From 11aaccdf665a561ba0f627bfa13f0ed611588d69 Mon Sep 17 00:00:00 2001 From: Craig Condon Date: Fri, 30 Nov 2012 20:11:55 -0600 Subject: [PATCH] finally works --- .cupboard | 3 +- .gitignore | 1 + README.md | 8 +- bin/nexe | 6 +- lib/index.js | 401 +- nexe | 1 - node-v0.8.14/.gitattributes | 1 + node-v0.8.14/.gitignore | 45 + node-v0.8.14/.mailmap | 104 + node-v0.8.14/.travis.yml | 14 + node-v0.8.14/AUTHORS | 370 + node-v0.8.14/BSDmakefile | 2 + node-v0.8.14/ChangeLog | 3543 +++++ node-v0.8.14/LICENSE | 603 + node-v0.8.14/Makefile | 316 + node-v0.8.14/README.md | 52 + node-v0.8.14/benchmark/arrays/var_int.js | 15 + node-v0.8.14/benchmark/arrays/zero_float.js | 15 + node-v0.8.14/benchmark/arrays/zero_int.js | 15 + node-v0.8.14/benchmark/buffer_creation.js | 6 + node-v0.8.14/benchmark/client_latency.js | 80 + node-v0.8.14/benchmark/fast_buffer2.js | 42 + .../benchmark/fast_buffer2_creation.js | 6 + .../benchmark/fast_buffer_creation.js | 4 + node-v0.8.14/benchmark/fs-readfile.js | 72 + node-v0.8.14/benchmark/function_call/bench.js | 43 + .../benchmark/function_call/binding.cc | 19 + node-v0.8.14/benchmark/function_call/wscript | 15 + node-v0.8.14/benchmark/http.sh | 12 + node-v0.8.14/benchmark/http_bench.js | 127 + node-v0.8.14/benchmark/http_server_lag.js | 13 + node-v0.8.14/benchmark/http_simple.js | 129 + node-v0.8.14/benchmark/http_simple.rb | 95 + node-v0.8.14/benchmark/http_simple_auto.js | 128 + node-v0.8.14/benchmark/http_simple_bench.sh | 77 + node-v0.8.14/benchmark/http_simple_cluster.js | 9 + node-v0.8.14/benchmark/idle_clients.js | 49 + node-v0.8.14/benchmark/idle_server.js | 31 + node-v0.8.14/benchmark/io.c | 122 + node-v0.8.14/benchmark/io.js | 109 + node-v0.8.14/benchmark/next-tick-2.js | 41 + node-v0.8.14/benchmark/next-tick.js | 17 + node-v0.8.14/benchmark/plot.R | 86 + node-v0.8.14/benchmark/process_loop.js | 19 + .../benchmark/report-startup-memory.js | 1 + node-v0.8.14/benchmark/run.js | 31 + node-v0.8.14/benchmark/settimeout.js | 15 + node-v0.8.14/benchmark/startup.js | 26 + node-v0.8.14/benchmark/static_http_server.js | 43 + node-v0.8.14/benchmark/string_creation.js | 6 + node-v0.8.14/benchmark/throughput-child.js | 25 + node-v0.8.14/benchmark/throughput.js | 21 + node-v0.8.14/benchmark/timers.js | 5 + node-v0.8.14/benchmark/tls-connect.js | 86 + node-v0.8.14/benchmark/tls-fragmentation.js | 63 + node-v0.8.14/benchmark/v8_bench.js | 15 + node-v0.8.14/common.gypi | 225 + node-v0.8.14/configure | 497 + node-v0.8.14/deps/http_parser/.gitignore | 8 + node-v0.8.14/deps/http_parser/.mailmap | 4 + node-v0.8.14/deps/http_parser/AUTHORS | 32 + node-v0.8.14/deps/http_parser/CONTRIBUTIONS | 4 + node-v0.8.14/deps/http_parser/LICENSE-MIT | 23 + node-v0.8.14/deps/http_parser/Makefile | 58 + node-v0.8.14/deps/http_parser/README.md | 178 + node-v0.8.14/deps/http_parser/http_parser.c | 2043 +++ node-v0.8.14/deps/http_parser/http_parser.gyp | 79 + node-v0.8.14/deps/http_parser/http_parser.h | 318 + node-v0.8.14/deps/http_parser/test.c | 2061 +++ node-v0.8.14/deps/npm/.npmignore | 22 + node-v0.8.14/deps/npm/AUTHORS | 79 + node-v0.8.14/deps/npm/LICENSE | 65 + node-v0.8.14/deps/npm/Makefile | 138 + node-v0.8.14/deps/npm/README.md | 239 + .../deps/npm/bin/node-gyp-bin/node-gyp | 2 + .../deps/npm/bin/node-gyp-bin/node-gyp.cmd | 1 + node-v0.8.14/deps/npm/bin/npm | 13 + node-v0.8.14/deps/npm/bin/npm-cli.js | 86 + node-v0.8.14/deps/npm/bin/npm.cmd | 6 + .../deps/npm/bin/read-package-json.js | 22 + node-v0.8.14/deps/npm/cli.js | 2 + node-v0.8.14/deps/npm/configure | 33 + node-v0.8.14/deps/npm/doc/api/bin.md | 13 + node-v0.8.14/deps/npm/doc/api/bugs.md | 19 + node-v0.8.14/deps/npm/doc/api/commands.md | 22 + node-v0.8.14/deps/npm/doc/api/config.md | 45 + node-v0.8.14/deps/npm/doc/api/deprecate.md | 32 + node-v0.8.14/deps/npm/doc/api/docs.md | 19 + node-v0.8.14/deps/npm/doc/api/edit.md | 24 + node-v0.8.14/deps/npm/doc/api/explore.md | 18 + node-v0.8.14/deps/npm/doc/api/help-search.md | 30 + node-v0.8.14/deps/npm/doc/api/init.md | 29 + node-v0.8.14/deps/npm/doc/api/install.md | 19 + node-v0.8.14/deps/npm/doc/api/link.md | 33 + node-v0.8.14/deps/npm/doc/api/load.md | 26 + node-v0.8.14/deps/npm/doc/api/ls.md | 56 + node-v0.8.14/deps/npm/doc/api/npm.md | 115 + node-v0.8.14/deps/npm/doc/api/outdated.md | 13 + node-v0.8.14/deps/npm/doc/api/owner.md | 31 + node-v0.8.14/deps/npm/doc/api/pack.md | 19 + node-v0.8.14/deps/npm/doc/api/prefix.md | 15 + node-v0.8.14/deps/npm/doc/api/prune.md | 17 + node-v0.8.14/deps/npm/doc/api/publish.md | 30 + node-v0.8.14/deps/npm/doc/api/rebuild.md | 16 + node-v0.8.14/deps/npm/doc/api/restart.md | 22 + node-v0.8.14/deps/npm/doc/api/root.md | 15 + node-v0.8.14/deps/npm/doc/api/run-script.md | 27 + node-v0.8.14/deps/npm/doc/api/search.md | 35 + node-v0.8.14/deps/npm/doc/api/shrinkwrap.md | 20 + node-v0.8.14/deps/npm/doc/api/start.md | 13 + node-v0.8.14/deps/npm/doc/api/stop.md | 13 + node-v0.8.14/deps/npm/doc/api/submodule.md | 28 + node-v0.8.14/deps/npm/doc/api/tag.md | 23 + node-v0.8.14/deps/npm/doc/api/test.md | 16 + node-v0.8.14/deps/npm/doc/api/uninstall.md | 16 + node-v0.8.14/deps/npm/doc/api/unpublish.md | 20 + node-v0.8.14/deps/npm/doc/api/update.md | 11 + node-v0.8.14/deps/npm/doc/api/version.md | 18 + node-v0.8.14/deps/npm/doc/api/view.md | 93 + node-v0.8.14/deps/npm/doc/api/whoami.md | 15 + node-v0.8.14/deps/npm/doc/cli/adduser.md | 36 + node-v0.8.14/deps/npm/doc/cli/bin.md | 17 + node-v0.8.14/deps/npm/doc/cli/bugs.md | 38 + node-v0.8.14/deps/npm/doc/cli/build.md | 22 + node-v0.8.14/deps/npm/doc/cli/bundle.md | 14 + node-v0.8.14/deps/npm/doc/cli/cache.md | 70 + node-v0.8.14/deps/npm/doc/cli/changelog.md | 80 + node-v0.8.14/deps/npm/doc/cli/coding-style.md | 179 + node-v0.8.14/deps/npm/doc/cli/completion.md | 29 + node-v0.8.14/deps/npm/doc/cli/config.md | 858 ++ node-v0.8.14/deps/npm/doc/cli/dedupe.md | 53 + node-v0.8.14/deps/npm/doc/cli/deprecate.md | 24 + node-v0.8.14/deps/npm/doc/cli/developers.md | 183 + node-v0.8.14/deps/npm/doc/cli/disputes.md | 84 + node-v0.8.14/deps/npm/doc/cli/docs.md | 38 + node-v0.8.14/deps/npm/doc/cli/edit.md | 35 + node-v0.8.14/deps/npm/doc/cli/explore.md | 40 + node-v0.8.14/deps/npm/doc/cli/faq.md | 260 + node-v0.8.14/deps/npm/doc/cli/folders.md | 209 + node-v0.8.14/deps/npm/doc/cli/help-search.md | 35 + node-v0.8.14/deps/npm/doc/cli/help.md | 38 + node-v0.8.14/deps/npm/doc/cli/index.md | 381 + node-v0.8.14/deps/npm/doc/cli/init.md | 25 + node-v0.8.14/deps/npm/doc/cli/install.md | 233 + node-v0.8.14/deps/npm/doc/cli/json.md | 566 + node-v0.8.14/deps/npm/doc/cli/link.md | 57 + node-v0.8.14/deps/npm/doc/cli/ls.md | 68 + node-v0.8.14/deps/npm/doc/cli/npm.md | 155 + node-v0.8.14/deps/npm/doc/cli/outdated.md | 17 + node-v0.8.14/deps/npm/doc/cli/owner.md | 33 + node-v0.8.14/deps/npm/doc/cli/pack.md | 25 + node-v0.8.14/deps/npm/doc/cli/prefix.md | 17 + node-v0.8.14/deps/npm/doc/cli/prune.md | 21 + node-v0.8.14/deps/npm/doc/cli/publish.md | 30 + node-v0.8.14/deps/npm/doc/cli/rebuild.md | 20 + node-v0.8.14/deps/npm/doc/cli/registry.md | 93 + node-v0.8.14/deps/npm/doc/cli/removing-npm.md | 54 + node-v0.8.14/deps/npm/doc/cli/restart.md | 22 + node-v0.8.14/deps/npm/doc/cli/root.md | 17 + node-v0.8.14/deps/npm/doc/cli/run-script.md | 21 + node-v0.8.14/deps/npm/doc/cli/scripts.md | 196 + node-v0.8.14/deps/npm/doc/cli/search.md | 20 + node-v0.8.14/deps/npm/doc/cli/semver.md | 130 + node-v0.8.14/deps/npm/doc/cli/shrinkwrap.md | 171 + node-v0.8.14/deps/npm/doc/cli/star.md | 22 + node-v0.8.14/deps/npm/doc/cli/start.md | 18 + node-v0.8.14/deps/npm/doc/cli/stop.md | 18 + node-v0.8.14/deps/npm/doc/cli/submodule.md | 28 + node-v0.8.14/deps/npm/doc/cli/tag.md | 17 + node-v0.8.14/deps/npm/doc/cli/test.md | 21 + node-v0.8.14/deps/npm/doc/cli/uninstall.md | 19 + node-v0.8.14/deps/npm/doc/cli/unpublish.md | 32 + node-v0.8.14/deps/npm/doc/cli/update.md | 21 + node-v0.8.14/deps/npm/doc/cli/version.md | 36 + node-v0.8.14/deps/npm/doc/cli/view.md | 85 + node-v0.8.14/deps/npm/doc/cli/whoami.md | 15 + node-v0.8.14/deps/npm/html/api/bin.html | 54 + node-v0.8.14/deps/npm/html/api/bugs.html | 60 + node-v0.8.14/deps/npm/html/api/commands.html | 63 + node-v0.8.14/deps/npm/html/api/config.html | 68 + node-v0.8.14/deps/npm/html/api/deprecate.html | 65 + node-v0.8.14/deps/npm/html/api/docs.html | 60 + node-v0.8.14/deps/npm/html/api/edit.html | 65 + node-v0.8.14/deps/npm/html/api/explore.html | 59 + .../deps/npm/html/api/help-search.html | 67 + node-v0.8.14/deps/npm/html/api/init.html | 70 + node-v0.8.14/deps/npm/html/api/install.html | 60 + node-v0.8.14/deps/npm/html/api/link.html | 74 + node-v0.8.14/deps/npm/html/api/load.html | 67 + node-v0.8.14/deps/npm/html/api/ls.html | 94 + node-v0.8.14/deps/npm/html/api/npm.html | 126 + node-v0.8.14/deps/npm/html/api/outdated.html | 54 + node-v0.8.14/deps/npm/html/api/owner.html | 69 + node-v0.8.14/deps/npm/html/api/pack.html | 60 + node-v0.8.14/deps/npm/html/api/prefix.html | 56 + node-v0.8.14/deps/npm/html/api/prune.html | 58 + node-v0.8.14/deps/npm/html/api/publish.html | 67 + node-v0.8.14/deps/npm/html/api/rebuild.html | 57 + node-v0.8.14/deps/npm/html/api/restart.html | 62 + node-v0.8.14/deps/npm/html/api/root.html | 56 + .../deps/npm/html/api/run-script.html | 64 + node-v0.8.14/deps/npm/html/api/search.html | 67 + .../deps/npm/html/api/shrinkwrap.html | 61 + node-v0.8.14/deps/npm/html/api/start.html | 54 + node-v0.8.14/deps/npm/html/api/stop.html | 54 + node-v0.8.14/deps/npm/html/api/submodule.html | 68 + node-v0.8.14/deps/npm/html/api/tag.html | 64 + node-v0.8.14/deps/npm/html/api/test.html | 57 + node-v0.8.14/deps/npm/html/api/uninstall.html | 57 + node-v0.8.14/deps/npm/html/api/unpublish.html | 61 + node-v0.8.14/deps/npm/html/api/update.html | 53 + node-v0.8.14/deps/npm/html/api/version.html | 59 + node-v0.8.14/deps/npm/html/api/view.html | 134 + node-v0.8.14/deps/npm/html/api/whoami.html | 56 + node-v0.8.14/deps/npm/html/doc/README.html | 275 + node-v0.8.14/deps/npm/html/doc/adduser.html | 74 + node-v0.8.14/deps/npm/html/doc/bin.html | 55 + node-v0.8.14/deps/npm/html/doc/bugs.html | 71 + node-v0.8.14/deps/npm/html/doc/build.html | 60 + node-v0.8.14/deps/npm/html/doc/bundle.html | 55 + node-v0.8.14/deps/npm/html/doc/cache.html | 101 + node-v0.8.14/deps/npm/html/doc/changelog.html | 100 + .../deps/npm/html/doc/coding-style.html | 215 + .../deps/npm/html/doc/completion.html | 68 + node-v0.8.14/deps/npm/html/doc/config.html | 791 ++ node-v0.8.14/deps/npm/html/doc/dedupe.html | 92 + node-v0.8.14/deps/npm/html/doc/deprecate.html | 64 + .../deps/npm/html/doc/developers.html | 195 + node-v0.8.14/deps/npm/html/doc/disputes.html | 115 + node-v0.8.14/deps/npm/html/doc/docs.html | 72 + node-v0.8.14/deps/npm/html/doc/edit.html | 72 + node-v0.8.14/deps/npm/html/doc/explore.html | 75 + node-v0.8.14/deps/npm/html/doc/faq.html | 285 + node-v0.8.14/deps/npm/html/doc/folders.html | 240 + .../deps/npm/html/doc/help-search.html | 73 + node-v0.8.14/deps/npm/html/doc/help.html | 71 + node-v0.8.14/deps/npm/html/doc/index.html | 423 + node-v0.8.14/deps/npm/html/doc/init.html | 64 + node-v0.8.14/deps/npm/html/doc/install.html | 168 + node-v0.8.14/deps/npm/html/doc/json.html | 560 + node-v0.8.14/deps/npm/html/doc/link.html | 93 + node-v0.8.14/deps/npm/html/doc/list.html | 99 + node-v0.8.14/deps/npm/html/doc/ls.html | 99 + node-v0.8.14/deps/npm/html/doc/npm.html | 170 + node-v0.8.14/deps/npm/html/doc/outdated.html | 56 + node-v0.8.14/deps/npm/html/doc/owner.html | 69 + node-v0.8.14/deps/npm/html/doc/pack.html | 64 + node-v0.8.14/deps/npm/html/doc/prefix.html | 55 + node-v0.8.14/deps/npm/html/doc/prune.html | 60 + node-v0.8.14/deps/npm/html/doc/publish.html | 64 + node-v0.8.14/deps/npm/html/doc/rebuild.html | 60 + node-v0.8.14/deps/npm/html/doc/registry.html | 132 + .../deps/npm/html/doc/removing-npm.html | 93 + node-v0.8.14/deps/npm/html/doc/restart.html | 59 + node-v0.8.14/deps/npm/html/doc/root.html | 55 + .../deps/npm/html/doc/run-script.html | 58 + node-v0.8.14/deps/npm/html/doc/scripts.html | 212 + node-v0.8.14/deps/npm/html/doc/search.html | 59 + node-v0.8.14/deps/npm/html/doc/semver.html | 139 + .../deps/npm/html/doc/shrinkwrap.html | 204 + node-v0.8.14/deps/npm/html/doc/star.html | 61 + node-v0.8.14/deps/npm/html/doc/start.html | 55 + node-v0.8.14/deps/npm/html/doc/stop.html | 55 + node-v0.8.14/deps/npm/html/doc/submodule.html | 68 + node-v0.8.14/deps/npm/html/doc/tag.html | 56 + node-v0.8.14/deps/npm/html/doc/test.html | 58 + node-v0.8.14/deps/npm/html/doc/uninstall.html | 57 + node-v0.8.14/deps/npm/html/doc/unpublish.html | 69 + node-v0.8.14/deps/npm/html/doc/update.html | 58 + node-v0.8.14/deps/npm/html/doc/version.html | 75 + node-v0.8.14/deps/npm/html/doc/view.html | 123 + node-v0.8.14/deps/npm/html/doc/whoami.html | 55 + node-v0.8.14/deps/npm/html/docfoot.html | 34 + node-v0.8.14/deps/npm/html/dochead.html | 8 + node-v0.8.14/deps/npm/html/favicon.ico | Bin 0 -> 7094 bytes node-v0.8.14/deps/npm/html/index.html | 95 + node-v0.8.14/deps/npm/html/static/style.css | 350 + .../npm/html/static/webfonts/23242D_3_0.eot | Bin 0 -> 9662 bytes .../npm/html/static/webfonts/23242D_3_0.ttf | Bin 0 -> 9356 bytes .../npm/html/static/webfonts/23242D_3_0.woff | Bin 0 -> 4373 bytes node-v0.8.14/deps/npm/lib/adduser.js | 138 + node-v0.8.14/deps/npm/lib/bin.js | 18 + node-v0.8.14/deps/npm/lib/bugs.js | 44 + node-v0.8.14/deps/npm/lib/build.js | 188 + node-v0.8.14/deps/npm/lib/cache.js | 973 ++ node-v0.8.14/deps/npm/lib/completion.js | 248 + node-v0.8.14/deps/npm/lib/config.js | 276 + node-v0.8.14/deps/npm/lib/dedupe.js | 334 + node-v0.8.14/deps/npm/lib/deprecate.js | 47 + node-v0.8.14/deps/npm/lib/docs.js | 30 + node-v0.8.14/deps/npm/lib/edit.js | 30 + node-v0.8.14/deps/npm/lib/explore.js | 34 + node-v0.8.14/deps/npm/lib/faq.js | 8 + node-v0.8.14/deps/npm/lib/get.js | 12 + node-v0.8.14/deps/npm/lib/help-search.js | 193 + node-v0.8.14/deps/npm/lib/help.js | 150 + node-v0.8.14/deps/npm/lib/init.js | 36 + node-v0.8.14/deps/npm/lib/install.js | 934 ++ node-v0.8.14/deps/npm/lib/link.js | 169 + node-v0.8.14/deps/npm/lib/ls.js | 334 + node-v0.8.14/deps/npm/lib/npm.js | 506 + node-v0.8.14/deps/npm/lib/outdated.js | 149 + node-v0.8.14/deps/npm/lib/owner.js | 205 + node-v0.8.14/deps/npm/lib/pack.js | 65 + node-v0.8.14/deps/npm/lib/prefix.js | 11 + node-v0.8.14/deps/npm/lib/prune.js | 40 + node-v0.8.14/deps/npm/lib/publish.js | 101 + node-v0.8.14/deps/npm/lib/rebuild.js | 95 + node-v0.8.14/deps/npm/lib/restart.js | 1 + node-v0.8.14/deps/npm/lib/root.js | 11 + node-v0.8.14/deps/npm/lib/run-script.js | 98 + node-v0.8.14/deps/npm/lib/search.js | 261 + node-v0.8.14/deps/npm/lib/set.js | 13 + node-v0.8.14/deps/npm/lib/shrinkwrap.js | 47 + node-v0.8.14/deps/npm/lib/star.js | 33 + node-v0.8.14/deps/npm/lib/start.js | 1 + node-v0.8.14/deps/npm/lib/stop.js | 1 + node-v0.8.14/deps/npm/lib/submodule.js | 91 + node-v0.8.14/deps/npm/lib/substack.js | 20 + node-v0.8.14/deps/npm/lib/tag.js | 18 + node-v0.8.14/deps/npm/lib/test.js | 14 + node-v0.8.14/deps/npm/lib/unbuild.js | 94 + node-v0.8.14/deps/npm/lib/uninstall.js | 127 + node-v0.8.14/deps/npm/lib/unpublish.js | 82 + node-v0.8.14/deps/npm/lib/update.js | 39 + node-v0.8.14/deps/npm/lib/utils/cmd-shim.js | 154 + node-v0.8.14/deps/npm/lib/utils/completion.sh | 54 + .../lib/utils/completion/file-completion.js | 26 + .../lib/utils/completion/installed-deep.js | 46 + .../lib/utils/completion/installed-shallow.js | 79 + .../lib/utils/completion/remote-packages.js | 58 + .../deps/npm/lib/utils/completion/users.js | 23 + .../deps/npm/lib/utils/error-handler.js | 293 + node-v0.8.14/deps/npm/lib/utils/exec.js | 82 + node-v0.8.14/deps/npm/lib/utils/fetch.js | 84 + .../deps/npm/lib/utils/find-prefix.js | 52 + node-v0.8.14/deps/npm/lib/utils/gently-rm.js | 45 + node-v0.8.14/deps/npm/lib/utils/lifecycle.js | 301 + node-v0.8.14/deps/npm/lib/utils/link.js | 39 + node-v0.8.14/deps/npm/lib/utils/sha.js | 54 + node-v0.8.14/deps/npm/lib/utils/tar.js | 269 + node-v0.8.14/deps/npm/lib/version.js | 105 + node-v0.8.14/deps/npm/lib/view.js | 246 + node-v0.8.14/deps/npm/lib/whoami.js | 13 + node-v0.8.14/deps/npm/lib/xmas.js | 56 + node-v0.8.14/deps/npm/man/man1/README.1 | 313 + node-v0.8.14/deps/npm/man/man1/adduser.1 | 57 + node-v0.8.14/deps/npm/man/man1/author.1 | 55 + node-v0.8.14/deps/npm/man/man1/bin.1 | 34 + node-v0.8.14/deps/npm/man/man1/bugs.1 | 70 + node-v0.8.14/deps/npm/man/man1/build.1 | 43 + node-v0.8.14/deps/npm/man/man1/bundle.1 | 23 + node-v0.8.14/deps/npm/man/man1/cache.1 | 97 + node-v0.8.14/deps/npm/man/man1/changelog.1 | 173 + node-v0.8.14/deps/npm/man/man1/coding-style.1 | 251 + node-v0.8.14/deps/npm/man/man1/completion.1 | 47 + node-v0.8.14/deps/npm/man/man1/config.1 | 1479 ++ node-v0.8.14/deps/npm/man/man1/dedupe.1 | 90 + node-v0.8.14/deps/npm/man/man1/deprecate.1 | 45 + node-v0.8.14/deps/npm/man/man1/developers.1 | 283 + node-v0.8.14/deps/npm/man/man1/disputes.1 | 124 + node-v0.8.14/deps/npm/man/man1/docs.1 | 68 + node-v0.8.14/deps/npm/man/man1/edit.1 | 60 + node-v0.8.14/deps/npm/man/man1/explore.1 | 76 + node-v0.8.14/deps/npm/man/man1/faq.1 | 341 + node-v0.8.14/deps/npm/man/man1/find.1 | 72 + node-v0.8.14/deps/npm/man/man1/folders.1 | 258 + node-v0.8.14/deps/npm/man/man1/get.1 | 1154 ++ node-v0.8.14/deps/npm/man/man1/global.1 | 259 + node-v0.8.14/deps/npm/man/man1/help-search.1 | 59 + node-v0.8.14/deps/npm/man/man1/help.1 | 71 + node-v0.8.14/deps/npm/man/man1/home.1 | 68 + node-v0.8.14/deps/npm/man/man1/index.1 | 289 + node-v0.8.14/deps/npm/man/man1/init.1 | 43 + node-v0.8.14/deps/npm/man/man1/install.1 | 405 + node-v0.8.14/deps/npm/man/man1/json.1 | 817 ++ node-v0.8.14/deps/npm/man/man1/link.1 | 108 + node-v0.8.14/deps/npm/man/man1/list.1 | 125 + node-v0.8.14/deps/npm/man/man1/ln.1 | 108 + node-v0.8.14/deps/npm/man/man1/ls.1 | 125 + node-v0.8.14/deps/npm/man/man1/npm.1 | 227 + node-v0.8.14/deps/npm/man/man1/outdated.1 | 32 + node-v0.8.14/deps/npm/man/man1/owner.1 | 58 + node-v0.8.14/deps/npm/man/man1/pack.1 | 42 + node-v0.8.14/deps/npm/man/man1/prefix.1 | 34 + node-v0.8.14/deps/npm/man/man1/prune.1 | 37 + node-v0.8.14/deps/npm/man/man1/publish.1 | 53 + node-v0.8.14/deps/npm/man/man1/rebuild.1 | 36 + node-v0.8.14/deps/npm/man/man1/registry.1 | 110 + node-v0.8.14/deps/npm/man/man1/removing-npm.1 | 107 + node-v0.8.14/deps/npm/man/man1/restart.1 | 42 + node-v0.8.14/deps/npm/man/man1/rm.1 | 36 + node-v0.8.14/deps/npm/man/man1/root.1 | 34 + node-v0.8.14/deps/npm/man/man1/run-script.1 | 41 + node-v0.8.14/deps/npm/man/man1/scripts.1 | 292 + node-v0.8.14/deps/npm/man/man1/search.1 | 36 + node-v0.8.14/deps/npm/man/man1/semver.1 | 221 + node-v0.8.14/deps/npm/man/man1/set.1 | 1154 ++ node-v0.8.14/deps/npm/man/man1/shrinkwrap.1 | 261 + node-v0.8.14/deps/npm/man/man1/star.1 | 39 + node-v0.8.14/deps/npm/man/man1/start.1 | 37 + node-v0.8.14/deps/npm/man/man1/stop.1 | 37 + node-v0.8.14/deps/npm/man/man1/submodule.1 | 42 + node-v0.8.14/deps/npm/man/man1/tag.1 | 31 + node-v0.8.14/deps/npm/man/man1/test.1 | 41 + node-v0.8.14/deps/npm/man/man1/uninstall.1 | 36 + node-v0.8.14/deps/npm/man/man1/unpublish.1 | 53 + node-v0.8.14/deps/npm/man/man1/update.1 | 41 + node-v0.8.14/deps/npm/man/man1/version.1 | 61 + node-v0.8.14/deps/npm/man/man1/view.1 | 176 + node-v0.8.14/deps/npm/man/man1/whoami.1 | 28 + node-v0.8.14/deps/npm/man/man3/author.3 | 52 + node-v0.8.14/deps/npm/man/man3/bin.3 | 21 + node-v0.8.14/deps/npm/man/man3/bugs.3 | 28 + node-v0.8.14/deps/npm/man/man3/commands.3 | 35 + node-v0.8.14/deps/npm/man/man3/config.3 | 69 + node-v0.8.14/deps/npm/man/man3/deprecate.3 | 54 + node-v0.8.14/deps/npm/man/man3/docs.3 | 28 + node-v0.8.14/deps/npm/man/man3/edit.3 | 35 + node-v0.8.14/deps/npm/man/man3/explore.3 | 28 + node-v0.8.14/deps/npm/man/man3/find.3 | 79 + node-v0.8.14/deps/npm/man/man3/get.3 | 69 + node-v0.8.14/deps/npm/man/man3/help-search.3 | 51 + node-v0.8.14/deps/npm/man/man3/home.3 | 28 + node-v0.8.14/deps/npm/man/man3/init.3 | 39 + node-v0.8.14/deps/npm/man/man3/install.3 | 29 + node-v0.8.14/deps/npm/man/man3/link.3 | 53 + node-v0.8.14/deps/npm/man/man3/list.3 | 79 + node-v0.8.14/deps/npm/man/man3/ln.3 | 53 + node-v0.8.14/deps/npm/man/man3/load.3 | 44 + node-v0.8.14/deps/npm/man/man3/ls.3 | 86 + node-v0.8.14/deps/npm/man/man3/npm.3 | 160 + node-v0.8.14/deps/npm/man/man3/outdated.3 | 21 + node-v0.8.14/deps/npm/man/man3/owner.3 | 52 + node-v0.8.14/deps/npm/man/man3/pack.3 | 28 + node-v0.8.14/deps/npm/man/man3/prefix.3 | 24 + node-v0.8.14/deps/npm/man/man3/prune.3 | 27 + node-v0.8.14/deps/npm/man/man3/publish.3 | 51 + node-v0.8.14/deps/npm/man/man3/rebuild.3 | 22 + node-v0.8.14/deps/npm/man/man3/restart.3 | 37 + node-v0.8.14/deps/npm/man/man3/rm.3 | 25 + node-v0.8.14/deps/npm/man/man3/root.3 | 24 + node-v0.8.14/deps/npm/man/man3/run-script.3 | 48 + node-v0.8.14/deps/npm/man/man3/search.3 | 64 + node-v0.8.14/deps/npm/man/man3/set.3 | 69 + node-v0.8.14/deps/npm/man/man3/shrinkwrap.3 | 30 + node-v0.8.14/deps/npm/man/man3/start.3 | 21 + node-v0.8.14/deps/npm/man/man3/stop.3 | 21 + node-v0.8.14/deps/npm/man/man3/submodule.3 | 42 + node-v0.8.14/deps/npm/man/man3/tag.3 | 31 + node-v0.8.14/deps/npm/man/man3/test.3 | 25 + node-v0.8.14/deps/npm/man/man3/uninstall.3 | 25 + node-v0.8.14/deps/npm/man/man3/unpublish.3 | 30 + node-v0.8.14/deps/npm/man/man3/update.3 | 18 + node-v0.8.14/deps/npm/man/man3/version.3 | 27 + node-v0.8.14/deps/npm/man/man3/view.3 | 176 + node-v0.8.14/deps/npm/man/man3/whoami.3 | 24 + node-v0.8.14/deps/npm/package.json | 130 + node-v0.8.14/deps/npm/scripts/clean-old.sh | 165 + node-v0.8.14/deps/npm/scripts/doc-build.sh | 77 + node-v0.8.14/deps/npm/scripts/index-build.js | 63 + node-v0.8.14/deps/npm/scripts/install.sh | 308 + node-v0.8.14/deps/npm/scripts/release.sh | 36 + node-v0.8.14/deps/npm/scripts/relocate.sh | 26 + node-v0.8.14/deps/npm/test/common.js | 7 + .../test/disabled/bundlerecurs/package.json | 4 + .../npm/test/disabled/change-bin-1/bin/foo | 2 + .../test/disabled/change-bin-1/package.json | 3 + .../npm/test/disabled/change-bin-2/bin/bar | 2 + .../test/disabled/change-bin-2/package.json | 3 + .../npm/test/disabled/failer/package.json | 5 + .../deps/npm/test/disabled/fast/package.json | 9 + .../test/disabled/package-bar/package.json | 7 + .../test/disabled/package-config/package.json | 4 + .../npm/test/disabled/package-config/test.js | 17 + .../test/disabled/package-foo/package.json | 4 + .../deps/npm/test/disabled/slow/package.json | 9 + .../npm/test/disabled/startstop/package.json | 3 + .../test/packages/npm-test-array-bin/README | 1 + .../packages/npm-test-array-bin/bin/array-bin | 2 + .../packages/npm-test-array-bin/package.json | 4 + .../test/packages/npm-test-array-bin/test.js | 6 + .../npm/test/packages/npm-test-blerg/README | 1 + .../test/packages/npm-test-blerg/package.json | 5 + .../npm/test/packages/npm-test-blerg/test.js | 5 + .../npm/test/packages/npm-test-blerg3/README | 1 + .../packages/npm-test-blerg3/package.json | 5 + .../npm/test/packages/npm-test-blerg3/test.js | 5 + .../test/packages/npm-test-bundled-git/README | 1 + .../minimatch-expected.json | 29 + .../npm-test-bundled-git/package.json | 5 + .../packages/npm-test-bundled-git/test.js | 4 + .../npm/test/packages/npm-test-dir-bin/README | 1 + .../packages/npm-test-dir-bin/bin/dir-bin | 2 + .../packages/npm-test-dir-bin/package.json | 4 + .../test/packages/npm-test-dir-bin/test.js | 5 + .../test/packages/npm-test-env-reader/README | 1 + .../packages/npm-test-env-reader/package.json | 14 + .../test/packages/npm-test-env-reader/test.js | 9 + .../test/packages/npm-test-files/.npmignore | 7 + .../npm/test/packages/npm-test-files/include4 | 0 .../test/packages/npm-test-files/package.json | 10 + .../test/packages/npm-test-files/sub/include | 0 .../test/packages/npm-test-files/sub/include2 | 0 .../test/packages/npm-test-files/sub/include4 | 1 + .../npm/test/packages/npm-test-files/test.sh | 27 + .../packages/npm-test-ignore-nested-nm/README | 1 + .../npm-test-ignore-nested-nm/package.json | 3 + .../npm-test-ignore-nested-nm/test.js | 2 + .../test/packages/npm-test-ignore/.npmignore | 7 + .../npm/test/packages/npm-test-ignore/README | 1 + .../test/packages/npm-test-ignore/include4 | 0 .../packages/npm-test-ignore/package.json | 3 + .../test/packages/npm-test-ignore/sub/include | 0 .../packages/npm-test-ignore/sub/include2 | 0 .../packages/npm-test-ignore/sub/include4 | 1 + .../npm/test/packages/npm-test-ignore/test.sh | 29 + .../packages/npm-test-missing-bindir/README | 1 + .../npm-test-missing-bindir/package.json | 4 + .../packages/npm-test-missing-bindir/test.js | 5 + .../packages/npm-test-optional-deps/README | 1 + .../npm-test-optional-deps/package.json | 12 + .../packages/npm-test-optional-deps/test.js | 9 + .../packages/npm-test-platform-all/README | 1 + .../npm-test-platform-all/package.json | 5 + .../test/packages/npm-test-platform/README | 1 + .../packages/npm-test-platform/package.json | 5 + .../npm/test/packages/npm-test-private/README | 1 + .../packages/npm-test-private/package.json | 4 + .../test/packages/npm-test-shrinkwrap/README | 1 + .../npm-test-shrinkwrap/npm-shrinkwrap.json | 43 + .../packages/npm-test-shrinkwrap/package.json | 13 + .../test/packages/npm-test-shrinkwrap/test.sh | 20 + .../packages/npm-test-test-package/README | 1 + .../npm-test-test-package/package.json | 5 + .../npm/test/packages/npm-test-url-dep/README | 1 + .../packages/npm-test-url-dep/package.json | 7 + node-v0.8.14/deps/npm/test/run.js | 210 + node-v0.8.14/deps/npm/test/tap/false_name.js | 29 + .../deps/npm/test/tap/false_name/index.js | 1 + .../deps/npm/test/tap/false_name/package.json | 8 + .../deps/npm/test/tap/publish-config.js | 41 + node-v0.8.14/deps/npm/test/update-test.sh | 59 + node-v0.8.14/deps/openssl/README.chromium | 96 + node-v0.8.14/deps/openssl/asm/Makefile | 182 + .../openssl/asm/x64-elf-gas/aes/aes-x86_64.s | 2545 ++++ .../openssl/asm/x64-elf-gas/bn/x86_64-mont.s | 172 + .../asm/x64-elf-gas/camellia/cmll-x86_64.s | 1844 +++ .../openssl/asm/x64-elf-gas/md5/md5-x86_64.s | 671 + .../openssl/asm/x64-elf-gas/rc4/rc4-x86_64.s | 430 + .../openssl/asm/x64-elf-gas/sha/sha1-x86_64.s | 1283 ++ .../asm/x64-elf-gas/sha/sha512-x86_64.s | 1971 +++ .../asm/x64-elf-gas/whrlpool/wp-x86_64.s | 859 ++ .../openssl/asm/x64-elf-gas/x86_64cpuid.s | 194 + .../asm/x64-macosx-gas/aes/aes-x86_64.s | 2545 ++++ .../asm/x64-macosx-gas/bn/x86_64-mont.s | 172 + .../asm/x64-macosx-gas/camellia/cmll-x86_64.s | 1844 +++ .../asm/x64-macosx-gas/md5/md5-x86_64.s | 671 + .../asm/x64-macosx-gas/rc4/rc4-x86_64.s | 430 + .../asm/x64-macosx-gas/sha/sha1-x86_64.s | 1283 ++ .../asm/x64-macosx-gas/sha/sha512-x86_64.s | 1971 +++ .../asm/x64-macosx-gas/whrlpool/wp-x86_64.s | 859 ++ .../openssl/asm/x64-macosx-gas/x86_64cpuid.s | 195 + .../asm/x64-win32-masm/aes/aes-x86_64.asm | 2885 ++++ .../asm/x64-win32-masm/bn/x86_64-mont.asm | 293 + .../x64-win32-masm/camellia/cmll-x86_64.asm | 2108 +++ .../asm/x64-win32-masm/md5/md5-x86_64.asm | 781 ++ .../asm/x64-win32-masm/rc4/rc4-x86_64.asm | 586 + .../asm/x64-win32-masm/sha/sha1-x86_64.asm | 1394 ++ .../asm/x64-win32-masm/sha/sha512-x86_64.asm | 2085 +++ .../asm/x64-win32-masm/whrlpool/wp-x86_64.asm | 972 ++ .../asm/x64-win32-masm/x86_64cpuid.asm | 186 + .../openssl/asm/x86-elf-gas/aes/aes-586.s | 3234 +++++ .../deps/openssl/asm/x86-elf-gas/bf/bf-686.s | 864 ++ .../openssl/asm/x86-elf-gas/bn/x86-mont.s | 338 + .../deps/openssl/asm/x86-elf-gas/bn/x86.s | 2114 +++ .../asm/x86-elf-gas/camellia/cmll-x86.s | 2375 ++++ .../openssl/asm/x86-elf-gas/cast/cast-586.s | 933 ++ .../openssl/asm/x86-elf-gas/des/crypt586.s | 875 ++ .../openssl/asm/x86-elf-gas/des/des-586.s | 1837 +++ .../openssl/asm/x86-elf-gas/md5/md5-586.s | 679 + .../openssl/asm/x86-elf-gas/rc4/rc4-586.s | 230 + .../openssl/asm/x86-elf-gas/rc5/rc5-586.s | 564 + .../openssl/asm/x86-elf-gas/ripemd/rmd-586.s | 1965 +++ .../openssl/asm/x86-elf-gas/sha/sha1-586.s | 1442 ++ .../openssl/asm/x86-elf-gas/sha/sha256-586.s | 261 + .../openssl/asm/x86-elf-gas/sha/sha512-586.s | 563 + .../openssl/asm/x86-elf-gas/whrlpool/wp-mmx.s | 1105 ++ .../deps/openssl/asm/x86-elf-gas/x86cpuid.s | 279 + .../openssl/asm/x86-macosx-gas/aes/aes-586.s | 3194 +++++ .../openssl/asm/x86-macosx-gas/bf/bf-686.s | 897 ++ .../openssl/asm/x86-macosx-gas/bn/x86-mont.s | 336 + .../deps/openssl/asm/x86-macosx-gas/bn/x86.s | 2385 ++++ .../asm/x86-macosx-gas/camellia/cmll-x86.s | 2353 ++++ .../asm/x86-macosx-gas/cast/cast-586.s | 967 ++ .../openssl/asm/x86-macosx-gas/des/crypt586.s | 891 ++ .../openssl/asm/x86-macosx-gas/des/des-586.s | 1873 +++ .../openssl/asm/x86-macosx-gas/md5/md5-586.s | 745 + .../openssl/asm/x86-macosx-gas/rc4/rc4-586.s | 224 + .../openssl/asm/x86-macosx-gas/rc5/rc5-586.s | 563 + .../asm/x86-macosx-gas/ripemd/rmd-586.s | 2123 +++ .../openssl/asm/x86-macosx-gas/sha/sha1-586.s | 1520 ++ .../asm/x86-macosx-gas/sha/sha256-586.s | 259 + .../asm/x86-macosx-gas/sha/sha512-586.s | 561 + .../asm/x86-macosx-gas/whrlpool/wp-mmx.s | 1103 ++ .../openssl/asm/x86-macosx-gas/x86cpuid.s | 261 + .../asm/x86-win32-masm/aes/aes-586.asm | 3222 +++++ .../openssl/asm/x86-win32-masm/bf/bf-686.asm | 907 ++ .../asm/x86-win32-masm/bn/x86-mont.asm | 348 + .../openssl/asm/x86-win32-masm/bn/x86.asm | 2116 +++ .../asm/x86-win32-masm/camellia/cmll-x86.asm | 2367 ++++ .../asm/x86-win32-masm/cast/cast-586.asm | 950 ++ .../asm/x86-win32-masm/des/crypt586.asm | 909 ++ .../asm/x86-win32-masm/des/des-586.asm | 1878 +++ .../asm/x86-win32-masm/md5/md5-586.asm | 693 + .../asm/x86-win32-masm/rc4/rc4-586.asm | 239 + .../asm/x86-win32-masm/rc5/rc5-586.asm | 573 + .../asm/x86-win32-masm/ripemd/rmd-586.asm | 1976 +++ .../asm/x86-win32-masm/sha/sha1-586.asm | 1452 ++ .../asm/x86-win32-masm/sha/sha256-586.asm | 271 + .../asm/x86-win32-masm/sha/sha512-586.asm | 573 + .../asm/x86-win32-masm/whrlpool/wp-mmx.asm | 1122 ++ .../openssl/asm/x86-win32-masm/x86cpuid.asm | 277 + node-v0.8.14/deps/openssl/buildinf.h | 7 + .../config/android/openssl/opensslconf.h | 253 + .../config/k8/openssl/opensslconf-posix.h | 273 + .../config/k8/openssl/opensslconf-win32.h | 262 + .../openssl/config/k8/openssl/opensslconf.h | 5 + .../config/piii/openssl/opensslconf-posix.h | 273 + .../config/piii/openssl/opensslconf-win32.h | 274 + .../openssl/config/piii/openssl/opensslconf.h | 5 + node-v0.8.14/deps/openssl/openssl.gyp | 870 ++ .../deps/openssl/openssl/ACKNOWLEDGMENTS | 25 + node-v0.8.14/deps/openssl/openssl/CHANGES | 9570 +++++++++++++ .../deps/openssl/openssl/CHANGES.SSLeay | 968 ++ node-v0.8.14/deps/openssl/openssl/Configure | 2057 +++ node-v0.8.14/deps/openssl/openssl/FAQ | 1025 ++ node-v0.8.14/deps/openssl/openssl/INSTALL | 360 + .../deps/openssl/openssl/INSTALL.DJGPP | 47 + .../deps/openssl/openssl/INSTALL.MacOS | 72 + node-v0.8.14/deps/openssl/openssl/INSTALL.NW | 454 + node-v0.8.14/deps/openssl/openssl/INSTALL.OS2 | 31 + node-v0.8.14/deps/openssl/openssl/INSTALL.VMS | 293 + node-v0.8.14/deps/openssl/openssl/INSTALL.W32 | 325 + node-v0.8.14/deps/openssl/openssl/INSTALL.W64 | 66 + node-v0.8.14/deps/openssl/openssl/INSTALL.WCE | 95 + node-v0.8.14/deps/openssl/openssl/LICENSE | 127 + .../deps/openssl/openssl/MacOS/GUSI_Init.cpp | 62 + .../MacOS/GetHTTPS.src/CPStringUtils.cpp | 2753 ++++ .../MacOS/GetHTTPS.src/CPStringUtils.hpp | 104 + .../MacOS/GetHTTPS.src/ErrorHandling.cpp | 170 + .../MacOS/GetHTTPS.src/ErrorHandling.hpp | 147 + .../openssl/MacOS/GetHTTPS.src/GetHTTPS.cpp | 209 + .../openssl/MacOS/GetHTTPS.src/MacSocket.cpp | 1607 +++ .../openssl/MacOS/GetHTTPS.src/MacSocket.h | 103 + .../openssl/openssl/MacOS/OpenSSL.mcp.hqx | 4940 +++++++ .../deps/openssl/openssl/MacOS/Randomizer.cpp | 476 + .../deps/openssl/openssl/MacOS/Randomizer.h | 43 + node-v0.8.14/deps/openssl/openssl/MacOS/TODO | 18 + .../openssl/MacOS/_MWERKS_GUSI_prefix.h | 9 + .../openssl/openssl/MacOS/_MWERKS_prefix.h | 9 + .../deps/openssl/openssl/MacOS/buildinf.h | 5 + .../deps/openssl/openssl/MacOS/mklinks.as.hqx | 820 ++ .../deps/openssl/openssl/MacOS/opensslconf.h | 116 + node-v0.8.14/deps/openssl/openssl/Makefile | 640 + .../deps/openssl/openssl/Makefile.org | 638 + .../deps/openssl/openssl/Makefile.shared | 655 + node-v0.8.14/deps/openssl/openssl/NEWS | 604 + .../deps/openssl/openssl/Netware/build.bat | 235 + .../openssl/openssl/Netware/cpy_tests.bat | 113 + .../deps/openssl/openssl/Netware/do_tests.pl | 624 + .../deps/openssl/openssl/Netware/globals.txt | 254 + .../deps/openssl/openssl/Netware/readme.txt | 19 + .../deps/openssl/openssl/Netware/set_env.bat | 112 + node-v0.8.14/deps/openssl/openssl/PROBLEMS | 199 + node-v0.8.14/deps/openssl/openssl/README | 218 + node-v0.8.14/deps/openssl/openssl/README.ASN1 | 187 + .../deps/openssl/openssl/README.ENGINE | 289 + node-v0.8.14/deps/openssl/openssl/VMS/TODO | 18 + .../deps/openssl/openssl/VMS/VMSify-conf.pl | 34 + .../deps/openssl/openssl/VMS/WISHLIST.TXT | 4 + .../deps/openssl/openssl/VMS/install-vms.com | 67 + .../deps/openssl/openssl/VMS/mkshared.com | 476 + .../deps/openssl/openssl/VMS/multinet_shr.opt | 1 + .../openssl/openssl/VMS/openssl_startup.com | 108 + .../deps/openssl/openssl/VMS/openssl_undo.com | 20 + .../openssl/openssl/VMS/openssl_utils.com | 46 + .../openssl/openssl/VMS/socketshr_shr.opt | 1 + .../openssl/openssl/VMS/tcpip_shr_decc.opt | 1 + .../openssl/openssl/VMS/test-includes.com | 28 + .../deps/openssl/openssl/VMS/ucx_shr_decc.opt | 1 + .../openssl/openssl/VMS/ucx_shr_decc_log.opt | 1 + .../deps/openssl/openssl/VMS/ucx_shr_vaxc.opt | 1 + node-v0.8.14/deps/openssl/openssl/bugs/MS | 7 + node-v0.8.14/deps/openssl/openssl/bugs/SSLv3 | 49 + .../deps/openssl/openssl/bugs/alpha.c | 91 + .../deps/openssl/openssl/bugs/dggccbug.c | 45 + .../deps/openssl/openssl/bugs/sgiccbug.c | 57 + .../deps/openssl/openssl/bugs/sslref.dif | 26 + .../deps/openssl/openssl/bugs/stream.c | 131 + .../deps/openssl/openssl/bugs/ultrixcc.c | 45 + .../openssl/openssl/certs/README.RootCerts | 4 + .../openssl/openssl/certs/demo/ca-cert.pem | 33 + .../openssl/openssl/certs/demo/dsa-ca.pem | 43 + .../openssl/openssl/certs/demo/dsa-pca.pem | 49 + .../openssl/openssl/certs/demo/pca-cert.pem | 33 + .../openssl/openssl/certs/expired/ICE.crl | 9 + node-v0.8.14/deps/openssl/openssl/config | 933 ++ .../deps/openssl/openssl/crypto/LPdir_nyi.c | 42 + .../deps/openssl/openssl/crypto/LPdir_unix.c | 127 + .../deps/openssl/openssl/crypto/LPdir_vms.c | 206 + .../deps/openssl/openssl/crypto/LPdir_win.c | 153 + .../deps/openssl/openssl/crypto/LPdir_win32.c | 30 + .../deps/openssl/openssl/crypto/LPdir_wince.c | 31 + .../deps/openssl/openssl/crypto/Makefile | 201 + .../deps/openssl/openssl/crypto/aes/Makefile | 132 + .../deps/openssl/openssl/crypto/aes/README | 3 + .../deps/openssl/openssl/crypto/aes/aes.h | 142 + .../deps/openssl/openssl/crypto/aes/aes_cbc.c | 63 + .../deps/openssl/openssl/crypto/aes/aes_cfb.c | 81 + .../openssl/openssl/crypto/aes/aes_core.c | 1358 ++ .../deps/openssl/openssl/crypto/aes/aes_ctr.c | 61 + .../deps/openssl/openssl/crypto/aes/aes_ecb.c | 73 + .../deps/openssl/openssl/crypto/aes/aes_ige.c | 323 + .../openssl/openssl/crypto/aes/aes_locl.h | 89 + .../openssl/openssl/crypto/aes/aes_misc.c | 64 + .../deps/openssl/openssl/crypto/aes/aes_ofb.c | 60 + .../openssl/openssl/crypto/aes/aes_wrap.c | 259 + .../openssl/openssl/crypto/aes/aes_x86core.c | 1063 ++ .../openssl/openssl/crypto/aes/asm/aes-586.pl | 2980 ++++ .../openssl/crypto/aes/asm/aes-armv4.pl | 1030 ++ .../openssl/openssl/crypto/aes/asm/aes-ia64.S | 1123 ++ .../openssl/openssl/crypto/aes/asm/aes-ppc.pl | 1189 ++ .../openssl/crypto/aes/asm/aes-s390x.pl | 1339 ++ .../openssl/crypto/aes/asm/aes-sparcv9.pl | 1181 ++ .../openssl/crypto/aes/asm/aes-x86_64.pl | 2809 ++++ .../deps/openssl/openssl/crypto/alphacpuid.pl | 126 + .../deps/openssl/openssl/crypto/asn1/Makefile | 930 ++ .../openssl/openssl/crypto/asn1/a_bitstr.c | 248 + .../deps/openssl/openssl/crypto/asn1/a_bool.c | 114 + .../openssl/openssl/crypto/asn1/a_bytes.c | 314 + .../openssl/openssl/crypto/asn1/a_d2i_fp.c | 286 + .../openssl/openssl/crypto/asn1/a_digest.c | 111 + .../deps/openssl/openssl/crypto/asn1/a_dup.c | 109 + .../deps/openssl/openssl/crypto/asn1/a_enum.c | 182 + .../openssl/openssl/crypto/asn1/a_gentm.c | 263 + .../openssl/openssl/crypto/asn1/a_i2d_fp.c | 163 + .../deps/openssl/openssl/crypto/asn1/a_int.c | 458 + .../openssl/openssl/crypto/asn1/a_mbstr.c | 400 + .../openssl/openssl/crypto/asn1/a_object.c | 403 + .../openssl/openssl/crypto/asn1/a_octet.c | 71 + .../openssl/openssl/crypto/asn1/a_print.c | 127 + .../deps/openssl/openssl/crypto/asn1/a_set.c | 241 + .../deps/openssl/openssl/crypto/asn1/a_sign.c | 298 + .../openssl/openssl/crypto/asn1/a_strex.c | 575 + .../openssl/openssl/crypto/asn1/a_strnid.c | 290 + .../deps/openssl/openssl/crypto/asn1/a_time.c | 198 + .../deps/openssl/openssl/crypto/asn1/a_type.c | 159 + .../openssl/openssl/crypto/asn1/a_utctm.c | 318 + .../deps/openssl/openssl/crypto/asn1/a_utf8.c | 211 + .../openssl/openssl/crypto/asn1/a_verify.c | 197 + .../openssl/openssl/crypto/asn1/ameth_lib.c | 450 + .../deps/openssl/openssl/crypto/asn1/asn1.h | 1402 ++ .../openssl/openssl/crypto/asn1/asn1_err.c | 329 + .../openssl/openssl/crypto/asn1/asn1_gen.c | 854 ++ .../openssl/openssl/crypto/asn1/asn1_lib.c | 482 + .../openssl/openssl/crypto/asn1/asn1_locl.h | 134 + .../openssl/openssl/crypto/asn1/asn1_mac.h | 578 + .../openssl/openssl/crypto/asn1/asn1_par.c | 437 + .../deps/openssl/openssl/crypto/asn1/asn1t.h | 960 ++ .../openssl/openssl/crypto/asn1/asn_mime.c | 942 ++ .../openssl/openssl/crypto/asn1/asn_moid.c | 160 + .../openssl/openssl/crypto/asn1/asn_pack.c | 191 + .../openssl/openssl/crypto/asn1/bio_asn1.c | 495 + .../openssl/openssl/crypto/asn1/bio_ndef.c | 243 + .../openssl/openssl/crypto/asn1/charmap.h | 15 + .../openssl/openssl/crypto/asn1/charmap.pl | 80 + .../deps/openssl/openssl/crypto/asn1/d2i_pr.c | 170 + .../deps/openssl/openssl/crypto/asn1/d2i_pu.c | 139 + .../openssl/openssl/crypto/asn1/evp_asn1.c | 189 + .../deps/openssl/openssl/crypto/asn1/f_enum.c | 207 + .../deps/openssl/openssl/crypto/asn1/f_int.c | 219 + .../openssl/openssl/crypto/asn1/f_string.c | 212 + .../deps/openssl/openssl/crypto/asn1/i2d_pr.c | 80 + .../deps/openssl/openssl/crypto/asn1/i2d_pu.c | 95 + .../deps/openssl/openssl/crypto/asn1/n_pkey.c | 343 + .../deps/openssl/openssl/crypto/asn1/nsseq.c | 83 + .../deps/openssl/openssl/crypto/asn1/p5_pbe.c | 148 + .../openssl/openssl/crypto/asn1/p5_pbev2.c | 235 + .../openssl/openssl/crypto/asn1/p8_pkey.c | 155 + .../openssl/openssl/crypto/asn1/t_bitst.c | 102 + .../deps/openssl/openssl/crypto/asn1/t_crl.c | 133 + .../deps/openssl/openssl/crypto/asn1/t_pkey.c | 114 + .../deps/openssl/openssl/crypto/asn1/t_req.c | 266 + .../deps/openssl/openssl/crypto/asn1/t_spki.c | 107 + .../deps/openssl/openssl/crypto/asn1/t_x509.c | 493 + .../openssl/openssl/crypto/asn1/t_x509a.c | 110 + .../openssl/openssl/crypto/asn1/tasn_dec.c | 1347 ++ .../openssl/openssl/crypto/asn1/tasn_enc.c | 691 + .../openssl/openssl/crypto/asn1/tasn_fre.c | 266 + .../openssl/openssl/crypto/asn1/tasn_new.c | 396 + .../openssl/openssl/crypto/asn1/tasn_prn.c | 627 + .../openssl/openssl/crypto/asn1/tasn_typ.c | 148 + .../openssl/openssl/crypto/asn1/tasn_utl.c | 279 + .../openssl/openssl/crypto/asn1/x_algor.c | 130 + .../openssl/openssl/crypto/asn1/x_attrib.c | 118 + .../openssl/openssl/crypto/asn1/x_bignum.c | 139 + .../deps/openssl/openssl/crypto/asn1/x_crl.c | 527 + .../openssl/openssl/crypto/asn1/x_exten.c | 76 + .../deps/openssl/openssl/crypto/asn1/x_info.c | 114 + .../deps/openssl/openssl/crypto/asn1/x_long.c | 179 + .../deps/openssl/openssl/crypto/asn1/x_name.c | 520 + .../openssl/openssl/crypto/asn1/x_nx509.c | 72 + .../deps/openssl/openssl/crypto/asn1/x_pkey.c | 151 + .../openssl/openssl/crypto/asn1/x_pubkey.c | 373 + .../deps/openssl/openssl/crypto/asn1/x_req.c | 113 + .../deps/openssl/openssl/crypto/asn1/x_sig.c | 69 + .../deps/openssl/openssl/crypto/asn1/x_spki.c | 81 + .../deps/openssl/openssl/crypto/asn1/x_val.c | 69 + .../deps/openssl/openssl/crypto/asn1/x_x509.c | 194 + .../openssl/openssl/crypto/asn1/x_x509a.c | 180 + .../deps/openssl/openssl/crypto/bf/COPYRIGHT | 46 + .../deps/openssl/openssl/crypto/bf/INSTALL | 14 + .../deps/openssl/openssl/crypto/bf/Makefile | 98 + .../deps/openssl/openssl/crypto/bf/README | 8 + .../deps/openssl/openssl/crypto/bf/VERSION | 6 + .../openssl/openssl/crypto/bf/asm/bf-586.pl | 137 + .../openssl/openssl/crypto/bf/asm/bf-686.pl | 127 + .../deps/openssl/openssl/crypto/bf/asm/readme | 10 + .../deps/openssl/openssl/crypto/bf/bf_cbc.c | 143 + .../deps/openssl/openssl/crypto/bf/bf_cfb64.c | 121 + .../deps/openssl/openssl/crypto/bf/bf_ecb.c | 96 + .../deps/openssl/openssl/crypto/bf/bf_enc.c | 306 + .../deps/openssl/openssl/crypto/bf/bf_locl.h | 219 + .../deps/openssl/openssl/crypto/bf/bf_ofb64.c | 110 + .../deps/openssl/openssl/crypto/bf/bf_opts.c | 331 + .../deps/openssl/openssl/crypto/bf/bf_pi.h | 325 + .../deps/openssl/openssl/crypto/bf/bf_skey.c | 116 + .../deps/openssl/openssl/crypto/bf/bfs.cpp | 67 + .../deps/openssl/openssl/crypto/bf/bfspeed.c | 277 + .../deps/openssl/openssl/crypto/bf/bftest.c | 540 + .../deps/openssl/openssl/crypto/bf/blowfish.h | 127 + .../deps/openssl/openssl/crypto/bio/Makefile | 222 + .../deps/openssl/openssl/crypto/bio/b_dump.c | 187 + .../deps/openssl/openssl/crypto/bio/b_print.c | 842 ++ .../deps/openssl/openssl/crypto/bio/b_sock.c | 975 ++ .../deps/openssl/openssl/crypto/bio/bf_buff.c | 512 + .../deps/openssl/openssl/crypto/bio/bf_lbuf.c | 397 + .../deps/openssl/openssl/crypto/bio/bf_nbio.c | 253 + .../deps/openssl/openssl/crypto/bio/bf_null.c | 183 + .../deps/openssl/openssl/crypto/bio/bio.h | 779 ++ .../deps/openssl/openssl/crypto/bio/bio_cb.c | 143 + .../deps/openssl/openssl/crypto/bio/bio_err.c | 154 + .../deps/openssl/openssl/crypto/bio/bio_lcl.h | 36 + .../deps/openssl/openssl/crypto/bio/bio_lib.c | 602 + .../openssl/openssl/crypto/bio/bss_acpt.c | 478 + .../deps/openssl/openssl/crypto/bio/bss_bio.c | 924 ++ .../openssl/openssl/crypto/bio/bss_conn.c | 652 + .../openssl/openssl/crypto/bio/bss_dgram.c | 836 ++ .../deps/openssl/openssl/crypto/bio/bss_fd.c | 319 + .../openssl/openssl/crypto/bio/bss_file.c | 477 + .../deps/openssl/openssl/crypto/bio/bss_log.c | 399 + .../deps/openssl/openssl/crypto/bio/bss_mem.c | 319 + .../openssl/openssl/crypto/bio/bss_null.c | 150 + .../openssl/openssl/crypto/bio/bss_rtcp.c | 294 + .../openssl/openssl/crypto/bio/bss_sock.c | 294 + .../deps/openssl/openssl/crypto/bn/Makefile | 347 + .../deps/openssl/openssl/crypto/bn/asm/README | 27 + .../openssl/crypto/bn/asm/alpha-mont.pl | 321 + .../openssl/crypto/bn/asm/armv4-mont.pl | 201 + .../openssl/openssl/crypto/bn/asm/bn-586.pl | 774 ++ .../openssl/openssl/crypto/bn/asm/co-586.pl | 287 + .../deps/openssl/openssl/crypto/bn/asm/ia64.S | 1555 +++ .../openssl/crypto/bn/asm/mips3-mont.pl | 327 + .../openssl/openssl/crypto/bn/asm/mips3.s | 2201 +++ .../openssl/openssl/crypto/bn/asm/pa-risc2.s | 1618 +++ .../openssl/openssl/crypto/bn/asm/pa-risc2W.s | 1605 +++ .../openssl/openssl/crypto/bn/asm/ppc-mont.pl | 323 + .../deps/openssl/openssl/crypto/bn/asm/ppc.pl | 1981 +++ .../openssl/crypto/bn/asm/ppc64-mont.pl | 918 ++ .../openssl/crypto/bn/asm/s390x-mont.pl | 225 + .../openssl/openssl/crypto/bn/asm/s390x.S | 678 + .../openssl/openssl/crypto/bn/asm/sparcv8.S | 1458 ++ .../openssl/crypto/bn/asm/sparcv8plus.S | 1558 +++ .../openssl/crypto/bn/asm/sparcv9-mont.pl | 606 + .../openssl/crypto/bn/asm/sparcv9a-mont.pl | 882 ++ .../openssl/openssl/crypto/bn/asm/via-mont.pl | 242 + .../openssl/openssl/crypto/bn/asm/vms.mar | 6440 +++++++++ .../openssl/openssl/crypto/bn/asm/x86-mont.pl | 593 + .../deps/openssl/openssl/crypto/bn/asm/x86.pl | 28 + .../openssl/openssl/crypto/bn/asm/x86/add.pl | 76 + .../openssl/crypto/bn/asm/x86/comba.pl | 277 + .../openssl/openssl/crypto/bn/asm/x86/div.pl | 15 + .../deps/openssl/openssl/crypto/bn/asm/x86/f | 3 + .../openssl/openssl/crypto/bn/asm/x86/mul.pl | 77 + .../openssl/crypto/bn/asm/x86/mul_add.pl | 87 + .../openssl/openssl/crypto/bn/asm/x86/sqr.pl | 60 + .../openssl/openssl/crypto/bn/asm/x86/sub.pl | 76 + .../openssl/crypto/bn/asm/x86_64-gcc.c | 606 + .../openssl/crypto/bn/asm/x86_64-mont.pl | 330 + .../crypto/bn/asm/x86_64-win32-masm.asm | 1679 +++ .../deps/openssl/openssl/crypto/bn/bn.h | 876 ++ .../deps/openssl/openssl/crypto/bn/bn.mul | 19 + .../deps/openssl/openssl/crypto/bn/bn_add.c | 313 + .../deps/openssl/openssl/crypto/bn/bn_asm.c | 1030 ++ .../deps/openssl/openssl/crypto/bn/bn_blind.c | 385 + .../deps/openssl/openssl/crypto/bn/bn_const.c | 402 + .../deps/openssl/openssl/crypto/bn/bn_ctx.c | 454 + .../deps/openssl/openssl/crypto/bn/bn_depr.c | 112 + .../deps/openssl/openssl/crypto/bn/bn_div.c | 650 + .../deps/openssl/openssl/crypto/bn/bn_err.c | 150 + .../deps/openssl/openssl/crypto/bn/bn_exp.c | 991 ++ .../deps/openssl/openssl/crypto/bn/bn_exp2.c | 312 + .../deps/openssl/openssl/crypto/bn/bn_gcd.c | 654 + .../deps/openssl/openssl/crypto/bn/bn_gf2m.c | 1035 ++ .../deps/openssl/openssl/crypto/bn/bn_kron.c | 184 + .../deps/openssl/openssl/crypto/bn/bn_lcl.h | 491 + .../deps/openssl/openssl/crypto/bn/bn_lib.c | 845 ++ .../deps/openssl/openssl/crypto/bn/bn_mod.c | 301 + .../deps/openssl/openssl/crypto/bn/bn_mont.c | 567 + .../deps/openssl/openssl/crypto/bn/bn_mpi.c | 130 + .../deps/openssl/openssl/crypto/bn/bn_mul.c | 1166 ++ .../deps/openssl/openssl/crypto/bn/bn_nist.c | 844 ++ .../deps/openssl/openssl/crypto/bn/bn_prime.c | 494 + .../deps/openssl/openssl/crypto/bn/bn_prime.h | 327 + .../openssl/openssl/crypto/bn/bn_prime.pl | 119 + .../deps/openssl/openssl/crypto/bn/bn_print.c | 359 + .../deps/openssl/openssl/crypto/bn/bn_rand.c | 305 + .../deps/openssl/openssl/crypto/bn/bn_recp.c | 234 + .../deps/openssl/openssl/crypto/bn/bn_shift.c | 220 + .../deps/openssl/openssl/crypto/bn/bn_sqr.c | 294 + .../deps/openssl/openssl/crypto/bn/bn_sqrt.c | 393 + .../deps/openssl/openssl/crypto/bn/bn_word.c | 247 + .../deps/openssl/openssl/crypto/bn/bnspeed.c | 233 + .../deps/openssl/openssl/crypto/bn/bntest.c | 2013 +++ .../deps/openssl/openssl/crypto/bn/divtest.c | 41 + .../deps/openssl/openssl/crypto/bn/exp.c | 62 + .../deps/openssl/openssl/crypto/bn/expspeed.c | 353 + .../deps/openssl/openssl/crypto/bn/exptest.c | 204 + .../deps/openssl/openssl/crypto/bn/todo | 3 + .../openssl/openssl/crypto/bn/vms-helper.c | 68 + .../openssl/openssl/crypto/buffer/Makefile | 90 + .../openssl/openssl/crypto/buffer/buf_err.c | 99 + .../openssl/openssl/crypto/buffer/buffer.c | 261 + .../openssl/openssl/crypto/buffer/buffer.h | 119 + .../openssl/openssl/crypto/camellia/Makefile | 103 + .../openssl/crypto/camellia/asm/cmll-x86.pl | 1138 ++ .../crypto/camellia/asm/cmll-x86_64.pl | 1080 ++ .../openssl/crypto/camellia/camellia.c | 582 + .../openssl/crypto/camellia/camellia.h | 126 + .../openssl/crypto/camellia/cmll_cbc.c | 64 + .../openssl/crypto/camellia/cmll_cfb.c | 139 + .../openssl/crypto/camellia/cmll_ctr.c | 64 + .../openssl/crypto/camellia/cmll_ecb.c | 74 + .../openssl/crypto/camellia/cmll_locl.h | 83 + .../openssl/crypto/camellia/cmll_misc.c | 79 + .../openssl/crypto/camellia/cmll_ofb.c | 119 + .../deps/openssl/openssl/crypto/cast/Makefile | 99 + .../openssl/crypto/cast/asm/cast-586.pl | 177 + .../openssl/openssl/crypto/cast/asm/readme | 7 + .../openssl/openssl/crypto/cast/c_cfb64.c | 121 + .../deps/openssl/openssl/crypto/cast/c_ecb.c | 79 + .../deps/openssl/openssl/crypto/cast/c_enc.c | 208 + .../openssl/openssl/crypto/cast/c_ofb64.c | 110 + .../deps/openssl/openssl/crypto/cast/c_skey.c | 166 + .../deps/openssl/openssl/crypto/cast/cast.h | 105 + .../openssl/openssl/crypto/cast/cast_lcl.h | 227 + .../deps/openssl/openssl/crypto/cast/cast_s.h | 585 + .../openssl/openssl/crypto/cast/cast_spd.c | 278 + .../openssl/openssl/crypto/cast/castopts.c | 342 + .../openssl/openssl/crypto/cast/casts.cpp | 70 + .../openssl/openssl/crypto/cast/casttest.c | 233 + .../deps/openssl/openssl/crypto/cms/Makefile | 264 + .../deps/openssl/openssl/crypto/cms/cms.h | 479 + .../openssl/openssl/crypto/cms/cms_asn1.c | 380 + .../deps/openssl/openssl/crypto/cms/cms_att.c | 195 + .../deps/openssl/openssl/crypto/cms/cms_cd.c | 134 + .../deps/openssl/openssl/crypto/cms/cms_dd.c | 148 + .../deps/openssl/openssl/crypto/cms/cms_enc.c | 262 + .../deps/openssl/openssl/crypto/cms/cms_env.c | 862 ++ .../deps/openssl/openssl/crypto/cms/cms_err.c | 236 + .../deps/openssl/openssl/crypto/cms/cms_ess.c | 420 + .../deps/openssl/openssl/crypto/cms/cms_io.c | 133 + .../deps/openssl/openssl/crypto/cms/cms_lcl.h | 461 + .../deps/openssl/openssl/crypto/cms/cms_lib.c | 627 + .../deps/openssl/openssl/crypto/cms/cms_sd.c | 984 ++ .../openssl/openssl/crypto/cms/cms_smime.c | 797 ++ .../deps/openssl/openssl/crypto/comp/Makefile | 108 + .../deps/openssl/openssl/crypto/comp/c_rle.c | 61 + .../deps/openssl/openssl/crypto/comp/c_zlib.c | 799 ++ .../deps/openssl/openssl/crypto/comp/comp.h | 80 + .../openssl/openssl/crypto/comp/comp_err.c | 100 + .../openssl/openssl/crypto/comp/comp_lib.c | 72 + .../deps/openssl/openssl/crypto/conf/Makefile | 152 + .../deps/openssl/openssl/crypto/conf/README | 73 + .../openssl/openssl/crypto/conf/cnf_save.c | 106 + .../deps/openssl/openssl/crypto/conf/conf.h | 263 + .../openssl/openssl/crypto/conf/conf_api.c | 301 + .../openssl/openssl/crypto/conf/conf_api.h | 89 + .../openssl/openssl/crypto/conf/conf_def.c | 740 + .../openssl/openssl/crypto/conf/conf_def.h | 180 + .../openssl/openssl/crypto/conf/conf_err.c | 131 + .../openssl/openssl/crypto/conf/conf_lib.c | 407 + .../openssl/openssl/crypto/conf/conf_mall.c | 80 + .../openssl/openssl/crypto/conf/conf_mod.c | 623 + .../openssl/openssl/crypto/conf/conf_sap.c | 111 + .../openssl/openssl/crypto/conf/keysets.pl | 185 + .../openssl/openssl/crypto/conf/ssleay.cnf | 78 + .../deps/openssl/openssl/crypto/conf/test.c | 98 + .../deps/openssl/openssl/crypto/cpt_err.c | 103 + .../deps/openssl/openssl/crypto/cryptlib.c | 898 ++ .../deps/openssl/openssl/crypto/cryptlib.h | 111 + .../openssl/openssl/crypto/crypto-lib.com | 1507 ++ .../deps/openssl/openssl/crypto/crypto.h | 575 + .../deps/openssl/openssl/crypto/cversion.c | 117 + .../deps/openssl/openssl/crypto/des/COPYRIGHT | 50 + .../deps/openssl/openssl/crypto/des/DES.pm | 19 + .../deps/openssl/openssl/crypto/des/DES.xs | 268 + .../deps/openssl/openssl/crypto/des/FILES0 | 96 + .../deps/openssl/openssl/crypto/des/INSTALL | 69 + .../deps/openssl/openssl/crypto/des/Imakefile | 35 + .../deps/openssl/openssl/crypto/des/KERBEROS | 41 + .../deps/openssl/openssl/crypto/des/Makefile | 278 + .../deps/openssl/openssl/crypto/des/README | 54 + .../deps/openssl/openssl/crypto/des/VERSION | 412 + .../openssl/crypto/des/asm/crypt586.pl | 209 + .../openssl/openssl/crypto/des/asm/des-586.pl | 453 + .../openssl/openssl/crypto/des/asm/des_enc.m4 | 2099 +++ .../openssl/openssl/crypto/des/asm/desboth.pl | 79 + .../openssl/openssl/crypto/des/asm/readme | 131 + .../openssl/openssl/crypto/des/cbc3_enc.c | 99 + .../openssl/openssl/crypto/des/cbc_cksm.c | 106 + .../deps/openssl/openssl/crypto/des/cbc_enc.c | 61 + .../openssl/openssl/crypto/des/cfb64ede.c | 254 + .../openssl/openssl/crypto/des/cfb64enc.c | 121 + .../deps/openssl/openssl/crypto/des/cfb_enc.c | 195 + .../openssl/openssl/crypto/des/des-lib.com | 1005 ++ .../deps/openssl/openssl/crypto/des/des.c | 932 ++ .../deps/openssl/openssl/crypto/des/des.h | 245 + .../deps/openssl/openssl/crypto/des/des.pod | 217 + .../deps/openssl/openssl/crypto/des/des3s.cpp | 67 + .../deps/openssl/openssl/crypto/des/des_enc.c | 400 + .../openssl/openssl/crypto/des/des_locl.h | 432 + .../deps/openssl/openssl/crypto/des/des_old.c | 273 + .../deps/openssl/openssl/crypto/des/des_old.h | 446 + .../openssl/openssl/crypto/des/des_old2.c | 82 + .../openssl/openssl/crypto/des/des_opts.c | 608 + .../deps/openssl/openssl/crypto/des/des_ver.h | 71 + .../deps/openssl/openssl/crypto/des/dess.cpp | 67 + .../deps/openssl/openssl/crypto/des/destest.c | 952 ++ .../openssl/openssl/crypto/des/ecb3_enc.c | 83 + .../deps/openssl/openssl/crypto/des/ecb_enc.c | 122 + .../openssl/openssl/crypto/des/ede_cbcm_enc.c | 199 + .../openssl/openssl/crypto/des/enc_read.c | 240 + .../openssl/openssl/crypto/des/enc_writ.c | 179 + .../deps/openssl/openssl/crypto/des/fcrypt.c | 170 + .../openssl/openssl/crypto/des/fcrypt_b.c | 143 + .../openssl/openssl/crypto/des/makefile.bc | 50 + .../openssl/openssl/crypto/des/ncbc_enc.c | 148 + .../openssl/openssl/crypto/des/ofb64ede.c | 125 + .../openssl/openssl/crypto/des/ofb64enc.c | 110 + .../deps/openssl/openssl/crypto/des/ofb_enc.c | 135 + .../openssl/openssl/crypto/des/options.txt | 39 + .../openssl/openssl/crypto/des/pcbc_enc.c | 123 + .../openssl/openssl/crypto/des/qud_cksm.c | 139 + .../openssl/openssl/crypto/des/rand_key.c | 68 + .../openssl/openssl/crypto/des/read2pwd.c | 140 + .../openssl/openssl/crypto/des/read_pwd.c | 521 + .../deps/openssl/openssl/crypto/des/rpc_des.h | 131 + .../deps/openssl/openssl/crypto/des/rpc_enc.c | 98 + .../deps/openssl/openssl/crypto/des/rpw.c | 99 + .../deps/openssl/openssl/crypto/des/set_key.c | 407 + .../deps/openssl/openssl/crypto/des/speed.c | 314 + .../deps/openssl/openssl/crypto/des/spr.h | 204 + .../deps/openssl/openssl/crypto/des/str2key.c | 174 + .../deps/openssl/openssl/crypto/des/t/test | 27 + .../openssl/crypto/des/times/486-50.sol | 16 + .../openssl/crypto/des/times/586-100.lnx | 20 + .../openssl/crypto/des/times/686-200.fre | 18 + .../openssl/openssl/crypto/des/times/aix.cc | 26 + .../openssl/openssl/crypto/des/times/alpha.cc | 18 + .../openssl/openssl/crypto/des/times/hpux.cc | 17 + .../openssl/crypto/des/times/sparc.gcc | 17 + .../openssl/crypto/des/times/usparc.cc | 31 + .../deps/openssl/openssl/crypto/des/typemap | 34 + .../openssl/openssl/crypto/des/xcbc_enc.c | 197 + .../deps/openssl/openssl/crypto/dh/Makefile | 180 + .../deps/openssl/openssl/crypto/dh/dh.h | 260 + .../deps/openssl/openssl/crypto/dh/dh1024.pem | 5 + .../deps/openssl/openssl/crypto/dh/dh192.pem | 3 + .../deps/openssl/openssl/crypto/dh/dh2048.pem | 16 + .../deps/openssl/openssl/crypto/dh/dh4096.pem | 14 + .../deps/openssl/openssl/crypto/dh/dh512.pem | 4 + .../deps/openssl/openssl/crypto/dh/dh_ameth.c | 500 + .../deps/openssl/openssl/crypto/dh/dh_asn1.c | 93 + .../deps/openssl/openssl/crypto/dh/dh_check.c | 142 + .../deps/openssl/openssl/crypto/dh/dh_depr.c | 83 + .../deps/openssl/openssl/crypto/dh/dh_err.c | 117 + .../deps/openssl/openssl/crypto/dh/dh_gen.c | 175 + .../deps/openssl/openssl/crypto/dh/dh_key.c | 263 + .../deps/openssl/openssl/crypto/dh/dh_lib.c | 247 + .../deps/openssl/openssl/crypto/dh/dh_pmeth.c | 254 + .../deps/openssl/openssl/crypto/dh/dh_prn.c | 80 + .../deps/openssl/openssl/crypto/dh/dhtest.c | 226 + .../deps/openssl/openssl/crypto/dh/example | 50 + .../deps/openssl/openssl/crypto/dh/generate | 65 + .../deps/openssl/openssl/crypto/dh/p1024.c | 92 + .../deps/openssl/openssl/crypto/dh/p192.c | 80 + .../deps/openssl/openssl/crypto/dh/p512.c | 85 + .../deps/openssl/openssl/crypto/dsa/Makefile | 208 + .../deps/openssl/openssl/crypto/dsa/README | 4 + .../deps/openssl/openssl/crypto/dsa/dsa.h | 307 + .../openssl/openssl/crypto/dsa/dsa_ameth.c | 657 + .../openssl/openssl/crypto/dsa/dsa_asn1.c | 150 + .../openssl/openssl/crypto/dsa/dsa_depr.c | 106 + .../deps/openssl/openssl/crypto/dsa/dsa_err.c | 125 + .../deps/openssl/openssl/crypto/dsa/dsa_gen.c | 344 + .../deps/openssl/openssl/crypto/dsa/dsa_key.c | 128 + .../deps/openssl/openssl/crypto/dsa/dsa_lib.c | 311 + .../openssl/openssl/crypto/dsa/dsa_locl.h | 59 + .../openssl/openssl/crypto/dsa/dsa_ossl.c | 398 + .../openssl/openssl/crypto/dsa/dsa_pmeth.c | 316 + .../deps/openssl/openssl/crypto/dsa/dsa_prn.c | 121 + .../openssl/openssl/crypto/dsa/dsa_sign.c | 90 + .../deps/openssl/openssl/crypto/dsa/dsa_vrf.c | 89 + .../deps/openssl/openssl/crypto/dsa/dsagen.c | 111 + .../deps/openssl/openssl/crypto/dsa/dsatest.c | 259 + .../openssl/openssl/crypto/dsa/fips186a.txt | 122 + .../deps/openssl/openssl/crypto/dso/Makefile | 150 + .../deps/openssl/openssl/crypto/dso/README | 22 + .../deps/openssl/openssl/crypto/dso/dso.h | 409 + .../openssl/openssl/crypto/dso/dso_beos.c | 270 + .../deps/openssl/openssl/crypto/dso/dso_dl.c | 393 + .../openssl/openssl/crypto/dso/dso_dlfcn.c | 483 + .../deps/openssl/openssl/crypto/dso/dso_err.c | 159 + .../deps/openssl/openssl/crypto/dso/dso_lib.c | 483 + .../openssl/openssl/crypto/dso/dso_null.c | 90 + .../openssl/openssl/crypto/dso/dso_openssl.c | 83 + .../deps/openssl/openssl/crypto/dso/dso_vms.c | 525 + .../openssl/openssl/crypto/dso/dso_win32.c | 844 ++ .../deps/openssl/openssl/crypto/ebcdic.c | 221 + .../deps/openssl/openssl/crypto/ebcdic.h | 19 + .../deps/openssl/openssl/crypto/ec/Makefile | 231 + .../deps/openssl/openssl/crypto/ec/ec.h | 1100 ++ .../deps/openssl/openssl/crypto/ec/ec2_mult.c | 386 + .../deps/openssl/openssl/crypto/ec/ec2_smpl.c | 1042 ++ .../deps/openssl/openssl/crypto/ec/ec_ameth.c | 659 + .../deps/openssl/openssl/crypto/ec/ec_asn1.c | 1429 ++ .../deps/openssl/openssl/crypto/ec/ec_check.c | 123 + .../deps/openssl/openssl/crypto/ec/ec_curve.c | 2059 +++ .../deps/openssl/openssl/crypto/ec/ec_cvt.c | 144 + .../deps/openssl/openssl/crypto/ec/ec_err.c | 258 + .../deps/openssl/openssl/crypto/ec/ec_key.c | 463 + .../deps/openssl/openssl/crypto/ec/ec_lcl.h | 393 + .../deps/openssl/openssl/crypto/ec/ec_lib.c | 1164 ++ .../deps/openssl/openssl/crypto/ec/ec_mult.c | 940 ++ .../deps/openssl/openssl/crypto/ec/ec_pmeth.c | 340 + .../deps/openssl/openssl/crypto/ec/ec_print.c | 195 + .../deps/openssl/openssl/crypto/ec/eck_prn.c | 391 + .../deps/openssl/openssl/crypto/ec/ecp_mont.c | 315 + .../deps/openssl/openssl/crypto/ec/ecp_nist.c | 210 + .../deps/openssl/openssl/crypto/ec/ecp_smpl.c | 1719 +++ .../deps/openssl/openssl/crypto/ec/ectest.c | 1334 ++ .../deps/openssl/openssl/crypto/ecdh/Makefile | 121 + .../deps/openssl/openssl/crypto/ecdh/ecdh.h | 123 + .../openssl/openssl/crypto/ecdh/ecdhtest.c | 368 + .../openssl/openssl/crypto/ecdh/ech_err.c | 98 + .../openssl/openssl/crypto/ecdh/ech_key.c | 83 + .../openssl/openssl/crypto/ecdh/ech_lib.c | 246 + .../openssl/openssl/crypto/ecdh/ech_locl.h | 94 + .../openssl/openssl/crypto/ecdh/ech_ossl.c | 213 + .../openssl/openssl/crypto/ecdsa/Makefile | 140 + .../deps/openssl/openssl/crypto/ecdsa/ecdsa.h | 258 + .../openssl/openssl/crypto/ecdsa/ecdsatest.c | 570 + .../openssl/openssl/crypto/ecdsa/ecs_asn1.c | 67 + .../openssl/openssl/crypto/ecdsa/ecs_err.c | 104 + .../openssl/openssl/crypto/ecdsa/ecs_lib.c | 259 + .../openssl/openssl/crypto/ecdsa/ecs_locl.h | 107 + .../openssl/openssl/crypto/ecdsa/ecs_ossl.c | 480 + .../openssl/openssl/crypto/ecdsa/ecs_sign.c | 106 + .../openssl/openssl/crypto/ecdsa/ecs_vrf.c | 96 + .../openssl/openssl/crypto/engine/Makefile | 417 + .../deps/openssl/openssl/crypto/engine/README | 211 + .../openssl/openssl/crypto/engine/eng_all.c | 126 + .../openssl/openssl/crypto/engine/eng_cnf.c | 259 + .../openssl/crypto/engine/eng_cryptodev.c | 1419 ++ .../openssl/openssl/crypto/engine/eng_ctrl.c | 389 + .../openssl/openssl/crypto/engine/eng_dyn.c | 548 + .../openssl/openssl/crypto/engine/eng_err.c | 173 + .../openssl/openssl/crypto/engine/eng_fat.c | 181 + .../openssl/openssl/crypto/engine/eng_init.c | 154 + .../openssl/openssl/crypto/engine/eng_int.h | 206 + .../openssl/openssl/crypto/engine/eng_lib.c | 332 + .../openssl/openssl/crypto/engine/eng_list.c | 433 + .../openssl/crypto/engine/eng_openssl.c | 384 + .../openssl/openssl/crypto/engine/eng_pkey.c | 196 + .../openssl/openssl/crypto/engine/eng_table.c | 351 + .../openssl/openssl/crypto/engine/engine.h | 833 ++ .../openssl/crypto/engine/enginetest.c | 283 + .../openssl/openssl/crypto/engine/tb_asnmth.c | 246 + .../openssl/openssl/crypto/engine/tb_cipher.c | 143 + .../openssl/openssl/crypto/engine/tb_dh.c | 118 + .../openssl/openssl/crypto/engine/tb_digest.c | 143 + .../openssl/openssl/crypto/engine/tb_dsa.c | 118 + .../openssl/openssl/crypto/engine/tb_ecdh.c | 133 + .../openssl/openssl/crypto/engine/tb_ecdsa.c | 118 + .../openssl/openssl/crypto/engine/tb_pkmeth.c | 167 + .../openssl/openssl/crypto/engine/tb_rand.c | 118 + .../openssl/openssl/crypto/engine/tb_rsa.c | 118 + .../openssl/openssl/crypto/engine/tb_store.c | 123 + .../deps/openssl/openssl/crypto/err/Makefile | 110 + .../deps/openssl/openssl/crypto/err/err.c | 1135 ++ .../deps/openssl/openssl/crypto/err/err.h | 385 + .../deps/openssl/openssl/crypto/err/err_all.c | 160 + .../deps/openssl/openssl/crypto/err/err_prn.c | 114 + .../openssl/openssl/crypto/err/openssl.ec | 96 + .../deps/openssl/openssl/crypto/evp/Makefile | 733 + .../deps/openssl/openssl/crypto/evp/bio_b64.c | 598 + .../deps/openssl/openssl/crypto/evp/bio_enc.c | 428 + .../deps/openssl/openssl/crypto/evp/bio_md.c | 270 + .../deps/openssl/openssl/crypto/evp/bio_ok.c | 575 + .../deps/openssl/openssl/crypto/evp/c_all.c | 90 + .../deps/openssl/openssl/crypto/evp/c_allc.c | 224 + .../deps/openssl/openssl/crypto/evp/c_alld.c | 114 + .../deps/openssl/openssl/crypto/evp/digest.c | 377 + .../deps/openssl/openssl/crypto/evp/e_aes.c | 120 + .../deps/openssl/openssl/crypto/evp/e_bf.c | 88 + .../openssl/openssl/crypto/evp/e_camellia.c | 131 + .../deps/openssl/openssl/crypto/evp/e_cast.c | 90 + .../deps/openssl/openssl/crypto/evp/e_des.c | 224 + .../deps/openssl/openssl/crypto/evp/e_des3.c | 313 + .../deps/openssl/openssl/crypto/evp/e_dsa.c | 71 + .../deps/openssl/openssl/crypto/evp/e_idea.c | 118 + .../deps/openssl/openssl/crypto/evp/e_null.c | 102 + .../deps/openssl/openssl/crypto/evp/e_old.c | 125 + .../deps/openssl/openssl/crypto/evp/e_rc2.c | 237 + .../deps/openssl/openssl/crypto/evp/e_rc4.c | 136 + .../deps/openssl/openssl/crypto/evp/e_rc5.c | 126 + .../deps/openssl/openssl/crypto/evp/e_seed.c | 83 + .../openssl/openssl/crypto/evp/e_xcbc_d.c | 138 + .../deps/openssl/openssl/crypto/evp/encode.c | 445 + .../deps/openssl/openssl/crypto/evp/evp.h | 1324 ++ .../openssl/openssl/crypto/evp/evp_acnf.c | 73 + .../deps/openssl/openssl/crypto/evp/evp_enc.c | 604 + .../deps/openssl/openssl/crypto/evp/evp_err.c | 218 + .../deps/openssl/openssl/crypto/evp/evp_key.c | 180 + .../deps/openssl/openssl/crypto/evp/evp_lib.c | 312 + .../openssl/openssl/crypto/evp/evp_locl.h | 345 + .../deps/openssl/openssl/crypto/evp/evp_pbe.c | 311 + .../openssl/openssl/crypto/evp/evp_pkey.c | 242 + .../openssl/openssl/crypto/evp/evp_test.c | 450 + .../openssl/openssl/crypto/evp/evptests.txt | 321 + .../deps/openssl/openssl/crypto/evp/m_dss.c | 99 + .../deps/openssl/openssl/crypto/evp/m_dss1.c | 100 + .../deps/openssl/openssl/crypto/evp/m_ecdsa.c | 148 + .../deps/openssl/openssl/crypto/evp/m_md2.c | 101 + .../deps/openssl/openssl/crypto/evp/m_md4.c | 101 + .../deps/openssl/openssl/crypto/evp/m_md5.c | 101 + .../deps/openssl/openssl/crypto/evp/m_mdc2.c | 101 + .../deps/openssl/openssl/crypto/evp/m_null.c | 95 + .../openssl/openssl/crypto/evp/m_ripemd.c | 101 + .../deps/openssl/openssl/crypto/evp/m_sha.c | 100 + .../deps/openssl/openssl/crypto/evp/m_sha1.c | 204 + .../openssl/openssl/crypto/evp/m_sigver.c | 200 + .../deps/openssl/openssl/crypto/evp/m_wp.c | 42 + .../deps/openssl/openssl/crypto/evp/names.c | 201 + .../openssl/openssl/crypto/evp/openbsd_hw.c | 446 + .../deps/openssl/openssl/crypto/evp/p5_crpt.c | 132 + .../openssl/openssl/crypto/evp/p5_crpt2.c | 299 + .../deps/openssl/openssl/crypto/evp/p_dec.c | 87 + .../deps/openssl/openssl/crypto/evp/p_enc.c | 86 + .../deps/openssl/openssl/crypto/evp/p_lib.c | 469 + .../deps/openssl/openssl/crypto/evp/p_open.c | 127 + .../deps/openssl/openssl/crypto/evp/p_seal.c | 115 + .../deps/openssl/openssl/crypto/evp/p_sign.c | 137 + .../openssl/openssl/crypto/evp/p_verify.c | 119 + .../openssl/openssl/crypto/evp/pmeth_fn.c | 368 + .../openssl/openssl/crypto/evp/pmeth_gn.c | 220 + .../openssl/openssl/crypto/evp/pmeth_lib.c | 540 + .../deps/openssl/openssl/crypto/ex_data.c | 636 + .../deps/openssl/openssl/crypto/hmac/Makefile | 110 + .../openssl/openssl/crypto/hmac/hm_ameth.c | 167 + .../openssl/openssl/crypto/hmac/hm_pmeth.c | 267 + .../deps/openssl/openssl/crypto/hmac/hmac.c | 214 + .../deps/openssl/openssl/crypto/hmac/hmac.h | 110 + .../openssl/openssl/crypto/hmac/hmactest.c | 175 + .../deps/openssl/openssl/crypto/ia64cpuid.S | 167 + .../deps/openssl/openssl/crypto/idea/Makefile | 86 + .../deps/openssl/openssl/crypto/idea/i_cbc.c | 168 + .../openssl/openssl/crypto/idea/i_cfb64.c | 122 + .../deps/openssl/openssl/crypto/idea/i_ecb.c | 85 + .../openssl/openssl/crypto/idea/i_ofb64.c | 111 + .../deps/openssl/openssl/crypto/idea/i_skey.c | 156 + .../deps/openssl/openssl/crypto/idea/idea.h | 100 + .../openssl/openssl/crypto/idea/idea_lcl.h | 215 + .../openssl/openssl/crypto/idea/idea_spd.c | 299 + .../openssl/openssl/crypto/idea/ideatest.c | 235 + .../deps/openssl/openssl/crypto/idea/version | 12 + .../openssl/openssl/crypto/install-crypto.com | 196 + .../openssl/openssl/crypto/jpake/Makefile | 64 + .../deps/openssl/openssl/crypto/jpake/jpake.c | 511 + .../deps/openssl/openssl/crypto/jpake/jpake.h | 131 + .../openssl/openssl/crypto/jpake/jpake_err.c | 107 + .../openssl/openssl/crypto/jpake/jpaketest.c | 192 + .../deps/openssl/openssl/crypto/krb5/Makefile | 84 + .../openssl/openssl/crypto/krb5/krb5_asn.c | 167 + .../openssl/openssl/crypto/krb5/krb5_asn.h | 256 + .../openssl/openssl/crypto/lhash/Makefile | 88 + .../openssl/openssl/crypto/lhash/lh_stats.c | 248 + .../openssl/openssl/crypto/lhash/lh_test.c | 88 + .../deps/openssl/openssl/crypto/lhash/lhash.c | 475 + .../deps/openssl/openssl/crypto/lhash/lhash.h | 241 + .../deps/openssl/openssl/crypto/lhash/num.pl | 17 + .../deps/openssl/openssl/crypto/md2/Makefile | 89 + .../deps/openssl/openssl/crypto/md2/md2.c | 124 + .../deps/openssl/openssl/crypto/md2/md2.h | 92 + .../openssl/openssl/crypto/md2/md2_dgst.c | 227 + .../deps/openssl/openssl/crypto/md2/md2_one.c | 94 + .../deps/openssl/openssl/crypto/md2/md2test.c | 143 + .../deps/openssl/openssl/crypto/md32_common.h | 415 + .../deps/openssl/openssl/crypto/md4/Makefile | 87 + .../deps/openssl/openssl/crypto/md4/md4.c | 127 + .../deps/openssl/openssl/crypto/md4/md4.h | 117 + .../openssl/openssl/crypto/md4/md4_dgst.c | 167 + .../openssl/openssl/crypto/md4/md4_locl.h | 112 + .../deps/openssl/openssl/crypto/md4/md4_one.c | 97 + .../deps/openssl/openssl/crypto/md4/md4s.cpp | 78 + .../deps/openssl/openssl/crypto/md4/md4test.c | 136 + .../deps/openssl/openssl/crypto/md5/Makefile | 100 + .../openssl/openssl/crypto/md5/asm/md5-586.pl | 307 + .../openssl/openssl/crypto/md5/asm/md5-ia64.S | 992 ++ .../openssl/crypto/md5/asm/md5-x86_64.pl | 369 + .../deps/openssl/openssl/crypto/md5/md5.c | 127 + .../deps/openssl/openssl/crypto/md5/md5.h | 117 + .../openssl/openssl/crypto/md5/md5_dgst.c | 184 + .../openssl/openssl/crypto/md5/md5_locl.h | 130 + .../deps/openssl/openssl/crypto/md5/md5_one.c | 97 + .../deps/openssl/openssl/crypto/md5/md5s.cpp | 78 + .../deps/openssl/openssl/crypto/md5/md5test.c | 140 + .../deps/openssl/openssl/crypto/mdc2/Makefile | 93 + .../deps/openssl/openssl/crypto/mdc2/mdc2.h | 95 + .../openssl/openssl/crypto/mdc2/mdc2_one.c | 76 + .../openssl/openssl/crypto/mdc2/mdc2dgst.c | 199 + .../openssl/openssl/crypto/mdc2/mdc2test.c | 149 + .../deps/openssl/openssl/crypto/mem.c | 418 + .../deps/openssl/openssl/crypto/mem_clr.c | 77 + .../deps/openssl/openssl/crypto/mem_dbg.c | 874 ++ .../openssl/openssl/crypto/modes/Makefile | 82 + .../openssl/openssl/crypto/modes/cbc128.c | 206 + .../openssl/openssl/crypto/modes/cfb128.c | 249 + .../openssl/openssl/crypto/modes/ctr128.c | 184 + .../openssl/openssl/crypto/modes/cts128.c | 259 + .../deps/openssl/openssl/crypto/modes/modes.h | 59 + .../openssl/openssl/crypto/modes/ofb128.c | 128 + .../deps/openssl/openssl/crypto/o_dir.c | 83 + .../deps/openssl/openssl/crypto/o_dir.h | 53 + .../deps/openssl/openssl/crypto/o_dir_test.c | 70 + .../deps/openssl/openssl/crypto/o_str.c | 111 + .../deps/openssl/openssl/crypto/o_str.h | 68 + .../deps/openssl/openssl/crypto/o_time.c | 372 + .../deps/openssl/openssl/crypto/o_time.h | 67 + .../openssl/openssl/crypto/objects/Makefile | 130 + .../openssl/openssl/crypto/objects/o_names.c | 372 + .../openssl/openssl/crypto/objects/obj_dat.c | 810 ++ .../openssl/openssl/crypto/objects/obj_dat.h | 4976 +++++++ .../openssl/openssl/crypto/objects/obj_dat.pl | 307 + .../openssl/openssl/crypto/objects/obj_err.c | 102 + .../openssl/openssl/crypto/objects/obj_lib.c | 129 + .../openssl/openssl/crypto/objects/obj_mac.h | 3914 ++++++ .../openssl/crypto/objects/obj_mac.num | 892 ++ .../openssl/openssl/crypto/objects/obj_xref.c | 231 + .../openssl/openssl/crypto/objects/obj_xref.h | 75 + .../openssl/crypto/objects/obj_xref.txt | 42 + .../openssl/crypto/objects/objects.README | 44 + .../openssl/openssl/crypto/objects/objects.h | 1138 ++ .../openssl/openssl/crypto/objects/objects.pl | 232 + .../openssl/crypto/objects/objects.txt | 1259 ++ .../openssl/openssl/crypto/objects/objxref.pl | 107 + .../deps/openssl/openssl/crypto/ocsp/Makefile | 213 + .../deps/openssl/openssl/crypto/ocsp/ocsp.h | 623 + .../openssl/openssl/crypto/ocsp/ocsp_asn.c | 182 + .../openssl/openssl/crypto/ocsp/ocsp_cl.c | 371 + .../openssl/openssl/crypto/ocsp/ocsp_err.c | 142 + .../openssl/openssl/crypto/ocsp/ocsp_ext.c | 518 + .../openssl/openssl/crypto/ocsp/ocsp_ht.c | 504 + .../openssl/openssl/crypto/ocsp/ocsp_lib.c | 265 + .../openssl/openssl/crypto/ocsp/ocsp_prn.c | 290 + .../openssl/openssl/crypto/ocsp/ocsp_srv.c | 264 + .../openssl/openssl/crypto/ocsp/ocsp_vfy.c | 446 + .../openssl/openssl/crypto/opensslconf.h.in | 154 + .../deps/openssl/openssl/crypto/opensslv.h | 89 + .../deps/openssl/openssl/crypto/ossl_typ.h | 200 + .../deps/openssl/openssl/crypto/pem/Makefile | 258 + .../deps/openssl/openssl/crypto/pem/message | 16 + .../deps/openssl/openssl/crypto/pem/pem.h | 641 + .../deps/openssl/openssl/crypto/pem/pem2.h | 70 + .../deps/openssl/openssl/crypto/pem/pem_all.c | 296 + .../deps/openssl/openssl/crypto/pem/pem_err.c | 161 + .../openssl/openssl/crypto/pem/pem_info.c | 405 + .../deps/openssl/openssl/crypto/pem/pem_lib.c | 852 ++ .../deps/openssl/openssl/crypto/pem/pem_oth.c | 86 + .../deps/openssl/openssl/crypto/pem/pem_pk8.c | 242 + .../openssl/openssl/crypto/pem/pem_pkey.c | 242 + .../openssl/openssl/crypto/pem/pem_seal.c | 189 + .../openssl/openssl/crypto/pem/pem_sign.c | 102 + .../openssl/openssl/crypto/pem/pem_x509.c | 68 + .../openssl/openssl/crypto/pem/pem_xaux.c | 68 + .../deps/openssl/openssl/crypto/pem/pkcs7.lis | 22 + .../deps/openssl/openssl/crypto/pem/pvkfmt.c | 938 ++ .../openssl/openssl/crypto/perlasm/cbc.pl | 349 + .../openssl/crypto/perlasm/ppc-xlate.pl | 152 + .../openssl/openssl/crypto/perlasm/readme | 124 + .../openssl/crypto/perlasm/x86_64-xlate.pl | 917 ++ .../openssl/openssl/crypto/perlasm/x86asm.pl | 207 + .../openssl/openssl/crypto/perlasm/x86gas.pl | 247 + .../openssl/openssl/crypto/perlasm/x86masm.pl | 184 + .../openssl/openssl/crypto/perlasm/x86nasm.pl | 166 + .../openssl/openssl/crypto/pkcs12/Makefile | 286 + .../openssl/openssl/crypto/pkcs12/p12_add.c | 240 + .../openssl/openssl/crypto/pkcs12/p12_asn.c | 125 + .../openssl/openssl/crypto/pkcs12/p12_attr.c | 145 + .../openssl/openssl/crypto/pkcs12/p12_crpt.c | 112 + .../openssl/openssl/crypto/pkcs12/p12_crt.c | 359 + .../openssl/openssl/crypto/pkcs12/p12_decr.c | 177 + .../openssl/openssl/crypto/pkcs12/p12_init.c | 92 + .../openssl/openssl/crypto/pkcs12/p12_key.c | 217 + .../openssl/openssl/crypto/pkcs12/p12_kiss.c | 302 + .../openssl/openssl/crypto/pkcs12/p12_mutl.c | 186 + .../openssl/openssl/crypto/pkcs12/p12_npas.c | 225 + .../openssl/openssl/crypto/pkcs12/p12_p8d.c | 68 + .../openssl/openssl/crypto/pkcs12/p12_p8e.c | 97 + .../openssl/openssl/crypto/pkcs12/p12_utl.c | 146 + .../openssl/openssl/crypto/pkcs12/pk12err.c | 144 + .../openssl/openssl/crypto/pkcs12/pkcs12.h | 331 + .../openssl/openssl/crypto/pkcs7/Makefile | 194 + .../openssl/openssl/crypto/pkcs7/bio_ber.c | 466 + .../openssl/openssl/crypto/pkcs7/bio_pk7.c | 69 + .../deps/openssl/openssl/crypto/pkcs7/dec.c | 248 + .../deps/openssl/openssl/crypto/pkcs7/des.pem | 15 + .../deps/openssl/openssl/crypto/pkcs7/doc | 24 + .../deps/openssl/openssl/crypto/pkcs7/enc.c | 174 + .../deps/openssl/openssl/crypto/pkcs7/es1.pem | 66 + .../openssl/openssl/crypto/pkcs7/example.c | 329 + .../openssl/openssl/crypto/pkcs7/example.h | 57 + .../openssl/openssl/crypto/pkcs7/info.pem | 57 + .../openssl/openssl/crypto/pkcs7/infokey.pem | 9 + .../deps/openssl/openssl/crypto/pkcs7/p7/a1 | 2 + .../deps/openssl/openssl/crypto/pkcs7/p7/a2 | 1 + .../openssl/openssl/crypto/pkcs7/p7/cert.p7c | Bin 0 -> 1728 bytes .../openssl/openssl/crypto/pkcs7/p7/smime.p7m | Bin 0 -> 4894 bytes .../openssl/openssl/crypto/pkcs7/p7/smime.p7s | Bin 0 -> 2625 bytes .../openssl/openssl/crypto/pkcs7/pk7_asn1.c | 247 + .../openssl/openssl/crypto/pkcs7/pk7_attr.c | 165 + .../openssl/openssl/crypto/pkcs7/pk7_dgst.c | 66 + .../openssl/openssl/crypto/pkcs7/pk7_doit.c | 1248 ++ .../openssl/openssl/crypto/pkcs7/pk7_enc.c | 76 + .../openssl/openssl/crypto/pkcs7/pk7_lib.c | 665 + .../openssl/openssl/crypto/pkcs7/pk7_mime.c | 97 + .../openssl/openssl/crypto/pkcs7/pk7_smime.c | 587 + .../deps/openssl/openssl/crypto/pkcs7/pkcs7.h | 499 + .../openssl/openssl/crypto/pkcs7/pkcs7err.c | 187 + .../openssl/openssl/crypto/pkcs7/server.pem | 24 + .../deps/openssl/openssl/crypto/pkcs7/sign.c | 154 + .../openssl/openssl/crypto/pkcs7/t/3des.pem | 16 + .../openssl/openssl/crypto/pkcs7/t/3dess.pem | 32 + .../deps/openssl/openssl/crypto/pkcs7/t/c.pem | 48 + .../deps/openssl/openssl/crypto/pkcs7/t/ff | 32 + .../openssl/openssl/crypto/pkcs7/t/msie-e | 20 + .../openssl/openssl/crypto/pkcs7/t/msie-e.pem | 22 + .../openssl/crypto/pkcs7/t/msie-enc-01 | 62 + .../openssl/crypto/pkcs7/t/msie-enc-01.pem | 66 + .../openssl/crypto/pkcs7/t/msie-enc-02 | 90 + .../openssl/crypto/pkcs7/t/msie-enc-02.pem | 106 + .../openssl/openssl/crypto/pkcs7/t/msie-s-a-e | 91 + .../openssl/crypto/pkcs7/t/msie-s-a-e.pem | 106 + .../openssl/openssl/crypto/pkcs7/t/nav-smime | 157 + .../deps/openssl/openssl/crypto/pkcs7/t/s.pem | 57 + .../openssl/openssl/crypto/pkcs7/t/server.pem | 57 + .../openssl/openssl/crypto/pkcs7/verify.c | 263 + .../deps/openssl/openssl/crypto/ppccpuid.pl | 96 + .../openssl/openssl/crypto/pqueue/Makefile | 83 + .../openssl/openssl/crypto/pqueue/pq_test.c | 95 + .../openssl/openssl/crypto/pqueue/pqueue.c | 252 + .../openssl/openssl/crypto/pqueue/pqueue.h | 94 + .../deps/openssl/openssl/crypto/rand/Makefile | 164 + .../openssl/openssl/crypto/rand/md_rand.c | 593 + .../deps/openssl/openssl/crypto/rand/rand.h | 140 + .../openssl/openssl/crypto/rand/rand_egd.c | 303 + .../openssl/openssl/crypto/rand/rand_err.c | 96 + .../openssl/openssl/crypto/rand/rand_lcl.h | 158 + .../openssl/openssl/crypto/rand/rand_lib.c | 176 + .../openssl/openssl/crypto/rand/rand_nw.c | 183 + .../openssl/openssl/crypto/rand/rand_os2.c | 153 + .../openssl/openssl/crypto/rand/rand_unix.c | 431 + .../openssl/openssl/crypto/rand/rand_vms.c | 148 + .../openssl/openssl/crypto/rand/rand_win.c | 807 ++ .../openssl/openssl/crypto/rand/randfile.c | 326 + .../openssl/openssl/crypto/rand/randtest.c | 219 + .../deps/openssl/openssl/crypto/rc2/Makefile | 86 + .../deps/openssl/openssl/crypto/rc2/rc2.h | 101 + .../deps/openssl/openssl/crypto/rc2/rc2_cbc.c | 226 + .../deps/openssl/openssl/crypto/rc2/rc2_ecb.c | 88 + .../openssl/openssl/crypto/rc2/rc2_locl.h | 156 + .../openssl/openssl/crypto/rc2/rc2_skey.c | 145 + .../openssl/openssl/crypto/rc2/rc2cfb64.c | 122 + .../openssl/openssl/crypto/rc2/rc2ofb64.c | 111 + .../openssl/openssl/crypto/rc2/rc2speed.c | 277 + .../deps/openssl/openssl/crypto/rc2/rc2test.c | 274 + .../deps/openssl/openssl/crypto/rc2/rrc2.doc | 219 + .../deps/openssl/openssl/crypto/rc2/tab.c | 86 + .../deps/openssl/openssl/crypto/rc2/version | 22 + .../deps/openssl/openssl/crypto/rc4/Makefile | 115 + .../openssl/openssl/crypto/rc4/asm/rc4-586.pl | 270 + .../openssl/crypto/rc4/asm/rc4-ia64.pl | 755 + .../openssl/crypto/rc4/asm/rc4-s390x.pl | 205 + .../openssl/crypto/rc4/asm/rc4-x86_64.pl | 504 + .../deps/openssl/openssl/crypto/rc4/rc4.c | 193 + .../deps/openssl/openssl/crypto/rc4/rc4.h | 89 + .../deps/openssl/openssl/crypto/rc4/rc4_enc.c | 315 + .../openssl/openssl/crypto/rc4/rc4_locl.h | 5 + .../openssl/openssl/crypto/rc4/rc4_skey.c | 150 + .../deps/openssl/openssl/crypto/rc4/rc4s.cpp | 73 + .../openssl/openssl/crypto/rc4/rc4speed.c | 253 + .../deps/openssl/openssl/crypto/rc4/rc4test.c | 236 + .../deps/openssl/openssl/crypto/rc4/rrc4.doc | 278 + .../deps/openssl/openssl/crypto/rc5/Makefile | 94 + .../openssl/openssl/crypto/rc5/asm/rc5-586.pl | 110 + .../deps/openssl/openssl/crypto/rc5/rc5.h | 118 + .../deps/openssl/openssl/crypto/rc5/rc5_ecb.c | 80 + .../deps/openssl/openssl/crypto/rc5/rc5_enc.c | 215 + .../openssl/openssl/crypto/rc5/rc5_locl.h | 207 + .../openssl/openssl/crypto/rc5/rc5_skey.c | 113 + .../openssl/openssl/crypto/rc5/rc5cfb64.c | 122 + .../openssl/openssl/crypto/rc5/rc5ofb64.c | 111 + .../deps/openssl/openssl/crypto/rc5/rc5s.cpp | 70 + .../openssl/openssl/crypto/rc5/rc5speed.c | 277 + .../deps/openssl/openssl/crypto/rc5/rc5test.c | 386 + .../openssl/openssl/crypto/ripemd/Makefile | 92 + .../deps/openssl/openssl/crypto/ripemd/README | 15 + .../openssl/crypto/ripemd/asm/rips.cpp | 82 + .../openssl/crypto/ripemd/asm/rmd-586.pl | 591 + .../openssl/openssl/crypto/ripemd/ripemd.h | 104 + .../openssl/openssl/crypto/ripemd/rmd160.c | 127 + .../openssl/openssl/crypto/ripemd/rmd_dgst.c | 291 + .../openssl/openssl/crypto/ripemd/rmd_locl.h | 150 + .../openssl/openssl/crypto/ripemd/rmd_one.c | 78 + .../openssl/openssl/crypto/ripemd/rmdconst.h | 399 + .../openssl/openssl/crypto/ripemd/rmdtest.c | 145 + .../deps/openssl/openssl/crypto/rsa/Makefile | 287 + .../deps/openssl/openssl/crypto/rsa/rsa.h | 503 + .../openssl/openssl/crypto/rsa/rsa_ameth.c | 349 + .../openssl/openssl/crypto/rsa/rsa_asn1.c | 111 + .../deps/openssl/openssl/crypto/rsa/rsa_chk.c | 184 + .../openssl/openssl/crypto/rsa/rsa_depr.c | 101 + .../deps/openssl/openssl/crypto/rsa/rsa_eay.c | 915 ++ .../deps/openssl/openssl/crypto/rsa/rsa_err.c | 190 + .../deps/openssl/openssl/crypto/rsa/rsa_gen.c | 219 + .../deps/openssl/openssl/crypto/rsa/rsa_lib.c | 483 + .../openssl/openssl/crypto/rsa/rsa_locl.h | 4 + .../openssl/openssl/crypto/rsa/rsa_none.c | 98 + .../openssl/openssl/crypto/rsa/rsa_null.c | 151 + .../openssl/openssl/crypto/rsa/rsa_oaep.c | 233 + .../deps/openssl/openssl/crypto/rsa/rsa_pk1.c | 224 + .../openssl/openssl/crypto/rsa/rsa_pmeth.c | 587 + .../deps/openssl/openssl/crypto/rsa/rsa_prn.c | 93 + .../deps/openssl/openssl/crypto/rsa/rsa_pss.c | 275 + .../openssl/openssl/crypto/rsa/rsa_saos.c | 150 + .../openssl/openssl/crypto/rsa/rsa_sign.c | 285 + .../deps/openssl/openssl/crypto/rsa/rsa_ssl.c | 154 + .../openssl/openssl/crypto/rsa/rsa_test.c | 340 + .../openssl/openssl/crypto/rsa/rsa_x931.c | 177 + .../deps/openssl/openssl/crypto/s390xcap.c | 37 + .../deps/openssl/openssl/crypto/s390xcpuid.S | 92 + .../deps/openssl/openssl/crypto/seed/Makefile | 106 + .../deps/openssl/openssl/crypto/seed/seed.c | 325 + .../deps/openssl/openssl/crypto/seed/seed.h | 137 + .../openssl/openssl/crypto/seed/seed_cbc.c | 63 + .../openssl/openssl/crypto/seed/seed_cfb.c | 116 + .../openssl/openssl/crypto/seed/seed_ecb.c | 60 + .../openssl/openssl/crypto/seed/seed_locl.h | 116 + .../openssl/openssl/crypto/seed/seed_ofb.c | 116 + .../deps/openssl/openssl/crypto/sha/Makefile | 145 + .../openssl/openssl/crypto/sha/asm/README | 1 + .../openssl/crypto/sha/asm/sha1-586.pl | 220 + .../crypto/sha/asm/sha1-armv4-large.pl | 229 + .../openssl/crypto/sha/asm/sha1-ia64.pl | 306 + .../openssl/crypto/sha/asm/sha1-ppc.pl | 319 + .../openssl/crypto/sha/asm/sha1-s390x.pl | 226 + .../openssl/crypto/sha/asm/sha1-sparcv9.pl | 284 + .../openssl/crypto/sha/asm/sha1-sparcv9a.pl | 601 + .../openssl/crypto/sha/asm/sha1-thumb.pl | 259 + .../openssl/crypto/sha/asm/sha1-x86_64.pl | 351 + .../openssl/crypto/sha/asm/sha256-586.pl | 251 + .../openssl/crypto/sha/asm/sha256-armv4.pl | 186 + .../openssl/crypto/sha/asm/sha512-586.pl | 644 + .../openssl/crypto/sha/asm/sha512-armv4.pl | 403 + .../openssl/crypto/sha/asm/sha512-ia64.pl | 672 + .../openssl/crypto/sha/asm/sha512-ppc.pl | 462 + .../openssl/crypto/sha/asm/sha512-s390x.pl | 301 + .../openssl/crypto/sha/asm/sha512-sparcv9.pl | 594 + .../openssl/crypto/sha/asm/sha512-x86_64.pl | 456 + .../deps/openssl/openssl/crypto/sha/sha.c | 124 + .../deps/openssl/openssl/crypto/sha/sha.h | 200 + .../deps/openssl/openssl/crypto/sha/sha1.c | 127 + .../openssl/openssl/crypto/sha/sha1_one.c | 78 + .../openssl/openssl/crypto/sha/sha1dgst.c | 74 + .../openssl/openssl/crypto/sha/sha1test.c | 178 + .../deps/openssl/openssl/crypto/sha/sha256.c | 282 + .../deps/openssl/openssl/crypto/sha/sha256t.c | 147 + .../deps/openssl/openssl/crypto/sha/sha512.c | 641 + .../deps/openssl/openssl/crypto/sha/sha512t.c | 184 + .../openssl/openssl/crypto/sha/sha_dgst.c | 74 + .../openssl/openssl/crypto/sha/sha_locl.h | 437 + .../deps/openssl/openssl/crypto/sha/sha_one.c | 78 + .../deps/openssl/openssl/crypto/sha/shatest.c | 178 + .../deps/openssl/openssl/crypto/sparccpuid.S | 402 + .../deps/openssl/openssl/crypto/sparcv9cap.c | 237 + .../openssl/openssl/crypto/stack/Makefile | 84 + .../openssl/openssl/crypto/stack/safestack.h | 2575 ++++ .../deps/openssl/openssl/crypto/stack/stack.c | 334 + .../deps/openssl/openssl/crypto/stack/stack.h | 108 + .../openssl/openssl/crypto/store/Makefile | 112 + .../deps/openssl/openssl/crypto/store/README | 95 + .../deps/openssl/openssl/crypto/store/store.h | 561 + .../openssl/openssl/crypto/store/str_err.c | 211 + .../openssl/openssl/crypto/store/str_lib.c | 1828 +++ .../openssl/openssl/crypto/store/str_locl.h | 124 + .../openssl/openssl/crypto/store/str_mem.c | 365 + .../openssl/openssl/crypto/store/str_meth.c | 250 + .../deps/openssl/openssl/crypto/symhacks.h | 449 + .../openssl/openssl/crypto/threads/README | 14 + .../openssl/openssl/crypto/threads/mttest.c | 1310 ++ .../openssl/crypto/threads/netware.bat | 79 + .../openssl/openssl/crypto/threads/profile.sh | 4 + .../openssl/openssl/crypto/threads/ptest.bat | 4 + .../openssl/openssl/crypto/threads/pthread.sh | 9 + .../openssl/crypto/threads/pthread2.sh | 7 + .../openssl/crypto/threads/pthreads-vms.com | 14 + .../openssl/openssl/crypto/threads/purify.sh | 4 + .../openssl/openssl/crypto/threads/solaris.sh | 4 + .../openssl/openssl/crypto/threads/th-lock.c | 387 + .../openssl/openssl/crypto/threads/win32.bat | 4 + .../deps/openssl/openssl/crypto/ts/Makefile | 269 + .../deps/openssl/openssl/crypto/ts/ts.h | 861 ++ .../deps/openssl/openssl/crypto/ts/ts_asn1.c | 322 + .../deps/openssl/openssl/crypto/ts/ts_conf.c | 507 + .../deps/openssl/openssl/crypto/ts/ts_err.c | 179 + .../deps/openssl/openssl/crypto/ts/ts_lib.c | 145 + .../openssl/openssl/crypto/ts/ts_req_print.c | 102 + .../openssl/openssl/crypto/ts/ts_req_utils.c | 234 + .../openssl/openssl/crypto/ts/ts_rsp_print.c | 287 + .../openssl/openssl/crypto/ts/ts_rsp_sign.c | 1020 ++ .../openssl/openssl/crypto/ts/ts_rsp_utils.c | 409 + .../openssl/openssl/crypto/ts/ts_rsp_verify.c | 725 + .../openssl/openssl/crypto/ts/ts_verify_ctx.c | 159 + .../openssl/openssl/crypto/txt_db/Makefile | 84 + .../openssl/openssl/crypto/txt_db/txt_db.c | 388 + .../openssl/openssl/crypto/txt_db/txt_db.h | 112 + .../deps/openssl/openssl/crypto/ui/Makefile | 111 + .../deps/openssl/openssl/crypto/ui/ui.h | 383 + .../openssl/openssl/crypto/ui/ui_compat.c | 67 + .../openssl/openssl/crypto/ui/ui_compat.h | 83 + .../deps/openssl/openssl/crypto/ui/ui_err.c | 112 + .../deps/openssl/openssl/crypto/ui/ui_lib.c | 924 ++ .../deps/openssl/openssl/crypto/ui/ui_locl.h | 153 + .../openssl/openssl/crypto/ui/ui_openssl.c | 712 + .../deps/openssl/openssl/crypto/ui/ui_util.c | 91 + .../deps/openssl/openssl/crypto/uid.c | 89 + .../deps/openssl/openssl/crypto/vms_rms.h | 51 + .../openssl/openssl/crypto/whrlpool/Makefile | 93 + .../openssl/crypto/whrlpool/asm/wp-mmx.pl | 493 + .../openssl/crypto/whrlpool/asm/wp-x86_64.pl | 589 + .../openssl/crypto/whrlpool/whrlpool.h | 38 + .../openssl/crypto/whrlpool/wp_block.c | 655 + .../openssl/openssl/crypto/whrlpool/wp_dgst.c | 264 + .../openssl/openssl/crypto/whrlpool/wp_locl.h | 3 + .../openssl/openssl/crypto/whrlpool/wp_test.c | 228 + .../deps/openssl/openssl/crypto/x509/Makefile | 407 + .../deps/openssl/openssl/crypto/x509/by_dir.c | 490 + .../openssl/openssl/crypto/x509/by_file.c | 300 + .../deps/openssl/openssl/crypto/x509/x509.h | 1286 ++ .../openssl/openssl/crypto/x509/x509_att.c | 359 + .../openssl/openssl/crypto/x509/x509_cmp.c | 331 + .../openssl/openssl/crypto/x509/x509_d2.c | 107 + .../openssl/openssl/crypto/x509/x509_def.c | 81 + .../openssl/openssl/crypto/x509/x509_err.c | 164 + .../openssl/openssl/crypto/x509/x509_ext.c | 210 + .../openssl/openssl/crypto/x509/x509_lu.c | 716 + .../openssl/openssl/crypto/x509/x509_obj.c | 226 + .../openssl/openssl/crypto/x509/x509_r2x.c | 114 + .../openssl/openssl/crypto/x509/x509_req.c | 316 + .../openssl/openssl/crypto/x509/x509_set.c | 150 + .../openssl/openssl/crypto/x509/x509_trs.c | 288 + .../openssl/openssl/crypto/x509/x509_txt.c | 193 + .../openssl/openssl/crypto/x509/x509_v3.c | 274 + .../openssl/openssl/crypto/x509/x509_vfy.c | 2219 +++ .../openssl/openssl/crypto/x509/x509_vfy.h | 567 + .../openssl/openssl/crypto/x509/x509_vpm.c | 438 + .../openssl/openssl/crypto/x509/x509cset.c | 170 + .../openssl/openssl/crypto/x509/x509name.c | 383 + .../openssl/openssl/crypto/x509/x509rset.c | 83 + .../openssl/openssl/crypto/x509/x509spki.c | 121 + .../openssl/openssl/crypto/x509/x509type.c | 125 + .../deps/openssl/openssl/crypto/x509/x_all.c | 516 + .../openssl/openssl/crypto/x509v3/Makefile | 591 + .../openssl/openssl/crypto/x509v3/ext_dat.h | 132 + .../openssl/openssl/crypto/x509v3/pcy_cache.c | 286 + .../openssl/openssl/crypto/x509v3/pcy_data.c | 135 + .../openssl/openssl/crypto/x509v3/pcy_int.h | 212 + .../openssl/openssl/crypto/x509v3/pcy_lib.c | 167 + .../openssl/openssl/crypto/x509v3/pcy_map.c | 132 + .../openssl/openssl/crypto/x509v3/pcy_node.c | 197 + .../openssl/openssl/crypto/x509v3/pcy_tree.c | 872 ++ .../openssl/openssl/crypto/x509v3/tabtest.c | 88 + .../openssl/openssl/crypto/x509v3/v3_addr.c | 1338 ++ .../openssl/openssl/crypto/x509v3/v3_akey.c | 208 + .../openssl/openssl/crypto/x509v3/v3_akeya.c | 72 + .../openssl/openssl/crypto/x509v3/v3_alt.c | 614 + .../openssl/openssl/crypto/x509v3/v3_asid.c | 843 ++ .../openssl/openssl/crypto/x509v3/v3_bcons.c | 124 + .../openssl/openssl/crypto/x509v3/v3_bitst.c | 141 + .../openssl/openssl/crypto/x509v3/v3_conf.c | 525 + .../openssl/openssl/crypto/x509v3/v3_cpols.c | 457 + .../openssl/openssl/crypto/x509v3/v3_crld.c | 616 + .../openssl/openssl/crypto/x509v3/v3_enum.c | 97 + .../openssl/openssl/crypto/x509v3/v3_extku.c | 144 + .../openssl/openssl/crypto/x509v3/v3_genn.c | 252 + .../openssl/openssl/crypto/x509v3/v3_ia5.c | 116 + .../openssl/openssl/crypto/x509v3/v3_info.c | 193 + .../openssl/openssl/crypto/x509v3/v3_int.c | 89 + .../openssl/openssl/crypto/x509v3/v3_lib.c | 309 + .../openssl/openssl/crypto/x509v3/v3_ncons.c | 505 + .../openssl/openssl/crypto/x509v3/v3_ocsp.c | 289 + .../openssl/openssl/crypto/x509v3/v3_pci.c | 328 + .../openssl/openssl/crypto/x509v3/v3_pcia.c | 55 + .../openssl/openssl/crypto/x509v3/v3_pcons.c | 140 + .../openssl/openssl/crypto/x509v3/v3_pku.c | 108 + .../openssl/openssl/crypto/x509v3/v3_pmaps.c | 155 + .../openssl/openssl/crypto/x509v3/v3_prn.c | 234 + .../openssl/openssl/crypto/x509v3/v3_purp.c | 767 + .../openssl/openssl/crypto/x509v3/v3_skey.c | 144 + .../openssl/openssl/crypto/x509v3/v3_sxnet.c | 262 + .../openssl/openssl/crypto/x509v3/v3_utl.c | 874 ++ .../openssl/openssl/crypto/x509v3/v3conf.c | 127 + .../openssl/openssl/crypto/x509v3/v3err.c | 226 + .../openssl/openssl/crypto/x509v3/v3prin.c | 99 + .../openssl/openssl/crypto/x509v3/x509v3.h | 1007 ++ .../openssl/openssl/crypto/x86_64cpuid.pl | 232 + .../deps/openssl/openssl/crypto/x86cpuid.pl | 312 + .../deps/openssl/openssl/demos/README | 9 + .../openssl/openssl/demos/asn1/README.ASN1 | 7 + .../deps/openssl/openssl/demos/asn1/ocsp.c | 366 + node-v0.8.14/deps/openssl/openssl/demos/b64.c | 268 + .../deps/openssl/openssl/demos/b64.pl | 20 + .../deps/openssl/openssl/demos/bio/Makefile | 16 + .../deps/openssl/openssl/demos/bio/README | 3 + .../deps/openssl/openssl/demos/bio/saccept.c | 112 + .../deps/openssl/openssl/demos/bio/sconnect.c | 121 + .../deps/openssl/openssl/demos/bio/server.pem | 30 + .../deps/openssl/openssl/demos/cms/cacert.pem | 18 + .../deps/openssl/openssl/demos/cms/cakey.pem | 15 + .../deps/openssl/openssl/demos/cms/cms_comp.c | 61 + .../deps/openssl/openssl/demos/cms/cms_ddec.c | 89 + .../deps/openssl/openssl/demos/cms/cms_dec.c | 79 + .../deps/openssl/openssl/demos/cms/cms_denc.c | 97 + .../deps/openssl/openssl/demos/cms/cms_enc.c | 92 + .../deps/openssl/openssl/demos/cms/cms_sign.c | 89 + .../openssl/openssl/demos/cms/cms_sign2.c | 103 + .../openssl/openssl/demos/cms/cms_uncomp.c | 56 + .../deps/openssl/openssl/demos/cms/cms_ver.c | 87 + .../deps/openssl/openssl/demos/cms/comp.txt | 22 + .../deps/openssl/openssl/demos/cms/encr.txt | 3 + .../deps/openssl/openssl/demos/cms/sign.txt | 3 + .../deps/openssl/openssl/demos/cms/signer.pem | 32 + .../openssl/openssl/demos/cms/signer2.pem | 32 + .../openssl/openssl/demos/easy_tls/Makefile | 123 + .../openssl/openssl/demos/easy_tls/README | 65 + .../openssl/demos/easy_tls/cacerts.pem | 18 + .../openssl/openssl/demos/easy_tls/cert.pem | 31 + .../openssl/openssl/demos/easy_tls/easy-tls.c | 1240 ++ .../openssl/openssl/demos/easy_tls/easy-tls.h | 57 + .../openssl/openssl/demos/easy_tls/test.c | 244 + .../openssl/openssl/demos/easy_tls/test.h | 11 + .../deps/openssl/openssl/demos/eay/Makefile | 24 + .../deps/openssl/openssl/demos/eay/base64.c | 49 + .../deps/openssl/openssl/demos/eay/conn.c | 105 + .../deps/openssl/openssl/demos/eay/loadrsa.c | 53 + .../demos/engines/cluster_labs/Makefile | 114 + .../demos/engines/cluster_labs/cluster_labs.h | 35 + .../engines/cluster_labs/hw_cluster_labs.c | 721 + .../engines/cluster_labs/hw_cluster_labs.ec | 8 + .../cluster_labs/hw_cluster_labs_err.c | 151 + .../cluster_labs/hw_cluster_labs_err.h | 99 + .../openssl/demos/engines/ibmca/Makefile | 114 + .../openssl/demos/engines/ibmca/hw_ibmca.c | 920 ++ .../openssl/demos/engines/ibmca/hw_ibmca.ec | 8 + .../demos/engines/ibmca/hw_ibmca_err.c | 154 + .../demos/engines/ibmca/hw_ibmca_err.h | 102 + .../demos/engines/ibmca/ica_openssl_api.h | 189 + .../openssl/demos/engines/rsaref/Makefile | 135 + .../openssl/demos/engines/rsaref/README | 22 + .../openssl/demos/engines/rsaref/build.com | 105 + .../openssl/demos/engines/rsaref/rsaref.c | 685 + .../openssl/demos/engines/rsaref/rsaref.ec | 8 + .../openssl/demos/engines/rsaref/rsaref_err.c | 161 + .../openssl/demos/engines/rsaref/rsaref_err.h | 109 + .../openssl/demos/engines/zencod/Makefile | 114 + .../openssl/demos/engines/zencod/hw_zencod.c | 1739 +++ .../openssl/demos/engines/zencod/hw_zencod.ec | 8 + .../openssl/demos/engines/zencod/hw_zencod.h | 160 + .../demos/engines/zencod/hw_zencod_err.c | 151 + .../demos/engines/zencod/hw_zencod_err.h | 99 + .../openssl/openssl/demos/maurice/Makefile | 59 + .../deps/openssl/openssl/demos/maurice/README | 34 + .../openssl/openssl/demos/maurice/cert.pem | 77 + .../openssl/openssl/demos/maurice/example1.c | 198 + .../openssl/openssl/demos/maurice/example2.c | 75 + .../openssl/openssl/demos/maurice/example3.c | 87 + .../openssl/openssl/demos/maurice/example4.c | 123 + .../openssl/openssl/demos/maurice/loadkeys.c | 72 + .../openssl/openssl/demos/maurice/loadkeys.h | 19 + .../openssl/openssl/demos/maurice/privkey.pem | 27 + .../deps/openssl/openssl/demos/pkcs12/README | 3 + .../openssl/openssl/demos/pkcs12/pkread.c | 61 + .../openssl/openssl/demos/pkcs12/pkwrite.c | 46 + .../deps/openssl/openssl/demos/prime/Makefile | 20 + .../deps/openssl/openssl/demos/prime/prime.c | 101 + .../deps/openssl/openssl/demos/privkey.pem | 9 + .../deps/openssl/openssl/demos/selfsign.c | 180 + .../deps/openssl/openssl/demos/sign/Makefile | 15 + .../deps/openssl/openssl/demos/sign/cert.pem | 14 + .../deps/openssl/openssl/demos/sign/key.pem | 9 + .../deps/openssl/openssl/demos/sign/sig.txt | 158 + .../deps/openssl/openssl/demos/sign/sign.c | 153 + .../deps/openssl/openssl/demos/sign/sign.txt | 170 + .../openssl/openssl/demos/smime/cacert.pem | 18 + .../openssl/openssl/demos/smime/cakey.pem | 15 + .../deps/openssl/openssl/demos/smime/encr.txt | 3 + .../deps/openssl/openssl/demos/smime/sign.txt | 3 + .../openssl/openssl/demos/smime/signer.pem | 32 + .../openssl/openssl/demos/smime/signer2.pem | 32 + .../deps/openssl/openssl/demos/smime/smdec.c | 83 + .../deps/openssl/openssl/demos/smime/smenc.c | 92 + .../deps/openssl/openssl/demos/smime/smsign.c | 89 + .../openssl/openssl/demos/smime/smsign2.c | 107 + .../deps/openssl/openssl/demos/smime/smver.c | 87 + .../deps/openssl/openssl/demos/spkigen.c | 161 + .../deps/openssl/openssl/demos/ssl/cli.cpp | 110 + .../openssl/openssl/demos/ssl/inetdsrv.cpp | 98 + .../deps/openssl/openssl/demos/ssl/serv.cpp | 152 + .../demos/ssltest-ecc/ECC-RSAcertgen.sh | 98 + .../openssl/demos/ssltest-ecc/ECCcertgen.sh | 164 + .../openssl/openssl/demos/ssltest-ecc/README | 15 + .../openssl/demos/ssltest-ecc/RSAcertgen.sh | 121 + .../openssl/demos/ssltest-ecc/ssltest.sh | 188 + .../openssl/demos/state_machine/Makefile | 9 + .../demos/state_machine/state_machine.c | 416 + .../openssl/openssl/demos/tunala/A-client.pem | 84 + .../openssl/openssl/demos/tunala/A-server.pem | 84 + .../deps/openssl/openssl/demos/tunala/CA.pem | 24 + .../deps/openssl/openssl/demos/tunala/INSTALL | 107 + .../openssl/openssl/demos/tunala/Makefile | 41 + .../openssl/openssl/demos/tunala/Makefile.am | 7 + .../deps/openssl/openssl/demos/tunala/README | 233 + .../openssl/openssl/demos/tunala/autogunk.sh | 25 + .../openssl/demos/tunala/autoungunk.sh | 19 + .../openssl/openssl/demos/tunala/breakage.c | 66 + .../openssl/openssl/demos/tunala/buffer.c | 205 + .../deps/openssl/openssl/demos/tunala/cb.c | 162 + .../openssl/openssl/demos/tunala/configure.in | 29 + .../deps/openssl/openssl/demos/tunala/ip.c | 146 + .../deps/openssl/openssl/demos/tunala/sm.c | 151 + .../deps/openssl/openssl/demos/tunala/test.sh | 107 + .../openssl/openssl/demos/tunala/tunala.c | 1109 ++ .../openssl/openssl/demos/tunala/tunala.h | 215 + .../deps/openssl/openssl/demos/x509/README | 3 + .../deps/openssl/openssl/demos/x509/mkcert.c | 172 + .../deps/openssl/openssl/demos/x509/mkreq.c | 161 + .../openssl/doc/HOWTO/certificates.txt | 105 + .../deps/openssl/openssl/doc/HOWTO/keys.txt | 73 + .../openssl/doc/HOWTO/proxy_certificates.txt | 322 + node-v0.8.14/deps/openssl/openssl/doc/README | 12 + .../deps/openssl/openssl/doc/apps/CA.pl.pod | 179 + .../openssl/openssl/doc/apps/asn1parse.pod | 175 + .../deps/openssl/openssl/doc/apps/ca.pod | 675 + .../deps/openssl/openssl/doc/apps/ciphers.pod | 478 + .../deps/openssl/openssl/doc/apps/cms.pod | 602 + .../deps/openssl/openssl/doc/apps/config.pod | 279 + .../deps/openssl/openssl/doc/apps/crl.pod | 117 + .../openssl/openssl/doc/apps/crl2pkcs7.pod | 91 + .../deps/openssl/openssl/doc/apps/dgst.pod | 162 + .../deps/openssl/openssl/doc/apps/dhparam.pod | 141 + .../deps/openssl/openssl/doc/apps/dsa.pod | 158 + .../openssl/openssl/doc/apps/dsaparam.pod | 110 + .../deps/openssl/openssl/doc/apps/ec.pod | 190 + .../deps/openssl/openssl/doc/apps/ecparam.pod | 179 + .../deps/openssl/openssl/doc/apps/enc.pod | 329 + .../deps/openssl/openssl/doc/apps/errstr.pod | 39 + .../deps/openssl/openssl/doc/apps/gendsa.pod | 66 + .../deps/openssl/openssl/doc/apps/genpkey.pod | 213 + .../deps/openssl/openssl/doc/apps/genrsa.pod | 96 + .../deps/openssl/openssl/doc/apps/nseq.pod | 70 + .../deps/openssl/openssl/doc/apps/ocsp.pod | 371 + .../deps/openssl/openssl/doc/apps/openssl.pod | 422 + .../deps/openssl/openssl/doc/apps/passwd.pod | 82 + .../deps/openssl/openssl/doc/apps/pkcs12.pod | 363 + .../deps/openssl/openssl/doc/apps/pkcs7.pod | 105 + .../deps/openssl/openssl/doc/apps/pkcs8.pod | 243 + .../deps/openssl/openssl/doc/apps/pkey.pod | 135 + .../openssl/openssl/doc/apps/pkeyparam.pod | 69 + .../deps/openssl/openssl/doc/apps/pkeyutl.pod | 222 + .../deps/openssl/openssl/doc/apps/rand.pod | 55 + .../deps/openssl/openssl/doc/apps/req.pod | 678 + .../deps/openssl/openssl/doc/apps/rsa.pod | 189 + .../deps/openssl/openssl/doc/apps/rsautl.pod | 183 + .../openssl/openssl/doc/apps/s_client.pod | 306 + .../openssl/openssl/doc/apps/s_server.pod | 355 + .../deps/openssl/openssl/doc/apps/s_time.pod | 173 + .../deps/openssl/openssl/doc/apps/sess_id.pod | 151 + .../deps/openssl/openssl/doc/apps/smime.pod | 445 + .../deps/openssl/openssl/doc/apps/speed.pod | 59 + .../deps/openssl/openssl/doc/apps/spkac.pod | 133 + .../deps/openssl/openssl/doc/apps/ts.pod | 594 + .../deps/openssl/openssl/doc/apps/tsget.pod | 194 + .../deps/openssl/openssl/doc/apps/verify.pod | 406 + .../deps/openssl/openssl/doc/apps/version.pod | 64 + .../deps/openssl/openssl/doc/apps/x509.pod | 856 ++ .../openssl/doc/apps/x509v3_config.pod | 529 + .../deps/openssl/openssl/doc/c-indentation.el | 45 + .../openssl/doc/crypto/ASN1_OBJECT_new.pod | 45 + .../openssl/doc/crypto/ASN1_STRING_length.pod | 83 + .../openssl/doc/crypto/ASN1_STRING_new.pod | 46 + .../doc/crypto/ASN1_STRING_print_ex.pod | 96 + .../doc/crypto/ASN1_generate_nconf.pod | 265 + .../openssl/openssl/doc/crypto/BIO_ctrl.pod | 128 + .../openssl/doc/crypto/BIO_f_base64.pod | 81 + .../openssl/doc/crypto/BIO_f_buffer.pod | 74 + .../openssl/doc/crypto/BIO_f_cipher.pod | 76 + .../openssl/openssl/doc/crypto/BIO_f_md.pod | 144 + .../openssl/openssl/doc/crypto/BIO_f_null.pod | 32 + .../openssl/openssl/doc/crypto/BIO_f_ssl.pod | 322 + .../openssl/doc/crypto/BIO_find_type.pod | 98 + .../openssl/openssl/doc/crypto/BIO_new.pod | 65 + .../openssl/doc/crypto/BIO_new_CMS.pod | 66 + .../openssl/openssl/doc/crypto/BIO_push.pod | 69 + .../openssl/openssl/doc/crypto/BIO_read.pod | 66 + .../openssl/doc/crypto/BIO_s_accept.pod | 195 + .../openssl/openssl/doc/crypto/BIO_s_bio.pod | 182 + .../openssl/doc/crypto/BIO_s_connect.pod | 192 + .../openssl/openssl/doc/crypto/BIO_s_fd.pod | 89 + .../openssl/openssl/doc/crypto/BIO_s_file.pod | 148 + .../openssl/openssl/doc/crypto/BIO_s_mem.pod | 115 + .../openssl/openssl/doc/crypto/BIO_s_null.pod | 37 + .../openssl/doc/crypto/BIO_s_socket.pod | 63 + .../openssl/doc/crypto/BIO_set_callback.pod | 108 + .../openssl/doc/crypto/BIO_should_retry.pod | 114 + .../openssl/doc/crypto/BN_BLINDING_new.pod | 115 + .../openssl/openssl/doc/crypto/BN_CTX_new.pod | 53 + .../openssl/doc/crypto/BN_CTX_start.pod | 52 + .../openssl/openssl/doc/crypto/BN_add.pod | 126 + .../openssl/doc/crypto/BN_add_word.pod | 61 + .../openssl/openssl/doc/crypto/BN_bn2bin.pod | 95 + .../openssl/openssl/doc/crypto/BN_cmp.pod | 48 + .../openssl/openssl/doc/crypto/BN_copy.pod | 34 + .../openssl/doc/crypto/BN_generate_prime.pod | 102 + .../openssl/doc/crypto/BN_mod_inverse.pod | 36 + .../doc/crypto/BN_mod_mul_montgomery.pod | 101 + .../doc/crypto/BN_mod_mul_reciprocal.pod | 81 + .../openssl/openssl/doc/crypto/BN_new.pod | 53 + .../openssl/doc/crypto/BN_num_bytes.pod | 57 + .../openssl/openssl/doc/crypto/BN_rand.pod | 58 + .../openssl/openssl/doc/crypto/BN_set_bit.pod | 66 + .../openssl/openssl/doc/crypto/BN_swap.pod | 23 + .../openssl/openssl/doc/crypto/BN_zero.pod | 59 + .../openssl/doc/crypto/CMS_add0_cert.pod | 66 + .../doc/crypto/CMS_add1_recipient_cert.pod | 62 + .../openssl/doc/crypto/CMS_compress.pod | 73 + .../openssl/doc/crypto/CMS_decrypt.pod | 65 + .../openssl/doc/crypto/CMS_encrypt.pod | 96 + .../openssl/openssl/doc/crypto/CMS_final.pod | 41 + .../doc/crypto/CMS_get0_RecipientInfos.pod | 106 + .../doc/crypto/CMS_get0_SignerInfos.pod | 75 + .../openssl/doc/crypto/CMS_get0_type.pod | 63 + .../doc/crypto/CMS_get1_ReceiptRequest.pod | 69 + .../openssl/openssl/doc/crypto/CMS_sign.pod | 121 + .../doc/crypto/CMS_sign_add1_signer.pod | 101 + .../openssl/doc/crypto/CMS_sign_receipt.pod | 45 + .../openssl/doc/crypto/CMS_uncompress.pod | 54 + .../openssl/openssl/doc/crypto/CMS_verify.pod | 126 + .../openssl/doc/crypto/CMS_verify_receipt.pod | 47 + .../openssl/doc/crypto/CONF_modules_free.pod | 47 + .../doc/crypto/CONF_modules_load_file.pod | 60 + .../openssl/doc/crypto/CRYPTO_set_ex_data.pod | 53 + .../openssl/doc/crypto/DH_generate_key.pod | 50 + .../doc/crypto/DH_generate_parameters.pod | 73 + .../doc/crypto/DH_get_ex_new_index.pod | 36 + .../openssl/openssl/doc/crypto/DH_new.pod | 40 + .../openssl/doc/crypto/DH_set_method.pod | 129 + .../openssl/openssl/doc/crypto/DH_size.pod | 33 + .../openssl/doc/crypto/DSA_SIG_new.pod | 40 + .../openssl/doc/crypto/DSA_do_sign.pod | 47 + .../openssl/openssl/doc/crypto/DSA_dup_DH.pod | 36 + .../openssl/doc/crypto/DSA_generate_key.pod | 34 + .../doc/crypto/DSA_generate_parameters.pod | 105 + .../doc/crypto/DSA_get_ex_new_index.pod | 36 + .../openssl/openssl/doc/crypto/DSA_new.pod | 42 + .../openssl/doc/crypto/DSA_set_method.pod | 143 + .../openssl/openssl/doc/crypto/DSA_sign.pod | 66 + .../openssl/openssl/doc/crypto/DSA_size.pod | 33 + .../openssl/doc/crypto/ERR_GET_LIB.pod | 51 + .../openssl/doc/crypto/ERR_clear_error.pod | 29 + .../openssl/doc/crypto/ERR_error_string.pod | 73 + .../openssl/doc/crypto/ERR_get_error.pod | 76 + .../doc/crypto/ERR_load_crypto_strings.pod | 46 + .../openssl/doc/crypto/ERR_load_strings.pod | 54 + .../openssl/doc/crypto/ERR_print_errors.pod | 51 + .../openssl/doc/crypto/ERR_put_error.pod | 44 + .../openssl/doc/crypto/ERR_remove_state.pod | 34 + .../openssl/doc/crypto/ERR_set_mark.pod | 38 + .../openssl/doc/crypto/EVP_BytesToKey.pod | 67 + .../openssl/doc/crypto/EVP_DigestInit.pod | 259 + .../openssl/doc/crypto/EVP_DigestSignInit.pod | 87 + .../doc/crypto/EVP_DigestVerifyInit.pod | 82 + .../openssl/doc/crypto/EVP_EncryptInit.pod | 511 + .../openssl/doc/crypto/EVP_OpenInit.pod | 63 + .../openssl/doc/crypto/EVP_PKEY_CTX_ctrl.pod | 128 + .../openssl/doc/crypto/EVP_PKEY_CTX_new.pod | 52 + .../openssl/doc/crypto/EVP_PKEY_cmp.pod | 61 + .../openssl/doc/crypto/EVP_PKEY_decrypt.pod | 93 + .../openssl/doc/crypto/EVP_PKEY_derive.pod | 93 + .../openssl/doc/crypto/EVP_PKEY_encrypt.pod | 93 + .../crypto/EVP_PKEY_get_default_digest.pod | 41 + .../openssl/doc/crypto/EVP_PKEY_keygen.pod | 161 + .../openssl/doc/crypto/EVP_PKEY_new.pod | 47 + .../doc/crypto/EVP_PKEY_print_private.pod | 53 + .../openssl/doc/crypto/EVP_PKEY_set1_RSA.pod | 80 + .../openssl/doc/crypto/EVP_PKEY_sign.pod | 96 + .../openssl/doc/crypto/EVP_PKEY_verify.pod | 91 + .../doc/crypto/EVP_PKEY_verifyrecover.pod | 103 + .../openssl/doc/crypto/EVP_SealInit.pod | 85 + .../openssl/doc/crypto/EVP_SignInit.pod | 104 + .../openssl/doc/crypto/EVP_VerifyInit.pod | 95 + .../openssl/doc/crypto/OBJ_nid2obj.pod | 151 + .../openssl/doc/crypto/OPENSSL_Applink.pod | 21 + .../doc/crypto/OPENSSL_VERSION_NUMBER.pod | 101 + .../openssl/doc/crypto/OPENSSL_config.pod | 82 + .../openssl/doc/crypto/OPENSSL_ia32cap.pod | 43 + .../crypto/OPENSSL_load_builtin_modules.pod | 51 + .../doc/crypto/OpenSSL_add_all_algorithms.pod | 66 + .../doc/crypto/PEM_write_bio_CMS_stream.pod | 41 + .../doc/crypto/PEM_write_bio_PKCS7_stream.pod | 41 + .../openssl/doc/crypto/PKCS12_create.pod | 75 + .../openssl/doc/crypto/PKCS12_parse.pod | 57 + .../openssl/doc/crypto/PKCS7_decrypt.pod | 55 + .../openssl/doc/crypto/PKCS7_encrypt.pod | 80 + .../openssl/openssl/doc/crypto/PKCS7_sign.pod | 116 + .../doc/crypto/PKCS7_sign_add_signer.pod | 87 + .../openssl/doc/crypto/PKCS7_verify.pod | 118 + .../openssl/openssl/doc/crypto/RAND_add.pod | 77 + .../openssl/openssl/doc/crypto/RAND_bytes.pod | 50 + .../openssl/doc/crypto/RAND_cleanup.pod | 29 + .../openssl/openssl/doc/crypto/RAND_egd.pod | 88 + .../openssl/doc/crypto/RAND_load_file.pod | 53 + .../doc/crypto/RAND_set_rand_method.pod | 83 + .../openssl/doc/crypto/RSA_blinding_on.pod | 43 + .../openssl/doc/crypto/RSA_check_key.pod | 67 + .../openssl/doc/crypto/RSA_generate_key.pod | 69 + .../doc/crypto/RSA_get_ex_new_index.pod | 120 + .../openssl/openssl/doc/crypto/RSA_new.pod | 41 + .../crypto/RSA_padding_add_PKCS1_type_1.pod | 124 + .../openssl/openssl/doc/crypto/RSA_print.pod | 49 + .../doc/crypto/RSA_private_encrypt.pod | 70 + .../openssl/doc/crypto/RSA_public_encrypt.pod | 84 + .../openssl/doc/crypto/RSA_set_method.pod | 202 + .../openssl/openssl/doc/crypto/RSA_sign.pod | 62 + .../doc/crypto/RSA_sign_ASN1_OCTET_STRING.pod | 59 + .../openssl/openssl/doc/crypto/RSA_size.pod | 33 + .../openssl/doc/crypto/SMIME_read_CMS.pod | 70 + .../openssl/doc/crypto/SMIME_read_PKCS7.pod | 73 + .../openssl/doc/crypto/SMIME_write_CMS.pod | 64 + .../openssl/doc/crypto/SMIME_write_PKCS7.pod | 65 + .../doc/crypto/X509_NAME_ENTRY_get_object.pod | 74 + .../doc/crypto/X509_NAME_add_entry_by_txt.pod | 116 + .../doc/crypto/X509_NAME_get_index_by_NID.pod | 108 + .../openssl/doc/crypto/X509_NAME_print_ex.pod | 105 + .../doc/crypto/X509_STORE_CTX_get_error.pod | 303 + .../X509_STORE_CTX_get_ex_new_index.pod | 41 + .../openssl/doc/crypto/X509_STORE_CTX_new.pod | 122 + .../crypto/X509_STORE_CTX_set_verify_cb.pod | 161 + .../crypto/X509_STORE_set_verify_cb_func.pod | 54 + .../crypto/X509_VERIFY_PARAM_set_flags.pod | 171 + .../openssl/openssl/doc/crypto/X509_new.pod | 39 + .../openssl/doc/crypto/X509_verify_cert.pod | 53 + .../deps/openssl/openssl/doc/crypto/bio.pod | 54 + .../openssl/openssl/doc/crypto/blowfish.pod | 112 + .../deps/openssl/openssl/doc/crypto/bn.pod | 181 + .../openssl/doc/crypto/bn_internal.pod | 238 + .../openssl/openssl/doc/crypto/buffer.pod | 73 + .../openssl/openssl/doc/crypto/crypto.pod | 85 + .../openssl/doc/crypto/d2i_ASN1_OBJECT.pod | 29 + .../openssl/doc/crypto/d2i_DHparams.pod | 30 + .../openssl/doc/crypto/d2i_DSAPublicKey.pod | 83 + .../doc/crypto/d2i_PKCS8PrivateKey.pod | 56 + .../openssl/doc/crypto/d2i_RSAPublicKey.pod | 67 + .../openssl/openssl/doc/crypto/d2i_X509.pod | 231 + .../openssl/doc/crypto/d2i_X509_ALGOR.pod | 30 + .../openssl/doc/crypto/d2i_X509_CRL.pod | 37 + .../openssl/doc/crypto/d2i_X509_NAME.pod | 31 + .../openssl/doc/crypto/d2i_X509_REQ.pod | 36 + .../openssl/doc/crypto/d2i_X509_SIG.pod | 30 + .../deps/openssl/openssl/doc/crypto/des.pod | 358 + .../openssl/openssl/doc/crypto/des_modes.pod | 255 + .../deps/openssl/openssl/doc/crypto/dh.pod | 78 + .../deps/openssl/openssl/doc/crypto/dsa.pod | 114 + .../deps/openssl/openssl/doc/crypto/ecdsa.pod | 210 + .../openssl/openssl/doc/crypto/engine.pod | 599 + .../deps/openssl/openssl/doc/crypto/err.pod | 187 + .../deps/openssl/openssl/doc/crypto/evp.pod | 55 + .../deps/openssl/openssl/doc/crypto/hmac.pod | 106 + .../openssl/doc/crypto/i2d_CMS_bio_stream.pod | 44 + .../doc/crypto/i2d_PKCS7_bio_stream.pod | 44 + .../openssl/openssl/doc/crypto/lh_stats.pod | 60 + .../deps/openssl/openssl/doc/crypto/lhash.pod | 302 + .../deps/openssl/openssl/doc/crypto/md5.pod | 101 + .../deps/openssl/openssl/doc/crypto/mdc2.pod | 64 + .../deps/openssl/openssl/doc/crypto/pem.pod | 476 + .../deps/openssl/openssl/doc/crypto/rand.pod | 175 + .../deps/openssl/openssl/doc/crypto/rc4.pod | 62 + .../openssl/openssl/doc/crypto/ripemd.pod | 66 + .../deps/openssl/openssl/doc/crypto/rsa.pod | 123 + .../deps/openssl/openssl/doc/crypto/sha.pod | 70 + .../openssl/openssl/doc/crypto/threads.pod | 210 + .../deps/openssl/openssl/doc/crypto/ui.pod | 194 + .../openssl/openssl/doc/crypto/ui_compat.pod | 57 + .../deps/openssl/openssl/doc/crypto/x509.pod | 64 + .../deps/openssl/openssl/doc/fingerprints.txt | 57 + .../openssl/openssl/doc/openssl-shared.txt | 32 + .../deps/openssl/openssl/doc/openssl.txt | 1254 ++ .../openssl/openssl/doc/openssl_button.gif | Bin 0 -> 2063 bytes .../openssl/openssl/doc/openssl_button.html | 7 + .../openssl/doc/ssl/SSL_CIPHER_get_name.pod | 112 + .../ssl/SSL_COMP_add_compression_method.pod | 70 + .../doc/ssl/SSL_CTX_add_extra_chain_cert.pod | 39 + .../openssl/doc/ssl/SSL_CTX_add_session.pod | 73 + .../openssl/openssl/doc/ssl/SSL_CTX_ctrl.pod | 34 + .../doc/ssl/SSL_CTX_flush_sessions.pod | 49 + .../openssl/openssl/doc/ssl/SSL_CTX_free.pod | 41 + .../doc/ssl/SSL_CTX_get_ex_new_index.pod | 53 + .../doc/ssl/SSL_CTX_get_verify_mode.pod | 50 + .../doc/ssl/SSL_CTX_load_verify_locations.pod | 124 + .../openssl/openssl/doc/ssl/SSL_CTX_new.pod | 94 + .../openssl/doc/ssl/SSL_CTX_sess_number.pod | 76 + .../doc/ssl/SSL_CTX_sess_set_cache_size.pod | 51 + .../doc/ssl/SSL_CTX_sess_set_get_cb.pod | 87 + .../openssl/doc/ssl/SSL_CTX_sessions.pod | 34 + .../doc/ssl/SSL_CTX_set_cert_store.pod | 57 + .../ssl/SSL_CTX_set_cert_verify_callback.pod | 75 + .../doc/ssl/SSL_CTX_set_cipher_list.pod | 70 + .../doc/ssl/SSL_CTX_set_client_CA_list.pod | 94 + .../doc/ssl/SSL_CTX_set_client_cert_cb.pod | 94 + .../doc/ssl/SSL_CTX_set_default_passwd_cb.pod | 76 + .../ssl/SSL_CTX_set_generate_session_id.pod | 150 + .../doc/ssl/SSL_CTX_set_info_callback.pod | 153 + .../doc/ssl/SSL_CTX_set_max_cert_list.pod | 77 + .../openssl/doc/ssl/SSL_CTX_set_mode.pod | 91 + .../doc/ssl/SSL_CTX_set_msg_callback.pod | 99 + .../openssl/doc/ssl/SSL_CTX_set_options.pod | 346 + .../ssl/SSL_CTX_set_psk_client_callback.pod | 81 + .../doc/ssl/SSL_CTX_set_quiet_shutdown.pod | 63 + .../ssl/SSL_CTX_set_session_cache_mode.pod | 137 + .../ssl/SSL_CTX_set_session_id_context.pod | 83 + .../doc/ssl/SSL_CTX_set_ssl_version.pod | 61 + .../openssl/doc/ssl/SSL_CTX_set_timeout.pod | 59 + .../doc/ssl/SSL_CTX_set_tmp_dh_callback.pod | 170 + .../doc/ssl/SSL_CTX_set_tmp_rsa_callback.pod | 166 + .../openssl/doc/ssl/SSL_CTX_set_verify.pod | 294 + .../doc/ssl/SSL_CTX_use_certificate.pod | 169 + .../doc/ssl/SSL_CTX_use_psk_identity_hint.pod | 102 + .../openssl/doc/ssl/SSL_SESSION_free.pod | 55 + .../doc/ssl/SSL_SESSION_get_ex_new_index.pod | 61 + .../openssl/doc/ssl/SSL_SESSION_get_time.pod | 64 + .../openssl/openssl/doc/ssl/SSL_accept.pod | 76 + .../openssl/doc/ssl/SSL_alert_type_string.pod | 228 + .../openssl/openssl/doc/ssl/SSL_clear.pod | 75 + .../openssl/openssl/doc/ssl/SSL_connect.pod | 73 + .../openssl/doc/ssl/SSL_do_handshake.pod | 75 + .../deps/openssl/openssl/doc/ssl/SSL_free.pod | 44 + .../openssl/doc/ssl/SSL_get_SSL_CTX.pod | 26 + .../openssl/doc/ssl/SSL_get_ciphers.pod | 42 + .../doc/ssl/SSL_get_client_CA_list.pod | 53 + .../doc/ssl/SSL_get_current_cipher.pod | 43 + .../doc/ssl/SSL_get_default_timeout.pod | 41 + .../openssl/openssl/doc/ssl/SSL_get_error.pod | 114 + .../SSL_get_ex_data_X509_STORE_CTX_idx.pod | 61 + .../openssl/doc/ssl/SSL_get_ex_new_index.pod | 59 + .../openssl/openssl/doc/ssl/SSL_get_fd.pod | 44 + .../doc/ssl/SSL_get_peer_cert_chain.pod | 52 + .../doc/ssl/SSL_get_peer_certificate.pod | 55 + .../openssl/doc/ssl/SSL_get_psk_identity.pod | 63 + .../openssl/openssl/doc/ssl/SSL_get_rbio.pod | 40 + .../openssl/doc/ssl/SSL_get_session.pod | 73 + .../openssl/doc/ssl/SSL_get_verify_result.pod | 57 + .../openssl/doc/ssl/SSL_get_version.pod | 46 + .../openssl/doc/ssl/SSL_library_init.pod | 57 + .../doc/ssl/SSL_load_client_CA_file.pod | 62 + .../deps/openssl/openssl/doc/ssl/SSL_new.pod | 44 + .../openssl/openssl/doc/ssl/SSL_pending.pod | 43 + .../deps/openssl/openssl/doc/ssl/SSL_read.pod | 124 + .../openssl/doc/ssl/SSL_rstate_string.pod | 59 + .../openssl/doc/ssl/SSL_session_reused.pod | 45 + .../openssl/openssl/doc/ssl/SSL_set_bio.pod | 34 + .../openssl/doc/ssl/SSL_set_connect_state.pod | 55 + .../openssl/openssl/doc/ssl/SSL_set_fd.pod | 54 + .../openssl/doc/ssl/SSL_set_session.pod | 57 + .../openssl/doc/ssl/SSL_set_shutdown.pod | 72 + .../openssl/doc/ssl/SSL_set_verify_result.pod | 38 + .../openssl/openssl/doc/ssl/SSL_shutdown.pod | 125 + .../openssl/doc/ssl/SSL_state_string.pod | 45 + .../deps/openssl/openssl/doc/ssl/SSL_want.pod | 77 + .../openssl/openssl/doc/ssl/SSL_write.pod | 109 + .../openssl/doc/ssl/d2i_SSL_SESSION.pod | 66 + .../deps/openssl/openssl/doc/ssl/ssl.pod | 758 + .../deps/openssl/openssl/doc/ssleay.txt | 7030 ++++++++++ .../deps/openssl/openssl/doc/standards.txt | 285 + node-v0.8.14/deps/openssl/openssl/e_os.h | 746 + node-v0.8.14/deps/openssl/openssl/e_os2.h | 295 + .../deps/openssl/openssl/engines/Makefile | 335 + .../deps/openssl/openssl/engines/alpha.opt | 1 + .../deps/openssl/openssl/engines/axp.opt | 1 + .../deps/openssl/openssl/engines/capierr.bat | 1 + .../openssl/openssl/engines/ccgost/Makefile | 275 + .../openssl/engines/ccgost/README.gost | 300 + .../openssl/engines/ccgost/e_gost_err.c | 212 + .../openssl/engines/ccgost/e_gost_err.h | 156 + .../openssl/engines/ccgost/e_gost_err.proto | 61 + .../openssl/openssl/engines/ccgost/gost.ec | 5 + .../openssl/openssl/engines/ccgost/gost2001.c | 343 + .../openssl/engines/ccgost/gost2001_keyx.c | 308 + .../openssl/engines/ccgost/gost2001_keyx.h | 10 + .../openssl/openssl/engines/ccgost/gost89.c | 409 + .../openssl/openssl/engines/ccgost/gost89.h | 96 + .../openssl/engines/ccgost/gost94_keyx.c | 291 + .../openssl/engines/ccgost/gost_ameth.c | 908 ++ .../openssl/engines/ccgost/gost_asn1.c | 55 + .../openssl/engines/ccgost/gost_crypt.c | 617 + .../openssl/openssl/engines/ccgost/gost_ctl.c | 89 + .../openssl/openssl/engines/ccgost/gost_eng.c | 273 + .../openssl/engines/ccgost/gost_keywrap.c | 109 + .../openssl/engines/ccgost/gost_keywrap.h | 56 + .../openssl/openssl/engines/ccgost/gost_lcl.h | 218 + .../openssl/openssl/engines/ccgost/gost_md.c | 75 + .../openssl/engines/ccgost/gost_params.c | 198 + .../openssl/engines/ccgost/gost_params.h | 34 + .../openssl/engines/ccgost/gost_pmeth.c | 621 + .../openssl/engines/ccgost/gost_sign.c | 321 + .../openssl/openssl/engines/ccgost/gosthash.c | 255 + .../openssl/openssl/engines/ccgost/gosthash.h | 48 + .../openssl/openssl/engines/ccgost/gostsum.c | 210 + .../deps/openssl/openssl/engines/e_4758cca.c | 987 ++ .../deps/openssl/openssl/engines/e_4758cca.ec | 1 + .../openssl/openssl/engines/e_4758cca_err.c | 153 + .../openssl/openssl/engines/e_4758cca_err.h | 97 + .../deps/openssl/openssl/engines/e_aep.c | 1140 ++ .../deps/openssl/openssl/engines/e_aep.ec | 1 + .../deps/openssl/openssl/engines/e_aep_err.c | 161 + .../deps/openssl/openssl/engines/e_aep_err.h | 105 + .../deps/openssl/openssl/engines/e_atalla.c | 607 + .../deps/openssl/openssl/engines/e_atalla.ec | 1 + .../openssl/openssl/engines/e_atalla_err.c | 149 + .../openssl/openssl/engines/e_atalla_err.h | 93 + .../deps/openssl/openssl/engines/e_capi.c | 1824 +++ .../deps/openssl/openssl/engines/e_capi.ec | 1 + .../deps/openssl/openssl/engines/e_capi_err.c | 184 + .../deps/openssl/openssl/engines/e_capi_err.h | 128 + .../deps/openssl/openssl/engines/e_chil.c | 1356 ++ .../deps/openssl/openssl/engines/e_chil.ec | 1 + .../deps/openssl/openssl/engines/e_chil_err.c | 160 + .../deps/openssl/openssl/engines/e_chil_err.h | 104 + .../deps/openssl/openssl/engines/e_cswift.c | 1129 ++ .../deps/openssl/openssl/engines/e_cswift.ec | 1 + .../openssl/openssl/engines/e_cswift_err.c | 154 + .../openssl/openssl/engines/e_cswift_err.h | 98 + .../deps/openssl/openssl/engines/e_gmp.c | 480 + .../deps/openssl/openssl/engines/e_gmp.ec | 1 + .../deps/openssl/openssl/engines/e_gmp_err.c | 141 + .../deps/openssl/openssl/engines/e_gmp_err.h | 85 + .../deps/openssl/openssl/engines/e_nuron.c | 434 + .../deps/openssl/openssl/engines/e_nuron.ec | 1 + .../openssl/openssl/engines/e_nuron_err.c | 146 + .../openssl/openssl/engines/e_nuron_err.h | 90 + .../deps/openssl/openssl/engines/e_padlock.c | 1233 ++ .../deps/openssl/openssl/engines/e_padlock.ec | 1 + .../deps/openssl/openssl/engines/e_sureware.c | 1055 ++ .../openssl/openssl/engines/e_sureware.ec | 1 + .../openssl/openssl/engines/e_sureware_err.c | 158 + .../openssl/openssl/engines/e_sureware_err.h | 102 + .../deps/openssl/openssl/engines/e_ubsec.c | 1069 ++ .../deps/openssl/openssl/engines/e_ubsec.ec | 1 + .../openssl/openssl/engines/e_ubsec_err.c | 157 + .../openssl/openssl/engines/e_ubsec_err.h | 101 + .../openssl/openssl/engines/engine_vector.mar | 24 + .../deps/openssl/openssl/engines/ia64.opt | 1 + .../openssl/openssl/engines/makeengines.com | 1125 ++ .../deps/openssl/openssl/engines/vax.opt | 9 + .../openssl/engines/vendor_defns/aep.h | 178 + .../openssl/engines/vendor_defns/atalla.h | 48 + .../openssl/engines/vendor_defns/cswift.h | 234 + .../engines/vendor_defns/hw_4758_cca.h | 149 + .../openssl/engines/vendor_defns/hw_ubsec.h | 100 + .../engines/vendor_defns/hwcryptohook.h | 486 + .../openssl/engines/vendor_defns/sureware.h | 239 + .../openssl/openssl/include/openssl/aes.h | 1 + .../openssl/openssl/include/openssl/asn1.h | 1 + .../openssl/include/openssl/asn1_mac.h | 1 + .../openssl/openssl/include/openssl/asn1t.h | 1 + .../openssl/openssl/include/openssl/bio.h | 1 + .../openssl/include/openssl/blowfish.h | 1 + .../deps/openssl/openssl/include/openssl/bn.h | 1 + .../openssl/openssl/include/openssl/buffer.h | 1 + .../openssl/include/openssl/camellia.h | 1 + .../openssl/openssl/include/openssl/cast.h | 1 + .../openssl/openssl/include/openssl/cms.h | 1 + .../openssl/openssl/include/openssl/comp.h | 1 + .../openssl/openssl/include/openssl/conf.h | 1 + .../openssl/include/openssl/conf_api.h | 1 + .../openssl/openssl/include/openssl/crypto.h | 1 + .../openssl/openssl/include/openssl/des.h | 1 + .../openssl/openssl/include/openssl/des_old.h | 1 + .../deps/openssl/openssl/include/openssl/dh.h | 1 + .../openssl/openssl/include/openssl/dsa.h | 1 + .../openssl/openssl/include/openssl/dso.h | 1 + .../openssl/openssl/include/openssl/dtls1.h | 1 + .../openssl/openssl/include/openssl/e_os2.h | 1 + .../openssl/openssl/include/openssl/ebcdic.h | 1 + .../deps/openssl/openssl/include/openssl/ec.h | 1 + .../openssl/openssl/include/openssl/ecdh.h | 1 + .../openssl/openssl/include/openssl/ecdsa.h | 1 + .../openssl/openssl/include/openssl/engine.h | 1 + .../openssl/openssl/include/openssl/err.h | 1 + .../openssl/openssl/include/openssl/evp.h | 1 + .../openssl/openssl/include/openssl/hmac.h | 1 + .../openssl/openssl/include/openssl/idea.h | 1 + .../openssl/include/openssl/krb5_asn.h | 1 + .../openssl/openssl/include/openssl/kssl.h | 1 + .../openssl/openssl/include/openssl/lhash.h | 1 + .../openssl/openssl/include/openssl/md2.h | 1 + .../openssl/openssl/include/openssl/md4.h | 1 + .../openssl/openssl/include/openssl/md5.h | 1 + .../openssl/openssl/include/openssl/mdc2.h | 1 + .../openssl/openssl/include/openssl/modes.h | 1 + .../openssl/openssl/include/openssl/obj_mac.h | 1 + .../openssl/openssl/include/openssl/objects.h | 1 + .../openssl/openssl/include/openssl/ocsp.h | 1 + .../openssl/include/openssl/opensslv.h | 1 + .../openssl/include/openssl/ossl_typ.h | 1 + .../openssl/openssl/include/openssl/pem.h | 1 + .../openssl/openssl/include/openssl/pem2.h | 1 + .../openssl/openssl/include/openssl/pkcs12.h | 1 + .../openssl/openssl/include/openssl/pkcs7.h | 1 + .../openssl/openssl/include/openssl/pqueue.h | 1 + .../openssl/openssl/include/openssl/rand.h | 1 + .../openssl/openssl/include/openssl/rc2.h | 1 + .../openssl/openssl/include/openssl/rc4.h | 1 + .../openssl/openssl/include/openssl/ripemd.h | 1 + .../openssl/openssl/include/openssl/rsa.h | 1 + .../openssl/include/openssl/safestack.h | 1 + .../openssl/openssl/include/openssl/seed.h | 1 + .../openssl/openssl/include/openssl/sha.h | 1 + .../openssl/openssl/include/openssl/ssl.h | 1 + .../openssl/openssl/include/openssl/ssl2.h | 1 + .../openssl/openssl/include/openssl/ssl23.h | 1 + .../openssl/openssl/include/openssl/ssl3.h | 1 + .../openssl/openssl/include/openssl/stack.h | 1 + .../openssl/openssl/include/openssl/store.h | 1 + .../openssl/include/openssl/symhacks.h | 1 + .../openssl/openssl/include/openssl/tls1.h | 1 + .../deps/openssl/openssl/include/openssl/ts.h | 1 + .../openssl/openssl/include/openssl/txt_db.h | 1 + .../deps/openssl/openssl/include/openssl/ui.h | 1 + .../openssl/include/openssl/ui_compat.h | 1 + .../openssl/include/openssl/whrlpool.h | 1 + .../openssl/openssl/include/openssl/x509.h | 1 + .../openssl/include/openssl/x509_vfy.h | 1 + .../openssl/openssl/include/openssl/x509v3.h | 1 + node-v0.8.14/deps/openssl/openssl/install.com | 136 + node-v0.8.14/deps/openssl/openssl/makevms.com | 1533 ++ node-v0.8.14/deps/openssl/openssl/ms/.rnd | Bin 0 -> 1024 bytes .../deps/openssl/openssl/ms/32all.bat | 20 + node-v0.8.14/deps/openssl/openssl/ms/README | 13 + .../deps/openssl/openssl/ms/applink.c | 94 + node-v0.8.14/deps/openssl/openssl/ms/bcb4.bat | 6 + .../deps/openssl/openssl/ms/certCA.srl | 1 + .../deps/openssl/openssl/ms/certCA.ss | 10 + node-v0.8.14/deps/openssl/openssl/ms/certU.ss | 10 + node-v0.8.14/deps/openssl/openssl/ms/cmp.pl | 47 + .../deps/openssl/openssl/ms/do_ms.bat | 11 + .../deps/openssl/openssl/ms/do_nasm.bat | 8 + .../deps/openssl/openssl/ms/do_nt.bat | 7 + .../deps/openssl/openssl/ms/do_win64a.bat | 9 + .../deps/openssl/openssl/ms/do_win64i.bat | 9 + node-v0.8.14/deps/openssl/openssl/ms/keyCA.ss | 9 + node-v0.8.14/deps/openssl/openssl/ms/keyU.ss | 9 + .../deps/openssl/openssl/ms/mingw32.bat | 90 + node-v0.8.14/deps/openssl/openssl/ms/mw.bat | 26 + .../deps/openssl/openssl/ms/req2CA.ss | 29 + node-v0.8.14/deps/openssl/openssl/ms/reqCA.ss | 8 + node-v0.8.14/deps/openssl/openssl/ms/reqU.ss | 8 + .../deps/openssl/openssl/ms/speed32.bat | 37 + node-v0.8.14/deps/openssl/openssl/ms/tenc.bat | 14 + .../deps/openssl/openssl/ms/tencce.bat | 19 + node-v0.8.14/deps/openssl/openssl/ms/test.bat | 185 + .../deps/openssl/openssl/ms/testce.bat | 234 + .../deps/openssl/openssl/ms/testce2.bat | 2 + .../deps/openssl/openssl/ms/testenc.bat | 94 + .../deps/openssl/openssl/ms/testencce.bat | 97 + .../deps/openssl/openssl/ms/testpem.bat | 32 + .../deps/openssl/openssl/ms/testpemce.bat | 42 + .../deps/openssl/openssl/ms/testss.bat | 98 + .../deps/openssl/openssl/ms/testssce.bat | 104 + .../deps/openssl/openssl/ms/tlhelp32.h | 136 + node-v0.8.14/deps/openssl/openssl/ms/tpem.bat | 6 + .../deps/openssl/openssl/ms/tpemce.bat | 8 + .../deps/openssl/openssl/ms/uplink-common.pl | 22 + .../deps/openssl/openssl/ms/uplink-ia64.pl | 50 + .../deps/openssl/openssl/ms/uplink-x86.pl | 33 + .../deps/openssl/openssl/ms/uplink-x86_64.pl | 64 + node-v0.8.14/deps/openssl/openssl/ms/uplink.c | 117 + node-v0.8.14/deps/openssl/openssl/ms/uplink.h | 29 + .../deps/openssl/openssl/ms/uplink.pl | 204 + .../deps/openssl/openssl/ms/x86asm.bat | 57 + .../deps/openssl/openssl/openssl.doxy | 7 + .../deps/openssl/openssl/openssl.spec | 213 + .../deps/openssl/openssl/os2/OS2-EMX.cmd | 102 + .../deps/openssl/openssl/os2/backwardify.pl | 32 + .../openssl/openssl/shlib/Makefile.hpux10-cc | 34 + .../deps/openssl/openssl/shlib/README | 1 + .../deps/openssl/openssl/shlib/hpux10-cc.sh | 92 + .../deps/openssl/openssl/shlib/irix.sh | 7 + .../openssl/openssl/shlib/sco5-shared-gcc.sh | 48 + .../openssl/shlib/sco5-shared-installed | 28 + .../deps/openssl/openssl/shlib/sco5-shared.sh | 48 + .../deps/openssl/openssl/shlib/solaris-sc4.sh | 42 + .../deps/openssl/openssl/shlib/solaris.sh | 36 + .../deps/openssl/openssl/shlib/sun.sh | 8 + .../openssl/openssl/shlib/svr5-shared-gcc.sh | 48 + .../openssl/shlib/svr5-shared-installed | 27 + .../deps/openssl/openssl/shlib/svr5-shared.sh | 48 + .../deps/openssl/openssl/shlib/win32.bat | 18 + .../deps/openssl/openssl/shlib/win32dll.bat | 13 + .../deps/openssl/openssl/ssl/Makefile | 975 ++ .../deps/openssl/openssl/ssl/bio_ssl.c | 605 + .../deps/openssl/openssl/ssl/d1_both.c | 1419 ++ .../deps/openssl/openssl/ssl/d1_clnt.c | 1542 +++ .../deps/openssl/openssl/ssl/d1_enc.c | 289 + .../deps/openssl/openssl/ssl/d1_lib.c | 451 + .../deps/openssl/openssl/ssl/d1_meth.c | 77 + .../deps/openssl/openssl/ssl/d1_pkt.c | 1806 +++ .../deps/openssl/openssl/ssl/d1_srvr.c | 1563 +++ node-v0.8.14/deps/openssl/openssl/ssl/dtls1.h | 267 + .../deps/openssl/openssl/ssl/install-ssl.com | 136 + node-v0.8.14/deps/openssl/openssl/ssl/kssl.c | 2205 +++ node-v0.8.14/deps/openssl/openssl/ssl/kssl.h | 179 + .../deps/openssl/openssl/ssl/kssl_lcl.h | 87 + .../deps/openssl/openssl/ssl/s23_clnt.c | 703 + .../deps/openssl/openssl/ssl/s23_lib.c | 187 + .../deps/openssl/openssl/ssl/s23_meth.c | 88 + .../deps/openssl/openssl/ssl/s23_pkt.c | 117 + .../deps/openssl/openssl/ssl/s23_srvr.c | 599 + .../deps/openssl/openssl/ssl/s2_clnt.c | 1125 ++ .../deps/openssl/openssl/ssl/s2_enc.c | 193 + .../deps/openssl/openssl/ssl/s2_lib.c | 556 + .../deps/openssl/openssl/ssl/s2_meth.c | 84 + .../deps/openssl/openssl/ssl/s2_pkt.c | 744 + .../deps/openssl/openssl/ssl/s2_srvr.c | 1142 ++ .../deps/openssl/openssl/ssl/s3_both.c | 867 ++ .../deps/openssl/openssl/ssl/s3_clnt.c | 3153 +++++ .../deps/openssl/openssl/ssl/s3_enc.c | 849 ++ .../deps/openssl/openssl/ssl/s3_lib.c | 3363 +++++ .../deps/openssl/openssl/ssl/s3_meth.c | 77 + .../deps/openssl/openssl/ssl/s3_pkt.c | 1502 ++ .../deps/openssl/openssl/ssl/s3_srvr.c | 3325 +++++ .../deps/openssl/openssl/ssl/ssl-lib.com | 1214 ++ node-v0.8.14/deps/openssl/openssl/ssl/ssl.h | 2386 ++++ node-v0.8.14/deps/openssl/openssl/ssl/ssl2.h | 268 + node-v0.8.14/deps/openssl/openssl/ssl/ssl23.h | 83 + node-v0.8.14/deps/openssl/openssl/ssl/ssl3.h | 675 + .../deps/openssl/openssl/ssl/ssl_algs.c | 140 + .../deps/openssl/openssl/ssl/ssl_asn1.c | 592 + .../deps/openssl/openssl/ssl/ssl_cert.c | 834 ++ .../deps/openssl/openssl/ssl/ssl_ciph.c | 1793 +++ .../deps/openssl/openssl/ssl/ssl_err.c | 577 + .../deps/openssl/openssl/ssl/ssl_err2.c | 70 + .../deps/openssl/openssl/ssl/ssl_lib.c | 3259 +++++ .../deps/openssl/openssl/ssl/ssl_locl.h | 1093 ++ .../deps/openssl/openssl/ssl/ssl_rsa.c | 815 ++ .../deps/openssl/openssl/ssl/ssl_sess.c | 1102 ++ .../deps/openssl/openssl/ssl/ssl_stat.c | 567 + .../deps/openssl/openssl/ssl/ssl_task.c | 369 + .../deps/openssl/openssl/ssl/ssl_txt.c | 240 + .../deps/openssl/openssl/ssl/ssltest.c | 2503 ++++ .../deps/openssl/openssl/ssl/t1_clnt.c | 79 + .../deps/openssl/openssl/ssl/t1_enc.c | 1134 ++ .../deps/openssl/openssl/ssl/t1_lib.c | 1866 +++ .../deps/openssl/openssl/ssl/t1_meth.c | 76 + .../deps/openssl/openssl/ssl/t1_reneg.c | 292 + .../deps/openssl/openssl/ssl/t1_srvr.c | 80 + node-v0.8.14/deps/openssl/openssl/ssl/tls1.h | 540 + .../deps/openssl/openssl/times/090/586-100.nt | 32 + .../deps/openssl/openssl/times/091/486-50.nt | 30 + .../openssl/openssl/times/091/586-100.lnx | 32 + .../deps/openssl/openssl/times/091/68000.bsd | 32 + .../openssl/openssl/times/091/686-200.lnx | 32 + .../openssl/openssl/times/091/alpha064.osf | 32 + .../openssl/openssl/times/091/alpha164.lnx | 32 + .../openssl/openssl/times/091/alpha164.osf | 31 + .../openssl/openssl/times/091/mips-rel.pl | 21 + .../deps/openssl/openssl/times/091/r10000.irx | 37 + .../deps/openssl/openssl/times/091/r3000.ult | 32 + .../deps/openssl/openssl/times/091/r4400.irx | 32 + .../deps/openssl/openssl/times/100.lnx | 32 + .../deps/openssl/openssl/times/100.nt | 29 + .../deps/openssl/openssl/times/200.lnx | 30 + .../deps/openssl/openssl/times/486-66.dos | 22 + .../deps/openssl/openssl/times/486-66.nt | 22 + .../deps/openssl/openssl/times/486-66.w31 | 23 + node-v0.8.14/deps/openssl/openssl/times/5.lnx | 29 + .../deps/openssl/openssl/times/586-085i.nt | 29 + .../deps/openssl/openssl/times/586-100.LN3 | 26 + .../deps/openssl/openssl/times/586-100.NT2 | 26 + .../deps/openssl/openssl/times/586-100.dos | 24 + .../deps/openssl/openssl/times/586-100.ln4 | 26 + .../deps/openssl/openssl/times/586-100.lnx | 23 + .../deps/openssl/openssl/times/586-100.nt | 23 + .../deps/openssl/openssl/times/586-100.ntx | 30 + .../deps/openssl/openssl/times/586-100.w31 | 27 + .../deps/openssl/openssl/times/586-1002.lnx | 26 + .../deps/openssl/openssl/times/586p-100.lnx | 26 + .../deps/openssl/openssl/times/686-200.bsd | 25 + .../deps/openssl/openssl/times/686-200.lnx | 26 + .../deps/openssl/openssl/times/686-200.nt | 24 + node-v0.8.14/deps/openssl/openssl/times/L1 | 27 + .../deps/openssl/openssl/times/R10000.t | 24 + .../deps/openssl/openssl/times/R4400.t | 26 + node-v0.8.14/deps/openssl/openssl/times/aix.t | 34 + .../deps/openssl/openssl/times/aixold.t | 23 + .../deps/openssl/openssl/times/alpha.t | 81 + .../deps/openssl/openssl/times/alpha400.t | 25 + .../deps/openssl/openssl/times/cyrix100.lnx | 22 + .../deps/openssl/openssl/times/dgux-x86.t | 23 + .../deps/openssl/openssl/times/dgux.t | 17 + .../deps/openssl/openssl/times/hpux-acc.t | 25 + .../deps/openssl/openssl/times/hpux-kr.t | 23 + .../deps/openssl/openssl/times/hpux.t | 86 + .../deps/openssl/openssl/times/p2.w95 | 22 + .../deps/openssl/openssl/times/pent2.t | 24 + .../deps/openssl/openssl/times/readme | 11 + .../deps/openssl/openssl/times/s586-100.lnx | 25 + .../deps/openssl/openssl/times/s586-100.nt | 23 + node-v0.8.14/deps/openssl/openssl/times/sgi.t | 29 + .../deps/openssl/openssl/times/sparc.t | 26 + .../deps/openssl/openssl/times/sparc2 | 21 + .../deps/openssl/openssl/times/sparcLX.t | 22 + .../deps/openssl/openssl/times/usparc.t | 25 + .../deps/openssl/openssl/times/x86/bfs.cpp | 67 + .../deps/openssl/openssl/times/x86/casts.cpp | 67 + .../deps/openssl/openssl/times/x86/des3s.cpp | 67 + .../deps/openssl/openssl/times/x86/dess.cpp | 67 + .../deps/openssl/openssl/times/x86/md4s.cpp | 78 + .../deps/openssl/openssl/times/x86/md5s.cpp | 78 + .../deps/openssl/openssl/times/x86/rc4s.cpp | 73 + .../deps/openssl/openssl/times/x86/sha1s.cpp | 79 + .../deps/openssl/openssl/tools/Makefile | 59 + .../deps/openssl/openssl/tools/c89.sh | 15 + .../deps/openssl/openssl/tools/c_hash | 9 + .../deps/openssl/openssl/tools/c_info | 12 + .../deps/openssl/openssl/tools/c_issuer | 10 + .../deps/openssl/openssl/tools/c_name | 10 + .../deps/openssl/openssl/tools/c_rehash | 180 + .../deps/openssl/openssl/tools/c_rehash.in | 180 + .../deps/openssl/openssl/util/FreeBSD.sh | 6 + .../deps/openssl/openssl/util/add_cr.pl | 123 + node-v0.8.14/deps/openssl/openssl/util/bat.sh | 134 + .../deps/openssl/openssl/util/ck_errf.pl | 64 + .../deps/openssl/openssl/util/clean-depend.pl | 58 + .../deps/openssl/openssl/util/copy.pl | 59 + .../deps/openssl/openssl/util/cygwin.sh | 146 + .../deps/openssl/openssl/util/deleof.pl | 7 + .../deps/openssl/openssl/util/deltree.com | 34 + .../deps/openssl/openssl/util/dirname.pl | 18 + .../deps/openssl/openssl/util/do_ms.sh | 19 + node-v0.8.14/deps/openssl/openssl/util/domd | 38 + .../deps/openssl/openssl/util/err-ins.pl | 33 + .../openssl/openssl/util/extract-names.pl | 26 + .../openssl/openssl/util/extract-section.pl | 12 + .../deps/openssl/openssl/util/files.pl | 61 + .../deps/openssl/openssl/util/fixNT.sh | 14 + .../deps/openssl/openssl/util/install.sh | 108 + .../deps/openssl/openssl/util/libeay.num | 4196 ++++++ .../deps/openssl/openssl/util/mk1mf.pl | 1164 ++ .../deps/openssl/openssl/util/mkcerts.sh | 220 + .../deps/openssl/openssl/util/mkdef.pl | 1509 ++ .../deps/openssl/openssl/util/mkdir-p.pl | 34 + .../deps/openssl/openssl/util/mkerr.pl | 810 ++ .../deps/openssl/openssl/util/mkfiles.pl | 141 + .../deps/openssl/openssl/util/mklink.pl | 73 + .../deps/openssl/openssl/util/mkrc.pl | 71 + .../deps/openssl/openssl/util/mkstack.pl | 192 + .../deps/openssl/openssl/util/opensslwrap.sh | 26 + .../deps/openssl/openssl/util/perlpath.pl | 35 + .../deps/openssl/openssl/util/pl/BC-32.pl | 139 + .../deps/openssl/openssl/util/pl/Mingw32.pl | 104 + .../deps/openssl/openssl/util/pl/OS2-EMX.pl | 120 + .../deps/openssl/openssl/util/pl/VC-32.pl | 338 + .../deps/openssl/openssl/util/pl/linux.pl | 104 + .../deps/openssl/openssl/util/pl/netware.pl | 532 + .../deps/openssl/openssl/util/pl/ultrix.pl | 38 + .../deps/openssl/openssl/util/pl/unix.pl | 96 + .../deps/openssl/openssl/util/pod2man.pl | 1184 ++ .../deps/openssl/openssl/util/pod2mantest | 58 + .../deps/openssl/openssl/util/pod2mantest.pod | 15 + .../deps/openssl/openssl/util/point.sh | 10 + .../deps/openssl/openssl/util/selftest.pl | 201 + .../deps/openssl/openssl/util/shlib_wrap.sh | 93 + .../deps/openssl/openssl/util/sp-diff.pl | 80 + .../deps/openssl/openssl/util/speed.sh | 39 + .../deps/openssl/openssl/util/src-dep.pl | 147 + .../deps/openssl/openssl/util/ssleay.num | 261 + .../deps/openssl/openssl/util/tab_num.pl | 17 + .../deps/openssl/openssl/util/x86asm.sh | 42 + .../patches/handshake_cutthrough.patch | 275 + node-v0.8.14/deps/openssl/patches/jsse.patch | 426 + node-v0.8.14/deps/openssl/patches/npn.patch | 1293 ++ .../openssl/patches/openssl_no_dtls1.patch | 13 + node-v0.8.14/deps/openssl/patches/progs.patch | 54 + .../openssl/patches/sha1_armv4_large.patch | 21 + .../deps/openssl/patches/small_records.patch | 337 + .../deps/openssl/patches/tls_exporter.patch | 220 + .../x509_hash_name_algorithm_change.patch | 31 + node-v0.8.14/deps/uv/.gitignore | 33 + node-v0.8.14/deps/uv/.mailmap | 13 + node-v0.8.14/deps/uv/.travis.yml | 9 + node-v0.8.14/deps/uv/AUTHORS | 45 + node-v0.8.14/deps/uv/LICENSE | 42 + node-v0.8.14/deps/uv/Makefile | 119 + node-v0.8.14/deps/uv/README.md | 88 + node-v0.8.14/deps/uv/common.gypi | 178 + node-v0.8.14/deps/uv/gyp_uv | 75 + node-v0.8.14/deps/uv/include/ares.h | 591 + node-v0.8.14/deps/uv/include/ares_version.h | 24 + node-v0.8.14/deps/uv/include/uv-private/eio.h | 403 + node-v0.8.14/deps/uv/include/uv-private/ev.h | 838 ++ .../deps/uv/include/uv-private/ngx-queue.h | 108 + .../deps/uv/include/uv-private/tree.h | 768 + .../deps/uv/include/uv-private/uv-unix.h | 314 + .../deps/uv/include/uv-private/uv-win.h | 517 + node-v0.8.14/deps/uv/include/uv.h | 1808 +++ node-v0.8.14/deps/uv/test/benchmark-ares.c | 117 + node-v0.8.14/deps/uv/test/benchmark-fs-stat.c | 164 + .../deps/uv/test/benchmark-getaddrinfo.c | 94 + node-v0.8.14/deps/uv/test/benchmark-list.h | 114 + .../deps/uv/test/benchmark-loop-count.c | 88 + .../deps/uv/test/benchmark-million-timers.c | 65 + .../deps/uv/test/benchmark-ping-pongs.c | 213 + node-v0.8.14/deps/uv/test/benchmark-pound.c | 324 + node-v0.8.14/deps/uv/test/benchmark-pump.c | 462 + node-v0.8.14/deps/uv/test/benchmark-sizes.c | 45 + node-v0.8.14/deps/uv/test/benchmark-spawn.c | 162 + .../deps/uv/test/benchmark-tcp-write-batch.c | 140 + node-v0.8.14/deps/uv/test/benchmark-thread.c | 64 + .../deps/uv/test/benchmark-udp-packet-storm.c | 247 + node-v0.8.14/deps/uv/test/blackhole-server.c | 118 + node-v0.8.14/deps/uv/test/dns-server.c | 321 + node-v0.8.14/deps/uv/test/echo-server.c | 378 + node-v0.8.14/deps/uv/test/fixtures/empty_file | 0 .../deps/uv/test/fixtures/load_error.node | 1 + node-v0.8.14/deps/uv/test/run-benchmarks.c | 64 + node-v0.8.14/deps/uv/test/run-tests.c | 138 + node-v0.8.14/deps/uv/test/runner-unix.c | 290 + node-v0.8.14/deps/uv/test/runner-unix.h | 36 + node-v0.8.14/deps/uv/test/runner-win.c | 293 + node-v0.8.14/deps/uv/test/runner-win.h | 42 + node-v0.8.14/deps/uv/test/runner.c | 326 + node-v0.8.14/deps/uv/test/runner.h | 159 + node-v0.8.14/deps/uv/test/task.h | 109 + node-v0.8.14/deps/uv/test/test-async.c | 118 + .../deps/uv/test/test-callback-order.c | 76 + .../deps/uv/test/test-callback-stack.c | 203 + .../deps/uv/test/test-connection-fail.c | 148 + .../deps/uv/test/test-counters-init.c | 215 + .../deps/uv/test/test-cwd-and-chdir.c | 64 + .../deps/uv/test/test-delayed-accept.c | 197 + node-v0.8.14/deps/uv/test/test-dlerror.c | 58 + node-v0.8.14/deps/uv/test/test-error.c | 59 + node-v0.8.14/deps/uv/test/test-fail-always.c | 29 + node-v0.8.14/deps/uv/test/test-fs-event.c | 474 + node-v0.8.14/deps/uv/test/test-fs-poll.c | 146 + node-v0.8.14/deps/uv/test/test-fs.c | 1843 +++ .../deps/uv/test/test-get-currentexe.c | 63 + node-v0.8.14/deps/uv/test/test-get-loadavg.c | 36 + node-v0.8.14/deps/uv/test/test-get-memory.c | 38 + node-v0.8.14/deps/uv/test/test-getaddrinfo.c | 122 + .../deps/uv/test/test-gethostbyname.c | 180 + node-v0.8.14/deps/uv/test/test-getsockname.c | 342 + node-v0.8.14/deps/uv/test/test-hrtime.c | 54 + node-v0.8.14/deps/uv/test/test-idle.c | 81 + .../deps/uv/test/test-ipc-send-recv.c | 209 + node-v0.8.14/deps/uv/test/test-ipc.c | 620 + node-v0.8.14/deps/uv/test/test-list.h | 424 + node-v0.8.14/deps/uv/test/test-loop-handles.c | 336 + .../deps/uv/test/test-multiple-listen.c | 102 + node-v0.8.14/deps/uv/test/test-mutexes.c | 63 + node-v0.8.14/deps/uv/test/test-pass-always.c | 28 + node-v0.8.14/deps/uv/test/test-ping-pong.c | 253 + .../deps/uv/test/test-pipe-bind-error.c | 140 + .../deps/uv/test/test-pipe-connect-error.c | 96 + .../deps/uv/test/test-platform-output.c | 87 + node-v0.8.14/deps/uv/test/test-poll-close.c | 77 + node-v0.8.14/deps/uv/test/test-poll.c | 573 + .../deps/uv/test/test-process-title.c | 49 + node-v0.8.14/deps/uv/test/test-ref.c | 338 + node-v0.8.14/deps/uv/test/test-run-once.c | 48 + node-v0.8.14/deps/uv/test/test-semaphore.c | 111 + .../deps/uv/test/test-shutdown-close.c | 103 + node-v0.8.14/deps/uv/test/test-shutdown-eof.c | 183 + node-v0.8.14/deps/uv/test/test-spawn.c | 847 ++ .../deps/uv/test/test-stdio-over-pipes.c | 246 + .../deps/uv/test/test-tcp-bind-error.c | 191 + .../deps/uv/test/test-tcp-bind6-error.c | 154 + .../uv/test/test-tcp-close-while-connecting.c | 80 + node-v0.8.14/deps/uv/test/test-tcp-close.c | 129 + .../test/test-tcp-connect-error-after-write.c | 95 + .../deps/uv/test/test-tcp-connect-error.c | 70 + .../deps/uv/test/test-tcp-connect-timeout.c | 85 + .../deps/uv/test/test-tcp-connect6-error.c | 68 + node-v0.8.14/deps/uv/test/test-tcp-flags.c | 51 + .../uv/test/test-tcp-shutdown-after-write.c | 131 + .../deps/uv/test/test-tcp-unexpected-read.c | 113 + .../deps/uv/test/test-tcp-write-error.c | 168 + .../test-tcp-write-to-half-open-connection.c | 135 + .../deps/uv/test/test-tcp-writealot.c | 170 + node-v0.8.14/deps/uv/test/test-thread.c | 183 + node-v0.8.14/deps/uv/test/test-threadpool.c | 57 + node-v0.8.14/deps/uv/test/test-timer-again.c | 141 + node-v0.8.14/deps/uv/test/test-timer.c | 152 + node-v0.8.14/deps/uv/test/test-tty.c | 110 + .../deps/uv/test/test-udp-dgram-too-big.c | 86 + node-v0.8.14/deps/uv/test/test-udp-ipv6.c | 156 + .../deps/uv/test/test-udp-multicast-join.c | 139 + .../deps/uv/test/test-udp-multicast-ttl.c | 86 + node-v0.8.14/deps/uv/test/test-udp-options.c | 86 + .../deps/uv/test/test-udp-send-and-recv.c | 208 + node-v0.8.14/deps/uv/test/test-util.c | 97 + node-v0.8.14/deps/uv/test/test-walk-handles.c | 77 + node-v0.8.14/deps/uv/uv.gyp | 453 + node-v0.8.14/deps/uv/vcbuild.bat | 105 + node-v0.8.14/deps/v8/.gitignore | 36 + node-v0.8.14/deps/v8/AUTHORS | 55 + node-v0.8.14/deps/v8/ChangeLog | 4248 ++++++ node-v0.8.14/deps/v8/DEPS | 27 + node-v0.8.14/deps/v8/LICENSE | 54 + node-v0.8.14/deps/v8/LICENSE.strongtalk | 29 + node-v0.8.14/deps/v8/LICENSE.v8 | 26 + node-v0.8.14/deps/v8/LICENSE.valgrind | 45 + node-v0.8.14/deps/v8/Makefile | 256 + node-v0.8.14/deps/v8/SConstruct | 1617 +++ node-v0.8.14/deps/v8/benchmarks/README.txt | 86 + node-v0.8.14/deps/v8/benchmarks/base.js | 284 + node-v0.8.14/deps/v8/benchmarks/crypto.js | 1698 +++ node-v0.8.14/deps/v8/benchmarks/deltablue.js | 880 ++ .../deps/v8/benchmarks/earley-boyer.js | 4684 +++++++ .../deps/v8/benchmarks/navier-stokes.js | 387 + node-v0.8.14/deps/v8/benchmarks/raytrace.js | 904 ++ node-v0.8.14/deps/v8/benchmarks/regexp.js | 1764 +++ .../deps/v8/benchmarks/revisions.html | 104 + node-v0.8.14/deps/v8/benchmarks/richards.js | 539 + node-v0.8.14/deps/v8/benchmarks/run.html | 143 + node-v0.8.14/deps/v8/benchmarks/run.js | 62 + .../v8/benchmarks/spinning-balls/index.html | 11 + .../benchmarks/spinning-balls/splay-tree.js | 326 + .../deps/v8/benchmarks/spinning-balls/v.js | 498 + node-v0.8.14/deps/v8/benchmarks/splay.js | 394 + node-v0.8.14/deps/v8/benchmarks/style.css | 77 + node-v0.8.14/deps/v8/benchmarks/v8-logo.png | Bin 0 -> 24293 bytes node-v0.8.14/deps/v8/build/README.txt | 66 + node-v0.8.14/deps/v8/build/all.gyp | 19 + node-v0.8.14/deps/v8/build/android.gypi | 225 + node-v0.8.14/deps/v8/build/common.gypi | 391 + node-v0.8.14/deps/v8/build/gyp_v8 | 169 + node-v0.8.14/deps/v8/build/standalone.gypi | 217 + node-v0.8.14/deps/v8/include/v8-debug.h | 400 + node-v0.8.14/deps/v8/include/v8-preparser.h | 117 + node-v0.8.14/deps/v8/include/v8-profiler.h | 584 + node-v0.8.14/deps/v8/include/v8-testing.h | 104 + node-v0.8.14/deps/v8/include/v8.h | 4505 ++++++ node-v0.8.14/deps/v8/include/v8stdint.h | 54 + node-v0.8.14/deps/v8/preparser/SConscript | 38 + .../deps/v8/preparser/preparser-process.cc | 370 + node-v0.8.14/deps/v8/preparser/preparser.gyp | 42 + node-v0.8.14/deps/v8/samples/SConscript | 38 + node-v0.8.14/deps/v8/samples/count-hosts.js | 42 + node-v0.8.14/deps/v8/samples/lineprocessor.cc | 447 + node-v0.8.14/deps/v8/samples/process.cc | 622 + node-v0.8.14/deps/v8/samples/samples.gyp | 59 + node-v0.8.14/deps/v8/samples/shell.cc | 340 + node-v0.8.14/deps/v8/tools/bash-completion.sh | 55 + .../v8/tools/check-static-initializers.sh | 63 + node-v0.8.14/deps/v8/tools/codemap.js | 292 + node-v0.8.14/deps/v8/tools/common-includes.sh | 205 + node-v0.8.14/deps/v8/tools/consarray.js | 93 + node-v0.8.14/deps/v8/tools/csvparser.js | 78 + node-v0.8.14/deps/v8/tools/disasm.py | 93 + .../deps/v8/tools/freebsd-tick-processor | 10 + node-v0.8.14/deps/v8/tools/fuzz-harness.sh | 92 + .../deps/v8/tools/gc-nvp-trace-processor.py | 389 + node-v0.8.14/deps/v8/tools/gcmole/Makefile | 43 + node-v0.8.14/deps/v8/tools/gcmole/README | 62 + node-v0.8.14/deps/v8/tools/gcmole/gccause.lua | 62 + node-v0.8.14/deps/v8/tools/gcmole/gcmole.cc | 1290 ++ node-v0.8.14/deps/v8/tools/gcmole/gcmole.lua | 381 + node-v0.8.14/deps/v8/tools/gdb-v8-support.py | 154 + .../deps/v8/tools/gen-postmortem-metadata.py | 481 + .../deps/v8/tools/generate-ten-powers.scm | 286 + node-v0.8.14/deps/v8/tools/grokdump.py | 1661 +++ node-v0.8.14/deps/v8/tools/gyp/v8.gyp | 997 ++ node-v0.8.14/deps/v8/tools/js2c.py | 396 + node-v0.8.14/deps/v8/tools/jsmin.py | 282 + .../deps/v8/tools/linux-tick-processor | 40 + node-v0.8.14/deps/v8/tools/ll_prof.py | 951 ++ node-v0.8.14/deps/v8/tools/logreader.js | 184 + node-v0.8.14/deps/v8/tools/mac-nm | 18 + node-v0.8.14/deps/v8/tools/mac-tick-processor | 6 + node-v0.8.14/deps/v8/tools/merge-to-branch.sh | 280 + node-v0.8.14/deps/v8/tools/oom_dump/README | 33 + .../deps/v8/tools/oom_dump/SConstruct | 42 + .../deps/v8/tools/oom_dump/oom_dump.cc | 288 + node-v0.8.14/deps/v8/tools/presubmit.py | 388 + .../deps/v8/tools/process-heap-prof.py | 120 + node-v0.8.14/deps/v8/tools/profile.js | 795 ++ node-v0.8.14/deps/v8/tools/profile_view.js | 219 + node-v0.8.14/deps/v8/tools/push-to-trunk.sh | 401 + node-v0.8.14/deps/v8/tools/run-valgrind.py | 77 + node-v0.8.14/deps/v8/tools/splaytree.js | 327 + node-v0.8.14/deps/v8/tools/stats-viewer.py | 472 + .../deps/v8/tools/test-wrapper-gypbuild.py | 265 + node-v0.8.14/deps/v8/tools/test.py | 1557 +++ .../deps/v8/tools/tickprocessor-driver.js | 60 + node-v0.8.14/deps/v8/tools/tickprocessor.js | 871 ++ node-v0.8.14/deps/v8/tools/utils.py | 98 + .../deps/v8/tools/visual_studio/README.txt | 12 + .../deps/v8/tools/windows-tick-processor.bat | 30 + node-v0.8.14/deps/zlib/LICENSE | 25 + node-v0.8.14/deps/zlib/README.chromium | 12 + node-v0.8.14/deps/zlib/adler32.c | 149 + node-v0.8.14/deps/zlib/compress.c | 79 + .../deps/zlib/contrib/minizip/ChangeLogUnzip | 67 + .../deps/zlib/contrib/minizip/Makefile | 25 + .../deps/zlib/contrib/minizip/crypt.h | 132 + .../deps/zlib/contrib/minizip/ioapi.c | 180 + .../deps/zlib/contrib/minizip/ioapi.h | 75 + .../deps/zlib/contrib/minizip/iowin32.c | 270 + .../deps/zlib/contrib/minizip/iowin32.h | 21 + .../deps/zlib/contrib/minizip/miniunz.c | 585 + .../deps/zlib/contrib/minizip/minizip.c | 420 + .../deps/zlib/contrib/minizip/mztools.c | 286 + .../deps/zlib/contrib/minizip/mztools.h | 33 + .../deps/zlib/contrib/minizip/unzip.c | 1606 +++ .../deps/zlib/contrib/minizip/unzip.h | 356 + node-v0.8.14/deps/zlib/contrib/minizip/zip.c | 1223 ++ node-v0.8.14/deps/zlib/contrib/minizip/zip.h | 237 + node-v0.8.14/deps/zlib/crc32.c | 423 + node-v0.8.14/deps/zlib/crc32.h | 441 + node-v0.8.14/deps/zlib/deflate.c | 1736 +++ node-v0.8.14/deps/zlib/deflate.h | 331 + node-v0.8.14/deps/zlib/gzio.c | 1033 ++ node-v0.8.14/deps/zlib/infback.c | 623 + node-v0.8.14/deps/zlib/inffast.c | 318 + node-v0.8.14/deps/zlib/inffast.h | 11 + node-v0.8.14/deps/zlib/inffixed.h | 94 + node-v0.8.14/deps/zlib/inflate.c | 1368 ++ node-v0.8.14/deps/zlib/inflate.h | 115 + node-v0.8.14/deps/zlib/inftrees.c | 329 + node-v0.8.14/deps/zlib/inftrees.h | 55 + node-v0.8.14/deps/zlib/mozzconf.h | 130 + node-v0.8.14/deps/zlib/trees.c | 1219 ++ node-v0.8.14/deps/zlib/trees.h | 128 + node-v0.8.14/deps/zlib/uncompr.c | 61 + node-v0.8.14/deps/zlib/zconf.h | 335 + node-v0.8.14/deps/zlib/zlib.gyp | 99 + node-v0.8.14/deps/zlib/zlib.h | 1357 ++ node-v0.8.14/deps/zlib/zutil.c | 320 + node-v0.8.14/deps/zlib/zutil.h | 269 + node-v0.8.14/doc/about/index.html | 146 + node-v0.8.14/doc/api/_toc.html | 124 + node-v0.8.14/doc/api/_toc.json | 372 + node-v0.8.14/doc/api/_toc.markdown | 36 + node-v0.8.14/doc/api/addons.html | 721 + node-v0.8.14/doc/api/addons.json | 79 + node-v0.8.14/doc/api/addons.markdown | 624 + node-v0.8.14/doc/api/all.html | 11221 +++++++++++++++ node-v0.8.14/doc/api/all.json | 11543 ++++++++++++++++ node-v0.8.14/doc/api/all.markdown | 36 + node-v0.8.14/doc/api/assert.html | 185 + node-v0.8.14/doc/api/assert.json | 258 + node-v0.8.14/doc/api/assert.markdown | 84 + node-v0.8.14/doc/api/assets/sh.css | 24 + node-v0.8.14/doc/api/assets/style.css | 518 + node-v0.8.14/doc/api/buffer.html | 865 ++ node-v0.8.14/doc/api/buffer.json | 1740 +++ node-v0.8.14/doc/api/buffer.markdown | 668 + node-v0.8.14/doc/api/child_process.html | 699 + node-v0.8.14/doc/api/child_process.json | 554 + node-v0.8.14/doc/api/child_process.markdown | 537 + node-v0.8.14/doc/api/cluster.html | 655 + node-v0.8.14/doc/api/cluster.json | 346 + node-v0.8.14/doc/api/cluster.markdown | 512 + node-v0.8.14/doc/api/crypto.html | 580 + node-v0.8.14/doc/api/crypto.json | 720 + node-v0.8.14/doc/api/crypto.markdown | 406 + node-v0.8.14/doc/api/debugger.html | 238 + node-v0.8.14/doc/api/debugger.json | 51 + node-v0.8.14/doc/api/debugger.markdown | 138 + node-v0.8.14/doc/api/dgram.html | 338 + node-v0.8.14/doc/api/dgram.json | 381 + node-v0.8.14/doc/api/dgram.markdown | 209 + node-v0.8.14/doc/api/dns.html | 257 + node-v0.8.14/doc/api/dns.json | 213 + node-v0.8.14/doc/api/dns.markdown | 148 + node-v0.8.14/doc/api/documentation.html | 171 + node-v0.8.14/doc/api/documentation.json | 28 + node-v0.8.14/doc/api/documentation.markdown | 68 + node-v0.8.14/doc/api/domain.html | 394 + node-v0.8.14/doc/api/domain.json | 219 + node-v0.8.14/doc/api/domain.markdown | 268 + node-v0.8.14/doc/api/events.html | 217 + node-v0.8.14/doc/api/events.json | 187 + node-v0.8.14/doc/api/events.markdown | 111 + node-v0.8.14/doc/api/fs.html | 880 ++ node-v0.8.14/doc/api/fs.json | 1496 ++ node-v0.8.14/doc/api/fs.markdown | 678 + node-v0.8.14/doc/api/globals.html | 306 + node-v0.8.14/doc/api/globals.json | 295 + node-v0.8.14/doc/api/globals.markdown | 184 + node-v0.8.14/doc/api/http.html | 1164 ++ node-v0.8.14/doc/api/http.json | 793 ++ node-v0.8.14/doc/api/http.markdown | 936 ++ node-v0.8.14/doc/api/https.html | 316 + node-v0.8.14/doc/api/https.json | 159 + node-v0.8.14/doc/api/https.markdown | 213 + node-v0.8.14/doc/api/index.html | 124 + node-v0.8.14/doc/api/index.json | 375 + node-v0.8.14/doc/api/index.markdown | 1 + node-v0.8.14/doc/api/modules.html | 618 + node-v0.8.14/doc/api/modules.json | 156 + node-v0.8.14/doc/api/modules.markdown | 461 + node-v0.8.14/doc/api/net.html | 664 + node-v0.8.14/doc/api/net.json | 712 + node-v0.8.14/doc/api/net.markdown | 485 + node-v0.8.14/doc/api/os.html | 241 + node-v0.8.14/doc/api/os.json | 155 + node-v0.8.14/doc/api/os.markdown | 138 + node-v0.8.14/doc/api/path.html | 258 + node-v0.8.14/doc/api/path.json | 148 + node-v0.8.14/doc/api/path.markdown | 156 + node-v0.8.14/doc/api/process.html | 537 + node-v0.8.14/doc/api/process.json | 291 + node-v0.8.14/doc/api/process.markdown | 432 + node-v0.8.14/doc/api/punycode.html | 163 + node-v0.8.14/doc/api/punycode.json | 103 + node-v0.8.14/doc/api/punycode.markdown | 70 + node-v0.8.14/doc/api/querystring.html | 144 + node-v0.8.14/doc/api/querystring.json | 78 + node-v0.8.14/doc/api/querystring.markdown | 49 + node-v0.8.14/doc/api/readline.html | 417 + node-v0.8.14/doc/api/readline.json | 204 + node-v0.8.14/doc/api/readline.markdown | 283 + node-v0.8.14/doc/api/repl.html | 299 + node-v0.8.14/doc/api/repl.json | 46 + node-v0.8.14/doc/api/repl.markdown | 188 + node-v0.8.14/doc/api/stdio.html | 159 + node-v0.8.14/doc/api/stdio.json | 174 + node-v0.8.14/doc/api/stdio.markdown | 62 + node-v0.8.14/doc/api/stream.html | 322 + node-v0.8.14/doc/api/stream.json | 274 + node-v0.8.14/doc/api/stream.markdown | 192 + node-v0.8.14/doc/api/string_decoder.html | 116 + node-v0.8.14/doc/api/string_decoder.json | 39 + node-v0.8.14/doc/api/string_decoder.markdown | 24 + node-v0.8.14/doc/api/synopsis.html | 112 + node-v0.8.14/doc/api/synopsis.json | 11 + node-v0.8.14/doc/api/synopsis.markdown | 23 + node-v0.8.14/doc/api/timers.html | 126 + node-v0.8.14/doc/api/timers.json | 98 + node-v0.8.14/doc/api/timers.markdown | 31 + node-v0.8.14/doc/api/tls.html | 645 + node-v0.8.14/doc/api/tls.json | 330 + node-v0.8.14/doc/api/tls.markdown | 508 + node-v0.8.14/doc/api/tty.html | 178 + node-v0.8.14/doc/api/tty.json | 108 + node-v0.8.14/doc/api/tty.markdown | 75 + node-v0.8.14/doc/api/url.html | 191 + node-v0.8.14/doc/api/url.json | 72 + node-v0.8.14/doc/api/url.markdown | 99 + node-v0.8.14/doc/api/util.html | 299 + node-v0.8.14/doc/api/util.json | 242 + node-v0.8.14/doc/api/util.markdown | 203 + node-v0.8.14/doc/api/vm.html | 336 + node-v0.8.14/doc/api/vm.json | 177 + node-v0.8.14/doc/api/vm.markdown | 220 + node-v0.8.14/doc/api/zlib.html | 474 + node-v0.8.14/doc/api/zlib.json | 324 + node-v0.8.14/doc/api/zlib.markdown | 333 + node-v0.8.14/doc/api_assets/sh.css | 24 + node-v0.8.14/doc/api_assets/style.css | 518 + node-v0.8.14/doc/blog.html | 240 + node-v0.8.14/doc/blog/README.md | 28 + ...-way-to-build-scalable-network-programs.md | 16 + .../Uncategorized/development-environment.md | 25 + .../evolving-the-node-js-brand.md | 34 + .../doc/blog/Uncategorized/growing-up.md | 12 + .../doc/blog/Uncategorized/jobs-nodejs-org.md | 14 + .../Uncategorized/ldapjs-a-reprise-of-ldap.md | 84 + .../blog/Uncategorized/libuv-status-report.md | 45 + .../node-meetup-this-thursday.md | 11 + .../node-office-hours-cut-short.md | 12 + .../doc/blog/Uncategorized/office-hours.md | 12 + ...o-windows-with-microsoft%e2%80%99s-help.md | 12 + .../blog/Uncategorized/profiling-node-js.md | 60 + .../Uncategorized/some-new-node-projects.md | 13 + .../the-videos-from-node-meetup.md | 10 + .../doc/blog/Uncategorized/trademark.md | 17 + .../doc/blog/Uncategorized/version-0-6.md | 12 + ...server-continuous-deployment-with-fleet.md | 89 + .../service-logging-in-json-with-bunyan.md | 337 + ...ng-node-js-dependencies-with-shrinkwrap.md | 167 + .../npm-1-0-global-vs-local-installation.md | 64 + node-v0.8.14/doc/blog/npm/npm-1-0-link.md | 114 + node-v0.8.14/doc/blog/npm/npm-1-0-released.md | 36 + .../doc/blog/npm/npm-1-0-the-new-ls.md | 144 + node-v0.8.14/doc/blog/release/0.6.21.md | 43 + node-v0.8.14/doc/blog/release/node-v0-4-10.md | 25 + node-v0.8.14/doc/blog/release/node-v0-4-11.md | 39 + node-v0.8.14/doc/blog/release/node-v0-4-12.md | 29 + node-v0.8.14/doc/blog/release/node-v0-4-3.md | 33 + node-v0.8.14/doc/blog/release/node-v0-4-4.md | 27 + node-v0.8.14/doc/blog/release/node-v0-4-5.md | 29 + node-v0.8.14/doc/blog/release/node-v0-4-6.md | 27 + node-v0.8.14/doc/blog/release/node-v0-4-7.md | 23 + node-v0.8.14/doc/blog/release/node-v0-4-8.md | 55 + node-v0.8.14/doc/blog/release/node-v0-4-9.md | 30 + .../doc/blog/release/node-v0-5-0-unstable.md | 39 + node-v0.8.14/doc/blog/release/node-v0-5-1.md | 30 + node-v0.8.14/doc/blog/release/node-v0-5-10.md | 41 + node-v0.8.14/doc/blog/release/node-v0-5-2.md | 27 + node-v0.8.14/doc/blog/release/node-v0-5-3.md | 53 + node-v0.8.14/doc/blog/release/node-v0-5-4.md | 36 + node-v0.8.14/doc/blog/release/node-v0-5-5.md | 40 + node-v0.8.14/doc/blog/release/node-v0-5-6.md | 49 + .../doc/blog/release/node-v0-5-7-unstable.md | 35 + node-v0.8.14/doc/blog/release/node-v0-5-8.md | 26 + node-v0.8.14/doc/blog/release/node-v0-5-9.md | 27 + node-v0.8.14/doc/blog/release/node-v0-6-0.md | 80 + node-v0.8.14/doc/blog/release/node-v0-6-1.md | 33 + node-v0.8.14/doc/blog/release/node-v0-6-10.md | 30 + node-v0.8.14/doc/blog/release/node-v0-6-2.md | 27 + node-v0.8.14/doc/blog/release/node-v0-6-3.md | 30 + node-v0.8.14/doc/blog/release/node-v0-6-4.md | 31 + node-v0.8.14/doc/blog/release/node-v0-6-5.md | 21 + node-v0.8.14/doc/blog/release/node-v0-6-6.md | 32 + node-v0.8.14/doc/blog/release/node-v0-6-7.md | 41 + node-v0.8.14/doc/blog/release/node-v0-6-8.md | 31 + node-v0.8.14/doc/blog/release/node-v0-6-9.md | 30 + .../doc/blog/release/node-v0-7-0-unstable.md | 29 + node-v0.8.14/doc/blog/release/node-v0-7-1.md | 30 + .../doc/blog/release/node-v0-7-2-unstable.md | 32 + node-v0.8.14/doc/blog/release/node-v0-7-3.md | 39 + node-v0.8.14/doc/blog/release/node-v0.8.0.md | 384 + .../release/node-version-0-6-19-stable.md | 61 + .../release/node-version-0-7-9-unstable.md | 73 + node-v0.8.14/doc/blog/release/v0.6.20.md | 51 + node-v0.8.14/doc/blog/release/v0.8.1.md | 77 + node-v0.8.14/doc/blog/release/v0.8.10.md | 93 + node-v0.8.14/doc/blog/release/v0.8.11.md | 63 + node-v0.8.14/doc/blog/release/v0.8.12.md | 73 + node-v0.8.14/doc/blog/release/v0.8.13.md | 72 + node-v0.8.14/doc/blog/release/v0.8.2.md | 73 + node-v0.8.14/doc/blog/release/v0.8.3.md | 71 + node-v0.8.14/doc/blog/release/v0.8.4.md | 59 + node-v0.8.14/doc/blog/release/v0.8.5.md | 77 + node-v0.8.14/doc/blog/release/v0.8.6.md | 85 + node-v0.8.14/doc/blog/release/v0.8.7.md | 75 + node-v0.8.14/doc/blog/release/v0.8.8.md | 77 + node-v0.8.14/doc/blog/release/v0.8.9.md | 97 + node-v0.8.14/doc/blog/release/v0.9.1.md | 116 + node-v0.8.14/doc/blog/release/v0.9.2.md | 95 + node-v0.8.14/doc/blog/release/v0.9.3.md | 87 + .../doc/blog/release/version-0-6-11-stable.md | 64 + .../doc/blog/release/version-0-6-12-stable.md | 66 + .../doc/blog/release/version-0-6-13-stable.md | 50 + .../doc/blog/release/version-0-6-14-stable.md | 55 + .../doc/blog/release/version-0-6-15-stable.md | 53 + .../doc/blog/release/version-0-6-16-stable.md | 59 + .../doc/blog/release/version-0-6-17-stable.md | 47 + .../doc/blog/release/version-0-6-18-stable.md | 59 + .../blog/release/version-0-7-10-unstable.md | 86 + .../blog/release/version-0-7-11-unstable.md | 80 + .../doc/blog/release/version-0-7-12.md | 56 + .../blog/release/version-0-7-4-unstable.md | 50 + .../blog/release/version-0-7-5-unstable.md | 62 + .../blog/release/version-0-7-6-unstable.md | 72 + .../blog/release/version-0-7-7-unstable.md | 71 + .../blog/release/version-0-7-8-unstable.md | 71 + .../blog/video/bert-belder-libuv-lxjs-2012.md | 13 + ...antrill-instrumenting-the-real-time-web.md | 42 + .../blog/video/welcome-to-the-node-blog.md | 13 + ...-vulnerability-please-upgrade-to-0-6-17.md | 45 + node-v0.8.14/doc/changelog-foot.html | 35 + node-v0.8.14/doc/changelog-head.html | 38 + node-v0.8.14/doc/cla.html | 193 + node-v0.8.14/doc/community/index.html | 247 + node-v0.8.14/doc/download/index.html | 158 + node-v0.8.14/doc/favicon.ico | Bin 0 -> 1150 bytes node-v0.8.14/doc/full-white-stripe.jpg | Bin 0 -> 4383 bytes node-v0.8.14/doc/index.html | 196 + node-v0.8.14/doc/logos/index.html | 92 + .../doc/mac_osx_nodejs_installer_logo.png | Bin 0 -> 23317 bytes node-v0.8.14/doc/node.1 | 446 + node-v0.8.14/doc/pipe.css | 658 + node-v0.8.14/doc/robots.txt | 6 + node-v0.8.14/doc/rss.xml | 45 + node-v0.8.14/doc/sh.css | 24 + node-v0.8.14/doc/sh_javascript.min.js | 1 + node-v0.8.14/doc/sh_main.js | 553 + node-v0.8.14/doc/sh_vim-dark.css | 33 + node-v0.8.14/doc/template.html | 85 + node-v0.8.14/doc/thin-white-stripe.jpg | Bin 0 -> 3316 bytes node-v0.8.14/doc/trademark-policy.pdf | Bin 0 -> 111996 bytes node-v0.8.14/doc/v0.4_announcement.html | 98 + node-v0.8.14/lib/_debugger.js | 1698 +++ node-v0.8.14/lib/_linklist.js | 76 + node-v0.8.14/lib/assert.js | 334 + node-v0.8.14/lib/buffer.js | 1157 ++ node-v0.8.14/lib/buffer_ieee754.js | 116 + node-v0.8.14/lib/child_process.js | 902 ++ node-v0.8.14/lib/cluster.js | 558 + node-v0.8.14/lib/console.js | 77 + node-v0.8.14/lib/constants.js | 22 + node-v0.8.14/lib/crypto.js | 195 + node-v0.8.14/lib/dgram.js | 360 + node-v0.8.14/lib/dns.js | 217 + node-v0.8.14/lib/domain.js | 258 + node-v0.8.14/lib/events.js | 253 + node-v0.8.14/lib/freelist.js | 43 + node-v0.8.14/lib/fs.js | 1671 +++ node-v0.8.14/lib/http.js | 1861 +++ node-v0.8.14/lib/https.js | 112 + node-v0.8.14/lib/module.js | 522 + node-v0.8.14/lib/net.js | 1147 ++ node-v0.8.14/lib/os.js | 54 + node-v0.8.14/lib/path.js | 453 + node-v0.8.14/lib/punycode.js | 512 + node-v0.8.14/lib/querystring.js | 215 + node-v0.8.14/lib/readline.js | 1132 ++ node-v0.8.14/lib/repl.js | 921 ++ node-v0.8.14/lib/stream.js | 116 + node-v0.8.14/lib/string_decoder.js | 156 + node-v0.8.14/lib/sys.js | 24 + node-v0.8.14/lib/timers.js | 247 + node-v0.8.14/lib/tls.js | 1337 ++ node-v0.8.14/lib/tty.js | 139 + node-v0.8.14/lib/url.js | 625 + node-v0.8.14/lib/util.js | 562 + node-v0.8.14/lib/vm.js | 54 + node-v0.8.14/lib/zlib.js | 467 + node-v0.8.14/node.gyp | 385 + node-v0.8.14/test/addons/.gitignore | 5 + node-v0.8.14/test/addons/at-exit/binding.cc | 43 + node-v0.8.14/test/addons/at-exit/binding.gyp | 8 + node-v0.8.14/test/addons/at-exit/test.js | 1 + .../test/addons/hello-world/binding.cc | 15 + .../test/addons/hello-world/binding.gyp | 8 + node-v0.8.14/test/addons/hello-world/test.js | 4 + node-v0.8.14/test/common.js | 146 + node-v0.8.14/test/disabled/GH-670.js | 59 + node-v0.8.14/test/disabled/test-cat.js | 76 + .../disabled/test-child-process-custom-fds.js | 117 + .../disabled/test-child-process-uid-gid.js | 83 + .../test/disabled/test-dgram-multicast.js | 119 + .../test/disabled/test-dgram-unix-anon.js | 81 + node-v0.8.14/test/disabled/test-dgram-unix.js | 75 + node-v0.8.14/test/disabled/test-dns.js | 231 + node-v0.8.14/test/disabled/test-eio-race3.js | 43 + .../test/disabled/test-fs-sendfile.js | 52 + .../test/disabled/test-http-agent2.js | 87 + .../disabled/test-http-big-proxy-responses.js | 135 + .../test/disabled/test-http-default-port.js | 68 + .../test/disabled/test-http-head-request.js | 67 + .../test/disabled/test-http-stress.js | 66 + node-v0.8.14/test/disabled/test-http-tls.js | 178 + .../disabled/test-https-loop-to-google.js | 56 + .../test/disabled/test-idle-watcher.js | 39 + .../test/disabled/test-net-fd-passing.js | 94 + .../test/disabled/test-net-tls-pummel.js | 150 + node-v0.8.14/test/disabled/test-net-tls.js | 135 + .../test/disabled/test-process-title.js | 63 + node-v0.8.14/test/disabled/test-readline.js | 136 + .../disabled/test-remote-module-loading.js | 62 + node-v0.8.14/test/disabled/test-sendfd.js | 149 + node-v0.8.14/test/disabled/test-setuidgid.js | 46 + .../test/disabled/test-tls-large-push.js | 87 + node-v0.8.14/test/disabled/test-tls-server.js | 59 + node-v0.8.14/test/disabled/test-tty-stdio.js | 36 + node-v0.8.14/test/disabled/tls-client.js | 46 + node-v0.8.14/test/disabled/tls_client.js | 67 + node-v0.8.14/test/disabled/tls_server.js | 70 + node-v0.8.14/test/fixtures/GH-1899-output.js | 23 + node-v0.8.14/test/fixtures/GH-892-request.js | 48 + node-v0.8.14/test/fixtures/a.js | 46 + node-v0.8.14/test/fixtures/a1.js | 46 + node-v0.8.14/test/fixtures/agent.crt | 21 + node-v0.8.14/test/fixtures/agent.key | 27 + node-v0.8.14/test/fixtures/alice.crt | 24 + node-v0.8.14/test/fixtures/b/c.js | 49 + node-v0.8.14/test/fixtures/b/d.js | 33 + node-v0.8.14/test/fixtures/b/package/index.js | 23 + node-v0.8.14/test/fixtures/breakpoints.js | 23 + .../test/fixtures/breakpoints_utf8.js | 19 + .../test/fixtures/catch-stdout-error.js | 38 + node-v0.8.14/test/fixtures/cert.pem | 35 + .../child-process-message-and-exit.js | 3 + .../test/fixtures/child-process-persistent.js | 1 + .../test/fixtures/child-process-spawn-node.js | 10 + .../child_process_should_emit_error.js | 29 + node-v0.8.14/test/fixtures/create-file.js | 29 + .../test/fixtures/cycles/folder/foo.js | 27 + node-v0.8.14/test/fixtures/cycles/root.js | 31 + node-v0.8.14/test/fixtures/deprecated.js | 1 + node-v0.8.14/test/fixtures/destroy-stdin.js | 1 + node-v0.8.14/test/fixtures/echo.js | 31 + node-v0.8.14/test/fixtures/elipses.txt | 1 + node-v0.8.14/test/fixtures/empty.js | 0 node-v0.8.14/test/fixtures/empty.txt | 0 node-v0.8.14/test/fixtures/empty/.gitkeep | 0 node-v0.8.14/test/fixtures/exit.js | 22 + node-v0.8.14/test/fixtures/fixture.ini | 19 + node-v0.8.14/test/fixtures/foafssl.crt | 25 + node-v0.8.14/test/fixtures/foafssl.key | 32 + node-v0.8.14/test/fixtures/foo | 2 + node-v0.8.14/test/fixtures/fork2.js | 23 + node-v0.8.14/test/fixtures/global/plain.js | 25 + node-v0.8.14/test/fixtures/invalid.json | 5 + node-v0.8.14/test/fixtures/keys/Makefile | 139 + .../test/fixtures/keys/agent1-cert.pem | 14 + .../test/fixtures/keys/agent1-csr.pem | 10 + .../test/fixtures/keys/agent1-key.pem | 9 + node-v0.8.14/test/fixtures/keys/agent1.cnf | 19 + .../test/fixtures/keys/agent2-cert.pem | 13 + .../test/fixtures/keys/agent2-csr.pem | 10 + .../test/fixtures/keys/agent2-key.pem | 9 + node-v0.8.14/test/fixtures/keys/agent2.cnf | 19 + .../test/fixtures/keys/agent3-cert.pem | 14 + .../test/fixtures/keys/agent3-csr.pem | 10 + .../test/fixtures/keys/agent3-key.pem | 9 + node-v0.8.14/test/fixtures/keys/agent3.cnf | 19 + .../test/fixtures/keys/agent4-cert.pem | 15 + .../test/fixtures/keys/agent4-csr.pem | 10 + .../test/fixtures/keys/agent4-key.pem | 9 + node-v0.8.14/test/fixtures/keys/agent4.cnf | 21 + node-v0.8.14/test/fixtures/keys/ca1-cert.pem | 15 + node-v0.8.14/test/fixtures/keys/ca1-cert.srl | 1 + node-v0.8.14/test/fixtures/keys/ca1-key.pem | 17 + node-v0.8.14/test/fixtures/keys/ca1.cnf | 20 + node-v0.8.14/test/fixtures/keys/ca2-cert.pem | 15 + node-v0.8.14/test/fixtures/keys/ca2-cert.srl | 1 + node-v0.8.14/test/fixtures/keys/ca2-crl.pem | 10 + .../test/fixtures/keys/ca2-database.txt | 1 + node-v0.8.14/test/fixtures/keys/ca2-key.pem | 17 + node-v0.8.14/test/fixtures/keys/ca2-serial | 1 + node-v0.8.14/test/fixtures/keys/ca2.cnf | 33 + .../test/fixtures/module-load-order/file1 | 1 + .../test/fixtures/module-load-order/file1.js | 22 + .../fixtures/module-load-order/file1.node | 1 + .../test/fixtures/module-load-order/file1.reg | 1 + .../fixtures/module-load-order/file1.reg2 | 1 + .../test/fixtures/module-load-order/file2.js | 22 + .../fixtures/module-load-order/file2.node | 1 + .../test/fixtures/module-load-order/file2.reg | 1 + .../fixtures/module-load-order/file2.reg2 | 1 + .../fixtures/module-load-order/file2/index.js | 22 + .../module-load-order/file2/index.node | 1 + .../module-load-order/file2/index.reg | 1 + .../module-load-order/file2/index.reg2 | 1 + .../fixtures/module-load-order/file3.node | 1 + .../test/fixtures/module-load-order/file3.reg | 1 + .../fixtures/module-load-order/file3.reg2 | 1 + .../fixtures/module-load-order/file3/index.js | 22 + .../module-load-order/file3/index.node | 1 + .../module-load-order/file3/index.reg | 1 + .../module-load-order/file3/index.reg2 | 1 + .../test/fixtures/module-load-order/file4.reg | 1 + .../fixtures/module-load-order/file4.reg2 | 1 + .../fixtures/module-load-order/file4/index.js | 22 + .../module-load-order/file4/index.node | 1 + .../module-load-order/file4/index.reg | 1 + .../module-load-order/file4/index.reg2 | 1 + .../fixtures/module-load-order/file5.reg2 | 1 + .../fixtures/module-load-order/file5/index.js | 22 + .../module-load-order/file5/index.node | 1 + .../module-load-order/file5/index.reg | 1 + .../module-load-order/file5/index.reg2 | 1 + .../fixtures/module-load-order/file6/index.js | 22 + .../module-load-order/file6/index.node | 1 + .../module-load-order/file6/index.reg | 1 + .../module-load-order/file6/index.reg2 | 1 + .../module-load-order/file7/index.node | 1 + .../module-load-order/file7/index.reg | 1 + .../module-load-order/file7/index.reg2 | 1 + .../module-load-order/file8/index.reg | 1 + .../module-load-order/file8/index.reg2 | 1 + .../module-load-order/file9/index.reg2 | 1 + .../test/fixtures/module-loading-error.node | 1 + .../fixtures/module-require/child/index.js | 2 + .../fixtures/module-require/parent/index.js | 5 + node-v0.8.14/test/fixtures/msca.pem | 15 + node-v0.8.14/test/fixtures/multi-alice.crt | 22 + .../test/fixtures/nested-index/one/hello.js | 23 + .../test/fixtures/nested-index/one/index.js | 22 + .../test/fixtures/nested-index/three.js | 21 + .../test/fixtures/nested-index/three/index.js | 21 + .../test/fixtures/nested-index/two/hello.js | 23 + .../test/fixtures/nested-index/two/index.js | 22 + .../test/fixtures/net-fd-passing-receiver.js | 53 + node-v0.8.14/test/fixtures/not-main-module.js | 25 + .../main-index/package-main-module/index.js | 22 + .../fixtures/packages/main-index/package.json | 3 + .../packages/main/package-main-module.js | 22 + .../test/fixtures/packages/main/package.json | 3 + .../fixtures/parent-process-nonpersistent.js | 13 + node-v0.8.14/test/fixtures/pass-cert.pem | 12 + node-v0.8.14/test/fixtures/pass-csr.pem | 10 + node-v0.8.14/test/fixtures/pass-key.pem | 18 + node-v0.8.14/test/fixtures/person.jpg | Bin 0 -> 57928 bytes node-v0.8.14/test/fixtures/person.jpg.gz | Bin 0 -> 50187 bytes node-v0.8.14/test/fixtures/print-10-lines.js | 24 + .../test/fixtures/print-chars-from-buffer.js | 32 + node-v0.8.14/test/fixtures/print-chars.js | 32 + node-v0.8.14/test/fixtures/readdir/are | 0 node-v0.8.14/test/fixtures/readdir/dir/empty | 0 node-v0.8.14/test/fixtures/readdir/empty | 0 node-v0.8.14/test/fixtures/readdir/files | 0 node-v0.8.14/test/fixtures/readdir/for | 0 node-v0.8.14/test/fixtures/readdir/just | 0 node-v0.8.14/test/fixtures/readdir/testing.js | 21 + node-v0.8.14/test/fixtures/readdir/these | 0 node-v0.8.14/test/fixtures/recvfd.js | 77 + .../test/fixtures/registerExt.hello.world | 1 + node-v0.8.14/test/fixtures/registerExt.test | 1 + node-v0.8.14/test/fixtures/registerExt2.test | 1 + node-v0.8.14/test/fixtures/sample.png | Bin 0 -> 9416 bytes node-v0.8.14/test/fixtures/semicolon.js | 22 + node-v0.8.14/test/fixtures/should_exit.js | 27 + node-v0.8.14/test/fixtures/stdio-filter.js | 32 + .../test/fixtures/test-init-index/index.js | 25 + .../test/fixtures/test-init-native/fs.js | 28 + .../test/fixtures/test-regress-GH-4015.js | 7 + node-v0.8.14/test/fixtures/test_ca.pem | 20 + node-v0.8.14/test/fixtures/test_cert.pem | 20 + node-v0.8.14/test/fixtures/test_cert.pfx | Bin 0 -> 1970 bytes .../test/fixtures/test_dsa_params.pem | 14 + .../test/fixtures/test_dsa_privkey.pem | 20 + .../test/fixtures/test_dsa_pubkey.pem | 20 + node-v0.8.14/test/fixtures/test_key.pem | 15 + .../test/fixtures/test_rsa_privkey.pem | 15 + .../test/fixtures/test_rsa_privkey_2.pem | 15 + .../test/fixtures/test_rsa_pubkey.pem | 6 + .../test/fixtures/test_rsa_pubkey_2.pem | 5 + node-v0.8.14/test/fixtures/throws_error.js | 22 + node-v0.8.14/test/fixtures/throws_error1.js | 22 + node-v0.8.14/test/fixtures/throws_error2.js | 24 + node-v0.8.14/test/fixtures/throws_error3.js | 24 + node-v0.8.14/test/fixtures/utf8-bom.js | 1 + node-v0.8.14/test/fixtures/utf8-bom.json | 1 + node-v0.8.14/test/fixtures/x.txt | 1 + .../test/gc/test-http-client-connaborted.js | 64 + .../test/gc/test-http-client-onerror.js | 69 + .../test/gc/test-http-client-timeout.js | 72 + node-v0.8.14/test/gc/test-http-client.js | 67 + node-v0.8.14/test/gc/test-net-timeout.js | 69 + node-v0.8.14/test/gc/testcfg.py | 133 + node-v0.8.14/test/internet/internet.status | 1 + node-v0.8.14/test/internet/test-dns.js | 405 + node-v0.8.14/test/internet/testcfg.py | 132 + node-v0.8.14/test/message/2100bytes.js | 73 + node-v0.8.14/test/message/2100bytes.out | 42 + node-v0.8.14/test/message/eval_messages.js | 53 + node-v0.8.14/test/message/eval_messages.out | 58 + node-v0.8.14/test/message/hello_world.js | 28 + node-v0.8.14/test/message/hello_world.out | 1 + node-v0.8.14/test/message/stack_overflow.js | 36 + node-v0.8.14/test/message/stack_overflow.out | 6 + node-v0.8.14/test/message/stdin_messages.js | 54 + node-v0.8.14/test/message/stdin_messages.out | 62 + node-v0.8.14/test/message/testcfg.py | 145 + .../test/message/throw_custom_error.js | 33 + .../test/message/throw_custom_error.out | 6 + .../test/message/throw_in_line_with_tabs.js | 35 + .../test/message/throw_in_line_with_tabs.out | 6 + node-v0.8.14/test/message/throw_non_error.js | 33 + node-v0.8.14/test/message/throw_non_error.out | 6 + .../undefined_reference_in_new_context.js | 36 + .../undefined_reference_in_new_context.out | 14 + node-v0.8.14/test/pummel/pummel.status | 1 + node-v0.8.14/test/pummel/test-buffer-big.js | 29 + .../pummel/test-child-process-spawn-loop.js | 64 + node-v0.8.14/test/pummel/test-crypto-dh.js | 70 + .../test/pummel/test-debugger-debug-brk.js | 49 + node-v0.8.14/test/pummel/test-dh-regr.js | 41 + node-v0.8.14/test/pummel/test-exec.js | 123 + node-v0.8.14/test/pummel/test-fs-largefile.js | 58 + .../test/pummel/test-fs-watch-file-slow.js | 73 + .../test/pummel/test-fs-watch-file.js | 128 + .../pummel/test-http-client-reconnect-bug.js | 69 + .../test/pummel/test-http-upload-timeout.js | 69 + .../test/pummel/test-https-ci-reneg-attack.js | 106 + .../test/pummel/test-https-large-response.js | 84 + node-v0.8.14/test/pummel/test-keep-alive.js | 90 + .../pummel/test-net-connect-econnrefused.js | 64 + .../test/pummel/test-net-many-clients.js | 104 + node-v0.8.14/test/pummel/test-net-pause.js | 89 + .../test/pummel/test-net-pingpong-delay.js | 114 + node-v0.8.14/test/pummel/test-net-pingpong.js | 123 + node-v0.8.14/test/pummel/test-net-throttle.js | 87 + node-v0.8.14/test/pummel/test-net-timeout.js | 109 + node-v0.8.14/test/pummel/test-net-timeout2.js | 65 + .../test/pummel/test-net-write-callbacks.js | 56 + .../test/pummel/test-next-tick-loops-quick.js | 48 + .../test/pummel/test-process-hrtime.js | 40 + .../test/pummel/test-process-uptime.js | 39 + .../test/pummel/test-regress-GH-814.js | 92 + .../test/pummel/test-regress-GH-814_2.js | 106 + .../test/pummel/test-regress-GH-892.js | 108 + node-v0.8.14/test/pummel/test-timer-wrap.js | 40 + node-v0.8.14/test/pummel/test-timer-wrap2.js | 29 + node-v0.8.14/test/pummel/test-timers.js | 128 + .../test/pummel/test-tls-ci-reneg-attack.js | 104 + node-v0.8.14/test/pummel/test-tls-throttle.js | 92 + node-v0.8.14/test/pummel/test-vm-memleak.js | 48 + node-v0.8.14/test/pummel/test-watch-file.js | 54 + node-v0.8.14/test/pummel/testcfg.py | 130 + node-v0.8.14/test/simple/path.js | 32 + node-v0.8.14/test/simple/simple.status | 1 + node-v0.8.14/test/simple/test-assert.js | 295 + node-v0.8.14/test/simple/test-bad-unicode.js | 31 + .../test/simple/test-buffer-concat.js | 41 + .../simple/test-buffer-regress-GH-2659.js | 30 + node-v0.8.14/test/simple/test-buffer.js | 739 + node-v0.8.14/test/simple/test-c-ares.js | 53 + node-v0.8.14/test/simple/test-chdir.js | 40 + .../simple/test-child-process-buffering.js | 65 + .../test-child-process-customfd-bounded.js | 29 + .../test/simple/test-child-process-cwd.js | 81 + .../simple/test-child-process-detached.js | 45 + .../simple/test-child-process-disconnect.js | 106 + .../simple/test-child-process-double-pipe.js | 117 + .../test/simple/test-child-process-env.js | 55 + .../simple/test-child-process-exec-cwd.js | 56 + .../simple/test-child-process-exec-env.js | 62 + .../simple/test-child-process-exit-code.js | 53 + .../test-child-process-fork-and-spawn.js | 53 + .../simple/test-child-process-fork-close.js | 57 + .../test-child-process-fork-exec-argv.js | 47 + .../simple/test-child-process-fork-net.js | 205 + .../simple/test-child-process-fork-net2.js | 131 + .../test/simple/test-child-process-fork.js | 52 + .../test/simple/test-child-process-fork2.js | 73 + .../simple/test-child-process-internal.js | 58 + .../test/simple/test-child-process-ipc.js | 63 + .../simple/test-child-process-kill-throw.js | 50 + .../test/simple/test-child-process-kill.js | 66 + .../simple/test-child-process-set-blocking.js | 40 + .../test/simple/test-child-process-silent.js | 106 + .../test/simple/test-child-process-stdin.js | 89 + .../test/simple/test-child-process-stdio.js | 36 + .../simple/test-child-process-stdout-flush.js | 52 + node-v0.8.14/test/simple/test-cli-eval.js | 81 + .../test/simple/test-cluster-basic.js | 183 + .../test/simple/test-cluster-disconnect.js | 122 + .../test/simple/test-cluster-fork-env.js | 63 + .../test/simple/test-cluster-http-pipe.js | 62 + .../test/simple/test-cluster-master-error.js | 139 + .../test/simple/test-cluster-master-kill.js | 98 + .../test/simple/test-cluster-message.js | 139 + .../test/simple/test-cluster-net-listen.js | 41 + .../test/simple/test-cluster-setup-master.js | 90 + .../simple/test-cluster-uncaught-exception.js | 59 + .../test/simple/test-cluster-worker-death.js | 46 + .../simple/test-cluster-worker-disconnect.js | 110 + .../test/simple/test-cluster-worker-exit.js | 152 + .../test/simple/test-cluster-worker-kill.js | 149 + .../simple/test-console-not-call-toString.js | 36 + node-v0.8.14/test/simple/test-console.js | 61 + node-v0.8.14/test/simple/test-crypto-ecb.js | 51 + .../test/simple/test-crypto-padding.js | 130 + .../test/simple/test-crypto-random.js | 70 + node-v0.8.14/test/simple/test-crypto.js | 667 + .../test/simple/test-debugger-client.js | 200 + .../test/simple/test-debugger-repl-utf8.js | 178 + .../test/simple/test-debugger-repl.js | 195 + .../test/simple/test-delayed-require.js | 34 + .../test/simple/test-deprecation-flags.js | 57 + .../test/simple/test-dgram-address.js | 64 + node-v0.8.14/test/simple/test-dgram-bind.js | 32 + .../test-dgram-broadcast-multi-process.js | 220 + node-v0.8.14/test/simple/test-dgram-close.js | 35 + .../test-dgram-multicast-multi-process.js | 225 + .../simple/test-dgram-multicast-setTTL.js | 41 + .../test/simple/test-dgram-oob-buffer.js | 52 + .../test/simple/test-dgram-pingpong.js | 113 + node-v0.8.14/test/simple/test-dgram-ref.js | 27 + .../test/simple/test-dgram-send-error.js | 81 + node-v0.8.14/test/simple/test-dgram-udp4.js | 81 + .../test/simple/test-domain-crypto.js | 37 + .../test/simple/test-domain-exit-dispose.js | 67 + .../test/simple/test-domain-http-server.js | 121 + .../test/simple/test-domain-implicit-fs.js | 72 + node-v0.8.14/test/simple/test-domain-multi.js | 99 + node-v0.8.14/test/simple/test-domain-stack.js | 46 + node-v0.8.14/test/simple/test-domain.js | 233 + node-v0.8.14/test/simple/test-eio-limit.js | 50 + node-v0.8.14/test/simple/test-eio-race.js | 85 + node-v0.8.14/test/simple/test-eio-race2.js | 45 + node-v0.8.14/test/simple/test-eio-race4.js | 42 + .../test/simple/test-error-reporting.js | 76 + node-v0.8.14/test/simple/test-eval-require.js | 38 + node-v0.8.14/test/simple/test-eval.js | 50 + .../test-event-emitter-add-listeners.js | 68 + ...test-event-emitter-check-listener-leaks.js | 58 + .../test-event-emitter-max-listeners.js | 41 + .../test-event-emitter-modify-in-emit.js | 77 + .../simple/test-event-emitter-num-args.js | 48 + .../test/simple/test-event-emitter-once.js | 49 + ...test-event-emitter-remove-all-listeners.js | 58 + .../test-event-emitter-remove-listeners.js | 61 + .../simple/test-event-emitter-subclass.js | 43 + .../test/simple/test-exception-handler.js | 47 + .../test/simple/test-exception-handler2.js | 42 + .../test/simple/test-exec-max-buffer.js | 34 + .../test/simple/test-executable-path.js | 52 + .../test/simple/test-file-read-noexist.js | 42 + .../test/simple/test-file-write-stream.js | 81 + .../test/simple/test-file-write-stream2.js | 98 + .../test/simple/test-file-write-stream3.js | 206 + node-v0.8.14/test/simple/test-force-repl.js | 44 + .../test/simple/test-fs-append-file-sync.js | 94 + .../test/simple/test-fs-append-file.js | 127 + node-v0.8.14/test/simple/test-fs-chmod.js | 161 + .../test/simple/test-fs-empty-readStream.js | 66 + .../test/simple/test-fs-error-messages.js | 189 + node-v0.8.14/test/simple/test-fs-exists.js | 43 + node-v0.8.14/test/simple/test-fs-fsync.js | 59 + node-v0.8.14/test/simple/test-fs-long-path.js | 51 + node-v0.8.14/test/simple/test-fs-mkdir.js | 83 + .../test-fs-non-number-arguments-throw.js | 24 + .../test/simple/test-fs-open-flags.js | 60 + node-v0.8.14/test/simple/test-fs-open.js | 59 + .../test/simple/test-fs-read-buffer.js | 50 + .../simple/test-fs-read-file-sync-hostname.js | 30 + .../test/simple/test-fs-read-file-sync.js | 33 + .../test/simple/test-fs-read-stream-fd.js | 44 + .../test/simple/test-fs-read-stream-resume.js | 51 + .../test/simple/test-fs-read-stream.js | 169 + node-v0.8.14/test/simple/test-fs-read.js | 48 + .../test/simple/test-fs-readfile-empty.js | 38 + .../test/simple/test-fs-readfile-pipe.js | 55 + .../test/simple/test-fs-readfile-unlink.js | 48 + .../simple/test-fs-readfile-zero-byte-liar.js | 58 + node-v0.8.14/test/simple/test-fs-realpath.js | 594 + .../test/simple/test-fs-sir-writes-alot.js | 71 + node-v0.8.14/test/simple/test-fs-stat.js | 123 + .../simple/test-fs-stream-double-close.js | 61 + .../simple/test-fs-symlink-dir-junction.js | 68 + node-v0.8.14/test/simple/test-fs-symlink.js | 92 + .../test/simple/test-fs-sync-fd-leak.js | 69 + node-v0.8.14/test/simple/test-fs-utimes.js | 160 + node-v0.8.14/test/simple/test-fs-watch.js | 133 + .../test/simple/test-fs-write-buffer.js | 54 + .../test/simple/test-fs-write-file-buffer.js | 51 + .../test/simple/test-fs-write-file.js | 101 + .../test-fs-write-stream-change-open.js | 52 + .../test/simple/test-fs-write-stream-end.js | 46 + .../test/simple/test-fs-write-stream.js | 50 + .../test/simple/test-fs-write-sync.js | 42 + node-v0.8.14/test/simple/test-fs-write.js | 76 + node-v0.8.14/test/simple/test-global.js | 39 + .../test/simple/test-http-1.0-keep-alive.js | 148 + node-v0.8.14/test/simple/test-http-1.0.js | 181 + node-v0.8.14/test/simple/test-http-304.js | 46 + .../test/simple/test-http-abort-before-end.js | 43 + .../test/simple/test-http-abort-client.js | 67 + .../test/simple/test-http-after-connect.js | 89 + node-v0.8.14/test/simple/test-http-agent.js | 57 + .../test-http-allow-req-after-204-res.js | 65 + .../test/simple/test-http-bind-twice.js | 47 + .../test/simple/test-http-blank-header.js | 68 + .../test/simple/test-http-buffer-sanity.js | 91 + node-v0.8.14/test/simple/test-http-chunked.js | 63 + .../test/simple/test-http-client-abort.js | 80 + .../test/simple/test-http-client-abort2.js | 41 + .../test/simple/test-http-client-agent.js | 69 + .../test/simple/test-http-client-get-url.js | 44 + .../simple/test-http-client-parse-error.js | 61 + .../test/simple/test-http-client-pipe-end.js | 58 + .../test/simple/test-http-client-race-2.js | 118 + .../test/simple/test-http-client-race.js | 66 + .../test-http-client-response-domain.js | 65 + .../simple/test-http-client-timeout-agent.js | 96 + .../test-http-client-timeout-with-data.js | 67 + .../test/simple/test-http-client-timeout.js | 50 + .../simple/test-http-client-upload-buf.js | 74 + .../test/simple/test-http-client-upload.js | 77 + .../test/simple/test-http-conn-reset.js | 57 + node-v0.8.14/test/simple/test-http-connect.js | 105 + .../test/simple/test-http-contentLength0.js | 42 + .../simple/test-http-curl-chunk-problem.js | 91 + .../test/simple/test-http-date-header.js | 54 + .../test/simple/test-http-default-encoding.js | 61 + .../test/simple/test-http-dns-error.js | 68 + .../test/simple/test-http-dns-fail.js | 62 + .../test/simple/test-http-eof-on-connect.js | 40 + .../test/simple/test-http-exceptions.js | 47 + .../test/simple/test-http-expect-continue.js | 88 + .../test/simple/test-http-extra-response.js | 86 + .../test/simple/test-http-full-response.js | 96 + .../simple/test-http-get-pipeline-problem.js | 111 + .../test/simple/test-http-head-request.js | 56 + ...test-http-head-response-has-no-body-end.js | 61 + .../test-http-head-response-has-no-body.js | 58 + .../test/simple/test-http-header-read.js | 52 + .../test/simple/test-http-host-headers.js | 163 + .../test-http-keep-alive-close-on-header.js | 94 + .../test/simple/test-http-keep-alive.js | 68 + node-v0.8.14/test/simple/test-http-legacy.js | 104 + .../test-http-localaddress-bind-error.js | 56 + .../test/simple/test-http-localaddress.js | 55 + .../simple/test-http-malformed-request.js | 57 + .../test-http-many-keep-alive-connections.js | 68 + .../simple/test-http-max-headers-count.js | 87 + .../simple/test-http-multi-line-headers.js | 59 + .../test/simple/test-http-mutable-headers.js | 153 + .../simple/test-http-no-content-length.js | 46 + .../test/simple/test-http-parser-bad-ref.js | 81 + .../test/simple/test-http-parser-free.js | 54 + node-v0.8.14/test/simple/test-http-parser.js | 549 + .../simple/test-http-pause-resume-one-end.js | 58 + node-v0.8.14/test/simple/test-http-pause.js | 75 + node-v0.8.14/test/simple/test-http-pipe-fs.js | 68 + node-v0.8.14/test/simple/test-http-proxy.js | 109 + .../simple/test-http-request-end-twice.js | 41 + .../test/simple/test-http-request-end.js | 58 + .../test/simple/test-http-request-methods.js | 72 + ...test-http-res-write-end-dont-take-array.js | 64 + .../test/simple/test-http-response-close.js | 61 + .../simple/test-http-response-no-headers.js | 80 + .../simple/test-http-response-readable.js | 40 + .../simple/test-http-server-multiheaders.js | 74 + node-v0.8.14/test/simple/test-http-server.js | 128 + .../test/simple/test-http-set-cookies.js | 84 + .../test/simple/test-http-set-timeout.js | 51 + .../test/simple/test-http-set-trailers.js | 111 + .../simple/test-http-should-keep-alive.js | 71 + .../test/simple/test-http-status-code.js | 69 + node-v0.8.14/test/simple/test-http-timeout.js | 63 + .../test/simple/test-http-unix-socket.js | 87 + .../test/simple/test-http-upgrade-agent.js | 93 + .../test/simple/test-http-upgrade-client.js | 76 + .../test/simple/test-http-upgrade-client2.js | 86 + .../test/simple/test-http-upgrade-server.js | 185 + .../test/simple/test-http-upgrade-server2.js | 72 + ...p-url.parse-auth-with-header-in-request.js | 50 + .../test/simple/test-http-url.parse-auth.js | 46 + .../test/simple/test-http-url.parse-basic.js | 55 + .../test-http-url.parse-https.request.js | 57 + ....parse-only-support-http-https-protocol.js | 82 + .../test/simple/test-http-url.parse-path.js | 45 + .../test/simple/test-http-url.parse-post.js | 52 + .../test/simple/test-http-url.parse-search.js | 46 + node-v0.8.14/test/simple/test-http-wget.js | 87 + .../simple/test-http-write-empty-string.js | 57 + node-v0.8.14/test/simple/test-http.js | 108 + node-v0.8.14/test/simple/test-https-agent.js | 70 + .../test/simple/test-https-client-get-url.js | 55 + .../test/simple/test-https-client-reject.js | 95 + .../simple/test-https-connecting-to-http.js | 64 + node-v0.8.14/test/simple/test-https-drain.js | 93 + .../test/simple/test-https-eof-for-eom.js | 101 + .../test/simple/test-https-foafssl.js | 89 + .../test/simple/test-https-invalid-key.js | 62 + .../test-https-localaddress-bind-error.js | 62 + .../test/simple/test-https-localaddress.js | 61 + node-v0.8.14/test/simple/test-https-pfx.js | 56 + node-v0.8.14/test/simple/test-https-simple.js | 75 + .../test/simple/test-https-socket-options.js | 83 + node-v0.8.14/test/simple/test-https-strict.js | 218 + .../test/simple/test-https-timeout.js | 73 + node-v0.8.14/test/simple/test-init.js | 68 + .../test/simple/test-listen-fd-cluster.js | 136 + .../simple/test-listen-fd-detached-inherit.js | 119 + .../test/simple/test-listen-fd-detached.js | 117 + .../test/simple/test-listen-fd-ebadf.js | 38 + .../test/simple/test-listen-fd-server.js | 122 + .../test/simple/test-memory-usage-emfile.js | 37 + node-v0.8.14/test/simple/test-memory-usage.js | 30 + node-v0.8.14/test/simple/test-mkdir-rmdir.js | 61 + .../test/simple/test-module-loading-error.js | 44 + .../test/simple/test-module-loading.js | 297 + .../test/simple/test-net-after-close.js | 52 + node-v0.8.14/test/simple/test-net-binary.js | 97 + .../test/simple/test-net-bind-twice.js | 46 + .../test/simple/test-net-bytes-stats.js | 74 + .../test/simple/test-net-can-reset-timeout.js | 62 + .../test/simple/test-net-connect-buffer.js | 110 + .../test-net-connect-handle-econnrefused.js | 48 + .../test/simple/test-net-connect-options.js | 58 + .../test/simple/test-net-connect-timeout.js | 94 + .../test/simple/test-net-create-connection.js | 50 + .../test/simple/test-net-dns-error.js | 49 + .../test/simple/test-net-during-close.js | 47 + .../test/simple/test-net-eaddrinuse.js | 35 + node-v0.8.14/test/simple/test-net-isip.js | 48 + .../test/simple/test-net-keepalive.js | 51 + .../test/simple/test-net-large-string.js | 55 + .../test/simple/test-net-listen-error.js | 39 + .../test/simple/test-net-listen-fd0.js | 36 + .../test-net-pause-resume-connecting.js | 101 + node-v0.8.14/test/simple/test-net-pingpong.js | 140 + .../simple/test-net-pipe-connect-errors.js | 86 + .../test/simple/test-net-reconnect.js | 78 + .../simple/test-net-remote-address-port.js | 56 + .../test/simple/test-net-server-address.js | 58 + .../test/simple/test-net-server-bind.js | 95 + .../test/simple/test-net-server-close.js | 54 + .../test-net-server-listen-remove-callback.js | 43 + .../simple/test-net-server-max-connections.js | 107 + .../test/simple/test-net-server-try-ports.js | 76 + .../test/simple/test-net-settimeout.js | 56 + .../simple/test-net-socket-destroy-twice.js | 43 + .../test/simple/test-net-socket-timeout.js | 44 + node-v0.8.14/test/simple/test-net-stream.js | 39 + .../test/simple/test-net-write-after-close.js | 51 + .../simple/test-net-write-connect-write.js | 48 + .../test/simple/test-net-write-slow.js | 67 + .../test/simple/test-next-tick-doesnt-hang.js | 30 + .../test/simple/test-next-tick-errors.js | 57 + .../test/simple/test-next-tick-ordering.js | 55 + .../test/simple/test-next-tick-ordering2.js | 38 + .../test/simple/test-next-tick-starvation.js | 52 + node-v0.8.14/test/simple/test-next-tick.js | 50 + node-v0.8.14/test/simple/test-os.js | 96 + .../test/simple/test-path-makelong.js | 38 + node-v0.8.14/test/simple/test-path.js | 285 + node-v0.8.14/test/simple/test-pipe-address.js | 39 + .../test/simple/test-pipe-file-to-http.js | 96 + node-v0.8.14/test/simple/test-pipe-head.js | 48 + .../test/simple/test-pipe-return-val.js | 37 + node-v0.8.14/test/simple/test-pipe-stream.js | 86 + node-v0.8.14/test/simple/test-pipe.js | 134 + .../test/simple/test-process-active-wraps.js | 56 + .../test/simple/test-process-argv-0.js | 55 + .../test/simple/test-process-config.js | 44 + node-v0.8.14/test/simple/test-process-env.js | 69 + .../test/simple/test-process-exec-argv.js | 40 + .../simple/test-process-exit-recursive.js | 35 + node-v0.8.14/test/simple/test-process-exit.js | 34 + .../test/simple/test-process-hrtime.js | 46 + .../test/simple/test-process-kill-null.js | 42 + .../test/simple/test-process-next-tick.js | 45 + node-v0.8.14/test/simple/test-process-wrap.js | 73 + .../test/simple/test-pump-file2tcp-noexist.js | 72 + .../test/simple/test-pump-file2tcp.js | 65 + node-v0.8.14/test/simple/test-punycode.js | 182 + node-v0.8.14/test/simple/test-querystring.js | 231 + node-v0.8.14/test/simple/test-readdir.js | 91 + node-v0.8.14/test/simple/test-readdouble.js | 131 + node-v0.8.14/test/simple/test-readfloat.js | 93 + node-v0.8.14/test/simple/test-readint.js | 122 + .../test/simple/test-readline-interface.js | 131 + .../test/simple/test-readline-set-raw-mode.js | 91 + node-v0.8.14/test/simple/test-readuint.js | 113 + .../test/simple/test-regress-GH-1531.js | 62 + .../test/simple/test-regress-GH-1697.js | 70 + .../test/simple/test-regress-GH-1726.js | 64 + .../test/simple/test-regress-GH-1899.js | 40 + .../test/simple/test-regress-GH-3542.js | 54 + .../test/simple/test-regress-GH-3739.js | 66 + .../test/simple/test-regress-GH-4015.js | 33 + .../test/simple/test-regress-GH-4027.js | 41 + .../test/simple/test-regress-GH-746.js | 50 + .../test/simple/test-regress-GH-784.js | 157 + .../test/simple/test-regress-GH-819.js | 28 + .../test/simple/test-regress-GH-877.js | 71 + .../test/simple/test-regress-GH-897.js | 35 + .../test-regression-object-prototype.js | 27 + .../test/simple/test-repl-.save.load.js | 98 + .../test/simple/test-repl-autolibs.js | 79 + .../test/simple/test-repl-end-emits-exit.js | 77 + node-v0.8.14/test/simple/test-repl-options.js | 71 + .../test/simple/test-repl-tab-complete.js | 210 + node-v0.8.14/test/simple/test-repl.js | 310 + .../simple/test-require-cache-without-stat.js | 72 + .../test/simple/test-require-cache.js | 43 + .../test/simple/test-require-exceptions.js | 42 + node-v0.8.14/test/simple/test-require-json.js | 30 + .../test/simple/test-require-resolve.js | 35 + .../test/simple/test-script-context.js | 71 + node-v0.8.14/test/simple/test-script-new.js | 93 + .../test/simple/test-script-static-context.js | 40 + .../test/simple/test-script-static-new.js | 62 + .../test/simple/test-script-static-this.js | 56 + node-v0.8.14/test/simple/test-script-this.js | 61 + node-v0.8.14/test/simple/test-setproctitle.js | 45 + .../test/simple/test-sigint-infinite-loop.js | 61 + .../test/simple/test-signal-handler.js | 71 + .../test/simple/test-signal-unregister.js | 56 + .../test/simple/test-stdin-child-proc.js | 28 + .../test/simple/test-stdin-from-file.js | 65 + node-v0.8.14/test/simple/test-stdin-hang.js | 31 + .../simple/test-stdin-pause-resume-sync.js | 31 + .../test/simple/test-stdin-pause-resume.js | 37 + .../test/simple/test-stdin-pipe-resume.js | 48 + .../test/simple/test-stdin-resume-pause.js | 23 + .../test/simple/test-stdout-close-catch.js | 56 + .../test/simple/test-stdout-to-file.js | 77 + .../test/simple/test-stream-pipe-cleanup.js | 96 + .../simple/test-stream-pipe-error-handling.js | 58 + .../test/simple/test-stream-pipe-event.js | 49 + .../test/simple/test-stream-pipe-multi.js | 121 + .../test/simple/test-string-decoder.js | 163 + .../test/simple/test-sync-fileread.js | 32 + node-v0.8.14/test/simple/test-sys.js | 129 + .../test/simple/test-tcp-wrap-connect.js | 71 + .../test/simple/test-tcp-wrap-listen.js | 116 + node-v0.8.14/test/simple/test-tcp-wrap.js | 39 + .../test/simple/test-timers-linked-list.js | 120 + .../simple/test-timers-uncaught-exception.js | 52 + .../test/simple/test-timers-zero-timeout.js | 59 + node-v0.8.14/test/simple/test-timers.js | 72 + .../simple/test-tls-check-server-identity.js | 204 + .../test/simple/test-tls-client-abort.js | 44 + .../test/simple/test-tls-client-abort2.js | 45 + .../test/simple/test-tls-client-reject.js | 92 + .../test/simple/test-tls-client-resume.js | 77 + .../test/simple/test-tls-client-verify.js | 154 + .../simple/test-tls-connect-given-socket.js | 59 + .../test/simple/test-tls-connect-pipe.js | 49 + .../test/simple/test-tls-connect-simple.js | 57 + node-v0.8.14/test/simple/test-tls-connect.js | 52 + .../test/simple/test-tls-getcipher.js | 53 + .../test/simple/test-tls-honorcipherorder.js | 86 + .../test/simple/test-tls-invalid-key.js | 62 + .../simple/test-tls-junk-closes-server.js | 54 + .../test/simple/test-tls-npn-server-client.js | 102 + .../test/simple/test-tls-over-http-tunnel.js | 173 + .../test/simple/test-tls-passphrase.js | 73 + .../test/simple/test-tls-pause-close.js | 100 + node-v0.8.14/test/simple/test-tls-pause.js | 78 + .../test-tls-peer-certificate-multi-keys.js | 58 + .../test/simple/test-tls-peer-certificate.js | 58 + node-v0.8.14/test/simple/test-tls-remote.js | 61 + .../test/simple/test-tls-request-timeout.js | 50 + .../test/simple/test-tls-securepair-client.js | 201 + .../test/simple/test-tls-securepair-server.js | 154 + .../test/simple/test-tls-server-verify.js | 290 + .../test/simple/test-tls-session-cache.js | 78 + .../test/simple/test-tls-set-ciphers.js | 62 + .../test/simple/test-tls-set-encoding.js | 71 + .../test/simple/test-tls-sni-server-client.js | 119 + .../test/simple/test-tty-stdout-end.js | 36 + node-v0.8.14/test/simple/test-tty-wrap.js | 52 + node-v0.8.14/test/simple/test-typed-arrays.js | 184 + node-v0.8.14/test/simple/test-umask.js | 41 + node-v0.8.14/test/simple/test-url.js | 1374 ++ node-v0.8.14/test/simple/test-utf8-scripts.js | 30 + node-v0.8.14/test/simple/test-util-format.js | 62 + node-v0.8.14/test/simple/test-util-inspect.js | 116 + node-v0.8.14/test/simple/test-util.js | 80 + .../test-vm-create-context-accessors.js | 47 + .../test/simple/test-vm-create-context-arg.js | 33 + ...st-vm-create-context-circular-reference.js | 34 + node-v0.8.14/test/simple/test-writedouble.js | 130 + node-v0.8.14/test/simple/test-writefloat.js | 90 + node-v0.8.14/test/simple/test-writeint.js | 192 + node-v0.8.14/test/simple/test-writeuint.js | 151 + .../test/simple/test-zerolengthbufferbug.js | 57 + node-v0.8.14/test/simple/test-zlib-destroy.js | 36 + .../test/simple/test-zlib-dictionary.js | 95 + .../test/simple/test-zlib-from-gzip.js | 48 + .../test/simple/test-zlib-from-string.js | 78 + .../test/simple/test-zlib-invalid-input.js | 72 + .../simple/test-zlib-random-byte-pipes.js | 164 + node-v0.8.14/test/simple/test-zlib.js | 229 + node-v0.8.14/test/simple/testcfg.py | 132 + node-v0.8.14/tools/addon.gypi | 24 + node-v0.8.14/tools/blog/README.md | 5 + node-v0.8.14/tools/blog/generate.js | 283 + node-v0.8.14/tools/blog/templates/index.ejs | 1 + node-v0.8.14/tools/blog/wp-to-markdown.js | 189 + node-v0.8.14/tools/build-changelog.sh | 16 + node-v0.8.14/tools/changelog-head.sh | 15 + node-v0.8.14/tools/closure_linter/PKG-INFO | 10 + node-v0.8.14/tools/closure_linter/README | 9 + .../closure_linter.egg-info/PKG-INFO | 10 + .../closure_linter.egg-info/SOURCES.txt | 41 + .../dependency_links.txt | 1 + .../closure_linter.egg-info/entry_points.txt | 4 + .../closure_linter.egg-info/requires.txt | 1 + .../closure_linter.egg-info/top_level.txt | 1 + .../closure_linter/closure_linter/__init__.py | 1 + .../closure_linter/closure_linter/checker.py | 82 + .../closure_linter/checkerbase.py | 237 + .../closure_linter/common/__init__.py | 1 + .../closure_linter/common/error.py | 65 + .../closure_linter/common/erroraccumulator.py | 46 + .../closure_linter/common/errorhandler.py | 61 + .../closure_linter/common/errorprinter.py | 203 + .../closure_linter/common/filetestcase.py | 105 + .../closure_linter/common/htmlutil.py | 170 + .../closure_linter/common/lintrunner.py | 39 + .../closure_linter/common/matcher.py | 60 + .../closure_linter/common/position.py | 126 + .../closure_linter/common/simplefileflags.py | 190 + .../closure_linter/common/tokenizer.py | 184 + .../closure_linter/common/tokens.py | 125 + .../closure_linter/ecmalintrules.py | 752 + .../closure_linter/ecmametadatapass.py | 521 + .../closure_linter/error_fixer.py | 336 + .../closure_linter/errorrules.py | 42 + .../closure_linter/closure_linter/errors.py | 131 + .../closure_linter/fixjsstyle.py | 47 + .../closure_linter/fixjsstyle_test.py | 61 + .../closure_linter/full_test.py | 99 + .../closure_linter/closure_linter/gjslint.py | 142 + .../closure_linter/indentation.py | 543 + .../closure_linter/javascriptlintrules.py | 395 + .../closure_linter/javascriptstatetracker.py | 238 + .../javascriptstatetracker_test.py | 53 + .../closure_linter/javascripttokenizer.py | 365 + .../closure_linter/javascripttokens.py | 147 + .../closure_linter/statetracker.py | 964 ++ .../closure_linter/tokenutil.py | 285 + node-v0.8.14/tools/closure_linter/gflags.py | 2489 ++++ node-v0.8.14/tools/closure_linter/setup.cfg | 5 + node-v0.8.14/tools/closure_linter/setup.py | 38 + node-v0.8.14/tools/cpplint.py | 3126 +++++ node-v0.8.14/tools/doc/LICENSE | 18 + node-v0.8.14/tools/doc/README.md | 96 + node-v0.8.14/tools/doc/generate.js | 119 + node-v0.8.14/tools/doc/html.js | 174 + node-v0.8.14/tools/doc/json.js | 557 + node-v0.8.14/tools/doc/package.json | 15 + node-v0.8.14/tools/email-footer.md | 23 + node-v0.8.14/tools/genv8constants.py | 82 + node-v0.8.14/tools/getnodeisrelease.py | 11 + node-v0.8.14/tools/getnodeversion.py | 16 + node-v0.8.14/tools/gyp/.gitignore | 1 + node-v0.8.14/tools/gyp/AUTHORS | 6 + node-v0.8.14/tools/gyp/DEPS | 26 + node-v0.8.14/tools/gyp/LICENSE | 27 + node-v0.8.14/tools/gyp/MANIFEST | 21 + node-v0.8.14/tools/gyp/OWNERS | 1 + node-v0.8.14/tools/gyp/PRESUBMIT.py | 109 + .../tools/gyp/buildbot/buildbot_run.py | 98 + node-v0.8.14/tools/gyp/codereview.settings | 10 + node-v0.8.14/tools/gyp/gyp | 18 + node-v0.8.14/tools/gyp/gyp.bat | 5 + node-v0.8.14/tools/gyp/gyp_dummy.c | 7 + node-v0.8.14/tools/gyp/gyptest.py | 264 + node-v0.8.14/tools/gyp/pylib/gyp/MSVSNew.py | 341 + .../tools/gyp/pylib/gyp/MSVSProject.py | 208 + .../tools/gyp/pylib/gyp/MSVSSettings.py | 1046 ++ .../tools/gyp/pylib/gyp/MSVSSettings_test.py | 1482 ++ .../tools/gyp/pylib/gyp/MSVSToolFile.py | 58 + .../tools/gyp/pylib/gyp/MSVSUserFile.py | 147 + .../tools/gyp/pylib/gyp/MSVSVersion.py | 353 + node-v0.8.14/tools/gyp/pylib/gyp/SCons.py | 199 + node-v0.8.14/tools/gyp/pylib/gyp/__init__.py | 517 + node-v0.8.14/tools/gyp/pylib/gyp/common.py | 461 + .../tools/gyp/pylib/gyp/common_test.py | 44 + node-v0.8.14/tools/gyp/pylib/gyp/easy_xml.py | 157 + .../tools/gyp/pylib/gyp/easy_xml_test.py | 103 + .../tools/gyp/pylib/gyp/generator/__init__.py | 0 .../tools/gyp/pylib/gyp/generator/android.py | 1077 ++ .../gyp/generator/dump_dependency_json.py | 66 + .../tools/gyp/pylib/gyp/generator/eclipse.py | 273 + .../tools/gyp/pylib/gyp/generator/gypd.py | 87 + .../tools/gyp/pylib/gyp/generator/gypsh.py | 56 + .../tools/gyp/pylib/gyp/generator/make.py | 2145 +++ .../tools/gyp/pylib/gyp/generator/msvs.py | 3143 +++++ .../gyp/pylib/gyp/generator/msvs_test.py | 35 + .../tools/gyp/pylib/gyp/generator/ninja.py | 1712 +++ .../gyp/pylib/gyp/generator/ninja_test.py | 44 + .../tools/gyp/pylib/gyp/generator/scons.py | 1047 ++ .../tools/gyp/pylib/gyp/generator/xcode.py | 1211 ++ node-v0.8.14/tools/gyp/pylib/gyp/input.py | 2485 ++++ node-v0.8.14/tools/gyp/pylib/gyp/mac_tool.py | 209 + .../tools/gyp/pylib/gyp/msvs_emulation.py | 691 + .../tools/gyp/pylib/gyp/ninja_syntax.py | 153 + node-v0.8.14/tools/gyp/pylib/gyp/sun_tool.py | 51 + .../tools/gyp/pylib/gyp/system_test.py | 68 + node-v0.8.14/tools/gyp/pylib/gyp/win_tool.py | 194 + .../tools/gyp/pylib/gyp/xcode_emulation.py | 1044 ++ .../tools/gyp/pylib/gyp/xcodeproj_file.py | 2834 ++++ node-v0.8.14/tools/gyp/pylib/gyp/xml_fix.py | 69 + node-v0.8.14/tools/gyp/pylintrc | 307 + node-v0.8.14/tools/gyp/samples/samples | 81 + node-v0.8.14/tools/gyp/samples/samples.bat | 5 + node-v0.8.14/tools/gyp/setup.py | 26 + node-v0.8.14/tools/gyp/tools/README | 15 + node-v0.8.14/tools/gyp/tools/Xcode/README | 5 + .../tools/Xcode/Specifications/gyp.pbfilespec | 27 + .../tools/Xcode/Specifications/gyp.xclangspec | 226 + node-v0.8.14/tools/gyp/tools/emacs/README | 12 + .../tools/gyp/tools/emacs/gyp-tests.el | 54 + node-v0.8.14/tools/gyp/tools/emacs/gyp.el | 251 + .../tools/gyp/tools/emacs/run-unit-tests.sh | 7 + .../tools/gyp/tools/emacs/testdata/media.gyp | 1105 ++ .../tools/emacs/testdata/media.gyp.fontified | 1107 ++ node-v0.8.14/tools/gyp/tools/graphviz.py | 100 + node-v0.8.14/tools/gyp/tools/pretty_gyp.py | 155 + node-v0.8.14/tools/gyp/tools/pretty_sln.py | 168 + node-v0.8.14/tools/gyp/tools/pretty_vcproj.py | 329 + node-v0.8.14/tools/gyp_addon | 42 + node-v0.8.14/tools/gyp_node | 58 + node-v0.8.14/tools/install.py | 225 + node-v0.8.14/tools/js2c.py | 368 + node-v0.8.14/tools/license2rtf.js | 334 + node-v0.8.14/tools/msvs/msi/nodemsi.sln | 26 + node-v0.8.14/tools/msvs/msi/nodemsi.wixproj | 55 + node-v0.8.14/tools/msvs/msi/product.wxs | 182 + node-v0.8.14/tools/msvs/nodejsvars.bat | 16 + node-v0.8.14/tools/msvs/npm/npmrc | 1 + node-v0.8.14/tools/node-waf | 17 + node-v0.8.14/tools/osx-codesign.sh | 12 + node-v0.8.14/tools/osx-pkg-postinstall.sh | 5 + .../tools/osx-pkg.pmdoc/01local-contents.xml | 1 + node-v0.8.14/tools/osx-pkg.pmdoc/01local.xml | 1 + .../tools/osx-pkg.pmdoc/02npm-contents.xml | 1 + node-v0.8.14/tools/osx-pkg.pmdoc/02npm.xml | 1 + node-v0.8.14/tools/osx-pkg.pmdoc/index.xml | 19 + node-v0.8.14/tools/osx-productsign.sh | 12 + node-v0.8.14/tools/test.py | 1440 ++ node-v0.8.14/tools/updateAuthors.awk | 13 + node-v0.8.14/tools/waf-light | 159 + node-v0.8.14/tools/wafadmin/Build.py | 1021 ++ node-v0.8.14/tools/wafadmin/Configure.py | 387 + node-v0.8.14/tools/wafadmin/Constants.py | 76 + node-v0.8.14/tools/wafadmin/Environment.py | 210 + node-v0.8.14/tools/wafadmin/Logs.py | 134 + node-v0.8.14/tools/wafadmin/Node.py | 693 + node-v0.8.14/tools/wafadmin/Options.py | 279 + node-v0.8.14/tools/wafadmin/Runner.py | 229 + node-v0.8.14/tools/wafadmin/Scripting.py | 586 + node-v0.8.14/tools/wafadmin/Task.py | 1171 ++ node-v0.8.14/tools/wafadmin/TaskGen.py | 588 + node-v0.8.14/tools/wafadmin/Tools/__init__.py | 4 + node-v0.8.14/tools/wafadmin/Tools/ar.py | 36 + node-v0.8.14/tools/wafadmin/Tools/cc.py | 100 + node-v0.8.14/tools/wafadmin/Tools/ccroot.py | 625 + .../tools/wafadmin/Tools/compiler_cc.py | 66 + .../tools/wafadmin/Tools/compiler_cxx.py | 61 + .../tools/wafadmin/Tools/compiler_d.py | 33 + node-v0.8.14/tools/wafadmin/Tools/config_c.py | 729 + node-v0.8.14/tools/wafadmin/Tools/cxx.py | 104 + node-v0.8.14/tools/wafadmin/Tools/d.py | 540 + node-v0.8.14/tools/wafadmin/Tools/dmd.py | 64 + node-v0.8.14/tools/wafadmin/Tools/gas.py | 38 + node-v0.8.14/tools/wafadmin/Tools/gcc.py | 137 + node-v0.8.14/tools/wafadmin/Tools/gdc.py | 52 + node-v0.8.14/tools/wafadmin/Tools/gnu_dirs.py | 111 + node-v0.8.14/tools/wafadmin/Tools/gob2.py | 18 + node-v0.8.14/tools/wafadmin/Tools/gxx.py | 134 + node-v0.8.14/tools/wafadmin/Tools/icc.py | 37 + node-v0.8.14/tools/wafadmin/Tools/icpc.py | 34 + node-v0.8.14/tools/wafadmin/Tools/intltool.py | 139 + node-v0.8.14/tools/wafadmin/Tools/libtool.py | 330 + node-v0.8.14/tools/wafadmin/Tools/misc.py | 430 + node-v0.8.14/tools/wafadmin/Tools/nasm.py | 49 + .../tools/wafadmin/Tools/node_addon.py | 86 + node-v0.8.14/tools/wafadmin/Tools/osx.py | 187 + node-v0.8.14/tools/wafadmin/Tools/preproc.py | 813 ++ node-v0.8.14/tools/wafadmin/Tools/python.py | 401 + node-v0.8.14/tools/wafadmin/Tools/suncc.py | 77 + node-v0.8.14/tools/wafadmin/Tools/suncxx.py | 75 + .../tools/wafadmin/Tools/unittestw.py | 305 + node-v0.8.14/tools/wafadmin/Tools/winres.py | 45 + node-v0.8.14/tools/wafadmin/Tools/xlc.py | 77 + node-v0.8.14/tools/wafadmin/Tools/xlcxx.py | 77 + node-v0.8.14/tools/wafadmin/Utils.py | 707 + node-v0.8.14/tools/wafadmin/__init__.py | 3 + node-v0.8.14/tools/wafadmin/ansiterm.py | 221 + node-v0.8.14/tools/wafadmin/pproc.py | 620 + node-v0.8.14/tools/wafadmin/py3kfixes.py | 122 + node-v0.8.14/vcbuild.bat | 198 + node_modules/.bin/sardines | 1 - node_modules/celeri/.cupboard | 2 - node_modules/celeri/.gitignore | 2 - node_modules/celeri/MIT-LICENSE.txt | 20 - node_modules/celeri/README.md | 357 - node_modules/celeri/examples/auth.js | 13 - node_modules/celeri/examples/authadv.js | 69 - node_modules/celeri/examples/confirm.js | 16 - node_modules/celeri/examples/exec.js | 11 - node_modules/celeri/examples/hello.js | 52 - node_modules/celeri/examples/hello2.js | 19 - node_modules/celeri/examples/table.js | 44 - node_modules/celeri/examples/table2.js | 29 - node_modules/celeri/examples/table3.js | 59 - node_modules/celeri/examples/tree.js | 34 - node_modules/celeri/images/screen.png | Bin 51631 -> 0 bytes node_modules/celeri/lib/index.js | 401 - node_modules/celeri/lib/modules/auth.js | 18 - node_modules/celeri/lib/modules/backspace.js | 22 - node_modules/celeri/lib/modules/confirm.js | 38 - node_modules/celeri/lib/modules/enter.js | 38 - node_modules/celeri/lib/modules/exec.js | 87 - node_modules/celeri/lib/modules/help.js | 42 - node_modules/celeri/lib/modules/history.js | 33 - node_modules/celeri/lib/modules/loading.js | 43 - node_modules/celeri/lib/modules/nav.js | 13 - node_modules/celeri/lib/modules/password.js | 58 - node_modules/celeri/lib/modules/progress.js | 33 - node_modules/celeri/lib/modules/prompt.js | 41 - node_modules/celeri/lib/modules/quit.js | 7 - node_modules/celeri/lib/modules/section.js | 6 - node_modules/celeri/lib/modules/table.js | 292 - node_modules/celeri/lib/modules/table2.js | 275 - node_modules/celeri/lib/modules/tree.js | 95 - node_modules/celeri/lib/utils.js | 44 - .../celeri/node_modules/beanpole/.cupboard | 2 - .../celeri/node_modules/beanpole/.gitignore | 2 - .../node_modules/beanpole/MIT-LICENSE.txt | 20 - .../celeri/node_modules/beanpole/README.md | 392 - .../node_modules/beanpole/beanpole.tmproj | 185 - .../beanpole/docs/beans/README.md | 76 - .../beanpole/docs/brainstorming/README.txt | 1 - .../beanpole/docs/brainstorming/analogy.txt | 1 - .../beanpole/docs/brainstorming/ideas.txt | 155 - .../node_modules/beanpole/docs/build-ebnf | 5 - .../node_modules/beanpole/docs/diagram.png | Bin 63906 -> 0 bytes .../node_modules/beanpole/docs/syntax.ebnf | 5 - .../bean.hello/beans/hello.core/index.js | 18 - .../bean.hello/beans/hello.friend/index.js | 13 - .../bean.hello/beans/hello.neighbor/index.js | 13 - .../beanpole/examples/bean.hello/index.js | 3 - .../beans/test/index.js | 72 - .../examples/bean.hook.call.receive/index.js | 28 - .../bean.hook.hello/beans/test/index.js | 41 - .../examples/bean.hook.hello/index.js | 26 - .../bean.hook.middleware/beans/test/index.js | 41 - .../examples/bean.hook.middleware/hook1.js | 32 - .../examples/bean.hook.middleware/hook2.js | 32 - .../examples/bean.hook.middleware/hook3.js | 26 - .../examples/bean.http.middleware/index.js | 101 - .../beans/hello.core/index.js | 34 - .../beans/http.server/index.js | 41 - .../examples/bean.http.server/index.js | 3 - .../beans/hello.core/index.js | 46 - .../examples/bean.website.load/index.js | 3 - .../examples/benchmark.silly/index.js | 32 - .../beanpole/examples/default/index.js | 49 - .../beans/test/index.js | 6 - .../examples/filter.metadata.rotate/index.js | 75 - .../examples/filter.metadata/index.js | 53 - .../beanpole/examples/http.gateway/direct.js | 33 - .../beanpole/examples/http.gateway/hook.js | 43 - .../beanpole/examples/http.gateway/hook2.js | 38 - .../beanpole/examples/http.gateway/hook3.js | 43 - .../beanpole/examples/http.gateway/hook4.js | 48 - .../beanpole/examples/http.gateway/index.js | 41 - .../examples/interception-old/index.js | 31 - .../beanpole/examples/multi.routes/index.js | 20 - .../beanpole/examples/or.hello/index.js | 32 - .../beanpole/examples/override.pull/index.js | 21 - .../beanpole/examples/pull.thru/index.js | 61 - .../beanpole/examples/push.pull/index.js | 46 - .../beanpole/examples/push.thru/index.js | 35 - .../beanpole/examples/rotate.hello/index.js | 43 - .../beanpole/examples/thru/index.js | 87 - .../examples/ws/client/release/index.html | 9 - .../examples/ws/client/release/index.js | 2139 --- .../node_modules/beanpole/examples/ws/hook.js | 37 - .../beanpole/examples/ws/server.js | 40 - .../beanpole/lib/core/concrete/collection.js | 338 - .../beanpole/lib/core/concrete/parser.js | 595 - .../beanpole/lib/core/concrete/request.js | 310 - .../beanpole/lib/core/concrete/router.js | 282 - .../beanpole/lib/core/concrete/utils.js | 115 - .../beanpole/lib/core/controller.js | 200 - .../node_modules/beanpole/lib/core/index.js | 11 - .../node_modules/beanpole/lib/core/loader.js | 76 - .../lib/core/middleware/meta/index.js | 138 - .../lib/core/middleware/meta/rotate.js | 39 - .../lib/core/middleware/meta/store.js | 8 - .../core/middleware/route/default/index.js | 13 - .../lib/core/middleware/route/index.js | 91 - .../middleware/route/pushPull/pull/index.js | 19 - .../middleware/route/pushPull/pull/request.js | 45 - .../middleware/route/pushPull/push/index.js | 14 - .../middleware/route/pushPull/push/request.js | 30 - .../middleware/route/pushPull/push/router.js | 63 - .../core/middleware/route/pushPull/request.js | 88 - .../core/middleware/route/pushPull/stream.js | 209 - .../lib/node/beans/system.core/index.js | 26 - .../node_modules/beanpole/lib/node/index.js | 21 - .../node_modules/beanpole/lib/node/loader.js | 171 - .../node_modules/beanpole/lib/web/index.js | 1 - .../celeri/node_modules/beanpole/package.json | 25 - .../beanpole/project.sublime-project | 23 - .../node_modules/beanpole/project.tmproj | 168 - .../node_modules/colors/MIT-LICENSE.txt | 19 - .../celeri/node_modules/colors/ReadMe.md | 30 - .../celeri/node_modules/colors/colors.js | 230 - .../celeri/node_modules/colors/example.html | 20 - .../celeri/node_modules/colors/example.js | 20 - .../celeri/node_modules/colors/package.json | 14 - .../celeri/node_modules/structr/package.json | 11 - .../celeri/node_modules/structr/structr.js | 488 - .../node_modules/structr/structr.min.js | 8 - node_modules/celeri/package.json | 18 - node_modules/celeri/project.sublime-project | 23 - node_modules/celeri/project.tmproj | 48 - node_modules/findit/README.markdown | 91 - node_modules/findit/examples/callback.js | 3 - node_modules/findit/examples/emitter.js | 9 - node_modules/findit/examples/sync.js | 2 - node_modules/findit/index.js | 88 - .../findit/node_modules/seq/.npmignore | 1 - .../findit/node_modules/seq/README.markdown | 442 - .../findit/node_modules/seq/examples/join.js | 18 - .../node_modules/seq/examples/parseq.coffee | 12 - .../node_modules/seq/examples/parseq.js | 19 - .../node_modules/seq/examples/stat_all.coffee | 16 - .../node_modules/seq/examples/stat_all.js | 17 - node_modules/findit/node_modules/seq/index.js | 520 - .../seq/node_modules/chainsaw/.npmignore | 1 - .../seq/node_modules/chainsaw/README.markdown | 140 - .../node_modules/chainsaw/examples/add_do.js | 25 - .../node_modules/chainsaw/examples/prompt.js | 67 - .../seq/node_modules/chainsaw/index.js | 108 - .../chainsaw/node_modules/traverse/.npmignore | 1 - .../chainsaw/node_modules/traverse/LICENSE | 24 - .../node_modules/traverse/README.markdown | 247 - .../node_modules/traverse/examples/json.js | 16 - .../node_modules/traverse/examples/leaves.js | 15 - .../traverse/examples/negative.js | 8 - .../traverse/examples/stringify.js | 38 - .../chainsaw/node_modules/traverse/index.js | 322 - .../node_modules/traverse/package.json | 18 - .../node_modules/traverse/test/circular.js | 114 - .../node_modules/traverse/test/date.js | 35 - .../node_modules/traverse/test/equal.js | 219 - .../node_modules/traverse/test/instance.js | 17 - .../node_modules/traverse/test/interface.js | 42 - .../node_modules/traverse/test/json.js | 47 - .../node_modules/traverse/test/leaves.js | 21 - .../node_modules/traverse/test/mutability.js | 203 - .../node_modules/traverse/test/negative.js | 20 - .../node_modules/traverse/test/obj.js | 15 - .../node_modules/traverse/test/stop.js | 41 - .../node_modules/traverse/test/stringify.js | 36 - .../node_modules/traverse/test/super_deep.js | 54 - .../seq/node_modules/chainsaw/package.json | 23 - .../node_modules/chainsaw/test/chainsaw.js | 418 - .../seq/node_modules/hashish/README.markdown | 191 - .../node_modules/hashish/examples/chain.js | 9 - .../seq/node_modules/hashish/examples/map.js | 7 - .../seq/node_modules/hashish/index.js | 253 - .../hashish/node_modules/traverse/.npmignore | 1 - .../hashish/node_modules/traverse/LICENSE | 24 - .../node_modules/traverse/README.markdown | 237 - .../node_modules/traverse/examples/json.js | 16 - .../node_modules/traverse/examples/leaves.js | 15 - .../traverse/examples/negative.js | 8 - .../node_modules/traverse/examples/scrub.js | 10 - .../traverse/examples/stringify.js | 38 - .../hashish/node_modules/traverse/index.js | 267 - .../hashish/node_modules/traverse/main.js | 10 - .../node_modules/traverse/package.json | 18 - .../node_modules/traverse/test/circular.js | 115 - .../node_modules/traverse/test/date.js | 35 - .../node_modules/traverse/test/equal.js | 220 - .../node_modules/traverse/test/instance.js | 17 - .../node_modules/traverse/test/interface.js | 42 - .../node_modules/traverse/test/json.js | 47 - .../node_modules/traverse/test/keys.js | 29 - .../node_modules/traverse/test/leaves.js | 21 - .../traverse/test/lib/deep_equal.js | 92 - .../node_modules/traverse/test/mutability.js | 252 - .../node_modules/traverse/test/negative.js | 20 - .../hashish/node_modules/traverse/test/obj.js | 15 - .../node_modules/traverse/test/siblings.js | 35 - .../node_modules/traverse/test/stop.js | 41 - .../node_modules/traverse/test/stringify.js | 36 - .../node_modules/traverse/test/subexpr.js | 34 - .../node_modules/traverse/test/super_deep.js | 55 - .../seq/node_modules/hashish/package.json | 33 - .../seq/node_modules/hashish/test/hash.js | 250 - .../seq/node_modules/hashish/test/property.js | 69 - .../findit/node_modules/seq/package.json | 33 - .../findit/node_modules/seq/test/readdir.js | 35 - .../findit/node_modules/seq/test/seq.js | 946 -- .../findit/node_modules/seq/test/seq_.js | 149 - node_modules/findit/package.json | 31 - node_modules/findit/test/cb.js | 24 - node_modules/findit/test/cycle.js | 41 - node_modules/findit/test/foo.js | 79 - node_modules/findit/test/module.js | 29 - node_modules/mkdirp/.gitignore | 2 - node_modules/mkdirp/.gitignore.orig | 2 - node_modules/mkdirp/.gitignore.rej | 5 - node_modules/mkdirp/LICENSE | 21 - node_modules/mkdirp/README.markdown | 50 - node_modules/mkdirp/examples/pow.js | 6 - node_modules/mkdirp/examples/pow.js.orig | 6 - node_modules/mkdirp/examples/pow.js.rej | 19 - node_modules/mkdirp/index.js | 85 - node_modules/mkdirp/package.json | 23 - node_modules/mkdirp/test/chmod.js | 39 - node_modules/mkdirp/test/clobber.js | 37 - node_modules/mkdirp/test/mkdirp.js | 28 - node_modules/mkdirp/test/perm.js | 32 - node_modules/mkdirp/test/perm_sync.js | 39 - node_modules/mkdirp/test/race.js | 41 - node_modules/mkdirp/test/rel.js | 32 - node_modules/mkdirp/test/sync.js | 27 - node_modules/optimist/.gitignore | 2 - node_modules/optimist/.npmignore | 4 - node_modules/optimist/README.markdown | 13 + node_modules/optimist/examples/bool.js | 10 - .../optimist/examples/boolean_double.js | 7 - .../optimist/examples/boolean_single.js | 7 - .../optimist/examples/default_hash.js | 8 - .../optimist/examples/default_singles.js | 7 - node_modules/optimist/examples/divide.js | 8 - node_modules/optimist/examples/line_count.js | 20 - .../optimist/examples/line_count_options.js | 29 - .../optimist/examples/line_count_wrap.js | 29 - node_modules/optimist/examples/nonopt.js | 4 - node_modules/optimist/examples/reflect.js | 2 - node_modules/optimist/examples/short.js | 3 - node_modules/optimist/examples/string.js | 11 - .../optimist/examples/usage-options.js | 19 - node_modules/optimist/examples/xup.js | 10 - node_modules/optimist/index.js | 46 +- node_modules/optimist/package.json | 86 +- node_modules/optimist/test/_.js | 91 +- node_modules/optimist/test/parse.js | 415 +- node_modules/optimist/test/usage.js | 180 +- node_modules/request/README.md | 43 +- node_modules/request/main.js | 1164 +- node_modules/request/mimetypes.js | 146 - node_modules/request/oauth.js | 44 +- node_modules/request/package.json | 54 +- node_modules/request/tests/run.sh | 6 - node_modules/request/tests/server.js | 47 +- node_modules/request/tests/test-body.js | 41 +- node_modules/request/tests/test-cookie.js | 6 +- node_modules/request/tests/test-errors.js | 7 + node_modules/request/tests/test-oauth.js | 28 +- node_modules/request/tests/test-pipes.js | 51 +- node_modules/request/uuid.js | 12 +- node_modules/request/vendor/cookie/index.js | 30 +- node_modules/sardines | 1 - node_modules/sk | 1 - node_modules/tar-async/header.js | 124 - node_modules/tar-async/index.js | 8 - node_modules/tar-async/package.json | 20 - node_modules/tar-async/tar.js | 156 - node_modules/tar-async/untar.js | 244 - node_modules/tar-async/utils.js | 19 - node_modules/tar/.gitignore | 4 - node_modules/tar/README.md | 50 - node_modules/tar/examples/extracter.js | 11 - node_modules/tar/examples/reader.js | 36 - node_modules/tar/lib/buffer-entry.js | 30 - node_modules/tar/lib/entry-writer.js | 169 - node_modules/tar/lib/entry.js | 212 - .../tar/lib/extended-header-writer.js | 179 - node_modules/tar/lib/extended-header.js | 139 - node_modules/tar/lib/extract.js | 64 - node_modules/tar/lib/global-header-writer.js | 14 - node_modules/tar/lib/header.js | 385 - node_modules/tar/lib/pack.js | 212 - node_modules/tar/lib/parse.js | 253 - node_modules/tar/old/README.md | 1 - node_modules/tar/old/doc/example.js | 24 - node_modules/tar/old/generator.js | 387 - node_modules/tar/old/parser.js | 344 - node_modules/tar/old/tar.js | 74 - node_modules/tar/old/test/test-generator.js | 13 - node_modules/tar/old/test/test-generator.tar | Bin 3260 -> 0 bytes node_modules/tar/old/test/test-generator.txt | Bin 3261 -> 0 bytes node_modules/tar/old/test/test-parser.js | 28 - node_modules/tar/old/test/test-tar.tar | Bin 3072 -> 0 bytes node_modules/tar/old/test/test-tar.txt | Bin 3073 -> 0 bytes node_modules/tar/package.json | 26 - node_modules/tar/tar.js | 172 - node_modules/tar/test/extract.js | 406 - node_modules/tar/test/fixtures/200.tar | Bin 3072 -> 0 bytes node_modules/tar/test/fixtures/200L.hex | 50 - ...cccccccccccccccccccccccccccccccccccccccccc | 1 - .../tar/test/fixtures/200longlink.tar | Bin 3584 -> 0 bytes .../tar/test/fixtures/200longname.tar | Bin 3072 -> 0 bytes node_modules/tar/test/fixtures/a.hex | 14 - node_modules/tar/test/fixtures/a.tar | Bin 2048 -> 0 bytes node_modules/tar/test/fixtures/a.txt | 1 - node_modules/tar/test/fixtures/b.hex | 14 - node_modules/tar/test/fixtures/b.tar | Bin 2048 -> 0 bytes node_modules/tar/test/fixtures/b.txt | 1 - node_modules/tar/test/fixtures/c.hex | 74 - node_modules/tar/test/fixtures/c.tar | Bin 18432 -> 0 bytes node_modules/tar/test/fixtures/c.txt | 1 - node_modules/tar/test/fixtures/cc.txt | 1 - node_modules/tar/test/fixtures/foo.hex | 14 - node_modules/tar/test/fixtures/foo.js | 1 - node_modules/tar/test/fixtures/foo.tar | Bin 2048 -> 0 bytes node_modules/tar/test/fixtures/hardlink-1 | 1 - node_modules/tar/test/fixtures/hardlink-2 | 1 - node_modules/tar/test/fixtures/omega.hex | 22 - node_modules/tar/test/fixtures/omega.tar | Bin 3072 -> 0 bytes node_modules/tar/test/fixtures/omega.txt | 1 - node_modules/tar/test/fixtures/omegapax.tar | Bin 5120 -> 0 bytes .../tar/test/fixtures/packtest/omega.txt | 1 - .../tar/test/fixtures/packtest/star.4.html | 1184 -- node_modules/tar/test/fixtures/packtest/Ω.txt | 1 - ...cccccccccccccccccccccccccccccccccccccccccc | 1 - node_modules/tar/test/fixtures/symlink | 1 - node_modules/tar/test/fixtures/Ω.txt | 1 - node_modules/tar/test/header.js | 183 - node_modules/tar/test/pack.js | 953 -- node_modules/tar/test/parse.js | 359 - node_modules/vine | 1 - package.json | 12 +- project.sublime-project | 23 - project.sublime-workspace | 547 - 4443 files changed, 947516 insertions(+), 27340 deletions(-) create mode 100644 .gitignore delete mode 120000 nexe create mode 100644 node-v0.8.14/.gitattributes create mode 100644 node-v0.8.14/.gitignore create mode 100644 node-v0.8.14/.mailmap create mode 100644 node-v0.8.14/.travis.yml create mode 100644 node-v0.8.14/AUTHORS create mode 100644 node-v0.8.14/BSDmakefile create mode 100644 node-v0.8.14/ChangeLog create mode 100644 node-v0.8.14/LICENSE create mode 100644 node-v0.8.14/Makefile create mode 100644 node-v0.8.14/README.md create mode 100644 node-v0.8.14/benchmark/arrays/var_int.js create mode 100644 node-v0.8.14/benchmark/arrays/zero_float.js create mode 100644 node-v0.8.14/benchmark/arrays/zero_int.js create mode 100644 node-v0.8.14/benchmark/buffer_creation.js create mode 100644 node-v0.8.14/benchmark/client_latency.js create mode 100644 node-v0.8.14/benchmark/fast_buffer2.js create mode 100644 node-v0.8.14/benchmark/fast_buffer2_creation.js create mode 100644 node-v0.8.14/benchmark/fast_buffer_creation.js create mode 100644 node-v0.8.14/benchmark/fs-readfile.js create mode 100644 node-v0.8.14/benchmark/function_call/bench.js create mode 100644 node-v0.8.14/benchmark/function_call/binding.cc create mode 100644 node-v0.8.14/benchmark/function_call/wscript create mode 100755 node-v0.8.14/benchmark/http.sh create mode 100644 node-v0.8.14/benchmark/http_bench.js create mode 100644 node-v0.8.14/benchmark/http_server_lag.js create mode 100644 node-v0.8.14/benchmark/http_simple.js create mode 100644 node-v0.8.14/benchmark/http_simple.rb create mode 100644 node-v0.8.14/benchmark/http_simple_auto.js create mode 100755 node-v0.8.14/benchmark/http_simple_bench.sh create mode 100644 node-v0.8.14/benchmark/http_simple_cluster.js create mode 100644 node-v0.8.14/benchmark/idle_clients.js create mode 100644 node-v0.8.14/benchmark/idle_server.js create mode 100644 node-v0.8.14/benchmark/io.c create mode 100644 node-v0.8.14/benchmark/io.js create mode 100644 node-v0.8.14/benchmark/next-tick-2.js create mode 100644 node-v0.8.14/benchmark/next-tick.js create mode 100755 node-v0.8.14/benchmark/plot.R create mode 100644 node-v0.8.14/benchmark/process_loop.js create mode 100644 node-v0.8.14/benchmark/report-startup-memory.js create mode 100644 node-v0.8.14/benchmark/run.js create mode 100644 node-v0.8.14/benchmark/settimeout.js create mode 100644 node-v0.8.14/benchmark/startup.js create mode 100644 node-v0.8.14/benchmark/static_http_server.js create mode 100644 node-v0.8.14/benchmark/string_creation.js create mode 100644 node-v0.8.14/benchmark/throughput-child.js create mode 100644 node-v0.8.14/benchmark/throughput.js create mode 100644 node-v0.8.14/benchmark/timers.js create mode 100644 node-v0.8.14/benchmark/tls-connect.js create mode 100644 node-v0.8.14/benchmark/tls-fragmentation.js create mode 100644 node-v0.8.14/benchmark/v8_bench.js create mode 100644 node-v0.8.14/common.gypi create mode 100755 node-v0.8.14/configure create mode 100644 node-v0.8.14/deps/http_parser/.gitignore create mode 100644 node-v0.8.14/deps/http_parser/.mailmap create mode 100644 node-v0.8.14/deps/http_parser/AUTHORS create mode 100644 node-v0.8.14/deps/http_parser/CONTRIBUTIONS create mode 100644 node-v0.8.14/deps/http_parser/LICENSE-MIT create mode 100644 node-v0.8.14/deps/http_parser/Makefile create mode 100644 node-v0.8.14/deps/http_parser/README.md create mode 100644 node-v0.8.14/deps/http_parser/http_parser.c create mode 100644 node-v0.8.14/deps/http_parser/http_parser.gyp create mode 100644 node-v0.8.14/deps/http_parser/http_parser.h create mode 100644 node-v0.8.14/deps/http_parser/test.c create mode 100644 node-v0.8.14/deps/npm/.npmignore create mode 100644 node-v0.8.14/deps/npm/AUTHORS create mode 100644 node-v0.8.14/deps/npm/LICENSE create mode 100644 node-v0.8.14/deps/npm/Makefile create mode 100644 node-v0.8.14/deps/npm/README.md create mode 100755 node-v0.8.14/deps/npm/bin/node-gyp-bin/node-gyp create mode 100755 node-v0.8.14/deps/npm/bin/node-gyp-bin/node-gyp.cmd create mode 100755 node-v0.8.14/deps/npm/bin/npm create mode 100755 node-v0.8.14/deps/npm/bin/npm-cli.js create mode 100644 node-v0.8.14/deps/npm/bin/npm.cmd create mode 100755 node-v0.8.14/deps/npm/bin/read-package-json.js create mode 100755 node-v0.8.14/deps/npm/cli.js create mode 100755 node-v0.8.14/deps/npm/configure create mode 100644 node-v0.8.14/deps/npm/doc/api/bin.md create mode 100644 node-v0.8.14/deps/npm/doc/api/bugs.md create mode 100644 node-v0.8.14/deps/npm/doc/api/commands.md create mode 100644 node-v0.8.14/deps/npm/doc/api/config.md create mode 100644 node-v0.8.14/deps/npm/doc/api/deprecate.md create mode 100644 node-v0.8.14/deps/npm/doc/api/docs.md create mode 100644 node-v0.8.14/deps/npm/doc/api/edit.md create mode 100644 node-v0.8.14/deps/npm/doc/api/explore.md create mode 100644 node-v0.8.14/deps/npm/doc/api/help-search.md create mode 100644 node-v0.8.14/deps/npm/doc/api/init.md create mode 100644 node-v0.8.14/deps/npm/doc/api/install.md create mode 100644 node-v0.8.14/deps/npm/doc/api/link.md create mode 100644 node-v0.8.14/deps/npm/doc/api/load.md create mode 100644 node-v0.8.14/deps/npm/doc/api/ls.md create mode 100644 node-v0.8.14/deps/npm/doc/api/npm.md create mode 100644 node-v0.8.14/deps/npm/doc/api/outdated.md create mode 100644 node-v0.8.14/deps/npm/doc/api/owner.md create mode 100644 node-v0.8.14/deps/npm/doc/api/pack.md create mode 100644 node-v0.8.14/deps/npm/doc/api/prefix.md create mode 100644 node-v0.8.14/deps/npm/doc/api/prune.md create mode 100644 node-v0.8.14/deps/npm/doc/api/publish.md create mode 100644 node-v0.8.14/deps/npm/doc/api/rebuild.md create mode 100644 node-v0.8.14/deps/npm/doc/api/restart.md create mode 100644 node-v0.8.14/deps/npm/doc/api/root.md create mode 100644 node-v0.8.14/deps/npm/doc/api/run-script.md create mode 100644 node-v0.8.14/deps/npm/doc/api/search.md create mode 100644 node-v0.8.14/deps/npm/doc/api/shrinkwrap.md create mode 100644 node-v0.8.14/deps/npm/doc/api/start.md create mode 100644 node-v0.8.14/deps/npm/doc/api/stop.md create mode 100644 node-v0.8.14/deps/npm/doc/api/submodule.md create mode 100644 node-v0.8.14/deps/npm/doc/api/tag.md create mode 100644 node-v0.8.14/deps/npm/doc/api/test.md create mode 100644 node-v0.8.14/deps/npm/doc/api/uninstall.md create mode 100644 node-v0.8.14/deps/npm/doc/api/unpublish.md create mode 100644 node-v0.8.14/deps/npm/doc/api/update.md create mode 100644 node-v0.8.14/deps/npm/doc/api/version.md create mode 100644 node-v0.8.14/deps/npm/doc/api/view.md create mode 100644 node-v0.8.14/deps/npm/doc/api/whoami.md create mode 100644 node-v0.8.14/deps/npm/doc/cli/adduser.md create mode 100644 node-v0.8.14/deps/npm/doc/cli/bin.md create mode 100644 node-v0.8.14/deps/npm/doc/cli/bugs.md create mode 100644 node-v0.8.14/deps/npm/doc/cli/build.md create mode 100644 node-v0.8.14/deps/npm/doc/cli/bundle.md create mode 100644 node-v0.8.14/deps/npm/doc/cli/cache.md create mode 100644 node-v0.8.14/deps/npm/doc/cli/changelog.md create mode 100644 node-v0.8.14/deps/npm/doc/cli/coding-style.md create mode 100644 node-v0.8.14/deps/npm/doc/cli/completion.md create mode 100644 node-v0.8.14/deps/npm/doc/cli/config.md create mode 100644 node-v0.8.14/deps/npm/doc/cli/dedupe.md create mode 100644 node-v0.8.14/deps/npm/doc/cli/deprecate.md create mode 100644 node-v0.8.14/deps/npm/doc/cli/developers.md create mode 100644 node-v0.8.14/deps/npm/doc/cli/disputes.md create mode 100644 node-v0.8.14/deps/npm/doc/cli/docs.md create mode 100644 node-v0.8.14/deps/npm/doc/cli/edit.md create mode 100644 node-v0.8.14/deps/npm/doc/cli/explore.md create mode 100644 node-v0.8.14/deps/npm/doc/cli/faq.md create mode 100644 node-v0.8.14/deps/npm/doc/cli/folders.md create mode 100644 node-v0.8.14/deps/npm/doc/cli/help-search.md create mode 100644 node-v0.8.14/deps/npm/doc/cli/help.md create mode 100644 node-v0.8.14/deps/npm/doc/cli/index.md create mode 100644 node-v0.8.14/deps/npm/doc/cli/init.md create mode 100644 node-v0.8.14/deps/npm/doc/cli/install.md create mode 100644 node-v0.8.14/deps/npm/doc/cli/json.md create mode 100644 node-v0.8.14/deps/npm/doc/cli/link.md create mode 100644 node-v0.8.14/deps/npm/doc/cli/ls.md create mode 100644 node-v0.8.14/deps/npm/doc/cli/npm.md create mode 100644 node-v0.8.14/deps/npm/doc/cli/outdated.md create mode 100644 node-v0.8.14/deps/npm/doc/cli/owner.md create mode 100644 node-v0.8.14/deps/npm/doc/cli/pack.md create mode 100644 node-v0.8.14/deps/npm/doc/cli/prefix.md create mode 100644 node-v0.8.14/deps/npm/doc/cli/prune.md create mode 100644 node-v0.8.14/deps/npm/doc/cli/publish.md create mode 100644 node-v0.8.14/deps/npm/doc/cli/rebuild.md create mode 100644 node-v0.8.14/deps/npm/doc/cli/registry.md create mode 100644 node-v0.8.14/deps/npm/doc/cli/removing-npm.md create mode 100644 node-v0.8.14/deps/npm/doc/cli/restart.md create mode 100644 node-v0.8.14/deps/npm/doc/cli/root.md create mode 100644 node-v0.8.14/deps/npm/doc/cli/run-script.md create mode 100644 node-v0.8.14/deps/npm/doc/cli/scripts.md create mode 100644 node-v0.8.14/deps/npm/doc/cli/search.md create mode 100644 node-v0.8.14/deps/npm/doc/cli/semver.md create mode 100644 node-v0.8.14/deps/npm/doc/cli/shrinkwrap.md create mode 100644 node-v0.8.14/deps/npm/doc/cli/star.md create mode 100644 node-v0.8.14/deps/npm/doc/cli/start.md create mode 100644 node-v0.8.14/deps/npm/doc/cli/stop.md create mode 100644 node-v0.8.14/deps/npm/doc/cli/submodule.md create mode 100644 node-v0.8.14/deps/npm/doc/cli/tag.md create mode 100644 node-v0.8.14/deps/npm/doc/cli/test.md create mode 100644 node-v0.8.14/deps/npm/doc/cli/uninstall.md create mode 100644 node-v0.8.14/deps/npm/doc/cli/unpublish.md create mode 100644 node-v0.8.14/deps/npm/doc/cli/update.md create mode 100644 node-v0.8.14/deps/npm/doc/cli/version.md create mode 100644 node-v0.8.14/deps/npm/doc/cli/view.md create mode 100644 node-v0.8.14/deps/npm/doc/cli/whoami.md create mode 100644 node-v0.8.14/deps/npm/html/api/bin.html create mode 100644 node-v0.8.14/deps/npm/html/api/bugs.html create mode 100644 node-v0.8.14/deps/npm/html/api/commands.html create mode 100644 node-v0.8.14/deps/npm/html/api/config.html create mode 100644 node-v0.8.14/deps/npm/html/api/deprecate.html create mode 100644 node-v0.8.14/deps/npm/html/api/docs.html create mode 100644 node-v0.8.14/deps/npm/html/api/edit.html create mode 100644 node-v0.8.14/deps/npm/html/api/explore.html create mode 100644 node-v0.8.14/deps/npm/html/api/help-search.html create mode 100644 node-v0.8.14/deps/npm/html/api/init.html create mode 100644 node-v0.8.14/deps/npm/html/api/install.html create mode 100644 node-v0.8.14/deps/npm/html/api/link.html create mode 100644 node-v0.8.14/deps/npm/html/api/load.html create mode 100644 node-v0.8.14/deps/npm/html/api/ls.html create mode 100644 node-v0.8.14/deps/npm/html/api/npm.html create mode 100644 node-v0.8.14/deps/npm/html/api/outdated.html create mode 100644 node-v0.8.14/deps/npm/html/api/owner.html create mode 100644 node-v0.8.14/deps/npm/html/api/pack.html create mode 100644 node-v0.8.14/deps/npm/html/api/prefix.html create mode 100644 node-v0.8.14/deps/npm/html/api/prune.html create mode 100644 node-v0.8.14/deps/npm/html/api/publish.html create mode 100644 node-v0.8.14/deps/npm/html/api/rebuild.html create mode 100644 node-v0.8.14/deps/npm/html/api/restart.html create mode 100644 node-v0.8.14/deps/npm/html/api/root.html create mode 100644 node-v0.8.14/deps/npm/html/api/run-script.html create mode 100644 node-v0.8.14/deps/npm/html/api/search.html create mode 100644 node-v0.8.14/deps/npm/html/api/shrinkwrap.html create mode 100644 node-v0.8.14/deps/npm/html/api/start.html create mode 100644 node-v0.8.14/deps/npm/html/api/stop.html create mode 100644 node-v0.8.14/deps/npm/html/api/submodule.html create mode 100644 node-v0.8.14/deps/npm/html/api/tag.html create mode 100644 node-v0.8.14/deps/npm/html/api/test.html create mode 100644 node-v0.8.14/deps/npm/html/api/uninstall.html create mode 100644 node-v0.8.14/deps/npm/html/api/unpublish.html create mode 100644 node-v0.8.14/deps/npm/html/api/update.html create mode 100644 node-v0.8.14/deps/npm/html/api/version.html create mode 100644 node-v0.8.14/deps/npm/html/api/view.html create mode 100644 node-v0.8.14/deps/npm/html/api/whoami.html create mode 100644 node-v0.8.14/deps/npm/html/doc/README.html create mode 100644 node-v0.8.14/deps/npm/html/doc/adduser.html create mode 100644 node-v0.8.14/deps/npm/html/doc/bin.html create mode 100644 node-v0.8.14/deps/npm/html/doc/bugs.html create mode 100644 node-v0.8.14/deps/npm/html/doc/build.html create mode 100644 node-v0.8.14/deps/npm/html/doc/bundle.html create mode 100644 node-v0.8.14/deps/npm/html/doc/cache.html create mode 100644 node-v0.8.14/deps/npm/html/doc/changelog.html create mode 100644 node-v0.8.14/deps/npm/html/doc/coding-style.html create mode 100644 node-v0.8.14/deps/npm/html/doc/completion.html create mode 100644 node-v0.8.14/deps/npm/html/doc/config.html create mode 100644 node-v0.8.14/deps/npm/html/doc/dedupe.html create mode 100644 node-v0.8.14/deps/npm/html/doc/deprecate.html create mode 100644 node-v0.8.14/deps/npm/html/doc/developers.html create mode 100644 node-v0.8.14/deps/npm/html/doc/disputes.html create mode 100644 node-v0.8.14/deps/npm/html/doc/docs.html create mode 100644 node-v0.8.14/deps/npm/html/doc/edit.html create mode 100644 node-v0.8.14/deps/npm/html/doc/explore.html create mode 100644 node-v0.8.14/deps/npm/html/doc/faq.html create mode 100644 node-v0.8.14/deps/npm/html/doc/folders.html create mode 100644 node-v0.8.14/deps/npm/html/doc/help-search.html create mode 100644 node-v0.8.14/deps/npm/html/doc/help.html create mode 100644 node-v0.8.14/deps/npm/html/doc/index.html create mode 100644 node-v0.8.14/deps/npm/html/doc/init.html create mode 100644 node-v0.8.14/deps/npm/html/doc/install.html create mode 100644 node-v0.8.14/deps/npm/html/doc/json.html create mode 100644 node-v0.8.14/deps/npm/html/doc/link.html create mode 100644 node-v0.8.14/deps/npm/html/doc/list.html create mode 100644 node-v0.8.14/deps/npm/html/doc/ls.html create mode 100644 node-v0.8.14/deps/npm/html/doc/npm.html create mode 100644 node-v0.8.14/deps/npm/html/doc/outdated.html create mode 100644 node-v0.8.14/deps/npm/html/doc/owner.html create mode 100644 node-v0.8.14/deps/npm/html/doc/pack.html create mode 100644 node-v0.8.14/deps/npm/html/doc/prefix.html create mode 100644 node-v0.8.14/deps/npm/html/doc/prune.html create mode 100644 node-v0.8.14/deps/npm/html/doc/publish.html create mode 100644 node-v0.8.14/deps/npm/html/doc/rebuild.html create mode 100644 node-v0.8.14/deps/npm/html/doc/registry.html create mode 100644 node-v0.8.14/deps/npm/html/doc/removing-npm.html create mode 100644 node-v0.8.14/deps/npm/html/doc/restart.html create mode 100644 node-v0.8.14/deps/npm/html/doc/root.html create mode 100644 node-v0.8.14/deps/npm/html/doc/run-script.html create mode 100644 node-v0.8.14/deps/npm/html/doc/scripts.html create mode 100644 node-v0.8.14/deps/npm/html/doc/search.html create mode 100644 node-v0.8.14/deps/npm/html/doc/semver.html create mode 100644 node-v0.8.14/deps/npm/html/doc/shrinkwrap.html create mode 100644 node-v0.8.14/deps/npm/html/doc/star.html create mode 100644 node-v0.8.14/deps/npm/html/doc/start.html create mode 100644 node-v0.8.14/deps/npm/html/doc/stop.html create mode 100644 node-v0.8.14/deps/npm/html/doc/submodule.html create mode 100644 node-v0.8.14/deps/npm/html/doc/tag.html create mode 100644 node-v0.8.14/deps/npm/html/doc/test.html create mode 100644 node-v0.8.14/deps/npm/html/doc/uninstall.html create mode 100644 node-v0.8.14/deps/npm/html/doc/unpublish.html create mode 100644 node-v0.8.14/deps/npm/html/doc/update.html create mode 100644 node-v0.8.14/deps/npm/html/doc/version.html create mode 100644 node-v0.8.14/deps/npm/html/doc/view.html create mode 100644 node-v0.8.14/deps/npm/html/doc/whoami.html create mode 100644 node-v0.8.14/deps/npm/html/docfoot.html create mode 100644 node-v0.8.14/deps/npm/html/dochead.html create mode 100644 node-v0.8.14/deps/npm/html/favicon.ico create mode 100644 node-v0.8.14/deps/npm/html/index.html create mode 100644 node-v0.8.14/deps/npm/html/static/style.css create mode 100644 node-v0.8.14/deps/npm/html/static/webfonts/23242D_3_0.eot create mode 100644 node-v0.8.14/deps/npm/html/static/webfonts/23242D_3_0.ttf create mode 100644 node-v0.8.14/deps/npm/html/static/webfonts/23242D_3_0.woff create mode 100644 node-v0.8.14/deps/npm/lib/adduser.js create mode 100644 node-v0.8.14/deps/npm/lib/bin.js create mode 100644 node-v0.8.14/deps/npm/lib/bugs.js create mode 100644 node-v0.8.14/deps/npm/lib/build.js create mode 100644 node-v0.8.14/deps/npm/lib/cache.js create mode 100644 node-v0.8.14/deps/npm/lib/completion.js create mode 100644 node-v0.8.14/deps/npm/lib/config.js create mode 100644 node-v0.8.14/deps/npm/lib/dedupe.js create mode 100644 node-v0.8.14/deps/npm/lib/deprecate.js create mode 100644 node-v0.8.14/deps/npm/lib/docs.js create mode 100644 node-v0.8.14/deps/npm/lib/edit.js create mode 100644 node-v0.8.14/deps/npm/lib/explore.js create mode 100644 node-v0.8.14/deps/npm/lib/faq.js create mode 100644 node-v0.8.14/deps/npm/lib/get.js create mode 100644 node-v0.8.14/deps/npm/lib/help-search.js create mode 100644 node-v0.8.14/deps/npm/lib/help.js create mode 100644 node-v0.8.14/deps/npm/lib/init.js create mode 100644 node-v0.8.14/deps/npm/lib/install.js create mode 100644 node-v0.8.14/deps/npm/lib/link.js create mode 100644 node-v0.8.14/deps/npm/lib/ls.js create mode 100644 node-v0.8.14/deps/npm/lib/npm.js create mode 100644 node-v0.8.14/deps/npm/lib/outdated.js create mode 100644 node-v0.8.14/deps/npm/lib/owner.js create mode 100644 node-v0.8.14/deps/npm/lib/pack.js create mode 100644 node-v0.8.14/deps/npm/lib/prefix.js create mode 100644 node-v0.8.14/deps/npm/lib/prune.js create mode 100644 node-v0.8.14/deps/npm/lib/publish.js create mode 100644 node-v0.8.14/deps/npm/lib/rebuild.js create mode 100644 node-v0.8.14/deps/npm/lib/restart.js create mode 100644 node-v0.8.14/deps/npm/lib/root.js create mode 100644 node-v0.8.14/deps/npm/lib/run-script.js create mode 100644 node-v0.8.14/deps/npm/lib/search.js create mode 100644 node-v0.8.14/deps/npm/lib/set.js create mode 100644 node-v0.8.14/deps/npm/lib/shrinkwrap.js create mode 100644 node-v0.8.14/deps/npm/lib/star.js create mode 100644 node-v0.8.14/deps/npm/lib/start.js create mode 100644 node-v0.8.14/deps/npm/lib/stop.js create mode 100644 node-v0.8.14/deps/npm/lib/submodule.js create mode 100644 node-v0.8.14/deps/npm/lib/substack.js create mode 100644 node-v0.8.14/deps/npm/lib/tag.js create mode 100644 node-v0.8.14/deps/npm/lib/test.js create mode 100644 node-v0.8.14/deps/npm/lib/unbuild.js create mode 100644 node-v0.8.14/deps/npm/lib/uninstall.js create mode 100644 node-v0.8.14/deps/npm/lib/unpublish.js create mode 100644 node-v0.8.14/deps/npm/lib/update.js create mode 100644 node-v0.8.14/deps/npm/lib/utils/cmd-shim.js create mode 100755 node-v0.8.14/deps/npm/lib/utils/completion.sh create mode 100644 node-v0.8.14/deps/npm/lib/utils/completion/file-completion.js create mode 100644 node-v0.8.14/deps/npm/lib/utils/completion/installed-deep.js create mode 100644 node-v0.8.14/deps/npm/lib/utils/completion/installed-shallow.js create mode 100644 node-v0.8.14/deps/npm/lib/utils/completion/remote-packages.js create mode 100644 node-v0.8.14/deps/npm/lib/utils/completion/users.js create mode 100644 node-v0.8.14/deps/npm/lib/utils/error-handler.js create mode 100644 node-v0.8.14/deps/npm/lib/utils/exec.js create mode 100644 node-v0.8.14/deps/npm/lib/utils/fetch.js create mode 100644 node-v0.8.14/deps/npm/lib/utils/find-prefix.js create mode 100644 node-v0.8.14/deps/npm/lib/utils/gently-rm.js create mode 100644 node-v0.8.14/deps/npm/lib/utils/lifecycle.js create mode 100644 node-v0.8.14/deps/npm/lib/utils/link.js create mode 100644 node-v0.8.14/deps/npm/lib/utils/sha.js create mode 100644 node-v0.8.14/deps/npm/lib/utils/tar.js create mode 100644 node-v0.8.14/deps/npm/lib/version.js create mode 100644 node-v0.8.14/deps/npm/lib/view.js create mode 100644 node-v0.8.14/deps/npm/lib/whoami.js create mode 100644 node-v0.8.14/deps/npm/lib/xmas.js create mode 100644 node-v0.8.14/deps/npm/man/man1/README.1 create mode 100644 node-v0.8.14/deps/npm/man/man1/adduser.1 create mode 100644 node-v0.8.14/deps/npm/man/man1/author.1 create mode 100644 node-v0.8.14/deps/npm/man/man1/bin.1 create mode 100644 node-v0.8.14/deps/npm/man/man1/bugs.1 create mode 100644 node-v0.8.14/deps/npm/man/man1/build.1 create mode 100644 node-v0.8.14/deps/npm/man/man1/bundle.1 create mode 100644 node-v0.8.14/deps/npm/man/man1/cache.1 create mode 100644 node-v0.8.14/deps/npm/man/man1/changelog.1 create mode 100644 node-v0.8.14/deps/npm/man/man1/coding-style.1 create mode 100644 node-v0.8.14/deps/npm/man/man1/completion.1 create mode 100644 node-v0.8.14/deps/npm/man/man1/config.1 create mode 100644 node-v0.8.14/deps/npm/man/man1/dedupe.1 create mode 100644 node-v0.8.14/deps/npm/man/man1/deprecate.1 create mode 100644 node-v0.8.14/deps/npm/man/man1/developers.1 create mode 100644 node-v0.8.14/deps/npm/man/man1/disputes.1 create mode 100644 node-v0.8.14/deps/npm/man/man1/docs.1 create mode 100644 node-v0.8.14/deps/npm/man/man1/edit.1 create mode 100644 node-v0.8.14/deps/npm/man/man1/explore.1 create mode 100644 node-v0.8.14/deps/npm/man/man1/faq.1 create mode 100644 node-v0.8.14/deps/npm/man/man1/find.1 create mode 100644 node-v0.8.14/deps/npm/man/man1/folders.1 create mode 100644 node-v0.8.14/deps/npm/man/man1/get.1 create mode 100644 node-v0.8.14/deps/npm/man/man1/global.1 create mode 100644 node-v0.8.14/deps/npm/man/man1/help-search.1 create mode 100644 node-v0.8.14/deps/npm/man/man1/help.1 create mode 100644 node-v0.8.14/deps/npm/man/man1/home.1 create mode 100644 node-v0.8.14/deps/npm/man/man1/index.1 create mode 100644 node-v0.8.14/deps/npm/man/man1/init.1 create mode 100644 node-v0.8.14/deps/npm/man/man1/install.1 create mode 100644 node-v0.8.14/deps/npm/man/man1/json.1 create mode 100644 node-v0.8.14/deps/npm/man/man1/link.1 create mode 100644 node-v0.8.14/deps/npm/man/man1/list.1 create mode 100644 node-v0.8.14/deps/npm/man/man1/ln.1 create mode 100644 node-v0.8.14/deps/npm/man/man1/ls.1 create mode 100644 node-v0.8.14/deps/npm/man/man1/npm.1 create mode 100644 node-v0.8.14/deps/npm/man/man1/outdated.1 create mode 100644 node-v0.8.14/deps/npm/man/man1/owner.1 create mode 100644 node-v0.8.14/deps/npm/man/man1/pack.1 create mode 100644 node-v0.8.14/deps/npm/man/man1/prefix.1 create mode 100644 node-v0.8.14/deps/npm/man/man1/prune.1 create mode 100644 node-v0.8.14/deps/npm/man/man1/publish.1 create mode 100644 node-v0.8.14/deps/npm/man/man1/rebuild.1 create mode 100644 node-v0.8.14/deps/npm/man/man1/registry.1 create mode 100644 node-v0.8.14/deps/npm/man/man1/removing-npm.1 create mode 100644 node-v0.8.14/deps/npm/man/man1/restart.1 create mode 100644 node-v0.8.14/deps/npm/man/man1/rm.1 create mode 100644 node-v0.8.14/deps/npm/man/man1/root.1 create mode 100644 node-v0.8.14/deps/npm/man/man1/run-script.1 create mode 100644 node-v0.8.14/deps/npm/man/man1/scripts.1 create mode 100644 node-v0.8.14/deps/npm/man/man1/search.1 create mode 100644 node-v0.8.14/deps/npm/man/man1/semver.1 create mode 100644 node-v0.8.14/deps/npm/man/man1/set.1 create mode 100644 node-v0.8.14/deps/npm/man/man1/shrinkwrap.1 create mode 100644 node-v0.8.14/deps/npm/man/man1/star.1 create mode 100644 node-v0.8.14/deps/npm/man/man1/start.1 create mode 100644 node-v0.8.14/deps/npm/man/man1/stop.1 create mode 100644 node-v0.8.14/deps/npm/man/man1/submodule.1 create mode 100644 node-v0.8.14/deps/npm/man/man1/tag.1 create mode 100644 node-v0.8.14/deps/npm/man/man1/test.1 create mode 100644 node-v0.8.14/deps/npm/man/man1/uninstall.1 create mode 100644 node-v0.8.14/deps/npm/man/man1/unpublish.1 create mode 100644 node-v0.8.14/deps/npm/man/man1/update.1 create mode 100644 node-v0.8.14/deps/npm/man/man1/version.1 create mode 100644 node-v0.8.14/deps/npm/man/man1/view.1 create mode 100644 node-v0.8.14/deps/npm/man/man1/whoami.1 create mode 100644 node-v0.8.14/deps/npm/man/man3/author.3 create mode 100644 node-v0.8.14/deps/npm/man/man3/bin.3 create mode 100644 node-v0.8.14/deps/npm/man/man3/bugs.3 create mode 100644 node-v0.8.14/deps/npm/man/man3/commands.3 create mode 100644 node-v0.8.14/deps/npm/man/man3/config.3 create mode 100644 node-v0.8.14/deps/npm/man/man3/deprecate.3 create mode 100644 node-v0.8.14/deps/npm/man/man3/docs.3 create mode 100644 node-v0.8.14/deps/npm/man/man3/edit.3 create mode 100644 node-v0.8.14/deps/npm/man/man3/explore.3 create mode 100644 node-v0.8.14/deps/npm/man/man3/find.3 create mode 100644 node-v0.8.14/deps/npm/man/man3/get.3 create mode 100644 node-v0.8.14/deps/npm/man/man3/help-search.3 create mode 100644 node-v0.8.14/deps/npm/man/man3/home.3 create mode 100644 node-v0.8.14/deps/npm/man/man3/init.3 create mode 100644 node-v0.8.14/deps/npm/man/man3/install.3 create mode 100644 node-v0.8.14/deps/npm/man/man3/link.3 create mode 100644 node-v0.8.14/deps/npm/man/man3/list.3 create mode 100644 node-v0.8.14/deps/npm/man/man3/ln.3 create mode 100644 node-v0.8.14/deps/npm/man/man3/load.3 create mode 100644 node-v0.8.14/deps/npm/man/man3/ls.3 create mode 100644 node-v0.8.14/deps/npm/man/man3/npm.3 create mode 100644 node-v0.8.14/deps/npm/man/man3/outdated.3 create mode 100644 node-v0.8.14/deps/npm/man/man3/owner.3 create mode 100644 node-v0.8.14/deps/npm/man/man3/pack.3 create mode 100644 node-v0.8.14/deps/npm/man/man3/prefix.3 create mode 100644 node-v0.8.14/deps/npm/man/man3/prune.3 create mode 100644 node-v0.8.14/deps/npm/man/man3/publish.3 create mode 100644 node-v0.8.14/deps/npm/man/man3/rebuild.3 create mode 100644 node-v0.8.14/deps/npm/man/man3/restart.3 create mode 100644 node-v0.8.14/deps/npm/man/man3/rm.3 create mode 100644 node-v0.8.14/deps/npm/man/man3/root.3 create mode 100644 node-v0.8.14/deps/npm/man/man3/run-script.3 create mode 100644 node-v0.8.14/deps/npm/man/man3/search.3 create mode 100644 node-v0.8.14/deps/npm/man/man3/set.3 create mode 100644 node-v0.8.14/deps/npm/man/man3/shrinkwrap.3 create mode 100644 node-v0.8.14/deps/npm/man/man3/start.3 create mode 100644 node-v0.8.14/deps/npm/man/man3/stop.3 create mode 100644 node-v0.8.14/deps/npm/man/man3/submodule.3 create mode 100644 node-v0.8.14/deps/npm/man/man3/tag.3 create mode 100644 node-v0.8.14/deps/npm/man/man3/test.3 create mode 100644 node-v0.8.14/deps/npm/man/man3/uninstall.3 create mode 100644 node-v0.8.14/deps/npm/man/man3/unpublish.3 create mode 100644 node-v0.8.14/deps/npm/man/man3/update.3 create mode 100644 node-v0.8.14/deps/npm/man/man3/version.3 create mode 100644 node-v0.8.14/deps/npm/man/man3/view.3 create mode 100644 node-v0.8.14/deps/npm/man/man3/whoami.3 create mode 100644 node-v0.8.14/deps/npm/package.json create mode 100755 node-v0.8.14/deps/npm/scripts/clean-old.sh create mode 100755 node-v0.8.14/deps/npm/scripts/doc-build.sh create mode 100755 node-v0.8.14/deps/npm/scripts/index-build.js create mode 100755 node-v0.8.14/deps/npm/scripts/install.sh create mode 100644 node-v0.8.14/deps/npm/scripts/release.sh create mode 100755 node-v0.8.14/deps/npm/scripts/relocate.sh create mode 100644 node-v0.8.14/deps/npm/test/common.js create mode 100644 node-v0.8.14/deps/npm/test/disabled/bundlerecurs/package.json create mode 100644 node-v0.8.14/deps/npm/test/disabled/change-bin-1/bin/foo create mode 100644 node-v0.8.14/deps/npm/test/disabled/change-bin-1/package.json create mode 100644 node-v0.8.14/deps/npm/test/disabled/change-bin-2/bin/bar create mode 100644 node-v0.8.14/deps/npm/test/disabled/change-bin-2/package.json create mode 100644 node-v0.8.14/deps/npm/test/disabled/failer/package.json create mode 100644 node-v0.8.14/deps/npm/test/disabled/fast/package.json create mode 100644 node-v0.8.14/deps/npm/test/disabled/package-bar/package.json create mode 100644 node-v0.8.14/deps/npm/test/disabled/package-config/package.json create mode 100755 node-v0.8.14/deps/npm/test/disabled/package-config/test.js create mode 100644 node-v0.8.14/deps/npm/test/disabled/package-foo/package.json create mode 100644 node-v0.8.14/deps/npm/test/disabled/slow/package.json create mode 100644 node-v0.8.14/deps/npm/test/disabled/startstop/package.json create mode 100644 node-v0.8.14/deps/npm/test/packages/npm-test-array-bin/README create mode 100644 node-v0.8.14/deps/npm/test/packages/npm-test-array-bin/bin/array-bin create mode 100644 node-v0.8.14/deps/npm/test/packages/npm-test-array-bin/package.json create mode 100644 node-v0.8.14/deps/npm/test/packages/npm-test-array-bin/test.js create mode 100644 node-v0.8.14/deps/npm/test/packages/npm-test-blerg/README create mode 100644 node-v0.8.14/deps/npm/test/packages/npm-test-blerg/package.json create mode 100644 node-v0.8.14/deps/npm/test/packages/npm-test-blerg/test.js create mode 100644 node-v0.8.14/deps/npm/test/packages/npm-test-blerg3/README create mode 100644 node-v0.8.14/deps/npm/test/packages/npm-test-blerg3/package.json create mode 100644 node-v0.8.14/deps/npm/test/packages/npm-test-blerg3/test.js create mode 100644 node-v0.8.14/deps/npm/test/packages/npm-test-bundled-git/README create mode 100644 node-v0.8.14/deps/npm/test/packages/npm-test-bundled-git/minimatch-expected.json create mode 100644 node-v0.8.14/deps/npm/test/packages/npm-test-bundled-git/package.json create mode 100644 node-v0.8.14/deps/npm/test/packages/npm-test-bundled-git/test.js create mode 100644 node-v0.8.14/deps/npm/test/packages/npm-test-dir-bin/README create mode 100644 node-v0.8.14/deps/npm/test/packages/npm-test-dir-bin/bin/dir-bin create mode 100644 node-v0.8.14/deps/npm/test/packages/npm-test-dir-bin/package.json create mode 100644 node-v0.8.14/deps/npm/test/packages/npm-test-dir-bin/test.js create mode 100644 node-v0.8.14/deps/npm/test/packages/npm-test-env-reader/README create mode 100644 node-v0.8.14/deps/npm/test/packages/npm-test-env-reader/package.json create mode 100755 node-v0.8.14/deps/npm/test/packages/npm-test-env-reader/test.js create mode 100644 node-v0.8.14/deps/npm/test/packages/npm-test-files/.npmignore rename node_modules/findit/test/foo/a/b/c/w => node-v0.8.14/deps/npm/test/packages/npm-test-files/include4 (100%) create mode 100644 node-v0.8.14/deps/npm/test/packages/npm-test-files/package.json rename node_modules/findit/test/foo/a/b/z => node-v0.8.14/deps/npm/test/packages/npm-test-files/sub/include (100%) rename node_modules/findit/test/foo/a/y => node-v0.8.14/deps/npm/test/packages/npm-test-files/sub/include2 (100%) create mode 100644 node-v0.8.14/deps/npm/test/packages/npm-test-files/sub/include4 create mode 100644 node-v0.8.14/deps/npm/test/packages/npm-test-files/test.sh create mode 100644 node-v0.8.14/deps/npm/test/packages/npm-test-ignore-nested-nm/README create mode 100644 node-v0.8.14/deps/npm/test/packages/npm-test-ignore-nested-nm/package.json create mode 100644 node-v0.8.14/deps/npm/test/packages/npm-test-ignore-nested-nm/test.js create mode 100644 node-v0.8.14/deps/npm/test/packages/npm-test-ignore/.npmignore create mode 100644 node-v0.8.14/deps/npm/test/packages/npm-test-ignore/README rename node_modules/findit/test/foo/x => node-v0.8.14/deps/npm/test/packages/npm-test-ignore/include4 (100%) create mode 100644 node-v0.8.14/deps/npm/test/packages/npm-test-ignore/package.json create mode 100644 node-v0.8.14/deps/npm/test/packages/npm-test-ignore/sub/include create mode 100644 node-v0.8.14/deps/npm/test/packages/npm-test-ignore/sub/include2 create mode 100644 node-v0.8.14/deps/npm/test/packages/npm-test-ignore/sub/include4 create mode 100644 node-v0.8.14/deps/npm/test/packages/npm-test-ignore/test.sh create mode 100644 node-v0.8.14/deps/npm/test/packages/npm-test-missing-bindir/README create mode 100644 node-v0.8.14/deps/npm/test/packages/npm-test-missing-bindir/package.json create mode 100644 node-v0.8.14/deps/npm/test/packages/npm-test-missing-bindir/test.js create mode 100644 node-v0.8.14/deps/npm/test/packages/npm-test-optional-deps/README create mode 100644 node-v0.8.14/deps/npm/test/packages/npm-test-optional-deps/package.json create mode 100644 node-v0.8.14/deps/npm/test/packages/npm-test-optional-deps/test.js create mode 100644 node-v0.8.14/deps/npm/test/packages/npm-test-platform-all/README create mode 100644 node-v0.8.14/deps/npm/test/packages/npm-test-platform-all/package.json create mode 100644 node-v0.8.14/deps/npm/test/packages/npm-test-platform/README create mode 100644 node-v0.8.14/deps/npm/test/packages/npm-test-platform/package.json create mode 100644 node-v0.8.14/deps/npm/test/packages/npm-test-private/README create mode 100644 node-v0.8.14/deps/npm/test/packages/npm-test-private/package.json create mode 100644 node-v0.8.14/deps/npm/test/packages/npm-test-shrinkwrap/README create mode 100644 node-v0.8.14/deps/npm/test/packages/npm-test-shrinkwrap/npm-shrinkwrap.json create mode 100644 node-v0.8.14/deps/npm/test/packages/npm-test-shrinkwrap/package.json create mode 100644 node-v0.8.14/deps/npm/test/packages/npm-test-shrinkwrap/test.sh create mode 100644 node-v0.8.14/deps/npm/test/packages/npm-test-test-package/README create mode 100644 node-v0.8.14/deps/npm/test/packages/npm-test-test-package/package.json create mode 100644 node-v0.8.14/deps/npm/test/packages/npm-test-url-dep/README create mode 100644 node-v0.8.14/deps/npm/test/packages/npm-test-url-dep/package.json create mode 100644 node-v0.8.14/deps/npm/test/run.js create mode 100644 node-v0.8.14/deps/npm/test/tap/false_name.js create mode 100644 node-v0.8.14/deps/npm/test/tap/false_name/index.js create mode 100644 node-v0.8.14/deps/npm/test/tap/false_name/package.json create mode 100644 node-v0.8.14/deps/npm/test/tap/publish-config.js create mode 100755 node-v0.8.14/deps/npm/test/update-test.sh create mode 100644 node-v0.8.14/deps/openssl/README.chromium create mode 100644 node-v0.8.14/deps/openssl/asm/Makefile create mode 100644 node-v0.8.14/deps/openssl/asm/x64-elf-gas/aes/aes-x86_64.s create mode 100644 node-v0.8.14/deps/openssl/asm/x64-elf-gas/bn/x86_64-mont.s create mode 100644 node-v0.8.14/deps/openssl/asm/x64-elf-gas/camellia/cmll-x86_64.s create mode 100644 node-v0.8.14/deps/openssl/asm/x64-elf-gas/md5/md5-x86_64.s create mode 100644 node-v0.8.14/deps/openssl/asm/x64-elf-gas/rc4/rc4-x86_64.s create mode 100644 node-v0.8.14/deps/openssl/asm/x64-elf-gas/sha/sha1-x86_64.s create mode 100644 node-v0.8.14/deps/openssl/asm/x64-elf-gas/sha/sha512-x86_64.s create mode 100644 node-v0.8.14/deps/openssl/asm/x64-elf-gas/whrlpool/wp-x86_64.s create mode 100644 node-v0.8.14/deps/openssl/asm/x64-elf-gas/x86_64cpuid.s create mode 100644 node-v0.8.14/deps/openssl/asm/x64-macosx-gas/aes/aes-x86_64.s create mode 100644 node-v0.8.14/deps/openssl/asm/x64-macosx-gas/bn/x86_64-mont.s create mode 100644 node-v0.8.14/deps/openssl/asm/x64-macosx-gas/camellia/cmll-x86_64.s create mode 100644 node-v0.8.14/deps/openssl/asm/x64-macosx-gas/md5/md5-x86_64.s create mode 100644 node-v0.8.14/deps/openssl/asm/x64-macosx-gas/rc4/rc4-x86_64.s create mode 100644 node-v0.8.14/deps/openssl/asm/x64-macosx-gas/sha/sha1-x86_64.s create mode 100644 node-v0.8.14/deps/openssl/asm/x64-macosx-gas/sha/sha512-x86_64.s create mode 100644 node-v0.8.14/deps/openssl/asm/x64-macosx-gas/whrlpool/wp-x86_64.s create mode 100644 node-v0.8.14/deps/openssl/asm/x64-macosx-gas/x86_64cpuid.s create mode 100644 node-v0.8.14/deps/openssl/asm/x64-win32-masm/aes/aes-x86_64.asm create mode 100644 node-v0.8.14/deps/openssl/asm/x64-win32-masm/bn/x86_64-mont.asm create mode 100644 node-v0.8.14/deps/openssl/asm/x64-win32-masm/camellia/cmll-x86_64.asm create mode 100644 node-v0.8.14/deps/openssl/asm/x64-win32-masm/md5/md5-x86_64.asm create mode 100644 node-v0.8.14/deps/openssl/asm/x64-win32-masm/rc4/rc4-x86_64.asm create mode 100644 node-v0.8.14/deps/openssl/asm/x64-win32-masm/sha/sha1-x86_64.asm create mode 100644 node-v0.8.14/deps/openssl/asm/x64-win32-masm/sha/sha512-x86_64.asm create mode 100644 node-v0.8.14/deps/openssl/asm/x64-win32-masm/whrlpool/wp-x86_64.asm create mode 100644 node-v0.8.14/deps/openssl/asm/x64-win32-masm/x86_64cpuid.asm create mode 100644 node-v0.8.14/deps/openssl/asm/x86-elf-gas/aes/aes-586.s create mode 100644 node-v0.8.14/deps/openssl/asm/x86-elf-gas/bf/bf-686.s create mode 100644 node-v0.8.14/deps/openssl/asm/x86-elf-gas/bn/x86-mont.s create mode 100644 node-v0.8.14/deps/openssl/asm/x86-elf-gas/bn/x86.s create mode 100644 node-v0.8.14/deps/openssl/asm/x86-elf-gas/camellia/cmll-x86.s create mode 100644 node-v0.8.14/deps/openssl/asm/x86-elf-gas/cast/cast-586.s create mode 100644 node-v0.8.14/deps/openssl/asm/x86-elf-gas/des/crypt586.s create mode 100644 node-v0.8.14/deps/openssl/asm/x86-elf-gas/des/des-586.s create mode 100644 node-v0.8.14/deps/openssl/asm/x86-elf-gas/md5/md5-586.s create mode 100644 node-v0.8.14/deps/openssl/asm/x86-elf-gas/rc4/rc4-586.s create mode 100644 node-v0.8.14/deps/openssl/asm/x86-elf-gas/rc5/rc5-586.s create mode 100644 node-v0.8.14/deps/openssl/asm/x86-elf-gas/ripemd/rmd-586.s create mode 100644 node-v0.8.14/deps/openssl/asm/x86-elf-gas/sha/sha1-586.s create mode 100644 node-v0.8.14/deps/openssl/asm/x86-elf-gas/sha/sha256-586.s create mode 100644 node-v0.8.14/deps/openssl/asm/x86-elf-gas/sha/sha512-586.s create mode 100644 node-v0.8.14/deps/openssl/asm/x86-elf-gas/whrlpool/wp-mmx.s create mode 100644 node-v0.8.14/deps/openssl/asm/x86-elf-gas/x86cpuid.s create mode 100644 node-v0.8.14/deps/openssl/asm/x86-macosx-gas/aes/aes-586.s create mode 100644 node-v0.8.14/deps/openssl/asm/x86-macosx-gas/bf/bf-686.s create mode 100644 node-v0.8.14/deps/openssl/asm/x86-macosx-gas/bn/x86-mont.s create mode 100644 node-v0.8.14/deps/openssl/asm/x86-macosx-gas/bn/x86.s create mode 100644 node-v0.8.14/deps/openssl/asm/x86-macosx-gas/camellia/cmll-x86.s create mode 100644 node-v0.8.14/deps/openssl/asm/x86-macosx-gas/cast/cast-586.s create mode 100644 node-v0.8.14/deps/openssl/asm/x86-macosx-gas/des/crypt586.s create mode 100644 node-v0.8.14/deps/openssl/asm/x86-macosx-gas/des/des-586.s create mode 100644 node-v0.8.14/deps/openssl/asm/x86-macosx-gas/md5/md5-586.s create mode 100644 node-v0.8.14/deps/openssl/asm/x86-macosx-gas/rc4/rc4-586.s create mode 100644 node-v0.8.14/deps/openssl/asm/x86-macosx-gas/rc5/rc5-586.s create mode 100644 node-v0.8.14/deps/openssl/asm/x86-macosx-gas/ripemd/rmd-586.s create mode 100644 node-v0.8.14/deps/openssl/asm/x86-macosx-gas/sha/sha1-586.s create mode 100644 node-v0.8.14/deps/openssl/asm/x86-macosx-gas/sha/sha256-586.s create mode 100644 node-v0.8.14/deps/openssl/asm/x86-macosx-gas/sha/sha512-586.s create mode 100644 node-v0.8.14/deps/openssl/asm/x86-macosx-gas/whrlpool/wp-mmx.s create mode 100644 node-v0.8.14/deps/openssl/asm/x86-macosx-gas/x86cpuid.s create mode 100644 node-v0.8.14/deps/openssl/asm/x86-win32-masm/aes/aes-586.asm create mode 100644 node-v0.8.14/deps/openssl/asm/x86-win32-masm/bf/bf-686.asm create mode 100644 node-v0.8.14/deps/openssl/asm/x86-win32-masm/bn/x86-mont.asm create mode 100644 node-v0.8.14/deps/openssl/asm/x86-win32-masm/bn/x86.asm create mode 100644 node-v0.8.14/deps/openssl/asm/x86-win32-masm/camellia/cmll-x86.asm create mode 100644 node-v0.8.14/deps/openssl/asm/x86-win32-masm/cast/cast-586.asm create mode 100644 node-v0.8.14/deps/openssl/asm/x86-win32-masm/des/crypt586.asm create mode 100644 node-v0.8.14/deps/openssl/asm/x86-win32-masm/des/des-586.asm create mode 100644 node-v0.8.14/deps/openssl/asm/x86-win32-masm/md5/md5-586.asm create mode 100644 node-v0.8.14/deps/openssl/asm/x86-win32-masm/rc4/rc4-586.asm create mode 100644 node-v0.8.14/deps/openssl/asm/x86-win32-masm/rc5/rc5-586.asm create mode 100644 node-v0.8.14/deps/openssl/asm/x86-win32-masm/ripemd/rmd-586.asm create mode 100644 node-v0.8.14/deps/openssl/asm/x86-win32-masm/sha/sha1-586.asm create mode 100644 node-v0.8.14/deps/openssl/asm/x86-win32-masm/sha/sha256-586.asm create mode 100644 node-v0.8.14/deps/openssl/asm/x86-win32-masm/sha/sha512-586.asm create mode 100644 node-v0.8.14/deps/openssl/asm/x86-win32-masm/whrlpool/wp-mmx.asm create mode 100644 node-v0.8.14/deps/openssl/asm/x86-win32-masm/x86cpuid.asm create mode 100644 node-v0.8.14/deps/openssl/buildinf.h create mode 100644 node-v0.8.14/deps/openssl/config/android/openssl/opensslconf.h create mode 100644 node-v0.8.14/deps/openssl/config/k8/openssl/opensslconf-posix.h create mode 100644 node-v0.8.14/deps/openssl/config/k8/openssl/opensslconf-win32.h create mode 100644 node-v0.8.14/deps/openssl/config/k8/openssl/opensslconf.h create mode 100644 node-v0.8.14/deps/openssl/config/piii/openssl/opensslconf-posix.h create mode 100644 node-v0.8.14/deps/openssl/config/piii/openssl/opensslconf-win32.h create mode 100644 node-v0.8.14/deps/openssl/config/piii/openssl/opensslconf.h create mode 100644 node-v0.8.14/deps/openssl/openssl.gyp create mode 100644 node-v0.8.14/deps/openssl/openssl/ACKNOWLEDGMENTS create mode 100644 node-v0.8.14/deps/openssl/openssl/CHANGES create mode 100644 node-v0.8.14/deps/openssl/openssl/CHANGES.SSLeay create mode 100755 node-v0.8.14/deps/openssl/openssl/Configure create mode 100644 node-v0.8.14/deps/openssl/openssl/FAQ create mode 100644 node-v0.8.14/deps/openssl/openssl/INSTALL create mode 100644 node-v0.8.14/deps/openssl/openssl/INSTALL.DJGPP create mode 100644 node-v0.8.14/deps/openssl/openssl/INSTALL.MacOS create mode 100644 node-v0.8.14/deps/openssl/openssl/INSTALL.NW create mode 100644 node-v0.8.14/deps/openssl/openssl/INSTALL.OS2 create mode 100644 node-v0.8.14/deps/openssl/openssl/INSTALL.VMS create mode 100644 node-v0.8.14/deps/openssl/openssl/INSTALL.W32 create mode 100644 node-v0.8.14/deps/openssl/openssl/INSTALL.W64 create mode 100644 node-v0.8.14/deps/openssl/openssl/INSTALL.WCE create mode 100644 node-v0.8.14/deps/openssl/openssl/LICENSE create mode 100644 node-v0.8.14/deps/openssl/openssl/MacOS/GUSI_Init.cpp create mode 100644 node-v0.8.14/deps/openssl/openssl/MacOS/GetHTTPS.src/CPStringUtils.cpp create mode 100644 node-v0.8.14/deps/openssl/openssl/MacOS/GetHTTPS.src/CPStringUtils.hpp create mode 100644 node-v0.8.14/deps/openssl/openssl/MacOS/GetHTTPS.src/ErrorHandling.cpp create mode 100644 node-v0.8.14/deps/openssl/openssl/MacOS/GetHTTPS.src/ErrorHandling.hpp create mode 100644 node-v0.8.14/deps/openssl/openssl/MacOS/GetHTTPS.src/GetHTTPS.cpp create mode 100644 node-v0.8.14/deps/openssl/openssl/MacOS/GetHTTPS.src/MacSocket.cpp create mode 100644 node-v0.8.14/deps/openssl/openssl/MacOS/GetHTTPS.src/MacSocket.h create mode 100644 node-v0.8.14/deps/openssl/openssl/MacOS/OpenSSL.mcp.hqx create mode 100644 node-v0.8.14/deps/openssl/openssl/MacOS/Randomizer.cpp create mode 100644 node-v0.8.14/deps/openssl/openssl/MacOS/Randomizer.h create mode 100644 node-v0.8.14/deps/openssl/openssl/MacOS/TODO create mode 100644 node-v0.8.14/deps/openssl/openssl/MacOS/_MWERKS_GUSI_prefix.h create mode 100644 node-v0.8.14/deps/openssl/openssl/MacOS/_MWERKS_prefix.h create mode 100644 node-v0.8.14/deps/openssl/openssl/MacOS/buildinf.h create mode 100644 node-v0.8.14/deps/openssl/openssl/MacOS/mklinks.as.hqx create mode 100644 node-v0.8.14/deps/openssl/openssl/MacOS/opensslconf.h create mode 100644 node-v0.8.14/deps/openssl/openssl/Makefile create mode 100644 node-v0.8.14/deps/openssl/openssl/Makefile.org create mode 100644 node-v0.8.14/deps/openssl/openssl/Makefile.shared create mode 100644 node-v0.8.14/deps/openssl/openssl/NEWS create mode 100644 node-v0.8.14/deps/openssl/openssl/Netware/build.bat create mode 100644 node-v0.8.14/deps/openssl/openssl/Netware/cpy_tests.bat create mode 100644 node-v0.8.14/deps/openssl/openssl/Netware/do_tests.pl create mode 100644 node-v0.8.14/deps/openssl/openssl/Netware/globals.txt create mode 100644 node-v0.8.14/deps/openssl/openssl/Netware/readme.txt create mode 100644 node-v0.8.14/deps/openssl/openssl/Netware/set_env.bat create mode 100644 node-v0.8.14/deps/openssl/openssl/PROBLEMS create mode 100644 node-v0.8.14/deps/openssl/openssl/README create mode 100644 node-v0.8.14/deps/openssl/openssl/README.ASN1 create mode 100644 node-v0.8.14/deps/openssl/openssl/README.ENGINE create mode 100644 node-v0.8.14/deps/openssl/openssl/VMS/TODO create mode 100644 node-v0.8.14/deps/openssl/openssl/VMS/VMSify-conf.pl create mode 100644 node-v0.8.14/deps/openssl/openssl/VMS/WISHLIST.TXT create mode 100644 node-v0.8.14/deps/openssl/openssl/VMS/install-vms.com create mode 100644 node-v0.8.14/deps/openssl/openssl/VMS/mkshared.com create mode 100644 node-v0.8.14/deps/openssl/openssl/VMS/multinet_shr.opt create mode 100644 node-v0.8.14/deps/openssl/openssl/VMS/openssl_startup.com create mode 100644 node-v0.8.14/deps/openssl/openssl/VMS/openssl_undo.com create mode 100644 node-v0.8.14/deps/openssl/openssl/VMS/openssl_utils.com create mode 100644 node-v0.8.14/deps/openssl/openssl/VMS/socketshr_shr.opt create mode 100644 node-v0.8.14/deps/openssl/openssl/VMS/tcpip_shr_decc.opt create mode 100644 node-v0.8.14/deps/openssl/openssl/VMS/test-includes.com create mode 100644 node-v0.8.14/deps/openssl/openssl/VMS/ucx_shr_decc.opt create mode 100644 node-v0.8.14/deps/openssl/openssl/VMS/ucx_shr_decc_log.opt create mode 100644 node-v0.8.14/deps/openssl/openssl/VMS/ucx_shr_vaxc.opt create mode 100644 node-v0.8.14/deps/openssl/openssl/bugs/MS create mode 100644 node-v0.8.14/deps/openssl/openssl/bugs/SSLv3 create mode 100644 node-v0.8.14/deps/openssl/openssl/bugs/alpha.c create mode 100644 node-v0.8.14/deps/openssl/openssl/bugs/dggccbug.c create mode 100644 node-v0.8.14/deps/openssl/openssl/bugs/sgiccbug.c create mode 100644 node-v0.8.14/deps/openssl/openssl/bugs/sslref.dif create mode 100644 node-v0.8.14/deps/openssl/openssl/bugs/stream.c create mode 100644 node-v0.8.14/deps/openssl/openssl/bugs/ultrixcc.c create mode 100644 node-v0.8.14/deps/openssl/openssl/certs/README.RootCerts create mode 100644 node-v0.8.14/deps/openssl/openssl/certs/demo/ca-cert.pem create mode 100644 node-v0.8.14/deps/openssl/openssl/certs/demo/dsa-ca.pem create mode 100644 node-v0.8.14/deps/openssl/openssl/certs/demo/dsa-pca.pem create mode 100644 node-v0.8.14/deps/openssl/openssl/certs/demo/pca-cert.pem create mode 100644 node-v0.8.14/deps/openssl/openssl/certs/expired/ICE.crl create mode 100755 node-v0.8.14/deps/openssl/openssl/config create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/LPdir_nyi.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/LPdir_unix.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/LPdir_vms.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/LPdir_win.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/LPdir_win32.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/LPdir_wince.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/Makefile create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/aes/Makefile create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/aes/README create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/aes/aes.h create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/aes/aes_cbc.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/aes/aes_cfb.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/aes/aes_core.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/aes/aes_ctr.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/aes/aes_ecb.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/aes/aes_ige.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/aes/aes_locl.h create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/aes/aes_misc.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/aes/aes_ofb.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/aes/aes_wrap.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/aes/aes_x86core.c create mode 100755 node-v0.8.14/deps/openssl/openssl/crypto/aes/asm/aes-586.pl create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/aes/asm/aes-armv4.pl create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/aes/asm/aes-ia64.S create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/aes/asm/aes-ppc.pl create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/aes/asm/aes-s390x.pl create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/aes/asm/aes-sparcv9.pl create mode 100755 node-v0.8.14/deps/openssl/openssl/crypto/aes/asm/aes-x86_64.pl create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/alphacpuid.pl create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/asn1/Makefile create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/asn1/a_bitstr.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/asn1/a_bool.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/asn1/a_bytes.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/asn1/a_d2i_fp.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/asn1/a_digest.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/asn1/a_dup.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/asn1/a_enum.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/asn1/a_gentm.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/asn1/a_i2d_fp.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/asn1/a_int.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/asn1/a_mbstr.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/asn1/a_object.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/asn1/a_octet.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/asn1/a_print.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/asn1/a_set.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/asn1/a_sign.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/asn1/a_strex.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/asn1/a_strnid.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/asn1/a_time.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/asn1/a_type.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/asn1/a_utctm.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/asn1/a_utf8.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/asn1/a_verify.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/asn1/ameth_lib.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/asn1/asn1.h create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/asn1/asn1_err.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/asn1/asn1_gen.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/asn1/asn1_lib.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/asn1/asn1_locl.h create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/asn1/asn1_mac.h create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/asn1/asn1_par.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/asn1/asn1t.h create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/asn1/asn_mime.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/asn1/asn_moid.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/asn1/asn_pack.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/asn1/bio_asn1.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/asn1/bio_ndef.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/asn1/charmap.h create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/asn1/charmap.pl create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/asn1/d2i_pr.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/asn1/d2i_pu.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/asn1/evp_asn1.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/asn1/f_enum.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/asn1/f_int.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/asn1/f_string.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/asn1/i2d_pr.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/asn1/i2d_pu.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/asn1/n_pkey.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/asn1/nsseq.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/asn1/p5_pbe.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/asn1/p5_pbev2.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/asn1/p8_pkey.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/asn1/t_bitst.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/asn1/t_crl.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/asn1/t_pkey.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/asn1/t_req.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/asn1/t_spki.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/asn1/t_x509.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/asn1/t_x509a.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/asn1/tasn_dec.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/asn1/tasn_enc.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/asn1/tasn_fre.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/asn1/tasn_new.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/asn1/tasn_prn.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/asn1/tasn_typ.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/asn1/tasn_utl.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/asn1/x_algor.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/asn1/x_attrib.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/asn1/x_bignum.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/asn1/x_crl.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/asn1/x_exten.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/asn1/x_info.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/asn1/x_long.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/asn1/x_name.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/asn1/x_nx509.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/asn1/x_pkey.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/asn1/x_pubkey.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/asn1/x_req.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/asn1/x_sig.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/asn1/x_spki.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/asn1/x_val.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/asn1/x_x509.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/asn1/x_x509a.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/bf/COPYRIGHT create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/bf/INSTALL create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/bf/Makefile create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/bf/README create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/bf/VERSION create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/bf/asm/bf-586.pl create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/bf/asm/bf-686.pl create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/bf/asm/readme create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/bf/bf_cbc.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/bf/bf_cfb64.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/bf/bf_ecb.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/bf/bf_enc.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/bf/bf_locl.h create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/bf/bf_ofb64.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/bf/bf_opts.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/bf/bf_pi.h create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/bf/bf_skey.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/bf/bfs.cpp create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/bf/bfspeed.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/bf/bftest.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/bf/blowfish.h create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/bio/Makefile create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/bio/b_dump.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/bio/b_print.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/bio/b_sock.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/bio/bf_buff.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/bio/bf_lbuf.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/bio/bf_nbio.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/bio/bf_null.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/bio/bio.h create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/bio/bio_cb.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/bio/bio_err.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/bio/bio_lcl.h create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/bio/bio_lib.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/bio/bss_acpt.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/bio/bss_bio.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/bio/bss_conn.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/bio/bss_dgram.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/bio/bss_fd.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/bio/bss_file.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/bio/bss_log.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/bio/bss_mem.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/bio/bss_null.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/bio/bss_rtcp.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/bio/bss_sock.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/bn/Makefile create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/bn/asm/README create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/bn/asm/alpha-mont.pl create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/bn/asm/armv4-mont.pl create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/bn/asm/bn-586.pl create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/bn/asm/co-586.pl create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/bn/asm/ia64.S create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/bn/asm/mips3-mont.pl create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/bn/asm/mips3.s create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/bn/asm/pa-risc2.s create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/bn/asm/pa-risc2W.s create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/bn/asm/ppc-mont.pl create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/bn/asm/ppc.pl create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/bn/asm/ppc64-mont.pl create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/bn/asm/s390x-mont.pl create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/bn/asm/s390x.S create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/bn/asm/sparcv8.S create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/bn/asm/sparcv8plus.S create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/bn/asm/sparcv9-mont.pl create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/bn/asm/sparcv9a-mont.pl create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/bn/asm/via-mont.pl create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/bn/asm/vms.mar create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/bn/asm/x86-mont.pl create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/bn/asm/x86.pl create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/bn/asm/x86/add.pl create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/bn/asm/x86/comba.pl create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/bn/asm/x86/div.pl create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/bn/asm/x86/f create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/bn/asm/x86/mul.pl create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/bn/asm/x86/mul_add.pl create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/bn/asm/x86/sqr.pl create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/bn/asm/x86/sub.pl create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/bn/asm/x86_64-gcc.c create mode 100755 node-v0.8.14/deps/openssl/openssl/crypto/bn/asm/x86_64-mont.pl create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/bn/asm/x86_64-win32-masm.asm create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/bn/bn.h create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/bn/bn.mul create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/bn/bn_add.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/bn/bn_asm.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/bn/bn_blind.c create mode 100755 node-v0.8.14/deps/openssl/openssl/crypto/bn/bn_const.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/bn/bn_ctx.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/bn/bn_depr.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/bn/bn_div.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/bn/bn_err.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/bn/bn_exp.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/bn/bn_exp2.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/bn/bn_gcd.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/bn/bn_gf2m.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/bn/bn_kron.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/bn/bn_lcl.h create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/bn/bn_lib.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/bn/bn_mod.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/bn/bn_mont.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/bn/bn_mpi.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/bn/bn_mul.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/bn/bn_nist.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/bn/bn_prime.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/bn/bn_prime.h create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/bn/bn_prime.pl create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/bn/bn_print.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/bn/bn_rand.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/bn/bn_recp.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/bn/bn_shift.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/bn/bn_sqr.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/bn/bn_sqrt.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/bn/bn_word.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/bn/bnspeed.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/bn/bntest.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/bn/divtest.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/bn/exp.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/bn/expspeed.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/bn/exptest.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/bn/todo create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/bn/vms-helper.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/buffer/Makefile create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/buffer/buf_err.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/buffer/buffer.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/buffer/buffer.h create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/camellia/Makefile create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/camellia/asm/cmll-x86.pl create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/camellia/asm/cmll-x86_64.pl create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/camellia/camellia.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/camellia/camellia.h create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/camellia/cmll_cbc.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/camellia/cmll_cfb.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/camellia/cmll_ctr.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/camellia/cmll_ecb.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/camellia/cmll_locl.h create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/camellia/cmll_misc.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/camellia/cmll_ofb.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/cast/Makefile create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/cast/asm/cast-586.pl create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/cast/asm/readme create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/cast/c_cfb64.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/cast/c_ecb.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/cast/c_enc.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/cast/c_ofb64.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/cast/c_skey.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/cast/cast.h create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/cast/cast_lcl.h create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/cast/cast_s.h create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/cast/cast_spd.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/cast/castopts.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/cast/casts.cpp create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/cast/casttest.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/cms/Makefile create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/cms/cms.h create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/cms/cms_asn1.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/cms/cms_att.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/cms/cms_cd.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/cms/cms_dd.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/cms/cms_enc.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/cms/cms_env.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/cms/cms_err.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/cms/cms_ess.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/cms/cms_io.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/cms/cms_lcl.h create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/cms/cms_lib.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/cms/cms_sd.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/cms/cms_smime.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/comp/Makefile create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/comp/c_rle.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/comp/c_zlib.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/comp/comp.h create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/comp/comp_err.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/comp/comp_lib.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/conf/Makefile create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/conf/README create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/conf/cnf_save.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/conf/conf.h create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/conf/conf_api.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/conf/conf_api.h create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/conf/conf_def.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/conf/conf_def.h create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/conf/conf_err.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/conf/conf_lib.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/conf/conf_mall.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/conf/conf_mod.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/conf/conf_sap.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/conf/keysets.pl create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/conf/ssleay.cnf create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/conf/test.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/cpt_err.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/cryptlib.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/cryptlib.h create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/crypto-lib.com create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/crypto.h create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/cversion.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/des/COPYRIGHT create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/des/DES.pm create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/des/DES.xs create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/des/FILES0 create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/des/INSTALL create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/des/Imakefile create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/des/KERBEROS create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/des/Makefile create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/des/README create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/des/VERSION create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/des/asm/crypt586.pl create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/des/asm/des-586.pl create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/des/asm/des_enc.m4 create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/des/asm/desboth.pl create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/des/asm/readme create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/des/cbc3_enc.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/des/cbc_cksm.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/des/cbc_enc.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/des/cfb64ede.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/des/cfb64enc.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/des/cfb_enc.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/des/des-lib.com create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/des/des.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/des/des.h create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/des/des.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/des/des3s.cpp create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/des/des_enc.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/des/des_locl.h create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/des/des_old.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/des/des_old.h create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/des/des_old2.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/des/des_opts.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/des/des_ver.h create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/des/dess.cpp create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/des/destest.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/des/ecb3_enc.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/des/ecb_enc.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/des/ede_cbcm_enc.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/des/enc_read.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/des/enc_writ.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/des/fcrypt.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/des/fcrypt_b.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/des/makefile.bc create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/des/ncbc_enc.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/des/ofb64ede.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/des/ofb64enc.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/des/ofb_enc.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/des/options.txt create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/des/pcbc_enc.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/des/qud_cksm.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/des/rand_key.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/des/read2pwd.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/des/read_pwd.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/des/rpc_des.h create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/des/rpc_enc.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/des/rpw.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/des/set_key.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/des/speed.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/des/spr.h create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/des/str2key.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/des/t/test create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/des/times/486-50.sol create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/des/times/586-100.lnx create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/des/times/686-200.fre create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/des/times/aix.cc create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/des/times/alpha.cc create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/des/times/hpux.cc create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/des/times/sparc.gcc create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/des/times/usparc.cc create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/des/typemap create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/des/xcbc_enc.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/dh/Makefile create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/dh/dh.h create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/dh/dh1024.pem create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/dh/dh192.pem create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/dh/dh2048.pem create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/dh/dh4096.pem create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/dh/dh512.pem create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/dh/dh_ameth.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/dh/dh_asn1.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/dh/dh_check.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/dh/dh_depr.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/dh/dh_err.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/dh/dh_gen.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/dh/dh_key.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/dh/dh_lib.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/dh/dh_pmeth.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/dh/dh_prn.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/dh/dhtest.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/dh/example create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/dh/generate create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/dh/p1024.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/dh/p192.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/dh/p512.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/dsa/Makefile create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/dsa/README create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/dsa/dsa.h create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/dsa/dsa_ameth.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/dsa/dsa_asn1.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/dsa/dsa_depr.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/dsa/dsa_err.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/dsa/dsa_gen.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/dsa/dsa_key.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/dsa/dsa_lib.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/dsa/dsa_locl.h create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/dsa/dsa_ossl.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/dsa/dsa_pmeth.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/dsa/dsa_prn.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/dsa/dsa_sign.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/dsa/dsa_vrf.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/dsa/dsagen.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/dsa/dsatest.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/dsa/fips186a.txt create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/dso/Makefile create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/dso/README create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/dso/dso.h create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/dso/dso_beos.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/dso/dso_dl.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/dso/dso_dlfcn.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/dso/dso_err.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/dso/dso_lib.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/dso/dso_null.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/dso/dso_openssl.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/dso/dso_vms.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/dso/dso_win32.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/ebcdic.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/ebcdic.h create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/ec/Makefile create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/ec/ec.h create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/ec/ec2_mult.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/ec/ec2_smpl.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/ec/ec_ameth.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/ec/ec_asn1.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/ec/ec_check.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/ec/ec_curve.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/ec/ec_cvt.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/ec/ec_err.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/ec/ec_key.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/ec/ec_lcl.h create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/ec/ec_lib.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/ec/ec_mult.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/ec/ec_pmeth.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/ec/ec_print.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/ec/eck_prn.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/ec/ecp_mont.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/ec/ecp_nist.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/ec/ecp_smpl.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/ec/ectest.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/ecdh/Makefile create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/ecdh/ecdh.h create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/ecdh/ecdhtest.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/ecdh/ech_err.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/ecdh/ech_key.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/ecdh/ech_lib.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/ecdh/ech_locl.h create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/ecdh/ech_ossl.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/ecdsa/Makefile create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/ecdsa/ecdsa.h create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/ecdsa/ecdsatest.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/ecdsa/ecs_asn1.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/ecdsa/ecs_err.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/ecdsa/ecs_lib.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/ecdsa/ecs_locl.h create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/ecdsa/ecs_ossl.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/ecdsa/ecs_sign.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/ecdsa/ecs_vrf.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/engine/Makefile create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/engine/README create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/engine/eng_all.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/engine/eng_cnf.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/engine/eng_cryptodev.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/engine/eng_ctrl.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/engine/eng_dyn.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/engine/eng_err.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/engine/eng_fat.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/engine/eng_init.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/engine/eng_int.h create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/engine/eng_lib.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/engine/eng_list.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/engine/eng_openssl.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/engine/eng_pkey.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/engine/eng_table.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/engine/engine.h create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/engine/enginetest.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/engine/tb_asnmth.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/engine/tb_cipher.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/engine/tb_dh.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/engine/tb_digest.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/engine/tb_dsa.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/engine/tb_ecdh.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/engine/tb_ecdsa.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/engine/tb_pkmeth.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/engine/tb_rand.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/engine/tb_rsa.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/engine/tb_store.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/err/Makefile create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/err/err.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/err/err.h create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/err/err_all.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/err/err_prn.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/err/openssl.ec create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/evp/Makefile create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/evp/bio_b64.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/evp/bio_enc.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/evp/bio_md.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/evp/bio_ok.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/evp/c_all.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/evp/c_allc.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/evp/c_alld.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/evp/digest.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/evp/e_aes.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/evp/e_bf.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/evp/e_camellia.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/evp/e_cast.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/evp/e_des.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/evp/e_des3.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/evp/e_dsa.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/evp/e_idea.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/evp/e_null.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/evp/e_old.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/evp/e_rc2.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/evp/e_rc4.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/evp/e_rc5.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/evp/e_seed.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/evp/e_xcbc_d.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/evp/encode.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/evp/evp.h create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/evp/evp_acnf.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/evp/evp_enc.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/evp/evp_err.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/evp/evp_key.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/evp/evp_lib.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/evp/evp_locl.h create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/evp/evp_pbe.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/evp/evp_pkey.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/evp/evp_test.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/evp/evptests.txt create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/evp/m_dss.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/evp/m_dss1.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/evp/m_ecdsa.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/evp/m_md2.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/evp/m_md4.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/evp/m_md5.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/evp/m_mdc2.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/evp/m_null.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/evp/m_ripemd.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/evp/m_sha.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/evp/m_sha1.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/evp/m_sigver.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/evp/m_wp.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/evp/names.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/evp/openbsd_hw.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/evp/p5_crpt.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/evp/p5_crpt2.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/evp/p_dec.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/evp/p_enc.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/evp/p_lib.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/evp/p_open.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/evp/p_seal.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/evp/p_sign.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/evp/p_verify.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/evp/pmeth_fn.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/evp/pmeth_gn.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/evp/pmeth_lib.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/ex_data.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/hmac/Makefile create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/hmac/hm_ameth.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/hmac/hm_pmeth.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/hmac/hmac.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/hmac/hmac.h create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/hmac/hmactest.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/ia64cpuid.S create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/idea/Makefile create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/idea/i_cbc.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/idea/i_cfb64.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/idea/i_ecb.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/idea/i_ofb64.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/idea/i_skey.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/idea/idea.h create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/idea/idea_lcl.h create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/idea/idea_spd.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/idea/ideatest.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/idea/version create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/install-crypto.com create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/jpake/Makefile create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/jpake/jpake.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/jpake/jpake.h create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/jpake/jpake_err.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/jpake/jpaketest.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/krb5/Makefile create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/krb5/krb5_asn.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/krb5/krb5_asn.h create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/lhash/Makefile create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/lhash/lh_stats.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/lhash/lh_test.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/lhash/lhash.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/lhash/lhash.h create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/lhash/num.pl create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/md2/Makefile create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/md2/md2.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/md2/md2.h create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/md2/md2_dgst.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/md2/md2_one.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/md2/md2test.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/md32_common.h create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/md4/Makefile create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/md4/md4.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/md4/md4.h create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/md4/md4_dgst.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/md4/md4_locl.h create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/md4/md4_one.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/md4/md4s.cpp create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/md4/md4test.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/md5/Makefile create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/md5/asm/md5-586.pl create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/md5/asm/md5-ia64.S create mode 100755 node-v0.8.14/deps/openssl/openssl/crypto/md5/asm/md5-x86_64.pl create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/md5/md5.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/md5/md5.h create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/md5/md5_dgst.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/md5/md5_locl.h create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/md5/md5_one.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/md5/md5s.cpp create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/md5/md5test.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/mdc2/Makefile create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/mdc2/mdc2.h create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/mdc2/mdc2_one.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/mdc2/mdc2dgst.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/mdc2/mdc2test.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/mem.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/mem_clr.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/mem_dbg.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/modes/Makefile create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/modes/cbc128.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/modes/cfb128.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/modes/ctr128.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/modes/cts128.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/modes/modes.h create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/modes/ofb128.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/o_dir.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/o_dir.h create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/o_dir_test.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/o_str.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/o_str.h create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/o_time.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/o_time.h create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/objects/Makefile create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/objects/o_names.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/objects/obj_dat.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/objects/obj_dat.h create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/objects/obj_dat.pl create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/objects/obj_err.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/objects/obj_lib.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/objects/obj_mac.h create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/objects/obj_mac.num create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/objects/obj_xref.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/objects/obj_xref.h create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/objects/obj_xref.txt create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/objects/objects.README create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/objects/objects.h create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/objects/objects.pl create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/objects/objects.txt create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/objects/objxref.pl create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/ocsp/Makefile create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/ocsp/ocsp.h create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/ocsp/ocsp_asn.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/ocsp/ocsp_cl.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/ocsp/ocsp_err.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/ocsp/ocsp_ext.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/ocsp/ocsp_ht.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/ocsp/ocsp_lib.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/ocsp/ocsp_prn.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/ocsp/ocsp_srv.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/ocsp/ocsp_vfy.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/opensslconf.h.in create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/opensslv.h create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/ossl_typ.h create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/pem/Makefile create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/pem/message create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/pem/pem.h create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/pem/pem2.h create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/pem/pem_all.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/pem/pem_err.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/pem/pem_info.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/pem/pem_lib.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/pem/pem_oth.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/pem/pem_pk8.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/pem/pem_pkey.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/pem/pem_seal.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/pem/pem_sign.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/pem/pem_x509.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/pem/pem_xaux.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/pem/pkcs7.lis create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/pem/pvkfmt.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/perlasm/cbc.pl create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/perlasm/ppc-xlate.pl create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/perlasm/readme create mode 100755 node-v0.8.14/deps/openssl/openssl/crypto/perlasm/x86_64-xlate.pl create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/perlasm/x86asm.pl create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/perlasm/x86gas.pl create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/perlasm/x86masm.pl create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/perlasm/x86nasm.pl create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/pkcs12/Makefile create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/pkcs12/p12_add.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/pkcs12/p12_asn.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/pkcs12/p12_attr.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/pkcs12/p12_crpt.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/pkcs12/p12_crt.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/pkcs12/p12_decr.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/pkcs12/p12_init.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/pkcs12/p12_key.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/pkcs12/p12_kiss.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/pkcs12/p12_mutl.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/pkcs12/p12_npas.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/pkcs12/p12_p8d.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/pkcs12/p12_p8e.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/pkcs12/p12_utl.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/pkcs12/pk12err.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/pkcs12/pkcs12.h create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/pkcs7/Makefile create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/pkcs7/bio_ber.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/pkcs7/bio_pk7.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/pkcs7/dec.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/pkcs7/des.pem create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/pkcs7/doc create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/pkcs7/enc.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/pkcs7/es1.pem create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/pkcs7/example.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/pkcs7/example.h create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/pkcs7/info.pem create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/pkcs7/infokey.pem create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/pkcs7/p7/a1 create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/pkcs7/p7/a2 create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/pkcs7/p7/cert.p7c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/pkcs7/p7/smime.p7m create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/pkcs7/p7/smime.p7s create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/pkcs7/pk7_asn1.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/pkcs7/pk7_attr.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/pkcs7/pk7_dgst.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/pkcs7/pk7_doit.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/pkcs7/pk7_enc.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/pkcs7/pk7_lib.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/pkcs7/pk7_mime.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/pkcs7/pk7_smime.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/pkcs7/pkcs7.h create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/pkcs7/pkcs7err.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/pkcs7/server.pem create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/pkcs7/sign.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/pkcs7/t/3des.pem create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/pkcs7/t/3dess.pem create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/pkcs7/t/c.pem create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/pkcs7/t/ff create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/pkcs7/t/msie-e create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/pkcs7/t/msie-e.pem create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/pkcs7/t/msie-enc-01 create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/pkcs7/t/msie-enc-01.pem create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/pkcs7/t/msie-enc-02 create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/pkcs7/t/msie-enc-02.pem create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/pkcs7/t/msie-s-a-e create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/pkcs7/t/msie-s-a-e.pem create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/pkcs7/t/nav-smime create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/pkcs7/t/s.pem create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/pkcs7/t/server.pem create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/pkcs7/verify.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/ppccpuid.pl create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/pqueue/Makefile create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/pqueue/pq_test.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/pqueue/pqueue.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/pqueue/pqueue.h create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/rand/Makefile create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/rand/md_rand.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/rand/rand.h create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/rand/rand_egd.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/rand/rand_err.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/rand/rand_lcl.h create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/rand/rand_lib.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/rand/rand_nw.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/rand/rand_os2.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/rand/rand_unix.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/rand/rand_vms.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/rand/rand_win.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/rand/randfile.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/rand/randtest.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/rc2/Makefile create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/rc2/rc2.h create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/rc2/rc2_cbc.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/rc2/rc2_ecb.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/rc2/rc2_locl.h create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/rc2/rc2_skey.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/rc2/rc2cfb64.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/rc2/rc2ofb64.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/rc2/rc2speed.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/rc2/rc2test.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/rc2/rrc2.doc create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/rc2/tab.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/rc2/version create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/rc4/Makefile create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/rc4/asm/rc4-586.pl create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/rc4/asm/rc4-ia64.pl create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/rc4/asm/rc4-s390x.pl create mode 100755 node-v0.8.14/deps/openssl/openssl/crypto/rc4/asm/rc4-x86_64.pl create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/rc4/rc4.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/rc4/rc4.h create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/rc4/rc4_enc.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/rc4/rc4_locl.h create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/rc4/rc4_skey.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/rc4/rc4s.cpp create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/rc4/rc4speed.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/rc4/rc4test.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/rc4/rrc4.doc create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/rc5/Makefile create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/rc5/asm/rc5-586.pl create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/rc5/rc5.h create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/rc5/rc5_ecb.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/rc5/rc5_enc.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/rc5/rc5_locl.h create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/rc5/rc5_skey.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/rc5/rc5cfb64.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/rc5/rc5ofb64.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/rc5/rc5s.cpp create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/rc5/rc5speed.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/rc5/rc5test.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/ripemd/Makefile create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/ripemd/README create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/ripemd/asm/rips.cpp create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/ripemd/asm/rmd-586.pl create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/ripemd/ripemd.h create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/ripemd/rmd160.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/ripemd/rmd_dgst.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/ripemd/rmd_locl.h create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/ripemd/rmd_one.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/ripemd/rmdconst.h create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/ripemd/rmdtest.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/rsa/Makefile create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/rsa/rsa.h create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/rsa/rsa_ameth.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/rsa/rsa_asn1.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/rsa/rsa_chk.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/rsa/rsa_depr.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/rsa/rsa_eay.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/rsa/rsa_err.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/rsa/rsa_gen.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/rsa/rsa_lib.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/rsa/rsa_locl.h create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/rsa/rsa_none.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/rsa/rsa_null.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/rsa/rsa_oaep.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/rsa/rsa_pk1.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/rsa/rsa_pmeth.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/rsa/rsa_prn.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/rsa/rsa_pss.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/rsa/rsa_saos.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/rsa/rsa_sign.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/rsa/rsa_ssl.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/rsa/rsa_test.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/rsa/rsa_x931.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/s390xcap.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/s390xcpuid.S create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/seed/Makefile create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/seed/seed.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/seed/seed.h create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/seed/seed_cbc.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/seed/seed_cfb.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/seed/seed_ecb.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/seed/seed_locl.h create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/seed/seed_ofb.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/sha/Makefile create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/sha/asm/README create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/sha/asm/sha1-586.pl create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/sha/asm/sha1-armv4-large.pl create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/sha/asm/sha1-ia64.pl create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/sha/asm/sha1-ppc.pl create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/sha/asm/sha1-s390x.pl create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/sha/asm/sha1-sparcv9.pl create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/sha/asm/sha1-sparcv9a.pl create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/sha/asm/sha1-thumb.pl create mode 100755 node-v0.8.14/deps/openssl/openssl/crypto/sha/asm/sha1-x86_64.pl create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/sha/asm/sha256-586.pl create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/sha/asm/sha256-armv4.pl create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/sha/asm/sha512-586.pl create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/sha/asm/sha512-armv4.pl create mode 100755 node-v0.8.14/deps/openssl/openssl/crypto/sha/asm/sha512-ia64.pl create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/sha/asm/sha512-ppc.pl create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/sha/asm/sha512-s390x.pl create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/sha/asm/sha512-sparcv9.pl create mode 100755 node-v0.8.14/deps/openssl/openssl/crypto/sha/asm/sha512-x86_64.pl create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/sha/sha.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/sha/sha.h create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/sha/sha1.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/sha/sha1_one.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/sha/sha1dgst.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/sha/sha1test.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/sha/sha256.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/sha/sha256t.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/sha/sha512.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/sha/sha512t.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/sha/sha_dgst.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/sha/sha_locl.h create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/sha/sha_one.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/sha/shatest.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/sparccpuid.S create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/sparcv9cap.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/stack/Makefile create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/stack/safestack.h create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/stack/stack.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/stack/stack.h create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/store/Makefile create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/store/README create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/store/store.h create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/store/str_err.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/store/str_lib.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/store/str_locl.h create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/store/str_mem.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/store/str_meth.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/symhacks.h create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/threads/README create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/threads/mttest.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/threads/netware.bat create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/threads/profile.sh create mode 100755 node-v0.8.14/deps/openssl/openssl/crypto/threads/ptest.bat create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/threads/pthread.sh create mode 100755 node-v0.8.14/deps/openssl/openssl/crypto/threads/pthread2.sh create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/threads/pthreads-vms.com create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/threads/purify.sh create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/threads/solaris.sh create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/threads/th-lock.c create mode 100755 node-v0.8.14/deps/openssl/openssl/crypto/threads/win32.bat create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/ts/Makefile create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/ts/ts.h create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/ts/ts_asn1.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/ts/ts_conf.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/ts/ts_err.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/ts/ts_lib.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/ts/ts_req_print.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/ts/ts_req_utils.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/ts/ts_rsp_print.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/ts/ts_rsp_sign.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/ts/ts_rsp_utils.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/ts/ts_rsp_verify.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/ts/ts_verify_ctx.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/txt_db/Makefile create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/txt_db/txt_db.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/txt_db/txt_db.h create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/ui/Makefile create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/ui/ui.h create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/ui/ui_compat.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/ui/ui_compat.h create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/ui/ui_err.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/ui/ui_lib.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/ui/ui_locl.h create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/ui/ui_openssl.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/ui/ui_util.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/uid.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/vms_rms.h create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/whrlpool/Makefile create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/whrlpool/asm/wp-mmx.pl create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/whrlpool/asm/wp-x86_64.pl create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/whrlpool/whrlpool.h create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/whrlpool/wp_block.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/whrlpool/wp_dgst.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/whrlpool/wp_locl.h create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/whrlpool/wp_test.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/x509/Makefile create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/x509/by_dir.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/x509/by_file.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/x509/x509.h create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/x509/x509_att.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/x509/x509_cmp.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/x509/x509_d2.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/x509/x509_def.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/x509/x509_err.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/x509/x509_ext.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/x509/x509_lu.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/x509/x509_obj.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/x509/x509_r2x.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/x509/x509_req.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/x509/x509_set.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/x509/x509_trs.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/x509/x509_txt.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/x509/x509_v3.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/x509/x509_vfy.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/x509/x509_vfy.h create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/x509/x509_vpm.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/x509/x509cset.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/x509/x509name.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/x509/x509rset.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/x509/x509spki.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/x509/x509type.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/x509/x_all.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/x509v3/Makefile create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/x509v3/ext_dat.h create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/x509v3/pcy_cache.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/x509v3/pcy_data.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/x509v3/pcy_int.h create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/x509v3/pcy_lib.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/x509v3/pcy_map.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/x509v3/pcy_node.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/x509v3/pcy_tree.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/x509v3/tabtest.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/x509v3/v3_addr.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/x509v3/v3_akey.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/x509v3/v3_akeya.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/x509v3/v3_alt.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/x509v3/v3_asid.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/x509v3/v3_bcons.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/x509v3/v3_bitst.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/x509v3/v3_conf.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/x509v3/v3_cpols.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/x509v3/v3_crld.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/x509v3/v3_enum.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/x509v3/v3_extku.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/x509v3/v3_genn.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/x509v3/v3_ia5.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/x509v3/v3_info.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/x509v3/v3_int.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/x509v3/v3_lib.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/x509v3/v3_ncons.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/x509v3/v3_ocsp.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/x509v3/v3_pci.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/x509v3/v3_pcia.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/x509v3/v3_pcons.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/x509v3/v3_pku.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/x509v3/v3_pmaps.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/x509v3/v3_prn.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/x509v3/v3_purp.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/x509v3/v3_skey.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/x509v3/v3_sxnet.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/x509v3/v3_utl.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/x509v3/v3conf.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/x509v3/v3err.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/x509v3/v3prin.c create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/x509v3/x509v3.h create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/x86_64cpuid.pl create mode 100644 node-v0.8.14/deps/openssl/openssl/crypto/x86cpuid.pl create mode 100644 node-v0.8.14/deps/openssl/openssl/demos/README create mode 100644 node-v0.8.14/deps/openssl/openssl/demos/asn1/README.ASN1 create mode 100644 node-v0.8.14/deps/openssl/openssl/demos/asn1/ocsp.c create mode 100644 node-v0.8.14/deps/openssl/openssl/demos/b64.c create mode 100644 node-v0.8.14/deps/openssl/openssl/demos/b64.pl create mode 100644 node-v0.8.14/deps/openssl/openssl/demos/bio/Makefile create mode 100644 node-v0.8.14/deps/openssl/openssl/demos/bio/README create mode 100644 node-v0.8.14/deps/openssl/openssl/demos/bio/saccept.c create mode 100644 node-v0.8.14/deps/openssl/openssl/demos/bio/sconnect.c create mode 100644 node-v0.8.14/deps/openssl/openssl/demos/bio/server.pem create mode 100644 node-v0.8.14/deps/openssl/openssl/demos/cms/cacert.pem create mode 100644 node-v0.8.14/deps/openssl/openssl/demos/cms/cakey.pem create mode 100644 node-v0.8.14/deps/openssl/openssl/demos/cms/cms_comp.c create mode 100644 node-v0.8.14/deps/openssl/openssl/demos/cms/cms_ddec.c create mode 100644 node-v0.8.14/deps/openssl/openssl/demos/cms/cms_dec.c create mode 100644 node-v0.8.14/deps/openssl/openssl/demos/cms/cms_denc.c create mode 100644 node-v0.8.14/deps/openssl/openssl/demos/cms/cms_enc.c create mode 100644 node-v0.8.14/deps/openssl/openssl/demos/cms/cms_sign.c create mode 100644 node-v0.8.14/deps/openssl/openssl/demos/cms/cms_sign2.c create mode 100644 node-v0.8.14/deps/openssl/openssl/demos/cms/cms_uncomp.c create mode 100644 node-v0.8.14/deps/openssl/openssl/demos/cms/cms_ver.c create mode 100644 node-v0.8.14/deps/openssl/openssl/demos/cms/comp.txt create mode 100644 node-v0.8.14/deps/openssl/openssl/demos/cms/encr.txt create mode 100644 node-v0.8.14/deps/openssl/openssl/demos/cms/sign.txt create mode 100644 node-v0.8.14/deps/openssl/openssl/demos/cms/signer.pem create mode 100644 node-v0.8.14/deps/openssl/openssl/demos/cms/signer2.pem create mode 100644 node-v0.8.14/deps/openssl/openssl/demos/easy_tls/Makefile create mode 100644 node-v0.8.14/deps/openssl/openssl/demos/easy_tls/README create mode 100644 node-v0.8.14/deps/openssl/openssl/demos/easy_tls/cacerts.pem create mode 100644 node-v0.8.14/deps/openssl/openssl/demos/easy_tls/cert.pem create mode 100644 node-v0.8.14/deps/openssl/openssl/demos/easy_tls/easy-tls.c create mode 100644 node-v0.8.14/deps/openssl/openssl/demos/easy_tls/easy-tls.h create mode 100644 node-v0.8.14/deps/openssl/openssl/demos/easy_tls/test.c create mode 100644 node-v0.8.14/deps/openssl/openssl/demos/easy_tls/test.h create mode 100644 node-v0.8.14/deps/openssl/openssl/demos/eay/Makefile create mode 100644 node-v0.8.14/deps/openssl/openssl/demos/eay/base64.c create mode 100644 node-v0.8.14/deps/openssl/openssl/demos/eay/conn.c create mode 100644 node-v0.8.14/deps/openssl/openssl/demos/eay/loadrsa.c create mode 100644 node-v0.8.14/deps/openssl/openssl/demos/engines/cluster_labs/Makefile create mode 100644 node-v0.8.14/deps/openssl/openssl/demos/engines/cluster_labs/cluster_labs.h create mode 100644 node-v0.8.14/deps/openssl/openssl/demos/engines/cluster_labs/hw_cluster_labs.c create mode 100644 node-v0.8.14/deps/openssl/openssl/demos/engines/cluster_labs/hw_cluster_labs.ec create mode 100644 node-v0.8.14/deps/openssl/openssl/demos/engines/cluster_labs/hw_cluster_labs_err.c create mode 100644 node-v0.8.14/deps/openssl/openssl/demos/engines/cluster_labs/hw_cluster_labs_err.h create mode 100644 node-v0.8.14/deps/openssl/openssl/demos/engines/ibmca/Makefile create mode 100644 node-v0.8.14/deps/openssl/openssl/demos/engines/ibmca/hw_ibmca.c create mode 100644 node-v0.8.14/deps/openssl/openssl/demos/engines/ibmca/hw_ibmca.ec create mode 100644 node-v0.8.14/deps/openssl/openssl/demos/engines/ibmca/hw_ibmca_err.c create mode 100644 node-v0.8.14/deps/openssl/openssl/demos/engines/ibmca/hw_ibmca_err.h create mode 100644 node-v0.8.14/deps/openssl/openssl/demos/engines/ibmca/ica_openssl_api.h create mode 100644 node-v0.8.14/deps/openssl/openssl/demos/engines/rsaref/Makefile create mode 100644 node-v0.8.14/deps/openssl/openssl/demos/engines/rsaref/README create mode 100644 node-v0.8.14/deps/openssl/openssl/demos/engines/rsaref/build.com create mode 100644 node-v0.8.14/deps/openssl/openssl/demos/engines/rsaref/rsaref.c create mode 100644 node-v0.8.14/deps/openssl/openssl/demos/engines/rsaref/rsaref.ec create mode 100644 node-v0.8.14/deps/openssl/openssl/demos/engines/rsaref/rsaref_err.c create mode 100644 node-v0.8.14/deps/openssl/openssl/demos/engines/rsaref/rsaref_err.h create mode 100644 node-v0.8.14/deps/openssl/openssl/demos/engines/zencod/Makefile create mode 100644 node-v0.8.14/deps/openssl/openssl/demos/engines/zencod/hw_zencod.c create mode 100644 node-v0.8.14/deps/openssl/openssl/demos/engines/zencod/hw_zencod.ec create mode 100644 node-v0.8.14/deps/openssl/openssl/demos/engines/zencod/hw_zencod.h create mode 100644 node-v0.8.14/deps/openssl/openssl/demos/engines/zencod/hw_zencod_err.c create mode 100644 node-v0.8.14/deps/openssl/openssl/demos/engines/zencod/hw_zencod_err.h create mode 100644 node-v0.8.14/deps/openssl/openssl/demos/maurice/Makefile create mode 100644 node-v0.8.14/deps/openssl/openssl/demos/maurice/README create mode 100644 node-v0.8.14/deps/openssl/openssl/demos/maurice/cert.pem create mode 100644 node-v0.8.14/deps/openssl/openssl/demos/maurice/example1.c create mode 100644 node-v0.8.14/deps/openssl/openssl/demos/maurice/example2.c create mode 100644 node-v0.8.14/deps/openssl/openssl/demos/maurice/example3.c create mode 100644 node-v0.8.14/deps/openssl/openssl/demos/maurice/example4.c create mode 100644 node-v0.8.14/deps/openssl/openssl/demos/maurice/loadkeys.c create mode 100644 node-v0.8.14/deps/openssl/openssl/demos/maurice/loadkeys.h create mode 100644 node-v0.8.14/deps/openssl/openssl/demos/maurice/privkey.pem create mode 100644 node-v0.8.14/deps/openssl/openssl/demos/pkcs12/README create mode 100644 node-v0.8.14/deps/openssl/openssl/demos/pkcs12/pkread.c create mode 100644 node-v0.8.14/deps/openssl/openssl/demos/pkcs12/pkwrite.c create mode 100644 node-v0.8.14/deps/openssl/openssl/demos/prime/Makefile create mode 100644 node-v0.8.14/deps/openssl/openssl/demos/prime/prime.c create mode 100644 node-v0.8.14/deps/openssl/openssl/demos/privkey.pem create mode 100644 node-v0.8.14/deps/openssl/openssl/demos/selfsign.c create mode 100644 node-v0.8.14/deps/openssl/openssl/demos/sign/Makefile create mode 100644 node-v0.8.14/deps/openssl/openssl/demos/sign/cert.pem create mode 100644 node-v0.8.14/deps/openssl/openssl/demos/sign/key.pem create mode 100644 node-v0.8.14/deps/openssl/openssl/demos/sign/sig.txt create mode 100644 node-v0.8.14/deps/openssl/openssl/demos/sign/sign.c create mode 100644 node-v0.8.14/deps/openssl/openssl/demos/sign/sign.txt create mode 100644 node-v0.8.14/deps/openssl/openssl/demos/smime/cacert.pem create mode 100644 node-v0.8.14/deps/openssl/openssl/demos/smime/cakey.pem create mode 100644 node-v0.8.14/deps/openssl/openssl/demos/smime/encr.txt create mode 100644 node-v0.8.14/deps/openssl/openssl/demos/smime/sign.txt create mode 100644 node-v0.8.14/deps/openssl/openssl/demos/smime/signer.pem create mode 100644 node-v0.8.14/deps/openssl/openssl/demos/smime/signer2.pem create mode 100644 node-v0.8.14/deps/openssl/openssl/demos/smime/smdec.c create mode 100644 node-v0.8.14/deps/openssl/openssl/demos/smime/smenc.c create mode 100644 node-v0.8.14/deps/openssl/openssl/demos/smime/smsign.c create mode 100644 node-v0.8.14/deps/openssl/openssl/demos/smime/smsign2.c create mode 100644 node-v0.8.14/deps/openssl/openssl/demos/smime/smver.c create mode 100644 node-v0.8.14/deps/openssl/openssl/demos/spkigen.c create mode 100644 node-v0.8.14/deps/openssl/openssl/demos/ssl/cli.cpp create mode 100644 node-v0.8.14/deps/openssl/openssl/demos/ssl/inetdsrv.cpp create mode 100644 node-v0.8.14/deps/openssl/openssl/demos/ssl/serv.cpp create mode 100755 node-v0.8.14/deps/openssl/openssl/demos/ssltest-ecc/ECC-RSAcertgen.sh create mode 100755 node-v0.8.14/deps/openssl/openssl/demos/ssltest-ecc/ECCcertgen.sh create mode 100644 node-v0.8.14/deps/openssl/openssl/demos/ssltest-ecc/README create mode 100755 node-v0.8.14/deps/openssl/openssl/demos/ssltest-ecc/RSAcertgen.sh create mode 100755 node-v0.8.14/deps/openssl/openssl/demos/ssltest-ecc/ssltest.sh create mode 100644 node-v0.8.14/deps/openssl/openssl/demos/state_machine/Makefile create mode 100644 node-v0.8.14/deps/openssl/openssl/demos/state_machine/state_machine.c create mode 100644 node-v0.8.14/deps/openssl/openssl/demos/tunala/A-client.pem create mode 100644 node-v0.8.14/deps/openssl/openssl/demos/tunala/A-server.pem create mode 100644 node-v0.8.14/deps/openssl/openssl/demos/tunala/CA.pem create mode 100644 node-v0.8.14/deps/openssl/openssl/demos/tunala/INSTALL create mode 100644 node-v0.8.14/deps/openssl/openssl/demos/tunala/Makefile create mode 100644 node-v0.8.14/deps/openssl/openssl/demos/tunala/Makefile.am create mode 100644 node-v0.8.14/deps/openssl/openssl/demos/tunala/README create mode 100755 node-v0.8.14/deps/openssl/openssl/demos/tunala/autogunk.sh create mode 100755 node-v0.8.14/deps/openssl/openssl/demos/tunala/autoungunk.sh create mode 100644 node-v0.8.14/deps/openssl/openssl/demos/tunala/breakage.c create mode 100644 node-v0.8.14/deps/openssl/openssl/demos/tunala/buffer.c create mode 100644 node-v0.8.14/deps/openssl/openssl/demos/tunala/cb.c create mode 100644 node-v0.8.14/deps/openssl/openssl/demos/tunala/configure.in create mode 100644 node-v0.8.14/deps/openssl/openssl/demos/tunala/ip.c create mode 100644 node-v0.8.14/deps/openssl/openssl/demos/tunala/sm.c create mode 100755 node-v0.8.14/deps/openssl/openssl/demos/tunala/test.sh create mode 100644 node-v0.8.14/deps/openssl/openssl/demos/tunala/tunala.c create mode 100644 node-v0.8.14/deps/openssl/openssl/demos/tunala/tunala.h create mode 100644 node-v0.8.14/deps/openssl/openssl/demos/x509/README create mode 100644 node-v0.8.14/deps/openssl/openssl/demos/x509/mkcert.c create mode 100644 node-v0.8.14/deps/openssl/openssl/demos/x509/mkreq.c create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/HOWTO/certificates.txt create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/HOWTO/keys.txt create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/HOWTO/proxy_certificates.txt create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/README create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/apps/CA.pl.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/apps/asn1parse.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/apps/ca.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/apps/ciphers.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/apps/cms.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/apps/config.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/apps/crl.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/apps/crl2pkcs7.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/apps/dgst.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/apps/dhparam.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/apps/dsa.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/apps/dsaparam.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/apps/ec.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/apps/ecparam.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/apps/enc.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/apps/errstr.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/apps/gendsa.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/apps/genpkey.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/apps/genrsa.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/apps/nseq.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/apps/ocsp.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/apps/openssl.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/apps/passwd.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/apps/pkcs12.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/apps/pkcs7.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/apps/pkcs8.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/apps/pkey.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/apps/pkeyparam.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/apps/pkeyutl.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/apps/rand.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/apps/req.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/apps/rsa.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/apps/rsautl.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/apps/s_client.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/apps/s_server.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/apps/s_time.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/apps/sess_id.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/apps/smime.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/apps/speed.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/apps/spkac.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/apps/ts.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/apps/tsget.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/apps/verify.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/apps/version.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/apps/x509.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/apps/x509v3_config.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/c-indentation.el create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/crypto/ASN1_OBJECT_new.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/crypto/ASN1_STRING_length.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/crypto/ASN1_STRING_new.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/crypto/ASN1_STRING_print_ex.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/crypto/ASN1_generate_nconf.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/crypto/BIO_ctrl.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/crypto/BIO_f_base64.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/crypto/BIO_f_buffer.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/crypto/BIO_f_cipher.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/crypto/BIO_f_md.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/crypto/BIO_f_null.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/crypto/BIO_f_ssl.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/crypto/BIO_find_type.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/crypto/BIO_new.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/crypto/BIO_new_CMS.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/crypto/BIO_push.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/crypto/BIO_read.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/crypto/BIO_s_accept.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/crypto/BIO_s_bio.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/crypto/BIO_s_connect.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/crypto/BIO_s_fd.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/crypto/BIO_s_file.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/crypto/BIO_s_mem.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/crypto/BIO_s_null.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/crypto/BIO_s_socket.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/crypto/BIO_set_callback.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/crypto/BIO_should_retry.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/crypto/BN_BLINDING_new.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/crypto/BN_CTX_new.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/crypto/BN_CTX_start.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/crypto/BN_add.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/crypto/BN_add_word.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/crypto/BN_bn2bin.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/crypto/BN_cmp.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/crypto/BN_copy.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/crypto/BN_generate_prime.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/crypto/BN_mod_inverse.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/crypto/BN_mod_mul_montgomery.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/crypto/BN_mod_mul_reciprocal.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/crypto/BN_new.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/crypto/BN_num_bytes.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/crypto/BN_rand.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/crypto/BN_set_bit.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/crypto/BN_swap.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/crypto/BN_zero.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/crypto/CMS_add0_cert.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/crypto/CMS_add1_recipient_cert.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/crypto/CMS_compress.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/crypto/CMS_decrypt.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/crypto/CMS_encrypt.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/crypto/CMS_final.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/crypto/CMS_get0_RecipientInfos.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/crypto/CMS_get0_SignerInfos.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/crypto/CMS_get0_type.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/crypto/CMS_get1_ReceiptRequest.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/crypto/CMS_sign.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/crypto/CMS_sign_add1_signer.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/crypto/CMS_sign_receipt.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/crypto/CMS_uncompress.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/crypto/CMS_verify.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/crypto/CMS_verify_receipt.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/crypto/CONF_modules_free.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/crypto/CONF_modules_load_file.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/crypto/CRYPTO_set_ex_data.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/crypto/DH_generate_key.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/crypto/DH_generate_parameters.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/crypto/DH_get_ex_new_index.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/crypto/DH_new.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/crypto/DH_set_method.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/crypto/DH_size.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/crypto/DSA_SIG_new.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/crypto/DSA_do_sign.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/crypto/DSA_dup_DH.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/crypto/DSA_generate_key.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/crypto/DSA_generate_parameters.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/crypto/DSA_get_ex_new_index.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/crypto/DSA_new.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/crypto/DSA_set_method.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/crypto/DSA_sign.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/crypto/DSA_size.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/crypto/ERR_GET_LIB.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/crypto/ERR_clear_error.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/crypto/ERR_error_string.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/crypto/ERR_get_error.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/crypto/ERR_load_crypto_strings.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/crypto/ERR_load_strings.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/crypto/ERR_print_errors.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/crypto/ERR_put_error.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/crypto/ERR_remove_state.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/crypto/ERR_set_mark.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/crypto/EVP_BytesToKey.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/crypto/EVP_DigestInit.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/crypto/EVP_DigestSignInit.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/crypto/EVP_DigestVerifyInit.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/crypto/EVP_EncryptInit.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/crypto/EVP_OpenInit.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/crypto/EVP_PKEY_CTX_ctrl.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/crypto/EVP_PKEY_CTX_new.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/crypto/EVP_PKEY_cmp.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/crypto/EVP_PKEY_decrypt.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/crypto/EVP_PKEY_derive.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/crypto/EVP_PKEY_encrypt.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/crypto/EVP_PKEY_get_default_digest.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/crypto/EVP_PKEY_keygen.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/crypto/EVP_PKEY_new.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/crypto/EVP_PKEY_print_private.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/crypto/EVP_PKEY_set1_RSA.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/crypto/EVP_PKEY_sign.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/crypto/EVP_PKEY_verify.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/crypto/EVP_PKEY_verifyrecover.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/crypto/EVP_SealInit.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/crypto/EVP_SignInit.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/crypto/EVP_VerifyInit.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/crypto/OBJ_nid2obj.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/crypto/OPENSSL_Applink.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/crypto/OPENSSL_VERSION_NUMBER.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/crypto/OPENSSL_config.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/crypto/OPENSSL_ia32cap.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/crypto/OPENSSL_load_builtin_modules.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/crypto/OpenSSL_add_all_algorithms.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/crypto/PEM_write_bio_CMS_stream.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/crypto/PEM_write_bio_PKCS7_stream.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/crypto/PKCS12_create.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/crypto/PKCS12_parse.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/crypto/PKCS7_decrypt.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/crypto/PKCS7_encrypt.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/crypto/PKCS7_sign.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/crypto/PKCS7_sign_add_signer.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/crypto/PKCS7_verify.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/crypto/RAND_add.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/crypto/RAND_bytes.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/crypto/RAND_cleanup.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/crypto/RAND_egd.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/crypto/RAND_load_file.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/crypto/RAND_set_rand_method.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/crypto/RSA_blinding_on.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/crypto/RSA_check_key.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/crypto/RSA_generate_key.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/crypto/RSA_get_ex_new_index.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/crypto/RSA_new.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/crypto/RSA_padding_add_PKCS1_type_1.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/crypto/RSA_print.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/crypto/RSA_private_encrypt.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/crypto/RSA_public_encrypt.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/crypto/RSA_set_method.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/crypto/RSA_sign.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/crypto/RSA_sign_ASN1_OCTET_STRING.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/crypto/RSA_size.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/crypto/SMIME_read_CMS.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/crypto/SMIME_read_PKCS7.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/crypto/SMIME_write_CMS.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/crypto/SMIME_write_PKCS7.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/crypto/X509_NAME_ENTRY_get_object.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/crypto/X509_NAME_add_entry_by_txt.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/crypto/X509_NAME_get_index_by_NID.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/crypto/X509_NAME_print_ex.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/crypto/X509_STORE_CTX_get_error.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/crypto/X509_STORE_CTX_get_ex_new_index.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/crypto/X509_STORE_CTX_new.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/crypto/X509_STORE_CTX_set_verify_cb.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/crypto/X509_STORE_set_verify_cb_func.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/crypto/X509_VERIFY_PARAM_set_flags.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/crypto/X509_new.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/crypto/X509_verify_cert.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/crypto/bio.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/crypto/blowfish.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/crypto/bn.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/crypto/bn_internal.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/crypto/buffer.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/crypto/crypto.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/crypto/d2i_ASN1_OBJECT.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/crypto/d2i_DHparams.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/crypto/d2i_DSAPublicKey.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/crypto/d2i_PKCS8PrivateKey.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/crypto/d2i_RSAPublicKey.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/crypto/d2i_X509.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/crypto/d2i_X509_ALGOR.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/crypto/d2i_X509_CRL.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/crypto/d2i_X509_NAME.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/crypto/d2i_X509_REQ.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/crypto/d2i_X509_SIG.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/crypto/des.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/crypto/des_modes.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/crypto/dh.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/crypto/dsa.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/crypto/ecdsa.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/crypto/engine.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/crypto/err.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/crypto/evp.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/crypto/hmac.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/crypto/i2d_CMS_bio_stream.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/crypto/i2d_PKCS7_bio_stream.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/crypto/lh_stats.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/crypto/lhash.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/crypto/md5.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/crypto/mdc2.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/crypto/pem.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/crypto/rand.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/crypto/rc4.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/crypto/ripemd.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/crypto/rsa.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/crypto/sha.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/crypto/threads.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/crypto/ui.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/crypto/ui_compat.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/crypto/x509.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/fingerprints.txt create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/openssl-shared.txt create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/openssl.txt create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/openssl_button.gif create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/openssl_button.html create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/ssl/SSL_CIPHER_get_name.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/ssl/SSL_COMP_add_compression_method.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/ssl/SSL_CTX_add_extra_chain_cert.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/ssl/SSL_CTX_add_session.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/ssl/SSL_CTX_ctrl.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/ssl/SSL_CTX_flush_sessions.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/ssl/SSL_CTX_free.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/ssl/SSL_CTX_get_ex_new_index.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/ssl/SSL_CTX_get_verify_mode.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/ssl/SSL_CTX_load_verify_locations.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/ssl/SSL_CTX_new.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/ssl/SSL_CTX_sess_number.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/ssl/SSL_CTX_sess_set_cache_size.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/ssl/SSL_CTX_sess_set_get_cb.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/ssl/SSL_CTX_sessions.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/ssl/SSL_CTX_set_cert_store.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/ssl/SSL_CTX_set_cert_verify_callback.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/ssl/SSL_CTX_set_cipher_list.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/ssl/SSL_CTX_set_client_CA_list.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/ssl/SSL_CTX_set_client_cert_cb.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/ssl/SSL_CTX_set_default_passwd_cb.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/ssl/SSL_CTX_set_generate_session_id.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/ssl/SSL_CTX_set_info_callback.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/ssl/SSL_CTX_set_max_cert_list.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/ssl/SSL_CTX_set_mode.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/ssl/SSL_CTX_set_msg_callback.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/ssl/SSL_CTX_set_options.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/ssl/SSL_CTX_set_psk_client_callback.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/ssl/SSL_CTX_set_quiet_shutdown.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/ssl/SSL_CTX_set_session_cache_mode.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/ssl/SSL_CTX_set_session_id_context.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/ssl/SSL_CTX_set_ssl_version.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/ssl/SSL_CTX_set_timeout.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/ssl/SSL_CTX_set_tmp_dh_callback.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/ssl/SSL_CTX_set_tmp_rsa_callback.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/ssl/SSL_CTX_set_verify.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/ssl/SSL_CTX_use_certificate.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/ssl/SSL_CTX_use_psk_identity_hint.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/ssl/SSL_SESSION_free.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/ssl/SSL_SESSION_get_ex_new_index.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/ssl/SSL_SESSION_get_time.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/ssl/SSL_accept.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/ssl/SSL_alert_type_string.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/ssl/SSL_clear.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/ssl/SSL_connect.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/ssl/SSL_do_handshake.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/ssl/SSL_free.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/ssl/SSL_get_SSL_CTX.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/ssl/SSL_get_ciphers.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/ssl/SSL_get_client_CA_list.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/ssl/SSL_get_current_cipher.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/ssl/SSL_get_default_timeout.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/ssl/SSL_get_error.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/ssl/SSL_get_ex_data_X509_STORE_CTX_idx.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/ssl/SSL_get_ex_new_index.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/ssl/SSL_get_fd.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/ssl/SSL_get_peer_cert_chain.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/ssl/SSL_get_peer_certificate.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/ssl/SSL_get_psk_identity.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/ssl/SSL_get_rbio.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/ssl/SSL_get_session.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/ssl/SSL_get_verify_result.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/ssl/SSL_get_version.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/ssl/SSL_library_init.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/ssl/SSL_load_client_CA_file.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/ssl/SSL_new.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/ssl/SSL_pending.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/ssl/SSL_read.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/ssl/SSL_rstate_string.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/ssl/SSL_session_reused.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/ssl/SSL_set_bio.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/ssl/SSL_set_connect_state.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/ssl/SSL_set_fd.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/ssl/SSL_set_session.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/ssl/SSL_set_shutdown.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/ssl/SSL_set_verify_result.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/ssl/SSL_shutdown.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/ssl/SSL_state_string.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/ssl/SSL_want.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/ssl/SSL_write.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/ssl/d2i_SSL_SESSION.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/ssl/ssl.pod create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/ssleay.txt create mode 100644 node-v0.8.14/deps/openssl/openssl/doc/standards.txt create mode 100644 node-v0.8.14/deps/openssl/openssl/e_os.h create mode 100644 node-v0.8.14/deps/openssl/openssl/e_os2.h create mode 100644 node-v0.8.14/deps/openssl/openssl/engines/Makefile create mode 100644 node-v0.8.14/deps/openssl/openssl/engines/alpha.opt create mode 100644 node-v0.8.14/deps/openssl/openssl/engines/axp.opt create mode 100644 node-v0.8.14/deps/openssl/openssl/engines/capierr.bat create mode 100644 node-v0.8.14/deps/openssl/openssl/engines/ccgost/Makefile create mode 100644 node-v0.8.14/deps/openssl/openssl/engines/ccgost/README.gost create mode 100644 node-v0.8.14/deps/openssl/openssl/engines/ccgost/e_gost_err.c create mode 100644 node-v0.8.14/deps/openssl/openssl/engines/ccgost/e_gost_err.h create mode 100644 node-v0.8.14/deps/openssl/openssl/engines/ccgost/e_gost_err.proto create mode 100644 node-v0.8.14/deps/openssl/openssl/engines/ccgost/gost.ec create mode 100644 node-v0.8.14/deps/openssl/openssl/engines/ccgost/gost2001.c create mode 100644 node-v0.8.14/deps/openssl/openssl/engines/ccgost/gost2001_keyx.c create mode 100644 node-v0.8.14/deps/openssl/openssl/engines/ccgost/gost2001_keyx.h create mode 100644 node-v0.8.14/deps/openssl/openssl/engines/ccgost/gost89.c create mode 100644 node-v0.8.14/deps/openssl/openssl/engines/ccgost/gost89.h create mode 100644 node-v0.8.14/deps/openssl/openssl/engines/ccgost/gost94_keyx.c create mode 100644 node-v0.8.14/deps/openssl/openssl/engines/ccgost/gost_ameth.c create mode 100644 node-v0.8.14/deps/openssl/openssl/engines/ccgost/gost_asn1.c create mode 100644 node-v0.8.14/deps/openssl/openssl/engines/ccgost/gost_crypt.c create mode 100644 node-v0.8.14/deps/openssl/openssl/engines/ccgost/gost_ctl.c create mode 100644 node-v0.8.14/deps/openssl/openssl/engines/ccgost/gost_eng.c create mode 100644 node-v0.8.14/deps/openssl/openssl/engines/ccgost/gost_keywrap.c create mode 100644 node-v0.8.14/deps/openssl/openssl/engines/ccgost/gost_keywrap.h create mode 100644 node-v0.8.14/deps/openssl/openssl/engines/ccgost/gost_lcl.h create mode 100644 node-v0.8.14/deps/openssl/openssl/engines/ccgost/gost_md.c create mode 100644 node-v0.8.14/deps/openssl/openssl/engines/ccgost/gost_params.c create mode 100644 node-v0.8.14/deps/openssl/openssl/engines/ccgost/gost_params.h create mode 100644 node-v0.8.14/deps/openssl/openssl/engines/ccgost/gost_pmeth.c create mode 100644 node-v0.8.14/deps/openssl/openssl/engines/ccgost/gost_sign.c create mode 100644 node-v0.8.14/deps/openssl/openssl/engines/ccgost/gosthash.c create mode 100644 node-v0.8.14/deps/openssl/openssl/engines/ccgost/gosthash.h create mode 100644 node-v0.8.14/deps/openssl/openssl/engines/ccgost/gostsum.c create mode 100644 node-v0.8.14/deps/openssl/openssl/engines/e_4758cca.c create mode 100644 node-v0.8.14/deps/openssl/openssl/engines/e_4758cca.ec create mode 100644 node-v0.8.14/deps/openssl/openssl/engines/e_4758cca_err.c create mode 100644 node-v0.8.14/deps/openssl/openssl/engines/e_4758cca_err.h create mode 100644 node-v0.8.14/deps/openssl/openssl/engines/e_aep.c create mode 100644 node-v0.8.14/deps/openssl/openssl/engines/e_aep.ec create mode 100644 node-v0.8.14/deps/openssl/openssl/engines/e_aep_err.c create mode 100644 node-v0.8.14/deps/openssl/openssl/engines/e_aep_err.h create mode 100644 node-v0.8.14/deps/openssl/openssl/engines/e_atalla.c create mode 100644 node-v0.8.14/deps/openssl/openssl/engines/e_atalla.ec create mode 100644 node-v0.8.14/deps/openssl/openssl/engines/e_atalla_err.c create mode 100644 node-v0.8.14/deps/openssl/openssl/engines/e_atalla_err.h create mode 100644 node-v0.8.14/deps/openssl/openssl/engines/e_capi.c create mode 100644 node-v0.8.14/deps/openssl/openssl/engines/e_capi.ec create mode 100644 node-v0.8.14/deps/openssl/openssl/engines/e_capi_err.c create mode 100644 node-v0.8.14/deps/openssl/openssl/engines/e_capi_err.h create mode 100644 node-v0.8.14/deps/openssl/openssl/engines/e_chil.c create mode 100644 node-v0.8.14/deps/openssl/openssl/engines/e_chil.ec create mode 100644 node-v0.8.14/deps/openssl/openssl/engines/e_chil_err.c create mode 100644 node-v0.8.14/deps/openssl/openssl/engines/e_chil_err.h create mode 100644 node-v0.8.14/deps/openssl/openssl/engines/e_cswift.c create mode 100644 node-v0.8.14/deps/openssl/openssl/engines/e_cswift.ec create mode 100644 node-v0.8.14/deps/openssl/openssl/engines/e_cswift_err.c create mode 100644 node-v0.8.14/deps/openssl/openssl/engines/e_cswift_err.h create mode 100644 node-v0.8.14/deps/openssl/openssl/engines/e_gmp.c create mode 100644 node-v0.8.14/deps/openssl/openssl/engines/e_gmp.ec create mode 100644 node-v0.8.14/deps/openssl/openssl/engines/e_gmp_err.c create mode 100644 node-v0.8.14/deps/openssl/openssl/engines/e_gmp_err.h create mode 100644 node-v0.8.14/deps/openssl/openssl/engines/e_nuron.c create mode 100644 node-v0.8.14/deps/openssl/openssl/engines/e_nuron.ec create mode 100644 node-v0.8.14/deps/openssl/openssl/engines/e_nuron_err.c create mode 100644 node-v0.8.14/deps/openssl/openssl/engines/e_nuron_err.h create mode 100644 node-v0.8.14/deps/openssl/openssl/engines/e_padlock.c create mode 100644 node-v0.8.14/deps/openssl/openssl/engines/e_padlock.ec create mode 100644 node-v0.8.14/deps/openssl/openssl/engines/e_sureware.c create mode 100644 node-v0.8.14/deps/openssl/openssl/engines/e_sureware.ec create mode 100644 node-v0.8.14/deps/openssl/openssl/engines/e_sureware_err.c create mode 100644 node-v0.8.14/deps/openssl/openssl/engines/e_sureware_err.h create mode 100644 node-v0.8.14/deps/openssl/openssl/engines/e_ubsec.c create mode 100644 node-v0.8.14/deps/openssl/openssl/engines/e_ubsec.ec create mode 100644 node-v0.8.14/deps/openssl/openssl/engines/e_ubsec_err.c create mode 100644 node-v0.8.14/deps/openssl/openssl/engines/e_ubsec_err.h create mode 100644 node-v0.8.14/deps/openssl/openssl/engines/engine_vector.mar create mode 100644 node-v0.8.14/deps/openssl/openssl/engines/ia64.opt create mode 100644 node-v0.8.14/deps/openssl/openssl/engines/makeengines.com create mode 100644 node-v0.8.14/deps/openssl/openssl/engines/vax.opt create mode 100644 node-v0.8.14/deps/openssl/openssl/engines/vendor_defns/aep.h create mode 100644 node-v0.8.14/deps/openssl/openssl/engines/vendor_defns/atalla.h create mode 100644 node-v0.8.14/deps/openssl/openssl/engines/vendor_defns/cswift.h create mode 100644 node-v0.8.14/deps/openssl/openssl/engines/vendor_defns/hw_4758_cca.h create mode 100644 node-v0.8.14/deps/openssl/openssl/engines/vendor_defns/hw_ubsec.h create mode 100644 node-v0.8.14/deps/openssl/openssl/engines/vendor_defns/hwcryptohook.h create mode 100644 node-v0.8.14/deps/openssl/openssl/engines/vendor_defns/sureware.h create mode 100644 node-v0.8.14/deps/openssl/openssl/include/openssl/aes.h create mode 100644 node-v0.8.14/deps/openssl/openssl/include/openssl/asn1.h create mode 100644 node-v0.8.14/deps/openssl/openssl/include/openssl/asn1_mac.h create mode 100644 node-v0.8.14/deps/openssl/openssl/include/openssl/asn1t.h create mode 100644 node-v0.8.14/deps/openssl/openssl/include/openssl/bio.h create mode 100644 node-v0.8.14/deps/openssl/openssl/include/openssl/blowfish.h create mode 100644 node-v0.8.14/deps/openssl/openssl/include/openssl/bn.h create mode 100644 node-v0.8.14/deps/openssl/openssl/include/openssl/buffer.h create mode 100644 node-v0.8.14/deps/openssl/openssl/include/openssl/camellia.h create mode 100644 node-v0.8.14/deps/openssl/openssl/include/openssl/cast.h create mode 100644 node-v0.8.14/deps/openssl/openssl/include/openssl/cms.h create mode 100644 node-v0.8.14/deps/openssl/openssl/include/openssl/comp.h create mode 100644 node-v0.8.14/deps/openssl/openssl/include/openssl/conf.h create mode 100644 node-v0.8.14/deps/openssl/openssl/include/openssl/conf_api.h create mode 100644 node-v0.8.14/deps/openssl/openssl/include/openssl/crypto.h create mode 100644 node-v0.8.14/deps/openssl/openssl/include/openssl/des.h create mode 100644 node-v0.8.14/deps/openssl/openssl/include/openssl/des_old.h create mode 100644 node-v0.8.14/deps/openssl/openssl/include/openssl/dh.h create mode 100644 node-v0.8.14/deps/openssl/openssl/include/openssl/dsa.h create mode 100644 node-v0.8.14/deps/openssl/openssl/include/openssl/dso.h create mode 100644 node-v0.8.14/deps/openssl/openssl/include/openssl/dtls1.h create mode 100644 node-v0.8.14/deps/openssl/openssl/include/openssl/e_os2.h create mode 100644 node-v0.8.14/deps/openssl/openssl/include/openssl/ebcdic.h create mode 100644 node-v0.8.14/deps/openssl/openssl/include/openssl/ec.h create mode 100644 node-v0.8.14/deps/openssl/openssl/include/openssl/ecdh.h create mode 100644 node-v0.8.14/deps/openssl/openssl/include/openssl/ecdsa.h create mode 100644 node-v0.8.14/deps/openssl/openssl/include/openssl/engine.h create mode 100644 node-v0.8.14/deps/openssl/openssl/include/openssl/err.h create mode 100644 node-v0.8.14/deps/openssl/openssl/include/openssl/evp.h create mode 100644 node-v0.8.14/deps/openssl/openssl/include/openssl/hmac.h create mode 100644 node-v0.8.14/deps/openssl/openssl/include/openssl/idea.h create mode 100644 node-v0.8.14/deps/openssl/openssl/include/openssl/krb5_asn.h create mode 100644 node-v0.8.14/deps/openssl/openssl/include/openssl/kssl.h create mode 100644 node-v0.8.14/deps/openssl/openssl/include/openssl/lhash.h create mode 100644 node-v0.8.14/deps/openssl/openssl/include/openssl/md2.h create mode 100644 node-v0.8.14/deps/openssl/openssl/include/openssl/md4.h create mode 100644 node-v0.8.14/deps/openssl/openssl/include/openssl/md5.h create mode 100644 node-v0.8.14/deps/openssl/openssl/include/openssl/mdc2.h create mode 100644 node-v0.8.14/deps/openssl/openssl/include/openssl/modes.h create mode 100644 node-v0.8.14/deps/openssl/openssl/include/openssl/obj_mac.h create mode 100644 node-v0.8.14/deps/openssl/openssl/include/openssl/objects.h create mode 100644 node-v0.8.14/deps/openssl/openssl/include/openssl/ocsp.h create mode 100644 node-v0.8.14/deps/openssl/openssl/include/openssl/opensslv.h create mode 100644 node-v0.8.14/deps/openssl/openssl/include/openssl/ossl_typ.h create mode 100644 node-v0.8.14/deps/openssl/openssl/include/openssl/pem.h create mode 100644 node-v0.8.14/deps/openssl/openssl/include/openssl/pem2.h create mode 100644 node-v0.8.14/deps/openssl/openssl/include/openssl/pkcs12.h create mode 100644 node-v0.8.14/deps/openssl/openssl/include/openssl/pkcs7.h create mode 100644 node-v0.8.14/deps/openssl/openssl/include/openssl/pqueue.h create mode 100644 node-v0.8.14/deps/openssl/openssl/include/openssl/rand.h create mode 100644 node-v0.8.14/deps/openssl/openssl/include/openssl/rc2.h create mode 100644 node-v0.8.14/deps/openssl/openssl/include/openssl/rc4.h create mode 100644 node-v0.8.14/deps/openssl/openssl/include/openssl/ripemd.h create mode 100644 node-v0.8.14/deps/openssl/openssl/include/openssl/rsa.h create mode 100644 node-v0.8.14/deps/openssl/openssl/include/openssl/safestack.h create mode 100644 node-v0.8.14/deps/openssl/openssl/include/openssl/seed.h create mode 100644 node-v0.8.14/deps/openssl/openssl/include/openssl/sha.h create mode 100644 node-v0.8.14/deps/openssl/openssl/include/openssl/ssl.h create mode 100644 node-v0.8.14/deps/openssl/openssl/include/openssl/ssl2.h create mode 100644 node-v0.8.14/deps/openssl/openssl/include/openssl/ssl23.h create mode 100644 node-v0.8.14/deps/openssl/openssl/include/openssl/ssl3.h create mode 100644 node-v0.8.14/deps/openssl/openssl/include/openssl/stack.h create mode 100644 node-v0.8.14/deps/openssl/openssl/include/openssl/store.h create mode 100644 node-v0.8.14/deps/openssl/openssl/include/openssl/symhacks.h create mode 100644 node-v0.8.14/deps/openssl/openssl/include/openssl/tls1.h create mode 100644 node-v0.8.14/deps/openssl/openssl/include/openssl/ts.h create mode 100644 node-v0.8.14/deps/openssl/openssl/include/openssl/txt_db.h create mode 100644 node-v0.8.14/deps/openssl/openssl/include/openssl/ui.h create mode 100644 node-v0.8.14/deps/openssl/openssl/include/openssl/ui_compat.h create mode 100644 node-v0.8.14/deps/openssl/openssl/include/openssl/whrlpool.h create mode 100644 node-v0.8.14/deps/openssl/openssl/include/openssl/x509.h create mode 100644 node-v0.8.14/deps/openssl/openssl/include/openssl/x509_vfy.h create mode 100644 node-v0.8.14/deps/openssl/openssl/include/openssl/x509v3.h create mode 100644 node-v0.8.14/deps/openssl/openssl/install.com create mode 100755 node-v0.8.14/deps/openssl/openssl/makevms.com create mode 100644 node-v0.8.14/deps/openssl/openssl/ms/.rnd create mode 100755 node-v0.8.14/deps/openssl/openssl/ms/32all.bat create mode 100644 node-v0.8.14/deps/openssl/openssl/ms/README create mode 100644 node-v0.8.14/deps/openssl/openssl/ms/applink.c create mode 100755 node-v0.8.14/deps/openssl/openssl/ms/bcb4.bat create mode 100644 node-v0.8.14/deps/openssl/openssl/ms/certCA.srl create mode 100644 node-v0.8.14/deps/openssl/openssl/ms/certCA.ss create mode 100644 node-v0.8.14/deps/openssl/openssl/ms/certU.ss create mode 100644 node-v0.8.14/deps/openssl/openssl/ms/cmp.pl create mode 100755 node-v0.8.14/deps/openssl/openssl/ms/do_ms.bat create mode 100755 node-v0.8.14/deps/openssl/openssl/ms/do_nasm.bat create mode 100755 node-v0.8.14/deps/openssl/openssl/ms/do_nt.bat create mode 100755 node-v0.8.14/deps/openssl/openssl/ms/do_win64a.bat create mode 100755 node-v0.8.14/deps/openssl/openssl/ms/do_win64i.bat create mode 100644 node-v0.8.14/deps/openssl/openssl/ms/keyCA.ss create mode 100644 node-v0.8.14/deps/openssl/openssl/ms/keyU.ss create mode 100644 node-v0.8.14/deps/openssl/openssl/ms/mingw32.bat create mode 100644 node-v0.8.14/deps/openssl/openssl/ms/mw.bat create mode 100644 node-v0.8.14/deps/openssl/openssl/ms/req2CA.ss create mode 100644 node-v0.8.14/deps/openssl/openssl/ms/reqCA.ss create mode 100644 node-v0.8.14/deps/openssl/openssl/ms/reqU.ss create mode 100755 node-v0.8.14/deps/openssl/openssl/ms/speed32.bat create mode 100755 node-v0.8.14/deps/openssl/openssl/ms/tenc.bat create mode 100644 node-v0.8.14/deps/openssl/openssl/ms/tencce.bat create mode 100755 node-v0.8.14/deps/openssl/openssl/ms/test.bat create mode 100644 node-v0.8.14/deps/openssl/openssl/ms/testce.bat create mode 100644 node-v0.8.14/deps/openssl/openssl/ms/testce2.bat create mode 100755 node-v0.8.14/deps/openssl/openssl/ms/testenc.bat create mode 100644 node-v0.8.14/deps/openssl/openssl/ms/testencce.bat create mode 100755 node-v0.8.14/deps/openssl/openssl/ms/testpem.bat create mode 100644 node-v0.8.14/deps/openssl/openssl/ms/testpemce.bat create mode 100755 node-v0.8.14/deps/openssl/openssl/ms/testss.bat create mode 100644 node-v0.8.14/deps/openssl/openssl/ms/testssce.bat create mode 100644 node-v0.8.14/deps/openssl/openssl/ms/tlhelp32.h create mode 100755 node-v0.8.14/deps/openssl/openssl/ms/tpem.bat create mode 100644 node-v0.8.14/deps/openssl/openssl/ms/tpemce.bat create mode 100644 node-v0.8.14/deps/openssl/openssl/ms/uplink-common.pl create mode 100644 node-v0.8.14/deps/openssl/openssl/ms/uplink-ia64.pl create mode 100644 node-v0.8.14/deps/openssl/openssl/ms/uplink-x86.pl create mode 100644 node-v0.8.14/deps/openssl/openssl/ms/uplink-x86_64.pl create mode 100644 node-v0.8.14/deps/openssl/openssl/ms/uplink.c create mode 100644 node-v0.8.14/deps/openssl/openssl/ms/uplink.h create mode 100755 node-v0.8.14/deps/openssl/openssl/ms/uplink.pl create mode 100755 node-v0.8.14/deps/openssl/openssl/ms/x86asm.bat create mode 100644 node-v0.8.14/deps/openssl/openssl/openssl.doxy create mode 100644 node-v0.8.14/deps/openssl/openssl/openssl.spec create mode 100644 node-v0.8.14/deps/openssl/openssl/os2/OS2-EMX.cmd create mode 100644 node-v0.8.14/deps/openssl/openssl/os2/backwardify.pl create mode 100644 node-v0.8.14/deps/openssl/openssl/shlib/Makefile.hpux10-cc create mode 100644 node-v0.8.14/deps/openssl/openssl/shlib/README create mode 100644 node-v0.8.14/deps/openssl/openssl/shlib/hpux10-cc.sh create mode 100644 node-v0.8.14/deps/openssl/openssl/shlib/irix.sh create mode 100755 node-v0.8.14/deps/openssl/openssl/shlib/sco5-shared-gcc.sh create mode 100755 node-v0.8.14/deps/openssl/openssl/shlib/sco5-shared-installed create mode 100755 node-v0.8.14/deps/openssl/openssl/shlib/sco5-shared.sh create mode 100755 node-v0.8.14/deps/openssl/openssl/shlib/solaris-sc4.sh create mode 100644 node-v0.8.14/deps/openssl/openssl/shlib/solaris.sh create mode 100644 node-v0.8.14/deps/openssl/openssl/shlib/sun.sh create mode 100755 node-v0.8.14/deps/openssl/openssl/shlib/svr5-shared-gcc.sh create mode 100755 node-v0.8.14/deps/openssl/openssl/shlib/svr5-shared-installed create mode 100755 node-v0.8.14/deps/openssl/openssl/shlib/svr5-shared.sh create mode 100755 node-v0.8.14/deps/openssl/openssl/shlib/win32.bat create mode 100755 node-v0.8.14/deps/openssl/openssl/shlib/win32dll.bat create mode 100644 node-v0.8.14/deps/openssl/openssl/ssl/Makefile create mode 100644 node-v0.8.14/deps/openssl/openssl/ssl/bio_ssl.c create mode 100644 node-v0.8.14/deps/openssl/openssl/ssl/d1_both.c create mode 100644 node-v0.8.14/deps/openssl/openssl/ssl/d1_clnt.c create mode 100644 node-v0.8.14/deps/openssl/openssl/ssl/d1_enc.c create mode 100644 node-v0.8.14/deps/openssl/openssl/ssl/d1_lib.c create mode 100644 node-v0.8.14/deps/openssl/openssl/ssl/d1_meth.c create mode 100644 node-v0.8.14/deps/openssl/openssl/ssl/d1_pkt.c create mode 100644 node-v0.8.14/deps/openssl/openssl/ssl/d1_srvr.c create mode 100644 node-v0.8.14/deps/openssl/openssl/ssl/dtls1.h create mode 100644 node-v0.8.14/deps/openssl/openssl/ssl/install-ssl.com create mode 100644 node-v0.8.14/deps/openssl/openssl/ssl/kssl.c create mode 100644 node-v0.8.14/deps/openssl/openssl/ssl/kssl.h create mode 100644 node-v0.8.14/deps/openssl/openssl/ssl/kssl_lcl.h create mode 100644 node-v0.8.14/deps/openssl/openssl/ssl/s23_clnt.c create mode 100644 node-v0.8.14/deps/openssl/openssl/ssl/s23_lib.c create mode 100644 node-v0.8.14/deps/openssl/openssl/ssl/s23_meth.c create mode 100644 node-v0.8.14/deps/openssl/openssl/ssl/s23_pkt.c create mode 100644 node-v0.8.14/deps/openssl/openssl/ssl/s23_srvr.c create mode 100644 node-v0.8.14/deps/openssl/openssl/ssl/s2_clnt.c create mode 100644 node-v0.8.14/deps/openssl/openssl/ssl/s2_enc.c create mode 100644 node-v0.8.14/deps/openssl/openssl/ssl/s2_lib.c create mode 100644 node-v0.8.14/deps/openssl/openssl/ssl/s2_meth.c create mode 100644 node-v0.8.14/deps/openssl/openssl/ssl/s2_pkt.c create mode 100644 node-v0.8.14/deps/openssl/openssl/ssl/s2_srvr.c create mode 100644 node-v0.8.14/deps/openssl/openssl/ssl/s3_both.c create mode 100644 node-v0.8.14/deps/openssl/openssl/ssl/s3_clnt.c create mode 100644 node-v0.8.14/deps/openssl/openssl/ssl/s3_enc.c create mode 100644 node-v0.8.14/deps/openssl/openssl/ssl/s3_lib.c create mode 100644 node-v0.8.14/deps/openssl/openssl/ssl/s3_meth.c create mode 100644 node-v0.8.14/deps/openssl/openssl/ssl/s3_pkt.c create mode 100644 node-v0.8.14/deps/openssl/openssl/ssl/s3_srvr.c create mode 100644 node-v0.8.14/deps/openssl/openssl/ssl/ssl-lib.com create mode 100644 node-v0.8.14/deps/openssl/openssl/ssl/ssl.h create mode 100644 node-v0.8.14/deps/openssl/openssl/ssl/ssl2.h create mode 100644 node-v0.8.14/deps/openssl/openssl/ssl/ssl23.h create mode 100644 node-v0.8.14/deps/openssl/openssl/ssl/ssl3.h create mode 100644 node-v0.8.14/deps/openssl/openssl/ssl/ssl_algs.c create mode 100644 node-v0.8.14/deps/openssl/openssl/ssl/ssl_asn1.c create mode 100644 node-v0.8.14/deps/openssl/openssl/ssl/ssl_cert.c create mode 100644 node-v0.8.14/deps/openssl/openssl/ssl/ssl_ciph.c create mode 100644 node-v0.8.14/deps/openssl/openssl/ssl/ssl_err.c create mode 100644 node-v0.8.14/deps/openssl/openssl/ssl/ssl_err2.c create mode 100644 node-v0.8.14/deps/openssl/openssl/ssl/ssl_lib.c create mode 100644 node-v0.8.14/deps/openssl/openssl/ssl/ssl_locl.h create mode 100644 node-v0.8.14/deps/openssl/openssl/ssl/ssl_rsa.c create mode 100644 node-v0.8.14/deps/openssl/openssl/ssl/ssl_sess.c create mode 100644 node-v0.8.14/deps/openssl/openssl/ssl/ssl_stat.c create mode 100644 node-v0.8.14/deps/openssl/openssl/ssl/ssl_task.c create mode 100644 node-v0.8.14/deps/openssl/openssl/ssl/ssl_txt.c create mode 100644 node-v0.8.14/deps/openssl/openssl/ssl/ssltest.c create mode 100644 node-v0.8.14/deps/openssl/openssl/ssl/t1_clnt.c create mode 100644 node-v0.8.14/deps/openssl/openssl/ssl/t1_enc.c create mode 100644 node-v0.8.14/deps/openssl/openssl/ssl/t1_lib.c create mode 100644 node-v0.8.14/deps/openssl/openssl/ssl/t1_meth.c create mode 100644 node-v0.8.14/deps/openssl/openssl/ssl/t1_reneg.c create mode 100644 node-v0.8.14/deps/openssl/openssl/ssl/t1_srvr.c create mode 100644 node-v0.8.14/deps/openssl/openssl/ssl/tls1.h create mode 100644 node-v0.8.14/deps/openssl/openssl/times/090/586-100.nt create mode 100644 node-v0.8.14/deps/openssl/openssl/times/091/486-50.nt create mode 100644 node-v0.8.14/deps/openssl/openssl/times/091/586-100.lnx create mode 100644 node-v0.8.14/deps/openssl/openssl/times/091/68000.bsd create mode 100644 node-v0.8.14/deps/openssl/openssl/times/091/686-200.lnx create mode 100644 node-v0.8.14/deps/openssl/openssl/times/091/alpha064.osf create mode 100644 node-v0.8.14/deps/openssl/openssl/times/091/alpha164.lnx create mode 100644 node-v0.8.14/deps/openssl/openssl/times/091/alpha164.osf create mode 100644 node-v0.8.14/deps/openssl/openssl/times/091/mips-rel.pl create mode 100644 node-v0.8.14/deps/openssl/openssl/times/091/r10000.irx create mode 100644 node-v0.8.14/deps/openssl/openssl/times/091/r3000.ult create mode 100644 node-v0.8.14/deps/openssl/openssl/times/091/r4400.irx create mode 100644 node-v0.8.14/deps/openssl/openssl/times/100.lnx create mode 100644 node-v0.8.14/deps/openssl/openssl/times/100.nt create mode 100644 node-v0.8.14/deps/openssl/openssl/times/200.lnx create mode 100644 node-v0.8.14/deps/openssl/openssl/times/486-66.dos create mode 100644 node-v0.8.14/deps/openssl/openssl/times/486-66.nt create mode 100644 node-v0.8.14/deps/openssl/openssl/times/486-66.w31 create mode 100644 node-v0.8.14/deps/openssl/openssl/times/5.lnx create mode 100644 node-v0.8.14/deps/openssl/openssl/times/586-085i.nt create mode 100644 node-v0.8.14/deps/openssl/openssl/times/586-100.LN3 create mode 100644 node-v0.8.14/deps/openssl/openssl/times/586-100.NT2 create mode 100644 node-v0.8.14/deps/openssl/openssl/times/586-100.dos create mode 100644 node-v0.8.14/deps/openssl/openssl/times/586-100.ln4 create mode 100644 node-v0.8.14/deps/openssl/openssl/times/586-100.lnx create mode 100644 node-v0.8.14/deps/openssl/openssl/times/586-100.nt create mode 100644 node-v0.8.14/deps/openssl/openssl/times/586-100.ntx create mode 100644 node-v0.8.14/deps/openssl/openssl/times/586-100.w31 create mode 100644 node-v0.8.14/deps/openssl/openssl/times/586-1002.lnx create mode 100644 node-v0.8.14/deps/openssl/openssl/times/586p-100.lnx create mode 100644 node-v0.8.14/deps/openssl/openssl/times/686-200.bsd create mode 100644 node-v0.8.14/deps/openssl/openssl/times/686-200.lnx create mode 100644 node-v0.8.14/deps/openssl/openssl/times/686-200.nt create mode 100644 node-v0.8.14/deps/openssl/openssl/times/L1 create mode 100644 node-v0.8.14/deps/openssl/openssl/times/R10000.t create mode 100644 node-v0.8.14/deps/openssl/openssl/times/R4400.t create mode 100644 node-v0.8.14/deps/openssl/openssl/times/aix.t create mode 100644 node-v0.8.14/deps/openssl/openssl/times/aixold.t create mode 100644 node-v0.8.14/deps/openssl/openssl/times/alpha.t create mode 100644 node-v0.8.14/deps/openssl/openssl/times/alpha400.t create mode 100644 node-v0.8.14/deps/openssl/openssl/times/cyrix100.lnx create mode 100644 node-v0.8.14/deps/openssl/openssl/times/dgux-x86.t create mode 100644 node-v0.8.14/deps/openssl/openssl/times/dgux.t create mode 100644 node-v0.8.14/deps/openssl/openssl/times/hpux-acc.t create mode 100644 node-v0.8.14/deps/openssl/openssl/times/hpux-kr.t create mode 100644 node-v0.8.14/deps/openssl/openssl/times/hpux.t create mode 100644 node-v0.8.14/deps/openssl/openssl/times/p2.w95 create mode 100644 node-v0.8.14/deps/openssl/openssl/times/pent2.t create mode 100644 node-v0.8.14/deps/openssl/openssl/times/readme create mode 100644 node-v0.8.14/deps/openssl/openssl/times/s586-100.lnx create mode 100644 node-v0.8.14/deps/openssl/openssl/times/s586-100.nt create mode 100644 node-v0.8.14/deps/openssl/openssl/times/sgi.t create mode 100644 node-v0.8.14/deps/openssl/openssl/times/sparc.t create mode 100644 node-v0.8.14/deps/openssl/openssl/times/sparc2 create mode 100644 node-v0.8.14/deps/openssl/openssl/times/sparcLX.t create mode 100644 node-v0.8.14/deps/openssl/openssl/times/usparc.t create mode 100644 node-v0.8.14/deps/openssl/openssl/times/x86/bfs.cpp create mode 100644 node-v0.8.14/deps/openssl/openssl/times/x86/casts.cpp create mode 100644 node-v0.8.14/deps/openssl/openssl/times/x86/des3s.cpp create mode 100644 node-v0.8.14/deps/openssl/openssl/times/x86/dess.cpp create mode 100644 node-v0.8.14/deps/openssl/openssl/times/x86/md4s.cpp create mode 100644 node-v0.8.14/deps/openssl/openssl/times/x86/md5s.cpp create mode 100644 node-v0.8.14/deps/openssl/openssl/times/x86/rc4s.cpp create mode 100644 node-v0.8.14/deps/openssl/openssl/times/x86/sha1s.cpp create mode 100644 node-v0.8.14/deps/openssl/openssl/tools/Makefile create mode 100755 node-v0.8.14/deps/openssl/openssl/tools/c89.sh create mode 100644 node-v0.8.14/deps/openssl/openssl/tools/c_hash create mode 100644 node-v0.8.14/deps/openssl/openssl/tools/c_info create mode 100644 node-v0.8.14/deps/openssl/openssl/tools/c_issuer create mode 100644 node-v0.8.14/deps/openssl/openssl/tools/c_name create mode 100644 node-v0.8.14/deps/openssl/openssl/tools/c_rehash create mode 100644 node-v0.8.14/deps/openssl/openssl/tools/c_rehash.in create mode 100755 node-v0.8.14/deps/openssl/openssl/util/FreeBSD.sh create mode 100755 node-v0.8.14/deps/openssl/openssl/util/add_cr.pl create mode 100755 node-v0.8.14/deps/openssl/openssl/util/bat.sh create mode 100755 node-v0.8.14/deps/openssl/openssl/util/ck_errf.pl create mode 100755 node-v0.8.14/deps/openssl/openssl/util/clean-depend.pl create mode 100644 node-v0.8.14/deps/openssl/openssl/util/copy.pl create mode 100755 node-v0.8.14/deps/openssl/openssl/util/cygwin.sh create mode 100755 node-v0.8.14/deps/openssl/openssl/util/deleof.pl create mode 100644 node-v0.8.14/deps/openssl/openssl/util/deltree.com create mode 100644 node-v0.8.14/deps/openssl/openssl/util/dirname.pl create mode 100755 node-v0.8.14/deps/openssl/openssl/util/do_ms.sh create mode 100755 node-v0.8.14/deps/openssl/openssl/util/domd create mode 100755 node-v0.8.14/deps/openssl/openssl/util/err-ins.pl create mode 100644 node-v0.8.14/deps/openssl/openssl/util/extract-names.pl create mode 100644 node-v0.8.14/deps/openssl/openssl/util/extract-section.pl create mode 100755 node-v0.8.14/deps/openssl/openssl/util/files.pl create mode 100755 node-v0.8.14/deps/openssl/openssl/util/fixNT.sh create mode 100755 node-v0.8.14/deps/openssl/openssl/util/install.sh create mode 100755 node-v0.8.14/deps/openssl/openssl/util/libeay.num create mode 100755 node-v0.8.14/deps/openssl/openssl/util/mk1mf.pl create mode 100755 node-v0.8.14/deps/openssl/openssl/util/mkcerts.sh create mode 100755 node-v0.8.14/deps/openssl/openssl/util/mkdef.pl create mode 100755 node-v0.8.14/deps/openssl/openssl/util/mkdir-p.pl create mode 100644 node-v0.8.14/deps/openssl/openssl/util/mkerr.pl create mode 100755 node-v0.8.14/deps/openssl/openssl/util/mkfiles.pl create mode 100755 node-v0.8.14/deps/openssl/openssl/util/mklink.pl create mode 100644 node-v0.8.14/deps/openssl/openssl/util/mkrc.pl create mode 100755 node-v0.8.14/deps/openssl/openssl/util/mkstack.pl create mode 100755 node-v0.8.14/deps/openssl/openssl/util/opensslwrap.sh create mode 100755 node-v0.8.14/deps/openssl/openssl/util/perlpath.pl create mode 100644 node-v0.8.14/deps/openssl/openssl/util/pl/BC-32.pl create mode 100644 node-v0.8.14/deps/openssl/openssl/util/pl/Mingw32.pl create mode 100644 node-v0.8.14/deps/openssl/openssl/util/pl/OS2-EMX.pl create mode 100644 node-v0.8.14/deps/openssl/openssl/util/pl/VC-32.pl create mode 100644 node-v0.8.14/deps/openssl/openssl/util/pl/linux.pl create mode 100644 node-v0.8.14/deps/openssl/openssl/util/pl/netware.pl create mode 100644 node-v0.8.14/deps/openssl/openssl/util/pl/ultrix.pl create mode 100644 node-v0.8.14/deps/openssl/openssl/util/pl/unix.pl create mode 100755 node-v0.8.14/deps/openssl/openssl/util/pod2man.pl create mode 100755 node-v0.8.14/deps/openssl/openssl/util/pod2mantest create mode 100644 node-v0.8.14/deps/openssl/openssl/util/pod2mantest.pod create mode 100755 node-v0.8.14/deps/openssl/openssl/util/point.sh create mode 100644 node-v0.8.14/deps/openssl/openssl/util/selftest.pl create mode 100755 node-v0.8.14/deps/openssl/openssl/util/shlib_wrap.sh create mode 100755 node-v0.8.14/deps/openssl/openssl/util/sp-diff.pl create mode 100755 node-v0.8.14/deps/openssl/openssl/util/speed.sh create mode 100755 node-v0.8.14/deps/openssl/openssl/util/src-dep.pl create mode 100755 node-v0.8.14/deps/openssl/openssl/util/ssleay.num create mode 100755 node-v0.8.14/deps/openssl/openssl/util/tab_num.pl create mode 100755 node-v0.8.14/deps/openssl/openssl/util/x86asm.sh create mode 100644 node-v0.8.14/deps/openssl/patches/handshake_cutthrough.patch create mode 100644 node-v0.8.14/deps/openssl/patches/jsse.patch create mode 100644 node-v0.8.14/deps/openssl/patches/npn.patch create mode 100644 node-v0.8.14/deps/openssl/patches/openssl_no_dtls1.patch create mode 100644 node-v0.8.14/deps/openssl/patches/progs.patch create mode 100644 node-v0.8.14/deps/openssl/patches/sha1_armv4_large.patch create mode 100644 node-v0.8.14/deps/openssl/patches/small_records.patch create mode 100755 node-v0.8.14/deps/openssl/patches/tls_exporter.patch create mode 100644 node-v0.8.14/deps/openssl/patches/x509_hash_name_algorithm_change.patch create mode 100644 node-v0.8.14/deps/uv/.gitignore create mode 100644 node-v0.8.14/deps/uv/.mailmap create mode 100644 node-v0.8.14/deps/uv/.travis.yml create mode 100644 node-v0.8.14/deps/uv/AUTHORS create mode 100644 node-v0.8.14/deps/uv/LICENSE create mode 100644 node-v0.8.14/deps/uv/Makefile create mode 100644 node-v0.8.14/deps/uv/README.md create mode 100644 node-v0.8.14/deps/uv/common.gypi create mode 100755 node-v0.8.14/deps/uv/gyp_uv create mode 100644 node-v0.8.14/deps/uv/include/ares.h create mode 100644 node-v0.8.14/deps/uv/include/ares_version.h create mode 100644 node-v0.8.14/deps/uv/include/uv-private/eio.h create mode 100644 node-v0.8.14/deps/uv/include/uv-private/ev.h create mode 100644 node-v0.8.14/deps/uv/include/uv-private/ngx-queue.h create mode 100644 node-v0.8.14/deps/uv/include/uv-private/tree.h create mode 100644 node-v0.8.14/deps/uv/include/uv-private/uv-unix.h create mode 100644 node-v0.8.14/deps/uv/include/uv-private/uv-win.h create mode 100644 node-v0.8.14/deps/uv/include/uv.h create mode 100644 node-v0.8.14/deps/uv/test/benchmark-ares.c create mode 100644 node-v0.8.14/deps/uv/test/benchmark-fs-stat.c create mode 100644 node-v0.8.14/deps/uv/test/benchmark-getaddrinfo.c create mode 100644 node-v0.8.14/deps/uv/test/benchmark-list.h create mode 100644 node-v0.8.14/deps/uv/test/benchmark-loop-count.c create mode 100644 node-v0.8.14/deps/uv/test/benchmark-million-timers.c create mode 100644 node-v0.8.14/deps/uv/test/benchmark-ping-pongs.c create mode 100644 node-v0.8.14/deps/uv/test/benchmark-pound.c create mode 100644 node-v0.8.14/deps/uv/test/benchmark-pump.c create mode 100644 node-v0.8.14/deps/uv/test/benchmark-sizes.c create mode 100644 node-v0.8.14/deps/uv/test/benchmark-spawn.c create mode 100644 node-v0.8.14/deps/uv/test/benchmark-tcp-write-batch.c create mode 100644 node-v0.8.14/deps/uv/test/benchmark-thread.c create mode 100644 node-v0.8.14/deps/uv/test/benchmark-udp-packet-storm.c create mode 100644 node-v0.8.14/deps/uv/test/blackhole-server.c create mode 100644 node-v0.8.14/deps/uv/test/dns-server.c create mode 100644 node-v0.8.14/deps/uv/test/echo-server.c create mode 100644 node-v0.8.14/deps/uv/test/fixtures/empty_file create mode 100644 node-v0.8.14/deps/uv/test/fixtures/load_error.node create mode 100644 node-v0.8.14/deps/uv/test/run-benchmarks.c create mode 100644 node-v0.8.14/deps/uv/test/run-tests.c create mode 100644 node-v0.8.14/deps/uv/test/runner-unix.c create mode 100644 node-v0.8.14/deps/uv/test/runner-unix.h create mode 100644 node-v0.8.14/deps/uv/test/runner-win.c create mode 100644 node-v0.8.14/deps/uv/test/runner-win.h create mode 100644 node-v0.8.14/deps/uv/test/runner.c create mode 100644 node-v0.8.14/deps/uv/test/runner.h create mode 100644 node-v0.8.14/deps/uv/test/task.h create mode 100644 node-v0.8.14/deps/uv/test/test-async.c create mode 100644 node-v0.8.14/deps/uv/test/test-callback-order.c create mode 100644 node-v0.8.14/deps/uv/test/test-callback-stack.c create mode 100644 node-v0.8.14/deps/uv/test/test-connection-fail.c create mode 100644 node-v0.8.14/deps/uv/test/test-counters-init.c create mode 100644 node-v0.8.14/deps/uv/test/test-cwd-and-chdir.c create mode 100644 node-v0.8.14/deps/uv/test/test-delayed-accept.c create mode 100644 node-v0.8.14/deps/uv/test/test-dlerror.c create mode 100644 node-v0.8.14/deps/uv/test/test-error.c create mode 100644 node-v0.8.14/deps/uv/test/test-fail-always.c create mode 100644 node-v0.8.14/deps/uv/test/test-fs-event.c create mode 100644 node-v0.8.14/deps/uv/test/test-fs-poll.c create mode 100644 node-v0.8.14/deps/uv/test/test-fs.c create mode 100644 node-v0.8.14/deps/uv/test/test-get-currentexe.c create mode 100644 node-v0.8.14/deps/uv/test/test-get-loadavg.c create mode 100644 node-v0.8.14/deps/uv/test/test-get-memory.c create mode 100644 node-v0.8.14/deps/uv/test/test-getaddrinfo.c create mode 100644 node-v0.8.14/deps/uv/test/test-gethostbyname.c create mode 100644 node-v0.8.14/deps/uv/test/test-getsockname.c create mode 100644 node-v0.8.14/deps/uv/test/test-hrtime.c create mode 100644 node-v0.8.14/deps/uv/test/test-idle.c create mode 100644 node-v0.8.14/deps/uv/test/test-ipc-send-recv.c create mode 100644 node-v0.8.14/deps/uv/test/test-ipc.c create mode 100644 node-v0.8.14/deps/uv/test/test-list.h create mode 100644 node-v0.8.14/deps/uv/test/test-loop-handles.c create mode 100644 node-v0.8.14/deps/uv/test/test-multiple-listen.c create mode 100644 node-v0.8.14/deps/uv/test/test-mutexes.c create mode 100644 node-v0.8.14/deps/uv/test/test-pass-always.c create mode 100644 node-v0.8.14/deps/uv/test/test-ping-pong.c create mode 100644 node-v0.8.14/deps/uv/test/test-pipe-bind-error.c create mode 100644 node-v0.8.14/deps/uv/test/test-pipe-connect-error.c create mode 100644 node-v0.8.14/deps/uv/test/test-platform-output.c create mode 100644 node-v0.8.14/deps/uv/test/test-poll-close.c create mode 100644 node-v0.8.14/deps/uv/test/test-poll.c create mode 100644 node-v0.8.14/deps/uv/test/test-process-title.c create mode 100644 node-v0.8.14/deps/uv/test/test-ref.c create mode 100644 node-v0.8.14/deps/uv/test/test-run-once.c create mode 100644 node-v0.8.14/deps/uv/test/test-semaphore.c create mode 100644 node-v0.8.14/deps/uv/test/test-shutdown-close.c create mode 100644 node-v0.8.14/deps/uv/test/test-shutdown-eof.c create mode 100644 node-v0.8.14/deps/uv/test/test-spawn.c create mode 100644 node-v0.8.14/deps/uv/test/test-stdio-over-pipes.c create mode 100644 node-v0.8.14/deps/uv/test/test-tcp-bind-error.c create mode 100644 node-v0.8.14/deps/uv/test/test-tcp-bind6-error.c create mode 100644 node-v0.8.14/deps/uv/test/test-tcp-close-while-connecting.c create mode 100644 node-v0.8.14/deps/uv/test/test-tcp-close.c create mode 100644 node-v0.8.14/deps/uv/test/test-tcp-connect-error-after-write.c create mode 100644 node-v0.8.14/deps/uv/test/test-tcp-connect-error.c create mode 100644 node-v0.8.14/deps/uv/test/test-tcp-connect-timeout.c create mode 100644 node-v0.8.14/deps/uv/test/test-tcp-connect6-error.c create mode 100644 node-v0.8.14/deps/uv/test/test-tcp-flags.c create mode 100644 node-v0.8.14/deps/uv/test/test-tcp-shutdown-after-write.c create mode 100644 node-v0.8.14/deps/uv/test/test-tcp-unexpected-read.c create mode 100644 node-v0.8.14/deps/uv/test/test-tcp-write-error.c create mode 100644 node-v0.8.14/deps/uv/test/test-tcp-write-to-half-open-connection.c create mode 100644 node-v0.8.14/deps/uv/test/test-tcp-writealot.c create mode 100644 node-v0.8.14/deps/uv/test/test-thread.c create mode 100644 node-v0.8.14/deps/uv/test/test-threadpool.c create mode 100644 node-v0.8.14/deps/uv/test/test-timer-again.c create mode 100644 node-v0.8.14/deps/uv/test/test-timer.c create mode 100644 node-v0.8.14/deps/uv/test/test-tty.c create mode 100644 node-v0.8.14/deps/uv/test/test-udp-dgram-too-big.c create mode 100644 node-v0.8.14/deps/uv/test/test-udp-ipv6.c create mode 100644 node-v0.8.14/deps/uv/test/test-udp-multicast-join.c create mode 100644 node-v0.8.14/deps/uv/test/test-udp-multicast-ttl.c create mode 100644 node-v0.8.14/deps/uv/test/test-udp-options.c create mode 100644 node-v0.8.14/deps/uv/test/test-udp-send-and-recv.c create mode 100644 node-v0.8.14/deps/uv/test/test-util.c create mode 100644 node-v0.8.14/deps/uv/test/test-walk-handles.c create mode 100644 node-v0.8.14/deps/uv/uv.gyp create mode 100644 node-v0.8.14/deps/uv/vcbuild.bat create mode 100644 node-v0.8.14/deps/v8/.gitignore create mode 100644 node-v0.8.14/deps/v8/AUTHORS create mode 100644 node-v0.8.14/deps/v8/ChangeLog create mode 100644 node-v0.8.14/deps/v8/DEPS create mode 100644 node-v0.8.14/deps/v8/LICENSE create mode 100644 node-v0.8.14/deps/v8/LICENSE.strongtalk create mode 100644 node-v0.8.14/deps/v8/LICENSE.v8 create mode 100644 node-v0.8.14/deps/v8/LICENSE.valgrind create mode 100644 node-v0.8.14/deps/v8/Makefile create mode 100644 node-v0.8.14/deps/v8/SConstruct create mode 100644 node-v0.8.14/deps/v8/benchmarks/README.txt create mode 100644 node-v0.8.14/deps/v8/benchmarks/base.js create mode 100644 node-v0.8.14/deps/v8/benchmarks/crypto.js create mode 100644 node-v0.8.14/deps/v8/benchmarks/deltablue.js create mode 100644 node-v0.8.14/deps/v8/benchmarks/earley-boyer.js create mode 100644 node-v0.8.14/deps/v8/benchmarks/navier-stokes.js create mode 100644 node-v0.8.14/deps/v8/benchmarks/raytrace.js create mode 100644 node-v0.8.14/deps/v8/benchmarks/regexp.js create mode 100644 node-v0.8.14/deps/v8/benchmarks/revisions.html create mode 100644 node-v0.8.14/deps/v8/benchmarks/richards.js create mode 100644 node-v0.8.14/deps/v8/benchmarks/run.html create mode 100644 node-v0.8.14/deps/v8/benchmarks/run.js create mode 100644 node-v0.8.14/deps/v8/benchmarks/spinning-balls/index.html create mode 100644 node-v0.8.14/deps/v8/benchmarks/spinning-balls/splay-tree.js create mode 100644 node-v0.8.14/deps/v8/benchmarks/spinning-balls/v.js create mode 100644 node-v0.8.14/deps/v8/benchmarks/splay.js create mode 100644 node-v0.8.14/deps/v8/benchmarks/style.css create mode 100644 node-v0.8.14/deps/v8/benchmarks/v8-logo.png create mode 100644 node-v0.8.14/deps/v8/build/README.txt create mode 100644 node-v0.8.14/deps/v8/build/all.gyp create mode 100644 node-v0.8.14/deps/v8/build/android.gypi create mode 100644 node-v0.8.14/deps/v8/build/common.gypi create mode 100755 node-v0.8.14/deps/v8/build/gyp_v8 create mode 100644 node-v0.8.14/deps/v8/build/standalone.gypi create mode 100755 node-v0.8.14/deps/v8/include/v8-debug.h create mode 100644 node-v0.8.14/deps/v8/include/v8-preparser.h create mode 100644 node-v0.8.14/deps/v8/include/v8-profiler.h create mode 100644 node-v0.8.14/deps/v8/include/v8-testing.h create mode 100644 node-v0.8.14/deps/v8/include/v8.h create mode 100644 node-v0.8.14/deps/v8/include/v8stdint.h create mode 100644 node-v0.8.14/deps/v8/preparser/SConscript create mode 100644 node-v0.8.14/deps/v8/preparser/preparser-process.cc create mode 100644 node-v0.8.14/deps/v8/preparser/preparser.gyp create mode 100644 node-v0.8.14/deps/v8/samples/SConscript create mode 100644 node-v0.8.14/deps/v8/samples/count-hosts.js create mode 100644 node-v0.8.14/deps/v8/samples/lineprocessor.cc create mode 100644 node-v0.8.14/deps/v8/samples/process.cc create mode 100644 node-v0.8.14/deps/v8/samples/samples.gyp create mode 100644 node-v0.8.14/deps/v8/samples/shell.cc create mode 100644 node-v0.8.14/deps/v8/tools/bash-completion.sh create mode 100644 node-v0.8.14/deps/v8/tools/check-static-initializers.sh create mode 100644 node-v0.8.14/deps/v8/tools/codemap.js create mode 100644 node-v0.8.14/deps/v8/tools/common-includes.sh create mode 100644 node-v0.8.14/deps/v8/tools/consarray.js create mode 100644 node-v0.8.14/deps/v8/tools/csvparser.js create mode 100644 node-v0.8.14/deps/v8/tools/disasm.py create mode 100755 node-v0.8.14/deps/v8/tools/freebsd-tick-processor create mode 100644 node-v0.8.14/deps/v8/tools/fuzz-harness.sh create mode 100755 node-v0.8.14/deps/v8/tools/gc-nvp-trace-processor.py create mode 100644 node-v0.8.14/deps/v8/tools/gcmole/Makefile create mode 100644 node-v0.8.14/deps/v8/tools/gcmole/README create mode 100644 node-v0.8.14/deps/v8/tools/gcmole/gccause.lua create mode 100644 node-v0.8.14/deps/v8/tools/gcmole/gcmole.cc create mode 100644 node-v0.8.14/deps/v8/tools/gcmole/gcmole.lua create mode 100644 node-v0.8.14/deps/v8/tools/gdb-v8-support.py create mode 100644 node-v0.8.14/deps/v8/tools/gen-postmortem-metadata.py create mode 100644 node-v0.8.14/deps/v8/tools/generate-ten-powers.scm create mode 100755 node-v0.8.14/deps/v8/tools/grokdump.py create mode 100644 node-v0.8.14/deps/v8/tools/gyp/v8.gyp create mode 100644 node-v0.8.14/deps/v8/tools/js2c.py create mode 100644 node-v0.8.14/deps/v8/tools/jsmin.py create mode 100755 node-v0.8.14/deps/v8/tools/linux-tick-processor create mode 100755 node-v0.8.14/deps/v8/tools/ll_prof.py create mode 100644 node-v0.8.14/deps/v8/tools/logreader.js create mode 100755 node-v0.8.14/deps/v8/tools/mac-nm create mode 100755 node-v0.8.14/deps/v8/tools/mac-tick-processor create mode 100644 node-v0.8.14/deps/v8/tools/merge-to-branch.sh create mode 100644 node-v0.8.14/deps/v8/tools/oom_dump/README create mode 100644 node-v0.8.14/deps/v8/tools/oom_dump/SConstruct create mode 100644 node-v0.8.14/deps/v8/tools/oom_dump/oom_dump.cc create mode 100755 node-v0.8.14/deps/v8/tools/presubmit.py create mode 100755 node-v0.8.14/deps/v8/tools/process-heap-prof.py create mode 100644 node-v0.8.14/deps/v8/tools/profile.js create mode 100644 node-v0.8.14/deps/v8/tools/profile_view.js create mode 100755 node-v0.8.14/deps/v8/tools/push-to-trunk.sh create mode 100755 node-v0.8.14/deps/v8/tools/run-valgrind.py create mode 100644 node-v0.8.14/deps/v8/tools/splaytree.js create mode 100755 node-v0.8.14/deps/v8/tools/stats-viewer.py create mode 100755 node-v0.8.14/deps/v8/tools/test-wrapper-gypbuild.py create mode 100755 node-v0.8.14/deps/v8/tools/test.py create mode 100644 node-v0.8.14/deps/v8/tools/tickprocessor-driver.js create mode 100644 node-v0.8.14/deps/v8/tools/tickprocessor.js create mode 100644 node-v0.8.14/deps/v8/tools/utils.py create mode 100644 node-v0.8.14/deps/v8/tools/visual_studio/README.txt create mode 100755 node-v0.8.14/deps/v8/tools/windows-tick-processor.bat create mode 100644 node-v0.8.14/deps/zlib/LICENSE create mode 100644 node-v0.8.14/deps/zlib/README.chromium create mode 100644 node-v0.8.14/deps/zlib/adler32.c create mode 100644 node-v0.8.14/deps/zlib/compress.c create mode 100644 node-v0.8.14/deps/zlib/contrib/minizip/ChangeLogUnzip create mode 100644 node-v0.8.14/deps/zlib/contrib/minizip/Makefile create mode 100644 node-v0.8.14/deps/zlib/contrib/minizip/crypt.h create mode 100644 node-v0.8.14/deps/zlib/contrib/minizip/ioapi.c create mode 100644 node-v0.8.14/deps/zlib/contrib/minizip/ioapi.h create mode 100644 node-v0.8.14/deps/zlib/contrib/minizip/iowin32.c create mode 100644 node-v0.8.14/deps/zlib/contrib/minizip/iowin32.h create mode 100644 node-v0.8.14/deps/zlib/contrib/minizip/miniunz.c create mode 100644 node-v0.8.14/deps/zlib/contrib/minizip/minizip.c create mode 100644 node-v0.8.14/deps/zlib/contrib/minizip/mztools.c create mode 100644 node-v0.8.14/deps/zlib/contrib/minizip/mztools.h create mode 100644 node-v0.8.14/deps/zlib/contrib/minizip/unzip.c create mode 100644 node-v0.8.14/deps/zlib/contrib/minizip/unzip.h create mode 100644 node-v0.8.14/deps/zlib/contrib/minizip/zip.c create mode 100644 node-v0.8.14/deps/zlib/contrib/minizip/zip.h create mode 100644 node-v0.8.14/deps/zlib/crc32.c create mode 100644 node-v0.8.14/deps/zlib/crc32.h create mode 100644 node-v0.8.14/deps/zlib/deflate.c create mode 100644 node-v0.8.14/deps/zlib/deflate.h create mode 100644 node-v0.8.14/deps/zlib/gzio.c create mode 100644 node-v0.8.14/deps/zlib/infback.c create mode 100644 node-v0.8.14/deps/zlib/inffast.c create mode 100644 node-v0.8.14/deps/zlib/inffast.h create mode 100644 node-v0.8.14/deps/zlib/inffixed.h create mode 100644 node-v0.8.14/deps/zlib/inflate.c create mode 100644 node-v0.8.14/deps/zlib/inflate.h create mode 100644 node-v0.8.14/deps/zlib/inftrees.c create mode 100644 node-v0.8.14/deps/zlib/inftrees.h create mode 100644 node-v0.8.14/deps/zlib/mozzconf.h create mode 100644 node-v0.8.14/deps/zlib/trees.c create mode 100644 node-v0.8.14/deps/zlib/trees.h create mode 100644 node-v0.8.14/deps/zlib/uncompr.c create mode 100644 node-v0.8.14/deps/zlib/zconf.h create mode 100644 node-v0.8.14/deps/zlib/zlib.gyp create mode 100644 node-v0.8.14/deps/zlib/zlib.h create mode 100644 node-v0.8.14/deps/zlib/zutil.c create mode 100644 node-v0.8.14/deps/zlib/zutil.h create mode 100644 node-v0.8.14/doc/about/index.html create mode 100644 node-v0.8.14/doc/api/_toc.html create mode 100644 node-v0.8.14/doc/api/_toc.json create mode 100644 node-v0.8.14/doc/api/_toc.markdown create mode 100644 node-v0.8.14/doc/api/addons.html create mode 100644 node-v0.8.14/doc/api/addons.json create mode 100644 node-v0.8.14/doc/api/addons.markdown create mode 100644 node-v0.8.14/doc/api/all.html create mode 100644 node-v0.8.14/doc/api/all.json create mode 100644 node-v0.8.14/doc/api/all.markdown create mode 100644 node-v0.8.14/doc/api/assert.html create mode 100644 node-v0.8.14/doc/api/assert.json create mode 100644 node-v0.8.14/doc/api/assert.markdown create mode 100644 node-v0.8.14/doc/api/assets/sh.css create mode 100644 node-v0.8.14/doc/api/assets/style.css create mode 100644 node-v0.8.14/doc/api/buffer.html create mode 100644 node-v0.8.14/doc/api/buffer.json create mode 100644 node-v0.8.14/doc/api/buffer.markdown create mode 100644 node-v0.8.14/doc/api/child_process.html create mode 100644 node-v0.8.14/doc/api/child_process.json create mode 100644 node-v0.8.14/doc/api/child_process.markdown create mode 100644 node-v0.8.14/doc/api/cluster.html create mode 100644 node-v0.8.14/doc/api/cluster.json create mode 100644 node-v0.8.14/doc/api/cluster.markdown create mode 100644 node-v0.8.14/doc/api/crypto.html create mode 100644 node-v0.8.14/doc/api/crypto.json create mode 100644 node-v0.8.14/doc/api/crypto.markdown create mode 100644 node-v0.8.14/doc/api/debugger.html create mode 100644 node-v0.8.14/doc/api/debugger.json create mode 100644 node-v0.8.14/doc/api/debugger.markdown create mode 100644 node-v0.8.14/doc/api/dgram.html create mode 100644 node-v0.8.14/doc/api/dgram.json create mode 100644 node-v0.8.14/doc/api/dgram.markdown create mode 100644 node-v0.8.14/doc/api/dns.html create mode 100644 node-v0.8.14/doc/api/dns.json create mode 100644 node-v0.8.14/doc/api/dns.markdown create mode 100644 node-v0.8.14/doc/api/documentation.html create mode 100644 node-v0.8.14/doc/api/documentation.json create mode 100644 node-v0.8.14/doc/api/documentation.markdown create mode 100644 node-v0.8.14/doc/api/domain.html create mode 100644 node-v0.8.14/doc/api/domain.json create mode 100644 node-v0.8.14/doc/api/domain.markdown create mode 100644 node-v0.8.14/doc/api/events.html create mode 100644 node-v0.8.14/doc/api/events.json create mode 100644 node-v0.8.14/doc/api/events.markdown create mode 100644 node-v0.8.14/doc/api/fs.html create mode 100644 node-v0.8.14/doc/api/fs.json create mode 100644 node-v0.8.14/doc/api/fs.markdown create mode 100644 node-v0.8.14/doc/api/globals.html create mode 100644 node-v0.8.14/doc/api/globals.json create mode 100644 node-v0.8.14/doc/api/globals.markdown create mode 100644 node-v0.8.14/doc/api/http.html create mode 100644 node-v0.8.14/doc/api/http.json create mode 100644 node-v0.8.14/doc/api/http.markdown create mode 100644 node-v0.8.14/doc/api/https.html create mode 100644 node-v0.8.14/doc/api/https.json create mode 100644 node-v0.8.14/doc/api/https.markdown create mode 100644 node-v0.8.14/doc/api/index.html create mode 100644 node-v0.8.14/doc/api/index.json create mode 100644 node-v0.8.14/doc/api/index.markdown create mode 100644 node-v0.8.14/doc/api/modules.html create mode 100644 node-v0.8.14/doc/api/modules.json create mode 100644 node-v0.8.14/doc/api/modules.markdown create mode 100644 node-v0.8.14/doc/api/net.html create mode 100644 node-v0.8.14/doc/api/net.json create mode 100644 node-v0.8.14/doc/api/net.markdown create mode 100644 node-v0.8.14/doc/api/os.html create mode 100644 node-v0.8.14/doc/api/os.json create mode 100644 node-v0.8.14/doc/api/os.markdown create mode 100644 node-v0.8.14/doc/api/path.html create mode 100644 node-v0.8.14/doc/api/path.json create mode 100644 node-v0.8.14/doc/api/path.markdown create mode 100644 node-v0.8.14/doc/api/process.html create mode 100644 node-v0.8.14/doc/api/process.json create mode 100644 node-v0.8.14/doc/api/process.markdown create mode 100644 node-v0.8.14/doc/api/punycode.html create mode 100644 node-v0.8.14/doc/api/punycode.json create mode 100644 node-v0.8.14/doc/api/punycode.markdown create mode 100644 node-v0.8.14/doc/api/querystring.html create mode 100644 node-v0.8.14/doc/api/querystring.json create mode 100644 node-v0.8.14/doc/api/querystring.markdown create mode 100644 node-v0.8.14/doc/api/readline.html create mode 100644 node-v0.8.14/doc/api/readline.json create mode 100644 node-v0.8.14/doc/api/readline.markdown create mode 100644 node-v0.8.14/doc/api/repl.html create mode 100644 node-v0.8.14/doc/api/repl.json create mode 100644 node-v0.8.14/doc/api/repl.markdown create mode 100644 node-v0.8.14/doc/api/stdio.html create mode 100644 node-v0.8.14/doc/api/stdio.json create mode 100644 node-v0.8.14/doc/api/stdio.markdown create mode 100644 node-v0.8.14/doc/api/stream.html create mode 100644 node-v0.8.14/doc/api/stream.json create mode 100644 node-v0.8.14/doc/api/stream.markdown create mode 100644 node-v0.8.14/doc/api/string_decoder.html create mode 100644 node-v0.8.14/doc/api/string_decoder.json create mode 100644 node-v0.8.14/doc/api/string_decoder.markdown create mode 100644 node-v0.8.14/doc/api/synopsis.html create mode 100644 node-v0.8.14/doc/api/synopsis.json create mode 100644 node-v0.8.14/doc/api/synopsis.markdown create mode 100644 node-v0.8.14/doc/api/timers.html create mode 100644 node-v0.8.14/doc/api/timers.json create mode 100644 node-v0.8.14/doc/api/timers.markdown create mode 100644 node-v0.8.14/doc/api/tls.html create mode 100644 node-v0.8.14/doc/api/tls.json create mode 100644 node-v0.8.14/doc/api/tls.markdown create mode 100644 node-v0.8.14/doc/api/tty.html create mode 100644 node-v0.8.14/doc/api/tty.json create mode 100644 node-v0.8.14/doc/api/tty.markdown create mode 100644 node-v0.8.14/doc/api/url.html create mode 100644 node-v0.8.14/doc/api/url.json create mode 100644 node-v0.8.14/doc/api/url.markdown create mode 100644 node-v0.8.14/doc/api/util.html create mode 100644 node-v0.8.14/doc/api/util.json create mode 100644 node-v0.8.14/doc/api/util.markdown create mode 100644 node-v0.8.14/doc/api/vm.html create mode 100644 node-v0.8.14/doc/api/vm.json create mode 100644 node-v0.8.14/doc/api/vm.markdown create mode 100644 node-v0.8.14/doc/api/zlib.html create mode 100644 node-v0.8.14/doc/api/zlib.json create mode 100644 node-v0.8.14/doc/api/zlib.markdown create mode 100644 node-v0.8.14/doc/api_assets/sh.css create mode 100644 node-v0.8.14/doc/api_assets/style.css create mode 100644 node-v0.8.14/doc/blog.html create mode 100644 node-v0.8.14/doc/blog/README.md create mode 100644 node-v0.8.14/doc/blog/Uncategorized/an-easy-way-to-build-scalable-network-programs.md create mode 100644 node-v0.8.14/doc/blog/Uncategorized/development-environment.md create mode 100644 node-v0.8.14/doc/blog/Uncategorized/evolving-the-node-js-brand.md create mode 100644 node-v0.8.14/doc/blog/Uncategorized/growing-up.md create mode 100644 node-v0.8.14/doc/blog/Uncategorized/jobs-nodejs-org.md create mode 100644 node-v0.8.14/doc/blog/Uncategorized/ldapjs-a-reprise-of-ldap.md create mode 100644 node-v0.8.14/doc/blog/Uncategorized/libuv-status-report.md create mode 100644 node-v0.8.14/doc/blog/Uncategorized/node-meetup-this-thursday.md create mode 100644 node-v0.8.14/doc/blog/Uncategorized/node-office-hours-cut-short.md create mode 100644 node-v0.8.14/doc/blog/Uncategorized/office-hours.md create mode 100644 node-v0.8.14/doc/blog/Uncategorized/porting-node-to-windows-with-microsoft%e2%80%99s-help.md create mode 100644 node-v0.8.14/doc/blog/Uncategorized/profiling-node-js.md create mode 100644 node-v0.8.14/doc/blog/Uncategorized/some-new-node-projects.md create mode 100644 node-v0.8.14/doc/blog/Uncategorized/the-videos-from-node-meetup.md create mode 100644 node-v0.8.14/doc/blog/Uncategorized/trademark.md create mode 100644 node-v0.8.14/doc/blog/Uncategorized/version-0-6.md create mode 100644 node-v0.8.14/doc/blog/module/multi-server-continuous-deployment-with-fleet.md create mode 100644 node-v0.8.14/doc/blog/module/service-logging-in-json-with-bunyan.md create mode 100644 node-v0.8.14/doc/blog/npm/managing-node-js-dependencies-with-shrinkwrap.md create mode 100644 node-v0.8.14/doc/blog/npm/npm-1-0-global-vs-local-installation.md create mode 100644 node-v0.8.14/doc/blog/npm/npm-1-0-link.md create mode 100644 node-v0.8.14/doc/blog/npm/npm-1-0-released.md create mode 100644 node-v0.8.14/doc/blog/npm/npm-1-0-the-new-ls.md create mode 100644 node-v0.8.14/doc/blog/release/0.6.21.md create mode 100644 node-v0.8.14/doc/blog/release/node-v0-4-10.md create mode 100644 node-v0.8.14/doc/blog/release/node-v0-4-11.md create mode 100644 node-v0.8.14/doc/blog/release/node-v0-4-12.md create mode 100644 node-v0.8.14/doc/blog/release/node-v0-4-3.md create mode 100644 node-v0.8.14/doc/blog/release/node-v0-4-4.md create mode 100644 node-v0.8.14/doc/blog/release/node-v0-4-5.md create mode 100644 node-v0.8.14/doc/blog/release/node-v0-4-6.md create mode 100644 node-v0.8.14/doc/blog/release/node-v0-4-7.md create mode 100644 node-v0.8.14/doc/blog/release/node-v0-4-8.md create mode 100644 node-v0.8.14/doc/blog/release/node-v0-4-9.md create mode 100644 node-v0.8.14/doc/blog/release/node-v0-5-0-unstable.md create mode 100644 node-v0.8.14/doc/blog/release/node-v0-5-1.md create mode 100644 node-v0.8.14/doc/blog/release/node-v0-5-10.md create mode 100644 node-v0.8.14/doc/blog/release/node-v0-5-2.md create mode 100644 node-v0.8.14/doc/blog/release/node-v0-5-3.md create mode 100644 node-v0.8.14/doc/blog/release/node-v0-5-4.md create mode 100644 node-v0.8.14/doc/blog/release/node-v0-5-5.md create mode 100644 node-v0.8.14/doc/blog/release/node-v0-5-6.md create mode 100644 node-v0.8.14/doc/blog/release/node-v0-5-7-unstable.md create mode 100644 node-v0.8.14/doc/blog/release/node-v0-5-8.md create mode 100644 node-v0.8.14/doc/blog/release/node-v0-5-9.md create mode 100644 node-v0.8.14/doc/blog/release/node-v0-6-0.md create mode 100644 node-v0.8.14/doc/blog/release/node-v0-6-1.md create mode 100644 node-v0.8.14/doc/blog/release/node-v0-6-10.md create mode 100644 node-v0.8.14/doc/blog/release/node-v0-6-2.md create mode 100644 node-v0.8.14/doc/blog/release/node-v0-6-3.md create mode 100644 node-v0.8.14/doc/blog/release/node-v0-6-4.md create mode 100644 node-v0.8.14/doc/blog/release/node-v0-6-5.md create mode 100644 node-v0.8.14/doc/blog/release/node-v0-6-6.md create mode 100644 node-v0.8.14/doc/blog/release/node-v0-6-7.md create mode 100644 node-v0.8.14/doc/blog/release/node-v0-6-8.md create mode 100644 node-v0.8.14/doc/blog/release/node-v0-6-9.md create mode 100644 node-v0.8.14/doc/blog/release/node-v0-7-0-unstable.md create mode 100644 node-v0.8.14/doc/blog/release/node-v0-7-1.md create mode 100644 node-v0.8.14/doc/blog/release/node-v0-7-2-unstable.md create mode 100644 node-v0.8.14/doc/blog/release/node-v0-7-3.md create mode 100644 node-v0.8.14/doc/blog/release/node-v0.8.0.md create mode 100644 node-v0.8.14/doc/blog/release/node-version-0-6-19-stable.md create mode 100644 node-v0.8.14/doc/blog/release/node-version-0-7-9-unstable.md create mode 100644 node-v0.8.14/doc/blog/release/v0.6.20.md create mode 100644 node-v0.8.14/doc/blog/release/v0.8.1.md create mode 100644 node-v0.8.14/doc/blog/release/v0.8.10.md create mode 100644 node-v0.8.14/doc/blog/release/v0.8.11.md create mode 100644 node-v0.8.14/doc/blog/release/v0.8.12.md create mode 100644 node-v0.8.14/doc/blog/release/v0.8.13.md create mode 100644 node-v0.8.14/doc/blog/release/v0.8.2.md create mode 100644 node-v0.8.14/doc/blog/release/v0.8.3.md create mode 100644 node-v0.8.14/doc/blog/release/v0.8.4.md create mode 100644 node-v0.8.14/doc/blog/release/v0.8.5.md create mode 100644 node-v0.8.14/doc/blog/release/v0.8.6.md create mode 100644 node-v0.8.14/doc/blog/release/v0.8.7.md create mode 100644 node-v0.8.14/doc/blog/release/v0.8.8.md create mode 100644 node-v0.8.14/doc/blog/release/v0.8.9.md create mode 100644 node-v0.8.14/doc/blog/release/v0.9.1.md create mode 100644 node-v0.8.14/doc/blog/release/v0.9.2.md create mode 100644 node-v0.8.14/doc/blog/release/v0.9.3.md create mode 100644 node-v0.8.14/doc/blog/release/version-0-6-11-stable.md create mode 100644 node-v0.8.14/doc/blog/release/version-0-6-12-stable.md create mode 100644 node-v0.8.14/doc/blog/release/version-0-6-13-stable.md create mode 100644 node-v0.8.14/doc/blog/release/version-0-6-14-stable.md create mode 100644 node-v0.8.14/doc/blog/release/version-0-6-15-stable.md create mode 100644 node-v0.8.14/doc/blog/release/version-0-6-16-stable.md create mode 100644 node-v0.8.14/doc/blog/release/version-0-6-17-stable.md create mode 100644 node-v0.8.14/doc/blog/release/version-0-6-18-stable.md create mode 100644 node-v0.8.14/doc/blog/release/version-0-7-10-unstable.md create mode 100644 node-v0.8.14/doc/blog/release/version-0-7-11-unstable.md create mode 100644 node-v0.8.14/doc/blog/release/version-0-7-12.md create mode 100644 node-v0.8.14/doc/blog/release/version-0-7-4-unstable.md create mode 100644 node-v0.8.14/doc/blog/release/version-0-7-5-unstable.md create mode 100644 node-v0.8.14/doc/blog/release/version-0-7-6-unstable.md create mode 100644 node-v0.8.14/doc/blog/release/version-0-7-7-unstable.md create mode 100644 node-v0.8.14/doc/blog/release/version-0-7-8-unstable.md create mode 100644 node-v0.8.14/doc/blog/video/bert-belder-libuv-lxjs-2012.md create mode 100644 node-v0.8.14/doc/blog/video/bryan-cantrill-instrumenting-the-real-time-web.md create mode 100644 node-v0.8.14/doc/blog/video/welcome-to-the-node-blog.md create mode 100644 node-v0.8.14/doc/blog/vulnerability/http-server-security-vulnerability-please-upgrade-to-0-6-17.md create mode 100644 node-v0.8.14/doc/changelog-foot.html create mode 100644 node-v0.8.14/doc/changelog-head.html create mode 100644 node-v0.8.14/doc/cla.html create mode 100644 node-v0.8.14/doc/community/index.html create mode 100644 node-v0.8.14/doc/download/index.html create mode 100644 node-v0.8.14/doc/favicon.ico create mode 100644 node-v0.8.14/doc/full-white-stripe.jpg create mode 100644 node-v0.8.14/doc/index.html create mode 100644 node-v0.8.14/doc/logos/index.html create mode 100644 node-v0.8.14/doc/mac_osx_nodejs_installer_logo.png create mode 100644 node-v0.8.14/doc/node.1 create mode 100644 node-v0.8.14/doc/pipe.css create mode 100644 node-v0.8.14/doc/robots.txt create mode 100644 node-v0.8.14/doc/rss.xml create mode 100644 node-v0.8.14/doc/sh.css create mode 100644 node-v0.8.14/doc/sh_javascript.min.js create mode 100644 node-v0.8.14/doc/sh_main.js create mode 100644 node-v0.8.14/doc/sh_vim-dark.css create mode 100644 node-v0.8.14/doc/template.html create mode 100644 node-v0.8.14/doc/thin-white-stripe.jpg create mode 100644 node-v0.8.14/doc/trademark-policy.pdf create mode 100644 node-v0.8.14/doc/v0.4_announcement.html create mode 100644 node-v0.8.14/lib/_debugger.js create mode 100644 node-v0.8.14/lib/_linklist.js create mode 100644 node-v0.8.14/lib/assert.js create mode 100644 node-v0.8.14/lib/buffer.js create mode 100644 node-v0.8.14/lib/buffer_ieee754.js create mode 100644 node-v0.8.14/lib/child_process.js create mode 100644 node-v0.8.14/lib/cluster.js create mode 100644 node-v0.8.14/lib/console.js create mode 100644 node-v0.8.14/lib/constants.js create mode 100644 node-v0.8.14/lib/crypto.js create mode 100644 node-v0.8.14/lib/dgram.js create mode 100644 node-v0.8.14/lib/dns.js create mode 100644 node-v0.8.14/lib/domain.js create mode 100644 node-v0.8.14/lib/events.js create mode 100644 node-v0.8.14/lib/freelist.js create mode 100644 node-v0.8.14/lib/fs.js create mode 100644 node-v0.8.14/lib/http.js create mode 100644 node-v0.8.14/lib/https.js create mode 100644 node-v0.8.14/lib/module.js create mode 100644 node-v0.8.14/lib/net.js create mode 100644 node-v0.8.14/lib/os.js create mode 100644 node-v0.8.14/lib/path.js create mode 100644 node-v0.8.14/lib/punycode.js create mode 100644 node-v0.8.14/lib/querystring.js create mode 100644 node-v0.8.14/lib/readline.js create mode 100644 node-v0.8.14/lib/repl.js create mode 100644 node-v0.8.14/lib/stream.js create mode 100644 node-v0.8.14/lib/string_decoder.js create mode 100644 node-v0.8.14/lib/sys.js create mode 100644 node-v0.8.14/lib/timers.js create mode 100644 node-v0.8.14/lib/tls.js create mode 100644 node-v0.8.14/lib/tty.js create mode 100644 node-v0.8.14/lib/url.js create mode 100644 node-v0.8.14/lib/util.js create mode 100644 node-v0.8.14/lib/vm.js create mode 100644 node-v0.8.14/lib/zlib.js create mode 100644 node-v0.8.14/node.gyp create mode 100644 node-v0.8.14/test/addons/.gitignore create mode 100644 node-v0.8.14/test/addons/at-exit/binding.cc create mode 100644 node-v0.8.14/test/addons/at-exit/binding.gyp create mode 100644 node-v0.8.14/test/addons/at-exit/test.js create mode 100644 node-v0.8.14/test/addons/hello-world/binding.cc create mode 100644 node-v0.8.14/test/addons/hello-world/binding.gyp create mode 100644 node-v0.8.14/test/addons/hello-world/test.js create mode 100644 node-v0.8.14/test/common.js create mode 100644 node-v0.8.14/test/disabled/GH-670.js create mode 100644 node-v0.8.14/test/disabled/test-cat.js create mode 100644 node-v0.8.14/test/disabled/test-child-process-custom-fds.js create mode 100644 node-v0.8.14/test/disabled/test-child-process-uid-gid.js create mode 100644 node-v0.8.14/test/disabled/test-dgram-multicast.js create mode 100644 node-v0.8.14/test/disabled/test-dgram-unix-anon.js create mode 100644 node-v0.8.14/test/disabled/test-dgram-unix.js create mode 100644 node-v0.8.14/test/disabled/test-dns.js create mode 100644 node-v0.8.14/test/disabled/test-eio-race3.js create mode 100644 node-v0.8.14/test/disabled/test-fs-sendfile.js create mode 100644 node-v0.8.14/test/disabled/test-http-agent2.js create mode 100644 node-v0.8.14/test/disabled/test-http-big-proxy-responses.js create mode 100644 node-v0.8.14/test/disabled/test-http-default-port.js create mode 100644 node-v0.8.14/test/disabled/test-http-head-request.js create mode 100644 node-v0.8.14/test/disabled/test-http-stress.js create mode 100644 node-v0.8.14/test/disabled/test-http-tls.js create mode 100644 node-v0.8.14/test/disabled/test-https-loop-to-google.js create mode 100644 node-v0.8.14/test/disabled/test-idle-watcher.js create mode 100644 node-v0.8.14/test/disabled/test-net-fd-passing.js create mode 100644 node-v0.8.14/test/disabled/test-net-tls-pummel.js create mode 100644 node-v0.8.14/test/disabled/test-net-tls.js create mode 100644 node-v0.8.14/test/disabled/test-process-title.js create mode 100644 node-v0.8.14/test/disabled/test-readline.js create mode 100644 node-v0.8.14/test/disabled/test-remote-module-loading.js create mode 100644 node-v0.8.14/test/disabled/test-sendfd.js create mode 100644 node-v0.8.14/test/disabled/test-setuidgid.js create mode 100644 node-v0.8.14/test/disabled/test-tls-large-push.js create mode 100644 node-v0.8.14/test/disabled/test-tls-server.js create mode 100644 node-v0.8.14/test/disabled/test-tty-stdio.js create mode 100644 node-v0.8.14/test/disabled/tls-client.js create mode 100644 node-v0.8.14/test/disabled/tls_client.js create mode 100644 node-v0.8.14/test/disabled/tls_server.js create mode 100644 node-v0.8.14/test/fixtures/GH-1899-output.js create mode 100644 node-v0.8.14/test/fixtures/GH-892-request.js create mode 100644 node-v0.8.14/test/fixtures/a.js create mode 100644 node-v0.8.14/test/fixtures/a1.js create mode 100644 node-v0.8.14/test/fixtures/agent.crt create mode 100644 node-v0.8.14/test/fixtures/agent.key create mode 100644 node-v0.8.14/test/fixtures/alice.crt create mode 100644 node-v0.8.14/test/fixtures/b/c.js create mode 100644 node-v0.8.14/test/fixtures/b/d.js create mode 100644 node-v0.8.14/test/fixtures/b/package/index.js create mode 100644 node-v0.8.14/test/fixtures/breakpoints.js create mode 100644 node-v0.8.14/test/fixtures/breakpoints_utf8.js create mode 100644 node-v0.8.14/test/fixtures/catch-stdout-error.js create mode 100644 node-v0.8.14/test/fixtures/cert.pem create mode 100644 node-v0.8.14/test/fixtures/child-process-message-and-exit.js create mode 100644 node-v0.8.14/test/fixtures/child-process-persistent.js create mode 100644 node-v0.8.14/test/fixtures/child-process-spawn-node.js create mode 100644 node-v0.8.14/test/fixtures/child_process_should_emit_error.js create mode 100644 node-v0.8.14/test/fixtures/create-file.js create mode 100644 node-v0.8.14/test/fixtures/cycles/folder/foo.js create mode 100644 node-v0.8.14/test/fixtures/cycles/root.js create mode 100644 node-v0.8.14/test/fixtures/deprecated.js create mode 100644 node-v0.8.14/test/fixtures/destroy-stdin.js create mode 100644 node-v0.8.14/test/fixtures/echo.js create mode 100644 node-v0.8.14/test/fixtures/elipses.txt create mode 100644 node-v0.8.14/test/fixtures/empty.js create mode 100644 node-v0.8.14/test/fixtures/empty.txt create mode 100644 node-v0.8.14/test/fixtures/empty/.gitkeep create mode 100644 node-v0.8.14/test/fixtures/exit.js create mode 100644 node-v0.8.14/test/fixtures/fixture.ini create mode 100644 node-v0.8.14/test/fixtures/foafssl.crt create mode 100644 node-v0.8.14/test/fixtures/foafssl.key create mode 100644 node-v0.8.14/test/fixtures/foo create mode 100644 node-v0.8.14/test/fixtures/fork2.js create mode 100644 node-v0.8.14/test/fixtures/global/plain.js create mode 100644 node-v0.8.14/test/fixtures/invalid.json create mode 100644 node-v0.8.14/test/fixtures/keys/Makefile create mode 100644 node-v0.8.14/test/fixtures/keys/agent1-cert.pem create mode 100644 node-v0.8.14/test/fixtures/keys/agent1-csr.pem create mode 100644 node-v0.8.14/test/fixtures/keys/agent1-key.pem create mode 100644 node-v0.8.14/test/fixtures/keys/agent1.cnf create mode 100644 node-v0.8.14/test/fixtures/keys/agent2-cert.pem create mode 100644 node-v0.8.14/test/fixtures/keys/agent2-csr.pem create mode 100644 node-v0.8.14/test/fixtures/keys/agent2-key.pem create mode 100644 node-v0.8.14/test/fixtures/keys/agent2.cnf create mode 100644 node-v0.8.14/test/fixtures/keys/agent3-cert.pem create mode 100644 node-v0.8.14/test/fixtures/keys/agent3-csr.pem create mode 100644 node-v0.8.14/test/fixtures/keys/agent3-key.pem create mode 100644 node-v0.8.14/test/fixtures/keys/agent3.cnf create mode 100644 node-v0.8.14/test/fixtures/keys/agent4-cert.pem create mode 100644 node-v0.8.14/test/fixtures/keys/agent4-csr.pem create mode 100644 node-v0.8.14/test/fixtures/keys/agent4-key.pem create mode 100644 node-v0.8.14/test/fixtures/keys/agent4.cnf create mode 100644 node-v0.8.14/test/fixtures/keys/ca1-cert.pem create mode 100644 node-v0.8.14/test/fixtures/keys/ca1-cert.srl create mode 100644 node-v0.8.14/test/fixtures/keys/ca1-key.pem create mode 100644 node-v0.8.14/test/fixtures/keys/ca1.cnf create mode 100644 node-v0.8.14/test/fixtures/keys/ca2-cert.pem create mode 100644 node-v0.8.14/test/fixtures/keys/ca2-cert.srl create mode 100644 node-v0.8.14/test/fixtures/keys/ca2-crl.pem create mode 100644 node-v0.8.14/test/fixtures/keys/ca2-database.txt create mode 100644 node-v0.8.14/test/fixtures/keys/ca2-key.pem create mode 100644 node-v0.8.14/test/fixtures/keys/ca2-serial create mode 100644 node-v0.8.14/test/fixtures/keys/ca2.cnf create mode 100644 node-v0.8.14/test/fixtures/module-load-order/file1 create mode 100644 node-v0.8.14/test/fixtures/module-load-order/file1.js create mode 100644 node-v0.8.14/test/fixtures/module-load-order/file1.node create mode 100644 node-v0.8.14/test/fixtures/module-load-order/file1.reg create mode 100644 node-v0.8.14/test/fixtures/module-load-order/file1.reg2 create mode 100644 node-v0.8.14/test/fixtures/module-load-order/file2.js create mode 100644 node-v0.8.14/test/fixtures/module-load-order/file2.node create mode 100644 node-v0.8.14/test/fixtures/module-load-order/file2.reg create mode 100644 node-v0.8.14/test/fixtures/module-load-order/file2.reg2 create mode 100644 node-v0.8.14/test/fixtures/module-load-order/file2/index.js create mode 100644 node-v0.8.14/test/fixtures/module-load-order/file2/index.node create mode 100644 node-v0.8.14/test/fixtures/module-load-order/file2/index.reg create mode 100644 node-v0.8.14/test/fixtures/module-load-order/file2/index.reg2 create mode 100644 node-v0.8.14/test/fixtures/module-load-order/file3.node create mode 100644 node-v0.8.14/test/fixtures/module-load-order/file3.reg create mode 100644 node-v0.8.14/test/fixtures/module-load-order/file3.reg2 create mode 100644 node-v0.8.14/test/fixtures/module-load-order/file3/index.js create mode 100644 node-v0.8.14/test/fixtures/module-load-order/file3/index.node create mode 100644 node-v0.8.14/test/fixtures/module-load-order/file3/index.reg create mode 100644 node-v0.8.14/test/fixtures/module-load-order/file3/index.reg2 create mode 100644 node-v0.8.14/test/fixtures/module-load-order/file4.reg create mode 100644 node-v0.8.14/test/fixtures/module-load-order/file4.reg2 create mode 100644 node-v0.8.14/test/fixtures/module-load-order/file4/index.js create mode 100644 node-v0.8.14/test/fixtures/module-load-order/file4/index.node create mode 100644 node-v0.8.14/test/fixtures/module-load-order/file4/index.reg create mode 100644 node-v0.8.14/test/fixtures/module-load-order/file4/index.reg2 create mode 100644 node-v0.8.14/test/fixtures/module-load-order/file5.reg2 create mode 100644 node-v0.8.14/test/fixtures/module-load-order/file5/index.js create mode 100644 node-v0.8.14/test/fixtures/module-load-order/file5/index.node create mode 100644 node-v0.8.14/test/fixtures/module-load-order/file5/index.reg create mode 100644 node-v0.8.14/test/fixtures/module-load-order/file5/index.reg2 create mode 100644 node-v0.8.14/test/fixtures/module-load-order/file6/index.js create mode 100644 node-v0.8.14/test/fixtures/module-load-order/file6/index.node create mode 100644 node-v0.8.14/test/fixtures/module-load-order/file6/index.reg create mode 100644 node-v0.8.14/test/fixtures/module-load-order/file6/index.reg2 create mode 100644 node-v0.8.14/test/fixtures/module-load-order/file7/index.node create mode 100644 node-v0.8.14/test/fixtures/module-load-order/file7/index.reg create mode 100644 node-v0.8.14/test/fixtures/module-load-order/file7/index.reg2 create mode 100644 node-v0.8.14/test/fixtures/module-load-order/file8/index.reg create mode 100644 node-v0.8.14/test/fixtures/module-load-order/file8/index.reg2 create mode 100644 node-v0.8.14/test/fixtures/module-load-order/file9/index.reg2 create mode 100644 node-v0.8.14/test/fixtures/module-loading-error.node create mode 100644 node-v0.8.14/test/fixtures/module-require/child/index.js create mode 100644 node-v0.8.14/test/fixtures/module-require/parent/index.js create mode 100644 node-v0.8.14/test/fixtures/msca.pem create mode 100644 node-v0.8.14/test/fixtures/multi-alice.crt create mode 100644 node-v0.8.14/test/fixtures/nested-index/one/hello.js create mode 100644 node-v0.8.14/test/fixtures/nested-index/one/index.js create mode 100644 node-v0.8.14/test/fixtures/nested-index/three.js create mode 100644 node-v0.8.14/test/fixtures/nested-index/three/index.js create mode 100644 node-v0.8.14/test/fixtures/nested-index/two/hello.js create mode 100644 node-v0.8.14/test/fixtures/nested-index/two/index.js create mode 100644 node-v0.8.14/test/fixtures/net-fd-passing-receiver.js create mode 100644 node-v0.8.14/test/fixtures/not-main-module.js create mode 100644 node-v0.8.14/test/fixtures/packages/main-index/package-main-module/index.js create mode 100644 node-v0.8.14/test/fixtures/packages/main-index/package.json create mode 100644 node-v0.8.14/test/fixtures/packages/main/package-main-module.js create mode 100644 node-v0.8.14/test/fixtures/packages/main/package.json create mode 100644 node-v0.8.14/test/fixtures/parent-process-nonpersistent.js create mode 100644 node-v0.8.14/test/fixtures/pass-cert.pem create mode 100644 node-v0.8.14/test/fixtures/pass-csr.pem create mode 100644 node-v0.8.14/test/fixtures/pass-key.pem create mode 100644 node-v0.8.14/test/fixtures/person.jpg create mode 100644 node-v0.8.14/test/fixtures/person.jpg.gz create mode 100644 node-v0.8.14/test/fixtures/print-10-lines.js create mode 100644 node-v0.8.14/test/fixtures/print-chars-from-buffer.js create mode 100644 node-v0.8.14/test/fixtures/print-chars.js create mode 100644 node-v0.8.14/test/fixtures/readdir/are create mode 100644 node-v0.8.14/test/fixtures/readdir/dir/empty create mode 100644 node-v0.8.14/test/fixtures/readdir/empty create mode 100644 node-v0.8.14/test/fixtures/readdir/files create mode 100644 node-v0.8.14/test/fixtures/readdir/for create mode 100644 node-v0.8.14/test/fixtures/readdir/just create mode 100644 node-v0.8.14/test/fixtures/readdir/testing.js create mode 100644 node-v0.8.14/test/fixtures/readdir/these create mode 100644 node-v0.8.14/test/fixtures/recvfd.js create mode 100644 node-v0.8.14/test/fixtures/registerExt.hello.world create mode 100644 node-v0.8.14/test/fixtures/registerExt.test create mode 100644 node-v0.8.14/test/fixtures/registerExt2.test create mode 100644 node-v0.8.14/test/fixtures/sample.png create mode 100644 node-v0.8.14/test/fixtures/semicolon.js create mode 100644 node-v0.8.14/test/fixtures/should_exit.js create mode 100644 node-v0.8.14/test/fixtures/stdio-filter.js create mode 100644 node-v0.8.14/test/fixtures/test-init-index/index.js create mode 100644 node-v0.8.14/test/fixtures/test-init-native/fs.js create mode 100644 node-v0.8.14/test/fixtures/test-regress-GH-4015.js create mode 100644 node-v0.8.14/test/fixtures/test_ca.pem create mode 100644 node-v0.8.14/test/fixtures/test_cert.pem create mode 100644 node-v0.8.14/test/fixtures/test_cert.pfx create mode 100644 node-v0.8.14/test/fixtures/test_dsa_params.pem create mode 100644 node-v0.8.14/test/fixtures/test_dsa_privkey.pem create mode 100644 node-v0.8.14/test/fixtures/test_dsa_pubkey.pem create mode 100644 node-v0.8.14/test/fixtures/test_key.pem create mode 100644 node-v0.8.14/test/fixtures/test_rsa_privkey.pem create mode 100644 node-v0.8.14/test/fixtures/test_rsa_privkey_2.pem create mode 100644 node-v0.8.14/test/fixtures/test_rsa_pubkey.pem create mode 100644 node-v0.8.14/test/fixtures/test_rsa_pubkey_2.pem create mode 100644 node-v0.8.14/test/fixtures/throws_error.js create mode 100644 node-v0.8.14/test/fixtures/throws_error1.js create mode 100644 node-v0.8.14/test/fixtures/throws_error2.js create mode 100644 node-v0.8.14/test/fixtures/throws_error3.js create mode 100644 node-v0.8.14/test/fixtures/utf8-bom.js create mode 100644 node-v0.8.14/test/fixtures/utf8-bom.json create mode 100644 node-v0.8.14/test/fixtures/x.txt create mode 100644 node-v0.8.14/test/gc/test-http-client-connaborted.js create mode 100644 node-v0.8.14/test/gc/test-http-client-onerror.js create mode 100644 node-v0.8.14/test/gc/test-http-client-timeout.js create mode 100644 node-v0.8.14/test/gc/test-http-client.js create mode 100644 node-v0.8.14/test/gc/test-net-timeout.js create mode 100644 node-v0.8.14/test/gc/testcfg.py create mode 100644 node-v0.8.14/test/internet/internet.status create mode 100644 node-v0.8.14/test/internet/test-dns.js create mode 100644 node-v0.8.14/test/internet/testcfg.py create mode 100644 node-v0.8.14/test/message/2100bytes.js create mode 100644 node-v0.8.14/test/message/2100bytes.out create mode 100644 node-v0.8.14/test/message/eval_messages.js create mode 100644 node-v0.8.14/test/message/eval_messages.out create mode 100644 node-v0.8.14/test/message/hello_world.js create mode 100644 node-v0.8.14/test/message/hello_world.out create mode 100644 node-v0.8.14/test/message/stack_overflow.js create mode 100644 node-v0.8.14/test/message/stack_overflow.out create mode 100644 node-v0.8.14/test/message/stdin_messages.js create mode 100644 node-v0.8.14/test/message/stdin_messages.out create mode 100644 node-v0.8.14/test/message/testcfg.py create mode 100644 node-v0.8.14/test/message/throw_custom_error.js create mode 100644 node-v0.8.14/test/message/throw_custom_error.out create mode 100644 node-v0.8.14/test/message/throw_in_line_with_tabs.js create mode 100644 node-v0.8.14/test/message/throw_in_line_with_tabs.out create mode 100644 node-v0.8.14/test/message/throw_non_error.js create mode 100644 node-v0.8.14/test/message/throw_non_error.out create mode 100644 node-v0.8.14/test/message/undefined_reference_in_new_context.js create mode 100644 node-v0.8.14/test/message/undefined_reference_in_new_context.out create mode 100644 node-v0.8.14/test/pummel/pummel.status create mode 100644 node-v0.8.14/test/pummel/test-buffer-big.js create mode 100644 node-v0.8.14/test/pummel/test-child-process-spawn-loop.js create mode 100644 node-v0.8.14/test/pummel/test-crypto-dh.js create mode 100644 node-v0.8.14/test/pummel/test-debugger-debug-brk.js create mode 100644 node-v0.8.14/test/pummel/test-dh-regr.js create mode 100644 node-v0.8.14/test/pummel/test-exec.js create mode 100644 node-v0.8.14/test/pummel/test-fs-largefile.js create mode 100644 node-v0.8.14/test/pummel/test-fs-watch-file-slow.js create mode 100644 node-v0.8.14/test/pummel/test-fs-watch-file.js create mode 100644 node-v0.8.14/test/pummel/test-http-client-reconnect-bug.js create mode 100644 node-v0.8.14/test/pummel/test-http-upload-timeout.js create mode 100644 node-v0.8.14/test/pummel/test-https-ci-reneg-attack.js create mode 100644 node-v0.8.14/test/pummel/test-https-large-response.js create mode 100644 node-v0.8.14/test/pummel/test-keep-alive.js create mode 100644 node-v0.8.14/test/pummel/test-net-connect-econnrefused.js create mode 100644 node-v0.8.14/test/pummel/test-net-many-clients.js create mode 100644 node-v0.8.14/test/pummel/test-net-pause.js create mode 100644 node-v0.8.14/test/pummel/test-net-pingpong-delay.js create mode 100644 node-v0.8.14/test/pummel/test-net-pingpong.js create mode 100644 node-v0.8.14/test/pummel/test-net-throttle.js create mode 100644 node-v0.8.14/test/pummel/test-net-timeout.js create mode 100644 node-v0.8.14/test/pummel/test-net-timeout2.js create mode 100644 node-v0.8.14/test/pummel/test-net-write-callbacks.js create mode 100644 node-v0.8.14/test/pummel/test-next-tick-loops-quick.js create mode 100644 node-v0.8.14/test/pummel/test-process-hrtime.js create mode 100644 node-v0.8.14/test/pummel/test-process-uptime.js create mode 100644 node-v0.8.14/test/pummel/test-regress-GH-814.js create mode 100644 node-v0.8.14/test/pummel/test-regress-GH-814_2.js create mode 100644 node-v0.8.14/test/pummel/test-regress-GH-892.js create mode 100644 node-v0.8.14/test/pummel/test-timer-wrap.js create mode 100644 node-v0.8.14/test/pummel/test-timer-wrap2.js create mode 100644 node-v0.8.14/test/pummel/test-timers.js create mode 100644 node-v0.8.14/test/pummel/test-tls-ci-reneg-attack.js create mode 100644 node-v0.8.14/test/pummel/test-tls-throttle.js create mode 100644 node-v0.8.14/test/pummel/test-vm-memleak.js create mode 100644 node-v0.8.14/test/pummel/test-watch-file.js create mode 100644 node-v0.8.14/test/pummel/testcfg.py create mode 100644 node-v0.8.14/test/simple/path.js create mode 100644 node-v0.8.14/test/simple/simple.status create mode 100644 node-v0.8.14/test/simple/test-assert.js create mode 100644 node-v0.8.14/test/simple/test-bad-unicode.js create mode 100644 node-v0.8.14/test/simple/test-buffer-concat.js create mode 100644 node-v0.8.14/test/simple/test-buffer-regress-GH-2659.js create mode 100644 node-v0.8.14/test/simple/test-buffer.js create mode 100644 node-v0.8.14/test/simple/test-c-ares.js create mode 100644 node-v0.8.14/test/simple/test-chdir.js create mode 100644 node-v0.8.14/test/simple/test-child-process-buffering.js create mode 100644 node-v0.8.14/test/simple/test-child-process-customfd-bounded.js create mode 100644 node-v0.8.14/test/simple/test-child-process-cwd.js create mode 100644 node-v0.8.14/test/simple/test-child-process-detached.js create mode 100644 node-v0.8.14/test/simple/test-child-process-disconnect.js create mode 100644 node-v0.8.14/test/simple/test-child-process-double-pipe.js create mode 100644 node-v0.8.14/test/simple/test-child-process-env.js create mode 100644 node-v0.8.14/test/simple/test-child-process-exec-cwd.js create mode 100644 node-v0.8.14/test/simple/test-child-process-exec-env.js create mode 100644 node-v0.8.14/test/simple/test-child-process-exit-code.js create mode 100644 node-v0.8.14/test/simple/test-child-process-fork-and-spawn.js create mode 100644 node-v0.8.14/test/simple/test-child-process-fork-close.js create mode 100644 node-v0.8.14/test/simple/test-child-process-fork-exec-argv.js create mode 100644 node-v0.8.14/test/simple/test-child-process-fork-net.js create mode 100644 node-v0.8.14/test/simple/test-child-process-fork-net2.js create mode 100644 node-v0.8.14/test/simple/test-child-process-fork.js create mode 100644 node-v0.8.14/test/simple/test-child-process-fork2.js create mode 100644 node-v0.8.14/test/simple/test-child-process-internal.js create mode 100644 node-v0.8.14/test/simple/test-child-process-ipc.js create mode 100644 node-v0.8.14/test/simple/test-child-process-kill-throw.js create mode 100644 node-v0.8.14/test/simple/test-child-process-kill.js create mode 100644 node-v0.8.14/test/simple/test-child-process-set-blocking.js create mode 100644 node-v0.8.14/test/simple/test-child-process-silent.js create mode 100644 node-v0.8.14/test/simple/test-child-process-stdin.js create mode 100644 node-v0.8.14/test/simple/test-child-process-stdio.js create mode 100644 node-v0.8.14/test/simple/test-child-process-stdout-flush.js create mode 100644 node-v0.8.14/test/simple/test-cli-eval.js create mode 100644 node-v0.8.14/test/simple/test-cluster-basic.js create mode 100644 node-v0.8.14/test/simple/test-cluster-disconnect.js create mode 100644 node-v0.8.14/test/simple/test-cluster-fork-env.js create mode 100644 node-v0.8.14/test/simple/test-cluster-http-pipe.js create mode 100644 node-v0.8.14/test/simple/test-cluster-master-error.js create mode 100644 node-v0.8.14/test/simple/test-cluster-master-kill.js create mode 100644 node-v0.8.14/test/simple/test-cluster-message.js create mode 100644 node-v0.8.14/test/simple/test-cluster-net-listen.js create mode 100644 node-v0.8.14/test/simple/test-cluster-setup-master.js create mode 100644 node-v0.8.14/test/simple/test-cluster-uncaught-exception.js create mode 100644 node-v0.8.14/test/simple/test-cluster-worker-death.js create mode 100644 node-v0.8.14/test/simple/test-cluster-worker-disconnect.js create mode 100644 node-v0.8.14/test/simple/test-cluster-worker-exit.js create mode 100644 node-v0.8.14/test/simple/test-cluster-worker-kill.js create mode 100644 node-v0.8.14/test/simple/test-console-not-call-toString.js create mode 100644 node-v0.8.14/test/simple/test-console.js create mode 100644 node-v0.8.14/test/simple/test-crypto-ecb.js create mode 100644 node-v0.8.14/test/simple/test-crypto-padding.js create mode 100644 node-v0.8.14/test/simple/test-crypto-random.js create mode 100644 node-v0.8.14/test/simple/test-crypto.js create mode 100644 node-v0.8.14/test/simple/test-debugger-client.js create mode 100644 node-v0.8.14/test/simple/test-debugger-repl-utf8.js create mode 100644 node-v0.8.14/test/simple/test-debugger-repl.js create mode 100644 node-v0.8.14/test/simple/test-delayed-require.js create mode 100644 node-v0.8.14/test/simple/test-deprecation-flags.js create mode 100644 node-v0.8.14/test/simple/test-dgram-address.js create mode 100644 node-v0.8.14/test/simple/test-dgram-bind.js create mode 100644 node-v0.8.14/test/simple/test-dgram-broadcast-multi-process.js create mode 100644 node-v0.8.14/test/simple/test-dgram-close.js create mode 100644 node-v0.8.14/test/simple/test-dgram-multicast-multi-process.js create mode 100644 node-v0.8.14/test/simple/test-dgram-multicast-setTTL.js create mode 100644 node-v0.8.14/test/simple/test-dgram-oob-buffer.js create mode 100644 node-v0.8.14/test/simple/test-dgram-pingpong.js create mode 100644 node-v0.8.14/test/simple/test-dgram-ref.js create mode 100644 node-v0.8.14/test/simple/test-dgram-send-error.js create mode 100644 node-v0.8.14/test/simple/test-dgram-udp4.js create mode 100644 node-v0.8.14/test/simple/test-domain-crypto.js create mode 100644 node-v0.8.14/test/simple/test-domain-exit-dispose.js create mode 100644 node-v0.8.14/test/simple/test-domain-http-server.js create mode 100644 node-v0.8.14/test/simple/test-domain-implicit-fs.js create mode 100644 node-v0.8.14/test/simple/test-domain-multi.js create mode 100644 node-v0.8.14/test/simple/test-domain-stack.js create mode 100644 node-v0.8.14/test/simple/test-domain.js create mode 100644 node-v0.8.14/test/simple/test-eio-limit.js create mode 100644 node-v0.8.14/test/simple/test-eio-race.js create mode 100644 node-v0.8.14/test/simple/test-eio-race2.js create mode 100644 node-v0.8.14/test/simple/test-eio-race4.js create mode 100644 node-v0.8.14/test/simple/test-error-reporting.js create mode 100644 node-v0.8.14/test/simple/test-eval-require.js create mode 100644 node-v0.8.14/test/simple/test-eval.js create mode 100644 node-v0.8.14/test/simple/test-event-emitter-add-listeners.js create mode 100644 node-v0.8.14/test/simple/test-event-emitter-check-listener-leaks.js create mode 100644 node-v0.8.14/test/simple/test-event-emitter-max-listeners.js create mode 100644 node-v0.8.14/test/simple/test-event-emitter-modify-in-emit.js create mode 100644 node-v0.8.14/test/simple/test-event-emitter-num-args.js create mode 100644 node-v0.8.14/test/simple/test-event-emitter-once.js create mode 100644 node-v0.8.14/test/simple/test-event-emitter-remove-all-listeners.js create mode 100644 node-v0.8.14/test/simple/test-event-emitter-remove-listeners.js create mode 100644 node-v0.8.14/test/simple/test-event-emitter-subclass.js create mode 100644 node-v0.8.14/test/simple/test-exception-handler.js create mode 100644 node-v0.8.14/test/simple/test-exception-handler2.js create mode 100644 node-v0.8.14/test/simple/test-exec-max-buffer.js create mode 100644 node-v0.8.14/test/simple/test-executable-path.js create mode 100644 node-v0.8.14/test/simple/test-file-read-noexist.js create mode 100644 node-v0.8.14/test/simple/test-file-write-stream.js create mode 100644 node-v0.8.14/test/simple/test-file-write-stream2.js create mode 100644 node-v0.8.14/test/simple/test-file-write-stream3.js create mode 100644 node-v0.8.14/test/simple/test-force-repl.js create mode 100644 node-v0.8.14/test/simple/test-fs-append-file-sync.js create mode 100644 node-v0.8.14/test/simple/test-fs-append-file.js create mode 100644 node-v0.8.14/test/simple/test-fs-chmod.js create mode 100644 node-v0.8.14/test/simple/test-fs-empty-readStream.js create mode 100644 node-v0.8.14/test/simple/test-fs-error-messages.js create mode 100644 node-v0.8.14/test/simple/test-fs-exists.js create mode 100644 node-v0.8.14/test/simple/test-fs-fsync.js create mode 100644 node-v0.8.14/test/simple/test-fs-long-path.js create mode 100644 node-v0.8.14/test/simple/test-fs-mkdir.js create mode 100644 node-v0.8.14/test/simple/test-fs-non-number-arguments-throw.js create mode 100644 node-v0.8.14/test/simple/test-fs-open-flags.js create mode 100644 node-v0.8.14/test/simple/test-fs-open.js create mode 100644 node-v0.8.14/test/simple/test-fs-read-buffer.js create mode 100644 node-v0.8.14/test/simple/test-fs-read-file-sync-hostname.js create mode 100644 node-v0.8.14/test/simple/test-fs-read-file-sync.js create mode 100644 node-v0.8.14/test/simple/test-fs-read-stream-fd.js create mode 100644 node-v0.8.14/test/simple/test-fs-read-stream-resume.js create mode 100644 node-v0.8.14/test/simple/test-fs-read-stream.js create mode 100644 node-v0.8.14/test/simple/test-fs-read.js create mode 100644 node-v0.8.14/test/simple/test-fs-readfile-empty.js create mode 100644 node-v0.8.14/test/simple/test-fs-readfile-pipe.js create mode 100644 node-v0.8.14/test/simple/test-fs-readfile-unlink.js create mode 100644 node-v0.8.14/test/simple/test-fs-readfile-zero-byte-liar.js create mode 100644 node-v0.8.14/test/simple/test-fs-realpath.js create mode 100644 node-v0.8.14/test/simple/test-fs-sir-writes-alot.js create mode 100644 node-v0.8.14/test/simple/test-fs-stat.js create mode 100644 node-v0.8.14/test/simple/test-fs-stream-double-close.js create mode 100644 node-v0.8.14/test/simple/test-fs-symlink-dir-junction.js create mode 100644 node-v0.8.14/test/simple/test-fs-symlink.js create mode 100644 node-v0.8.14/test/simple/test-fs-sync-fd-leak.js create mode 100644 node-v0.8.14/test/simple/test-fs-utimes.js create mode 100644 node-v0.8.14/test/simple/test-fs-watch.js create mode 100644 node-v0.8.14/test/simple/test-fs-write-buffer.js create mode 100644 node-v0.8.14/test/simple/test-fs-write-file-buffer.js create mode 100644 node-v0.8.14/test/simple/test-fs-write-file.js create mode 100644 node-v0.8.14/test/simple/test-fs-write-stream-change-open.js create mode 100644 node-v0.8.14/test/simple/test-fs-write-stream-end.js create mode 100644 node-v0.8.14/test/simple/test-fs-write-stream.js create mode 100644 node-v0.8.14/test/simple/test-fs-write-sync.js create mode 100644 node-v0.8.14/test/simple/test-fs-write.js create mode 100644 node-v0.8.14/test/simple/test-global.js create mode 100644 node-v0.8.14/test/simple/test-http-1.0-keep-alive.js create mode 100644 node-v0.8.14/test/simple/test-http-1.0.js create mode 100644 node-v0.8.14/test/simple/test-http-304.js create mode 100644 node-v0.8.14/test/simple/test-http-abort-before-end.js create mode 100644 node-v0.8.14/test/simple/test-http-abort-client.js create mode 100644 node-v0.8.14/test/simple/test-http-after-connect.js create mode 100644 node-v0.8.14/test/simple/test-http-agent.js create mode 100644 node-v0.8.14/test/simple/test-http-allow-req-after-204-res.js create mode 100644 node-v0.8.14/test/simple/test-http-bind-twice.js create mode 100644 node-v0.8.14/test/simple/test-http-blank-header.js create mode 100644 node-v0.8.14/test/simple/test-http-buffer-sanity.js create mode 100644 node-v0.8.14/test/simple/test-http-chunked.js create mode 100644 node-v0.8.14/test/simple/test-http-client-abort.js create mode 100644 node-v0.8.14/test/simple/test-http-client-abort2.js create mode 100644 node-v0.8.14/test/simple/test-http-client-agent.js create mode 100644 node-v0.8.14/test/simple/test-http-client-get-url.js create mode 100644 node-v0.8.14/test/simple/test-http-client-parse-error.js create mode 100644 node-v0.8.14/test/simple/test-http-client-pipe-end.js create mode 100644 node-v0.8.14/test/simple/test-http-client-race-2.js create mode 100644 node-v0.8.14/test/simple/test-http-client-race.js create mode 100644 node-v0.8.14/test/simple/test-http-client-response-domain.js create mode 100644 node-v0.8.14/test/simple/test-http-client-timeout-agent.js create mode 100644 node-v0.8.14/test/simple/test-http-client-timeout-with-data.js create mode 100644 node-v0.8.14/test/simple/test-http-client-timeout.js create mode 100644 node-v0.8.14/test/simple/test-http-client-upload-buf.js create mode 100644 node-v0.8.14/test/simple/test-http-client-upload.js create mode 100644 node-v0.8.14/test/simple/test-http-conn-reset.js create mode 100644 node-v0.8.14/test/simple/test-http-connect.js create mode 100644 node-v0.8.14/test/simple/test-http-contentLength0.js create mode 100644 node-v0.8.14/test/simple/test-http-curl-chunk-problem.js create mode 100644 node-v0.8.14/test/simple/test-http-date-header.js create mode 100644 node-v0.8.14/test/simple/test-http-default-encoding.js create mode 100644 node-v0.8.14/test/simple/test-http-dns-error.js create mode 100644 node-v0.8.14/test/simple/test-http-dns-fail.js create mode 100644 node-v0.8.14/test/simple/test-http-eof-on-connect.js create mode 100644 node-v0.8.14/test/simple/test-http-exceptions.js create mode 100644 node-v0.8.14/test/simple/test-http-expect-continue.js create mode 100644 node-v0.8.14/test/simple/test-http-extra-response.js create mode 100644 node-v0.8.14/test/simple/test-http-full-response.js create mode 100644 node-v0.8.14/test/simple/test-http-get-pipeline-problem.js create mode 100644 node-v0.8.14/test/simple/test-http-head-request.js create mode 100644 node-v0.8.14/test/simple/test-http-head-response-has-no-body-end.js create mode 100644 node-v0.8.14/test/simple/test-http-head-response-has-no-body.js create mode 100644 node-v0.8.14/test/simple/test-http-header-read.js create mode 100644 node-v0.8.14/test/simple/test-http-host-headers.js create mode 100644 node-v0.8.14/test/simple/test-http-keep-alive-close-on-header.js create mode 100644 node-v0.8.14/test/simple/test-http-keep-alive.js create mode 100644 node-v0.8.14/test/simple/test-http-legacy.js create mode 100644 node-v0.8.14/test/simple/test-http-localaddress-bind-error.js create mode 100644 node-v0.8.14/test/simple/test-http-localaddress.js create mode 100644 node-v0.8.14/test/simple/test-http-malformed-request.js create mode 100644 node-v0.8.14/test/simple/test-http-many-keep-alive-connections.js create mode 100644 node-v0.8.14/test/simple/test-http-max-headers-count.js create mode 100644 node-v0.8.14/test/simple/test-http-multi-line-headers.js create mode 100644 node-v0.8.14/test/simple/test-http-mutable-headers.js create mode 100644 node-v0.8.14/test/simple/test-http-no-content-length.js create mode 100644 node-v0.8.14/test/simple/test-http-parser-bad-ref.js create mode 100644 node-v0.8.14/test/simple/test-http-parser-free.js create mode 100644 node-v0.8.14/test/simple/test-http-parser.js create mode 100644 node-v0.8.14/test/simple/test-http-pause-resume-one-end.js create mode 100644 node-v0.8.14/test/simple/test-http-pause.js create mode 100644 node-v0.8.14/test/simple/test-http-pipe-fs.js create mode 100644 node-v0.8.14/test/simple/test-http-proxy.js create mode 100644 node-v0.8.14/test/simple/test-http-request-end-twice.js create mode 100644 node-v0.8.14/test/simple/test-http-request-end.js create mode 100644 node-v0.8.14/test/simple/test-http-request-methods.js create mode 100644 node-v0.8.14/test/simple/test-http-res-write-end-dont-take-array.js create mode 100644 node-v0.8.14/test/simple/test-http-response-close.js create mode 100644 node-v0.8.14/test/simple/test-http-response-no-headers.js create mode 100644 node-v0.8.14/test/simple/test-http-response-readable.js create mode 100644 node-v0.8.14/test/simple/test-http-server-multiheaders.js create mode 100644 node-v0.8.14/test/simple/test-http-server.js create mode 100644 node-v0.8.14/test/simple/test-http-set-cookies.js create mode 100644 node-v0.8.14/test/simple/test-http-set-timeout.js create mode 100644 node-v0.8.14/test/simple/test-http-set-trailers.js create mode 100644 node-v0.8.14/test/simple/test-http-should-keep-alive.js create mode 100644 node-v0.8.14/test/simple/test-http-status-code.js create mode 100644 node-v0.8.14/test/simple/test-http-timeout.js create mode 100644 node-v0.8.14/test/simple/test-http-unix-socket.js create mode 100644 node-v0.8.14/test/simple/test-http-upgrade-agent.js create mode 100644 node-v0.8.14/test/simple/test-http-upgrade-client.js create mode 100644 node-v0.8.14/test/simple/test-http-upgrade-client2.js create mode 100644 node-v0.8.14/test/simple/test-http-upgrade-server.js create mode 100644 node-v0.8.14/test/simple/test-http-upgrade-server2.js create mode 100644 node-v0.8.14/test/simple/test-http-url.parse-auth-with-header-in-request.js create mode 100644 node-v0.8.14/test/simple/test-http-url.parse-auth.js create mode 100644 node-v0.8.14/test/simple/test-http-url.parse-basic.js create mode 100644 node-v0.8.14/test/simple/test-http-url.parse-https.request.js create mode 100644 node-v0.8.14/test/simple/test-http-url.parse-only-support-http-https-protocol.js create mode 100644 node-v0.8.14/test/simple/test-http-url.parse-path.js create mode 100644 node-v0.8.14/test/simple/test-http-url.parse-post.js create mode 100644 node-v0.8.14/test/simple/test-http-url.parse-search.js create mode 100644 node-v0.8.14/test/simple/test-http-wget.js create mode 100644 node-v0.8.14/test/simple/test-http-write-empty-string.js create mode 100644 node-v0.8.14/test/simple/test-http.js create mode 100644 node-v0.8.14/test/simple/test-https-agent.js create mode 100644 node-v0.8.14/test/simple/test-https-client-get-url.js create mode 100644 node-v0.8.14/test/simple/test-https-client-reject.js create mode 100644 node-v0.8.14/test/simple/test-https-connecting-to-http.js create mode 100644 node-v0.8.14/test/simple/test-https-drain.js create mode 100644 node-v0.8.14/test/simple/test-https-eof-for-eom.js create mode 100644 node-v0.8.14/test/simple/test-https-foafssl.js create mode 100644 node-v0.8.14/test/simple/test-https-invalid-key.js create mode 100644 node-v0.8.14/test/simple/test-https-localaddress-bind-error.js create mode 100644 node-v0.8.14/test/simple/test-https-localaddress.js create mode 100644 node-v0.8.14/test/simple/test-https-pfx.js create mode 100644 node-v0.8.14/test/simple/test-https-simple.js create mode 100644 node-v0.8.14/test/simple/test-https-socket-options.js create mode 100644 node-v0.8.14/test/simple/test-https-strict.js create mode 100644 node-v0.8.14/test/simple/test-https-timeout.js create mode 100644 node-v0.8.14/test/simple/test-init.js create mode 100644 node-v0.8.14/test/simple/test-listen-fd-cluster.js create mode 100644 node-v0.8.14/test/simple/test-listen-fd-detached-inherit.js create mode 100644 node-v0.8.14/test/simple/test-listen-fd-detached.js create mode 100644 node-v0.8.14/test/simple/test-listen-fd-ebadf.js create mode 100644 node-v0.8.14/test/simple/test-listen-fd-server.js create mode 100644 node-v0.8.14/test/simple/test-memory-usage-emfile.js create mode 100644 node-v0.8.14/test/simple/test-memory-usage.js create mode 100644 node-v0.8.14/test/simple/test-mkdir-rmdir.js create mode 100644 node-v0.8.14/test/simple/test-module-loading-error.js create mode 100644 node-v0.8.14/test/simple/test-module-loading.js create mode 100644 node-v0.8.14/test/simple/test-net-after-close.js create mode 100644 node-v0.8.14/test/simple/test-net-binary.js create mode 100644 node-v0.8.14/test/simple/test-net-bind-twice.js create mode 100644 node-v0.8.14/test/simple/test-net-bytes-stats.js create mode 100644 node-v0.8.14/test/simple/test-net-can-reset-timeout.js create mode 100644 node-v0.8.14/test/simple/test-net-connect-buffer.js create mode 100644 node-v0.8.14/test/simple/test-net-connect-handle-econnrefused.js create mode 100644 node-v0.8.14/test/simple/test-net-connect-options.js create mode 100644 node-v0.8.14/test/simple/test-net-connect-timeout.js create mode 100644 node-v0.8.14/test/simple/test-net-create-connection.js create mode 100644 node-v0.8.14/test/simple/test-net-dns-error.js create mode 100644 node-v0.8.14/test/simple/test-net-during-close.js create mode 100644 node-v0.8.14/test/simple/test-net-eaddrinuse.js create mode 100644 node-v0.8.14/test/simple/test-net-isip.js create mode 100644 node-v0.8.14/test/simple/test-net-keepalive.js create mode 100644 node-v0.8.14/test/simple/test-net-large-string.js create mode 100644 node-v0.8.14/test/simple/test-net-listen-error.js create mode 100644 node-v0.8.14/test/simple/test-net-listen-fd0.js create mode 100644 node-v0.8.14/test/simple/test-net-pause-resume-connecting.js create mode 100644 node-v0.8.14/test/simple/test-net-pingpong.js create mode 100644 node-v0.8.14/test/simple/test-net-pipe-connect-errors.js create mode 100644 node-v0.8.14/test/simple/test-net-reconnect.js create mode 100644 node-v0.8.14/test/simple/test-net-remote-address-port.js create mode 100644 node-v0.8.14/test/simple/test-net-server-address.js create mode 100644 node-v0.8.14/test/simple/test-net-server-bind.js create mode 100644 node-v0.8.14/test/simple/test-net-server-close.js create mode 100644 node-v0.8.14/test/simple/test-net-server-listen-remove-callback.js create mode 100644 node-v0.8.14/test/simple/test-net-server-max-connections.js create mode 100644 node-v0.8.14/test/simple/test-net-server-try-ports.js create mode 100644 node-v0.8.14/test/simple/test-net-settimeout.js create mode 100644 node-v0.8.14/test/simple/test-net-socket-destroy-twice.js create mode 100644 node-v0.8.14/test/simple/test-net-socket-timeout.js create mode 100644 node-v0.8.14/test/simple/test-net-stream.js create mode 100644 node-v0.8.14/test/simple/test-net-write-after-close.js create mode 100644 node-v0.8.14/test/simple/test-net-write-connect-write.js create mode 100644 node-v0.8.14/test/simple/test-net-write-slow.js create mode 100644 node-v0.8.14/test/simple/test-next-tick-doesnt-hang.js create mode 100644 node-v0.8.14/test/simple/test-next-tick-errors.js create mode 100644 node-v0.8.14/test/simple/test-next-tick-ordering.js create mode 100644 node-v0.8.14/test/simple/test-next-tick-ordering2.js create mode 100644 node-v0.8.14/test/simple/test-next-tick-starvation.js create mode 100644 node-v0.8.14/test/simple/test-next-tick.js create mode 100644 node-v0.8.14/test/simple/test-os.js create mode 100644 node-v0.8.14/test/simple/test-path-makelong.js create mode 100644 node-v0.8.14/test/simple/test-path.js create mode 100644 node-v0.8.14/test/simple/test-pipe-address.js create mode 100644 node-v0.8.14/test/simple/test-pipe-file-to-http.js create mode 100644 node-v0.8.14/test/simple/test-pipe-head.js create mode 100644 node-v0.8.14/test/simple/test-pipe-return-val.js create mode 100644 node-v0.8.14/test/simple/test-pipe-stream.js create mode 100644 node-v0.8.14/test/simple/test-pipe.js create mode 100644 node-v0.8.14/test/simple/test-process-active-wraps.js create mode 100644 node-v0.8.14/test/simple/test-process-argv-0.js create mode 100644 node-v0.8.14/test/simple/test-process-config.js create mode 100644 node-v0.8.14/test/simple/test-process-env.js create mode 100644 node-v0.8.14/test/simple/test-process-exec-argv.js create mode 100644 node-v0.8.14/test/simple/test-process-exit-recursive.js create mode 100644 node-v0.8.14/test/simple/test-process-exit.js create mode 100644 node-v0.8.14/test/simple/test-process-hrtime.js create mode 100644 node-v0.8.14/test/simple/test-process-kill-null.js create mode 100644 node-v0.8.14/test/simple/test-process-next-tick.js create mode 100644 node-v0.8.14/test/simple/test-process-wrap.js create mode 100644 node-v0.8.14/test/simple/test-pump-file2tcp-noexist.js create mode 100644 node-v0.8.14/test/simple/test-pump-file2tcp.js create mode 100644 node-v0.8.14/test/simple/test-punycode.js create mode 100644 node-v0.8.14/test/simple/test-querystring.js create mode 100644 node-v0.8.14/test/simple/test-readdir.js create mode 100644 node-v0.8.14/test/simple/test-readdouble.js create mode 100644 node-v0.8.14/test/simple/test-readfloat.js create mode 100644 node-v0.8.14/test/simple/test-readint.js create mode 100644 node-v0.8.14/test/simple/test-readline-interface.js create mode 100644 node-v0.8.14/test/simple/test-readline-set-raw-mode.js create mode 100644 node-v0.8.14/test/simple/test-readuint.js create mode 100644 node-v0.8.14/test/simple/test-regress-GH-1531.js create mode 100644 node-v0.8.14/test/simple/test-regress-GH-1697.js create mode 100644 node-v0.8.14/test/simple/test-regress-GH-1726.js create mode 100644 node-v0.8.14/test/simple/test-regress-GH-1899.js create mode 100644 node-v0.8.14/test/simple/test-regress-GH-3542.js create mode 100644 node-v0.8.14/test/simple/test-regress-GH-3739.js create mode 100644 node-v0.8.14/test/simple/test-regress-GH-4015.js create mode 100644 node-v0.8.14/test/simple/test-regress-GH-4027.js create mode 100644 node-v0.8.14/test/simple/test-regress-GH-746.js create mode 100644 node-v0.8.14/test/simple/test-regress-GH-784.js create mode 100644 node-v0.8.14/test/simple/test-regress-GH-819.js create mode 100644 node-v0.8.14/test/simple/test-regress-GH-877.js create mode 100644 node-v0.8.14/test/simple/test-regress-GH-897.js create mode 100644 node-v0.8.14/test/simple/test-regression-object-prototype.js create mode 100644 node-v0.8.14/test/simple/test-repl-.save.load.js create mode 100644 node-v0.8.14/test/simple/test-repl-autolibs.js create mode 100644 node-v0.8.14/test/simple/test-repl-end-emits-exit.js create mode 100644 node-v0.8.14/test/simple/test-repl-options.js create mode 100644 node-v0.8.14/test/simple/test-repl-tab-complete.js create mode 100644 node-v0.8.14/test/simple/test-repl.js create mode 100644 node-v0.8.14/test/simple/test-require-cache-without-stat.js create mode 100644 node-v0.8.14/test/simple/test-require-cache.js create mode 100644 node-v0.8.14/test/simple/test-require-exceptions.js create mode 100644 node-v0.8.14/test/simple/test-require-json.js create mode 100644 node-v0.8.14/test/simple/test-require-resolve.js create mode 100644 node-v0.8.14/test/simple/test-script-context.js create mode 100644 node-v0.8.14/test/simple/test-script-new.js create mode 100644 node-v0.8.14/test/simple/test-script-static-context.js create mode 100644 node-v0.8.14/test/simple/test-script-static-new.js create mode 100644 node-v0.8.14/test/simple/test-script-static-this.js create mode 100644 node-v0.8.14/test/simple/test-script-this.js create mode 100644 node-v0.8.14/test/simple/test-setproctitle.js create mode 100644 node-v0.8.14/test/simple/test-sigint-infinite-loop.js create mode 100644 node-v0.8.14/test/simple/test-signal-handler.js create mode 100644 node-v0.8.14/test/simple/test-signal-unregister.js create mode 100644 node-v0.8.14/test/simple/test-stdin-child-proc.js create mode 100644 node-v0.8.14/test/simple/test-stdin-from-file.js create mode 100644 node-v0.8.14/test/simple/test-stdin-hang.js create mode 100644 node-v0.8.14/test/simple/test-stdin-pause-resume-sync.js create mode 100644 node-v0.8.14/test/simple/test-stdin-pause-resume.js create mode 100644 node-v0.8.14/test/simple/test-stdin-pipe-resume.js create mode 100644 node-v0.8.14/test/simple/test-stdin-resume-pause.js create mode 100644 node-v0.8.14/test/simple/test-stdout-close-catch.js create mode 100644 node-v0.8.14/test/simple/test-stdout-to-file.js create mode 100644 node-v0.8.14/test/simple/test-stream-pipe-cleanup.js create mode 100644 node-v0.8.14/test/simple/test-stream-pipe-error-handling.js create mode 100644 node-v0.8.14/test/simple/test-stream-pipe-event.js create mode 100644 node-v0.8.14/test/simple/test-stream-pipe-multi.js create mode 100644 node-v0.8.14/test/simple/test-string-decoder.js create mode 100644 node-v0.8.14/test/simple/test-sync-fileread.js create mode 100644 node-v0.8.14/test/simple/test-sys.js create mode 100644 node-v0.8.14/test/simple/test-tcp-wrap-connect.js create mode 100644 node-v0.8.14/test/simple/test-tcp-wrap-listen.js create mode 100644 node-v0.8.14/test/simple/test-tcp-wrap.js create mode 100644 node-v0.8.14/test/simple/test-timers-linked-list.js create mode 100644 node-v0.8.14/test/simple/test-timers-uncaught-exception.js create mode 100644 node-v0.8.14/test/simple/test-timers-zero-timeout.js create mode 100644 node-v0.8.14/test/simple/test-timers.js create mode 100644 node-v0.8.14/test/simple/test-tls-check-server-identity.js create mode 100644 node-v0.8.14/test/simple/test-tls-client-abort.js create mode 100644 node-v0.8.14/test/simple/test-tls-client-abort2.js create mode 100644 node-v0.8.14/test/simple/test-tls-client-reject.js create mode 100644 node-v0.8.14/test/simple/test-tls-client-resume.js create mode 100644 node-v0.8.14/test/simple/test-tls-client-verify.js create mode 100644 node-v0.8.14/test/simple/test-tls-connect-given-socket.js create mode 100644 node-v0.8.14/test/simple/test-tls-connect-pipe.js create mode 100644 node-v0.8.14/test/simple/test-tls-connect-simple.js create mode 100644 node-v0.8.14/test/simple/test-tls-connect.js create mode 100644 node-v0.8.14/test/simple/test-tls-getcipher.js create mode 100644 node-v0.8.14/test/simple/test-tls-honorcipherorder.js create mode 100644 node-v0.8.14/test/simple/test-tls-invalid-key.js create mode 100644 node-v0.8.14/test/simple/test-tls-junk-closes-server.js create mode 100644 node-v0.8.14/test/simple/test-tls-npn-server-client.js create mode 100644 node-v0.8.14/test/simple/test-tls-over-http-tunnel.js create mode 100644 node-v0.8.14/test/simple/test-tls-passphrase.js create mode 100644 node-v0.8.14/test/simple/test-tls-pause-close.js create mode 100644 node-v0.8.14/test/simple/test-tls-pause.js create mode 100644 node-v0.8.14/test/simple/test-tls-peer-certificate-multi-keys.js create mode 100644 node-v0.8.14/test/simple/test-tls-peer-certificate.js create mode 100644 node-v0.8.14/test/simple/test-tls-remote.js create mode 100644 node-v0.8.14/test/simple/test-tls-request-timeout.js create mode 100644 node-v0.8.14/test/simple/test-tls-securepair-client.js create mode 100644 node-v0.8.14/test/simple/test-tls-securepair-server.js create mode 100644 node-v0.8.14/test/simple/test-tls-server-verify.js create mode 100644 node-v0.8.14/test/simple/test-tls-session-cache.js create mode 100644 node-v0.8.14/test/simple/test-tls-set-ciphers.js create mode 100644 node-v0.8.14/test/simple/test-tls-set-encoding.js create mode 100644 node-v0.8.14/test/simple/test-tls-sni-server-client.js create mode 100644 node-v0.8.14/test/simple/test-tty-stdout-end.js create mode 100644 node-v0.8.14/test/simple/test-tty-wrap.js create mode 100644 node-v0.8.14/test/simple/test-typed-arrays.js create mode 100644 node-v0.8.14/test/simple/test-umask.js create mode 100644 node-v0.8.14/test/simple/test-url.js create mode 100644 node-v0.8.14/test/simple/test-utf8-scripts.js create mode 100644 node-v0.8.14/test/simple/test-util-format.js create mode 100644 node-v0.8.14/test/simple/test-util-inspect.js create mode 100644 node-v0.8.14/test/simple/test-util.js create mode 100644 node-v0.8.14/test/simple/test-vm-create-context-accessors.js create mode 100644 node-v0.8.14/test/simple/test-vm-create-context-arg.js create mode 100644 node-v0.8.14/test/simple/test-vm-create-context-circular-reference.js create mode 100644 node-v0.8.14/test/simple/test-writedouble.js create mode 100644 node-v0.8.14/test/simple/test-writefloat.js create mode 100644 node-v0.8.14/test/simple/test-writeint.js create mode 100644 node-v0.8.14/test/simple/test-writeuint.js create mode 100644 node-v0.8.14/test/simple/test-zerolengthbufferbug.js create mode 100644 node-v0.8.14/test/simple/test-zlib-destroy.js create mode 100644 node-v0.8.14/test/simple/test-zlib-dictionary.js create mode 100644 node-v0.8.14/test/simple/test-zlib-from-gzip.js create mode 100644 node-v0.8.14/test/simple/test-zlib-from-string.js create mode 100644 node-v0.8.14/test/simple/test-zlib-invalid-input.js create mode 100644 node-v0.8.14/test/simple/test-zlib-random-byte-pipes.js create mode 100644 node-v0.8.14/test/simple/test-zlib.js create mode 100644 node-v0.8.14/test/simple/testcfg.py create mode 100644 node-v0.8.14/tools/addon.gypi create mode 100644 node-v0.8.14/tools/blog/README.md create mode 100644 node-v0.8.14/tools/blog/generate.js create mode 100644 node-v0.8.14/tools/blog/templates/index.ejs create mode 100644 node-v0.8.14/tools/blog/wp-to-markdown.js create mode 100644 node-v0.8.14/tools/build-changelog.sh create mode 100644 node-v0.8.14/tools/changelog-head.sh create mode 100644 node-v0.8.14/tools/closure_linter/PKG-INFO create mode 100644 node-v0.8.14/tools/closure_linter/README create mode 100644 node-v0.8.14/tools/closure_linter/closure_linter.egg-info/PKG-INFO create mode 100644 node-v0.8.14/tools/closure_linter/closure_linter.egg-info/SOURCES.txt create mode 100644 node-v0.8.14/tools/closure_linter/closure_linter.egg-info/dependency_links.txt create mode 100644 node-v0.8.14/tools/closure_linter/closure_linter.egg-info/entry_points.txt create mode 100644 node-v0.8.14/tools/closure_linter/closure_linter.egg-info/requires.txt create mode 100644 node-v0.8.14/tools/closure_linter/closure_linter.egg-info/top_level.txt create mode 100755 node-v0.8.14/tools/closure_linter/closure_linter/__init__.py create mode 100755 node-v0.8.14/tools/closure_linter/closure_linter/checker.py create mode 100755 node-v0.8.14/tools/closure_linter/closure_linter/checkerbase.py create mode 100755 node-v0.8.14/tools/closure_linter/closure_linter/common/__init__.py create mode 100755 node-v0.8.14/tools/closure_linter/closure_linter/common/error.py create mode 100755 node-v0.8.14/tools/closure_linter/closure_linter/common/erroraccumulator.py create mode 100755 node-v0.8.14/tools/closure_linter/closure_linter/common/errorhandler.py create mode 100755 node-v0.8.14/tools/closure_linter/closure_linter/common/errorprinter.py create mode 100755 node-v0.8.14/tools/closure_linter/closure_linter/common/filetestcase.py create mode 100755 node-v0.8.14/tools/closure_linter/closure_linter/common/htmlutil.py create mode 100755 node-v0.8.14/tools/closure_linter/closure_linter/common/lintrunner.py create mode 100755 node-v0.8.14/tools/closure_linter/closure_linter/common/matcher.py create mode 100755 node-v0.8.14/tools/closure_linter/closure_linter/common/position.py create mode 100755 node-v0.8.14/tools/closure_linter/closure_linter/common/simplefileflags.py create mode 100755 node-v0.8.14/tools/closure_linter/closure_linter/common/tokenizer.py create mode 100755 node-v0.8.14/tools/closure_linter/closure_linter/common/tokens.py create mode 100755 node-v0.8.14/tools/closure_linter/closure_linter/ecmalintrules.py create mode 100755 node-v0.8.14/tools/closure_linter/closure_linter/ecmametadatapass.py create mode 100755 node-v0.8.14/tools/closure_linter/closure_linter/error_fixer.py create mode 100755 node-v0.8.14/tools/closure_linter/closure_linter/errorrules.py create mode 100755 node-v0.8.14/tools/closure_linter/closure_linter/errors.py create mode 100755 node-v0.8.14/tools/closure_linter/closure_linter/fixjsstyle.py create mode 100755 node-v0.8.14/tools/closure_linter/closure_linter/fixjsstyle_test.py create mode 100755 node-v0.8.14/tools/closure_linter/closure_linter/full_test.py create mode 100755 node-v0.8.14/tools/closure_linter/closure_linter/gjslint.py create mode 100755 node-v0.8.14/tools/closure_linter/closure_linter/indentation.py create mode 100755 node-v0.8.14/tools/closure_linter/closure_linter/javascriptlintrules.py create mode 100755 node-v0.8.14/tools/closure_linter/closure_linter/javascriptstatetracker.py create mode 100755 node-v0.8.14/tools/closure_linter/closure_linter/javascriptstatetracker_test.py create mode 100755 node-v0.8.14/tools/closure_linter/closure_linter/javascripttokenizer.py create mode 100755 node-v0.8.14/tools/closure_linter/closure_linter/javascripttokens.py create mode 100755 node-v0.8.14/tools/closure_linter/closure_linter/statetracker.py create mode 100755 node-v0.8.14/tools/closure_linter/closure_linter/tokenutil.py create mode 100644 node-v0.8.14/tools/closure_linter/gflags.py create mode 100644 node-v0.8.14/tools/closure_linter/setup.cfg create mode 100755 node-v0.8.14/tools/closure_linter/setup.py create mode 100644 node-v0.8.14/tools/cpplint.py create mode 100644 node-v0.8.14/tools/doc/LICENSE create mode 100644 node-v0.8.14/tools/doc/README.md create mode 100755 node-v0.8.14/tools/doc/generate.js create mode 100644 node-v0.8.14/tools/doc/html.js create mode 100644 node-v0.8.14/tools/doc/json.js create mode 100644 node-v0.8.14/tools/doc/package.json create mode 100644 node-v0.8.14/tools/email-footer.md create mode 100755 node-v0.8.14/tools/genv8constants.py create mode 100644 node-v0.8.14/tools/getnodeisrelease.py create mode 100644 node-v0.8.14/tools/getnodeversion.py create mode 100644 node-v0.8.14/tools/gyp/.gitignore create mode 100644 node-v0.8.14/tools/gyp/AUTHORS create mode 100644 node-v0.8.14/tools/gyp/DEPS create mode 100644 node-v0.8.14/tools/gyp/LICENSE create mode 100644 node-v0.8.14/tools/gyp/MANIFEST create mode 100644 node-v0.8.14/tools/gyp/OWNERS create mode 100644 node-v0.8.14/tools/gyp/PRESUBMIT.py create mode 100755 node-v0.8.14/tools/gyp/buildbot/buildbot_run.py create mode 100644 node-v0.8.14/tools/gyp/codereview.settings create mode 100755 node-v0.8.14/tools/gyp/gyp create mode 100755 node-v0.8.14/tools/gyp/gyp.bat create mode 100644 node-v0.8.14/tools/gyp/gyp_dummy.c create mode 100755 node-v0.8.14/tools/gyp/gyptest.py create mode 100644 node-v0.8.14/tools/gyp/pylib/gyp/MSVSNew.py create mode 100644 node-v0.8.14/tools/gyp/pylib/gyp/MSVSProject.py create mode 100644 node-v0.8.14/tools/gyp/pylib/gyp/MSVSSettings.py create mode 100755 node-v0.8.14/tools/gyp/pylib/gyp/MSVSSettings_test.py create mode 100644 node-v0.8.14/tools/gyp/pylib/gyp/MSVSToolFile.py create mode 100644 node-v0.8.14/tools/gyp/pylib/gyp/MSVSUserFile.py create mode 100644 node-v0.8.14/tools/gyp/pylib/gyp/MSVSVersion.py create mode 100644 node-v0.8.14/tools/gyp/pylib/gyp/SCons.py create mode 100755 node-v0.8.14/tools/gyp/pylib/gyp/__init__.py create mode 100644 node-v0.8.14/tools/gyp/pylib/gyp/common.py create mode 100755 node-v0.8.14/tools/gyp/pylib/gyp/common_test.py create mode 100644 node-v0.8.14/tools/gyp/pylib/gyp/easy_xml.py create mode 100755 node-v0.8.14/tools/gyp/pylib/gyp/easy_xml_test.py create mode 100644 node-v0.8.14/tools/gyp/pylib/gyp/generator/__init__.py create mode 100644 node-v0.8.14/tools/gyp/pylib/gyp/generator/android.py create mode 100644 node-v0.8.14/tools/gyp/pylib/gyp/generator/dump_dependency_json.py create mode 100644 node-v0.8.14/tools/gyp/pylib/gyp/generator/eclipse.py create mode 100644 node-v0.8.14/tools/gyp/pylib/gyp/generator/gypd.py create mode 100644 node-v0.8.14/tools/gyp/pylib/gyp/generator/gypsh.py create mode 100644 node-v0.8.14/tools/gyp/pylib/gyp/generator/make.py create mode 100644 node-v0.8.14/tools/gyp/pylib/gyp/generator/msvs.py create mode 100755 node-v0.8.14/tools/gyp/pylib/gyp/generator/msvs_test.py create mode 100644 node-v0.8.14/tools/gyp/pylib/gyp/generator/ninja.py create mode 100644 node-v0.8.14/tools/gyp/pylib/gyp/generator/ninja_test.py create mode 100644 node-v0.8.14/tools/gyp/pylib/gyp/generator/scons.py create mode 100644 node-v0.8.14/tools/gyp/pylib/gyp/generator/xcode.py create mode 100644 node-v0.8.14/tools/gyp/pylib/gyp/input.py create mode 100755 node-v0.8.14/tools/gyp/pylib/gyp/mac_tool.py create mode 100644 node-v0.8.14/tools/gyp/pylib/gyp/msvs_emulation.py create mode 100644 node-v0.8.14/tools/gyp/pylib/gyp/ninja_syntax.py create mode 100755 node-v0.8.14/tools/gyp/pylib/gyp/sun_tool.py create mode 100755 node-v0.8.14/tools/gyp/pylib/gyp/system_test.py create mode 100644 node-v0.8.14/tools/gyp/pylib/gyp/win_tool.py create mode 100644 node-v0.8.14/tools/gyp/pylib/gyp/xcode_emulation.py create mode 100644 node-v0.8.14/tools/gyp/pylib/gyp/xcodeproj_file.py create mode 100644 node-v0.8.14/tools/gyp/pylib/gyp/xml_fix.py create mode 100644 node-v0.8.14/tools/gyp/pylintrc create mode 100755 node-v0.8.14/tools/gyp/samples/samples create mode 100644 node-v0.8.14/tools/gyp/samples/samples.bat create mode 100755 node-v0.8.14/tools/gyp/setup.py create mode 100644 node-v0.8.14/tools/gyp/tools/README create mode 100644 node-v0.8.14/tools/gyp/tools/Xcode/README create mode 100644 node-v0.8.14/tools/gyp/tools/Xcode/Specifications/gyp.pbfilespec create mode 100644 node-v0.8.14/tools/gyp/tools/Xcode/Specifications/gyp.xclangspec create mode 100644 node-v0.8.14/tools/gyp/tools/emacs/README create mode 100644 node-v0.8.14/tools/gyp/tools/emacs/gyp-tests.el create mode 100644 node-v0.8.14/tools/gyp/tools/emacs/gyp.el create mode 100755 node-v0.8.14/tools/gyp/tools/emacs/run-unit-tests.sh create mode 100644 node-v0.8.14/tools/gyp/tools/emacs/testdata/media.gyp create mode 100644 node-v0.8.14/tools/gyp/tools/emacs/testdata/media.gyp.fontified create mode 100755 node-v0.8.14/tools/gyp/tools/graphviz.py create mode 100755 node-v0.8.14/tools/gyp/tools/pretty_gyp.py create mode 100755 node-v0.8.14/tools/gyp/tools/pretty_sln.py create mode 100755 node-v0.8.14/tools/gyp/tools/pretty_vcproj.py create mode 100755 node-v0.8.14/tools/gyp_addon create mode 100755 node-v0.8.14/tools/gyp_node create mode 100755 node-v0.8.14/tools/install.py create mode 100755 node-v0.8.14/tools/js2c.py create mode 100644 node-v0.8.14/tools/license2rtf.js create mode 100644 node-v0.8.14/tools/msvs/msi/nodemsi.sln create mode 100644 node-v0.8.14/tools/msvs/msi/nodemsi.wixproj create mode 100755 node-v0.8.14/tools/msvs/msi/product.wxs create mode 100644 node-v0.8.14/tools/msvs/nodejsvars.bat create mode 100644 node-v0.8.14/tools/msvs/npm/npmrc create mode 100755 node-v0.8.14/tools/node-waf create mode 100644 node-v0.8.14/tools/osx-codesign.sh create mode 100644 node-v0.8.14/tools/osx-pkg-postinstall.sh create mode 100644 node-v0.8.14/tools/osx-pkg.pmdoc/01local-contents.xml create mode 100644 node-v0.8.14/tools/osx-pkg.pmdoc/01local.xml create mode 100644 node-v0.8.14/tools/osx-pkg.pmdoc/02npm-contents.xml create mode 100644 node-v0.8.14/tools/osx-pkg.pmdoc/02npm.xml create mode 100644 node-v0.8.14/tools/osx-pkg.pmdoc/index.xml create mode 100644 node-v0.8.14/tools/osx-productsign.sh create mode 100755 node-v0.8.14/tools/test.py create mode 100644 node-v0.8.14/tools/updateAuthors.awk create mode 100755 node-v0.8.14/tools/waf-light create mode 100644 node-v0.8.14/tools/wafadmin/Build.py create mode 100644 node-v0.8.14/tools/wafadmin/Configure.py create mode 100644 node-v0.8.14/tools/wafadmin/Constants.py create mode 100644 node-v0.8.14/tools/wafadmin/Environment.py create mode 100644 node-v0.8.14/tools/wafadmin/Logs.py create mode 100644 node-v0.8.14/tools/wafadmin/Node.py create mode 100644 node-v0.8.14/tools/wafadmin/Options.py create mode 100644 node-v0.8.14/tools/wafadmin/Runner.py create mode 100644 node-v0.8.14/tools/wafadmin/Scripting.py create mode 100644 node-v0.8.14/tools/wafadmin/Task.py create mode 100644 node-v0.8.14/tools/wafadmin/TaskGen.py create mode 100644 node-v0.8.14/tools/wafadmin/Tools/__init__.py create mode 100644 node-v0.8.14/tools/wafadmin/Tools/ar.py create mode 100644 node-v0.8.14/tools/wafadmin/Tools/cc.py create mode 100644 node-v0.8.14/tools/wafadmin/Tools/ccroot.py create mode 100644 node-v0.8.14/tools/wafadmin/Tools/compiler_cc.py create mode 100644 node-v0.8.14/tools/wafadmin/Tools/compiler_cxx.py create mode 100644 node-v0.8.14/tools/wafadmin/Tools/compiler_d.py create mode 100644 node-v0.8.14/tools/wafadmin/Tools/config_c.py create mode 100644 node-v0.8.14/tools/wafadmin/Tools/cxx.py create mode 100644 node-v0.8.14/tools/wafadmin/Tools/d.py create mode 100644 node-v0.8.14/tools/wafadmin/Tools/dmd.py create mode 100644 node-v0.8.14/tools/wafadmin/Tools/gas.py create mode 100644 node-v0.8.14/tools/wafadmin/Tools/gcc.py create mode 100644 node-v0.8.14/tools/wafadmin/Tools/gdc.py create mode 100644 node-v0.8.14/tools/wafadmin/Tools/gnu_dirs.py create mode 100644 node-v0.8.14/tools/wafadmin/Tools/gob2.py create mode 100644 node-v0.8.14/tools/wafadmin/Tools/gxx.py create mode 100644 node-v0.8.14/tools/wafadmin/Tools/icc.py create mode 100644 node-v0.8.14/tools/wafadmin/Tools/icpc.py create mode 100644 node-v0.8.14/tools/wafadmin/Tools/intltool.py create mode 100644 node-v0.8.14/tools/wafadmin/Tools/libtool.py create mode 100644 node-v0.8.14/tools/wafadmin/Tools/misc.py create mode 100644 node-v0.8.14/tools/wafadmin/Tools/nasm.py create mode 100644 node-v0.8.14/tools/wafadmin/Tools/node_addon.py create mode 100644 node-v0.8.14/tools/wafadmin/Tools/osx.py create mode 100644 node-v0.8.14/tools/wafadmin/Tools/preproc.py create mode 100644 node-v0.8.14/tools/wafadmin/Tools/python.py create mode 100644 node-v0.8.14/tools/wafadmin/Tools/suncc.py create mode 100644 node-v0.8.14/tools/wafadmin/Tools/suncxx.py create mode 100644 node-v0.8.14/tools/wafadmin/Tools/unittestw.py create mode 100644 node-v0.8.14/tools/wafadmin/Tools/winres.py create mode 100644 node-v0.8.14/tools/wafadmin/Tools/xlc.py create mode 100644 node-v0.8.14/tools/wafadmin/Tools/xlcxx.py create mode 100644 node-v0.8.14/tools/wafadmin/Utils.py create mode 100644 node-v0.8.14/tools/wafadmin/__init__.py create mode 100644 node-v0.8.14/tools/wafadmin/ansiterm.py create mode 100644 node-v0.8.14/tools/wafadmin/pproc.py create mode 100644 node-v0.8.14/tools/wafadmin/py3kfixes.py create mode 100644 node-v0.8.14/vcbuild.bat delete mode 120000 node_modules/.bin/sardines delete mode 100644 node_modules/celeri/.cupboard delete mode 100755 node_modules/celeri/.gitignore delete mode 100755 node_modules/celeri/MIT-LICENSE.txt delete mode 100755 node_modules/celeri/README.md delete mode 100755 node_modules/celeri/examples/auth.js delete mode 100755 node_modules/celeri/examples/authadv.js delete mode 100755 node_modules/celeri/examples/confirm.js delete mode 100755 node_modules/celeri/examples/exec.js delete mode 100755 node_modules/celeri/examples/hello.js delete mode 100755 node_modules/celeri/examples/hello2.js delete mode 100755 node_modules/celeri/examples/table.js delete mode 100644 node_modules/celeri/examples/table2.js delete mode 100644 node_modules/celeri/examples/table3.js delete mode 100755 node_modules/celeri/examples/tree.js delete mode 100755 node_modules/celeri/images/screen.png delete mode 100755 node_modules/celeri/lib/index.js delete mode 100755 node_modules/celeri/lib/modules/auth.js delete mode 100755 node_modules/celeri/lib/modules/backspace.js delete mode 100755 node_modules/celeri/lib/modules/confirm.js delete mode 100755 node_modules/celeri/lib/modules/enter.js delete mode 100755 node_modules/celeri/lib/modules/exec.js delete mode 100755 node_modules/celeri/lib/modules/help.js delete mode 100755 node_modules/celeri/lib/modules/history.js delete mode 100755 node_modules/celeri/lib/modules/loading.js delete mode 100755 node_modules/celeri/lib/modules/nav.js delete mode 100755 node_modules/celeri/lib/modules/password.js delete mode 100755 node_modules/celeri/lib/modules/progress.js delete mode 100755 node_modules/celeri/lib/modules/prompt.js delete mode 100755 node_modules/celeri/lib/modules/quit.js delete mode 100755 node_modules/celeri/lib/modules/section.js delete mode 100644 node_modules/celeri/lib/modules/table.js delete mode 100755 node_modules/celeri/lib/modules/table2.js delete mode 100755 node_modules/celeri/lib/modules/tree.js delete mode 100755 node_modules/celeri/lib/utils.js delete mode 100644 node_modules/celeri/node_modules/beanpole/.cupboard delete mode 100644 node_modules/celeri/node_modules/beanpole/.gitignore delete mode 100644 node_modules/celeri/node_modules/beanpole/MIT-LICENSE.txt delete mode 100644 node_modules/celeri/node_modules/beanpole/README.md delete mode 100644 node_modules/celeri/node_modules/beanpole/beanpole.tmproj delete mode 100644 node_modules/celeri/node_modules/beanpole/docs/beans/README.md delete mode 100644 node_modules/celeri/node_modules/beanpole/docs/brainstorming/README.txt delete mode 100644 node_modules/celeri/node_modules/beanpole/docs/brainstorming/analogy.txt delete mode 100644 node_modules/celeri/node_modules/beanpole/docs/brainstorming/ideas.txt delete mode 100755 node_modules/celeri/node_modules/beanpole/docs/build-ebnf delete mode 100644 node_modules/celeri/node_modules/beanpole/docs/diagram.png delete mode 100644 node_modules/celeri/node_modules/beanpole/docs/syntax.ebnf delete mode 100644 node_modules/celeri/node_modules/beanpole/examples/bean.hello/beans/hello.core/index.js delete mode 100644 node_modules/celeri/node_modules/beanpole/examples/bean.hello/beans/hello.friend/index.js delete mode 100644 node_modules/celeri/node_modules/beanpole/examples/bean.hello/beans/hello.neighbor/index.js delete mode 100644 node_modules/celeri/node_modules/beanpole/examples/bean.hello/index.js delete mode 100644 node_modules/celeri/node_modules/beanpole/examples/bean.hook.call.receive/beans/test/index.js delete mode 100644 node_modules/celeri/node_modules/beanpole/examples/bean.hook.call.receive/index.js delete mode 100644 node_modules/celeri/node_modules/beanpole/examples/bean.hook.hello/beans/test/index.js delete mode 100644 node_modules/celeri/node_modules/beanpole/examples/bean.hook.hello/index.js delete mode 100644 node_modules/celeri/node_modules/beanpole/examples/bean.hook.middleware/beans/test/index.js delete mode 100644 node_modules/celeri/node_modules/beanpole/examples/bean.hook.middleware/hook1.js delete mode 100644 node_modules/celeri/node_modules/beanpole/examples/bean.hook.middleware/hook2.js delete mode 100644 node_modules/celeri/node_modules/beanpole/examples/bean.hook.middleware/hook3.js delete mode 100644 node_modules/celeri/node_modules/beanpole/examples/bean.http.middleware/index.js delete mode 100644 node_modules/celeri/node_modules/beanpole/examples/bean.http.server/beans/hello.core/index.js delete mode 100644 node_modules/celeri/node_modules/beanpole/examples/bean.http.server/beans/http.server/index.js delete mode 100644 node_modules/celeri/node_modules/beanpole/examples/bean.http.server/index.js delete mode 100644 node_modules/celeri/node_modules/beanpole/examples/bean.website.load/beans/hello.core/index.js delete mode 100644 node_modules/celeri/node_modules/beanpole/examples/bean.website.load/index.js delete mode 100644 node_modules/celeri/node_modules/beanpole/examples/benchmark.silly/index.js delete mode 100644 node_modules/celeri/node_modules/beanpole/examples/default/index.js delete mode 100644 node_modules/celeri/node_modules/beanpole/examples/filter.metadata.rotate/beans/test/index.js delete mode 100644 node_modules/celeri/node_modules/beanpole/examples/filter.metadata.rotate/index.js delete mode 100644 node_modules/celeri/node_modules/beanpole/examples/filter.metadata/index.js delete mode 100644 node_modules/celeri/node_modules/beanpole/examples/http.gateway/direct.js delete mode 100644 node_modules/celeri/node_modules/beanpole/examples/http.gateway/hook.js delete mode 100644 node_modules/celeri/node_modules/beanpole/examples/http.gateway/hook2.js delete mode 100644 node_modules/celeri/node_modules/beanpole/examples/http.gateway/hook3.js delete mode 100644 node_modules/celeri/node_modules/beanpole/examples/http.gateway/hook4.js delete mode 100644 node_modules/celeri/node_modules/beanpole/examples/http.gateway/index.js delete mode 100644 node_modules/celeri/node_modules/beanpole/examples/interception-old/index.js delete mode 100644 node_modules/celeri/node_modules/beanpole/examples/multi.routes/index.js delete mode 100644 node_modules/celeri/node_modules/beanpole/examples/or.hello/index.js delete mode 100644 node_modules/celeri/node_modules/beanpole/examples/override.pull/index.js delete mode 100644 node_modules/celeri/node_modules/beanpole/examples/pull.thru/index.js delete mode 100644 node_modules/celeri/node_modules/beanpole/examples/push.pull/index.js delete mode 100644 node_modules/celeri/node_modules/beanpole/examples/push.thru/index.js delete mode 100644 node_modules/celeri/node_modules/beanpole/examples/rotate.hello/index.js delete mode 100644 node_modules/celeri/node_modules/beanpole/examples/thru/index.js delete mode 100644 node_modules/celeri/node_modules/beanpole/examples/ws/client/release/index.html delete mode 100644 node_modules/celeri/node_modules/beanpole/examples/ws/client/release/index.js delete mode 100644 node_modules/celeri/node_modules/beanpole/examples/ws/hook.js delete mode 100644 node_modules/celeri/node_modules/beanpole/examples/ws/server.js delete mode 100644 node_modules/celeri/node_modules/beanpole/lib/core/concrete/collection.js delete mode 100644 node_modules/celeri/node_modules/beanpole/lib/core/concrete/parser.js delete mode 100644 node_modules/celeri/node_modules/beanpole/lib/core/concrete/request.js delete mode 100644 node_modules/celeri/node_modules/beanpole/lib/core/concrete/router.js delete mode 100644 node_modules/celeri/node_modules/beanpole/lib/core/concrete/utils.js delete mode 100644 node_modules/celeri/node_modules/beanpole/lib/core/controller.js delete mode 100644 node_modules/celeri/node_modules/beanpole/lib/core/index.js delete mode 100644 node_modules/celeri/node_modules/beanpole/lib/core/loader.js delete mode 100644 node_modules/celeri/node_modules/beanpole/lib/core/middleware/meta/index.js delete mode 100644 node_modules/celeri/node_modules/beanpole/lib/core/middleware/meta/rotate.js delete mode 100644 node_modules/celeri/node_modules/beanpole/lib/core/middleware/meta/store.js delete mode 100644 node_modules/celeri/node_modules/beanpole/lib/core/middleware/route/default/index.js delete mode 100644 node_modules/celeri/node_modules/beanpole/lib/core/middleware/route/index.js delete mode 100644 node_modules/celeri/node_modules/beanpole/lib/core/middleware/route/pushPull/pull/index.js delete mode 100644 node_modules/celeri/node_modules/beanpole/lib/core/middleware/route/pushPull/pull/request.js delete mode 100644 node_modules/celeri/node_modules/beanpole/lib/core/middleware/route/pushPull/push/index.js delete mode 100644 node_modules/celeri/node_modules/beanpole/lib/core/middleware/route/pushPull/push/request.js delete mode 100644 node_modules/celeri/node_modules/beanpole/lib/core/middleware/route/pushPull/push/router.js delete mode 100644 node_modules/celeri/node_modules/beanpole/lib/core/middleware/route/pushPull/request.js delete mode 100644 node_modules/celeri/node_modules/beanpole/lib/core/middleware/route/pushPull/stream.js delete mode 100644 node_modules/celeri/node_modules/beanpole/lib/node/beans/system.core/index.js delete mode 100644 node_modules/celeri/node_modules/beanpole/lib/node/index.js delete mode 100644 node_modules/celeri/node_modules/beanpole/lib/node/loader.js delete mode 100644 node_modules/celeri/node_modules/beanpole/lib/web/index.js delete mode 100644 node_modules/celeri/node_modules/beanpole/package.json delete mode 100644 node_modules/celeri/node_modules/beanpole/project.sublime-project delete mode 100644 node_modules/celeri/node_modules/beanpole/project.tmproj delete mode 100644 node_modules/celeri/node_modules/colors/MIT-LICENSE.txt delete mode 100644 node_modules/celeri/node_modules/colors/ReadMe.md delete mode 100644 node_modules/celeri/node_modules/colors/colors.js delete mode 100644 node_modules/celeri/node_modules/colors/example.html delete mode 100644 node_modules/celeri/node_modules/colors/example.js delete mode 100644 node_modules/celeri/node_modules/colors/package.json delete mode 100644 node_modules/celeri/node_modules/structr/package.json delete mode 100644 node_modules/celeri/node_modules/structr/structr.js delete mode 100644 node_modules/celeri/node_modules/structr/structr.min.js delete mode 100755 node_modules/celeri/package.json delete mode 100644 node_modules/celeri/project.sublime-project delete mode 100644 node_modules/celeri/project.tmproj delete mode 100644 node_modules/findit/README.markdown delete mode 100644 node_modules/findit/examples/callback.js delete mode 100644 node_modules/findit/examples/emitter.js delete mode 100644 node_modules/findit/examples/sync.js delete mode 100644 node_modules/findit/index.js delete mode 100644 node_modules/findit/node_modules/seq/.npmignore delete mode 100644 node_modules/findit/node_modules/seq/README.markdown delete mode 100644 node_modules/findit/node_modules/seq/examples/join.js delete mode 100644 node_modules/findit/node_modules/seq/examples/parseq.coffee delete mode 100644 node_modules/findit/node_modules/seq/examples/parseq.js delete mode 100644 node_modules/findit/node_modules/seq/examples/stat_all.coffee delete mode 100644 node_modules/findit/node_modules/seq/examples/stat_all.js delete mode 100755 node_modules/findit/node_modules/seq/index.js delete mode 100644 node_modules/findit/node_modules/seq/node_modules/chainsaw/.npmignore delete mode 100644 node_modules/findit/node_modules/seq/node_modules/chainsaw/README.markdown delete mode 100644 node_modules/findit/node_modules/seq/node_modules/chainsaw/examples/add_do.js delete mode 100644 node_modules/findit/node_modules/seq/node_modules/chainsaw/examples/prompt.js delete mode 100755 node_modules/findit/node_modules/seq/node_modules/chainsaw/index.js delete mode 100644 node_modules/findit/node_modules/seq/node_modules/chainsaw/node_modules/traverse/.npmignore delete mode 100644 node_modules/findit/node_modules/seq/node_modules/chainsaw/node_modules/traverse/LICENSE delete mode 100644 node_modules/findit/node_modules/seq/node_modules/chainsaw/node_modules/traverse/README.markdown delete mode 100755 node_modules/findit/node_modules/seq/node_modules/chainsaw/node_modules/traverse/examples/json.js delete mode 100755 node_modules/findit/node_modules/seq/node_modules/chainsaw/node_modules/traverse/examples/leaves.js delete mode 100755 node_modules/findit/node_modules/seq/node_modules/chainsaw/node_modules/traverse/examples/negative.js delete mode 100755 node_modules/findit/node_modules/seq/node_modules/chainsaw/node_modules/traverse/examples/stringify.js delete mode 100755 node_modules/findit/node_modules/seq/node_modules/chainsaw/node_modules/traverse/index.js delete mode 100644 node_modules/findit/node_modules/seq/node_modules/chainsaw/node_modules/traverse/package.json delete mode 100644 node_modules/findit/node_modules/seq/node_modules/chainsaw/node_modules/traverse/test/circular.js delete mode 100644 node_modules/findit/node_modules/seq/node_modules/chainsaw/node_modules/traverse/test/date.js delete mode 100644 node_modules/findit/node_modules/seq/node_modules/chainsaw/node_modules/traverse/test/equal.js delete mode 100644 node_modules/findit/node_modules/seq/node_modules/chainsaw/node_modules/traverse/test/instance.js delete mode 100644 node_modules/findit/node_modules/seq/node_modules/chainsaw/node_modules/traverse/test/interface.js delete mode 100644 node_modules/findit/node_modules/seq/node_modules/chainsaw/node_modules/traverse/test/json.js delete mode 100644 node_modules/findit/node_modules/seq/node_modules/chainsaw/node_modules/traverse/test/leaves.js delete mode 100644 node_modules/findit/node_modules/seq/node_modules/chainsaw/node_modules/traverse/test/mutability.js delete mode 100644 node_modules/findit/node_modules/seq/node_modules/chainsaw/node_modules/traverse/test/negative.js delete mode 100644 node_modules/findit/node_modules/seq/node_modules/chainsaw/node_modules/traverse/test/obj.js delete mode 100644 node_modules/findit/node_modules/seq/node_modules/chainsaw/node_modules/traverse/test/stop.js delete mode 100644 node_modules/findit/node_modules/seq/node_modules/chainsaw/node_modules/traverse/test/stringify.js delete mode 100644 node_modules/findit/node_modules/seq/node_modules/chainsaw/node_modules/traverse/test/super_deep.js delete mode 100644 node_modules/findit/node_modules/seq/node_modules/chainsaw/package.json delete mode 100644 node_modules/findit/node_modules/seq/node_modules/chainsaw/test/chainsaw.js delete mode 100644 node_modules/findit/node_modules/seq/node_modules/hashish/README.markdown delete mode 100644 node_modules/findit/node_modules/seq/node_modules/hashish/examples/chain.js delete mode 100644 node_modules/findit/node_modules/seq/node_modules/hashish/examples/map.js delete mode 100644 node_modules/findit/node_modules/seq/node_modules/hashish/index.js delete mode 100644 node_modules/findit/node_modules/seq/node_modules/hashish/node_modules/traverse/.npmignore delete mode 100644 node_modules/findit/node_modules/seq/node_modules/hashish/node_modules/traverse/LICENSE delete mode 100644 node_modules/findit/node_modules/seq/node_modules/hashish/node_modules/traverse/README.markdown delete mode 100755 node_modules/findit/node_modules/seq/node_modules/hashish/node_modules/traverse/examples/json.js delete mode 100755 node_modules/findit/node_modules/seq/node_modules/hashish/node_modules/traverse/examples/leaves.js delete mode 100755 node_modules/findit/node_modules/seq/node_modules/hashish/node_modules/traverse/examples/negative.js delete mode 100755 node_modules/findit/node_modules/seq/node_modules/hashish/node_modules/traverse/examples/scrub.js delete mode 100755 node_modules/findit/node_modules/seq/node_modules/hashish/node_modules/traverse/examples/stringify.js delete mode 100644 node_modules/findit/node_modules/seq/node_modules/hashish/node_modules/traverse/index.js delete mode 100755 node_modules/findit/node_modules/seq/node_modules/hashish/node_modules/traverse/main.js delete mode 100644 node_modules/findit/node_modules/seq/node_modules/hashish/node_modules/traverse/package.json delete mode 100644 node_modules/findit/node_modules/seq/node_modules/hashish/node_modules/traverse/test/circular.js delete mode 100644 node_modules/findit/node_modules/seq/node_modules/hashish/node_modules/traverse/test/date.js delete mode 100644 node_modules/findit/node_modules/seq/node_modules/hashish/node_modules/traverse/test/equal.js delete mode 100644 node_modules/findit/node_modules/seq/node_modules/hashish/node_modules/traverse/test/instance.js delete mode 100644 node_modules/findit/node_modules/seq/node_modules/hashish/node_modules/traverse/test/interface.js delete mode 100644 node_modules/findit/node_modules/seq/node_modules/hashish/node_modules/traverse/test/json.js delete mode 100644 node_modules/findit/node_modules/seq/node_modules/hashish/node_modules/traverse/test/keys.js delete mode 100644 node_modules/findit/node_modules/seq/node_modules/hashish/node_modules/traverse/test/leaves.js delete mode 100644 node_modules/findit/node_modules/seq/node_modules/hashish/node_modules/traverse/test/lib/deep_equal.js delete mode 100644 node_modules/findit/node_modules/seq/node_modules/hashish/node_modules/traverse/test/mutability.js delete mode 100644 node_modules/findit/node_modules/seq/node_modules/hashish/node_modules/traverse/test/negative.js delete mode 100644 node_modules/findit/node_modules/seq/node_modules/hashish/node_modules/traverse/test/obj.js delete mode 100644 node_modules/findit/node_modules/seq/node_modules/hashish/node_modules/traverse/test/siblings.js delete mode 100644 node_modules/findit/node_modules/seq/node_modules/hashish/node_modules/traverse/test/stop.js delete mode 100644 node_modules/findit/node_modules/seq/node_modules/hashish/node_modules/traverse/test/stringify.js delete mode 100644 node_modules/findit/node_modules/seq/node_modules/hashish/node_modules/traverse/test/subexpr.js delete mode 100644 node_modules/findit/node_modules/seq/node_modules/hashish/node_modules/traverse/test/super_deep.js delete mode 100644 node_modules/findit/node_modules/seq/node_modules/hashish/package.json delete mode 100644 node_modules/findit/node_modules/seq/node_modules/hashish/test/hash.js delete mode 100644 node_modules/findit/node_modules/seq/node_modules/hashish/test/property.js delete mode 100644 node_modules/findit/node_modules/seq/package.json delete mode 100644 node_modules/findit/node_modules/seq/test/readdir.js delete mode 100644 node_modules/findit/node_modules/seq/test/seq.js delete mode 100644 node_modules/findit/node_modules/seq/test/seq_.js delete mode 100644 node_modules/findit/package.json delete mode 100644 node_modules/findit/test/cb.js delete mode 100644 node_modules/findit/test/cycle.js delete mode 100644 node_modules/findit/test/foo.js delete mode 100644 node_modules/findit/test/module.js delete mode 100644 node_modules/mkdirp/.gitignore delete mode 100644 node_modules/mkdirp/.gitignore.orig delete mode 100644 node_modules/mkdirp/.gitignore.rej delete mode 100644 node_modules/mkdirp/LICENSE delete mode 100644 node_modules/mkdirp/README.markdown delete mode 100644 node_modules/mkdirp/examples/pow.js delete mode 100644 node_modules/mkdirp/examples/pow.js.orig delete mode 100644 node_modules/mkdirp/examples/pow.js.rej delete mode 100644 node_modules/mkdirp/index.js delete mode 100644 node_modules/mkdirp/package.json delete mode 100644 node_modules/mkdirp/test/chmod.js delete mode 100644 node_modules/mkdirp/test/clobber.js delete mode 100644 node_modules/mkdirp/test/mkdirp.js delete mode 100644 node_modules/mkdirp/test/perm.js delete mode 100644 node_modules/mkdirp/test/perm_sync.js delete mode 100644 node_modules/mkdirp/test/race.js delete mode 100644 node_modules/mkdirp/test/rel.js delete mode 100644 node_modules/mkdirp/test/sync.js delete mode 100644 node_modules/optimist/.gitignore delete mode 100644 node_modules/optimist/.npmignore delete mode 100644 node_modules/optimist/examples/bool.js delete mode 100644 node_modules/optimist/examples/boolean_double.js delete mode 100644 node_modules/optimist/examples/boolean_single.js delete mode 100644 node_modules/optimist/examples/default_hash.js delete mode 100644 node_modules/optimist/examples/default_singles.js delete mode 100644 node_modules/optimist/examples/divide.js delete mode 100644 node_modules/optimist/examples/line_count.js delete mode 100644 node_modules/optimist/examples/line_count_options.js delete mode 100644 node_modules/optimist/examples/line_count_wrap.js delete mode 100644 node_modules/optimist/examples/nonopt.js delete mode 100644 node_modules/optimist/examples/reflect.js delete mode 100644 node_modules/optimist/examples/short.js delete mode 100644 node_modules/optimist/examples/string.js delete mode 100644 node_modules/optimist/examples/usage-options.js delete mode 100644 node_modules/optimist/examples/xup.js delete mode 100644 node_modules/request/mimetypes.js delete mode 100755 node_modules/request/tests/run.sh delete mode 120000 node_modules/sardines delete mode 120000 node_modules/sk delete mode 100644 node_modules/tar-async/header.js delete mode 100644 node_modules/tar-async/index.js delete mode 100644 node_modules/tar-async/package.json delete mode 100644 node_modules/tar-async/tar.js delete mode 100644 node_modules/tar-async/untar.js delete mode 100644 node_modules/tar-async/utils.js delete mode 100644 node_modules/tar/.gitignore delete mode 100644 node_modules/tar/README.md delete mode 100644 node_modules/tar/examples/extracter.js delete mode 100644 node_modules/tar/examples/reader.js delete mode 100644 node_modules/tar/lib/buffer-entry.js delete mode 100644 node_modules/tar/lib/entry-writer.js delete mode 100644 node_modules/tar/lib/entry.js delete mode 100644 node_modules/tar/lib/extended-header-writer.js delete mode 100644 node_modules/tar/lib/extended-header.js delete mode 100644 node_modules/tar/lib/extract.js delete mode 100644 node_modules/tar/lib/global-header-writer.js delete mode 100644 node_modules/tar/lib/header.js delete mode 100644 node_modules/tar/lib/pack.js delete mode 100644 node_modules/tar/lib/parse.js delete mode 100644 node_modules/tar/old/README.md delete mode 100644 node_modules/tar/old/doc/example.js delete mode 100644 node_modules/tar/old/generator.js delete mode 100644 node_modules/tar/old/parser.js delete mode 100644 node_modules/tar/old/tar.js delete mode 100644 node_modules/tar/old/test/test-generator.js delete mode 100644 node_modules/tar/old/test/test-generator.tar delete mode 100644 node_modules/tar/old/test/test-generator.txt delete mode 100644 node_modules/tar/old/test/test-parser.js delete mode 100644 node_modules/tar/old/test/test-tar.tar delete mode 100644 node_modules/tar/old/test/test-tar.txt delete mode 100644 node_modules/tar/package.json delete mode 100644 node_modules/tar/tar.js delete mode 100644 node_modules/tar/test/extract.js delete mode 100644 node_modules/tar/test/fixtures/200.tar delete mode 100644 node_modules/tar/test/fixtures/200L.hex delete mode 100644 node_modules/tar/test/fixtures/200ccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc delete mode 100644 node_modules/tar/test/fixtures/200longlink.tar delete mode 100644 node_modules/tar/test/fixtures/200longname.tar delete mode 100644 node_modules/tar/test/fixtures/a.hex delete mode 100644 node_modules/tar/test/fixtures/a.tar delete mode 100644 node_modules/tar/test/fixtures/a.txt delete mode 100644 node_modules/tar/test/fixtures/b.hex delete mode 100644 node_modules/tar/test/fixtures/b.tar delete mode 100644 node_modules/tar/test/fixtures/b.txt delete mode 100644 node_modules/tar/test/fixtures/c.hex delete mode 100644 node_modules/tar/test/fixtures/c.tar delete mode 100644 node_modules/tar/test/fixtures/c.txt delete mode 100644 node_modules/tar/test/fixtures/cc.txt delete mode 100644 node_modules/tar/test/fixtures/foo.hex delete mode 100644 node_modules/tar/test/fixtures/foo.js delete mode 100644 node_modules/tar/test/fixtures/foo.tar delete mode 100644 node_modules/tar/test/fixtures/hardlink-1 delete mode 100644 node_modules/tar/test/fixtures/hardlink-2 delete mode 100644 node_modules/tar/test/fixtures/omega.hex delete mode 100644 node_modules/tar/test/fixtures/omega.tar delete mode 100644 node_modules/tar/test/fixtures/omega.txt delete mode 100644 node_modules/tar/test/fixtures/omegapax.tar delete mode 100644 node_modules/tar/test/fixtures/packtest/omega.txt delete mode 100644 node_modules/tar/test/fixtures/packtest/star.4.html delete mode 100644 node_modules/tar/test/fixtures/packtest/Ω.txt delete mode 100644 node_modules/tar/test/fixtures/r/e/a/l/l/y/-/d/e/e/p/-/f/o/l/d/e/r/-/p/a/t/h/cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc delete mode 120000 node_modules/tar/test/fixtures/symlink delete mode 100644 node_modules/tar/test/fixtures/Ω.txt delete mode 100644 node_modules/tar/test/header.js delete mode 100644 node_modules/tar/test/pack.js delete mode 100644 node_modules/tar/test/parse.js delete mode 120000 node_modules/vine delete mode 100644 project.sublime-project delete mode 100644 project.sublime-workspace diff --git a/.cupboard b/.cupboard index 46d2b19..b659210 100644 --- a/.cupboard +++ b/.cupboard @@ -1,2 +1,3 @@ [commands] -proj = subl --project project.sublime-project +proj = subl . + diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..b512c09 --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +node_modules \ No newline at end of file diff --git a/README.md b/README.md index fba00b0..e4d41a6 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,7 @@ Compile javascript **with** node.js. This allows you to move your executable aro ## Requirements -- Linux / Mac (windows soon) +- Linux / Mac ## Installation @@ -23,7 +23,7 @@ Or git: - Developing client-side utilities without requiring to install a bunch of dependencies first (node.js, npm). - Ability to run multiple node.js applications with *different* node.js runtimes. - +- Distributable packages without needing node / npm. ### CLI Usage @@ -34,7 +34,7 @@ Usage: nexe -i [sources] -o [binary] Options: -i, --input The entry javascript files [default: cwd] -o, --output The output binary [default: cwd/app.nex] - -r, --runtime The node.js runtime to use [default: "0.6.3"] + -r, --runtime The node.js runtime to use [default: "0.8.15"] ```` @@ -46,7 +46,7 @@ Options: var nexe = require('nexe'); -nexe.compile({ entries: 'input.js', output: 'path/to/bin', runtime: '0.6.3' } function() { +nexe.compile({ input: 'input.js', output: 'path/to/bin', runtime: '0.8.15' } function() { }); diff --git a/bin/nexe b/bin/nexe index e904a04..7b29281 100755 --- a/bin/nexe +++ b/bin/nexe @@ -14,17 +14,17 @@ options('o', { demand: true, alias: 'output', desc: 'The output binary', - default: process.cwd() + '/' + path.basename(process.cwd()) + '.nex' + default: process.cwd() + '/release/' + path.basename(process.cwd()) + '.nex' }). options('r', { alias: 'runtime', - default: '0.6.3', + default: '0.8.14', description: 'The node.js runtime to use' }).argv; -require('../lib').compile({ entries: argv.i.split(' '), output: argv.o, runtime: argv.r }, function(error) { +require('../lib').compile({ input: argv.i, output: argv.o, runtime: argv.r }, function(error) { if(error) console.log(error.message); }); \ No newline at end of file diff --git a/lib/index.js b/lib/index.js index fa67278..cac5e36 100644 --- a/lib/index.js +++ b/lib/index.js @@ -1,227 +1,248 @@ -var sardines = require('sardines'), -child_process = require('child_process'), -spawn = child_process.spawn, +var step = require("step"), +outcome = require("outcome"), +request = require("request"), +fs = require("fs"), +mkdirp = require("mkdirp"), +path = require("path"), +child_process = require("child_process"), exec = child_process.exec, -fs = require('fs'), -mkdirp = require('mkdirp'), -http = require('http'), -celeri = require('celeri'); - -const ETC_DIR = '/usr/local/etc/nexe'; -const RUNTIMES_DIR = ETC_DIR + '/runtimes'; -const CURRENT_RUNTIME_DIR = ETC_DIR + '/current-runtime'; - +spawn = child_process.spawn, +sprintf = require("sprintf").sprintf, +browserify = require("browserify"), +ncp = require("ncp").ncp; /** */ -function fileExists(file) { +exports.compile = function(args, next) { + + var on = outcome.error(next); + + args.input = require.resolve(args.input); + + step( + + /** + * 1. download node + */ + + function() { + downloadNode(args.runtime, this); + }, + + /** + * 2. build the script into ONE file + */ + + on.success(function(node) { + console.log("making application bundle with %s", args.input); + this.node = node; + var b = browserify(); + b.addEntry(args.input); + this(null, b.bundle()); + }), + + /** + * 3. write the file into the node libs directory + */ + + on.success(function(bundle) { + console.log("writing application bundle"); + fs.writeFile(this.nexePath = path.join(this.node.dir, "lib", "nexe.js"), bundle, "utf8", this); + }), + + /** + * 4. monkeypatch the node entry + */ + + on.success(function() { + console.log("monkey patching node.js file"); + monkeyPatchNodejs(this.node, this); + }), + + /** + * 5. bundle it all together + */ + + on.success(function() { + console.log("building node.js"); + this.node.make(this); + }), + + /** + * 6. copy the executable + */ + + on.success(function() { + console.log("copying binary to output directory to %s", args.output); + + mkdirp(path.dirname(args.output), this); + }), + + /** + */ + + function() { + ncp(this.node.releasePath, args.output, this); + }, + + /** + */ + + next + + ) +} + +/** + */ + +function downloadNode(version, next) { + + var tmpPath = path.join("/tmp/nexe", "node-v" + version + ".tar.gz"), + srcDr = tmpPath.replace(/\.tar.gz$/, ""); + try { - return !!fs.lstatSync(file); - } catch(e) { - return false; - } -} -/** - * modify the input node.js file to evaluate nexe - */ + mkdirp.sync(path.dirname(tmpPath)) -function wrapNode(path) { + //an error will usually occur when the dir already exists. + } catch(e) { } - var nodePath = path + '/src/node.js', - content = fs.readFileSync(nodePath,'utf8'); + step( - content = content.replace(/\(function\(process\) \{/,'(function(process){ \n process._eval = require("nexe"); '); + /** + * download + */ - fs.writeFileSync(nodePath, content); -} + function() { -/** - */ + //zip exists? + if(fs.existsSync(tmpPath) || fs.existsSync(srcDr)) return this(); -function nexeMain(path) { - var pkgPath = path + '/package.json'; + console.log("downloading node %s", version); - if(!fileExists(pkgPath)) return null; + var output = fs.createWriteStream(tmpPath, { "flags": "w+" }), + req = request("http://nodejs.org/dist/v" + version + "/node-v" + version + ".tar.gz").pipe(output); - var script = JSON.parse(fs.readFileSync(pkgPath,'utf8'))['nexe-main']; + output.on("close", this); + }, - return script ? fs.realpathSync(path+'/' + script) : null; -} + /** + * untar + */ -/** - */ + function() { -function prepare(version, callback) { + //source dir exists? + if(fs.existsSync(srcDr)) return this(); - var runtimeDir = 'node-v' + version, - runtimeDirPath = RUNTIMES_DIR + '/' + runtimeDir, - runtimeTarPath = RUNTIMES_DIR + '/'+ runtimeDir + '.tar'; - - function onComplete() { - callback(false, { - path: runtimeDirPath, - libDir: runtimeDirPath + '/lib' - }); - } - - //file exists? already prepared - if(fileExists(runtimeDirPath)) return onComplete(); + console.log("unzipping node source"); - mkdirp(runtimeDirPath, 0755, function(err) { - - if(err) return callback(err); + //TODO - use native zlib library for this + exec(sprintf("tar -xf '%s'", tmpPath), { cwd: path.dirname(tmpPath) }, this); + }, + /** + * cleanup the node.js file + */ - //download the node.js runtime if it doesn't exist - http.get({ host: 'nodejs.org', port: 80, path: '/dist/v' + version + '/node-v' + version + '.tar.gz' }, function(res) { + function() { + fs.unlink(tmpfile, this); + }, - res.setEncoding('binary'); - - var output = fs.createWriteStream(runtimeTarPath, { 'flags': 'a' }), - size = Number(res.headers['content-length'] || 0), - progress = 0; + /** + * return make script + */ - res.on('data', function(chunk) { - progress += chunk.length; - celeri.progress('Downloading ' + runtimeDir, Math.floor(progress/size * 100)); - output.write(chunk, 'binary'); - }); + function() { + next(null, { - res.on('end', function() { + //the directory to the node.js file + dir: srcDr, - output.end(); + releasePath: path.join(srcDr, "out/Release/node"), - - function onUnzipped(err) { - - fs.unlinkSync(runtimeTarPath); - if(err) return callback(err); - - wrapNode(runtimeDirPath); - - onComplete(); - } - - console.log('Configuring %s', runtimeDirPath); - exec('tar -xf ' + runtimeTarPath + '; cd ' + runtimeDirPath + '; ./configure', { cwd: RUNTIMES_DIR }, onUnzipped); - }); - - - - - }).on('error', function(e) { - - try { - fs.rmdirSync(runtimeDirPath); - } catch(e) { } - - callback(new Error('Unable to download node '+version+': '+e.message)); - }); - - - }); - - -} - -/** - */ - -function findIncludes(dir, inc) { - - if(!inc) inc = []; - - fs.readdirSync(dir).forEach(function(name) { - - if(name.substr(0,1) == '.' || name == 'node_modules') return; - - var subPath = dir + '/' + name; - - if(fs.statSync(subPath).isDirectory()) { - - findIncludes(subPath, inc); - - } else if(name.match(/\.js$/)) { - - inc.push(subPath); - } - }); - - return inc; -} - -/** - */ - -exports.compile = function(ops, callback) { - - if(!ops.entries) throw new Error('You must provide entry javascript files.'); - if(!ops.runtime) throw new Error('A node.js runtime version must be provided.'); - if(!ops.output) throw new Error('Output must be provided.'); - - - ops.output = ops.output.replace('~', process.env.HOME); - - prepare(ops.runtime, function(err, node) { - - if(err) return callback(err); - - var include = [], - entries = []; - - ops.entries.forEach(function(entry) { - - var main = nexeMain(entry); - - if(main) { - - findIncludes(entry).forEach(function(path) { - - include.push({ - script: path, - alias: path.replace(entry,'') + //makes node.js + make: function(next) { + var proc = exec(sprintf("cd %s; ./configure; make; ", srcDr)); + proc.stdout._events = {}; //remove stdout & stdin capture + proc.stdin._events = {}; + proc.stdout.on("data", function(chunk) { + process.stdout.write(chunk); + }); + proc.stderr.on("data", function(chunk) { + process.stdout.write(chunk); }); - }); - - entries.push(main); - } else { - - entries.push(entry); - } - - - }); - - - //combine the JS - sardines.package({ input: entries, include: include, output: node.libDir + '/nexe.js' }, function(err) { - - if(err) return callback(new Error('Unable to make nexe.js')); - - console.log('Making executable'); - - - var proc = spawn('make', [], { cwd: node.path }); - - proc.stdout.on('data', function(data) { - console.log(data.toString()); + proc.on("exit", next); + } }); + } + ); +} - proc.stderr.on('data', function(data) { - console.error(data.toString()); - }); +/** + */ - proc.on('exit', function() { - exec('cp ./out/Release/node ' + ops.output, { cwd: node.path }, callback); - }); +function monkeyPatchNodejs(node, next) { + var nodejsPath = path.join(node.dir, "src", "node.js"), + nodegypPath = path.join(node.dir, "node.gyp"), + on = outcome.error(next); - }); + step( - - }); + /** + * read the node.js file + */ + + function() { + fs.readFile(nodejsPath, "utf8", this); + }, + + /** + * inject nexe as _eval IF it hasn't already been injected + */ + + on.success(function(content) { + + //nexe already injected? + if(~content.indexOf('nexe')) return this(); + + fs.writeFile(nodejsPath, + content.replace(/\(function\(process\) \{/,'(function(process){ \n process._eval = \'require("nexe");\'; '), + "utf8", + this); + }), + + /** + * next, find node.gyp and add nexe as a native lib file + */ + + on.success(function() { + fs.readFile(nodegypPath, "utf8", this); + }), + + /** + * finally, monkeypatch node.gyp + */ + + on.success(function(content) { + + //nexe already included as dep? + if(~content.indexOf('lib/nexe.js')) return this(); + + fs.writeFile(nodegypPath, + content.replace("'lib/fs.js',", "'lib/fs.js', 'lib/nexe.js', "), + "utf8", + this); + }), + + /** + */ + + next + ); } \ No newline at end of file diff --git a/nexe b/nexe deleted file mode 120000 index e9cfd10..0000000 --- a/nexe +++ /dev/null @@ -1 +0,0 @@ -/Users/craig/Dropbox/Developer/public/nexe \ No newline at end of file diff --git a/node-v0.8.14/.gitattributes b/node-v0.8.14/.gitattributes new file mode 100644 index 0000000..a185d69 --- /dev/null +++ b/node-v0.8.14/.gitattributes @@ -0,0 +1 @@ +test/fixtures/* -text diff --git a/node-v0.8.14/.gitignore b/node-v0.8.14/.gitignore new file mode 100644 index 0000000..38e9ca9 --- /dev/null +++ b/node-v0.8.14/.gitignore @@ -0,0 +1,45 @@ +core +vgcore.* +.waf* +tags +.lock-wscript +*.pyc +doc/api.xml +tmp/ +node +node_g +*.swp +.benchmark_reports +/.project +/.cproject + +/out + +# various stuff that VC++ produces/uses +Debug/ +Release/ +!doc/blog/** +*.sln +!nodemsi.sln +*.suo +*.vcproj +*.vcxproj +*.vcxproj.user +*.vcxproj.filters +UpgradeLog*.XML +_UpgradeReport_Files/ +ipch/ +*.sdf +*.opensdf + +/config.mk +/config.gypi +*-nodegyp* +/gyp-mac-tool +/dist-osx +/npm.wxs +/tools/msvs/npm.wixobj +email.md +deps/v8-* +./node_modules +.svn/ \ No newline at end of file diff --git a/node-v0.8.14/.mailmap b/node-v0.8.14/.mailmap new file mode 100644 index 0000000..33d125d --- /dev/null +++ b/node-v0.8.14/.mailmap @@ -0,0 +1,104 @@ +Aaron Heckmann +Abe Fettig +Alex Kocharin +Alex Kocharin +Alexis Sellier +Alexis Sellier +Arlo Breault +Artem Zaytsev +Atsuo Fukaya +Ben Noordhuis +Bert Belder +Bert Belder +Brandon Benvie +Brian White +Brian White +Chew Choon Keat +Christopher Lenz +Daniel Berger +Daniel Chcouri <333222@gmail.com> +Daniel Gröber +Daniel Gröber +Daniel Pihlström +David Siegel +Domenic Denicola +Eduard Burtescu +Einar Otto Stangvik +Elliott Cable +EungJun Yi +Evan Larkin +Farid Neshat +Felix Geisendörfer +Felix Geisendörfer +Friedemann Altrock +Fuji Goro +Gabriel de Perthuis +Herbert Vojčík +Igor Zinkovsky +Isaac Z. Schlueter +Isaac Z. Schlueter +Jérémy Lal +Jérémy Lal +Jered Schmidt +Joe Shaw +Johan Bergström +Johan Dahlberg +Jonas Pfenniger +Jonathan Rentzsch +Joshua S. Weinstein +Koichi Kobayashi +Kris Kowal +Kyle Robinson Young +Mathias Pettersson +Michael Bernstein +Michael Wilber +Micheil Smith +Mikael Bourges-Sevenier +Nebu Pookins +Nicholas Kinsey +Onne Gorter +Paul Querna +Ray Morgan +Ray Solomon +Rick Olson +Ryan Dahl +Ryan Emery +Sam Shull +Sam Shull +Sambasiva Suda +San-Tai Hsu +Sergey Kryzhanovsky +Shannen Saez +Shigeki Ohtsu +Siddharth Mahendraker +Simon Willison +Stanislav Opichal +Stefan Bühler +Tadashi SAWADA +Takahiro ANDO +Ted Young +Thomas Lee +Tim Caswell +Tim Smart +Tim Smart +TJ Holowaychuk +TJ Holowaychuk +Trevor Burnham +Tyler Larson +Vincent Voyer +Yoshihiro KIKUCHI +Yuichiro MASUI +Zachary Scott +Zoran Tomicic + +# These people didn't contribute patches to node directly, +# but we've landed their v8 patches in the node repository: +Daniel Clifford +Erik Corry +Jakob Kummerow +Kevin Millikin +Lasse R.H. Nielsen +Michael Starzinger +Toon Verwaest +Vyacheslav Egorov +Yang Guo diff --git a/node-v0.8.14/.travis.yml b/node-v0.8.14/.travis.yml new file mode 100644 index 0000000..595409c --- /dev/null +++ b/node-v0.8.14/.travis.yml @@ -0,0 +1,14 @@ +language: node_js + +before_script: + - "./configure" + - "make" + +script: + - "make test" + +notifications: + email: false + irc: + - "irc.freenode.net#libuv" + diff --git a/node-v0.8.14/AUTHORS b/node-v0.8.14/AUTHORS new file mode 100644 index 0000000..48c8977 --- /dev/null +++ b/node-v0.8.14/AUTHORS @@ -0,0 +1,370 @@ +# Authors ordered by first contribution. + +Ryan Dahl +Urban Hafner +Joshaven Potter +Abe Fettig +Kevin van Zonneveld +Michael Carter +Jeff Smick +Jon Crosby +Felix Geisendörfer +Ray Morgan +Jérémy Lal +Isaac Z. Schlueter +Brandon Beacher +Tim Caswell +Connor Dunn +Johan Sørensen +Friedemann Altrock +Onne Gorter +Rhys Jones +Jan Lehnardt +Simon Willison +Chew Choon Keat +Jered Schmidt +Michaeljohn Clement +Karl Guertin +Xavier Shay +Christopher Lenz +TJ Holowaychuk +Johan Dahlberg +Simon Cornelius P. Umacob +Ryan McGrath +Rasmus Andersson +Micheil Smith +Jonas Pfenniger +David Sklar +Charles Lehner +Elliott Cable +Benjamin Thomas +San-Tai Hsu +Ben Williamson +Joseph Pecoraro +Erich Ocean +Alexis Sellier +Blaine Cook +Stanislav Opichal +Aaron Heckmann +Mikeal Rogers +Matt Brubeck +Michael Stillwell +Yuichiro MASUI +Mark Hansen +Zoran Tomicic +Jeremy Ashkenas +Scott González +James Duncan +Arlo Breault +Kris Kowal +Jacek Becela +Rob Ellis +Tim Smart +Herbert Vojčík +Krishna Rajendran +Nicholas Kinsey +Scott Taylor +Carson McDonald +Matt Ranney +James Herdman +Julian Lamb +Brian Hammond +Mathias Pettersson +Trevor Blackwell +Thomas Lee +Daniel Berger +Paulo Matias +Peter Griess +Jonathan Knezek +Jonathan Rentzsch +Ben Noordhuis +Elijah Insua +Andrew Johnston +Brian White +Aapo Laitinen +Sam Hughes +Orlando Vazquez +Raffaele Sena +Brian McKenna +Paul Querna +Ben Lowery +Peter Dekkers +David Siegel +Marshall Culpepper +Ruben Rodriguez +Dmitry Baranovskiy +Blake Mizerany +Jerome Etienne +Dmitriy Shalashov +Adam Wiggins +Rick Olson +Sergey Kryzhanovsky +Marco Rogers +Benjamin Fritsch +Jan Kassens +Robert Keizer +Sam Shull +Chandra Sekar S +Andrew Naylor +Benjamin Kramer +Danny Coates +Nick Stenning +Bert Belder +Trent Mick +Fedor Indutny +Illarionov Oleg +Aria Stewart +Johan Euphrosine +Russell Haering +Bradley Meck +Tobie Langel +Tony Metzidis +Mark Nottingham +Sam Stephenson +Jorge Chamorro Bieling +Evan Larkin +Sean Coates +Tom Hughes +Joshua Peek +Nathan Rajlich +Peteris Krumins +AJ ONeal +Sami Samhuri +Nikhil Marathe +Vitali Lovich +Stéphan Kochen +Oleg Efimov +Guillaume Tuton +Tim Cooijmans +Dan Søndergaard +Silas Sewell +Wade Simmons +Daniel Gröber +Travis Swicegood +Oleg Slobodskoi +Jeremy Martin +Michael Wilber +Sean Braithwaite +Anders Conbere +Devin Torres +Theo Schlossnagle +Kai Chen +Daniel Chcouri <333222@gmail.com> +Mihai Călin Bazon +Ali Farhadi +Daniel Ennis +Carter Allen +Greg Hughes +David Trejo +Joe Walnes +Koichi Kobayashi +Konstantin Käfer +Richard Rodger +Andreas Reich +Tony Huang +Dean McNamee +Trevor Burnham +Zachary Scott +Arnout Kazemier +George Stagas +Ben Weaver +Scott McWhirter +Jakub Lekstan +Nick Campbell +Nebu Pookins +Tim Baumann +Robert Mustacchi +George Miroshnykov +Mark Cavage +Håvard Stranden +Marcel Laverdet +Alexandre Marangone +Ryan Petrello +Fuji Goro +Siddharth Mahendraker +Dave Pacheco +Mathias Buus +Henry Rawas +Yoshihiro KIKUCHI +Brett Kiefer +Mariano Iglesias +Jörn Horstmann +Joe Shaw +Niklas Fiekas +Adam Luikart +Artem Zaytsev +Alex Xu +Jeremy Selier +Igor Zinkovsky +Kip Gebhardt +Stefan Rusu +Shigeki Ohtsu +Wojciech Wnętrzak +Devon Govett +Steve Engledow +Pierre-Alexandre St-Jean +Reid Burke +Vicente Jimenez Aguilar +Tadashi SAWADA +Jeroen Janssen +Daniel Pihlström +Stefan Bühler +Alexander Uvarov +Aku Kotkavuo +Peter Bright +Logan Smyth +Christopher Wright +Glen Low +Thomas Shinnick +Mickaël Delahaye +Antranig Basman +Maciej Małecki +Evan Martin +Peter Lyons +Jann Horn +Abimanyu Raja +Karl Skomski +Niclas Hoyer +Michael Jackson +Ashok Mudukutore +Sean Cunningham +Vitor Balocco +Ben Leslie +Eric Lovett +Christian Tellnes +Colton Baker +Tyler Larson +Tomasz Janczuk +Ilya Dmitrichenko +Simen Brekken +Guglielmo Ferri <44gatti@gmail.com> +Thomas Parslow +Ryan Emery +Jordan Sissel +Matt Robenolt +Jacob H.C. Kragh +Benjamin Pasero +Scott Anderson +Yoji SHIDARA +Mathias Bynens +Łukasz Walukiewicz +Artur Adib +E. Azer Koçulu +Paddy Byers +Roman Shtylman +Kyle Robinson Young +Tim Oxley +Eduard Burtescu +Ingmar Runge +Russ Bradberry +Andreas Madsen +Adam Malcontenti-Wilson +Avi Flax +Pedro Teixeira +Johan Bergström +James Hartig +Shannen Saez +Seong-Rak Choi +Dave Irvine +Ju-yeong Park +Phil Sung +Damon Oehlman +Mikael Bourges-Sevenier +Emerson Macedo +Ryunosuke SATO +Michael Bernstein +Guillermo Rauch +Dan Williams +Brandon Benvie +Nicolas LaCasse +Dan VerWeire +Matthew Fitzsimmons +Philip Tellis +Christopher Jeffrey +Seth Fitzsimmons +Einar Otto Stangvik +Paul Vorbach +Luke Gallagher +Tomasz Buchert +Myles Byrne +T.C. Hollingsworth +Cam Pedersen +Roly Fentanes +Ted Young +Joshua Holbrook +Blake Miner +Vincent Ollivier +Jimb Esser +Sambasiva Suda +Sadique Ali +Dmitry Nizovtsev +Alex Kocharin +Ming Liu +Shea Levy +Nao Iizuka +Christian Ress +Rod Vagg +Matt Ezell +Charlie McConnell +Farid Neshat +Johannes Wüller +Erik Lundin +Bryan Cantrill +Yosef Dinerstein +Nathan Friedly +Aaron Jacobs +Mustansir Golawala +Atsuo Fukaya +Domenic Denicola +Joshua S. Weinstein +Dane Springmeyer +Erik Dubbelboer +Malte-Thorben Bruns +Michael Thomas +Garen Torikian +EungJun Yi +Vincent Voyer +Takahiro ANDO +Erwin van der Koogh +Brian Schroeder +J. Lee Coltrane +Javier Hernández +James Koval +Kevin Gadd +Ray Solomon +Kevin Bowman +Matt Gollob +Simon Sturmer +Joel Brandt +Marc Harter +Nuno Job +Ben Kelly +Felix Böhm +Gabriel de Perthuis +Tim Macfarlane +Jonas Westerlund +Dominic Tarr +Justin Plock +Toshihiro Nakamura +Ivan Torres +Philipp Hagemeister +George Shank +Mike Morearty +Peter Rybin +Eugen Dueck +Gil Pedersen +Tyler Neylon +Golo Roden +Ron Korving +Brandon Wilson +Bearice Ren +Ankur Oberoi +Atsuya Takagi +Pooya Karimian +Frédéric Germain +Robin Lee +Adam Blackburn +Willi Eggeling +Andrew Paprocki +Max Ogden +Olivier Lalonde diff --git a/node-v0.8.14/BSDmakefile b/node-v0.8.14/BSDmakefile new file mode 100644 index 0000000..227ee74 --- /dev/null +++ b/node-v0.8.14/BSDmakefile @@ -0,0 +1,2 @@ +all: + @echo "I need GNU make. Please run \`gmake\` instead." diff --git a/node-v0.8.14/ChangeLog b/node-v0.8.14/ChangeLog new file mode 100644 index 0000000..d30c6c0 --- /dev/null +++ b/node-v0.8.14/ChangeLog @@ -0,0 +1,3543 @@ +2012.10.25, Version 0.8.14 (Stable) + +* events: Don't clobber pre-existing _events obj in EE ctor (isaacs) + + +2012.10.25, Version 0.8.13 (Stable), ff4c974873f9a7cc6a5b042eb9b6389bb8dde6d6 + +* V8: Upgrade to 3.11.10.25 + +* npm: Upgrade to 1.1.65 + +* url: parse hostnames that start with - or _ (Ben Noordhuis) + +* repl: Fix Windows 8 terminal issue (Bert Belder) + +* typed arrays: use signed char for signed int8s (Aaron Jacobs) + +* crypto: fix bugs in DiffieHellman (Ben Noordhuis) + +* configure: turn on VFPv3 on ARMv7 (Ben Noordhuis) + +* Re-enable OpenSSL UI for entering passphrases via tty (Ben Noordhuis) + +* repl: ensure each REPL instance gets its own "context" (Nathan Rajlich) + + +2012.10.12, Version 0.8.12 (Stable), 38c72d4e29574dec5205bcf23c2a85efe65331a4 + +* npm: Upgrade to 1.1.63 + +* crypto: Reduce stability index to 2-Unstable (isaacs) + +* windows: fix handle leak in uv_fs_utime (Bert Belder) + +* windows: fix application crashed popup in debug version (Bert Belder) + +* buffer: report proper retained size in profiler (Ben Noordhuis) + +* buffer: fix byteLength with UTF-16LE (koichik) + +* repl: make "end of input" JSON.parse() errors throw in the REPL (Nathan Rajlich) + +* repl: make invalid RegExp modifiers throw in the REPL (Nathan Rajlich) + +* http: handle multiple Proxy-Authenticate values (Willi Eggeling) + + +2012.09.27, Version 0.8.11 (Stable), e1f39468fa580c1e4cb15fac621f87944ee625dc + +* fs: Fix stat() size reporting for large files (Ben Noordhuis) + + +2012.09.25, Version 0.8.10 (Stable), 0bc273da4fcaa79b209ed755ad249a3e7be626a6 + +* npm: Upgrade to 1.1.62 + +* repl: make invalid RegExps throw in the REPL (Nathan Rajlich) + +* v8: loosen artificial mmap constraint (Bryan Cantrill) + +* process: fix setuid() and setgid() error reporting (Ben Noordhuis) + +* domain: Properly exit() on domain disposal (isaacs) + +* fs: fix watchFile() missing deletion events (Ben Noordhuis) + +* fs: fix assert in fs.watch() (Ben Noordhuis) + +* fs: don't segfault on deeply recursive stat() (Ben Noordhuis) + +* http: Remove timeout handler when data arrives (Frédéric Germain) + +* http: make the client "res" object gets the same domain as "req" (Nathan Rajlich) + +* windows: don't blow up when an invalid FD is used (Bert Belder) + +* unix: map EDQUOT to UV_ENOSPC (Charlie McConnell) + +* linux: improve /proc/cpuinfo parser (Ben Noordhuis) + +* win/tty: reset background brightness when color is set to default (Bert Belder) + +* unix: put child process stdio fds in blocking mode (Ben Noordhuis) + +* unix: fix EMFILE busy loop (Ben Noordhuis) + +* sunos: don't set TCP_KEEPALIVE (Ben Noordhuis) + +* tls: Use slab allocator for memory management (Fedor Indutny) + +* openssl: Use optimized assembly code for x86 and x64 (Bert Belder) + + +2012.09.11, Version 0.8.9 (Stable), b88c3902b241cf934e75443b934f2033ad3915b1 + +* v8: upgrade to 3.11.10.22 + +* GYP: upgrade to r1477 + +* npm: Upgrade to 1.1.61 + +* npm: Don't create world-writable files (isaacs) + +* windows: fix single-accept mode for shared server sockets (Bert Belder) + +* windows: fix uninitialized memory access in uv_update_time() (Bert Belder) + +* windows: don't throw when a signal handler is attached (Bert Belder) + +* unix: fix memory leak in udp (Ben Noordhuis) + +* unix: map errno ESPIPE (Ben Noordhuis) + +* unix, windows: fix memory corruption in fs-poll.c (Ben Noordhuis) + +* sunos: fix os.cpus() on x86_64 (Ben Noordhuis) + +* child process: fix processes with IPC channel don't emit 'close' (Bert Belder) + +* build: add a "--dest-os" option to force a gyp "flavor" (Nathan Rajlich) + +* build: set `process.platform` to "sunos" on SunOS (Nathan Rajlich) + +* build: fix `make -j` fails after `make clean` (Bearice Ren) + +* build: fix openssl configuration for "arm" builds (Nathan Rajlich) + +* tls: support unix domain socket/named pipe in tls.connect (Shigeki Ohtsu) + +* https: make https.get() accept a URL (koichik) + +* http: respect HTTP/1.0 TE header (Ben Noordhuis) + +* crypto, tls: Domainify setSNICallback, pbkdf2, randomBytes (Ben Noordhuis) + +* stream.pipe: Don't call destroy() unless it's a function (isaacs) + + +2012.08.22, Version 0.8.8 (Stable), a299c97bbc701f4d460e91214d7bfe7a9589d361 + +* V8: upgrade to 3.11.10.19 + +* npm: upgrade to 1.1.59 + +* windows: fix uninitialized memory access in uv_update_time() (Bert Belder) + +* unix, windows: fix memory corruption in fs-poll.c (Ben Noordhuis) + +* unix: fix integer overflow in uv_hrtime (Tim Holy) + +* sunos: fix uv_cpu_info() on x86_64 (Ben Noordhuis) + +* tls: update default cipher list (Ben Noordhuis) + +* unix: Fix llvm and older gcc duplicate symbol warnings (Bert Belder) + +* fs: fix use after free in stat watcher (Ben Noordhuis) + +* build: Fix using manually compiled gcc on OS X (Nathan Rajlich) + +* windows: make junctions work again (Bert Belder) + + +2012.08.15, Version 0.8.7 (Stable), f640c5d35cba96634cd8176a525a1d876e361a61 + +* npm: Upgrade to 1.1.49 + +* website: download page (Golo Roden) + +* crypto: fix uninitialized memory access in openssl (Ben Noordhuis) + +* buffer, crypto: fix buffer decoding (Ben Noordhuis) + +* build: compile with -fno-tree-vrp when gcc >= 4.0 (Ben Noordhuis) + +* tls: handle multiple CN fields when verifying cert (Ben Noordhuis) + +* doc: remove unused util from child_process (Kyle Robinson Young) + +* build: rework -fvisibility=hidden detection (Ben Noordhuis) + +* windows: don't duplicate invalid stdio handles (Bert Belder) + +* windows: fix typos in process-stdio.c (Bert Belder) + + +2012.08.07, Version 0.8.6 (Stable), 0544a586ca6b6b900a42e164033dbf350765700a + +* npm: Upgrade to v1.1.48 + +* Add 'make binary' to build binary tarballs for all Unixes (Nathan Rajlich) + +* zlib: Emit 'close' on destroy(). (Dominic Tarr) + +* child_process: Fix stdout=null when stdio=['pipe'] (Tyler Neylon) + +* installer: prevent ETXTBSY errors (Ben Noordhuis) + +* installer: honor --without-npm, default install path (Ben Noordhuis) + +* net: make pause work with connecting sockets (Bert Belder) + +* installer: fix cross-compile installs (Ben Noordhuis) + +* net: fix .listen({fd:0}) (Ben Noordhuis) + +* windows: map WSANO_DATA to UV_ENOENT (Bert Belder) + + +2012.08.02, Version 0.8.5 (Stable), 9b86a4453f0c76f2707a75c0b2343aba33ec63bc + +* node: tag Encode and friends NODE_EXTERN (Ben Noordhuis) + +* fs: fix ReadStream / WriteStream missing callback (Gil Pedersen) + +* fs: fix readFileSync("/proc/cpuinfo") regression (Ben Noordhuis) + +* installer: don't assume bash is installed (Ben Noordhuis) + +* Report errors properly from --eval and stdin (isaacs) + +* assert: fix throws() throws an error without message property (koichik) + +* cluster: fix libuv assert in net.listen() (Ben Noordhuis) + +* build: always link sunos builds with libumem (Trent Mick) + +* build: improve armv7 / hard-float detection (Adam Malcontenti-Wilson) + +* https: Use host header as effective servername (isaacs) + +* sunos: work around OS bug to prevent fs.watch() from spinning (Bryan Cantrill) + +* linux: fix 'two watchers, one path' segfault (Ben Noordhuis) + +* windows: fix memory leaks in many fs functions (Bert Belder) + +* windows: don't allow directories to be opened for writing/appending (Bert Belder) + +* windows: make fork() work even when not all stdio handles are valid (Bert Belder) + +* windows: make unlink() not remove mount points, and improve performance (Bert Belder) + +* build: Sign pkg installer for OS X (isaacs) + + +2012.07.25, Version 0.8.4 (Stable), f98562fcd7d1cab573ca4dc1612157d6999befd4 + +* V8: Upgrade to 3.11.10.17 + +* npm: Upgrade to 1.1.45 + +* net: fix Socket({ fd: 42 }) api (Ben Noordhuis) + +* readline: Remove event listeners on close (isaacs) + +* windows: correctly prep long path for fs.exists(Sync) (Bert Belder) + +* debugger: wake up the event loop when a debugger command is dispatched (Peter Rybin) + +* tls: verify server's identity (Fedor Indutny) + +* net: ignore socket.setTimeout(Infinity or NaN) (Fedor Indutny) + + +2012.07.19, Version 0.8.3 (Stable), 60bf2d6cb33e4ce55604f73889ab840a9de8bdab + +* V8: upgrade to 3.11.10.15 + +* npm: Upgrade to 1.1.43 + +* net: fix net.Server.listen({fd:x}) error reporting (Ben Noordhuis) + +* net: fix bogus errno reporting (Ben Noordhuis) + +* build: Move npm shebang logic into an npm script (isaacs) + +* build: fix add-on loading on freebsd (Ben Noordhuis) + +* build: disable unsafe optimizations (Ben Noordhuis) + +* build: fix spurious mksnapshot crashes for good (Ben Noordhuis) + +* build: speed up genv8constants (Dave Pacheco) + +* fs: make unwatchFile() remove a specific listener (Ben Noordhuis) + +* domain: Remove first arg from intercepted fn (Toshihiro Nakamura) + +* domain: Fix memory leak on error (isaacs) + +* events: Fix memory leak from removeAllListeners (Nathan Rajlich) + +* zlib: Fix memory leak in Unzip class. (isaacs) + +* crypto: Fix memory leak in DecipherUpdate() (Ben Noordhuis) + + +2012.07.09, Version 0.8.2 (Stable), cc6084b9ac5cf1d4fe5e7165b71e8fc05d11be1f + +* npm: Upgrade to 1.1.36 + +* readline: don't use Function#call() (Nathan Rajlich) + +* Code cleanup to pass 'use strict' (Jonas Westerlund) + +* module: add filename to require() json errors (TJ Holowaychuk) + +* readline: fix for unicode prompts (Tim Macfarlane) + +* timers: fix handling of large timeouts (Ben Noordhuis) + +* repl: fix passing an empty line inserting "undefined" into the buffer (Nathan Rajlich) + +* repl: fix crashes when buffering command (Maciej Małecki) + +* build: rename strict_aliasing to node_no_strict_aliasing (Ben Noordhuis) + +* build: disable -fstrict-aliasing for any gcc < 4.6.0 (Ben Noordhuis) + +* build: detect cc version with -dumpversion (Ben Noordhuis) + +* build: handle output of localized gcc or clang (Ben Noordhuis) + +* unix: fix memory corruption in freebsd.c (Ben Noordhuis) + +* unix: fix 'zero handles, one request' busy loop (Ben Noordhuis) + +* unix: fix busy loop on unexpected tcp message (Ben Noordhuis) + +* unix: fix EINPROGRESS busy loop (Ben Noordhuis) + + +2012.06.29, Version 0.8.1 (stable), 2134aa3d5c622fc3c3b02ccb713fcde0e0df479a + +* V8: upgrade to v3.11.10.12 + +* npm: upgrade to v1.1.33 + - Support for parallel use of the cache folder + - Retry on registry timeouts or network failures (Trent Mick) + - Reduce 'engines' failures to a warning + - Use new zsh completion if aviailable (Jeremy Cantrell) + +* Fix #3577 Un-break require('sys') + +* util: speed up formatting of large arrays/objects (Ben Noordhuis) + +* windows: make fs.realpath(Sync) work with UNC paths (Bert Belder) + +* build: fix --shared-v8 option (Ben Noordhuis) + +* doc: `detached` is a boolean (Andreas Madsen) + +* build: use proper python interpreter (Ben Noordhuis) + +* build: expand ~ in `./configure --prefix=~/a/b/c` (Ben Noordhuis) + +* build: handle CC env var with spaces (Gabriel de Perthuis) + +* build: fix V8 build when compiling with gcc 4.5 (Ben Noordhuis) + +* build: fix --shared-v8 option (Ben Noordhuis) + +* windows msi: Fix icon issue which caused huge file size (Bert Belder) + +* unix: assume that dlopen() may clobber dlerror() (Ben Noordhuis) + +* sunos: fix memory corruption bugs (Ben Noordhuis) + +* windows: better (f)utimes and (f)stat (Bert Belder) + + +2012.06.25, Version 0.8.0 (stable), 8b8a7a7f9b41e74e1e810d0330738ad06fc302ec + +* V8: upgrade to v3.11.10.10 + +* npm: Upgrade to 1.1.32 + +* Deprecate iowatcher (Ben Noordhuis) + +* windows: update icon (Bert Belder) + +* http: Hush 'MUST NOT have a body' warnings to debug() (isaacs) + +* Move blog.nodejs.org content into repository (isaacs) + +* Fix #3503: stdin: resume() on pipe(dest) (isaacs) + +* crypto: fix error reporting in SetKey() (Fedor Indutny) + +* Add --no-deprecation and --trace-deprecation command-line flags (isaacs) + +* fs: fix fs.watchFile() (Ben Noordhuis) + +* fs: Fix fs.readfile() on pipes (isaacs) + +* Rename GYP variable node_use_system_openssl to be consistent (Ryan Dahl) + + +2012.06.19, Version 0.7.12 (unstable), a72120190a8ffdbcd3d6ad2a2e6ceecd2087111e + +* npm: Upgrade to 1.1.30 + - Improved 'npm init' + - Fix the 'cb never called' error from 'oudated' and 'update' + - Add --save-bundle|-B config + - Fix isaacs/npm#2465: Make npm script and windows shims cygwin-aware + - Fix isaacs/npm#2452 Use --save(-dev|-optional) in npm rm + - `logstream` option to replace removed `logfd` (Rod Vagg) + - Read default descriptions from README.md files + +* Shims to support deprecated ev_* and eio_* methods (Ben Noordhuis) + +* #3118 net.Socket: Delay pause/resume until after connect (isaacs) + +* #3465 Add ./configure --no-ifaddrs flag (isaacs) + +* child_process: add .stdin stream to forks (Fedor Indutny) + +* build: fix `make install DESTDIR=/path` (Ben Noordhuis) + +* tls: fix off-by-one error in renegotiation check (Ben Noordhuis) + +* crypto: Fix diffie-hellman key generation UTF-8 errors (Fedor Indutny) + +* node: change the constructor name of process from EventEmitter to process (Andreas Madsen) + +* net: Prevent property access throws during close (Reid Burke) + +* querystring: improved speed and code cleanup (Felix Böhm) + +* sunos: fix assertion errors breaking fs.watch() (Fedor Indutny) + +* unix: stat: detect sub-second changes (Ben Noordhuis) + +* add stat() based file watcher (Ben Noordhuis) + + +2012.06.15, Version 0.7.11 (unstable), 5cfe0b86d5be266ef51bbba369c39e412ee51944 + +* V8: Upgrade to v3.11.10 + +* npm: Upgrade to 1.1.26 + +* doc: Improve cross-linking in API docs markdown (Ben Kelly) + +* Fix #3425: removeAllListeners should delete array (Reid Burke) + +* cluster: don't silently drop messages when the write queue gets big (Bert Belder) + +* Add Buffer.concat method (isaacs) + +* windows: make symlinks tolerant to forward slashes (Bert Belder) + +* build: Add node.d and node.1 to installer (isaacs) + +* cluster: rename worker.unqiueID to worker.id (Andreas Madsen) + +* Windows: Enable ETW events on Windows for existing DTrace probes. (Igor Zinkovsky) + +* test: bundle node-weak in test/gc so that it doesn't need to be downloaded (Nathan Rajlich) + +* Make many tests pass on Windows (Bert Belder) + +* Fix #3388 Support listening on file descriptors (isaacs) + +* Fix #3407 Add os.tmpDir() (isaacs) + +* Unbreak the snapshotted build on Windows (Bert Belder) + +* Clean up child_process.kill throws (Bert Belder) + +* crypto: make cipher/decipher accept buffer args (Ben Noordhuis) + + +2012.06.11, Version 0.7.10 (unstable), 12a32a48a30182621b3f8e9b9695d1946b53c131 + +* Roll V8 back to 3.9.24.31 + +* build: x64 target should always pass -m64 (Robert Mustacchi) + +* add NODE_EXTERN to node::Start (Joel Brandt) + +* repl: Warn about running npm commands (isaacs) + +* slab_allocator: fix crash in dtor if V8 is dead (Ben Noordhuis) + +* slab_allocator: fix leak of Persistent handles (Shigeki Ohtsu) + +* windows/msi: add node.js prompt to startmenu (Jeroen Janssen) + +* windows/msi: fix adding node to PATH (Jeroen Janssen) + +* windows/msi: add start menu links when installing (Jeroen Janssen) + +* windows: don't install x64 version into the 'program files (x86)' folder (Matt Gollob) + +* domain: Fix #3379 domain.intercept no longer passes error arg to cb (Marc Harter) + +* fs: make callbacks run in global context (Ben Noordhuis) + +* fs: enable fs.realpath on windows (isaacs) + +* child_process: expose UV_PROCESS_DETACHED as options.detached (Charlie McConnell) + +* child_process: new stdio API for .spawn() method (Fedor Indutny) + +* child_process: spawn().ref() and spawn().unref() (Fedor Indutny) + +* Upgrade npm to 1.1.25 + - Enable npm link on windows + - Properly remove sh-shim on Windows + - Abstract out registry client and logger + + +2012.05.28, Version 0.7.9 (unstable), 782277f11a753ded831439ed826448c06fc0f356 + +* Upgrade V8 to 3.11.1 + +* Upgrade npm to 1.1.23 + +* uv: rework reference counting scheme (Ben Noordhuis) + +* uv: add interface for joining external event loops (Bert Belder) + +* repl, readline: Handle Ctrl+Z and SIGCONT better (Nathan Rajlich) + +* fs: 64bit offsets for fs calls (Igor Zinkovsky) + +* fs: add sync open flags 'rs' and 'rs+' (Kevin Bowman) + +* windows: enable creating directory junctions with fs.symlink (Igor Zinkovsky, Bert Belder) + +* windows: fix fs.lstat to properly detect symlinks. (Igor Zinkovsky) + +* Fix #3270 Escape url.parse delims (isaacs) + +* http: make http.get() accept a URL (Adam Malcontenti-Wilson) + +* Cleanup vm module memory leakage (Marcel Laverdet) + +* Optimize writing strings with Socket.write (Bert Belder) + +* add support for CESU-8 and UTF-16LE encodings (koichik) + +* path: add path.sep to get the path separator. (Yi, EungJun) + +* net, http: add backlog parameter to .listen() (Erik Dubbelboer) + +* debugger: support mirroring Date objects (Fedor Indutny) + +* addon: add AtExit() function (Ben Noordhuis) + +* net: signal localAddress bind failure in connect (Brian Schroeder) + +* util: handle non-string return value in .inspect() (Alex Kocharin) + + +2012.04.18, Version 0.7.8 (unstable), c2b47097c0b483552efc1947c6766fa1128600b6 + +* Upgrade V8 to 3.9.24.9 + +* Upgrade OpenSSL to 1.0.0f + +* Upgrade npm to 1.1.18 + +* Show licenses in Binary installers + +* Domains (isaacs) + +* readline: rename "end" to "close" (Nathan Rajlich) + +* tcp: make getsockname() return address family as string (Shigeki Ohtsu) + +* http, https: fix .setTimeout() (ssuda) + +* os: add cross platform EOL character (Mustansir Golawala) + +* typed arrays: unexport SizeOfArrayElementForType() (Aaron Jacobs) + +* net: honor 'enable' flag in .setNoDelay() (Ben Noordhuis) + +* child_process: emit error when .kill fails (Andreas Madsen) + +* gyp: fix 'argument list too long' build error (Ben Noordhuis) + +* fs.WriteStream: Handle modifications to fs.open (isaacs) + +* repl, readline: Handle newlines better (Nathan Rajlich, Nathan Friedly) + +* build: target OSX 10.5 when building on darwin (Nathan Rajlich) + +* Fix #3052 Handle errors properly in zlib (isaacs) + +* build: add support for DTrace and postmortem (Dave Pacheco) + +* core: add reusable Slab allocator (Ben Noordhuis) + + +2012.03.30, Version 0.7.7 (unstable), 5cda2542fdb086f9fe5de889bea435a65e377dea + +* Upgrade V8 to 3.9.24.7 + +* Upgrade npm to 1.1.15 + +* Handle Emoji characters properly (Erik Corry, Bert Belder) + +* readline: migrate ansi/vt100 logic from tty to readline (Nathan Rajlich) + +* readline: Fix multiline handling (Alex Kocharin) + +* add a -i/--interactive flag to force the REPL (Nathan Rajlich) + +* debugger: add breakOnException command (Fedor Indutny) + +* cluster: kill workers when master dies (Andreas Madsen) + +* cluster: add graceful disconnect support (Andreas Madsen) + +* child_process: Separate 'close' event from 'exit' (Charlie McConnell) + +* typed arrays: add Uint8ClampedArray (Mikael Bourges-Sevenier) + +* buffer: Fix byte alignment issues (Ben Noordhuis, Erik Lundin) + +* tls: fix CryptoStream.setKeepAlive() (Shigeki Ohtsu) + +* Expose http parse error codes (Felix Geisendörfer) + +* events: don't delete the listeners array (Ben Noordhuis, Nathan Rajlich) + +* process: add process.config to view node's ./configure settings (Nathan Rajlich) + +* process: process.execArgv to see node's arguments (Micheil Smith) + +* process: fix process.title setter (Ben Noordhuis) + +* timers: handle negative or non-numeric timeout values (Ben Noordhuis) + + +2012.03.13, Version 0.7.6 (unstable), f06abda6f58e517349d1b63a2cbf5a8d04a03505 + +* Upgrade v8 to 3.9.17 + +* Upgrade npm to 1.1.8 + - Add support for os/cpu fields in package.json (Adam Blackburn) + - Automatically node-gyp packages containing a binding.gyp + - Fix failures unpacking in UNC shares + - Never create un-listable directories + - Handle cases where an optionalDependency fails to build + +* events: newListener emit correct fn when using 'once' (Roly Fentanes) + +* url: Ignore empty port component (Łukasz Walukiewicz) + +* module: replace 'children' array (isaacs) + +* tls: parse multiple values of a key in ssl certificate (Sambasiva Suda) + +* cluster: support passing of named pipes (Ben Noordhuis) + +* Windows: include syscall in fs errors (Bert Belder) + +* http: #2888 Emit end event only once (Igor Zinkovsky) + +* readline: add multiline support (Rlidwka) + +* process: add `process.hrtime()` (Nathan Rajlich) + +* net, http, https: add localAddress option (Dmitry Nizovtsev) + +* addon improvements (Nathan Rajlich) + +* build improvements (Ben Noordhuis, Sadique Ali, T.C. Hollingsworth, Nathan Rajlich) + +* add support for "SEARCH" request methods (Nathan Rajlich) + +* expose the zlib and http_parser version in process.versions (Nathan Rajlich) + + +2012.02.23, Version 0.7.5 (unstable), d384b8b0d2ab7f05465f0a3e15fe20b4e25b5f86 + +* startup speed improvements (Maciej Małecki) + +* crypto: add function getDiffieHellman() (Tomasz Buchert) + +* buffer: support decoding of URL-safe base64 (Ben Noordhuis) + +* Make QueryString.parse() even faster (Brian White) + +* url: decode url entities in auth section (Ben Noordhuis) + +* http: support PURGE request method (Ben Noordhuis) + +* http: Generate Date headers on responses (Mark Nottingham) + +* Fix #2762: Add callback to close function. (Mikeal Rogers) + +* dgram: fix out-of-bound memory read (Ben Noordhuis) + +* repl: add automatic loading of built-in libs (Brandon Benvie) + +* repl: remove double calls where possible (Fedor Indutny) + +* Readline improvements. Related: #2737 #2756 (Colton Baker) + +* build: disable -fomit-frame-pointer on solaris (Dave Pacheco) + +* build: arch detection improvements (Nathan Rajlich) + +* build: Make a fat binary for the OS X `make pkg`. (Nathan Rajlich) + +* jslint src/ and lib/ on 'make test' (isaacs) + + + +2012.02.14, Version 0.7.4 (unstable), de21de920cf93ec40736ada3792a7f85f3eadeda + +* Upgrade V8 to 3.9.5 + +* Upgrade npm to 1.1.1 + +* build: Detect host_arch better (Karl Skomski) + +* debugger: export `debug_port` to `process` (Fedor Indutny) + +* api docs: CSS bug fixes (isaacs) + +* build: use -fPIC for native addons on UNIX (Nathan Rajlich) + +* Re-add top-level v8::Locker (Marcel Laverdet) + +* Move images out of the dist tarballs (isaacs) + +* libuv: Remove uv_export and uv_import (Ben Noordhuis) + +* build: Support x64 build on Windows (Igor Zinkovsky) + + +2012.02.07, Version 0.7.3 (unstable), 99059aad8d654acda4abcfaa68df182b50f2ec90 + +* Upgrade V8 to 3.9.2 + +* Revert support for isolates. (Ben Noordhuis) + +* cluster: Cleanup docs, event handling, and process.disconnect (Andreas Madsen) + +* gyp_addon: link with node.lib on Windows (Nathan Rajlich) + +* http: fix case where http-parser is freed twice (koichik) + +* Windows: disable RTTI and exceptions (Bert Belder) + + +2012.02.01, Version 0.7.2 (unstable), ec79acb3a6166e30f0bf271fbbfda1fb575b3321 + +* Update V8 to 3.8.9 + +* Support for sharing streams across Isolates (Igor Zinkovsky) + +* #2636 - Fix case where http_parsers are freed too early (koichik) + +* url: Support for IPv6 addresses in URLs (Łukasz Walukiewicz) + +* child_process: Add disconnect() method to child processes (Andreas Madsen) + +* fs: add O_EXCL support, exclusive open file (Ben Noordhuis) + +* fs: more specific error messages (Tj Holowaychuk) + +* tty: emit 'unknown' key event if key sequence not found (Dan VerWeire, Nathan Rajlich) + +* build: compile release build too if BUILDTYPE=Debug (Ben Noordhuis) + +* module: fix --debug-brk on symlinked scripts (Fedor Indutny) + +* zlib: fix `Failed to set dictionary` issue (Fedor Indutny) + +* waf: predict target arch for OS X (Fedor Indutny) + + +2012.01.23, Version 0.7.1 (unstable), a74354735ab5d5b0fa35a1e4ff7e653757d2069b + +* Update V8 to 3.8.8 + +* Install node-waf by default (Fedor Indutny) + +* crypto: Add ability to turn off PKCS padding (Ingmar Runge) + +* v8: implement VirtualMemory class on SunOS (Ben Noordhuis) + +* Add cluster.setupMaster (Andreas Madsen) + +* move `path.exists*` to `fs.exists*` (Maciej Małecki) + +* typed arrays: set class name (Ben Noordhuis) + +* libuv bug fixes (Igor Zinkovsky, Ben Noordhuis, Dan VerWeire) + + +2012.01.16, Version 0.7.0 (unstable), 9cc55dca6f67a6096c858b841c677b0593404321 + +* Upgrade V8 to 3.8.6 + +* Use GYP build system on unix (Ben Noordhuis) + +* Experimenetal isolates support (Ben Noordhuis) + +* Improvements to Cluster API (Andreas Madsen) + +* Use isolates for internal debugger (Fedor Indutny) + +* Bug fixes + + +2012.07.10 Version 0.6.20 (maintenance), 952e513379169ec1b40909d1db056e9bf4294899 + +* npm: Upgrade to 1.1.37 (isaacs) + +* benchmark: Backport improvements made in master (isaacs) + +* build: always link with -lz (Trent Mick) + +* core: use proper #include directives (Ben Noordhuis) + +* cluster: don't silently drop messages when the write queue gets big (Bert Belder) + +* windows: don't print error when GetConsoleTitleW returns an empty string (Bert Belder) + + +2012.06.06 Version 0.6.19 (stable), debf552ed2d4a53957446e82ff3c52a8182d5ff4 + +* npm: upgrade to 1.1.24 + +* fs: no end emit after createReadStream.pause() (Andreas Madsen) + +* vm: cleanup module memory leakage (Marcel Laverdet) + +* unix: fix loop starvation under high network load (Ben Noordhuis) + +* unix: remove abort() in ev_unref() (Ben Noordhuis) + +* windows/tty: never report error after forcibly aborting line-buffered read (Bert Belder) + +* windows: skip GetFileAttributes call when opening a file (Bert Belder) + + +2012.05.15 Version 0.6.18 (stable), 4bc1d395de6abed2cf1e4d0b7b3a1480a21c368f + +* windows: skip GetFileAttributes call when opening a file (Bert Belder) + +* crypto: add PKCS12/PFX support (Sambasiva Suda) + +* #3240: child_process: delete NODE_CHANNEL_FD from env in spawn (Ben Noordhuis) + +* windows: add test for path.normalize with UNC paths (Bert Belder) + +* windows: make path.normalize convert all slashes to backslashes (Bert Belder) + +* fs: Automatically close FSWatcher on error (Bert Belder) + +* #3258: fs.ReadStream.pause() emits duplicate data event (koichik) + +* pipe_wrap: don't assert() on pipe accept errors (Ben Noordhuis) + +* Better exception output for module load and process.nextTick (Felix Geisendörfer) + +* zlib: fix error reporting (Ben Noordhuis) + +* http: Don't destroy on timeout (isaacs) + +* #3231: http: Don't try to emit error on a null'ed req object (isaacs) + +* #3236: http: Refactor ClientRequest.onSocket (isaacs) + + +2012.05.04 Version 0.6.17 (stable), 4ced23deaf36493f4303a18f6fdce768c58becc0 + +* Upgrade npm to 1.1.21 + +* uv: Add support for EROFS errors (Ben Noordhuis, Maciej Małecki) + +* uv: Add support for EIO and ENOSPC errors (Fedor Indutny) + +* windows: Add support for EXDEV errors (Bert Belder) + +* http: Fix client memory leaks (isaacs, Vincent Voyer) + +* fs: fix file descriptor leak in sync functions (Ben Noordhuis) + +* fs: fix ReadStream / WriteStream double close bug (Ben Noordhuis) + + +2012.04.30 Version 0.6.16 (stable), a1d193963ddc80a27da5da01b59751e14e33d1d6 + +* Upgrade V8 to 3.6.6.25 + +* Upgrade npm to 1.1.19 + +* Windows: add mappings for UV_ENOENT (Bert Belder) + +* linux: add IN_MOVE_SELF to inotify event mask (Ben Noordhuis) + +* unix: call pipe handle connection cb on accept() error (Ben Noordhuis) + +* unix: handle EWOULDBLOCK (Ben Noordhuis) + +* map EWOULDBLOCK to UV_EAGAIN (Ben Noordhuis) + +* Map ENOMEM to UV_ENOMEM (isaacs) + +* Child process: support the `gid` and `uid` options (Bert Belder) + +* test: cluster: add worker death event test (Ben Noordhuis) + +* typo in node_http_parser (isaacs) + +* http_parser: Eat CRLF between requests, even on connection:close. (Ben Noordhuis) + +* don't check return value of unsetenv (Ben Noordhuis) + + +2012.04.09 Version 0.6.15 (stable), f160a45b254e591eb33716311c92be533c6d86c4 + +* Update npm to 1.1.16 + +* Show licenses in binary installers. + +* unix: add uv_fs_read64, uv_fs_write64 and uv_fs_ftruncate64 (Ben Noordhuis) + +* add 64bit offset fs functions (Igor Zinkovsky) + +* windows: don't report ENOTSOCK when attempting to bind an udp handle twice (Bert Belder) + +* windows: backport pipe-connect-to-file fixes from master (Bert Belder) + +* windows: never call fs event callbacks after closing the watcher (Bert Belder) + +* fs.readFile: don't make the callback before the fd is closed (Bert Belder) + +* windows: use 64bit offsets for uv_fs apis (Igor Zinkovsky) + +* Fix #2061: segmentation fault on OS X due to stat size mismatch (Ben Noordhuis) + + +2012.03.22 Version 0.6.14 (stable), e513ffef7549a56a5af728e1f0c2c0c8f290518a + +* net: don't crash when queued write fails (Igor Zinkovsky) + +* sunos: fix EMFILE on process.memoryUsage() (Bryan Cantrill) + +* crypto: fix compile-time error with openssl 0.9.7e (Ben Noordhuis) + +* unix: ignore ECONNABORTED errors from accept() (Ben Noordhuis) + +* Add UV_ENOSPC and mappings to it (Bert Belder) + +* http-parser: Fix response body is not read (koichik) + +* Upgrade npm to 1.1.12 + - upgrade node-gyp to 0.3.7 + - work around AV-locked directories on Windows + - Fix isaacs/npm#2293 Don't try to 'uninstall' / + - Exclude symbolic links from packages. + - Fix isaacs/npm#2275 Spurious 'unresolvable cycle' error. + - Exclude/include dot files as if they were normal files + + +2012.03.15 Version 0.6.13 (stable), 9f7f86b534f8556290eb8cad915984ff4ca54996 + +* Windows: Many libuv test fixes (Bert Belder) + +* Windows: avoid uv_guess_handle crash in when fd < 0 (Bert Belder) + +* Map EBUSY and ENOTEMPTY errors (Bert Belder) + +* Windows: include syscall in fs errors (Bert Belder) + +* Fix fs.watch ENOSYS on Linux kernel version mismatch (Ben Noordhuis) + +* Update npm to 1.1.9 + - upgrade node-gyp to 0.3.5 (Nathan Rajlich) + - Fix isaacs/npm#2249 Add cache-max and cache-min configs + - Properly redirect across https/http registry requests + - log config usage if undefined key in set function (Kris Windham) + - Add support for os/cpu fields in package.json (Adam Blackburn) + - Automatically node-gyp packages containing a binding.gyp + - Fix failures unpacking in UNC shares + - Never create un-listable directories + - Handle cases where an optionalDependency fails to build + + +2012.03.02 Version 0.6.12 (stable), 48a2d34cfe6b7e1c9d15202a4ef5e3c82d1fba35 + +* Upgrade V8 to 3.6.6.24 + +* dtrace ustack helper improvements (Dave Pacheco) + +* API Documentation refactor (isaacs) + +* #2827 net: fix race write() before and after connect() (koichik) + +* #2554 #2567 throw if fs args for 'start' or 'end' are strings (AJ ONeal) + +* punycode: Update to v1.0.0 (Mathias Bynens) + +* Make a fat binary for the OS X pkg (isaacs) + +* Fix hang on accessing process.stdin (isaacs) + +* repl: make tab completion work on non-objects (Nathan Rajlich) + +* Fix fs.watch on OS X (Ben Noordhuis) + +* Fix #2515 nested setTimeouts cause premature process exit (Ben Noordhuis) + +* windows: fix time conversion in stat (Igor Zinkovsky) + +* windows: fs: handle EOF in read (Brandon Philips) + +* windows: avoid IOCP short-circuit on non-ifs lsps (Igor Zinkovsky) + +* Upgrade npm to 1.1.4 (isaacs) + - windows fixes + - Bundle nested bundleDependencies properly + - install: support --save with url install targets + - shrinkwrap: behave properly with url-installed modules + - support installing uncompressed tars or single file modules from urls etc. + - don't run make clean on rebuild + - support HTTPS-over-HTTP proxy tunneling + + +2012.02.17 Version 0.6.11 (stable), 1eb1fe32250fc88cb5b0a97cddf3e02be02e3f4a + +* http: allow multiple WebSocket RFC6455 headers (Einar Otto Stangvik) + +* http: allow multiple WWW-Authenticate headers (Ben Noordhuis) + +* windows: support unicode argv and environment variables (Bert Belder) + +* tls: mitigate session renegotiation attacks (Ben Noordhuis) + +* tcp, pipe: don't assert on uv_accept() errors (Ben Noordhuis) + +* tls: Allow establishing secure connection on the existing socket (koichik) + +* dgram: handle close of dgram socket before DNS lookup completes (Seth Fitzsimmons) + +* windows: Support half-duplex pipes (Igor Zinkovsky) + +* build: disable omit-frame-pointer on solaris systems (Dave Pacheco) + +* debugger: fix --debug-brk (Ben Noordhuis) + +* net: fix large file downloads failing (koichik) + +* fs: fix ReadStream failure to read from existing fd (Christopher Jeffrey) + +* net: destroy socket on DNS error (Stefan Rusu) + +* dtrace: add missing translator (Dave Pacheco) + +* unix: don't flush tty on switch to raw mode (Ben Noordhuis) + +* windows: reset brightness when reverting to default text color (Bert Belder) + +* npm: update to 1.1.1 + - Update which, fstream, mkdirp, request, and rimraf + - Fix #2123 Set path properly for lifecycle scripts on windows + - Mark the root as seen, so we don't recurse into it. Fixes #1838. (Martin Cooper) + + +2012.02.02, Version 0.6.10 (stable), 051908e023f87894fa68f5b64d0b99a19a7db01e + +* Update V8 to 3.6.6.20 + +* Add npm msysgit bash shim to msi installer (isaacs) + +* buffers: fix intermittent out of bounds error (Ben Noordhuis) + +* buffers: honor length argument in base64 decoder (Ben Noordhuis) + +* windows: Fix path.exists regression (Bert Belder) + +* Make QueryString.parse run faster (Philip Tellis) + +* http: avoid freeing http-parser objects too early (koichik) + +* timers: add v0.4 compatibility hack (Ben Noordhuis) + +* Proper EPERM error code support (Igor Zinkovsky, Brandon Philips) + +* dgram: Implement udp multicast methods on windows (Bert Belder) + + +2012.01.27, Version 0.6.9 (stable), f19e20d33f57c4d2853aaea7d2724d44f3b0012f + +* dgram: Bring back missing functionality for Unix (Dan VerWeire, Roman Shtylman, Ben Noordhuis) + - Note: Windows UDP support not yet complete. + +* http: Fix parser memory leak (koichik) + +* zlib: Fix #2365 crashes on invalid input (Nicolas LaCasse) + +* module: fix --debug-brk on symlinked scripts (Fedor Indutny) + +* Documentation Restyling (Matthew Fitzsimmons) + +* Update npm to 1.1.0-3 (isaacs) + +* Windows: fix regression in stat() calls to C:\ (Bert Belder) + + +2012.01.19, Version 0.6.8 (stable), d18cebaf8a7ac701dabd71a3aa4eb0571db6a645 + +* Update V8 to 3.6.6.19 + +* Numeric key hash collision fix for V8 (Erik Corry, Fedor Indutny) + +* Add missing TTY key translations for F1-F5 on Windows (Brandon Benvie) + +* path.extname bugfix with . and .. paths (Bert Belder) + +* cluster: don't always kill the master on uncaughtException (Ben Noordhuis) + +* Update npm to 1.1.0-2 (isaacs) + +* typed arrays: set class name (Ben Noordhuis) + +* zlib binding cleanup (isaacs, Bert Belder) + +* dgram: use slab memory allocator (Michael Bernstein) + +* fix segfault #2473 + +* #2521 60% improvement in fs.stat on Windows (Igor Zinkovsky) + + +2012.01.06, Version 0.6.7 (stable), d5a189acef14a851287ee555f7a39431fe276e1c + +* V8 hash collision fix (Breaks MIPS) (Bert Belder, Erik Corry) + +* Upgrade V8 to 3.6.6.15 + +* Upgrade npm to 1.1.0-beta-10 (isaacs) + +* many doc updates (Ben Noordhuis, Jeremy Martin, koichik, Dave Irvine, + Seong-Rak Choi, Shannen, Adam Malcontenti-Wilson, koichik) + +* Fix segfault in node_http_parser.cc + +* dgram, timers: fix memory leaks (Ben Noordhuis, Yoshihiro Kikuchi) + +* repl: fix repl.start not passing the `ignoreUndefined` arg (Damon Oehlman) + +* #1980: Socket.pause null reference when called on a closed Stream (koichik) + +* #2263: XMLHttpRequest piped in a writable file stream hang (koichik) + +* #2069: http resource leak (koichik) + +* buffer.readInt global pollution fix (Phil Sung) + +* timers: fix performance regression (Ben Noordhuis) + +* #2308, #2246: node swallows openssl error on request (koichik) + +* #2114: timers: remove _idleTimeout from item in .unenroll() (James Hartig) + +* #2379: debugger: Request backtrace w/o refs (Fedor Indutny) + +* simple DTrace ustack helper (Dave Pacheco) + +* crypto: rewrite HexDecode without snprintf (Roman Shtylman) + +* crypto: don't ignore DH init errors (Ben Noordhuis) + + +2011.12.14, Version 0.6.6 (stable), 9a059ea69e1f6ebd8899246682d8ca257610b8ab + +* npm update to 1.1.0-beta-4 (Isaac Z. Schlueter) + +* cli: fix output of --help (Ben Noordhuis) + +* new website + +* pause/resume semantics for stdin (Isaac Z. Schlueter) + +* Travis CI integration (Maciej Małecki) + +* child_process: Fix bug regarding closed stdin (Ben Noordhuis) + +* Enable upgrades in MSI. (Igor Zinkovsky) + +* net: Fixes memory leak (Ben Noordhuis) + +* fs: handle fractional or NaN ReadStream buffer size (Ben Noordhuis) + +* crypto: fix memory leaks in PBKDF2 error path (Ben Noordhuis) + + +2011.12.04, Version 0.6.5 (stable), 6cc94db653a2739ab28e33b2d6a63c51bd986a9f + +* npm workaround Windows antivirus software (isaacs) + +* Upgrade V8 to 3.6.6.11 + + +2011.12.02, Version 0.6.4 (stable), 9170077f13e5e5475b23d1d3c2e7f69bfe139727 + +* doc improvements (Kyle Young, Tim Oxley, Roman Shtylman, Mathias Bynens) + +* upgrade bundled npm (Isaac Schlueter) + +* polish Windows installer (Igor Zinkovsky, Isaac Schlueter) + +* punycode: upgrade to v0.2.1 (Mathias Bynens) + +* build: add –without-npm flag to configure script + +* sys: deprecate module some more, print stack trace if NODE_DEBUG=sys + +* cli: add -p switch, prints result of –eval + +* #1997: fix Blowfish ECB encryption and decryption (Ingmar Runge) + +* #2223: fix socket ‘close’ event being emitted twice + +* #2224: fix RSS memory usage > 4 GB reporting (Russ Bradberry) + +* #2225: fix util.inspect() object stringification bug (Nathan Rajlich) + + +2011.11.25, Version 0.6.3 (stable), b159c6d62e5756d3f8847419d29c6959ea288b56 + +* #2083 Land NPM in Node. It is included in packages/installers and installed + on `make install`. + +* #2076 Add logos to windows installer. + +* #1711 Correctly handle http requests without headers. (Ben Noordhuis, + Felix Geisendörfer) + +* TLS: expose more openssl SSL context options and constants. (Ben Noordhuis) + +* #2177 Windows: don't kill UDP socket when a packet fails to reach its + destination. (Bert Belder) + +* Windows: support paths longer than 260 characters. (Igor Zinkovsky) + +* Windows: correctly resolve drive-relative paths. (Bert Belder) + +* #2166 Don't leave file descriptor open after lchmod. (Isaac Schlueter) + +* #2084 Add OS X .pkg build script to make file. + +* #2160 Documentation improvements. (Ben Noordhuis) + + +2011.11.18, Version 0.6.2 (stable), a4402f0b2e410b19375a1d5c5fb7fe7f66f3c7f8 + +* doc improvements (Artur Adib, Trevor Burnham, Ryan Emery, Trent Mick) + +* timers: remember extra setTimeout() arguments when timeout==0 + +* punycode: use Mathias Bynens's punycode library, it's more compliant + +* repl: improved tab completion (Ryan Emery) + +* buffer: fix range checks in .writeInt() functions (Lukasz Walukiewicz) + +* tls: make cipher list configurable + +* addons: make Buffer and ObjectWrap visible to Windows add-ons (Bert Belder) + +* crypto: add PKCS#1 a.k.a RSA public key verification support + +* windows: fix stdout writes when redirected to nul + +* sunos: fix build on Solaris and Illumos + +* Upgrade V8 to 3.6.6.8 + + +2011.11.11, Version 0.6.1 (stable), 170f2addb2dd0c625bc4a6d461e89a31ad68b79b + +* doc improvements (Eric Lovett, Ben Noordhuis, Scott Anderson, Yoji SHIDARA) + +* crypto: make thread-safe (Ben Noordhuis) + +* fix process.kill error object + +* debugger: correctly handle source with multi-byte characters (Shigeki Ohtsu) + +* make stdout and stderr non-destroyable (Igor Zinkovsky) + +* fs: don't close uninitialized fs.watch handle (Ben Noordhuis) + +* #2026 fix man page install on BSDs (Ben Noordhuis) + +* #2040 fix unrecognized errno assert in uv_err_name + +* #2043 fs: mkdir() should call callback if mode is omitted + +* #2045 fs: fix fs.realpath on windows to return on error (Benjamin Pasero) + +* #2047 minor cluster improvements + +* #2052 readline get window columns correctly + +* Upgrade V8 to 3.6.6.7 + + +2011.11.04, Version 0.6.0 (stable), 865b077819a9271a29f982faaef99dc635b57fbc + +* print undefined on undefined values in REPL (Nathan Rajlich) + +* doc improvements (koichik, seebees, bnoordhuis, + Maciej Małecki, Jacob Kragh) + +* support native addon loading in windows (Bert Belder) + +* rename getNetworkInterfaces() to networkInterfaces() (bnoordhuis) + +* add pending accepts knob for windows (igorzi) + +* http.request(url.parse(x)) (seebees) + +* #1929 zlib Respond to 'resume' events properly (isaacs) + +* stream.pipe: Remove resume and pause events + +* test fixes for windows (igorzi) + +* build system improvements (bnoordhuis) + +* #1936 tls: does not emit 'end' from EncryptedStream (koichik) + +* #758 tls: add address(), remoteAddress/remotePort + +* #1399 http: emit Error object after .abort() (bnoordhuis) + +* #1999 fs: make mkdir() default to 0777 permissions (bnoordhuis) + +* #2001 fix pipe error codes + +* #2002 Socket.write should reset timeout timer + +* stdout and stderr are blocking when associated with file too. + +* remote debugger support on windows (Bert Belder) + +* convenience methods for zlib (Matt Robenolt) + +* process.kill support on windows (igorzi) + +* process.uptime() support on windows (igorzi) + +* Return IPv4 addresses before IPv6 addresses from getaddrinfo + +* util.inspect improvements (Nathan Rajlich) + +* cluster module api changes + +* Downgrade V8 to 3.6.6.6 + + +2011.10.21, Version 0.5.10 (unstable), 220e61c1f65bf4db09699fcf6399c0809c0bc446 + +* Remove cmake build system, support for Cygwin, legacy code base, + process.ENV, process.ARGV, process.memoryUsage().vsize, os.openOSHandle + +* Documentation improvments (Igor Zinkovsky, Bert Belder, Ilya Dmitrichenko, +koichik, Maciej Małecki, Guglielmo Ferri, isaacs) + +* Performance improvements (Daniel Ennis, Bert Belder, Ben Noordhuis) + +* Long process.title support (Ben Noordhuis) + +* net: register net.Server callback only once (Simen Brekken) + +* net: fix connect queue bugs (Ben Noordhuis) + +* debugger: fix backtrace err handling (Fedor Indutny) + +* Use getaddrinfo instead of c-ares for dns.lookup + +* Emit 'end' from crypto streams on close + +* #1902 buffer: use NO_NULL_TERMINATION flag (koichik) + +* #1907 http: Added support for HTTP PATCH verb (Thomas Parslow) + +* #1644 add GetCPUInfo on windows (Karl Skomski) + +* #1484, #1834, #1482, #771 Don't use a separate context for the repl. + (isaacs) + +* #1882 zlib Update 'availOutBefore' value, and test (isaacs) + +* #1888 child_process.fork: don't modify args (koichik) + +* #1516 tls: requestCert unusable with Firefox and Chrome (koichik) + +* #1467 tls: The TLS API is inconsistent with the TCP API (koichik) + +* #1894 net: fix error handling in listen() (koichik) + +* #1860 console.error now goes through uv_tty_t + +* Upgrade V8 to 3.7.0 + +* Upgrade GYP to r1081 + + +2011.10.10, Version 0.5.9 (unstable), 3bd9b08fb125b606f97a4079b147accfdeebb07d + +* fs.watch interface backed by kqueue, inotify, and ReadDirectoryChangesW + (Igor Zinkovsky, Ben Noordhuis) + +* add dns.resolveTxt (Christian Tellnes) + +* Remove legacy http library (Ben Noordhuis) + +* child_process.fork returns and works on Windows. Allows passing handles. + (Igor Zinkovsky, Bert Belder) + +* #1774 Lint and clean up for --harmony_block_scoping (Tyler Larson, Colton + Baker) + +* #1813 Fix ctrl+c on Windows (Bert Belder) + +* #1844 unbreak --use-legacy (Ben Noordhuis) + +* process.stderr now goes through libuv. Both process.stdout and + process.stderr are blocking when referencing a TTY. + +* net_uv performance improvements (Ben Noordhuis, Bert Belder) + + +2011.09.30, Version 0.5.8 (unstable), 7cc17a0cea1d25188c103745a7d0c24375e3a609 + +* zlib bindings (isaacs) + +* Windows supports TTY ANSI escape codes (Bert Belder) + +* Debugger improvements (Fedor Indutny) + +* crypto: look up SSL errors with ERR_print_errors() (Ben Noordhuis) + +* dns callbacks go through MakeCallback now + +* Raise an error when a malformed package.json file is found. (Ben Leslie) + +* buffers: handle bad length argument in constructor (Ben Noordhuis) + +* #1726, unref process.stdout + +* Doc improvements (Ben Noordhuis, Fedor Indutny, koichik) + +* Upgrade libuv to fe18438 + + +2011.09.16, Version 0.5.7 (unstable), 558241166c4f3c516e5a448e676db0b57119212f + +* Upgrade V8 to 3.6.4 + +* Improve Windows compatibility + +* Documentation improvements + +* Debugger and REPL improvements (Fedor Indutny) + +* Add legacy API support: net.Stream(fd), process.stdout.writable, + process.stdout.fd + +* Fix mkdir EEXIST handling (isaacs) + +* Use net_uv instead of net_legacy for stdio + +* Do not load readline from util.inspect + +* #1673 Fix bug related to V8 context with accessors (Fedor Indutny) + +* #1634 util: Fix inspection for Error (koichik) + +* #1645 fs: Add positioned file writing feature to fs.WriteStream (Thomas + Shinnick) + +* #1637 fs: Unguarded fs.watchFile cache statWatchers checking fixed (Thomas + Shinnick) + +* #1695 Forward customFds to ChildProcess.spawn + +* #1707 Fix hasOwnProperty security problem in querystring (isaacs) + +* #1719 Drain OpenSSL error queue + + +2011.09.08, Version 0.5.6 (unstable), b49bec55806574a47403771bce1ee379c2b09ca2 + +* #345, #1635, #1648 Documentation improvements (Thomas Shinnick, + Abimanyu Raja, AJ ONeal, Koichi Kobayashi, Michael Jackson, Logan Smyth, + Ben Noordhuis) + +* #650 Improve path parsing on windows (Bert Belder) + +* #752 Remove headers sent check in OutgoingMessage.getHeader() + (Peter Lyons) + +* #1236, #1438, #1506, #1513, #1621, #1640, #1647 Libuv-related bugs fixed + (Jorge Chamorro Bieling, Peter Bright, Luis Lavena, Igor Zinkovsky) + +* #1296, #1612 crypto: Fix BIO's usage. (Koichi Kobayashi) + +* #1345 Correctly set socket.remoteAddress with libuv backend (Bert Belder) + +* #1429 Don't clobber quick edit mode on windows (Peter Bright) + +* #1503 Make libuv backend default on unix, override with `node --use-legacy` + +* #1565 Fix fs.stat for paths ending with \ on windows (Igor Zinkovsky) + +* #1568 Fix x509 certificate subject parsing (Koichi Kobayashi) + +* #1586 Make socket write encoding case-insensitive (Koichi Kobayashi) + +* #1591, #1656, #1657 Implement fs in libuv, remove libeio and pthread-win32 + dependency on windows (Igor Zinkovsky, Ben Noordhuis, Ryan Dahl, + Isaac Schlueter) + +* #1592 Don't load-time link against CreateSymbolicLink on windows + (Peter Bright) + +* #1601 Improve API consistency when dealing with the socket underlying a HTTP + client request (Mikeal Rogers) + +* #1610 Remove DigiNotar CA from trusted list (Isaac Schlueter) + +* #1617 Added some win32 os functions (Karl Skomski) + +* #1624 avoid buffer overrun with 'binary' encoding (Koichi Kobayashi) + +* #1633 make Buffer.write() always set _charsWritten (Koichi Kobayashi) + +* #1644 Windows: set executables to be console programs (Peter Bright) + +* #1651 improve inspection for sparse array (Koichi Kobayashi) + +* #1672 set .code='ECONNRESET' on socket hang up errors (Ben Noordhuis) + +* Add test case for foaf+ssl client certificate (Niclas Hoyer) + +* Added RPATH environment variable to override run-time library paths + (Ashok Mudukutore) + +* Added TLS client-side session resumption support (Sean Cunningham) + +* Added additional properties to getPeerCertificate (Nathan Rixham, + Niclas Hoyer) + +* Don't eval repl command twice when an error is thrown (Nathan Rajlich) + +* Improve util.isDate() (Nathan Rajlich) + +* Improvements in libuv backend and bindings, upgrade libuv to + bd6066cb349a9b3a1b0d87b146ddaee06db31d10 + +* Show warning when using lib/sys.js (Maciej Malecki) + +* Support plus sign in url protocol (Maciej Malecki) + +* Upgrade V8 to 3.6.2 + + +2011.08.26, Version 0.5.5 (unstable), d2d53d4bb262f517a227cc178a1648094ba54c20 + +* typed arrays, implementation from Plesk + +* fix IP multicast on SunOS + +* fix DNS lookup order: IPv4 first, IPv6 second (--use-uv only) + +* remove support for UNIX datagram sockets (--use-uv only) + +* UDP support for Windows (Bert Belder) + +* #1572 improve tab completion for objects in the REPL (Nathan Rajlich) + +* #1563 fix buffer overflow in child_process module (reported by Dean McNamee) + +* #1546 fix performance regression in http module (reported by Brian Geffon) + +* #1491 add PBKDF2 crypto support (Glen Low) + +* #1447 remove deprecated http.cat() function (Mikeal Rogers) + +* #1140 fix incorrect dispatch of vm.runInContext's filename argument + (Antranig Basman) + +* #1140 document vm.runInContext() and vm.createContext() (Antranig Basman) + +* #1428 fix os.freemem() on 64 bits freebsd (Artem Zaytsev) + +* #1164 make all DNS lookups async, fixes uncatchable exceptions + (Koichi Kobayashi) + +* fix incorrect ssl shutdown check (Tom Hughes) + +* various cmake fixes (Tom Hughes) + +* improved documentation (Koichi Kobayashi, Logan Smyth, Fedor Indutny, + Mikeal Rogers, Maciej Małecki, Antranig Basman, Mickaël Delahaye) + +* upgrade libuv to commit 835782a + +* upgrade V8 to 3.5.8 + + +2011.08.12, Version 0.5.4 (unstable), cfba1f59224ff8602c3fe9145181cad4c6df89a9 + +* libuv/Windows compatibility improvements + +* Build on Microsoft Visual Studio via GYP. Use generate-projects.bat in the + to build sln files. (Peter Bright, Igor Zinkovsky) + +* Make Mikeal's HTTP agent client the default. Use old HTTP client with + --use-http1 + +* Fixes https host header default port handling. (Mikeal Rogers) + +* #1440 strip byte order marker when loading *.js and *.json files + (Ben Noordhuis) + +* #1434 Improve util.format() compatibility with browser. (Koichi Kobayashi) + +* Provide unchecked uint entry points for integer Buffer.read/writeInt + methods. (Robert Mustacchi) + +* CMake improvements (Tom Huges) + +* Upgrade V8 to 3.5.4. + + +2011.08.01, Version 0.5.3 (unstable), 4585330afef44ddfb6a4054bd9b0f190b352628b + +* Fix crypto encryption/decryption with Base64. (SAWADA Tadashi) + +* #243 Add an optional length argument to Buffer.write() (koichik) + +* #657 convert nonbuffer data to string in fs.writeFile/Sync + (Daniel Pihlström) + +* Add process.features, remove process.useUV (Ben Noordhuis) + +* #324 Fix crypto hmac to accept binary keys + add test cases from rfc 2202 + and 4231 (Stefan Bühler) + +* Add Socket::bytesRead, Socket::bytesWritten (Alexander Uvarov) + +* #572 Don't print result of --eval in CLI (Ben Noordhuis) + +* #1223 Fix http.ClientRequest crashes if end() was called twice (koichik) + +* #1383 Emit 'close' after all connections have closed (Felix Geisendörfer) + +* Add sprintf-like util.format() function (Ben Noordhuis) + +* Add support for TLS SNI (Fedor Indutny) + +* New http agent implementation. Off by default the command line flag + --use-http2 will enable it. "make test-http2" will run the tests + for the new implementation. (Mikeal Rogers) + +* Revert AMD compatibility. (isaacs) + +* Windows: improvements, child_process support. + +* Remove pkg-config file. + +* Fix startup time regressions. + +* doc improvements + + +2011.07.22, Version 0.5.2 (unstable), 08ffce1a00dde1199174b390a64a90b60768ddf5 + +* libuv improvements; named pipe support + +* #1242 check for SSL_COMP_get_compression_methods() (Ben Noordhuis) + +* #1348 remove require.paths (isaacs) + +* #1349 Delimit NODE_PATH with ; on Windows (isaacs) + +* #1335 Remove EventEmitter from C++ + +* #1357 Load json files with require() (isaacs) + +* #1374 fix setting ServerResponse.statusCode in writeHead (Trent Mick) + +* Fixed: GC was being run too often. + +* Upgrade V8 to 3.4.14 + +* doc improvements + + +2011.07.14, Version 0.5.1 (unstable), f8bfa54d0fa509f9242637bef2869a1b1e842ec8 + +* #1233 Fix os.totalmem on FreeBSD amd64 (Artem Zaytsev) + +* #1149 IDNA and Punycode support in url.parse + (Jeremy Selier, Ben Noordhuis, isaacs) + +* Export $CC and $CXX to uv and V8's build systems + +* Include pthread-win32 static libraries in build (Igor Zinkovsky) + +* #1199, #1094 Fix fs can't handle large file on 64bit platform (koichik) + +* #1281 Make require a public member of module (isaacs) + +* #1303 Stream.pipe returns the destination (Elijah Insua) + +* #1229 Addons should not -DEV_MULTIPLICITY=0 (Brian White) + +* libuv backend improvements + +* Upgrade V8 to 3.4.10 + + +2011.07.05, Version 0.5.0 (unstable), ae7ed8482ea7e53c59acbdf3cf0e0a0ae9d792cd + +* New non-default libuv backend to support IOCP on Windows. + Use --use-uv to enable. + +* deprecate http.cat + +* docs improved. + +* add child_process.fork + +* add fs.utimes() and fs.futimes() support (Ben Noordhuis) + +* add process.uptime() (Tom Huges) + +* add path.relative (Tony Huang) + +* add os.getNetworkInterfaces() + +* add remoteAddress and remotePort for client TCP connections + (Brian White) + +* add secureOptions flag, setting ciphers, + SSL_OP_CRYPTOPRO_TLSEXT_BUG to TLS (Theo Schlossnagle) + +* add process.arch (Nathan Rajlich) + +* add reading/writing of floats and doubles from/to buffers (Brian White) + +* Allow script to be read from stdin + +* #477 add Buffer::fill method to do memset (Konstantin Käfer) + +* #573 Diffie-Hellman support to crypto module (Håvard Stranden) + +* #695 add 'hex' encoding to buffer (isaacs) + +* #851 Update how REPLServer uses contexts (Ben Weaver) + +* #853 add fs.lchow, fs.lchmod, fs.fchmod, fs.fchown (isaacs) + +* #889 Allow to remove all EventEmitter listeners at once + (Felix Geisendörfer) + +* #926 OpenSSL NPN support (Fedor Indutny) + +* #955 Change ^C handling in REPL (isaacs) + +* #979 add support for Unix Domain Sockets to HTTP (Mark Cavage) + +* #1173 #1170 add AMD, asynchronous module definition (isaacs) + +* DTrace probes: support X-Forwarded-For (Dave Pacheco) + + +2011.09.15, Version 0.4.12 (stable), 771ba34ca7b839add2ef96879e1ffc684813cf7c + +* Improve docs + +* #1563 overflow in ChildProcess custom_fd. + +* #1569, parse error on multi-line HTTP headers. (Ben Noordhuis) + +* #1586 net: Socket write encoding case sensitivity (koichik) + +* #1610 Remove DigiNotar CA from trusted list (isaacs) + +* #1624 buffer: Avoid overrun with 'binary' encoding. (koichik) + +* #1633 buffer: write() should always set _charsWritten. (koichik) + +* #1707 hasOwnProperty usage security hole in querystring (isaacs) + +* #1719 Drain OpenSSL error queue + +* Fix error reporting in net.Server.listen + + +2011.08.17, Version 0.4.11 (stable), a745d19ce7d1c0e3778371af4f0346be70cf2c8e + +* #738 Fix crypto encryption/decryption with Base64. (SAWADA Tadashi) + +* #1202 net.createConnection defer DNS lookup error events to next tick + (Ben Noordhuis) + +* #1374 fix setting ServerResponse.statusCode in writeHead (Trent Mick) + +* #1417 Fix http.ClientRequest crashes if end() was called twice + +* #1497 querystring: Replace 'in' test with 'hasOwnProperty' (isaacs) + +* #1546 http perf improvement + +* fix memleak in libeio (Tom Hughes) + +* cmake improvements (Tom Hughes) + +* node_net.cc: fix incorrect sizeof() (Tom Hughes) + +* Windows/cygwin: no more GetConsoleTitleW errors on XP (Bert Belder) + +* Doc improvments (koichik, Logan Smyth, Ben Noordhuis, Arnout Kazemier) + + +2011.07.19, Version 0.4.10 (stable), 1b8dd65d6e3b82b6863ef38835cc436c5d30c1d5 + +* #394 Fix Buffer drops last null character in UTF-8 + +* #829 Backport r8577 from V8 (Ben Noordhuis) + +* #877 Don't wait for HTTP Agent socket pool to establish connections. + +* #915 Find kqueue on FreeBSD correctly (Brett Kiefer) + +* #1085 HTTP: Fix race in abort/dispatch code (Stefan Rusu) + +* #1274 debugger improvement (Yoshihiro Kikuchi) + +* #1291 Properly respond to HEAD during end(body) hot path (Reid Burke) + +* #1304 TLS: Fix race in abort/connection code (Stefan Rusu) + +* #1360 Allow _ in url hostnames. + +* Revert 37d529f8 - unbreaks debugger command parsing. + +* Bring back global execScript + +* Doc improvements + + +2011.06.29, Version 0.4.9 (stable), de44eafd7854d06cd85006f509b7051e8540589b + +* Improve documentation + +* #1095 error handling bug in stream.pipe() (Felix Geisendörfer) + +* #1097 Fix a few leaks in node_crypto.cc (Ben Noordhuis) + +* #562 #1078 Parse file:// urls properly (Ryan Petrello) + +* #880 Option to disable SSLv2 (Jérémy Lal) + +* #1087 Disabling SSL compression disabled with early OpenSSLs. + +* #1144 debugger: don't allow users to input non-valid commands + (Siddharth Mahendraker) + +* Perf improvement for util.inherits + +* #1166 Support for signature verification with RSA/DSA public keys + (Mark Cavage) + +* #1177 Remove node_modules lookup optimization to better support + nested project structures (Mathias Buus) + +* #1203 Add missing scope.Close to fs.sendfileSync + +* #1187 Support multiple 'link' headers + +* #1196 Fix -e/--eval can't load module from node_modules (Koichi Kobayashi) + +* Upgrade V8 to 3.1.8.25, upgrade http-parser. + + +2011.05.20, Version 0.4.8 (stable), 7dd22c26e4365698dc3efddf138c4d399cb912c8 + +* #974 Properly report traceless errors (isaacs) + +* #983 Better JSON.parse error detection in REPL (isaacs) + +* #836 Agent socket errors bubble up to req only if req exists + +* #1041 Fix event listener leak check timing (koichik) + +* #1038 Fix dns.resolve() with 'PTR' throws Error: Unknown type "PTR" + (koichik) + +* #1073 Share SSL context between server connections (Fedor Indutny) + +* Disable compression with OpenSSL. Improves memory perf. + +* Implement os.totalmem() and os.freemem() for SunOS (Alexandre Marangone) + +* Fix a special characters in URL regression (isaacs) + +* Fix idle timeouts in HTTPS (Felix Geisendörfer) + +* SlowBuffer.write() with 'ucs2' throws ReferenceError. (koichik) + +* http.ServerRequest 'close' sometimes gets an error argument + (Felix Geisendörfer) + +* Doc improvements + +* cleartextstream.destroy() should close(2) the socket. Previously was being + mapped to a shutdown(2) syscall. + +* No longer compile out asserts and debug statements in normal build. + +* Debugger improvements. + +* Upgrade V8 to 3.1.8.16. + + +2011.04.22, Version 0.4.7 (stable), c85455a954411b38232e79752d4abb61bb75031b + +* Don't emit error on ECONNRESET from read() #670 + +* Fix: Multiple pipes to the same stream were broken #929 + (Felix Geisendörfer) + +* URL parsing/formatting corrections #954 (isaacs) + +* make it possible to do repl.start('', stream) (Wade Simmons) + +* Add os.loadavg for SunOS (Robert Mustacchi) + +* Fix timeouts with floating point numbers #897 (Jorge Chamorro Bieling) + +* Improve docs. + + +2011.04.13, Version 0.4.6 (stable), 58002d56bc79410c5ff397fc0e1ffec0665db38a + +* Don't error on ENOTCONN from shutdown() #670 + +* Auto completion of built-in debugger suggests prefix match rather than + partial match. (koichik) + +* circular reference in vm modules. #822 (Jakub Lekstan) + +* http response.readable should be false after 'end' #867 (Abe Fettig) + +* Implement os.cpus() and os.uptime() on Solaris (Scott McWhirter) + +* fs.ReadStream: Allow omission of end option for range reads #801 + (Felix Geisendörfer) + +* Buffer.write() with UCS-2 should not be write partial char + #916 (koichik) + +* Pass secureProtocol through on tls.Server creation (Theo Schlossnagle) + +* TLS use RC4-SHA by default + +* Don't strangely drop out of event loop on HTTPS client uploads #892 + +* Doc improvements + +* Upgrade v8 to 3.1.8.10 + + +2011.04.01, Version 0.4.5 (stable), 787a343b588de26784fef97f953420b53a6e1d73 + +* Fix listener leak in stream.pipe() (Mikeal Rogers) + +* Retain buffers in fs.read/write() GH-814 (Jorge Chamorro Bieling) + +* TLS performance improvements + +* SlowBuffer.prototype.slice bug GH-843 + +* process.stderr.write should return true + +* Immediate pause/resume race condition GH-535 (isaacs) + +* Set default host header properly GH-721 (isaacs) + +* Upgrade V8 to 3.1.8.8 + + +2011.03.26, Version 0.4.4 (stable), 25122b986a90ba0982697b7abcb0158c302a1019 + +* CryptoStream.end shouldn't throw if not writable GH-820 + +* Drop out if connection destroyed before connect() GH-819 + +* expose https.Agent + +* Correctly setsid in tty.open GH-815 + +* Bug fix for failed buffer construction + +* Added support for removing .once listeners (GH-806) + +* Upgrade V8 to 3.1.8.5 + + +2011.03.18, Version 0.4.3 (stable), c095ce1a1b41ca015758a713283bf1f0bd41e4c4 + +* Don't decrease server connection counter again if destroy() is called more + than once GH-431 (Andreas Reich, Anders Conbere) + +* Documentation improvements (koichik) + +* Fix bug with setMaxListeners GH-682 + +* Start up memory footprint improvement. (Tom Hughes) + +* Solaris improvements. + +* Buffer::Length(Buffer*) should not invoke itself recursively GH-759 (Ben + Noordhuis) + +* TLS: Advertise support for client certs GH-774 (Theo Schlossnagle) + +* HTTP Agent bugs: GH-787, GH-784, GH-803. + +* Don't call GetMemoryUsage every 5 seconds. + +* Upgrade V8 to 3.1.8.3 + + +2011.03.02, Version 0.4.2 (stable), 39280e1b5731f3fcd8cc42ad41b86cdfdcb6d58b + +* Improve docs. + +* Fix process.on edge case with signal event (Alexis Sellier) + +* Pragma HTTP header comma separation + +* In addition to 'aborted' emit 'close' from incoming requests + (Felix Geisendörfer) + +* Fix memleak in vm.runInNewContext + +* Do not cache modules that throw exceptions (Felix Geisendörfer) + +* Build system changes for libnode (Aria Stewart) + +* Read up the prototype of the 'env' object. (Nathan Rajlich) + +* Add 'close' and 'aborted' events to Agent responses + +* http: fix missing 'drain' events (Russell Haering) + +* Fix process.stdout.end() throws ENOTSOCK error. (Koichi Kobayashi) + +* REPL bug fixes (isaacs) + +* node_modules folders should be highest priority (isaacs) + +* URL parse more safely (isaacs) + +* Expose errno with a string for dns/cares (Felix Geisendörfer) + +* Fix tty.setWindowSize + +* spawn: setuid after chdir (isaacs) + +* SIGUSR1 should break the VM without delay + +* Upgrade V8 to 3.1.8. + + +2011.02.19, Version 0.4.1 (stable), e8aef84191bc2c1ba2bcaa54f30aabde7f03769b + +* Fixed field merging with progressive fields on writeHead() + (TJ Holowaychuk) + +* Make the repl respect node_modules folders (isaacs) + +* Fix for DNS fail in HTTP request (Richard Rodger) + +* Default to port 80 for http.request and http.get. + +* Improve V8 support for Cygwin (Bert Belder) + +* Fix fs.open param parsing. (Felix Geisendörfer) + +* Fixed null signal. + +* Fix various HTTP and HTTPS bugs + +* cmake improvements (Tom Hughes) + +* Fix: TLS sockets should not be writable after 'end' + +* Fix os.cpus() on cygwin (Brian White) + +* MinGW: OpenSSL support (Bert Belder) + +* Upgrade V8 to 3.1.5, libev to 4.4. + + +2011.02.10, Version 0.4.0 (stable), eb155ea6f6a6aa341aa8c731dca8da545c6a4008 + +* require() improvements (isaacs) + - understand package.json (isaacs) + - look for 'node_modules' dir + +* cmake fixes (Daniel Gröber) + +* http: fix buffer writes to outgoing messages (Russell Haering) + +* Expose UCS-2 Encoding (Konstantin Käfer) + +* Support strings for octal modes (isaacs) + +* Support array-ish args to Buffer ctor (isaacs) + +* cygwin and mingw improvements (Bert Belder) + +* TLS improvements + +* Fewer syscalls during require (Bert Belder, isaacs) + +* More DTrace probes (Bryan Cantrill, Robert Mustacchi) + +* 'pipe' event on pipe() (Mikeal Rogers) + +* CRL support in TLS (Theo Schlossnagle) + +* HTTP header manipulation methods (Tim Caswell, Charlie Robbins) + +* Upgrade V8 to 3.1.2 + + +2011.02.04, Version 0.3.8 (unstable), 9493b7563bff31525b4080df5aeef09747782d5e + +* Add req.abort() for client side requests. + +* Add exception.code for easy testing: + Example: if (err.code == 'EADDRINUSE'); + +* Add process.stderr. + +* require.main is the main module. (Isaac Schlueter) + +* dgram: setMulticastTTL, setMulticastLoopback and addMembership. + (Joe Walnes) + +* Fix throttling in TLS connections + +* Add socket.bufferSize + +* MinGW improvements (Bert Belder) + +* Upgrade V8 to 3.1.1 + +2011.01.27, Version 0.3.7 (unstable), d8579c6afdbe868de6dffa8db78bbe4ba2d03e0e + +* Expose agent in http and https client. (Mikeal Rogers) + +* Fix bug in http request's end method. (Ali Farhadi) + +* MinGW: better net support (Bert Belder) + +* fs.open should set FD_CLOEXEC + +* DTrace probes (Bryan Cantrill) + +* REPL fixes and improvements (isaacs, Bert Belder) + +* Fix many bugs with legacy http.Client interface + +* Deprecate process.assert. Use require('assert').ok + +* Add callback parameter to socket.setTimeout(). (Ali Farhadi) + +* Fixing bug in http request default encoding (Ali Farhadi) + +* require: A module ID with a trailing slash must be a dir. + (isaacs) + +* Add ext_key_usage to getPeerCertificate (Greg Hughes) + +* Error when child_process.exec hits maxBuffer. + +* Fix option parsing in tls.connect() + +* Upgrade to V8 3.0.10 + + +2011.01.21, Version 0.3.6 (unstable), bb3e71466e5240626d9d21cf791fe43e87d90011 + +* REPL and other improvements on MinGW (Bert Belder) + +* listen/bind errors should close net.Server + +* New HTTP and HTTPS client APIs + +* Upgrade V8 to 3.0.9 + + +2011.01.16, Version 0.3.5 (unstable), b622bc6305e3c675e0edfcdbaa387d849ad0bba0 + +* Built-in debugger improvements. + +* Add setsid, setuid, setgid options to child_process.spawn + (Isaac Schlueter) + +* tty module improvements. + +* Upgrade libev to 4.3, libeio to latest, c-ares to 1.7.4 + +* Allow third party hooks before main module load. + (See 496be457b6a2bc5b01ec13644b9c9783976159b2) + +* Don't stat() on cached modules. (Felix Geisendörfer) + + +2011.01.08, Version 0.3.4 (unstable), 73f53e12e4a5b9ef7dbb4792bd5f8ad403094441 + +* Primordial mingw build (Bert Belder) + +* HTTPS server + +* Built in debugger 'node debug script.js' + +* realpath files during module load (Mihai Călin Bazon) + +* Rename net.Stream to net.Socket (existing name will continue to be + supported) + +* Fix process.platform + + +2011.01.02, Version 0.3.3 (unstable), 57544ba1c54c7d0da890317deeb73076350c5647 + +* TLS improvements. + +* url.parse(url, true) defaults query field to {} (Jeremy Martin) + +* Upgrade V8 to 3.0.4 + +* Handle ECONNABORT properly (Theo Schlossnagle) + +* Fix memory leaks (Tom Hughes) + +* Add os.cpus(), os.freemem(), os.totalmem(), os.loadavg() and other + functions for OSX, Linux, and Cygwin. (Brian White) + +* Fix REPL syntax error bug (GH-543), improve how REPL commands are + evaluated. + +* Use process.stdin instead of process.openStdin(). + +* Disable TLS tests when node doesn't have OpenSSL. + + +2010.12.16, Version 0.3.2 (unstable), 4bb914bde9f3c2d6de00853353b6b8fc9c66143a + +* Rip out the old (broken) TLS implementation introduce new tested + implementation and API. See docs. HTTPS not supported in this release. + +* Introduce 'os' and 'tty' modules. + +* Callback parameters for socket.write() and socket.connect(). + +* Support CNAME lookups in DNS module. (Ben Noordhuis) + +* cmake support (Tom Hughes) + +* 'make lint' + +* oprofile support (./configure --oprofile) + +* Lots of bug fixes, including: + - Memory leak in ChildProcess:Spawn(). (Tom Hughes) + - buffer.slice(0, 0) + - Global variable leaks + - clearTimeouts calling multiple times (Michael W) + - utils.inspect's detection of circular structures (Tim Cooijmans) + - Apple's threaded write()s bug (Jorge Chamorro Bieling) + - Make sure raw mode is disabled when exiting a terminal-based REPL. + (Brian White) + +* Deprecate process.compile, process.ENV + +* Upgrade V8 to 3.0.3, upgrade http-parser. + + +2010.11.16, Version 0.3.1 (unstable), ce9a54aa1fbf709dd30316af8a2f14d83150e947 + +* TLS improvements (Paul Querna) + - Centralize error handling in SecureStream + - Add SecurePair for handling of a ssl/tls stream. + +* New documentation organization (Micheil Smith) + +* allowHalfOpen TCP connections disabled by default. + +* Add C++ API for constructing fast buffer from string + +* Move idle timers into its own module + +* Gracefully handle EMFILE and server.maxConnections + +* make "node --eval" eval in the global scope. + (Jorge Chamorro Bieling) + +* Let exit listeners know the exit code (isaacs) + +* Handle cyclic links smarter in fs.realpath (isaacs) + +* Remove node-repl (just use 'node' without args) + +* Rewrite libeio After callback to use req->result instead of req->errorno + for error checking (Micheil Smith) + +* Remove warning about deprecating 'sys' - too aggressive + +* Make writes to process.env update the real environment. (Ben Noordhuis) + +* Set FD_CLOEXEC flag on stdio FDs before spawning. (Guillaume Tuton) + +* Move ev_loop out of javascript + +* Switch \n with \r\n for all strings printed out. + +* Added support for cross compilation (Rasmus Andersson) + +* Add --profile flag to configure script, enables gprof profiling. + (Ben Noordhuis) + +* writeFileSync could exhibit pathological behavior when a buffer + could not be written to the file in a single write() call. + +* new path.join behavior (isaacs) + - Express desired path.join behavior in tests. + - Update fs.realpath to reflect new path.join behavior + - Update url.resolve() to use new path.join behavior. + +* API: Move process.binding('evals') to require('vm') + +* Fix V8 build on Cygwin (Bert Belder) + +* Add ref to buffer during fs.write and fs.read + +* Fix segfault on test-crypto + +* Upgrade http-parser to latest and V8 to 2.5.3 + + +2010.10.23, Version 0.3.0 (unstable) 1582cfebd6719b2d2373547994b3dca5c8c569c0 + +* Bugfix: Do not spin on accept() with EMFILE + +* Improvements to readline.js (Trent Mick, Johan Euphrosine, Brian White) + +* Safe constructors (missing 'new' doesn't segfault) + +* Fix process.nextTick so thrown errors don't confuse it. + (Benjamin Thomas) + +* Allow Strings for ports on net.Server.listen (Bradley Meck) + +* fs bugfixes (Tj Holowaychuk, Tobie Langel, Marco Rogers, isaacs) + +* http bug fixes (Fedor Indutny, Mikeal Rogers) + +* Faster buffers; breaks C++ API (Tim-Smart, Stéphan Kochen) + +* crypto, tls improvements (Paul Querna) + +* Add lfs flags to node addon script + +* Simpler querystring parsing; breaks API (Peter Griess) + +* HTTP trailers (Mark Nottingham) + +* http 100-continue support (Mark Nottingham) + +* Module system simplifications (Herbert Vojčík, isaacs, Tim-Smart) + - remove require.async + - remove registerExtension, add .extensions + - expose require.resolve + - expose require.cache + - require looks in node_modules folders + +* Add --eval command line option (TJ Holowaychuk) + +* Commas last in sys.inspect + +* Constants moved from process object to require('constants') + +* Fix parsing of linux memory (Vitali Lovich) + +* inspect shows function names (Jorge Chamorro Bieling) + +* uncaughtException corner cases (Felix Geisendörfer) + +* TCP clients now buffer writes before connection + +* Rename sys module to 'util' (Micheil Smith) + +* Properly set stdio handlers to blocking on SIGTERM and SIGINT + (Tom Hughes) + +* Add destroy methods to HTTP messages + +* base64 improvements (isaacs, Jorge Chamorro Bieling) + +* API for defining REPL commands (Sami Samhuri) + +* child_process.exec timeout fix (Aaron Heckmann) + +* Upgrade V8 to 2.5.1, Libev to 4.00, libeio, http-parser + + +2010.08.20, Version 0.2.0, 9283e134e558900ba89d9a33c18a9bdedab07cb9 + +* process.title support for FreeBSD, Macintosh, Linux + +* Fix OpenSSL 100% CPU usage on error (Illarionov Oleg) + +* Implement net.Server.maxConnections. + +* Fix process.platform, add process.version. + +* Add --without-snapshot configure option. + +* Readline REPL improvements (Trent Mick) + +* Bug fixes. + +* Upgrade V8 to 2.3.8 + + +2010.08.13, Version 0.1.104, b14dd49222687c12f3e8eac597cff4f2674f84e8 + +* Various bug fixes (console, querystring, require) + +* Set cwd for child processes (Bert Belder) + +* Tab completion for readline (Trent Mick) + +* process.title getter/setter for OSX, Linux, Cygwin. + (Rasmus Andersson, Bert Belder) + +* Upgrade V8 to 2.3.6 + + +2010.08.04, Version 0.1.103, 0b925d075d359d03426f0b32bb58a5e05825b4ea + +* Implement keep-alive for http.Client (Mikeal Rogers) + +* base64 fixes. (Ben Noordhuis) + +* Fix --debug-brk (Danny Coates) + +* Don't let path.normalize get above the root. (Isaac Schlueter) + +* Allow signals to be used with process.on in addition to + process.addListener. (Brian White) + +* Globalize the Buffer object + +* Use kqueue on recent macintosh builds + +* Fix addrlen for unix_dgram sockets (Benjamin Kramer) + +* Fix stats.isDirectory() and friends (Benjamin Kramer) + +* Upgrade http-parser, V8 to 2.3.5 + + +2010.07.25, Version 0.1.102, 2a4568c85f33869c75ff43ccd30f0ec188b43eab + +* base64 encoding for Buffers. + +* Buffer support for Cipher, Decipher, Hmac, Sign and Verify + (Andrew Naylor) + +* Support for reading byte ranges from files using fs.createReadStream. + (Chandra Sekar) + +* Fix Buffer.toString() on 0-length slices. (Peter Griess) + +* Cache modules based on filename rather than ID (Isaac Schlueter) + +* querystring improvments (Jan Kassens, Micheil Smith) + +* Support DEL in the REPL. (Jérémy Lal) + +* Upgrade http-parser, upgrade V8 to 2.3.2 + + +2010.07.16, Version 0.1.101, 0174ceb6b24caa0bdfc523934c56af9600fa9b58 + +* Added env to child_process.exec (Сергей Крыжановский) + +* Allow modules to optionally be loaded in separate contexts + with env var NODE_MODULE_CONTEXTS=1. + +* setTTL and setBroadcast for dgram (Matt Ranney) + +* Use execPath for default NODE_PATH, not installPrefix + (Isaac Schlueter) + +* Support of console.dir + console.assert (Jerome Etienne) + +* on() as alias to addListener() + +* Use javascript port of Ronn to build docs (Jérémy Lal) + +* Upgrade V8 to 2.3.0 + + +2010.07.03, Version 0.1.100, a6b8586e947f9c3ced180fe68c233d0c252add8b + +* process.execPath (Marshall Culpepper) + +* sys.pump (Mikeal Rogers) + +* Remove ini and mjsunit libraries. + +* Introduce console.log() and friends. + +* Switch order of arguments for Buffer.write (Blake Mizerany) + +* On overlapping buffers use memmove (Matt Ranney) + +* Resolve .local domains with getaddrinfo() + +* Upgrade http-parser, V8 to 2.2.21 + + +2010.06.21, Version 0.1.99, a620b7298f68f68a855306437a3b60b650d61d78 + +* Datagram sockets (Paul Querna) + +* fs.writeFile could not handle utf8 (Felix Geisendörfer) + and now accepts Buffers (Aaron Heckmann) + +* Fix crypto memory leaks. + +* A replacement for decodeURIComponent that doesn't throw. + (Isaac Schlueter) + +* Only concatenate some incoming HTTP headers. (Peter Griess) + +* Upgrade V8 to 2.2.18 + + +2010.06.11, Version 0.1.98, 10d8adb08933d1d4cea60192c2a31c56d896733d + +* Port to Windows/Cygwin (Raffaele Sena) + +* File descriptor passing on unix sockets. (Peter Griess) + +* Simple, builtin readline library. REPL is now entered by + executing "node" without arguments. + +* Add a parameter to spawn() that sets the child's stdio file + descriptors. (Orlando Vazquez) + +* Upgrade V8 to 2.2.16, http-parser fixes, upgrade c-ares to 1.7.3. + + +2010.05.29, Version 0.1.97, 0c1aa36835fa6a3557843dcbc6ed6714d353a783 + +* HTTP throttling: outgoing messages emit 'drain' and write() returns false + when send buffer is full. + +* API: readFileSync without encoding argument now returns a Buffer + +* Improve Buffer C++ API; addons now compile with debugging symbols. + +* Improvements to path.extname() and REPL; add fs.chown(). + +* fs.ReadStream now emits buffers, fs.readFileSync returns buffers. + +* Bugfix: parsing HTTP responses to HEAD requests. + +* Port to OpenBSD. + +* Upgrade V8 to 2.2.12, libeio, http-parser. + + +2010.05.21, Version 0.1.96, 9514a4d5476225e8c8310ce5acae2857033bcaaa + +* Thrown errors in http and socket call back get bubbled up. + +* Add fs.fsync (Andrew Johnston) + +* Bugfix: signal unregistering (Jonas Pfenniger) + +* Added better error messages for async and sync fs calls with paths + (TJ Holowaychuk) + +* Support arrays and strings in buffer constructor. + (Felix Geisendörfer) + +* Fix errno reporting in DNS exceptions. + +* Support buffers in fs.WriteStream.write. + +* Bugfix: Safely decode a utf8 streams that are broken on a multbyte + character (http and net). (Felix Geisendörfer) + +* Make Buffer's C++ constructor public. + +* Deprecate sys.p() + +* FIX path.dirname('/tmp') => '/'. (Jonathan Rentzsch) + + +2010.05.13, Version 0.1.95, 0914d33842976c2c870df06573b68f9192a1fb7a + +* Change GC idle notify so that it runs alongside setInterval + +* Install node_buffer.h on make install + +* fs.readFile returns Buffer by default (Tim Caswell) + +* Fix error reporting in child_process callbacks + +* Better logic for testing if an argument is a port + +* Improve error reporting (single line "node.js:176:9" errors) + +* Bugfix: Some http responses being truncated (appeared in 0.1.94) + +* Fix long standing net idle timeout bugs. Enable 2 minute timeout + by default in HTTP servers. + +* Add fs.fstat (Ben Noordhuis) + +* Upgrade to V8 2.2.9 + + +2010.05.06, Version 0.1.94, f711d5343b29d1e72e87107315708e40951a7826 + +* Look in /usr/local/lib/node for modules, so that there's a way + to install modules globally (Issac Schlueter) + +* SSL improvements (Rhys Jones, Paulo Matias) + +* Added c-ares headers for linux-arm (Jonathan Knezek) + +* Add symbols to release build + +* HTTP upgrade improvements, docs (Micheil Smith) + +* HTTP server emits 'clientError' instead of printing message + +* Bugfix: Don't emit 'error' twice from http.Client + +* Bugfix: Ignore SIGPIPE + +* Bugfix: destroy() instead of end() http connection at end of + pipeline + +* Bugfix: http.Client may be prematurely released back to the + free pool. (Thomas Lee) + +* Upgrade V8 to 2.2.8 + + +2010.04.29, Version 0.1.93, 557ba6bd97bad3afe0f9bd3ac07efac0a39978c1 + + * Fixed no 'end' event on long chunked HTTP messages + https://github.com/joyent/node/issues/77 + + * Remove legacy modules http_old and tcp_old + + * Support DNS MX queries (Jérémy Lal) + + * Fix large socket write (tlb@tlb.org) + + * Fix child process exit codes (Felix Geisendörfer) + + * Allow callers to disable PHP/Rails style parameter munging in + querystring.stringify (Thomas Lee) + + * Upgrade V8 to 2.2.6 + + +2010.04.23, Version 0.1.92, caa828a242f39b6158084ef4376355161c14fe34 + + * OpenSSL support. Still undocumented (see tests). (Rhys Jones) + + * API: Unhandled 'error' events throw. + + * Script class with eval-function-family in binding('evals') plus tests. + (Herbert Vojcik) + + * stream.setKeepAlive (Julian Lamb) + + * Bugfix: Force no body on http 204 and 304 + + * Upgrade Waf to 1.5.16, V8 to 2.2.4.2 + + +2010.04.15, Version 0.1.91, 311d7dee19034ff1c6bc9098c36973b8d687eaba + + * Add incoming.httpVersion + + * Object.prototype problem with C-Ares binding + + * REPL can be run from multiple different streams. (Matt Ranney) + + * After V8 heap is compact, don't use a timer every 2 seconds. + + * Improve nextTick implementation. + + * Add primative support for Upgrading HTTP connections. + (See commit log for docs 760bba5) + + * Add timeout and maxBuffer options to child_process.exec + + * Fix bugs. + + * Upgrade V8 to 2.2.3.1 + + +2010.04.09, Version 0.1.90, 07e64d45ffa1856e824c4fa6afd0442ba61d6fd8 + + * Merge writing of networking system (net2) + - New Buffer object for binary data. + - Support UNIX sockets, Pipes + - Uniform stream API + - Currently no SSL + - Legacy modules can be accessed at 'http_old' and 'tcp_old' + + * Replace udns with c-ares. (Krishna Rajendran) + + * New documentation system using Markdown and Ronn + (Tim Caswell, Micheil Smith) + + * Better idle-time GC + + * Countless small bug fixes. + + * Upgrade V8 to 2.2.X, WAF 1.5.15 + + +2010.03.19, Version 0.1.33, 618296ef571e873976f608d91a3d6b9e65fe8284 + + * Include lib/ directory in node executable. Compile on demand. + + * evalcx clean ups (Isaac Z. Schlueter, Tim-Smart) + + * Various fixes, clean ups + + * V8 upgraded to 2.1.5 + + +2010.03.12, Version 0.1.32, 61c801413544a50000faa7f58376e9b33ba6254f + + * Optimize event emitter for single listener + + * Add process.evalcx, require.registerExtension (Tim Smart) + + * Replace --cflags with --vars + + * Fix bugs in fs.create*Stream (Felix Geisendörfer) + + * Deprecate process.mixin, process.unloop + + * Remove the 'Error: (no message)' exceptions, print stack + trace instead + + * INI parser bug fixes (Isaac Schlueter) + + * FreeBSD fixes (Vanilla Hsu) + + * Upgrade to V8 2.1.3, WAF 1.5.14a, libev + + +2010.03.05, Version 0.1.31, 39b63dfe1737d46a8c8818c92773ef181fd174b3 + + * API: - Move process.watchFile into fs module + - Move process.inherits to sys + + * Improve Solaris port + + * tcp.Connection.prototype.write now returns boolean to indicate if + argument was flushed to the kernel buffer. + + * Added fs.link, fs.symlink, fs.readlink, fs.realpath + (Rasmus Andersson) + + * Add setgid,getgid (James Duncan) + + * Improve sys.inspect (Benjamin Thomas) + + * Allow passing env to child process (Isaac Schlueter) + + * fs.createWriteStream, fs.createReadStream (Felix Geisendörfer) + + * Add INI parser (Rob Ellis) + + * Bugfix: fs.readFile handling encoding (Jacek Becela) + + * Upgrade V8 to 2.1.2 + + +2010.02.22, Version 0.1.30, bb0d1e65e1671aaeb21fac186b066701da0bc33b + + * Major API Changes + + - Promises removed. See + http://groups.google.com/group/nodejs/msg/426f3071f3eec16b + http://groups.google.com/group/nodejs/msg/df199d233ff17efa + The API for fs was + + fs.readdir("/usr").addCallback(function (files) { + puts("/usr files: " + files); + }); + + It is now + + fs.readdir("/usr", function (err, files) { + if (err) throw err; + puts("/usr files: " + files); + }); + + - Synchronous fs operations exposed, use with care. + + - tcp.Connection.prototype.readPause() and readResume() + renamed to pause() and resume() + + - http.ServerResponse.prototype.sendHeader() renamed to + writeHeader(). Now accepts reasonPhrase. + + * Compact garbage on idle. + + * Configurable debug ports, and --debug-brk (Zoran Tomicic) + + * Better command line option parsing (Jeremy Ashkenas) + + * Add fs.chmod (Micheil Smith), fs.lstat (Isaac Z. Schlueter) + + * Fixes to process.mixin (Rasmus Andersson, Benjamin Thomas) + + * Upgrade V8 to 2.1.1 + + +2010.02.17, Version 0.1.29, 87d5e5b316a4276bcf881f176971c1a237dcdc7a + + * Major API Changes + - Remove 'file' module + - require('posix') -----------------> require('fs') + - fs.cat ---------------------------> fs.readFile + - file.write -----------------------> fs.writeFile + - TCP 'receive' event --------------> 'data' + - TCP 'eof' event ------------------> 'end' + - TCP send() -----------------------> write() + - HTTP sendBody() ------------------> write() + - HTTP finish() --------------------> close() + - HTTP 'body' event ----------------> 'data' + - HTTP 'complete' event ------------> 'end' + - http.Client.prototype.close() (formerly finish()) no longer + takes an argument. Add the 'response' listener manually. + - Allow strings for the flag argument to fs.open + ("r", "r+", "w", "w+", "a", "a+") + + * Added multiple arg support for sys.puts(), print(), etc. + (tj@vision-media.ca) + + * sys.inspect(Date) now shows the date value (Mark Hansen) + + * Calculate page size with getpagesize for armel (Jérémy Lal) + + * Bugfix: stderr flushing. + + * Bugfix: Promise late chain (Yuichiro MASUI) + + * Bugfix: wait() on fired promises + (Felix Geisendörfer, Jonas Pfenniger) + + * Bugfix: Use InstanceTemplate() instead of PrototypeTemplate() for + accessor methods. Was causing a crash with Eclipse debugger. + (Zoran Tomicic) + + * Bugfix: Throw from connection.connect if resolving. + (Reported by James Golick) + + +2010.02.09, Version 0.1.28, 49de41ef463292988ddacfb01a20543b963d9669 + + * Use Google's jsmin.py which can be used for evil. + + * Add posix.truncate() + + * Throw errors from server.listen() + + * stdio bugfix (test by Mikeal Rogers) + + * Module system refactor (Felix Geisendörfer, Blaine Cook) + + * Add process.setuid(), getuid() (Michael Carter) + + * sys.inspect refactor (Tim Caswell) + + * Multipart library rewrite (isaacs) + + +2010.02.03, Version 0.1.27, 0cfa789cc530848725a8cb5595224e78ae7b9dd0 + + * Implemented __dirname (Felix Geisendörfer) + + * Downcase process.ARGV, process.ENV, GLOBAL + (now process.argv, process.env, global) + + * Bug Fix: Late promise promise callbacks firing + (Felix Geisendörfer, Jonas Pfenniger) + + * Make assert.AssertionError instance of Error + + * Removed inline require call for querystring + (self@cloudhead.net) + + * Add support for MX, TXT, and SRV records in DNS module. + (Blaine Cook) + + * Bugfix: HTTP client automatically reconnecting + + * Adding OS X .dmg build scripts. (Standa Opichal) + + * Bugfix: ObjectWrap memory leak + + * Bugfix: Multipart handle Content-Type headers with charset + (Felix Geisendörfer) + + * Upgrade http-parser to fix header overflow attack. + + * Upgrade V8 to 2.1.0 + + * Various other bug fixes, performance improvements. + + +2010.01.20, Version 0.1.26, da00413196e432247346d9e587f8c78ce5ceb087 + + * Bugfix, HTTP eof causing crash (Ben Williamson) + + * Better error message on SyntaxError + + * API: Move Promise and EventEmitter into 'events' module + + * API: Add process.nextTick() + + * Allow optional params to setTimeout, setInterval + (Micheil Smith) + + * API: change some Promise behavior (Felix Geisendörfer) + - Removed Promise.cancel() + - Support late callback binding + - Make unhandled Promise errors throw an exception + + * Upgrade V8 to 2.0.6.1 + + * Solaris port (Erich Ocean) + + +2010.01.09, Version 0.1.25, 39ca93549af91575ca9d4cbafd1e170fbcef3dfa + + * sys.inspect() improvements (Tim Caswell) + + * path module improvements (isaacs, Benjamin Thomas) + + * API: request.uri -> request.url + It is no longer an object, but a string. The 'url' module + was addded to parse that string. That is, node no longer + parses the request URL automatically. + + require('url').parse(request.url) + + is roughly equivlent to the old request.uri object. + (isaacs) + + * Bugfix: Several libeio related race conditions. + + * Better errors for multipart library (Felix Geisendörfer) + + * Bugfix: Update node-waf version to 1.5.10 + + * getmem for freebsd (Vanilla Hsu) + + +2009.12.31, Version 0.1.24, 642c2773a7eb2034f597af1cd404b9e086b59632 + + * Bugfix: don't chunk responses to HTTP/1.0 clients, even if + they send Connection: Keep-Alive (e.g. wget) + + * Bugfix: libeio race condition + + * Bugfix: Don't segfault on unknown http method + + * Simplify exception reporting + + * Upgrade V8 to 2.0.5.4 + + +2009.12.22, Version 0.1.23, f91e347eeeeac1a8bd6a7b462df0321b60f3affc + + * Bugfix: require("../blah") issues (isaacs) + + * Bugfix: posix.cat (Jonas Pfenniger) + + * Do not pause request for multipart parsing (Felix Geisendörfer) + + +2009.12.19, Version 0.1.22, a2d809fe902f6c4102dba8f2e3e9551aad137c0f + + * Bugfix: child modules get wrong id with "index.js" (isaacs) + + * Bugfix: require("../foo") cycles (isaacs) + + * Bugfix: require() should throw error if module does. + + * New URI parser stolen from Narwhal (isaacs) + + * Bugfix: correctly check kqueue and epoll. (Rasmus Andersson) + + * Upgrade WAF to 1.5.10 + + * Bugfix: posix.statSync() was crashing + + * Statically define string symbols for performance improvement + + * Bugfix: ARGV[0] weirdness + + * Added superCtor to ctor.super_ instead superCtor.prototype. + (Johan Dahlberg) + + * http-parser supports webdav methods + + * API: http.Client.prototype.request() (Christopher Lenz) + + +2009.12.06, Version 0.1.21, c6affb64f96a403a14d20035e7fbd6d0ce089db5 + + * Feature: Add HTTP client TLS support (Rhys Jones) + + * Bugfix: use --jobs=1 with WAF + + * Bugfix: Don't use chunked encoding for 1.0 requests + + * Bugfix: Duplicated header weren't handled correctly + + * Improve sys.inspect (Xavier Shay) + + * Upgrade v8 to 2.0.3 + + * Use CommonJS assert API (Felix Geisendörfer, Karl Guertin) + + +2009.11.28, Version 0.1.20, aa42c6790da8ed2cd2b72051c07f6251fe1724d8 + + * Add gnutls version to configure script + + * Add V8 heap info to process.memoryUsage() + + * process.watchFile callback has 2 arguments with the stat object + (choonkeat@gmail.com) + + +2009.11.28, Version 0.1.19, 633d6be328708055897b72327b88ac88e158935f + + * Feature: Initial TLS support for TCP servers and clients. + (Rhys Jones) + + * Add options to process.watchFile() + + * Add process.umask() (Friedemann Altrock) + + * Bugfix: only detach timers when active. + + * Bugfix: lib/file.js write(), shouldn't always emit errors or success + (onne@onnlucky.com) + + * Bugfix: Memory leak in fs.write + (Reported by onne@onnlucky.com) + + * Bugfix: Fix regular expressions detecting outgoing message headers. + (Reported by Elliott Cable) + + * Improvements to Multipart parser (Felix Geisendörfer) + + * New HTTP parser + + * Upgrade v8 to 2.0.2 + + +2009.11.17, Version 0.1.18, 027829d2853a14490e6de9fc5f7094652d045ab8 + + * Feature: process.watchFile() process.unwatchFile() + + * Feature: "uncaughtException" event on process + (Felix Geisendörfer) + + * Feature: 'drain' event to tcp.Connection + + * Bugfix: Promise.timeout() blocked the event loop + (Felix Geisendörfer) + + * Bugfix: sendBody() and chunked utf8 strings + (Felix Geisendörfer) + + * Supply the strerror as a second arg to the tcp.Connection close + event (Johan Sørensen) + + * Add EventEmitter.removeListener (frodenius@gmail.com) + + * Format JSON for inspecting objects (Felix Geisendörfer) + + * Upgrade libev to latest CVS + + +2009.11.07, Version 0.1.17, d1f69ef35dac810530df8249d523add168e09f03 + + * Feature: process.chdir() (Brandon Beacher) + + * Revert http parser upgrade. (b893859c34f05db5c45f416949ebc0eee665cca6) + Broke keep-alive. + + * API: rename process.inherits to sys.inherits + + +2009.11.03, Version 0.1.16, 726865af7bbafe58435986f4a193ff11c84e4bfe + + * API: Use CommonJS-style module requiring + - require("/sys.js") becomes require("sys") + - require("circle.js") becomes require("./circle") + - process.path.join() becomes require("path").join() + - __module becomes module + + * API: Many namespacing changes + - Move node.* into process.* + - Move node.dns into module "dns" + - Move node.fs into module "posix" + - process is no longer the global object. GLOBAL is. + + For more information on the API changes see: + http://thread.gmane.org/gmane.comp.lang.javascript.nodejs/6 + http://thread.gmane.org/gmane.comp.lang.javascript.nodejs/14 + + * Feature: process.platform, process.memoryUsage() + + * Feature: promise.cancel() (Felix Geisendörfer) + + * Upgrade V8 to 1.3.18 + + +2009.10.28, Version 0.1.15, eca2de73ed786b935507fd1c6faccd8df9938fd3 + + * Many build system fixes (esp. for OSX users) + + * Feature: promise.timeout() (Felix Geisendörfer) + + * Feature: Added external interface for signal handlers, process.pid, and + process.kill() (Brandon Beacher) + + * API: Rename node.libraryPaths to require.paths + + * Bugfix: 'data' event for stdio should emit a string + + * Large file support + + * Upgrade http_parser + + * Upgrade v8 to 1.3.16 + + +2009.10.09, Version 0.1.14, b12c809bb84d1265b6a4d970a5b54ee8a4890513 + + * Feature: Improved addon builds with node-waf + + * Feature: node.SignalHandler (Brandon Beacher) + + * Feature: Enable V8 debugging (but still need to make a debugger) + + * API: Rename library /utils.js to /sys.js + + * Clean up Node's build system + + * Don't use parseUri for HTTP server + + * Remove node.pc + + * Don't use /bin/sh to create child process except with exec() + + * API: Add __module to reference current module + + * API: Remove include() add node.mixin() + + * Normalize http headers; "Content-Length" becomes "content-length" + + * Upgrade V8 to 1.3.15 + + +2009.09.30, Version 0.1.13, 58493bb05b3da3dc8051fabc0bdea9e575c1a107 + + * Feature: Multipart stream parser (Felix Geisendörfer) + + * API: Move node.puts(), node.exec() and others to /utils.js + + * API: Move http, tcp libraries to /http.js and /tcp.js + + * API: Rename node.exit() to process.exit() + + * Bugfix: require() and include() should work in callbacks. + + * Pass the Host header in http.cat calls + + * Add warning when coroutine stack size grows too large. + + * Enhance repl library (Ray Morgan) + + * Bugfix: build script for + GCC 4.4 (removed -Werror in V8), + on Linux 2.4, + and with Python 2.4.4. + + * Add read() and write() to /file.js to read and write + whole files at once. + + +2009.09.24, Version 0.1.12, 2f56ccb45e87510de712f56705598b3b4e3548ec + + * Feature: System modules, node.libraryPaths + + * API: Remove "raw" encoding, rename "raws" to "binary". + + * API: Added connection.setNoDElay() to disable Nagle algo. + + * Decrease default TCP server backlog to 128 + + * Bugfix: memory leak involving node.fs.* methods. + + * Upgrade v8 to 1.3.13 + + +2009.09.18, Version 0.1.11, 5ddc4f5d0c002bac0ae3d62fc0dc58f0d2d83ec4 + + * API: default to utf8 encoding for node.fs.cat() + + * API: add node.exec() + + * API: node.fs.read() takes a normal encoding parameter. + + * API: Change arguments of emit(), emitSuccess(), emitError() + + * Bugfix: node.fs.write() was stack allocating buffer. + + * Bugfix: ReportException shouldn't forget the top frame. + + * Improve buffering for HTTP outgoing messages + + * Fix and reenable x64 macintosh build. + + * Upgrade v8 to 1.3.11 + + +2009.09.11, Version 0.1.10, 12bb0d46ce761e3d00a27170e63b40408c15b558 + + * Feature: raw string encoding "raws" + + * Feature: access to environ through "ENV" + + * Feature: add isDirectory, isFile, isSocket, ... methods + to stats object. + + * Bugfix: Internally use full paths when loading modules + this fixes a shebang loading problem. + + * Bugfix: Add '--' command line argument for seperating v8 + args from program args. + + * Add man page. + + * Add node-repl + + * Upgrade v8 to 1.3.10 + +2009.09.05, Version 0.1.9, d029764bb32058389ecb31ed54a5d24d2915ad4c + + * Bugfix: Compile on Snow Leopard. + + * Bugfix: Malformed URIs raising exceptions. + +2009.09.04, Version 0.1.8, e6d712a937b61567e81b15085edba863be16ba96 + + * Feature: External modules + + * Feature: setTimeout() for node.tcp.Connection + + * Feature: add node.cwd(), node.fs.readdir(), node.fs.mkdir() + + * Bugfix: promise.wait() releasing out of order. + + * Bugfix: Asyncly do getaddrinfo() on Apple. + + * Disable useless evcom error messages. + + * Better stack traces. + + * Built natively on x64. + + * Upgrade v8 to 1.3.9 + +2009.08.27, Version 0.1.7, f7acef9acf8ba8433d697ad5ed99d2e857387e4b + + * Feature: global 'process' object. Emits "exit". + + * Feature: promise.wait() + + * Feature: node.stdio + + * Feature: EventEmitters emit "newListener" when listeners are + added + + * API: Use flat object instead of array-of-arrays for HTTP + headers. + + * API: Remove buffered file object (node.File) + + * API: require(), include() are synchronous. (Uses + continuations.) + + * API: Deprecate onLoad and onExit. + + * API: Rename node.Process to node.ChildProcess + + * Refactor node.Process to take advantage of evcom_reader/writer. + + * Upgrade v8 to 1.3.7 + +2009.08.22, Version 0.1.6, 9c97b1db3099d61cd292aa59ec2227a619f3a7ab + + * Bugfix: Ignore SIGPIPE. + +2009.08.21, Version 0.1.5, b0fd3e281cb5f7cd8d3a26bd2b89e1b59998e5ed + + * Bugfix: Buggy connections could crash node.js. Now check + connection before sending data every time (Kevin van Zonneveld) + + * Bugfix: stdin fd (0) being ignored by node.File. (Abe Fettig) + + * API: Remove connnection.fullClose() + + * API: Return the EventEmitter from addListener for chaining. + + * API: tcp.Connection "disconnect" event renamed to "close" + + * Upgrade evcom + Upgrade v8 to 1.3.6 + +2009.08.13, Version 0.1.4, 0f888ed6de153f68c17005211d7e0f960a5e34f3 + + * Major refactor to evcom. + + * Enable test-tcp-many-clients. + + * Add -m32 gcc flag to udns. + + * Add connection.readPause() and connection.readResume() + Add IncomingMessage.prototype.pause() and resume(). + + * Fix http benchmark. Wasn't correctly dispatching. + + * Bugfix: response.setBodyEncoding("ascii") not working. + + * Bugfix: Negative ints in HTTP's on_body and node.fs.read() + + * Upgrade v8 to 1.3.4 + Upgrade libev to 3.8 + Upgrade http_parser to v0.2 + +2009.08.06, Version 0.1.3, 695f0296e35b30cf8322fd1bd934810403cca9f3 + + * Upgrade v8 to 1.3.2 + + * Bugfix: node.http.ServerRequest.setBodyEncoding('ascii') not + working + + * Bugfix: node.encodeUtf8 was broken. (Connor Dunn) + + * Add ranlib to udns Makefile. + + * Upgrade evcom - fix accepting too many connections issue. + + * Initial support for shebang + + * Add simple command line switches + + * Add node.version API + + +2009.08.01, Version 0.1.2, 025a34244d1cea94d6d40ad7bf92671cb909a96c + + * Add DNS API + + * node.tcp.Server's backlog option is now an argument to listen() + + * Upgrade V8 to 1.3.1 + + * Bugfix: Default to chunked for client requests without + Content-Length. + + * Bugfix: Line numbers in stack traces. + + * Bugfix: negative integers in raw encoding stream + + * Bugfix: node.fs.File was not passing args to promise callbacks. + + +2009.07.27, Version 0.1.1, 77d407df2826b20e9177c26c0d2bb4481e497937 + + * Simplify and clean up ObjectWrap. + + * Upgrade liboi (which is now called evcom) + Upgrade libev to 3.7 + Upgrade V8 to 1.2.14 + + * Array.prototype.encodeUtf8 renamed to node.encodeUtf8(array) + + * Move EventEmitter.prototype.emit() completely into C++. + + * Bugfix: Fix memory leak in event emitters. + http://groups.google.com/group/nodejs/browse_thread/thread/a8d1dfc2fd57a6d1 + + * Bugfix: Had problems reading scripts with non-ascii characters. + + * Bugfix: Fix Detach() in node::Server + + * Bugfix: Sockets not properly reattached if reconnected during + disconnect event. + + * Bugfix: Server-side clients not attached between creation and + on_connect. + + * Add 'close' event to node.tcp.Server + + * Simplify and clean up http.js. (Takes more advantage of event + infrastructure.) + + * Add benchmark scripts. Run with "make benchmark". + + +2009.06.30, Version 0.1.0, 0fe44d52fe75f151bceb59534394658aae6ac328 + + * Update documentation, use asciidoc. + + * EventEmitter and Promise interfaces. (Breaks previous API.) + + * Remove node.Process constructor in favor of node.createProcess + + * Add -m32 flags for compiling on x64 platforms. + (Thanks to András Bártházi) + + * Upgrade v8 to 1.2.10 and libev to 3.6 + + * Bugfix: Timer::RepeatSetter wasn't working. + + * Bugfix: Spawning many processes in a loop + (reported by Felix Geisendörfer) + + +2009.06.24, Version 0.0.6, fbe0be19ebfb422d8fa20ea5204c1713e9214d5f + + * Load modules via HTTP URLs (Urban Hafner) + + * Bugfix: Add HTTPConnection->size() and HTTPServer->size() + + * New node.Process API + + * Clean up build tools, use v8's test runner. + + * Use ev_unref() instead of starting/stopping the eio thread + pool watcher. + + +2009.06.18, Version 0.0.5, 3a2b41de74b6c343b8464a68eff04c4bfd9aebea + + * Support for IPv6 + + * Remove namespace node.constants + + * Upgrade v8 to 1.2.8.1 + + * Accept ports as strings in the TCP client and server. + + * Bugfix: HTTP Client race + + * Bugfix: freeaddrinfo() wasn't getting called after + getaddrinfo() for TCP servers + + * Add "opening" to TCP client readyState + + * Add remoteAddress to TCP client + + * Add global print() function. + + +2009.06.13, Version 0.0.4, 916b9ca715b229b0703f0ed6c2fc065410fb189c + + * Add interrupt() method to server-side HTTP requests. + + * Bugfix: onBodyComplete was not getting called on server-side + HTTP + + +2009.06.11, Version 0.0.3, 6e0dfe50006ae4f5dac987f055e0c9338662f40a + + * Many bug fixes including the problem with http.Client on + macintosh + + * Upgrades v8 to 1.2.7 + + * Adds onExit hook + + * Guard against buffer overflow in http parser + + * require() and include() now need the ".js" extension + + * http.Client uses identity transfer encoding by default. diff --git a/node-v0.8.14/LICENSE b/node-v0.8.14/LICENSE new file mode 100644 index 0000000..adc86f2 --- /dev/null +++ b/node-v0.8.14/LICENSE @@ -0,0 +1,603 @@ +Node's license follows: + +==== + +Copyright Joyent, Inc. and other Node contributors. All rights reserved. +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to +deal in the Software without restriction, including without limitation the +rights to use, copy, modify, merge, publish, distribute, sublicense, and/or +sell copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS +IN THE SOFTWARE. + +==== + +This license applies to all parts of Node that are not externally +maintained libraries. The externally maintained libraries used by Node are: + +- V8, located at deps/v8. V8's license follows: + """ + This license applies to all parts of V8 that are not externally + maintained libraries. The externally maintained libraries used by V8 + are: + + - PCRE test suite, located in + test/mjsunit/third_party/regexp-pcre.js. This is based on the + test suite from PCRE-7.3, which is copyrighted by the University + of Cambridge and Google, Inc. The copyright notice and license + are embedded in regexp-pcre.js. + + - Layout tests, located in test/mjsunit/third_party. These are + based on layout tests from webkit.org which are copyrighted by + Apple Computer, Inc. and released under a 3-clause BSD license. + + - Strongtalk assembler, the basis of the files assembler-arm-inl.h, + assembler-arm.cc, assembler-arm.h, assembler-ia32-inl.h, + assembler-ia32.cc, assembler-ia32.h, assembler-x64-inl.h, + assembler-x64.cc, assembler-x64.h, assembler-mips-inl.h, + assembler-mips.cc, assembler-mips.h, assembler.cc and assembler.h. + This code is copyrighted by Sun Microsystems Inc. and released + under a 3-clause BSD license. + + - Valgrind client API header, located at third_party/valgrind/valgrind.h + This is release under the BSD license. + + These libraries have their own licenses; we recommend you read them, + as their terms may differ from the terms below. + + Copyright 2006-2012, the V8 project authors. All rights reserved. + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are + met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above + copyright notice, this list of conditions and the following + disclaimer in the documentation and/or other materials provided + with the distribution. + * Neither the name of Google Inc. nor the names of its + contributors may be used to endorse or promote products derived + from this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + """ + +- libev, located at deps/uv/src/unix/ev. libev's license follows: + """ + All files in libev are Copyright (C)2007,2008,2009 Marc Alexander Lehmann. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are + met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + * Redistributions in binary form must reproduce the above + copyright notice, this list of conditions and the following + disclaimer in the documentation and/or other materials provided + with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + Alternatively, the contents of this package may be used under the terms + of the GNU General Public License ("GPL") version 2 or any later version, + in which case the provisions of the GPL are applicable instead of the + above. If you wish to allow the use of your version of this package only + under the terms of the GPL and not to allow others to use your version of + this file under the BSD license, indicate your decision by deleting the + provisions above and replace them with the notice and other provisions + required by the GPL in this and the other files of this package. If you do + not delete the provisions above, a recipient may use your version of this + file under either the BSD or the GPL. + """ + +- libeio, located at deps/uv/src/unix/eio. libeio's license follows: + """ + All files in libeio are Copyright (C)2007,2008 Marc Alexander Lehmann. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are + met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + * Redistributions in binary form must reproduce the above + copyright notice, this list of conditions and the following + disclaimer in the documentation and/or other materials provided + with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + Alternatively, the contents of this package may be used under the terms + of the GNU General Public License ("GPL") version 2 or any later version, + in which case the provisions of the GPL are applicable instead of the + above. If you wish to allow the use of your version of this package only + under the terms of the GPL and not to allow others to use your version of + this file under the BSD license, indicate your decision by deleting the + provisions above and replace them with the notice and other provisions + required by the GPL in this and the other files of this package. If you do + not delete the provisions above, a recipient may use your version of this + file under either the BSD or the GPL. + """ + +- WAF build system, located at tools/waf*. WAF's license follows: + """ + Copyright Thomas Nagy, 2005-2011 + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + + 1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + 3. The name of the author may not be used to endorse or promote products + derived from this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHOR "AS IS" AND ANY EXPRESS OR + IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, + INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, + STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + POSSIBILITY OF SUCH DAMAGE. + """ + +- C-Ares, an asynchronous DNS client, located at deps/uv/src/ares. C-Ares license + follows: + """ + /* Copyright 1998 by the Massachusetts Institute of Technology. + * + * Permission to use, copy, modify, and distribute this + * software and its documentation for any purpose and without + * fee is hereby granted, provided that the above copyright + * notice appear in all copies and that both that copyright + * notice and this permission notice appear in supporting + * documentation, and that the name of M.I.T. not be used in + * advertising or publicity pertaining to distribution of the + * software without specific, written prior permission. + * M.I.T. makes no representations about the suitability of + * this software for any purpose. It is provided "as is" + * without express or implied warranty. + """ + +- OpenSSL located at deps/openssl. OpenSSL is cryptographic software written + by Eric Young (eay@cryptsoft.com) to provide SSL/TLS encryption. OpenSSL's + license follows: + """ + /* ==================================================================== + * Copyright (c) 1998-2011 The OpenSSL Project. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. All advertising materials mentioning features or use of this + * software must display the following acknowledgment: + * "This product includes software developed by the OpenSSL Project + * for use in the OpenSSL Toolkit. (http://www.openssl.org/)" + * + * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to + * endorse or promote products derived from this software without + * prior written permission. For written permission, please contact + * openssl-core@openssl.org. + * + * 5. Products derived from this software may not be called "OpenSSL" + * nor may "OpenSSL" appear in their names without prior written + * permission of the OpenSSL Project. + * + * 6. Redistributions of any form whatsoever must retain the following + * acknowledgment: + * "This product includes software developed by the OpenSSL Project + * for use in the OpenSSL Toolkit (http://www.openssl.org/)" + * + * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY + * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR + * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, + * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * ==================================================================== + * + * This product includes cryptographic software written by Eric Young + * (eay@cryptsoft.com). This product includes software written by Tim + * Hudson (tjh@cryptsoft.com). + * + */ + """ + +- HTTP Parser, located at deps/http_parser. HTTP Parser's license follows: + """ + http_parser.c is based on src/http/ngx_http_parse.c from NGINX copyright + Igor Sysoev. + + Additional changes are licensed under the same terms as NGINX and + copyright Joyent, Inc. and other Node contributors. All rights reserved. + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to + deal in the Software without restriction, including without limitation the + rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + sell copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + IN THE SOFTWARE. + """ + +- Closure Linter is located at tools/closure_linter. Closure's license + follows: + """ + # Copyright (c) 2007, Google Inc. + # All rights reserved. + # + # Redistribution and use in source and binary forms, with or without + # modification, are permitted provided that the following conditions are + # met: + # + # * Redistributions of source code must retain the above copyright + # notice, this list of conditions and the following disclaimer. + # * Redistributions in binary form must reproduce the above + # copyright notice, this list of conditions and the following disclaimer + # in the documentation and/or other materials provided with the + # distribution. + # * Neither the name of Google Inc. nor the names of its + # contributors may be used to endorse or promote products derived from + # this software without specific prior written permission. + # + # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + """ + +- tools/cpplint.py is a C++ linter. Its license follows: + """ + # Copyright (c) 2009 Google Inc. All rights reserved. + # + # Redistribution and use in source and binary forms, with or without + # modification, are permitted provided that the following conditions are + # met: + # + # * Redistributions of source code must retain the above copyright + # notice, this list of conditions and the following disclaimer. + # * Redistributions in binary form must reproduce the above + # copyright notice, this list of conditions and the following disclaimer + # in the documentation and/or other materials provided with the + # distribution. + # * Neither the name of Google Inc. nor the names of its + # contributors may be used to endorse or promote products derived from + # this software without specific prior written permission. + # + # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + """ + +- lib/buffer_ieee754.js. Its license follows: + """ + // Copyright (c) 2008, Fair Oaks Labs, Inc. + // All rights reserved. + // + // Redistribution and use in source and binary forms, with or without + // modification, are permitted provided that the following conditions are met: + // + // * Redistributions of source code must retain the above copyright notice, + // this list of conditions and the following disclaimer. + // + // * Redistributions in binary form must reproduce the above copyright notice, + // this list of conditions and the following disclaimer in the documentation + // and/or other materials provided with the distribution. + // + // * Neither the name of Fair Oaks Labs, Inc. nor the names of its contributors + // may be used to endorse or promote products derived from this software + // without specific prior written permission. + // + // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE + // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + // POSSIBILITY OF SUCH DAMAGE. + """ + +- lib/punycode.js is copyright 2011 Mathias Bynens + and released under the MIT license. + """ + * Punycode.js + * Copyright 2011 Mathias Bynens + * Available under MIT license + """ + +- tools/gyp. GYP is a meta-build system. GYP's license follows: + """ + Copyright (c) 2009 Google Inc. All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are + met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above + copyright notice, this list of conditions and the following disclaimer + in the documentation and/or other materials provided with the + distribution. + * Neither the name of Google Inc. nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + """ + +- Zlib at deps/zlib. zlib's license follows: + """ + /* zlib.h -- interface of the 'zlib' general purpose compression library + version 1.2.4, March 14th, 2010 + + Copyright (C) 1995-2010 Jean-loup Gailly and Mark Adler + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. + + Jean-loup Gailly + Mark Adler + + */ + """ + +- npm is a package manager program located at deps/npm. + npm's license follows: + """ + Copyright 2009-2012, Isaac Z. Schlueter (the "Original Author") + All rights reserved. + + MIT +no-false-attribs License + + Permission is hereby granted, free of charge, to any person + obtaining a copy of this software and associated documentation + files (the "Software"), to deal in the Software without + restriction, including without limitation the rights to use, + copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the + Software is furnished to do so, subject to the following + conditions: + + The above copyright notice and this permission notice shall be + included in all copies or substantial portions of the Software. + + Distributions of all or part of the Software intended to be used + by the recipients as they would use the unmodified Software, + containing modifications that substantially alter, remove, or + disable functionality of the Software, outside of the documented + configuration mechanisms provided by the Software, shall be + modified such that the Original Author's bug reporting email + addresses and urls are either replaced with the contact information + of the parties responsible for the changes, or removed entirely. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES + OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT + HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + OTHER DEALINGS IN THE SOFTWARE. + + + Except where noted, this license applies to any and all software + programs and associated documentation files created by the + Original Author, when distributed with the Software. + + "Node.js" and "node" trademark Joyent, Inc. npm is not officially + part of the Node.js project, and is neither owned by nor + officially affiliated with Joyent, Inc. + + Packages published in the npm registry are not part of npm + itself, are the sole property of their respective maintainers, + and are not covered by this license. + + "npm Logo" created by Mathias Pettersson and Brian Hammond, + used with permission. + + "Gubblebum Blocky" font + Copyright (c) 2007 by Tjarda Koster, http://jelloween.deviantart.com + included for use in the npm website and documentation, + used with permission. + + This program uses "node-uuid", Copyright (c) 2010 Robert Kieffer, + according to the terms of the MIT license. + + This program uses "request", Copyright (c) 2011 Mikeal Rogers, + according to the terms of the Apache license. + + This program uses "mkdirp", Copyright (c) 2010 James Halliday, + according to the terms of the MIT/X11 license. + """ + +- tools/doc/node_modules/marked. Marked is a Markdown parser. Marked's + license follows: + """ + Copyright (c) 2011-2012, Christopher Jeffrey (https://github.com/chjj/) + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + """ + +- test/gc/node_modules/weak. Node-weak is a node.js addon that provides garbage + collector notifications. Node-weak's license follows: + """ + Copyright (c) 2011, Ben Noordhuis + + Permission to use, copy, modify, and/or distribute this software for any + purpose with or without fee is hereby granted, provided that the above + copyright notice and this permission notice appear in all copies. + + THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + """ + +- src/ngx-queue.h. ngx-queue.h is taken from the nginx source tree. nginx's + license follows: + """ + Copyright (C) 2002-2012 Igor Sysoev + Copyright (C) 2011,2012 Nginx, Inc. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + 1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY AUTHOR AND CONTRIBUTORS ``AS IS'' AND + ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + ARE DISCLAIMED. IN NO EVENT SHALL AUTHOR OR CONTRIBUTORS BE LIABLE + FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + SUCH DAMAGE. + """ diff --git a/node-v0.8.14/Makefile b/node-v0.8.14/Makefile new file mode 100644 index 0000000..d02a64a --- /dev/null +++ b/node-v0.8.14/Makefile @@ -0,0 +1,316 @@ +-include config.mk + +BUILDTYPE ?= Release +PYTHON ?= python +DESTDIR ?= +SIGN ?= + +# Default to verbose builds. +# To do quiet/pretty builds, run `make V=` to set V to an empty string, +# or set the V environment variable to an empty string. +V ?= 1 + +# BUILDTYPE=Debug builds both release and debug builds. If you want to compile +# just the debug build, run `make -C out BUILDTYPE=Debug` instead. +ifeq ($(BUILDTYPE),Release) +all: out/Makefile node +else +all: out/Makefile node node_g +endif + +# The .PHONY is needed to ensure that we recursively use the out/Makefile +# to check for changes. +.PHONY: node node_g + +node: config.gypi out/Makefile + $(MAKE) -C out BUILDTYPE=Release V=$(V) + ln -fs out/Release/node node + +node_g: config.gypi out/Makefile + $(MAKE) -C out BUILDTYPE=Debug V=$(V) + ln -fs out/Debug/node node_g + +config.gypi: configure + ./configure + +out/Debug/node: + $(MAKE) -C out BUILDTYPE=Debug V=$(V) + +out/Makefile: common.gypi deps/uv/uv.gyp deps/http_parser/http_parser.gyp deps/zlib/zlib.gyp deps/v8/build/common.gypi deps/v8/tools/gyp/v8.gyp node.gyp config.gypi + $(PYTHON) tools/gyp_node -f make + +install: all + $(PYTHON) tools/install.py $@ $(DESTDIR) + +uninstall: + $(PYTHON) tools/install.py $@ $(DESTDIR) + +clean: + -rm -rf out/Makefile node node_g out/$(BUILDTYPE)/node blog.html email.md + -find out/ -name '*.o' -o -name '*.a' | xargs rm -rf + -rm -rf node_modules + +distclean: + -rm -rf out + -rm -f config.gypi + -rm -f config.mk + -rm -rf node node_g blog.html email.md + -rm -rf node_modules + +test: all + $(PYTHON) tools/test.py --mode=release simple message + PYTHONPATH=tools/closure_linter/ $(PYTHON) tools/closure_linter/closure_linter/gjslint.py --unix_mode --strict --nojsdoc -r lib/ -r src/ --exclude_files lib/punycode.js + +test-http1: all + $(PYTHON) tools/test.py --mode=release --use-http1 simple message + +test-valgrind: all + $(PYTHON) tools/test.py --mode=release --valgrind simple message + +test/gc/node_modules/weak/build: + @if [ ! -f node ]; then make all; fi + ./node deps/npm/node_modules/node-gyp/bin/node-gyp rebuild \ + --directory="$(shell pwd)/test/gc/node_modules/weak" \ + --nodedir="$(shell pwd)" + +test-gc: all test/gc/node_modules/weak/build + $(PYTHON) tools/test.py --mode=release gc + +test-all: all test/gc/node_modules/weak/build + $(PYTHON) tools/test.py --mode=debug,release + make test-npm + +test-all-http1: all + $(PYTHON) tools/test.py --mode=debug,release --use-http1 + +test-all-valgrind: all + $(PYTHON) tools/test.py --mode=debug,release --valgrind + +test-release: all + $(PYTHON) tools/test.py --mode=release + +test-debug: all + $(PYTHON) tools/test.py --mode=debug + +test-message: all + $(PYTHON) tools/test.py message + +test-simple: all + $(PYTHON) tools/test.py simple + +test-pummel: all + $(PYTHON) tools/test.py pummel + +test-internet: all + $(PYTHON) tools/test.py internet + +test-npm: node + ./node deps/npm/test/run.js + +test-npm-publish: node + npm_package_config_publishtest=true ./node deps/npm/test/run.js + +apidoc_sources = $(wildcard doc/api/*.markdown) +apidocs = $(addprefix out/,$(apidoc_sources:.markdown=.html)) \ + $(addprefix out/,$(apidoc_sources:.markdown=.json)) + +apidoc_dirs = out/doc out/doc/api/ out/doc/api/assets out/doc/about out/doc/community out/doc/download out/doc/logos out/doc/images + +apiassets = $(subst api_assets,api/assets,$(addprefix out/,$(wildcard doc/api_assets/*))) + +doc_images = $(addprefix out/,$(wildcard doc/images/* doc/*.jpg doc/*.png)) + +website_files = \ + out/doc/index.html \ + out/doc/v0.4_announcement.html \ + out/doc/cla.html \ + out/doc/sh_main.js \ + out/doc/sh_javascript.min.js \ + out/doc/sh_vim-dark.css \ + out/doc/sh.css \ + out/doc/favicon.ico \ + out/doc/pipe.css \ + out/doc/about/index.html \ + out/doc/community/index.html \ + out/doc/download/index.html \ + out/doc/logos/index.html \ + out/doc/changelog.html \ + $(doc_images) + +doc: $(apidoc_dirs) $(website_files) $(apiassets) $(apidocs) tools/doc/ blog node + +blogclean: + rm -rf out/blog + +blog: doc/blog out/Release/node tools/blog + out/Release/node tools/blog/generate.js doc/blog/ out/blog/ doc/blog.html doc/rss.xml + +$(apidoc_dirs): + mkdir -p $@ + +out/doc/api/assets/%: doc/api_assets/% out/doc/api/assets/ + cp $< $@ + +out/doc/changelog.html: ChangeLog doc/changelog-head.html doc/changelog-foot.html tools/build-changelog.sh node + bash tools/build-changelog.sh + +out/doc/%.html: doc/%.html node + cat $< | sed -e 's|__VERSION__|'$(VERSION)'|g' > $@ + +out/doc/%: doc/% + cp -r $< $@ + +out/doc/api/%.json: doc/api/%.markdown node + out/Release/node tools/doc/generate.js --format=json $< > $@ + +out/doc/api/%.html: doc/api/%.markdown node + out/Release/node tools/doc/generate.js --format=html --template=doc/template.html $< > $@ + +email.md: ChangeLog tools/email-footer.md + bash tools/changelog-head.sh | sed 's|^\* #|* \\#|g' > $@ + cat tools/email-footer.md | sed -e 's|__VERSION__|'$(VERSION)'|g' >> $@ + +blog.html: email.md + cat $< | ./node tools/doc/node_modules/.bin/marked > $@ + +blog-upload: blog + rsync -r out/blog/ node@nodejs.org:~/web/nodejs.org/blog/ + +website-upload: doc + rsync -r out/doc/ node@nodejs.org:~/web/nodejs.org/ + ssh node@nodejs.org '\ + rm -f ~/web/nodejs.org/dist/latest &&\ + ln -s $(VERSION) ~/web/nodejs.org/dist/latest &&\ + rm -f ~/web/nodejs.org/docs/latest &&\ + ln -s $(VERSION) ~/web/nodejs.org/docs/latest &&\ + rm -f ~/web/nodejs.org/dist/node-latest.tar.gz &&\ + ln -s $(VERSION)/node-$(VERSION).tar.gz ~/web/nodejs.org/dist/node-latest.tar.gz' + +docopen: out/doc/api/all.html + -google-chrome out/doc/api/all.html + +docclean: + -rm -rf out/doc + +VERSION=v$(shell $(PYTHON) tools/getnodeversion.py) +RELEASE=$(shell $(PYTHON) tools/getnodeisrelease.py) +PLATFORM=$(shell uname | tr '[:upper:]' '[:lower:]') +ifeq ($(findstring x86_64,$(shell uname -m)),x86_64) +DESTCPU ?= x64 +else +DESTCPU ?= ia32 +endif +ifeq ($(DESTCPU),x64) +ARCH=x64 +else +ARCH=x86 +endif +TARNAME=node-$(VERSION) +TARBALL=$(TARNAME).tar.gz +BINARYNAME=$(TARNAME)-$(PLATFORM)-$(ARCH) +BINARYTAR=$(BINARYNAME).tar.gz +PKG=out/$(TARNAME).pkg +packagemaker=/Developer/Applications/Utilities/PackageMaker.app/Contents/MacOS/PackageMaker + +dist: doc $(TARBALL) $(PKG) + +PKGDIR=out/dist-osx + +release-only: + @if [ "$(shell git status --porcelain | egrep -v '^\?\? ')" = "" ]; then \ + exit 0 ; \ + else \ + echo "" >&2 ; \ + echo "The git repository is not clean." >&2 ; \ + echo "Please commit changes before building release tarball." >&2 ; \ + echo "" >&2 ; \ + git status --porcelain | egrep -v '^\?\?' >&2 ; \ + echo "" >&2 ; \ + exit 1 ; \ + fi + @if [ "$(RELEASE)" = "1" ]; then \ + exit 0; \ + else \ + echo "" >&2 ; \ + echo "#NODE_VERSION_IS_RELEASE is set to $(RELEASE)." >&2 ; \ + echo "Did you remember to update src/node_version.cc?" >&2 ; \ + echo "" >&2 ; \ + exit 1 ; \ + fi + +pkg: $(PKG) + +$(PKG): release-only + rm -rf $(PKGDIR) + rm -rf out/deps out/Release + ./configure --prefix=$(PKGDIR)/32/usr/local --without-snapshot --dest-cpu=ia32 + $(MAKE) install V=$(V) + rm -rf out/deps out/Release + ./configure --prefix=$(PKGDIR)/usr/local --without-snapshot --dest-cpu=x64 + $(MAKE) install V=$(V) + SIGN="$(SIGN)" PKGDIR="$(PKGDIR)" bash tools/osx-codesign.sh + lipo $(PKGDIR)/32/usr/local/bin/node \ + $(PKGDIR)/usr/local/bin/node \ + -output $(PKGDIR)/usr/local/bin/node-universal \ + -create + mv $(PKGDIR)/usr/local/bin/node-universal $(PKGDIR)/usr/local/bin/node + rm -rf $(PKGDIR)/32 + $(packagemaker) \ + --id "org.nodejs.Node" \ + --doc tools/osx-pkg.pmdoc \ + --out $(PKG) + SIGN="$(SIGN)" PKG="$(PKG)" bash tools/osx-productsign.sh + +$(TARBALL): release-only node doc + git archive --format=tar --prefix=$(TARNAME)/ HEAD | tar xf - + mkdir -p $(TARNAME)/doc/api + cp doc/node.1 $(TARNAME)/doc/node.1 + cp -r out/doc/api/* $(TARNAME)/doc/api/ + rm -rf $(TARNAME)/deps/v8/test # too big + rm -rf $(TARNAME)/doc/images # too big + find $(TARNAME)/ -type l | xargs rm # annoying on windows + tar -cf $(TARNAME).tar $(TARNAME) + rm -rf $(TARNAME) + gzip -f -9 $(TARNAME).tar + +tar: $(TARBALL) + +$(BINARYTAR): release-only + rm -rf $(BINARYNAME) + rm -rf out/deps out/Release + ./configure --prefix=/ --without-snapshot --dest-cpu=$(DESTCPU) + $(MAKE) install DESTDIR=$(BINARYNAME) V=$(V) PORTABLE=1 + cp README.md $(BINARYNAME) + cp LICENSE $(BINARYNAME) + cp ChangeLog $(BINARYNAME) + tar -cf $(BINARYNAME).tar $(BINARYNAME) + rm -rf $(BINARYNAME) + gzip -f -9 $(BINARYNAME).tar + +binary: $(BINARYTAR) + +dist-upload: $(TARBALL) $(PKG) + ssh node@nodejs.org mkdir -p web/nodejs.org/dist/$(VERSION) + scp $(TARBALL) node@nodejs.org:~/web/nodejs.org/dist/$(VERSION)/$(TARBALL) + scp $(PKG) node@nodejs.org:~/web/nodejs.org/dist/$(VERSION)/$(TARNAME).pkg + +bench: + benchmark/http_simple_bench.sh + +bench-idle: + ./node benchmark/idle_server.js & + sleep 1 + ./node benchmark/idle_clients.js & + +jslintfix: + PYTHONPATH=tools/closure_linter/ $(PYTHON) tools/closure_linter/closure_linter/fixjsstyle.py --strict --nojsdoc -r lib/ -r src/ --exclude_files lib/punycode.js + +jslint: + PYTHONPATH=tools/closure_linter/ $(PYTHON) tools/closure_linter/closure_linter/gjslint.py --unix_mode --strict --nojsdoc -r lib/ -r src/ --exclude_files lib/punycode.js + +cpplint: + @$(PYTHON) tools/cpplint.py $(wildcard src/*.cc src/*.h src/*.c) + +lint: jslint cpplint + +.PHONY: lint cpplint jslint bench clean docopen docclean doc dist distclean check uninstall install install-includes install-bin all staticlib dynamiclib test test-all website-upload pkg blog blogclean tar binary release-only diff --git a/node-v0.8.14/README.md b/node-v0.8.14/README.md new file mode 100644 index 0000000..988305f --- /dev/null +++ b/node-v0.8.14/README.md @@ -0,0 +1,52 @@ +Evented I/O for V8 javascript. [![Build Status](https://secure.travis-ci.org/joyent/node.png)](http://travis-ci.org/joyent/node) +=== + +### To build: + +Prerequisites (Unix only): + + * Python 2.6 or 2.7 + * GNU Make 3.81 or newer + * libexecinfo (FreeBSD and OpenBSD only) + +Unix/Macintosh: + + ./configure + make + make install + +Windows: + + vcbuild.bat + +### To run the tests: + +Unix/Macintosh: + + make test + +Windows: + + vcbuild.bat test + +### To build the documentation: + + make doc + +### To read the documentation: + + man doc/node.1 + +Resources for Newcomers +--- + - [The Wiki](https://github.com/joyent/node/wiki) + - [nodejs.org](http://nodejs.org/) + - [how to install node.js and npm (node package manager)](http://joyeur.com/2010/12/10/installing-node-and-npm/) + - [list of modules](https://github.com/joyent/node/wiki/modules) + - [searching the npm registry](http://search.npmjs.org/) + - [list of companies and projects using node](https://github.com/joyent/node/wiki/Projects,-Applications,-and-Companies-Using-Node) + - [node.js mailing list](http://groups.google.com/group/nodejs) + - irc chatroom, [#node.js on freenode.net](http://webchat.freenode.net?channels=node.js&uio=d4) + - [community](https://github.com/joyent/node/wiki/Community) + - [contributing](https://github.com/joyent/node/wiki/Contributing) + - [big list of all the helpful wiki pages](https://github.com/joyent/node/wiki/_pages) diff --git a/node-v0.8.14/benchmark/arrays/var_int.js b/node-v0.8.14/benchmark/arrays/var_int.js new file mode 100644 index 0000000..17e1298 --- /dev/null +++ b/node-v0.8.14/benchmark/arrays/var_int.js @@ -0,0 +1,15 @@ +var types = 'Array Buffer Int8Array Uint8Array Int16Array Uint16Array Int32Array Uint32Array Float32Array Float64Array'.split(' '); + +var type = types[types.indexOf(process.argv[2])]; +if (!type) + type = types[0]; + +console.error('Benchmarking', type); +var clazz = global[type]; + +var arr = new clazz(25 * 10e5); +for (var i = 0; i < 10; ++i) { + for (var j = 0, k = arr.length; j < k; ++j) { + arr[j] = (j ^ k) & 127; + } +} diff --git a/node-v0.8.14/benchmark/arrays/zero_float.js b/node-v0.8.14/benchmark/arrays/zero_float.js new file mode 100644 index 0000000..bdb8765 --- /dev/null +++ b/node-v0.8.14/benchmark/arrays/zero_float.js @@ -0,0 +1,15 @@ +var types = 'Array Buffer Int8Array Uint8Array Int16Array Uint16Array Int32Array Uint32Array Float32Array Float64Array'.split(' '); + +var type = types[types.indexOf(process.argv[2])]; +if (!type) + type = types[0]; + +console.error('Benchmarking', type); +var clazz = global[type]; + +var arr = new clazz(25 * 10e5); +for (var i = 0; i < 10; ++i) { + for (var j = 0, k = arr.length; j < k; ++j) { + arr[j] = 0.0; + } +} diff --git a/node-v0.8.14/benchmark/arrays/zero_int.js b/node-v0.8.14/benchmark/arrays/zero_int.js new file mode 100644 index 0000000..17dac62 --- /dev/null +++ b/node-v0.8.14/benchmark/arrays/zero_int.js @@ -0,0 +1,15 @@ +var types = 'Array Buffer Int8Array Uint8Array Int16Array Uint16Array Int32Array Uint32Array Float32Array Float64Array'.split(' '); + +var type = types[types.indexOf(process.argv[2])]; +if (!type) + type = types[0]; + +console.error('Benchmarking', type); +var clazz = global[type]; + +var arr = new clazz(25 * 10e5); +for (var i = 0; i < 10; ++i) { + for (var j = 0, k = arr.length; j < k; ++j) { + arr[j] = 0; + } +} diff --git a/node-v0.8.14/benchmark/buffer_creation.js b/node-v0.8.14/benchmark/buffer_creation.js new file mode 100644 index 0000000..3bc711e --- /dev/null +++ b/node-v0.8.14/benchmark/buffer_creation.js @@ -0,0 +1,6 @@ +SlowBuffer = require('buffer').SlowBuffer; + +for (var i = 0; i < 1e6; i++) { + b = new SlowBuffer(10); + b[1] = 2 +} diff --git a/node-v0.8.14/benchmark/client_latency.js b/node-v0.8.14/benchmark/client_latency.js new file mode 100644 index 0000000..09630a0 --- /dev/null +++ b/node-v0.8.14/benchmark/client_latency.js @@ -0,0 +1,80 @@ +// first start node http_simple.js +var http = require('http'); + +var latency = []; + +var numRequests = parseInt(process.argv[2], 10) || 100; +var maxSockets = parseInt(process.argv[3], 10) || 100; +var runs = parseInt(process.argv[4], 10) || 100; +var prefix = process.argv[5] || ''; +if (prefix) prefix += '_'; +var r = 0; + +var port = parseInt(process.env.PORT, 10) || 8000; +var host = process.env.HOST || '127.0.0.1'; + +http.globalAgent.maxSockets = maxSockets; + +run(); + +function run() { + if (r++ === runs) { + return finish(); + } + + // make numRequests in parallel + // retain the order in which they are *made*. This requires trapping + // each one in a closure, since otherwise, we'll of course end + // up mostly sorting them in ascending order, since the cb from a + // fast request will almost always be called before the cb from a + // slow one. + var c = numRequests; + var lat = []; + latency.push(lat); + for (var i = 0; i < numRequests; i++) (function (i) { + makeRequest(function(l) { + lat[i] = l; + c--; + if (c === 0) run(); + }); + })(i); +} + +function makeRequest(cb) { + var opts = { host: host, + port: port, + uri: 'http://'+host+':'+port+'/bytes/12', + forever: true, + path: '/bytes/12' }; + var pre = Date.now(); + var req = http.get(opts, function(res) { + return cb(Date.now() - pre); + }); +} + +function finish() { + var data = []; + latency.forEach(function(run, i) { + run.forEach(function(l, j) { + data[j] = data[j] || []; + data[j][i] = l; + }); + }); + + data = data.map(function (l, i) { + return l.join('\t') + }).join('\n') + '\n'; + + var fname = prefix + + 'client_latency_' + + numRequests + '_' + + maxSockets + '_' + + runs + '.tab'; + var path = require('path'); + fname = path.resolve(__dirname, '..', 'out', fname); + fname = path.relative(process.cwd(), fname); + require('fs').writeFile(fname, data, function(er) { + if (er) throw er; + console.log('written: %s', fname); + }); +} diff --git a/node-v0.8.14/benchmark/fast_buffer2.js b/node-v0.8.14/benchmark/fast_buffer2.js new file mode 100644 index 0000000..861ae3b --- /dev/null +++ b/node-v0.8.14/benchmark/fast_buffer2.js @@ -0,0 +1,42 @@ +var SlowBuffer = require('buffer').SlowBuffer; +var POOLSIZE = 8*1024; +var pool; + +function allocPool () { + pool = new SlowBuffer(POOLSIZE); + pool.used = 0; +} + +function FastBuffer (length) { + this.length = length; + + if (length > POOLSIZE) { + // Big buffer, just alloc one. + this.parent = new Buffer(length); + this.offset = 0; + } else { + // Small buffer. + if (!pool || pool.length - pool.used < length) allocPool(); + this.parent = pool; + this.offset = pool.used; + pool.used += length; + } + + // HERE HERE HERE + SlowBuffer.makeFastBuffer(this.parent, this, this.offset, this.length); +} + +exports.FastBuffer = FastBuffer; + +FastBuffer.prototype.get = function (i) { + if (i < 0 || i >= this.length) throw new Error("oob"); + return this.parent[this.offset + i]; +}; + +FastBuffer.prototype.set = function (i, v) { + if (i < 0 || i >= this.length) throw new Error("oob"); + return this.parent[this.offset + i] = v; +}; + +// TODO define slice, toString, write, etc. +// slice should not use c++ diff --git a/node-v0.8.14/benchmark/fast_buffer2_creation.js b/node-v0.8.14/benchmark/fast_buffer2_creation.js new file mode 100644 index 0000000..877f569 --- /dev/null +++ b/node-v0.8.14/benchmark/fast_buffer2_creation.js @@ -0,0 +1,6 @@ + +FastBuffer = require('./fast_buffer2').FastBuffer; +for (var i = 0; i < 1e6; i++) { + b = new FastBuffer(10); + b[1] = 2; +} diff --git a/node-v0.8.14/benchmark/fast_buffer_creation.js b/node-v0.8.14/benchmark/fast_buffer_creation.js new file mode 100644 index 0000000..fbd0c75 --- /dev/null +++ b/node-v0.8.14/benchmark/fast_buffer_creation.js @@ -0,0 +1,4 @@ +for (var i = 0; i < 1e6; i++) { + b = new Buffer(10); + b[1] = 2; +} diff --git a/node-v0.8.14/benchmark/fs-readfile.js b/node-v0.8.14/benchmark/fs-readfile.js new file mode 100644 index 0000000..3aa72e1 --- /dev/null +++ b/node-v0.8.14/benchmark/fs-readfile.js @@ -0,0 +1,72 @@ +// Call fs.readFile over and over again really fast. +// Then see how many times it got called. +// Yes, this is a silly benchmark. Most benchmarks are silly. + +var path = require('path'); +var filename = path.resolve(__dirname, 'http.sh'); +var fs = require('fs'); +var count = 0; +var go = true; +var len = -1; +var assert = require('assert'); + +var concurrency = 1; +var encoding = null; +var time = 10; + +for (var i = 2; i < process.argv.length; i++) { + var arg = process.argv[i]; + if (arg.match(/^-e$/)) { + encoding = process.argv[++i] || null; + } else if (arg.match(/^-c$/)) { + concurrency = ~~process.argv[++i]; + if (concurrency < 1) concurrency = 1; + } else if (arg === '-t') { + time = ~~process.argv[++i]; + if (time < 1) time = 1; + } +} + + +setTimeout(function() { + go = false; +}, time * 1000); + +function round(n) { + return Math.floor(n * 100) / 100; +} + +var start = process.hrtime(); +while (concurrency--) readFile(); + +function readFile() { + if (!go) { + process.stdout.write('\n'); + console.log('read the file %d times (higher is better)', count); + var end = process.hrtime(); + var elapsed = [end[0] - start[0], end[1] - start[1]]; + var ns = elapsed[0] * 1E9 + elapsed[1]; + var nsper = round(ns / count); + console.log('%d ns per read (lower is better)', nsper); + var readsper = round(count / (ns / 1E9)); + console.log('%d reads per sec (higher is better)', readsper); + process.exit(0); + return; + } + + if (!(count % 1000)) { + process.stdout.write('.'); + } + + if (encoding) fs.readFile(filename, encoding, then); + else fs.readFile(filename, then); + + function then(er, data) { + assert.ifError(er); + count++; + // basic sanity test: we should get the same number of bytes each time. + if (count === 1) len = data.length; + else assert(len === data.length); + readFile(); + } +} diff --git a/node-v0.8.14/benchmark/function_call/bench.js b/node-v0.8.14/benchmark/function_call/bench.js new file mode 100644 index 0000000..55e6ea1 --- /dev/null +++ b/node-v0.8.14/benchmark/function_call/bench.js @@ -0,0 +1,43 @@ +var binding = require('./build/default/binding'); + +c = 0 + +function js() { + return c++; //(new Date()).getTime(); +} + +var cxx = binding.hello; + +var i, N = 100000000; + +console.log(js()); +console.log(cxx()); + + + +var start = new Date(); +for (i = 0; i < N; i++) { + js(); +} +var jsDiff = new Date() - start; +console.log(N +" JS function calls: " + jsDiff); + + +var start = new Date(); +for (i = 0; i < N; i++) { + cxx(); +} +var cxxDiff = new Date() - start; +console.log(N +" C++ function calls: " + cxxDiff); + +function toMicro (diff) { + return (diff / N) * 1000000; +} + +console.log("\nJS function call speed: %d microseconds", toMicro(jsDiff)); +console.log("C++ function call speed: %d microseconds", toMicro(cxxDiff)); + + +console.log("\nJS speedup " + (cxxDiff / jsDiff)); + + diff --git a/node-v0.8.14/benchmark/function_call/binding.cc b/node-v0.8.14/benchmark/function_call/binding.cc new file mode 100644 index 0000000..75882c1 --- /dev/null +++ b/node-v0.8.14/benchmark/function_call/binding.cc @@ -0,0 +1,19 @@ +#include +#include +#include + +using namespace v8; + +static int c = 0; + +static Handle Hello(const Arguments& args) { + HandleScope scope; + //time_t tv = time(NULL); + return scope.Close(Integer::New(c++)); +} + +extern "C" void init (Handle target) { + HandleScope scope; + //target->Set(String::New("hello"), String::New("World")); + NODE_SET_METHOD(target, "hello", Hello); +} diff --git a/node-v0.8.14/benchmark/function_call/wscript b/node-v0.8.14/benchmark/function_call/wscript new file mode 100644 index 0000000..3db367f --- /dev/null +++ b/node-v0.8.14/benchmark/function_call/wscript @@ -0,0 +1,15 @@ +srcdir = '.' +blddir = 'build' +VERSION = '0.0.1' + +def set_options(opt): + opt.tool_options('compiler_cxx') + +def configure(conf): + conf.check_tool('compiler_cxx') + conf.check_tool('node_addon') + +def build(bld): + obj = bld.new_task_gen('cxx', 'shlib', 'node_addon') + obj.target = 'binding' + obj.source = 'binding.cc' diff --git a/node-v0.8.14/benchmark/http.sh b/node-v0.8.14/benchmark/http.sh new file mode 100755 index 0000000..40d0c71 --- /dev/null +++ b/node-v0.8.14/benchmark/http.sh @@ -0,0 +1,12 @@ +#!/bin/bash +cd "$(dirname "$(dirname $0)")" +sudo sysctl -w net.inet.ip.portrange.first=12000 +sudo sysctl -w net.inet.tcp.msl=1000 +sudo sysctl -w kern.maxfiles=1000000 kern.maxfilesperproc=1000000 +ulimit -n 100000 + +./node benchmark/http_simple.js || exit 1 & +sleep 1 + +ab -n 30000 -c 100 http://127.0.0.1:8000/${TYPE:-bytes}/${LENGTH:-1024} | grep Req +killall node diff --git a/node-v0.8.14/benchmark/http_bench.js b/node-v0.8.14/benchmark/http_bench.js new file mode 100644 index 0000000..842b942 --- /dev/null +++ b/node-v0.8.14/benchmark/http_bench.js @@ -0,0 +1,127 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var spawn = require('child_process').spawn; +var cluster = require('cluster'); +var http = require('http'); + +var options = { + mode: 'master', + host: '127.0.0.1', + port: 22344, + path: '/', + servers: 1, + clients: 1 +}; + +for (var i = 2; i < process.argv.length; ++i) { + var args = process.argv[i].split('=', 2); + var key = args[0]; + var val = args[1]; + options[key] = val; +} + +switch (options.mode) { +case 'master': startMaster(); break; +case 'server': startServer(); break; +case 'client': startClient(); break; +default: throw new Error('Bad mode: ' + options.mode); +} + +process.title = 'http_bench[' + options.mode + ']'; + +// monkey-patch the log functions so they include name + pid +console.log = patch(console.log); +console.trace = patch(console.trace); +console.error = patch(console.error); + +function patch(fun) { + var prefix = process.title + '[' + process.pid + '] '; + return function() { + var args = Array.prototype.slice.call(arguments); + args[0] = prefix + args[0]; + return fun.apply(console, args); + }; +} + +function startMaster() { + if (!cluster.isMaster) return startServer(); + + for (var i = ~~options.servers; i > 0; --i) cluster.fork(); + + for (var i = ~~options.clients; i > 0; --i) { + var cp = spawn(process.execPath, [__filename, 'mode=client']); + cp.stdout.pipe(process.stdout); + cp.stderr.pipe(process.stderr); + } +} + +function startServer() { + http.createServer(onRequest).listen(options.port, options.host); + + var body = Array(1024).join('x'); + var headers = {'Content-Length': '' + body.length}; + + function onRequest(req, res) { + req.on('error', onError); + res.on('error', onError); + res.writeHead(200, headers); + res.end(body); + } + + function onError(err) { + console.error(err.stack); + } +} + +function startClient() { + // send off a bunch of concurrent requests + // TODO make configurable + sendRequest(); + sendRequest(); + + function sendRequest() { + var req = http.request(options, onConnection); + req.on('error', onError); + req.end(); + } + + // add a little back-off to prevent EADDRNOTAVAIL errors, it's pretty easy + // to exhaust the available port range + function relaxedSendRequest() { + setTimeout(sendRequest, 1); + } + + function onConnection(res) { + res.on('error', onError); + res.on('data', onData); + res.on('end', relaxedSendRequest); + } + + function onError(err) { + console.error(err.stack); + relaxedSendRequest(); + } + + function onData(data) { + // this space intentionally left blank + } +} diff --git a/node-v0.8.14/benchmark/http_server_lag.js b/node-v0.8.14/benchmark/http_server_lag.js new file mode 100644 index 0000000..ca923d5 --- /dev/null +++ b/node-v0.8.14/benchmark/http_server_lag.js @@ -0,0 +1,13 @@ +var http = require('http'); +var port = parseInt(process.env.PORT, 10) || 8000; +var defaultLag = parseInt(process.argv[2], 10) || 100; + +http.createServer(function(req, res) { + res.writeHead(200, { 'content-type': 'text/plain', + 'content-length': '2' }); + + var lag = parseInt(req.url.split("/").pop(), 10) || defaultLag; + setTimeout(function() { + res.end('ok'); + }, lag); +}).listen(port, 'localhost'); diff --git a/node-v0.8.14/benchmark/http_simple.js b/node-v0.8.14/benchmark/http_simple.js new file mode 100644 index 0000000..1b3cee7 --- /dev/null +++ b/node-v0.8.14/benchmark/http_simple.js @@ -0,0 +1,129 @@ +var path = require('path'), + exec = require('child_process').exec, + http = require('http'); + +var port = parseInt(process.env.PORT || 8000); + +console.log('pid ' + process.pid); + +var fixed = makeString(20 * 1024, 'C'), + storedBytes = {}, + storedBuffer = {}, + storedUnicode = {}; + +var useDomains = process.env.NODE_USE_DOMAINS; + +// set up one global domain. +if (useDomains) { + var domain = require('domain'); + var gdom = domain.create(); + gdom.on('error', function(er) { + console.log('Error on global domain', er); + throw er; + }); + gdom.enter(); +} + +var server = http.createServer(function (req, res) { + if (useDomains) { + var dom = domain.create(); + dom.add(req); + dom.add(res); + } + + var commands = req.url.split('/'); + var command = commands[1]; + var body = ''; + var arg = commands[2]; + var n_chunks = parseInt(commands[3], 10); + var status = 200; + + if (command == 'bytes') { + var n = ~~arg; + if (n <= 0) + throw new Error('bytes called with n <= 0') + if (storedBytes[n] === undefined) { + console.log('create storedBytes[n]'); + storedBytes[n] = makeString(n, 'C'); + } + body = storedBytes[n]; + + } else if (command == 'buffer') { + var n = ~~arg; + if (n <= 0) + throw new Error('buffer called with n <= 0'); + if (storedBuffer[n] === undefined) { + console.log('create storedBuffer[n]'); + storedBuffer[n] = new Buffer(n); + for (var i = 0; i < n; i++) { + storedBuffer[n][i] = 'C'.charCodeAt(0); + } + } + body = storedBuffer[n]; + + } else if (command == 'unicode') { + var n = ~~arg; + if (n <= 0) + throw new Error('unicode called with n <= 0'); + if (storedUnicode[n] === undefined) { + console.log('create storedUnicode[n]'); + storedUnicode[n] = makeString(n, '\u263A'); + } + body = storedUnicode[n]; + + } else if (command == 'quit') { + res.connection.server.close(); + body = 'quitting'; + + } else if (command == 'fixed') { + body = fixed; + + } else if (command == 'echo') { + res.writeHead(200, { 'Content-Type': 'text/plain', + 'Transfer-Encoding': 'chunked' }); + req.pipe(res); + return; + + } else { + status = 404; + body = 'not found\n'; + } + + // example: http://localhost:port/bytes/512/4 + // sends a 512 byte body in 4 chunks of 128 bytes + if (n_chunks > 0) { + res.writeHead(status, { 'Content-Type': 'text/plain', + 'Transfer-Encoding': 'chunked' }); + // send body in chunks + var len = body.length; + var step = ~~(len / n_chunks) || len; + + for (var i = 0; i < len; i += step) { + res.write(body.slice(i, i + step)); + } + + res.end(); + } else { + var content_length = body.length.toString(); + + res.writeHead(status, { 'Content-Type': 'text/plain', + 'Content-Length': content_length }); + res.end(body); + } +}); + +function makeString(size, c) { + var s = ''; + while (s.length < size) { + s += c; + } + return s; +} + +server.listen(port, function () { + console.log('Listening at http://127.0.0.1:'+port+'/'); +}); + +process.on('exit', function() { + console.error('libuv counters', process.uvCounters()); +}); diff --git a/node-v0.8.14/benchmark/http_simple.rb b/node-v0.8.14/benchmark/http_simple.rb new file mode 100644 index 0000000..e9a44fa --- /dev/null +++ b/node-v0.8.14/benchmark/http_simple.rb @@ -0,0 +1,95 @@ +DIR = File.dirname(__FILE__) + +def fib(n) + return 1 if n <= 1 + fib(n-1) + fib(n-2) +end + +def wait(seconds) + n = (seconds / 0.01).to_i + n.times do + sleep(0.01) + #File.read(DIR + '/yahoo.html') + end +end + +class SimpleApp + @@responses = {} + + def initialize + @count = 0 + end + + def deferred?(env) + false + end + + def call(env) + path = env['PATH_INFO'] || env['REQUEST_URI'] + commands = path.split('/') + + @count += 1 + if commands.include?('periodical_activity') and @count % 10 != 1 + return [200, {'Content-Type'=>'text/plain'}, "quick response!\r\n"] + end + + if commands.include?('fibonacci') + n = commands.last.to_i + raise "fibonacci called with n <= 0" if n <= 0 + body = (1..n).to_a.map { |i| fib(i).to_s }.join(' ') + status = 200 + + elsif commands.include?('wait') + n = commands.last.to_f + raise "wait called with n <= 0" if n <= 0 + wait(n) + body = "waited about #{n} seconds" + status = 200 + + elsif commands.include?('bytes') + n = commands.last.to_i + raise "bytes called with n <= 0" if n <= 0 + body = @@responses[n] || "C"*n + status = 200 + + elsif commands.include?('fixed') + n = 20 * 1024; + body = @@responses[n] || "C"*n + status = 200 + + elsif commands.include?('test_post_length') + input_body = "" + while chunk = env['rack.input'].read(512) + input_body << chunk + end + if env['CONTENT_LENGTH'].to_i == input_body.length + body = "Content-Length matches input length" + status = 200 + else + body = "Content-Length doesn't matches input length! + content_length = #{env['CONTENT_LENGTH'].to_i} + input_body.length = #{input_body.length}" + status = 500 + end + else + status = 404 + body = "Undefined url" + end + + body += "\r\n" + headers = {'Content-Type' => 'text/plain', 'Content-Length' => body.length.to_s } + [status, headers, [body]] + end +end + + +if $0 == __FILE__ + #require DIR + '/../lib/ebb' + require 'rubygems' + require 'rack' + require 'thin' + require 'ebb' +# Rack::Handler::Mongrel.run(SimpleApp.new, :Port => 8000) + Thin::Server.start("0.0.0.0", 8000, SimpleApp.new) +# Ebb::start_server(SimpleApp.new, :port => 8000) +end diff --git a/node-v0.8.14/benchmark/http_simple_auto.js b/node-v0.8.14/benchmark/http_simple_auto.js new file mode 100644 index 0000000..3192635 --- /dev/null +++ b/node-v0.8.14/benchmark/http_simple_auto.js @@ -0,0 +1,128 @@ +// +// Usage: +// node benchmark/http_simple_auto.js +// +// Where: +// Arguments to pass to `ab`. +// Target to benchmark, e.g. `bytes/1024` or `buffer/8192`. +// + +var path = require("path"); +var http = require("http"); +var spawn = require("child_process").spawn; + +var port = parseInt(process.env.PORT || 8000); + +var fixed = "" +for (var i = 0; i < 20*1024; i++) { + fixed += "C"; +} + +var stored = {}; +var storedBuffer = {}; + +var server = http.createServer(function (req, res) { + var commands = req.url.split("/"); + var command = commands[1]; + var body = ""; + var arg = commands[2]; + var n_chunks = parseInt(commands[3], 10); + var status = 200; + + if (command == "bytes") { + var n = parseInt(arg, 10) + if (n <= 0) + throw "bytes called with n <= 0" + if (stored[n] === undefined) { + stored[n] = ""; + for (var i = 0; i < n; i++) { + stored[n] += "C" + } + } + body = stored[n]; + + } else if (command == "buffer") { + var n = parseInt(arg, 10) + if (n <= 0) throw new Error("bytes called with n <= 0"); + if (storedBuffer[n] === undefined) { + storedBuffer[n] = new Buffer(n); + for (var i = 0; i < n; i++) { + storedBuffer[n][i] = "C".charCodeAt(0); + } + } + body = storedBuffer[n]; + + } else if (command == "quit") { + res.connection.server.close(); + body = "quitting"; + + } else if (command == "fixed") { + body = fixed; + + } else if (command == "echo") { + res.writeHead(200, { "Content-Type": "text/plain", + "Transfer-Encoding": "chunked" }); + req.pipe(res); + return; + + } else { + status = 404; + body = "not found\n"; + } + + // example: http://localhost:port/bytes/512/4 + // sends a 512 byte body in 4 chunks of 128 bytes + if (n_chunks > 0) { + res.writeHead(status, { "Content-Type": "text/plain", + "Transfer-Encoding": "chunked" }); + // send body in chunks + var len = body.length; + var step = ~~(len / n_chunks) || len; + + for (var i = 0; i < len; i += step) { + res.write(body.slice(i, i + step)); + } + + res.end(); + } else { + var content_length = body.length.toString(); + + res.writeHead(status, { "Content-Type": "text/plain", + "Content-Length": content_length }); + res.end(body); + } + +}); + +server.listen(port, function () { + var url = 'http://127.0.0.1:' + port + '/'; + + var n = process.argv.length - 1; + process.argv[n] = url + process.argv[n]; + + var cp = spawn('ab', process.argv.slice(2)); + cp.stdout.pipe(process.stdout); + cp.stderr.pipe(process.stderr); + cp.on('exit', function() { + server.close(); + process.nextTick(dump_mm_stats); + }); +}); + +function dump_mm_stats() { + if (typeof gc != 'function') return; + + var before = process.memoryUsage(); + for (var i = 0; i < 10; ++i) gc(); + var after = process.memoryUsage(); + setTimeout(print_stats, 250); // give GC time to settle + + function print_stats() { + console.log('\nBEFORE / AFTER GC'); + ['rss', 'heapTotal', 'heapUsed'].forEach(function(key) { + var a = before[key] / (1024 * 1024); + var b = after[key] / (1024 * 1024); + console.log('%sM / %sM %s', a.toFixed(2), b.toFixed(2), key); + }); + } +} diff --git a/node-v0.8.14/benchmark/http_simple_bench.sh b/node-v0.8.14/benchmark/http_simple_bench.sh new file mode 100755 index 0000000..6ba8e06 --- /dev/null +++ b/node-v0.8.14/benchmark/http_simple_bench.sh @@ -0,0 +1,77 @@ +#!/bin/bash + +SERVER=127.0.0.1 +PORT=8000 + +# You may want to configure your TCP settings to make many ports available +# to node and ab. On macintosh use: +# sudo sysctl -w net.inet.ip.portrange.first=32768 +# sudo sysctl -w net.inet.tcp.msl=1000 + +if [ ! -d benchmark/ ]; then + echo "Run this script from the node root directory" + exit 1 +fi + +if [ $SERVER == "127.0.0.1" ]; then + ./node benchmark/http_simple.js & + node_pid=$! + sleep 1 +fi + +info=`curl -s http://$SERVER:$PORT/info` +eval $info + +date=`date "+%Y%m%d%H%M%S"` + +ab_hello_world() { + local type="$1" + local ressize="$2" + if [ $type == "string" ]; then + local uri="bytes/$ressize" + else + local uri="buffer/$ressize" + fi + + + name="ab-hello-world-$type-$ressize" + + dir=".benchmark_reports/$name/$rev/" + if [ ! -d $dir ]; then + mkdir -p $dir + fi + + summary_fn="$dir/$date.summary" + data_fn="$dir/$date.data" + + echo "Bench $name starts in 3 seconds..." + # let shit calm down + sleep 3 + + # hammer that as hard as it can for 10 seconds. + ab -g $data_fn -c 100 -t 10 http://$SERVER:$PORT/$uri > $summary_fn + + # add our data about the server + echo >> $summary_fn + echo >> $summary_fn + echo "webserver-rev: $rev" >> $summary_fn + echo "webserver-uname: $uname" >> $summary_fn + + grep Req $summary_fn + + echo "Summary: $summary_fn" + echo +} + +# 1k +ab_hello_world 'string' '1024' +ab_hello_world 'buffer' '1024' + +# 100k +ab_hello_world 'string' '102400' +ab_hello_world 'buffer' '102400' + + +if [ ! -z $node_pid ]; then + kill -9 $node_pid +fi diff --git a/node-v0.8.14/benchmark/http_simple_cluster.js b/node-v0.8.14/benchmark/http_simple_cluster.js new file mode 100644 index 0000000..9a886f2 --- /dev/null +++ b/node-v0.8.14/benchmark/http_simple_cluster.js @@ -0,0 +1,9 @@ +var cluster = require('cluster'); +var os = require('os'); + +if (cluster.isMaster) { + console.log('master running on pid %d', process.pid); + for (var i = 0, n = os.cpus().length; i < n; ++i) cluster.fork(); +} else { + require(__dirname + '/http_simple.js'); +} diff --git a/node-v0.8.14/benchmark/idle_clients.js b/node-v0.8.14/benchmark/idle_clients.js new file mode 100644 index 0000000..da96b8a --- /dev/null +++ b/node-v0.8.14/benchmark/idle_clients.js @@ -0,0 +1,49 @@ +net = require('net'); + +var errors = 0, connections = 0; + +var lastClose = 0; + +function connect () { + process.nextTick(function () { + var s = net.Stream(); + var gotConnected = false; + s.connect(9000); + + s.on('connect', function () { + gotConnected = true; + connections++; + connect(); + }); + + s.on('close', function () { + if (gotConnected) connections--; + lastClose = new Date(); + }); + + s.on('error', function () { + errors++; + }); + }); +} + +connect(); + + +var oldConnections, oldErrors; + +// Try to start new connections every so often +setInterval(connect, 5000); + +setInterval(function () { + if (oldConnections != connections) { + oldConnections = connections; + console.log("CLIENT %d connections: %d", process.pid, connections); + } + + if (oldErrors != errors) { + oldErrors = errors; + console.log("CLIENT %d errors: %d", process.pid, errors); + } +}, 1000); + diff --git a/node-v0.8.14/benchmark/idle_server.js b/node-v0.8.14/benchmark/idle_server.js new file mode 100644 index 0000000..a4c70d7 --- /dev/null +++ b/node-v0.8.14/benchmark/idle_server.js @@ -0,0 +1,31 @@ +net = require('net'); +connections = 0; + +var errors = 0; + +server = net.Server(function (socket) { + + socket.on('error', function () { + errors++; + }); + +}); + +//server.maxConnections = 128; + +server.listen(9000); + +var oldConnections, oldErrors; + +setInterval(function () { + if (oldConnections != server.connections) { + oldConnections = server.connections; + console.log("SERVER %d connections: %d", process.pid, server.connections); + } + + if (oldErrors != errors) { + oldErrors = errors; + console.log("SERVER %d errors: %d", process.pid, errors); + } +}, 1000); + diff --git a/node-v0.8.14/benchmark/io.c b/node-v0.8.14/benchmark/io.c new file mode 100644 index 0000000..a4f4575 --- /dev/null +++ b/node-v0.8.14/benchmark/io.c @@ -0,0 +1,122 @@ +/** + * gcc -o iotest io.c + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +static int c = 0; +static int tsize = 1000 * 1048576; +static const char path[] = "/tmp/wt.dat"; +static char buf[65536]; + +static uint64_t now(void) { + struct timeval tv; + + if (gettimeofday(&tv, NULL)) + abort(); + + return tv.tv_sec * 1000000ULL + tv.tv_usec; +} + +static void writetest(int size, size_t bsize) +{ + int i; + uint64_t start, end; + double elapsed; + double mbps; + + assert(bsize <= sizeof buf); + + int fd = open(path, O_CREAT|O_WRONLY, 0644); + if (fd < 0) { + perror("open failed"); + exit(254); + } + + start = now(); + + for (i = 0; i < size; i += bsize) { + int rv = write(fd, buf, bsize); + if (c++ % 2000 == 0) fprintf(stderr, "."); + if (rv < 0) { + perror("write failed"); + exit(254); + } + } + +#ifndef NSYNC +# ifdef __linux__ + fdatasync(fd); +# else + fsync(fd); +# endif +#endif /* SYNC */ + + close(fd); + + end = now(); + elapsed = (end - start) / 1e6; + mbps = ((tsize/elapsed)) / 1048576; + + fprintf(stderr, "\nWrote %d bytes in %03fs using %ld byte buffers: %03fmB/s\n", size, elapsed, bsize, mbps); +} + +void readtest(int size, size_t bsize) +{ + int i; + uint64_t start, end; + double elapsed; + double mbps; + + assert(bsize <= sizeof buf); + + int fd = open(path, O_RDONLY, 0644); + if (fd < 0) { + perror("open failed"); + exit(254); + } + + start = now(); + + for (i = 0; i < size; i += bsize) { + int rv = read(fd, buf, bsize); + if (rv < 0) { + perror("write failed"); + exit(254); + } + } + close(fd); + + end = now(); + elapsed = (end - start) / 1e6; + mbps = ((tsize/elapsed)) / 1048576; + + fprintf(stderr, "Read %d bytes in %03fs using %ld byte buffers: %03fmB/s\n", size, elapsed, bsize, mbps); +} + +void cleanup() { + unlink(path); +} + +int main() +{ + int i; + int bsizes[] = {1024, 4096, 8192, 16384, 32768, 65536, 0}; + + for (i = 0; bsizes[i] != 0; i++) { + writetest(tsize, bsizes[i]); + } + for (i = 0; bsizes[i] != 0; i++) { + readtest(tsize, bsizes[i]); + } + atexit(cleanup); + return 0; +} diff --git a/node-v0.8.14/benchmark/io.js b/node-v0.8.14/benchmark/io.js new file mode 100644 index 0000000..1c18e05 --- /dev/null +++ b/node-v0.8.14/benchmark/io.js @@ -0,0 +1,109 @@ +var fs = require('fs'); +var util = require('util'); +var Buffer = require('buffer').Buffer; + +var path = "/tmp/wt.dat"; +var tsize = 1000 * 1048576; +var bsizes = [1024, 4096, 8192, 16384, 32768, 65536]; + +function bufit(size) { + var buf = new Buffer(size); + for (var i = 0; i 0) { + //if (remaining % 90000 == 0) console.error("remaining: %d", remaining); + //process.nextTick(dowrite); + } else { + s.emit('done') + s.end(); + } + } + + s.on('drain', function () { + dowrite(); + if (c++ % 2000 == 0) util.print("."); + }); + + dowrite(); + + return s; +} + +function readtest(size, bsize) { + var s = fs.createReadStream(path, {'flags': 'r', 'encoding': 'binary', 'mode': 0644, 'bufferSize': bsize}); + s.addListener("data", function (chunk) { + // got a chunk... + + }); + return s; +} + +function wt(tsize, bsize, done) { + var start = Date.now(); + s = writetest(tsize, bsize); + s.addListener('close', function() { + var end = Date.now(); + var diff = end - start; + console.log('Wrote '+ tsize +' bytes in '+ diff/1000 +'s using '+ bsize +' byte buffers: '+ ((tsize/(diff/1000)) / 1048576) +' mB/s'); + done(); + }); +} + +function rt(tsize, bsize, done) { + var start = Date.now(); + s = readtest(tsize, bsize); + s.addListener('close', function() { + var end = Date.now(); + var diff = end - start; + console.log('Read '+ tsize +' bytes in '+ diff/1000 +'s using '+ bsize +' byte buffers: '+ ((tsize/(diff/1000)) / 1048576) +' mB/s'); + done(); + }); +} + +var bs= 0; + +function nextwt() { + if (bsizes.length <= bs) { + bs = 0; + nextrt(); + return; + } + wt(tsize, bsizes[bs], nextwt); + bs += 1; +} + +function nextrt() { + if (bsizes.length <= bs) { + fs.unlink(path, function (err) { + if (err) throw err; + console.log('All done!'); + }); + return; + } + rt(tsize, bsizes[bs], nextrt); + bs += 1; +} + +nextwt(); diff --git a/node-v0.8.14/benchmark/next-tick-2.js b/node-v0.8.14/benchmark/next-tick-2.js new file mode 100644 index 0000000..44a2b41 --- /dev/null +++ b/node-v0.8.14/benchmark/next-tick-2.js @@ -0,0 +1,41 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var count = 2e6, + left = count, + start; + +function onNextTick() { + if (--left) { + process.nextTick(onNextTick); + } else { + finalize(); + } +} + +function finalize() { + var duration = (new Date()).getTime() - start, + ticksPerSec = count / duration * 1000; + console.log("nextTick callbacks per second: " + Math.round(ticksPerSec)); +} + +start = (new Date()).getTime(); +process.nextTick(onNextTick); diff --git a/node-v0.8.14/benchmark/next-tick.js b/node-v0.8.14/benchmark/next-tick.js new file mode 100644 index 0000000..9352f8d --- /dev/null +++ b/node-v0.8.14/benchmark/next-tick.js @@ -0,0 +1,17 @@ +// run with `time node benchmark/next-tick.js` +var assert = require('assert'); + +var N = 1e7; +var n = 0; + +process.on('exit', function() { + assert.equal(n, N); +}); + +function cb() { + n++; +} + +for (var i = 0; i < N; ++i) { + process.nextTick(cb); +} diff --git a/node-v0.8.14/benchmark/plot.R b/node-v0.8.14/benchmark/plot.R new file mode 100755 index 0000000..1f902ed --- /dev/null +++ b/node-v0.8.14/benchmark/plot.R @@ -0,0 +1,86 @@ +#!/usr/bin/env Rscript + +# To use this script you'll need to install R: http://www.r-project.org/ +# and a library for R called ggplot2 +# Which can be done by starting R and typing install.packages("ggplot2") +# like this: +# +# shell% R +# R version 2.11.0 beta (2010-04-12 r51689) +# > install.packages("ggplot2") +# (follow prompt) +# +# Then you can try this script by providing a full path to .data file +# outputed from 'make bench' +# +# > cd ~/src/node +# > make bench +# ... +# > ./benchmark/plot.R .benchmark_reports/ab-hello-world-buffer-1024/ff456b38862de3fd0118c6ac6b3f46edb1fbb87f/20101013162056.data +# +# This will generate a PNG file which you can view +# +# +# Hopefully these steps will be automated in the future. + + + +library(ggplot2) + +args <- commandArgs(TRUE) + +ab.load <- function (filename, name) { + raw <- data.frame(read.csv(filename, sep="\t", header=T), server=name) + raw <- data.frame(raw, time=raw$seconds-min(raw$seconds)) + raw <- data.frame(raw, time_s=raw$time/1000000) + raw +} + +#ab.tsPoint <- function (d) { +# qplot(time_s, ttime, data=d, facets=server~., +# geom="point", alpha=I(1/15), ylab="response time (ms)", +# xlab="time (s)", main="c=30, res=26kb", +# ylim=c(0,100)) +#} +# +#ab.tsLine <- function (d) { +# qplot(time_s, ttime, data=d, facets=server~., +# geom="line", ylab="response time (ms)", +# xlab="time (s)", main="c=30, res=26kb", +# ylim=c(0,100)) +#} + + +filename <- args[0:1] +data <- ab.load(filename, "node") + + +# histogram + +#hist_png_filename <- gsub(".data", "_hist.png", filename) +hist_png_filename <- "hist.png" + +png(filename = hist_png_filename, width = 480, height = 380, units = "px") + +qplot(ttime, data=data, geom="histogram", + main="xxx", + binwidth=1, xlab="response time (ms)", + xlim=c(0,100)) + +print(hist_png_filename) + + + +# time series + +#ts_png_filename <- gsub(".data", "_ts.png", filename) +ts_png_filename = "ts.png" + +png(filename = ts_png_filename, width = 480, height = 380, units = "px") + +qplot(time, ttime, data=data, facets=server~., + geom="point", alpha=I(1/15), ylab="response time (ms)", + xlab="time (s)", main="xxx", + ylim=c(0,100)) + +print(ts_png_filename) diff --git a/node-v0.8.14/benchmark/process_loop.js b/node-v0.8.14/benchmark/process_loop.js new file mode 100644 index 0000000..eeba06a --- /dev/null +++ b/node-v0.8.14/benchmark/process_loop.js @@ -0,0 +1,19 @@ +var util = require("util"), + childProcess = require("child_process"); + +function next (i) { + if (i <= 0) return; + + var child = childProcess.spawn("echo", ["hello"]); + + child.stdout.addListener("data", function (chunk) { + util.print(chunk); + }); + + child.addListener("exit", function (code) { + if (code != 0) process.exit(-1); + next(i - 1); + }); +} + +next(500); diff --git a/node-v0.8.14/benchmark/report-startup-memory.js b/node-v0.8.14/benchmark/report-startup-memory.js new file mode 100644 index 0000000..14e5623 --- /dev/null +++ b/node-v0.8.14/benchmark/report-startup-memory.js @@ -0,0 +1 @@ +console.log(process.memoryUsage().rss); diff --git a/node-v0.8.14/benchmark/run.js b/node-v0.8.14/benchmark/run.js new file mode 100644 index 0000000..2891687 --- /dev/null +++ b/node-v0.8.14/benchmark/run.js @@ -0,0 +1,31 @@ +var path = require("path"); +var util = require("util"); +var childProcess = require("child_process"); +var benchmarks = [ "timers.js" + , "process_loop.js" + , "static_http_server.js" + ]; + +var benchmarkDir = path.dirname(__filename); + +function exec (script, callback) { + var start = new Date(); + var child = childProcess.spawn(process.argv[0], [path.join(benchmarkDir, script)]); + child.addListener("exit", function (code) { + var elapsed = new Date() - start; + callback(elapsed, code); + }); +} + +function runNext (i) { + if (i >= benchmarks.length) return; + util.print(benchmarks[i] + ": "); + exec(benchmarks[i], function (elapsed, code) { + if (code != 0) { + console.log("ERROR "); + } + console.log(elapsed); + runNext(i+1); + }); +}; +runNext(0); diff --git a/node-v0.8.14/benchmark/settimeout.js b/node-v0.8.14/benchmark/settimeout.js new file mode 100644 index 0000000..dd52dc9 --- /dev/null +++ b/node-v0.8.14/benchmark/settimeout.js @@ -0,0 +1,15 @@ +console.log("wait..."); +var done = 0; +var N = 5000000; +var begin = new Date(); +for (var i = 0; i < N; i++) { + setTimeout(function () { + if (++done == N) { + var end = new Date(); + console.log("smaller is better"); + console.log("startup: %d", start - begin); + console.log("done: %d", end - start); + } + }, 1000); +} +var start = new Date(); diff --git a/node-v0.8.14/benchmark/startup.js b/node-v0.8.14/benchmark/startup.js new file mode 100644 index 0000000..97bb8d5 --- /dev/null +++ b/node-v0.8.14/benchmark/startup.js @@ -0,0 +1,26 @@ +var spawn = require('child_process').spawn, + path = require('path'), + emptyJsFile = path.join(__dirname, '../test/fixtures/semicolon.js'), + starts = 100, + i = 0, + start; + +function startNode() { + var node = spawn(process.execPath || process.argv[0], [emptyJsFile]); + node.on('exit', function(exitCode) { + if (exitCode !== 0) { + throw new Error('Error during node startup'); + } + + i++; + if (i < starts) { + startNode(); + } else{ + var duration = +new Date - start; + console.log('Started node %d times in %s ms. %d ms / start.', starts, duration, duration / starts); + } + }); +} + +start = +new Date; +startNode(); diff --git a/node-v0.8.14/benchmark/static_http_server.js b/node-v0.8.14/benchmark/static_http_server.js new file mode 100644 index 0000000..4884224 --- /dev/null +++ b/node-v0.8.14/benchmark/static_http_server.js @@ -0,0 +1,43 @@ +var http = require('http'); + +var concurrency = 30; +var port = 12346; +var n = 700; +var bytes = 1024*5; + +var requests = 0; +var responses = 0; + +var body = ''; +for (var i = 0; i < bytes; i++) { + body += 'C'; +} + +var server = http.createServer(function(req, res) { + res.writeHead(200, { + 'Content-Type': 'text/plain', + 'Content-Length': body.length + }); + res.end(body); +}) + +server.listen(port, function() { + var agent = new http.Agent(); + agent.maxSockets = concurrency; + + for (var i = 0; i < n; i++) { + var req = http.get({ + port: port, + path: '/', + agent: agent + }, function(res) { + res.on('end', function() { + if (++responses === n) { + server.close(); + } + }); + }); + req.id = i; + requests++; + } +}); diff --git a/node-v0.8.14/benchmark/string_creation.js b/node-v0.8.14/benchmark/string_creation.js new file mode 100644 index 0000000..7f81ec1 --- /dev/null +++ b/node-v0.8.14/benchmark/string_creation.js @@ -0,0 +1,6 @@ + + +for (var i = 0; i < 9e7; i++) { + s = '01234567890'; + s[1] = "a"; +} diff --git a/node-v0.8.14/benchmark/throughput-child.js b/node-v0.8.14/benchmark/throughput-child.js new file mode 100644 index 0000000..5cd5c47 --- /dev/null +++ b/node-v0.8.14/benchmark/throughput-child.js @@ -0,0 +1,25 @@ +var net = require('net'); +var received = 0; +var start = new Date(); +var socket = net.connect(8000); + +socket.on('data', function(d) { + received += d.length; +}); + +var interval = setInterval(function() { + // After 1 gigabyte shutdown. + if (received > 10 * 1024 * 1024 * 1024) { + socket.destroy(); + clearInterval(interval); + process.exit(0); + } else { + // Otherwise print some stats. + var now = new Date(); + var gigabytes = received / (1024 * 1024 * 1024); + var gigabits = gigabytes * 8.0; + var millisec = now - start; + var sec = millisec / 1000; + console.log((gigabits / sec) + " gbit/sec") + } +}, 1000); diff --git a/node-v0.8.14/benchmark/throughput.js b/node-v0.8.14/benchmark/throughput.js new file mode 100644 index 0000000..a1ff1b6 --- /dev/null +++ b/node-v0.8.14/benchmark/throughput.js @@ -0,0 +1,21 @@ +var fork = require('child_process').fork; +var net = require('net'); +var buffer = new Buffer(1024 * 1024); + +function write(socket) { + if (!socket.writable) return; + + socket.write(buffer, function() { + write(socket); + }); +} + +var server = net.createServer(function(socket) { + server.close(); + write(socket); +}); + +server.listen(8000, function() { + fork(__dirname + '/throughput-child.js'); +}); + diff --git a/node-v0.8.14/benchmark/timers.js b/node-v0.8.14/benchmark/timers.js new file mode 100644 index 0000000..095cca1 --- /dev/null +++ b/node-v0.8.14/benchmark/timers.js @@ -0,0 +1,5 @@ +function next (i) { + if (i <= 0) return; + setTimeout(function () { next(i-1); }, 1); +} +next(700); diff --git a/node-v0.8.14/benchmark/tls-connect.js b/node-v0.8.14/benchmark/tls-connect.js new file mode 100644 index 0000000..512adca --- /dev/null +++ b/node-v0.8.14/benchmark/tls-connect.js @@ -0,0 +1,86 @@ + +var assert = require('assert'), + fs = require('fs'), + path = require('path'), + tls = require('tls'); + + +var target_connections = 10000, + concurrency = 10; + +for (var i = 2; i < process.argv.length; i++) { + switch (process.argv[i]) { + case '-c': + concurrency = ~~process.argv[++i]; + break; + + case '-n': + target_connections = ~~process.argv[++i]; + break; + + default: + throw new Error('Invalid flag: ' + process.argv[i]); + } +} + + +var cert_dir = path.resolve(__dirname, '../test/fixtures'), + options = { key: fs.readFileSync(cert_dir + '/test_key.pem'), + cert: fs.readFileSync(cert_dir + '/test_cert.pem'), + ca: [ fs.readFileSync(cert_dir + '/test_ca.pem') ] }; + +var server = tls.createServer(options, onConnection); +server.listen(8000); + + +var initiated_connections = 0, + server_connections = 0, + client_connections = 0, + start = Date.now(); + +for (var i = 0; i < concurrency; i++) + makeConnection(); + + +process.on('exit', onExit); + + +function makeConnection() { + if (initiated_connections >= target_connections) + return; + + initiated_connections++; + + var conn = tls.connect(8000, function() { + client_connections++; + + if (client_connections % 100 === 0) + console.log(client_connections + ' of ' + target_connections + + ' connections made'); + + conn.end(); + makeConnection(); + }); +} + + +function onConnection(conn) { + server_connections++; + + if (server_connections === target_connections) + server.close(); +} + + +function onExit() { + var end = Date.now(), + s = (end - start) / 1000, + persec = Math.round(target_connections / s); + + assert.equal(initiated_connections, target_connections); + assert.equal(client_connections, target_connections); + assert.equal(server_connections, target_connections); + + console.log('%d connections in %d s', target_connections, s); + console.log('%d connections per second', persec); +} diff --git a/node-v0.8.14/benchmark/tls-fragmentation.js b/node-v0.8.14/benchmark/tls-fragmentation.js new file mode 100644 index 0000000..5abe093 --- /dev/null +++ b/node-v0.8.14/benchmark/tls-fragmentation.js @@ -0,0 +1,63 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +if (!process.versions.openssl) { + console.error('Skipping because node compiled without OpenSSL.'); + process.exit(0); +} + +var common = require('../common'); +var assert = require('assert'); +var tls = require('tls'); +var fs = require('fs'); +var path = require('path'); + +var options = { + key: fs.readFileSync(path.join(common.fixturesDir, 'test_key.pem')), + cert: fs.readFileSync(path.join(common.fixturesDir, 'test_cert.pem')) +}; + +var fragment = 'fr'; +var dataSize = 1024 * 1024; +var sent = 0; +var received = 0; + +var server = tls.createServer(options, function (stream) { + for (sent = 0; sent <= dataSize; sent += fragment.length) { + stream.write(fragment); + } + stream.end(); +}); + +server.listen(common.PORT, function () { + var client = tls.connect(common.PORT, function () { + client.on('data', function (data) { + received += data.length; + }); + client.on('end', function () { + server.close(); + }); + }); +}); + +process.on('exit', function () { + assert.equal(sent, received); +}); diff --git a/node-v0.8.14/benchmark/v8_bench.js b/node-v0.8.14/benchmark/v8_bench.js new file mode 100644 index 0000000..fbd3748 --- /dev/null +++ b/node-v0.8.14/benchmark/v8_bench.js @@ -0,0 +1,15 @@ +// compare with "google-chrome deps/v8/benchmarks/run.html" +var fs = require('fs'); +var path = require('path'); +var vm = require('vm'); + +var dir = path.join(__dirname, '..', 'deps', 'v8', 'benchmarks'); + +global.print = console.log; + +global.load = function (x) { + var source = fs.readFileSync(path.join(dir, x), 'utf8'); + vm.runInThisContext(source, x); +} + +load('run.js'); diff --git a/node-v0.8.14/common.gypi b/node-v0.8.14/common.gypi new file mode 100644 index 0000000..b26d2f3 --- /dev/null +++ b/node-v0.8.14/common.gypi @@ -0,0 +1,225 @@ +{ + 'variables': { + 'visibility%': 'hidden', # V8's visibility setting + 'target_arch%': 'ia32', # set v8's target architecture + 'host_arch%': 'ia32', # set v8's host architecture + 'want_separate_host_toolset': 0, # V8 should not build target and host + 'library%': 'static_library', # allow override to 'shared_library' for DLL/.so builds + 'component%': 'static_library', # NB. these names match with what V8 expects + 'msvs_multi_core_compile': '0', # we do enable multicore compiles, but not using the V8 way + 'gcc_version%': 'unknown', + 'clang%': 0, + + # Turn on optimizations that may trigger compiler bugs. + # Use at your own risk. Do *NOT* report bugs if this option is enabled. + 'node_unsafe_optimizations%': 0, + + # Enable V8's post-mortem debugging only on unix flavors. + 'conditions': [ + ['OS != "win"', { + 'v8_postmortem_support': 'true' + }] + ], + }, + + 'target_defaults': { + 'default_configuration': 'Release', + 'configurations': { + 'Debug': { + 'defines': [ 'DEBUG', '_DEBUG' ], + 'cflags': [ '-g', '-O0' ], + 'conditions': [ + ['target_arch=="x64"', { + 'msvs_configuration_platform': 'x64', + }], + ], + 'msvs_settings': { + 'VCCLCompilerTool': { + 'RuntimeLibrary': 1, # static debug + 'Optimization': 0, # /Od, no optimization + 'MinimalRebuild': 'false', + 'OmitFramePointers': 'false', + 'BasicRuntimeChecks': 3, # /RTC1 + }, + 'VCLinkerTool': { + 'LinkIncremental': 2, # enable incremental linking + }, + }, + }, + 'Release': { + 'conditions': [ + ['target_arch=="x64"', { + 'msvs_configuration_platform': 'x64', + }], + ['node_unsafe_optimizations==1', { + 'cflags': [ '-O3', '-ffunction-sections', '-fdata-sections' ], + 'ldflags': [ '-Wl,--gc-sections' ], + }, { + 'cflags': [ '-O2', '-fno-strict-aliasing' ], + 'cflags!': [ '-O3', '-fstrict-aliasing' ], + 'conditions': [ + # Required by the dtrace post-processor. Unfortunately, + # some gcc/binutils combos generate bad code when + # -ffunction-sections is enabled. Let's hope for the best. + ['OS=="solaris"', { + 'cflags': [ '-ffunction-sections', '-fdata-sections' ], + }, { + 'cflags!': [ '-ffunction-sections', '-fdata-sections' ], + }], + ['clang == 0 and gcc_version >= 40', { + 'cflags': [ '-fno-tree-vrp' ], + }], + ['clang == 0 and gcc_version <= 44', { + 'cflags': [ '-fno-tree-sink' ], + }], + ], + }], + ['OS=="solaris"', { + 'cflags': [ '-fno-omit-frame-pointer' ], + # pull in V8's postmortem metadata + 'ldflags': [ '-Wl,-z,allextract' ] + }], + ], + 'msvs_settings': { + 'VCCLCompilerTool': { + 'RuntimeLibrary': 0, # static release + 'Optimization': 3, # /Ox, full optimization + 'FavorSizeOrSpeed': 1, # /Ot, favour speed over size + 'InlineFunctionExpansion': 2, # /Ob2, inline anything eligible + 'WholeProgramOptimization': 'true', # /GL, whole program optimization, needed for LTCG + 'OmitFramePointers': 'true', + 'EnableFunctionLevelLinking': 'true', + 'EnableIntrinsicFunctions': 'true', + 'RuntimeTypeInfo': 'false', + 'ExceptionHandling': '0', + 'AdditionalOptions': [ + '/MP', # compile across multiple CPUs + ], + }, + 'VCLibrarianTool': { + 'AdditionalOptions': [ + '/LTCG', # link time code generation + ], + }, + 'VCLinkerTool': { + 'LinkTimeCodeGeneration': 1, # link-time code generation + 'OptimizeReferences': 2, # /OPT:REF + 'EnableCOMDATFolding': 2, # /OPT:ICF + 'LinkIncremental': 1, # disable incremental linking + }, + }, + } + }, + 'msvs_settings': { + 'VCCLCompilerTool': { + 'StringPooling': 'true', # pool string literals + 'DebugInformationFormat': 3, # Generate a PDB + 'WarningLevel': 3, + 'BufferSecurityCheck': 'true', + 'ExceptionHandling': 1, # /EHsc + 'SuppressStartupBanner': 'true', + 'WarnAsError': 'false', + }, + 'VCLibrarianTool': { + }, + 'VCLinkerTool': { + 'conditions': [ + ['target_arch=="x64"', { + 'TargetMachine' : 17 # /MACHINE:X64 + }], + ], + 'GenerateDebugInformation': 'true', + 'RandomizedBaseAddress': 2, # enable ASLR + 'DataExecutionPrevention': 2, # enable DEP + 'AllowIsolation': 'true', + 'SuppressStartupBanner': 'true', + 'target_conditions': [ + ['_type=="executable"', { + 'SubSystem': 1, # console executable + }], + ], + }, + }, + 'conditions': [ + ['OS == "win"', { + 'msvs_cygwin_shell': 0, # prevent actions from trying to use cygwin + 'defines': [ + 'WIN32', + # we don't really want VC++ warning us about + # how dangerous C functions are... + '_CRT_SECURE_NO_DEPRECATE', + # ... or that C implementations shouldn't use + # POSIX names + '_CRT_NONSTDC_NO_DEPRECATE', + 'BUILDING_V8_SHARED=1', + 'BUILDING_UV_SHARED=1', + ], + }, { + 'defines': [ + '_LARGEFILE_SOURCE', + '_FILE_OFFSET_BITS=64', + ], + }], + [ 'OS=="linux" or OS=="freebsd" or OS=="openbsd" or OS=="solaris"', { + 'cflags': [ '-Wall', '-pthread', ], + 'cflags_cc': [ '-fno-rtti', '-fno-exceptions' ], + 'ldflags': [ '-pthread', '-rdynamic' ], + 'conditions': [ + [ 'target_arch=="ia32"', { + 'cflags': [ '-m32' ], + 'ldflags': [ '-m32' ], + }], + [ 'target_arch=="x64"', { + 'cflags': [ '-m64' ], + 'ldflags': [ '-m64' ], + }], + [ 'OS=="solaris"', { + 'cflags': [ '-pthreads' ], + 'ldflags': [ '-pthreads' ], + 'cflags!': [ '-pthread' ], + 'ldflags!': [ '-pthread' ], + }], + ], + }], + ['OS=="mac"', { + 'defines': ['_DARWIN_USE_64_BIT_INODE=1'], + 'xcode_settings': { + 'ALWAYS_SEARCH_USER_PATHS': 'NO', + 'GCC_CW_ASM_SYNTAX': 'NO', # No -fasm-blocks + 'GCC_DYNAMIC_NO_PIC': 'NO', # No -mdynamic-no-pic + # (Equivalent to -fPIC) + 'GCC_ENABLE_CPP_EXCEPTIONS': 'NO', # -fno-exceptions + 'GCC_ENABLE_CPP_RTTI': 'NO', # -fno-rtti + 'GCC_ENABLE_PASCAL_STRINGS': 'NO', # No -mpascal-strings + 'GCC_THREADSAFE_STATICS': 'NO', # -fno-threadsafe-statics + 'GCC_VERSION': '4.2', + 'PREBINDING': 'NO', # No -Wl,-prebind + 'MACOSX_DEPLOYMENT_TARGET': '10.5', # -mmacosx-version-min=10.5 + 'USE_HEADERMAP': 'NO', + 'OTHER_CFLAGS': [ + '-fno-strict-aliasing', + ], + 'WARNING_CFLAGS': [ + '-Wall', + '-Wendif-labels', + '-W', + '-Wno-unused-parameter', + ], + }, + 'target_conditions': [ + ['_type!="static_library"', { + 'xcode_settings': {'OTHER_LDFLAGS': ['-Wl,-search_paths_first']}, + }], + ], + 'conditions': [ + ['target_arch=="ia32"', { + 'xcode_settings': {'ARCHS': ['i386']}, + }], + ['target_arch=="x64"', { + 'xcode_settings': {'ARCHS': ['x86_64']}, + }], + ], + }], + ], + } +} diff --git a/node-v0.8.14/configure b/node-v0.8.14/configure new file mode 100755 index 0000000..7211682 --- /dev/null +++ b/node-v0.8.14/configure @@ -0,0 +1,497 @@ +#!/usr/bin/env python +import optparse +import os +import pprint +import re +import subprocess +import sys + +CC = os.environ.get('CC', 'cc') + +root_dir = os.path.dirname(__file__) +sys.path.insert(0, os.path.join(root_dir, 'deps', 'v8', 'tools')) + +# parse our options +parser = optparse.OptionParser() + +parser.add_option("--debug", + action="store_true", + dest="debug", + help="Also build debug build") + +parser.add_option("--prefix", + action="store", + dest="prefix", + help="Select the install prefix (defaults to /usr/local)") + +parser.add_option("--without-npm", + action="store_true", + dest="without_npm", + help="Don\'t install the bundled npm package manager") + +parser.add_option("--without-waf", + action="store_true", + dest="without_waf", + help="Don\'t install node-waf") + +parser.add_option("--without-ssl", + action="store_true", + dest="without_ssl", + help="Build without SSL") + +parser.add_option("--without-snapshot", + action="store_true", + dest="without_snapshot", + help="Build without snapshotting V8 libraries. You might want to set" + " this for cross-compiling. [Default: False]") + +parser.add_option("--shared-v8", + action="store_true", + dest="shared_v8", + help="Link to a shared V8 DLL instead of static linking") + +parser.add_option("--shared-v8-includes", + action="store", + dest="shared_v8_includes", + help="Directory containing V8 header files") + +parser.add_option("--shared-v8-libpath", + action="store", + dest="shared_v8_libpath", + help="A directory to search for the shared V8 DLL") + +parser.add_option("--shared-v8-libname", + action="store", + dest="shared_v8_libname", + help="Alternative lib name to link to (default: 'v8')") + +parser.add_option("--shared-openssl", + action="store_true", + dest="shared_openssl", + help="Link to a shared OpenSSl DLL instead of static linking") + +parser.add_option("--shared-openssl-includes", + action="store", + dest="shared_openssl_includes", + help="Directory containing OpenSSL header files") + +parser.add_option("--shared-openssl-libpath", + action="store", + dest="shared_openssl_libpath", + help="A directory to search for the shared OpenSSL DLLs") + +parser.add_option("--shared-openssl-libname", + action="store", + dest="shared_openssl_libname", + help="Alternative lib name to link to (default: 'crypto,ssl')") + +# deprecated +parser.add_option("--openssl-use-sys", + action="store_true", + dest="shared_openssl", + help=optparse.SUPPRESS_HELP) + +# deprecated +parser.add_option("--openssl-includes", + action="store", + dest="shared_openssl_includes", + help=optparse.SUPPRESS_HELP) + +# deprecated +parser.add_option("--openssl-libpath", + action="store", + dest="shared_openssl_libpath", + help=optparse.SUPPRESS_HELP) + +parser.add_option("--no-ssl2", + action="store_true", + dest="no_ssl2", + help="Disable OpenSSL v2") + +parser.add_option("--shared-zlib", + action="store_true", + dest="shared_zlib", + help="Link to a shared zlib DLL instead of static linking") + +parser.add_option("--shared-zlib-includes", + action="store", + dest="shared_zlib_includes", + help="Directory containing zlib header files") + +parser.add_option("--shared-zlib-libpath", + action="store", + dest="shared_zlib_libpath", + help="A directory to search for the shared zlib DLL") + +parser.add_option("--shared-zlib-libname", + action="store", + dest="shared_zlib_libname", + help="Alternative lib name to link to (default: 'z')") + +parser.add_option("--with-dtrace", + action="store_true", + dest="with_dtrace", + help="Build with DTrace (default is true on supported systems)") + +parser.add_option("--without-dtrace", + action="store_true", + dest="without_dtrace", + help="Build without DTrace") + +parser.add_option("--with-etw", + action="store_true", + dest="with_etw", + help="Build with ETW (default is true on Windows)") + +parser.add_option("--without-etw", + action="store_true", + dest="without_etw", + help="Build without ETW") + +# CHECKME does this still work with recent releases of V8? +parser.add_option("--gdb", + action="store_true", + dest="gdb", + help="add gdb support") + +parser.add_option("--dest-cpu", + action="store", + dest="dest_cpu", + help="CPU architecture to build for. Valid values are: arm, ia32, x64") + +parser.add_option("--dest-os", + action="store", + dest="dest_os", + help="Operating system to build for. Valid values are: " + "win, mac, solaris, freebsd, linux") + +parser.add_option("--no-ifaddrs", + action="store_true", + dest="no_ifaddrs", + help="Use on deprecated SunOS systems that do not support ifaddrs.h") + +parser.add_option("--with-arm-float-abi", + action="store", + dest="arm_float_abi", + help="Specifies which floating-point ABI to use. Valid values are: " + "soft, softfp, hard") + +# Using --unsafe-optimizations voids your warranty. +parser.add_option("--unsafe-optimizations", + action="store_true", + dest="unsafe_optimizations", + help=optparse.SUPPRESS_HELP) + +(options, args) = parser.parse_args() + + +def b(value): + """Returns the string 'true' if value is truthy, 'false' otherwise.""" + if value: + return 'true' + else: + return 'false' + + +def pkg_config(pkg): + cmd = os.popen('pkg-config --libs %s' % pkg, 'r') + libs = cmd.readline().strip() + ret = cmd.close() + if (ret): return None + + cmd = os.popen('pkg-config --cflags %s' % pkg, 'r') + cflags = cmd.readline().strip() + ret = cmd.close() + if (ret): return None + + return (libs, cflags) + + +def cc_macros(): + """Checks predefined macros using the CC command.""" + + try: + p = subprocess.Popen(CC.split() + ['-dM', '-E', '-'], + stdin=subprocess.PIPE, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE) + except OSError: + print '''Node.js configure error: No acceptable C compiler found! + + Please make sure you have a C compiler installed on your system and/or + consider adjusting the CC environment variable if you installed + it in a non-standard prefix. + ''' + sys.exit() + + p.stdin.write('\n') + out = p.communicate()[0] + + out = str(out).split('\n') + + k = {} + for line in out: + import shlex + lst = shlex.split(line) + if len(lst) > 2: + key = lst[1] + val = lst[2] + k[key] = val + return k + + +def is_arch_armv7(): + """Check for ARMv7 instructions""" + cc_macros_cache = cc_macros() + return ('__ARM_ARCH_7__' in cc_macros_cache or + '__ARM_ARCH_7A__' in cc_macros_cache or + '__ARM_ARCH_7R__' in cc_macros_cache or + '__ARM_ARCH_7M__' in cc_macros_cache) + + +def arm_hard_float_abi(): + """Check for hardfloat or softfloat eabi on ARM""" + # GCC versions 4.6 and above define __ARM_PCS or __ARM_PCS_VFP to specify + # the Floating Point ABI used (PCS stands for Procedure Call Standard). + # We use these as well as a couple of other defines to statically determine + # what FP ABI used. + # GCC versions 4.4 and below don't support hard-fp. + # GCC versions 4.5 may support hard-fp without defining __ARM_PCS or + # __ARM_PCS_VFP. + + if compiler_version() >= (4, 6, 0): + return '__ARM_PCS_VFP' in cc_macros() + elif compiler_version() < (4, 5, 0): + return False + elif '__ARM_PCS_VFP' in cc_macros(): + return True + elif ('__ARM_PCS' in cc_macros() or + '__SOFTFP' in cc_macros() or + not '__VFP_FP__' in cc_macros()): + return False + else: + print '''Node.js configure error: Your version of GCC does not report + the Floating-Point ABI to compile for your hardware + + Please manually specify which floating-point ABI to use with the + --with-arm-float-abi option. + ''' + sys.exit() + + +def host_arch_cc(): + """Host architecture check using the CC command.""" + + k = cc_macros() + + matchup = { + '__x86_64__' : 'x64', + '__i386__' : 'ia32', + '__arm__' : 'arm', + } + + rtn = 'ia32' # default + + for i in matchup: + if i in k and k[i] != '0': + rtn = matchup[i] + break + + return rtn + + +def host_arch_win(): + """Host architecture check using environ vars (better way to do this?)""" + + arch = os.environ.get('PROCESSOR_ARCHITECTURE', 'x86') + + matchup = { + 'AMD64' : 'x64', + 'x86' : 'ia32', + 'arm' : 'arm', + } + + return matchup.get(arch, 'ia32') + + +def compiler_version(): + try: + proc = subprocess.Popen(CC.split() + ['--version'], stdout=subprocess.PIPE) + except WindowsError: + return (0, False) + + is_clang = 'clang' in proc.communicate()[0].split('\n')[0] + + proc = subprocess.Popen(CC.split() + ['-dumpversion'], stdout=subprocess.PIPE) + version = tuple(map(int, proc.communicate()[0].split('.'))) + + return (version, is_clang) + + +def configure_arm(o): + # V8 on ARM requires that armv7 is set. CPU Model detected by + # the presence of __ARM_ARCH_7__ and the like defines in compiler + if options.arm_float_abi: + hard_float = options.arm_float_abi == 'hard' + else: + hard_float = arm_hard_float_abi() + o['variables']['v8_use_arm_eabi_hardfloat'] = b(hard_float) + + armv7 = is_arch_armv7() + if armv7: + # CHECKME VFPv3 implies ARMv7+ but is the reverse true as well? + o['variables']['arm_fpu'] = 'vfpv3' + o['variables']['arm_neon'] = 0 + o['variables']['armv7'] = int(armv7) + + +def configure_node(o): + # TODO add gdb + o['variables']['v8_no_strict_aliasing'] = 1 # work around compiler bugs + o['variables']['node_prefix'] = os.path.expanduser(options.prefix or '') + o['variables']['node_install_npm'] = b(not options.without_npm) + o['variables']['node_install_waf'] = b(not options.without_waf) + o['variables']['node_unsafe_optimizations'] = ( + 1 if options.unsafe_optimizations else 0) + o['default_configuration'] = 'Debug' if options.debug else 'Release' + + host_arch = host_arch_win() if os.name == 'nt' else host_arch_cc() + target_arch = options.dest_cpu or host_arch + o['variables']['host_arch'] = host_arch + o['variables']['target_arch'] = target_arch + + if target_arch == 'arm': + configure_arm(o) + + cc_version, is_clang = compiler_version() + o['variables']['clang'] = 1 if is_clang else 0 + + if not is_clang and cc_version != 0: + o['variables']['gcc_version'] = 10 * cc_version[0] + cc_version[1] + + # clang has always supported -fvisibility=hidden, right? + if not is_clang and cc_version < (4,0,0): + o['variables']['visibility'] = '' + + # By default, enable DTrace on SunOS systems. Don't allow it on other + # systems, since it won't work. (The MacOS build process is different than + # SunOS, and we haven't implemented it.) + if sys.platform.startswith('sunos'): + o['variables']['node_use_dtrace'] = b(not options.without_dtrace) + elif b(options.with_dtrace) == 'true': + raise Exception('DTrace is currently only supported on SunOS systems.') + else: + o['variables']['node_use_dtrace'] = 'false' + + if options.no_ifaddrs: + o['defines'] += ['SUNOS_NO_IFADDRS'] + + # By default, enable ETW on Windows. + if sys.platform.startswith('win32'): + o['variables']['node_use_etw'] = b(not options.without_etw); + elif b(options.with_etw) == 'true': + raise Exception('ETW is only supported on Windows.') + else: + o['variables']['node_use_etw'] = 'false' + + +def configure_libz(o): + o['variables']['node_shared_zlib'] = b(options.shared_zlib) + + # assume shared_zlib if one of these is set? + if options.shared_zlib_libpath: + o['libraries'] += ['-L%s' % options.shared_zlib_libpath] + if options.shared_zlib_libname: + o['libraries'] += ['-l%s' % options.shared_zlib_libname] + elif options.shared_zlib: + o['libraries'] += ['-lz'] + if options.shared_zlib_includes: + o['include_dirs'] += [options.shared_zlib_includes] + + +def configure_v8(o): + o['variables']['v8_use_snapshot'] = b(not options.without_snapshot) + o['variables']['node_shared_v8'] = b(options.shared_v8) + + # assume shared_v8 if one of these is set? + if options.shared_v8_libpath: + o['libraries'] += ['-L%s' % options.shared_v8_libpath] + if options.shared_v8_libname: + o['libraries'] += ['-l%s' % options.shared_v8_libname] + elif options.shared_v8: + o['libraries'] += ['-lv8'] + if options.shared_v8_includes: + o['include_dirs'] += [options.shared_v8_includes] + + +def configure_openssl(o): + o['variables']['node_use_openssl'] = b(not options.without_ssl) + o['variables']['node_shared_openssl'] = b(options.shared_openssl) + + if options.without_ssl: + return + + if options.no_ssl2: + o['defines'] += ['OPENSSL_NO_SSL2=1'] + + if options.shared_openssl: + (libs, cflags) = pkg_config('openssl') or ('-lssl -lcrypto', '') + + if options.shared_openssl_libpath: + o['libraries'] += ['-L%s' % options.shared_openssl_libpath] + + if options.shared_openssl_libname: + libnames = options.shared_openssl_libname.split(',') + o['libraries'] += ['-l%s' % s for s in libnames] + else: + o['libraries'] += libs.split() + + if options.shared_openssl_includes: + o['include_dirs'] += [options.shared_openssl_includes] + else: + o['cflags'] += cflags.split() + + +output = { + 'variables': {}, + 'include_dirs': [], + 'libraries': [], + 'defines': [], + 'cflags': [], +} + +configure_node(output) +configure_libz(output) +configure_v8(output) +configure_openssl(output) + +# variables should be a root level element, +# move everything else to target_defaults +variables = output['variables'] +del output['variables'] +output = { + 'variables': variables, + 'target_defaults': output +} +pprint.pprint(output, indent=2) + +def write(filename, data): + filename = os.path.join(root_dir, filename) + print "creating ", filename + f = open(filename, 'w+') + f.write(data) + +write('config.gypi', "# Do not edit. Generated by the configure script.\n" + + pprint.pformat(output, indent=2) + "\n") + +write('config.mk', "# Do not edit. Generated by the configure script.\n" + + ("BUILDTYPE=%s\n" % ('Debug' if options.debug else 'Release'))) + +if os.name == 'nt': + gyp_args = ['-f', 'msvs', '-G', 'msvs_version=2010'] +elif options.dest_os: + gyp_args = ['-f', 'make-' + options.dest_os] +else: + gyp_args = ['-f', 'make'] + +subprocess.call([sys.executable, 'tools/gyp_node'] + gyp_args) diff --git a/node-v0.8.14/deps/http_parser/.gitignore b/node-v0.8.14/deps/http_parser/.gitignore new file mode 100644 index 0000000..cfadcbe --- /dev/null +++ b/node-v0.8.14/deps/http_parser/.gitignore @@ -0,0 +1,8 @@ +core +tags +*.o +test +test_g +test_fast +*.mk +*.Makefile diff --git a/node-v0.8.14/deps/http_parser/.mailmap b/node-v0.8.14/deps/http_parser/.mailmap new file mode 100644 index 0000000..c25ea86 --- /dev/null +++ b/node-v0.8.14/deps/http_parser/.mailmap @@ -0,0 +1,4 @@ +# update AUTHORS with: +# git log --all --reverse --format='%aN <%aE>' | perl -ne 'BEGIN{print "# Authors ordered by first contribution.\n"} print unless $h{$_}; $h{$_} = 1' > AUTHORS +Ryan Dahl +Salman Haq diff --git a/node-v0.8.14/deps/http_parser/AUTHORS b/node-v0.8.14/deps/http_parser/AUTHORS new file mode 100644 index 0000000..abe99de --- /dev/null +++ b/node-v0.8.14/deps/http_parser/AUTHORS @@ -0,0 +1,32 @@ +# Authors ordered by first contribution. +Ryan Dahl +Jeremy Hinegardner +Sergey Shepelev +Joe Damato +tomika +Phoenix Sol +Cliff Frey +Ewen Cheslack-Postava +Santiago Gala +Tim Becker +Jeff Terrace +Ben Noordhuis +Nathan Rajlich +Mark Nottingham +Aman Gupta +Tim Becker +Sean Cunningham +Peter Griess +Salman Haq +Cliff Frey +Jon Kolb +Fouad Mardini +Paul Querna +Felix Geisendörfer +koichik +Andre Caron +Ivo Raisr +James McLaughlin +David Gwynne +LE ROUX Thomas +Randy Rizun diff --git a/node-v0.8.14/deps/http_parser/CONTRIBUTIONS b/node-v0.8.14/deps/http_parser/CONTRIBUTIONS new file mode 100644 index 0000000..11ba31e --- /dev/null +++ b/node-v0.8.14/deps/http_parser/CONTRIBUTIONS @@ -0,0 +1,4 @@ +Contributors must agree to the Contributor License Agreement before patches +can be accepted. + +http://spreadsheets2.google.com/viewform?hl=en&formkey=dDJXOGUwbzlYaWM4cHN1MERwQS1CSnc6MQ diff --git a/node-v0.8.14/deps/http_parser/LICENSE-MIT b/node-v0.8.14/deps/http_parser/LICENSE-MIT new file mode 100644 index 0000000..58010b3 --- /dev/null +++ b/node-v0.8.14/deps/http_parser/LICENSE-MIT @@ -0,0 +1,23 @@ +http_parser.c is based on src/http/ngx_http_parse.c from NGINX copyright +Igor Sysoev. + +Additional changes are licensed under the same terms as NGINX and +copyright Joyent, Inc. and other Node contributors. All rights reserved. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to +deal in the Software without restriction, including without limitation the +rights to use, copy, modify, merge, publish, distribute, sublicense, and/or +sell copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS +IN THE SOFTWARE. diff --git a/node-v0.8.14/deps/http_parser/Makefile b/node-v0.8.14/deps/http_parser/Makefile new file mode 100644 index 0000000..8d90f8d --- /dev/null +++ b/node-v0.8.14/deps/http_parser/Makefile @@ -0,0 +1,58 @@ +CC?=gcc +AR?=ar + +CPPFLAGS += -I. +CPPFLAGS_DEBUG = $(CPPFLAGS) -DHTTP_PARSER_STRICT=1 -DHTTP_PARSER_DEBUG=1 +CPPFLAGS_DEBUG += $(CPPFLAGS_DEBUG_EXTRA) +CPPFLAGS_FAST = $(CPPFLAGS) -DHTTP_PARSER_STRICT=0 -DHTTP_PARSER_DEBUG=0 +CPPFLAGS_FAST += $(CPPFLAGS_FAST_EXTRA) + +CFLAGS += -Wall -Wextra -Werror +CFLAGS_DEBUG = $(CFLAGS) -O0 -g $(CFLAGS_DEBUG_EXTRA) +CFLAGS_FAST = $(CFLAGS) -O3 $(CFLAGS_FAST_EXTRA) +CFLAGS_LIB = $(CFLAGS_FAST) -fPIC + +test: test_g test_fast + ./test_g + ./test_fast + +test_g: http_parser_g.o test_g.o + $(CC) $(CFLAGS_DEBUG) $(LDFLAGS) http_parser_g.o test_g.o -o $@ + +test_g.o: test.c http_parser.h Makefile + $(CC) $(CPPFLAGS_DEBUG) $(CFLAGS_DEBUG) -c test.c -o $@ + +http_parser_g.o: http_parser.c http_parser.h Makefile + $(CC) $(CPPFLAGS_DEBUG) $(CFLAGS_DEBUG) -c http_parser.c -o $@ + +test_fast: http_parser.o test.o http_parser.h + $(CC) $(CFLAGS_FAST) $(LDFLAGS) http_parser.o test.o -o $@ + +test.o: test.c http_parser.h Makefile + $(CC) $(CPPFLAGS_FAST) $(CFLAGS_FAST) -c test.c -o $@ + +http_parser.o: http_parser.c http_parser.h Makefile + $(CC) $(CPPFLAGS_FAST) $(CFLAGS_FAST) -c http_parser.c + +test-run-timed: test_fast + while(true) do time ./test_fast > /dev/null; done + +test-valgrind: test_g + valgrind ./test_g + +libhttp_parser.o: http_parser.c http_parser.h Makefile + $(CC) $(CPPFLAGS_FAST) $(CFLAGS_LIB) -c http_parser.c -o libhttp_parser.o + +library: libhttp_parser.o + $(CC) -shared -o libhttp_parser.so libhttp_parser.o + +package: http_parser.o + $(AR) rcs libhttp_parser.a http_parser.o + +tags: http_parser.c http_parser.h test.c + ctags $^ + +clean: + rm -f *.o *.a test test_fast test_g http_parser.tar tags libhttp_parser.so libhttp_parser.o + +.PHONY: clean package test-run test-run-timed test-valgrind diff --git a/node-v0.8.14/deps/http_parser/README.md b/node-v0.8.14/deps/http_parser/README.md new file mode 100644 index 0000000..3815e36 --- /dev/null +++ b/node-v0.8.14/deps/http_parser/README.md @@ -0,0 +1,178 @@ +HTTP Parser +=========== + +This is a parser for HTTP messages written in C. It parses both requests and +responses. The parser is designed to be used in performance HTTP +applications. It does not make any syscalls nor allocations, it does not +buffer data, it can be interrupted at anytime. Depending on your +architecture, it only requires about 40 bytes of data per message +stream (in a web server that is per connection). + +Features: + + * No dependencies + * Handles persistent streams (keep-alive). + * Decodes chunked encoding. + * Upgrade support + * Defends against buffer overflow attacks. + +The parser extracts the following information from HTTP messages: + + * Header fields and values + * Content-Length + * Request method + * Response status code + * Transfer-Encoding + * HTTP version + * Request URL + * Message body + + +Usage +----- + +One `http_parser` object is used per TCP connection. Initialize the struct +using `http_parser_init()` and set the callbacks. That might look something +like this for a request parser: + + http_parser_settings settings; + settings.on_path = my_path_callback; + settings.on_header_field = my_header_field_callback; + /* ... */ + + http_parser *parser = malloc(sizeof(http_parser)); + http_parser_init(parser, HTTP_REQUEST); + parser->data = my_socket; + +When data is received on the socket execute the parser and check for errors. + + size_t len = 80*1024, nparsed; + char buf[len]; + ssize_t recved; + + recved = recv(fd, buf, len, 0); + + if (recved < 0) { + /* Handle error. */ + } + + /* Start up / continue the parser. + * Note we pass recved==0 to signal that EOF has been recieved. + */ + nparsed = http_parser_execute(parser, &settings, buf, recved); + + if (parser->upgrade) { + /* handle new protocol */ + } else if (nparsed != recved) { + /* Handle error. Usually just close the connection. */ + } + +HTTP needs to know where the end of the stream is. For example, sometimes +servers send responses without Content-Length and expect the client to +consume input (for the body) until EOF. To tell http_parser about EOF, give +`0` as the forth parameter to `http_parser_execute()`. Callbacks and errors +can still be encountered during an EOF, so one must still be prepared +to receive them. + +Scalar valued message information such as `status_code`, `method`, and the +HTTP version are stored in the parser structure. This data is only +temporally stored in `http_parser` and gets reset on each new message. If +this information is needed later, copy it out of the structure during the +`headers_complete` callback. + +The parser decodes the transfer-encoding for both requests and responses +transparently. That is, a chunked encoding is decoded before being sent to +the on_body callback. + + +The Special Problem of Upgrade +------------------------------ + +HTTP supports upgrading the connection to a different protocol. An +increasingly common example of this is the Web Socket protocol which sends +a request like + + GET /demo HTTP/1.1 + Upgrade: WebSocket + Connection: Upgrade + Host: example.com + Origin: http://example.com + WebSocket-Protocol: sample + +followed by non-HTTP data. + +(See http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol-75 for more +information the Web Socket protocol.) + +To support this, the parser will treat this as a normal HTTP message without a +body. Issuing both on_headers_complete and on_message_complete callbacks. However +http_parser_execute() will stop parsing at the end of the headers and return. + +The user is expected to check if `parser->upgrade` has been set to 1 after +`http_parser_execute()` returns. Non-HTTP data begins at the buffer supplied +offset by the return value of `http_parser_execute()`. + + +Callbacks +--------- + +During the `http_parser_execute()` call, the callbacks set in +`http_parser_settings` will be executed. The parser maintains state and +never looks behind, so buffering the data is not necessary. If you need to +save certain data for later usage, you can do that from the callbacks. + +There are two types of callbacks: + +* notification `typedef int (*http_cb) (http_parser*);` + Callbacks: on_message_begin, on_headers_complete, on_message_complete. +* data `typedef int (*http_data_cb) (http_parser*, const char *at, size_t length);` + Callbacks: (requests only) on_uri, + (common) on_header_field, on_header_value, on_body; + +Callbacks must return 0 on success. Returning a non-zero value indicates +error to the parser, making it exit immediately. + +In case you parse HTTP message in chunks (i.e. `read()` request line +from socket, parse, read half headers, parse, etc) your data callbacks +may be called more than once. Http-parser guarantees that data pointer is only +valid for the lifetime of callback. You can also `read()` into a heap allocated +buffer to avoid copying memory around if this fits your application. + +Reading headers may be a tricky task if you read/parse headers partially. +Basically, you need to remember whether last header callback was field or value +and apply following logic: + + (on_header_field and on_header_value shortened to on_h_*) + ------------------------ ------------ -------------------------------------------- + | State (prev. callback) | Callback | Description/action | + ------------------------ ------------ -------------------------------------------- + | nothing (first call) | on_h_field | Allocate new buffer and copy callback data | + | | | into it | + ------------------------ ------------ -------------------------------------------- + | value | on_h_field | New header started. | + | | | Copy current name,value buffers to headers | + | | | list and allocate new buffer for new name | + ------------------------ ------------ -------------------------------------------- + | field | on_h_field | Previous name continues. Reallocate name | + | | | buffer and append callback data to it | + ------------------------ ------------ -------------------------------------------- + | field | on_h_value | Value for current header started. Allocate | + | | | new buffer and copy callback data to it | + ------------------------ ------------ -------------------------------------------- + | value | on_h_value | Value continues. Reallocate value buffer | + | | | and append callback data to it | + ------------------------ ------------ -------------------------------------------- + + +Parsing URLs +------------ + +A simplistic zero-copy URL parser is provided as `http_parser_parse_url()`. +Users of this library may wish to use it to parse URLs constructed from +consecutive `on_url` callbacks. + +See examples of reading in headers: + +* [partial example](http://gist.github.com/155877) in C +* [from http-parser tests](http://github.com/joyent/http-parser/blob/37a0ff8/test.c#L403) in C +* [from Node library](http://github.com/joyent/node/blob/842eaf4/src/http.js#L284) in Javascript diff --git a/node-v0.8.14/deps/http_parser/http_parser.c b/node-v0.8.14/deps/http_parser/http_parser.c new file mode 100644 index 0000000..acd4130 --- /dev/null +++ b/node-v0.8.14/deps/http_parser/http_parser.c @@ -0,0 +1,2043 @@ +/* Based on src/http/ngx_http_parse.c from NGINX copyright Igor Sysoev + * + * Additional changes are licensed under the same terms as NGINX and + * copyright Joyent, Inc. and other Node contributors. All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +#include "http_parser.h" +#include +#include +#include +#include +#include +#include + +#ifndef ULLONG_MAX +# define ULLONG_MAX ((uint64_t) -1) /* 2^64-1 */ +#endif + +#ifndef MIN +# define MIN(a,b) ((a) < (b) ? (a) : (b)) +#endif + + +#if HTTP_PARSER_DEBUG +#define SET_ERRNO(e) \ +do { \ + parser->http_errno = (e); \ + parser->error_lineno = __LINE__; \ +} while (0) +#else +#define SET_ERRNO(e) \ +do { \ + parser->http_errno = (e); \ +} while(0) +#endif + + +/* Run the notify callback FOR, returning ER if it fails */ +#define CALLBACK_NOTIFY_(FOR, ER) \ +do { \ + assert(HTTP_PARSER_ERRNO(parser) == HPE_OK); \ + \ + if (settings->on_##FOR) { \ + if (0 != settings->on_##FOR(parser)) { \ + SET_ERRNO(HPE_CB_##FOR); \ + } \ + \ + /* We either errored above or got paused; get out */ \ + if (HTTP_PARSER_ERRNO(parser) != HPE_OK) { \ + return (ER); \ + } \ + } \ +} while (0) + +/* Run the notify callback FOR and consume the current byte */ +#define CALLBACK_NOTIFY(FOR) CALLBACK_NOTIFY_(FOR, p - data + 1) + +/* Run the notify callback FOR and don't consume the current byte */ +#define CALLBACK_NOTIFY_NOADVANCE(FOR) CALLBACK_NOTIFY_(FOR, p - data) + +/* Run data callback FOR with LEN bytes, returning ER if it fails */ +#define CALLBACK_DATA_(FOR, LEN, ER) \ +do { \ + assert(HTTP_PARSER_ERRNO(parser) == HPE_OK); \ + \ + if (FOR##_mark) { \ + if (settings->on_##FOR) { \ + if (0 != settings->on_##FOR(parser, FOR##_mark, (LEN))) { \ + SET_ERRNO(HPE_CB_##FOR); \ + } \ + \ + /* We either errored above or got paused; get out */ \ + if (HTTP_PARSER_ERRNO(parser) != HPE_OK) { \ + return (ER); \ + } \ + } \ + FOR##_mark = NULL; \ + } \ +} while (0) + +/* Run the data callback FOR and consume the current byte */ +#define CALLBACK_DATA(FOR) \ + CALLBACK_DATA_(FOR, p - FOR##_mark, p - data + 1) + +/* Run the data callback FOR and don't consume the current byte */ +#define CALLBACK_DATA_NOADVANCE(FOR) \ + CALLBACK_DATA_(FOR, p - FOR##_mark, p - data) + +/* Set the mark FOR; non-destructive if mark is already set */ +#define MARK(FOR) \ +do { \ + if (!FOR##_mark) { \ + FOR##_mark = p; \ + } \ +} while (0) + + +#define PROXY_CONNECTION "proxy-connection" +#define CONNECTION "connection" +#define CONTENT_LENGTH "content-length" +#define TRANSFER_ENCODING "transfer-encoding" +#define UPGRADE "upgrade" +#define CHUNKED "chunked" +#define KEEP_ALIVE "keep-alive" +#define CLOSE "close" + + +static const char *method_strings[] = + { +#define XX(num, name, string) #string, + HTTP_METHOD_MAP(XX) +#undef XX + }; + + +/* Tokens as defined by rfc 2616. Also lowercases them. + * token = 1* + * separators = "(" | ")" | "<" | ">" | "@" + * | "," | ";" | ":" | "\" | <"> + * | "/" | "[" | "]" | "?" | "=" + * | "{" | "}" | SP | HT + */ +static const char tokens[256] = { +/* 0 nul 1 soh 2 stx 3 etx 4 eot 5 enq 6 ack 7 bel */ + 0, 0, 0, 0, 0, 0, 0, 0, +/* 8 bs 9 ht 10 nl 11 vt 12 np 13 cr 14 so 15 si */ + 0, 0, 0, 0, 0, 0, 0, 0, +/* 16 dle 17 dc1 18 dc2 19 dc3 20 dc4 21 nak 22 syn 23 etb */ + 0, 0, 0, 0, 0, 0, 0, 0, +/* 24 can 25 em 26 sub 27 esc 28 fs 29 gs 30 rs 31 us */ + 0, 0, 0, 0, 0, 0, 0, 0, +/* 32 sp 33 ! 34 " 35 # 36 $ 37 % 38 & 39 ' */ + 0, '!', 0, '#', '$', '%', '&', '\'', +/* 40 ( 41 ) 42 * 43 + 44 , 45 - 46 . 47 / */ + 0, 0, '*', '+', 0, '-', '.', 0, +/* 48 0 49 1 50 2 51 3 52 4 53 5 54 6 55 7 */ + '0', '1', '2', '3', '4', '5', '6', '7', +/* 56 8 57 9 58 : 59 ; 60 < 61 = 62 > 63 ? */ + '8', '9', 0, 0, 0, 0, 0, 0, +/* 64 @ 65 A 66 B 67 C 68 D 69 E 70 F 71 G */ + 0, 'a', 'b', 'c', 'd', 'e', 'f', 'g', +/* 72 H 73 I 74 J 75 K 76 L 77 M 78 N 79 O */ + 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', +/* 80 P 81 Q 82 R 83 S 84 T 85 U 86 V 87 W */ + 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', +/* 88 X 89 Y 90 Z 91 [ 92 \ 93 ] 94 ^ 95 _ */ + 'x', 'y', 'z', 0, 0, 0, '^', '_', +/* 96 ` 97 a 98 b 99 c 100 d 101 e 102 f 103 g */ + '`', 'a', 'b', 'c', 'd', 'e', 'f', 'g', +/* 104 h 105 i 106 j 107 k 108 l 109 m 110 n 111 o */ + 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', +/* 112 p 113 q 114 r 115 s 116 t 117 u 118 v 119 w */ + 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', +/* 120 x 121 y 122 z 123 { 124 | 125 } 126 ~ 127 del */ + 'x', 'y', 'z', 0, '|', 0, '~', 0 }; + + +static const int8_t unhex[256] = + {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1 + ,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1 + ,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1 + , 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,-1,-1,-1,-1,-1,-1 + ,-1,10,11,12,13,14,15,-1,-1,-1,-1,-1,-1,-1,-1,-1 + ,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1 + ,-1,10,11,12,13,14,15,-1,-1,-1,-1,-1,-1,-1,-1,-1 + ,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1 + }; + + +static const uint8_t normal_url_char[256] = { +/* 0 nul 1 soh 2 stx 3 etx 4 eot 5 enq 6 ack 7 bel */ + 0, 0, 0, 0, 0, 0, 0, 0, +/* 8 bs 9 ht 10 nl 11 vt 12 np 13 cr 14 so 15 si */ + 0, 0, 0, 0, 0, 0, 0, 0, +/* 16 dle 17 dc1 18 dc2 19 dc3 20 dc4 21 nak 22 syn 23 etb */ + 0, 0, 0, 0, 0, 0, 0, 0, +/* 24 can 25 em 26 sub 27 esc 28 fs 29 gs 30 rs 31 us */ + 0, 0, 0, 0, 0, 0, 0, 0, +/* 32 sp 33 ! 34 " 35 # 36 $ 37 % 38 & 39 ' */ + 0, 1, 1, 0, 1, 1, 1, 1, +/* 40 ( 41 ) 42 * 43 + 44 , 45 - 46 . 47 / */ + 1, 1, 1, 1, 1, 1, 1, 1, +/* 48 0 49 1 50 2 51 3 52 4 53 5 54 6 55 7 */ + 1, 1, 1, 1, 1, 1, 1, 1, +/* 56 8 57 9 58 : 59 ; 60 < 61 = 62 > 63 ? */ + 1, 1, 1, 1, 1, 1, 1, 0, +/* 64 @ 65 A 66 B 67 C 68 D 69 E 70 F 71 G */ + 1, 1, 1, 1, 1, 1, 1, 1, +/* 72 H 73 I 74 J 75 K 76 L 77 M 78 N 79 O */ + 1, 1, 1, 1, 1, 1, 1, 1, +/* 80 P 81 Q 82 R 83 S 84 T 85 U 86 V 87 W */ + 1, 1, 1, 1, 1, 1, 1, 1, +/* 88 X 89 Y 90 Z 91 [ 92 \ 93 ] 94 ^ 95 _ */ + 1, 1, 1, 1, 1, 1, 1, 1, +/* 96 ` 97 a 98 b 99 c 100 d 101 e 102 f 103 g */ + 1, 1, 1, 1, 1, 1, 1, 1, +/* 104 h 105 i 106 j 107 k 108 l 109 m 110 n 111 o */ + 1, 1, 1, 1, 1, 1, 1, 1, +/* 112 p 113 q 114 r 115 s 116 t 117 u 118 v 119 w */ + 1, 1, 1, 1, 1, 1, 1, 1, +/* 120 x 121 y 122 z 123 { 124 | 125 } 126 ~ 127 del */ + 1, 1, 1, 1, 1, 1, 1, 0, }; + + +enum state + { s_dead = 1 /* important that this is > 0 */ + + , s_start_req_or_res + , s_res_or_resp_H + , s_start_res + , s_res_H + , s_res_HT + , s_res_HTT + , s_res_HTTP + , s_res_first_http_major + , s_res_http_major + , s_res_first_http_minor + , s_res_http_minor + , s_res_first_status_code + , s_res_status_code + , s_res_status + , s_res_line_almost_done + + , s_start_req + + , s_req_method + , s_req_spaces_before_url + , s_req_schema + , s_req_schema_slash + , s_req_schema_slash_slash + , s_req_host_start + , s_req_host_v6_start + , s_req_host_v6 + , s_req_host_v6_end + , s_req_host + , s_req_port_start + , s_req_port + , s_req_path + , s_req_query_string_start + , s_req_query_string + , s_req_fragment_start + , s_req_fragment + , s_req_http_start + , s_req_http_H + , s_req_http_HT + , s_req_http_HTT + , s_req_http_HTTP + , s_req_first_http_major + , s_req_http_major + , s_req_first_http_minor + , s_req_http_minor + , s_req_line_almost_done + + , s_header_field_start + , s_header_field + , s_header_value_start + , s_header_value + , s_header_value_lws + + , s_header_almost_done + + , s_chunk_size_start + , s_chunk_size + , s_chunk_parameters + , s_chunk_size_almost_done + + , s_headers_almost_done + , s_headers_done + + /* Important: 's_headers_done' must be the last 'header' state. All + * states beyond this must be 'body' states. It is used for overflow + * checking. See the PARSING_HEADER() macro. + */ + + , s_chunk_data + , s_chunk_data_almost_done + , s_chunk_data_done + + , s_body_identity + , s_body_identity_eof + + , s_message_done + }; + + +#define PARSING_HEADER(state) (state <= s_headers_done) + + +enum header_states + { h_general = 0 + , h_C + , h_CO + , h_CON + + , h_matching_connection + , h_matching_proxy_connection + , h_matching_content_length + , h_matching_transfer_encoding + , h_matching_upgrade + + , h_connection + , h_content_length + , h_transfer_encoding + , h_upgrade + + , h_matching_transfer_encoding_chunked + , h_matching_connection_keep_alive + , h_matching_connection_close + + , h_transfer_encoding_chunked + , h_connection_keep_alive + , h_connection_close + }; + + +/* Macros for character classes; depends on strict-mode */ +#define CR '\r' +#define LF '\n' +#define LOWER(c) (unsigned char)(c | 0x20) +#define IS_ALPHA(c) (LOWER(c) >= 'a' && LOWER(c) <= 'z') +#define IS_NUM(c) ((c) >= '0' && (c) <= '9') +#define IS_ALPHANUM(c) (IS_ALPHA(c) || IS_NUM(c)) +#define IS_HEX(c) (IS_NUM(c) || (LOWER(c) >= 'a' && LOWER(c) <= 'f')) + +#if HTTP_PARSER_STRICT +#define TOKEN(c) (tokens[(unsigned char)c]) +#define IS_URL_CHAR(c) (normal_url_char[(unsigned char) (c)]) +#define IS_HOST_CHAR(c) (IS_ALPHANUM(c) || (c) == '.' || (c) == '-') +#else +#define TOKEN(c) ((c == ' ') ? ' ' : tokens[(unsigned char)c]) +#define IS_URL_CHAR(c) \ + (normal_url_char[(unsigned char) (c)] || ((c) & 0x80)) +#define IS_HOST_CHAR(c) \ + (IS_ALPHANUM(c) || (c) == '.' || (c) == '-' || (c) == '_') +#endif + + +#define start_state (parser->type == HTTP_REQUEST ? s_start_req : s_start_res) + + +#if HTTP_PARSER_STRICT +# define STRICT_CHECK(cond) \ +do { \ + if (cond) { \ + SET_ERRNO(HPE_STRICT); \ + goto error; \ + } \ +} while (0) +# define NEW_MESSAGE() (http_should_keep_alive(parser) ? start_state : s_dead) +#else +# define STRICT_CHECK(cond) +# define NEW_MESSAGE() start_state +#endif + + +/* Map errno values to strings for human-readable output */ +#define HTTP_STRERROR_GEN(n, s) { "HPE_" #n, s }, +static struct { + const char *name; + const char *description; +} http_strerror_tab[] = { + HTTP_ERRNO_MAP(HTTP_STRERROR_GEN) +}; +#undef HTTP_STRERROR_GEN + +int http_message_needs_eof(http_parser *parser); + +/* Our URL parser. + * + * This is designed to be shared by http_parser_execute() for URL validation, + * hence it has a state transition + byte-for-byte interface. In addition, it + * is meant to be embedded in http_parser_parse_url(), which does the dirty + * work of turning state transitions URL components for its API. + * + * This function should only be invoked with non-space characters. It is + * assumed that the caller cares about (and can detect) the transition between + * URL and non-URL states by looking for these. + */ +static enum state +parse_url_char(enum state s, const char ch) +{ + assert(!isspace(ch)); + + switch (s) { + case s_req_spaces_before_url: + /* Proxied requests are followed by scheme of an absolute URI (alpha). + * All methods except CONNECT are followed by '/' or '*'. + */ + + if (ch == '/' || ch == '*') { + return s_req_path; + } + + if (IS_ALPHA(ch)) { + return s_req_schema; + } + + break; + + case s_req_schema: + if (IS_ALPHA(ch)) { + return s; + } + + if (ch == ':') { + return s_req_schema_slash; + } + + break; + + case s_req_schema_slash: + if (ch == '/') { + return s_req_schema_slash_slash; + } + + break; + + case s_req_schema_slash_slash: + if (ch == '/') { + return s_req_host_start; + } + + break; + + case s_req_host_start: + if (ch == '[') { + return s_req_host_v6_start; + } + + if (IS_HOST_CHAR(ch)) { + return s_req_host; + } + + break; + + case s_req_host: + if (IS_HOST_CHAR(ch)) { + return s_req_host; + } + + /* FALLTHROUGH */ + case s_req_host_v6_end: + switch (ch) { + case ':': + return s_req_port_start; + + case '/': + return s_req_path; + + case '?': + return s_req_query_string_start; + } + + break; + + case s_req_host_v6: + if (ch == ']') { + return s_req_host_v6_end; + } + + /* FALLTHROUGH */ + case s_req_host_v6_start: + if (IS_HEX(ch) || ch == ':') { + return s_req_host_v6; + } + break; + + case s_req_port: + switch (ch) { + case '/': + return s_req_path; + + case '?': + return s_req_query_string_start; + } + + /* FALLTHROUGH */ + case s_req_port_start: + if (IS_NUM(ch)) { + return s_req_port; + } + + break; + + case s_req_path: + if (IS_URL_CHAR(ch)) { + return s; + } + + switch (ch) { + case '?': + return s_req_query_string_start; + + case '#': + return s_req_fragment_start; + } + + break; + + case s_req_query_string_start: + case s_req_query_string: + if (IS_URL_CHAR(ch)) { + return s_req_query_string; + } + + switch (ch) { + case '?': + /* allow extra '?' in query string */ + return s_req_query_string; + + case '#': + return s_req_fragment_start; + } + + break; + + case s_req_fragment_start: + if (IS_URL_CHAR(ch)) { + return s_req_fragment; + } + + switch (ch) { + case '?': + return s_req_fragment; + + case '#': + return s; + } + + break; + + case s_req_fragment: + if (IS_URL_CHAR(ch)) { + return s; + } + + switch (ch) { + case '?': + case '#': + return s; + } + + break; + + default: + break; + } + + /* We should never fall out of the switch above unless there's an error */ + return s_dead; +} + +size_t http_parser_execute (http_parser *parser, + const http_parser_settings *settings, + const char *data, + size_t len) +{ + char c, ch; + int8_t unhex_val; + const char *p = data; + const char *header_field_mark = 0; + const char *header_value_mark = 0; + const char *url_mark = 0; + const char *body_mark = 0; + + /* We're in an error state. Don't bother doing anything. */ + if (HTTP_PARSER_ERRNO(parser) != HPE_OK) { + return 0; + } + + if (len == 0) { + switch (parser->state) { + case s_body_identity_eof: + /* Use of CALLBACK_NOTIFY() here would erroneously return 1 byte read if + * we got paused. + */ + CALLBACK_NOTIFY_NOADVANCE(message_complete); + return 0; + + case s_dead: + case s_start_req_or_res: + case s_start_res: + case s_start_req: + return 0; + + default: + SET_ERRNO(HPE_INVALID_EOF_STATE); + return 1; + } + } + + + if (parser->state == s_header_field) + header_field_mark = data; + if (parser->state == s_header_value) + header_value_mark = data; + switch (parser->state) { + case s_req_path: + case s_req_schema: + case s_req_schema_slash: + case s_req_schema_slash_slash: + case s_req_host_start: + case s_req_host_v6_start: + case s_req_host_v6: + case s_req_host_v6_end: + case s_req_host: + case s_req_port_start: + case s_req_port: + case s_req_query_string_start: + case s_req_query_string: + case s_req_fragment_start: + case s_req_fragment: + url_mark = data; + break; + } + + for (p=data; p != data + len; p++) { + ch = *p; + + if (PARSING_HEADER(parser->state)) { + ++parser->nread; + /* Buffer overflow attack */ + if (parser->nread > HTTP_MAX_HEADER_SIZE) { + SET_ERRNO(HPE_HEADER_OVERFLOW); + goto error; + } + } + + reexecute_byte: + switch (parser->state) { + + case s_dead: + /* this state is used after a 'Connection: close' message + * the parser will error out if it reads another message + */ + if (ch == CR || ch == LF) + break; + + SET_ERRNO(HPE_CLOSED_CONNECTION); + goto error; + + case s_start_req_or_res: + { + if (ch == CR || ch == LF) + break; + parser->flags = 0; + parser->content_length = ULLONG_MAX; + + if (ch == 'H') { + parser->state = s_res_or_resp_H; + + CALLBACK_NOTIFY(message_begin); + } else { + parser->type = HTTP_REQUEST; + parser->state = s_start_req; + goto reexecute_byte; + } + + break; + } + + case s_res_or_resp_H: + if (ch == 'T') { + parser->type = HTTP_RESPONSE; + parser->state = s_res_HT; + } else { + if (ch != 'E') { + SET_ERRNO(HPE_INVALID_CONSTANT); + goto error; + } + + parser->type = HTTP_REQUEST; + parser->method = HTTP_HEAD; + parser->index = 2; + parser->state = s_req_method; + } + break; + + case s_start_res: + { + parser->flags = 0; + parser->content_length = ULLONG_MAX; + + switch (ch) { + case 'H': + parser->state = s_res_H; + break; + + case CR: + case LF: + break; + + default: + SET_ERRNO(HPE_INVALID_CONSTANT); + goto error; + } + + CALLBACK_NOTIFY(message_begin); + break; + } + + case s_res_H: + STRICT_CHECK(ch != 'T'); + parser->state = s_res_HT; + break; + + case s_res_HT: + STRICT_CHECK(ch != 'T'); + parser->state = s_res_HTT; + break; + + case s_res_HTT: + STRICT_CHECK(ch != 'P'); + parser->state = s_res_HTTP; + break; + + case s_res_HTTP: + STRICT_CHECK(ch != '/'); + parser->state = s_res_first_http_major; + break; + + case s_res_first_http_major: + if (ch < '0' || ch > '9') { + SET_ERRNO(HPE_INVALID_VERSION); + goto error; + } + + parser->http_major = ch - '0'; + parser->state = s_res_http_major; + break; + + /* major HTTP version or dot */ + case s_res_http_major: + { + if (ch == '.') { + parser->state = s_res_first_http_minor; + break; + } + + if (!IS_NUM(ch)) { + SET_ERRNO(HPE_INVALID_VERSION); + goto error; + } + + parser->http_major *= 10; + parser->http_major += ch - '0'; + + if (parser->http_major > 999) { + SET_ERRNO(HPE_INVALID_VERSION); + goto error; + } + + break; + } + + /* first digit of minor HTTP version */ + case s_res_first_http_minor: + if (!IS_NUM(ch)) { + SET_ERRNO(HPE_INVALID_VERSION); + goto error; + } + + parser->http_minor = ch - '0'; + parser->state = s_res_http_minor; + break; + + /* minor HTTP version or end of request line */ + case s_res_http_minor: + { + if (ch == ' ') { + parser->state = s_res_first_status_code; + break; + } + + if (!IS_NUM(ch)) { + SET_ERRNO(HPE_INVALID_VERSION); + goto error; + } + + parser->http_minor *= 10; + parser->http_minor += ch - '0'; + + if (parser->http_minor > 999) { + SET_ERRNO(HPE_INVALID_VERSION); + goto error; + } + + break; + } + + case s_res_first_status_code: + { + if (!IS_NUM(ch)) { + if (ch == ' ') { + break; + } + + SET_ERRNO(HPE_INVALID_STATUS); + goto error; + } + parser->status_code = ch - '0'; + parser->state = s_res_status_code; + break; + } + + case s_res_status_code: + { + if (!IS_NUM(ch)) { + switch (ch) { + case ' ': + parser->state = s_res_status; + break; + case CR: + parser->state = s_res_line_almost_done; + break; + case LF: + parser->state = s_header_field_start; + break; + default: + SET_ERRNO(HPE_INVALID_STATUS); + goto error; + } + break; + } + + parser->status_code *= 10; + parser->status_code += ch - '0'; + + if (parser->status_code > 999) { + SET_ERRNO(HPE_INVALID_STATUS); + goto error; + } + + break; + } + + case s_res_status: + /* the human readable status. e.g. "NOT FOUND" + * we are not humans so just ignore this */ + if (ch == CR) { + parser->state = s_res_line_almost_done; + break; + } + + if (ch == LF) { + parser->state = s_header_field_start; + break; + } + break; + + case s_res_line_almost_done: + STRICT_CHECK(ch != LF); + parser->state = s_header_field_start; + break; + + case s_start_req: + { + if (ch == CR || ch == LF) + break; + parser->flags = 0; + parser->content_length = ULLONG_MAX; + + if (!IS_ALPHA(ch)) { + SET_ERRNO(HPE_INVALID_METHOD); + goto error; + } + + parser->method = (enum http_method) 0; + parser->index = 1; + switch (ch) { + case 'C': parser->method = HTTP_CONNECT; /* or COPY, CHECKOUT */ break; + case 'D': parser->method = HTTP_DELETE; break; + case 'G': parser->method = HTTP_GET; break; + case 'H': parser->method = HTTP_HEAD; break; + case 'L': parser->method = HTTP_LOCK; break; + case 'M': parser->method = HTTP_MKCOL; /* or MOVE, MKACTIVITY, MERGE, M-SEARCH */ break; + case 'N': parser->method = HTTP_NOTIFY; break; + case 'O': parser->method = HTTP_OPTIONS; break; + case 'P': parser->method = HTTP_POST; + /* or PROPFIND|PROPPATCH|PUT|PATCH|PURGE */ + break; + case 'R': parser->method = HTTP_REPORT; break; + case 'S': parser->method = HTTP_SUBSCRIBE; /* or SEARCH */ break; + case 'T': parser->method = HTTP_TRACE; break; + case 'U': parser->method = HTTP_UNLOCK; /* or UNSUBSCRIBE */ break; + default: + SET_ERRNO(HPE_INVALID_METHOD); + goto error; + } + parser->state = s_req_method; + + CALLBACK_NOTIFY(message_begin); + + break; + } + + case s_req_method: + { + const char *matcher; + if (ch == '\0') { + SET_ERRNO(HPE_INVALID_METHOD); + goto error; + } + + matcher = method_strings[parser->method]; + if (ch == ' ' && matcher[parser->index] == '\0') { + parser->state = s_req_spaces_before_url; + } else if (ch == matcher[parser->index]) { + ; /* nada */ + } else if (parser->method == HTTP_CONNECT) { + if (parser->index == 1 && ch == 'H') { + parser->method = HTTP_CHECKOUT; + } else if (parser->index == 2 && ch == 'P') { + parser->method = HTTP_COPY; + } else { + goto error; + } + } else if (parser->method == HTTP_MKCOL) { + if (parser->index == 1 && ch == 'O') { + parser->method = HTTP_MOVE; + } else if (parser->index == 1 && ch == 'E') { + parser->method = HTTP_MERGE; + } else if (parser->index == 1 && ch == '-') { + parser->method = HTTP_MSEARCH; + } else if (parser->index == 2 && ch == 'A') { + parser->method = HTTP_MKACTIVITY; + } else { + goto error; + } + } else if (parser->method == HTTP_SUBSCRIBE) { + if (parser->index == 1 && ch == 'E') { + parser->method = HTTP_SEARCH; + } else { + goto error; + } + } else if (parser->index == 1 && parser->method == HTTP_POST) { + if (ch == 'R') { + parser->method = HTTP_PROPFIND; /* or HTTP_PROPPATCH */ + } else if (ch == 'U') { + parser->method = HTTP_PUT; /* or HTTP_PURGE */ + } else if (ch == 'A') { + parser->method = HTTP_PATCH; + } else { + goto error; + } + } else if (parser->index == 2) { + if (parser->method == HTTP_PUT) { + if (ch == 'R') parser->method = HTTP_PURGE; + } else if (parser->method == HTTP_UNLOCK) { + if (ch == 'S') parser->method = HTTP_UNSUBSCRIBE; + } + } else if (parser->index == 4 && parser->method == HTTP_PROPFIND && ch == 'P') { + parser->method = HTTP_PROPPATCH; + } else { + SET_ERRNO(HPE_INVALID_METHOD); + goto error; + } + + ++parser->index; + break; + } + + case s_req_spaces_before_url: + { + if (ch == ' ') break; + + MARK(url); + if (parser->method == HTTP_CONNECT) { + parser->state = s_req_host_start; + } + + parser->state = parse_url_char((enum state)parser->state, ch); + if (parser->state == s_dead) { + SET_ERRNO(HPE_INVALID_URL); + goto error; + } + + break; + } + + case s_req_schema: + case s_req_schema_slash: + case s_req_schema_slash_slash: + case s_req_host_start: + case s_req_host_v6_start: + case s_req_host_v6: + case s_req_port_start: + { + switch (ch) { + /* No whitespace allowed here */ + case ' ': + case CR: + case LF: + SET_ERRNO(HPE_INVALID_URL); + goto error; + default: + parser->state = parse_url_char((enum state)parser->state, ch); + if (parser->state == s_dead) { + SET_ERRNO(HPE_INVALID_URL); + goto error; + } + } + + break; + } + + case s_req_host: + case s_req_host_v6_end: + case s_req_port: + case s_req_path: + case s_req_query_string_start: + case s_req_query_string: + case s_req_fragment_start: + case s_req_fragment: + { + switch (ch) { + case ' ': + parser->state = s_req_http_start; + CALLBACK_DATA(url); + break; + case CR: + case LF: + parser->http_major = 0; + parser->http_minor = 9; + parser->state = (ch == CR) ? + s_req_line_almost_done : + s_header_field_start; + CALLBACK_DATA(url); + break; + default: + parser->state = parse_url_char((enum state)parser->state, ch); + if (parser->state == s_dead) { + SET_ERRNO(HPE_INVALID_URL); + goto error; + } + } + break; + } + + case s_req_http_start: + switch (ch) { + case 'H': + parser->state = s_req_http_H; + break; + case ' ': + break; + default: + SET_ERRNO(HPE_INVALID_CONSTANT); + goto error; + } + break; + + case s_req_http_H: + STRICT_CHECK(ch != 'T'); + parser->state = s_req_http_HT; + break; + + case s_req_http_HT: + STRICT_CHECK(ch != 'T'); + parser->state = s_req_http_HTT; + break; + + case s_req_http_HTT: + STRICT_CHECK(ch != 'P'); + parser->state = s_req_http_HTTP; + break; + + case s_req_http_HTTP: + STRICT_CHECK(ch != '/'); + parser->state = s_req_first_http_major; + break; + + /* first digit of major HTTP version */ + case s_req_first_http_major: + if (ch < '1' || ch > '9') { + SET_ERRNO(HPE_INVALID_VERSION); + goto error; + } + + parser->http_major = ch - '0'; + parser->state = s_req_http_major; + break; + + /* major HTTP version or dot */ + case s_req_http_major: + { + if (ch == '.') { + parser->state = s_req_first_http_minor; + break; + } + + if (!IS_NUM(ch)) { + SET_ERRNO(HPE_INVALID_VERSION); + goto error; + } + + parser->http_major *= 10; + parser->http_major += ch - '0'; + + if (parser->http_major > 999) { + SET_ERRNO(HPE_INVALID_VERSION); + goto error; + } + + break; + } + + /* first digit of minor HTTP version */ + case s_req_first_http_minor: + if (!IS_NUM(ch)) { + SET_ERRNO(HPE_INVALID_VERSION); + goto error; + } + + parser->http_minor = ch - '0'; + parser->state = s_req_http_minor; + break; + + /* minor HTTP version or end of request line */ + case s_req_http_minor: + { + if (ch == CR) { + parser->state = s_req_line_almost_done; + break; + } + + if (ch == LF) { + parser->state = s_header_field_start; + break; + } + + /* XXX allow spaces after digit? */ + + if (!IS_NUM(ch)) { + SET_ERRNO(HPE_INVALID_VERSION); + goto error; + } + + parser->http_minor *= 10; + parser->http_minor += ch - '0'; + + if (parser->http_minor > 999) { + SET_ERRNO(HPE_INVALID_VERSION); + goto error; + } + + break; + } + + /* end of request line */ + case s_req_line_almost_done: + { + if (ch != LF) { + SET_ERRNO(HPE_LF_EXPECTED); + goto error; + } + + parser->state = s_header_field_start; + break; + } + + case s_header_field_start: + { + if (ch == CR) { + parser->state = s_headers_almost_done; + break; + } + + if (ch == LF) { + /* they might be just sending \n instead of \r\n so this would be + * the second \n to denote the end of headers*/ + parser->state = s_headers_almost_done; + goto reexecute_byte; + } + + c = TOKEN(ch); + + if (!c) { + SET_ERRNO(HPE_INVALID_HEADER_TOKEN); + goto error; + } + + MARK(header_field); + + parser->index = 0; + parser->state = s_header_field; + + switch (c) { + case 'c': + parser->header_state = h_C; + break; + + case 'p': + parser->header_state = h_matching_proxy_connection; + break; + + case 't': + parser->header_state = h_matching_transfer_encoding; + break; + + case 'u': + parser->header_state = h_matching_upgrade; + break; + + default: + parser->header_state = h_general; + break; + } + break; + } + + case s_header_field: + { + c = TOKEN(ch); + + if (c) { + switch (parser->header_state) { + case h_general: + break; + + case h_C: + parser->index++; + parser->header_state = (c == 'o' ? h_CO : h_general); + break; + + case h_CO: + parser->index++; + parser->header_state = (c == 'n' ? h_CON : h_general); + break; + + case h_CON: + parser->index++; + switch (c) { + case 'n': + parser->header_state = h_matching_connection; + break; + case 't': + parser->header_state = h_matching_content_length; + break; + default: + parser->header_state = h_general; + break; + } + break; + + /* connection */ + + case h_matching_connection: + parser->index++; + if (parser->index > sizeof(CONNECTION)-1 + || c != CONNECTION[parser->index]) { + parser->header_state = h_general; + } else if (parser->index == sizeof(CONNECTION)-2) { + parser->header_state = h_connection; + } + break; + + /* proxy-connection */ + + case h_matching_proxy_connection: + parser->index++; + if (parser->index > sizeof(PROXY_CONNECTION)-1 + || c != PROXY_CONNECTION[parser->index]) { + parser->header_state = h_general; + } else if (parser->index == sizeof(PROXY_CONNECTION)-2) { + parser->header_state = h_connection; + } + break; + + /* content-length */ + + case h_matching_content_length: + parser->index++; + if (parser->index > sizeof(CONTENT_LENGTH)-1 + || c != CONTENT_LENGTH[parser->index]) { + parser->header_state = h_general; + } else if (parser->index == sizeof(CONTENT_LENGTH)-2) { + parser->header_state = h_content_length; + } + break; + + /* transfer-encoding */ + + case h_matching_transfer_encoding: + parser->index++; + if (parser->index > sizeof(TRANSFER_ENCODING)-1 + || c != TRANSFER_ENCODING[parser->index]) { + parser->header_state = h_general; + } else if (parser->index == sizeof(TRANSFER_ENCODING)-2) { + parser->header_state = h_transfer_encoding; + } + break; + + /* upgrade */ + + case h_matching_upgrade: + parser->index++; + if (parser->index > sizeof(UPGRADE)-1 + || c != UPGRADE[parser->index]) { + parser->header_state = h_general; + } else if (parser->index == sizeof(UPGRADE)-2) { + parser->header_state = h_upgrade; + } + break; + + case h_connection: + case h_content_length: + case h_transfer_encoding: + case h_upgrade: + if (ch != ' ') parser->header_state = h_general; + break; + + default: + assert(0 && "Unknown header_state"); + break; + } + break; + } + + if (ch == ':') { + parser->state = s_header_value_start; + CALLBACK_DATA(header_field); + break; + } + + if (ch == CR) { + parser->state = s_header_almost_done; + CALLBACK_DATA(header_field); + break; + } + + if (ch == LF) { + parser->state = s_header_field_start; + CALLBACK_DATA(header_field); + break; + } + + SET_ERRNO(HPE_INVALID_HEADER_TOKEN); + goto error; + } + + case s_header_value_start: + { + if (ch == ' ' || ch == '\t') break; + + MARK(header_value); + + parser->state = s_header_value; + parser->index = 0; + + if (ch == CR) { + parser->header_state = h_general; + parser->state = s_header_almost_done; + CALLBACK_DATA(header_value); + break; + } + + if (ch == LF) { + parser->state = s_header_field_start; + CALLBACK_DATA(header_value); + break; + } + + c = LOWER(ch); + + switch (parser->header_state) { + case h_upgrade: + parser->flags |= F_UPGRADE; + parser->header_state = h_general; + break; + + case h_transfer_encoding: + /* looking for 'Transfer-Encoding: chunked' */ + if ('c' == c) { + parser->header_state = h_matching_transfer_encoding_chunked; + } else { + parser->header_state = h_general; + } + break; + + case h_content_length: + if (!IS_NUM(ch)) { + SET_ERRNO(HPE_INVALID_CONTENT_LENGTH); + goto error; + } + + parser->content_length = ch - '0'; + break; + + case h_connection: + /* looking for 'Connection: keep-alive' */ + if (c == 'k') { + parser->header_state = h_matching_connection_keep_alive; + /* looking for 'Connection: close' */ + } else if (c == 'c') { + parser->header_state = h_matching_connection_close; + } else { + parser->header_state = h_general; + } + break; + + default: + parser->header_state = h_general; + break; + } + break; + } + + case s_header_value: + { + + if (ch == CR) { + parser->state = s_header_almost_done; + CALLBACK_DATA(header_value); + break; + } + + if (ch == LF) { + parser->state = s_header_almost_done; + CALLBACK_DATA_NOADVANCE(header_value); + goto reexecute_byte; + } + + c = LOWER(ch); + + switch (parser->header_state) { + case h_general: + break; + + case h_connection: + case h_transfer_encoding: + assert(0 && "Shouldn't get here."); + break; + + case h_content_length: + { + uint64_t t; + + if (ch == ' ') break; + + if (!IS_NUM(ch)) { + SET_ERRNO(HPE_INVALID_CONTENT_LENGTH); + goto error; + } + + t = parser->content_length; + t *= 10; + t += ch - '0'; + + /* Overflow? */ + if (t < parser->content_length || t == ULLONG_MAX) { + SET_ERRNO(HPE_INVALID_CONTENT_LENGTH); + goto error; + } + + parser->content_length = t; + break; + } + + /* Transfer-Encoding: chunked */ + case h_matching_transfer_encoding_chunked: + parser->index++; + if (parser->index > sizeof(CHUNKED)-1 + || c != CHUNKED[parser->index]) { + parser->header_state = h_general; + } else if (parser->index == sizeof(CHUNKED)-2) { + parser->header_state = h_transfer_encoding_chunked; + } + break; + + /* looking for 'Connection: keep-alive' */ + case h_matching_connection_keep_alive: + parser->index++; + if (parser->index > sizeof(KEEP_ALIVE)-1 + || c != KEEP_ALIVE[parser->index]) { + parser->header_state = h_general; + } else if (parser->index == sizeof(KEEP_ALIVE)-2) { + parser->header_state = h_connection_keep_alive; + } + break; + + /* looking for 'Connection: close' */ + case h_matching_connection_close: + parser->index++; + if (parser->index > sizeof(CLOSE)-1 || c != CLOSE[parser->index]) { + parser->header_state = h_general; + } else if (parser->index == sizeof(CLOSE)-2) { + parser->header_state = h_connection_close; + } + break; + + case h_transfer_encoding_chunked: + case h_connection_keep_alive: + case h_connection_close: + if (ch != ' ') parser->header_state = h_general; + break; + + default: + parser->state = s_header_value; + parser->header_state = h_general; + break; + } + break; + } + + case s_header_almost_done: + { + STRICT_CHECK(ch != LF); + + parser->state = s_header_value_lws; + + switch (parser->header_state) { + case h_connection_keep_alive: + parser->flags |= F_CONNECTION_KEEP_ALIVE; + break; + case h_connection_close: + parser->flags |= F_CONNECTION_CLOSE; + break; + case h_transfer_encoding_chunked: + parser->flags |= F_CHUNKED; + break; + default: + break; + } + + break; + } + + case s_header_value_lws: + { + if (ch == ' ' || ch == '\t') + parser->state = s_header_value_start; + else + { + parser->state = s_header_field_start; + goto reexecute_byte; + } + break; + } + + case s_headers_almost_done: + { + STRICT_CHECK(ch != LF); + + if (parser->flags & F_TRAILING) { + /* End of a chunked request */ + parser->state = NEW_MESSAGE(); + CALLBACK_NOTIFY(message_complete); + break; + } + + parser->state = s_headers_done; + + /* Set this here so that on_headers_complete() callbacks can see it */ + parser->upgrade = + (parser->flags & F_UPGRADE || parser->method == HTTP_CONNECT); + + /* Here we call the headers_complete callback. This is somewhat + * different than other callbacks because if the user returns 1, we + * will interpret that as saying that this message has no body. This + * is needed for the annoying case of recieving a response to a HEAD + * request. + * + * We'd like to use CALLBACK_NOTIFY_NOADVANCE() here but we cannot, so + * we have to simulate it by handling a change in errno below. + */ + if (settings->on_headers_complete) { + switch (settings->on_headers_complete(parser)) { + case 0: + break; + + case 1: + parser->flags |= F_SKIPBODY; + break; + + default: + SET_ERRNO(HPE_CB_headers_complete); + return p - data; /* Error */ + } + } + + if (HTTP_PARSER_ERRNO(parser) != HPE_OK) { + return p - data; + } + + goto reexecute_byte; + } + + case s_headers_done: + { + STRICT_CHECK(ch != LF); + + parser->nread = 0; + + /* Exit, the rest of the connect is in a different protocol. */ + if (parser->upgrade) { + parser->state = NEW_MESSAGE(); + CALLBACK_NOTIFY(message_complete); + return (p - data) + 1; + } + + if (parser->flags & F_SKIPBODY) { + parser->state = NEW_MESSAGE(); + CALLBACK_NOTIFY(message_complete); + } else if (parser->flags & F_CHUNKED) { + /* chunked encoding - ignore Content-Length header */ + parser->state = s_chunk_size_start; + } else { + if (parser->content_length == 0) { + /* Content-Length header given but zero: Content-Length: 0\r\n */ + parser->state = NEW_MESSAGE(); + CALLBACK_NOTIFY(message_complete); + } else if (parser->content_length != ULLONG_MAX) { + /* Content-Length header given and non-zero */ + parser->state = s_body_identity; + } else { + if (parser->type == HTTP_REQUEST || + !http_message_needs_eof(parser)) { + /* Assume content-length 0 - read the next */ + parser->state = NEW_MESSAGE(); + CALLBACK_NOTIFY(message_complete); + } else { + /* Read body until EOF */ + parser->state = s_body_identity_eof; + } + } + } + + break; + } + + case s_body_identity: + { + uint64_t to_read = MIN(parser->content_length, + (uint64_t) ((data + len) - p)); + + assert(parser->content_length != 0 + && parser->content_length != ULLONG_MAX); + + /* The difference between advancing content_length and p is because + * the latter will automaticaly advance on the next loop iteration. + * Further, if content_length ends up at 0, we want to see the last + * byte again for our message complete callback. + */ + MARK(body); + parser->content_length -= to_read; + p += to_read - 1; + + if (parser->content_length == 0) { + parser->state = s_message_done; + + /* Mimic CALLBACK_DATA_NOADVANCE() but with one extra byte. + * + * The alternative to doing this is to wait for the next byte to + * trigger the data callback, just as in every other case. The + * problem with this is that this makes it difficult for the test + * harness to distinguish between complete-on-EOF and + * complete-on-length. It's not clear that this distinction is + * important for applications, but let's keep it for now. + */ + CALLBACK_DATA_(body, p - body_mark + 1, p - data); + goto reexecute_byte; + } + + break; + } + + /* read until EOF */ + case s_body_identity_eof: + MARK(body); + p = data + len - 1; + + break; + + case s_message_done: + parser->state = NEW_MESSAGE(); + CALLBACK_NOTIFY(message_complete); + break; + + case s_chunk_size_start: + { + assert(parser->nread == 1); + assert(parser->flags & F_CHUNKED); + + unhex_val = unhex[(unsigned char)ch]; + if (unhex_val == -1) { + SET_ERRNO(HPE_INVALID_CHUNK_SIZE); + goto error; + } + + parser->content_length = unhex_val; + parser->state = s_chunk_size; + break; + } + + case s_chunk_size: + { + uint64_t t; + + assert(parser->flags & F_CHUNKED); + + if (ch == CR) { + parser->state = s_chunk_size_almost_done; + break; + } + + unhex_val = unhex[(unsigned char)ch]; + + if (unhex_val == -1) { + if (ch == ';' || ch == ' ') { + parser->state = s_chunk_parameters; + break; + } + + SET_ERRNO(HPE_INVALID_CHUNK_SIZE); + goto error; + } + + t = parser->content_length; + t *= 16; + t += unhex_val; + + /* Overflow? */ + if (t < parser->content_length || t == ULLONG_MAX) { + SET_ERRNO(HPE_INVALID_CONTENT_LENGTH); + goto error; + } + + parser->content_length = t; + break; + } + + case s_chunk_parameters: + { + assert(parser->flags & F_CHUNKED); + /* just ignore this shit. TODO check for overflow */ + if (ch == CR) { + parser->state = s_chunk_size_almost_done; + break; + } + break; + } + + case s_chunk_size_almost_done: + { + assert(parser->flags & F_CHUNKED); + STRICT_CHECK(ch != LF); + + parser->nread = 0; + + if (parser->content_length == 0) { + parser->flags |= F_TRAILING; + parser->state = s_header_field_start; + } else { + parser->state = s_chunk_data; + } + break; + } + + case s_chunk_data: + { + uint64_t to_read = MIN(parser->content_length, + (uint64_t) ((data + len) - p)); + + assert(parser->flags & F_CHUNKED); + assert(parser->content_length != 0 + && parser->content_length != ULLONG_MAX); + + /* See the explanation in s_body_identity for why the content + * length and data pointers are managed this way. + */ + MARK(body); + parser->content_length -= to_read; + p += to_read - 1; + + if (parser->content_length == 0) { + parser->state = s_chunk_data_almost_done; + } + + break; + } + + case s_chunk_data_almost_done: + assert(parser->flags & F_CHUNKED); + assert(parser->content_length == 0); + STRICT_CHECK(ch != CR); + parser->state = s_chunk_data_done; + CALLBACK_DATA(body); + break; + + case s_chunk_data_done: + assert(parser->flags & F_CHUNKED); + STRICT_CHECK(ch != LF); + parser->nread = 0; + parser->state = s_chunk_size_start; + break; + + default: + assert(0 && "unhandled state"); + SET_ERRNO(HPE_INVALID_INTERNAL_STATE); + goto error; + } + } + + /* Run callbacks for any marks that we have leftover after we ran our of + * bytes. There should be at most one of these set, so it's OK to invoke + * them in series (unset marks will not result in callbacks). + * + * We use the NOADVANCE() variety of callbacks here because 'p' has already + * overflowed 'data' and this allows us to correct for the off-by-one that + * we'd otherwise have (since CALLBACK_DATA() is meant to be run with a 'p' + * value that's in-bounds). + */ + + assert(((header_field_mark ? 1 : 0) + + (header_value_mark ? 1 : 0) + + (url_mark ? 1 : 0) + + (body_mark ? 1 : 0)) <= 1); + + CALLBACK_DATA_NOADVANCE(header_field); + CALLBACK_DATA_NOADVANCE(header_value); + CALLBACK_DATA_NOADVANCE(url); + CALLBACK_DATA_NOADVANCE(body); + + return len; + +error: + if (HTTP_PARSER_ERRNO(parser) == HPE_OK) { + SET_ERRNO(HPE_UNKNOWN); + } + + return (p - data); +} + + +/* Does the parser need to see an EOF to find the end of the message? */ +int +http_message_needs_eof (http_parser *parser) +{ + if (parser->type == HTTP_REQUEST) { + return 0; + } + + /* See RFC 2616 section 4.4 */ + if (parser->status_code / 100 == 1 || /* 1xx e.g. Continue */ + parser->status_code == 204 || /* No Content */ + parser->status_code == 304 || /* Not Modified */ + parser->flags & F_SKIPBODY) { /* response to a HEAD request */ + return 0; + } + + if ((parser->flags & F_CHUNKED) || parser->content_length != ULLONG_MAX) { + return 0; + } + + return 1; +} + + +int +http_should_keep_alive (http_parser *parser) +{ + if (parser->http_major > 0 && parser->http_minor > 0) { + /* HTTP/1.1 */ + if (parser->flags & F_CONNECTION_CLOSE) { + return 0; + } + } else { + /* HTTP/1.0 or earlier */ + if (!(parser->flags & F_CONNECTION_KEEP_ALIVE)) { + return 0; + } + } + + return !http_message_needs_eof(parser); +} + + +const char * http_method_str (enum http_method m) +{ + return method_strings[m]; +} + + +void +http_parser_init (http_parser *parser, enum http_parser_type t) +{ + void *data = parser->data; /* preserve application data */ + memset(parser, 0, sizeof(*parser)); + parser->data = data; + parser->type = t; + parser->state = (t == HTTP_REQUEST ? s_start_req : (t == HTTP_RESPONSE ? s_start_res : s_start_req_or_res)); + parser->http_errno = HPE_OK; +} + +const char * +http_errno_name(enum http_errno err) { + assert(err < (sizeof(http_strerror_tab)/sizeof(http_strerror_tab[0]))); + return http_strerror_tab[err].name; +} + +const char * +http_errno_description(enum http_errno err) { + assert(err < (sizeof(http_strerror_tab)/sizeof(http_strerror_tab[0]))); + return http_strerror_tab[err].description; +} + +int +http_parser_parse_url(const char *buf, size_t buflen, int is_connect, + struct http_parser_url *u) +{ + enum state s; + const char *p; + enum http_parser_url_fields uf, old_uf; + + u->port = u->field_set = 0; + s = is_connect ? s_req_host_start : s_req_spaces_before_url; + uf = old_uf = UF_MAX; + + for (p = buf; p < buf + buflen; p++) { + s = parse_url_char(s, *p); + + /* Figure out the next field that we're operating on */ + switch (s) { + case s_dead: + return 1; + + /* Skip delimeters */ + case s_req_schema_slash: + case s_req_schema_slash_slash: + case s_req_host_start: + case s_req_host_v6_start: + case s_req_host_v6_end: + case s_req_port_start: + case s_req_query_string_start: + case s_req_fragment_start: + continue; + + case s_req_schema: + uf = UF_SCHEMA; + break; + + case s_req_host: + case s_req_host_v6: + uf = UF_HOST; + break; + + case s_req_port: + uf = UF_PORT; + break; + + case s_req_path: + uf = UF_PATH; + break; + + case s_req_query_string: + uf = UF_QUERY; + break; + + case s_req_fragment: + uf = UF_FRAGMENT; + break; + + default: + assert(!"Unexpected state"); + return 1; + } + + /* Nothing's changed; soldier on */ + if (uf == old_uf) { + u->field_data[uf].len++; + continue; + } + + u->field_data[uf].off = p - buf; + u->field_data[uf].len = 1; + + u->field_set |= (1 << uf); + old_uf = uf; + } + + /* CONNECT requests can only contain "hostname:port" */ + if (is_connect && u->field_set != ((1 << UF_HOST)|(1 << UF_PORT))) { + return 1; + } + + /* Make sure we don't end somewhere unexpected */ + switch (s) { + case s_req_host_v6_start: + case s_req_host_v6: + case s_req_host_v6_end: + case s_req_host: + case s_req_port_start: + return 1; + default: + break; + } + + if (u->field_set & (1 << UF_PORT)) { + /* Don't bother with endp; we've already validated the string */ + unsigned long v = strtoul(buf + u->field_data[UF_PORT].off, NULL, 10); + + /* Ports have a max value of 2^16 */ + if (v > 0xffff) { + return 1; + } + + u->port = (uint16_t) v; + } + + return 0; +} + +void +http_parser_pause(http_parser *parser, int paused) { + /* Users should only be pausing/unpausing a parser that is not in an error + * state. In non-debug builds, there's not much that we can do about this + * other than ignore it. + */ + if (HTTP_PARSER_ERRNO(parser) == HPE_OK || + HTTP_PARSER_ERRNO(parser) == HPE_PAUSED) { + SET_ERRNO((paused) ? HPE_PAUSED : HPE_OK); + } else { + assert(0 && "Attempting to pause parser in error state"); + } +} diff --git a/node-v0.8.14/deps/http_parser/http_parser.gyp b/node-v0.8.14/deps/http_parser/http_parser.gyp new file mode 100644 index 0000000..c6eada7 --- /dev/null +++ b/node-v0.8.14/deps/http_parser/http_parser.gyp @@ -0,0 +1,79 @@ +# This file is used with the GYP meta build system. +# http://code.google.com/p/gyp/ +# To build try this: +# svn co http://gyp.googlecode.com/svn/trunk gyp +# ./gyp/gyp -f make --depth=`pwd` http_parser.gyp +# ./out/Debug/test +{ + 'target_defaults': { + 'default_configuration': 'Debug', + 'configurations': { + # TODO: hoist these out and put them somewhere common, because + # RuntimeLibrary MUST MATCH across the entire project + 'Debug': { + 'defines': [ 'DEBUG', '_DEBUG' ], + 'msvs_settings': { + 'VCCLCompilerTool': { + 'RuntimeLibrary': 1, # static debug + }, + }, + }, + 'Release': { + 'defines': [ 'NDEBUG' ], + 'msvs_settings': { + 'VCCLCompilerTool': { + 'RuntimeLibrary': 0, # static release + }, + }, + } + }, + 'msvs_settings': { + 'VCCLCompilerTool': { + }, + 'VCLibrarianTool': { + }, + 'VCLinkerTool': { + 'GenerateDebugInformation': 'true', + }, + }, + 'conditions': [ + ['OS == "win"', { + 'defines': [ + 'WIN32' + ], + }] + ], + }, + + 'targets': [ + { + 'target_name': 'http_parser', + 'type': 'static_library', + 'include_dirs': [ '.' ], + 'direct_dependent_settings': { + 'include_dirs': [ '.' ], + }, + 'defines': [ 'HTTP_PARSER_STRICT=0' ], + 'sources': [ './http_parser.c', ], + 'conditions': [ + ['OS=="win"', { + 'msvs_settings': { + 'VCCLCompilerTool': { + # Compile as C++. http_parser.c is actually C99, but C++ is + # close enough in this case. + 'CompileAs': 2, + }, + }, + }] + ], + }, + + { + 'target_name': 'test', + 'type': 'executable', + 'dependencies': [ 'http_parser' ], + 'sources': [ 'test.c' ] + } + ] +} + diff --git a/node-v0.8.14/deps/http_parser/http_parser.h b/node-v0.8.14/deps/http_parser/http_parser.h new file mode 100644 index 0000000..8ed4180 --- /dev/null +++ b/node-v0.8.14/deps/http_parser/http_parser.h @@ -0,0 +1,318 @@ +/* Copyright Joyent, Inc. and other Node contributors. All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +#ifndef http_parser_h +#define http_parser_h +#ifdef __cplusplus +extern "C" { +#endif + +#define HTTP_PARSER_VERSION_MAJOR 1 +#define HTTP_PARSER_VERSION_MINOR 0 + +#include +#if defined(_WIN32) && !defined(__MINGW32__) && (!defined(_MSC_VER) || _MSC_VER<1600) +typedef __int8 int8_t; +typedef unsigned __int8 uint8_t; +typedef __int16 int16_t; +typedef unsigned __int16 uint16_t; +typedef __int32 int32_t; +typedef unsigned __int32 uint32_t; +typedef __int64 int64_t; +typedef unsigned __int64 uint64_t; + +typedef unsigned int size_t; +typedef int ssize_t; +#else +#include +#endif + +/* Compile with -DHTTP_PARSER_STRICT=0 to make less checks, but run + * faster + */ +#ifndef HTTP_PARSER_STRICT +# define HTTP_PARSER_STRICT 1 +#endif + +/* Compile with -DHTTP_PARSER_DEBUG=1 to add extra debugging information to + * the error reporting facility. + */ +#ifndef HTTP_PARSER_DEBUG +# define HTTP_PARSER_DEBUG 0 +#endif + + +/* Maximium header size allowed */ +#define HTTP_MAX_HEADER_SIZE (80*1024) + + +typedef struct http_parser http_parser; +typedef struct http_parser_settings http_parser_settings; + + +/* Callbacks should return non-zero to indicate an error. The parser will + * then halt execution. + * + * The one exception is on_headers_complete. In a HTTP_RESPONSE parser + * returning '1' from on_headers_complete will tell the parser that it + * should not expect a body. This is used when receiving a response to a + * HEAD request which may contain 'Content-Length' or 'Transfer-Encoding: + * chunked' headers that indicate the presence of a body. + * + * http_data_cb does not return data chunks. It will be call arbitrarally + * many times for each string. E.G. you might get 10 callbacks for "on_path" + * each providing just a few characters more data. + */ +typedef int (*http_data_cb) (http_parser*, const char *at, size_t length); +typedef int (*http_cb) (http_parser*); + + +/* Request Methods */ +#define HTTP_METHOD_MAP(XX) \ + XX(0, DELETE, DELETE) \ + XX(1, GET, GET) \ + XX(2, HEAD, HEAD) \ + XX(3, POST, POST) \ + XX(4, PUT, PUT) \ + /* pathological */ \ + XX(5, CONNECT, CONNECT) \ + XX(6, OPTIONS, OPTIONS) \ + XX(7, TRACE, TRACE) \ + /* webdav */ \ + XX(8, COPY, COPY) \ + XX(9, LOCK, LOCK) \ + XX(10, MKCOL, MKCOL) \ + XX(11, MOVE, MOVE) \ + XX(12, PROPFIND, PROPFIND) \ + XX(13, PROPPATCH, PROPPATCH) \ + XX(14, SEARCH, SEARCH) \ + XX(15, UNLOCK, UNLOCK) \ + /* subversion */ \ + XX(16, REPORT, REPORT) \ + XX(17, MKACTIVITY, MKACTIVITY) \ + XX(18, CHECKOUT, CHECKOUT) \ + XX(19, MERGE, MERGE) \ + /* upnp */ \ + XX(20, MSEARCH, M-SEARCH) \ + XX(21, NOTIFY, NOTIFY) \ + XX(22, SUBSCRIBE, SUBSCRIBE) \ + XX(23, UNSUBSCRIBE, UNSUBSCRIBE) \ + /* RFC-5789 */ \ + XX(24, PATCH, PATCH) \ + XX(25, PURGE, PURGE) \ + +enum http_method + { +#define XX(num, name, string) HTTP_##name = num, + HTTP_METHOD_MAP(XX) +#undef XX + }; + + +enum http_parser_type { HTTP_REQUEST, HTTP_RESPONSE, HTTP_BOTH }; + + +/* Flag values for http_parser.flags field */ +enum flags + { F_CHUNKED = 1 << 0 + , F_CONNECTION_KEEP_ALIVE = 1 << 1 + , F_CONNECTION_CLOSE = 1 << 2 + , F_TRAILING = 1 << 3 + , F_UPGRADE = 1 << 4 + , F_SKIPBODY = 1 << 5 + }; + + +/* Map for errno-related constants + * + * The provided argument should be a macro that takes 2 arguments. + */ +#define HTTP_ERRNO_MAP(XX) \ + /* No error */ \ + XX(OK, "success") \ + \ + /* Callback-related errors */ \ + XX(CB_message_begin, "the on_message_begin callback failed") \ + XX(CB_url, "the on_url callback failed") \ + XX(CB_header_field, "the on_header_field callback failed") \ + XX(CB_header_value, "the on_header_value callback failed") \ + XX(CB_headers_complete, "the on_headers_complete callback failed") \ + XX(CB_body, "the on_body callback failed") \ + XX(CB_message_complete, "the on_message_complete callback failed") \ + \ + /* Parsing-related errors */ \ + XX(INVALID_EOF_STATE, "stream ended at an unexpected time") \ + XX(HEADER_OVERFLOW, \ + "too many header bytes seen; overflow detected") \ + XX(CLOSED_CONNECTION, \ + "data received after completed connection: close message") \ + XX(INVALID_VERSION, "invalid HTTP version") \ + XX(INVALID_STATUS, "invalid HTTP status code") \ + XX(INVALID_METHOD, "invalid HTTP method") \ + XX(INVALID_URL, "invalid URL") \ + XX(INVALID_HOST, "invalid host") \ + XX(INVALID_PORT, "invalid port") \ + XX(INVALID_PATH, "invalid path") \ + XX(INVALID_QUERY_STRING, "invalid query string") \ + XX(INVALID_FRAGMENT, "invalid fragment") \ + XX(LF_EXPECTED, "LF character expected") \ + XX(INVALID_HEADER_TOKEN, "invalid character in header") \ + XX(INVALID_CONTENT_LENGTH, \ + "invalid character in content-length header") \ + XX(INVALID_CHUNK_SIZE, \ + "invalid character in chunk size header") \ + XX(INVALID_CONSTANT, "invalid constant string") \ + XX(INVALID_INTERNAL_STATE, "encountered unexpected internal state")\ + XX(STRICT, "strict mode assertion failed") \ + XX(PAUSED, "parser is paused") \ + XX(UNKNOWN, "an unknown error occurred") + + +/* Define HPE_* values for each errno value above */ +#define HTTP_ERRNO_GEN(n, s) HPE_##n, +enum http_errno { + HTTP_ERRNO_MAP(HTTP_ERRNO_GEN) +}; +#undef HTTP_ERRNO_GEN + + +/* Get an http_errno value from an http_parser */ +#define HTTP_PARSER_ERRNO(p) ((enum http_errno) (p)->http_errno) + +/* Get the line number that generated the current error */ +#if HTTP_PARSER_DEBUG +#define HTTP_PARSER_ERRNO_LINE(p) ((p)->error_lineno) +#else +#define HTTP_PARSER_ERRNO_LINE(p) 0 +#endif + + +struct http_parser { + /** PRIVATE **/ + unsigned char type : 2; /* enum http_parser_type */ + unsigned char flags : 6; /* F_* values from 'flags' enum; semi-public */ + unsigned char state; /* enum state from http_parser.c */ + unsigned char header_state; /* enum header_state from http_parser.c */ + unsigned char index; /* index into current matcher */ + + uint32_t nread; /* # bytes read in various scenarios */ + uint64_t content_length; /* # bytes in body (0 if no Content-Length header) */ + + /** READ-ONLY **/ + unsigned short http_major; + unsigned short http_minor; + unsigned short status_code; /* responses only */ + unsigned char method; /* requests only */ + unsigned char http_errno : 7; + + /* 1 = Upgrade header was present and the parser has exited because of that. + * 0 = No upgrade header present. + * Should be checked when http_parser_execute() returns in addition to + * error checking. + */ + unsigned char upgrade : 1; + +#if HTTP_PARSER_DEBUG + uint32_t error_lineno; +#endif + + /** PUBLIC **/ + void *data; /* A pointer to get hook to the "connection" or "socket" object */ +}; + + +struct http_parser_settings { + http_cb on_message_begin; + http_data_cb on_url; + http_data_cb on_header_field; + http_data_cb on_header_value; + http_cb on_headers_complete; + http_data_cb on_body; + http_cb on_message_complete; +}; + + +enum http_parser_url_fields + { UF_SCHEMA = 0 + , UF_HOST = 1 + , UF_PORT = 2 + , UF_PATH = 3 + , UF_QUERY = 4 + , UF_FRAGMENT = 5 + , UF_MAX = 6 + }; + + +/* Result structure for http_parser_parse_url(). + * + * Callers should index into field_data[] with UF_* values iff field_set + * has the relevant (1 << UF_*) bit set. As a courtesy to clients (and + * because we probably have padding left over), we convert any port to + * a uint16_t. + */ +struct http_parser_url { + uint16_t field_set; /* Bitmask of (1 << UF_*) values */ + uint16_t port; /* Converted UF_PORT string */ + + struct { + uint16_t off; /* Offset into buffer in which field starts */ + uint16_t len; /* Length of run in buffer */ + } field_data[UF_MAX]; +}; + + +void http_parser_init(http_parser *parser, enum http_parser_type type); + + +size_t http_parser_execute(http_parser *parser, + const http_parser_settings *settings, + const char *data, + size_t len); + + +/* If http_should_keep_alive() in the on_headers_complete or + * on_message_complete callback returns true, then this will be should be + * the last message on the connection. + * If you are the server, respond with the "Connection: close" header. + * If you are the client, close the connection. + */ +int http_should_keep_alive(http_parser *parser); + +/* Returns a string version of the HTTP method. */ +const char *http_method_str(enum http_method m); + +/* Return a string name of the given error */ +const char *http_errno_name(enum http_errno err); + +/* Return a string description of the given error */ +const char *http_errno_description(enum http_errno err); + +/* Parse a URL; return nonzero on failure */ +int http_parser_parse_url(const char *buf, size_t buflen, + int is_connect, + struct http_parser_url *u); + +/* Pause or un-pause the parser; a nonzero value pauses */ +void http_parser_pause(http_parser *parser, int paused); + +#ifdef __cplusplus +} +#endif +#endif diff --git a/node-v0.8.14/deps/http_parser/test.c b/node-v0.8.14/deps/http_parser/test.c new file mode 100644 index 0000000..6af0e78 --- /dev/null +++ b/node-v0.8.14/deps/http_parser/test.c @@ -0,0 +1,2061 @@ +/* Copyright Joyent, Inc. and other Node contributors. All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +#include "http_parser.h" +#include +#include +#include +#include /* rand */ +#include +#include + +#undef TRUE +#define TRUE 1 +#undef FALSE +#define FALSE 0 + +#define MAX_HEADERS 13 +#define MAX_ELEMENT_SIZE 500 + +#define MIN(a,b) ((a) < (b) ? (a) : (b)) + +static http_parser *parser; + +struct message { + const char *name; // for debugging purposes + const char *raw; + enum http_parser_type type; + enum http_method method; + int status_code; + char request_url[MAX_ELEMENT_SIZE]; + char body[MAX_ELEMENT_SIZE]; + size_t body_size; + int num_headers; + enum { NONE=0, FIELD, VALUE } last_header_element; + char headers [MAX_HEADERS][2][MAX_ELEMENT_SIZE]; + int should_keep_alive; + + const char *upgrade; // upgraded body + + unsigned short http_major; + unsigned short http_minor; + + int message_begin_cb_called; + int headers_complete_cb_called; + int message_complete_cb_called; + int message_complete_on_eof; +}; + +static int currently_parsing_eof; + +static struct message messages[5]; +static int num_messages; + +/* * R E Q U E S T S * */ +const struct message requests[] = +#define CURL_GET 0 +{ {.name= "curl get" + ,.type= HTTP_REQUEST + ,.raw= "GET /test HTTP/1.1\r\n" + "User-Agent: curl/7.18.0 (i486-pc-linux-gnu) libcurl/7.18.0 OpenSSL/0.9.8g zlib/1.2.3.3 libidn/1.1\r\n" + "Host: 0.0.0.0=5000\r\n" + "Accept: */*\r\n" + "\r\n" + ,.should_keep_alive= TRUE + ,.message_complete_on_eof= FALSE + ,.http_major= 1 + ,.http_minor= 1 + ,.method= HTTP_GET + ,.request_url= "/test" + ,.num_headers= 3 + ,.headers= + { { "User-Agent", "curl/7.18.0 (i486-pc-linux-gnu) libcurl/7.18.0 OpenSSL/0.9.8g zlib/1.2.3.3 libidn/1.1" } + , { "Host", "0.0.0.0=5000" } + , { "Accept", "*/*" } + } + ,.body= "" + } + +#define FIREFOX_GET 1 +, {.name= "firefox get" + ,.type= HTTP_REQUEST + ,.raw= "GET /favicon.ico HTTP/1.1\r\n" + "Host: 0.0.0.0=5000\r\n" + "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9) Gecko/2008061015 Firefox/3.0\r\n" + "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\r\n" + "Accept-Language: en-us,en;q=0.5\r\n" + "Accept-Encoding: gzip,deflate\r\n" + "Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7\r\n" + "Keep-Alive: 300\r\n" + "Connection: keep-alive\r\n" + "\r\n" + ,.should_keep_alive= TRUE + ,.message_complete_on_eof= FALSE + ,.http_major= 1 + ,.http_minor= 1 + ,.method= HTTP_GET + ,.request_url= "/favicon.ico" + ,.num_headers= 8 + ,.headers= + { { "Host", "0.0.0.0=5000" } + , { "User-Agent", "Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9) Gecko/2008061015 Firefox/3.0" } + , { "Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8" } + , { "Accept-Language", "en-us,en;q=0.5" } + , { "Accept-Encoding", "gzip,deflate" } + , { "Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.7" } + , { "Keep-Alive", "300" } + , { "Connection", "keep-alive" } + } + ,.body= "" + } + +#define DUMBFUCK 2 +, {.name= "dumbfuck" + ,.type= HTTP_REQUEST + ,.raw= "GET /dumbfuck HTTP/1.1\r\n" + "aaaaaaaaaaaaa:++++++++++\r\n" + "\r\n" + ,.should_keep_alive= TRUE + ,.message_complete_on_eof= FALSE + ,.http_major= 1 + ,.http_minor= 1 + ,.method= HTTP_GET + ,.request_url= "/dumbfuck" + ,.num_headers= 1 + ,.headers= + { { "aaaaaaaaaaaaa", "++++++++++" } + } + ,.body= "" + } + +#define FRAGMENT_IN_URI 3 +, {.name= "fragment in url" + ,.type= HTTP_REQUEST + ,.raw= "GET /forums/1/topics/2375?page=1#posts-17408 HTTP/1.1\r\n" + "\r\n" + ,.should_keep_alive= TRUE + ,.message_complete_on_eof= FALSE + ,.http_major= 1 + ,.http_minor= 1 + ,.method= HTTP_GET + /* XXX request url does include fragment? */ + ,.request_url= "/forums/1/topics/2375?page=1#posts-17408" + ,.num_headers= 0 + ,.body= "" + } + +#define GET_NO_HEADERS_NO_BODY 4 +, {.name= "get no headers no body" + ,.type= HTTP_REQUEST + ,.raw= "GET /get_no_headers_no_body/world HTTP/1.1\r\n" + "\r\n" + ,.should_keep_alive= TRUE + ,.message_complete_on_eof= FALSE /* would need Connection: close */ + ,.http_major= 1 + ,.http_minor= 1 + ,.method= HTTP_GET + ,.request_url= "/get_no_headers_no_body/world" + ,.num_headers= 0 + ,.body= "" + } + +#define GET_ONE_HEADER_NO_BODY 5 +, {.name= "get one header no body" + ,.type= HTTP_REQUEST + ,.raw= "GET /get_one_header_no_body HTTP/1.1\r\n" + "Accept: */*\r\n" + "\r\n" + ,.should_keep_alive= TRUE + ,.message_complete_on_eof= FALSE /* would need Connection: close */ + ,.http_major= 1 + ,.http_minor= 1 + ,.method= HTTP_GET + ,.request_url= "/get_one_header_no_body" + ,.num_headers= 1 + ,.headers= + { { "Accept" , "*/*" } + } + ,.body= "" + } + +#define GET_FUNKY_CONTENT_LENGTH 6 +, {.name= "get funky content length body hello" + ,.type= HTTP_REQUEST + ,.raw= "GET /get_funky_content_length_body_hello HTTP/1.0\r\n" + "conTENT-Length: 5\r\n" + "\r\n" + "HELLO" + ,.should_keep_alive= FALSE + ,.message_complete_on_eof= FALSE + ,.http_major= 1 + ,.http_minor= 0 + ,.method= HTTP_GET + ,.request_url= "/get_funky_content_length_body_hello" + ,.num_headers= 1 + ,.headers= + { { "conTENT-Length" , "5" } + } + ,.body= "HELLO" + } + +#define POST_IDENTITY_BODY_WORLD 7 +, {.name= "post identity body world" + ,.type= HTTP_REQUEST + ,.raw= "POST /post_identity_body_world?q=search#hey HTTP/1.1\r\n" + "Accept: */*\r\n" + "Transfer-Encoding: identity\r\n" + "Content-Length: 5\r\n" + "\r\n" + "World" + ,.should_keep_alive= TRUE + ,.message_complete_on_eof= FALSE + ,.http_major= 1 + ,.http_minor= 1 + ,.method= HTTP_POST + ,.request_url= "/post_identity_body_world?q=search#hey" + ,.num_headers= 3 + ,.headers= + { { "Accept", "*/*" } + , { "Transfer-Encoding", "identity" } + , { "Content-Length", "5" } + } + ,.body= "World" + } + +#define POST_CHUNKED_ALL_YOUR_BASE 8 +, {.name= "post - chunked body: all your base are belong to us" + ,.type= HTTP_REQUEST + ,.raw= "POST /post_chunked_all_your_base HTTP/1.1\r\n" + "Transfer-Encoding: chunked\r\n" + "\r\n" + "1e\r\nall your base are belong to us\r\n" + "0\r\n" + "\r\n" + ,.should_keep_alive= TRUE + ,.message_complete_on_eof= FALSE + ,.http_major= 1 + ,.http_minor= 1 + ,.method= HTTP_POST + ,.request_url= "/post_chunked_all_your_base" + ,.num_headers= 1 + ,.headers= + { { "Transfer-Encoding" , "chunked" } + } + ,.body= "all your base are belong to us" + } + +#define TWO_CHUNKS_MULT_ZERO_END 9 +, {.name= "two chunks ; triple zero ending" + ,.type= HTTP_REQUEST + ,.raw= "POST /two_chunks_mult_zero_end HTTP/1.1\r\n" + "Transfer-Encoding: chunked\r\n" + "\r\n" + "5\r\nhello\r\n" + "6\r\n world\r\n" + "000\r\n" + "\r\n" + ,.should_keep_alive= TRUE + ,.message_complete_on_eof= FALSE + ,.http_major= 1 + ,.http_minor= 1 + ,.method= HTTP_POST + ,.request_url= "/two_chunks_mult_zero_end" + ,.num_headers= 1 + ,.headers= + { { "Transfer-Encoding", "chunked" } + } + ,.body= "hello world" + } + +#define CHUNKED_W_TRAILING_HEADERS 10 +, {.name= "chunked with trailing headers. blech." + ,.type= HTTP_REQUEST + ,.raw= "POST /chunked_w_trailing_headers HTTP/1.1\r\n" + "Transfer-Encoding: chunked\r\n" + "\r\n" + "5\r\nhello\r\n" + "6\r\n world\r\n" + "0\r\n" + "Vary: *\r\n" + "Content-Type: text/plain\r\n" + "\r\n" + ,.should_keep_alive= TRUE + ,.message_complete_on_eof= FALSE + ,.http_major= 1 + ,.http_minor= 1 + ,.method= HTTP_POST + ,.request_url= "/chunked_w_trailing_headers" + ,.num_headers= 3 + ,.headers= + { { "Transfer-Encoding", "chunked" } + , { "Vary", "*" } + , { "Content-Type", "text/plain" } + } + ,.body= "hello world" + } + +#define CHUNKED_W_BULLSHIT_AFTER_LENGTH 11 +, {.name= "with bullshit after the length" + ,.type= HTTP_REQUEST + ,.raw= "POST /chunked_w_bullshit_after_length HTTP/1.1\r\n" + "Transfer-Encoding: chunked\r\n" + "\r\n" + "5; ihatew3;whatthefuck=aretheseparametersfor\r\nhello\r\n" + "6; blahblah; blah\r\n world\r\n" + "0\r\n" + "\r\n" + ,.should_keep_alive= TRUE + ,.message_complete_on_eof= FALSE + ,.http_major= 1 + ,.http_minor= 1 + ,.method= HTTP_POST + ,.request_url= "/chunked_w_bullshit_after_length" + ,.num_headers= 1 + ,.headers= + { { "Transfer-Encoding", "chunked" } + } + ,.body= "hello world" + } + +#define WITH_QUOTES 12 +, {.name= "with quotes" + ,.type= HTTP_REQUEST + ,.raw= "GET /with_\"stupid\"_quotes?foo=\"bar\" HTTP/1.1\r\n\r\n" + ,.should_keep_alive= TRUE + ,.message_complete_on_eof= FALSE + ,.http_major= 1 + ,.http_minor= 1 + ,.method= HTTP_GET + ,.request_url= "/with_\"stupid\"_quotes?foo=\"bar\"" + ,.num_headers= 0 + ,.headers= { } + ,.body= "" + } + +#define APACHEBENCH_GET 13 +/* The server receiving this request SHOULD NOT wait for EOF + * to know that content-length == 0. + * How to represent this in a unit test? message_complete_on_eof + * Compare with NO_CONTENT_LENGTH_RESPONSE. + */ +, {.name = "apachebench get" + ,.type= HTTP_REQUEST + ,.raw= "GET /test HTTP/1.0\r\n" + "Host: 0.0.0.0:5000\r\n" + "User-Agent: ApacheBench/2.3\r\n" + "Accept: */*\r\n\r\n" + ,.should_keep_alive= FALSE + ,.message_complete_on_eof= FALSE + ,.http_major= 1 + ,.http_minor= 0 + ,.method= HTTP_GET + ,.request_url= "/test" + ,.num_headers= 3 + ,.headers= { { "Host", "0.0.0.0:5000" } + , { "User-Agent", "ApacheBench/2.3" } + , { "Accept", "*/*" } + } + ,.body= "" + } + +#define QUERY_URL_WITH_QUESTION_MARK_GET 14 +/* Some clients include '?' characters in query strings. + */ +, {.name = "query url with question mark" + ,.type= HTTP_REQUEST + ,.raw= "GET /test.cgi?foo=bar?baz HTTP/1.1\r\n\r\n" + ,.should_keep_alive= TRUE + ,.message_complete_on_eof= FALSE + ,.http_major= 1 + ,.http_minor= 1 + ,.method= HTTP_GET + ,.request_url= "/test.cgi?foo=bar?baz" + ,.num_headers= 0 + ,.headers= {} + ,.body= "" + } + +#define PREFIX_NEWLINE_GET 15 +/* Some clients, especially after a POST in a keep-alive connection, + * will send an extra CRLF before the next request + */ +, {.name = "newline prefix get" + ,.type= HTTP_REQUEST + ,.raw= "\r\nGET /test HTTP/1.1\r\n\r\n" + ,.should_keep_alive= TRUE + ,.message_complete_on_eof= FALSE + ,.http_major= 1 + ,.http_minor= 1 + ,.method= HTTP_GET + ,.request_url= "/test" + ,.num_headers= 0 + ,.headers= { } + ,.body= "" + } + +#define UPGRADE_REQUEST 16 +, {.name = "upgrade request" + ,.type= HTTP_REQUEST + ,.raw= "GET /demo HTTP/1.1\r\n" + "Host: example.com\r\n" + "Connection: Upgrade\r\n" + "Sec-WebSocket-Key2: 12998 5 Y3 1 .P00\r\n" + "Sec-WebSocket-Protocol: sample\r\n" + "Upgrade: WebSocket\r\n" + "Sec-WebSocket-Key1: 4 @1 46546xW%0l 1 5\r\n" + "Origin: http://example.com\r\n" + "\r\n" + "Hot diggity dogg" + ,.should_keep_alive= TRUE + ,.message_complete_on_eof= FALSE + ,.http_major= 1 + ,.http_minor= 1 + ,.method= HTTP_GET + ,.request_url= "/demo" + ,.num_headers= 7 + ,.upgrade="Hot diggity dogg" + ,.headers= { { "Host", "example.com" } + , { "Connection", "Upgrade" } + , { "Sec-WebSocket-Key2", "12998 5 Y3 1 .P00" } + , { "Sec-WebSocket-Protocol", "sample" } + , { "Upgrade", "WebSocket" } + , { "Sec-WebSocket-Key1", "4 @1 46546xW%0l 1 5" } + , { "Origin", "http://example.com" } + } + ,.body= "" + } + +#define CONNECT_REQUEST 17 +, {.name = "connect request" + ,.type= HTTP_REQUEST + ,.raw= "CONNECT 0-home0.netscape.com:443 HTTP/1.0\r\n" + "User-agent: Mozilla/1.1N\r\n" + "Proxy-authorization: basic aGVsbG86d29ybGQ=\r\n" + "\r\n" + "some data\r\n" + "and yet even more data" + ,.should_keep_alive= FALSE + ,.message_complete_on_eof= FALSE + ,.http_major= 1 + ,.http_minor= 0 + ,.method= HTTP_CONNECT + ,.request_url= "0-home0.netscape.com:443" + ,.num_headers= 2 + ,.upgrade="some data\r\nand yet even more data" + ,.headers= { { "User-agent", "Mozilla/1.1N" } + , { "Proxy-authorization", "basic aGVsbG86d29ybGQ=" } + } + ,.body= "" + } + +#define REPORT_REQ 18 +, {.name= "report request" + ,.type= HTTP_REQUEST + ,.raw= "REPORT /test HTTP/1.1\r\n" + "\r\n" + ,.should_keep_alive= TRUE + ,.message_complete_on_eof= FALSE + ,.http_major= 1 + ,.http_minor= 1 + ,.method= HTTP_REPORT + ,.request_url= "/test" + ,.num_headers= 0 + ,.headers= {} + ,.body= "" + } + +#define NO_HTTP_VERSION 19 +, {.name= "request with no http version" + ,.type= HTTP_REQUEST + ,.raw= "GET /\r\n" + "\r\n" + ,.should_keep_alive= FALSE + ,.message_complete_on_eof= FALSE + ,.http_major= 0 + ,.http_minor= 9 + ,.method= HTTP_GET + ,.request_url= "/" + ,.num_headers= 0 + ,.headers= {} + ,.body= "" + } + +#define MSEARCH_REQ 20 +, {.name= "m-search request" + ,.type= HTTP_REQUEST + ,.raw= "M-SEARCH * HTTP/1.1\r\n" + "HOST: 239.255.255.250:1900\r\n" + "MAN: \"ssdp:discover\"\r\n" + "ST: \"ssdp:all\"\r\n" + "\r\n" + ,.should_keep_alive= TRUE + ,.message_complete_on_eof= FALSE + ,.http_major= 1 + ,.http_minor= 1 + ,.method= HTTP_MSEARCH + ,.request_url= "*" + ,.num_headers= 3 + ,.headers= { { "HOST", "239.255.255.250:1900" } + , { "MAN", "\"ssdp:discover\"" } + , { "ST", "\"ssdp:all\"" } + } + ,.body= "" + } + +#define LINE_FOLDING_IN_HEADER 20 +, {.name= "line folding in header value" + ,.type= HTTP_REQUEST + ,.raw= "GET / HTTP/1.1\r\n" + "Line1: abc\r\n" + "\tdef\r\n" + " ghi\r\n" + "\t\tjkl\r\n" + " mno \r\n" + "\t \tqrs\r\n" + "Line2: \t line2\t\r\n" + "\r\n" + ,.should_keep_alive= TRUE + ,.message_complete_on_eof= FALSE + ,.http_major= 1 + ,.http_minor= 1 + ,.method= HTTP_GET + ,.request_url= "/" + ,.num_headers= 2 + ,.headers= { { "Line1", "abcdefghijklmno qrs" } + , { "Line2", "line2\t" } + } + ,.body= "" + } + + +#define QUERY_TERMINATED_HOST 21 +, {.name= "host terminated by a query string" + ,.type= HTTP_REQUEST + ,.raw= "GET http://hypnotoad.org?hail=all HTTP/1.1\r\n" + "\r\n" + ,.should_keep_alive= TRUE + ,.message_complete_on_eof= FALSE + ,.http_major= 1 + ,.http_minor= 1 + ,.method= HTTP_GET + ,.request_url= "http://hypnotoad.org?hail=all" + ,.num_headers= 0 + ,.headers= { } + ,.body= "" + } + +#define QUERY_TERMINATED_HOSTPORT 22 +, {.name= "host:port terminated by a query string" + ,.type= HTTP_REQUEST + ,.raw= "GET http://hypnotoad.org:1234?hail=all HTTP/1.1\r\n" + "\r\n" + ,.should_keep_alive= TRUE + ,.message_complete_on_eof= FALSE + ,.http_major= 1 + ,.http_minor= 1 + ,.method= HTTP_GET + ,.request_url= "http://hypnotoad.org:1234?hail=all" + ,.num_headers= 0 + ,.headers= { } + ,.body= "" + } + +#define SPACE_TERMINATED_HOSTPORT 23 +, {.name= "host:port terminated by a space" + ,.type= HTTP_REQUEST + ,.raw= "GET http://hypnotoad.org:1234 HTTP/1.1\r\n" + "\r\n" + ,.should_keep_alive= TRUE + ,.message_complete_on_eof= FALSE + ,.http_major= 1 + ,.http_minor= 1 + ,.method= HTTP_GET + ,.request_url= "http://hypnotoad.org:1234" + ,.num_headers= 0 + ,.headers= { } + ,.body= "" + } + +#if !HTTP_PARSER_STRICT +#define UTF8_PATH_REQ 24 +, {.name= "utf-8 path request" + ,.type= HTTP_REQUEST + ,.raw= "GET /δ¶/δt/pope?q=1#narf HTTP/1.1\r\n" + "Host: github.com\r\n" + "\r\n" + ,.should_keep_alive= TRUE + ,.message_complete_on_eof= FALSE + ,.http_major= 1 + ,.http_minor= 1 + ,.method= HTTP_GET + ,.request_url= "/δ¶/δt/pope?q=1#narf" + ,.num_headers= 1 + ,.headers= { {"Host", "github.com" } + } + ,.body= "" + } + +#define HOSTNAME_UNDERSCORE 25 +, {.name = "hostname underscore" + ,.type= HTTP_REQUEST + ,.raw= "CONNECT home_0.netscape.com:443 HTTP/1.0\r\n" + "User-agent: Mozilla/1.1N\r\n" + "Proxy-authorization: basic aGVsbG86d29ybGQ=\r\n" + "\r\n" + ,.should_keep_alive= FALSE + ,.message_complete_on_eof= FALSE + ,.http_major= 1 + ,.http_minor= 0 + ,.method= HTTP_CONNECT + ,.request_url= "home_0.netscape.com:443" + ,.num_headers= 2 + ,.upgrade="" + ,.headers= { { "User-agent", "Mozilla/1.1N" } + , { "Proxy-authorization", "basic aGVsbG86d29ybGQ=" } + } + ,.body= "" + } +#endif /* !HTTP_PARSER_STRICT */ + +#define PATCH_REQ 26 +, {.name = "PATCH request" + ,.type= HTTP_REQUEST + ,.raw= "PATCH /file.txt HTTP/1.1\r\n" + "Host: www.example.com\r\n" + "Content-Type: application/example\r\n" + "If-Match: \"e0023aa4e\"\r\n" + "Content-Length: 10\r\n" + "\r\n" + "cccccccccc" + ,.should_keep_alive= TRUE + ,.message_complete_on_eof= FALSE + ,.http_major= 1 + ,.http_minor= 1 + ,.method= HTTP_PATCH + ,.request_url= "/file.txt" + ,.num_headers= 4 + ,.headers= { { "Host", "www.example.com" } + , { "Content-Type", "application/example" } + , { "If-Match", "\"e0023aa4e\"" } + , { "Content-Length", "10" } + } + ,.body= "cccccccccc" + } + +#define CONNECT_CAPS_REQUEST 27 +, {.name = "connect caps request" + ,.type= HTTP_REQUEST + ,.raw= "CONNECT HOME0.NETSCAPE.COM:443 HTTP/1.0\r\n" + "User-agent: Mozilla/1.1N\r\n" + "Proxy-authorization: basic aGVsbG86d29ybGQ=\r\n" + "\r\n" + ,.should_keep_alive= FALSE + ,.message_complete_on_eof= FALSE + ,.http_major= 1 + ,.http_minor= 0 + ,.method= HTTP_CONNECT + ,.request_url= "HOME0.NETSCAPE.COM:443" + ,.num_headers= 2 + ,.upgrade="" + ,.headers= { { "User-agent", "Mozilla/1.1N" } + , { "Proxy-authorization", "basic aGVsbG86d29ybGQ=" } + } + ,.body= "" + } + +, {.name= NULL } /* sentinel */ +}; + +/* * R E S P O N S E S * */ +const struct message responses[] = +#define GOOGLE_301 0 +{ {.name= "google 301" + ,.type= HTTP_RESPONSE + ,.raw= "HTTP/1.1 301 Moved Permanently\r\n" + "Location: http://www.google.com/\r\n" + "Content-Type: text/html; charset=UTF-8\r\n" + "Date: Sun, 26 Apr 2009 11:11:49 GMT\r\n" + "Expires: Tue, 26 May 2009 11:11:49 GMT\r\n" + "X-$PrototypeBI-Version: 1.6.0.3\r\n" /* $ char in header field */ + "Cache-Control: public, max-age=2592000\r\n" + "Server: gws\r\n" + "Content-Length: 219 \r\n" + "\r\n" + "\n" + "301 Moved\n" + "

301 Moved

\n" + "The document has moved\n" + "here.\r\n" + "\r\n" + ,.should_keep_alive= TRUE + ,.message_complete_on_eof= FALSE + ,.http_major= 1 + ,.http_minor= 1 + ,.status_code= 301 + ,.num_headers= 8 + ,.headers= + { { "Location", "http://www.google.com/" } + , { "Content-Type", "text/html; charset=UTF-8" } + , { "Date", "Sun, 26 Apr 2009 11:11:49 GMT" } + , { "Expires", "Tue, 26 May 2009 11:11:49 GMT" } + , { "X-$PrototypeBI-Version", "1.6.0.3" } + , { "Cache-Control", "public, max-age=2592000" } + , { "Server", "gws" } + , { "Content-Length", "219 " } + } + ,.body= "\n" + "301 Moved\n" + "

301 Moved

\n" + "The document has moved\n" + "here.\r\n" + "\r\n" + } + +#define NO_CONTENT_LENGTH_RESPONSE 1 +/* The client should wait for the server's EOF. That is, when content-length + * is not specified, and "Connection: close", the end of body is specified + * by the EOF. + * Compare with APACHEBENCH_GET + */ +, {.name= "no content-length response" + ,.type= HTTP_RESPONSE + ,.raw= "HTTP/1.1 200 OK\r\n" + "Date: Tue, 04 Aug 2009 07:59:32 GMT\r\n" + "Server: Apache\r\n" + "X-Powered-By: Servlet/2.5 JSP/2.1\r\n" + "Content-Type: text/xml; charset=utf-8\r\n" + "Connection: close\r\n" + "\r\n" + "\n" + "\n" + " \n" + " \n" + " SOAP-ENV:Client\n" + " Client Error\n" + " \n" + " \n" + "" + ,.should_keep_alive= FALSE + ,.message_complete_on_eof= TRUE + ,.http_major= 1 + ,.http_minor= 1 + ,.status_code= 200 + ,.num_headers= 5 + ,.headers= + { { "Date", "Tue, 04 Aug 2009 07:59:32 GMT" } + , { "Server", "Apache" } + , { "X-Powered-By", "Servlet/2.5 JSP/2.1" } + , { "Content-Type", "text/xml; charset=utf-8" } + , { "Connection", "close" } + } + ,.body= "\n" + "\n" + " \n" + " \n" + " SOAP-ENV:Client\n" + " Client Error\n" + " \n" + " \n" + "" + } + +#define NO_HEADERS_NO_BODY_404 2 +, {.name= "404 no headers no body" + ,.type= HTTP_RESPONSE + ,.raw= "HTTP/1.1 404 Not Found\r\n\r\n" + ,.should_keep_alive= TRUE + ,.message_complete_on_eof= FALSE + ,.http_major= 1 + ,.http_minor= 1 + ,.status_code= 404 + ,.num_headers= 0 + ,.headers= {} + ,.body_size= 0 + ,.body= "" + } + +#define NO_REASON_PHRASE 3 +, {.name= "301 no response phrase" + ,.type= HTTP_RESPONSE + ,.raw= "HTTP/1.1 301\r\n\r\n" + ,.should_keep_alive = TRUE + ,.message_complete_on_eof= FALSE + ,.http_major= 1 + ,.http_minor= 1 + ,.status_code= 301 + ,.num_headers= 0 + ,.headers= {} + ,.body= "" + } + +#define TRAILING_SPACE_ON_CHUNKED_BODY 4 +, {.name="200 trailing space on chunked body" + ,.type= HTTP_RESPONSE + ,.raw= "HTTP/1.1 200 OK\r\n" + "Content-Type: text/plain\r\n" + "Transfer-Encoding: chunked\r\n" + "\r\n" + "25 \r\n" + "This is the data in the first chunk\r\n" + "\r\n" + "1C\r\n" + "and this is the second one\r\n" + "\r\n" + "0 \r\n" + "\r\n" + ,.should_keep_alive= TRUE + ,.message_complete_on_eof= FALSE + ,.http_major= 1 + ,.http_minor= 1 + ,.status_code= 200 + ,.num_headers= 2 + ,.headers= + { {"Content-Type", "text/plain" } + , {"Transfer-Encoding", "chunked" } + } + ,.body_size = 37+28 + ,.body = + "This is the data in the first chunk\r\n" + "and this is the second one\r\n" + + } + +#define NO_CARRIAGE_RET 5 +, {.name="no carriage ret" + ,.type= HTTP_RESPONSE + ,.raw= "HTTP/1.1 200 OK\n" + "Content-Type: text/html; charset=utf-8\n" + "Connection: close\n" + "\n" + "these headers are from http://news.ycombinator.com/" + ,.should_keep_alive= FALSE + ,.message_complete_on_eof= TRUE + ,.http_major= 1 + ,.http_minor= 1 + ,.status_code= 200 + ,.num_headers= 2 + ,.headers= + { {"Content-Type", "text/html; charset=utf-8" } + , {"Connection", "close" } + } + ,.body= "these headers are from http://news.ycombinator.com/" + } + +#define PROXY_CONNECTION 6 +, {.name="proxy connection" + ,.type= HTTP_RESPONSE + ,.raw= "HTTP/1.1 200 OK\r\n" + "Content-Type: text/html; charset=UTF-8\r\n" + "Content-Length: 11\r\n" + "Proxy-Connection: close\r\n" + "Date: Thu, 31 Dec 2009 20:55:48 +0000\r\n" + "\r\n" + "hello world" + ,.should_keep_alive= FALSE + ,.message_complete_on_eof= FALSE + ,.http_major= 1 + ,.http_minor= 1 + ,.status_code= 200 + ,.num_headers= 4 + ,.headers= + { {"Content-Type", "text/html; charset=UTF-8" } + , {"Content-Length", "11" } + , {"Proxy-Connection", "close" } + , {"Date", "Thu, 31 Dec 2009 20:55:48 +0000"} + } + ,.body= "hello world" + } + +#define UNDERSTORE_HEADER_KEY 7 + // shown by + // curl -o /dev/null -v "http://ad.doubleclick.net/pfadx/DARTSHELLCONFIGXML;dcmt=text/xml;" +, {.name="underscore header key" + ,.type= HTTP_RESPONSE + ,.raw= "HTTP/1.1 200 OK\r\n" + "Server: DCLK-AdSvr\r\n" + "Content-Type: text/xml\r\n" + "Content-Length: 0\r\n" + "DCLK_imp: v7;x;114750856;0-0;0;17820020;0/0;21603567/21621457/1;;~okv=;dcmt=text/xml;;~cs=o\r\n\r\n" + ,.should_keep_alive= TRUE + ,.message_complete_on_eof= FALSE + ,.http_major= 1 + ,.http_minor= 1 + ,.status_code= 200 + ,.num_headers= 4 + ,.headers= + { {"Server", "DCLK-AdSvr" } + , {"Content-Type", "text/xml" } + , {"Content-Length", "0" } + , {"DCLK_imp", "v7;x;114750856;0-0;0;17820020;0/0;21603567/21621457/1;;~okv=;dcmt=text/xml;;~cs=o" } + } + ,.body= "" + } + +#define BONJOUR_MADAME_FR 8 +/* The client should not merge two headers fields when the first one doesn't + * have a value. + */ +, {.name= "bonjourmadame.fr" + ,.type= HTTP_RESPONSE + ,.raw= "HTTP/1.0 301 Moved Permanently\r\n" + "Date: Thu, 03 Jun 2010 09:56:32 GMT\r\n" + "Server: Apache/2.2.3 (Red Hat)\r\n" + "Cache-Control: public\r\n" + "Pragma: \r\n" + "Location: http://www.bonjourmadame.fr/\r\n" + "Vary: Accept-Encoding\r\n" + "Content-Length: 0\r\n" + "Content-Type: text/html; charset=UTF-8\r\n" + "Connection: keep-alive\r\n" + "\r\n" + ,.should_keep_alive= TRUE + ,.message_complete_on_eof= FALSE + ,.http_major= 1 + ,.http_minor= 0 + ,.status_code= 301 + ,.num_headers= 9 + ,.headers= + { { "Date", "Thu, 03 Jun 2010 09:56:32 GMT" } + , { "Server", "Apache/2.2.3 (Red Hat)" } + , { "Cache-Control", "public" } + , { "Pragma", "" } + , { "Location", "http://www.bonjourmadame.fr/" } + , { "Vary", "Accept-Encoding" } + , { "Content-Length", "0" } + , { "Content-Type", "text/html; charset=UTF-8" } + , { "Connection", "keep-alive" } + } + ,.body= "" + } + +#define SPACE_IN_FIELD_RES 9 +/* Should handle spaces in header fields */ +, {.name= "field space" + ,.type= HTTP_RESPONSE + ,.raw= "HTTP/1.1 200 OK\r\n" + "Server: Microsoft-IIS/6.0\r\n" + "X-Powered-By: ASP.NET\r\n" + "en-US Content-Type: text/xml\r\n" /* this is the problem */ + "Content-Type: text/xml\r\n" + "Content-Length: 16\r\n" + "Date: Fri, 23 Jul 2010 18:45:38 GMT\r\n" + "Connection: keep-alive\r\n" + "\r\n" + "hello" /* fake body */ + ,.should_keep_alive= TRUE + ,.message_complete_on_eof= FALSE + ,.http_major= 1 + ,.http_minor= 1 + ,.status_code= 200 + ,.num_headers= 7 + ,.headers= + { { "Server", "Microsoft-IIS/6.0" } + , { "X-Powered-By", "ASP.NET" } + , { "en-US Content-Type", "text/xml" } + , { "Content-Type", "text/xml" } + , { "Content-Length", "16" } + , { "Date", "Fri, 23 Jul 2010 18:45:38 GMT" } + , { "Connection", "keep-alive" } + } + ,.body= "hello" + } + + +#define RES_FIELD_UNDERSCORE 10 +/* Should handle spaces in header fields */ +, {.name= "field underscore" + ,.type= HTTP_RESPONSE + ,.raw= "HTTP/1.1 200 OK\r\n" + "Date: Tue, 28 Sep 2010 01:14:13 GMT\r\n" + "Server: Apache\r\n" + "Cache-Control: no-cache, must-revalidate\r\n" + "Expires: Mon, 26 Jul 1997 05:00:00 GMT\r\n" + ".et-Cookie: PlaxoCS=1274804622353690521; path=/; domain=.plaxo.com\r\n" + "Vary: Accept-Encoding\r\n" + "_eep-Alive: timeout=45\r\n" /* semantic value ignored */ + "_onnection: Keep-Alive\r\n" /* semantic value ignored */ + "Transfer-Encoding: chunked\r\n" + "Content-Type: text/html\r\n" + "Connection: close\r\n" + "\r\n" + "0\r\n\r\n" + ,.should_keep_alive= FALSE + ,.message_complete_on_eof= FALSE + ,.http_major= 1 + ,.http_minor= 1 + ,.status_code= 200 + ,.num_headers= 11 + ,.headers= + { { "Date", "Tue, 28 Sep 2010 01:14:13 GMT" } + , { "Server", "Apache" } + , { "Cache-Control", "no-cache, must-revalidate" } + , { "Expires", "Mon, 26 Jul 1997 05:00:00 GMT" } + , { ".et-Cookie", "PlaxoCS=1274804622353690521; path=/; domain=.plaxo.com" } + , { "Vary", "Accept-Encoding" } + , { "_eep-Alive", "timeout=45" } + , { "_onnection", "Keep-Alive" } + , { "Transfer-Encoding", "chunked" } + , { "Content-Type", "text/html" } + , { "Connection", "close" } + } + ,.body= "" + } + +#define NON_ASCII_IN_STATUS_LINE 11 +/* Should handle non-ASCII in status line */ +, {.name= "non-ASCII in status line" + ,.type= HTTP_RESPONSE + ,.raw= "HTTP/1.1 500 Oriëntatieprobleem\r\n" + "Date: Fri, 5 Nov 2010 23:07:12 GMT+2\r\n" + "Content-Length: 0\r\n" + "Connection: close\r\n" + "\r\n" + ,.should_keep_alive= FALSE + ,.message_complete_on_eof= FALSE + ,.http_major= 1 + ,.http_minor= 1 + ,.status_code= 500 + ,.num_headers= 3 + ,.headers= + { { "Date", "Fri, 5 Nov 2010 23:07:12 GMT+2" } + , { "Content-Length", "0" } + , { "Connection", "close" } + } + ,.body= "" + } + +#define HTTP_VERSION_0_9 12 +/* Should handle HTTP/0.9 */ +, {.name= "http version 0.9" + ,.type= HTTP_RESPONSE + ,.raw= "HTTP/0.9 200 OK\r\n" + "\r\n" + ,.should_keep_alive= FALSE + ,.message_complete_on_eof= TRUE + ,.http_major= 0 + ,.http_minor= 9 + ,.status_code= 200 + ,.num_headers= 0 + ,.headers= + {} + ,.body= "" + } +, {.name= NULL } /* sentinel */ + +}; + +int +request_url_cb (http_parser *p, const char *buf, size_t len) +{ + assert(p == parser); + strncat(messages[num_messages].request_url, buf, len); + return 0; +} + +int +header_field_cb (http_parser *p, const char *buf, size_t len) +{ + assert(p == parser); + struct message *m = &messages[num_messages]; + + if (m->last_header_element != FIELD) + m->num_headers++; + + strncat(m->headers[m->num_headers-1][0], buf, len); + + m->last_header_element = FIELD; + + return 0; +} + +int +header_value_cb (http_parser *p, const char *buf, size_t len) +{ + assert(p == parser); + struct message *m = &messages[num_messages]; + + strncat(m->headers[m->num_headers-1][1], buf, len); + + m->last_header_element = VALUE; + + return 0; +} + +int +body_cb (http_parser *p, const char *buf, size_t len) +{ + assert(p == parser); + strncat(messages[num_messages].body, buf, len); + messages[num_messages].body_size += len; + // printf("body_cb: '%s'\n", requests[num_messages].body); + return 0; +} + +int +count_body_cb (http_parser *p, const char *buf, size_t len) +{ + assert(p == parser); + assert(buf); + messages[num_messages].body_size += len; + return 0; +} + +int +message_begin_cb (http_parser *p) +{ + assert(p == parser); + messages[num_messages].message_begin_cb_called = TRUE; + return 0; +} + +int +headers_complete_cb (http_parser *p) +{ + assert(p == parser); + messages[num_messages].method = parser->method; + messages[num_messages].status_code = parser->status_code; + messages[num_messages].http_major = parser->http_major; + messages[num_messages].http_minor = parser->http_minor; + messages[num_messages].headers_complete_cb_called = TRUE; + messages[num_messages].should_keep_alive = http_should_keep_alive(parser); + return 0; +} + +int +message_complete_cb (http_parser *p) +{ + assert(p == parser); + if (messages[num_messages].should_keep_alive != http_should_keep_alive(parser)) + { + fprintf(stderr, "\n\n *** Error http_should_keep_alive() should have same " + "value in both on_message_complete and on_headers_complete " + "but it doesn't! ***\n\n"); + assert(0); + exit(1); + } + messages[num_messages].message_complete_cb_called = TRUE; + + messages[num_messages].message_complete_on_eof = currently_parsing_eof; + + num_messages++; + return 0; +} + +static http_parser_settings settings = + {.on_message_begin = message_begin_cb + ,.on_header_field = header_field_cb + ,.on_header_value = header_value_cb + ,.on_url = request_url_cb + ,.on_body = body_cb + ,.on_headers_complete = headers_complete_cb + ,.on_message_complete = message_complete_cb + }; + +static http_parser_settings settings_count_body = + {.on_message_begin = message_begin_cb + ,.on_header_field = header_field_cb + ,.on_header_value = header_value_cb + ,.on_url = request_url_cb + ,.on_body = count_body_cb + ,.on_headers_complete = headers_complete_cb + ,.on_message_complete = message_complete_cb + }; + +static http_parser_settings settings_null = + {.on_message_begin = 0 + ,.on_header_field = 0 + ,.on_header_value = 0 + ,.on_url = 0 + ,.on_body = 0 + ,.on_headers_complete = 0 + ,.on_message_complete = 0 + }; + +void +parser_init (enum http_parser_type type) +{ + num_messages = 0; + + assert(parser == NULL); + + parser = malloc(sizeof(http_parser)); + + http_parser_init(parser, type); + + memset(&messages, 0, sizeof messages); + +} + +void +parser_free () +{ + assert(parser); + free(parser); + parser = NULL; +} + +size_t parse (const char *buf, size_t len) +{ + size_t nparsed; + currently_parsing_eof = (len == 0); + nparsed = http_parser_execute(parser, &settings, buf, len); + return nparsed; +} + +size_t parse_count_body (const char *buf, size_t len) +{ + size_t nparsed; + currently_parsing_eof = (len == 0); + nparsed = http_parser_execute(parser, &settings_count_body, buf, len); + return nparsed; +} + +static inline int +check_str_eq (const struct message *m, + const char *prop, + const char *expected, + const char *found) { + if ((expected == NULL) != (found == NULL)) { + printf("\n*** Error: %s in '%s' ***\n\n", prop, m->name); + printf("expected %s\n", (expected == NULL) ? "NULL" : expected); + printf(" found %s\n", (found == NULL) ? "NULL" : found); + return 0; + } + if (expected != NULL && 0 != strcmp(expected, found)) { + printf("\n*** Error: %s in '%s' ***\n\n", prop, m->name); + printf("expected '%s'\n", expected); + printf(" found '%s'\n", found); + return 0; + } + return 1; +} + +static inline int +check_num_eq (const struct message *m, + const char *prop, + int expected, + int found) { + if (expected != found) { + printf("\n*** Error: %s in '%s' ***\n\n", prop, m->name); + printf("expected %d\n", expected); + printf(" found %d\n", found); + return 0; + } + return 1; +} + +#define MESSAGE_CHECK_STR_EQ(expected, found, prop) \ + if (!check_str_eq(expected, #prop, expected->prop, found->prop)) return 0 + +#define MESSAGE_CHECK_NUM_EQ(expected, found, prop) \ + if (!check_num_eq(expected, #prop, expected->prop, found->prop)) return 0 + + +int +message_eq (int index, const struct message *expected) +{ + int i; + struct message *m = &messages[index]; + + MESSAGE_CHECK_NUM_EQ(expected, m, http_major); + MESSAGE_CHECK_NUM_EQ(expected, m, http_minor); + + if (expected->type == HTTP_REQUEST) { + MESSAGE_CHECK_NUM_EQ(expected, m, method); + } else { + MESSAGE_CHECK_NUM_EQ(expected, m, status_code); + } + + MESSAGE_CHECK_NUM_EQ(expected, m, should_keep_alive); + MESSAGE_CHECK_NUM_EQ(expected, m, message_complete_on_eof); + + assert(m->message_begin_cb_called); + assert(m->headers_complete_cb_called); + assert(m->message_complete_cb_called); + + + MESSAGE_CHECK_STR_EQ(expected, m, request_url); + if (expected->body_size) { + MESSAGE_CHECK_NUM_EQ(expected, m, body_size); + } else { + MESSAGE_CHECK_STR_EQ(expected, m, body); + } + + MESSAGE_CHECK_NUM_EQ(expected, m, num_headers); + + int r; + for (i = 0; i < m->num_headers; i++) { + r = check_str_eq(expected, "header field", expected->headers[i][0], m->headers[i][0]); + if (!r) return 0; + r = check_str_eq(expected, "header value", expected->headers[i][1], m->headers[i][1]); + if (!r) return 0; + } + + MESSAGE_CHECK_STR_EQ(expected, m, upgrade); + + return 1; +} + +/* Given a sequence of varargs messages, return the number of them that the + * parser should successfully parse, taking into account that upgraded + * messages prevent all subsequent messages from being parsed. + */ +size_t +count_parsed_messages(const size_t nmsgs, ...) { + size_t i; + va_list ap; + + va_start(ap, nmsgs); + + for (i = 0; i < nmsgs; i++) { + struct message *m = va_arg(ap, struct message *); + + if (m->upgrade) { + va_end(ap); + return i + 1; + } + } + + va_end(ap); + return nmsgs; +} + +/* Given a sequence of bytes and the number of these that we were able to + * parse, verify that upgrade bodies are correct. + */ +void +upgrade_message_fix(char *body, const size_t nread, const size_t nmsgs, ...) { + va_list ap; + size_t i; + size_t off = 0; + + va_start(ap, nmsgs); + + for (i = 0; i < nmsgs; i++) { + struct message *m = va_arg(ap, struct message *); + + off += strlen(m->raw); + + if (m->upgrade) { + off -= strlen(m->upgrade); + + /* Check the portion of the response after its specified upgrade */ + if (!check_str_eq(m, "upgrade", body + off, body + nread)) { + exit(1); + } + + /* Fix up the response so that message_eq() will verify the beginning + * of the upgrade */ + *(body + nread + strlen(m->upgrade)) = '\0'; + messages[num_messages -1 ].upgrade = body + nread; + + va_end(ap); + return; + } + } + + va_end(ap); + printf("\n\n*** Error: expected a message with upgrade ***\n"); + + exit(1); +} + +static void +print_error (const char *raw, size_t error_location) +{ + fprintf(stderr, "\n*** %s:%d -- %s ***\n\n", + "http_parser.c", HTTP_PARSER_ERRNO_LINE(parser), + http_errno_description(HTTP_PARSER_ERRNO(parser))); + + int this_line = 0, char_len = 0; + size_t i, j, len = strlen(raw), error_location_line = 0; + for (i = 0; i < len; i++) { + if (i == error_location) this_line = 1; + switch (raw[i]) { + case '\r': + char_len = 2; + fprintf(stderr, "\\r"); + break; + + case '\n': + char_len = 2; + fprintf(stderr, "\\n\n"); + + if (this_line) goto print; + + error_location_line = 0; + continue; + + default: + char_len = 1; + fputc(raw[i], stderr); + break; + } + if (!this_line) error_location_line += char_len; + } + + fprintf(stderr, "[eof]\n"); + + print: + for (j = 0; j < error_location_line; j++) { + fputc(' ', stderr); + } + fprintf(stderr, "^\n\nerror location: %u\n", (unsigned int)error_location); +} + + +void +test_message (const struct message *message) +{ + size_t raw_len = strlen(message->raw); + size_t msg1len; + for (msg1len = 0; msg1len < raw_len; msg1len++) { + parser_init(message->type); + + size_t read; + const char *msg1 = message->raw; + const char *msg2 = msg1 + msg1len; + size_t msg2len = raw_len - msg1len; + + if (msg1len) { + read = parse(msg1, msg1len); + + if (message->upgrade && parser->upgrade) { + messages[num_messages - 1].upgrade = msg1 + read; + goto test; + } + + if (read != msg1len) { + print_error(msg1, read); + exit(1); + } + } + + + read = parse(msg2, msg2len); + + if (message->upgrade && parser->upgrade) { + messages[num_messages - 1].upgrade = msg2 + read; + goto test; + } + + if (read != msg2len) { + print_error(msg2, read); + exit(1); + } + + read = parse(NULL, 0); + + if (read != 0) { + print_error(message->raw, read); + exit(1); + } + + test: + + if (num_messages != 1) { + printf("\n*** num_messages != 1 after testing '%s' ***\n\n", message->name); + exit(1); + } + + if(!message_eq(0, message)) exit(1); + + parser_free(); + } +} + +void +test_message_count_body (const struct message *message) +{ + parser_init(message->type); + + size_t read; + size_t l = strlen(message->raw); + size_t i, toread; + size_t chunk = 4024; + + for (i = 0; i < l; i+= chunk) { + toread = MIN(l-i, chunk); + read = parse_count_body(message->raw + i, toread); + if (read != toread) { + print_error(message->raw, read); + exit(1); + } + } + + + read = parse_count_body(NULL, 0); + if (read != 0) { + print_error(message->raw, read); + exit(1); + } + + if (num_messages != 1) { + printf("\n*** num_messages != 1 after testing '%s' ***\n\n", message->name); + exit(1); + } + + if(!message_eq(0, message)) exit(1); + + parser_free(); +} + +void +test_simple (const char *buf, enum http_errno err_expected) +{ + parser_init(HTTP_REQUEST); + + size_t parsed; + int pass; + enum http_errno err; + + parsed = parse(buf, strlen(buf)); + pass = (parsed == strlen(buf)); + err = HTTP_PARSER_ERRNO(parser); + parsed = parse(NULL, 0); + pass &= (parsed == 0); + + parser_free(); + + /* In strict mode, allow us to pass with an unexpected HPE_STRICT as + * long as the caller isn't expecting success. + */ +#if HTTP_PARSER_STRICT + if (err_expected != err && err_expected != HPE_OK && err != HPE_STRICT) { +#else + if (err_expected != err) { +#endif + fprintf(stderr, "\n*** test_simple expected %s, but saw %s ***\n\n%s\n", + http_errno_name(err_expected), http_errno_name(err), buf); + exit(1); + } +} + +void +test_header_overflow_error (int req) +{ + http_parser parser; + http_parser_init(&parser, req ? HTTP_REQUEST : HTTP_RESPONSE); + size_t parsed; + const char *buf; + buf = req ? "GET / HTTP/1.1\r\n" : "HTTP/1.0 200 OK\r\n"; + parsed = http_parser_execute(&parser, &settings_null, buf, strlen(buf)); + assert(parsed == strlen(buf)); + + buf = "header-key: header-value\r\n"; + size_t buflen = strlen(buf); + + int i; + for (i = 0; i < 10000; i++) { + parsed = http_parser_execute(&parser, &settings_null, buf, buflen); + if (parsed != buflen) { + //fprintf(stderr, "error found on iter %d\n", i); + assert(HTTP_PARSER_ERRNO(&parser) == HPE_HEADER_OVERFLOW); + return; + } + } + + fprintf(stderr, "\n*** Error expected but none in header overflow test ***\n"); + exit(1); +} + +void +test_no_overflow_long_body (int req, size_t length) +{ + http_parser parser; + http_parser_init(&parser, req ? HTTP_REQUEST : HTTP_RESPONSE); + size_t parsed; + size_t i; + char buf1[3000]; + size_t buf1len = sprintf(buf1, "%s\r\nConnection: Keep-Alive\r\nContent-Length: %zu\r\n\r\n", + req ? "POST / HTTP/1.0" : "HTTP/1.0 200 OK", length); + parsed = http_parser_execute(&parser, &settings_null, buf1, buf1len); + if (parsed != buf1len) + goto err; + + for (i = 0; i < length; i++) { + char foo = 'a'; + parsed = http_parser_execute(&parser, &settings_null, &foo, 1); + if (parsed != 1) + goto err; + } + + parsed = http_parser_execute(&parser, &settings_null, buf1, buf1len); + if (parsed != buf1len) goto err; + return; + + err: + fprintf(stderr, + "\n*** error in test_no_overflow_long_body %s of length %zu ***\n", + req ? "REQUEST" : "RESPONSE", + length); + exit(1); +} + +void +test_multiple3 (const struct message *r1, const struct message *r2, const struct message *r3) +{ + int message_count = count_parsed_messages(3, r1, r2, r3); + + char total[ strlen(r1->raw) + + strlen(r2->raw) + + strlen(r3->raw) + + 1 + ]; + total[0] = '\0'; + + strcat(total, r1->raw); + strcat(total, r2->raw); + strcat(total, r3->raw); + + parser_init(r1->type); + + size_t read; + + read = parse(total, strlen(total)); + + if (parser->upgrade) { + upgrade_message_fix(total, read, 3, r1, r2, r3); + goto test; + } + + if (read != strlen(total)) { + print_error(total, read); + exit(1); + } + + read = parse(NULL, 0); + + if (read != 0) { + print_error(total, read); + exit(1); + } + +test: + + if (message_count != num_messages) { + fprintf(stderr, "\n\n*** Parser didn't see 3 messages only %d *** \n", num_messages); + exit(1); + } + + if (!message_eq(0, r1)) exit(1); + if (message_count > 1 && !message_eq(1, r2)) exit(1); + if (message_count > 2 && !message_eq(2, r3)) exit(1); + + parser_free(); +} + +/* SCAN through every possible breaking to make sure the + * parser can handle getting the content in any chunks that + * might come from the socket + */ +void +test_scan (const struct message *r1, const struct message *r2, const struct message *r3) +{ + char total[80*1024] = "\0"; + char buf1[80*1024] = "\0"; + char buf2[80*1024] = "\0"; + char buf3[80*1024] = "\0"; + + strcat(total, r1->raw); + strcat(total, r2->raw); + strcat(total, r3->raw); + + size_t read; + + int total_len = strlen(total); + + int total_ops = 2 * (total_len - 1) * (total_len - 2) / 2; + int ops = 0 ; + + size_t buf1_len, buf2_len, buf3_len; + int message_count = count_parsed_messages(3, r1, r2, r3); + + int i,j,type_both; + for (type_both = 0; type_both < 2; type_both ++ ) { + for (j = 2; j < total_len; j ++ ) { + for (i = 1; i < j; i ++ ) { + + if (ops % 1000 == 0) { + printf("\b\b\b\b%3.0f%%", 100 * (float)ops /(float)total_ops); + fflush(stdout); + } + ops += 1; + + parser_init(type_both ? HTTP_BOTH : r1->type); + + buf1_len = i; + strncpy(buf1, total, buf1_len); + buf1[buf1_len] = 0; + + buf2_len = j - i; + strncpy(buf2, total+i, buf2_len); + buf2[buf2_len] = 0; + + buf3_len = total_len - j; + strncpy(buf3, total+j, buf3_len); + buf3[buf3_len] = 0; + + read = parse(buf1, buf1_len); + + if (parser->upgrade) goto test; + + if (read != buf1_len) { + print_error(buf1, read); + goto error; + } + + read += parse(buf2, buf2_len); + + if (parser->upgrade) goto test; + + if (read != buf1_len + buf2_len) { + print_error(buf2, read); + goto error; + } + + read += parse(buf3, buf3_len); + + if (parser->upgrade) goto test; + + if (read != buf1_len + buf2_len + buf3_len) { + print_error(buf3, read); + goto error; + } + + parse(NULL, 0); + +test: + if (parser->upgrade) { + upgrade_message_fix(total, read, 3, r1, r2, r3); + } + + if (message_count != num_messages) { + fprintf(stderr, "\n\nParser didn't see %d messages only %d\n", + message_count, num_messages); + goto error; + } + + if (!message_eq(0, r1)) { + fprintf(stderr, "\n\nError matching messages[0] in test_scan.\n"); + goto error; + } + + if (message_count > 1 && !message_eq(1, r2)) { + fprintf(stderr, "\n\nError matching messages[1] in test_scan.\n"); + goto error; + } + + if (message_count > 2 && !message_eq(2, r3)) { + fprintf(stderr, "\n\nError matching messages[2] in test_scan.\n"); + goto error; + } + + parser_free(); + } + } + } + puts("\b\b\b\b100%"); + return; + + error: + fprintf(stderr, "i=%d j=%d\n", i, j); + fprintf(stderr, "buf1 (%u) %s\n\n", (unsigned int)buf1_len, buf1); + fprintf(stderr, "buf2 (%u) %s\n\n", (unsigned int)buf2_len , buf2); + fprintf(stderr, "buf3 (%u) %s\n", (unsigned int)buf3_len, buf3); + exit(1); +} + +// user required to free the result +// string terminated by \0 +char * +create_large_chunked_message (int body_size_in_kb, const char* headers) +{ + int i; + size_t wrote = 0; + size_t headers_len = strlen(headers); + size_t bufsize = headers_len + (5+1024+2)*body_size_in_kb + 6; + char * buf = malloc(bufsize); + + memcpy(buf, headers, headers_len); + wrote += headers_len; + + for (i = 0; i < body_size_in_kb; i++) { + // write 1kb chunk into the body. + memcpy(buf + wrote, "400\r\n", 5); + wrote += 5; + memset(buf + wrote, 'C', 1024); + wrote += 1024; + strcpy(buf + wrote, "\r\n"); + wrote += 2; + } + + memcpy(buf + wrote, "0\r\n\r\n", 6); + wrote += 6; + assert(wrote == bufsize); + + return buf; +} + + +int +main (void) +{ + parser = NULL; + int i, j, k; + int request_count; + int response_count; + + printf("sizeof(http_parser) = %u\n", (unsigned int)sizeof(http_parser)); + + for (request_count = 0; requests[request_count].name; request_count++); + for (response_count = 0; responses[response_count].name; response_count++); + + //// OVERFLOW CONDITIONS + + test_header_overflow_error(HTTP_REQUEST); + test_no_overflow_long_body(HTTP_REQUEST, 1000); + test_no_overflow_long_body(HTTP_REQUEST, 100000); + + test_header_overflow_error(HTTP_RESPONSE); + test_no_overflow_long_body(HTTP_RESPONSE, 1000); + test_no_overflow_long_body(HTTP_RESPONSE, 100000); + + //// RESPONSES + + for (i = 0; i < response_count; i++) { + test_message(&responses[i]); + } + + for (i = 0; i < response_count; i++) { + if (!responses[i].should_keep_alive) continue; + for (j = 0; j < response_count; j++) { + if (!responses[j].should_keep_alive) continue; + for (k = 0; k < response_count; k++) { + test_multiple3(&responses[i], &responses[j], &responses[k]); + } + } + } + + test_message_count_body(&responses[NO_HEADERS_NO_BODY_404]); + test_message_count_body(&responses[TRAILING_SPACE_ON_CHUNKED_BODY]); + + // test very large chunked response + { + char * msg = create_large_chunked_message(31337, + "HTTP/1.0 200 OK\r\n" + "Transfer-Encoding: chunked\r\n" + "Content-Type: text/plain\r\n" + "\r\n"); + struct message large_chunked = + {.name= "large chunked" + ,.type= HTTP_RESPONSE + ,.raw= msg + ,.should_keep_alive= FALSE + ,.message_complete_on_eof= FALSE + ,.http_major= 1 + ,.http_minor= 0 + ,.status_code= 200 + ,.num_headers= 2 + ,.headers= + { { "Transfer-Encoding", "chunked" } + , { "Content-Type", "text/plain" } + } + ,.body_size= 31337*1024 + }; + test_message_count_body(&large_chunked); + free(msg); + } + + + + printf("response scan 1/2 "); + test_scan( &responses[TRAILING_SPACE_ON_CHUNKED_BODY] + , &responses[NO_HEADERS_NO_BODY_404] + , &responses[NO_REASON_PHRASE] + ); + + printf("response scan 2/2 "); + test_scan( &responses[BONJOUR_MADAME_FR] + , &responses[UNDERSTORE_HEADER_KEY] + , &responses[NO_CARRIAGE_RET] + ); + + puts("responses okay"); + + + /// REQUESTS + + test_simple("hello world", HPE_INVALID_METHOD); + test_simple("GET / HTP/1.1\r\n\r\n", HPE_INVALID_VERSION); + + + test_simple("ASDF / HTTP/1.1\r\n\r\n", HPE_INVALID_METHOD); + test_simple("PROPPATCHA / HTTP/1.1\r\n\r\n", HPE_INVALID_METHOD); + test_simple("GETA / HTTP/1.1\r\n\r\n", HPE_INVALID_METHOD); + + // Well-formed but incomplete + test_simple("GET / HTTP/1.1\r\n" + "Content-Type: text/plain\r\n" + "Content-Length: 6\r\n" + "\r\n" + "fooba", + HPE_OK); + + static const char *all_methods[] = { + "DELETE", + "GET", + "HEAD", + "POST", + "PUT", + //"CONNECT", //CONNECT can't be tested like other methods, it's a tunnel + "OPTIONS", + "TRACE", + "COPY", + "LOCK", + "MKCOL", + "MOVE", + "PROPFIND", + "PROPPATCH", + "UNLOCK", + "REPORT", + "MKACTIVITY", + "CHECKOUT", + "MERGE", + "M-SEARCH", + "NOTIFY", + "SUBSCRIBE", + "UNSUBSCRIBE", + "PATCH", + 0 }; + const char **this_method; + for (this_method = all_methods; *this_method; this_method++) { + char buf[200]; + sprintf(buf, "%s / HTTP/1.1\r\n\r\n", *this_method); + test_simple(buf, HPE_OK); + } + + static const char *bad_methods[] = { + "C******", + "M****", + 0 }; + for (this_method = bad_methods; *this_method; this_method++) { + char buf[200]; + sprintf(buf, "%s / HTTP/1.1\r\n\r\n", *this_method); + test_simple(buf, HPE_UNKNOWN); + } + + const char *dumbfuck2 = + "GET / HTTP/1.1\r\n" + "X-SSL-Bullshit: -----BEGIN CERTIFICATE-----\r\n" + "\tMIIFbTCCBFWgAwIBAgICH4cwDQYJKoZIhvcNAQEFBQAwcDELMAkGA1UEBhMCVUsx\r\n" + "\tETAPBgNVBAoTCGVTY2llbmNlMRIwEAYDVQQLEwlBdXRob3JpdHkxCzAJBgNVBAMT\r\n" + "\tAkNBMS0wKwYJKoZIhvcNAQkBFh5jYS1vcGVyYXRvckBncmlkLXN1cHBvcnQuYWMu\r\n" + "\tdWswHhcNMDYwNzI3MTQxMzI4WhcNMDcwNzI3MTQxMzI4WjBbMQswCQYDVQQGEwJV\r\n" + "\tSzERMA8GA1UEChMIZVNjaWVuY2UxEzARBgNVBAsTCk1hbmNoZXN0ZXIxCzAJBgNV\r\n" + "\tBAcTmrsogriqMWLAk1DMRcwFQYDVQQDEw5taWNoYWVsIHBhcmQYJKoZIhvcNAQEB\r\n" + "\tBQADggEPADCCAQoCggEBANPEQBgl1IaKdSS1TbhF3hEXSl72G9J+WC/1R64fAcEF\r\n" + "\tW51rEyFYiIeZGx/BVzwXbeBoNUK41OK65sxGuflMo5gLflbwJtHBRIEKAfVVp3YR\r\n" + "\tgW7cMA/s/XKgL1GEC7rQw8lIZT8RApukCGqOVHSi/F1SiFlPDxuDfmdiNzL31+sL\r\n" + "\t0iwHDdNkGjy5pyBSB8Y79dsSJtCW/iaLB0/n8Sj7HgvvZJ7x0fr+RQjYOUUfrePP\r\n" + "\tu2MSpFyf+9BbC/aXgaZuiCvSR+8Snv3xApQY+fULK/xY8h8Ua51iXoQ5jrgu2SqR\r\n" + "\twgA7BUi3G8LFzMBl8FRCDYGUDy7M6QaHXx1ZWIPWNKsCAwEAAaOCAiQwggIgMAwG\r\n" + "\tA1UdEwEB/wQCMAAwEQYJYIZIAYb4QgHTTPAQDAgWgMA4GA1UdDwEB/wQEAwID6DAs\r\n" + "\tBglghkgBhvhCAQ0EHxYdVUsgZS1TY2llbmNlIFVzZXIgQ2VydGlmaWNhdGUwHQYD\r\n" + "\tVR0OBBYEFDTt/sf9PeMaZDHkUIldrDYMNTBZMIGaBgNVHSMEgZIwgY+AFAI4qxGj\r\n" + "\tloCLDdMVKwiljjDastqooXSkcjBwMQswCQYDVQQGEwJVSzERMA8GA1UEChMIZVNj\r\n" + "\taWVuY2UxEjAQBgNVBAsTCUF1dGhvcml0eTELMAkGA1UEAxMCQ0ExLTArBgkqhkiG\r\n" + "\t9w0BCQEWHmNhLW9wZXJhdG9yQGdyaWQtc3VwcG9ydC5hYy51a4IBADApBgNVHRIE\r\n" + "\tIjAggR5jYS1vcGVyYXRvckBncmlkLXN1cHBvcnQuYWMudWswGQYDVR0gBBIwEDAO\r\n" + "\tBgwrBgEEAdkvAQEBAQYwPQYJYIZIAYb4QgEEBDAWLmh0dHA6Ly9jYS5ncmlkLXN1\r\n" + "\tcHBvcnQuYWMudmT4sopwqlBWsvcHViL2NybC9jYWNybC5jcmwwPQYJYIZIAYb4QgEDBDAWLmh0\r\n" + "\tdHA6Ly9jYS5ncmlkLXN1cHBvcnQuYWMudWsvcHViL2NybC9jYWNybC5jcmwwPwYD\r\n" + "\tVR0fBDgwNjA0oDKgMIYuaHR0cDovL2NhLmdyaWQt5hYy51ay9wdWIv\r\n" + "\tY3JsL2NhY3JsLmNybDANBgkqhkiG9w0BAQUFAAOCAQEAS/U4iiooBENGW/Hwmmd3\r\n" + "\tXCy6Zrt08YjKCzGNjorT98g8uGsqYjSxv/hmi0qlnlHs+k/3Iobc3LjS5AMYr5L8\r\n" + "\tUO7OSkgFFlLHQyC9JzPfmLCAugvzEbyv4Olnsr8hbxF1MbKZoQxUZtMVu29wjfXk\r\n" + "\thTeApBv7eaKCWpSp7MCbvgzm74izKhu3vlDk9w6qVrxePfGgpKPqfHiOoGhFnbTK\r\n" + "\twTC6o2xq5y0qZ03JonF7OJspEd3I5zKY3E+ov7/ZhW6DqT8UFvsAdjvQbXyhV8Eu\r\n" + "\tYhixw1aKEPzNjNowuIseVogKOLXxWI5vAi5HgXdS0/ES5gDGsABo4fqovUKlgop3\r\n" + "\tRA==\r\n" + "\t-----END CERTIFICATE-----\r\n" + "\r\n"; + test_simple(dumbfuck2, HPE_OK); + +#if 0 + // NOTE(Wed Nov 18 11:57:27 CET 2009) this seems okay. we just read body + // until EOF. + // + // no content-length + // error if there is a body without content length + const char *bad_get_no_headers_no_body = "GET /bad_get_no_headers_no_body/world HTTP/1.1\r\n" + "Accept: */*\r\n" + "\r\n" + "HELLO"; + test_simple(bad_get_no_headers_no_body, 0); +#endif + /* TODO sending junk and large headers gets rejected */ + + + /* check to make sure our predefined requests are okay */ + for (i = 0; requests[i].name; i++) { + test_message(&requests[i]); + } + + + + for (i = 0; i < request_count; i++) { + if (!requests[i].should_keep_alive) continue; + for (j = 0; j < request_count; j++) { + if (!requests[j].should_keep_alive) continue; + for (k = 0; k < request_count; k++) { + test_multiple3(&requests[i], &requests[j], &requests[k]); + } + } + } + + printf("request scan 1/4 "); + test_scan( &requests[GET_NO_HEADERS_NO_BODY] + , &requests[GET_ONE_HEADER_NO_BODY] + , &requests[GET_NO_HEADERS_NO_BODY] + ); + + printf("request scan 2/4 "); + test_scan( &requests[POST_CHUNKED_ALL_YOUR_BASE] + , &requests[POST_IDENTITY_BODY_WORLD] + , &requests[GET_FUNKY_CONTENT_LENGTH] + ); + + printf("request scan 3/4 "); + test_scan( &requests[TWO_CHUNKS_MULT_ZERO_END] + , &requests[CHUNKED_W_TRAILING_HEADERS] + , &requests[CHUNKED_W_BULLSHIT_AFTER_LENGTH] + ); + + printf("request scan 4/4 "); + test_scan( &requests[QUERY_URL_WITH_QUESTION_MARK_GET] + , &requests[PREFIX_NEWLINE_GET ] + , &requests[CONNECT_REQUEST] + ); + + puts("requests okay"); + + return 0; +} diff --git a/node-v0.8.14/deps/npm/.npmignore b/node-v0.8.14/deps/npm/.npmignore new file mode 100644 index 0000000..bd0982f --- /dev/null +++ b/node-v0.8.14/deps/npm/.npmignore @@ -0,0 +1,22 @@ +*.swp +npm-debug.log +/test/bin +/test/output.log +/test/packages/*/node_modules +/test/packages/npm-test-depends-on-spark/which-spark.log +/test/packages/test-package/random-data.txt +/test/root +node_modules/ronn +node_modules/tap +node_modules/.bin +/npmrc +/release/ + +# don't need these in the npm package. +html/*.png + +# don't ignore .npmignore files +# these are used in some tests. +!.npmignore + +/npm-*.tgz diff --git a/node-v0.8.14/deps/npm/AUTHORS b/node-v0.8.14/deps/npm/AUTHORS new file mode 100644 index 0000000..d1306ad --- /dev/null +++ b/node-v0.8.14/deps/npm/AUTHORS @@ -0,0 +1,79 @@ +# Authors sorted by whether or not they're me +Isaac Z. Schlueter (http://blog.izs.me/) +Steve Steiner (http://websaucesoftware.com/blog/) +Mikeal Rogers (http://www.mikealrogers.com/) +Aaron Blohowiak (http://aaronblohowiak.com/) +Martyn Smith (http://dollyfish.net.nz/) +Mathias Pettersson (http://mape.me/) +Brian Hammond (http://fictorial.com/) +Charlie Robbins (http://www.charlierobbins.com/) +Francisco Treacy (http://franciscotreacy.com/) +Cliffano Subagio (http://blog.cliffano.com/) +Christian Eager (http://perpenduum.com) +Dav Glass (http://blog.davglass.com) +Alex K. Wolfe +James Sanders (http://james-sanders.com/) +Reid Burke (http://reidburke.com/) +Arlo Breault (http://thoughtherder.com/) +Timo Derstappen (http://teemow.com) +Bradley Meck +Bart Teeuwisse (http://thecodemill.biz/) +Ben Noordhuis (http://bnoordhuis.nl/) +Tor Valamo (http://www.magnimedia.no/) +Whyme.Lyu <5longluna@gmail.com> (http://whyme.kuantu.com/) +Olivier Melcher +Tomaž Muraus (http://www.tomaz-muraus.info) +Evan Meagher (http://evanmeagher.net/) +Orlando Vazquez (http://2wycked.net/) +George Miroshnykov +Geoff Flarity (http://ca.linkedin.com/pub/geoff-flarity/a/536/43a) +Pete Kruckenberg +Laurie Harper (http://laurie.holoweb.net/) +Chris Wong +Max Goodman (http://chromacode.com/) +Scott Bronson +Federico Romero +Visnu Pitiyanuvath (http://visnup.com) +Irakli Gozalishvili (http://jeditoolkit.com/) +Mark Cahill (http://www.tiemonster.info/) +Zearin +Iain Sproat +Trent Mick (http://trentm.com/) +Felix Geisendörfer (http://www.debuggable.com/) +Conny Brunnkvist (http://twitter.com/connyb) +Will Elwood (https://github.com/welwood08) +Oleg Efimov (http://sannis.ru) +Martin Cooper +Jameson Little +cspotcode +Maciej Małecki +Stephen Sugden +Gautham Pai +David Trejo +Paul Vorbach +George Ornbo +Tim Oxley +Tyler Green +atomizer +Rod Vagg +Christian Howe +Andrew Lunny +Henrik Hodne +Adam Blackburn +Kris Windham +Jens Grunert +Joost-Wim Boekesteijn +Dalmais Maxence +Marcus Ekwall +Aaron Stacy +Phillip Howell +Domenic Denicola +James Halliday +Jeremy Cantrell +Ribettes +Don Park +Kei Son +Nicolas Morel +Mark Dube +Maxim Bogushevich +Justin Beckwith diff --git a/node-v0.8.14/deps/npm/LICENSE b/node-v0.8.14/deps/npm/LICENSE new file mode 100644 index 0000000..c0f51a7 --- /dev/null +++ b/node-v0.8.14/deps/npm/LICENSE @@ -0,0 +1,65 @@ +Copyright (c) Isaac Z. Schlueter (the "Original Author") +All rights reserved. + +MIT +no-false-attribs License + +Permission is hereby granted, free of charge, to any person +obtaining a copy of this software and associated documentation +files (the "Software"), to deal in the Software without +restriction, including without limitation the rights to use, +copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the +Software is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +Distributions of all or part of the Software intended to be used +by the recipients as they would use the unmodified Software, +containing modifications that substantially alter, remove, or +disable functionality of the Software, outside of the documented +configuration mechanisms provided by the Software, shall be +modified such that the Original Author's bug reporting email +addresses and urls are either replaced with the contact information +of the parties responsible for the changes, or removed entirely. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES +OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +OTHER DEALINGS IN THE SOFTWARE. + + +Except where noted, this license applies to any and all software +programs and associated documentation files created by the +Original Author, when distributed with the Software. + +"Node.js" and "node" trademark Joyent, Inc. npm is not officially +part of the Node.js project, and is neither owned by nor +officially affiliated with Joyent, Inc. + +Packages published in the npm registry (other than the Software and +its included dependencies) are not part of npm itself, are the sole +property of their respective maintainers, and are not covered by +this license. + +"npm Logo" created by Mathias Pettersson and Brian Hammond, +used with permission. + +"Gubblebum Blocky" font +Copyright (c) by Tjarda Koster, http://jelloween.deviantart.com +included for use in the npm website and documentation, +used with permission. + +This program uses "request", Copyright (c) Mikeal Rogers, +according to the terms of the Apache license. + +This program uses "mkdirp", Copyright (c) James Halliday, +according to the terms of the MIT/X11 license. + +This program uses "opener", Copyright (c) Domenic Denicola, +according to the terms of the DWTFPL2 license. diff --git a/node-v0.8.14/deps/npm/Makefile b/node-v0.8.14/deps/npm/Makefile new file mode 100644 index 0000000..6ee80d5 --- /dev/null +++ b/node-v0.8.14/deps/npm/Makefile @@ -0,0 +1,138 @@ +SHELL = bash + +markdowns = $(shell find doc -name '*.md' | grep -v 'index') README.md + +cli_mandocs = $(shell find doc/cli -name '*.md' \ + |sed 's|.md|.1|g' \ + |sed 's|doc/cli/|man/man1/|g' ) \ + man/man1/README.1 \ + man/man1/index.1 + +api_mandocs = $(shell find doc/api -name '*.md' \ + |sed 's|.md|.3|g' \ + |sed 's|doc/api/|man/man3/|g' ) + +cli_htmldocs = $(shell find doc/cli -name '*.md' \ + |grep -v 'index.md' \ + |sed 's|.md|.html|g' \ + |sed 's|doc/cli/|html/doc/|g' ) \ + html/doc/README.html \ + html/doc/index.html + +api_htmldocs = $(shell find doc/api -name '*.md' \ + |sed 's|.md|.html|g' \ + |sed 's|doc/api/|html/api/|g' ) + +mandocs = $(api_mandocs) $(cli_mandocs) + +htmldocs = $(api_htmldocs) $(cli_htmldocs) + +all: doc + +latest: + @echo "Installing latest published npm" + @echo "Use 'make install' or 'make link' to install the code" + @echo "in this folder that you're looking at right now." + node cli.js install -g -f npm + +install: all + node cli.js install -g -f + +# backwards compat +dev: install + +link: uninstall + node cli.js link -f + +clean: doc-clean uninstall + rm npmrc + node cli.js cache clean + +uninstall: + node cli.js rm npm -g -f + +doc: $(mandocs) $(htmldocs) + +docclean: doc-clean +doc-clean: + rm -rf \ + node_modules/ronn \ + node_modules/.bin/ronn \ + .building_ronn \ + doc/cli/index.md \ + doc/api/index.md \ + $(api_mandocs) \ + $(cli_mandocs) \ + $(api_htmldocs) \ + $(cli_htmldocs) \ + &>/dev/null || true + +# use `npm install ronn` for this to work. +man/man1/README.1: README.md scripts/doc-build.sh package.json + scripts/doc-build.sh $< $@ + +man/man1/%.1: doc/cli/%.md scripts/doc-build.sh package.json + @[ -d man/man1 ] || mkdir -p man/man1 + scripts/doc-build.sh $< $@ + +man/man3/%.3: doc/api/%.md scripts/doc-build.sh package.json + @[ -d man/man3 ] || mkdir -p man/man3 + scripts/doc-build.sh $< $@ + +html/doc/README.html: README.md html/dochead.html html/docfoot.html scripts/doc-build.sh package.json + scripts/doc-build.sh $< $@ + +html/doc/%.html: doc/cli/%.md html/dochead.html html/docfoot.html scripts/doc-build.sh package.json + scripts/doc-build.sh $< $@ + +html/api/%.html: doc/api/%.md html/dochead.html html/docfoot.html scripts/doc-build.sh package.json + scripts/doc-build.sh $< $@ + +doc/cli/index.md: $(markdowns) scripts/index-build.js scripts/doc-build.sh package.json + node scripts/index-build.js > $@ + +node_modules/.bin/ronn: + node cli.js install + +doc: man + +man: $(cli_docs) $(api_docs) + +test: + node cli.js test + +publish: link doc + @git push origin :v$(shell npm -v) || true + @npm unpublish npm@$(shell npm -v) || true + git clean -fd + git push origin --tags &&\ + npm publish &&\ + npm tag npm@$(shell npm -v) $(shell npm -v | awk -F. '{print $$1 "." $$2}') &&\ + make doc-publish &&\ + make zip-publish + +docpublish: doc-publish +doc-publish: doc + rsync -vazu --stats --no-implied-dirs --delete \ + html/doc/ \ + node@npmjs.org:/home/node/npm-www/doc + rsync -vazu --stats --no-implied-dirs --delete \ + html/api/ \ + node@npmjs.org:/home/node/npm-www/api + rsync -vazu --stats --no-implied-dirs --delete \ + html/static/webfonts/ \ + node@npmjs.org:/home/node/npm-www/static/webfonts + rsync -vazu --stats --no-implied-dirs --delete \ + html/static/style.css \ + node@npmjs.org:/home/node/npm-www/static/ + +zip-publish: release + scp release/* node@nodejs.org:dist/npm/ + +release: + @bash scripts/release.sh + +sandwich: + @[ $$(whoami) = "root" ] && (echo "ok"; echo "ham" > sandwich) || echo "make it yourself" && exit 13 + +.PHONY: all latest install dev link doc clean uninstall test man doc-publish doc-clean docclean docpublish release zip-publish diff --git a/node-v0.8.14/deps/npm/README.md b/node-v0.8.14/deps/npm/README.md new file mode 100644 index 0000000..d3e361c --- /dev/null +++ b/node-v0.8.14/deps/npm/README.md @@ -0,0 +1,239 @@ +npm(1) -- node package manager +============================== + +## SYNOPSIS + +This is just enough info to get you up and running. + +Much more info available via `npm help` once it's installed. + +## IMPORTANT + +**You need node v0.6 or higher to run this program.** + +To install an old **and unsupported** version of npm that works on node 0.3 +and prior, clone the git repo and dig through the old tags and branches. + +## Super Easy Install + +npm comes with node now. + +### Windows Computers + +Get the MSI. npm is in it. + +### Apple Macintosh Computers + +Get the pkg. npm is in it. + +### Other Sorts of Unices + +Run `make install`. npm will be installed with node. + +If you want a more fancy pants install (a different version, customized +paths, etc.) then read on. + +## Fancy Install (Unix) + +There's a pretty robust install script at +. You can download that and run it. + +### Slightly Fancier + +You can set any npm configuration params with that script: + +npm_config_prefix=/some/path sh install.sh + +Or, you can run it in uber-debuggery mode: + +npm_debug=1 sh install.sh + +### Even Fancier + +Get the code with git. Use `make` to build the docs and do other stuff. +If you plan on hacking on npm, `make link` is your friend. + +If you've got the npm source code, you can also semi-permanently set +arbitrary config keys using the `./configure --key=val ...`, and then +run npm commands by doing `node cli.js `. (This is helpful +for testing, or running stuff without actually installing npm itself.) + +## Fancy Windows Install + +You can download a zip file from , and unpack it +in the same folder where node.exe lives. + +If that's not fancy enough for you, then you can fetch the code with +git, and mess with it directly. + +## Installing on Cygwin + +No. + +## Permissions when Using npm to Install Other Stuff + +**tl;dr** + +* Use `sudo` for greater safety. Or don't, if you prefer not to. +* npm will downgrade permissions if it's root before running any build + scripts that package authors specified. + +### More details... + +As of version 0.3, it is recommended to run npm as root. +This allows npm to change the user identifier to the `nobody` user prior +to running any package build or test commands. + +If you are not the root user, or if you are on a platform that does not +support uid switching, then npm will not attempt to change the userid. + +If you would like to ensure that npm **always** runs scripts as the +"nobody" user, and have it fail if it cannot downgrade permissions, then +set the following configuration param: + + npm config set unsafe-perm false + +This will prevent running in unsafe mode, even as non-root users. + +## Uninstalling + +So sad to see you go. + + sudo npm uninstall npm -g + +Or, if that fails, + + sudo make uninstall + +## More Severe Uninstalling + +Usually, the above instructions are sufficient. That will remove +npm, but leave behind anything you've installed. + +If you would like to remove all the packages that you have installed, +then you can use the `npm ls` command to find them, and then `npm rm` to +remove them. + +To remove cruft left behind by npm 0.x, you can use the included +`clean-old.sh` script file. You can run it conveniently like this: + + npm explore npm -g -- sh scripts/clean-old.sh + +npm uses two configuration files, one for per-user configs, and another +for global (every-user) configs. You can view them by doing: + + npm config get userconfig # defaults to ~/.npmrc + npm config get globalconfig # defaults to /usr/local/etc/npmrc + +Uninstalling npm does not remove configuration files by default. You +must remove them yourself manually if you want them gone. Note that +this means that future npm installs will not remember the settings that +you have chosen. + +## Using npm Programmatically + +If you would like to use npm programmatically, you can do that. +It's not very well documented, but it *is* rather simple. + +Most of the time, unless you actually want to do all the things that +npm does, you should try using one of npm's dependencies rather than +using npm itself, if possible. + +Eventually, npm will be just a thin cli wrapper around the modules +that it depends on, but for now, there are some things that you must +use npm itself to do. + + var npm = require("npm") + npm.load(myConfigObject, function (er) { + if (er) return handlError(er) + npm.commands.install(["some", "args"], function (er, data) { + if (er) return commandFailed(er) + // command succeeded, and data might have some info + }) + npm.on("log", function (message) { .... }) + }) + +The `load` function takes an object hash of the command-line configs. +The various `npm.commands.` functions take an **array** of +positional argument **strings**. The last argument to any +`npm.commands.` function is a callback. Some commands take other +optional arguments. Read the source. + +You cannot set configs individually for any single npm function at this +time. Since `npm` is a singleton, any call to `npm.config.set` will +change the value for *all* npm commands in that process. + +See `./bin/npm-cli.js` for an example of pulling config values off of the +command line arguments using nopt. You may also want to check out `npm +help config` to learn about all the options you can set there. + +## More Docs + +Check out the [docs](https://npmjs.org/doc/), +especially the [faq](https://npmjs.org/doc/faq.html). + +You can use the `npm help` command to read any of them. + +If you're a developer, and you want to use npm to publish your program, +you should [read this](https://npmjs.org/doc/developers.html) + +## Legal Stuff + +"npm" and "the npm registry" are owned by Isaac Z. Schlueter. All +rights not explicitly granted in the MIT license are reserved. See the +included LICENSE file for more details. + +"Node.js" and "node" are trademarks owned by Joyent, Inc. npm is not +officially part of the Node.js project, and is neither owned by nor +officially affiliated with Joyent, Inc. + +The packages in the npm registry are not part of npm itself, and are the +sole property of their respective maintainers. While every effort is +made to ensure accountability, there is absolutely no guarantee, +warrantee, or assertion made as to the quality, fitness for a specific +purpose, or lack of malice in any given npm package. Modules +published on the npm registry are not affiliated with or endorsed by +Joyent, Inc., Isaac Z. Schlueter, Ryan Dahl, or the Node.js project. + +If you have a complaint about a package in the npm registry, and cannot +resolve it with the package owner, please express your concerns to +Isaac Z. Schlueter at . + +### In plain english + +This is mine; not my employer's, not Node's, not Joyent's, not Ryan +Dahl's. + +If you publish something, it's yours, and you are solely accountable +for it. Not me, not Node, not Joyent, not Ryan Dahl. + +If other people publish something, it's theirs. Not mine, not Node's, +not Joyent's, not Ryan Dahl's. + +Yes, you can publish something evil. It will be removed promptly if +reported, and we'll lose respect for you. But there is no vetting +process for published modules. + +If this concerns you, inspect the source before using packages. + +## BUGS + +When you find issues, please report them: + +* web: + +* email: + + +Be sure to include *all* of the output from the npm command that didn't work +as expected. The `npm-debug.log` file is also helpful to provide. + +You can also look for isaacs in #node.js on irc://irc.freenode.net. He +will no doubt tell you to put the output in a gist or email. + +## SEE ALSO + +* npm(1) +* npm-faq(1) +* npm-help(1) +* npm-index(1) diff --git a/node-v0.8.14/deps/npm/bin/node-gyp-bin/node-gyp b/node-v0.8.14/deps/npm/bin/node-gyp-bin/node-gyp new file mode 100755 index 0000000..345f07a --- /dev/null +++ b/node-v0.8.14/deps/npm/bin/node-gyp-bin/node-gyp @@ -0,0 +1,2 @@ +#!/usr/bin/env sh +node "`dirname "$0"`/../../node_modules/node-gyp/bin/node-gyp.js" "$@" diff --git a/node-v0.8.14/deps/npm/bin/node-gyp-bin/node-gyp.cmd b/node-v0.8.14/deps/npm/bin/node-gyp-bin/node-gyp.cmd new file mode 100755 index 0000000..c2563ea --- /dev/null +++ b/node-v0.8.14/deps/npm/bin/node-gyp-bin/node-gyp.cmd @@ -0,0 +1 @@ +node "%~dp0\..\..\node_modules\node-gyp\bin\node-gyp.js" %* diff --git a/node-v0.8.14/deps/npm/bin/npm b/node-v0.8.14/deps/npm/bin/npm new file mode 100755 index 0000000..07ade35 --- /dev/null +++ b/node-v0.8.14/deps/npm/bin/npm @@ -0,0 +1,13 @@ +#!/bin/sh + +basedir=`dirname "$0"` + +case `uname` in + *CYGWIN*) basedir=`cygpath -w "$basedir"`;; +esac + +if [ -x "$basedir/node.exe" ]; then + "$basedir/node.exe" "$basedir/node_modules/npm/bin/npm-cli.js" "$@" +else + node "$basedir/node_modules/npm/bin/npm-cli.js" "$@" +fi diff --git a/node-v0.8.14/deps/npm/bin/npm-cli.js b/node-v0.8.14/deps/npm/bin/npm-cli.js new file mode 100755 index 0000000..ef88735 --- /dev/null +++ b/node-v0.8.14/deps/npm/bin/npm-cli.js @@ -0,0 +1,86 @@ +#!/usr/bin/env node +;(function () { // wrapper in case we're in module_context mode + +// windows: running "npm blah" in this folder will invoke WSH, not node. +if (typeof WScript !== "undefined") { + WScript.echo("npm does not work when run\n" + +"with the Windows Scripting Host\n\n" + +"'cd' to a different directory,\n" + +"or type 'npm.cmd ',\n" + +"or type 'node npm '.") + WScript.quit(1) + return +} + + +process.title = "npm" + +var log = require("npmlog") +log.pause() // will be unpaused when config is loaded. +log.info("it worked if it ends with", "ok") + +var fs = require("graceful-fs") + , path = require("path") + , npm = require("../lib/npm.js") + , npmconf = require("npmconf") + , errorHandler = require("../lib/utils/error-handler.js") + + , configDefs = npmconf.defs + , shorthands = configDefs.shorthands + , types = configDefs.types + , nopt = require("nopt") + +// if npm is called as "npmg" or "npm_g", then +// run in global mode. +if (path.basename(process.argv[1]).slice(-1) === "g") { + process.argv.splice(1, 1, "npm", "-g") +} + +log.verbose("cli", process.argv) + +var conf = nopt(types, shorthands) +npm.argv = conf.argv.remain +if (npm.deref(npm.argv[0])) npm.command = npm.argv.shift() +else conf.usage = true + + +if (conf.version) { + console.log(npm.version) + return +} + +if (conf.versions) { + npm.command = "version" + conf.usage = false + npm.argv = [] +} + +log.info("using", "npm@%s", npm.version) +log.info("using", "node@%s", process.version) + +// make sure that this version of node works with this version of npm. +var semver = require("semver") + , nodeVer = process.version + , reqVer = npm.nodeVersionRequired +if (reqVer && !semver.satisfies(nodeVer, reqVer)) { + return errorHandler(new Error( + "npm doesn't work with node " + nodeVer + + "\nRequired: node@" + reqVer), true) +} + +process.on("uncaughtException", errorHandler) + +if (conf.usage && npm.command !== "help") { + npm.argv.unshift(npm.command) + npm.command = "help" +} + +// now actually fire up npm and run the command. +// this is how to use npm programmatically: +conf._exit = true +npm.load(conf, function (er) { + if (er) return errorHandler(er) + npm.commands[npm.command](npm.argv, errorHandler) +}) + +})() diff --git a/node-v0.8.14/deps/npm/bin/npm.cmd b/node-v0.8.14/deps/npm/bin/npm.cmd new file mode 100644 index 0000000..7720e20 --- /dev/null +++ b/node-v0.8.14/deps/npm/bin/npm.cmd @@ -0,0 +1,6 @@ +:: Created by npm, please don't edit manually. +@IF EXIST "%~dp0\node.exe" ( + "%~dp0\node.exe" "%~dp0\.\node_modules\npm\bin\npm-cli.js" %* +) ELSE ( + node "%~dp0\.\node_modules\npm\bin\npm-cli.js" %* +) diff --git a/node-v0.8.14/deps/npm/bin/read-package-json.js b/node-v0.8.14/deps/npm/bin/read-package-json.js new file mode 100755 index 0000000..3e5a0c7 --- /dev/null +++ b/node-v0.8.14/deps/npm/bin/read-package-json.js @@ -0,0 +1,22 @@ +var argv = process.argv +if (argv.length < 3) { + console.error("Usage: read-package.json [ ...]") + process.exit(1) +} + +var fs = require("fs") + , file = argv[2] + , readJson = require("read-package-json") + +readJson(file, function (er, data) { + if (er) throw er + if (argv.length === 3) console.log(data) + else argv.slice(3).forEach(function (field) { + field = field.split(".") + var val = data + field.forEach(function (f) { + val = val[f] + }) + console.log(val) + }) +}) diff --git a/node-v0.8.14/deps/npm/cli.js b/node-v0.8.14/deps/npm/cli.js new file mode 100755 index 0000000..0df931e --- /dev/null +++ b/node-v0.8.14/deps/npm/cli.js @@ -0,0 +1,2 @@ +#!/usr/bin/env node +require("./bin/npm-cli.js") diff --git a/node-v0.8.14/deps/npm/configure b/node-v0.8.14/deps/npm/configure new file mode 100755 index 0000000..b13c8d0 --- /dev/null +++ b/node-v0.8.14/deps/npm/configure @@ -0,0 +1,33 @@ +#!/bin/bash + +# set configurations that will be "sticky" on this system, +# surviving npm self-updates. + +CONFIGS=() +i=0 + +# get the location of this file. +unset CDPATH +CONFFILE=$(cd $(dirname "$0"); pwd -P)/npmrc + +while [ $# -gt 0 ]; do + conf="$1" + case $conf in + --help) + echo "./configure --param=value ..." + exit 0 + ;; + --*) + CONFIGS[$i]="${conf:2}" + ;; + *) + CONFIGS[$i]="$conf" + ;; + esac + let i++ + shift +done + +for c in "${CONFIGS[@]}"; do + echo "$c" >> "$CONFFILE" +done diff --git a/node-v0.8.14/deps/npm/doc/api/bin.md b/node-v0.8.14/deps/npm/doc/api/bin.md new file mode 100644 index 0000000..f3dc482 --- /dev/null +++ b/node-v0.8.14/deps/npm/doc/api/bin.md @@ -0,0 +1,13 @@ +npm-bin(3) -- Display npm bin folder +==================================== + +## SYNOPSIS + + npm.commands.bin(args, cb) + +## DESCRIPTION + +Print the folder where npm will install executables. + +This function should not be used programmatically. Instead, just refer +to the `npm.bin` member. diff --git a/node-v0.8.14/deps/npm/doc/api/bugs.md b/node-v0.8.14/deps/npm/doc/api/bugs.md new file mode 100644 index 0000000..cc4db8f --- /dev/null +++ b/node-v0.8.14/deps/npm/doc/api/bugs.md @@ -0,0 +1,19 @@ +npm-bugs(3) -- Bugs for a package in a web browser maybe +======================================================== + +## SYNOPSIS + + npm.commands.bugs(package, callback) + +## DESCRIPTION + +This command tries to guess at the likely location of a package's +bug tracker URL, and then tries to open it using the `--browser` +config param. + +Like other commands, the first parameter is an array. This command only +uses the first element, which is expected to be a package name with an +optional version number. + +This command will launch a browser, so this command may not be the most +friendly for programmatic use. diff --git a/node-v0.8.14/deps/npm/doc/api/commands.md b/node-v0.8.14/deps/npm/doc/api/commands.md new file mode 100644 index 0000000..eb75456 --- /dev/null +++ b/node-v0.8.14/deps/npm/doc/api/commands.md @@ -0,0 +1,22 @@ +npm-commands(3) -- npm commands +=============================== + +## SYNOPSIS + + npm.commands[](args, callback) + +## DESCRIPTION + +npm comes with a full set of commands, and each of the commands takes a +similar set of arguments. + +In general, all commands on the command object take an **array** of positional +argument **strings**. The last argument to any function is a callback. Some +commands are special and take other optional arguments. + +All commands have their own man page. See `man npm-` for command-line +usage, or `man 3 npm-` for programmatic usage. + +## SEE ALSO + +* npm-index(1) diff --git a/node-v0.8.14/deps/npm/doc/api/config.md b/node-v0.8.14/deps/npm/doc/api/config.md new file mode 100644 index 0000000..7ae2274 --- /dev/null +++ b/node-v0.8.14/deps/npm/doc/api/config.md @@ -0,0 +1,45 @@ +npm-config(3) -- Manage the npm configuration files +=================================================== + +## SYNOPSIS + + npm.commands.config(args, callback) + var val = npm.config.get(key) + npm.config.set(key, val) + +## DESCRIPTION + +This function acts much the same way as the command-line version. The first +element in the array tells config what to do. Possible values are: + +* `set` + + Sets a config parameter. The second element in `args` is interpreted as the + key, and the third element is interpreted as the value. + +* `get` + + Gets the value of a config parameter. The second element in `args` is the + key to get the value of. + +* `delete` (`rm` or `del`) + + Deletes a parameter from the config. The second element in `args` is the + key to delete. + +* `list` (`ls`) + + Show all configs that aren't secret. No parameters necessary. + +* `edit`: + + Opens the config file in the default editor. This command isn't very useful + programmatically, but it is made available. + +To programmatically access npm configuration settings, or set them for +the duration of a program, use the `npm.config.set` and `npm.config.get` +functions instead. + +## SEE ALSO + +* npm(3) diff --git a/node-v0.8.14/deps/npm/doc/api/deprecate.md b/node-v0.8.14/deps/npm/doc/api/deprecate.md new file mode 100644 index 0000000..ac94fd7 --- /dev/null +++ b/node-v0.8.14/deps/npm/doc/api/deprecate.md @@ -0,0 +1,32 @@ +npm-deprecate(3) -- Deprecate a version of a package +==================================================== + +## SYNOPSIS + + npm.commands.deprecate(args, callback) + +## DESCRIPTION + +This command will update the npm registry entry for a package, providing +a deprecation warning to all who attempt to install it. + +The 'args' parameter must have exactly two elements: + +* `package[@version]` + + The `version` portion is optional, and may be either a range, or a + specific version, or a tag. + +* `message` + + The warning message that will be printed whenever a user attempts to + install the package. + +Note that you must be the package owner to deprecate something. See the +`owner` and `adduser` help topics. + +## SEE ALSO + +* npm-publish(3) +* npm-unpublish(3) +* npm-registry(1) diff --git a/node-v0.8.14/deps/npm/doc/api/docs.md b/node-v0.8.14/deps/npm/doc/api/docs.md new file mode 100644 index 0000000..2c5fc5e --- /dev/null +++ b/node-v0.8.14/deps/npm/doc/api/docs.md @@ -0,0 +1,19 @@ +npm-docs(3) -- Docs for a package in a web browser maybe +======================================================== + +## SYNOPSIS + + npm.commands.docs(package, callback) + +## DESCRIPTION + +This command tries to guess at the likely location of a package's +documentation URL, and then tries to open it using the `--browser` +config param. + +Like other commands, the first parameter is an array. This command only +uses the first element, which is expected to be a package name with an +optional version number. + +This command will launch a browser, so this command may not be the most +friendly for programmatic use. diff --git a/node-v0.8.14/deps/npm/doc/api/edit.md b/node-v0.8.14/deps/npm/doc/api/edit.md new file mode 100644 index 0000000..b13fbb8 --- /dev/null +++ b/node-v0.8.14/deps/npm/doc/api/edit.md @@ -0,0 +1,24 @@ +npm-edit(3) -- Edit an installed package +======================================== + +## SYNOPSIS + + npm.commands.edit(package, callback) + +## DESCRIPTION + +Opens the package folder in the default editor (or whatever you've +configured as the npm `editor` config -- see `npm help config`.) + +After it has been edited, the package is rebuilt so as to pick up any +changes in compiled packages. + +For instance, you can do `npm install connect` to install connect +into your package, and then `npm.commands.edit(["connect"], callback)` +to make a few changes to your locally installed copy. + +The first parameter is a string array with a single element, the package +to open. The package can optionally have a version number attached. + +Since this command opens an editor in a new process, be careful about where +and how this is used. diff --git a/node-v0.8.14/deps/npm/doc/api/explore.md b/node-v0.8.14/deps/npm/doc/api/explore.md new file mode 100644 index 0000000..a239f3d --- /dev/null +++ b/node-v0.8.14/deps/npm/doc/api/explore.md @@ -0,0 +1,18 @@ +npm-explore(3) -- Browse an installed package +============================================= + +## SYNOPSIS + + npm.commands.explore(args, callback) + +## DESCRIPTION + +Spawn a subshell in the directory of the installed package specified. + +If a command is specified, then it is run in the subshell, which then +immediately terminates. + +Note that the package is *not* automatically rebuilt afterwards, so be +sure to use `npm rebuild ` if you make any changes. + +The first element in the 'args' parameter must be a package name. After that is the optional command, which can be any number of strings. All of the strings will be combined into one, space-delimited command. diff --git a/node-v0.8.14/deps/npm/doc/api/help-search.md b/node-v0.8.14/deps/npm/doc/api/help-search.md new file mode 100644 index 0000000..5c00cfc --- /dev/null +++ b/node-v0.8.14/deps/npm/doc/api/help-search.md @@ -0,0 +1,30 @@ +npm-help-search(3) -- Search the help pages +=========================================== + +## SYNOPSIS + + npm.commands.helpSearch(args, [silent,] callback) + +## DESCRIPTION + +This command is rarely useful, but it exists in the rare case that it is. + +This command takes an array of search terms and returns the help pages that +match in order of best match. + +If there is only one match, then npm displays that help section. If there +are multiple results, the results are printed to the screen formatted and the +array of results is returned. Each result is an object with these properties: + +* hits: + A map of args to number of hits on that arg. For example, {"npm": 3} +* found: + Total number of unique args that matched. +* totalHits: + Total number of hits. +* lines: + An array of all matching lines (and some adjacent lines). +* file: + Name of the file that matched + +The silent parameter is not neccessary not used, but it may in the future. diff --git a/node-v0.8.14/deps/npm/doc/api/init.md b/node-v0.8.14/deps/npm/doc/api/init.md new file mode 100644 index 0000000..5afc11b --- /dev/null +++ b/node-v0.8.14/deps/npm/doc/api/init.md @@ -0,0 +1,29 @@ +npm init(3) -- Interactively create a package.json file +======================================================= + +## SYNOPSIS + + npm.commands.init(args, callback) + +## DESCRIPTION + +This will ask you a bunch of questions, and then write a package.json for you. + +It attempts to make reasonable guesses about what you want things to be set to, +and then writes a package.json file with the options you've selected. + +If you already have a package.json file, it'll read that first, and default to +the options in there. + +It is strictly additive, so it does not delete options from your package.json +without a really good reason to do so. + +Since this function expects to be run on the command-line, it doesn't work very +well as a programmatically. The best option is to roll your own, and since +JavaScript makes it stupid simple to output formatted JSON, that is the +preferred method. If you're sure you want to handle command-line prompting, +then go ahead and use this programmatically. + +## SEE ALSO + +npm-json(1) diff --git a/node-v0.8.14/deps/npm/doc/api/install.md b/node-v0.8.14/deps/npm/doc/api/install.md new file mode 100644 index 0000000..12f665a --- /dev/null +++ b/node-v0.8.14/deps/npm/doc/api/install.md @@ -0,0 +1,19 @@ +npm-install(3) -- install a package programmatically +==================================================== + +## SYNOPSIS + + npm.commands.install([where,] packages, callback) + +## DESCRIPTION + +This acts much the same ways as installing on the command-line. + +The 'where' parameter is optional and only used internally, and it specifies +where the packages should be installed to. + +The 'packages' parameter is an array of strings. Each element in the array is +the name of a package to be installed. + +Finally, 'callback' is a function that will be called when all packages have been +installed or when an error has been encountered. diff --git a/node-v0.8.14/deps/npm/doc/api/link.md b/node-v0.8.14/deps/npm/doc/api/link.md new file mode 100644 index 0000000..ad8cefc --- /dev/null +++ b/node-v0.8.14/deps/npm/doc/api/link.md @@ -0,0 +1,33 @@ +npm-link(3) -- Symlink a package folder +======================================= + +## SYNOPSIS + + npm.command.link(callback) + npm.command.link(packages, callback) + +## DESCRIPTION + +Package linking is a two-step process. + +Without parameters, link will create a globally-installed +symbolic link from `prefix/package-name` to the current folder. + +With a parameters, link will create a symlink from the local `node_modules` +folder to the global symlink. + +When creating tarballs for `npm publish`, the linked packages are +"snapshotted" to their current state by resolving the symbolic links. + +This is +handy for installing your own stuff, so that you can work on it and test it +iteratively without having to continually rebuild. + +For example: + + npm.commands.link(cb) # creates global link from the cwd + # (say redis package) + npm.commands.link('redis', cb) # link-install the package + +Now, any changes to the redis package will be reflected in +the package in the current working directory diff --git a/node-v0.8.14/deps/npm/doc/api/load.md b/node-v0.8.14/deps/npm/doc/api/load.md new file mode 100644 index 0000000..a95a6b2 --- /dev/null +++ b/node-v0.8.14/deps/npm/doc/api/load.md @@ -0,0 +1,26 @@ +npm-load(3) -- Load config settings +=================================== + +## SYNOPSIS + + npm.load(conf, cb) + +## DESCRIPTION + +npm.load() must be called before any other function call. Both parameters are +optional, but the second is recommended. + +The first parameter is an object hash of command-line config params, and the +second parameter is a callback that will be called when npm is loaded and +ready to serve. + +The first parameter should follow a similar structure as the package.json +config object. + +For example, to emulate the --dev flag, pass an object that looks like this: + + { + "dev": true + } + +For a list of all the available command-line configs, see `npm help config` diff --git a/node-v0.8.14/deps/npm/doc/api/ls.md b/node-v0.8.14/deps/npm/doc/api/ls.md new file mode 100644 index 0000000..ed890ff --- /dev/null +++ b/node-v0.8.14/deps/npm/doc/api/ls.md @@ -0,0 +1,56 @@ +npm-ls(3) -- List installed packages +====================================== + +## SYNOPSIS + + npm.commands.ls(args, [silent,] callback) + +## DESCRIPTION + +This command will print to stdout all the versions of packages that are +installed, as well as their dependencies, in a tree-structure. It will also +return that data using the callback. + +This command does not take any arguments, but args must be defined. +Beyond that, if any arguments are passed in, npm will politely warn that it +does not take positional arguments, though you may set config flags +like with any other command, such as `global` to list global packages. + +It will print out extraneous, missing, and invalid packages. + +If the silent parameter is set to true, nothing will be output to the screen, +but the data will still be returned. + +Callback is provided an error if one occurred, the full data about which +packages are installed and which dependencies they will receive, and a +"lite" data object which just shows which versions are installed where. +Note that the full data object is a circular structure, so care must be +taken if it is serialized to JSON. + +## CONFIGURATION + +### long + +* Default: false +* Type: Boolean + +Show extended information. + +### parseable + +* Default: false +* Type: Boolean + +Show parseable output instead of tree view. + +### global + +* Default: false +* Type: Boolean + +List packages in the global install prefix instead of in the current +project. + +Note, if parseable is set or long isn't set, then duplicates will be trimmed. +This means that if a submodule a same dependency as a parent module, then the +dependency will only be output once. diff --git a/node-v0.8.14/deps/npm/doc/api/npm.md b/node-v0.8.14/deps/npm/doc/api/npm.md new file mode 100644 index 0000000..a2f034c --- /dev/null +++ b/node-v0.8.14/deps/npm/doc/api/npm.md @@ -0,0 +1,115 @@ +npm(3) -- node package manager +============================== + +## SYNOPSIS + + var npm = require("npm") + npm.load(configObject, function (er, npm) { + // use the npm object, now that it's loaded. + + npm.config.set(key, val) + val = npm.config.get(key) + + console.log("prefix = %s", npm.prefix) + + npm.commands.install(["package"], cb) + }) + +## VERSION + +@VERSION@ + +## DESCRIPTION + +This is the API documentation for npm. +To find documentation of the command line +client, see `npm(1)`. + +Prior to using npm's commands, +`npm.load()` must be called with an object hash of +top-level configs. In the npm command line client, +this set of configs is parsed from the command line options. Additional +configuration params are loaded from two configuration files. See +`npm-config(1)` for more information. + +After that, each of the functions are accessible in the +commands object: `npm.commands.`. See `npm-index(1)` for a list of +all possible commands. + +All commands on the command object take an **array** of positional argument +**strings**. The last argument to any function is a callback. Some +commands take other optional arguments. + +Configs cannot currently be set on a per function basis, as each call to +npm.config.set will change the value for *all* npm commands in that process. + +To find API documentation for a specific command, run the `npm apihelp` +command. + +## METHODS AND PROPERTIES + +* `npm.load(configs, cb)` + + Load the configuration params, and call the `cb` function once the + globalconfig and userconfig files have been loaded as well, or on + nextTick if they've already been loaded. + +* `npm.config` + + An object for accessing npm configuration parameters. + + * `npm.config.get(key)` + * `npm.config.set(key, val)` + * `npm.config.del(key)` + +* `npm.dir` or `npm.root` + + The `node_modules` directory where npm will operate. + +* `npm.prefix` + + The prefix where npm is operating. (Most often the current working + directory.) + +* `npm.cache` + + The place where npm keeps JSON and tarballs it fetches from the + registry (or uploads to the registry). + +* `npm.tmp` + + npm's temporary working directory. + +* `npm.deref` + + Get the "real" name for a command that has either an alias or + abbreviation. + +## MAGIC + +For each of the methods in the `npm.commands` hash, a method is added to +the npm object, which takes a set of positional string arguments rather +than an array and a callback. + +If the last argument is a callback, then it will use the supplied +callback. However, if no callback is provided, then it will print out +the error or results. + +For example, this would work in a node repl: + + > npm = require("npm") + > npm.load() // wait a sec... + > npm.install("dnode", "express") + +Note that that *won't* work in a node program, since the `install` +method will get called before the configuration load is completed. + +## ABBREVS + +In order to support `npm ins foo` instead of `npm install foo`, the +`npm.commands` object has a set of abbreviations as well as the full +method names. Use the `npm.deref` method to find the real name. + +For example: + + var cmd = npm.deref("unp") // cmd === "unpublish" diff --git a/node-v0.8.14/deps/npm/doc/api/outdated.md b/node-v0.8.14/deps/npm/doc/api/outdated.md new file mode 100644 index 0000000..89f4cf6 --- /dev/null +++ b/node-v0.8.14/deps/npm/doc/api/outdated.md @@ -0,0 +1,13 @@ +npm-outdated(3) -- Check for outdated packages +============================================== + +## SYNOPSIS + + npm.commands.outdated([packages,] callback) + +## DESCRIPTION + +This command will check the registry to see if the specified packages are +currently outdated. + +If the 'packages' parameter is left out, npm will check all packages. diff --git a/node-v0.8.14/deps/npm/doc/api/owner.md b/node-v0.8.14/deps/npm/doc/api/owner.md new file mode 100644 index 0000000..de203c0 --- /dev/null +++ b/node-v0.8.14/deps/npm/doc/api/owner.md @@ -0,0 +1,31 @@ +npm-owner(3) -- Manage package owners +===================================== + +## SYNOPSIS + + npm.commands.owner(args, callback) + +## DESCRIPTION + +The first element of the 'args' parameter defines what to do, and the subsequent +elements depend on the action. Possible values for the action are (order of +parameters are given in parenthesis): + +* ls (package): + List all the users who have access to modify a package and push new versions. + Handy when you need to know who to bug for help. +* add (user, package): + Add a new user as a maintainer of a package. This user is enabled to modify + metadata, publish new versions, and add other owners. +* rm (user, package): + Remove a user from the package owner list. This immediately revokes their + privileges. + +Note that there is only one level of access. Either you can modify a package, +or you can't. Future versions may contain more fine-grained access levels, but +that is not implemented at this time. + +## SEE ALSO + +* npm-publish(3) +* npm-registry(1) diff --git a/node-v0.8.14/deps/npm/doc/api/pack.md b/node-v0.8.14/deps/npm/doc/api/pack.md new file mode 100644 index 0000000..cb339c0 --- /dev/null +++ b/node-v0.8.14/deps/npm/doc/api/pack.md @@ -0,0 +1,19 @@ +npm-pack(3) -- Create a tarball from a package +============================================== + +## SYNOPSIS + + npm.commands.pack([packages,] callback) + +## DESCRIPTION + +For anything that's installable (that is, a package folder, tarball, +tarball url, name@tag, name@version, or name), this command will fetch +it to the cache, and then copy the tarball to the current working +directory as `-.tgz`, and then write the filenames out to +stdout. + +If the same package is specified multiple times, then the file will be +overwritten the second time. + +If no arguments are supplied, then npm packs the current package folder. diff --git a/node-v0.8.14/deps/npm/doc/api/prefix.md b/node-v0.8.14/deps/npm/doc/api/prefix.md new file mode 100644 index 0000000..806dd4b --- /dev/null +++ b/node-v0.8.14/deps/npm/doc/api/prefix.md @@ -0,0 +1,15 @@ +npm-prefix(3) -- Display prefix +=============================== + +## SYNOPSIS + + npm.commands.prefix(args, callback) + +## DESCRIPTION + +Print the prefix to standard out. + +'args' is never used and callback is never called with data. +'args' must be present or things will break. + +This function is not useful programmatically diff --git a/node-v0.8.14/deps/npm/doc/api/prune.md b/node-v0.8.14/deps/npm/doc/api/prune.md new file mode 100644 index 0000000..2a4f177 --- /dev/null +++ b/node-v0.8.14/deps/npm/doc/api/prune.md @@ -0,0 +1,17 @@ +npm-prune(3) -- Remove extraneous packages +========================================== + +## SYNOPSIS + + npm.commands.prune([packages,] callback) + +## DESCRIPTION + +This command removes "extraneous" packages. + +The first parameter is optional, and it specifies packages to be removed. + +No packages are specified, then all packages will be checked. + +Extraneous packages are packages that are not listed on the parent +package's dependencies list. diff --git a/node-v0.8.14/deps/npm/doc/api/publish.md b/node-v0.8.14/deps/npm/doc/api/publish.md new file mode 100644 index 0000000..a743303 --- /dev/null +++ b/node-v0.8.14/deps/npm/doc/api/publish.md @@ -0,0 +1,30 @@ +npm-publish(3) -- Publish a package +=================================== + +## SYNOPSIS + + npm.commands.publish([packages,] callback) + +## DESCRIPTION + +Publishes a package to the registry so that it can be installed by name. +Possible values in the 'packages' array are: + +* ``: + A folder containing a package.json file + +* ``: + A url or file path to a gzipped tar archive containing a single folder + with a package.json file inside. + +If the package array is empty, npm will try to publish something in the +current working directory. + +This command could fails if one of the packages specified already exists in +the registry. Overwrites when the "force" environment variable is set. + +## SEE ALSO + +* npm-registry(1) +* npm-adduser(1) +* npm-owner(3) diff --git a/node-v0.8.14/deps/npm/doc/api/rebuild.md b/node-v0.8.14/deps/npm/doc/api/rebuild.md new file mode 100644 index 0000000..8b89898 --- /dev/null +++ b/node-v0.8.14/deps/npm/doc/api/rebuild.md @@ -0,0 +1,16 @@ +npm-rebuild(3) -- Rebuild a package +=================================== + +## SYNOPSIS + + npm.commands.rebuild([packages,] callback) + +## DESCRIPTION + +This command runs the `npm build` command on each of the matched packages. This is useful +when you install a new version of node, and must recompile all your C++ addons with +the new binary. If no 'packages' parameter is specify, every package will be rebuilt. + +## CONFIGURATION + +See `npm help build` diff --git a/node-v0.8.14/deps/npm/doc/api/restart.md b/node-v0.8.14/deps/npm/doc/api/restart.md new file mode 100644 index 0000000..c407044 --- /dev/null +++ b/node-v0.8.14/deps/npm/doc/api/restart.md @@ -0,0 +1,22 @@ +npm-restart(3) -- Start a package +================================= + +## SYNOPSIS + + npm.commands.restart(packages, callback) + +## DESCRIPTION + +This runs a package's "restart" script, if one was provided. +Otherwise it runs package's "stop" script, if one was provided, and then +the "start" script. + +If no version is specified, then it restarts the "active" version. + +npm can run tests on multiple packages. Just specify multiple packages +in the `packages` parameter. + +## SEE ALSO + +* npm-start(3) +* npm-stop(3) diff --git a/node-v0.8.14/deps/npm/doc/api/root.md b/node-v0.8.14/deps/npm/doc/api/root.md new file mode 100644 index 0000000..1c3ab56 --- /dev/null +++ b/node-v0.8.14/deps/npm/doc/api/root.md @@ -0,0 +1,15 @@ +npm-root(3) -- Display npm root +=============================== + +## SYNOPSIS + + npm.commands.root(args, callback) + +## DESCRIPTION + +Print the effective `node_modules` folder to standard out. + +'args' is never used and callback is never called with data. +'args' must be present or things will break. + +This function is not useful programmatically. diff --git a/node-v0.8.14/deps/npm/doc/api/run-script.md b/node-v0.8.14/deps/npm/doc/api/run-script.md new file mode 100644 index 0000000..f15900e --- /dev/null +++ b/node-v0.8.14/deps/npm/doc/api/run-script.md @@ -0,0 +1,27 @@ +npm-run-script(3) -- Run arbitrary package scripts +================================================== + +## SYNOPSIS + + npm.commands.run-script(args, callback) + +## DESCRIPTION + +This runs an arbitrary command from a package's "scripts" object. + +It is used by the test, start, restart, and stop commands, but can be +called directly, as well. + +The 'args' parameter is an array of strings. Behavior depends on the number +of elements. If there is only one element, npm assumes that the element +represents a command to be run on the local repository. If there is more than +one element, then the first is assumed to be the package and the second is +assumed to be the command to run. All other elements are ignored. + +## SEE ALSO + +* npm-scripts(1) +* npm-test(3) +* npm-start(3) +* npm-restart(3) +* npm-stop(3) diff --git a/node-v0.8.14/deps/npm/doc/api/search.md b/node-v0.8.14/deps/npm/doc/api/search.md new file mode 100644 index 0000000..30651d7 --- /dev/null +++ b/node-v0.8.14/deps/npm/doc/api/search.md @@ -0,0 +1,35 @@ +npm-search(3) -- Search for packages +==================================== + +## SYNOPSIS + + npm.commands.search(searchTerms, [silent,] [staleness,] callback) + +## DESCRIPTION + +Search the registry for packages matching the search terms. The available parameters are: + +* searchTerms: + Array of search terms. These terms are case-insensitive. +* silent: + If true, npm will not log anything to the console. +* staleness: + This is the threshold for stale packages. "Fresh" packages are not refreshed + from the registry. This value is measured in seconds. +* callback: + Returns an object where each key is the name of a package, and the value + is information about that package along with a 'words' property, which is + a space-delimited string of all of the interesting words in that package. + The only properties included are those that are searched, which generally include: + + * name + * description + * maintainers + * url + * keywords + +A search on the registry excludes any result that does not match all of the +search terms. It also removes any items from the results that contain an +excluded term (the "searchexclude" config). The search is case insensitive +and doesn't try to read your mind (it doesn't do any verb tense matching or the +like). diff --git a/node-v0.8.14/deps/npm/doc/api/shrinkwrap.md b/node-v0.8.14/deps/npm/doc/api/shrinkwrap.md new file mode 100644 index 0000000..6584d6a --- /dev/null +++ b/node-v0.8.14/deps/npm/doc/api/shrinkwrap.md @@ -0,0 +1,20 @@ +npm-shrinkwrap(3) -- programmatically generate package shrinkwrap file +==================================================== + +## SYNOPSIS + + npm.commands.shrinkwrap(args, [silent,] callback) + +## DESCRIPTION + +This acts much the same ways as shrinkwrapping on the command-line. + +This command does not take any arguments, but 'args' must be defined. +Beyond that, if any arguments are passed in, npm will politely warn that it +does not take positional arguments. + +If the 'silent' parameter is set to true, nothing will be output to the screen, +but the shrinkwrap file will still be written. + +Finally, 'callback' is a function that will be called when the shrinkwrap has +been saved. diff --git a/node-v0.8.14/deps/npm/doc/api/start.md b/node-v0.8.14/deps/npm/doc/api/start.md new file mode 100644 index 0000000..7449114 --- /dev/null +++ b/node-v0.8.14/deps/npm/doc/api/start.md @@ -0,0 +1,13 @@ +npm-start(3) -- Start a package +=============================== + +## SYNOPSIS + + npm.commands.start(packages, callback) + +## DESCRIPTION + +This runs a package's "start" script, if one was provided. + +npm can run tests on multiple packages. Just specify multiple packages +in the `packages` parameter. diff --git a/node-v0.8.14/deps/npm/doc/api/stop.md b/node-v0.8.14/deps/npm/doc/api/stop.md new file mode 100644 index 0000000..0f8333d --- /dev/null +++ b/node-v0.8.14/deps/npm/doc/api/stop.md @@ -0,0 +1,13 @@ +npm-stop(3) -- Stop a package +============================= + +## SYNOPSIS + + npm.commands.stop(packages, callback) + +## DESCRIPTION + +This runs a package's "stop" script, if one was provided. + +npm can run stop on multiple packages. Just specify multiple packages +in the `packages` parameter. diff --git a/node-v0.8.14/deps/npm/doc/api/submodule.md b/node-v0.8.14/deps/npm/doc/api/submodule.md new file mode 100644 index 0000000..2d8bafa --- /dev/null +++ b/node-v0.8.14/deps/npm/doc/api/submodule.md @@ -0,0 +1,28 @@ +npm-submodule(3) -- Add a package as a git submodule +==================================================== + +## SYNOPSIS + + npm.commands.submodule(packages, callback) + +## DESCRIPTION + +For each package specified, npm will check if it has a git repository url +in its package.json description then add it as a git submodule at +`node_modules/`. + +This is a convenience only. From then on, it's up to you to manage +updates by using the appropriate git commands. npm will stubbornly +refuse to update, modify, or remove anything with a `.git` subfolder +in it. + +This command also does not install missing dependencies, if the package +does not include them in its git repository. If `npm ls` reports that +things are missing, you can either install, link, or submodule them yourself, +or you can do `npm explore -- npm install` to install the +dependencies into the submodule folder. + +## SEE ALSO + +* npm help json +* git help submodule diff --git a/node-v0.8.14/deps/npm/doc/api/tag.md b/node-v0.8.14/deps/npm/doc/api/tag.md new file mode 100644 index 0000000..b5a3d7f --- /dev/null +++ b/node-v0.8.14/deps/npm/doc/api/tag.md @@ -0,0 +1,23 @@ +npm-tag(3) -- Tag a published version +===================================== + +## SYNOPSIS + + npm.commands.tag(package@version, tag, callback) + +## DESCRIPTION + +Tags the specified version of the package with the specified tag, or the +`--tag` config if not specified. + +The 'package@version' is an array of strings, but only the first two elements are +currently used. + +The first element must be in the form package@version, where package +is the package name and version is the version number (much like installing a +specific version). + +The second element is the name of the tag to tag this version with. If this +parameter is missing or falsey (empty), the default froom the config will be +used. For more information about how to set this config, check +`man 3 npm-config` for programmatic usage or `man npm-config` for cli usage. diff --git a/node-v0.8.14/deps/npm/doc/api/test.md b/node-v0.8.14/deps/npm/doc/api/test.md new file mode 100644 index 0000000..bc48dcc --- /dev/null +++ b/node-v0.8.14/deps/npm/doc/api/test.md @@ -0,0 +1,16 @@ +npm-test(3) -- Test a package +============================= + +## SYNOPSIS + + npm.commands.test(packages, callback) + +## DESCRIPTION + +This runs a package's "test" script, if one was provided. + +To run tests as a condition of installation, set the `npat` config to +true. + +npm can run tests on multiple packages. Just specify multiple packages +in the `packages` parameter. diff --git a/node-v0.8.14/deps/npm/doc/api/uninstall.md b/node-v0.8.14/deps/npm/doc/api/uninstall.md new file mode 100644 index 0000000..4505295 --- /dev/null +++ b/node-v0.8.14/deps/npm/doc/api/uninstall.md @@ -0,0 +1,16 @@ +npm-uninstall(3) -- uninstall a package programmatically +======================================================== + +## SYNOPSIS + + npm.commands.uninstall(packages, callback) + +## DESCRIPTION + +This acts much the same ways as uninstalling on the command-line. + +The 'packages' parameter is an array of strings. Each element in the array is +the name of a package to be uninstalled. + +Finally, 'callback' is a function that will be called when all packages have been +uninstalled or when an error has been encountered. diff --git a/node-v0.8.14/deps/npm/doc/api/unpublish.md b/node-v0.8.14/deps/npm/doc/api/unpublish.md new file mode 100644 index 0000000..6cbc5c1 --- /dev/null +++ b/node-v0.8.14/deps/npm/doc/api/unpublish.md @@ -0,0 +1,20 @@ +npm-unpublish(3) -- Remove a package from the registry +====================================================== + +## SYNOPSIS + + npm.commands.unpublish(package, callback) + +## DESCRIPTION + +This removes a package version from the registry, deleting its +entry and removing the tarball. + +The package parameter must be defined. + +Only the first element in the package parameter is used. If there is no first +element, then npm assumes that the package at the current working directory +is what is meant. + +If no version is specified, or if all versions are removed then +the root package entry is removed from the registry entirely. diff --git a/node-v0.8.14/deps/npm/doc/api/update.md b/node-v0.8.14/deps/npm/doc/api/update.md new file mode 100644 index 0000000..bf02fd3 --- /dev/null +++ b/node-v0.8.14/deps/npm/doc/api/update.md @@ -0,0 +1,11 @@ +npm-update(3) -- Update a package +================================= + +## SYNOPSIS + npm.commands.update(packages, callback) + +# DESCRIPTION + +Updates a package, upgrading it to the latest version. It also installs any missing packages. + +The 'packages' argument is an array of packages to update. The 'callback' parameter will be called when done or when an error occurs. diff --git a/node-v0.8.14/deps/npm/doc/api/version.md b/node-v0.8.14/deps/npm/doc/api/version.md new file mode 100644 index 0000000..bd40102 --- /dev/null +++ b/node-v0.8.14/deps/npm/doc/api/version.md @@ -0,0 +1,18 @@ +npm-version(3) -- Bump a package version +======================================== + +## SYNOPSIS + + npm.commands.version(newversion, callback) + +## DESCRIPTION + +Run this in a package directory to bump the version and write the new +data back to the package.json file. + +If run in a git repo, it will also create a version commit and tag, and +fail if the repo is not clean. + +Like all other commands, this function takes a string array as its first +parameter. The difference, however, is this function will fail if it does +not have exactly one element. The only element should be a version number. diff --git a/node-v0.8.14/deps/npm/doc/api/view.md b/node-v0.8.14/deps/npm/doc/api/view.md new file mode 100644 index 0000000..fd0076c --- /dev/null +++ b/node-v0.8.14/deps/npm/doc/api/view.md @@ -0,0 +1,93 @@ +npm-view(3) -- View registry info +================================= + +## SYNOPSIS + + npm.commands.view(args, [silent,] callback) + +## DESCRIPTION + +This command shows data about a package and prints it to the stream +referenced by the `outfd` config, which defaults to stdout. + +The "args" parameter is an ordered list that closely resembles the command-line +usage. The elements should be ordered such that the first element is +the package and version (package@version). The version is optional. After that, +the rest of the parameters are fields with optional subfields ("field.subfield") +which can be used to get only the information desired from the registry. + +The callback will be passed all of the data returned by the query. + +For example, to get the package registry entry for the `connect` package, +you can do this: + + npm.commands.view(["connect"], callback) + +If no version is specified, "latest" is assumed. + +Field names can be specified after the package descriptor. +For example, to show the dependencies of the `ronn` package at version +0.3.5, you could do the following: + + npm.commands.view(["ronn@0.3.5", "dependencies"], callback) + +You can view child field by separating them with a period. +To view the git repository URL for the latest version of npm, you could +do this: + + npm.commands.view(["npm", "repository.url"], callback) + +For fields that are arrays, requesting a non-numeric field will return +all of the values from the objects in the list. For example, to get all +the contributor names for the "express" project, you can do this: + + npm.commands.view(["express", "contributors.email"], callback) + +You may also use numeric indices in square braces to specifically select +an item in an array field. To just get the email address of the first +contributor in the list, you can do this: + + npm.commands.view(["express", "contributors[0].email"], callback) + +Multiple fields may be specified, and will be printed one after another. +For exampls, to get all the contributor names and email addresses, you +can do this: + + npm.commands.view(["express", "contributors.name", "contributors.email"], callback) + +"Person" fields are shown as a string if they would be shown as an +object. So, for example, this will show the list of npm contributors in +the shortened string format. (See `npm help json` for more on this.) + + npm.commands.view(["npm", "contributors"], callback) + +If a version range is provided, then data will be printed for every +matching version of the package. This will show which version of jsdom +was required by each matching version of yui3: + + npm.commands.view(["yui3@'>0.5.4'", "dependencies.jsdom"], callback) + +## OUTPUT + +If only a single string field for a single version is output, then it +will not be colorized or quoted, so as to enable piping the output to +another command. + +If the version range matches multiple versions, than each printed value +will be prefixed with the version it applies to. + +If multiple fields are requested, than each of them are prefixed with +the field name. + +Console output can be disabled by setting the 'silent' parameter to true. + +## RETURN VALUE + +The data returned will be an object in this formation: + + { : + { : + , ... } + , ... } + +corresponding to the list of fields selected. diff --git a/node-v0.8.14/deps/npm/doc/api/whoami.md b/node-v0.8.14/deps/npm/doc/api/whoami.md new file mode 100644 index 0000000..598a1ab --- /dev/null +++ b/node-v0.8.14/deps/npm/doc/api/whoami.md @@ -0,0 +1,15 @@ +npm-whoami(3) -- Display npm username +===================================== + +## SYNOPSIS + + npm.commands.whoami(args, callback) + +## DESCRIPTION + +Print the `username` config to standard output. + +'args' is never used and callback is never called with data. +'args' must be present or things will break. + +This function is not useful programmatically diff --git a/node-v0.8.14/deps/npm/doc/cli/adduser.md b/node-v0.8.14/deps/npm/doc/cli/adduser.md new file mode 100644 index 0000000..51aa6f6 --- /dev/null +++ b/node-v0.8.14/deps/npm/doc/cli/adduser.md @@ -0,0 +1,36 @@ +npm-adduser(1) -- Add a registry user account +============================================= + +## SYNOPSIS + + npm adduser + +## DESCRIPTION + +Create or verify a user named `` in the npm registry, and +save the credentials to the `.npmrc` file. + +The username, password, and email are read in from prompts. + +You may use this command to change your email address, but not username +or password. + +To reset your password, go to + +You may use this command multiple times with the same user account to +authorize on a new machine. + +## CONFIGURATION + +### registry + +Default: http://registry.npmjs.org/ + +The base URL of the npm package registry. + +## SEE ALSO + +* npm-registry(1) +* npm-config(1) +* npm-owner(1) +* npm-whoami(1) diff --git a/node-v0.8.14/deps/npm/doc/cli/bin.md b/node-v0.8.14/deps/npm/doc/cli/bin.md new file mode 100644 index 0000000..2c2e7c4 --- /dev/null +++ b/node-v0.8.14/deps/npm/doc/cli/bin.md @@ -0,0 +1,17 @@ +npm-bin(1) -- Display npm bin folder +==================================== + +## SYNOPSIS + + npm bin + +## DESCRIPTION + +Print the folder where npm will install executables. + +## SEE ALSO + +* npm-prefix(1) +* npm-root(1) +* npm-folders(1) +* npm-config(1) diff --git a/node-v0.8.14/deps/npm/doc/cli/bugs.md b/node-v0.8.14/deps/npm/doc/cli/bugs.md new file mode 100644 index 0000000..2e57cc8 --- /dev/null +++ b/node-v0.8.14/deps/npm/doc/cli/bugs.md @@ -0,0 +1,38 @@ +npm-bugs(1) -- Bugs for a package in a web browser maybe +======================================================== + +## SYNOPSIS + + npm bugs + +## DESCRIPTION + +This command tries to guess at the likely location of a package's +bug tracker URL, and then tries to open it using the `--browser` +config param. + +## CONFIGURATION + +### browser + +* Default: OS X: `"open"`, others: `"google-chrome"` +* Type: String + +The browser that is called by the `npm bugs` command to open websites. + +### registry + +* Default: https://registry.npmjs.org/ +* Type: url + +The base URL of the npm package registry. + + +## SEE ALSO + +* npm-docs(1) +* npm-view(1) +* npm-publish(1) +* npm-registry(1) +* npm-config(1) +* npm-json(1) diff --git a/node-v0.8.14/deps/npm/doc/cli/build.md b/node-v0.8.14/deps/npm/doc/cli/build.md new file mode 100644 index 0000000..978f4a6 --- /dev/null +++ b/node-v0.8.14/deps/npm/doc/cli/build.md @@ -0,0 +1,22 @@ +npm-build(1) -- Build a package +=============================== + +## SYNOPSIS + + npm build + +* ``: + A folder containing a `package.json` file in its root. + +## DESCRIPTION + +This is the plumbing command called by `npm link` and `npm install`. + +It should generally not be called directly. + +## SEE ALSO + +* npm-install(1) +* npm-link(1) +* npm-scripts(1) +* npm-json(1) diff --git a/node-v0.8.14/deps/npm/doc/cli/bundle.md b/node-v0.8.14/deps/npm/doc/cli/bundle.md new file mode 100644 index 0000000..69b3d83 --- /dev/null +++ b/node-v0.8.14/deps/npm/doc/cli/bundle.md @@ -0,0 +1,14 @@ +npm-bundle(1) -- REMOVED +======================== + +## DESCRIPTION + +The `npm bundle` command has been removed in 1.0, for the simple reason +that it is no longer necessary, as the default behavior is now to +install packages into the local space. + +Just use `npm install` now to do what `npm bundle` used to do. + +## SEE ALSO + +* npm-install(1) diff --git a/node-v0.8.14/deps/npm/doc/cli/cache.md b/node-v0.8.14/deps/npm/doc/cli/cache.md new file mode 100644 index 0000000..1fa128a --- /dev/null +++ b/node-v0.8.14/deps/npm/doc/cli/cache.md @@ -0,0 +1,70 @@ +npm-cache(1) -- Manipulates packages cache +========================================== + +## SYNOPSIS + + npm cache add + npm cache add + npm cache add + npm cache add @ + + npm cache ls [] + + npm cache clean [] + +## DESCRIPTION + +Used to add, list, or clear the npm cache folder. + +* add: + Add the specified package to the local cache. This command is primarily + intended to be used internally by npm, but it can provide a way to + add data to the local installation cache explicitly. + +* ls: + Show the data in the cache. Argument is a path to show in the cache + folder. Works a bit like the `find` program, but limited by the + `depth` config. + +* clean: + Delete data out of the cache folder. If an argument is provided, then + it specifies a subpath to delete. If no argument is provided, then + the entire cache is cleared. + +## DETAILS + +npm stores cache data in `$HOME/.npm`. For each package that is added +to the cache, three pieces of information are stored in +`{cache}/{name}/{version}`: + +* .../package/: + A folder containing the package contents as they appear in the tarball. +* .../package.json: + The package.json file, as npm sees it, with overlays applied and a _id attribute. +* .../package.tgz: + The tarball for that version. + +Additionally, whenever a registry request is made, a `.cache.json` file +is placed at the corresponding URI, to store the ETag and the requested +data. + +Commands that make non-essential registry requests (such as `search` and +`view`, or the completion scripts) generally specify a minimum timeout. +If the `.cache.json` file is younger than the specified timeout, then +they do not make an HTTP request to the registry. + +## CONFIGURATION + +### cache + +Default: `$HOME/.npm` on Posix, or `$HOME/npm-cache` on Windows. + +The root cache folder. + +## SEE ALSO + +* npm-folders(1) +* npm-config(1) +* npm-install(1) +* npm-publish(1) +* npm-pack(1) diff --git a/node-v0.8.14/deps/npm/doc/cli/changelog.md b/node-v0.8.14/deps/npm/doc/cli/changelog.md new file mode 100644 index 0000000..64feeac --- /dev/null +++ b/node-v0.8.14/deps/npm/doc/cli/changelog.md @@ -0,0 +1,80 @@ +npm-changelog(1) -- Changes +=========================== + +## HISTORY + +### 1.1.3, 1.1.4 + +* Update request to support HTTPS-over-HTTP proxy tunneling +* Throw on undefined envs in config settings +* Update which to 1.0.5 +* Fix windows UNC busyloop in findPrefix +* Bundle nested bundleDependencies properly +* Alias adduser to add-user +* Doc updates (Christian Howe, Henrik Hodne, Andrew Lunny) +* ignore logfd/outfd streams in makeEnv() (Rod Vagg) +* shrinkwrap: Behave properly with url-installed deps +* install: Support --save with url install targets +* Support installing naked tars or single-file modules from urls etc. +* init: Don't add engines section +* Don't run make clean on rebuild +* Added missing unicode replacement (atomizer) + +### 1.1.2 + +Dave Pacheco (2): + add "npm shrinkwrap" + +Martin Cooper (1): + Fix #1753 Make a copy of the cached objects we'll modify. + +Tim Oxley (1): + correctly remove readme from default npm view command. + +Tyler Green (1): + fix #2187 set terminal columns to Infinity if 0 + +isaacs (19): + update minimatch + update request + Experimental: single-file modules + Fix #2172 Don't remove global mans uninstalling local pkgs + Add --versions flag to show the version of node as well + Support --json flag for ls output + update request to 2.9.151 + +### 1.1 +* Replace system tar dependency with a JS tar +* Continue to refine + +### 1.0 +* Greatly simplified folder structure +* Install locally (bundle by default) +* Drastic rearchitecture + +### 0.3 +* More correct permission/uid handling when running as root +* Require node 0.4.0 +* Reduce featureset +* Packages without "main" modules don't export modules +* Remove support for invalid JSON (since node doesn't support it) + +### 0.2 +* First allegedly "stable" release +* Most functionality implemented +* Used shim files and `name@version` symlinks +* Feature explosion +* Kind of a mess + +### 0.1 +* push to beta, and announce +* Solaris and Cygwin support + +### 0.0 +* Lots of sketches and false starts; abandoned a few times +* Core functionality established + +## SEE ALSO + +* npm(1) +* npm-faq(1) diff --git a/node-v0.8.14/deps/npm/doc/cli/coding-style.md b/node-v0.8.14/deps/npm/doc/cli/coding-style.md new file mode 100644 index 0000000..c505dba --- /dev/null +++ b/node-v0.8.14/deps/npm/doc/cli/coding-style.md @@ -0,0 +1,179 @@ +npm-coding-style(1) -- npm's "funny" coding style +================================================= + +## DESCRIPTION + +npm's coding style is a bit unconventional. It is not different for +difference's sake, but rather a carefully crafted style that is +designed to reduce visual clutter and make bugs more apparent. + +If you want to contribute to npm (which is very encouraged), you should +make your code conform to npm's style. + +## Line Length + +Keep lines shorter than 80 characters. It's better for lines to be +too short than to be too long. Break up long lists, objects, and other +statements onto multiple lines. + +## Indentation + +Two-spaces. Tabs are better, but they look like hell in web browsers +(and on github), and node uses 2 spaces, so that's that. + +Configure your editor appropriately. + +## Curly braces + +Curly braces belong on the same line as the thing that necessitates them. + +Bad: + + function () + { + +Good: + + function () { + +If a block needs to wrap to the next line, use a curly brace. Don't +use it if it doesn't. + +Bad: + + if (foo) { bar() } + while (foo) + bar() + +Good: + + if (foo) bar() + while (foo) { + bar() + } + +## Semicolons + +Don't use them except in four situations: + +* `for (;;)` loops. They're actually required. +* null loops like: `while (something) ;` (But you'd better have a good + reason for doing that.) +* `case "foo": doSomething(); break` +* In front of a leading `(` or `[` at the start of the line. + This prevents the expression from being interpreted + as a function call or property access, respectively. + +Some examples of good semicolon usage: + + ;(x || y).doSomething() + ;[a, b, c].forEach(doSomething) + for (var i = 0; i < 10; i ++) { + switch (state) { + case "begin": start(); continue + case "end": finish(); break + default: throw new Error("unknown state") + } + end() + } + +Note that starting lines with `-` and `+` also should be prefixed +with a semicolon, but this is much less common. + +## Comma First + +If there is a list of things separated by commas, and it wraps +across multiple lines, put the comma at the start of the next +line, directly below the token that starts the list. Put the +final token in the list on a line by itself. For example: + + var magicWords = [ "abracadabra" + , "gesundheit" + , "ventrilo" + ] + , spells = { "fireball" : function () { setOnFire() } + , "water" : function () { putOut() } + } + , a = 1 + , b = "abc" + , etc + , somethingElse + +## Whitespace + +Put a single space in front of ( for anything other than a function call. +Also use a single space wherever it makes things more readable. + +Don't leave trailing whitespace at the end of lines. Don't indent empty +lines. Don't use more spaces than are helpful. + +## Functions + +Use named functions. They make stack traces a lot easier to read. + +## Callbacks, Sync/async Style + +Use the asynchronous/non-blocking versions of things as much as possible. +It might make more sense for npm to use the synchronous fs APIs, but this +way, the fs and http and child process stuff all uses the same callback-passing +methodology. + +The callback should always be the last argument in the list. Its first +argument is the Error or null. + +Be very careful never to ever ever throw anything. It's worse than useless. +Just send the error message back as the first argument to the callback. + +## Errors + +Always create a new Error object with your message. Don't just return a +string message to the callback. Stack traces are handy. + +## Logging + +Logging is done using the [npmlog](https://github.com/isaacs/npmlog) +utility. + +Please clean up logs when they are no longer helpful. In particular, +logging the same object over and over again is not helpful. Logs should +report what's happening so that it's easier to track down where a fault +occurs. + +Use appropriate log levels. See `npm-config(1)` and search for +"loglevel". + +## Case, naming, etc. + +Use `lowerCamelCase` for multiword identifiers when they refer to objects, +functions, methods, members, or anything not specified in this section. + +Use `UpperCamelCase` for class names (things that you'd pass to "new"). + +Use `all-lower-hyphen-css-case` for multiword filenames and config keys. + +Use named functions. They make stack traces easier to follow. + +Use `CAPS_SNAKE_CASE` for constants, things that should never change +and are rarely used. + +Use a single uppercase letter for function names where the function +would normally be anonymous, but needs to call itself recursively. It +makes it clear that it's a "throwaway" function. + +## null, undefined, false, 0 + +Boolean variables and functions should always be either `true` or +`false`. Don't set it to 0 unless it's supposed to be a number. + +When something is intentionally missing or removed, set it to `null`. + +Don't set things to `undefined`. Reserve that value to mean "not yet +set to anything." + +Boolean objects are verboten. + +## SEE ALSO + +* npm-developers(1) +* npm-faq(1) +* npm(1) diff --git a/node-v0.8.14/deps/npm/doc/cli/completion.md b/node-v0.8.14/deps/npm/doc/cli/completion.md new file mode 100644 index 0000000..48bc50f --- /dev/null +++ b/node-v0.8.14/deps/npm/doc/cli/completion.md @@ -0,0 +1,29 @@ +npm-completion(1) -- Tab Completion for npm +=========================================== + +## SYNOPSIS + + . <(npm completion) + +## DESCRIPTION + +Enables tab-completion in all npm commands. + +The synopsis above +loads the completions into your current shell. Adding it to +your ~/.bashrc or ~/.zshrc will make the completions available +everywhere. + +You may of course also pipe the output of npm completion to a file +such as `/usr/local/etc/bash_completion.d/npm` if you have a system +that will read that file for you. + +When `COMP_CWORD`, `COMP_LINE`, and `COMP_POINT` are defined in the +environment, `npm completion` acts in "plumbing mode", and outputs +completions based on the arguments. + +## SEE ALSO + +* npm-developers(1) +* npm-faq(1) +* npm(1) diff --git a/node-v0.8.14/deps/npm/doc/cli/config.md b/node-v0.8.14/deps/npm/doc/cli/config.md new file mode 100644 index 0000000..9f051a0 --- /dev/null +++ b/node-v0.8.14/deps/npm/doc/cli/config.md @@ -0,0 +1,858 @@ +npm-config(1) -- Manage the npm configuration file +================================================== + +## SYNOPSIS + + npm config set [--global] + npm config get + npm config delete + npm config list + npm config edit + npm get + npm set [--global] + +## DESCRIPTION + +npm gets its configuration values from 6 sources, in this priority: + +### Command Line Flags + +Putting `--foo bar` on the command line sets the +`foo` configuration parameter to `"bar"`. A `--` argument tells the cli +parser to stop reading flags. A `--flag` parameter that is at the *end* of +the command will be given the value of `true`. + +### Environment Variables + +Any environment variables that start with `npm_config_` will be interpreted +as a configuration parameter. For example, putting `npm_config_foo=bar` in +your environment will set the `foo` configuration parameter to `bar`. Any +environment configurations that are not given a value will be given the value +of `true`. Config values are case-insensitive, so `NPM_CONFIG_FOO=bar` will +work the same. + +### Per-user config file + +`$HOME/.npmrc` (or the `userconfig` param, if set above) + +This file is an ini-file formatted list of `key = value` parameters. + +### Global config file + +`$PREFIX/etc/npmrc` (or the `globalconfig` param, if set above): +This file is an ini-file formatted list of `key = value` parameters + +### Built-in config file + +`path/to/npm/itself/npmrc` + +This is an unchangeable "builtin" +configuration file that npm keeps consistent across updates. Set +fields in here using the `./configure` script that comes with npm. +This is primarily for distribution maintainers to override default +configs in a standard and consistent manner. + +### Default Configs + +A set of configuration parameters that are internal to npm, and are +defaults if nothing else is specified. + +## Sub-commands + +Config supports the following sub-commands: + +### set + + npm config set key value + +Sets the config key to the value. + +If value is omitted, then it sets it to "true". + +### get + + npm config get key + +Echo the config value to stdout. + +### list + + npm config list + +Show all the config settings. + +### delete + + npm config delete key + +Deletes the key from all configuration files. + +### edit + + npm config edit + +Opens the config file in an editor. Use the `--global` flag to edit the +global config. + +## Shorthands and Other CLI Niceties + +The following shorthands are parsed on the command-line: + +* `-v`: `--version` +* `-h`, `-?`, `--help`, `-H`: `--usage` +* `-s`, `--silent`: `--loglevel silent` +* `-q`, `--quiet`: `--loglevel warn` +* `-d`: `--loglevel info` +* `-dd`, `--verbose`: `--loglevel verbose` +* `-ddd`: `--loglevel silly` +* `-g`: `--global` +* `-l`: `--long` +* `-m`: `--message` +* `-p`, `--porcelain`: `--parseable` +* `-reg`: `--registry` +* `-v`: `--version` +* `-f`: `--force` +* `-desc`: `--description` +* `-S`: `--save` +* `-D`: `--save-dev` +* `-O`: `--save-optional` +* `-B`: `--save-bundle` +* `-y`: `--yes` +* `-n`: `--yes false` +* `ll` and `la` commands: `ls --long` + +If the specified configuration param resolves unambiguously to a known +configuration parameter, then it is expanded to that configuration +parameter. For example: + + npm ls --par + # same as: + npm ls --parseable + +If multiple single-character shorthands are strung together, and the +resulting combination is unambiguously not some other configuration +param, then it is expanded to its various component pieces. For +example: + + npm ls -gpld + # same as: + npm ls --global --parseable --long --loglevel info + +## Per-Package Config Settings + +When running scripts (see `npm-scripts(1)`) +the package.json "config" keys are overwritten in the environment if +there is a config param of `[@]:`. For example, if +the package.json has this: + + { "name" : "foo" + , "config" : { "port" : "8080" } + , "scripts" : { "start" : "node server.js" } } + +and the server.js is this: + + http.createServer(...).listen(process.env.npm_package_config_port) + +then the user could change the behavior by doing: + + npm config set foo:port 80 + +## Config Settings + +### always-auth + +* Default: false +* Type: Boolean + +Force npm to always require authentication when accessing the registry, +even for `GET` requests. + +### browser + +* Default: OS X: `"open"`, others: `"google-chrome"` +* Type: String + +The browser that is called by the `npm docs` command to open websites. + +### ca + +* Default: The npm CA certificate +* Type: String or null + +The Certificate Authority signing certificate that is trusted for SSL +connections to the registry. + +Set to `null` to only allow "known" registrars, or to a specific CA cert +to trust only that specific signing authority. + +See also the `strict-ssl` config. + +### cache + +* Default: Windows: `%APPDATA%\npm-cache`, Posix: `~/.npm` +* Type: path + +The location of npm's cache directory. See `npm-cache(1)` + +### cache-lock-stale + +* Default: 60000 (1 minute) +* Type: Number + +The number of ms before cache folder lockfiles are considered stale. + +### cache-lock-retries + +* Default: 10 +* Type: Number + +Number of times to retry to acquire a lock on cache folder lockfiles. + +### cache-lock-wait + +* Default: 10000 (10 seconds) +* Type: Number + +Number of ms to wait for cache lock files to expire. + +### cache-max + +* Default: Infinity +* Type: Number + +The maximum time (in seconds) to keep items in the registry cache before +re-checking against the registry. + +Note that no purging is done unless the `npm cache clean` command is +explicitly used, and that only GET requests use the cache. + +### cache-min + +* Default: 0 +* Type: Number + +The minimum time (in seconds) to keep items in the registry cache before +re-checking against the registry. + +Note that no purging is done unless the `npm cache clean` command is +explicitly used, and that only GET requests use the cache. + +### color + +* Default: true on Posix, false on Windows +* Type: Boolean or `"always"` + +If false, never shows colors. If `"always"` then always shows colors. +If true, then only prints color codes for tty file descriptors. + +### coverage + +* Default: false +* Type: Boolean + +A flag to tell test-harness to run with their coverage options enabled, +if they respond to the `npm_config_coverage` environment variable. + +### depth + +* Default: Infinity +* Type: Number + +The depth to go when recursing directories for `npm ls` and +`npm cache ls`. + +### description + +* Default: true +* Type: Boolean + +Show the description in `npm search` + +### dev + +* Default: false +* Type: Boolean + +Install `dev-dependencies` along with packages. + +Note that `dev-dependencies` are also installed if the `npat` flag is +set. + +### editor + +* Default: `EDITOR` environment variable if set, or `"vi"` on Posix, + or `"notepad"` on Windows. +* Type: path + +The command to run for `npm edit` or `npm config edit`. + +### engine-strict + +* Default: false +* Type: Boolean + +If set to true, then npm will stubbornly refuse to install (or even +consider installing) any package that claims to not be compatible with +the current Node.js version. + +### force + +* Default: false +* Type: Boolean + +Makes various commands more forceful. + +* lifecycle script failure does not block progress. +* publishing clobbers previously published versions. +* skips cache when requesting from the registry. +* prevents checks against clobbering non-npm files. + +### fetch-retries + +* Default: 2 +* Type: Number + +The "retries" config for the `retry` module to use when fetching +packages from the registry. + +### fetch-retry-factor + +* Default: 10 +* Type: Number + +The "factor" config for the `retry` module to use when fetching +packages. + +### fetch-retry-mintimeout + +* Default: 10000 (10 seconds) +* Type: Number + +The "minTimeout" config for the `retry` module to use when fetching +packages. + +### fetch-retry-maxtimeout + +* Default: 60000 (1 minute) +* Type: Number + +The "maxTimeout" config for the `retry` module to use when fetching +packages. + +### git + +* Default: `"git"` +* Type: String + +The command to use for git commands. If git is installed on the +computer, but is not in the `PATH`, then set this to the full path to +the git binary. + +### global + +* Default: false +* Type: Boolean + +Operates in "global" mode, so that packages are installed into the +`prefix` folder instead of the current working directory. See +`npm-folders(1)` for more on the differences in behavior. + +* packages are installed into the `prefix/node_modules` folder, instead of the + current working directory. +* bin files are linked to `prefix/bin` +* man pages are linked to `prefix/share/man` + +### globalconfig + +* Default: {prefix}/etc/npmrc +* Type: path + +The config file to read for global config options. + +### globalignorefile + +* Default: {prefix}/etc/npmignore +* Type: path + +The config file to read for global ignore patterns to apply to all users +and all projects. + +If not found, but there is a "gitignore" file in the +same directory, then that will be used instead. + +### group + +* Default: GID of the current process +* Type: String or Number + +The group to use when running package scripts in global mode as the root +user. + +### https-proxy + +* Default: the `HTTPS_PROXY` or `https_proxy` or `HTTP_PROXY` or + `http_proxy` environment variables. +* Type: url + +A proxy to use for outgoing https requests. + +### user-agent + +* Default: npm/{npm.version} node/{process.version} +* Type: String + +Sets a User-Agent to the request header + +### ignore + +* Default: "" +* Type: string + +A white-space separated list of glob patterns of files to always exclude +from packages when building tarballs. + +### init-module + +* Default: ~/.npm-init.js +* Type: path + +A module that will be loaded by the `npm init` command. See the +documentation for the +[init-package-json](https://github.com/isaacs/init-package-json) module +for more information, or npm-init(1). + +### init.version + +* Default: "0.0.0" +* Type: semver + +The value `npm init` should use by default for the package version. + +### init.author.name + +* Default: "" +* Type: String + +The value `npm init` should use by default for the package author's name. + +### init.author.email + +* Default: "" +* Type: String + +The value `npm init` should use by default for the package author's email. + +### init.author.url + +* Default: "" +* Type: String + +The value `npm init` should use by default for the package author's homepage. + +### json + +* Default: false +* Type: Boolean + +Whether or not to output JSON data, rather than the normal output. + +This feature is currently experimental, and the output data structures +for many commands is either not implemented in JSON yet, or subject to +change. Only the output from `npm ls --json` is currently valid. + +### link + +* Default: false +* Type: Boolean + +If true, then local installs will link if there is a suitable globally +installed package. + +Note that this means that local installs can cause things to be +installed into the global space at the same time. The link is only done +if one of the two conditions are met: + +* The package is not already installed globally, or +* the globally installed version is identical to the version that is + being installed locally. + +### loglevel + +* Default: "http" +* Type: String +* Values: "silent", "win", "error", "warn", "http", "info", "verbose", "silly" + +What level of logs to report. On failure, *all* logs are written to +`npm-debug.log` in the current working directory. + +Any logs of a higher level than the setting are shown. +The default is "http", which shows http, warn, and error output. + +### logstream + +* Default: process.stderr +* Type: Stream + +This is the stream that is passed to the +[npmlog](https://github.com/isaacs/npmlog) module at run time. + +It cannot be set from the command line, but if you are using npm +programmatically, you may wish to send logs to somewhere other than +stderr. + +If the `color` config is set to true, then this stream will receive +colored output if it is a TTY. + +### long + +* Default: false +* Type: Boolean + +Show extended information in `npm ls` + +### message + +* Default: "%s" +* Type: String + +Commit message which is used by `npm version` when creating version commit. + +Any "%s" in the message will be replaced with the version number. + +### node-version + +* Default: process.version +* Type: semver or false + +The node version to use when checking package's "engines" hash. + +### npat + +* Default: false +* Type: Boolean + +Run tests on installation and report results to the +`npaturl`. + +### npaturl + +* Default: Not yet implemented +* Type: url + +The url to report npat test results. + +### onload-script + +* Default: false +* Type: path + +A node module to `require()` when npm loads. Useful for programmatic +usage. + +### optional + +* Default: true +* Type: Boolean + +Attempt to install packages in the `optionalDependencies` hash. Note +that if these packages fail to install, the overall installation +process is not aborted. + +### parseable + +* Default: false +* Type: Boolean + +Output parseable results from commands that write to +standard output. + +### prefix + +* Default: node's process.installPrefix +* Type: path + +The location to install global items. If set on the command line, then +it forces non-global commands to run in the specified folder. + +### production + +* Default: false +* Type: Boolean + +Set to true to run in "production" mode. + +1. devDependencies are not installed at the topmost level when running + local `npm install` without any arguments. +2. Set the NODE_ENV="production" for lifecycle scripts. + +### proprietary-attribs + +* Default: true +* Type: Boolean + +Whether or not to include proprietary extended attributes in the +tarballs created by npm. + +Unless you are expecting to unpack package tarballs with something other +than npm -- particularly a very outdated tar implementation -- leave +this as true. + +### proxy + +* Default: `HTTP_PROXY` or `http_proxy` environment variable, or null +* Type: url + +A proxy to use for outgoing http requests. + +### rebuild-bundle + +* Default: true +* Type: Boolean + +Rebuild bundled dependencies after installation. + +### registry + +* Default: https://registry.npmjs.org/ +* Type: url + +The base URL of the npm package registry. + +### rollback + +* Default: true +* Type: Boolean + +Remove failed installs. + +### save + +* Default: false +* Type: Boolean + +Save installed packages to a package.json file as dependencies. + +When used with the `npm rm` command, it removes it from the dependencies +hash. + +Only works if there is already a package.json file present. + +### save-bundle + +* Default: false +* Type: Boolean + +If a package would be saved at install time by the use of `--save`, +`--save-dev`, or `--save-optional`, then also put it in the +`bundleDependencies` list. + +When used with the `npm rm` command, it removes it from the +bundledDependencies list. + +### save-dev + +* Default: false +* Type: Boolean + +Save installed packages to a package.json file as devDependencies. + +When used with the `npm rm` command, it removes it from the devDependencies +hash. + +Only works if there is already a package.json file present. + +### save-optional + +* Default: false +* Type: Boolean + +Save installed packages to a package.json file as optionalDependencies. + +When used with the `npm rm` command, it removes it from the devDependencies +hash. + +Only works if there is already a package.json file present. + +### searchopts + +* Default: "" +* Type: String + +Space-separated options that are always passed to search. + +### searchexclude + +* Default: "" +* Type: String + +Space-separated options that limit the results from search. + +### searchsort + +* Default: "name" +* Type: String +* Values: "name", "-name", "date", "-date", "description", + "-description", "keywords", "-keywords" + +Indication of which field to sort search results by. Prefix with a `-` +character to indicate reverse sort. + +### shell + +* Default: SHELL environment variable, or "bash" on Posix, or "cmd" on + Windows +* Type: path + +The shell to run for the `npm explore` command. + +### sign-git-tag + +* Default: false +* Type: Boolean + +If set to true, then the `npm version` command will tag the version +using `-s` to add a signature. + +Note that git requires you to have set up GPG keys in your git configs +for this to work properly. + +### strict-ssl + +* Default: true +* Type: Boolean + +Whether or not to do SSL key validation when making requests to the +registry via https. + +See also the `ca` config. + +### tag + +* Default: latest +* Type: String + +If you ask npm to install a package and don't tell it a specific version, then +it will install the specified tag. + +Also the tag that is added to the package@version specified by the `npm +tag` command, if no explicit tag is given. + +### tmp + +* Default: TMPDIR environment variable, or "/tmp" +* Type: path + +Where to store temporary files and folders. All temp files are deleted +on success, but left behind on failure for forensic purposes. + +### unicode + +* Default: true +* Type: Boolean + +When set to true, npm uses unicode characters in the tree output. When +false, it uses ascii characters to draw trees. + +### unsafe-perm + +* Default: false if running as root, true otherwise +* Type: Boolean + +Set to true to suppress the UID/GID switching when running package +scripts. If set explicitly to false, then installing as a non-root user +will fail. + +### usage + +* Default: false +* Type: Boolean + +Set to show short usage output (like the -H output) +instead of complete help when doing `npm-help(1)`. + +### user + +* Default: "nobody" +* Type: String or Number + +The UID to set to when running package scripts as root. + +### username + +* Default: null +* Type: String + +The username on the npm registry. Set with `npm adduser` + +### userconfig + +* Default: ~/.npmrc +* Type: path + +The location of user-level configuration settings. + +### userignorefile + +* Default: ~/.npmignore +* Type: path + +The location of a user-level ignore file to apply to all packages. + +If not found, but there is a .gitignore file in the same directory, then +that will be used instead. + +### umask + +* Default: 022 +* Type: Octal numeric string + +The "umask" value to use when setting the file creation mode on files +and folders. + +Folders and executables are given a mode which is `0777` masked against +this value. Other files are given a mode which is `0666` masked against +this value. Thus, the defaults are `0755` and `0644` respectively. + +### version + +* Default: false +* Type: boolean + +If true, output the npm version and exit successfully. + +Only relevant when specified explicitly on the command line. + +### versions + +* Default: false +* Type: boolean + +If true, output the npm version as well as node's `process.versions` +hash, and exit successfully. + +Only relevant when specified explicitly on the command line. + +### viewer + +* Default: "man" on Posix, "browser" on Windows +* Type: path + +The program to use to view help content. + +Set to `"browser"` to view html help content in the default web browser. + +### yes + +* Default: null +* Type: Boolean or null + +If set to `null`, then prompt the user for responses in some +circumstances. + +If set to `true`, then answer "yes" to any prompt. If set to `false` +then answer "no" to any prompt. + +## SEE ALSO + +* npm-folders(1) +* npm(1) diff --git a/node-v0.8.14/deps/npm/doc/cli/dedupe.md b/node-v0.8.14/deps/npm/doc/cli/dedupe.md new file mode 100644 index 0000000..220329a --- /dev/null +++ b/node-v0.8.14/deps/npm/doc/cli/dedupe.md @@ -0,0 +1,53 @@ +npm-dedupe(1) -- Reduce duplication +=================================== + +## SYNOPSIS + + npm dedupe [package names...] + +## DESCRIPTION + +Searches the local package tree and attempts to simplify the overall +structure by moving dependencies further up the tree, where they can +be more effectively shared by multiple dependent packages. + +For example, consider this dependency graph: + + a + +-- b <-- depends on c@1.0.x + | `-- c@1.0.3 + `-- d <-- depends on c@~1.0.9 + `-- c@1.0.10 + +In this case, `npm-dedupe(1)` will transform the tree to: + + a + +-- b + +-- d + `-- c@1.0.10 + +Because of the hierarchical nature of node's module lookup, b and d +will both get their dependency met by the single c package at the root +level of the tree. + +If a suitable version exists at the target location in the tree +already, then it will be left untouched, but the other duplicates will +be deleted. + +If no suitable version can be found, then a warning is printed, and +nothing is done. + +If any arguments are supplied, then they are filters, and only the +named packages will be touched. + +Note that this operation transforms the dependency tree, and may +result in packages getting updated versions, perhaps from the npm +registry. + +This feature is experimental, and may change in future versions. + +## SEE ALSO + +* npm-ls(1) +* npm-update(1) +* npm-install(1) diff --git a/node-v0.8.14/deps/npm/doc/cli/deprecate.md b/node-v0.8.14/deps/npm/doc/cli/deprecate.md new file mode 100644 index 0000000..925337f --- /dev/null +++ b/node-v0.8.14/deps/npm/doc/cli/deprecate.md @@ -0,0 +1,24 @@ +npm-deprecate(1) -- Deprecate a version of a package +==================================================== + +## SYNOPSIS + + npm deprecate [@] + +## DESCRIPTION + +This command will update the npm registry entry for a package, providing +a deprecation warning to all who attempt to install it. + +It works on version ranges as well as specific versions, so you can do +something like this: + + npm deprecate my-thing@"< 0.2.3" "critical bug fixed in v0.2.3" + +Note that you must be the package owner to deprecate something. See the +`owner` and `adduser` help topics. + +## SEE ALSO + +* npm-publish(1) +* npm-registry(1) diff --git a/node-v0.8.14/deps/npm/doc/cli/developers.md b/node-v0.8.14/deps/npm/doc/cli/developers.md new file mode 100644 index 0000000..7ab905b --- /dev/null +++ b/node-v0.8.14/deps/npm/doc/cli/developers.md @@ -0,0 +1,183 @@ +npm-developers(1) -- Developer Guide +==================================== + +## DESCRIPTION + +So, you've decided to use npm to develop (and maybe publish/deploy) +your project. + +Fantastic! + +There are a few things that you need to do above the simple steps +that your users will do to install your program. + +## About These Documents + +These are man pages. If you install npm, you should be able to +then do `man npm-thing` to get the documentation on a particular +topic, or `npm help thing` to see the same information. + +## What is a `package` + +A package is: + +* a) a folder containing a program described by a package.json file +* b) a gzipped tarball containing (a) +* c) a url that resolves to (b) +* d) a `@` that is published on the registry with (c) +* e) a `@` that points to (d) +* f) a `` that has a "latest" tag satisfying (e) +* g) a `git` url that, when cloned, results in (a). + +Even if you never publish your package, you can still get a lot of +benefits of using npm if you just want to write a node program (a), and +perhaps if you also want to be able to easily install it elsewhere +after packing it up into a tarball (b). + +Git urls can be of the form: + + git://github.com/user/project.git#commit-ish + git+ssh://user@hostname:project.git#commit-ish + git+http://user@hostname/project/blah.git#commit-ish + git+https://user@hostname/project/blah.git#commit-ish + +The `commit-ish` can be any tag, sha, or branch which can be supplied as +an argument to `git checkout`. The default is `master`. + +## The package.json File + +You need to have a `package.json` file in the root of your project to do +much of anything with npm. That is basically the whole interface. + +See `npm-json(1)` for details about what goes in that file. At the very +least, you need: + +* name: + This should be a string that identifies your project. Please do not + use the name to specify that it runs on node, or is in JavaScript. + You can use the "engines" field to explicitly state the versions of + node (or whatever else) that your program requires, and it's pretty + well assumed that it's javascript. + + It does not necessarily need to match your github repository name. + + So, `node-foo` and `bar-js` are bad names. `foo` or `bar` are better. + +* version: + A semver-compatible version. + +* engines: + Specify the versions of node (or whatever else) that your program + runs on. The node API changes a lot, and there may be bugs or new + functionality that you depend on. Be explicit. + +* author: + Take some credit. + +* scripts: + If you have a special compilation or installation script, then you + should put it in the `scripts` hash. You should definitely have at + least a basic smoke-test command as the "scripts.test" field. + See npm-scripts(1). + +* main: + If you have a single module that serves as the entry point to your + program (like what the "foo" package gives you at require("foo")), + then you need to specify that in the "main" field. + +* directories: + This is a hash of folders. The best ones to include are "lib" and + "doc", but if you specify a folder full of man pages in "man", then + they'll get installed just like these ones. + +You can use `npm init` in the root of your package in order to get you +started with a pretty basic package.json file. See `npm-init(1)` for +more info. + +## Keeping files *out* of your package + +Use a `.npmignore` file to keep stuff out of your package. If there's +no .npmignore file, but there *is* a .gitignore file, then npm will +ignore the stuff matched by the .gitignore file. If you *want* to +include something that is excluded by your .gitignore file, you can +create an empty .npmignore file to override it. + +## Link Packages + +`npm link` is designed to install a development package and see the +changes in real time without having to keep re-installing it. (You do +need to either re-link or `npm rebuild -g` to update compiled packages, +of course.) + +More info at `npm-link(1)`. + +## Before Publishing: Make Sure Your Package Installs and Works + +**This is important.** + +If you can not install it locally, you'll have +problems trying to publish it. Or, worse yet, you'll be able to +publish it, but you'll be publishing a broken or pointless package. +So don't do that. + +In the root of your package, do this: + + npm install . -g + +That'll show you that it's working. If you'd rather just create a symlink +package that points to your working directory, then do this: + + npm link + +Use `npm ls -g` to see if it's there. + +To test a local install, go into some other folder, and then do: + + cd ../some-other-folder + npm install ../my-package + +to install it locally into the node_modules folder in that other place. + +Then go into the node-repl, and try using require("my-thing") to +bring in your module's main module. + +## Create a User Account + +Create a user with the adduser command. It works like this: + + npm adduser + +and then follow the prompts. + +This is documented better in npm-adduser(1). + +## Publish your package + +This part's easy. IN the root of your folder, do this: + + npm publish + +You can give publish a url to a tarball, or a filename of a tarball, +or a path to a folder. + +Note that pretty much **everything in that folder will be exposed** +by default. So, if you have secret stuff in there, use a +`.npmignore` file to list out the globs to ignore, or publish +from a fresh checkout. + +## Brag about it + +Send emails, write blogs, blab in IRC. + +Tell the world how easy it is to install your program! + +## SEE ALSO + +* npm-faq(1) +* npm(1) +* npm-init(1) +* npm-json(1) +* npm-scripts(1) +* npm-publish(1) +* npm-adduser(1) +* npm-registry(1) diff --git a/node-v0.8.14/deps/npm/doc/cli/disputes.md b/node-v0.8.14/deps/npm/doc/cli/disputes.md new file mode 100644 index 0000000..96ad9ef --- /dev/null +++ b/node-v0.8.14/deps/npm/doc/cli/disputes.md @@ -0,0 +1,84 @@ +npm-disputes(1) -- Handling Module Name Disputes +================================================ + +## SYNOPSIS + +1. Get the author email with `npm owner ls ` +1. Email the author, CC . +2. After a few weeks, if there's no resolution, we'll sort it out. + +## DESCRIPTION + +There sometimes arise cases where a user publishes a module, and then +later, some other user wants to use that name. Here are some common +ways that happens (each of these is based on actual events.) + +1. Bob writes a JavaScript module `foo`, which is not node-specific. + Bob doesn't use node at all. Joe wants to use `foo` in node, so he + wraps it in an npm module. Some time later, Bob starts using node, + and wants to take over management of his program. +2. Bob writes an npm module `foo`, and publishes it. Perhaps much + later, Joe finds a bug in `foo`, and fixes it. He sends a pull + request to Bob, but Bob doesn't have the time to deal with it, + because he has a new job and a new baby and is focused on his new + erlang project, and kind of not involved with node any more. Joe + would like to publish a new `foo`, but can't, because the name is + taken. +3. Bob writes a 10-line flow-control library, and calls it `foo`, and + publishes it to the npm registry. Being a simple little thing, it + never really has to be updated. Joe works for Foo Inc, the makers + of the critically acclaimed and widely-marketed `foo` JavaScript + toolkit framework. They publish it to npm as `foojs`, but people are + routinely confused when `npm install foo` is some different thing. +4. Bob writes a parser for the widely-known `foo` file format, because + he needs it for work. Then, he gets a new job, and never updates the + prototype. Later on, Joe writes a much more complete `foo` parser, + but can't publish, because Bob's `foo` is in the way. + +The validity of Joe's claim in each situation can be debated. However, +Joe's appropriate course of action in each case is the same. + +1. `npm owner ls foo`. This will tell Joe the email address of the + owner (Bob). +2. Joe emails Bob, explaining the situation **as respecfully as possible**, + and what he would like to do with the module name. He adds + isaacs to the CC list of the email. Mention in the email + that Bob can run `npm owner add joe foo` to add Joe as an owner of + the `foo` package. +3. After a reasonable amount of time, if Bob has not responded, or if + Bob and Joe can't come to any sort of resolution, email isaacs + and we'll sort it out. + +## REASONING + +In almost every case so far, the parties involved have been able to reach +an amicable resolution without any major intervention. Most people +really do want to be reasonable, and are probably not even aware that +they're in your way. + +Module ecosystems are most vibrant and powerful when they are as +self-directed as possible. If an admin one day deletes something you +had worked on, then that is going to make most people quite upset, +regardless of the justification. When humans solve their problems by +talking to other humans with respect, everyone has the chance to end up +feeling good about the interaction. + +## EXCEPTIONS + +Some things are not allowed, and will be removed without discussion if +they are brought to the attention of the npm registry admins, including +but not limited to: + +1. Malware (that is, a module designed to exploit or harm the machine on + which it is installed) +2. Violations of copyright or licenses (for example, cloning an + MIT-licensed program, and then removing or changing the copyright and + license statement) +3. Illegal content. + +If you see bad behavior like this, please report it right away. + +## SEE ALSO + +* npm-registry(1) +* npm-owner(1) diff --git a/node-v0.8.14/deps/npm/doc/cli/docs.md b/node-v0.8.14/deps/npm/doc/cli/docs.md new file mode 100644 index 0000000..26b2455 --- /dev/null +++ b/node-v0.8.14/deps/npm/doc/cli/docs.md @@ -0,0 +1,38 @@ +npm-docs(1) -- Docs for a package in a web browser maybe +======================================================== + +## SYNOPSIS + + npm docs + npm home + +## DESCRIPTION + +This command tries to guess at the likely location of a package's +documentation URL, and then tries to open it using the `--browser` +config param. + +## CONFIGURATION + +### browser + +* Default: OS X: `"open"`, others: `"google-chrome"` +* Type: String + +The browser that is called by the `npm docs` command to open websites. + +### registry + +* Default: https://registry.npmjs.org/ +* Type: url + +The base URL of the npm package registry. + + +## SEE ALSO + +* npm-view(1) +* npm-publish(1) +* npm-registry(1) +* npm-config(1) +* npm-json(1) diff --git a/node-v0.8.14/deps/npm/doc/cli/edit.md b/node-v0.8.14/deps/npm/doc/cli/edit.md new file mode 100644 index 0000000..9eaccfc --- /dev/null +++ b/node-v0.8.14/deps/npm/doc/cli/edit.md @@ -0,0 +1,35 @@ +npm-edit(1) -- Edit an installed package +======================================== + +## SYNOPSIS + + npm edit [@] + +## DESCRIPTION + +Opens the package folder in the default editor (or whatever you've +configured as the npm `editor` config -- see `npm-config(1)`.) + +After it has been edited, the package is rebuilt so as to pick up any +changes in compiled packages. + +For instance, you can do `npm install connect` to install connect +into your package, and then `npm edit connect` to make a few +changes to your locally installed copy. + +## CONFIGURATION + +### editor + +* Default: `EDITOR` environment variable if set, or `"vi"` on Posix, + or `"notepad"` on Windows. +* Type: path + +The command to run for `npm edit` or `npm config edit`. + +## SEE ALSO + +* npm-folders(1) +* npm-explore(1) +* npm-install(1) +* npm-config(1) diff --git a/node-v0.8.14/deps/npm/doc/cli/explore.md b/node-v0.8.14/deps/npm/doc/cli/explore.md new file mode 100644 index 0000000..00701b3 --- /dev/null +++ b/node-v0.8.14/deps/npm/doc/cli/explore.md @@ -0,0 +1,40 @@ +npm-explore(1) -- Browse an installed package +============================================= + +## SYNOPSIS + + npm explore [@] [ -- ] + +## DESCRIPTION + +Spawn a subshell in the directory of the installed package specified. + +If a command is specified, then it is run in the subshell, which then +immediately terminates. + +This is particularly handy in the case of git submodules in the +`node_modules` folder: + + npm explore some-dependency -- git pull origin master + +Note that the package is *not* automatically rebuilt afterwards, so be +sure to use `npm rebuild ` if you make any changes. + +## CONFIGURATION + +### shell + +* Default: SHELL environment variable, or "bash" on Posix, or "cmd" on + Windows +* Type: path + +The shell to run for the `npm explore` command. + +## SEE ALSO + +* npm-submodule(1) +* npm-folders(1) +* npm-edit(1) +* npm-rebuild(1) +* npm-build(1) +* npm-install(1) diff --git a/node-v0.8.14/deps/npm/doc/cli/faq.md b/node-v0.8.14/deps/npm/doc/cli/faq.md new file mode 100644 index 0000000..4c83671 --- /dev/null +++ b/node-v0.8.14/deps/npm/doc/cli/faq.md @@ -0,0 +1,260 @@ +npm-faq(1) -- Frequently Asked Questions +======================================== + +## Where can I find these docs in HTML? + +, or run: + + npm config set viewer browser + +to open these documents in your default web browser rather than `man`. + +## It didn't work. + +That's not really a question. + +## Why didn't it work? + +I don't know yet. + +Read the error output, and if you can't figure out what it means, +do what it says and post a bug with all the information it asks for. + +## Where does npm put stuff? + +See `npm-folders(1)` + +tl;dr: + +* Use the `npm root` command to see where modules go, and the `npm bin` + command to see where executables go +* Global installs are different from local installs. If you install + something with the `-g` flag, then its executables go in `npm bin -g` + and its modules go in `npm root -g`. + +## How do I install something on my computer in a central location? + +Install it globally by tacking `-g` or `--global` to the command. (This +is especially important for command line utilities that need to add +their bins to the global system `PATH`.) + +## I installed something globally, but I can't `require()` it + +Install it locally. + +The global install location is a place for command-line utilities +to put their bins in the system `PATH`. It's not for use with `require()`. + +If you `require()` a module in your code, then that means it's a +dependency, and a part of your program. You need to install it locally +in your program. + +## Why can't npm just put everything in one place, like other package managers? + +Not every change is an improvement, but every improvement is a change. +This would be like asking git to do network IO for every commit. It's +not going to happen, because it's a terrible idea that causes more +problems than it solves. + +It is much harder to avoid dependency conflicts without nesting +dependencies. This is fundamental to the way that npm works, and has +proven to be an extremely successful approach. See `npm-folders(1)` for +more details. + +If you want a package to be installed in one place, and have all your +programs reference the same copy of it, then use the `npm link` command. +That's what it's for. Install it globally, then link it into each +program that uses it. + +## Whatever, I really want the old style 'everything global' style. + +Write your own package manager, then. It's not that hard. + +npm will not help you do something that is known to be a bad idea. + +## Should I check my `node_modules` folder into git? + +Mikeal Rogers answered this question very well: + + + +tl;dr + +* Check `node_modules` into git for things you **deploy**, such as + websites and apps. +* Do not check `node_modules` into git for libraries and modules + intended to be reused. +* Use npm to manage dependencies in your dev environment, but not in + your deployment scripts. + +## Is it 'npm' or 'NPM' or 'Npm'? + +npm should never be capitalized unless it is being displayed in a +location that is customarily all-caps (such as the title of man pages.) + +## If 'npm' is an acronym, why is it never capitalized? + +Contrary to the belief of many, "npm" is not in fact an abbreviation for +"Node Package Manager". It is a recursive bacronymic abbreviation for +"npm is not an acronym". (If it was "ninaa", then it would be an +acronym, and thus incorrectly named.) + +"NPM", however, *is* an acronym (more precisely, a capitonym) for the +National Association of Pastoral Musicians. You can learn more +about them at . + +In software, "NPM" is a Non-Parametric Mapping utility written by +Chris Rorden. You can analyze pictures of brains with it. Learn more +about the (capitalized) NPM program at . + +The first seed that eventually grew into this flower was a bash utility +named "pm", which was a shortened descendent of "pkgmakeinst", a +bash function that was used to install various different things on different +platforms, most often using Yahoo's `yinst`. If `npm` was ever an +acronym for anything, it was `node pm` or maybe `new pm`. + +So, in all seriousness, the "npm" project is named after its command-line +utility, which was organically selected to be easily typed by a right-handed +programmer using a US QWERTY keyboard layout, ending with the +right-ring-finger in a postition to type the `-` key for flags and +other command-line arguments. That command-line utility is always +lower-case, though it starts most sentences it is a part of. + +## How do I list installed packages? + +`npm ls` + +## How do I search for packages? + +`npm search` + +Arguments are greps. `npm search jsdom` shows jsdom packages. + +## How do I update npm? + + npm update npm -g + +You can also update all outdated local packages by doing `npm update` without +any arguments, or global packages by doing `npm update -g`. + +Occasionally, the version of npm will progress such that the current +version cannot be properly installed with the version that you have +installed already. (Consider, if there is ever a bug in the `update` +command.) + +In those cases, you can do this: + + curl https://npmjs.org/install.sh | sh + +## What is a `package`? + +A package is: + +* a) a folder containing a program described by a package.json file +* b) a gzipped tarball containing (a) +* c) a url that resolves to (b) +* d) a `@` that is published on the registry with (c) +* e) a `@` that points to (d) +* f) a `` that has a "latest" tag satisfying (e) +* g) a `git` url that, when cloned, results in (a). + +Even if you never publish your package, you can still get a lot of +benefits of using npm if you just want to write a node program (a), and +perhaps if you also want to be able to easily install it elsewhere +after packing it up into a tarball (b). + +Git urls can be of the form: + + git://github.com/user/project.git#commit-ish + git+ssh://user@hostname:project.git#commit-ish + git+http://user@hostname/project/blah.git#commit-ish + git+https://user@hostname/project/blah.git#commit-ish + +The `commit-ish` can be any tag, sha, or branch which can be supplied as +an argument to `git checkout`. The default is `master`. + +## How do I install node with npm? + +You don't. Try one of these: + +* +* +* + +## How can I use npm for development? + +See `npm-developers(1)` and `npm-json(1)`. + +You'll most likely want to `npm link` your development folder. That's +awesomely handy. + +To set up your own private registry, check out `npm-registry(1)`. + +## Can I list a url as a dependency? + +Yes. It should be a url to a gzipped tarball containing a single folder +that has a package.json in its root, or a git url. +(See "what is a package?" above.) + +## How do I symlink to a dev folder so I don't have to keep re-installing? + +See `npm-link(1)` + +## The package registry website. What is that exactly? + +See `npm-registry(1)`. + +## What's up with the insecure channel warnings? + +Until node 0.4.10, there were problems sending big files over HTTPS. That +means that publishes go over HTTP by default in those versions of node. + +## I forgot my password, and can't publish. How do I reset it? + +Go to . + +## I get ECONNREFUSED a lot. What's up? + +Either the registry is down, or node's DNS isn't able to reach out. + +To check if the registry is down, open up +in a web browser. This will also tell you if you are just unable to +access the internet for some reason. + +If the registry IS down, let me know by emailing or posting an issue. +We'll have someone kick it or something. + +## Why no namespaces? + +Please see this discussion: + +tl;dr - It doesn't actually make things better, and can make them worse. + +If you want to namespace your own packages, you may: simply use the +`-` character to separate the names. npm is a mostly anarchic system. +There is not sufficient need to impose namespace rules on everyone. + +## Who does npm? + +`npm view npm author` + +`npm view npm contributors` + +## I have a question or request not addressed here. Where should I put it? + +Discuss it on the mailing list, or post an issue. + +* +* + +## Why does npm hate me? + +npm is not capable of hatred. It loves everyone, especially you. + +## SEE ALSO + +* npm(1) +* npm-developers(1) +* npm-json(1) +* npm-config(1) +* npm-folders(1) diff --git a/node-v0.8.14/deps/npm/doc/cli/folders.md b/node-v0.8.14/deps/npm/doc/cli/folders.md new file mode 100644 index 0000000..2035861 --- /dev/null +++ b/node-v0.8.14/deps/npm/doc/cli/folders.md @@ -0,0 +1,209 @@ +npm-folders(1) -- Folder Structures Used by npm +=============================================== + +## DESCRIPTION + +npm puts various things on your computer. That's its job. + +This document will tell you what it puts where. + +### tl;dr + +* Local install (default): puts stuff in `./node_modules` of the current + package root. +* Global install (with `-g`): puts stuff in /usr/local or wherever node + is installed. +* Install it **locally** if you're going to `require()` it. +* Install it **globally** if you're going to run it on the command line. +* If you need both, then install it in both places, or use `npm link`. + +### prefix Configuration + +The `prefix` config defaults to the location where node is installed. +On most systems, this is `/usr/local`, and most of the time is the same +as node's `process.installPrefix`. + +On windows, this is the exact location of the node.exe binary. On Unix +systems, it's one level up, since node is typically installed at +`{prefix}/bin/node` rather than `{prefix}/node.exe`. + +When the `global` flag is set, npm installs things into this prefix. +When it is not set, it uses the root of the current package, or the +current working directory if not in a package already. + +### Node Modules + +Packages are dropped into the `node_modules` folder under the `prefix`. +When installing locally, this means that you can +`require("packagename")` to load its main module, or +`require("packagename/lib/path/to/sub/module")` to load other modules. + +Global installs on Unix systems go to `{prefix}/lib/node_modules`. +Global installs on Windows go to `{prefix}/node_modules` (that is, no +`lib` folder.) + +If you wish to `require()` a package, then install it locally. + +### Executables + +When in global mode, executables are linked into `{prefix}/bin` on Unix, +or directly into `{prefix}` on Windows. + +When in local mode, executables are linked into +`./node_modules/.bin` so that they can be made available to scripts run +through npm. (For example, so that a test runner will be in the path +when you run `npm test`.) + +### Man Pages + +When in global mode, man pages are linked into `{prefix}/share/man`. + +When in local mode, man pages are not installed. + +Man pages are not installed on Windows systems. + +### Cache + +See `npm-cache(1)`. Cache files are stored in `~/.npm` on Posix, or +`~/npm-cache` on Windows. + +This is controlled by the `cache` configuration param. + +### Temp Files + +Temporary files are stored by default in the folder specified by the +`tmp` config, which defaults to the TMPDIR, TMP, or TEMP environment +variables, or `/tmp` on Unix and `c:\windows\temp` on Windows. + +Temp files are given a unique folder under this root for each run of the +program, and are deleted upon successful exit. + +## More Information + +When installing locally, npm first tries to find an appropriate +`prefix` folder. This is so that `npm install foo@1.2.3` will install +to the sensible root of your package, even if you happen to have `cd`ed +into some other folder. + +Starting at the $PWD, npm will walk up the folder tree checking for a +folder that contains either a `package.json` file, or a `node_modules` +folder. If such a thing is found, then that is treated as the effective +"current directory" for the purpose of running npm commands. (This +behavior is inspired by and similar to git's .git-folder seeking +logic when running git commands in a working dir.) + +If no package root is found, then the current folder is used. + +When you run `npm install foo@1.2.3`, then the package is loaded into +the cache, and then unpacked into `./node_modules/foo`. Then, any of +foo's dependencies are similarly unpacked into +`./node_modules/foo/node_modules/...`. + +Any bin files are symlinked to `./node_modules/.bin/`, so that they may +be found by npm scripts when necessary. + +### Global Installation + +If the `global` configuration is set to true, then npm will +install packages "globally". + +For global installation, packages are installed roughly the same way, +but using the folders described above. + +### Cycles, Conflicts, and Folder Parsimony + +Cycles are handled using the property of node's module system that it +walks up the directories looking for `node_modules` folders. So, at every +stage, if a package is already installed in an ancestor `node_modules` +folder, then it is not installed at the current location. + +Consider the case above, where `foo -> bar -> baz`. Imagine if, in +addition to that, baz depended on bar, so you'd have: +`foo -> bar -> baz -> bar -> baz ...`. However, since the folder +structure is: `foo/node_modules/bar/node_modules/baz`, there's no need to +put another copy of bar into `.../baz/node_modules`, since when it calls +require("bar"), it will get the copy that is installed in +`foo/node_modules/bar`. + +This shortcut is only used if the exact same +version would be installed in multiple nested `node_modules` folders. It +is still possible to have `a/node_modules/b/node_modules/a` if the two +"a" packages are different versions. However, without repeating the +exact same package multiple times, an infinite regress will always be +prevented. + +Another optimization can be made by installing dependencies at the +highest level possible, below the localized "target" folder. + +#### Example + +Consider this dependency graph: + + foo + +-- blerg@1.2.5 + +-- bar@1.2.3 + | +-- blerg@1.x (latest=1.3.7) + | +-- baz@2.x + | | `-- quux@3.x + | | `-- bar@1.2.3 (cycle) + | `-- asdf@* + `-- baz@1.2.3 + `-- quux@3.x + `-- bar + +In this case, we might expect a folder structure like this: + + foo + +-- node_modules + +-- blerg (1.2.5) <---[A] + +-- bar (1.2.3) <---[B] + | +-- node_modules + | | `-- baz (2.0.2) <---[C] + | | `-- node_modules + | | `-- quux (3.2.0) + | `-- asdf (2.3.4) + `-- baz (1.2.3) <---[D] + `-- node_modules + `-- quux (3.2.0) <---[E] + +Since foo depends directly on bar@1.2.3 and baz@1.2.3, those are +installed in foo's `node_modules` folder. + +Even though the latest copy of blerg is 1.3.7, foo has a specific +dependency on version 1.2.5. So, that gets installed at [A]. Since the +parent installation of blerg satisfie's bar's dependency on blerg@1.x, +it does not install another copy under [B]. + +Bar [B] also has dependencies on baz and asdf, so those are installed in +bar's `node_modules` folder. Because it depends on `baz@2.x`, it cannot +re-use the `baz@1.2.3` installed in the parent `node_modules` folder [D], +and must install its own copy [C]. + +Underneath bar, the `baz->quux->bar` dependency creates a cycle. +However, because `bar` is already in `quux`'s ancestry [B], it does not +unpack another copy of bar into that folder. + +Underneath `foo->baz` [D], quux's [E] folder tree is empty, because its +dependency on bar is satisfied by the parent folder copy installed at [B]. + +For a graphical breakdown of what is installed where, use `npm ls`. + +### Publishing + +Upon publishing, npm will look in the `node_modules` folder. If any of +the items there are not in the `bundledDependencies` array, then they will +not be included in the package tarball. + +This allows a package maintainer to install all of their dependencies +(and dev dependencies) locally, but only re-publish those items that +cannot be found elsewhere. See `npm-json(1)` for more information. + +## SEE ALSO + +* npm-faq(1) +* npm-json(1) +* npm-install(1) +* npm-pack(1) +* npm-cache(1) +* npm-config(1) +* npm-publish(1) diff --git a/node-v0.8.14/deps/npm/doc/cli/help-search.md b/node-v0.8.14/deps/npm/doc/cli/help-search.md new file mode 100644 index 0000000..9c16901 --- /dev/null +++ b/node-v0.8.14/deps/npm/doc/cli/help-search.md @@ -0,0 +1,35 @@ +npm-help-search(1) -- Search npm help documentation +=================================================== + +## SYNOPSIS + + npm help-search some search terms + +## DESCRIPTION + +This command will search the npm markdown documentation files for the +terms provided, and then list the results, sorted by relevance. + +If only one result is found, then it will show that help topic. + +If the argument to `npm help` is not a known help topic, then it will +call `help-search`. It is rarely if ever necessary to call this +command directly. + +## CONFIGURATION + +### long + +* Type: Boolean +* Default false + +If true, the "long" flag will cause help-search to output context around +where the terms were found in the documentation. + +If false, then help-search will just list out the help topics found. + +## SEE ALSO + +* npm(1) +* npm-faq(1) +* npm-help(1) diff --git a/node-v0.8.14/deps/npm/doc/cli/help.md b/node-v0.8.14/deps/npm/doc/cli/help.md new file mode 100644 index 0000000..b51b0f1 --- /dev/null +++ b/node-v0.8.14/deps/npm/doc/cli/help.md @@ -0,0 +1,38 @@ +npm-help(1) -- Get help on npm +============================== + +## SYNOPSIS + + npm help + npm help some search terms + +## DESCRIPTION + +If supplied a topic, then show the appropriate documentation page. + +If the topic does not exist, or if multiple terms are provided, then run +the `help-search` command to find a match. Note that, if `help-search` +finds a single subject, then it will run `help` on that topic, so unique +matches are equivalent to specifying a topic name. + +## CONFIGURATION + +### viewer + +* Default: "man" on Posix, "browser" on Windows +* Type: path + +The program to use to view help content. + +Set to `"browser"` to view html help content in the default web browser. + +## SEE ALSO + +* npm(1) +* README +* npm-faq(1) +* npm-folders(1) +* npm-config(1) +* npm-json(1) +* npm-help-search(1) +* npm-index(1) diff --git a/node-v0.8.14/deps/npm/doc/cli/index.md b/node-v0.8.14/deps/npm/doc/cli/index.md new file mode 100644 index 0000000..f8fde25 --- /dev/null +++ b/node-v0.8.14/deps/npm/doc/cli/index.md @@ -0,0 +1,381 @@ +npm-index(1) -- Index of all npm documentation +============================================== + +## npm-README(1) + + node package manager + +# Command Line Documentation +## npm-adduser(1) + + Add a registry user account + +## npm-bin(1) + + Display npm bin folder + +## npm-bugs(1) + + Bugs for a package in a web browser maybe + +## npm-build(1) + + Build a package + +## npm-bundle(1) + + REMOVED + +## npm-cache(1) + + Manipulates packages cache + +## npm-changelog(1) + + Changes + +## npm-coding-style(1) + + npm's "funny" coding style + +## npm-completion(1) + + Tab Completion for npm + +## npm-config(1) + + Manage the npm configuration file + +## npm-dedupe(1) + + Reduce duplication + +## npm-deprecate(1) + + Deprecate a version of a package + +## npm-developers(1) + + Developer Guide + +## npm-disputes(1) + + Handling Module Name Disputes + +## npm-docs(1) + + Docs for a package in a web browser maybe + +## npm-edit(1) + + Edit an installed package + +## npm-explore(1) + + Browse an installed package + +## npm-faq(1) + + Frequently Asked Questions + +## npm-folders(1) + + Folder Structures Used by npm + +## npm-help-search(1) + + Search npm help documentation + +## npm-help(1) + + Get help on npm + +## npm-init(1) + + Interactively create a package.json file + +## npm-install(1) + + Install a package + +## npm-json(1) + + Specifics of npm's package.json handling + +## npm-link(1) + + Symlink a package folder + +## npm-ls(1) + + List installed packages + +## npm-npm(1) + + node package manager + +## npm-outdated(1) + + Check for outdated packages + +## npm-owner(1) + + Manage package owners + +## npm-pack(1) + + Create a tarball from a package + +## npm-prefix(1) + + Display prefix + +## npm-prune(1) + + Remove extraneous packages + +## npm-publish(1) + + Publish a package + +## npm-rebuild(1) + + Rebuild a package + +## npm-registry(1) + + The JavaScript Package Registry + +## npm-removing-npm(1) + + Cleaning the Slate + +## npm-restart(1) + + Start a package + +## npm-root(1) + + Display npm root + +## npm-run-script(1) + + Run arbitrary package scripts + +## npm-scripts(1) + + How npm handles the "scripts" field + +## npm-search(1) + + Search for packages + +## npm-semver(1) + + The semantic versioner for npm + +## npm-shrinkwrap(1) + + Lock down dependency versions + +## npm-star(1) + + Mark your favorite packages + +## npm-start(1) + + Start a package + +## npm-stop(1) + + Stop a package + +## npm-submodule(1) + + Add a package as a git submodule + +## npm-tag(1) + + Tag a published version + +## npm-test(1) + + Test a package + +## npm-uninstall(1) + + Remove a package + +## npm-unpublish(1) + + Remove a package from the registry + +## npm-update(1) + + Update a package + +## npm-version(1) + + Bump a package version + +## npm-view(1) + + View registry info + +## npm-whoami(1) + + Display npm username + +# API Documentation +## npm-bin(3) + + Display npm bin folder + +## npm-bugs(3) + + Bugs for a package in a web browser maybe + +## npm-commands(3) + + npm commands + +## npm-config(3) + + Manage the npm configuration files + +## npm-deprecate(3) + + Deprecate a version of a package + +## npm-docs(3) + + Docs for a package in a web browser maybe + +## npm-edit(3) + + Edit an installed package + +## npm-explore(3) + + Browse an installed package + +## npm-help-search(3) + + Search the help pages + +## npm-init(3) + + Interactively create a package.json file + +## npm-install(3) + + install a package programmatically + +## npm-link(3) + + Symlink a package folder + +## npm-load(3) + + Load config settings + +## npm-ls(3) + + List installed packages + +## npm-npm(3) + + node package manager + +## npm-outdated(3) + + Check for outdated packages + +## npm-owner(3) + + Manage package owners + +## npm-pack(3) + + Create a tarball from a package + +## npm-prefix(3) + + Display prefix + +## npm-prune(3) + + Remove extraneous packages + +## npm-publish(3) + + Publish a package + +## npm-rebuild(3) + + Rebuild a package + +## npm-restart(3) + + Start a package + +## npm-root(3) + + Display npm root + +## npm-run-script(3) + + Run arbitrary package scripts + +## npm-search(3) + + Search for packages + +## npm-shrinkwrap(3) + + programmatically generate package shrinkwrap file + +## npm-start(3) + + Start a package + +## npm-stop(3) + + Stop a package + +## npm-submodule(3) + + Add a package as a git submodule + +## npm-tag(3) + + Tag a published version + +## npm-test(3) + + Test a package + +## npm-uninstall(3) + + uninstall a package programmatically + +## npm-unpublish(3) + + Remove a package from the registry + +## npm-update(3) + + Update a package + +## npm-version(3) + + Bump a package version + +## npm-view(3) + + View registry info + +## npm-whoami(3) + + Display npm username + diff --git a/node-v0.8.14/deps/npm/doc/cli/init.md b/node-v0.8.14/deps/npm/doc/cli/init.md new file mode 100644 index 0000000..d036f92 --- /dev/null +++ b/node-v0.8.14/deps/npm/doc/cli/init.md @@ -0,0 +1,25 @@ +npm-init(1) -- Interactively create a package.json file +======================================================= + +## SYNOPSIS + + npm init + +## DESCRIPTION + +This will ask you a bunch of questions, and then write a package.json for you. + +It attempts to make reasonable guesses about what you want things to be set to, +and then writes a package.json file with the options you've selected. + +If you already have a package.json file, it'll read that first, and default to +the options in there. + +It is strictly additive, so it does not delete options from your package.json +without a really good reason to do so. + +## SEE ALSO + +* +* npm-json(1) +* npm-version(1) diff --git a/node-v0.8.14/deps/npm/doc/cli/install.md b/node-v0.8.14/deps/npm/doc/cli/install.md new file mode 100644 index 0000000..1d2f6ec --- /dev/null +++ b/node-v0.8.14/deps/npm/doc/cli/install.md @@ -0,0 +1,233 @@ +npm-install(1) -- Install a package +=================================== + +## SYNOPSIS + + npm install (with no args in a package dir) + npm install + npm install + npm install + npm install [--save|--save-dev|--save-optional] + npm install @ + npm install @ + npm install @ + npm install @ + +## DESCRIPTION + +This command installs a package, and any packages that it depends on. If the +package has a shrinkwrap file, the installation of dependencies will be driven +by that. See npm-shrinkwrap(1). + +A `package` is: + +* a) a folder containing a program described by a package.json file +* b) a gzipped tarball containing (a) +* c) a url that resolves to (b) +* d) a `@` that is published on the registry with (c) +* e) a `@` that points to (d) +* f) a `` that has a "latest" tag satisfying (e) +* g) a `` that resolves to (b) + +Even if you never publish your package, you can still get a lot of +benefits of using npm if you just want to write a node program (a), and +perhaps if you also want to be able to easily install it elsewhere +after packing it up into a tarball (b). + + +* `npm install` (in package directory, no arguments): + + Install the dependencies in the local node_modules folder. + + In global mode (ie, with `-g` or `--global` appended to the command), + it installs the current package context (ie, the current working + directory) as a global package. + + +* `npm install `: + + Install a package that is sitting in a folder on the filesystem. + +* `npm install `: + + Install a package that is sitting on the filesystem. Note: if you just want + to link a dev directory into your npm root, you can do this more easily by + using `npm link`. + + Example: + + npm install ./package.tgz + +* `npm install `: + + Fetch the tarball url, and then install it. In order to distinguish between + this and other options, the argument must start with "http://" or "https://" + + Example: + + npm install https://github.com/indexzero/forever/tarball/v0.5.6 + +* `npm install [--save|--save-dev|--save-optional]`: + + Do a `@` install, where `` is the "tag" config. (See + `npm-config(1)`.) + + In most cases, this will install the latest version + of the module published on npm. + + Example: + + npm install sax + + `npm install` takes 3 exclusive, optional flags which save or update + the package version in your main package.json: + + * `--save`: Package will appear in your `dependencies`. + + * `--save-dev`: Package will appear in your `devDependencies`. + + * `--save-optional`: Package will appear in your `optionalDependencies`. + + Examples: + + npm install sax --save + npm install node-tap --save-dev + npm install dtrace-provider --save-optional + + + **Note**: If there is a file or folder named `` in the current + working directory, then it will try to install that, and only try to + fetch the package by name if it is not valid. + +* `npm install @`: + + Install the version of the package that is referenced by the specified tag. + If the tag does not exist in the registry data for that package, then this + will fail. + + Example: + + npm install sax@latest + +* `npm install @`: + + Install the specified version of the package. This will fail if the version + has not been published to the registry. + + Example: + + npm install sax@0.1.1 + +* `npm install @`: + + Install a version of the package matching the specified version range. This + will follow the same rules for resolving dependencies described in `npm-json(1)`. + + Note that most version ranges must be put in quotes so that your shell will + treat it as a single argument. + + Example: + + npm install sax@">=0.1.0 <0.2.0" + +* `npm install `: + + Install a package by cloning a git remote url. The format of the git + url is: + + ://[@][#] + + `` is one of `git`, `git+ssh`, `git+http`, or + `git+https`. If no `` is specified, then `master` is + used. + + Examples: + + git+ssh://git@github.com:isaacs/npm.git#v1.0.27 + git+https://isaacs@github.com/isaacs/npm.git + git://github.com/isaacs/npm.git#v1.0.27 + +You may combine multiple arguments, and even multiple types of arguments. +For example: + + npm install sax@">=0.1.0 <0.2.0" bench supervisor + +The `--tag` argument will apply to all of the specified install targets. + +The `--force` argument will force npm to fetch remote resources even if a +local copy exists on disk. + + npm install sax --force + +The `--global` argument will cause npm to install the package globally +rather than locally. See `npm-folders(1)`. + +The `--link` argument will cause npm to link global installs into the +local space in some cases. + +See `npm-config(1)`. Many of the configuration params have some +effect on installation, since that's most of what npm does. + +## ALGORITHM + +To install a package, npm uses the following algorithm: + + install(where, what, family, ancestors) + fetch what, unpack to /node_modules/ + for each dep in what.dependencies + resolve dep to precise version + for each dep@version in what.dependencies + not in /node_modules//node_modules/* + and not in + add precise version deps to + install(/node_modules/, dep, family) + +For this `package{dep}` structure: `A{B,C}, B{C}, C{D}`, +this algorithm produces: + + A + +-- B + `-- C + `-- D + +That is, the dependency from B to C is satisfied by the fact that A +already caused C to be installed at a higher level. + +See npm-folders(1) for a more detailed description of the specific +folder structures that npm creates. + +### Limitations of npm's Install Algorithm + +There are some very rare and pathological edge-cases where a cycle can +cause npm to try to install a never-ending tree of packages. Here is +the simplest case: + + A -> B -> A' -> B' -> A -> B -> A' -> B' -> A -> ... + +where `A` is some version of a package, and `A'` is a different version +of the same package. Because `B` depends on a different version of `A` +than the one that is already in the tree, it must install a separate +copy. The same is true of `A'`, which must install `B'`. Because `B'` +depends on the original version of `A`, which has been overridden, the +cycle falls into infinite regress. + +To avoid this situation, npm flat-out refuses to install any +`name@version` that is already present anywhere in the tree of package +folder ancestors. A more correct, but more complex, solution would be +to symlink the existing version into the new location. If this ever +affects a real use-case, it will be investigated. + +## SEE ALSO + +* npm-folders(1) +* npm-update(1) +* npm-link(1) +* npm-rebuild(1) +* npm-scripts(1) +* npm-build(1) +* npm-config(1) +* npm-registry(1) +* npm-folders(1) +* npm-tag(1) +* npm-rm(1) +* npm-shrinkwrap(1) diff --git a/node-v0.8.14/deps/npm/doc/cli/json.md b/node-v0.8.14/deps/npm/doc/cli/json.md new file mode 100644 index 0000000..46df441 --- /dev/null +++ b/node-v0.8.14/deps/npm/doc/cli/json.md @@ -0,0 +1,566 @@ +npm-json(1) -- Specifics of npm's package.json handling +======================================================= + +## DESCRIPTION + +This document is all you need to know about what's required in your package.json +file. It must be actual JSON, not just a JavaScript object literal. + +A lot of the behavior described in this document is affected by the config +settings described in `npm-config(1)`. + +## DEFAULT VALUES + +npm will default some values based on package contents. + +* `"scripts": {"start": "node server.js"}` + + If there is a `server.js` file in the root of your package, then npm + will default the `start` command to `node server.js`. + +* `"scripts":{"preinstall": "node-waf clean || true; node-waf configure build"}` + + If there is a `wscript` file in the root of your package, npm will + default the `preinstall` command to compile using node-waf. + +* `"scripts":{"preinstall": "node-gyp rebuild"}` + + If there is a `binding.gyp` file in the root of your package, npm will + default the `preinstall` command to compile using node-gyp. + +* `"contributors": [...]` + + If there is an `AUTHORS` file in the root of your package, npm will + treat each line as a `Name (url)` format, where email and url + are optional. Lines which start with a `#` or are blank, will be + ignored. + +## name + +The *most* important things in your package.json are the name and version fields. +Those are actually required, and your package won't install without +them. The name and version together form an identifier that is assumed +to be completely unique. Changes to the package should come along with +changes to the version. + +The name is what your thing is called. Some tips: + +* Don't put "js" or "node" in the name. It's assumed that it's js, since you're + writing a package.json file, and you can specify the engine using the "engines" + field. (See below.) +* The name ends up being part of a URL, an argument on the command line, and a + folder name. Any name with non-url-safe characters will be rejected. + Also, it can't start with a dot or an underscore. +* The name will probably be passed as an argument to require(), so it should + be something short, but also reasonably descriptive. +* You may want to check the npm registry to see if there's something by that name + already, before you get too attached to it. http://registry.npmjs.org/ + +## version + +The *most* important things in your package.json are the name and version fields. +Those are actually required, and your package won't install without +them. The name and version together form an identifier that is assumed +to be completely unique. Changes to the package should come along with +changes to the version. + +Version must be parseable by +[node-semver](https://github.com/isaacs/node-semver), which is bundled +with npm as a dependency. (`npm install semver` to use it yourself.) + +Here's how npm's semver implementation deviates from what's on semver.org: + +* Versions can start with "v" +* A numeric item separated from the main three-number version by a hyphen + will be interpreted as a "build" number, and will *increase* the version. + But, if the tag is not a number separated by a hyphen, then it's treated + as a pre-release tag, and is *less than* the version without a tag. + So, `0.1.2-7 > 0.1.2-7-beta > 0.1.2-6 > 0.1.2 > 0.1.2beta` + +This is a little bit confusing to explain, but matches what you see in practice +when people create tags in git like "v1.2.3" and then do "git describe" to generate +a patch version. + +## description + +Put a description in it. It's a string. This helps people discover your +package, as it's listed in `npm search`. + +## keywords + +Put keywords in it. It's an array of strings. This helps people +discover your package as it's listed in `npm search`. + +## homepage + +The url to the project homepage. + +**NOTE**: This is *not* the same as "url". If you put a "url" field, +then the registry will think it's a redirection to your package that has +been published somewhere else, and spit at you. + +Literally. Spit. I'm so not kidding. + +## bugs + +The url to your project's issue tracker and / or the email address to which +issues should be reported. These are helpful for people who encounter issues +with your package. + +It should look like this: + + { "url" : "http://github.com/owner/project/issues" + , "email" : "project@hostname.com" + } + +You can specify either one or both values. If you want to provide only a url, +you can specify the value for "bugs" as a simple string instead of an object. + +If a url is provided, it will be used by the `npm bugs` command. + +## people fields: author, contributors + +The "author" is one person. "contributors" is an array of people. A "person" +is an object with a "name" field and optionally "url" and "email", like this: + + { "name" : "Barney Rubble" + , "email" : "b@rubble.com" + , "url" : "http://barnyrubble.tumblr.com/" + } + +Or you can shorten that all into a single string, and npm will parse it for you: + + "Barney Rubble (http://barnyrubble.tumblr.com/) + +Both email and url are optional either way. + +npm also sets a top-level "maintainers" field with your npm user info. + +## files + +The "files" field is an array of files to include in your project. If +you name a folder in the array, then it will also include the files +inside that folder. (Unless they would be ignored by another rule.) + +You can also provide a ".npmignore" file in the root of your package, +which will keep files from being included, even if they would be picked +up by the files array. The ".npmignore" file works just like a +".gitignore". + +## main + +The main field is a module ID that is the primary entry point to your program. +That is, if your package is named `foo`, and a user installs it, and then does +`require("foo")`, then your main module's exports object will be returned. + +This should be a module ID relative to the root of your package folder. + +For most modules, it makes the most sense to have a main script and often not +much else. + +## bin + +A lot of packages have one or more executable files that they'd like to +install into the PATH. npm makes this pretty easy (in fact, it uses this +feature to install the "npm" executable.) + +To use this, supply a `bin` field in your package.json which is a map of +command name to local file name. On install, npm will symlink that file into +`prefix/bin` for global installs, or `./node_modules/.bin/` for local +installs. + + +For example, npm has this: + + { "bin" : { "npm" : "./cli.js" } } + +So, when you install npm, it'll create a symlink from the `cli.js` script to +`/usr/local/bin/npm`. + +If you have a single executable, and its name should be the name +of the package, then you can just supply it as a string. For example: + + { "name": "my-program" + , "version": "1.2.5" + , "bin": "./path/to/program" } + +would be the same as this: + + { "name": "my-program" + , "version": "1.2.5" + , "bin" : { "my-program" : "./path/to/program" } } + +## man + +Specify either a single file or an array of filenames to put in place for the +`man` program to find. + +If only a single file is provided, then it's installed such that it is the +result from `man `, regardless of its actual filename. For example: + + { "name" : "foo" + , "version" : "1.2.3" + , "description" : "A packaged foo fooer for fooing foos" + , "main" : "foo.js" + , "man" : "./man/doc.1" + } + +would link the `./man/doc.1` file in such that it is the target for `man foo` + +If the filename doesn't start with the package name, then it's prefixed. +So, this: + + { "name" : "foo" + , "version" : "1.2.3" + , "description" : "A packaged foo fooer for fooing foos" + , "main" : "foo.js" + , "man" : [ "./man/foo.1", "./man/bar.1" ] + } + +will create files to do `man foo` and `man foo-bar`. + +Man files must end with a number, and optionally a `.gz` suffix if they are +compressed. The number dictates which man section the file is installed into. + + { "name" : "foo" + , "version" : "1.2.3" + , "description" : "A packaged foo fooer for fooing foos" + , "main" : "foo.js" + , "man" : [ "./man/foo.1", "./man/foo.2" ] + } + +will create entries for `man foo` and `man 2 foo` + +## directories + +The CommonJS [Packages](http://wiki.commonjs.org/wiki/Packages/1.0) spec details a +few ways that you can indicate the structure of your package using a `directories` +hash. If you look at [npm's package.json](http://registry.npmjs.org/npm/latest), +you'll see that it has directories for doc, lib, and man. + +In the future, this information may be used in other creative ways. + +### directories.lib + +Tell people where the bulk of your library is. Nothing special is done +with the lib folder in any way, but it's useful meta info. + +### directories.bin + +If you specify a "bin" directory, then all the files in that folder will +be used as the "bin" hash. + +If you have a "bin" hash already, then this has no effect. + +### directories.man + +A folder that is full of man pages. Sugar to generate a "man" array by +walking the folder. + +### directories.doc + +Put markdown files in here. Eventually, these will be displayed nicely, +maybe, someday. + +### directories.example + +Put example scripts in here. Someday, it might be exposed in some clever way. + +## repository + +Specify the place where your code lives. This is helpful for people who +want to contribute. If the git repo is on github, then the `npm docs` +command will be able to find you. + +Do it like this: + + "repository" : + { "type" : "git" + , "url" : "http://github.com/isaacs/npm.git" + } + + "repository" : + { "type" : "svn" + , "url" : "http://v8.googlecode.com/svn/trunk/" + } + +The URL should be a publicly available (perhaps read-only) url that can be handed +directly to a VCS program without any modification. It should not be a url to an +html project page that you put in your browser. It's for computers. + +## scripts + +The "scripts" member is an object hash of script commands that are run +at various times in the lifecycle of your package. The key is the lifecycle +event, and the value is the command to run at that point. + +See `npm-scripts(1)` to find out more about writing package scripts. + +## config + +A "config" hash can be used to set configuration +parameters used in package scripts that persist across upgrades. For +instance, if a package had the following: + + { "name" : "foo" + , "config" : { "port" : "8080" } } + +and then had a "start" command that then referenced the +`npm_package_config_port` environment variable, then the user could +override that by doing `npm config set foo:port 8001`. + +See `npm-config(1)` and `npm-scripts(1)` for more on package +configs. + +## dependencies + +Dependencies are specified with a simple hash of package name to version +range. The version range is EITHER a string which has one or more +space-separated descriptors, OR a range like "fromVersion - toVersion" + +**Please do not put test harnesses in your `dependencies` hash.** See +`devDependencies`, below. + +Version range descriptors may be any of the following styles, where "version" +is a semver compatible version identifier. + +* `version` Must match `version` exactly +* `=version` Same as just `version` +* `>version` Must be greater than `version` +* `>=version` etc +* `=version1 <=version2`. +* `range1 || range2` Passes if either range1 or range2 are satisfied. +* `git...` See 'Git URLs as Dependencies' below + +For example, these are all valid: + + { "dependencies" : + { "foo" : "1.0.0 - 2.9999.9999" + , "bar" : ">=1.0.2 <2.1.2" + , "baz" : ">1.0.2 <=2.3.4" + , "boo" : "2.0.1" + , "qux" : "<1.0.0 || >=2.3.1 <2.4.5 || >=2.5.2 <3.0.0" + , "asd" : "http://asdf.com/asdf.tar.gz" + , "til" : "~1.2" + , "elf" : "~1.2.3" + , "two" : "2.x" + , "thr" : "3.3.x" + } + } + +### Tilde Version Ranges + +A range specifier starting with a tilde `~` character is matched against +a version in the following fashion. + +* The version must be at least as high as the range. +* The version must be less than the next major revision above the range. + +For example, the following are equivalent: + +* `"~1.2.3" = ">=1.2.3 <1.3.0"` +* `"~1.2" = ">=1.2.0 <2.0.0"` +* `"~1" = ">=1.0.0 <2.0.0"` + +### X Version Ranges + +An "x" in a version range specifies that the version number must start +with the supplied digits, but any digit may be used in place of the x. + +The following are equivalent: + +* `"1.2.x" = ">=1.2.0 <1.3.0"` +* `"1.x.x" = ">=1.0.0 <2.0.0"` +* `"1.2" = "1.2.x"` +* `"1.x" = "1.x.x"` +* `"1" = "1.x.x"` + +You may not supply a comparator with a version containing an x. Any +digits after the first "x" are ignored. + +### URLs as Dependencies + +Starting with npm version 0.2.14, you may specify a tarball URL in place +of a version range. + +This tarball will be downloaded and installed locally to your package at +install time. + +### Git URLs as Dependencies + +Git urls can be of the form: + + git://github.com/user/project.git#commit-ish + git+ssh://user@hostname:project.git#commit-ish + git+ssh://user@hostname/project.git#commit-ish + git+http://user@hostname/project/blah.git#commit-ish + git+https://user@hostname/project/blah.git#commit-ish + +The `commit-ish` can be any tag, sha, or branch which can be supplied as +an argument to `git checkout`. The default is `master`. + +## devDependencies + +If someone is planning on downloading and using your module in their +program, then they probably don't want or need to download and build +the external test or documentation framework that you use. + +In this case, it's best to list these additional items in a +`devDependencies` hash. + +These things will be installed whenever the `--dev` configuration flag +is set. This flag is set automatically when doing `npm link`, and can +be managed like any other npm configuration param. See `npm-config(1)` +for more on the topic. + +## bundledDependencies + +Array of package names that will be bundled when publishing the package. + +If this is spelled `"bundleDependencies"`, then that is also honorable. + +## optionalDependencies + +If a dependency can be used, but you would like npm to proceed if it +cannot be found or fails to install, then you may put it in the +`optionalDependencies` hash. This is a map of package name to version +or url, just like the `dependencies` hash. The difference is that +failure is tolerated. + +It is still your program's responsibility to handle the lack of the +dependency. For example, something like this: + + try { + var foo = require('foo') + var fooVersion = require('foo/package.json').version + } catch (er) { + foo = null + } + if ( notGoodFooVersion(fooVersion) ) { + foo = null + } + + // .. then later in your program .. + + if (foo) { + foo.doFooThings() + } + +Entries in `optionalDependencies` will override entries of the same name in +`dependencies`, so it's usually best to only put in one place. + +## engines + +You can specify the version of node that your stuff works on: + + { "engines" : { "node" : ">=0.1.27 <0.1.30" } } + +And, like with dependencies, if you don't specify the version (or if you +specify "\*" as the version), then any version of node will do. + +If you specify an "engines" field, then npm will require that "node" be +somewhere on that list. If "engines" is omitted, then npm will just assume +that it works on node. + +You can also use the "engines" field to specify which versions of npm +are capable of properly installing your program. For example: + + { "engines" : { "npm" : "~1.0.20" } } + +Note that, unless the user has set the `engine-strict` config flag, this +field is advisory only. + +## engineStrict + +If you are sure that your module will *definitely not* run properly on +versions of Node/npm other than those specified in the `engines` hash, +then you can set `"engineStrict": true` in your package.json file. +This will override the user's `engine-strict` config setting. + +Please do not do this unless you are really very very sure. If your +engines hash is something overly restrictive, you can quite easily and +inadvertently lock yourself into obscurity and prevent your users from +updating to new versions of Node. Consider this choice carefully. If +people abuse it, it will be removed in a future version of npm. + +## os + +You can specify which operating systems your +module will run on: + + "os" : [ "darwin", "linux" ] + +You can also blacklist instead of whitelist operating systems, +just prepend the blacklisted os with a '!': + + "os" : [ "!win32" ] + +The host operating system is determined by `process.platform` + +It is allowed to both blacklist, and whitelist, although there isn't any +good reason to do this. + +## cpu + +If your code only runs on certain cpu architectures, +you can specify which ones. + + "cpu" : [ "x64", "ia32" ] + +Like the `os` option, you can also blacklist architectures: + + "cpu" : [ "!arm", "!mips" ] + +The host architecture is determined by `process.arch` + +## preferGlobal + +If your package is primarily a command-line application that should be +installed globally, then set this value to `true` to provide a warning +if it is installed locally. + +It doesn't actually prevent users from installing it locally, but it +does help prevent some confusion if it doesn't work as expected. + +## private + +If you set `"private": true` in your package.json, then npm will refuse +to publish it. + +This is a way to prevent accidental publication of private repositories. +If you would like to ensure that a given package is only ever published +to a specific registry (for example, an internal registry), +then use the `publishConfig` hash described below +to override the `registry` config param at publish-time. + +## publishConfig + +This is a set of config values that will be used at publish-time. It's +especially handy if you want to set the tag or registry, so that you can +ensure that a given package is not tagged with "latest" or published to +the global public registry by default. + +Any config values can be overridden, but of course only "tag" and +"registry" probably matter for the purposes of publishing. + +See `npm-config(1)` to see the list of config options that can be +overridden. + +## SEE ALSO + +* npm-semver(1) +* npm-init(1) +* npm-version(1) +* npm-config(1) +* npm-help(1) +* npm-faq(1) +* npm-install(1) +* npm-publish(1) +* npm-rm(1) diff --git a/node-v0.8.14/deps/npm/doc/cli/link.md b/node-v0.8.14/deps/npm/doc/cli/link.md new file mode 100644 index 0000000..dd54792 --- /dev/null +++ b/node-v0.8.14/deps/npm/doc/cli/link.md @@ -0,0 +1,57 @@ +npm-link(1) -- Symlink a package folder +======================================= + +## SYNOPSIS + + npm link (in package folder) + npm link + +## DESCRIPTION + +Package linking is a two-step process. + +First, `npm link` in a package folder will create a globally-installed +symbolic link from `prefix/package-name` to the current folder. + +Next, in some other location, `npm link package-name` will create a +symlink from the local `node_modules` folder to the global symlink. + +When creating tarballs for `npm publish`, the linked packages are +"snapshotted" to their current state by resolving the symbolic links. + +This is +handy for installing your own stuff, so that you can work on it and test it +iteratively without having to continually rebuild. + +For example: + + cd ~/projects/node-redis # go into the package directory + npm link # creates global link + cd ~/projects/node-bloggy # go into some other package directory. + npm link redis # link-install the package + +Now, any changes to ~/projects/node-redis will be reflected in +~/projects/node-bloggy/node_modules/redis/ + +You may also shortcut the two steps in one. For example, to do the +above use-case in a shorter way: + + cd ~/projects/node-bloggy # go into the dir of your main project + npm link ../node-redis # link the dir of your dependency + +The second line is the equivalent of doing: + + (cd ../node-redis; npm link) + npm link redis + +That is, it first creates a global link, and then links the global +installation target into your project's `node_modules` folder. + +## SEE ALSO + +* npm-developers(1) +* npm-faq(1) +* npm-json(1) +* npm-install(1) +* npm-folders(1) +* npm-config(1) diff --git a/node-v0.8.14/deps/npm/doc/cli/ls.md b/node-v0.8.14/deps/npm/doc/cli/ls.md new file mode 100644 index 0000000..3dd709b --- /dev/null +++ b/node-v0.8.14/deps/npm/doc/cli/ls.md @@ -0,0 +1,68 @@ +npm-ls(1) -- List installed packages +====================================== + +## SYNOPSIS + + npm list [ ...] + npm ls [ ...] + npm la [ ...] + npm ll [ ...] + +## DESCRIPTION + +This command will print to stdout all the versions of packages that are +installed, as well as their dependencies, in a tree-structure. + +Positional arguments are `name@version-range` identifiers, which will +limit the results to only the paths to the packages named. Note that +nested packages will *also* show the paths to the specified packages. +For example, running `npm ls promzard` in npm's source tree will show: + + npm@@VERSION@ /path/to/npm + └─┬ init-package-json@0.0.4 + └── promzard@0.1.5 + +It will show print out extraneous, missing, and invalid packages. + +When run as `ll` or `la`, it shows extended information by default. + +## CONFIGURATION + +### json + +* Default: false +* Type: Boolean + +Show information in JSON format. + +### long + +* Default: false +* Type: Boolean + +Show extended information. + +### parseable + +* Default: false +* Type: Boolean + +Show parseable output instead of tree view. + +### global + +* Default: false +* Type: Boolean + +List packages in the global install prefix instead of in the current +project. + +## SEE ALSO + +* npm-config(1) +* npm-folders(1) +* npm-install(1) +* npm-link(1) +* npm-prune(1) +* npm-outdated(1) +* npm-update(1) diff --git a/node-v0.8.14/deps/npm/doc/cli/npm.md b/node-v0.8.14/deps/npm/doc/cli/npm.md new file mode 100644 index 0000000..a325fdf --- /dev/null +++ b/node-v0.8.14/deps/npm/doc/cli/npm.md @@ -0,0 +1,155 @@ +npm(1) -- node package manager +============================== + +## SYNOPSIS + + npm [args] + +## VERSION + +@VERSION@ + +## DESCRIPTION + +npm is the package manager for the Node JavaScript platform. It puts +modules in place so that node can find them, and manages dependency +conflicts intelligently. + +It is extremely configurable to support a wide variety of use cases. +Most commonly, it is used to publish, discover, install, and develop node +programs. + +Run `npm help` to get a list of available commands. + +## INTRODUCTION + +You probably got npm because you want to install stuff. + +Use `npm install blerg` to install the latest version of "blerg". Check out +`npm-install(1)` for more info. It can do a lot of stuff. + +Use the `npm search` command to show everything that's available. +Use `npm ls` to show everything you've installed. + +## DIRECTORIES + +See `npm-folders(1)` to learn about where npm puts stuff. + +In particular, npm has two modes of operation: + +* global mode: + npm installs packages into the install prefix at + `prefix/lib/node_modules` and bins are installed in `prefix/bin`. +* local mode: + npm installs packages into the current project directory, which + defaults to the current working directory. Packages are installed to + `./node_modules`, and bins are installed to `./node_modules/.bin`. + +Local mode is the default. Use `--global` or `-g` on any command to +operate in global mode instead. + +## DEVELOPER USAGE + +If you're using npm to develop and publish your code, check out the +following help topics: + +* json: + Make a package.json file. See `npm-json(1)`. +* link: + For linking your current working code into Node's path, so that you + don't have to reinstall every time you make a change. Use + `npm link` to do this. +* install: + It's a good idea to install things if you don't need the symbolic link. + Especially, installing other peoples code from the registry is done via + `npm install` +* adduser: + Create an account or log in. Credentials are stored in the + user config file. +* publish: + Use the `npm publish` command to upload your code to the registry. + +## CONFIGURATION + +npm is extremely configurable. It reads its configuration options from +5 places. + +* Command line switches: + Set a config with `--key val`. All keys take a value, even if they + are booleans (the config parser doesn't know what the options are at + the time of parsing.) If no value is provided, then the option is set + to boolean `true`. +* Environment Variables: + Set any config by prefixing the name in an environment variable with + `npm_config_`. For example, `export npm_config_key=val`. +* User Configs: + The file at $HOME/.npmrc is an ini-formatted list of configs. If + present, it is parsed. If the `userconfig` option is set in the cli + or env, then that will be used instead. +* Global Configs: + The file found at ../etc/npmrc (from the node executable, by default + this resolves to /usr/local/etc/npmrc) will be parsed if it is found. + If the `globalconfig` option is set in the cli, env, or user config, + then that file is parsed instead. +* Defaults: + npm's default configuration options are defined in + lib/utils/config-defs.js. These must not be changed. + +See `npm-config(1)` for much much more information. + +## CONTRIBUTIONS + +Patches welcome! + +* code: + Read through `npm-coding-style(1)` if you plan to submit code. + You don't have to agree with it, but you do have to follow it. +* docs: + If you find an error in the documentation, edit the appropriate markdown + file in the "doc" folder. (Don't worry about generating the man page.) + +Contributors are listed in npm's `package.json` file. You can view them +easily by doing `npm view npm contributors`. + +If you would like to contribute, but don't know what to work on, check +the issues list or ask on the mailing list. + +* +* + +## BUGS + +When you find issues, please report them: + +* web: + +* email: + + +Be sure to include *all* of the output from the npm command that didn't work +as expected. The `npm-debug.log` file is also helpful to provide. + +You can also look for isaacs in #node.js on irc://irc.freenode.net. He +will no doubt tell you to put the output in a gist or email. + +## HISTORY + +See npm-changelog(1) + +## AUTHOR + +[Isaac Z. Schlueter](http://blog.izs.me/) :: +[isaacs](https://github.com/isaacs/) :: +[@izs](http://twitter.com/izs) :: + + +## SEE ALSO + +* npm-help(1) +* npm-faq(1) +* README +* npm-json(1) +* npm-install(1) +* npm-config(1) +* npm-index(1) +* npm(3) diff --git a/node-v0.8.14/deps/npm/doc/cli/outdated.md b/node-v0.8.14/deps/npm/doc/cli/outdated.md new file mode 100644 index 0000000..78df4a8 --- /dev/null +++ b/node-v0.8.14/deps/npm/doc/cli/outdated.md @@ -0,0 +1,17 @@ +npm-outdated(1) -- Check for outdated packages +============================================== + +## SYNOPSIS + + npm outdated [ [ ...]] + +## DESCRIPTION + +This command will check the registry to see if any (or, specific) installed +packages are currently outdated. + +## SEE ALSO + +* npm-update(1) +* npm-registry(1) +* npm-folders(1) diff --git a/node-v0.8.14/deps/npm/doc/cli/owner.md b/node-v0.8.14/deps/npm/doc/cli/owner.md new file mode 100644 index 0000000..902e083 --- /dev/null +++ b/node-v0.8.14/deps/npm/doc/cli/owner.md @@ -0,0 +1,33 @@ +npm-owner(1) -- Manage package owners +===================================== + +## SYNOPSIS + + npm owner ls + npm owner add + npm owner rm + +## DESCRIPTION + +Manage ownership of published packages. + +* ls: + List all the users who have access to modify a package and push new versions. + Handy when you need to know who to bug for help. +* add: + Add a new user as a maintainer of a package. This user is enabled to modify + metadata, publish new versions, and add other owners. +* rm: + Remove a user from the package owner list. This immediately revokes their + privileges. + +Note that there is only one level of access. Either you can modify a package, +or you can't. Future versions may contain more fine-grained access levels, but +that is not implemented at this time. + +## SEE ALSO + +* npm-publish(1) +* npm-registry(1) +* npm-adduser(1) +* npm-disputes(1) diff --git a/node-v0.8.14/deps/npm/doc/cli/pack.md b/node-v0.8.14/deps/npm/doc/cli/pack.md new file mode 100644 index 0000000..98d8c81 --- /dev/null +++ b/node-v0.8.14/deps/npm/doc/cli/pack.md @@ -0,0 +1,25 @@ +npm-pack(1) -- Create a tarball from a package +============================================== + +## SYNOPSIS + + npm pack [ [ ...]] + +## DESCRIPTION + +For anything that's installable (that is, a package folder, tarball, +tarball url, name@tag, name@version, or name), this command will fetch +it to the cache, and then copy the tarball to the current working +directory as `-.tgz`, and then write the filenames out to +stdout. + +If the same package is specified multiple times, then the file will be +overwritten the second time. + +If no arguments are supplied, then npm packs the current package folder. + +## SEE ALSO + +* npm-cache(1) +* npm-publish(1) +* npm-config(1) diff --git a/node-v0.8.14/deps/npm/doc/cli/prefix.md b/node-v0.8.14/deps/npm/doc/cli/prefix.md new file mode 100644 index 0000000..f6247ca --- /dev/null +++ b/node-v0.8.14/deps/npm/doc/cli/prefix.md @@ -0,0 +1,17 @@ +npm-prefix(1) -- Display prefix +=============================== + +## SYNOPSIS + + npm prefix + +## DESCRIPTION + +Print the prefix to standard out. + +## SEE ALSO + +* npm-root(1) +* npm-bin(1) +* npm-folders(1) +* npm-config(1) diff --git a/node-v0.8.14/deps/npm/doc/cli/prune.md b/node-v0.8.14/deps/npm/doc/cli/prune.md new file mode 100644 index 0000000..8c4b957 --- /dev/null +++ b/node-v0.8.14/deps/npm/doc/cli/prune.md @@ -0,0 +1,21 @@ +npm-prune(1) -- Remove extraneous packages +========================================== + +## SYNOPSIS + + npm prune [ [ + npm publish + +## DESCRIPTION + +Publishes a package to the registry so that it can be installed by name. + +* ``: + A folder containing a package.json file + +* ``: + A url or file path to a gzipped tar archive containing a single folder + with a package.json file inside. + +Fails if the package name and version combination already exists in +the registry. Overwrites when the "--force" flag is set. + +## SEE ALSO + +* npm-registry(1) +* npm-adduser(1) +* npm-owner(1) +* npm-deprecate(1) +* npm-tag(1) diff --git a/node-v0.8.14/deps/npm/doc/cli/rebuild.md b/node-v0.8.14/deps/npm/doc/cli/rebuild.md new file mode 100644 index 0000000..6985a7b --- /dev/null +++ b/node-v0.8.14/deps/npm/doc/cli/rebuild.md @@ -0,0 +1,20 @@ +npm-rebuild(1) -- Rebuild a package +=================================== + +## SYNOPSIS + + npm rebuild [ [ ...]] + +* ``: + The package to rebuild + +## DESCRIPTION + +This command runs the `npm build` command on the matched folders. This is useful +when you install a new version of node, and must recompile all your C++ addons with +the new binary. + +## SEE ALSO + +* npm-build(1) +* npm-install(1) diff --git a/node-v0.8.14/deps/npm/doc/cli/registry.md b/node-v0.8.14/deps/npm/doc/cli/registry.md new file mode 100644 index 0000000..44ddd94 --- /dev/null +++ b/node-v0.8.14/deps/npm/doc/cli/registry.md @@ -0,0 +1,93 @@ +npm-registry(1) -- The JavaScript Package Registry +================================================== + +## DESCRIPTION + +To resolve packages by name and version, npm talks to a registry website +that implements the CommonJS Package Registry specification for reading +package info. + +Additionally, npm's package registry implementation supports several +write APIs as well, to allow for publishing packages and managing user +account information. + +The official public npm registry is at . It +is powered by a CouchDB database at +. The code for the couchapp is +available at . npm user accounts +are CouchDB users, stored in the +database. + +The registry URL is supplied by the `registry` config parameter. See +`npm-config(1)` for more on managing npm's configuration. + +## Can I run my own private registry? + +Yes! + +The easiest way is to replicate the couch database, and use the same (or +similar) design doc to implement the APIs. + +If you set up continuous replication from the official CouchDB, and then +set your internal CouchDB as the registry config, then you'll be able +to read any published packages, in addition to your private ones, and by +default will only publish internally. If you then want to publish a +package for the whole world to see, you can simply override the +`--registry` config for that command. + +## I don't want my package published in the official registry. It's private. + +Set `"private": true` in your package.json to prevent it from being +published at all, or +`"publishConfig":{"registry":"http://my-internal-registry.local"}` +to force it to be published only to your internal registry. + +See `npm-json(1)` for more info on what goes in the package.json file. + +## Will you replicate from my registry into the public one? + +No. If you want things to be public, then publish them into the public +registry using npm. What little security there is would be for nought +otherwise. + +## Do I have to use couchdb to build a registry that npm can talk to? + +No, but it's way easier. + +## I published something elsewhere, and want to tell the npm registry about it. + +That is supported, but not using the npm client. You'll have to get +your hands dirty and do some HTTP. The request looks something like +this: + + PUT /my-foreign-package + content-type:application/json + accept:application/json + authorization:Basic $base_64_encoded + + { "name":"my-foreign-package" + , "maintainers":["owner","usernames"] + , "description":"A package that is hosted elsewhere" + , "keywords":["nih","my cheese smells the best"] + , "url":"http://my-different-registry.com/blerg/my-local-package" + } + +(Keywords and description are optional, but recommended. Name, +maintainers, and url are required.) + +Then, when a user tries to install "my-foreign-package", it'll redirect +to your registry. If that doesn't resolve to a valid package entry, +then it'll fail, so please make sure that you understand the spec, and +ask for help on the mailing list. + +## Is there a website or something to see package docs and such? + +No, but such a thing is planned, and a tiny bit developed. + +Stay tuned! + +## SEE ALSO + +* npm-config(1) +* npm-developers(1) +* npm-disputes(1) diff --git a/node-v0.8.14/deps/npm/doc/cli/removing-npm.md b/node-v0.8.14/deps/npm/doc/cli/removing-npm.md new file mode 100644 index 0000000..bedd28a --- /dev/null +++ b/node-v0.8.14/deps/npm/doc/cli/removing-npm.md @@ -0,0 +1,54 @@ +npm-removal(1) -- Cleaning the Slate +==================================== + +## SYNOPSIS + +So sad to see you go. + + sudo npm uninstall npm -g + +Or, if that fails, get the npm source code, and do: + + sudo make uninstall + +## More Severe Uninstalling + +Usually, the above instructions are sufficient. That will remove +npm, but leave behind anything you've installed. + +If that doesn't work, or if you require more drastic measures, +continue reading. + +Note that this is only necessary for globally-installed packages. Local +installs are completely contained within a project's `node_modules` +folder. Delete that folder, and everything is gone (unless a package's +install script is particularly ill-behaved). + +This assumes that you installed node and npm in the default place. If +you configured node with a different `--prefix`, or installed npm with a +different prefix setting, then adjust the paths accordingly, replacing +`/usr/local` with your install prefix. + +To remove everything npm-related manually: + + rm -rf /usr/local/{lib/node{,/.npm,_modules},bin,share/man}/npm* + +If you installed things *with* npm, then your best bet is to uninstall +them with npm first, and then install them again once you have a +proper install. This can help find any symlinks that are lying +around: + + ls -laF /usr/local/{lib/node{,/.npm},bin,share/man} | grep npm + +Prior to version 0.3, npm used shim files for executables and node +modules. To track those down, you can do the following: + + find /usr/local/{lib/node,bin} -exec grep -l npm \{\} \; ; + +(This is also in the README file.) + +## SEE ALSO + +* README +* npm-rm(1) +* npm-prune(1) diff --git a/node-v0.8.14/deps/npm/doc/cli/restart.md b/node-v0.8.14/deps/npm/doc/cli/restart.md new file mode 100644 index 0000000..6139dbe --- /dev/null +++ b/node-v0.8.14/deps/npm/doc/cli/restart.md @@ -0,0 +1,22 @@ +npm-restart(1) -- Start a package +================================= + +## SYNOPSIS + + npm restart + +## DESCRIPTION + +This runs a package's "restart" script, if one was provided. +Otherwise it runs package's "stop" script, if one was provided, and then +the "start" script. + +If no version is specified, then it restarts the "active" version. + +## SEE ALSO + +* npm-run-script(1) +* npm-scripts(1) +* npm-test(1) +* npm-start(1) +* npm-stop(1) diff --git a/node-v0.8.14/deps/npm/doc/cli/root.md b/node-v0.8.14/deps/npm/doc/cli/root.md new file mode 100644 index 0000000..3e41995 --- /dev/null +++ b/node-v0.8.14/deps/npm/doc/cli/root.md @@ -0,0 +1,17 @@ +npm-root(1) -- Display npm root +=============================== + +## SYNOPSIS + + npm root + +## DESCRIPTION + +Print the effective `node_modules` folder to standard out. + +## SEE ALSO + +* npm-prefix(1) +* npm-bin(1) +* npm-folders(1) +* npm-config(1) diff --git a/node-v0.8.14/deps/npm/doc/cli/run-script.md b/node-v0.8.14/deps/npm/doc/cli/run-script.md new file mode 100644 index 0000000..41ef5e7 --- /dev/null +++ b/node-v0.8.14/deps/npm/doc/cli/run-script.md @@ -0,0 +1,21 @@ +npm-run-script(1) -- Run arbitrary package scripts +================================================== + +## SYNOPSIS + + npm run-script + diff --git a/node-v0.8.14/deps/npm/html/api/bugs.html b/node-v0.8.14/deps/npm/html/api/bugs.html new file mode 100644 index 0000000..33d5c55 --- /dev/null +++ b/node-v0.8.14/deps/npm/html/api/bugs.html @@ -0,0 +1,60 @@ + + + bugs + + + + +
+

bugs

Bugs for a package in a web browser maybe

+ +

SYNOPSIS

+ +
npm.commands.bugs(package, callback)
+ +

DESCRIPTION

+ +

This command tries to guess at the likely location of a package's +bug tracker URL, and then tries to open it using the --browser +config param.

+ +

Like other commands, the first parameter is an array. This command only +uses the first element, which is expected to be a package name with an +optional version number.

+ +

This command will launch a browser, so this command may not be the most +friendly for programmatic use.

+
+ + + diff --git a/node-v0.8.14/deps/npm/html/api/commands.html b/node-v0.8.14/deps/npm/html/api/commands.html new file mode 100644 index 0000000..3a497c1 --- /dev/null +++ b/node-v0.8.14/deps/npm/html/api/commands.html @@ -0,0 +1,63 @@ + + + commands + + + + +
+

commands

npm commands

+ +

SYNOPSIS

+ +
npm.commands[<command>](args, callback)
+ +

DESCRIPTION

+ +

npm comes with a full set of commands, and each of the commands takes a +similar set of arguments.

+ +

In general, all commands on the command object take an array of positional +argument strings. The last argument to any function is a callback. Some +commands are special and take other optional arguments.

+ +

All commands have their own man page. See man npm-<command> for command-line +usage, or man 3 npm-<command> for programmatic usage.

+ +

SEE ALSO

+ + +
+ + + diff --git a/node-v0.8.14/deps/npm/html/api/config.html b/node-v0.8.14/deps/npm/html/api/config.html new file mode 100644 index 0000000..9689b08 --- /dev/null +++ b/node-v0.8.14/deps/npm/html/api/config.html @@ -0,0 +1,68 @@ + + + config + + + + +
+

config

Manage the npm configuration files

+ +

SYNOPSIS

+ +
npm.commands.config(args, callback)
+var val = npm.config.get(key)
+npm.config.set(key, val)
+ +

DESCRIPTION

+ +

This function acts much the same way as the command-line version. The first +element in the array tells config what to do. Possible values are:

+ +
  • set

    Sets a config parameter. The second element in args is interpreted as the +key, and the third element is interpreted as the value.

  • get

    Gets the value of a config parameter. The second element in args is the +key to get the value of.

  • delete (rm or del)

    Deletes a parameter from the config. The second element in args is the +key to delete.

  • list (ls)

    Show all configs that aren't secret. No parameters necessary.

  • edit:

    Opens the config file in the default editor. This command isn't very useful +programmatically, but it is made available.

+ +

To programmatically access npm configuration settings, or set them for +the duration of a program, use the npm.config.set and npm.config.get +functions instead.

+ +

SEE ALSO

+ + +
+ + + diff --git a/node-v0.8.14/deps/npm/html/api/deprecate.html b/node-v0.8.14/deps/npm/html/api/deprecate.html new file mode 100644 index 0000000..8319186 --- /dev/null +++ b/node-v0.8.14/deps/npm/html/api/deprecate.html @@ -0,0 +1,65 @@ + + + deprecate + + + + +
+

deprecate

Deprecate a version of a package

+ +

SYNOPSIS

+ +
npm.commands.deprecate(args, callback)
+ +

DESCRIPTION

+ +

This command will update the npm registry entry for a package, providing +a deprecation warning to all who attempt to install it.

+ +

The 'args' parameter must have exactly two elements:

+ +
  • package[@version]

    The version portion is optional, and may be either a range, or a +specific version, or a tag.

  • message

    The warning message that will be printed whenever a user attempts to +install the package.

+ +

Note that you must be the package owner to deprecate something. See the +owner and adduser help topics.

+ +

SEE ALSO

+ + +
+ + + diff --git a/node-v0.8.14/deps/npm/html/api/docs.html b/node-v0.8.14/deps/npm/html/api/docs.html new file mode 100644 index 0000000..6118079 --- /dev/null +++ b/node-v0.8.14/deps/npm/html/api/docs.html @@ -0,0 +1,60 @@ + + + docs + + + + +
+

docs

Docs for a package in a web browser maybe

+ +

SYNOPSIS

+ +
npm.commands.docs(package, callback)
+ +

DESCRIPTION

+ +

This command tries to guess at the likely location of a package's +documentation URL, and then tries to open it using the --browser +config param.

+ +

Like other commands, the first parameter is an array. This command only +uses the first element, which is expected to be a package name with an +optional version number.

+ +

This command will launch a browser, so this command may not be the most +friendly for programmatic use.

+
+ + + diff --git a/node-v0.8.14/deps/npm/html/api/edit.html b/node-v0.8.14/deps/npm/html/api/edit.html new file mode 100644 index 0000000..baf0e8d --- /dev/null +++ b/node-v0.8.14/deps/npm/html/api/edit.html @@ -0,0 +1,65 @@ + + + edit + + + + +
+

edit

Edit an installed package

+ +

SYNOPSIS

+ +
npm.commands.edit(package, callback)
+ +

DESCRIPTION

+ +

Opens the package folder in the default editor (or whatever you've +configured as the npm editor config -- see npm help config.)

+ +

After it has been edited, the package is rebuilt so as to pick up any +changes in compiled packages.

+ +

For instance, you can do npm install connect to install connect +into your package, and then npm.commands.edit(["connect"], callback) +to make a few changes to your locally installed copy.

+ +

The first parameter is a string array with a single element, the package +to open. The package can optionally have a version number attached.

+ +

Since this command opens an editor in a new process, be careful about where +and how this is used.

+
+ + + diff --git a/node-v0.8.14/deps/npm/html/api/explore.html b/node-v0.8.14/deps/npm/html/api/explore.html new file mode 100644 index 0000000..9bd45a6 --- /dev/null +++ b/node-v0.8.14/deps/npm/html/api/explore.html @@ -0,0 +1,59 @@ + + + explore + + + + +
+

explore

Browse an installed package

+ +

SYNOPSIS

+ +
npm.commands.explore(args, callback)
+ +

DESCRIPTION

+ +

Spawn a subshell in the directory of the installed package specified.

+ +

If a command is specified, then it is run in the subshell, which then +immediately terminates.

+ +

Note that the package is not automatically rebuilt afterwards, so be +sure to use npm rebuild <pkg> if you make any changes.

+ +

The first element in the 'args' parameter must be a package name. After that is the optional command, which can be any number of strings. All of the strings will be combined into one, space-delimited command.

+
+ + + diff --git a/node-v0.8.14/deps/npm/html/api/help-search.html b/node-v0.8.14/deps/npm/html/api/help-search.html new file mode 100644 index 0000000..ac85471 --- /dev/null +++ b/node-v0.8.14/deps/npm/html/api/help-search.html @@ -0,0 +1,67 @@ + + + help-search + + + + +
+

help-search

Search the help pages

+ +

SYNOPSIS

+ +
npm.commands.helpSearch(args, [silent,] callback)
+ +

DESCRIPTION

+ +

This command is rarely useful, but it exists in the rare case that it is.

+ +

This command takes an array of search terms and returns the help pages that +match in order of best match.

+ +

If there is only one match, then npm displays that help section. If there +are multiple results, the results are printed to the screen formatted and the +array of results is returned. Each result is an object with these properties:

+ +
  • hits: +A map of args to number of hits on that arg. For example, {"npm": 3}
  • found: +Total number of unique args that matched.
  • totalHits: +Total number of hits.
  • lines: +An array of all matching lines (and some adjacent lines).
  • file: +Name of the file that matched
+ +

The silent parameter is not neccessary not used, but it may in the future.

+
+ + + diff --git a/node-v0.8.14/deps/npm/html/api/init.html b/node-v0.8.14/deps/npm/html/api/init.html new file mode 100644 index 0000000..3cdeb49 --- /dev/null +++ b/node-v0.8.14/deps/npm/html/api/init.html @@ -0,0 +1,70 @@ + + + init + + + + +
+

npm init(3)

Interactively create a package.json file

+ +

SYNOPSIS

+ +
npm.commands.init(args, callback)
+ +

DESCRIPTION

+ +

This will ask you a bunch of questions, and then write a package.json for you.

+ +

It attempts to make reasonable guesses about what you want things to be set to, +and then writes a package.json file with the options you've selected.

+ +

If you already have a package.json file, it'll read that first, and default to +the options in there.

+ +

It is strictly additive, so it does not delete options from your package.json +without a really good reason to do so.

+ +

Since this function expects to be run on the command-line, it doesn't work very +well as a programmatically. The best option is to roll your own, and since +JavaScript makes it stupid simple to output formatted JSON, that is the +preferred method. If you're sure you want to handle command-line prompting, +then go ahead and use this programmatically.

+ +

SEE ALSO

+ +

json(1)

+
+ + + diff --git a/node-v0.8.14/deps/npm/html/api/install.html b/node-v0.8.14/deps/npm/html/api/install.html new file mode 100644 index 0000000..926daed --- /dev/null +++ b/node-v0.8.14/deps/npm/html/api/install.html @@ -0,0 +1,60 @@ + + + install + + + + +
+

install

install a package programmatically

+ +

SYNOPSIS

+ +
npm.commands.install([where,] packages, callback)
+ +

DESCRIPTION

+ +

This acts much the same ways as installing on the command-line.

+ +

The 'where' parameter is optional and only used internally, and it specifies +where the packages should be installed to.

+ +

The 'packages' parameter is an array of strings. Each element in the array is +the name of a package to be installed.

+ +

Finally, 'callback' is a function that will be called when all packages have been +installed or when an error has been encountered.

+
+ + + diff --git a/node-v0.8.14/deps/npm/html/api/link.html b/node-v0.8.14/deps/npm/html/api/link.html new file mode 100644 index 0000000..b240696 --- /dev/null +++ b/node-v0.8.14/deps/npm/html/api/link.html @@ -0,0 +1,74 @@ + + + link + + + + +
+

link

Symlink a package folder

+ +

SYNOPSIS

+ +
npm.command.link(callback)
+npm.command.link(packages, callback)
+ +

DESCRIPTION

+ +

Package linking is a two-step process.

+ +

Without parameters, link will create a globally-installed +symbolic link from prefix/package-name to the current folder.

+ +

With a parameters, link will create a symlink from the local node_modules +folder to the global symlink.

+ +

When creating tarballs for npm publish, the linked packages are +"snapshotted" to their current state by resolving the symbolic links.

+ +

This is +handy for installing your own stuff, so that you can work on it and test it +iteratively without having to continually rebuild.

+ +

For example:

+ +
npm.commands.link(cb)           # creates global link from the cwd
+                                # (say redis package)
+npm.commands.link('redis', cb)  # link-install the package
+ +

Now, any changes to the redis package will be reflected in +the package in the current working directory

+
+ + + diff --git a/node-v0.8.14/deps/npm/html/api/load.html b/node-v0.8.14/deps/npm/html/api/load.html new file mode 100644 index 0000000..81f0817 --- /dev/null +++ b/node-v0.8.14/deps/npm/html/api/load.html @@ -0,0 +1,67 @@ + + + load + + + + +
+

load

Load config settings

+ +

SYNOPSIS

+ +
npm.load(conf, cb)
+ +

DESCRIPTION

+ +

npm.load() must be called before any other function call. Both parameters are +optional, but the second is recommended.

+ +

The first parameter is an object hash of command-line config params, and the +second parameter is a callback that will be called when npm is loaded and +ready to serve.

+ +

The first parameter should follow a similar structure as the package.json +config object.

+ +

For example, to emulate the --dev flag, pass an object that looks like this:

+ +
{
+  "dev": true
+}
+ +

For a list of all the available command-line configs, see npm help config

+
+ + + diff --git a/node-v0.8.14/deps/npm/html/api/ls.html b/node-v0.8.14/deps/npm/html/api/ls.html new file mode 100644 index 0000000..96888bd --- /dev/null +++ b/node-v0.8.14/deps/npm/html/api/ls.html @@ -0,0 +1,94 @@ + + + ls + + + + +
+

ls

List installed packages

+ +

SYNOPSIS

+ +
npm.commands.ls(args, [silent,] callback)
+ +

DESCRIPTION

+ +

This command will print to stdout all the versions of packages that are +installed, as well as their dependencies, in a tree-structure. It will also +return that data using the callback.

+ +

This command does not take any arguments, but args must be defined. +Beyond that, if any arguments are passed in, npm will politely warn that it +does not take positional arguments, though you may set config flags +like with any other command, such as global to list global packages.

+ +

It will print out extraneous, missing, and invalid packages.

+ +

If the silent parameter is set to true, nothing will be output to the screen, +but the data will still be returned.

+ +

Callback is provided an error if one occurred, the full data about which +packages are installed and which dependencies they will receive, and a +"lite" data object which just shows which versions are installed where. +Note that the full data object is a circular structure, so care must be +taken if it is serialized to JSON.

+ +

CONFIGURATION

+ +

long

+ +
  • Default: false
  • Type: Boolean
+ +

Show extended information.

+ +

parseable

+ +
  • Default: false
  • Type: Boolean
+ +

Show parseable output instead of tree view.

+ +

global

+ +
  • Default: false
  • Type: Boolean
+ +

List packages in the global install prefix instead of in the current +project.

+ +

Note, if parseable is set or long isn't set, then duplicates will be trimmed. +This means that if a submodule a same dependency as a parent module, then the +dependency will only be output once.

+
+ + + diff --git a/node-v0.8.14/deps/npm/html/api/npm.html b/node-v0.8.14/deps/npm/html/api/npm.html new file mode 100644 index 0000000..9f50cdf --- /dev/null +++ b/node-v0.8.14/deps/npm/html/api/npm.html @@ -0,0 +1,126 @@ + + + npm + + + + +
+

npm

node package manager

+ +

SYNOPSIS

+ +
var npm = require("npm")
+npm.load(configObject, function (er, npm) {
+  // use the npm object, now that it's loaded.
+
+  npm.config.set(key, val)
+  val = npm.config.get(key)
+
+  console.log("prefix = %s", npm.prefix)
+
+  npm.commands.install(["package"], cb)
+})
+ +

VERSION

+ +

1.1.65

+ +

DESCRIPTION

+ +

This is the API documentation for npm. +To find documentation of the command line +client, see npm(1).

+ +

Prior to using npm's commands, +npm.load() must be called with an object hash of +top-level configs. In the npm command line client, +this set of configs is parsed from the command line options. Additional +configuration params are loaded from two configuration files. See +config(1) for more information.

+ +

After that, each of the functions are accessible in the +commands object: npm.commands.<cmd>. See index(1) for a list of +all possible commands.

+ +

All commands on the command object take an array of positional argument +strings. The last argument to any function is a callback. Some +commands take other optional arguments.

+ +

Configs cannot currently be set on a per function basis, as each call to +npm.config.set will change the value for all npm commands in that process.

+ +

To find API documentation for a specific command, run the npm apihelp +command.

+ +

METHODS AND PROPERTIES

+ +
  • npm.load(configs, cb)

    Load the configuration params, and call the cb function once the +globalconfig and userconfig files have been loaded as well, or on +nextTick if they've already been loaded.

  • npm.config

    An object for accessing npm configuration parameters.

    • npm.config.get(key)

    • npm.config.set(key, val)
    • npm.config.del(key)

  • npm.dir or npm.root

    The node_modules directory where npm will operate.

  • npm.prefix

    The prefix where npm is operating. (Most often the current working +directory.)

  • npm.cache

    The place where npm keeps JSON and tarballs it fetches from the +registry (or uploads to the registry).

  • npm.tmp

    npm's temporary working directory.

  • npm.deref

    Get the "real" name for a command that has either an alias or +abbreviation.

+ +

MAGIC

+ +

For each of the methods in the npm.commands hash, a method is added to +the npm object, which takes a set of positional string arguments rather +than an array and a callback.

+ +

If the last argument is a callback, then it will use the supplied +callback. However, if no callback is provided, then it will print out +the error or results.

+ +

For example, this would work in a node repl:

+ +
> npm = require("npm")
+> npm.load()  // wait a sec...
+> npm.install("dnode", "express")
+ +

Note that that won't work in a node program, since the install +method will get called before the configuration load is completed.

+ +

ABBREVS

+ +

In order to support npm ins foo instead of npm install foo, the +npm.commands object has a set of abbreviations as well as the full +method names. Use the npm.deref method to find the real name.

+ +

For example:

+ +
var cmd = npm.deref("unp") // cmd === "unpublish"
+
+ + + diff --git a/node-v0.8.14/deps/npm/html/api/outdated.html b/node-v0.8.14/deps/npm/html/api/outdated.html new file mode 100644 index 0000000..b57f7b0 --- /dev/null +++ b/node-v0.8.14/deps/npm/html/api/outdated.html @@ -0,0 +1,54 @@ + + + outdated + + + + +
+

outdated

Check for outdated packages

+ +

SYNOPSIS

+ +
npm.commands.outdated([packages,] callback)
+ +

DESCRIPTION

+ +

This command will check the registry to see if the specified packages are +currently outdated.

+ +

If the 'packages' parameter is left out, npm will check all packages.

+
+ + + diff --git a/node-v0.8.14/deps/npm/html/api/owner.html b/node-v0.8.14/deps/npm/html/api/owner.html new file mode 100644 index 0000000..2d2891b --- /dev/null +++ b/node-v0.8.14/deps/npm/html/api/owner.html @@ -0,0 +1,69 @@ + + + owner + + + + +
+

owner

Manage package owners

+ +

SYNOPSIS

+ +
npm.commands.owner(args, callback)
+ +

DESCRIPTION

+ +

The first element of the 'args' parameter defines what to do, and the subsequent +elements depend on the action. Possible values for the action are (order of +parameters are given in parenthesis):

+ +
  • ls (package): +List all the users who have access to modify a package and push new versions. +Handy when you need to know who to bug for help.
  • add (user, package): +Add a new user as a maintainer of a package. This user is enabled to modify +metadata, publish new versions, and add other owners.
  • rm (user, package): +Remove a user from the package owner list. This immediately revokes their +privileges.
+ +

Note that there is only one level of access. Either you can modify a package, +or you can't. Future versions may contain more fine-grained access levels, but +that is not implemented at this time.

+ +

SEE ALSO

+ + +
+ + + diff --git a/node-v0.8.14/deps/npm/html/api/pack.html b/node-v0.8.14/deps/npm/html/api/pack.html new file mode 100644 index 0000000..dbfc41b --- /dev/null +++ b/node-v0.8.14/deps/npm/html/api/pack.html @@ -0,0 +1,60 @@ + + + pack + + + + +
+

pack

Create a tarball from a package

+ +

SYNOPSIS

+ +
npm.commands.pack([packages,] callback)
+ +

DESCRIPTION

+ +

For anything that's installable (that is, a package folder, tarball, +tarball url, name@tag, name@version, or name), this command will fetch +it to the cache, and then copy the tarball to the current working +directory as <name>-<version>.tgz, and then write the filenames out to +stdout.

+ +

If the same package is specified multiple times, then the file will be +overwritten the second time.

+ +

If no arguments are supplied, then npm packs the current package folder.

+
+ + + diff --git a/node-v0.8.14/deps/npm/html/api/prefix.html b/node-v0.8.14/deps/npm/html/api/prefix.html new file mode 100644 index 0000000..429fd82 --- /dev/null +++ b/node-v0.8.14/deps/npm/html/api/prefix.html @@ -0,0 +1,56 @@ + + + prefix + + + + +
+

prefix

Display prefix

+ +

SYNOPSIS

+ +
npm.commands.prefix(args, callback)
+ +

DESCRIPTION

+ +

Print the prefix to standard out.

+ +

'args' is never used and callback is never called with data. +'args' must be present or things will break.

+ +

This function is not useful programmatically

+
+ + + diff --git a/node-v0.8.14/deps/npm/html/api/prune.html b/node-v0.8.14/deps/npm/html/api/prune.html new file mode 100644 index 0000000..447082f --- /dev/null +++ b/node-v0.8.14/deps/npm/html/api/prune.html @@ -0,0 +1,58 @@ + + + prune + + + + +
+

prune

Remove extraneous packages

+ +

SYNOPSIS

+ +
npm.commands.prune([packages,] callback)
+ +

DESCRIPTION

+ +

This command removes "extraneous" packages.

+ +

The first parameter is optional, and it specifies packages to be removed.

+ +

No packages are specified, then all packages will be checked.

+ +

Extraneous packages are packages that are not listed on the parent +package's dependencies list.

+
+ + + diff --git a/node-v0.8.14/deps/npm/html/api/publish.html b/node-v0.8.14/deps/npm/html/api/publish.html new file mode 100644 index 0000000..13247ad --- /dev/null +++ b/node-v0.8.14/deps/npm/html/api/publish.html @@ -0,0 +1,67 @@ + + + publish + + + + +
+

publish

Publish a package

+ +

SYNOPSIS

+ +
npm.commands.publish([packages,] callback)
+ +

DESCRIPTION

+ +

Publishes a package to the registry so that it can be installed by name. +Possible values in the 'packages' array are:

+ +
  • <folder>: +A folder containing a package.json file

  • <tarball>: +A url or file path to a gzipped tar archive containing a single folder +with a package.json file inside.

+ +

If the package array is empty, npm will try to publish something in the +current working directory.

+ +

This command could fails if one of the packages specified already exists in +the registry. Overwrites when the "force" environment variable is set.

+ +

SEE ALSO

+ + +
+ + + diff --git a/node-v0.8.14/deps/npm/html/api/rebuild.html b/node-v0.8.14/deps/npm/html/api/rebuild.html new file mode 100644 index 0000000..18352a9 --- /dev/null +++ b/node-v0.8.14/deps/npm/html/api/rebuild.html @@ -0,0 +1,57 @@ + + + rebuild + + + + +
+

rebuild

Rebuild a package

+ +

SYNOPSIS

+ +
npm.commands.rebuild([packages,] callback)
+ +

DESCRIPTION

+ +

This command runs the npm build command on each of the matched packages. This is useful +when you install a new version of node, and must recompile all your C++ addons with +the new binary. If no 'packages' parameter is specify, every package will be rebuilt.

+ +

CONFIGURATION

+ +

See npm help build

+
+ + + diff --git a/node-v0.8.14/deps/npm/html/api/restart.html b/node-v0.8.14/deps/npm/html/api/restart.html new file mode 100644 index 0000000..8e60c8a --- /dev/null +++ b/node-v0.8.14/deps/npm/html/api/restart.html @@ -0,0 +1,62 @@ + + + restart + + + + +
+

restart

Start a package

+ +

SYNOPSIS

+ +
npm.commands.restart(packages, callback)
+ +

DESCRIPTION

+ +

This runs a package's "restart" script, if one was provided. +Otherwise it runs package's "stop" script, if one was provided, and then +the "start" script.

+ +

If no version is specified, then it restarts the "active" version.

+ +

npm can run tests on multiple packages. Just specify multiple packages +in the packages parameter.

+ +

SEE ALSO

+ + +
+ + + diff --git a/node-v0.8.14/deps/npm/html/api/root.html b/node-v0.8.14/deps/npm/html/api/root.html new file mode 100644 index 0000000..14d238d --- /dev/null +++ b/node-v0.8.14/deps/npm/html/api/root.html @@ -0,0 +1,56 @@ + + + root + + + + +
+

root

Display npm root

+ +

SYNOPSIS

+ +
npm.commands.root(args, callback)
+ +

DESCRIPTION

+ +

Print the effective node_modules folder to standard out.

+ +

'args' is never used and callback is never called with data. +'args' must be present or things will break.

+ +

This function is not useful programmatically.

+
+ + + diff --git a/node-v0.8.14/deps/npm/html/api/run-script.html b/node-v0.8.14/deps/npm/html/api/run-script.html new file mode 100644 index 0000000..ba34435 --- /dev/null +++ b/node-v0.8.14/deps/npm/html/api/run-script.html @@ -0,0 +1,64 @@ + + + run-script + + + + +
+

run-script

Run arbitrary package scripts

+ +

SYNOPSIS

+ +
npm.commands.run-script(args, callback)
+ +

DESCRIPTION

+ +

This runs an arbitrary command from a package's "scripts" object.

+ +

It is used by the test, start, restart, and stop commands, but can be +called directly, as well.

+ +

The 'args' parameter is an array of strings. Behavior depends on the number +of elements. If there is only one element, npm assumes that the element +represents a command to be run on the local repository. If there is more than +one element, then the first is assumed to be the package and the second is +assumed to be the command to run. All other elements are ignored.

+ +

SEE ALSO

+ + +
+ + + diff --git a/node-v0.8.14/deps/npm/html/api/search.html b/node-v0.8.14/deps/npm/html/api/search.html new file mode 100644 index 0000000..3b8ab16 --- /dev/null +++ b/node-v0.8.14/deps/npm/html/api/search.html @@ -0,0 +1,67 @@ + + + search + + + + +
+

search

Search for packages

+ +

SYNOPSIS

+ +
npm.commands.search(searchTerms, [silent,] [staleness,] callback)
+ +

DESCRIPTION

+ +

Search the registry for packages matching the search terms. The available parameters are:

+ +
  • searchTerms: +Array of search terms. These terms are case-insensitive.
  • silent: +If true, npm will not log anything to the console.
  • staleness: +This is the threshold for stale packages. "Fresh" packages are not refreshed +from the registry. This value is measured in seconds.
  • callback: +Returns an object where each key is the name of a package, and the value +is information about that package along with a 'words' property, which is +a space-delimited string of all of the interesting words in that package. +The only properties included are those that are searched, which generally include:

    • name
    • description
    • maintainers
    • url
    • keywords
+ +

A search on the registry excludes any result that does not match all of the +search terms. It also removes any items from the results that contain an +excluded term (the "searchexclude" config). The search is case insensitive +and doesn't try to read your mind (it doesn't do any verb tense matching or the +like).

+
+ + + diff --git a/node-v0.8.14/deps/npm/html/api/shrinkwrap.html b/node-v0.8.14/deps/npm/html/api/shrinkwrap.html new file mode 100644 index 0000000..7bdd0e0 --- /dev/null +++ b/node-v0.8.14/deps/npm/html/api/shrinkwrap.html @@ -0,0 +1,61 @@ + + + shrinkwrap + + + + +
+

shrinkwrap

programmatically generate package shrinkwrap file

+ +

SYNOPSIS

+ +
npm.commands.shrinkwrap(args, [silent,] callback)
+ +

DESCRIPTION

+ +

This acts much the same ways as shrinkwrapping on the command-line.

+ +

This command does not take any arguments, but 'args' must be defined. +Beyond that, if any arguments are passed in, npm will politely warn that it +does not take positional arguments.

+ +

If the 'silent' parameter is set to true, nothing will be output to the screen, +but the shrinkwrap file will still be written.

+ +

Finally, 'callback' is a function that will be called when the shrinkwrap has +been saved.

+
+ + + diff --git a/node-v0.8.14/deps/npm/html/api/start.html b/node-v0.8.14/deps/npm/html/api/start.html new file mode 100644 index 0000000..cc13ac2 --- /dev/null +++ b/node-v0.8.14/deps/npm/html/api/start.html @@ -0,0 +1,54 @@ + + + start + + + + +
+

start

Start a package

+ +

SYNOPSIS

+ +
npm.commands.start(packages, callback)
+ +

DESCRIPTION

+ +

This runs a package's "start" script, if one was provided.

+ +

npm can run tests on multiple packages. Just specify multiple packages +in the packages parameter.

+
+ + + diff --git a/node-v0.8.14/deps/npm/html/api/stop.html b/node-v0.8.14/deps/npm/html/api/stop.html new file mode 100644 index 0000000..80952b0 --- /dev/null +++ b/node-v0.8.14/deps/npm/html/api/stop.html @@ -0,0 +1,54 @@ + + + stop + + + + +
+

stop

Stop a package

+ +

SYNOPSIS

+ +
npm.commands.stop(packages, callback)
+ +

DESCRIPTION

+ +

This runs a package's "stop" script, if one was provided.

+ +

npm can run stop on multiple packages. Just specify multiple packages +in the packages parameter.

+
+ + + diff --git a/node-v0.8.14/deps/npm/html/api/submodule.html b/node-v0.8.14/deps/npm/html/api/submodule.html new file mode 100644 index 0000000..452318f --- /dev/null +++ b/node-v0.8.14/deps/npm/html/api/submodule.html @@ -0,0 +1,68 @@ + + + submodule + + + + +
+

submodule

Add a package as a git submodule

+ +

SYNOPSIS

+ +
npm.commands.submodule(packages, callback)
+ +

DESCRIPTION

+ +

For each package specified, npm will check if it has a git repository url +in its package.json description then add it as a git submodule at +node_modules/<pkg name>.

+ +

This is a convenience only. From then on, it's up to you to manage +updates by using the appropriate git commands. npm will stubbornly +refuse to update, modify, or remove anything with a .git subfolder +in it.

+ +

This command also does not install missing dependencies, if the package +does not include them in its git repository. If npm ls reports that +things are missing, you can either install, link, or submodule them yourself, +or you can do npm explore <pkgname> -- npm install to install the +dependencies into the submodule folder.

+ +

SEE ALSO

+ +
  • npm help json
  • git help submodule
+
+ + + diff --git a/node-v0.8.14/deps/npm/html/api/tag.html b/node-v0.8.14/deps/npm/html/api/tag.html new file mode 100644 index 0000000..bd8bf63 --- /dev/null +++ b/node-v0.8.14/deps/npm/html/api/tag.html @@ -0,0 +1,64 @@ + + + tag + + + + +
+

tag

Tag a published version

+ +

SYNOPSIS

+ +
npm.commands.tag(package@version, tag, callback)
+ +

DESCRIPTION

+ +

Tags the specified version of the package with the specified tag, or the +--tag config if not specified.

+ +

The 'package@version' is an array of strings, but only the first two elements are +currently used.

+ +

The first element must be in the form package@version, where package +is the package name and version is the version number (much like installing a +specific version).

+ +

The second element is the name of the tag to tag this version with. If this +parameter is missing or falsey (empty), the default froom the config will be +used. For more information about how to set this config, check +man 3 npm-config for programmatic usage or man npm-config for cli usage.

+
+ + + diff --git a/node-v0.8.14/deps/npm/html/api/test.html b/node-v0.8.14/deps/npm/html/api/test.html new file mode 100644 index 0000000..3ef9cdc --- /dev/null +++ b/node-v0.8.14/deps/npm/html/api/test.html @@ -0,0 +1,57 @@ + + + test + + + + +
+

test

Test a package

+ +

SYNOPSIS

+ +
  npm.commands.test(packages, callback)
+ +

DESCRIPTION

+ +

This runs a package's "test" script, if one was provided.

+ +

To run tests as a condition of installation, set the npat config to +true.

+ +

npm can run tests on multiple packages. Just specify multiple packages +in the packages parameter.

+
+ + + diff --git a/node-v0.8.14/deps/npm/html/api/uninstall.html b/node-v0.8.14/deps/npm/html/api/uninstall.html new file mode 100644 index 0000000..f10ce92 --- /dev/null +++ b/node-v0.8.14/deps/npm/html/api/uninstall.html @@ -0,0 +1,57 @@ + + + uninstall + + + + +
+

uninstall

uninstall a package programmatically

+ +

SYNOPSIS

+ +
npm.commands.uninstall(packages, callback)
+ +

DESCRIPTION

+ +

This acts much the same ways as uninstalling on the command-line.

+ +

The 'packages' parameter is an array of strings. Each element in the array is +the name of a package to be uninstalled.

+ +

Finally, 'callback' is a function that will be called when all packages have been +uninstalled or when an error has been encountered.

+
+ + + diff --git a/node-v0.8.14/deps/npm/html/api/unpublish.html b/node-v0.8.14/deps/npm/html/api/unpublish.html new file mode 100644 index 0000000..3229e9c --- /dev/null +++ b/node-v0.8.14/deps/npm/html/api/unpublish.html @@ -0,0 +1,61 @@ + + + unpublish + + + + +
+

unpublish

Remove a package from the registry

+ +

SYNOPSIS

+ +
npm.commands.unpublish(package, callback)
+ +

DESCRIPTION

+ +

This removes a package version from the registry, deleting its +entry and removing the tarball.

+ +

The package parameter must be defined.

+ +

Only the first element in the package parameter is used. If there is no first +element, then npm assumes that the package at the current working directory +is what is meant.

+ +

If no version is specified, or if all versions are removed then +the root package entry is removed from the registry entirely.

+
+ + + diff --git a/node-v0.8.14/deps/npm/html/api/update.html b/node-v0.8.14/deps/npm/html/api/update.html new file mode 100644 index 0000000..e138b02 --- /dev/null +++ b/node-v0.8.14/deps/npm/html/api/update.html @@ -0,0 +1,53 @@ + + + update + + + + +
+

update

Update a package

+ +

SYNOPSIS

+ +
npm.commands.update(packages, callback)
+ +

DESCRIPTION

+ +

Updates a package, upgrading it to the latest version. It also installs any missing packages.

+ +

The 'packages' argument is an array of packages to update. The 'callback' parameter will be called when done or when an error occurs.

+
+ + + diff --git a/node-v0.8.14/deps/npm/html/api/version.html b/node-v0.8.14/deps/npm/html/api/version.html new file mode 100644 index 0000000..12b2d26 --- /dev/null +++ b/node-v0.8.14/deps/npm/html/api/version.html @@ -0,0 +1,59 @@ + + + version + + + + +
+

version

Bump a package version

+ +

SYNOPSIS

+ +
npm.commands.version(newversion, callback)
+ +

DESCRIPTION

+ +

Run this in a package directory to bump the version and write the new +data back to the package.json file.

+ +

If run in a git repo, it will also create a version commit and tag, and +fail if the repo is not clean.

+ +

Like all other commands, this function takes a string array as its first +parameter. The difference, however, is this function will fail if it does +not have exactly one element. The only element should be a version number.

+
+ + + diff --git a/node-v0.8.14/deps/npm/html/api/view.html b/node-v0.8.14/deps/npm/html/api/view.html new file mode 100644 index 0000000..49df896 --- /dev/null +++ b/node-v0.8.14/deps/npm/html/api/view.html @@ -0,0 +1,134 @@ + + + view + + + + +
+

view

View registry info

+ +

SYNOPSIS

+ +
npm.commands.view(args, [silent,] callback)
+ +

DESCRIPTION

+ +

This command shows data about a package and prints it to the stream +referenced by the outfd config, which defaults to stdout.

+ +

The "args" parameter is an ordered list that closely resembles the command-line +usage. The elements should be ordered such that the first element is +the package and version (package@version). The version is optional. After that, +the rest of the parameters are fields with optional subfields ("field.subfield") +which can be used to get only the information desired from the registry.

+ +

The callback will be passed all of the data returned by the query.

+ +

For example, to get the package registry entry for the connect package, +you can do this:

+ +
npm.commands.view(["connect"], callback)
+ +

If no version is specified, "latest" is assumed.

+ +

Field names can be specified after the package descriptor. +For example, to show the dependencies of the ronn package at version +0.3.5, you could do the following:

+ +
npm.commands.view(["ronn@0.3.5", "dependencies"], callback)
+ +

You can view child field by separating them with a period. +To view the git repository URL for the latest version of npm, you could +do this:

+ +
npm.commands.view(["npm", "repository.url"], callback)
+ +

For fields that are arrays, requesting a non-numeric field will return +all of the values from the objects in the list. For example, to get all +the contributor names for the "express" project, you can do this:

+ +
npm.commands.view(["express", "contributors.email"], callback)
+ +

You may also use numeric indices in square braces to specifically select +an item in an array field. To just get the email address of the first +contributor in the list, you can do this:

+ +
npm.commands.view(["express", "contributors[0].email"], callback)
+ +

Multiple fields may be specified, and will be printed one after another. +For exampls, to get all the contributor names and email addresses, you +can do this:

+ +
npm.commands.view(["express", "contributors.name", "contributors.email"], callback)
+ +

"Person" fields are shown as a string if they would be shown as an +object. So, for example, this will show the list of npm contributors in +the shortened string format. (See npm help json for more on this.)

+ +
npm.commands.view(["npm", "contributors"], callback)
+ +

If a version range is provided, then data will be printed for every +matching version of the package. This will show which version of jsdom +was required by each matching version of yui3:

+ +
npm.commands.view(["yui3@'>0.5.4'", "dependencies.jsdom"], callback)
+ +

OUTPUT

+ +

If only a single string field for a single version is output, then it +will not be colorized or quoted, so as to enable piping the output to +another command.

+ +

If the version range matches multiple versions, than each printed value +will be prefixed with the version it applies to.

+ +

If multiple fields are requested, than each of them are prefixed with +the field name.

+ +

Console output can be disabled by setting the 'silent' parameter to true.

+ +

RETURN VALUE

+ +

The data returned will be an object in this formation:

+ +
{ <version>:
+  { <field>: <value>
+  , ... }
+, ... }
+ +

corresponding to the list of fields selected.

+
+ + + diff --git a/node-v0.8.14/deps/npm/html/api/whoami.html b/node-v0.8.14/deps/npm/html/api/whoami.html new file mode 100644 index 0000000..51b5906 --- /dev/null +++ b/node-v0.8.14/deps/npm/html/api/whoami.html @@ -0,0 +1,56 @@ + + + whoami + + + + +
+

whoami

Display npm username

+ +

SYNOPSIS

+ +
npm.commands.whoami(args, callback)
+ +

DESCRIPTION

+ +

Print the username config to standard output.

+ +

'args' is never used and callback is never called with data. +'args' must be present or things will break.

+ +

This function is not useful programmatically

+
+ + + diff --git a/node-v0.8.14/deps/npm/html/doc/README.html b/node-v0.8.14/deps/npm/html/doc/README.html new file mode 100644 index 0000000..26bb952 --- /dev/null +++ b/node-v0.8.14/deps/npm/html/doc/README.html @@ -0,0 +1,275 @@ + + + README + + + + +
+

npm

node package manager

+ +

SYNOPSIS

+ +

This is just enough info to get you up and running.

+ +

Much more info available via npm help once it's installed.

+ +

IMPORTANT

+ +

You need node v0.6 or higher to run this program.

+ +

To install an old and unsupported version of npm that works on node 0.3 +and prior, clone the git repo and dig through the old tags and branches.

+ +

Super Easy Install

+ +

npm comes with node now.

+ +

Windows Computers

+ +

Get the MSI. npm is in it.

+ +

Apple Macintosh Computers

+ +

Get the pkg. npm is in it.

+ +

Other Sorts of Unices

+ +

Run make install. npm will be installed with node.

+ +

If you want a more fancy pants install (a different version, customized +paths, etc.) then read on.

+ +

Fancy Install (Unix)

+ +

There's a pretty robust install script at +https://npmjs.org/install.sh. You can download that and run it.

+ +

Slightly Fancier

+ +

You can set any npm configuration params with that script:

+ +

npmconfigprefix=/some/path sh install.sh

+ +

Or, you can run it in uber-debuggery mode:

+ +

npm_debug=1 sh install.sh

+ +

Even Fancier

+ +

Get the code with git. Use make to build the docs and do other stuff. +If you plan on hacking on npm, make link is your friend.

+ +

If you've got the npm source code, you can also semi-permanently set +arbitrary config keys using the ./configure --key=val ..., and then +run npm commands by doing node cli.js <cmd> <args>. (This is helpful +for testing, or running stuff without actually installing npm itself.)

+ +

Fancy Windows Install

+ +

You can download a zip file from https://npmjs.org/dist/, and unpack it +in the same folder where node.exe lives.

+ +

If that's not fancy enough for you, then you can fetch the code with +git, and mess with it directly.

+ +

Installing on Cygwin

+ +

No.

+ +

Permissions when Using npm to Install Other Stuff

+ +

tl;dr

+ +
  • Use sudo for greater safety. Or don't, if you prefer not to.
  • npm will downgrade permissions if it's root before running any build +scripts that package authors specified.
+ +

More details...

+ +

As of version 0.3, it is recommended to run npm as root. +This allows npm to change the user identifier to the nobody user prior +to running any package build or test commands.

+ +

If you are not the root user, or if you are on a platform that does not +support uid switching, then npm will not attempt to change the userid.

+ +

If you would like to ensure that npm always runs scripts as the +"nobody" user, and have it fail if it cannot downgrade permissions, then +set the following configuration param:

+ +
npm config set unsafe-perm false
+ +

This will prevent running in unsafe mode, even as non-root users.

+ +

Uninstalling

+ +

So sad to see you go.

+ +
sudo npm uninstall npm -g
+ +

Or, if that fails,

+ +
sudo make uninstall
+ +

More Severe Uninstalling

+ +

Usually, the above instructions are sufficient. That will remove +npm, but leave behind anything you've installed.

+ +

If you would like to remove all the packages that you have installed, +then you can use the npm ls command to find them, and then npm rm to +remove them.

+ +

To remove cruft left behind by npm 0.x, you can use the included +clean-old.sh script file. You can run it conveniently like this:

+ +
npm explore npm -g -- sh scripts/clean-old.sh
+ +

npm uses two configuration files, one for per-user configs, and another +for global (every-user) configs. You can view them by doing:

+ +
npm config get userconfig   # defaults to ~/.npmrc
+npm config get globalconfig # defaults to /usr/local/etc/npmrc
+ +

Uninstalling npm does not remove configuration files by default. You +must remove them yourself manually if you want them gone. Note that +this means that future npm installs will not remember the settings that +you have chosen.

+ +

Using npm Programmatically

+ +

If you would like to use npm programmatically, you can do that. +It's not very well documented, but it is rather simple.

+ +

Most of the time, unless you actually want to do all the things that +npm does, you should try using one of npm's dependencies rather than +using npm itself, if possible.

+ +

Eventually, npm will be just a thin cli wrapper around the modules +that it depends on, but for now, there are some things that you must +use npm itself to do.

+ +
var npm = require("npm")
+npm.load(myConfigObject, function (er) {
+  if (er) return handlError(er)
+  npm.commands.install(["some", "args"], function (er, data) {
+    if (er) return commandFailed(er)
+    // command succeeded, and data might have some info
+  })
+  npm.on("log", function (message) { .... })
+})
+ +

The load function takes an object hash of the command-line configs. +The various npm.commands.<cmd> functions take an array of +positional argument strings. The last argument to any +npm.commands.<cmd> function is a callback. Some commands take other +optional arguments. Read the source.

+ +

You cannot set configs individually for any single npm function at this +time. Since npm is a singleton, any call to npm.config.set will +change the value for all npm commands in that process.

+ +

See ./bin/npm-cli.js for an example of pulling config values off of the +command line arguments using nopt. You may also want to check out npm +help config to learn about all the options you can set there.

+ +

More Docs

+ +

Check out the docs, +especially the faq.

+ +

You can use the npm help command to read any of them.

+ +

If you're a developer, and you want to use npm to publish your program, +you should read this

+ + + +

"npm" and "the npm registry" are owned by Isaac Z. Schlueter. All +rights not explicitly granted in the MIT license are reserved. See the +included LICENSE file for more details.

+ +

"Node.js" and "node" are trademarks owned by Joyent, Inc. npm is not +officially part of the Node.js project, and is neither owned by nor +officially affiliated with Joyent, Inc.

+ +

The packages in the npm registry are not part of npm itself, and are the +sole property of their respective maintainers. While every effort is +made to ensure accountability, there is absolutely no guarantee, +warrantee, or assertion made as to the quality, fitness for a specific +purpose, or lack of malice in any given npm package. Modules +published on the npm registry are not affiliated with or endorsed by +Joyent, Inc., Isaac Z. Schlueter, Ryan Dahl, or the Node.js project.

+ +

If you have a complaint about a package in the npm registry, and cannot +resolve it with the package owner, please express your concerns to +Isaac Z. Schlueter at i@izs.me.

+ +

In plain english

+ +

This is mine; not my employer's, not Node's, not Joyent's, not Ryan +Dahl's.

+ +

If you publish something, it's yours, and you are solely accountable +for it. Not me, not Node, not Joyent, not Ryan Dahl.

+ +

If other people publish something, it's theirs. Not mine, not Node's, +not Joyent's, not Ryan Dahl's.

+ +

Yes, you can publish something evil. It will be removed promptly if +reported, and we'll lose respect for you. But there is no vetting +process for published modules.

+ +

If this concerns you, inspect the source before using packages.

+ +

BUGS

+ +

When you find issues, please report them:

+ + + +

Be sure to include all of the output from the npm command that didn't work +as expected. The npm-debug.log file is also helpful to provide.

+ +

You can also look for isaacs in #node.js on irc://irc.freenode.net. He +will no doubt tell you to put the output in a gist or email.

+ +

SEE ALSO

+ + +
+ + + diff --git a/node-v0.8.14/deps/npm/html/doc/adduser.html b/node-v0.8.14/deps/npm/html/doc/adduser.html new file mode 100644 index 0000000..936f7ec --- /dev/null +++ b/node-v0.8.14/deps/npm/html/doc/adduser.html @@ -0,0 +1,74 @@ + + + adduser + + + + +
+

adduser

Add a registry user account

+ +

SYNOPSIS

+ +
npm adduser
+ +

DESCRIPTION

+ +

Create or verify a user named <username> in the npm registry, and +save the credentials to the .npmrc file.

+ +

The username, password, and email are read in from prompts.

+ +

You may use this command to change your email address, but not username +or password.

+ +

To reset your password, go to http://admin.npmjs.org/

+ +

You may use this command multiple times with the same user account to +authorize on a new machine.

+ +

CONFIGURATION

+ +

registry

+ +

Default: http://registry.npmjs.org/

+ +

The base URL of the npm package registry.

+ +

SEE ALSO

+ + +
+ + + diff --git a/node-v0.8.14/deps/npm/html/doc/bin.html b/node-v0.8.14/deps/npm/html/doc/bin.html new file mode 100644 index 0000000..66a64b1 --- /dev/null +++ b/node-v0.8.14/deps/npm/html/doc/bin.html @@ -0,0 +1,55 @@ + + + bin + + + + +
+

bin

Display npm bin folder

+ +

SYNOPSIS

+ +
npm bin
+ +

DESCRIPTION

+ +

Print the folder where npm will install executables.

+ +

SEE ALSO

+ + +
+ + + diff --git a/node-v0.8.14/deps/npm/html/doc/bugs.html b/node-v0.8.14/deps/npm/html/doc/bugs.html new file mode 100644 index 0000000..09173d6 --- /dev/null +++ b/node-v0.8.14/deps/npm/html/doc/bugs.html @@ -0,0 +1,71 @@ + + + bugs + + + + +
+

bugs

Bugs for a package in a web browser maybe

+ +

SYNOPSIS

+ +
npm bugs <pkgname>
+ +

DESCRIPTION

+ +

This command tries to guess at the likely location of a package's +bug tracker URL, and then tries to open it using the --browser +config param.

+ +

CONFIGURATION

+ +

browser

+ +
  • Default: OS X: "open", others: "google-chrome"
  • Type: String
+ +

The browser that is called by the npm bugs command to open websites.

+ +

registry

+ +
  • Default: https://registry.npmjs.org/
  • Type: url
+ +

The base URL of the npm package registry.

+ +

SEE ALSO

+ + +
+ + + diff --git a/node-v0.8.14/deps/npm/html/doc/build.html b/node-v0.8.14/deps/npm/html/doc/build.html new file mode 100644 index 0000000..583af3c --- /dev/null +++ b/node-v0.8.14/deps/npm/html/doc/build.html @@ -0,0 +1,60 @@ + + + build + + + + +
+

build

Build a package

+ +

SYNOPSIS

+ +
npm build <package-folder>
+ +
  • <package-folder>: +A folder containing a package.json file in its root.
+ +

DESCRIPTION

+ +

This is the plumbing command called by npm link and npm install.

+ +

It should generally not be called directly.

+ +

SEE ALSO

+ + +
+ + + diff --git a/node-v0.8.14/deps/npm/html/doc/bundle.html b/node-v0.8.14/deps/npm/html/doc/bundle.html new file mode 100644 index 0000000..c733941 --- /dev/null +++ b/node-v0.8.14/deps/npm/html/doc/bundle.html @@ -0,0 +1,55 @@ + + + bundle + + + + +
+

bundle

REMOVED

+ +

DESCRIPTION

+ +

The npm bundle command has been removed in 1.0, for the simple reason +that it is no longer necessary, as the default behavior is now to +install packages into the local space.

+ +

Just use npm install now to do what npm bundle used to do.

+ +

SEE ALSO

+ + +
+ + + diff --git a/node-v0.8.14/deps/npm/html/doc/cache.html b/node-v0.8.14/deps/npm/html/doc/cache.html new file mode 100644 index 0000000..0096988 --- /dev/null +++ b/node-v0.8.14/deps/npm/html/doc/cache.html @@ -0,0 +1,101 @@ + + + cache + + + + +
+

cache

Manipulates packages cache

+ +

SYNOPSIS

+ +
npm cache add <tarball file>
+npm cache add <folder>
+npm cache add <tarball url>
+npm cache add <name>@<version>
+
+npm cache ls [<path>]
+
+npm cache clean [<path>]
+ +

DESCRIPTION

+ +

Used to add, list, or clear the npm cache folder.

+ +
  • add: +Add the specified package to the local cache. This command is primarily +intended to be used internally by npm, but it can provide a way to +add data to the local installation cache explicitly.

  • ls: +Show the data in the cache. Argument is a path to show in the cache +folder. Works a bit like the find program, but limited by the +depth config.

  • clean: +Delete data out of the cache folder. If an argument is provided, then +it specifies a subpath to delete. If no argument is provided, then +the entire cache is cleared.

+ +

DETAILS

+ +

npm stores cache data in $HOME/.npm. For each package that is added +to the cache, three pieces of information are stored in +{cache}/{name}/{version}:

+ +
  • .../package/: +A folder containing the package contents as they appear in the tarball.
  • .../package.json: +The package.json file, as npm sees it, with overlays applied and a _id attribute.
  • .../package.tgz: +The tarball for that version.
+ +

Additionally, whenever a registry request is made, a .cache.json file +is placed at the corresponding URI, to store the ETag and the requested +data.

+ +

Commands that make non-essential registry requests (such as search and +view, or the completion scripts) generally specify a minimum timeout. +If the .cache.json file is younger than the specified timeout, then +they do not make an HTTP request to the registry.

+ +

CONFIGURATION

+ +

cache

+ +

Default: $HOME/.npm on Posix, or $HOME/npm-cache on Windows.

+ +

The root cache folder.

+ +

SEE ALSO

+ + +
+ + + diff --git a/node-v0.8.14/deps/npm/html/doc/changelog.html b/node-v0.8.14/deps/npm/html/doc/changelog.html new file mode 100644 index 0000000..9be667e --- /dev/null +++ b/node-v0.8.14/deps/npm/html/doc/changelog.html @@ -0,0 +1,100 @@ + + + changelog + + + + +
+

changelog

Changes

+ +

HISTORY

+ +

1.1.3, 1.1.4

+ +
  • Update request to support HTTPS-over-HTTP proxy tunneling
  • Throw on undefined envs in config settings
  • Update which to 1.0.5
  • Fix windows UNC busyloop in findPrefix
  • Bundle nested bundleDependencies properly
  • Alias adduser to add-user
  • Doc updates (Christian Howe, Henrik Hodne, Andrew Lunny)
  • ignore logfd/outfd streams in makeEnv() (Rod Vagg)
  • shrinkwrap: Behave properly with url-installed deps
  • install: Support --save with url install targets
  • Support installing naked tars or single-file modules from urls etc.
  • init: Don't add engines section
  • Don't run make clean on rebuild
  • Added missing unicode replacement (atomizer)
+ +

1.1.2

+ +

Dave Pacheco (2): + add "npm shrinkwrap"

+ +

Martin Cooper (1): + Fix #1753 Make a copy of the cached objects we'll modify.

+ +

Tim Oxley (1): + correctly remove readme from default npm view command.

+ +

Tyler Green (1): + fix #2187 set terminal columns to Infinity if 0

+ +

isaacs (19): + update minimatch + update request + Experimental: single-file modules + Fix #2172 Don't remove global mans uninstalling local pkgs + Add --versions flag to show the version of node as well + Support --json flag for ls output + update request to 2.9.151

+ +

1.1

+ +
  • Replace system tar dependency with a JS tar
  • Continue to refine
+ +

1.0

+ +
  • Greatly simplified folder structure
  • Install locally (bundle by default)
  • Drastic rearchitecture
+ +

0.3

+ +
  • More correct permission/uid handling when running as root
  • Require node 0.4.0
  • Reduce featureset
  • Packages without "main" modules don't export modules
  • Remove support for invalid JSON (since node doesn't support it)
+ +

0.2

+ +
  • First allegedly "stable" release
  • Most functionality implemented
  • Used shim files and name@version symlinks
  • Feature explosion
  • Kind of a mess
+ +

0.1

+ +
  • push to beta, and announce
  • Solaris and Cygwin support
+ +

0.0

+ +
  • Lots of sketches and false starts; abandoned a few times
  • Core functionality established
+ +

SEE ALSO

+ + +
+ + + diff --git a/node-v0.8.14/deps/npm/html/doc/coding-style.html b/node-v0.8.14/deps/npm/html/doc/coding-style.html new file mode 100644 index 0000000..b0cd350 --- /dev/null +++ b/node-v0.8.14/deps/npm/html/doc/coding-style.html @@ -0,0 +1,215 @@ + + + coding-style + + + + +
+

coding-style

npm's "funny" coding style

+ +

DESCRIPTION

+ +

npm's coding style is a bit unconventional. It is not different for +difference's sake, but rather a carefully crafted style that is +designed to reduce visual clutter and make bugs more apparent.

+ +

If you want to contribute to npm (which is very encouraged), you should +make your code conform to npm's style.

+ +

Line Length

+ +

Keep lines shorter than 80 characters. It's better for lines to be +too short than to be too long. Break up long lists, objects, and other +statements onto multiple lines.

+ +

Indentation

+ +

Two-spaces. Tabs are better, but they look like hell in web browsers +(and on github), and node uses 2 spaces, so that's that.

+ +

Configure your editor appropriately.

+ +

Curly braces

+ +

Curly braces belong on the same line as the thing that necessitates them.

+ +

Bad:

+ +
function ()
+{
+ +

Good:

+ +
function () {
+ +

If a block needs to wrap to the next line, use a curly brace. Don't +use it if it doesn't.

+ +

Bad:

+ +
if (foo) { bar() }
+while (foo)
+  bar()
+ +

Good:

+ +
if (foo) bar()
+while (foo) {
+  bar()
+}
+ +

Semicolons

+ +

Don't use them except in four situations:

+ +
  • for (;;) loops. They're actually required.
  • null loops like: while (something) ; (But you'd better have a good +reason for doing that.)
  • case "foo": doSomething(); break
  • In front of a leading ( or [ at the start of the line. +This prevents the expression from being interpreted +as a function call or property access, respectively.
+ +

Some examples of good semicolon usage:

+ +
;(x || y).doSomething()
+;[a, b, c].forEach(doSomething)
+for (var i = 0; i < 10; i ++) {
+  switch (state) {
+    case "begin": start(); continue
+    case "end": finish(); break
+    default: throw new Error("unknown state")
+  }
+  end()
+}
+ +

Note that starting lines with - and + also should be prefixed +with a semicolon, but this is much less common.

+ +

Comma First

+ +

If there is a list of things separated by commas, and it wraps +across multiple lines, put the comma at the start of the next +line, directly below the token that starts the list. Put the +final token in the list on a line by itself. For example:

+ +
var magicWords = [ "abracadabra"
+                 , "gesundheit"
+                 , "ventrilo"
+                 ]
+  , spells = { "fireball" : function () { setOnFire() }
+             , "water" : function () { putOut() }
+             }
+  , a = 1
+  , b = "abc"
+  , etc
+  , somethingElse
+ +

Whitespace

+ +

Put a single space in front of ( for anything other than a function call. +Also use a single space wherever it makes things more readable.

+ +

Don't leave trailing whitespace at the end of lines. Don't indent empty +lines. Don't use more spaces than are helpful.

+ +

Functions

+ +

Use named functions. They make stack traces a lot easier to read.

+ +

Callbacks, Sync/async Style

+ +

Use the asynchronous/non-blocking versions of things as much as possible. +It might make more sense for npm to use the synchronous fs APIs, but this +way, the fs and http and child process stuff all uses the same callback-passing +methodology.

+ +

The callback should always be the last argument in the list. Its first +argument is the Error or null.

+ +

Be very careful never to ever ever throw anything. It's worse than useless. +Just send the error message back as the first argument to the callback.

+ +

Errors

+ +

Always create a new Error object with your message. Don't just return a +string message to the callback. Stack traces are handy.

+ +

Logging

+ +

Logging is done using the npmlog +utility.

+ +

Please clean up logs when they are no longer helpful. In particular, +logging the same object over and over again is not helpful. Logs should +report what's happening so that it's easier to track down where a fault +occurs.

+ +

Use appropriate log levels. See config(1) and search for +"loglevel".

+ +

Case, naming, etc.

+ +

Use lowerCamelCase for multiword identifiers when they refer to objects, +functions, methods, members, or anything not specified in this section.

+ +

Use UpperCamelCase for class names (things that you'd pass to "new").

+ +

Use all-lower-hyphen-css-case for multiword filenames and config keys.

+ +

Use named functions. They make stack traces easier to follow.

+ +

Use CAPS_SNAKE_CASE for constants, things that should never change +and are rarely used.

+ +

Use a single uppercase letter for function names where the function +would normally be anonymous, but needs to call itself recursively. It +makes it clear that it's a "throwaway" function.

+ +

null, undefined, false, 0

+ +

Boolean variables and functions should always be either true or +false. Don't set it to 0 unless it's supposed to be a number.

+ +

When something is intentionally missing or removed, set it to null.

+ +

Don't set things to undefined. Reserve that value to mean "not yet +set to anything."

+ +

Boolean objects are verboten.

+ +

SEE ALSO

+ + +
+ + + diff --git a/node-v0.8.14/deps/npm/html/doc/completion.html b/node-v0.8.14/deps/npm/html/doc/completion.html new file mode 100644 index 0000000..cbebc75 --- /dev/null +++ b/node-v0.8.14/deps/npm/html/doc/completion.html @@ -0,0 +1,68 @@ + + + completion + + + + +
+

completion

Tab Completion for npm

+ +

SYNOPSIS

+ +
. <(npm completion)
+ +

DESCRIPTION

+ +

Enables tab-completion in all npm commands.

+ +

The synopsis above +loads the completions into your current shell. Adding it to +your ~/.bashrc or ~/.zshrc will make the completions available +everywhere.

+ +

You may of course also pipe the output of npm completion to a file +such as /usr/local/etc/bash_completion.d/npm if you have a system +that will read that file for you.

+ +

When COMP_CWORD, COMP_LINE, and COMP_POINT are defined in the +environment, npm completion acts in "plumbing mode", and outputs +completions based on the arguments.

+ +

SEE ALSO

+ + +
+ + + diff --git a/node-v0.8.14/deps/npm/html/doc/config.html b/node-v0.8.14/deps/npm/html/doc/config.html new file mode 100644 index 0000000..412fc32 --- /dev/null +++ b/node-v0.8.14/deps/npm/html/doc/config.html @@ -0,0 +1,791 @@ + + + config + + + + +
+

config

Manage the npm configuration file

+ +

SYNOPSIS

+ +
npm config set <key> <value> [--global]
+npm config get <key>
+npm config delete <key>
+npm config list
+npm config edit
+npm get <key>
+npm set <key> <value> [--global]
+ +

DESCRIPTION

+ +

npm gets its configuration values from 6 sources, in this priority:

+ +

Command Line Flags

+ +

Putting --foo bar on the command line sets the +foo configuration parameter to "bar". A -- argument tells the cli +parser to stop reading flags. A --flag parameter that is at the end of +the command will be given the value of true.

+ +

Environment Variables

+ +

Any environment variables that start with npm_config_ will be interpreted +as a configuration parameter. For example, putting npm_config_foo=bar in +your environment will set the foo configuration parameter to bar. Any +environment configurations that are not given a value will be given the value +of true. Config values are case-insensitive, so NPM_CONFIG_FOO=bar will +work the same.

+ +

Per-user config file

+ +

$HOME/.npmrc (or the userconfig param, if set above)

+ +

This file is an ini-file formatted list of key = value parameters.

+ +

Global config file

+ +

$PREFIX/etc/npmrc (or the globalconfig param, if set above): +This file is an ini-file formatted list of key = value parameters

+ +

Built-in config file

+ +

path/to/npm/itself/npmrc

+ +

This is an unchangeable "builtin" +configuration file that npm keeps consistent across updates. Set +fields in here using the ./configure script that comes with npm. +This is primarily for distribution maintainers to override default +configs in a standard and consistent manner.

+ +

Default Configs

+ +

A set of configuration parameters that are internal to npm, and are +defaults if nothing else is specified.

+ +

Sub-commands

+ +

Config supports the following sub-commands:

+ +

set

+ +
npm config set key value
+ +

Sets the config key to the value.

+ +

If value is omitted, then it sets it to "true".

+ +

get

+ +
npm config get key
+ +

Echo the config value to stdout.

+ +

list

+ +
npm config list
+ +

Show all the config settings.

+ +

delete

+ +
npm config delete key
+ +

Deletes the key from all configuration files.

+ +

edit

+ +
npm config edit
+ +

Opens the config file in an editor. Use the --global flag to edit the +global config.

+ +

Shorthands and Other CLI Niceties

+ +

The following shorthands are parsed on the command-line:

+ +
  • -v: --version
  • -h, -?, --help, -H: --usage
  • -s, --silent: --loglevel silent
  • -q, --quiet: --loglevel warn
  • -d: --loglevel info
  • -dd, --verbose: --loglevel verbose
  • -ddd: --loglevel silly
  • -g: --global
  • -l: --long
  • -m: --message
  • -p, --porcelain: --parseable
  • -reg: --registry
  • -v: --version
  • -f: --force
  • -desc: --description
  • -S: --save
  • -D: --save-dev
  • -O: --save-optional
  • -B: --save-bundle
  • -y: --yes
  • -n: --yes false
  • ll and la commands: ls --long
+ +

If the specified configuration param resolves unambiguously to a known +configuration parameter, then it is expanded to that configuration +parameter. For example:

+ +
npm ls --par
+# same as:
+npm ls --parseable
+ +

If multiple single-character shorthands are strung together, and the +resulting combination is unambiguously not some other configuration +param, then it is expanded to its various component pieces. For +example:

+ +
npm ls -gpld
+# same as:
+npm ls --global --parseable --long --loglevel info
+ +

Per-Package Config Settings

+ +

When running scripts (see scripts(1)) +the package.json "config" keys are overwritten in the environment if +there is a config param of <name>[@<version>]:<key>. For example, if +the package.json has this:

+ +
{ "name" : "foo"
+, "config" : { "port" : "8080" }
+, "scripts" : { "start" : "node server.js" } }
+ +

and the server.js is this:

+ +
http.createServer(...).listen(process.env.npm_package_config_port)
+ +

then the user could change the behavior by doing:

+ +
npm config set foo:port 80
+ +

Config Settings

+ +

always-auth

+ +
  • Default: false
  • Type: Boolean
+ +

Force npm to always require authentication when accessing the registry, +even for GET requests.

+ +

browser

+ +
  • Default: OS X: "open", others: "google-chrome"
  • Type: String
+ +

The browser that is called by the npm docs command to open websites.

+ +

ca

+ +
  • Default: The npm CA certificate
  • Type: String or null
+ +

The Certificate Authority signing certificate that is trusted for SSL +connections to the registry.

+ +

Set to null to only allow "known" registrars, or to a specific CA cert +to trust only that specific signing authority.

+ +

See also the strict-ssl config.

+ +

cache

+ +
  • Default: Windows: %APPDATA%\npm-cache, Posix: ~/.npm
  • Type: path
+ +

The location of npm's cache directory. See cache(1)

+ +

cache-lock-stale

+ +
  • Default: 60000 (1 minute)
  • Type: Number
+ +

The number of ms before cache folder lockfiles are considered stale.

+ +

cache-lock-retries

+ +
  • Default: 10
  • Type: Number
+ +

Number of times to retry to acquire a lock on cache folder lockfiles.

+ +

cache-lock-wait

+ +
  • Default: 10000 (10 seconds)
  • Type: Number
+ +

Number of ms to wait for cache lock files to expire.

+ +

cache-max

+ +
  • Default: Infinity
  • Type: Number
+ +

The maximum time (in seconds) to keep items in the registry cache before +re-checking against the registry.

+ +

Note that no purging is done unless the npm cache clean command is +explicitly used, and that only GET requests use the cache.

+ +

cache-min

+ +
  • Default: 0
  • Type: Number
+ +

The minimum time (in seconds) to keep items in the registry cache before +re-checking against the registry.

+ +

Note that no purging is done unless the npm cache clean command is +explicitly used, and that only GET requests use the cache.

+ +

color

+ +
  • Default: true on Posix, false on Windows
  • Type: Boolean or "always"
+ +

If false, never shows colors. If "always" then always shows colors. +If true, then only prints color codes for tty file descriptors.

+ +

coverage

+ +
  • Default: false
  • Type: Boolean
+ +

A flag to tell test-harness to run with their coverage options enabled, +if they respond to the npm_config_coverage environment variable.

+ +

depth

+ +
  • Default: Infinity
  • Type: Number
+ +

The depth to go when recursing directories for npm ls and +npm cache ls.

+ +

description

+ +
  • Default: true
  • Type: Boolean
+ +

Show the description in npm search

+ +

dev

+ +
  • Default: false
  • Type: Boolean
+ +

Install dev-dependencies along with packages.

+ +

Note that dev-dependencies are also installed if the npat flag is +set.

+ +

editor

+ +
  • Default: EDITOR environment variable if set, or "vi" on Posix, +or "notepad" on Windows.
  • Type: path
+ +

The command to run for npm edit or npm config edit.

+ +

engine-strict

+ +
  • Default: false
  • Type: Boolean
+ +

If set to true, then npm will stubbornly refuse to install (or even +consider installing) any package that claims to not be compatible with +the current Node.js version.

+ +

force

+ +
  • Default: false
  • Type: Boolean
+ +

Makes various commands more forceful.

+ +
  • lifecycle script failure does not block progress.
  • publishing clobbers previously published versions.
  • skips cache when requesting from the registry.
  • prevents checks against clobbering non-npm files.
+ +

fetch-retries

+ +
  • Default: 2
  • Type: Number
+ +

The "retries" config for the retry module to use when fetching +packages from the registry.

+ +

fetch-retry-factor

+ +
  • Default: 10
  • Type: Number
+ +

The "factor" config for the retry module to use when fetching +packages.

+ +

fetch-retry-mintimeout

+ +
  • Default: 10000 (10 seconds)
  • Type: Number
+ +

The "minTimeout" config for the retry module to use when fetching +packages.

+ +

fetch-retry-maxtimeout

+ +
  • Default: 60000 (1 minute)
  • Type: Number
+ +

The "maxTimeout" config for the retry module to use when fetching +packages.

+ +

git

+ +
  • Default: "git"
  • Type: String
+ +

The command to use for git commands. If git is installed on the +computer, but is not in the PATH, then set this to the full path to +the git binary.

+ +

global

+ +
  • Default: false
  • Type: Boolean
+ +

Operates in "global" mode, so that packages are installed into the +prefix folder instead of the current working directory. See +folders(1) for more on the differences in behavior.

+ +
  • packages are installed into the prefix/node_modules folder, instead of the +current working directory.
  • bin files are linked to prefix/bin
  • man pages are linked to prefix/share/man
+ +

globalconfig

+ +
  • Default: {prefix}/etc/npmrc
  • Type: path
+ +

The config file to read for global config options.

+ +

globalignorefile

+ +
  • Default: {prefix}/etc/npmignore
  • Type: path
+ +

The config file to read for global ignore patterns to apply to all users +and all projects.

+ +

If not found, but there is a "gitignore" file in the +same directory, then that will be used instead.

+ +

group

+ +
  • Default: GID of the current process
  • Type: String or Number
+ +

The group to use when running package scripts in global mode as the root +user.

+ +

https-proxy

+ +
  • Default: the HTTPS_PROXY or https_proxy or HTTP_PROXY or +http_proxy environment variables.
  • Type: url
+ +

A proxy to use for outgoing https requests.

+ +

user-agent

+ +
  • Default: npm/{npm.version} node/{process.version}
  • Type: String
+ +

Sets a User-Agent to the request header

+ +

ignore

+ +
  • Default: ""
  • Type: string
+ +

A white-space separated list of glob patterns of files to always exclude +from packages when building tarballs.

+ +

init-module

+ +
  • Default: ~/.npm-init.js
  • Type: path
+ +

A module that will be loaded by the npm init command. See the +documentation for the +init-package-json module +for more information, or init(1).

+ +

init.version

+ +
  • Default: "0.0.0"
  • Type: semver
+ +

The value npm init should use by default for the package version.

+ +

init.author.name

+ +
  • Default: ""
  • Type: String
+ +

The value npm init should use by default for the package author's name.

+ +

init.author.email

+ +
  • Default: ""
  • Type: String
+ +

The value npm init should use by default for the package author's email.

+ +

init.author.url

+ +
  • Default: ""
  • Type: String
+ +

The value npm init should use by default for the package author's homepage.

+ +

json

+ +
  • Default: false
  • Type: Boolean
+ +

Whether or not to output JSON data, rather than the normal output.

+ +

This feature is currently experimental, and the output data structures +for many commands is either not implemented in JSON yet, or subject to +change. Only the output from npm ls --json is currently valid.

+ + + +
  • Default: false
  • Type: Boolean
+ +

If true, then local installs will link if there is a suitable globally +installed package.

+ +

Note that this means that local installs can cause things to be +installed into the global space at the same time. The link is only done +if one of the two conditions are met:

+ +
  • The package is not already installed globally, or
  • the globally installed version is identical to the version that is +being installed locally.
+ +

loglevel

+ +
  • Default: "http"
  • Type: String
  • Values: "silent", "win", "error", "warn", "http", "info", "verbose", "silly"
+ +

What level of logs to report. On failure, all logs are written to +npm-debug.log in the current working directory.

+ +

Any logs of a higher level than the setting are shown. +The default is "http", which shows http, warn, and error output.

+ +

logstream

+ +
  • Default: process.stderr
  • Type: Stream
+ +

This is the stream that is passed to the +npmlog module at run time.

+ +

It cannot be set from the command line, but if you are using npm +programmatically, you may wish to send logs to somewhere other than +stderr.

+ +

If the color config is set to true, then this stream will receive +colored output if it is a TTY.

+ +

long

+ +
  • Default: false
  • Type: Boolean
+ +

Show extended information in npm ls

+ +

message

+ +
  • Default: "%s"
  • Type: String
+ +

Commit message which is used by npm version when creating version commit.

+ +

Any "%s" in the message will be replaced with the version number.

+ +

node-version

+ +
  • Default: process.version
  • Type: semver or false
+ +

The node version to use when checking package's "engines" hash.

+ +

npat

+ +
  • Default: false
  • Type: Boolean
+ +

Run tests on installation and report results to the +npaturl.

+ +

npaturl

+ +
  • Default: Not yet implemented
  • Type: url
+ +

The url to report npat test results.

+ +

onload-script

+ +
  • Default: false
  • Type: path
+ +

A node module to require() when npm loads. Useful for programmatic +usage.

+ +

optional

+ +
  • Default: true
  • Type: Boolean
+ +

Attempt to install packages in the optionalDependencies hash. Note +that if these packages fail to install, the overall installation +process is not aborted.

+ +

parseable

+ +
  • Default: false
  • Type: Boolean
+ +

Output parseable results from commands that write to +standard output.

+ +

prefix

+ +
  • Default: node's process.installPrefix
  • Type: path
+ +

The location to install global items. If set on the command line, then +it forces non-global commands to run in the specified folder.

+ +

production

+ +
  • Default: false
  • Type: Boolean
+ +

Set to true to run in "production" mode.

+ +
  1. devDependencies are not installed at the topmost level when running +local npm install without any arguments.
  2. Set the NODE_ENV="production" for lifecycle scripts.
+ +

proprietary-attribs

+ +
  • Default: true
  • Type: Boolean
+ +

Whether or not to include proprietary extended attributes in the +tarballs created by npm.

+ +

Unless you are expecting to unpack package tarballs with something other +than npm -- particularly a very outdated tar implementation -- leave +this as true.

+ +

proxy

+ +
  • Default: HTTP_PROXY or http_proxy environment variable, or null
  • Type: url
+ +

A proxy to use for outgoing http requests.

+ +

rebuild-bundle

+ +
  • Default: true
  • Type: Boolean
+ +

Rebuild bundled dependencies after installation.

+ +

registry

+ +
  • Default: https://registry.npmjs.org/
  • Type: url
+ +

The base URL of the npm package registry.

+ +

rollback

+ +
  • Default: true
  • Type: Boolean
+ +

Remove failed installs.

+ +

save

+ +
  • Default: false
  • Type: Boolean
+ +

Save installed packages to a package.json file as dependencies.

+ +

When used with the npm rm command, it removes it from the dependencies +hash.

+ +

Only works if there is already a package.json file present.

+ +

save-bundle

+ +
  • Default: false
  • Type: Boolean
+ +

If a package would be saved at install time by the use of --save, +--save-dev, or --save-optional, then also put it in the +bundleDependencies list.

+ +

When used with the npm rm command, it removes it from the +bundledDependencies list.

+ +

save-dev

+ +
  • Default: false
  • Type: Boolean
+ +

Save installed packages to a package.json file as devDependencies.

+ +

When used with the npm rm command, it removes it from the devDependencies +hash.

+ +

Only works if there is already a package.json file present.

+ +

save-optional

+ +
  • Default: false
  • Type: Boolean
+ +

Save installed packages to a package.json file as optionalDependencies.

+ +

When used with the npm rm command, it removes it from the devDependencies +hash.

+ +

Only works if there is already a package.json file present.

+ +

searchopts

+ +
  • Default: ""
  • Type: String
+ +

Space-separated options that are always passed to search.

+ +

searchexclude

+ +
  • Default: ""
  • Type: String
+ +

Space-separated options that limit the results from search.

+ +

searchsort

+ +
  • Default: "name"
  • Type: String
  • Values: "name", "-name", "date", "-date", "description", +"-description", "keywords", "-keywords"
+ +

Indication of which field to sort search results by. Prefix with a - +character to indicate reverse sort.

+ +

shell

+ +
  • Default: SHELL environment variable, or "bash" on Posix, or "cmd" on +Windows
  • Type: path
+ +

The shell to run for the npm explore command.

+ +

sign-git-tag

+ +
  • Default: false
  • Type: Boolean
+ +

If set to true, then the npm version command will tag the version +using -s to add a signature.

+ +

Note that git requires you to have set up GPG keys in your git configs +for this to work properly.

+ +

strict-ssl

+ +
  • Default: true
  • Type: Boolean
+ +

Whether or not to do SSL key validation when making requests to the +registry via https.

+ +

See also the ca config.

+ +

tag

+ +
  • Default: latest
  • Type: String
+ +

If you ask npm to install a package and don't tell it a specific version, then +it will install the specified tag.

+ +

Also the tag that is added to the package@version specified by the npm +tag command, if no explicit tag is given.

+ +

tmp

+ +
  • Default: TMPDIR environment variable, or "/tmp"
  • Type: path
+ +

Where to store temporary files and folders. All temp files are deleted +on success, but left behind on failure for forensic purposes.

+ +

unicode

+ +
  • Default: true
  • Type: Boolean
+ +

When set to true, npm uses unicode characters in the tree output. When +false, it uses ascii characters to draw trees.

+ +

unsafe-perm

+ +
  • Default: false if running as root, true otherwise
  • Type: Boolean
+ +

Set to true to suppress the UID/GID switching when running package +scripts. If set explicitly to false, then installing as a non-root user +will fail.

+ +

usage

+ +
  • Default: false
  • Type: Boolean
+ +

Set to show short usage output (like the -H output) +instead of complete help when doing help(1).

+ +

user

+ +
  • Default: "nobody"
  • Type: String or Number
+ +

The UID to set to when running package scripts as root.

+ +

username

+ +
  • Default: null
  • Type: String
+ +

The username on the npm registry. Set with npm adduser

+ +

userconfig

+ +
  • Default: ~/.npmrc
  • Type: path
+ +

The location of user-level configuration settings.

+ +

userignorefile

+ +
  • Default: ~/.npmignore
  • Type: path
+ +

The location of a user-level ignore file to apply to all packages.

+ +

If not found, but there is a .gitignore file in the same directory, then +that will be used instead.

+ +

umask

+ +
  • Default: 022
  • Type: Octal numeric string
+ +

The "umask" value to use when setting the file creation mode on files +and folders.

+ +

Folders and executables are given a mode which is 0777 masked against +this value. Other files are given a mode which is 0666 masked against +this value. Thus, the defaults are 0755 and 0644 respectively.

+ +

version

+ +
  • Default: false
  • Type: boolean
+ +

If true, output the npm version and exit successfully.

+ +

Only relevant when specified explicitly on the command line.

+ +

versions

+ +
  • Default: false
  • Type: boolean
+ +

If true, output the npm version as well as node's process.versions +hash, and exit successfully.

+ +

Only relevant when specified explicitly on the command line.

+ +

viewer

+ +
  • Default: "man" on Posix, "browser" on Windows
  • Type: path
+ +

The program to use to view help content.

+ +

Set to "browser" to view html help content in the default web browser.

+ +

yes

+ +
  • Default: null
  • Type: Boolean or null
+ +

If set to null, then prompt the user for responses in some +circumstances.

+ +

If set to true, then answer "yes" to any prompt. If set to false +then answer "no" to any prompt.

+ +

SEE ALSO

+ + +
+ + + diff --git a/node-v0.8.14/deps/npm/html/doc/dedupe.html b/node-v0.8.14/deps/npm/html/doc/dedupe.html new file mode 100644 index 0000000..4b17ce1 --- /dev/null +++ b/node-v0.8.14/deps/npm/html/doc/dedupe.html @@ -0,0 +1,92 @@ + + + dedupe + + + + +
+

dedupe

Reduce duplication

+ +

SYNOPSIS

+ +
npm dedupe [package names...]
+ +

DESCRIPTION

+ +

Searches the local package tree and attempts to simplify the overall +structure by moving dependencies further up the tree, where they can +be more effectively shared by multiple dependent packages.

+ +

For example, consider this dependency graph:

+ +
a
++-- b <-- depends on c@1.0.x
+|   `-- c@1.0.3
+`-- d <-- depends on c@~1.0.9
+    `-- c@1.0.10
+ +

In this case, dedupe(1) will transform the tree to:

+ +
a
++-- b
++-- d
+`-- c@1.0.10
+ +

Because of the hierarchical nature of node's module lookup, b and d +will both get their dependency met by the single c package at the root +level of the tree.

+ +

If a suitable version exists at the target location in the tree +already, then it will be left untouched, but the other duplicates will +be deleted.

+ +

If no suitable version can be found, then a warning is printed, and +nothing is done.

+ +

If any arguments are supplied, then they are filters, and only the +named packages will be touched.

+ +

Note that this operation transforms the dependency tree, and may +result in packages getting updated versions, perhaps from the npm +registry.

+ +

This feature is experimental, and may change in future versions.

+ +

SEE ALSO

+ + +
+ + + diff --git a/node-v0.8.14/deps/npm/html/doc/deprecate.html b/node-v0.8.14/deps/npm/html/doc/deprecate.html new file mode 100644 index 0000000..a565af8 --- /dev/null +++ b/node-v0.8.14/deps/npm/html/doc/deprecate.html @@ -0,0 +1,64 @@ + + + deprecate + + + + +
+

deprecate

Deprecate a version of a package

+ +

SYNOPSIS

+ +
npm deprecate <name>[@<version>] <message>
+ +

DESCRIPTION

+ +

This command will update the npm registry entry for a package, providing +a deprecation warning to all who attempt to install it.

+ +

It works on version ranges as well as specific versions, so you can do +something like this:

+ +
npm deprecate my-thing@"< 0.2.3" "critical bug fixed in v0.2.3"
+ +

Note that you must be the package owner to deprecate something. See the +owner and adduser help topics.

+ +

SEE ALSO

+ + +
+ + + diff --git a/node-v0.8.14/deps/npm/html/doc/developers.html b/node-v0.8.14/deps/npm/html/doc/developers.html new file mode 100644 index 0000000..657ba69 --- /dev/null +++ b/node-v0.8.14/deps/npm/html/doc/developers.html @@ -0,0 +1,195 @@ + + + developers + + + + +
+

developers

Developer Guide

+ +

DESCRIPTION

+ +

So, you've decided to use npm to develop (and maybe publish/deploy) +your project.

+ +

Fantastic!

+ +

There are a few things that you need to do above the simple steps +that your users will do to install your program.

+ +

About These Documents

+ +

These are man pages. If you install npm, you should be able to +then do man npm-thing to get the documentation on a particular +topic, or npm help thing to see the same information.

+ +

What is a package

+ +

A package is:

+ +
  • a) a folder containing a program described by a package.json file
  • b) a gzipped tarball containing (a)
  • c) a url that resolves to (b)
  • d) a <name>@<version> that is published on the registry with (c)
  • e) a <name>@<tag> that points to (d)
  • f) a <name> that has a "latest" tag satisfying (e)
  • g) a git url that, when cloned, results in (a).
+ +

Even if you never publish your package, you can still get a lot of +benefits of using npm if you just want to write a node program (a), and +perhaps if you also want to be able to easily install it elsewhere +after packing it up into a tarball (b).

+ +

Git urls can be of the form:

+ +
git://github.com/user/project.git#commit-ish
+git+ssh://user@hostname:project.git#commit-ish
+git+http://user@hostname/project/blah.git#commit-ish
+git+https://user@hostname/project/blah.git#commit-ish
+ +

The commit-ish can be any tag, sha, or branch which can be supplied as +an argument to git checkout. The default is master.

+ +

The package.json File

+ +

You need to have a package.json file in the root of your project to do +much of anything with npm. That is basically the whole interface.

+ +

See json(1) for details about what goes in that file. At the very +least, you need:

+ +
  • name: +This should be a string that identifies your project. Please do not +use the name to specify that it runs on node, or is in JavaScript. +You can use the "engines" field to explicitly state the versions of +node (or whatever else) that your program requires, and it's pretty +well assumed that it's javascript.

    It does not necessarily need to match your github repository name.

    So, node-foo and bar-js are bad names. foo or bar are better.

  • version: +A semver-compatible version.

  • engines: +Specify the versions of node (or whatever else) that your program +runs on. The node API changes a lot, and there may be bugs or new +functionality that you depend on. Be explicit.

  • author: +Take some credit.

  • scripts: +If you have a special compilation or installation script, then you +should put it in the scripts hash. You should definitely have at +least a basic smoke-test command as the "scripts.test" field. +See scripts(1).

  • main: +If you have a single module that serves as the entry point to your +program (like what the "foo" package gives you at require("foo")), +then you need to specify that in the "main" field.

  • directories: +This is a hash of folders. The best ones to include are "lib" and +"doc", but if you specify a folder full of man pages in "man", then +they'll get installed just like these ones.

+ +

You can use npm init in the root of your package in order to get you +started with a pretty basic package.json file. See init(1) for +more info.

+ +

Keeping files out of your package

+ +

Use a .npmignore file to keep stuff out of your package. If there's +no .npmignore file, but there is a .gitignore file, then npm will +ignore the stuff matched by the .gitignore file. If you want to +include something that is excluded by your .gitignore file, you can +create an empty .npmignore file to override it.

+ + + +

npm link is designed to install a development package and see the +changes in real time without having to keep re-installing it. (You do +need to either re-link or npm rebuild -g to update compiled packages, +of course.)

+ +

More info at link(1).

+ +

Before Publishing: Make Sure Your Package Installs and Works

+ +

This is important.

+ +

If you can not install it locally, you'll have +problems trying to publish it. Or, worse yet, you'll be able to +publish it, but you'll be publishing a broken or pointless package. +So don't do that.

+ +

In the root of your package, do this:

+ +
npm install . -g
+ +

That'll show you that it's working. If you'd rather just create a symlink +package that points to your working directory, then do this:

+ +
npm link
+ +

Use npm ls -g to see if it's there.

+ +

To test a local install, go into some other folder, and then do:

+ +
cd ../some-other-folder
+npm install ../my-package
+ +

to install it locally into the node_modules folder in that other place.

+ +

Then go into the node-repl, and try using require("my-thing") to +bring in your module's main module.

+ +

Create a User Account

+ +

Create a user with the adduser command. It works like this:

+ +
npm adduser
+ +

and then follow the prompts.

+ +

This is documented better in adduser(1).

+ +

Publish your package

+ +

This part's easy. IN the root of your folder, do this:

+ +
npm publish
+ +

You can give publish a url to a tarball, or a filename of a tarball, +or a path to a folder.

+ +

Note that pretty much everything in that folder will be exposed +by default. So, if you have secret stuff in there, use a +.npmignore file to list out the globs to ignore, or publish +from a fresh checkout.

+ +

Brag about it

+ +

Send emails, write blogs, blab in IRC.

+ +

Tell the world how easy it is to install your program!

+ +

SEE ALSO

+ + +
+ + + diff --git a/node-v0.8.14/deps/npm/html/doc/disputes.html b/node-v0.8.14/deps/npm/html/doc/disputes.html new file mode 100644 index 0000000..1703151 --- /dev/null +++ b/node-v0.8.14/deps/npm/html/doc/disputes.html @@ -0,0 +1,115 @@ + + + disputes + + + + +
+

disputes

Handling Module Name Disputes

+ +

SYNOPSIS

+ +
  1. Get the author email with npm owner ls <pkgname>
  2. Email the author, CC i@izs.me.
  3. After a few weeks, if there's no resolution, we'll sort it out.
+ +

DESCRIPTION

+ +

There sometimes arise cases where a user publishes a module, and then +later, some other user wants to use that name. Here are some common +ways that happens (each of these is based on actual events.)

+ +
  1. Bob writes a JavaScript module foo, which is not node-specific. +Bob doesn't use node at all. Joe wants to use foo in node, so he +wraps it in an npm module. Some time later, Bob starts using node, +and wants to take over management of his program.
  2. Bob writes an npm module foo, and publishes it. Perhaps much +later, Joe finds a bug in foo, and fixes it. He sends a pull +request to Bob, but Bob doesn't have the time to deal with it, +because he has a new job and a new baby and is focused on his new +erlang project, and kind of not involved with node any more. Joe +would like to publish a new foo, but can't, because the name is +taken.
  3. Bob writes a 10-line flow-control library, and calls it foo, and +publishes it to the npm registry. Being a simple little thing, it +never really has to be updated. Joe works for Foo Inc, the makers +of the critically acclaimed and widely-marketed foo JavaScript +toolkit framework. They publish it to npm as foojs, but people are +routinely confused when npm install foo is some different thing.
  4. Bob writes a parser for the widely-known foo file format, because +he needs it for work. Then, he gets a new job, and never updates the +prototype. Later on, Joe writes a much more complete foo parser, +but can't publish, because Bob's foo is in the way.
+ +

The validity of Joe's claim in each situation can be debated. However, +Joe's appropriate course of action in each case is the same.

+ +
  1. npm owner ls foo. This will tell Joe the email address of the +owner (Bob).
  2. Joe emails Bob, explaining the situation as respecfully as possible, +and what he would like to do with the module name. He adds +isaacs i@izs.me to the CC list of the email. Mention in the email +that Bob can run npm owner add joe foo to add Joe as an owner of +the foo package.
  3. After a reasonable amount of time, if Bob has not responded, or if +Bob and Joe can't come to any sort of resolution, email isaacs +i@izs.me and we'll sort it out.
+ +

REASONING

+ +

In almost every case so far, the parties involved have been able to reach +an amicable resolution without any major intervention. Most people +really do want to be reasonable, and are probably not even aware that +they're in your way.

+ +

Module ecosystems are most vibrant and powerful when they are as +self-directed as possible. If an admin one day deletes something you +had worked on, then that is going to make most people quite upset, +regardless of the justification. When humans solve their problems by +talking to other humans with respect, everyone has the chance to end up +feeling good about the interaction.

+ +

EXCEPTIONS

+ +

Some things are not allowed, and will be removed without discussion if +they are brought to the attention of the npm registry admins, including +but not limited to:

+ +
  1. Malware (that is, a module designed to exploit or harm the machine on +which it is installed)
  2. Violations of copyright or licenses (for example, cloning an +MIT-licensed program, and then removing or changing the copyright and +license statement)
  3. Illegal content.
+ +

If you see bad behavior like this, please report it right away.

+ +

SEE ALSO

+ + +
+ + + diff --git a/node-v0.8.14/deps/npm/html/doc/docs.html b/node-v0.8.14/deps/npm/html/doc/docs.html new file mode 100644 index 0000000..c22bb5f --- /dev/null +++ b/node-v0.8.14/deps/npm/html/doc/docs.html @@ -0,0 +1,72 @@ + + + docs + + + + +
+

docs

Docs for a package in a web browser maybe

+ +

SYNOPSIS

+ +
npm docs <pkgname>
+npm home <pkgname>
+ +

DESCRIPTION

+ +

This command tries to guess at the likely location of a package's +documentation URL, and then tries to open it using the --browser +config param.

+ +

CONFIGURATION

+ +

browser

+ +
  • Default: OS X: "open", others: "google-chrome"
  • Type: String
+ +

The browser that is called by the npm docs command to open websites.

+ +

registry

+ +
  • Default: https://registry.npmjs.org/
  • Type: url
+ +

The base URL of the npm package registry.

+ +

SEE ALSO

+ + +
+ + + diff --git a/node-v0.8.14/deps/npm/html/doc/edit.html b/node-v0.8.14/deps/npm/html/doc/edit.html new file mode 100644 index 0000000..448d00e --- /dev/null +++ b/node-v0.8.14/deps/npm/html/doc/edit.html @@ -0,0 +1,72 @@ + + + edit + + + + +
+

edit

Edit an installed package

+ +

SYNOPSIS

+ +
npm edit <name>[@<version>]
+ +

DESCRIPTION

+ +

Opens the package folder in the default editor (or whatever you've +configured as the npm editor config -- see config(1).)

+ +

After it has been edited, the package is rebuilt so as to pick up any +changes in compiled packages.

+ +

For instance, you can do npm install connect to install connect +into your package, and then npm edit connect to make a few +changes to your locally installed copy.

+ +

CONFIGURATION

+ +

editor

+ +
  • Default: EDITOR environment variable if set, or "vi" on Posix, +or "notepad" on Windows.
  • Type: path
+ +

The command to run for npm edit or npm config edit.

+ +

SEE ALSO

+ + +
+ + + diff --git a/node-v0.8.14/deps/npm/html/doc/explore.html b/node-v0.8.14/deps/npm/html/doc/explore.html new file mode 100644 index 0000000..9c60bad --- /dev/null +++ b/node-v0.8.14/deps/npm/html/doc/explore.html @@ -0,0 +1,75 @@ + + + explore + + + + +
+

explore

Browse an installed package

+ +

SYNOPSIS

+ +
npm explore <name>[@<version>] [ -- <cmd>]
+ +

DESCRIPTION

+ +

Spawn a subshell in the directory of the installed package specified.

+ +

If a command is specified, then it is run in the subshell, which then +immediately terminates.

+ +

This is particularly handy in the case of git submodules in the +node_modules folder:

+ +
npm explore some-dependency -- git pull origin master
+ +

Note that the package is not automatically rebuilt afterwards, so be +sure to use npm rebuild <pkg> if you make any changes.

+ +

CONFIGURATION

+ +

shell

+ +
  • Default: SHELL environment variable, or "bash" on Posix, or "cmd" on +Windows
  • Type: path
+ +

The shell to run for the npm explore command.

+ +

SEE ALSO

+ + +
+ + + diff --git a/node-v0.8.14/deps/npm/html/doc/faq.html b/node-v0.8.14/deps/npm/html/doc/faq.html new file mode 100644 index 0000000..464d45b --- /dev/null +++ b/node-v0.8.14/deps/npm/html/doc/faq.html @@ -0,0 +1,285 @@ + + + faq + + + + +
+

faq

Frequently Asked Questions

+ +

Where can I find these docs in HTML?

+ +

https://npmjs.org/doc/, or run:

+ +
npm config set viewer browser
+ +

to open these documents in your default web browser rather than man.

+ +

It didn't work.

+ +

That's not really a question.

+ +

Why didn't it work?

+ +

I don't know yet.

+ +

Read the error output, and if you can't figure out what it means, +do what it says and post a bug with all the information it asks for.

+ +

Where does npm put stuff?

+ +

See folders(1)

+ +

tl;dr:

+ +
  • Use the npm root command to see where modules go, and the npm bin +command to see where executables go
  • Global installs are different from local installs. If you install +something with the -g flag, then its executables go in npm bin -g +and its modules go in npm root -g.
+ +

How do I install something on my computer in a central location?

+ +

Install it globally by tacking -g or --global to the command. (This +is especially important for command line utilities that need to add +their bins to the global system PATH.)

+ +

I installed something globally, but I can't require() it

+ +

Install it locally.

+ +

The global install location is a place for command-line utilities +to put their bins in the system PATH. It's not for use with require().

+ +

If you require() a module in your code, then that means it's a +dependency, and a part of your program. You need to install it locally +in your program.

+ +

Why can't npm just put everything in one place, like other package managers?

+ +

Not every change is an improvement, but every improvement is a change. +This would be like asking git to do network IO for every commit. It's +not going to happen, because it's a terrible idea that causes more +problems than it solves.

+ +

It is much harder to avoid dependency conflicts without nesting +dependencies. This is fundamental to the way that npm works, and has +proven to be an extremely successful approach. See folders(1) for +more details.

+ +

If you want a package to be installed in one place, and have all your +programs reference the same copy of it, then use the npm link command. +That's what it's for. Install it globally, then link it into each +program that uses it.

+ +

Whatever, I really want the old style 'everything global' style.

+ +

Write your own package manager, then. It's not that hard.

+ +

npm will not help you do something that is known to be a bad idea.

+ +

Should I check my node_modules folder into git?

+ +

Mikeal Rogers answered this question very well:

+ +

http://www.mikealrogers.com/posts/nodemodules-in-git.html

+ +

tl;dr

+ +
  • Check node_modules into git for things you deploy, such as +websites and apps.
  • Do not check node_modules into git for libraries and modules +intended to be reused.
  • Use npm to manage dependencies in your dev environment, but not in +your deployment scripts.
+ +

Is it 'npm' or 'NPM' or 'Npm'?

+ +

npm should never be capitalized unless it is being displayed in a +location that is customarily all-caps (such as the title of man pages.)

+ +

If 'npm' is an acronym, why is it never capitalized?

+ +

Contrary to the belief of many, "npm" is not in fact an abbreviation for +"Node Package Manager". It is a recursive bacronymic abbreviation for +"npm is not an acronym". (If it was "ninaa", then it would be an +acronym, and thus incorrectly named.)

+ +

"NPM", however, is an acronym (more precisely, a capitonym) for the +National Association of Pastoral Musicians. You can learn more +about them at http://npm.org/.

+ +

In software, "NPM" is a Non-Parametric Mapping utility written by +Chris Rorden. You can analyze pictures of brains with it. Learn more +about the (capitalized) NPM program at http://www.cabiatl.com/mricro/npm/.

+ +

The first seed that eventually grew into this flower was a bash utility +named "pm", which was a shortened descendent of "pkgmakeinst", a +bash function that was used to install various different things on different +platforms, most often using Yahoo's yinst. If npm was ever an +acronym for anything, it was node pm or maybe new pm.

+ +

So, in all seriousness, the "npm" project is named after its command-line +utility, which was organically selected to be easily typed by a right-handed +programmer using a US QWERTY keyboard layout, ending with the +right-ring-finger in a postition to type the - key for flags and +other command-line arguments. That command-line utility is always +lower-case, though it starts most sentences it is a part of.

+ +

How do I list installed packages?

+ +

npm ls

+ +

How do I search for packages?

+ +

npm search

+ +

Arguments are greps. npm search jsdom shows jsdom packages.

+ +

How do I update npm?

+ +
npm update npm -g
+ +

You can also update all outdated local packages by doing npm update without +any arguments, or global packages by doing npm update -g.

+ +

Occasionally, the version of npm will progress such that the current +version cannot be properly installed with the version that you have +installed already. (Consider, if there is ever a bug in the update +command.)

+ +

In those cases, you can do this:

+ +
curl https://npmjs.org/install.sh | sh
+ +

What is a package?

+ +

A package is:

+ +
  • a) a folder containing a program described by a package.json file
  • b) a gzipped tarball containing (a)
  • c) a url that resolves to (b)
  • d) a <name>@<version> that is published on the registry with (c)
  • e) a <name>@<tag> that points to (d)
  • f) a <name> that has a "latest" tag satisfying (e)
  • g) a git url that, when cloned, results in (a).
+ +

Even if you never publish your package, you can still get a lot of +benefits of using npm if you just want to write a node program (a), and +perhaps if you also want to be able to easily install it elsewhere +after packing it up into a tarball (b).

+ +

Git urls can be of the form:

+ +
git://github.com/user/project.git#commit-ish
+git+ssh://user@hostname:project.git#commit-ish
+git+http://user@hostname/project/blah.git#commit-ish
+git+https://user@hostname/project/blah.git#commit-ish
+ +

The commit-ish can be any tag, sha, or branch which can be supplied as +an argument to git checkout. The default is master.

+ +

How do I install node with npm?

+ +

You don't. Try one of these:

+ + + +

How can I use npm for development?

+ +

See developers(1) and json(1).

+ +

You'll most likely want to npm link your development folder. That's +awesomely handy.

+ +

To set up your own private registry, check out registry(1).

+ +

Can I list a url as a dependency?

+ +

Yes. It should be a url to a gzipped tarball containing a single folder +that has a package.json in its root, or a git url. +(See "what is a package?" above.)

+ + + +

See link(1)

+ +

The package registry website. What is that exactly?

+ +

See registry(1).

+ +

What's up with the insecure channel warnings?

+ +

Until node 0.4.10, there were problems sending big files over HTTPS. That +means that publishes go over HTTP by default in those versions of node.

+ +

I forgot my password, and can't publish. How do I reset it?

+ +

Go to https://npmjs.org/forgot.

+ +

I get ECONNREFUSED a lot. What's up?

+ +

Either the registry is down, or node's DNS isn't able to reach out.

+ +

To check if the registry is down, open up http://registry.npmjs.org/ +in a web browser. This will also tell you if you are just unable to +access the internet for some reason.

+ +

If the registry IS down, let me know by emailing or posting an issue. +We'll have someone kick it or something.

+ +

Why no namespaces?

+ +

Please see this discussion: https://github.com/isaacs/npm/issues/798

+ +

tl;dr - It doesn't actually make things better, and can make them worse.

+ +

If you want to namespace your own packages, you may: simply use the +- character to separate the names. npm is a mostly anarchic system. +There is not sufficient need to impose namespace rules on everyone.

+ +

Who does npm?

+ +

npm view npm author

+ +

npm view npm contributors

+ +

I have a question or request not addressed here. Where should I put it?

+ +

Discuss it on the mailing list, or post an issue.

+ + + +

Why does npm hate me?

+ +

npm is not capable of hatred. It loves everyone, especially you.

+ +

SEE ALSO

+ + +
+ + + diff --git a/node-v0.8.14/deps/npm/html/doc/folders.html b/node-v0.8.14/deps/npm/html/doc/folders.html new file mode 100644 index 0000000..91f8adb --- /dev/null +++ b/node-v0.8.14/deps/npm/html/doc/folders.html @@ -0,0 +1,240 @@ + + + folders + + + + +
+

folders

Folder Structures Used by npm

+ +

DESCRIPTION

+ +

npm puts various things on your computer. That's its job.

+ +

This document will tell you what it puts where.

+ +

tl;dr

+ +
  • Local install (default): puts stuff in ./node_modules of the current +package root.
  • Global install (with -g): puts stuff in /usr/local or wherever node +is installed.
  • Install it locally if you're going to require() it.
  • Install it globally if you're going to run it on the command line.
  • If you need both, then install it in both places, or use npm link.
+ +

prefix Configuration

+ +

The prefix config defaults to the location where node is installed. +On most systems, this is /usr/local, and most of the time is the same +as node's process.installPrefix.

+ +

On windows, this is the exact location of the node.exe binary. On Unix +systems, it's one level up, since node is typically installed at +{prefix}/bin/node rather than {prefix}/node.exe.

+ +

When the global flag is set, npm installs things into this prefix. +When it is not set, it uses the root of the current package, or the +current working directory if not in a package already.

+ +

Node Modules

+ +

Packages are dropped into the node_modules folder under the prefix. +When installing locally, this means that you can +require("packagename") to load its main module, or +require("packagename/lib/path/to/sub/module") to load other modules.

+ +

Global installs on Unix systems go to {prefix}/lib/node_modules. +Global installs on Windows go to {prefix}/node_modules (that is, no +lib folder.)

+ +

If you wish to require() a package, then install it locally.

+ +

Executables

+ +

When in global mode, executables are linked into {prefix}/bin on Unix, +or directly into {prefix} on Windows.

+ +

When in local mode, executables are linked into +./node_modules/.bin so that they can be made available to scripts run +through npm. (For example, so that a test runner will be in the path +when you run npm test.)

+ +

Man Pages

+ +

When in global mode, man pages are linked into {prefix}/share/man.

+ +

When in local mode, man pages are not installed.

+ +

Man pages are not installed on Windows systems.

+ +

Cache

+ +

See cache(1). Cache files are stored in ~/.npm on Posix, or +~/npm-cache on Windows.

+ +

This is controlled by the cache configuration param.

+ +

Temp Files

+ +

Temporary files are stored by default in the folder specified by the +tmp config, which defaults to the TMPDIR, TMP, or TEMP environment +variables, or /tmp on Unix and c:\windows\temp on Windows.

+ +

Temp files are given a unique folder under this root for each run of the +program, and are deleted upon successful exit.

+ +

More Information

+ +

When installing locally, npm first tries to find an appropriate +prefix folder. This is so that npm install foo@1.2.3 will install +to the sensible root of your package, even if you happen to have cded +into some other folder.

+ +

Starting at the $PWD, npm will walk up the folder tree checking for a +folder that contains either a package.json file, or a node_modules +folder. If such a thing is found, then that is treated as the effective +"current directory" for the purpose of running npm commands. (This +behavior is inspired by and similar to git's .git-folder seeking +logic when running git commands in a working dir.)

+ +

If no package root is found, then the current folder is used.

+ +

When you run npm install foo@1.2.3, then the package is loaded into +the cache, and then unpacked into ./node_modules/foo. Then, any of +foo's dependencies are similarly unpacked into +./node_modules/foo/node_modules/....

+ +

Any bin files are symlinked to ./node_modules/.bin/, so that they may +be found by npm scripts when necessary.

+ +

Global Installation

+ +

If the global configuration is set to true, then npm will +install packages "globally".

+ +

For global installation, packages are installed roughly the same way, +but using the folders described above.

+ +

Cycles, Conflicts, and Folder Parsimony

+ +

Cycles are handled using the property of node's module system that it +walks up the directories looking for node_modules folders. So, at every +stage, if a package is already installed in an ancestor node_modules +folder, then it is not installed at the current location.

+ +

Consider the case above, where foo -> bar -> baz. Imagine if, in +addition to that, baz depended on bar, so you'd have: +foo -> bar -> baz -> bar -> baz .... However, since the folder +structure is: foo/node_modules/bar/node_modules/baz, there's no need to +put another copy of bar into .../baz/node_modules, since when it calls +require("bar"), it will get the copy that is installed in +foo/node_modules/bar.

+ +

This shortcut is only used if the exact same +version would be installed in multiple nested node_modules folders. It +is still possible to have a/node_modules/b/node_modules/a if the two +"a" packages are different versions. However, without repeating the +exact same package multiple times, an infinite regress will always be +prevented.

+ +

Another optimization can be made by installing dependencies at the +highest level possible, below the localized "target" folder.

+ +

Example

+ +

Consider this dependency graph:

+ +
foo
++-- blerg@1.2.5
++-- bar@1.2.3
+|   +-- blerg@1.x (latest=1.3.7)
+|   +-- baz@2.x
+|   |   `-- quux@3.x
+|   |       `-- bar@1.2.3 (cycle)
+|   `-- asdf@*
+`-- baz@1.2.3
+    `-- quux@3.x
+        `-- bar
+ +

In this case, we might expect a folder structure like this:

+ +
foo
++-- node_modules
+    +-- blerg (1.2.5) <---[A]
+    +-- bar (1.2.3) <---[B]
+    |   +-- node_modules
+    |   |   `-- baz (2.0.2) <---[C]
+    |   |       `-- node_modules
+    |   |           `-- quux (3.2.0)
+    |   `-- asdf (2.3.4)
+    `-- baz (1.2.3) <---[D]
+        `-- node_modules
+            `-- quux (3.2.0) <---[E]
+ +

Since foo depends directly on bar@1.2.3 and baz@1.2.3, those are +installed in foo's node_modules folder.

+ +

Even though the latest copy of blerg is 1.3.7, foo has a specific +dependency on version 1.2.5. So, that gets installed at [A]. Since the +parent installation of blerg satisfie's bar's dependency on blerg@1.x, +it does not install another copy under [B].

+ +

Bar [B] also has dependencies on baz and asdf, so those are installed in +bar's node_modules folder. Because it depends on baz@2.x, it cannot +re-use the baz@1.2.3 installed in the parent node_modules folder [D], +and must install its own copy [C].

+ +

Underneath bar, the baz->quux->bar dependency creates a cycle. +However, because bar is already in quux's ancestry [B], it does not +unpack another copy of bar into that folder.

+ +

Underneath foo->baz [D], quux's [E] folder tree is empty, because its +dependency on bar is satisfied by the parent folder copy installed at [B].

+ +

For a graphical breakdown of what is installed where, use npm ls.

+ +

Publishing

+ +

Upon publishing, npm will look in the node_modules folder. If any of +the items there are not in the bundledDependencies array, then they will +not be included in the package tarball.

+ +

This allows a package maintainer to install all of their dependencies +(and dev dependencies) locally, but only re-publish those items that +cannot be found elsewhere. See json(1) for more information.

+ +

SEE ALSO

+ + +
+ + + diff --git a/node-v0.8.14/deps/npm/html/doc/help-search.html b/node-v0.8.14/deps/npm/html/doc/help-search.html new file mode 100644 index 0000000..81d1598 --- /dev/null +++ b/node-v0.8.14/deps/npm/html/doc/help-search.html @@ -0,0 +1,73 @@ + + + help-search + + + + +
+

help-search

Search npm help documentation

+ +

SYNOPSIS

+ +
npm help-search some search terms
+ +

DESCRIPTION

+ +

This command will search the npm markdown documentation files for the +terms provided, and then list the results, sorted by relevance.

+ +

If only one result is found, then it will show that help topic.

+ +

If the argument to npm help is not a known help topic, then it will +call help-search. It is rarely if ever necessary to call this +command directly.

+ +

CONFIGURATION

+ +

long

+ +
  • Type: Boolean
  • Default false
+ +

If true, the "long" flag will cause help-search to output context around +where the terms were found in the documentation.

+ +

If false, then help-search will just list out the help topics found.

+ +

SEE ALSO

+ + +
+ + + diff --git a/node-v0.8.14/deps/npm/html/doc/help.html b/node-v0.8.14/deps/npm/html/doc/help.html new file mode 100644 index 0000000..d06dbf6 --- /dev/null +++ b/node-v0.8.14/deps/npm/html/doc/help.html @@ -0,0 +1,71 @@ + + + help + + + + +
+

help

Get help on npm

+ +

SYNOPSIS

+ +
npm help <topic>
+npm help some search terms
+ +

DESCRIPTION

+ +

If supplied a topic, then show the appropriate documentation page.

+ +

If the topic does not exist, or if multiple terms are provided, then run +the help-search command to find a match. Note that, if help-search +finds a single subject, then it will run help on that topic, so unique +matches are equivalent to specifying a topic name.

+ +

CONFIGURATION

+ +

viewer

+ +
  • Default: "man" on Posix, "browser" on Windows
  • Type: path
+ +

The program to use to view help content.

+ +

Set to "browser" to view html help content in the default web browser.

+ +

SEE ALSO

+ + +
+ + + diff --git a/node-v0.8.14/deps/npm/html/doc/index.html b/node-v0.8.14/deps/npm/html/doc/index.html new file mode 100644 index 0000000..fea91ce --- /dev/null +++ b/node-v0.8.14/deps/npm/html/doc/index.html @@ -0,0 +1,423 @@ + + + index + + + + +
+

index

Index of all npm documentation

+ +

README

+ +

node package manager

+ +

Command Line Documentation

+ +

adduser(1)

+ +

Add a registry user account

+ +

bin(1)

+ +

Display npm bin folder

+ +

bugs(1)

+ +

Bugs for a package in a web browser maybe

+ +

build(1)

+ +

Build a package

+ +

bundle(1)

+ +

REMOVED

+ +

cache(1)

+ +

Manipulates packages cache

+ +

changelog(1)

+ +

Changes

+ +

coding-style(1)

+ +

npm's "funny" coding style

+ +

completion(1)

+ +

Tab Completion for npm

+ +

config(1)

+ +

Manage the npm configuration file

+ +

dedupe(1)

+ +

Reduce duplication

+ +

deprecate(1)

+ +

Deprecate a version of a package

+ +

developers(1)

+ +

Developer Guide

+ +

disputes(1)

+ +

Handling Module Name Disputes

+ +

docs(1)

+ +

Docs for a package in a web browser maybe

+ +

edit(1)

+ +

Edit an installed package

+ +

explore(1)

+ +

Browse an installed package

+ +

faq(1)

+ +

Frequently Asked Questions

+ +

folders(1)

+ +

Folder Structures Used by npm

+ +

help-search(1)

+ +

Search npm help documentation

+ +

help(1)

+ +

Get help on npm

+ +

init(1)

+ +

Interactively create a package.json file

+ +

install(1)

+ +

Install a package

+ +

json(1)

+ +

Specifics of npm's package.json handling

+ + + +

Symlink a package folder

+ +

ls(1)

+ +

List installed packages

+ +

npm(1)

+ +

node package manager

+ +

outdated(1)

+ +

Check for outdated packages

+ +

owner(1)

+ +

Manage package owners

+ +

pack(1)

+ +

Create a tarball from a package

+ +

prefix(1)

+ +

Display prefix

+ +

prune(1)

+ +

Remove extraneous packages

+ +

publish(1)

+ +

Publish a package

+ +

rebuild(1)

+ +

Rebuild a package

+ +

registry(1)

+ +

The JavaScript Package Registry

+ +

removing-npm(1)

+ +

Cleaning the Slate

+ +

restart(1)

+ +

Start a package

+ +

root(1)

+ +

Display npm root

+ +

run-script(1)

+ +

Run arbitrary package scripts

+ +

scripts(1)

+ +

How npm handles the "scripts" field

+ +

search(1)

+ +

Search for packages

+ +

semver(1)

+ +

The semantic versioner for npm

+ +

shrinkwrap(1)

+ +

Lock down dependency versions

+ +

star(1)

+ +

Mark your favorite packages

+ +

start(1)

+ +

Start a package

+ +

stop(1)

+ +

Stop a package

+ +

submodule(1)

+ +

Add a package as a git submodule

+ +

tag(1)

+ +

Tag a published version

+ +

test(1)

+ +

Test a package

+ +

uninstall(1)

+ +

Remove a package

+ +

unpublish(1)

+ +

Remove a package from the registry

+ +

update(1)

+ +

Update a package

+ +

version(1)

+ +

Bump a package version

+ +

view(1)

+ +

View registry info

+ +

whoami(1)

+ +

Display npm username

+ +

API Documentation

+ +

bin(3)

+ +

Display npm bin folder

+ +

bugs(3)

+ +

Bugs for a package in a web browser maybe

+ +

commands(3)

+ +

npm commands

+ +

config(3)

+ +

Manage the npm configuration files

+ +

deprecate(3)

+ +

Deprecate a version of a package

+ +

docs(3)

+ +

Docs for a package in a web browser maybe

+ +

edit(3)

+ +

Edit an installed package

+ +

explore(3)

+ +

Browse an installed package

+ +

help-search(3)

+ +

Search the help pages

+ +

init(3)

+ +

Interactively create a package.json file

+ +

install(3)

+ +

install a package programmatically

+ + + +

Symlink a package folder

+ +

load(3)

+ +

Load config settings

+ +

ls(3)

+ +

List installed packages

+ +

npm(3)

+ +

node package manager

+ +

outdated(3)

+ +

Check for outdated packages

+ +

owner(3)

+ +

Manage package owners

+ +

pack(3)

+ +

Create a tarball from a package

+ +

prefix(3)

+ +

Display prefix

+ +

prune(3)

+ +

Remove extraneous packages

+ +

publish(3)

+ +

Publish a package

+ +

rebuild(3)

+ +

Rebuild a package

+ +

restart(3)

+ +

Start a package

+ +

root(3)

+ +

Display npm root

+ +

run-script(3)

+ +

Run arbitrary package scripts

+ +

search(3)

+ +

Search for packages

+ +

shrinkwrap(3)

+ +

programmatically generate package shrinkwrap file

+ +

start(3)

+ +

Start a package

+ +

stop(3)

+ +

Stop a package

+ +

submodule(3)

+ +

Add a package as a git submodule

+ +

tag(3)

+ +

Tag a published version

+ +

test(3)

+ +

Test a package

+ +

uninstall(3)

+ +

uninstall a package programmatically

+ +

unpublish(3)

+ +

Remove a package from the registry

+ +

update(3)

+ +

Update a package

+ +

version(3)

+ +

Bump a package version

+ +

view(3)

+ +

View registry info

+ +

whoami(3)

+ +

Display npm username

+
+ + + diff --git a/node-v0.8.14/deps/npm/html/doc/init.html b/node-v0.8.14/deps/npm/html/doc/init.html new file mode 100644 index 0000000..1cc027c --- /dev/null +++ b/node-v0.8.14/deps/npm/html/doc/init.html @@ -0,0 +1,64 @@ + + + init + + + + +
+

init

Interactively create a package.json file

+ +

SYNOPSIS

+ +
npm init
+ +

DESCRIPTION

+ +

This will ask you a bunch of questions, and then write a package.json for you.

+ +

It attempts to make reasonable guesses about what you want things to be set to, +and then writes a package.json file with the options you've selected.

+ +

If you already have a package.json file, it'll read that first, and default to +the options in there.

+ +

It is strictly additive, so it does not delete options from your package.json +without a really good reason to do so.

+ +

SEE ALSO

+ + +
+ + + diff --git a/node-v0.8.14/deps/npm/html/doc/install.html b/node-v0.8.14/deps/npm/html/doc/install.html new file mode 100644 index 0000000..8536735 --- /dev/null +++ b/node-v0.8.14/deps/npm/html/doc/install.html @@ -0,0 +1,168 @@ + + + install + + + + +
+

install

Install a package

+ +

SYNOPSIS

+ +
npm install (with no args in a package dir)
+npm install <tarball file>
+npm install <tarball url>
+npm install <folder>
+npm install <name> [--save|--save-dev|--save-optional]
+npm install <name>@<tag>
+npm install <name>@<version>
+npm install <name>@<version range>
+npm install <name>@<version range>
+ +

DESCRIPTION

+ +

This command installs a package, and any packages that it depends on. If the +package has a shrinkwrap file, the installation of dependencies will be driven +by that. See shrinkwrap(1).

+ +

A package is:

+ +
  • a) a folder containing a program described by a package.json file
  • b) a gzipped tarball containing (a)
  • c) a url that resolves to (b)
  • d) a <name>@<version> that is published on the registry with (c)
  • e) a <name>@<tag> that points to (d)
  • f) a <name> that has a "latest" tag satisfying (e)
  • g) a <git remote url> that resolves to (b)
+ +

Even if you never publish your package, you can still get a lot of +benefits of using npm if you just want to write a node program (a), and +perhaps if you also want to be able to easily install it elsewhere +after packing it up into a tarball (b).

+ +
  • npm install (in package directory, no arguments):

    Install the dependencies in the local node_modules folder.

    In global mode (ie, with -g or --global appended to the command), +it installs the current package context (ie, the current working +directory) as a global package.

  • npm install <folder>:

    Install a package that is sitting in a folder on the filesystem.

  • npm install <tarball file>:

    Install a package that is sitting on the filesystem. Note: if you just want +to link a dev directory into your npm root, you can do this more easily by +using npm link.

    Example:

      npm install ./package.tgz
  • npm install <tarball url>:

    Fetch the tarball url, and then install it. In order to distinguish between +this and other options, the argument must start with "http://" or "https://"

    Example:

      npm install https://github.com/indexzero/forever/tarball/v0.5.6
  • npm install <name> [--save|--save-dev|--save-optional]:

    Do a <name>@<tag> install, where <tag> is the "tag" config. (See +config(1).)

    In most cases, this will install the latest version +of the module published on npm.

    Example:

    npm install sax

    npm install takes 3 exclusive, optional flags which save or update +the package version in your main package.json:

    • --save: Package will appear in your dependencies.

    • --save-dev: Package will appear in your devDependencies.

    • --save-optional: Package will appear in your optionalDependencies.

      Examples:

      npm install sax --save + npm install node-tap --save-dev + npm install dtrace-provider --save-optional

      Note: If there is a file or folder named <name> in the current +working directory, then it will try to install that, and only try to +fetch the package by name if it is not valid.

  • npm install <name>@<tag>:

    Install the version of the package that is referenced by the specified tag. +If the tag does not exist in the registry data for that package, then this +will fail.

    Example:

      npm install sax@latest
  • npm install <name>@<version>:

    Install the specified version of the package. This will fail if the version +has not been published to the registry.

    Example:

      npm install sax@0.1.1
  • npm install <name>@<version range>:

    Install a version of the package matching the specified version range. This +will follow the same rules for resolving dependencies described in json(1).

    Note that most version ranges must be put in quotes so that your shell will +treat it as a single argument.

    Example:

    npm install sax@">=0.1.0 <0.2.0"

  • npm install <git remote url>:

    Install a package by cloning a git remote url. The format of the git +url is:

    <protocol>://[<user>@]<hostname><separator><path>[#<commit-ish>]

    <protocol> is one of git, git+ssh, git+http, or +git+https. If no <commit-ish> is specified, then master is +used.

    Examples:

      git+ssh://git@github.com:isaacs/npm.git#v1.0.27
    +  git+https://isaacs@github.com/isaacs/npm.git
    +  git://github.com/isaacs/npm.git#v1.0.27
+ +

You may combine multiple arguments, and even multiple types of arguments. +For example:

+ +
npm install sax@">=0.1.0 <0.2.0" bench supervisor
+ +

The --tag argument will apply to all of the specified install targets.

+ +

The --force argument will force npm to fetch remote resources even if a +local copy exists on disk.

+ +
npm install sax --force
+ +

The --global argument will cause npm to install the package globally +rather than locally. See folders(1).

+ +

The --link argument will cause npm to link global installs into the +local space in some cases.

+ +

See config(1). Many of the configuration params have some +effect on installation, since that's most of what npm does.

+ +

ALGORITHM

+ +

To install a package, npm uses the following algorithm:

+ +
install(where, what, family, ancestors)
+fetch what, unpack to <where>/node_modules/<what>
+for each dep in what.dependencies
+  resolve dep to precise version
+for each dep@version in what.dependencies
+    not in <where>/node_modules/<what>/node_modules/*
+    and not in <family>
+  add precise version deps to <family>
+  install(<where>/node_modules/<what>, dep, family)
+ +

For this package{dep} structure: A{B,C}, B{C}, C{D}, +this algorithm produces:

+ +
A
++-- B
+`-- C
+    `-- D
+ +

That is, the dependency from B to C is satisfied by the fact that A +already caused C to be installed at a higher level.

+ +

See folders(1) for a more detailed description of the specific +folder structures that npm creates.

+ +

Limitations of npm's Install Algorithm

+ +

There are some very rare and pathological edge-cases where a cycle can +cause npm to try to install a never-ending tree of packages. Here is +the simplest case:

+ +
A -> B -> A' -> B' -> A -> B -> A' -> B' -> A -> ...
+ +

where A is some version of a package, and A' is a different version +of the same package. Because B depends on a different version of A +than the one that is already in the tree, it must install a separate +copy. The same is true of A', which must install B'. Because B' +depends on the original version of A, which has been overridden, the +cycle falls into infinite regress.

+ +

To avoid this situation, npm flat-out refuses to install any +name@version that is already present anywhere in the tree of package +folder ancestors. A more correct, but more complex, solution would be +to symlink the existing version into the new location. If this ever +affects a real use-case, it will be investigated.

+ +

SEE ALSO

+ + +
+ + + diff --git a/node-v0.8.14/deps/npm/html/doc/json.html b/node-v0.8.14/deps/npm/html/doc/json.html new file mode 100644 index 0000000..6f9e125 --- /dev/null +++ b/node-v0.8.14/deps/npm/html/doc/json.html @@ -0,0 +1,560 @@ + + + json + + + + +
+

json

Specifics of npm's package.json handling

+ +

DESCRIPTION

+ +

This document is all you need to know about what's required in your package.json +file. It must be actual JSON, not just a JavaScript object literal.

+ +

A lot of the behavior described in this document is affected by the config +settings described in config(1).

+ +

DEFAULT VALUES

+ +

npm will default some values based on package contents.

+ +
  • "scripts": {"start": "node server.js"}

    If there is a server.js file in the root of your package, then npm +will default the start command to node server.js.

  • "scripts":{"preinstall": "node-waf clean || true; node-waf configure build"}

    If there is a wscript file in the root of your package, npm will +default the preinstall command to compile using node-waf.

  • "scripts":{"preinstall": "node-gyp rebuild"}

    If there is a binding.gyp file in the root of your package, npm will +default the preinstall command to compile using node-gyp.

  • "contributors": [...]

    If there is an AUTHORS file in the root of your package, npm will +treat each line as a Name <email> (url) format, where email and url +are optional. Lines which start with a # or are blank, will be +ignored.

+ +

name

+ +

The most important things in your package.json are the name and version fields. +Those are actually required, and your package won't install without +them. The name and version together form an identifier that is assumed +to be completely unique. Changes to the package should come along with +changes to the version.

+ +

The name is what your thing is called. Some tips:

+ +
  • Don't put "js" or "node" in the name. It's assumed that it's js, since you're +writing a package.json file, and you can specify the engine using the "engines" +field. (See below.)
  • The name ends up being part of a URL, an argument on the command line, and a +folder name. Any name with non-url-safe characters will be rejected. +Also, it can't start with a dot or an underscore.
  • The name will probably be passed as an argument to require(), so it should +be something short, but also reasonably descriptive.
  • You may want to check the npm registry to see if there's something by that name +already, before you get too attached to it. http://registry.npmjs.org/
+ +

version

+ +

The most important things in your package.json are the name and version fields. +Those are actually required, and your package won't install without +them. The name and version together form an identifier that is assumed +to be completely unique. Changes to the package should come along with +changes to the version.

+ +

Version must be parseable by +node-semver, which is bundled +with npm as a dependency. (npm install semver to use it yourself.)

+ +

Here's how npm's semver implementation deviates from what's on semver.org:

+ +
  • Versions can start with "v"
  • A numeric item separated from the main three-number version by a hyphen +will be interpreted as a "build" number, and will increase the version. +But, if the tag is not a number separated by a hyphen, then it's treated +as a pre-release tag, and is less than the version without a tag. +So, 0.1.2-7 > 0.1.2-7-beta > 0.1.2-6 > 0.1.2 > 0.1.2beta
+ +

This is a little bit confusing to explain, but matches what you see in practice +when people create tags in git like "v1.2.3" and then do "git describe" to generate +a patch version.

+ +

description

+ +

Put a description in it. It's a string. This helps people discover your +package, as it's listed in npm search.

+ +

keywords

+ +

Put keywords in it. It's an array of strings. This helps people +discover your package as it's listed in npm search.

+ +

homepage

+ +

The url to the project homepage.

+ +

NOTE: This is not the same as "url". If you put a "url" field, +then the registry will think it's a redirection to your package that has +been published somewhere else, and spit at you.

+ +

Literally. Spit. I'm so not kidding.

+ +

bugs

+ +

The url to your project's issue tracker and / or the email address to which +issues should be reported. These are helpful for people who encounter issues +with your package.

+ +

It should look like this:

+ +
{ "url" : "http://github.com/owner/project/issues"
+, "email" : "project@hostname.com"
+}
+ +

You can specify either one or both values. If you want to provide only a url, +you can specify the value for "bugs" as a simple string instead of an object.

+ +

If a url is provided, it will be used by the npm bugs command.

+ +

people fields: author, contributors

+ +

The "author" is one person. "contributors" is an array of people. A "person" +is an object with a "name" field and optionally "url" and "email", like this:

+ +
{ "name" : "Barney Rubble"
+, "email" : "b@rubble.com"
+, "url" : "http://barnyrubble.tumblr.com/"
+}
+ +

Or you can shorten that all into a single string, and npm will parse it for you:

+ +
"Barney Rubble <b@rubble.com> (http://barnyrubble.tumblr.com/)
+ +

Both email and url are optional either way.

+ +

npm also sets a top-level "maintainers" field with your npm user info.

+ +

files

+ +

The "files" field is an array of files to include in your project. If +you name a folder in the array, then it will also include the files +inside that folder. (Unless they would be ignored by another rule.)

+ +

You can also provide a ".npmignore" file in the root of your package, +which will keep files from being included, even if they would be picked +up by the files array. The ".npmignore" file works just like a +".gitignore".

+ +

main

+ +

The main field is a module ID that is the primary entry point to your program. +That is, if your package is named foo, and a user installs it, and then does +require("foo"), then your main module's exports object will be returned.

+ +

This should be a module ID relative to the root of your package folder.

+ +

For most modules, it makes the most sense to have a main script and often not +much else.

+ +

bin

+ +

A lot of packages have one or more executable files that they'd like to +install into the PATH. npm makes this pretty easy (in fact, it uses this +feature to install the "npm" executable.)

+ +

To use this, supply a bin field in your package.json which is a map of +command name to local file name. On install, npm will symlink that file into +prefix/bin for global installs, or ./node_modules/.bin/ for local +installs.

+ +

For example, npm has this:

+ +
{ "bin" : { "npm" : "./cli.js" } }
+ +

So, when you install npm, it'll create a symlink from the cli.js script to +/usr/local/bin/npm.

+ +

If you have a single executable, and its name should be the name +of the package, then you can just supply it as a string. For example:

+ +
{ "name": "my-program"
+, "version": "1.2.5"
+, "bin": "./path/to/program" }
+ +

would be the same as this:

+ +
{ "name": "my-program"
+, "version": "1.2.5"
+, "bin" : { "my-program" : "./path/to/program" } }
+ +

man

+ +

Specify either a single file or an array of filenames to put in place for the +man program to find.

+ +

If only a single file is provided, then it's installed such that it is the +result from man <pkgname>, regardless of its actual filename. For example:

+ +
{ "name" : "foo"
+, "version" : "1.2.3"
+, "description" : "A packaged foo fooer for fooing foos"
+, "main" : "foo.js"
+, "man" : "./man/doc.1"
+}
+ +

would link the ./man/doc.1 file in such that it is the target for man foo

+ +

If the filename doesn't start with the package name, then it's prefixed. +So, this:

+ +
{ "name" : "foo"
+, "version" : "1.2.3"
+, "description" : "A packaged foo fooer for fooing foos"
+, "main" : "foo.js"
+, "man" : [ "./man/foo.1", "./man/bar.1" ]
+}
+ +

will create files to do man foo and man foo-bar.

+ +

Man files must end with a number, and optionally a .gz suffix if they are +compressed. The number dictates which man section the file is installed into.

+ +
{ "name" : "foo"
+, "version" : "1.2.3"
+, "description" : "A packaged foo fooer for fooing foos"
+, "main" : "foo.js"
+, "man" : [ "./man/foo.1", "./man/foo.2" ]
+}
+ +

will create entries for man foo and man 2 foo

+ +

directories

+ +

The CommonJS Packages spec details a +few ways that you can indicate the structure of your package using a directories +hash. If you look at npm's package.json, +you'll see that it has directories for doc, lib, and man.

+ +

In the future, this information may be used in other creative ways.

+ +

directories.lib

+ +

Tell people where the bulk of your library is. Nothing special is done +with the lib folder in any way, but it's useful meta info.

+ +

directories.bin

+ +

If you specify a "bin" directory, then all the files in that folder will +be used as the "bin" hash.

+ +

If you have a "bin" hash already, then this has no effect.

+ +

directories.man

+ +

A folder that is full of man pages. Sugar to generate a "man" array by +walking the folder.

+ +

directories.doc

+ +

Put markdown files in here. Eventually, these will be displayed nicely, +maybe, someday.

+ +

directories.example

+ +

Put example scripts in here. Someday, it might be exposed in some clever way.

+ +

repository

+ +

Specify the place where your code lives. This is helpful for people who +want to contribute. If the git repo is on github, then the npm docs +command will be able to find you.

+ +

Do it like this:

+ +
"repository" :
+  { "type" : "git"
+  , "url" : "http://github.com/isaacs/npm.git"
+  }
+
+"repository" :
+  { "type" : "svn"
+  , "url" : "http://v8.googlecode.com/svn/trunk/"
+  }
+ +

The URL should be a publicly available (perhaps read-only) url that can be handed +directly to a VCS program without any modification. It should not be a url to an +html project page that you put in your browser. It's for computers.

+ +

scripts

+ +

The "scripts" member is an object hash of script commands that are run +at various times in the lifecycle of your package. The key is the lifecycle +event, and the value is the command to run at that point.

+ +

See scripts(1) to find out more about writing package scripts.

+ +

config

+ +

A "config" hash can be used to set configuration +parameters used in package scripts that persist across upgrades. For +instance, if a package had the following:

+ +
{ "name" : "foo"
+, "config" : { "port" : "8080" } }
+ +

and then had a "start" command that then referenced the +npm_package_config_port environment variable, then the user could +override that by doing npm config set foo:port 8001.

+ +

See config(1) and scripts(1) for more on package +configs.

+ +

dependencies

+ +

Dependencies are specified with a simple hash of package name to version +range. The version range is EITHER a string which has one or more +space-separated descriptors, OR a range like "fromVersion - toVersion"

+ +

Please do not put test harnesses in your dependencies hash. See +devDependencies, below.

+ +

Version range descriptors may be any of the following styles, where "version" +is a semver compatible version identifier.

+ +
  • version Must match version exactly
  • =version Same as just version
  • >version Must be greater than version
  • >=version etc
  • <version
  • <=version
  • ~version See 'Tilde Version Ranges' below
  • 1.2.x See 'X Version Ranges' below
  • http://... See 'URLs as Dependencies' below
  • * Matches any version
  • "" (just an empty string) Same as *
  • version1 - version2 Same as >=version1 <=version2.
  • range1 || range2 Passes if either range1 or range2 are satisfied.
  • git... See 'Git URLs as Dependencies' below
+ +

For example, these are all valid:

+ +
{ "dependencies" :
+  { "foo" : "1.0.0 - 2.9999.9999"
+  , "bar" : ">=1.0.2 <2.1.2"
+  , "baz" : ">1.0.2 <=2.3.4"
+  , "boo" : "2.0.1"
+  , "qux" : "<1.0.0 || >=2.3.1 <2.4.5 || >=2.5.2 <3.0.0"
+  , "asd" : "http://asdf.com/asdf.tar.gz"
+  , "til" : "~1.2"
+  , "elf" : "~1.2.3"
+  , "two" : "2.x"
+  , "thr" : "3.3.x"
+  }
+}
+ +

Tilde Version Ranges

+ +

A range specifier starting with a tilde ~ character is matched against +a version in the following fashion.

+ +
  • The version must be at least as high as the range.
  • The version must be less than the next major revision above the range.
+ +

For example, the following are equivalent:

+ +
  • "~1.2.3" = ">=1.2.3 <1.3.0"
  • "~1.2" = ">=1.2.0 <2.0.0"
  • "~1" = ">=1.0.0 <2.0.0"
+ +

X Version Ranges

+ +

An "x" in a version range specifies that the version number must start +with the supplied digits, but any digit may be used in place of the x.

+ +

The following are equivalent:

+ +
  • "1.2.x" = ">=1.2.0 <1.3.0"
  • "1.x.x" = ">=1.0.0 <2.0.0"
  • "1.2" = "1.2.x"
  • "1.x" = "1.x.x"
  • "1" = "1.x.x"
+ +

You may not supply a comparator with a version containing an x. Any +digits after the first "x" are ignored.

+ +

URLs as Dependencies

+ +

Starting with npm version 0.2.14, you may specify a tarball URL in place +of a version range.

+ +

This tarball will be downloaded and installed locally to your package at +install time.

+ +

Git URLs as Dependencies

+ +

Git urls can be of the form:

+ +
git://github.com/user/project.git#commit-ish
+git+ssh://user@hostname:project.git#commit-ish
+git+ssh://user@hostname/project.git#commit-ish
+git+http://user@hostname/project/blah.git#commit-ish
+git+https://user@hostname/project/blah.git#commit-ish
+ +

The commit-ish can be any tag, sha, or branch which can be supplied as +an argument to git checkout. The default is master.

+ +

devDependencies

+ +

If someone is planning on downloading and using your module in their +program, then they probably don't want or need to download and build +the external test or documentation framework that you use.

+ +

In this case, it's best to list these additional items in a +devDependencies hash.

+ +

These things will be installed whenever the --dev configuration flag +is set. This flag is set automatically when doing npm link, and can +be managed like any other npm configuration param. See config(1) +for more on the topic.

+ +

bundledDependencies

+ +

Array of package names that will be bundled when publishing the package.

+ +

If this is spelled "bundleDependencies", then that is also honorable.

+ +

optionalDependencies

+ +

If a dependency can be used, but you would like npm to proceed if it +cannot be found or fails to install, then you may put it in the +optionalDependencies hash. This is a map of package name to version +or url, just like the dependencies hash. The difference is that +failure is tolerated.

+ +

It is still your program's responsibility to handle the lack of the +dependency. For example, something like this:

+ +
try {
+  var foo = require('foo')
+  var fooVersion = require('foo/package.json').version
+} catch (er) {
+  foo = null
+}
+if ( notGoodFooVersion(fooVersion) ) {
+  foo = null
+}
+
+// .. then later in your program ..
+
+if (foo) {
+  foo.doFooThings()
+}
+ +

Entries in optionalDependencies will override entries of the same name in +dependencies, so it's usually best to only put in one place.

+ +

engines

+ +

You can specify the version of node that your stuff works on:

+ +
{ "engines" : { "node" : ">=0.1.27 <0.1.30" } }
+ +

And, like with dependencies, if you don't specify the version (or if you +specify "*" as the version), then any version of node will do.

+ +

If you specify an "engines" field, then npm will require that "node" be +somewhere on that list. If "engines" is omitted, then npm will just assume +that it works on node.

+ +

You can also use the "engines" field to specify which versions of npm +are capable of properly installing your program. For example:

+ +
{ "engines" : { "npm" : "~1.0.20" } }
+ +

Note that, unless the user has set the engine-strict config flag, this +field is advisory only.

+ +

engineStrict

+ +

If you are sure that your module will definitely not run properly on +versions of Node/npm other than those specified in the engines hash, +then you can set "engineStrict": true in your package.json file. +This will override the user's engine-strict config setting.

+ +

Please do not do this unless you are really very very sure. If your +engines hash is something overly restrictive, you can quite easily and +inadvertently lock yourself into obscurity and prevent your users from +updating to new versions of Node. Consider this choice carefully. If +people abuse it, it will be removed in a future version of npm.

+ +

os

+ +

You can specify which operating systems your +module will run on:

+ +
"os" : [ "darwin", "linux" ]
+ +

You can also blacklist instead of whitelist operating systems, +just prepend the blacklisted os with a '!':

+ +
"os" : [ "!win32" ]
+ +

The host operating system is determined by process.platform

+ +

It is allowed to both blacklist, and whitelist, although there isn't any +good reason to do this.

+ +

cpu

+ +

If your code only runs on certain cpu architectures, +you can specify which ones.

+ +
"cpu" : [ "x64", "ia32" ]
+ +

Like the os option, you can also blacklist architectures:

+ +
"cpu" : [ "!arm", "!mips" ]
+ +

The host architecture is determined by process.arch

+ +

preferGlobal

+ +

If your package is primarily a command-line application that should be +installed globally, then set this value to true to provide a warning +if it is installed locally.

+ +

It doesn't actually prevent users from installing it locally, but it +does help prevent some confusion if it doesn't work as expected.

+ +

private

+ +

If you set "private": true in your package.json, then npm will refuse +to publish it.

+ +

This is a way to prevent accidental publication of private repositories. +If you would like to ensure that a given package is only ever published +to a specific registry (for example, an internal registry), +then use the publishConfig hash described below +to override the registry config param at publish-time.

+ +

publishConfig

+ +

This is a set of config values that will be used at publish-time. It's +especially handy if you want to set the tag or registry, so that you can +ensure that a given package is not tagged with "latest" or published to +the global public registry by default.

+ +

Any config values can be overridden, but of course only "tag" and +"registry" probably matter for the purposes of publishing.

+ +

See config(1) to see the list of config options that can be +overridden.

+ +

SEE ALSO

+ + +
+ + + diff --git a/node-v0.8.14/deps/npm/html/doc/link.html b/node-v0.8.14/deps/npm/html/doc/link.html new file mode 100644 index 0000000..82d9bad --- /dev/null +++ b/node-v0.8.14/deps/npm/html/doc/link.html @@ -0,0 +1,93 @@ + + + link + + + + +
+

link

Symlink a package folder

+ +

SYNOPSIS

+ +
npm link (in package folder)
+npm link <pkgname>
+ +

DESCRIPTION

+ +

Package linking is a two-step process.

+ +

First, npm link in a package folder will create a globally-installed +symbolic link from prefix/package-name to the current folder.

+ +

Next, in some other location, npm link package-name will create a +symlink from the local node_modules folder to the global symlink.

+ +

When creating tarballs for npm publish, the linked packages are +"snapshotted" to their current state by resolving the symbolic links.

+ +

This is +handy for installing your own stuff, so that you can work on it and test it +iteratively without having to continually rebuild.

+ +

For example:

+ +
cd ~/projects/node-redis    # go into the package directory
+npm link                    # creates global link
+cd ~/projects/node-bloggy   # go into some other package directory.
+npm link redis              # link-install the package
+ +

Now, any changes to ~/projects/node-redis will be reflected in +~/projects/node-bloggy/node_modules/redis/

+ +

You may also shortcut the two steps in one. For example, to do the +above use-case in a shorter way:

+ +
cd ~/projects/node-bloggy  # go into the dir of your main project
+npm link ../node-redis     # link the dir of your dependency
+ +

The second line is the equivalent of doing:

+ +
(cd ../node-redis; npm link)
+npm link redis
+ +

That is, it first creates a global link, and then links the global +installation target into your project's node_modules folder.

+ +

SEE ALSO

+ + +
+ + + diff --git a/node-v0.8.14/deps/npm/html/doc/list.html b/node-v0.8.14/deps/npm/html/doc/list.html new file mode 100644 index 0000000..45f4b7d --- /dev/null +++ b/node-v0.8.14/deps/npm/html/doc/list.html @@ -0,0 +1,99 @@ + + + list + + + + +
+

ls

List installed packages

+ +

SYNOPSIS

+ +
npm list [<pkg> ...]
+npm ls [<pkg> ...]
+npm la [<pkg> ...]
+npm ll [<pkg> ...]
+ +

DESCRIPTION

+ +

This command will print to stdout all the versions of packages that are +installed, as well as their dependencies, in a tree-structure.

+ +

Positional arguments are name@version-range identifiers, which will +limit the results to only the paths to the packages named. Note that +nested packages will also show the paths to the specified packages. +For example, running npm ls promzard in npm's source tree will show:

+ +
npm@1.1.59 /path/to/npm
+└─┬ init-package-json@0.0.4
+  └── promzard@0.1.5
+ +

It will show print out extraneous, missing, and invalid packages.

+ +

When run as ll or la, it shows extended information by default.

+ +

CONFIGURATION

+ +

json

+ +
  • Default: false
  • Type: Boolean
+ +

Show information in JSON format.

+ +

long

+ +
  • Default: false
  • Type: Boolean
+ +

Show extended information.

+ +

parseable

+ +
  • Default: false
  • Type: Boolean
+ +

Show parseable output instead of tree view.

+ +

global

+ +
  • Default: false
  • Type: Boolean
+ +

List packages in the global install prefix instead of in the current +project.

+ +

SEE ALSO

+ + +
+ + + diff --git a/node-v0.8.14/deps/npm/html/doc/ls.html b/node-v0.8.14/deps/npm/html/doc/ls.html new file mode 100644 index 0000000..4971d28 --- /dev/null +++ b/node-v0.8.14/deps/npm/html/doc/ls.html @@ -0,0 +1,99 @@ + + + ls + + + + +
+

ls

List installed packages

+ +

SYNOPSIS

+ +
npm list [<pkg> ...]
+npm ls [<pkg> ...]
+npm la [<pkg> ...]
+npm ll [<pkg> ...]
+ +

DESCRIPTION

+ +

This command will print to stdout all the versions of packages that are +installed, as well as their dependencies, in a tree-structure.

+ +

Positional arguments are name@version-range identifiers, which will +limit the results to only the paths to the packages named. Note that +nested packages will also show the paths to the specified packages. +For example, running npm ls promzard in npm's source tree will show:

+ +
npm@1.1.65 /path/to/npm
+└─┬ init-package-json@0.0.4
+  └── promzard@0.1.5
+ +

It will show print out extraneous, missing, and invalid packages.

+ +

When run as ll or la, it shows extended information by default.

+ +

CONFIGURATION

+ +

json

+ +
  • Default: false
  • Type: Boolean
+ +

Show information in JSON format.

+ +

long

+ +
  • Default: false
  • Type: Boolean
+ +

Show extended information.

+ +

parseable

+ +
  • Default: false
  • Type: Boolean
+ +

Show parseable output instead of tree view.

+ +

global

+ +
  • Default: false
  • Type: Boolean
+ +

List packages in the global install prefix instead of in the current +project.

+ +

SEE ALSO

+ + +
+ + + diff --git a/node-v0.8.14/deps/npm/html/doc/npm.html b/node-v0.8.14/deps/npm/html/doc/npm.html new file mode 100644 index 0000000..211a73f --- /dev/null +++ b/node-v0.8.14/deps/npm/html/doc/npm.html @@ -0,0 +1,170 @@ + + + npm + + + + +
+

npm

node package manager

+ +

SYNOPSIS

+ +
npm <command> [args]
+ +

VERSION

+ +

1.1.65

+ +

DESCRIPTION

+ +

npm is the package manager for the Node JavaScript platform. It puts +modules in place so that node can find them, and manages dependency +conflicts intelligently.

+ +

It is extremely configurable to support a wide variety of use cases. +Most commonly, it is used to publish, discover, install, and develop node +programs.

+ +

Run npm help to get a list of available commands.

+ +

INTRODUCTION

+ +

You probably got npm because you want to install stuff.

+ +

Use npm install blerg to install the latest version of "blerg". Check out +install(1) for more info. It can do a lot of stuff.

+ +

Use the npm search command to show everything that's available. +Use npm ls to show everything you've installed.

+ +

DIRECTORIES

+ +

See folders(1) to learn about where npm puts stuff.

+ +

In particular, npm has two modes of operation:

+ +
  • global mode:
    npm installs packages into the install prefix at +prefix/lib/node_modules and bins are installed in prefix/bin.
  • local mode:
    npm installs packages into the current project directory, which +defaults to the current working directory. Packages are installed to +./node_modules, and bins are installed to ./node_modules/.bin.
+ +

Local mode is the default. Use --global or -g on any command to +operate in global mode instead.

+ +

DEVELOPER USAGE

+ +

If you're using npm to develop and publish your code, check out the +following help topics:

+ +
  • json: +Make a package.json file. See json(1).
  • link: +For linking your current working code into Node's path, so that you +don't have to reinstall every time you make a change. Use +npm link to do this.
  • install: +It's a good idea to install things if you don't need the symbolic link. +Especially, installing other peoples code from the registry is done via +npm install
  • adduser: +Create an account or log in. Credentials are stored in the +user config file.
  • publish: +Use the npm publish command to upload your code to the registry.
+ +

CONFIGURATION

+ +

npm is extremely configurable. It reads its configuration options from +5 places.

+ +
  • Command line switches:
    Set a config with --key val. All keys take a value, even if they +are booleans (the config parser doesn't know what the options are at +the time of parsing.) If no value is provided, then the option is set +to boolean true.
  • Environment Variables:
    Set any config by prefixing the name in an environment variable with +npm_config_. For example, export npm_config_key=val.
  • User Configs:
    The file at $HOME/.npmrc is an ini-formatted list of configs. If +present, it is parsed. If the userconfig option is set in the cli +or env, then that will be used instead.
  • Global Configs:
    The file found at ../etc/npmrc (from the node executable, by default +this resolves to /usr/local/etc/npmrc) will be parsed if it is found. +If the globalconfig option is set in the cli, env, or user config, +then that file is parsed instead.
  • Defaults:
    npm's default configuration options are defined in +lib/utils/config-defs.js. These must not be changed.
+ +

See config(1) for much much more information.

+ +

CONTRIBUTIONS

+ +

Patches welcome!

+ +
  • code: +Read through coding-style(1) if you plan to submit code. +You don't have to agree with it, but you do have to follow it.
  • docs: +If you find an error in the documentation, edit the appropriate markdown +file in the "doc" folder. (Don't worry about generating the man page.)
+ +

Contributors are listed in npm's package.json file. You can view them +easily by doing npm view npm contributors.

+ +

If you would like to contribute, but don't know what to work on, check +the issues list or ask on the mailing list.

+ + + +

BUGS

+ +

When you find issues, please report them:

+ + + +

Be sure to include all of the output from the npm command that didn't work +as expected. The npm-debug.log file is also helpful to provide.

+ +

You can also look for isaacs in #node.js on irc://irc.freenode.net. He +will no doubt tell you to put the output in a gist or email.

+ +

HISTORY

+ +

See changelog(1)

+ +

AUTHOR

+ +

Isaac Z. Schlueter :: +isaacs :: +@izs :: +i@izs.me

+ +

SEE ALSO

+ + +
+ + + diff --git a/node-v0.8.14/deps/npm/html/doc/outdated.html b/node-v0.8.14/deps/npm/html/doc/outdated.html new file mode 100644 index 0000000..82c937d --- /dev/null +++ b/node-v0.8.14/deps/npm/html/doc/outdated.html @@ -0,0 +1,56 @@ + + + outdated + + + + +
+

outdated

Check for outdated packages

+ +

SYNOPSIS

+ +
npm outdated [<name> [<name> ...]]
+ +

DESCRIPTION

+ +

This command will check the registry to see if any (or, specific) installed +packages are currently outdated.

+ +

SEE ALSO

+ + +
+ + + diff --git a/node-v0.8.14/deps/npm/html/doc/owner.html b/node-v0.8.14/deps/npm/html/doc/owner.html new file mode 100644 index 0000000..9d46429 --- /dev/null +++ b/node-v0.8.14/deps/npm/html/doc/owner.html @@ -0,0 +1,69 @@ + + + owner + + + + +
+

owner

Manage package owners

+ +

SYNOPSIS

+ +
npm owner ls <package name>
+npm owner add <user> <package name>
+npm owner rm <user> <package name>
+ +

DESCRIPTION

+ +

Manage ownership of published packages.

+ +
  • ls: +List all the users who have access to modify a package and push new versions. +Handy when you need to know who to bug for help.
  • add: +Add a new user as a maintainer of a package. This user is enabled to modify +metadata, publish new versions, and add other owners.
  • rm: +Remove a user from the package owner list. This immediately revokes their +privileges.
+ +

Note that there is only one level of access. Either you can modify a package, +or you can't. Future versions may contain more fine-grained access levels, but +that is not implemented at this time.

+ +

SEE ALSO

+ + +
+ + + diff --git a/node-v0.8.14/deps/npm/html/doc/pack.html b/node-v0.8.14/deps/npm/html/doc/pack.html new file mode 100644 index 0000000..bdddd1e --- /dev/null +++ b/node-v0.8.14/deps/npm/html/doc/pack.html @@ -0,0 +1,64 @@ + + + pack + + + + +
+

pack

Create a tarball from a package

+ +

SYNOPSIS

+ +
npm pack [<pkg> [<pkg> ...]]
+ +

DESCRIPTION

+ +

For anything that's installable (that is, a package folder, tarball, +tarball url, name@tag, name@version, or name), this command will fetch +it to the cache, and then copy the tarball to the current working +directory as <name>-<version>.tgz, and then write the filenames out to +stdout.

+ +

If the same package is specified multiple times, then the file will be +overwritten the second time.

+ +

If no arguments are supplied, then npm packs the current package folder.

+ +

SEE ALSO

+ + +
+ + + diff --git a/node-v0.8.14/deps/npm/html/doc/prefix.html b/node-v0.8.14/deps/npm/html/doc/prefix.html new file mode 100644 index 0000000..5c7b360 --- /dev/null +++ b/node-v0.8.14/deps/npm/html/doc/prefix.html @@ -0,0 +1,55 @@ + + + prefix + + + + +
+

prefix

Display prefix

+ +

SYNOPSIS

+ +
npm prefix
+ +

DESCRIPTION

+ +

Print the prefix to standard out.

+ +

SEE ALSO

+ + +
+ + + diff --git a/node-v0.8.14/deps/npm/html/doc/prune.html b/node-v0.8.14/deps/npm/html/doc/prune.html new file mode 100644 index 0000000..144bc4f --- /dev/null +++ b/node-v0.8.14/deps/npm/html/doc/prune.html @@ -0,0 +1,60 @@ + + + prune + + + + +
+

prune

Remove extraneous packages

+ +

SYNOPSIS

+ +
npm prune [<name> [<name ...]]
+ +

DESCRIPTION

+ +

This command removes "extraneous" packages. If a package name is +provided, then only packages matching one of the supplied names are +removed.

+ +

Extraneous packages are packages that are not listed on the parent +package's dependencies list.

+ +

SEE ALSO

+ + +
+ + + diff --git a/node-v0.8.14/deps/npm/html/doc/publish.html b/node-v0.8.14/deps/npm/html/doc/publish.html new file mode 100644 index 0000000..dbdaaf6 --- /dev/null +++ b/node-v0.8.14/deps/npm/html/doc/publish.html @@ -0,0 +1,64 @@ + + + publish + + + + +
+

publish

Publish a package

+ +

SYNOPSIS

+ +
npm publish <tarball>
+npm publish <folder>
+ +

DESCRIPTION

+ +

Publishes a package to the registry so that it can be installed by name.

+ +
  • <folder>: +A folder containing a package.json file

  • <tarball>: +A url or file path to a gzipped tar archive containing a single folder +with a package.json file inside.

+ +

Fails if the package name and version combination already exists in +the registry. Overwrites when the "--force" flag is set.

+ +

SEE ALSO

+ + +
+ + + diff --git a/node-v0.8.14/deps/npm/html/doc/rebuild.html b/node-v0.8.14/deps/npm/html/doc/rebuild.html new file mode 100644 index 0000000..f55e5a5 --- /dev/null +++ b/node-v0.8.14/deps/npm/html/doc/rebuild.html @@ -0,0 +1,60 @@ + + + rebuild + + + + +
+

rebuild

Rebuild a package

+ +

SYNOPSIS

+ +
npm rebuild [<name> [<name> ...]]
+ +
  • <name>: +The package to rebuild
+ +

DESCRIPTION

+ +

This command runs the npm build command on the matched folders. This is useful +when you install a new version of node, and must recompile all your C++ addons with +the new binary.

+ +

SEE ALSO

+ + +
+ + + diff --git a/node-v0.8.14/deps/npm/html/doc/registry.html b/node-v0.8.14/deps/npm/html/doc/registry.html new file mode 100644 index 0000000..6b6b63a --- /dev/null +++ b/node-v0.8.14/deps/npm/html/doc/registry.html @@ -0,0 +1,132 @@ + + + registry + + + + +
+

registry

The JavaScript Package Registry

+ +

DESCRIPTION

+ +

To resolve packages by name and version, npm talks to a registry website +that implements the CommonJS Package Registry specification for reading +package info.

+ +

Additionally, npm's package registry implementation supports several +write APIs as well, to allow for publishing packages and managing user +account information.

+ +

The official public npm registry is at http://registry.npmjs.org/. It +is powered by a CouchDB database at +http://isaacs.iriscouch.com/registry. The code for the couchapp is +available at http://github.com/isaacs/npmjs.org. npm user accounts +are CouchDB users, stored in the http://isaacs.iriscouch.com/_users +database.

+ +

The registry URL is supplied by the registry config parameter. See +config(1) for more on managing npm's configuration.

+ +

Can I run my own private registry?

+ +

Yes!

+ +

The easiest way is to replicate the couch database, and use the same (or +similar) design doc to implement the APIs.

+ +

If you set up continuous replication from the official CouchDB, and then +set your internal CouchDB as the registry config, then you'll be able +to read any published packages, in addition to your private ones, and by +default will only publish internally. If you then want to publish a +package for the whole world to see, you can simply override the +--registry config for that command.

+ +

I don't want my package published in the official registry. It's private.

+ +

Set "private": true in your package.json to prevent it from being +published at all, or +"publishConfig":{"registry":"http://my-internal-registry.local"} +to force it to be published only to your internal registry.

+ +

See json(1) for more info on what goes in the package.json file.

+ +

Will you replicate from my registry into the public one?

+ +

No. If you want things to be public, then publish them into the public +registry using npm. What little security there is would be for nought +otherwise.

+ +

Do I have to use couchdb to build a registry that npm can talk to?

+ +

No, but it's way easier.

+ +

I published something elsewhere, and want to tell the npm registry about it.

+ +

That is supported, but not using the npm client. You'll have to get +your hands dirty and do some HTTP. The request looks something like +this:

+ +
PUT /my-foreign-package
+content-type:application/json
+accept:application/json
+authorization:Basic $base_64_encoded
+
+{ "name":"my-foreign-package"
+, "maintainers":["owner","usernames"]
+, "description":"A package that is hosted elsewhere"
+, "keywords":["nih","my cheese smells the best"]
+, "url":"http://my-different-registry.com/blerg/my-local-package"
+}
+ +

(Keywords and description are optional, but recommended. Name, +maintainers, and url are required.)

+ +

Then, when a user tries to install "my-foreign-package", it'll redirect +to your registry. If that doesn't resolve to a valid package entry, +then it'll fail, so please make sure that you understand the spec, and +ask for help on the npm-@googlegroups.com mailing list.

+ +

Is there a website or something to see package docs and such?

+ +

No, but such a thing is planned, and a tiny bit developed.

+ +

Stay tuned!

+ +

SEE ALSO

+ + +
+ + + diff --git a/node-v0.8.14/deps/npm/html/doc/removing-npm.html b/node-v0.8.14/deps/npm/html/doc/removing-npm.html new file mode 100644 index 0000000..5a13f03 --- /dev/null +++ b/node-v0.8.14/deps/npm/html/doc/removing-npm.html @@ -0,0 +1,93 @@ + + + removing-npm + + + + +
+

removal

Cleaning the Slate

+ +

SYNOPSIS

+ +

So sad to see you go.

+ +
sudo npm uninstall npm -g
+ +

Or, if that fails, get the npm source code, and do:

+ +
sudo make uninstall
+ +

More Severe Uninstalling

+ +

Usually, the above instructions are sufficient. That will remove +npm, but leave behind anything you've installed.

+ +

If that doesn't work, or if you require more drastic measures, +continue reading.

+ +

Note that this is only necessary for globally-installed packages. Local +installs are completely contained within a project's node_modules +folder. Delete that folder, and everything is gone (unless a package's +install script is particularly ill-behaved).

+ +

This assumes that you installed node and npm in the default place. If +you configured node with a different --prefix, or installed npm with a +different prefix setting, then adjust the paths accordingly, replacing +/usr/local with your install prefix.

+ +

To remove everything npm-related manually:

+ +
rm -rf /usr/local/{lib/node{,/.npm,_modules},bin,share/man}/npm*
+ +

If you installed things with npm, then your best bet is to uninstall +them with npm first, and then install them again once you have a +proper install. This can help find any symlinks that are lying +around:

+ +
ls -laF /usr/local/{lib/node{,/.npm},bin,share/man} | grep npm
+ +

Prior to version 0.3, npm used shim files for executables and node +modules. To track those down, you can do the following:

+ +
find /usr/local/{lib/node,bin} -exec grep -l npm \{\} \; ;
+ +

(This is also in the README file.)

+ +

SEE ALSO

+ + +
+ + + diff --git a/node-v0.8.14/deps/npm/html/doc/restart.html b/node-v0.8.14/deps/npm/html/doc/restart.html new file mode 100644 index 0000000..e241001 --- /dev/null +++ b/node-v0.8.14/deps/npm/html/doc/restart.html @@ -0,0 +1,59 @@ + + + restart + + + + +
+

restart

Start a package

+ +

SYNOPSIS

+ +
npm restart <name>
+ +

DESCRIPTION

+ +

This runs a package's "restart" script, if one was provided. +Otherwise it runs package's "stop" script, if one was provided, and then +the "start" script.

+ +

If no version is specified, then it restarts the "active" version.

+ +

SEE ALSO

+ + +
+ + + diff --git a/node-v0.8.14/deps/npm/html/doc/root.html b/node-v0.8.14/deps/npm/html/doc/root.html new file mode 100644 index 0000000..e995249 --- /dev/null +++ b/node-v0.8.14/deps/npm/html/doc/root.html @@ -0,0 +1,55 @@ + + + root + + + + +
+

root

Display npm root

+ +

SYNOPSIS

+ +
npm root
+ +

DESCRIPTION

+ +

Print the effective node_modules folder to standard out.

+ +

SEE ALSO

+ + +
+ + + diff --git a/node-v0.8.14/deps/npm/html/doc/run-script.html b/node-v0.8.14/deps/npm/html/doc/run-script.html new file mode 100644 index 0000000..490d063 --- /dev/null +++ b/node-v0.8.14/deps/npm/html/doc/run-script.html @@ -0,0 +1,58 @@ + + + run-script + + + + +
+

run-script

Run arbitrary package scripts

+ +

SYNOPSIS

+ +
npm run-script <script> <name>
+ +

DESCRIPTION

+ +

This runs an arbitrary command from a package's "scripts" object.

+ +

It is used by the test, start, restart, and stop commands, but can be +called directly, as well.

+ +

SEE ALSO

+ + +
+ + + diff --git a/node-v0.8.14/deps/npm/html/doc/scripts.html b/node-v0.8.14/deps/npm/html/doc/scripts.html new file mode 100644 index 0000000..88c128d --- /dev/null +++ b/node-v0.8.14/deps/npm/html/doc/scripts.html @@ -0,0 +1,212 @@ + + + scripts + + + + +
+

scripts

How npm handles the "scripts" field

+ +

DESCRIPTION

+ +

npm supports the "scripts" member of the package.json script, for the +following scripts:

+ +
  • preinstall: +Run BEFORE the package is installed
  • install, postinstall: +Run AFTER the package is installed.
  • preuninstall, uninstall: +Run BEFORE the package is uninstalled.
  • postuninstall: +Run AFTER the package is uninstalled.
  • preupdate: +Run BEFORE the package is updated with the update command.
  • update, postupdate: +Run AFTER the package is updated with the update command.
  • prepublish: +Run BEFORE the package is published.
  • publish, postpublish: +Run AFTER the package is published.
  • pretest, test, posttest: +Run by the npm test command.
  • prestop, stop, poststop: +Run by the npm stop command.
  • prestart, start, poststart: +Run by the npm start command.
  • prerestart, restart, postrestart: +Run by the npm restart command. Note: npm restart will run the +stop and start scripts if no restart script is provided.
+ +

Additionally, arbitrary scrips can be run by doing +npm run-script <stage> <pkg>.

+ +

DEFAULT VALUES

+ +

npm will default some script values based on package contents.

+ +
  • "start": "node server.js":

    If there is a server.js file in the root of your package, then npm +will default the start command to node server.js.

  • "preinstall": "node-waf clean || true; node-waf configure build":

    If there is a wscript file in the root of your package, npm will +default the preinstall command to compile using node-waf.

+ +

USER

+ +

If npm was invoked with root privileges, then it will change the uid to +the user account or uid specified by the user config, which defaults +to nobody. Set the unsafe-perm flag to run scripts with root +privileges.

+ +

ENVIRONMENT

+ +

Package scripts run in an environment where many pieces of information are +made available regarding the setup of npm and the current state of the +process.

+ +

path

+ +

If you depend on modules that define executable scripts, like test suites, +then those executables will be added to the PATH for executing the scripts. +So, if your package.json has this:

+ +
{ "name" : "foo"
+, "dependencies" : { "bar" : "0.1.x" }
+, "scripts": { "start" : "bar ./test" } }
+ +

then you could run npm start to execute the bar script, which is exported +into the node_modules/.bin directory on npm install.

+ +

package.json vars

+ +

The package.json fields are tacked onto the npm_package_ prefix. So, for +instance, if you had {"name":"foo", "version":"1.2.5"} in your package.json +file, then your package scripts would have the npm_package_name environment +variable set to "foo", and the npm_package_version set to "1.2.5"

+ +

configuration

+ +

Configuration parameters are put in the environment with the npm_config_ +prefix. For instance, you can view the effective root config by checking the +npm_config_root environment variable.

+ +

Special: package.json "config" hash

+ +

The package.json "config" keys are overwritten in the environment if +there is a config param of <name>[@<version>]:<key>. For example, if +the package.json has this:

+ +
{ "name" : "foo"
+, "config" : { "port" : "8080" }
+, "scripts" : { "start" : "node server.js" } }
+ +

and the server.js is this:

+ +
http.createServer(...).listen(process.env.npm_package_config_port)
+ +

then the user could change the behavior by doing:

+ +
npm config set foo:port 80
+ +

current lifecycle event

+ +

Lastly, the npm_lifecycle_event environment variable is set to whichever +stage of the cycle is being executed. So, you could have a single script used +for different parts of the process which switches based on what's currently +happening.

+ +

Objects are flattened following this format, so if you had +{"scripts":{"install":"foo.js"}} in your package.json, then you'd see this +in the script:

+ +
process.env.npm_package_scripts_install === "foo.js"
+ +

EXAMPLES

+ +

For example, if your package.json contains this:

+ +
{ "scripts" :
+  { "install" : "scripts/install.js"
+  , "postinstall" : "scripts/install.js"
+  , "uninstall" : "scripts/uninstall.js"
+  }
+}
+ +

then the scripts/install.js will be called for the install, post-install, +stages of the lifecycle, and the scripts/uninstall.js would be +called when the package is uninstalled. Since scripts/install.js is running +for three different phases, it would be wise in this case to look at the +npm_lifecycle_event environment variable.

+ +

If you want to run a make command, you can do so. This works just fine:

+ +
{ "scripts" :
+  { "preinstall" : "./configure"
+  , "install" : "make && make install"
+  , "test" : "make test"
+  }
+}
+ +

EXITING

+ +

Scripts are run by passing the line as a script argument to sh.

+ +

If the script exits with a code other than 0, then this will abort the +process.

+ +

Note that these script files don't have to be nodejs or even javascript +programs. They just have to be some kind of executable file.

+ +

HOOK SCRIPTS

+ +

If you want to run a specific script at a specific lifecycle event for ALL +packages, then you can use a hook script.

+ +

Place an executable file at node_modules/.hooks/{eventname}, and it'll get +run for all packages when they are going through that point in the package +lifecycle for any packages installed in that root.

+ +

Hook scripts are run exactly the same way as package.json scripts. That is, +they are in a separate child process, with the env described above.

+ +

BEST PRACTICES

+ +
  • Don't exit with a non-zero error code unless you really mean it. +Except for uninstall scripts, this will cause the npm action +to fail, and potentially be rolled back. If the failure is minor or +only will prevent some optional features, then it's better to just +print a warning and exit successfully.
  • Try not to use scripts to do what npm can do for you. Read through +json(1) to see all the things that you can specify and enable +by simply describing your package appropriately. In general, this will +lead to a more robust and consistent state.
  • Inspect the env to determine where to put things. For instance, if +the npm_config_binroot environ is set to /home/user/bin, then don't +try to install executables into /usr/local/bin. The user probably +set it up that way for a reason.
  • Don't prefix your script commands with "sudo". If root permissions are +required for some reason, then it'll fail with that error, and the user +will sudo the npm command in question.
+ +

SEE ALSO

+ + +
+ + + diff --git a/node-v0.8.14/deps/npm/html/doc/search.html b/node-v0.8.14/deps/npm/html/doc/search.html new file mode 100644 index 0000000..acb17a7 --- /dev/null +++ b/node-v0.8.14/deps/npm/html/doc/search.html @@ -0,0 +1,59 @@ + + + search + + + + +
+

search

Search for packages

+ +

SYNOPSIS

+ +
npm search [search terms ...]
+ +

DESCRIPTION

+ +

Search the registry for packages matching the search terms.

+ +

If a term starts with /, then it's interpreted as a regular expression. +A trailing / will be ignored in this case. (Note that many regular +expression characters must be escaped or quoted in most shells.)

+ +

SEE ALSO

+ + +
+ + + diff --git a/node-v0.8.14/deps/npm/html/doc/semver.html b/node-v0.8.14/deps/npm/html/doc/semver.html new file mode 100644 index 0000000..7c6b334 --- /dev/null +++ b/node-v0.8.14/deps/npm/html/doc/semver.html @@ -0,0 +1,139 @@ + + + semver + + + + +
+

semver

The semantic versioner for npm

+ +

SYNOPSIS

+ +

The npm semantic versioning utility.

+ +

DESCRIPTION

+ +

As a node module:

+ +
$ npm install semver
+
+semver.valid('1.2.3') // true
+semver.valid('a.b.c') // false
+semver.clean('  =v1.2.3   ') // '1.2.3'
+semver.satisfies('1.2.3', '1.x || >=2.5.0 || 5.0.0 - 7.2.3') // true
+semver.gt('1.2.3', '9.8.7') // false
+semver.lt('1.2.3', '9.8.7') // true
+ +

As a command-line utility:

+ +
$ npm install semver -g
+$ semver -h
+
+Usage: semver -v <version> [-r <range>]
+Test if version(s) satisfy the supplied range(s),
+and sort them.
+
+Multiple versions or ranges may be supplied.
+
+Program exits successfully if any valid version satisfies
+all supplied ranges, and prints all satisfying versions.
+
+If no versions are valid, or ranges are not satisfied,
+then exits failure.
+
+Versions are printed in ascending order, so supplying
+multiple versions to the utility will just sort them.
+ +

Versions

+ +

A version is the following things, in this order:

+ +
  • a number (Major)
  • a period
  • a number (minor)
  • a period
  • a number (patch)
  • OPTIONAL: a hyphen, followed by a number (build)
  • OPTIONAL: a collection of pretty much any non-whitespace characters +(tag)
+ +

A leading "=" or "v" character is stripped off and ignored.

+ +

Comparisons

+ +

The ordering of versions is done using the following algorithm, given +two versions and asked to find the greater of the two:

+ +
  • If the majors are numerically different, then take the one +with a bigger major number. 2.3.4 > 1.3.4
  • If the minors are numerically different, then take the one +with the bigger minor number. 2.3.4 > 2.2.4
  • If the patches are numerically different, then take the one with the +bigger patch number. 2.3.4 > 2.3.3
  • If only one of them has a build number, then take the one with the +build number. 2.3.4-0 > 2.3.4
  • If they both have build numbers, and the build numbers are numerically +different, then take the one with the bigger build number. +2.3.4-10 > 2.3.4-9
  • If only one of them has a tag, then take the one without the tag. +2.3.4 > 2.3.4-beta
  • If they both have tags, then take the one with the lexicographically +larger tag. 2.3.4-beta > 2.3.4-alpha
  • At this point, they're equal.
+ +

Ranges

+ +

The following range styles are supported:

+ +
  • >1.2.3 Greater than a specific version.
  • <1.2.3 Less than
  • 1.2.3 - 2.3.4 := >=1.2.3 <=2.3.4
  • ~1.2.3 := >=1.2.3 <1.3.0
  • ~1.2 := >=1.2.0 <2.0.0
  • ~1 := >=1.0.0 <2.0.0
  • 1.2.x := >=1.2.0 <1.3.0
  • 1.x := >=1.0.0 <2.0.0
+ +

Ranges can be joined with either a space (which implies "and") or a +|| (which implies "or").

+ +

Functions

+ +
  • valid(v): Return the parsed version, or null if it's not valid.
  • inc(v, release): Return the version incremented by the release type +(major, minor, patch, or build), or null if it's not valid.
+ +

Comparison

+ +
  • gt(v1, v2): v1 > v2
  • gte(v1, v2): v1 >= v2
  • lt(v1, v2): v1 < v2
  • lte(v1, v2): v1 <= v2
  • eq(v1, v2): v1 == v2 This is true if they're logically equivalent, +even if they're not the exact same string. You already know how to +compare strings.
  • neq(v1, v2): v1 != v2 The opposite of eq.
  • cmp(v1, comparator, v2): Pass in a comparison string, and it'll call +the corresponding function above. "===" and "!==" do simple +string comparison, but are included for completeness. Throws if an +invalid comparison string is provided.
  • compare(v1, v2): Return 0 if v1 == v2, or 1 if v1 is greater, or -1 if +v2 is greater. Sorts in ascending order if passed to Array.sort().
  • rcompare(v1, v2): The reverse of compare. Sorts an array of versions +in descending order when passed to Array.sort().
+ +

Ranges

+ +
  • validRange(range): Return the valid range or null if it's not valid
  • satisfies(version, range): Return true if the version satisfies the +range.
  • maxSatisfying(versions, range): Return the highest version in the list +that satisfies the range, or null if none of them do.
+ +

SEE ALSO

+ + +
+ + + diff --git a/node-v0.8.14/deps/npm/html/doc/shrinkwrap.html b/node-v0.8.14/deps/npm/html/doc/shrinkwrap.html new file mode 100644 index 0000000..04dd5e8 --- /dev/null +++ b/node-v0.8.14/deps/npm/html/doc/shrinkwrap.html @@ -0,0 +1,204 @@ + + + shrinkwrap + + + + +
+

shrinkwrap

Lock down dependency versions

+ +

SYNOPSIS

+ +
npm shrinkwrap
+ +

DESCRIPTION

+ +

This command locks down the versions of a package's dependencies so that you can +control exactly which versions of each dependency will be used when your package +is installed.

+ +

By default, "npm install" recursively installs the target's dependencies (as +specified in package.json), choosing the latest available version that satisfies +the dependency's semver pattern. In some situations, particularly when shipping +software where each change is tightly managed, it's desirable to fully specify +each version of each dependency recursively so that subsequent builds and +deploys do not inadvertently pick up newer versions of a dependency that satisfy +the semver pattern. Specifying specific semver patterns in each dependency's +package.json would facilitate this, but that's not always possible or desirable, +as when another author owns the npm package. It's also possible to check +dependencies directly into source control, but that may be undesirable for other +reasons.

+ +

As an example, consider package A:

+ +
{
+    "name": "A",
+    "version": "0.1.0",
+    "dependencies": {
+        "B": "<0.1.0"
+    }
+}
+ +

package B:

+ +
{
+    "name": "B",
+    "version": "0.0.1",
+    "dependencies": {
+        "C": "<0.1.0"
+    }
+}
+ +

and package C:

+ +
{
+    "name": "C,
+    "version": "0.0.1"
+}
+ +

If these are the only versions of A, B, and C available in the registry, then +a normal "npm install A" will install:

+ +
A@0.1.0
+`-- B@0.0.1
+    `-- C@0.0.1
+ +

However, if B@0.0.2 is published, then a fresh "npm install A" will install:

+ +
A@0.1.0
+`-- B@0.0.2
+    `-- C@0.0.1
+ +

assuming the new version did not modify B's dependencies. Of course, the new +version of B could include a new version of C and any number of new +dependencies. If such changes are undesirable, the author of A could specify a +dependency on B@0.0.1. However, if A's author and B's author are not the same +person, there's no way for A's author to say that he or she does not want to +pull in newly published versions of C when B hasn't changed at all.

+ +

In this case, A's author can run

+ +
npm shrinkwrap
+ +

This generates npm-shrinkwrap.json, which will look something like this:

+ +
{
+  "name": "A",
+  "version": "0.1.0",
+  "dependencies": {
+    "B": {
+      "version": "0.0.1",
+      "dependencies": {
+        "C": {
+          "version": "0.1.0"
+        }
+      }
+    }
+  }
+}
+ +

The shrinkwrap command has locked down the dependencies based on what's +currently installed in node_modules. When "npm install" installs a package with +a npm-shrinkwrap.json file in the package root, the shrinkwrap file (rather than +package.json files) completely drives the installation of that package and all +of its dependencies (recursively). So now the author publishes A@0.1.0, and +subsequent installs of this package will use B@0.0.1 and C@0.1.0, regardless the +dependencies and versions listed in A's, B's, and C's package.json files.

+ +

Using shrinkwrapped packages

+ +

Using a shrinkwrapped package is no different than using any other package: you +can "npm install" it by hand, or add a dependency to your package.json file and +"npm install" it.

+ +

Building shrinkwrapped packages

+ +

To shrinkwrap an existing package:

+ +
  1. Run "npm install" in the package root to install the current versions of all +dependencies.
  2. Validate that the package works as expected with these versions.
  3. Run "npm shrinkwrap", add npm-shrinkwrap.json to git, and publish your +package.
+ +

To add or update a dependency in a shrinkwrapped package:

+ +
  1. Run "npm install" in the package root to install the current versions of all +dependencies.
  2. Add or update dependencies. "npm install" each new or updated package +individually and then update package.json. Note that they must be +explicitly named in order to be installed: running npm install with +no arguments will merely reproduce the existing shrinkwrap.
  3. Validate that the package works as expected with the new dependencies.
  4. Run "npm shrinkwrap", commit the new npm-shrinkwrap.json, and publish your +package.
+ +

You can use outdated(1) to view dependencies with newer versions available.

+ +

Other Notes

+ +

Since "npm shrinkwrap" uses the locally installed packages to construct the +shrinkwrap file, devDependencies will be included if and only if you've +installed them already when you make the shrinkwrap.

+ +

A shrinkwrap file must be consistent with the package's package.json file. "npm +shrinkwrap" will fail if required dependencies are not already installed, since +that would result in a shrinkwrap that wouldn't actually work. Similarly, the +command will fail if there are extraneous packages (not referenced by +package.json), since that would indicate that package.json is not correct.

+ +

If shrinkwrapped package A depends on shrinkwrapped package B, B's shrinkwrap +will not be used as part of the installation of A. However, because A's +shrinkwrap is constructed from a valid installation of B and recursively +specifies all dependencies, the contents of B's shrinkwrap will implicitly be +included in A's shrinkwrap.

+ +

Caveats

+ +

Shrinkwrap files only lock down package versions, not actual package contents. +While discouraged, a package author can republish an existing version of a +package, causing shrinkwrapped packages using that version to pick up different +code than they were before. If you want to avoid any risk that a byzantine +author replaces a package you're using with code that breaks your application, +you could modify the shrinkwrap file to use git URL references rather than +version numbers so that npm always fetches all packages from git.

+ +

If you wish to lock down the specific bytes included in a package, for +example to have 100% confidence in being able to reproduce a deployment +or build, then you ought to check your dependencies into source control, +or pursue some other mechanism that can verify contents rather than +versions.

+ +

SEE ALSO

+ + +
+ + + diff --git a/node-v0.8.14/deps/npm/html/doc/star.html b/node-v0.8.14/deps/npm/html/doc/star.html new file mode 100644 index 0000000..9568d30 --- /dev/null +++ b/node-v0.8.14/deps/npm/html/doc/star.html @@ -0,0 +1,61 @@ + + + star + + + + +
+

star

Mark your favorite packages

+ +

SYNOPSIS

+ +
npm star <pkgname> [<pkg>, ...]
+npm unstar <pkgname> [<pkg>, ...]
+ +

DESCRIPTION

+ +

"Starring" a package means that you have some interest in it. It's +a vaguely positive way to show that you care.

+ +

"Unstarring" is the same thing, but in reverse.

+ +

It's a boolean thing. Starring repeatedly has no additional effect.

+ +

SEE ALSO

+ + +
+ + + diff --git a/node-v0.8.14/deps/npm/html/doc/start.html b/node-v0.8.14/deps/npm/html/doc/start.html new file mode 100644 index 0000000..b8aa7e2 --- /dev/null +++ b/node-v0.8.14/deps/npm/html/doc/start.html @@ -0,0 +1,55 @@ + + + start + + + + +
+

start

Start a package

+ +

SYNOPSIS

+ +
npm start <name>
+ +

DESCRIPTION

+ +

This runs a package's "start" script, if one was provided.

+ +

SEE ALSO

+ + +
+ + + diff --git a/node-v0.8.14/deps/npm/html/doc/stop.html b/node-v0.8.14/deps/npm/html/doc/stop.html new file mode 100644 index 0000000..b2fb619 --- /dev/null +++ b/node-v0.8.14/deps/npm/html/doc/stop.html @@ -0,0 +1,55 @@ + + + stop + + + + +
+

stop

Stop a package

+ +

SYNOPSIS

+ +
npm stop <name>
+ +

DESCRIPTION

+ +

This runs a package's "stop" script, if one was provided.

+ +

SEE ALSO

+ + +
+ + + diff --git a/node-v0.8.14/deps/npm/html/doc/submodule.html b/node-v0.8.14/deps/npm/html/doc/submodule.html new file mode 100644 index 0000000..d5f3d5d --- /dev/null +++ b/node-v0.8.14/deps/npm/html/doc/submodule.html @@ -0,0 +1,68 @@ + + + submodule + + + + +
+

submodule

Add a package as a git submodule

+ +

SYNOPSIS

+ +
npm submodule <pkg>
+ +

DESCRIPTION

+ +

If the specified package has a git repository url in its package.json +description, then this command will add it as a git submodule at +node_modules/<pkg name>.

+ +

This is a convenience only. From then on, it's up to you to manage +updates by using the appropriate git commands. npm will stubbornly +refuse to update, modify, or remove anything with a .git subfolder +in it.

+ +

This command also does not install missing dependencies, if the package +does not include them in its git repository. If npm ls reports that +things are missing, you can either install, link, or submodule them yourself, +or you can do npm explore <pkgname> -- npm install to install the +dependencies into the submodule folder.

+ +

SEE ALSO

+ + +
+ + + diff --git a/node-v0.8.14/deps/npm/html/doc/tag.html b/node-v0.8.14/deps/npm/html/doc/tag.html new file mode 100644 index 0000000..e04f3b1 --- /dev/null +++ b/node-v0.8.14/deps/npm/html/doc/tag.html @@ -0,0 +1,56 @@ + + + tag + + + + +
+

tag

Tag a published version

+ +

SYNOPSIS

+ +
npm tag <name>@<version> [<tag>]
+ +

DESCRIPTION

+ +

Tags the specified version of the package with the specified tag, or the +--tag config if not specified.

+ +

SEE ALSO

+ + +
+ + + diff --git a/node-v0.8.14/deps/npm/html/doc/test.html b/node-v0.8.14/deps/npm/html/doc/test.html new file mode 100644 index 0000000..3caba81 --- /dev/null +++ b/node-v0.8.14/deps/npm/html/doc/test.html @@ -0,0 +1,58 @@ + + + test + + + + +
+

test

Test a package

+ +

SYNOPSIS

+ +
  npm test <name>
+ +

DESCRIPTION

+ +

This runs a package's "test" script, if one was provided.

+ +

To run tests as a condition of installation, set the npat config to +true.

+ +

SEE ALSO

+ + +
+ + + diff --git a/node-v0.8.14/deps/npm/html/doc/uninstall.html b/node-v0.8.14/deps/npm/html/doc/uninstall.html new file mode 100644 index 0000000..efe6865 --- /dev/null +++ b/node-v0.8.14/deps/npm/html/doc/uninstall.html @@ -0,0 +1,57 @@ + + + uninstall + + + + +
+

rm

Remove a package

+ +

SYNOPSIS

+ +
npm rm <name>
+npm uninstall <name>
+ +

DESCRIPTION

+ +

This uninstalls a package, completely removing everything npm installed +on its behalf.

+ +

SEE ALSO

+ + +
+ + + diff --git a/node-v0.8.14/deps/npm/html/doc/unpublish.html b/node-v0.8.14/deps/npm/html/doc/unpublish.html new file mode 100644 index 0000000..d2eab97 --- /dev/null +++ b/node-v0.8.14/deps/npm/html/doc/unpublish.html @@ -0,0 +1,69 @@ + + + unpublish + + + + +
+

unpublish

Remove a package from the registry

+ +

SYNOPSIS

+ +
npm unpublish <name>[@<version>]
+ +

WARNING

+ +

It is generally considered bad behavior to remove versions of a library +that others are depending on!

+ +

Consider using the deprecate command +instead, if your intent is to encourage users to upgrade.

+ +

There is plenty of room on the registry.

+ +

DESCRIPTION

+ +

This removes a package version from the registry, deleting its +entry and removing the tarball.

+ +

If no version is specified, or if all versions are removed then +the root package entry is removed from the registry entirely.

+ +

SEE ALSO

+ + +
+ + + diff --git a/node-v0.8.14/deps/npm/html/doc/update.html b/node-v0.8.14/deps/npm/html/doc/update.html new file mode 100644 index 0000000..107dd17 --- /dev/null +++ b/node-v0.8.14/deps/npm/html/doc/update.html @@ -0,0 +1,58 @@ + + + update + + + + +
+

update

Update a package

+ +

SYNOPSIS

+ +
npm update [<name> [<name> ...]]
+ +

DESCRIPTION

+ +

This command will update all the packages listed to the latest version +(specified by the tag config).

+ +

It will also install missing packages.

+ +

SEE ALSO

+ + +
+ + + diff --git a/node-v0.8.14/deps/npm/html/doc/version.html b/node-v0.8.14/deps/npm/html/doc/version.html new file mode 100644 index 0000000..75c3c1a --- /dev/null +++ b/node-v0.8.14/deps/npm/html/doc/version.html @@ -0,0 +1,75 @@ + + + version + + + + +
+

version

Bump a package version

+ +

SYNOPSIS

+ +
npm version [<newversion> | major | minor | patch | build]
+ +

DESCRIPTION

+ +

Run this in a package directory to bump the version and write the new +data back to the package.json file.

+ +

The newversion argument should be a valid semver string, or a valid +second argument to semver.inc (one of "build", "patch", "minor", or +"major"). In the second case, the existing version will be incremented +by 1 in the specified field.

+ +

If run in a git repo, it will also create a version commit and tag, and +fail if the repo is not clean.

+ +

If supplied with --message (shorthand: -m) config option, npm will +use it as a commit message when creating a version commit. If the +message config contains %s then that will be replaced with the +resulting version number. For example:

+ +
npm version patch -m "Upgrade to %s for reasons"
+ +

If the sign-git-tag config is set, then the tag will be signed using +the -s flag to git. Note that you must have a default GPG key set up +in your git config for this to work properly.

+ +

SEE ALSO

+ + +
+ + + diff --git a/node-v0.8.14/deps/npm/html/doc/view.html b/node-v0.8.14/deps/npm/html/doc/view.html new file mode 100644 index 0000000..13caf07 --- /dev/null +++ b/node-v0.8.14/deps/npm/html/doc/view.html @@ -0,0 +1,123 @@ + + + view + + + + +
+

view

View registry info

+ +

SYNOPSIS

+ +
npm view <name>[@<version>] [<field>[.<subfield>]...]
+ +

DESCRIPTION

+ +

This command shows data about a package and prints it to the stream +referenced by the outfd config, which defaults to stdout.

+ +

To show the package registry entry for the connect package, you can do +this:

+ +
npm view connect
+ +

The default version is "latest" if unspecified.

+ +

Field names can be specified after the package descriptor. +For example, to show the dependencies of the ronn package at version +0.3.5, you could do the following:

+ +
npm view ronn@0.3.5 dependencies
+ +

You can view child field by separating them with a period. +To view the git repository URL for the latest version of npm, you could +do this:

+ +
npm view npm repository.url
+ +

This makes it easy to view information about a dependency with a bit of +shell scripting. For example, to view all the data about the version of +opts that ronn depends on, you can do this:

+ +
npm view opts@$(npm view ronn dependencies.opts)
+ +

For fields that are arrays, requesting a non-numeric field will return +all of the values from the objects in the list. For example, to get all +the contributor names for the "express" project, you can do this:

+ +
npm view express contributors.email
+ +

You may also use numeric indices in square braces to specifically select +an item in an array field. To just get the email address of the first +contributor in the list, you can do this:

+ +
npm view express contributors[0].email
+ +

Multiple fields may be specified, and will be printed one after another. +For exampls, to get all the contributor names and email addresses, you +can do this:

+ +
npm view express contributors.name contributors.email
+ +

"Person" fields are shown as a string if they would be shown as an +object. So, for example, this will show the list of npm contributors in +the shortened string format. (See json(1) for more on this.)

+ +
npm view npm contributors
+ +

If a version range is provided, then data will be printed for every +matching version of the package. This will show which version of jsdom +was required by each matching version of yui3:

+ +
npm view yui3@'>0.5.4' dependencies.jsdom
+ +

OUTPUT

+ +

If only a single string field for a single version is output, then it +will not be colorized or quoted, so as to enable piping the output to +another command.

+ +

If the version range matches multiple versions, than each printed value +will be prefixed with the version it applies to.

+ +

If multiple fields are requested, than each of them are prefixed with +the field name.

+ +

SEE ALSO

+ + +
+ + + diff --git a/node-v0.8.14/deps/npm/html/doc/whoami.html b/node-v0.8.14/deps/npm/html/doc/whoami.html new file mode 100644 index 0000000..b7b98e6 --- /dev/null +++ b/node-v0.8.14/deps/npm/html/doc/whoami.html @@ -0,0 +1,55 @@ + + + whoami + + + + +
+

whoami

Display npm username

+ +

SYNOPSIS

+ +
npm whoami
+ +

DESCRIPTION

+ +

Print the username config to standard output.

+ +

SEE ALSO

+ + +
+ + + diff --git a/node-v0.8.14/deps/npm/html/docfoot.html b/node-v0.8.14/deps/npm/html/docfoot.html new file mode 100644 index 0000000..3e35341 --- /dev/null +++ b/node-v0.8.14/deps/npm/html/docfoot.html @@ -0,0 +1,34 @@ + + + + diff --git a/node-v0.8.14/deps/npm/html/dochead.html b/node-v0.8.14/deps/npm/html/dochead.html new file mode 100644 index 0000000..1526e1b --- /dev/null +++ b/node-v0.8.14/deps/npm/html/dochead.html @@ -0,0 +1,8 @@ + + + @NAME@ + + + + +
diff --git a/node-v0.8.14/deps/npm/html/favicon.ico b/node-v0.8.14/deps/npm/html/favicon.ico new file mode 100644 index 0000000000000000000000000000000000000000..9e0d4eef78c9c01027fb8a88af38c17628e34889 GIT binary patch literal 7094 zcmeHLI}XAy40Q@fj1>bj6Y33M%n3LL$KVKv%fQIaDVRA#u@eWiRY0^ARe)zH@h@)N zm$Z^iWGEwR$x$&UTC$YqUf)iLHf$?cwLEq_3{81vnt9fo%d(`^`a*~Ol}^W7(+wR6 z00AHX1b_e#00JLIAgfXP&1&IU>hbk#RWqJOQRf@RVdHf-!-ng@@UuiiKmZ5; z0U#gXT)GJTKs4hWlUmH+?% literal 0 HcmV?d00001 diff --git a/node-v0.8.14/deps/npm/html/index.html b/node-v0.8.14/deps/npm/html/index.html new file mode 100644 index 0000000..b4a22be --- /dev/null +++ b/node-v0.8.14/deps/npm/html/index.html @@ -0,0 +1,95 @@ + + + + + + npm - Node Package Manager + +

npm

+ +

npm is a package manager for node. You can use it to install + and publish your node programs. It manages dependencies and does other cool stuff.

+ +

Easy Zero Line Install

+ +

Install Node.js
+(npm comes with it.)

+ +

Because a one-line install is one too many.

+ +

Fancy Install

+ +
    +
  1. Get the code. +
  2. Do what the README + says to do. +
+ +

There's a pretty thorough install script at +https://npmjs.org/install.sh

+ +

For maximum security, make sure to thorougly inspect every +program that you run on your computer!

+ +

Other Cool Stuff

+ + + + + diff --git a/node-v0.8.14/deps/npm/html/static/style.css b/node-v0.8.14/deps/npm/html/static/style.css new file mode 100644 index 0000000..e63b745 --- /dev/null +++ b/node-v0.8.14/deps/npm/html/static/style.css @@ -0,0 +1,350 @@ +/* + +Webfont: Gubblebum Blocky by Jelloween +License: http://www.myfonts.com/viewlicense?type=web&buildid=2303021 +Webfonts copyright: Copyright (c) 2007 by Tjarda Koster. All rights reserved. + +"Gubblebum Blocky" font +Copyright (c) 2007 by Tjarda Koster, http://jelloween.deviantart.com +included for use in the npm website and documentation, +used with permission. + +*/ + +@font-face { + font-family: gubblefont; + src: url('webfonts/23242D_3_0.eot'); + src: url('webfonts/23242D_3_0.eot?#iefix') format('embedded-opentype'), + url('webfonts/23242D_3_0.woff') format('woff'), + url('webfonts/23242D_3_0.ttf') format('truetype'); +} + +/* reset */ +* { + margin:0; + padding:0; + border:none; + font-family:inherit; + font-size:inherit; + font-weight:inherit; +} +:target::before { + content:" >>> "; + position:absolute; + display:block; + opacity:0.5; + color:#f00; + margin:0 0 0 -2em; +} +abbr, acronym { + border-bottom:1px dotted #aaa; +} +kbd, code, pre { + font-family:monospace; + margin:0; + font-size:18px; + line-height:24px; + background:#eee; + outline:1px solid #ccc; +} +kbd code, kbd pre, kbd kbd, +pre code, pre pre, pre kbd, +code code, code pre, code kbd { outline: none } +.dollar::before { + content:"$ "; + display:inline; +} +p, ul, ol, dl, pre { + margin:30px 0; + line-height:30px; +} +hr { + margin:30px auto 29px; + width:66%; + height:1px; + background:#aaa; +} +pre { + display:block; +} +dd :first-child { + margin-top:0; +} + +body { + quotes:"“" "”" "‘" "’"; + width:666px; + margin:30px auto 120px; + font-family:Times New Roman, serif; + font-size:20px; + background:#fff; + line-height:30px; + color:#111; +} + +blockquote { + position:relative; + font-size:16px; + line-height:30px; + font-weight:bold; + width:85%; + margin:0 auto; +} +blockquote::before { + font-size:90px; + display:block; + position:absolute; + top:20px; + right:100%; + content:"“"; + padding-right:10px; + color:#ccc; +} +.source cite::before { + content:"— "; +} +.source { + padding-left:20%; + margin-top:30px; +} +.source cite span { + font-style:normal; +} +blockquote p { + margin-bottom:0; +} +.quote blockquote { + font-weight:normal; +} + +h1, h2, h3, h4, h5, h6, dt, #header { + font-family:serif; + font-size:20px; + font-weight:bold; +} +h2 { + background:#eee; +} +h1, h2 { + line-height:40px; +} + +i, em, cite { + font-style:italic; +} +b, strong { + font-weight:bold; +} +i, em, cite, b, strong, small { + line-height:28px; +} +small, .small, .small *, aside { + font-style:italic; + color:#669; + font-size:18px; +} +spall a, .small a { + text-decoration:underline; +} +del { + text-decoration:line-through; +} +ins { + text-decoration:underline; +} +.alignright { display:block; float:right; margin-left:1em; } +.alignleft { display:block; float:left; margin-right:1em; } + +q:before, q q q:before, q q q q q:before, q q q q q q q:before { content:"“"; } +q q:before, q q q q:before, q q q q q q:before, q q q q q q q q:before { content:"‘"; } +q:after, q q q:after, q q q q q:after, q q q q q q q:after { content:"”"; } +q q:after, q q q q:after, q q q q q q:after, q q q q q q q q:after { content:"’"; } + +a { color:#00f; text-decoration:none; } +a:visited { color:#636; } +a:hover, a:active { color:#900!important; text-decoration:underline; } + +h1 { + font-weight:bold; + background:#fff; +} +h1 a, h1 a:visited { + font-family:gubblefont, Gubblebum-Blocky, GubbleBum Blocky, GubbleBum, monospace; + font-size:60px; + color:#900; + display:block; +} +h1 a:focus, h1 a:hover, h1 a:active { + color:#f00!important; + text-decoration:none; +} + +.navigation { + display:table; + width:100%; + margin:0 0 30px 0; + position:relative; +} +#nav-above { + margin-bottom:0; +} +.navigation .nav-previous { + display:table-cell; + text-align:left; + width:50%; +} +/* hang the » and « off into the margins */ +.navigation .nav-previous a:before, .navigation .nav-next a:after { + content: "«"; + display:block; + height:30px; + margin-bottom:-30px; + text-decoration:none; + margin-left:-15px; +} +.navigation .nav-next a:after { + content: "»"; + text-align:right; + margin-left:0; + margin-top:-30px; + margin-right:-15px; +} + + +.navigation .nav-next { + display:table-cell; + text-align:right; + width:50%; +} +.navigation a { + display:block; + width:100%; + height:100%; +} + +input, button, textarea { + border:0; + line-height:30px; +} +textarea { + height:300px; +} +input { + height:30px; + line-height:30px; +} +input.submit, input#submit, input.button, button, input[type=submit] { + cursor:hand; cursor:pointer; + outline:1px solid #ccc; +} + +#wrapper { + margin-bottom:90px; + position:relative; + z-index:1; + *zoom:1; + background:#fff; +} +#wrapper:after { + display:block; + content:"."; + visibility:hidden; + width:0; + height:0; + clear:both; +} + +.sidebar .xoxo > li { + float:left; + width:50%; +} +.sidebar li { + list-style:none; +} +.sidebar #elsewhere { + margin-left:-10%; + margin-right:-10%; +} +.sidebar #rss-links, .sidebar #twitter-feeds { + float:right; + clear:right; + width:20%; +} +.sidebar #comment { + clear:both; + float:none; + width:100%; +} +.sidebar #search { + clear:both; + float:none; + width:100%; +} +.sidebar #search h2 { + margin-left:40%; +} +.sidebar #search #s { + width:90%; + float:left; +} +.sidebar #search #searchsubmit { + width:10%; + float:right; +} +.sidebar * { + font-size:15px; + line-height:30px; +} + +#footer, #footer * { + text-align:right; + font-size:16px; + color:#ccc; + font-style:italic; + word-spacing:1em; +} + +#toc { + position:absolute; + top:0; + right:0; + padding:40px 0 40px 20px; + margin:0; + width:200px; + opacity:0.2; + z-index:-1; +} +#toc:hover { + opacity:1; + background:#fff; + z-index:999; +} +#toc ul { + padding:0; + margin:0; +} +#toc, #toc li { + list-style-type:none; + font-size:15px; + line-height:15px; +} +#toc li { + padding:0 0 0 10px; +} +#toc li a { + position:relative; + display:block; +} + +@media print { + a[href] { + color:inherit; + } + a[href]:after { + white-space:nowrap; + content:" " attr(href); + } + a[href^=\#], .navigation { + display:none; + } +} diff --git a/node-v0.8.14/deps/npm/html/static/webfonts/23242D_3_0.eot b/node-v0.8.14/deps/npm/html/static/webfonts/23242D_3_0.eot new file mode 100644 index 0000000000000000000000000000000000000000..a2ce3085246c3914132e3bba552166c12071a598 GIT binary patch literal 9662 zcmdU#d3>C8oyR}V9GM&~Z3t;O%cN-wNGPQ-EtIQ3I0^-dT%iaw>4ctXW7+~ms0a~3 z5u=DAR763o$R&bStcX={5SA6U%d)P!+f^5^vWi*|CC%*n`~5w0BrV&0t$%H%^O@gs zeDCY`%=F30(k+vuND0|rLg_01NJScm?9AMGH`qtTpP%OVfjQTXXR+l@c z)m)jXrGDRX&Rof=8!l6|NNd!^%jmmU8=W1kgv&DMr*iM*tW4f?juz@Hod}gQ5uH!n zi8{;GGPRp%=8w{KN^17m=N>-&*hKfu_zxdy!3FJScC6TV#o5w?`=s>Ng*~0UV_F8c za=oAH{fjzR^%e>^Ta)a#deQQ=m*3TL`+-vCb!psVi@Q5>uRr{=3%K?g?-`3ZQL`<5 zJ#ne#c+%pY)mOc`ea~qex4`qJ3;UA zSLR5`$Drx!UAby?>%Fs{kgDwd9i|EHX;F$#OM;Pqc7}KRwR0Z0Y|Jrls4n@c-LiS} zC8ocgdH(QuQek~sX*;ZmlL&E%13^-vGN^{7*J*RJSIL1#J+4`zBe98fmbbA$3h%u@yE+#ej^wje)m%$xo$k?t$#r*DiC<#bBCPHAH4d>TsJ<$S7?jqZup8FfYb$LnhCs~6*SZH25o zpw$1PR(TT5w3k-eM-yG7#Wd2a4yKVF!e_aucX3Bn=h37)xibf5bq18HxZj4tRE|%e zwT6aY zs~ioduIcJp-rcpPCwn4IdD&Vbn((-)@Hk%C)n6A$n23^OM2b#Xr3{^`hW=HjQDo~L z8l$nQ*Pd#i$2Dr4#%piwLk{hy{dIsQ=s;|0Vr(^Qk|t}44k8MN=v_LLetsBUJDdS~ z1hQN8ZnbHKX3`&z(kuq*F*;Vq>3Gd10w?Muwd-WE`c$2!IXayv&DEKV#j`a}=jc5; zmnfc3eqN{!U8MQCSnt&(x>T2GfjZMuSFBmSeC&#qD|$NnmMvMasIPnVn!Xjm-f?Jc zujz2OMH}^Uv_~{0YLB|28>9Q9&C!d|wnS}WN@7-Ge&XuH9f^&JmlAI#$0cVZJLv!S zC7(?GI#r#Tl4?&aP2H5bFSR+fH8q&tH$5$VdU|QPKfNLSbo!T7iK>ZJ?Nwb>*HztJ zwXy0K8D%D9j>*i=T%EZi^GN3D%+E7#R_|3kt$JQ{Z}qL!k5>P*dRtAZW>U?pn)x-W zYX)i_s(HR@+Hsjpd*6i=*#^yG=kc+lE``pMs1R>QgS6<5JEWZou zUFSM-aip~RlC=6DDIc}u(Kw$s4+KbNb35AI7A)b<49VfvvK?c{_yZ)Ifa>*F(%95s z+Baen`nR?vIZA9Y#yRIRnR|7Q#Z{yrx%;DGEmI;bCN89r# z2b#A0A!TS3QNtNIKjCT;sex!9j+^NTo0&M2*bM}ul35EnH1Yj~^?rW_`ED1U*c|PY z86hKL8V`oqOn}S?j|+#+ha~U!92>!BW-+_)AwDSwn~0e2h&+5eKKY_8%y`RpuactQ ztV-f+C_4_@Z70EO_Zo~y>hV^CEqH9lhD3)s4)(?uB|BL8eO7%$qgZ(q%N8OLd};R; zeHoEo#IAKFAFaIH4?zojFf@u%-HruTv9RW^Tx)TiN05)_ohBw$-XxCEd!<_iQC>q^ z%zyk@r3d{iU#vTX#t^p!?hW^OEhjBcoO@$aBe%Elst*#d#-vza=_i{APzV+xT+S}& zjR#!H^vQWH-^Q?RAqq2FAepP+4~&cY)mf@c)Gbvdy1?U|bq|)qsHD4j&Ra1V2PfOCR`i|_*P`z|vY~|r z{XM$F;|q_9yohygvhLfIgub=0fd+&0Q3xd?tcM_T#|Dd`m4@k_8ZkeRU(8{0v@(~` z-lvJRI#^k9hSWA5)+gc|8%>uR#-p;%Xf@8q>#fXbSid5c#;eYHCA!3Ym|Agnn0c*j zgq{{`oza?w)jP2WR#EWQKd{YaBh|!nK(S^><;IFiW|Ebv8CxtMUeD0P@*|&T-Ynz3 z*W^9hk{^#k!EiKRdM?_+*64y3E?>^e`e*P8^Q7MUwJjp+6if{3qoyB;4#nb3&xl6eeEjOj1 zx4mv0qo6gEWT4lr&HUm-4D^FrVPZRH>nB@=>FvE|WW*|K-#b>>c-w#C(_t|$`;E3k z3nS*iZ=QigzhQ}WgQCw%y^q-0cBi?1JlgYWOJ?)-R1wOD$?p3q8x1YCo$_26InP5K z_+G$z1!5}FEcD+Idja-&!D^Fidx*Hl6t%T(iNsy!8I^8!#xKt^WTGF*R$@>T>uiSU zZF^PA@J4T#JJ*S6537<1?h6OEzZCm8@_3FuS+v7iD~V&o6=5&iGGZ@eI)uI#d=R=u zY($8?m7D4Rw>&GrpuE4e@O4oILq#@cC(7FHU3Ai)V}N-0k=J)3x*UvW>aI zGt_%Wd9MLe+rNfd@9+lag~~Dr3D0Lmy3mU)+Ehq9FZ?;V)EzDD?9s#f_yDC7=Ub3j zo-@{u(J&EYl4G_Cn+&qXN^2*XW|cp&$NHA1KZVh-+f z=u3GRNXvOx-k-aDwy$Gf8gghDU2K>8lD&lOhvWPUyE8l!)8arIE6F# zL}A@E-VgJwhGkz|tnEHe?NPJBr?G6Wxma@8#df${lM0hiGhqu`ily0FoTb*6?aMMU zKlsQZS9BA)^RGlVA_t&i_hS`P><`>tk*iqXW4J^gYIXQLELLebFnkeGoQH0s_tUt# zeGY~vqE7V4JyG-Bq!Fy1OAvxC>zmvpoe{=(d}?{QtWJ+C6!vG_fmNjGIf7xcau z_AO?$y|`r0GW>IXJTv#x6g-Z_dB@(vGmaF)ZIDA0I)Qn>Q;pxZ>`$ZgR&{}27Bc)2 zTBB-^Ur50^)f9%fS__U=9k_=^fnyxUYBcM5?E&toF<^tnf_phOs=ly;@AdZt$EyL{ zTYG`~IPR-P*86E3xWC4O2WW3_g5!bOr!dGb7yE)u+7Fzl{lR9(NjiY_WK964=s@rw zWx<0T4^dO$ZGPdH2p+0tutk%=!yKn-GV8-N1)QdXz$0`pINh;ThZO$GFCp&&+jJ;6 zLoMJ;$0KzZ>!UOkoTbCTqcsgY#_?DkQTPkLm`n$cS1UMM?*>nBJW*||PtpvqT{FRx zbtHI-jt9@yY;d0AIXa>6XMTY>5j;3YZ(yi{|+%N!TzOxB$`3+&R_ z;6lv2;Q3trfaiuOQZ0GmE`QZC> zG1#Z~f~y=?>k`&$bSZd+E(5RB0`MxwwdySVNmr{2e7_cg*C+>G>$pzctUsX3!RxdL z{Gb+t*E`;zC51n#UrWIcX&HEH|Nn zRp5YDgP(Bxq}H&$O;>=Q(v{%tx(fWX<7c$C@Vf5M)!=9Ke(+9R1K#DhUe~hzoYsMN z>jU8Dbscz*;}`V7!teQA`g-tQ-2mRFe(+0Qf8}woDtGWri-|=g@x$rwZ zppSqL>Z9O8x&?gL@ezHD_1ASP_^3V(enSJ`V~&sO6NUfMH}y&ITe=P0s8504c6>s& zv;K}g4Q|qB!0+k~@JYw->9d8`^px%dzpuN%%~}us!10Ir9P1zHZt!V+9{jQH0rQT} z=nIA4>L>al_^j>)pVNKd-#I?7FR}i6eHr|zz5>3W4dBll|3P0ZY||Fq5B{UR2EM2V zz<+XlNe{CAXFUY|Tn~f)qDR1AIR2}?UigjvO^<^Au5W-_^%(dcj=$97tbe6%g1^?c z!2i@n@MXtW^zFi{dR0$=ztMNVZQ2C>*6}rcmo>ftf2Z$(zt>aX>yCfW_Y1G+kJ=3W zNk0I$>xbYQj&JHmtpBX1!MF5d@Gm@dy~6*GF??Ik6kgV#egf{$v*3`P0}GC9cMZ97vj+n{}XXFkO7ZpM>CDSsS zGRu_Al4>$wQ9}U=KH5VDV5v(drcE{s7Ymf!qBl4>*qXp)$kdwt0wu1UEZsh><_4Q_DjmF=0A5qWK9O%>NVj3l5diylK2cpTJH~yxJ9owhrnZLHrC$Y$%8+@Ph zKyTBH>hVgp4H})2EcGu^svPc}uH;`2#mbY{FR)0o2f6qLBj`IIXi-50Mb)DayKuPb$!UWnJ# zC9;M=Da}(S=hkS6R%xZunyiVMR)pFkLP!|$>r|)2Gbau1~F3X^w$h}vyGI>)tTB!3i z3#!w(ql@dSxw1%$xti87Ts@Z0qNW|(k=DgXZs*PnnASN^uHk;ObRx&6AuU*u=d^~i zW|LX7TGxOX?wq}krfD=OYHEHlN|Uh`x^}2KvBxAYCj_&;?SKl*KD?5o3sQXOWm z>*!eC*|Ba#dKOK2*?J~PP8J)6R6?CpD`d5vHkgdZsTq9Jg zgH%V4tJg@4(jhvO96DS_=tzy$QP|X=F>2IUjnjA?O%#sRJ9HfVd;(rOo}8JC>}I`F zEt*RHoS+jmoh+H5lXZ$t)l4EVi+Hx`46=H*&e9y6O_a{ndBpkx&DDi^mo6fTmyn;A zs!f+^zAo3hb%n0fRa&6-)WntRmMn9S-EI+=h}6vR|b1WqP4xIz~MG+ z(@W8?XnfQfbwoEu4@5hn7oy#X>csfO^u+wchQwWoZHX5XZzM-1rzYFz|67yaN&dR5 zvTS@=YuVDWTgtYU?I_z-)|WagH7Rv=YH4b7sweeS>X+q-@-gMD*SLN-Mk5&G(a(7i()!3@(Rr9OXR&`fB zT=iVl?&|XD@zpb{=T~p2zPGx!`o$X6jI24OWwxM<$5D~V%baH#& z%#_|zx@^1IoU~r!bIR_mk?Od!uC}>0S>N1}jk^20GTAKcd2ef?t$%0K#BnCjDe6x2 zCesM2A?k|io1utW8j%(?+CkKv$@CA&BzpV1vKc-ynQZ^gjIoHCoQX|CC3@+FHRQr^ zCcD15wz0keCe6+D#>5%580Y4eMt?WfH@4V?Oti<@X9oWv2&sO#^inos`JLP1I@gek zgQe9Lq}2vV*{CUt#@VcSAV4ym+1u*2UQiSN&C@%t-~?{<+KmLV1-Xb6Je z4b@J2CDX2iB}qbA{N08ur%g3LNqVF_$j!B=MluDdSzKwaIAfePYKmip&Cx!Y5i%mC z@nD$E1jvl=xNzuvNb=2|V}tli%V!rp#3#jI6A|+rk%y1RC!4p08E^USRg(9cRY{x; zMaN;g?If7(UV{-yJ<4jZ36JgVNwk^cU~ha;vW=DBXVphE@|8!i>?9Jwmv&#?ml63z z?3$8B3v2$0wHDWT1oTLa-3wa`r=SJm6BK zcOC_LSlITdl-}wjFY*S;vbRQI6ypgv}~ z;nL#@rIRG7&O&9PZlNmC1s(_1Jy;H-g6`%yZ^dLBoNTjN(tAQ&^S<}Uh87z1_vj9c zFFZ=}BG$dZx^F`g`sVsN8Vu5hAe4--9)irhJr+YN4b#1B(ELDtK8MNC(p*M+pC;Do zU}eb}Qrmb~pNMm8C|zy=o0r~YQ^1Q<~6qvdRnk` zMr#&U@5CZlMZsJDz&4wWR1?nu`I;e>>q{z`Nmi(4Y_WiNJwp@Ak9?kavyA&*gZFGp zemn{V!_j={xo8VpqYGNNd^s=cpTR54lUncBwur1#Ffpu;n$j5H;flH~R)t|5W_&Mp zq}Z+gT zx5|t`TvxFLQ9P^0(GzTbQK9s%5C!i!j4-361zW;JP1YxzO$o1Jj<>KIAWv%`)gpZSXx#gjDN&6~*2MWq~kmef#Z6g{fPV$+#_$nkDBzPoJ zGA~4|P+)^?^=Jic&DMsZrG+kv-5X>9Y?m=t7M z1_ysOGK;c%d)P;qCwKOD1y|bCbDHF4^h{dyB9sr4-S<^C8k%f7<+(C=o`*W{y@2%! z#FV62=)Z&Z0_^jG)h5~Y5OI&mYir#SiTlqpD&6diU!G^kL_d7Y=TJA@*_P@f>|JZ-=#3632*3!d|px&|b)N2z@X3Aasq`h!A@# zH`D(gc~*cyaer&&jnE3ORBGIIqp|mVPBr-%Q`to$`yYGO2+y*~{NBEfzGS_L>Q+wb+KYv=1_8*_zcsQ0$w zUIV7Ke+{+X<_*pZm1PhTp3m}hp%+`UsgQVH_;YfhJ6hV=qlfqLZb~Q4w;;1PXRIHi zVIs&R$7~fg8Dx!>);==LDt}^+^({_;&|B=w1K(hTS(B%?eU zyrsOCwnLZ&eDg3Fsg3nVxA-JMbDkF3tP*TbLz4E`NanbINUXc>HQW5#4%<`t{vqsT zDx6b8i`{RUhrN}#n?g00xl>B!d(ff8>tQO`^Q6rrE6@_B+f?Zey_qk^+?ZM_{$-!7hjjfS0RA-Q@adkNbQ$N3j_XLu&2#ep_lf>0|Q+pQV-erWB9!n$j` zALd&P%f7f+TYa9|qh^UuW7%GFvE;CeZF9LM6(*r(!WOm=OS3gUORX>4mt|yr@R3C> z?cDxJuhL>*_#z}f58X!Zr*U=rB#fg{ z(9-g>NaOiaw9l$BKR?qpsQ7MdA4;b#&V1AJ|35oJYcbO;)@HHKusA*gW+xTH%LC(? zfhDbl*ajs^bNE0pvPKg6h+AV(3Nn306rNd0eKX#^-yyGv6K_jEf7C-!=<;8<*#xv~ z;~z;D>X!L5Xy(8$-YO>3eH-mdI$8;TVQ$*@xGvkCSCQCx`UiodR0kfSgTX@` z4^uts!!;5-LZiSVbqF}x@hBad>*JS;!@vd|4vx_gV58$$9m#r}MuX#Z6nM1K;4zNJ zsv-9lzi^BJk5ePqq_N-x$B7!p`gn~8C+TQ#vW@|#I5z9p++X=6IT3Da1sbH(7foJFh@Jz?q zIx+XA&eC*nj!pv4)(r3*$8&Wu>+^I9c)m^rFVIYIuH%I|E%#@Bftdwfq|?ER)e2tX zI8SG=zEo#|ZJG^UrnA8Lj+bjr?hSsaIUBq}=YUu0T<|K#1v-y)yUqtYbOE?fbHR*b zr!LIB&TnS#0vG8baIr21mpCrfC9Ice9=KeWf-BSpu5?_b%W`}8eQ-Yb9$gNu*1N$q zj%#%V>vg&kyhc}n*J=THo#T47=l-M(>Hy!Xh2TbI!0R11sgw2lbTxQ`7J={AV(>=C zo3teNM{U+p@B>-~-mK-|2OV$G3f8x3CHNt&0za%S@HWSf=smeV=yt6JKdLogx7LCm zbNsm0vA#psfS=H{;GMb-{G{Wjv_AKm?$QSE(|Rv>w>ER@F9H| zd|0=Ek2pT6kFfr#ZU-OJN5QYD8+_dH34JX0zxuj94t_&-fZOy5@SBcL>Q2_*(kH=Q zeG2@x?gGE#_+5QE_o}w*Zt#1$2i&18;P)MWpwF=Wq3#8r(r3XR={_*)__RKk`>lSg z&x6nCe(+gs1%KlBoW8*NpY%oWr}`53yn4W&IsUW0oZGFPdI0KU+K&w@EeHoW#fTmA-4C1Mf) literal 0 HcmV?d00001 diff --git a/node-v0.8.14/deps/npm/html/static/webfonts/23242D_3_0.woff b/node-v0.8.14/deps/npm/html/static/webfonts/23242D_3_0.woff new file mode 100644 index 0000000000000000000000000000000000000000..46540e82af7b76127cdc179f65d2e2db6e09a2d0 GIT binary patch literal 4373 zcmXX}2{crH8@^-4%owsHOBk~JDKtiykUdKw^e6i=W8cO$lqFj#TZ|>L%a%1Hq_K@% z${;)0BD=_%BH#3V-@WI#zwcPSWF#KJGp8dT708URoSgw6C-(qHYK#E@z|;VMy*5)kh0oamXHSilrg~(k!0c3g zHg=|p)H)zkeu)Ypx^>z|&UjycswPC`K2(3y>i&7OyQdx12Z^F;-G9NE!V1UZ{QuU% zL*<-QTmqbcs~$MK12r~{s$;0D&qx22+g_doUuqA7R8Jihr&0y-B>yQptUVTc%XScl z#Q`8qD77jkJs{=(I$-<4d_d;M3C8APL%I#1!O4h>!GnfG2G(F`^hs_<9~tr0=NdZv zG9V|82%skY8|SEv%_5Wg$nEm6qiNycce&K0Z0ymtKfB1}PI6y2kZ&4hF9klovvbz~ z>xDJIR@zbi%zZNL@JYm7Ge~0*>bcNX3%hj%jRpWTGlSrNb7HZ!SS%K5%W~-hyfB#4 zlv6xRnga|oh>y;T$ALP`mq}-5;kF3$;aSgF@|nn)888L{+pmKG9V9QctpDbq_W8dX zb(6_Ep^Rc+umOZt2n4uQLj3)wo+NxcN4~^x^W3fM0x;SDW-AWuy^MSbHqry3zkO6r?f{Tio1s}1$-=Gnkn9{FUe90rct<9};Q958Trqb>t&De4ikpR1^;+}qt1az9E6!WuZjDF9z;@ZvuXudW=1EXIktuzp_BG>! zWXcu&XdQXC^%)(u4T5s=<`<*L>!a3ty;4O!P3Y1kA?0M!+1D&oL7v2`j|Sh82#4A& zivwnd56=2cmx!d3hS4dm8FnA%k3zY@G%kxa)E(|Wh3|LJdjtZ2L0A-WV#aD>W@hH9 z2Sx4&!Oll|pqMh(La%@eZE0orJ;0jhby+~*rqL_$NuQ;@ zt|MiJRjLKT{pPi%$TrQGx~7&Hgk0Q~|3V7xE|m^myEmIkYab;G7$hwuw9wstj>_iOt+6Wvk5u@ zK9h&|x9gDxTY3XZj}5lxa@K$NmelXgmS>mWKWH)2NxL!L*LY8YeY85!c@*kdmVHzl zWV5Y5(DqSzHgdSFL!+)J85+Od+}T3lo8gOUUZ3tSV-*Q*eZ(ry^;6OPXR{d|deUa1 zMQZ(-r1DedPgW@Hw(CkuD30>r`%$bjK4#3d&;TD{&qE{nQaPh8H0U!kOtwq4>A9bL zPy6Y52thCA62<&S^Lna6_)oqaHLDFpo^mGHr&=v9w29)$CwgLv$2rm4ML}Vn{?_es zds!BxWp)WmOCmK6{OxPjr27Mxt$!OAc#cwjJyq!HFF5olj&vP!CQVH2&9&|vzwcam zZ?3t0w?15PdDzyETy7>sr$2q^fVW_)f>kHH=b6K{#qB%sC3hp9pO?7FfG>Z2piQx~ zx^$BThl!kUaABUUmQe6M_wah|WTuod@qMno7=ZMQ-}t3MHpM z9LvF@uMLC)>bP*RwF$`@KgPsYJf=3p-WC(>iDi6NIAy6U?TLR%YZ5u0GDi}nrE(4@ z-L9F~y|e236ZoCQQ3LOk1+d<9NRpP5A{c9@GE2kgV;wxD(? z>z2JFi$e~```%{obrN*m{Hg=_*8Xpm*q4%X*7NiuVQY<2r>44`mD=JuhfpqCu6ZNp z4p@VO((K3QVh@)TVna5?hYTgF#QAoE)0e%LZk*ll(#;42E_nYDU1;WIoVx5@*3)@$ z?W3q&&1ExN!r;@@CbQyz4wnv`3!!SU3FKdt4?-`c{diM?89);l&L!+ z*}^QEbj(3AHd`0!Urm&vvoFLUSUq3KdDb6ijrTq0(J{aEPZBF)f7V(Es&HH6fx%s_ zZ||?heyPnd3nBZY@?WpoOH--#yXnK=DN&=9&{^yx6HzkwbSk$;w@S|zlWU{wEk_gb zHc&H9a;w>Rd`ZwwWo^Oq(|GRiOzeA0)kM>`6#rrZQ=%+FFv{pT*Nh+iZ&kn7?f*nBF+oZMEqg8`CX4;hV(~96oobZ*P3Ei2VGqc8oUxfKan|?< zHe<#0k<`}o!|Ai2@xey-WDl}20lpvHbV2fAwdtimyb0yX_A}*wX50P@H+ye2aRCVs7`Xxy7zLe3t8`y747!aKu8UQ$^v5ncfk5X5(_Ns9mw^0fpE=2waCM=ogw!#UL%|6VsFj_{&LUG~bg; zNR@)6t1pi!)5pnUv;U-?+be9i*bEo$|2>DdZvAkM6GM}*Ctt)fteH^r=?#lo=a~LB zMsawx&nGeXtjc;OqNpx(Mx<(@%XK4$KzUAJH+yFqM}O1X)=BZ5*vhW9S%J*g z=D~O!@11vOa{r{#FjT6@{pZjKI-DP}9t{Z&xR$*$YX!h-Q z-MOFj{JsUB^oqL{AFfn1X0*OWI(QOJ|9BJ8w|wKBu>%9C3kTG?sV($<)Aajt zJ@@$ixWM?o8kW`2iMVm0(chuKbdZ$b-+w4_&=5#)0yGzfM{8zkwo>up)Ajgi4~u%d zcu;+FQ&aWM_I@+RK!4DKFwRbYsjs`@j_SIzF#@(MhIX(;X0gC6Zi_`0twmN7RtW2P zeO4A5)?}6B1cPK~a^mGc4WILFh$Lt2B-b*mYmy6B(#CY*U~S=uZ`*!hjCE4@NJgS` zM)W%w0-D}MMr=)*drjuXMQJUx$i)JVC4uB+;kV2DvCHR{1YrhQubD=p^XtB-!ZPRndWcG(ZRHnIT-{5N-i6&QGu!F|Pl_xH!xX ziC!2lYjb@bm2)>c$vom;^W@LwVy2nb%p+@lp}y6kzSUV*E3xGlOTWy=6eeNvYcPzM zyckST8KxiuQ%tId*B5H;KQ<&ZGBx zl|^v%rQljg!D?YagxzX|-CF+QYT4r2E7nJ>YrKl~=M{agDf%IreO?!d9c~qfoXbD91Du9m>JqH`n3W;1Or(wv@Iq9OYD7 ziG5aSUr}kBRmoV1d+1B7(;f8F9XZhbe6B4{ckGVtP`~czRo&s&ZFpVc_nPdBq=V4=MB5hx6Lz@j52*((yXH;kAqAbt=ulriXAUdiuZRSq3Y1_$YEK^dJ-mw42GI&AqP87n(k0tYS<|%T3IR`QBJ7GlsN7PoKyAx|q37 zz-(}|Nlc!f`6^bwKJGs3IZ-(WZMBOG8PGcoxB4a6cu+h)uo>;KOCNM#a=7NXIX)K= z>ZNkF^zu&^|7m7N;8p)@!J%^=UPhiix}M&ap0I5%HGIJXxzZ!qqN4~VS)|npztcX8 z(}Cp5{@gq(Wy27)Dur4npw>d$I4t8Ue7_qt93XGQVR2LIjEr7BySwvS?^YE^Uhe_x~;}tXLKo`dWp~y^l;NZ z0L^u{>h{fD?fcp@zrv(czkqgyb6olk;=T)DH@T~-B6f&9ZNkd^o9WA-_j znY^(|joMo08eO|F&I}ikzWDlp()O&FqkF2RT-!t1D{VdzbO9S<5!ot>eromnM)ciN z_1O)l448(;TBT~iQ#@Ol$fKl=@^bL6GyZ#_EKX)}+Gd<_g6Vghqw99c5U0Vzvh)05 z%Qvq&-zH6#asBFAV0{~oc>e$ze|)8a`?c!imw*l!u=7a<)Q;s|id`jIF2>(EcvGsx z-sKJ-5@~`9TaE_YbMLsz7z&ufU~NwLz(<+3)rxDaBJUIb+_M@Rb0 k3llqQJvy9>(vJSsWM0cZZp)9A?P`XZbP7B(uxlCr0WrSuZ~y=R literal 0 HcmV?d00001 diff --git a/node-v0.8.14/deps/npm/lib/adduser.js b/node-v0.8.14/deps/npm/lib/adduser.js new file mode 100644 index 0000000..2d6d6bc --- /dev/null +++ b/node-v0.8.14/deps/npm/lib/adduser.js @@ -0,0 +1,138 @@ + +module.exports = adduser + +var log = require("npmlog") + , npm = require("./npm.js") + , registry = npm.registry + , read = require("read") + , crypto + +try { + crypto = process.binding("crypto") && require("crypto") +} catch (ex) {} + +adduser.usage = "npm adduser\nThen enter stuff at the prompts" + +function adduser (args, cb) { + if (!crypto) return cb(new Error( + "You must compile node with ssl support to use the adduser feature")) + + var c = { u : npm.config.get("username") + , p : npm.config.get("_password") + , e : npm.config.get("email") + } + , changed = false + , u = {} + , fns = [readUsername, readPassword, readEmail, save] + + loop() + function loop (er) { + if (er) return cb(er) + var fn = fns.shift() + if (fn) return fn(c, u, loop) + cb() + } +} + +function readUsername (c, u, cb) { + read({prompt: "Username: ", default: c.u}, function (er, un) { + if (er) { + return cb(er.message === "cancelled" ? er.message : er) + } + + // make sure it's valid. we have to do this here, because + // couchdb will only ever say "bad password" with a 401 when + // you try to PUT a _users record that the validate_doc_update + // rejects for *any* reason. + + if (!un) { + return readUsername(c, u, cb) + } + + if (un !== un.toLowerCase()) { + log.warn('Username must be lowercase') + return readUsername(c, u, cb) + } + + if (un !== encodeURIComponent(un)) { + log.warn('Username may not contain non-url-safe chars') + return readUsername(c, u, cb) + } + + if (un.charAt(0) === '.') { + log.warn('Username may not start with "."') + return readUsername(c, u, cb) + } + + c.changed = c.u !== un + u.u = un + cb(er) + }) +} + +function readPassword (c, u, cb) { + if (!c.changed) { + u.p = c.p + return cb() + } + read({prompt: "Password: ", silent: true}, function (er, pw) { + if (er) { + return cb(er.message === "cancelled" ? er.message : er) + } + + if (!pw) { + return readPassword(c, u, cb) + } + + if (pw.match(/['!:@"]/)) { + log.warn('Sorry, passwords cannot contain these characters: \'!:@"') + return readPassword(c, u, cb) + } + + u.p = pw + cb(er) + }) +} + +function readEmail (c, u, cb) { + read({prompt: "Email: ", default: c.e}, function (er, em) { + if (er) { + return cb(er.message === "cancelled" ? er.message : er) + } + + if (!em) { + return readEmail(c, u, cb) + } + + if (!em.match(/^.+@.+\..+$/)) { + log.warn('Email must be an email address') + return readEmail(c, u, cb) + } + + u.e = em + cb(er) + }) +} + +function save (c, u, cb) { + if (c.changed) { + delete registry.auth + delete registry.username + delete registry.password + registry.username = u.u + registry.password = u.p + } + + // save existing configs, but yank off for this PUT + registry.adduser(u.u, u.p, u.e, function (er) { + if (er) return cb(er) + registry.username = u.u + registry.password = u.p + registry.email = u.e + npm.config.set("username", u.u, "user") + npm.config.set("_password", u.p, "user") + npm.config.set("email", u.e, "user") + log.info("adduser", "Authorized user %s", u.u) + npm.config.save("user", cb) + }) +} diff --git a/node-v0.8.14/deps/npm/lib/bin.js b/node-v0.8.14/deps/npm/lib/bin.js new file mode 100644 index 0000000..719e887 --- /dev/null +++ b/node-v0.8.14/deps/npm/lib/bin.js @@ -0,0 +1,18 @@ +module.exports = bin + +var npm = require("./npm.js") + +bin.usage = "npm bin\nnpm bin -g\n(just prints the bin folder)" + +function bin (args, silent, cb) { + if (typeof cb !== "function") cb = silent, silent = false + var b = npm.bin + , PATH = (process.env.PATH || "").split(":") + + if (!silent) console.log(b) + process.nextTick(cb.bind(this, null, b)) + + if (npm.config.get("global") && PATH.indexOf(b) === -1) { + npm.config.get("logstream").write("(not in PATH env variable)\n") + } +} diff --git a/node-v0.8.14/deps/npm/lib/bugs.js b/node-v0.8.14/deps/npm/lib/bugs.js new file mode 100644 index 0000000..fa66dc3 --- /dev/null +++ b/node-v0.8.14/deps/npm/lib/bugs.js @@ -0,0 +1,44 @@ + +module.exports = bugs + +bugs.usage = "npm bugs " + +var exec = require("./utils/exec.js") + , npm = require("./npm.js") + , registry = npm.registry + , log = require("npmlog") + , opener = require("opener") + +bugs.completion = function (opts, cb) { + if (opts.conf.argv.remain.length > 2) return cb() + registry.get("/-/short", 60000, function (er, list) { + return cb(null, list || []) + }) +} + +function bugs (args, cb) { + if (!args.length) return cb(bugs.usage) + var n = args[0].split("@").shift() + registry.get(n + "/latest", 3600, function (er, d) { + if (er) return cb(er) + var bugs = d.bugs + , repo = d.repository || d.repositories + , url + if (bugs) { + url = (typeof bugs === "string") ? bugs : bugs.url + } else if (repo) { + if (Array.isArray(repo)) repo = repo.shift() + if (repo.hasOwnProperty("url")) repo = repo.url + log.verbose("repository", repo) + if (repo && repo.match(/^(https?:\/\/|git(:\/\/|@))github.com/)) { + url = repo.replace(/^git(@|:\/\/)/, "https://") + .replace(/^https?:\/\/github.com:/, "https://github.com/") + .replace(/\.git$/, '')+"/issues" + } + } + if (!url) { + url = "https://npmjs.org/package/" + d.name + } + opener(url, { command: npm.config.get("browser") }, cb) + }) +} diff --git a/node-v0.8.14/deps/npm/lib/build.js b/node-v0.8.14/deps/npm/lib/build.js new file mode 100644 index 0000000..815739c --- /dev/null +++ b/node-v0.8.14/deps/npm/lib/build.js @@ -0,0 +1,188 @@ +// npm build command + +// everything about the installation after the creation of +// the .npm/{name}/{version}/package folder. +// linking the modules into the npm.root, +// resolving dependencies, etc. + +// This runs AFTER install or link are completed. + +var npm = require("./npm.js") + , log = require("npmlog") + , chain = require("slide").chain + , fs = require("graceful-fs") + , path = require("path") + , lifecycle = require("./utils/lifecycle.js") + , readJson = require("read-package-json") + , link = require("./utils/link.js") + , linkIfExists = link.ifExists + , cmdShim = require("./utils/cmd-shim.js") + , cmdShimIfExists = cmdShim.ifExists + , asyncMap = require("slide").asyncMap + +module.exports = build +build.usage = "npm build \n(this is plumbing)" + +build._didBuild = {} +build._noLC = {} +function build (args, global, didPre, didRB, cb) { + if (typeof cb !== "function") cb = didRB, didRB = false + if (typeof cb !== "function") cb = didPre, didPre = false + if (typeof cb !== "function") { + cb = global, global = npm.config.get("global") + } + // it'd be nice to asyncMap these, but actually, doing them + // in parallel generally munges up the output from node-waf + var builder = build_(global, didPre, didRB) + chain(args.map(function (arg) { return function (cb) { + builder(arg, cb) + }}), cb) +} + +function build_ (global, didPre, didRB) { return function (folder, cb) { + folder = path.resolve(folder) + build._didBuild[folder] = true + log.info("build", folder) + readJson(path.resolve(folder, "package.json"), function (er, pkg) { + if (er) return cb(er) + chain + ( [ !didPre && [lifecycle, pkg, "preinstall", folder] + , [linkStuff, pkg, folder, global, didRB] + , pkg.name === "npm" && [writeBuiltinConf, folder] + , didPre !== build._noLC && [lifecycle, pkg, "install", folder] + , didPre !== build._noLC && [lifecycle, pkg, "postinstall", folder] + , didPre !== build._noLC + && npm.config.get("npat") + && [lifecycle, pkg, "test", folder] ] + , cb ) + }) +}} + +function writeBuiltinConf (folder, cb) { + // the builtin config is "sticky". Any time npm installs itself, + // it puts its builtin config file there, as well. + if (!npm.config.usingBuiltin + || folder !== path.dirname(__dirname)) { + return cb() + } + npm.config.save("builtin", cb) +} + +function linkStuff (pkg, folder, global, didRB, cb) { + // if it's global, and folder is in {prefix}/node_modules, + // then bins are in {prefix}/bin + // otherwise, then bins are in folder/../.bin + var parent = path.dirname(folder) + , gnm = global && npm.globalDir + , top = parent === npm.dir + , gtop = parent === gnm + + log.verbose("linkStuff", [global, gnm, gtop, parent]) + log.info("linkStuff", pkg._id) + + if (top && pkg.preferGlobal && !global) { + log.warn("prefer global", pkg._id + " should be installed with -g") + } + + asyncMap( [linkBins, linkMans, !didRB && rebuildBundles] + , function (fn, cb) { + if (!fn) return cb() + log.verbose(fn.name, pkg._id) + fn(pkg, folder, parent, gtop, cb) + }, cb) +} + +function rebuildBundles (pkg, folder, parent, gtop, cb) { + if (!npm.config.get("rebuild-bundle")) return cb() + + var deps = Object.keys(pkg.dependencies || {}) + .concat(Object.keys(pkg.devDependencies || {})) + , bundles = pkg.bundleDependencies || pkg.bundledDependencies || [] + + fs.readdir(path.resolve(folder, "node_modules"), function (er, files) { + // error means no bundles + if (er) return cb() + + log.verbose("rebuildBundles", files) + // don't asyncMap these, because otherwise build script output + // gets interleaved and is impossible to read + chain(files.filter(function (file) { + // rebuild if: + // not a .folder, like .bin or .hooks + return file.charAt(0) !== "." + // not some old 0.x style bundle + && file.indexOf("@") === -1 + // either not a dep, or explicitly bundled + && (deps.indexOf(file) === -1 || bundles.indexOf(file) !== -1) + }).map(function (file) { + file = path.resolve(folder, "node_modules", file) + return function (cb) { + if (build._didBuild[file]) return cb() + log.verbose("rebuild bundle", file) + // if file is not a package dir, then don't do it. + fs.lstat(path.resolve(file, "package.json"), function (er, st) { + if (er) return cb() + build_(false)(file, cb) + }) + }}), cb) + }) +} + +function linkBins (pkg, folder, parent, gtop, cb) { + if (!pkg.bin || !gtop && path.basename(parent) !== "node_modules") { + return cb() + } + var binRoot = gtop ? npm.globalBin + : path.resolve(parent, ".bin") + log.verbose("link bins", [pkg.bin, binRoot, gtop]) + + asyncMap(Object.keys(pkg.bin), function (b, cb) { + linkBin( path.resolve(folder, pkg.bin[b]) + , path.resolve(binRoot, b) + , gtop && folder + , function (er) { + if (er) return cb(er) + // bins should always be executable. + // XXX skip chmod on windows? + fs.chmod(path.resolve(folder, pkg.bin[b]), npm.modes.exec, function (er) { + if (er || !gtop) return cb(er) + var dest = path.resolve(binRoot, b) + , src = path.resolve(folder, pkg.bin[b]) + , out = npm.config.get("parseable") + ? dest + "::" + src + ":BINFILE" + : dest + " -> " + src + console.log(out) + cb() + }) + }) + }, cb) +} + +function linkBin (from, to, gently, cb) { + if (process.platform !== "win32") { + return linkIfExists(from, to, gently, cb) + } else { + return cmdShimIfExists(from, to, cb) + } +} + +function linkMans (pkg, folder, parent, gtop, cb) { + if (!pkg.man || !gtop || process.platform === "win32") return cb() + var manRoot = path.resolve(npm.config.get("prefix"), "share", "man") + asyncMap(pkg.man, function (man, cb) { + if (typeof man !== "string") return cb() + var parseMan = man.match(/(.*)\.([0-9]+)(\.gz)?$/) + , stem = parseMan[1] + , sxn = parseMan[2] + , gz = parseMan[3] || "" + , bn = path.basename(stem) + , manSrc = path.join( folder, man ) + , manDest = path.join( manRoot + , "man"+sxn + , (bn.indexOf(pkg.name) === 0 ? bn + : pkg.name + "-" + bn) + + "." + sxn + gz + ) + linkIfExists(manSrc, manDest, gtop && folder, cb) + }, cb) +} diff --git a/node-v0.8.14/deps/npm/lib/cache.js b/node-v0.8.14/deps/npm/lib/cache.js new file mode 100644 index 0000000..c2f870b --- /dev/null +++ b/node-v0.8.14/deps/npm/lib/cache.js @@ -0,0 +1,973 @@ +// XXX lib/utils/tar.js and this file need to be rewritten. + +// URL-to-cache folder mapping: +// : -> ! +// @ -> _ +// http://registry.npmjs.org/foo/version -> cache/http!/... +// + +/* +fetching a url: +1. Check for url in inFlightUrls. If present, add cb, and return. +2. create inFlightURL list +3. Acquire lock at {cache}/{sha(url)}.lock + retries = {cache-lock-retries, def=3} + stale = {cache-lock-stale, def=30000} + wait = {cache-lock-wait, def=100} +4. if lock can't be acquired, then fail +5. fetch url, clear lock, call cbs + +cache folders: +1. urls: http!/server.com/path/to/thing +2. c:\path\to\thing: file!/c!/path/to/thing +3. /path/to/thing: file!/path/to/thing +4. git@ private: git_github.com!isaacs/npm +5. git://public: git!/github.com/isaacs/npm +6. git+blah:// git-blah!/server.com/foo/bar + +adding a folder: +1. tar into tmp/random/package.tgz +2. untar into tmp/random/contents/package, stripping one dir piece +3. tar tmp/random/contents/package to cache/n/v/package.tgz +4. untar cache/n/v/package.tgz into cache/n/v/package +5. rm tmp/random + +Adding a url: +1. fetch to tmp/random/package.tgz +2. goto folder(2) + +adding a name@version: +1. registry.get(name/version) +2. if response isn't 304, add url(dist.tarball) + +adding a name@range: +1. registry.get(name) +2. Find a version that satisfies +3. add name@version + +adding a local tarball: +1. untar to tmp/random/{blah} +2. goto folder(2) +*/ + +exports = module.exports = cache +exports.read = read +exports.clean = clean +exports.unpack = unpack +exports.lock = lock +exports.unlock = unlock + +var mkdir = require("mkdirp") + , exec = require("./utils/exec.js") + , fetch = require("./utils/fetch.js") + , npm = require("./npm.js") + , fs = require("graceful-fs") + , rm = require("rimraf") + , readJson = require("read-package-json") + , registry = npm.registry + , log = require("npmlog") + , path = require("path") + , sha = require("./utils/sha.js") + , asyncMap = require("slide").asyncMap + , semver = require("semver") + , tar = require("./utils/tar.js") + , fileCompletion = require("./utils/completion/file-completion.js") + , url = require("url") + , chownr = require("chownr") + , lockFile = require("lockfile") + , crypto = require("crypto") + , retry = require("retry") + +cache.usage = "npm cache add " + + "\nnpm cache add " + + "\nnpm cache add " + + "\nnpm cache add " + + "\nnpm cache add @" + + "\nnpm cache ls []" + + "\nnpm cache clean [[@]]" + +cache.completion = function (opts, cb) { + + var argv = opts.conf.argv.remain + if (argv.length === 2) { + return cb(null, ["add", "ls", "clean"]) + } + + switch (argv[2]) { + case "clean": + case "ls": + // cache and ls are easy, because the completion is + // what ls_ returns anyway. + // just get the partial words, minus the last path part + var p = path.dirname(opts.partialWords.slice(3).join("/")) + if (p === ".") p = "" + return ls_(p, 2, cb) + case "add": + // Same semantics as install and publish. + return npm.commands.install.completion(opts, cb) + } +} + +function cache (args, cb) { + var cmd = args.shift() + switch (cmd) { + case "rm": case "clear": case "clean": return clean(args, cb) + case "list": case "sl": case "ls": return ls(args, cb) + case "add": return add(args, cb) + default: return cb(new Error( + "Invalid cache action: "+cmd)) + } +} + +// if the pkg and ver are in the cache, then +// just do a readJson and return. +// if they're not, then fetch them from the registry. +function read (name, ver, forceBypass, cb) { + if (typeof cb !== "function") cb = forceBypass, forceBypass = true + var jsonFile = path.join(npm.cache, name, ver, "package", "package.json") + function c (er, data) { + if (data) deprCheck(data) + return cb(er, data) + } + + if (forceBypass && npm.config.get("force")) { + log.verbose("using force", "skipping cache") + return addNamed(name, ver, c) + } + + readJson(jsonFile, function (er, data) { + if (er) return addNamed(name, ver, c) + deprCheck(data) + c(er, data) + }) +} + +// npm cache ls [] +function ls (args, cb) { + args = args.join("/").split("@").join("/") + if (args.substr(-1) === "/") args = args.substr(0, args.length - 1) + var prefix = npm.config.get("cache") + if (0 === prefix.indexOf(process.env.HOME)) { + prefix = "~" + prefix.substr(process.env.HOME.length) + } + ls_(args, npm.config.get("depth"), function(er, files) { + console.log(files.map(function (f) { + return path.join(prefix, f) + }).join("\n").trim()) + cb(er, files) + }) +} + +// Calls cb with list of cached pkgs matching show. +function ls_ (req, depth, cb) { + return fileCompletion(npm.cache, req, depth, cb) +} + +// npm cache clean [] +function clean (args, cb) { + if (!cb) cb = args, args = [] + if (!args) args = [] + args = args.join("/").split("@").join("/") + if (args.substr(-1) === "/") args = args.substr(0, args.length - 1) + var f = path.join(npm.cache, path.normalize(args)) + if (f === npm.cache) { + fs.readdir(npm.cache, function (er, files) { + if (er) return cb() + asyncMap( files.filter(function (f) { + return npm.config.get("force") || f !== "-" + }).map(function (f) { + return path.join(npm.cache, f) + }) + , rm, cb ) + }) + } else rm(path.join(npm.cache, path.normalize(args)), cb) +} + +// npm cache add +// npm cache add +// npm cache add +// npm cache add +exports.add = function (pkg, ver, scrub, cb) { + if (typeof cb !== "function") cb = scrub, scrub = false + if (typeof cb !== "function") cb = ver, ver = null + if (scrub) { + return clean([], function (er) { + if (er) return cb(er) + add([pkg, ver], cb) + }) + } + log.verbose("cache add", [pkg, ver]) + return add([pkg, ver], cb) +} + +function add (args, cb) { + // this is hot code. almost everything passes through here. + // the args can be any of: + // ["url"] + // ["pkg", "version"] + // ["pkg@version"] + // ["pkg", "url"] + // This is tricky, because urls can contain @ + // Also, in some cases we get [name, null] rather + // that just a single argument. + + var usage = "Usage:\n" + + " npm cache add \n" + + " npm cache add @\n" + + " npm cache add \n" + + " npm cache add \n" + , name + , spec + + if (args[1] === undefined) args[1] = null + + // at this point the args length must ==2 + if (args[1] !== null) { + name = args[0] + spec = args[1] + } else if (args.length === 2) { + spec = args[0] + } + + log.silly("cache add", "name=%j spec=%j args=%j", name, spec, args) + + + if (!name && !spec) return cb(usage) + + // see if the spec is a url + // otherwise, treat as name@version + var p = url.parse(spec) || {} + log.verbose("parsed url", p) + + // it could be that we got name@http://blah + // in that case, we will not have a protocol now, but if we + // split and check, we will. + if (!name && !p.protocol && spec.indexOf("@") !== -1) { + spec = spec.split("@") + name = spec.shift() + spec = spec.join("@") + return add([name, spec], cb) + } + + switch (p.protocol) { + case "http:": + case "https:": + return addRemoteTarball(spec, null, name, cb) + case "git:": + case "git+http:": + case "git+https:": + case "git+rsync:": + case "git+ftp:": + case "git+ssh:": + //p.protocol = p.protocol.replace(/^git([^:])/, "$1") + return addRemoteGit(spec, p, name, cb) + default: + // if we have a name and a spec, then try name@spec + // if not, then try just spec (which may try name@"" if not found) + if (name) { + addNamed(name, spec, cb) + } else { + addLocal(spec, cb) + } + } +} + +function fetchAndShaCheck (u, tmp, shasum, cb) { + fetch(u, tmp, function (er, response) { + if (er) { + log.error("fetch failed", u) + return cb(er, response) + } + if (!shasum) return cb() + // validate that the url we just downloaded matches the expected shasum. + sha.check(tmp, shasum, cb) + }) +} + +// Only have a single download action at once for a given url +// additional calls stack the callbacks. +var inFlightURLs = {} +function addRemoteTarball (u, shasum, name, cb_) { + if (typeof cb_ !== "function") cb_ = name, name = "" + if (typeof cb_ !== "function") cb_ = shasum, shasum = null + + if (!inFlightURLs[u]) inFlightURLs[u] = [] + var iF = inFlightURLs[u] + iF.push(cb_) + if (iF.length > 1) return + + function cb (er, data) { + unlock(u, function () { + var c + while (c = iF.shift()) c(er, data) + delete inFlightURLs[u] + }) + } + + lock(u, function (er) { + if (er) return cb(er) + + log.verbose("addRemoteTarball", [u, shasum]) + var tmp = path.join(npm.tmp, Date.now()+"-"+Math.random(), "tmp.tgz") + mkdir(path.dirname(tmp), function (er) { + if (er) return cb(er) + // Tuned to spread 3 attempts over about a minute. + // See formula at . + var operation = retry.operation + ( { retries: npm.config.get("fetch-retries") + , factor: npm.config.get("fetch-retry-factor") + , minTimeout: npm.config.get("fetch-retry-mintimeout") + , maxTimeout: npm.config.get("fetch-retry-maxtimeout") }) + + operation.attempt(function (currentAttempt) { + log.info("retry", "fetch attempt " + currentAttempt + + " at " + (new Date()).toLocaleTimeString()) + fetchAndShaCheck(u, tmp, shasum, function (er, response) { + // Only retry on 408, 5xx or no `response`. + var statusCode = response && response.statusCode + var statusRetry = !statusCode || (statusCode === 408 || statusCode >= 500) + if (er && statusRetry && operation.retry(er)) { + log.info("retry", "will retry, error on last attempt: " + er) + return + } + done(er) + }) + }) + }) + function done (er) { + if (er) return cb(er) + addLocalTarball(tmp, name, cb) + } + }) +} + +// For now, this is kind of dumb. Just basically treat git as +// yet another "fetch and scrub" kind of thing. +// Clone to temp folder, then proceed with the addLocal stuff. +function addRemoteGit (u, parsed, name, cb_) { + if (typeof cb_ !== "function") cb_ = name, name = null + + if (!inFlightURLs[u]) inFlightURLs[u] = [] + var iF = inFlightURLs[u] + iF.push(cb_) + if (iF.length > 1) return + + function cb (er, data) { + unlock(u, function () { + var c + while (c = iF.shift()) c(er, data) + delete inFlightURLs[u] + }) + } + + lock(u, function (er) { + if (er) return cb(er) + + // figure out what we should check out. + var co = parsed.hash && parsed.hash.substr(1) || "master" + // git is so tricky! + // if the path is like ssh://foo:22/some/path then it works, but + // it needs the ssh:// + // If the path is like ssh://foo:some/path then it works, but + // only if you remove the ssh:// + u = u.replace(/^git\+/, "") + .replace(/#.*$/, "") + + // ssh paths that are scp-style urls don't need the ssh:// + if (parsed.pathname.match(/^\/?:/)) { + u = u.replace(/^ssh:\/\//, "") + } + + log.verbose("addRemoteGit", [u, co]) + + var tmp = path.join(npm.tmp, Date.now()+"-"+Math.random()) + mkdir(path.dirname(tmp), function (er) { + if (er) return cb(er) + exec( npm.config.get("git"), ["clone", u, tmp], gitEnv(), false + , function (er, code, stdout, stderr) { + stdout = (stdout + "\n" + stderr).trim() + if (er) { + log.error("git clone " + u, stdout) + return cb(er) + } + log.verbose("git clone "+u, stdout) + exec( npm.config.get("git"), ["checkout", co], gitEnv(), false, tmp + , function (er, code, stdout, stderr) { + stdout = (stdout + "\n" + stderr).trim() + if (er) { + log.error("git checkout " + co, stdout) + return cb(er) + } + log.verbose("git checkout " + co, stdout) + addLocalDirectory(tmp, cb) + }) + }) + }) + }) +} + + +var gitEnv_ +function gitEnv () { + // git responds to env vars in some weird ways in post-receive hooks + // so don't carry those along. + if (gitEnv_) return gitEnv_ + gitEnv_ = {} + for (var k in process.env) { + if (!~['GIT_PROXY_COMMAND'].indexOf(k) && k.match(/^GIT/)) continue + gitEnv_[k] = process.env[k] + } + return gitEnv_ +} + + +// only have one request in flight for a given +// name@blah thing. +var inFlightNames = {} +function addNamed (name, x, data, cb_) { + if (typeof cb_ !== "function") cb_ = data, data = null + log.verbose("addNamed", [name, x]) + + var k = name + "@" + x + if (!inFlightNames[k]) inFlightNames[k] = [] + var iF = inFlightNames[k] + iF.push(cb_) + if (iF.length > 1) return + + function cb (er, data) { + unlock(k, function () { + var c + while (c = iF.shift()) c(er, data) + delete inFlightNames[k] + }) + } + + log.verbose("addNamed", [semver.valid(x), semver.validRange(x)]) + lock(k, function (er, fd) { + if (er) return cb(er) + + var fn = ( null !== semver.valid(x) ? addNameVersion + : null !== semver.validRange(x) ? addNameRange + : addNameTag + ) + fn(name, x, data, cb) + }) +} + +function addNameTag (name, tag, data, cb) { + if (typeof cb !== "function") cb = data, data = null + log.info("addNameTag", [name, tag]) + var explicit = true + if (!tag) { + explicit = false + tag = npm.config.get("tag") + } + + registry.get(name, function (er, data, json, response) { + if (er) return cb(er) + engineFilter(data) + if (data["dist-tags"] && data["dist-tags"][tag] + && data.versions[data["dist-tags"][tag]]) { + var ver = data["dist-tags"][tag] + return addNamed(name, ver, data.versions[ver], cb) + } + if (!explicit && Object.keys(data.versions).length) { + return addNamed(name, "*", data, cb) + } + + er = installTargetsError(tag, data) + + // might be username/project + // in that case, try it as a github url. + if (tag.split("/").length === 2) { + return maybeGithub(tag, name, er, cb) + } + + return cb(er) + }) +} + + +function engineFilter (data) { + var npmv = npm.version + , nodev = npm.config.get("node-version") + , strict = npm.config.get("engine-strict") + + if (!nodev || npm.config.get("force")) return data + + Object.keys(data.versions || {}).forEach(function (v) { + var eng = data.versions[v].engines + if (!eng) return + if (!strict && !data.versions[v].engineStrict) return + if (eng.node && !semver.satisfies(nodev, eng.node) + || eng.npm && !semver.satisfies(npmv, eng.npm)) { + delete data.versions[v] + } + }) +} + +function addNameRange (name, range, data, cb) { + if (typeof cb !== "function") cb = data, data = null + + range = semver.validRange(range) + if (range === null) return cb(new Error( + "Invalid version range: "+range)) + + log.silly("addNameRange", {name:name, range:range, hasData:!!data}) + + if (data) return next() + registry.get(name, function (er, d, json, response) { + if (er) return cb(er) + data = d + next() + }) + + function next () { + log.silly( "addNameRange", "number 2" + , {name:name, range:range, hasData:!!data}) + engineFilter(data) + + log.silly("addNameRange", "versions" + , [data.name, Object.keys(data.versions || {})]) + + // if the tagged version satisfies, then use that. + var tagged = data["dist-tags"][npm.config.get("tag")] + if (tagged && data.versions[tagged] && semver.satisfies(tagged, range)) { + return addNamed(name, tagged, data.versions[tagged], cb) + } + + // find the max satisfying version. + var ms = semver.maxSatisfying(Object.keys(data.versions || {}), range) + if (!ms) { + return cb(installTargetsError(range, data)) + } + + // if we don't have a registry connection, try to see if + // there's a cached copy that will be ok. + addNamed(name, ms, data.versions[ms], cb) + } +} + +function installTargetsError (requested, data) { + var targets = Object.keys(data["dist-tags"]).filter(function (f) { + return (data.versions || {}).hasOwnProperty(f) + }).concat(Object.keys(data.versions || {})) + + requested = data.name + (requested ? "@'" + requested + "'" : "") + + targets = targets.length + ? "Valid install targets:\n" + JSON.stringify(targets) + : "No valid targets found.\n" + + "Perhaps not compatible with your version of node?" + + return new Error( "No compatible version found: " + + requested + "\n" + targets) +} + +function addNameVersion (name, ver, data, cb) { + if (typeof cb !== "function") cb = data, data = null + + ver = semver.valid(ver) + if (ver === null) return cb(new Error("Invalid version: "+ver)) + + var response + + if (data) { + response = null + return next() + } + registry.get(name + "/" + ver, function (er, d, json, resp) { + if (er) return cb(er) + data = d + response = resp + next() + }) + + function next () { + deprCheck(data) + var dist = data.dist + + if (!dist) return cb(new Error("No dist in "+data._id+" package")) + + if (!dist.tarball) return cb(new Error( + "No dist.tarball in " + data._id + " package")) + + if ((response && response.statusCode !== 304) || npm.config.get("force")) { + return fetchit() + } + + // we got cached data, so let's see if we have a tarball. + fs.stat(path.join(npm.cache, name, ver, "package.tgz"), function (er, s) { + if (!er) readJson( path.join( npm.cache, name, ver + , "package", "package.json" ) + , function (er, data) { + if (er) return fetchit() + return cb(null, data) + }) + else return fetchit() + }) + + function fetchit () { + if (!npm.config.get("registry")) { + return cb(new Error("Cannot fetch: "+dist.tarball)) + } + + // use the same protocol as the registry. + // https registry --> https tarballs. + var tb = url.parse(dist.tarball) + tb.protocol = url.parse(npm.config.get("registry")).protocol + delete tb.href + tb = url.format(tb) + return addRemoteTarball( tb + , dist.shasum + , name+"-"+ver + , cb ) + } + } +} + +function addLocal (p, name, cb_) { + if (typeof cb_ !== "function") cb_ = name, name = "" + + function cb (er, data) { + unlock(p, function () { + if (er) { + // if it doesn't have a / in it, it might be a + // remote thing. + if (p.indexOf("/") === -1 && p.charAt(0) !== "." + && (process.platform !== "win32" || p.indexOf("\\") === -1)) { + return addNamed(p, "", cb_) + } + log.error("addLocal", "Could not install %s", p) + return cb_(er) + } + return cb_(er, data) + }) + } + + lock(p, function (er) { + if (er) return cb(er) + // figure out if this is a folder or file. + fs.stat(p, function (er, s) { + if (er) { + // might be username/project + // in that case, try it as a github url. + if (p.split("/").length === 2) { + return maybeGithub(p, name, er, cb) + } + return cb(er) + } + if (s.isDirectory()) addLocalDirectory(p, name, cb) + else addLocalTarball(p, name, cb) + }) + }) +} + +function maybeGithub (p, name, er, cb) { + var u = "git://github.com/" + p + , up = url.parse(u) + log.info("maybeGithub", "Attempting to fetch %s from %s", p, u) + return addRemoteGit(u, up, name, function (er2, data) { + if (er2) return cb(er) + return cb(null, data) + }) +} + +function addLocalTarball (p, name, cb) { + if (typeof cb !== "function") cb = name, name = "" + // if it's a tar, and not in place, + // then unzip to .tmp, add the tmp folder, and clean up tmp + if (p.indexOf(npm.tmp) === 0) return addTmpTarball(p, name, cb) + + if (p.indexOf(npm.cache) === 0) { + if (path.basename(p) !== "package.tgz") return cb(new Error( + "Not a valid cache tarball name: "+p)) + return addPlacedTarball(p, name, cb) + } + + // just copy it over and then add the temp tarball file. + var tmp = path.join(npm.tmp, name + Date.now() + + "-" + Math.random(), "tmp.tgz") + mkdir(path.dirname(tmp), function (er) { + if (er) return cb(er) + var from = fs.createReadStream(p) + , to = fs.createWriteStream(tmp) + , errState = null + function errHandler (er) { + if (errState) return + return cb(errState = er) + } + from.on("error", errHandler) + to.on("error", errHandler) + to.on("close", function () { + if (errState) return + log.verbose("chmod", tmp, npm.modes.file.toString(8)) + fs.chmod(tmp, npm.modes.file, function (er) { + if (er) return cb(er) + addTmpTarball(tmp, name, cb) + }) + }) + from.pipe(to) + }) +} + +// to maintain the cache dir's permissions consistently. +var cacheStat = null +function getCacheStat (cb) { + if (cacheStat) return cb(null, cacheStat) + fs.stat(npm.cache, function (er, st) { + if (er) return makeCacheDir(cb) + if (!st.isDirectory()) { + log.error("getCacheStat", "invalid cache dir %j", npm.cache) + return cb(er) + } + return cb(null, cacheStat = st) + }) +} + +function makeCacheDir (cb) { + if (!process.getuid) return mkdir(npm.cache, cb) + + var uid = +process.getuid() + , gid = +process.getgid() + + if (uid === 0) { + if (process.env.SUDO_UID) uid = +process.env.SUDO_UID + if (process.env.SUDO_GID) gid = +process.env.SUDO_GID + } + if (uid !== 0 || !process.env.HOME) { + cacheStat = {uid: uid, gid: gid} + return mkdir(npm.cache, afterMkdir) + } + + fs.stat(process.env.HOME, function (er, st) { + if (er) { + log.error("makeCacheDir", "homeless?") + return cb(er) + } + cacheStat = st + log.silly("makeCacheDir", "cache dir uid, gid", [st.uid, st.gid]) + return mkdir(npm.cache, afterMkdir) + }) + + function afterMkdir (er, made) { + if (er || !cacheStat || isNaN(cacheStat.uid) || isNaN(cacheStat.gid)) { + return cb(er, cacheStat) + } + + if (!made) return cb(er, cacheStat) + + // ensure that the ownership is correct. + chownr(made, cacheStat.uid, cacheStat.gid, function (er) { + return cb(er, cacheStat) + }) + } +} + + + + +function addPlacedTarball (p, name, cb) { + if (!cb) cb = name, name = "" + getCacheStat(function (er, cs) { + if (er) return cb(er) + return addPlacedTarball_(p, name, cs.uid, cs.gid, cb) + }) +} + +function addPlacedTarball_ (p, name, uid, gid, cb) { + // now we know it's in place already as .cache/name/ver/package.tgz + // unpack to .cache/name/ver/package/, read the package.json, + // and fire cb with the json data. + var target = path.dirname(p) + , folder = path.join(target, "package") + + lock(folder, function (er) { + if (er) return cb(er) + rmUnpack() + }) + + function rmUnpack () { + rm(folder, function (er) { + unlock(folder, function () { + if (er) { + log.error("addPlacedTarball", "Could not remove %j", folder) + return cb(er) + } + thenUnpack() + }) + }) + } + + function thenUnpack () { + tar.unpack(p, folder, null, null, uid, gid, function (er) { + if (er) { + log.error("addPlacedTarball", "Could not unpack %j to %j", p, target) + return cb(er) + } + // calculate the sha of the file that we just unpacked. + // this is so that the data is available when publishing. + sha.get(p, function (er, shasum) { + if (er) { + log.error("addPlacedTarball", "shasum fail", p) + return cb(er) + } + readJson(path.join(folder, "package.json"), function (er, data) { + if (er) { + log.error("addPlacedTarball", "Couldn't read json in %j" + , folder) + return cb(er) + } + data.dist = data.dist || {} + if (shasum) data.dist.shasum = shasum + deprCheck(data) + asyncMap([p], function (f, cb) { + log.verbose("chmod", f, npm.modes.file.toString(8)) + fs.chmod(f, npm.modes.file, cb) + }, function (f, cb) { + if (process.platform === "win32") { + log.silly("chown", "skipping for windows", f) + cb() + } else if (typeof uid === "number" + && typeof gid === "number" + && parseInt(uid, 10) === uid + && parseInt(gid, 10) === gid) { + log.verbose("chown", f, [uid, gid]) + fs.chown(f, uid, gid, cb) + } else { + log.verbose("chown", "skip for invalid uid/gid", [f, uid, gid]) + cb() + } + }, function (er) { + cb(er, data) + }) + }) + }) + }) + } +} + +function addLocalDirectory (p, name, cb) { + if (typeof cb !== "function") cb = name, name = "" + // if it's a folder, then read the package.json, + // tar it to the proper place, and add the cache tar + if (p.indexOf(npm.cache) === 0) return cb(new Error( + "Adding a cache directory to the cache will make the world implode.")) + readJson(path.join(p, "package.json"), function (er, data) { + if (er) return cb(er) + deprCheck(data) + var random = Date.now() + "-" + Math.random() + , tmp = path.join(npm.tmp, random) + , tmptgz = path.resolve(tmp, "tmp.tgz") + , placed = path.resolve( npm.cache, data.name + , data.version, "package.tgz" ) + , placeDirect = path.basename(p) === "package" + , tgz = placeDirect ? placed : tmptgz + , doFancyCrap = p.indexOf(npm.tmp) !== 0 + && p.indexOf(npm.cache) !== 0 + getCacheStat(function (er, cs) { + mkdir(path.dirname(tgz), function (er, made) { + if (er) return cb(er) + tar.pack(tgz, p, data, doFancyCrap, function (er) { + if (er) { + log.error( "addLocalDirectory", "Could not pack %j to %j" + , p, tgz ) + return cb(er) + } + + // if we don't get a cache stat, or if the gid/uid is not + // a number, then just move on. chown would fail anyway. + if (!cs || isNaN(cs.uid) || isNaN(cs.gid)) return cb() + + chownr(made || tgz, cs.uid, cs.gid, function (er) { + if (er) return cb(er) + addLocalTarball(tgz, name, cb) + }) + }) + }) + }) + }) +} + +function addTmpTarball (tgz, name, cb) { + if (!cb) cb = name, name = "" + getCacheStat(function (er, cs) { + if (er) return cb(er) + var contents = path.dirname(tgz) + tar.unpack( tgz, path.resolve(contents, "package") + , null, null + , cs.uid, cs.gid + , function (er) { + if (er) { + return cb(er) + } + addLocalDirectory(path.resolve(contents, "package"), name, cb) + }) + }) +} + +function unpack (pkg, ver, unpackTarget, dMode, fMode, uid, gid, cb) { + if (typeof cb !== "function") cb = gid, gid = null + if (typeof cb !== "function") cb = uid, uid = null + if (typeof cb !== "function") cb = fMode, fMode = null + if (typeof cb !== "function") cb = dMode, dMode = null + + read(pkg, ver, false, function (er, data) { + if (er) { + log.error("unpack", "Could not read data for %s", pkg + "@" + ver) + return cb(er) + } + npm.commands.unbuild([unpackTarget], function (er) { + if (er) return cb(er) + tar.unpack( path.join(npm.cache, pkg, ver, "package.tgz") + , unpackTarget + , dMode, fMode + , uid, gid + , cb ) + }) + }) +} + +var deprecated = {} + , deprWarned = {} +function deprCheck (data) { + if (deprecated[data._id]) data.deprecated = deprecated[data._id] + if (data.deprecated) deprecated[data._id] = data.deprecated + else return + if (!deprWarned[data._id]) { + deprWarned[data._id] = true + log.warn("deprecated", "%s: %s", data._id, data.deprecated) + } +} + +function lockFileName (u) { + var c = u.replace(/[^a-zA-Z0-9]+/g, "-").replace(/^-+|-+$/g, "") + , h = crypto.createHash("sha1").update(u).digest("hex") + h = h.substr(0, 8) + c = c.substr(-32) + log.silly("lockFile", h + "-" + c, u) + return path.resolve(npm.config.get("cache"), h + "-" + c + ".lock") +} + +var madeCache = false +function lock (u, cb) { + // the cache dir needs to exist already for this. + if (madeCache) then() + else mkdir(npm.config.get("cache"), function (er) { + if (er) return cb(er) + madeCache = true + then() + }) + function then () { + var opts = { stale: npm.config.get("cache-lock-stale") + , retries: npm.config.get("cache-lock-retries") + , wait: npm.config.get("cache-lock-wait") } + var lf = lockFileName(u) + log.verbose("lock", u, lf) + lockFile.lock(lf, opts, cb) + } +} + +function unlock (u, cb) { + lockFile.unlock(lockFileName(u), cb) +} diff --git a/node-v0.8.14/deps/npm/lib/completion.js b/node-v0.8.14/deps/npm/lib/completion.js new file mode 100644 index 0000000..87bb7a0 --- /dev/null +++ b/node-v0.8.14/deps/npm/lib/completion.js @@ -0,0 +1,248 @@ + +module.exports = completion + +completion.usage = "npm completion >> ~/.bashrc\n" + + "npm completion >> ~/.zshrc\n" + + "source <(npm completion)" + +var npm = require("./npm.js") + , npmconf = require("npmconf") + , configDefs = npmconf.defs + , configTypes = configDefs.types + , shorthands = configDefs.shorthands + , nopt = require("nopt") + , configNames = Object.keys(configTypes).filter(function (e) { + return e.charAt(0) !== "_" + }) + , shorthandNames = Object.keys(shorthands) + , allConfs = configNames.concat(shorthandNames) + , npm = require("./npm.js") + +completion.completion = function (opts, cb) { + if (opts.w > 3) return cb() + + var fs = require("graceful-fs") + , path = require("path") + , bashExists = null + , zshExists = null + , bashProfExists = null + fs.stat(path.resolve(process.env.HOME, ".bashrc"), function (er, b) { + bashExists = !er + next() + }) + fs.stat(path.resolve(process.env.HOME, ".zshrc"), function (er, b) { + zshExists = !er + next() + }) + function next () { + if (zshExists === null || bashExists === null) return + var out = [] + if (zshExists) out.push("~/.zshrc") + if (bashExists) out.push("~/.bashrc") + if (opts.w === 2) out = out.map(function (m) { + return [">>", m] + }) + cb(null, out) + } +} + +function completion (args, cb) { + if (process.platform === "win32") { + var e = new Error("npm completion not supported on windows") + e.code = "ENOTSUP" + e.errno = require("constants").ENOTSUP + return cb(e) + } + + // if the COMP_* isn't in the env, then just dump the script. + if (process.env.COMP_CWORD === undefined + ||process.env.COMP_LINE === undefined + ||process.env.COMP_POINT === undefined + ) return dumpScript(cb) + + console.error(process.env.COMP_CWORD) + console.error(process.env.COMP_LINE) + console.error(process.env.COMP_POINT) + + //console.log("abracadabrasauce\nabracad cat monger") + //if (Math.random() * 3 < 1) console.log("man\\ bear\\ pig") + //else if (Math.random() * 3 < 1) + // console.log("porkchop\\ sandwiches\nporkman") + //else console.log("encephylophagy") + + // get the partial line and partial word, + // if the point isn't at the end. + // ie, tabbing at: npm foo b|ar + var w = +process.env.COMP_CWORD + , words = args.map(unescape) + , word = words[w] + , line = process.env.COMP_LINE + , point = +process.env.COMP_POINT + , lineLength = line.length + , partialLine = line.substr(0, point) + , partialWords = words.slice(0, w) + + // figure out where in that last word the point is. + var partialWord = args[w] + , i = partialWord.length + while (partialWord.substr(0, i) !== partialLine.substr(-1*i) && i > 0) { + i -- + } + partialWord = unescape(partialWord.substr(0, i)) + partialWords.push(partialWord) + + var opts = { words : words + , w : w + , word : word + , line : line + , lineLength : line.length + , point : point + , partialLine : partialLine + , partialWords : partialWords + , partialWord : partialWord + , raw: args + } + + cb = wrapCb(cb, opts) + + console.error(opts) + + if (partialWords.slice(0, -1).indexOf("--") === -1) { + if (word.charAt(0) === "-") return configCompl(opts, cb) + if (words[w - 1] + && words[w - 1].charAt(0) === "-" + && !isFlag(words[w - 1])) { + // awaiting a value for a non-bool config. + // don't even try to do this for now + console.error("configValueCompl") + return configValueCompl(opts, cb) + } + } + + // try to find the npm command. + // it's the first thing after all the configs. + // take a little shortcut and use npm's arg parsing logic. + // don't have to worry about the last arg being implicitly + // boolean'ed, since the last block will catch that. + var parsed = opts.conf = + nopt(configTypes, shorthands, partialWords.slice(0, -1), 0) + // check if there's a command already. + console.error(parsed) + var cmd = parsed.argv.remain[1] + if (!cmd) return cmdCompl(opts, cb) + + Object.keys(parsed).forEach(function (k) { + npm.config.set(k, parsed[k]) + }) + + // at this point, if words[1] is some kind of npm command, + // then complete on it. + // otherwise, do nothing + cmd = npm.commands[cmd] + if (cmd && cmd.completion) return cmd.completion(opts, cb) + + // nothing to do. + cb() +} + +function dumpScript (cb) { + var fs = require("graceful-fs") + , path = require("path") + , p = path.resolve(__dirname, "utils/completion.sh") + + fs.readFile(p, "utf8", function (er, d) { + if (er) return cb(er) + d = d.replace(/^\#\!.*?\n/, "") + + process.stdout.write(d, function (n) { cb() }) + process.stdout.on("error", function (er) { + // Darwin is a real dick sometimes. + // + // This is necessary because the "source" or "." program in + // bash on OS X closes its file argument before reading + // from it, meaning that you get exactly 1 write, which will + // work most of the time, and will always raise an EPIPE. + // + // Really, one should not be tossing away EPIPE errors, or any + // errors, so casually. But, without this, `. <(npm completion)` + // can never ever work on OS X. + if (er.errno === require("constants").EPIPE) er = null + cb(er) + }) + + }) +} + +function unescape (w) { + if (w.charAt(0) === "\"") return w.replace(/^"|"$/g, "") + else return w.replace(/\\ /g, " ") +} + +function escape (w) { + if (!w.match(/\s+/)) return w + return "\"" + w + "\"" +} + +// The command should respond with an array. Loop over that, +// wrapping quotes around any that have spaces, and writing +// them to stdout. Use console.log, not the outfd config. +// If any of the items are arrays, then join them with a space. +// Ie, returning ["a", "b c", ["d", "e"]] would allow it to expand +// to: "a", "b c", or "d" "e" +function wrapCb (cb, opts) { return function (er, compls) { + if (!Array.isArray(compls)) compls = compls ? [compls] : [] + compls = compls.map(function (c) { + if (Array.isArray(c)) c = c.map(escape).join(" ") + else c = escape(c) + return c + }) + if (opts.partialWord) compls = compls.filter(function (c) { + return c.indexOf(opts.partialWord) === 0 + }) + console.error([er && er.stack, compls, opts.partialWord]) + if (er || compls.length === 0) return cb(er) + + console.log(compls.join("\n")) + cb() +}} + +// the current word has a dash. Return the config names, +// with the same number of dashes as the current word has. +function configCompl (opts, cb) { + var word = opts.word + , split = word.match(/^(-+)((?:no-)*)(.*)$/) + , dashes = split[1] + , no = split[2] + , conf = split[3] + , confs = allConfs + , flags = configNames.filter(isFlag) + console.error(flags) + + return cb(null, allConfs.map(function (c) { + return dashes + c + }).concat(flags.map(function (f) { + return dashes + (no || "no-") + f + }))) +} + +// expand with the valid values of various config values. +// not yet implemented. +function configValueCompl (opts, cb) { + console.error('configValue', opts) + return cb(null, []) +} + +// check if the thing is a flag or not. +function isFlag (word) { + // shorthands never take args. + var split = word.match(/^(-*)((?:no-)+)?(.*)$/) + , dashes = split[1] + , no = split[2] + , conf = split[3] + return no || configTypes[conf] === Boolean || shorthands[conf] +} + +// complete against the npm commands +function cmdCompl (opts, cb) { + return cb(null, npm.fullList) +} diff --git a/node-v0.8.14/deps/npm/lib/config.js b/node-v0.8.14/deps/npm/lib/config.js new file mode 100644 index 0000000..27a5f35 --- /dev/null +++ b/node-v0.8.14/deps/npm/lib/config.js @@ -0,0 +1,276 @@ + +module.exports = config + +config.usage = "npm config set " + + "\nnpm config get []" + + "\nnpm config delete " + + "\nnpm config list" + + "\nnpm config edit" + + "\nnpm set " + + "\nnpm get []" + +var log = require("npmlog") + , npm = require("./npm.js") + , exec = require("./utils/exec.js") + , fs = require("graceful-fs") + , npmconf = require("npmconf") + , types = npmconf.defs.types + , ini = require("ini") + +config.completion = function (opts, cb) { + var argv = opts.conf.argv.remain + if (argv[1] !== "config") argv.unshift("config") + if (argv.length === 2) { + var cmds = ["get", "set", "delete", "ls", "rm", "edit"] + if (opts.partialWord !== "l") cmds.push("list") + return cb(null, cmds) + } + + var action = argv[2] + switch (action) { + case "set": + // todo: complete with valid values, if possible. + if (argv.length > 3) return cb(null, []) + // fallthrough + case "get": + case "delete": + case "rm": + return cb(null, Object.keys(types)) + case "edit": + case "list": case "ls": + return cb(null, []) + default: return cb(null, []) + } +} + +// npm config set key value +// npm config get key +// npm config list +function config (args, cb) { + var action = args.shift() + switch (action) { + case "set": return set(args[0], args[1], cb) + case "get": return get(args[0], cb) + case "delete": case "rm": case "del": return del(args[0], cb) + case "list": case "ls": return list(cb) + case "edit": return edit(cb) + default: return unknown(action, cb) + } +} + +function edit (cb) { + var e = npm.config.get("editor") + , which = npm.config.get("global") ? "global" : "user" + , f = npm.config.get(which + "config") + , eol = process.platform === "win32" ? "\r\n" : "\n" + if (!e) return cb(new Error("No EDITOR config or environ set.")) + npm.config.save(which, function (er) { + if (er) return cb(er) + fs.readFile(f, "utf8", function (er, data) { + if (er) data = "" + data = [ ";;;;" + , "; npm "+(npm.config.get("global") ? + "globalconfig" : "userconfig")+" file" + , "; this is a simple ini-formatted file" + , "; lines that start with semi-colons are comments." + , "; read `npm help config` for help on the various options" + , ";;;;" + , "" + , data + ].concat( [ ";;;;" + , "; all options with default values" + , ";;;;" + ] + ) + .concat(Object.keys(npmconf.defaults).map(function (k) { + return "; " + k + " = " + npmconf.defaults[k] + })) + .concat([""]) + .join(eol) + fs.writeFile + ( f + , data + , "utf8" + , function (er) { + if (er) return cb(er) + exec(e, [f], cb) + } + ) + }) + }) +} + +function del (key, cb) { + if (!key) return cb(new Error("no key provided")) + var where = npm.config.get("global") ? "global" : "user" + npm.config.del(key, where) + npm.config.save(where, cb) +} + +function set (key, val, cb) { + if (key === undefined) { + return unknown("", cb) + } + if (val === undefined) { + if (key.indexOf("=") !== -1) { + var k = key.split("=") + key = k.shift() + val = k.join("=") + } else { + val = "" + } + } + key = key.trim() + val = val.trim() + log.info("config", "set %j %j", key, val) + var where = npm.config.get("global") ? "global" : "user" + npm.config.set(key, val, where) + npm.config.save(where, cb) +} + +function get (key, cb) { + if (!key) return list(cb) + if (key.charAt(0) === "_") { + return cb(new Error("---sekretz---")) + } + console.log(npm.config.get(key)) + cb() +} + +function sort (a, b) { + return a > b ? 1 : -1 +} + +function reverse (a, b) { + return a > b ? -1 : 1 +} + +function public (k) { + return !(k.charAt(0) === "_" || types[k] !== types[k]) +} + +function getKeys (data) { + return Object.keys(data).filter(public).sort(sort) +} + +function list (cb) { + var msg = "" + , long = npm.config.get("long") + + var cli = npm.config.sources.cli.data + , cliKeys = getKeys(cli) + if (cliKeys.length) { + msg += "; cli configs\n" + cliKeys.forEach(function (k) { + if (cli[k] && typeof cli[k] === "object") return + if (k === "argv") return + msg += k + " = " + JSON.stringify(cli[k]) + "\n" + }) + msg += "\n" + } + + // env configs + var env = npm.config.sources.env.data + , envKeys = getKeys(env) + if (envKeys.length) { + msg += "; environment configs\n" + envKeys.forEach(function (k) { + if (env[k] !== npm.config.get(k)) { + if (!long) return + msg += "; " + k + " = " + JSON.stringify(env[k]) + + " (overridden)\n" + } else msg += k + " = " + JSON.stringify(env[k]) + "\n" + }) + msg += "\n" + } + + // user config file + var uconf = npm.config.sources.user.data + , uconfKeys = getKeys(uconf) + if (uconfKeys.length) { + msg += "; userconfig " + npm.config.get("userconfig") + "\n" + uconfKeys.forEach(function (k) { + var val = (k.charAt(0) === "_") + ? "---sekretz---" + : JSON.stringify(uconf[k]) + if (uconf[k] !== npm.config.get(k)) { + if (!long) return + msg += "; " + k + " = " + val + + " (overridden)\n" + } else msg += k + " = " + val + "\n" + }) + msg += "\n" + } + + // global config file + var gconf = npm.config.sources.global.data + , gconfKeys = getKeys(gconf) + if (gconfKeys.length) { + msg += "; globalconfig " + npm.config.get("globalconfig") + "\n" + gconfKeys.forEach(function (k) { + var val = (k.charAt(0) === "_") + ? "---sekretz---" + : JSON.stringify(gconf[k]) + if (gconf[k] !== npm.config.get(k)) { + if (!long) return + msg += "; " + k + " = " + val + + " (overridden)\n" + } else msg += k + " = " + val + "\n" + }) + msg += "\n" + } + + // builtin config file + var builtin = npm.config.sources.builtin || {} + if (builtin && builtin.data) { + var bconf = builtin.data + , bpath = builtin.path + , bconfKeys = getKeys(bconf) + if (bconfKeys.length) { + var path = require("path") + msg += "; builtin config " + bpath + "\n" + bconfKeys.forEach(function (k) { + var val = (k.charAt(0) === "_") + ? "---sekretz---" + : JSON.stringify(bconf[k]) + if (bconf[k] !== npm.config.get(k)) { + if (!long) return + msg += "; " + k + " = " + val + + " (overridden)\n" + } else msg += k + " = " + val + "\n" + }) + msg += "\n" + } + } + + // only show defaults if --long + if (!long) { + msg += "; node bin location = " + process.execPath + "\n" + + "; cwd = " + process.cwd() + "\n" + + "; HOME = " + process.env.HOME + "\n" + + "; 'npm config ls -l' to show all defaults.\n" + + console.log(msg) + return cb() + } + + var defaults = npmconf.defaults + , defKeys = getKeys(defaults) + msg += "; default values\n" + defKeys.forEach(function (k) { + if (defaults[k] && typeof defaults[k] === "object") return + var val = JSON.stringify(defaults[k]) + if (defaults[k] !== npm.config.get(k)) { + msg += "; " + k + " = " + val + + " (overridden)\n" + } else msg += k + " = " + val + "\n" + }) + msg += "\n" + + console.log(msg) + return cb() +} + +function unknown (action, cb) { + cb("Usage:\n" + config.usage) +} diff --git a/node-v0.8.14/deps/npm/lib/dedupe.js b/node-v0.8.14/deps/npm/lib/dedupe.js new file mode 100644 index 0000000..9a35790 --- /dev/null +++ b/node-v0.8.14/deps/npm/lib/dedupe.js @@ -0,0 +1,334 @@ +// traverse the node_modules/package.json tree +// looking for duplicates. If any duplicates are found, +// then move them up to the highest level necessary +// in order to make them no longer duplicated. +// +// This is kind of ugly, and really highlights the need for +// much better "put pkg X at folder Y" abstraction. Oh well, +// whatever. Perfect enemy of the good, and all that. + +var fs = require("fs") +var asyncMap = require("slide").asyncMap +var path = require("path") +var readJson = require("read-package-json") +var archy = require("archy") +var util = require("util") +var RegClient = require("npm-registry-client") +var npmconf = require("npmconf") +var npm = require("npm") +var semver = require("semver") +var npm = require("npm") +var rimraf = require("rimraf") +var log = require("npmlog") +var npm = require("./npm.js") + +module.exports = dedupe + +dedupe.usage = "npm dedupe [pkg pkg...]" + +function dedupe (args, silent, cb) { + if (typeof silent === "function") cb = silent, silent = false + var dryrun = false + if (npm.command.match(/^find/)) dryrun = true + return dedupe_(npm.prefix, args, {}, dryrun, silent, cb) +} + +function dedupe_ (dir, filter, unavoidable, dryrun, silent, cb) { + readInstalled(path.resolve(dir), {}, null, function (er, data, counter) { + // find out which things are dupes + var dupes = Object.keys(counter).filter(function (k) { + if (filter.length && -1 === filter.indexOf(k)) return false + return counter[k] > 1 && !unavoidable[k] + }).reduce(function (s, k) { + s[k] = [] + return s + }, {}) + + // any that are unavoidable need to remain as they are. don't even + // try to touch them or figure it out. Maybe some day, we can do + // something a bit more clever here, but for now, just skip over it, + // and all its children. + ;(function U (obj) { + if (unavoidable[obj.name]) { + obj.unavoidable = true + } + if (obj.parent && obj.parent.unavoidable) { + obj.unavoidable = true + } + Object.keys(obj.children).forEach(function (k) { + U(obj.children[k]) + }) + }) + + // then collect them up and figure out who needs them + ;(function C (obj) { + if (dupes[obj.name] && !obj.unavoidable) { + dupes[obj.name].push(obj) + obj.duplicate = true + } + obj.dependents = whoDepends(obj) + Object.keys(obj.children).forEach(function (k) { + C(obj.children[k]) + }) + })(data) + + if (dryrun) { + var k = Object.keys(dupes) + if (!k.length) return cb() + return npm.commands.ls(k, silent, cb) + } + + var summary = Object.keys(dupes).map(function (n) { + return [n, dupes[n].filter(function (d) { + return d && d.parent && !d.parent.duplicate && !d.unavoidable + }).map(function M (d) { + return [d.path, d.version, d.dependents.map(function (k) { + return [k.path, k.version, k.dependencies[d.name] || ""] + })] + })] + }).map(function (item) { + var name = item[0] + var set = item[1] + + var ranges = set.map(function (i) { + return i[2].map(function (d) { + return d[2] + }) + }).reduce(function (l, r) { + return l.concat(r) + }, []).map(function (v, i, set) { + if (set.indexOf(v) !== i) return false + return v + }).filter(function (v) { + return v !== false + }) + + var locs = set.map(function (i) { + return i[0] + }) + + var versions = set.map(function (i) { + return i[1] + }).filter(function (v, i, set) { + return set.indexOf(v) === i + }) + + var has = set.map(function (i) { + return [i[0], i[1]] + }).reduce(function (set, kv) { + set[kv[0]] = kv[1] + return set + }, {}) + + var loc = locs.length ? locs.reduce(function (a, b) { + // a=/path/to/node_modules/foo/node_modules/bar + // b=/path/to/node_modules/elk/node_modules/bar + // ==/path/to/node_modules/bar + a = a.split(/\/node_modules\//) + b = b.split(/\/node_modules\//) + var name = a.pop() + b.pop() + // find the longest chain that both A and B share. + // then push the name back on it, and join by /node_modules/ + var res = [] + for (var i = 0, al = a.length, bl = b.length; i < al && i < bl && a[i] === b[i]; i++); + return a.slice(0, i).concat(name).join("/node_modules/") + }) : undefined + + return [item[0], { item: item + , ranges: ranges + , locs: locs + , loc: loc + , has: has + , versions: versions + }] + }).filter(function (i) { + return i[1].loc + }) + + findVersions(npm, summary, function (er, set) { + if (er) return cb(er) + if (!set.length) return cb() + installAndRetest(set, filter, dir, unavoidable, silent, cb) + }) + }) +} + +function installAndRetest (set, filter, dir, unavoidable, silent, cb) { + //return cb(null, set) + var remove = [] + + asyncMap(set, function (item, cb) { + // [name, has, loc, locMatch, regMatch, others] + var name = item[0] + var has = item[1] + var where = item[2] + var locMatch = item[3] + var regMatch = item[4] + var others = item[5] + + // nothing to be done here. oh well. just a conflict. + if (!locMatch && !regMatch) { + log.warn("unavoidable conflict", item[0], item[1]) + log.warn("unavoidable conflict", "Not de-duplicating") + unavoidable[item[0]] = true + return cb() + } + + // nothing to do except to clean up the extraneous deps + if (locMatch && has[where] === locMatch) { + remove.push.apply(remove, others) + return cb() + } + + if (regMatch) { + var what = name + "@" + regMatch + // where is /path/to/node_modules/foo/node_modules/bar + // for package "bar", but we need it to be just + // /path/to/node_modules/foo + where = where.split(/\/node_modules\//) + where.pop() + where = where.join("/node_modules/") + remove.push.apply(remove, others) + + return npm.commands.install(where, what, cb) + } + + // hrm? + return cb(new Error("danger zone\n" + name + " " + + + regMatch + " " + locMatch)) + + }, function (er, installed) { + if (er) return cb(er) + asyncMap(remove, rimraf, function (er) { + if (er) return cb(er) + remove.forEach(function (r) { + log.info("rm", r) + }) + dedupe_(dir, filter, unavoidable, false, silent, cb) + }) + }) +} + +function findVersions (npm, summary, cb) { + // now, for each item in the summary, try to find the maximum version + // that will satisfy all the ranges. next step is to install it at + // the specified location. + asyncMap(summary, function (item, cb) { + var name = item[0] + var data = item[1] + var loc = data.loc + var locs = data.locs.filter(function (l) { + return l !== loc + }) + + // not actually a dupe, or perhaps all the other copies were + // children of a dupe, so this'll maybe be picked up later. + if (locs.length === 0) { + return cb() + } + + // { : } + var has = data.has + + // the versions that we already have. + // if one of these is ok, then prefer to use that. + // otherwise, try fetching from the registry. + var versions = data.versions + + var ranges = data.ranges + npm.registry.get(name, function (er, data) { + var regVersions = er ? [] : Object.keys(data.versions) + var locMatch = bestMatch(versions, ranges) + var regMatch = bestMatch(regVersions, ranges) + + cb(null, [[name, has, loc, locMatch, regMatch, locs]]) + }) + }, cb) +} + +function bestMatch (versions, ranges) { + return versions.filter(function (v) { + return !ranges.some(function (r) { + return !semver.satisfies(v, r) + }) + }).sort(semver.compare).pop() +} + + +function readInstalled (dir, counter, parent, cb) { + var pkg, children, realpath + + fs.realpath(dir, function (er, rp) { + realpath = rp + next() + }) + + readJson(path.resolve(dir, "package.json"), function (er, data) { + if (er) return cb() // not a package, probably. + counter[data.name] = counter[data.name] || 0 + counter[data.name]++ + pkg = + { _id: data._id + , name: data.name + , version: data.version + , dependencies: data.dependencies || {} + , optionalDependencies: data.optionalDependencies || {} + , devDependencies: data.devDependencies || {} + , bundledDependencies: data.bundledDependencies || [] + , path: dir + , realPath: dir + , children: {} + , parent: parent + , family: Object.create(parent ? parent.family : null) + , unavoidable: false + , duplicate: false + } + if (parent) { + parent.children[data.name] = pkg + parent.family[data.name] = pkg + } + next() + }) + + fs.readdir(path.resolve(dir, "node_modules"), function (er, c) { + children = c || [] // error is ok, just means no children. + next() + }) + + function next () { + if (!children || !pkg || !realpath) return + + // ignore devDependencies. Just leave them where they are. + children = children.filter(function (c) { + return !pkg.devDependencies.hasOwnProperty(c) + }) + + pkg.realPath = realpath + if (pkg.realPath !== pkg.path) children = [] + var d = path.resolve(dir, "node_modules") + asyncMap(children, function (child, cb) { + readInstalled(path.resolve(d, child), counter, pkg, cb) + }, function (er) { + cb(er, pkg, counter) + }) + } +} + +function whoDepends (pkg) { + var start = pkg.parent || pkg + return whoDepends_(pkg, [], start) +} + +function whoDepends_ (pkg, who, test) { + if (test !== pkg && + test.dependencies[pkg.name] && + test.family[pkg.name] === pkg) { + who.push(test) + } + Object.keys(test.children).forEach(function (n) { + whoDepends_(pkg, who, test.children[n]) + }) + return who +} + diff --git a/node-v0.8.14/deps/npm/lib/deprecate.js b/node-v0.8.14/deps/npm/lib/deprecate.js new file mode 100644 index 0000000..c9e724e --- /dev/null +++ b/node-v0.8.14/deps/npm/lib/deprecate.js @@ -0,0 +1,47 @@ + +module.exports = deprecate + +deprecate.usage = "npm deprecate [@] " + +deprecate.completion = function (opts, cb) { + // first, get a list of remote packages this user owns. + // once we have a user account, then don't complete anything. + var un = npm.config.get("username") + if (!npm.config.get("username")) return cb() + if (opts.conf.argv.remain.length > 2) return cb() + // get the list of packages by user + var uri = "/-/by-user/"+encodeURIComponent(un) + registry.get(uri, null, 60000, function (er, list) { + if (er) return cb() + console.error(list) + return cb(null, list[un]) + }) +} + +var semver = require("semver") + , npm = require("./npm.js") + , registry = npm.registry + +function deprecate (args, cb) { + var pkg = args[0] + , msg = args[1] + if (msg === undefined) return cb(new Error(deprecate.usage)) + // fetch the data and make sure it exists. + pkg = pkg.split(/@/) + var name = pkg.shift() + , ver = pkg.join("@") + if (semver.validRange(ver) === null) { + return cb(new Error("invalid version range: "+ver)) + } + registry.get(name, function (er, data) { + if (er) return cb(er) + // filter all the versions that match + Object.keys(data.versions).filter(function (v) { + return semver.satisfies(v, ver) + }).forEach(function (v) { + data.versions[v].deprecated = msg + }) + // now update the doc on the registry + registry.request('PUT', data._id, data, cb) + }) +} diff --git a/node-v0.8.14/deps/npm/lib/docs.js b/node-v0.8.14/deps/npm/lib/docs.js new file mode 100644 index 0000000..ffa91aa --- /dev/null +++ b/node-v0.8.14/deps/npm/lib/docs.js @@ -0,0 +1,30 @@ + +module.exports = docs + +docs.usage = "npm docs " + +docs.completion = function (opts, cb) { + if (opts.conf.argv.remain.length > 2) return cb() + registry.get("/-/short", 60000, function (er, list) { + return cb(null, list || []) + }) +} + +var exec = require("./utils/exec.js") + , npm = require("./npm.js") + , registry = npm.registry + , log = require("npmlog") + , opener = require("opener") + +function docs (args, cb) { + if (!args.length) return cb(docs.usage) + var n = args[0].split("@").shift() + registry.get(n + "/latest", 3600, function (er, d) { + if (er) return cb(er) + var homepage = d.homepage + , repo = d.repository || d.repositories + , url = homepage ? homepage + : "https://npmjs.org/package/" + d.name + opener(url, { command: npm.config.get("browser") }, cb) + }) +} diff --git a/node-v0.8.14/deps/npm/lib/edit.js b/node-v0.8.14/deps/npm/lib/edit.js new file mode 100644 index 0000000..0ffe723 --- /dev/null +++ b/node-v0.8.14/deps/npm/lib/edit.js @@ -0,0 +1,30 @@ +// npm edit [@] +// open the package folder in the $EDITOR + +module.exports = edit +edit.usage = "npm edit " + +edit.completion = require("./utils/completion/installed-shallow.js") + +var npm = require("./npm.js") + , exec = require("./utils/exec.js") + , path = require("path") + , fs = require("graceful-fs") + +function edit (args, cb) { + var p = args[0] + if (args.length !== 1 || !p) return cb(edit.usage) + var editor = npm.config.get("editor") + if (!editor) return cb(new Error( + "No editor set. Set the 'editor' config, or $EDITOR environ.")) + p = p.split("/") + .join("/node_modules/") + .replace(/(\/node_modules)+/, "/node_modules") + fs.lstat(path.resolve(npm.dir, p), function (er) { + if (er) return cb(er) + exec(editor, [path.resolve(npm.dir, p)], function (er) { + if (er) return cb(er) + npm.commands.rebuild(args, cb) + }) + }) +} diff --git a/node-v0.8.14/deps/npm/lib/explore.js b/node-v0.8.14/deps/npm/lib/explore.js new file mode 100644 index 0000000..8392c91 --- /dev/null +++ b/node-v0.8.14/deps/npm/lib/explore.js @@ -0,0 +1,34 @@ +// npm expore [@] +// open a subshell to the package folder. + +module.exports = explore +explore.usage = "npm explore [ -- ]" +explore.completion = require("./utils/completion/installed-shallow.js") + +var npm = require("./npm.js") + , exec = require("./utils/exec.js") + , path = require("path") + , fs = require("graceful-fs") + +function explore (args, cb) { + if (args.length < 1 || !args[0]) return cb(explore.usage) + var p = args.shift() + args = args.join(" ").trim() + if (args) args = ["-c", args] + else args = [] + + var editor = npm.config.get("editor") + , cwd = path.resolve(npm.dir, p) + fs.stat(cwd, function (er, s) { + if (er || !s.isDirectory()) return cb(new Error( + "It doesn't look like "+p+" is installed.")) + if (!args.length) console.log( + "\nExploring "+cwd+"\n"+ + "Type 'exit' or ^D when finished\n") + exec(npm.config.get("shell"), args, null, true, cwd, function (er) { + // only fail if non-interactive. + if (!args.length) return cb() + cb(er) + }) + }) +} diff --git a/node-v0.8.14/deps/npm/lib/faq.js b/node-v0.8.14/deps/npm/lib/faq.js new file mode 100644 index 0000000..912db00 --- /dev/null +++ b/node-v0.8.14/deps/npm/lib/faq.js @@ -0,0 +1,8 @@ + +module.exports = faq + +faq.usage = "npm faq" + +var npm = require("./npm.js") + +function faq (args, cb) { npm.commands.help(["faq"], cb) } diff --git a/node-v0.8.14/deps/npm/lib/get.js b/node-v0.8.14/deps/npm/lib/get.js new file mode 100644 index 0000000..aa05800 --- /dev/null +++ b/node-v0.8.14/deps/npm/lib/get.js @@ -0,0 +1,12 @@ + +module.exports = get + +get.usage = "npm get (See `npm config`)" + +var npm = require("./npm.js") + +get.completion = npm.commands.config.completion + +function get (args, cb) { + npm.commands.config(["get"].concat(args), cb) +} diff --git a/node-v0.8.14/deps/npm/lib/help-search.js b/node-v0.8.14/deps/npm/lib/help-search.js new file mode 100644 index 0000000..b0b15ba --- /dev/null +++ b/node-v0.8.14/deps/npm/lib/help-search.js @@ -0,0 +1,193 @@ + +module.exports = helpSearch + +var fs = require("graceful-fs") + , path = require("path") + , asyncMap = require("slide").asyncMap + , cliDocsPath = path.join(__dirname, "..", "doc", "cli") + , apiDocsPath = path.join(__dirname, "..", "doc", "api") + , log = require("npmlog") + , npm = require("./npm.js") + +helpSearch.usage = "npm help-search " + +function helpSearch (args, silent, cb) { + if (typeof cb !== "function") cb = silent, silent = false + if (!args.length) return cb(helpSearch.usage) + + // see if we're actually searching the api docs. + var argv = npm.config.get("argv").cooked + , docsPath = cliDocsPath + , cmd = "help" + if (argv.length && argv[0].indexOf("api") !== -1) { + docsPath = apiDocsPath + cmd = "apihelp" + } + + fs.readdir(docsPath, function(er, files) { + if (er) { + log.error("helpSearch", "Could not load documentation") + return cb(er) + } + + var search = args.join(" ") + , results = [] + asyncMap(files, function (file, cb) { + fs.lstat(path.resolve(docsPath, file), function (er, st) { + if (er) return cb(er) + if (!st.isFile()) return cb(null, []) + + fs.readFile(path.resolve(docsPath, file), "utf8", function (er, data) { + if (er) return cb(er) + + var match = false + for (var a = 0, l = args.length; a < l && !match; a ++) { + match = data.toLowerCase().indexOf(args[a].toLowerCase()) !== -1 + } + if (!match) return cb(null, []) + + var lines = data.split(/\n+/) + , context = [] + + // if a line has a search term, then skip it and the next line. + // if the next line has a search term, then skip all 3 + // otherwise, set the line to null. + for (var i = 0, l = lines.length; i < l; i ++) { + var line = lines[i] + , nextLine = lines[i + 1] + , match = false + if (nextLine) { + for (var a = 0, ll = args.length; a < ll && !match; a ++) { + match = nextLine.toLowerCase() + .indexOf(args[a].toLowerCase()) !== -1 + } + if (match) { + // skip over the next line, and the line after it. + i += 2 + continue + } + } + + match = false + for (var a = 0, ll = args.length; a < ll && !match; a ++) { + match = line.toLowerCase().indexOf(args[a].toLowerCase()) !== -1 + } + if (match) { + // skip over the next line + i ++ + continue + } + + lines[i] = null + } + + // now squish any string of nulls into a single null + lines = lines.reduce(function (l, r) { + if (!(r === null && l[l.length-1] === null)) l.push(r) + return l + }, []) + + if (lines[lines.length - 1] === null) lines.pop() + if (lines[0] === null) lines.shift() + + // now see how many args were found at all. + var found = {} + , totalHits = 0 + lines.forEach(function (line) { + args.forEach(function (arg) { + var hit = (line || "").toLowerCase() + .split(arg.toLowerCase()).length - 1 + if (hit > 0) { + found[arg] = (found[arg] || 0) + hit + totalHits += hit + } + }) + }) + + return cb(null, { file: file, lines: lines, found: Object.keys(found) + , hits: found, totalHits: totalHits }) + }) + }) + }, function (er, results) { + if (er) return cb(er) + + // if only one result, then just show that help section. + if (results.length === 1) { + return npm.commands.help([results[0].file.replace(/\.md$/, "")], cb) + } + + if (results.length === 0) { + console.log("No results for " + args.map(JSON.stringify).join(" ")) + return cb() + } + + // sort results by number of results found, then by number of hits + // then by number of matching lines + results = results.sort(function (a, b) { + return a.found.length > b.found.length ? -1 + : a.found.length < b.found.length ? 1 + : a.totalHits > b.totalHits ? -1 + : a.totalHits < b.totalHits ? 1 + : a.lines.length > b.lines.length ? -1 + : a.lines.length < b.lines.length ? 1 + : 0 + }) + + var out = results.map(function (res, i, results) { + var out = "npm " + cmd + " "+res.file.replace(/\.md$/, "") + , r = Object.keys(res.hits).map(function (k) { + return k + ":" + res.hits[k] + }).sort(function (a, b) { + return a > b ? 1 : -1 + }).join(" ") + + out += ((new Array(Math.max(1, 81 - out.length - r.length))) + .join (" ")) + r + + if (!npm.config.get("long")) return out + + var out = "\n\n" + out + + "\n" + (new Array(81)).join("—") + "\n" + + res.lines.map(function (line, i) { + if (line === null || i > 3) return "" + for (var out = line, a = 0, l = args.length; a < l; a ++) { + var finder = out.toLowerCase().split(args[a].toLowerCase()) + , newOut = [] + , p = 0 + finder.forEach(function (f) { + newOut.push( out.substr(p, f.length) + , "\1" + , out.substr(p + f.length, args[a].length) + , "\2" ) + p += f.length + args[a].length + }) + out = newOut.join("") + } + if (npm.color) { + var color = "\033[31;40m" + , reset = "\033[0m" + } else { + var color = "" + , reset = "" + } + out = out.split("\1").join(color) + .split("\2").join(reset) + return out + }).join("\n").trim() + return out + }).join("\n") + + if (results.length && !npm.config.get("long")) { + out = "Top hits for "+(args.map(JSON.stringify).join(" ")) + + "\n" + (new Array(81)).join("—") + "\n" + + out + + "\n" + (new Array(81)).join("—") + "\n" + + "(run with -l or --long to see more context)" + } + + console.log(out.trim()) + cb(null, results) + }) + + }) +} diff --git a/node-v0.8.14/deps/npm/lib/help.js b/node-v0.8.14/deps/npm/lib/help.js new file mode 100644 index 0000000..a8b1f2d --- /dev/null +++ b/node-v0.8.14/deps/npm/lib/help.js @@ -0,0 +1,150 @@ + +module.exports = help + +help.completion = function (opts, cb) { + if (opts.conf.argv.remain.length > 2) return cb(null, []) + var num = 1 + if (-1 !== opts.conf.argv.remain[1].indexOf("api")) num = 3 + getSections(num, cb) +} + +var fs = require("graceful-fs") + , path = require("path") + , exec = require("./utils/exec.js") + , npm = require("./npm.js") + , log = require("npmlog") + , opener = require("opener") + +function help (args, cb) { + var num = 1 + , argv = npm.config.get("argv").cooked + if (argv.length && -1 !== argv[0].indexOf("api")) { + num = 3 + } + + if (args.length > 1 && args[0]) { + return npm.commands["help-search"](args, num, cb) + } + + var section = npm.deref(args[0]) || args[0] + + if (section) { + if ( npm.config.get("usage") + && npm.commands[section] + && npm.commands[section].usage + ) { + npm.config.set("loglevel", "silent") + log.level = "silent" + console.log(npm.commands[section].usage) + return cb() + } + + var sectionPath = path.join( __dirname, "..", "man", "man" + num + , section + "." + num) + , htmlPath = path.resolve( __dirname, "..", "html" + , num === 3 ? "api" : "doc" + , section+".html" ) + return fs.stat + ( sectionPath + , function (e, o) { + if (e) return npm.commands["help-search"](args, cb) + + var manpath = path.join(__dirname, "..", "man") + , env = {} + Object.keys(process.env).forEach(function (i) { + env[i] = process.env[i] + }) + env.MANPATH = manpath + var viewer = npm.config.get("viewer") + + switch (viewer) { + case "woman": + var a = ["-e", "(woman-find-file \"" + sectionPath + "\")"] + exec("emacsclient", a, env, true, cb) + break + + case "browser": + opener(htmlPath, { command: npm.config.get("browser") }, cb) + break + + default: + exec("man", [num, section], env, true, cb) + } + } + ) + } else getSections(function (er, sections) { + if (er) return cb(er) + npm.config.set("loglevel", "silent") + log.level = "silent" + console.log + ( ["\nUsage: npm " + , "" + , "where is one of:" + , npm.config.get("long") ? usages() + : " " + wrap(Object.keys(npm.commands)) + , "" + , "npm -h quick help on " + , "npm -l display full usage info" + , "npm faq commonly asked questions" + , "npm help search for help on " + , "npm help npm involved overview" + , "" + , "Specify configs in the ini-formatted file:" + , " " + npm.config.get("userconfig") + , "or on the command line via: npm --key value" + , "Config info can be viewed via: npm help config" + , "" + , "npm@" + npm.version + " " + path.dirname(__dirname) + ].join("\n")) + cb(er) + }) +} + +function usages () { + // return a string of : + var maxLen = 0 + return Object.keys(npm.commands).filter(function (c) { + return c === npm.deref(c) + }).reduce(function (set, c) { + set.push([c, npm.commands[c].usage || ""]) + maxLen = Math.max(maxLen, c.length) + return set + }, []).map(function (item) { + var c = item[0] + , usage = item[1] + return "\n " + c + (new Array(maxLen - c.length + 2).join(" ")) + + (usage.split("\n") + .join("\n" + (new Array(maxLen + 6).join(" ")))) + }).join("\n") + return out +} + + +function wrap (arr) { + var out = [''] + , l = 0 + arr.sort(function (a,b) { return a --save` afterwards to install a package and" + ,"save it as a dependency in the package.json file." + ,"" + ,"Press ^C at any time to quit." + ].join("\n")) + + initJson(dir, initFile, npm.config.get(), function (er, data) { + log.resume() + log.silly('package data', data) + log.info('init', 'written successfully') + cb(er, data) + }) +} diff --git a/node-v0.8.14/deps/npm/lib/install.js b/node-v0.8.14/deps/npm/lib/install.js new file mode 100644 index 0000000..ecb5d0d --- /dev/null +++ b/node-v0.8.14/deps/npm/lib/install.js @@ -0,0 +1,934 @@ +// npm install +// +// See doc/install.md for more description + +// Managing contexts... +// there's a lot of state associated with an "install" operation, including +// packages that are already installed, parent packages, current shrinkwrap, and +// so on. We maintain this state in a "context" object that gets passed around. +// every time we dive into a deeper node_modules folder, the "family" list that +// gets passed along uses the previous "family" list as its __proto__. Any +// "resolved precise dependency" things that aren't already on this object get +// added, and then that's passed to the next generation of installation. + +module.exports = install + +install.usage = "npm install " + + "\nnpm install " + + "\nnpm install " + + "\nnpm install " + + "\nnpm install @" + + "\nnpm install @" + + "\nnpm install @" + + "\n\nCan specify one or more: npm install ./foo.tgz bar@stable /some/folder" + + "\nIf no argument is supplied and ./npm-shrinkwrap.json is " + + "\npresent, installs dependencies specified in the shrinkwrap." + + "\nOtherwise, installs dependencies from ./package.json." + +install.completion = function (opts, cb) { + // install can complete to a folder with a package.json, or any package. + // if it has a slash, then it's gotta be a folder + // if it starts with https?://, then just give up, because it's a url + // for now, not yet implemented. + var registry = npm.registry + registry.get("/-/short", function (er, pkgs) { + if (er) return cb() + if (!opts.partialWord) return cb(null, pkgs) + + var name = opts.partialWord.split("@").shift() + pkgs = pkgs.filter(function (p) { + return p.indexOf(name) === 0 + }) + + if (pkgs.length !== 1 && opts.partialWord === name) { + return cb(null, pkgs) + } + + registry.get(pkgs[0], function (er, d) { + if (er) return cb() + return cb(null, Object.keys(d["dist-tags"] || {}) + .concat(Object.keys(d.versions || {})) + .map(function (t) { + return pkgs[0] + "@" + t + })) + }) + }) +} + +var npm = require("./npm.js") + , semver = require("semver") + , readJson = require("read-package-json") + , log = require("npmlog") + , path = require("path") + , fs = require("graceful-fs") + , cache = require("./cache.js") + , asyncMap = require("slide").asyncMap + , chain = require("slide").chain + , url = require("url") + , mkdir = require("mkdirp") + , lifecycle = require("./utils/lifecycle.js") + , archy = require("archy") + +function install (args, cb_) { + + function cb (er, installed) { + if (er) return cb_(er) + + var tree = treeify(installed || []) + , pretty = prettify(tree, installed).trim() + + if (pretty) console.log(pretty) + if (er) return cb_(er) + save(where, installed, tree, pretty, cb_) + } + + // the /path/to/node_modules/.. + var where = path.resolve(npm.dir, "..") + + // internal api: install(where, what, cb) + if (arguments.length === 3) { + where = args + args = [].concat(cb_) // pass in [] to do default dep-install + cb_ = arguments[2] + log.verbose("install", "where,what", [where, args]) + } + + if (!npm.config.get("global")) { + args = args.filter(function (a) { + return path.resolve(a) !== where + }) + } + + mkdir(where, function (er, made) { + if (er) return cb(er) + // install dependencies locally by default, + // or install current folder globally + if (!args.length) { + var opt = { dev: npm.config.get("dev") || !npm.config.get("production") } + + if (npm.config.get("global")) args = ["."] + else return readDependencies(null, where, opt, function (er, data) { + if (er) { + log.error("install", "Couldn't read dependencies") + return cb(er) + } + var deps = Object.keys(data.dependencies || {}) + log.verbose("install", "where, deps", [where, deps]) + var context = { family: {} + , ancestors: {} + , explicit: false + , parent: data + , wrap: null } + + if (data.name === path.basename(where) && + path.basename(path.dirname(where)) === "node_modules") { + // Only include in ancestry if it can actually be required. + // Otherwise, it does not count. + context.family[data.name] = + context.ancestors[data.name] = data.version + } + + installManyTop(deps.map(function (dep) { + var target = data.dependencies[dep] + , parsed = url.parse(target.replace(/^git\+/, "git")) + target = dep + "@" + target + return target + }), where, context, cb) + }) + } + + // initial "family" is the name:version of the root, if it's got + // a package.json file. + readJson(path.resolve(where, "package.json"), function (er, data) { + if (er) data = null + var context = { family: {} + , ancestors: {} + , explicit: true + , parent: data + , wrap: null } + if (data) { + context.family[data.name] = context.ancestors[data.name] = data.version + } + var fn = npm.config.get("global") ? installMany : installManyTop + fn(args, where, context, cb) + }) + }) +} + +// reads dependencies for the package at "where". There are several cases, +// depending on our current state and the package's configuration: +// +// 1. If "context" is specified, then we examine the context to see if there's a +// shrinkwrap there. In that case, dependencies are read from the shrinkwrap. +// 2. Otherwise, if an npm-shrinkwrap.json file is present, dependencies are +// read from there. +// 3. Otherwise, dependencies come from package.json. +// +// Regardless of which case we fall into, "cb" is invoked with a first argument +// describing the full package (as though readJson had been used) but with +// "dependencies" read as described above. The second argument to "cb" is the +// shrinkwrap to use in processing this package's dependencies, which may be +// "wrap" (in case 1) or a new shrinkwrap (in case 2). +function readDependencies (context, where, opts, cb) { + var wrap = context ? context.wrap : null + + readJson( path.resolve(where, "package.json") + , function (er, data) { + if (er) return cb(er) + + if (opts && opts.dev) { + if (!data.dependencies) data.dependencies = {}; + Object.keys(data.devDependencies || {}).forEach(function (k) { + data.dependencies[k] = data.devDependencies[k] + }) + } + + if (!npm.config.get("optional") && data.optionalDependencies) { + Object.keys(data.optionalDependencies).forEach(function (d) { + delete data.dependencies[d] + }) + } + + if (wrap) { + log.verbose("readDependencies: using existing wrap", [where, wrap]) + var rv = {} + Object.keys(data).forEach(function (key) { + rv[key] = data[key] + }) + rv.dependencies = {} + Object.keys(wrap).forEach(function (key) { + log.verbose("from wrap", [key, wrap[key]]) + var w = wrap[key] + rv.dependencies[key] = w.from || w.version + }) + log.verbose("readDependencies returned deps", rv.dependencies) + return cb(null, rv, wrap) + } + + var wrapfile = path.resolve(where, "npm-shrinkwrap.json") + + fs.readFile(wrapfile, "utf8", function (er, wrapjson) { + if (er) { + log.verbose("readDependencies", "using package.json deps") + return cb(null, data, null) + } + + try { + var newwrap = JSON.parse(wrapjson) + } catch (ex) { + return cb(ex) + } + + log.info("shrinkwrap", "file %j", wrapfile) + var rv = {} + Object.keys(data).forEach(function (key) { + rv[key] = data[key] + }) + rv.dependencies = {} + Object.keys(newwrap.dependencies || {}).forEach(function (key) { + var w = newwrap.dependencies[key] + rv.dependencies[key] = w.from || w.version + }) + log.verbose("readDependencies returned deps", rv.dependencies) + return cb(null, rv, newwrap.dependencies) + }) + }) +} + +// if the -S|--save option is specified, then write installed packages +// as dependencies to a package.json file. +// This is experimental. +function save (where, installed, tree, pretty, cb) { + if (!npm.config.get("save") && + !npm.config.get("save-dev") && + !npm.config.get("save-optional") || + npm.config.get("global")) { + return cb(null, installed, tree, pretty) + } + + var saveBundle = npm.config.get('save-bundle') + + // each item in the tree is a top-level thing that should be saved + // to the package.json file. + // The relevant tree shape is { : {what:} } + var saveTarget = path.resolve(where, "package.json") + , things = Object.keys(tree).map(function (k) { + // if "what" was a url, then save that instead. + var t = tree[k] + , u = url.parse(t.from) + , w = t.what.split("@") + if (u && u.protocol) w[1] = t.from + return w + }).reduce(function (set, k) { + var rangeDescriptor = semver.valid(k[1]) && + semver.gte(k[1], "0.1.0") + ? "~" : "" + set[k[0]] = rangeDescriptor + k[1] + return set + }, {}) + + // don't use readJson, because we don't want to do all the other + // tricky npm-specific stuff that's in there. + fs.readFile(saveTarget, function (er, data) { + // ignore errors here, just don't save it. + try { + data = JSON.parse(data.toString("utf8")) + } catch (ex) { + er = ex + } + if (er) { + return cb(null, installed, tree, pretty) + + } + + var deps = npm.config.get("save-optional") ? "optionalDependencies" + : npm.config.get("save-dev") ? "devDependencies" + : "dependencies" + + if (saveBundle) { + var bundle = data.bundleDependencies || data.bundledDependencies + delete data.bundledDependencies + if (!Array.isArray(bundle)) bundle = [] + data.bundleDependencies = bundle + } + + data[deps] = data[deps] || {} + Object.keys(things).forEach(function (t) { + data[deps][t] = things[t] + if (saveBundle) { + var i = bundle.indexOf(t) + if (i === -1) bundle.push(t) + } + }) + + data = JSON.stringify(data, null, 2) + "\n" + fs.writeFile(saveTarget, data, function (er) { + cb(er, installed, tree, pretty) + }) + }) +} + + +// Outputting *all* the installed modules is a bit confusing, +// because the length of the path does not make it clear +// that the submodules are not immediately require()able. +// TODO: Show the complete tree, ls-style, but only if --long is provided +function prettify (tree, installed) { + if (npm.config.get("json")) { + function red (set, kv) { + set[kv[0]] = kv[1] + return set + } + + tree = Object.keys(tree).map(function (p) { + if (!tree[p]) return null + var what = tree[p].what.split("@") + , name = what.shift() + , version = what.join("@") + , o = { name: name, version: version, from: tree[p].from } + o.dependencies = tree[p].children.map(function P (dep) { + var what = dep.what.split("@") + , name = what.shift() + , version = what.join("@") + , o = { version: version, from: dep.from } + o.dependencies = dep.children.map(P).reduce(red, {}) + return [name, o] + }).reduce(red, {}) + return o + }) + + return JSON.stringify(tree, null, 2) + } + if (npm.config.get("parseable")) return parseable(installed) + + return Object.keys(tree).map(function (p) { + return archy({ label: tree[p].what + " " + p + , nodes: (tree[p].children || []).map(function P (c) { + if (npm.config.get("long")) { + return { label: c.what, nodes: c.children.map(P) } + } + var g = c.children.map(function (g) { + return g.what + }).join(", ") + if (g) g = " (" + g + ")" + return c.what + g + }) + }) + }).join("\n") +} + +function parseable (installed) { + var long = npm.config.get("long") + , cwd = process.cwd() + return installed.map(function (item) { + return path.resolve(cwd, item[1]) + + ( long ? ":" + item[0] : "" ) + }).join("\n") +} + +function treeify (installed) { + // each item is [what, where, parent, parentDir] + // If no parent, then report it. + // otherwise, tack it into the parent's children list. + // If the parent isn't a top-level then ignore it. + var whatWhere = installed.reduce(function (l, r) { + var parentDir = r[3] + , parent = r[2] + , where = r[1] + , what = r[0] + , from = r[4] + l[where] = { parentDir: parentDir + , parent: parent + , children: [] + , where: where + , what: what + , from: from } + return l + }, {}) + + // log.warn("install", whatWhere, "whatWhere") + return Object.keys(whatWhere).reduce(function (l, r) { + var ww = whatWhere[r] + //log.warn("r, ww", [r, ww]) + if (!ww.parent) { + l[r] = ww + } else { + var p = whatWhere[ww.parentDir] + if (p) p.children.push(ww) + else l[r] = ww + } + return l + }, {}) +} + + +// just like installMany, but also add the existing packages in +// where/node_modules to the family object. +function installManyTop (what, where, context, cb_) { + function cb (er, d) { + if (context.explicit || er) return cb_(er, d) + // since this wasn't an explicit install, let's build the top + // folder, so that `npm install` also runs the lifecycle scripts. + npm.commands.build([where], false, true, function (er) { + return cb_(er, d) + }) + } + + if (context.explicit) return next() + + readJson(path.join(where, "package.json"), function (er, data) { + if (er) return next(er) + lifecycle(data, "preinstall", where, next) + }) + + function next (er) { + if (er) return cb(er) + installManyTop_(what, where, context, cb) + } +} + +function installManyTop_ (what, where, context, cb) { + var nm = path.resolve(where, "node_modules") + , names = context.explicit + ? what.map(function (w) { return w.split(/@/).shift() }) + : [] + + fs.readdir(nm, function (er, pkgs) { + if (er) return installMany(what, where, context, cb) + pkgs = pkgs.filter(function (p) { + return !p.match(/^[\._-]/) + }) + asyncMap(pkgs.map(function (p) { + return path.resolve(nm, p, "package.json") + }), function (jsonfile, cb) { + readJson(jsonfile, function (er, data) { + if (er) return cb(null, []) + return cb(null, [[data.name, data.version]]) + }) + }, function (er, packages) { + // add all the existing packages to the family list. + // however, do not add to the ancestors list. + packages.forEach(function (p) { + context.family[p[0]] = p[1] + }) + return installMany(what, where, context, cb) + }) + }) +} + +function installMany (what, where, context, cb) { + // readDependencies takes care of figuring out whether the list of + // dependencies we'll iterate below comes from an existing shrinkwrap from a + // parent level, a new shrinkwrap at this level, or package.json at this + // level, as well as which shrinkwrap (if any) our dependencies should use. + var opt = { dev: npm.config.get("dev") } + readDependencies(context, where, opt, function (er, data, wrap) { + if (er) data = {} + + var parent = data + + var d = data.dependencies || {} + + // if we're explicitly installing "what" into "where", then the shrinkwrap + // for "where" doesn't apply. This would be the case if someone were adding + // a new package to a shrinkwrapped package. (data.dependencies will not be + // used here except to indicate what packages are already present, so + // there's no harm in using that.) + if (context.explicit) wrap = null + + // what is a list of things. + // resolve each one. + asyncMap( what + , targetResolver(where, context, d) + , function (er, targets) { + + if (er) return cb(er) + + // each target will be a data object corresponding + // to a package, folder, or whatever that is in the cache now. + var newPrev = Object.create(context.family) + , newAnc = Object.create(context.ancestors) + + newAnc[data.name] = data.version + targets.forEach(function (t) { + newPrev[t.name] = t.version + }) + log.silly("resolved", targets) + targets.filter(function (t) { return t }).forEach(function (t) { + log.info("install", "%s into %s", t._id, where) + }) + asyncMap(targets, function (target, cb) { + log.info("installOne", target._id) + var newWrap = wrap ? wrap[target.name].dependencies || {} : null + var newContext = { family: newPrev + , ancestors: newAnc + , parent: parent + , explicit: false + , wrap: newWrap } + installOne(target, where, newContext, cb) + }, cb) + }) + }) +} + +function targetResolver (where, context, deps) { + var alreadyInstalledManually = context.explicit ? [] : null + , nm = path.resolve(where, "node_modules") + , parent = context.parent + , wrap = context.wrap + + if (!context.explicit) fs.readdir(nm, function (er, inst) { + if (er) return alreadyInstalledManually = [] + asyncMap(inst, function (pkg, cb) { + readJson(path.resolve(nm, pkg, "package.json"), function (er, d) { + // error means it's not a package, most likely. + if (er) return cb(null, []) + + // if it's a bundled dep, then assume that anything there is valid. + // otherwise, make sure that it's a semver match with what we want. + var bd = parent.bundleDependencies + if (bd && bd.indexOf(d.name) !== -1 || + semver.satisfies(d.version, deps[d.name] || "*")) { + return cb(null, d.name) + } + + // something is there, but it's not satisfactory. Clobber it. + return cb(null, []) + }) + }, function (er, inst) { + // this is the list of things that are valid and should be ignored. + alreadyInstalledManually = inst + }) + }) + + var to = 0 + return function resolver (what, cb) { + if (!alreadyInstalledManually) return setTimeout(function () { + resolver(what, cb) + }, to++) + + // now we know what's been installed here manually, + // or tampered with in some way that npm doesn't want to overwrite. + if (alreadyInstalledManually.indexOf(what.split("@").shift()) !== -1) { + log.verbose("already installed", "skipping %s %s", what, where) + return cb(null, []) + } + + // check for a version installed higher in the tree. + // If installing from a shrinkwrap, it must match exactly. + if (context.family[what]) { + if (wrap && wrap[what].version === context.family[what]) { + log.verbose("shrinkwrap", "use existing", what) + return cb(null, []) + } + } + + // if it's identical to its parent, then it's probably someone + // doing `npm install foo` inside of the foo project. Print + // a warning, and skip it. + if (parent && parent.name === what && !npm.config.get("force")) { + log.warn("install", "Refusing to install %s as a dependency of itself" + , what) + return cb(null, []) + } + + if (wrap) { + name = what.split(/@/).shift() + if (wrap[name]) { + var wrapTarget = wrap[name].from || wrap[name].version + log.verbose("shrinkwrap", "resolving %s to %s", wrapTarget, what) + what = name + "@" + wrapTarget + } else { + log.verbose("shrinkwrap", "skipping %s (not in shrinkwrap)", what) + } + } else if (deps[what]) { + what = what + "@" + deps[what] + } + + cache.add(what, function (er, data) { + if (er && parent && parent.optionalDependencies && + parent.optionalDependencies.hasOwnProperty(what.split("@")[0])) { + log.warn("optional dep failed, continuing", what) + log.verbose("optional dep failed, continuing", [what, er]) + return cb(null, []) + } + + if (!er && + data && + !context.explicit && + context.family[data.name] === data.version && + !npm.config.get("force")) { + log.info("already installed", data.name + "@" + data.version) + return cb(null, []) + } + + if (data) data._from = what + + return cb(er, data) + }) + } +} + +// we've already decided to install this. if anything's in the way, +// then uninstall it first. +function installOne (target, where, context, cb) { + // the --link flag makes this a "link" command if it's at the + // the top level. + if (where === npm.prefix && npm.config.get("link") + && !npm.config.get("global")) { + return localLink(target, where, context, cb) + } + installOne_(target, where, context, function (er, installedWhat) { + + // check if this one is optional to its parent. + if (er && context.parent && context.parent.optionalDependencies && + context.parent.optionalDependencies.hasOwnProperty(target.name)) { + log.warn("optional dep failed, continuing", target._id) + log.verbose("optional dep failed, continuing", [target._id, er]) + er = null + } + + cb(er, installedWhat) + }) + +} + +function localLink (target, where, context, cb) { + log.verbose("localLink", target._id) + var jsonFile = path.resolve( npm.globalDir, target.name + , "package.json" ) + , parent = context.parent + + readJson(jsonFile, function (er, data) { + if (er || data._id === target._id) { + if (er) { + install( path.resolve(npm.globalDir, "..") + , target._id + , function (er) { + if (er) return cb(er, []) + thenLink() + }) + } else thenLink() + + function thenLink () { + npm.commands.link([target.name], function (er, d) { + log.silly("localLink", "back from link", [er, d]) + cb(er, [resultList(target, where, parent && parent._id)]) + }) + } + + } else { + log.verbose("localLink", "install locally (no link)", target._id) + installOne_(target, where, context, cb) + } + }) +} + +function resultList (target, where, parentId) { + var nm = path.resolve(where, "node_modules") + , targetFolder = path.resolve(nm, target.name) + , prettyWhere = where + + if (!npm.config.get("global")) { + prettyWhere = path.relative(process.cwd(), where) + } + + if (prettyWhere === ".") prettyWhere = null + + if (!npm.config.get("global")) { + // print out the folder relative to where we are right now. + targetFolder = path.relative(process.cwd(), targetFolder) + } + + return [ target._id + , targetFolder + , prettyWhere && parentId + , parentId && prettyWhere + , target._from ] +} + +function installOne_ (target, where, context, cb) { + var nm = path.resolve(where, "node_modules") + , targetFolder = path.resolve(nm, target.name) + , prettyWhere = path.relative(process.cwd, where) + , parent = context.parent + + if (prettyWhere === ".") prettyWhere = null + + chain + ( [ [checkEngine, target] + , [checkPlatform, target] + , [checkCycle, target, context.ancestors] + , [checkGit, targetFolder] + , [write, target, targetFolder, context] ] + , function (er, d) { + if (er) return cb(er) + d.push(resultList(target, where, parent && parent._id)) + cb(er, d) + } + ) +} + +function checkEngine (target, cb) { + var npmv = npm.version + , force = npm.config.get("force") + , nodev = force ? null : npm.config.get("node-version") + , strict = npm.config.get("engine-strict") || target.engineStrict + , eng = target.engines + if (!eng) return cb() + if (nodev && eng.node && !semver.satisfies(nodev, eng.node) + || eng.npm && !semver.satisfies(npmv, eng.npm)) { + if (strict) { + var er = new Error("Unsupported") + er.code = "ENOTSUP" + er.required = eng + er.pkgid = target._id + return cb(er) + } else { + log.warn( "engine", "%s: wanted: %j (current: %j)" + , target._id, eng, {node: nodev, npm: npm.version} ) + } + } + return cb() +} + +function checkPlatform (target, cb) { + var platform = process.platform + , arch = process.arch + , osOk = true + , cpuOk = true + , force = npm.config.get("force") + + if (force) { + return cb() + } + + if (target.os) { + osOk = checkList(platform, target.os) + } + if (target.cpu) { + cpuOk = checkList(arch, target.cpu) + } + if (!osOk || !cpuOk) { + var er = new Error("Unsupported") + er.code = "EBADPLATFORM" + er.os = target.os || ['any'] + er.cpu = target.cpu || ['any'] + er.pkgid = target._id + return cb(er) + } + return cb() +} + +function checkList (value, list) { + var tmp + , match = false + , blc = 0 + if (typeof list === "string") { + list = [list] + } + if (list.length === 1 && list[0] === "any") { + return true; + } + for (var i = 0; i < list.length; ++i) { + tmp = list[i] + if (tmp[0] === '!') { + tmp = tmp.slice(1) + if (tmp === value) { + return false; + } + ++blc + } else { + match = match || tmp === value + } + } + return match || blc === list.length +} + +function checkCycle (target, ancestors, cb) { + // there are some very rare and pathological edge-cases where + // a cycle can cause npm to try to install a never-ending tree + // of stuff. + // Simplest: + // + // A -> B -> A' -> B' -> A -> B -> A' -> B' -> A -> ... + // + // Solution: Simply flat-out refuse to install any name@version + // that is already in the prototype tree of the ancestors object. + // A more correct, but more complex, solution would be to symlink + // the deeper thing into the new location. + // Will do that if anyone whines about this irl. + // + // Note: `npm install foo` inside of the `foo` package will abort + // earlier if `--force` is not set. However, if it IS set, then + // we need to still fail here, but just skip the first level. Of + // course, it'll still fail eventually if it's a true cycle, and + // leave things in an undefined state, but that's what is to be + // expected when `--force` is used. That is why getPrototypeOf + // is used *twice* here: to skip the first level of repetition. + + var p = Object.getPrototypeOf(Object.getPrototypeOf(ancestors)) + , name = target.name + , version = target.version + while (p && p !== Object.prototype && p[name] !== version) { + p = Object.getPrototypeOf(p) + } + if (p[name] !== version) return cb() + + var er = new Error("Unresolvable cycle detected") + var tree = [target._id, JSON.parse(JSON.stringify(ancestors))] + , t = Object.getPrototypeOf(ancestors) + while (t && t !== Object.prototype) { + if (t === p) t.THIS_IS_P = true + tree.push(JSON.parse(JSON.stringify(t))) + t = Object.getPrototypeOf(t) + } + log.verbose("unresolvable dependency tree", tree) + er.pkgid = target._id + er.code = "ECYCLE" + return cb(er) +} + +function checkGit (folder, cb) { + // if it's a git repo then don't touch it! + fs.lstat(folder, function (er, s) { + if (er || !s.isDirectory()) return cb() + else checkGit_(folder, cb) + }) +} + +function checkGit_ (folder, cb) { + fs.stat(path.resolve(folder, ".git"), function (er, s) { + if (!er && s.isDirectory()) { + var e = new Error("Appears to be a git repo or submodule.") + e.path = folder + e.code = "EISGIT" + return cb(e) + } + cb() + }) +} + +function write (target, targetFolder, context, cb_) { + var up = npm.config.get("unsafe-perm") + , user = up ? null : npm.config.get("user") + , group = up ? null : npm.config.get("group") + , family = context.family + + function cb (er, data) { + // cache.unpack returns the data object, and all we care about + // is the list of installed packages from that last thing. + if (!er) return cb_(er, data) + + if (false === npm.config.get("rollback")) return cb_(er) + npm.commands.unbuild([targetFolder], function (er2) { + if (er2) log.error("error rolling back", target._id, er2) + return cb_(er, data) + }) + } + + var bundled = [] + + chain + ( [ [ cache.unpack, target.name, target.version, targetFolder + , null, null, user, group ] + , [ fs, "writeFile" + , path.resolve(targetFolder, "package.json") + , JSON.stringify(target, null, 2) + "\n" ] + , [ lifecycle, target, "preinstall", targetFolder ] + , function (cb) { + if (!target.bundleDependencies) return cb() + + var bd = path.resolve(targetFolder, "node_modules") + fs.readdir(bd, function (er, b) { + // nothing bundled, maybe + if (er) return cb() + bundled = b || [] + cb() + }) + } ] + + // nest the chain so that we can throw away the results returned + // up until this point, since we really don't care about it. + , function X (er) { + if (er) return cb(er) + + // before continuing to installing dependencies, check for a shrinkwrap. + var opt = { dev: npm.config.get("dev") } + readDependencies(context, targetFolder, opt, function (er, data, wrap) { + var deps = Object.keys(data.dependencies || {}) + + // don't install bundleDependencies, unless they're missing. + if (data.bundleDependencies) { + deps = deps.filter(function (d) { + return data.bundleDependencies.indexOf(d) === -1 || + bundled.indexOf(d) === -1 + }) + } + + var newcontext = { family: family + , ancestors: context.ancestors + , parent: target + , explicit: false + , wrap: wrap } + installMany(deps.filter(function (d) { + // prefer to not install things that are satisfied by + // something in the "family" list, unless we're installing + // from a shrinkwrap. + return wrap || !semver.satisfies(family[d], data.dependencies[d]) + }).map(function (d) { + var t = data.dependencies[d] + , parsed = url.parse(t.replace(/^git\+/, "git")) + t = d + "@" + t + return t + }), targetFolder, newcontext, function (er, d) { + log.verbose("about to build", targetFolder) + if (er) return cb(er) + npm.commands.build( [targetFolder] + , npm.config.get("global") + , true + , function (er) { return cb(er, d) }) + }) + }) + }) +} diff --git a/node-v0.8.14/deps/npm/lib/link.js b/node-v0.8.14/deps/npm/lib/link.js new file mode 100644 index 0000000..e912796 --- /dev/null +++ b/node-v0.8.14/deps/npm/lib/link.js @@ -0,0 +1,169 @@ +// link with no args: symlink the folder to the global location +// link with package arg: symlink the global to the local + +var npm = require("./npm.js") + , symlink = require("./utils/link.js") + , fs = require("graceful-fs") + , log = require("npmlog") + , asyncMap = require("slide").asyncMap + , chain = require("slide").chain + , path = require("path") + , rm = require("rimraf") + , build = require("./build.js") + +module.exports = link + +link.usage = "npm link (in package dir)" + + "\nnpm link (link global into local)" + +link.completion = function (opts, cb) { + var dir = npm.globalDir + fs.readdir(dir, function (er, files) { + cb(er, files.filter(function (f) { + return f.charAt(0) !== "." + })) + }) +} + +function link (args, cb) { + if (process.platform === "win32") { + var semver = require("semver") + if (!semver.satisfies(process.version, ">=0.7.9")) { + var msg = "npm link not supported on windows prior to node 0.7.9" + , e = new Error(msg) + e.code = "ENOTSUP" + e.errno = require("constants").ENOTSUP + return cb(e) + } + } + + if (npm.config.get("global")) { + return cb(new Error("link should never be --global.\n" + +"Please re-run this command with --local")) + } + + if (args.length === 1 && args[0] === ".") args = [] + if (args.length) return linkInstall(args, cb) + linkPkg(npm.prefix, cb) +} + +function linkInstall (pkgs, cb) { + asyncMap(pkgs, function (pkg, cb) { + function n (er, data) { + if (er) return cb(er, data) + // install returns [ [folder, pkgId], ... ] + // but we definitely installed just one thing. + var d = data.filter(function (d) { return !d[3] }) + pp = d[0][1] + pkg = path.basename(pp) + target = path.resolve(npm.dir, pkg) + next() + } + + var t = path.resolve(npm.globalDir, "..") + , pp = path.resolve(npm.globalDir, pkg) + , rp = null + , target = path.resolve(npm.dir, pkg) + + // if it's a folder or a random not-installed thing, then + // link or install it first + if (pkg.indexOf("/") !== -1 || pkg.indexOf("\\") !== -1) { + return fs.lstat(path.resolve(pkg), function (er, st) { + if (er || !st.isDirectory()) { + npm.commands.install(t, pkg, n) + } else { + rp = path.resolve(pkg) + linkPkg(rp, n) + } + }) + } + + fs.lstat(pp, function (er, st) { + if (er) { + rp = pp + return npm.commands.install(t, pkg, n) + } else if (!st.isSymbolicLink()) { + rp = pp + next() + } else { + return fs.realpath(pp, function (er, real) { + if (er) log.warn("invalid symbolic link", pkg) + else rp = real + next() + }) + } + }) + + function next () { + chain + ( [ [npm.commands, "unbuild", [target]] + , [function (cb) { + log.verbose("link", "symlinking %s to %s", pp, target) + cb() + }] + , [symlink, pp, target] + // do run lifecycle scripts - full build here. + , rp && [build, [target]] + , [ resultPrinter, pkg, pp, target, rp ] ] + , cb ) + } + }, cb) +} + +function linkPkg (folder, cb_) { + var me = folder || npm.prefix + , readJson = require("read-package-json") + + log.verbose("linkPkg", folder) + + readJson(path.resolve(me, "package.json"), function (er, d) { + function cb (er) { + return cb_(er, [[d && d._id, target, null, null]]) + } + if (er) return cb(er) + var target = path.resolve(npm.globalDir, d.name) + rm(target, function (er) { + if (er) return cb(er) + symlink(me, target, function (er) { + if (er) return cb(er) + log.verbose("link", "build target", target) + // also install missing dependencies. + npm.commands.install(me, [], function (er, installed) { + if (er) return cb(er) + // build the global stuff. Don't run *any* scripts, because + // install command already will have done that. + build([target], true, build._noLC, true, function (er) { + if (er) return cb(er) + resultPrinter(path.basename(me), me, target, cb) + }) + }) + }) + }) + }) +} + +function resultPrinter (pkg, src, dest, rp, cb) { + if (typeof cb !== "function") cb = rp, rp = null + var where = dest + rp = (rp || "").trim() + src = (src || "").trim() + // XXX If --json is set, then look up the data from the package.json + if (npm.config.get("parseable")) { + return parseableOutput(dest, rp || src, cb) + } + if (rp === src) rp = null + console.log(where + " -> " + src + (rp ? " -> " + rp: "")) + cb() +} + +function parseableOutput (dest, rp, cb) { + // XXX this should match ls --parseable and install --parseable + // look up the data from package.json, format it the same way. + // + // link is always effectively "long", since it doesn't help much to + // *just* print the target folder. + // However, we don't actually ever read the version number, so + // the second field is always blank. + console.log(dest + "::" + rp) + cb() +} diff --git a/node-v0.8.14/deps/npm/lib/ls.js b/node-v0.8.14/deps/npm/lib/ls.js new file mode 100644 index 0000000..8a4d627 --- /dev/null +++ b/node-v0.8.14/deps/npm/lib/ls.js @@ -0,0 +1,334 @@ + +// show the installed versions of packages +// +// --parseable creates output like this: +// ::: +// Flags are a :-separated list of zero or more indicators + +module.exports = exports = ls + +var npm = require("./npm.js") + , readInstalled = require("read-installed") + , log = require("npmlog") + , path = require("path") + , archy = require("archy") + , semver = require("semver") + +ls.usage = "npm ls" + +ls.completion = require("./utils/completion/installed-deep.js") + +function ls (args, silent, cb) { + if (typeof cb !== "function") cb = silent, silent = false + + var dir = path.resolve(npm.dir, "..") + + // npm ls 'foo@~1.3' bar 'baz@<2' + if (!args) args = [] + else args = args.map(function (a) { + var nv = a.split("@") + , name = nv.shift() + , ver = semver.validRange(nv.join("@")) || "" + + return [ name, ver ] + }) + + readInstalled(dir, npm.config.get("depth"), function (er, data) { + var bfs = bfsify(data, args) + , lite = getLite(bfs) + + if (er || silent) return cb(er, data, lite) + + var long = npm.config.get("long") + , json = npm.config.get("json") + , out + if (json) { + var seen = [] + var d = long ? bfs : lite + // the raw data can be circular + out = JSON.stringify(d, function (k, o) { + if (typeof o === "object") { + if (-1 !== seen.indexOf(o)) return "[Circular]" + seen.push(o) + } + return o + }, 2) + } else if (npm.config.get("parseable")) { + out = makeParseable(bfs, long, dir) + } else if (data) { + out = makeArchy(bfs, long, dir) + } + console.log(out) + + // if any errors were found, then complain and exit status 1 + if (lite.problems && lite.problems.length) { + er = lite.problems.join('\n') + } + cb(er, data, lite) + }) +} + +// only include +function filter (data, args) { + +} + +function alphasort (a, b) { + a = a.toLowerCase() + b = b.toLowerCase() + return a > b ? 1 + : a < b ? -1 : 0 +} + +function getLite (data, noname) { + var lite = {} + , maxDepth = npm.config.get("depth") + , url = require("url") + + if (!noname && data.name) lite.name = data.name + if (data.version) lite.version = data.version + if (data.extraneous) { + lite.extraneous = true + lite.problems = lite.problems || [] + lite.problems.push( "extraneous: " + + data.name + "@" + data.version + + " " + (data.path || "") ) + } + + if (data._from) { + var from = data._from + if (from.indexOf(data.name + "@") === 0) { + from = from.substr(data.name.length + 1) + } + var u = url.parse(from) + if (u.protocol) lite.from = from + } + + if (data.invalid) { + lite.invalid = true + lite.problems = lite.problems || [] + lite.problems.push( "invalid: " + + data.name + "@" + data.version + + " " + (data.path || "") ) + } + + if (data.dependencies) { + var deps = Object.keys(data.dependencies) + if (deps.length) lite.dependencies = deps.map(function (d) { + var dep = data.dependencies[d] + if (typeof dep === "string") { + lite.problems = lite.problems || [] + var p + if (data.depth >= maxDepth) { + p = "max depth reached: " + } else { + p = "missing: " + } + p += d + "@" + dep + + ", required by " + + data.name + "@" + data.version + lite.problems.push(p) + return [d, { required: dep, missing: true }] + } + return [d, getLite(dep, true)] + }).reduce(function (deps, d) { + if (d[1].problems) { + lite.problems = lite.problems || [] + lite.problems.push.apply(lite.problems, d[1].problems) + } + deps[d[0]] = d[1] + return deps + }, {}) + } + return lite +} + +function bfsify (root, args, current, queue, seen) { + // walk over the data, and turn it from this: + // +-- a + // | `-- b + // | `-- a (truncated) + // `--b (truncated) + // into this: + // +-- a + // `-- b + // which looks nicer + args = args || [] + current = current || root + queue = queue || [] + seen = seen || [root] + var deps = current.dependencies = current.dependencies || {} + Object.keys(deps).forEach(function (d) { + var dep = deps[d] + if (typeof dep !== "object") return + if (seen.indexOf(dep) !== -1) { + if (npm.config.get("parseable") || !npm.config.get("long")) { + delete deps[d] + return + } else { + dep = deps[d] = Object.create(dep) + dep.dependencies = {} + } + } + queue.push(dep) + seen.push(dep) + }) + + if (!queue.length) { + // if there were args, then only show the paths to found nodes. + return filterFound(root, args) + } + return bfsify(root, args, queue.shift(), queue, seen) +} + +function filterFound (root, args) { + if (!args.length) return root + var deps = root.dependencies + if (deps) Object.keys(deps).forEach(function (d) { + var dep = filterFound(deps[d], args) + + // see if this one itself matches + var found = false + for (var i = 0; !found && i < args.length; i ++) { + if (d === args[i][0]) { + found = semver.satisfies(dep.version, args[i][1]) + } + } + // included explicitly + if (found) dep._found = true + // included because a child was included + if (dep._found && !root._found) root._found = 1 + // not included + if (!dep._found) delete deps[d] + }) + if (!root._found) root._found = false + return root +} + +function makeArchy (data, long, dir) { + var out = makeArchy_(data, long, dir, 0) + return archy(out, "", { unicode: npm.config.get("unicode") }) +} + +function makeArchy_ (data, long, dir, depth, parent, d) { + var color = npm.color + if (typeof data === "string") { + if (depth < npm.config.get("depth")) { + // just missing + var p = parent.link || parent.path + var unmet = "UNMET DEPENDENCY" + if (color) { + unmet = "\033[31;40m" + unmet + "\033[0m" + } + data = unmet + " " + d + " " + data + } else { + data = d+"@"+ data + } + return data + } + + var out = {} + // the top level is a bit special. + out.label = data._id || "" + if (data._found === true && data._id) { + var pre = color ? "\033[33;40m" : "" + , post = color ? "\033[m" : "" + out.label = pre + out.label.trim() + post + " " + } + if (data.link) out.label += " -> " + data.link + + if (data.invalid) { + if (data.realName !== data.name) out.label += " ("+data.realName+")" + out.label += " " + (color ? "\033[31;40m" : "") + + "invalid" + + (color ? "\033[0m" : "") + } + + if (data.extraneous && data.path !== dir) { + out.label += " " + (color ? "\033[32;40m" : "") + + "extraneous" + + (color ? "\033[0m" : "") + } + + if (long) { + if (dir === data.path) out.label += "\n" + dir + out.label += "\n" + getExtras(data, dir) + } else if (dir === data.path) { + if (out.label) out.label += " " + out.label += dir + } + + // now all the children. + out.nodes = Object.keys(data.dependencies || {}) + .sort(alphasort).map(function (d) { + return makeArchy_(data.dependencies[d], long, dir, depth + 1, data, d) + }) + + if (out.nodes.length === 0 && data.path === dir) { + out.nodes = ["(empty)"] + } + + return out +} + +function getExtras (data, dir) { + var extras = [] + , url = require("url") + + if (data.description) extras.push(data.description) + if (data.repository) extras.push(data.repository.url) + if (data.homepage) extras.push(data.homepage) + if (data._from) { + var from = data._from + if (from.indexOf(data.name + "@") === 0) { + from = from.substr(data.name.length + 1) + } + var u = url.parse(from) + if (u.protocol) extras.push(from) + } + return extras.join("\n") +} + + +function makeParseable (data, long, dir, depth, parent, d) { + depth = depth || 0 + + return [ makeParseable_(data, long, dir, depth, parent, d) ] + .concat(Object.keys(data.dependencies || {}) + .sort(alphasort).map(function (d) { + return makeParseable(data.dependencies[d], long, dir, depth + 1, data, d) + })) + .filter(function (x) { return x }) + .join("\n") +} + +function makeParseable_ (data, long, dir, depth, parent, d) { + if (data.hasOwnProperty("_found") && data._found !== true) return "" + + if (typeof data === "string") { + if (data.depth < npm.config.get("depth")) { + var p = parent.link || parent.path + data = npm.config.get("long") + ? path.resolve(parent.path, "node_modules", d) + + ":"+d+"@"+JSON.stringify(data)+":INVALID:MISSING" + : "" + } else { + data = path.resolve(data.path, "node_modules", d) + + (npm.config.get("long") + ? ":" + d + "@" + JSON.stringify(data) + + ":" // no realpath resolved + + ":MAXDEPTH" + : "") + } + + return data + } + + if (!npm.config.get("long")) return data.path + + return data.path + + ":" + (data._id || "") + + ":" + (data.realPath !== data.path ? data.realPath : "") + + (data.extraneous ? ":EXTRANEOUS" : "") + + (data.invalid ? ":INVALID" : "") +} diff --git a/node-v0.8.14/deps/npm/lib/npm.js b/node-v0.8.14/deps/npm/lib/npm.js new file mode 100644 index 0000000..f009607 --- /dev/null +++ b/node-v0.8.14/deps/npm/lib/npm.js @@ -0,0 +1,506 @@ +;(function(){ +// windows: running "npm blah" in this folder will invoke WSH, not node. +if (typeof WScript !== "undefined") { + WScript.echo("npm does not work when run\n" + +"with the Windows Scripting Host\n\n" + +"'cd' to a different directory,\n" + +"or type 'npm.cmd ',\n" + +"or type 'node npm '.") + WScript.quit(1) + return +} + + +// FIXME there really ought to be a path.split in node core +require("path").SPLIT_CHAR = process.platform === "win32" ? "\\" : "/" + +var EventEmitter = require("events").EventEmitter + , npm = module.exports = new EventEmitter + , config = require("./config.js") + , npmconf = require("npmconf") + , log = require("npmlog") + , fs = require("graceful-fs") + , path = require("path") + , abbrev = require("abbrev") + , which = require("which") + , semver = require("semver") + , findPrefix = require("./utils/find-prefix.js") + , getUid = require("uid-number") + , mkdirp = require("mkdirp") + , slide = require("slide") + , chain = slide.chain + , RegClient = require("npm-registry-client") + +npm.config = {loaded: false} + +// /usr/local is often a read-only fs, which is not +// well handled by node or mkdirp. Just double-check +// in the case of errors when making the prefix dirs. +function mkdir (p, cb) { + mkdirp(p, function (er, made) { + // it could be that we couldn't create it, because it + // already exists, and is on a read-only fs. + if (er) { + return fs.stat(p, function (er2, st) { + if (er2 || !st.isDirectory()) return cb(er) + return cb(null, made) + }) + } + return cb(er, made) + }) +} + +npm.commands = {} + +try { + // startup, ok to do this synchronously + var j = JSON.parse(fs.readFileSync( + path.join(__dirname, "../package.json"))+"") + npm.version = j.version + npm.nodeVersionRequired = j.engines.node + if (!semver.satisfies(process.version, j.engines.node)) { + log.warn("unsupported version", ["" + ,"npm requires node version: "+j.engines.node + ,"And you have: "+process.version + ,"which is not satisfactory." + ,"" + ,"Bad things will likely happen. You have been warned." + ,""].join("\n")) + } +} catch (ex) { + try { + log.info("error reading version", ex) + } catch (er) {} + npm.version = ex +} + +var commandCache = {} + // short names for common things + , aliases = { "rm" : "uninstall" + , "r" : "uninstall" + , "un" : "uninstall" + , "unlink" : "uninstall" + , "remove" : "uninstall" + , "rb" : "rebuild" + , "list" : "ls" + , "la" : "ls" + , "ll" : "ls" + , "ln" : "link" + , "i" : "install" + , "isntall" : "install" + , "up" : "update" + , "c" : "config" + , "info" : "view" + , "show" : "view" + , "find" : "search" + , "s" : "search" + , "se" : "search" + , "author" : "owner" + , "home" : "docs" + , "unstar": "star" // same function + , "apihelp" : "help" + , "login": "adduser" + , "add-user": "adduser" + , "tst": "test" + , "find-dupes": "dedupe" + , "ddp": "dedupe" + } + + , aliasNames = Object.keys(aliases) + // these are filenames in . + , cmdList = [ "install" + , "uninstall" + , "cache" + , "config" + , "set" + , "get" + , "update" + , "outdated" + , "prune" + , "submodule" + , "pack" + , "dedupe" + + , "rebuild" + , "link" + + , "publish" + , "star" + , "tag" + , "adduser" + , "unpublish" + , "owner" + , "deprecate" + , "shrinkwrap" + + , "help" + , "help-search" + , "ls" + , "search" + , "view" + , "init" + , "version" + , "edit" + , "explore" + , "docs" + , "bugs" + , "faq" + , "root" + , "prefix" + , "bin" + , "whoami" + + , "test" + , "stop" + , "start" + , "restart" + , "run-script" + , "completion" + ] + , plumbing = [ "build" + , "unbuild" + , "xmas" + , "substack" + ] + , fullList = npm.fullList = cmdList.concat(aliasNames).filter(function (c) { + return plumbing.indexOf(c) === -1 + }) + , abbrevs = abbrev(fullList) + +Object.keys(abbrevs).concat(plumbing).forEach(function addCommand (c) { + Object.defineProperty(npm.commands, c, { get : function () { + if (!loaded) throw new Error( + "Call npm.load(conf, cb) before using this command.\n"+ + "See the README.md or cli.js for example usage.") + var a = npm.deref(c) + if (c === "la" || c === "ll") { + npm.config.set("long", true) + } + npm.command = c + if (commandCache[a]) return commandCache[a] + var cmd = require(__dirname+"/"+a+".js") + commandCache[a] = function () { + var args = Array.prototype.slice.call(arguments, 0) + if (typeof args[args.length - 1] !== "function") { + args.push(defaultCb) + } + if (args.length === 1) args.unshift([]) + cmd.apply(npm, args) + } + Object.keys(cmd).forEach(function (k) { + commandCache[a][k] = cmd[k] + }) + return commandCache[a] + }, enumerable: fullList.indexOf(c) !== -1 }) + + // make css-case commands callable via camelCase as well + if (c.match(/\-([a-z])/)) { + addCommand(c.replace(/\-([a-z])/g, function (a, b) { + return b.toUpperCase() + })) + } +}) + +function defaultCb (er, data) { + if (er) console.error(er.stack || er.message) + else console.log(data) +} + +npm.deref = function (c) { + if (!c) return "" + if (c.match(/[A-Z]/)) c = c.replace(/([A-Z])/g, function (m) { + return "-" + m.toLowerCase() + }) + if (plumbing.indexOf(c) !== -1) return c + var a = abbrevs[c] + if (aliases[a]) a = aliases[a] + return a +} + +var loaded = false + , loading = false + , loadErr = null + , loadListeners = [] + +function loadCb (er) { + loadListeners.forEach(function (cb) { + process.nextTick(cb.bind(npm, er, npm)) + }) + loadListeners.length = 0 +} + +npm.load = function (cli, cb_) { + if (!cb_ && typeof cli === "function") cb_ = cli , cli = {} + if (!cb_) cb_ = function () {} + if (!cli) cli = {} + loadListeners.push(cb_) + if (loaded || loadErr) return cb(loadErr) + if (loading) return + loading = true + var onload = true + + function cb (er) { + if (loadErr) return + npm.config.loaded = true + loaded = true + loadCb(loadErr = er) + if (onload = onload && npm.config.get("onload-script")) { + require(onload) + onload = false + } + } + + log.pause() + + load(npm, cli, cb) +} + +function load (npm, cli, cb) { + which(process.argv[0], function (er, node) { + if (!er && node.toUpperCase() !== process.execPath.toUpperCase()) { + log.verbose("node symlink", node) + process.execPath = node + process.installPrefix = path.resolve(node, "..", "..") + } + + // look up configs + //console.error("about to look up configs") + + var builtin = path.resolve(__dirname, "..", "npmrc") + npmconf.load(cli, builtin, function (er, conf) { + if (er === conf) er = null + + npm.config = conf + + var color = conf.get("color") + + log.level = conf.get("loglevel") + log.heading = "npm" + log.stream = conf.get("logstream") + switch (color) { + case "always": log.enableColor(); break + case false: log.disableColor(); break + } + log.resume() + + if (er) return cb(er) + + // see if we need to color normal output + switch (color) { + case "always": + npm.color = true + break + case false: + npm.color = false + break + default: + var tty = require("tty") + if (process.stdout.isTTY) npm.color = true + else if (!tty.isatty) npm.color = true + else if (tty.isatty(1)) npm.color = true + else npm.color = false + break + } + + // at this point the configs are all set. + // go ahead and spin up the registry client. + var token = conf.get("_token") + if (typeof token === "string") { + try { + token = JSON.parse(token) + conf.set("_token", token, "user") + conf.save("user") + } catch (e) { token = null } + } + + npm.registry = new RegClient(npm.config) + + // save the token cookie in the config file + if (npm.registry.couchLogin) { + npm.registry.couchLogin.tokenSet = function (tok) { + npm.config.set("_token", tok, "user") + // ignore save error. best effort. + npm.config.save("user") + } + } + + var umask = npm.config.get("umask") + npm.modes = { exec: 0777 & (~umask) + , file: 0666 & (~umask) + , umask: umask } + + chain([ [ loadPrefix, npm, cli ] + , [ setUser, conf, conf.root ] + , [ loadUid, npm ] + ], cb) + }) + }) +} + +function loadPrefix (npm, conf, cb) { + // try to guess at a good node_modules location. + var p + , gp + if (!Object.prototype.hasOwnProperty.call(conf, "prefix")) { + p = process.cwd() + } else { + p = npm.config.get("prefix") + } + gp = npm.config.get("prefix") + + findPrefix(p, function (er, p) { + Object.defineProperty(npm, "localPrefix", + { get : function () { return p } + , set : function (r) { return p = r } + , enumerable : true + }) + // the prefix MUST exist, or else nothing works. + if (!npm.config.get("global")) { + mkdir(p, next) + } else { + next(er) + } + }) + + gp = path.resolve(gp) + Object.defineProperty(npm, "globalPrefix", + { get : function () { return gp } + , set : function (r) { return gp = r } + , enumerable : true + }) + // the prefix MUST exist, or else nothing works. + mkdir(gp, next) + + + var i = 2 + , errState = null + function next (er) { + if (errState) return + if (er) return cb(errState = er) + if (--i === 0) return cb() + } +} + + +function loadUid (npm, cb) { + // if we're not in unsafe-perm mode, then figure out who + // to run stuff as. Do this first, to support `npm update npm -g` + if (!npm.config.get("unsafe-perm")) { + getUid(npm.config.get("user"), npm.config.get("group"), cb) + } else { + process.nextTick(cb) + } +} + +function setUser (cl, dc, cb) { + // If global, leave it as-is. + // If not global, then set the user to the owner of the prefix folder. + // Just set the default, so it can be overridden. + if (cl.get("global")) return cb() + if (process.env.SUDO_UID) { + dc.user = +(process.env.SUDO_UID) + return cb() + } + + var prefix = path.resolve(cl.get("prefix")) + mkdir(prefix, function (er) { + if (er) { + log.error("could not create prefix dir", prefix) + return cb(er) + } + fs.stat(prefix, function (er, st) { + dc.user = st && st.uid + return cb(er) + }) + }) +} + + +Object.defineProperty(npm, "prefix", + { get : function () { + return npm.config.get("global") ? npm.globalPrefix : npm.localPrefix + } + , set : function (r) { + var k = npm.config.get("global") ? "globalPrefix" : "localPrefix" + return npm[k] = r + } + , enumerable : true + }) + +Object.defineProperty(npm, "bin", + { get : function () { + if (npm.config.get("global")) return npm.globalBin + return path.resolve(npm.root, ".bin") + } + , enumerable : true + }) + +Object.defineProperty(npm, "globalBin", + { get : function () { + var b = npm.globalPrefix + if (process.platform !== "win32") b = path.resolve(b, "bin") + return b + } + }) + +Object.defineProperty(npm, "dir", + { get : function () { + if (npm.config.get("global")) return npm.globalDir + return path.resolve(npm.prefix, "node_modules") + } + , enumerable : true + }) + +Object.defineProperty(npm, "globalDir", + { get : function () { + return (process.platform !== "win32") + ? path.resolve(npm.globalPrefix, "lib", "node_modules") + : path.resolve(npm.globalPrefix, "node_modules") + } + , enumerable : true + }) + +Object.defineProperty(npm, "root", + { get : function () { return npm.dir } }) + +Object.defineProperty(npm, "cache", + { get : function () { return npm.config.get("cache") } + , set : function (r) { return npm.config.set("cache", r) } + , enumerable : true + }) + +var tmpFolder +Object.defineProperty(npm, "tmp", + { get : function () { + if (!tmpFolder) tmpFolder = "npm-" + process.pid + return path.resolve(npm.config.get("tmp"), tmpFolder) + } + , enumerable : true + }) + +// the better to repl you with +Object.getOwnPropertyNames(npm.commands).forEach(function (n) { + if (npm.hasOwnProperty(n) || n === "config") return + + Object.defineProperty(npm, n, { get: function () { + return function () { + var args = Array.prototype.slice.call(arguments, 0) + , cb = defaultCb + + if (args.length === 1 && Array.isArray(args[0])) { + args = args[0] + } + + if (typeof args[args.length - 1] === "function") { + cb = args.pop() + } + + npm.commands[n](args, cb) + } + }, enumerable: false, configurable: true }) +}) + +if (require.main === module) { + require("../bin/npm-cli.js") +} +})() diff --git a/node-v0.8.14/deps/npm/lib/outdated.js b/node-v0.8.14/deps/npm/lib/outdated.js new file mode 100644 index 0000000..33c182c --- /dev/null +++ b/node-v0.8.14/deps/npm/lib/outdated.js @@ -0,0 +1,149 @@ +/* + +npm outdated [pkg] + +Does the following: + +1. check for a new version of pkg + +If no packages are specified, then run for all installed +packages. + +*/ + +module.exports = outdated + +outdated.usage = "npm outdated [ [ ...]]" + +outdated.completion = require("./utils/completion/installed-deep.js") + + +var path = require("path") + , fs = require("graceful-fs") + , readJson = require("read-package-json") + , cache = require("./cache.js") + , asyncMap = require("slide").asyncMap + , npm = require("./npm.js") + , semver = require("semver") + +function outdated (args, silent, cb) { + if (typeof cb !== "function") cb = silent, silent = false + var dir = path.resolve(npm.dir, "..") + outdated_(args, dir, {}, function (er, list) { + if (er || silent) return cb(er, list) + var outList = list.map(makePretty) + console.log(outList.join("\n")) + cb(null, list) + }) +} + +// [[ dir, dep, has, want ]] +function makePretty (p) { + var parseable = npm.config.get("parseable") + , long = npm.config.get("long") + , dep = p[1] + , dir = path.resolve(p[0], "node_modules", dep) + , has = p[2] + , want = p[3] + + // XXX add --json support + // Should match (more or less) the output of ls --json + + if (parseable) { + var str = dir + if (npm.config.get("long")) { + str += ":" + dep + "@" + want + + ":" + (has ? (dep + "@" + has) : "MISSING") + } + return str + } + + if (!npm.config.get("global")) { + dir = path.relative(process.cwd(), dir) + } + return dep + "@" + want + " " + dir + + " current=" + (has || "MISSING") +} + +function outdated_ (args, dir, parentHas, cb) { + // get the deps from package.json, or {:"*"} + // asyncMap over deps: + // shouldHave = cache.add(dep, req).version + // if has === shouldHave then + // return outdated(args, dir/node_modules/dep, parentHas + has) + // else if dep in args or args is empty + // return [dir, dep, has, shouldHave] + + var deps = null + readJson(path.resolve(dir, "package.json"), function (er, d) { + deps = (er) ? true : (d.dependencies || {}) + return next() + }) + + var has = null + fs.readdir(path.resolve(dir, "node_modules"), function (er, pkgs) { + if (er) { + has = Object.create(parentHas) + return next() + } + asyncMap(pkgs, function (pkg, cb) { + var jsonFile = path.resolve(dir, "node_modules", pkg, "package.json") + readJson(jsonFile, function (er, d) { + cb(null, er ? [] : [[d.name, d.version]]) + }) + }, function (er, pvs) { + if (er) return cb(er) + has = Object.create(parentHas) + pvs.forEach(function (pv) { + has[pv[0]] = pv[1] + }) + + next() + }) + }) + + function next () { + if (!has || !deps) return + if (deps === true) { + deps = Object.keys(has).reduce(function (l, r) { + l[r] = "*" + return l + }, {}) + } + + // now get what we should have, based on the dep. + // if has[dep] !== shouldHave[dep], then cb with the data + // otherwise dive into the folder + asyncMap(Object.keys(deps), function (dep, cb) { + shouldUpdate(args, dir, dep, has, deps[dep], cb) + }, cb) + } +} + +function shouldUpdate (args, dir, dep, has, req, cb) { + // look up the most recent version. + // if that's what we already have, or if it's not on the args list, + // then dive into it. Otherwise, cb() with the data. + + function skip () { + outdated_( args + , path.resolve(dir, "node_modules", dep) + , has + , cb ) + } + + function doIt (shouldHave) { + cb(null, [[ dir, dep, has[dep], shouldHave ]]) + } + + if (args.length && args.indexOf(dep) === -1) { + return skip() + } + + // so, we can conceivably update this. find out if we need to. + cache.add(dep, req, function (er, d) { + // if this fails, then it means we can't update this thing. + // it's probably a thing that isn't published. + return (er || d.version === has[dep]) ? skip() : doIt(d.version) + }) +} diff --git a/node-v0.8.14/deps/npm/lib/owner.js b/node-v0.8.14/deps/npm/lib/owner.js new file mode 100644 index 0000000..fdf4559 --- /dev/null +++ b/node-v0.8.14/deps/npm/lib/owner.js @@ -0,0 +1,205 @@ + +module.exports = owner + +owner.usage = "npm owner add " + + "\nnpm owner rm " + + "\nnpm owner ls " + +owner.completion = function (opts, cb) { + var argv = opts.conf.argv.remain + if (argv.length > 4) return cb() + if (argv.length <= 2) { + var subs = ["add", "rm"] + if (opts.partialWord === "l") subs.push("ls") + else subs.push("ls", "list") + return cb(null, subs) + } + var un = encodeURIComponent(npm.config.get("username")) + switch (argv[2]) { + case "ls": + if (argv.length > 3) return cb() + else return registry.get("/-/short", cb) + + case "rm": + if (argv.length > 3) { + var theUser = encodeURIComponent(argv[3]) + , uri = "/-/by-user/"+theUser+"|"+un + console.error(uri) + return registry.get(uri, function (er, d) { + if (er) return cb(er) + // return the intersection + return cb(null, d[theUser].filter(function (p) { + // kludge for server adminery. + return un === "isaacs" || d[un].indexOf(p) === -1 + })) + }) + } + // else fallthrough + case "add": + if (argv.length > 3) { + var theUser = encodeURIComponent(argv[3]) + , uri = "/-/by-user/"+theUser+"|"+un + console.error(uri) + return registry.get(uri, function (er, d) { + console.error(uri, er || d) + // return mine that they're not already on. + if (er) return cb(er) + var mine = d[un] || [] + , theirs = d[theUser] || [] + return cb(null, mine.filter(function (p) { + return theirs.indexOf(p) === -1 + })) + }) + } + // just list all users who aren't me. + return registry.get("/-/users", function (er, list) { + if (er) return cb() + return cb(null, Object.keys(list).filter(function (n) { + return n !== un + })) + }) + + default: + return cb() + } +} + +var npm = require("./npm.js") + , registry = npm.registry + , log = require("npmlog") + , readJson = require("read-package-json") + +function owner (args, cb) { + var action = args.shift() + switch (action) { + case "ls": case "list": return ls(args[0], cb) + case "add": return add(args[0], args[1], cb) + case "rm": case "remove": return rm(args[0], args[1], cb) + default: return unknown(action, cb) + } +} + +function ls (pkg, cb) { + if (!pkg) return readLocalPkg(function (er, pkg) { + if (er) return cb(er) + if (!pkg) return cb(owner.usage) + ls(pkg, cb) + }) + + registry.get(pkg, function (er, data) { + var msg = "" + if (er) { + log.error("owner ls", "Couldn't get owner data", pkg) + return cb(er) + } + var owners = data.maintainers + if (!owners || !owners.length) msg = "admin party!" + else msg = owners.map(function (o) { return o.name +" <"+o.email+">" }).join("\n") + console.log(msg) + cb(er, owners) + }) +} + +function add (user, pkg, cb) { + if (!user) return cb(owner.usage) + if (!pkg) return readLocalPkg(function (er, pkg) { + if (er) return cb(er) + if (!pkg) return cb(new Error(owner.usage)) + add(user, pkg, cb) + }) + + log.verbose("owner add", "%s to %s", user, pkg) + mutate(pkg, user, function (u, owners) { + if (!owners) owners = [] + for (var i = 0, l = owners.length; i < l; i ++) { + var o = owners[i] + if (o.name === u.name) { + log.info( "owner add" + , "Already a package owner: "+o.name+" <"+o.email+">") + return false + } + } + owners.push(u) + return owners + }, cb) +} + +function rm (user, pkg, cb) { + if (!pkg) return readLocalPkg(function (er, pkg) { + if (er) return cb(er) + if (!pkg) return cb(new Error(owner.usage)) + rm(user, pkg, cb) + }) + + log.verbose("owner rm", "%s from %s", user, pkg) + mutate(pkg, null, function (u, owners) { + var found = false + , m = owners.filter(function (o) { + var match = (o.name === user) + found = found || match + return !match + }) + if (!found) { + log.info("owner rm", "Not a package owner: "+user) + return false + } + if (!m.length) return new Error( + "Cannot remove all owners of a package. Add someone else first.") + return m + }, cb) +} + +function mutate (pkg, user, mutation, cb) { + if (user) { + registry.get("/-/user/org.couchdb.user:"+user, mutate_) + } else { + mutate_(null, null) + } + + function mutate_ (er, u) { + if (!er && user && (!u || u.error)) er = new Error( + "Couldn't get user data for "+user+": "+JSON.stringify(u)) + + if (er) { + log.error("owner mutate", "Error getting user data for %s", user) + return cb(er) + } + + if (u) u = { "name" : u.name, "email" : u.email } + registry.get(pkg, function (er, data) { + if (er) { + log.error("owner mutate", "Error getting package data for %s", pkg) + return cb(er) + } + var m = mutation(u, data.maintainers) + if (!m) return cb() // handled + if (m instanceof Error) return cb(m) // error + data = { _id : data._id + , _rev : data._rev + , maintainers : m + } + registry.request("PUT" + , pkg+"/-rev/"+data._rev, data + , function (er, data) { + if (!er && data.error) er = new Error( + "Failed to update package metadata: "+JSON.stringify(data)) + if (er) { + log.error("owner mutate", "Failed to update package metadata") + } + cb(er, data) + }) + }) + } +} + +function readLocalPkg (cb) { + if (npm.config.get("global")) return cb() + var path = require("path") + readJson(path.resolve(npm.prefix, "package.json"), function (er, d) { + return cb(er, d && d.name) + }) +} + +function unknown (action, cb) { + cb("Usage: \n"+owner.usage) +} diff --git a/node-v0.8.14/deps/npm/lib/pack.js b/node-v0.8.14/deps/npm/lib/pack.js new file mode 100644 index 0000000..302aa81 --- /dev/null +++ b/node-v0.8.14/deps/npm/lib/pack.js @@ -0,0 +1,65 @@ +// npm pack +// Packs the specified package into a .tgz file, which can then +// be installed. + +module.exports = pack + +var npm = require("./npm.js") + , install = require("./install.js") + , cache = require("./cache.js") + , fs = require("graceful-fs") + , chain = require("slide").chain + , path = require("path") + , cwd = process.cwd() + +pack.usage = "npm pack " + +// if it can be installed, it can be packed. +pack.completion = install.completion + +function pack (args, silent, cb) { + if (typeof cb !== "function") cb = silent, silent = false + + if (args.length === 0) args = ["."] + + chain(args.map(function (arg) { return function (cb) { + pack_(arg, cb) + }}), function (er, files) { + if (er || silent) return cb(er, files) + printFiles(files, cb) + }) +} + +function printFiles (files, cb) { + files = files.map(function (file) { + return path.relative(cwd, file) + }) + console.log(files.join("\n")) + cb() +} + +// add to cache, then cp to the cwd +function pack_ (pkg, cb) { + cache.add(pkg, function (er, data) { + if (er) return cb(er) + var fname = path.resolve(data._id.replace(/@/g, "-") + ".tgz") + , cached = path.resolve( npm.cache + , data.name + , data.version + , "package.tgz" ) + , from = fs.createReadStream(cached) + , to = fs.createWriteStream(fname) + , errState = null + + from.on("error", cb_) + to.on("error", cb_) + to.on("close", cb_) + from.pipe(to) + + function cb_ (er) { + if (errState) return + if (er) return cb(errState = er) + cb(null, fname) + } + }) +} diff --git a/node-v0.8.14/deps/npm/lib/prefix.js b/node-v0.8.14/deps/npm/lib/prefix.js new file mode 100644 index 0000000..e002ede --- /dev/null +++ b/node-v0.8.14/deps/npm/lib/prefix.js @@ -0,0 +1,11 @@ +module.exports = prefix + +var npm = require("./npm.js") + +prefix.usage = "npm prefix\nnpm prefix -g\n(just prints the prefix folder)" + +function prefix (args, silent, cb) { + if (typeof cb !== "function") cb = silent, silent = false + if (!silent) console.log(npm.prefix) + process.nextTick(cb.bind(this, null, npm.prefix)) +} diff --git a/node-v0.8.14/deps/npm/lib/prune.js b/node-v0.8.14/deps/npm/lib/prune.js new file mode 100644 index 0000000..2afb2b9 --- /dev/null +++ b/node-v0.8.14/deps/npm/lib/prune.js @@ -0,0 +1,40 @@ +// prune extraneous packages. + +module.exports = prune + +prune.usage = "npm prune" + +var readInstalled = require("read-installed") + , npm = require("./npm.js") + +prune.completion = require("./utils/completion/installed-deep.js") + +function prune (args, cb) { + readInstalled(npm.prefix, npm.config.get("depth"), function (er, data) { + if (er) return cb(er) + prune_(args, data, cb) + }) +} + +function prune_ (args, data, cb) { + npm.commands.unbuild(prunables(args, data, []), cb) +} + +function prunables (args, data, seen) { + var deps = data.dependencies || {} + return Object.keys(deps).map(function (d) { + if (typeof deps[d] !== "object" + || seen.indexOf(deps[d]) !== -1) return null + seen.push(deps[d]) + if (deps[d].extraneous + && (args.length === 0 || args.indexOf(d) !== -1)) { + var extra = deps[d] + delete deps[d] + return extra.path + } + return prunables(args, deps[d], seen) + }).filter(function (d) { return d !== null }) + .reduce(function FLAT (l, r) { + return l.concat(Array.isArray(r) ? r.reduce(FLAT,[]) : r) + }, []) +} diff --git a/node-v0.8.14/deps/npm/lib/publish.js b/node-v0.8.14/deps/npm/lib/publish.js new file mode 100644 index 0000000..bb6a4ce --- /dev/null +++ b/node-v0.8.14/deps/npm/lib/publish.js @@ -0,0 +1,101 @@ + +module.exports = publish + +var npm = require("./npm.js") + , log = require("npmlog") + , tar = require("./utils/tar.js") + , path = require("path") + , readJson = require("read-package-json") + , fs = require("graceful-fs") + , lifecycle = require("./utils/lifecycle.js") + , chain = require("slide").chain + , Conf = require("npmconf").Conf + , RegClient = require("npm-registry-client") + +publish.usage = "npm publish " + + "\nnpm publish " + + "\n\nPublishes '.' if no argument supplied" + +publish.completion = function (opts, cb) { + // publish can complete to a folder with a package.json + // or a tarball, or a tarball url. + // for now, not yet implemented. + return cb() +} + +function publish (args, isRetry, cb) { + if (typeof cb !== "function") cb = isRetry, isRetry = false + if (args.length === 0) args = ["."] + if (args.length !== 1) return cb(publish.usage) + + log.verbose("publish", args) + var arg = args[0] + // if it's a local folder, then run the prepublish there, first. + readJson(path.resolve(arg, "package.json"), function (er, data) { + // error is ok. could be publishing a url or tarball + // however, that means that we will not have automatically run + // the prepublish script, since that gets run when adding a folder + // to the cache. + if (er) return cacheAddPublish(arg, false, isRetry, cb) + cacheAddPublish(arg, true, isRetry, cb) + }) +} + +function cacheAddPublish (arg, didPre, isRetry, cb) { + npm.commands.cache.add(arg, function (er, data) { + if (er) return cb(er) + log.silly("publish", data) + var cachedir = path.resolve( npm.cache + , data.name + , data.version + , "package" ) + chain + ( [ !didPre && [lifecycle, data, "prepublish", cachedir] + , [publish_, arg, data, isRetry, cachedir] + , [lifecycle, data, "publish", cachedir] + , [lifecycle, data, "postpublish", cachedir] ] + , cb ) + }) +} + +function publish_ (arg, data, isRetry, cachedir, cb) { + if (!data) return cb(new Error("no package.json file found")) + + // check for publishConfig hash + var registry = npm.registry + if (data.publishConfig) { + var pubConf = new Conf(npm.config) + + // don't modify the actual publishConfig object, in case we have + // to set a login token or some other data. + pubConf.unshift(Object.keys(data.publishConfig).reduce(function (s, k) { + s[k] = data.publishConfig[k] + return s + }, {})) + registry = new RegClient(pubConf) + } + + data._npmVersion = npm.version + data._npmUser = { name: npm.config.get("username") + , email: npm.config.get("email") } + + delete data.modules + if (data.private) return cb(new Error + ("This package has been marked as private\n" + +"Remove the 'private' field from the package.json to publish it.")) + + var tarball = cachedir + ".tgz" + registry.publish(data, tarball, function (er) { + if (er && er.code === "EPUBLISHCONFLICT" + && npm.config.get("force") && !isRetry) { + log.warn("publish", "Forced publish over "+data._id) + return npm.commands.unpublish([data._id], function (er) { + // ignore errors. Use the force. Reach out with your feelings. + publish([arg], true, cb) + }) + } + if (er) return cb(er) + console.log("+ " + data._id) + cb() + }) +} diff --git a/node-v0.8.14/deps/npm/lib/rebuild.js b/node-v0.8.14/deps/npm/lib/rebuild.js new file mode 100644 index 0000000..16451fb --- /dev/null +++ b/node-v0.8.14/deps/npm/lib/rebuild.js @@ -0,0 +1,95 @@ + +module.exports = rebuild + +var readInstalled = require("read-installed") + , semver = require("semver") + , log = require("npmlog") + , path = require("path") + , npm = require("./npm.js") + , asyncMap = require("slide").asyncMap + , fs = require("graceful-fs") + , exec = require("./utils/exec.js") + +rebuild.usage = "npm rebuild [[@] [name[@] ...]]" + +rebuild.completion = require("./utils/completion/installed-deep.js") + +function rebuild (args, cb) { + readInstalled(npm.prefix, npm.config.get("depth"), function (er, data) { + log.info("readInstalled", typeof data) + if (er) return cb(er) + var set = filter(data, args) + , folders = Object.keys(set).filter(function (f) { + return f !== npm.prefix + }) + if (!folders.length) return cb() + log.silly("rebuild set", folders) + cleanBuild(folders, set, cb) + }) +} + +function cleanBuild (folders, set, cb) { + // https://github.com/isaacs/npm/issues/1872 + // If there's a wscript, try 'node-waf clean' + // But don't die on either of those if they fail. + // Just a best-effort kind of deal. + asyncMap(folders, function (f, cb) { + fs.readdir(f, function (er, files) { + // everything should be a dir. + if (er) return cb(er) + if (files.indexOf("wscript") !== -1) { + exec("node-waf", ["clean"], null, false, f, thenBuild) + } else thenBuild() + }) + function thenBuild (er) { + // ignore error, just continue + // it could be that it's not configured yet or whatever. + cb() + } + }, function (er) { + if (er) return cb(er) + npm.commands.build(folders, function (er) { + if (er) return cb(er) + console.log(folders.map(function (f) { + return set[f] + " " + f + }).join("\n")) + cb() + }) + }) +} + +function filter (data, args, set, seen) { + if (!set) set = {} + if (!seen) seen = {} + if (set.hasOwnProperty(data.path)) return set + if (seen.hasOwnProperty(data.path)) return set + seen[data.path] = true + var pass + if (!args.length) pass = true // rebuild everything + else if (data.name && data._id) { + for (var i = 0, l = args.length; i < l; i ++) { + var arg = args[i] + , nv = arg.split("@") + , n = nv.shift() + , v = nv.join("@") + if (n !== data.name) continue + if (!semver.satisfies(data.version, v)) continue + pass = true + break + } + } + if (pass && data._id) { + log.verbose("rebuild", "path, id", [data.path, data._id]) + set[data.path] = data._id + } + // need to also dive through kids, always. + // since this isn't an install these won't get auto-built unless + // they're not dependencies. + Object.keys(data.dependencies || {}).forEach(function (d) { + // return + var dep = data.dependencies[d] + if (typeof dep === "string") return + filter(dep, args, set, seen) + }) + return set +} diff --git a/node-v0.8.14/deps/npm/lib/restart.js b/node-v0.8.14/deps/npm/lib/restart.js new file mode 100644 index 0000000..69c4b91 --- /dev/null +++ b/node-v0.8.14/deps/npm/lib/restart.js @@ -0,0 +1 @@ +module.exports = require("./utils/lifecycle.js").cmd("restart") diff --git a/node-v0.8.14/deps/npm/lib/root.js b/node-v0.8.14/deps/npm/lib/root.js new file mode 100644 index 0000000..b2f731e --- /dev/null +++ b/node-v0.8.14/deps/npm/lib/root.js @@ -0,0 +1,11 @@ +module.exports = root + +var npm = require("./npm.js") + +root.usage = "npm root\nnpm root -g\n(just prints the root folder)" + +function root (args, silent, cb) { + if (typeof cb !== "function") cb = silent, silent = false + if (!silent) console.log(npm.dir) + process.nextTick(cb.bind(this, null, npm.dir)) +} diff --git a/node-v0.8.14/deps/npm/lib/run-script.js b/node-v0.8.14/deps/npm/lib/run-script.js new file mode 100644 index 0000000..3291ae5 --- /dev/null +++ b/node-v0.8.14/deps/npm/lib/run-script.js @@ -0,0 +1,98 @@ + +module.exports = runScript + +var lifecycle = require("./utils/lifecycle.js") + , npm = require("./npm.js") + , path = require("path") + , readJson = require("read-package-json") + , log = require("npmlog") + , chain = require("slide").chain + , fs = require("graceful-fs") + , asyncMap = require("slide").asyncMap + +runScript.usage = "npm run-script [] " + +runScript.completion = function (opts, cb) { + + // see if there's already a package specified. + var argv = opts.conf.argv.remain + , installedShallow = require("./utils/completion/installed-shallow.js") + + if (argv.length >= 4) return cb() + + if (argv.length === 3) { + // either specified a script locally, in which case, done, + // or a package, in which case, complete against its scripts + var json = path.join(npm.prefix, "package.json") + return readJson(json, function (er, d) { + if (er) d = {} + var scripts = Object.keys(d.scripts || {}) + console.error("local scripts", scripts) + if (scripts.indexOf(argv[2]) !== -1) return cb() + // ok, try to find out which package it was, then + var pref = npm.config.get("global") ? npm.config.get("prefix") + : npm.prefix + var pkgDir = path.resolve( pref, "node_modules" + , argv[2], "package.json" ) + readJson(pkgDir, function (er, d) { + if (er) d = {} + var scripts = Object.keys(d.scripts || {}) + return cb(null, scripts) + }) + }) + } + + // complete against the installed-shallow, and the pwd's scripts. + // but only packages that have scripts + var installed + , scripts + installedShallow(opts, function (d) { + return d.scripts + }, function (er, inst) { + installed = inst + next() + }) + + if (npm.config.get("global")) scripts = [], next() + else readJson(path.join(npm.prefix, "package.json"), function (er, d) { + d = d || {} + scripts = Object.keys(d.scripts || {}) + next() + }) + + function next () { + if (!installed || !scripts) return + return cb(null, scripts.concat(installed)) + } +} + +function runScript (args, cb) { + var pkgdir = args.length === 1 ? process.cwd() + : path.resolve(npm.dir, args[0]) + , cmd = args.pop() + + readJson(path.resolve(pkgdir, "package.json"), function (er, d) { + if (er) return cb(er) + run(d, pkgdir, cmd, cb) + }) +} + +function run (pkg, wd, cmd, cb) { + var cmds = [] + if (!pkg.scripts) pkg.scripts = {} + if (cmd === "restart") { + cmds = ["prestop","stop","poststop" + ,"restart" + ,"prestart","start","poststart"] + } else { + cmds = [cmd] + } + if (!cmd.match(/^(pre|post)/)) { + cmds = ["pre"+cmd].concat(cmds).concat("post"+cmd) + } + log.verbose("run-script", cmds) + chain(cmds.map(function (c) { + // when running scripts explicitly, assume that they're trusted. + return [lifecycle, pkg, c, wd, true] + }), cb) +} diff --git a/node-v0.8.14/deps/npm/lib/search.js b/node-v0.8.14/deps/npm/lib/search.js new file mode 100644 index 0000000..3e9bdb1 --- /dev/null +++ b/node-v0.8.14/deps/npm/lib/search.js @@ -0,0 +1,261 @@ + +module.exports = exports = search + +var npm = require("./npm.js") + , registry = npm.registry + , semver = require("semver") + +search.usage = "npm search [some search terms ...]" + +search.completion = function (opts, cb) { + var compl = {} + , partial = opts.partialWord + , ipartial = partial.toLowerCase() + , plen = partial.length + + // get the batch of data that matches so far. + // this is an example of using npm.commands.search programmatically + // to fetch data that has been filtered by a set of arguments. + search(opts.conf.argv.remain.slice(2), true, function (er, data) { + if (er) return cb(er) + Object.keys(data).forEach(function (name) { + data[name].words.split(" ").forEach(function (w) { + if (w.toLowerCase().indexOf(ipartial) === 0) { + compl[partial + w.substr(plen)] = true + } + }) + }) + cb(null, Object.keys(compl)) + }) +} + +function search (args, silent, staleness, cb) { + if (typeof cb !== "function") cb = staleness, staleness = 600 + if (typeof cb !== "function") cb = silent, silent = false + + var searchopts = npm.config.get("searchopts") + , searchexclude = npm.config.get("searchexclude") + if (typeof searchopts !== "string") searchopts = "" + searchopts = searchopts.split(/\s+/) + if (typeof searchexclude === "string") { + searchexclude = searchexclude.split(/\s+/) + } else searchexclude = [] + var opts = searchopts.concat(args).map(function (s) { + return s.toLowerCase() + }).filter(function (s) { return s }) + searchexclude = searchexclude.map(function (s) { + return s.toLowerCase() + }) + getFilteredData( staleness, opts, searchexclude, function (er, data) { + // now data is the list of data that we want to show. + // prettify and print it, and then provide the raw + // data to the cb. + if (er || silent) return cb(er, data) + console.log(prettify(data, args)) + cb(null, data) + }) +} + +function getFilteredData (staleness, args, notArgs, cb) { + registry.get( "/-/all", staleness, false + , true, function (er, data) { + if (er) return cb(er) + return cb(null, filter(data, args, notArgs)) + }) +} + +function filter (data, args, notArgs) { + // data={:{package data}} + return Object.keys(data).map(function (d) { + return data[d] + }).filter(function (d) { + return typeof d === "object" + }).map(stripData).map(getWords).filter(function (data) { + return filterWords(data, args, notArgs) + }).reduce(function (l, r) { + l[r.name] = r + return l + }, {}) +} + +function stripData (data) { + return { name: data.name + , description: npm.config.get("description") ? data.description : "" + , maintainers: (data.maintainers || []).map(function (m) { + return "=" + m.name + }) + , url: !Object.keys(data.versions || {}).length ? data.url : null + , keywords: data.keywords || [] + , time: data.time + && data.time.modified + && (new Date(data.time.modified).toISOString() + .split("T").join(" ") + .replace(/:[0-9]{2}\.[0-9]{3}Z$/, "")) + || "(prehistoric)" + } +} + +function getWords (data) { + data.words = [ data.name ] + .concat(data.description) + .concat(data.maintainers) + .concat(data.url && ("<" + data.url + ">")) + .concat(data.keywords) + .map(function (f) { return f && f.trim && f.trim() }) + .filter(function (f) { return f }) + .join(" ") + .toLowerCase() + return data +} + +function filterWords (data, args, notArgs) { + var words = data.words + for (var i = 0, l = args.length; i < l; i ++) { + if (!match(words, args[i])) return false + } + for (var i = 0, l = notArgs.length; i < l; i ++) { + if (match(words, notArgs[i])) return false + } + return true +} + +function match (words, arg) { + if (arg.charAt(0) === "/") { + arg = arg.replace(/\/$/, "") + arg = new RegExp(arg.substr(1, arg.length - 1)) + return words.match(arg) + } + return words.indexOf(arg) !== -1 +} + +function prettify (data, args) { + try { + var tty = require("tty") + , stdout = process.stdout + , cols = !tty.isatty(stdout.fd) ? Infinity + : stdout._handle ? stdout._handle.getWindowSize()[0] + : process.stdout.getWindowSize()[0] + cols = (cols == 0) ? Infinity : cols + } catch (ex) { cols = Infinity } + + // name, desc, author, keywords + var longest = [] + , spaces + , maxLen = npm.config.get("description") + ? [20, 60, 20, 20, Infinity] + : [20, 20, 20, Infinity] + , headings = npm.config.get("description") + ? ["NAME", "DESCRIPTION", "AUTHOR", "DATE", "KEYWORDS"] + : ["NAME", "AUTHOR", "DATE", "KEYWORDS"] + , lines + , searchsort = (npm.config.get("searchsort") || "NAME").toLowerCase() + , sortFields = { name: 0 + , description: 1 + , author: 2 + , date: 3 + , keywords: 4 } + , searchRev = searchsort.charAt(0) === "-" + , sortField = sortFields[searchsort.replace(/^\-+/, "")] + + lines = Object.keys(data).map(function (d) { + return data[d] + }).map(function (data) { + // turn a pkg data into a string + // [name,who,desc,targets,keywords] tuple + // also set longest to the longest name + if (typeof data.keywords === "string") { + data.keywords = data.keywords.split(/[,\s]+/) + } + if (!Array.isArray(data.keywords)) data.keywords = [] + var l = [ data.name + , data.description || "" + , data.maintainers.join(" ") + , data.time + , (data.keywords || []).join(" ") + ] + l.forEach(function (s, i) { + var len = s.length + longest[i] = Math.min(maxLen[i] || Infinity + ,Math.max(longest[i] || 0, len)) + if (len > longest[i]) { + l._undent = l._undent || [] + l._undent[i] = len - longest[i] + } + l[i] = ('' + l[i]).replace(/\s+/g, " ") + }) + return l + }).sort(function (a, b) { + // a and b are "line" objects of [name, desc, maint, time, kw] + var aa = a[sortField].toLowerCase() + , bb = b[sortField].toLowerCase() + return aa === bb ? 0 + : aa < bb ? (searchRev ? 1 : -1) + : (searchRev ? -1 : 1) + }).map(function (line) { + return line.map(function (s, i) { + spaces = spaces || longest.map(function (n) { + return new Array(n + 2).join(" ") + }) + var len = s.length + if (line._undent && line._undent[i - 1]) { + len += line._undent[i - 1] - 1 + } + return s + spaces[i].substr(len) + }).join(" ").substr(0, cols).trim() + }).map(function (line) { + // colorize! + args.forEach(function (arg, i) { + line = addColorMarker(line, arg, i) + }) + return colorize(line).trim() + }) + + if (lines.length === 0) { + return "No match found for "+(args.map(JSON.stringify).join(" ")) + } + + // build the heading padded to the longest in each field + return headings.map(function (h, i) { + var space = Math.max(2, 3 + (longest[i] || 0) - h.length) + return h + (new Array(space).join(" ")) + }).join("").substr(0, cols).trim() + "\n" + lines.join("\n") + +} + +var colors = [31, 33, 32, 36, 34, 35 ] + , cl = colors.length +function addColorMarker (str, arg, i) { + var m = i % cl + 1 + , markStart = String.fromCharCode(m) + , markEnd = String.fromCharCode(0) + + if (arg.charAt(0) === "/") { + //arg = arg.replace(/\/$/, "") + return str.replace( new RegExp(arg.substr(1, arg.length - 1), "gi") + , function (bit) { return markStart + bit + markEnd } ) + + } + + // just a normal string, do the split/map thing + var pieces = str.toLowerCase().split(arg.toLowerCase()) + , p = 0 + + return pieces.map(function (piece, i) { + piece = str.substr(p, piece.length) + var mark = markStart + + str.substr(p+piece.length, arg.length) + + markEnd + p += piece.length + arg.length + return piece + mark + }).join("") +} + +function colorize (line) { + for (var i = 0; i < cl; i ++) { + var m = i + 1 + var color = npm.color ? "\033["+colors[i]+"m" : "" + line = line.split(String.fromCharCode(m)).join(color) + } + var uncolor = npm.color ? "\033[0m" : "" + return line.split("\u0000").join(uncolor) +} diff --git a/node-v0.8.14/deps/npm/lib/set.js b/node-v0.8.14/deps/npm/lib/set.js new file mode 100644 index 0000000..c83602e --- /dev/null +++ b/node-v0.8.14/deps/npm/lib/set.js @@ -0,0 +1,13 @@ + +module.exports = set + +set.usage = "npm set (See `npm config`)" + +var npm = require("./npm.js") + +set.completion = npm.commands.config.completion + +function set (args, cb) { + if (!args.length) return cb(set.usage) + npm.commands.config(["set"].concat(args), cb) +} diff --git a/node-v0.8.14/deps/npm/lib/shrinkwrap.js b/node-v0.8.14/deps/npm/lib/shrinkwrap.js new file mode 100644 index 0000000..e41f8cf --- /dev/null +++ b/node-v0.8.14/deps/npm/lib/shrinkwrap.js @@ -0,0 +1,47 @@ +// emit JSON describing versions of all packages currently installed (for later +// use with shrinkwrap install) + +module.exports = exports = shrinkwrap + +var npm = require("./npm.js") + , log = require("npmlog") + , fs = require("fs") + , path = require("path") + +shrinkwrap.usage = "npm shrinkwrap" + +function shrinkwrap (args, silent, cb) { + if (typeof cb !== "function") cb = silent, silent = false + + if (args.length) { + log.warn("shrinkwrap", "doesn't take positional args") + } + + npm.commands.ls([], true, function (er, _, pkginfo) { + if (er) return cb(er) + shrinkwrap_(pkginfo, silent, cb) + }) +} + +function shrinkwrap_ (pkginfo, silent, cb) { + if (pkginfo.problems) { + return cb(new Error("Problems were encountered\n" + +"Please correct and try again.\n" + +pkginfo.problems.join("\n"))) + } + try { + var swdata = JSON.stringify(pkginfo, null, 2) + "\n" + } catch (er) { + log.error("shrinkwrap", "Error converting package info to json") + return cb(er) + } + + var file = path.resolve(npm.prefix, "npm-shrinkwrap.json") + + fs.writeFile(file, swdata, function (er) { + if (er) return cb(er) + if (silent) return cb(null, pkginfo) + console.log("wrote npm-shrinkwrap.json") + cb(null, pkginfo) + }) +} diff --git a/node-v0.8.14/deps/npm/lib/star.js b/node-v0.8.14/deps/npm/lib/star.js new file mode 100644 index 0000000..33b1247 --- /dev/null +++ b/node-v0.8.14/deps/npm/lib/star.js @@ -0,0 +1,33 @@ + +module.exports = star + +var npm = require("./npm.js") + , registry = npm.registry + , log = require("npmlog") + , asyncMap = require("slide").asyncMap + +star.usage = "npm star [pkg, pkg, ...]\n" + + "npm unstar [pkg, pkg, ...]" + +star.completion = function (opts, cb) { + registry.get("/-/short", 60000, function (er, list) { + return cb(null, list || []) + }) +} + +function star (args, cb) { + if (!args.length) return cb(star.usage) + var s = npm.config.get("unicode") ? "\u2605 " : "(*)" + , u = npm.config.get("unicode") ? "\u2606 " : "( )" + , using = !(npm.command.match(/^un/)) + if (!using) s = u + asyncMap(args, function (pkg, cb) { + registry.star(pkg, using, function (er, data, raw, req) { + if (!er) { + console.log(s + " "+pkg) + log.verbose("star", data) + } + cb(er, data, raw, req) + }) + }, cb) +} diff --git a/node-v0.8.14/deps/npm/lib/start.js b/node-v0.8.14/deps/npm/lib/start.js new file mode 100644 index 0000000..9882382 --- /dev/null +++ b/node-v0.8.14/deps/npm/lib/start.js @@ -0,0 +1 @@ +module.exports = require("./utils/lifecycle.js").cmd("start") diff --git a/node-v0.8.14/deps/npm/lib/stop.js b/node-v0.8.14/deps/npm/lib/stop.js new file mode 100644 index 0000000..8ea5ba6 --- /dev/null +++ b/node-v0.8.14/deps/npm/lib/stop.js @@ -0,0 +1 @@ +module.exports = require("./utils/lifecycle.js").cmd("stop") diff --git a/node-v0.8.14/deps/npm/lib/submodule.js b/node-v0.8.14/deps/npm/lib/submodule.js new file mode 100644 index 0000000..c152398 --- /dev/null +++ b/node-v0.8.14/deps/npm/lib/submodule.js @@ -0,0 +1,91 @@ +// npm submodule +// Check the package contents for a git repository url. +// If there is one, then create a git submodule in the node_modules folder. + +module.exports = submodule + +var npm = require("./npm.js") + , exec = require("./utils/exec.js") + , cache = require("./cache.js") + , asyncMap = require("slide").asyncMap + , chain = require("slide").chain + +submodule.usage = "npm submodule " + +submodule.completion = require("./docs.js").completion + +function submodule (args, cb) { + if (npm.config.get("global")) { + return cb(new Error("Cannot use submodule command in global mode.")) + } + + if (args.length === 0) return cb(submodule.usage) + + asyncMap(args, function (arg, cb) { + cache.add(arg, cb) + }, function (er, pkgs) { + if (er) return cb(er) + chain(pkgs.map(function (pkg) { return function (cb) { + submodule_(pkg, cb) + }}), cb) + }) + +} + +function submodule_ (pkg, cb) { + if (!pkg.repository + || pkg.repository.type !== "git" + || !pkg.repository.url) { + return cb(new Error(pkg._id + ": No git repository listed")) + } + + // prefer https:// github urls + pkg.repository.url = pkg.repository.url + .replace(/^(git:\/\/)?(git@)?github.com[:\/]/, "https://github.com/") + + // first get the list of submodules, and update if it's already there. + getSubmodules(function (er, modules) { + if (er) return cb(er) + // if there's already a submodule, then just update it. + if (modules.indexOf(pkg.name) !== -1) { + return updateSubmodule(pkg.name, cb) + } + addSubmodule(pkg.name, pkg.repository.url, cb) + }) +} + +function updateSubmodule (name, cb) { + exec( npm.config.get("git"), [ "submodule", "update", "--init" + , "node_modules/" + name ] + , null, true, npm.prefix, cb) +} + +function addSubmodule (name, url, cb) { + exec( npm.config.get("git"), [ "submodule", "add", url + , "node_modules/" + name ] + , null, true, npm.prefix, function (er) { + if (er) return cb(er) + updateSubmodule(name, cb) + }) +} + + +var getSubmodules = function getSubmodules (cb) { + exec( npm.config.get("git"), ["submodule", "status"], null, false + , npm.prefix, function (er, code, stdout, stderr) { + if (er) return cb(er) + res = stdout.trim().split(/\n/).map(function (line) { + return line.trim().split(/\s+/)[1] + }).filter(function (line) { + // only care about submodules in the node_modules folder. + return line && line.match(/^node_modules\//) + }).map(function (line) { + return line.replace(/^node_modules\//g, "") + }) + + // memoize. + getSubmodules = function (cb) { return cb(null, res) } + + cb(null, res) + }) +} diff --git a/node-v0.8.14/deps/npm/lib/substack.js b/node-v0.8.14/deps/npm/lib/substack.js new file mode 100644 index 0000000..1929f18 --- /dev/null +++ b/node-v0.8.14/deps/npm/lib/substack.js @@ -0,0 +1,20 @@ +module.exports = substack +var npm = require("./npm.js") + +var isms = + [ "\033[32mbeep \033[35mboop\033[m" + , "Replace your configs with services" + , "SEPARATE ALL THE CONCERNS!" + , "MODULE ALL THE THINGS!" + , "\\o/" + , "but first, burritos" + , "full time mad scientist here" + , "c/,,\\" ] + +function substack (args, cb) { + var i = Math.floor(Math.random() * isms.length) + console.log(isms[i]) + var c = args.shift() + if (c) npm.commands[c](args, cb) + else cb() +} diff --git a/node-v0.8.14/deps/npm/lib/tag.js b/node-v0.8.14/deps/npm/lib/tag.js new file mode 100644 index 0000000..8a7c51c --- /dev/null +++ b/node-v0.8.14/deps/npm/lib/tag.js @@ -0,0 +1,18 @@ +// turns out tagging isn't very complicated +// all the smarts are in the couch. +module.exports = tag +tag.usage = "npm tag @ []" + +tag.completion = require("./unpublish.js").completion + +var npm = require("./npm.js") + , registry = npm.registry + +function tag (args, cb) { + var thing = (args.shift() || "").split("@") + , project = thing.shift() + , version = thing.join("@") + , t = args.shift() || npm.config.get("tag") + if (!project || !version || !t) return cb("Usage:\n"+tag.usage) + registry.tag(project, version, t, cb) +} diff --git a/node-v0.8.14/deps/npm/lib/test.js b/node-v0.8.14/deps/npm/lib/test.js new file mode 100644 index 0000000..d741807 --- /dev/null +++ b/node-v0.8.14/deps/npm/lib/test.js @@ -0,0 +1,14 @@ +module.exports = test + +var testCmd = require("./utils/lifecycle.js").cmd("test") + , log = require("npmlog") + +function test (args, cb) { + testCmd(args, function (er) { + if (!er) return cb() + if (er.code === "ELIFECYCLE") { + return cb("Test failed. See above for more details.") + } + return cb(er) + }) +} diff --git a/node-v0.8.14/deps/npm/lib/unbuild.js b/node-v0.8.14/deps/npm/lib/unbuild.js new file mode 100644 index 0000000..1cbf054 --- /dev/null +++ b/node-v0.8.14/deps/npm/lib/unbuild.js @@ -0,0 +1,94 @@ +module.exports = unbuild +unbuild.usage = "npm unbuild \n(this is plumbing)" + +var readJson = require("read-package-json") + , rm = require("rimraf") + , gentlyRm = require("./utils/gently-rm.js") + , npm = require("./npm.js") + , path = require("path") + , fs = require("graceful-fs") + , lifecycle = require("./utils/lifecycle.js") + , asyncMap = require("slide").asyncMap + , chain = require("slide").chain + , log = require("npmlog") + , build = require("./build.js") + +// args is a list of folders. +// remove any bins/etc, and then delete the folder. +function unbuild (args, cb) { asyncMap(args, unbuild_, cb) } + +function unbuild_ (folder, cb) { + folder = path.resolve(folder) + delete build._didBuild[folder] + log.info(folder, "unbuild") + readJson(path.resolve(folder, "package.json"), function (er, pkg) { + // if no json, then just trash it, but no scripts or whatever. + if (er) return rm(folder, cb) + readJson.cache.del(folder) + chain + ( [ [lifecycle, pkg, "preuninstall", folder, false, true] + , [lifecycle, pkg, "uninstall", folder, false, true] + , [rmStuff, pkg, folder] + , [lifecycle, pkg, "postuninstall", folder, false, true] + , [rm, folder] ] + , cb ) + }) +} + +function rmStuff (pkg, folder, cb) { + // if it's global, and folder is in {prefix}/node_modules, + // then bins are in {prefix}/bin + // otherwise, then bins are in folder/../.bin + var parent = path.dirname(folder) + , gnm = npm.dir + , top = gnm === parent + + readJson.cache.del(path.resolve(folder, "package.json")) + + log.verbose([top, gnm, parent], "unbuild "+pkg._id) + asyncMap([rmBins, rmMans], function (fn, cb) { + fn(pkg, folder, parent, top, cb) + }, cb) +} + +function rmBins (pkg, folder, parent, top, cb) { + if (!pkg.bin) return cb() + var binRoot = top ? npm.bin : path.resolve(parent, ".bin") + log.verbose([binRoot, pkg.bin], "binRoot") + asyncMap(Object.keys(pkg.bin), function (b, cb) { + if (process.platform === "win32") { + chain([ [rm, path.resolve(binRoot, b) + ".cmd"] + , [rm, path.resolve(binRoot, b) ] ], cb) + } else { + gentlyRm( path.resolve(binRoot, b) + , !npm.config.get("force") && folder + , cb ) + } + }, cb) +} + +function rmMans (pkg, folder, parent, top, cb) { + if (!pkg.man + || !top + || process.platform === "win32" + || !npm.config.get("global")) { + return cb() + } + var manRoot = path.resolve(npm.config.get("prefix"), "share", "man") + asyncMap(pkg.man, function (man, cb) { + var parseMan = man.match(/(.*)\.([0-9]+)(\.gz)?$/) + , stem = parseMan[1] + , sxn = parseMan[2] + , gz = parseMan[3] || "" + , bn = path.basename(stem) + , manDest = path.join( manRoot + , "man"+sxn + , (bn.indexOf(pkg.name) === 0 ? bn + : pkg.name + "-" + bn) + + "." + sxn + gz + ) + gentlyRm( manDest + , !npm.config.get("force") && folder + , cb ) + }, cb) +} diff --git a/node-v0.8.14/deps/npm/lib/uninstall.js b/node-v0.8.14/deps/npm/lib/uninstall.js new file mode 100644 index 0000000..b4dbd1d --- /dev/null +++ b/node-v0.8.14/deps/npm/lib/uninstall.js @@ -0,0 +1,127 @@ + +// remove a package. + +module.exports = uninstall + +uninstall.usage = "npm uninstall [@ [[@] ...]" + + "\nnpm rm [@ [[@] ...]" + +uninstall.completion = require("./utils/completion/installed-shallow.js") + +var fs = require("graceful-fs") + , log = require("npmlog") + , readJson = require("read-package-json") + , path = require("path") + , npm = require("./npm.js") + , semver = require("semver") + , asyncMap = require("slide").asyncMap + +function uninstall (args, cb) { + // this is super easy + // get the list of args that correspond to package names in either + // the global npm.dir, + // then call unbuild on all those folders to pull out their bins + // and mans and whatnot, and then delete the folder. + + var nm = npm.dir + if (args.length === 1 && args[0] === ".") args = [] + if (args.length) return uninstall_(args, nm, cb) + + // remove this package from the global space, if it's installed there + if (npm.config.get("global")) return cb(uninstall.usage) + readJson(path.resolve(npm.prefix, "package.json"), function (er, pkg) { + if (er) return cb(uninstall.usage) + uninstall_( [pkg.name] + , npm.dir + , cb ) + }) + +} + +function uninstall_ (args, nm, cb) { + // if we've been asked to --save or --save-dev or --save-optional, + // then also remove it from the associated dependencies hash. + var s = npm.config.get('save') + , d = npm.config.get('save-dev') + , o = npm.config.get('save-optional') + if (s || d || o) { + cb = saver(args, nm, cb) + } + + asyncMap(args, function (arg, cb) { + // uninstall .. should not delete /usr/local/lib/node_modules/.. + var p = path.join(path.resolve(nm), path.join("/", arg)) + if (path.resolve(p) === nm) { + log.warn("uninstall", "invalid argument: %j", arg) + return cb(null, []) + } + fs.lstat(p, function (er) { + if (er) { + log.warn("uninstall", "not installed in %s: %j", nm, arg) + return cb(null, []) + } + cb(null, p) + }) + }, function (er, folders) { + if (er) return cb(er) + asyncMap(folders, npm.commands.unbuild, cb) + }) +} + +function saver (args, nm, cb_) { + return cb + function cb (er, data) { + var s = npm.config.get('save') + , d = npm.config.get('save-dev') + , o = npm.config.get('save-optional') + if (er || !(s || d || o)) return cb_(er, data) + var pj = path.resolve(nm, '..', 'package.json') + // don't use readJson here, because we don't want all the defaults + // filled in, for mans and other bs. + fs.readFile(pj, 'utf8', function (er, json) { + try { + var pkg = JSON.parse(json) + } catch (_) {} + if (!pkg) return cb_(null, data) + + var bundle + if (npm.config.get('save-bundle')) { + var bundle = pkg.bundleDependencies || pkg.bundledDependencies + if (!Array.isArray(bundle)) bundle = undefined + } + + var changed = false + args.forEach(function (a) { + ; [ [s, 'dependencies'] + , [o, 'optionalDependencies'] + , [d, 'devDependencies'] ].forEach(function (f) { + var flag = f[0] + , field = f[1] + if (!flag || !pkg[field] || !pkg[field].hasOwnProperty(a)) return + changed = true + + if (bundle) { + var i = bundle.indexOf(a) + if (i !== -1) bundle.splice(i, 1) + } + + delete pkg[field][a] + }) + }) + if (!changed) return cb_(null, data) + + if (bundle) { + delete pkg.bundledDependencies + if (bundle.length) { + pkg.bundleDependencies = bundle + } else { + delete pkg.bundleDependencies + } + } + + fs.writeFile(pj, JSON.stringify(pkg, null, 2) + "\n", function (er) { + return cb_(er, data) + }) + }) + } +} diff --git a/node-v0.8.14/deps/npm/lib/unpublish.js b/node-v0.8.14/deps/npm/lib/unpublish.js new file mode 100644 index 0000000..def3085 --- /dev/null +++ b/node-v0.8.14/deps/npm/lib/unpublish.js @@ -0,0 +1,82 @@ + +module.exports = unpublish + +var log = require("npmlog") + , npm = require("./npm.js") + , registry = npm.registry + , readJson = require("read-package-json") + , path = require("path") + +unpublish.usage = "npm unpublish [@]" + +unpublish.completion = function (opts, cb) { + if (opts.conf.argv.remain.length >= 3) return cb() + var un = encodeURIComponent(npm.config.get("username")) + if (!un) return cb() + registry.get("/-/by-user/"+un, function (er, pkgs) { + // do a bit of filtering at this point, so that we don't need + // to fetch versions for more than one thing, but also don't + // accidentally a whole project. + pkgs = pkgs[un] + if (!pkgs || !pkgs.length) return cb() + var partial = opts.partialWord.split("@") + , pp = partial.shift() + , pv = partial.join("@") + pkgs = pkgs.filter(function (p) { + return p.indexOf(pp) === 0 + }) + if (pkgs.length > 1) return cb(null, pkgs) + registry.get(pkgs[0], function (er, d) { + if (er) return cb(er) + var vers = Object.keys(d.versions) + if (!vers.length) return cb(null, pkgs) + return cb(null, vers.map(function (v) { + return pkgs[0]+"@"+v + })) + }) + }) +} + +function unpublish (args, cb) { + + if (args.length > 1) return cb(unpublish.usage) + + var thing = args.length ? args.shift().split("@") : [] + , project = thing.shift() + , version = thing.join("@") + + if (!version && !npm.config.get("force")) { + return cb("Refusing to delete entire project.\n" + +"Run with --force to do this.\n" + +unpublish.usage) + } + + if (!project || path.resolve(project) === npm.prefix) { + // if there's a package.json in the current folder, then + // read the package name and version out of that. + var cwdJson = path.join(process.cwd(), "package.json") + return readJson(cwdJson, function (er, data) { + if (er) return cb("Usage:\n"+unpublish.usage) + gotProject(data.name, data.version, cb) + }) + } + return gotProject(project, version, cb) +} + +function gotProject (project, version, cb_) { + function cb (er) { + if (er) return cb_(er) + console.log("- " + project + (version ? "@" + version : "")) + cb_() + } + + // remove from the cache first + npm.commands.cache(["clean", project, version], function (er) { + if (er) { + log.error("unpublish", "Failed to clean cache") + return cb(er) + } + + registry.unpublish(project, version, cb) + }) +} diff --git a/node-v0.8.14/deps/npm/lib/update.js b/node-v0.8.14/deps/npm/lib/update.js new file mode 100644 index 0000000..46d3267 --- /dev/null +++ b/node-v0.8.14/deps/npm/lib/update.js @@ -0,0 +1,39 @@ +/* +for each pkg in prefix that isn't a git repo + look for a new version of pkg that satisfies dep + if so, install it. + if not, then update it +*/ + +module.exports = update + +update.usage = "npm update [pkg]" + +var npm = require("./npm.js") + , lifecycle = require("./utils/lifecycle.js") + , asyncMap = require("slide").asyncMap + , log = require("npmlog") + + // load these, just so that we know that they'll be available, in case + // npm itself is getting overwritten. + , install = require("./install.js") + , build = require("./build.js") + +update.completion = npm.commands.outdated.completion + +function update (args, cb) { + npm.commands.outdated(args, true, function (er, outdated) { + log.info("outdated", "updating", outdated) + if (er) return cb(er) + + asyncMap(outdated, function (ww, cb) { + // [[ dir, dep, has, want ]] + var where = ww[0] + , dep = ww[1] + , want = ww[3] + , what = dep + "@" + want + + npm.commands.install(where, what, cb) + }, cb) + }) +} diff --git a/node-v0.8.14/deps/npm/lib/utils/cmd-shim.js b/node-v0.8.14/deps/npm/lib/utils/cmd-shim.js new file mode 100644 index 0000000..6fce0e0 --- /dev/null +++ b/node-v0.8.14/deps/npm/lib/utils/cmd-shim.js @@ -0,0 +1,154 @@ +// XXX Todo: +// On windows, create a .cmd file. +// Read the #! in the file to see what it uses. The vast majority +// of the time, this will be either: +// "#!/usr/bin/env " +// or: +// "#! " +// +// Write a binroot/pkg.bin + ".cmd" file that has this line in it: +// @ %~dp0 %* + +module.exports = cmdShim +cmdShim.ifExists = cmdShimIfExists + +var fs = require("graceful-fs") + , chain = require("slide").chain + , mkdir = require("mkdirp") + , rm = require("rimraf") + , log = require("npmlog") + , path = require("path") + , npm = require("../npm.js") + , shebangExpr = /^#\!\s*(?:\/usr\/bin\/env)?\s*([^ \t]+)(.*)$/ + +function cmdShimIfExists (from, to, cb) { + fs.stat(from, function (er) { + if (er) return cb() + cmdShim(from, to, cb) + }) +} + +function cmdShim (from, to, cb) { + if (process.platform !== "win32") { + return cb(new Error(".cmd shims only should be used on windows")) + } + + chain + ( [ [fs, "stat", from] + , [rm, to + ".cmd"] + , [rm, to] + , [mkdir, path.dirname(to)] + , [writeShim, from, to] ] + , cb ) +} + +function writeShim (from, to, cb) { + // make a cmd file and a sh script + // First, check if the bin is a #! of some sort. + // If not, then assume it's something that'll be compiled, or some other + // sort of script, and just call it directly. + fs.readFile(from, "utf8", function (er, data) { + if (er) return writeShim_(from, to, null, null, cb) + var firstLine = data.trim().split(/\r*\n/)[0] + , shebang = firstLine.match(shebangExpr) + if (!shebang) return writeShim_(from, to, null, null, cb) + var prog = shebang[1] + , args = shebang[2] || "" + return writeShim_(from, to, prog, args, cb) + }) +} + +function writeShim_ (from, to, prog, args, cb) { + var shTarget = path.relative(path.dirname(to), from) + , target = shTarget.split("/").join("\\") + , longProg + , shProg = prog && prog.split("\\").join("/") + , shLongProg + shTarget = shTarget.split("\\").join("/") + args = args || "" + if (!prog) { + prog = "\"%~dp0\\" + target + "\"" + shProg = "\"$basedir/" + shTarget + "\"" + args = "" + target = "" + shTarget = "" + } else { + longProg = "\"%~dp0\\" + prog + ".exe\"" + shLongProg = "\"$basedir/" + prog + "\"" + target = "\"%~dp0\\" + target + "\"" + shTarget = "\"$basedir/" + shTarget + "\"" + } + + // @IF EXIST "%~dp0\node.exe" ( + // "%~dp0\node.exe" "%~dp0\.\node_modules\npm\bin\npm-cli.js" %* + // ) ELSE ( + // node "%~dp0\.\node_modules\npm\bin\npm-cli.js" %* + // ) + var cmd + if (longProg) { + cmd = "@IF EXIST " + longProg + " (\r\n" + + " " + longProg + " " + args + " " + target + " %*\r\n" + + ") ELSE (\r\n" + + " " + prog + " " + args + " " + target + " %*\r\n" + + ")" + } else { + cmd = prog + " " + args + " " + target + " %*\r\n" + } + + cmd = ":: Created by npm, please don't edit manually.\r\n" + cmd + + // #!/bin/sh + // basedir=`dirname "$0"` + // + // case `uname` in + // *CYGWIN*) basedir=`cygpath -w "$basedir"`;; + // esac + // + // if [ -x "$basedir/node.exe" ]; then + // "$basedir/node.exe" "$basedir/node_modules/npm/bin/npm-cli.js" "$@" + // ret=$? + // else + // node "$basedir/node_modules/npm/bin/npm-cli.js" "$@" + // ret=$? + // fi + // exit $ret + + var sh = "#!/bin/sh\n" + + if (shLongProg) { + sh = sh + + "basedir=`dirname \"$0\"`\n" + + "\n" + + "case `uname` in\n" + + " *CYGWIN*) basedir=`cygpath -w \"$basedir\"`;;\n" + + "esac\n" + + "\n" + + sh = sh + + "if [ -x "+shLongProg+" ]; then\n" + + " " + shLongProg + " " + args + " " + shTarget + " \"$@\"\n" + + " ret=$?\n" + + "else \n" + + " " + shProg + " " + args + " " + shTarget + " \"$@\"\n" + + " ret=$?\n" + + "fi\n" + + "exit $ret\n" + } else { + sh = shProg + " " + args + " " + shTarget + " \"$@\"\n" + + "exit $?\n" + } + + fs.writeFile(to + ".cmd", cmd, "utf8", function (er) { + if (er) { + log.warn("cmdShim", "Could not write "+to+".cmd") + return cb(er) + } + fs.writeFile(to, sh, "utf8", function (er) { + if (er) { + log.warn("shShim", "Could not write "+to) + return cb(er) + } + fs.chmod(to, 0755, cb) + }) + }) +} diff --git a/node-v0.8.14/deps/npm/lib/utils/completion.sh b/node-v0.8.14/deps/npm/lib/utils/completion.sh new file mode 100755 index 0000000..d027590 --- /dev/null +++ b/node-v0.8.14/deps/npm/lib/utils/completion.sh @@ -0,0 +1,54 @@ +#!/bin/bash +###-begin-npm-completion-### +# +# npm command completion script +# +# Installation: npm completion >> ~/.bashrc (or ~/.zshrc) +# Or, maybe: npm completion > /usr/local/etc/bash_completion.d/npm +# + +COMP_WORDBREAKS=${COMP_WORDBREAKS/=/} +COMP_WORDBREAKS=${COMP_WORDBREAKS/@/} +export COMP_WORDBREAKS + +if type complete &>/dev/null; then + _npm_completion () { + local si="$IFS" + IFS=$'\n' COMPREPLY=($(COMP_CWORD="$COMP_CWORD" \ + COMP_LINE="$COMP_LINE" \ + COMP_POINT="$COMP_POINT" \ + npm completion -- "${COMP_WORDS[@]}" \ + 2>/dev/null)) || return $? + IFS="$si" + } + complete -F _npm_completion npm +elif type compdef &>/dev/null; then + _npm_completion() { + si=$IFS + compadd -- $(COMP_CWORD=$((CURRENT-1)) \ + COMP_LINE=$BUFFER \ + COMP_POINT=0 \ + npm completion -- "${words[@]}" \ + 2>/dev/null) + IFS=$si + } + compdef _npm_completion npm +elif type compctl &>/dev/null; then + _npm_completion () { + local cword line point words si + read -Ac words + read -cn cword + let cword-=1 + read -l line + read -ln point + si="$IFS" + IFS=$'\n' reply=($(COMP_CWORD="$cword" \ + COMP_LINE="$line" \ + COMP_POINT="$point" \ + npm completion -- "${words[@]}" \ + 2>/dev/null)) || return $? + IFS="$si" + } + compctl -K _npm_completion npm +fi +###-end-npm-completion-### diff --git a/node-v0.8.14/deps/npm/lib/utils/completion/file-completion.js b/node-v0.8.14/deps/npm/lib/utils/completion/file-completion.js new file mode 100644 index 0000000..3605557 --- /dev/null +++ b/node-v0.8.14/deps/npm/lib/utils/completion/file-completion.js @@ -0,0 +1,26 @@ +module.exports = fileCompletion + +var mkdir = require("mkdirp") + , path = require("path") + , fs = require("graceful-fs") + , glob = require("glob") + +function fileCompletion (root, req, depth, cb) { + if (typeof cb !== "function") cb = depth, depth = Infinity + mkdir(root, function (er) { + if (er) return cb(er) + + // can be either exactly the req, or a descendent + var pattern = root + "/{" + req + "," + req + "/**/*}" + , opts = { mark: true, dot: true, maxDepth: depth } + glob(pattern, opts, function (er, files) { + if (er) return cb(er) + return cb(null, (files || []).map(function (f) { + return path.join(req, f.substr(root.length + 1) + .substr((f === req ? path.dirname(req) + : req).length) + .replace(/^\//, "")) + })) + }) + }) +} diff --git a/node-v0.8.14/deps/npm/lib/utils/completion/installed-deep.js b/node-v0.8.14/deps/npm/lib/utils/completion/installed-deep.js new file mode 100644 index 0000000..b49d7bb --- /dev/null +++ b/node-v0.8.14/deps/npm/lib/utils/completion/installed-deep.js @@ -0,0 +1,46 @@ +module.exports = installedDeep + +var npm = require("../../npm.js") + , readInstalled = require("read-installed") + +function installedDeep (opts, cb) { + var local + , global + if (npm.config.get("global")) local = [], next() + else readInstalled(npm.prefix, npm.config.get("depth"), function (er, data) { + local = getNames(data || {}) + next() + }) + readInstalled(npm.config.get("prefix"), npm.config.get("depth"), function (er, data) { + global = getNames(data || {}) + next() + }) + + function getNames_ (d, n) { + if (d.realName && n) { + if (n[d.realName]) return n + n[d.realName] = true + } + if (!n) n = {} + Object.keys(d.dependencies || {}).forEach(function (dep) { + getNames_(d.dependencies[dep], n) + }) + return n + } + function getNames (d) { + return Object.keys(getNames_(d)) + } + + function next () { + if (!local || !global) return + if (!npm.config.get("global")) { + global = global.map(function (g) { + return [g, "-g"] + }) + } + var names = local.concat(global) + return cb(null, names) + } + +} + diff --git a/node-v0.8.14/deps/npm/lib/utils/completion/installed-shallow.js b/node-v0.8.14/deps/npm/lib/utils/completion/installed-shallow.js new file mode 100644 index 0000000..8d64649 --- /dev/null +++ b/node-v0.8.14/deps/npm/lib/utils/completion/installed-shallow.js @@ -0,0 +1,79 @@ + +module.exports = installedShallow + +var npm = require("../../npm.js") + , fs = require("graceful-fs") + , path = require("path") + , readJson = require("read-package-json") + , asyncMap = require("slide").asyncMap + +function installedShallow (opts, filter, cb) { + if (typeof cb !== "function") cb = filter, filter = null + var conf = opts.conf + , args = conf.argv.remain + if (args.length > 3) return cb() + var local + , global + , localDir = npm.dir + , globalDir = npm.globalDir + if (npm.config.get("global")) local = [], next() + else fs.readdir(localDir, function (er, pkgs) { + local = (pkgs || []).filter(function (p) { + return p.charAt(0) !== "." + }) + next() + }) + fs.readdir(globalDir, function (er, pkgs) { + global = (pkgs || []).filter(function (p) { + return p.charAt(0) !== "." + }) + next() + }) + function next () { + if (!local || !global) return + filterInstalled(local, global, filter, cb) + } +} + +function filterInstalled (local, global, filter, cb) { + var fl + , fg + + if (!filter) { + fl = local + fg = global + return next() + } + + asyncMap(local, function (p, cb) { + readJson(path.join(npm.dir, p, "package.json"), function (er, d) { + if (!d || !filter(d)) return cb(null, []) + return cb(null, d.name) + }) + }, function (er, local) { + fl = local || [] + next() + }) + + var globalDir = npm.globalDir + asyncMap(global, function (p, cb) { + readJson(path.join(globalDir, p, "package.json"), function (er, d) { + if (!d || !filter(d)) return cb(null, []) + return cb(null, d.name) + }) + }, function (er, global) { + fg = global || [] + next() + }) + + function next () { + if (!fg || !fl) return + if (!npm.config.get("global")) { + fg = fg.map(function (g) { + return [g, "-g"] + }) + } + console.error("filtered", fl, fg) + return cb(null, fl.concat(fg)) + } +} diff --git a/node-v0.8.14/deps/npm/lib/utils/completion/remote-packages.js b/node-v0.8.14/deps/npm/lib/utils/completion/remote-packages.js new file mode 100644 index 0000000..18d812c --- /dev/null +++ b/node-v0.8.14/deps/npm/lib/utils/completion/remote-packages.js @@ -0,0 +1,58 @@ + +module.exports = remotePackages + +var npm = require("../../npm.js") + , registry = npm.registry + , containsSingleMatch = require("./contains-single-match.js") + , getCompletions = require("./get-completions.js") + +/* + Looks up remote packages for CLI tab-completion. + + NOTE: If doVersion is true, versions in the form @ + will be completed. + + If doTag is true, tags in the form @ will be + completed. + + If recurring in true, sequences of multiple packages can be + completed. i.e. for schemes such as: + npm [@ [[@] ...] +*/ +function remotePackages (args, index, doVersion, doTag + , recurring, cb) { + if (recurring || index < 3) { + var name = (args.length + 1 === index) ? args[args.length - 1] : "" + if (name === undefined) name = "" + if (name.indexOf("/") !== -1) return cb(null, []) + // use up-to 1 hour stale cache. not super urgent. + registry.get("/", 3600, function (er, d) { + if (er) return cb(er) + var remoteList = Object.keys(d) + , found = remoteList.indexOf(name) + , unique = found && containsSingleMatch(name, remoteList) + , simpleMatches = getCompletions(name, remoteList) + , uniqueMatch = unique && simpleMatches[0] + , addTag = doTag && (unique || found || name.indexOf("@") !== -1) + , addVer = doVersion && (unique || found || name.indexOf("@") !== -1) + , list = [] + , pieces = (uniqueMatch || name).split("@") + , pkgname = pieces[0] + , extras = [] + if (unique && !addTag && !addVer) return cb(null, [uniqueMatch]) + if (d[pkgname] && (addTag || addVer)) { + if (d[pkgname].versions && addVer) { + extras = extras.concat(Object.keys(d[pkgname].versions)) + } + if (d[pkgname]["dist-tags"] && addTag) { + extras = extras.concat(Object.keys(d[pkgname]["dist-tags"])) + } + list = getCompletions(name, list.concat(extras.map(function (e) { + return pkgname + "@" + e + }))) + } + if (!unique) list = list.concat(getCompletions(name, remoteList)) + return cb(null, list) + }) + } +} diff --git a/node-v0.8.14/deps/npm/lib/utils/completion/users.js b/node-v0.8.14/deps/npm/lib/utils/completion/users.js new file mode 100644 index 0000000..1dc6dbb --- /dev/null +++ b/node-v0.8.14/deps/npm/lib/utils/completion/users.js @@ -0,0 +1,23 @@ + +module.exports = users + +var npm = require("../../npm") + , registry = npm.registry + , containsSingleMatch = require("./contains-single-match.js") + , getCompletions = require("./get-completions.js") + , log = require("npmlog") + +function users (args, index, cb) { + var name = (args.length + 1 === index) ? args[args.length - 1] : "" + if (name === undefined) name = "" + // use up-to 1 day stale cache. doesn't change much + log.warn("users completion", "About to fetch") + registry.get("/-/users", 24*60*60, function (er, d) { + log.warn("userdata", d) + log.warn("name", name) + if (er) return cb(er) + var remoteList = Object.keys(d) + , simpleMatches = getCompletions(name, remoteList) + return cb(null, simpleMatches) + }) +} diff --git a/node-v0.8.14/deps/npm/lib/utils/error-handler.js b/node-v0.8.14/deps/npm/lib/utils/error-handler.js new file mode 100644 index 0000000..7fabd69 --- /dev/null +++ b/node-v0.8.14/deps/npm/lib/utils/error-handler.js @@ -0,0 +1,293 @@ + +module.exports = errorHandler + +var cbCalled = false + , log = require("npmlog") + , npm = require("../npm.js") + , rm = require("rimraf") + , itWorked = false + , path = require("path") + , wroteLogFile = false + , exitCode = 0 + + +process.on("exit", function (code) { + // console.error("exit", code) + if (!npm.config.loaded) return + if (code) itWorked = false + if (itWorked) log.info("ok") + else { + if (!cbCalled) { + log.error("", "cb() never called!") + } + + if (wroteLogFile) { + log.error("", ["" + ,"Additional logging details can be found in:" + ," " + path.resolve("npm-debug.log") + ].join("\n")) + wroteLogFile = false + } + log.error("not ok", "code", code) + } + + var doExit = npm.config.get("_exit") + if (doExit) { + // actually exit. + if (exitCode === 0 && !itWorked) { + exitCode = 1 + } + if (exitCode !== 0) process.exit(exitCode) + } else { + itWorked = false // ready for next exit + } +}) + +function exit (code, noLog) { + exitCode = exitCode || code + + var doExit = npm.config.get("_exit") + log.verbose("exit", [code, doExit]) + if (log.level === "silent") noLog = true + + if (code && !noLog) writeLogFile(reallyExit) + else rm("npm-debug.log", function () { rm(npm.tmp, reallyExit) }) + + function reallyExit() { + // truncate once it's been written. + log.record.length = 0 + + itWorked = !code + + // just emit a fake exit event. + // if we're really exiting, then let it exit on its own, so that + // in-process stuff can finish or clean up first. + if (!doExit) process.emit("exit", code) + } +} + + +function errorHandler (er) { + var printStack = false + // console.error("errorHandler", er) + if (!npm.config.loaded) { + // logging won't work unless we pretend that it's ready + er = er || new Error("Exit prior to config file resolving.") + console.error(er.stack || er.message) + } + + if (cbCalled) { + er = er || new Error("Callback called more than once.") + } + + cbCalled = true + if (!er) return exit(0) + if (typeof er === "string") { + log.error("", er) + return exit(1, true) + } else if (!(er instanceof Error)) { + log.error("weird error", er) + return exit(1, true) + } + + var m = er.code || er.message.match(/^(?:Error: )?(E[A-Z]+)/) + if (m && !er.code) er.code = m + + switch (er.code) { + case "ECONNREFUSED": + log.error("", er) + log.error("", ["\nIf you are behind a proxy, please make sure that the" + ,"'proxy' config is set properly. See: 'npm help config'" + ].join("\n")) + printStack = true + break + + case "EACCES": + case "EPERM": + log.error("", er) + log.error("", ["\nPlease try running this command again as root/Administrator." + ].join("\n")) + printStack = true + break + + case "ELIFECYCLE": + er.code = "ELIFECYCLE" + log.error("", er.message) + log.error("", ["","Failed at the "+er.pkgid+" "+er.stage+" script." + ,"This is most likely a problem with the "+er.pkgname+" package," + ,"not with npm itself." + ,"Tell the author that this fails on your system:" + ," "+er.script + ,"You can get their info via:" + ," npm owner ls "+er.pkgname + ,"There is likely additional logging output above." + ].join("\n")) + break + + case "EJSONPARSE": + er.code = "EJSONPARSE" + log.error("", er.message) + log.error("", "File: "+er.file) + log.error("", ["Failed to parse package.json data." + ,"package.json must be actual JSON, not just JavaScript." + ,"","This is not a bug in npm." + ,"Tell the package author to fix their package.json file." + ].join("\n"), "JSON.parse") + break + + case "E404": + er.code = "E404" + if (er.pkgid && er.pkgid !== "-") { + var msg = ["'"+er.pkgid+"' is not in the npm registry." + ,"You should bug the author to publish it"] + if (er.pkgid.match(/^node[\.\-]|[\.\-]js$/)) { + var s = er.pkgid.replace(/^node[\.\-]|[\.\-]js$/g, "") + if (s !== er.pkgid) { + s = s.replace(/[^a-z0-9]/g, ' ') + msg.push("\nMaybe try 'npm search " + s + "'") + } + } + msg.push("\nNote that you can also install from a" + ,"tarball, folder, or http url, or git url.") + log.error("404", msg.join("\n")) + } + break + + case "EPUBLISHCONFLICT": + er.code = "EPUBLISHCONFLICT" + log.error("publish fail", ["Cannot publish over existing version." + ,"Bump the 'version' field, set the --force flag, or" + ," npm unpublish '"+er.pkgid+"'" + ,"and try again" + ].join("\n")) + break + + case "EISGIT": + er.code = "EISGIT" + log.error("git", [er.message + ," "+er.path + ,"Refusing to remove it. Update manually," + ,"or move it out of the way first." + ].join("\n")) + break + + case "ECYCLE": + er.code = "ECYCLE" + log.error("cycle", [er.message + ,"While installing: "+er.pkgid + ,"Found a pathological dependency case that npm cannot solve." + ,"Please report this to the package author." + ].join("\n")) + break + + case "EBADPLATFORM": + er.code = "EBADPLATFORM" + log.error("notsup", [er.message + ,"Not compatible with your operating system or architecture: "+er.pkgid + ,"Valid OS: "+er.os.join(",") + ,"Valid Arch: "+er.cpu.join(",") + ,"Actual OS: "+process.platform + ,"Actual Arch: "+process.arch + ].join("\n")) + break + + case "EEXIST": + log.error([er.message + ,"File exists: "+er.path + ,"Move it away, and try again."].join("\n")) + break + + case "ENEEDAUTH": + log.error("need auth", [er.message + ,"You need to authorize this machine using `npm adduser`" + ].join("\n")) + break + + case "ENOTSUP": + if (er.required) { + log.error("notsup", [er.message + ,"Not compatible with your version of node/npm: "+er.pkgid + ,"Required: "+JSON.stringify(er.required) + ,"Actual: " + +JSON.stringify({npm:npm.version + ,node:npm.config.get("node-version")}) + ].join("\n")) + break + } // else passthrough + + default: + log.error("", er.stack || er.message || er) + log.error("", ["If you need help, you may report this log at:" + ," " + ,"or email it to:" + ," " + ].join("\n")) + printStack = false + break + } + + var os = require("os") + // just a line break + console.error("") + log.error("System", os.type() + " " + os.release()) + log.error("command", process.argv + .map(JSON.stringify).join(" ")) + log.error("cwd", process.cwd()) + log.error("node -v", process.version) + log.error("npm -v", npm.version) + + ; [ "file" + , "path" + , "type" + , "syscall" + , "fstream_path" + , "fstream_unc_path" + , "fstream_type" + , "fstream_class" + , "fstream_finish_call" + , "fstream_linkpath" + , "code" + , "errno" + , "stack" + , "fstream_stack" + ].forEach(function (k) { + var v = er[k] + if (k === "stack") { + if (!printStack) return + if (!v) v = er.message + } + if (!v) return + if (k === "fstream_stack") v = v.join("\n") + log.error(k, v) + }) + + exit(typeof er.errno === "number" ? er.errno : 1) +} + +var writingLogFile = false +function writeLogFile (cb) { + if (writingLogFile) return cb() + writingLogFile = true + wroteLogFile = true + + var fs = require("graceful-fs") + , fstr = fs.createWriteStream("npm-debug.log") + , util = require("util") + , eol = process.platform === "win32" ? "\r\n" : "\n" + , out = "" + + log.record.forEach(function (m) { + var pref = [m.id, m.level] + if (m.prefix) pref.push(m.prefix) + pref = pref.join(' ') + + m.message.trim().split(/\r?\n/).map(function (line) { + return (pref + ' ' + line).trim() + }).forEach(function (line) { + out += line + eol + }) + }) + + fstr.end(out) + fstr.on("close", cb) +} diff --git a/node-v0.8.14/deps/npm/lib/utils/exec.js b/node-v0.8.14/deps/npm/lib/utils/exec.js new file mode 100644 index 0000000..56d331a --- /dev/null +++ b/node-v0.8.14/deps/npm/lib/utils/exec.js @@ -0,0 +1,82 @@ +module.exports = exec +exec.spawn = spawn + +var log = require("npmlog") + , child_process = require("child_process") + , util = require("util") + , npm = require("../npm.js") + , myUID = process.getuid ? process.getuid() : null + , myGID = process.getgid ? process.getgid() : null + , isRoot = process.getuid && myUID === 0 + , constants = require("constants") + , uidNumber = require("uid-number") + +function exec (cmd, args, env, takeOver, cwd, uid, gid, cb) { + if (typeof cb !== "function") cb = gid, gid = null + if (typeof cb !== "function") cb = uid, uid = null + if (typeof cb !== "function") cb = cwd, cwd = null + if (typeof cb !== "function") cb = takeOver, takeOver = true + if (typeof cb !== "function") cb = env, env = process.env + gid = gid == null ? myGID : gid + uid = uid == null ? myUID : uid + if (!isRoot) { + if (npm.config.get("unsafe-perm")) { + uid = myUID + gid = myGID + } else if (uid !== myUID || gid !== myGID) { + var e = new Error("EPERM: setuid() operation not permitted") + e.errno = constants.EPERM + return cb(e) + } + } + if (uid !== myUID) { + log.verbose("set uid", "from=%s to=%s", myUID, uid) + } + + if (uid && gid && (isNaN(uid) || isNaN(gid))) { + // get the numeric values + return uidNumber(uid, gid, function (er, uid, gid) { + if (er) return cb(er) + exec(cmd, args, env, takeOver, cwd, uid, gid, cb) + }) + } + + log.silly("exec", cmd+" "+args.map(JSON.stringify).join(" ")) + var stdout = "" + , stderr = "" + , cp = spawn(cmd, args, env, takeOver, cwd, uid, gid) + cp.stdout && cp.stdout.on("data", function (chunk) { + if (chunk) stdout += chunk + }) + cp.stderr && cp.stderr.on("data", function (chunk) { + if (chunk) stderr += chunk + }) + cp.on("exit", function (code) { + var er = null + if (code) er = new Error("`"+cmd + +(args.length ? " " + + args.map(JSON.stringify).join(" ") + : "") + +"` failed with "+code) + cb(er, code, stdout, stderr) + }) + return cp +} + + +function spawn (c, a, env, takeOver, cwd, uid, gid) { + var fds = [ 0, 1, 2 ] + , opts = { customFds : takeOver ? fds : [-1,-1,-1] + , env : env || process.env + , cwd : cwd || null } + , cp + + if (uid && !isNaN(uid)) opts.uid = +uid + if (gid && !isNaN(gid)) opts.gid = +gid + + var name = c +" "+ a.map(JSON.stringify).join(" ") + log.silly([c, a, opts.cwd], "spawning") + cp = child_process.spawn(c, a, opts) + cp.name = name + return cp +} diff --git a/node-v0.8.14/deps/npm/lib/utils/fetch.js b/node-v0.8.14/deps/npm/lib/utils/fetch.js new file mode 100644 index 0000000..b988520 --- /dev/null +++ b/node-v0.8.14/deps/npm/lib/utils/fetch.js @@ -0,0 +1,84 @@ +/** + * Fetch an HTTP url to a local file. + **/ + +var request = require("request") + , fs = require("graceful-fs") + , npm = require("../npm.js") + , url = require("url") + , log = require("npmlog") + , path = require("path") + , mkdir = require("mkdirp") + , chownr = require("chownr") + , regHost + +module.exports = fetch + +function fetch (remote, local, headers, cb) { + if (typeof cb !== "function") cb = headers, headers = {} + log.verbose("fetch", "to=", local) + mkdir(path.dirname(local), function (er, made) { + if (er) return cb(er) + fetch_(remote, local, headers, cb) + }) +} + +function fetch_ (remote, local, headers, cb) { + var fstr = fs.createWriteStream(local, { mode : npm.modes.file }) + var response = null + var calledback = false + fstr.on("error", function (er) { + fs.close(fstr.fd, function () {}) + if (calledback) return + calledback = true + cb(fstr._ERROR = er) + }) + fstr.on("open", function () { + var req = makeRequest(remote, fstr, headers) + req.on("response", function (res) { + log.http(res.statusCode, remote) + response = res + }) + }) + fstr.on("close", function () { + if (calledback) return + calledback = true + if (response && response.statusCode && response.statusCode >= 400) { + var er = new Error(response.statusCode + " " + + require("http").STATUS_CODES[response.statusCode]) + cb(fstr._ERROR = er, response) + } else { + cb(null, response) + } + }) +} + +function makeRequest (remote, fstr, headers) { + remote = url.parse(remote) + log.http("GET", remote.href) + regHost = regHost || url.parse(npm.config.get("registry")).host + + if (remote.host === regHost && npm.config.get("always-auth")) { + remote.auth = new Buffer( npm.config.get("_auth") + , "base64" ).toString("utf8") + if (!remote.auth) return fstr.emit("error", new Error( + "Auth required and none provided. Please run 'npm adduser'")) + } + + var proxy + if (remote.protocol !== "https:" || !(proxy = npm.config.get("https-proxy"))) { + proxy = npm.config.get("proxy") + } + + var opts = { url: remote + , proxy: proxy + , strictSSL: npm.config.get("strict-ssl") + , ca: remote.host === regHost ? npm.config.get("ca") : undefined + , headers: { "user-agent": npm.config.get("user-agent") }} + var req = request(opts) + req.on("error", function (er) { + fstr.emit("error", er) + }) + req.pipe(fstr) + return req; +} diff --git a/node-v0.8.14/deps/npm/lib/utils/find-prefix.js b/node-v0.8.14/deps/npm/lib/utils/find-prefix.js new file mode 100644 index 0000000..c3ff85f --- /dev/null +++ b/node-v0.8.14/deps/npm/lib/utils/find-prefix.js @@ -0,0 +1,52 @@ +// try to find the most reasonable prefix to use + +module.exports = findPrefix + +var fs = require("graceful-fs") + , path = require("path") + , npm = require("../npm.js") + +function findPrefix (p, cb_) { + function cb (er, p) { + process.nextTick(function () { + cb_(er, p) + }) + } + + p = path.resolve(p) + // if there's no node_modules folder, then + // walk up until we hopefully find one. + // if none anywhere, then use cwd. + var walkedUp = false + while (path.basename(p) === "node_modules") { + p = path.dirname(p) + walkedUp = true + } + if (walkedUp) return cb(null, p) + + findPrefix_(p, p, cb) +} + +function findPrefix_ (p, original, cb) { + if (p === "/" + || (process.platform === "win32" && p.match(/^[a-zA-Z]:(\\|\/)?$/))) { + return cb(null, original) + } + fs.readdir(p, function (er, files) { + // an error right away is a bad sign. + if (er && p === original) return cb(er) + + // walked up too high or something. + if (er) return cb(null, original) + + if (files.indexOf("node_modules") !== -1 + || files.indexOf("package.json") !== -1) { + return cb(null, p) + } + + var d = path.dirname(p) + if (d === p) return cb(null, original) + + return findPrefix_(d, original, cb) + }) +} diff --git a/node-v0.8.14/deps/npm/lib/utils/gently-rm.js b/node-v0.8.14/deps/npm/lib/utils/gently-rm.js new file mode 100644 index 0000000..f24309a --- /dev/null +++ b/node-v0.8.14/deps/npm/lib/utils/gently-rm.js @@ -0,0 +1,45 @@ +// only remove the thing if it's a symlink into a specific folder. +// This is a very common use-case of npm's, but not so common elsewhere. + +module.exports = gentlyRm + +var rimraf = require("rimraf") + , fs = require("graceful-fs") + , npm = require("../npm.js") + , path = require("path") + +function gentlyRm (p, gently, cb) { + if (npm.config.get("force") || !gently) { + return rimraf(p, cb) + } + + gently = path.resolve(gently) + + // lstat it, see if it's a symlink. + fs.lstat(p, function (er, s) { + if (er) return rimraf(p, cb) + if (!s.isSymbolicLink()) next(null, path.resolve(p)) + realish(p, next) + }) + + function next (er, rp) { + if (rp && rp.indexOf(gently) !== 0) { + return clobberFail(p, gently, cb) + } + rimraf(p, cb) + } +} + +function realish (p, cb) { + fs.readlink(p, function (er, r) { + if (er) return cb(er) + return cb(null, path.resolve(path.dirname(p), r)) + }) +} + +function clobberFail (p, g, cb) { + var er = new Error("Refusing to delete: "+p+" not in "+g) + er.code = "EEXIST" + er.path = p + return cb(er) +} diff --git a/node-v0.8.14/deps/npm/lib/utils/lifecycle.js b/node-v0.8.14/deps/npm/lib/utils/lifecycle.js new file mode 100644 index 0000000..eae3c3e --- /dev/null +++ b/node-v0.8.14/deps/npm/lib/utils/lifecycle.js @@ -0,0 +1,301 @@ + +exports = module.exports = lifecycle +exports.cmd = cmd + +var log = require("npmlog") + , exec = require("./exec.js") + , npm = require("../npm.js") + , path = require("path") + , fs = require("graceful-fs") + , chain = require("slide").chain + , constants = require("constants") + , Stream = require("stream").Stream + , PATH = "PATH" + +// windows calls it's path "Path" usually, but this is not guaranteed. +if (process.platform === "win32") { + PATH = "Path" + Object.keys(process.env).forEach(function (e) { + if (e.match(/^PATH$/i)) { + PATH = e + } + }) +} + +function lifecycle (pkg, stage, wd, unsafe, failOk, cb) { + if (typeof cb !== "function") cb = failOk, failOk = false + if (typeof cb !== "function") cb = unsafe, unsafe = false + if (typeof cb !== "function") cb = wd, wd = null + + while (pkg && pkg._data) pkg = pkg._data + if (!pkg) return cb(new Error("Invalid package data")) + + log.info(stage, pkg._id) + if (!pkg.scripts) pkg.scripts = {} + + validWd(wd || path.resolve(npm.dir, pkg.name), function (er, wd) { + if (er) return cb(er) + + unsafe = unsafe || npm.config.get("unsafe-perm") + + if ((wd.indexOf(npm.dir) !== 0 || path.basename(wd) !== pkg.name) + && !unsafe && pkg.scripts[stage]) { + log.warn( "cannot run in wd", "%s %s (wd=%s)" + , pkg._id, pkg.scripts[stage], wd) + return cb() + } + + // set the env variables, then run scripts as a child process. + var env = makeEnv(pkg) + env.npm_lifecycle_event = stage + + // "nobody" typically doesn't have permission to write to /tmp + // even if it's never used, sh freaks out. + if (!npm.config.get("unsafe-perm")) env.TMPDIR = wd + + lifecycle_(pkg, stage, wd, env, unsafe, failOk, cb) + }) +} + +function checkForLink (pkg, cb) { + var f = path.join(npm.dir, pkg.name) + fs.lstat(f, function (er, s) { + cb(null, !(er || !s.isSymbolicLink())) + }) +} + +function lifecycle_ (pkg, stage, wd, env, unsafe, failOk, cb) { + var pathArr = [] + , p = wd.split("node_modules") + , acc = path.resolve(p.shift()) + p.forEach(function (pp) { + pathArr.unshift(path.join(acc, "node_modules", ".bin")) + acc = path.join(acc, "node_modules", pp) + }) + pathArr.unshift(path.join(acc, "node_modules", ".bin")) + + // we also unshift the bundled node-gyp-bin folder so that + // the bundled one will be used for installing things. + pathArr.unshift(path.join(__dirname, "..", "..", "bin", "node-gyp-bin")) + + // add the directory containing the `node` executable currently running, so + // that any lifecycle script that invoke "node" will execute this same one. + pathArr.unshift(path.dirname(process.execPath)) + + if (env[PATH]) pathArr.push(env[PATH]) + env[PATH] = pathArr.join(process.platform === "win32" ? ";" : ":") + + var packageLifecycle = pkg.scripts && pkg.scripts.hasOwnProperty(stage) + + if (packageLifecycle) { + // define this here so it's available to all scripts. + env.npm_lifecycle_script = pkg.scripts[stage] + } + + if (failOk) { + cb = (function (cb_) { return function (er) { + if (er) log.warn("continuing anyway", er.message) + cb_() + }})(cb) + } + + if (npm.config.get("force")) { + cb = (function (cb_) { return function (er) { + if (er) log.info("forced, continuing", er) + cb_() + }})(cb) + } + + chain + ( [ packageLifecycle && [runPackageLifecycle, pkg, env, wd, unsafe] + , [runHookLifecycle, pkg, env, wd, unsafe] ] + , cb ) +} + +function validWd (d, cb) { + fs.stat(d, function (er, st) { + if (er || !st.isDirectory()) { + var p = path.dirname(d) + if (p === d) { + return cb(new Error("Could not find suitable wd")) + } + return validWd(p, cb) + } + return cb(null, d) + }) +} + +function runPackageLifecycle (pkg, env, wd, unsafe, cb) { + // run package lifecycle scripts in the package root, or the nearest parent. + var stage = env.npm_lifecycle_event + , user = unsafe ? null : npm.config.get("user") + , group = unsafe ? null : npm.config.get("group") + , cmd = env.npm_lifecycle_script + , sh = "sh" + , shFlag = "-c" + + if (process.platform === "win32") { + sh = "cmd" + shFlag = "/c" + } + + log.verbose("unsafe-perm in lifecycle", unsafe) + + var note = "\n> " + pkg._id + " " + stage + " " + wd + + "\n> " + cmd + "\n" + + console.log(note) + exec( sh, [shFlag, cmd], env, true, wd + , user, group + , function (er, code, stdout, stderr) { + if (er && !npm.ROLLBACK) { + log.info(pkg._id, "Failed to exec "+stage+" script") + er.message = pkg._id + " " + + stage + ": `" + env.npm_lifecycle_script+"`\n" + + er.message + if (er.code !== "EPERM") { + er.code = "ELIFECYCLE" + } + er.pkgid = pkg._id + er.stage = stage + er.script = env.npm_lifecycle_script + er.pkgname = pkg.name + return cb(er) + } else if (er) { + log.error(pkg._id+"."+stage, er) + log.error(pkg._id+"."+stage, "continuing anyway") + return cb() + } + cb(er) + }) +} + +function runHookLifecycle (pkg, env, wd, unsafe, cb) { + // check for a hook script, run if present. + var stage = env.npm_lifecycle_event + , hook = path.join(npm.dir, ".hooks", stage) + , user = unsafe ? null : npm.config.get("user") + , group = unsafe ? null : npm.config.get("group") + , cmd = hook + + fs.stat(hook, function (er) { + if (er) return cb() + + exec( "sh", ["-c", cmd], env, true, wd + , user, group + , function (er) { + if (er) { + er.message += "\nFailed to exec "+stage+" hook script" + log.info(pkg._id, er) + } + if (npm.ROLLBACK) return cb() + cb(er) + }) + }) +} + +function makeEnv (data, prefix, env) { + prefix = prefix || "npm_package_" + if (!env) { + env = {} + for (var i in process.env) if (!i.match(/^npm_/)) { + env[i] = process.env[i] + } + + // npat asks for tap output + if (npm.config.get("npat")) env.TAP = 1 + + // express and others respect the NODE_ENV value. + if (npm.config.get("production")) env.NODE_ENV = "production" + + } else if (!data.hasOwnProperty("_lifecycleEnv")) { + Object.defineProperty(data, "_lifecycleEnv", + { value : env + , enumerable : false + }) + } + + for (var i in data) if (i.charAt(0) !== "_") { + var envKey = (prefix+i).replace(/[^a-zA-Z0-9_]/g, '_') + if (data[i] && typeof(data[i]) === "object") { + try { + // quick and dirty detection for cyclical structures + JSON.stringify(data[i]) + makeEnv(data[i], envKey+"_", env) + } catch (ex) { + // usually these are package objects. + // just get the path and basic details. + var d = data[i] + makeEnv( { name: d.name, version: d.version, path:d.path } + , envKey+"_", env) + } + } else { + env[envKey] = String(data[i]) + env[envKey] = -1 !== env[envKey].indexOf("\n") + ? JSON.stringify(env[envKey]) + : env[envKey] + } + + } + + if (prefix !== "npm_package_") return env + + prefix = "npm_config_" + var pkgConfig = {} + , keys = npm.config.keys + , pkgVerConfig = {} + , namePref = data.name + ":" + , verPref = data.name + "@" + data.version + ":" + + keys.forEach(function (i) { + if (i.charAt(0) === "_" && i.indexOf("_"+namePref) !== 0) { + return + } + var value = npm.config.get(i) + if (value instanceof Stream || Array.isArray(value)) return + if (!value) value = "" + else if (typeof value !== "string") value = JSON.stringify(value) + + value = -1 !== value.indexOf("\n") + ? JSON.stringify(value) + : value + i = i.replace(/^_+/, "") + if (i.indexOf(namePref) === 0) { + var k = i.substr(namePref.length).replace(/[^a-zA-Z0-9_]/g, "_") + pkgConfig[ k ] = value + } else if (i.indexOf(verPref) === 0) { + var k = i.substr(verPref.length).replace(/[^a-zA-Z0-9_]/g, "_") + pkgVerConfig[ k ] = value + } + var envKey = (prefix+i).replace(/[^a-zA-Z0-9_]/g, "_") + env[envKey] = value + }) + + prefix = "npm_package_config_" + ;[pkgConfig, pkgVerConfig].forEach(function (conf) { + for (var i in conf) { + var envKey = (prefix+i) + env[envKey] = conf[i] + } + }) + + return env +} + +function cmd (stage) { + function CMD (args, cb) { + if (args.length) { + chain(args.map(function (p) { + return [npm.commands, "run-script", [p, stage]] + }), cb) + } else npm.commands["run-script"]([stage], cb) + } + CMD.usage = "npm "+stage+" " + var installedShallow = require("./completion/installed-shallow.js") + CMD.completion = function (opts, cb) { + installedShallow(opts, function (d) { + return d.scripts && d.scripts[stage] + }, cb) + } + return CMD +} diff --git a/node-v0.8.14/deps/npm/lib/utils/link.js b/node-v0.8.14/deps/npm/lib/utils/link.js new file mode 100644 index 0000000..9e01d82 --- /dev/null +++ b/node-v0.8.14/deps/npm/lib/utils/link.js @@ -0,0 +1,39 @@ + +module.exports = link +link.ifExists = linkIfExists + +var fs = require("graceful-fs") + , chain = require("slide").chain + , mkdir = require("mkdirp") + , rm = require("./gently-rm.js") + , path = require("path") + , npm = require("../npm.js") + +function linkIfExists (from, to, gently, cb) { + fs.stat(from, function (er) { + if (er) return cb() + link(from, to, gently, cb) + }) +} + +function link (from, to, gently, cb) { + if (typeof cb !== "function") cb = gently, gently = null + if (npm.config.get("force")) gently = false + + to = path.resolve(to) + var target = from = path.resolve(from) + if (process.platform !== "win32") { + // junctions on windows must be absolute + target = path.relative(path.dirname(to), from) + // if there is no folder in common, then it will be much + // longer, and using a relative link is dumb. + if (target.length >= from.length) target = from + } + + chain + ( [ [fs, "stat", from] + , [rm, to, gently] + , [mkdir, path.dirname(to)] + , [fs, "symlink", target, to, "junction"] ] + , cb) +} diff --git a/node-v0.8.14/deps/npm/lib/utils/sha.js b/node-v0.8.14/deps/npm/lib/utils/sha.js new file mode 100644 index 0000000..d3cd83a --- /dev/null +++ b/node-v0.8.14/deps/npm/lib/utils/sha.js @@ -0,0 +1,54 @@ + +var fs = require("graceful-fs") + , crypto = require("crypto") + , log = require("npmlog") + , binding + +try { binding = process.binding("crypto") } +catch (e) { binding = null } + +exports.check = check +exports.get = get + +function check (file, sum, cb) { + if (!binding) { + log.warn("shasum", "crypto binding not found. Cannot verify shasum.") + return cb() + } + get(file, function (er, actual) { + if (er) { + log.error("shasum", "error getting shasum") + return cb(er) + } + var expected = sum.toLowerCase().trim() + , ok = actual === expected + cb(ok ? null : new Error( + "shasum check failed for "+file+"\n" + +"Expected: "+expected+"\n" + +"Actual: "+actual)) + }) +} + +function get (file, cb) { + if (!binding) { + log.warn("shasum", "crypto binding not found. Cannot verify shasum.") + return cb() + } + var h = crypto.createHash("sha1") + , s = fs.createReadStream(file) + , errState = null + s.on("error", function (er) { + if (errState) return + log.silly("shasum", "error", er) + return cb(errState = er) + }).on("data", function (chunk) { + if (errState) return + log.silly("shasum", "updated bytes", chunk.length) + h.update(chunk) + }).on("end", function () { + if (errState) return + var actual = h.digest("hex").toLowerCase().trim() + log.info("shasum", actual+"\n"+file) + cb(null, actual) + }) +} diff --git a/node-v0.8.14/deps/npm/lib/utils/tar.js b/node-v0.8.14/deps/npm/lib/utils/tar.js new file mode 100644 index 0000000..5d738ba --- /dev/null +++ b/node-v0.8.14/deps/npm/lib/utils/tar.js @@ -0,0 +1,269 @@ +// commands for packing and unpacking tarballs +// this file is used by lib/cache.js + +var npm = require("../npm.js") + , fs = require("graceful-fs") + , path = require("path") + , log = require("npmlog") + , uidNumber = require("uid-number") + , rm = require("rimraf") + , readJson = require("read-package-json") + , cache = require("../cache.js") + , lock = cache.lock + , unlock = cache.unlock + , myUid = process.getuid && process.getuid() + , myGid = process.getgid && process.getgid() + , tar = require("tar") + , zlib = require("zlib") + , fstream = require("fstream") + , Packer = require("fstream-npm") + , lifecycle = require("./lifecycle.js") + +if (process.env.SUDO_UID && myUid === 0) { + if (!isNaN(process.env.SUDO_UID)) myUid = +process.env.SUDO_UID + if (!isNaN(process.env.SUDO_GID)) myGid = +process.env.SUDO_GID +} + +exports.pack = pack +exports.unpack = unpack + +function pack (targetTarball, folder, pkg, dfc, cb) { + log.verbose("tar pack", [targetTarball, folder]) + if (typeof cb !== "function") cb = dfc, dfc = false + + log.verbose("tarball", targetTarball) + log.verbose("folder", folder) + + if (dfc) { + // do fancy crap + return lifecycle(pkg, 'prepublish', folder, function (er) { + if (er) return cb(er) + pack_(targetTarball, folder, pkg, cb) + }) + } else { + pack_(targetTarball, folder, pkg, cb) + } +} + +function pack_ (targetTarball, folder, pkg, cb_) { + function cb (er) { + unlock(targetTarball, function () { + return cb_(er) + }) + } + lock(targetTarball, function (er) { + if (er) return cb(er) + + new Packer({ path: folder, type: "Directory", isDirectory: true }) + .on("error", function (er) { + if (er) log.error("tar pack", "Error reading " + folder) + return cb(er) + }) + + // By default, npm includes some proprietary attributes in the + // package tarball. This is sane, and allowed by the spec. + // However, npm *itself* excludes these from its own package, + // so that it can be more easily bootstrapped using old and + // non-compliant tar implementations. + .pipe(tar.Pack({ noProprietary: !npm.config.get("proprietary-attribs") })) + .on("error", function (er) { + if (er) log.error("tar.pack", "tar creation error", targetTarball) + cb(er) + }) + .pipe(zlib.Gzip()) + .on("error", function (er) { + if (er) log.error("tar.pack", "gzip error "+targetTarball) + cb(er) + }) + .pipe(fstream.Writer({ type: "File", path: targetTarball })) + .on("error", function (er) { + if (er) log.error("tar.pack", "Could not write "+targetTarball) + cb(er) + }) + .on("close", cb) + }) +} + + +function unpack (tarball, unpackTarget, dMode, fMode, uid, gid, cb) { + log.verbose("tar unpack", tarball) + if (typeof cb !== "function") cb = gid, gid = null + if (typeof cb !== "function") cb = uid, uid = null + if (typeof cb !== "function") cb = fMode, fMode = npm.modes.file + if (typeof cb !== "function") cb = dMode, dMode = npm.modes.exec + + uidNumber(uid, gid, function (er, uid, gid) { + if (er) return cb(er) + unpack_(tarball, unpackTarget, dMode, fMode, uid, gid, cb) + }) +} + +function unpack_ ( tarball, unpackTarget, dMode, fMode, uid, gid, cb_ ) { + var parent = path.dirname(unpackTarget) + , base = path.basename(unpackTarget) + + function cb (er) { + unlock(unpackTarget, function () { + return cb_(er) + }) + } + + lock(unpackTarget, function (er) { + if (er) return cb(er) + rmGunz() + }) + + function rmGunz () { + rm(unpackTarget, function (er) { + if (er) return cb(er) + gtp() + }) + } + + function gtp () { + // gzip {tarball} --decompress --stdout \ + // | tar -mvxpf - --strip-components=1 -C {unpackTarget} + gunzTarPerm( tarball, unpackTarget + , dMode, fMode + , uid, gid + , function (er, folder) { + if (er) return cb(er) + readJson(path.resolve(folder, "package.json"), cb) + }) + } +} + + +function gunzTarPerm (tarball, target, dMode, fMode, uid, gid, cb_) { + if (!dMode) dMode = npm.modes.exec + if (!fMode) fMode = npm.modes.file + log.silly("gunzTarPerm", "modes", [dMode.toString(8), fMode.toString(8)]) + + var cbCalled = false + function cb (er) { + if (cbCalled) return + cbCalled = true + cb_(er, target) + } + + var fst = fs.createReadStream(tarball) + + // figure out who we're supposed to be, if we're not pretending + // to be a specific user. + if (npm.config.get("unsafe-perm") && process.platform !== "win32") { + uid = myUid + gid = myGid + } + + function extractEntry (entry) { + log.silly("gunzTarPerm", "extractEntry", entry.path) + // never create things that are user-unreadable, + // or dirs that are user-un-listable. Only leads to headaches. + var originalMode = entry.mode = entry.mode || entry.props.mode + entry.mode = entry.mode | (entry.type === "Directory" ? dMode : fMode) + entry.mode = entry.mode & (~npm.modes.umask) + entry.props.mode = entry.mode + if (originalMode !== entry.mode) { + log.silly( "gunzTarPerm", "modified mode" + , [entry.path, originalMode, entry.mode]) + } + + // if there's a specific owner uid/gid that we want, then set that + if (process.platform !== "win32" && + typeof uid === "number" && + typeof gid === "number") { + entry.props.uid = entry.uid = uid + entry.props.gid = entry.gid = gid + } + } + + var extractOpts = { type: "Directory", path: target, strip: 1 } + + if (process.platform !== "win32" && + typeof uid === "number" && + typeof gid === "number") { + extractOpts.uid = uid + extractOpts.gid = gid + } + + extractOpts.filter = function () { + // symbolic links are not allowed in packages. + if (this.type.match(/^.*Link$/)) { + log.warn( "excluding symbolic link" + , this.path.substr(target.length + 1) + + ' -> ' + this.linkpath ) + return false + } + return true + } + + + fst.on("error", function (er) { + if (er) log.error("tar.unpack", "error reading "+tarball) + cb(er) + }) + fst.on("data", function OD (c) { + // detect what it is. + // Then, depending on that, we'll figure out whether it's + // a single-file module, gzipped tarball, or naked tarball. + // gzipped files all start with 1f8b08 + if (c[0] === 0x1F && + c[1] === 0x8B && + c[2] === 0x08) { + fst + .pipe(zlib.Unzip()) + .on("error", function (er) { + if (er) log.error("tar.unpack", "unzip error "+tarball) + cb(er) + }) + .pipe(tar.Extract(extractOpts)) + .on("entry", extractEntry) + .on("error", function (er) { + if (er) log.error("tar.unpack", "untar error "+tarball) + cb(er) + }) + .on("close", cb) + } else if (c.toString().match(/^package\//)) { + // naked tar + fst + .pipe(tar.Extract(extractOpts)) + .on("entry", extractEntry) + .on("error", function (er) { + if (er) log.error("tar.unpack", "untar error "+tarball) + cb(er) + }) + .on("close", cb) + } else { + // naked js file + var jsOpts = { path: path.resolve(target, "index.js") } + + if (process.platform !== "win32" && + typeof uid === "number" && + typeof gid === "number") { + jsOpts.uid = uid + jsOpts.gid = gid + } + + fst + .pipe(fstream.Writer(jsOpts)) + .on("error", function (er) { + if (er) log.error("tar.unpack", "copy error "+tarball) + cb(er) + }) + .on("close", function () { + var j = path.resolve(target, "package.json") + readJson(j, function (er, d) { + if (er) { + log.error("not a package", tarball) + return cb(er) + } + fs.writeFile(j, JSON.stringify(d) + "\n", cb) + }) + }) + } + + // now un-hook, and re-emit the chunk + fst.removeListener("data", OD) + fst.emit("data", c) + }) +} diff --git a/node-v0.8.14/deps/npm/lib/version.js b/node-v0.8.14/deps/npm/lib/version.js new file mode 100644 index 0000000..fb00e21 --- /dev/null +++ b/node-v0.8.14/deps/npm/lib/version.js @@ -0,0 +1,105 @@ +// npm version + +module.exports = version + +var exec = require("./utils/exec.js") + , semver = require("semver") + , path = require("path") + , fs = require("graceful-fs") + , chain = require("slide").chain + , log = require("npmlog") + , npm = require("./npm.js") + +version.usage = "npm version [ | major | minor | patch | build]\n" + + "\n(run in package dir)\n" + + "'npm -v' or 'npm --version' to print npm version " + + "("+npm.version+")\n" + + "'npm view version' to view a package's " + + "published version\n" + + "'npm ls' to inspect current package/dependency versions" + +function version (args, silent, cb_) { + if (typeof cb_ !== "function") cb_ = silent, silent = false + if (args.length > 1) return cb_(version.usage) + fs.readFile(path.join(process.cwd(), "package.json"), function (er, data) { + if (!args.length) { + var v = {} + Object.keys(process.versions).forEach(function (k) { + v[k] = process.versions[k] + }) + v.npm = npm.version + try { + data = JSON.parse(data.toString()) + } catch (er) { + data = null + } + if (data && data.name && data.version) { + v[data.name] = data.version + } + console.log(v) + return cb_() + } + + if (er) { + log.error("version", "No package.json found") + return cb_(er) + } + + try { + data = JSON.parse(data) + } catch (er) { + log.error("version", "Bad package.json data") + return cb_(er) + } + + var newVer = semver.valid(args[0]) + if (!newVer) newVer = semver.inc(data.version, args[0]) + if (!newVer) return cb_(version.usage) + if (data.version === newVer) return cb_(new Error("Version not changed")) + data.version = newVer + + fs.stat(path.join(process.cwd(), ".git"), function (er, s) { + function cb (er) { + if (!er && !silent) console.log("v" + newVer) + cb_(er) + } + + var doGit = !er && s.isDirectory() + if (!doGit) return write(data, cb) + else checkGit(data, cb) + }) + }) +} + +function checkGit (data, cb) { + exec( npm.config.get("git"), ["status", "--porcelain"], process.env, false + , function (er, code, stdout, stderr) { + var lines = stdout.trim().split("\n").filter(function (line) { + return line.trim() && !line.match(/^\?\? /) + }).map(function (line) { + return line.trim() + }) + if (lines.length) return cb(new Error( + "Git working directory not clean.\n"+lines.join("\n"))) + write(data, function (er) { + if (er) return cb(er) + var message = npm.config.get("message").replace(/%s/g, data.version) + , sign = npm.config.get("sign-git-tag") + , flag = sign ? "-sm" : "-am" + chain + ( [ [ exec, npm.config.get("git") + , ["add","package.json"], process.env, false ] + , [ exec, npm.config.get("git") + , ["commit", "-m", message ], process.env, false ] + , [ exec, npm.config.get("git") + , ["tag", "v"+data.version, flag, message], process.env, false ] ] + , cb ) + }) + }) +} + +function write (data, cb) { + fs.writeFile( path.join(process.cwd(), "package.json") + , new Buffer(JSON.stringify(data, null, 2) + "\n") + , cb ) +} diff --git a/node-v0.8.14/deps/npm/lib/view.js b/node-v0.8.14/deps/npm/lib/view.js new file mode 100644 index 0000000..b88f98a --- /dev/null +++ b/node-v0.8.14/deps/npm/lib/view.js @@ -0,0 +1,246 @@ +// npm view [pkg [pkg ...]] + +module.exports = view +view.usage = "npm view pkg[@version] [[.subfield]...]" + +view.completion = function (opts, cb) { + if (opts.conf.argv.remain.length <= 2) { + return registry.get("/-/short", cb) + } + // have the package, get the fields. + var tag = npm.config.get("tag") + registry.get(opts.conf.argv.remain[2], function (er, d) { + if (er) return cb(er) + var dv = d.versions[d["dist-tags"][tag]] + , fields = [] + d.versions = Object.keys(d.versions).sort(semver.compare) + fields = getFields(d).concat(getFields(dv)) + cb(null, fields) + }) + + function getFields (d, f, pref) { + f = f || [] + if (!d) return f + pref = pref || [] + Object.keys(d).forEach(function (k) { + if (k.charAt(0) === "_" || k.indexOf(".") !== -1) return + var p = pref.concat(k).join(".") + f.push(p) + if (Array.isArray(d[k])) { + return d[k].forEach(function (val, i) { + var pi = p + "[" + i + "]" + if (val && typeof val === "object") getFields(val, f, [p]) + else f.push(pi) + }) + } + if (typeof d[k] === "object") getFields(d[k], f, [p]) + }) + return f + } +} + +var npm = require("./npm.js") + , registry = npm.registry + , log = require("npmlog") + , util = require("util") + , semver = require("semver") + +function view (args, silent, cb) { + if (typeof cb !== "function") cb = silent, silent = false + if (!args.length) return cb("Usage: "+view.usage) + var pkg = args.shift() + , nv = pkg.split("@") + , name = nv.shift() + , version = nv.join("@") || npm.config.get("tag") + + if (name === ".") return cb(view.usage) + + // get the data about this package + registry.get(name, 600, function (er, data) { + if (er) return cb(er) + if (data["dist-tags"].hasOwnProperty(version)) { + version = data["dist-tags"][version] + } + var results = [] + , error = null + , versions = data.versions + data.versions = Object.keys(data.versions).sort(semver.compare) + if (!args.length) args = [""] + + // remove readme unless we asked for it + if (-1 === args.indexOf("readme")) { + delete data.readme + } + + Object.keys(versions).forEach(function (v) { + if (semver.satisfies(v, version)) args.forEach(function (args) { + // remove readme unless we asked for it + if (-1 === args.indexOf("readme")) { + delete versions[v].readme + } + results.push(showFields(data, versions[v], args)) + }) + }) + results = results.reduce(reducer, {}) + var retval = results + + if (args.length === 1 && args[0] === "") { + retval = cleanBlanks(retval) + log.silly("cleanup", retval) + } + + if (error || silent) cb(error, retval) + else printData(results, data._id, cb.bind(null, error, retval)) + }) +} + +function cleanBlanks (obj) { + var clean = {} + Object.keys(obj).forEach(function (version) { + clean[version] = obj[version][""] + }) + return clean +} + +function reducer (l, r) { + if (r) Object.keys(r).forEach(function (v) { + l[v] = l[v] || {} + Object.keys(r[v]).forEach(function (t) { + l[v][t] = r[v][t] + }) + }) + return l +} + +// return whatever was printed +function showFields (data, version, fields) { + var o = {} + ;[data, version].forEach(function (s) { + Object.keys(s).forEach(function (k) { + o[k] = s[k] + }) + }) + return search(o, fields.split("."), version.version, fields) +} + +function search (data, fields, version, title) { + var field + , tail = fields + while (!field && fields.length) field = tail.shift() + fields = [field].concat(tail) + if (!field && !tail.length) { + var o = {} + o[version] = {} + o[version][title] = data + return o + } + var index = field.match(/(.+)\[([^\]]+)\]$/) + if (index) { + field = index[1] + index = index[2] + if (data.field && data.field.hasOwnProperty(index)) { + return search(data[field][index], tail, version, title) + } else { + field = field + "[" + index + "]" + } + } + if (Array.isArray(data)) { + if (data.length === 1) { + return search(data[0], fields, version, title) + } + var results = [] + , res = null + data.forEach(function (data, i) { + var tl = title.length + , newt = title.substr(0, tl-(fields.join(".").length) - 1) + + "["+i+"]" + [""].concat(fields).join(".") + results.push(search(data, fields.slice(), version, newt)) + }) + results = results.reduce(reducer, {}) + return results + } + if (!data.hasOwnProperty(field)) { + return + } + data = data[field] + if (tail.length) { + if (typeof data === "object") { + // there are more fields to deal with. + return search(data, tail, version, title) + } else { + return new Error("Not an object: "+data) + } + } + var o = {} + o[version] = {} + o[version][title] = data + return o +} + +function printData (data, name, cb) { + var versions = Object.keys(data) + , msg = "" + , showVersions = versions.length > 1 + , showFields + + versions.forEach(function (v, i) { + var fields = Object.keys(data[v]) + showFields = showFields || (fields.length > 1) + fields.forEach(function (f) { + var d = cleanup(data[v][f]) + if (showVersions || showFields || typeof d !== "string") { + d = cleanup(data[v][f]) + d = npm.config.get("json") + ? JSON.stringify(d, null, 2) + : util.inspect(d, false, 5, npm.color) + } else if (typeof d === "string" && npm.config.get("json")) { + d = JSON.stringify(d) + } + if (f && showFields) f += " = " + if (d.indexOf("\n") !== -1) d = "\n" + d + msg += (showVersions ? name + "@" + v + " " : "") + + (showFields ? f : "") + d + "\n" + }) + }) + + console.log(msg) + cb(null, data) +} +function cleanup (data) { + if (Array.isArray(data)) { + if (data.length === 1) { + data = data[0] + } else { + return data.map(cleanup) + } + } + if (!data || typeof data !== "object") return data + + if (typeof data.versions === "object" + && data.versions + && !Array.isArray(data.versions)) { + data.versions = Object.keys(data.versions || {}) + } + + var keys = Object.keys(data) + keys.forEach(function (d) { + if (d.charAt(0) === "_") delete data[d] + else if (typeof data[d] === "object") data[d] = cleanup(data[d]) + }) + keys = Object.keys(data) + if (keys.length <= 3 + && data.name + && (keys.length === 1 + || keys.length === 3 && data.email && data.url + || keys.length === 2 && (data.email || data.url))) { + data = unparsePerson(data) + } + return data +} +function unparsePerson (d) { + if (typeof d === "string") return d + return d.name + + (d.email ? " <"+d.email+">" : "") + + (d.url ? " ("+d.url+")" : "") +} + diff --git a/node-v0.8.14/deps/npm/lib/whoami.js b/node-v0.8.14/deps/npm/lib/whoami.js new file mode 100644 index 0000000..664cbdb --- /dev/null +++ b/node-v0.8.14/deps/npm/lib/whoami.js @@ -0,0 +1,13 @@ +module.exports = whoami + +var npm = require("./npm.js") + +whoami.usage = "npm whoami\n(just prints the 'username' config)" + +function whoami (args, silent, cb) { + if (typeof cb !== "function") cb = silent, silent = false + var me = npm.config.get("username") + msg = me ? me : "Not authed. Run 'npm adduser'" + if (!silent) console.log(msg) + process.nextTick(cb.bind(this, null, me)) +} diff --git a/node-v0.8.14/deps/npm/lib/xmas.js b/node-v0.8.14/deps/npm/lib/xmas.js new file mode 100644 index 0000000..bf838a8 --- /dev/null +++ b/node-v0.8.14/deps/npm/lib/xmas.js @@ -0,0 +1,56 @@ +// happy xmas +var npm = require("./npm.js") + , log = require("npmlog") + +module.exports = function (args, cb) { +var s = process.platform === "win32" ? " *" : " \u2605" + , f = "\uFF0F" + , b = "\uFF3C" + , x = process.platform === "win32" ? " " : "" + , o = [ "\u0069" , "\u0020", "\u0020", "\u0020", "\u0020", "\u0020" + , "\u0020", "\u0020", "\u0020", "\u0020", "\u0020", "\u0020" + , "\u0020", "\u2E1B","\u2042","\u2E2E","&","@","\uFF61" ] + , oc = [21,33,34,35,36,37] + , l = "\u005e" + +function w (s) { process.stderr.write(s) } + +w("\n") +;(function T (H) { + for (var i = 0; i < H; i ++) w(" ") + w(x+"\033[33m"+s+"\n") + var M = H * 2 - 1 + for (L = 1; L <= H; L ++) { + var O = L * 2 - 2 + var S = (M - O) / 2 + for (var i = 0; i < S; i ++) w(" ") + w(x+"\033[32m"+f) + for (var i = 0; i < O; i ++) w( + "\033["+oc[Math.floor(Math.random()*oc.length)]+"m"+ + o[Math.floor(Math.random() * o.length)] + ) + w(x+"\033[32m"+b+"\n") + } + w(" ") + for (var i = 1; i < H; i ++) w("\033[32m"+l) + w("| "+x+" |") + for (var i = 1; i < H; i ++) w("\033[32m"+l) + if (H > 10) { + w("\n ") + for (var i = 1; i < H; i ++) w(" ") + w("| "+x+" |") + for (var i = 1; i < H; i ++) w(" ") + } +})(20) +w("\n\n") +log.heading = '' +log.addLevel('npm', 100000, log.headingStyle) +log.npm("loves you", "Happy Xmas, Noders!") +cb() +} +var dg=false +Object.defineProperty(module.exports, "usage", {get:function () { + if (dg) module.exports([], function () {}) + dg = true + return " " +}}) diff --git a/node-v0.8.14/deps/npm/man/man1/README.1 b/node-v0.8.14/deps/npm/man/man1/README.1 new file mode 100644 index 0000000..84d6019 --- /dev/null +++ b/node-v0.8.14/deps/npm/man/man1/README.1 @@ -0,0 +1,313 @@ +.\" Generated with Ronnjs 0.3.8 +.\" http://github.com/kapouer/ronnjs/ +. +.TH "NPM" "1" "October 2012" "" "" +. +.SH "NAME" +\fBnpm\fR \-\- node package manager +. +.SH "SYNOPSIS" +This is just enough info to get you up and running\. +. +.P +Much more info available via \fBnpm help\fR once it\'s installed\. +. +.SH "IMPORTANT" +\fBYou need node v0\.6 or higher to run this program\.\fR +. +.P +To install an old \fBand unsupported\fR version of npm that works on node 0\.3 +and prior, clone the git repo and dig through the old tags and branches\. +. +.SH "Super Easy Install" +npm comes with node now\. +. +.SS "Windows Computers" +Get the MSI\. npm is in it\. +. +.SS "Apple Macintosh Computers" +Get the pkg\. npm is in it\. +. +.SS "Other Sorts of Unices" +Run \fBmake install\fR\|\. npm will be installed with node\. +. +.P +If you want a more fancy pants install (a different version, customized +paths, etc\.) then read on\. +. +.SH "Fancy Install (Unix)" +There\'s a pretty robust install script at \fIhttps://npmjs\.org/install\.sh\fR\|\. You can download that and run it\. +. +.SS "Slightly Fancier" +You can set any npm configuration params with that script: +. +.P +npm\fIconfig\fRprefix=/some/path sh install\.sh +. +.P +Or, you can run it in uber\-debuggery mode: +. +.P +npm_debug=1 sh install\.sh +. +.SS "Even Fancier" +Get the code with git\. Use \fBmake\fR to build the docs and do other stuff\. +If you plan on hacking on npm, \fBmake link\fR is your friend\. +. +.P +If you\'ve got the npm source code, you can also semi\-permanently set +arbitrary config keys using the \fB\|\./configure \-\-key=val \.\.\.\fR, and then +run npm commands by doing \fBnode cli\.js \fR\|\. (This is helpful +for testing, or running stuff without actually installing npm itself\.) +. +.SH "Fancy Windows Install" +You can download a zip file from \fIhttps://npmjs\.org/dist/\fR, and unpack it +in the same folder where node\.exe lives\. +. +.P +If that\'s not fancy enough for you, then you can fetch the code with +git, and mess with it directly\. +. +.SH "Installing on Cygwin" +No\. +. +.SH "Permissions when Using npm to Install Other Stuff" +\fBtl;dr\fR +. +.IP "\(bu" 4 +Use \fBsudo\fR for greater safety\. Or don\'t, if you prefer not to\. +. +.IP "\(bu" 4 +npm will downgrade permissions if it\'s root before running any build +scripts that package authors specified\. +. +.IP "" 0 +. +.SS "More details\.\.\." +As of version 0\.3, it is recommended to run npm as root\. +This allows npm to change the user identifier to the \fBnobody\fR user prior +to running any package build or test commands\. +. +.P +If you are not the root user, or if you are on a platform that does not +support uid switching, then npm will not attempt to change the userid\. +. +.P +If you would like to ensure that npm \fBalways\fR runs scripts as the +"nobody" user, and have it fail if it cannot downgrade permissions, then +set the following configuration param: +. +.IP "" 4 +. +.nf +npm config set unsafe\-perm false +. +.fi +. +.IP "" 0 +. +.P +This will prevent running in unsafe mode, even as non\-root users\. +. +.SH "Uninstalling" +So sad to see you go\. +. +.IP "" 4 +. +.nf +sudo npm uninstall npm \-g +. +.fi +. +.IP "" 0 +. +.P +Or, if that fails, +. +.IP "" 4 +. +.nf +sudo make uninstall +. +.fi +. +.IP "" 0 +. +.SH "More Severe Uninstalling" +Usually, the above instructions are sufficient\. That will remove +npm, but leave behind anything you\'ve installed\. +. +.P +If you would like to remove all the packages that you have installed, +then you can use the \fBnpm ls\fR command to find them, and then \fBnpm rm\fR to +remove them\. +. +.P +To remove cruft left behind by npm 0\.x, you can use the included \fBclean\-old\.sh\fR script file\. You can run it conveniently like this: +. +.IP "" 4 +. +.nf +npm explore npm \-g \-\- sh scripts/clean\-old\.sh +. +.fi +. +.IP "" 0 +. +.P +npm uses two configuration files, one for per\-user configs, and another +for global (every\-user) configs\. You can view them by doing: +. +.IP "" 4 +. +.nf +npm config get userconfig # defaults to ~/\.npmrc +npm config get globalconfig # defaults to /usr/local/etc/npmrc +. +.fi +. +.IP "" 0 +. +.P +Uninstalling npm does not remove configuration files by default\. You +must remove them yourself manually if you want them gone\. Note that +this means that future npm installs will not remember the settings that +you have chosen\. +. +.SH "Using npm Programmatically" +If you would like to use npm programmatically, you can do that\. +It\'s not very well documented, but it \fIis\fR rather simple\. +. +.P +Most of the time, unless you actually want to do all the things that +npm does, you should try using one of npm\'s dependencies rather than +using npm itself, if possible\. +. +.P +Eventually, npm will be just a thin cli wrapper around the modules +that it depends on, but for now, there are some things that you must +use npm itself to do\. +. +.IP "" 4 +. +.nf +var npm = require("npm") +npm\.load(myConfigObject, function (er) { + if (er) return handlError(er) + npm\.commands\.install(["some", "args"], function (er, data) { + if (er) return commandFailed(er) + // command succeeded, and data might have some info + }) + npm\.on("log", function (message) { \.\.\.\. }) +}) +. +.fi +. +.IP "" 0 +. +.P +The \fBload\fR function takes an object hash of the command\-line configs\. +The various \fBnpm\.commands\.\fR functions take an \fBarray\fR of +positional argument \fBstrings\fR\|\. The last argument to any \fBnpm\.commands\.\fR function is a callback\. Some commands take other +optional arguments\. Read the source\. +. +.P +You cannot set configs individually for any single npm function at this +time\. Since \fBnpm\fR is a singleton, any call to \fBnpm\.config\.set\fR will +change the value for \fIall\fR npm commands in that process\. +. +.P +See \fB\|\./bin/npm\-cli\.js\fR for an example of pulling config values off of the +command line arguments using nopt\. You may also want to check out \fBnpm +help config\fR to learn about all the options you can set there\. +. +.SH "More Docs" +Check out the docs \fIhttps://npmjs\.org/doc/\fR, +especially the faq \fIhttps://npmjs\.org/doc/faq\.html\fR\|\. +. +.P +You can use the \fBnpm help\fR command to read any of them\. +. +.P +If you\'re a developer, and you want to use npm to publish your program, +you should read this \fIhttps://npmjs\.org/doc/developers\.html\fR +. +.SH "Legal Stuff" +"npm" and "the npm registry" are owned by Isaac Z\. Schlueter\. All +rights not explicitly granted in the MIT license are reserved\. See the +included LICENSE file for more details\. +. +.P +"Node\.js" and "node" are trademarks owned by Joyent, Inc\. npm is not +officially part of the Node\.js project, and is neither owned by nor +officially affiliated with Joyent, Inc\. +. +.P +The packages in the npm registry are not part of npm itself, and are the +sole property of their respective maintainers\. While every effort is +made to ensure accountability, there is absolutely no guarantee, +warrantee, or assertion made as to the quality, fitness for a specific +purpose, or lack of malice in any given npm package\. Modules +published on the npm registry are not affiliated with or endorsed by +Joyent, Inc\., Isaac Z\. Schlueter, Ryan Dahl, or the Node\.js project\. +. +.P +If you have a complaint about a package in the npm registry, and cannot +resolve it with the package owner, please express your concerns to +Isaac Z\. Schlueter at \fIi@izs\.me\fR\|\. +. +.SS "In plain english" +This is mine; not my employer\'s, not Node\'s, not Joyent\'s, not Ryan +Dahl\'s\. +. +.P +If you publish something, it\'s yours, and you are solely accountable +for it\. Not me, not Node, not Joyent, not Ryan Dahl\. +. +.P +If other people publish something, it\'s theirs\. Not mine, not Node\'s, +not Joyent\'s, not Ryan Dahl\'s\. +. +.P +Yes, you can publish something evil\. It will be removed promptly if +reported, and we\'ll lose respect for you\. But there is no vetting +process for published modules\. +. +.P +If this concerns you, inspect the source before using packages\. +. +.SH "BUGS" +When you find issues, please report them: +. +.IP "\(bu" 4 +web: \fIhttps://github\.com/isaacs/npm/issues\fR +. +.IP "\(bu" 4 +email: \fInpm\-@googlegroups\.com\fR +. +.IP "" 0 +. +.P +Be sure to include \fIall\fR of the output from the npm command that didn\'t work +as expected\. The \fBnpm\-debug\.log\fR file is also helpful to provide\. +. +.P +You can also look for isaacs in #node\.js on irc://irc\.freenode\.net\. He +will no doubt tell you to put the output in a gist or email\. +. +.SH "SEE ALSO" +. +.IP "\(bu" 4 +npm help npm +. +.IP "\(bu" 4 +npm help faq +. +.IP "\(bu" 4 +npm help help +. +.IP "\(bu" 4 +npm help index +. +.IP "" 0 + diff --git a/node-v0.8.14/deps/npm/man/man1/adduser.1 b/node-v0.8.14/deps/npm/man/man1/adduser.1 new file mode 100644 index 0000000..16db118 --- /dev/null +++ b/node-v0.8.14/deps/npm/man/man1/adduser.1 @@ -0,0 +1,57 @@ +.\" Generated with Ronnjs 0.3.8 +.\" http://github.com/kapouer/ronnjs/ +. +.TH "NPM\-ADDUSER" "1" "October 2012" "" "" +. +.SH "NAME" +\fBnpm-adduser\fR \-\- Add a registry user account +. +.SH "SYNOPSIS" +. +.nf +npm adduser +. +.fi +. +.SH "DESCRIPTION" +Create or verify a user named \fB\fR in the npm registry, and +save the credentials to the \fB\|\.npmrc\fR file\. +. +.P +The username, password, and email are read in from prompts\. +. +.P +You may use this command to change your email address, but not username +or password\. +. +.P +To reset your password, go to \fIhttp://admin\.npmjs\.org/\fR +. +.P +You may use this command multiple times with the same user account to +authorize on a new machine\. +. +.SH "CONFIGURATION" +. +.SS "registry" +Default: http://registry\.npmjs\.org/ +. +.P +The base URL of the npm package registry\. +. +.SH "SEE ALSO" +. +.IP "\(bu" 4 +npm help registry +. +.IP "\(bu" 4 +npm help config +. +.IP "\(bu" 4 +npm help owner +. +.IP "\(bu" 4 +npm help whoami +. +.IP "" 0 + diff --git a/node-v0.8.14/deps/npm/man/man1/author.1 b/node-v0.8.14/deps/npm/man/man1/author.1 new file mode 100644 index 0000000..6373c3e --- /dev/null +++ b/node-v0.8.14/deps/npm/man/man1/author.1 @@ -0,0 +1,55 @@ +.\" Generated with Ronnjs/v0.1 +.\" http://github.com/kapouer/ronnjs/ +. +.TH "NPM\-OWNER" "1" "November 2011" "" "" +. +.SH "NAME" +\fBnpm-owner\fR \-\- Manage package owners +. +.SH "SYNOPSIS" +. +.nf +npm owner ls +npm owner add +npm owner rm +. +.fi +. +.SH "DESCRIPTION" +Manage ownership of published packages\. +. +.IP "\(bu" 4 +ls: +List all the users who have access to modify a package and push new versions\. +Handy when you need to know who to bug for help\. +. +.IP "\(bu" 4 +add: +Add a new user as a maintainer of a package\. This user is enabled to modify +metadata, publish new versions, and add other owners\. +. +.IP "\(bu" 4 +rm: +Remove a user from the package owner list\. This immediately revokes their +privileges\. +. +.IP "" 0 +. +.P +Note that there is only one level of access\. Either you can modify a package, +or you can\'t\. Future versions may contain more fine\-grained access levels, but +that is not implemented at this time\. +. +.SH "SEE ALSO" +. +.IP "\(bu" 4 +npm help publish +. +.IP "\(bu" 4 +npm help registry +. +.IP "\(bu" 4 +npm help adduser +. +.IP "" 0 + diff --git a/node-v0.8.14/deps/npm/man/man1/bin.1 b/node-v0.8.14/deps/npm/man/man1/bin.1 new file mode 100644 index 0000000..7fde544 --- /dev/null +++ b/node-v0.8.14/deps/npm/man/man1/bin.1 @@ -0,0 +1,34 @@ +.\" Generated with Ronnjs 0.3.8 +.\" http://github.com/kapouer/ronnjs/ +. +.TH "NPM\-BIN" "1" "October 2012" "" "" +. +.SH "NAME" +\fBnpm-bin\fR \-\- Display npm bin folder +. +.SH "SYNOPSIS" +. +.nf +npm bin +. +.fi +. +.SH "DESCRIPTION" +Print the folder where npm will install executables\. +. +.SH "SEE ALSO" +. +.IP "\(bu" 4 +npm help prefix +. +.IP "\(bu" 4 +npm help root +. +.IP "\(bu" 4 +npm help folders +. +.IP "\(bu" 4 +npm help config +. +.IP "" 0 + diff --git a/node-v0.8.14/deps/npm/man/man1/bugs.1 b/node-v0.8.14/deps/npm/man/man1/bugs.1 new file mode 100644 index 0000000..68d24ab --- /dev/null +++ b/node-v0.8.14/deps/npm/man/man1/bugs.1 @@ -0,0 +1,70 @@ +.\" Generated with Ronnjs 0.3.8 +.\" http://github.com/kapouer/ronnjs/ +. +.TH "NPM\-BUGS" "1" "October 2012" "" "" +. +.SH "NAME" +\fBnpm-bugs\fR \-\- Bugs for a package in a web browser maybe +. +.SH "SYNOPSIS" +. +.nf +npm bugs +. +.fi +. +.SH "DESCRIPTION" +This command tries to guess at the likely location of a package\'s +bug tracker URL, and then tries to open it using the \fB\-\-browser\fR +config param\. +. +.SH "CONFIGURATION" +. +.SS "browser" +. +.IP "\(bu" 4 +Default: OS X: \fB"open"\fR, others: \fB"google\-chrome"\fR +. +.IP "\(bu" 4 +Type: String +. +.IP "" 0 +. +.P +The browser that is called by the \fBnpm bugs\fR command to open websites\. +. +.SS "registry" +. +.IP "\(bu" 4 +Default: https://registry\.npmjs\.org/ +. +.IP "\(bu" 4 +Type: url +. +.IP "" 0 +. +.P +The base URL of the npm package registry\. +. +.SH "SEE ALSO" +. +.IP "\(bu" 4 +npm help docs +. +.IP "\(bu" 4 +npm help view +. +.IP "\(bu" 4 +npm help publish +. +.IP "\(bu" 4 +npm help registry +. +.IP "\(bu" 4 +npm help config +. +.IP "\(bu" 4 +npm help json +. +.IP "" 0 + diff --git a/node-v0.8.14/deps/npm/man/man1/build.1 b/node-v0.8.14/deps/npm/man/man1/build.1 new file mode 100644 index 0000000..921ed62 --- /dev/null +++ b/node-v0.8.14/deps/npm/man/man1/build.1 @@ -0,0 +1,43 @@ +.\" Generated with Ronnjs 0.3.8 +.\" http://github.com/kapouer/ronnjs/ +. +.TH "NPM\-BUILD" "1" "October 2012" "" "" +. +.SH "NAME" +\fBnpm-build\fR \-\- Build a package +. +.SH "SYNOPSIS" +. +.nf +npm build +. +.fi +. +.IP "\(bu" 4 +\fB\fR: +A folder containing a \fBpackage\.json\fR file in its root\. +. +.IP "" 0 +. +.SH "DESCRIPTION" +This is the plumbing command called by \fBnpm link\fR and \fBnpm install\fR\|\. +. +.P +It should generally not be called directly\. +. +.SH "SEE ALSO" +. +.IP "\(bu" 4 +npm help install +. +.IP "\(bu" 4 +npm help link +. +.IP "\(bu" 4 +npm help scripts +. +.IP "\(bu" 4 +npm help json +. +.IP "" 0 + diff --git a/node-v0.8.14/deps/npm/man/man1/bundle.1 b/node-v0.8.14/deps/npm/man/man1/bundle.1 new file mode 100644 index 0000000..6391e37 --- /dev/null +++ b/node-v0.8.14/deps/npm/man/man1/bundle.1 @@ -0,0 +1,23 @@ +.\" Generated with Ronnjs 0.3.8 +.\" http://github.com/kapouer/ronnjs/ +. +.TH "NPM\-BUNDLE" "1" "October 2012" "" "" +. +.SH "NAME" +\fBnpm-bundle\fR \-\- REMOVED +. +.SH "DESCRIPTION" +The \fBnpm bundle\fR command has been removed in 1\.0, for the simple reason +that it is no longer necessary, as the default behavior is now to +install packages into the local space\. +. +.P +Just use \fBnpm install\fR now to do what \fBnpm bundle\fR used to do\. +. +.SH "SEE ALSO" +. +.IP "\(bu" 4 +npm help install +. +.IP "" 0 + diff --git a/node-v0.8.14/deps/npm/man/man1/cache.1 b/node-v0.8.14/deps/npm/man/man1/cache.1 new file mode 100644 index 0000000..83b4767 --- /dev/null +++ b/node-v0.8.14/deps/npm/man/man1/cache.1 @@ -0,0 +1,97 @@ +.\" Generated with Ronnjs 0.3.8 +.\" http://github.com/kapouer/ronnjs/ +. +.TH "NPM\-CACHE" "1" "October 2012" "" "" +. +.SH "NAME" +\fBnpm-cache\fR \-\- Manipulates packages cache +. +.SH "SYNOPSIS" +. +.nf +npm cache add +npm cache add +npm cache add +npm cache add @ +npm cache ls [] +npm cache clean [] +. +.fi +. +.SH "DESCRIPTION" +Used to add, list, or clear the npm cache folder\. +. +.IP "\(bu" 4 +add: +Add the specified package to the local cache\. This command is primarily +intended to be used internally by npm, but it can provide a way to +add data to the local installation cache explicitly\. +. +.IP "\(bu" 4 +ls: +Show the data in the cache\. Argument is a path to show in the cache +folder\. Works a bit like the \fBfind\fR program, but limited by the \fBdepth\fR config\. +. +.IP "\(bu" 4 +clean: +Delete data out of the cache folder\. If an argument is provided, then +it specifies a subpath to delete\. If no argument is provided, then +the entire cache is cleared\. +. +.IP "" 0 +. +.SH "DETAILS" +npm stores cache data in \fB$HOME/\.npm\fR\|\. For each package that is added +to the cache, three pieces of information are stored in \fB{cache}/{name}/{version}\fR: +. +.IP "\(bu" 4 +\|\.\.\./package/: +A folder containing the package contents as they appear in the tarball\. +. +.IP "\(bu" 4 +\|\.\.\./package\.json: +The package\.json file, as npm sees it, with overlays applied and a _id attribute\. +. +.IP "\(bu" 4 +\|\.\.\./package\.tgz: +The tarball for that version\. +. +.IP "" 0 +. +.P +Additionally, whenever a registry request is made, a \fB\|\.cache\.json\fR file +is placed at the corresponding URI, to store the ETag and the requested +data\. +. +.P +Commands that make non\-essential registry requests (such as \fBsearch\fR and \fBview\fR, or the completion scripts) generally specify a minimum timeout\. +If the \fB\|\.cache\.json\fR file is younger than the specified timeout, then +they do not make an HTTP request to the registry\. +. +.SH "CONFIGURATION" +. +.SS "cache" +Default: \fB$HOME/\.npm\fR on Posix, or \fB$HOME/npm\-cache\fR on Windows\. +. +.P +The root cache folder\. +. +.SH "SEE ALSO" +. +.IP "\(bu" 4 +npm help folders +. +.IP "\(bu" 4 +npm help config +. +.IP "\(bu" 4 +npm help install +. +.IP "\(bu" 4 +npm help publish +. +.IP "\(bu" 4 +npm help pack +. +.IP "" 0 + diff --git a/node-v0.8.14/deps/npm/man/man1/changelog.1 b/node-v0.8.14/deps/npm/man/man1/changelog.1 new file mode 100644 index 0000000..74e2834 --- /dev/null +++ b/node-v0.8.14/deps/npm/man/man1/changelog.1 @@ -0,0 +1,173 @@ +.\" Generated with Ronnjs 0.3.8 +.\" http://github.com/kapouer/ronnjs/ +. +.TH "NPM\-CHANGELOG" "1" "October 2012" "" "" +. +.SH "NAME" +\fBnpm-changelog\fR \-\- Changes +. +.SH "HISTORY" +. +.SS "1\.1\.3, 1\.1\.4" +. +.IP "\(bu" 4 +Update request to support HTTPS\-over\-HTTP proxy tunneling +. +.IP "\(bu" 4 +Throw on undefined envs in config settings +. +.IP "\(bu" 4 +Update which to 1\.0\.5 +. +.IP "\(bu" 4 +Fix windows UNC busyloop in findPrefix +. +.IP "\(bu" 4 +Bundle nested bundleDependencies properly +. +.IP "\(bu" 4 +Alias adduser to add\-user +. +.IP "\(bu" 4 +Doc updates (Christian Howe, Henrik Hodne, Andrew Lunny) +. +.IP "\(bu" 4 +ignore logfd/outfd streams in makeEnv() (Rod Vagg) +. +.IP "\(bu" 4 +shrinkwrap: Behave properly with url\-installed deps +. +.IP "\(bu" 4 +install: Support \-\-save with url install targets +. +.IP "\(bu" 4 +Support installing naked tars or single\-file modules from urls etc\. +. +.IP "\(bu" 4 +init: Don\'t add engines section +. +.IP "\(bu" 4 +Don\'t run make clean on rebuild +. +.IP "\(bu" 4 +Added missing unicode replacement (atomizer) +. +.IP "" 0 +. +.SS "1\.1\.2" +Dave Pacheco (2): + add "npm shrinkwrap" +. +.P +Martin Cooper (1): + Fix #1753 Make a copy of the cached objects we\'ll modify\. +. +.P +Tim Oxley (1): + correctly remove readme from default npm view command\. +. +.P +Tyler Green (1): + fix #2187 set terminal columns to Infinity if 0 +. +.P +isaacs (19): + update minimatch + update request + Experimental: single\-file modules + Fix #2172 Don\'t remove global mans uninstalling local pkgs + Add \-\-versions flag to show the version of node as well + Support \-\-json flag for ls output + update request to 2\.9\.151 +. +.SS "1\.1" +. +.IP "\(bu" 4 +Replace system tar dependency with a JS tar +. +.IP "\(bu" 4 +Continue to refine +. +.IP "" 0 +. +.SS "1\.0" +. +.IP "\(bu" 4 +Greatly simplified folder structure +. +.IP "\(bu" 4 +Install locally (bundle by default) +. +.IP "\(bu" 4 +Drastic rearchitecture +. +.IP "" 0 +. +.SS "0\.3" +. +.IP "\(bu" 4 +More correct permission/uid handling when running as root +. +.IP "\(bu" 4 +Require node 0\.4\.0 +. +.IP "\(bu" 4 +Reduce featureset +. +.IP "\(bu" 4 +Packages without "main" modules don\'t export modules +. +.IP "\(bu" 4 +Remove support for invalid JSON (since node doesn\'t support it) +. +.IP "" 0 +. +.SS "0\.2" +. +.IP "\(bu" 4 +First allegedly "stable" release +. +.IP "\(bu" 4 +Most functionality implemented +. +.IP "\(bu" 4 +Used shim files and \fBname@version\fR symlinks +. +.IP "\(bu" 4 +Feature explosion +. +.IP "\(bu" 4 +Kind of a mess +. +.IP "" 0 +. +.SS "0\.1" +. +.IP "\(bu" 4 +push to beta, and announce +. +.IP "\(bu" 4 +Solaris and Cygwin support +. +.IP "" 0 +. +.SS "0\.0" +. +.IP "\(bu" 4 +Lots of sketches and false starts; abandoned a few times +. +.IP "\(bu" 4 +Core functionality established +. +.IP "" 0 +. +.SH "SEE ALSO" +. +.IP "\(bu" 4 +npm help npm +. +.IP "\(bu" 4 +npm help faq +. +.IP "" 0 + diff --git a/node-v0.8.14/deps/npm/man/man1/coding-style.1 b/node-v0.8.14/deps/npm/man/man1/coding-style.1 new file mode 100644 index 0000000..bcb395c --- /dev/null +++ b/node-v0.8.14/deps/npm/man/man1/coding-style.1 @@ -0,0 +1,251 @@ +.\" Generated with Ronnjs 0.3.8 +.\" http://github.com/kapouer/ronnjs/ +. +.TH "NPM\-CODING\-STYLE" "1" "October 2012" "" "" +. +.SH "NAME" +\fBnpm-coding-style\fR \-\- npm\'s "funny" coding style +. +.SH "DESCRIPTION" +npm\'s coding style is a bit unconventional\. It is not different for +difference\'s sake, but rather a carefully crafted style that is +designed to reduce visual clutter and make bugs more apparent\. +. +.P +If you want to contribute to npm (which is very encouraged), you should +make your code conform to npm\'s style\. +. +.SH "Line Length" +Keep lines shorter than 80 characters\. It\'s better for lines to be +too short than to be too long\. Break up long lists, objects, and other +statements onto multiple lines\. +. +.SH "Indentation" +Two\-spaces\. Tabs are better, but they look like hell in web browsers +(and on github), and node uses 2 spaces, so that\'s that\. +. +.P +Configure your editor appropriately\. +. +.SH "Curly braces" +Curly braces belong on the same line as the thing that necessitates them\. +. +.P +Bad: +. +.IP "" 4 +. +.nf +function () +{ +. +.fi +. +.IP "" 0 +. +.P +Good: +. +.IP "" 4 +. +.nf +function () { +. +.fi +. +.IP "" 0 +. +.P +If a block needs to wrap to the next line, use a curly brace\. Don\'t +use it if it doesn\'t\. +. +.P +Bad: +. +.IP "" 4 +. +.nf +if (foo) { bar() } +while (foo) + bar() +. +.fi +. +.IP "" 0 +. +.P +Good: +. +.IP "" 4 +. +.nf +if (foo) bar() +while (foo) { + bar() +} +. +.fi +. +.IP "" 0 +. +.SH "Semicolons" +Don\'t use them except in four situations: +. +.IP "\(bu" 4 +\fBfor (;;)\fR loops\. They\'re actually required\. +. +.IP "\(bu" 4 +null loops like: \fBwhile (something) ;\fR (But you\'d better have a good +reason for doing that\.) +. +.IP "\(bu" 4 +\fBcase "foo": doSomething(); break\fR +. +.IP "\(bu" 4 +In front of a leading \fB(\fR or \fB[\fR at the start of the line\. +This prevents the expression from being interpreted +as a function call or property access, respectively\. +. +.IP "" 0 +. +.P +Some examples of good semicolon usage: +. +.IP "" 4 +. +.nf +;(x || y)\.doSomething() +;[a, b, c]\.forEach(doSomething) +for (var i = 0; i < 10; i ++) { + switch (state) { + case "begin": start(); continue + case "end": finish(); break + default: throw new Error("unknown state") + } + end() +} +. +.fi +. +.IP "" 0 +. +.P +Note that starting lines with \fB\-\fR and \fB+\fR also should be prefixed +with a semicolon, but this is much less common\. +. +.SH "Comma First" +If there is a list of things separated by commas, and it wraps +across multiple lines, put the comma at the start of the next +line, directly below the token that starts the list\. Put the +final token in the list on a line by itself\. For example: +. +.IP "" 4 +. +.nf +var magicWords = [ "abracadabra" + , "gesundheit" + , "ventrilo" + ] + , spells = { "fireball" : function () { setOnFire() } + , "water" : function () { putOut() } + } + , a = 1 + , b = "abc" + , etc + , somethingElse +. +.fi +. +.IP "" 0 +. +.SH "Whitespace" +Put a single space in front of ( for anything other than a function call\. +Also use a single space wherever it makes things more readable\. +. +.P +Don\'t leave trailing whitespace at the end of lines\. Don\'t indent empty +lines\. Don\'t use more spaces than are helpful\. +. +.SH "Functions" +Use named functions\. They make stack traces a lot easier to read\. +. +.SH "Callbacks, Sync/async Style" +Use the asynchronous/non\-blocking versions of things as much as possible\. +It might make more sense for npm to use the synchronous fs APIs, but this +way, the fs and http and child process stuff all uses the same callback\-passing +methodology\. +. +.P +The callback should always be the last argument in the list\. Its first +argument is the Error or null\. +. +.P +Be very careful never to ever ever throw anything\. It\'s worse than useless\. +Just send the error message back as the first argument to the callback\. +. +.SH "Errors" +Always create a new Error object with your message\. Don\'t just return a +string message to the callback\. Stack traces are handy\. +. +.SH "Logging" +Logging is done using the npmlog \fIhttps://github\.com/isaacs/npmlog\fR +utility\. +. +.P +Please clean up logs when they are no longer helpful\. In particular, +logging the same object over and over again is not helpful\. Logs should +report what\'s happening so that it\'s easier to track down where a fault +occurs\. +. +.P +Use appropriate log levels\. See \fBnpm help config\fR and search for +"loglevel"\. +. +.SH "Case, naming, etc\." +Use \fBlowerCamelCase\fR for multiword identifiers when they refer to objects, +functions, methods, members, or anything not specified in this section\. +. +.P +Use \fBUpperCamelCase\fR for class names (things that you\'d pass to "new")\. +. +.P +Use \fBall\-lower\-hyphen\-css\-case\fR for multiword filenames and config keys\. +. +.P +Use named functions\. They make stack traces easier to follow\. +. +.P +Use \fBCAPS_SNAKE_CASE\fR for constants, things that should never change +and are rarely used\. +. +.P +Use a single uppercase letter for function names where the function +would normally be anonymous, but needs to call itself recursively\. It +makes it clear that it\'s a "throwaway" function\. +. +.SH "null, undefined, false, 0" +Boolean variables and functions should always be either \fBtrue\fR or \fBfalse\fR\|\. Don\'t set it to 0 unless it\'s supposed to be a number\. +. +.P +When something is intentionally missing or removed, set it to \fBnull\fR\|\. +. +.P +Don\'t set things to \fBundefined\fR\|\. Reserve that value to mean "not yet +set to anything\." +. +.P +Boolean objects are verboten\. +. +.SH "SEE ALSO" +. +.IP "\(bu" 4 +npm help developers +. +.IP "\(bu" 4 +npm help faq +. +.IP "\(bu" 4 +npm help npm +. +.IP "" 0 + diff --git a/node-v0.8.14/deps/npm/man/man1/completion.1 b/node-v0.8.14/deps/npm/man/man1/completion.1 new file mode 100644 index 0000000..4ad3571 --- /dev/null +++ b/node-v0.8.14/deps/npm/man/man1/completion.1 @@ -0,0 +1,47 @@ +.\" Generated with Ronnjs 0.3.8 +.\" http://github.com/kapouer/ronnjs/ +. +.TH "NPM\-COMPLETION" "1" "October 2012" "" "" +. +.SH "NAME" +\fBnpm-completion\fR \-\- Tab Completion for npm +. +.SH "SYNOPSIS" +. +.nf +\|\. <(npm completion) +. +.fi +. +.SH "DESCRIPTION" +Enables tab\-completion in all npm commands\. +. +.P +The synopsis above +loads the completions into your current shell\. Adding it to +your ~/\.bashrc or ~/\.zshrc will make the completions available +everywhere\. +. +.P +You may of course also pipe the output of npm completion to a file +such as \fB/usr/local/etc/bash_completion\.d/npm\fR if you have a system +that will read that file for you\. +. +.P +When \fBCOMP_CWORD\fR, \fBCOMP_LINE\fR, and \fBCOMP_POINT\fR are defined in the +environment, \fBnpm completion\fR acts in "plumbing mode", and outputs +completions based on the arguments\. +. +.SH "SEE ALSO" +. +.IP "\(bu" 4 +npm help developers +. +.IP "\(bu" 4 +npm help faq +. +.IP "\(bu" 4 +npm help npm +. +.IP "" 0 + diff --git a/node-v0.8.14/deps/npm/man/man1/config.1 b/node-v0.8.14/deps/npm/man/man1/config.1 new file mode 100644 index 0000000..15eaec2 --- /dev/null +++ b/node-v0.8.14/deps/npm/man/man1/config.1 @@ -0,0 +1,1479 @@ +.\" Generated with Ronnjs 0.3.8 +.\" http://github.com/kapouer/ronnjs/ +. +.TH "NPM\-CONFIG" "1" "October 2012" "" "" +. +.SH "NAME" +\fBnpm-config\fR \-\- Manage the npm configuration file +. +.SH "SYNOPSIS" +. +.nf +npm config set [\-\-global] +npm config get +npm config delete +npm config list +npm config edit +npm get +npm set [\-\-global] +. +.fi +. +.SH "DESCRIPTION" +npm gets its configuration values from 6 sources, in this priority: +. +.SS "Command Line Flags" +Putting \fB\-\-foo bar\fR on the command line sets the \fBfoo\fR configuration parameter to \fB"bar"\fR\|\. A \fB\-\-\fR argument tells the cli +parser to stop reading flags\. A \fB\-\-flag\fR parameter that is at the \fIend\fR of +the command will be given the value of \fBtrue\fR\|\. +. +.SS "Environment Variables" +Any environment variables that start with \fBnpm_config_\fR will be interpreted +as a configuration parameter\. For example, putting \fBnpm_config_foo=bar\fR in +your environment will set the \fBfoo\fR configuration parameter to \fBbar\fR\|\. Any +environment configurations that are not given a value will be given the value +of \fBtrue\fR\|\. Config values are case\-insensitive, so \fBNPM_CONFIG_FOO=bar\fR will +work the same\. +. +.SS "Per\-user config file" +\fB$HOME/\.npmrc\fR (or the \fBuserconfig\fR param, if set above) +. +.P +This file is an ini\-file formatted list of \fBkey = value\fR parameters\. +. +.SS "Global config file" +\fB$PREFIX/etc/npmrc\fR (or the \fBglobalconfig\fR param, if set above): +This file is an ini\-file formatted list of \fBkey = value\fR parameters +. +.SS "Built\-in config file" +\fBpath/to/npm/itself/npmrc\fR +. +.P +This is an unchangeable "builtin" +configuration file that npm keeps consistent across updates\. Set +fields in here using the \fB\|\./configure\fR script that comes with npm\. +This is primarily for distribution maintainers to override default +configs in a standard and consistent manner\. +. +.SS "Default Configs" +A set of configuration parameters that are internal to npm, and are +defaults if nothing else is specified\. +. +.SH "Sub\-commands" +Config supports the following sub\-commands: +. +.SS "set" +. +.nf +npm config set key value +. +.fi +. +.P +Sets the config key to the value\. +. +.P +If value is omitted, then it sets it to "true"\. +. +.SS "get" +. +.nf +npm config get key +. +.fi +. +.P +Echo the config value to stdout\. +. +.SS "list" +. +.nf +npm config list +. +.fi +. +.P +Show all the config settings\. +. +.SS "delete" +. +.nf +npm config delete key +. +.fi +. +.P +Deletes the key from all configuration files\. +. +.SS "edit" +. +.nf +npm config edit +. +.fi +. +.P +Opens the config file in an editor\. Use the \fB\-\-global\fR flag to edit the +global config\. +. +.SH "Shorthands and Other CLI Niceties" +The following shorthands are parsed on the command\-line: +. +.IP "\(bu" 4 +\fB\-v\fR: \fB\-\-version\fR +. +.IP "\(bu" 4 +\fB\-h\fR, \fB\-?\fR, \fB\-\-help\fR, \fB\-H\fR: \fB\-\-usage\fR +. +.IP "\(bu" 4 +\fB\-s\fR, \fB\-\-silent\fR: \fB\-\-loglevel silent\fR +. +.IP "\(bu" 4 +\fB\-q\fR, \fB\-\-quiet\fR: \fB\-\-loglevel warn\fR +. +.IP "\(bu" 4 +\fB\-d\fR: \fB\-\-loglevel info\fR +. +.IP "\(bu" 4 +\fB\-dd\fR, \fB\-\-verbose\fR: \fB\-\-loglevel verbose\fR +. +.IP "\(bu" 4 +\fB\-ddd\fR: \fB\-\-loglevel silly\fR +. +.IP "\(bu" 4 +\fB\-g\fR: \fB\-\-global\fR +. +.IP "\(bu" 4 +\fB\-l\fR: \fB\-\-long\fR +. +.IP "\(bu" 4 +\fB\-m\fR: \fB\-\-message\fR +. +.IP "\(bu" 4 +\fB\-p\fR, \fB\-\-porcelain\fR: \fB\-\-parseable\fR +. +.IP "\(bu" 4 +\fB\-reg\fR: \fB\-\-registry\fR +. +.IP "\(bu" 4 +\fB\-v\fR: \fB\-\-version\fR +. +.IP "\(bu" 4 +\fB\-f\fR: \fB\-\-force\fR +. +.IP "\(bu" 4 +\fB\-desc\fR: \fB\-\-description\fR +. +.IP "\(bu" 4 +\fB\-S\fR: \fB\-\-save\fR +. +.IP "\(bu" 4 +\fB\-D\fR: \fB\-\-save\-dev\fR +. +.IP "\(bu" 4 +\fB\-O\fR: \fB\-\-save\-optional\fR +. +.IP "\(bu" 4 +\fB\-B\fR: \fB\-\-save\-bundle\fR +. +.IP "\(bu" 4 +\fB\-y\fR: \fB\-\-yes\fR +. +.IP "\(bu" 4 +\fB\-n\fR: \fB\-\-yes false\fR +. +.IP "\(bu" 4 +\fBll\fR and \fBla\fR commands: \fBls \-\-long\fR +. +.IP "" 0 +. +.P +If the specified configuration param resolves unambiguously to a known +configuration parameter, then it is expanded to that configuration +parameter\. For example: +. +.IP "" 4 +. +.nf +npm ls \-\-par +# same as: +npm ls \-\-parseable +. +.fi +. +.IP "" 0 +. +.P +If multiple single\-character shorthands are strung together, and the +resulting combination is unambiguously not some other configuration +param, then it is expanded to its various component pieces\. For +example: +. +.IP "" 4 +. +.nf +npm ls \-gpld +# same as: +npm ls \-\-global \-\-parseable \-\-long \-\-loglevel info +. +.fi +. +.IP "" 0 +. +.SH "Per\-Package Config Settings" +When running scripts (see \fBnpm help scripts\fR) +the package\.json "config" keys are overwritten in the environment if +there is a config param of \fB[@]:\fR\|\. For example, if +the package\.json has this: +. +.IP "" 4 +. +.nf +{ "name" : "foo" +, "config" : { "port" : "8080" } +, "scripts" : { "start" : "node server\.js" } } +. +.fi +. +.IP "" 0 +. +.P +and the server\.js is this: +. +.IP "" 4 +. +.nf +http\.createServer(\.\.\.)\.listen(process\.env\.npm_package_config_port) +. +.fi +. +.IP "" 0 +. +.P +then the user could change the behavior by doing: +. +.IP "" 4 +. +.nf +npm config set foo:port 80 +. +.fi +. +.IP "" 0 +. +.SH "Config Settings" +. +.SS "always\-auth" +. +.IP "\(bu" 4 +Default: false +. +.IP "\(bu" 4 +Type: Boolean +. +.IP "" 0 +. +.P +Force npm to always require authentication when accessing the registry, +even for \fBGET\fR requests\. +. +.SS "browser" +. +.IP "\(bu" 4 +Default: OS X: \fB"open"\fR, others: \fB"google\-chrome"\fR +. +.IP "\(bu" 4 +Type: String +. +.IP "" 0 +. +.P +The browser that is called by the \fBnpm docs\fR command to open websites\. +. +.SS "ca" +. +.IP "\(bu" 4 +Default: The npm CA certificate +. +.IP "\(bu" 4 +Type: String or null +. +.IP "" 0 +. +.P +The Certificate Authority signing certificate that is trusted for SSL +connections to the registry\. +. +.P +Set to \fBnull\fR to only allow "known" registrars, or to a specific CA cert +to trust only that specific signing authority\. +. +.P +See also the \fBstrict\-ssl\fR config\. +. +.SS "cache" +. +.IP "\(bu" 4 +Default: Windows: \fB%APPDATA%\\npm\-cache\fR, Posix: \fB~/\.npm\fR +. +.IP "\(bu" 4 +Type: path +. +.IP "" 0 +. +.P +The location of npm\'s cache directory\. See \fBnpm help cache\fR +. +.SS "cache\-lock\-stale" +. +.IP "\(bu" 4 +Default: 60000 (1 minute) +. +.IP "\(bu" 4 +Type: Number +. +.IP "" 0 +. +.P +The number of ms before cache folder lockfiles are considered stale\. +. +.SS "cache\-lock\-retries" +. +.IP "\(bu" 4 +Default: 10 +. +.IP "\(bu" 4 +Type: Number +. +.IP "" 0 +. +.P +Number of times to retry to acquire a lock on cache folder lockfiles\. +. +.SS "cache\-lock\-wait" +. +.IP "\(bu" 4 +Default: 10000 (10 seconds) +. +.IP "\(bu" 4 +Type: Number +. +.IP "" 0 +. +.P +Number of ms to wait for cache lock files to expire\. +. +.SS "cache\-max" +. +.IP "\(bu" 4 +Default: Infinity +. +.IP "\(bu" 4 +Type: Number +. +.IP "" 0 +. +.P +The maximum time (in seconds) to keep items in the registry cache before +re\-checking against the registry\. +. +.P +Note that no purging is done unless the \fBnpm cache clean\fR command is +explicitly used, and that only GET requests use the cache\. +. +.SS "cache\-min" +. +.IP "\(bu" 4 +Default: 0 +. +.IP "\(bu" 4 +Type: Number +. +.IP "" 0 +. +.P +The minimum time (in seconds) to keep items in the registry cache before +re\-checking against the registry\. +. +.P +Note that no purging is done unless the \fBnpm cache clean\fR command is +explicitly used, and that only GET requests use the cache\. +. +.SS "color" +. +.IP "\(bu" 4 +Default: true on Posix, false on Windows +. +.IP "\(bu" 4 +Type: Boolean or \fB"always"\fR +. +.IP "" 0 +. +.P +If false, never shows colors\. If \fB"always"\fR then always shows colors\. +If true, then only prints color codes for tty file descriptors\. +. +.SS "coverage" +. +.IP "\(bu" 4 +Default: false +. +.IP "\(bu" 4 +Type: Boolean +. +.IP "" 0 +. +.P +A flag to tell test\-harness to run with their coverage options enabled, +if they respond to the \fBnpm_config_coverage\fR environment variable\. +. +.SS "depth" +. +.IP "\(bu" 4 +Default: Infinity +. +.IP "\(bu" 4 +Type: Number +. +.IP "" 0 +. +.P +The depth to go when recursing directories for \fBnpm ls\fR and \fBnpm cache ls\fR\|\. +. +.SS "description" +. +.IP "\(bu" 4 +Default: true +. +.IP "\(bu" 4 +Type: Boolean +. +.IP "" 0 +. +.P +Show the description in \fBnpm search\fR +. +.SS "dev" +. +.IP "\(bu" 4 +Default: false +. +.IP "\(bu" 4 +Type: Boolean +. +.IP "" 0 +. +.P +Install \fBdev\-dependencies\fR along with packages\. +. +.P +Note that \fBdev\-dependencies\fR are also installed if the \fBnpat\fR flag is +set\. +. +.SS "editor" +. +.IP "\(bu" 4 +Default: \fBEDITOR\fR environment variable if set, or \fB"vi"\fR on Posix, +or \fB"notepad"\fR on Windows\. +. +.IP "\(bu" 4 +Type: path +. +.IP "" 0 +. +.P +The command to run for \fBnpm edit\fR or \fBnpm config edit\fR\|\. +. +.SS "engine\-strict" +. +.IP "\(bu" 4 +Default: false +. +.IP "\(bu" 4 +Type: Boolean +. +.IP "" 0 +. +.P +If set to true, then npm will stubbornly refuse to install (or even +consider installing) any package that claims to not be compatible with +the current Node\.js version\. +. +.SS "force" +. +.IP "\(bu" 4 +Default: false +. +.IP "\(bu" 4 +Type: Boolean +. +.IP "" 0 +. +.P +Makes various commands more forceful\. +. +.IP "\(bu" 4 +lifecycle script failure does not block progress\. +. +.IP "\(bu" 4 +publishing clobbers previously published versions\. +. +.IP "\(bu" 4 +skips cache when requesting from the registry\. +. +.IP "\(bu" 4 +prevents checks against clobbering non\-npm files\. +. +.IP "" 0 +. +.SS "fetch\-retries" +. +.IP "\(bu" 4 +Default: 2 +. +.IP "\(bu" 4 +Type: Number +. +.IP "" 0 +. +.P +The "retries" config for the \fBretry\fR module to use when fetching +packages from the registry\. +. +.SS "fetch\-retry\-factor" +. +.IP "\(bu" 4 +Default: 10 +. +.IP "\(bu" 4 +Type: Number +. +.IP "" 0 +. +.P +The "factor" config for the \fBretry\fR module to use when fetching +packages\. +. +.SS "fetch\-retry\-mintimeout" +. +.IP "\(bu" 4 +Default: 10000 (10 seconds) +. +.IP "\(bu" 4 +Type: Number +. +.IP "" 0 +. +.P +The "minTimeout" config for the \fBretry\fR module to use when fetching +packages\. +. +.SS "fetch\-retry\-maxtimeout" +. +.IP "\(bu" 4 +Default: 60000 (1 minute) +. +.IP "\(bu" 4 +Type: Number +. +.IP "" 0 +. +.P +The "maxTimeout" config for the \fBretry\fR module to use when fetching +packages\. +. +.SS "git" +. +.IP "\(bu" 4 +Default: \fB"git"\fR +. +.IP "\(bu" 4 +Type: String +. +.IP "" 0 +. +.P +The command to use for git commands\. If git is installed on the +computer, but is not in the \fBPATH\fR, then set this to the full path to +the git binary\. +. +.SS "global" +. +.IP "\(bu" 4 +Default: false +. +.IP "\(bu" 4 +Type: Boolean +. +.IP "" 0 +. +.P +Operates in "global" mode, so that packages are installed into the \fBprefix\fR folder instead of the current working directory\. See \fBnpm help folders\fR for more on the differences in behavior\. +. +.IP "\(bu" 4 +packages are installed into the \fBprefix/node_modules\fR folder, instead of the +current working directory\. +. +.IP "\(bu" 4 +bin files are linked to \fBprefix/bin\fR +. +.IP "\(bu" 4 +man pages are linked to \fBprefix/share/man\fR +. +.IP "" 0 +. +.SS "globalconfig" +. +.IP "\(bu" 4 +Default: {prefix}/etc/npmrc +. +.IP "\(bu" 4 +Type: path +. +.IP "" 0 +. +.P +The config file to read for global config options\. +. +.SS "globalignorefile" +. +.IP "\(bu" 4 +Default: {prefix}/etc/npmignore +. +.IP "\(bu" 4 +Type: path +. +.IP "" 0 +. +.P +The config file to read for global ignore patterns to apply to all users +and all projects\. +. +.P +If not found, but there is a "gitignore" file in the +same directory, then that will be used instead\. +. +.SS "group" +. +.IP "\(bu" 4 +Default: GID of the current process +. +.IP "\(bu" 4 +Type: String or Number +. +.IP "" 0 +. +.P +The group to use when running package scripts in global mode as the root +user\. +. +.SS "https\-proxy" +. +.IP "\(bu" 4 +Default: the \fBHTTPS_PROXY\fR or \fBhttps_proxy\fR or \fBHTTP_PROXY\fR or \fBhttp_proxy\fR environment variables\. +. +.IP "\(bu" 4 +Type: url +. +.IP "" 0 +. +.P +A proxy to use for outgoing https requests\. +. +.SS "user\-agent" +. +.IP "\(bu" 4 +Default: npm/{npm\.version} node/{process\.version} +. +.IP "\(bu" 4 +Type: String +. +.IP "" 0 +. +.P +Sets a User\-Agent to the request header +. +.SS "ignore" +. +.IP "\(bu" 4 +Default: "" +. +.IP "\(bu" 4 +Type: string +. +.IP "" 0 +. +.P +A white\-space separated list of glob patterns of files to always exclude +from packages when building tarballs\. +. +.SS "init\-module" +. +.IP "\(bu" 4 +Default: ~/\.npm\-init\.js +. +.IP "\(bu" 4 +Type: path +. +.IP "" 0 +. +.P +A module that will be loaded by the \fBnpm init\fR command\. See the +documentation for the init\-package\-json \fIhttps://github\.com/isaacs/init\-package\-json\fR module +for more information, or npm help init\. +. +.SS "init\.version" +. +.IP "\(bu" 4 +Default: "0\.0\.0" +. +.IP "\(bu" 4 +Type: semver +. +.IP "" 0 +. +.P +The value \fBnpm init\fR should use by default for the package version\. +. +.SS "init\.author\.name" +. +.IP "\(bu" 4 +Default: "" +. +.IP "\(bu" 4 +Type: String +. +.IP "" 0 +. +.P +The value \fBnpm init\fR should use by default for the package author\'s name\. +. +.SS "init\.author\.email" +. +.IP "\(bu" 4 +Default: "" +. +.IP "\(bu" 4 +Type: String +. +.IP "" 0 +. +.P +The value \fBnpm init\fR should use by default for the package author\'s email\. +. +.SS "init\.author\.url" +. +.IP "\(bu" 4 +Default: "" +. +.IP "\(bu" 4 +Type: String +. +.IP "" 0 +. +.P +The value \fBnpm init\fR should use by default for the package author\'s homepage\. +. +.SS "json" +. +.IP "\(bu" 4 +Default: false +. +.IP "\(bu" 4 +Type: Boolean +. +.IP "" 0 +. +.P +Whether or not to output JSON data, rather than the normal output\. +. +.P +This feature is currently experimental, and the output data structures +for many commands is either not implemented in JSON yet, or subject to +change\. Only the output from \fBnpm ls \-\-json\fR is currently valid\. +. +.SS "link" +. +.IP "\(bu" 4 +Default: false +. +.IP "\(bu" 4 +Type: Boolean +. +.IP "" 0 +. +.P +If true, then local installs will link if there is a suitable globally +installed package\. +. +.P +Note that this means that local installs can cause things to be +installed into the global space at the same time\. The link is only done +if one of the two conditions are met: +. +.IP "\(bu" 4 +The package is not already installed globally, or +. +.IP "\(bu" 4 +the globally installed version is identical to the version that is +being installed locally\. +. +.IP "" 0 +. +.SS "loglevel" +. +.IP "\(bu" 4 +Default: "http" +. +.IP "\(bu" 4 +Type: String +. +.IP "\(bu" 4 +Values: "silent", "win", "error", "warn", "http", "info", "verbose", "silly" +. +.IP "" 0 +. +.P +What level of logs to report\. On failure, \fIall\fR logs are written to \fBnpm\-debug\.log\fR in the current working directory\. +. +.P +Any logs of a higher level than the setting are shown\. +The default is "http", which shows http, warn, and error output\. +. +.SS "logstream" +. +.IP "\(bu" 4 +Default: process\.stderr +. +.IP "\(bu" 4 +Type: Stream +. +.IP "" 0 +. +.P +This is the stream that is passed to the npmlog \fIhttps://github\.com/isaacs/npmlog\fR module at run time\. +. +.P +It cannot be set from the command line, but if you are using npm +programmatically, you may wish to send logs to somewhere other than +stderr\. +. +.P +If the \fBcolor\fR config is set to true, then this stream will receive +colored output if it is a TTY\. +. +.SS "long" +. +.IP "\(bu" 4 +Default: false +. +.IP "\(bu" 4 +Type: Boolean +. +.IP "" 0 +. +.P +Show extended information in \fBnpm ls\fR +. +.SS "message" +. +.IP "\(bu" 4 +Default: "%s" +. +.IP "\(bu" 4 +Type: String +. +.IP "" 0 +. +.P +Commit message which is used by \fBnpm version\fR when creating version commit\. +. +.P +Any "%s" in the message will be replaced with the version number\. +. +.SS "node\-version" +. +.IP "\(bu" 4 +Default: process\.version +. +.IP "\(bu" 4 +Type: semver or false +. +.IP "" 0 +. +.P +The node version to use when checking package\'s "engines" hash\. +. +.SS "npat" +. +.IP "\(bu" 4 +Default: false +. +.IP "\(bu" 4 +Type: Boolean +. +.IP "" 0 +. +.P +Run tests on installation and report results to the \fBnpaturl\fR\|\. +. +.SS "npaturl" +. +.IP "\(bu" 4 +Default: Not yet implemented +. +.IP "\(bu" 4 +Type: url +. +.IP "" 0 +. +.P +The url to report npat test results\. +. +.SS "onload\-script" +. +.IP "\(bu" 4 +Default: false +. +.IP "\(bu" 4 +Type: path +. +.IP "" 0 +. +.P +A node module to \fBrequire()\fR when npm loads\. Useful for programmatic +usage\. +. +.SS "optional" +. +.IP "\(bu" 4 +Default: true +. +.IP "\(bu" 4 +Type: Boolean +. +.IP "" 0 +. +.P +Attempt to install packages in the \fBoptionalDependencies\fR hash\. Note +that if these packages fail to install, the overall installation +process is not aborted\. +. +.SS "parseable" +. +.IP "\(bu" 4 +Default: false +. +.IP "\(bu" 4 +Type: Boolean +. +.IP "" 0 +. +.P +Output parseable results from commands that write to +standard output\. +. +.SS "prefix" +. +.IP "\(bu" 4 +Default: node\'s process\.installPrefix +. +.IP "\(bu" 4 +Type: path +. +.IP "" 0 +. +.P +The location to install global items\. If set on the command line, then +it forces non\-global commands to run in the specified folder\. +. +.SS "production" +. +.IP "\(bu" 4 +Default: false +. +.IP "\(bu" 4 +Type: Boolean +. +.IP "" 0 +. +.P +Set to true to run in "production" mode\. +. +.IP "1" 4 +devDependencies are not installed at the topmost level when running +local \fBnpm install\fR without any arguments\. +. +.IP "2" 4 +Set the NODE_ENV="production" for lifecycle scripts\. +. +.IP "" 0 +. +.SS "proprietary\-attribs" +. +.IP "\(bu" 4 +Default: true +. +.IP "\(bu" 4 +Type: Boolean +. +.IP "" 0 +. +.P +Whether or not to include proprietary extended attributes in the +tarballs created by npm\. +. +.P +Unless you are expecting to unpack package tarballs with something other +than npm \-\- particularly a very outdated tar implementation \-\- leave +this as true\. +. +.SS "proxy" +. +.IP "\(bu" 4 +Default: \fBHTTP_PROXY\fR or \fBhttp_proxy\fR environment variable, or null +. +.IP "\(bu" 4 +Type: url +. +.IP "" 0 +. +.P +A proxy to use for outgoing http requests\. +. +.SS "rebuild\-bundle" +. +.IP "\(bu" 4 +Default: true +. +.IP "\(bu" 4 +Type: Boolean +. +.IP "" 0 +. +.P +Rebuild bundled dependencies after installation\. +. +.SS "registry" +. +.IP "\(bu" 4 +Default: https://registry\.npmjs\.org/ +. +.IP "\(bu" 4 +Type: url +. +.IP "" 0 +. +.P +The base URL of the npm package registry\. +. +.SS "rollback" +. +.IP "\(bu" 4 +Default: true +. +.IP "\(bu" 4 +Type: Boolean +. +.IP "" 0 +. +.P +Remove failed installs\. +. +.SS "save" +. +.IP "\(bu" 4 +Default: false +. +.IP "\(bu" 4 +Type: Boolean +. +.IP "" 0 +. +.P +Save installed packages to a package\.json file as dependencies\. +. +.P +When used with the \fBnpm rm\fR command, it removes it from the dependencies +hash\. +. +.P +Only works if there is already a package\.json file present\. +. +.SS "save\-bundle" +. +.IP "\(bu" 4 +Default: false +. +.IP "\(bu" 4 +Type: Boolean +. +.IP "" 0 +. +.P +If a package would be saved at install time by the use of \fB\-\-save\fR, \fB\-\-save\-dev\fR, or \fB\-\-save\-optional\fR, then also put it in the \fBbundleDependencies\fR list\. +. +.P +When used with the \fBnpm rm\fR command, it removes it from the +bundledDependencies list\. +. +.SS "save\-dev" +. +.IP "\(bu" 4 +Default: false +. +.IP "\(bu" 4 +Type: Boolean +. +.IP "" 0 +. +.P +Save installed packages to a package\.json file as devDependencies\. +. +.P +When used with the \fBnpm rm\fR command, it removes it from the devDependencies +hash\. +. +.P +Only works if there is already a package\.json file present\. +. +.SS "save\-optional" +. +.IP "\(bu" 4 +Default: false +. +.IP "\(bu" 4 +Type: Boolean +. +.IP "" 0 +. +.P +Save installed packages to a package\.json file as optionalDependencies\. +. +.P +When used with the \fBnpm rm\fR command, it removes it from the devDependencies +hash\. +. +.P +Only works if there is already a package\.json file present\. +. +.SS "searchopts" +. +.IP "\(bu" 4 +Default: "" +. +.IP "\(bu" 4 +Type: String +. +.IP "" 0 +. +.P +Space\-separated options that are always passed to search\. +. +.SS "searchexclude" +. +.IP "\(bu" 4 +Default: "" +. +.IP "\(bu" 4 +Type: String +. +.IP "" 0 +. +.P +Space\-separated options that limit the results from search\. +. +.SS "searchsort" +. +.IP "\(bu" 4 +Default: "name" +. +.IP "\(bu" 4 +Type: String +. +.IP "\(bu" 4 +Values: "name", "\-name", "date", "\-date", "description", +"\-description", "keywords", "\-keywords" +. +.IP "" 0 +. +.P +Indication of which field to sort search results by\. Prefix with a \fB\-\fR +character to indicate reverse sort\. +. +.SS "shell" +. +.IP "\(bu" 4 +Default: SHELL environment variable, or "bash" on Posix, or "cmd" on +Windows +. +.IP "\(bu" 4 +Type: path +. +.IP "" 0 +. +.P +The shell to run for the \fBnpm explore\fR command\. +. +.SS "sign\-git\-tag" +. +.IP "\(bu" 4 +Default: false +. +.IP "\(bu" 4 +Type: Boolean +. +.IP "" 0 +. +.P +If set to true, then the \fBnpm version\fR command will tag the version +using \fB\-s\fR to add a signature\. +. +.P +Note that git requires you to have set up GPG keys in your git configs +for this to work properly\. +. +.SS "strict\-ssl" +. +.IP "\(bu" 4 +Default: true +. +.IP "\(bu" 4 +Type: Boolean +. +.IP "" 0 +. +.P +Whether or not to do SSL key validation when making requests to the +registry via https\. +. +.P +See also the \fBca\fR config\. +. +.SS "tag" +. +.IP "\(bu" 4 +Default: latest +. +.IP "\(bu" 4 +Type: String +. +.IP "" 0 +. +.P +If you ask npm to install a package and don\'t tell it a specific version, then +it will install the specified tag\. +. +.P +Also the tag that is added to the package@version specified by the \fBnpm +tag\fR command, if no explicit tag is given\. +. +.SS "tmp" +. +.IP "\(bu" 4 +Default: TMPDIR environment variable, or "/tmp" +. +.IP "\(bu" 4 +Type: path +. +.IP "" 0 +. +.P +Where to store temporary files and folders\. All temp files are deleted +on success, but left behind on failure for forensic purposes\. +. +.SS "unicode" +. +.IP "\(bu" 4 +Default: true +. +.IP "\(bu" 4 +Type: Boolean +. +.IP "" 0 +. +.P +When set to true, npm uses unicode characters in the tree output\. When +false, it uses ascii characters to draw trees\. +. +.SS "unsafe\-perm" +. +.IP "\(bu" 4 +Default: false if running as root, true otherwise +. +.IP "\(bu" 4 +Type: Boolean +. +.IP "" 0 +. +.P +Set to true to suppress the UID/GID switching when running package +scripts\. If set explicitly to false, then installing as a non\-root user +will fail\. +. +.SS "usage" +. +.IP "\(bu" 4 +Default: false +. +.IP "\(bu" 4 +Type: Boolean +. +.IP "" 0 +. +.P +Set to show short usage output (like the \-H output) +instead of complete help when doing \fBnpm help help\fR\|\. +. +.SS "user" +. +.IP "\(bu" 4 +Default: "nobody" +. +.IP "\(bu" 4 +Type: String or Number +. +.IP "" 0 +. +.P +The UID to set to when running package scripts as root\. +. +.SS "username" +. +.IP "\(bu" 4 +Default: null +. +.IP "\(bu" 4 +Type: String +. +.IP "" 0 +. +.P +The username on the npm registry\. Set with \fBnpm adduser\fR +. +.SS "userconfig" +. +.IP "\(bu" 4 +Default: ~/\.npmrc +. +.IP "\(bu" 4 +Type: path +. +.IP "" 0 +. +.P +The location of user\-level configuration settings\. +. +.SS "userignorefile" +. +.IP "\(bu" 4 +Default: ~/\.npmignore +. +.IP "\(bu" 4 +Type: path +. +.IP "" 0 +. +.P +The location of a user\-level ignore file to apply to all packages\. +. +.P +If not found, but there is a \.gitignore file in the same directory, then +that will be used instead\. +. +.SS "umask" +. +.IP "\(bu" 4 +Default: 022 +. +.IP "\(bu" 4 +Type: Octal numeric string +. +.IP "" 0 +. +.P +The "umask" value to use when setting the file creation mode on files +and folders\. +. +.P +Folders and executables are given a mode which is \fB0777\fR masked against +this value\. Other files are given a mode which is \fB0666\fR masked against +this value\. Thus, the defaults are \fB0755\fR and \fB0644\fR respectively\. +. +.SS "version" +. +.IP "\(bu" 4 +Default: false +. +.IP "\(bu" 4 +Type: boolean +. +.IP "" 0 +. +.P +If true, output the npm version and exit successfully\. +. +.P +Only relevant when specified explicitly on the command line\. +. +.SS "versions" +. +.IP "\(bu" 4 +Default: false +. +.IP "\(bu" 4 +Type: boolean +. +.IP "" 0 +. +.P +If true, output the npm version as well as node\'s \fBprocess\.versions\fR +hash, and exit successfully\. +. +.P +Only relevant when specified explicitly on the command line\. +. +.SS "viewer" +. +.IP "\(bu" 4 +Default: "man" on Posix, "browser" on Windows +. +.IP "\(bu" 4 +Type: path +. +.IP "" 0 +. +.P +The program to use to view help content\. +. +.P +Set to \fB"browser"\fR to view html help content in the default web browser\. +. +.SS "yes" +. +.IP "\(bu" 4 +Default: null +. +.IP "\(bu" 4 +Type: Boolean or null +. +.IP "" 0 +. +.P +If set to \fBnull\fR, then prompt the user for responses in some +circumstances\. +. +.P +If set to \fBtrue\fR, then answer "yes" to any prompt\. If set to \fBfalse\fR +then answer "no" to any prompt\. +. +.SH "SEE ALSO" +. +.IP "\(bu" 4 +npm help folders +. +.IP "\(bu" 4 +npm help npm +. +.IP "" 0 + diff --git a/node-v0.8.14/deps/npm/man/man1/dedupe.1 b/node-v0.8.14/deps/npm/man/man1/dedupe.1 new file mode 100644 index 0000000..fed46d7 --- /dev/null +++ b/node-v0.8.14/deps/npm/man/man1/dedupe.1 @@ -0,0 +1,90 @@ +.\" Generated with Ronnjs 0.3.8 +.\" http://github.com/kapouer/ronnjs/ +. +.TH "NPM\-DEDUPE" "1" "October 2012" "" "" +. +.SH "NAME" +\fBnpm-dedupe\fR \-\- Reduce duplication +. +.SH "SYNOPSIS" +. +.nf +npm dedupe [package names\.\.\.] +. +.fi +. +.SH "DESCRIPTION" +Searches the local package tree and attempts to simplify the overall +structure by moving dependencies further up the tree, where they can +be more effectively shared by multiple dependent packages\. +. +.P +For example, consider this dependency graph: +. +.IP "" 4 +. +.nf +a ++\-\- b <\-\- depends on c@1\.0\.x +| `\-\- c@1\.0\.3 +`\-\- d <\-\- depends on c@~1\.0\.9 + `\-\- c@1\.0\.10 +. +.fi +. +.IP "" 0 +. +.P +In this case, \fBnpm help dedupe\fR will transform the tree to: +. +.IP "" 4 +. +.nf +a ++\-\- b ++\-\- d +`\-\- c@1\.0\.10 +. +.fi +. +.IP "" 0 +. +.P +Because of the hierarchical nature of node\'s module lookup, b and d +will both get their dependency met by the single c package at the root +level of the tree\. +. +.P +If a suitable version exists at the target location in the tree +already, then it will be left untouched, but the other duplicates will +be deleted\. +. +.P +If no suitable version can be found, then a warning is printed, and +nothing is done\. +. +.P +If any arguments are supplied, then they are filters, and only the +named packages will be touched\. +. +.P +Note that this operation transforms the dependency tree, and may +result in packages getting updated versions, perhaps from the npm +registry\. +. +.P +This feature is experimental, and may change in future versions\. +. +.SH "SEE ALSO" +. +.IP "\(bu" 4 +npm help ls +. +.IP "\(bu" 4 +npm help update +. +.IP "\(bu" 4 +npm help install +. +.IP "" 0 + diff --git a/node-v0.8.14/deps/npm/man/man1/deprecate.1 b/node-v0.8.14/deps/npm/man/man1/deprecate.1 new file mode 100644 index 0000000..8084b8b --- /dev/null +++ b/node-v0.8.14/deps/npm/man/man1/deprecate.1 @@ -0,0 +1,45 @@ +.\" Generated with Ronnjs 0.3.8 +.\" http://github.com/kapouer/ronnjs/ +. +.TH "NPM\-DEPRECATE" "1" "October 2012" "" "" +. +.SH "NAME" +\fBnpm-deprecate\fR \-\- Deprecate a version of a package +. +.SH "SYNOPSIS" +. +.nf +npm deprecate [@] +. +.fi +. +.SH "DESCRIPTION" +This command will update the npm registry entry for a package, providing +a deprecation warning to all who attempt to install it\. +. +.P +It works on version ranges as well as specific versions, so you can do +something like this: +. +.IP "" 4 +. +.nf +npm deprecate my\-thing@"< 0\.2\.3" "critical bug fixed in v0\.2\.3" +. +.fi +. +.IP "" 0 +. +.P +Note that you must be the package owner to deprecate something\. See the \fBowner\fR and \fBadduser\fR help topics\. +. +.SH "SEE ALSO" +. +.IP "\(bu" 4 +npm help publish +. +.IP "\(bu" 4 +npm help registry +. +.IP "" 0 + diff --git a/node-v0.8.14/deps/npm/man/man1/developers.1 b/node-v0.8.14/deps/npm/man/man1/developers.1 new file mode 100644 index 0000000..10a4084 --- /dev/null +++ b/node-v0.8.14/deps/npm/man/man1/developers.1 @@ -0,0 +1,283 @@ +.\" Generated with Ronnjs 0.3.8 +.\" http://github.com/kapouer/ronnjs/ +. +.TH "NPM\-DEVELOPERS" "1" "October 2012" "" "" +. +.SH "NAME" +\fBnpm-developers\fR \-\- Developer Guide +. +.SH "DESCRIPTION" +So, you\'ve decided to use npm to develop (and maybe publish/deploy) +your project\. +. +.P +Fantastic! +. +.P +There are a few things that you need to do above the simple steps +that your users will do to install your program\. +. +.SH "About These Documents" +These are man pages\. If you install npm, you should be able to +then do \fBman npm\-thing\fR to get the documentation on a particular +topic, or \fBnpm help thing\fR to see the same information\. +. +.SH "What is a " +A package is: +. +.IP "\(bu" 4 +a) a folder containing a program described by a package\.json file +. +.IP "\(bu" 4 +b) a gzipped tarball containing (a) +. +.IP "\(bu" 4 +c) a url that resolves to (b) +. +.IP "\(bu" 4 +d) a \fB@\fR that is published on the registry with (c) +. +.IP "\(bu" 4 +e) a \fB@\fR that points to (d) +. +.IP "\(bu" 4 +f) a \fB\fR that has a "latest" tag satisfying (e) +. +.IP "\(bu" 4 +g) a \fBgit\fR url that, when cloned, results in (a)\. +. +.IP "" 0 +. +.P +Even if you never publish your package, you can still get a lot of +benefits of using npm if you just want to write a node program (a), and +perhaps if you also want to be able to easily install it elsewhere +after packing it up into a tarball (b)\. +. +.P +Git urls can be of the form: +. +.IP "" 4 +. +.nf +git://github\.com/user/project\.git#commit\-ish +git+ssh://user@hostname:project\.git#commit\-ish +git+http://user@hostname/project/blah\.git#commit\-ish +git+https://user@hostname/project/blah\.git#commit\-ish +. +.fi +. +.IP "" 0 +. +.P +The \fBcommit\-ish\fR can be any tag, sha, or branch which can be supplied as +an argument to \fBgit checkout\fR\|\. The default is \fBmaster\fR\|\. +. +.SH "The package\.json File" +You need to have a \fBpackage\.json\fR file in the root of your project to do +much of anything with npm\. That is basically the whole interface\. +. +.P +See \fBnpm help json\fR for details about what goes in that file\. At the very +least, you need: +. +.IP "\(bu" 4 +name: +This should be a string that identifies your project\. Please do not +use the name to specify that it runs on node, or is in JavaScript\. +You can use the "engines" field to explicitly state the versions of +node (or whatever else) that your program requires, and it\'s pretty +well assumed that it\'s javascript\. +. +.IP +It does not necessarily need to match your github repository name\. +. +.IP +So, \fBnode\-foo\fR and \fBbar\-js\fR are bad names\. \fBfoo\fR or \fBbar\fR are better\. +. +.IP "\(bu" 4 +version: +A semver\-compatible version\. +. +.IP "\(bu" 4 +engines: +Specify the versions of node (or whatever else) that your program +runs on\. The node API changes a lot, and there may be bugs or new +functionality that you depend on\. Be explicit\. +. +.IP "\(bu" 4 +author: +Take some credit\. +. +.IP "\(bu" 4 +scripts: +If you have a special compilation or installation script, then you +should put it in the \fBscripts\fR hash\. You should definitely have at +least a basic smoke\-test command as the "scripts\.test" field\. +See npm help scripts\. +. +.IP "\(bu" 4 +main: +If you have a single module that serves as the entry point to your +program (like what the "foo" package gives you at require("foo")), +then you need to specify that in the "main" field\. +. +.IP "\(bu" 4 +directories: +This is a hash of folders\. The best ones to include are "lib" and +"doc", but if you specify a folder full of man pages in "man", then +they\'ll get installed just like these ones\. +. +.IP "" 0 +. +.P +You can use \fBnpm init\fR in the root of your package in order to get you +started with a pretty basic package\.json file\. See \fBnpm help init\fR for +more info\. +. +.SH "Keeping files " +Use a \fB\|\.npmignore\fR file to keep stuff out of your package\. If there\'s +no \.npmignore file, but there \fIis\fR a \.gitignore file, then npm will +ignore the stuff matched by the \.gitignore file\. If you \fIwant\fR to +include something that is excluded by your \.gitignore file, you can +create an empty \.npmignore file to override it\. +. +.SH "Link Packages" +\fBnpm link\fR is designed to install a development package and see the +changes in real time without having to keep re\-installing it\. (You do +need to either re\-link or \fBnpm rebuild \-g\fR to update compiled packages, +of course\.) +. +.P +More info at \fBnpm help link\fR\|\. +. +.SH "Before Publishing: Make Sure Your Package Installs and Works" +\fBThis is important\.\fR +. +.P +If you can not install it locally, you\'ll have +problems trying to publish it\. Or, worse yet, you\'ll be able to +publish it, but you\'ll be publishing a broken or pointless package\. +So don\'t do that\. +. +.P +In the root of your package, do this: +. +.IP "" 4 +. +.nf +npm install \. \-g +. +.fi +. +.IP "" 0 +. +.P +That\'ll show you that it\'s working\. If you\'d rather just create a symlink +package that points to your working directory, then do this: +. +.IP "" 4 +. +.nf +npm link +. +.fi +. +.IP "" 0 +. +.P +Use \fBnpm ls \-g\fR to see if it\'s there\. +. +.P +To test a local install, go into some other folder, and then do: +. +.IP "" 4 +. +.nf +cd \.\./some\-other\-folder +npm install \.\./my\-package +. +.fi +. +.IP "" 0 +. +.P +to install it locally into the node_modules folder in that other place\. +. +.P +Then go into the node\-repl, and try using require("my\-thing") to +bring in your module\'s main module\. +. +.SH "Create a User Account" +Create a user with the adduser command\. It works like this: +. +.IP "" 4 +. +.nf +npm adduser +. +.fi +. +.IP "" 0 +. +.P +and then follow the prompts\. +. +.P +This is documented better in npm help adduser\. +. +.SH "Publish your package" +This part\'s easy\. IN the root of your folder, do this: +. +.IP "" 4 +. +.nf +npm publish +. +.fi +. +.IP "" 0 +. +.P +You can give publish a url to a tarball, or a filename of a tarball, +or a path to a folder\. +. +.P +Note that pretty much \fBeverything in that folder will be exposed\fR +by default\. So, if you have secret stuff in there, use a \fB\|\.npmignore\fR file to list out the globs to ignore, or publish +from a fresh checkout\. +. +.SH "Brag about it" +Send emails, write blogs, blab in IRC\. +. +.P +Tell the world how easy it is to install your program! +. +.SH "SEE ALSO" +. +.IP "\(bu" 4 +npm help faq +. +.IP "\(bu" 4 +npm help npm +. +.IP "\(bu" 4 +npm help init +. +.IP "\(bu" 4 +npm help json +. +.IP "\(bu" 4 +npm help scripts +. +.IP "\(bu" 4 +npm help publish +. +.IP "\(bu" 4 +npm help adduser +. +.IP "\(bu" 4 +npm help registry +. +.IP "" 0 + diff --git a/node-v0.8.14/deps/npm/man/man1/disputes.1 b/node-v0.8.14/deps/npm/man/man1/disputes.1 new file mode 100644 index 0000000..0b68d13 --- /dev/null +++ b/node-v0.8.14/deps/npm/man/man1/disputes.1 @@ -0,0 +1,124 @@ +.\" Generated with Ronnjs 0.3.8 +.\" http://github.com/kapouer/ronnjs/ +. +.TH "NPM\-DISPUTES" "1" "October 2012" "" "" +. +.SH "NAME" +\fBnpm-disputes\fR \-\- Handling Module Name Disputes +. +.SH "SYNOPSIS" +. +.IP "1" 4 +Get the author email with \fBnpm owner ls \fR +. +.IP "2" 4 +Email the author, CC \fIi@izs\.me\fR\|\. +. +.IP "3" 4 +After a few weeks, if there\'s no resolution, we\'ll sort it out\. +. +.IP "" 0 +. +.SH "DESCRIPTION" +There sometimes arise cases where a user publishes a module, and then +later, some other user wants to use that name\. Here are some common +ways that happens (each of these is based on actual events\.) +. +.IP "1" 4 +Bob writes a JavaScript module \fBfoo\fR, which is not node\-specific\. +Bob doesn\'t use node at all\. Joe wants to use \fBfoo\fR in node, so he +wraps it in an npm module\. Some time later, Bob starts using node, +and wants to take over management of his program\. +. +.IP "2" 4 +Bob writes an npm module \fBfoo\fR, and publishes it\. Perhaps much +later, Joe finds a bug in \fBfoo\fR, and fixes it\. He sends a pull +request to Bob, but Bob doesn\'t have the time to deal with it, +because he has a new job and a new baby and is focused on his new +erlang project, and kind of not involved with node any more\. Joe +would like to publish a new \fBfoo\fR, but can\'t, because the name is +taken\. +. +.IP "3" 4 +Bob writes a 10\-line flow\-control library, and calls it \fBfoo\fR, and +publishes it to the npm registry\. Being a simple little thing, it +never really has to be updated\. Joe works for Foo Inc, the makers +of the critically acclaimed and widely\-marketed \fBfoo\fR JavaScript +toolkit framework\. They publish it to npm as \fBfoojs\fR, but people are +routinely confused when \fBnpm install foo\fR is some different thing\. +. +.IP "4" 4 +Bob writes a parser for the widely\-known \fBfoo\fR file format, because +he needs it for work\. Then, he gets a new job, and never updates the +prototype\. Later on, Joe writes a much more complete \fBfoo\fR parser, +but can\'t publish, because Bob\'s \fBfoo\fR is in the way\. +. +.IP "" 0 +. +.P +The validity of Joe\'s claim in each situation can be debated\. However, +Joe\'s appropriate course of action in each case is the same\. +. +.IP "1" 4 +\fBnpm owner ls foo\fR\|\. This will tell Joe the email address of the +owner (Bob)\. +. +.IP "2" 4 +Joe emails Bob, explaining the situation \fBas respecfully as possible\fR, +and what he would like to do with the module name\. He adds +isaacs \fIi@izs\.me\fR to the CC list of the email\. Mention in the email +that Bob can run \fBnpm owner add joe foo\fR to add Joe as an owner of +the \fBfoo\fR package\. +. +.IP "3" 4 +After a reasonable amount of time, if Bob has not responded, or if +Bob and Joe can\'t come to any sort of resolution, email isaacs \fIi@izs\.me\fR and we\'ll sort it out\. +. +.IP "" 0 +. +.SH "REASONING" +In almost every case so far, the parties involved have been able to reach +an amicable resolution without any major intervention\. Most people +really do want to be reasonable, and are probably not even aware that +they\'re in your way\. +. +.P +Module ecosystems are most vibrant and powerful when they are as +self\-directed as possible\. If an admin one day deletes something you +had worked on, then that is going to make most people quite upset, +regardless of the justification\. When humans solve their problems by +talking to other humans with respect, everyone has the chance to end up +feeling good about the interaction\. +. +.SH "EXCEPTIONS" +Some things are not allowed, and will be removed without discussion if +they are brought to the attention of the npm registry admins, including +but not limited to: +. +.IP "1" 4 +Malware (that is, a module designed to exploit or harm the machine on +which it is installed) +. +.IP "2" 4 +Violations of copyright or licenses (for example, cloning an +MIT\-licensed program, and then removing or changing the copyright and +license statement) +. +.IP "3" 4 +Illegal content\. +. +.IP "" 0 +. +.P +If you see bad behavior like this, please report it right away\. +. +.SH "SEE ALSO" +. +.IP "\(bu" 4 +npm help registry +. +.IP "\(bu" 4 +npm help owner +. +.IP "" 0 + diff --git a/node-v0.8.14/deps/npm/man/man1/docs.1 b/node-v0.8.14/deps/npm/man/man1/docs.1 new file mode 100644 index 0000000..39c29ed --- /dev/null +++ b/node-v0.8.14/deps/npm/man/man1/docs.1 @@ -0,0 +1,68 @@ +.\" Generated with Ronnjs 0.3.8 +.\" http://github.com/kapouer/ronnjs/ +. +.TH "NPM\-DOCS" "1" "October 2012" "" "" +. +.SH "NAME" +\fBnpm-docs\fR \-\- Docs for a package in a web browser maybe +. +.SH "SYNOPSIS" +. +.nf +npm docs +npm home +. +.fi +. +.SH "DESCRIPTION" +This command tries to guess at the likely location of a package\'s +documentation URL, and then tries to open it using the \fB\-\-browser\fR +config param\. +. +.SH "CONFIGURATION" +. +.SS "browser" +. +.IP "\(bu" 4 +Default: OS X: \fB"open"\fR, others: \fB"google\-chrome"\fR +. +.IP "\(bu" 4 +Type: String +. +.IP "" 0 +. +.P +The browser that is called by the \fBnpm docs\fR command to open websites\. +. +.SS "registry" +. +.IP "\(bu" 4 +Default: https://registry\.npmjs\.org/ +. +.IP "\(bu" 4 +Type: url +. +.IP "" 0 +. +.P +The base URL of the npm package registry\. +. +.SH "SEE ALSO" +. +.IP "\(bu" 4 +npm help view +. +.IP "\(bu" 4 +npm help publish +. +.IP "\(bu" 4 +npm help registry +. +.IP "\(bu" 4 +npm help config +. +.IP "\(bu" 4 +npm help json +. +.IP "" 0 + diff --git a/node-v0.8.14/deps/npm/man/man1/edit.1 b/node-v0.8.14/deps/npm/man/man1/edit.1 new file mode 100644 index 0000000..f27dae3 --- /dev/null +++ b/node-v0.8.14/deps/npm/man/man1/edit.1 @@ -0,0 +1,60 @@ +.\" Generated with Ronnjs 0.3.8 +.\" http://github.com/kapouer/ronnjs/ +. +.TH "NPM\-EDIT" "1" "October 2012" "" "" +. +.SH "NAME" +\fBnpm-edit\fR \-\- Edit an installed package +. +.SH "SYNOPSIS" +. +.nf +npm edit [@] +. +.fi +. +.SH "DESCRIPTION" +Opens the package folder in the default editor (or whatever you\'ve +configured as the npm \fBeditor\fR config \-\- see \fBnpm help config\fR\|\.) +. +.P +After it has been edited, the package is rebuilt so as to pick up any +changes in compiled packages\. +. +.P +For instance, you can do \fBnpm install connect\fR to install connect +into your package, and then \fBnpm edit connect\fR to make a few +changes to your locally installed copy\. +. +.SH "CONFIGURATION" +. +.SS "editor" +. +.IP "\(bu" 4 +Default: \fBEDITOR\fR environment variable if set, or \fB"vi"\fR on Posix, +or \fB"notepad"\fR on Windows\. +. +.IP "\(bu" 4 +Type: path +. +.IP "" 0 +. +.P +The command to run for \fBnpm edit\fR or \fBnpm config edit\fR\|\. +. +.SH "SEE ALSO" +. +.IP "\(bu" 4 +npm help folders +. +.IP "\(bu" 4 +npm help explore +. +.IP "\(bu" 4 +npm help install +. +.IP "\(bu" 4 +npm help config +. +.IP "" 0 + diff --git a/node-v0.8.14/deps/npm/man/man1/explore.1 b/node-v0.8.14/deps/npm/man/man1/explore.1 new file mode 100644 index 0000000..0e41e84 --- /dev/null +++ b/node-v0.8.14/deps/npm/man/man1/explore.1 @@ -0,0 +1,76 @@ +.\" Generated with Ronnjs 0.3.8 +.\" http://github.com/kapouer/ronnjs/ +. +.TH "NPM\-EXPLORE" "1" "October 2012" "" "" +. +.SH "NAME" +\fBnpm-explore\fR \-\- Browse an installed package +. +.SH "SYNOPSIS" +. +.nf +npm explore [@] [ \-\- ] +. +.fi +. +.SH "DESCRIPTION" +Spawn a subshell in the directory of the installed package specified\. +. +.P +If a command is specified, then it is run in the subshell, which then +immediately terminates\. +. +.P +This is particularly handy in the case of git submodules in the \fBnode_modules\fR folder: +. +.IP "" 4 +. +.nf +npm explore some\-dependency \-\- git pull origin master +. +.fi +. +.IP "" 0 +. +.P +Note that the package is \fInot\fR automatically rebuilt afterwards, so be +sure to use \fBnpm rebuild \fR if you make any changes\. +. +.SH "CONFIGURATION" +. +.SS "shell" +. +.IP "\(bu" 4 +Default: SHELL environment variable, or "bash" on Posix, or "cmd" on +Windows +. +.IP "\(bu" 4 +Type: path +. +.IP "" 0 +. +.P +The shell to run for the \fBnpm explore\fR command\. +. +.SH "SEE ALSO" +. +.IP "\(bu" 4 +npm help submodule +. +.IP "\(bu" 4 +npm help folders +. +.IP "\(bu" 4 +npm help edit +. +.IP "\(bu" 4 +npm help rebuild +. +.IP "\(bu" 4 +npm help build +. +.IP "\(bu" 4 +npm help install +. +.IP "" 0 + diff --git a/node-v0.8.14/deps/npm/man/man1/faq.1 b/node-v0.8.14/deps/npm/man/man1/faq.1 new file mode 100644 index 0000000..93a724d --- /dev/null +++ b/node-v0.8.14/deps/npm/man/man1/faq.1 @@ -0,0 +1,341 @@ +.\" Generated with Ronnjs 0.3.8 +.\" http://github.com/kapouer/ronnjs/ +. +.TH "NPM\-FAQ" "1" "October 2012" "" "" +. +.SH "NAME" +\fBnpm-faq\fR \-\- Frequently Asked Questions +. +.SH "Where can I find these docs in HTML?" +\fIhttps://npmjs\.org/doc/\fR, or run: +. +.IP "" 4 +. +.nf +npm config set viewer browser +. +.fi +. +.IP "" 0 +. +.P +to open these documents in your default web browser rather than \fBman\fR\|\. +. +.SH "It didn't work\." +That\'s not really a question\. +. +.SH "Why didn't it work?" +I don\'t know yet\. +. +.P +Read the error output, and if you can\'t figure out what it means, +do what it says and post a bug with all the information it asks for\. +. +.SH "Where does npm put stuff?" +See \fBnpm help folders\fR +. +.P +tl;dr: +. +.IP "\(bu" 4 +Use the \fBnpm root\fR command to see where modules go, and the \fBnpm bin\fR +command to see where executables go +. +.IP "\(bu" 4 +Global installs are different from local installs\. If you install +something with the \fB\-g\fR flag, then its executables go in \fBnpm bin \-g\fR +and its modules go in \fBnpm root \-g\fR\|\. +. +.IP "" 0 +. +.SH "How do I install something on my computer in a central location?" +Install it globally by tacking \fB\-g\fR or \fB\-\-global\fR to the command\. (This +is especially important for command line utilities that need to add +their bins to the global system \fBPATH\fR\|\.) +. +.SH "I installed something globally, but I can't " +Install it locally\. +. +.P +The global install location is a place for command\-line utilities +to put their bins in the system \fBPATH\fR\|\. It\'s not for use with \fBrequire()\fR\|\. +. +.P +If you \fBrequire()\fR a module in your code, then that means it\'s a +dependency, and a part of your program\. You need to install it locally +in your program\. +. +.SH "Why can't npm just put everything in one place, like other package managers?" +Not every change is an improvement, but every improvement is a change\. +This would be like asking git to do network IO for every commit\. It\'s +not going to happen, because it\'s a terrible idea that causes more +problems than it solves\. +. +.P +It is much harder to avoid dependency conflicts without nesting +dependencies\. This is fundamental to the way that npm works, and has +proven to be an extremely successful approach\. See \fBnpm help folders\fR for +more details\. +. +.P +If you want a package to be installed in one place, and have all your +programs reference the same copy of it, then use the \fBnpm link\fR command\. +That\'s what it\'s for\. Install it globally, then link it into each +program that uses it\. +. +.SH "Whatever, I really want the old style 'everything global' style\." +Write your own package manager, then\. It\'s not that hard\. +. +.P +npm will not help you do something that is known to be a bad idea\. +. +.SH "Should I check my " +Mikeal Rogers answered this question very well: +. +.P +\fIhttp://www\.mikealrogers\.com/posts/nodemodules\-in\-git\.html\fR +. +.P +tl;dr +. +.IP "\(bu" 4 +Check \fBnode_modules\fR into git for things you \fBdeploy\fR, such as +websites and apps\. +. +.IP "\(bu" 4 +Do not check \fBnode_modules\fR into git for libraries and modules +intended to be reused\. +. +.IP "\(bu" 4 +Use npm to manage dependencies in your dev environment, but not in +your deployment scripts\. +. +.IP "" 0 +. +.SH "Is it 'npm' or 'NPM' or 'Npm'?" +npm should never be capitalized unless it is being displayed in a +location that is customarily all\-caps (such as the title of man pages\.) +. +.SH "If 'npm' is an acronym, why is it never capitalized?" +Contrary to the belief of many, "npm" is not in fact an abbreviation for +"Node Package Manager"\. It is a recursive bacronymic abbreviation for +"npm is not an acronym"\. (If it was "ninaa", then it would be an +acronym, and thus incorrectly named\.) +. +.P +"NPM", however, \fIis\fR an acronym (more precisely, a capitonym) for the +National Association of Pastoral Musicians\. You can learn more +about them at \fIhttp://npm\.org/\fR\|\. +. +.P +In software, "NPM" is a Non\-Parametric Mapping utility written by +Chris Rorden\. You can analyze pictures of brains with it\. Learn more +about the (capitalized) NPM program at \fIhttp://www\.cabiatl\.com/mricro/npm/\fR\|\. +. +.P +The first seed that eventually grew into this flower was a bash utility +named "pm", which was a shortened descendent of "pkgmakeinst", a +bash function that was used to install various different things on different +platforms, most often using Yahoo\'s \fByinst\fR\|\. If \fBnpm\fR was ever an +acronym for anything, it was \fBnode pm\fR or maybe \fBnew pm\fR\|\. +. +.P +So, in all seriousness, the "npm" project is named after its command\-line +utility, which was organically selected to be easily typed by a right\-handed +programmer using a US QWERTY keyboard layout, ending with the +right\-ring\-finger in a postition to type the \fB\-\fR key for flags and +other command\-line arguments\. That command\-line utility is always +lower\-case, though it starts most sentences it is a part of\. +. +.SH "How do I list installed packages?" +\fBnpm ls\fR +. +.SH "How do I search for packages?" +\fBnpm search\fR +. +.P +Arguments are greps\. \fBnpm search jsdom\fR shows jsdom packages\. +. +.SH "How do I update npm?" +. +.nf +npm update npm \-g +. +.fi +. +.P +You can also update all outdated local packages by doing \fBnpm update\fR without +any arguments, or global packages by doing \fBnpm update \-g\fR\|\. +. +.P +Occasionally, the version of npm will progress such that the current +version cannot be properly installed with the version that you have +installed already\. (Consider, if there is ever a bug in the \fBupdate\fR +command\.) +. +.P +In those cases, you can do this: +. +.IP "" 4 +. +.nf +curl https://npmjs\.org/install\.sh | sh +. +.fi +. +.IP "" 0 +. +.SH "What is a " +A package is: +. +.IP "\(bu" 4 +a) a folder containing a program described by a package\.json file +. +.IP "\(bu" 4 +b) a gzipped tarball containing (a) +. +.IP "\(bu" 4 +c) a url that resolves to (b) +. +.IP "\(bu" 4 +d) a \fB@\fR that is published on the registry with (c) +. +.IP "\(bu" 4 +e) a \fB@\fR that points to (d) +. +.IP "\(bu" 4 +f) a \fB\fR that has a "latest" tag satisfying (e) +. +.IP "\(bu" 4 +g) a \fBgit\fR url that, when cloned, results in (a)\. +. +.IP "" 0 +. +.P +Even if you never publish your package, you can still get a lot of +benefits of using npm if you just want to write a node program (a), and +perhaps if you also want to be able to easily install it elsewhere +after packing it up into a tarball (b)\. +. +.P +Git urls can be of the form: +. +.IP "" 4 +. +.nf +git://github\.com/user/project\.git#commit\-ish +git+ssh://user@hostname:project\.git#commit\-ish +git+http://user@hostname/project/blah\.git#commit\-ish +git+https://user@hostname/project/blah\.git#commit\-ish +. +.fi +. +.IP "" 0 +. +.P +The \fBcommit\-ish\fR can be any tag, sha, or branch which can be supplied as +an argument to \fBgit checkout\fR\|\. The default is \fBmaster\fR\|\. +. +.SH "How do I install node with npm?" +You don\'t\. Try one of these: +. +.IP "\(bu" 4 +\fIhttps://github\.com/isaacs/nave\fR +. +.IP "\(bu" 4 +\fIhttps://github\.com/visionmedia/n\fR +. +.IP "\(bu" 4 +\fIhttps://github\.com/creationix/nvm\fR +. +.IP "" 0 +. +.SH "How can I use npm for development?" +See \fBnpm help developers\fR and \fBnpm help json\fR\|\. +. +.P +You\'ll most likely want to \fBnpm link\fR your development folder\. That\'s +awesomely handy\. +. +.P +To set up your own private registry, check out \fBnpm help registry\fR\|\. +. +.SH "Can I list a url as a dependency?" +Yes\. It should be a url to a gzipped tarball containing a single folder +that has a package\.json in its root, or a git url\. +(See "what is a package?" above\.) +. +.SH "How do I symlink to a dev folder so I don't have to keep re\-installing?" +See \fBnpm help link\fR +. +.SH "The package registry website\. What is that exactly?" +See \fBnpm help registry\fR\|\. +. +.SH "What's up with the insecure channel warnings?" +Until node 0\.4\.10, there were problems sending big files over HTTPS\. That +means that publishes go over HTTP by default in those versions of node\. +. +.SH "I forgot my password, and can't publish\. How do I reset it?" +Go to \fIhttps://npmjs\.org/forgot\fR\|\. +. +.SH "I get ECONNREFUSED a lot\. What's up?" +Either the registry is down, or node\'s DNS isn\'t able to reach out\. +. +.P +To check if the registry is down, open up \fIhttp://registry\.npmjs\.org/\fR +in a web browser\. This will also tell you if you are just unable to +access the internet for some reason\. +. +.P +If the registry IS down, let me know by emailing or posting an issue\. +We\'ll have someone kick it or something\. +. +.SH "Why no namespaces?" +Please see this discussion: \fIhttps://github\.com/isaacs/npm/issues/798\fR +. +.P +tl;dr \- It doesn\'t actually make things better, and can make them worse\. +. +.P +If you want to namespace your own packages, you may: simply use the \fB\-\fR character to separate the names\. npm is a mostly anarchic system\. +There is not sufficient need to impose namespace rules on everyone\. +. +.SH "Who does npm?" +\fBnpm view npm author\fR +. +.P +\fBnpm view npm contributors\fR +. +.SH "I have a question or request not addressed here\. Where should I put it?" +Discuss it on the mailing list, or post an issue\. +. +.IP "\(bu" 4 +\fInpm\-@googlegroups\.com\fR +. +.IP "\(bu" 4 +\fIhttps://github\.com/isaacs/npm/issues\fR +. +.IP "" 0 +. +.SH "Why does npm hate me?" +npm is not capable of hatred\. It loves everyone, especially you\. +. +.SH "SEE ALSO" +. +.IP "\(bu" 4 +npm help npm +. +.IP "\(bu" 4 +npm help developers +. +.IP "\(bu" 4 +npm help json +. +.IP "\(bu" 4 +npm help config +. +.IP "\(bu" 4 +npm help folders +. +.IP "" 0 + diff --git a/node-v0.8.14/deps/npm/man/man1/find.1 b/node-v0.8.14/deps/npm/man/man1/find.1 new file mode 100644 index 0000000..653597f --- /dev/null +++ b/node-v0.8.14/deps/npm/man/man1/find.1 @@ -0,0 +1,72 @@ +.\" Generated with Ronnjs/v0.1 +.\" http://github.com/kapouer/ronnjs/ +. +.TH "NPM\-SEARCH" "1" "November 2011" "" "" +. +.SH "NAME" +\fBnpm-search\fR \-\- Search for packages +. +.SH "SYNOPSIS" +. +.nf +npm search [search terms \.\.\.] +. +.fi +. +.SH "DESCRIPTION" +Search the registry for packages matching the search terms\. +. +.SH "CONFIGURATION" +. +.SS "description" +. +.IP "\(bu" 4 +Default: true +. +.IP "\(bu" 4 +Type: Boolean +. +.IP "" 0 +. +.P +Show the description in \fBnpm search\fR +. +.SS "searchopts" +. +.IP "\(bu" 4 +Default: "" +. +.IP "\(bu" 4 +Type: String +. +.IP "" 0 +. +.P +Space\-separated options that are always passed to search\. +. +.SS "searchexclude" +. +.IP "\(bu" 4 +Default: "" +. +.IP "\(bu" 4 +Type: String +. +.IP "" 0 +. +.P +Space\-separated options that limit the results from search\. +. +.SH "SEE ALSO" +. +.IP "\(bu" 4 +npm help registry +. +.IP "\(bu" 4 +npm help config +. +.IP "\(bu" 4 +npm help view +. +.IP "" 0 + diff --git a/node-v0.8.14/deps/npm/man/man1/folders.1 b/node-v0.8.14/deps/npm/man/man1/folders.1 new file mode 100644 index 0000000..72dcbcf --- /dev/null +++ b/node-v0.8.14/deps/npm/man/man1/folders.1 @@ -0,0 +1,258 @@ +.\" Generated with Ronnjs 0.3.8 +.\" http://github.com/kapouer/ronnjs/ +. +.TH "NPM\-FOLDERS" "1" "October 2012" "" "" +. +.SH "NAME" +\fBnpm-folders\fR \-\- Folder Structures Used by npm +. +.SH "DESCRIPTION" +npm puts various things on your computer\. That\'s its job\. +. +.P +This document will tell you what it puts where\. +. +.SS "tl;dr" +. +.IP "\(bu" 4 +Local install (default): puts stuff in \fB\|\./node_modules\fR of the current +package root\. +. +.IP "\(bu" 4 +Global install (with \fB\-g\fR): puts stuff in /usr/local or wherever node +is installed\. +. +.IP "\(bu" 4 +Install it \fBlocally\fR if you\'re going to \fBrequire()\fR it\. +. +.IP "\(bu" 4 +Install it \fBglobally\fR if you\'re going to run it on the command line\. +. +.IP "\(bu" 4 +If you need both, then install it in both places, or use \fBnpm link\fR\|\. +. +.IP "" 0 +. +.SS "prefix Configuration" +The \fBprefix\fR config defaults to the location where node is installed\. +On most systems, this is \fB/usr/local\fR, and most of the time is the same +as node\'s \fBprocess\.installPrefix\fR\|\. +. +.P +On windows, this is the exact location of the node\.exe binary\. On Unix +systems, it\'s one level up, since node is typically installed at \fB{prefix}/bin/node\fR rather than \fB{prefix}/node\.exe\fR\|\. +. +.P +When the \fBglobal\fR flag is set, npm installs things into this prefix\. +When it is not set, it uses the root of the current package, or the +current working directory if not in a package already\. +. +.SS "Node Modules" +Packages are dropped into the \fBnode_modules\fR folder under the \fBprefix\fR\|\. +When installing locally, this means that you can \fBrequire("packagename")\fR to load its main module, or \fBrequire("packagename/lib/path/to/sub/module")\fR to load other modules\. +. +.P +Global installs on Unix systems go to \fB{prefix}/lib/node_modules\fR\|\. +Global installs on Windows go to \fB{prefix}/node_modules\fR (that is, no \fBlib\fR folder\.) +. +.P +If you wish to \fBrequire()\fR a package, then install it locally\. +. +.SS "Executables" +When in global mode, executables are linked into \fB{prefix}/bin\fR on Unix, +or directly into \fB{prefix}\fR on Windows\. +. +.P +When in local mode, executables are linked into \fB\|\./node_modules/\.bin\fR so that they can be made available to scripts run +through npm\. (For example, so that a test runner will be in the path +when you run \fBnpm test\fR\|\.) +. +.SS "Man Pages" +When in global mode, man pages are linked into \fB{prefix}/share/man\fR\|\. +. +.P +When in local mode, man pages are not installed\. +. +.P +Man pages are not installed on Windows systems\. +. +.SS "Cache" +See \fBnpm help cache\fR\|\. Cache files are stored in \fB~/\.npm\fR on Posix, or \fB~/npm\-cache\fR on Windows\. +. +.P +This is controlled by the \fBcache\fR configuration param\. +. +.SS "Temp Files" +Temporary files are stored by default in the folder specified by the \fBtmp\fR config, which defaults to the TMPDIR, TMP, or TEMP environment +variables, or \fB/tmp\fR on Unix and \fBc:\\windows\\temp\fR on Windows\. +. +.P +Temp files are given a unique folder under this root for each run of the +program, and are deleted upon successful exit\. +. +.SH "More Information" +When installing locally, npm first tries to find an appropriate \fBprefix\fR folder\. This is so that \fBnpm install foo@1\.2\.3\fR will install +to the sensible root of your package, even if you happen to have \fBcd\fRed +into some other folder\. +. +.P +Starting at the $PWD, npm will walk up the folder tree checking for a +folder that contains either a \fBpackage\.json\fR file, or a \fBnode_modules\fR +folder\. If such a thing is found, then that is treated as the effective +"current directory" for the purpose of running npm commands\. (This +behavior is inspired by and similar to git\'s \.git\-folder seeking +logic when running git commands in a working dir\.) +. +.P +If no package root is found, then the current folder is used\. +. +.P +When you run \fBnpm install foo@1\.2\.3\fR, then the package is loaded into +the cache, and then unpacked into \fB\|\./node_modules/foo\fR\|\. Then, any of +foo\'s dependencies are similarly unpacked into \fB\|\./node_modules/foo/node_modules/\.\.\.\fR\|\. +. +.P +Any bin files are symlinked to \fB\|\./node_modules/\.bin/\fR, so that they may +be found by npm scripts when necessary\. +. +.SS "Global Installation" +If the \fBglobal\fR configuration is set to true, then npm will +install packages "globally"\. +. +.P +For global installation, packages are installed roughly the same way, +but using the folders described above\. +. +.SS "Cycles, Conflicts, and Folder Parsimony" +Cycles are handled using the property of node\'s module system that it +walks up the directories looking for \fBnode_modules\fR folders\. So, at every +stage, if a package is already installed in an ancestor \fBnode_modules\fR +folder, then it is not installed at the current location\. +. +.P +Consider the case above, where \fBfoo \-> bar \-> baz\fR\|\. Imagine if, in +addition to that, baz depended on bar, so you\'d have: \fBfoo \-> bar \-> baz \-> bar \-> baz \.\.\.\fR\|\. However, since the folder +structure is: \fBfoo/node_modules/bar/node_modules/baz\fR, there\'s no need to +put another copy of bar into \fB\|\.\.\./baz/node_modules\fR, since when it calls +require("bar"), it will get the copy that is installed in \fBfoo/node_modules/bar\fR\|\. +. +.P +This shortcut is only used if the exact same +version would be installed in multiple nested \fBnode_modules\fR folders\. It +is still possible to have \fBa/node_modules/b/node_modules/a\fR if the two +"a" packages are different versions\. However, without repeating the +exact same package multiple times, an infinite regress will always be +prevented\. +. +.P +Another optimization can be made by installing dependencies at the +highest level possible, below the localized "target" folder\. +. +.SS "\fIExample\fR" +Consider this dependency graph: +. +.IP "" 4 +. +.nf +foo ++\-\- blerg@1\.2\.5 ++\-\- bar@1\.2\.3 +| +\-\- blerg@1\.x (latest=1\.3\.7) +| +\-\- baz@2\.x +| | `\-\- quux@3\.x +| | `\-\- bar@1\.2\.3 (cycle) +| `\-\- asdf@* +`\-\- baz@1\.2\.3 + `\-\- quux@3\.x + `\-\- bar +. +.fi +. +.IP "" 0 +. +.P +In this case, we might expect a folder structure like this: +. +.IP "" 4 +. +.nf +foo ++\-\- node_modules + +\-\- blerg (1\.2\.5) <\-\-\-[A] + +\-\- bar (1\.2\.3) <\-\-\-[B] + | +\-\- node_modules + | | `\-\- baz (2\.0\.2) <\-\-\-[C] + | | `\-\- node_modules + | | `\-\- quux (3\.2\.0) + | `\-\- asdf (2\.3\.4) + `\-\- baz (1\.2\.3) <\-\-\-[D] + `\-\- node_modules + `\-\- quux (3\.2\.0) <\-\-\-[E] +. +.fi +. +.IP "" 0 +. +.P +Since foo depends directly on bar@1\.2\.3 and baz@1\.2\.3, those are +installed in foo\'s \fBnode_modules\fR folder\. +. +.P +Even though the latest copy of blerg is 1\.3\.7, foo has a specific +dependency on version 1\.2\.5\. So, that gets installed at [A]\. Since the +parent installation of blerg satisfie\'s bar\'s dependency on blerg@1\.x, +it does not install another copy under [B]\. +. +.P +Bar [B] also has dependencies on baz and asdf, so those are installed in +bar\'s \fBnode_modules\fR folder\. Because it depends on \fBbaz@2\.x\fR, it cannot +re\-use the \fBbaz@1\.2\.3\fR installed in the parent \fBnode_modules\fR folder [D], +and must install its own copy [C]\. +. +.P +Underneath bar, the \fBbaz\->quux\->bar\fR dependency creates a cycle\. +However, because \fBbar\fR is already in \fBquux\fR\'s ancestry [B], it does not +unpack another copy of bar into that folder\. +. +.P +Underneath \fBfoo\->baz\fR [D], quux\'s [E] folder tree is empty, because its +dependency on bar is satisfied by the parent folder copy installed at [B]\. +. +.P +For a graphical breakdown of what is installed where, use \fBnpm ls\fR\|\. +. +.SS "Publishing" +Upon publishing, npm will look in the \fBnode_modules\fR folder\. If any of +the items there are not in the \fBbundledDependencies\fR array, then they will +not be included in the package tarball\. +. +.P +This allows a package maintainer to install all of their dependencies +(and dev dependencies) locally, but only re\-publish those items that +cannot be found elsewhere\. See \fBnpm help json\fR for more information\. +. +.SH "SEE ALSO" +. +.IP "\(bu" 4 +npm help faq +. +.IP "\(bu" 4 +npm help json +. +.IP "\(bu" 4 +npm help install +. +.IP "\(bu" 4 +npm help pack +. +.IP "\(bu" 4 +npm help cache +. +.IP "\(bu" 4 +npm help config +. +.IP "\(bu" 4 +npm help publish +. +.IP "" 0 + diff --git a/node-v0.8.14/deps/npm/man/man1/get.1 b/node-v0.8.14/deps/npm/man/man1/get.1 new file mode 100644 index 0000000..5075c9f --- /dev/null +++ b/node-v0.8.14/deps/npm/man/man1/get.1 @@ -0,0 +1,1154 @@ +.\" Generated with Ronnjs/v0.1 +.\" http://github.com/kapouer/ronnjs/ +. +.TH "NPM\-CONFIG" "1" "November 2011" "" "" +. +.SH "NAME" +\fBnpm-config\fR \-\- Manage the npm configuration file +. +.SH "SYNOPSIS" +. +.nf +npm config set [\-\-global] +npm config get +npm config delete +npm config list +npm config edit +npm get +npm set [\-\-global] +. +.fi +. +.SH "DESCRIPTION" +npm gets its configuration values from 6 sources, in this priority: +. +.SS "Command Line Flags" +Putting \fB\-\-foo bar\fR on the command line sets the \fBfoo\fR configuration parameter to \fB"bar"\fR\|\. A \fB\-\-\fR argument tells the cli +parser to stop reading flags\. A \fB\-\-flag\fR parameter that is at the \fIend\fR of +the command will be given the value of \fBtrue\fR\|\. +. +.SS "Environment Variables" +Any environment variables that start with \fBnpm_config_\fR will be interpreted +as a configuration parameter\. For example, putting \fBnpm_config_foo=bar\fR in +your environment will set the \fBfoo\fR configuration parameter to \fBbar\fR\|\. Any +environment configurations that are not given a value will be given the value +of \fBtrue\fR\|\. Config values are case\-insensitive, so \fBNPM_CONFIG_FOO=bar\fR will +work the same\. +. +.SS "Per\-user config file" +\fB$HOME/\.npmrc\fR (or the \fBuserconfig\fR param, if set above) +. +.P +This file is an ini\-file formatted list of \fBkey = value\fR parameters\. +. +.SS "Global config file" +\fB$PREFIX/etc/npmrc\fR (or the \fBglobalconfig\fR param, if set above): +This file is an ini\-file formatted list of \fBkey = value\fR parameters +. +.SS "Built\-in config file" +\fBpath/to/npm/itself/npmrc\fR +. +.P +This is an unchangeable "builtin" +configuration file that npm keeps consistent across updates\. Set +fields in here using the \fB\|\./configure\fR script that comes with npm\. +This is primarily for distribution maintainers to override default +configs in a standard and consistent manner\. +. +.SS "Default Configs" +A set of configuration parameters that are internal to npm, and are +defaults if nothing else is specified\. +. +.SH "Sub\-commands" +Config supports the following sub\-commands: +. +.SS "set" +. +.nf +npm config set key value +. +.fi +. +.P +Sets the config key to the value\. +. +.P +If value is omitted, then it sets it to "true"\. +. +.SS "get" +. +.nf +npm config get key +. +.fi +. +.P +Echo the config value to stdout\. +. +.SS "list" +. +.nf +npm config list +. +.fi +. +.P +Show all the config settings\. +. +.SS "delete" +. +.nf +npm config delete key +. +.fi +. +.P +Deletes the key from all configuration files\. +. +.SS "edit" +. +.nf +npm config edit +. +.fi +. +.P +Opens the config file in an editor\. Use the \fB\-\-global\fR flag to edit the +global config\. +. +.SH "Shorthands and Other CLI Niceties" +The following shorthands are parsed on the command\-line: +. +.IP "\(bu" 4 +\fB\-v\fR: \fB\-\-version\fR +. +.IP "\(bu" 4 +\fB\-h\fR, \fB\-?\fR, \fB\-\-help\fR, \fB\-H\fR: \fB\-\-usage\fR +. +.IP "\(bu" 4 +\fB\-s\fR, \fB\-\-silent\fR: \fB\-\-loglevel silent\fR +. +.IP "\(bu" 4 +\fB\-d\fR: \fB\-\-loglevel info\fR +. +.IP "\(bu" 4 +\fB\-dd\fR, \fB\-\-verbose\fR: \fB\-\-loglevel verbose\fR +. +.IP "\(bu" 4 +\fB\-ddd\fR: \fB\-\-loglevel silly\fR +. +.IP "\(bu" 4 +\fB\-g\fR: \fB\-\-global\fR +. +.IP "\(bu" 4 +\fB\-l\fR: \fB\-\-long\fR +. +.IP "\(bu" 4 +\fB\-m\fR: \fB\-\-message\fR +. +.IP "\(bu" 4 +\fB\-p\fR, \fB\-\-porcelain\fR: \fB\-\-parseable\fR +. +.IP "\(bu" 4 +\fB\-reg\fR: \fB\-\-registry\fR +. +.IP "\(bu" 4 +\fB\-v\fR: \fB\-\-version\fR +. +.IP "\(bu" 4 +\fB\-f\fR: \fB\-\-force\fR +. +.IP "\(bu" 4 +\fB\-l\fR: \fB\-\-long\fR +. +.IP "\(bu" 4 +\fB\-desc\fR: \fB\-\-description\fR +. +.IP "\(bu" 4 +\fB\-S\fR: \fB\-\-save\fR +. +.IP "\(bu" 4 +\fB\-y\fR: \fB\-\-yes\fR +. +.IP "\(bu" 4 +\fB\-n\fR: \fB\-\-yes false\fR +. +.IP "\(bu" 4 +\fBll\fR and \fBla\fR commands: \fBls \-\-long\fR +. +.IP "" 0 +. +.P +If the specified configuration param resolves unambiguously to a known +configuration parameter, then it is expanded to that configuration +parameter\. For example: +. +.IP "" 4 +. +.nf +npm ls \-\-par +# same as: +npm ls \-\-parseable +. +.fi +. +.IP "" 0 +. +.P +If multiple single\-character shorthands are strung together, and the +resulting combination is unambiguously not some other configuration +param, then it is expanded to its various component pieces\. For +example: +. +.IP "" 4 +. +.nf +npm ls \-gpld +# same as: +npm ls \-\-global \-\-parseable \-\-long \-\-loglevel info +. +.fi +. +.IP "" 0 +. +.SH "Per\-Package Config Settings" +When running scripts (see \fBnpm help scripts\fR) +the package\.json "config" keys are overwritten in the environment if +there is a config param of \fB[@]:\fR\|\. For example, if +the package\.json has this: +. +.IP "" 4 +. +.nf +{ "name" : "foo" +, "config" : { "port" : "8080" } +, "scripts" : { "start" : "node server\.js" } } +. +.fi +. +.IP "" 0 +. +.P +and the server\.js is this: +. +.IP "" 4 +. +.nf +http\.createServer(\.\.\.)\.listen(process\.env\.npm_package_config_port) +. +.fi +. +.IP "" 0 +. +.P +then the user could change the behavior by doing: +. +.IP "" 4 +. +.nf +npm config set foo:port 80 +. +.fi +. +.IP "" 0 +. +.SH "Config Settings" +. +.SS "always\-auth" +. +.IP "\(bu" 4 +Default: false +. +.IP "\(bu" 4 +Type: Boolean +. +.IP "" 0 +. +.P +Force npm to always require authentication when accessing the registry, +even for \fBGET\fR requests\. +. +.SS "bin\-publish" +. +.IP "\(bu" 4 +Default: false +. +.IP "\(bu" 4 +Type: Boolean +. +.IP "" 0 +. +.P +If set to true, then binary packages will be created on publish\. +. +.P +This is the way to opt into the "bindist" behavior described below\. +. +.SS "bindist" +. +.IP "\(bu" 4 +Default: Unstable node versions, \fBnull\fR, otherwise \fB"\-\-"\fR +. +.IP "\(bu" 4 +Type: String or \fBnull\fR +. +.IP "" 0 +. +.P +Experimental: on stable versions of node, binary distributions will be +created with this tag\. If a user then installs that package, and their \fBbindist\fR tag is found in the list of binary distributions, they will +get that prebuilt version\. +. +.P +Pre\-build node packages have their preinstall, install, and postinstall +scripts stripped (since they are run prior to publishing), and do not +have their \fBbuild\fR directories automatically ignored\. +. +.P +It\'s yet to be seen if this is a good idea\. +. +.SS "browser" +. +.IP "\(bu" 4 +Default: OS X: \fB"open"\fR, others: \fB"google\-chrome"\fR +. +.IP "\(bu" 4 +Type: String +. +.IP "" 0 +. +.P +The browser that is called by the \fBnpm docs\fR command to open websites\. +. +.SS "ca" +. +.IP "\(bu" 4 +Default: The npm CA certificate +. +.IP "\(bu" 4 +Type: String or null +. +.IP "" 0 +. +.P +The Certificate Authority signing certificate that is trusted for SSL +connections to the registry\. +. +.P +Set to \fBnull\fR to only allow "known" registrars, or to a specific CA cert +to trust only that specific signing authority\. +. +.P +See also the \fBstrict\-ssl\fR config\. +. +.SS "cache" +. +.IP "\(bu" 4 +Default: Windows: \fB~/npm\-cache\fR, Posix: \fB~/\.npm\fR +. +.IP "\(bu" 4 +Type: path +. +.IP "" 0 +. +.P +The location of npm\'s cache directory\. See \fBnpm help cache\fR +. +.SS "color" +. +.IP "\(bu" 4 +Default: true on Posix, false on Windows +. +.IP "\(bu" 4 +Type: Boolean or \fB"always"\fR +. +.IP "" 0 +. +.P +If false, never shows colors\. If \fB"always"\fR then always shows colors\. +If true, then only prints color codes for tty file descriptors\. +. +.SS "depth" +. +.IP "\(bu" 4 +Default: Infinity +. +.IP "\(bu" 4 +Type: Number +. +.IP "" 0 +. +.P +The depth to go when recursing directories for \fBnpm ls\fR and \fBnpm cache ls\fR\|\. +. +.SS "description" +. +.IP "\(bu" 4 +Default: true +. +.IP "\(bu" 4 +Type: Boolean +. +.IP "" 0 +. +.P +Show the description in \fBnpm search\fR +. +.SS "dev" +. +.IP "\(bu" 4 +Default: false +. +.IP "\(bu" 4 +Type: Boolean +. +.IP "" 0 +. +.P +Install \fBdev\-dependencies\fR along with packages\. +. +.P +Note that \fBdev\-dependencies\fR are also installed if the \fBnpat\fR flag is +set\. +. +.SS "editor" +. +.IP "\(bu" 4 +Default: \fBEDITOR\fR environment variable if set, or \fB"vi"\fR on Posix, +or \fB"notepad"\fR on Windows\. +. +.IP "\(bu" 4 +Type: path +. +.IP "" 0 +. +.P +The command to run for \fBnpm edit\fR or \fBnpm config edit\fR\|\. +. +.SS "force" +. +.IP "\(bu" 4 +Default: false +. +.IP "\(bu" 4 +Type: Boolean +. +.IP "" 0 +. +.P +Makes various commands more forceful\. +. +.IP "\(bu" 4 +lifecycle script failure does not block progress\. +. +.IP "\(bu" 4 +publishing clobbers previously published versions\. +. +.IP "\(bu" 4 +skips cache when requesting from the registry\. +. +.IP "\(bu" 4 +prevents checks against clobbering non\-npm files\. +. +.IP "" 0 +. +.SS "global" +. +.IP "\(bu" 4 +Default: false +. +.IP "\(bu" 4 +Type: Boolean +. +.IP "" 0 +. +.P +Operates in "global" mode, so that packages are installed into the \fBprefix\fR folder instead of the current working directory\. See \fBnpm help folders\fR for more on the differences in behavior\. +. +.IP "\(bu" 4 +packages are installed into the \fBprefix/node_modules\fR folder, instead of the +current working directory\. +. +.IP "\(bu" 4 +bin files are linked to \fBprefix/bin\fR +. +.IP "\(bu" 4 +man pages are linked to \fBprefix/share/man\fR +. +.IP "" 0 +. +.SS "globalconfig" +. +.IP "\(bu" 4 +Default: {prefix}/etc/npmrc +. +.IP "\(bu" 4 +Type: path +. +.IP "" 0 +. +.P +The config file to read for global config options\. +. +.SS "globalignorefile" +. +.IP "\(bu" 4 +Default: {prefix}/etc/npmignore +. +.IP "\(bu" 4 +Type: path +. +.IP "" 0 +. +.P +The config file to read for global ignore patterns to apply to all users +and all projects\. +. +.P +If not found, but there is a "gitignore" file in the +same directory, then that will be used instead\. +. +.SS "group" +. +.IP "\(bu" 4 +Default: GID of the current process +. +.IP "\(bu" 4 +Type: String or Number +. +.IP "" 0 +. +.P +The group to use when running package scripts in global mode as the root +user\. +. +.SS "https\-proxy" +. +.IP "\(bu" 4 +Default: the \fBHTTPS_PROXY\fR or \fBhttps_proxy\fR or \fBHTTP_PROXY\fR or \fBhttp_proxy\fR environment variables\. +. +.IP "\(bu" 4 +Type: url +. +.IP "" 0 +. +.P +A proxy to use for outgoing https requests\. +. +.SS "ignore" +. +.IP "\(bu" 4 +Default: "" +. +.IP "\(bu" 4 +Type: string +. +.IP "" 0 +. +.P +A white\-space separated list of glob patterns of files to always exclude +from packages when building tarballs\. +. +.SS "init\.version" +. +.IP "\(bu" 4 +Default: "0\.0\.0" +. +.IP "\(bu" 4 +Type: semver +. +.IP "" 0 +. +.P +The value \fBnpm init\fR should use by default for the package version\. +. +.SS "init\.author\.name" +. +.IP "\(bu" 4 +Default: "0\.0\.0" +. +.IP "\(bu" 4 +Type: String +. +.IP "" 0 +. +.P +The value \fBnpm init\fR should use by default for the package author\'s name\. +. +.SS "init\.author\.email" +. +.IP "\(bu" 4 +Default: "" +. +.IP "\(bu" 4 +Type: String +. +.IP "" 0 +. +.P +The value \fBnpm init\fR should use by default for the package author\'s email\. +. +.SS "init\.author\.url" +. +.IP "\(bu" 4 +Default: "" +. +.IP "\(bu" 4 +Type: String +. +.IP "" 0 +. +.P +The value \fBnpm init\fR should use by default for the package author\'s homepage\. +. +.SS "link" +. +.IP "\(bu" 4 +Default: false +. +.IP "\(bu" 4 +Type: Boolean +. +.IP "" 0 +. +.P +If true, then local installs will link if there is a suitable globally +installed package\. +. +.P +Note that this means that local installs can cause things to be +installed into the global space at the same time\. The link is only done +if one of the two conditions are met: +. +.IP "\(bu" 4 +The package is not already installed globally, or +. +.IP "\(bu" 4 +the globally installed version is identical to the version that is +being installed locally\. +. +.IP "" 0 +. +.SS "logfd" +. +.IP "\(bu" 4 +Default: stderr file descriptor +. +.IP "\(bu" 4 +Type: Number or Stream +. +.IP "" 0 +. +.P +The location to write log output\. +. +.SS "loglevel" +. +.IP "\(bu" 4 +Default: "warn" +. +.IP "\(bu" 4 +Type: String +. +.IP "\(bu" 4 +Values: "silent", "win", "error", "warn", "info", "verbose", "silly" +. +.IP "" 0 +. +.P +What level of logs to report\. On failure, \fIall\fR logs are written to \fBnpm\-debug\.log\fR in the current working directory\. +. +.SS "logprefix" +. +.IP "\(bu" 4 +Default: true on Posix, false on Windows +. +.IP "\(bu" 4 +Type: Boolean +. +.IP "" 0 +. +.P +Whether or not to prefix log messages with "npm" and the log level\. See +also "color" and "loglevel"\. +. +.SS "long" +. +.IP "\(bu" 4 +Default: false +. +.IP "\(bu" 4 +Type: Boolean +. +.IP "" 0 +. +.P +Show extended information in \fBnpm ls\fR +. +.SS "message" +. +.IP "\(bu" 4 +Default: "%s" +. +.IP "\(bu" 4 +Type: String +. +.IP "" 0 +. +.P +Commit message which is used by \fBnpm version\fR when creating version commit\. +. +.P +Any "%s" in the message will be replaced with the version number\. +. +.SS "node\-version" +. +.IP "\(bu" 4 +Default: process\.version +. +.IP "\(bu" 4 +Type: semver or false +. +.IP "" 0 +. +.P +The node version to use when checking package\'s "engines" hash\. +. +.SS "npat" +. +.IP "\(bu" 4 +Default: false +. +.IP "\(bu" 4 +Type: Boolean +. +.IP "" 0 +. +.P +Run tests on installation and report results to the \fBnpaturl\fR\|\. +. +.SS "npaturl" +. +.IP "\(bu" 4 +Default: Not yet implemented +. +.IP "\(bu" 4 +Type: url +. +.IP "" 0 +. +.P +The url to report npat test results\. +. +.SS "onload\-script" +. +.IP "\(bu" 4 +Default: false +. +.IP "\(bu" 4 +Type: path +. +.IP "" 0 +. +.P +A node module to \fBrequire()\fR when npm loads\. Useful for programmatic +usage\. +. +.SS "outfd" +. +.IP "\(bu" 4 +Default: standard output file descriptor +. +.IP "\(bu" 4 +Type: Number or Stream +. +.IP "" 0 +. +.P +Where to write "normal" output\. This has no effect on log output\. +. +.SS "parseable" +. +.IP "\(bu" 4 +Default: false +. +.IP "\(bu" 4 +Type: Boolean +. +.IP "" 0 +. +.P +Output parseable results from commands that write to +standard output\. +. +.SS "prefix" +. +.IP "\(bu" 4 +Default: node\'s process\.installPrefix +. +.IP "\(bu" 4 +Type: path +. +.IP "" 0 +. +.P +The location to install global items\. If set on the command line, then +it forces non\-global commands to run in the specified folder\. +. +.SS "production" +. +.IP "\(bu" 4 +Default: false +. +.IP "\(bu" 4 +Type: Boolean +. +.IP "" 0 +. +.P +Set to true to run in "production" mode\. +. +.IP "1" 4 +devDependencies are not installed at the topmost level when running +local \fBnpm install\fR without any arguments\. +. +.IP "2" 4 +Set the NODE_ENV="production" for lifecycle scripts\. +. +.IP "" 0 +. +.SS "proxy" +. +.IP "\(bu" 4 +Default: \fBHTTP_PROXY\fR or \fBhttp_proxy\fR environment variable, or null +. +.IP "\(bu" 4 +Type: url +. +.IP "" 0 +. +.P +A proxy to use for outgoing http requests\. +. +.SS "rebuild\-bundle" +. +.IP "\(bu" 4 +Default: true +. +.IP "\(bu" 4 +Type: Boolean +. +.IP "" 0 +. +.P +Rebuild bundled dependencies after installation\. +. +.SS "registry" +. +.IP "\(bu" 4 +Default: https://registry\.npmjs\.org/ +. +.IP "\(bu" 4 +Type: url +. +.IP "" 0 +. +.P +The base URL of the npm package registry\. +. +.SS "rollback" +. +.IP "\(bu" 4 +Default: true +. +.IP "\(bu" 4 +Type: Boolean +. +.IP "" 0 +. +.P +Remove failed installs\. +. +.SS "save" +. +.IP "\(bu" 4 +Default: false +. +.IP "\(bu" 4 +Type: Boolean +. +.IP "" 0 +. +.P +Save installed packages to a package\.json file as dependencies\. +. +.P +Only works if there is already a package\.json file present\. +. +.SS "searchopts" +. +.IP "\(bu" 4 +Default: "" +. +.IP "\(bu" 4 +Type: String +. +.IP "" 0 +. +.P +Space\-separated options that are always passed to search\. +. +.SS "searchexclude" +. +.IP "\(bu" 4 +Default: "" +. +.IP "\(bu" 4 +Type: String +. +.IP "" 0 +. +.P +Space\-separated options that limit the results from search\. +. +.SS "shell" +. +.IP "\(bu" 4 +Default: SHELL environment variable, or "bash" on Posix, or "cmd" on +Windows +. +.IP "\(bu" 4 +Type: path +. +.IP "" 0 +. +.P +The shell to run for the \fBnpm explore\fR command\. +. +.SS "strict\-ssl" +. +.IP "\(bu" 4 +Default: true +. +.IP "\(bu" 4 +Type: Boolean +. +.IP "" 0 +. +.P +Whether or not to do SSL key validation when making requests to the +registry via https\. +. +.P +See also the \fBca\fR config\. +. +.SS "tag" +. +.IP "\(bu" 4 +Default: latest +. +.IP "\(bu" 4 +Type: String +. +.IP "" 0 +. +.P +If you ask npm to install a package and don\'t tell it a specific version, then +it will install the specified tag\. +. +.P +Also the tag that is added to the package@version specified by the \fBnpm +tag\fR command, if no explicit tag is given\. +. +.SS "tmp" +. +.IP "\(bu" 4 +Default: TMPDIR environment variable, or "/tmp" +. +.IP "\(bu" 4 +Type: path +. +.IP "" 0 +. +.P +Where to store temporary files and folders\. All temp files are deleted +on success, but left behind on failure for forensic purposes\. +. +.SS "unicode" +. +.IP "\(bu" 4 +Default: true +. +.IP "\(bu" 4 +Type: Boolean +. +.IP "" 0 +. +.P +When set to true, npm uses unicode characters in the tree output\. When +false, it uses ascii characters to draw trees\. +. +.SS "unsafe\-perm" +. +.IP "\(bu" 4 +Default: false if running as root, true otherwise +. +.IP "\(bu" 4 +Type: Boolean +. +.IP "" 0 +. +.P +Set to true to suppress the UID/GID switching when running package +scripts\. If set explicitly to false, then installing as a non\-root user +will fail\. +. +.SS "usage" +. +.IP "\(bu" 4 +Default: false +. +.IP "\(bu" 4 +Type: Boolean +. +.IP "" 0 +. +.P +Set to show short usage output (like the \-H output) +instead of complete help when doing \fBnpm help help\fR\|\. +. +.SS "user" +. +.IP "\(bu" 4 +Default: "nobody" +. +.IP "\(bu" 4 +Type: String or Number +. +.IP "" 0 +. +.P +The UID to set to when running package scripts as root\. +. +.SS "username" +. +.IP "\(bu" 4 +Default: null +. +.IP "\(bu" 4 +Type: String +. +.IP "" 0 +. +.P +The username on the npm registry\. Set with \fBnpm adduser\fR +. +.SS "userconfig" +. +.IP "\(bu" 4 +Default: ~/\.npmrc +. +.IP "\(bu" 4 +Type: path +. +.IP "" 0 +. +.P +The location of user\-level configuration settings\. +. +.SS "userignorefile" +. +.IP "\(bu" 4 +Default: ~/\.npmignore +. +.IP "\(bu" 4 +Type: path +. +.IP "" 0 +. +.P +The location of a user\-level ignore file to apply to all packages\. +. +.P +If not found, but there is a \.gitignore file in the same directory, then +that will be used instead\. +. +.SS "umask" +. +.IP "\(bu" 4 +Default: 022 +. +.IP "\(bu" 4 +Type: Octal numeric string +. +.IP "" 0 +. +.P +The "umask" value to use when setting the file creation mode on files +and folders\. +. +.P +Folders and executables are given a mode which is \fB0777\fR masked against +this value\. Other files are given a mode which is \fB0666\fR masked against +this value\. Thus, the defaults are \fB0755\fR and \fB0644\fR respectively\. +. +.SS "version" +. +.IP "\(bu" 4 +Default: false +. +.IP "\(bu" 4 +Type: boolean +. +.IP "" 0 +. +.P +If true, output the npm version and exit successfully\. +. +.P +Only relevant when specified explicitly on the command line\. +. +.SS "viewer" +. +.IP "\(bu" 4 +Default: "man" on Posix, "browser" on Windows +. +.IP "\(bu" 4 +Type: path +. +.IP "" 0 +. +.P +The program to use to view help content\. +. +.P +Set to \fB"browser"\fR to view html help content in the default web browser\. +. +.SS "yes" +. +.IP "\(bu" 4 +Default: null +. +.IP "\(bu" 4 +Type: Boolean or null +. +.IP "" 0 +. +.P +If set to \fBnull\fR, then prompt the user for responses in some +circumstances\. +. +.P +If set to \fBtrue\fR, then answer "yes" to any prompt\. If set to \fBfalse\fR +then answer "no" to any prompt\. +. +.SH "SEE ALSO" +. +.IP "\(bu" 4 +npm help folders +. +.IP "\(bu" 4 +npm help npm +. +.IP "" 0 + diff --git a/node-v0.8.14/deps/npm/man/man1/global.1 b/node-v0.8.14/deps/npm/man/man1/global.1 new file mode 100644 index 0000000..070d40c --- /dev/null +++ b/node-v0.8.14/deps/npm/man/man1/global.1 @@ -0,0 +1,259 @@ +.\" Generated with Ronnjs/v0.1 +.\" http://github.com/kapouer/ronnjs/ +. +.TH "NPM\-FOLDERS" "1" "November 2011" "" "" +. +.SH "NAME" +\fBnpm-folders\fR \-\- Folder Structures Used by npm +. +.SH "DESCRIPTION" +npm puts various things on your computer\. That\'s its job\. +. +.P +This document will tell you what it puts where\. +. +.SS "tl;dr" +. +.IP "\(bu" 4 +Local install (default): puts stuff in \fB\|\./node_modules\fR of the current +package root\. +. +.IP "\(bu" 4 +Global install (with \fB\-g\fR): puts stuff in /usr/local or wherever node +is installed\. +. +.IP "\(bu" 4 +Install it \fBlocally\fR if you\'re going to \fBrequire()\fR it\. +. +.IP "\(bu" 4 +Install it \fBglobally\fR if you\'re going to run it on the command line\. +. +.IP "\(bu" 4 +If you need both, then install it in both places, or use \fBnpm link\fR\|\. +. +.IP "" 0 +. +.SS "prefix Configuration" +The \fBprefix\fR config defaults to the location where node is installed\. +On most systems, this is \fB/usr/local\fR, and most of the time is the same +as node\'s \fBprocess\.installPrefix\fR\|\. +. +.P +On windows, this is the exact location of the node\.exe binary\. On Unix +systems, it\'s one level up, since node is typically installed at \fB{prefix}/bin/node\fR rather than \fB{prefix}/node\.exe\fR\|\. +. +.P +When the \fBglobal\fR flag is set, npm installs things into this prefix\. +When it is not set, it uses the root of the current package, or the +current working directory if not in a package already\. +. +.SS "Node Modules" +Packages are dropped into the \fBnode_modules\fR folder under the \fBprefix\fR\|\. +When installing locally, this means that you can \fBrequire("packagename")\fR to load its main module, or \fBrequire("packagename/lib/path/to/sub/module")\fR to load other modules\. +. +.P +Global installs on Unix systems go to \fB{prefix}/lib/node_modules\fR\|\. +Global installs on Windows go to \fB{prefix}/node_modules\fR (that is, no \fBlib\fR folder\.) +. +.P +If you wish to \fBrequire()\fR a package, then install it locally\. +. +.SS "Executables" +When in global mode, executables are linked into \fB{prefix}/bin\fR on Unix, +or directly into \fB{prefix}\fR on Windows\. +. +.P +When in local mode, executables are linked into \fB\|\./node_modules/\.bin\fR so that they can be made available to scripts run +through npm\. (For example, so that a test runner will be in the path +when you run \fBnpm test\fR\|\.) +. +.SS "Man Pages" +When in global mode, man pages are linked into \fB{prefix}/share/man\fR\|\. +. +.P +When in local mode, man pages are not installed\. +. +.P +Man pages are not installed on Windows systems\. +. +.SS "Cache" +See \fBnpm help cache\fR\|\. Cache files are stored in \fB~/\.npm\fR on Posix, or \fB~/npm\-cache\fR on Windows\. +. +.P +This is controlled by the \fBcache\fR configuration param\. +. +.SS "Temp Files" +Temporary files are stored by default in the folder specified by the \fBtmp\fR config, which defaults to the TMPDIR, TMP, or TEMP environment +variables, or \fB/tmp\fR on Unix and \fBc:\\windows\\temp\fR on Windows\. +. +.P +Temp files are given a unique folder under this root for each run of the +program, and are deleted upon successful exit\. +. +.SH "More Information" +When installing locally, npm first tries to find an appropriate \fBprefix\fR folder\. This is so that \fBnpm install foo@1\.2\.3\fR will install +to the sensible root of your package, even if you happen to have \fBcd\fRed +into some other folder\. +. +.P +Starting at the $PWD, npm will walk up the folder tree checking for a +folder that contains either a \fBpackage\.json\fR file, or a \fBnode_modules\fR +folder\. If such a thing is found, then that is treated as the effective +"current directory" for the purpose of running npm commands\. (This +behavior is inspired by and similar to git\'s \.git\-folder seeking +logic when running git commands in a working dir\.) +. +.P +If no package root is found, then the current folder is used\. +. +.P +When you run \fBnpm install foo@1\.2\.3\fR, then the package is loaded into +the cache, and then unpacked into \fB\|\./node_modules/foo\fR\|\. Then, any of +foo\'s dependencies are similarly unpacked into \fB\|\./node_modules/foo/node_modules/\.\.\.\fR\|\. +. +.P +Any bin files are symlinked to \fB\|\./node_modules/\.bin/\fR, so that they may +be found by npm scripts when necessary\. +. +.SS "Global Installation" +If the \fBglobal\fR configuration is set to true, then npm will +install packages "globally"\. +. +.P +For global installation, packages are installed roughly the same way, +but using the folders described above\. +. +.SS "Cycles, Conflicts, and Folder Parsimony" +Cycles are handled using the property of node\'s module system that it +walks up the directories looking for \fBnode_modules\fR folders\. So, at every +stage, if a package is already installed in an ancestor \fBnode_modules\fR +folder, then it is not installed at the current location\. +. +.P +Consider the case above, where \fBfoo \-> bar \-> baz\fR\|\. Imagine if, in +addition to that, baz depended on bar, so you\'d have: \fBfoo \-> bar \-> baz \-> bar \-> baz \.\.\.\fR\|\. However, since the folder +structure is: \fBfoo/node_modules/bar/node_modules/baz\fR, there\'s no need to +put another copy of bar into \fB\|\.\.\./baz/node_modules\fR, since when it calls +require("bar"), it will get the copy that is installed in \fBfoo/node_modules/bar\fR\|\. +. +.P +This shortcut is only used if the exact same +version would be installed in multiple nested \fBnode_modules\fR folders\. It +is still possible to have \fBa/node_modules/b/node_modules/a\fR if the two +"a" packages are different versions\. However, without repeating the +exact same package multiple times, an infinite regress will always be +prevented\. +. +.P +Another optimization can be made by installing dependencies at the +highest level possible, below the localized "target" folder\. +. +.TP +Example +.Consider this dependency graph: +. +.IP "" 4 +. +.nf +foo ++\-\- blerg@1\.2\.5 ++\-\- bar@1\.2\.3 +| +\-\- blerg@1\.x (latest=1\.3\.7) +| +\-\- baz@2\.x +| | `\-\- quux@3\.x +| | `\-\- bar@1\.2\.3 (cycle) +| `\-\- asdf@* +`\-\- baz@1\.2\.3 + `\-\- quux@3\.x + `\-\- bar +. +.fi +. +.IP "" 0 +. +.P +In this case, we might expect a folder structure like this: +. +.IP "" 4 +. +.nf +foo ++\-\- node_modules + +\-\- blerg (1\.2\.5) <\-\-\-[A] + +\-\- bar (1\.2\.3) <\-\-\-[B] + | +\-\- node_modules + | | `\-\- baz (2\.0\.2) <\-\-\-[C] + | | `\-\- node_modules + | | `\-\- quux (3\.2\.0) + | `\-\- asdf (2\.3\.4) + `\-\- baz (1\.2\.3) <\-\-\-[D] + `\-\- node_modules + `\-\- quux (3\.2\.0) <\-\-\-[E] +. +.fi +. +.IP "" 0 +. +.P +Since foo depends directly on bar@1\.2\.3 and baz@1\.2\.3, those are +installed in foo\'s \fBnode_modules\fR folder\. +. +.P +Even though the latest copy of blerg is 1\.3\.7, foo has a specific +dependency on version 1\.2\.5\. So, that gets installed at [A]\. Since the +parent installation of blerg satisfie\'s bar\'s dependency on blerg@1\.x, +it does not install another copy under [B]\. +. +.P +Bar [B] also has dependencies on baz and asdf, so those are installed in +bar\'s \fBnode_modules\fR folder\. Because it depends on \fBbaz@2\.x\fR, it cannot +re\-use the \fBbaz@1\.2\.3\fR installed in the parent \fBnode_modules\fR folder [D], +and must install its own copy [C]\. +. +.P +Underneath bar, the \fBbaz\->quux\->bar\fR dependency creates a cycle\. +However, because \fBbar\fR is already in \fBquux\fR\'s ancestry [B], it does not +unpack another copy of bar into that folder\. +. +.P +Underneath \fBfoo\->baz\fR [D], quux\'s [E] folder tree is empty, because its +dependency on bar is satisfied by the parent folder copy installed at [B]\. +. +.P +For a graphical breakdown of what is installed where, use \fBnpm ls\fR\|\. +. +.SS "Publishing" +Upon publishing, npm will look in the \fBnode_modules\fR folder\. If any of +the items there are not in the \fBbundledDependencies\fR array, then they will +not be included in the package tarball\. +. +.P +This allows a package maintainer to install all of their dependencies +(and dev dependencies) locally, but only re\-publish those items that +cannot be found elsewhere\. See \fBnpm help json\fR for more information\. +. +.SH "SEE ALSO" +. +.IP "\(bu" 4 +npm help faq +. +.IP "\(bu" 4 +npm help json +. +.IP "\(bu" 4 +npm help install +. +.IP "\(bu" 4 +npm help pack +. +.IP "\(bu" 4 +npm help cache +. +.IP "\(bu" 4 +npm help config +. +.IP "\(bu" 4 +npm help publish +. +.IP "" 0 + diff --git a/node-v0.8.14/deps/npm/man/man1/help-search.1 b/node-v0.8.14/deps/npm/man/man1/help-search.1 new file mode 100644 index 0000000..287faa3 --- /dev/null +++ b/node-v0.8.14/deps/npm/man/man1/help-search.1 @@ -0,0 +1,59 @@ +.\" Generated with Ronnjs 0.3.8 +.\" http://github.com/kapouer/ronnjs/ +. +.TH "NPM\-HELP\-SEARCH" "1" "October 2012" "" "" +. +.SH "NAME" +\fBnpm-help-search\fR \-\- Search npm help documentation +. +.SH "SYNOPSIS" +. +.nf +npm help\-search some search terms +. +.fi +. +.SH "DESCRIPTION" +This command will search the npm markdown documentation files for the +terms provided, and then list the results, sorted by relevance\. +. +.P +If only one result is found, then it will show that help topic\. +. +.P +If the argument to \fBnpm help\fR is not a known help topic, then it will +call \fBhelp\-search\fR\|\. It is rarely if ever necessary to call this +command directly\. +. +.SH "CONFIGURATION" +. +.SS "long" +. +.IP "\(bu" 4 +Type: Boolean +. +.IP "\(bu" 4 +Default false +. +.IP "" 0 +. +.P +If true, the "long" flag will cause help\-search to output context around +where the terms were found in the documentation\. +. +.P +If false, then help\-search will just list out the help topics found\. +. +.SH "SEE ALSO" +. +.IP "\(bu" 4 +npm help npm +. +.IP "\(bu" 4 +npm help faq +. +.IP "\(bu" 4 +npm help help +. +.IP "" 0 + diff --git a/node-v0.8.14/deps/npm/man/man1/help.1 b/node-v0.8.14/deps/npm/man/man1/help.1 new file mode 100644 index 0000000..983e5f1 --- /dev/null +++ b/node-v0.8.14/deps/npm/man/man1/help.1 @@ -0,0 +1,71 @@ +.\" Generated with Ronnjs 0.3.8 +.\" http://github.com/kapouer/ronnjs/ +. +.TH "NPM\-HELP" "1" "October 2012" "" "" +. +.SH "NAME" +\fBnpm-help\fR \-\- Get help on npm +. +.SH "SYNOPSIS" +. +.nf +npm help +npm help some search terms +. +.fi +. +.SH "DESCRIPTION" +If supplied a topic, then show the appropriate documentation page\. +. +.P +If the topic does not exist, or if multiple terms are provided, then run +the \fBhelp\-search\fR command to find a match\. Note that, if \fBhelp\-search\fR +finds a single subject, then it will run \fBhelp\fR on that topic, so unique +matches are equivalent to specifying a topic name\. +. +.SH "CONFIGURATION" +. +.SS "viewer" +. +.IP "\(bu" 4 +Default: "man" on Posix, "browser" on Windows +. +.IP "\(bu" 4 +Type: path +. +.IP "" 0 +. +.P +The program to use to view help content\. +. +.P +Set to \fB"browser"\fR to view html help content in the default web browser\. +. +.SH "SEE ALSO" +. +.IP "\(bu" 4 +npm help npm +. +.IP "\(bu" 4 +README +. +.IP "\(bu" 4 +npm help faq +. +.IP "\(bu" 4 +npm help folders +. +.IP "\(bu" 4 +npm help config +. +.IP "\(bu" 4 +npm help json +. +.IP "\(bu" 4 +npm help help\-search +. +.IP "\(bu" 4 +npm help index +. +.IP "" 0 + diff --git a/node-v0.8.14/deps/npm/man/man1/home.1 b/node-v0.8.14/deps/npm/man/man1/home.1 new file mode 100644 index 0000000..c63dd3c --- /dev/null +++ b/node-v0.8.14/deps/npm/man/man1/home.1 @@ -0,0 +1,68 @@ +.\" Generated with Ronnjs/v0.1 +.\" http://github.com/kapouer/ronnjs/ +. +.TH "NPM\-DOCS" "1" "November 2011" "" "" +. +.SH "NAME" +\fBnpm-docs\fR \-\- Docs for a package in a web browser maybe +. +.SH "SYNOPSIS" +. +.nf +npm docs +npm home +. +.fi +. +.SH "DESCRIPTION" +This command tries to guess at the likely location of a package\'s +documentation URL, and then tries to open it using the \fB\-\-browser\fR +config param\. +. +.SH "CONFIGURATION" +. +.SS "browser" +. +.IP "\(bu" 4 +Default: OS X: \fB"open"\fR, others: \fB"google\-chrome"\fR +. +.IP "\(bu" 4 +Type: String +. +.IP "" 0 +. +.P +The browser that is called by the \fBnpm docs\fR command to open websites\. +. +.SS "registry" +. +.IP "\(bu" 4 +Default: https://registry\.npmjs\.org/ +. +.IP "\(bu" 4 +Type: url +. +.IP "" 0 +. +.P +The base URL of the npm package registry\. +. +.SH "SEE ALSO" +. +.IP "\(bu" 4 +npm help view +. +.IP "\(bu" 4 +npm help publish +. +.IP "\(bu" 4 +npm help registry +. +.IP "\(bu" 4 +npm help config +. +.IP "\(bu" 4 +npm help json +. +.IP "" 0 + diff --git a/node-v0.8.14/deps/npm/man/man1/index.1 b/node-v0.8.14/deps/npm/man/man1/index.1 new file mode 100644 index 0000000..3bf6c6f --- /dev/null +++ b/node-v0.8.14/deps/npm/man/man1/index.1 @@ -0,0 +1,289 @@ +.\" Generated with Ronnjs 0.3.8 +.\" http://github.com/kapouer/ronnjs/ +. +.TH "NPM\-INDEX" "1" "October 2012" "" "" +. +.SH "NAME" +\fBnpm-index\fR \-\- Index of all npm documentation +. +.SH "npm help README" + node package manager +. +.SH "npm help adduser" + Add a registry user account +. +.SH "npm help bin" + Display npm bin folder +. +.SH "npm help bugs" + Bugs for a package in a web browser maybe +. +.SH "npm help build" + Build a package +. +.SH "npm help bundle" + REMOVED +. +.SH "npm help cache" + Manipulates packages cache +. +.SH "npm help changelog" + Changes +. +.SH "npm help coding\-style" + npm\'s "funny" coding style +. +.SH "npm help completion" + Tab Completion for npm +. +.SH "npm help config" + Manage the npm configuration file +. +.SH "npm help dedupe" + Reduce duplication +. +.SH "npm help deprecate" + Deprecate a version of a package +. +.SH "npm help developers" + Developer Guide +. +.SH "npm help disputes" + Handling Module Name Disputes +. +.SH "npm help docs" + Docs for a package in a web browser maybe +. +.SH "npm help edit" + Edit an installed package +. +.SH "npm help explore" + Browse an installed package +. +.SH "npm help faq" + Frequently Asked Questions +. +.SH "npm help folders" + Folder Structures Used by npm +. +.SH "npm help help\-search" + Search npm help documentation +. +.SH "npm help help" + Get help on npm +. +.SH "npm help init" + Interactively create a package\.json file +. +.SH "npm help install" + Install a package +. +.SH "npm help json" + Specifics of npm\'s package\.json handling +. +.SH "npm help link" + Symlink a package folder +. +.SH "npm help ls" + List installed packages +. +.SH "npm help npm" + node package manager +. +.SH "npm help outdated" + Check for outdated packages +. +.SH "npm help owner" + Manage package owners +. +.SH "npm help pack" + Create a tarball from a package +. +.SH "npm help prefix" + Display prefix +. +.SH "npm help prune" + Remove extraneous packages +. +.SH "npm help publish" + Publish a package +. +.SH "npm help rebuild" + Rebuild a package +. +.SH "npm help registry" + The JavaScript Package Registry +. +.SH "npm help removing\-npm" + Cleaning the Slate +. +.SH "npm help restart" + Start a package +. +.SH "npm help root" + Display npm root +. +.SH "npm help run\-script" + Run arbitrary package scripts +. +.SH "npm help scripts" + How npm handles the "scripts" field +. +.SH "npm help search" + Search for packages +. +.SH "npm help semver" + The semantic versioner for npm +. +.SH "npm help shrinkwrap" + Lock down dependency versions +. +.SH "npm help star" + Mark your favorite packages +. +.SH "npm help start" + Start a package +. +.SH "npm help stop" + Stop a package +. +.SH "npm help submodule" + Add a package as a git submodule +. +.SH "npm help tag" + Tag a published version +. +.SH "npm help test" + Test a package +. +.SH "npm help uninstall" + Remove a package +. +.SH "npm help unpublish" + Remove a package from the registry +. +.SH "npm help update" + Update a package +. +.SH "npm help version" + Bump a package version +. +.SH "npm help view" + View registry info +. +.SH "npm help whoami" + Display npm username +. +.SH "npm apihelp bin" + Display npm bin folder +. +.SH "npm apihelp bugs" + Bugs for a package in a web browser maybe +. +.SH "npm apihelp commands" + npm commands +. +.SH "npm apihelp config" + Manage the npm configuration files +. +.SH "npm apihelp deprecate" + Deprecate a version of a package +. +.SH "npm apihelp docs" + Docs for a package in a web browser maybe +. +.SH "npm apihelp edit" + Edit an installed package +. +.SH "npm apihelp explore" + Browse an installed package +. +.SH "npm apihelp help\-search" + Search the help pages +. +.SH "npm apihelp init" + Interactively create a package\.json file +. +.SH "npm apihelp install" + install a package programmatically +. +.SH "npm apihelp link" + Symlink a package folder +. +.SH "npm apihelp load" + Load config settings +. +.SH "npm apihelp ls" + List installed packages +. +.SH "npm apihelp npm" + node package manager +. +.SH "npm apihelp outdated" + Check for outdated packages +. +.SH "npm apihelp owner" + Manage package owners +. +.SH "npm apihelp pack" + Create a tarball from a package +. +.SH "npm apihelp prefix" + Display prefix +. +.SH "npm apihelp prune" + Remove extraneous packages +. +.SH "npm apihelp publish" + Publish a package +. +.SH "npm apihelp rebuild" + Rebuild a package +. +.SH "npm apihelp restart" + Start a package +. +.SH "npm apihelp root" + Display npm root +. +.SH "npm apihelp run\-script" + Run arbitrary package scripts +. +.SH "npm apihelp search" + Search for packages +. +.SH "npm apihelp shrinkwrap" + programmatically generate package shrinkwrap file +. +.SH "npm apihelp start" + Start a package +. +.SH "npm apihelp stop" + Stop a package +. +.SH "npm apihelp submodule" + Add a package as a git submodule +. +.SH "npm apihelp tag" + Tag a published version +. +.SH "npm apihelp test" + Test a package +. +.SH "npm apihelp uninstall" + uninstall a package programmatically +. +.SH "npm apihelp unpublish" + Remove a package from the registry +. +.SH "npm apihelp update" + Update a package +. +.SH "npm apihelp version" + Bump a package version +. +.SH "npm apihelp view" + View registry info +. +.SH "npm apihelp whoami" + Display npm username diff --git a/node-v0.8.14/deps/npm/man/man1/init.1 b/node-v0.8.14/deps/npm/man/man1/init.1 new file mode 100644 index 0000000..ae488ed --- /dev/null +++ b/node-v0.8.14/deps/npm/man/man1/init.1 @@ -0,0 +1,43 @@ +.\" Generated with Ronnjs 0.3.8 +.\" http://github.com/kapouer/ronnjs/ +. +.TH "NPM\-INIT" "1" "October 2012" "" "" +. +.SH "NAME" +\fBnpm-init\fR \-\- Interactively create a package\.json file +. +.SH "SYNOPSIS" +. +.nf +npm init +. +.fi +. +.SH "DESCRIPTION" +This will ask you a bunch of questions, and then write a package\.json for you\. +. +.P +It attempts to make reasonable guesses about what you want things to be set to, +and then writes a package\.json file with the options you\'ve selected\. +. +.P +If you already have a package\.json file, it\'ll read that first, and default to +the options in there\. +. +.P +It is strictly additive, so it does not delete options from your package\.json +without a really good reason to do so\. +. +.SH "SEE ALSO" +. +.IP "\(bu" 4 +\fIhttps://github\.com/isaacs/init\-package\-json\fR +. +.IP "\(bu" 4 +npm help json +. +.IP "\(bu" 4 +npm help version +. +.IP "" 0 + diff --git a/node-v0.8.14/deps/npm/man/man1/install.1 b/node-v0.8.14/deps/npm/man/man1/install.1 new file mode 100644 index 0000000..5ead91c --- /dev/null +++ b/node-v0.8.14/deps/npm/man/man1/install.1 @@ -0,0 +1,405 @@ +.\" Generated with Ronnjs 0.3.8 +.\" http://github.com/kapouer/ronnjs/ +. +.TH "NPM\-INSTALL" "1" "October 2012" "" "" +. +.SH "NAME" +\fBnpm-install\fR \-\- Install a package +. +.SH "SYNOPSIS" +. +.nf +npm install (with no args in a package dir) +npm install +npm install +npm install +npm install [\-\-save|\-\-save\-dev|\-\-save\-optional] +npm install @ +npm install @ +npm install @ +npm install @ +. +.fi +. +.SH "DESCRIPTION" +This command installs a package, and any packages that it depends on\. If the +package has a shrinkwrap file, the installation of dependencies will be driven +by that\. See npm help shrinkwrap\. +. +.P +A \fBpackage\fR is: +. +.IP "\(bu" 4 +a) a folder containing a program described by a package\.json file +. +.IP "\(bu" 4 +b) a gzipped tarball containing (a) +. +.IP "\(bu" 4 +c) a url that resolves to (b) +. +.IP "\(bu" 4 +d) a \fB@\fR that is published on the registry with (c) +. +.IP "\(bu" 4 +e) a \fB@\fR that points to (d) +. +.IP "\(bu" 4 +f) a \fB\fR that has a "latest" tag satisfying (e) +. +.IP "\(bu" 4 +g) a \fB\fR that resolves to (b) +. +.IP "" 0 +. +.P +Even if you never publish your package, you can still get a lot of +benefits of using npm if you just want to write a node program (a), and +perhaps if you also want to be able to easily install it elsewhere +after packing it up into a tarball (b)\. +. +.IP "\(bu" 4 +\fBnpm install\fR (in package directory, no arguments): +. +.IP +Install the dependencies in the local node_modules folder\. +. +.IP +In global mode (ie, with \fB\-g\fR or \fB\-\-global\fR appended to the command), +it installs the current package context (ie, the current working +directory) as a global package\. +. +.IP "\(bu" 4 +\fBnpm install \fR: +. +.IP +Install a package that is sitting in a folder on the filesystem\. +. +.IP "\(bu" 4 +\fBnpm install \fR: +. +.IP +Install a package that is sitting on the filesystem\. Note: if you just want +to link a dev directory into your npm root, you can do this more easily by +using \fBnpm link\fR\|\. +. +.IP +Example: +. +.IP "" 4 +. +.nf + npm install \./package\.tgz +. +.fi +. +.IP "" 0 + +. +.IP "\(bu" 4 +\fBnpm install \fR: +. +.IP +Fetch the tarball url, and then install it\. In order to distinguish between +this and other options, the argument must start with "http://" or "https://" +. +.IP +Example: +. +.IP "" 4 +. +.nf + npm install https://github\.com/indexzero/forever/tarball/v0\.5\.6 +. +.fi +. +.IP "" 0 + +. +.IP "\(bu" 4 +\fBnpm install [\-\-save|\-\-save\-dev|\-\-save\-optional]\fR: +. +.IP +Do a \fB@\fR install, where \fB\fR is the "tag" config\. (See \fBnpm help config\fR\|\.) +. +.IP +In most cases, this will install the latest version +of the module published on npm\. +. +.IP +Example: +. +.IP + npm install sax +. +.IP +\fBnpm install\fR takes 3 exclusive, optional flags which save or update +the package version in your main package\.json: +. +.IP "\(bu" 4 +\fB\-\-save\fR: Package will appear in your \fBdependencies\fR\|\. +. +.IP "\(bu" 4 +\fB\-\-save\-dev\fR: Package will appear in your \fBdevDependencies\fR\|\. +. +.IP "\(bu" 4 +\fB\-\-save\-optional\fR: Package will appear in your \fBoptionalDependencies\fR\|\. +. +.IP +Examples: +. +.IP + npm install sax \-\-save + npm install node\-tap \-\-save\-dev + npm install dtrace\-provider \-\-save\-optional +. +.IP +\fBNote\fR: If there is a file or folder named \fB\fR in the current +working directory, then it will try to install that, and only try to +fetch the package by name if it is not valid\. +. +.IP "" 0 + +. +.IP "\(bu" 4 +\fBnpm install @\fR: +. +.IP +Install the version of the package that is referenced by the specified tag\. +If the tag does not exist in the registry data for that package, then this +will fail\. +. +.IP +Example: +. +.IP "" 4 +. +.nf + npm install sax@latest +. +.fi +. +.IP "" 0 + +. +.IP "\(bu" 4 +\fBnpm install @\fR: +. +.IP +Install the specified version of the package\. This will fail if the version +has not been published to the registry\. +. +.IP +Example: +. +.IP "" 4 +. +.nf + npm install sax@0\.1\.1 +. +.fi +. +.IP "" 0 + +. +.IP "\(bu" 4 +\fBnpm install @\fR: +. +.IP +Install a version of the package matching the specified version range\. This +will follow the same rules for resolving dependencies described in \fBnpm help json\fR\|\. +. +.IP +Note that most version ranges must be put in quotes so that your shell will +treat it as a single argument\. +. +.IP +Example: +. +.IP + npm install sax@">=0\.1\.0 <0\.2\.0" +. +.IP "\(bu" 4 +\fBnpm install \fR: +. +.IP +Install a package by cloning a git remote url\. The format of the git +url is: +. +.IP + ://[@][#] +. +.IP +\fB\fR is one of \fBgit\fR, \fBgit+ssh\fR, \fBgit+http\fR, or \fBgit+https\fR\|\. If no \fB\fR is specified, then \fBmaster\fR is +used\. +. +.IP +Examples: +. +.IP "" 4 +. +.nf + git+ssh://git@github\.com:isaacs/npm\.git#v1\.0\.27 + git+https://isaacs@github\.com/isaacs/npm\.git + git://github\.com/isaacs/npm\.git#v1\.0\.27 +. +.fi +. +.IP "" 0 + +. +.IP "" 0 +. +.P +You may combine multiple arguments, and even multiple types of arguments\. +For example: +. +.IP "" 4 +. +.nf +npm install sax@">=0\.1\.0 <0\.2\.0" bench supervisor +. +.fi +. +.IP "" 0 +. +.P +The \fB\-\-tag\fR argument will apply to all of the specified install targets\. +. +.P +The \fB\-\-force\fR argument will force npm to fetch remote resources even if a +local copy exists on disk\. +. +.IP "" 4 +. +.nf +npm install sax \-\-force +. +.fi +. +.IP "" 0 +. +.P +The \fB\-\-global\fR argument will cause npm to install the package globally +rather than locally\. See \fBnpm help folders\fR\|\. +. +.P +The \fB\-\-link\fR argument will cause npm to link global installs into the +local space in some cases\. +. +.P +See \fBnpm help config\fR\|\. Many of the configuration params have some +effect on installation, since that\'s most of what npm does\. +. +.SH "ALGORITHM" +To install a package, npm uses the following algorithm: +. +.IP "" 4 +. +.nf +install(where, what, family, ancestors) +fetch what, unpack to /node_modules/ +for each dep in what\.dependencies + resolve dep to precise version +for each dep@version in what\.dependencies + not in /node_modules//node_modules/* + and not in + add precise version deps to + install(/node_modules/, dep, family) +. +.fi +. +.IP "" 0 +. +.P +For this \fBpackage{dep}\fR structure: \fBA{B,C}, B{C}, C{D}\fR, +this algorithm produces: +. +.IP "" 4 +. +.nf +A ++\-\- B +`\-\- C + `\-\- D +. +.fi +. +.IP "" 0 +. +.P +That is, the dependency from B to C is satisfied by the fact that A +already caused C to be installed at a higher level\. +. +.P +See npm help folders for a more detailed description of the specific +folder structures that npm creates\. +. +.SS "Limitations of npm's Install Algorithm" +There are some very rare and pathological edge\-cases where a cycle can +cause npm to try to install a never\-ending tree of packages\. Here is +the simplest case: +. +.IP "" 4 +. +.nf +A \-> B \-> A\' \-> B\' \-> A \-> B \-> A\' \-> B\' \-> A \-> \.\.\. +. +.fi +. +.IP "" 0 +. +.P +where \fBA\fR is some version of a package, and \fBA\'\fR is a different version +of the same package\. Because \fBB\fR depends on a different version of \fBA\fR +than the one that is already in the tree, it must install a separate +copy\. The same is true of \fBA\'\fR, which must install \fBB\'\fR\|\. Because \fBB\'\fR +depends on the original version of \fBA\fR, which has been overridden, the +cycle falls into infinite regress\. +. +.P +To avoid this situation, npm flat\-out refuses to install any \fBname@version\fR that is already present anywhere in the tree of package +folder ancestors\. A more correct, but more complex, solution would be +to symlink the existing version into the new location\. If this ever +affects a real use\-case, it will be investigated\. +. +.SH "SEE ALSO" +. +.IP "\(bu" 4 +npm help folders +. +.IP "\(bu" 4 +npm help update +. +.IP "\(bu" 4 +npm help link +. +.IP "\(bu" 4 +npm help rebuild +. +.IP "\(bu" 4 +npm help scripts +. +.IP "\(bu" 4 +npm help build +. +.IP "\(bu" 4 +npm help config +. +.IP "\(bu" 4 +npm help registry +. +.IP "\(bu" 4 +npm help folders +. +.IP "\(bu" 4 +npm help tag +. +.IP "\(bu" 4 +npm help rm +. +.IP "\(bu" 4 +npm help shrinkwrap +. +.IP "" 0 + diff --git a/node-v0.8.14/deps/npm/man/man1/json.1 b/node-v0.8.14/deps/npm/man/man1/json.1 new file mode 100644 index 0000000..0ea424c --- /dev/null +++ b/node-v0.8.14/deps/npm/man/man1/json.1 @@ -0,0 +1,817 @@ +.\" Generated with Ronnjs 0.3.8 +.\" http://github.com/kapouer/ronnjs/ +. +.TH "NPM\-JSON" "1" "October 2012" "" "" +. +.SH "NAME" +\fBnpm-json\fR \-\- Specifics of npm\'s package\.json handling +. +.SH "DESCRIPTION" +This document is all you need to know about what\'s required in your package\.json +file\. It must be actual JSON, not just a JavaScript object literal\. +. +.P +A lot of the behavior described in this document is affected by the config +settings described in \fBnpm help config\fR\|\. +. +.SH "DEFAULT VALUES" +npm will default some values based on package contents\. +. +.IP "\(bu" 4 +\fB"scripts": {"start": "node server\.js"}\fR +. +.IP +If there is a \fBserver\.js\fR file in the root of your package, then npm +will default the \fBstart\fR command to \fBnode server\.js\fR\|\. +. +.IP "\(bu" 4 +\fB"scripts":{"preinstall": "node\-waf clean || true; node\-waf configure build"}\fR +. +.IP +If there is a \fBwscript\fR file in the root of your package, npm will +default the \fBpreinstall\fR command to compile using node\-waf\. +. +.IP "\(bu" 4 +\fB"scripts":{"preinstall": "node\-gyp rebuild"}\fR +. +.IP +If there is a \fBbinding\.gyp\fR file in the root of your package, npm will +default the \fBpreinstall\fR command to compile using node\-gyp\. +. +.IP "\(bu" 4 +\fB"contributors": [\.\.\.]\fR +. +.IP +If there is an \fBAUTHORS\fR file in the root of your package, npm will +treat each line as a \fBName (url)\fR format, where email and url +are optional\. Lines which start with a \fB#\fR or are blank, will be +ignored\. +. +.IP "" 0 +. +.SH "name" +The \fImost\fR important things in your package\.json are the name and version fields\. +Those are actually required, and your package won\'t install without +them\. The name and version together form an identifier that is assumed +to be completely unique\. Changes to the package should come along with +changes to the version\. +. +.P +The name is what your thing is called\. Some tips: +. +.IP "\(bu" 4 +Don\'t put "js" or "node" in the name\. It\'s assumed that it\'s js, since you\'re +writing a package\.json file, and you can specify the engine using the "engines" +field\. (See below\.) +. +.IP "\(bu" 4 +The name ends up being part of a URL, an argument on the command line, and a +folder name\. Any name with non\-url\-safe characters will be rejected\. +Also, it can\'t start with a dot or an underscore\. +. +.IP "\(bu" 4 +The name will probably be passed as an argument to require(), so it should +be something short, but also reasonably descriptive\. +. +.IP "\(bu" 4 +You may want to check the npm registry to see if there\'s something by that name +already, before you get too attached to it\. http://registry\.npmjs\.org/ +. +.IP "" 0 +. +.SH "version" +The \fImost\fR important things in your package\.json are the name and version fields\. +Those are actually required, and your package won\'t install without +them\. The name and version together form an identifier that is assumed +to be completely unique\. Changes to the package should come along with +changes to the version\. +. +.P +Version must be parseable by node\-semver \fIhttps://github\.com/isaacs/node\-semver\fR, which is bundled +with npm as a dependency\. (\fBnpm install semver\fR to use it yourself\.) +. +.P +Here\'s how npm\'s semver implementation deviates from what\'s on semver\.org: +. +.IP "\(bu" 4 +Versions can start with "v" +. +.IP "\(bu" 4 +A numeric item separated from the main three\-number version by a hyphen +will be interpreted as a "build" number, and will \fIincrease\fR the version\. +But, if the tag is not a number separated by a hyphen, then it\'s treated +as a pre\-release tag, and is \fIless than\fR the version without a tag\. +So, \fB0\.1\.2\-7 > 0\.1\.2\-7\-beta > 0\.1\.2\-6 > 0\.1\.2 > 0\.1\.2beta\fR +. +.IP "" 0 +. +.P +This is a little bit confusing to explain, but matches what you see in practice +when people create tags in git like "v1\.2\.3" and then do "git describe" to generate +a patch version\. +. +.SH "description" +Put a description in it\. It\'s a string\. This helps people discover your +package, as it\'s listed in \fBnpm search\fR\|\. +. +.SH "keywords" +Put keywords in it\. It\'s an array of strings\. This helps people +discover your package as it\'s listed in \fBnpm search\fR\|\. +. +.SH "homepage" +The url to the project homepage\. +. +.P +\fBNOTE\fR: This is \fInot\fR the same as "url"\. If you put a "url" field, +then the registry will think it\'s a redirection to your package that has +been published somewhere else, and spit at you\. +. +.P +Literally\. Spit\. I\'m so not kidding\. +. +.SH "bugs" +The url to your project\'s issue tracker and / or the email address to which +issues should be reported\. These are helpful for people who encounter issues +with your package\. +. +.P +It should look like this: +. +.IP "" 4 +. +.nf +{ "url" : "http://github\.com/owner/project/issues" +, "email" : "project@hostname\.com" +} +. +.fi +. +.IP "" 0 +. +.P +You can specify either one or both values\. If you want to provide only a url, +you can specify the value for "bugs" as a simple string instead of an object\. +. +.P +If a url is provided, it will be used by the \fBnpm bugs\fR command\. +. +.SH "people fields: author, contributors" +The "author" is one person\. "contributors" is an array of people\. A "person" +is an object with a "name" field and optionally "url" and "email", like this: +. +.IP "" 4 +. +.nf +{ "name" : "Barney Rubble" +, "email" : "b@rubble\.com" +, "url" : "http://barnyrubble\.tumblr\.com/" +} +. +.fi +. +.IP "" 0 +. +.P +Or you can shorten that all into a single string, and npm will parse it for you: +. +.IP "" 4 +. +.nf +"Barney Rubble (http://barnyrubble\.tumblr\.com/) +. +.fi +. +.IP "" 0 +. +.P +Both email and url are optional either way\. +. +.P +npm also sets a top\-level "maintainers" field with your npm user info\. +. +.SH "files" +The "files" field is an array of files to include in your project\. If +you name a folder in the array, then it will also include the files +inside that folder\. (Unless they would be ignored by another rule\.) +. +.P +You can also provide a "\.npmignore" file in the root of your package, +which will keep files from being included, even if they would be picked +up by the files array\. The "\.npmignore" file works just like a +"\.gitignore"\. +. +.SH "main" +The main field is a module ID that is the primary entry point to your program\. +That is, if your package is named \fBfoo\fR, and a user installs it, and then does \fBrequire("foo")\fR, then your main module\'s exports object will be returned\. +. +.P +This should be a module ID relative to the root of your package folder\. +. +.P +For most modules, it makes the most sense to have a main script and often not +much else\. +. +.SH "bin" +A lot of packages have one or more executable files that they\'d like to +install into the PATH\. npm makes this pretty easy (in fact, it uses this +feature to install the "npm" executable\.) +. +.P +To use this, supply a \fBbin\fR field in your package\.json which is a map of +command name to local file name\. On install, npm will symlink that file into \fBprefix/bin\fR for global installs, or \fB\|\./node_modules/\.bin/\fR for local +installs\. +. +.P +For example, npm has this: +. +.IP "" 4 +. +.nf +{ "bin" : { "npm" : "\./cli\.js" } } +. +.fi +. +.IP "" 0 +. +.P +So, when you install npm, it\'ll create a symlink from the \fBcli\.js\fR script to \fB/usr/local/bin/npm\fR\|\. +. +.P +If you have a single executable, and its name should be the name +of the package, then you can just supply it as a string\. For example: +. +.IP "" 4 +. +.nf +{ "name": "my\-program" +, "version": "1\.2\.5" +, "bin": "\./path/to/program" } +. +.fi +. +.IP "" 0 +. +.P +would be the same as this: +. +.IP "" 4 +. +.nf +{ "name": "my\-program" +, "version": "1\.2\.5" +, "bin" : { "my\-program" : "\./path/to/program" } } +. +.fi +. +.IP "" 0 +. +.SH "man" +Specify either a single file or an array of filenames to put in place for the \fBman\fR program to find\. +. +.P +If only a single file is provided, then it\'s installed such that it is the +result from \fBman \fR, regardless of its actual filename\. For example: +. +.IP "" 4 +. +.nf +{ "name" : "foo" +, "version" : "1\.2\.3" +, "description" : "A packaged foo fooer for fooing foos" +, "main" : "foo\.js" +, "man" : "\./man/doc\.1" +} +. +.fi +. +.IP "" 0 +. +.P +would link the \fB\|\./man/doc\.1\fR file in such that it is the target for \fBman foo\fR +. +.P +If the filename doesn\'t start with the package name, then it\'s prefixed\. +So, this: +. +.IP "" 4 +. +.nf +{ "name" : "foo" +, "version" : "1\.2\.3" +, "description" : "A packaged foo fooer for fooing foos" +, "main" : "foo\.js" +, "man" : [ "\./man/foo\.1", "\./man/bar\.1" ] +} +. +.fi +. +.IP "" 0 +. +.P +will create files to do \fBman foo\fR and \fBman foo\-bar\fR\|\. +. +.P +Man files must end with a number, and optionally a \fB\|\.gz\fR suffix if they are +compressed\. The number dictates which man section the file is installed into\. +. +.IP "" 4 +. +.nf +{ "name" : "foo" +, "version" : "1\.2\.3" +, "description" : "A packaged foo fooer for fooing foos" +, "main" : "foo\.js" +, "man" : [ "\./man/foo\.1", "\./man/foo\.2" ] +} +. +.fi +. +.IP "" 0 +. +.P +will create entries for \fBman foo\fR and \fBman 2 foo\fR +. +.SH "directories" +The CommonJS Packages \fIhttp://wiki\.commonjs\.org/wiki/Packages/1\.0\fR spec details a +few ways that you can indicate the structure of your package using a \fBdirectories\fR +hash\. If you look at npm\'s package\.json \fIhttp://registry\.npmjs\.org/npm/latest\fR, +you\'ll see that it has directories for doc, lib, and man\. +. +.P +In the future, this information may be used in other creative ways\. +. +.SS "directories\.lib" +Tell people where the bulk of your library is\. Nothing special is done +with the lib folder in any way, but it\'s useful meta info\. +. +.SS "directories\.bin" +If you specify a "bin" directory, then all the files in that folder will +be used as the "bin" hash\. +. +.P +If you have a "bin" hash already, then this has no effect\. +. +.SS "directories\.man" +A folder that is full of man pages\. Sugar to generate a "man" array by +walking the folder\. +. +.SS "directories\.doc" +Put markdown files in here\. Eventually, these will be displayed nicely, +maybe, someday\. +. +.SS "directories\.example" +Put example scripts in here\. Someday, it might be exposed in some clever way\. +. +.SH "repository" +Specify the place where your code lives\. This is helpful for people who +want to contribute\. If the git repo is on github, then the \fBnpm docs\fR +command will be able to find you\. +. +.P +Do it like this: +. +.IP "" 4 +. +.nf +"repository" : + { "type" : "git" + , "url" : "http://github\.com/isaacs/npm\.git" + } +"repository" : + { "type" : "svn" + , "url" : "http://v8\.googlecode\.com/svn/trunk/" + } +. +.fi +. +.IP "" 0 +. +.P +The URL should be a publicly available (perhaps read\-only) url that can be handed +directly to a VCS program without any modification\. It should not be a url to an +html project page that you put in your browser\. It\'s for computers\. +. +.SH "scripts" +The "scripts" member is an object hash of script commands that are run +at various times in the lifecycle of your package\. The key is the lifecycle +event, and the value is the command to run at that point\. +. +.P +See \fBnpm help scripts\fR to find out more about writing package scripts\. +. +.SH "config" +A "config" hash can be used to set configuration +parameters used in package scripts that persist across upgrades\. For +instance, if a package had the following: +. +.IP "" 4 +. +.nf +{ "name" : "foo" +, "config" : { "port" : "8080" } } +. +.fi +. +.IP "" 0 +. +.P +and then had a "start" command that then referenced the \fBnpm_package_config_port\fR environment variable, then the user could +override that by doing \fBnpm config set foo:port 8001\fR\|\. +. +.P +See \fBnpm help config\fR and \fBnpm help scripts\fR for more on package +configs\. +. +.SH "dependencies" +Dependencies are specified with a simple hash of package name to version +range\. The version range is EITHER a string which has one or more +space\-separated descriptors, OR a range like "fromVersion \- toVersion" +. +.P +\fBPlease do not put test harnesses in your \fBdependencies\fR hash\.\fR See \fBdevDependencies\fR, below\. +. +.P +Version range descriptors may be any of the following styles, where "version" +is a semver compatible version identifier\. +. +.IP "\(bu" 4 +\fBversion\fR Must match \fBversion\fR exactly +. +.IP "\(bu" 4 +\fB=version\fR Same as just \fBversion\fR +. +.IP "\(bu" 4 +\fB>version\fR Must be greater than \fBversion\fR +. +.IP "\(bu" 4 +\fB>=version\fR etc +. +.IP "\(bu" 4 +\fB=version1 <=version2\fR\|\. +. +.IP "\(bu" 4 +\fBrange1 || range2\fR Passes if either range1 or range2 are satisfied\. +. +.IP "\(bu" 4 +\fBgit\.\.\.\fR See \'Git URLs as Dependencies\' below +. +.IP "" 0 +. +.P +For example, these are all valid: +. +.IP "" 4 +. +.nf +{ "dependencies" : + { "foo" : "1\.0\.0 \- 2\.9999\.9999" + , "bar" : ">=1\.0\.2 <2\.1\.2" + , "baz" : ">1\.0\.2 <=2\.3\.4" + , "boo" : "2\.0\.1" + , "qux" : "<1\.0\.0 || >=2\.3\.1 <2\.4\.5 || >=2\.5\.2 <3\.0\.0" + , "asd" : "http://asdf\.com/asdf\.tar\.gz" + , "til" : "~1\.2" + , "elf" : "~1\.2\.3" + , "two" : "2\.x" + , "thr" : "3\.3\.x" + } +} +. +.fi +. +.IP "" 0 +. +.SS "Tilde Version Ranges" +A range specifier starting with a tilde \fB~\fR character is matched against +a version in the following fashion\. +. +.IP "\(bu" 4 +The version must be at least as high as the range\. +. +.IP "\(bu" 4 +The version must be less than the next major revision above the range\. +. +.IP "" 0 +. +.P +For example, the following are equivalent: +. +.IP "\(bu" 4 +\fB"~1\.2\.3" = ">=1\.2\.3 <1\.3\.0"\fR +. +.IP "\(bu" 4 +\fB"~1\.2" = ">=1\.2\.0 <2\.0\.0"\fR +. +.IP "\(bu" 4 +\fB"~1" = ">=1\.0\.0 <2\.0\.0"\fR +. +.IP "" 0 +. +.SS "X Version Ranges" +An "x" in a version range specifies that the version number must start +with the supplied digits, but any digit may be used in place of the x\. +. +.P +The following are equivalent: +. +.IP "\(bu" 4 +\fB"1\.2\.x" = ">=1\.2\.0 <1\.3\.0"\fR +. +.IP "\(bu" 4 +\fB"1\.x\.x" = ">=1\.0\.0 <2\.0\.0"\fR +. +.IP "\(bu" 4 +\fB"1\.2" = "1\.2\.x"\fR +. +.IP "\(bu" 4 +\fB"1\.x" = "1\.x\.x"\fR +. +.IP "\(bu" 4 +\fB"1" = "1\.x\.x"\fR +. +.IP "" 0 +. +.P +You may not supply a comparator with a version containing an x\. Any +digits after the first "x" are ignored\. +. +.SS "URLs as Dependencies" +Starting with npm version 0\.2\.14, you may specify a tarball URL in place +of a version range\. +. +.P +This tarball will be downloaded and installed locally to your package at +install time\. +. +.SS "Git URLs as Dependencies" +Git urls can be of the form: +. +.IP "" 4 +. +.nf +git://github\.com/user/project\.git#commit\-ish +git+ssh://user@hostname:project\.git#commit\-ish +git+ssh://user@hostname/project\.git#commit\-ish +git+http://user@hostname/project/blah\.git#commit\-ish +git+https://user@hostname/project/blah\.git#commit\-ish +. +.fi +. +.IP "" 0 +. +.P +The \fBcommit\-ish\fR can be any tag, sha, or branch which can be supplied as +an argument to \fBgit checkout\fR\|\. The default is \fBmaster\fR\|\. +. +.SH "devDependencies" +If someone is planning on downloading and using your module in their +program, then they probably don\'t want or need to download and build +the external test or documentation framework that you use\. +. +.P +In this case, it\'s best to list these additional items in a \fBdevDependencies\fR hash\. +. +.P +These things will be installed whenever the \fB\-\-dev\fR configuration flag +is set\. This flag is set automatically when doing \fBnpm link\fR, and can +be managed like any other npm configuration param\. See \fBnpm help config\fR +for more on the topic\. +. +.SH "bundledDependencies" +Array of package names that will be bundled when publishing the package\. +. +.P +If this is spelled \fB"bundleDependencies"\fR, then that is also honorable\. +. +.SH "optionalDependencies" +If a dependency can be used, but you would like npm to proceed if it +cannot be found or fails to install, then you may put it in the \fBoptionalDependencies\fR hash\. This is a map of package name to version +or url, just like the \fBdependencies\fR hash\. The difference is that +failure is tolerated\. +. +.P +It is still your program\'s responsibility to handle the lack of the +dependency\. For example, something like this: +. +.IP "" 4 +. +.nf +try { + var foo = require(\'foo\') + var fooVersion = require(\'foo/package\.json\')\.version +} catch (er) { + foo = null +} +if ( notGoodFooVersion(fooVersion) ) { + foo = null +} +// \.\. then later in your program \.\. +if (foo) { + foo\.doFooThings() +} +. +.fi +. +.IP "" 0 +. +.P +Entries in \fBoptionalDependencies\fR will override entries of the same name in \fBdependencies\fR, so it\'s usually best to only put in one place\. +. +.SH "engines" +You can specify the version of node that your stuff works on: +. +.IP "" 4 +. +.nf +{ "engines" : { "node" : ">=0\.1\.27 <0\.1\.30" } } +. +.fi +. +.IP "" 0 +. +.P +And, like with dependencies, if you don\'t specify the version (or if you +specify "*" as the version), then any version of node will do\. +. +.P +If you specify an "engines" field, then npm will require that "node" be +somewhere on that list\. If "engines" is omitted, then npm will just assume +that it works on node\. +. +.P +You can also use the "engines" field to specify which versions of npm +are capable of properly installing your program\. For example: +. +.IP "" 4 +. +.nf +{ "engines" : { "npm" : "~1\.0\.20" } } +. +.fi +. +.IP "" 0 +. +.P +Note that, unless the user has set the \fBengine\-strict\fR config flag, this +field is advisory only\. +. +.SH "engineStrict" +If you are sure that your module will \fIdefinitely not\fR run properly on +versions of Node/npm other than those specified in the \fBengines\fR hash, +then you can set \fB"engineStrict": true\fR in your package\.json file\. +This will override the user\'s \fBengine\-strict\fR config setting\. +. +.P +Please do not do this unless you are really very very sure\. If your +engines hash is something overly restrictive, you can quite easily and +inadvertently lock yourself into obscurity and prevent your users from +updating to new versions of Node\. Consider this choice carefully\. If +people abuse it, it will be removed in a future version of npm\. +. +.SH "os" +You can specify which operating systems your +module will run on: +. +.IP "" 4 +. +.nf +"os" : [ "darwin", "linux" ] +. +.fi +. +.IP "" 0 +. +.P +You can also blacklist instead of whitelist operating systems, +just prepend the blacklisted os with a \'!\': +. +.IP "" 4 +. +.nf +"os" : [ "!win32" ] +. +.fi +. +.IP "" 0 +. +.P +The host operating system is determined by \fBprocess\.platform\fR +. +.P +It is allowed to both blacklist, and whitelist, although there isn\'t any +good reason to do this\. +. +.SH "cpu" +If your code only runs on certain cpu architectures, +you can specify which ones\. +. +.IP "" 4 +. +.nf +"cpu" : [ "x64", "ia32" ] +. +.fi +. +.IP "" 0 +. +.P +Like the \fBos\fR option, you can also blacklist architectures: +. +.IP "" 4 +. +.nf +"cpu" : [ "!arm", "!mips" ] +. +.fi +. +.IP "" 0 +. +.P +The host architecture is determined by \fBprocess\.arch\fR +. +.SH "preferGlobal" +If your package is primarily a command\-line application that should be +installed globally, then set this value to \fBtrue\fR to provide a warning +if it is installed locally\. +. +.P +It doesn\'t actually prevent users from installing it locally, but it +does help prevent some confusion if it doesn\'t work as expected\. +. +.SH "private" +If you set \fB"private": true\fR in your package\.json, then npm will refuse +to publish it\. +. +.P +This is a way to prevent accidental publication of private repositories\. +If you would like to ensure that a given package is only ever published +to a specific registry (for example, an internal registry), +then use the \fBpublishConfig\fR hash described below +to override the \fBregistry\fR config param at publish\-time\. +. +.SH "publishConfig" +This is a set of config values that will be used at publish\-time\. It\'s +especially handy if you want to set the tag or registry, so that you can +ensure that a given package is not tagged with "latest" or published to +the global public registry by default\. +. +.P +Any config values can be overridden, but of course only "tag" and +"registry" probably matter for the purposes of publishing\. +. +.P +See \fBnpm help config\fR to see the list of config options that can be +overridden\. +. +.SH "SEE ALSO" +. +.IP "\(bu" 4 +npm help semver +. +.IP "\(bu" 4 +npm help init +. +.IP "\(bu" 4 +npm help version +. +.IP "\(bu" 4 +npm help config +. +.IP "\(bu" 4 +npm help help +. +.IP "\(bu" 4 +npm help faq +. +.IP "\(bu" 4 +npm help install +. +.IP "\(bu" 4 +npm help publish +. +.IP "\(bu" 4 +npm help rm +. +.IP "" 0 + diff --git a/node-v0.8.14/deps/npm/man/man1/link.1 b/node-v0.8.14/deps/npm/man/man1/link.1 new file mode 100644 index 0000000..b8583ab --- /dev/null +++ b/node-v0.8.14/deps/npm/man/man1/link.1 @@ -0,0 +1,108 @@ +.\" Generated with Ronnjs 0.3.8 +.\" http://github.com/kapouer/ronnjs/ +. +.TH "NPM\-LINK" "1" "October 2012" "" "" +. +.SH "NAME" +\fBnpm-link\fR \-\- Symlink a package folder +. +.SH "SYNOPSIS" +. +.nf +npm link (in package folder) +npm link +. +.fi +. +.SH "DESCRIPTION" +Package linking is a two\-step process\. +. +.P +First, \fBnpm link\fR in a package folder will create a globally\-installed +symbolic link from \fBprefix/package\-name\fR to the current folder\. +. +.P +Next, in some other location, \fBnpm link package\-name\fR will create a +symlink from the local \fBnode_modules\fR folder to the global symlink\. +. +.P +When creating tarballs for \fBnpm publish\fR, the linked packages are +"snapshotted" to their current state by resolving the symbolic links\. +. +.P +This is +handy for installing your own stuff, so that you can work on it and test it +iteratively without having to continually rebuild\. +. +.P +For example: +. +.IP "" 4 +. +.nf +cd ~/projects/node\-redis # go into the package directory +npm link # creates global link +cd ~/projects/node\-bloggy # go into some other package directory\. +npm link redis # link\-install the package +. +.fi +. +.IP "" 0 +. +.P +Now, any changes to ~/projects/node\-redis will be reflected in +~/projects/node\-bloggy/node_modules/redis/ +. +.P +You may also shortcut the two steps in one\. For example, to do the +above use\-case in a shorter way: +. +.IP "" 4 +. +.nf +cd ~/projects/node\-bloggy # go into the dir of your main project +npm link \.\./node\-redis # link the dir of your dependency +. +.fi +. +.IP "" 0 +. +.P +The second line is the equivalent of doing: +. +.IP "" 4 +. +.nf +(cd \.\./node\-redis; npm link) +npm link redis +. +.fi +. +.IP "" 0 +. +.P +That is, it first creates a global link, and then links the global +installation target into your project\'s \fBnode_modules\fR folder\. +. +.SH "SEE ALSO" +. +.IP "\(bu" 4 +npm help developers +. +.IP "\(bu" 4 +npm help faq +. +.IP "\(bu" 4 +npm help json +. +.IP "\(bu" 4 +npm help install +. +.IP "\(bu" 4 +npm help folders +. +.IP "\(bu" 4 +npm help config +. +.IP "" 0 + diff --git a/node-v0.8.14/deps/npm/man/man1/list.1 b/node-v0.8.14/deps/npm/man/man1/list.1 new file mode 100644 index 0000000..00a743a --- /dev/null +++ b/node-v0.8.14/deps/npm/man/man1/list.1 @@ -0,0 +1,125 @@ +.\" Generated with Ronnjs 0.3.8 +.\" http://github.com/kapouer/ronnjs/ +. +.TH "NPM\-LS" "1" "August 2012" "" "" +. +.SH "NAME" +\fBnpm-ls\fR \-\- List installed packages +. +.SH "SYNOPSIS" +. +.nf +npm list [ \.\.\.] +npm ls [ \.\.\.] +npm la [ \.\.\.] +npm ll [ \.\.\.] +. +.fi +. +.SH "DESCRIPTION" +This command will print to stdout all the versions of packages that are +installed, as well as their dependencies, in a tree\-structure\. +. +.P +Positional arguments are \fBname@version\-range\fR identifiers, which will +limit the results to only the paths to the packages named\. Note that +nested packages will \fIalso\fR show the paths to the specified packages\. +For example, running \fBnpm ls promzard\fR in npm\'s source tree will show: +. +.IP "" 4 +. +.nf +npm@1.1.59 /path/to/npm +└─┬ init\-package\-json@0\.0\.4 + └── promzard@0\.1\.5 +. +.fi +. +.IP "" 0 +. +.P +It will show print out extraneous, missing, and invalid packages\. +. +.P +When run as \fBll\fR or \fBla\fR, it shows extended information by default\. +. +.SH "CONFIGURATION" +. +.SS "json" +. +.IP "\(bu" 4 +Default: false +. +.IP "\(bu" 4 +Type: Boolean +. +.IP "" 0 +. +.P +Show information in JSON format\. +. +.SS "long" +. +.IP "\(bu" 4 +Default: false +. +.IP "\(bu" 4 +Type: Boolean +. +.IP "" 0 +. +.P +Show extended information\. +. +.SS "parseable" +. +.IP "\(bu" 4 +Default: false +. +.IP "\(bu" 4 +Type: Boolean +. +.IP "" 0 +. +.P +Show parseable output instead of tree view\. +. +.SS "global" +. +.IP "\(bu" 4 +Default: false +. +.IP "\(bu" 4 +Type: Boolean +. +.IP "" 0 +. +.P +List packages in the global install prefix instead of in the current +project\. +. +.SH "SEE ALSO" +. +.IP "\(bu" 4 +npm help config +. +.IP "\(bu" 4 +npm help folders +. +.IP "\(bu" 4 +npm help install +. +.IP "\(bu" 4 +npm help link +. +.IP "\(bu" 4 +npm help prune +. +.IP "\(bu" 4 +npm help outdated +. +.IP "\(bu" 4 +npm help update +. +.IP "" 0 + diff --git a/node-v0.8.14/deps/npm/man/man1/ln.1 b/node-v0.8.14/deps/npm/man/man1/ln.1 new file mode 100644 index 0000000..74bf729 --- /dev/null +++ b/node-v0.8.14/deps/npm/man/man1/ln.1 @@ -0,0 +1,108 @@ +.\" Generated with Ronnjs/v0.1 +.\" http://github.com/kapouer/ronnjs/ +. +.TH "NPM\-LINK" "1" "November 2011" "" "" +. +.SH "NAME" +\fBnpm-link\fR \-\- Symlink a package folder +. +.SH "SYNOPSIS" +. +.nf +npm link (in package folder) +npm link +. +.fi +. +.SH "DESCRIPTION" +Package linking is a two\-step process\. +. +.P +First, \fBnpm link\fR in a package folder will create a globally\-installed +symbolic link from \fBprefix/package\-name\fR to the current folder\. +. +.P +Next, in some other location, \fBnpm link package\-name\fR will create a +symlink from the local \fBnode_modules\fR folder to the global symlink\. +. +.P +When creating tarballs for \fBnpm publish\fR, the linked packages are +"snapshotted" to their current state by resolving the symbolic links\. +. +.P +This is +handy for installing your own stuff, so that you can work on it and test it +iteratively without having to continually rebuild\. +. +.P +For example: +. +.IP "" 4 +. +.nf +cd ~/projects/node\-redis # go into the package directory +npm link # creates global link +cd ~/projects/node\-bloggy # go into some other package directory\. +npm link redis # link\-install the package +. +.fi +. +.IP "" 0 +. +.P +Now, any changes to ~/projects/node\-redis will be reflected in +~/projects/node\-bloggy/node_modules/redis/ +. +.P +You may also shortcut the two steps in one\. For example, to do the +above use\-case in a shorter way: +. +.IP "" 4 +. +.nf +cd ~/projects/node\-bloggy # go into the dir of your main project +npm link \.\./node\-redis # link the dir of your dependency +. +.fi +. +.IP "" 0 +. +.P +The second line is the equivalent of doing: +. +.IP "" 4 +. +.nf +(cd \.\./node\-redis; npm link) +npm link redis +. +.fi +. +.IP "" 0 +. +.P +That is, it first creates a global link, and then links the global +installation target into your project\'s \fBnode_modules\fR folder\. +. +.SH "SEE ALSO" +. +.IP "\(bu" 4 +npm help developers +. +.IP "\(bu" 4 +npm help faq +. +.IP "\(bu" 4 +npm help json +. +.IP "\(bu" 4 +npm help install +. +.IP "\(bu" 4 +npm help folders +. +.IP "\(bu" 4 +npm help config +. +.IP "" 0 + diff --git a/node-v0.8.14/deps/npm/man/man1/ls.1 b/node-v0.8.14/deps/npm/man/man1/ls.1 new file mode 100644 index 0000000..00d9be7 --- /dev/null +++ b/node-v0.8.14/deps/npm/man/man1/ls.1 @@ -0,0 +1,125 @@ +.\" Generated with Ronnjs 0.3.8 +.\" http://github.com/kapouer/ronnjs/ +. +.TH "NPM\-LS" "1" "October 2012" "" "" +. +.SH "NAME" +\fBnpm-ls\fR \-\- List installed packages +. +.SH "SYNOPSIS" +. +.nf +npm list [ \.\.\.] +npm ls [ \.\.\.] +npm la [ \.\.\.] +npm ll [ \.\.\.] +. +.fi +. +.SH "DESCRIPTION" +This command will print to stdout all the versions of packages that are +installed, as well as their dependencies, in a tree\-structure\. +. +.P +Positional arguments are \fBname@version\-range\fR identifiers, which will +limit the results to only the paths to the packages named\. Note that +nested packages will \fIalso\fR show the paths to the specified packages\. +For example, running \fBnpm ls promzard\fR in npm\'s source tree will show: +. +.IP "" 4 +. +.nf +npm@1.1.65 /path/to/npm +└─┬ init\-package\-json@0\.0\.4 + └── promzard@0\.1\.5 +. +.fi +. +.IP "" 0 +. +.P +It will show print out extraneous, missing, and invalid packages\. +. +.P +When run as \fBll\fR or \fBla\fR, it shows extended information by default\. +. +.SH "CONFIGURATION" +. +.SS "json" +. +.IP "\(bu" 4 +Default: false +. +.IP "\(bu" 4 +Type: Boolean +. +.IP "" 0 +. +.P +Show information in JSON format\. +. +.SS "long" +. +.IP "\(bu" 4 +Default: false +. +.IP "\(bu" 4 +Type: Boolean +. +.IP "" 0 +. +.P +Show extended information\. +. +.SS "parseable" +. +.IP "\(bu" 4 +Default: false +. +.IP "\(bu" 4 +Type: Boolean +. +.IP "" 0 +. +.P +Show parseable output instead of tree view\. +. +.SS "global" +. +.IP "\(bu" 4 +Default: false +. +.IP "\(bu" 4 +Type: Boolean +. +.IP "" 0 +. +.P +List packages in the global install prefix instead of in the current +project\. +. +.SH "SEE ALSO" +. +.IP "\(bu" 4 +npm help config +. +.IP "\(bu" 4 +npm help folders +. +.IP "\(bu" 4 +npm help install +. +.IP "\(bu" 4 +npm help link +. +.IP "\(bu" 4 +npm help prune +. +.IP "\(bu" 4 +npm help outdated +. +.IP "\(bu" 4 +npm help update +. +.IP "" 0 + diff --git a/node-v0.8.14/deps/npm/man/man1/npm.1 b/node-v0.8.14/deps/npm/man/man1/npm.1 new file mode 100644 index 0000000..bb60c93 --- /dev/null +++ b/node-v0.8.14/deps/npm/man/man1/npm.1 @@ -0,0 +1,227 @@ +.\" Generated with Ronnjs 0.3.8 +.\" http://github.com/kapouer/ronnjs/ +. +.TH "NPM" "1" "October 2012" "" "" +. +.SH "NAME" +\fBnpm\fR \-\- node package manager +. +.SH "SYNOPSIS" +. +.nf +npm [args] +. +.fi +. +.SH "VERSION" +1.1.65 +. +.SH "DESCRIPTION" +npm is the package manager for the Node JavaScript platform\. It puts +modules in place so that node can find them, and manages dependency +conflicts intelligently\. +. +.P +It is extremely configurable to support a wide variety of use cases\. +Most commonly, it is used to publish, discover, install, and develop node +programs\. +. +.P +Run \fBnpm help\fR to get a list of available commands\. +. +.SH "INTRODUCTION" +You probably got npm because you want to install stuff\. +. +.P +Use \fBnpm install blerg\fR to install the latest version of "blerg"\. Check out \fBnpm help install\fR for more info\. It can do a lot of stuff\. +. +.P +Use the \fBnpm search\fR command to show everything that\'s available\. +Use \fBnpm ls\fR to show everything you\'ve installed\. +. +.SH "DIRECTORIES" +See \fBnpm help folders\fR to learn about where npm puts stuff\. +. +.P +In particular, npm has two modes of operation: +. +.IP "\(bu" 4 +global mode: +. +.br +npm installs packages into the install prefix at \fBprefix/lib/node_modules\fR and bins are installed in \fBprefix/bin\fR\|\. +. +.IP "\(bu" 4 +local mode: +. +.br +npm installs packages into the current project directory, which +defaults to the current working directory\. Packages are installed to \fB\|\./node_modules\fR, and bins are installed to \fB\|\./node_modules/\.bin\fR\|\. +. +.IP "" 0 +. +.P +Local mode is the default\. Use \fB\-\-global\fR or \fB\-g\fR on any command to +operate in global mode instead\. +. +.SH "DEVELOPER USAGE" +If you\'re using npm to develop and publish your code, check out the +following help topics: +. +.IP "\(bu" 4 +json: +Make a package\.json file\. See \fBnpm help json\fR\|\. +. +.IP "\(bu" 4 +link: +For linking your current working code into Node\'s path, so that you +don\'t have to reinstall every time you make a change\. Use \fBnpm link\fR to do this\. +. +.IP "\(bu" 4 +install: +It\'s a good idea to install things if you don\'t need the symbolic link\. +Especially, installing other peoples code from the registry is done via \fBnpm install\fR +. +.IP "\(bu" 4 +adduser: +Create an account or log in\. Credentials are stored in the +user config file\. +. +.IP "\(bu" 4 +publish: +Use the \fBnpm publish\fR command to upload your code to the registry\. +. +.IP "" 0 +. +.SH "CONFIGURATION" +npm is extremely configurable\. It reads its configuration options from +5 places\. +. +.IP "\(bu" 4 +Command line switches: +. +.br +Set a config with \fB\-\-key val\fR\|\. All keys take a value, even if they +are booleans (the config parser doesn\'t know what the options are at +the time of parsing\.) If no value is provided, then the option is set +to boolean \fBtrue\fR\|\. +. +.IP "\(bu" 4 +Environment Variables: +. +.br +Set any config by prefixing the name in an environment variable with \fBnpm_config_\fR\|\. For example, \fBexport npm_config_key=val\fR\|\. +. +.IP "\(bu" 4 +User Configs: +. +.br +The file at $HOME/\.npmrc is an ini\-formatted list of configs\. If +present, it is parsed\. If the \fBuserconfig\fR option is set in the cli +or env, then that will be used instead\. +. +.IP "\(bu" 4 +Global Configs: +. +.br +The file found at \.\./etc/npmrc (from the node executable, by default +this resolves to /usr/local/etc/npmrc) will be parsed if it is found\. +If the \fBglobalconfig\fR option is set in the cli, env, or user config, +then that file is parsed instead\. +. +.IP "\(bu" 4 +Defaults: +. +.br +npm\'s default configuration options are defined in +lib/utils/config\-defs\.js\. These must not be changed\. +. +.IP "" 0 +. +.P +See \fBnpm help config\fR for much much more information\. +. +.SH "CONTRIBUTIONS" +Patches welcome! +. +.IP "\(bu" 4 +code: +Read through \fBnpm help coding\-style\fR if you plan to submit code\. +You don\'t have to agree with it, but you do have to follow it\. +. +.IP "\(bu" 4 +docs: +If you find an error in the documentation, edit the appropriate markdown +file in the "doc" folder\. (Don\'t worry about generating the man page\.) +. +.IP "" 0 +. +.P +Contributors are listed in npm\'s \fBpackage\.json\fR file\. You can view them +easily by doing \fBnpm view npm contributors\fR\|\. +. +.P +If you would like to contribute, but don\'t know what to work on, check +the issues list or ask on the mailing list\. +. +.IP "\(bu" 4 +\fIhttp://github\.com/isaacs/npm/issues\fR +. +.IP "\(bu" 4 +\fInpm\-@googlegroups\.com\fR +. +.IP "" 0 +. +.SH "BUGS" +When you find issues, please report them: +. +.IP "\(bu" 4 +web: \fIhttp://github\.com/isaacs/npm/issues\fR +. +.IP "\(bu" 4 +email: \fInpm\-@googlegroups\.com\fR +. +.IP "" 0 +. +.P +Be sure to include \fIall\fR of the output from the npm command that didn\'t work +as expected\. The \fBnpm\-debug\.log\fR file is also helpful to provide\. +. +.P +You can also look for isaacs in #node\.js on irc://irc\.freenode\.net\. He +will no doubt tell you to put the output in a gist or email\. +. +.SH "HISTORY" +See npm help changelog +. +.SH "AUTHOR" +Isaac Z\. Schlueter \fIhttp://blog\.izs\.me/\fR :: isaacs \fIhttps://github\.com/isaacs/\fR :: @izs \fIhttp://twitter\.com/izs\fR :: \fIi@izs\.me\fR +. +.SH "SEE ALSO" +. +.IP "\(bu" 4 +npm help help +. +.IP "\(bu" 4 +npm help faq +. +.IP "\(bu" 4 +README +. +.IP "\(bu" 4 +npm help json +. +.IP "\(bu" 4 +npm help install +. +.IP "\(bu" 4 +npm help config +. +.IP "\(bu" 4 +npm help index +. +.IP "\(bu" 4 +npm apihelp npm +. +.IP "" 0 + diff --git a/node-v0.8.14/deps/npm/man/man1/outdated.1 b/node-v0.8.14/deps/npm/man/man1/outdated.1 new file mode 100644 index 0000000..d04989c --- /dev/null +++ b/node-v0.8.14/deps/npm/man/man1/outdated.1 @@ -0,0 +1,32 @@ +.\" Generated with Ronnjs 0.3.8 +.\" http://github.com/kapouer/ronnjs/ +. +.TH "NPM\-OUTDATED" "1" "October 2012" "" "" +. +.SH "NAME" +\fBnpm-outdated\fR \-\- Check for outdated packages +. +.SH "SYNOPSIS" +. +.nf +npm outdated [ [ \.\.\.]] +. +.fi +. +.SH "DESCRIPTION" +This command will check the registry to see if any (or, specific) installed +packages are currently outdated\. +. +.SH "SEE ALSO" +. +.IP "\(bu" 4 +npm help update +. +.IP "\(bu" 4 +npm help registry +. +.IP "\(bu" 4 +npm help folders +. +.IP "" 0 + diff --git a/node-v0.8.14/deps/npm/man/man1/owner.1 b/node-v0.8.14/deps/npm/man/man1/owner.1 new file mode 100644 index 0000000..79a8faf --- /dev/null +++ b/node-v0.8.14/deps/npm/man/man1/owner.1 @@ -0,0 +1,58 @@ +.\" Generated with Ronnjs 0.3.8 +.\" http://github.com/kapouer/ronnjs/ +. +.TH "NPM\-OWNER" "1" "October 2012" "" "" +. +.SH "NAME" +\fBnpm-owner\fR \-\- Manage package owners +. +.SH "SYNOPSIS" +. +.nf +npm owner ls +npm owner add +npm owner rm +. +.fi +. +.SH "DESCRIPTION" +Manage ownership of published packages\. +. +.IP "\(bu" 4 +ls: +List all the users who have access to modify a package and push new versions\. +Handy when you need to know who to bug for help\. +. +.IP "\(bu" 4 +add: +Add a new user as a maintainer of a package\. This user is enabled to modify +metadata, publish new versions, and add other owners\. +. +.IP "\(bu" 4 +rm: +Remove a user from the package owner list\. This immediately revokes their +privileges\. +. +.IP "" 0 +. +.P +Note that there is only one level of access\. Either you can modify a package, +or you can\'t\. Future versions may contain more fine\-grained access levels, but +that is not implemented at this time\. +. +.SH "SEE ALSO" +. +.IP "\(bu" 4 +npm help publish +. +.IP "\(bu" 4 +npm help registry +. +.IP "\(bu" 4 +npm help adduser +. +.IP "\(bu" 4 +npm help disputes +. +.IP "" 0 + diff --git a/node-v0.8.14/deps/npm/man/man1/pack.1 b/node-v0.8.14/deps/npm/man/man1/pack.1 new file mode 100644 index 0000000..f48391f --- /dev/null +++ b/node-v0.8.14/deps/npm/man/man1/pack.1 @@ -0,0 +1,42 @@ +.\" Generated with Ronnjs 0.3.8 +.\" http://github.com/kapouer/ronnjs/ +. +.TH "NPM\-PACK" "1" "October 2012" "" "" +. +.SH "NAME" +\fBnpm-pack\fR \-\- Create a tarball from a package +. +.SH "SYNOPSIS" +. +.nf +npm pack [ [ \.\.\.]] +. +.fi +. +.SH "DESCRIPTION" +For anything that\'s installable (that is, a package folder, tarball, +tarball url, name@tag, name@version, or name), this command will fetch +it to the cache, and then copy the tarball to the current working +directory as \fB\-\.tgz\fR, and then write the filenames out to +stdout\. +. +.P +If the same package is specified multiple times, then the file will be +overwritten the second time\. +. +.P +If no arguments are supplied, then npm packs the current package folder\. +. +.SH "SEE ALSO" +. +.IP "\(bu" 4 +npm help cache +. +.IP "\(bu" 4 +npm help publish +. +.IP "\(bu" 4 +npm help config +. +.IP "" 0 + diff --git a/node-v0.8.14/deps/npm/man/man1/prefix.1 b/node-v0.8.14/deps/npm/man/man1/prefix.1 new file mode 100644 index 0000000..1a82395 --- /dev/null +++ b/node-v0.8.14/deps/npm/man/man1/prefix.1 @@ -0,0 +1,34 @@ +.\" Generated with Ronnjs 0.3.8 +.\" http://github.com/kapouer/ronnjs/ +. +.TH "NPM\-PREFIX" "1" "October 2012" "" "" +. +.SH "NAME" +\fBnpm-prefix\fR \-\- Display prefix +. +.SH "SYNOPSIS" +. +.nf +npm prefix +. +.fi +. +.SH "DESCRIPTION" +Print the prefix to standard out\. +. +.SH "SEE ALSO" +. +.IP "\(bu" 4 +npm help root +. +.IP "\(bu" 4 +npm help bin +. +.IP "\(bu" 4 +npm help folders +. +.IP "\(bu" 4 +npm help config +. +.IP "" 0 + diff --git a/node-v0.8.14/deps/npm/man/man1/prune.1 b/node-v0.8.14/deps/npm/man/man1/prune.1 new file mode 100644 index 0000000..387b89d --- /dev/null +++ b/node-v0.8.14/deps/npm/man/man1/prune.1 @@ -0,0 +1,37 @@ +.\" Generated with Ronnjs 0.3.8 +.\" http://github.com/kapouer/ronnjs/ +. +.TH "NPM\-PRUNE" "1" "October 2012" "" "" +. +.SH "NAME" +\fBnpm-prune\fR \-\- Remove extraneous packages +. +.SH "SYNOPSIS" +. +.nf +npm prune [ [ +npm publish +. +.fi +. +.SH "DESCRIPTION" +Publishes a package to the registry so that it can be installed by name\. +. +.IP "\(bu" 4 +\fB\fR: +A folder containing a package\.json file +. +.IP "\(bu" 4 +\fB\fR: +A url or file path to a gzipped tar archive containing a single folder +with a package\.json file inside\. +. +.IP "" 0 +. +.P +Fails if the package name and version combination already exists in +the registry\. Overwrites when the "\-\-force" flag is set\. +. +.SH "SEE ALSO" +. +.IP "\(bu" 4 +npm help registry +. +.IP "\(bu" 4 +npm help adduser +. +.IP "\(bu" 4 +npm help owner +. +.IP "\(bu" 4 +npm help deprecate +. +.IP "\(bu" 4 +npm help tag +. +.IP "" 0 + diff --git a/node-v0.8.14/deps/npm/man/man1/rebuild.1 b/node-v0.8.14/deps/npm/man/man1/rebuild.1 new file mode 100644 index 0000000..4432d7b --- /dev/null +++ b/node-v0.8.14/deps/npm/man/man1/rebuild.1 @@ -0,0 +1,36 @@ +.\" Generated with Ronnjs 0.3.8 +.\" http://github.com/kapouer/ronnjs/ +. +.TH "NPM\-REBUILD" "1" "October 2012" "" "" +. +.SH "NAME" +\fBnpm-rebuild\fR \-\- Rebuild a package +. +.SH "SYNOPSIS" +. +.nf +npm rebuild [ [ \.\.\.]] +. +.fi +. +.IP "\(bu" 4 +\fB\fR: +The package to rebuild +. +.IP "" 0 +. +.SH "DESCRIPTION" +This command runs the \fBnpm build\fR command on the matched folders\. This is useful +when you install a new version of node, and must recompile all your C++ addons with +the new binary\. +. +.SH "SEE ALSO" +. +.IP "\(bu" 4 +npm help build +. +.IP "\(bu" 4 +npm help install +. +.IP "" 0 + diff --git a/node-v0.8.14/deps/npm/man/man1/registry.1 b/node-v0.8.14/deps/npm/man/man1/registry.1 new file mode 100644 index 0000000..83665a6 --- /dev/null +++ b/node-v0.8.14/deps/npm/man/man1/registry.1 @@ -0,0 +1,110 @@ +.\" Generated with Ronnjs 0.3.8 +.\" http://github.com/kapouer/ronnjs/ +. +.TH "NPM\-REGISTRY" "1" "October 2012" "" "" +. +.SH "NAME" +\fBnpm-registry\fR \-\- The JavaScript Package Registry +. +.SH "DESCRIPTION" +To resolve packages by name and version, npm talks to a registry website +that implements the CommonJS Package Registry specification for reading +package info\. +. +.P +Additionally, npm\'s package registry implementation supports several +write APIs as well, to allow for publishing packages and managing user +account information\. +. +.P +The official public npm registry is at \fIhttp://registry\.npmjs\.org/\fR\|\. It +is powered by a CouchDB database at \fIhttp://isaacs\.iriscouch\.com/registry\fR\|\. The code for the couchapp is +available at \fIhttp://github\.com/isaacs/npmjs\.org\fR\|\. npm user accounts +are CouchDB users, stored in the \fIhttp://isaacs\.iriscouch\.com/_users\fR +database\. +. +.P +The registry URL is supplied by the \fBregistry\fR config parameter\. See \fBnpm help config\fR for more on managing npm\'s configuration\. +. +.SH "Can I run my own private registry?" +Yes! +. +.P +The easiest way is to replicate the couch database, and use the same (or +similar) design doc to implement the APIs\. +. +.P +If you set up continuous replication from the official CouchDB, and then +set your internal CouchDB as the registry config, then you\'ll be able +to read any published packages, in addition to your private ones, and by +default will only publish internally\. If you then want to publish a +package for the whole world to see, you can simply override the \fB\-\-registry\fR config for that command\. +. +.SH "I don't want my package published in the official registry\. It's private\." +Set \fB"private": true\fR in your package\.json to prevent it from being +published at all, or \fB"publishConfig":{"registry":"http://my\-internal\-registry\.local"}\fR +to force it to be published only to your internal registry\. +. +.P +See \fBnpm help json\fR for more info on what goes in the package\.json file\. +. +.SH "Will you replicate from my registry into the public one?" +No\. If you want things to be public, then publish them into the public +registry using npm\. What little security there is would be for nought +otherwise\. +. +.SH "Do I have to use couchdb to build a registry that npm can talk to?" +No, but it\'s way easier\. +. +.SH "I published something elsewhere, and want to tell the npm registry about it\." +That is supported, but not using the npm client\. You\'ll have to get +your hands dirty and do some HTTP\. The request looks something like +this: +. +.IP "" 4 +. +.nf +PUT /my\-foreign\-package +content\-type:application/json +accept:application/json +authorization:Basic $base_64_encoded +{ "name":"my\-foreign\-package" +, "maintainers":["owner","usernames"] +, "description":"A package that is hosted elsewhere" +, "keywords":["nih","my cheese smells the best"] +, "url":"http://my\-different\-registry\.com/blerg/my\-local\-package" +} +. +.fi +. +.IP "" 0 +. +.P +(Keywords and description are optional, but recommended\. Name, +maintainers, and url are required\.) +. +.P +Then, when a user tries to install "my\-foreign\-package", it\'ll redirect +to your registry\. If that doesn\'t resolve to a valid package entry, +then it\'ll fail, so please make sure that you understand the spec, and +ask for help on the \fInpm\-@googlegroups\.com\fR mailing list\. +. +.SH "Is there a website or something to see package docs and such?" +No, but such a thing is planned, and a tiny bit developed\. +. +.P +Stay tuned! +. +.SH "SEE ALSO" +. +.IP "\(bu" 4 +npm help config +. +.IP "\(bu" 4 +npm help developers +. +.IP "\(bu" 4 +npm help disputes +. +.IP "" 0 + diff --git a/node-v0.8.14/deps/npm/man/man1/removing-npm.1 b/node-v0.8.14/deps/npm/man/man1/removing-npm.1 new file mode 100644 index 0000000..1e6c6a4 --- /dev/null +++ b/node-v0.8.14/deps/npm/man/man1/removing-npm.1 @@ -0,0 +1,107 @@ +.\" Generated with Ronnjs 0.3.8 +.\" http://github.com/kapouer/ronnjs/ +. +.TH "NPM\-REMOVAL" "1" "October 2012" "" "" +. +.SH "NAME" +\fBnpm-removal\fR \-\- Cleaning the Slate +. +.SH "SYNOPSIS" +So sad to see you go\. +. +.IP "" 4 +. +.nf +sudo npm uninstall npm \-g +. +.fi +. +.IP "" 0 +. +.P +Or, if that fails, get the npm source code, and do: +. +.IP "" 4 +. +.nf +sudo make uninstall +. +.fi +. +.IP "" 0 +. +.SH "More Severe Uninstalling" +Usually, the above instructions are sufficient\. That will remove +npm, but leave behind anything you\'ve installed\. +. +.P +If that doesn\'t work, or if you require more drastic measures, +continue reading\. +. +.P +Note that this is only necessary for globally\-installed packages\. Local +installs are completely contained within a project\'s \fBnode_modules\fR +folder\. Delete that folder, and everything is gone (unless a package\'s +install script is particularly ill\-behaved)\. +. +.P +This assumes that you installed node and npm in the default place\. If +you configured node with a different \fB\-\-prefix\fR, or installed npm with a +different prefix setting, then adjust the paths accordingly, replacing \fB/usr/local\fR with your install prefix\. +. +.P +To remove everything npm\-related manually: +. +.IP "" 4 +. +.nf +rm \-rf /usr/local/{lib/node{,/\.npm,_modules},bin,share/man}/npm* +. +.fi +. +.IP "" 0 +. +.P +If you installed things \fIwith\fR npm, then your best bet is to uninstall +them with npm first, and then install them again once you have a +proper install\. This can help find any symlinks that are lying +around: +. +.IP "" 4 +. +.nf +ls \-laF /usr/local/{lib/node{,/\.npm},bin,share/man} | grep npm +. +.fi +. +.IP "" 0 +. +.P +Prior to version 0\.3, npm used shim files for executables and node +modules\. To track those down, you can do the following: +. +.IP "" 4 +. +.nf +find /usr/local/{lib/node,bin} \-exec grep \-l npm \\{\\} \\; ; +. +.fi +. +.IP "" 0 +. +.P +(This is also in the README file\.) +. +.SH "SEE ALSO" +. +.IP "\(bu" 4 +README +. +.IP "\(bu" 4 +npm help rm +. +.IP "\(bu" 4 +npm help prune +. +.IP "" 0 + diff --git a/node-v0.8.14/deps/npm/man/man1/restart.1 b/node-v0.8.14/deps/npm/man/man1/restart.1 new file mode 100644 index 0000000..1510345 --- /dev/null +++ b/node-v0.8.14/deps/npm/man/man1/restart.1 @@ -0,0 +1,42 @@ +.\" Generated with Ronnjs 0.3.8 +.\" http://github.com/kapouer/ronnjs/ +. +.TH "NPM\-RESTART" "1" "October 2012" "" "" +. +.SH "NAME" +\fBnpm-restart\fR \-\- Start a package +. +.SH "SYNOPSIS" +. +.nf +npm restart +. +.fi +. +.SH "DESCRIPTION" +This runs a package\'s "restart" script, if one was provided\. +Otherwise it runs package\'s "stop" script, if one was provided, and then +the "start" script\. +. +.P +If no version is specified, then it restarts the "active" version\. +. +.SH "SEE ALSO" +. +.IP "\(bu" 4 +npm help run\-script +. +.IP "\(bu" 4 +npm help scripts +. +.IP "\(bu" 4 +npm help test +. +.IP "\(bu" 4 +npm help start +. +.IP "\(bu" 4 +npm help stop +. +.IP "" 0 + diff --git a/node-v0.8.14/deps/npm/man/man1/rm.1 b/node-v0.8.14/deps/npm/man/man1/rm.1 new file mode 100644 index 0000000..5df9588 --- /dev/null +++ b/node-v0.8.14/deps/npm/man/man1/rm.1 @@ -0,0 +1,36 @@ +.\" Generated with Ronnjs/v0.1 +.\" http://github.com/kapouer/ronnjs/ +. +.TH "NPM\-RM" "1" "November 2011" "" "" +. +.SH "NAME" +\fBnpm-rm\fR \-\- Remove a package +. +.SH "SYNOPSIS" +. +.nf +npm rm +npm uninstall +. +.fi +. +.SH "DESCRIPTION" +This uninstalls a package, completely removing everything npm installed +on its behalf\. +. +.SH "SEE ALSO" +. +.IP "\(bu" 4 +npm help prune +. +.IP "\(bu" 4 +npm help install +. +.IP "\(bu" 4 +npm help folders +. +.IP "\(bu" 4 +npm help config +. +.IP "" 0 + diff --git a/node-v0.8.14/deps/npm/man/man1/root.1 b/node-v0.8.14/deps/npm/man/man1/root.1 new file mode 100644 index 0000000..7194c40 --- /dev/null +++ b/node-v0.8.14/deps/npm/man/man1/root.1 @@ -0,0 +1,34 @@ +.\" Generated with Ronnjs 0.3.8 +.\" http://github.com/kapouer/ronnjs/ +. +.TH "NPM\-ROOT" "1" "October 2012" "" "" +. +.SH "NAME" +\fBnpm-root\fR \-\- Display npm root +. +.SH "SYNOPSIS" +. +.nf +npm root +. +.fi +. +.SH "DESCRIPTION" +Print the effective \fBnode_modules\fR folder to standard out\. +. +.SH "SEE ALSO" +. +.IP "\(bu" 4 +npm help prefix +. +.IP "\(bu" 4 +npm help bin +. +.IP "\(bu" 4 +npm help folders +. +.IP "\(bu" 4 +npm help config +. +.IP "" 0 + diff --git a/node-v0.8.14/deps/npm/man/man1/run-script.1 b/node-v0.8.14/deps/npm/man/man1/run-script.1 new file mode 100644 index 0000000..895285c --- /dev/null +++ b/node-v0.8.14/deps/npm/man/man1/run-script.1 @@ -0,0 +1,41 @@ +.\" Generated with Ronnjs 0.3.8 +.\" http://github.com/kapouer/ronnjs/ +. +.TH "NPM\-RUN\-SCRIPT" "1" "October 2012" "" "" +. +.SH "NAME" +\fBnpm-run-script\fR \-\- Run arbitrary package scripts +. +.SH "SYNOPSIS" +. +.nf +npm run\-script + + +EOF +-----END ms-enroll.cgi----- + +Second, how to extract the request and feed the certificate back? We need to +"normalize" the base64 encoding of the PKCS#10 format which means +regenerating the lines and wrapping with BEGIN and END line. This is done by +gawk. The request is taken by ca the normal way. Then the cert needs to be +packed into a PKCS#7 structure (note: the use of a CRL is necessary for +crl2pkcs7 as of version 0.6.6. Starting with 0.8.0 it it might probably be +ommited). Finally we need to format the PKCS#7 object and generate the HTML +text. I use two templates to have a clearer script. + +1st note: postit2 is slightly modified from a program I found at ncsa's ftp +site. Grab it from http://www.easterngraphics.com/certs/IX9704/postit2.c. You +need utils.c from there too. + +2nd note: I'm note quite sure wether the gawk script really handles all +possible inputs for the request right! Today I don't use this construction +anymore myself. + +3d note: the cert must be of version 3! This could be done with the nsComment +line in ssleay.cnf... + +------BEGIN ms-gencert.cgi----- +#!/bin/sh +FILE="/tmp/"`date '+%y%m%d%H%M%S'-`$$ +rm -f "$FILE".* + +HOME=`pwd`; export HOME # as ssleay.cnf insists on having such an env var +cd /usr/local/ssl #where demoCA (as named in ssleay.conf) is located + +postit2 -s " " -i 0x0d > "$FILE".inp # process the FORM vars + +SESSION_ID=`gawk '$1 == "SessionId" { print $2; exit }' "$FILE".inp` + +gawk \ + 'BEGIN { \ + OFS = ""; \ + print "-----BEGIN CERTIFICATE REQUEST-----"; \ + req_seen=0 \ + } \ + $1 == "Request" { \ + req_seen=1; \ + if (length($2) == 72) print($2); \ + lastline=$2; \ + next; \ + } \ + { \ + if (req_seen == 1) { \ + if (length($1) >= 72) print($1); \ + else if (length(lastline) < 72) { \ + req_seen=0; \ + print (lastline,$1); \ + } \ + lastline=$1; \ + } \ + } \ + END { \ + print "-----END CERTIFICATE REQUEST-----"; \ + }' > "$FILE".pem < "$FILE".inp + +ssleay ca -batch -in "$FILE".pem -key passwd -out "$FILE".out +ssleay crl2pkcs7 -certfile "$FILE".out -out "$FILE".pkcs7 -in demoCA/crl.pem + +sed s/template_for_sessId/$SESSION_ID/ "$FILE".cert +/usr/local/bin/gawk \ + 'BEGIN { \ + OFS = ""; \ + dq = sprintf("%c",34); \ + } \ + $0 ~ "PKCS7" { next; } \ + { \ + print dq$0dq" & _"; \ + }' <"$FILE".pkcs7 >> "$FILE".cert +cat ms-enroll2b.html >>"$FILE".cert + +echo Content-type: text/html +echo Content-length: `wc -c "$FILE".cert` +echo +cat "$FILE".cert +rm -f "$FILE".* +-----END ms-gencert.cgi----- + +----BEGIN ms-enroll2a.html---- +Certificate Acceptance Test Page + + + + +
+

Your personal certificate

+


+Press the button! +

+

+


+ + + + +----END ms-enroll2b.html---- + +4.) What do do with the cert? +----------------------------- + +The cert is visible (without restarting MSIE) under the following menu: +View->Options->Security->Personal certs. You can examine it's contents at +least partially. + +To use it for client authentication you need to use SSL3.0 (fortunately +SSLeay supports it with 0.8.0). Furthermore MSIE is told to only supports a +kind of automatic selection of certs (I personally wasn't able to test it +myself). But there is a requirement that the issuer of the server cert and +the issuer of the client cert needs to be the same (according to a developer +from MS). Which means: you need may more then one cert to talk to all +servers... + +I'm sure we will get a bit more experience after ApacheSSL is available for +SSLeay 0.8.8. + + +I hope you enjoyed reading and that in future questions on this topic will +rarely appear on ssl-users@moncom.com ;-) + +Ilmenau, 9th of June 1997 +Holger Reif +-- +read you later - Holger Reif +---------------------------------------- Signaturprojekt Deutsche Einheit +TU Ilmenau - Informatik - Telematik (Verdamp lang her) +Holger.Reif@PrakInf.TU-Ilmenau.DE Alt wie ein Baum werden, um ueber +http://Remus.PrakInf.TU-Ilmenau.DE/Reif/ alle 7 Bruecken gehen zu koennen + + +==== ns-ca.doc ======================================================== + +The following documentation was supplied by Jeff Barber, who provided the +patch to the CA program to add this functionality. + +eric +-- +Jeff Barber Email: jeffb@issl.atl.hp.com + +Hewlett Packard Phone: (404) 648-9503 +Internet and System Security Lab Fax: (404) 648-9516 + + oo +---------------------cut /\ here for ns-ca.doc ------------------------------ + +This document briefly describes how to use SSLeay to implement a +certificate authority capable of dynamically serving up client +certificates for version 3.0 beta 5 (and presumably later) versions of +the Netscape Navigator. Before describing how this is done, it's +important to understand a little about how the browser implements its +client certificate support. This is documented in some detail in the +URLs based at . +Here's a brief overview: + +- The Navigator supports a new HTML tag "KEYGEN" which will cause + the browser to generate an RSA key pair when you submit a form + containing the tag. The public key, along with an optional + challenge (supposedly provided for use in certificate revocation + but I don't use it) is signed, DER-encoded, base-64 encoded + and sent to the web server as the value of the variable + whose NAME is provided in the KEYGEN tag. The private key is + stored by the browser in a local key database. + + This "Signed Public Key And Challenge" (SPKAC) arrives formatted + into 64 character lines (which are of course URL-encoded when + sent via HTTP -- i.e. spaces, newlines and most punctuatation are + encoded as "%HH" where HH is the hex equivalent of the ASCII code). + Note that the SPKAC does not contain the other usual attributes + of a certificate request, especially the subject name fields. + These must be otherwise encoded in the form for submission along + with the SPKAC. + +- Either immediately (in response to this form submission), or at + some later date (a real CA will probably verify your identity in + some way before issuing the certificate), a web server can send a + certificate based on the public key and other attributes back to + the browser by encoding it in DER (the binary form) and sending it + to the browser as MIME type: + "Content-type: application/x-x509-user-cert" + + The browser uses the public key encoded in the certificate to + associate the certificate with the appropriate private key in + its local key database. Now, the certificate is "installed". + +- When a server wants to require authentication based on client + certificates, it uses the right signals via the SSL protocol to + trigger the Navigator to ask you which certificate you want to + send. Whether the certificate is accepted is dependent on CA + certificates and so forth installed in the server and is beyond + the scope of this document. + + +Now, here's how the SSLeay package can be used to provide client +certficates: + +- You prepare a file for input to the SSLeay ca application. + The file contains a number of "name = value" pairs that identify + the subject. The names here are the same subject name component + identifiers used in the CA section of the lib/ssleay.conf file, + such as "emailAddress", "commonName" "organizationName" and so + forth. Both the long version and the short version (e.g. "Email", + "CN", "O") can be used. + + One more name is supported: this one is "SPKAC". Its value + is simply the value of the base-64 encoded SPKAC sent by the + browser (with all the newlines and other space charaters + removed -- and newline escapes are NOT supported). + + [ As of SSLeay 0.6.4, multiple lines are supported. + Put a \ at the end of each line and it will be joined with the + previous line with the '\n' removed - eay ] + + Here's a sample input file: + +C = US +SP = Georgia +O = Some Organization, Inc. +OU = Netscape Compatibility Group +CN = John X. Doe +Email = jxdoe@someorg.com +SPKAC = MIG0MGAwXDANBgkqhkiG9w0BAQEFAANLADBIAkEAwmk6FMJ4uAVIYbcvIOx5+bDGTfvL8X5gE+R67ccMk6rCSGbVQz2cetyQtnI+VIs0NwdD6wjuSuVtVFbLoHonowIDAQABFgAwDQYJKoZIhvcNAQEEBQADQQBFZDUWFl6BJdomtN1Bi53mwijy1rRgJ4YirF15yBEDM3DjAQkKXHYOIX+qpz4KXKnl6EYxTnGSFL5wWt8X2iyx + +- You execute the ca command (either from a CGI program run out of + the web server, or as a later manual task) giving it the above + file as input. For example, if the file were named /tmp/cert.req, + you'd run: + $SSLDIR/bin/ca -spkac /tmp/cert.req -out /tmp/cert + + The output is in DER format (binary) if a -out argument is + provided, as above; otherwise, it's in the PEM format (base-64 + encoded DER). Also, the "-batch" switch is implied by the + "-spkac" so you don't get asked whether to complete the signing + (probably it shouldn't work this way but I was only interested + in hacking together an online CA that could be used for issuing + test certificates). + + The "-spkac" capability doesn't support multiple files (I think). + + Any CHALLENGE provided in the SPKAC is simply ignored. + + The interactions between the identification fields you provide + and those identified in your lib/ssleay.conf are the same as if + you did an ordinary "ca -in infile -out outfile" -- that is, if + something is marked as required in the ssleay.conf file and it + isn't found in the -spkac file, the certificate won't be issued. + +- Now, you pick up the output from /tmp/cert and pass it back to + the Navigator prepending the Content-type string described earlier. + +- In order to run the ca command out of a CGI program, you must + provide a password to decrypt the CA's private key. You can + do this by using "echo MyKeyPassword | $SSLDIR/bin/ca ..." + I think there's a way to not encrypt the key file in the first + place, but I didn't see how to do that, so I made a small change + to the library that allows the password to be accepted from a pipe. + Either way is UTTERLY INSECURE and a real CA would never do that. + + [ You can use the 'ssleay rsa' command to remove the password + from the private key, or you can use the '-key' option to the + ca command to specify the decryption key on the command line + or use the -nodes option when generating the key. + ca will try to clear the command line version of the password + but for quite a few operating systems, this is not possible. + - eric ] + +So, what do you have to do to make use of this stuff to create an online +demo CA capability with SSLeay? + +1 Create an HTML form for your users. The form should contain + fields for all of the required or optional fields in ssleay.conf. + The form must contain a KEYGEN tag somewhere with at least a NAME + attribute. + +2 Create a CGI program to process the form input submitted by the + browser. The CGI program must URL-decode the variables and create + the file described above, containing subject identification info + as well as the SPKAC block. It should then run the the ca program + with the -spkac option. If it works (check the exit status), + return the new certificate with the appropriate MIME type. If not, + return the output of the ca command with MIME type "text/plain". + +3 Set up your web server to accept connections signed by your demo + CA. This probably involves obtaining the PEM-encoded CA certificate + (ordinarily in $SSLDIR/CA/cacert.pem) and installing it into a + server database. See your server manual for instructions. + + +==== obj.doc ======================================================== + +The Object library. + +As part of my Crypto library, I found I required a method of identifying various +objects. These objects normally had 3 different values associated with +them, a short text name, a long (or lower case) text name, and an +ASN.1 Object Identifier (which is a sequence of numbers). +This library contains a static list of objects and functions to lookup +according to one type and to return the other types. + +To use these routines, 'Object.h' needs to be included. + +For each supported object, #define entries are defined as follows +#define SN_Algorithm "Algorithm" +#define LN_algorithm "algorithm" +#define NID_algorithm 38 +#define OBJ_algorithm 1L,3L,14L,3L,2L + +SN_ stands for short name. +LN_ stands for either long name or lowercase name. +NID_ stands for Numeric ID. I each object has a unique NID and this + should be used internally to identify objects. +OBJ_ stands for ASN.1 Object Identifier or ASN1_OBJECT as defined in the + ASN1 routines. These values are used in ASN1 encoding. + +The following functions are to be used to return pointers into a static +definition of these types. What this means is "don't try to free() any +pointers returned from these functions. + +ASN1_OBJECT *OBJ_nid2obj( +int n); + Return the ASN1_OBJECT that corresponds to a NID of n. + +char *OBJ_nid2ln( +int n); + Return the long/lower case name of the object represented by the + NID of n. + +char *OBJ_nid2sn( +int n); + Return the short name for the object represented by the NID of n. + +ASN1_OBJECT *OBJ_dup( +ASN1_OBJECT *o); + Duplicate and return a new ASN1_OBJECT that is the same as the + passed parameter. + +int OBJ_obj2nid( +ASN1_OBJECT *o); + Given ASN1_OBJECT o, return the NID that corresponds. + +int OBJ_ln2nid( +char *s); + Given the long/lower case name 's', return the NID of the object. + +int OBJ_sn2nid( +char *s); + Given the short name 's', return the NID of the object. + +char *OBJ_bsearch( +char *key, +char *base, +int num, +int size, +int (*cmp)()); + Since I have come across a few platforms that do not have the + bsearch() function, OBJ_bsearch is my version of that function. + Feel free to use this function, but you may as well just use the + normal system bsearch(3) if it is present. This version also + has tolerance of being passed NULL pointers. + +==== keys =========================================================== + +EVP_PKEY_DSA +EVP_PKEY_DSA2 +EVP_PKEY_DSA3 +EVP_PKEY_DSA4 + +EVP_PKEY_RSA +EVP_PKEY_RSA2 + +valid DSA pkey types + NID_dsa + NID_dsaWithSHA + NID_dsaWithSHA1 + NID_dsaWithSHA1_2 + +valid RSA pkey types + NID_rsaEncryption + NID_rsa + +NID_dsaWithSHA NID_dsaWithSHA DSA SHA +NID_dsa NID_dsaWithSHA1 DSA SHA1 +NID_md2 NID_md2WithRSAEncryption RSA-pkcs1 MD2 +NID_md5 NID_md5WithRSAEncryption RSA-pkcs1 MD5 +NID_mdc2 NID_mdc2WithRSA RSA-none MDC2 +NID_ripemd160 NID_ripemd160WithRSA RSA-pkcs1 RIPEMD160 +NID_sha NID_shaWithRSAEncryption RSA-pkcs1 SHA +NID_sha1 NID_sha1WithRSAEncryption RSA-pkcs1 SHA1 + +==== rand.doc ======================================================== + +My Random number library. + +These routines can be used to generate pseudo random numbers and can be +used to 'seed' the pseudo random number generator (RNG). The RNG make no +effort to reproduce the same random number stream with each execution. +Various other routines in the SSLeay library 'seed' the RNG when suitable +'random' input data is available. Read the section at the end for details +on the design of the RNG. + +void RAND_bytes( +unsigned char *buf, +int num); + This routine puts 'num' random bytes into 'buf'. One should make + sure RAND_seed() has been called before using this routine. + +void RAND_seed( +unsigned char *buf, +int num); + This routine adds more 'seed' data the RNG state. 'num' bytes + are added to the RNG state, they are taken from 'buf'. This + routine can be called with sensitive data such as user entered + passwords. This sensitive data is in no way recoverable from + the RAND library routines or state. Try to pass as much data + from 'random' sources as possible into the RNG via this function. + Also strongly consider using the RAND_load_file() and + RAND_write_file() routines. + +void RAND_cleanup(); + When a program has finished with the RAND library, if it so + desires, it can 'zero' all RNG state. + +The following 3 routines are convenience routines that can be used to +'save' and 'restore' data from/to the RNG and it's state. +Since the more 'random' data that is feed as seed data the better, why not +keep it around between executions of the program? Of course the +application should pass more 'random' data in via RAND_seed() and +make sure no-one can read the 'random' data file. + +char *RAND_file_name( +char *buf, +int size); + This routine returns a 'default' name for the location of a 'rand' + file. The 'rand' file should keep a sequence of random bytes used + to initialise the RNG. The filename is put in 'buf'. Buf is 'size' + bytes long. Buf is returned if things go well, if they do not, + NULL is returned. The 'rand' file name is generated in the + following way. First, if there is a 'RANDFILE' environment + variable, it is returned. Second, if there is a 'HOME' environment + variable, $HOME/.rand is returned. Third, NULL is returned. NULL + is also returned if a buf would overflow. + +int RAND_load_file( +char *file, +long number); + This function 'adds' the 'file' into the RNG state. It does this by + doing a RAND_seed() on the value returned from a stat() system call + on the file and if 'number' is non-zero, upto 'number' bytes read + from the file. The number of bytes passed to RAND_seed() is returned. + +int RAND_write_file( +char *file), + RAND_write_file() writes N random bytes to the file 'file', where + N is the size of the internal RND state (currently 1k). + This is a suitable method of saving RNG state for reloading via + RAND_load_file(). + +What follows is a description of this RNG and a description of the rational +behind it's design. + +It should be noted that this RNG is intended to be used to generate +'random' keys for various ciphers including generation of DH and RSA keys. + +It should also be noted that I have just created a system that I am happy with. +It may be overkill but that does not worry me. I have not spent that much +time on this algorithm so if there are glaring errors, please let me know. +Speed has not been a consideration in the design of these routines. + +First up I will state the things I believe I need for a good RNG. +1) A good hashing algorithm to mix things up and to convert the RNG 'state' + to random numbers. +2) An initial source of random 'state'. +3) The state should be very large. If the RNG is being used to generate + 4096 bit RSA keys, 2 2048 bit random strings are required (at a minimum). + If your RNG state only has 128 bits, you are obviously limiting the + search space to 128 bits, not 2048. I'm probably getting a little + carried away on this last point but it does indicate that it may not be + a bad idea to keep quite a lot of RNG state. It should be easier to + break a cipher than guess the RNG seed data. +4) Any RNG seed data should influence all subsequent random numbers + generated. This implies that any random seed data entered will have + an influence on all subsequent random numbers generated. +5) When using data to seed the RNG state, the data used should not be + extractable from the RNG state. I believe this should be a + requirement because one possible source of 'secret' semi random + data would be a private key or a password. This data must + not be disclosed by either subsequent random numbers or a + 'core' dump left by a program crash. +6) Given the same initial 'state', 2 systems should deviate in their RNG state + (and hence the random numbers generated) over time if at all possible. +7) Given the random number output stream, it should not be possible to determine + the RNG state or the next random number. + + +The algorithm is as follows. + +There is global state made up of a 1023 byte buffer (the 'state'), a +working message digest ('md') and a counter ('count'). + +Whenever seed data is added, it is inserted into the 'state' as +follows. + The input is chopped up into units of 16 bytes (or less for + the last block). Each of these blocks is run through the MD5 + message digest. The data passed to the MD5 digest is the + current 'md', the same number of bytes from the 'state' + (the location determined by in incremented looping index) as + the current 'block' and the new key data 'block'. The result + of this is kept in 'md' and also xored into the 'state' at the + same locations that were used as input into the MD5. + I believe this system addresses points 1 (MD5), 3 (the 'state'), + 4 (via the 'md'), 5 (by the use of MD5 and xor). + +When bytes are extracted from the RNG, the following process is used. +For each group of 8 bytes (or less), we do the following, + Input into MD5, the top 8 bytes from 'md', the byte that are + to be overwritten by the random bytes and bytes from the + 'state' (incrementing looping index). From this digest output + (which is kept in 'md'), the top (upto) 8 bytes are + returned to the caller and the bottom (upto) 8 bytes are xored + into the 'state'. + Finally, after we have finished 'generation' random bytes for the + called, 'count' (which is incremented) and 'md' are fed into MD5 and + the results are kept in 'md'. + I believe the above addressed points 1 (use of MD5), 6 (by + hashing into the 'state' the 'old' data from the caller that + is about to be overwritten) and 7 (by not using the 8 bytes + given to the caller to update the 'state', but they are used + to update 'md'). + +So of the points raised, only 2 is not addressed, but sources of +random data will always be a problem. + + +==== rc2.doc ======================================================== + +The RC2 library. + +RC2 is a block cipher that operates on 64bit (8 byte) quantities. It +uses variable size key, but 128bit (16 byte) key would normally be considered +good. It can be used in all the modes that DES can be used. This +library implements the ecb, cbc, cfb64, ofb64 modes. + +I have implemented this library from an article posted to sci.crypt on +11-Feb-1996. I personally don't know how far to trust the RC2 cipher. +While it is capable of having a key of any size, not much reseach has +publically been done on it at this point in time (Apr-1996) +since the cipher has only been public for a few months :-) +It is of a similar speed to DES and IDEA, so unless it is required for +meeting some standard (SSLv2, perhaps S/MIME), it would probably be advisable +to stick to IDEA, or for the paranoid, Tripple DES. + +Mind you, having said all that, I should mention that I just read alot and +implement ciphers, I'm a 'babe in the woods' when it comes to evaluating +ciphers :-). + +For all calls that have an 'input' and 'output' variables, they can be the +same. + +This library requires the inclusion of 'rc2.h'. + +All of the encryption functions take what is called an RC2_KEY as an +argument. An RC2_KEY is an expanded form of the RC2 key. +For all modes of the RC2 algorithm, the RC2_KEY used for +decryption is the same one that was used for encryption. + +The define RC2_ENCRYPT is passed to specify encryption for the functions +that require an encryption/decryption flag. RC2_DECRYPT is passed to +specify decryption. + +Please note that any of the encryption modes specified in my DES library +could be used with RC2. I have only implemented ecb, cbc, cfb64 and +ofb64 for the following reasons. +- ecb is the basic RC2 encryption. +- cbc is the normal 'chaining' form for block ciphers. +- cfb64 can be used to encrypt single characters, therefore input and output + do not need to be a multiple of 8. +- ofb64 is similar to cfb64 but is more like a stream cipher, not as + secure (not cipher feedback) but it does not have an encrypt/decrypt mode. +- If you want triple RC2, thats 384 bits of key and you must be totally + obsessed with security. Still, if you want it, it is simple enough to + copy the function from the DES library and change the des_encrypt to + RC2_encrypt; an exercise left for the paranoid reader :-). + +The functions are as follows: + +void RC2_set_key( +RC2_KEY *ks; +int len; +unsigned char *key; +int bits; + RC2_set_key converts an 'len' byte key into a RC2_KEY. + A 'ks' is an expanded form of the 'key' which is used to + perform actual encryption. It can be regenerated from the RC2 key + so it only needs to be kept when encryption or decryption is about + to occur. Don't save or pass around RC2_KEY's since they + are CPU architecture dependent, 'key's are not. RC2 is an + interesting cipher in that it can be used with a variable length + key. 'len' is the length of 'key' to be used as the key. + A 'len' of 16 is recomended. The 'bits' argument is an + interesting addition which I only found out about in Aug 96. + BSAFE uses this parameter to 'limit' the number of bits used + for the key. To use the 'key' unmodified, set bits to 1024. + This is what old versions of my RC2 library did (SSLeay 0.6.3). + RSAs BSAFE library sets this parameter to be 128 if 128 bit + keys are being used. So to be compatable with BSAFE, set it + to 128, if you don't want to reduce RC2's key length, leave it + at 1024. + +void RC2_encrypt( +unsigned long *data, +RC2_KEY *key, +int encrypt); + This is the RC2 encryption function that gets called by just about + every other RC2 routine in the library. You should not use this + function except to implement 'modes' of RC2. I say this because the + functions that call this routine do the conversion from 'char *' to + long, and this needs to be done to make sure 'non-aligned' memory + access do not occur. + Data is a pointer to 2 unsigned long's and key is the + RC2_KEY to use. Encryption or decryption is indicated by 'encrypt'. + which can have the values RC2_ENCRYPT or RC2_DECRYPT. + +void RC2_ecb_encrypt( +unsigned char *in, +unsigned char *out, +RC2_KEY *key, +int encrypt); + This is the basic Electronic Code Book form of RC2 (in DES this + mode is called Electronic Code Book so I'm going to use the term + for rc2 as well. + Input is encrypted into output using the key represented by + key. Depending on the encrypt, encryption or + decryption occurs. Input is 8 bytes long and output is 8 bytes. + +void RC2_cbc_encrypt( +unsigned char *in, +unsigned char *out, +long length, +RC2_KEY *ks, +unsigned char *ivec, +int encrypt); + This routine implements RC2 in Cipher Block Chaining mode. + Input, which should be a multiple of 8 bytes is encrypted + (or decrypted) to output which will also be a multiple of 8 bytes. + The number of bytes is in length (and from what I've said above, + should be a multiple of 8). If length is not a multiple of 8, bad + things will probably happen. ivec is the initialisation vector. + This function updates iv after each call so that it can be passed to + the next call to RC2_cbc_encrypt(). + +void RC2_cfb64_encrypt( +unsigned char *in, +unsigned char *out, +long length, +RC2_KEY *schedule, +unsigned char *ivec, +int *num, +int encrypt); + This is one of the more useful functions in this RC2 library, it + implements CFB mode of RC2 with 64bit feedback. + This allows you to encrypt an arbitrary number of bytes, + you do not require 8 byte padding. Each call to this + routine will encrypt the input bytes to output and then update ivec + and num. Num contains 'how far' we are though ivec. + 'Encrypt' is used to indicate encryption or decryption. + CFB64 mode operates by using the cipher to generate a stream + of bytes which is used to encrypt the plain text. + The cipher text is then encrypted to generate the next 64 bits to + be xored (incrementally) with the next 64 bits of plain + text. As can be seen from this, to encrypt or decrypt, + the same 'cipher stream' needs to be generated but the way the next + block of data is gathered for encryption is different for + encryption and decryption. + +void RC2_ofb64_encrypt( +unsigned char *in, +unsigned char *out, +long length, +RC2_KEY *schedule, +unsigned char *ivec, +int *num); + This functions implements OFB mode of RC2 with 64bit feedback. + This allows you to encrypt an arbitrary number of bytes, + you do not require 8 byte padding. Each call to this + routine will encrypt the input bytes to output and then update ivec + and num. Num contains 'how far' we are though ivec. + This is in effect a stream cipher, there is no encryption or + decryption mode. + +For reading passwords, I suggest using des_read_pw_string() from my DES library. +To generate a password from a text string, I suggest using MD5 (or MD2) to +produce a 16 byte message digest that can then be passed directly to +RC2_set_key(). + +===== +For more information about the specific RC2 modes in this library +(ecb, cbc, cfb and ofb), read the section entitled 'Modes of DES' from the +documentation on my DES library. What is said about DES is directly +applicable for RC2. + + +==== rc4.doc ======================================================== + +The RC4 library. +RC4 is a stream cipher that operates on a byte stream. It can be used with +any length key but I would recommend normally using 16 bytes. + +This library requires the inclusion of 'rc4.h'. + +The RC4 encryption function takes what is called an RC4_KEY as an argument. +The RC4_KEY is generated by the RC4_set_key function from the key bytes. + +RC4, being a stream cipher, does not have an encryption or decryption mode. +It produces a stream of bytes that the input stream is xor'ed against and +so decryption is just a case of 'encrypting' again with the same key. + +I have only put in one 'mode' for RC4 which is the normal one. This means +there is no initialisation vector and there is no feedback of the cipher +text into the cipher. This implies that you should not ever use the +same key twice if you can help it. If you do, you leave yourself open to +known plain text attacks; if you know the plain text and +corresponding cipher text in one message, all messages that used the same +key can have the cipher text decoded for the corresponding positions in the +cipher stream. + +The main positive feature of RC4 is that it is a very fast cipher; about 4 +times faster that DES. This makes it ideally suited to protocols where the +key is randomly chosen, like SSL. + +The functions are as follows: + +void RC4_set_key( +RC4_KEY *key; +int len; +unsigned char *data); + This function initialises the RC4_KEY structure with the key passed + in 'data', which is 'len' bytes long. The key data can be any + length but 16 bytes seems to be a good number. + +void RC4( +RC4_KEY *key; +unsigned long len; +unsigned char *in; +unsigned char *out); + Do the actual RC4 encryption/decryption. Using the 'key', 'len' + bytes are transformed from 'in' to 'out'. As mentioned above, + decryption is the operation as encryption. + +==== ref.doc ======================================================== + +I have lots more references etc, and will update this list in the future, +30 Aug 1996 - eay + + +SSL The SSL Protocol - from Netscapes. + +RC4 Newsgroups: sci.crypt + From: sterndark@netcom.com (David Sterndark) + Subject: RC4 Algorithm revealed. + Message-ID: + +RC2 Newsgroups: sci.crypt + From: pgut01@cs.auckland.ac.nz (Peter Gutmann) + Subject: Specification for Ron Rivests Cipher No.2 + Message-ID: <4fk39f$f70@net.auckland.ac.nz> + +MD2 RFC1319 The MD2 Message-Digest Algorithm +MD5 RFC1321 The MD5 Message-Digest Algorithm + +X509 Certificates + RFC1421 Privacy Enhancement for Internet Electronic Mail: Part I + RFC1422 Privacy Enhancement for Internet Electronic Mail: Part II + RFC1423 Privacy Enhancement for Internet Electronic Mail: Part III + RFC1424 Privacy Enhancement for Internet Electronic Mail: Part IV + +RSA and various standard encoding + PKCS#1 RSA Encryption Standard + PKCS#5 Password-Based Encryption Standard + PKCS#7 Cryptographic Message Syntax Standard + A Layman's Guide to a Subset of ASN.1, BER, and DER + An Overview of the PKCS Standards + Some Examples of the PKCS Standards + +IDEA Chapter 3 The Block Cipher IDEA + +RSA, prime number generation and bignum algorithms + Introduction To Algorithms, + Thomas Cormen, Charles Leiserson, Ronald Rivest, + Section 29 Arithmetic Circuits + Section 33 Number-Theoretic Algorithms + +Fast Private Key algorithm + Fast Decipherment Algorithm for RSA Public-Key Cryptosystem + J.-J. Quisquater and C. Couvreur, Electronics Letters, + 14th October 1982, Vol. 18 No. 21 + +Prime number generation and bignum algorithms. + PGP-2.3a + +==== rsa.doc ======================================================== + +The RSA encryption and utility routines. + +The RSA routines are built on top of a big number library (the BN library). +There are support routines in the X509 library for loading and manipulating +the various objects in the RSA library. When errors are returned, read +about the ERR library for how to access the error codes. + +All RSA encryption is done according to the PKCS-1 standard which is +compatible with PEM and RSAref. This means that any values being encrypted +must be less than the size of the modulus in bytes, minus 10, bytes long. + +This library uses RAND_bytes()() for it's random data, make sure to feed +RAND_seed() with lots of interesting and varied data before using these +routines. + +The RSA library has one specific data type, the RSA structure. +It is composed of 8 BIGNUM variables (see the BN library for details) and +can hold either a private RSA key or a public RSA key. +Some RSA libraries have different structures for public and private keys, I +don't. For my libraries, a public key is determined by the fact that the +RSA->d value is NULL. These routines will operate on any size RSA keys. +While I'm sure 4096 bit keys are very very secure, they take a lot longer +to process that 1024 bit keys :-). + +The function in the RSA library are as follows. + +RSA *RSA_new(); + This function creates a new RSA object. The sub-fields of the RSA + type are also malloced so you should always use this routine to + create RSA variables. + +void RSA_free( +RSA *rsa); + This function 'frees' an RSA structure. This routine should always + be used to free the RSA structure since it will also 'free' any + sub-fields of the RSA type that need freeing. + +int RSA_size( +RSA *rsa); + This function returns the size of the RSA modulus in bytes. Why do + I need this you may ask, well the reason is that when you encrypt + with RSA, the output string will be the size of the RSA modulus. + So the output for the RSA_encrypt and the input for the RSA_decrypt + routines need to be RSA_size() bytes long, because this is how many + bytes are expected. + +For the following 4 RSA encryption routines, it should be noted that +RSA_private_decrypt() should be used on the output from +RSA_public_encrypt() and RSA_public_decrypt() should be used on +the output from RSA_private_encrypt(). + +int RSA_public_encrypt( +int from_len; +unsigned char *from +unsigned char *to +RSA *rsa); + This function implements RSA public encryption, the rsa variable + should be a public key (but can be a private key). 'from_len' + bytes taken from 'from' and encrypted and put into 'to'. 'to' needs + to be at least RSA_size(rsa) bytes long. The number of bytes + written into 'to' is returned. -1 is returned on an error. The + operation performed is + to = from^rsa->e mod rsa->n. + +int RSA_private_encrypt( +int from_len; +unsigned char *from +unsigned char *to +RSA *rsa); + This function implements RSA private encryption, the rsa variable + should be a private key. 'from_len' bytes taken from + 'from' and encrypted and put into 'to'. 'to' needs + to be at least RSA_size(rsa) bytes long. The number of bytes + written into 'to' is returned. -1 is returned on an error. The + operation performed is + to = from^rsa->d mod rsa->n. + +int RSA_public_decrypt( +int from_len; +unsigned char *from +unsigned char *to +RSA *rsa); + This function implements RSA public decryption, the rsa variable + should be a public key (but can be a private key). 'from_len' + bytes are taken from 'from' and decrypted. The decrypted data is + put into 'to'. The number of bytes encrypted is returned. -1 is + returned to indicate an error. The operation performed is + to = from^rsa->e mod rsa->n. + +int RSA_private_decrypt( +int from_len; +unsigned char *from +unsigned char *to +RSA *rsa); + This function implements RSA private decryption, the rsa variable + should be a private key. 'from_len' bytes are taken + from 'from' and decrypted. The decrypted data is + put into 'to'. The number of bytes encrypted is returned. -1 is + returned to indicate an error. The operation performed is + to = from^rsa->d mod rsa->n. + +int RSA_mod_exp( +BIGNUM *n; +BIGNUM *p; +RSA *rsa); + Normally you will never use this routine. + This is really an internal function which is called by + RSA_private_encrypt() and RSA_private_decrypt(). It performs + n=n^p mod rsa->n except that it uses the 5 extra variables in the + RSA structure to make this more efficient. + +RSA *RSA_generate_key( +int bits; +unsigned long e; +void (*callback)(); +char *cb_arg; + This routine is used to generate RSA private keys. It takes + quite a period of time to run and should only be used to + generate initial private keys that should then be stored + for later use. The passed callback function + will be called periodically so that feedback can be given + as to how this function is progressing. + 'bits' is the length desired for the modulus, so it would be 1024 + to generate a 1024 bit private key. + 'e' is the value to use for the public exponent 'e'. Traditionally + it is set to either 3 or 0x10001. + The callback function (if not NULL) is called in the following + situations. + when we have generated a suspected prime number to test, + callback(0,num1++,cb_arg). When it passes a prime number test, + callback(1,num2++,cb_arg). When it is rejected as one of + the 2 primes required due to gcd(prime,e value) != 0, + callback(2,num3++,cb_arg). When finally accepted as one + of the 2 primes, callback(3,num4++,cb_arg). + + +==== rsaref.doc ======================================================== + +This package can be compiled to use the RSAref library. +This library is not allowed outside of the USA but inside the USA it is +claimed by RSA to be the only RSA public key library that can be used +besides BSAFE.. + +There are 2 files, rsaref/rsaref.c and rsaref/rsaref.h that contain the glue +code to use RSAref. These files were written by looking at the PGP +source code and seeing which routines it used to access RSAref. +I have also been sent by some-one a copy of the RSAref header file that +contains the library error codes. + +[ Jun 1996 update - I have recently gotten hold of RSAref 2.0 from + South Africa and have been doing some performace tests. ] + +They have now been tested against the recently announced RSAEURO +library. + +There are 2 ways to use SSLeay and RSAref. First, to build so that +the programs must be linked with RSAref, add '-DRSAref' to CFLAG in the top +level makefile and -lrsaref (or where ever you are keeping RSAref) to +EX_LIBS. + +To build a makefile via util/mk1mf.pl to do this, use the 'rsaref' option. + +The second method is to build as per normal and link applications with +the RSAglue library. The correct library order would be +cc -o cmd cmd.o -lssl -lRSAglue -lcrypto -lrsaref -ldes +The RSAglue library is built in the rsa directory and is NOT +automatically installed. + +Be warned that the RSAEURO library, that is claimed to be compatible +with RSAref contains a different value for the maximum number of bits +supported. This changes structure sizes and so if you are using +RSAEURO, change the value of RSAref_MAX_BITS in rsa/rsaref.h + + +==== s_mult.doc ======================================================== + +s_mult is a test program I hacked up on a Sunday for testing non-blocking +IO. It has a select loop at it's centre that handles multiple readers +and writers. + +Try the following command +ssleay s_mult -echo -nbio -ssl -v +echo - sends any sent text back to the sender +nbio - turns on non-blocking IO +ssl - accept SSL connections, default is normal text +v - print lots + type Q to quit + +In another window, run the following +ssleay s_client -pause new_session_cb is a function pointer to a function of type +int new_session_callback(SSL *ssl,SSL_SESSION *new); +This function, if set in the SSL_CTX structure is called whenever a new +SSL_SESSION is added to the cache. If the callback returns non-zero, it +means that the application will have to do a SSL_SESSION_free() +on the structure (this is +to do with the cache keeping the reference counts correct, without the +application needing to know about it. +The 'active' parameter is the current SSL session for which this connection +was created. + +void SSL_CTX_sess_set_new_cb(SSL_CTX *ctx,int (*cb)()); +to set the callback, +int (*cb)() SSL_CTX_sess_get_new_cb(SSL_CTX *ctx) +to get the callback. + +If the 'get session' callback is set, when a session id is looked up and +it is not in the session-id cache, this callback is called. The callback is +of the form +SSL_SESSION *get_session_callback(unsigned char *sess_id,int sess_id_len, + int *copy); + +The get_session_callback is intended to return null if no session id is found. +The reference count on the SSL_SESSION in incremented by the SSL library, +if copy is 1. Otherwise, the reference count is not modified. + +void SSL_CTX_sess_set_get_cb(ctx,cb) sets the callback and +int (*cb)()SSL_CTX_sess_get_get_cb(ctx) returns the callback. + +These callbacks are basically intended to be used by processes to +send their session-id's to other processes. I currently have not implemented +non-blocking semantics for these callbacks, it is upto the application +to make the callbacks efficient if they require blocking (perhaps +by 'saving' them and then 'posting them' when control returns from +the SSL_accept(). + +LHASH *SSL_CTX_sessions(SSL_CTX *ctx) +This returns the session cache. The lhash strucutre can be accessed for +statistics about the cache. + +void lh_stats(LHASH *lh, FILE *out); +void lh_node_stats(LHASH *lh, FILE *out); +void lh_node_usage_stats(LHASH *lh, FILE *out); + +can be used to print details about it's activity and current state. +You can also delve directly into the lhash structure for 14 different +counters that are kept against the structure. When I wrote the lhash library, +I was interested in gathering statistics :-). +Have a read of doc/lhash.doc in the SSLeay distribution area for more details +on the lhash library. + +Now as mentioned ealier, when a SSL is created, it needs a SSL_CTX. +SSL * SSL_new(SSL_CTX *); + +This stores a session. A session is secret information shared between 2 +SSL contexts. It will only be created if both ends of the connection have +authenticated their peer to their satisfaction. It basically contains +the information required to use a particular secret key cipher. + +To retrieve the SSL_CTX being used by a SSL, +SSL_CTX *SSL_get_SSL_CTX(SSL *s); + +Now when a SSL session is established between to programs, the 'session' +information that is cached in the SSL_CTX can me manipulated by the +following functions. +int SSL_set_session(SSL *s, SSL_SESSION *session); +This will set the SSL_SESSION to use for the next SSL_connect(). If you use +this function on an already 'open' established SSL connection, 'bad things +will happen'. This function is meaning-less when used on a ssl strucutre +that is just about to be used in a SSL_accept() call since the +SSL_accept() will either create a new session or retrieve one from the +cache. + +SSL_SESSION *SSL_get_session(SSL *s); +This will return the SSL_SESSION for the current SSL, NULL if there is +no session associated with the SSL structure. + +The SSL sessions are kept in the SSL_CTX in a hash table, to remove a +session +void SSL_CTX_remove_session(SSL_CTX *,SSL_SESSION *c); +and to add one +int SSL_CTX_add_session(SSL_CTX *s, SSL_SESSION *c); +SSL_CTX_add_session() returns 1 if the session was already in the cache (so it +was not added). +Whenever a new session is created via SSL_connect()/SSL_accept(), +they are automatically added to the cache, depending on the session_cache_mode +settings. SSL_set_session() +does not add it to the cache. Just call SSL_CTX_add_session() if you do want the +session added. For a 'client' this would not normally be the case. +SSL_CTX_add_session() is not normally ever used, except for doing 'evil' things +which the next 2 funtions help you do. + +int i2d_SSL_SESSION(SSL_SESSION *in,unsigned char **pp); +SSL_SESSION *d2i_SSL_SESSION(SSL_SESSION **a,unsigned char **pp,long length); +These 2 functions are in the standard ASN1 library form and can be used to +load and save to a byte format, the SSL_SESSION structure. +With these functions, you can save and read these structures to a files or +arbitary byte string. +The PEM_write_SSL_SESSION(fp,x) and PEM_read_SSL_SESSION(fp,x,cb) will +write to a file pointer in base64 encoding. + +What you can do with this, is pass session information between separate +processes. Please note, that you will probably also need to modify the +timeout information on the SSL_SESSIONs. + +long SSL_get_time(SSL_SESSION *s) +will return the 'time' that the session +was loaded. The timeout is relative to this time. This information is +saved when the SSL_SESSION is converted to binarary but it is stored +in as a unix long, which is rather OS dependant, but easy to convert back. + +long SSL_set_time(SSL_SESSION *s,long t) will set the above mentioned time. +The time value is just the value returned from time(3), and should really +be defined by be to be time_t. + +long SSL_get_timeout(SSL_SESSION *s); +long SSL_set_timeout(SSL_SESSION *s,long t); +These 2 retrieve and set the timeout which is just a number of secconds +from the 'SSL_get_time()' value. When this time period has elapesed, +the session will no longer be in the cache (well it will actually be removed +the next time it is attempted to be retrieved, so you could 'bump' +the timeout so it remains valid). +The 'time' and 'timeout' are set on a session when it is created, not reset +each time it is reused. If you did wish to 'bump it', just after establishing +a connection, do a +SSL_set_time(ssl,time(NULL)); + +You can also use +SSL_CTX_set_timeout(SSL_CTX *ctx,unsigned long t) and +SSL_CTX_get_timeout(SSL_CTX *ctx) to manipulate the default timeouts for +all SSL connections created against a SSL_CTX. If you set a timeout in +an SSL_CTX, all new SSL's created will inherit the timeout. It can be over +written by the SSL_set_timeout(SSL *s,unsigned long t) function call. +If you 'set' the timeout back to 0, the system default will be used. + +SSL_SESSION *SSL_SESSION_new(); +void SSL_SESSION_free(SSL_SESSION *ses); +These 2 functions are used to create and dispose of SSL_SESSION functions. +You should not ever normally need to use them unless you are using +i2d_SSL_SESSION() and/or d2i_SSL_SESSION(). If you 'load' a SSL_SESSION +via d2i_SSL_SESSION(), you will need to SSL_SESSION_free() it. +Both SSL_set_session() and SSL_CTX_add_session() will 'take copies' of the +structure (via reference counts) when it is passed to them. + +SSL_CTX_flush_sessions(ctx,time); +The first function will clear all sessions from the cache, which have expired +relative to 'time' (which could just be time(NULL)). + +SSL_CTX_flush_sessions(ctx,0); +This is a special case that clears everything. + +As a final comment, a 'session' is not enough to establish a new +connection. If a session has timed out, a certificate and private key +need to have been associated with the SSL structure. +SSL_copy_session_id(SSL *to,SSL *from); will copy not only the session +strucutre but also the private key and certificate associated with +'from'. + +EXAMPLES. + +So lets play at being a weird SSL server. + +/* setup a context */ +ctx=SSL_CTX_new(); + +/* Lets load some session from binary into the cache, why one would do + * this is not toally clear, but passing between programs does make sense + * Perhaps you are using 4096 bit keys and are happy to keep them + * valid for a week, to avoid the RSA overhead of 15 seconds, I'm not toally + * sure, perhaps this is a process called from an SSL inetd and this is being + * passed to the application. */ +session=d2i_SSL_SESSION(....) +SSL_CTX_add_session(ctx,session); + +/* Lets even add a session from a file */ +session=PEM_read_SSL_SESSION(....) +SSL_CTX_add_session(ctx,session); + +/* create a new SSL structure */ +ssl=SSL_new(ctx); + +/* At this point we want to be able to 'create' new session if + * required, so we need a certificate and RSAkey. */ +SSL_use_RSAPrivateKey_file(ssl,...) +SSL_use_certificate_file(ssl,...) + +/* Now since we are a server, it make little sence to load a session against + * the ssl strucutre since a SSL_accept() will either create a new session or + * grab an existing one from the cache. */ + +/* grab a socket descriptor */ +fd=accept(...); + +/* associated it with the ssl strucutre */ +SSL_set_fd(ssl,fd); + +SSL_accept(ssl); /* 'do' SSL using out cert and RSA key */ + +/* Lets print out the session details or lets save it to a file, + * perhaps with a secret key cipher, so that we can pass it to the FBI + * when they want to decode the session :-). While we have RSA + * this does not matter much but when I do SSLv3, this will allow a mechanism + * for the server/client to record the information needed to decode + * the traffic that went over the wire, even when using Diffie-Hellman */ +PEM_write_SSL_SESSION(SSL_get_session(ssl),stdout,....) + +Lets 'connect' back to the caller using the same session id. + +ssl2=SSL_new(ctx); +fd2=connect(them); +SSL_set_fd(ssl2,fd2); +SSL_set_session(ssl2,SSL_get_session(ssl)); +SSL_connect(ssl2); + +/* what the hell, lets accept no more connections using this session */ +SSL_CTX_remove_session(SSL_get_SSL_CTX(ssl),SSL_get_session(ssl)); + +/* we could have just as easily used ssl2 since they both are using the + * same session. + * You will note that both ssl and ssl2 are still using the session, and + * the SSL_SESSION structure will be free()ed when both ssl and ssl2 + * finish using the session. Also note that you could continue to initiate + * connections using this session by doing SSL_get_session(ssl) to get the + * existing session, but SSL_accept() will not be able to find it to + * use for incoming connections. + * Of corse, the session will timeout at the far end and it will no + * longer be accepted after a while. The time and timeout are ignored except + * by SSL_accept(). */ + +/* Since we have had our server running for 10 weeks, and memory is getting + * short, perhaps we should clear the session cache to remove those + * 100000 session entries that have expired. Some may consider this + * a memory leak :-) */ + +SSL_CTX_flush_sessions(ctx,time(NULL)); + +/* Ok, after a bit more time we wish to flush all sessions from the cache + * so that all new connections will be authenticated and incure the + * public key operation overhead */ + +SSL_CTX_flush_sessions(ctx,0); + +/* As a final note, to copy everything to do with a SSL, use */ +SSL_copy_session_id(SSL *to,SSL *from); +/* as this also copies the certificate and RSA key so new session can + * be established using the same details */ + + +==== sha.doc ======================================================== + +The SHA (Secure Hash Algorithm) library. +SHA is a message digest algorithm that can be used to condense an arbitrary +length message down to a 20 byte hash. The functions all need to be passed +a SHA_CTX which is used to hold the SHA context during multiple SHA_Update() +function calls. The normal method of use for this library is as follows +This library contains both SHA and SHA-1 digest algorithms. SHA-1 is +an update to SHA (which should really be called SHA-0 now) which +tweaks the algorithm slightly. The SHA-1 algorithm is used by simply +using SHA1_Init(), SHA1_Update(), SHA1_Final() and SHA1() instead of the +SHA*() calls + +SHA_Init(...); +SHA_Update(...); +... +SHA_Update(...); +SHA_Final(...); + +This library requires the inclusion of 'sha.h'. + +The functions are as follows: + +void SHA_Init( +SHA_CTX *c); + This function needs to be called to initiate a SHA_CTX structure for + use. + +void SHA_Update( +SHA_CTX *c; +unsigned char *data; +unsigned long len); + This updates the message digest context being generated with 'len' + bytes from the 'data' pointer. The number of bytes can be any + length. + +void SHA_Final( +unsigned char *md; +SHA_CTX *c; + This function is called when a message digest of the data digested + with SHA_Update() is wanted. The message digest is put in the 'md' + array and is SHA_DIGEST_LENGTH (20) bytes long. + +unsigned char *SHA( +unsigned char *d; +unsigned long n; +unsigned char *md; + This function performs a SHA_Init(), followed by a SHA_Update() + followed by a SHA_Final() (using a local SHA_CTX). + The resulting digest is put into 'md' if it is not NULL. + Regardless of the value of 'md', the message + digest is returned from the function. If 'md' was NULL, the message + digest returned is being stored in a static structure. + + +==== speed.doc ======================================================== + +To get an idea of the performance of this library, use +ssleay speed + +perl util/sp-diff.pl file1 file2 + +will print out the relative differences between the 2 files which are +expected to be the output from the speed program. + +The performace of the library is very dependant on the Compiler +quality and various flags used to build. + +--- + +These are some numbers I did comparing RSAref and SSLeay on a Pentium 100. +[ These numbers are all out of date, as of SSL - 0.6.1 the RSA +operations are about 2 times faster, so check the version number ] + +RSA performance. + +SSLeay 0.6.0 +Pentium 100, 32meg, Windows NT Workstation 3.51 +linux - gcc v 2.7.0 -O3 -fomit-frame-pointer -m486 +and +Windows NT - Windows NT 3.51 - Visual C++ 4.1 - 586 code + 32bit assember +Windows 3.1 - Windows NT 3.51 - Visual C++ 1.52c - 286 code + 32bit assember +NT Dos Shell- Windows NT 3.51 - Visual C++ 1.52c - 286 code + 16bit assember + +Times are how long it takes to do an RSA private key operation. + + 512bits 1024bits +------------------------------- +SSLeay NT dll 0.042s 0.202s see above +SSLeay linux 0.046s 0.218s Assember inner loops (normal build) +SSLeay linux 0.067s 0.380s Pure C code with BN_LLONG defined +SSLeay W3.1 dll 0.108s 0.478s see above +SSLeay linux 0.109s 0.713s C without BN_LLONG. +RSAref2.0 linux 0.149s 0.936s +SSLeay MS-DOS 0.197s 1.049s see above + +486DX66, 32meg, Windows NT Server 3.51 + 512bits 1024bits +------------------------------- +SSLeay NT dll 0.084s 0.495s <- SSLeay 0.6.3 +SSLeay NT dll 0.154s 0.882s +SSLeay W3.1 dll 0.335s 1.538s +SSLeay MS-DOS 0.490s 2.790s + +What I find cute is that I'm still faster than RSAref when using standard C, +without using the 'long long' data type :-), %35 faster for 512bit and we +scale up to 3.2 times faster for the 'default linux' build. I should mention +that people should 'try' to use either x86-lnx.s (elf), x86-lnxa.s or +x86-sol.s for any x86 based unix they are building on. The only problems +with be with syntax but the performance gain is quite large, especially for +servers. The code is very simple, you just need to modify the 'header'. + +The message is, if you are stuck using RSAref, the RSA performance will be +bad. Considering the code was compiled for a pentium, the 486DX66 number +would indicate 'Use RSAref and turn you Pentium 100 into a 486DX66' :-). +[ As of verson 0.6.1, it would be correct to say 'turn you pentium 100 + into a 486DX33' :-) ] + +I won't tell people if the DLL's are using RSAref or my stuff if no-one +asks :-). + +eric + +PS while I know I could speed things up further, I will probably not do + so due to the effort involved. I did do some timings on the + SSLeay bignum format -> RSAref number format conversion that occurs + each time RSAref is used by SSLeay, and the numbers are trivial. + 0.00012s a call for 512bit vs 0.149s for the time spent in the function. + 0.00018s for 1024bit vs 0.938s. Insignificant. + So the 'way to go', to support faster RSA libraries, if people are keen, + is to write 'glue' code in a similar way that I do for RSAref and send it + to me :-). + My base library still has the advantage of being able to operate on + any size numbers, and is not that far from the performance from the + leaders in the field. (-%30?) + [ Well as of 0.6.1 I am now the leader in the filed on x86 (we at + least very close :-) ] + + I suppose I should also mention some other numbers RSAref numbers, again + on my Pentium. + DES CBC EDE-DES MD5 + RSAref linux 830k/s 302k/s 4390k/s + SSLeay linux 855k/s 319k/s 10025k/s + SSLeay NT 1158k/s 410k/s 10470k/s + SSLeay w31 378k/s 143k/s 2383k/s (fully 16bit) + + Got to admit that Visual C++ 4.[01] is a damn fine compiler :-) +-- +Eric Young | BOOL is tri-state according to Bill Gates. +AARNet: eay@cryptsoft.com | RTFM Win32 GetMessage(). + + + + +==== ssl-ciph.doc ======================================================== + +This is a quick high level summery of how things work now. + +Each SSLv2 and SSLv3 cipher is composed of 4 major attributes plus a few extra +minor ones. + +They are 'The key exchange algorithm', which is RSA for SSLv2 but can also +be Diffle-Hellman for SSLv3. + +An 'Authenticion algorithm', which can be RSA, Diffle-Helman, DSS or +none. + +The cipher + +The MAC digest. + +A cipher can also be an export cipher and is either an SSLv2 or a +SSLv3 ciphers. + +To specify which ciphers to use, one can either specify all the ciphers, +one at a time, or use 'aliases' to specify the preference and order for +the ciphers. + +There are a large number of aliases, but the most importaint are +kRSA, kDHr, kDHd and kEDH for key exchange types. + +aRSA, aDSS, aNULL and aDH for authentication +DES, 3DES, RC4, RC2, IDEA and eNULL for ciphers +MD5, SHA0 and SHA1 digests + +Now where this becomes interesting is that these can be put together to +specify the order and ciphers you wish to use. + +To speed this up there are also aliases for certian groups of ciphers. +The main ones are +SSLv2 - all SSLv2 ciphers +SSLv3 - all SSLv3 ciphers +EXP - all export ciphers +LOW - all low strngth ciphers (no export ciphers, normally single DES) +MEDIUM - 128 bit encryption +HIGH - Triple DES + +These aliases can be joined in a : separated list which specifies to +add ciphers, move them to the current location and delete them. + +A simpler way to look at all of this is to use the 'ssleay ciphers -v' command. +The default library cipher spec is +!ADH:RC4+RSA:HIGH:MEDIUM:LOW:EXP:+SSLv2:+EXP +which means, first, remove from consideration any ciphers that do not +authenticate. Next up, use ciphers using RC4 and RSA. Next include the HIGH, +MEDIUM and the LOW security ciphers. Finish up by adding all the export +ciphers on the end, then 'pull' all the SSLv2 and export ciphers to +the end of the list. + +The results are +$ ssleay ciphers -v '!ADH:RC4+RSA:HIGH:MEDIUM:LOW:EXP:+SSLv2:+EXP' + +RC4-SHA SSLv3 Kx=RSA Au=RSA Enc=RC4(128) Mac=SHA1 +RC4-MD5 SSLv3 Kx=RSA Au=RSA Enc=RC4(128) Mac=MD5 +EDH-RSA-DES-CBC3-SHA SSLv3 Kx=DH Au=RSA Enc=3DES(168) Mac=SHA1 +EDH-DSS-DES-CBC3-SHA SSLv3 Kx=DH Au=DSS Enc=3DES(168) Mac=SHA1 +DES-CBC3-SHA SSLv3 Kx=RSA Au=RSA Enc=3DES(168) Mac=SHA1 +IDEA-CBC-MD5 SSLv3 Kx=RSA Au=RSA Enc=IDEA(128) Mac=SHA1 +EDH-RSA-DES-CBC-SHA SSLv3 Kx=DH Au=RSA Enc=DES(56) Mac=SHA1 +EDH-DSS-DES-CBC-SHA SSLv3 Kx=DH Au=DSS Enc=DES(56) Mac=SHA1 +DES-CBC-SHA SSLv3 Kx=RSA Au=RSA Enc=DES(56) Mac=SHA1 +DES-CBC3-MD5 SSLv2 Kx=RSA Au=RSA Enc=3DES(168) Mac=MD5 +DES-CBC-MD5 SSLv2 Kx=RSA Au=RSA Enc=DES(56) Mac=MD5 +IDEA-CBC-MD5 SSLv2 Kx=RSA Au=RSA Enc=IDEA(128) Mac=MD5 +RC2-CBC-MD5 SSLv2 Kx=RSA Au=RSA Enc=RC2(128) Mac=MD5 +RC4-MD5 SSLv2 Kx=RSA Au=RSA Enc=RC4(128) Mac=MD5 +EXP-EDH-RSA-DES-CBC SSLv3 Kx=DH(512) Au=RSA Enc=DES(40) Mac=SHA1 export +EXP-EDH-DSS-DES-CBC-SHA SSLv3 Kx=DH(512) Au=DSS Enc=DES(40) Mac=SHA1 export +EXP-DES-CBC-SHA SSLv3 Kx=RSA(512) Au=RSA Enc=DES(40) Mac=SHA1 export +EXP-RC2-CBC-MD5 SSLv3 Kx=RSA(512) Au=RSA Enc=RC2(40) Mac=MD5 export +EXP-RC4-MD5 SSLv3 Kx=RSA(512) Au=RSA Enc=RC4(40) Mac=MD5 export +EXP-RC2-CBC-MD5 SSLv2 Kx=RSA(512) Au=RSA Enc=RC2(40) Mac=MD5 export +EXP-RC4-MD5 SSLv2 Kx=RSA(512) Au=RSA Enc=RC4(40) Mac=MD5 export + +I would recoment people use the 'ssleay ciphers -v "text"' +command to check what they are going to use. + +Anyway, I'm falling asleep here so I'll do some more tomorrow. + +eric + +==== ssl.doc ======================================================== + +SSL_CTX_sessions(SSL_CTX *ctx) - the session-id hash table. + +/* Session-id cache stats */ +SSL_CTX_sess_number +SSL_CTX_sess_connect +SSL_CTX_sess_connect_good +SSL_CTX_sess_accept +SSL_CTX_sess_accept_good +SSL_CTX_sess_hits +SSL_CTX_sess_cb_hits +SSL_CTX_sess_misses +SSL_CTX_sess_timeouts + +/* Session-id application notification callbacks */ +SSL_CTX_sess_set_new_cb +SSL_CTX_sess_get_new_cb +SSL_CTX_sess_set_get_cb +SSL_CTX_sess_get_get_cb + +/* Session-id cache operation mode */ +SSL_CTX_set_session_cache_mode +SSL_CTX_get_session_cache_mode + +/* Set default timeout values to use. */ +SSL_CTX_set_timeout +SSL_CTX_get_timeout + +/* Global SSL initalisation informational callback */ +SSL_CTX_set_info_callback +SSL_CTX_get_info_callback +SSL_set_info_callback +SSL_get_info_callback + +/* If the SSL_accept/SSL_connect returned with -1, these indicate when + * we should re-call *. +SSL_want +SSL_want_nothing +SSL_want_read +SSL_want_write +SSL_want_x509_lookup + +/* Where we are in SSL initalisation, used in non-blocking, perhaps + * have a look at ssl/bio_ssl.c */ +SSL_state +SSL_is_init_finished +SSL_in_init +SSL_in_connect_init +SSL_in_accept_init + +/* Used to set the 'inital' state so SSL_in_connect_init and SSL_in_accept_init + * can be used to work out which function to call. */ +SSL_set_connect_state +SSL_set_accept_state + +/* Where to look for certificates for authentication */ +SSL_set_default_verify_paths /* calles SSL_load_verify_locations */ +SSL_load_verify_locations + +/* get info from an established connection */ +SSL_get_session +SSL_get_certificate +SSL_get_SSL_CTX + +SSL_CTX_new +SSL_CTX_free +SSL_new +SSL_clear +SSL_free + +SSL_CTX_set_cipher_list +SSL_get_cipher +SSL_set_cipher_list +SSL_get_cipher_list +SSL_get_shared_ciphers + +SSL_accept +SSL_connect +SSL_read +SSL_write + +SSL_debug + +SSL_get_read_ahead +SSL_set_read_ahead +SSL_set_verify + +SSL_pending + +SSL_set_fd +SSL_set_rfd +SSL_set_wfd +SSL_set_bio +SSL_get_fd +SSL_get_rbio +SSL_get_wbio + +SSL_use_RSAPrivateKey +SSL_use_RSAPrivateKey_ASN1 +SSL_use_RSAPrivateKey_file +SSL_use_PrivateKey +SSL_use_PrivateKey_ASN1 +SSL_use_PrivateKey_file +SSL_use_certificate +SSL_use_certificate_ASN1 +SSL_use_certificate_file + +ERR_load_SSL_strings +SSL_load_error_strings + +/* human readable version of the 'state' of the SSL connection. */ +SSL_state_string +SSL_state_string_long +/* These 2 report what kind of IO operation the library was trying to + * perform last. Probably not very usefull. */ +SSL_rstate_string +SSL_rstate_string_long + +SSL_get_peer_certificate + +SSL_SESSION_new +SSL_SESSION_print_fp +SSL_SESSION_print +SSL_SESSION_free +i2d_SSL_SESSION +d2i_SSL_SESSION + +SSL_get_time +SSL_set_time +SSL_get_timeout +SSL_set_timeout +SSL_copy_session_id +SSL_set_session +SSL_CTX_add_session +SSL_CTX_remove_session +SSL_CTX_flush_sessions + +BIO_f_ssl + +/* used to hold information as to why a certificate verification failed */ +SSL_set_verify_result +SSL_get_verify_result + +/* can be used by the application to associate data with an SSL structure. + * It needs to be 'free()ed' by the application */ +SSL_set_app_data +SSL_get_app_data + +/* The following all set values that are kept in the SSL_CTX but + * are used as the default values when an SSL session is created. + * They are over writen by the relevent SSL_xxxx functions */ + +/* SSL_set_verify */ +void SSL_CTX_set_default_verify + +/* This callback, if set, totaly overrides the normal SSLeay verification + * functions and should return 1 on success and 0 on failure */ +void SSL_CTX_set_cert_verify_callback + +/* The following are the same as the equivilent SSL_xxx functions. + * Only one copy of this information is kept and if a particular + * SSL structure has a local override, it is totally separate structure. + */ +int SSL_CTX_use_RSAPrivateKey +int SSL_CTX_use_RSAPrivateKey_ASN1 +int SSL_CTX_use_RSAPrivateKey_file +int SSL_CTX_use_PrivateKey +int SSL_CTX_use_PrivateKey_ASN1 +int SSL_CTX_use_PrivateKey_file +int SSL_CTX_use_certificate +int SSL_CTX_use_certificate_ASN1 +int SSL_CTX_use_certificate_file + + +==== ssl_ctx.doc ======================================================== + +This is now a bit dated, quite a few of the SSL_ functions could be +SSL_CTX_ functions. I will update this in the future. 30 Aug 1996 + +From eay@orb.mincom.oz.au Mon Dec 11 21:37:08 1995 +Received: by orb.mincom.oz.au id AA00696 + (5.65c/IDA-1.4.4 for eay); Mon, 11 Dec 1995 11:37:08 +1000 +Date: Mon, 11 Dec 1995 11:37:08 +1000 (EST) +From: Eric Young +X-Sender: eay@orb +To: sameer +Cc: Eric Young +Subject: Re: PEM_readX509 oesn't seem to be working +In-Reply-To: <199512110102.RAA12521@infinity.c2.org> +Message-Id: +Mime-Version: 1.0 +Content-Type: TEXT/PLAIN; charset=US-ASCII +Status: RO +X-Status: + +On Sun, 10 Dec 1995, sameer wrote: +> OK, that's solved. I've found out that it is saying "no +> certificate set" in SSL_accept because s->conn == NULL +> so there is some place I need to initialize s->conn that I am +> not initializing it. + +The full order of things for a server should be. + +ctx=SSL_CTX_new(); + +/* The next line should not really be using ctx->cert but I'll leave it + * this way right now... I don't want a X509_ routine to know about an SSL + * structure, there should be an SSL_load_verify_locations... hmm, I may + * add it tonight. + */ +X509_load_verify_locations(ctx->cert,CAfile,CApath); + +/* Ok now for each new connection we do the following */ +con=SSL_new(ctx); +SSL_set_fd(con,s); +SSL_set_verify(con,verify,verify_callback); + +/* set the certificate and private key to use. */ +SSL_use_certificate_ASN1(con,X509_certificate); +SSL_use_RSAPrivateKey_ASN1(con,RSA_private_key); + +SSL_accept(con); + +SSL_read(con)/SSL_write(con); + +There is a bit more than that but that is basically the structure. + +Create a context and specify where to lookup certificates. + +foreach connection + { + create a SSL structure + set the certificate and private key + do a SSL_accept + + we should now be ok + } + +eric +-- +Eric Young | Signature removed since it was generating +AARNet: eay@mincom.oz.au | more followups than the message contents :-) + + + +==== ssleay.doc ======================================================== + +SSLeay: a cryptographic kitchen sink. + +1st December 1995 +Way back at the start of April 1995, I was looking for a mindless +programming project. A friend of mine (Tim Hudson) said "why don't you do SSL, +it has DES encryption in it and I would not mind using it in a SSL telnet". +While it was true I had written a DES library in previous years, litle +did I know what an expansive task SSL would turn into. + +First of all, the SSL protocol contains DES encryption. Well and good. My +DES library was fast and portable. It also contained the RSA's RC4 stream +cipher. Again, not a problem, some-one had just posted to sci.crypt +something that was claimed to be RC4. It also contained IDEA, I had the +specifications, not a problem to implement. MD5, an RFC, trivial, at most +I could spend a week or so trying to see if I could speed up the +implementation. All in all a nice set of ciphers. +Then the first 'expantion of the scope', RSA public key +encryption. Since I did not knowing a thing about public key encryption +or number theory, this appeared quite a daunting task. Just writing a +big number library would be problomatic in itself, let alone making it fast. +At this point the scope of 'implementing SSL' expands eponentialy. +First of all, the RSA private keys were being kept in ASN.1 format. +Thankfully the RSA PKCS series of documents explains this format. So I now +needed to be able to encode and decode arbitary ASN.1 objects. The Public +keys were embeded in X509 certificates. Hmm... these are not only +ASN.1 objects but they make up a heirachy of authentication. To +authenticate a X509 certificate one needs to retrieve it's issuers +certificate etc etc. Hmm..., so I also need to implement some kind +of certificate management software. I would also have to implement +software to authenticate certificates. At this point the support code made +the SSL part of my library look quite small. +Around this time, the first version of SSLeay was released. + +Ah, but here was the problem, I was not happy with the code so far. As may +have become obvious, I had been treating all of this as a learning +exersize, so I have completely written the library myself. As such, due +to the way it had grown like a fungus, much of the library was not +'elagent' or neat. There were global and static variables all over the +place, the SSL part did not even handle non-blocking IO. +The Great rewrite began. + +As of this point in time, the 'Great rewrite' has almost finished. So what +follows is an approximate list of what is actually SSLeay 0.5.0 + +/********* This needs to be updated for 0.6.0+ *************/ + +--- +The library contains the following routines. Please note that most of these +functions are not specfic for SSL or any other particular cipher +implementation. I have tried to make all the routines as general purpose +as possible. So you should not think of this library as an SSL +implemtation, but rather as a library of cryptographic functions +that also contains SSL. I refer to each of these function groupings as +libraries since they are often capable of functioning as independant +libraries + +First up, the general ciphers and message digests supported by the library. + +MD2 rfc???, a standard 'by parts' interface to this algorithm. +MD5 rfc???, the same type of interface as for the MD2 library except a + different algorithm. +SHA THe Secure Hash Algorithm. Again the same type of interface as + MD2/MD5 except the digest is 20 bytes. +SHA1 The 'revised' version of SHA. Just about identical to SHA except + for one tweak of an inner loop. +DES This is my libdes library that has been floating around for the last + few years. It has been enhanced for no other reason than completeness. + It now supports ecb, cbc, cfb, ofb, cfb64, ofb64 in normal mode and + triple DES modes of ecb, cbc, cfb64 and ofb64. cfb64 and ofb64 are + functional interfaces to the 64 bit modes of cfb and ofb used in + such a way thay they function as single character interfaces. +RC4 The RSA Inc. stream cipher. +RC2 The RSA Inc. block cipher. +IDEA An implmentation of the IDEA cipher, the library supports ecb, cbc, + cfb64 and ofb64 modes of operation. + +Now all the above mentioned ciphers and digests libraries support high +speed, minimal 'crap in the way' type interfaces. For fastest and +lowest level access, these routines should be used directly. + +Now there was also the matter of public key crypto systems. These are +based on large integer arithmatic. + +BN This is my large integer library. It supports all the normal + arithmentic operations. It uses malloc extensivly and as such has + no limits of the size of the numbers being manipulated. If you + wish to use 4000 bit RSA moduli, these routines will handle it. + This library also contains routines to 'generate' prime numbers and + to test for primality. The RSA and DH libraries sit on top of this + library. As of this point in time, I don't support SHA, but + when I do add it, it will just sit on top of the routines contained + in this library. +RSA This implements the RSA public key algorithm. It also contains + routines that will generate a new private/public key pair. + All the RSA functions conform to the PKCS#1 standard. +DH This is an implementation of the + Diffie-Hellman protocol. There are all the require routines for + the protocol, plus extra routines that can be used to generate a + strong prime for use with a specified generator. While this last + routine is not generally required by applications implementing DH, + It is present for completeness and because I thing it is much + better to be able to 'generate' your own 'magic' numbers as oposed + to using numbers suplied by others. I conform to the PKCS#3 + standard where required. + +You may have noticed the preceeding section mentions the 'generation' of +prime numbers. Now this requries the use of 'random numbers'. + +RAND This psuedo-random number library is based on MD5 at it's core + and a large internal state (2k bytes). Once you have entered enough + seed data into this random number algorithm I don't feel + you will ever need to worry about it generating predictable output. + Due to the way I am writing a portable library, I have left the + issue of how to get good initial random seed data upto the + application but I do have support routines for saving and loading a + persistant random number state for use between program runs. + +Now to make all these ciphers easier to use, a higher level +interface was required. In this form, the same function would be used to +encrypt 'by parts', via any one of the above mentioned ciphers. + +EVP The Digital EnVeloPe library is quite large. At it's core are + function to perform encryption and decryption by parts while using + an initial parameter to specify which of the 17 different ciphers + or 4 different message digests to use. On top of these are implmented + the digital signature functions, sign, verify, seal and open. + Base64 encoding of binary data is also done in this library. + +PEM rfc???? describe the format for Privacy Enhanced eMail. + As part of this standard, methods of encoding digital enveloped + data is an ascii format are defined. As such, I use a form of these + to encode enveloped data. While at this point in time full support + for PEM has not been built into the library, a minimal subset of + the secret key and Base64 encoding is present. These reoutines are + mostly used to Ascii encode binary data with a 'type' associated + with it and perhaps details of private key encryption used to + encrypt the data. + +PKCS7 This is another Digital Envelope encoding standard which uses ASN.1 + to encode the data. At this point in time, while there are some + routines to encode and decode this binary format, full support is + not present. + +As Mentioned, above, there are several different ways to encode +data structures. + +ASN1 This library is more a set of primatives used to encode the packing + and unpacking of data structures. It is used by the X509 + certificate standard and by the PKCS standards which are used by + this library. It also contains routines for duplicating and signing + the structures asocisated with X509. + +X509 The X509 library contains routines for packing and unpacking, + verifying and just about every thing else you would want to do with + X509 certificates. + +PKCS7 PKCS-7 is a standard for encoding digital envelope data + structures. At this point in time the routines will load and save + DER forms of these structees. They need to be re-worked to support + the BER form which is the normal way PKCS-7 is encoded. If the + previous 2 sentances don't make much sense, don't worry, this + library is not used by this version of SSLeay anyway. + +OBJ ASN.1 uses 'object identifiers' to identify objects. A set of + functions were requred to translate from ASN.1 to an intenger, to a + character string. This library provieds these translations + +Now I mentioned an X509 library. X509 specified a hieachy of certificates +which needs to be traversed to authenticate particular certificates. + +METH This library is used to push 'methods' of retrieving certificates + into the library. There are some supplied 'methods' with SSLeay + but applications can add new methods if they so desire. + This library has not been finished and is not being used in this + version. + +Now all the above are required for use in the initial point of this project. + +SSL The SSL protocol. This is a full implmentation of SSL v 2. It + support both server and client authentication. SSL v 3 support + will be added when the SSL v 3 specification is released in it's + final form. + +Now quite a few of the above mentioned libraries rely on a few 'complex' +data structures. For each of these I have a library. + +Lhash This is a hash table library which is used extensivly. + +STACK An implemetation of a Stack data structure. + +BUF A simple character array structure that also support a function to + check that the array is greater that a certain size, if it is not, + it is realloced so that is it. + +TXT_DB A simple memory based text file data base. The application can specify + unique indexes that will be enforced at update time. + +CONF Most of the programs written for this library require a configuration + file. Instead of letting programs constantly re-implment this + subsystem, the CONF library provides a consistant and flexable + interface to not only configuration files but also environment + variables. + +But what about when something goes wrong? +The one advantage (and perhaps disadvantage) of all of these +functions being in one library was the ability to implement a +single error reporting system. + +ERR This library is used to report errors. The error system records + library number, function number (in the library) and reason + number. Multiple errors can be reported so that an 'error' trace + is created. The errors can be printed in numeric or textual form. + + +==== ssluse.doc ======================================================== + +We have an SSL_CTX which contains global information for lots of +SSL connections. The session-id cache and the certificate verificate cache. +It also contains default values for use when certificates are used. + +SSL_CTX + default cipher list + session-id cache + certificate cache + default session-id timeout period + New session-id callback + Required session-id callback + session-id stats + Informational callback + Callback that is set, overrides the SSLeay X509 certificate + verification + The default Certificate/Private Key pair + Default read ahead mode. + Default verify mode and verify callback. These are not used + if the over ride callback mentioned above is used. + +Each SSL can have the following defined for it before a connection is made. + +Certificate +Private key +Ciphers to use +Certificate verify mode and callback +IO object to use in the comunication. +Some 'read-ahead' mode information. +A previous session-id to re-use. + +A connection is made by using SSL_connect or SSL_accept. +When non-blocking IO is being used, there are functions that can be used +to determin where and why the SSL_connect or SSL_accept did not complete. +This information can be used to recall the functions when the 'error' +condition has dissapeared. + +After the connection has been made, information can be retrived about the +SSL session and the session-id values that have been decided upon. +The 'peer' certificate can be retrieved. + +The session-id values include +'start time' +'timeout length' + + + +==== stack.doc ======================================================== + +The stack data structure is used to store an ordered list of objects. +It is basically misnamed to call it a stack but it can function that way +and that is what I originally used it for. Due to the way element +pointers are kept in a malloc()ed array, the most efficient way to use this +structure is to add and delete elements from the end via sk_pop() and +sk_push(). If you wish to do 'lookups' sk_find() is quite efficient since +it will sort the stack (if required) and then do a binary search to lookup +the requested item. This sorting occurs automatically so just sk_push() +elements on the stack and don't worry about the order. Do remember that if +you do a sk_find(), the order of the elements will change. + +You should never need to 'touch' this structure directly. +typedef struct stack_st + { + unsigned int num; + char **data; + int sorted; + + unsigned int num_alloc; + int (*comp)(); + } STACK; + +'num' holds the number of elements in the stack, 'data' is the array of +elements. 'sorted' is 1 is the list has been sorted, 0 if not. + +num_alloc is the number of 'nodes' allocated in 'data'. When num becomes +larger than num_alloc, data is realloced to a larger size. +If 'comp' is set, it is a function that is used to compare 2 of the items +in the stack. The function should return -1, 0 or 1, depending on the +ordering. + +#define sk_num(sk) ((sk)->num) +#define sk_value(sk,n) ((sk)->data[n]) + +These 2 macros should be used to access the number of elements in the +'stack' and to access a pointer to one of the values. + +STACK *sk_new(int (*c)()); + This creates a new stack. If 'c', the comparison function, is not +specified, the various functions that operate on a sorted 'stack' will not +work (sk_find()). NULL is returned on failure. + +void sk_free(STACK *); + This function free()'s a stack structure. The elements in the +stack will not be freed so one should 'pop' and free all elements from the +stack before calling this function or call sk_pop_free() instead. + +void sk_pop_free(STACK *st; void (*func)()); + This function calls 'func' for each element on the stack, passing +the element as the argument. sk_free() is then called to free the 'stack' +structure. + +int sk_insert(STACK *sk,char *data,int where); + This function inserts 'data' into stack 'sk' at location 'where'. +If 'where' is larger that the number of elements in the stack, the element +is put at the end. This function tends to be used by other 'stack' +functions. Returns 0 on failure, otherwise the number of elements in the +new stack. + +char *sk_delete(STACK *st,int loc); + Remove the item a location 'loc' from the stack and returns it. +Returns NULL if the 'loc' is out of range. + +char *sk_delete_ptr(STACK *st, char *p); + If the data item pointed to by 'p' is in the stack, it is deleted +from the stack and returned. NULL is returned if the element is not in the +stack. + +int sk_find(STACK *st,char *data); + Returns the location that contains a value that is equal to +the 'data' item. If the comparison function was not set, this function +does a linear search. This function actually qsort()s the stack if it is not +in order and then uses bsearch() to do the initial search. If the +search fails,, -1 is returned. For mutliple items with the same +value, the index of the first in the array is returned. + +int sk_push(STACK *st,char *data); + Append 'data' to the stack. 0 is returned if there is a failure +(due to a malloc failure), else 1. This is +sk_insert(st,data,sk_num(st)); + +int sk_unshift(STACK *st,char *data); + Prepend 'data' to the front (location 0) of the stack. This is +sk_insert(st,data,0); + +char *sk_shift(STACK *st); + Return and delete from the stack the first element in the stack. +This is sk_delete(st,0); + +char *sk_pop(STACK *st); + Return and delete the last element on the stack. This is +sk_delete(st,sk_num(sk)-1); + +void sk_zero(STACK *st); + Removes all items from the stack. It does not 'free' +pointers but is a quick way to clear a 'stack of references'. + +==== threads.doc ======================================================== + +How to compile SSLeay for multi-threading. + +Well basically it is quite simple, set the compiler flags and build. +I have only really done much testing under Solaris and Windows NT. +If you library supports localtime_r() and gmtime_r() add, +-DTHREADS to the makefile parameters. You can probably survive with out +this define unless you are going to have multiple threads generating +certificates at once. It will not affect the SSL side of things. + +The approach I have taken to doing locking is to make the application provide +callbacks to perform locking and so that the SSLeay library can distinguish +between threads (for the error state). + +To have a look at an example program, 'cd mt; vi mttest.c'. +To build under solaris, sh solaris.sh, for Windows NT or Windows 95, +win32.bat + +This will build mttest which will fire up 10 threads that talk SSL +to each other 10 times. +To enable everything to work, the application needs to call + +CRYPTO_set_id_callback(id_function); +CRYPTO_set_locking_callback(locking_function); + +before any multithreading is started. +id_function does not need to be defined under Windows NT or 95, the +correct function will be called if it is not. Under unix, getpid() +is call if the id_callback is not defined, for Solaris this is wrong +(since threads id's are not pid's) but under Linux it is correct +(threads are just processes sharing the data segement). + +The locking_callback is used to perform locking by the SSLeay library. +eg. + +void solaris_locking_callback(mode,type,file,line) +int mode; +int type; +char *file; +int line; + { + if (mode & CRYPTO_LOCK) + mutex_lock(&(lock_cs[type])); + else + mutex_unlock(&(lock_cs[type])); + } + +Now in this case I have used mutexes instead of read/write locks, since they +are faster and there are not many read locks in SSLeay, you may as well +always use write locks. file and line are __FILE__ and __LINE__ from +the compile and can be usefull when debugging. + +Now as you can see, 'type' can be one of a range of values, these values are +defined in crypto/crypto.h +CRYPTO_get_lock_name(type) will return a text version of what the lock is. +There are CRYPTO_NUM_LOCKS locks required, so under solaris, the setup +for multi-threading can be + +static mutex_t lock_cs[CRYPTO_NUM_LOCKS]; + +void thread_setup() + { + int i; + + for (i=0; i => string to prompt with +# _default => default value for people +# _value => Automatically use this value for this field. +# _min => minimum number of characters for data (def. 0) +# _max => maximum number of characters for data (def. inf.) +# All of these entries are optional except for the first one. +[ req_dn ] +countryName = Country Name (2 letter code) +countryName_default = AU + +stateOrProvinceName = State or Province Name (full name) +stateOrProvinceName_default = Queensland + +localityName = Locality Name (eg, city) + +organizationName = Organization Name (eg, company) +organizationName_default = Mincom Pty Ltd + +organizationalUnitName = Organizational Unit Name (eg, section) +organizationalUnitName_default = MTR + +commonName = Common Name (eg, YOUR name) +commonName_max = 64 + +emailAddress = Email Address +emailAddress_max = 40 + +# The next section is the attributes section. This is exactly the +# same as for the previous section except that the resulting objects are +# put in the attributes field. +[ req_attr ] +challengePassword = A challenge password +challengePassword_min = 4 +challengePassword_max = 20 + +unstructuredName = An optional company name + +---- +Also note that the order that attributes appear in this file is the +order they will be put into the distinguished name. + +Once this request has been generated, it can be sent to a CA for +certifying. + +---- +A few quick examples.... + +To generate a new request and a new key +req -new + +To generate a new request and a 1058 bit key +req -newkey 1058 + +To generate a new request using a pre-existing key +req -new -key key.pem + +To generate a self signed x509 certificate from a certificate +request using a supplied key, and we want to see the text form of the +output certificate (which we will put in the file selfSign.pem +req -x509 -in req.pem -key key.pem -text -out selfSign.pem + +Verify that the signature is correct on a certificate request. +req -verify -in req.pem + +Verify that the signature was made using a specified public key. +req -verify -in req.pem -key key.pem + +Print the contents of a certificate request +req -text -in req.pem + +==== danger ======================================================== + +If you specify a SSLv2 cipher, and the mode is SSLv23 and the server +can talk SSLv3, it will claim there is no cipher since you should be +using SSLv3. + +When tracing debug stuff, remember BIO_s_socket() is different to +BIO_s_connect(). + +BSD/OS assember is not working + diff --git a/node-v0.8.14/deps/openssl/openssl/doc/standards.txt b/node-v0.8.14/deps/openssl/openssl/doc/standards.txt new file mode 100644 index 0000000..7bada8d --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/doc/standards.txt @@ -0,0 +1,285 @@ +Standards related to OpenSSL +============================ + +[Please, this is currently a draft. I made a first try at finding + documents that describe parts of what OpenSSL implements. There are + big gaps, and I've most certainly done something wrong. Please + correct whatever is... Also, this note should be removed when this + file is reaching a somewhat correct state. -- Richard Levitte] + + +All pointers in here will be either URL's or blobs of text borrowed +from miscellaneous indexes, like rfc-index.txt (index of RFCs), +1id-index.txt (index of Internet drafts) and the like. + +To find the latest possible RFCs, it's recommended to either browse +ftp://ftp.isi.edu/in-notes/ or go to http://www.rfc-editor.org/ and +use the search mechanism found there. +To find the latest possible Internet drafts, it's recommended to +browse ftp://ftp.isi.edu/internet-drafts/. +To find the latest possible PKCS, it's recommended to browse +http://www.rsasecurity.com/rsalabs/pkcs/. + + +Implemented: +------------ + +These are documents that describe things that are implemented (in +whole or at least great parts) in OpenSSL. + +1319 The MD2 Message-Digest Algorithm. B. Kaliski. April 1992. + (Format: TXT=25661 bytes) (Status: INFORMATIONAL) + +1320 The MD4 Message-Digest Algorithm. R. Rivest. April 1992. (Format: + TXT=32407 bytes) (Status: INFORMATIONAL) + +1321 The MD5 Message-Digest Algorithm. R. Rivest. April 1992. (Format: + TXT=35222 bytes) (Status: INFORMATIONAL) + +2246 The TLS Protocol Version 1.0. T. Dierks, C. Allen. January 1999. + (Format: TXT=170401 bytes) (Status: PROPOSED STANDARD) + +2268 A Description of the RC2(r) Encryption Algorithm. R. Rivest. + January 1998. (Format: TXT=19048 bytes) (Status: INFORMATIONAL) + +2315 PKCS 7: Cryptographic Message Syntax Version 1.5. B. Kaliski. + March 1998. (Format: TXT=69679 bytes) (Status: INFORMATIONAL) + +PKCS#8: Private-Key Information Syntax Standard + +PKCS#12: Personal Information Exchange Syntax Standard, version 1.0. + +2560 X.509 Internet Public Key Infrastructure Online Certificate + Status Protocol - OCSP. M. Myers, R. Ankney, A. Malpani, S. Galperin, + C. Adams. June 1999. (Format: TXT=43243 bytes) (Status: PROPOSED + STANDARD) + +2712 Addition of Kerberos Cipher Suites to Transport Layer Security + (TLS). A. Medvinsky, M. Hur. October 1999. (Format: TXT=13763 bytes) + (Status: PROPOSED STANDARD) + +2898 PKCS #5: Password-Based Cryptography Specification Version 2.0. + B. Kaliski. September 2000. (Format: TXT=68692 bytes) (Status: + INFORMATIONAL) + +2986 PKCS #10: Certification Request Syntax Specification Version 1.7. + M. Nystrom, B. Kaliski. November 2000. (Format: TXT=27794 bytes) + (Obsoletes RFC2314) (Status: INFORMATIONAL) + +3174 US Secure Hash Algorithm 1 (SHA1). D. Eastlake 3rd, P. Jones. + September 2001. (Format: TXT=35525 bytes) (Status: INFORMATIONAL) + +3161 Internet X.509 Public Key Infrastructure, Time-Stamp Protocol (TSP) + C. Adams, P. Cain, D. Pinkas, R. Zuccherato. August 2001 + (Status: PROPOSED STANDARD) + +3268 Advanced Encryption Standard (AES) Ciphersuites for Transport + Layer Security (TLS). P. Chown. June 2002. (Format: TXT=13530 bytes) + (Status: PROPOSED STANDARD) + +3279 Algorithms and Identifiers for the Internet X.509 Public Key + Infrastructure Certificate and Certificate Revocation List (CRL) + Profile. L. Bassham, W. Polk, R. Housley. April 2002. (Format: + TXT=53833 bytes) (Status: PROPOSED STANDARD) + +3280 Internet X.509 Public Key Infrastructure Certificate and + Certificate Revocation List (CRL) Profile. R. Housley, W. Polk, W. + Ford, D. Solo. April 2002. (Format: TXT=295556 bytes) (Obsoletes + RFC2459) (Status: PROPOSED STANDARD) + +3447 Public-Key Cryptography Standards (PKCS) #1: RSA Cryptography + Specifications Version 2.1. J. Jonsson, B. Kaliski. February 2003. + (Format: TXT=143173 bytes) (Obsoletes RFC2437) (Status: + INFORMATIONAL) + +3713 A Description of the Camellia Encryption Algorithm. M. Matsui, + J. Nakajima, S. Moriai. April 2004. (Format: TXT=25031 bytes) + (Status: INFORMATIONAL) + +3820 Internet X.509 Public Key Infrastructure (PKI) Proxy Certificate + Profile. S. Tuecke, V. Welch, D. Engert, L. Pearlman, M. Thompson. + June 2004. (Format: TXT=86374 bytes) (Status: PROPOSED STANDARD) + +4132 Addition of Camellia Cipher Suites to Transport Layer Security + (TLS). S. Moriai, A. Kato, M. Kanda. July 2005. (Format: TXT=13590 + bytes) (Status: PROPOSED STANDARD) + +4162 Addition of SEED Cipher Suites to Transport Layer Security (TLS). + H.J. Lee, J.H. Yoon, J.I. Lee. August 2005. (Format: TXT=10578 bytes) + (Status: PROPOSED STANDARD) + +4269 The SEED Encryption Algorithm. H.J. Lee, S.J. Lee, J.H. Yoon, + D.H. Cheon, J.I. Lee. December 2005. (Format: TXT=34390 bytes) + (Obsoletes RFC4009) (Status: INFORMATIONAL) + + +Related: +-------- + +These are documents that are close to OpenSSL, for example the +STARTTLS documents. + +1421 Privacy Enhancement for Internet Electronic Mail: Part I: Message + Encryption and Authentication Procedures. J. Linn. February 1993. + (Format: TXT=103894 bytes) (Obsoletes RFC1113) (Status: PROPOSED + STANDARD) + +1422 Privacy Enhancement for Internet Electronic Mail: Part II: + Certificate-Based Key Management. S. Kent. February 1993. (Format: + TXT=86085 bytes) (Obsoletes RFC1114) (Status: PROPOSED STANDARD) + +1423 Privacy Enhancement for Internet Electronic Mail: Part III: + Algorithms, Modes, and Identifiers. D. Balenson. February 1993. + (Format: TXT=33277 bytes) (Obsoletes RFC1115) (Status: PROPOSED + STANDARD) + +1424 Privacy Enhancement for Internet Electronic Mail: Part IV: Key + Certification and Related Services. B. Kaliski. February 1993. + (Format: TXT=17537 bytes) (Status: PROPOSED STANDARD) + +2025 The Simple Public-Key GSS-API Mechanism (SPKM). C. Adams. October + 1996. (Format: TXT=101692 bytes) (Status: PROPOSED STANDARD) + +2510 Internet X.509 Public Key Infrastructure Certificate Management + Protocols. C. Adams, S. Farrell. March 1999. (Format: TXT=158178 + bytes) (Status: PROPOSED STANDARD) + +2511 Internet X.509 Certificate Request Message Format. M. Myers, C. + Adams, D. Solo, D. Kemp. March 1999. (Format: TXT=48278 bytes) + (Status: PROPOSED STANDARD) + +2527 Internet X.509 Public Key Infrastructure Certificate Policy and + Certification Practices Framework. S. Chokhani, W. Ford. March 1999. + (Format: TXT=91860 bytes) (Status: INFORMATIONAL) + +2538 Storing Certificates in the Domain Name System (DNS). D. Eastlake + 3rd, O. Gudmundsson. March 1999. (Format: TXT=19857 bytes) (Status: + PROPOSED STANDARD) + +2539 Storage of Diffie-Hellman Keys in the Domain Name System (DNS). + D. Eastlake 3rd. March 1999. (Format: TXT=21049 bytes) (Status: + PROPOSED STANDARD) + +2559 Internet X.509 Public Key Infrastructure Operational Protocols - + LDAPv2. S. Boeyen, T. Howes, P. Richard. April 1999. (Format: + TXT=22889 bytes) (Updates RFC1778) (Status: PROPOSED STANDARD) + +2585 Internet X.509 Public Key Infrastructure Operational Protocols: + FTP and HTTP. R. Housley, P. Hoffman. May 1999. (Format: TXT=14813 + bytes) (Status: PROPOSED STANDARD) + +2587 Internet X.509 Public Key Infrastructure LDAPv2 Schema. S. + Boeyen, T. Howes, P. Richard. June 1999. (Format: TXT=15102 bytes) + (Status: PROPOSED STANDARD) + +2595 Using TLS with IMAP, POP3 and ACAP. C. Newman. June 1999. + (Format: TXT=32440 bytes) (Status: PROPOSED STANDARD) + +2631 Diffie-Hellman Key Agreement Method. E. Rescorla. June 1999. + (Format: TXT=25932 bytes) (Status: PROPOSED STANDARD) + +2632 S/MIME Version 3 Certificate Handling. B. Ramsdell, Ed.. June + 1999. (Format: TXT=27925 bytes) (Status: PROPOSED STANDARD) + +2716 PPP EAP TLS Authentication Protocol. B. Aboba, D. Simon. October + 1999. (Format: TXT=50108 bytes) (Status: EXPERIMENTAL) + +2773 Encryption using KEA and SKIPJACK. R. Housley, P. Yee, W. Nace. + February 2000. (Format: TXT=20008 bytes) (Updates RFC0959) (Status: + EXPERIMENTAL) + +2797 Certificate Management Messages over CMS. M. Myers, X. Liu, J. + Schaad, J. Weinstein. April 2000. (Format: TXT=103357 bytes) (Status: + PROPOSED STANDARD) + +2817 Upgrading to TLS Within HTTP/1.1. R. Khare, S. Lawrence. May + 2000. (Format: TXT=27598 bytes) (Updates RFC2616) (Status: PROPOSED + STANDARD) + +2818 HTTP Over TLS. E. Rescorla. May 2000. (Format: TXT=15170 bytes) + (Status: INFORMATIONAL) + +2876 Use of the KEA and SKIPJACK Algorithms in CMS. J. Pawling. July + 2000. (Format: TXT=29265 bytes) (Status: INFORMATIONAL) + +2984 Use of the CAST-128 Encryption Algorithm in CMS. C. Adams. + October 2000. (Format: TXT=11591 bytes) (Status: PROPOSED STANDARD) + +2985 PKCS #9: Selected Object Classes and Attribute Types Version 2.0. + M. Nystrom, B. Kaliski. November 2000. (Format: TXT=70703 bytes) + (Status: INFORMATIONAL) + +3029 Internet X.509 Public Key Infrastructure Data Validation and + Certification Server Protocols. C. Adams, P. Sylvester, M. Zolotarev, + R. Zuccherato. February 2001. (Format: TXT=107347 bytes) (Status: + EXPERIMENTAL) + +3039 Internet X.509 Public Key Infrastructure Qualified Certificates + Profile. S. Santesson, W. Polk, P. Barzin, M. Nystrom. January 2001. + (Format: TXT=67619 bytes) (Status: PROPOSED STANDARD) + +3058 Use of the IDEA Encryption Algorithm in CMS. S. Teiwes, P. + Hartmann, D. Kuenzi. February 2001. (Format: TXT=17257 bytes) + (Status: INFORMATIONAL) + +3161 Internet X.509 Public Key Infrastructure Time-Stamp Protocol + (TSP). C. Adams, P. Cain, D. Pinkas, R. Zuccherato. August 2001. + (Format: TXT=54585 bytes) (Status: PROPOSED STANDARD) + +3185 Reuse of CMS Content Encryption Keys. S. Farrell, S. Turner. + October 2001. (Format: TXT=20404 bytes) (Status: PROPOSED STANDARD) + +3207 SMTP Service Extension for Secure SMTP over Transport Layer + Security. P. Hoffman. February 2002. (Format: TXT=18679 bytes) + (Obsoletes RFC2487) (Status: PROPOSED STANDARD) + +3217 Triple-DES and RC2 Key Wrapping. R. Housley. December 2001. + (Format: TXT=19855 bytes) (Status: INFORMATIONAL) + +3274 Compressed Data Content Type for Cryptographic Message Syntax + (CMS). P. Gutmann. June 2002. (Format: TXT=11276 bytes) (Status: + PROPOSED STANDARD) + +3278 Use of Elliptic Curve Cryptography (ECC) Algorithms in + Cryptographic Message Syntax (CMS). S. Blake-Wilson, D. Brown, P. + Lambert. April 2002. (Format: TXT=33779 bytes) (Status: + INFORMATIONAL) + +3281 An Internet Attribute Certificate Profile for Authorization. S. + Farrell, R. Housley. April 2002. (Format: TXT=90580 bytes) (Status: + PROPOSED STANDARD) + +3369 Cryptographic Message Syntax (CMS). R. Housley. August 2002. + (Format: TXT=113975 bytes) (Obsoletes RFC2630, RFC3211) (Status: + PROPOSED STANDARD) + +3370 Cryptographic Message Syntax (CMS) Algorithms. R. Housley. August + 2002. (Format: TXT=51001 bytes) (Obsoletes RFC2630, RFC3211) (Status: + PROPOSED STANDARD) + +3377 Lightweight Directory Access Protocol (v3): Technical + Specification. J. Hodges, R. Morgan. September 2002. (Format: + TXT=9981 bytes) (Updates RFC2251, RFC2252, RFC2253, RFC2254, RFC2255, + RFC2256, RFC2829, RFC2830) (Status: PROPOSED STANDARD) + +3394 Advanced Encryption Standard (AES) Key Wrap Algorithm. J. Schaad, + R. Housley. September 2002. (Format: TXT=73072 bytes) (Status: + INFORMATIONAL) + +3436 Transport Layer Security over Stream Control Transmission + Protocol. A. Jungmaier, E. Rescorla, M. Tuexen. December 2002. + (Format: TXT=16333 bytes) (Status: PROPOSED STANDARD) + +3657 Use of the Camellia Encryption Algorithm in Cryptographic + Message Syntax (CMS). S. Moriai, A. Kato. January 2004. + (Format: TXT=26282 bytes) (Status: PROPOSED STANDARD) + +"Securing FTP with TLS", 01/27/2000, + + +To be implemented: +------------------ + +These are documents that describe things that are planed to be +implemented in the hopefully short future. + diff --git a/node-v0.8.14/deps/openssl/openssl/e_os.h b/node-v0.8.14/deps/openssl/openssl/e_os.h new file mode 100644 index 0000000..5ceeeeb --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/e_os.h @@ -0,0 +1,746 @@ +/* e_os.h */ +/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com) + * All rights reserved. + * + * This package is an SSL implementation written + * by Eric Young (eay@cryptsoft.com). + * The implementation was written so as to conform with Netscapes SSL. + * + * This library is free for commercial and non-commercial use as long as + * the following conditions are aheared to. The following conditions + * apply to all code found in this distribution, be it the RC4, RSA, + * lhash, DES, etc., code; not just the SSL code. The SSL documentation + * included with this distribution is covered by the same copyright terms + * except that the holder is Tim Hudson (tjh@cryptsoft.com). + * + * Copyright remains Eric Young's, and as such any Copyright notices in + * the code are not to be removed. + * If this package is used in a product, Eric Young should be given attribution + * as the author of the parts of the library used. + * This can be in the form of a textual message at program startup or + * in documentation (online or textual) provided with the package. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * "This product includes cryptographic software written by + * Eric Young (eay@cryptsoft.com)" + * The word 'cryptographic' can be left out if the rouines from the library + * being used are not cryptographic related :-). + * 4. If you include any Windows specific code (or a derivative thereof) from + * the apps directory (application code) you must include an acknowledgement: + * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)" + * + * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * + * The licence and distribution terms for any publically available version or + * derivative of this code cannot be changed. i.e. this code cannot simply be + * copied and put under another distribution licence + * [including the GNU Public Licence.] + */ + +#ifndef HEADER_E_OS_H +#define HEADER_E_OS_H + +#include + +#include +/* contains what we can justify to make visible + * to the outside; this file e_os.h is not part of the exported + * interface. */ + +#ifdef __cplusplus +extern "C" { +#endif + +/* Used to checking reference counts, most while doing perl5 stuff :-) */ +#ifdef REF_PRINT +#undef REF_PRINT +#define REF_PRINT(a,b) fprintf(stderr,"%08X:%4d:%s\n",(int)b,b->references,a) +#endif + +#ifndef DEVRANDOM +/* set this to a comma-separated list of 'random' device files to try out. + * My default, we will try to read at least one of these files */ +#define DEVRANDOM "/dev/urandom","/dev/random","/dev/srandom" +#endif +#ifndef DEVRANDOM_EGD +/* set this to a comma-seperated list of 'egd' sockets to try out. These + * sockets will be tried in the order listed in case accessing the device files + * listed in DEVRANDOM did not return enough entropy. */ +#define DEVRANDOM_EGD "/var/run/egd-pool","/dev/egd-pool","/etc/egd-pool","/etc/entropy" +#endif + +#if defined(OPENSSL_SYS_VXWORKS) +# define NO_SYS_PARAM_H +# define NO_CHMOD +# define NO_SYSLOG +#endif + +#if defined(OPENSSL_SYS_MACINTOSH_CLASSIC) +# if macintosh==1 +# ifndef MAC_OS_GUSI_SOURCE +# define MAC_OS_pre_X +# define NO_SYS_TYPES_H + typedef long ssize_t; +# endif +# define NO_SYS_PARAM_H +# define NO_CHMOD +# define NO_SYSLOG +# undef DEVRANDOM +# define GETPID_IS_MEANINGLESS +# endif +#endif + +/******************************************************************** + The Microsoft section + ********************************************************************/ +/* The following is used because of the small stack in some + * Microsoft operating systems */ +#if defined(OPENSSL_SYS_MSDOS) && !defined(OPENSSL_SYSNAME_WIN32) +# define MS_STATIC static +#else +# define MS_STATIC +#endif + +#if defined(OPENSSL_SYS_WIN32) && !defined(WIN32) +# define WIN32 +#endif +#if defined(OPENSSL_SYS_WINDOWS) && !defined(WINDOWS) +# define WINDOWS +#endif +#if defined(OPENSSL_SYS_MSDOS) && !defined(MSDOS) +# define MSDOS +#endif + +#if defined(MSDOS) && !defined(GETPID_IS_MEANINGLESS) +# define GETPID_IS_MEANINGLESS +#endif + +#ifdef WIN32 +#define get_last_sys_error() GetLastError() +#define clear_sys_error() SetLastError(0) +#if !defined(WINNT) +#define WIN_CONSOLE_BUG +#endif +#else +#define get_last_sys_error() errno +#define clear_sys_error() errno=0 +#endif + +#if defined(WINDOWS) +#define get_last_socket_error() WSAGetLastError() +#define clear_socket_error() WSASetLastError(0) +#define readsocket(s,b,n) recv((s),(b),(n),0) +#define writesocket(s,b,n) send((s),(b),(n),0) +#elif defined(__DJGPP__) +#define WATT32 +#define get_last_socket_error() errno +#define clear_socket_error() errno=0 +#define closesocket(s) close_s(s) +#define readsocket(s,b,n) read_s(s,b,n) +#define writesocket(s,b,n) send(s,b,n,0) +#elif defined(MAC_OS_pre_X) +#define get_last_socket_error() errno +#define clear_socket_error() errno=0 +#define closesocket(s) MacSocket_close(s) +#define readsocket(s,b,n) MacSocket_recv((s),(b),(n),true) +#define writesocket(s,b,n) MacSocket_send((s),(b),(n)) +#elif defined(OPENSSL_SYS_VMS) +#define get_last_socket_error() errno +#define clear_socket_error() errno=0 +#define ioctlsocket(a,b,c) ioctl(a,b,c) +#define closesocket(s) close(s) +#define readsocket(s,b,n) recv((s),(b),(n),0) +#define writesocket(s,b,n) send((s),(b),(n),0) +#elif defined(OPENSSL_SYS_VXWORKS) +#define get_last_socket_error() errno +#define clear_socket_error() errno=0 +#define ioctlsocket(a,b,c) ioctl((a),(b),(int)(c)) +#define closesocket(s) close(s) +#define readsocket(s,b,n) read((s),(b),(n)) +#define writesocket(s,b,n) write((s),(char *)(b),(n)) +#elif defined(OPENSSL_SYS_BEOS_R5) +#define get_last_socket_error() errno +#define clear_socket_error() errno=0 +#define FIONBIO SO_NONBLOCK +#define ioctlsocket(a,b,c) setsockopt((a),SOL_SOCKET,(b),(c),sizeof(*(c))) +#define readsocket(s,b,n) recv((s),(b),(n),0) +#define writesocket(s,b,n) send((s),(b),(n),0) +#elif defined(OPENSSL_SYS_NETWARE) +#if defined(NETWARE_BSDSOCK) +#define get_last_socket_error() errno +#define clear_socket_error() errno=0 +#define closesocket(s) close(s) +#define ioctlsocket(a,b,c) ioctl(a,b,c) +#if defined(NETWARE_LIBC) +#define readsocket(s,b,n) recv((s),(b),(n),0) +#define writesocket(s,b,n) send((s),(b),(n),0) +#else +#define readsocket(s,b,n) recv((s),(char*)(b),(n),0) +#define writesocket(s,b,n) send((s),(char*)(b),(n),0) +#endif +#else +#define get_last_socket_error() WSAGetLastError() +#define clear_socket_error() WSASetLastError(0) +#define readsocket(s,b,n) recv((s),(b),(n),0) +#define writesocket(s,b,n) send((s),(b),(n),0) +#endif +#else +#define get_last_socket_error() errno +#define clear_socket_error() errno=0 +#define ioctlsocket(a,b,c) ioctl(a,b,c) +#define closesocket(s) close(s) +#define readsocket(s,b,n) read((s),(b),(n)) +#define writesocket(s,b,n) write((s),(b),(n)) +#endif + +#ifdef WIN16 /* never the case */ +# define MS_CALLBACK _far _loadds +# define MS_FAR _far +#else +# define MS_CALLBACK +# define MS_FAR +#endif + +#ifdef OPENSSL_NO_STDIO +# undef OPENSSL_NO_FP_API +# define OPENSSL_NO_FP_API +#endif + +#if (defined(WINDOWS) || defined(MSDOS)) + +# ifdef __DJGPP__ +# include +# include +# include +# include +# include +# define _setmode setmode +# define _O_TEXT O_TEXT +# define _O_BINARY O_BINARY +# undef DEVRANDOM +# define DEVRANDOM "/dev/urandom\x24" +# endif /* __DJGPP__ */ + +# ifndef S_IFDIR +# define S_IFDIR _S_IFDIR +# endif + +# ifndef S_IFMT +# define S_IFMT _S_IFMT +# endif + +# if !defined(WINNT) && !defined(__DJGPP__) +# define NO_SYSLOG +# endif +# define NO_DIRENT + +# ifdef WINDOWS +# if !defined(_WIN32_WCE) && !defined(_WIN32_WINNT) + /* + * Defining _WIN32_WINNT here in e_os.h implies certain "discipline." + * Most notably we ought to check for availability of each specific + * routine with GetProcAddress() and/or guard NT-specific calls with + * GetVersion() < 0x80000000. One can argue that in latter "or" case + * we ought to /DELAYLOAD some .DLLs in order to protect ourselves + * against run-time link errors. This doesn't seem to be necessary, + * because it turned out that already Windows 95, first non-NT Win32 + * implementation, is equipped with at least NT 3.51 stubs, dummy + * routines with same name, but which do nothing. Meaning that it's + * apparently sufficient to guard "vanilla" NT calls with GetVersion + * alone, while NT 4.0 and above interfaces ought to be linked with + * GetProcAddress at run-time. + */ +# define _WIN32_WINNT 0x0400 +# endif +# if !defined(OPENSSL_NO_SOCK) && defined(_WIN32_WINNT) + /* + * Just like defining _WIN32_WINNT including winsock2.h implies + * certain "discipline" for maintaining [broad] binary compatibility. + * As long as structures are invariant among Winsock versions, + * it's sufficient to check for specific Winsock2 API availability + * at run-time [DSO_global_lookup is recommended]... + */ +# include +# include + /* yes, they have to be #included prior to */ +# endif +# include +# include +# include +# include +# include +# ifdef _WIN64 +# define strlen(s) _strlen31(s) +/* cut strings to 2GB */ +static unsigned int _strlen31(const char *str) + { + unsigned int len=0; + while (*str && len<0x80000000U) str++, len++; + return len&0x7FFFFFFF; + } +# endif +# include +# if defined(_MSC_VER) && _MSC_VER<=1200 && defined(_MT) && defined(isspace) + /* compensate for bug in VC6 ctype.h */ +# undef isspace +# undef isdigit +# undef isalnum +# undef isupper +# undef isxdigit +# endif +# if defined(_MSC_VER) && !defined(_DLL) && defined(stdin) +# if _MSC_VER>=1300 +# undef stdin +# undef stdout +# undef stderr + FILE *__iob_func(); +# define stdin (&__iob_func()[0]) +# define stdout (&__iob_func()[1]) +# define stderr (&__iob_func()[2]) +# elif defined(I_CAN_LIVE_WITH_LNK4049) +# undef stdin +# undef stdout +# undef stderr + /* pre-1300 has __p__iob(), but it's available only in msvcrt.lib, + * or in other words with /MD. Declaring implicit import, i.e. + * with _imp_ prefix, works correctly with all compiler options, + * but without /MD results in LINK warning LNK4049: + * 'locally defined symbol "__iob" imported'. + */ + extern FILE *_imp___iob; +# define stdin (&_imp___iob[0]) +# define stdout (&_imp___iob[1]) +# define stderr (&_imp___iob[2]) +# endif +# endif +# endif +# include +# include + +# ifdef OPENSSL_SYS_WINCE +# define OPENSSL_NO_POSIX_IO +# endif + +# define ssize_t long + +# if defined (__BORLANDC__) +# define _setmode setmode +# define _O_TEXT O_TEXT +# define _O_BINARY O_BINARY +# define _int64 __int64 +# define _kbhit kbhit +# endif + +# define EXIT(n) exit(n) +# define LIST_SEPARATOR_CHAR ';' +# ifndef X_OK +# define X_OK 0 +# endif +# ifndef W_OK +# define W_OK 2 +# endif +# ifndef R_OK +# define R_OK 4 +# endif +# define OPENSSL_CONF "openssl.cnf" +# define SSLEAY_CONF OPENSSL_CONF +# define NUL_DEV "nul" +# define RFILE ".rnd" +# ifdef OPENSSL_SYS_WINCE +# define DEFAULT_HOME "" +# else +# define DEFAULT_HOME "C:" +# endif + +#else /* The non-microsoft world */ + +# ifdef OPENSSL_SYS_VMS +# define VMS 1 + /* some programs don't include stdlib, so exit() and others give implicit + function warnings */ +# include +# if defined(__DECC) +# include +# else +# include +# endif +# define OPENSSL_CONF "openssl.cnf" +# define SSLEAY_CONF OPENSSL_CONF +# define RFILE ".rnd" +# define LIST_SEPARATOR_CHAR ',' +# define NUL_DEV "NLA0:" + /* We don't have any well-defined random devices on VMS, yet... */ +# undef DEVRANDOM + /* We need to do this since VMS has the following coding on status codes: + + Bits 0-2: status type: 0 = warning, 1 = success, 2 = error, 3 = info ... + The important thing to know is that odd numbers are considered + good, while even ones are considered errors. + Bits 3-15: actual status number + Bits 16-27: facility number. 0 is considered "unknown" + Bits 28-31: control bits. If bit 28 is set, the shell won't try to + output the message (which, for random codes, just looks ugly) + + So, what we do here is to change 0 to 1 to get the default success status, + and everything else is shifted up to fit into the status number field, and + the status is tagged as an error, which I believe is what is wanted here. + -- Richard Levitte + */ +# define EXIT(n) do { int __VMS_EXIT = n; \ + if (__VMS_EXIT == 0) \ + __VMS_EXIT = 1; \ + else \ + __VMS_EXIT = (n << 3) | 2; \ + __VMS_EXIT |= 0x10000000; \ + exit(__VMS_EXIT); } while(0) +# define NO_SYS_PARAM_H + +# elif defined(OPENSSL_SYS_NETWARE) +# include +# include +# define NO_SYS_TYPES_H +# undef DEVRANDOM +# ifdef NETWARE_CLIB +# define getpid GetThreadID + extern int GetThreadID(void); +/* # include */ + extern int kbhit(void); +# else +# include +# endif +# define NO_SYSLOG +# define _setmode setmode +# define _kbhit kbhit +# define _O_TEXT O_TEXT +# define _O_BINARY O_BINARY +# define OPENSSL_CONF "openssl.cnf" +# define SSLEAY_CONF OPENSSL_CONF +# define RFILE ".rnd" +# define LIST_SEPARATOR_CHAR ';' +# define EXIT(n) { if (n) printf("ERROR: %d\n", (int)n); exit(n); } + +# else + /* !defined VMS */ +# ifdef OPENSSL_SYS_MPE +# define NO_SYS_PARAM_H +# endif +# ifdef OPENSSL_UNISTD +# include OPENSSL_UNISTD +# else +# include +# endif +# ifndef NO_SYS_TYPES_H +# include +# endif +# if defined(NeXT) || defined(OPENSSL_SYS_NEWS4) +# define pid_t int /* pid_t is missing on NEXTSTEP/OPENSTEP + * (unless when compiling with -D_POSIX_SOURCE, + * which doesn't work for us) */ +# endif +# if defined(NeXT) || defined(OPENSSL_SYS_NEWS4) || defined(OPENSSL_SYS_SUNOS) +# define ssize_t int /* ditto */ +# endif +# ifdef OPENSSL_SYS_NEWS4 /* setvbuf is missing on mips-sony-bsd */ +# define setvbuf(a, b, c, d) setbuffer((a), (b), (d)) + typedef unsigned long clock_t; +# endif +# ifdef OPENSSL_SYS_WIN32_CYGWIN +# include +# include +# endif + +# define OPENSSL_CONF "openssl.cnf" +# define SSLEAY_CONF OPENSSL_CONF +# define RFILE ".rnd" +# define LIST_SEPARATOR_CHAR ':' +# define NUL_DEV "/dev/null" +# define EXIT(n) exit(n) +# endif + +# define SSLeay_getpid() getpid() + +#endif + + +/*************/ + +#ifdef USE_SOCKETS +# if defined(WINDOWS) || defined(MSDOS) + /* windows world */ + +# ifdef OPENSSL_NO_SOCK +# define SSLeay_Write(a,b,c) (-1) +# define SSLeay_Read(a,b,c) (-1) +# define SHUTDOWN(fd) close(fd) +# define SHUTDOWN2(fd) close(fd) +# elif !defined(__DJGPP__) +# if defined(_WIN32_WCE) && _WIN32_WCE<410 +# define getservbyname _masked_declaration_getservbyname +# endif +# if !defined(IPPROTO_IP) + /* winsock[2].h was included already? */ +# include +# endif +# ifdef getservbyname +# undef getservbyname + /* this is used to be wcecompat/include/winsock_extras.h */ + struct servent* PASCAL getservbyname(const char*,const char*); +# endif + +# ifdef _WIN64 +/* + * Even though sizeof(SOCKET) is 8, it's safe to cast it to int, because + * the value constitutes an index in per-process table of limited size + * and not a real pointer. + */ +# define socket(d,t,p) ((int)socket(d,t,p)) +# define accept(s,f,l) ((int)accept(s,f,l)) +# endif +# define SSLeay_Write(a,b,c) send((a),(b),(c),0) +# define SSLeay_Read(a,b,c) recv((a),(b),(c),0) +# define SHUTDOWN(fd) { shutdown((fd),0); closesocket(fd); } +# define SHUTDOWN2(fd) { shutdown((fd),2); closesocket(fd); } +# else +# define SSLeay_Write(a,b,c) write_s(a,b,c,0) +# define SSLeay_Read(a,b,c) read_s(a,b,c) +# define SHUTDOWN(fd) close_s(fd) +# define SHUTDOWN2(fd) close_s(fd) +# endif + +# elif defined(MAC_OS_pre_X) + +# include "MacSocket.h" +# define SSLeay_Write(a,b,c) MacSocket_send((a),(b),(c)) +# define SSLeay_Read(a,b,c) MacSocket_recv((a),(b),(c),true) +# define SHUTDOWN(fd) MacSocket_close(fd) +# define SHUTDOWN2(fd) MacSocket_close(fd) + +# elif defined(OPENSSL_SYS_NETWARE) + /* NetWare uses the WinSock2 interfaces by default, but can be configured for BSD + */ +# if defined(NETWARE_BSDSOCK) +# include +# include +# include +# if defined(NETWARE_CLIB) +# include +# else +# include +# endif +# define INVALID_SOCKET (int)(~0) +# else +# include +# endif +# define SSLeay_Write(a,b,c) send((a),(b),(c),0) +# define SSLeay_Read(a,b,c) recv((a),(b),(c),0) +# define SHUTDOWN(fd) { shutdown((fd),0); closesocket(fd); } +# define SHUTDOWN2(fd) { shutdown((fd),2); closesocket(fd); } + +# else + +# ifndef NO_SYS_PARAM_H +# include +# endif +# ifdef OPENSSL_SYS_VXWORKS +# include +# elif !defined(OPENSSL_SYS_MPE) +# include /* Needed under linux for FD_XXX */ +# endif + +# include +# if defined(OPENSSL_SYS_VMS_NODECC) +# include +# include +# include +# else +# include +# ifdef FILIO_H +# include /* Added for FIONBIO under unixware */ +# endif +# include +# if !defined(OPENSSL_SYS_BEOS_R5) +# include +# endif +# endif + +# if defined(NeXT) || defined(_NEXT_SOURCE) +# include +# include +# endif + +# ifdef OPENSSL_SYS_AIX +# include +# endif + +# ifdef __QNX__ +# include +# endif + +# if defined(sun) +# include +# else +# ifndef VMS +# include +# else + /* ioctl is only in VMS > 7.0 and when socketshr is not used */ +# if !defined(TCPIP_TYPE_SOCKETSHR) && defined(__VMS_VER) && (__VMS_VER > 70000000) +# include +# endif +# endif +# endif + +# ifdef VMS +# include +# if defined(TCPIP_TYPE_SOCKETSHR) +# include +# endif +# endif + +# define SSLeay_Read(a,b,c) read((a),(b),(c)) +# define SSLeay_Write(a,b,c) write((a),(b),(c)) +# define SHUTDOWN(fd) { shutdown((fd),0); closesocket((fd)); } +# define SHUTDOWN2(fd) { shutdown((fd),2); closesocket((fd)); } +# ifndef INVALID_SOCKET +# define INVALID_SOCKET (-1) +# endif /* INVALID_SOCKET */ +# endif + +/* Some IPv6 implementations are broken, disable them in known bad + * versions. + */ +# if !defined(OPENSSL_USE_IPV6) +# if defined(AF_INET6) && !defined(OPENSSL_SYS_BEOS_BONE) && !defined(NETWARE_CLIB) +# define OPENSSL_USE_IPV6 1 +# else +# define OPENSSL_USE_IPV6 0 +# endif +# endif + +#endif + +#if defined(__ultrix) +# ifndef ssize_t +# define ssize_t int +# endif +#endif + +#if defined(sun) && !defined(__svr4__) && !defined(__SVR4) + /* include headers first, so our defines don't break it */ +#include +#include + /* bcopy can handle overlapping moves according to SunOS 4.1.4 manpage */ +# define memmove(s1,s2,n) bcopy((s2),(s1),(n)) +# define strtoul(s,e,b) ((unsigned long int)strtol((s),(e),(b))) +extern char *sys_errlist[]; extern int sys_nerr; +# define strerror(errnum) \ + (((errnum)<0 || (errnum)>=sys_nerr) ? NULL : sys_errlist[errnum]) + /* Being signed SunOS 4.x memcpy breaks ASN1_OBJECT table lookup */ +#include "crypto/o_str.h" +# define memcmp OPENSSL_memcmp +#endif + +#ifndef OPENSSL_EXIT +# if defined(MONOLITH) && !defined(OPENSSL_C) +# define OPENSSL_EXIT(n) return(n) +# else +# define OPENSSL_EXIT(n) do { EXIT(n); return(n); } while(0) +# endif +#endif + +/***********************************************/ + +#define DG_GCC_BUG /* gcc < 2.6.3 on DGUX */ + +#ifdef sgi +#define IRIX_CC_BUG /* all version of IRIX I've tested (4.* 5.*) */ +#endif +#ifdef OPENSSL_SYS_SNI +#define IRIX_CC_BUG /* CDS++ up to V2.0Bsomething suffered from the same bug.*/ +#endif + +#if defined(OPENSSL_SYS_WINDOWS) +# define strcasecmp _stricmp +# define strncasecmp _strnicmp +#elif defined(OPENSSL_SYS_VMS) +/* VMS below version 7.0 doesn't have strcasecmp() */ +# include "o_str.h" +# define strcasecmp OPENSSL_strcasecmp +# define strncasecmp OPENSSL_strncasecmp +# define OPENSSL_IMPLEMENTS_strncasecmp +#elif defined(OPENSSL_SYS_OS2) && defined(__EMX__) +# define strcasecmp stricmp +# define strncasecmp strnicmp +#elif defined(OPENSSL_SYS_NETWARE) +# include +# if defined(NETWARE_CLIB) +# define strcasecmp stricmp +# define strncasecmp strnicmp +# endif /* NETWARE_CLIB */ +#endif + +#if defined(OPENSSL_SYS_OS2) && defined(__EMX__) +# include +# include +# define NO_SYSLOG +#endif + +/* vxworks */ +#if defined(OPENSSL_SYS_VXWORKS) +#include +#include +#include + +#define TTY_STRUCT int + +#define sleep(a) taskDelay((a) * sysClkRateGet()) + +#include +#include +#include + +#define getpid taskIdSelf + +/* NOTE: these are implemented by helpers in database app! + * if the database is not linked, we need to implement them + * elswhere */ +struct hostent *gethostbyname(const char *name); +struct hostent *gethostbyaddr(const char *addr, int length, int type); +struct servent *getservbyname(const char *name, const char *proto); + +#endif +/* end vxworks */ + +/* beos */ +#if defined(OPENSSL_SYS_BEOS_R5) +#define SO_ERROR 0 +#define NO_SYS_UN +#define IPPROTO_IP 0 +#include +#endif + + +#ifdef __cplusplus +} +#endif + +#endif + diff --git a/node-v0.8.14/deps/openssl/openssl/e_os2.h b/node-v0.8.14/deps/openssl/openssl/e_os2.h new file mode 100644 index 0000000..d30724d --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/e_os2.h @@ -0,0 +1,295 @@ +/* e_os2.h */ +/* ==================================================================== + * Copyright (c) 1998-2000 The OpenSSL Project. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. All advertising materials mentioning features or use of this + * software must display the following acknowledgment: + * "This product includes software developed by the OpenSSL Project + * for use in the OpenSSL Toolkit. (http://www.openssl.org/)" + * + * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to + * endorse or promote products derived from this software without + * prior written permission. For written permission, please contact + * openssl-core@openssl.org. + * + * 5. Products derived from this software may not be called "OpenSSL" + * nor may "OpenSSL" appear in their names without prior written + * permission of the OpenSSL Project. + * + * 6. Redistributions of any form whatsoever must retain the following + * acknowledgment: + * "This product includes software developed by the OpenSSL Project + * for use in the OpenSSL Toolkit (http://www.openssl.org/)" + * + * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY + * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR + * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, + * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * ==================================================================== + * + * This product includes cryptographic software written by Eric Young + * (eay@cryptsoft.com). This product includes software written by Tim + * Hudson (tjh@cryptsoft.com). + * + */ + +#include + +#ifndef HEADER_E_OS2_H +#define HEADER_E_OS2_H + +#ifdef __cplusplus +extern "C" { +#endif + +/****************************************************************************** + * Detect operating systems. This probably needs completing. + * The result is that at least one OPENSSL_SYS_os macro should be defined. + * However, if none is defined, Unix is assumed. + **/ + +#define OPENSSL_SYS_UNIX + +/* ----------------------- Macintosh, before MacOS X ----------------------- */ +#if defined(__MWERKS__) && defined(macintosh) || defined(OPENSSL_SYSNAME_MAC) +# undef OPENSSL_SYS_UNIX +# define OPENSSL_SYS_MACINTOSH_CLASSIC +#endif + +/* ----------------------- NetWare ----------------------------------------- */ +#if defined(NETWARE) || defined(OPENSSL_SYSNAME_NETWARE) +# undef OPENSSL_SYS_UNIX +# define OPENSSL_SYS_NETWARE +#endif + +/* ---------------------- Microsoft operating systems ---------------------- */ + +/* Note that MSDOS actually denotes 32-bit environments running on top of + MS-DOS, such as DJGPP one. */ +#if defined(OPENSSL_SYSNAME_MSDOS) +# undef OPENSSL_SYS_UNIX +# define OPENSSL_SYS_MSDOS +#endif + +/* For 32 bit environment, there seems to be the CygWin environment and then + all the others that try to do the same thing Microsoft does... */ +#if defined(OPENSSL_SYSNAME_UWIN) +# undef OPENSSL_SYS_UNIX +# define OPENSSL_SYS_WIN32_UWIN +#else +# if defined(__CYGWIN32__) || defined(OPENSSL_SYSNAME_CYGWIN32) +# undef OPENSSL_SYS_UNIX +# define OPENSSL_SYS_WIN32_CYGWIN +# else +# if defined(_WIN32) || defined(OPENSSL_SYSNAME_WIN32) +# undef OPENSSL_SYS_UNIX +# define OPENSSL_SYS_WIN32 +# endif +# if defined(OPENSSL_SYSNAME_WINNT) +# undef OPENSSL_SYS_UNIX +# define OPENSSL_SYS_WINNT +# endif +# if defined(OPENSSL_SYSNAME_WINCE) +# undef OPENSSL_SYS_UNIX +# define OPENSSL_SYS_WINCE +# endif +# endif +#endif + +/* Anything that tries to look like Microsoft is "Windows" */ +#if defined(OPENSSL_SYS_WIN32) || defined(OPENSSL_SYS_WINNT) || defined(OPENSSL_SYS_WINCE) +# undef OPENSSL_SYS_UNIX +# define OPENSSL_SYS_WINDOWS +# ifndef OPENSSL_SYS_MSDOS +# define OPENSSL_SYS_MSDOS +# endif +#endif + +/* DLL settings. This part is a bit tough, because it's up to the application + implementor how he or she will link the application, so it requires some + macro to be used. */ +#ifdef OPENSSL_SYS_WINDOWS +# ifndef OPENSSL_OPT_WINDLL +# if defined(_WINDLL) /* This is used when building OpenSSL to indicate that + DLL linkage should be used */ +# define OPENSSL_OPT_WINDLL +# endif +# endif +#endif + +/* -------------------------------- OpenVMS -------------------------------- */ +#if defined(__VMS) || defined(VMS) || defined(OPENSSL_SYSNAME_VMS) +# undef OPENSSL_SYS_UNIX +# define OPENSSL_SYS_VMS +# if defined(__DECC) +# define OPENSSL_SYS_VMS_DECC +# elif defined(__DECCXX) +# define OPENSSL_SYS_VMS_DECC +# define OPENSSL_SYS_VMS_DECCXX +# else +# define OPENSSL_SYS_VMS_NODECC +# endif +#endif + +/* --------------------------------- OS/2 ---------------------------------- */ +#if defined(__EMX__) || defined(__OS2__) +# undef OPENSSL_SYS_UNIX +# define OPENSSL_SYS_OS2 +#endif + +/* --------------------------------- Unix ---------------------------------- */ +#ifdef OPENSSL_SYS_UNIX +# if defined(linux) || defined(__linux__) || defined(OPENSSL_SYSNAME_LINUX) +# define OPENSSL_SYS_LINUX +# endif +# ifdef OPENSSL_SYSNAME_MPE +# define OPENSSL_SYS_MPE +# endif +# ifdef OPENSSL_SYSNAME_SNI +# define OPENSSL_SYS_SNI +# endif +# ifdef OPENSSL_SYSNAME_ULTRASPARC +# define OPENSSL_SYS_ULTRASPARC +# endif +# ifdef OPENSSL_SYSNAME_NEWS4 +# define OPENSSL_SYS_NEWS4 +# endif +# ifdef OPENSSL_SYSNAME_MACOSX +# define OPENSSL_SYS_MACOSX +# endif +# ifdef OPENSSL_SYSNAME_MACOSX_RHAPSODY +# define OPENSSL_SYS_MACOSX_RHAPSODY +# define OPENSSL_SYS_MACOSX +# endif +# ifdef OPENSSL_SYSNAME_SUNOS +# define OPENSSL_SYS_SUNOS +#endif +# if defined(_CRAY) || defined(OPENSSL_SYSNAME_CRAY) +# define OPENSSL_SYS_CRAY +# endif +# if defined(_AIX) || defined(OPENSSL_SYSNAME_AIX) +# define OPENSSL_SYS_AIX +# endif +#endif + +/* --------------------------------- VOS ----------------------------------- */ +#if defined(__VOS__) || defined(OPENSSL_SYSNAME_VOS) +# define OPENSSL_SYS_VOS +#ifdef __HPPA__ +# define OPENSSL_SYS_VOS_HPPA +#endif +#ifdef __IA32__ +# define OPENSSL_SYS_VOS_IA32 +#endif +#endif + +/* ------------------------------- VxWorks --------------------------------- */ +#ifdef OPENSSL_SYSNAME_VXWORKS +# define OPENSSL_SYS_VXWORKS +#endif + +/* --------------------------------- BeOS ---------------------------------- */ +#if defined(__BEOS__) +# define OPENSSL_SYS_BEOS +# include +# if defined(BONE_VERSION) +# define OPENSSL_SYS_BEOS_BONE +# else +# define OPENSSL_SYS_BEOS_R5 +# endif +#endif + +/** + * That's it for OS-specific stuff + *****************************************************************************/ + + +/* Specials for I/O an exit */ +#ifdef OPENSSL_SYS_MSDOS +# define OPENSSL_UNISTD_IO +# define OPENSSL_DECLARE_EXIT extern void exit(int); +#else +# define OPENSSL_UNISTD_IO OPENSSL_UNISTD +# define OPENSSL_DECLARE_EXIT /* declared in unistd.h */ +#endif + +/* Definitions of OPENSSL_GLOBAL and OPENSSL_EXTERN, to define and declare + certain global symbols that, with some compilers under VMS, have to be + defined and declared explicitely with globaldef and globalref. + Definitions of OPENSSL_EXPORT and OPENSSL_IMPORT, to define and declare + DLL exports and imports for compilers under Win32. These are a little + more complicated to use. Basically, for any library that exports some + global variables, the following code must be present in the header file + that declares them, before OPENSSL_EXTERN is used: + + #ifdef SOME_BUILD_FLAG_MACRO + # undef OPENSSL_EXTERN + # define OPENSSL_EXTERN OPENSSL_EXPORT + #endif + + The default is to have OPENSSL_EXPORT, OPENSSL_IMPORT and OPENSSL_GLOBAL + have some generally sensible values, and for OPENSSL_EXTERN to have the + value OPENSSL_IMPORT. +*/ + +#if defined(OPENSSL_SYS_VMS_NODECC) +# define OPENSSL_EXPORT globalref +# define OPENSSL_IMPORT globalref +# define OPENSSL_GLOBAL globaldef +#elif defined(OPENSSL_SYS_WINDOWS) && defined(OPENSSL_OPT_WINDLL) +# define OPENSSL_EXPORT extern __declspec(dllexport) +# define OPENSSL_IMPORT extern __declspec(dllimport) +# define OPENSSL_GLOBAL +#else +# define OPENSSL_EXPORT extern +# define OPENSSL_IMPORT extern +# define OPENSSL_GLOBAL +#endif +#define OPENSSL_EXTERN OPENSSL_IMPORT + +/* Macros to allow global variables to be reached through function calls when + required (if a shared library version requires it, for example. + The way it's done allows definitions like this: + + // in foobar.c + OPENSSL_IMPLEMENT_GLOBAL(int,foobar,0) + // in foobar.h + OPENSSL_DECLARE_GLOBAL(int,foobar); + #define foobar OPENSSL_GLOBAL_REF(foobar) +*/ +#ifdef OPENSSL_EXPORT_VAR_AS_FUNCTION +# define OPENSSL_IMPLEMENT_GLOBAL(type,name,value) \ + type *_shadow_##name(void) \ + { static type _hide_##name=value; return &_hide_##name; } +# define OPENSSL_DECLARE_GLOBAL(type,name) type *_shadow_##name(void) +# define OPENSSL_GLOBAL_REF(name) (*(_shadow_##name())) +#else +# define OPENSSL_IMPLEMENT_GLOBAL(type,name,value) OPENSSL_GLOBAL type _shadow_##name=value; +# define OPENSSL_DECLARE_GLOBAL(type,name) OPENSSL_EXPORT type _shadow_##name +# define OPENSSL_GLOBAL_REF(name) _shadow_##name +#endif + +#ifdef __cplusplus +} +#endif +#endif diff --git a/node-v0.8.14/deps/openssl/openssl/engines/Makefile b/node-v0.8.14/deps/openssl/openssl/engines/Makefile new file mode 100644 index 0000000..2fa9534 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/engines/Makefile @@ -0,0 +1,335 @@ +# +# OpenSSL/engines/Makefile +# + +DIR= engines +TOP= .. +CC= cc +INCLUDES= -I../include +CFLAG=-g +MAKEFILE= Makefile +AR= ar r +ENGDIRS= ccgost + +RECURSIVE_MAKE= [ -z "$(ENGDIRS)" ] || for i in $(ENGDIRS) ; do \ + (cd $$i && echo "making $$target in $(DIR)/$$i..." && \ + $(MAKE) -e TOP=../.. DIR=$$i $$target ) || exit 1; \ + done; + +PEX_LIBS= +EX_LIBS= + +CFLAGS= $(INCLUDES) $(CFLAG) + +GENERAL=Makefile engines.com install.com engine_vector.mar +TEST= +APPS= + +LIB=$(TOP)/libcrypto.a +LIBNAMES= 4758cca aep atalla cswift gmp chil nuron sureware ubsec padlock capi + +LIBSRC= e_4758cca.c \ + e_aep.c \ + e_atalla.c \ + e_cswift.c \ + e_gmp.c \ + e_chil.c \ + e_nuron.c \ + e_sureware.c \ + e_ubsec.c \ + e_padlock.c \ + e_capi.c +LIBOBJ= e_4758cca.o \ + e_aep.o \ + e_atalla.o \ + e_cswift.o \ + e_gmp.o \ + e_chil.o \ + e_nuron.o \ + e_sureware.o \ + e_ubsec.o \ + e_padlock.o \ + e_capi.o + +SRC= $(LIBSRC) + +EXHEADER= +HEADER= e_4758cca_err.c e_4758cca_err.h \ + e_aep_err.c e_aep_err.h \ + e_atalla_err.c e_atalla_err.h \ + e_cswift_err.c e_cswift_err.h \ + e_gmp_err.c e_gmp_err.h \ + e_chil_err.c e_chil_err.h \ + e_nuron_err.c e_nuron_err.h \ + e_sureware_err.c e_sureware_err.h \ + e_ubsec_err.c e_ubsec_err.h \ + e_capi_err.c e_capi_err.h + +ALL= $(GENERAL) $(SRC) $(HEADER) + +top: + (cd ..; $(MAKE) DIRS=$(DIR) all) + +all: lib subdirs + +lib: $(LIBOBJ) + @if [ -n "$(SHARED_LIBS)" ]; then \ + set -e; \ + for l in $(LIBNAMES); do \ + $(MAKE) -f ../Makefile.shared -e \ + LIBNAME=$$l LIBEXTRAS=e_$$l.o \ + LIBDEPS='-L.. -lcrypto $(EX_LIBS)' \ + link_o.$(SHLIB_TARGET); \ + done; \ + else \ + $(AR) $(LIB) $(LIBOBJ); \ + $(RANLIB) $(LIB) || echo Never mind.; \ + fi; \ + touch lib + +subdirs: + echo $(EDIRS) + @target=all; $(RECURSIVE_MAKE) + +files: + $(PERL) $(TOP)/util/files.pl Makefile >> $(TOP)/MINFO + @target=files; $(RECURSIVE_MAKE) + +links: + @target=links; $(RECURSIVE_MAKE) + +# XXXXX This currently only works on systems that use .so as suffix +# for shared libraries as well as for Cygwin which uses the +# dlfcn_name_converter and therefore stores the engines with .so suffix, too. +# XXXXX This was extended to HP-UX dl targets, which use .sl suffix. +# XXXXX This was extended to mingw targets, which use eay32.dll suffix without lib as prefix. +install: + @[ -n "$(INSTALLTOP)" ] # should be set by top Makefile... + @if [ -n "$(SHARED_LIBS)" ]; then \ + set -e; \ + $(PERL) $(TOP)/util/mkdir-p.pl $(INSTALL_PREFIX)$(INSTALLTOP)/$(LIBDIR)/engines; \ + for l in $(LIBNAMES); do \ + ( echo installing $$l; \ + pfx=lib; \ + if [ "$(PLATFORM)" != "Cygwin" ]; then \ + case "$(CFLAGS)" in \ + *DSO_BEOS*) sfx=".so";; \ + *DSO_DLFCN*) sfx=`expr "$(SHLIB_EXT)" : '.*\(\.[a-z][a-z]*\)' \| ".so"`;; \ + *DSO_DL*) sfx=".sl";; \ + *DSO_WIN32*) sfx="eay32.dll"; pfx=;; \ + *) sfx=".bad";; \ + esac; \ + cp $$pfx$$l$$sfx $(INSTALL_PREFIX)$(INSTALLTOP)/$(LIBDIR)/engines/$$pfx$$l$$sfx.new; \ + else \ + sfx=".so"; \ + cp cyg$$l.dll $(INSTALL_PREFIX)$(INSTALLTOP)/$(LIBDIR)/engines/$$pfx$$l$$sfx.new; \ + fi; \ + chmod 555 $(INSTALL_PREFIX)$(INSTALLTOP)/$(LIBDIR)/engines/$$pfx$$l$$sfx.new; \ + mv -f $(INSTALL_PREFIX)$(INSTALLTOP)/$(LIBDIR)/engines/$$pfx$$l$$sfx.new $(INSTALL_PREFIX)$(INSTALLTOP)/$(LIBDIR)/engines/$$pfx$$l$$sfx ); \ + done; \ + fi + @target=install; $(RECURSIVE_MAKE) + +tags: + ctags $(SRC) + +errors: + set -e; for l in $(LIBNAMES); do \ + $(PERL) ../util/mkerr.pl -conf e_$$l.ec \ + -nostatic -staticloader -write e_$$l.c; \ + done + (cd ccgost; $(MAKE) PERL=$(PERL) errors) + +tests: + +lint: + lint -DLINT $(INCLUDES) $(SRC)>fluff + @target=lint; $(RECURSIVE_MAKE) + +depend: + @if [ -z "$(THIS)" ]; then \ + $(MAKE) -f $(TOP)/Makefile reflect THIS=$@; \ + fi + @[ -z "$(THIS)" ] || $(MAKEDEPEND) -- $(CFLAG) $(INCLUDES) $(DEPFLAG) -- $(PROGS) $(LIBSRC) + @[ -z "$(THIS)" ] || (set -e; target=depend; $(RECURSIVE_MAKE) ) + +dclean: + $(PERL) -pe 'if (/^# DO NOT DELETE THIS LINE/) {print; exit(0);}' $(MAKEFILE) >Makefile.new + mv -f Makefile.new $(MAKEFILE) + @target=dclean; $(RECURSIVE_MAKE) + +clean: + rm -f *.o *.obj lib tags core .pure .nfs* *.old *.bak fluff + @target=clean; $(RECURSIVE_MAKE) + +# DO NOT DELETE THIS LINE -- make depend depends on it. + +e_4758cca.o: ../include/openssl/asn1.h ../include/openssl/bio.h +e_4758cca.o: ../include/openssl/bn.h ../include/openssl/buffer.h +e_4758cca.o: ../include/openssl/crypto.h ../include/openssl/dso.h +e_4758cca.o: ../include/openssl/e_os2.h ../include/openssl/ec.h +e_4758cca.o: ../include/openssl/ecdh.h ../include/openssl/ecdsa.h +e_4758cca.o: ../include/openssl/engine.h ../include/openssl/err.h +e_4758cca.o: ../include/openssl/evp.h ../include/openssl/lhash.h +e_4758cca.o: ../include/openssl/obj_mac.h ../include/openssl/objects.h +e_4758cca.o: ../include/openssl/opensslconf.h ../include/openssl/opensslv.h +e_4758cca.o: ../include/openssl/ossl_typ.h ../include/openssl/pkcs7.h +e_4758cca.o: ../include/openssl/rand.h ../include/openssl/rsa.h +e_4758cca.o: ../include/openssl/safestack.h ../include/openssl/sha.h +e_4758cca.o: ../include/openssl/stack.h ../include/openssl/symhacks.h +e_4758cca.o: ../include/openssl/x509.h ../include/openssl/x509_vfy.h +e_4758cca.o: e_4758cca.c e_4758cca_err.c e_4758cca_err.h +e_4758cca.o: vendor_defns/hw_4758_cca.h +e_aep.o: ../include/openssl/asn1.h ../include/openssl/bio.h +e_aep.o: ../include/openssl/bn.h ../include/openssl/buffer.h +e_aep.o: ../include/openssl/crypto.h ../include/openssl/dh.h +e_aep.o: ../include/openssl/dsa.h ../include/openssl/dso.h +e_aep.o: ../include/openssl/e_os2.h ../include/openssl/ec.h +e_aep.o: ../include/openssl/ecdh.h ../include/openssl/ecdsa.h +e_aep.o: ../include/openssl/engine.h ../include/openssl/err.h +e_aep.o: ../include/openssl/evp.h ../include/openssl/lhash.h +e_aep.o: ../include/openssl/obj_mac.h ../include/openssl/objects.h +e_aep.o: ../include/openssl/opensslconf.h ../include/openssl/opensslv.h +e_aep.o: ../include/openssl/ossl_typ.h ../include/openssl/pkcs7.h +e_aep.o: ../include/openssl/rsa.h ../include/openssl/safestack.h +e_aep.o: ../include/openssl/sha.h ../include/openssl/stack.h +e_aep.o: ../include/openssl/symhacks.h ../include/openssl/x509.h +e_aep.o: ../include/openssl/x509_vfy.h e_aep.c e_aep_err.c e_aep_err.h +e_aep.o: vendor_defns/aep.h +e_atalla.o: ../include/openssl/asn1.h ../include/openssl/bio.h +e_atalla.o: ../include/openssl/bn.h ../include/openssl/buffer.h +e_atalla.o: ../include/openssl/crypto.h ../include/openssl/dh.h +e_atalla.o: ../include/openssl/dsa.h ../include/openssl/dso.h +e_atalla.o: ../include/openssl/e_os2.h ../include/openssl/ec.h +e_atalla.o: ../include/openssl/ecdh.h ../include/openssl/ecdsa.h +e_atalla.o: ../include/openssl/engine.h ../include/openssl/err.h +e_atalla.o: ../include/openssl/evp.h ../include/openssl/lhash.h +e_atalla.o: ../include/openssl/obj_mac.h ../include/openssl/objects.h +e_atalla.o: ../include/openssl/opensslconf.h ../include/openssl/opensslv.h +e_atalla.o: ../include/openssl/ossl_typ.h ../include/openssl/pkcs7.h +e_atalla.o: ../include/openssl/rsa.h ../include/openssl/safestack.h +e_atalla.o: ../include/openssl/sha.h ../include/openssl/stack.h +e_atalla.o: ../include/openssl/symhacks.h ../include/openssl/x509.h +e_atalla.o: ../include/openssl/x509_vfy.h e_atalla.c e_atalla_err.c +e_atalla.o: e_atalla_err.h vendor_defns/atalla.h +e_capi.o: ../include/openssl/asn1.h ../include/openssl/bio.h +e_capi.o: ../include/openssl/bn.h ../include/openssl/buffer.h +e_capi.o: ../include/openssl/crypto.h ../include/openssl/e_os2.h +e_capi.o: ../include/openssl/ec.h ../include/openssl/ecdh.h +e_capi.o: ../include/openssl/ecdsa.h ../include/openssl/engine.h +e_capi.o: ../include/openssl/evp.h ../include/openssl/lhash.h +e_capi.o: ../include/openssl/obj_mac.h ../include/openssl/objects.h +e_capi.o: ../include/openssl/opensslconf.h ../include/openssl/opensslv.h +e_capi.o: ../include/openssl/ossl_typ.h ../include/openssl/pkcs7.h +e_capi.o: ../include/openssl/safestack.h ../include/openssl/sha.h +e_capi.o: ../include/openssl/stack.h ../include/openssl/symhacks.h +e_capi.o: ../include/openssl/x509.h ../include/openssl/x509_vfy.h e_capi.c +e_chil.o: ../include/openssl/asn1.h ../include/openssl/bio.h +e_chil.o: ../include/openssl/bn.h ../include/openssl/buffer.h +e_chil.o: ../include/openssl/crypto.h ../include/openssl/dh.h +e_chil.o: ../include/openssl/dso.h ../include/openssl/e_os2.h +e_chil.o: ../include/openssl/ec.h ../include/openssl/ecdh.h +e_chil.o: ../include/openssl/ecdsa.h ../include/openssl/engine.h +e_chil.o: ../include/openssl/err.h ../include/openssl/evp.h +e_chil.o: ../include/openssl/lhash.h ../include/openssl/obj_mac.h +e_chil.o: ../include/openssl/objects.h ../include/openssl/opensslconf.h +e_chil.o: ../include/openssl/opensslv.h ../include/openssl/ossl_typ.h +e_chil.o: ../include/openssl/pem.h ../include/openssl/pem2.h +e_chil.o: ../include/openssl/pkcs7.h ../include/openssl/rand.h +e_chil.o: ../include/openssl/rsa.h ../include/openssl/safestack.h +e_chil.o: ../include/openssl/sha.h ../include/openssl/stack.h +e_chil.o: ../include/openssl/symhacks.h ../include/openssl/ui.h +e_chil.o: ../include/openssl/x509.h ../include/openssl/x509_vfy.h e_chil.c +e_chil.o: e_chil_err.c e_chil_err.h vendor_defns/hwcryptohook.h +e_cswift.o: ../include/openssl/asn1.h ../include/openssl/bio.h +e_cswift.o: ../include/openssl/bn.h ../include/openssl/buffer.h +e_cswift.o: ../include/openssl/crypto.h ../include/openssl/dh.h +e_cswift.o: ../include/openssl/dsa.h ../include/openssl/dso.h +e_cswift.o: ../include/openssl/e_os2.h ../include/openssl/ec.h +e_cswift.o: ../include/openssl/ecdh.h ../include/openssl/ecdsa.h +e_cswift.o: ../include/openssl/engine.h ../include/openssl/err.h +e_cswift.o: ../include/openssl/evp.h ../include/openssl/lhash.h +e_cswift.o: ../include/openssl/obj_mac.h ../include/openssl/objects.h +e_cswift.o: ../include/openssl/opensslconf.h ../include/openssl/opensslv.h +e_cswift.o: ../include/openssl/ossl_typ.h ../include/openssl/pkcs7.h +e_cswift.o: ../include/openssl/rand.h ../include/openssl/rsa.h +e_cswift.o: ../include/openssl/safestack.h ../include/openssl/sha.h +e_cswift.o: ../include/openssl/stack.h ../include/openssl/symhacks.h +e_cswift.o: ../include/openssl/x509.h ../include/openssl/x509_vfy.h e_cswift.c +e_cswift.o: e_cswift_err.c e_cswift_err.h vendor_defns/cswift.h +e_gmp.o: ../include/openssl/asn1.h ../include/openssl/bio.h +e_gmp.o: ../include/openssl/bn.h ../include/openssl/buffer.h +e_gmp.o: ../include/openssl/crypto.h ../include/openssl/e_os2.h +e_gmp.o: ../include/openssl/ec.h ../include/openssl/ecdh.h +e_gmp.o: ../include/openssl/ecdsa.h ../include/openssl/engine.h +e_gmp.o: ../include/openssl/evp.h ../include/openssl/lhash.h +e_gmp.o: ../include/openssl/obj_mac.h ../include/openssl/objects.h +e_gmp.o: ../include/openssl/opensslconf.h ../include/openssl/opensslv.h +e_gmp.o: ../include/openssl/ossl_typ.h ../include/openssl/pkcs7.h +e_gmp.o: ../include/openssl/rsa.h ../include/openssl/safestack.h +e_gmp.o: ../include/openssl/sha.h ../include/openssl/stack.h +e_gmp.o: ../include/openssl/symhacks.h ../include/openssl/x509.h +e_gmp.o: ../include/openssl/x509_vfy.h e_gmp.c +e_nuron.o: ../include/openssl/asn1.h ../include/openssl/bio.h +e_nuron.o: ../include/openssl/bn.h ../include/openssl/buffer.h +e_nuron.o: ../include/openssl/crypto.h ../include/openssl/dh.h +e_nuron.o: ../include/openssl/dsa.h ../include/openssl/dso.h +e_nuron.o: ../include/openssl/e_os2.h ../include/openssl/ec.h +e_nuron.o: ../include/openssl/ecdh.h ../include/openssl/ecdsa.h +e_nuron.o: ../include/openssl/engine.h ../include/openssl/err.h +e_nuron.o: ../include/openssl/evp.h ../include/openssl/lhash.h +e_nuron.o: ../include/openssl/obj_mac.h ../include/openssl/objects.h +e_nuron.o: ../include/openssl/opensslconf.h ../include/openssl/opensslv.h +e_nuron.o: ../include/openssl/ossl_typ.h ../include/openssl/pkcs7.h +e_nuron.o: ../include/openssl/rsa.h ../include/openssl/safestack.h +e_nuron.o: ../include/openssl/sha.h ../include/openssl/stack.h +e_nuron.o: ../include/openssl/symhacks.h ../include/openssl/x509.h +e_nuron.o: ../include/openssl/x509_vfy.h e_nuron.c e_nuron_err.c e_nuron_err.h +e_padlock.o: ../include/openssl/aes.h ../include/openssl/asn1.h +e_padlock.o: ../include/openssl/bio.h ../include/openssl/buffer.h +e_padlock.o: ../include/openssl/crypto.h ../include/openssl/dso.h +e_padlock.o: ../include/openssl/e_os2.h ../include/openssl/ec.h +e_padlock.o: ../include/openssl/ecdh.h ../include/openssl/ecdsa.h +e_padlock.o: ../include/openssl/engine.h ../include/openssl/err.h +e_padlock.o: ../include/openssl/evp.h ../include/openssl/lhash.h +e_padlock.o: ../include/openssl/obj_mac.h ../include/openssl/objects.h +e_padlock.o: ../include/openssl/opensslconf.h ../include/openssl/opensslv.h +e_padlock.o: ../include/openssl/ossl_typ.h ../include/openssl/pkcs7.h +e_padlock.o: ../include/openssl/rand.h ../include/openssl/safestack.h +e_padlock.o: ../include/openssl/sha.h ../include/openssl/stack.h +e_padlock.o: ../include/openssl/symhacks.h ../include/openssl/x509.h +e_padlock.o: ../include/openssl/x509_vfy.h e_padlock.c +e_sureware.o: ../include/openssl/asn1.h ../include/openssl/bio.h +e_sureware.o: ../include/openssl/bn.h ../include/openssl/buffer.h +e_sureware.o: ../include/openssl/crypto.h ../include/openssl/dh.h +e_sureware.o: ../include/openssl/dsa.h ../include/openssl/dso.h +e_sureware.o: ../include/openssl/e_os2.h ../include/openssl/ec.h +e_sureware.o: ../include/openssl/ecdh.h ../include/openssl/ecdsa.h +e_sureware.o: ../include/openssl/engine.h ../include/openssl/err.h +e_sureware.o: ../include/openssl/evp.h ../include/openssl/lhash.h +e_sureware.o: ../include/openssl/obj_mac.h ../include/openssl/objects.h +e_sureware.o: ../include/openssl/opensslconf.h ../include/openssl/opensslv.h +e_sureware.o: ../include/openssl/ossl_typ.h ../include/openssl/pem.h +e_sureware.o: ../include/openssl/pem2.h ../include/openssl/pkcs7.h +e_sureware.o: ../include/openssl/rand.h ../include/openssl/rsa.h +e_sureware.o: ../include/openssl/safestack.h ../include/openssl/sha.h +e_sureware.o: ../include/openssl/stack.h ../include/openssl/symhacks.h +e_sureware.o: ../include/openssl/x509.h ../include/openssl/x509_vfy.h +e_sureware.o: e_sureware.c e_sureware_err.c e_sureware_err.h +e_sureware.o: vendor_defns/sureware.h +e_ubsec.o: ../include/openssl/asn1.h ../include/openssl/bio.h +e_ubsec.o: ../include/openssl/bn.h ../include/openssl/buffer.h +e_ubsec.o: ../include/openssl/crypto.h ../include/openssl/dh.h +e_ubsec.o: ../include/openssl/dsa.h ../include/openssl/dso.h +e_ubsec.o: ../include/openssl/e_os2.h ../include/openssl/ec.h +e_ubsec.o: ../include/openssl/ecdh.h ../include/openssl/ecdsa.h +e_ubsec.o: ../include/openssl/engine.h ../include/openssl/err.h +e_ubsec.o: ../include/openssl/evp.h ../include/openssl/lhash.h +e_ubsec.o: ../include/openssl/obj_mac.h ../include/openssl/objects.h +e_ubsec.o: ../include/openssl/opensslconf.h ../include/openssl/opensslv.h +e_ubsec.o: ../include/openssl/ossl_typ.h ../include/openssl/pkcs7.h +e_ubsec.o: ../include/openssl/rsa.h ../include/openssl/safestack.h +e_ubsec.o: ../include/openssl/sha.h ../include/openssl/stack.h +e_ubsec.o: ../include/openssl/symhacks.h ../include/openssl/x509.h +e_ubsec.o: ../include/openssl/x509_vfy.h e_ubsec.c e_ubsec_err.c e_ubsec_err.h +e_ubsec.o: vendor_defns/hw_ubsec.h diff --git a/node-v0.8.14/deps/openssl/openssl/engines/alpha.opt b/node-v0.8.14/deps/openssl/openssl/engines/alpha.opt new file mode 100644 index 0000000..1dc71bf --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/engines/alpha.opt @@ -0,0 +1 @@ +SYMBOL_VECTOR=(bind_engine=PROCEDURE,v_check=PROCEDURE) diff --git a/node-v0.8.14/deps/openssl/openssl/engines/axp.opt b/node-v0.8.14/deps/openssl/openssl/engines/axp.opt new file mode 100644 index 0000000..1dc71bf --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/engines/axp.opt @@ -0,0 +1 @@ +SYMBOL_VECTOR=(bind_engine=PROCEDURE,v_check=PROCEDURE) diff --git a/node-v0.8.14/deps/openssl/openssl/engines/capierr.bat b/node-v0.8.14/deps/openssl/openssl/engines/capierr.bat new file mode 100644 index 0000000..274ffac --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/engines/capierr.bat @@ -0,0 +1 @@ +perl ../util/mkerr.pl -conf e_capi.ec -nostatic -staticloader -write e_capi.c diff --git a/node-v0.8.14/deps/openssl/openssl/engines/ccgost/Makefile b/node-v0.8.14/deps/openssl/openssl/engines/ccgost/Makefile new file mode 100644 index 0000000..dadb523 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/engines/ccgost/Makefile @@ -0,0 +1,275 @@ +DIR=ccgost +TOP=../.. +CC=cc +INCLUDES= -I../../include +CFLAG=-g +MAKEFILE= Makefile +AR= ar r +CFLAGS= $(INCLUDES) $(CFLAG) +LIB=$(TOP)/libcrypto.a + +LIBSRC= gost2001.c gost2001_keyx.c gost89.c gost94_keyx.c gost_ameth.c gost_asn1.c gost_crypt.c gost_ctl.c gost_eng.c gosthash.c gost_keywrap.c gost_md.c gost_params.c gost_pmeth.c gost_sign.c + +LIBOBJ= e_gost_err.o gost2001_keyx.o gost2001.o gost89.o gost94_keyx.o gost_ameth.o gost_asn1.o gost_crypt.o gost_ctl.o gost_eng.o gosthash.o gost_keywrap.o gost_md.o gost_params.o gost_pmeth.o gost_sign.o + +SRC=$(LIBSRC) + +LIBNAME=gost + +top: + (cd $(TOP); $(MAKE) DIRS=engines EDIRS=$(DIR) sub_all) + +all: lib + +tags: + ctags $(SRC) + +errors: + $(PERL) ../../util/mkerr.pl -conf gost.ec -nostatic -write $(SRC) + +lib: $(LIBOBJ) + if [ -n "$(SHARED_LIBS)" ]; then \ + $(MAKE) -f $(TOP)/Makefile.shared -e \ + LIBNAME=$(LIBNAME) \ + LIBEXTRAS='$(LIBOBJ)' \ + LIBDEPS='-L$(TOP) -lcrypto' \ + link_o.$(SHLIB_TARGET); \ + else \ + $(AR) $(LIB) $(LIBOBJ); \ + fi + @touch lib + +install: + [ -n "$(INSTALLTOP)" ] # should be set by top Makefile... + if [ -n "$(SHARED_LIBS)" ]; then \ + set -e; \ + echo installing $(LIBNAME); \ + pfx=lib; \ + if [ "$(PLATFORM)" != "Cygwin" ]; then \ + case "$(CFLAGS)" in \ + *DSO_BEOS*) sfx=".so";; \ + *DSO_DLFCN*) sfx=`expr "$(SHLIB_EXT)" : '.*\(\.[a-z][a-z]*\)' \| ".so"`;; \ + *DSO_DL*) sfx=".sl";; \ + *DSO_WIN32*) sfx="eay32.dll"; pfx=;; \ + *) sfx=".bad";; \ + esac; \ + cp $${pfx}$(LIBNAME)$$sfx $(INSTALL_PREFIX)$(INSTALLTOP)/$(LIBDIR)/engines/$${pfx}$(LIBNAME)$$sfx.new; \ + else \ + sfx=".so"; \ + cp cyg$(LIBNAME).dll $(INSTALL_PREFIX)$(INSTALLTOP)/$(LIBDIR)/engines/$${pfx}$(LIBNAME)$$sfx.new; \ + fi; \ + chmod 555 $(INSTALL_PREFIX)$(INSTALLTOP)/$(LIBDIR)/engines/$${pfx}$(LIBNAME)$$sfx.new; \ + mv -f $(INSTALL_PREFIX)$(INSTALLTOP)/$(LIBDIR)/engines/$${pfx}$(LIBNAME)$$sfx.new $(INSTALL_PREFIX)$(INSTALLTOP)/$(LIBDIR)/engines/$${pfx}$(LIBNAME)$$sfx; \ + fi + +links: + +tests: + +depend: + @if [ -z "$(THIS)" ]; then \ + $(MAKE) -f $(TOP)/Makefile reflect THIS=$@; \ + else \ + $(MAKEDEPEND) -- $(CFLAG) $(INCLUDES) $(DEPFLAG) -- $(PROGS) $(LIBSRC); \ + fi + +files: + + + +lint: + lint -DLINT $(INCLUDES) $(SRC)>fluff + +dclean: + $(PERL) -pe 'if (/^# DO NOT DELETE THIS LINE/) {print; exit(0);}' $(MAKEFILE) >Makefile.new + mv -f Makefile.new $(MAKEFILE) + +clean: + rm -f *.o *.obj lib tags core .pure .nfs* *.old *.bak fluff *.so *.sl *.dll + +# DO NOT DELETE THIS LINE -- make depend depends on it. + +gost2001.o: ../../include/openssl/asn1.h ../../include/openssl/asn1t.h +gost2001.o: ../../include/openssl/bio.h ../../include/openssl/bn.h +gost2001.o: ../../include/openssl/buffer.h ../../include/openssl/crypto.h +gost2001.o: ../../include/openssl/dsa.h ../../include/openssl/e_os2.h +gost2001.o: ../../include/openssl/ec.h ../../include/openssl/ecdh.h +gost2001.o: ../../include/openssl/ecdsa.h ../../include/openssl/engine.h +gost2001.o: ../../include/openssl/err.h ../../include/openssl/evp.h +gost2001.o: ../../include/openssl/lhash.h ../../include/openssl/obj_mac.h +gost2001.o: ../../include/openssl/objects.h ../../include/openssl/opensslconf.h +gost2001.o: ../../include/openssl/opensslv.h ../../include/openssl/ossl_typ.h +gost2001.o: ../../include/openssl/pkcs7.h ../../include/openssl/rand.h +gost2001.o: ../../include/openssl/safestack.h ../../include/openssl/sha.h +gost2001.o: ../../include/openssl/stack.h ../../include/openssl/symhacks.h +gost2001.o: ../../include/openssl/x509.h ../../include/openssl/x509_vfy.h +gost2001.o: e_gost_err.h gost2001.c gost89.h gost_lcl.h gost_params.h +gost2001.o: gosthash.h +gost2001_keyx.o: ../../include/openssl/asn1.h ../../include/openssl/asn1t.h +gost2001_keyx.o: ../../include/openssl/bio.h ../../include/openssl/bn.h +gost2001_keyx.o: ../../include/openssl/buffer.h ../../include/openssl/crypto.h +gost2001_keyx.o: ../../include/openssl/dsa.h ../../include/openssl/e_os2.h +gost2001_keyx.o: ../../include/openssl/ec.h ../../include/openssl/ecdh.h +gost2001_keyx.o: ../../include/openssl/ecdsa.h ../../include/openssl/engine.h +gost2001_keyx.o: ../../include/openssl/evp.h ../../include/openssl/lhash.h +gost2001_keyx.o: ../../include/openssl/obj_mac.h +gost2001_keyx.o: ../../include/openssl/objects.h +gost2001_keyx.o: ../../include/openssl/opensslconf.h +gost2001_keyx.o: ../../include/openssl/opensslv.h +gost2001_keyx.o: ../../include/openssl/ossl_typ.h ../../include/openssl/pkcs7.h +gost2001_keyx.o: ../../include/openssl/rand.h ../../include/openssl/safestack.h +gost2001_keyx.o: ../../include/openssl/sha.h ../../include/openssl/stack.h +gost2001_keyx.o: ../../include/openssl/symhacks.h ../../include/openssl/x509.h +gost2001_keyx.o: ../../include/openssl/x509_vfy.h e_gost_err.h gost2001_keyx.c +gost2001_keyx.o: gost2001_keyx.h gost89.h gost_keywrap.h gost_lcl.h gosthash.h +gost89.o: gost89.c gost89.h +gost94_keyx.o: ../../include/openssl/asn1.h ../../include/openssl/asn1t.h +gost94_keyx.o: ../../include/openssl/bio.h ../../include/openssl/bn.h +gost94_keyx.o: ../../include/openssl/buffer.h ../../include/openssl/crypto.h +gost94_keyx.o: ../../include/openssl/dh.h ../../include/openssl/dsa.h +gost94_keyx.o: ../../include/openssl/e_os2.h ../../include/openssl/ec.h +gost94_keyx.o: ../../include/openssl/ecdh.h ../../include/openssl/ecdsa.h +gost94_keyx.o: ../../include/openssl/engine.h ../../include/openssl/evp.h +gost94_keyx.o: ../../include/openssl/lhash.h ../../include/openssl/obj_mac.h +gost94_keyx.o: ../../include/openssl/objects.h +gost94_keyx.o: ../../include/openssl/opensslconf.h +gost94_keyx.o: ../../include/openssl/opensslv.h +gost94_keyx.o: ../../include/openssl/ossl_typ.h ../../include/openssl/pkcs7.h +gost94_keyx.o: ../../include/openssl/rand.h ../../include/openssl/safestack.h +gost94_keyx.o: ../../include/openssl/sha.h ../../include/openssl/stack.h +gost94_keyx.o: ../../include/openssl/symhacks.h ../../include/openssl/x509.h +gost94_keyx.o: ../../include/openssl/x509_vfy.h e_gost_err.h gost89.h +gost94_keyx.o: gost94_keyx.c gost_keywrap.h gost_lcl.h gosthash.h +gost_ameth.o: ../../include/openssl/asn1.h ../../include/openssl/asn1t.h +gost_ameth.o: ../../include/openssl/bio.h ../../include/openssl/bn.h +gost_ameth.o: ../../include/openssl/buffer.h ../../include/openssl/crypto.h +gost_ameth.o: ../../include/openssl/dsa.h ../../include/openssl/e_os2.h +gost_ameth.o: ../../include/openssl/ec.h ../../include/openssl/ecdh.h +gost_ameth.o: ../../include/openssl/ecdsa.h ../../include/openssl/engine.h +gost_ameth.o: ../../include/openssl/err.h ../../include/openssl/evp.h +gost_ameth.o: ../../include/openssl/lhash.h ../../include/openssl/obj_mac.h +gost_ameth.o: ../../include/openssl/objects.h +gost_ameth.o: ../../include/openssl/opensslconf.h +gost_ameth.o: ../../include/openssl/opensslv.h ../../include/openssl/ossl_typ.h +gost_ameth.o: ../../include/openssl/pkcs7.h ../../include/openssl/safestack.h +gost_ameth.o: ../../include/openssl/sha.h ../../include/openssl/stack.h +gost_ameth.o: ../../include/openssl/symhacks.h ../../include/openssl/x509.h +gost_ameth.o: ../../include/openssl/x509_vfy.h e_gost_err.h gost89.h +gost_ameth.o: gost_ameth.c gost_lcl.h gost_params.h gosthash.h +gost_asn1.o: ../../include/openssl/asn1.h ../../include/openssl/asn1t.h +gost_asn1.o: ../../include/openssl/bio.h ../../include/openssl/bn.h +gost_asn1.o: ../../include/openssl/buffer.h ../../include/openssl/crypto.h +gost_asn1.o: ../../include/openssl/dsa.h ../../include/openssl/e_os2.h +gost_asn1.o: ../../include/openssl/ec.h ../../include/openssl/ecdh.h +gost_asn1.o: ../../include/openssl/ecdsa.h ../../include/openssl/engine.h +gost_asn1.o: ../../include/openssl/evp.h ../../include/openssl/lhash.h +gost_asn1.o: ../../include/openssl/obj_mac.h ../../include/openssl/objects.h +gost_asn1.o: ../../include/openssl/opensslconf.h +gost_asn1.o: ../../include/openssl/opensslv.h ../../include/openssl/ossl_typ.h +gost_asn1.o: ../../include/openssl/pkcs7.h ../../include/openssl/safestack.h +gost_asn1.o: ../../include/openssl/sha.h ../../include/openssl/stack.h +gost_asn1.o: ../../include/openssl/symhacks.h ../../include/openssl/x509.h +gost_asn1.o: ../../include/openssl/x509_vfy.h gost89.h gost_asn1.c gost_lcl.h +gost_asn1.o: gosthash.h +gost_crypt.o: ../../include/openssl/asn1.h ../../include/openssl/asn1t.h +gost_crypt.o: ../../include/openssl/bio.h ../../include/openssl/bn.h +gost_crypt.o: ../../include/openssl/buffer.h ../../include/openssl/crypto.h +gost_crypt.o: ../../include/openssl/dsa.h ../../include/openssl/e_os2.h +gost_crypt.o: ../../include/openssl/ec.h ../../include/openssl/ecdh.h +gost_crypt.o: ../../include/openssl/ecdsa.h ../../include/openssl/engine.h +gost_crypt.o: ../../include/openssl/evp.h ../../include/openssl/lhash.h +gost_crypt.o: ../../include/openssl/obj_mac.h ../../include/openssl/objects.h +gost_crypt.o: ../../include/openssl/opensslconf.h +gost_crypt.o: ../../include/openssl/opensslv.h ../../include/openssl/ossl_typ.h +gost_crypt.o: ../../include/openssl/pkcs7.h ../../include/openssl/rand.h +gost_crypt.o: ../../include/openssl/safestack.h ../../include/openssl/sha.h +gost_crypt.o: ../../include/openssl/stack.h ../../include/openssl/symhacks.h +gost_crypt.o: ../../include/openssl/x509.h ../../include/openssl/x509_vfy.h +gost_crypt.o: e_gost_err.h gost89.h gost_crypt.c gost_lcl.h gosthash.h +gost_ctl.o: ../../include/openssl/asn1.h ../../include/openssl/asn1t.h +gost_ctl.o: ../../include/openssl/bio.h ../../include/openssl/bn.h +gost_ctl.o: ../../include/openssl/buffer.h ../../include/openssl/crypto.h +gost_ctl.o: ../../include/openssl/dsa.h ../../include/openssl/e_os2.h +gost_ctl.o: ../../include/openssl/ec.h ../../include/openssl/ecdh.h +gost_ctl.o: ../../include/openssl/ecdsa.h ../../include/openssl/engine.h +gost_ctl.o: ../../include/openssl/err.h ../../include/openssl/evp.h +gost_ctl.o: ../../include/openssl/lhash.h ../../include/openssl/obj_mac.h +gost_ctl.o: ../../include/openssl/objects.h ../../include/openssl/opensslconf.h +gost_ctl.o: ../../include/openssl/opensslv.h ../../include/openssl/ossl_typ.h +gost_ctl.o: ../../include/openssl/pkcs7.h ../../include/openssl/safestack.h +gost_ctl.o: ../../include/openssl/sha.h ../../include/openssl/stack.h +gost_ctl.o: ../../include/openssl/symhacks.h ../../include/openssl/x509.h +gost_ctl.o: ../../include/openssl/x509_vfy.h gost89.h gost_ctl.c gost_lcl.h +gost_ctl.o: gosthash.h +gost_eng.o: ../../include/openssl/asn1.h ../../include/openssl/asn1t.h +gost_eng.o: ../../include/openssl/bio.h ../../include/openssl/bn.h +gost_eng.o: ../../include/openssl/buffer.h ../../include/openssl/crypto.h +gost_eng.o: ../../include/openssl/dsa.h ../../include/openssl/e_os2.h +gost_eng.o: ../../include/openssl/ec.h ../../include/openssl/ecdh.h +gost_eng.o: ../../include/openssl/ecdsa.h ../../include/openssl/engine.h +gost_eng.o: ../../include/openssl/err.h ../../include/openssl/evp.h +gost_eng.o: ../../include/openssl/lhash.h ../../include/openssl/obj_mac.h +gost_eng.o: ../../include/openssl/objects.h ../../include/openssl/opensslconf.h +gost_eng.o: ../../include/openssl/opensslv.h ../../include/openssl/ossl_typ.h +gost_eng.o: ../../include/openssl/pkcs7.h ../../include/openssl/safestack.h +gost_eng.o: ../../include/openssl/sha.h ../../include/openssl/stack.h +gost_eng.o: ../../include/openssl/symhacks.h ../../include/openssl/x509.h +gost_eng.o: ../../include/openssl/x509_vfy.h e_gost_err.h gost89.h gost_eng.c +gost_eng.o: gost_lcl.h gosthash.h +gost_keywrap.o: gost89.h gost_keywrap.c gost_keywrap.h +gost_md.o: ../../include/openssl/asn1.h ../../include/openssl/asn1t.h +gost_md.o: ../../include/openssl/bio.h ../../include/openssl/bn.h +gost_md.o: ../../include/openssl/buffer.h ../../include/openssl/crypto.h +gost_md.o: ../../include/openssl/dsa.h ../../include/openssl/e_os2.h +gost_md.o: ../../include/openssl/ec.h ../../include/openssl/ecdh.h +gost_md.o: ../../include/openssl/ecdsa.h ../../include/openssl/engine.h +gost_md.o: ../../include/openssl/evp.h ../../include/openssl/lhash.h +gost_md.o: ../../include/openssl/obj_mac.h ../../include/openssl/objects.h +gost_md.o: ../../include/openssl/opensslconf.h ../../include/openssl/opensslv.h +gost_md.o: ../../include/openssl/ossl_typ.h ../../include/openssl/pkcs7.h +gost_md.o: ../../include/openssl/safestack.h ../../include/openssl/sha.h +gost_md.o: ../../include/openssl/stack.h ../../include/openssl/symhacks.h +gost_md.o: ../../include/openssl/x509.h ../../include/openssl/x509_vfy.h +gost_md.o: e_gost_err.h gost89.h gost_lcl.h gost_md.c gosthash.h +gost_params.o: ../../include/openssl/asn1.h ../../include/openssl/bio.h +gost_params.o: ../../include/openssl/crypto.h ../../include/openssl/e_os2.h +gost_params.o: ../../include/openssl/obj_mac.h ../../include/openssl/objects.h +gost_params.o: ../../include/openssl/opensslconf.h +gost_params.o: ../../include/openssl/opensslv.h +gost_params.o: ../../include/openssl/ossl_typ.h +gost_params.o: ../../include/openssl/safestack.h ../../include/openssl/stack.h +gost_params.o: ../../include/openssl/symhacks.h gost_params.c gost_params.h +gost_pmeth.o: ../../include/openssl/asn1.h ../../include/openssl/asn1t.h +gost_pmeth.o: ../../include/openssl/bio.h ../../include/openssl/bn.h +gost_pmeth.o: ../../include/openssl/buffer.h ../../include/openssl/conf.h +gost_pmeth.o: ../../include/openssl/crypto.h ../../include/openssl/dsa.h +gost_pmeth.o: ../../include/openssl/e_os2.h ../../include/openssl/ec.h +gost_pmeth.o: ../../include/openssl/ecdh.h ../../include/openssl/ecdsa.h +gost_pmeth.o: ../../include/openssl/engine.h ../../include/openssl/evp.h +gost_pmeth.o: ../../include/openssl/lhash.h ../../include/openssl/obj_mac.h +gost_pmeth.o: ../../include/openssl/objects.h +gost_pmeth.o: ../../include/openssl/opensslconf.h +gost_pmeth.o: ../../include/openssl/opensslv.h ../../include/openssl/ossl_typ.h +gost_pmeth.o: ../../include/openssl/pkcs7.h ../../include/openssl/safestack.h +gost_pmeth.o: ../../include/openssl/sha.h ../../include/openssl/stack.h +gost_pmeth.o: ../../include/openssl/symhacks.h ../../include/openssl/x509.h +gost_pmeth.o: ../../include/openssl/x509_vfy.h ../../include/openssl/x509v3.h +gost_pmeth.o: e_gost_err.h gost89.h gost_lcl.h gost_params.h gost_pmeth.c +gost_pmeth.o: gosthash.h +gost_sign.o: ../../include/openssl/asn1.h ../../include/openssl/asn1t.h +gost_sign.o: ../../include/openssl/bio.h ../../include/openssl/bn.h +gost_sign.o: ../../include/openssl/buffer.h ../../include/openssl/crypto.h +gost_sign.o: ../../include/openssl/dsa.h ../../include/openssl/e_os2.h +gost_sign.o: ../../include/openssl/ec.h ../../include/openssl/ecdh.h +gost_sign.o: ../../include/openssl/ecdsa.h ../../include/openssl/engine.h +gost_sign.o: ../../include/openssl/evp.h ../../include/openssl/lhash.h +gost_sign.o: ../../include/openssl/obj_mac.h ../../include/openssl/objects.h +gost_sign.o: ../../include/openssl/opensslconf.h +gost_sign.o: ../../include/openssl/opensslv.h ../../include/openssl/ossl_typ.h +gost_sign.o: ../../include/openssl/pkcs7.h ../../include/openssl/rand.h +gost_sign.o: ../../include/openssl/safestack.h ../../include/openssl/sha.h +gost_sign.o: ../../include/openssl/stack.h ../../include/openssl/symhacks.h +gost_sign.o: ../../include/openssl/x509.h ../../include/openssl/x509_vfy.h +gost_sign.o: e_gost_err.h gost89.h gost_lcl.h gost_params.h gost_sign.c +gost_sign.o: gosthash.h +gosthash.o: gost89.h gosthash.c gosthash.h diff --git a/node-v0.8.14/deps/openssl/openssl/engines/ccgost/README.gost b/node-v0.8.14/deps/openssl/openssl/engines/ccgost/README.gost new file mode 100644 index 0000000..c96cccc --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/engines/ccgost/README.gost @@ -0,0 +1,300 @@ +GOST ENGINE + +This engine provides implementation of Russian cryptography standard. +This is also an example of adding new cryptoalgorithms into OpenSSL +without changing its core. If OpenSSL is compiled with dynamic engine +support, new algorithms can be added even without recompilation of +OpenSSL and applications which use it. + +ALGORITHMS SUPPORTED + +GOST R 34.10-94 and GOST R 34.10-2001 - digital signature algorithms. + Also support key exchange based on public keys. See RFC 4357 for + details of VKO key exchange algorithm. These algorithms use + 256 bit private keys. Public keys are 1024 bit for 94 and 512 bit for + 2001 (which is elliptic-curve based). Key exchange algorithms + (VKO R 34.10) are supported on these keys too. + +GOST R 34.11-94 Message digest algorithm. 256-bit hash value + +GOST 28147-89 - Symmetric cipher with 256-bit key. Various modes are + defined in the standard, but only CFB and CNT modes are implemented + in the engine. To make statistical analysis more difficult, key + meshing is supported (see RFC 4357). + +GOST 28147-89 MAC mode. Message authentication code. While most MAC + algorithms out there are based on hash functions using HMAC + algorithm, this algoritm is based on symmetric cipher. + It has 256-bit symmetric key and only 32 bits of MAC value + (while HMAC has same key size and value size). + + It is implemented as combination of EVP_PKEY type and EVP_MD type. + +USAGE OF THESE ALGORITHMS + +This engine is designed to allow usage of this algorithms in the +high-level openssl functions, such as PKI, S/MIME and TLS. + +See RFC 4490 for S/MIME with GOST algorithms and RFC 4491 for PKI. +TLS support is implemented according IETF +draft-chudov-cryptopro-cptls-03.txt and is compatible with +CryptoPro CSP 3.0 and 3.6 as well as with MagPro CSP. +GOST ciphersuites implemented in CryptoPro CSP 2.0 are not supported +because they use ciphersuite numbers used now by AES ciphersuites. + +To use the engine you have to load it via openssl configuration +file. Applications should read openssl configuration file or provide +their own means to load engines. Also, applications which operate with +private keys, should use generic EVP_PKEY API instead of using RSA or +other algorithm-specific API. + +CONFIGURATION FILE + +Configuration file should include following statement in the global +section, i.e. before first bracketed section header (see config(5) for details) + + openssl_conf = openssl_def + +where openssl_def is name of the section in configuration file which +describes global defaults. + +This section should contain following statement: + + [openssl_def] + engines = engine_section + +which points to the section which describes list of the engines to be +loaded. This section should contain: + + [engine_section] + gost = gost_section + +And section which describes configuration of the engine should contain + + [gost_section] + engine_id = gost + dynamic_path = /usr/lib/ssl/engines/libgost.so + default_algorithms = ALL + CRYPT_PARAMS = id-Gost28147-89-CryptoPro-A-ParamSet + +Where engine_id parameter specifies name of engine (should be "gost"). +dynamic_path is a location of the loadable shared library implementing the +engine. If the engine is compiled statically or is located in the OpenSSL +engines directory, this line can be omitted. +default_algorithms parameter specifies that all algorithms, provided by +engine, should be used. + +The CRYPT_PARAMS parameter is engine-specific. It allows the user to choose +between different parameter sets of symmetric cipher algorithm. RFC 4357 +specifies several parameters for the GOST 28147-89 algorithm, but OpenSSL +doesn't provide user interface to choose one when encrypting. So use engine +configuration parameter instead. + +Value of this parameter can be either short name, defined in OpenSSL +obj_dat.h header file or numeric representation of OID, defined in RFC +4357. + +USAGE WITH COMMAND LINE openssl UTILITY + +1. Generation of private key + + openssl genpkey -algorithm gost2001 -pkeyopt paramset:A -out seckey.pem + + Use -algorithm option to specify algorithm. + Use -pkeyopt option to pass paramset to algorithm. The following paramsets + are supported by + gost94: 0,A,B,C,D,XA,XB,XC + gost2001: 0,A,B,C,XA,XB + You can also use numeric representation of OID as to destinate + paramset. + + Paramsets starting with X are intended to use for key exchange keys. + Paramsets without X are for digital signature keys. + + Paramset for both algorithms 0 is the test paramset which should be used + only for test purposes. + +There are no algorithm-specific things with generation of certificate +request once you have a private key. + +2. Generation of certificate request along with private/public keypar + + openssl req -newkey gost2001 -pkeyopt paramset:A + + Syntax of -pkeyopt parameter is identical with genpkey command. + + You can also use oldstyle syntax -newkey gost2001:paramfile, but in + this case you should create parameter file first. + + It can be created with + + openssl genpkey -genparam -algorithm gost2001 -pkeyopt paramset:A\ + -out paramfile. + +3. S/MIME operations + +If you want to send encrypted mail using GOST algorithms, don't forget +to specify -gost89 as encryption algorithm for OpenSSL smime command. +While OpenSSL is clever enough to find out that GOST R 34.11-94 digest +must be used for digital signing with GOST private key, it have no way +to derive symmetric encryption algorithm from key exchange keys. + +4. TLS operations + +OpenSSL supports all four ciphersuites defined in the IETF draft. +Once you've loaded GOST key and certificate into your TLS server, +ciphersuites which use GOST 28147-89 encryption are enabled. + +Ciphersuites with NULL encryption should be enabled explicitely if +needed. + +GOST2001-GOST89-GOST89 Uses GOST R 34.10-2001 for auth and key exchange + GOST 28147-89 for encryption and GOST 28147-89 MAC +GOST94-GOST89-GOST89 Uses GOST R 34.10-94 for auth and key exchange + GOST 28147-89 for encryption and GOST 28147-89 MAC +GOST2001-NULL-GOST94 Uses GOST R 34.10-2001 for auth and key exchange, + no encryption and HMAC, based on GOST R 34.11-94 +GOST94-NULL-GOST94 Uses GOST R 34.10-94 for auth and key exchange, + no encryption and HMAC, based on GOST R 34.11-94 + +Gost 94 and gost 2001 keys can be used simultaneously in the TLS server. +RSA, DSA and EC keys can be used simultaneously with GOST keys, if +server implementation supports loading more than two private +key/certificate pairs. In this case ciphersuites which use any of loaded +keys would be supported and clients can negotiate ones they wish. + +This allows creation of TLS servers which use GOST ciphersuites for +Russian clients and RSA/DSA ciphersuites for foreign clients. + +5. Calculation of digests and symmetric encryption + OpenSSL provides specific commands (like sha1, aes etc) for calculation + of digests and symmetric encryption. Since such commands cannot be + added dynamically, no such commands are provided for GOST algorithms. + Use generic commands 'dgst' and 'enc'. + + Calculation of GOST R 34.11-94 message digest + + openssl dgst -md_gost94 datafile + + Note that GOST R 34.11-94 specifies that digest value should be + interpreted as little-endian number, but OpenSSL outputs just hex dump + of digest value. + + So, to obtain correct digest value, such as produced by gostsum utility + included in the engine distribution, bytes of output should be + reversed. + + Calculation of HMAC based on GOST R 34.11-94 + + openssl dgst -md_gost94 -mac hmac -macopt key:<32 bytes of key> datafile + + (or use hexkey if key contain NUL bytes) + Calculation of GOST 28147 MAC + + openssl dgst -mac gost-mac -macopt key:<32 bytes of key> datafile + + Note absense of an option that specifies digest algorithm. gost-mac + algorithm supports only one digest (which is actually part of + implementation of this mac) and OpenSSL is clever enough to find out + this. + + Encryption with GOST 28147 CFB mode + openssl enc -gost89 -out encrypted-file -in plain-text-file -k + Encryption with GOST 28147 CNT mode + openssl enc -gost89-cnt -out encrypted-file -in plain-text-file -k + + +6. Encrypting private keys and PKCS12 + +To produce PKCS12 files compatible with MagPro CSP, you need to use +GOST algorithm for encryption of PKCS12 file and also GOST R 34.11-94 +hash to derive key from password. + +openssl pksc12 -export -inkey gost.pem -in gost_cert.pem -keypbe gost89\ + -certpbe gost89 -macalg md_gost94 + +7. Testing speed of symmetric ciphers. + +To test performance of GOST symmetric ciphers you should use -evp switch +of the openssl speed command. Engine-provided ciphers couldn't be +accessed by cipher-specific functions, only via generic evp interface + + openssl speed -evp gost89 + openssl speed -evp gost89-cnt + + +PROGRAMMING INTERFACES DETAILS + +Applications never should access engine directly. They only use provided +EVP_PKEY API. But there are some details, which should be taken into +account. + +EVP provides two kinds of API for key exchange: + +1. EVP_PKEY_encrypt/EVP_PKEY_decrypt functions, intended to use with + RSA-like public key encryption algorithms + +2. EVP_PKEY_derive, intended to use with Diffie-Hellman-like shared key +computing algorithms. + +Although VKO R 34.10 algorithms, described in the RFC 4357 are +definitely second case, engine provides BOTH API for GOST R 34.10 keys. + +EVP_PKEY_derive just invokes appropriate VKO algorithm and computes +256 bit shared key. VKO R 34.10-2001 requires 64 bits of random user key +material (UKM). This UKM should be transmitted to other party, so it is +not generated inside derive function. + +It should be set by EVP_PKEY_CTX_ctrl function using +EVP_PKEY_CTRL_SET_IV command after call of EVP_PKEY_derive_init, but +before EVP_PKEY_derive. + unsigned char ukm[8]; + RAND_bytes(ukm,8); + EVP_PKEY_CTX_ctrl(ctx, -1, EVP_PKEY_OP_DERIVE, 8, ukm) + +EVP_PKEY_encrypt encrypts provided session key with VKO shared key and +packs it into GOST key transport structure, described in the RFC 4490. + +It typically uses ephemeral key pair to compute shared key and packs its +public part along with encrypted key. So, for most cases use of +EVP_PKEY_encrypt/EVP_PKEY_decrypt with GOST keys is almost same as with +RSA. + +However, if peerkey field in the EVP_PKEY_CTX structure is set (using +EVP_PKEY_derive_set_peerkey function) to EVP_PKEY structure which has private +key and uses same parameters as the public key from which this EVP_PKEY_CTX is +created, EVP_PKEY_encrypt will use this private key to compute shared key and +set ephemeral key in the GOST_key_transport structure to NULL. In this case +pkey and peerkey fields in the EVP_PKEY_CTX are used upside-down. + +If EVP_PKEY_decrypt encounters GOST_key_transport structure with NULL +public key field, it tries to use peerkey field from the context to +compute shared key. In this case peerkey field should really contain +peer public key. + +Encrypt operation supports EVP_PKEY_CTRL_SET_IV operation as well. +It can be used when some specific restriction on UKM are imposed by +higher level protocol. For instance, description of GOST ciphersuites +requires UKM to be derived from shared secret. + +If UKM is not set by this control command, encrypt operation would +generate random UKM. + + +This sources include implementation of GOST 28147-89 and GOST R 34.11-94 +which are completely indepentent from OpenSSL and can be used separately +(files gost89.c, gost89.h, gosthash.c, gosthash.h) Utility gostsum (file +gostsum.c) is provided as example of such separate usage. This is +program, simular to md5sum and sha1sum utilities, but calculates GOST R +34.11-94 hash. + +Makefile doesn't include rule for compiling gostsum. +Use command + +$(CC) -o gostsum gostsum.c gost89.c gosthash.c +where $(CC) is name of your C compiler. + +Implementations of GOST R 34.10-xx, including VKO algorithms heavily +depends on OpenSSL BIGNUM and Elliptic Curve libraries. + + diff --git a/node-v0.8.14/deps/openssl/openssl/engines/ccgost/e_gost_err.c b/node-v0.8.14/deps/openssl/openssl/engines/ccgost/e_gost_err.c new file mode 100644 index 0000000..9a79a37 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/engines/ccgost/e_gost_err.c @@ -0,0 +1,212 @@ +/* e_gost_err.c */ +/* ==================================================================== + * Copyright (c) 1999-2009 The OpenSSL Project. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. All advertising materials mentioning features or use of this + * software must display the following acknowledgment: + * "This product includes software developed by the OpenSSL Project + * for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)" + * + * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to + * endorse or promote products derived from this software without + * prior written permission. For written permission, please contact + * openssl-core@OpenSSL.org. + * + * 5. Products derived from this software may not be called "OpenSSL" + * nor may "OpenSSL" appear in their names without prior written + * permission of the OpenSSL Project. + * + * 6. Redistributions of any form whatsoever must retain the following + * acknowledgment: + * "This product includes software developed by the OpenSSL Project + * for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)" + * + * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY + * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR + * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, + * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * ==================================================================== + * + * This product includes cryptographic software written by Eric Young + * (eay@cryptsoft.com). This product includes software written by Tim + * Hudson (tjh@cryptsoft.com). + * + */ + +/* NOTE: this file was auto generated by the mkerr.pl script: any changes + * made to it will be overwritten when the script next updates this file, + * only reason strings will be preserved. + */ + +#include +#include +#include "e_gost_err.h" + +/* BEGIN ERROR CODES */ +#ifndef OPENSSL_NO_ERR + +#define ERR_FUNC(func) ERR_PACK(0,func,0) +#define ERR_REASON(reason) ERR_PACK(0,0,reason) + +static ERR_STRING_DATA GOST_str_functs[]= + { +{ERR_FUNC(GOST_F_DECODE_GOST_ALGOR_PARAMS), "DECODE_GOST_ALGOR_PARAMS"}, +{ERR_FUNC(GOST_F_ENCODE_GOST_ALGOR_PARAMS), "ENCODE_GOST_ALGOR_PARAMS"}, +{ERR_FUNC(GOST_F_FILL_GOST2001_PARAMS), "FILL_GOST2001_PARAMS"}, +{ERR_FUNC(GOST_F_FILL_GOST94_PARAMS), "FILL_GOST94_PARAMS"}, +{ERR_FUNC(GOST_F_GET_ENCRYPTION_PARAMS), "GET_ENCRYPTION_PARAMS"}, +{ERR_FUNC(GOST_F_GOST2001_COMPUTE_PUBLIC), "GOST2001_COMPUTE_PUBLIC"}, +{ERR_FUNC(GOST_F_GOST2001_DO_SIGN), "GOST2001_DO_SIGN"}, +{ERR_FUNC(GOST_F_GOST2001_DO_VERIFY), "GOST2001_DO_VERIFY"}, +{ERR_FUNC(GOST_F_GOST2001_KEYGEN), "GOST2001_KEYGEN"}, +{ERR_FUNC(GOST_F_GOST89_GET_ASN1_PARAMETERS), "GOST89_GET_ASN1_PARAMETERS"}, +{ERR_FUNC(GOST_F_GOST89_SET_ASN1_PARAMETERS), "GOST89_SET_ASN1_PARAMETERS"}, +{ERR_FUNC(GOST_F_GOST94_COMPUTE_PUBLIC), "GOST94_COMPUTE_PUBLIC"}, +{ERR_FUNC(GOST_F_GOST_CIPHER_CTL), "GOST_CIPHER_CTL"}, +{ERR_FUNC(GOST_F_GOST_DO_SIGN), "GOST_DO_SIGN"}, +{ERR_FUNC(GOST_F_GOST_DO_VERIFY), "GOST_DO_VERIFY"}, +{ERR_FUNC(GOST_F_GOST_IMIT_CTRL), "GOST_IMIT_CTRL"}, +{ERR_FUNC(GOST_F_GOST_IMIT_FINAL), "GOST_IMIT_FINAL"}, +{ERR_FUNC(GOST_F_GOST_IMIT_UPDATE), "GOST_IMIT_UPDATE"}, +{ERR_FUNC(GOST_F_PARAM_COPY_GOST01), "PARAM_COPY_GOST01"}, +{ERR_FUNC(GOST_F_PARAM_COPY_GOST94), "PARAM_COPY_GOST94"}, +{ERR_FUNC(GOST_F_PKEY_GOST01CP_DECRYPT), "PKEY_GOST01CP_DECRYPT"}, +{ERR_FUNC(GOST_F_PKEY_GOST01CP_ENCRYPT), "PKEY_GOST01CP_ENCRYPT"}, +{ERR_FUNC(GOST_F_PKEY_GOST01CP_KEYGEN), "PKEY_GOST01CP_KEYGEN"}, +{ERR_FUNC(GOST_F_PKEY_GOST01_PARAMGEN), "PKEY_GOST01_PARAMGEN"}, +{ERR_FUNC(GOST_F_PKEY_GOST2001_DERIVE), "PKEY_GOST2001_DERIVE"}, +{ERR_FUNC(GOST_F_PKEY_GOST94CP_DECRYPT), "PKEY_GOST94CP_DECRYPT"}, +{ERR_FUNC(GOST_F_PKEY_GOST94CP_ENCRYPT), "PKEY_GOST94CP_ENCRYPT"}, +{ERR_FUNC(GOST_F_PKEY_GOST94CP_KEYGEN), "PKEY_GOST94CP_KEYGEN"}, +{ERR_FUNC(GOST_F_PKEY_GOST94_PARAMGEN), "PKEY_GOST94_PARAMGEN"}, +{ERR_FUNC(GOST_F_PKEY_GOST_CTRL), "PKEY_GOST_CTRL"}, +{ERR_FUNC(GOST_F_PKEY_GOST_CTRL01_STR), "PKEY_GOST_CTRL01_STR"}, +{ERR_FUNC(GOST_F_PKEY_GOST_CTRL94_STR), "PKEY_GOST_CTRL94_STR"}, +{ERR_FUNC(GOST_F_PKEY_GOST_MAC_CTRL), "PKEY_GOST_MAC_CTRL"}, +{ERR_FUNC(GOST_F_PKEY_GOST_MAC_CTRL_STR), "PKEY_GOST_MAC_CTRL_STR"}, +{ERR_FUNC(GOST_F_PKEY_GOST_MAC_KEYGEN), "PKEY_GOST_MAC_KEYGEN"}, +{ERR_FUNC(GOST_F_PRINT_GOST_01), "PRINT_GOST_01"}, +{ERR_FUNC(GOST_F_PRIV_DECODE_GOST), "PRIV_DECODE_GOST"}, +{ERR_FUNC(GOST_F_PUB_DECODE_GOST01), "PUB_DECODE_GOST01"}, +{ERR_FUNC(GOST_F_PUB_DECODE_GOST94), "PUB_DECODE_GOST94"}, +{ERR_FUNC(GOST_F_PUB_ENCODE_GOST01), "PUB_ENCODE_GOST01"}, +{ERR_FUNC(GOST_F_UNPACK_CC_SIGNATURE), "UNPACK_CC_SIGNATURE"}, +{ERR_FUNC(GOST_F_UNPACK_CP_SIGNATURE), "UNPACK_CP_SIGNATURE"}, +{0,NULL} + }; + +static ERR_STRING_DATA GOST_str_reasons[]= + { +{ERR_REASON(GOST_R_BAD_KEY_PARAMETERS_FORMAT),"bad key parameters format"}, +{ERR_REASON(GOST_R_BAD_PKEY_PARAMETERS_FORMAT),"bad pkey parameters format"}, +{ERR_REASON(GOST_R_CANNOT_PACK_EPHEMERAL_KEY),"cannot pack ephemeral key"}, +{ERR_REASON(GOST_R_CTRL_CALL_FAILED) ,"ctrl call failed"}, +{ERR_REASON(GOST_R_ERROR_COMPUTING_SHARED_KEY),"error computing shared key"}, +{ERR_REASON(GOST_R_ERROR_PACKING_KEY_TRANSPORT_INFO),"error packing key transport info"}, +{ERR_REASON(GOST_R_ERROR_PARSING_KEY_TRANSPORT_INFO),"error parsing key transport info"}, +{ERR_REASON(GOST_R_INCOMPATIBLE_ALGORITHMS),"incompatible algorithms"}, +{ERR_REASON(GOST_R_INCOMPATIBLE_PEER_KEY),"incompatible peer key"}, +{ERR_REASON(GOST_R_INVALID_CIPHER_PARAMS),"invalid cipher params"}, +{ERR_REASON(GOST_R_INVALID_CIPHER_PARAM_OID),"invalid cipher param oid"}, +{ERR_REASON(GOST_R_INVALID_DIGEST_TYPE) ,"invalid digest type"}, +{ERR_REASON(GOST_R_INVALID_GOST94_PARMSET),"invalid gost94 parmset"}, +{ERR_REASON(GOST_R_INVALID_IV_LENGTH) ,"invalid iv length"}, +{ERR_REASON(GOST_R_INVALID_MAC_KEY_LENGTH),"invalid mac key length"}, +{ERR_REASON(GOST_R_INVALID_PARAMSET) ,"invalid paramset"}, +{ERR_REASON(GOST_R_KEY_IS_NOT_INITALIZED),"key is not initalized"}, +{ERR_REASON(GOST_R_KEY_IS_NOT_INITIALIZED),"key is not initialized"}, +{ERR_REASON(GOST_R_KEY_PARAMETERS_MISSING),"key parameters missing"}, +{ERR_REASON(GOST_R_MAC_KEY_NOT_SET) ,"mac key not set"}, +{ERR_REASON(GOST_R_MALLOC_FAILURE) ,"malloc failure"}, +{ERR_REASON(GOST_R_NO_MEMORY) ,"no memory"}, +{ERR_REASON(GOST_R_NO_PARAMETERS_SET) ,"no parameters set"}, +{ERR_REASON(GOST_R_NO_PEER_KEY) ,"no peer key"}, +{ERR_REASON(GOST_R_NO_PRIVATE_PART_OF_NON_EPHEMERAL_KEYPAIR),"no private part of non ephemeral keypair"}, +{ERR_REASON(GOST_R_PUBLIC_KEY_UNDEFINED) ,"public key undefined"}, +{ERR_REASON(GOST_R_RANDOM_GENERATOR_ERROR),"random generator error"}, +{ERR_REASON(GOST_R_RANDOM_GENERATOR_FAILURE),"random generator failure"}, +{ERR_REASON(GOST_R_RANDOM_NUMBER_GENERATOR_FAILED),"random number generator failed"}, +{ERR_REASON(GOST_R_SIGNATURE_MISMATCH) ,"signature mismatch"}, +{ERR_REASON(GOST_R_SIGNATURE_PARTS_GREATER_THAN_Q),"signature parts greater than q"}, +{ERR_REASON(GOST_R_UKM_NOT_SET) ,"ukm not set"}, +{ERR_REASON(GOST_R_UNSUPPORTED_CIPHER_CTL_COMMAND),"unsupported cipher ctl command"}, +{ERR_REASON(GOST_R_UNSUPPORTED_PARAMETER_SET),"unsupported parameter set"}, +{0,NULL} + }; + +#endif + +#ifdef GOST_LIB_NAME +static ERR_STRING_DATA GOST_lib_name[]= + { +{0 ,GOST_LIB_NAME}, +{0,NULL} + }; +#endif + + +static int GOST_lib_error_code=0; +static int GOST_error_init=1; + +void ERR_load_GOST_strings(void) + { + if (GOST_lib_error_code == 0) + GOST_lib_error_code=ERR_get_next_error_library(); + + if (GOST_error_init) + { + GOST_error_init=0; +#ifndef OPENSSL_NO_ERR + ERR_load_strings(GOST_lib_error_code,GOST_str_functs); + ERR_load_strings(GOST_lib_error_code,GOST_str_reasons); +#endif + +#ifdef GOST_LIB_NAME + GOST_lib_name->error = ERR_PACK(GOST_lib_error_code,0,0); + ERR_load_strings(0,GOST_lib_name); +#endif + } + } + +void ERR_unload_GOST_strings(void) + { + if (GOST_error_init == 0) + { +#ifndef OPENSSL_NO_ERR + ERR_unload_strings(GOST_lib_error_code,GOST_str_functs); + ERR_unload_strings(GOST_lib_error_code,GOST_str_reasons); +#endif + +#ifdef GOST_LIB_NAME + ERR_unload_strings(0,GOST_lib_name); +#endif + GOST_error_init=1; + } + } + +void ERR_GOST_error(int function, int reason, char *file, int line) + { + if (GOST_lib_error_code == 0) + GOST_lib_error_code=ERR_get_next_error_library(); + ERR_PUT_error(GOST_lib_error_code,function,reason,file,line); + } diff --git a/node-v0.8.14/deps/openssl/openssl/engines/ccgost/e_gost_err.h b/node-v0.8.14/deps/openssl/openssl/engines/ccgost/e_gost_err.h new file mode 100644 index 0000000..6dc5000 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/engines/ccgost/e_gost_err.h @@ -0,0 +1,156 @@ +/* ==================================================================== + * Copyright (c) 2001-2005 The OpenSSL Project. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. All advertising materials mentioning features or use of this + * software must display the following acknowledgment: + * "This product includes software developed by the OpenSSL Project + * for use in the OpenSSL Toolkit. (http://www.openssl.org/)" + * + * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to + * endorse or promote products derived from this software without + * prior written permission. For written permission, please contact + * openssl-core@openssl.org. + * + * 5. Products derived from this software may not be called "OpenSSL" + * nor may "OpenSSL" appear in their names without prior written + * permission of the OpenSSL Project. + * + * 6. Redistributions of any form whatsoever must retain the following + * acknowledgment: + * "This product includes software developed by the OpenSSL Project + * for use in the OpenSSL Toolkit (http://www.openssl.org/)" + * + * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY + * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR + * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, + * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * ==================================================================== + * + * This product includes cryptographic software written by Eric Young + * (eay@cryptsoft.com). This product includes software written by Tim + * Hudson (tjh@cryptsoft.com). + * + */ + +#ifndef HEADER_GOST_ERR_H +#define HEADER_GOST_ERR_H + +#ifdef __cplusplus +extern "C" { +#endif + +/* BEGIN ERROR CODES */ +/* The following lines are auto generated by the script mkerr.pl. Any changes + * made after this point may be overwritten when the script is next run. + */ +void ERR_load_GOST_strings(void); +void ERR_unload_GOST_strings(void); +void ERR_GOST_error(int function, int reason, char *file, int line); +#define GOSTerr(f,r) ERR_GOST_error((f),(r),__FILE__,__LINE__) + +/* Error codes for the GOST functions. */ + +/* Function codes. */ +#define GOST_F_DECODE_GOST_ALGOR_PARAMS 99 +#define GOST_F_ENCODE_GOST_ALGOR_PARAMS 100 +#define GOST_F_FILL_GOST2001_PARAMS 101 +#define GOST_F_FILL_GOST94_PARAMS 102 +#define GOST_F_GET_ENCRYPTION_PARAMS 103 +#define GOST_F_GOST2001_COMPUTE_PUBLIC 104 +#define GOST_F_GOST2001_DO_SIGN 105 +#define GOST_F_GOST2001_DO_VERIFY 106 +#define GOST_F_GOST2001_KEYGEN 107 +#define GOST_F_GOST89_GET_ASN1_PARAMETERS 108 +#define GOST_F_GOST89_SET_ASN1_PARAMETERS 109 +#define GOST_F_GOST94_COMPUTE_PUBLIC 110 +#define GOST_F_GOST_CIPHER_CTL 111 +#define GOST_F_GOST_DO_SIGN 112 +#define GOST_F_GOST_DO_VERIFY 113 +#define GOST_F_GOST_IMIT_CTRL 114 +#define GOST_F_GOST_IMIT_FINAL 140 +#define GOST_F_GOST_IMIT_UPDATE 115 +#define GOST_F_PARAM_COPY_GOST01 116 +#define GOST_F_PARAM_COPY_GOST94 117 +#define GOST_F_PKEY_GOST01CP_DECRYPT 118 +#define GOST_F_PKEY_GOST01CP_ENCRYPT 119 +#define GOST_F_PKEY_GOST01CP_KEYGEN 120 +#define GOST_F_PKEY_GOST01_PARAMGEN 138 +#define GOST_F_PKEY_GOST2001_DERIVE 121 +#define GOST_F_PKEY_GOST94CP_DECRYPT 122 +#define GOST_F_PKEY_GOST94CP_ENCRYPT 123 +#define GOST_F_PKEY_GOST94CP_KEYGEN 124 +#define GOST_F_PKEY_GOST94_PARAMGEN 139 +#define GOST_F_PKEY_GOST_CTRL 125 +#define GOST_F_PKEY_GOST_CTRL01_STR 126 +#define GOST_F_PKEY_GOST_CTRL94_STR 127 +#define GOST_F_PKEY_GOST_MAC_CTRL 128 +#define GOST_F_PKEY_GOST_MAC_CTRL_STR 129 +#define GOST_F_PKEY_GOST_MAC_KEYGEN 130 +#define GOST_F_PRINT_GOST_01 131 +#define GOST_F_PRIV_DECODE_GOST 132 +#define GOST_F_PUB_DECODE_GOST01 133 +#define GOST_F_PUB_DECODE_GOST94 134 +#define GOST_F_PUB_ENCODE_GOST01 135 +#define GOST_F_UNPACK_CC_SIGNATURE 136 +#define GOST_F_UNPACK_CP_SIGNATURE 137 + +/* Reason codes. */ +#define GOST_R_BAD_KEY_PARAMETERS_FORMAT 99 +#define GOST_R_BAD_PKEY_PARAMETERS_FORMAT 100 +#define GOST_R_CANNOT_PACK_EPHEMERAL_KEY 101 +#define GOST_R_CTRL_CALL_FAILED 132 +#define GOST_R_ERROR_COMPUTING_SHARED_KEY 102 +#define GOST_R_ERROR_PACKING_KEY_TRANSPORT_INFO 103 +#define GOST_R_ERROR_PARSING_KEY_TRANSPORT_INFO 104 +#define GOST_R_INCOMPATIBLE_ALGORITHMS 105 +#define GOST_R_INCOMPATIBLE_PEER_KEY 131 +#define GOST_R_INVALID_CIPHER_PARAMS 106 +#define GOST_R_INVALID_CIPHER_PARAM_OID 107 +#define GOST_R_INVALID_DIGEST_TYPE 108 +#define GOST_R_INVALID_GOST94_PARMSET 109 +#define GOST_R_INVALID_IV_LENGTH 110 +#define GOST_R_INVALID_MAC_KEY_LENGTH 111 +#define GOST_R_INVALID_PARAMSET 112 +#define GOST_R_KEY_IS_NOT_INITALIZED 113 +#define GOST_R_KEY_IS_NOT_INITIALIZED 114 +#define GOST_R_KEY_PARAMETERS_MISSING 115 +#define GOST_R_MAC_KEY_NOT_SET 116 +#define GOST_R_MALLOC_FAILURE 117 +#define GOST_R_NO_MEMORY 118 +#define GOST_R_NO_PARAMETERS_SET 119 +#define GOST_R_NO_PEER_KEY 120 +#define GOST_R_NO_PRIVATE_PART_OF_NON_EPHEMERAL_KEYPAIR 121 +#define GOST_R_PUBLIC_KEY_UNDEFINED 122 +#define GOST_R_RANDOM_GENERATOR_ERROR 123 +#define GOST_R_RANDOM_GENERATOR_FAILURE 124 +#define GOST_R_RANDOM_NUMBER_GENERATOR_FAILED 125 +#define GOST_R_SIGNATURE_MISMATCH 126 +#define GOST_R_SIGNATURE_PARTS_GREATER_THAN_Q 127 +#define GOST_R_UKM_NOT_SET 128 +#define GOST_R_UNSUPPORTED_CIPHER_CTL_COMMAND 129 +#define GOST_R_UNSUPPORTED_PARAMETER_SET 130 + +#ifdef __cplusplus +} +#endif +#endif diff --git a/node-v0.8.14/deps/openssl/openssl/engines/ccgost/e_gost_err.proto b/node-v0.8.14/deps/openssl/openssl/engines/ccgost/e_gost_err.proto new file mode 100644 index 0000000..c57bd1b --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/engines/ccgost/e_gost_err.proto @@ -0,0 +1,61 @@ +/* ==================================================================== + * Copyright (c) 2001-2005 The OpenSSL Project. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. All advertising materials mentioning features or use of this + * software must display the following acknowledgment: + * "This product includes software developed by the OpenSSL Project + * for use in the OpenSSL Toolkit. (http://www.openssl.org/)" + * + * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to + * endorse or promote products derived from this software without + * prior written permission. For written permission, please contact + * openssl-core@openssl.org. + * + * 5. Products derived from this software may not be called "OpenSSL" + * nor may "OpenSSL" appear in their names without prior written + * permission of the OpenSSL Project. + * + * 6. Redistributions of any form whatsoever must retain the following + * acknowledgment: + * "This product includes software developed by the OpenSSL Project + * for use in the OpenSSL Toolkit (http://www.openssl.org/)" + * + * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY + * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR + * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, + * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * ==================================================================== + * + * This product includes cryptographic software written by Eric Young + * (eay@cryptsoft.com). This product includes software written by Tim + * Hudson (tjh@cryptsoft.com). + * + */ + +#ifndef HEADER_GOST_ERR_H +#define HEADER_GOST_ERR_H + +#define GOST_LIB_NAME "GOST engine" +#ifdef __cplusplus + extern "C" { +#endif diff --git a/node-v0.8.14/deps/openssl/openssl/engines/ccgost/gost.ec b/node-v0.8.14/deps/openssl/openssl/engines/ccgost/gost.ec new file mode 100644 index 0000000..6c2c85e --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/engines/ccgost/gost.ec @@ -0,0 +1,5 @@ +L GOST e_gost_err.h e_gost_err.c +L NONE asymm.h NONE +L NONE md.h NONE +L NONE crypt.h NONE +L NONE gostkeyx.h NONE diff --git a/node-v0.8.14/deps/openssl/openssl/engines/ccgost/gost2001.c b/node-v0.8.14/deps/openssl/openssl/engines/ccgost/gost2001.c new file mode 100644 index 0000000..dacd82d --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/engines/ccgost/gost2001.c @@ -0,0 +1,343 @@ +/********************************************************************** + * gost2001.c * + * Copyright (c) 2005-2006 Cryptocom LTD * + * This file is distributed under the same license as OpenSSL * + * * + * Implementation of GOST R 34.10-2001 * + * Requires OpenSSL 0.9.9 for compilation * + **********************************************************************/ +#include "gost_lcl.h" +#include "gost_params.h" +#include +#include +#include +#include +#include "e_gost_err.h" +#ifdef DEBUG_SIGN +extern +void dump_signature(const char *message,const unsigned char *buffer,size_t len); +void dump_dsa_sig(const char *message, DSA_SIG *sig); +#else + +#define dump_signature(a,b,c) +#define dump_dsa_sig(a,b) +#endif + +/* + * Fills EC_KEY structure hidden in the app_data field of DSA structure + * with parameter information, extracted from parameter array in + * params.c file. + * + * Also fils DSA->q field with copy of EC_GROUP order field to make + * DSA_size function work + */ +int fill_GOST2001_params(EC_KEY *eckey, int nid) + { + R3410_2001_params *params = R3410_2001_paramset; + EC_GROUP *grp=NULL; + BIGNUM *p=NULL,*q=NULL,*a=NULL,*b=NULL,*x=NULL,*y=NULL; + EC_POINT *P=NULL; + BN_CTX *ctx=BN_CTX_new(); + int ok=0; + + BN_CTX_start(ctx); + p=BN_CTX_get(ctx); + a=BN_CTX_get(ctx); + b=BN_CTX_get(ctx); + x=BN_CTX_get(ctx); + y=BN_CTX_get(ctx); + q=BN_CTX_get(ctx); + while (params->nid!=NID_undef && params->nid != nid) params++; + if (params->nid == NID_undef) + { + GOSTerr(GOST_F_FILL_GOST2001_PARAMS,GOST_R_UNSUPPORTED_PARAMETER_SET); + goto err; + } + BN_hex2bn(&p,params->p); + BN_hex2bn(&a,params->a); + BN_hex2bn(&b,params->b); + + grp = EC_GROUP_new_curve_GFp(p,a,b,ctx); + + P = EC_POINT_new(grp); + + BN_hex2bn(&x,params->x); + BN_hex2bn(&y,params->y); + EC_POINT_set_affine_coordinates_GFp(grp,P,x,y,ctx); + BN_hex2bn(&q,params->q); +#ifdef DEBUG_KEYS + fprintf(stderr,"Set params index %d oid %s\nq=", + (params-R3410_2001_paramset),OBJ_nid2sn(params->nid)); + BN_print_fp(stderr,q); + fprintf(stderr,"\n"); +#endif + + EC_GROUP_set_generator(grp,P,q,NULL); + EC_GROUP_set_curve_name(grp,params->nid); + + EC_KEY_set_group(eckey,grp); + ok=1; + err: + EC_POINT_free(P); + EC_GROUP_free(grp); + BN_CTX_end(ctx); + BN_CTX_free(ctx); + return ok; + } + + +/* + * Computes gost2001 signature as DSA_SIG structure + * + * + */ +DSA_SIG *gost2001_do_sign(const unsigned char *dgst,int dlen, EC_KEY *eckey) + { + DSA_SIG *newsig = NULL; + BIGNUM *md = hashsum2bn(dgst); + BIGNUM *order = NULL; + const EC_GROUP *group; + const BIGNUM *priv_key; + BIGNUM *r=NULL,*s=NULL,*X=NULL,*tmp=NULL,*tmp2=NULL, *k=NULL,*e=NULL; + EC_POINT *C=NULL; + BN_CTX *ctx = BN_CTX_new(); + BN_CTX_start(ctx); + OPENSSL_assert(dlen==32); + newsig=DSA_SIG_new(); + if (!newsig) + { + GOSTerr(GOST_F_GOST2001_DO_SIGN,GOST_R_NO_MEMORY); + goto err; + } + group = EC_KEY_get0_group(eckey); + order=BN_CTX_get(ctx); + EC_GROUP_get_order(group,order,ctx); + priv_key = EC_KEY_get0_private_key(eckey); + e = BN_CTX_get(ctx); + BN_mod(e,md,order,ctx); +#ifdef DEBUG_SIGN + fprintf(stderr,"digest as bignum="); + BN_print_fp(stderr,md); + fprintf(stderr,"\ndigest mod q="); + BN_print_fp(stderr,e); + fprintf(stderr,"\n"); +#endif + if (BN_is_zero(e)) + { + BN_one(e); + } + k =BN_CTX_get(ctx); + C=EC_POINT_new(group); + do + { + do + { + if (!BN_rand_range(k,order)) + { + GOSTerr(GOST_F_GOST2001_DO_SIGN,GOST_R_RANDOM_NUMBER_GENERATOR_FAILED); + DSA_SIG_free(newsig); + newsig = NULL; + goto err; + } + if (!EC_POINT_mul(group,C,k,NULL,NULL,ctx)) + { + GOSTerr(GOST_F_GOST2001_DO_SIGN,ERR_R_EC_LIB); + DSA_SIG_free(newsig); + newsig = NULL; + goto err; + } + if (!X) X=BN_CTX_get(ctx); + if (!EC_POINT_get_affine_coordinates_GFp(group,C,X,NULL,ctx)) + { + GOSTerr(GOST_F_GOST2001_DO_SIGN,ERR_R_EC_LIB); + DSA_SIG_free(newsig); + newsig = NULL; + goto err; + } + if (!r) r=BN_CTX_get(ctx); + BN_nnmod(r,X,order,ctx); + } + while (BN_is_zero(r)); + /* s = (r*priv_key+k*e) mod order */ + if (!tmp) tmp = BN_CTX_get(ctx); + BN_mod_mul(tmp,priv_key,r,order,ctx); + if (!tmp2) tmp2 = BN_CTX_get(ctx); + BN_mod_mul(tmp2,k,e,order,ctx); + if (!s) s=BN_CTX_get(ctx); + BN_mod_add(s,tmp,tmp2,order,ctx); + } + while (BN_is_zero(s)); + + newsig->s=BN_dup(s); + newsig->r=BN_dup(r); + err: + BN_CTX_end(ctx); + BN_CTX_free(ctx); + EC_POINT_free(C); + BN_free(md); + return newsig; + } +/* + * Verifies gost 2001 signature + * + */ +int gost2001_do_verify(const unsigned char *dgst,int dgst_len, + DSA_SIG *sig, EC_KEY *ec) + { + BN_CTX *ctx=BN_CTX_new(); + const EC_GROUP *group = EC_KEY_get0_group(ec); + BIGNUM *order; + BIGNUM *md = NULL,*e=NULL,*R=NULL,*v=NULL,*z1=NULL,*z2=NULL; + BIGNUM *X=NULL,*tmp=NULL; + EC_POINT *C = NULL; + const EC_POINT *pub_key=NULL; + int ok=0; + + BN_CTX_start(ctx); + order = BN_CTX_get(ctx); + e = BN_CTX_get(ctx); + z1 = BN_CTX_get(ctx); + z2 = BN_CTX_get(ctx); + tmp = BN_CTX_get(ctx); + X= BN_CTX_get(ctx); + R=BN_CTX_get(ctx); + v=BN_CTX_get(ctx); + + EC_GROUP_get_order(group,order,ctx); + pub_key = EC_KEY_get0_public_key(ec); + if (BN_is_zero(sig->s) || BN_is_zero(sig->r) || + (BN_cmp(sig->s,order)>=1) || (BN_cmp(sig->r,order)>=1)) + { + GOSTerr(GOST_F_GOST2001_DO_VERIFY,GOST_R_SIGNATURE_PARTS_GREATER_THAN_Q); + goto err; + + } + md = hashsum2bn(dgst); + + BN_mod(e,md,order,ctx); +#ifdef DEBUG_SIGN + fprintf(stderr,"digest as bignum: "); + BN_print_fp(stderr,md); + fprintf(stderr,"\ndigest mod q: "); + BN_print_fp(stderr,e); +#endif + if (BN_is_zero(e)) BN_one(e); + v=BN_mod_inverse(v,e,order,ctx); + BN_mod_mul(z1,sig->s,v,order,ctx); + BN_sub(tmp,order,sig->r); + BN_mod_mul(z2,tmp,v,order,ctx); +#ifdef DEBUG_SIGN + fprintf(stderr,"\nInverted digest value: "); + BN_print_fp(stderr,v); + fprintf(stderr,"\nz1: "); + BN_print_fp(stderr,z1); + fprintf(stderr,"\nz2: "); + BN_print_fp(stderr,z2); +#endif + C = EC_POINT_new(group); + if (!EC_POINT_mul(group,C,z1,pub_key,z2,ctx)) + { + GOSTerr(GOST_F_GOST2001_DO_VERIFY,ERR_R_EC_LIB); + goto err; + } + if (!EC_POINT_get_affine_coordinates_GFp(group,C,X,NULL,ctx)) + { + GOSTerr(GOST_F_GOST2001_DO_VERIFY,ERR_R_EC_LIB); + goto err; + } + BN_mod(R,X,order,ctx); +#ifdef DEBUG_SIGN + fprintf(stderr,"\nX="); + BN_print_fp(stderr,X); + fprintf(stderr,"\nX mod q="); + BN_print_fp(stderr,R); + fprintf(stderr,"\n"); +#endif + if (BN_cmp(R,sig->r)!=0) + { + GOSTerr(GOST_F_GOST2001_DO_VERIFY,GOST_R_SIGNATURE_MISMATCH); + } + else + { + ok = 1; + } + err: + EC_POINT_free(C); + BN_CTX_end(ctx); + BN_CTX_free(ctx); + BN_free(md); + return ok; + } +/* + * Computes GOST R 34.10-2001 public key + * + * + */ +int gost2001_compute_public(EC_KEY *ec) + { + const EC_GROUP *group = EC_KEY_get0_group(ec); + EC_POINT *pub_key=NULL; + const BIGNUM *priv_key=NULL; + BN_CTX *ctx=NULL; + int ok=0; + + if (!group) + { + GOSTerr(GOST_F_GOST2001_COMPUTE_PUBLIC,GOST_R_KEY_IS_NOT_INITIALIZED); + return 0; + } + ctx=BN_CTX_new(); + BN_CTX_start(ctx); + if (!(priv_key=EC_KEY_get0_private_key(ec))) + { + GOSTerr(GOST_F_GOST2001_COMPUTE_PUBLIC,ERR_R_EC_LIB); + goto err; + } + + pub_key = EC_POINT_new(group); + if (!EC_POINT_mul(group,pub_key,priv_key,NULL,NULL,ctx)) + { + GOSTerr(GOST_F_GOST2001_COMPUTE_PUBLIC,ERR_R_EC_LIB); + goto err; + } + if (!EC_KEY_set_public_key(ec,pub_key)) + { + GOSTerr(GOST_F_GOST2001_COMPUTE_PUBLIC,ERR_R_EC_LIB); + goto err; + } + ok = 256; + err: + BN_CTX_end(ctx); + EC_POINT_free(pub_key); + BN_CTX_free(ctx); + return ok; + } +/* + * + * Generates GOST R 34.10-2001 keypair + * + * + */ +int gost2001_keygen(EC_KEY *ec) + { + BIGNUM *order = BN_new(),*d=BN_new(); + const EC_GROUP *group = EC_KEY_get0_group(ec); + EC_GROUP_get_order(group,order,NULL); + + do + { + if (!BN_rand_range(d,order)) + { + GOSTerr(GOST_F_GOST2001_KEYGEN,GOST_R_RANDOM_NUMBER_GENERATOR_FAILED); + BN_free(d); + BN_free(order); + return 0; + } + } + while (BN_is_zero(d)); + EC_KEY_set_private_key(ec,d); + BN_free(d); + BN_free(order); + return gost2001_compute_public(ec); + } + diff --git a/node-v0.8.14/deps/openssl/openssl/engines/ccgost/gost2001_keyx.c b/node-v0.8.14/deps/openssl/openssl/engines/ccgost/gost2001_keyx.c new file mode 100644 index 0000000..c748102 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/engines/ccgost/gost2001_keyx.c @@ -0,0 +1,308 @@ +/********************************************************************** + * gost_keyx.c * + * Copyright (c) 2005-2006 Cryptocom LTD * + * This file is distributed under the same license as OpenSSL * + * * + * VK0 34.10-2001 key exchange and GOST R 34.10-2001 * + * based PKCS7/SMIME support * + * Requires OpenSSL 0.9.9 for compilation * + **********************************************************************/ +#include +#include +#include +#include +#include "gost89.h" +#include "gosthash.h" +#include "e_gost_err.h" +#include "gost_keywrap.h" +#include "gost_lcl.h" +#include "gost2001_keyx.h" + + + +/* Implementation of CryptoPro VKO 34.10-2001 algorithm */ +static int VKO_compute_key(unsigned char *shared_key,size_t shared_key_size,const EC_POINT *pub_key,EC_KEY *priv_key,const unsigned char *ukm) + { + unsigned char ukm_be[8],databuf[64],hashbuf[64]; + BIGNUM *UKM=NULL,*p=NULL,*order=NULL,*X=NULL,*Y=NULL; + const BIGNUM* key=EC_KEY_get0_private_key(priv_key); + EC_POINT *pnt=EC_POINT_new(EC_KEY_get0_group(priv_key)); + int i; + gost_hash_ctx hash_ctx; + BN_CTX *ctx = BN_CTX_new(); + + for (i=0;i<8;i++) + { + ukm_be[7-i]=ukm[i]; + } + BN_CTX_start(ctx); + UKM=getbnfrombuf(ukm_be,8); + p=BN_CTX_get(ctx); + order = BN_CTX_get(ctx); + X=BN_CTX_get(ctx); + Y=BN_CTX_get(ctx); + EC_GROUP_get_order(EC_KEY_get0_group(priv_key),order,ctx); + BN_mod_mul(p,key,UKM,order,ctx); + EC_POINT_mul(EC_KEY_get0_group(priv_key),pnt,NULL,pub_key,p,ctx); + EC_POINT_get_affine_coordinates_GFp(EC_KEY_get0_group(priv_key), + pnt,X,Y,ctx); + /*Serialize elliptic curve point same way as we do it when saving + * key */ + store_bignum(Y,databuf,32); + store_bignum(X,databuf+32,32); + /* And reverse byte order of whole buffer */ + for (i=0;i<64;i++) + { + hashbuf[63-i]=databuf[i]; + } + init_gost_hash_ctx(&hash_ctx,&GostR3411_94_CryptoProParamSet); + start_hash(&hash_ctx); + hash_block(&hash_ctx,hashbuf,64); + finish_hash(&hash_ctx,shared_key); + done_gost_hash_ctx(&hash_ctx); + BN_free(UKM); + BN_CTX_end(ctx); + BN_CTX_free(ctx); + EC_POINT_free(pnt); + return 32; + } + + +/* + * EVP_PKEY_METHOD callback derive. Implements VKO R 34.10-2001 + * algorithm + */ +int pkey_gost2001_derive(EVP_PKEY_CTX *ctx, unsigned char *key, size_t *keylen) +{ + /* Public key of peer in the ctx field peerkey + * Our private key in the ctx pkey + * ukm is in the algorithm specific context data + */ + EVP_PKEY *my_key = EVP_PKEY_CTX_get0_pkey(ctx); + EVP_PKEY *peer_key = EVP_PKEY_CTX_get0_peerkey(ctx); + struct gost_pmeth_data *data = EVP_PKEY_CTX_get_data(ctx); + + if (!data->shared_ukm) { + GOSTerr(GOST_F_PKEY_GOST2001_DERIVE, GOST_R_UKM_NOT_SET); + return 0; + } + + if (key == NULL) { + *keylen = 32; + return 32; + } + + *keylen=VKO_compute_key(key, 32, EC_KEY_get0_public_key(EVP_PKEY_get0(peer_key)), + (EC_KEY *)EVP_PKEY_get0(my_key),data->shared_ukm); + return 1; +} + + + + +/* + * EVP_PKEY_METHOD callback encrypt + * Implementation of GOST2001 key transport, cryptocom variation + */ +/* Generates ephemeral key based on pubk algorithm + * computes shared key using VKO and returns filled up + * GOST_KEY_TRANSPORT structure + */ + +/* + * EVP_PKEY_METHOD callback encrypt + * Implementation of GOST2001 key transport, cryptopo variation + */ + +int pkey_GOST01cp_encrypt(EVP_PKEY_CTX *pctx, unsigned char *out, size_t *out_len, const unsigned char *key,size_t key_len) + { + GOST_KEY_TRANSPORT *gkt=NULL; + EVP_PKEY *pubk = EVP_PKEY_CTX_get0_pkey(pctx); + struct gost_pmeth_data *data = EVP_PKEY_CTX_get_data(pctx); + const struct gost_cipher_info *param=get_encryption_params(NULL); + unsigned char ukm[8], shared_key[32], crypted_key[44]; + int ret=0; + int key_is_ephemeral=1; + gost_ctx cctx; + EVP_PKEY *sec_key=EVP_PKEY_CTX_get0_peerkey(pctx); + if (data->shared_ukm) + { + memcpy(ukm, data->shared_ukm,8); + } + else if (out) + { + + if (RAND_bytes(ukm,8)<=0) + { + GOSTerr(GOST_F_PKEY_GOST01CP_ENCRYPT, + GOST_R_RANDOM_GENERATOR_FAILURE); + return 0; + } + } + /* Check for private key in the peer_key of context */ + if (sec_key) + { + key_is_ephemeral=0; + if (!gost_get0_priv_key(sec_key)) + { + GOSTerr(GOST_F_PKEY_GOST01CP_ENCRYPT, + GOST_R_NO_PRIVATE_PART_OF_NON_EPHEMERAL_KEYPAIR); + goto err; + } + } + else + { + key_is_ephemeral=1; + if (out) + { + sec_key = EVP_PKEY_new(); + EVP_PKEY_assign(sec_key,EVP_PKEY_base_id(pubk),EC_KEY_new()); + EVP_PKEY_copy_parameters(sec_key,pubk); + if (!gost2001_keygen(EVP_PKEY_get0(sec_key))) + { + goto err; + } + } + } + if (!get_gost_engine_param(GOST_PARAM_CRYPT_PARAMS) && param == gost_cipher_list) + { + param= gost_cipher_list+1; + } + if (out) + { + VKO_compute_key(shared_key,32,EC_KEY_get0_public_key(EVP_PKEY_get0(pubk)),EVP_PKEY_get0(sec_key),ukm); + gost_init(&cctx,param->sblock); + keyWrapCryptoPro(&cctx,shared_key,ukm,key,crypted_key); + } + gkt = GOST_KEY_TRANSPORT_new(); + if (!gkt) + { + goto err; + } + if(!ASN1_OCTET_STRING_set(gkt->key_agreement_info->eph_iv, + ukm,8)) + { + goto err; + } + if (!ASN1_OCTET_STRING_set(gkt->key_info->imit,crypted_key+40,4)) + { + goto err; + } + if (!ASN1_OCTET_STRING_set(gkt->key_info->encrypted_key,crypted_key+8,32)) + { + goto err; + } + if (key_is_ephemeral) { + if (!X509_PUBKEY_set(&gkt->key_agreement_info->ephem_key,out?sec_key:pubk)) + { + GOSTerr(GOST_F_PKEY_GOST01CP_ENCRYPT, + GOST_R_CANNOT_PACK_EPHEMERAL_KEY); + goto err; + } + } + ASN1_OBJECT_free(gkt->key_agreement_info->cipher); + gkt->key_agreement_info->cipher = OBJ_nid2obj(param->nid); + if (key_is_ephemeral && sec_key) EVP_PKEY_free(sec_key); + if (!key_is_ephemeral) + { + /* Set control "public key from client certificate used" */ + if (EVP_PKEY_CTX_ctrl(pctx, -1, -1, EVP_PKEY_CTRL_PEER_KEY, 3, NULL) <= 0) + { + GOSTerr(GOST_F_PKEY_GOST01CP_ENCRYPT, + GOST_R_CTRL_CALL_FAILED); + goto err; + } + } + if ((*out_len = i2d_GOST_KEY_TRANSPORT(gkt,out?&out:NULL))>0) ret =1; + GOST_KEY_TRANSPORT_free(gkt); + return ret; + err: + if (key_is_ephemeral && sec_key) EVP_PKEY_free(sec_key); + GOST_KEY_TRANSPORT_free(gkt); + return -1; + } +/* + * EVP_PKEY_METHOD callback decrypt + * Implementation of GOST2001 key transport, cryptopo variation + */ +int pkey_GOST01cp_decrypt(EVP_PKEY_CTX *pctx, unsigned char *key, size_t * key_len, const unsigned char *in, size_t in_len) + { + const unsigned char *p = in; + EVP_PKEY *priv = EVP_PKEY_CTX_get0_pkey(pctx); + GOST_KEY_TRANSPORT *gkt = NULL; + int ret=0; + unsigned char wrappedKey[44]; + unsigned char sharedKey[32]; + gost_ctx ctx; + const struct gost_cipher_info *param=NULL; + EVP_PKEY *eph_key=NULL, *peerkey=NULL; + + if (!key) + { + *key_len = 32; + return 1; + } + gkt = d2i_GOST_KEY_TRANSPORT(NULL,(const unsigned char **)&p, + in_len); + if (!gkt) + { + GOSTerr(GOST_F_PKEY_GOST01CP_DECRYPT,GOST_R_ERROR_PARSING_KEY_TRANSPORT_INFO); + return -1; + } + + /* If key transport structure contains public key, use it */ + eph_key = X509_PUBKEY_get(gkt->key_agreement_info->ephem_key); + if (eph_key) + { + if (EVP_PKEY_derive_set_peer(pctx, eph_key) <= 0) + { + GOSTerr(GOST_F_PKEY_GOST01CP_DECRYPT, + GOST_R_INCOMPATIBLE_PEER_KEY); + goto err; + } + } + else + { + /* Set control "public key from client certificate used" */ + if (EVP_PKEY_CTX_ctrl(pctx, -1, -1, EVP_PKEY_CTRL_PEER_KEY, 3, NULL) <= 0) + { + GOSTerr(GOST_F_PKEY_GOST01CP_DECRYPT, + GOST_R_CTRL_CALL_FAILED); + goto err; + } + } + peerkey = EVP_PKEY_CTX_get0_peerkey(pctx); + if (!peerkey) + { + GOSTerr(GOST_F_PKEY_GOST01CP_DECRYPT, + GOST_R_NO_PEER_KEY); + goto err; + } + + param = get_encryption_params(gkt->key_agreement_info->cipher); + if(!param){ + goto err; + } + + gost_init(&ctx,param->sblock); + OPENSSL_assert(gkt->key_agreement_info->eph_iv->length==8); + memcpy(wrappedKey,gkt->key_agreement_info->eph_iv->data,8); + OPENSSL_assert(gkt->key_info->encrypted_key->length==32); + memcpy(wrappedKey+8,gkt->key_info->encrypted_key->data,32); + OPENSSL_assert(gkt->key_info->imit->length==4); + memcpy(wrappedKey+40,gkt->key_info->imit->data,4); + VKO_compute_key(sharedKey,32,EC_KEY_get0_public_key(EVP_PKEY_get0(peerkey)), + EVP_PKEY_get0(priv),wrappedKey); + if (!keyUnwrapCryptoPro(&ctx,sharedKey,wrappedKey,key)) + { + GOSTerr(GOST_F_PKEY_GOST01CP_DECRYPT, + GOST_R_ERROR_COMPUTING_SHARED_KEY); + goto err; + } + + ret=1; +err: + if (eph_key) EVP_PKEY_free(eph_key); + if (gkt) GOST_KEY_TRANSPORT_free(gkt); + return ret; + } diff --git a/node-v0.8.14/deps/openssl/openssl/engines/ccgost/gost2001_keyx.h b/node-v0.8.14/deps/openssl/openssl/engines/ccgost/gost2001_keyx.h new file mode 100644 index 0000000..a014d9c --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/engines/ccgost/gost2001_keyx.h @@ -0,0 +1,10 @@ +GOST_KEY_TRANSPORT * +make_rfc4490_keytransport_2001(EVP_PKEY *pubk, BIGNUM *eph_key, + const unsigned char *key, size_t keylen, + unsigned char *ukm, size_t ukm_len); + +int decrypt_rfc4490_shared_key_2001(EVP_PKEY *priv, + GOST_KEY_TRANSPORT *gkt, + unsigned char *key_buf, + int key_buf_len) ; + diff --git a/node-v0.8.14/deps/openssl/openssl/engines/ccgost/gost89.c b/node-v0.8.14/deps/openssl/openssl/engines/ccgost/gost89.c new file mode 100644 index 0000000..7ebae0f --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/engines/ccgost/gost89.c @@ -0,0 +1,409 @@ +/********************************************************************** + * gost89.c * + * Copyright (c) 2005-2006 Cryptocom LTD * + * This file is distributed under the same license as OpenSSL * + * * + * Implementation of GOST 28147-89 encryption algorithm * + * No OpenSSL libraries required to compile and use * + * this code * + **********************************************************************/ +#include +#include "gost89.h" +/* Substitution blocks from RFC 4357 + + Note: our implementation of gost 28147-89 algorithm + uses S-box matrix rotated 90 degrees counterclockwise, relative to + examples given in RFC. + + +*/ + +/* Substitution blocks from test examples for GOST R 34.11-94*/ +gost_subst_block GostR3411_94_TestParamSet = { + {0X1,0XF,0XD,0X0,0X5,0X7,0XA,0X4,0X9,0X2,0X3,0XE,0X6,0XB,0X8,0XC}, + {0XD,0XB,0X4,0X1,0X3,0XF,0X5,0X9,0X0,0XA,0XE,0X7,0X6,0X8,0X2,0XC}, + {0X4,0XB,0XA,0X0,0X7,0X2,0X1,0XD,0X3,0X6,0X8,0X5,0X9,0XC,0XF,0XE}, + {0X6,0XC,0X7,0X1,0X5,0XF,0XD,0X8,0X4,0XA,0X9,0XE,0X0,0X3,0XB,0X2}, + {0X7,0XD,0XA,0X1,0X0,0X8,0X9,0XF,0XE,0X4,0X6,0XC,0XB,0X2,0X5,0X3}, + {0X5,0X8,0X1,0XD,0XA,0X3,0X4,0X2,0XE,0XF,0XC,0X7,0X6,0X0,0X9,0XB}, + {0XE,0XB,0X4,0XC,0X6,0XD,0XF,0XA,0X2,0X3,0X8,0X1,0X0,0X7,0X5,0X9}, + {0X4,0XA,0X9,0X2,0XD,0X8,0X0,0XE,0X6,0XB,0X1,0XC,0X7,0XF,0X5,0X3} + }; +/* Substitution blocks for hash function 1.2.643.2.9.1.6.1 */ +gost_subst_block GostR3411_94_CryptoProParamSet= { + {0x1,0x3,0xA,0x9,0x5,0xB,0x4,0xF,0x8,0x6,0x7,0xE,0xD,0x0,0x2,0xC}, + {0xD,0xE,0x4,0x1,0x7,0x0,0x5,0xA,0x3,0xC,0x8,0xF,0x6,0x2,0x9,0xB}, + {0x7,0x6,0x2,0x4,0xD,0x9,0xF,0x0,0xA,0x1,0x5,0xB,0x8,0xE,0xC,0x3}, + {0x7,0x6,0x4,0xB,0x9,0xC,0x2,0xA,0x1,0x8,0x0,0xE,0xF,0xD,0x3,0x5}, + {0x4,0xA,0x7,0xC,0x0,0xF,0x2,0x8,0xE,0x1,0x6,0x5,0xD,0xB,0x9,0x3}, + {0x7,0xF,0xC,0xE,0x9,0x4,0x1,0x0,0x3,0xB,0x5,0x2,0x6,0xA,0x8,0xD}, + {0x5,0xF,0x4,0x0,0x2,0xD,0xB,0x9,0x1,0x7,0x6,0x3,0xC,0xE,0xA,0x8}, + {0xA,0x4,0x5,0x6,0x8,0x1,0x3,0x7,0xD,0xC,0xE,0x0,0x9,0x2,0xB,0xF} + } ; + +/* Test paramset from GOST 28147 */ +gost_subst_block Gost28147_TestParamSet = + { + {0xC,0x6,0x5,0x2,0xB,0x0,0x9,0xD,0x3,0xE,0x7,0xA,0xF,0x4,0x1,0x8}, + {0x9,0xB,0xC,0x0,0x3,0x6,0x7,0x5,0x4,0x8,0xE,0xF,0x1,0xA,0x2,0xD}, + {0x8,0xF,0x6,0xB,0x1,0x9,0xC,0x5,0xD,0x3,0x7,0xA,0x0,0xE,0x2,0x4}, + {0x3,0xE,0x5,0x9,0x6,0x8,0x0,0xD,0xA,0xB,0x7,0xC,0x2,0x1,0xF,0x4}, + {0xE,0x9,0xB,0x2,0x5,0xF,0x7,0x1,0x0,0xD,0xC,0x6,0xA,0x4,0x3,0x8}, + {0xD,0x8,0xE,0xC,0x7,0x3,0x9,0xA,0x1,0x5,0x2,0x4,0x6,0xF,0x0,0xB}, + {0xC,0x9,0xF,0xE,0x8,0x1,0x3,0xA,0x2,0x7,0x4,0xD,0x6,0x0,0xB,0x5}, + {0x4,0x2,0xF,0x5,0x9,0x1,0x0,0x8,0xE,0x3,0xB,0xC,0xD,0x7,0xA,0x6} + }; + + + + +/* 1.2.643.2.2.31.1 */ +gost_subst_block Gost28147_CryptoProParamSetA= { + {0xB,0xA,0xF,0x5,0x0,0xC,0xE,0x8,0x6,0x2,0x3,0x9,0x1,0x7,0xD,0x4}, + {0x1,0xD,0x2,0x9,0x7,0xA,0x6,0x0,0x8,0xC,0x4,0x5,0xF,0x3,0xB,0xE}, + {0x3,0xA,0xD,0xC,0x1,0x2,0x0,0xB,0x7,0x5,0x9,0x4,0x8,0xF,0xE,0x6}, + {0xB,0x5,0x1,0x9,0x8,0xD,0xF,0x0,0xE,0x4,0x2,0x3,0xC,0x7,0xA,0x6}, + {0xE,0x7,0xA,0xC,0xD,0x1,0x3,0x9,0x0,0x2,0xB,0x4,0xF,0x8,0x5,0x6}, + {0xE,0x4,0x6,0x2,0xB,0x3,0xD,0x8,0xC,0xF,0x5,0xA,0x0,0x7,0x1,0x9}, + {0x3,0x7,0xE,0x9,0x8,0xA,0xF,0x0,0x5,0x2,0x6,0xC,0xB,0x4,0xD,0x1}, + {0x9,0x6,0x3,0x2,0x8,0xB,0x1,0x7,0xA,0x4,0xE,0xF,0xC,0x0,0xD,0x5} + }; +/* 1.2.643.2.2.31.2 */ +gost_subst_block Gost28147_CryptoProParamSetB= + { + {0x0,0x4,0xB,0xE,0x8,0x3,0x7,0x1,0xA,0x2,0x9,0x6,0xF,0xD,0x5,0xC}, + {0x5,0x2,0xA,0xB,0x9,0x1,0xC,0x3,0x7,0x4,0xD,0x0,0x6,0xF,0x8,0xE}, + {0x8,0x3,0x2,0x6,0x4,0xD,0xE,0xB,0xC,0x1,0x7,0xF,0xA,0x0,0x9,0x5}, + {0x2,0x7,0xC,0xF,0x9,0x5,0xA,0xB,0x1,0x4,0x0,0xD,0x6,0x8,0xE,0x3}, + {0x7,0x5,0x0,0xD,0xB,0x6,0x1,0x2,0x3,0xA,0xC,0xF,0x4,0xE,0x9,0x8}, + {0xE,0xC,0x0,0xA,0x9,0x2,0xD,0xB,0x7,0x5,0x8,0xF,0x3,0x6,0x1,0x4}, + {0x0,0x1,0x2,0xA,0x4,0xD,0x5,0xC,0x9,0x7,0x3,0xF,0xB,0x8,0x6,0xE}, + {0x8,0x4,0xB,0x1,0x3,0x5,0x0,0x9,0x2,0xE,0xA,0xC,0xD,0x6,0x7,0xF} + }; +/* 1.2.643.2.2.31.3 */ +gost_subst_block Gost28147_CryptoProParamSetC= + { + {0x7,0x4,0x0,0x5,0xA,0x2,0xF,0xE,0xC,0x6,0x1,0xB,0xD,0x9,0x3,0x8}, + {0xA,0x9,0x6,0x8,0xD,0xE,0x2,0x0,0xF,0x3,0x5,0xB,0x4,0x1,0xC,0x7}, + {0xC,0x9,0xB,0x1,0x8,0xE,0x2,0x4,0x7,0x3,0x6,0x5,0xA,0x0,0xF,0xD}, + {0x8,0xD,0xB,0x0,0x4,0x5,0x1,0x2,0x9,0x3,0xC,0xE,0x6,0xF,0xA,0x7}, + {0x3,0x6,0x0,0x1,0x5,0xD,0xA,0x8,0xB,0x2,0x9,0x7,0xE,0xF,0xC,0x4}, + {0x8,0x2,0x5,0x0,0x4,0x9,0xF,0xA,0x3,0x7,0xC,0xD,0x6,0xE,0x1,0xB}, + {0x0,0x1,0x7,0xD,0xB,0x4,0x5,0x2,0x8,0xE,0xF,0xC,0x9,0xA,0x6,0x3}, + {0x1,0xB,0xC,0x2,0x9,0xD,0x0,0xF,0x4,0x5,0x8,0xE,0xA,0x7,0x6,0x3} + }; + +/* 1.2.643.2.2.31.4 */ +gost_subst_block Gost28147_CryptoProParamSetD= + { + {0x1,0xA,0x6,0x8,0xF,0xB,0x0,0x4,0xC,0x3,0x5,0x9,0x7,0xD,0x2,0xE}, + {0x3,0x0,0x6,0xF,0x1,0xE,0x9,0x2,0xD,0x8,0xC,0x4,0xB,0xA,0x5,0x7}, + {0x8,0x0,0xF,0x3,0x2,0x5,0xE,0xB,0x1,0xA,0x4,0x7,0xC,0x9,0xD,0x6}, + {0x0,0xC,0x8,0x9,0xD,0x2,0xA,0xB,0x7,0x3,0x6,0x5,0x4,0xE,0xF,0x1}, + {0x1,0x5,0xE,0xC,0xA,0x7,0x0,0xD,0x6,0x2,0xB,0x4,0x9,0x3,0xF,0x8}, + {0x1,0xC,0xB,0x0,0xF,0xE,0x6,0x5,0xA,0xD,0x4,0x8,0x9,0x3,0x7,0x2}, + {0xB,0x6,0x3,0x4,0xC,0xF,0xE,0x2,0x7,0xD,0x8,0x0,0x5,0xA,0x9,0x1}, + {0xF,0xC,0x2,0xA,0x6,0x4,0x5,0x0,0x7,0x9,0xE,0xD,0x1,0xB,0x8,0x3} + }; + + +const byte CryptoProKeyMeshingKey[]={ + 0x69, 0x00, 0x72, 0x22, 0x64, 0xC9, 0x04, 0x23, + 0x8D, 0x3A, 0xDB, 0x96, 0x46, 0xE9, 0x2A, 0xC4, + 0x18, 0xFE, 0xAC, 0x94, 0x00, 0xED, 0x07, 0x12, + 0xC0, 0x86, 0xDC, 0xC2, 0xEF, 0x4C, 0xA9, 0x2B + }; +/* Initialization of gost_ctx subst blocks*/ +static void kboxinit(gost_ctx *c, const gost_subst_block *b) + { + int i; + + for (i = 0; i < 256; i++) + { + c->k87[i] = (b->k8[i>>4] <<4 | b->k7 [i &15])<<24; + c->k65[i] = (b->k6[i>>4] << 4 | b->k5 [i &15])<<16; + c->k43[i] = (b->k4[i>>4] <<4 | b->k3 [i &15])<<8; + c->k21[i] = b->k2[i>>4] <<4 | b->k1 [i &15]; + + } + } + +/* Part of GOST 28147 algorithm moved into separate function */ +static word32 f(gost_ctx *c,word32 x) + { + x = c->k87[x>>24 & 255] | c->k65[x>>16 & 255]| + c->k43[x>> 8 & 255] | c->k21[x & 255]; + /* Rotate left 11 bits */ + return x<<11 | x>>(32-11); + } +/* Low-level encryption routine - encrypts one 64 bit block*/ +void gostcrypt(gost_ctx *c, const byte *in, byte *out) + { + register word32 n1, n2; /* As named in the GOST */ + n1 = in[0]|(in[1]<<8)|(in[2]<<16)|(in[3]<<24); + n2 = in[4]|(in[5]<<8)|(in[6]<<16)|(in[7]<<24); + /* Instead of swapping halves, swap names each round */ + + n2 ^= f(c,n1+c->k[0]); n1 ^= f(c,n2+c->k[1]); + n2 ^= f(c,n1+c->k[2]); n1 ^= f(c,n2+c->k[3]); + n2 ^= f(c,n1+c->k[4]); n1 ^= f(c,n2+c->k[5]); + n2 ^= f(c,n1+c->k[6]); n1 ^= f(c,n2+c->k[7]); + + n2 ^= f(c,n1+c->k[0]); n1 ^= f(c,n2+c->k[1]); + n2 ^= f(c,n1+c->k[2]); n1 ^= f(c,n2+c->k[3]); + n2 ^= f(c,n1+c->k[4]); n1 ^= f(c,n2+c->k[5]); + n2 ^= f(c,n1+c->k[6]); n1 ^= f(c,n2+c->k[7]); + + n2 ^= f(c,n1+c->k[0]); n1 ^= f(c,n2+c->k[1]); + n2 ^= f(c,n1+c->k[2]); n1 ^= f(c,n2+c->k[3]); + n2 ^= f(c,n1+c->k[4]); n1 ^= f(c,n2+c->k[5]); + n2 ^= f(c,n1+c->k[6]); n1 ^= f(c,n2+c->k[7]); + + n2 ^= f(c,n1+c->k[7]); n1 ^= f(c,n2+c->k[6]); + n2 ^= f(c,n1+c->k[5]); n1 ^= f(c,n2+c->k[4]); + n2 ^= f(c,n1+c->k[3]); n1 ^= f(c,n2+c->k[2]); + n2 ^= f(c,n1+c->k[1]); n1 ^= f(c,n2+c->k[0]); + + out[0] = (byte)(n2&0xff); out[1] = (byte)((n2>>8)&0xff); + out[2] = (byte)((n2>>16)&0xff); out[3]=(byte)(n2>>24); + out[4] = (byte)(n1&0xff); out[5] = (byte)((n1>>8)&0xff); + out[6] = (byte)((n1>>16)&0xff); out[7] = (byte)(n1>>24); + } +/* Low-level decryption routine. Decrypts one 64-bit block */ +void gostdecrypt(gost_ctx *c, const byte *in,byte *out) + { + register word32 n1, n2; /* As named in the GOST */ + n1 = in[0]|(in[1]<<8)|(in[2]<<16)|(in[3]<<24); + n2 = in[4]|(in[5]<<8)|(in[6]<<16)|(in[7]<<24); + + n2 ^= f(c,n1+c->k[0]); n1 ^= f(c,n2+c->k[1]); + n2 ^= f(c,n1+c->k[2]); n1 ^= f(c,n2+c->k[3]); + n2 ^= f(c,n1+c->k[4]); n1 ^= f(c,n2+c->k[5]); + n2 ^= f(c,n1+c->k[6]); n1 ^= f(c,n2+c->k[7]); + + n2 ^= f(c,n1+c->k[7]); n1 ^= f(c,n2+c->k[6]); + n2 ^= f(c,n1+c->k[5]); n1 ^= f(c,n2+c->k[4]); + n2 ^= f(c,n1+c->k[3]); n1 ^= f(c,n2+c->k[2]); + n2 ^= f(c,n1+c->k[1]); n1 ^= f(c,n2+c->k[0]); + + n2 ^= f(c,n1+c->k[7]); n1 ^= f(c,n2+c->k[6]); + n2 ^= f(c,n1+c->k[5]); n1 ^= f(c,n2+c->k[4]); + n2 ^= f(c,n1+c->k[3]); n1 ^= f(c,n2+c->k[2]); + n2 ^= f(c,n1+c->k[1]); n1 ^= f(c,n2+c->k[0]); + + n2 ^= f(c,n1+c->k[7]); n1 ^= f(c,n2+c->k[6]); + n2 ^= f(c,n1+c->k[5]); n1 ^= f(c,n2+c->k[4]); + n2 ^= f(c,n1+c->k[3]); n1 ^= f(c,n2+c->k[2]); + n2 ^= f(c,n1+c->k[1]); n1 ^= f(c,n2+c->k[0]); + + out[0] = (byte)(n2&0xff); out[1] = (byte)((n2>>8)&0xff); + out[2] = (byte)((n2>>16)&0xff); out[3]=(byte)(n2>>24); + out[4] = (byte)(n1&0xff); out[5] = (byte)((n1>>8)&0xff); + out[6] = (byte)((n1>>16)&0xff); out[7] = (byte)(n1>>24); + } + +/* Encrypts several blocks in ECB mode */ +void gost_enc(gost_ctx *c,const byte *clear,byte *cipher, int blocks) + { + int i; + for(i=0;ik[i]=k[j]|(k[j+1]<<8)|(k[j+2]<<16)|(k[j+3]<<24); + } + } + +/* Retrieve 256-bit key from context */ +void gost_get_key(gost_ctx *c, byte *k) + { + int i,j; + for(i=0,j=0;i<8;i++,j+=4) + { + k[j]=(byte)(c->k[i]& 0xFF); + k[j+1]=(byte)((c->k[i]>>8 )&0xFF); + k[j+2]=(byte)((c->k[i]>>16) &0xFF); + k[j+3]=(byte)((c->k[i]>>24) &0xFF); + } + } + +/* Initalize context. Provides default value for subst_block */ +void gost_init(gost_ctx *c, const gost_subst_block *b) + { + if(!b) + { + b=&GostR3411_94_TestParamSet; + } + kboxinit(c,b); + } + +/* Cleans up key from context */ +void gost_destroy(gost_ctx *c) + { + int i; for(i=0;i<8;i++) c->k[i]=0; + } + +/* Compute GOST 28147 mac block + * + * Parameters + * gost_ctx *c - context initalized with substitution blocks and key + * buffer - 8-byte mac state buffer + * block 8-byte block to process. + * */ +void mac_block(gost_ctx *c,byte *buffer,const byte *block) + { + register word32 n1, n2; /* As named in the GOST */ + int i; + for (i=0; i<8; i++) + { + buffer[i]^=block[i]; + } + n1 = buffer[0]|(buffer[1]<<8)|(buffer[2]<<16)|(buffer[3]<<24); + n2 = buffer[4]|(buffer[5]<<8)|(buffer[6]<<16)|(buffer[7]<<24); + /* Instead of swapping halves, swap names each round */ + + n2 ^= f(c,n1+c->k[0]); n1 ^= f(c,n2+c->k[1]); + n2 ^= f(c,n1+c->k[2]); n1 ^= f(c,n2+c->k[3]); + n2 ^= f(c,n1+c->k[4]); n1 ^= f(c,n2+c->k[5]); + n2 ^= f(c,n1+c->k[6]); n1 ^= f(c,n2+c->k[7]); + + n2 ^= f(c,n1+c->k[0]); n1 ^= f(c,n2+c->k[1]); + n2 ^= f(c,n1+c->k[2]); n1 ^= f(c,n2+c->k[3]); + n2 ^= f(c,n1+c->k[4]); n1 ^= f(c,n2+c->k[5]); + n2 ^= f(c,n1+c->k[6]); n1 ^= f(c,n2+c->k[7]); + + buffer[0] = (byte)(n1&0xff); buffer[1] = (byte)((n1>>8)&0xff); + buffer[2] = (byte)((n1>>16)&0xff); buffer[3] = (byte)(n1>>24); + buffer[4] = (byte)(n2&0xff); buffer[5] = (byte)((n2>>8)&0xff); + buffer[6] = (byte)((n2>>16)&0xff); buffer[7] = (byte)(n2>>24); + } + +/* Get mac with specified number of bits from MAC state buffer */ +void get_mac(byte *buffer,int nbits,byte *out) + { + int nbytes= nbits >> 3; + int rembits = nbits & 7; + int mask =rembits?((1 2147483647L +typedef unsigned int u4; +#else +typedef unsigned long u4; +#endif +/* Typedef for unsigned 8-bit integer */ +typedef unsigned char byte; + +/* Internal representation of GOST substitution blocks */ +typedef struct { + byte k8[16]; + byte k7[16]; + byte k6[16]; + byte k5[16]; + byte k4[16]; + byte k3[16]; + byte k2[16]; + byte k1[16]; +} gost_subst_block; + + +/* Cipher context includes key and preprocessed substitution block */ +typedef struct { + u4 k[8]; + /* Constant s-boxes -- set up in gost_init(). */ + u4 k87[256],k65[256],k43[256],k21[256]; +} gost_ctx; +/* Note: encrypt and decrypt expect full blocks--padding blocks is + caller's responsibility. All bulk encryption is done in + ECB mode by these calls. Other modes may be added easily + enough. */ +/* Encrypt several full blocks in ECB mode */ +void gost_enc(gost_ctx *ctx, const byte *clear,byte *cipher, int blocks); +/* Decrypt several full blocks in ECB mode */ +void gost_dec(gost_ctx *ctx, const byte *cipher,byte *clear, int blocks); +/* Encrypts several full blocks in CFB mode using 8byte IV */ +void gost_enc_cfb(gost_ctx *ctx,const byte *iv,const byte *clear,byte *cipher,int blocks); +/* Decrypts several full blocks in CFB mode using 8byte IV */ +void gost_dec_cfb(gost_ctx *ctx,const byte *iv,const byte *cipher,byte *clear,int blocks); + +/* Encrypt one block */ +void gostcrypt(gost_ctx *c, const byte *in, byte *out); +/* Decrypt one block */ +void gostdecrypt(gost_ctx *c, const byte *in,byte *out); +/* Set key into context */ +void gost_key(gost_ctx *ctx, const byte *key); +/* Get key from context */ +void gost_get_key(gost_ctx *ctx, byte *key); +/* Set S-blocks into context */ +void gost_init(gost_ctx *ctx, const gost_subst_block *subst_block); +/* Clean up context */ +void gost_destroy(gost_ctx *ctx); +/* Intermediate function used for calculate hash */ +void gost_enc_with_key(gost_ctx *,byte *key,byte *inblock,byte *outblock); +/* Compute MAC of given length in bits from data */ +int gost_mac(gost_ctx *ctx,int hmac_len,const unsigned char *data, + unsigned int data_len,unsigned char *hmac) ; +/* Compute MAC of given length in bits from data, using non-zero 8-byte + * IV (non-standard, for use in CryptoPro key transport only */ +int gost_mac_iv(gost_ctx *ctx,int hmac_len,const unsigned char *iv,const unsigned char *data, + unsigned int data_len,unsigned char *hmac) ; +/* Perform one step of MAC calculation like gostcrypt */ +void mac_block(gost_ctx *c,byte *buffer,const byte *block); +/* Extracts MAC value from mac state buffer */ +void get_mac(byte *buffer,int nbits,byte *out); +/* Implements cryptopro key meshing algorithm. Expect IV to be 8-byte size*/ +void cryptopro_key_meshing(gost_ctx *ctx, unsigned char *iv); +/* Parameter sets specified in RFC 4357 */ +extern gost_subst_block GostR3411_94_TestParamSet; +extern gost_subst_block GostR3411_94_CryptoProParamSet; +extern gost_subst_block Gost28147_TestParamSet; +extern gost_subst_block Gost28147_CryptoProParamSetA; +extern gost_subst_block Gost28147_CryptoProParamSetB; +extern gost_subst_block Gost28147_CryptoProParamSetC; +extern gost_subst_block Gost28147_CryptoProParamSetD; +extern const byte CryptoProKeyMeshingKey[]; +#if __LONG_MAX__ > 2147483647L +typedef unsigned int word32; +#else +typedef unsigned long word32; +#endif + +#endif diff --git a/node-v0.8.14/deps/openssl/openssl/engines/ccgost/gost94_keyx.c b/node-v0.8.14/deps/openssl/openssl/engines/ccgost/gost94_keyx.c new file mode 100644 index 0000000..0d7d3ff --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/engines/ccgost/gost94_keyx.c @@ -0,0 +1,291 @@ +/********************************************************************** + * gost94_keyx.c * + * Copyright (c) 2005-2006 Cryptocom LTD * + * This file is distributed under the same license as OpenSSL * + * * + * Implements generation and parsing of GOST_KEY_TRANSPORT for * + * GOST R 34.10-94 algorithms * + * * + * Requires OpenSSL 0.9.9 for compilation * + **********************************************************************/ +#include +#include +#include +#include +#include + +#include "gost89.h" +#include "gosthash.h" +#include "e_gost_err.h" +#include "gost_keywrap.h" +#include "gost_lcl.h" +/* Common functions for both 94 and 2001 key exchange schemes */ +/* Implementation of the Diffi-Hellman key agreement scheme based on + * GOST-94 keys */ + +/* Computes Diffie-Hellman key and stores it into buffer in + * little-endian byte order as expected by both versions of GOST 94 + * algorithm + */ +static int compute_pair_key_le(unsigned char *pair_key,BIGNUM *pub_key,DH *dh) + { + unsigned char be_key[128]; + int i,key_size; + key_size=DH_compute_key(be_key,pub_key,dh); + if (!key_size) return 0; + memset(pair_key,0,128); + for (i=0;ig = BN_dup(pubk->pkey.dsa->g); + dh->p = BN_dup(pubk->pkey.dsa->p); + dh->priv_key = BN_dup(priv_key); + ret=compute_pair_key_le(dh_key,((DSA *)(EVP_PKEY_get0(pubk)))->pub_key,dh) ; + DH_free(dh); + if (!ret) return 0; + init_gost_hash_ctx(&hash_ctx,&GostR3411_94_CryptoProParamSet); + start_hash(&hash_ctx); + hash_block(&hash_ctx,dh_key,128); + finish_hash(&hash_ctx,shared_key); + done_gost_hash_ctx(&hash_ctx); + return 1; + } + +/* EVP_PKEY_METHOD callback derive. Implements VKO R 34.10-94 */ + +int pkey_gost94_derive(EVP_PKEY_CTX *ctx,unsigned char *key,size_t *keylen) + { + EVP_PKEY *pubk = EVP_PKEY_CTX_get0_peerkey(ctx); + EVP_PKEY *mykey = EVP_PKEY_CTX_get0_pkey(ctx); + *keylen = 32; + if (key == NULL) return 1; + + return make_cp_exchange_key(gost_get0_priv_key(mykey), pubk, key); + } + +/* EVP_PKEY_METHOD callback encrypt for + * GOST R 34.10-94 cryptopro modification + */ + + +int pkey_GOST94cp_encrypt(EVP_PKEY_CTX *ctx, unsigned char *out, size_t *outlen, const unsigned char* key, size_t key_len ) + { + GOST_KEY_TRANSPORT *gkt=NULL; + unsigned char shared_key[32], ukm[8],crypted_key[44]; + const struct gost_cipher_info *param=get_encryption_params(NULL); + EVP_PKEY *pubk = EVP_PKEY_CTX_get0_pkey(ctx); + struct gost_pmeth_data *data = EVP_PKEY_CTX_get_data(ctx); + gost_ctx cctx; + int key_is_ephemeral=1; + EVP_PKEY *mykey = EVP_PKEY_CTX_get0_peerkey(ctx); + + /* Do not use vizir cipher parameters with cryptopro */ + if (!get_gost_engine_param(GOST_PARAM_CRYPT_PARAMS) && param == gost_cipher_list) + { + param= gost_cipher_list+1; + } + + if (mykey) + { + /* If key already set, it is not ephemeral */ + key_is_ephemeral=0; + if (!gost_get0_priv_key(mykey)) + { + GOSTerr(GOST_F_PKEY_GOST94CP_ENCRYPT, + GOST_R_NO_PRIVATE_PART_OF_NON_EPHEMERAL_KEYPAIR); + goto err; + } + } + else + { + /* Otherwise generate ephemeral key */ + key_is_ephemeral = 1; + if (out) + { + mykey = EVP_PKEY_new(); + EVP_PKEY_assign(mykey, EVP_PKEY_base_id(pubk),DSA_new()); + EVP_PKEY_copy_parameters(mykey,pubk); + if (!gost_sign_keygen(EVP_PKEY_get0(mykey))) + { + goto err; + } + } + } + if (out) + make_cp_exchange_key(gost_get0_priv_key(mykey),pubk,shared_key); + if (data->shared_ukm) + { + memcpy(ukm,data->shared_ukm,8); + } + else if (out) + { + if (RAND_bytes(ukm,8)<=0) + { + GOSTerr(GOST_F_PKEY_GOST94CP_ENCRYPT, + GOST_R_RANDOM_GENERATOR_FAILURE); + goto err; + } + } + + if (out) { + gost_init(&cctx,param->sblock); + keyWrapCryptoPro(&cctx,shared_key,ukm,key,crypted_key); + } + gkt = GOST_KEY_TRANSPORT_new(); + if (!gkt) + { + goto memerr; + } + if(!ASN1_OCTET_STRING_set(gkt->key_agreement_info->eph_iv, + ukm,8)) + { + goto memerr; + } + if (!ASN1_OCTET_STRING_set(gkt->key_info->imit,crypted_key+40,4)) + { + goto memerr; + } + if (!ASN1_OCTET_STRING_set(gkt->key_info->encrypted_key,crypted_key+8,32)) + { + goto memerr; + } + if (key_is_ephemeral) { + if (!X509_PUBKEY_set(&gkt->key_agreement_info->ephem_key,out?mykey:pubk)) + { + GOSTerr(GOST_F_PKEY_GOST94CP_ENCRYPT,GOST_R_CANNOT_PACK_EPHEMERAL_KEY); + goto err; + } + if (out) EVP_PKEY_free(mykey); + } + ASN1_OBJECT_free(gkt->key_agreement_info->cipher); + gkt->key_agreement_info->cipher = OBJ_nid2obj(param->nid); + *outlen = i2d_GOST_KEY_TRANSPORT(gkt,out?&out:NULL); + if (*outlen <= 0) + { + GOSTerr(GOST_F_PKEY_GOST94CP_ENCRYPT,GOST_R_ERROR_PACKING_KEY_TRANSPORT_INFO); + goto err; + } + if (!key_is_ephemeral) + { + /* Set control "public key from client certificate used" */ + if (EVP_PKEY_CTX_ctrl(ctx, -1, -1, EVP_PKEY_CTRL_PEER_KEY, 3, NULL) <= 0) + { + GOSTerr(GOST_F_PKEY_GOST94CP_ENCRYPT, + GOST_R_CTRL_CALL_FAILED); + goto err; + } + } + GOST_KEY_TRANSPORT_free(gkt); + return 1; + memerr: + if (key_is_ephemeral) { + EVP_PKEY_free(mykey); + } + GOSTerr(GOST_F_PKEY_GOST94CP_ENCRYPT, + GOST_R_MALLOC_FAILURE); + err: + GOST_KEY_TRANSPORT_free(gkt); + return -1; + } + + +/* EVP_PLEY_METHOD callback decrypt for + * GOST R 34.10-94 cryptopro modification + */ +int pkey_GOST94cp_decrypt(EVP_PKEY_CTX *ctx, unsigned char *key, size_t *key_len,const unsigned char *in, size_t in_len) { + const unsigned char *p = in; + GOST_KEY_TRANSPORT *gkt = NULL; + unsigned char wrappedKey[44]; + unsigned char sharedKey[32]; + gost_ctx cctx; + const struct gost_cipher_info *param=NULL; + EVP_PKEY *eph_key=NULL, *peerkey=NULL; + EVP_PKEY *priv= EVP_PKEY_CTX_get0_pkey(ctx); + + if (!key) + { + *key_len = 32; + return 1; + } + + gkt = d2i_GOST_KEY_TRANSPORT(NULL,(const unsigned char **)&p, + in_len); + if (!gkt) + { + GOSTerr(GOST_F_PKEY_GOST94CP_DECRYPT,GOST_R_ERROR_PARSING_KEY_TRANSPORT_INFO); + return 0; + } + eph_key = X509_PUBKEY_get(gkt->key_agreement_info->ephem_key); + if (eph_key) + { + if (EVP_PKEY_derive_set_peer(ctx, eph_key) <= 0) + { + GOSTerr(GOST_F_PKEY_GOST94CP_DECRYPT, + GOST_R_INCOMPATIBLE_PEER_KEY); + goto err; + } + } + else + { + /* Set control "public key from client certificate used" */ + if (EVP_PKEY_CTX_ctrl(ctx, -1, -1, EVP_PKEY_CTRL_PEER_KEY, 3, NULL) <= 0) + { + GOSTerr(GOST_F_PKEY_GOST94CP_DECRYPT, + GOST_R_CTRL_CALL_FAILED); + goto err; + } + } + peerkey = EVP_PKEY_CTX_get0_peerkey(ctx); + if (!peerkey) + { + GOSTerr(GOST_F_PKEY_GOST94CP_DECRYPT, + GOST_R_NO_PEER_KEY); + goto err; + } + + param = get_encryption_params(gkt->key_agreement_info->cipher); + if(!param){ + goto err; + } + + gost_init(&cctx,param->sblock); + OPENSSL_assert(gkt->key_agreement_info->eph_iv->length==8); + memcpy(wrappedKey,gkt->key_agreement_info->eph_iv->data,8); + OPENSSL_assert(gkt->key_info->encrypted_key->length==32); + memcpy(wrappedKey+8,gkt->key_info->encrypted_key->data,32); + OPENSSL_assert(gkt->key_info->imit->length==4); + memcpy(wrappedKey+40,gkt->key_info->imit->data,4); + make_cp_exchange_key(gost_get0_priv_key(priv),peerkey,sharedKey); + if (!keyUnwrapCryptoPro(&cctx,sharedKey,wrappedKey,key)) + { + GOSTerr(GOST_F_PKEY_GOST94CP_DECRYPT, + GOST_R_ERROR_COMPUTING_SHARED_KEY); + goto err; + } + + EVP_PKEY_free(eph_key); + GOST_KEY_TRANSPORT_free(gkt); + return 1; +err: + EVP_PKEY_free(eph_key); + GOST_KEY_TRANSPORT_free(gkt); + return -1; + } + diff --git a/node-v0.8.14/deps/openssl/openssl/engines/ccgost/gost_ameth.c b/node-v0.8.14/deps/openssl/openssl/engines/ccgost/gost_ameth.c new file mode 100644 index 0000000..e6c2839 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/engines/ccgost/gost_ameth.c @@ -0,0 +1,908 @@ +/********************************************************************** + * gost_ameth.c * + * Copyright (c) 2005-2006 Cryptocom LTD * + * This file is distributed under the same license as OpenSSL * + * * + * Implementation of RFC 4490/4491 ASN1 method * + * for OpenSSL * + * Requires OpenSSL 0.9.9 for compilation * + **********************************************************************/ +#include +#include +#include +#include +#include +#include +#include "gost_params.h" +#include "gost_lcl.h" +#include "e_gost_err.h" + +int gost94_nid_by_params(DSA *p) + { + R3410_params *gost_params; + BIGNUM *q=BN_new(); + for (gost_params = R3410_paramset;gost_params->q!=NULL; gost_params++) + { + BN_dec2bn(&q,gost_params->q); + if (!BN_cmp(q,p->q)) + { + BN_free(q); + return gost_params->nid; + } + } + BN_free(q); + return NID_undef; + } + +static ASN1_STRING *encode_gost_algor_params(const EVP_PKEY *key) + { + ASN1_STRING *params = ASN1_STRING_new(); + GOST_KEY_PARAMS *gkp = GOST_KEY_PARAMS_new(); + int pkey_param_nid = NID_undef; + + if (!params || !gkp) + { + GOSTerr(GOST_F_ENCODE_GOST_ALGOR_PARAMS, + ERR_R_MALLOC_FAILURE); + ASN1_STRING_free(params); + params = NULL; + goto err; + } + switch (EVP_PKEY_base_id(key)) + { + case NID_id_GostR3410_2001: + pkey_param_nid = EC_GROUP_get_curve_name(EC_KEY_get0_group(EVP_PKEY_get0((EVP_PKEY *)key))); + break; + case NID_id_GostR3410_94: + pkey_param_nid = (int) gost94_nid_by_params(EVP_PKEY_get0((EVP_PKEY *)key)); + if (pkey_param_nid == NID_undef) + { + GOSTerr(GOST_F_ENCODE_GOST_ALGOR_PARAMS, + GOST_R_INVALID_GOST94_PARMSET); + ASN1_STRING_free(params); + params=NULL; + goto err; + } + break; + } + gkp->key_params = OBJ_nid2obj(pkey_param_nid); + gkp->hash_params = OBJ_nid2obj(NID_id_GostR3411_94_CryptoProParamSet); + /*gkp->cipher_params = OBJ_nid2obj(cipher_param_nid);*/ + params->length = i2d_GOST_KEY_PARAMS(gkp, ¶ms->data); + if (params->length <=0 ) + { + GOSTerr(GOST_F_ENCODE_GOST_ALGOR_PARAMS, + ERR_R_MALLOC_FAILURE); + ASN1_STRING_free(params); + params = NULL; + goto err; + } + params ->type = V_ASN1_SEQUENCE; + err: + GOST_KEY_PARAMS_free(gkp); + return params; + } + +/* Parses GOST algorithm parameters from X509_ALGOR and + * modifies pkey setting NID and parameters + */ +static int decode_gost_algor_params(EVP_PKEY *pkey, X509_ALGOR *palg) + { + ASN1_OBJECT *palg_obj =NULL; + int ptype = V_ASN1_UNDEF; + int pkey_nid = NID_undef,param_nid = NID_undef; + void *_pval; + ASN1_STRING *pval = NULL; + const unsigned char *p; + GOST_KEY_PARAMS *gkp = NULL; + + X509_ALGOR_get0(&palg_obj, &ptype, &_pval, palg); + pval = _pval; + if (ptype != V_ASN1_SEQUENCE) + { + GOSTerr(GOST_F_DECODE_GOST_ALGOR_PARAMS, + GOST_R_BAD_KEY_PARAMETERS_FORMAT); + return 0; + } + p=pval->data; + pkey_nid = OBJ_obj2nid(palg_obj); + + gkp = d2i_GOST_KEY_PARAMS(NULL,&p,pval->length); + if (!gkp) + { + GOSTerr(GOST_F_DECODE_GOST_ALGOR_PARAMS, + GOST_R_BAD_PKEY_PARAMETERS_FORMAT); + return 0; + } + param_nid = OBJ_obj2nid(gkp->key_params); + GOST_KEY_PARAMS_free(gkp); + EVP_PKEY_set_type(pkey,pkey_nid); + switch (pkey_nid) + { + case NID_id_GostR3410_94: + { + DSA *dsa= EVP_PKEY_get0(pkey); + if (!dsa) + { + dsa = DSA_new(); + if (!EVP_PKEY_assign(pkey,pkey_nid,dsa)) return 0; + } + if (!fill_GOST94_params(dsa,param_nid)) return 0; + break; + } + case NID_id_GostR3410_2001: + { + EC_KEY *ec = EVP_PKEY_get0(pkey); + if (!ec) + { + ec = EC_KEY_new(); + if (!EVP_PKEY_assign(pkey,pkey_nid,ec)) return 0; + } + if (!fill_GOST2001_params(ec,param_nid)) return 0; + } + } + + return 1; + } + +static int gost_set_priv_key(EVP_PKEY *pkey,BIGNUM *priv) + { + switch (EVP_PKEY_base_id(pkey)) + { + case NID_id_GostR3410_94: + { + DSA *dsa = EVP_PKEY_get0(pkey); + if (!dsa) + { + dsa = DSA_new(); + EVP_PKEY_assign(pkey,EVP_PKEY_base_id(pkey),dsa); + } + dsa->priv_key = BN_dup(priv); + if (!EVP_PKEY_missing_parameters(pkey)) + gost94_compute_public(dsa); + break; + } + case NID_id_GostR3410_2001: + { + EC_KEY *ec = EVP_PKEY_get0(pkey); + if (!ec) + { + ec = EC_KEY_new(); + EVP_PKEY_assign(pkey,EVP_PKEY_base_id(pkey),ec); + } + if (!EC_KEY_set_private_key(ec,priv)) return 0; + if (!EVP_PKEY_missing_parameters(pkey)) + gost2001_compute_public(ec); + break; + } + } + return 1; + } +BIGNUM* gost_get0_priv_key(const EVP_PKEY *pkey) + { + switch (EVP_PKEY_base_id(pkey)) + { + case NID_id_GostR3410_94: + { + DSA *dsa = EVP_PKEY_get0((EVP_PKEY *)pkey); + if (!dsa) + { + return NULL; + } + if (!dsa->priv_key) return NULL; + return dsa->priv_key; + break; + } + case NID_id_GostR3410_2001: + { + EC_KEY *ec = EVP_PKEY_get0((EVP_PKEY *)pkey); + const BIGNUM* priv; + if (!ec) + { + return NULL; + } + if (!(priv=EC_KEY_get0_private_key(ec))) return NULL; + return (BIGNUM *)priv; + break; + } + } + return NULL; + } + +static int pkey_ctrl_gost(EVP_PKEY *pkey, int op, + long arg1, void *arg2) + { + switch (op) + { + case ASN1_PKEY_CTRL_PKCS7_SIGN: + if (arg1 == 0) + { + X509_ALGOR *alg1 = NULL, *alg2 = NULL; + int nid = EVP_PKEY_base_id(pkey); + PKCS7_SIGNER_INFO_get0_algs((PKCS7_SIGNER_INFO*)arg2, + NULL, &alg1, &alg2); + X509_ALGOR_set0(alg1, OBJ_nid2obj(NID_id_GostR3411_94), + V_ASN1_NULL, 0); + if (nid == NID_undef) + { + return (-1); + } + X509_ALGOR_set0(alg2, OBJ_nid2obj(nid), V_ASN1_NULL, 0); + } + return 1; + case ASN1_PKEY_CTRL_PKCS7_ENCRYPT: + if (arg1 == 0) + { + X509_ALGOR *alg; + ASN1_STRING * params = encode_gost_algor_params(pkey); + if (!params) + { + return -1; + } + PKCS7_RECIP_INFO_get0_alg((PKCS7_RECIP_INFO*)arg2, &alg); + X509_ALGOR_set0(alg, OBJ_nid2obj(pkey->type), + V_ASN1_SEQUENCE, params); + } + return 1; + case ASN1_PKEY_CTRL_DEFAULT_MD_NID: + *(int *)arg2 = NID_id_GostR3411_94; + return 2; + } + + return -2; + } +/*----------------------- free functions * ------------------------------*/ +static void pkey_free_gost94(EVP_PKEY *key) + { + if (key->pkey.dsa) + { + DSA_free(key->pkey.dsa); + } + } + +static void pkey_free_gost01(EVP_PKEY *key) + { + if (key->pkey.ec) + { + EC_KEY_free(key->pkey.ec); + } + } + +/* ------------------ private key functions -----------------------------*/ +static int priv_decode_gost( EVP_PKEY *pk, PKCS8_PRIV_KEY_INFO *p8inf) + { + const unsigned char *pkey_buf = NULL,*p=NULL; + int priv_len = 0; + BIGNUM *pk_num=NULL; + int ret =0; + X509_ALGOR *palg =NULL; + ASN1_OBJECT *palg_obj = NULL; + ASN1_INTEGER *priv_key=NULL; + + if (!PKCS8_pkey_get0(&palg_obj,&pkey_buf,&priv_len,&palg,p8inf)) + return 0; + p = pkey_buf; + if (!decode_gost_algor_params(pk,palg)) + { + return 0; + } + if (V_ASN1_OCTET_STRING == *p) + { + /* New format - Little endian octet string */ + unsigned char rev_buf[32]; + int i; + ASN1_OCTET_STRING *s = d2i_ASN1_OCTET_STRING(NULL,&p,priv_len); + if (!s||s->length !=32) + { + GOSTerr(GOST_F_PRIV_DECODE_GOST, + EVP_R_DECODE_ERROR); + return 0; + } + for (i=0;i<32;i++) + { + rev_buf[31-i]=s->data[i]; + } + ASN1_STRING_free(s); + pk_num = getbnfrombuf(rev_buf,32); + } + else + { + priv_key=d2i_ASN1_INTEGER(NULL,&p,priv_len); + if (!priv_key) return 0; + ret= ((pk_num = ASN1_INTEGER_to_BN(priv_key, NULL))!=NULL) ; + ASN1_INTEGER_free(priv_key); + if (!ret) + { + GOSTerr(GOST_F_PRIV_DECODE_GOST, + EVP_R_DECODE_ERROR); + return 0; + } + } + + ret= gost_set_priv_key(pk,pk_num); + BN_free(pk_num); + return ret; + } + +/* ----------------------------------------------------------------------*/ +static int priv_encode_gost(PKCS8_PRIV_KEY_INFO *p8, const EVP_PKEY *pk) + { + ASN1_OBJECT *algobj = OBJ_nid2obj(EVP_PKEY_base_id(pk)); + ASN1_STRING *params = encode_gost_algor_params(pk); + unsigned char *priv_buf = NULL; + int priv_len; + + ASN1_INTEGER *asn1key=NULL; + if (!params) + { + return 0; + } + asn1key = BN_to_ASN1_INTEGER(gost_get0_priv_key(pk),NULL); + priv_len = i2d_ASN1_INTEGER(asn1key,&priv_buf); + ASN1_INTEGER_free(asn1key); + return PKCS8_pkey_set0(p8,algobj,0,V_ASN1_SEQUENCE,params, + priv_buf,priv_len); + } +/* --------- printing keys --------------------------------*/ +static int print_gost_94(BIO *out, const EVP_PKEY *pkey, int indent, + ASN1_PCTX *pctx, int type) + { + int param_nid = NID_undef; + + if (type == 2) + { + BIGNUM *key; + + if (!BIO_indent(out,indent,128)) return 0; + BIO_printf(out,"Private key: "); + key = gost_get0_priv_key(pkey); + if (!key) + BIO_printf(out,""); + else + BN_print(out,key); + BIO_printf(out,"\n"); + } + if (type >= 1) + { + BIGNUM *pubkey; + + pubkey = ((DSA *)EVP_PKEY_get0((EVP_PKEY *)pkey))->pub_key; + BIO_indent(out,indent,128); + BIO_printf(out,"Public key: "); + BN_print(out,pubkey); + BIO_printf(out,"\n"); + } + + param_nid = gost94_nid_by_params(EVP_PKEY_get0((EVP_PKEY *)pkey)); + BIO_indent(out,indent,128); + BIO_printf(out, "Parameter set: %s\n",OBJ_nid2ln(param_nid)); + return 1; +} + +static int param_print_gost94(BIO *out, const EVP_PKEY *pkey, int indent, + ASN1_PCTX *pctx) + { + return print_gost_94(out, pkey, indent, pctx,0); + } + +static int pub_print_gost94(BIO *out, const EVP_PKEY *pkey, int indent, + ASN1_PCTX *pctx) + { + return print_gost_94(out,pkey, indent, pctx,1); + } +static int priv_print_gost94(BIO *out,const EVP_PKEY *pkey, int indent, + ASN1_PCTX *pctx) + { + return print_gost_94(out,pkey,indent,pctx,2); + } + +static int print_gost_01(BIO *out, const EVP_PKEY *pkey, int indent, + ASN1_PCTX *pctx, int type) + { + int param_nid = NID_undef; + if (type == 2) + { + BIGNUM *key; + + if (!BIO_indent(out,indent,128)) return 0; + BIO_printf(out,"Private key: "); + key = gost_get0_priv_key(pkey); + if (!key) + BIO_printf(out,"= 1) + { + BN_CTX *ctx = BN_CTX_new(); + BIGNUM *X,*Y; + const EC_POINT *pubkey; + const EC_GROUP *group; + + if (!ctx) + { + GOSTerr(GOST_F_PRINT_GOST_01,ERR_R_MALLOC_FAILURE); + return 0; + } + BN_CTX_start(ctx); + X = BN_CTX_get(ctx); + Y = BN_CTX_get(ctx); + pubkey = EC_KEY_get0_public_key((EC_KEY *)EVP_PKEY_get0((EVP_PKEY *)pkey)); + group = EC_KEY_get0_group((EC_KEY *)EVP_PKEY_get0((EVP_PKEY *)pkey)); + if (!EC_POINT_get_affine_coordinates_GFp(group,pubkey,X,Y,ctx)) + { + GOSTerr(GOST_F_PRINT_GOST_01,ERR_R_EC_LIB); + BN_CTX_free(ctx); + return 0; + } + if (!BIO_indent(out,indent,128)) return 0; + BIO_printf(out,"Public key:\n"); + if (!BIO_indent(out,indent+3,128)) return 0; + BIO_printf(out,"X:"); + BN_print(out,X); + BIO_printf(out,"\n"); + BIO_indent(out,indent+3,128); + BIO_printf(out,"Y:"); + BN_print(out,Y); + BIO_printf(out,"\n"); + BN_CTX_end(ctx); + BN_CTX_free(ctx); + } + + param_nid = EC_GROUP_get_curve_name(EC_KEY_get0_group(EVP_PKEY_get0((EVP_PKEY *)pkey))); + if (!BIO_indent(out,indent,128)) return 0; + BIO_printf(out,"Parameter set: %s\n",OBJ_nid2ln(param_nid)); + return 1; +} +static int param_print_gost01(BIO *out, const EVP_PKEY *pkey, int indent, + ASN1_PCTX *pctx) + { + return print_gost_01(out,pkey,indent,pctx,0); + } +static int pub_print_gost01(BIO *out, const EVP_PKEY *pkey, int indent, + ASN1_PCTX *pctx) + { + return print_gost_01(out,pkey, indent, pctx,1); + } +static int priv_print_gost01(BIO *out,const EVP_PKEY *pkey, int indent, + ASN1_PCTX *pctx) + { + return print_gost_01(out,pkey,indent,pctx,2); + } +/* ---------------------------------------------------------------------*/ +static int param_missing_gost94(const EVP_PKEY *pk) + { + const DSA *dsa = EVP_PKEY_get0((EVP_PKEY *)pk); + if (!dsa) return 1; + if (!dsa->q) return 1; + return 0; + } + +static int param_missing_gost01(const EVP_PKEY *pk) + { + const EC_KEY *ec = EVP_PKEY_get0((EVP_PKEY *)pk); + if (!ec) return 1; + if (!EC_KEY_get0_group(ec)) return 1; + return 0; + } + +static int param_copy_gost94(EVP_PKEY *to, const EVP_PKEY *from) + { + const DSA *dfrom = EVP_PKEY_get0((EVP_PKEY *)from); + DSA *dto = EVP_PKEY_get0(to); + if (EVP_PKEY_base_id(from) != EVP_PKEY_base_id(to)) + { + GOSTerr(GOST_F_PARAM_COPY_GOST94, + GOST_R_INCOMPATIBLE_ALGORITHMS); + return 0; + } + if (!dfrom) + { + GOSTerr(GOST_F_PARAM_COPY_GOST94, + GOST_R_KEY_PARAMETERS_MISSING); + return 0; + } + if (!dto) + { + dto = DSA_new(); + EVP_PKEY_assign(to,EVP_PKEY_base_id(from),dto); + } +#define COPYBIGNUM(a,b,x) if (a->x) BN_free(a->x); a->x=BN_dup(b->x); + COPYBIGNUM(dto,dfrom,p) + COPYBIGNUM(dto,dfrom,q) + COPYBIGNUM(dto,dfrom,g) + + if (dto->priv_key) + gost94_compute_public(dto); + return 1; + } +static int param_copy_gost01(EVP_PKEY *to, const EVP_PKEY *from) + { + EC_KEY *eto = EVP_PKEY_get0(to); + const EC_KEY *efrom = EVP_PKEY_get0((EVP_PKEY *)from); + if (EVP_PKEY_base_id(from) != EVP_PKEY_base_id(to)) + { + GOSTerr(GOST_F_PARAM_COPY_GOST01, + GOST_R_INCOMPATIBLE_ALGORITHMS); + return 0; + } + if (!efrom) + { + GOSTerr(GOST_F_PARAM_COPY_GOST01, + GOST_R_KEY_PARAMETERS_MISSING); + return 0; + } + if (!eto) + { + eto = EC_KEY_new(); + EVP_PKEY_assign(to,EVP_PKEY_base_id(from),eto); + } + EC_KEY_set_group(eto,EC_KEY_get0_group(efrom)); + if (EC_KEY_get0_private_key(eto)) + { + gost2001_compute_public(eto); + } + return 1; + } + +static int param_cmp_gost94(const EVP_PKEY *a, const EVP_PKEY *b) + { + const DSA *da = EVP_PKEY_get0((EVP_PKEY *)a); + const DSA *db = EVP_PKEY_get0((EVP_PKEY *)b); + if (!BN_cmp(da->q,db->q)) return 1; + return 0; + } + +static int param_cmp_gost01(const EVP_PKEY *a, const EVP_PKEY *b) + { + if (EC_GROUP_get_curve_name(EC_KEY_get0_group(EVP_PKEY_get0((EVP_PKEY *)a)))== + EC_GROUP_get_curve_name(EC_KEY_get0_group(EVP_PKEY_get0((EVP_PKEY *)b)))) + { + return 1; + } + return 0; + + } + +/* ---------- Public key functions * --------------------------------------*/ +static int pub_decode_gost94(EVP_PKEY *pk, X509_PUBKEY *pub) + { + X509_ALGOR *palg = NULL; + const unsigned char *pubkey_buf = NULL; + unsigned char *databuf; + ASN1_OBJECT *palgobj = NULL; + int pub_len,i,j; + DSA *dsa; + ASN1_OCTET_STRING *octet= NULL; + + if (!X509_PUBKEY_get0_param(&palgobj,&pubkey_buf,&pub_len, + &palg, pub)) return 0; + EVP_PKEY_assign(pk,OBJ_obj2nid(palgobj),NULL); + if (!decode_gost_algor_params(pk,palg)) return 0; + octet = d2i_ASN1_OCTET_STRING(NULL,&pubkey_buf,pub_len); + if (!octet) + { + GOSTerr(GOST_F_PUB_DECODE_GOST94,ERR_R_MALLOC_FAILURE); + return 0; + } + databuf = OPENSSL_malloc(octet->length); + for (i=0,j=octet->length-1;ilength;i++,j--) + { + databuf[j]=octet->data[i]; + } + dsa = EVP_PKEY_get0(pk); + dsa->pub_key=BN_bin2bn(databuf,octet->length,NULL); + ASN1_OCTET_STRING_free(octet); + OPENSSL_free(databuf); + return 1; + + } + +static int pub_encode_gost94(X509_PUBKEY *pub,const EVP_PKEY *pk) + { + ASN1_OBJECT *algobj = NULL; + ASN1_OCTET_STRING *octet = NULL; + void *pval = NULL; + unsigned char *buf=NULL,*databuf,*sptr; + int i,j,data_len,ret=0; + + int ptype = V_ASN1_UNDEF; + DSA *dsa = EVP_PKEY_get0((EVP_PKEY *)pk); + algobj = OBJ_nid2obj(EVP_PKEY_base_id(pk)); + if (pk->save_parameters) + { + ASN1_STRING *params = encode_gost_algor_params(pk); + pval = params; + ptype = V_ASN1_SEQUENCE; + } + data_len = BN_num_bytes(dsa->pub_key); + databuf = OPENSSL_malloc(data_len); + BN_bn2bin(dsa->pub_key,databuf); + octet = ASN1_OCTET_STRING_new(); + ASN1_STRING_set(octet,NULL,data_len); + sptr = ASN1_STRING_data(octet); + for (i=0,j=data_len-1; i< data_len;i++,j--) + { + sptr[i]=databuf[j]; + } + OPENSSL_free(databuf); + ret = i2d_ASN1_OCTET_STRING(octet,&buf); + ASN1_BIT_STRING_free(octet); + if (ret <0) return 0; + return X509_PUBKEY_set0_param(pub,algobj,ptype,pval,buf,ret); + } + +static int pub_decode_gost01(EVP_PKEY *pk,X509_PUBKEY *pub) + { + X509_ALGOR *palg = NULL; + const unsigned char *pubkey_buf = NULL; + unsigned char *databuf; + ASN1_OBJECT *palgobj = NULL; + int pub_len,i,j; + EC_POINT *pub_key; + BIGNUM *X,*Y; + ASN1_OCTET_STRING *octet= NULL; + int len; + const EC_GROUP *group; + + if (!X509_PUBKEY_get0_param(&palgobj,&pubkey_buf,&pub_len, + &palg, pub)) return 0; + EVP_PKEY_assign(pk,OBJ_obj2nid(palgobj),NULL); + if (!decode_gost_algor_params(pk,palg)) return 0; + group = EC_KEY_get0_group(EVP_PKEY_get0(pk)); + octet = d2i_ASN1_OCTET_STRING(NULL,&pubkey_buf,pub_len); + if (!octet) + { + GOSTerr(GOST_F_PUB_DECODE_GOST01,ERR_R_MALLOC_FAILURE); + return 0; + } + databuf = OPENSSL_malloc(octet->length); + for (i=0,j=octet->length-1;ilength;i++,j--) + { + databuf[j]=octet->data[i]; + } + len=octet->length/2; + ASN1_OCTET_STRING_free(octet); + + Y= getbnfrombuf(databuf,len); + X= getbnfrombuf(databuf+len,len); + OPENSSL_free(databuf); + pub_key = EC_POINT_new(group); + if (!EC_POINT_set_affine_coordinates_GFp(group + ,pub_key,X,Y,NULL)) + { + GOSTerr(GOST_F_PUB_DECODE_GOST01, + ERR_R_EC_LIB); + EC_POINT_free(pub_key); + BN_free(X); + BN_free(Y); + return 0; + } + BN_free(X); + BN_free(Y); + if (!EC_KEY_set_public_key(EVP_PKEY_get0(pk),pub_key)) + { + GOSTerr(GOST_F_PUB_DECODE_GOST01, + ERR_R_EC_LIB); + EC_POINT_free(pub_key); + return 0; + } + EC_POINT_free(pub_key); + return 1; + + } + +static int pub_encode_gost01(X509_PUBKEY *pub,const EVP_PKEY *pk) + { + ASN1_OBJECT *algobj = NULL; + ASN1_OCTET_STRING *octet = NULL; + void *pval = NULL; + unsigned char *buf=NULL,*databuf,*sptr; + int i,j,data_len,ret=0; + const EC_POINT *pub_key; + BIGNUM *X,*Y,*order; + const EC_KEY *ec = EVP_PKEY_get0((EVP_PKEY *)pk); + int ptype = V_ASN1_UNDEF; + + algobj = OBJ_nid2obj(EVP_PKEY_base_id(pk)); + if (pk->save_parameters) + { + ASN1_STRING *params = encode_gost_algor_params(pk); + pval = params; + ptype = V_ASN1_SEQUENCE; + } + order = BN_new(); + EC_GROUP_get_order(EC_KEY_get0_group(ec),order,NULL); + pub_key=EC_KEY_get0_public_key(ec); + if (!pub_key) + { + GOSTerr(GOST_F_PUB_ENCODE_GOST01, + GOST_R_PUBLIC_KEY_UNDEFINED); + return 0; + } + X=BN_new(); + Y=BN_new(); + EC_POINT_get_affine_coordinates_GFp(EC_KEY_get0_group(ec), + pub_key,X,Y,NULL); + data_len = 2*BN_num_bytes(order); + BN_free(order); + databuf = OPENSSL_malloc(data_len); + memset(databuf,0,data_len); + + store_bignum(X,databuf+data_len/2,data_len/2); + store_bignum(Y,databuf,data_len/2); + + BN_free(X); + BN_free(Y); + octet = ASN1_OCTET_STRING_new(); + ASN1_STRING_set(octet,NULL,data_len); + sptr=ASN1_STRING_data(octet); + for (i=0,j=data_len-1;ipub_key && db->pub_key + && !BN_cmp(da->pub_key,db->pub_key)) + { + return 1; + } + return 0; + } + +static int pub_cmp_gost01(const EVP_PKEY *a,const EVP_PKEY *b) + { + const EC_KEY *ea = EVP_PKEY_get0((EVP_PKEY *)a); + const EC_KEY *eb = EVP_PKEY_get0((EVP_PKEY *)b); + const EC_POINT *ka,*kb; + int ret=0; + if (!ea || !eb) return 0; + ka = EC_KEY_get0_public_key(ea); + kb = EC_KEY_get0_public_key(eb); + if (!ka || !kb) return 0; + ret = (0==EC_POINT_cmp(EC_KEY_get0_group(ea),ka,kb,NULL)) ; + return ret; + } + + + + +static int pkey_size_gost(const EVP_PKEY *pk) + { + return 64; + } + +static int pkey_bits_gost(const EVP_PKEY *pk) + { + return 256; + } +/*------------------------ ASN1 METHOD for GOST MAC -------------------*/ +static void mackey_free_gost(EVP_PKEY *pk) + { + if (pk->pkey.ptr) { + OPENSSL_free(pk->pkey.ptr); + } + } +static int mac_ctrl_gost(EVP_PKEY *pkey, int op, long arg1, void *arg2) +{ + switch (op) + { + case ASN1_PKEY_CTRL_DEFAULT_MD_NID: + *(int *)arg2 = NID_id_Gost28147_89_MAC; + return 2; + } + return -2; +} + +static int gost94_param_encode(const EVP_PKEY *pkey, unsigned char **pder) +{ + int nid=gost94_nid_by_params(EVP_PKEY_get0((EVP_PKEY *)pkey)); + return i2d_ASN1_OBJECT(OBJ_nid2obj(nid),pder); +} +static int gost2001_param_encode(const EVP_PKEY *pkey, unsigned char **pder) +{ + int nid = EC_GROUP_get_curve_name(EC_KEY_get0_group(EVP_PKEY_get0((EVP_PKEY *)pkey))); + return i2d_ASN1_OBJECT(OBJ_nid2obj(nid),pder); +} + +static int gost94_param_decode(EVP_PKEY *pkey, const unsigned char **pder, int derlen) +{ + ASN1_OBJECT *obj=NULL; + DSA *dsa = EVP_PKEY_get0(pkey); + int nid; + if (d2i_ASN1_OBJECT(&obj,pder,derlen)==NULL) { + return 0; + } + nid = OBJ_obj2nid(obj); + ASN1_OBJECT_free(obj); + if (!dsa) + { + dsa=DSA_new(); + if (!EVP_PKEY_assign(pkey,NID_id_GostR3410_94,dsa)) return 0; + } + if (!fill_GOST94_params(dsa,nid)) return 0; + return 1; +} + +static int gost2001_param_decode(EVP_PKEY *pkey, const unsigned char **pder, int derlen) { + ASN1_OBJECT *obj=NULL; + int nid; + EC_KEY *ec = EVP_PKEY_get0(pkey); + if (d2i_ASN1_OBJECT(&obj,pder,derlen)==NULL) { + return 0; + } + nid = OBJ_obj2nid(obj); + ASN1_OBJECT_free(obj); + if (!ec) + { + ec = EC_KEY_new(); + if (!EVP_PKEY_assign(pkey,NID_id_GostR3410_2001,ec)) return 0; + } + if (!fill_GOST2001_params(ec, nid)) return 0; + return 1; +} + + + + + +/* ----------------------------------------------------------------------*/ +int register_ameth_gost (int nid, EVP_PKEY_ASN1_METHOD **ameth, const char* pemstr, const char* info) + { + *ameth = EVP_PKEY_asn1_new(nid, + ASN1_PKEY_SIGPARAM_NULL, pemstr, info); + if (!*ameth) return 0; + switch (nid) + { + case NID_id_GostR3410_94: + EVP_PKEY_asn1_set_free (*ameth, pkey_free_gost94); + EVP_PKEY_asn1_set_private (*ameth, + priv_decode_gost, priv_encode_gost, + priv_print_gost94); + + EVP_PKEY_asn1_set_param (*ameth, + gost94_param_decode, gost94_param_encode, + param_missing_gost94, param_copy_gost94, + param_cmp_gost94,param_print_gost94 ); + EVP_PKEY_asn1_set_public (*ameth, + pub_decode_gost94, pub_encode_gost94, + pub_cmp_gost94, pub_print_gost94, + pkey_size_gost, pkey_bits_gost); + + EVP_PKEY_asn1_set_ctrl (*ameth, pkey_ctrl_gost); + break; + case NID_id_GostR3410_2001: + EVP_PKEY_asn1_set_free (*ameth, pkey_free_gost01); + EVP_PKEY_asn1_set_private (*ameth, + priv_decode_gost, priv_encode_gost, + priv_print_gost01); + + EVP_PKEY_asn1_set_param (*ameth, + gost2001_param_decode, gost2001_param_encode, + param_missing_gost01, param_copy_gost01, + param_cmp_gost01, param_print_gost01); + EVP_PKEY_asn1_set_public (*ameth, + pub_decode_gost01, pub_encode_gost01, + pub_cmp_gost01, pub_print_gost01, + pkey_size_gost, pkey_bits_gost); + + EVP_PKEY_asn1_set_ctrl (*ameth, pkey_ctrl_gost); + break; + case NID_id_Gost28147_89_MAC: + EVP_PKEY_asn1_set_free(*ameth, mackey_free_gost); + EVP_PKEY_asn1_set_ctrl(*ameth,mac_ctrl_gost); + break; + } + return 1; + } diff --git a/node-v0.8.14/deps/openssl/openssl/engines/ccgost/gost_asn1.c b/node-v0.8.14/deps/openssl/openssl/engines/ccgost/gost_asn1.c new file mode 100644 index 0000000..318ecfc --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/engines/ccgost/gost_asn1.c @@ -0,0 +1,55 @@ +/********************************************************************** + * gost_keytrans.c * + * Copyright (c) 2005-2006 Cryptocom LTD * + * This file is distributed under the same license as OpenSSL * + * * + * ASN1 structure definition for GOST key transport * + * Requires OpenSSL 0.9.9 for compilation * + **********************************************************************/ +#include +#include +#include +#include "gost_lcl.h" + +ASN1_NDEF_SEQUENCE(GOST_KEY_TRANSPORT) = { + ASN1_SIMPLE(GOST_KEY_TRANSPORT, key_info, GOST_KEY_INFO), + ASN1_IMP(GOST_KEY_TRANSPORT, key_agreement_info, GOST_KEY_AGREEMENT_INFO, 0) +} ASN1_NDEF_SEQUENCE_END(GOST_KEY_TRANSPORT) + +IMPLEMENT_ASN1_FUNCTIONS(GOST_KEY_TRANSPORT) + +ASN1_NDEF_SEQUENCE(GOST_KEY_INFO) = { + ASN1_SIMPLE(GOST_KEY_INFO, encrypted_key, ASN1_OCTET_STRING), + ASN1_SIMPLE(GOST_KEY_INFO, imit, ASN1_OCTET_STRING) +} ASN1_NDEF_SEQUENCE_END(GOST_KEY_INFO) + +IMPLEMENT_ASN1_FUNCTIONS(GOST_KEY_INFO) + +ASN1_NDEF_SEQUENCE(GOST_KEY_AGREEMENT_INFO) = { + ASN1_SIMPLE(GOST_KEY_AGREEMENT_INFO, cipher, ASN1_OBJECT), + ASN1_IMP_OPT(GOST_KEY_AGREEMENT_INFO, ephem_key, X509_PUBKEY, 0), + ASN1_SIMPLE(GOST_KEY_AGREEMENT_INFO, eph_iv, ASN1_OCTET_STRING) +} ASN1_NDEF_SEQUENCE_END(GOST_KEY_AGREEMENT_INFO) + +IMPLEMENT_ASN1_FUNCTIONS(GOST_KEY_AGREEMENT_INFO) + +ASN1_NDEF_SEQUENCE(GOST_KEY_PARAMS) = { + ASN1_SIMPLE(GOST_KEY_PARAMS, key_params, ASN1_OBJECT), + ASN1_SIMPLE(GOST_KEY_PARAMS, hash_params, ASN1_OBJECT), + ASN1_OPT(GOST_KEY_PARAMS, cipher_params, ASN1_OBJECT), +} ASN1_NDEF_SEQUENCE_END(GOST_KEY_PARAMS) + +IMPLEMENT_ASN1_FUNCTIONS(GOST_KEY_PARAMS) + +ASN1_NDEF_SEQUENCE(GOST_CIPHER_PARAMS) = { + ASN1_SIMPLE(GOST_CIPHER_PARAMS, iv, ASN1_OCTET_STRING), + ASN1_SIMPLE(GOST_CIPHER_PARAMS, enc_param_set, ASN1_OBJECT), +} ASN1_NDEF_SEQUENCE_END(GOST_CIPHER_PARAMS) + +IMPLEMENT_ASN1_FUNCTIONS(GOST_CIPHER_PARAMS) + +ASN1_NDEF_SEQUENCE(GOST_CLIENT_KEY_EXCHANGE_PARAMS) = { /*FIXME incomplete*/ + ASN1_SIMPLE(GOST_CLIENT_KEY_EXCHANGE_PARAMS, gkt, GOST_KEY_TRANSPORT) +} ASN1_NDEF_SEQUENCE_END(GOST_CLIENT_KEY_EXCHANGE_PARAMS) + +IMPLEMENT_ASN1_FUNCTIONS(GOST_CLIENT_KEY_EXCHANGE_PARAMS) diff --git a/node-v0.8.14/deps/openssl/openssl/engines/ccgost/gost_crypt.c b/node-v0.8.14/deps/openssl/openssl/engines/ccgost/gost_crypt.c new file mode 100644 index 0000000..cde58c0 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/engines/ccgost/gost_crypt.c @@ -0,0 +1,617 @@ +/********************************************************************** + * gost_crypt.c * + * Copyright (c) 2005-2006 Cryptocom LTD * + * This file is distributed under the same license as OpenSSL * + * * + * OpenSSL interface to GOST 28147-89 cipher functions * + * Requires OpenSSL 0.9.9 for compilation * + **********************************************************************/ +#include +#include "gost89.h" +#include +#include "e_gost_err.h" +#include "gost_lcl.h" +static int gost_cipher_init(EVP_CIPHER_CTX *ctx, const unsigned char *key, + const unsigned char *iv, int enc); +static int gost_cipher_init_cpa(EVP_CIPHER_CTX *ctx, const unsigned char *key, + const unsigned char *iv, int enc); +/* Handles block of data in CFB mode */ +static int gost_cipher_do_cfb(EVP_CIPHER_CTX *ctx, unsigned char *out, + const unsigned char *in, size_t inl); +/* Handles block of data in CNT mode */ +static int gost_cipher_do_cnt(EVP_CIPHER_CTX *ctx, unsigned char *out, + const unsigned char *in, size_t inl); +/* Cleanup function */ +static int gost_cipher_cleanup(EVP_CIPHER_CTX *); +/* set/get cipher parameters */ +static int gost89_set_asn1_parameters(EVP_CIPHER_CTX *ctx,ASN1_TYPE *params); +static int gost89_get_asn1_parameters(EVP_CIPHER_CTX *ctx,ASN1_TYPE *params); +/* Control function */ +static int gost_cipher_ctl(EVP_CIPHER_CTX *ctx,int type,int arg,void *ptr); + +EVP_CIPHER cipher_gost = + { + NID_id_Gost28147_89, + 1,/*block_size*/ + 32,/*key_size*/ + 8,/*iv_len */ + EVP_CIPH_CFB_MODE| EVP_CIPH_NO_PADDING | + EVP_CIPH_CUSTOM_IV| EVP_CIPH_RAND_KEY | EVP_CIPH_ALWAYS_CALL_INIT, + gost_cipher_init, + gost_cipher_do_cfb, + gost_cipher_cleanup, + sizeof(struct ossl_gost_cipher_ctx),/* ctx_size */ + gost89_set_asn1_parameters, + gost89_get_asn1_parameters, + gost_cipher_ctl, + NULL, + }; + +EVP_CIPHER cipher_gost_cpacnt = + { + NID_gost89_cnt, + 1,/*block_size*/ + 32,/*key_size*/ + 8,/*iv_len */ + EVP_CIPH_OFB_MODE| EVP_CIPH_NO_PADDING | + EVP_CIPH_CUSTOM_IV| EVP_CIPH_RAND_KEY | EVP_CIPH_ALWAYS_CALL_INIT, + gost_cipher_init_cpa, + gost_cipher_do_cnt, + gost_cipher_cleanup, + sizeof(struct ossl_gost_cipher_ctx), /* ctx_size */ + gost89_set_asn1_parameters, + gost89_get_asn1_parameters, + gost_cipher_ctl, + NULL, + }; + +/* Implementation of GOST 28147-89 in MAC (imitovstavka) mode */ +/* Init functions which set specific parameters */ +static int gost_imit_init_cpa(EVP_MD_CTX *ctx); +/* process block of data */ +static int gost_imit_update(EVP_MD_CTX *ctx, const void *data, size_t count); +/* Return computed value */ +static int gost_imit_final(EVP_MD_CTX *ctx,unsigned char *md); +/* Copies context */ +static int gost_imit_copy(EVP_MD_CTX *to,const EVP_MD_CTX *from); +static int gost_imit_cleanup(EVP_MD_CTX *ctx); +/* Control function, knows how to set MAC key.*/ +static int gost_imit_ctrl(EVP_MD_CTX *ctx,int type, int arg, void *ptr); + +EVP_MD imit_gost_cpa = + { + NID_id_Gost28147_89_MAC, + NID_undef, + 4, + 0, + gost_imit_init_cpa, + gost_imit_update, + gost_imit_final, + gost_imit_copy, + gost_imit_cleanup, + NULL, + NULL, + {0,0,0,0,0}, + 8, + sizeof(struct ossl_gost_imit_ctx), + gost_imit_ctrl + }; + +/* + * Correspondence between gost parameter OIDs and substitution blocks + * NID field is filed by register_gost_NID function in engine.c + * upon engine initialization + */ + +struct gost_cipher_info gost_cipher_list[]= + { +/* NID */ /* Subst block */ /* Key meshing*/ +/*{NID_id_GostR3411_94_CryptoProParamSet,&GostR3411_94_CryptoProParamSet,0},*/ + {NID_id_Gost28147_89_cc,&GostR3411_94_CryptoProParamSet,0}, + {NID_id_Gost28147_89_CryptoPro_A_ParamSet,&Gost28147_CryptoProParamSetA,1}, + {NID_id_Gost28147_89_CryptoPro_B_ParamSet,&Gost28147_CryptoProParamSetB,1}, + {NID_id_Gost28147_89_CryptoPro_C_ParamSet,&Gost28147_CryptoProParamSetC,1}, + {NID_id_Gost28147_89_CryptoPro_D_ParamSet,&Gost28147_CryptoProParamSetD,1}, + {NID_id_Gost28147_89_TestParamSet,&Gost28147_TestParamSet,1}, + {NID_undef,NULL,0} + }; + +/* get encryption parameters from crypto network settings + FIXME For now we use environment var CRYPT_PARAMS as place to + store these settings. Actually, it is better to use engine control command, read from configuration file to set them */ +const struct gost_cipher_info *get_encryption_params(ASN1_OBJECT *obj) + { + int nid; + struct gost_cipher_info *param; + if (!obj) + { + const char * params = get_gost_engine_param(GOST_PARAM_CRYPT_PARAMS); + if (!params || !strlen(params)) + return &gost_cipher_list[1]; + + nid = OBJ_txt2nid(params); + if (nid == NID_undef) + { + GOSTerr(GOST_F_GET_ENCRYPTION_PARAMS, + GOST_R_INVALID_CIPHER_PARAM_OID); + return NULL; + } + } + else + { + nid= OBJ_obj2nid(obj); + } + for (param=gost_cipher_list;param->sblock!=NULL && param->nid!=nid; + param++); + if (!param->sblock) + { + GOSTerr(GOST_F_GET_ENCRYPTION_PARAMS,GOST_R_INVALID_CIPHER_PARAMS); + return NULL; + } + return param; + } + +/* Sets cipher param from paramset NID. */ +static int gost_cipher_set_param(struct ossl_gost_cipher_ctx *c,int nid) + { + const struct gost_cipher_info *param; + param=get_encryption_params((nid==NID_undef?NULL:OBJ_nid2obj(nid))); + if (!param) return 0; + + c->paramNID = param->nid; + c->key_meshing=param->key_meshing; + c->count=0; + gost_init(&(c->cctx), param->sblock); + return 1; + } + +/* Initializes EVP_CIPHER_CTX by paramset NID */ +static int gost_cipher_init_param(EVP_CIPHER_CTX *ctx, const unsigned char *key, + const unsigned char *iv, int enc, int paramNID,int mode) + { + struct ossl_gost_cipher_ctx *c=ctx->cipher_data; + if (ctx->app_data == NULL) + { + if (!gost_cipher_set_param(c,paramNID)) return 0; + ctx->app_data = ctx->cipher_data; + } + if (key) gost_key(&(c->cctx),key); + if(iv) memcpy(ctx->oiv, iv, EVP_CIPHER_CTX_iv_length(ctx)); + memcpy(ctx->iv, ctx->oiv, EVP_CIPHER_CTX_iv_length(ctx)); + return 1; + } + +static int gost_cipher_init_cpa(EVP_CIPHER_CTX *ctx, const unsigned char *key, + const unsigned char *iv, int enc) + { + struct ossl_gost_cipher_ctx *c=ctx->cipher_data; + gost_init(&(c->cctx),&Gost28147_CryptoProParamSetA); + c->key_meshing=1; + c->count=0; + if(key) gost_key(&(c->cctx),key); + if(iv) memcpy(ctx->oiv, iv, EVP_CIPHER_CTX_iv_length(ctx)); + memcpy(ctx->iv, ctx->oiv, EVP_CIPHER_CTX_iv_length(ctx)); + return 1; + } + +/* Initializes EVP_CIPHER_CTX with default values */ +int gost_cipher_init(EVP_CIPHER_CTX *ctx, const unsigned char *key, + const unsigned char *iv, int enc) + { + return gost_cipher_init_param(ctx,key,iv,enc,NID_undef,EVP_CIPH_CFB_MODE); + } +/* Wrapper around gostcrypt function from gost89.c which perform + * key meshing when nesseccary + */ +static void gost_crypt_mesh (void *ctx,unsigned char *iv,unsigned char *buf) + { + struct ossl_gost_cipher_ctx *c = ctx; + if (c->count&&c->key_meshing && c->count%1024==0) + { + cryptopro_key_meshing(&(c->cctx),iv); + } + gostcrypt(&(c->cctx),iv,buf); + c->count+=8; + } + +static void gost_cnt_next (void *ctx, unsigned char *iv, unsigned char *buf) + { + struct ossl_gost_cipher_ctx *c = ctx; + word32 g,go; + unsigned char buf1[8]; + if (c->count && c->key_meshing && c->count %1024 ==0) + { + cryptopro_key_meshing(&(c->cctx),iv); + } + if (c->count==0) + { + gostcrypt(&(c->cctx),iv,buf1); + } + else + { + memcpy(buf1,iv,8); + } + g = buf1[0]|(buf1[1]<<8)|(buf1[2]<<16)|(buf1[3]<<24); + g += 0x01010101; + buf1[0]=(unsigned char)(g&0xff); + buf1[1]=(unsigned char)((g>>8)&0xff); + buf1[2]=(unsigned char)((g>>16)&0xff); + buf1[3]=(unsigned char)((g>>24)&0xff); + g = buf1[4]|(buf1[5]<<8)|(buf1[6]<<16)|(buf1[7]<<24); + go = g; + g += 0x01010104; + if (go > g) /* overflow*/ + g++; + buf1[4]=(unsigned char)(g&0xff); + buf1[5]=(unsigned char)((g>>8)&0xff); + buf1[6]=(unsigned char)((g>>16)&0xff); + buf1[7]=(unsigned char)((g>>24)&0xff); + memcpy(iv,buf1,8); + gostcrypt(&(c->cctx),buf1,buf); + c->count +=8; + } + +/* GOST encryption in CFB mode */ +int gost_cipher_do_cfb(EVP_CIPHER_CTX *ctx, unsigned char *out, + const unsigned char *in, size_t inl) + { + const unsigned char *in_ptr=in; + unsigned char *out_ptr=out; + size_t i=0; + size_t j=0; +/* process partial block if any */ + if (ctx->num) + { + for (j=ctx->num,i=0;j<8 && iencrypt) ctx->buf[j+8]=*in_ptr; + *out_ptr=ctx->buf[j]^(*in_ptr); + if (ctx->encrypt) ctx->buf[j+8]=*out_ptr; + } + if (j==8) + { + memcpy(ctx->iv,ctx->buf+8,8); + ctx->num=0; + } + else + { + ctx->num=j; + return 1; + } + } + + for (;i+8cipher_data,ctx->iv,ctx->buf); + /*xor next block of input text with it and output it*/ + /*output this block */ + if (!ctx->encrypt) memcpy(ctx->iv,in_ptr,8); + for (j=0;j<8;j++) + { + out_ptr[j]=ctx->buf[j]^in_ptr[j]; + } + /* Encrypt */ + /* Next iv is next block of cipher text*/ + if (ctx->encrypt) memcpy(ctx->iv,out_ptr,8); + } +/* Process rest of buffer */ + if (icipher_data,ctx->iv,ctx->buf); + if (!ctx->encrypt) memcpy(ctx->buf+8,in_ptr,inl-i); + for (j=0;ibuf[j]^in_ptr[j]; + } + ctx->num = j; + if (ctx->encrypt) memcpy(ctx->buf+8,out_ptr,j); + } + else + { + ctx->num = 0; + } + return 1; + } + +static int gost_cipher_do_cnt(EVP_CIPHER_CTX *ctx, unsigned char *out, + const unsigned char *in, size_t inl) + { + const unsigned char *in_ptr=in; + unsigned char *out_ptr=out; + size_t i=0; + size_t j; +/* process partial block if any */ + if (ctx->num) + { + for (j=ctx->num,i=0;j<8 && ibuf[j]^(*in_ptr); + } + if (j==8) + { + ctx->num=0; + } + else + { + ctx->num=j; + return 1; + } + } + + for (;i+8cipher_data,ctx->iv,ctx->buf); + /*xor next block of input text with it and output it*/ + /*output this block */ + for (j=0;j<8;j++) + { + out_ptr[j]=ctx->buf[j]^in_ptr[j]; + } + } +/* Process rest of buffer */ + if (icipher_data,ctx->iv,ctx->buf); + for (j=0;ibuf[j]^in_ptr[j]; + } + ctx->num = j; + } + else + { + ctx->num = 0; + } + return 1; + } + +/* Cleaning up of EVP_CIPHER_CTX */ +int gost_cipher_cleanup(EVP_CIPHER_CTX *ctx) + { + gost_destroy(&((struct ossl_gost_cipher_ctx *)ctx->cipher_data)->cctx); + ctx->app_data = NULL; + return 1; + } + +/* Control function for gost cipher */ +int gost_cipher_ctl(EVP_CIPHER_CTX *ctx,int type,int arg,void *ptr) + { + switch (type) + { + case EVP_CTRL_RAND_KEY: + { + if (RAND_bytes((unsigned char *)ptr,ctx->key_len)<=0) + { + GOSTerr(GOST_F_GOST_CIPHER_CTL,GOST_R_RANDOM_GENERATOR_ERROR); + return -1; + } + break; + } + case EVP_CTRL_PBE_PRF_NID: + if (ptr) { + *((int *)ptr)= NID_id_HMACGostR3411_94; + return 1; + } else { + return 0; + } + + default: + GOSTerr(GOST_F_GOST_CIPHER_CTL,GOST_R_UNSUPPORTED_CIPHER_CTL_COMMAND); + return -1; + } + return 1; + } + +/* Set cipher parameters from ASN1 structure */ +int gost89_set_asn1_parameters(EVP_CIPHER_CTX *ctx,ASN1_TYPE *params) + { + int len=0; + unsigned char *buf=NULL; + unsigned char *p=NULL; + struct ossl_gost_cipher_ctx *c = ctx->cipher_data; + GOST_CIPHER_PARAMS *gcp = GOST_CIPHER_PARAMS_new(); + ASN1_OCTET_STRING *os = NULL; + if (!gcp) + { + GOSTerr(GOST_F_GOST89_SET_ASN1_PARAMETERS, GOST_R_NO_MEMORY); + return 0; + } + if (!ASN1_OCTET_STRING_set(gcp->iv, ctx->iv, ctx->cipher->iv_len)) + { + GOST_CIPHER_PARAMS_free(gcp); + GOSTerr(GOST_F_GOST89_SET_ASN1_PARAMETERS, GOST_R_NO_MEMORY); + return 0; + } + ASN1_OBJECT_free(gcp->enc_param_set); + gcp->enc_param_set = OBJ_nid2obj(c->paramNID); + + len = i2d_GOST_CIPHER_PARAMS(gcp, NULL); + p = buf = (unsigned char*)OPENSSL_malloc(len); + if (!buf) + { + GOST_CIPHER_PARAMS_free(gcp); + GOSTerr(GOST_F_GOST89_SET_ASN1_PARAMETERS, GOST_R_NO_MEMORY); + return 0; + } + i2d_GOST_CIPHER_PARAMS(gcp, &p); + GOST_CIPHER_PARAMS_free(gcp); + + os = ASN1_OCTET_STRING_new(); + + if(!os || !ASN1_OCTET_STRING_set(os, buf, len)) + { + OPENSSL_free(buf); + GOSTerr(GOST_F_GOST89_SET_ASN1_PARAMETERS, GOST_R_NO_MEMORY); + return 0; + } + OPENSSL_free(buf); + + ASN1_TYPE_set(params, V_ASN1_SEQUENCE, os); + return 1; + } + +/* Store parameters into ASN1 structure */ +int gost89_get_asn1_parameters(EVP_CIPHER_CTX *ctx,ASN1_TYPE *params) + { + int ret = -1; + int len; + GOST_CIPHER_PARAMS *gcp = NULL; + unsigned char *p; + struct ossl_gost_cipher_ctx *c=ctx->cipher_data; + if (ASN1_TYPE_get(params) != V_ASN1_SEQUENCE) + { + return ret; + } + + p = params->value.sequence->data; + + gcp = d2i_GOST_CIPHER_PARAMS(NULL, (const unsigned char **)&p, + params->value.sequence->length); + + len = gcp->iv->length; + if (len != ctx->cipher->iv_len) + { + GOST_CIPHER_PARAMS_free(gcp); + GOSTerr(GOST_F_GOST89_GET_ASN1_PARAMETERS, + GOST_R_INVALID_IV_LENGTH); + return -1; + } + if (!gost_cipher_set_param(c,OBJ_obj2nid(gcp->enc_param_set))) + { + GOST_CIPHER_PARAMS_free(gcp); + return -1; + } + memcpy(ctx->oiv, gcp->iv->data, len); + + GOST_CIPHER_PARAMS_free(gcp); + + return 1; + } + + +int gost_imit_init_cpa(EVP_MD_CTX *ctx) + { + struct ossl_gost_imit_ctx *c = ctx->md_data; + memset(c->buffer,0,sizeof(c->buffer)); + memset(c->partial_block,0,sizeof(c->partial_block)); + c->count = 0; + c->bytes_left=0; + c->key_meshing=1; + gost_init(&(c->cctx),&Gost28147_CryptoProParamSetA); + return 1; + } + +static void mac_block_mesh(struct ossl_gost_imit_ctx *c,const unsigned char *data) + { + unsigned char buffer[8]; + /* We are using local buffer for iv because CryptoPro doesn't + * interpret internal state of MAC algorithm as iv during keymeshing + * (but does initialize internal state from iv in key transport + */ + if (c->key_meshing&& c->count && c->count %1024 ==0) + { + cryptopro_key_meshing(&(c->cctx),buffer); + } + mac_block(&(c->cctx),c->buffer,data); + c->count +=8; + } + +int gost_imit_update(EVP_MD_CTX *ctx, const void *data, size_t count) + { + struct ossl_gost_imit_ctx *c = ctx->md_data; + const unsigned char *p = data; + size_t bytes = count,i; + if (!(c->key_set)) { + GOSTerr(GOST_F_GOST_IMIT_UPDATE, GOST_R_MAC_KEY_NOT_SET); + return 0; + } + if (c->bytes_left) + { + for (i=c->bytes_left;i<8&&bytes>0;bytes--,i++,p++) + { + c->partial_block[i]=*p; + } + if (i==8) + { + mac_block_mesh(c,c->partial_block); + } + else + { + c->bytes_left = i; + return 1; + } + } + while (bytes>8) + { + mac_block_mesh(c,p); + p+=8; + bytes-=8; + } + if (bytes>0) + { + memcpy(c->partial_block,p,bytes); + } + c->bytes_left=bytes; + return 1; + } + +int gost_imit_final(EVP_MD_CTX *ctx,unsigned char *md) + { + struct ossl_gost_imit_ctx *c = ctx->md_data; + if (!c->key_set) { + GOSTerr(GOST_F_GOST_IMIT_FINAL, GOST_R_MAC_KEY_NOT_SET); + return 0; + } + if (c->bytes_left) + { + int i; + for (i=c->bytes_left;i<8;i++) + { + c->partial_block[i]=0; + } + mac_block_mesh(c,c->partial_block); + } + get_mac(c->buffer,32,md); + return 1; + } + +int gost_imit_ctrl(EVP_MD_CTX *ctx,int type, int arg, void *ptr) + { + switch (type) + { + case EVP_MD_CTRL_KEY_LEN: + *((unsigned int*)(ptr)) = 32; + return 1; + case EVP_MD_CTRL_SET_KEY: + { + if (arg!=32) { + GOSTerr(GOST_F_GOST_IMIT_CTRL, GOST_R_INVALID_MAC_KEY_LENGTH); + return 0; + } + + gost_key(&(((struct ossl_gost_imit_ctx*)(ctx->md_data))->cctx),ptr) ; + ((struct ossl_gost_imit_ctx*)(ctx->md_data))->key_set = 1; + return 1; + + } + default: + return 0; + } + } + +int gost_imit_copy(EVP_MD_CTX *to,const EVP_MD_CTX *from) + { + memcpy(to->md_data,from->md_data,sizeof(struct ossl_gost_imit_ctx)); + return 1; + } + +/* Clean up imit ctx */ +int gost_imit_cleanup(EVP_MD_CTX *ctx) + { + memset(ctx->md_data,0,sizeof(struct ossl_gost_imit_ctx)); + return 1; + } + diff --git a/node-v0.8.14/deps/openssl/openssl/engines/ccgost/gost_ctl.c b/node-v0.8.14/deps/openssl/openssl/engines/ccgost/gost_ctl.c new file mode 100644 index 0000000..d3cd171 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/engines/ccgost/gost_ctl.c @@ -0,0 +1,89 @@ +/********************************************************************** + * gost_ctl.c * + * Copyright (c) 2005-2006 Cryptocom LTD * + * This file is distributed under the same license as OpenSSL * + * * + * Implementation of control commands for GOST engine * + * OpenSSL 0.9.9 libraries required * + **********************************************************************/ +#include +#include +#include +#include +#include +#include +#include "gost_lcl.h" + +static char *gost_params[GOST_PARAM_MAX+1]={NULL}; +static const char *gost_envnames[]={"CRYPT_PARAMS"}; +const ENGINE_CMD_DEFN gost_cmds[]= + { +/* { GOST_CTRL_RNG, + "RNG", + "Type of random number generator to use", + ENGINE_CMD_FLAG_STRING + }, + { GOST_CTRL_RNG_PARAMS, + "RNG_PARAMS", + "Parameter for random number generator", + ENGINE_CMD_FLAG_STRING + }, +*/ { GOST_CTRL_CRYPT_PARAMS, + "CRYPT_PARAMS", + "OID of default GOST 28147-89 parameters", + ENGINE_CMD_FLAG_STRING + }, +{0,NULL,NULL,0} + }; + +void gost_param_free() +{ + int i; + for (i=0;i<=GOST_PARAM_MAX;i++) + if (gost_params[i]!=NULL) + { + OPENSSL_free(gost_params[i]); + gost_params[i]=NULL; + } + +} + +int gost_control_func(ENGINE *e,int cmd,long i, void *p, void (*f)(void)) + { + int param = cmd-ENGINE_CMD_BASE; + int ret=0; + if (param <0 || param >GOST_PARAM_MAX) return -1; + ret=gost_set_default_param(param,p); + return ret; + } + +const char *get_gost_engine_param(int param) + { + char *tmp; + if (param <0 || param >GOST_PARAM_MAX) return NULL; + if (gost_params[param]!=NULL) + { + return gost_params[param]; + } + tmp = getenv(gost_envnames[param]); + if (tmp) + { + if (gost_params[param]) OPENSSL_free(gost_params[param]); + gost_params[param] = BUF_strdup(tmp); + return gost_params[param]; + } + return NULL; + } + +int gost_set_default_param(int param, const char *value) + { + const char *tmp; + if (param <0 || param >GOST_PARAM_MAX) return 0; + tmp = getenv(gost_envnames[param]); + /* if there is value in the environment, use it, else -passed string * */ + if (!tmp) tmp=value; + if (gost_params[param]) OPENSSL_free(gost_params[param]); + gost_params[param] = BUF_strdup(tmp); + + return 1; + } diff --git a/node-v0.8.14/deps/openssl/openssl/engines/ccgost/gost_eng.c b/node-v0.8.14/deps/openssl/openssl/engines/ccgost/gost_eng.c new file mode 100644 index 0000000..d2cbe3b --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/engines/ccgost/gost_eng.c @@ -0,0 +1,273 @@ +/********************************************************************** + * gost_eng.c * + * Copyright (c) 2005-2006 Cryptocom LTD * + * This file is distributed under the same license as OpenSSL * + * * + * Main file of GOST engine * + * for OpenSSL * + * Requires OpenSSL 0.9.9 for compilation * + **********************************************************************/ +#include +#include +#include +#include +#include +#include +#include "e_gost_err.h" +#include "gost_lcl.h" +static const char *engine_gost_id = "gost"; +static const char *engine_gost_name = "Reference implementation of GOST engine"; + +/* Symmetric cipher and digest function registrar */ + +static int gost_ciphers(ENGINE *e, const EVP_CIPHER **cipher, + const int **nids, int nid); + +static int gost_digests(ENGINE *e, const EVP_MD **digest, + const int **nids, int ind); + +static int gost_pkey_meths (ENGINE *e, EVP_PKEY_METHOD **pmeth, + const int **nids, int nid); + +static int gost_pkey_asn1_meths (ENGINE *e, EVP_PKEY_ASN1_METHOD **ameth, + const int **nids, int nid); + +static int gost_cipher_nids[] = + {NID_id_Gost28147_89, NID_gost89_cnt,0}; + +static int gost_digest_nids[] = + {NID_id_GostR3411_94,NID_id_Gost28147_89_MAC, 0}; + +static int gost_pkey_meth_nids[] = + {NID_id_GostR3410_94, + NID_id_GostR3410_2001, NID_id_Gost28147_89_MAC, 0}; + +static EVP_PKEY_METHOD *pmeth_GostR3410_94 = NULL, + *pmeth_GostR3410_2001 = NULL, + *pmeth_Gost28147_MAC = NULL; + +static EVP_PKEY_ASN1_METHOD *ameth_GostR3410_94 = NULL, + *ameth_GostR3410_2001 = NULL, + *ameth_Gost28147_MAC = NULL; + + +static int gost_engine_init(ENGINE *e) + { + return 1; + } + +static int gost_engine_finish(ENGINE *e) + { + return 1; + } + +static int gost_engine_destroy(ENGINE *e) + { + gost_param_free(); + return 1; + } + +static int bind_gost (ENGINE *e,const char *id) + { + int ret = 0; + if (id && strcmp(id, engine_gost_id)) return 0; + + if (!ENGINE_set_id(e, engine_gost_id)) + { + printf("ENGINE_set_id failed\n"); + goto end; + } + if (!ENGINE_set_name(e, engine_gost_name)) + { + printf("ENGINE_set_name failed\n"); + goto end; + } + if (!ENGINE_set_digests(e, gost_digests)) + { + printf("ENGINE_set_digests failed\n"); + goto end; + } + if (! ENGINE_set_ciphers(e, gost_ciphers)) + { + printf("ENGINE_set_ciphers failed\n"); + goto end; + } + if (! ENGINE_set_pkey_meths(e, gost_pkey_meths)) + { + printf("ENGINE_set_pkey_meths failed\n"); + goto end; + } + if (! ENGINE_set_pkey_asn1_meths(e, gost_pkey_asn1_meths)) + { + printf("ENGINE_set_pkey_asn1_meths failed\n"); + goto end; + } + /* Control function and commands */ + if (!ENGINE_set_cmd_defns(e,gost_cmds)) + { + fprintf(stderr,"ENGINE_set_cmd_defns failed\n"); + goto end; + } + if (!ENGINE_set_ctrl_function(e,gost_control_func)) + { + fprintf(stderr,"ENGINE_set_ctrl_func failed\n"); + goto end; + } + if ( ! ENGINE_set_destroy_function(e, gost_engine_destroy) + || ! ENGINE_set_init_function(e,gost_engine_init) + || ! ENGINE_set_finish_function(e,gost_engine_finish)) + { + goto end; + } + + if (!register_ameth_gost(NID_id_GostR3410_94, &ameth_GostR3410_94, "GOST94", "GOST R 34.10-94")) goto end; + if (!register_ameth_gost(NID_id_GostR3410_2001, &ameth_GostR3410_2001, "GOST2001", "GOST R 34.10-2001")) goto end; + if (!register_ameth_gost(NID_id_Gost28147_89_MAC, &ameth_Gost28147_MAC, + "GOST-MAC", "GOST 28147-89 MAC")) goto end; + + if (!register_pmeth_gost(NID_id_GostR3410_94, &pmeth_GostR3410_94, 0)) goto end; + if (!register_pmeth_gost(NID_id_GostR3410_2001, &pmeth_GostR3410_2001, 0)) goto end; + if (!register_pmeth_gost(NID_id_Gost28147_89_MAC, &pmeth_Gost28147_MAC, 0)) + goto end; + if ( ! ENGINE_register_ciphers(e) + || ! ENGINE_register_digests(e) + || ! ENGINE_register_pkey_meths(e) + /* These two actually should go in LIST_ADD command */ + || ! EVP_add_cipher(&cipher_gost) + || ! EVP_add_cipher(&cipher_gost_cpacnt) + || ! EVP_add_digest(&digest_gost) + || ! EVP_add_digest(&imit_gost_cpa) + ) + { + goto end; + } + + ERR_load_GOST_strings(); + ret = 1; + end: + return ret; + } + +#ifndef OPENSSL_NO_DYNAMIC_ENGINE +IMPLEMENT_DYNAMIC_BIND_FN(bind_gost) +IMPLEMENT_DYNAMIC_CHECK_FN() +#endif /* ndef OPENSSL_NO_DYNAMIC_ENGINE */ + +static int gost_digests(ENGINE *e, const EVP_MD **digest, + const int **nids, int nid) + { + int ok =1 ; + if (!digest) + { + *nids = gost_digest_nids; + return 2; + } + /*printf("Digest no %d requested\n",nid);*/ + if(nid == NID_id_GostR3411_94) + { + *digest = &digest_gost; + } + else if (nid == NID_id_Gost28147_89_MAC) + { + *digest = &imit_gost_cpa; + } + else + { + ok =0; + *digest = NULL; + } + return ok; + } + +static int gost_ciphers (ENGINE *e,const EVP_CIPHER **cipher, + const int **nids, int nid) + { + int ok = 1; + if (!cipher) + { + *nids = gost_cipher_nids; + return 2; /* two ciphers are supported */ + } + + if(nid == NID_id_Gost28147_89) + { + *cipher = &cipher_gost; + } + else if (nid == NID_gost89_cnt) + { + *cipher = &cipher_gost_cpacnt; + } + else + { + ok = 0; + *cipher = NULL; + } + return ok; + } + +static int gost_pkey_meths (ENGINE *e, EVP_PKEY_METHOD **pmeth, + const int **nids, int nid) + { + if (!pmeth) + { + *nids = gost_pkey_meth_nids; + return 3; + } + + switch (nid) + { + case NID_id_GostR3410_94: *pmeth = pmeth_GostR3410_94; return 1; + case NID_id_GostR3410_2001: *pmeth = pmeth_GostR3410_2001; return 1; + case NID_id_Gost28147_89_MAC: *pmeth = pmeth_Gost28147_MAC; return 1; + default:; + } + + *pmeth = NULL; + return 0; + } + +static int gost_pkey_asn1_meths (ENGINE *e, EVP_PKEY_ASN1_METHOD **ameth, + const int **nids, int nid) + { + if (!ameth) + { + *nids = gost_pkey_meth_nids; + return 3; + } + switch (nid) + { + case NID_id_GostR3410_94: *ameth = ameth_GostR3410_94; return 1; + case NID_id_GostR3410_2001: *ameth = ameth_GostR3410_2001; return 1; + case NID_id_Gost28147_89_MAC: *ameth = ameth_Gost28147_MAC; return 1; + + default:; + } + + *ameth = NULL; + return 0; + } + +#ifdef OPENSSL_NO_DYNAMIC_ENGINE +static ENGINE *engine_gost(void) + { + ENGINE *ret = ENGINE_new(); + if (!ret) + return NULL; + if (!bind_gost(ret,engine_gost_id)) + { + ENGINE_free(ret); + return NULL; + } + return ret; + } + +void ENGINE_load_gost(void) + { + ENGINE *toadd =engine_gost(); + if (!toadd) return; + ENGINE_add(toadd); + ENGINE_free(toadd); + ERR_clear_error(); + } +#endif + diff --git a/node-v0.8.14/deps/openssl/openssl/engines/ccgost/gost_keywrap.c b/node-v0.8.14/deps/openssl/openssl/engines/ccgost/gost_keywrap.c new file mode 100644 index 0000000..c618f6d --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/engines/ccgost/gost_keywrap.c @@ -0,0 +1,109 @@ +/********************************************************************** + * keywrap.c * + * Copyright (c) 2005-2006 Cryptocom LTD * + * This file is distributed under the same license as OpenSSL * + * * + * Implementation of CryptoPro key wrap algorithm, as defined in * + * RFC 4357 p 6.3 and 6.4 * + * Doesn't need OpenSSL * + **********************************************************************/ +#include +#include "gost89.h" +#include "gost_keywrap.h" + +/* Diversifies key using random UserKey Material + * Implements RFC 4357 p 6.5 key diversification algorithm + * + * inputKey - 32byte key to be diversified + * ukm - 8byte user key material + * outputKey - 32byte buffer to store diversified key + * + */ +void keyDiversifyCryptoPro(gost_ctx *ctx,const unsigned char *inputKey, const unsigned char *ukm, unsigned char *outputKey) + { + + u4 k,s1,s2; + int i,j,mask; + unsigned char S[8]; + memcpy(outputKey,inputKey,32); + for (i=0;i<8;i++) + { + /* Make array of integers from key */ + /* Compute IV S*/ + s1=0,s2=0; + for (j=0,mask=1;j<8;j++,mask<<=1) + { + k=((u4)outputKey[4*j])|(outputKey[4*j+1]<<8)| + (outputKey[4*j+2]<<16)|(outputKey[4*j+3]<<24); + if (mask & ukm[i]) + { + s1+=k; + } + else + { + s2+=k; + } + } + S[0]=(unsigned char)(s1&0xff); + S[1]=(unsigned char)((s1>>8)&0xff); + S[2]=(unsigned char)((s1>>16)&0xff); + S[3]=(unsigned char)((s1>>24)&0xff); + S[4]=(unsigned char)(s2&0xff); + S[5]=(unsigned char)((s2>>8)&0xff); + S[6]=(unsigned char)((s2>>16)&0xff); + S[7]=(unsigned char)((s2>>24)&0xff); + gost_key(ctx,outputKey); + gost_enc_cfb(ctx,S,outputKey,outputKey,4); + } + } + + +/* + * Wraps key using RFC 4357 6.3 + * ctx - gost encryption context, initialized with some S-boxes + * keyExchangeKey (KEK) 32-byte (256-bit) shared key + * ukm - 8 byte (64 bit) user key material, + * sessionKey - 32-byte (256-bit) key to be wrapped + * wrappedKey - 44-byte buffer to store wrapped key + */ + +int keyWrapCryptoPro(gost_ctx *ctx,const unsigned char *keyExchangeKey, const unsigned char *ukm, + const unsigned char *sessionKey, unsigned char *wrappedKey) + { + unsigned char kek_ukm[32]; + keyDiversifyCryptoPro(ctx,keyExchangeKey,ukm,kek_ukm); + gost_key(ctx,kek_ukm); + memcpy(wrappedKey,ukm,8); + gost_enc(ctx,sessionKey,wrappedKey+8,4); + gost_mac_iv(ctx,32,ukm,sessionKey,32,wrappedKey+40); + return 1; + } +/* + * Unwraps key using RFC 4357 6.4 + * ctx - gost encryption context, initialized with some S-boxes + * keyExchangeKey 32-byte shared key + * wrappedKey 44 byte key to be unwrapped (concatenation of 8-byte UKM, + * 32 byte encrypted key and 4 byte MAC + * + * sessionKEy - 32byte buffer to store sessionKey in + * Returns 1 if key is decrypted successfully, and 0 if MAC doesn't match + */ + +int keyUnwrapCryptoPro(gost_ctx *ctx,const unsigned char *keyExchangeKey, + const unsigned char *wrappedKey, unsigned char *sessionKey) + { + unsigned char kek_ukm[32],cek_mac[4]; + keyDiversifyCryptoPro(ctx,keyExchangeKey,wrappedKey + /* First 8 bytes of wrapped Key is ukm */ + ,kek_ukm); + gost_key(ctx,kek_ukm); + gost_dec(ctx,wrappedKey+8,sessionKey,4); + gost_mac_iv(ctx,32,wrappedKey,sessionKey,32,cek_mac); + if (memcmp(cek_mac,wrappedKey+40,4)) + { + return 0; + } + return 1; + } + + diff --git a/node-v0.8.14/deps/openssl/openssl/engines/ccgost/gost_keywrap.h b/node-v0.8.14/deps/openssl/openssl/engines/ccgost/gost_keywrap.h new file mode 100644 index 0000000..37c2a0f --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/engines/ccgost/gost_keywrap.h @@ -0,0 +1,56 @@ +/********************************************************************** + * gost_keywrap.h * + * Copyright (c) 2005-2006 Cryptocom LTD * + * This file is distributed under the same license as OpenSSL * + * * + * Implementation of CryptoPro key wrap algorithm, as defined in * + * RFC 4357 p 6.3 and 6.4 * + * Doesn't need OpenSSL * + **********************************************************************/ +#ifndef GOST_KEYWRAP_H +#define GOST_KEYWRAP_H +#include +#include "gost89.h" +/* Diversifies key using random UserKey Material + * Implements RFC 4357 p 6.5 key diversification algorithm + * + * inputKey - 32byte key to be diversified + * ukm - 8byte user key material + * outputKey - 32byte buffer to store diversified key + * + */ +void keyDiversifyCryptoPro(gost_ctx *ctx, + const unsigned char *inputKey, + const unsigned char *ukm, + unsigned char *outputKey); +/* + * Wraps key using RFC 4357 6.3 + * ctx - gost encryption context, initialized with some S-boxes + * keyExchangeKey (KEK) 32-byte (256-bit) shared key + * ukm - 8 byte (64 bit) user key material, + * sessionKey - 32-byte (256-bit) key to be wrapped + * wrappedKey - 44-byte buffer to store wrapped key + */ + +int keyWrapCryptoPro(gost_ctx *ctx, + const unsigned char *keyExchangeKey, + const unsigned char *ukm, + const unsigned char *sessionKey, + unsigned char *wrappedKey) ; +/* + * Unwraps key using RFC 4357 6.4 + * ctx - gost encryption context, initialized with some S-boxes + * keyExchangeKey 32-byte shared key + * wrappedKey 44 byte key to be unwrapped (concatenation of 8-byte UKM, + * 32 byte encrypted key and 4 byte MAC + * + * sessionKEy - 32byte buffer to store sessionKey in + * Returns 1 if key is decrypted successfully, and 0 if MAC doesn't match + */ + + +int keyUnwrapCryptoPro(gost_ctx *ctx, + const unsigned char *keyExchangeKey, + const unsigned char *wrappedKey, + unsigned char *sessionKey) ; +#endif diff --git a/node-v0.8.14/deps/openssl/openssl/engines/ccgost/gost_lcl.h b/node-v0.8.14/deps/openssl/openssl/engines/ccgost/gost_lcl.h new file mode 100644 index 0000000..437a48c --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/engines/ccgost/gost_lcl.h @@ -0,0 +1,218 @@ +#ifndef GOST_TOOLS_H +#define GOST_TOOLS_H +/********************************************************************** + * gost_lcl.h * + * Copyright (c) 2006 Cryptocom LTD * + * This file is distributed under the same license as OpenSSL * + * * + * Internal declarations used in GOST engine * + * OpenSSL 0.9.9 libraries required to compile and use * + * this code * + **********************************************************************/ +#include +#include +#include +#include +#include +#include +#include +#include "gost89.h" +#include "gosthash.h" +/* Control commands */ +#define GOST_PARAM_CRYPT_PARAMS 0 +#define GOST_PARAM_MAX 0 +#define GOST_CTRL_CRYPT_PARAMS (ENGINE_CMD_BASE+GOST_PARAM_CRYPT_PARAMS) + + extern const ENGINE_CMD_DEFN gost_cmds[]; + int gost_control_func(ENGINE *e,int cmd, long i, void *p, void (*f)(void)); + const char *get_gost_engine_param(int param); + int gost_set_default_param(int param, const char *value); + void gost_param_free(void); + +/* method registration */ + + int register_ameth_gost (int nid, EVP_PKEY_ASN1_METHOD **ameth, const char* pemstr, const char* info); + int register_pmeth_gost (int id, EVP_PKEY_METHOD **pmeth, int flags); + +/* Gost-specific pmeth control-function parameters */ +/* For GOST R34.10 parameters */ +#define param_ctrl_string "paramset" +#define EVP_PKEY_CTRL_GOST_PARAMSET (EVP_PKEY_ALG_CTRL+1) +/* For GOST 28147 MAC */ +#define key_ctrl_string "key" +#define hexkey_ctrl_string "hexkey" +#define EVP_PKEY_CTRL_GOST_MAC_HEXKEY (EVP_PKEY_ALG_CTRL+3) +/* Pmeth internal representation */ + struct gost_pmeth_data { + int sign_param_nid; /* Should be set whenever parameters are filled */ + EVP_MD *md; + unsigned char *shared_ukm; + int peer_key_used; + }; + + struct gost_mac_pmeth_data { + int key_set; + EVP_MD *md; + unsigned char key[32]; + } ; +/* GOST-specific ASN1 structures */ + + +typedef struct { + ASN1_OCTET_STRING *encrypted_key; + ASN1_OCTET_STRING *imit; +} GOST_KEY_INFO; + +DECLARE_ASN1_FUNCTIONS(GOST_KEY_INFO) + +typedef struct { + ASN1_OBJECT *cipher; + X509_PUBKEY *ephem_key; + ASN1_OCTET_STRING *eph_iv; +} GOST_KEY_AGREEMENT_INFO; + +DECLARE_ASN1_FUNCTIONS(GOST_KEY_AGREEMENT_INFO) + +typedef struct { + GOST_KEY_INFO *key_info; + GOST_KEY_AGREEMENT_INFO *key_agreement_info; +} GOST_KEY_TRANSPORT; + +DECLARE_ASN1_FUNCTIONS(GOST_KEY_TRANSPORT) + +typedef struct { /* FIXME incomplete */ + GOST_KEY_TRANSPORT *gkt; +} GOST_CLIENT_KEY_EXCHANGE_PARAMS; + +/* Hacks to shorten symbols to 31 characters or less, or OpenVMS. + This mimics what's done in symhacks.h, but since this is a very + local header file, I prefered to put this hack directly here. + -- Richard Levitte */ +#ifdef OPENSSL_SYS_VMS +#undef GOST_CLIENT_KEY_EXCHANGE_PARAMS_it +#define GOST_CLIENT_KEY_EXCHANGE_PARAMS_it GOST_CLIENT_KEY_EXC_PARAMS_it +#undef GOST_CLIENT_KEY_EXCHANGE_PARAMS_new +#define GOST_CLIENT_KEY_EXCHANGE_PARAMS_new GOST_CLIENT_KEY_EXC_PARAMS_new +#undef GOST_CLIENT_KEY_EXCHANGE_PARAMS_free +#define GOST_CLIENT_KEY_EXCHANGE_PARAMS_free GOST_CLIENT_KEY_EXC_PARAMS_free +#undef d2i_GOST_CLIENT_KEY_EXCHANGE_PARAMS +#define d2i_GOST_CLIENT_KEY_EXCHANGE_PARAMS d2i_GOST_CLIENT_KEY_EXC_PARAMS +#undef i2d_GOST_CLIENT_KEY_EXCHANGE_PARAMS +#define i2d_GOST_CLIENT_KEY_EXCHANGE_PARAMS i2d_GOST_CLIENT_KEY_EXC_PARAMS +#endif /* End of hack */ +DECLARE_ASN1_FUNCTIONS(GOST_CLIENT_KEY_EXCHANGE_PARAMS) +typedef struct { + ASN1_OBJECT *key_params; + ASN1_OBJECT *hash_params; + ASN1_OBJECT *cipher_params; +} GOST_KEY_PARAMS; + +DECLARE_ASN1_FUNCTIONS(GOST_KEY_PARAMS) + +typedef struct { + ASN1_OCTET_STRING *iv; + ASN1_OBJECT *enc_param_set; +} GOST_CIPHER_PARAMS; + +DECLARE_ASN1_FUNCTIONS(GOST_CIPHER_PARAMS) +/*============== Message digest and cipher related structures ==========*/ + /* Structure used as EVP_MD_CTX-md_data. + * It allows to avoid storing in the md-data pointers to + * dynamically allocated memory. + * + * I cannot invent better way to avoid memory leaks, because + * openssl insist on invoking Init on Final-ed digests, and there + * is no reliable way to find out whether pointer in the passed + * md_data is valid or not. + * */ +struct ossl_gost_digest_ctx { + gost_hash_ctx dctx; + gost_ctx cctx; +}; +/* EVP_MD structure for GOST R 34.11 */ +extern EVP_MD digest_gost; +/* EVP_MD structure for GOST 28147 in MAC mode */ +extern EVP_MD imit_gost_cpa; +/* Cipher context used for EVP_CIPHER operation */ +struct ossl_gost_cipher_ctx { + int paramNID; + off_t count; + int key_meshing; + gost_ctx cctx; +}; +/* Structure to map parameter NID to S-block */ +struct gost_cipher_info { + int nid; + gost_subst_block *sblock; + int key_meshing; +}; +/* Context for MAC */ +struct ossl_gost_imit_ctx { + gost_ctx cctx; + unsigned char buffer[8]; + unsigned char partial_block[8]; + off_t count; + int key_meshing; + int bytes_left; + int key_set; +}; +/* Table which maps parameter NID to S-blocks */ +extern struct gost_cipher_info gost_cipher_list[]; +/* Find encryption params from ASN1_OBJECT */ +const struct gost_cipher_info *get_encryption_params(ASN1_OBJECT *obj); +/* Implementation of GOST 28147-89 cipher in CFB and CNT modes */ +extern EVP_CIPHER cipher_gost; +extern EVP_CIPHER cipher_gost_cpacnt; +#define EVP_MD_CTRL_KEY_LEN (EVP_MD_CTRL_ALG_CTRL+3) +#define EVP_MD_CTRL_SET_KEY (EVP_MD_CTRL_ALG_CTRL+4) +/* EVP_PKEY_METHOD key encryption callbacks */ +/* From gost94_keyx.c */ +int pkey_GOST94cp_encrypt(EVP_PKEY_CTX *ctx, unsigned char *out, size_t *outlen, const unsigned char* key, size_t key_len ); + +int pkey_GOST94cp_decrypt(EVP_PKEY_CTX *ctx, unsigned char *out, size_t *outlen, const unsigned char* in, size_t in_len ); +/* From gost2001_keyx.c */ +int pkey_GOST01cp_encrypt(EVP_PKEY_CTX *ctx, unsigned char *out, size_t *outlen, const unsigned char* key, size_t key_len ); + +int pkey_GOST01cp_decrypt(EVP_PKEY_CTX *ctx, unsigned char *out, size_t *outlen, const unsigned char* in, size_t in_len ); +/* derive functions */ +/* From gost2001_keyx.c */ +int pkey_gost2001_derive(EVP_PKEY_CTX *ctx, unsigned char *key, size_t *keylen); +/* From gost94_keyx.c */ +int pkey_gost94_derive(EVP_PKEY_CTX *ctx, unsigned char *key, size_t *keylen); +/* Internal functions for signature algorithms */ +int fill_GOST94_params(DSA *dsa,int nid); +int fill_GOST2001_params(EC_KEY *eckey, int nid); +int gost_sign_keygen(DSA *dsa) ; +int gost2001_keygen(EC_KEY *ec) ; + +DSA_SIG *gost_do_sign(const unsigned char *dgst,int dlen, DSA *dsa) ; +DSA_SIG *gost2001_do_sign(const unsigned char *dgst,int dlen, EC_KEY *eckey); + +int gost_do_verify(const unsigned char *dgst, int dgst_len, + DSA_SIG *sig, DSA *dsa) ; +int gost2001_do_verify(const unsigned char *dgst,int dgst_len, + DSA_SIG *sig, EC_KEY *ec); +int gost2001_compute_public(EC_KEY *ec) ; +int gost94_compute_public(DSA *dsa) ; +/*============== miscellaneous functions============================= */ +/* from gost_sign.c */ +/* Convert GOST R 34.11 hash sum to bignum according to standard */ +BIGNUM *hashsum2bn(const unsigned char *dgst) ; +/* Store bignum in byte array of given length, prepending by zeros + * if nesseccary */ +int store_bignum(BIGNUM *bn, unsigned char *buf,int len); +/* Read bignum, which can have few MSB all-zeros from buffer*/ +BIGNUM *getbnfrombuf(const unsigned char *buf,size_t len); +/* Pack GOST R 34.10 signature according to CryptoPro rules */ +int pack_sign_cp(DSA_SIG *s,int order,unsigned char *sig, size_t *siglen); +/* Unpack GOST R 34.10 signature according to CryptoPro rules */ +DSA_SIG *unpack_cp_signature(const unsigned char *sig,size_t siglen) ; +/* from ameth.c */ +/* Get private key as BIGNUM from both R 34.10-94 and R 34.10-2001 keys*/ +/* Returns pointer into EVP_PKEY structure */ +BIGNUM* gost_get0_priv_key(const EVP_PKEY *pkey) ; +/* Find NID by GOST 94 parameters */ +int gost94_nid_by_params(DSA *p) ; + + +#endif diff --git a/node-v0.8.14/deps/openssl/openssl/engines/ccgost/gost_md.c b/node-v0.8.14/deps/openssl/openssl/engines/ccgost/gost_md.c new file mode 100644 index 0000000..417e108 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/engines/ccgost/gost_md.c @@ -0,0 +1,75 @@ +/********************************************************************** + * md_gost.c * + * Copyright (c) 2005-2006 Cryptocom LTD * + * This file is distributed under the same license as OpenSSL * + * * + * OpenSSL interface to GOST R 34.11-94 hash functions * + * Requires OpenSSL 0.9.9 for compilation * + **********************************************************************/ +#include +#include "gost_lcl.h" +#include "gosthash.h" +#include "e_gost_err.h" + +/* implementation of GOST 34.11 hash function See gost_md.c*/ +static int gost_digest_init(EVP_MD_CTX *ctx); +static int gost_digest_update(EVP_MD_CTX *ctx, const void *data, size_t count); +static int gost_digest_final(EVP_MD_CTX *ctx,unsigned char *md); +static int gost_digest_copy(EVP_MD_CTX *to,const EVP_MD_CTX *from); +static int gost_digest_cleanup(EVP_MD_CTX *ctx); + +EVP_MD digest_gost= + { + NID_id_GostR3411_94, + NID_undef, + 32, + EVP_MD_FLAG_PKEY_METHOD_SIGNATURE, + gost_digest_init, + gost_digest_update, + gost_digest_final, + gost_digest_copy, + gost_digest_cleanup, + NULL, + NULL, + {NID_undef,NID_undef,0,0,0}, + 32, + sizeof(struct ossl_gost_digest_ctx ), + NULL + }; + +int gost_digest_init(EVP_MD_CTX *ctx) + { + struct ossl_gost_digest_ctx *c = ctx->md_data; + memset(&(c->dctx),0,sizeof(gost_hash_ctx)); + gost_init(&(c->cctx),&GostR3411_94_CryptoProParamSet); + c->dctx.cipher_ctx= &(c->cctx); + return 1; + } + +int gost_digest_update(EVP_MD_CTX *ctx,const void *data,size_t count) + { + return hash_block((gost_hash_ctx *)ctx->md_data,data,count); + } + +int gost_digest_final(EVP_MD_CTX *ctx,unsigned char *md) + { + return finish_hash((gost_hash_ctx *)ctx->md_data,md); + + } + +int gost_digest_copy(EVP_MD_CTX *to,const EVP_MD_CTX *from) + { + struct ossl_gost_digest_ctx *md_ctx=to->md_data; + if (to->md_data && from->md_data) { + memcpy(to->md_data,from->md_data,sizeof(struct ossl_gost_digest_ctx)); + md_ctx->dctx.cipher_ctx=&(md_ctx->cctx); + } + return 1; + } + +int gost_digest_cleanup(EVP_MD_CTX *ctx) + { + if (ctx->md_data) + memset(ctx->md_data,0,sizeof(struct ossl_gost_digest_ctx)); + return 1; + } diff --git a/node-v0.8.14/deps/openssl/openssl/engines/ccgost/gost_params.c b/node-v0.8.14/deps/openssl/openssl/engines/ccgost/gost_params.c new file mode 100644 index 0000000..40fc343 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/engines/ccgost/gost_params.c @@ -0,0 +1,198 @@ +/********************************************************************** + * params.c * + * Copyright (c) 2005-2006 Cryptocom LTD * + * This file is distributed under the same license as OpenSSL * + * * + * Definitions of GOST R 34.10 parameter sets, defined in RFC 4357 * + * OpenSSL 0.9.9 libraries required to compile and use * + * this code * + **********************************************************************/ +#include "gost_params.h" +#include +/* Parameters of GOST 34.10 */ + +R3410_params R3410_paramset[]={ +/* Paramset A */ +{NID_id_GostR3410_94_CryptoPro_A_ParamSet, +"100997906755055304772081815535925224869" +"8410825720534578748235158755771479905292727772441528526992987964833" +"5669968284202797289605274717317548059048560713474685214192868091256" +"1502802222185647539190902656116367847270145019066794290930185446216" +"3997308722217328898303231940973554032134009725883228768509467406639" +"62", +"127021248288932417465907042777176443525" +"7876535089165358128175072657050312609850984974231883334834011809259" +"9999512098893413065920561499672425412104927434935707492031276956145" +"1689224110579311248812610229678534638401693520013288995000362260684" +"2227508135323070045173416336850045410625869714168836867788425378203" +"83", +"683631961449557007844441656118272528951" +"02170888761442055095051287550314083023"}, +{NID_id_GostR3410_94_CryptoPro_B_ParamSet, +"429418261486158041438734477379555023926" +"7234596860714306679811299408947123142002706038521669956384871995765" +"7284814898909770759462613437669456364882730370838934791080835932647" +"9767786019153434744009610342313166725786869204821949328786333602033" +"8479709268434224762105576023501613261478065276102850944540333865234" +"1", +"139454871199115825601409655107690713107" +"0417070599280317977580014543757653577229840941243685222882398330391" +"1468164807668823692122073732267216074074777170091113455043205380464" +"7694904686120113087816240740184800477047157336662926249423571248823" +"9685422217536601433914856808405203368594584948031873412885804895251" +"63", +"79885141663410976897627118935756323747307951916507639758300472692338873533959" +}, +{NID_id_GostR3410_94_CryptoPro_C_ParamSet, +"816552717970881016017893191415300348226" +"2544051353358162468249467681876621283478212884286545844013955142622" +"2087723485023722868022275009502224827866201744494021697716482008353" +"6398202298024892620480898699335508064332313529725332208819456895108" +"5155178100221003459370588291073071186553005962149936840737128710832" +"3", +"110624679233511963040518952417017040248" +"5862954819831383774196396298584395948970608956170224210628525560327" +"8638246716655439297654402921844747893079518669992827880792192992701" +"1428546551433875806377110443534293554066712653034996277099320715774" +"3542287621283671843703709141350171945045805050291770503634517804938" +"01", +"113468861199819350564868233378875198043" +"267947776488510997961231672532899549103" +}, +{NID_id_GostR3410_94_CryptoPro_D_ParamSet, +"756976611021707301782128757801610628085" +"5283803109571158829574281419208532589041660017017859858216341400371" +"4687551412794400562878935266630754392677014598582103365983119173924" +"4732511225464712252386803315902707727668715343476086350472025298282" +"7271461690125050616858238384366331089777463541013033926723743254833" +"7", +"905457649621929965904290958774625315611" +"3056083907389766971404812524422262512556054474620855996091570786713" +"5849550236741915584185990627801066465809510095784713989819413820871" +"5964648914493053407920737078890520482730623038837767710173664838239" +"8574828787891286471201460474326612697849693665518073864436497893214" +"9", +"108988435796353506912374591498972192620" +"190487557619582334771735390599299211593" +}, + +{NID_id_GostR3410_94_CryptoPro_XchA_ParamSet, +"1335318132727206734338595199483190012179423759678474868994823595993" +"6964252873471246159040332773182141032801252925387191478859899310331" +"0567744136196364803064721377826656898686468463277710150809401182608" +"7702016153249904683329312949209127762411378780302243557466062839716" +"59376426832674269780880061631528163475887", +"14201174159756348119636828602231808974327613839524373876287257344192" +"74593935127189736311660784676003608489466235676257952827747192122419" +"29071046134208380636394084512691828894000571524625445295769349356752" +"72895683154177544176313938445719175509684710784659566254794231229333" +"8483924514339614727760681880609734239", +"91771529896554605945588149018382750217296858393520724172743325725474" +"374979801" +}, +{NID_id_GostR3410_94_CryptoPro_XchB_ParamSet, +"8890864727828423151699995801875757891031463338652579140051973659" +"3048131440685857067369829407947744496306656291505503608252399443" +"7900272386749145996230867832228661977543992816745254823298629859" +"8753575466286051738837854736167685769017780335804511440773337196" +"2538423532919394477873664752824509986617878992443177", +"1028946126624994859676552074360530315217970499989304888248413244" +"8474923022758470167998871003604670704877377286176171227694098633" +"1539089568784129110109512690503345393869871295783467257264868341" +"7200196629860561193666752429682367397084815179752036423595736533" +"68957392061769855284593965042530895046088067160269433", +"9109671391802626916582318050603555673628769498182593088388796888" +"5281641595199" +}, +{NID_id_GostR3410_94_CryptoPro_XchC_ParamSet, +"4430618464297584182473135030809859326863990650118941756995270074" +"8609973181426950235239623239110557450826919295792878938752101867" +"7047181623251027516953100431855964837602657827828194249605561893" +"6965865325513137194483136247773653468410118796740709840825496997" +"9375560722345106704721086025979309968763193072908334", +"1246996366993477513607147265794064436203408861395055989217248455" +"7299870737698999651480662364723992859320868822848751165438350943" +"3276647222625940615560580450040947211826027729977563540237169063" +"0448079715771649447778447000597419032457722226253269698374446528" +"35352729304393746106576383349151001715930924115499549", +"6787876137336591234380295020065682527118129468050147943114675429" +"4748422492761" +}, + + +{NID_undef,NULL, NULL, NULL} +}; + +R3410_2001_params R3410_2001_paramset[]={ + /* default_cc_sign01_param 1.2.643.2.9.1.8.1 */ + {NID_id_GostR3410_2001_ParamSet_cc, + /* A */ + "C0000000000000000000000000000000000000000000000000000000000003c4", + /* B */ + "2d06B4265ebc749ff7d0f1f1f88232e81632e9088fd44b7787d5e407e955080c", + /* P */ + "C0000000000000000000000000000000000000000000000000000000000003C7", + /* Q */ + "5fffffffffffffffffffffffffffffff606117a2f4bde428b7458a54b6e87b85", + /* X */ + "2", + /* Y */ + "a20e034bf8813ef5c18d01105e726a17eb248b264ae9706f440bedc8ccb6b22c" + }, + /* 1.2.643.2.2.35.0 */ + {NID_id_GostR3410_2001_TestParamSet, + "7", + "5FBFF498AA938CE739B8E022FBAFEF40563F6E6A3472FC2A514C0CE9DAE23B7E", + "8000000000000000000000000000000000000000000000000000000000000431", + "8000000000000000000000000000000150FE8A1892976154C59CFC193ACCF5B3", + "2", + "08E2A8A0E65147D4BD6316030E16D19C85C97F0A9CA267122B96ABBCEA7E8FC8" + }, + /*1.2.643.2.2.35.1*/ + {NID_id_GostR3410_2001_CryptoPro_A_ParamSet, + "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFD94", + "a6", + "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFD97", + "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF6C611070995AD10045841B09B761B893", + "1", + "8D91E471E0989CDA27DF505A453F2B7635294F2DDF23E3B122ACC99C9E9F1E14" + }, + /*1.2.643.2.2.35.2*/ + {NID_id_GostR3410_2001_CryptoPro_B_ParamSet, + "8000000000000000000000000000000000000000000000000000000000000C96", + "3E1AF419A269A5F866A7D3C25C3DF80AE979259373FF2B182F49D4CE7E1BBC8B", + "8000000000000000000000000000000000000000000000000000000000000C99", + "800000000000000000000000000000015F700CFFF1A624E5E497161BCC8A198F", + "1", + "3FA8124359F96680B83D1C3EB2C070E5C545C9858D03ECFB744BF8D717717EFC" + }, + /*1.2.643.2.2.35.3*/ + {NID_id_GostR3410_2001_CryptoPro_C_ParamSet, + "9B9F605F5A858107AB1EC85E6B41C8AACF846E86789051D37998F7B9022D7598", + "805a", + "9B9F605F5A858107AB1EC85E6B41C8AACF846E86789051D37998F7B9022D759B", + "9B9F605F5A858107AB1EC85E6B41C8AA582CA3511EDDFB74F02F3A6598980BB9", + "0", + "41ECE55743711A8C3CBF3783CD08C0EE4D4DC440D4641A8F366E550DFDB3BB67" + }, + /*1.2.643.2.2.36.0*/ + {NID_id_GostR3410_2001_CryptoPro_XchA_ParamSet, + "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFD94", + "a6", + "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFD97", + "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF6C611070995AD10045841B09B761B893", + "1", + "8D91E471E0989CDA27DF505A453F2B7635294F2DDF23E3B122ACC99C9E9F1E14" + }, + /*1.2.643.2.2.36.1*/ + {NID_id_GostR3410_2001_CryptoPro_XchB_ParamSet, + "9B9F605F5A858107AB1EC85E6B41C8AACF846E86789051D37998F7B9022D7598", + "805a", + "9B9F605F5A858107AB1EC85E6B41C8AACF846E86789051D37998F7B9022D759B", + "9B9F605F5A858107AB1EC85E6B41C8AA582CA3511EDDFB74F02F3A6598980BB9", + "0", + "41ECE55743711A8C3CBF3783CD08C0EE4D4DC440D4641A8F366E550DFDB3BB67" + }, + { 0,NULL,NULL,NULL,NULL,NULL,NULL + } +}; diff --git a/node-v0.8.14/deps/openssl/openssl/engines/ccgost/gost_params.h b/node-v0.8.14/deps/openssl/openssl/engines/ccgost/gost_params.h new file mode 100644 index 0000000..4c3f556 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/engines/ccgost/gost_params.h @@ -0,0 +1,34 @@ +/********************************************************************** + * gost_params.h * + * Copyright (c) 2005-2006 Cryptocom LTD * + * This file is distributed under the same license as OpenSSL * + * * + * Declaration of structures used to represent GOST R 34.10 * + * parameter sets, defined in RFC 4357 * + * OpenSSL 0.9.9 libraries required to compile and use * + * this code * + **********************************************************************/ +#ifndef GOST_PARAMSET_H +#define GOST_PARAMSET_H +typedef struct R3410 { + int nid; + char *a; + char *p; + char *q; +} R3410_params; + +extern R3410_params R3410_paramset[]; + +typedef struct R3410_2001 { + int nid; + char *a; + char *b; + char *p; + char *q; + char *x; + char *y; +} R3410_2001_params; + +extern R3410_2001_params R3410_2001_paramset[]; + +#endif diff --git a/node-v0.8.14/deps/openssl/openssl/engines/ccgost/gost_pmeth.c b/node-v0.8.14/deps/openssl/openssl/engines/ccgost/gost_pmeth.c new file mode 100644 index 0000000..caaea99 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/engines/ccgost/gost_pmeth.c @@ -0,0 +1,621 @@ +/********************************************************************** + * gost_pmeth.c * + * Copyright (c) 2005-2006 Cryptocom LTD * + * This file is distributed under the same license as OpenSSL * + * * + * Implementation of RFC 4357 (GOST R 34.10) Publick key method * + * for OpenSSL * + * Requires OpenSSL 0.9.9 for compilation * + **********************************************************************/ +#include +#include +#include +#include /*For string_to_hex */ +#include +#include +#include +#include "gost_params.h" +#include "gost_lcl.h" +#include "e_gost_err.h" +/*-------init, cleanup, copy - uniform for all algs ---------------*/ +/* Allocates new gost_pmeth_data structure and assigns it as data */ +static int pkey_gost_init(EVP_PKEY_CTX *ctx) + { + struct gost_pmeth_data *data; + EVP_PKEY *pkey = EVP_PKEY_CTX_get0_pkey(ctx); + data = OPENSSL_malloc(sizeof(struct gost_pmeth_data)); + if (!data) return 0; + memset(data,0,sizeof(struct gost_pmeth_data)); + if (pkey && EVP_PKEY_get0(pkey)) + { + switch (EVP_PKEY_base_id(pkey)) { + case NID_id_GostR3410_94: + data->sign_param_nid = gost94_nid_by_params(EVP_PKEY_get0(pkey)); + break; + case NID_id_GostR3410_2001: + data->sign_param_nid = EC_GROUP_get_curve_name(EC_KEY_get0_group(EVP_PKEY_get0((EVP_PKEY *)pkey))); + break; + default: + return 0; + } + } + EVP_PKEY_CTX_set_data(ctx,data); + return 1; + } + +/* Copies contents of gost_pmeth_data structure */ +static int pkey_gost_copy(EVP_PKEY_CTX *dst, EVP_PKEY_CTX *src) + { + struct gost_pmeth_data *dst_data,*src_data; + if (!pkey_gost_init(dst)) + { + return 0; + } + src_data = EVP_PKEY_CTX_get_data(src); + dst_data = EVP_PKEY_CTX_get_data(dst); + *dst_data = *src_data; + if (src_data -> shared_ukm) { + dst_data->shared_ukm=NULL; + } + return 1; + } + +/* Frees up gost_pmeth_data structure */ +static void pkey_gost_cleanup (EVP_PKEY_CTX *ctx) + { + struct gost_pmeth_data *data = EVP_PKEY_CTX_get_data(ctx); + if (data->shared_ukm) OPENSSL_free(data->shared_ukm); + OPENSSL_free(data); + } + +/* --------------------- control functions ------------------------------*/ +static int pkey_gost_ctrl(EVP_PKEY_CTX *ctx, int type, int p1, void *p2) + { + struct gost_pmeth_data *pctx = (struct gost_pmeth_data*)EVP_PKEY_CTX_get_data(ctx); + switch (type) + { + case EVP_PKEY_CTRL_MD: + { + if (EVP_MD_type((const EVP_MD *)p2) != NID_id_GostR3411_94) + { + GOSTerr(GOST_F_PKEY_GOST_CTRL, GOST_R_INVALID_DIGEST_TYPE); + return 0; + } + pctx->md = (EVP_MD *)p2; + return 1; + } + break; + + case EVP_PKEY_CTRL_PKCS7_ENCRYPT: + case EVP_PKEY_CTRL_PKCS7_DECRYPT: + case EVP_PKEY_CTRL_PKCS7_SIGN: + return 1; + + case EVP_PKEY_CTRL_GOST_PARAMSET: + pctx->sign_param_nid = (int)p1; + return 1; + case EVP_PKEY_CTRL_SET_IV: + pctx->shared_ukm=OPENSSL_malloc((int)p1); + memcpy(pctx->shared_ukm,p2,(int) p1); + return 1; + case EVP_PKEY_CTRL_PEER_KEY: + if (p1 == 0 || p1 == 1) /* call from EVP_PKEY_derive_set_peer */ + return 1; + if (p1 == 2) /* TLS: peer key used? */ + return pctx->peer_key_used; + if (p1 == 3) /* TLS: peer key used! */ + return (pctx->peer_key_used = 1); + return -2; + } + return -2; + } + + +static int pkey_gost_ctrl94_str(EVP_PKEY_CTX *ctx, + const char *type, const char *value) + { + int param_nid=0; + if(!strcmp(type, param_ctrl_string)) + { + if (!value) + { + return 0; + } + if (strlen(value) == 1) + { + switch(toupper(value[0])) + { + case 'A': + param_nid = NID_id_GostR3410_94_CryptoPro_A_ParamSet; + break; + case 'B': + param_nid = NID_id_GostR3410_94_CryptoPro_B_ParamSet; + break; + case 'C': + param_nid = NID_id_GostR3410_94_CryptoPro_C_ParamSet; + break; + case 'D': + param_nid = NID_id_GostR3410_94_CryptoPro_D_ParamSet; + break; + default: + return 0; + break; + } + } + else if ((strlen(value) == 2) && (toupper(value[0]) == 'X')) + { + switch (toupper(value[1])) + { + case 'A': + param_nid = NID_id_GostR3410_94_CryptoPro_XchA_ParamSet; + break; + case 'B': + param_nid = NID_id_GostR3410_94_CryptoPro_XchB_ParamSet; + break; + case 'C': + param_nid = NID_id_GostR3410_94_CryptoPro_XchC_ParamSet; + break; + default: + return 0; + break; + } + } + else + { + R3410_params *p = R3410_paramset; + param_nid = OBJ_txt2nid(value); + if (param_nid == NID_undef) + { + return 0; + } + for (;p->nid != NID_undef;p++) + { + if (p->nid == param_nid) break; + } + if (p->nid == NID_undef) + { + GOSTerr(GOST_F_PKEY_GOST_CTRL94_STR, + GOST_R_INVALID_PARAMSET); + return 0; + } + } + + return pkey_gost_ctrl(ctx, EVP_PKEY_CTRL_GOST_PARAMSET, + param_nid, NULL); + } + return -2; + } + +static int pkey_gost_ctrl01_str(EVP_PKEY_CTX *ctx, + const char *type, const char *value) + { + int param_nid=0; + if(!strcmp(type, param_ctrl_string)) + { + if (!value) + { + return 0; + } + if (strlen(value) == 1) + { + switch(toupper(value[0])) + { + case 'A': + param_nid = NID_id_GostR3410_2001_CryptoPro_A_ParamSet; + break; + case 'B': + param_nid = NID_id_GostR3410_2001_CryptoPro_B_ParamSet; + break; + case 'C': + param_nid = NID_id_GostR3410_2001_CryptoPro_C_ParamSet; + break; + case '0': + param_nid = NID_id_GostR3410_2001_TestParamSet; + break; + default: + return 0; + break; + } + } + else if ((strlen(value) == 2) && (toupper(value[0]) == 'X')) + { + switch (toupper(value[1])) + { + case 'A': + param_nid = NID_id_GostR3410_2001_CryptoPro_XchA_ParamSet; + break; + case 'B': + param_nid = NID_id_GostR3410_2001_CryptoPro_XchB_ParamSet; + break; + default: + return 0; + break; + } + } + else + { + R3410_2001_params *p = R3410_2001_paramset; + param_nid = OBJ_txt2nid(value); + if (param_nid == NID_undef) + { + return 0; + } + for (;p->nid != NID_undef;p++) + { + if (p->nid == param_nid) break; + } + if (p->nid == NID_undef) + { + GOSTerr(GOST_F_PKEY_GOST_CTRL01_STR, + GOST_R_INVALID_PARAMSET); + return 0; + } + } + + return pkey_gost_ctrl(ctx, EVP_PKEY_CTRL_GOST_PARAMSET, + param_nid, NULL); + } + return -2; + } + +/* --------------------- key generation --------------------------------*/ + +static int pkey_gost_paramgen_init(EVP_PKEY_CTX *ctx) { + return 1; +} +static int pkey_gost94_paramgen(EVP_PKEY_CTX *ctx, EVP_PKEY *pkey) + { + struct gost_pmeth_data *data = EVP_PKEY_CTX_get_data(ctx); + DSA *dsa=NULL; + if (data->sign_param_nid == NID_undef) + { + GOSTerr(GOST_F_PKEY_GOST94_PARAMGEN, + GOST_R_NO_PARAMETERS_SET); + return 0; + } + dsa = DSA_new(); + if (!fill_GOST94_params(dsa,data->sign_param_nid)) + { + DSA_free(dsa); + return 0; + } + EVP_PKEY_assign(pkey,NID_id_GostR3410_94,dsa); + return 1; + } +static int pkey_gost01_paramgen(EVP_PKEY_CTX *ctx, EVP_PKEY *pkey) + { + struct gost_pmeth_data *data = EVP_PKEY_CTX_get_data(ctx); + EC_KEY *ec=NULL; + + if (data->sign_param_nid == NID_undef) + { + GOSTerr(GOST_F_PKEY_GOST01_PARAMGEN, + GOST_R_NO_PARAMETERS_SET); + return 0; + } + if (!ec) + ec = EC_KEY_new(); + if (!fill_GOST2001_params(ec,data->sign_param_nid)) + { + EC_KEY_free(ec); + return 0; + } + EVP_PKEY_assign(pkey,NID_id_GostR3410_2001,ec); + return 1; + } + +/* Generates Gost_R3410_94_cp key */ +static int pkey_gost94cp_keygen(EVP_PKEY_CTX *ctx, EVP_PKEY *pkey) + { + DSA *dsa; + if (!pkey_gost94_paramgen(ctx,pkey)) return 0; + dsa = EVP_PKEY_get0(pkey); + gost_sign_keygen(dsa); + return 1; + } + +/* Generates GOST_R3410 2001 key and assigns it using specified type */ +static int pkey_gost01cp_keygen(EVP_PKEY_CTX *ctx, EVP_PKEY *pkey) + { + EC_KEY *ec; + if (!pkey_gost01_paramgen(ctx,pkey)) return 0; + ec = EVP_PKEY_get0(pkey); + gost2001_keygen(ec); + return 1; + } + + + +/* ----------- sign callbacks --------------------------------------*/ + +static int pkey_gost94_cp_sign(EVP_PKEY_CTX *ctx, unsigned char *sig, size_t *siglen, + const unsigned char *tbs, size_t tbs_len) + { + DSA_SIG *unpacked_sig=NULL; + EVP_PKEY *pkey = EVP_PKEY_CTX_get0_pkey(ctx); + if (!siglen) return 0; + if (!sig) + { + *siglen= 64; /* better to check size of pkey->pkey.dsa-q */ + return 1; + } + unpacked_sig = gost_do_sign(tbs,tbs_len,EVP_PKEY_get0(pkey)); + if (!unpacked_sig) + { + return 0; + } + return pack_sign_cp(unpacked_sig,32,sig,siglen); + } + +static int pkey_gost01_cp_sign(EVP_PKEY_CTX *ctx, unsigned char *sig, size_t *siglen, + const unsigned char *tbs, size_t tbs_len) + { + DSA_SIG *unpacked_sig=NULL; + EVP_PKEY *pkey = EVP_PKEY_CTX_get0_pkey(ctx); + if (!siglen) return 0; + if (!sig) + { + *siglen= 64; /* better to check size of curve order*/ + return 1; + } + unpacked_sig = gost2001_do_sign(tbs,tbs_len,EVP_PKEY_get0(pkey)); + if (!unpacked_sig) + { + return 0; + } + return pack_sign_cp(unpacked_sig,32,sig,siglen); + } + +/* ------------------- verify callbacks ---------------------------*/ + +static int pkey_gost94_cp_verify(EVP_PKEY_CTX *ctx, const unsigned char *sig, + size_t siglen, const unsigned char *tbs, size_t tbs_len) + { + int ok = 0; + EVP_PKEY* pub_key = EVP_PKEY_CTX_get0_pkey(ctx); + DSA_SIG *s=unpack_cp_signature(sig,siglen); + if (!s) return 0; + if (pub_key) ok = gost_do_verify(tbs,tbs_len,s,EVP_PKEY_get0(pub_key)); + DSA_SIG_free(s); + return ok; + } + + +static int pkey_gost01_cp_verify(EVP_PKEY_CTX *ctx, const unsigned char *sig, + size_t siglen, const unsigned char *tbs, size_t tbs_len) + { + int ok = 0; + EVP_PKEY* pub_key = EVP_PKEY_CTX_get0_pkey(ctx); + DSA_SIG *s=unpack_cp_signature(sig,siglen); + if (!s) return 0; +#ifdef DEBUG_SIGN + fprintf(stderr,"R="); + BN_print_fp(stderr,s->r); + fprintf(stderr,"\nS="); + BN_print_fp(stderr,s->s); + fprintf(stderr,"\n"); +#endif + if (pub_key) ok = gost2001_do_verify(tbs,tbs_len,s,EVP_PKEY_get0(pub_key)); + DSA_SIG_free(s); + return ok; + } + +/* ------------- encrypt init -------------------------------------*/ +/* Generates ephermeral key */ +static int pkey_gost_encrypt_init(EVP_PKEY_CTX *ctx) + { + return 1; + } +/* --------------- Derive init ------------------------------------*/ +static int pkey_gost_derive_init(EVP_PKEY_CTX *ctx) +{ + return 1; +} +/* -------- PKEY_METHOD for GOST MAC algorithm --------------------*/ +static int pkey_gost_mac_init(EVP_PKEY_CTX *ctx) + { + struct gost_mac_pmeth_data *data; + data = OPENSSL_malloc(sizeof(struct gost_mac_pmeth_data)); + if (!data) return 0; + memset(data,0,sizeof(struct gost_mac_pmeth_data)); + EVP_PKEY_CTX_set_data(ctx,data); + return 1; + } +static void pkey_gost_mac_cleanup (EVP_PKEY_CTX *ctx) + { + struct gost_mac_pmeth_data *data = EVP_PKEY_CTX_get_data(ctx); + OPENSSL_free(data); + } +static int pkey_gost_mac_copy(EVP_PKEY_CTX *dst, EVP_PKEY_CTX *src) + { + struct gost_mac_pmeth_data *dst_data,*src_data; + if (!pkey_gost_mac_init(dst)) + { + return 0; + } + src_data = EVP_PKEY_CTX_get_data(src); + dst_data = EVP_PKEY_CTX_get_data(dst); + *dst_data = *src_data; + return 1; + } + +static int pkey_gost_mac_ctrl(EVP_PKEY_CTX *ctx, int type, int p1, void *p2) + { + struct gost_mac_pmeth_data *data = +(struct gost_mac_pmeth_data*)EVP_PKEY_CTX_get_data(ctx); + + switch (type) + { + case EVP_PKEY_CTRL_MD: + { + if (EVP_MD_type((const EVP_MD *)p2) != NID_id_Gost28147_89_MAC) + { + GOSTerr(GOST_F_PKEY_GOST_MAC_CTRL, GOST_R_INVALID_DIGEST_TYPE); + return 0; + } + data->md = (EVP_MD *)p2; + return 1; + } + break; + + case EVP_PKEY_CTRL_PKCS7_ENCRYPT: + case EVP_PKEY_CTRL_PKCS7_DECRYPT: + case EVP_PKEY_CTRL_PKCS7_SIGN: + return 1; + case EVP_PKEY_CTRL_SET_MAC_KEY: + if (p1 != 32) + { + GOSTerr(GOST_F_PKEY_GOST_MAC_CTRL, + GOST_R_INVALID_MAC_KEY_LENGTH); + return 0; + } + + memcpy(data->key,p2,32); + data->key_set = 1; + return 1; + case EVP_PKEY_CTRL_DIGESTINIT: + { + EVP_MD_CTX *mctx = p2; + void *key; + if (!data->key_set) + { + EVP_PKEY *pkey = EVP_PKEY_CTX_get0_pkey(ctx); + if (!pkey) + { + GOSTerr(GOST_F_PKEY_GOST_MAC_CTRL,GOST_R_MAC_KEY_NOT_SET); + return 0; + } + key = EVP_PKEY_get0(pkey); + if (!key) + { + GOSTerr(GOST_F_PKEY_GOST_MAC_CTRL,GOST_R_MAC_KEY_NOT_SET); + return 0; + } + } else { + key = &(data->key); + } + return mctx->digest->md_ctrl(mctx,EVP_MD_CTRL_SET_KEY,32,key); + } + } + return -2; + } +static int pkey_gost_mac_ctrl_str(EVP_PKEY_CTX *ctx, + const char *type, const char *value) + { + if (!strcmp(type, key_ctrl_string)) + { + if (strlen(value)!=32) + { + GOSTerr(GOST_F_PKEY_GOST_MAC_CTRL_STR, + GOST_R_INVALID_MAC_KEY_LENGTH); + return 0; + } + return pkey_gost_mac_ctrl(ctx, EVP_PKEY_CTRL_SET_MAC_KEY, + 32,(char *)value); + } + if (!strcmp(type, hexkey_ctrl_string)) + { + long keylen; int ret; + unsigned char *keybuf=string_to_hex(value,&keylen); + if (keylen != 32) + { + GOSTerr(GOST_F_PKEY_GOST_MAC_CTRL_STR, + GOST_R_INVALID_MAC_KEY_LENGTH); + return 0; + } + ret= pkey_gost_mac_ctrl(ctx, EVP_PKEY_CTRL_SET_MAC_KEY, + 32,keybuf); + OPENSSL_free(keybuf); + return ret; + + } + return -2; + } + +static int pkey_gost_mac_keygen(EVP_PKEY_CTX *ctx, EVP_PKEY *pkey) + { + struct gost_mac_pmeth_data *data = EVP_PKEY_CTX_get_data(ctx); + unsigned char *keydata; + if (!data->key_set) + { + GOSTerr(GOST_F_PKEY_GOST_MAC_KEYGEN,GOST_R_MAC_KEY_NOT_SET); + return 0; + } + keydata = OPENSSL_malloc(32); + memcpy(keydata,data->key,32); + EVP_PKEY_assign(pkey, NID_id_Gost28147_89_MAC, keydata); + return 1; + } + +static int pkey_gost_mac_signctx_init(EVP_PKEY_CTX *ctx, EVP_MD_CTX *mctx) + { + return 1; +} + +static int pkey_gost_mac_signctx(EVP_PKEY_CTX *ctx, unsigned char *sig, size_t *siglen, EVP_MD_CTX *mctx) + { + unsigned int tmpsiglen=*siglen; /* for platforms where sizeof(int)!=sizeof(size_t)*/ + int ret; + if (!sig) + { + *siglen = 4; + return 1; + } + ret=EVP_DigestFinal_ex(mctx,sig,&tmpsiglen); + *siglen = tmpsiglen; + return ret; + } +/* ----------------------------------------------------------------*/ +int register_pmeth_gost(int id, EVP_PKEY_METHOD **pmeth,int flags) + { + *pmeth = EVP_PKEY_meth_new(id, flags); + if (!*pmeth) return 0; + + switch (id) + { + case NID_id_GostR3410_94: + EVP_PKEY_meth_set_ctrl(*pmeth,pkey_gost_ctrl, pkey_gost_ctrl94_str); + EVP_PKEY_meth_set_keygen(*pmeth,NULL,pkey_gost94cp_keygen); + EVP_PKEY_meth_set_sign(*pmeth, NULL, pkey_gost94_cp_sign); + EVP_PKEY_meth_set_verify(*pmeth, NULL, pkey_gost94_cp_verify); + EVP_PKEY_meth_set_encrypt(*pmeth, + pkey_gost_encrypt_init, pkey_GOST94cp_encrypt); + EVP_PKEY_meth_set_decrypt(*pmeth, NULL, pkey_GOST94cp_decrypt); + EVP_PKEY_meth_set_derive(*pmeth, + pkey_gost_derive_init, pkey_gost94_derive); + EVP_PKEY_meth_set_paramgen(*pmeth, pkey_gost_paramgen_init,pkey_gost94_paramgen); + break; + case NID_id_GostR3410_2001: + EVP_PKEY_meth_set_ctrl(*pmeth,pkey_gost_ctrl, pkey_gost_ctrl01_str); + EVP_PKEY_meth_set_sign(*pmeth, NULL, pkey_gost01_cp_sign); + EVP_PKEY_meth_set_verify(*pmeth, NULL, pkey_gost01_cp_verify); + + EVP_PKEY_meth_set_keygen(*pmeth, NULL, pkey_gost01cp_keygen); + + EVP_PKEY_meth_set_encrypt(*pmeth, + pkey_gost_encrypt_init, pkey_GOST01cp_encrypt); + EVP_PKEY_meth_set_decrypt(*pmeth, NULL, pkey_GOST01cp_decrypt); + EVP_PKEY_meth_set_derive(*pmeth, + pkey_gost_derive_init, pkey_gost2001_derive); + EVP_PKEY_meth_set_paramgen(*pmeth, pkey_gost_paramgen_init,pkey_gost01_paramgen); + break; + case NID_id_Gost28147_89_MAC: + EVP_PKEY_meth_set_ctrl(*pmeth,pkey_gost_mac_ctrl, pkey_gost_mac_ctrl_str); + EVP_PKEY_meth_set_signctx(*pmeth,pkey_gost_mac_signctx_init, pkey_gost_mac_signctx); + EVP_PKEY_meth_set_keygen(*pmeth,NULL, pkey_gost_mac_keygen); + EVP_PKEY_meth_set_init(*pmeth,pkey_gost_mac_init); + EVP_PKEY_meth_set_cleanup(*pmeth,pkey_gost_mac_cleanup); + EVP_PKEY_meth_set_copy(*pmeth,pkey_gost_mac_copy); + return 1; + default: /*Unsupported method*/ + return 0; + } + EVP_PKEY_meth_set_init(*pmeth, pkey_gost_init); + EVP_PKEY_meth_set_cleanup(*pmeth, pkey_gost_cleanup); + + EVP_PKEY_meth_set_copy(*pmeth, pkey_gost_copy); + /*FIXME derive etc...*/ + + return 1; + } + diff --git a/node-v0.8.14/deps/openssl/openssl/engines/ccgost/gost_sign.c b/node-v0.8.14/deps/openssl/openssl/engines/ccgost/gost_sign.c new file mode 100644 index 0000000..4095654 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/engines/ccgost/gost_sign.c @@ -0,0 +1,321 @@ +/********************************************************************** + * gost_sign.c * + * Copyright (c) 2005-2006 Cryptocom LTD * + * This file is distributed under the same license as OpenSSL * + * * + * Implementation of GOST R 34.10-94 signature algorithm * + * for OpenSSL * + * Requires OpenSSL 0.9.9 for compilation * + **********************************************************************/ +#include +#include +#include +#include +#include + +#include "gost_params.h" +#include "gost_lcl.h" +#include "e_gost_err.h" + +#ifdef DEBUG_SIGN +void dump_signature(const char *message,const unsigned char *buffer,size_t len) + { + size_t i; + fprintf(stderr,"signature %s Length=%d",message,len); + for (i=0; iq,ctx); + if (BN_is_zero(tmp)) + { + BN_one(md); + } + do + { + do + { + /*Generate random number k less than q*/ + BN_rand_range(k,dsa->q); + /* generate r = (a^x mod p) mod q */ + BN_mod_exp(tmp,dsa->g, k, dsa->p,ctx); + if (!(newsig->r)) newsig->r=BN_new(); + BN_mod(newsig->r,tmp,dsa->q,ctx); + } + while (BN_is_zero(newsig->r)); + /* generate s = (xr + k(Hm)) mod q */ + BN_mod_mul(tmp,dsa->priv_key,newsig->r,dsa->q,ctx); + BN_mod_mul(tmp2,k,md,dsa->q,ctx); + if (!newsig->s) newsig->s=BN_new(); + BN_mod_add(newsig->s,tmp,tmp2,dsa->q,ctx); + } + while (BN_is_zero(newsig->s)); + err: + BN_free(md); + BN_CTX_end(ctx); + BN_CTX_free(ctx); + return newsig; + } + + +/* + * Packs signature according to Cryptocom rules + * and frees up DSA_SIG structure + */ +/* +int pack_sign_cc(DSA_SIG *s,int order,unsigned char *sig, size_t *siglen) + { + *siglen = 2*order; + memset(sig,0,*siglen); + store_bignum(s->r, sig,order); + store_bignum(s->s, sig + order,order); + dump_signature("serialized",sig,*siglen); + DSA_SIG_free(s); + return 1; + } +*/ +/* + * Packs signature according to Cryptopro rules + * and frees up DSA_SIG structure + */ +int pack_sign_cp(DSA_SIG *s,int order,unsigned char *sig, size_t *siglen) + { + *siglen = 2*order; + memset(sig,0,*siglen); + store_bignum(s->s, sig, order); + store_bignum(s->r, sig+order,order); + dump_signature("serialized",sig,*siglen); + DSA_SIG_free(s); + return 1; + } + +/* + * Verifies signature passed as DSA_SIG structure + * + */ + +int gost_do_verify(const unsigned char *dgst, int dgst_len, + DSA_SIG *sig, DSA *dsa) + { + BIGNUM *md, *tmp=NULL; + BIGNUM *q2=NULL; + BIGNUM *u=NULL,*v=NULL,*z1=NULL,*z2=NULL; + BIGNUM *tmp2=NULL,*tmp3=NULL; + int ok; + BN_CTX *ctx = BN_CTX_new(); + + BN_CTX_start(ctx); + if (BN_cmp(sig->s,dsa->q)>=1|| + BN_cmp(sig->r,dsa->q)>=1) + { + GOSTerr(GOST_F_GOST_DO_VERIFY,GOST_R_SIGNATURE_PARTS_GREATER_THAN_Q); + return 0; + } + md=hashsum2bn(dgst); + + tmp=BN_CTX_get(ctx); + v=BN_CTX_get(ctx); + q2=BN_CTX_get(ctx); + z1=BN_CTX_get(ctx); + z2=BN_CTX_get(ctx); + tmp2=BN_CTX_get(ctx); + tmp3=BN_CTX_get(ctx); + u = BN_CTX_get(ctx); + + BN_mod(tmp,md,dsa->q,ctx); + if (BN_is_zero(tmp)) + { + BN_one(md); + } + BN_copy(q2,dsa->q); + BN_sub_word(q2,2); + BN_mod_exp(v,md,q2,dsa->q,ctx); + BN_mod_mul(z1,sig->s,v,dsa->q,ctx); + BN_sub(tmp,dsa->q,sig->r); + BN_mod_mul(z2,tmp,v,dsa->p,ctx); + BN_mod_exp(tmp,dsa->g,z1,dsa->p,ctx); + BN_mod_exp(tmp2,dsa->pub_key,z2,dsa->p,ctx); + BN_mod_mul(tmp3,tmp,tmp2,dsa->p,ctx); + BN_mod(u,tmp3,dsa->q,ctx); + ok= BN_cmp(u,sig->r); + + BN_free(md); + BN_CTX_end(ctx); + BN_CTX_free(ctx); + if (ok!=0) + { + GOSTerr(GOST_F_GOST_DO_VERIFY,GOST_R_SIGNATURE_MISMATCH); + } + return (ok==0); + } + +/* + * Computes public keys for GOST R 34.10-94 algorithm + * + */ +int gost94_compute_public(DSA *dsa) + { + /* Now fill algorithm parameters with correct values */ + BN_CTX *ctx = BN_CTX_new(); + if (!dsa->g) + { + GOSTerr(GOST_F_GOST94_COMPUTE_PUBLIC,GOST_R_KEY_IS_NOT_INITALIZED); + return 0; + } + /* Compute public key y = a^x mod p */ + dsa->pub_key=BN_new(); + BN_mod_exp(dsa->pub_key, dsa->g,dsa->priv_key,dsa->p,ctx); + BN_CTX_free(ctx); + return 1; + } + +/* + * Fill GOST 94 params, searching them in R3410_paramset array + * by nid of paramset + * + */ +int fill_GOST94_params(DSA *dsa,int nid) + { + R3410_params *params=R3410_paramset; + while (params->nid!=NID_undef && params->nid !=nid) params++; + if (params->nid == NID_undef) + { + GOSTerr(GOST_F_FILL_GOST94_PARAMS,GOST_R_UNSUPPORTED_PARAMETER_SET); + return 0; + } +#define dump_signature(a,b,c) + if (dsa->p) { BN_free(dsa->p); } + dsa->p=NULL; + BN_dec2bn(&(dsa->p),params->p); + if (dsa->q) { BN_free(dsa->q); } + dsa->q=NULL; + BN_dec2bn(&(dsa->q),params->q); + if (dsa->g) { BN_free(dsa->g); } + dsa->g=NULL; + BN_dec2bn(&(dsa->g),params->a); + return 1; + } + +/* + * Generate GOST R 34.10-94 keypair + * + * + */ +int gost_sign_keygen(DSA *dsa) + { + dsa->priv_key = BN_new(); + BN_rand_range(dsa->priv_key,dsa->q); + return gost94_compute_public( dsa); + } + +/* Unpack signature according to cryptocom rules */ +/* +DSA_SIG *unpack_cc_signature(const unsigned char *sig,size_t siglen) + { + DSA_SIG *s; + s = DSA_SIG_new(); + if (s == NULL) + { + GOSTerr(GOST_F_UNPACK_CC_SIGNATURE,GOST_R_NO_MEMORY); + return(NULL); + } + s->r = getbnfrombuf(sig, siglen/2); + s->s = getbnfrombuf(sig + siglen/2, siglen/2); + return s; + } +*/ +/* Unpack signature according to cryptopro rules */ +DSA_SIG *unpack_cp_signature(const unsigned char *sig,size_t siglen) + { + DSA_SIG *s; + + s = DSA_SIG_new(); + if (s == NULL) + { + GOSTerr(GOST_F_UNPACK_CP_SIGNATURE,GOST_R_NO_MEMORY); + return NULL; + } + s->s = getbnfrombuf(sig , siglen/2); + s->r = getbnfrombuf(sig + siglen/2, siglen/2); + return s; + } + +/* Convert little-endian byte array into bignum */ +BIGNUM *hashsum2bn(const unsigned char *dgst) + { + unsigned char buf[32]; + int i; + for (i=0;i<32;i++) + { + buf[31-i]=dgst[i]; + } + return getbnfrombuf(buf,32); + } + +/* Convert byte buffer to bignum, skipping leading zeros*/ +BIGNUM *getbnfrombuf(const unsigned char *buf,size_t len) + { + while (*buf==0&&len>0) + { + buf++; len--; + } + if (len) + { + return BN_bin2bn(buf,len,NULL); + } + else + { + BIGNUM *b=BN_new(); + BN_zero(b); + return b; + } + } + +/* Pack bignum into byte buffer of given size, filling all leading bytes + * by zeros */ +int store_bignum(BIGNUM *bn, unsigned char *buf,int len) + { + int bytes = BN_num_bytes(bn); + if (bytes>len) return 0; + memset(buf,0,len); + BN_bn2bin(bn,buf+len-bytes); + return 1; + } diff --git a/node-v0.8.14/deps/openssl/openssl/engines/ccgost/gosthash.c b/node-v0.8.14/deps/openssl/openssl/engines/ccgost/gosthash.c new file mode 100644 index 0000000..a5c0662 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/engines/ccgost/gosthash.c @@ -0,0 +1,255 @@ +/********************************************************************** + * gosthash.c * + * Copyright (c) 2005-2006 Cryptocom LTD * + * This file is distributed under the same license as OpenSSL * + * * + * Implementation of GOST R 34.11-94 hash function * + * uses on gost89.c and gost89.h Doesn't need OpenSSL * + **********************************************************************/ +#include + +#include "gost89.h" +#include "gosthash.h" + + +/* Use OPENSSL_malloc for memory allocation if compiled with + * -DOPENSSL_BUILD, and libc malloc otherwise + */ +#ifndef MYALLOC +# ifdef OPENSSL_BUILD +# include +# define MYALLOC(size) OPENSSL_malloc(size) +# define MYFREE(ptr) OPENSSL_free(ptr) +# else +# define MYALLOC(size) malloc(size) +# define MYFREE(ptr) free(ptr) +# endif +#endif +/* Following functions are various bit meshing routines used in + * GOST R 34.11-94 algorithms */ +static void swap_bytes (byte *w, byte *k) + { + int i,j; + for (i=0;i<4;i++) + for (j=0;j<8;j++) + k[i+4*j]=w[8*i+j]; + + } + +/* was A_A */ +static void circle_xor8 (const byte *w, byte *k) + { + byte buf[8]; + int i; + memcpy(buf,w,8); + memcpy(k,w+8,24); + for(i=0;i<8;i++) + k[i+24]=buf[i]^k[i]; + } + +/* was R_R */ +static void transform_3 (byte *data) + { + unsigned short int acc; + acc=(data[0]^data[2]^data[4]^data[6]^data[24]^data[30])| + ((data[1]^data[3]^data[5]^data[7]^data[25]^data[31])<<8); + memmove(data,data+2,30); + data[30]=acc&0xff; + data[31]=acc>>8; + } + +/* Adds blocks of N bytes modulo 2**(8*n). Returns carry*/ +static int add_blocks(int n,byte *left, const byte *right) + { + int i; + int carry=0; + int sum; + for (i=0;i>8; + } + return carry; + } + +/* Xor two sequences of bytes */ +static void xor_blocks (byte *result,const byte *a,const byte *b,size_t len) + { + size_t i; + for (i=0;icipher_ctx = (gost_ctx *)MYALLOC(sizeof(gost_ctx)); + if (!ctx->cipher_ctx) + { + return 0; + } + gost_init(ctx->cipher_ctx,subst_block); + return 1; + } + +/* + * Free cipher CTX if it is dynamically allocated. Do not use + * if cipher ctx is statically allocated as in OpenSSL implementation of + * GOST hash algroritm + * + */ +void done_gost_hash_ctx(gost_hash_ctx *ctx) + { + /* No need to use gost_destroy, because cipher keys are not really + * secret when hashing */ + MYFREE(ctx->cipher_ctx); + } + +/* + * reset state of hash context to begin hashing new message + */ +int start_hash(gost_hash_ctx *ctx) + { + if (!ctx->cipher_ctx) return 0; + memset(&(ctx->H),0,32); + memset(&(ctx->S),0,32); + ctx->len = 0L; + ctx->left=0; + return 1; + } + +/* + * Hash block of arbitrary length + * + * + */ +int hash_block(gost_hash_ctx *ctx,const byte *block, size_t length) + { + const byte *curptr=block; + const byte *barrier=block+(length-32);/* Last byte we can safely hash*/ + if (ctx->left) + { + /*There are some bytes from previous step*/ + unsigned int add_bytes = 32-ctx->left; + if (add_bytes>length) + { + add_bytes = length; + } + memcpy(&(ctx->remainder[ctx->left]),block,add_bytes); + ctx->left+=add_bytes; + if (ctx->left<32) + { + return 1; + } + curptr=block+add_bytes; + hash_step(ctx->cipher_ctx,ctx->H,ctx->remainder); + add_blocks(32,ctx->S,ctx->remainder); + ctx->len+=32; + ctx->left=0; + } + while (curptr<=barrier) + { + hash_step(ctx->cipher_ctx,ctx->H,curptr); + + add_blocks(32,ctx->S,curptr); + ctx->len+=32; + curptr+=32; + } + if (curptr!=block+length) + { + ctx->left=block+length-curptr; + memcpy(ctx->remainder,curptr,ctx->left); + } + return 1; + } + +/* + * Compute hash value from current state of ctx + * state of hash ctx becomes invalid and cannot be used for further + * hashing. + */ +int finish_hash(gost_hash_ctx *ctx,byte *hashval) + { + byte buf[32]; + byte H[32]; + byte S[32]; + ghosthash_len fin_len=ctx->len; + byte *bptr; + memcpy(H,ctx->H,32); + memcpy(S,ctx->S,32); + if (ctx->left) + { + memset(buf,0,32); + memcpy(buf,ctx->remainder,ctx->left); + hash_step(ctx->cipher_ctx,H,buf); + add_blocks(32,S,buf); + fin_len+=ctx->left; + } + memset(buf,0,32); + bptr=buf; + fin_len<<=3; /* Hash length in BITS!!*/ + while(fin_len>0) + { + *(bptr++)=(byte)(fin_len&0xFF); + fin_len>>=8; + }; + hash_step(ctx->cipher_ctx,H,buf); + hash_step(ctx->cipher_ctx,H,S); + memcpy(hashval,H,32); + return 1; + } diff --git a/node-v0.8.14/deps/openssl/openssl/engines/ccgost/gosthash.h b/node-v0.8.14/deps/openssl/openssl/engines/ccgost/gosthash.h new file mode 100644 index 0000000..4a2e441 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/engines/ccgost/gosthash.h @@ -0,0 +1,48 @@ +/********************************************************************** + * gosthash.h * + * Copyright (c) 2005-2006 Cryptocom LTD * + * This file is distributed under the same license as OpenSSL * + * * + * Declaration of GOST R 34.11-94 hash functions * + * uses and gost89.h Doesn't need OpenSSL * + **********************************************************************/ +#ifndef GOSTHASH_H +#define GOSTHASH_H +#include "gost89.h" +#include + +#if (defined(_WIN32) || defined(_WIN64)) && !defined(__MINGW32__) +typedef __int64 ghosthash_len; +#elif defined(__arch64__) +typedef long ghosthash_len; +#else +typedef long long ghosthash_len; +#endif + +typedef struct gost_hash_ctx { + ghosthash_len len; + gost_ctx *cipher_ctx; + int left; + byte H[32]; + byte S[32]; + byte remainder[32]; +} gost_hash_ctx; + + +/* Initalizes gost hash ctx, including creation of gost cipher ctx */ + +int init_gost_hash_ctx(gost_hash_ctx *ctx, const gost_subst_block *subst_block); +void done_gost_hash_ctx(gost_hash_ctx *ctx); + +/* Cleans up all fields, except cipher ctx preparing ctx for computing + * of new hash value */ +int start_hash(gost_hash_ctx *ctx); + +/* Hashes block of data */ +int hash_block(gost_hash_ctx *ctx, const byte *block, size_t length); + +/* Finalizes computation of hash and fills buffer (which should be at + * least 32 bytes long) with value of computed hash. */ +int finish_hash(gost_hash_ctx *ctx, byte *hashval); + +#endif diff --git a/node-v0.8.14/deps/openssl/openssl/engines/ccgost/gostsum.c b/node-v0.8.14/deps/openssl/openssl/engines/ccgost/gostsum.c new file mode 100644 index 0000000..d57112e --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/engines/ccgost/gostsum.c @@ -0,0 +1,210 @@ +/********************************************************************** + * gostsum.c * + * Copyright (c) 2005-2006 Cryptocom LTD * + * This file is distributed under the same license as OpenSSL * + * * + * Almost drop-in replacement for md5sum and sha1sum * + * which computes GOST R 34.11-94 hashsum instead * + * * + **********************************************************************/ +#include +#include +#include +#include +#include +#include +#include "gosthash.h" +#define BUF_SIZE 262144 +int hash_file(gost_hash_ctx *ctx,char *filename,char *sum,int mode); +int hash_stream(gost_hash_ctx *ctx,int fd, char *sum); +int get_line(FILE *f,char *hash,char *filename); +void help() + { + fprintf(stderr,"gostsum [-bvt] [-c [file]]| [files]\n" + "\t-c check message digests (default is generate)\n" + "\t-v verbose, print file names when checking\n" + "\t-b read files in binary mode\n" + "\t-t use test GOST paramset (default is CryptoPro paramset)\n" + "The input for -c should be the list of message digests and file names\n" + "that is printed on stdout by this program when it generates digests.\n"); + exit(3); + } + +#ifndef O_BINARY +#define O_BINARY 0 +#endif + +int main(int argc,char **argv) + { + int c,i; + int verbose=0; + int errors=0; + int open_mode = O_RDONLY; + gost_subst_block *b= &GostR3411_94_CryptoProParamSet; + FILE *check_file = NULL; + gost_hash_ctx ctx; + + while( (c=getopt(argc,argv,"bc::tv"))!=-1) + { + switch (c) + { + case 'v': verbose=1; break; + case 't': b= &GostR3411_94_TestParamSet; break; + case 'b': open_mode |= O_BINARY; break; + case 'c': + if (optarg) + { + check_file = fopen(optarg,"r"); + if (!check_file) + { + perror(optarg); + exit(2); + } + } + else + { + check_file= stdin; + } + break; + default: + fprintf(stderr,"invalid option %c",optopt); + help(); + } + } + init_gost_hash_ctx(&ctx,b); + if (check_file) + { + char inhash[65],calcsum[65],filename[PATH_MAX]; + int failcount=0,count=0;; + if (check_file==stdin && optind0) + { + hash_block(ctx,buffer,bytes); + } + if (bytes<0) + { + return 0; + } + finish_hash(ctx,buffer); + for (i=0;i<32;i++) + { + sprintf(sum+2*i,"%02x",buffer[31-i]); + } + return 1; + } + +int get_line(FILE *f,char *hash,char *filename) + { + int i; + if (fread(hash,1,64,f)<64) return 0; + hash[64]=0; + for (i=0;i<64;i++) + { + if (hash[i]<'0' || (hash[i]>'9' && hash[i]<'A') || (hash[i]>'F' + && hash[i]<'a')||hash[i]>'f') + { + fprintf(stderr,"Not a hash value '%s'\n",hash); + return 0; + } + } + if (fgetc(f)!=' ') + { + fprintf(stderr,"Malformed input line\n"); + return 0; + } + i=strlen(fgets(filename,PATH_MAX,f)); + while (filename[--i]=='\n'||filename[i]=='\r') filename[i]=0; + return 1; + } diff --git a/node-v0.8.14/deps/openssl/openssl/engines/e_4758cca.c b/node-v0.8.14/deps/openssl/openssl/engines/e_4758cca.c new file mode 100644 index 0000000..443182b --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/engines/e_4758cca.c @@ -0,0 +1,987 @@ +/* Author: Maurice Gittens */ +/* ==================================================================== + * Copyright (c) 1999 The OpenSSL Project. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. All advertising materials mentioning features or use of this + * software must display the following acknowledgment: + * "This product includes software developed by the OpenSSL Project + * for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)" + * + * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to + * endorse or promote products derived from this software without + * prior written permission. For written permission, please contact + * licensing@OpenSSL.org. + * + * 5. Products derived from this software may not be called "OpenSSL" + * nor may "OpenSSL" appear in their names without prior written + * permission of the OpenSSL Project. + * + * 6. Redistributions of any form whatsoever must retain the following + * acknowledgment: + * "This product includes software developed by the OpenSSL Project + * for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)" + * + * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY + * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR + * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, + * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * ==================================================================== + * + * This product includes cryptographic software written by Eric Young + * (eay@cryptsoft.com). This product includes software written by Tim + * Hudson (tjh@cryptsoft.com). + * + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#ifndef OPENSSL_NO_RSA +#include +#endif +#include + +#ifndef OPENSSL_NO_HW +#ifndef OPENSSL_NO_HW_4758_CCA + +#ifdef FLAT_INC +#include "hw_4758_cca.h" +#else +#include "vendor_defns/hw_4758_cca.h" +#endif + +#include "e_4758cca_err.c" + +static int ibm_4758_cca_destroy(ENGINE *e); +static int ibm_4758_cca_init(ENGINE *e); +static int ibm_4758_cca_finish(ENGINE *e); +static int ibm_4758_cca_ctrl(ENGINE *e, int cmd, long i, void *p, void (*f)(void)); + +/* rsa functions */ +/*---------------*/ +#ifndef OPENSSL_NO_RSA +static int cca_rsa_pub_enc(int flen, const unsigned char *from, + unsigned char *to, RSA *rsa,int padding); +static int cca_rsa_priv_dec(int flen, const unsigned char *from, + unsigned char *to, RSA *rsa,int padding); +static int cca_rsa_sign(int type, const unsigned char *m, unsigned int m_len, + unsigned char *sigret, unsigned int *siglen, const RSA *rsa); +static int cca_rsa_verify(int dtype, const unsigned char *m, unsigned int m_len, + const unsigned char *sigbuf, unsigned int siglen, const RSA *rsa); + +/* utility functions */ +/*-----------------------*/ +static EVP_PKEY *ibm_4758_load_privkey(ENGINE*, const char*, + UI_METHOD *ui_method, void *callback_data); +static EVP_PKEY *ibm_4758_load_pubkey(ENGINE*, const char*, + UI_METHOD *ui_method, void *callback_data); + +static int getModulusAndExponent(const unsigned char *token, long *exponentLength, + unsigned char *exponent, long *modulusLength, + long *modulusFieldLength, unsigned char *modulus); +#endif + +/* RAND number functions */ +/*-----------------------*/ +static int cca_get_random_bytes(unsigned char*, int); +static int cca_random_status(void); + +#ifndef OPENSSL_NO_RSA +static void cca_ex_free(void *obj, void *item, CRYPTO_EX_DATA *ad, + int idx,long argl, void *argp); +#endif + +/* Function pointers for CCA verbs */ +/*---------------------------------*/ +#ifndef OPENSSL_NO_RSA +static F_KEYRECORDREAD keyRecordRead; +static F_DIGITALSIGNATUREGENERATE digitalSignatureGenerate; +static F_DIGITALSIGNATUREVERIFY digitalSignatureVerify; +static F_PUBLICKEYEXTRACT publicKeyExtract; +static F_PKAENCRYPT pkaEncrypt; +static F_PKADECRYPT pkaDecrypt; +#endif +static F_RANDOMNUMBERGENERATE randomNumberGenerate; + +/* static variables */ +/*------------------*/ +static const char *CCA4758_LIB_NAME = NULL; +static const char *get_CCA4758_LIB_NAME(void) + { + if(CCA4758_LIB_NAME) + return CCA4758_LIB_NAME; + return CCA_LIB_NAME; + } +static void free_CCA4758_LIB_NAME(void) + { + if(CCA4758_LIB_NAME) + OPENSSL_free((void*)CCA4758_LIB_NAME); + CCA4758_LIB_NAME = NULL; + } +static long set_CCA4758_LIB_NAME(const char *name) + { + free_CCA4758_LIB_NAME(); + return (((CCA4758_LIB_NAME = BUF_strdup(name)) != NULL) ? 1 : 0); + } +#ifndef OPENSSL_NO_RSA +static const char* n_keyRecordRead = CSNDKRR; +static const char* n_digitalSignatureGenerate = CSNDDSG; +static const char* n_digitalSignatureVerify = CSNDDSV; +static const char* n_publicKeyExtract = CSNDPKX; +static const char* n_pkaEncrypt = CSNDPKE; +static const char* n_pkaDecrypt = CSNDPKD; +#endif +static const char* n_randomNumberGenerate = CSNBRNG; + +#ifndef OPENSSL_NO_RSA +static int hndidx = -1; +#endif +static DSO *dso = NULL; + +/* openssl engine initialization structures */ +/*------------------------------------------*/ + +#define CCA4758_CMD_SO_PATH ENGINE_CMD_BASE +static const ENGINE_CMD_DEFN cca4758_cmd_defns[] = { + {CCA4758_CMD_SO_PATH, + "SO_PATH", + "Specifies the path to the '4758cca' shared library", + ENGINE_CMD_FLAG_STRING}, + {0, NULL, NULL, 0} + }; + +#ifndef OPENSSL_NO_RSA +static RSA_METHOD ibm_4758_cca_rsa = + { + "IBM 4758 CCA RSA method", + cca_rsa_pub_enc, + NULL, + NULL, + cca_rsa_priv_dec, + NULL, /*rsa_mod_exp,*/ + NULL, /*mod_exp_mont,*/ + NULL, /* init */ + NULL, /* finish */ + RSA_FLAG_SIGN_VER, /* flags */ + NULL, /* app_data */ + cca_rsa_sign, /* rsa_sign */ + cca_rsa_verify, /* rsa_verify */ + NULL /* rsa_keygen */ + }; +#endif + +static RAND_METHOD ibm_4758_cca_rand = + { + /* "IBM 4758 RAND method", */ + NULL, /* seed */ + cca_get_random_bytes, /* get random bytes from the card */ + NULL, /* cleanup */ + NULL, /* add */ + cca_get_random_bytes, /* pseudo rand */ + cca_random_status, /* status */ + }; + +static const char *engine_4758_cca_id = "4758cca"; +static const char *engine_4758_cca_name = "IBM 4758 CCA hardware engine support"; +#ifndef OPENSSL_NO_DYNAMIC_ENGINE +/* Compatibility hack, the dynamic library uses this form in the path */ +static const char *engine_4758_cca_id_alt = "4758_cca"; +#endif + +/* engine implementation */ +/*-----------------------*/ +static int bind_helper(ENGINE *e) + { + if(!ENGINE_set_id(e, engine_4758_cca_id) || + !ENGINE_set_name(e, engine_4758_cca_name) || +#ifndef OPENSSL_NO_RSA + !ENGINE_set_RSA(e, &ibm_4758_cca_rsa) || +#endif + !ENGINE_set_RAND(e, &ibm_4758_cca_rand) || + !ENGINE_set_destroy_function(e, ibm_4758_cca_destroy) || + !ENGINE_set_init_function(e, ibm_4758_cca_init) || + !ENGINE_set_finish_function(e, ibm_4758_cca_finish) || + !ENGINE_set_ctrl_function(e, ibm_4758_cca_ctrl) || +#ifndef OPENSSL_NO_RSA + !ENGINE_set_load_privkey_function(e, ibm_4758_load_privkey) || + !ENGINE_set_load_pubkey_function(e, ibm_4758_load_pubkey) || +#endif + !ENGINE_set_cmd_defns(e, cca4758_cmd_defns)) + return 0; + /* Ensure the error handling is set up */ + ERR_load_CCA4758_strings(); + return 1; + } + +#ifdef OPENSSL_NO_DYNAMIC_ENGINE +static ENGINE *engine_4758_cca(void) + { + ENGINE *ret = ENGINE_new(); + if(!ret) + return NULL; + if(!bind_helper(ret)) + { + ENGINE_free(ret); + return NULL; + } + return ret; + } + +void ENGINE_load_4758cca(void) + { + ENGINE *e_4758 = engine_4758_cca(); + if (!e_4758) return; + ENGINE_add(e_4758); + ENGINE_free(e_4758); + ERR_clear_error(); + } +#endif + +static int ibm_4758_cca_destroy(ENGINE *e) + { + ERR_unload_CCA4758_strings(); + free_CCA4758_LIB_NAME(); + return 1; + } + +static int ibm_4758_cca_init(ENGINE *e) + { + if(dso) + { + CCA4758err(CCA4758_F_IBM_4758_CCA_INIT,CCA4758_R_ALREADY_LOADED); + goto err; + } + + dso = DSO_load(NULL, get_CCA4758_LIB_NAME(), NULL, 0); + if(!dso) + { + CCA4758err(CCA4758_F_IBM_4758_CCA_INIT,CCA4758_R_DSO_FAILURE); + goto err; + } + +#ifndef OPENSSL_NO_RSA + if(!(keyRecordRead = (F_KEYRECORDREAD) + DSO_bind_func(dso, n_keyRecordRead)) || + !(randomNumberGenerate = (F_RANDOMNUMBERGENERATE) + DSO_bind_func(dso, n_randomNumberGenerate)) || + !(digitalSignatureGenerate = (F_DIGITALSIGNATUREGENERATE) + DSO_bind_func(dso, n_digitalSignatureGenerate)) || + !(digitalSignatureVerify = (F_DIGITALSIGNATUREVERIFY) + DSO_bind_func(dso, n_digitalSignatureVerify)) || + !(publicKeyExtract = (F_PUBLICKEYEXTRACT) + DSO_bind_func(dso, n_publicKeyExtract)) || + !(pkaEncrypt = (F_PKAENCRYPT) + DSO_bind_func(dso, n_pkaEncrypt)) || + !(pkaDecrypt = (F_PKADECRYPT) + DSO_bind_func(dso, n_pkaDecrypt))) + { + CCA4758err(CCA4758_F_IBM_4758_CCA_INIT,CCA4758_R_DSO_FAILURE); + goto err; + } +#else + if(!(randomNumberGenerate = (F_RANDOMNUMBERGENERATE) + DSO_bind_func(dso, n_randomNumberGenerate))) + { + CCA4758err(CCA4758_F_IBM_4758_CCA_INIT,CCA4758_R_DSO_FAILURE); + goto err; + } +#endif + +#ifndef OPENSSL_NO_RSA + hndidx = RSA_get_ex_new_index(0, "IBM 4758 CCA RSA key handle", + NULL, NULL, cca_ex_free); +#endif + + return 1; +err: + if(dso) + DSO_free(dso); + dso = NULL; + +#ifndef OPENSSL_NO_RSA + keyRecordRead = (F_KEYRECORDREAD)0; + digitalSignatureGenerate = (F_DIGITALSIGNATUREGENERATE)0; + digitalSignatureVerify = (F_DIGITALSIGNATUREVERIFY)0; + publicKeyExtract = (F_PUBLICKEYEXTRACT)0; + pkaEncrypt = (F_PKAENCRYPT)0; + pkaDecrypt = (F_PKADECRYPT)0; +#endif + randomNumberGenerate = (F_RANDOMNUMBERGENERATE)0; + return 0; + } + +static int ibm_4758_cca_finish(ENGINE *e) + { + free_CCA4758_LIB_NAME(); + if(!dso) + { + CCA4758err(CCA4758_F_IBM_4758_CCA_FINISH, + CCA4758_R_NOT_LOADED); + return 0; + } + if(!DSO_free(dso)) + { + CCA4758err(CCA4758_F_IBM_4758_CCA_FINISH, + CCA4758_R_UNIT_FAILURE); + return 0; + } + dso = NULL; +#ifndef OPENSSL_NO_RSA + keyRecordRead = (F_KEYRECORDREAD)0; + randomNumberGenerate = (F_RANDOMNUMBERGENERATE)0; + digitalSignatureGenerate = (F_DIGITALSIGNATUREGENERATE)0; + digitalSignatureVerify = (F_DIGITALSIGNATUREVERIFY)0; + publicKeyExtract = (F_PUBLICKEYEXTRACT)0; + pkaEncrypt = (F_PKAENCRYPT)0; + pkaDecrypt = (F_PKADECRYPT)0; +#endif + randomNumberGenerate = (F_RANDOMNUMBERGENERATE)0; + return 1; + } + +static int ibm_4758_cca_ctrl(ENGINE *e, int cmd, long i, void *p, void (*f)(void)) + { + int initialised = ((dso == NULL) ? 0 : 1); + switch(cmd) + { + case CCA4758_CMD_SO_PATH: + if(p == NULL) + { + CCA4758err(CCA4758_F_IBM_4758_CCA_CTRL, + ERR_R_PASSED_NULL_PARAMETER); + return 0; + } + if(initialised) + { + CCA4758err(CCA4758_F_IBM_4758_CCA_CTRL, + CCA4758_R_ALREADY_LOADED); + return 0; + } + return set_CCA4758_LIB_NAME((const char *)p); + default: + break; + } + CCA4758err(CCA4758_F_IBM_4758_CCA_CTRL, + CCA4758_R_COMMAND_NOT_IMPLEMENTED); + return 0; + } + +#ifndef OPENSSL_NO_RSA + +#define MAX_CCA_PKA_TOKEN_SIZE 2500 + +static EVP_PKEY *ibm_4758_load_privkey(ENGINE* e, const char* key_id, + UI_METHOD *ui_method, void *callback_data) + { + RSA *rtmp = NULL; + EVP_PKEY *res = NULL; + unsigned char* keyToken = NULL; + unsigned char pubKeyToken[MAX_CCA_PKA_TOKEN_SIZE]; + long pubKeyTokenLength = MAX_CCA_PKA_TOKEN_SIZE; + long keyTokenLength = MAX_CCA_PKA_TOKEN_SIZE; + long returnCode; + long reasonCode; + long exitDataLength = 0; + long ruleArrayLength = 0; + unsigned char exitData[8]; + unsigned char ruleArray[8]; + unsigned char keyLabel[64]; + unsigned long keyLabelLength = strlen(key_id); + unsigned char modulus[256]; + long modulusFieldLength = sizeof(modulus); + long modulusLength = 0; + unsigned char exponent[256]; + long exponentLength = sizeof(exponent); + + if (keyLabelLength > sizeof(keyLabel)) + { + CCA4758err(CCA4758_F_IBM_4758_LOAD_PRIVKEY, + CCA4758_R_SIZE_TOO_LARGE_OR_TOO_SMALL); + return NULL; + } + + memset(keyLabel,' ', sizeof(keyLabel)); + memcpy(keyLabel, key_id, keyLabelLength); + + keyToken = OPENSSL_malloc(MAX_CCA_PKA_TOKEN_SIZE + sizeof(long)); + if (!keyToken) + { + CCA4758err(CCA4758_F_IBM_4758_LOAD_PRIVKEY, + ERR_R_MALLOC_FAILURE); + goto err; + } + + keyRecordRead(&returnCode, &reasonCode, &exitDataLength, + exitData, &ruleArrayLength, ruleArray, keyLabel, + &keyTokenLength, keyToken+sizeof(long)); + + if (returnCode) + { + CCA4758err(CCA4758_F_IBM_4758_LOAD_PRIVKEY, + CCA4758_R_FAILED_LOADING_PRIVATE_KEY); + goto err; + } + + publicKeyExtract(&returnCode, &reasonCode, &exitDataLength, + exitData, &ruleArrayLength, ruleArray, &keyTokenLength, + keyToken+sizeof(long), &pubKeyTokenLength, pubKeyToken); + + if (returnCode) + { + CCA4758err(CCA4758_F_IBM_4758_LOAD_PRIVKEY, + CCA4758_R_FAILED_LOADING_PRIVATE_KEY); + goto err; + } + + if (!getModulusAndExponent(pubKeyToken, &exponentLength, + exponent, &modulusLength, &modulusFieldLength, + modulus)) + { + CCA4758err(CCA4758_F_IBM_4758_LOAD_PRIVKEY, + CCA4758_R_FAILED_LOADING_PRIVATE_KEY); + goto err; + } + + (*(long*)keyToken) = keyTokenLength; + rtmp = RSA_new_method(e); + RSA_set_ex_data(rtmp, hndidx, (char *)keyToken); + + rtmp->e = BN_bin2bn(exponent, exponentLength, NULL); + rtmp->n = BN_bin2bn(modulus, modulusFieldLength, NULL); + rtmp->flags |= RSA_FLAG_EXT_PKEY; + + res = EVP_PKEY_new(); + EVP_PKEY_assign_RSA(res, rtmp); + + return res; +err: + if (keyToken) + OPENSSL_free(keyToken); + return NULL; + } + +static EVP_PKEY *ibm_4758_load_pubkey(ENGINE* e, const char* key_id, + UI_METHOD *ui_method, void *callback_data) + { + RSA *rtmp = NULL; + EVP_PKEY *res = NULL; + unsigned char* keyToken = NULL; + long keyTokenLength = MAX_CCA_PKA_TOKEN_SIZE; + long returnCode; + long reasonCode; + long exitDataLength = 0; + long ruleArrayLength = 0; + unsigned char exitData[8]; + unsigned char ruleArray[8]; + unsigned char keyLabel[64]; + unsigned long keyLabelLength = strlen(key_id); + unsigned char modulus[512]; + long modulusFieldLength = sizeof(modulus); + long modulusLength = 0; + unsigned char exponent[512]; + long exponentLength = sizeof(exponent); + + if (keyLabelLength > sizeof(keyLabel)) + { + CCA4758err(CCA4758_F_IBM_4758_LOAD_PUBKEY, + CCA4758_R_SIZE_TOO_LARGE_OR_TOO_SMALL); + return NULL; + } + + memset(keyLabel,' ', sizeof(keyLabel)); + memcpy(keyLabel, key_id, keyLabelLength); + + keyToken = OPENSSL_malloc(MAX_CCA_PKA_TOKEN_SIZE + sizeof(long)); + if (!keyToken) + { + CCA4758err(CCA4758_F_IBM_4758_LOAD_PUBKEY, + ERR_R_MALLOC_FAILURE); + goto err; + } + + keyRecordRead(&returnCode, &reasonCode, &exitDataLength, exitData, + &ruleArrayLength, ruleArray, keyLabel, &keyTokenLength, + keyToken+sizeof(long)); + + if (returnCode) + { + CCA4758err(CCA4758_F_IBM_4758_LOAD_PUBKEY, + ERR_R_MALLOC_FAILURE); + goto err; + } + + if (!getModulusAndExponent(keyToken+sizeof(long), &exponentLength, + exponent, &modulusLength, &modulusFieldLength, modulus)) + { + CCA4758err(CCA4758_F_IBM_4758_LOAD_PUBKEY, + CCA4758_R_FAILED_LOADING_PUBLIC_KEY); + goto err; + } + + (*(long*)keyToken) = keyTokenLength; + rtmp = RSA_new_method(e); + RSA_set_ex_data(rtmp, hndidx, (char *)keyToken); + rtmp->e = BN_bin2bn(exponent, exponentLength, NULL); + rtmp->n = BN_bin2bn(modulus, modulusFieldLength, NULL); + rtmp->flags |= RSA_FLAG_EXT_PKEY; + res = EVP_PKEY_new(); + EVP_PKEY_assign_RSA(res, rtmp); + + return res; +err: + if (keyToken) + OPENSSL_free(keyToken); + return NULL; + } + +static int cca_rsa_pub_enc(int flen, const unsigned char *from, + unsigned char *to, RSA *rsa,int padding) + { + long returnCode; + long reasonCode; + long lflen = flen; + long exitDataLength = 0; + unsigned char exitData[8]; + long ruleArrayLength = 1; + unsigned char ruleArray[8] = "PKCS-1.2"; + long dataStructureLength = 0; + unsigned char dataStructure[8]; + long outputLength = RSA_size(rsa); + long keyTokenLength; + unsigned char* keyToken = (unsigned char*)RSA_get_ex_data(rsa, hndidx); + + keyTokenLength = *(long*)keyToken; + keyToken+=sizeof(long); + + pkaEncrypt(&returnCode, &reasonCode, &exitDataLength, exitData, + &ruleArrayLength, ruleArray, &lflen, (unsigned char*)from, + &dataStructureLength, dataStructure, &keyTokenLength, + keyToken, &outputLength, to); + + if (returnCode || reasonCode) + return -(returnCode << 16 | reasonCode); + return outputLength; + } + +static int cca_rsa_priv_dec(int flen, const unsigned char *from, + unsigned char *to, RSA *rsa,int padding) + { + long returnCode; + long reasonCode; + long lflen = flen; + long exitDataLength = 0; + unsigned char exitData[8]; + long ruleArrayLength = 1; + unsigned char ruleArray[8] = "PKCS-1.2"; + long dataStructureLength = 0; + unsigned char dataStructure[8]; + long outputLength = RSA_size(rsa); + long keyTokenLength; + unsigned char* keyToken = (unsigned char*)RSA_get_ex_data(rsa, hndidx); + + keyTokenLength = *(long*)keyToken; + keyToken+=sizeof(long); + + pkaDecrypt(&returnCode, &reasonCode, &exitDataLength, exitData, + &ruleArrayLength, ruleArray, &lflen, (unsigned char*)from, + &dataStructureLength, dataStructure, &keyTokenLength, + keyToken, &outputLength, to); + + return (returnCode | reasonCode) ? 0 : 1; + } + +#define SSL_SIG_LEN 36 + +static int cca_rsa_verify(int type, const unsigned char *m, unsigned int m_len, + const unsigned char *sigbuf, unsigned int siglen, const RSA *rsa) + { + long returnCode; + long reasonCode; + long lsiglen = siglen; + long exitDataLength = 0; + unsigned char exitData[8]; + long ruleArrayLength = 1; + unsigned char ruleArray[8] = "PKCS-1.1"; + long keyTokenLength; + unsigned char* keyToken = (unsigned char*)RSA_get_ex_data(rsa, hndidx); + long length = SSL_SIG_LEN; + long keyLength ; + unsigned char *hashBuffer = NULL; + X509_SIG sig; + ASN1_TYPE parameter; + X509_ALGOR algorithm; + ASN1_OCTET_STRING digest; + + keyTokenLength = *(long*)keyToken; + keyToken+=sizeof(long); + + if (type == NID_md5 || type == NID_sha1) + { + sig.algor = &algorithm; + algorithm.algorithm = OBJ_nid2obj(type); + + if (!algorithm.algorithm) + { + CCA4758err(CCA4758_F_CCA_RSA_VERIFY, + CCA4758_R_UNKNOWN_ALGORITHM_TYPE); + return 0; + } + + if (!algorithm.algorithm->length) + { + CCA4758err(CCA4758_F_CCA_RSA_VERIFY, + CCA4758_R_ASN1_OID_UNKNOWN_FOR_MD); + return 0; + } + + parameter.type = V_ASN1_NULL; + parameter.value.ptr = NULL; + algorithm.parameter = ¶meter; + + sig.digest = &digest; + sig.digest->data = (unsigned char*)m; + sig.digest->length = m_len; + + length = i2d_X509_SIG(&sig, NULL); + } + + keyLength = RSA_size(rsa); + + if (length - RSA_PKCS1_PADDING > keyLength) + { + CCA4758err(CCA4758_F_CCA_RSA_VERIFY, + CCA4758_R_SIZE_TOO_LARGE_OR_TOO_SMALL); + return 0; + } + + switch (type) + { + case NID_md5_sha1 : + if (m_len != SSL_SIG_LEN) + { + CCA4758err(CCA4758_F_CCA_RSA_VERIFY, + CCA4758_R_SIZE_TOO_LARGE_OR_TOO_SMALL); + return 0; + } + + hashBuffer = (unsigned char *)m; + length = m_len; + break; + case NID_md5 : + { + unsigned char *ptr; + ptr = hashBuffer = OPENSSL_malloc( + (unsigned int)keyLength+1); + if (!hashBuffer) + { + CCA4758err(CCA4758_F_CCA_RSA_VERIFY, + ERR_R_MALLOC_FAILURE); + return 0; + } + + i2d_X509_SIG(&sig, &ptr); + } + break; + case NID_sha1 : + { + unsigned char *ptr; + ptr = hashBuffer = OPENSSL_malloc( + (unsigned int)keyLength+1); + if (!hashBuffer) + { + CCA4758err(CCA4758_F_CCA_RSA_VERIFY, + ERR_R_MALLOC_FAILURE); + return 0; + } + i2d_X509_SIG(&sig, &ptr); + } + break; + default: + return 0; + } + + digitalSignatureVerify(&returnCode, &reasonCode, &exitDataLength, + exitData, &ruleArrayLength, ruleArray, &keyTokenLength, + keyToken, &length, hashBuffer, &lsiglen, + (unsigned char *)sigbuf); + + if (type == NID_sha1 || type == NID_md5) + { + OPENSSL_cleanse(hashBuffer, keyLength+1); + OPENSSL_free(hashBuffer); + } + + return ((returnCode || reasonCode) ? 0 : 1); + } + +#define SSL_SIG_LEN 36 + +static int cca_rsa_sign(int type, const unsigned char *m, unsigned int m_len, + unsigned char *sigret, unsigned int *siglen, const RSA *rsa) + { + long returnCode; + long reasonCode; + long exitDataLength = 0; + unsigned char exitData[8]; + long ruleArrayLength = 1; + unsigned char ruleArray[8] = "PKCS-1.1"; + long outputLength=256; + long outputBitLength; + long keyTokenLength; + unsigned char *hashBuffer = NULL; + unsigned char* keyToken = (unsigned char*)RSA_get_ex_data(rsa, hndidx); + long length = SSL_SIG_LEN; + long keyLength ; + X509_SIG sig; + ASN1_TYPE parameter; + X509_ALGOR algorithm; + ASN1_OCTET_STRING digest; + + keyTokenLength = *(long*)keyToken; + keyToken+=sizeof(long); + + if (type == NID_md5 || type == NID_sha1) + { + sig.algor = &algorithm; + algorithm.algorithm = OBJ_nid2obj(type); + + if (!algorithm.algorithm) + { + CCA4758err(CCA4758_F_CCA_RSA_SIGN, + CCA4758_R_UNKNOWN_ALGORITHM_TYPE); + return 0; + } + + if (!algorithm.algorithm->length) + { + CCA4758err(CCA4758_F_CCA_RSA_SIGN, + CCA4758_R_ASN1_OID_UNKNOWN_FOR_MD); + return 0; + } + + parameter.type = V_ASN1_NULL; + parameter.value.ptr = NULL; + algorithm.parameter = ¶meter; + + sig.digest = &digest; + sig.digest->data = (unsigned char*)m; + sig.digest->length = m_len; + + length = i2d_X509_SIG(&sig, NULL); + } + + keyLength = RSA_size(rsa); + + if (length - RSA_PKCS1_PADDING > keyLength) + { + CCA4758err(CCA4758_F_CCA_RSA_SIGN, + CCA4758_R_SIZE_TOO_LARGE_OR_TOO_SMALL); + return 0; + } + + switch (type) + { + case NID_md5_sha1 : + if (m_len != SSL_SIG_LEN) + { + CCA4758err(CCA4758_F_CCA_RSA_SIGN, + CCA4758_R_SIZE_TOO_LARGE_OR_TOO_SMALL); + return 0; + } + hashBuffer = (unsigned char*)m; + length = m_len; + break; + case NID_md5 : + { + unsigned char *ptr; + ptr = hashBuffer = OPENSSL_malloc( + (unsigned int)keyLength+1); + if (!hashBuffer) + { + CCA4758err(CCA4758_F_CCA_RSA_SIGN, + ERR_R_MALLOC_FAILURE); + return 0; + } + i2d_X509_SIG(&sig, &ptr); + } + break; + case NID_sha1 : + { + unsigned char *ptr; + ptr = hashBuffer = OPENSSL_malloc( + (unsigned int)keyLength+1); + if (!hashBuffer) + { + CCA4758err(CCA4758_F_CCA_RSA_SIGN, + ERR_R_MALLOC_FAILURE); + return 0; + } + i2d_X509_SIG(&sig, &ptr); + } + break; + default: + return 0; + } + + digitalSignatureGenerate(&returnCode, &reasonCode, &exitDataLength, + exitData, &ruleArrayLength, ruleArray, &keyTokenLength, + keyToken, &length, hashBuffer, &outputLength, &outputBitLength, + sigret); + + if (type == NID_sha1 || type == NID_md5) + { + OPENSSL_cleanse(hashBuffer, keyLength+1); + OPENSSL_free(hashBuffer); + } + + *siglen = outputLength; + + return ((returnCode || reasonCode) ? 0 : 1); + } + +static int getModulusAndExponent(const unsigned char*token, long *exponentLength, + unsigned char *exponent, long *modulusLength, long *modulusFieldLength, + unsigned char *modulus) + { + unsigned long len; + + if (*token++ != (char)0x1E) /* internal PKA token? */ + return 0; + + if (*token++) /* token version must be zero */ + return 0; + + len = *token++; + len = len << 8; + len |= (unsigned char)*token++; + + token += 4; /* skip reserved bytes */ + + if (*token++ == (char)0x04) + { + if (*token++) /* token version must be zero */ + return 0; + + len = *token++; + len = len << 8; + len |= (unsigned char)*token++; + + token+=2; /* skip reserved section */ + + len = *token++; + len = len << 8; + len |= (unsigned char)*token++; + + *exponentLength = len; + + len = *token++; + len = len << 8; + len |= (unsigned char)*token++; + + *modulusLength = len; + + len = *token++; + len = len << 8; + len |= (unsigned char)*token++; + + *modulusFieldLength = len; + + memcpy(exponent, token, *exponentLength); + token+= *exponentLength; + + memcpy(modulus, token, *modulusFieldLength); + return 1; + } + return 0; + } + +#endif /* OPENSSL_NO_RSA */ + +static int cca_random_status(void) + { + return 1; + } + +static int cca_get_random_bytes(unsigned char* buf, int num) + { + long ret_code; + long reason_code; + long exit_data_length; + unsigned char exit_data[4]; + unsigned char form[] = "RANDOM "; + unsigned char rand_buf[8]; + + while(num >= (int)sizeof(rand_buf)) + { + randomNumberGenerate(&ret_code, &reason_code, &exit_data_length, + exit_data, form, rand_buf); + if (ret_code) + return 0; + num -= sizeof(rand_buf); + memcpy(buf, rand_buf, sizeof(rand_buf)); + buf += sizeof(rand_buf); + } + + if (num) + { + randomNumberGenerate(&ret_code, &reason_code, NULL, NULL, + form, rand_buf); + if (ret_code) + return 0; + memcpy(buf, rand_buf, num); + } + + return 1; + } + +#ifndef OPENSSL_NO_RSA +static void cca_ex_free(void *obj, void *item, CRYPTO_EX_DATA *ad, int idx, + long argl, void *argp) + { + if (item) + OPENSSL_free(item); + } +#endif + +/* Goo to handle building as a dynamic engine */ +#ifndef OPENSSL_NO_DYNAMIC_ENGINE +static int bind_fn(ENGINE *e, const char *id) + { + if(id && (strcmp(id, engine_4758_cca_id) != 0) && + (strcmp(id, engine_4758_cca_id_alt) != 0)) + return 0; + if(!bind_helper(e)) + return 0; + return 1; + } +IMPLEMENT_DYNAMIC_CHECK_FN() +IMPLEMENT_DYNAMIC_BIND_FN(bind_fn) +#endif /* OPENSSL_NO_DYNAMIC_ENGINE */ + +#endif /* !OPENSSL_NO_HW_4758_CCA */ +#endif /* !OPENSSL_NO_HW */ diff --git a/node-v0.8.14/deps/openssl/openssl/engines/e_4758cca.ec b/node-v0.8.14/deps/openssl/openssl/engines/e_4758cca.ec new file mode 100644 index 0000000..f30ed02 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/engines/e_4758cca.ec @@ -0,0 +1 @@ +L CCA4758 e_4758cca_err.h e_4758cca_err.c diff --git a/node-v0.8.14/deps/openssl/openssl/engines/e_4758cca_err.c b/node-v0.8.14/deps/openssl/openssl/engines/e_4758cca_err.c new file mode 100644 index 0000000..6ecdc6e --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/engines/e_4758cca_err.c @@ -0,0 +1,153 @@ +/* e_4758cca_err.c */ +/* ==================================================================== + * Copyright (c) 1999-2005 The OpenSSL Project. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. All advertising materials mentioning features or use of this + * software must display the following acknowledgment: + * "This product includes software developed by the OpenSSL Project + * for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)" + * + * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to + * endorse or promote products derived from this software without + * prior written permission. For written permission, please contact + * openssl-core@OpenSSL.org. + * + * 5. Products derived from this software may not be called "OpenSSL" + * nor may "OpenSSL" appear in their names without prior written + * permission of the OpenSSL Project. + * + * 6. Redistributions of any form whatsoever must retain the following + * acknowledgment: + * "This product includes software developed by the OpenSSL Project + * for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)" + * + * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY + * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR + * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, + * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * ==================================================================== + * + * This product includes cryptographic software written by Eric Young + * (eay@cryptsoft.com). This product includes software written by Tim + * Hudson (tjh@cryptsoft.com). + * + */ + +/* NOTE: this file was auto generated by the mkerr.pl script: any changes + * made to it will be overwritten when the script next updates this file, + * only reason strings will be preserved. + */ + +#include +#include +#include "e_4758cca_err.h" + +/* BEGIN ERROR CODES */ +#ifndef OPENSSL_NO_ERR + +#define ERR_FUNC(func) ERR_PACK(0,func,0) +#define ERR_REASON(reason) ERR_PACK(0,0,reason) + +static ERR_STRING_DATA CCA4758_str_functs[]= + { +{ERR_FUNC(CCA4758_F_CCA_RSA_SIGN), "CCA_RSA_SIGN"}, +{ERR_FUNC(CCA4758_F_CCA_RSA_VERIFY), "CCA_RSA_VERIFY"}, +{ERR_FUNC(CCA4758_F_IBM_4758_CCA_CTRL), "IBM_4758_CCA_CTRL"}, +{ERR_FUNC(CCA4758_F_IBM_4758_CCA_FINISH), "IBM_4758_CCA_FINISH"}, +{ERR_FUNC(CCA4758_F_IBM_4758_CCA_INIT), "IBM_4758_CCA_INIT"}, +{ERR_FUNC(CCA4758_F_IBM_4758_LOAD_PRIVKEY), "IBM_4758_LOAD_PRIVKEY"}, +{ERR_FUNC(CCA4758_F_IBM_4758_LOAD_PUBKEY), "IBM_4758_LOAD_PUBKEY"}, +{0,NULL} + }; + +static ERR_STRING_DATA CCA4758_str_reasons[]= + { +{ERR_REASON(CCA4758_R_ALREADY_LOADED) ,"already loaded"}, +{ERR_REASON(CCA4758_R_ASN1_OID_UNKNOWN_FOR_MD),"asn1 oid unknown for md"}, +{ERR_REASON(CCA4758_R_COMMAND_NOT_IMPLEMENTED),"command not implemented"}, +{ERR_REASON(CCA4758_R_DSO_FAILURE) ,"dso failure"}, +{ERR_REASON(CCA4758_R_FAILED_LOADING_PRIVATE_KEY),"failed loading private key"}, +{ERR_REASON(CCA4758_R_FAILED_LOADING_PUBLIC_KEY),"failed loading public key"}, +{ERR_REASON(CCA4758_R_NOT_LOADED) ,"not loaded"}, +{ERR_REASON(CCA4758_R_SIZE_TOO_LARGE_OR_TOO_SMALL),"size too large or too small"}, +{ERR_REASON(CCA4758_R_UNIT_FAILURE) ,"unit failure"}, +{ERR_REASON(CCA4758_R_UNKNOWN_ALGORITHM_TYPE),"unknown algorithm type"}, +{0,NULL} + }; + +#endif + +#ifdef CCA4758_LIB_NAME +static ERR_STRING_DATA CCA4758_lib_name[]= + { +{0 ,CCA4758_LIB_NAME}, +{0,NULL} + }; +#endif + + +static int CCA4758_lib_error_code=0; +static int CCA4758_error_init=1; + +static void ERR_load_CCA4758_strings(void) + { + if (CCA4758_lib_error_code == 0) + CCA4758_lib_error_code=ERR_get_next_error_library(); + + if (CCA4758_error_init) + { + CCA4758_error_init=0; +#ifndef OPENSSL_NO_ERR + ERR_load_strings(CCA4758_lib_error_code,CCA4758_str_functs); + ERR_load_strings(CCA4758_lib_error_code,CCA4758_str_reasons); +#endif + +#ifdef CCA4758_LIB_NAME + CCA4758_lib_name->error = ERR_PACK(CCA4758_lib_error_code,0,0); + ERR_load_strings(0,CCA4758_lib_name); +#endif + } + } + +static void ERR_unload_CCA4758_strings(void) + { + if (CCA4758_error_init == 0) + { +#ifndef OPENSSL_NO_ERR + ERR_unload_strings(CCA4758_lib_error_code,CCA4758_str_functs); + ERR_unload_strings(CCA4758_lib_error_code,CCA4758_str_reasons); +#endif + +#ifdef CCA4758_LIB_NAME + ERR_unload_strings(0,CCA4758_lib_name); +#endif + CCA4758_error_init=1; + } + } + +static void ERR_CCA4758_error(int function, int reason, char *file, int line) + { + if (CCA4758_lib_error_code == 0) + CCA4758_lib_error_code=ERR_get_next_error_library(); + ERR_PUT_error(CCA4758_lib_error_code,function,reason,file,line); + } diff --git a/node-v0.8.14/deps/openssl/openssl/engines/e_4758cca_err.h b/node-v0.8.14/deps/openssl/openssl/engines/e_4758cca_err.h new file mode 100644 index 0000000..26087ed --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/engines/e_4758cca_err.h @@ -0,0 +1,97 @@ +/* ==================================================================== + * Copyright (c) 2001 The OpenSSL Project. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. All advertising materials mentioning features or use of this + * software must display the following acknowledgment: + * "This product includes software developed by the OpenSSL Project + * for use in the OpenSSL Toolkit. (http://www.openssl.org/)" + * + * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to + * endorse or promote products derived from this software without + * prior written permission. For written permission, please contact + * openssl-core@openssl.org. + * + * 5. Products derived from this software may not be called "OpenSSL" + * nor may "OpenSSL" appear in their names without prior written + * permission of the OpenSSL Project. + * + * 6. Redistributions of any form whatsoever must retain the following + * acknowledgment: + * "This product includes software developed by the OpenSSL Project + * for use in the OpenSSL Toolkit (http://www.openssl.org/)" + * + * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY + * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR + * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, + * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * ==================================================================== + * + * This product includes cryptographic software written by Eric Young + * (eay@cryptsoft.com). This product includes software written by Tim + * Hudson (tjh@cryptsoft.com). + * + */ + +#ifndef HEADER_CCA4758_ERR_H +#define HEADER_CCA4758_ERR_H + +#ifdef __cplusplus +extern "C" { +#endif + +/* BEGIN ERROR CODES */ +/* The following lines are auto generated by the script mkerr.pl. Any changes + * made after this point may be overwritten when the script is next run. + */ +static void ERR_load_CCA4758_strings(void); +static void ERR_unload_CCA4758_strings(void); +static void ERR_CCA4758_error(int function, int reason, char *file, int line); +#define CCA4758err(f,r) ERR_CCA4758_error((f),(r),__FILE__,__LINE__) + +/* Error codes for the CCA4758 functions. */ + +/* Function codes. */ +#define CCA4758_F_CCA_RSA_SIGN 105 +#define CCA4758_F_CCA_RSA_VERIFY 106 +#define CCA4758_F_IBM_4758_CCA_CTRL 100 +#define CCA4758_F_IBM_4758_CCA_FINISH 101 +#define CCA4758_F_IBM_4758_CCA_INIT 102 +#define CCA4758_F_IBM_4758_LOAD_PRIVKEY 103 +#define CCA4758_F_IBM_4758_LOAD_PUBKEY 104 + +/* Reason codes. */ +#define CCA4758_R_ALREADY_LOADED 100 +#define CCA4758_R_ASN1_OID_UNKNOWN_FOR_MD 101 +#define CCA4758_R_COMMAND_NOT_IMPLEMENTED 102 +#define CCA4758_R_DSO_FAILURE 103 +#define CCA4758_R_FAILED_LOADING_PRIVATE_KEY 104 +#define CCA4758_R_FAILED_LOADING_PUBLIC_KEY 105 +#define CCA4758_R_NOT_LOADED 106 +#define CCA4758_R_SIZE_TOO_LARGE_OR_TOO_SMALL 107 +#define CCA4758_R_UNIT_FAILURE 108 +#define CCA4758_R_UNKNOWN_ALGORITHM_TYPE 109 + +#ifdef __cplusplus +} +#endif +#endif diff --git a/node-v0.8.14/deps/openssl/openssl/engines/e_aep.c b/node-v0.8.14/deps/openssl/openssl/engines/e_aep.c new file mode 100644 index 0000000..d7f89e5 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/engines/e_aep.c @@ -0,0 +1,1140 @@ +/* ==================================================================== + * Copyright (c) 1999 The OpenSSL Project. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. All advertising materials mentioning features or use of this + * software must display the following acknowledgment: + * "This product includes software developed by the OpenSSL Project + * for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)" + * + * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to + * endorse or promote products derived from this software without + * prior written permission. For written permission, please contact + * licensing@OpenSSL.org. + * + * 5. Products derived from this software may not be called "OpenSSL" + * nor may "OpenSSL" appear in their names without prior written + * permission of the OpenSSL Project. + * + * 6. Redistributions of any form whatsoever must retain the following + * acknowledgment: + * "This product includes software developed by the OpenSSL Project + * for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)" + * + * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY + * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR + * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, + * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * ==================================================================== + * + * This product includes cryptographic software written by Eric Young + * (eay@cryptsoft.com). This product includes software written by Tim + * Hudson (tjh@cryptsoft.com). + * + */ + +#include +#include +#include + +#include +#if !defined(OPENSSL_SYS_MSDOS) || defined(__DJGPP__) || defined(__MINGW32__) +#include +#include +#else +#include +typedef int pid_t; +#endif + +#if defined(OPENSSL_SYS_NETWARE) && defined(NETWARE_CLIB) +#define getpid GetThreadID +extern int GetThreadID(void); +#elif defined(_WIN32) && !defined(__WATCOMC__) +#define getpid _getpid +#endif + +#include +#include +#include +#include +#ifndef OPENSSL_NO_RSA +#include +#endif +#ifndef OPENSSL_NO_DSA +#include +#endif +#ifndef OPENSSL_NO_DH +#include +#endif +#include + +#ifndef OPENSSL_NO_HW +#ifndef OPENSSL_NO_HW_AEP +#ifdef FLAT_INC +#include "aep.h" +#else +#include "vendor_defns/aep.h" +#endif + +#define AEP_LIB_NAME "aep engine" +#define FAIL_TO_SW 0x10101010 + +#include "e_aep_err.c" + +static int aep_init(ENGINE *e); +static int aep_finish(ENGINE *e); +static int aep_ctrl(ENGINE *e, int cmd, long i, void *p, void (*f)(void)); +static int aep_destroy(ENGINE *e); + +static AEP_RV aep_get_connection(AEP_CONNECTION_HNDL_PTR hConnection); +static AEP_RV aep_return_connection(AEP_CONNECTION_HNDL hConnection); +static AEP_RV aep_close_connection(AEP_CONNECTION_HNDL hConnection); +static AEP_RV aep_close_all_connections(int use_engine_lock, int *in_use); + +/* BIGNUM stuff */ +#ifndef OPENSSL_NO_RSA +static int aep_mod_exp(BIGNUM *r, const BIGNUM *a, const BIGNUM *p, + const BIGNUM *m, BN_CTX *ctx); + +static AEP_RV aep_mod_exp_crt(BIGNUM *r,const BIGNUM *a, const BIGNUM *p, + const BIGNUM *q, const BIGNUM *dmp1,const BIGNUM *dmq1, + const BIGNUM *iqmp, BN_CTX *ctx); +#endif + +/* RSA stuff */ +#ifndef OPENSSL_NO_RSA +static int aep_rsa_mod_exp(BIGNUM *r0, const BIGNUM *I, RSA *rsa, BN_CTX *ctx); +#endif + +/* This function is aliased to mod_exp (with the mont stuff dropped). */ +#ifndef OPENSSL_NO_RSA +static int aep_mod_exp_mont(BIGNUM *r, const BIGNUM *a, const BIGNUM *p, + const BIGNUM *m, BN_CTX *ctx, BN_MONT_CTX *m_ctx); +#endif + +/* DSA stuff */ +#ifndef OPENSSL_NO_DSA +static int aep_dsa_mod_exp(DSA *dsa, BIGNUM *rr, BIGNUM *a1, + BIGNUM *p1, BIGNUM *a2, BIGNUM *p2, BIGNUM *m, + BN_CTX *ctx, BN_MONT_CTX *in_mont); + +static int aep_mod_exp_dsa(DSA *dsa, BIGNUM *r, BIGNUM *a, + const BIGNUM *p, const BIGNUM *m, BN_CTX *ctx, + BN_MONT_CTX *m_ctx); +#endif + +/* DH stuff */ +/* This function is aliased to mod_exp (with the DH and mont dropped). */ +#ifndef OPENSSL_NO_DH +static int aep_mod_exp_dh(const DH *dh, BIGNUM *r, const BIGNUM *a, + const BIGNUM *p, const BIGNUM *m, BN_CTX *ctx, BN_MONT_CTX *m_ctx); +#endif + +/* rand stuff */ +#ifdef AEPRAND +static int aep_rand(unsigned char *buf, int num); +static int aep_rand_status(void); +#endif + +/* Bignum conversion stuff */ +static AEP_RV GetBigNumSize(AEP_VOID_PTR ArbBigNum, AEP_U32* BigNumSize); +static AEP_RV MakeAEPBigNum(AEP_VOID_PTR ArbBigNum, AEP_U32 BigNumSize, + unsigned char* AEP_BigNum); +static AEP_RV ConvertAEPBigNum(void* ArbBigNum, AEP_U32 BigNumSize, + unsigned char* AEP_BigNum); + +/* The definitions for control commands specific to this engine */ +#define AEP_CMD_SO_PATH ENGINE_CMD_BASE +static const ENGINE_CMD_DEFN aep_cmd_defns[] = + { + { AEP_CMD_SO_PATH, + "SO_PATH", + "Specifies the path to the 'aep' shared library", + ENGINE_CMD_FLAG_STRING + }, + {0, NULL, NULL, 0} + }; + +#ifndef OPENSSL_NO_RSA +/* Our internal RSA_METHOD that we provide pointers to */ +static RSA_METHOD aep_rsa = + { + "Aep RSA method", + NULL, /*rsa_pub_encrypt*/ + NULL, /*rsa_pub_decrypt*/ + NULL, /*rsa_priv_encrypt*/ + NULL, /*rsa_priv_encrypt*/ + aep_rsa_mod_exp, /*rsa_mod_exp*/ + aep_mod_exp_mont, /*bn_mod_exp*/ + NULL, /*init*/ + NULL, /*finish*/ + 0, /*flags*/ + NULL, /*app_data*/ + NULL, /*rsa_sign*/ + NULL, /*rsa_verify*/ + NULL /*rsa_keygen*/ + }; +#endif + +#ifndef OPENSSL_NO_DSA +/* Our internal DSA_METHOD that we provide pointers to */ +static DSA_METHOD aep_dsa = + { + "Aep DSA method", + NULL, /* dsa_do_sign */ + NULL, /* dsa_sign_setup */ + NULL, /* dsa_do_verify */ + aep_dsa_mod_exp, /* dsa_mod_exp */ + aep_mod_exp_dsa, /* bn_mod_exp */ + NULL, /* init */ + NULL, /* finish */ + 0, /* flags */ + NULL, /* app_data */ + NULL, /* dsa_paramgen */ + NULL /* dsa_keygen */ + }; +#endif + +#ifndef OPENSSL_NO_DH +/* Our internal DH_METHOD that we provide pointers to */ +static DH_METHOD aep_dh = + { + "Aep DH method", + NULL, + NULL, + aep_mod_exp_dh, + NULL, + NULL, + 0, + NULL, + NULL + }; +#endif + +#ifdef AEPRAND +/* our internal RAND_method that we provide pointers to */ +static RAND_METHOD aep_random = + { + /*"AEP RAND method", */ + NULL, + aep_rand, + NULL, + NULL, + aep_rand, + aep_rand_status, + }; +#endif + +/*Define an array of structures to hold connections*/ +static AEP_CONNECTION_ENTRY aep_app_conn_table[MAX_PROCESS_CONNECTIONS]; + +/*Used to determine if this is a new process*/ +static pid_t recorded_pid = 0; + +#ifdef AEPRAND +static AEP_U8 rand_block[RAND_BLK_SIZE]; +static AEP_U32 rand_block_bytes = 0; +#endif + +/* Constants used when creating the ENGINE */ +static const char *engine_aep_id = "aep"; +static const char *engine_aep_name = "Aep hardware engine support"; + +static int max_key_len = 2176; + + +/* This internal function is used by ENGINE_aep() and possibly by the + * "dynamic" ENGINE support too */ +static int bind_aep(ENGINE *e) + { +#ifndef OPENSSL_NO_RSA + const RSA_METHOD *meth1; +#endif +#ifndef OPENSSL_NO_DSA + const DSA_METHOD *meth2; +#endif +#ifndef OPENSSL_NO_DH + const DH_METHOD *meth3; +#endif + + if(!ENGINE_set_id(e, engine_aep_id) || + !ENGINE_set_name(e, engine_aep_name) || +#ifndef OPENSSL_NO_RSA + !ENGINE_set_RSA(e, &aep_rsa) || +#endif +#ifndef OPENSSL_NO_DSA + !ENGINE_set_DSA(e, &aep_dsa) || +#endif +#ifndef OPENSSL_NO_DH + !ENGINE_set_DH(e, &aep_dh) || +#endif +#ifdef AEPRAND + !ENGINE_set_RAND(e, &aep_random) || +#endif + !ENGINE_set_init_function(e, aep_init) || + !ENGINE_set_destroy_function(e, aep_destroy) || + !ENGINE_set_finish_function(e, aep_finish) || + !ENGINE_set_ctrl_function(e, aep_ctrl) || + !ENGINE_set_cmd_defns(e, aep_cmd_defns)) + return 0; + +#ifndef OPENSSL_NO_RSA + /* We know that the "PKCS1_SSLeay()" functions hook properly + * to the aep-specific mod_exp and mod_exp_crt so we use + * those functions. NB: We don't use ENGINE_openssl() or + * anything "more generic" because something like the RSAref + * code may not hook properly, and if you own one of these + * cards then you have the right to do RSA operations on it + * anyway! */ + meth1 = RSA_PKCS1_SSLeay(); + aep_rsa.rsa_pub_enc = meth1->rsa_pub_enc; + aep_rsa.rsa_pub_dec = meth1->rsa_pub_dec; + aep_rsa.rsa_priv_enc = meth1->rsa_priv_enc; + aep_rsa.rsa_priv_dec = meth1->rsa_priv_dec; +#endif + + +#ifndef OPENSSL_NO_DSA + /* Use the DSA_OpenSSL() method and just hook the mod_exp-ish + * bits. */ + meth2 = DSA_OpenSSL(); + aep_dsa.dsa_do_sign = meth2->dsa_do_sign; + aep_dsa.dsa_sign_setup = meth2->dsa_sign_setup; + aep_dsa.dsa_do_verify = meth2->dsa_do_verify; + + aep_dsa = *DSA_get_default_method(); + aep_dsa.dsa_mod_exp = aep_dsa_mod_exp; + aep_dsa.bn_mod_exp = aep_mod_exp_dsa; +#endif + +#ifndef OPENSSL_NO_DH + /* Much the same for Diffie-Hellman */ + meth3 = DH_OpenSSL(); + aep_dh.generate_key = meth3->generate_key; + aep_dh.compute_key = meth3->compute_key; + aep_dh.bn_mod_exp = meth3->bn_mod_exp; +#endif + + /* Ensure the aep error handling is set up */ + ERR_load_AEPHK_strings(); + + return 1; +} + +#ifndef OPENSSL_NO_DYNAMIC_ENGINE +static int bind_helper(ENGINE *e, const char *id) + { + if(id && (strcmp(id, engine_aep_id) != 0)) + return 0; + if(!bind_aep(e)) + return 0; + return 1; + } +IMPLEMENT_DYNAMIC_CHECK_FN() +IMPLEMENT_DYNAMIC_BIND_FN(bind_helper) +#else +static ENGINE *engine_aep(void) + { + ENGINE *ret = ENGINE_new(); + if(!ret) + return NULL; + if(!bind_aep(ret)) + { + ENGINE_free(ret); + return NULL; + } + return ret; + } + +void ENGINE_load_aep(void) + { + /* Copied from eng_[openssl|dyn].c */ + ENGINE *toadd = engine_aep(); + if(!toadd) return; + ENGINE_add(toadd); + ENGINE_free(toadd); + ERR_clear_error(); + } +#endif + +/* This is a process-global DSO handle used for loading and unloading + * the Aep library. NB: This is only set (or unset) during an + * init() or finish() call (reference counts permitting) and they're + * operating with global locks, so this should be thread-safe + * implicitly. */ +static DSO *aep_dso = NULL; + +/* These are the static string constants for the DSO file name and the function + * symbol names to bind to. +*/ +static const char *AEP_LIBNAME = NULL; +static const char *get_AEP_LIBNAME(void) + { + if(AEP_LIBNAME) + return AEP_LIBNAME; + return "aep"; + } +static void free_AEP_LIBNAME(void) + { + if(AEP_LIBNAME) + OPENSSL_free((void*)AEP_LIBNAME); + AEP_LIBNAME = NULL; + } +static long set_AEP_LIBNAME(const char *name) + { + free_AEP_LIBNAME(); + return ((AEP_LIBNAME = BUF_strdup(name)) != NULL ? 1 : 0); + } + +static const char *AEP_F1 = "AEP_ModExp"; +static const char *AEP_F2 = "AEP_ModExpCrt"; +#ifdef AEPRAND +static const char *AEP_F3 = "AEP_GenRandom"; +#endif +static const char *AEP_F4 = "AEP_Finalize"; +static const char *AEP_F5 = "AEP_Initialize"; +static const char *AEP_F6 = "AEP_OpenConnection"; +static const char *AEP_F7 = "AEP_SetBNCallBacks"; +static const char *AEP_F8 = "AEP_CloseConnection"; + +/* These are the function pointers that are (un)set when the library has + * successfully (un)loaded. */ +static t_AEP_OpenConnection *p_AEP_OpenConnection = NULL; +static t_AEP_CloseConnection *p_AEP_CloseConnection = NULL; +static t_AEP_ModExp *p_AEP_ModExp = NULL; +static t_AEP_ModExpCrt *p_AEP_ModExpCrt = NULL; +#ifdef AEPRAND +static t_AEP_GenRandom *p_AEP_GenRandom = NULL; +#endif +static t_AEP_Initialize *p_AEP_Initialize = NULL; +static t_AEP_Finalize *p_AEP_Finalize = NULL; +static t_AEP_SetBNCallBacks *p_AEP_SetBNCallBacks = NULL; + +/* (de)initialisation functions. */ +static int aep_init(ENGINE *e) + { + t_AEP_ModExp *p1; + t_AEP_ModExpCrt *p2; +#ifdef AEPRAND + t_AEP_GenRandom *p3; +#endif + t_AEP_Finalize *p4; + t_AEP_Initialize *p5; + t_AEP_OpenConnection *p6; + t_AEP_SetBNCallBacks *p7; + t_AEP_CloseConnection *p8; + + int to_return = 0; + + if(aep_dso != NULL) + { + AEPHKerr(AEPHK_F_AEP_INIT,AEPHK_R_ALREADY_LOADED); + goto err; + } + /* Attempt to load libaep.so. */ + + aep_dso = DSO_load(NULL, get_AEP_LIBNAME(), NULL, 0); + + if(aep_dso == NULL) + { + AEPHKerr(AEPHK_F_AEP_INIT,AEPHK_R_NOT_LOADED); + goto err; + } + + if( !(p1 = (t_AEP_ModExp *) DSO_bind_func( aep_dso,AEP_F1)) || + !(p2 = (t_AEP_ModExpCrt*) DSO_bind_func( aep_dso,AEP_F2)) || +#ifdef AEPRAND + !(p3 = (t_AEP_GenRandom*) DSO_bind_func( aep_dso,AEP_F3)) || +#endif + !(p4 = (t_AEP_Finalize*) DSO_bind_func( aep_dso,AEP_F4)) || + !(p5 = (t_AEP_Initialize*) DSO_bind_func( aep_dso,AEP_F5)) || + !(p6 = (t_AEP_OpenConnection*) DSO_bind_func( aep_dso,AEP_F6)) || + !(p7 = (t_AEP_SetBNCallBacks*) DSO_bind_func( aep_dso,AEP_F7)) || + !(p8 = (t_AEP_CloseConnection*) DSO_bind_func( aep_dso,AEP_F8))) + { + AEPHKerr(AEPHK_F_AEP_INIT,AEPHK_R_NOT_LOADED); + goto err; + } + + /* Copy the pointers */ + + p_AEP_ModExp = p1; + p_AEP_ModExpCrt = p2; +#ifdef AEPRAND + p_AEP_GenRandom = p3; +#endif + p_AEP_Finalize = p4; + p_AEP_Initialize = p5; + p_AEP_OpenConnection = p6; + p_AEP_SetBNCallBacks = p7; + p_AEP_CloseConnection = p8; + + to_return = 1; + + return to_return; + + err: + + if(aep_dso) + DSO_free(aep_dso); + aep_dso = NULL; + + p_AEP_OpenConnection = NULL; + p_AEP_ModExp = NULL; + p_AEP_ModExpCrt = NULL; +#ifdef AEPRAND + p_AEP_GenRandom = NULL; +#endif + p_AEP_Initialize = NULL; + p_AEP_Finalize = NULL; + p_AEP_SetBNCallBacks = NULL; + p_AEP_CloseConnection = NULL; + + return to_return; + } + +/* Destructor (complements the "ENGINE_aep()" constructor) */ +static int aep_destroy(ENGINE *e) + { + free_AEP_LIBNAME(); + ERR_unload_AEPHK_strings(); + return 1; + } + +static int aep_finish(ENGINE *e) + { + int to_return = 0, in_use; + AEP_RV rv; + + if(aep_dso == NULL) + { + AEPHKerr(AEPHK_F_AEP_FINISH,AEPHK_R_NOT_LOADED); + goto err; + } + + rv = aep_close_all_connections(0, &in_use); + if (rv != AEP_R_OK) + { + AEPHKerr(AEPHK_F_AEP_FINISH,AEPHK_R_CLOSE_HANDLES_FAILED); + goto err; + } + if (in_use) + { + AEPHKerr(AEPHK_F_AEP_FINISH,AEPHK_R_CONNECTIONS_IN_USE); + goto err; + } + + rv = p_AEP_Finalize(); + if (rv != AEP_R_OK) + { + AEPHKerr(AEPHK_F_AEP_FINISH,AEPHK_R_FINALIZE_FAILED); + goto err; + } + + if(!DSO_free(aep_dso)) + { + AEPHKerr(AEPHK_F_AEP_FINISH,AEPHK_R_UNIT_FAILURE); + goto err; + } + + aep_dso = NULL; + p_AEP_CloseConnection = NULL; + p_AEP_OpenConnection = NULL; + p_AEP_ModExp = NULL; + p_AEP_ModExpCrt = NULL; +#ifdef AEPRAND + p_AEP_GenRandom = NULL; +#endif + p_AEP_Initialize = NULL; + p_AEP_Finalize = NULL; + p_AEP_SetBNCallBacks = NULL; + + to_return = 1; + err: + return to_return; + } + +static int aep_ctrl(ENGINE *e, int cmd, long i, void *p, void (*f)(void)) + { + int initialised = ((aep_dso == NULL) ? 0 : 1); + switch(cmd) + { + case AEP_CMD_SO_PATH: + if(p == NULL) + { + AEPHKerr(AEPHK_F_AEP_CTRL, + ERR_R_PASSED_NULL_PARAMETER); + return 0; + } + if(initialised) + { + AEPHKerr(AEPHK_F_AEP_CTRL, + AEPHK_R_ALREADY_LOADED); + return 0; + } + return set_AEP_LIBNAME((const char*)p); + default: + break; + } + AEPHKerr(AEPHK_F_AEP_CTRL,AEPHK_R_CTRL_COMMAND_NOT_IMPLEMENTED); + return 0; + } + +static int aep_mod_exp(BIGNUM *r, const BIGNUM *a, const BIGNUM *p, + const BIGNUM *m, BN_CTX *ctx) + { + int to_return = 0; + int r_len = 0; + AEP_CONNECTION_HNDL hConnection; + AEP_RV rv; + + r_len = BN_num_bits(m); + + /* Perform in software if modulus is too large for hardware. */ + + if (r_len > max_key_len){ + AEPHKerr(AEPHK_F_AEP_MOD_EXP, AEPHK_R_SIZE_TOO_LARGE_OR_TOO_SMALL); + return BN_mod_exp(r, a, p, m, ctx); + } + + /*Grab a connection from the pool*/ + rv = aep_get_connection(&hConnection); + if (rv != AEP_R_OK) + { + AEPHKerr(AEPHK_F_AEP_MOD_EXP,AEPHK_R_GET_HANDLE_FAILED); + return BN_mod_exp(r, a, p, m, ctx); + } + + /*To the card with the mod exp*/ + rv = p_AEP_ModExp(hConnection,(void*)a, (void*)p,(void*)m, (void*)r,NULL); + + if (rv != AEP_R_OK) + { + AEPHKerr(AEPHK_F_AEP_MOD_EXP,AEPHK_R_MOD_EXP_FAILED); + rv = aep_close_connection(hConnection); + return BN_mod_exp(r, a, p, m, ctx); + } + + /*Return the connection to the pool*/ + rv = aep_return_connection(hConnection); + if (rv != AEP_R_OK) + { + AEPHKerr(AEPHK_F_AEP_MOD_EXP,AEPHK_R_RETURN_CONNECTION_FAILED); + goto err; + } + + to_return = 1; + err: + return to_return; + } + +#ifndef OPENSSL_NO_RSA +static AEP_RV aep_mod_exp_crt(BIGNUM *r, const BIGNUM *a, const BIGNUM *p, + const BIGNUM *q, const BIGNUM *dmp1, + const BIGNUM *dmq1,const BIGNUM *iqmp, BN_CTX *ctx) + { + AEP_RV rv = AEP_R_OK; + AEP_CONNECTION_HNDL hConnection; + + /*Grab a connection from the pool*/ + rv = aep_get_connection(&hConnection); + if (rv != AEP_R_OK) + { + AEPHKerr(AEPHK_F_AEP_MOD_EXP_CRT,AEPHK_R_GET_HANDLE_FAILED); + return FAIL_TO_SW; + } + + /*To the card with the mod exp*/ + rv = p_AEP_ModExpCrt(hConnection,(void*)a, (void*)p, (void*)q, (void*)dmp1,(void*)dmq1, + (void*)iqmp,(void*)r,NULL); + if (rv != AEP_R_OK) + { + AEPHKerr(AEPHK_F_AEP_MOD_EXP_CRT,AEPHK_R_MOD_EXP_CRT_FAILED); + rv = aep_close_connection(hConnection); + return FAIL_TO_SW; + } + + /*Return the connection to the pool*/ + rv = aep_return_connection(hConnection); + if (rv != AEP_R_OK) + { + AEPHKerr(AEPHK_F_AEP_MOD_EXP_CRT,AEPHK_R_RETURN_CONNECTION_FAILED); + goto err; + } + + err: + return rv; + } +#endif + + +#ifdef AEPRAND +static int aep_rand(unsigned char *buf,int len ) + { + AEP_RV rv = AEP_R_OK; + AEP_CONNECTION_HNDL hConnection; + + CRYPTO_w_lock(CRYPTO_LOCK_RAND); + + /*Can the request be serviced with what's already in the buffer?*/ + if (len <= rand_block_bytes) + { + memcpy(buf, &rand_block[RAND_BLK_SIZE - rand_block_bytes], len); + rand_block_bytes -= len; + CRYPTO_w_unlock(CRYPTO_LOCK_RAND); + } + else + /*If not the get another block of random bytes*/ + { + CRYPTO_w_unlock(CRYPTO_LOCK_RAND); + + rv = aep_get_connection(&hConnection); + if (rv != AEP_R_OK) + { + AEPHKerr(AEPHK_F_AEP_RAND,AEPHK_R_GET_HANDLE_FAILED); + goto err_nounlock; + } + + if (len > RAND_BLK_SIZE) + { + rv = p_AEP_GenRandom(hConnection, len, 2, buf, NULL); + if (rv != AEP_R_OK) + { + AEPHKerr(AEPHK_F_AEP_RAND,AEPHK_R_GET_RANDOM_FAILED); + goto err_nounlock; + } + } + else + { + CRYPTO_w_lock(CRYPTO_LOCK_RAND); + + rv = p_AEP_GenRandom(hConnection, RAND_BLK_SIZE, 2, &rand_block[0], NULL); + if (rv != AEP_R_OK) + { + AEPHKerr(AEPHK_F_AEP_RAND,AEPHK_R_GET_RANDOM_FAILED); + + goto err; + } + + rand_block_bytes = RAND_BLK_SIZE; + + memcpy(buf, &rand_block[RAND_BLK_SIZE - rand_block_bytes], len); + rand_block_bytes -= len; + + CRYPTO_w_unlock(CRYPTO_LOCK_RAND); + } + + rv = aep_return_connection(hConnection); + if (rv != AEP_R_OK) + { + AEPHKerr(AEPHK_F_AEP_RAND,AEPHK_R_RETURN_CONNECTION_FAILED); + + goto err_nounlock; + } + } + + return 1; + err: + CRYPTO_w_unlock(CRYPTO_LOCK_RAND); + err_nounlock: + return 0; + } + +static int aep_rand_status(void) +{ + return 1; +} +#endif + +#ifndef OPENSSL_NO_RSA +static int aep_rsa_mod_exp(BIGNUM *r0, const BIGNUM *I, RSA *rsa, BN_CTX *ctx) + { + int to_return = 0; + AEP_RV rv = AEP_R_OK; + + if (!aep_dso) + { + AEPHKerr(AEPHK_F_AEP_RSA_MOD_EXP,AEPHK_R_NOT_LOADED); + goto err; + } + + /*See if we have all the necessary bits for a crt*/ + if (rsa->q && rsa->dmp1 && rsa->dmq1 && rsa->iqmp) + { + rv = aep_mod_exp_crt(r0,I,rsa->p,rsa->q, rsa->dmp1,rsa->dmq1,rsa->iqmp,ctx); + + if (rv == FAIL_TO_SW){ + const RSA_METHOD *meth = RSA_PKCS1_SSLeay(); + to_return = (*meth->rsa_mod_exp)(r0, I, rsa, ctx); + goto err; + } + else if (rv != AEP_R_OK) + goto err; + } + else + { + if (!rsa->d || !rsa->n) + { + AEPHKerr(AEPHK_F_AEP_RSA_MOD_EXP,AEPHK_R_MISSING_KEY_COMPONENTS); + goto err; + } + + rv = aep_mod_exp(r0,I,rsa->d,rsa->n,ctx); + if (rv != AEP_R_OK) + goto err; + + } + + to_return = 1; + + err: + return to_return; +} +#endif + +#ifndef OPENSSL_NO_DSA +static int aep_dsa_mod_exp(DSA *dsa, BIGNUM *rr, BIGNUM *a1, + BIGNUM *p1, BIGNUM *a2, BIGNUM *p2, BIGNUM *m, + BN_CTX *ctx, BN_MONT_CTX *in_mont) + { + BIGNUM t; + int to_return = 0; + BN_init(&t); + + /* let rr = a1 ^ p1 mod m */ + if (!aep_mod_exp(rr,a1,p1,m,ctx)) goto end; + /* let t = a2 ^ p2 mod m */ + if (!aep_mod_exp(&t,a2,p2,m,ctx)) goto end; + /* let rr = rr * t mod m */ + if (!BN_mod_mul(rr,rr,&t,m,ctx)) goto end; + to_return = 1; + end: + BN_free(&t); + return to_return; + } + +static int aep_mod_exp_dsa(DSA *dsa, BIGNUM *r, BIGNUM *a, + const BIGNUM *p, const BIGNUM *m, BN_CTX *ctx, + BN_MONT_CTX *m_ctx) + { + return aep_mod_exp(r, a, p, m, ctx); + } +#endif + +#ifndef OPENSSL_NO_RSA +/* This function is aliased to mod_exp (with the mont stuff dropped). */ +static int aep_mod_exp_mont(BIGNUM *r, const BIGNUM *a, const BIGNUM *p, + const BIGNUM *m, BN_CTX *ctx, BN_MONT_CTX *m_ctx) + { + return aep_mod_exp(r, a, p, m, ctx); + } +#endif + +#ifndef OPENSSL_NO_DH +/* This function is aliased to mod_exp (with the dh and mont dropped). */ +static int aep_mod_exp_dh(const DH *dh, BIGNUM *r, const BIGNUM *a, + const BIGNUM *p, const BIGNUM *m, BN_CTX *ctx, + BN_MONT_CTX *m_ctx) + { + return aep_mod_exp(r, a, p, m, ctx); + } +#endif + +static AEP_RV aep_get_connection(AEP_CONNECTION_HNDL_PTR phConnection) + { + int count; + AEP_RV rv = AEP_R_OK; + + /*Get the current process id*/ + pid_t curr_pid; + + CRYPTO_w_lock(CRYPTO_LOCK_ENGINE); + + curr_pid = getpid(); + + /*Check if this is the first time this is being called from the current + process*/ + if (recorded_pid != curr_pid) + { + /*Remember our pid so we can check if we're in a new process*/ + recorded_pid = curr_pid; + + /*Call Finalize to make sure we have not inherited some data + from a parent process*/ + p_AEP_Finalize(); + + /*Initialise the AEP API*/ + rv = p_AEP_Initialize(NULL); + + if (rv != AEP_R_OK) + { + AEPHKerr(AEPHK_F_AEP_GET_CONNECTION,AEPHK_R_INIT_FAILURE); + recorded_pid = 0; + goto end; + } + + /*Set the AEP big num call back functions*/ + rv = p_AEP_SetBNCallBacks(&GetBigNumSize, &MakeAEPBigNum, + &ConvertAEPBigNum); + + if (rv != AEP_R_OK) + { + AEPHKerr(AEPHK_F_AEP_GET_CONNECTION,AEPHK_R_SETBNCALLBACK_FAILURE); + recorded_pid = 0; + goto end; + } + +#ifdef AEPRAND + /*Reset the rand byte count*/ + rand_block_bytes = 0; +#endif + + /*Init the structures*/ + for (count = 0;count < MAX_PROCESS_CONNECTIONS;count ++) + { + aep_app_conn_table[count].conn_state = NotConnected; + aep_app_conn_table[count].conn_hndl = 0; + } + + /*Open a connection*/ + rv = p_AEP_OpenConnection(phConnection); + + if (rv != AEP_R_OK) + { + AEPHKerr(AEPHK_F_AEP_GET_CONNECTION,AEPHK_R_UNIT_FAILURE); + recorded_pid = 0; + goto end; + } + + aep_app_conn_table[0].conn_state = InUse; + aep_app_conn_table[0].conn_hndl = *phConnection; + goto end; + } + /*Check the existing connections to see if we can find a free one*/ + for (count = 0;count < MAX_PROCESS_CONNECTIONS;count ++) + { + if (aep_app_conn_table[count].conn_state == Connected) + { + aep_app_conn_table[count].conn_state = InUse; + *phConnection = aep_app_conn_table[count].conn_hndl; + goto end; + } + } + /*If no connections available, we're going to have to try + to open a new one*/ + for (count = 0;count < MAX_PROCESS_CONNECTIONS;count ++) + { + if (aep_app_conn_table[count].conn_state == NotConnected) + { + /*Open a connection*/ + rv = p_AEP_OpenConnection(phConnection); + + if (rv != AEP_R_OK) + { + AEPHKerr(AEPHK_F_AEP_GET_CONNECTION,AEPHK_R_UNIT_FAILURE); + goto end; + } + + aep_app_conn_table[count].conn_state = InUse; + aep_app_conn_table[count].conn_hndl = *phConnection; + goto end; + } + } + rv = AEP_R_GENERAL_ERROR; + end: + CRYPTO_w_unlock(CRYPTO_LOCK_ENGINE); + return rv; + } + + +static AEP_RV aep_return_connection(AEP_CONNECTION_HNDL hConnection) + { + int count; + + CRYPTO_w_lock(CRYPTO_LOCK_ENGINE); + + /*Find the connection item that matches this connection handle*/ + for(count = 0;count < MAX_PROCESS_CONNECTIONS;count ++) + { + if (aep_app_conn_table[count].conn_hndl == hConnection) + { + aep_app_conn_table[count].conn_state = Connected; + break; + } + } + + CRYPTO_w_unlock(CRYPTO_LOCK_ENGINE); + + return AEP_R_OK; + } + +static AEP_RV aep_close_connection(AEP_CONNECTION_HNDL hConnection) + { + int count; + AEP_RV rv = AEP_R_OK; + + CRYPTO_w_lock(CRYPTO_LOCK_ENGINE); + + /*Find the connection item that matches this connection handle*/ + for(count = 0;count < MAX_PROCESS_CONNECTIONS;count ++) + { + if (aep_app_conn_table[count].conn_hndl == hConnection) + { + rv = p_AEP_CloseConnection(aep_app_conn_table[count].conn_hndl); + if (rv != AEP_R_OK) + goto end; + aep_app_conn_table[count].conn_state = NotConnected; + aep_app_conn_table[count].conn_hndl = 0; + break; + } + } + + end: + CRYPTO_w_unlock(CRYPTO_LOCK_ENGINE); + return rv; + } + +static AEP_RV aep_close_all_connections(int use_engine_lock, int *in_use) + { + int count; + AEP_RV rv = AEP_R_OK; + + *in_use = 0; + if (use_engine_lock) CRYPTO_w_lock(CRYPTO_LOCK_ENGINE); + for (count = 0;count < MAX_PROCESS_CONNECTIONS;count ++) + { + switch (aep_app_conn_table[count].conn_state) + { + case Connected: + rv = p_AEP_CloseConnection(aep_app_conn_table[count].conn_hndl); + if (rv != AEP_R_OK) + goto end; + aep_app_conn_table[count].conn_state = NotConnected; + aep_app_conn_table[count].conn_hndl = 0; + break; + case InUse: + (*in_use)++; + break; + case NotConnected: + break; + } + } + end: + if (use_engine_lock) CRYPTO_w_unlock(CRYPTO_LOCK_ENGINE); + return rv; + } + +/*BigNum call back functions, used to convert OpenSSL bignums into AEP bignums. + Note only 32bit Openssl build support*/ + +static AEP_RV GetBigNumSize(AEP_VOID_PTR ArbBigNum, AEP_U32* BigNumSize) + { + BIGNUM* bn; + + /*Cast the ArbBigNum pointer to our BIGNUM struct*/ + bn = (BIGNUM*) ArbBigNum; + +#ifdef SIXTY_FOUR_BIT_LONG + *BigNumSize = bn->top << 3; +#else + /*Size of the bignum in bytes is equal to the bn->top (no of 32 bit + words) multiplies by 4*/ + *BigNumSize = bn->top << 2; +#endif + + return AEP_R_OK; + } + +static AEP_RV MakeAEPBigNum(AEP_VOID_PTR ArbBigNum, AEP_U32 BigNumSize, + unsigned char* AEP_BigNum) + { + BIGNUM* bn; + +#ifndef SIXTY_FOUR_BIT_LONG + unsigned char* buf; + int i; +#endif + + /*Cast the ArbBigNum pointer to our BIGNUM struct*/ + bn = (BIGNUM*) ArbBigNum; + +#ifdef SIXTY_FOUR_BIT_LONG + memcpy(AEP_BigNum, bn->d, BigNumSize); +#else + /*Must copy data into a (monotone) least significant byte first format + performing endian conversion if necessary*/ + for(i=0;itop;i++) + { + buf = (unsigned char*)&bn->d[i]; + + *((AEP_U32*)AEP_BigNum) = (AEP_U32) + ((unsigned) buf[1] << 8 | buf[0]) | + ((unsigned) buf[3] << 8 | buf[2]) << 16; + + AEP_BigNum += 4; + } +#endif + + return AEP_R_OK; + } + +/*Turn an AEP Big Num back to a user big num*/ +static AEP_RV ConvertAEPBigNum(void* ArbBigNum, AEP_U32 BigNumSize, + unsigned char* AEP_BigNum) + { + BIGNUM* bn; +#ifndef SIXTY_FOUR_BIT_LONG + int i; +#endif + + bn = (BIGNUM*)ArbBigNum; + + /*Expand the result bn so that it can hold our big num. + Size is in bits*/ + bn_expand(bn, (int)(BigNumSize << 3)); + +#ifdef SIXTY_FOUR_BIT_LONG + bn->top = BigNumSize >> 3; + + if((BigNumSize & 7) != 0) + bn->top++; + + memset(bn->d, 0, bn->top << 3); + + memcpy(bn->d, AEP_BigNum, BigNumSize); +#else + bn->top = BigNumSize >> 2; + + for(i=0;itop;i++) + { + bn->d[i] = (AEP_U32) + ((unsigned) AEP_BigNum[3] << 8 | AEP_BigNum[2]) << 16 | + ((unsigned) AEP_BigNum[1] << 8 | AEP_BigNum[0]); + AEP_BigNum += 4; + } +#endif + + return AEP_R_OK; +} + +#endif /* !OPENSSL_NO_HW_AEP */ +#endif /* !OPENSSL_NO_HW */ diff --git a/node-v0.8.14/deps/openssl/openssl/engines/e_aep.ec b/node-v0.8.14/deps/openssl/openssl/engines/e_aep.ec new file mode 100644 index 0000000..8eae642 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/engines/e_aep.ec @@ -0,0 +1 @@ +L AEPHK e_aep_err.h e_aep_err.c diff --git a/node-v0.8.14/deps/openssl/openssl/engines/e_aep_err.c b/node-v0.8.14/deps/openssl/openssl/engines/e_aep_err.c new file mode 100644 index 0000000..3f95881 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/engines/e_aep_err.c @@ -0,0 +1,161 @@ +/* e_aep_err.c */ +/* ==================================================================== + * Copyright (c) 1999-2005 The OpenSSL Project. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. All advertising materials mentioning features or use of this + * software must display the following acknowledgment: + * "This product includes software developed by the OpenSSL Project + * for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)" + * + * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to + * endorse or promote products derived from this software without + * prior written permission. For written permission, please contact + * openssl-core@OpenSSL.org. + * + * 5. Products derived from this software may not be called "OpenSSL" + * nor may "OpenSSL" appear in their names without prior written + * permission of the OpenSSL Project. + * + * 6. Redistributions of any form whatsoever must retain the following + * acknowledgment: + * "This product includes software developed by the OpenSSL Project + * for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)" + * + * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY + * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR + * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, + * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * ==================================================================== + * + * This product includes cryptographic software written by Eric Young + * (eay@cryptsoft.com). This product includes software written by Tim + * Hudson (tjh@cryptsoft.com). + * + */ + +/* NOTE: this file was auto generated by the mkerr.pl script: any changes + * made to it will be overwritten when the script next updates this file, + * only reason strings will be preserved. + */ + +#include +#include +#include "e_aep_err.h" + +/* BEGIN ERROR CODES */ +#ifndef OPENSSL_NO_ERR + +#define ERR_FUNC(func) ERR_PACK(0,func,0) +#define ERR_REASON(reason) ERR_PACK(0,0,reason) + +static ERR_STRING_DATA AEPHK_str_functs[]= + { +{ERR_FUNC(AEPHK_F_AEP_CTRL), "AEP_CTRL"}, +{ERR_FUNC(AEPHK_F_AEP_FINISH), "AEP_FINISH"}, +{ERR_FUNC(AEPHK_F_AEP_GET_CONNECTION), "AEP_GET_CONNECTION"}, +{ERR_FUNC(AEPHK_F_AEP_INIT), "AEP_INIT"}, +{ERR_FUNC(AEPHK_F_AEP_MOD_EXP), "AEP_MOD_EXP"}, +{ERR_FUNC(AEPHK_F_AEP_MOD_EXP_CRT), "AEP_MOD_EXP_CRT"}, +{ERR_FUNC(AEPHK_F_AEP_RAND), "AEP_RAND"}, +{ERR_FUNC(AEPHK_F_AEP_RSA_MOD_EXP), "AEP_RSA_MOD_EXP"}, +{0,NULL} + }; + +static ERR_STRING_DATA AEPHK_str_reasons[]= + { +{ERR_REASON(AEPHK_R_ALREADY_LOADED) ,"already loaded"}, +{ERR_REASON(AEPHK_R_CLOSE_HANDLES_FAILED),"close handles failed"}, +{ERR_REASON(AEPHK_R_CONNECTIONS_IN_USE) ,"connections in use"}, +{ERR_REASON(AEPHK_R_CTRL_COMMAND_NOT_IMPLEMENTED),"ctrl command not implemented"}, +{ERR_REASON(AEPHK_R_FINALIZE_FAILED) ,"finalize failed"}, +{ERR_REASON(AEPHK_R_GET_HANDLE_FAILED) ,"get handle failed"}, +{ERR_REASON(AEPHK_R_GET_RANDOM_FAILED) ,"get random failed"}, +{ERR_REASON(AEPHK_R_INIT_FAILURE) ,"init failure"}, +{ERR_REASON(AEPHK_R_MISSING_KEY_COMPONENTS),"missing key components"}, +{ERR_REASON(AEPHK_R_MOD_EXP_CRT_FAILED) ,"mod exp crt failed"}, +{ERR_REASON(AEPHK_R_MOD_EXP_FAILED) ,"mod exp failed"}, +{ERR_REASON(AEPHK_R_NOT_LOADED) ,"not loaded"}, +{ERR_REASON(AEPHK_R_OK) ,"ok"}, +{ERR_REASON(AEPHK_R_RETURN_CONNECTION_FAILED),"return connection failed"}, +{ERR_REASON(AEPHK_R_SETBNCALLBACK_FAILURE),"setbncallback failure"}, +{ERR_REASON(AEPHK_R_SIZE_TOO_LARGE_OR_TOO_SMALL),"size too large or too small"}, +{ERR_REASON(AEPHK_R_UNIT_FAILURE) ,"unit failure"}, +{0,NULL} + }; + +#endif + +#ifdef AEPHK_LIB_NAME +static ERR_STRING_DATA AEPHK_lib_name[]= + { +{0 ,AEPHK_LIB_NAME}, +{0,NULL} + }; +#endif + + +static int AEPHK_lib_error_code=0; +static int AEPHK_error_init=1; + +static void ERR_load_AEPHK_strings(void) + { + if (AEPHK_lib_error_code == 0) + AEPHK_lib_error_code=ERR_get_next_error_library(); + + if (AEPHK_error_init) + { + AEPHK_error_init=0; +#ifndef OPENSSL_NO_ERR + ERR_load_strings(AEPHK_lib_error_code,AEPHK_str_functs); + ERR_load_strings(AEPHK_lib_error_code,AEPHK_str_reasons); +#endif + +#ifdef AEPHK_LIB_NAME + AEPHK_lib_name->error = ERR_PACK(AEPHK_lib_error_code,0,0); + ERR_load_strings(0,AEPHK_lib_name); +#endif + } + } + +static void ERR_unload_AEPHK_strings(void) + { + if (AEPHK_error_init == 0) + { +#ifndef OPENSSL_NO_ERR + ERR_unload_strings(AEPHK_lib_error_code,AEPHK_str_functs); + ERR_unload_strings(AEPHK_lib_error_code,AEPHK_str_reasons); +#endif + +#ifdef AEPHK_LIB_NAME + ERR_unload_strings(0,AEPHK_lib_name); +#endif + AEPHK_error_init=1; + } + } + +static void ERR_AEPHK_error(int function, int reason, char *file, int line) + { + if (AEPHK_lib_error_code == 0) + AEPHK_lib_error_code=ERR_get_next_error_library(); + ERR_PUT_error(AEPHK_lib_error_code,function,reason,file,line); + } diff --git a/node-v0.8.14/deps/openssl/openssl/engines/e_aep_err.h b/node-v0.8.14/deps/openssl/openssl/engines/e_aep_err.h new file mode 100644 index 0000000..35b2e74 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/engines/e_aep_err.h @@ -0,0 +1,105 @@ +/* ==================================================================== + * Copyright (c) 2001 The OpenSSL Project. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. All advertising materials mentioning features or use of this + * software must display the following acknowledgment: + * "This product includes software developed by the OpenSSL Project + * for use in the OpenSSL Toolkit. (http://www.openssl.org/)" + * + * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to + * endorse or promote products derived from this software without + * prior written permission. For written permission, please contact + * openssl-core@openssl.org. + * + * 5. Products derived from this software may not be called "OpenSSL" + * nor may "OpenSSL" appear in their names without prior written + * permission of the OpenSSL Project. + * + * 6. Redistributions of any form whatsoever must retain the following + * acknowledgment: + * "This product includes software developed by the OpenSSL Project + * for use in the OpenSSL Toolkit (http://www.openssl.org/)" + * + * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY + * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR + * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, + * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * ==================================================================== + * + * This product includes cryptographic software written by Eric Young + * (eay@cryptsoft.com). This product includes software written by Tim + * Hudson (tjh@cryptsoft.com). + * + */ + +#ifndef HEADER_AEPHK_ERR_H +#define HEADER_AEPHK_ERR_H + +#ifdef __cplusplus +extern "C" { +#endif + +/* BEGIN ERROR CODES */ +/* The following lines are auto generated by the script mkerr.pl. Any changes + * made after this point may be overwritten when the script is next run. + */ +static void ERR_load_AEPHK_strings(void); +static void ERR_unload_AEPHK_strings(void); +static void ERR_AEPHK_error(int function, int reason, char *file, int line); +#define AEPHKerr(f,r) ERR_AEPHK_error((f),(r),__FILE__,__LINE__) + +/* Error codes for the AEPHK functions. */ + +/* Function codes. */ +#define AEPHK_F_AEP_CTRL 100 +#define AEPHK_F_AEP_FINISH 101 +#define AEPHK_F_AEP_GET_CONNECTION 102 +#define AEPHK_F_AEP_INIT 103 +#define AEPHK_F_AEP_MOD_EXP 104 +#define AEPHK_F_AEP_MOD_EXP_CRT 105 +#define AEPHK_F_AEP_RAND 106 +#define AEPHK_F_AEP_RSA_MOD_EXP 107 + +/* Reason codes. */ +#define AEPHK_R_ALREADY_LOADED 100 +#define AEPHK_R_CLOSE_HANDLES_FAILED 101 +#define AEPHK_R_CONNECTIONS_IN_USE 102 +#define AEPHK_R_CTRL_COMMAND_NOT_IMPLEMENTED 103 +#define AEPHK_R_FINALIZE_FAILED 104 +#define AEPHK_R_GET_HANDLE_FAILED 105 +#define AEPHK_R_GET_RANDOM_FAILED 106 +#define AEPHK_R_INIT_FAILURE 107 +#define AEPHK_R_MISSING_KEY_COMPONENTS 108 +#define AEPHK_R_MOD_EXP_CRT_FAILED 109 +#define AEPHK_R_MOD_EXP_FAILED 110 +#define AEPHK_R_NOT_LOADED 111 +#define AEPHK_R_OK 112 +#define AEPHK_R_RETURN_CONNECTION_FAILED 113 +#define AEPHK_R_SETBNCALLBACK_FAILURE 114 +#define AEPHK_R_SIZE_TOO_LARGE_OR_TOO_SMALL 116 +#define AEPHK_R_UNIT_FAILURE 115 + +#ifdef __cplusplus +} +#endif +#endif diff --git a/node-v0.8.14/deps/openssl/openssl/engines/e_atalla.c b/node-v0.8.14/deps/openssl/openssl/engines/e_atalla.c new file mode 100644 index 0000000..fabaa86 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/engines/e_atalla.c @@ -0,0 +1,607 @@ +/* crypto/engine/hw_atalla.c */ +/* Written by Geoff Thorpe (geoff@geoffthorpe.net) for the OpenSSL + * project 2000. + */ +/* ==================================================================== + * Copyright (c) 1999-2001 The OpenSSL Project. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. All advertising materials mentioning features or use of this + * software must display the following acknowledgment: + * "This product includes software developed by the OpenSSL Project + * for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)" + * + * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to + * endorse or promote products derived from this software without + * prior written permission. For written permission, please contact + * licensing@OpenSSL.org. + * + * 5. Products derived from this software may not be called "OpenSSL" + * nor may "OpenSSL" appear in their names without prior written + * permission of the OpenSSL Project. + * + * 6. Redistributions of any form whatsoever must retain the following + * acknowledgment: + * "This product includes software developed by the OpenSSL Project + * for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)" + * + * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY + * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR + * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, + * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * ==================================================================== + * + * This product includes cryptographic software written by Eric Young + * (eay@cryptsoft.com). This product includes software written by Tim + * Hudson (tjh@cryptsoft.com). + * + */ + +#include +#include +#include +#include +#include +#include +#ifndef OPENSSL_NO_RSA +#include +#endif +#ifndef OPENSSL_NO_DSA +#include +#endif +#ifndef OPENSSL_NO_DH +#include +#endif +#include + +#ifndef OPENSSL_NO_HW +#ifndef OPENSSL_NO_HW_ATALLA + +#ifdef FLAT_INC +#include "atalla.h" +#else +#include "vendor_defns/atalla.h" +#endif + +#define ATALLA_LIB_NAME "atalla engine" +#include "e_atalla_err.c" + +static int atalla_destroy(ENGINE *e); +static int atalla_init(ENGINE *e); +static int atalla_finish(ENGINE *e); +static int atalla_ctrl(ENGINE *e, int cmd, long i, void *p, void (*f)(void)); + +/* BIGNUM stuff */ +static int atalla_mod_exp(BIGNUM *r, const BIGNUM *a, const BIGNUM *p, + const BIGNUM *m, BN_CTX *ctx); + +#ifndef OPENSSL_NO_RSA +/* RSA stuff */ +static int atalla_rsa_mod_exp(BIGNUM *r0, const BIGNUM *I, RSA *rsa, BN_CTX *ctx); +/* This function is aliased to mod_exp (with the mont stuff dropped). */ +static int atalla_mod_exp_mont(BIGNUM *r, const BIGNUM *a, const BIGNUM *p, + const BIGNUM *m, BN_CTX *ctx, BN_MONT_CTX *m_ctx); +#endif + +#ifndef OPENSSL_NO_DSA +/* DSA stuff */ +static int atalla_dsa_mod_exp(DSA *dsa, BIGNUM *rr, BIGNUM *a1, + BIGNUM *p1, BIGNUM *a2, BIGNUM *p2, BIGNUM *m, + BN_CTX *ctx, BN_MONT_CTX *in_mont); +static int atalla_mod_exp_dsa(DSA *dsa, BIGNUM *r, BIGNUM *a, + const BIGNUM *p, const BIGNUM *m, BN_CTX *ctx, + BN_MONT_CTX *m_ctx); +#endif + +#ifndef OPENSSL_NO_DH +/* DH stuff */ +/* This function is alised to mod_exp (with the DH and mont dropped). */ +static int atalla_mod_exp_dh(const DH *dh, BIGNUM *r, + const BIGNUM *a, const BIGNUM *p, + const BIGNUM *m, BN_CTX *ctx, BN_MONT_CTX *m_ctx); +#endif + +/* The definitions for control commands specific to this engine */ +#define ATALLA_CMD_SO_PATH ENGINE_CMD_BASE +static const ENGINE_CMD_DEFN atalla_cmd_defns[] = { + {ATALLA_CMD_SO_PATH, + "SO_PATH", + "Specifies the path to the 'atasi' shared library", + ENGINE_CMD_FLAG_STRING}, + {0, NULL, NULL, 0} + }; + +#ifndef OPENSSL_NO_RSA +/* Our internal RSA_METHOD that we provide pointers to */ +static RSA_METHOD atalla_rsa = + { + "Atalla RSA method", + NULL, + NULL, + NULL, + NULL, + atalla_rsa_mod_exp, + atalla_mod_exp_mont, + NULL, + NULL, + 0, + NULL, + NULL, + NULL, + NULL + }; +#endif + +#ifndef OPENSSL_NO_DSA +/* Our internal DSA_METHOD that we provide pointers to */ +static DSA_METHOD atalla_dsa = + { + "Atalla DSA method", + NULL, /* dsa_do_sign */ + NULL, /* dsa_sign_setup */ + NULL, /* dsa_do_verify */ + atalla_dsa_mod_exp, /* dsa_mod_exp */ + atalla_mod_exp_dsa, /* bn_mod_exp */ + NULL, /* init */ + NULL, /* finish */ + 0, /* flags */ + NULL, /* app_data */ + NULL, /* dsa_paramgen */ + NULL /* dsa_keygen */ + }; +#endif + +#ifndef OPENSSL_NO_DH +/* Our internal DH_METHOD that we provide pointers to */ +static DH_METHOD atalla_dh = + { + "Atalla DH method", + NULL, + NULL, + atalla_mod_exp_dh, + NULL, + NULL, + 0, + NULL, + NULL + }; +#endif + +/* Constants used when creating the ENGINE */ +static const char *engine_atalla_id = "atalla"; +static const char *engine_atalla_name = "Atalla hardware engine support"; + +/* This internal function is used by ENGINE_atalla() and possibly by the + * "dynamic" ENGINE support too */ +static int bind_helper(ENGINE *e) + { +#ifndef OPENSSL_NO_RSA + const RSA_METHOD *meth1; +#endif +#ifndef OPENSSL_NO_DSA + const DSA_METHOD *meth2; +#endif +#ifndef OPENSSL_NO_DH + const DH_METHOD *meth3; +#endif + if(!ENGINE_set_id(e, engine_atalla_id) || + !ENGINE_set_name(e, engine_atalla_name) || +#ifndef OPENSSL_NO_RSA + !ENGINE_set_RSA(e, &atalla_rsa) || +#endif +#ifndef OPENSSL_NO_DSA + !ENGINE_set_DSA(e, &atalla_dsa) || +#endif +#ifndef OPENSSL_NO_DH + !ENGINE_set_DH(e, &atalla_dh) || +#endif + !ENGINE_set_destroy_function(e, atalla_destroy) || + !ENGINE_set_init_function(e, atalla_init) || + !ENGINE_set_finish_function(e, atalla_finish) || + !ENGINE_set_ctrl_function(e, atalla_ctrl) || + !ENGINE_set_cmd_defns(e, atalla_cmd_defns)) + return 0; + +#ifndef OPENSSL_NO_RSA + /* We know that the "PKCS1_SSLeay()" functions hook properly + * to the atalla-specific mod_exp and mod_exp_crt so we use + * those functions. NB: We don't use ENGINE_openssl() or + * anything "more generic" because something like the RSAref + * code may not hook properly, and if you own one of these + * cards then you have the right to do RSA operations on it + * anyway! */ + meth1 = RSA_PKCS1_SSLeay(); + atalla_rsa.rsa_pub_enc = meth1->rsa_pub_enc; + atalla_rsa.rsa_pub_dec = meth1->rsa_pub_dec; + atalla_rsa.rsa_priv_enc = meth1->rsa_priv_enc; + atalla_rsa.rsa_priv_dec = meth1->rsa_priv_dec; +#endif + +#ifndef OPENSSL_NO_DSA + /* Use the DSA_OpenSSL() method and just hook the mod_exp-ish + * bits. */ + meth2 = DSA_OpenSSL(); + atalla_dsa.dsa_do_sign = meth2->dsa_do_sign; + atalla_dsa.dsa_sign_setup = meth2->dsa_sign_setup; + atalla_dsa.dsa_do_verify = meth2->dsa_do_verify; +#endif + +#ifndef OPENSSL_NO_DH + /* Much the same for Diffie-Hellman */ + meth3 = DH_OpenSSL(); + atalla_dh.generate_key = meth3->generate_key; + atalla_dh.compute_key = meth3->compute_key; +#endif + + /* Ensure the atalla error handling is set up */ + ERR_load_ATALLA_strings(); + return 1; + } + +#ifdef OPENSSL_NO_DYNAMIC_ENGINE +static ENGINE *engine_atalla(void) + { + ENGINE *ret = ENGINE_new(); + if(!ret) + return NULL; + if(!bind_helper(ret)) + { + ENGINE_free(ret); + return NULL; + } + return ret; + } + +void ENGINE_load_atalla(void) + { + /* Copied from eng_[openssl|dyn].c */ + ENGINE *toadd = engine_atalla(); + if(!toadd) return; + ENGINE_add(toadd); + ENGINE_free(toadd); + ERR_clear_error(); + } +#endif + +/* This is a process-global DSO handle used for loading and unloading + * the Atalla library. NB: This is only set (or unset) during an + * init() or finish() call (reference counts permitting) and they're + * operating with global locks, so this should be thread-safe + * implicitly. */ +static DSO *atalla_dso = NULL; + +/* These are the function pointers that are (un)set when the library has + * successfully (un)loaded. */ +static tfnASI_GetHardwareConfig *p_Atalla_GetHardwareConfig = NULL; +static tfnASI_RSAPrivateKeyOpFn *p_Atalla_RSAPrivateKeyOpFn = NULL; +static tfnASI_GetPerformanceStatistics *p_Atalla_GetPerformanceStatistics = NULL; + +/* These are the static string constants for the DSO file name and the function + * symbol names to bind to. Regrettably, the DSO name on *nix appears to be + * "atasi.so" rather than something more consistent like "libatasi.so". At the + * time of writing, I'm not sure what the file name on win32 is but clearly + * native name translation is not possible (eg libatasi.so on *nix, and + * atasi.dll on win32). For the purposes of testing, I have created a symbollic + * link called "libatasi.so" so that we can use native name-translation - a + * better solution will be needed. */ +static const char *ATALLA_LIBNAME = NULL; +static const char *get_ATALLA_LIBNAME(void) + { + if(ATALLA_LIBNAME) + return ATALLA_LIBNAME; + return "atasi"; + } +static void free_ATALLA_LIBNAME(void) + { + if(ATALLA_LIBNAME) + OPENSSL_free((void*)ATALLA_LIBNAME); + ATALLA_LIBNAME = NULL; + } +static long set_ATALLA_LIBNAME(const char *name) + { + free_ATALLA_LIBNAME(); + return (((ATALLA_LIBNAME = BUF_strdup(name)) != NULL) ? 1 : 0); + } +static const char *ATALLA_F1 = "ASI_GetHardwareConfig"; +static const char *ATALLA_F2 = "ASI_RSAPrivateKeyOpFn"; +static const char *ATALLA_F3 = "ASI_GetPerformanceStatistics"; + +/* Destructor (complements the "ENGINE_atalla()" constructor) */ +static int atalla_destroy(ENGINE *e) + { + free_ATALLA_LIBNAME(); + /* Unload the atalla error strings so any error state including our + * functs or reasons won't lead to a segfault (they simply get displayed + * without corresponding string data because none will be found). */ + ERR_unload_ATALLA_strings(); + return 1; + } + +/* (de)initialisation functions. */ +static int atalla_init(ENGINE *e) + { + tfnASI_GetHardwareConfig *p1; + tfnASI_RSAPrivateKeyOpFn *p2; + tfnASI_GetPerformanceStatistics *p3; + /* Not sure of the origin of this magic value, but Ben's code had it + * and it seemed to have been working for a few people. :-) */ + unsigned int config_buf[1024]; + + if(atalla_dso != NULL) + { + ATALLAerr(ATALLA_F_ATALLA_INIT,ATALLA_R_ALREADY_LOADED); + goto err; + } + /* Attempt to load libatasi.so/atasi.dll/whatever. Needs to be + * changed unfortunately because the Atalla drivers don't have + * standard library names that can be platform-translated well. */ + /* TODO: Work out how to actually map to the names the Atalla + * drivers really use - for now a symbollic link needs to be + * created on the host system from libatasi.so to atasi.so on + * unix variants. */ + atalla_dso = DSO_load(NULL, get_ATALLA_LIBNAME(), NULL, 0); + if(atalla_dso == NULL) + { + ATALLAerr(ATALLA_F_ATALLA_INIT,ATALLA_R_NOT_LOADED); + goto err; + } + if(!(p1 = (tfnASI_GetHardwareConfig *)DSO_bind_func( + atalla_dso, ATALLA_F1)) || + !(p2 = (tfnASI_RSAPrivateKeyOpFn *)DSO_bind_func( + atalla_dso, ATALLA_F2)) || + !(p3 = (tfnASI_GetPerformanceStatistics *)DSO_bind_func( + atalla_dso, ATALLA_F3))) + { + ATALLAerr(ATALLA_F_ATALLA_INIT,ATALLA_R_NOT_LOADED); + goto err; + } + /* Copy the pointers */ + p_Atalla_GetHardwareConfig = p1; + p_Atalla_RSAPrivateKeyOpFn = p2; + p_Atalla_GetPerformanceStatistics = p3; + /* Perform a basic test to see if there's actually any unit + * running. */ + if(p1(0L, config_buf) != 0) + { + ATALLAerr(ATALLA_F_ATALLA_INIT,ATALLA_R_UNIT_FAILURE); + goto err; + } + /* Everything's fine. */ + return 1; +err: + if(atalla_dso) + DSO_free(atalla_dso); + atalla_dso = NULL; + p_Atalla_GetHardwareConfig = NULL; + p_Atalla_RSAPrivateKeyOpFn = NULL; + p_Atalla_GetPerformanceStatistics = NULL; + return 0; + } + +static int atalla_finish(ENGINE *e) + { + free_ATALLA_LIBNAME(); + if(atalla_dso == NULL) + { + ATALLAerr(ATALLA_F_ATALLA_FINISH,ATALLA_R_NOT_LOADED); + return 0; + } + if(!DSO_free(atalla_dso)) + { + ATALLAerr(ATALLA_F_ATALLA_FINISH,ATALLA_R_UNIT_FAILURE); + return 0; + } + atalla_dso = NULL; + p_Atalla_GetHardwareConfig = NULL; + p_Atalla_RSAPrivateKeyOpFn = NULL; + p_Atalla_GetPerformanceStatistics = NULL; + return 1; + } + +static int atalla_ctrl(ENGINE *e, int cmd, long i, void *p, void (*f)(void)) + { + int initialised = ((atalla_dso == NULL) ? 0 : 1); + switch(cmd) + { + case ATALLA_CMD_SO_PATH: + if(p == NULL) + { + ATALLAerr(ATALLA_F_ATALLA_CTRL,ERR_R_PASSED_NULL_PARAMETER); + return 0; + } + if(initialised) + { + ATALLAerr(ATALLA_F_ATALLA_CTRL,ATALLA_R_ALREADY_LOADED); + return 0; + } + return set_ATALLA_LIBNAME((const char *)p); + default: + break; + } + ATALLAerr(ATALLA_F_ATALLA_CTRL,ATALLA_R_CTRL_COMMAND_NOT_IMPLEMENTED); + return 0; + } + +static int atalla_mod_exp(BIGNUM *r, const BIGNUM *a, const BIGNUM *p, + const BIGNUM *m, BN_CTX *ctx) + { + /* I need somewhere to store temporary serialised values for + * use with the Atalla API calls. A neat cheat - I'll use + * BIGNUMs from the BN_CTX but access their arrays directly as + * byte arrays . This way I don't have to clean anything + * up. */ + BIGNUM *modulus; + BIGNUM *exponent; + BIGNUM *argument; + BIGNUM *result; + RSAPrivateKey keydata; + int to_return, numbytes; + + modulus = exponent = argument = result = NULL; + to_return = 0; /* expect failure */ + + if(!atalla_dso) + { + ATALLAerr(ATALLA_F_ATALLA_MOD_EXP,ATALLA_R_NOT_LOADED); + goto err; + } + /* Prepare the params */ + BN_CTX_start(ctx); + modulus = BN_CTX_get(ctx); + exponent = BN_CTX_get(ctx); + argument = BN_CTX_get(ctx); + result = BN_CTX_get(ctx); + if (!result) + { + ATALLAerr(ATALLA_F_ATALLA_MOD_EXP,ATALLA_R_BN_CTX_FULL); + goto err; + } + if(!bn_wexpand(modulus, m->top) || !bn_wexpand(exponent, m->top) || + !bn_wexpand(argument, m->top) || !bn_wexpand(result, m->top)) + { + ATALLAerr(ATALLA_F_ATALLA_MOD_EXP,ATALLA_R_BN_EXPAND_FAIL); + goto err; + } + /* Prepare the key-data */ + memset(&keydata, 0,sizeof keydata); + numbytes = BN_num_bytes(m); + memset(exponent->d, 0, numbytes); + memset(modulus->d, 0, numbytes); + BN_bn2bin(p, (unsigned char *)exponent->d + numbytes - BN_num_bytes(p)); + BN_bn2bin(m, (unsigned char *)modulus->d + numbytes - BN_num_bytes(m)); + keydata.privateExponent.data = (unsigned char *)exponent->d; + keydata.privateExponent.len = numbytes; + keydata.modulus.data = (unsigned char *)modulus->d; + keydata.modulus.len = numbytes; + /* Prepare the argument */ + memset(argument->d, 0, numbytes); + memset(result->d, 0, numbytes); + BN_bn2bin(a, (unsigned char *)argument->d + numbytes - BN_num_bytes(a)); + /* Perform the operation */ + if(p_Atalla_RSAPrivateKeyOpFn(&keydata, (unsigned char *)result->d, + (unsigned char *)argument->d, + keydata.modulus.len) != 0) + { + ATALLAerr(ATALLA_F_ATALLA_MOD_EXP,ATALLA_R_REQUEST_FAILED); + goto err; + } + /* Convert the response */ + BN_bin2bn((unsigned char *)result->d, numbytes, r); + to_return = 1; +err: + BN_CTX_end(ctx); + return to_return; + } + +#ifndef OPENSSL_NO_RSA +static int atalla_rsa_mod_exp(BIGNUM *r0, const BIGNUM *I, RSA *rsa, BN_CTX *ctx) + { + int to_return = 0; + + if(!atalla_dso) + { + ATALLAerr(ATALLA_F_ATALLA_RSA_MOD_EXP,ATALLA_R_NOT_LOADED); + goto err; + } + if(!rsa->d || !rsa->n) + { + ATALLAerr(ATALLA_F_ATALLA_RSA_MOD_EXP,ATALLA_R_MISSING_KEY_COMPONENTS); + goto err; + } + to_return = atalla_mod_exp(r0, I, rsa->d, rsa->n, ctx); +err: + return to_return; + } +#endif + +#ifndef OPENSSL_NO_DSA +/* This code was liberated and adapted from the commented-out code in + * dsa_ossl.c. Because of the unoptimised form of the Atalla acceleration + * (it doesn't have a CRT form for RSA), this function means that an + * Atalla system running with a DSA server certificate can handshake + * around 5 or 6 times faster/more than an equivalent system running with + * RSA. Just check out the "signs" statistics from the RSA and DSA parts + * of "openssl speed -engine atalla dsa1024 rsa1024". */ +static int atalla_dsa_mod_exp(DSA *dsa, BIGNUM *rr, BIGNUM *a1, + BIGNUM *p1, BIGNUM *a2, BIGNUM *p2, BIGNUM *m, + BN_CTX *ctx, BN_MONT_CTX *in_mont) + { + BIGNUM t; + int to_return = 0; + + BN_init(&t); + /* let rr = a1 ^ p1 mod m */ + if (!atalla_mod_exp(rr,a1,p1,m,ctx)) goto end; + /* let t = a2 ^ p2 mod m */ + if (!atalla_mod_exp(&t,a2,p2,m,ctx)) goto end; + /* let rr = rr * t mod m */ + if (!BN_mod_mul(rr,rr,&t,m,ctx)) goto end; + to_return = 1; +end: + BN_free(&t); + return to_return; + } + +static int atalla_mod_exp_dsa(DSA *dsa, BIGNUM *r, BIGNUM *a, + const BIGNUM *p, const BIGNUM *m, BN_CTX *ctx, + BN_MONT_CTX *m_ctx) + { + return atalla_mod_exp(r, a, p, m, ctx); + } +#endif + +#ifndef OPENSSL_NO_RSA +/* This function is aliased to mod_exp (with the mont stuff dropped). */ +static int atalla_mod_exp_mont(BIGNUM *r, const BIGNUM *a, const BIGNUM *p, + const BIGNUM *m, BN_CTX *ctx, BN_MONT_CTX *m_ctx) + { + return atalla_mod_exp(r, a, p, m, ctx); + } +#endif + +#ifndef OPENSSL_NO_DH +/* This function is aliased to mod_exp (with the dh and mont dropped). */ +static int atalla_mod_exp_dh(const DH *dh, BIGNUM *r, + const BIGNUM *a, const BIGNUM *p, + const BIGNUM *m, BN_CTX *ctx, BN_MONT_CTX *m_ctx) + { + return atalla_mod_exp(r, a, p, m, ctx); + } +#endif + +/* This stuff is needed if this ENGINE is being compiled into a self-contained + * shared-library. */ +#ifndef OPENSSL_NO_DYNAMIC_ENGINE +static int bind_fn(ENGINE *e, const char *id) + { + if(id && (strcmp(id, engine_atalla_id) != 0)) + return 0; + if(!bind_helper(e)) + return 0; + return 1; + } +IMPLEMENT_DYNAMIC_CHECK_FN() +IMPLEMENT_DYNAMIC_BIND_FN(bind_fn) +#endif /* OPENSSL_NO_DYNAMIC_ENGINE */ + +#endif /* !OPENSSL_NO_HW_ATALLA */ +#endif /* !OPENSSL_NO_HW */ diff --git a/node-v0.8.14/deps/openssl/openssl/engines/e_atalla.ec b/node-v0.8.14/deps/openssl/openssl/engines/e_atalla.ec new file mode 100644 index 0000000..1d735e1 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/engines/e_atalla.ec @@ -0,0 +1 @@ +L ATALLA e_atalla_err.h e_atalla_err.c diff --git a/node-v0.8.14/deps/openssl/openssl/engines/e_atalla_err.c b/node-v0.8.14/deps/openssl/openssl/engines/e_atalla_err.c new file mode 100644 index 0000000..fd3e004 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/engines/e_atalla_err.c @@ -0,0 +1,149 @@ +/* e_atalla_err.c */ +/* ==================================================================== + * Copyright (c) 1999-2005 The OpenSSL Project. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. All advertising materials mentioning features or use of this + * software must display the following acknowledgment: + * "This product includes software developed by the OpenSSL Project + * for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)" + * + * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to + * endorse or promote products derived from this software without + * prior written permission. For written permission, please contact + * openssl-core@OpenSSL.org. + * + * 5. Products derived from this software may not be called "OpenSSL" + * nor may "OpenSSL" appear in their names without prior written + * permission of the OpenSSL Project. + * + * 6. Redistributions of any form whatsoever must retain the following + * acknowledgment: + * "This product includes software developed by the OpenSSL Project + * for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)" + * + * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY + * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR + * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, + * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * ==================================================================== + * + * This product includes cryptographic software written by Eric Young + * (eay@cryptsoft.com). This product includes software written by Tim + * Hudson (tjh@cryptsoft.com). + * + */ + +/* NOTE: this file was auto generated by the mkerr.pl script: any changes + * made to it will be overwritten when the script next updates this file, + * only reason strings will be preserved. + */ + +#include +#include +#include "e_atalla_err.h" + +/* BEGIN ERROR CODES */ +#ifndef OPENSSL_NO_ERR + +#define ERR_FUNC(func) ERR_PACK(0,func,0) +#define ERR_REASON(reason) ERR_PACK(0,0,reason) + +static ERR_STRING_DATA ATALLA_str_functs[]= + { +{ERR_FUNC(ATALLA_F_ATALLA_CTRL), "ATALLA_CTRL"}, +{ERR_FUNC(ATALLA_F_ATALLA_FINISH), "ATALLA_FINISH"}, +{ERR_FUNC(ATALLA_F_ATALLA_INIT), "ATALLA_INIT"}, +{ERR_FUNC(ATALLA_F_ATALLA_MOD_EXP), "ATALLA_MOD_EXP"}, +{ERR_FUNC(ATALLA_F_ATALLA_RSA_MOD_EXP), "ATALLA_RSA_MOD_EXP"}, +{0,NULL} + }; + +static ERR_STRING_DATA ATALLA_str_reasons[]= + { +{ERR_REASON(ATALLA_R_ALREADY_LOADED) ,"already loaded"}, +{ERR_REASON(ATALLA_R_BN_CTX_FULL) ,"bn ctx full"}, +{ERR_REASON(ATALLA_R_BN_EXPAND_FAIL) ,"bn expand fail"}, +{ERR_REASON(ATALLA_R_CTRL_COMMAND_NOT_IMPLEMENTED),"ctrl command not implemented"}, +{ERR_REASON(ATALLA_R_MISSING_KEY_COMPONENTS),"missing key components"}, +{ERR_REASON(ATALLA_R_NOT_LOADED) ,"not loaded"}, +{ERR_REASON(ATALLA_R_REQUEST_FAILED) ,"request failed"}, +{ERR_REASON(ATALLA_R_UNIT_FAILURE) ,"unit failure"}, +{0,NULL} + }; + +#endif + +#ifdef ATALLA_LIB_NAME +static ERR_STRING_DATA ATALLA_lib_name[]= + { +{0 ,ATALLA_LIB_NAME}, +{0,NULL} + }; +#endif + + +static int ATALLA_lib_error_code=0; +static int ATALLA_error_init=1; + +static void ERR_load_ATALLA_strings(void) + { + if (ATALLA_lib_error_code == 0) + ATALLA_lib_error_code=ERR_get_next_error_library(); + + if (ATALLA_error_init) + { + ATALLA_error_init=0; +#ifndef OPENSSL_NO_ERR + ERR_load_strings(ATALLA_lib_error_code,ATALLA_str_functs); + ERR_load_strings(ATALLA_lib_error_code,ATALLA_str_reasons); +#endif + +#ifdef ATALLA_LIB_NAME + ATALLA_lib_name->error = ERR_PACK(ATALLA_lib_error_code,0,0); + ERR_load_strings(0,ATALLA_lib_name); +#endif + } + } + +static void ERR_unload_ATALLA_strings(void) + { + if (ATALLA_error_init == 0) + { +#ifndef OPENSSL_NO_ERR + ERR_unload_strings(ATALLA_lib_error_code,ATALLA_str_functs); + ERR_unload_strings(ATALLA_lib_error_code,ATALLA_str_reasons); +#endif + +#ifdef ATALLA_LIB_NAME + ERR_unload_strings(0,ATALLA_lib_name); +#endif + ATALLA_error_init=1; + } + } + +static void ERR_ATALLA_error(int function, int reason, char *file, int line) + { + if (ATALLA_lib_error_code == 0) + ATALLA_lib_error_code=ERR_get_next_error_library(); + ERR_PUT_error(ATALLA_lib_error_code,function,reason,file,line); + } diff --git a/node-v0.8.14/deps/openssl/openssl/engines/e_atalla_err.h b/node-v0.8.14/deps/openssl/openssl/engines/e_atalla_err.h new file mode 100644 index 0000000..36e09bf --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/engines/e_atalla_err.h @@ -0,0 +1,93 @@ +/* ==================================================================== + * Copyright (c) 2001 The OpenSSL Project. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. All advertising materials mentioning features or use of this + * software must display the following acknowledgment: + * "This product includes software developed by the OpenSSL Project + * for use in the OpenSSL Toolkit. (http://www.openssl.org/)" + * + * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to + * endorse or promote products derived from this software without + * prior written permission. For written permission, please contact + * openssl-core@openssl.org. + * + * 5. Products derived from this software may not be called "OpenSSL" + * nor may "OpenSSL" appear in their names without prior written + * permission of the OpenSSL Project. + * + * 6. Redistributions of any form whatsoever must retain the following + * acknowledgment: + * "This product includes software developed by the OpenSSL Project + * for use in the OpenSSL Toolkit (http://www.openssl.org/)" + * + * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY + * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR + * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, + * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * ==================================================================== + * + * This product includes cryptographic software written by Eric Young + * (eay@cryptsoft.com). This product includes software written by Tim + * Hudson (tjh@cryptsoft.com). + * + */ + +#ifndef HEADER_ATALLA_ERR_H +#define HEADER_ATALLA_ERR_H + +#ifdef __cplusplus +extern "C" { +#endif + +/* BEGIN ERROR CODES */ +/* The following lines are auto generated by the script mkerr.pl. Any changes + * made after this point may be overwritten when the script is next run. + */ +static void ERR_load_ATALLA_strings(void); +static void ERR_unload_ATALLA_strings(void); +static void ERR_ATALLA_error(int function, int reason, char *file, int line); +#define ATALLAerr(f,r) ERR_ATALLA_error((f),(r),__FILE__,__LINE__) + +/* Error codes for the ATALLA functions. */ + +/* Function codes. */ +#define ATALLA_F_ATALLA_CTRL 100 +#define ATALLA_F_ATALLA_FINISH 101 +#define ATALLA_F_ATALLA_INIT 102 +#define ATALLA_F_ATALLA_MOD_EXP 103 +#define ATALLA_F_ATALLA_RSA_MOD_EXP 104 + +/* Reason codes. */ +#define ATALLA_R_ALREADY_LOADED 100 +#define ATALLA_R_BN_CTX_FULL 101 +#define ATALLA_R_BN_EXPAND_FAIL 102 +#define ATALLA_R_CTRL_COMMAND_NOT_IMPLEMENTED 103 +#define ATALLA_R_MISSING_KEY_COMPONENTS 104 +#define ATALLA_R_NOT_LOADED 105 +#define ATALLA_R_REQUEST_FAILED 106 +#define ATALLA_R_UNIT_FAILURE 107 + +#ifdef __cplusplus +} +#endif +#endif diff --git a/node-v0.8.14/deps/openssl/openssl/engines/e_capi.c b/node-v0.8.14/deps/openssl/openssl/engines/e_capi.c new file mode 100644 index 0000000..24b620f --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/engines/e_capi.c @@ -0,0 +1,1824 @@ +/* engines/e_capi.c */ +/* Written by Dr Stephen N Henson (steve@openssl.org) for the OpenSSL + * project. + */ +/* ==================================================================== + * Copyright (c) 2008 The OpenSSL Project. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. All advertising materials mentioning features or use of this + * software must display the following acknowledgment: + * "This product includes software developed by the OpenSSL Project + * for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)" + * + * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to + * endorse or promote products derived from this software without + * prior written permission. For written permission, please contact + * licensing@OpenSSL.org. + * + * 5. Products derived from this software may not be called "OpenSSL" + * nor may "OpenSSL" appear in their names without prior written + * permission of the OpenSSL Project. + * + * 6. Redistributions of any form whatsoever must retain the following + * acknowledgment: + * "This product includes software developed by the OpenSSL Project + * for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)" + * + * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY + * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR + * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, + * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * ==================================================================== + */ + + +#include +#include +#include +#include +#include + +#ifdef OPENSSL_SYS_WIN32 +#ifndef OPENSSL_NO_CAPIENG + +#include + +#include + +#ifndef _WIN32_WINNT +#define _WIN32_WINNT 0x0400 +#endif + +#include + +/* + * This module uses several "new" interfaces, among which is + * CertGetCertificateContextProperty. CERT_KEY_PROV_INFO_PROP_ID is + * one of possible values you can pass to function in question. By + * checking if it's defined we can see if wincrypt.h and accompanying + * crypt32.lib are in shape. The native MingW32 headers up to and + * including __W32API_VERSION 3.14 lack of struct DSSPUBKEY and the + * defines CERT_STORE_PROV_SYSTEM_A and CERT_STORE_READONLY_FLAG, + * so we check for these too and avoid compiling. + * Yes, it's rather "weak" test and if compilation fails, + * then re-configure with -DOPENSSL_NO_CAPIENG. + */ +#if defined(CERT_KEY_PROV_INFO_PROP_ID) && \ + defined(CERT_STORE_PROV_SYSTEM_A) && \ + defined(CERT_STORE_READONLY_FLAG) +# define __COMPILE_CAPIENG +#endif /* CERT_KEY_PROV_INFO_PROP_ID */ +#endif /* OPENSSL_NO_CAPIENG */ +#endif /* OPENSSL_SYS_WIN32 */ + +#ifdef __COMPILE_CAPIENG + +#undef X509_EXTENSIONS +#undef X509_CERT_PAIR + +/* Definitions which may be missing from earlier version of headers */ +#ifndef CERT_STORE_OPEN_EXISTING_FLAG +#define CERT_STORE_OPEN_EXISTING_FLAG 0x00004000 +#endif + +#ifndef CERT_STORE_CREATE_NEW_FLAG +#define CERT_STORE_CREATE_NEW_FLAG 0x00002000 +#endif + +#ifndef CERT_SYSTEM_STORE_CURRENT_USER +#define CERT_SYSTEM_STORE_CURRENT_USER 0x00010000 +#endif + +#include +#include +#include + +#include "e_capi_err.h" +#include "e_capi_err.c" + + +static const char *engine_capi_id = "capi"; +static const char *engine_capi_name = "CryptoAPI ENGINE"; + +typedef struct CAPI_CTX_st CAPI_CTX; +typedef struct CAPI_KEY_st CAPI_KEY; + +static void capi_addlasterror(void); +static void capi_adderror(DWORD err); + +static void CAPI_trace(CAPI_CTX *ctx, char *format, ...); + +static int capi_list_providers(CAPI_CTX *ctx, BIO *out); +static int capi_list_containers(CAPI_CTX *ctx, BIO *out); +int capi_list_certs(CAPI_CTX *ctx, BIO *out, char *storename); +void capi_free_key(CAPI_KEY *key); + +static PCCERT_CONTEXT capi_find_cert(CAPI_CTX *ctx, const char *id, HCERTSTORE hstore); + +CAPI_KEY *capi_find_key(CAPI_CTX *ctx, const char *id); + +static EVP_PKEY *capi_load_privkey(ENGINE *eng, const char *key_id, + UI_METHOD *ui_method, void *callback_data); +static int capi_rsa_sign(int dtype, const unsigned char *m, unsigned int m_len, + unsigned char *sigret, unsigned int *siglen, const RSA *rsa); +static int capi_rsa_priv_enc(int flen, const unsigned char *from, + unsigned char *to, RSA *rsa, int padding); +static int capi_rsa_priv_dec(int flen, const unsigned char *from, + unsigned char *to, RSA *rsa, int padding); +static int capi_rsa_free(RSA *rsa); + +static DSA_SIG *capi_dsa_do_sign(const unsigned char *digest, int dlen, + DSA *dsa); +static int capi_dsa_free(DSA *dsa); + +static int capi_load_ssl_client_cert(ENGINE *e, SSL *ssl, + STACK_OF(X509_NAME) *ca_dn, X509 **pcert, EVP_PKEY **pkey, + STACK_OF(X509) **pother, UI_METHOD *ui_method, void *callback_data); + +static int cert_select_simple(ENGINE *e, SSL *ssl, STACK_OF(X509) *certs); +#ifdef OPENSSL_CAPIENG_DIALOG +static int cert_select_dialog(ENGINE *e, SSL *ssl, STACK_OF(X509) *certs); +#endif + +typedef PCCERT_CONTEXT (WINAPI *CERTDLG)(HCERTSTORE, HWND, LPCWSTR, + LPCWSTR, DWORD, DWORD, + void *); +typedef HWND (WINAPI *GETCONSWIN)(void); + +/* This structure contains CAPI ENGINE specific data: + * it contains various global options and affects how + * other functions behave. + */ + +#define CAPI_DBG_TRACE 2 +#define CAPI_DBG_ERROR 1 + +struct CAPI_CTX_st { + int debug_level; + char *debug_file; + /* Parameters to use for container lookup */ + DWORD keytype; + LPSTR cspname; + DWORD csptype; + /* Certificate store name to use */ + LPSTR storename; + LPSTR ssl_client_store; + /* System store flags */ + DWORD store_flags; + +/* Lookup string meanings in load_private_key */ +/* Substring of subject: uses "storename" */ +#define CAPI_LU_SUBSTR 1 +/* Friendly name: uses storename */ +#define CAPI_LU_FNAME 2 +/* Container name: uses cspname, keytype */ +#define CAPI_LU_CONTNAME 3 + int lookup_method; +/* Info to dump with dumpcerts option */ +/* Issuer and serial name strings */ +#define CAPI_DMP_SUMMARY 0x1 +/* Friendly name */ +#define CAPI_DMP_FNAME 0x2 +/* Full X509_print dump */ +#define CAPI_DMP_FULL 0x4 +/* Dump PEM format certificate */ +#define CAPI_DMP_PEM 0x8 +/* Dump pseudo key (if possible) */ +#define CAPI_DMP_PSKEY 0x10 +/* Dump key info (if possible) */ +#define CAPI_DMP_PKEYINFO 0x20 + + DWORD dump_flags; + int (*client_cert_select)(ENGINE *e, SSL *ssl, STACK_OF(X509) *certs); + + CERTDLG certselectdlg; + GETCONSWIN getconswindow; +}; + + +static CAPI_CTX *capi_ctx_new(); +static void capi_ctx_free(CAPI_CTX *ctx); +static int capi_ctx_set_provname(CAPI_CTX *ctx, LPSTR pname, DWORD type, int check); +static int capi_ctx_set_provname_idx(CAPI_CTX *ctx, int idx); + +#define CAPI_CMD_LIST_CERTS ENGINE_CMD_BASE +#define CAPI_CMD_LOOKUP_CERT (ENGINE_CMD_BASE + 1) +#define CAPI_CMD_DEBUG_LEVEL (ENGINE_CMD_BASE + 2) +#define CAPI_CMD_DEBUG_FILE (ENGINE_CMD_BASE + 3) +#define CAPI_CMD_KEYTYPE (ENGINE_CMD_BASE + 4) +#define CAPI_CMD_LIST_CSPS (ENGINE_CMD_BASE + 5) +#define CAPI_CMD_SET_CSP_IDX (ENGINE_CMD_BASE + 6) +#define CAPI_CMD_SET_CSP_NAME (ENGINE_CMD_BASE + 7) +#define CAPI_CMD_SET_CSP_TYPE (ENGINE_CMD_BASE + 8) +#define CAPI_CMD_LIST_CONTAINERS (ENGINE_CMD_BASE + 9) +#define CAPI_CMD_LIST_OPTIONS (ENGINE_CMD_BASE + 10) +#define CAPI_CMD_LOOKUP_METHOD (ENGINE_CMD_BASE + 11) +#define CAPI_CMD_STORE_NAME (ENGINE_CMD_BASE + 12) +#define CAPI_CMD_STORE_FLAGS (ENGINE_CMD_BASE + 13) + +static const ENGINE_CMD_DEFN capi_cmd_defns[] = { + {CAPI_CMD_LIST_CERTS, + "list_certs", + "List all certificates in store", + ENGINE_CMD_FLAG_NO_INPUT}, + {CAPI_CMD_LOOKUP_CERT, + "lookup_cert", + "Lookup and output certificates", + ENGINE_CMD_FLAG_STRING}, + {CAPI_CMD_DEBUG_LEVEL, + "debug_level", + "debug level (1=errors, 2=trace)", + ENGINE_CMD_FLAG_NUMERIC}, + {CAPI_CMD_DEBUG_FILE, + "debug_file", + "debugging filename)", + ENGINE_CMD_FLAG_STRING}, + {CAPI_CMD_KEYTYPE, + "key_type", + "Key type: 1=AT_KEYEXCHANGE (default), 2=AT_SIGNATURE", + ENGINE_CMD_FLAG_NUMERIC}, + {CAPI_CMD_LIST_CSPS, + "list_csps", + "List all CSPs", + ENGINE_CMD_FLAG_NO_INPUT}, + {CAPI_CMD_SET_CSP_IDX, + "csp_idx", + "Set CSP by index", + ENGINE_CMD_FLAG_NUMERIC}, + {CAPI_CMD_SET_CSP_NAME, + "csp_name", + "Set CSP name, (default CSP used if not specified)", + ENGINE_CMD_FLAG_STRING}, + {CAPI_CMD_SET_CSP_TYPE, + "csp_type", + "Set CSP type, (default RSA_PROV_FULL)", + ENGINE_CMD_FLAG_NUMERIC}, + {CAPI_CMD_LIST_CONTAINERS, + "list_containers", + "list container names", + ENGINE_CMD_FLAG_NO_INPUT}, + {CAPI_CMD_LIST_OPTIONS, + "list_options", + "Set list options (1=summary,2=friendly name, 4=full printout, 8=PEM output, 16=XXX, " + "32=private key info)", + ENGINE_CMD_FLAG_NUMERIC}, + {CAPI_CMD_LOOKUP_METHOD, + "lookup_method", + "Set key lookup method (1=substring, 2=friendlyname, 3=container name)", + ENGINE_CMD_FLAG_NUMERIC}, + {CAPI_CMD_STORE_NAME, + "store_name", + "certificate store name, default \"MY\"", + ENGINE_CMD_FLAG_STRING}, + {CAPI_CMD_STORE_FLAGS, + "store_flags", + "Certificate store flags: 1 = system store", + ENGINE_CMD_FLAG_NUMERIC}, + + {0, NULL, NULL, 0} + }; + +static int capi_idx = -1; +static int rsa_capi_idx = -1; +static int dsa_capi_idx = -1; +static int cert_capi_idx = -1; + +static int capi_ctrl(ENGINE *e, int cmd, long i, void *p, void (*f)(void)) + { + int ret = 1; + CAPI_CTX *ctx; + BIO *out; + if (capi_idx == -1) + { + CAPIerr(CAPI_F_CAPI_CTRL, CAPI_R_ENGINE_NOT_INITIALIZED); + return 0; + } + ctx = ENGINE_get_ex_data(e, capi_idx); + out = BIO_new_fp(stdout, BIO_NOCLOSE); + switch (cmd) + { + case CAPI_CMD_LIST_CSPS: + ret = capi_list_providers(ctx, out); + break; + + case CAPI_CMD_LIST_CERTS: + ret = capi_list_certs(ctx, out, NULL); + break; + + case CAPI_CMD_LOOKUP_CERT: + ret = capi_list_certs(ctx, out, p); + break; + + case CAPI_CMD_LIST_CONTAINERS: + ret = capi_list_containers(ctx, out); + break; + + case CAPI_CMD_STORE_NAME: + if (ctx->storename) + OPENSSL_free(ctx->storename); + ctx->storename = BUF_strdup(p); + CAPI_trace(ctx, "Setting store name to %s\n", p); + break; + + case CAPI_CMD_STORE_FLAGS: + if (i & 1) + { + ctx->store_flags |= CERT_SYSTEM_STORE_LOCAL_MACHINE; + ctx->store_flags &= ~CERT_SYSTEM_STORE_CURRENT_USER; + } + else + { + ctx->store_flags |= CERT_SYSTEM_STORE_CURRENT_USER; + ctx->store_flags &= ~CERT_SYSTEM_STORE_LOCAL_MACHINE; + } + CAPI_trace(ctx, "Setting flags to %d\n", i); + break; + + case CAPI_CMD_DEBUG_LEVEL: + ctx->debug_level = (int)i; + CAPI_trace(ctx, "Setting debug level to %d\n", ctx->debug_level); + break; + + case CAPI_CMD_DEBUG_FILE: + ctx->debug_file = BUF_strdup(p); + CAPI_trace(ctx, "Setting debug file to %s\n", ctx->debug_file); + break; + + case CAPI_CMD_KEYTYPE: + ctx->keytype = i; + CAPI_trace(ctx, "Setting key type to %d\n", ctx->keytype); + break; + + case CAPI_CMD_SET_CSP_IDX: + ret = capi_ctx_set_provname_idx(ctx, i); + break; + + case CAPI_CMD_LIST_OPTIONS: + ctx->dump_flags = i; + break; + + case CAPI_CMD_LOOKUP_METHOD: + if (i < 1 || i > 3) + { + CAPIerr(CAPI_F_CAPI_CTRL, CAPI_R_INVALID_LOOKUP_METHOD); + return 0; + } + ctx->lookup_method = i; + break; + + case CAPI_CMD_SET_CSP_NAME: + ret = capi_ctx_set_provname(ctx, p, ctx->csptype, 1); + break; + + case CAPI_CMD_SET_CSP_TYPE: + ctx->csptype = i; + break; + + default: + CAPIerr(CAPI_F_CAPI_CTRL, CAPI_R_UNKNOWN_COMMAND); + ret = 0; + } + + BIO_free(out); + return ret; + + } + +static RSA_METHOD capi_rsa_method = + { + "CryptoAPI RSA method", + 0, /* pub_enc */ + 0, /* pub_dec */ + capi_rsa_priv_enc, /* priv_enc */ + capi_rsa_priv_dec, /* priv_dec */ + 0, /* rsa_mod_exp */ + 0, /* bn_mod_exp */ + 0, /* init */ + capi_rsa_free, /* finish */ + RSA_FLAG_SIGN_VER, /* flags */ + NULL, /* app_data */ + capi_rsa_sign, /* rsa_sign */ + 0 /* rsa_verify */ + }; + +static DSA_METHOD capi_dsa_method = + { + "CryptoAPI DSA method", + capi_dsa_do_sign, /* dsa_do_sign */ + 0, /* dsa_sign_setup */ + 0, /* dsa_do_verify */ + 0, /* dsa_mod_exp */ + 0, /* bn_mod_exp */ + 0, /* init */ + capi_dsa_free, /* finish */ + 0, /* flags */ + NULL, /* app_data */ + 0, /* dsa_paramgen */ + 0 /* dsa_keygen */ + }; + +static int capi_init(ENGINE *e) + { + CAPI_CTX *ctx; + const RSA_METHOD *ossl_rsa_meth; + const DSA_METHOD *ossl_dsa_meth; + capi_idx = ENGINE_get_ex_new_index(0, NULL, NULL, NULL, 0); + cert_capi_idx = X509_get_ex_new_index(0, NULL, NULL, NULL, 0); + + ctx = capi_ctx_new(); + if (!ctx || (capi_idx < 0)) + goto memerr; + + ENGINE_set_ex_data(e, capi_idx, ctx); + /* Setup RSA_METHOD */ + rsa_capi_idx = RSA_get_ex_new_index(0, NULL, NULL, NULL, 0); + ossl_rsa_meth = RSA_PKCS1_SSLeay(); + capi_rsa_method.rsa_pub_enc = ossl_rsa_meth->rsa_pub_enc; + capi_rsa_method.rsa_pub_dec = ossl_rsa_meth->rsa_pub_dec; + capi_rsa_method.rsa_mod_exp = ossl_rsa_meth->rsa_mod_exp; + capi_rsa_method.bn_mod_exp = ossl_rsa_meth->bn_mod_exp; + + /* Setup DSA Method */ + dsa_capi_idx = DSA_get_ex_new_index(0, NULL, NULL, NULL, 0); + ossl_dsa_meth = DSA_OpenSSL(); + capi_dsa_method.dsa_do_verify = ossl_dsa_meth->dsa_do_verify; + capi_dsa_method.dsa_mod_exp = ossl_dsa_meth->dsa_mod_exp; + capi_dsa_method.bn_mod_exp = ossl_dsa_meth->bn_mod_exp; + +#ifdef OPENSSL_CAPIENG_DIALOG + { + HMODULE cryptui = LoadLibrary(TEXT("CRYPTUI.DLL")); + HMODULE kernel = GetModuleHandle(TEXT("KERNEL32.DLL")); + if (cryptui) + ctx->certselectdlg = (CERTDLG)GetProcAddress(cryptui, "CryptUIDlgSelectCertificateFromStore"); + if (kernel) + ctx->getconswindow = (GETCONSWIN)GetProcAddress(kernel, "GetConsoleWindow"); + if (cryptui && !OPENSSL_isservice()) + ctx->client_cert_select = cert_select_dialog; + } +#endif + + + return 1; + + memerr: + CAPIerr(CAPI_F_CAPI_INIT, ERR_R_MALLOC_FAILURE); + return 0; + + return 1; + } + +static int capi_destroy(ENGINE *e) + { + ERR_unload_CAPI_strings(); + return 1; + } + +static int capi_finish(ENGINE *e) + { + CAPI_CTX *ctx; + ctx = ENGINE_get_ex_data(e, capi_idx); + capi_ctx_free(ctx); + ENGINE_set_ex_data(e, capi_idx, NULL); + return 1; + } + + +/* CryptoAPI key application data. This contains + * a handle to the private key container (for sign operations) + * and a handle to the key (for decrypt operations). + */ + +struct CAPI_KEY_st + { + /* Associated certificate context (if any) */ + PCCERT_CONTEXT pcert; + HCRYPTPROV hprov; + HCRYPTKEY key; + DWORD keyspec; + }; + +static int bind_capi(ENGINE *e) + { + if (!ENGINE_set_id(e, engine_capi_id) + || !ENGINE_set_name(e, engine_capi_name) + || !ENGINE_set_init_function(e, capi_init) + || !ENGINE_set_finish_function(e, capi_finish) + || !ENGINE_set_destroy_function(e, capi_destroy) + || !ENGINE_set_RSA(e, &capi_rsa_method) + || !ENGINE_set_DSA(e, &capi_dsa_method) + || !ENGINE_set_load_privkey_function(e, capi_load_privkey) + || !ENGINE_set_load_ssl_client_cert_function(e, + capi_load_ssl_client_cert) + || !ENGINE_set_cmd_defns(e, capi_cmd_defns) + || !ENGINE_set_ctrl_function(e, capi_ctrl)) + return 0; + ERR_load_CAPI_strings(); + + return 1; + + } + +#ifndef OPENSSL_NO_DYNAMIC_ENGINE +static int bind_helper(ENGINE *e, const char *id) + { + if(id && (strcmp(id, engine_capi_id) != 0)) + return 0; + if(!bind_capi(e)) + return 0; + return 1; + } +IMPLEMENT_DYNAMIC_CHECK_FN() +IMPLEMENT_DYNAMIC_BIND_FN(bind_helper) +#else +static ENGINE *engine_capi(void) + { + ENGINE *ret = ENGINE_new(); + if(!ret) + return NULL; + if(!bind_capi(ret)) + { + ENGINE_free(ret); + return NULL; + } + return ret; + } + +void ENGINE_load_capi(void) + { + /* Copied from eng_[openssl|dyn].c */ + ENGINE *toadd = engine_capi(); + if(!toadd) return; + ENGINE_add(toadd); + ENGINE_free(toadd); + ERR_clear_error(); + } +#endif + + +static int lend_tobn(BIGNUM *bn, unsigned char *bin, int binlen) + { + int i; + /* Reverse buffer in place: since this is a keyblob structure + * that will be freed up after conversion anyway it doesn't + * matter if we change it. + */ + for(i = 0; i < binlen / 2; i++) + { + unsigned char c; + c = bin[i]; + bin[i] = bin[binlen - i - 1]; + bin[binlen - i - 1] = c; + } + + if (!BN_bin2bn(bin, binlen, bn)) + return 0; + return 1; + } + +/* Given a CAPI_KEY get an EVP_PKEY structure */ + +static EVP_PKEY *capi_get_pkey(ENGINE *eng, CAPI_KEY *key) + { + unsigned char *pubkey = NULL; + DWORD len; + BLOBHEADER *bh; + RSA *rkey = NULL; + DSA *dkey = NULL; + EVP_PKEY *ret = NULL; + if (!CryptExportKey(key->key, 0, PUBLICKEYBLOB, 0, NULL, &len)) + { + CAPIerr(CAPI_F_CAPI_GET_PKEY, CAPI_R_PUBKEY_EXPORT_LENGTH_ERROR); + capi_addlasterror(); + return NULL; + } + + pubkey = OPENSSL_malloc(len); + + if (!pubkey) + goto memerr; + + if (!CryptExportKey(key->key, 0, PUBLICKEYBLOB, 0, pubkey, &len)) + { + CAPIerr(CAPI_F_CAPI_GET_PKEY, CAPI_R_PUBKEY_EXPORT_ERROR); + capi_addlasterror(); + goto err; + } + + bh = (BLOBHEADER *)pubkey; + if (bh->bType != PUBLICKEYBLOB) + { + CAPIerr(CAPI_F_CAPI_GET_PKEY, CAPI_R_INVALID_PUBLIC_KEY_BLOB); + goto err; + } + if (bh->aiKeyAlg == CALG_RSA_SIGN || bh->aiKeyAlg == CALG_RSA_KEYX) + { + RSAPUBKEY *rp; + DWORD rsa_modlen; + unsigned char *rsa_modulus; + rp = (RSAPUBKEY *)(bh + 1); + if (rp->magic != 0x31415352) + { + char magstr[10]; + BIO_snprintf(magstr, 10, "%lx", rp->magic); + CAPIerr(CAPI_F_CAPI_GET_PKEY, CAPI_R_INVALID_RSA_PUBLIC_KEY_BLOB_MAGIC_NUMBER); + ERR_add_error_data(2, "magic=0x", magstr); + goto err; + } + rsa_modulus = (unsigned char *)(rp + 1); + rkey = RSA_new_method(eng); + if (!rkey) + goto memerr; + + rkey->e = BN_new(); + rkey->n = BN_new(); + + if (!rkey->e || !rkey->n) + goto memerr; + + if (!BN_set_word(rkey->e, rp->pubexp)) + goto memerr; + + rsa_modlen = rp->bitlen / 8; + if (!lend_tobn(rkey->n, rsa_modulus, rsa_modlen)) + goto memerr; + + RSA_set_ex_data(rkey, rsa_capi_idx, key); + + if (!(ret = EVP_PKEY_new())) + goto memerr; + + EVP_PKEY_assign_RSA(ret, rkey); + rkey = NULL; + + } + else if (bh->aiKeyAlg == CALG_DSS_SIGN) + { + DSSPUBKEY *dp; + DWORD dsa_plen; + unsigned char *btmp; + dp = (DSSPUBKEY *)(bh + 1); + if (dp->magic != 0x31535344) + { + char magstr[10]; + BIO_snprintf(magstr, 10, "%lx", dp->magic); + CAPIerr(CAPI_F_CAPI_GET_PKEY, CAPI_R_INVALID_DSA_PUBLIC_KEY_BLOB_MAGIC_NUMBER); + ERR_add_error_data(2, "magic=0x", magstr); + goto err; + } + dsa_plen = dp->bitlen / 8; + btmp = (unsigned char *)(dp + 1); + dkey = DSA_new_method(eng); + if (!dkey) + goto memerr; + dkey->p = BN_new(); + dkey->q = BN_new(); + dkey->g = BN_new(); + dkey->pub_key = BN_new(); + if (!dkey->p || !dkey->q || !dkey->g || !dkey->pub_key) + goto memerr; + if (!lend_tobn(dkey->p, btmp, dsa_plen)) + goto memerr; + btmp += dsa_plen; + if (!lend_tobn(dkey->q, btmp, 20)) + goto memerr; + btmp += 20; + if (!lend_tobn(dkey->g, btmp, dsa_plen)) + goto memerr; + btmp += dsa_plen; + if (!lend_tobn(dkey->pub_key, btmp, dsa_plen)) + goto memerr; + btmp += dsa_plen; + + DSA_set_ex_data(dkey, dsa_capi_idx, key); + + if (!(ret = EVP_PKEY_new())) + goto memerr; + + EVP_PKEY_assign_DSA(ret, dkey); + dkey = NULL; + } + else + { + char algstr[10]; + BIO_snprintf(algstr, 10, "%lx", bh->aiKeyAlg); + CAPIerr(CAPI_F_CAPI_GET_PKEY, CAPI_R_UNSUPPORTED_PUBLIC_KEY_ALGORITHM); + ERR_add_error_data(2, "aiKeyAlg=0x", algstr); + goto err; + } + + + err: + if (pubkey) + OPENSSL_free(pubkey); + if (!ret) + { + if (rkey) + RSA_free(rkey); + if (dkey) + DSA_free(dkey); + } + + return ret; + +memerr: + CAPIerr(CAPI_F_CAPI_GET_PKEY, ERR_R_MALLOC_FAILURE); + goto err; + + } + +static EVP_PKEY *capi_load_privkey(ENGINE *eng, const char *key_id, + UI_METHOD *ui_method, void *callback_data) + { + CAPI_CTX *ctx; + CAPI_KEY *key; + EVP_PKEY *ret; + ctx = ENGINE_get_ex_data(eng, capi_idx); + + if (!ctx) + { + CAPIerr(CAPI_F_CAPI_LOAD_PRIVKEY, CAPI_R_CANT_FIND_CAPI_CONTEXT); + return NULL; + } + + key = capi_find_key(ctx, key_id); + + if (!key) + return NULL; + + ret = capi_get_pkey(eng, key); + + if (!ret) + capi_free_key(key); + return ret; + + } + +/* CryptoAPI RSA operations */ + +int capi_rsa_priv_enc(int flen, const unsigned char *from, + unsigned char *to, RSA *rsa, int padding) + { + CAPIerr(CAPI_F_CAPI_RSA_PRIV_ENC, CAPI_R_FUNCTION_NOT_SUPPORTED); + return -1; + } + +int capi_rsa_sign(int dtype, const unsigned char *m, unsigned int m_len, + unsigned char *sigret, unsigned int *siglen, const RSA *rsa) + { + ALG_ID alg; + HCRYPTHASH hash; + DWORD slen; + unsigned int i; + int ret = -1; + CAPI_KEY *capi_key; + CAPI_CTX *ctx; + + ctx = ENGINE_get_ex_data(rsa->engine, capi_idx); + + CAPI_trace(ctx, "Called CAPI_rsa_sign()\n"); + + capi_key = RSA_get_ex_data(rsa, rsa_capi_idx); + if (!capi_key) + { + CAPIerr(CAPI_F_CAPI_RSA_SIGN, CAPI_R_CANT_GET_KEY); + return -1; + } +/* Convert the signature type to a CryptoAPI algorithm ID */ + switch(dtype) + { + case NID_sha1: + alg = CALG_SHA1; + break; + + case NID_md5: + alg = CALG_MD5; + break; + + case NID_md5_sha1: + alg = CALG_SSL3_SHAMD5; + break; + default: + { + char algstr[10]; + BIO_snprintf(algstr, 10, "%lx", dtype); + CAPIerr(CAPI_F_CAPI_RSA_SIGN, CAPI_R_UNSUPPORTED_ALGORITHM_NID); + ERR_add_error_data(2, "NID=0x", algstr); + return -1; + } + } + + + +/* Create the hash object */ + if(!CryptCreateHash(capi_key->hprov, alg, 0, 0, &hash)) + { + CAPIerr(CAPI_F_CAPI_RSA_SIGN, CAPI_R_CANT_CREATE_HASH_OBJECT); + capi_addlasterror(); + return -1; + } +/* Set the hash value to the value passed */ + + if(!CryptSetHashParam(hash, HP_HASHVAL, (unsigned char *)m, 0)) + { + CAPIerr(CAPI_F_CAPI_RSA_SIGN, CAPI_R_CANT_SET_HASH_VALUE); + capi_addlasterror(); + goto err; + } + + +/* Finally sign it */ + slen = RSA_size(rsa); + if(!CryptSignHashA(hash, capi_key->keyspec, NULL, 0, sigret, &slen)) + { + CAPIerr(CAPI_F_CAPI_RSA_SIGN, CAPI_R_ERROR_SIGNING_HASH); + capi_addlasterror(); + goto err; + } + else + { + ret = 1; + /* Inplace byte reversal of signature */ + for(i = 0; i < slen / 2; i++) + { + unsigned char c; + c = sigret[i]; + sigret[i] = sigret[slen - i - 1]; + sigret[slen - i - 1] = c; + } + *siglen = slen; + } + + /* Now cleanup */ + +err: + CryptDestroyHash(hash); + + return ret; + } + +int capi_rsa_priv_dec(int flen, const unsigned char *from, + unsigned char *to, RSA *rsa, int padding) + { + int i; + unsigned char *tmpbuf; + CAPI_KEY *capi_key; + CAPI_CTX *ctx; + ctx = ENGINE_get_ex_data(rsa->engine, capi_idx); + + CAPI_trace(ctx, "Called capi_rsa_priv_dec()\n"); + + + capi_key = RSA_get_ex_data(rsa, rsa_capi_idx); + if (!capi_key) + { + CAPIerr(CAPI_F_CAPI_RSA_PRIV_DEC, CAPI_R_CANT_GET_KEY); + return -1; + } + + if(padding != RSA_PKCS1_PADDING) + { + char errstr[10]; + BIO_snprintf(errstr, 10, "%d", padding); + CAPIerr(CAPI_F_CAPI_RSA_PRIV_DEC, CAPI_R_UNSUPPORTED_PADDING); + ERR_add_error_data(2, "padding=", errstr); + return -1; + } + + /* Create temp reverse order version of input */ + if(!(tmpbuf = OPENSSL_malloc(flen)) ) + { + CAPIerr(CAPI_F_CAPI_RSA_PRIV_DEC, ERR_R_MALLOC_FAILURE); + return -1; + } + for(i = 0; i < flen; i++) + tmpbuf[flen - i - 1] = from[i]; + + /* Finally decrypt it */ + if(!CryptDecrypt(capi_key->key, 0, TRUE, 0, tmpbuf, &flen)) + { + CAPIerr(CAPI_F_CAPI_RSA_PRIV_DEC, CAPI_R_DECRYPT_ERROR); + capi_addlasterror(); + OPENSSL_free(tmpbuf); + return -1; + } + else memcpy(to, tmpbuf, flen); + + OPENSSL_free(tmpbuf); + + return flen; + } + +static int capi_rsa_free(RSA *rsa) + { + CAPI_KEY *capi_key; + capi_key = RSA_get_ex_data(rsa, rsa_capi_idx); + capi_free_key(capi_key); + RSA_set_ex_data(rsa, rsa_capi_idx, 0); + return 1; + } + +/* CryptoAPI DSA operations */ + +static DSA_SIG *capi_dsa_do_sign(const unsigned char *digest, int dlen, + DSA *dsa) + { + HCRYPTHASH hash; + DWORD slen; + DSA_SIG *ret = NULL; + CAPI_KEY *capi_key; + CAPI_CTX *ctx; + unsigned char csigbuf[40]; + + ctx = ENGINE_get_ex_data(dsa->engine, capi_idx); + + CAPI_trace(ctx, "Called CAPI_dsa_do_sign()\n"); + + capi_key = DSA_get_ex_data(dsa, dsa_capi_idx); + + if (!capi_key) + { + CAPIerr(CAPI_F_CAPI_DSA_DO_SIGN, CAPI_R_CANT_GET_KEY); + return NULL; + } + + if (dlen != 20) + { + CAPIerr(CAPI_F_CAPI_DSA_DO_SIGN, CAPI_R_INVALID_DIGEST_LENGTH); + return NULL; + } + + /* Create the hash object */ + if(!CryptCreateHash(capi_key->hprov, CALG_SHA1, 0, 0, &hash)) + { + CAPIerr(CAPI_F_CAPI_DSA_DO_SIGN, CAPI_R_CANT_CREATE_HASH_OBJECT); + capi_addlasterror(); + return NULL; + } + + /* Set the hash value to the value passed */ + if(!CryptSetHashParam(hash, HP_HASHVAL, (unsigned char *)digest, 0)) + { + CAPIerr(CAPI_F_CAPI_DSA_DO_SIGN, CAPI_R_CANT_SET_HASH_VALUE); + capi_addlasterror(); + goto err; + } + + + /* Finally sign it */ + slen = sizeof(csigbuf); + if(!CryptSignHashA(hash, capi_key->keyspec, NULL, 0, csigbuf, &slen)) + { + CAPIerr(CAPI_F_CAPI_DSA_DO_SIGN, CAPI_R_ERROR_SIGNING_HASH); + capi_addlasterror(); + goto err; + } + else + { + ret = DSA_SIG_new(); + if (!ret) + goto err; + ret->r = BN_new(); + ret->s = BN_new(); + if (!ret->r || !ret->s) + goto err; + if (!lend_tobn(ret->r, csigbuf, 20) + || !lend_tobn(ret->s, csigbuf + 20, 20)) + { + DSA_SIG_free(ret); + ret = NULL; + goto err; + } + } + + /* Now cleanup */ + +err: + OPENSSL_cleanse(csigbuf, 40); + CryptDestroyHash(hash); + return ret; + } + +static int capi_dsa_free(DSA *dsa) + { + CAPI_KEY *capi_key; + capi_key = DSA_get_ex_data(dsa, dsa_capi_idx); + capi_free_key(capi_key); + DSA_set_ex_data(dsa, dsa_capi_idx, 0); + return 1; + } + +static void capi_vtrace(CAPI_CTX *ctx, int level, char *format, va_list argptr) + { + BIO *out; + + if (!ctx || (ctx->debug_level < level) || (!ctx->debug_file)) + return; + out = BIO_new_file(ctx->debug_file, "a+"); + BIO_vprintf(out, format, argptr); + BIO_free(out); + } + +static void CAPI_trace(CAPI_CTX *ctx, char *format, ...) + { + va_list args; + va_start(args, format); + capi_vtrace(ctx, CAPI_DBG_TRACE, format, args); + va_end(args); + } + +static void capi_addlasterror(void) + { + capi_adderror(GetLastError()); + } + +static void capi_adderror(DWORD err) + { + char errstr[10]; + BIO_snprintf(errstr, 10, "%lX", err); + ERR_add_error_data(2, "Error code= 0x", errstr); + } + +static char *wide_to_asc(LPWSTR wstr) + { + char *str; + int len_0,sz; + + if (!wstr) + return NULL; + len_0 = (int)wcslen(wstr)+1; /* WideCharToMultiByte expects int */ + sz = WideCharToMultiByte(CP_ACP,0,wstr,len_0,NULL,0,NULL,NULL); + if (!sz) + { + CAPIerr(CAPI_F_WIDE_TO_ASC, CAPI_R_WIN32_ERROR); + return NULL; + } + str = OPENSSL_malloc(sz); + if (!str) + { + CAPIerr(CAPI_F_WIDE_TO_ASC, ERR_R_MALLOC_FAILURE); + return NULL; + } + if (!WideCharToMultiByte(CP_ACP,0,wstr,len_0,str,sz,NULL,NULL)) + { + OPENSSL_free(str); + CAPIerr(CAPI_F_WIDE_TO_ASC, CAPI_R_WIN32_ERROR); + return NULL; + } + return str; + } + +static int capi_get_provname(CAPI_CTX *ctx, LPSTR *pname, DWORD *ptype, DWORD idx) + { + LPSTR name; + DWORD len, err; + CAPI_trace(ctx, "capi_get_provname, index=%d\n", idx); + if (!CryptEnumProvidersA(idx, NULL, 0, ptype, NULL, &len)) + { + err = GetLastError(); + if (err == ERROR_NO_MORE_ITEMS) + return 2; + CAPIerr(CAPI_F_CAPI_GET_PROVNAME, CAPI_R_CRYPTENUMPROVIDERS_ERROR); + capi_adderror(err); + return 0; + } + name = OPENSSL_malloc(len); + if (!CryptEnumProvidersA(idx, NULL, 0, ptype, name, &len)) + { + err = GetLastError(); + if (err == ERROR_NO_MORE_ITEMS) + return 2; + CAPIerr(CAPI_F_CAPI_GET_PROVNAME, CAPI_R_CRYPTENUMPROVIDERS_ERROR); + capi_adderror(err); + return 0; + } + *pname = name; + CAPI_trace(ctx, "capi_get_provname, returned name=%s, type=%d\n", name, *ptype); + + return 1; + } + +static int capi_list_providers(CAPI_CTX *ctx, BIO *out) + { + DWORD idx, ptype; + int ret; + LPSTR provname = NULL; + CAPI_trace(ctx, "capi_list_providers\n"); + BIO_printf(out, "Available CSPs:\n"); + for(idx = 0; ; idx++) + { + ret = capi_get_provname(ctx, &provname, &ptype, idx); + if (ret == 2) + break; + if (ret == 0) + break; + BIO_printf(out, "%d. %s, type %d\n", idx, provname, ptype); + OPENSSL_free(provname); + } + return 1; + } + +static int capi_list_containers(CAPI_CTX *ctx, BIO *out) + { + int ret = 1; + HCRYPTPROV hprov; + DWORD err, idx, flags, buflen = 0, clen; + LPSTR cname; + CAPI_trace(ctx, "Listing containers CSP=%s, type = %d\n", ctx->cspname, ctx->csptype); + if (!CryptAcquireContextA(&hprov, NULL, ctx->cspname, ctx->csptype, CRYPT_VERIFYCONTEXT)) + { + CAPIerr(CAPI_F_CAPI_LIST_CONTAINERS, CAPI_R_CRYPTACQUIRECONTEXT_ERROR); + capi_addlasterror(); + return 0; + } + if (!CryptGetProvParam(hprov, PP_ENUMCONTAINERS, NULL, &buflen, CRYPT_FIRST)) + { + CAPIerr(CAPI_F_CAPI_LIST_CONTAINERS, CAPI_R_ENUMCONTAINERS_ERROR); + capi_addlasterror(); + return 0; + } + CAPI_trace(ctx, "Got max container len %d\n", buflen); + if (buflen == 0) + buflen = 1024; + cname = OPENSSL_malloc(buflen); + if (!cname) + { + CAPIerr(CAPI_F_CAPI_LIST_CONTAINERS, ERR_R_MALLOC_FAILURE); + goto err; + } + + for (idx = 0;;idx++) + { + clen = buflen; + cname[0] = 0; + + if (idx == 0) + flags = CRYPT_FIRST; + else + flags = 0; + if(!CryptGetProvParam(hprov, PP_ENUMCONTAINERS, cname, &clen, flags)) + { + err = GetLastError(); + if (err == ERROR_NO_MORE_ITEMS) + goto done; + CAPIerr(CAPI_F_CAPI_LIST_CONTAINERS, CAPI_R_ENUMCONTAINERS_ERROR); + capi_adderror(err); + goto err; + } + CAPI_trace(ctx, "Container name %s, len=%d, index=%d, flags=%d\n", cname, clen, idx, flags); + if (!cname[0] && (clen == buflen)) + { + CAPI_trace(ctx, "Enumerate bug: using workaround\n"); + goto done; + } + BIO_printf(out, "%d. %s\n", idx, cname); + } + err: + + ret = 0; + + done: + if (cname) + OPENSSL_free(cname); + CryptReleaseContext(hprov, 0); + + return ret; + } + +CRYPT_KEY_PROV_INFO *capi_get_prov_info(CAPI_CTX *ctx, PCCERT_CONTEXT cert) + { + DWORD len; + CRYPT_KEY_PROV_INFO *pinfo; + + if(!CertGetCertificateContextProperty(cert, CERT_KEY_PROV_INFO_PROP_ID, NULL, &len)) + return NULL; + pinfo = OPENSSL_malloc(len); + if (!pinfo) + { + CAPIerr(CAPI_F_CAPI_GET_PROV_INFO, ERR_R_MALLOC_FAILURE); + return NULL; + } + if(!CertGetCertificateContextProperty(cert, CERT_KEY_PROV_INFO_PROP_ID, pinfo, &len)) + { + CAPIerr(CAPI_F_CAPI_GET_PROV_INFO, CAPI_R_ERROR_GETTING_KEY_PROVIDER_INFO); + capi_addlasterror(); + OPENSSL_free(pinfo); + return NULL; + } + return pinfo; + } + +static void capi_dump_prov_info(CAPI_CTX *ctx, BIO *out, CRYPT_KEY_PROV_INFO *pinfo) + { + char *provname = NULL, *contname = NULL; + if (!pinfo) + { + BIO_printf(out, " No Private Key\n"); + return; + } + provname = wide_to_asc(pinfo->pwszProvName); + contname = wide_to_asc(pinfo->pwszContainerName); + if (!provname || !contname) + goto err; + + BIO_printf(out, " Private Key Info:\n"); + BIO_printf(out, " Provider Name: %s, Provider Type %d\n", provname, pinfo->dwProvType); + BIO_printf(out, " Container Name: %s, Key Type %d\n", contname, pinfo->dwKeySpec); + err: + if (provname) + OPENSSL_free(provname); + if (contname) + OPENSSL_free(contname); + } + +char * capi_cert_get_fname(CAPI_CTX *ctx, PCCERT_CONTEXT cert) + { + LPWSTR wfname; + DWORD dlen; + + CAPI_trace(ctx, "capi_cert_get_fname\n"); + if (!CertGetCertificateContextProperty(cert, CERT_FRIENDLY_NAME_PROP_ID, NULL, &dlen)) + return NULL; + wfname = OPENSSL_malloc(dlen); + if (CertGetCertificateContextProperty(cert, CERT_FRIENDLY_NAME_PROP_ID, wfname, &dlen)) + { + char *fname = wide_to_asc(wfname); + OPENSSL_free(wfname); + return fname; + } + CAPIerr(CAPI_F_CAPI_CERT_GET_FNAME, CAPI_R_ERROR_GETTING_FRIENDLY_NAME); + capi_addlasterror(); + + OPENSSL_free(wfname); + return NULL; + } + + +void capi_dump_cert(CAPI_CTX *ctx, BIO *out, PCCERT_CONTEXT cert) + { + X509 *x; + unsigned char *p; + unsigned long flags = ctx->dump_flags; + if (flags & CAPI_DMP_FNAME) + { + char *fname; + fname = capi_cert_get_fname(ctx, cert); + if (fname) + { + BIO_printf(out, " Friendly Name \"%s\"\n", fname); + OPENSSL_free(fname); + } + else + BIO_printf(out, " \n"); + } + + p = cert->pbCertEncoded; + x = d2i_X509(NULL, &p, cert->cbCertEncoded); + if (!x) + BIO_printf(out, " \n"); + if (flags & CAPI_DMP_SUMMARY) + { + BIO_printf(out, " Subject: "); + X509_NAME_print_ex(out, X509_get_subject_name(x), 0, XN_FLAG_ONELINE); + BIO_printf(out, "\n Issuer: "); + X509_NAME_print_ex(out, X509_get_issuer_name(x), 0, XN_FLAG_ONELINE); + BIO_printf(out, "\n"); + } + if (flags & CAPI_DMP_FULL) + X509_print_ex(out, x, XN_FLAG_ONELINE,0); + + if (flags & CAPI_DMP_PKEYINFO) + { + CRYPT_KEY_PROV_INFO *pinfo; + pinfo = capi_get_prov_info(ctx, cert); + capi_dump_prov_info(ctx, out, pinfo); + if (pinfo) + OPENSSL_free(pinfo); + } + + if (flags & CAPI_DMP_PEM) + PEM_write_bio_X509(out, x); + X509_free(x); + } + +HCERTSTORE capi_open_store(CAPI_CTX *ctx, char *storename) + { + HCERTSTORE hstore; + + if (!storename) + storename = ctx->storename; + if (!storename) + storename = "MY"; + CAPI_trace(ctx, "Opening certificate store %s\n", storename); + + hstore = CertOpenStore(CERT_STORE_PROV_SYSTEM_A, 0, 0, + ctx->store_flags, storename); + if (!hstore) + { + CAPIerr(CAPI_F_CAPI_OPEN_STORE, CAPI_R_ERROR_OPENING_STORE); + capi_addlasterror(); + } + return hstore; + } + +int capi_list_certs(CAPI_CTX *ctx, BIO *out, char *id) + { + char *storename; + int idx; + int ret = 1; + HCERTSTORE hstore; + PCCERT_CONTEXT cert = NULL; + + storename = ctx->storename; + if (!storename) + storename = "MY"; + CAPI_trace(ctx, "Listing certs for store %s\n", storename); + + hstore = capi_open_store(ctx, storename); + if (!hstore) + return 0; + if (id) + { + cert = capi_find_cert(ctx, id, hstore); + if (!cert) + { + ret = 0; + goto err; + } + capi_dump_cert(ctx, out, cert); + CertFreeCertificateContext(cert); + } + else + { + for(idx = 0;;idx++) + { + LPWSTR fname = NULL; + cert = CertEnumCertificatesInStore(hstore, cert); + if (!cert) + break; + BIO_printf(out, "Certificate %d\n", idx); + capi_dump_cert(ctx, out, cert); + } + } + err: + CertCloseStore(hstore, 0); + return ret; + } + +static PCCERT_CONTEXT capi_find_cert(CAPI_CTX *ctx, const char *id, HCERTSTORE hstore) + { + PCCERT_CONTEXT cert = NULL; + char *fname = NULL; + int match; + switch(ctx->lookup_method) + { + case CAPI_LU_SUBSTR: + return CertFindCertificateInStore(hstore, + X509_ASN_ENCODING, 0, + CERT_FIND_SUBJECT_STR_A, id, NULL); + case CAPI_LU_FNAME: + for(;;) + { + cert = CertEnumCertificatesInStore(hstore, cert); + if (!cert) + return NULL; + fname = capi_cert_get_fname(ctx, cert); + if (fname) + { + if (strcmp(fname, id)) + match = 0; + else + match = 1; + OPENSSL_free(fname); + if (match) + return cert; + } + } + default: + return NULL; + } + } + +static CAPI_KEY *capi_get_key(CAPI_CTX *ctx, const char *contname, char *provname, DWORD ptype, DWORD keyspec) + { + CAPI_KEY *key; + key = OPENSSL_malloc(sizeof(CAPI_KEY)); + CAPI_trace(ctx, "capi_get_key, contname=%s, provname=%s, type=%d\n", + contname, provname, ptype); + if (!CryptAcquireContextA(&key->hprov, contname, provname, ptype, 0)) + { + CAPIerr(CAPI_F_CAPI_GET_KEY, CAPI_R_CRYPTACQUIRECONTEXT_ERROR); + capi_addlasterror(); + goto err; + } + if (!CryptGetUserKey(key->hprov, keyspec, &key->key)) + { + CAPIerr(CAPI_F_CAPI_GET_KEY, CAPI_R_GETUSERKEY_ERROR); + capi_addlasterror(); + CryptReleaseContext(key->hprov, 0); + goto err; + } + key->keyspec = keyspec; + key->pcert = NULL; + return key; + + err: + OPENSSL_free(key); + return NULL; + } + +static CAPI_KEY *capi_get_cert_key(CAPI_CTX *ctx, PCCERT_CONTEXT cert) + { + CAPI_KEY *key = NULL; + CRYPT_KEY_PROV_INFO *pinfo = NULL; + char *provname = NULL, *contname = NULL; + pinfo = capi_get_prov_info(ctx, cert); + if (!pinfo) + goto err; + provname = wide_to_asc(pinfo->pwszProvName); + contname = wide_to_asc(pinfo->pwszContainerName); + if (!provname || !contname) + goto err; + key = capi_get_key(ctx, contname, provname, + pinfo->dwProvType, pinfo->dwKeySpec); + + err: + if (pinfo) + OPENSSL_free(pinfo); + if (provname) + OPENSSL_free(provname); + if (contname) + OPENSSL_free(contname); + return key; + } + +CAPI_KEY *capi_find_key(CAPI_CTX *ctx, const char *id) + { + PCCERT_CONTEXT cert; + HCERTSTORE hstore; + CAPI_KEY *key = NULL; + switch (ctx->lookup_method) + { + case CAPI_LU_SUBSTR: + case CAPI_LU_FNAME: + hstore = capi_open_store(ctx, NULL); + if (!hstore) + return NULL; + cert = capi_find_cert(ctx, id, hstore); + if (cert) + { + key = capi_get_cert_key(ctx, cert); + CertFreeCertificateContext(cert); + } + CertCloseStore(hstore, 0); + break; + + case CAPI_LU_CONTNAME: + key = capi_get_key(ctx, id, ctx->cspname, ctx->csptype, + ctx->keytype); + break; + } + + return key; + } + +void capi_free_key(CAPI_KEY *key) + { + if (!key) + return; + CryptDestroyKey(key->key); + CryptReleaseContext(key->hprov, 0); + if (key->pcert) + CertFreeCertificateContext(key->pcert); + OPENSSL_free(key); + } + + +/* Initialize a CAPI_CTX structure */ + +static CAPI_CTX *capi_ctx_new() + { + CAPI_CTX *ctx; + ctx = OPENSSL_malloc(sizeof(CAPI_CTX)); + if (!ctx) + { + CAPIerr(CAPI_F_CAPI_CTX_NEW, ERR_R_MALLOC_FAILURE); + return NULL; + } + ctx->cspname = NULL; + ctx->csptype = PROV_RSA_FULL; + ctx->dump_flags = CAPI_DMP_SUMMARY|CAPI_DMP_FNAME; + ctx->keytype = AT_KEYEXCHANGE; + ctx->storename = NULL; + ctx->ssl_client_store = NULL; + ctx->store_flags = CERT_STORE_OPEN_EXISTING_FLAG | + CERT_STORE_READONLY_FLAG | + CERT_SYSTEM_STORE_CURRENT_USER; + ctx->lookup_method = CAPI_LU_SUBSTR; + ctx->debug_level = 0; + ctx->debug_file = NULL; + ctx->client_cert_select = cert_select_simple; + return ctx; + } + +static void capi_ctx_free(CAPI_CTX *ctx) + { + CAPI_trace(ctx, "Calling capi_ctx_free with %lx\n", ctx); + if (!ctx) + return; + if (ctx->cspname) + OPENSSL_free(ctx->cspname); + if (ctx->debug_file) + OPENSSL_free(ctx->debug_file); + if (ctx->storename) + OPENSSL_free(ctx->storename); + if (ctx->ssl_client_store) + OPENSSL_free(ctx->ssl_client_store); + OPENSSL_free(ctx); + } + +static int capi_ctx_set_provname(CAPI_CTX *ctx, LPSTR pname, DWORD type, int check) + { + CAPI_trace(ctx, "capi_ctx_set_provname, name=%s, type=%d\n", pname, type); + if (check) + { + HCRYPTPROV hprov; + if (!CryptAcquireContextA(&hprov, NULL, pname, type, + CRYPT_VERIFYCONTEXT)) + { + CAPIerr(CAPI_F_CAPI_CTX_SET_PROVNAME, CAPI_R_CRYPTACQUIRECONTEXT_ERROR); + capi_addlasterror(); + return 0; + } + CryptReleaseContext(hprov, 0); + } + ctx->cspname = BUF_strdup(pname); + ctx->csptype = type; + return 1; + } + +static int capi_ctx_set_provname_idx(CAPI_CTX *ctx, int idx) + { + LPSTR pname; + DWORD type; + if (capi_get_provname(ctx, &pname, &type, idx) != 1) + return 0; + return capi_ctx_set_provname(ctx, pname, type, 0); + } + +static int cert_issuer_match(STACK_OF(X509_NAME) *ca_dn, X509 *x) + { + int i; + X509_NAME *nm; + /* Special case: empty list: match anything */ + if (sk_X509_NAME_num(ca_dn) <= 0) + return 1; + for (i = 0; i < sk_X509_NAME_num(ca_dn); i++) + { + nm = sk_X509_NAME_value(ca_dn, i); + if (!X509_NAME_cmp(nm, X509_get_issuer_name(x))) + return 1; + } + return 0; + } + + + +static int capi_load_ssl_client_cert(ENGINE *e, SSL *ssl, + STACK_OF(X509_NAME) *ca_dn, X509 **pcert, EVP_PKEY **pkey, + STACK_OF(X509) **pother, UI_METHOD *ui_method, void *callback_data) + { + STACK_OF(X509) *certs = NULL; + X509 *x; + char *storename; + const char *p; + int i, client_cert_idx; + HCERTSTORE hstore; + PCCERT_CONTEXT cert = NULL, excert = NULL; + CAPI_CTX *ctx; + CAPI_KEY *key; + ctx = ENGINE_get_ex_data(e, capi_idx); + + *pcert = NULL; + *pkey = NULL; + + storename = ctx->ssl_client_store; + if (!storename) + storename = "MY"; + + hstore = capi_open_store(ctx, storename); + if (!hstore) + return 0; + /* Enumerate all certificates collect any matches */ + for(i = 0;;i++) + { + cert = CertEnumCertificatesInStore(hstore, cert); + if (!cert) + break; + p = cert->pbCertEncoded; + x = d2i_X509(NULL, &p, cert->cbCertEncoded); + if (!x) + { + CAPI_trace(ctx, "Can't Parse Certificate %d\n", i); + continue; + } + if (cert_issuer_match(ca_dn, x) + && X509_check_purpose(x, X509_PURPOSE_SSL_CLIENT, 0)) + { + key = capi_get_cert_key(ctx, cert); + if (!key) + { + X509_free(x); + continue; + } + /* Match found: attach extra data to it so + * we can retrieve the key later. + */ + excert = CertDuplicateCertificateContext(cert); + key->pcert = excert; + X509_set_ex_data(x, cert_capi_idx, key); + + if (!certs) + certs = sk_X509_new_null(); + + sk_X509_push(certs, x); + } + else + X509_free(x); + + } + + if (cert) + CertFreeCertificateContext(cert); + if (hstore) + CertCloseStore(hstore, 0); + + if (!certs) + return 0; + + + /* Select the appropriate certificate */ + + client_cert_idx = ctx->client_cert_select(e, ssl, certs); + + /* Set the selected certificate and free the rest */ + + for(i = 0; i < sk_X509_num(certs); i++) + { + x = sk_X509_value(certs, i); + if (i == client_cert_idx) + *pcert = x; + else + { + key = X509_get_ex_data(x, cert_capi_idx); + capi_free_key(key); + X509_free(x); + } + } + + sk_X509_free(certs); + + if (!*pcert) + return 0; + + /* Setup key for selected certificate */ + + key = X509_get_ex_data(*pcert, cert_capi_idx); + *pkey = capi_get_pkey(e, key); + X509_set_ex_data(*pcert, cert_capi_idx, NULL); + + return 1; + + } + + +/* Simple client cert selection function: always select first */ + +static int cert_select_simple(ENGINE *e, SSL *ssl, STACK_OF(X509) *certs) + { + return 0; + } + +#ifdef OPENSSL_CAPIENG_DIALOG + +/* More complex cert selection function, using standard function + * CryptUIDlgSelectCertificateFromStore() to produce a dialog box. + */ + +/* Definitions which are in cryptuiapi.h but this is not present in older + * versions of headers. + */ + +#ifndef CRYPTUI_SELECT_LOCATION_COLUMN +#define CRYPTUI_SELECT_LOCATION_COLUMN 0x000000010 +#define CRYPTUI_SELECT_INTENDEDUSE_COLUMN 0x000000004 +#endif + +#define dlg_title L"OpenSSL Application SSL Client Certificate Selection" +#define dlg_prompt L"Select a certificate to use for authentication" +#define dlg_columns CRYPTUI_SELECT_LOCATION_COLUMN \ + |CRYPTUI_SELECT_INTENDEDUSE_COLUMN + +static int cert_select_dialog(ENGINE *e, SSL *ssl, STACK_OF(X509) *certs) + { + X509 *x; + HCERTSTORE dstore; + PCCERT_CONTEXT cert; + CAPI_CTX *ctx; + CAPI_KEY *key; + HWND hwnd; + int i, idx = -1; + if (sk_X509_num(certs) == 1) + return 0; + ctx = ENGINE_get_ex_data(e, capi_idx); + /* Create an in memory store of certificates */ + dstore = CertOpenStore(CERT_STORE_PROV_MEMORY, 0, 0, + CERT_STORE_CREATE_NEW_FLAG, NULL); + if (!dstore) + { + CAPIerr(CAPI_F_CERT_SELECT_DIALOG, CAPI_R_ERROR_CREATING_STORE); + capi_addlasterror(); + goto err; + } + /* Add all certificates to store */ + for(i = 0; i < sk_X509_num(certs); i++) + { + x = sk_X509_value(certs, i); + key = X509_get_ex_data(x, cert_capi_idx); + + if (!CertAddCertificateContextToStore(dstore, key->pcert, + CERT_STORE_ADD_NEW, NULL)) + { + CAPIerr(CAPI_F_CERT_SELECT_DIALOG, CAPI_R_ERROR_ADDING_CERT); + capi_addlasterror(); + goto err; + } + + } + hwnd = GetForegroundWindow(); + if (!hwnd) + hwnd = GetActiveWindow(); + if (!hwnd && ctx->getconswindow) + hwnd = ctx->getconswindow(); + /* Call dialog to select one */ + cert = ctx->certselectdlg(dstore, hwnd, dlg_title, dlg_prompt, + dlg_columns, 0, NULL); + + /* Find matching cert from list */ + if (cert) + { + for(i = 0; i < sk_X509_num(certs); i++) + { + x = sk_X509_value(certs, i); + key = X509_get_ex_data(x, cert_capi_idx); + if (CertCompareCertificate( + X509_ASN_ENCODING | PKCS_7_ASN_ENCODING, + cert->pCertInfo, + key->pcert->pCertInfo)) + { + idx = i; + break; + } + } + } + + err: + if (dstore) + CertCloseStore(dstore, 0); + return idx; + + } +#endif + +#else /* !__COMPILE_CAPIENG */ +#include +#ifndef OPENSSL_NO_DYNAMIC_ENGINE +OPENSSL_EXPORT +int bind_engine(ENGINE *e, const char *id, const dynamic_fns *fns); +OPENSSL_EXPORT +int bind_engine(ENGINE *e, const char *id, const dynamic_fns *fns) { return 0; } +IMPLEMENT_DYNAMIC_CHECK_FN() +#else +void ENGINE_load_capi(void){} +#endif +#endif diff --git a/node-v0.8.14/deps/openssl/openssl/engines/e_capi.ec b/node-v0.8.14/deps/openssl/openssl/engines/e_capi.ec new file mode 100644 index 0000000..d2ad668 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/engines/e_capi.ec @@ -0,0 +1 @@ +L CAPI e_capi_err.h e_capi_err.c diff --git a/node-v0.8.14/deps/openssl/openssl/engines/e_capi_err.c b/node-v0.8.14/deps/openssl/openssl/engines/e_capi_err.c new file mode 100644 index 0000000..a1fbd04 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/engines/e_capi_err.c @@ -0,0 +1,184 @@ +/* e_capi_err.c */ +/* ==================================================================== + * Copyright (c) 1999-2009 The OpenSSL Project. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. All advertising materials mentioning features or use of this + * software must display the following acknowledgment: + * "This product includes software developed by the OpenSSL Project + * for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)" + * + * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to + * endorse or promote products derived from this software without + * prior written permission. For written permission, please contact + * openssl-core@OpenSSL.org. + * + * 5. Products derived from this software may not be called "OpenSSL" + * nor may "OpenSSL" appear in their names without prior written + * permission of the OpenSSL Project. + * + * 6. Redistributions of any form whatsoever must retain the following + * acknowledgment: + * "This product includes software developed by the OpenSSL Project + * for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)" + * + * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY + * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR + * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, + * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * ==================================================================== + * + * This product includes cryptographic software written by Eric Young + * (eay@cryptsoft.com). This product includes software written by Tim + * Hudson (tjh@cryptsoft.com). + * + */ + +/* NOTE: this file was auto generated by the mkerr.pl script: any changes + * made to it will be overwritten when the script next updates this file, + * only reason strings will be preserved. + */ + +#include +#include +#include "e_capi_err.h" + +/* BEGIN ERROR CODES */ +#ifndef OPENSSL_NO_ERR + +#define ERR_FUNC(func) ERR_PACK(0,func,0) +#define ERR_REASON(reason) ERR_PACK(0,0,reason) + +static ERR_STRING_DATA CAPI_str_functs[]= + { +{ERR_FUNC(CAPI_F_CAPI_CERT_GET_FNAME), "CAPI_CERT_GET_FNAME"}, +{ERR_FUNC(CAPI_F_CAPI_CTRL), "CAPI_CTRL"}, +{ERR_FUNC(CAPI_F_CAPI_CTX_NEW), "CAPI_CTX_NEW"}, +{ERR_FUNC(CAPI_F_CAPI_CTX_SET_PROVNAME), "CAPI_CTX_SET_PROVNAME"}, +{ERR_FUNC(CAPI_F_CAPI_DSA_DO_SIGN), "CAPI_DSA_DO_SIGN"}, +{ERR_FUNC(CAPI_F_CAPI_GET_KEY), "CAPI_GET_KEY"}, +{ERR_FUNC(CAPI_F_CAPI_GET_PKEY), "CAPI_GET_PKEY"}, +{ERR_FUNC(CAPI_F_CAPI_GET_PROVNAME), "CAPI_GET_PROVNAME"}, +{ERR_FUNC(CAPI_F_CAPI_GET_PROV_INFO), "CAPI_GET_PROV_INFO"}, +{ERR_FUNC(CAPI_F_CAPI_INIT), "CAPI_INIT"}, +{ERR_FUNC(CAPI_F_CAPI_LIST_CONTAINERS), "CAPI_LIST_CONTAINERS"}, +{ERR_FUNC(CAPI_F_CAPI_LOAD_PRIVKEY), "CAPI_LOAD_PRIVKEY"}, +{ERR_FUNC(CAPI_F_CAPI_OPEN_STORE), "CAPI_OPEN_STORE"}, +{ERR_FUNC(CAPI_F_CAPI_RSA_PRIV_DEC), "CAPI_RSA_PRIV_DEC"}, +{ERR_FUNC(CAPI_F_CAPI_RSA_PRIV_ENC), "CAPI_RSA_PRIV_ENC"}, +{ERR_FUNC(CAPI_F_CAPI_RSA_SIGN), "CAPI_RSA_SIGN"}, +{ERR_FUNC(CAPI_F_CERT_SELECT_DIALOG), "CERT_SELECT_DIALOG"}, +{ERR_FUNC(CAPI_F_CLIENT_CERT_SELECT), "CLIENT_CERT_SELECT"}, +{ERR_FUNC(CAPI_F_WIDE_TO_ASC), "WIDE_TO_ASC"}, +{0,NULL} + }; + +static ERR_STRING_DATA CAPI_str_reasons[]= + { +{ERR_REASON(CAPI_R_CANT_CREATE_HASH_OBJECT),"cant create hash object"}, +{ERR_REASON(CAPI_R_CANT_FIND_CAPI_CONTEXT),"cant find capi context"}, +{ERR_REASON(CAPI_R_CANT_GET_KEY) ,"cant get key"}, +{ERR_REASON(CAPI_R_CANT_SET_HASH_VALUE) ,"cant set hash value"}, +{ERR_REASON(CAPI_R_CRYPTACQUIRECONTEXT_ERROR),"cryptacquirecontext error"}, +{ERR_REASON(CAPI_R_CRYPTENUMPROVIDERS_ERROR),"cryptenumproviders error"}, +{ERR_REASON(CAPI_R_DECRYPT_ERROR) ,"decrypt error"}, +{ERR_REASON(CAPI_R_ENGINE_NOT_INITIALIZED),"engine not initialized"}, +{ERR_REASON(CAPI_R_ENUMCONTAINERS_ERROR) ,"enumcontainers error"}, +{ERR_REASON(CAPI_R_ERROR_ADDING_CERT) ,"error adding cert"}, +{ERR_REASON(CAPI_R_ERROR_CREATING_STORE) ,"error creating store"}, +{ERR_REASON(CAPI_R_ERROR_GETTING_FRIENDLY_NAME),"error getting friendly name"}, +{ERR_REASON(CAPI_R_ERROR_GETTING_KEY_PROVIDER_INFO),"error getting key provider info"}, +{ERR_REASON(CAPI_R_ERROR_OPENING_STORE) ,"error opening store"}, +{ERR_REASON(CAPI_R_ERROR_SIGNING_HASH) ,"error signing hash"}, +{ERR_REASON(CAPI_R_FUNCTION_NOT_SUPPORTED),"function not supported"}, +{ERR_REASON(CAPI_R_GETUSERKEY_ERROR) ,"getuserkey error"}, +{ERR_REASON(CAPI_R_INVALID_DIGEST_LENGTH),"invalid digest length"}, +{ERR_REASON(CAPI_R_INVALID_DSA_PUBLIC_KEY_BLOB_MAGIC_NUMBER),"invalid dsa public key blob magic number"}, +{ERR_REASON(CAPI_R_INVALID_LOOKUP_METHOD),"invalid lookup method"}, +{ERR_REASON(CAPI_R_INVALID_PUBLIC_KEY_BLOB),"invalid public key blob"}, +{ERR_REASON(CAPI_R_INVALID_RSA_PUBLIC_KEY_BLOB_MAGIC_NUMBER),"invalid rsa public key blob magic number"}, +{ERR_REASON(CAPI_R_PUBKEY_EXPORT_ERROR) ,"pubkey export error"}, +{ERR_REASON(CAPI_R_PUBKEY_EXPORT_LENGTH_ERROR),"pubkey export length error"}, +{ERR_REASON(CAPI_R_UNKNOWN_COMMAND) ,"unknown command"}, +{ERR_REASON(CAPI_R_UNSUPPORTED_ALGORITHM_NID),"unsupported algorithm nid"}, +{ERR_REASON(CAPI_R_UNSUPPORTED_PADDING) ,"unsupported padding"}, +{ERR_REASON(CAPI_R_UNSUPPORTED_PUBLIC_KEY_ALGORITHM),"unsupported public key algorithm"}, +{ERR_REASON(CAPI_R_WIN32_ERROR) ,"win32 error"}, +{0,NULL} + }; + +#endif + +#ifdef CAPI_LIB_NAME +static ERR_STRING_DATA CAPI_lib_name[]= + { +{0 ,CAPI_LIB_NAME}, +{0,NULL} + }; +#endif + + +static int CAPI_lib_error_code=0; +static int CAPI_error_init=1; + +static void ERR_load_CAPI_strings(void) + { + if (CAPI_lib_error_code == 0) + CAPI_lib_error_code=ERR_get_next_error_library(); + + if (CAPI_error_init) + { + CAPI_error_init=0; +#ifndef OPENSSL_NO_ERR + ERR_load_strings(CAPI_lib_error_code,CAPI_str_functs); + ERR_load_strings(CAPI_lib_error_code,CAPI_str_reasons); +#endif + +#ifdef CAPI_LIB_NAME + CAPI_lib_name->error = ERR_PACK(CAPI_lib_error_code,0,0); + ERR_load_strings(0,CAPI_lib_name); +#endif + } + } + +static void ERR_unload_CAPI_strings(void) + { + if (CAPI_error_init == 0) + { +#ifndef OPENSSL_NO_ERR + ERR_unload_strings(CAPI_lib_error_code,CAPI_str_functs); + ERR_unload_strings(CAPI_lib_error_code,CAPI_str_reasons); +#endif + +#ifdef CAPI_LIB_NAME + ERR_unload_strings(0,CAPI_lib_name); +#endif + CAPI_error_init=1; + } + } + +static void ERR_CAPI_error(int function, int reason, char *file, int line) + { + if (CAPI_lib_error_code == 0) + CAPI_lib_error_code=ERR_get_next_error_library(); + ERR_PUT_error(CAPI_lib_error_code,function,reason,file,line); + } diff --git a/node-v0.8.14/deps/openssl/openssl/engines/e_capi_err.h b/node-v0.8.14/deps/openssl/openssl/engines/e_capi_err.h new file mode 100644 index 0000000..efa7001 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/engines/e_capi_err.h @@ -0,0 +1,128 @@ +/* ==================================================================== + * Copyright (c) 2001-2008 The OpenSSL Project. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. All advertising materials mentioning features or use of this + * software must display the following acknowledgment: + * "This product includes software developed by the OpenSSL Project + * for use in the OpenSSL Toolkit. (http://www.openssl.org/)" + * + * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to + * endorse or promote products derived from this software without + * prior written permission. For written permission, please contact + * openssl-core@openssl.org. + * + * 5. Products derived from this software may not be called "OpenSSL" + * nor may "OpenSSL" appear in their names without prior written + * permission of the OpenSSL Project. + * + * 6. Redistributions of any form whatsoever must retain the following + * acknowledgment: + * "This product includes software developed by the OpenSSL Project + * for use in the OpenSSL Toolkit (http://www.openssl.org/)" + * + * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY + * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR + * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, + * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * ==================================================================== + * + * This product includes cryptographic software written by Eric Young + * (eay@cryptsoft.com). This product includes software written by Tim + * Hudson (tjh@cryptsoft.com). + * + */ + +#ifndef HEADER_CAPI_ERR_H +#define HEADER_CAPI_ERR_H + +#ifdef __cplusplus +extern "C" { +#endif + +/* BEGIN ERROR CODES */ +/* The following lines are auto generated by the script mkerr.pl. Any changes + * made after this point may be overwritten when the script is next run. + */ +static void ERR_load_CAPI_strings(void); +static void ERR_unload_CAPI_strings(void); +static void ERR_CAPI_error(int function, int reason, char *file, int line); +#define CAPIerr(f,r) ERR_CAPI_error((f),(r),__FILE__,__LINE__) + +/* Error codes for the CAPI functions. */ + +/* Function codes. */ +#define CAPI_F_CAPI_CERT_GET_FNAME 99 +#define CAPI_F_CAPI_CTRL 100 +#define CAPI_F_CAPI_CTX_NEW 101 +#define CAPI_F_CAPI_CTX_SET_PROVNAME 102 +#define CAPI_F_CAPI_DSA_DO_SIGN 114 +#define CAPI_F_CAPI_GET_KEY 103 +#define CAPI_F_CAPI_GET_PKEY 115 +#define CAPI_F_CAPI_GET_PROVNAME 104 +#define CAPI_F_CAPI_GET_PROV_INFO 105 +#define CAPI_F_CAPI_INIT 106 +#define CAPI_F_CAPI_LIST_CONTAINERS 107 +#define CAPI_F_CAPI_LOAD_PRIVKEY 108 +#define CAPI_F_CAPI_OPEN_STORE 109 +#define CAPI_F_CAPI_RSA_PRIV_DEC 110 +#define CAPI_F_CAPI_RSA_PRIV_ENC 111 +#define CAPI_F_CAPI_RSA_SIGN 112 +#define CAPI_F_CERT_SELECT_DIALOG 117 +#define CAPI_F_CLIENT_CERT_SELECT 116 +#define CAPI_F_WIDE_TO_ASC 113 + +/* Reason codes. */ +#define CAPI_R_CANT_CREATE_HASH_OBJECT 99 +#define CAPI_R_CANT_FIND_CAPI_CONTEXT 100 +#define CAPI_R_CANT_GET_KEY 101 +#define CAPI_R_CANT_SET_HASH_VALUE 102 +#define CAPI_R_CRYPTACQUIRECONTEXT_ERROR 103 +#define CAPI_R_CRYPTENUMPROVIDERS_ERROR 104 +#define CAPI_R_DECRYPT_ERROR 105 +#define CAPI_R_ENGINE_NOT_INITIALIZED 106 +#define CAPI_R_ENUMCONTAINERS_ERROR 107 +#define CAPI_R_ERROR_ADDING_CERT 125 +#define CAPI_R_ERROR_CREATING_STORE 126 +#define CAPI_R_ERROR_GETTING_FRIENDLY_NAME 108 +#define CAPI_R_ERROR_GETTING_KEY_PROVIDER_INFO 109 +#define CAPI_R_ERROR_OPENING_STORE 110 +#define CAPI_R_ERROR_SIGNING_HASH 111 +#define CAPI_R_FUNCTION_NOT_SUPPORTED 112 +#define CAPI_R_GETUSERKEY_ERROR 113 +#define CAPI_R_INVALID_DIGEST_LENGTH 124 +#define CAPI_R_INVALID_DSA_PUBLIC_KEY_BLOB_MAGIC_NUMBER 122 +#define CAPI_R_INVALID_LOOKUP_METHOD 114 +#define CAPI_R_INVALID_PUBLIC_KEY_BLOB 115 +#define CAPI_R_INVALID_RSA_PUBLIC_KEY_BLOB_MAGIC_NUMBER 123 +#define CAPI_R_PUBKEY_EXPORT_ERROR 116 +#define CAPI_R_PUBKEY_EXPORT_LENGTH_ERROR 117 +#define CAPI_R_UNKNOWN_COMMAND 118 +#define CAPI_R_UNSUPPORTED_ALGORITHM_NID 119 +#define CAPI_R_UNSUPPORTED_PADDING 120 +#define CAPI_R_UNSUPPORTED_PUBLIC_KEY_ALGORITHM 121 +#define CAPI_R_WIN32_ERROR 127 + +#ifdef __cplusplus +} +#endif +#endif diff --git a/node-v0.8.14/deps/openssl/openssl/engines/e_chil.c b/node-v0.8.14/deps/openssl/openssl/engines/e_chil.c new file mode 100644 index 0000000..fdc2100 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/engines/e_chil.c @@ -0,0 +1,1356 @@ +/* crypto/engine/e_chil.c -*- mode: C; c-file-style: "eay" -*- */ +/* Written by Richard Levitte (richard@levitte.org), Geoff Thorpe + * (geoff@geoffthorpe.net) and Dr Stephen N Henson (steve@openssl.org) + * for the OpenSSL project 2000. + */ +/* ==================================================================== + * Copyright (c) 1999-2001 The OpenSSL Project. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. All advertising materials mentioning features or use of this + * software must display the following acknowledgment: + * "This product includes software developed by the OpenSSL Project + * for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)" + * + * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to + * endorse or promote products derived from this software without + * prior written permission. For written permission, please contact + * licensing@OpenSSL.org. + * + * 5. Products derived from this software may not be called "OpenSSL" + * nor may "OpenSSL" appear in their names without prior written + * permission of the OpenSSL Project. + * + * 6. Redistributions of any form whatsoever must retain the following + * acknowledgment: + * "This product includes software developed by the OpenSSL Project + * for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)" + * + * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY + * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR + * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, + * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * ==================================================================== + * + * This product includes cryptographic software written by Eric Young + * (eay@cryptsoft.com). This product includes software written by Tim + * Hudson (tjh@cryptsoft.com). + * + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#ifndef OPENSSL_NO_RSA +#include +#endif +#ifndef OPENSSL_NO_DH +#include +#endif +#include + +#ifndef OPENSSL_NO_HW +#ifndef OPENSSL_NO_HW_CHIL + +/* Attribution notice: nCipher have said several times that it's OK for + * us to implement a general interface to their boxes, and recently declared + * their HWCryptoHook to be public, and therefore available for us to use. + * Thanks, nCipher. + * + * The hwcryptohook.h included here is from May 2000. + * [Richard Levitte] + */ +#ifdef FLAT_INC +#include "hwcryptohook.h" +#else +#include "vendor_defns/hwcryptohook.h" +#endif + +#define HWCRHK_LIB_NAME "CHIL engine" +#include "e_chil_err.c" + +static int hwcrhk_destroy(ENGINE *e); +static int hwcrhk_init(ENGINE *e); +static int hwcrhk_finish(ENGINE *e); +static int hwcrhk_ctrl(ENGINE *e, int cmd, long i, void *p, void (*f)(void)); + +/* Functions to handle mutexes */ +static int hwcrhk_mutex_init(HWCryptoHook_Mutex*, HWCryptoHook_CallerContext*); +static int hwcrhk_mutex_lock(HWCryptoHook_Mutex*); +static void hwcrhk_mutex_unlock(HWCryptoHook_Mutex*); +static void hwcrhk_mutex_destroy(HWCryptoHook_Mutex*); + +/* BIGNUM stuff */ +static int hwcrhk_mod_exp(BIGNUM *r, const BIGNUM *a, const BIGNUM *p, + const BIGNUM *m, BN_CTX *ctx); + +#ifndef OPENSSL_NO_RSA +/* RSA stuff */ +static int hwcrhk_rsa_mod_exp(BIGNUM *r, const BIGNUM *I, RSA *rsa, BN_CTX *ctx); +/* This function is aliased to mod_exp (with the mont stuff dropped). */ +static int hwcrhk_mod_exp_mont(BIGNUM *r, const BIGNUM *a, const BIGNUM *p, + const BIGNUM *m, BN_CTX *ctx, BN_MONT_CTX *m_ctx); +static int hwcrhk_rsa_finish(RSA *rsa); +#endif + +#ifndef OPENSSL_NO_DH +/* DH stuff */ +/* This function is alised to mod_exp (with the DH and mont dropped). */ +static int hwcrhk_mod_exp_dh(const DH *dh, BIGNUM *r, + const BIGNUM *a, const BIGNUM *p, + const BIGNUM *m, BN_CTX *ctx, BN_MONT_CTX *m_ctx); +#endif + +/* RAND stuff */ +static int hwcrhk_rand_bytes(unsigned char *buf, int num); +static int hwcrhk_rand_status(void); + +/* KM stuff */ +static EVP_PKEY *hwcrhk_load_privkey(ENGINE *eng, const char *key_id, + UI_METHOD *ui_method, void *callback_data); +static EVP_PKEY *hwcrhk_load_pubkey(ENGINE *eng, const char *key_id, + UI_METHOD *ui_method, void *callback_data); + +/* Interaction stuff */ +static int hwcrhk_insert_card(const char *prompt_info, + const char *wrong_info, + HWCryptoHook_PassphraseContext *ppctx, + HWCryptoHook_CallerContext *cactx); +static int hwcrhk_get_pass(const char *prompt_info, + int *len_io, char *buf, + HWCryptoHook_PassphraseContext *ppctx, + HWCryptoHook_CallerContext *cactx); +static void hwcrhk_log_message(void *logstr, const char *message); + +/* The definitions for control commands specific to this engine */ +#define HWCRHK_CMD_SO_PATH ENGINE_CMD_BASE +#define HWCRHK_CMD_FORK_CHECK (ENGINE_CMD_BASE + 1) +#define HWCRHK_CMD_THREAD_LOCKING (ENGINE_CMD_BASE + 2) +#define HWCRHK_CMD_SET_USER_INTERFACE (ENGINE_CMD_BASE + 3) +#define HWCRHK_CMD_SET_CALLBACK_DATA (ENGINE_CMD_BASE + 4) +static const ENGINE_CMD_DEFN hwcrhk_cmd_defns[] = { + {HWCRHK_CMD_SO_PATH, + "SO_PATH", + "Specifies the path to the 'hwcrhk' shared library", + ENGINE_CMD_FLAG_STRING}, + {HWCRHK_CMD_FORK_CHECK, + "FORK_CHECK", + "Turns fork() checking on (non-zero) or off (zero)", + ENGINE_CMD_FLAG_NUMERIC}, + {HWCRHK_CMD_THREAD_LOCKING, + "THREAD_LOCKING", + "Turns thread-safe locking on (zero) or off (non-zero)", + ENGINE_CMD_FLAG_NUMERIC}, + {HWCRHK_CMD_SET_USER_INTERFACE, + "SET_USER_INTERFACE", + "Set the global user interface (internal)", + ENGINE_CMD_FLAG_INTERNAL}, + {HWCRHK_CMD_SET_CALLBACK_DATA, + "SET_CALLBACK_DATA", + "Set the global user interface extra data (internal)", + ENGINE_CMD_FLAG_INTERNAL}, + {0, NULL, NULL, 0} + }; + +#ifndef OPENSSL_NO_RSA +/* Our internal RSA_METHOD that we provide pointers to */ +static RSA_METHOD hwcrhk_rsa = + { + "CHIL RSA method", + NULL, + NULL, + NULL, + NULL, + hwcrhk_rsa_mod_exp, + hwcrhk_mod_exp_mont, + NULL, + hwcrhk_rsa_finish, + 0, + NULL, + NULL, + NULL, + NULL + }; +#endif + +#ifndef OPENSSL_NO_DH +/* Our internal DH_METHOD that we provide pointers to */ +static DH_METHOD hwcrhk_dh = + { + "CHIL DH method", + NULL, + NULL, + hwcrhk_mod_exp_dh, + NULL, + NULL, + 0, + NULL, + NULL + }; +#endif + +static RAND_METHOD hwcrhk_rand = + { + /* "CHIL RAND method", */ + NULL, + hwcrhk_rand_bytes, + NULL, + NULL, + hwcrhk_rand_bytes, + hwcrhk_rand_status, + }; + +/* Constants used when creating the ENGINE */ +static const char *engine_hwcrhk_id = "chil"; +static const char *engine_hwcrhk_name = "CHIL hardware engine support"; +#ifndef OPENSSL_NO_DYNAMIC_ENGINE +/* Compatibility hack, the dynamic library uses this form in the path */ +static const char *engine_hwcrhk_id_alt = "ncipher"; +#endif + +/* Internal stuff for HWCryptoHook */ + +/* Some structures needed for proper use of thread locks */ +/* hwcryptohook.h has some typedefs that turn struct HWCryptoHook_MutexValue + into HWCryptoHook_Mutex */ +struct HWCryptoHook_MutexValue + { + int lockid; + }; + +/* hwcryptohook.h has some typedefs that turn + struct HWCryptoHook_PassphraseContextValue + into HWCryptoHook_PassphraseContext */ +struct HWCryptoHook_PassphraseContextValue + { + UI_METHOD *ui_method; + void *callback_data; + }; + +/* hwcryptohook.h has some typedefs that turn + struct HWCryptoHook_CallerContextValue + into HWCryptoHook_CallerContext */ +struct HWCryptoHook_CallerContextValue + { + pem_password_cb *password_callback; /* Deprecated! Only present for + backward compatibility! */ + UI_METHOD *ui_method; + void *callback_data; + }; + +/* The MPI structure in HWCryptoHook is pretty compatible with OpenSSL + BIGNUM's, so lets define a couple of conversion macros */ +#define BN2MPI(mp, bn) \ + {mp.size = bn->top * sizeof(BN_ULONG); mp.buf = (unsigned char *)bn->d;} +#define MPI2BN(bn, mp) \ + {mp.size = bn->dmax * sizeof(BN_ULONG); mp.buf = (unsigned char *)bn->d;} + +static BIO *logstream = NULL; +static int disable_mutex_callbacks = 0; + +/* One might wonder why these are needed, since one can pass down at least + a UI_METHOD and a pointer to callback data to the key-loading functions. + The thing is that the ModExp and RSAImmed functions can load keys as well, + if the data they get is in a special, nCipher-defined format (hint: if you + look at the private exponent of the RSA data as a string, you'll see this + string: "nCipher KM tool key id", followed by some bytes, followed a key + identity string, followed by more bytes. This happens when you use "embed" + keys instead of "hwcrhk" keys). Unfortunately, those functions do not take + any passphrase or caller context, and our functions can't really take any + callback data either. Still, the "insert_card" and "get_passphrase" + callbacks may be called down the line, and will need to know what user + interface callbacks to call, and having callback data from the application + may be a nice thing as well, so we need to keep track of that globally. */ +static HWCryptoHook_CallerContext password_context = { NULL, NULL, NULL }; + +/* Stuff to pass to the HWCryptoHook library */ +static HWCryptoHook_InitInfo hwcrhk_globals = { + HWCryptoHook_InitFlags_SimpleForkCheck, /* Flags */ + &logstream, /* logstream */ + sizeof(BN_ULONG), /* limbsize */ + 0, /* mslimb first: false for BNs */ + -1, /* msbyte first: use native */ + 0, /* Max mutexes, 0 = no small limit */ + 0, /* Max simultaneous, 0 = default */ + + /* The next few are mutex stuff: we write wrapper functions + around the OS mutex functions. We initialise them to 0 + here, and change that to actual function pointers in hwcrhk_init() + if dynamic locks are supported (that is, if the application + programmer has made sure of setting up callbacks bafore starting + this engine) *and* if disable_mutex_callbacks hasn't been set by + a call to ENGINE_ctrl(ENGINE_CTRL_CHIL_NO_LOCKING). */ + sizeof(HWCryptoHook_Mutex), + 0, + 0, + 0, + 0, + + /* The next few are condvar stuff: we write wrapper functions + round the OS functions. Currently not implemented and not + and absolute necessity even in threaded programs, therefore + 0'ed. Will hopefully be implemented some day, since it + enhances the efficiency of HWCryptoHook. */ + 0, /* sizeof(HWCryptoHook_CondVar), */ + 0, /* hwcrhk_cv_init, */ + 0, /* hwcrhk_cv_wait, */ + 0, /* hwcrhk_cv_signal, */ + 0, /* hwcrhk_cv_broadcast, */ + 0, /* hwcrhk_cv_destroy, */ + + hwcrhk_get_pass, /* pass phrase */ + hwcrhk_insert_card, /* insert a card */ + hwcrhk_log_message /* Log message */ +}; + + +/* Now, to our own code */ + +/* This internal function is used by ENGINE_chil() and possibly by the + * "dynamic" ENGINE support too */ +static int bind_helper(ENGINE *e) + { +#ifndef OPENSSL_NO_RSA + const RSA_METHOD *meth1; +#endif +#ifndef OPENSSL_NO_DH + const DH_METHOD *meth2; +#endif + if(!ENGINE_set_id(e, engine_hwcrhk_id) || + !ENGINE_set_name(e, engine_hwcrhk_name) || +#ifndef OPENSSL_NO_RSA + !ENGINE_set_RSA(e, &hwcrhk_rsa) || +#endif +#ifndef OPENSSL_NO_DH + !ENGINE_set_DH(e, &hwcrhk_dh) || +#endif + !ENGINE_set_RAND(e, &hwcrhk_rand) || + !ENGINE_set_destroy_function(e, hwcrhk_destroy) || + !ENGINE_set_init_function(e, hwcrhk_init) || + !ENGINE_set_finish_function(e, hwcrhk_finish) || + !ENGINE_set_ctrl_function(e, hwcrhk_ctrl) || + !ENGINE_set_load_privkey_function(e, hwcrhk_load_privkey) || + !ENGINE_set_load_pubkey_function(e, hwcrhk_load_pubkey) || + !ENGINE_set_cmd_defns(e, hwcrhk_cmd_defns)) + return 0; + +#ifndef OPENSSL_NO_RSA + /* We know that the "PKCS1_SSLeay()" functions hook properly + * to the cswift-specific mod_exp and mod_exp_crt so we use + * those functions. NB: We don't use ENGINE_openssl() or + * anything "more generic" because something like the RSAref + * code may not hook properly, and if you own one of these + * cards then you have the right to do RSA operations on it + * anyway! */ + meth1 = RSA_PKCS1_SSLeay(); + hwcrhk_rsa.rsa_pub_enc = meth1->rsa_pub_enc; + hwcrhk_rsa.rsa_pub_dec = meth1->rsa_pub_dec; + hwcrhk_rsa.rsa_priv_enc = meth1->rsa_priv_enc; + hwcrhk_rsa.rsa_priv_dec = meth1->rsa_priv_dec; +#endif + +#ifndef OPENSSL_NO_DH + /* Much the same for Diffie-Hellman */ + meth2 = DH_OpenSSL(); + hwcrhk_dh.generate_key = meth2->generate_key; + hwcrhk_dh.compute_key = meth2->compute_key; +#endif + + /* Ensure the hwcrhk error handling is set up */ + ERR_load_HWCRHK_strings(); + return 1; + } + +#ifdef OPENSSL_NO_DYNAMIC_ENGINE +static ENGINE *engine_chil(void) + { + ENGINE *ret = ENGINE_new(); + if(!ret) + return NULL; + if(!bind_helper(ret)) + { + ENGINE_free(ret); + return NULL; + } + return ret; + } + +void ENGINE_load_chil(void) + { + /* Copied from eng_[openssl|dyn].c */ + ENGINE *toadd = engine_chil(); + if(!toadd) return; + ENGINE_add(toadd); + ENGINE_free(toadd); + ERR_clear_error(); + } +#endif + +/* This is a process-global DSO handle used for loading and unloading + * the HWCryptoHook library. NB: This is only set (or unset) during an + * init() or finish() call (reference counts permitting) and they're + * operating with global locks, so this should be thread-safe + * implicitly. */ +static DSO *hwcrhk_dso = NULL; +static HWCryptoHook_ContextHandle hwcrhk_context = 0; +#ifndef OPENSSL_NO_RSA +static int hndidx_rsa = -1; /* Index for KM handle. Not really used yet. */ +#endif + +/* These are the function pointers that are (un)set when the library has + * successfully (un)loaded. */ +static HWCryptoHook_Init_t *p_hwcrhk_Init = NULL; +static HWCryptoHook_Finish_t *p_hwcrhk_Finish = NULL; +static HWCryptoHook_ModExp_t *p_hwcrhk_ModExp = NULL; +#ifndef OPENSSL_NO_RSA +static HWCryptoHook_RSA_t *p_hwcrhk_RSA = NULL; +#endif +static HWCryptoHook_RandomBytes_t *p_hwcrhk_RandomBytes = NULL; +#ifndef OPENSSL_NO_RSA +static HWCryptoHook_RSALoadKey_t *p_hwcrhk_RSALoadKey = NULL; +static HWCryptoHook_RSAGetPublicKey_t *p_hwcrhk_RSAGetPublicKey = NULL; +static HWCryptoHook_RSAUnloadKey_t *p_hwcrhk_RSAUnloadKey = NULL; +#endif +static HWCryptoHook_ModExpCRT_t *p_hwcrhk_ModExpCRT = NULL; + +/* Used in the DSO operations. */ +static const char *HWCRHK_LIBNAME = NULL; +static void free_HWCRHK_LIBNAME(void) + { + if(HWCRHK_LIBNAME) + OPENSSL_free((void*)HWCRHK_LIBNAME); + HWCRHK_LIBNAME = NULL; + } +static const char *get_HWCRHK_LIBNAME(void) + { + if(HWCRHK_LIBNAME) + return HWCRHK_LIBNAME; + return "nfhwcrhk"; + } +static long set_HWCRHK_LIBNAME(const char *name) + { + free_HWCRHK_LIBNAME(); + return (((HWCRHK_LIBNAME = BUF_strdup(name)) != NULL) ? 1 : 0); + } +static const char *n_hwcrhk_Init = "HWCryptoHook_Init"; +static const char *n_hwcrhk_Finish = "HWCryptoHook_Finish"; +static const char *n_hwcrhk_ModExp = "HWCryptoHook_ModExp"; +#ifndef OPENSSL_NO_RSA +static const char *n_hwcrhk_RSA = "HWCryptoHook_RSA"; +#endif +static const char *n_hwcrhk_RandomBytes = "HWCryptoHook_RandomBytes"; +#ifndef OPENSSL_NO_RSA +static const char *n_hwcrhk_RSALoadKey = "HWCryptoHook_RSALoadKey"; +static const char *n_hwcrhk_RSAGetPublicKey = "HWCryptoHook_RSAGetPublicKey"; +static const char *n_hwcrhk_RSAUnloadKey = "HWCryptoHook_RSAUnloadKey"; +#endif +static const char *n_hwcrhk_ModExpCRT = "HWCryptoHook_ModExpCRT"; + +/* HWCryptoHook library functions and mechanics - these are used by the + * higher-level functions further down. NB: As and where there's no + * error checking, take a look lower down where these functions are + * called, the checking and error handling is probably down there. */ + +/* utility function to obtain a context */ +static int get_context(HWCryptoHook_ContextHandle *hac, + HWCryptoHook_CallerContext *cac) + { + char tempbuf[1024]; + HWCryptoHook_ErrMsgBuf rmsg; + + rmsg.buf = tempbuf; + rmsg.size = sizeof(tempbuf); + + *hac = p_hwcrhk_Init(&hwcrhk_globals, sizeof(hwcrhk_globals), &rmsg, + cac); + if (!*hac) + return 0; + return 1; + } + +/* similarly to release one. */ +static void release_context(HWCryptoHook_ContextHandle hac) + { + p_hwcrhk_Finish(hac); + } + +/* Destructor (complements the "ENGINE_chil()" constructor) */ +static int hwcrhk_destroy(ENGINE *e) + { + free_HWCRHK_LIBNAME(); + ERR_unload_HWCRHK_strings(); + return 1; + } + +/* (de)initialisation functions. */ +static int hwcrhk_init(ENGINE *e) + { + HWCryptoHook_Init_t *p1; + HWCryptoHook_Finish_t *p2; + HWCryptoHook_ModExp_t *p3; +#ifndef OPENSSL_NO_RSA + HWCryptoHook_RSA_t *p4; + HWCryptoHook_RSALoadKey_t *p5; + HWCryptoHook_RSAGetPublicKey_t *p6; + HWCryptoHook_RSAUnloadKey_t *p7; +#endif + HWCryptoHook_RandomBytes_t *p8; + HWCryptoHook_ModExpCRT_t *p9; + + if(hwcrhk_dso != NULL) + { + HWCRHKerr(HWCRHK_F_HWCRHK_INIT,HWCRHK_R_ALREADY_LOADED); + goto err; + } + /* Attempt to load libnfhwcrhk.so/nfhwcrhk.dll/whatever. */ + hwcrhk_dso = DSO_load(NULL, get_HWCRHK_LIBNAME(), NULL, 0); + if(hwcrhk_dso == NULL) + { + HWCRHKerr(HWCRHK_F_HWCRHK_INIT,HWCRHK_R_DSO_FAILURE); + goto err; + } + if(!(p1 = (HWCryptoHook_Init_t *) + DSO_bind_func(hwcrhk_dso, n_hwcrhk_Init)) || + !(p2 = (HWCryptoHook_Finish_t *) + DSO_bind_func(hwcrhk_dso, n_hwcrhk_Finish)) || + !(p3 = (HWCryptoHook_ModExp_t *) + DSO_bind_func(hwcrhk_dso, n_hwcrhk_ModExp)) || +#ifndef OPENSSL_NO_RSA + !(p4 = (HWCryptoHook_RSA_t *) + DSO_bind_func(hwcrhk_dso, n_hwcrhk_RSA)) || + !(p5 = (HWCryptoHook_RSALoadKey_t *) + DSO_bind_func(hwcrhk_dso, n_hwcrhk_RSALoadKey)) || + !(p6 = (HWCryptoHook_RSAGetPublicKey_t *) + DSO_bind_func(hwcrhk_dso, n_hwcrhk_RSAGetPublicKey)) || + !(p7 = (HWCryptoHook_RSAUnloadKey_t *) + DSO_bind_func(hwcrhk_dso, n_hwcrhk_RSAUnloadKey)) || +#endif + !(p8 = (HWCryptoHook_RandomBytes_t *) + DSO_bind_func(hwcrhk_dso, n_hwcrhk_RandomBytes)) || + !(p9 = (HWCryptoHook_ModExpCRT_t *) + DSO_bind_func(hwcrhk_dso, n_hwcrhk_ModExpCRT))) + { + HWCRHKerr(HWCRHK_F_HWCRHK_INIT,HWCRHK_R_DSO_FAILURE); + goto err; + } + /* Copy the pointers */ + p_hwcrhk_Init = p1; + p_hwcrhk_Finish = p2; + p_hwcrhk_ModExp = p3; +#ifndef OPENSSL_NO_RSA + p_hwcrhk_RSA = p4; + p_hwcrhk_RSALoadKey = p5; + p_hwcrhk_RSAGetPublicKey = p6; + p_hwcrhk_RSAUnloadKey = p7; +#endif + p_hwcrhk_RandomBytes = p8; + p_hwcrhk_ModExpCRT = p9; + + /* Check if the application decided to support dynamic locks, + and if it does, use them. */ + if (disable_mutex_callbacks == 0) + { + if (CRYPTO_get_dynlock_create_callback() != NULL && + CRYPTO_get_dynlock_lock_callback() != NULL && + CRYPTO_get_dynlock_destroy_callback() != NULL) + { + hwcrhk_globals.mutex_init = hwcrhk_mutex_init; + hwcrhk_globals.mutex_acquire = hwcrhk_mutex_lock; + hwcrhk_globals.mutex_release = hwcrhk_mutex_unlock; + hwcrhk_globals.mutex_destroy = hwcrhk_mutex_destroy; + } + } + + /* Try and get a context - if not, we may have a DSO but no + * accelerator! */ + if(!get_context(&hwcrhk_context, &password_context)) + { + HWCRHKerr(HWCRHK_F_HWCRHK_INIT,HWCRHK_R_UNIT_FAILURE); + goto err; + } + /* Everything's fine. */ +#ifndef OPENSSL_NO_RSA + if (hndidx_rsa == -1) + hndidx_rsa = RSA_get_ex_new_index(0, + "nFast HWCryptoHook RSA key handle", + NULL, NULL, NULL); +#endif + return 1; +err: + if(hwcrhk_dso) + DSO_free(hwcrhk_dso); + hwcrhk_dso = NULL; + p_hwcrhk_Init = NULL; + p_hwcrhk_Finish = NULL; + p_hwcrhk_ModExp = NULL; +#ifndef OPENSSL_NO_RSA + p_hwcrhk_RSA = NULL; + p_hwcrhk_RSALoadKey = NULL; + p_hwcrhk_RSAGetPublicKey = NULL; + p_hwcrhk_RSAUnloadKey = NULL; +#endif + p_hwcrhk_ModExpCRT = NULL; + p_hwcrhk_RandomBytes = NULL; + return 0; + } + +static int hwcrhk_finish(ENGINE *e) + { + int to_return = 1; + free_HWCRHK_LIBNAME(); + if(hwcrhk_dso == NULL) + { + HWCRHKerr(HWCRHK_F_HWCRHK_FINISH,HWCRHK_R_NOT_LOADED); + to_return = 0; + goto err; + } + release_context(hwcrhk_context); + if(!DSO_free(hwcrhk_dso)) + { + HWCRHKerr(HWCRHK_F_HWCRHK_FINISH,HWCRHK_R_DSO_FAILURE); + to_return = 0; + goto err; + } + err: + if (logstream) + BIO_free(logstream); + hwcrhk_dso = NULL; + p_hwcrhk_Init = NULL; + p_hwcrhk_Finish = NULL; + p_hwcrhk_ModExp = NULL; +#ifndef OPENSSL_NO_RSA + p_hwcrhk_RSA = NULL; + p_hwcrhk_RSALoadKey = NULL; + p_hwcrhk_RSAGetPublicKey = NULL; + p_hwcrhk_RSAUnloadKey = NULL; +#endif + p_hwcrhk_ModExpCRT = NULL; + p_hwcrhk_RandomBytes = NULL; + return to_return; + } + +static int hwcrhk_ctrl(ENGINE *e, int cmd, long i, void *p, void (*f)(void)) + { + int to_return = 1; + + switch(cmd) + { + case HWCRHK_CMD_SO_PATH: + if(hwcrhk_dso) + { + HWCRHKerr(HWCRHK_F_HWCRHK_CTRL,HWCRHK_R_ALREADY_LOADED); + return 0; + } + if(p == NULL) + { + HWCRHKerr(HWCRHK_F_HWCRHK_CTRL,ERR_R_PASSED_NULL_PARAMETER); + return 0; + } + return set_HWCRHK_LIBNAME((const char *)p); + case ENGINE_CTRL_SET_LOGSTREAM: + { + BIO *bio = (BIO *)p; + + CRYPTO_w_lock(CRYPTO_LOCK_ENGINE); + if (logstream) + { + BIO_free(logstream); + logstream = NULL; + } + if (CRYPTO_add(&bio->references,1,CRYPTO_LOCK_BIO) > 1) + logstream = bio; + else + HWCRHKerr(HWCRHK_F_HWCRHK_CTRL,HWCRHK_R_BIO_WAS_FREED); + } + CRYPTO_w_unlock(CRYPTO_LOCK_ENGINE); + break; + case ENGINE_CTRL_SET_PASSWORD_CALLBACK: + CRYPTO_w_lock(CRYPTO_LOCK_ENGINE); + password_context.password_callback = (pem_password_cb *)f; + CRYPTO_w_unlock(CRYPTO_LOCK_ENGINE); + break; + case ENGINE_CTRL_SET_USER_INTERFACE: + case HWCRHK_CMD_SET_USER_INTERFACE: + CRYPTO_w_lock(CRYPTO_LOCK_ENGINE); + password_context.ui_method = (UI_METHOD *)p; + CRYPTO_w_unlock(CRYPTO_LOCK_ENGINE); + break; + case ENGINE_CTRL_SET_CALLBACK_DATA: + case HWCRHK_CMD_SET_CALLBACK_DATA: + CRYPTO_w_lock(CRYPTO_LOCK_ENGINE); + password_context.callback_data = p; + CRYPTO_w_unlock(CRYPTO_LOCK_ENGINE); + break; + /* this enables or disables the "SimpleForkCheck" flag used in the + * initialisation structure. */ + case ENGINE_CTRL_CHIL_SET_FORKCHECK: + case HWCRHK_CMD_FORK_CHECK: + CRYPTO_w_lock(CRYPTO_LOCK_ENGINE); + if(i) + hwcrhk_globals.flags |= + HWCryptoHook_InitFlags_SimpleForkCheck; + else + hwcrhk_globals.flags &= + ~HWCryptoHook_InitFlags_SimpleForkCheck; + CRYPTO_w_unlock(CRYPTO_LOCK_ENGINE); + break; + /* This will prevent the initialisation function from "installing" + * the mutex-handling callbacks, even if they are available from + * within the library (or were provided to the library from the + * calling application). This is to remove any baggage for + * applications not using multithreading. */ + case ENGINE_CTRL_CHIL_NO_LOCKING: + CRYPTO_w_lock(CRYPTO_LOCK_ENGINE); + disable_mutex_callbacks = 1; + CRYPTO_w_unlock(CRYPTO_LOCK_ENGINE); + break; + case HWCRHK_CMD_THREAD_LOCKING: + CRYPTO_w_lock(CRYPTO_LOCK_ENGINE); + disable_mutex_callbacks = ((i == 0) ? 0 : 1); + CRYPTO_w_unlock(CRYPTO_LOCK_ENGINE); + break; + + /* The command isn't understood by this engine */ + default: + HWCRHKerr(HWCRHK_F_HWCRHK_CTRL, + HWCRHK_R_CTRL_COMMAND_NOT_IMPLEMENTED); + to_return = 0; + break; + } + + return to_return; + } + +static EVP_PKEY *hwcrhk_load_privkey(ENGINE *eng, const char *key_id, + UI_METHOD *ui_method, void *callback_data) + { +#ifndef OPENSSL_NO_RSA + RSA *rtmp = NULL; +#endif + EVP_PKEY *res = NULL; +#ifndef OPENSSL_NO_RSA + HWCryptoHook_MPI e, n; + HWCryptoHook_RSAKeyHandle *hptr; +#endif +#if !defined(OPENSSL_NO_RSA) + char tempbuf[1024]; + HWCryptoHook_ErrMsgBuf rmsg; + HWCryptoHook_PassphraseContext ppctx; +#endif + +#if !defined(OPENSSL_NO_RSA) + rmsg.buf = tempbuf; + rmsg.size = sizeof(tempbuf); +#endif + + if(!hwcrhk_context) + { + HWCRHKerr(HWCRHK_F_HWCRHK_LOAD_PRIVKEY, + HWCRHK_R_NOT_INITIALISED); + goto err; + } +#ifndef OPENSSL_NO_RSA + hptr = OPENSSL_malloc(sizeof(HWCryptoHook_RSAKeyHandle)); + if (!hptr) + { + HWCRHKerr(HWCRHK_F_HWCRHK_LOAD_PRIVKEY, + ERR_R_MALLOC_FAILURE); + goto err; + } + ppctx.ui_method = ui_method; + ppctx.callback_data = callback_data; + if (p_hwcrhk_RSALoadKey(hwcrhk_context, key_id, hptr, + &rmsg, &ppctx)) + { + HWCRHKerr(HWCRHK_F_HWCRHK_LOAD_PRIVKEY, + HWCRHK_R_CHIL_ERROR); + ERR_add_error_data(1,rmsg.buf); + goto err; + } + if (!*hptr) + { + HWCRHKerr(HWCRHK_F_HWCRHK_LOAD_PRIVKEY, + HWCRHK_R_NO_KEY); + goto err; + } +#endif +#ifndef OPENSSL_NO_RSA + rtmp = RSA_new_method(eng); + RSA_set_ex_data(rtmp, hndidx_rsa, (char *)hptr); + rtmp->e = BN_new(); + rtmp->n = BN_new(); + rtmp->flags |= RSA_FLAG_EXT_PKEY; + MPI2BN(rtmp->e, e); + MPI2BN(rtmp->n, n); + if (p_hwcrhk_RSAGetPublicKey(*hptr, &n, &e, &rmsg) + != HWCRYPTOHOOK_ERROR_MPISIZE) + { + HWCRHKerr(HWCRHK_F_HWCRHK_LOAD_PRIVKEY,HWCRHK_R_CHIL_ERROR); + ERR_add_error_data(1,rmsg.buf); + goto err; + } + + bn_expand2(rtmp->e, e.size/sizeof(BN_ULONG)); + bn_expand2(rtmp->n, n.size/sizeof(BN_ULONG)); + MPI2BN(rtmp->e, e); + MPI2BN(rtmp->n, n); + + if (p_hwcrhk_RSAGetPublicKey(*hptr, &n, &e, &rmsg)) + { + HWCRHKerr(HWCRHK_F_HWCRHK_LOAD_PRIVKEY, + HWCRHK_R_CHIL_ERROR); + ERR_add_error_data(1,rmsg.buf); + goto err; + } + rtmp->e->top = e.size / sizeof(BN_ULONG); + bn_fix_top(rtmp->e); + rtmp->n->top = n.size / sizeof(BN_ULONG); + bn_fix_top(rtmp->n); + + res = EVP_PKEY_new(); + EVP_PKEY_assign_RSA(res, rtmp); +#endif + + if (!res) + HWCRHKerr(HWCRHK_F_HWCRHK_LOAD_PRIVKEY, + HWCRHK_R_PRIVATE_KEY_ALGORITHMS_DISABLED); + + return res; + err: +#ifndef OPENSSL_NO_RSA + if (rtmp) + RSA_free(rtmp); +#endif + return NULL; + } + +static EVP_PKEY *hwcrhk_load_pubkey(ENGINE *eng, const char *key_id, + UI_METHOD *ui_method, void *callback_data) + { + EVP_PKEY *res = NULL; + +#ifndef OPENSSL_NO_RSA + res = hwcrhk_load_privkey(eng, key_id, + ui_method, callback_data); +#endif + + if (res) + switch(res->type) + { +#ifndef OPENSSL_NO_RSA + case EVP_PKEY_RSA: + { + RSA *rsa = NULL; + + CRYPTO_w_lock(CRYPTO_LOCK_EVP_PKEY); + rsa = res->pkey.rsa; + res->pkey.rsa = RSA_new(); + res->pkey.rsa->n = rsa->n; + res->pkey.rsa->e = rsa->e; + rsa->n = NULL; + rsa->e = NULL; + CRYPTO_w_unlock(CRYPTO_LOCK_EVP_PKEY); + RSA_free(rsa); + } + break; +#endif + default: + HWCRHKerr(HWCRHK_F_HWCRHK_LOAD_PUBKEY, + HWCRHK_R_CTRL_COMMAND_NOT_IMPLEMENTED); + goto err; + } + + return res; + err: + if (res) + EVP_PKEY_free(res); + return NULL; + } + +/* A little mod_exp */ +static int hwcrhk_mod_exp(BIGNUM *r, const BIGNUM *a, const BIGNUM *p, + const BIGNUM *m, BN_CTX *ctx) + { + char tempbuf[1024]; + HWCryptoHook_ErrMsgBuf rmsg; + /* Since HWCryptoHook_MPI is pretty compatible with BIGNUM's, + we use them directly, plus a little macro magic. We only + thing we need to make sure of is that enough space is allocated. */ + HWCryptoHook_MPI m_a, m_p, m_n, m_r; + int to_return, ret; + + to_return = 0; /* expect failure */ + rmsg.buf = tempbuf; + rmsg.size = sizeof(tempbuf); + + if(!hwcrhk_context) + { + HWCRHKerr(HWCRHK_F_HWCRHK_MOD_EXP,HWCRHK_R_NOT_INITIALISED); + goto err; + } + /* Prepare the params */ + bn_expand2(r, m->top); /* Check for error !! */ + BN2MPI(m_a, a); + BN2MPI(m_p, p); + BN2MPI(m_n, m); + MPI2BN(r, m_r); + + /* Perform the operation */ + ret = p_hwcrhk_ModExp(hwcrhk_context, m_a, m_p, m_n, &m_r, &rmsg); + + /* Convert the response */ + r->top = m_r.size / sizeof(BN_ULONG); + bn_fix_top(r); + + if (ret < 0) + { + /* FIXME: When this error is returned, HWCryptoHook is + telling us that falling back to software computation + might be a good thing. */ + if(ret == HWCRYPTOHOOK_ERROR_FALLBACK) + { + HWCRHKerr(HWCRHK_F_HWCRHK_MOD_EXP,HWCRHK_R_REQUEST_FALLBACK); + } + else + { + HWCRHKerr(HWCRHK_F_HWCRHK_MOD_EXP,HWCRHK_R_REQUEST_FAILED); + } + ERR_add_error_data(1,rmsg.buf); + goto err; + } + + to_return = 1; +err: + return to_return; + } + +#ifndef OPENSSL_NO_RSA +static int hwcrhk_rsa_mod_exp(BIGNUM *r, const BIGNUM *I, RSA *rsa, BN_CTX *ctx) + { + char tempbuf[1024]; + HWCryptoHook_ErrMsgBuf rmsg; + HWCryptoHook_RSAKeyHandle *hptr; + int to_return = 0, ret; + + rmsg.buf = tempbuf; + rmsg.size = sizeof(tempbuf); + + if(!hwcrhk_context) + { + HWCRHKerr(HWCRHK_F_HWCRHK_RSA_MOD_EXP,HWCRHK_R_NOT_INITIALISED); + goto err; + } + + /* This provides support for nForce keys. Since that's opaque data + all we do is provide a handle to the proper key and let HWCryptoHook + take care of the rest. */ + if ((hptr = (HWCryptoHook_RSAKeyHandle *) RSA_get_ex_data(rsa, hndidx_rsa)) + != NULL) + { + HWCryptoHook_MPI m_a, m_r; + + if(!rsa->n) + { + HWCRHKerr(HWCRHK_F_HWCRHK_RSA_MOD_EXP, + HWCRHK_R_MISSING_KEY_COMPONENTS); + goto err; + } + + /* Prepare the params */ + bn_expand2(r, rsa->n->top); /* Check for error !! */ + BN2MPI(m_a, I); + MPI2BN(r, m_r); + + /* Perform the operation */ + ret = p_hwcrhk_RSA(m_a, *hptr, &m_r, &rmsg); + + /* Convert the response */ + r->top = m_r.size / sizeof(BN_ULONG); + bn_fix_top(r); + + if (ret < 0) + { + /* FIXME: When this error is returned, HWCryptoHook is + telling us that falling back to software computation + might be a good thing. */ + if(ret == HWCRYPTOHOOK_ERROR_FALLBACK) + { + HWCRHKerr(HWCRHK_F_HWCRHK_RSA_MOD_EXP, + HWCRHK_R_REQUEST_FALLBACK); + } + else + { + HWCRHKerr(HWCRHK_F_HWCRHK_RSA_MOD_EXP, + HWCRHK_R_REQUEST_FAILED); + } + ERR_add_error_data(1,rmsg.buf); + goto err; + } + } + else + { + HWCryptoHook_MPI m_a, m_p, m_q, m_dmp1, m_dmq1, m_iqmp, m_r; + + if(!rsa->p || !rsa->q || !rsa->dmp1 || !rsa->dmq1 || !rsa->iqmp) + { + HWCRHKerr(HWCRHK_F_HWCRHK_RSA_MOD_EXP, + HWCRHK_R_MISSING_KEY_COMPONENTS); + goto err; + } + + /* Prepare the params */ + bn_expand2(r, rsa->n->top); /* Check for error !! */ + BN2MPI(m_a, I); + BN2MPI(m_p, rsa->p); + BN2MPI(m_q, rsa->q); + BN2MPI(m_dmp1, rsa->dmp1); + BN2MPI(m_dmq1, rsa->dmq1); + BN2MPI(m_iqmp, rsa->iqmp); + MPI2BN(r, m_r); + + /* Perform the operation */ + ret = p_hwcrhk_ModExpCRT(hwcrhk_context, m_a, m_p, m_q, + m_dmp1, m_dmq1, m_iqmp, &m_r, &rmsg); + + /* Convert the response */ + r->top = m_r.size / sizeof(BN_ULONG); + bn_fix_top(r); + + if (ret < 0) + { + /* FIXME: When this error is returned, HWCryptoHook is + telling us that falling back to software computation + might be a good thing. */ + if(ret == HWCRYPTOHOOK_ERROR_FALLBACK) + { + HWCRHKerr(HWCRHK_F_HWCRHK_RSA_MOD_EXP, + HWCRHK_R_REQUEST_FALLBACK); + } + else + { + HWCRHKerr(HWCRHK_F_HWCRHK_RSA_MOD_EXP, + HWCRHK_R_REQUEST_FAILED); + } + ERR_add_error_data(1,rmsg.buf); + goto err; + } + } + /* If we're here, we must be here with some semblance of success :-) */ + to_return = 1; +err: + return to_return; + } +#endif + +#ifndef OPENSSL_NO_RSA +/* This function is aliased to mod_exp (with the mont stuff dropped). */ +static int hwcrhk_mod_exp_mont(BIGNUM *r, const BIGNUM *a, const BIGNUM *p, + const BIGNUM *m, BN_CTX *ctx, BN_MONT_CTX *m_ctx) + { + return hwcrhk_mod_exp(r, a, p, m, ctx); + } + +static int hwcrhk_rsa_finish(RSA *rsa) + { + HWCryptoHook_RSAKeyHandle *hptr; + + hptr = RSA_get_ex_data(rsa, hndidx_rsa); + if (hptr) + { + p_hwcrhk_RSAUnloadKey(*hptr, NULL); + OPENSSL_free(hptr); + RSA_set_ex_data(rsa, hndidx_rsa, NULL); + } + return 1; + } + +#endif + +#ifndef OPENSSL_NO_DH +/* This function is aliased to mod_exp (with the dh and mont dropped). */ +static int hwcrhk_mod_exp_dh(const DH *dh, BIGNUM *r, + const BIGNUM *a, const BIGNUM *p, + const BIGNUM *m, BN_CTX *ctx, BN_MONT_CTX *m_ctx) + { + return hwcrhk_mod_exp(r, a, p, m, ctx); + } +#endif + +/* Random bytes are good */ +static int hwcrhk_rand_bytes(unsigned char *buf, int num) + { + char tempbuf[1024]; + HWCryptoHook_ErrMsgBuf rmsg; + int to_return = 0; /* assume failure */ + int ret; + + rmsg.buf = tempbuf; + rmsg.size = sizeof(tempbuf); + + if(!hwcrhk_context) + { + HWCRHKerr(HWCRHK_F_HWCRHK_RAND_BYTES,HWCRHK_R_NOT_INITIALISED); + goto err; + } + + ret = p_hwcrhk_RandomBytes(hwcrhk_context, buf, num, &rmsg); + if (ret < 0) + { + /* FIXME: When this error is returned, HWCryptoHook is + telling us that falling back to software computation + might be a good thing. */ + if(ret == HWCRYPTOHOOK_ERROR_FALLBACK) + { + HWCRHKerr(HWCRHK_F_HWCRHK_RAND_BYTES, + HWCRHK_R_REQUEST_FALLBACK); + } + else + { + HWCRHKerr(HWCRHK_F_HWCRHK_RAND_BYTES, + HWCRHK_R_REQUEST_FAILED); + } + ERR_add_error_data(1,rmsg.buf); + goto err; + } + to_return = 1; + err: + return to_return; + } + +static int hwcrhk_rand_status(void) + { + return 1; + } + +/* Mutex calls: since the HWCryptoHook model closely follows the POSIX model + * these just wrap the POSIX functions and add some logging. + */ + +static int hwcrhk_mutex_init(HWCryptoHook_Mutex* mt, + HWCryptoHook_CallerContext *cactx) + { + mt->lockid = CRYPTO_get_new_dynlockid(); + if (mt->lockid == 0) + return 1; /* failure */ + return 0; /* success */ + } + +static int hwcrhk_mutex_lock(HWCryptoHook_Mutex *mt) + { + CRYPTO_w_lock(mt->lockid); + return 0; + } + +static void hwcrhk_mutex_unlock(HWCryptoHook_Mutex * mt) + { + CRYPTO_w_unlock(mt->lockid); + } + +static void hwcrhk_mutex_destroy(HWCryptoHook_Mutex *mt) + { + CRYPTO_destroy_dynlockid(mt->lockid); + } + +static int hwcrhk_get_pass(const char *prompt_info, + int *len_io, char *buf, + HWCryptoHook_PassphraseContext *ppctx, + HWCryptoHook_CallerContext *cactx) + { + pem_password_cb *callback = NULL; + void *callback_data = NULL; + UI_METHOD *ui_method = NULL; + /* Despite what the documentation says prompt_info can be + * an empty string. + */ + if (prompt_info && !*prompt_info) + prompt_info = NULL; + + if (cactx) + { + if (cactx->ui_method) + ui_method = cactx->ui_method; + if (cactx->password_callback) + callback = cactx->password_callback; + if (cactx->callback_data) + callback_data = cactx->callback_data; + } + if (ppctx) + { + if (ppctx->ui_method) + { + ui_method = ppctx->ui_method; + callback = NULL; + } + if (ppctx->callback_data) + callback_data = ppctx->callback_data; + } + if (callback == NULL && ui_method == NULL) + { + HWCRHKerr(HWCRHK_F_HWCRHK_GET_PASS,HWCRHK_R_NO_CALLBACK); + return -1; + } + + if (ui_method) + { + UI *ui = UI_new_method(ui_method); + if (ui) + { + int ok; + char *prompt = UI_construct_prompt(ui, + "pass phrase", prompt_info); + + ok = UI_add_input_string(ui,prompt, + UI_INPUT_FLAG_DEFAULT_PWD, + buf,0,(*len_io) - 1); + UI_add_user_data(ui, callback_data); + UI_ctrl(ui, UI_CTRL_PRINT_ERRORS, 1, 0, 0); + + if (ok >= 0) + do + { + ok=UI_process(ui); + } + while (ok < 0 && UI_ctrl(ui, UI_CTRL_IS_REDOABLE, 0, 0, 0)); + + if (ok >= 0) + *len_io = strlen(buf); + + UI_free(ui); + OPENSSL_free(prompt); + } + } + else + { + *len_io = callback(buf, *len_io, 0, callback_data); + } + if(!*len_io) + return -1; + return 0; + } + +static int hwcrhk_insert_card(const char *prompt_info, + const char *wrong_info, + HWCryptoHook_PassphraseContext *ppctx, + HWCryptoHook_CallerContext *cactx) + { + int ok = -1; + UI *ui; + void *callback_data = NULL; + UI_METHOD *ui_method = NULL; + + if (cactx) + { + if (cactx->ui_method) + ui_method = cactx->ui_method; + if (cactx->callback_data) + callback_data = cactx->callback_data; + } + if (ppctx) + { + if (ppctx->ui_method) + ui_method = ppctx->ui_method; + if (ppctx->callback_data) + callback_data = ppctx->callback_data; + } + if (ui_method == NULL) + { + HWCRHKerr(HWCRHK_F_HWCRHK_INSERT_CARD, + HWCRHK_R_NO_CALLBACK); + return -1; + } + + ui = UI_new_method(ui_method); + + if (ui) + { + char answer; + char buf[BUFSIZ]; + /* Despite what the documentation says wrong_info can be + * an empty string. + */ + if (wrong_info && *wrong_info) + BIO_snprintf(buf, sizeof(buf)-1, + "Current card: \"%s\"\n", wrong_info); + else + buf[0] = 0; + ok = UI_dup_info_string(ui, buf); + if (ok >= 0 && prompt_info) + { + BIO_snprintf(buf, sizeof(buf)-1, + "Insert card \"%s\"", prompt_info); + ok = UI_dup_input_boolean(ui, buf, + "\n then hit or C to cancel\n", + "\r\n", "Cc", UI_INPUT_FLAG_ECHO, &answer); + } + UI_add_user_data(ui, callback_data); + + if (ok >= 0) + ok = UI_process(ui); + UI_free(ui); + + if (ok == -2 || (ok >= 0 && answer == 'C')) + ok = 1; + else if (ok < 0) + ok = -1; + else + ok = 0; + } + return ok; + } + +static void hwcrhk_log_message(void *logstr, const char *message) + { + BIO *lstream = NULL; + + CRYPTO_w_lock(CRYPTO_LOCK_BIO); + if (logstr) + lstream=*(BIO **)logstr; + if (lstream) + { + BIO_printf(lstream, "%s\n", message); + } + CRYPTO_w_unlock(CRYPTO_LOCK_BIO); + } + +/* This stuff is needed if this ENGINE is being compiled into a self-contained + * shared-library. */ +#ifndef OPENSSL_NO_DYNAMIC_ENGINE +static int bind_fn(ENGINE *e, const char *id) + { + if(id && (strcmp(id, engine_hwcrhk_id) != 0) && + (strcmp(id, engine_hwcrhk_id_alt) != 0)) + return 0; + if(!bind_helper(e)) + return 0; + return 1; + } +IMPLEMENT_DYNAMIC_CHECK_FN() +IMPLEMENT_DYNAMIC_BIND_FN(bind_fn) +#endif /* OPENSSL_NO_DYNAMIC_ENGINE */ + +#endif /* !OPENSSL_NO_HW_CHIL */ +#endif /* !OPENSSL_NO_HW */ diff --git a/node-v0.8.14/deps/openssl/openssl/engines/e_chil.ec b/node-v0.8.14/deps/openssl/openssl/engines/e_chil.ec new file mode 100644 index 0000000..b5a76e1 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/engines/e_chil.ec @@ -0,0 +1 @@ +L HWCRHK e_chil_err.h e_chil_err.c diff --git a/node-v0.8.14/deps/openssl/openssl/engines/e_chil_err.c b/node-v0.8.14/deps/openssl/openssl/engines/e_chil_err.c new file mode 100644 index 0000000..c5983b2 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/engines/e_chil_err.c @@ -0,0 +1,160 @@ +/* e_chil_err.c */ +/* ==================================================================== + * Copyright (c) 1999-2005 The OpenSSL Project. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. All advertising materials mentioning features or use of this + * software must display the following acknowledgment: + * "This product includes software developed by the OpenSSL Project + * for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)" + * + * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to + * endorse or promote products derived from this software without + * prior written permission. For written permission, please contact + * openssl-core@OpenSSL.org. + * + * 5. Products derived from this software may not be called "OpenSSL" + * nor may "OpenSSL" appear in their names without prior written + * permission of the OpenSSL Project. + * + * 6. Redistributions of any form whatsoever must retain the following + * acknowledgment: + * "This product includes software developed by the OpenSSL Project + * for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)" + * + * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY + * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR + * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, + * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * ==================================================================== + * + * This product includes cryptographic software written by Eric Young + * (eay@cryptsoft.com). This product includes software written by Tim + * Hudson (tjh@cryptsoft.com). + * + */ + +/* NOTE: this file was auto generated by the mkerr.pl script: any changes + * made to it will be overwritten when the script next updates this file, + * only reason strings will be preserved. + */ + +#include +#include +#include "e_chil_err.h" + +/* BEGIN ERROR CODES */ +#ifndef OPENSSL_NO_ERR + +#define ERR_FUNC(func) ERR_PACK(0,func,0) +#define ERR_REASON(reason) ERR_PACK(0,0,reason) + +static ERR_STRING_DATA HWCRHK_str_functs[]= + { +{ERR_FUNC(HWCRHK_F_HWCRHK_CTRL), "HWCRHK_CTRL"}, +{ERR_FUNC(HWCRHK_F_HWCRHK_FINISH), "HWCRHK_FINISH"}, +{ERR_FUNC(HWCRHK_F_HWCRHK_GET_PASS), "HWCRHK_GET_PASS"}, +{ERR_FUNC(HWCRHK_F_HWCRHK_INIT), "HWCRHK_INIT"}, +{ERR_FUNC(HWCRHK_F_HWCRHK_INSERT_CARD), "HWCRHK_INSERT_CARD"}, +{ERR_FUNC(HWCRHK_F_HWCRHK_LOAD_PRIVKEY), "HWCRHK_LOAD_PRIVKEY"}, +{ERR_FUNC(HWCRHK_F_HWCRHK_LOAD_PUBKEY), "HWCRHK_LOAD_PUBKEY"}, +{ERR_FUNC(HWCRHK_F_HWCRHK_MOD_EXP), "HWCRHK_MOD_EXP"}, +{ERR_FUNC(HWCRHK_F_HWCRHK_RAND_BYTES), "HWCRHK_RAND_BYTES"}, +{ERR_FUNC(HWCRHK_F_HWCRHK_RSA_MOD_EXP), "HWCRHK_RSA_MOD_EXP"}, +{0,NULL} + }; + +static ERR_STRING_DATA HWCRHK_str_reasons[]= + { +{ERR_REASON(HWCRHK_R_ALREADY_LOADED) ,"already loaded"}, +{ERR_REASON(HWCRHK_R_BIO_WAS_FREED) ,"bio was freed"}, +{ERR_REASON(HWCRHK_R_CHIL_ERROR) ,"chil error"}, +{ERR_REASON(HWCRHK_R_CTRL_COMMAND_NOT_IMPLEMENTED),"ctrl command not implemented"}, +{ERR_REASON(HWCRHK_R_DSO_FAILURE) ,"dso failure"}, +{ERR_REASON(HWCRHK_R_MISSING_KEY_COMPONENTS),"missing key components"}, +{ERR_REASON(HWCRHK_R_NOT_INITIALISED) ,"not initialised"}, +{ERR_REASON(HWCRHK_R_NOT_LOADED) ,"not loaded"}, +{ERR_REASON(HWCRHK_R_NO_CALLBACK) ,"no callback"}, +{ERR_REASON(HWCRHK_R_NO_KEY) ,"no key"}, +{ERR_REASON(HWCRHK_R_PRIVATE_KEY_ALGORITHMS_DISABLED),"private key algorithms disabled"}, +{ERR_REASON(HWCRHK_R_REQUEST_FAILED) ,"request failed"}, +{ERR_REASON(HWCRHK_R_REQUEST_FALLBACK) ,"request fallback"}, +{ERR_REASON(HWCRHK_R_UNIT_FAILURE) ,"unit failure"}, +{0,NULL} + }; + +#endif + +#ifdef HWCRHK_LIB_NAME +static ERR_STRING_DATA HWCRHK_lib_name[]= + { +{0 ,HWCRHK_LIB_NAME}, +{0,NULL} + }; +#endif + + +static int HWCRHK_lib_error_code=0; +static int HWCRHK_error_init=1; + +static void ERR_load_HWCRHK_strings(void) + { + if (HWCRHK_lib_error_code == 0) + HWCRHK_lib_error_code=ERR_get_next_error_library(); + + if (HWCRHK_error_init) + { + HWCRHK_error_init=0; +#ifndef OPENSSL_NO_ERR + ERR_load_strings(HWCRHK_lib_error_code,HWCRHK_str_functs); + ERR_load_strings(HWCRHK_lib_error_code,HWCRHK_str_reasons); +#endif + +#ifdef HWCRHK_LIB_NAME + HWCRHK_lib_name->error = ERR_PACK(HWCRHK_lib_error_code,0,0); + ERR_load_strings(0,HWCRHK_lib_name); +#endif + } + } + +static void ERR_unload_HWCRHK_strings(void) + { + if (HWCRHK_error_init == 0) + { +#ifndef OPENSSL_NO_ERR + ERR_unload_strings(HWCRHK_lib_error_code,HWCRHK_str_functs); + ERR_unload_strings(HWCRHK_lib_error_code,HWCRHK_str_reasons); +#endif + +#ifdef HWCRHK_LIB_NAME + ERR_unload_strings(0,HWCRHK_lib_name); +#endif + HWCRHK_error_init=1; + } + } + +static void ERR_HWCRHK_error(int function, int reason, char *file, int line) + { + if (HWCRHK_lib_error_code == 0) + HWCRHK_lib_error_code=ERR_get_next_error_library(); + ERR_PUT_error(HWCRHK_lib_error_code,function,reason,file,line); + } diff --git a/node-v0.8.14/deps/openssl/openssl/engines/e_chil_err.h b/node-v0.8.14/deps/openssl/openssl/engines/e_chil_err.h new file mode 100644 index 0000000..3c42a02 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/engines/e_chil_err.h @@ -0,0 +1,104 @@ +/* ==================================================================== + * Copyright (c) 2001 The OpenSSL Project. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. All advertising materials mentioning features or use of this + * software must display the following acknowledgment: + * "This product includes software developed by the OpenSSL Project + * for use in the OpenSSL Toolkit. (http://www.openssl.org/)" + * + * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to + * endorse or promote products derived from this software without + * prior written permission. For written permission, please contact + * openssl-core@openssl.org. + * + * 5. Products derived from this software may not be called "OpenSSL" + * nor may "OpenSSL" appear in their names without prior written + * permission of the OpenSSL Project. + * + * 6. Redistributions of any form whatsoever must retain the following + * acknowledgment: + * "This product includes software developed by the OpenSSL Project + * for use in the OpenSSL Toolkit (http://www.openssl.org/)" + * + * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY + * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR + * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, + * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * ==================================================================== + * + * This product includes cryptographic software written by Eric Young + * (eay@cryptsoft.com). This product includes software written by Tim + * Hudson (tjh@cryptsoft.com). + * + */ + +#ifndef HEADER_HWCRHK_ERR_H +#define HEADER_HWCRHK_ERR_H + +#ifdef __cplusplus +extern "C" { +#endif + +/* BEGIN ERROR CODES */ +/* The following lines are auto generated by the script mkerr.pl. Any changes + * made after this point may be overwritten when the script is next run. + */ +static void ERR_load_HWCRHK_strings(void); +static void ERR_unload_HWCRHK_strings(void); +static void ERR_HWCRHK_error(int function, int reason, char *file, int line); +#define HWCRHKerr(f,r) ERR_HWCRHK_error((f),(r),__FILE__,__LINE__) + +/* Error codes for the HWCRHK functions. */ + +/* Function codes. */ +#define HWCRHK_F_HWCRHK_CTRL 100 +#define HWCRHK_F_HWCRHK_FINISH 101 +#define HWCRHK_F_HWCRHK_GET_PASS 102 +#define HWCRHK_F_HWCRHK_INIT 103 +#define HWCRHK_F_HWCRHK_INSERT_CARD 104 +#define HWCRHK_F_HWCRHK_LOAD_PRIVKEY 105 +#define HWCRHK_F_HWCRHK_LOAD_PUBKEY 106 +#define HWCRHK_F_HWCRHK_MOD_EXP 107 +#define HWCRHK_F_HWCRHK_RAND_BYTES 108 +#define HWCRHK_F_HWCRHK_RSA_MOD_EXP 109 + +/* Reason codes. */ +#define HWCRHK_R_ALREADY_LOADED 100 +#define HWCRHK_R_BIO_WAS_FREED 101 +#define HWCRHK_R_CHIL_ERROR 102 +#define HWCRHK_R_CTRL_COMMAND_NOT_IMPLEMENTED 103 +#define HWCRHK_R_DSO_FAILURE 104 +#define HWCRHK_R_MISSING_KEY_COMPONENTS 105 +#define HWCRHK_R_NOT_INITIALISED 106 +#define HWCRHK_R_NOT_LOADED 107 +#define HWCRHK_R_NO_CALLBACK 108 +#define HWCRHK_R_NO_KEY 109 +#define HWCRHK_R_PRIVATE_KEY_ALGORITHMS_DISABLED 110 +#define HWCRHK_R_REQUEST_FAILED 111 +#define HWCRHK_R_REQUEST_FALLBACK 112 +#define HWCRHK_R_UNIT_FAILURE 113 + +#ifdef __cplusplus +} +#endif +#endif diff --git a/node-v0.8.14/deps/openssl/openssl/engines/e_cswift.c b/node-v0.8.14/deps/openssl/openssl/engines/e_cswift.c new file mode 100644 index 0000000..2e64ff3 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/engines/e_cswift.c @@ -0,0 +1,1129 @@ +/* crypto/engine/hw_cswift.c */ +/* Written by Geoff Thorpe (geoff@geoffthorpe.net) for the OpenSSL + * project 2000. + */ +/* ==================================================================== + * Copyright (c) 1999-2001 The OpenSSL Project. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. All advertising materials mentioning features or use of this + * software must display the following acknowledgment: + * "This product includes software developed by the OpenSSL Project + * for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)" + * + * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to + * endorse or promote products derived from this software without + * prior written permission. For written permission, please contact + * licensing@OpenSSL.org. + * + * 5. Products derived from this software may not be called "OpenSSL" + * nor may "OpenSSL" appear in their names without prior written + * permission of the OpenSSL Project. + * + * 6. Redistributions of any form whatsoever must retain the following + * acknowledgment: + * "This product includes software developed by the OpenSSL Project + * for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)" + * + * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY + * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR + * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, + * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * ==================================================================== + * + * This product includes cryptographic software written by Eric Young + * (eay@cryptsoft.com). This product includes software written by Tim + * Hudson (tjh@cryptsoft.com). + * + */ + +#include +#include +#include +#include +#include +#include +#ifndef OPENSSL_NO_RSA +#include +#endif +#ifndef OPENSSL_NO_DSA +#include +#endif +#ifndef OPENSSL_NO_DH +#include +#endif +#include +#include + +#ifndef OPENSSL_NO_HW +#ifndef OPENSSL_NO_HW_CSWIFT + +/* Attribution notice: Rainbow have generously allowed me to reproduce + * the necessary definitions here from their API. This means the support + * can build independently of whether application builders have the + * API or hardware. This will allow developers to easily produce software + * that has latent hardware support for any users that have accelerators + * installed, without the developers themselves needing anything extra. + * + * I have only clipped the parts from the CryptoSwift header files that + * are (or seem) relevant to the CryptoSwift support code. This is + * simply to keep the file sizes reasonable. + * [Geoff] + */ +#ifdef FLAT_INC +#include "cswift.h" +#else +#include "vendor_defns/cswift.h" +#endif + +#define CSWIFT_LIB_NAME "cswift engine" +#include "e_cswift_err.c" + +#define DECIMAL_SIZE(type) ((sizeof(type)*8+2)/3+1) + +static int cswift_destroy(ENGINE *e); +static int cswift_init(ENGINE *e); +static int cswift_finish(ENGINE *e); +static int cswift_ctrl(ENGINE *e, int cmd, long i, void *p, void (*f)(void)); +#ifndef OPENSSL_NO_RSA +static int cswift_bn_32copy(SW_LARGENUMBER * out, const BIGNUM * in); +#endif + +/* BIGNUM stuff */ +static int cswift_mod_exp(BIGNUM *r, const BIGNUM *a, const BIGNUM *p, + const BIGNUM *m, BN_CTX *ctx); +#ifndef OPENSSL_NO_RSA +static int cswift_mod_exp_crt(BIGNUM *r, const BIGNUM *a, const BIGNUM *p, + const BIGNUM *q, const BIGNUM *dmp1, const BIGNUM *dmq1, + const BIGNUM *iqmp, BN_CTX *ctx); +#endif + +#ifndef OPENSSL_NO_RSA +/* RSA stuff */ +static int cswift_rsa_mod_exp(BIGNUM *r0, const BIGNUM *I, RSA *rsa, BN_CTX *ctx); +/* This function is aliased to mod_exp (with the mont stuff dropped). */ +static int cswift_mod_exp_mont(BIGNUM *r, const BIGNUM *a, const BIGNUM *p, + const BIGNUM *m, BN_CTX *ctx, BN_MONT_CTX *m_ctx); +#endif + +#ifndef OPENSSL_NO_DSA +/* DSA stuff */ +static DSA_SIG *cswift_dsa_sign(const unsigned char *dgst, int dlen, DSA *dsa); +static int cswift_dsa_verify(const unsigned char *dgst, int dgst_len, + DSA_SIG *sig, DSA *dsa); +#endif + +#ifndef OPENSSL_NO_DH +/* DH stuff */ +/* This function is alised to mod_exp (with the DH and mont dropped). */ +static int cswift_mod_exp_dh(const DH *dh, BIGNUM *r, + const BIGNUM *a, const BIGNUM *p, + const BIGNUM *m, BN_CTX *ctx, BN_MONT_CTX *m_ctx); +#endif + +/* RAND stuff */ +static int cswift_rand_bytes(unsigned char *buf, int num); +static int cswift_rand_status(void); + +/* The definitions for control commands specific to this engine */ +#define CSWIFT_CMD_SO_PATH ENGINE_CMD_BASE +static const ENGINE_CMD_DEFN cswift_cmd_defns[] = { + {CSWIFT_CMD_SO_PATH, + "SO_PATH", + "Specifies the path to the 'cswift' shared library", + ENGINE_CMD_FLAG_STRING}, + {0, NULL, NULL, 0} + }; + +#ifndef OPENSSL_NO_RSA +/* Our internal RSA_METHOD that we provide pointers to */ +static RSA_METHOD cswift_rsa = + { + "CryptoSwift RSA method", + NULL, + NULL, + NULL, + NULL, + cswift_rsa_mod_exp, + cswift_mod_exp_mont, + NULL, + NULL, + 0, + NULL, + NULL, + NULL, + NULL + }; +#endif + +#ifndef OPENSSL_NO_DSA +/* Our internal DSA_METHOD that we provide pointers to */ +static DSA_METHOD cswift_dsa = + { + "CryptoSwift DSA method", + cswift_dsa_sign, + NULL, /* dsa_sign_setup */ + cswift_dsa_verify, + NULL, /* dsa_mod_exp */ + NULL, /* bn_mod_exp */ + NULL, /* init */ + NULL, /* finish */ + 0, /* flags */ + NULL, /* app_data */ + NULL, /* dsa_paramgen */ + NULL /* dsa_keygen */ + }; +#endif + +#ifndef OPENSSL_NO_DH +/* Our internal DH_METHOD that we provide pointers to */ +static DH_METHOD cswift_dh = + { + "CryptoSwift DH method", + NULL, + NULL, + cswift_mod_exp_dh, + NULL, + NULL, + 0, + NULL, + NULL + }; +#endif + +static RAND_METHOD cswift_random = + { + /* "CryptoSwift RAND method", */ + NULL, + cswift_rand_bytes, + NULL, + NULL, + cswift_rand_bytes, + cswift_rand_status, + }; + + +/* Constants used when creating the ENGINE */ +static const char *engine_cswift_id = "cswift"; +static const char *engine_cswift_name = "CryptoSwift hardware engine support"; + +/* This internal function is used by ENGINE_cswift() and possibly by the + * "dynamic" ENGINE support too */ +static int bind_helper(ENGINE *e) + { +#ifndef OPENSSL_NO_RSA + const RSA_METHOD *meth1; +#endif +#ifndef OPENSSL_NO_DH + const DH_METHOD *meth2; +#endif + if(!ENGINE_set_id(e, engine_cswift_id) || + !ENGINE_set_name(e, engine_cswift_name) || +#ifndef OPENSSL_NO_RSA + !ENGINE_set_RSA(e, &cswift_rsa) || +#endif +#ifndef OPENSSL_NO_DSA + !ENGINE_set_DSA(e, &cswift_dsa) || +#endif +#ifndef OPENSSL_NO_DH + !ENGINE_set_DH(e, &cswift_dh) || +#endif + !ENGINE_set_RAND(e, &cswift_random) || + !ENGINE_set_destroy_function(e, cswift_destroy) || + !ENGINE_set_init_function(e, cswift_init) || + !ENGINE_set_finish_function(e, cswift_finish) || + !ENGINE_set_ctrl_function(e, cswift_ctrl) || + !ENGINE_set_cmd_defns(e, cswift_cmd_defns)) + return 0; + +#ifndef OPENSSL_NO_RSA + /* We know that the "PKCS1_SSLeay()" functions hook properly + * to the cswift-specific mod_exp and mod_exp_crt so we use + * those functions. NB: We don't use ENGINE_openssl() or + * anything "more generic" because something like the RSAref + * code may not hook properly, and if you own one of these + * cards then you have the right to do RSA operations on it + * anyway! */ + meth1 = RSA_PKCS1_SSLeay(); + cswift_rsa.rsa_pub_enc = meth1->rsa_pub_enc; + cswift_rsa.rsa_pub_dec = meth1->rsa_pub_dec; + cswift_rsa.rsa_priv_enc = meth1->rsa_priv_enc; + cswift_rsa.rsa_priv_dec = meth1->rsa_priv_dec; +#endif + +#ifndef OPENSSL_NO_DH + /* Much the same for Diffie-Hellman */ + meth2 = DH_OpenSSL(); + cswift_dh.generate_key = meth2->generate_key; + cswift_dh.compute_key = meth2->compute_key; +#endif + + /* Ensure the cswift error handling is set up */ + ERR_load_CSWIFT_strings(); + return 1; + } + +#ifdef OPENSSL_NO_DYNAMIC_ENGINE +static ENGINE *engine_cswift(void) + { + ENGINE *ret = ENGINE_new(); + if(!ret) + return NULL; + if(!bind_helper(ret)) + { + ENGINE_free(ret); + return NULL; + } + return ret; + } + +void ENGINE_load_cswift(void) + { + /* Copied from eng_[openssl|dyn].c */ + ENGINE *toadd = engine_cswift(); + if(!toadd) return; + ENGINE_add(toadd); + ENGINE_free(toadd); + ERR_clear_error(); + } +#endif + +/* This is a process-global DSO handle used for loading and unloading + * the CryptoSwift library. NB: This is only set (or unset) during an + * init() or finish() call (reference counts permitting) and they're + * operating with global locks, so this should be thread-safe + * implicitly. */ +static DSO *cswift_dso = NULL; + +/* These are the function pointers that are (un)set when the library has + * successfully (un)loaded. */ +t_swAcquireAccContext *p_CSwift_AcquireAccContext = NULL; +t_swAttachKeyParam *p_CSwift_AttachKeyParam = NULL; +t_swSimpleRequest *p_CSwift_SimpleRequest = NULL; +t_swReleaseAccContext *p_CSwift_ReleaseAccContext = NULL; + +/* Used in the DSO operations. */ +static const char *CSWIFT_LIBNAME = NULL; +static const char *get_CSWIFT_LIBNAME(void) + { + if(CSWIFT_LIBNAME) + return CSWIFT_LIBNAME; + return "swift"; + } +static void free_CSWIFT_LIBNAME(void) + { + if(CSWIFT_LIBNAME) + OPENSSL_free((void*)CSWIFT_LIBNAME); + CSWIFT_LIBNAME = NULL; + } +static long set_CSWIFT_LIBNAME(const char *name) + { + free_CSWIFT_LIBNAME(); + return (((CSWIFT_LIBNAME = BUF_strdup(name)) != NULL) ? 1 : 0); + } +static const char *CSWIFT_F1 = "swAcquireAccContext"; +static const char *CSWIFT_F2 = "swAttachKeyParam"; +static const char *CSWIFT_F3 = "swSimpleRequest"; +static const char *CSWIFT_F4 = "swReleaseAccContext"; + + +/* CryptoSwift library functions and mechanics - these are used by the + * higher-level functions further down. NB: As and where there's no + * error checking, take a look lower down where these functions are + * called, the checking and error handling is probably down there. */ + +/* utility function to obtain a context */ +static int get_context(SW_CONTEXT_HANDLE *hac) + { + SW_STATUS status; + + status = p_CSwift_AcquireAccContext(hac); + if(status != SW_OK) + return 0; + return 1; + } + +/* similarly to release one. */ +static void release_context(SW_CONTEXT_HANDLE hac) + { + p_CSwift_ReleaseAccContext(hac); + } + +/* Destructor (complements the "ENGINE_cswift()" constructor) */ +static int cswift_destroy(ENGINE *e) + { + free_CSWIFT_LIBNAME(); + ERR_unload_CSWIFT_strings(); + return 1; + } + +/* (de)initialisation functions. */ +static int cswift_init(ENGINE *e) + { + SW_CONTEXT_HANDLE hac; + t_swAcquireAccContext *p1; + t_swAttachKeyParam *p2; + t_swSimpleRequest *p3; + t_swReleaseAccContext *p4; + + if(cswift_dso != NULL) + { + CSWIFTerr(CSWIFT_F_CSWIFT_INIT,CSWIFT_R_ALREADY_LOADED); + goto err; + } + /* Attempt to load libswift.so/swift.dll/whatever. */ + cswift_dso = DSO_load(NULL, get_CSWIFT_LIBNAME(), NULL, 0); + if(cswift_dso == NULL) + { + CSWIFTerr(CSWIFT_F_CSWIFT_INIT,CSWIFT_R_NOT_LOADED); + goto err; + } + if(!(p1 = (t_swAcquireAccContext *) + DSO_bind_func(cswift_dso, CSWIFT_F1)) || + !(p2 = (t_swAttachKeyParam *) + DSO_bind_func(cswift_dso, CSWIFT_F2)) || + !(p3 = (t_swSimpleRequest *) + DSO_bind_func(cswift_dso, CSWIFT_F3)) || + !(p4 = (t_swReleaseAccContext *) + DSO_bind_func(cswift_dso, CSWIFT_F4))) + { + CSWIFTerr(CSWIFT_F_CSWIFT_INIT,CSWIFT_R_NOT_LOADED); + goto err; + } + /* Copy the pointers */ + p_CSwift_AcquireAccContext = p1; + p_CSwift_AttachKeyParam = p2; + p_CSwift_SimpleRequest = p3; + p_CSwift_ReleaseAccContext = p4; + /* Try and get a context - if not, we may have a DSO but no + * accelerator! */ + if(!get_context(&hac)) + { + CSWIFTerr(CSWIFT_F_CSWIFT_INIT,CSWIFT_R_UNIT_FAILURE); + goto err; + } + release_context(hac); + /* Everything's fine. */ + return 1; +err: + if(cswift_dso) + { + DSO_free(cswift_dso); + cswift_dso = NULL; + } + p_CSwift_AcquireAccContext = NULL; + p_CSwift_AttachKeyParam = NULL; + p_CSwift_SimpleRequest = NULL; + p_CSwift_ReleaseAccContext = NULL; + return 0; + } + +static int cswift_finish(ENGINE *e) + { + free_CSWIFT_LIBNAME(); + if(cswift_dso == NULL) + { + CSWIFTerr(CSWIFT_F_CSWIFT_FINISH,CSWIFT_R_NOT_LOADED); + return 0; + } + if(!DSO_free(cswift_dso)) + { + CSWIFTerr(CSWIFT_F_CSWIFT_FINISH,CSWIFT_R_UNIT_FAILURE); + return 0; + } + cswift_dso = NULL; + p_CSwift_AcquireAccContext = NULL; + p_CSwift_AttachKeyParam = NULL; + p_CSwift_SimpleRequest = NULL; + p_CSwift_ReleaseAccContext = NULL; + return 1; + } + +static int cswift_ctrl(ENGINE *e, int cmd, long i, void *p, void (*f)(void)) + { + int initialised = ((cswift_dso == NULL) ? 0 : 1); + switch(cmd) + { + case CSWIFT_CMD_SO_PATH: + if(p == NULL) + { + CSWIFTerr(CSWIFT_F_CSWIFT_CTRL,ERR_R_PASSED_NULL_PARAMETER); + return 0; + } + if(initialised) + { + CSWIFTerr(CSWIFT_F_CSWIFT_CTRL,CSWIFT_R_ALREADY_LOADED); + return 0; + } + return set_CSWIFT_LIBNAME((const char *)p); + default: + break; + } + CSWIFTerr(CSWIFT_F_CSWIFT_CTRL,CSWIFT_R_CTRL_COMMAND_NOT_IMPLEMENTED); + return 0; + } + +/* Un petit mod_exp */ +static int cswift_mod_exp(BIGNUM *r, const BIGNUM *a, const BIGNUM *p, + const BIGNUM *m, BN_CTX *ctx) + { + /* I need somewhere to store temporary serialised values for + * use with the CryptoSwift API calls. A neat cheat - I'll use + * BIGNUMs from the BN_CTX but access their arrays directly as + * byte arrays . This way I don't have to clean anything + * up. */ + BIGNUM *modulus; + BIGNUM *exponent; + BIGNUM *argument; + BIGNUM *result; + SW_STATUS sw_status; + SW_LARGENUMBER arg, res; + SW_PARAM sw_param; + SW_CONTEXT_HANDLE hac; + int to_return, acquired; + + modulus = exponent = argument = result = NULL; + to_return = 0; /* expect failure */ + acquired = 0; + + if(!get_context(&hac)) + { + CSWIFTerr(CSWIFT_F_CSWIFT_MOD_EXP,CSWIFT_R_UNIT_FAILURE); + goto err; + } + acquired = 1; + /* Prepare the params */ + BN_CTX_start(ctx); + modulus = BN_CTX_get(ctx); + exponent = BN_CTX_get(ctx); + argument = BN_CTX_get(ctx); + result = BN_CTX_get(ctx); + if(!result) + { + CSWIFTerr(CSWIFT_F_CSWIFT_MOD_EXP,CSWIFT_R_BN_CTX_FULL); + goto err; + } + if(!bn_wexpand(modulus, m->top) || !bn_wexpand(exponent, p->top) || + !bn_wexpand(argument, a->top) || !bn_wexpand(result, m->top)) + { + CSWIFTerr(CSWIFT_F_CSWIFT_MOD_EXP,CSWIFT_R_BN_EXPAND_FAIL); + goto err; + } + sw_param.type = SW_ALG_EXP; + sw_param.up.exp.modulus.nbytes = BN_bn2bin(m, + (unsigned char *)modulus->d); + sw_param.up.exp.modulus.value = (unsigned char *)modulus->d; + sw_param.up.exp.exponent.nbytes = BN_bn2bin(p, + (unsigned char *)exponent->d); + sw_param.up.exp.exponent.value = (unsigned char *)exponent->d; + /* Attach the key params */ + sw_status = p_CSwift_AttachKeyParam(hac, &sw_param); + switch(sw_status) + { + case SW_OK: + break; + case SW_ERR_INPUT_SIZE: + CSWIFTerr(CSWIFT_F_CSWIFT_MOD_EXP,CSWIFT_R_BAD_KEY_SIZE); + goto err; + default: + { + char tmpbuf[DECIMAL_SIZE(sw_status)+1]; + CSWIFTerr(CSWIFT_F_CSWIFT_MOD_EXP,CSWIFT_R_REQUEST_FAILED); + sprintf(tmpbuf, "%ld", sw_status); + ERR_add_error_data(2, "CryptoSwift error number is ",tmpbuf); + } + goto err; + } + /* Prepare the argument and response */ + arg.nbytes = BN_bn2bin(a, (unsigned char *)argument->d); + arg.value = (unsigned char *)argument->d; + res.nbytes = BN_num_bytes(m); + memset(result->d, 0, res.nbytes); + res.value = (unsigned char *)result->d; + /* Perform the operation */ + if((sw_status = p_CSwift_SimpleRequest(hac, SW_CMD_MODEXP, &arg, 1, + &res, 1)) != SW_OK) + { + char tmpbuf[DECIMAL_SIZE(sw_status)+1]; + CSWIFTerr(CSWIFT_F_CSWIFT_MOD_EXP,CSWIFT_R_REQUEST_FAILED); + sprintf(tmpbuf, "%ld", sw_status); + ERR_add_error_data(2, "CryptoSwift error number is ",tmpbuf); + goto err; + } + /* Convert the response */ + BN_bin2bn((unsigned char *)result->d, res.nbytes, r); + to_return = 1; +err: + if(acquired) + release_context(hac); + BN_CTX_end(ctx); + return to_return; + } + + +#ifndef OPENSSL_NO_RSA +int cswift_bn_32copy(SW_LARGENUMBER * out, const BIGNUM * in) +{ + int mod; + int numbytes = BN_num_bytes(in); + + mod = 0; + while( ((out->nbytes = (numbytes+mod)) % 32) ) + { + mod++; + } + out->value = (unsigned char*)OPENSSL_malloc(out->nbytes); + if(!out->value) + { + return 0; + } + BN_bn2bin(in, &out->value[mod]); + if(mod) + memset(out->value, 0, mod); + + return 1; +} +#endif + +#ifndef OPENSSL_NO_RSA +/* Un petit mod_exp chinois */ +static int cswift_mod_exp_crt(BIGNUM *r, const BIGNUM *a, const BIGNUM *p, + const BIGNUM *q, const BIGNUM *dmp1, + const BIGNUM *dmq1, const BIGNUM *iqmp, BN_CTX *ctx) + { + SW_STATUS sw_status; + SW_LARGENUMBER arg, res; + SW_PARAM sw_param; + SW_CONTEXT_HANDLE hac; + BIGNUM *result = NULL; + BIGNUM *argument = NULL; + int to_return = 0; /* expect failure */ + int acquired = 0; + + sw_param.up.crt.p.value = NULL; + sw_param.up.crt.q.value = NULL; + sw_param.up.crt.dmp1.value = NULL; + sw_param.up.crt.dmq1.value = NULL; + sw_param.up.crt.iqmp.value = NULL; + + if(!get_context(&hac)) + { + CSWIFTerr(CSWIFT_F_CSWIFT_MOD_EXP_CRT,CSWIFT_R_UNIT_FAILURE); + goto err; + } + acquired = 1; + + /* Prepare the params */ + argument = BN_new(); + result = BN_new(); + if(!result || !argument) + { + CSWIFTerr(CSWIFT_F_CSWIFT_MOD_EXP_CRT,CSWIFT_R_BN_CTX_FULL); + goto err; + } + + + sw_param.type = SW_ALG_CRT; + /************************************************************************/ + /* 04/02/2003 */ + /* Modified by Frederic Giudicelli (deny-all.com) to overcome the */ + /* limitation of cswift with values not a multiple of 32 */ + /************************************************************************/ + if(!cswift_bn_32copy(&sw_param.up.crt.p, p)) + { + CSWIFTerr(CSWIFT_F_CSWIFT_MOD_EXP_CRT,CSWIFT_R_BN_EXPAND_FAIL); + goto err; + } + if(!cswift_bn_32copy(&sw_param.up.crt.q, q)) + { + CSWIFTerr(CSWIFT_F_CSWIFT_MOD_EXP_CRT,CSWIFT_R_BN_EXPAND_FAIL); + goto err; + } + if(!cswift_bn_32copy(&sw_param.up.crt.dmp1, dmp1)) + { + CSWIFTerr(CSWIFT_F_CSWIFT_MOD_EXP_CRT,CSWIFT_R_BN_EXPAND_FAIL); + goto err; + } + if(!cswift_bn_32copy(&sw_param.up.crt.dmq1, dmq1)) + { + CSWIFTerr(CSWIFT_F_CSWIFT_MOD_EXP_CRT,CSWIFT_R_BN_EXPAND_FAIL); + goto err; + } + if(!cswift_bn_32copy(&sw_param.up.crt.iqmp, iqmp)) + { + CSWIFTerr(CSWIFT_F_CSWIFT_MOD_EXP_CRT,CSWIFT_R_BN_EXPAND_FAIL); + goto err; + } + if( !bn_wexpand(argument, a->top) || + !bn_wexpand(result, p->top + q->top)) + { + CSWIFTerr(CSWIFT_F_CSWIFT_MOD_EXP_CRT,CSWIFT_R_BN_EXPAND_FAIL); + goto err; + } + + /* Attach the key params */ + sw_status = p_CSwift_AttachKeyParam(hac, &sw_param); + switch(sw_status) + { + case SW_OK: + break; + case SW_ERR_INPUT_SIZE: + CSWIFTerr(CSWIFT_F_CSWIFT_MOD_EXP_CRT,CSWIFT_R_BAD_KEY_SIZE); + goto err; + default: + { + char tmpbuf[DECIMAL_SIZE(sw_status)+1]; + CSWIFTerr(CSWIFT_F_CSWIFT_MOD_EXP_CRT,CSWIFT_R_REQUEST_FAILED); + sprintf(tmpbuf, "%ld", sw_status); + ERR_add_error_data(2, "CryptoSwift error number is ",tmpbuf); + } + goto err; + } + /* Prepare the argument and response */ + arg.nbytes = BN_bn2bin(a, (unsigned char *)argument->d); + arg.value = (unsigned char *)argument->d; + res.nbytes = 2 * BN_num_bytes(p); + memset(result->d, 0, res.nbytes); + res.value = (unsigned char *)result->d; + /* Perform the operation */ + if((sw_status = p_CSwift_SimpleRequest(hac, SW_CMD_MODEXP_CRT, &arg, 1, + &res, 1)) != SW_OK) + { + char tmpbuf[DECIMAL_SIZE(sw_status)+1]; + CSWIFTerr(CSWIFT_F_CSWIFT_MOD_EXP_CRT,CSWIFT_R_REQUEST_FAILED); + sprintf(tmpbuf, "%ld", sw_status); + ERR_add_error_data(2, "CryptoSwift error number is ",tmpbuf); + goto err; + } + /* Convert the response */ + BN_bin2bn((unsigned char *)result->d, res.nbytes, r); + to_return = 1; +err: + if(sw_param.up.crt.p.value) + OPENSSL_free(sw_param.up.crt.p.value); + if(sw_param.up.crt.q.value) + OPENSSL_free(sw_param.up.crt.q.value); + if(sw_param.up.crt.dmp1.value) + OPENSSL_free(sw_param.up.crt.dmp1.value); + if(sw_param.up.crt.dmq1.value) + OPENSSL_free(sw_param.up.crt.dmq1.value); + if(sw_param.up.crt.iqmp.value) + OPENSSL_free(sw_param.up.crt.iqmp.value); + if(result) + BN_free(result); + if(argument) + BN_free(argument); + if(acquired) + release_context(hac); + return to_return; + } +#endif + +#ifndef OPENSSL_NO_RSA +static int cswift_rsa_mod_exp(BIGNUM *r0, const BIGNUM *I, RSA *rsa, BN_CTX *ctx) + { + int to_return = 0; + const RSA_METHOD * def_rsa_method; + + if(!rsa->p || !rsa->q || !rsa->dmp1 || !rsa->dmq1 || !rsa->iqmp) + { + CSWIFTerr(CSWIFT_F_CSWIFT_RSA_MOD_EXP,CSWIFT_R_MISSING_KEY_COMPONENTS); + goto err; + } + + /* Try the limits of RSA (2048 bits) */ + if(BN_num_bytes(rsa->p) > 128 || + BN_num_bytes(rsa->q) > 128 || + BN_num_bytes(rsa->dmp1) > 128 || + BN_num_bytes(rsa->dmq1) > 128 || + BN_num_bytes(rsa->iqmp) > 128) + { +#ifdef RSA_NULL + def_rsa_method=RSA_null_method(); +#else +#if 0 + def_rsa_method=RSA_PKCS1_RSAref(); +#else + def_rsa_method=RSA_PKCS1_SSLeay(); +#endif +#endif + if(def_rsa_method) + return def_rsa_method->rsa_mod_exp(r0, I, rsa, ctx); + } + + to_return = cswift_mod_exp_crt(r0, I, rsa->p, rsa->q, rsa->dmp1, + rsa->dmq1, rsa->iqmp, ctx); +err: + return to_return; + } + +/* This function is aliased to mod_exp (with the mont stuff dropped). */ +static int cswift_mod_exp_mont(BIGNUM *r, const BIGNUM *a, const BIGNUM *p, + const BIGNUM *m, BN_CTX *ctx, BN_MONT_CTX *m_ctx) + { + const RSA_METHOD * def_rsa_method; + + /* Try the limits of RSA (2048 bits) */ + if(BN_num_bytes(r) > 256 || + BN_num_bytes(a) > 256 || + BN_num_bytes(m) > 256) + { +#ifdef RSA_NULL + def_rsa_method=RSA_null_method(); +#else +#if 0 + def_rsa_method=RSA_PKCS1_RSAref(); +#else + def_rsa_method=RSA_PKCS1_SSLeay(); +#endif +#endif + if(def_rsa_method) + return def_rsa_method->bn_mod_exp(r, a, p, m, ctx, m_ctx); + } + + return cswift_mod_exp(r, a, p, m, ctx); + } +#endif /* OPENSSL_NO_RSA */ + +#ifndef OPENSSL_NO_DSA +static DSA_SIG *cswift_dsa_sign(const unsigned char *dgst, int dlen, DSA *dsa) + { + SW_CONTEXT_HANDLE hac; + SW_PARAM sw_param; + SW_STATUS sw_status; + SW_LARGENUMBER arg, res; + BN_CTX *ctx; + BIGNUM *dsa_p = NULL; + BIGNUM *dsa_q = NULL; + BIGNUM *dsa_g = NULL; + BIGNUM *dsa_key = NULL; + BIGNUM *result = NULL; + DSA_SIG *to_return = NULL; + int acquired = 0; + + if((ctx = BN_CTX_new()) == NULL) + goto err; + if(!get_context(&hac)) + { + CSWIFTerr(CSWIFT_F_CSWIFT_DSA_SIGN,CSWIFT_R_UNIT_FAILURE); + goto err; + } + acquired = 1; + /* Prepare the params */ + BN_CTX_start(ctx); + dsa_p = BN_CTX_get(ctx); + dsa_q = BN_CTX_get(ctx); + dsa_g = BN_CTX_get(ctx); + dsa_key = BN_CTX_get(ctx); + result = BN_CTX_get(ctx); + if(!result) + { + CSWIFTerr(CSWIFT_F_CSWIFT_DSA_SIGN,CSWIFT_R_BN_CTX_FULL); + goto err; + } + if(!bn_wexpand(dsa_p, dsa->p->top) || + !bn_wexpand(dsa_q, dsa->q->top) || + !bn_wexpand(dsa_g, dsa->g->top) || + !bn_wexpand(dsa_key, dsa->priv_key->top) || + !bn_wexpand(result, dsa->p->top)) + { + CSWIFTerr(CSWIFT_F_CSWIFT_DSA_SIGN,CSWIFT_R_BN_EXPAND_FAIL); + goto err; + } + sw_param.type = SW_ALG_DSA; + sw_param.up.dsa.p.nbytes = BN_bn2bin(dsa->p, + (unsigned char *)dsa_p->d); + sw_param.up.dsa.p.value = (unsigned char *)dsa_p->d; + sw_param.up.dsa.q.nbytes = BN_bn2bin(dsa->q, + (unsigned char *)dsa_q->d); + sw_param.up.dsa.q.value = (unsigned char *)dsa_q->d; + sw_param.up.dsa.g.nbytes = BN_bn2bin(dsa->g, + (unsigned char *)dsa_g->d); + sw_param.up.dsa.g.value = (unsigned char *)dsa_g->d; + sw_param.up.dsa.key.nbytes = BN_bn2bin(dsa->priv_key, + (unsigned char *)dsa_key->d); + sw_param.up.dsa.key.value = (unsigned char *)dsa_key->d; + /* Attach the key params */ + sw_status = p_CSwift_AttachKeyParam(hac, &sw_param); + switch(sw_status) + { + case SW_OK: + break; + case SW_ERR_INPUT_SIZE: + CSWIFTerr(CSWIFT_F_CSWIFT_DSA_SIGN,CSWIFT_R_BAD_KEY_SIZE); + goto err; + default: + { + char tmpbuf[DECIMAL_SIZE(sw_status)+1]; + CSWIFTerr(CSWIFT_F_CSWIFT_DSA_SIGN,CSWIFT_R_REQUEST_FAILED); + sprintf(tmpbuf, "%ld", sw_status); + ERR_add_error_data(2, "CryptoSwift error number is ",tmpbuf); + } + goto err; + } + /* Prepare the argument and response */ + arg.nbytes = dlen; + arg.value = (unsigned char *)dgst; + res.nbytes = BN_num_bytes(dsa->p); + memset(result->d, 0, res.nbytes); + res.value = (unsigned char *)result->d; + /* Perform the operation */ + sw_status = p_CSwift_SimpleRequest(hac, SW_CMD_DSS_SIGN, &arg, 1, + &res, 1); + if(sw_status != SW_OK) + { + char tmpbuf[DECIMAL_SIZE(sw_status)+1]; + CSWIFTerr(CSWIFT_F_CSWIFT_DSA_SIGN,CSWIFT_R_REQUEST_FAILED); + sprintf(tmpbuf, "%ld", sw_status); + ERR_add_error_data(2, "CryptoSwift error number is ",tmpbuf); + goto err; + } + /* Convert the response */ + if((to_return = DSA_SIG_new()) == NULL) + goto err; + to_return->r = BN_bin2bn((unsigned char *)result->d, 20, NULL); + to_return->s = BN_bin2bn((unsigned char *)result->d + 20, 20, NULL); + +err: + if(acquired) + release_context(hac); + if(ctx) + { + BN_CTX_end(ctx); + BN_CTX_free(ctx); + } + return to_return; + } + +static int cswift_dsa_verify(const unsigned char *dgst, int dgst_len, + DSA_SIG *sig, DSA *dsa) + { + SW_CONTEXT_HANDLE hac; + SW_PARAM sw_param; + SW_STATUS sw_status; + SW_LARGENUMBER arg[2], res; + unsigned long sig_result; + BN_CTX *ctx; + BIGNUM *dsa_p = NULL; + BIGNUM *dsa_q = NULL; + BIGNUM *dsa_g = NULL; + BIGNUM *dsa_key = NULL; + BIGNUM *argument = NULL; + int to_return = -1; + int acquired = 0; + + if((ctx = BN_CTX_new()) == NULL) + goto err; + if(!get_context(&hac)) + { + CSWIFTerr(CSWIFT_F_CSWIFT_DSA_VERIFY,CSWIFT_R_UNIT_FAILURE); + goto err; + } + acquired = 1; + /* Prepare the params */ + BN_CTX_start(ctx); + dsa_p = BN_CTX_get(ctx); + dsa_q = BN_CTX_get(ctx); + dsa_g = BN_CTX_get(ctx); + dsa_key = BN_CTX_get(ctx); + argument = BN_CTX_get(ctx); + if(!argument) + { + CSWIFTerr(CSWIFT_F_CSWIFT_DSA_VERIFY,CSWIFT_R_BN_CTX_FULL); + goto err; + } + if(!bn_wexpand(dsa_p, dsa->p->top) || + !bn_wexpand(dsa_q, dsa->q->top) || + !bn_wexpand(dsa_g, dsa->g->top) || + !bn_wexpand(dsa_key, dsa->pub_key->top) || + !bn_wexpand(argument, 40)) + { + CSWIFTerr(CSWIFT_F_CSWIFT_DSA_VERIFY,CSWIFT_R_BN_EXPAND_FAIL); + goto err; + } + sw_param.type = SW_ALG_DSA; + sw_param.up.dsa.p.nbytes = BN_bn2bin(dsa->p, + (unsigned char *)dsa_p->d); + sw_param.up.dsa.p.value = (unsigned char *)dsa_p->d; + sw_param.up.dsa.q.nbytes = BN_bn2bin(dsa->q, + (unsigned char *)dsa_q->d); + sw_param.up.dsa.q.value = (unsigned char *)dsa_q->d; + sw_param.up.dsa.g.nbytes = BN_bn2bin(dsa->g, + (unsigned char *)dsa_g->d); + sw_param.up.dsa.g.value = (unsigned char *)dsa_g->d; + sw_param.up.dsa.key.nbytes = BN_bn2bin(dsa->pub_key, + (unsigned char *)dsa_key->d); + sw_param.up.dsa.key.value = (unsigned char *)dsa_key->d; + /* Attach the key params */ + sw_status = p_CSwift_AttachKeyParam(hac, &sw_param); + switch(sw_status) + { + case SW_OK: + break; + case SW_ERR_INPUT_SIZE: + CSWIFTerr(CSWIFT_F_CSWIFT_DSA_VERIFY,CSWIFT_R_BAD_KEY_SIZE); + goto err; + default: + { + char tmpbuf[DECIMAL_SIZE(sw_status)+1]; + CSWIFTerr(CSWIFT_F_CSWIFT_DSA_VERIFY,CSWIFT_R_REQUEST_FAILED); + sprintf(tmpbuf, "%ld", sw_status); + ERR_add_error_data(2, "CryptoSwift error number is ",tmpbuf); + } + goto err; + } + /* Prepare the argument and response */ + arg[0].nbytes = dgst_len; + arg[0].value = (unsigned char *)dgst; + arg[1].nbytes = 40; + arg[1].value = (unsigned char *)argument->d; + memset(arg[1].value, 0, 40); + BN_bn2bin(sig->r, arg[1].value + 20 - BN_num_bytes(sig->r)); + BN_bn2bin(sig->s, arg[1].value + 40 - BN_num_bytes(sig->s)); + res.nbytes = 4; /* unsigned long */ + res.value = (unsigned char *)(&sig_result); + /* Perform the operation */ + sw_status = p_CSwift_SimpleRequest(hac, SW_CMD_DSS_VERIFY, arg, 2, + &res, 1); + if(sw_status != SW_OK) + { + char tmpbuf[DECIMAL_SIZE(sw_status)+1]; + CSWIFTerr(CSWIFT_F_CSWIFT_DSA_VERIFY,CSWIFT_R_REQUEST_FAILED); + sprintf(tmpbuf, "%ld", sw_status); + ERR_add_error_data(2, "CryptoSwift error number is ",tmpbuf); + goto err; + } + /* Convert the response */ + to_return = ((sig_result == 0) ? 0 : 1); + +err: + if(acquired) + release_context(hac); + if(ctx) + { + BN_CTX_end(ctx); + BN_CTX_free(ctx); + } + return to_return; + } +#endif + +#ifndef OPENSSL_NO_DH +/* This function is aliased to mod_exp (with the dh and mont dropped). */ +static int cswift_mod_exp_dh(const DH *dh, BIGNUM *r, + const BIGNUM *a, const BIGNUM *p, + const BIGNUM *m, BN_CTX *ctx, BN_MONT_CTX *m_ctx) + { + return cswift_mod_exp(r, a, p, m, ctx); + } +#endif + +/* Random bytes are good */ +static int cswift_rand_bytes(unsigned char *buf, int num) +{ + SW_CONTEXT_HANDLE hac; + SW_STATUS swrc; + SW_LARGENUMBER largenum; + int acquired = 0; + int to_return = 0; /* assume failure */ + unsigned char buf32[1024]; + + + if (!get_context(&hac)) + { + CSWIFTerr(CSWIFT_F_CSWIFT_RAND_BYTES, CSWIFT_R_UNIT_FAILURE); + goto err; + } + acquired = 1; + + /************************************************************************/ + /* 04/02/2003 */ + /* Modified by Frederic Giudicelli (deny-all.com) to overcome the */ + /* limitation of cswift with values not a multiple of 32 */ + /************************************************************************/ + + while(num >= (int)sizeof(buf32)) + { + largenum.value = buf; + largenum.nbytes = sizeof(buf32); + /* tell CryptoSwift how many bytes we want and where we want it. + * Note: - CryptoSwift cannot do more than 4096 bytes at a time. + * - CryptoSwift can only do multiple of 32-bits. */ + swrc = p_CSwift_SimpleRequest(hac, SW_CMD_RAND, NULL, 0, &largenum, 1); + if (swrc != SW_OK) + { + char tmpbuf[20]; + CSWIFTerr(CSWIFT_F_CSWIFT_RAND_BYTES, CSWIFT_R_REQUEST_FAILED); + sprintf(tmpbuf, "%ld", swrc); + ERR_add_error_data(2, "CryptoSwift error number is ", tmpbuf); + goto err; + } + buf += sizeof(buf32); + num -= sizeof(buf32); + } + if(num) + { + largenum.nbytes = sizeof(buf32); + largenum.value = buf32; + swrc = p_CSwift_SimpleRequest(hac, SW_CMD_RAND, NULL, 0, &largenum, 1); + if (swrc != SW_OK) + { + char tmpbuf[20]; + CSWIFTerr(CSWIFT_F_CSWIFT_RAND_BYTES, CSWIFT_R_REQUEST_FAILED); + sprintf(tmpbuf, "%ld", swrc); + ERR_add_error_data(2, "CryptoSwift error number is ", tmpbuf); + goto err; + } + memcpy(buf, largenum.value, num); + } + + to_return = 1; /* success */ +err: + if (acquired) + release_context(hac); + + return to_return; +} + +static int cswift_rand_status(void) +{ + return 1; +} + + +/* This stuff is needed if this ENGINE is being compiled into a self-contained + * shared-library. */ +#ifndef OPENSSL_NO_DYNAMIC_ENGINE +static int bind_fn(ENGINE *e, const char *id) + { + if(id && (strcmp(id, engine_cswift_id) != 0)) + return 0; + if(!bind_helper(e)) + return 0; + return 1; + } +IMPLEMENT_DYNAMIC_CHECK_FN() +IMPLEMENT_DYNAMIC_BIND_FN(bind_fn) +#endif /* OPENSSL_NO_DYNAMIC_ENGINE */ + +#endif /* !OPENSSL_NO_HW_CSWIFT */ +#endif /* !OPENSSL_NO_HW */ diff --git a/node-v0.8.14/deps/openssl/openssl/engines/e_cswift.ec b/node-v0.8.14/deps/openssl/openssl/engines/e_cswift.ec new file mode 100644 index 0000000..a7f9d11 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/engines/e_cswift.ec @@ -0,0 +1 @@ +L CSWIFT e_cswift_err.h e_cswift_err.c diff --git a/node-v0.8.14/deps/openssl/openssl/engines/e_cswift_err.c b/node-v0.8.14/deps/openssl/openssl/engines/e_cswift_err.c new file mode 100644 index 0000000..c7942a3 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/engines/e_cswift_err.c @@ -0,0 +1,154 @@ +/* e_cswift_err.c */ +/* ==================================================================== + * Copyright (c) 1999-2005 The OpenSSL Project. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. All advertising materials mentioning features or use of this + * software must display the following acknowledgment: + * "This product includes software developed by the OpenSSL Project + * for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)" + * + * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to + * endorse or promote products derived from this software without + * prior written permission. For written permission, please contact + * openssl-core@OpenSSL.org. + * + * 5. Products derived from this software may not be called "OpenSSL" + * nor may "OpenSSL" appear in their names without prior written + * permission of the OpenSSL Project. + * + * 6. Redistributions of any form whatsoever must retain the following + * acknowledgment: + * "This product includes software developed by the OpenSSL Project + * for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)" + * + * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY + * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR + * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, + * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * ==================================================================== + * + * This product includes cryptographic software written by Eric Young + * (eay@cryptsoft.com). This product includes software written by Tim + * Hudson (tjh@cryptsoft.com). + * + */ + +/* NOTE: this file was auto generated by the mkerr.pl script: any changes + * made to it will be overwritten when the script next updates this file, + * only reason strings will be preserved. + */ + +#include +#include +#include "e_cswift_err.h" + +/* BEGIN ERROR CODES */ +#ifndef OPENSSL_NO_ERR + +#define ERR_FUNC(func) ERR_PACK(0,func,0) +#define ERR_REASON(reason) ERR_PACK(0,0,reason) + +static ERR_STRING_DATA CSWIFT_str_functs[]= + { +{ERR_FUNC(CSWIFT_F_CSWIFT_CTRL), "CSWIFT_CTRL"}, +{ERR_FUNC(CSWIFT_F_CSWIFT_DSA_SIGN), "CSWIFT_DSA_SIGN"}, +{ERR_FUNC(CSWIFT_F_CSWIFT_DSA_VERIFY), "CSWIFT_DSA_VERIFY"}, +{ERR_FUNC(CSWIFT_F_CSWIFT_FINISH), "CSWIFT_FINISH"}, +{ERR_FUNC(CSWIFT_F_CSWIFT_INIT), "CSWIFT_INIT"}, +{ERR_FUNC(CSWIFT_F_CSWIFT_MOD_EXP), "CSWIFT_MOD_EXP"}, +{ERR_FUNC(CSWIFT_F_CSWIFT_MOD_EXP_CRT), "CSWIFT_MOD_EXP_CRT"}, +{ERR_FUNC(CSWIFT_F_CSWIFT_RAND_BYTES), "CSWIFT_RAND_BYTES"}, +{ERR_FUNC(CSWIFT_F_CSWIFT_RSA_MOD_EXP), "CSWIFT_RSA_MOD_EXP"}, +{0,NULL} + }; + +static ERR_STRING_DATA CSWIFT_str_reasons[]= + { +{ERR_REASON(CSWIFT_R_ALREADY_LOADED) ,"already loaded"}, +{ERR_REASON(CSWIFT_R_BAD_KEY_SIZE) ,"bad key size"}, +{ERR_REASON(CSWIFT_R_BN_CTX_FULL) ,"bn ctx full"}, +{ERR_REASON(CSWIFT_R_BN_EXPAND_FAIL) ,"bn expand fail"}, +{ERR_REASON(CSWIFT_R_CTRL_COMMAND_NOT_IMPLEMENTED),"ctrl command not implemented"}, +{ERR_REASON(CSWIFT_R_MISSING_KEY_COMPONENTS),"missing key components"}, +{ERR_REASON(CSWIFT_R_NOT_LOADED) ,"not loaded"}, +{ERR_REASON(CSWIFT_R_REQUEST_FAILED) ,"request failed"}, +{ERR_REASON(CSWIFT_R_UNIT_FAILURE) ,"unit failure"}, +{0,NULL} + }; + +#endif + +#ifdef CSWIFT_LIB_NAME +static ERR_STRING_DATA CSWIFT_lib_name[]= + { +{0 ,CSWIFT_LIB_NAME}, +{0,NULL} + }; +#endif + + +static int CSWIFT_lib_error_code=0; +static int CSWIFT_error_init=1; + +static void ERR_load_CSWIFT_strings(void) + { + if (CSWIFT_lib_error_code == 0) + CSWIFT_lib_error_code=ERR_get_next_error_library(); + + if (CSWIFT_error_init) + { + CSWIFT_error_init=0; +#ifndef OPENSSL_NO_ERR + ERR_load_strings(CSWIFT_lib_error_code,CSWIFT_str_functs); + ERR_load_strings(CSWIFT_lib_error_code,CSWIFT_str_reasons); +#endif + +#ifdef CSWIFT_LIB_NAME + CSWIFT_lib_name->error = ERR_PACK(CSWIFT_lib_error_code,0,0); + ERR_load_strings(0,CSWIFT_lib_name); +#endif + } + } + +static void ERR_unload_CSWIFT_strings(void) + { + if (CSWIFT_error_init == 0) + { +#ifndef OPENSSL_NO_ERR + ERR_unload_strings(CSWIFT_lib_error_code,CSWIFT_str_functs); + ERR_unload_strings(CSWIFT_lib_error_code,CSWIFT_str_reasons); +#endif + +#ifdef CSWIFT_LIB_NAME + ERR_unload_strings(0,CSWIFT_lib_name); +#endif + CSWIFT_error_init=1; + } + } + +static void ERR_CSWIFT_error(int function, int reason, char *file, int line) + { + if (CSWIFT_lib_error_code == 0) + CSWIFT_lib_error_code=ERR_get_next_error_library(); + ERR_PUT_error(CSWIFT_lib_error_code,function,reason,file,line); + } diff --git a/node-v0.8.14/deps/openssl/openssl/engines/e_cswift_err.h b/node-v0.8.14/deps/openssl/openssl/engines/e_cswift_err.h new file mode 100644 index 0000000..69c2a9f --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/engines/e_cswift_err.h @@ -0,0 +1,98 @@ +/* ==================================================================== + * Copyright (c) 2001 The OpenSSL Project. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. All advertising materials mentioning features or use of this + * software must display the following acknowledgment: + * "This product includes software developed by the OpenSSL Project + * for use in the OpenSSL Toolkit. (http://www.openssl.org/)" + * + * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to + * endorse or promote products derived from this software without + * prior written permission. For written permission, please contact + * openssl-core@openssl.org. + * + * 5. Products derived from this software may not be called "OpenSSL" + * nor may "OpenSSL" appear in their names without prior written + * permission of the OpenSSL Project. + * + * 6. Redistributions of any form whatsoever must retain the following + * acknowledgment: + * "This product includes software developed by the OpenSSL Project + * for use in the OpenSSL Toolkit (http://www.openssl.org/)" + * + * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY + * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR + * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, + * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * ==================================================================== + * + * This product includes cryptographic software written by Eric Young + * (eay@cryptsoft.com). This product includes software written by Tim + * Hudson (tjh@cryptsoft.com). + * + */ + +#ifndef HEADER_CSWIFT_ERR_H +#define HEADER_CSWIFT_ERR_H + +#ifdef __cplusplus +extern "C" { +#endif + +/* BEGIN ERROR CODES */ +/* The following lines are auto generated by the script mkerr.pl. Any changes + * made after this point may be overwritten when the script is next run. + */ +static void ERR_load_CSWIFT_strings(void); +static void ERR_unload_CSWIFT_strings(void); +static void ERR_CSWIFT_error(int function, int reason, char *file, int line); +#define CSWIFTerr(f,r) ERR_CSWIFT_error((f),(r),__FILE__,__LINE__) + +/* Error codes for the CSWIFT functions. */ + +/* Function codes. */ +#define CSWIFT_F_CSWIFT_CTRL 100 +#define CSWIFT_F_CSWIFT_DSA_SIGN 101 +#define CSWIFT_F_CSWIFT_DSA_VERIFY 102 +#define CSWIFT_F_CSWIFT_FINISH 103 +#define CSWIFT_F_CSWIFT_INIT 104 +#define CSWIFT_F_CSWIFT_MOD_EXP 105 +#define CSWIFT_F_CSWIFT_MOD_EXP_CRT 106 +#define CSWIFT_F_CSWIFT_RAND_BYTES 108 +#define CSWIFT_F_CSWIFT_RSA_MOD_EXP 107 + +/* Reason codes. */ +#define CSWIFT_R_ALREADY_LOADED 100 +#define CSWIFT_R_BAD_KEY_SIZE 101 +#define CSWIFT_R_BN_CTX_FULL 102 +#define CSWIFT_R_BN_EXPAND_FAIL 103 +#define CSWIFT_R_CTRL_COMMAND_NOT_IMPLEMENTED 104 +#define CSWIFT_R_MISSING_KEY_COMPONENTS 105 +#define CSWIFT_R_NOT_LOADED 106 +#define CSWIFT_R_REQUEST_FAILED 107 +#define CSWIFT_R_UNIT_FAILURE 108 + +#ifdef __cplusplus +} +#endif +#endif diff --git a/node-v0.8.14/deps/openssl/openssl/engines/e_gmp.c b/node-v0.8.14/deps/openssl/openssl/engines/e_gmp.c new file mode 100644 index 0000000..a3d4715 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/engines/e_gmp.c @@ -0,0 +1,480 @@ +/* crypto/engine/e_gmp.c */ +/* Written by Geoff Thorpe (geoff@geoffthorpe.net) for the OpenSSL + * project 2003. + */ +/* ==================================================================== + * Copyright (c) 1999-2001 The OpenSSL Project. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. All advertising materials mentioning features or use of this + * software must display the following acknowledgment: + * "This product includes software developed by the OpenSSL Project + * for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)" + * + * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to + * endorse or promote products derived from this software without + * prior written permission. For written permission, please contact + * licensing@OpenSSL.org. + * + * 5. Products derived from this software may not be called "OpenSSL" + * nor may "OpenSSL" appear in their names without prior written + * permission of the OpenSSL Project. + * + * 6. Redistributions of any form whatsoever must retain the following + * acknowledgment: + * "This product includes software developed by the OpenSSL Project + * for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)" + * + * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY + * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR + * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, + * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * ==================================================================== + * + * This product includes cryptographic software written by Eric Young + * (eay@cryptsoft.com). This product includes software written by Tim + * Hudson (tjh@cryptsoft.com). + * + */ + +/* This engine is not (currently) compiled in by default. Do enable it, + * reconfigure OpenSSL with "enable-gmp -lgmp". The GMP libraries and + * headers must reside in one of the paths searched by the compiler/linker, + * otherwise paths must be specified - eg. try configuring with + * "enable-gmp -I -L -lgmp". YMMV. */ + +/* As for what this does - it's a largely unoptimised implementation of an + * ENGINE that uses the GMP library to perform RSA private key operations. To + * obtain more information about what "unoptimised" means, see my original mail + * on the subject (though ignore the build instructions which have since + * changed); + * + * http://www.mail-archive.com/openssl-dev@openssl.org/msg12227.html + * + * On my athlon system at least, it appears the builtin OpenSSL code is now + * slightly faster, which is to say that the RSA-related MPI performance + * between OpenSSL's BIGNUM and GMP's mpz implementations is probably pretty + * balanced for this chip, and so the performance degradation in this ENGINE by + * having to convert to/from GMP formats (and not being able to cache + * montgomery forms) is probably the difference. However, if some unconfirmed + * reports from users is anything to go by, the situation on some other + * chipsets might be a good deal more favourable to the GMP version (eg. PPC). + * Feedback welcome. */ + +#include +#include +#include +#include +#include +#ifndef OPENSSL_NO_RSA +#include +#endif +#include + +#ifndef OPENSSL_NO_HW +#ifndef OPENSSL_NO_GMP + +#include + +#define E_GMP_LIB_NAME "gmp engine" +#include "e_gmp_err.c" + +static int e_gmp_destroy(ENGINE *e); +static int e_gmp_init(ENGINE *e); +static int e_gmp_finish(ENGINE *e); +static int e_gmp_ctrl(ENGINE *e, int cmd, long i, void *p, void (*f)(void)); + +#ifndef OPENSSL_NO_RSA +/* RSA stuff */ +static int e_gmp_rsa_mod_exp(BIGNUM *r, const BIGNUM *I, RSA *rsa, BN_CTX *ctx); +static int e_gmp_rsa_finish(RSA *r); +#endif + +/* The definitions for control commands specific to this engine */ +/* #define E_GMP_CMD_SO_PATH ENGINE_CMD_BASE */ +static const ENGINE_CMD_DEFN e_gmp_cmd_defns[] = { +#if 0 + {E_GMP_CMD_SO_PATH, + "SO_PATH", + "Specifies the path to the 'e_gmp' shared library", + ENGINE_CMD_FLAG_STRING}, +#endif + {0, NULL, NULL, 0} + }; + +#ifndef OPENSSL_NO_RSA +/* Our internal RSA_METHOD that we provide pointers to */ +static RSA_METHOD e_gmp_rsa = + { + "GMP RSA method", + NULL, + NULL, + NULL, + NULL, + e_gmp_rsa_mod_exp, + NULL, + NULL, + e_gmp_rsa_finish, + /* These flags initialise montgomery crud that GMP ignores, however it + * makes sure the public key ops (which are done in openssl) don't seem + * *slower* than usual :-) */ + RSA_FLAG_CACHE_PUBLIC|RSA_FLAG_CACHE_PRIVATE, + NULL, + NULL, + NULL + }; +#endif + +/* Constants used when creating the ENGINE */ +static const char *engine_e_gmp_id = "gmp"; +static const char *engine_e_gmp_name = "GMP engine support"; + +/* This internal function is used by ENGINE_gmp() and possibly by the + * "dynamic" ENGINE support too */ +static int bind_helper(ENGINE *e) + { +#ifndef OPENSSL_NO_RSA + const RSA_METHOD *meth1; +#endif + if(!ENGINE_set_id(e, engine_e_gmp_id) || + !ENGINE_set_name(e, engine_e_gmp_name) || +#ifndef OPENSSL_NO_RSA + !ENGINE_set_RSA(e, &e_gmp_rsa) || +#endif + !ENGINE_set_destroy_function(e, e_gmp_destroy) || + !ENGINE_set_init_function(e, e_gmp_init) || + !ENGINE_set_finish_function(e, e_gmp_finish) || + !ENGINE_set_ctrl_function(e, e_gmp_ctrl) || + !ENGINE_set_cmd_defns(e, e_gmp_cmd_defns)) + return 0; + +#ifndef OPENSSL_NO_RSA + meth1 = RSA_PKCS1_SSLeay(); + e_gmp_rsa.rsa_pub_enc = meth1->rsa_pub_enc; + e_gmp_rsa.rsa_pub_dec = meth1->rsa_pub_dec; + e_gmp_rsa.rsa_priv_enc = meth1->rsa_priv_enc; + e_gmp_rsa.rsa_priv_dec = meth1->rsa_priv_dec; + e_gmp_rsa.bn_mod_exp = meth1->bn_mod_exp; +#endif + + /* Ensure the e_gmp error handling is set up */ + ERR_load_GMP_strings(); + return 1; + } + +static ENGINE *engine_gmp(void) + { + ENGINE *ret = ENGINE_new(); + if(!ret) + return NULL; + if(!bind_helper(ret)) + { + ENGINE_free(ret); + return NULL; + } + return ret; + } + +void ENGINE_load_gmp(void) + { + /* Copied from eng_[openssl|dyn].c */ + ENGINE *toadd = engine_gmp(); + if(!toadd) return; + ENGINE_add(toadd); + ENGINE_free(toadd); + ERR_clear_error(); + } + +#ifndef OPENSSL_NO_RSA +/* Used to attach our own key-data to an RSA structure */ +static int hndidx_rsa = -1; +#endif + +static int e_gmp_destroy(ENGINE *e) + { + ERR_unload_GMP_strings(); + return 1; + } + +/* (de)initialisation functions. */ +static int e_gmp_init(ENGINE *e) + { +#ifndef OPENSSL_NO_RSA + if (hndidx_rsa == -1) + hndidx_rsa = RSA_get_ex_new_index(0, + "GMP-based RSA key handle", + NULL, NULL, NULL); +#endif + if (hndidx_rsa == -1) + return 0; + return 1; + } + +static int e_gmp_finish(ENGINE *e) + { + return 1; + } + +static int e_gmp_ctrl(ENGINE *e, int cmd, long i, void *p, void (*f)(void)) + { + int to_return = 1; + + switch(cmd) + { +#if 0 + case E_GMP_CMD_SO_PATH: + /* ... */ +#endif + /* The command isn't understood by this engine */ + default: + GMPerr(GMP_F_E_GMP_CTRL, + GMP_R_CTRL_COMMAND_NOT_IMPLEMENTED); + to_return = 0; + break; + } + + return to_return; + } + + +/* Most often limb sizes will be the same. If not, we use hex conversion + * which is neat, but extremely inefficient. */ +static int bn2gmp(const BIGNUM *bn, mpz_t g) + { + bn_check_top(bn); + if(((sizeof(bn->d[0]) * 8) == GMP_NUMB_BITS) && + (BN_BITS2 == GMP_NUMB_BITS)) + { + /* The common case */ + if(!_mpz_realloc (g, bn->top)) + return 0; + memcpy(&g->_mp_d[0], &bn->d[0], bn->top * sizeof(bn->d[0])); + g->_mp_size = bn->top; + if(bn->neg) + g->_mp_size = -g->_mp_size; + return 1; + } + else + { + int toret; + char *tmpchar = BN_bn2hex(bn); + if(!tmpchar) return 0; + toret = (mpz_set_str(g, tmpchar, 16) == 0 ? 1 : 0); + OPENSSL_free(tmpchar); + return toret; + } + } + +static int gmp2bn(mpz_t g, BIGNUM *bn) + { + if(((sizeof(bn->d[0]) * 8) == GMP_NUMB_BITS) && + (BN_BITS2 == GMP_NUMB_BITS)) + { + /* The common case */ + int s = (g->_mp_size >= 0) ? g->_mp_size : -g->_mp_size; + BN_zero(bn); + if(bn_expand2 (bn, s) == NULL) + return 0; + bn->top = s; + memcpy(&bn->d[0], &g->_mp_d[0], s * sizeof(bn->d[0])); + bn_correct_top(bn); + bn->neg = g->_mp_size >= 0 ? 0 : 1; + return 1; + } + else + { + int toret; + char *tmpchar = OPENSSL_malloc(mpz_sizeinbase(g, 16) + 10); + if(!tmpchar) return 0; + mpz_get_str(tmpchar, 16, g); + toret = BN_hex2bn(&bn, tmpchar); + OPENSSL_free(tmpchar); + return toret; + } + } + +#ifndef OPENSSL_NO_RSA +typedef struct st_e_gmp_rsa_ctx + { + int public_only; + mpz_t n; + mpz_t d; + mpz_t e; + mpz_t p; + mpz_t q; + mpz_t dmp1; + mpz_t dmq1; + mpz_t iqmp; + mpz_t r0, r1, I0, m1; + } E_GMP_RSA_CTX; + +static E_GMP_RSA_CTX *e_gmp_get_rsa(RSA *rsa) + { + E_GMP_RSA_CTX *hptr = RSA_get_ex_data(rsa, hndidx_rsa); + if(hptr) return hptr; + hptr = OPENSSL_malloc(sizeof(E_GMP_RSA_CTX)); + if(!hptr) return NULL; + /* These inits could probably be replaced by more intelligent + * mpz_init2() versions, to reduce malloc-thrashing. */ + mpz_init(hptr->n); + mpz_init(hptr->d); + mpz_init(hptr->e); + mpz_init(hptr->p); + mpz_init(hptr->q); + mpz_init(hptr->dmp1); + mpz_init(hptr->dmq1); + mpz_init(hptr->iqmp); + mpz_init(hptr->r0); + mpz_init(hptr->r1); + mpz_init(hptr->I0); + mpz_init(hptr->m1); + if(!bn2gmp(rsa->n, hptr->n) || !bn2gmp(rsa->e, hptr->e)) + goto err; + if(!rsa->p || !rsa->q || !rsa->d || !rsa->dmp1 || !rsa->dmq1 || !rsa->iqmp) + { + hptr->public_only = 1; + return hptr; + } + if(!bn2gmp(rsa->d, hptr->d) || !bn2gmp(rsa->p, hptr->p) || + !bn2gmp(rsa->q, hptr->q) || !bn2gmp(rsa->dmp1, hptr->dmp1) || + !bn2gmp(rsa->dmq1, hptr->dmq1) || !bn2gmp(rsa->iqmp, hptr->iqmp)) + goto err; + hptr->public_only = 0; + RSA_set_ex_data(rsa, hndidx_rsa, hptr); + return hptr; +err: + mpz_clear(hptr->n); + mpz_clear(hptr->d); + mpz_clear(hptr->e); + mpz_clear(hptr->p); + mpz_clear(hptr->q); + mpz_clear(hptr->dmp1); + mpz_clear(hptr->dmq1); + mpz_clear(hptr->iqmp); + mpz_clear(hptr->r0); + mpz_clear(hptr->r1); + mpz_clear(hptr->I0); + mpz_clear(hptr->m1); + OPENSSL_free(hptr); + return NULL; + } + +static int e_gmp_rsa_finish(RSA *rsa) + { + E_GMP_RSA_CTX *hptr = RSA_get_ex_data(rsa, hndidx_rsa); + if(!hptr) return 0; + mpz_clear(hptr->n); + mpz_clear(hptr->d); + mpz_clear(hptr->e); + mpz_clear(hptr->p); + mpz_clear(hptr->q); + mpz_clear(hptr->dmp1); + mpz_clear(hptr->dmq1); + mpz_clear(hptr->iqmp); + mpz_clear(hptr->r0); + mpz_clear(hptr->r1); + mpz_clear(hptr->I0); + mpz_clear(hptr->m1); + OPENSSL_free(hptr); + RSA_set_ex_data(rsa, hndidx_rsa, NULL); + return 1; + } + +static int e_gmp_rsa_mod_exp(BIGNUM *r, const BIGNUM *I, RSA *rsa, BN_CTX *ctx) + { + E_GMP_RSA_CTX *hptr; + int to_return = 0; + + hptr = e_gmp_get_rsa(rsa); + if(!hptr) + { + GMPerr(GMP_F_E_GMP_RSA_MOD_EXP, + GMP_R_KEY_CONTEXT_ERROR); + return 0; + } + if(hptr->public_only) + { + GMPerr(GMP_F_E_GMP_RSA_MOD_EXP, + GMP_R_MISSING_KEY_COMPONENTS); + return 0; + } + + /* ugh!!! */ + if(!bn2gmp(I, hptr->I0)) + return 0; + + /* This is basically the CRT logic in crypto/rsa/rsa_eay.c reworded into + * GMP-speak. It may be that GMP's API facilitates cleaner formulations + * of this stuff, eg. better handling of negatives, or functions that + * combine operations. */ + + mpz_mod(hptr->r1, hptr->I0, hptr->q); + mpz_powm(hptr->m1, hptr->r1, hptr->dmq1, hptr->q); + + mpz_mod(hptr->r1, hptr->I0, hptr->p); + mpz_powm(hptr->r0, hptr->r1, hptr->dmp1, hptr->p); + + mpz_sub(hptr->r0, hptr->r0, hptr->m1); + + if(mpz_sgn(hptr->r0) < 0) + mpz_add(hptr->r0, hptr->r0, hptr->p); + mpz_mul(hptr->r1, hptr->r0, hptr->iqmp); + mpz_mod(hptr->r0, hptr->r1, hptr->p); + + if(mpz_sgn(hptr->r0) < 0) + mpz_add(hptr->r0, hptr->r0, hptr->p); + mpz_mul(hptr->r1, hptr->r0, hptr->q); + mpz_add(hptr->r0, hptr->r1, hptr->m1); + + /* ugh!!! */ + if(gmp2bn(hptr->r0, r)) + to_return = 1; + + return 1; + } +#endif + +#endif /* !OPENSSL_NO_GMP */ + +/* This stuff is needed if this ENGINE is being compiled into a self-contained + * shared-library. */ +#ifndef OPENSSL_NO_DYNAMIC_ENGINE +IMPLEMENT_DYNAMIC_CHECK_FN() +#ifndef OPENSSL_NO_GMP +static int bind_fn(ENGINE *e, const char *id) + { + if(id && (strcmp(id, engine_e_gmp_id) != 0)) + return 0; + if(!bind_helper(e)) + return 0; + return 1; + } +IMPLEMENT_DYNAMIC_BIND_FN(bind_fn) +#else +OPENSSL_EXPORT +int bind_engine(ENGINE *e, const char *id, const dynamic_fns *fns); +OPENSSL_EXPORT +int bind_engine(ENGINE *e, const char *id, const dynamic_fns *fns) { return 0; } +#endif +#endif /* !OPENSSL_NO_DYNAMIC_ENGINE */ + +#endif /* !OPENSSL_NO_HW */ diff --git a/node-v0.8.14/deps/openssl/openssl/engines/e_gmp.ec b/node-v0.8.14/deps/openssl/openssl/engines/e_gmp.ec new file mode 100644 index 0000000..72ec447 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/engines/e_gmp.ec @@ -0,0 +1 @@ +L GMP e_gmp_err.h e_gmp_err.c diff --git a/node-v0.8.14/deps/openssl/openssl/engines/e_gmp_err.c b/node-v0.8.14/deps/openssl/openssl/engines/e_gmp_err.c new file mode 100644 index 0000000..61db956 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/engines/e_gmp_err.c @@ -0,0 +1,141 @@ +/* e_gmp_err.c */ +/* ==================================================================== + * Copyright (c) 1999-2005 The OpenSSL Project. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. All advertising materials mentioning features or use of this + * software must display the following acknowledgment: + * "This product includes software developed by the OpenSSL Project + * for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)" + * + * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to + * endorse or promote products derived from this software without + * prior written permission. For written permission, please contact + * openssl-core@OpenSSL.org. + * + * 5. Products derived from this software may not be called "OpenSSL" + * nor may "OpenSSL" appear in their names without prior written + * permission of the OpenSSL Project. + * + * 6. Redistributions of any form whatsoever must retain the following + * acknowledgment: + * "This product includes software developed by the OpenSSL Project + * for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)" + * + * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY + * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR + * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, + * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * ==================================================================== + * + * This product includes cryptographic software written by Eric Young + * (eay@cryptsoft.com). This product includes software written by Tim + * Hudson (tjh@cryptsoft.com). + * + */ + +/* NOTE: this file was auto generated by the mkerr.pl script: any changes + * made to it will be overwritten when the script next updates this file, + * only reason strings will be preserved. + */ + +#include +#include +#include "e_gmp_err.h" + +/* BEGIN ERROR CODES */ +#ifndef OPENSSL_NO_ERR + +#define ERR_FUNC(func) ERR_PACK(0,func,0) +#define ERR_REASON(reason) ERR_PACK(0,0,reason) + +static ERR_STRING_DATA GMP_str_functs[]= + { +{ERR_FUNC(GMP_F_E_GMP_CTRL), "E_GMP_CTRL"}, +{ERR_FUNC(GMP_F_E_GMP_RSA_MOD_EXP), "E_GMP_RSA_MOD_EXP"}, +{0,NULL} + }; + +static ERR_STRING_DATA GMP_str_reasons[]= + { +{ERR_REASON(GMP_R_CTRL_COMMAND_NOT_IMPLEMENTED),"ctrl command not implemented"}, +{ERR_REASON(GMP_R_KEY_CONTEXT_ERROR) ,"key context error"}, +{ERR_REASON(GMP_R_MISSING_KEY_COMPONENTS),"missing key components"}, +{0,NULL} + }; + +#endif + +#ifdef GMP_LIB_NAME +static ERR_STRING_DATA GMP_lib_name[]= + { +{0 ,GMP_LIB_NAME}, +{0,NULL} + }; +#endif + + +static int GMP_lib_error_code=0; +static int GMP_error_init=1; + +static void ERR_load_GMP_strings(void) + { + if (GMP_lib_error_code == 0) + GMP_lib_error_code=ERR_get_next_error_library(); + + if (GMP_error_init) + { + GMP_error_init=0; +#ifndef OPENSSL_NO_ERR + ERR_load_strings(GMP_lib_error_code,GMP_str_functs); + ERR_load_strings(GMP_lib_error_code,GMP_str_reasons); +#endif + +#ifdef GMP_LIB_NAME + GMP_lib_name->error = ERR_PACK(GMP_lib_error_code,0,0); + ERR_load_strings(0,GMP_lib_name); +#endif + } + } + +static void ERR_unload_GMP_strings(void) + { + if (GMP_error_init == 0) + { +#ifndef OPENSSL_NO_ERR + ERR_unload_strings(GMP_lib_error_code,GMP_str_functs); + ERR_unload_strings(GMP_lib_error_code,GMP_str_reasons); +#endif + +#ifdef GMP_LIB_NAME + ERR_unload_strings(0,GMP_lib_name); +#endif + GMP_error_init=1; + } + } + +static void ERR_GMP_error(int function, int reason, char *file, int line) + { + if (GMP_lib_error_code == 0) + GMP_lib_error_code=ERR_get_next_error_library(); + ERR_PUT_error(GMP_lib_error_code,function,reason,file,line); + } diff --git a/node-v0.8.14/deps/openssl/openssl/engines/e_gmp_err.h b/node-v0.8.14/deps/openssl/openssl/engines/e_gmp_err.h new file mode 100644 index 0000000..dd05dfd --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/engines/e_gmp_err.h @@ -0,0 +1,85 @@ +/* ==================================================================== + * Copyright (c) 2001-2002 The OpenSSL Project. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. All advertising materials mentioning features or use of this + * software must display the following acknowledgment: + * "This product includes software developed by the OpenSSL Project + * for use in the OpenSSL Toolkit. (http://www.openssl.org/)" + * + * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to + * endorse or promote products derived from this software without + * prior written permission. For written permission, please contact + * openssl-core@openssl.org. + * + * 5. Products derived from this software may not be called "OpenSSL" + * nor may "OpenSSL" appear in their names without prior written + * permission of the OpenSSL Project. + * + * 6. Redistributions of any form whatsoever must retain the following + * acknowledgment: + * "This product includes software developed by the OpenSSL Project + * for use in the OpenSSL Toolkit (http://www.openssl.org/)" + * + * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY + * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR + * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, + * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * ==================================================================== + * + * This product includes cryptographic software written by Eric Young + * (eay@cryptsoft.com). This product includes software written by Tim + * Hudson (tjh@cryptsoft.com). + * + */ + +#ifndef HEADER_GMP_ERR_H +#define HEADER_GMP_ERR_H + +#ifdef __cplusplus +extern "C" { +#endif + +/* BEGIN ERROR CODES */ +/* The following lines are auto generated by the script mkerr.pl. Any changes + * made after this point may be overwritten when the script is next run. + */ +static void ERR_load_GMP_strings(void); +static void ERR_unload_GMP_strings(void); +static void ERR_GMP_error(int function, int reason, char *file, int line); +#define GMPerr(f,r) ERR_GMP_error((f),(r),__FILE__,__LINE__) + +/* Error codes for the GMP functions. */ + +/* Function codes. */ +#define GMP_F_E_GMP_CTRL 100 +#define GMP_F_E_GMP_RSA_MOD_EXP 101 + +/* Reason codes. */ +#define GMP_R_CTRL_COMMAND_NOT_IMPLEMENTED 100 +#define GMP_R_KEY_CONTEXT_ERROR 101 +#define GMP_R_MISSING_KEY_COMPONENTS 102 + +#ifdef __cplusplus +} +#endif +#endif diff --git a/node-v0.8.14/deps/openssl/openssl/engines/e_nuron.c b/node-v0.8.14/deps/openssl/openssl/engines/e_nuron.c new file mode 100644 index 0000000..4c2537c --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/engines/e_nuron.c @@ -0,0 +1,434 @@ +/* crypto/engine/hw_nuron.c */ +/* Written by Ben Laurie for the OpenSSL Project, leaning heavily on Geoff + * Thorpe's Atalla implementation. + */ +/* ==================================================================== + * Copyright (c) 2000-2001 The OpenSSL Project. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. All advertising materials mentioning features or use of this + * software must display the following acknowledgment: + * "This product includes software developed by the OpenSSL Project + * for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)" + * + * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to + * endorse or promote products derived from this software without + * prior written permission. For written permission, please contact + * licensing@OpenSSL.org. + * + * 5. Products derived from this software may not be called "OpenSSL" + * nor may "OpenSSL" appear in their names without prior written + * permission of the OpenSSL Project. + * + * 6. Redistributions of any form whatsoever must retain the following + * acknowledgment: + * "This product includes software developed by the OpenSSL Project + * for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)" + * + * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY + * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR + * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, + * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * ==================================================================== + * + * This product includes cryptographic software written by Eric Young + * (eay@cryptsoft.com). This product includes software written by Tim + * Hudson (tjh@cryptsoft.com). + * + */ + +#include +#include +#include +#include +#include +#include +#ifndef OPENSSL_NO_RSA +#include +#endif +#ifndef OPENSSL_NO_DSA +#include +#endif +#ifndef OPENSSL_NO_DH +#include +#endif +#include + +#ifndef OPENSSL_NO_HW +#ifndef OPENSSL_NO_HW_NURON + +#define NURON_LIB_NAME "nuron engine" +#include "e_nuron_err.c" + +static const char *NURON_LIBNAME = NULL; +static const char *get_NURON_LIBNAME(void) + { + if(NURON_LIBNAME) + return NURON_LIBNAME; + return "nuronssl"; + } +static void free_NURON_LIBNAME(void) + { + if(NURON_LIBNAME) + OPENSSL_free((void*)NURON_LIBNAME); + NURON_LIBNAME = NULL; + } +static long set_NURON_LIBNAME(const char *name) + { + free_NURON_LIBNAME(); + return (((NURON_LIBNAME = BUF_strdup(name)) != NULL) ? 1 : 0); + } +static const char *NURON_F1 = "nuron_mod_exp"; + +/* The definitions for control commands specific to this engine */ +#define NURON_CMD_SO_PATH ENGINE_CMD_BASE +static const ENGINE_CMD_DEFN nuron_cmd_defns[] = { + {NURON_CMD_SO_PATH, + "SO_PATH", + "Specifies the path to the 'nuronssl' shared library", + ENGINE_CMD_FLAG_STRING}, + {0, NULL, NULL, 0} + }; + +typedef int tfnModExp(BIGNUM *r,const BIGNUM *a,const BIGNUM *p,const BIGNUM *m); +static tfnModExp *pfnModExp = NULL; + +static DSO *pvDSOHandle = NULL; + +static int nuron_destroy(ENGINE *e) + { + free_NURON_LIBNAME(); + ERR_unload_NURON_strings(); + return 1; + } + +static int nuron_init(ENGINE *e) + { + if(pvDSOHandle != NULL) + { + NURONerr(NURON_F_NURON_INIT,NURON_R_ALREADY_LOADED); + return 0; + } + + pvDSOHandle = DSO_load(NULL, get_NURON_LIBNAME(), NULL, + DSO_FLAG_NAME_TRANSLATION_EXT_ONLY); + if(!pvDSOHandle) + { + NURONerr(NURON_F_NURON_INIT,NURON_R_DSO_NOT_FOUND); + return 0; + } + + pfnModExp = (tfnModExp *)DSO_bind_func(pvDSOHandle, NURON_F1); + if(!pfnModExp) + { + NURONerr(NURON_F_NURON_INIT,NURON_R_DSO_FUNCTION_NOT_FOUND); + return 0; + } + + return 1; + } + +static int nuron_finish(ENGINE *e) + { + free_NURON_LIBNAME(); + if(pvDSOHandle == NULL) + { + NURONerr(NURON_F_NURON_FINISH,NURON_R_NOT_LOADED); + return 0; + } + if(!DSO_free(pvDSOHandle)) + { + NURONerr(NURON_F_NURON_FINISH,NURON_R_DSO_FAILURE); + return 0; + } + pvDSOHandle=NULL; + pfnModExp=NULL; + return 1; + } + +static int nuron_ctrl(ENGINE *e, int cmd, long i, void *p, void (*f)(void)) + { + int initialised = ((pvDSOHandle == NULL) ? 0 : 1); + switch(cmd) + { + case NURON_CMD_SO_PATH: + if(p == NULL) + { + NURONerr(NURON_F_NURON_CTRL,ERR_R_PASSED_NULL_PARAMETER); + return 0; + } + if(initialised) + { + NURONerr(NURON_F_NURON_CTRL,NURON_R_ALREADY_LOADED); + return 0; + } + return set_NURON_LIBNAME((const char *)p); + default: + break; + } + NURONerr(NURON_F_NURON_CTRL,NURON_R_CTRL_COMMAND_NOT_IMPLEMENTED); + return 0; +} + +static int nuron_mod_exp(BIGNUM *r,const BIGNUM *a,const BIGNUM *p, + const BIGNUM *m,BN_CTX *ctx) + { + if(!pvDSOHandle) + { + NURONerr(NURON_F_NURON_MOD_EXP,NURON_R_NOT_LOADED); + return 0; + } + return pfnModExp(r,a,p,m); + } + +#ifndef OPENSSL_NO_RSA +static int nuron_rsa_mod_exp(BIGNUM *r0, const BIGNUM *I, RSA *rsa, BN_CTX *ctx) + { + return nuron_mod_exp(r0,I,rsa->d,rsa->n,ctx); + } +#endif + +#ifndef OPENSSL_NO_DSA +/* This code was liberated and adapted from the commented-out code in + * dsa_ossl.c. Because of the unoptimised form of the Atalla acceleration + * (it doesn't have a CRT form for RSA), this function means that an + * Atalla system running with a DSA server certificate can handshake + * around 5 or 6 times faster/more than an equivalent system running with + * RSA. Just check out the "signs" statistics from the RSA and DSA parts + * of "openssl speed -engine atalla dsa1024 rsa1024". */ +static int nuron_dsa_mod_exp(DSA *dsa, BIGNUM *rr, BIGNUM *a1, + BIGNUM *p1, BIGNUM *a2, BIGNUM *p2, BIGNUM *m, + BN_CTX *ctx, BN_MONT_CTX *in_mont) + { + BIGNUM t; + int to_return = 0; + + BN_init(&t); + /* let rr = a1 ^ p1 mod m */ + if (!nuron_mod_exp(rr,a1,p1,m,ctx)) + goto end; + /* let t = a2 ^ p2 mod m */ + if (!nuron_mod_exp(&t,a2,p2,m,ctx)) + goto end; + /* let rr = rr * t mod m */ + if (!BN_mod_mul(rr,rr,&t,m,ctx)) + goto end; + to_return = 1; +end: + BN_free(&t); + return to_return; + } + + +static int nuron_mod_exp_dsa(DSA *dsa, BIGNUM *r, BIGNUM *a, + const BIGNUM *p, const BIGNUM *m, BN_CTX *ctx, + BN_MONT_CTX *m_ctx) + { + return nuron_mod_exp(r, a, p, m, ctx); + } +#endif + +/* This function is aliased to mod_exp (with the mont stuff dropped). */ +#ifndef OPENSSL_NO_RSA +static int nuron_mod_exp_mont(BIGNUM *r, const BIGNUM *a, const BIGNUM *p, + const BIGNUM *m, BN_CTX *ctx, BN_MONT_CTX *m_ctx) + { + return nuron_mod_exp(r, a, p, m, ctx); + } +#endif + +#ifndef OPENSSL_NO_DH +/* This function is aliased to mod_exp (with the dh and mont dropped). */ +static int nuron_mod_exp_dh(const DH *dh, BIGNUM *r, + const BIGNUM *a, const BIGNUM *p, + const BIGNUM *m, BN_CTX *ctx, BN_MONT_CTX *m_ctx) + { + return nuron_mod_exp(r, a, p, m, ctx); + } +#endif + +#ifndef OPENSSL_NO_RSA +static RSA_METHOD nuron_rsa = + { + "Nuron RSA method", + NULL, + NULL, + NULL, + NULL, + nuron_rsa_mod_exp, + nuron_mod_exp_mont, + NULL, + NULL, + 0, + NULL, + NULL, + NULL, + NULL + }; +#endif + +#ifndef OPENSSL_NO_DSA +static DSA_METHOD nuron_dsa = + { + "Nuron DSA method", + NULL, /* dsa_do_sign */ + NULL, /* dsa_sign_setup */ + NULL, /* dsa_do_verify */ + nuron_dsa_mod_exp, /* dsa_mod_exp */ + nuron_mod_exp_dsa, /* bn_mod_exp */ + NULL, /* init */ + NULL, /* finish */ + 0, /* flags */ + NULL, /* app_data */ + NULL, /* dsa_paramgen */ + NULL /* dsa_keygen */ + }; +#endif + +#ifndef OPENSSL_NO_DH +static DH_METHOD nuron_dh = + { + "Nuron DH method", + NULL, + NULL, + nuron_mod_exp_dh, + NULL, + NULL, + 0, + NULL, + NULL + }; +#endif + +/* Constants used when creating the ENGINE */ +static const char *engine_nuron_id = "nuron"; +static const char *engine_nuron_name = "Nuron hardware engine support"; + +/* This internal function is used by ENGINE_nuron() and possibly by the + * "dynamic" ENGINE support too */ +static int bind_helper(ENGINE *e) + { +#ifndef OPENSSL_NO_RSA + const RSA_METHOD *meth1; +#endif +#ifndef OPENSSL_NO_DSA + const DSA_METHOD *meth2; +#endif +#ifndef OPENSSL_NO_DH + const DH_METHOD *meth3; +#endif + if(!ENGINE_set_id(e, engine_nuron_id) || + !ENGINE_set_name(e, engine_nuron_name) || +#ifndef OPENSSL_NO_RSA + !ENGINE_set_RSA(e, &nuron_rsa) || +#endif +#ifndef OPENSSL_NO_DSA + !ENGINE_set_DSA(e, &nuron_dsa) || +#endif +#ifndef OPENSSL_NO_DH + !ENGINE_set_DH(e, &nuron_dh) || +#endif + !ENGINE_set_destroy_function(e, nuron_destroy) || + !ENGINE_set_init_function(e, nuron_init) || + !ENGINE_set_finish_function(e, nuron_finish) || + !ENGINE_set_ctrl_function(e, nuron_ctrl) || + !ENGINE_set_cmd_defns(e, nuron_cmd_defns)) + return 0; + +#ifndef OPENSSL_NO_RSA + /* We know that the "PKCS1_SSLeay()" functions hook properly + * to the nuron-specific mod_exp and mod_exp_crt so we use + * those functions. NB: We don't use ENGINE_openssl() or + * anything "more generic" because something like the RSAref + * code may not hook properly, and if you own one of these + * cards then you have the right to do RSA operations on it + * anyway! */ + meth1=RSA_PKCS1_SSLeay(); + nuron_rsa.rsa_pub_enc=meth1->rsa_pub_enc; + nuron_rsa.rsa_pub_dec=meth1->rsa_pub_dec; + nuron_rsa.rsa_priv_enc=meth1->rsa_priv_enc; + nuron_rsa.rsa_priv_dec=meth1->rsa_priv_dec; +#endif + +#ifndef OPENSSL_NO_DSA + /* Use the DSA_OpenSSL() method and just hook the mod_exp-ish + * bits. */ + meth2=DSA_OpenSSL(); + nuron_dsa.dsa_do_sign=meth2->dsa_do_sign; + nuron_dsa.dsa_sign_setup=meth2->dsa_sign_setup; + nuron_dsa.dsa_do_verify=meth2->dsa_do_verify; +#endif + +#ifndef OPENSSL_NO_DH + /* Much the same for Diffie-Hellman */ + meth3=DH_OpenSSL(); + nuron_dh.generate_key=meth3->generate_key; + nuron_dh.compute_key=meth3->compute_key; +#endif + + /* Ensure the nuron error handling is set up */ + ERR_load_NURON_strings(); + return 1; + } + +#ifdef OPENSSL_NO_DYNAMIC_ENGINE +static ENGINE *engine_nuron(void) + { + ENGINE *ret = ENGINE_new(); + if(!ret) + return NULL; + if(!bind_helper(ret)) + { + ENGINE_free(ret); + return NULL; + } + return ret; + } + +void ENGINE_load_nuron(void) + { + /* Copied from eng_[openssl|dyn].c */ + ENGINE *toadd = engine_nuron(); + if(!toadd) return; + ENGINE_add(toadd); + ENGINE_free(toadd); + ERR_clear_error(); + } +#endif + +/* This stuff is needed if this ENGINE is being compiled into a self-contained + * shared-library. */ +#ifndef OPENSSL_NO_DYNAMIC_ENGINE +static int bind_fn(ENGINE *e, const char *id) + { + if(id && (strcmp(id, engine_nuron_id) != 0)) + return 0; + if(!bind_helper(e)) + return 0; + return 1; + } +IMPLEMENT_DYNAMIC_CHECK_FN() +IMPLEMENT_DYNAMIC_BIND_FN(bind_fn) +#endif /* OPENSSL_NO_DYNAMIC_ENGINE */ + +#endif /* !OPENSSL_NO_HW_NURON */ +#endif /* !OPENSSL_NO_HW */ diff --git a/node-v0.8.14/deps/openssl/openssl/engines/e_nuron.ec b/node-v0.8.14/deps/openssl/openssl/engines/e_nuron.ec new file mode 100644 index 0000000..cfa430d --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/engines/e_nuron.ec @@ -0,0 +1 @@ +L NURON e_nuron_err.h e_nuron_err.c diff --git a/node-v0.8.14/deps/openssl/openssl/engines/e_nuron_err.c b/node-v0.8.14/deps/openssl/openssl/engines/e_nuron_err.c new file mode 100644 index 0000000..9a7864f --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/engines/e_nuron_err.c @@ -0,0 +1,146 @@ +/* e_nuron_err.c */ +/* ==================================================================== + * Copyright (c) 1999-2005 The OpenSSL Project. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. All advertising materials mentioning features or use of this + * software must display the following acknowledgment: + * "This product includes software developed by the OpenSSL Project + * for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)" + * + * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to + * endorse or promote products derived from this software without + * prior written permission. For written permission, please contact + * openssl-core@OpenSSL.org. + * + * 5. Products derived from this software may not be called "OpenSSL" + * nor may "OpenSSL" appear in their names without prior written + * permission of the OpenSSL Project. + * + * 6. Redistributions of any form whatsoever must retain the following + * acknowledgment: + * "This product includes software developed by the OpenSSL Project + * for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)" + * + * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY + * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR + * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, + * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * ==================================================================== + * + * This product includes cryptographic software written by Eric Young + * (eay@cryptsoft.com). This product includes software written by Tim + * Hudson (tjh@cryptsoft.com). + * + */ + +/* NOTE: this file was auto generated by the mkerr.pl script: any changes + * made to it will be overwritten when the script next updates this file, + * only reason strings will be preserved. + */ + +#include +#include +#include "e_nuron_err.h" + +/* BEGIN ERROR CODES */ +#ifndef OPENSSL_NO_ERR + +#define ERR_FUNC(func) ERR_PACK(0,func,0) +#define ERR_REASON(reason) ERR_PACK(0,0,reason) + +static ERR_STRING_DATA NURON_str_functs[]= + { +{ERR_FUNC(NURON_F_NURON_CTRL), "NURON_CTRL"}, +{ERR_FUNC(NURON_F_NURON_FINISH), "NURON_FINISH"}, +{ERR_FUNC(NURON_F_NURON_INIT), "NURON_INIT"}, +{ERR_FUNC(NURON_F_NURON_MOD_EXP), "NURON_MOD_EXP"}, +{0,NULL} + }; + +static ERR_STRING_DATA NURON_str_reasons[]= + { +{ERR_REASON(NURON_R_ALREADY_LOADED) ,"already loaded"}, +{ERR_REASON(NURON_R_CTRL_COMMAND_NOT_IMPLEMENTED),"ctrl command not implemented"}, +{ERR_REASON(NURON_R_DSO_FAILURE) ,"dso failure"}, +{ERR_REASON(NURON_R_DSO_FUNCTION_NOT_FOUND),"dso function not found"}, +{ERR_REASON(NURON_R_DSO_NOT_FOUND) ,"dso not found"}, +{ERR_REASON(NURON_R_NOT_LOADED) ,"not loaded"}, +{0,NULL} + }; + +#endif + +#ifdef NURON_LIB_NAME +static ERR_STRING_DATA NURON_lib_name[]= + { +{0 ,NURON_LIB_NAME}, +{0,NULL} + }; +#endif + + +static int NURON_lib_error_code=0; +static int NURON_error_init=1; + +static void ERR_load_NURON_strings(void) + { + if (NURON_lib_error_code == 0) + NURON_lib_error_code=ERR_get_next_error_library(); + + if (NURON_error_init) + { + NURON_error_init=0; +#ifndef OPENSSL_NO_ERR + ERR_load_strings(NURON_lib_error_code,NURON_str_functs); + ERR_load_strings(NURON_lib_error_code,NURON_str_reasons); +#endif + +#ifdef NURON_LIB_NAME + NURON_lib_name->error = ERR_PACK(NURON_lib_error_code,0,0); + ERR_load_strings(0,NURON_lib_name); +#endif + } + } + +static void ERR_unload_NURON_strings(void) + { + if (NURON_error_init == 0) + { +#ifndef OPENSSL_NO_ERR + ERR_unload_strings(NURON_lib_error_code,NURON_str_functs); + ERR_unload_strings(NURON_lib_error_code,NURON_str_reasons); +#endif + +#ifdef NURON_LIB_NAME + ERR_unload_strings(0,NURON_lib_name); +#endif + NURON_error_init=1; + } + } + +static void ERR_NURON_error(int function, int reason, char *file, int line) + { + if (NURON_lib_error_code == 0) + NURON_lib_error_code=ERR_get_next_error_library(); + ERR_PUT_error(NURON_lib_error_code,function,reason,file,line); + } diff --git a/node-v0.8.14/deps/openssl/openssl/engines/e_nuron_err.h b/node-v0.8.14/deps/openssl/openssl/engines/e_nuron_err.h new file mode 100644 index 0000000..219babb --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/engines/e_nuron_err.h @@ -0,0 +1,90 @@ +/* ==================================================================== + * Copyright (c) 2001 The OpenSSL Project. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. All advertising materials mentioning features or use of this + * software must display the following acknowledgment: + * "This product includes software developed by the OpenSSL Project + * for use in the OpenSSL Toolkit. (http://www.openssl.org/)" + * + * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to + * endorse or promote products derived from this software without + * prior written permission. For written permission, please contact + * openssl-core@openssl.org. + * + * 5. Products derived from this software may not be called "OpenSSL" + * nor may "OpenSSL" appear in their names without prior written + * permission of the OpenSSL Project. + * + * 6. Redistributions of any form whatsoever must retain the following + * acknowledgment: + * "This product includes software developed by the OpenSSL Project + * for use in the OpenSSL Toolkit (http://www.openssl.org/)" + * + * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY + * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR + * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, + * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * ==================================================================== + * + * This product includes cryptographic software written by Eric Young + * (eay@cryptsoft.com). This product includes software written by Tim + * Hudson (tjh@cryptsoft.com). + * + */ + +#ifndef HEADER_NURON_ERR_H +#define HEADER_NURON_ERR_H + +#ifdef __cplusplus +extern "C" { +#endif + +/* BEGIN ERROR CODES */ +/* The following lines are auto generated by the script mkerr.pl. Any changes + * made after this point may be overwritten when the script is next run. + */ +static void ERR_load_NURON_strings(void); +static void ERR_unload_NURON_strings(void); +static void ERR_NURON_error(int function, int reason, char *file, int line); +#define NURONerr(f,r) ERR_NURON_error((f),(r),__FILE__,__LINE__) + +/* Error codes for the NURON functions. */ + +/* Function codes. */ +#define NURON_F_NURON_CTRL 100 +#define NURON_F_NURON_FINISH 101 +#define NURON_F_NURON_INIT 102 +#define NURON_F_NURON_MOD_EXP 103 + +/* Reason codes. */ +#define NURON_R_ALREADY_LOADED 100 +#define NURON_R_CTRL_COMMAND_NOT_IMPLEMENTED 101 +#define NURON_R_DSO_FAILURE 102 +#define NURON_R_DSO_FUNCTION_NOT_FOUND 103 +#define NURON_R_DSO_NOT_FOUND 104 +#define NURON_R_NOT_LOADED 105 + +#ifdef __cplusplus +} +#endif +#endif diff --git a/node-v0.8.14/deps/openssl/openssl/engines/e_padlock.c b/node-v0.8.14/deps/openssl/openssl/engines/e_padlock.c new file mode 100644 index 0000000..7d09419 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/engines/e_padlock.c @@ -0,0 +1,1233 @@ +/* + * Support for VIA PadLock Advanced Cryptography Engine (ACE) + * Written by Michal Ludvig + * http://www.logix.cz/michal + * + * Big thanks to Andy Polyakov for a help with optimization, + * assembler fixes, port to MS Windows and a lot of other + * valuable work on this engine! + */ + +/* ==================================================================== + * Copyright (c) 1999-2001 The OpenSSL Project. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. All advertising materials mentioning features or use of this + * software must display the following acknowledgment: + * "This product includes software developed by the OpenSSL Project + * for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)" + * + * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to + * endorse or promote products derived from this software without + * prior written permission. For written permission, please contact + * licensing@OpenSSL.org. + * + * 5. Products derived from this software may not be called "OpenSSL" + * nor may "OpenSSL" appear in their names without prior written + * permission of the OpenSSL Project. + * + * 6. Redistributions of any form whatsoever must retain the following + * acknowledgment: + * "This product includes software developed by the OpenSSL Project + * for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)" + * + * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY + * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR + * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, + * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * ==================================================================== + * + * This product includes cryptographic software written by Eric Young + * (eay@cryptsoft.com). This product includes software written by Tim + * Hudson (tjh@cryptsoft.com). + * + */ + + +#include +#include + +#include +#include +#include +#include +#include +#ifndef OPENSSL_NO_AES +#include +#endif +#include +#include + +#ifndef OPENSSL_NO_HW +#ifndef OPENSSL_NO_HW_PADLOCK + +/* Attempt to have a single source for both 0.9.7 and 0.9.8 :-) */ +#if (OPENSSL_VERSION_NUMBER >= 0x00908000L) +# ifndef OPENSSL_NO_DYNAMIC_ENGINE +# define DYNAMIC_ENGINE +# endif +#elif (OPENSSL_VERSION_NUMBER >= 0x00907000L) +# ifdef ENGINE_DYNAMIC_SUPPORT +# define DYNAMIC_ENGINE +# endif +#else +# error "Only OpenSSL >= 0.9.7 is supported" +#endif + +/* VIA PadLock AES is available *ONLY* on some x86 CPUs. + Not only that it doesn't exist elsewhere, but it + even can't be compiled on other platforms! + + In addition, because of the heavy use of inline assembler, + compiler choice is limited to GCC and Microsoft C. */ +#undef COMPILE_HW_PADLOCK +#if !defined(I386_ONLY) && !defined(OPENSSL_NO_INLINE_ASM) +# if (defined(__GNUC__) && (defined(__i386__) || defined(__i386))) || \ + (defined(_MSC_VER) && defined(_M_IX86)) +# define COMPILE_HW_PADLOCK +static ENGINE *ENGINE_padlock (void); +# endif +#endif + +#ifdef OPENSSL_NO_DYNAMIC_ENGINE + +void ENGINE_load_padlock (void) +{ +/* On non-x86 CPUs it just returns. */ +#ifdef COMPILE_HW_PADLOCK + ENGINE *toadd = ENGINE_padlock (); + if (!toadd) return; + ENGINE_add (toadd); + ENGINE_free (toadd); + ERR_clear_error (); +#endif +} + +#endif + +#ifdef COMPILE_HW_PADLOCK +/* We do these includes here to avoid header problems on platforms that + do not have the VIA padlock anyway... */ +#include +#ifdef _WIN32 +# include +# ifndef alloca +# define alloca _alloca +# endif +#elif defined(__GNUC__) +# ifndef alloca +# define alloca(s) __builtin_alloca(s) +# endif +#endif + +/* Function for ENGINE detection and control */ +static int padlock_available(void); +static int padlock_init(ENGINE *e); + +/* RNG Stuff */ +static RAND_METHOD padlock_rand; + +/* Cipher Stuff */ +#ifndef OPENSSL_NO_AES +static int padlock_ciphers(ENGINE *e, const EVP_CIPHER **cipher, const int **nids, int nid); +#endif + +/* Engine names */ +static const char *padlock_id = "padlock"; +static char padlock_name[100]; + +/* Available features */ +static int padlock_use_ace = 0; /* Advanced Cryptography Engine */ +static int padlock_use_rng = 0; /* Random Number Generator */ +#ifndef OPENSSL_NO_AES +static int padlock_aes_align_required = 1; +#endif + +/* ===== Engine "management" functions ===== */ + +/* Prepare the ENGINE structure for registration */ +static int +padlock_bind_helper(ENGINE *e) +{ + /* Check available features */ + padlock_available(); + +#if 1 /* disable RNG for now, see commentary in vicinity of RNG code */ + padlock_use_rng=0; +#endif + + /* Generate a nice engine name with available features */ + BIO_snprintf(padlock_name, sizeof(padlock_name), + "VIA PadLock (%s, %s)", + padlock_use_rng ? "RNG" : "no-RNG", + padlock_use_ace ? "ACE" : "no-ACE"); + + /* Register everything or return with an error */ + if (!ENGINE_set_id(e, padlock_id) || + !ENGINE_set_name(e, padlock_name) || + + !ENGINE_set_init_function(e, padlock_init) || +#ifndef OPENSSL_NO_AES + (padlock_use_ace && !ENGINE_set_ciphers (e, padlock_ciphers)) || +#endif + (padlock_use_rng && !ENGINE_set_RAND (e, &padlock_rand))) { + return 0; + } + + /* Everything looks good */ + return 1; +} + +/* Constructor */ +static ENGINE * +ENGINE_padlock(void) +{ + ENGINE *eng = ENGINE_new(); + + if (!eng) { + return NULL; + } + + if (!padlock_bind_helper(eng)) { + ENGINE_free(eng); + return NULL; + } + + return eng; +} + +/* Check availability of the engine */ +static int +padlock_init(ENGINE *e) +{ + return (padlock_use_rng || padlock_use_ace); +} + +/* This stuff is needed if this ENGINE is being compiled into a self-contained + * shared-library. + */ +#ifdef DYNAMIC_ENGINE +static int +padlock_bind_fn(ENGINE *e, const char *id) +{ + if (id && (strcmp(id, padlock_id) != 0)) { + return 0; + } + + if (!padlock_bind_helper(e)) { + return 0; + } + + return 1; +} + +IMPLEMENT_DYNAMIC_CHECK_FN() +IMPLEMENT_DYNAMIC_BIND_FN (padlock_bind_fn) +#endif /* DYNAMIC_ENGINE */ + +/* ===== Here comes the "real" engine ===== */ + +#ifndef OPENSSL_NO_AES +/* Some AES-related constants */ +#define AES_BLOCK_SIZE 16 +#define AES_KEY_SIZE_128 16 +#define AES_KEY_SIZE_192 24 +#define AES_KEY_SIZE_256 32 + +/* Here we store the status information relevant to the + current context. */ +/* BIG FAT WARNING: + * Inline assembler in PADLOCK_XCRYPT_ASM() + * depends on the order of items in this structure. + * Don't blindly modify, reorder, etc! + */ +struct padlock_cipher_data +{ + unsigned char iv[AES_BLOCK_SIZE]; /* Initialization vector */ + union { unsigned int pad[4]; + struct { + int rounds:4; + int dgst:1; /* n/a in C3 */ + int align:1; /* n/a in C3 */ + int ciphr:1; /* n/a in C3 */ + unsigned int keygen:1; + int interm:1; + unsigned int encdec:1; + int ksize:2; + } b; + } cword; /* Control word */ + AES_KEY ks; /* Encryption key */ +}; + +/* + * Essentially this variable belongs in thread local storage. + * Having this variable global on the other hand can only cause + * few bogus key reloads [if any at all on single-CPU system], + * so we accept the penatly... + */ +static volatile struct padlock_cipher_data *padlock_saved_context; +#endif + +/* + * ======================================================= + * Inline assembler section(s). + * ======================================================= + * Order of arguments is chosen to facilitate Windows port + * using __fastcall calling convention. If you wish to add + * more routines, keep in mind that first __fastcall + * argument is passed in %ecx and second - in %edx. + * ======================================================= + */ +#if defined(__GNUC__) && __GNUC__>=2 +/* + * As for excessive "push %ebx"/"pop %ebx" found all over. + * When generating position-independent code GCC won't let + * us use "b" in assembler templates nor even respect "ebx" + * in "clobber description." Therefore the trouble... + */ + +/* Helper function - check if a CPUID instruction + is available on this CPU */ +static int +padlock_insn_cpuid_available(void) +{ + int result = -1; + + /* We're checking if the bit #21 of EFLAGS + can be toggled. If yes = CPUID is available. */ + asm volatile ( + "pushf\n" + "popl %%eax\n" + "xorl $0x200000, %%eax\n" + "movl %%eax, %%ecx\n" + "andl $0x200000, %%ecx\n" + "pushl %%eax\n" + "popf\n" + "pushf\n" + "popl %%eax\n" + "andl $0x200000, %%eax\n" + "xorl %%eax, %%ecx\n" + "movl %%ecx, %0\n" + : "=r" (result) : : "eax", "ecx"); + + return (result == 0); +} + +/* Load supported features of the CPU to see if + the PadLock is available. */ +static int +padlock_available(void) +{ + char vendor_string[16]; + unsigned int eax, edx; + + /* First check if the CPUID instruction is available at all... */ + if (! padlock_insn_cpuid_available()) + return 0; + + /* Are we running on the Centaur (VIA) CPU? */ + eax = 0x00000000; + vendor_string[12] = 0; + asm volatile ( + "pushl %%ebx\n" + "cpuid\n" + "movl %%ebx,(%%edi)\n" + "movl %%edx,4(%%edi)\n" + "movl %%ecx,8(%%edi)\n" + "popl %%ebx" + : "+a"(eax) : "D"(vendor_string) : "ecx", "edx"); + if (strcmp(vendor_string, "CentaurHauls") != 0) + return 0; + + /* Check for Centaur Extended Feature Flags presence */ + eax = 0xC0000000; + asm volatile ("pushl %%ebx; cpuid; popl %%ebx" + : "+a"(eax) : : "ecx", "edx"); + if (eax < 0xC0000001) + return 0; + + /* Read the Centaur Extended Feature Flags */ + eax = 0xC0000001; + asm volatile ("pushl %%ebx; cpuid; popl %%ebx" + : "+a"(eax), "=d"(edx) : : "ecx"); + + /* Fill up some flags */ + padlock_use_ace = ((edx & (0x3<<6)) == (0x3<<6)); + padlock_use_rng = ((edx & (0x3<<2)) == (0x3<<2)); + + return padlock_use_ace + padlock_use_rng; +} + +#ifndef OPENSSL_NO_AES +/* Our own htonl()/ntohl() */ +static inline void +padlock_bswapl(AES_KEY *ks) +{ + size_t i = sizeof(ks->rd_key)/sizeof(ks->rd_key[0]); + unsigned int *key = ks->rd_key; + + while (i--) { + asm volatile ("bswapl %0" : "+r"(*key)); + key++; + } +} +#endif + +/* Force key reload from memory to the CPU microcode. + Loading EFLAGS from the stack clears EFLAGS[30] + which does the trick. */ +static inline void +padlock_reload_key(void) +{ + asm volatile ("pushfl; popfl"); +} + +#ifndef OPENSSL_NO_AES +/* + * This is heuristic key context tracing. At first one + * believes that one should use atomic swap instructions, + * but it's not actually necessary. Point is that if + * padlock_saved_context was changed by another thread + * after we've read it and before we compare it with cdata, + * our key *shall* be reloaded upon thread context switch + * and we are therefore set in either case... + */ +static inline void +padlock_verify_context(struct padlock_cipher_data *cdata) +{ + asm volatile ( + "pushfl\n" +" btl $30,(%%esp)\n" +" jnc 1f\n" +" cmpl %2,%1\n" +" je 1f\n" +" popfl\n" +" subl $4,%%esp\n" +"1: addl $4,%%esp\n" +" movl %2,%0" + :"+m"(padlock_saved_context) + : "r"(padlock_saved_context), "r"(cdata) : "cc"); +} + +/* Template for padlock_xcrypt_* modes */ +/* BIG FAT WARNING: + * The offsets used with 'leal' instructions + * describe items of the 'padlock_cipher_data' + * structure. + */ +#define PADLOCK_XCRYPT_ASM(name,rep_xcrypt) \ +static inline void *name(size_t cnt, \ + struct padlock_cipher_data *cdata, \ + void *out, const void *inp) \ +{ void *iv; \ + asm volatile ( "pushl %%ebx\n" \ + " leal 16(%0),%%edx\n" \ + " leal 32(%0),%%ebx\n" \ + rep_xcrypt "\n" \ + " popl %%ebx" \ + : "=a"(iv), "=c"(cnt), "=D"(out), "=S"(inp) \ + : "0"(cdata), "1"(cnt), "2"(out), "3"(inp) \ + : "edx", "cc", "memory"); \ + return iv; \ +} + +/* Generate all functions with appropriate opcodes */ +PADLOCK_XCRYPT_ASM(padlock_xcrypt_ecb, ".byte 0xf3,0x0f,0xa7,0xc8") /* rep xcryptecb */ +PADLOCK_XCRYPT_ASM(padlock_xcrypt_cbc, ".byte 0xf3,0x0f,0xa7,0xd0") /* rep xcryptcbc */ +PADLOCK_XCRYPT_ASM(padlock_xcrypt_cfb, ".byte 0xf3,0x0f,0xa7,0xe0") /* rep xcryptcfb */ +PADLOCK_XCRYPT_ASM(padlock_xcrypt_ofb, ".byte 0xf3,0x0f,0xa7,0xe8") /* rep xcryptofb */ +#endif + +/* The RNG call itself */ +static inline unsigned int +padlock_xstore(void *addr, unsigned int edx_in) +{ + unsigned int eax_out; + + asm volatile (".byte 0x0f,0xa7,0xc0" /* xstore */ + : "=a"(eax_out),"=m"(*(unsigned *)addr) + : "D"(addr), "d" (edx_in) + ); + + return eax_out; +} + +/* Why not inline 'rep movsd'? I failed to find information on what + * value in Direction Flag one can expect and consequently have to + * apply "better-safe-than-sorry" approach and assume "undefined." + * I could explicitly clear it and restore the original value upon + * return from padlock_aes_cipher, but it's presumably too much + * trouble for too little gain... + * + * In case you wonder 'rep xcrypt*' instructions above are *not* + * affected by the Direction Flag and pointers advance toward + * larger addresses unconditionally. + */ +static inline unsigned char * +padlock_memcpy(void *dst,const void *src,size_t n) +{ + long *d=dst; + const long *s=src; + + n /= sizeof(*d); + do { *d++ = *s++; } while (--n); + + return dst; +} + +#elif defined(_MSC_VER) +/* + * Unlike GCC these are real functions. In order to minimize impact + * on performance we adhere to __fastcall calling convention in + * order to get two first arguments passed through %ecx and %edx. + * Which kind of suits very well, as instructions in question use + * both %ecx and %edx as input:-) + */ +#define REP_XCRYPT(code) \ + _asm _emit 0xf3 \ + _asm _emit 0x0f _asm _emit 0xa7 \ + _asm _emit code + +/* BIG FAT WARNING: + * The offsets used with 'lea' instructions + * describe items of the 'padlock_cipher_data' + * structure. + */ +#define PADLOCK_XCRYPT_ASM(name,code) \ +static void * __fastcall \ + name (size_t cnt, void *cdata, \ + void *outp, const void *inp) \ +{ _asm mov eax,edx \ + _asm lea edx,[eax+16] \ + _asm lea ebx,[eax+32] \ + _asm mov edi,outp \ + _asm mov esi,inp \ + REP_XCRYPT(code) \ +} + +PADLOCK_XCRYPT_ASM(padlock_xcrypt_ecb,0xc8) +PADLOCK_XCRYPT_ASM(padlock_xcrypt_cbc,0xd0) +PADLOCK_XCRYPT_ASM(padlock_xcrypt_cfb,0xe0) +PADLOCK_XCRYPT_ASM(padlock_xcrypt_ofb,0xe8) + +static int __fastcall +padlock_xstore(void *outp,unsigned int code) +{ _asm mov edi,ecx + _asm _emit 0x0f _asm _emit 0xa7 _asm _emit 0xc0 +} + +static void __fastcall +padlock_reload_key(void) +{ _asm pushfd _asm popfd } + +static void __fastcall +padlock_verify_context(void *cdata) +{ _asm { + pushfd + bt DWORD PTR[esp],30 + jnc skip + cmp ecx,padlock_saved_context + je skip + popfd + sub esp,4 + skip: add esp,4 + mov padlock_saved_context,ecx + } +} + +static int +padlock_available(void) +{ _asm { + pushfd + pop eax + mov ecx,eax + xor eax,1<<21 + push eax + popfd + pushfd + pop eax + xor eax,ecx + bt eax,21 + jnc noluck + mov eax,0 + cpuid + xor eax,eax + cmp ebx,'tneC' + jne noluck + cmp edx,'Hrua' + jne noluck + cmp ecx,'slua' + jne noluck + mov eax,0xC0000000 + cpuid + mov edx,eax + xor eax,eax + cmp edx,0xC0000001 + jb noluck + mov eax,0xC0000001 + cpuid + xor eax,eax + bt edx,6 + jnc skip_a + bt edx,7 + jnc skip_a + mov padlock_use_ace,1 + inc eax + skip_a: bt edx,2 + jnc skip_r + bt edx,3 + jnc skip_r + mov padlock_use_rng,1 + inc eax + skip_r: + noluck: + } +} + +static void __fastcall +padlock_bswapl(void *key) +{ _asm { + pushfd + cld + mov esi,ecx + mov edi,ecx + mov ecx,60 + up: lodsd + bswap eax + stosd + loop up + popfd + } +} + +/* MS actually specifies status of Direction Flag and compiler even + * manages to compile following as 'rep movsd' all by itself... + */ +#define padlock_memcpy(o,i,n) ((unsigned char *)memcpy((o),(i),(n)&~3U)) +#endif + +/* ===== AES encryption/decryption ===== */ +#ifndef OPENSSL_NO_AES + +#if defined(NID_aes_128_cfb128) && ! defined (NID_aes_128_cfb) +#define NID_aes_128_cfb NID_aes_128_cfb128 +#endif + +#if defined(NID_aes_128_ofb128) && ! defined (NID_aes_128_ofb) +#define NID_aes_128_ofb NID_aes_128_ofb128 +#endif + +#if defined(NID_aes_192_cfb128) && ! defined (NID_aes_192_cfb) +#define NID_aes_192_cfb NID_aes_192_cfb128 +#endif + +#if defined(NID_aes_192_ofb128) && ! defined (NID_aes_192_ofb) +#define NID_aes_192_ofb NID_aes_192_ofb128 +#endif + +#if defined(NID_aes_256_cfb128) && ! defined (NID_aes_256_cfb) +#define NID_aes_256_cfb NID_aes_256_cfb128 +#endif + +#if defined(NID_aes_256_ofb128) && ! defined (NID_aes_256_ofb) +#define NID_aes_256_ofb NID_aes_256_ofb128 +#endif + +/* List of supported ciphers. */ +static int padlock_cipher_nids[] = { + NID_aes_128_ecb, + NID_aes_128_cbc, + NID_aes_128_cfb, + NID_aes_128_ofb, + + NID_aes_192_ecb, + NID_aes_192_cbc, + NID_aes_192_cfb, + NID_aes_192_ofb, + + NID_aes_256_ecb, + NID_aes_256_cbc, + NID_aes_256_cfb, + NID_aes_256_ofb, +}; +static int padlock_cipher_nids_num = (sizeof(padlock_cipher_nids)/ + sizeof(padlock_cipher_nids[0])); + +/* Function prototypes ... */ +static int padlock_aes_init_key(EVP_CIPHER_CTX *ctx, const unsigned char *key, + const unsigned char *iv, int enc); +static int padlock_aes_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out, + const unsigned char *in, size_t nbytes); + +#define NEAREST_ALIGNED(ptr) ( (unsigned char *)(ptr) + \ + ( (0x10 - ((size_t)(ptr) & 0x0F)) & 0x0F ) ) +#define ALIGNED_CIPHER_DATA(ctx) ((struct padlock_cipher_data *)\ + NEAREST_ALIGNED(ctx->cipher_data)) + +#define EVP_CIPHER_block_size_ECB AES_BLOCK_SIZE +#define EVP_CIPHER_block_size_CBC AES_BLOCK_SIZE +#define EVP_CIPHER_block_size_OFB 1 +#define EVP_CIPHER_block_size_CFB 1 + +/* Declaring so many ciphers by hand would be a pain. + Instead introduce a bit of preprocessor magic :-) */ +#define DECLARE_AES_EVP(ksize,lmode,umode) \ +static const EVP_CIPHER padlock_aes_##ksize##_##lmode = { \ + NID_aes_##ksize##_##lmode, \ + EVP_CIPHER_block_size_##umode, \ + AES_KEY_SIZE_##ksize, \ + AES_BLOCK_SIZE, \ + 0 | EVP_CIPH_##umode##_MODE, \ + padlock_aes_init_key, \ + padlock_aes_cipher, \ + NULL, \ + sizeof(struct padlock_cipher_data) + 16, \ + EVP_CIPHER_set_asn1_iv, \ + EVP_CIPHER_get_asn1_iv, \ + NULL, \ + NULL \ +} + +DECLARE_AES_EVP(128,ecb,ECB); +DECLARE_AES_EVP(128,cbc,CBC); +DECLARE_AES_EVP(128,cfb,CFB); +DECLARE_AES_EVP(128,ofb,OFB); + +DECLARE_AES_EVP(192,ecb,ECB); +DECLARE_AES_EVP(192,cbc,CBC); +DECLARE_AES_EVP(192,cfb,CFB); +DECLARE_AES_EVP(192,ofb,OFB); + +DECLARE_AES_EVP(256,ecb,ECB); +DECLARE_AES_EVP(256,cbc,CBC); +DECLARE_AES_EVP(256,cfb,CFB); +DECLARE_AES_EVP(256,ofb,OFB); + +static int +padlock_ciphers (ENGINE *e, const EVP_CIPHER **cipher, const int **nids, int nid) +{ + /* No specific cipher => return a list of supported nids ... */ + if (!cipher) { + *nids = padlock_cipher_nids; + return padlock_cipher_nids_num; + } + + /* ... or the requested "cipher" otherwise */ + switch (nid) { + case NID_aes_128_ecb: + *cipher = &padlock_aes_128_ecb; + break; + case NID_aes_128_cbc: + *cipher = &padlock_aes_128_cbc; + break; + case NID_aes_128_cfb: + *cipher = &padlock_aes_128_cfb; + break; + case NID_aes_128_ofb: + *cipher = &padlock_aes_128_ofb; + break; + + case NID_aes_192_ecb: + *cipher = &padlock_aes_192_ecb; + break; + case NID_aes_192_cbc: + *cipher = &padlock_aes_192_cbc; + break; + case NID_aes_192_cfb: + *cipher = &padlock_aes_192_cfb; + break; + case NID_aes_192_ofb: + *cipher = &padlock_aes_192_ofb; + break; + + case NID_aes_256_ecb: + *cipher = &padlock_aes_256_ecb; + break; + case NID_aes_256_cbc: + *cipher = &padlock_aes_256_cbc; + break; + case NID_aes_256_cfb: + *cipher = &padlock_aes_256_cfb; + break; + case NID_aes_256_ofb: + *cipher = &padlock_aes_256_ofb; + break; + + default: + /* Sorry, we don't support this NID */ + *cipher = NULL; + return 0; + } + + return 1; +} + +/* Prepare the encryption key for PadLock usage */ +static int +padlock_aes_init_key (EVP_CIPHER_CTX *ctx, const unsigned char *key, + const unsigned char *iv, int enc) +{ + struct padlock_cipher_data *cdata; + int key_len = EVP_CIPHER_CTX_key_length(ctx) * 8; + + if (key==NULL) return 0; /* ERROR */ + + cdata = ALIGNED_CIPHER_DATA(ctx); + memset(cdata, 0, sizeof(struct padlock_cipher_data)); + + /* Prepare Control word. */ + if (EVP_CIPHER_CTX_mode(ctx) == EVP_CIPH_OFB_MODE) + cdata->cword.b.encdec = 0; + else + cdata->cword.b.encdec = (ctx->encrypt == 0); + cdata->cword.b.rounds = 10 + (key_len - 128) / 32; + cdata->cword.b.ksize = (key_len - 128) / 64; + + switch(key_len) { + case 128: + /* PadLock can generate an extended key for + AES128 in hardware */ + memcpy(cdata->ks.rd_key, key, AES_KEY_SIZE_128); + cdata->cword.b.keygen = 0; + break; + + case 192: + case 256: + /* Generate an extended AES key in software. + Needed for AES192/AES256 */ + /* Well, the above applies to Stepping 8 CPUs + and is listed as hardware errata. They most + likely will fix it at some point and then + a check for stepping would be due here. */ + if (EVP_CIPHER_CTX_mode(ctx) == EVP_CIPH_CFB_MODE || + EVP_CIPHER_CTX_mode(ctx) == EVP_CIPH_OFB_MODE || + enc) + AES_set_encrypt_key(key, key_len, &cdata->ks); + else + AES_set_decrypt_key(key, key_len, &cdata->ks); +#ifndef AES_ASM + /* OpenSSL C functions use byte-swapped extended key. */ + padlock_bswapl(&cdata->ks); +#endif + cdata->cword.b.keygen = 1; + break; + + default: + /* ERROR */ + return 0; + } + + /* + * This is done to cover for cases when user reuses the + * context for new key. The catch is that if we don't do + * this, padlock_eas_cipher might proceed with old key... + */ + padlock_reload_key (); + + return 1; +} + +/* + * Simplified version of padlock_aes_cipher() used when + * 1) both input and output buffers are at aligned addresses. + * or when + * 2) running on a newer CPU that doesn't require aligned buffers. + */ +static int +padlock_aes_cipher_omnivorous(EVP_CIPHER_CTX *ctx, unsigned char *out_arg, + const unsigned char *in_arg, size_t nbytes) +{ + struct padlock_cipher_data *cdata; + void *iv; + + cdata = ALIGNED_CIPHER_DATA(ctx); + padlock_verify_context(cdata); + + switch (EVP_CIPHER_CTX_mode(ctx)) { + case EVP_CIPH_ECB_MODE: + padlock_xcrypt_ecb(nbytes/AES_BLOCK_SIZE, cdata, out_arg, in_arg); + break; + + case EVP_CIPH_CBC_MODE: + memcpy(cdata->iv, ctx->iv, AES_BLOCK_SIZE); + iv = padlock_xcrypt_cbc(nbytes/AES_BLOCK_SIZE, cdata, out_arg, in_arg); + memcpy(ctx->iv, iv, AES_BLOCK_SIZE); + break; + + case EVP_CIPH_CFB_MODE: + memcpy(cdata->iv, ctx->iv, AES_BLOCK_SIZE); + iv = padlock_xcrypt_cfb(nbytes/AES_BLOCK_SIZE, cdata, out_arg, in_arg); + memcpy(ctx->iv, iv, AES_BLOCK_SIZE); + break; + + case EVP_CIPH_OFB_MODE: + memcpy(cdata->iv, ctx->iv, AES_BLOCK_SIZE); + padlock_xcrypt_ofb(nbytes/AES_BLOCK_SIZE, cdata, out_arg, in_arg); + memcpy(ctx->iv, cdata->iv, AES_BLOCK_SIZE); + break; + + default: + return 0; + } + + memset(cdata->iv, 0, AES_BLOCK_SIZE); + + return 1; +} + +#ifndef PADLOCK_CHUNK +# define PADLOCK_CHUNK 512 /* Must be a power of 2 larger than 16 */ +#endif +#if PADLOCK_CHUNK<16 || PADLOCK_CHUNK&(PADLOCK_CHUNK-1) +# error "insane PADLOCK_CHUNK..." +#endif + +/* Re-align the arguments to 16-Bytes boundaries and run the + encryption function itself. This function is not AES-specific. */ +static int +padlock_aes_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out_arg, + const unsigned char *in_arg, size_t nbytes) +{ + struct padlock_cipher_data *cdata; + const void *inp; + unsigned char *out; + void *iv; + int inp_misaligned, out_misaligned, realign_in_loop; + size_t chunk, allocated=0; + + /* ctx->num is maintained in byte-oriented modes, + such as CFB and OFB... */ + if ((chunk = ctx->num)) { /* borrow chunk variable */ + unsigned char *ivp=ctx->iv; + + switch (EVP_CIPHER_CTX_mode(ctx)) { + case EVP_CIPH_CFB_MODE: + if (chunk >= AES_BLOCK_SIZE) + return 0; /* bogus value */ + + if (ctx->encrypt) + while (chunknum = chunk%AES_BLOCK_SIZE; + break; + case EVP_CIPH_OFB_MODE: + if (chunk >= AES_BLOCK_SIZE) + return 0; /* bogus value */ + + while (chunknum = chunk%AES_BLOCK_SIZE; + break; + } + } + + if (nbytes == 0) + return 1; +#if 0 + if (nbytes % AES_BLOCK_SIZE) + return 0; /* are we expected to do tail processing? */ +#else + /* nbytes is always multiple of AES_BLOCK_SIZE in ECB and CBC + modes and arbitrary value in byte-oriented modes, such as + CFB and OFB... */ +#endif + + /* VIA promises CPUs that won't require alignment in the future. + For now padlock_aes_align_required is initialized to 1 and + the condition is never met... */ + /* C7 core is capable to manage unaligned input in non-ECB[!] + mode, but performance penalties appear to be approximately + same as for software alignment below or ~3x. They promise to + improve it in the future, but for now we can just as well + pretend that it can only handle aligned input... */ + if (!padlock_aes_align_required && (nbytes%AES_BLOCK_SIZE)==0) + return padlock_aes_cipher_omnivorous(ctx, out_arg, in_arg, nbytes); + + inp_misaligned = (((size_t)in_arg) & 0x0F); + out_misaligned = (((size_t)out_arg) & 0x0F); + + /* Note that even if output is aligned and input not, + * I still prefer to loop instead of copy the whole + * input and then encrypt in one stroke. This is done + * in order to improve L1 cache utilization... */ + realign_in_loop = out_misaligned|inp_misaligned; + + if (!realign_in_loop && (nbytes%AES_BLOCK_SIZE)==0) + return padlock_aes_cipher_omnivorous(ctx, out_arg, in_arg, nbytes); + + /* this takes one "if" out of the loops */ + chunk = nbytes; + chunk %= PADLOCK_CHUNK; + if (chunk==0) chunk = PADLOCK_CHUNK; + + if (out_misaligned) { + /* optmize for small input */ + allocated = (chunkiv, ctx->iv, AES_BLOCK_SIZE); + goto cbc_shortcut; + do { + if (iv != cdata->iv) + memcpy(cdata->iv, iv, AES_BLOCK_SIZE); + chunk = PADLOCK_CHUNK; + cbc_shortcut: /* optimize for small input */ + if (inp_misaligned) + inp = padlock_memcpy(out, in_arg, chunk); + else + inp = in_arg; + in_arg += chunk; + + iv = padlock_xcrypt_cbc(chunk/AES_BLOCK_SIZE, cdata, out, inp); + + if (out_misaligned) + out_arg = padlock_memcpy(out_arg, out, chunk) + chunk; + else + out = out_arg+=chunk; + + } while (nbytes -= chunk); + memcpy(ctx->iv, iv, AES_BLOCK_SIZE); + break; + + case EVP_CIPH_CFB_MODE: + memcpy (iv = cdata->iv, ctx->iv, AES_BLOCK_SIZE); + chunk &= ~(AES_BLOCK_SIZE-1); + if (chunk) goto cfb_shortcut; + else goto cfb_skiploop; + do { + if (iv != cdata->iv) + memcpy(cdata->iv, iv, AES_BLOCK_SIZE); + chunk = PADLOCK_CHUNK; + cfb_shortcut: /* optimize for small input */ + if (inp_misaligned) + inp = padlock_memcpy(out, in_arg, chunk); + else + inp = in_arg; + in_arg += chunk; + + iv = padlock_xcrypt_cfb(chunk/AES_BLOCK_SIZE, cdata, out, inp); + + if (out_misaligned) + out_arg = padlock_memcpy(out_arg, out, chunk) + chunk; + else + out = out_arg+=chunk; + + nbytes -= chunk; + } while (nbytes >= AES_BLOCK_SIZE); + + cfb_skiploop: + if (nbytes) { + unsigned char *ivp = cdata->iv; + + if (iv != ivp) { + memcpy(ivp, iv, AES_BLOCK_SIZE); + iv = ivp; + } + ctx->num = nbytes; + if (cdata->cword.b.encdec) { + cdata->cword.b.encdec=0; + padlock_reload_key(); + padlock_xcrypt_ecb(1,cdata,ivp,ivp); + cdata->cword.b.encdec=1; + padlock_reload_key(); + while(nbytes) { + unsigned char c = *(in_arg++); + *(out_arg++) = c ^ *ivp; + *(ivp++) = c, nbytes--; + } + } + else { padlock_reload_key(); + padlock_xcrypt_ecb(1,cdata,ivp,ivp); + padlock_reload_key(); + while (nbytes) { + *ivp = *(out_arg++) = *(in_arg++) ^ *ivp; + ivp++, nbytes--; + } + } + } + + memcpy(ctx->iv, iv, AES_BLOCK_SIZE); + break; + + case EVP_CIPH_OFB_MODE: + memcpy(cdata->iv, ctx->iv, AES_BLOCK_SIZE); + chunk &= ~(AES_BLOCK_SIZE-1); + if (chunk) do { + if (inp_misaligned) + inp = padlock_memcpy(out, in_arg, chunk); + else + inp = in_arg; + in_arg += chunk; + + padlock_xcrypt_ofb(chunk/AES_BLOCK_SIZE, cdata, out, inp); + + if (out_misaligned) + out_arg = padlock_memcpy(out_arg, out, chunk) + chunk; + else + out = out_arg+=chunk; + + nbytes -= chunk; + chunk = PADLOCK_CHUNK; + } while (nbytes >= AES_BLOCK_SIZE); + + if (nbytes) { + unsigned char *ivp = cdata->iv; + + ctx->num = nbytes; + padlock_reload_key(); /* empirically found */ + padlock_xcrypt_ecb(1,cdata,ivp,ivp); + padlock_reload_key(); /* empirically found */ + while (nbytes) { + *(out_arg++) = *(in_arg++) ^ *ivp; + ivp++, nbytes--; + } + } + + memcpy(ctx->iv, cdata->iv, AES_BLOCK_SIZE); + break; + + default: + return 0; + } + + /* Clean the realign buffer if it was used */ + if (out_misaligned) { + volatile unsigned long *p=(void *)out; + size_t n = allocated/sizeof(*p); + while (n--) *p++=0; + } + + memset(cdata->iv, 0, AES_BLOCK_SIZE); + + return 1; +} + +#endif /* OPENSSL_NO_AES */ + +/* ===== Random Number Generator ===== */ +/* + * This code is not engaged. The reason is that it does not comply + * with recommendations for VIA RNG usage for secure applications + * (posted at http://www.via.com.tw/en/viac3/c3.jsp) nor does it + * provide meaningful error control... + */ +/* Wrapper that provides an interface between the API and + the raw PadLock RNG */ +static int +padlock_rand_bytes(unsigned char *output, int count) +{ + unsigned int eax, buf; + + while (count >= 8) { + eax = padlock_xstore(output, 0); + if (!(eax&(1<<6))) return 0; /* RNG disabled */ + /* this ---vv--- covers DC bias, Raw Bits and String Filter */ + if (eax&(0x1F<<10)) return 0; + if ((eax&0x1F)==0) continue; /* no data, retry... */ + if ((eax&0x1F)!=8) return 0; /* fatal failure... */ + output += 8; + count -= 8; + } + while (count > 0) { + eax = padlock_xstore(&buf, 3); + if (!(eax&(1<<6))) return 0; /* RNG disabled */ + /* this ---vv--- covers DC bias, Raw Bits and String Filter */ + if (eax&(0x1F<<10)) return 0; + if ((eax&0x1F)==0) continue; /* no data, retry... */ + if ((eax&0x1F)!=1) return 0; /* fatal failure... */ + *output++ = (unsigned char)buf; + count--; + } + *(volatile unsigned int *)&buf=0; + + return 1; +} + +/* Dummy but necessary function */ +static int +padlock_rand_status(void) +{ + return 1; +} + +/* Prepare structure for registration */ +static RAND_METHOD padlock_rand = { + NULL, /* seed */ + padlock_rand_bytes, /* bytes */ + NULL, /* cleanup */ + NULL, /* add */ + padlock_rand_bytes, /* pseudorand */ + padlock_rand_status, /* rand status */ +}; + +#else /* !COMPILE_HW_PADLOCK */ +#ifndef OPENSSL_NO_DYNAMIC_ENGINE +OPENSSL_EXPORT +int bind_engine(ENGINE *e, const char *id, const dynamic_fns *fns); +OPENSSL_EXPORT +int bind_engine(ENGINE *e, const char *id, const dynamic_fns *fns) { return 0; } +IMPLEMENT_DYNAMIC_CHECK_FN() +#endif +#endif /* COMPILE_HW_PADLOCK */ + +#endif /* !OPENSSL_NO_HW_PADLOCK */ +#endif /* !OPENSSL_NO_HW */ diff --git a/node-v0.8.14/deps/openssl/openssl/engines/e_padlock.ec b/node-v0.8.14/deps/openssl/openssl/engines/e_padlock.ec new file mode 100644 index 0000000..5c8a1d2 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/engines/e_padlock.ec @@ -0,0 +1 @@ +L PADLOCK e_padlock_err.h e_padlock_err.c diff --git a/node-v0.8.14/deps/openssl/openssl/engines/e_sureware.c b/node-v0.8.14/deps/openssl/openssl/engines/e_sureware.c new file mode 100644 index 0000000..cd0fa4c --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/engines/e_sureware.c @@ -0,0 +1,1055 @@ +/* Written by Corinne Dive-Reclus(cdive@baltimore.com) +* +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions +* are met: +* +* 1. Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* +* 2. Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in +* the documentation and/or other materials provided with the +* distribution. +* +* 3. All advertising materials mentioning features or use of this +* software must display the following acknowledgment: +* "This product includes software developed by the OpenSSL Project +* for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)" +* +* 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to +* endorse or promote products derived from this software without +* prior written permission. For written permission, please contact +* licensing@OpenSSL.org. +* +* 5. Products derived from this software may not be called "OpenSSL" +* nor may "OpenSSL" appear in their names without prior written +* permission of the OpenSSL Project. +* +* 6. Redistributions of any form whatsoever must retain the following +* acknowledgment: +* "This product includes software developed by the OpenSSL Project +* for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)" +* +* Written by Corinne Dive-Reclus(cdive@baltimore.com) +* +* Copyright@2001 Baltimore Technologies Ltd. +* All right Reserved. +* * +* THIS FILE IS PROVIDED BY BALTIMORE TECHNOLOGIES ``AS IS'' AND * +* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * +* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * +* ARE DISCLAIMED. IN NO EVENT SHALL BALTIMORE TECHNOLOGIES BE LIABLE * +* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * +* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * +* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * +* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * +* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * +* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * +* SUCH DAMAGE. * +====================================================================*/ + +#include +#include +#include +#include +#include +#include +#include +#ifndef OPENSSL_NO_RSA +#include +#endif +#ifndef OPENSSL_NO_DSA +#include +#endif +#ifndef OPENSSL_NO_DH +#include +#endif +#include + +#ifndef OPENSSL_NO_HW +#ifndef OPENSSL_NO_HW_SUREWARE + +#ifdef FLAT_INC +#include "sureware.h" +#else +#include "vendor_defns/sureware.h" +#endif + +#define SUREWARE_LIB_NAME "sureware engine" +#include "e_sureware_err.c" + +static int surewarehk_ctrl(ENGINE *e, int cmd, long i, void *p, void (*f)(void)); +static int surewarehk_destroy(ENGINE *e); +static int surewarehk_init(ENGINE *e); +static int surewarehk_finish(ENGINE *e); +static int surewarehk_modexp(BIGNUM *r, const BIGNUM *a, const BIGNUM *p, + const BIGNUM *m, BN_CTX *ctx); + +/* RSA stuff */ +#ifndef OPENSSL_NO_RSA +static int surewarehk_rsa_priv_dec(int flen,const unsigned char *from,unsigned char *to, + RSA *rsa,int padding); +static int surewarehk_rsa_sign(int flen,const unsigned char *from,unsigned char *to, + RSA *rsa,int padding); +#endif + +/* RAND stuff */ +static int surewarehk_rand_bytes(unsigned char *buf, int num); +static void surewarehk_rand_seed(const void *buf, int num); +static void surewarehk_rand_add(const void *buf, int num, double entropy); + +/* KM stuff */ +static EVP_PKEY *surewarehk_load_privkey(ENGINE *e, const char *key_id, + UI_METHOD *ui_method, void *callback_data); +static EVP_PKEY *surewarehk_load_pubkey(ENGINE *e, const char *key_id, + UI_METHOD *ui_method, void *callback_data); +static void surewarehk_ex_free(void *obj, void *item, CRYPTO_EX_DATA *ad, + int idx,long argl, void *argp); +#if 0 +static void surewarehk_dh_ex_free(void *obj, void *item, CRYPTO_EX_DATA *ad, + int idx,long argl, void *argp); +#endif + +#ifndef OPENSSL_NO_RSA +/* This function is aliased to mod_exp (with the mont stuff dropped). */ +static int surewarehk_mod_exp_mont(BIGNUM *r, const BIGNUM *a, const BIGNUM *p, + const BIGNUM *m, BN_CTX *ctx, BN_MONT_CTX *m_ctx) +{ + return surewarehk_modexp(r, a, p, m, ctx); +} + +/* Our internal RSA_METHOD that we provide pointers to */ +static RSA_METHOD surewarehk_rsa = + { + "SureWare RSA method", + NULL, /* pub_enc*/ + NULL, /* pub_dec*/ + surewarehk_rsa_sign, /* our rsa_sign is OpenSSL priv_enc*/ + surewarehk_rsa_priv_dec, /* priv_dec*/ + NULL, /*mod_exp*/ + surewarehk_mod_exp_mont, /*mod_exp_mongomery*/ + NULL, /* init*/ + NULL, /* finish*/ + 0, /* RSA flag*/ + NULL, + NULL, /* OpenSSL sign*/ + NULL, /* OpenSSL verify*/ + NULL /* keygen */ + }; +#endif + +#ifndef OPENSSL_NO_DH +/* Our internal DH_METHOD that we provide pointers to */ +/* This function is aliased to mod_exp (with the dh and mont dropped). */ +static int surewarehk_modexp_dh(const DH *dh, BIGNUM *r, const BIGNUM *a, + const BIGNUM *p, const BIGNUM *m, BN_CTX *ctx, BN_MONT_CTX *m_ctx) +{ + return surewarehk_modexp(r, a, p, m, ctx); +} + +static DH_METHOD surewarehk_dh = + { + "SureWare DH method", + NULL,/*gen_key*/ + NULL,/*agree,*/ + surewarehk_modexp_dh, /*dh mod exp*/ + NULL, /* init*/ + NULL, /* finish*/ + 0, /* flags*/ + NULL, + NULL + }; +#endif + +static RAND_METHOD surewarehk_rand = + { + /* "SureWare RAND method", */ + surewarehk_rand_seed, + surewarehk_rand_bytes, + NULL,/*cleanup*/ + surewarehk_rand_add, + surewarehk_rand_bytes, + NULL,/*rand_status*/ + }; + +#ifndef OPENSSL_NO_DSA +/* DSA stuff */ +static DSA_SIG * surewarehk_dsa_do_sign(const unsigned char *dgst, int dlen, DSA *dsa); +static int surewarehk_dsa_mod_exp(DSA *dsa, BIGNUM *rr, BIGNUM *a1, + BIGNUM *p1, BIGNUM *a2, BIGNUM *p2, BIGNUM *m, + BN_CTX *ctx, BN_MONT_CTX *in_mont) +{ + BIGNUM t; + int to_return = 0; + BN_init(&t); + /* let rr = a1 ^ p1 mod m */ + if (!surewarehk_modexp(rr,a1,p1,m,ctx)) goto end; + /* let t = a2 ^ p2 mod m */ + if (!surewarehk_modexp(&t,a2,p2,m,ctx)) goto end; + /* let rr = rr * t mod m */ + if (!BN_mod_mul(rr,rr,&t,m,ctx)) goto end; + to_return = 1; +end: + BN_free(&t); + return to_return; +} + +static DSA_METHOD surewarehk_dsa = + { + "SureWare DSA method", + surewarehk_dsa_do_sign, + NULL,/*sign setup*/ + NULL,/*verify,*/ + surewarehk_dsa_mod_exp,/*mod exp*/ + NULL,/*bn mod exp*/ + NULL, /*init*/ + NULL,/*finish*/ + 0, + NULL, + NULL, + NULL + }; +#endif + +static const char *engine_sureware_id = "sureware"; +static const char *engine_sureware_name = "SureWare hardware engine support"; + +/* Now, to our own code */ + +/* As this is only ever called once, there's no need for locking + * (indeed - the lock will already be held by our caller!!!) */ +static int bind_sureware(ENGINE *e) +{ +#ifndef OPENSSL_NO_RSA + const RSA_METHOD *meth1; +#endif +#ifndef OPENSSL_NO_DSA + const DSA_METHOD *meth2; +#endif +#ifndef OPENSSL_NO_DH + const DH_METHOD *meth3; +#endif + + if(!ENGINE_set_id(e, engine_sureware_id) || + !ENGINE_set_name(e, engine_sureware_name) || +#ifndef OPENSSL_NO_RSA + !ENGINE_set_RSA(e, &surewarehk_rsa) || +#endif +#ifndef OPENSSL_NO_DSA + !ENGINE_set_DSA(e, &surewarehk_dsa) || +#endif +#ifndef OPENSSL_NO_DH + !ENGINE_set_DH(e, &surewarehk_dh) || +#endif + !ENGINE_set_RAND(e, &surewarehk_rand) || + !ENGINE_set_destroy_function(e, surewarehk_destroy) || + !ENGINE_set_init_function(e, surewarehk_init) || + !ENGINE_set_finish_function(e, surewarehk_finish) || + !ENGINE_set_ctrl_function(e, surewarehk_ctrl) || + !ENGINE_set_load_privkey_function(e, surewarehk_load_privkey) || + !ENGINE_set_load_pubkey_function(e, surewarehk_load_pubkey)) + return 0; + +#ifndef OPENSSL_NO_RSA + /* We know that the "PKCS1_SSLeay()" functions hook properly + * to the cswift-specific mod_exp and mod_exp_crt so we use + * those functions. NB: We don't use ENGINE_openssl() or + * anything "more generic" because something like the RSAref + * code may not hook properly, and if you own one of these + * cards then you have the right to do RSA operations on it + * anyway! */ + meth1 = RSA_PKCS1_SSLeay(); + if (meth1) + { + surewarehk_rsa.rsa_pub_enc = meth1->rsa_pub_enc; + surewarehk_rsa.rsa_pub_dec = meth1->rsa_pub_dec; + } +#endif + +#ifndef OPENSSL_NO_DSA + /* Use the DSA_OpenSSL() method and just hook the mod_exp-ish + * bits. */ + meth2 = DSA_OpenSSL(); + if (meth2) + { + surewarehk_dsa.dsa_do_verify = meth2->dsa_do_verify; + } +#endif + +#ifndef OPENSSL_NO_DH + /* Much the same for Diffie-Hellman */ + meth3 = DH_OpenSSL(); + if (meth3) + { + surewarehk_dh.generate_key = meth3->generate_key; + surewarehk_dh.compute_key = meth3->compute_key; + } +#endif + + /* Ensure the sureware error handling is set up */ + ERR_load_SUREWARE_strings(); + return 1; +} + +#ifndef OPENSSL_NO_DYNAMIC_ENGINE +static int bind_helper(ENGINE *e, const char *id) + { + if(id && (strcmp(id, engine_sureware_id) != 0)) + return 0; + if(!bind_sureware(e)) + return 0; + return 1; + } +IMPLEMENT_DYNAMIC_CHECK_FN() +IMPLEMENT_DYNAMIC_BIND_FN(bind_helper) +#else +static ENGINE *engine_sureware(void) + { + ENGINE *ret = ENGINE_new(); + if(!ret) + return NULL; + if(!bind_sureware(ret)) + { + ENGINE_free(ret); + return NULL; + } + return ret; + } + +void ENGINE_load_sureware(void) + { + /* Copied from eng_[openssl|dyn].c */ + ENGINE *toadd = engine_sureware(); + if(!toadd) return; + ENGINE_add(toadd); + ENGINE_free(toadd); + ERR_clear_error(); + } +#endif + +/* This is a process-global DSO handle used for loading and unloading + * the SureWareHook library. NB: This is only set (or unset) during an + * init() or finish() call (reference counts permitting) and they're + * operating with global locks, so this should be thread-safe + * implicitly. */ +static DSO *surewarehk_dso = NULL; +#ifndef OPENSSL_NO_RSA +static int rsaHndidx = -1; /* Index for KM handle. Not really used yet. */ +#endif +#ifndef OPENSSL_NO_DSA +static int dsaHndidx = -1; /* Index for KM handle. Not really used yet. */ +#endif + +/* These are the function pointers that are (un)set when the library has + * successfully (un)loaded. */ +static SureWareHook_Init_t *p_surewarehk_Init = NULL; +static SureWareHook_Finish_t *p_surewarehk_Finish = NULL; +static SureWareHook_Rand_Bytes_t *p_surewarehk_Rand_Bytes = NULL; +static SureWareHook_Rand_Seed_t *p_surewarehk_Rand_Seed = NULL; +static SureWareHook_Load_Privkey_t *p_surewarehk_Load_Privkey = NULL; +static SureWareHook_Info_Pubkey_t *p_surewarehk_Info_Pubkey = NULL; +static SureWareHook_Load_Rsa_Pubkey_t *p_surewarehk_Load_Rsa_Pubkey = NULL; +static SureWareHook_Load_Dsa_Pubkey_t *p_surewarehk_Load_Dsa_Pubkey = NULL; +static SureWareHook_Free_t *p_surewarehk_Free=NULL; +static SureWareHook_Rsa_Priv_Dec_t *p_surewarehk_Rsa_Priv_Dec=NULL; +static SureWareHook_Rsa_Sign_t *p_surewarehk_Rsa_Sign=NULL; +static SureWareHook_Dsa_Sign_t *p_surewarehk_Dsa_Sign=NULL; +static SureWareHook_Mod_Exp_t *p_surewarehk_Mod_Exp=NULL; + +/* Used in the DSO operations. */ +static const char *surewarehk_LIBNAME = "SureWareHook"; +static const char *n_surewarehk_Init = "SureWareHook_Init"; +static const char *n_surewarehk_Finish = "SureWareHook_Finish"; +static const char *n_surewarehk_Rand_Bytes="SureWareHook_Rand_Bytes"; +static const char *n_surewarehk_Rand_Seed="SureWareHook_Rand_Seed"; +static const char *n_surewarehk_Load_Privkey="SureWareHook_Load_Privkey"; +static const char *n_surewarehk_Info_Pubkey="SureWareHook_Info_Pubkey"; +static const char *n_surewarehk_Load_Rsa_Pubkey="SureWareHook_Load_Rsa_Pubkey"; +static const char *n_surewarehk_Load_Dsa_Pubkey="SureWareHook_Load_Dsa_Pubkey"; +static const char *n_surewarehk_Free="SureWareHook_Free"; +static const char *n_surewarehk_Rsa_Priv_Dec="SureWareHook_Rsa_Priv_Dec"; +static const char *n_surewarehk_Rsa_Sign="SureWareHook_Rsa_Sign"; +static const char *n_surewarehk_Dsa_Sign="SureWareHook_Dsa_Sign"; +static const char *n_surewarehk_Mod_Exp="SureWareHook_Mod_Exp"; +static BIO *logstream = NULL; + +/* SureWareHook library functions and mechanics - these are used by the + * higher-level functions further down. NB: As and where there's no + * error checking, take a look lower down where these functions are + * called, the checking and error handling is probably down there. +*/ +static int threadsafe=1; +static int surewarehk_ctrl(ENGINE *e, int cmd, long i, void *p, void (*f)(void)) +{ + int to_return = 1; + + switch(cmd) + { + case ENGINE_CTRL_SET_LOGSTREAM: + { + BIO *bio = (BIO *)p; + CRYPTO_w_lock(CRYPTO_LOCK_ENGINE); + if (logstream) + { + BIO_free(logstream); + logstream = NULL; + } + if (CRYPTO_add(&bio->references,1,CRYPTO_LOCK_BIO) > 1) + logstream = bio; + else + SUREWAREerr(SUREWARE_F_SUREWAREHK_CTRL,SUREWARE_R_BIO_WAS_FREED); + } + CRYPTO_w_unlock(CRYPTO_LOCK_ENGINE); + break; + /* This will prevent the initialisation function from "installing" + * the mutex-handling callbacks, even if they are available from + * within the library (or were provided to the library from the + * calling application). This is to remove any baggage for + * applications not using multithreading. */ + case ENGINE_CTRL_CHIL_NO_LOCKING: + CRYPTO_w_lock(CRYPTO_LOCK_ENGINE); + threadsafe = 0; + CRYPTO_w_unlock(CRYPTO_LOCK_ENGINE); + break; + + /* The command isn't understood by this engine */ + default: + SUREWAREerr(SUREWARE_F_SUREWAREHK_CTRL, + ENGINE_R_CTRL_COMMAND_NOT_IMPLEMENTED); + to_return = 0; + break; + } + + return to_return; +} + +/* Destructor (complements the "ENGINE_surewarehk()" constructor) */ +static int surewarehk_destroy(ENGINE *e) +{ + ERR_unload_SUREWARE_strings(); + return 1; +} + +/* (de)initialisation functions. */ +static int surewarehk_init(ENGINE *e) +{ + char msg[64]="ENGINE_init"; + SureWareHook_Init_t *p1=NULL; + SureWareHook_Finish_t *p2=NULL; + SureWareHook_Rand_Bytes_t *p3=NULL; + SureWareHook_Rand_Seed_t *p4=NULL; + SureWareHook_Load_Privkey_t *p5=NULL; + SureWareHook_Load_Rsa_Pubkey_t *p6=NULL; + SureWareHook_Free_t *p7=NULL; + SureWareHook_Rsa_Priv_Dec_t *p8=NULL; + SureWareHook_Rsa_Sign_t *p9=NULL; + SureWareHook_Dsa_Sign_t *p12=NULL; + SureWareHook_Info_Pubkey_t *p13=NULL; + SureWareHook_Load_Dsa_Pubkey_t *p14=NULL; + SureWareHook_Mod_Exp_t *p15=NULL; + + if(surewarehk_dso != NULL) + { + SUREWAREerr(SUREWARE_F_SUREWAREHK_INIT,ENGINE_R_ALREADY_LOADED); + goto err; + } + /* Attempt to load libsurewarehk.so/surewarehk.dll/whatever. */ + surewarehk_dso = DSO_load(NULL, surewarehk_LIBNAME, NULL, 0); + if(surewarehk_dso == NULL) + { + SUREWAREerr(SUREWARE_F_SUREWAREHK_INIT,ENGINE_R_DSO_FAILURE); + goto err; + } + if(!(p1=(SureWareHook_Init_t*)DSO_bind_func(surewarehk_dso, n_surewarehk_Init)) || + !(p2=(SureWareHook_Finish_t*)DSO_bind_func(surewarehk_dso, n_surewarehk_Finish)) || + !(p3=(SureWareHook_Rand_Bytes_t*)DSO_bind_func(surewarehk_dso, n_surewarehk_Rand_Bytes)) || + !(p4=(SureWareHook_Rand_Seed_t*)DSO_bind_func(surewarehk_dso, n_surewarehk_Rand_Seed)) || + !(p5=(SureWareHook_Load_Privkey_t*)DSO_bind_func(surewarehk_dso, n_surewarehk_Load_Privkey)) || + !(p6=(SureWareHook_Load_Rsa_Pubkey_t*)DSO_bind_func(surewarehk_dso, n_surewarehk_Load_Rsa_Pubkey)) || + !(p7=(SureWareHook_Free_t*)DSO_bind_func(surewarehk_dso, n_surewarehk_Free)) || + !(p8=(SureWareHook_Rsa_Priv_Dec_t*)DSO_bind_func(surewarehk_dso, n_surewarehk_Rsa_Priv_Dec)) || + !(p9=(SureWareHook_Rsa_Sign_t*)DSO_bind_func(surewarehk_dso, n_surewarehk_Rsa_Sign)) || + !(p12=(SureWareHook_Dsa_Sign_t*)DSO_bind_func(surewarehk_dso, n_surewarehk_Dsa_Sign)) || + !(p13=(SureWareHook_Info_Pubkey_t*)DSO_bind_func(surewarehk_dso, n_surewarehk_Info_Pubkey)) || + !(p14=(SureWareHook_Load_Dsa_Pubkey_t*)DSO_bind_func(surewarehk_dso, n_surewarehk_Load_Dsa_Pubkey)) || + !(p15=(SureWareHook_Mod_Exp_t*)DSO_bind_func(surewarehk_dso, n_surewarehk_Mod_Exp))) + { + SUREWAREerr(SUREWARE_F_SUREWAREHK_INIT,ENGINE_R_DSO_FAILURE); + goto err; + } + /* Copy the pointers */ + p_surewarehk_Init = p1; + p_surewarehk_Finish = p2; + p_surewarehk_Rand_Bytes = p3; + p_surewarehk_Rand_Seed = p4; + p_surewarehk_Load_Privkey = p5; + p_surewarehk_Load_Rsa_Pubkey = p6; + p_surewarehk_Free = p7; + p_surewarehk_Rsa_Priv_Dec = p8; + p_surewarehk_Rsa_Sign = p9; + p_surewarehk_Dsa_Sign = p12; + p_surewarehk_Info_Pubkey = p13; + p_surewarehk_Load_Dsa_Pubkey = p14; + p_surewarehk_Mod_Exp = p15; + /* Contact the hardware and initialises it. */ + if(p_surewarehk_Init(msg,threadsafe)==SUREWAREHOOK_ERROR_UNIT_FAILURE) + { + SUREWAREerr(SUREWARE_F_SUREWAREHK_INIT,SUREWARE_R_UNIT_FAILURE); + goto err; + } + if(p_surewarehk_Init(msg,threadsafe)==SUREWAREHOOK_ERROR_UNIT_FAILURE) + { + SUREWAREerr(SUREWARE_F_SUREWAREHK_INIT,SUREWARE_R_UNIT_FAILURE); + goto err; + } + /* try to load the default private key, if failed does not return a failure but + wait for an explicit ENGINE_load_privakey */ + surewarehk_load_privkey(e,NULL,NULL,NULL); + + /* Everything's fine. */ +#ifndef OPENSSL_NO_RSA + if (rsaHndidx == -1) + rsaHndidx = RSA_get_ex_new_index(0, + "SureWareHook RSA key handle", + NULL, NULL, surewarehk_ex_free); +#endif +#ifndef OPENSSL_NO_DSA + if (dsaHndidx == -1) + dsaHndidx = DSA_get_ex_new_index(0, + "SureWareHook DSA key handle", + NULL, NULL, surewarehk_ex_free); +#endif + + return 1; +err: + if(surewarehk_dso) + DSO_free(surewarehk_dso); + surewarehk_dso = NULL; + p_surewarehk_Init = NULL; + p_surewarehk_Finish = NULL; + p_surewarehk_Rand_Bytes = NULL; + p_surewarehk_Rand_Seed = NULL; + p_surewarehk_Load_Privkey = NULL; + p_surewarehk_Load_Rsa_Pubkey = NULL; + p_surewarehk_Free = NULL; + p_surewarehk_Rsa_Priv_Dec = NULL; + p_surewarehk_Rsa_Sign = NULL; + p_surewarehk_Dsa_Sign = NULL; + p_surewarehk_Info_Pubkey = NULL; + p_surewarehk_Load_Dsa_Pubkey = NULL; + p_surewarehk_Mod_Exp = NULL; + return 0; +} + +static int surewarehk_finish(ENGINE *e) +{ + int to_return = 1; + if(surewarehk_dso == NULL) + { + SUREWAREerr(SUREWARE_F_SUREWAREHK_FINISH,ENGINE_R_NOT_LOADED); + to_return = 0; + goto err; + } + p_surewarehk_Finish(); + if(!DSO_free(surewarehk_dso)) + { + SUREWAREerr(SUREWARE_F_SUREWAREHK_FINISH,ENGINE_R_DSO_FAILURE); + to_return = 0; + goto err; + } + err: + if (logstream) + BIO_free(logstream); + surewarehk_dso = NULL; + p_surewarehk_Init = NULL; + p_surewarehk_Finish = NULL; + p_surewarehk_Rand_Bytes = NULL; + p_surewarehk_Rand_Seed = NULL; + p_surewarehk_Load_Privkey = NULL; + p_surewarehk_Load_Rsa_Pubkey = NULL; + p_surewarehk_Free = NULL; + p_surewarehk_Rsa_Priv_Dec = NULL; + p_surewarehk_Rsa_Sign = NULL; + p_surewarehk_Dsa_Sign = NULL; + p_surewarehk_Info_Pubkey = NULL; + p_surewarehk_Load_Dsa_Pubkey = NULL; + p_surewarehk_Mod_Exp = NULL; + return to_return; +} + +static void surewarehk_error_handling(char *const msg,int func,int ret) +{ + switch (ret) + { + case SUREWAREHOOK_ERROR_UNIT_FAILURE: + ENGINEerr(func,SUREWARE_R_UNIT_FAILURE); + break; + case SUREWAREHOOK_ERROR_FALLBACK: + ENGINEerr(func,SUREWARE_R_REQUEST_FALLBACK); + break; + case SUREWAREHOOK_ERROR_DATA_SIZE: + ENGINEerr(func,SUREWARE_R_SIZE_TOO_LARGE_OR_TOO_SMALL); + break; + case SUREWAREHOOK_ERROR_INVALID_PAD: + ENGINEerr(func,SUREWARE_R_PADDING_CHECK_FAILED); + break; + default: + ENGINEerr(func,SUREWARE_R_REQUEST_FAILED); + break; + case 1:/*nothing*/ + msg[0]='\0'; + } + if (*msg) + { + ERR_add_error_data(1,msg); + if (logstream) + { + CRYPTO_w_lock(CRYPTO_LOCK_BIO); + BIO_write(logstream, msg, strlen(msg)); + CRYPTO_w_unlock(CRYPTO_LOCK_BIO); + } + } +} + +static int surewarehk_rand_bytes(unsigned char *buf, int num) +{ + int ret=0; + char msg[64]="ENGINE_rand_bytes"; + if(!p_surewarehk_Rand_Bytes) + { + SUREWAREerr(SUREWARE_F_SUREWAREHK_RAND_BYTES,ENGINE_R_NOT_INITIALISED); + } + else + { + ret = p_surewarehk_Rand_Bytes(msg,buf, num); + surewarehk_error_handling(msg,SUREWARE_F_SUREWAREHK_RAND_BYTES,ret); + } + return ret==1 ? 1 : 0; +} + +static void surewarehk_rand_seed(const void *buf, int num) +{ + int ret=0; + char msg[64]="ENGINE_rand_seed"; + if(!p_surewarehk_Rand_Seed) + { + SUREWAREerr(SUREWARE_F_SUREWAREHK_RAND_SEED,ENGINE_R_NOT_INITIALISED); + } + else + { + ret = p_surewarehk_Rand_Seed(msg,buf, num); + surewarehk_error_handling(msg,SUREWARE_F_SUREWAREHK_RAND_SEED,ret); + } +} + +static void surewarehk_rand_add(const void *buf, int num, double entropy) +{ + surewarehk_rand_seed(buf,num); +} + +static EVP_PKEY* sureware_load_public(ENGINE *e,const char *key_id,char *hptr,unsigned long el,char keytype) +{ + EVP_PKEY *res = NULL; +#ifndef OPENSSL_NO_RSA + RSA *rsatmp = NULL; +#endif +#ifndef OPENSSL_NO_DSA + DSA *dsatmp=NULL; +#endif + char msg[64]="sureware_load_public"; + int ret=0; + if(!p_surewarehk_Load_Rsa_Pubkey || !p_surewarehk_Load_Dsa_Pubkey) + { + SUREWAREerr(SUREWARE_F_SUREWARE_LOAD_PUBLIC,ENGINE_R_NOT_INITIALISED); + goto err; + } + switch (keytype) + { +#ifndef OPENSSL_NO_RSA + case 1: /*RSA*/ + /* set private external reference */ + rsatmp = RSA_new_method(e); + RSA_set_ex_data(rsatmp,rsaHndidx,hptr); + rsatmp->flags |= RSA_FLAG_EXT_PKEY; + + /* set public big nums*/ + rsatmp->e = BN_new(); + rsatmp->n = BN_new(); + bn_expand2(rsatmp->e, el/sizeof(BN_ULONG)); + bn_expand2(rsatmp->n, el/sizeof(BN_ULONG)); + if (!rsatmp->e || rsatmp->e->dmax!=(int)(el/sizeof(BN_ULONG))|| + !rsatmp->n || rsatmp->n->dmax!=(int)(el/sizeof(BN_ULONG))) + goto err; + ret=p_surewarehk_Load_Rsa_Pubkey(msg,key_id,el, + (unsigned long *)rsatmp->n->d, + (unsigned long *)rsatmp->e->d); + surewarehk_error_handling(msg,SUREWARE_F_SUREWARE_LOAD_PUBLIC,ret); + if (ret!=1) + { + SUREWAREerr(SUREWARE_F_SUREWARE_LOAD_PUBLIC,ENGINE_R_FAILED_LOADING_PUBLIC_KEY); + goto err; + } + /* normalise pub e and pub n */ + rsatmp->e->top=el/sizeof(BN_ULONG); + bn_fix_top(rsatmp->e); + rsatmp->n->top=el/sizeof(BN_ULONG); + bn_fix_top(rsatmp->n); + /* create an EVP object: engine + rsa key */ + res = EVP_PKEY_new(); + EVP_PKEY_assign_RSA(res, rsatmp); + break; +#endif + +#ifndef OPENSSL_NO_DSA + case 2:/*DSA*/ + /* set private/public external reference */ + dsatmp = DSA_new_method(e); + DSA_set_ex_data(dsatmp,dsaHndidx,hptr); + /*dsatmp->flags |= DSA_FLAG_EXT_PKEY;*/ + + /* set public key*/ + dsatmp->pub_key = BN_new(); + dsatmp->p = BN_new(); + dsatmp->q = BN_new(); + dsatmp->g = BN_new(); + bn_expand2(dsatmp->pub_key, el/sizeof(BN_ULONG)); + bn_expand2(dsatmp->p, el/sizeof(BN_ULONG)); + bn_expand2(dsatmp->q, 20/sizeof(BN_ULONG)); + bn_expand2(dsatmp->g, el/sizeof(BN_ULONG)); + if (!dsatmp->pub_key || dsatmp->pub_key->dmax!=(int)(el/sizeof(BN_ULONG))|| + !dsatmp->p || dsatmp->p->dmax!=(int)(el/sizeof(BN_ULONG)) || + !dsatmp->q || dsatmp->q->dmax!=20/sizeof(BN_ULONG) || + !dsatmp->g || dsatmp->g->dmax!=(int)(el/sizeof(BN_ULONG))) + goto err; + + ret=p_surewarehk_Load_Dsa_Pubkey(msg,key_id,el, + (unsigned long *)dsatmp->pub_key->d, + (unsigned long *)dsatmp->p->d, + (unsigned long *)dsatmp->q->d, + (unsigned long *)dsatmp->g->d); + surewarehk_error_handling(msg,SUREWARE_F_SUREWARE_LOAD_PUBLIC,ret); + if (ret!=1) + { + SUREWAREerr(SUREWARE_F_SUREWARE_LOAD_PUBLIC,ENGINE_R_FAILED_LOADING_PUBLIC_KEY); + goto err; + } + /* set parameters */ + /* normalise pubkey and parameters in case of */ + dsatmp->pub_key->top=el/sizeof(BN_ULONG); + bn_fix_top(dsatmp->pub_key); + dsatmp->p->top=el/sizeof(BN_ULONG); + bn_fix_top(dsatmp->p); + dsatmp->q->top=20/sizeof(BN_ULONG); + bn_fix_top(dsatmp->q); + dsatmp->g->top=el/sizeof(BN_ULONG); + bn_fix_top(dsatmp->g); + + /* create an EVP object: engine + rsa key */ + res = EVP_PKEY_new(); + EVP_PKEY_assign_DSA(res, dsatmp); + break; +#endif + + default: + SUREWAREerr(SUREWARE_F_SUREWARE_LOAD_PUBLIC,ENGINE_R_FAILED_LOADING_PRIVATE_KEY); + goto err; + } + return res; + err: +#ifndef OPENSSL_NO_RSA + if (rsatmp) + RSA_free(rsatmp); +#endif +#ifndef OPENSSL_NO_DSA + if (dsatmp) + DSA_free(dsatmp); +#endif + return NULL; +} + +static EVP_PKEY *surewarehk_load_privkey(ENGINE *e, const char *key_id, + UI_METHOD *ui_method, void *callback_data) +{ + EVP_PKEY *res = NULL; + int ret=0; + unsigned long el=0; + char *hptr=NULL; + char keytype=0; + char msg[64]="ENGINE_load_privkey"; + + if(!p_surewarehk_Load_Privkey) + { + SUREWAREerr(SUREWARE_F_SUREWAREHK_LOAD_PRIVKEY,ENGINE_R_NOT_INITIALISED); + } + else + { + ret=p_surewarehk_Load_Privkey(msg,key_id,&hptr,&el,&keytype); + if (ret!=1) + { + SUREWAREerr(SUREWARE_F_SUREWAREHK_LOAD_PRIVKEY,ENGINE_R_FAILED_LOADING_PRIVATE_KEY); + ERR_add_error_data(1,msg); + } + else + res=sureware_load_public(e,key_id,hptr,el,keytype); + } + return res; +} + +static EVP_PKEY *surewarehk_load_pubkey(ENGINE *e, const char *key_id, + UI_METHOD *ui_method, void *callback_data) +{ + EVP_PKEY *res = NULL; + int ret=0; + unsigned long el=0; + char *hptr=NULL; + char keytype=0; + char msg[64]="ENGINE_load_pubkey"; + + if(!p_surewarehk_Info_Pubkey) + { + SUREWAREerr(SUREWARE_F_SUREWAREHK_LOAD_PUBKEY,ENGINE_R_NOT_INITIALISED); + } + else + { + /* call once to identify if DSA or RSA */ + ret=p_surewarehk_Info_Pubkey(msg,key_id,&el,&keytype); + if (ret!=1) + { + SUREWAREerr(SUREWARE_F_SUREWAREHK_LOAD_PUBKEY,ENGINE_R_FAILED_LOADING_PUBLIC_KEY); + ERR_add_error_data(1,msg); + } + else + res=sureware_load_public(e,key_id,hptr,el,keytype); + } + return res; +} + +/* This cleans up an RSA/DSA KM key(do not destroy the key into the hardware) +, called when ex_data is freed */ +static void surewarehk_ex_free(void *obj, void *item, CRYPTO_EX_DATA *ad, + int idx,long argl, void *argp) +{ + if(!p_surewarehk_Free) + { + SUREWAREerr(SUREWARE_F_SUREWAREHK_EX_FREE,ENGINE_R_NOT_INITIALISED); + } + else + p_surewarehk_Free((char *)item,0); +} + +#if 0 +/* not currently used (bug?) */ +/* This cleans up an DH KM key (destroys the key into hardware), +called when ex_data is freed */ +static void surewarehk_dh_ex_free(void *obj, void *item, CRYPTO_EX_DATA *ad, + int idx,long argl, void *argp) +{ + if(!p_surewarehk_Free) + { + SUREWAREerr(SUREWARE_F_SUREWAREHK_DH_EX_FREE,ENGINE_R_NOT_INITIALISED); + } + else + p_surewarehk_Free((char *)item,1); +} +#endif + +/* +* return number of decrypted bytes +*/ +#ifndef OPENSSL_NO_RSA +static int surewarehk_rsa_priv_dec(int flen,const unsigned char *from,unsigned char *to, + RSA *rsa,int padding) +{ + int ret=0,tlen; + char *buf=NULL,*hptr=NULL; + char msg[64]="ENGINE_rsa_priv_dec"; + if (!p_surewarehk_Rsa_Priv_Dec) + { + SUREWAREerr(SUREWARE_F_SUREWAREHK_RSA_PRIV_DEC,ENGINE_R_NOT_INITIALISED); + } + /* extract ref to private key */ + else if (!(hptr=RSA_get_ex_data(rsa, rsaHndidx))) + { + SUREWAREerr(SUREWARE_F_SUREWAREHK_RSA_PRIV_DEC,SUREWARE_R_MISSING_KEY_COMPONENTS); + goto err; + } + /* analyse what padding we can do into the hardware */ + if (padding==RSA_PKCS1_PADDING) + { + /* do it one shot */ + ret=p_surewarehk_Rsa_Priv_Dec(msg,flen,(unsigned char *)from,&tlen,to,hptr,SUREWARE_PKCS1_PAD); + surewarehk_error_handling(msg,SUREWARE_F_SUREWAREHK_RSA_PRIV_DEC,ret); + if (ret!=1) + goto err; + ret=tlen; + } + else /* do with no padding into hardware */ + { + ret=p_surewarehk_Rsa_Priv_Dec(msg,flen,(unsigned char *)from,&tlen,to,hptr,SUREWARE_NO_PAD); + surewarehk_error_handling(msg,SUREWARE_F_SUREWAREHK_RSA_PRIV_DEC,ret); + if (ret!=1) + goto err; + /* intermediate buffer for padding */ + if ((buf=OPENSSL_malloc(tlen)) == NULL) + { + SUREWAREerr(SUREWARE_F_SUREWAREHK_RSA_PRIV_DEC,ERR_R_MALLOC_FAILURE); + goto err; + } + memcpy(buf,to,tlen);/* transfert to into buf */ + switch (padding) /* check padding in software */ + { +#ifndef OPENSSL_NO_SHA + case RSA_PKCS1_OAEP_PADDING: + ret=RSA_padding_check_PKCS1_OAEP(to,tlen,(unsigned char *)buf,tlen,tlen,NULL,0); + break; +#endif + case RSA_SSLV23_PADDING: + ret=RSA_padding_check_SSLv23(to,tlen,(unsigned char *)buf,flen,tlen); + break; + case RSA_NO_PADDING: + ret=RSA_padding_check_none(to,tlen,(unsigned char *)buf,flen,tlen); + break; + default: + SUREWAREerr(SUREWARE_F_SUREWAREHK_RSA_PRIV_DEC,SUREWARE_R_UNKNOWN_PADDING_TYPE); + goto err; + } + if (ret < 0) + SUREWAREerr(SUREWARE_F_SUREWAREHK_RSA_PRIV_DEC,SUREWARE_R_PADDING_CHECK_FAILED); + } +err: + if (buf) + { + OPENSSL_cleanse(buf,tlen); + OPENSSL_free(buf); + } + return ret; +} + +/* +* Does what OpenSSL rsa_priv_enc does. +*/ +static int surewarehk_rsa_sign(int flen,const unsigned char *from,unsigned char *to, + RSA *rsa,int padding) +{ + int ret=0,tlen; + char *hptr=NULL; + char msg[64]="ENGINE_rsa_sign"; + if (!p_surewarehk_Rsa_Sign) + { + SUREWAREerr(SUREWARE_F_SUREWAREHK_RSA_SIGN,ENGINE_R_NOT_INITIALISED); + } + /* extract ref to private key */ + else if (!(hptr=RSA_get_ex_data(rsa, rsaHndidx))) + { + SUREWAREerr(SUREWARE_F_SUREWAREHK_RSA_SIGN,SUREWARE_R_MISSING_KEY_COMPONENTS); + } + else + { + switch (padding) + { + case RSA_PKCS1_PADDING: /* do it in one shot */ + ret=p_surewarehk_Rsa_Sign(msg,flen,(unsigned char *)from,&tlen,to,hptr,SUREWARE_PKCS1_PAD); + surewarehk_error_handling(msg,SUREWARE_F_SUREWAREHK_RSA_SIGN,ret); + break; + case RSA_NO_PADDING: + default: + SUREWAREerr(SUREWARE_F_SUREWAREHK_RSA_SIGN,SUREWARE_R_UNKNOWN_PADDING_TYPE); + } + } + return ret==1 ? tlen : ret; +} + +#endif + +#ifndef OPENSSL_NO_DSA +/* DSA sign and verify */ +static DSA_SIG * surewarehk_dsa_do_sign(const unsigned char *from, int flen, DSA *dsa) +{ + int ret=0; + char *hptr=NULL; + DSA_SIG *psign=NULL; + char msg[64]="ENGINE_dsa_do_sign"; + if (!p_surewarehk_Dsa_Sign) + { + SUREWAREerr(SUREWARE_F_SUREWAREHK_DSA_DO_SIGN,ENGINE_R_NOT_INITIALISED); + goto err; + } + /* extract ref to private key */ + else if (!(hptr=DSA_get_ex_data(dsa, dsaHndidx))) + { + SUREWAREerr(SUREWARE_F_SUREWAREHK_DSA_DO_SIGN,SUREWARE_R_MISSING_KEY_COMPONENTS); + goto err; + } + else + { + if((psign = DSA_SIG_new()) == NULL) + { + SUREWAREerr(SUREWARE_F_SUREWAREHK_DSA_DO_SIGN,ERR_R_MALLOC_FAILURE); + goto err; + } + psign->r=BN_new(); + psign->s=BN_new(); + bn_expand2(psign->r, 20/sizeof(BN_ULONG)); + bn_expand2(psign->s, 20/sizeof(BN_ULONG)); + if (!psign->r || psign->r->dmax!=20/sizeof(BN_ULONG) || + !psign->s || psign->s->dmax!=20/sizeof(BN_ULONG)) + goto err; + ret=p_surewarehk_Dsa_Sign(msg,flen,from, + (unsigned long *)psign->r->d, + (unsigned long *)psign->s->d, + hptr); + surewarehk_error_handling(msg,SUREWARE_F_SUREWAREHK_DSA_DO_SIGN,ret); + } + psign->r->top=20/sizeof(BN_ULONG); + bn_fix_top(psign->r); + psign->s->top=20/sizeof(BN_ULONG); + bn_fix_top(psign->s); + +err: + if (psign) + { + DSA_SIG_free(psign); + psign=NULL; + } + return psign; +} +#endif + +static int surewarehk_modexp(BIGNUM *r, const BIGNUM *a, const BIGNUM *p, + const BIGNUM *m, BN_CTX *ctx) +{ + int ret=0; + char msg[64]="ENGINE_modexp"; + if (!p_surewarehk_Mod_Exp) + { + SUREWAREerr(SUREWARE_F_SUREWAREHK_MODEXP,ENGINE_R_NOT_INITIALISED); + } + else + { + bn_expand2(r,m->top); + if (r && r->dmax==m->top) + { + /* do it*/ + ret=p_surewarehk_Mod_Exp(msg, + m->top*sizeof(BN_ULONG), + (unsigned long *)m->d, + p->top*sizeof(BN_ULONG), + (unsigned long *)p->d, + a->top*sizeof(BN_ULONG), + (unsigned long *)a->d, + (unsigned long *)r->d); + surewarehk_error_handling(msg,SUREWARE_F_SUREWAREHK_MODEXP,ret); + if (ret==1) + { + /* normalise result */ + r->top=m->top; + bn_fix_top(r); + } + } + } + return ret; +} +#endif /* !OPENSSL_NO_HW_SureWare */ +#endif /* !OPENSSL_NO_HW */ diff --git a/node-v0.8.14/deps/openssl/openssl/engines/e_sureware.ec b/node-v0.8.14/deps/openssl/openssl/engines/e_sureware.ec new file mode 100644 index 0000000..3d266b8 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/engines/e_sureware.ec @@ -0,0 +1 @@ +L SUREWARE e_sureware_err.h e_sureware_err.c diff --git a/node-v0.8.14/deps/openssl/openssl/engines/e_sureware_err.c b/node-v0.8.14/deps/openssl/openssl/engines/e_sureware_err.c new file mode 100644 index 0000000..d4ca68c --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/engines/e_sureware_err.c @@ -0,0 +1,158 @@ +/* e_sureware_err.c */ +/* ==================================================================== + * Copyright (c) 1999-2005 The OpenSSL Project. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. All advertising materials mentioning features or use of this + * software must display the following acknowledgment: + * "This product includes software developed by the OpenSSL Project + * for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)" + * + * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to + * endorse or promote products derived from this software without + * prior written permission. For written permission, please contact + * openssl-core@OpenSSL.org. + * + * 5. Products derived from this software may not be called "OpenSSL" + * nor may "OpenSSL" appear in their names without prior written + * permission of the OpenSSL Project. + * + * 6. Redistributions of any form whatsoever must retain the following + * acknowledgment: + * "This product includes software developed by the OpenSSL Project + * for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)" + * + * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY + * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR + * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, + * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * ==================================================================== + * + * This product includes cryptographic software written by Eric Young + * (eay@cryptsoft.com). This product includes software written by Tim + * Hudson (tjh@cryptsoft.com). + * + */ + +/* NOTE: this file was auto generated by the mkerr.pl script: any changes + * made to it will be overwritten when the script next updates this file, + * only reason strings will be preserved. + */ + +#include +#include +#include "e_sureware_err.h" + +/* BEGIN ERROR CODES */ +#ifndef OPENSSL_NO_ERR + +#define ERR_FUNC(func) ERR_PACK(0,func,0) +#define ERR_REASON(reason) ERR_PACK(0,0,reason) + +static ERR_STRING_DATA SUREWARE_str_functs[]= + { +{ERR_FUNC(SUREWARE_F_SUREWAREHK_CTRL), "SUREWAREHK_CTRL"}, +{ERR_FUNC(SUREWARE_F_SUREWAREHK_DH_EX_FREE), "SUREWAREHK_DH_EX_FREE"}, +{ERR_FUNC(SUREWARE_F_SUREWAREHK_DSA_DO_SIGN), "SUREWAREHK_DSA_DO_SIGN"}, +{ERR_FUNC(SUREWARE_F_SUREWAREHK_EX_FREE), "SUREWAREHK_EX_FREE"}, +{ERR_FUNC(SUREWARE_F_SUREWAREHK_FINISH), "SUREWAREHK_FINISH"}, +{ERR_FUNC(SUREWARE_F_SUREWAREHK_INIT), "SUREWAREHK_INIT"}, +{ERR_FUNC(SUREWARE_F_SUREWAREHK_LOAD_PRIVKEY), "SUREWAREHK_LOAD_PRIVKEY"}, +{ERR_FUNC(SUREWARE_F_SUREWAREHK_LOAD_PUBKEY), "SUREWAREHK_LOAD_PUBKEY"}, +{ERR_FUNC(SUREWARE_F_SUREWAREHK_MODEXP), "SUREWAREHK_MODEXP"}, +{ERR_FUNC(SUREWARE_F_SUREWAREHK_RAND_BYTES), "SUREWAREHK_RAND_BYTES"}, +{ERR_FUNC(SUREWARE_F_SUREWAREHK_RAND_SEED), "SUREWAREHK_RAND_SEED"}, +{ERR_FUNC(SUREWARE_F_SUREWAREHK_RSA_PRIV_DEC), "SUREWAREHK_RSA_PRIV_DEC"}, +{ERR_FUNC(SUREWARE_F_SUREWAREHK_RSA_SIGN), "SUREWAREHK_RSA_SIGN"}, +{ERR_FUNC(SUREWARE_F_SUREWARE_LOAD_PUBLIC), "SUREWARE_LOAD_PUBLIC"}, +{0,NULL} + }; + +static ERR_STRING_DATA SUREWARE_str_reasons[]= + { +{ERR_REASON(SUREWARE_R_BIO_WAS_FREED) ,"bio was freed"}, +{ERR_REASON(SUREWARE_R_MISSING_KEY_COMPONENTS),"missing key components"}, +{ERR_REASON(SUREWARE_R_PADDING_CHECK_FAILED),"padding check failed"}, +{ERR_REASON(SUREWARE_R_REQUEST_FAILED) ,"request failed"}, +{ERR_REASON(SUREWARE_R_REQUEST_FALLBACK) ,"request fallback"}, +{ERR_REASON(SUREWARE_R_SIZE_TOO_LARGE_OR_TOO_SMALL),"size too large or too small"}, +{ERR_REASON(SUREWARE_R_UNIT_FAILURE) ,"unit failure"}, +{ERR_REASON(SUREWARE_R_UNKNOWN_PADDING_TYPE),"unknown padding type"}, +{0,NULL} + }; + +#endif + +#ifdef SUREWARE_LIB_NAME +static ERR_STRING_DATA SUREWARE_lib_name[]= + { +{0 ,SUREWARE_LIB_NAME}, +{0,NULL} + }; +#endif + + +static int SUREWARE_lib_error_code=0; +static int SUREWARE_error_init=1; + +static void ERR_load_SUREWARE_strings(void) + { + if (SUREWARE_lib_error_code == 0) + SUREWARE_lib_error_code=ERR_get_next_error_library(); + + if (SUREWARE_error_init) + { + SUREWARE_error_init=0; +#ifndef OPENSSL_NO_ERR + ERR_load_strings(SUREWARE_lib_error_code,SUREWARE_str_functs); + ERR_load_strings(SUREWARE_lib_error_code,SUREWARE_str_reasons); +#endif + +#ifdef SUREWARE_LIB_NAME + SUREWARE_lib_name->error = ERR_PACK(SUREWARE_lib_error_code,0,0); + ERR_load_strings(0,SUREWARE_lib_name); +#endif + } + } + +static void ERR_unload_SUREWARE_strings(void) + { + if (SUREWARE_error_init == 0) + { +#ifndef OPENSSL_NO_ERR + ERR_unload_strings(SUREWARE_lib_error_code,SUREWARE_str_functs); + ERR_unload_strings(SUREWARE_lib_error_code,SUREWARE_str_reasons); +#endif + +#ifdef SUREWARE_LIB_NAME + ERR_unload_strings(0,SUREWARE_lib_name); +#endif + SUREWARE_error_init=1; + } + } + +static void ERR_SUREWARE_error(int function, int reason, char *file, int line) + { + if (SUREWARE_lib_error_code == 0) + SUREWARE_lib_error_code=ERR_get_next_error_library(); + ERR_PUT_error(SUREWARE_lib_error_code,function,reason,file,line); + } diff --git a/node-v0.8.14/deps/openssl/openssl/engines/e_sureware_err.h b/node-v0.8.14/deps/openssl/openssl/engines/e_sureware_err.h new file mode 100644 index 0000000..ec8ed0c --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/engines/e_sureware_err.h @@ -0,0 +1,102 @@ +/* ==================================================================== + * Copyright (c) 2001 The OpenSSL Project. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. All advertising materials mentioning features or use of this + * software must display the following acknowledgment: + * "This product includes software developed by the OpenSSL Project + * for use in the OpenSSL Toolkit. (http://www.openssl.org/)" + * + * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to + * endorse or promote products derived from this software without + * prior written permission. For written permission, please contact + * openssl-core@openssl.org. + * + * 5. Products derived from this software may not be called "OpenSSL" + * nor may "OpenSSL" appear in their names without prior written + * permission of the OpenSSL Project. + * + * 6. Redistributions of any form whatsoever must retain the following + * acknowledgment: + * "This product includes software developed by the OpenSSL Project + * for use in the OpenSSL Toolkit (http://www.openssl.org/)" + * + * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY + * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR + * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, + * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * ==================================================================== + * + * This product includes cryptographic software written by Eric Young + * (eay@cryptsoft.com). This product includes software written by Tim + * Hudson (tjh@cryptsoft.com). + * + */ + +#ifndef HEADER_SUREWARE_ERR_H +#define HEADER_SUREWARE_ERR_H + +#ifdef __cplusplus +extern "C" { +#endif + +/* BEGIN ERROR CODES */ +/* The following lines are auto generated by the script mkerr.pl. Any changes + * made after this point may be overwritten when the script is next run. + */ +static void ERR_load_SUREWARE_strings(void); +static void ERR_unload_SUREWARE_strings(void); +static void ERR_SUREWARE_error(int function, int reason, char *file, int line); +#define SUREWAREerr(f,r) ERR_SUREWARE_error((f),(r),__FILE__,__LINE__) + +/* Error codes for the SUREWARE functions. */ + +/* Function codes. */ +#define SUREWARE_F_SUREWAREHK_CTRL 100 +#define SUREWARE_F_SUREWAREHK_DH_EX_FREE 112 +#define SUREWARE_F_SUREWAREHK_DSA_DO_SIGN 101 +#define SUREWARE_F_SUREWAREHK_EX_FREE 102 +#define SUREWARE_F_SUREWAREHK_FINISH 103 +#define SUREWARE_F_SUREWAREHK_INIT 104 +#define SUREWARE_F_SUREWAREHK_LOAD_PRIVKEY 105 +#define SUREWARE_F_SUREWAREHK_LOAD_PUBKEY 113 +#define SUREWARE_F_SUREWAREHK_MODEXP 107 +#define SUREWARE_F_SUREWAREHK_RAND_BYTES 108 +#define SUREWARE_F_SUREWAREHK_RAND_SEED 109 +#define SUREWARE_F_SUREWAREHK_RSA_PRIV_DEC 110 +#define SUREWARE_F_SUREWAREHK_RSA_SIGN 111 +#define SUREWARE_F_SUREWARE_LOAD_PUBLIC 106 + +/* Reason codes. */ +#define SUREWARE_R_BIO_WAS_FREED 100 +#define SUREWARE_R_MISSING_KEY_COMPONENTS 105 +#define SUREWARE_R_PADDING_CHECK_FAILED 106 +#define SUREWARE_R_REQUEST_FAILED 101 +#define SUREWARE_R_REQUEST_FALLBACK 102 +#define SUREWARE_R_SIZE_TOO_LARGE_OR_TOO_SMALL 103 +#define SUREWARE_R_UNIT_FAILURE 104 +#define SUREWARE_R_UNKNOWN_PADDING_TYPE 107 + +#ifdef __cplusplus +} +#endif +#endif diff --git a/node-v0.8.14/deps/openssl/openssl/engines/e_ubsec.c b/node-v0.8.14/deps/openssl/openssl/engines/e_ubsec.c new file mode 100644 index 0000000..aa5709b --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/engines/e_ubsec.c @@ -0,0 +1,1069 @@ +/* crypto/engine/hw_ubsec.c */ +/* Written by Geoff Thorpe (geoff@geoffthorpe.net) for the OpenSSL + * project 2000. + * + * Cloned shamelessly by Joe Tardo. + */ +/* ==================================================================== + * Copyright (c) 1999-2001 The OpenSSL Project. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. All advertising materials mentioning features or use of this + * software must display the following acknowledgment: + * "This product includes software developed by the OpenSSL Project + * for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)" + * + * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to + * endorse or promote products derived from this software without + * prior written permission. For written permission, please contact + * licensing@OpenSSL.org. + * + * 5. Products derived from this software may not be called "OpenSSL" + * nor may "OpenSSL" appear in their names without prior written + * permission of the OpenSSL Project. + * + * 6. Redistributions of any form whatsoever must retain the following + * acknowledgment: + * "This product includes software developed by the OpenSSL Project + * for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)" + * + * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY + * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR + * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, + * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * ==================================================================== + * + * This product includes cryptographic software written by Eric Young + * (eay@cryptsoft.com). This product includes software written by Tim + * Hudson (tjh@cryptsoft.com). + * + */ + +#include +#include +#include +#include +#include +#include +#ifndef OPENSSL_NO_RSA +#include +#endif +#ifndef OPENSSL_NO_DSA +#include +#endif +#ifndef OPENSSL_NO_DH +#include +#endif +#include + +#ifndef OPENSSL_NO_HW +#ifndef OPENSSL_NO_HW_UBSEC + +#ifdef FLAT_INC +#include "hw_ubsec.h" +#else +#include "vendor_defns/hw_ubsec.h" +#endif + +#define UBSEC_LIB_NAME "ubsec engine" +#include "e_ubsec_err.c" + +#define FAIL_TO_SOFTWARE -15 + +static int ubsec_destroy(ENGINE *e); +static int ubsec_init(ENGINE *e); +static int ubsec_finish(ENGINE *e); +static int ubsec_ctrl(ENGINE *e, int cmd, long i, void *p, void (*f)(void)); +static int ubsec_mod_exp(BIGNUM *r, const BIGNUM *a, const BIGNUM *p, + const BIGNUM *m, BN_CTX *ctx); +#ifndef OPENSSL_NO_RSA +static int ubsec_mod_exp_crt(BIGNUM *r, const BIGNUM *a, const BIGNUM *p, + const BIGNUM *q, const BIGNUM *dp, + const BIGNUM *dq, const BIGNUM *qinv, BN_CTX *ctx); +static int ubsec_rsa_mod_exp(BIGNUM *r0, const BIGNUM *I, RSA *rsa, BN_CTX *ctx); +static int ubsec_mod_exp_mont(BIGNUM *r, const BIGNUM *a, const BIGNUM *p, + const BIGNUM *m, BN_CTX *ctx, BN_MONT_CTX *m_ctx); +#endif +#ifndef OPENSSL_NO_DSA +#ifdef NOT_USED +static int ubsec_dsa_mod_exp(DSA *dsa, BIGNUM *rr, BIGNUM *a1, + BIGNUM *p1, BIGNUM *a2, BIGNUM *p2, BIGNUM *m, + BN_CTX *ctx, BN_MONT_CTX *in_mont); +static int ubsec_mod_exp_dsa(DSA *dsa, BIGNUM *r, BIGNUM *a, + const BIGNUM *p, const BIGNUM *m, BN_CTX *ctx, + BN_MONT_CTX *m_ctx); +#endif +static DSA_SIG *ubsec_dsa_do_sign(const unsigned char *dgst, int dlen, DSA *dsa); +static int ubsec_dsa_verify(const unsigned char *dgst, int dgst_len, + DSA_SIG *sig, DSA *dsa); +#endif +#ifndef OPENSSL_NO_DH +static int ubsec_mod_exp_dh(const DH *dh, BIGNUM *r, const BIGNUM *a, + const BIGNUM *p, const BIGNUM *m, BN_CTX *ctx, + BN_MONT_CTX *m_ctx); +static int ubsec_dh_compute_key(unsigned char *key,const BIGNUM *pub_key,DH *dh); +static int ubsec_dh_generate_key(DH *dh); +#endif + +#ifdef NOT_USED +static int ubsec_rand_bytes(unsigned char *buf, int num); +static int ubsec_rand_status(void); +#endif + +#define UBSEC_CMD_SO_PATH ENGINE_CMD_BASE +static const ENGINE_CMD_DEFN ubsec_cmd_defns[] = { + {UBSEC_CMD_SO_PATH, + "SO_PATH", + "Specifies the path to the 'ubsec' shared library", + ENGINE_CMD_FLAG_STRING}, + {0, NULL, NULL, 0} + }; + +#ifndef OPENSSL_NO_RSA +/* Our internal RSA_METHOD that we provide pointers to */ +static RSA_METHOD ubsec_rsa = + { + "UBSEC RSA method", + NULL, + NULL, + NULL, + NULL, + ubsec_rsa_mod_exp, + ubsec_mod_exp_mont, + NULL, + NULL, + 0, + NULL, + NULL, + NULL, + NULL + }; +#endif + +#ifndef OPENSSL_NO_DSA +/* Our internal DSA_METHOD that we provide pointers to */ +static DSA_METHOD ubsec_dsa = + { + "UBSEC DSA method", + ubsec_dsa_do_sign, /* dsa_do_sign */ + NULL, /* dsa_sign_setup */ + ubsec_dsa_verify, /* dsa_do_verify */ + NULL, /* ubsec_dsa_mod_exp */ /* dsa_mod_exp */ + NULL, /* ubsec_mod_exp_dsa */ /* bn_mod_exp */ + NULL, /* init */ + NULL, /* finish */ + 0, /* flags */ + NULL, /* app_data */ + NULL, /* dsa_paramgen */ + NULL /* dsa_keygen */ + }; +#endif + +#ifndef OPENSSL_NO_DH +/* Our internal DH_METHOD that we provide pointers to */ +static DH_METHOD ubsec_dh = + { + "UBSEC DH method", + ubsec_dh_generate_key, + ubsec_dh_compute_key, + ubsec_mod_exp_dh, + NULL, + NULL, + 0, + NULL, + NULL + }; +#endif + +/* Constants used when creating the ENGINE */ +static const char *engine_ubsec_id = "ubsec"; +static const char *engine_ubsec_name = "UBSEC hardware engine support"; + +/* This internal function is used by ENGINE_ubsec() and possibly by the + * "dynamic" ENGINE support too */ +static int bind_helper(ENGINE *e) + { +#ifndef OPENSSL_NO_RSA + const RSA_METHOD *meth1; +#endif +#ifndef OPENSSL_NO_DH +#ifndef HAVE_UBSEC_DH + const DH_METHOD *meth3; +#endif /* HAVE_UBSEC_DH */ +#endif + if(!ENGINE_set_id(e, engine_ubsec_id) || + !ENGINE_set_name(e, engine_ubsec_name) || +#ifndef OPENSSL_NO_RSA + !ENGINE_set_RSA(e, &ubsec_rsa) || +#endif +#ifndef OPENSSL_NO_DSA + !ENGINE_set_DSA(e, &ubsec_dsa) || +#endif +#ifndef OPENSSL_NO_DH + !ENGINE_set_DH(e, &ubsec_dh) || +#endif + !ENGINE_set_destroy_function(e, ubsec_destroy) || + !ENGINE_set_init_function(e, ubsec_init) || + !ENGINE_set_finish_function(e, ubsec_finish) || + !ENGINE_set_ctrl_function(e, ubsec_ctrl) || + !ENGINE_set_cmd_defns(e, ubsec_cmd_defns)) + return 0; + +#ifndef OPENSSL_NO_RSA + /* We know that the "PKCS1_SSLeay()" functions hook properly + * to the Broadcom-specific mod_exp and mod_exp_crt so we use + * those functions. NB: We don't use ENGINE_openssl() or + * anything "more generic" because something like the RSAref + * code may not hook properly, and if you own one of these + * cards then you have the right to do RSA operations on it + * anyway! */ + meth1 = RSA_PKCS1_SSLeay(); + ubsec_rsa.rsa_pub_enc = meth1->rsa_pub_enc; + ubsec_rsa.rsa_pub_dec = meth1->rsa_pub_dec; + ubsec_rsa.rsa_priv_enc = meth1->rsa_priv_enc; + ubsec_rsa.rsa_priv_dec = meth1->rsa_priv_dec; +#endif + +#ifndef OPENSSL_NO_DH +#ifndef HAVE_UBSEC_DH + /* Much the same for Diffie-Hellman */ + meth3 = DH_OpenSSL(); + ubsec_dh.generate_key = meth3->generate_key; + ubsec_dh.compute_key = meth3->compute_key; +#endif /* HAVE_UBSEC_DH */ +#endif + + /* Ensure the ubsec error handling is set up */ + ERR_load_UBSEC_strings(); + return 1; + } + +#ifdef OPENSSL_NO_DYNAMIC_ENGINE +static ENGINE *engine_ubsec(void) + { + ENGINE *ret = ENGINE_new(); + if(!ret) + return NULL; + if(!bind_helper(ret)) + { + ENGINE_free(ret); + return NULL; + } + return ret; + } + +void ENGINE_load_ubsec(void) + { + /* Copied from eng_[openssl|dyn].c */ + ENGINE *toadd = engine_ubsec(); + if(!toadd) return; + ENGINE_add(toadd); + ENGINE_free(toadd); + ERR_clear_error(); + } +#endif + +/* This is a process-global DSO handle used for loading and unloading + * the UBSEC library. NB: This is only set (or unset) during an + * init() or finish() call (reference counts permitting) and they're + * operating with global locks, so this should be thread-safe + * implicitly. */ + +static DSO *ubsec_dso = NULL; + +/* These are the function pointers that are (un)set when the library has + * successfully (un)loaded. */ + +static t_UBSEC_ubsec_bytes_to_bits *p_UBSEC_ubsec_bytes_to_bits = NULL; +static t_UBSEC_ubsec_bits_to_bytes *p_UBSEC_ubsec_bits_to_bytes = NULL; +static t_UBSEC_ubsec_open *p_UBSEC_ubsec_open = NULL; +static t_UBSEC_ubsec_close *p_UBSEC_ubsec_close = NULL; +#ifndef OPENSSL_NO_DH +static t_UBSEC_diffie_hellman_generate_ioctl + *p_UBSEC_diffie_hellman_generate_ioctl = NULL; +static t_UBSEC_diffie_hellman_agree_ioctl *p_UBSEC_diffie_hellman_agree_ioctl = NULL; +#endif +#ifndef OPENSSL_NO_RSA +static t_UBSEC_rsa_mod_exp_ioctl *p_UBSEC_rsa_mod_exp_ioctl = NULL; +static t_UBSEC_rsa_mod_exp_crt_ioctl *p_UBSEC_rsa_mod_exp_crt_ioctl = NULL; +#endif +#ifndef OPENSSL_NO_DSA +static t_UBSEC_dsa_sign_ioctl *p_UBSEC_dsa_sign_ioctl = NULL; +static t_UBSEC_dsa_verify_ioctl *p_UBSEC_dsa_verify_ioctl = NULL; +#endif +static t_UBSEC_math_accelerate_ioctl *p_UBSEC_math_accelerate_ioctl = NULL; +static t_UBSEC_rng_ioctl *p_UBSEC_rng_ioctl = NULL; +static t_UBSEC_max_key_len_ioctl *p_UBSEC_max_key_len_ioctl = NULL; + +static int max_key_len = 1024; /* ??? */ + +/* + * These are the static string constants for the DSO file name and the function + * symbol names to bind to. + */ + +static const char *UBSEC_LIBNAME = NULL; +static const char *get_UBSEC_LIBNAME(void) + { + if(UBSEC_LIBNAME) + return UBSEC_LIBNAME; + return "ubsec"; + } +static void free_UBSEC_LIBNAME(void) + { + if(UBSEC_LIBNAME) + OPENSSL_free((void*)UBSEC_LIBNAME); + UBSEC_LIBNAME = NULL; + } +static long set_UBSEC_LIBNAME(const char *name) + { + free_UBSEC_LIBNAME(); + return (((UBSEC_LIBNAME = BUF_strdup(name)) != NULL) ? 1 : 0); + } +static const char *UBSEC_F1 = "ubsec_bytes_to_bits"; +static const char *UBSEC_F2 = "ubsec_bits_to_bytes"; +static const char *UBSEC_F3 = "ubsec_open"; +static const char *UBSEC_F4 = "ubsec_close"; +#ifndef OPENSSL_NO_DH +static const char *UBSEC_F5 = "diffie_hellman_generate_ioctl"; +static const char *UBSEC_F6 = "diffie_hellman_agree_ioctl"; +#endif +/* #ifndef OPENSSL_NO_RSA */ +static const char *UBSEC_F7 = "rsa_mod_exp_ioctl"; +static const char *UBSEC_F8 = "rsa_mod_exp_crt_ioctl"; +/* #endif */ +#ifndef OPENSSL_NO_DSA +static const char *UBSEC_F9 = "dsa_sign_ioctl"; +static const char *UBSEC_F10 = "dsa_verify_ioctl"; +#endif +static const char *UBSEC_F11 = "math_accelerate_ioctl"; +static const char *UBSEC_F12 = "rng_ioctl"; +static const char *UBSEC_F13 = "ubsec_max_key_len_ioctl"; + +/* Destructor (complements the "ENGINE_ubsec()" constructor) */ +static int ubsec_destroy(ENGINE *e) + { + free_UBSEC_LIBNAME(); + ERR_unload_UBSEC_strings(); + return 1; + } + +/* (de)initialisation functions. */ +static int ubsec_init(ENGINE *e) + { + t_UBSEC_ubsec_bytes_to_bits *p1; + t_UBSEC_ubsec_bits_to_bytes *p2; + t_UBSEC_ubsec_open *p3; + t_UBSEC_ubsec_close *p4; +#ifndef OPENSSL_NO_DH + t_UBSEC_diffie_hellman_generate_ioctl *p5; + t_UBSEC_diffie_hellman_agree_ioctl *p6; +#endif +/* #ifndef OPENSSL_NO_RSA */ + t_UBSEC_rsa_mod_exp_ioctl *p7; + t_UBSEC_rsa_mod_exp_crt_ioctl *p8; +/* #endif */ +#ifndef OPENSSL_NO_DSA + t_UBSEC_dsa_sign_ioctl *p9; + t_UBSEC_dsa_verify_ioctl *p10; +#endif + t_UBSEC_math_accelerate_ioctl *p11; + t_UBSEC_rng_ioctl *p12; + t_UBSEC_max_key_len_ioctl *p13; + int fd = 0; + + if(ubsec_dso != NULL) + { + UBSECerr(UBSEC_F_UBSEC_INIT, UBSEC_R_ALREADY_LOADED); + goto err; + } + /* + * Attempt to load libubsec.so/ubsec.dll/whatever. + */ + ubsec_dso = DSO_load(NULL, get_UBSEC_LIBNAME(), NULL, 0); + if(ubsec_dso == NULL) + { + UBSECerr(UBSEC_F_UBSEC_INIT, UBSEC_R_DSO_FAILURE); + goto err; + } + + if ( + !(p1 = (t_UBSEC_ubsec_bytes_to_bits *) DSO_bind_func(ubsec_dso, UBSEC_F1)) || + !(p2 = (t_UBSEC_ubsec_bits_to_bytes *) DSO_bind_func(ubsec_dso, UBSEC_F2)) || + !(p3 = (t_UBSEC_ubsec_open *) DSO_bind_func(ubsec_dso, UBSEC_F3)) || + !(p4 = (t_UBSEC_ubsec_close *) DSO_bind_func(ubsec_dso, UBSEC_F4)) || +#ifndef OPENSSL_NO_DH + !(p5 = (t_UBSEC_diffie_hellman_generate_ioctl *) + DSO_bind_func(ubsec_dso, UBSEC_F5)) || + !(p6 = (t_UBSEC_diffie_hellman_agree_ioctl *) + DSO_bind_func(ubsec_dso, UBSEC_F6)) || +#endif +/* #ifndef OPENSSL_NO_RSA */ + !(p7 = (t_UBSEC_rsa_mod_exp_ioctl *) DSO_bind_func(ubsec_dso, UBSEC_F7)) || + !(p8 = (t_UBSEC_rsa_mod_exp_crt_ioctl *) DSO_bind_func(ubsec_dso, UBSEC_F8)) || +/* #endif */ +#ifndef OPENSSL_NO_DSA + !(p9 = (t_UBSEC_dsa_sign_ioctl *) DSO_bind_func(ubsec_dso, UBSEC_F9)) || + !(p10 = (t_UBSEC_dsa_verify_ioctl *) DSO_bind_func(ubsec_dso, UBSEC_F10)) || +#endif + !(p11 = (t_UBSEC_math_accelerate_ioctl *) + DSO_bind_func(ubsec_dso, UBSEC_F11)) || + !(p12 = (t_UBSEC_rng_ioctl *) DSO_bind_func(ubsec_dso, UBSEC_F12)) || + !(p13 = (t_UBSEC_max_key_len_ioctl *) DSO_bind_func(ubsec_dso, UBSEC_F13))) + { + UBSECerr(UBSEC_F_UBSEC_INIT, UBSEC_R_DSO_FAILURE); + goto err; + } + + /* Copy the pointers */ + p_UBSEC_ubsec_bytes_to_bits = p1; + p_UBSEC_ubsec_bits_to_bytes = p2; + p_UBSEC_ubsec_open = p3; + p_UBSEC_ubsec_close = p4; +#ifndef OPENSSL_NO_DH + p_UBSEC_diffie_hellman_generate_ioctl = p5; + p_UBSEC_diffie_hellman_agree_ioctl = p6; +#endif +#ifndef OPENSSL_NO_RSA + p_UBSEC_rsa_mod_exp_ioctl = p7; + p_UBSEC_rsa_mod_exp_crt_ioctl = p8; +#endif +#ifndef OPENSSL_NO_DSA + p_UBSEC_dsa_sign_ioctl = p9; + p_UBSEC_dsa_verify_ioctl = p10; +#endif + p_UBSEC_math_accelerate_ioctl = p11; + p_UBSEC_rng_ioctl = p12; + p_UBSEC_max_key_len_ioctl = p13; + + /* Perform an open to see if there's actually any unit running. */ + if (((fd = p_UBSEC_ubsec_open(UBSEC_KEY_DEVICE_NAME)) > 0) && (p_UBSEC_max_key_len_ioctl(fd, &max_key_len) == 0)) + { + p_UBSEC_ubsec_close(fd); + return 1; + } + else + { + UBSECerr(UBSEC_F_UBSEC_INIT, UBSEC_R_UNIT_FAILURE); + } + +err: + if(ubsec_dso) + DSO_free(ubsec_dso); + ubsec_dso = NULL; + p_UBSEC_ubsec_bytes_to_bits = NULL; + p_UBSEC_ubsec_bits_to_bytes = NULL; + p_UBSEC_ubsec_open = NULL; + p_UBSEC_ubsec_close = NULL; +#ifndef OPENSSL_NO_DH + p_UBSEC_diffie_hellman_generate_ioctl = NULL; + p_UBSEC_diffie_hellman_agree_ioctl = NULL; +#endif +#ifndef OPENSSL_NO_RSA + p_UBSEC_rsa_mod_exp_ioctl = NULL; + p_UBSEC_rsa_mod_exp_crt_ioctl = NULL; +#endif +#ifndef OPENSSL_NO_DSA + p_UBSEC_dsa_sign_ioctl = NULL; + p_UBSEC_dsa_verify_ioctl = NULL; +#endif + p_UBSEC_math_accelerate_ioctl = NULL; + p_UBSEC_rng_ioctl = NULL; + p_UBSEC_max_key_len_ioctl = NULL; + + return 0; + } + +static int ubsec_finish(ENGINE *e) + { + free_UBSEC_LIBNAME(); + if(ubsec_dso == NULL) + { + UBSECerr(UBSEC_F_UBSEC_FINISH, UBSEC_R_NOT_LOADED); + return 0; + } + if(!DSO_free(ubsec_dso)) + { + UBSECerr(UBSEC_F_UBSEC_FINISH, UBSEC_R_DSO_FAILURE); + return 0; + } + ubsec_dso = NULL; + p_UBSEC_ubsec_bytes_to_bits = NULL; + p_UBSEC_ubsec_bits_to_bytes = NULL; + p_UBSEC_ubsec_open = NULL; + p_UBSEC_ubsec_close = NULL; +#ifndef OPENSSL_NO_DH + p_UBSEC_diffie_hellman_generate_ioctl = NULL; + p_UBSEC_diffie_hellman_agree_ioctl = NULL; +#endif +#ifndef OPENSSL_NO_RSA + p_UBSEC_rsa_mod_exp_ioctl = NULL; + p_UBSEC_rsa_mod_exp_crt_ioctl = NULL; +#endif +#ifndef OPENSSL_NO_DSA + p_UBSEC_dsa_sign_ioctl = NULL; + p_UBSEC_dsa_verify_ioctl = NULL; +#endif + p_UBSEC_math_accelerate_ioctl = NULL; + p_UBSEC_rng_ioctl = NULL; + p_UBSEC_max_key_len_ioctl = NULL; + return 1; + } + +static int ubsec_ctrl(ENGINE *e, int cmd, long i, void *p, void (*f)(void)) + { + int initialised = ((ubsec_dso == NULL) ? 0 : 1); + switch(cmd) + { + case UBSEC_CMD_SO_PATH: + if(p == NULL) + { + UBSECerr(UBSEC_F_UBSEC_CTRL,ERR_R_PASSED_NULL_PARAMETER); + return 0; + } + if(initialised) + { + UBSECerr(UBSEC_F_UBSEC_CTRL,UBSEC_R_ALREADY_LOADED); + return 0; + } + return set_UBSEC_LIBNAME((const char *)p); + default: + break; + } + UBSECerr(UBSEC_F_UBSEC_CTRL,UBSEC_R_CTRL_COMMAND_NOT_IMPLEMENTED); + return 0; + } + +static int ubsec_mod_exp(BIGNUM *r, const BIGNUM *a, const BIGNUM *p, + const BIGNUM *m, BN_CTX *ctx) + { + int y_len = 0; + int fd; + + if(ubsec_dso == NULL) + { + UBSECerr(UBSEC_F_UBSEC_MOD_EXP, UBSEC_R_NOT_LOADED); + return 0; + } + + /* Check if hardware can't handle this argument. */ + y_len = BN_num_bits(m); + if (y_len > max_key_len) { + UBSECerr(UBSEC_F_UBSEC_MOD_EXP, UBSEC_R_SIZE_TOO_LARGE_OR_TOO_SMALL); + return BN_mod_exp(r, a, p, m, ctx); + } + + if(!bn_wexpand(r, m->top)) + { + UBSECerr(UBSEC_F_UBSEC_MOD_EXP, UBSEC_R_BN_EXPAND_FAIL); + return 0; + } + + if ((fd = p_UBSEC_ubsec_open(UBSEC_KEY_DEVICE_NAME)) <= 0) { + fd = 0; + UBSECerr(UBSEC_F_UBSEC_MOD_EXP, UBSEC_R_UNIT_FAILURE); + return BN_mod_exp(r, a, p, m, ctx); + } + + if (p_UBSEC_rsa_mod_exp_ioctl(fd, (unsigned char *)a->d, BN_num_bits(a), + (unsigned char *)m->d, BN_num_bits(m), (unsigned char *)p->d, + BN_num_bits(p), (unsigned char *)r->d, &y_len) != 0) + { + UBSECerr(UBSEC_F_UBSEC_MOD_EXP, UBSEC_R_REQUEST_FAILED); + p_UBSEC_ubsec_close(fd); + + return BN_mod_exp(r, a, p, m, ctx); + } + + p_UBSEC_ubsec_close(fd); + + r->top = (BN_num_bits(m)+BN_BITS2-1)/BN_BITS2; + return 1; + } + +#ifndef OPENSSL_NO_RSA +static int ubsec_rsa_mod_exp(BIGNUM *r0, const BIGNUM *I, RSA *rsa, BN_CTX *ctx) + { + int to_return = 0; + + if(!rsa->p || !rsa->q || !rsa->dmp1 || !rsa->dmq1 || !rsa->iqmp) + { + UBSECerr(UBSEC_F_UBSEC_RSA_MOD_EXP, UBSEC_R_MISSING_KEY_COMPONENTS); + goto err; + } + + to_return = ubsec_mod_exp_crt(r0, I, rsa->p, rsa->q, rsa->dmp1, + rsa->dmq1, rsa->iqmp, ctx); + if (to_return == FAIL_TO_SOFTWARE) + { + /* + * Do in software as hardware failed. + */ + const RSA_METHOD *meth = RSA_PKCS1_SSLeay(); + to_return = (*meth->rsa_mod_exp)(r0, I, rsa, ctx); + } +err: + return to_return; + } + +static int ubsec_mod_exp_crt(BIGNUM *r, const BIGNUM *a, const BIGNUM *p, + const BIGNUM *q, const BIGNUM *dp, + const BIGNUM *dq, const BIGNUM *qinv, BN_CTX *ctx) + { + int y_len, + fd; + + y_len = BN_num_bits(p) + BN_num_bits(q); + + /* Check if hardware can't handle this argument. */ + if (y_len > max_key_len) { + UBSECerr(UBSEC_F_UBSEC_MOD_EXP_CRT, UBSEC_R_SIZE_TOO_LARGE_OR_TOO_SMALL); + return FAIL_TO_SOFTWARE; + } + + if (!bn_wexpand(r, p->top + q->top + 1)) { + UBSECerr(UBSEC_F_UBSEC_MOD_EXP_CRT, UBSEC_R_BN_EXPAND_FAIL); + return 0; + } + + if ((fd = p_UBSEC_ubsec_open(UBSEC_KEY_DEVICE_NAME)) <= 0) { + fd = 0; + UBSECerr(UBSEC_F_UBSEC_MOD_EXP_CRT, UBSEC_R_UNIT_FAILURE); + return FAIL_TO_SOFTWARE; + } + + if (p_UBSEC_rsa_mod_exp_crt_ioctl(fd, + (unsigned char *)a->d, BN_num_bits(a), + (unsigned char *)qinv->d, BN_num_bits(qinv), + (unsigned char *)dp->d, BN_num_bits(dp), + (unsigned char *)p->d, BN_num_bits(p), + (unsigned char *)dq->d, BN_num_bits(dq), + (unsigned char *)q->d, BN_num_bits(q), + (unsigned char *)r->d, &y_len) != 0) { + UBSECerr(UBSEC_F_UBSEC_MOD_EXP_CRT, UBSEC_R_REQUEST_FAILED); + p_UBSEC_ubsec_close(fd); + return FAIL_TO_SOFTWARE; + } + + p_UBSEC_ubsec_close(fd); + + r->top = (BN_num_bits(p) + BN_num_bits(q) + BN_BITS2 - 1)/BN_BITS2; + return 1; +} +#endif + +#ifndef OPENSSL_NO_DSA +#ifdef NOT_USED +static int ubsec_dsa_mod_exp(DSA *dsa, BIGNUM *rr, BIGNUM *a1, + BIGNUM *p1, BIGNUM *a2, BIGNUM *p2, BIGNUM *m, + BN_CTX *ctx, BN_MONT_CTX *in_mont) + { + BIGNUM t; + int to_return = 0; + + BN_init(&t); + /* let rr = a1 ^ p1 mod m */ + if (!ubsec_mod_exp(rr,a1,p1,m,ctx)) goto end; + /* let t = a2 ^ p2 mod m */ + if (!ubsec_mod_exp(&t,a2,p2,m,ctx)) goto end; + /* let rr = rr * t mod m */ + if (!BN_mod_mul(rr,rr,&t,m,ctx)) goto end; + to_return = 1; +end: + BN_free(&t); + return to_return; + } + +static int ubsec_mod_exp_dsa(DSA *dsa, BIGNUM *r, BIGNUM *a, + const BIGNUM *p, const BIGNUM *m, BN_CTX *ctx, + BN_MONT_CTX *m_ctx) + { + return ubsec_mod_exp(r, a, p, m, ctx); + } +#endif +#endif + +#ifndef OPENSSL_NO_RSA + +/* + * This function is aliased to mod_exp (with the mont stuff dropped). + */ +static int ubsec_mod_exp_mont(BIGNUM *r, const BIGNUM *a, const BIGNUM *p, + const BIGNUM *m, BN_CTX *ctx, BN_MONT_CTX *m_ctx) + { + int ret = 0; + + /* Do in software if the key is too large for the hardware. */ + if (BN_num_bits(m) > max_key_len) + { + const RSA_METHOD *meth = RSA_PKCS1_SSLeay(); + ret = (*meth->bn_mod_exp)(r, a, p, m, ctx, m_ctx); + } + else + { + ret = ubsec_mod_exp(r, a, p, m, ctx); + } + + return ret; + } +#endif + +#ifndef OPENSSL_NO_DH +/* This function is aliased to mod_exp (with the dh and mont dropped). */ +static int ubsec_mod_exp_dh(const DH *dh, BIGNUM *r, const BIGNUM *a, + const BIGNUM *p, const BIGNUM *m, BN_CTX *ctx, + BN_MONT_CTX *m_ctx) + { + return ubsec_mod_exp(r, a, p, m, ctx); + } +#endif + +#ifndef OPENSSL_NO_DSA +static DSA_SIG *ubsec_dsa_do_sign(const unsigned char *dgst, int dlen, DSA *dsa) + { + DSA_SIG *to_return = NULL; + int s_len = 160, r_len = 160, d_len, fd; + BIGNUM m, *r=NULL, *s=NULL; + + BN_init(&m); + + s = BN_new(); + r = BN_new(); + if ((s == NULL) || (r==NULL)) + goto err; + + d_len = p_UBSEC_ubsec_bytes_to_bits((unsigned char *)dgst, dlen); + + if(!bn_wexpand(r, (160+BN_BITS2-1)/BN_BITS2) || + (!bn_wexpand(s, (160+BN_BITS2-1)/BN_BITS2))) { + UBSECerr(UBSEC_F_UBSEC_DSA_DO_SIGN, UBSEC_R_BN_EXPAND_FAIL); + goto err; + } + + if (BN_bin2bn(dgst,dlen,&m) == NULL) { + UBSECerr(UBSEC_F_UBSEC_DSA_DO_SIGN, UBSEC_R_BN_EXPAND_FAIL); + goto err; + } + + if ((fd = p_UBSEC_ubsec_open(UBSEC_KEY_DEVICE_NAME)) <= 0) { + const DSA_METHOD *meth; + fd = 0; + UBSECerr(UBSEC_F_UBSEC_DSA_DO_SIGN, UBSEC_R_UNIT_FAILURE); + meth = DSA_OpenSSL(); + to_return = meth->dsa_do_sign(dgst, dlen, dsa); + goto err; + } + + if (p_UBSEC_dsa_sign_ioctl(fd, 0, /* compute hash before signing */ + (unsigned char *)dgst, d_len, + NULL, 0, /* compute random value */ + (unsigned char *)dsa->p->d, BN_num_bits(dsa->p), + (unsigned char *)dsa->q->d, BN_num_bits(dsa->q), + (unsigned char *)dsa->g->d, BN_num_bits(dsa->g), + (unsigned char *)dsa->priv_key->d, BN_num_bits(dsa->priv_key), + (unsigned char *)r->d, &r_len, + (unsigned char *)s->d, &s_len ) != 0) { + const DSA_METHOD *meth; + + UBSECerr(UBSEC_F_UBSEC_DSA_DO_SIGN, UBSEC_R_REQUEST_FAILED); + p_UBSEC_ubsec_close(fd); + meth = DSA_OpenSSL(); + to_return = meth->dsa_do_sign(dgst, dlen, dsa); + + goto err; + } + + p_UBSEC_ubsec_close(fd); + + r->top = (160+BN_BITS2-1)/BN_BITS2; + s->top = (160+BN_BITS2-1)/BN_BITS2; + + to_return = DSA_SIG_new(); + if(to_return == NULL) { + UBSECerr(UBSEC_F_UBSEC_DSA_DO_SIGN, UBSEC_R_BN_EXPAND_FAIL); + goto err; + } + + to_return->r = r; + to_return->s = s; + +err: + if (!to_return) { + if (r) BN_free(r); + if (s) BN_free(s); + } + BN_clear_free(&m); + return to_return; +} + +static int ubsec_dsa_verify(const unsigned char *dgst, int dgst_len, + DSA_SIG *sig, DSA *dsa) + { + int v_len, d_len; + int to_return = 0; + int fd; + BIGNUM v, *pv = &v; + + BN_init(&v); + + if(!bn_wexpand(pv, dsa->p->top)) { + UBSECerr(UBSEC_F_UBSEC_DSA_VERIFY, UBSEC_R_BN_EXPAND_FAIL); + goto err; + } + + v_len = BN_num_bits(dsa->p); + + d_len = p_UBSEC_ubsec_bytes_to_bits((unsigned char *)dgst, dgst_len); + + if ((fd = p_UBSEC_ubsec_open(UBSEC_KEY_DEVICE_NAME)) <= 0) { + const DSA_METHOD *meth; + fd = 0; + UBSECerr(UBSEC_F_UBSEC_DSA_VERIFY, UBSEC_R_UNIT_FAILURE); + meth = DSA_OpenSSL(); + to_return = meth->dsa_do_verify(dgst, dgst_len, sig, dsa); + goto err; + } + + if (p_UBSEC_dsa_verify_ioctl(fd, 0, /* compute hash before signing */ + (unsigned char *)dgst, d_len, + (unsigned char *)dsa->p->d, BN_num_bits(dsa->p), + (unsigned char *)dsa->q->d, BN_num_bits(dsa->q), + (unsigned char *)dsa->g->d, BN_num_bits(dsa->g), + (unsigned char *)dsa->pub_key->d, BN_num_bits(dsa->pub_key), + (unsigned char *)sig->r->d, BN_num_bits(sig->r), + (unsigned char *)sig->s->d, BN_num_bits(sig->s), + (unsigned char *)v.d, &v_len) != 0) { + const DSA_METHOD *meth; + UBSECerr(UBSEC_F_UBSEC_DSA_VERIFY, UBSEC_R_REQUEST_FAILED); + p_UBSEC_ubsec_close(fd); + + meth = DSA_OpenSSL(); + to_return = meth->dsa_do_verify(dgst, dgst_len, sig, dsa); + + goto err; + } + + p_UBSEC_ubsec_close(fd); + + to_return = 1; +err: + BN_clear_free(&v); + return to_return; + } +#endif + +#ifndef OPENSSL_NO_DH +static int ubsec_dh_compute_key(unsigned char *key,const BIGNUM *pub_key,DH *dh) + { + int ret = -1, + k_len, + fd; + + k_len = BN_num_bits(dh->p); + + if ((fd = p_UBSEC_ubsec_open(UBSEC_KEY_DEVICE_NAME)) <= 0) + { + const DH_METHOD *meth; + UBSECerr(UBSEC_F_UBSEC_DH_COMPUTE_KEY, UBSEC_R_UNIT_FAILURE); + meth = DH_OpenSSL(); + ret = meth->compute_key(key, pub_key, dh); + goto err; + } + + if (p_UBSEC_diffie_hellman_agree_ioctl(fd, + (unsigned char *)dh->priv_key->d, BN_num_bits(dh->priv_key), + (unsigned char *)pub_key->d, BN_num_bits(pub_key), + (unsigned char *)dh->p->d, BN_num_bits(dh->p), + key, &k_len) != 0) + { + /* Hardware's a no go, failover to software */ + const DH_METHOD *meth; + UBSECerr(UBSEC_F_UBSEC_DH_COMPUTE_KEY, UBSEC_R_REQUEST_FAILED); + p_UBSEC_ubsec_close(fd); + + meth = DH_OpenSSL(); + ret = meth->compute_key(key, pub_key, dh); + + goto err; + } + + p_UBSEC_ubsec_close(fd); + + ret = p_UBSEC_ubsec_bits_to_bytes(k_len); +err: + return ret; + } + +static int ubsec_dh_generate_key(DH *dh) + { + int ret = 0, + random_bits = 0, + pub_key_len = 0, + priv_key_len = 0, + fd; + BIGNUM *pub_key = NULL; + BIGNUM *priv_key = NULL; + + /* + * How many bits should Random x be? dh_key.c + * sets the range from 0 to num_bits(modulus) ??? + */ + + if (dh->priv_key == NULL) + { + priv_key = BN_new(); + if (priv_key == NULL) goto err; + priv_key_len = BN_num_bits(dh->p); + if(bn_wexpand(priv_key, dh->p->top) == NULL) goto err; + do + if (!BN_rand_range(priv_key, dh->p)) goto err; + while (BN_is_zero(priv_key)); + random_bits = BN_num_bits(priv_key); + } + else + { + priv_key = dh->priv_key; + } + + if (dh->pub_key == NULL) + { + pub_key = BN_new(); + pub_key_len = BN_num_bits(dh->p); + if(bn_wexpand(pub_key, dh->p->top) == NULL) goto err; + if(pub_key == NULL) goto err; + } + else + { + pub_key = dh->pub_key; + } + + if ((fd = p_UBSEC_ubsec_open(UBSEC_KEY_DEVICE_NAME)) <= 0) + { + const DH_METHOD *meth; + UBSECerr(UBSEC_F_UBSEC_DH_GENERATE_KEY, UBSEC_R_UNIT_FAILURE); + meth = DH_OpenSSL(); + ret = meth->generate_key(dh); + goto err; + } + + if (p_UBSEC_diffie_hellman_generate_ioctl(fd, + (unsigned char *)priv_key->d, &priv_key_len, + (unsigned char *)pub_key->d, &pub_key_len, + (unsigned char *)dh->g->d, BN_num_bits(dh->g), + (unsigned char *)dh->p->d, BN_num_bits(dh->p), + 0, 0, random_bits) != 0) + { + /* Hardware's a no go, failover to software */ + const DH_METHOD *meth; + + UBSECerr(UBSEC_F_UBSEC_DH_GENERATE_KEY, UBSEC_R_REQUEST_FAILED); + p_UBSEC_ubsec_close(fd); + + meth = DH_OpenSSL(); + ret = meth->generate_key(dh); + + goto err; + } + + p_UBSEC_ubsec_close(fd); + + dh->pub_key = pub_key; + dh->pub_key->top = (pub_key_len + BN_BITS2-1) / BN_BITS2; + dh->priv_key = priv_key; + dh->priv_key->top = (priv_key_len + BN_BITS2-1) / BN_BITS2; + + ret = 1; +err: + return ret; + } +#endif + +#ifdef NOT_USED +static int ubsec_rand_bytes(unsigned char * buf, + int num) + { + int ret = 0, + fd; + + if ((fd = p_UBSEC_ubsec_open(UBSEC_KEY_DEVICE_NAME)) <= 0) + { + const RAND_METHOD *meth; + UBSECerr(UBSEC_F_UBSEC_RAND_BYTES, UBSEC_R_UNIT_FAILURE); + num = p_UBSEC_ubsec_bits_to_bytes(num); + meth = RAND_SSLeay(); + meth->seed(buf, num); + ret = meth->bytes(buf, num); + goto err; + } + + num *= 8; /* bytes to bits */ + + if (p_UBSEC_rng_ioctl(fd, + UBSEC_RNG_DIRECT, + buf, + &num) != 0) + { + /* Hardware's a no go, failover to software */ + const RAND_METHOD *meth; + + UBSECerr(UBSEC_F_UBSEC_RAND_BYTES, UBSEC_R_REQUEST_FAILED); + p_UBSEC_ubsec_close(fd); + + num = p_UBSEC_ubsec_bits_to_bytes(num); + meth = RAND_SSLeay(); + meth->seed(buf, num); + ret = meth->bytes(buf, num); + + goto err; + } + + p_UBSEC_ubsec_close(fd); + + ret = 1; +err: + return(ret); + } + + +static int ubsec_rand_status(void) + { + return 0; + } +#endif + +/* This stuff is needed if this ENGINE is being compiled into a self-contained + * shared-library. */ +#ifndef OPENSSL_NO_DYNAMIC_ENGINE +static int bind_fn(ENGINE *e, const char *id) + { + if(id && (strcmp(id, engine_ubsec_id) != 0)) + return 0; + if(!bind_helper(e)) + return 0; + return 1; + } +IMPLEMENT_DYNAMIC_CHECK_FN() +IMPLEMENT_DYNAMIC_BIND_FN(bind_fn) +#endif /* OPENSSL_NO_DYNAMIC_ENGINE */ + +#endif /* !OPENSSL_NO_HW_UBSEC */ +#endif /* !OPENSSL_NO_HW */ diff --git a/node-v0.8.14/deps/openssl/openssl/engines/e_ubsec.ec b/node-v0.8.14/deps/openssl/openssl/engines/e_ubsec.ec new file mode 100644 index 0000000..99b9233 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/engines/e_ubsec.ec @@ -0,0 +1 @@ +L UBSEC e_ubsec_err.h e_ubsec_err.c diff --git a/node-v0.8.14/deps/openssl/openssl/engines/e_ubsec_err.c b/node-v0.8.14/deps/openssl/openssl/engines/e_ubsec_err.c new file mode 100644 index 0000000..14c3d61 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/engines/e_ubsec_err.c @@ -0,0 +1,157 @@ +/* e_ubsec_err.c */ +/* ==================================================================== + * Copyright (c) 1999-2005 The OpenSSL Project. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. All advertising materials mentioning features or use of this + * software must display the following acknowledgment: + * "This product includes software developed by the OpenSSL Project + * for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)" + * + * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to + * endorse or promote products derived from this software without + * prior written permission. For written permission, please contact + * openssl-core@OpenSSL.org. + * + * 5. Products derived from this software may not be called "OpenSSL" + * nor may "OpenSSL" appear in their names without prior written + * permission of the OpenSSL Project. + * + * 6. Redistributions of any form whatsoever must retain the following + * acknowledgment: + * "This product includes software developed by the OpenSSL Project + * for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)" + * + * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY + * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR + * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, + * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * ==================================================================== + * + * This product includes cryptographic software written by Eric Young + * (eay@cryptsoft.com). This product includes software written by Tim + * Hudson (tjh@cryptsoft.com). + * + */ + +/* NOTE: this file was auto generated by the mkerr.pl script: any changes + * made to it will be overwritten when the script next updates this file, + * only reason strings will be preserved. + */ + +#include +#include +#include "e_ubsec_err.h" + +/* BEGIN ERROR CODES */ +#ifndef OPENSSL_NO_ERR + +#define ERR_FUNC(func) ERR_PACK(0,func,0) +#define ERR_REASON(reason) ERR_PACK(0,0,reason) + +static ERR_STRING_DATA UBSEC_str_functs[]= + { +{ERR_FUNC(UBSEC_F_UBSEC_CTRL), "UBSEC_CTRL"}, +{ERR_FUNC(UBSEC_F_UBSEC_DH_COMPUTE_KEY), "UBSEC_DH_COMPUTE_KEY"}, +{ERR_FUNC(UBSEC_F_UBSEC_DH_GENERATE_KEY), "UBSEC_DH_GENERATE_KEY"}, +{ERR_FUNC(UBSEC_F_UBSEC_DSA_DO_SIGN), "UBSEC_DSA_DO_SIGN"}, +{ERR_FUNC(UBSEC_F_UBSEC_DSA_VERIFY), "UBSEC_DSA_VERIFY"}, +{ERR_FUNC(UBSEC_F_UBSEC_FINISH), "UBSEC_FINISH"}, +{ERR_FUNC(UBSEC_F_UBSEC_INIT), "UBSEC_INIT"}, +{ERR_FUNC(UBSEC_F_UBSEC_MOD_EXP), "UBSEC_MOD_EXP"}, +{ERR_FUNC(UBSEC_F_UBSEC_MOD_EXP_CRT), "UBSEC_MOD_EXP_CRT"}, +{ERR_FUNC(UBSEC_F_UBSEC_RAND_BYTES), "UBSEC_RAND_BYTES"}, +{ERR_FUNC(UBSEC_F_UBSEC_RSA_MOD_EXP), "UBSEC_RSA_MOD_EXP"}, +{ERR_FUNC(UBSEC_F_UBSEC_RSA_MOD_EXP_CRT), "UBSEC_RSA_MOD_EXP_CRT"}, +{0,NULL} + }; + +static ERR_STRING_DATA UBSEC_str_reasons[]= + { +{ERR_REASON(UBSEC_R_ALREADY_LOADED) ,"already loaded"}, +{ERR_REASON(UBSEC_R_BN_EXPAND_FAIL) ,"bn expand fail"}, +{ERR_REASON(UBSEC_R_CTRL_COMMAND_NOT_IMPLEMENTED),"ctrl command not implemented"}, +{ERR_REASON(UBSEC_R_DSO_FAILURE) ,"dso failure"}, +{ERR_REASON(UBSEC_R_MISSING_KEY_COMPONENTS),"missing key components"}, +{ERR_REASON(UBSEC_R_NOT_LOADED) ,"not loaded"}, +{ERR_REASON(UBSEC_R_REQUEST_FAILED) ,"request failed"}, +{ERR_REASON(UBSEC_R_SIZE_TOO_LARGE_OR_TOO_SMALL),"size too large or too small"}, +{ERR_REASON(UBSEC_R_UNIT_FAILURE) ,"unit failure"}, +{0,NULL} + }; + +#endif + +#ifdef UBSEC_LIB_NAME +static ERR_STRING_DATA UBSEC_lib_name[]= + { +{0 ,UBSEC_LIB_NAME}, +{0,NULL} + }; +#endif + + +static int UBSEC_lib_error_code=0; +static int UBSEC_error_init=1; + +static void ERR_load_UBSEC_strings(void) + { + if (UBSEC_lib_error_code == 0) + UBSEC_lib_error_code=ERR_get_next_error_library(); + + if (UBSEC_error_init) + { + UBSEC_error_init=0; +#ifndef OPENSSL_NO_ERR + ERR_load_strings(UBSEC_lib_error_code,UBSEC_str_functs); + ERR_load_strings(UBSEC_lib_error_code,UBSEC_str_reasons); +#endif + +#ifdef UBSEC_LIB_NAME + UBSEC_lib_name->error = ERR_PACK(UBSEC_lib_error_code,0,0); + ERR_load_strings(0,UBSEC_lib_name); +#endif + } + } + +static void ERR_unload_UBSEC_strings(void) + { + if (UBSEC_error_init == 0) + { +#ifndef OPENSSL_NO_ERR + ERR_unload_strings(UBSEC_lib_error_code,UBSEC_str_functs); + ERR_unload_strings(UBSEC_lib_error_code,UBSEC_str_reasons); +#endif + +#ifdef UBSEC_LIB_NAME + ERR_unload_strings(0,UBSEC_lib_name); +#endif + UBSEC_error_init=1; + } + } + +static void ERR_UBSEC_error(int function, int reason, char *file, int line) + { + if (UBSEC_lib_error_code == 0) + UBSEC_lib_error_code=ERR_get_next_error_library(); + ERR_PUT_error(UBSEC_lib_error_code,function,reason,file,line); + } diff --git a/node-v0.8.14/deps/openssl/openssl/engines/e_ubsec_err.h b/node-v0.8.14/deps/openssl/openssl/engines/e_ubsec_err.h new file mode 100644 index 0000000..b10b238 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/engines/e_ubsec_err.h @@ -0,0 +1,101 @@ +/* ==================================================================== + * Copyright (c) 2001 The OpenSSL Project. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. All advertising materials mentioning features or use of this + * software must display the following acknowledgment: + * "This product includes software developed by the OpenSSL Project + * for use in the OpenSSL Toolkit. (http://www.openssl.org/)" + * + * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to + * endorse or promote products derived from this software without + * prior written permission. For written permission, please contact + * openssl-core@openssl.org. + * + * 5. Products derived from this software may not be called "OpenSSL" + * nor may "OpenSSL" appear in their names without prior written + * permission of the OpenSSL Project. + * + * 6. Redistributions of any form whatsoever must retain the following + * acknowledgment: + * "This product includes software developed by the OpenSSL Project + * for use in the OpenSSL Toolkit (http://www.openssl.org/)" + * + * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY + * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR + * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, + * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * ==================================================================== + * + * This product includes cryptographic software written by Eric Young + * (eay@cryptsoft.com). This product includes software written by Tim + * Hudson (tjh@cryptsoft.com). + * + */ + +#ifndef HEADER_UBSEC_ERR_H +#define HEADER_UBSEC_ERR_H + +#ifdef __cplusplus +extern "C" { +#endif + +/* BEGIN ERROR CODES */ +/* The following lines are auto generated by the script mkerr.pl. Any changes + * made after this point may be overwritten when the script is next run. + */ +static void ERR_load_UBSEC_strings(void); +static void ERR_unload_UBSEC_strings(void); +static void ERR_UBSEC_error(int function, int reason, char *file, int line); +#define UBSECerr(f,r) ERR_UBSEC_error((f),(r),__FILE__,__LINE__) + +/* Error codes for the UBSEC functions. */ + +/* Function codes. */ +#define UBSEC_F_UBSEC_CTRL 100 +#define UBSEC_F_UBSEC_DH_COMPUTE_KEY 101 +#define UBSEC_F_UBSEC_DH_GENERATE_KEY 111 +#define UBSEC_F_UBSEC_DSA_DO_SIGN 102 +#define UBSEC_F_UBSEC_DSA_VERIFY 103 +#define UBSEC_F_UBSEC_FINISH 104 +#define UBSEC_F_UBSEC_INIT 105 +#define UBSEC_F_UBSEC_MOD_EXP 106 +#define UBSEC_F_UBSEC_MOD_EXP_CRT 110 +#define UBSEC_F_UBSEC_RAND_BYTES 107 +#define UBSEC_F_UBSEC_RSA_MOD_EXP 108 +#define UBSEC_F_UBSEC_RSA_MOD_EXP_CRT 109 + +/* Reason codes. */ +#define UBSEC_R_ALREADY_LOADED 100 +#define UBSEC_R_BN_EXPAND_FAIL 101 +#define UBSEC_R_CTRL_COMMAND_NOT_IMPLEMENTED 102 +#define UBSEC_R_DSO_FAILURE 103 +#define UBSEC_R_MISSING_KEY_COMPONENTS 104 +#define UBSEC_R_NOT_LOADED 105 +#define UBSEC_R_REQUEST_FAILED 106 +#define UBSEC_R_SIZE_TOO_LARGE_OR_TOO_SMALL 107 +#define UBSEC_R_UNIT_FAILURE 108 + +#ifdef __cplusplus +} +#endif +#endif diff --git a/node-v0.8.14/deps/openssl/openssl/engines/engine_vector.mar b/node-v0.8.14/deps/openssl/openssl/engines/engine_vector.mar new file mode 100644 index 0000000..7d968e7 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/engines/engine_vector.mar @@ -0,0 +1,24 @@ +; +; Transfer vector for VAX shareable image +; + .TITLE ENGINE + .IDENT /ENGINE/ +; +; Define macro to assist in building transfer vector entries. Each entry +; should take no more than 8 bytes. +; + .MACRO FTRANSFER_ENTRY routine + .ALIGN QUAD + .TRANSFER routine + .MASK routine + JMP routine+2 + .ENDM FTRANSFER_ENTRY +; +; Place entries in own program section. +; + .PSECT $$ENGINE,QUAD,PIC,USR,CON,REL,LCL,SHR,EXE,RD,NOWRT +ENGINE_xfer: + FTRANSFER_ENTRY bind_engine + FTRANSFER_ENTRY v_check + .BLKB 32768-<.-ENGINE_xfer> ; 64 pages total. + .END diff --git a/node-v0.8.14/deps/openssl/openssl/engines/ia64.opt b/node-v0.8.14/deps/openssl/openssl/engines/ia64.opt new file mode 100644 index 0000000..1dc71bf --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/engines/ia64.opt @@ -0,0 +1 @@ +SYMBOL_VECTOR=(bind_engine=PROCEDURE,v_check=PROCEDURE) diff --git a/node-v0.8.14/deps/openssl/openssl/engines/makeengines.com b/node-v0.8.14/deps/openssl/openssl/engines/makeengines.com new file mode 100644 index 0000000..6329fbb --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/engines/makeengines.com @@ -0,0 +1,1125 @@ +$! +$! MAKEENGINES.COM +$! Written By: Richard Levitte +$! richard@levitte.org +$! +$! This command file compiles and creates the various engines in form +$! of shared images. They are placed in [.xxx.EXE.ENGINES], where "xxx" +$! is ALPHA, IA64 or VAX, depending on your hardware. +$! +$! P1 if this is ENGINES or ALL, the engines will build, otherwise not. +$! +$! P2 DEBUG or NODEBUG to compile with or without debugger information. +$! +$! P3 VAXC for VAX C +$! DECC for DEC C +$! GNUC for GNU C (untested) +$! +$! P4 if defined, sets the TCP/IP libraries to use. UCX or TCPIP is +$! used by default since most other implementations come with a +$! compatibility library. The value must be one of the following: +$! +$! UCX for UCX +$! SOCKETSHR for SOCKETSHR+NETLIB +$! TCPIP for TCPIP (post UCX) +$! +$! P5 if defined, tells the compiler not to use special threads. +$! +$! P6 if defined, denotes which engines to build. If not defined, +$! all available engines are built. +$! +$! P7, if defined, specifies the C pointer size. Ignored on VAX. +$! ("64=ARGV" gives more efficient code with HP C V7.3 or newer.) +$! Supported values are: +$! +$! "" Compile with default (/NOPOINTER_SIZE) +$! 32 Compile with /POINTER_SIZE=32 (SHORT) +$! 64 Compile with /POINTER_SIZE=64[=ARGV] (LONG[=ARGV]) +$! (Automatically select ARGV if compiler supports it.) +$! 64= Compile with /POINTER_SIZE=64 (LONG). +$! 64=ARGV Compile with /POINTER_SIZE=64=ARGV (LONG=ARGV). +$! +$! P8, if defined, specifies a directory where ZLIB files (zlib.h, +$! libz.olb) may be found. Optionally, a non-default object library +$! name may be included ("dev:[dir]libz_64.olb", for example). +$! +$!----------------------------------------------------------------------------- +$! +$! Announce/identify. +$! +$ proc = f$environment( "procedure") +$ write sys$output "@@@ "+ - + f$parse( proc, , , "name")+ f$parse( proc, , , "type") +$! +$ on control_c then goto exit +$! +$! Set the default TCP/IP library to link against if needed +$! +$ TCPIP_LIB = "" +$ ZLIB_LIB = "" +$! +$! Check What Architecture We Are Using. +$! +$ IF (F$GETSYI("CPU").LT.128) +$ THEN +$! +$! The Architecture Is VAX. +$! +$ ARCH = "VAX" +$! +$! Else... +$! +$ ELSE +$! +$! The Architecture Is Alpha, IA64 or whatever comes in the future. +$! +$ ARCH = F$EDIT( F$GETSYI( "ARCH_NAME"), "UPCASE") +$ IF (ARCH .EQS. "") THEN ARCH = "UNK" +$! +$! End The Architecture Check. +$! +$ ENDIF +$! +$ ARCHD = ARCH +$ LIB32 = "32" +$ OPT_FILE = "" +$ POINTER_SIZE = "" +$! +$! Set the names of the engines we want to build +$! NOTE: Some might think this list ugly. However, it's made this way to +$! reflect the LIBNAMES variable in Makefile as closely as possible, +$! thereby making it fairly easy to verify that the lists are the same. +$! NOTE: gmp isn't built, as it's mostly a test engine and brings in another +$! library that isn't necessarely ported to VMS. +$! +$ ENGINES = "," + P6 +$ IF ENGINES .EQS. "," THEN - + ENGINES = ",4758cca,aep,atalla,cswift,chil,nuron,sureware,ubsec,padlock," +$! +$! GOST requires a 64-bit integer type, unavailable on VAX. +$! +$ IF (ARCH .NES. "VAX") THEN - + ENGINES = ENGINES+ ",ccgost" +$! +$! Check options. +$! +$ OPT_PHASE = P1 +$ ACCEPT_PHASE = "ALL,ENGINES" +$ OPT_DEBUG = P2 +$ OPT_COMPILER = P3 +$ OPT_TCPIP_LIB = P4 +$ OPT_SPECIAL_THREADS = P5 +$ OPT_POINTER_SIZE = P7 +$ ZLIB = P8 +$ +$ GOSUB CHECK_OPTIONS +$! +$! Set the goal directories, and create them if necessary +$! +$ OBJ_DIR := SYS$DISK:[-.'ARCHD'.OBJ.ENGINES] +$ EXE_DIR := SYS$DISK:[-.'ARCHD'.EXE.ENGINES] +$ IF F$PARSE(OBJ_DIR) .EQS. "" THEN CREATE/DIRECTORY 'OBJ_DIR' +$ IF F$PARSE(EXE_DIR) .EQS. "" THEN CREATE/DIRECTORY 'EXE_DIR' +$! +$! Set the goal files, and create them if necessary +$! +$ CRYPTO_LIB := SYS$DISK:[-.'ARCHD'.EXE.CRYPTO]SSL_LIBCRYPTO'LIB32'.OLB +$ IF F$SEARCH(CRYPTO_LIB) .EQS. "" THEN LIBRARY/CREATE/OBJECT 'CRYPTO_LIB' +$! +$! Specify the destination directory in any /MAP option. +$! +$ if (LINKMAP .eqs. "MAP") +$ then +$ LINKMAP = LINKMAP+ "=''EXE_DIR'" +$ endif +$! +$! Add the location prefix to the linker options file name. +$! +$ if (OPT_FILE .nes. "") +$ then +$ OPT_FILE = EXE_DIR+ OPT_FILE +$ endif +$! +$! Initialise. +$! +$ GOSUB INITIALISE +$ GOSUB CHECK_OPT_FILE +$! +$! Define what goes into each engine. VAX includes a transfer vector. +$! +$ ENGINE_ = "" +$ TV_OBJ = "" +$ IF ARCH .EQS. "VAX" +$ THEN +$ ENGINE_ = "engine_vector.mar" +$ TV_OBJ_NAME = OBJ_DIR + F$PARSE(ENGINE_,,,"NAME","SYNTAX_ONLY") + ".OBJ" +$ TV_OBJ = ",''TV_OBJ_NAME'" +$ ENDIF +$ ENGINE_4758CCA = "e_4758cca" +$ ENGINE_aep = "e_aep" +$ ENGINE_atalla = "e_atalla" +$ ENGINE_cswift = "e_cswift" +$ ENGINE_chil = "e_chil" +$ ENGINE_nuron = "e_nuron" +$ ENGINE_sureware = "e_sureware" +$ ENGINE_ubsec = "e_ubsec" +$ ENGINE_padlock = "e_padlock" +$ +$ ENGINE_ccgost_SUBDIR = "ccgost" +$ ENGINE_ccgost = "e_gost_err,gost2001_keyx,gost2001,gost89,gost94_keyx,"+ - + "gost_ameth,gost_asn1,gost_crypt,gost_ctl,gost_eng,"+ - + "gosthash,gost_keywrap,gost_md,gost_params,gost_pmeth,"+ - + "gost_sign" +$! +$! Define which programs need to be linked with a TCP/IP library +$! +$ TCPIP_ENGINES = ",," +$ IF COMPILER .EQS. "VAXC" THEN - + TCPIP_ENGINES = ",," +$! +$! Set up two loops, one that keeps track of the engines, +$! and one that keeps track of all the files going into +$! the current engine. +$! +$! Here's the start of the engine loop. +$! +$ ENGINE_COUNTER = 0 +$ ENGINE_NEXT: +$! +$! Extract the current engine name, and if we've reached the end, stop +$! +$ ENGINE_NAME = F$ELEMENT(ENGINE_COUNTER,",",ENGINES) +$ IF (ENGINE_NAME.EQS.",") THEN GOTO ENGINE_DONE +$! +$ ENGINE_COUNTER = ENGINE_COUNTER + 1 +$! +$! Set up the engine library names. +$! +$ LIB_ENGINE = "ENGINE_" + ENGINE_NAME +$! +$! Check if the library module name actually is defined +$! +$ IF F$TYPE('LIB_ENGINE') .EQS. "" +$ THEN +$ WRITE SYS$ERROR "" +$ WRITE SYS$ERROR "The module ",ENGINE_NAME," does not exist. Continuing..." +$ WRITE SYS$ERROR "" +$ GOTO ENGINE_NEXT +$ ENDIF +$! +$! Talk to the user +$! +$ IF ENGINE_NAME .NES. "" +$ THEN +$ WRITE SYS$OUTPUT "Compiling The ",ENGINE_NAME," Library Files. (",BUILDALL,")" +$ ELSE +$ WRITE SYS$OUTPUT "Compiling Support Files. (",BUILDALL,")" +$ ENDIF +$! +$! Create a .OPT file for the object files (for a real engine name). +$! +$ IF ENGINE_NAME .NES. "" +$ THEN +$ OPEN /WRITE OBJECTS 'EXE_DIR''ENGINE_NAME'.OPT +$ ENDIF +$! +$! Here's the start of per-engine module loop. +$! +$ FILE_COUNTER = 0 +$ FILE_NEXT: +$! +$! Extract the file name from the file list, and if we've reached the end, stop +$! +$ FILE_NAME = F$ELEMENT(FILE_COUNTER,",",'LIB_ENGINE') +$ IF (FILE_NAME.EQS.",") THEN GOTO FILE_DONE +$! +$ FILE_COUNTER = FILE_COUNTER + 1 +$! +$ IF FILE_NAME .EQS. "" THEN GOTO FILE_NEXT +$! +$! Set up the source and object reference +$! +$ IF F$TYPE('LIB_ENGINE'_SUBDIR) .EQS. "" +$ THEN +$ SOURCE_FILE = F$PARSE(FILE_NAME,"SYS$DISK:[].C",,,"SYNTAX_ONLY") +$ ELSE +$ SOURCE_FILE = F$PARSE(FILE_NAME,"SYS$DISK:[."+'LIB_ENGINE'_SUBDIR+"].C",,,"SYNTAX_ONLY") +$ ENDIF +$ OBJECT_FILE = OBJ_DIR + F$PARSE(FILE_NAME,,,"NAME","SYNTAX_ONLY") + ".OBJ" +$! +$! If we get some problem, we just go on trying to build the next module. +$ ON WARNING THEN GOTO FILE_NEXT +$! +$! Check if the module we want to compile is actually there. +$! +$ IF F$SEARCH(SOURCE_FILE) .EQS. "" +$ THEN +$ WRITE SYS$OUTPUT "" +$ WRITE SYS$OUTPUT "The File ",SOURCE_FILE," Doesn't Exist." +$ WRITE SYS$OUTPUT "" +$ GOTO EXIT +$ ENDIF +$! +$! Talk to the user. +$! +$ WRITE SYS$OUTPUT " ",FILE_NAME,"" +$! +$! Do the dirty work. +$! +$ ON ERROR THEN GOTO FILE_NEXT +$ IF F$EDIT(F$PARSE(SOURCE_FILE,,,"TYPE","SYNTAX_ONLY"),"UPCASE") .EQS. ".MAR" +$ THEN +$ MACRO/OBJECT='OBJECT_FILE' 'SOURCE_FILE' +$ ELSE +$ CC/OBJECT='OBJECT_FILE' 'SOURCE_FILE' +$ ENDIF +$! +$! Write the entry to the .OPT file (for a real engine name). +$! +$ IF ENGINE_NAME .NES. "" +$ THEN +$ WRITE OBJECTS OBJECT_FILE +$ ENDIF +$! +$! Next file +$! +$ GOTO FILE_NEXT +$! +$ FILE_DONE: +$! +$! Do not link the support files. +$! +$ IF ENGINE_NAME .EQS. "" THEN GOTO ENGINE_NEXT +$! +$! Close the linker options file (for a real engine name). +$! +$ CLOSE OBJECTS +$! +$! Now, there are two ways to handle this. We can either build +$! shareable images or stick the engine object file into libcrypto. +$! For now, the latter is NOT supported. +$! +$!!!!! LIBRARY/REPLACE 'CRYPTO_LIB' 'OBJECT_FILE' +$! +$! For shareable libraries, we need to do things a little differently +$! depending on if we link with a TCP/IP library or not. +$! +$ ENGINE_OPT := SYS$DISK:[]'ARCH'.OPT +$ LINK /'DEBUGGER' /'LINKMAP' /'TRACEBACK' /SHARE='EXE_DIR''ENGINE_NAME'.EXE - + 'EXE_DIR''ENGINE_NAME'.OPT /OPTIONS - + 'TV_OBJ', - + 'CRYPTO_LIB' /LIBRARY, - + 'ENGINE_OPT' /OPTIONS - + 'TCPIP_LIB' - + 'ZLIB_LIB' - + ,'OPT_FILE' /OPTIONS +$! +$! Next engine +$! +$ GOTO ENGINE_NEXT +$! +$ ENGINE_DONE: +$! +$! Talk to the user +$! +$ WRITE SYS$OUTPUT "All Done..." +$ EXIT: +$ GOSUB CLEANUP +$ EXIT +$! +$! Check For The Link Option FIle. +$! +$ CHECK_OPT_FILE: +$! +$! Check To See If We Need To Make A VAX C Option File. +$! +$ IF (COMPILER.EQS."VAXC") +$ THEN +$! +$! Check To See If We Already Have A VAX C Linker Option File. +$! +$ IF (F$SEARCH(OPT_FILE).EQS."") +$ THEN +$! +$! We Need A VAX C Linker Option File. +$! +$ CREATE 'OPT_FILE' +$DECK +! +! Default System Options File To Link Against +! The Sharable VAX C Runtime Library. +! +SYS$SHARE:VAXCRTL.EXE/SHARE +$EOD +$! +$! End The Option File Check. +$! +$ ENDIF +$! +$! End The VAXC Check. +$! +$ ENDIF +$! +$! Check To See If We Need A GNU C Option File. +$! +$ IF (COMPILER.EQS."GNUC") +$ THEN +$! +$! Check To See If We Already Have A GNU C Linker Option File. +$! +$ IF (F$SEARCH(OPT_FILE).EQS."") +$ THEN +$! +$! We Need A GNU C Linker Option File. +$! +$ CREATE 'OPT_FILE' +$DECK +! +! Default System Options File To Link Against +! The Sharable C Runtime Library. +! +GNU_CC:[000000]GCCLIB/LIBRARY +SYS$SHARE:VAXCRTL/SHARE +$EOD +$! +$! End The Option File Check. +$! +$ ENDIF +$! +$! End The GNU C Check. +$! +$ ENDIF +$! +$! Check To See If We Need A DEC C Option File. +$! +$ IF (COMPILER.EQS."DECC") +$ THEN +$! +$! Check To See If We Already Have A DEC C Linker Option File. +$! +$ IF (F$SEARCH(OPT_FILE).EQS."") +$ THEN +$! +$! Figure Out If We Need A non-VAX Or A VAX Linker Option File. +$! +$ IF ARCH .EQS. "VAX" +$ THEN +$! +$! We Need A DEC C Linker Option File For VAX. +$! +$ CREATE 'OPT_FILE' +$DECK +! +! Default System Options File To Link Against +! The Sharable DEC C Runtime Library. +! +SYS$SHARE:DECC$SHR.EXE/SHARE +$EOD +$! +$! Else... +$! +$ ELSE +$! +$! Create The non-VAX Linker Option File. +$! +$ CREATE 'OPT_FILE' +$DECK +! +! Default System Options File For non-VAX To Link Against +! The Sharable C Runtime Library. +! +SYS$SHARE:CMA$OPEN_LIB_SHR/SHARE +SYS$SHARE:CMA$OPEN_RTL/SHARE +$EOD +$! +$! End The DEC C Option File Check. +$! +$ ENDIF +$! +$! End The Option File Search. +$! +$ ENDIF +$! +$! End The DEC C Check. +$! +$ ENDIF +$! +$! Tell The User What Linker Option File We Are Using. +$! +$ WRITE SYS$OUTPUT "Using Linker Option File ",OPT_FILE,"." +$! +$! Time To RETURN. +$! +$ RETURN +$! +$! Check The User's Options. +$! +$ CHECK_OPTIONS: +$! +$! Check To See If OPT_PHASE Is Blank. +$! +$ IF (OPT_PHASE.EQS."ALL") +$ THEN +$! +$! OPT_PHASE Is Blank, So Build Everything. +$! +$ BUILDALL = "ALL" +$! +$! Else... +$! +$ ELSE +$! +$! Else, Check To See If OPT_PHASE Has A Valid Argument. +$! +$ IF ("," + ACCEPT_PHASE + ",") - ("," + OPT_PHASE + ",") - + .NES. ("," + ACCEPT_PHASE + ",") +$ THEN +$! +$! A Valid Argument. +$! +$ BUILDALL = OPT_PHASE +$! +$! Else... +$! +$ ELSE +$! +$! Tell The User We Don't Know What They Want. +$! +$ WRITE SYS$OUTPUT "" +$ WRITE SYS$OUTPUT "The option ",OPT_PHASE," is invalid. The valid options are:" +$ WRITE SYS$OUTPUT "" +$ IF ("," + ACCEPT_PHASE + ",") - ",ALL," - + .NES. ("," + ACCEPT_PHASE + ",") THEN - + WRITE SYS$OUTPUT " ALL : just build everything." +$ IF ("," + ACCEPT_PHASE + ",") - ",ENGINES," - + .NES. ("," + ACCEPT_PHASE + ",") THEN - + WRITE SYS$OUTPUT " ENGINES : to compile just the [.xxx.EXE.ENGINES]*.EXE hareable images." +$ WRITE SYS$OUTPUT "" +$ WRITE SYS$OUTPUT " where 'xxx' stands for:" +$ WRITE SYS$OUTPUT "" +$ WRITE SYS$OUTPUT " ALPHA[64]: Alpha architecture." +$ WRITE SYS$OUTPUT " IA64[64] : IA64 architecture." +$ WRITE SYS$OUTPUT " VAX : VAX architecture." +$ WRITE SYS$OUTPUT "" +$! +$! Time To EXIT. +$! +$ EXIT +$! +$! End The Valid Argument Check. +$! +$ ENDIF +$! +$! End The OPT_PHASE Check. +$! +$ ENDIF +$! +$! Check To See If OPT_DEBUG Is Blank. +$! +$ IF (OPT_DEBUG.EQS."NODEBUG") +$ THEN +$! +$! OPT_DEBUG Is NODEBUG, So Compile Without The Debugger Information. +$! +$ DEBUGGER = "NODEBUG" +$ LINKMAP = "NOMAP" +$ TRACEBACK = "NOTRACEBACK" +$ GCC_OPTIMIZE = "OPTIMIZE" +$ CC_OPTIMIZE = "OPTIMIZE" +$ MACRO_OPTIMIZE = "OPTIMIZE" +$ WRITE SYS$OUTPUT "No Debugger Information Will Be Produced During Compile." +$ WRITE SYS$OUTPUT "Compiling With Compiler Optimization." +$ ELSE +$! +$! Check To See If We Are To Compile With Debugger Information. +$! +$ IF (OPT_DEBUG.EQS."DEBUG") +$ THEN +$! +$! Compile With Debugger Information. +$! +$ DEBUGGER = "DEBUG" +$ LINKMAP = "MAP" +$ TRACEBACK = "TRACEBACK" +$ GCC_OPTIMIZE = "NOOPTIMIZE" +$ CC_OPTIMIZE = "NOOPTIMIZE" +$ MACRO_OPTIMIZE = "NOOPTIMIZE" +$ WRITE SYS$OUTPUT "Debugger Information Will Be Produced During Compile." +$ WRITE SYS$OUTPUT "Compiling Without Compiler Optimization." +$ ELSE +$! +$! They Entered An Invalid Option. +$! +$ WRITE SYS$OUTPUT "" +$ WRITE SYS$OUTPUT "The Option ",OPT_DEBUG," Is Invalid. The Valid Options Are:" +$ WRITE SYS$OUTPUT "" +$ WRITE SYS$OUTPUT " DEBUG : Compile With The Debugger Information." +$ WRITE SYS$OUTPUT " NODEBUG : Compile Without The Debugger Information." +$ WRITE SYS$OUTPUT "" +$! +$! Time To EXIT. +$! +$ EXIT +$! +$! End The Valid Argument Check. +$! +$ ENDIF +$! +$! End The OPT_DEBUG Check. +$! +$ ENDIF +$! +$! Special Threads For OpenVMS v7.1 Or Later +$! +$! Written By: Richard Levitte +$! richard@levitte.org +$! +$! +$! Check To See If We Have A Option For OPT_SPECIAL_THREADS. +$! +$ IF (OPT_SPECIAL_THREADS.EQS."") +$ THEN +$! +$! Get The Version Of VMS We Are Using. +$! +$ ISSEVEN := +$ TMP = F$ELEMENT(0,"-",F$EXTRACT(1,4,F$GETSYI("VERSION"))) +$ TMP = F$INTEGER(F$ELEMENT(0,".",TMP)+F$ELEMENT(1,".",TMP)) +$! +$! Check To See If The VMS Version Is v7.1 Or Later. +$! +$ IF (TMP.GE.71) +$ THEN +$! +$! We Have OpenVMS v7.1 Or Later, So Use The Special Threads. +$! +$ ISSEVEN := ,PTHREAD_USE_D4 +$! +$! End The VMS Version Check. +$! +$ ENDIF +$! +$! End The OPT_SPECIAL_THREADS Check. +$! +$ ENDIF +$! +$! Check OPT_POINTER_SIZE (P7). +$! +$ IF (OPT_POINTER_SIZE .NES. "") .AND. (ARCH .NES. "VAX") +$ THEN +$! +$ IF (OPT_POINTER_SIZE .EQS. "32") +$ THEN +$ POINTER_SIZE = " /POINTER_SIZE=32" +$ ELSE +$ POINTER_SIZE = F$EDIT( OPT_POINTER_SIZE, "COLLAPSE, UPCASE") +$ IF ((POINTER_SIZE .EQS. "64") .OR. - + (POINTER_SIZE .EQS. "64=") .OR. - + (POINTER_SIZE .EQS. "64=ARGV")) +$ THEN +$ ARCHD = ARCH+ "_64" +$ LIB32 = "" +$ POINTER_SIZE = " /POINTER_SIZE=64" +$ ELSE +$! +$! Tell The User Entered An Invalid Option. +$! +$ WRITE SYS$OUTPUT "" +$ WRITE SYS$OUTPUT "The Option ", OPT_POINTER_SIZE, - + " Is Invalid. The Valid Options Are:" +$ WRITE SYS$OUTPUT "" +$ WRITE SYS$OUTPUT - + " """" : Compile with default (short) pointers." +$ WRITE SYS$OUTPUT - + " 32 : Compile with 32-bit (short) pointers." +$ WRITE SYS$OUTPUT - + " 64 : Compile with 64-bit (long) pointers (auto ARGV)." +$ WRITE SYS$OUTPUT - + " 64= : Compile with 64-bit (long) pointers (no ARGV)." +$ WRITE SYS$OUTPUT - + " 64=ARGV : Compile with 64-bit (long) pointers (ARGV)." +$ WRITE SYS$OUTPUT "" +$! +$! Time To EXIT. +$! +$ EXIT +$! +$ ENDIF +$! +$ ENDIF +$! +$! End The OPT_POINTER_SIZE Check. +$! +$ ENDIF +$! +$! Set basic C compiler /INCLUDE directories. +$! +$ CC_INCLUDES = "SYS$DISK:[],SYS$DISK:[.VENDOR_DEFNS]" +$! +$! Check To See If OPT_COMPILER Is Blank. +$! +$ IF (OPT_COMPILER.EQS."") +$ THEN +$! +$! O.K., The User Didn't Specify A Compiler, Let's Try To +$! Find Out Which One To Use. +$! +$! Check To See If We Have GNU C. +$! +$ IF (F$TRNLNM("GNU_CC").NES."") +$ THEN +$! +$! Looks Like GNUC, Set To Use GNUC. +$! +$ OPT_COMPILER = "GNUC" +$! +$! Else... +$! +$ ELSE +$! +$! Check To See If We Have VAXC Or DECC. +$! +$ IF (ARCH.NES."VAX").OR.(F$TRNLNM("DECC$CC_DEFAULT").NES."") +$ THEN +$! +$! Looks Like DECC, Set To Use DECC. +$! +$ OPT_COMPILER = "DECC" +$! +$! Else... +$! +$ ELSE +$! +$! Looks Like VAXC, Set To Use VAXC. +$! +$ OPT_COMPILER = "VAXC" +$! +$! End The VAXC Compiler Check. +$! +$ ENDIF +$! +$! End The DECC & VAXC Compiler Check. +$! +$ ENDIF +$! +$! End The Compiler Check. +$! +$ ENDIF +$! +$! Check To See If We Have A Option For OPT_TCPIP_LIB. +$! +$ IF (OPT_TCPIP_LIB.EQS."") +$ THEN +$! +$! Find out what socket library we have available +$! +$ IF F$PARSE("SOCKETSHR:") .NES. "" +$ THEN +$! +$! We have SOCKETSHR, and it is my opinion that it's the best to use. +$! +$ OPT_TCPIP_LIB = "SOCKETSHR" +$! +$! Tell the user +$! +$ WRITE SYS$OUTPUT "Using SOCKETSHR for TCP/IP" +$! +$! Else, let's look for something else +$! +$ ELSE +$! +$! Like UCX (the reason to do this before Multinet is that the UCX +$! emulation is easier to use...) +$! +$ IF F$TRNLNM("UCX$IPC_SHR") .NES. "" - + .OR. F$PARSE("SYS$SHARE:UCX$IPC_SHR.EXE") .NES. "" - + .OR. F$PARSE("SYS$LIBRARY:UCX$IPC.OLB") .NES. "" +$ THEN +$! +$! Last resort: a UCX or UCX-compatible library +$! +$ OPT_TCPIP_LIB = "UCX" +$! +$! Tell the user +$! +$ WRITE SYS$OUTPUT "Using UCX or an emulation thereof for TCP/IP" +$! +$! That was all... +$! +$ ENDIF +$ ENDIF +$ ENDIF +$! +$! Set Up Initial CC Definitions, Possibly With User Ones +$! +$ CCDEFS = "TCPIP_TYPE_''OPT_TCPIP_LIB',DSO_VMS" +$ IF F$TYPE(USER_CCDEFS) .NES. "" THEN CCDEFS = CCDEFS + "," + USER_CCDEFS +$ CCEXTRAFLAGS = "" +$ IF F$TYPE(USER_CCFLAGS) .NES. "" THEN CCEXTRAFLAGS = USER_CCFLAGS +$ CCDISABLEWARNINGS = "" !!! "LONGLONGTYPE,LONGLONGSUFX" +$ IF F$TYPE(USER_CCDISABLEWARNINGS) .NES. "" THEN - + CCDISABLEWARNINGS = CCDISABLEWARNINGS + "," + USER_CCDISABLEWARNINGS +$! +$! Check To See If We Have A ZLIB Option. +$! +$ IF (ZLIB .NES. "") +$ THEN +$! +$! Check for expected ZLIB files. +$! +$ err = 0 +$ file1 = f$parse( "zlib.h", ZLIB, , , "SYNTAX_ONLY") +$ if (f$search( file1) .eqs. "") +$ then +$ WRITE SYS$OUTPUT "" +$ WRITE SYS$OUTPUT "The Option ", ZLIB, " Is Invalid." +$ WRITE SYS$OUTPUT " Can't find header: ''file1'" +$ err = 1 +$ endif +$ file1 = f$parse( "A.;", ZLIB)- "A.;" +$! +$ file2 = f$parse( ZLIB, "libz.olb", , , "SYNTAX_ONLY") +$ if (f$search( file2) .eqs. "") +$ then +$ if (err .eq. 0) +$ then +$ WRITE SYS$OUTPUT "" +$ WRITE SYS$OUTPUT "The Option ", ZLIB, " Is Invalid." +$ endif +$ WRITE SYS$OUTPUT " Can't find library: ''file2'" +$ WRITE SYS$OUTPUT "" +$ err = err+ 2 +$ endif +$ if (err .eq. 1) +$ then +$ WRITE SYS$OUTPUT "" +$ endif +$! +$ if (err .ne. 0) +$ then +$ EXIT +$ endif +$! +$ CCDEFS = """ZLIB=1"", "+ CCDEFS +$ CC_INCLUDES = CC_INCLUDES+ ", "+ file1 +$ ZLIB_LIB = ", ''file2' /library" +$! +$! Print info +$! +$ WRITE SYS$OUTPUT "ZLIB library spec: ", file2 +$! +$! End The ZLIB Check. +$! +$ ENDIF +$! +$! Check To See If The User Entered A Valid Parameter. +$! +$ IF (OPT_COMPILER.EQS."VAXC").OR.(OPT_COMPILER.EQS."DECC").OR.(OPT_COMPILER.EQS."GNUC") +$ THEN +$! +$! Check To See If The User Wanted DECC. +$! +$ IF (OPT_COMPILER.EQS."DECC") +$ THEN +$! +$! Looks Like DECC, Set To Use DECC. +$! +$ COMPILER = "DECC" +$! +$! Tell The User We Are Using DECC. +$! +$ WRITE SYS$OUTPUT "Using DECC 'C' Compiler." +$! +$! Use DECC... +$! +$ CC = "CC" +$ IF ARCH.EQS."VAX" .AND. F$TRNLNM("DECC$CC_DEFAULT").NES."/DECC" - + THEN CC = "CC/DECC" +$ CC = CC + " /''CC_OPTIMIZE' /''DEBUGGER' /STANDARD=RELAXED"+ - + "''POINTER_SIZE' /NOLIST /PREFIX=ALL" + - + " /INCLUDE=(''CC_INCLUDES') " + - + CCEXTRAFLAGS +$! +$! Define The Linker Options File Name. +$! +$ OPT_FILE = "VAX_DECC_OPTIONS.OPT" +$! +$! End DECC Check. +$! +$ ENDIF +$! +$! Check To See If We Are To Use VAXC. +$! +$ IF (OPT_COMPILER.EQS."VAXC") +$ THEN +$! +$! Looks Like VAXC, Set To Use VAXC. +$! +$ COMPILER = "VAXC" +$! +$! Tell The User We Are Using VAX C. +$! +$ WRITE SYS$OUTPUT "Using VAXC 'C' Compiler." +$! +$! Compile Using VAXC. +$! +$ CC = "CC" +$ IF ARCH.NES."VAX" +$ THEN +$ WRITE SYS$OUTPUT "There is no VAX C on Alpha!" +$ EXIT +$ ENDIF +$ IF F$TRNLNM("DECC$CC_DEFAULT").EQS."/DECC" THEN CC = "CC/VAXC" +$ CC = CC + "/''CC_OPTIMIZE'/''DEBUGGER'/NOLIST" + - + "/INCLUDE=(''CC_INCLUDES')" + - + CCEXTRAFLAGS +$ CCDEFS = """VAXC""," + CCDEFS +$! +$! Define As SYS$COMMON:[SYSLIB] +$! +$ DEFINE/NOLOG SYS SYS$COMMON:[SYSLIB] +$! +$! Define The Linker Options File Name. +$! +$ OPT_FILE = "VAX_VAXC_OPTIONS.OPT" +$! +$! End VAXC Check +$! +$ ENDIF +$! +$! Check To See If We Are To Use GNU C. +$! +$ IF (OPT_COMPILER.EQS."GNUC") +$ THEN +$! +$! Looks Like GNUC, Set To Use GNUC. +$! +$ COMPILER = "GNUC" +$! +$! Tell The User We Are Using GNUC. +$! +$ WRITE SYS$OUTPUT "Using GNU 'C' Compiler." +$! +$! Use GNU C... +$! +$ CC = "GCC/NOCASE_HACK/''GCC_OPTIMIZE'/''DEBUGGER'/NOLIST" + - + "/INCLUDE=(''CC_INCLUDES')" + - + CCEXTRAFLAGS +$! +$! Define The Linker Options File Name. +$! +$ OPT_FILE = "VAX_GNUC_OPTIONS.OPT" +$! +$! End The GNU C Check. +$! +$ ENDIF +$! +$! Set up default defines +$! +$ CCDEFS = """FLAT_INC=1""," + CCDEFS +$! +$! Finish up the definition of CC. +$! +$ IF COMPILER .EQS. "DECC" +$ THEN +$ IF CCDISABLEWARNINGS .NES. "" +$ THEN +$ CCDISABLEWARNINGS = " /WARNING=(DISABLE=(" + CCDISABLEWARNINGS + "))" +$ ENDIF +$ ELSE +$ CCDISABLEWARNINGS = "" +$ ENDIF +$ CC = CC + " /DEFINE=(" + CCDEFS + ")" + CCDISABLEWARNINGS +$! +$! Show user the result +$! +$ WRITE/SYMBOL SYS$OUTPUT "Main C Compiling Command: ",CC +$! +$! Else The User Entered An Invalid Argument. +$! +$ ELSE +$! +$! Tell The User We Don't Know What They Want. +$! +$ WRITE SYS$OUTPUT "" +$ WRITE SYS$OUTPUT "The Option ",OPT_COMPILER," Is Invalid. The Valid Options Are:" +$ WRITE SYS$OUTPUT "" +$ WRITE SYS$OUTPUT " VAXC : To Compile With VAX C." +$ WRITE SYS$OUTPUT " DECC : To Compile With DEC C." +$ WRITE SYS$OUTPUT " GNUC : To Compile With GNU C." +$ WRITE SYS$OUTPUT "" +$! +$! Time To EXIT. +$! +$ EXIT +$! +$! End The Valid Argument Check. +$! +$ ENDIF +$! +$! Build a MACRO command for the architecture at hand +$! +$ IF ARCH .EQS. "VAX" +$ THEN +$ MACRO = "MACRO/''DEBUGGER'" +$ ELSE +$ MACRO = "MACRO/MIGRATION/''DEBUGGER'/''MACRO_OPTIMIZE'" +$ ENDIF +$! +$! Show user the result +$! +$ WRITE/SYMBOL SYS$OUTPUT "Main MACRO Compiling Command: ",MACRO +$! +$! Time to check the contents, and to make sure we get the correct library. +$! +$ IF OPT_TCPIP_LIB.EQS."SOCKETSHR" .OR. OPT_TCPIP_LIB.EQS."MULTINET" - + .OR. OPT_TCPIP_LIB.EQS."UCX" .OR. OPT_TCPIP_LIB.EQS."TCPIP" - + .OR. OPT_TCPIP_LIB.EQS."NONE" +$ THEN +$! +$! Check to see if SOCKETSHR was chosen +$! +$ IF OPT_TCPIP_LIB.EQS."SOCKETSHR" +$ THEN +$! +$! Set the library to use SOCKETSHR +$! +$ TCPIP_LIB = ",SYS$DISK:[-.VMS]SOCKETSHR_SHR.OPT /OPTIONS" +$! +$! Done with SOCKETSHR +$! +$ ENDIF +$! +$! Check to see if MULTINET was chosen +$! +$ IF OPT_TCPIP_LIB.EQS."MULTINET" +$ THEN +$! +$! Set the library to use UCX emulation. +$! +$ OPT_TCPIP_LIB = "UCX" +$! +$! Done with MULTINET +$! +$ ENDIF +$! +$! Check to see if UCX was chosen +$! +$ IF OPT_TCPIP_LIB.EQS."UCX" +$ THEN +$! +$! Set the library to use UCX. +$! +$ TCPIP_LIB = "SYS$DISK:[-.VMS]UCX_SHR_DECC.OPT /OPTIONS" +$ IF F$TRNLNM("UCX$IPC_SHR") .NES. "" +$ THEN +$ TCPIP_LIB = ",SYS$DISK:[-.VMS]UCX_SHR_DECC_LOG.OPT /OPTIONS" +$ ELSE +$ IF COMPILER .NES. "DECC" .AND. ARCH .EQS. "VAX" THEN - + TCPIP_LIB = ",SYS$DISK:[-.VMS]UCX_SHR_VAXC.OPT /OPTIONS" +$ ENDIF +$! +$! Done with UCX +$! +$ ENDIF +$! +$! Check to see if TCPIP was chosen +$! +$ IF OPT_TCPIP_LIB.EQS."TCPIP" +$ THEN +$! +$! Set the library to use TCPIP (post UCX). +$! +$ TCPIP_LIB = ",SYS$DISK:[-.VMS]TCPIP_SHR_DECC.OPT /OPTIONS" +$! +$! Done with TCPIP +$! +$ ENDIF +$! +$! Check to see if NONE was chosen +$! +$ IF OPT_TCPIP_LIB.EQS."NONE" +$ THEN +$! +$! Do not use a TCPIP library. +$! +$ TCPIP_LIB = "" +$! +$! Done with TCPIP +$! +$ ENDIF +$! +$! Print info +$! +$ WRITE SYS$OUTPUT "TCP/IP library spec: ", TCPIP_LIB- "," +$! +$! Else The User Entered An Invalid Argument. +$! +$ ELSE +$! +$! Tell The User We Don't Know What They Want. +$! +$ WRITE SYS$OUTPUT "" +$ WRITE SYS$OUTPUT "The Option ",OPT_TCPIP_LIB," Is Invalid. The Valid Options Are:" +$ WRITE SYS$OUTPUT "" +$ WRITE SYS$OUTPUT " SOCKETSHR : To link with SOCKETSHR TCP/IP library." +$ WRITE SYS$OUTPUT " UCX : To link with UCX TCP/IP library." +$ WRITE SYS$OUTPUT " TCPIP : To link with TCPIP (post UCX) TCP/IP library." +$ WRITE SYS$OUTPUT "" +$! +$! Time To EXIT. +$! +$ EXIT +$! +$! Done with TCP/IP libraries +$! +$ ENDIF +$! +$! Time To RETURN... +$! +$ RETURN +$! +$ INITIALISE: +$! +$! Save old value of the logical name OPENSSL +$! +$ __SAVE_OPENSSL = F$TRNLNM("OPENSSL","LNM$PROCESS_TABLE") +$! +$! Save directory information +$! +$ __HERE = F$PARSE(F$PARSE("A.;",F$ENVIRONMENT("PROCEDURE"))-"A.;","[]A.;") - "A.;" +$ __HERE = F$EDIT(__HERE,"UPCASE") +$ __TOP = __HERE - "ENGINES]" +$ __INCLUDE = __TOP + "INCLUDE.OPENSSL]" +$! +$! Set up the logical name OPENSSL to point at the include directory +$! +$ DEFINE OPENSSL /NOLOG '__INCLUDE' +$! +$! Done +$! +$ RETURN +$! +$ CLEANUP: +$! +$! Restore the saved logical name OPENSSL, if it had a value. +$! +$ if (f$type( __SAVE_OPENSSL) .nes. "") +$ then +$ IF __SAVE_OPENSSL .EQS. "" +$ THEN +$ DEASSIGN OPENSSL +$ ELSE +$ DEFINE /NOLOG OPENSSL '__SAVE_OPENSSL' +$ ENDIF +$ endif +$! +$! Close any open files. +$! +$ if (f$trnlnm( "objects", "LNM$PROCESS", 0, "SUPERVISOR") .nes. "") then - + close objects +$! +$! Done +$! +$ RETURN +$! diff --git a/node-v0.8.14/deps/openssl/openssl/engines/vax.opt b/node-v0.8.14/deps/openssl/openssl/engines/vax.opt new file mode 100644 index 0000000..72e6bd8 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/engines/vax.opt @@ -0,0 +1,9 @@ +! +! Ensure transfer vector is at beginning of image +! +CLUSTER=FIRST +COLLECT=FIRST,$$ENGINE +! +! make psects nonshareable so image can be installed. +! +PSECT_ATTR=$CHAR_STRING_CONSTANTS,NOWRT diff --git a/node-v0.8.14/deps/openssl/openssl/engines/vendor_defns/aep.h b/node-v0.8.14/deps/openssl/openssl/engines/vendor_defns/aep.h new file mode 100644 index 0000000..5e9754f --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/engines/vendor_defns/aep.h @@ -0,0 +1,178 @@ +/* This header declares the necessary definitions for using the exponentiation + * acceleration capabilities, and rnd number generation of the AEP card. + * + */ + +/* + * + * Some AEP defines + * + */ + +/*Successful return value*/ +#define AEP_R_OK 0x00000000 + +/*Miscelleanous unsuccessful return value*/ +#define AEP_R_GENERAL_ERROR 0x10000001 + +/*Insufficient host memory*/ +#define AEP_R_HOST_MEMORY 0x10000002 + +#define AEP_R_FUNCTION_FAILED 0x10000006 + +/*Invalid arguments in function call*/ +#define AEP_R_ARGUMENTS_BAD 0x10020000 + +#define AEP_R_NO_TARGET_RESOURCES 0x10030000 + +/*Error occuring on socket operation*/ +#define AEP_R_SOCKERROR 0x10000010 + +/*Socket has been closed from the other end*/ +#define AEP_R_SOCKEOF 0x10000011 + +/*Invalid handles*/ +#define AEP_R_CONNECTION_HANDLE_INVALID 0x100000B3 + +#define AEP_R_TRANSACTION_HANDLE_INVALID 0x10040000 + +/*Transaction has not yet returned from accelerator*/ +#define AEP_R_TRANSACTION_NOT_READY 0x00010000 + +/*There is already a thread waiting on this transaction*/ +#define AEP_R_TRANSACTION_CLAIMED 0x10050000 + +/*The transaction timed out*/ +#define AEP_R_TIMED_OUT 0x10060000 + +#define AEP_R_FXN_NOT_IMPLEMENTED 0x10070000 + +#define AEP_R_TARGET_ERROR 0x10080000 + +/*Error in the AEP daemon process*/ +#define AEP_R_DAEMON_ERROR 0x10090000 + +/*Invalid ctx id*/ +#define AEP_R_INVALID_CTX_ID 0x10009000 + +#define AEP_R_NO_KEY_MANAGER 0x1000a000 + +/*Error obtaining a mutex*/ +#define AEP_R_MUTEX_BAD 0x000001A0 + +/*Fxn call before AEP_Initialise ot after AEP_Finialise*/ +#define AEP_R_AEPAPI_NOT_INITIALIZED 0x10000190 + +/*AEP_Initialise has already been called*/ +#define AEP_R_AEPAPI_ALREADY_INITIALIZED 0x10000191 + +/*Maximum number of connections to daemon reached*/ +#define AEP_R_NO_MORE_CONNECTION_HNDLS 0x10000200 + +/* + * + * Some AEP Type definitions + * + */ + +/* an unsigned 8-bit value */ +typedef unsigned char AEP_U8; + +/* an unsigned 8-bit character */ +typedef char AEP_CHAR; + +/* a BYTE-sized Boolean flag */ +typedef AEP_U8 AEP_BBOOL; + +/*Unsigned value, at least 16 bits long*/ +typedef unsigned short AEP_U16; + +/* an unsigned value, at least 32 bits long */ +#ifdef SIXTY_FOUR_BIT_LONG +typedef unsigned int AEP_U32; +#else +typedef unsigned long AEP_U32; +#endif + +#ifdef SIXTY_FOUR_BIT_LONG +typedef unsigned long AEP_U64; +#else +typedef struct { unsigned long l1, l2; } AEP_U64; +#endif + +/* at least 32 bits; each bit is a Boolean flag */ +typedef AEP_U32 AEP_FLAGS; + +typedef AEP_U8 *AEP_U8_PTR; +typedef AEP_CHAR *AEP_CHAR_PTR; +typedef AEP_U32 *AEP_U32_PTR; +typedef AEP_U64 *AEP_U64_PTR; +typedef void *AEP_VOID_PTR; + +/* Pointer to a AEP_VOID_PTR-- i.e., pointer to pointer to void */ +typedef AEP_VOID_PTR *AEP_VOID_PTR_PTR; + +/*Used to identify an AEP connection handle*/ +typedef AEP_U32 AEP_CONNECTION_HNDL; + +/*Pointer to an AEP connection handle*/ +typedef AEP_CONNECTION_HNDL *AEP_CONNECTION_HNDL_PTR; + +/*Used by an application (in conjunction with the apps process id) to +identify an individual transaction*/ +typedef AEP_U32 AEP_TRANSACTION_ID; + +/*Pointer to an applications transaction identifier*/ +typedef AEP_TRANSACTION_ID *AEP_TRANSACTION_ID_PTR; + +/*Return value type*/ +typedef AEP_U32 AEP_RV; + +#define MAX_PROCESS_CONNECTIONS 256 + +#define RAND_BLK_SIZE 1024 + +typedef enum{ + NotConnected= 0, + Connected= 1, + InUse= 2 +} AEP_CONNECTION_STATE; + + +typedef struct AEP_CONNECTION_ENTRY{ + AEP_CONNECTION_STATE conn_state; + AEP_CONNECTION_HNDL conn_hndl; +} AEP_CONNECTION_ENTRY; + + +typedef AEP_RV t_AEP_OpenConnection(AEP_CONNECTION_HNDL_PTR phConnection); +typedef AEP_RV t_AEP_CloseConnection(AEP_CONNECTION_HNDL hConnection); + +typedef AEP_RV t_AEP_ModExp(AEP_CONNECTION_HNDL hConnection, + AEP_VOID_PTR pA, AEP_VOID_PTR pP, + AEP_VOID_PTR pN, + AEP_VOID_PTR pResult, + AEP_TRANSACTION_ID* pidTransID); + +typedef AEP_RV t_AEP_ModExpCrt(AEP_CONNECTION_HNDL hConnection, + AEP_VOID_PTR pA, AEP_VOID_PTR pP, + AEP_VOID_PTR pQ, + AEP_VOID_PTR pDmp1, AEP_VOID_PTR pDmq1, + AEP_VOID_PTR pIqmp, + AEP_VOID_PTR pResult, + AEP_TRANSACTION_ID* pidTransID); + +#ifdef AEPRAND +typedef AEP_RV t_AEP_GenRandom(AEP_CONNECTION_HNDL hConnection, + AEP_U32 Len, + AEP_U32 Type, + AEP_VOID_PTR pResult, + AEP_TRANSACTION_ID* pidTransID); +#endif + +typedef AEP_RV t_AEP_Initialize(AEP_VOID_PTR pInitArgs); +typedef AEP_RV t_AEP_Finalize(void); +typedef AEP_RV t_AEP_SetBNCallBacks(AEP_RV (*GetBigNumSizeFunc)(AEP_VOID_PTR ArbBigNum, AEP_U32* BigNumSize), + AEP_RV (*MakeAEPBigNumFunc)(AEP_VOID_PTR ArbBigNum, AEP_U32 BigNumSize, unsigned char* AEP_BigNum), + AEP_RV (*ConverAEPBigNumFunc)(void* ArbBigNum, AEP_U32 BigNumSize, unsigned char* AEP_BigNum)); + diff --git a/node-v0.8.14/deps/openssl/openssl/engines/vendor_defns/atalla.h b/node-v0.8.14/deps/openssl/openssl/engines/vendor_defns/atalla.h new file mode 100644 index 0000000..149970d --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/engines/vendor_defns/atalla.h @@ -0,0 +1,48 @@ +/* This header declares the necessary definitions for using the exponentiation + * acceleration capabilities of Atalla cards. The only cryptographic operation + * is performed by "ASI_RSAPrivateKeyOpFn" and this takes a structure that + * defines an "RSA private key". However, it is really only performing a + * regular mod_exp using the supplied modulus and exponent - no CRT form is + * being used. Hence, it is a generic mod_exp function in disguise, and we use + * it as such. + * + * Thanks to the people at Atalla for letting me know these definitions are + * fine and that they can be reproduced here. + * + * Geoff. + */ + +typedef struct ItemStr + { + unsigned char *data; + int len; + } Item; + +typedef struct RSAPrivateKeyStr + { + void *reserved; + Item version; + Item modulus; + Item publicExponent; + Item privateExponent; + Item prime[2]; + Item exponent[2]; + Item coefficient; + } RSAPrivateKey; + +/* Predeclare the function pointer types that we dynamically load from the DSO. + * These use the same names and form that Ben's original support code had (in + * crypto/bn/bn_exp.c) unless of course I've inadvertently changed the style + * somewhere along the way! + */ + +typedef int tfnASI_GetPerformanceStatistics(int reset_flag, + unsigned int *ret_buf); + +typedef int tfnASI_GetHardwareConfig(long card_num, unsigned int *ret_buf); + +typedef int tfnASI_RSAPrivateKeyOpFn(RSAPrivateKey * rsaKey, + unsigned char *output, + unsigned char *input, + unsigned int modulus_len); + diff --git a/node-v0.8.14/deps/openssl/openssl/engines/vendor_defns/cswift.h b/node-v0.8.14/deps/openssl/openssl/engines/vendor_defns/cswift.h new file mode 100644 index 0000000..6007932 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/engines/vendor_defns/cswift.h @@ -0,0 +1,234 @@ +/* Attribution notice: Rainbow have generously allowed me to reproduce + * the necessary definitions here from their API. This means the support + * can build independently of whether application builders have the + * API or hardware. This will allow developers to easily produce software + * that has latent hardware support for any users that have accelertors + * installed, without the developers themselves needing anything extra. + * + * I have only clipped the parts from the CryptoSwift header files that + * are (or seem) relevant to the CryptoSwift support code. This is + * simply to keep the file sizes reasonable. + * [Geoff] + */ + + +/* NB: These type widths do *not* seem right in general, in particular + * they're not terribly friendly to 64-bit architectures (unsigned long) + * will be 64-bit on IA-64 for a start. I'm leaving these alone as they + * agree with Rainbow's API and this will only be called into question + * on platforms with Rainbow support anyway! ;-) */ + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +typedef long SW_STATUS; /* status */ +typedef unsigned char SW_BYTE; /* 8 bit byte */ +typedef unsigned short SW_U16; /* 16 bit number */ +#if defined(_IRIX) +#include +typedef __uint32_t SW_U32; +#else +typedef unsigned long SW_U32; /* 32 bit integer */ +#endif + +#if defined(OPENSSL_SYS_WIN32) + typedef struct _SW_U64 { + SW_U32 low32; + SW_U32 high32; + } SW_U64; /* 64 bit integer */ +#elif defined(OPENSSL_SYS_MACINTOSH_CLASSIC) + typedef longlong SW_U64 +#else /* Unix variants */ + typedef struct _SW_U64 { + SW_U32 low32; + SW_U32 high32; + } SW_U64; /* 64 bit integer */ +#endif + +/* status codes */ +#define SW_OK (0L) +#define SW_ERR_BASE (-10000L) +#define SW_ERR_NO_CARD (SW_ERR_BASE-1) /* The Card is not present */ +#define SW_ERR_CARD_NOT_READY (SW_ERR_BASE-2) /* The card has not powered */ + /* up yet */ +#define SW_ERR_TIME_OUT (SW_ERR_BASE-3) /* Execution of a command */ + /* time out */ +#define SW_ERR_NO_EXECUTE (SW_ERR_BASE-4) /* The Card failed to */ + /* execute the command */ +#define SW_ERR_INPUT_NULL_PTR (SW_ERR_BASE-5) /* a required pointer is */ + /* NULL */ +#define SW_ERR_INPUT_SIZE (SW_ERR_BASE-6) /* size is invalid, too */ + /* small, too large. */ +#define SW_ERR_INVALID_HANDLE (SW_ERR_BASE-7) /* Invalid SW_ACC_CONTEXT */ + /* handle */ +#define SW_ERR_PENDING (SW_ERR_BASE-8) /* A request is already out- */ + /* standing at this */ + /* context handle */ +#define SW_ERR_AVAILABLE (SW_ERR_BASE-9) /* A result is available. */ +#define SW_ERR_NO_PENDING (SW_ERR_BASE-10)/* No request is pending. */ +#define SW_ERR_NO_MEMORY (SW_ERR_BASE-11)/* Not enough memory */ +#define SW_ERR_BAD_ALGORITHM (SW_ERR_BASE-12)/* Invalid algorithm type */ + /* in SW_PARAM structure */ +#define SW_ERR_MISSING_KEY (SW_ERR_BASE-13)/* No key is associated with */ + /* context. */ + /* swAttachKeyParam() is */ + /* not called. */ +#define SW_ERR_KEY_CMD_MISMATCH \ + (SW_ERR_BASE-14)/* Cannot perform requested */ + /* SW_COMMAND_CODE since */ + /* key attached via */ + /* swAttachKeyParam() */ + /* cannot be used for this*/ + /* SW_COMMAND_CODE. */ +#define SW_ERR_NOT_IMPLEMENTED \ + (SW_ERR_BASE-15)/* Not implemented */ +#define SW_ERR_BAD_COMMAND (SW_ERR_BASE-16)/* Bad command code */ +#define SW_ERR_BAD_ITEM_SIZE (SW_ERR_BASE-17)/* too small or too large in */ + /* the "initems" or */ + /* "outitems". */ +#define SW_ERR_BAD_ACCNUM (SW_ERR_BASE-18)/* Bad accelerator number */ +#define SW_ERR_SELFTEST_FAIL (SW_ERR_BASE-19)/* At least one of the self */ + /* test fail, look at the */ + /* selfTestBitmap in */ + /* SW_ACCELERATOR_INFO for*/ + /* details. */ +#define SW_ERR_MISALIGN (SW_ERR_BASE-20)/* Certain alogrithms require*/ + /* key materials aligned */ + /* in certain order, e.g. */ + /* 128 bit for CRT */ +#define SW_ERR_OUTPUT_NULL_PTR \ + (SW_ERR_BASE-21)/* a required pointer is */ + /* NULL */ +#define SW_ERR_OUTPUT_SIZE \ + (SW_ERR_BASE-22)/* size is invalid, too */ + /* small, too large. */ +#define SW_ERR_FIRMWARE_CHECKSUM \ + (SW_ERR_BASE-23)/* firmware checksum mismatch*/ + /* download failed. */ +#define SW_ERR_UNKNOWN_FIRMWARE \ + (SW_ERR_BASE-24)/* unknown firmware error */ +#define SW_ERR_INTERRUPT (SW_ERR_BASE-25)/* request is abort when */ + /* it's waiting to be */ + /* completed. */ +#define SW_ERR_NVWRITE_FAIL (SW_ERR_BASE-26)/* error in writing to Non- */ + /* volatile memory */ +#define SW_ERR_NVWRITE_RANGE (SW_ERR_BASE-27)/* out of range error in */ + /* writing to NV memory */ +#define SW_ERR_RNG_ERROR (SW_ERR_BASE-28)/* Random Number Generation */ + /* failure */ +#define SW_ERR_DSS_FAILURE (SW_ERR_BASE-29)/* DSS Sign or Verify failure*/ +#define SW_ERR_MODEXP_FAILURE (SW_ERR_BASE-30)/* Failure in various math */ + /* calculations */ +#define SW_ERR_ONBOARD_MEMORY (SW_ERR_BASE-31)/* Error in accessing on - */ + /* board memory */ +#define SW_ERR_FIRMWARE_VERSION \ + (SW_ERR_BASE-32)/* Wrong version in firmware */ + /* update */ +#define SW_ERR_ZERO_WORKING_ACCELERATOR \ + (SW_ERR_BASE-44)/* All accelerators are bad */ + + + /* algorithm type */ +#define SW_ALG_CRT 1 +#define SW_ALG_EXP 2 +#define SW_ALG_DSA 3 +#define SW_ALG_NVDATA 4 + + /* command code */ +#define SW_CMD_MODEXP_CRT 1 /* perform Modular Exponentiation using */ + /* Chinese Remainder Theorem (CRT) */ +#define SW_CMD_MODEXP 2 /* perform Modular Exponentiation */ +#define SW_CMD_DSS_SIGN 3 /* perform DSS sign */ +#define SW_CMD_DSS_VERIFY 4 /* perform DSS verify */ +#define SW_CMD_RAND 5 /* perform random number generation */ +#define SW_CMD_NVREAD 6 /* perform read to nonvolatile RAM */ +#define SW_CMD_NVWRITE 7 /* perform write to nonvolatile RAM */ + +typedef SW_U32 SW_ALGTYPE; /* alogrithm type */ +typedef SW_U32 SW_STATE; /* state */ +typedef SW_U32 SW_COMMAND_CODE; /* command code */ +typedef SW_U32 SW_COMMAND_BITMAP[4]; /* bitmap */ + +typedef struct _SW_LARGENUMBER { + SW_U32 nbytes; /* number of bytes in the buffer "value" */ + SW_BYTE* value; /* the large integer as a string of */ + /* bytes in network (big endian) order */ +} SW_LARGENUMBER; + +#if defined(OPENSSL_SYS_WIN32) + #include + typedef HANDLE SW_OSHANDLE; /* handle to kernel object */ + #define SW_OS_INVALID_HANDLE INVALID_HANDLE_VALUE + #define SW_CALLCONV _stdcall +#elif defined(OPENSSL_SYS_MACINTOSH_CLASSIC) + /* async callback mechanisms */ + /* swiftCallbackLevel */ + #define SW_MAC_CALLBACK_LEVEL_NO 0 + #define SW_MAC_CALLBACK_LEVEL_HARDWARE 1 /* from the hardware ISR */ + #define SW_MAC_CALLBACK_LEVEL_SECONDARY 2 /* as secondary ISR */ + typedef int SW_MAC_CALLBACK_LEVEL; + typedef int SW_OSHANDLE; + #define SW_OS_INVALID_HANDLE (-1) + #define SW_CALLCONV +#else /* Unix variants */ + typedef int SW_OSHANDLE; /* handle to driver */ + #define SW_OS_INVALID_HANDLE (-1) + #define SW_CALLCONV +#endif + +typedef struct _SW_CRT { + SW_LARGENUMBER p; /* prime number p */ + SW_LARGENUMBER q; /* prime number q */ + SW_LARGENUMBER dmp1; /* exponent1 */ + SW_LARGENUMBER dmq1; /* exponent2 */ + SW_LARGENUMBER iqmp; /* CRT coefficient */ +} SW_CRT; + +typedef struct _SW_EXP { + SW_LARGENUMBER modulus; /* modulus */ + SW_LARGENUMBER exponent;/* exponent */ +} SW_EXP; + +typedef struct _SW_DSA { + SW_LARGENUMBER p; /* */ + SW_LARGENUMBER q; /* */ + SW_LARGENUMBER g; /* */ + SW_LARGENUMBER key; /* private/public key */ +} SW_DSA; + +typedef struct _SW_NVDATA { + SW_U32 accnum; /* accelerator board number */ + SW_U32 offset; /* offset in byte */ +} SW_NVDATA; + +typedef struct _SW_PARAM { + SW_ALGTYPE type; /* type of the alogrithm */ + union { + SW_CRT crt; + SW_EXP exp; + SW_DSA dsa; + SW_NVDATA nvdata; + } up; +} SW_PARAM; + +typedef SW_U32 SW_CONTEXT_HANDLE; /* opaque context handle */ + + +/* Now the OpenSSL bits, these function types are the for the function + * pointers that will bound into the Rainbow shared libraries. */ +typedef SW_STATUS SW_CALLCONV t_swAcquireAccContext(SW_CONTEXT_HANDLE *hac); +typedef SW_STATUS SW_CALLCONV t_swAttachKeyParam(SW_CONTEXT_HANDLE hac, + SW_PARAM *key_params); +typedef SW_STATUS SW_CALLCONV t_swSimpleRequest(SW_CONTEXT_HANDLE hac, + SW_COMMAND_CODE cmd, + SW_LARGENUMBER pin[], + SW_U32 pin_count, + SW_LARGENUMBER pout[], + SW_U32 pout_count); +typedef SW_STATUS SW_CALLCONV t_swReleaseAccContext(SW_CONTEXT_HANDLE hac); + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + diff --git a/node-v0.8.14/deps/openssl/openssl/engines/vendor_defns/hw_4758_cca.h b/node-v0.8.14/deps/openssl/openssl/engines/vendor_defns/hw_4758_cca.h new file mode 100644 index 0000000..296636e --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/engines/vendor_defns/hw_4758_cca.h @@ -0,0 +1,149 @@ +/**********************************************************************/ +/* */ +/* Prototypes of the CCA verbs used by the 4758 CCA openssl driver */ +/* */ +/* Maurice Gittens */ +/* */ +/**********************************************************************/ + +#ifndef __HW_4758_CCA__ +#define __HW_4758_CCA__ + +/* + * Only WIN32 support for now + */ +#if defined(WIN32) + + #define CCA_LIB_NAME "CSUNSAPI" + + #define CSNDPKX "CSNDPKX_32" + #define CSNDKRR "CSNDKRR_32" + #define CSNDPKE "CSNDPKE_32" + #define CSNDPKD "CSNDPKD_32" + #define CSNDDSV "CSNDDSV_32" + #define CSNDDSG "CSNDDSG_32" + #define CSNBRNG "CSNBRNG_32" + + #define SECURITYAPI __stdcall +#else + /* Fixme!! + Find out the values of these constants for other platforms. + */ + #define CCA_LIB_NAME "CSUNSAPI" + + #define CSNDPKX "CSNDPKX" + #define CSNDKRR "CSNDKRR" + #define CSNDPKE "CSNDPKE" + #define CSNDPKD "CSNDPKD" + #define CSNDDSV "CSNDDSV" + #define CSNDDSG "CSNDDSG" + #define CSNBRNG "CSNBRNG" + + #define SECURITYAPI +#endif + +/* + * security API prototypes + */ + +/* PKA Key Record Read */ +typedef void (SECURITYAPI *F_KEYRECORDREAD) + (long * return_code, + long * reason_code, + long * exit_data_length, + unsigned char * exit_data, + long * rule_array_count, + unsigned char * rule_array, + unsigned char * key_label, + long * key_token_length, + unsigned char * key_token); + +/* Random Number Generate */ +typedef void (SECURITYAPI *F_RANDOMNUMBERGENERATE) + (long * return_code, + long * reason_code, + long * exit_data_length, + unsigned char * exit_data, + unsigned char * form, + unsigned char * random_number); + +/* Digital Signature Generate */ +typedef void (SECURITYAPI *F_DIGITALSIGNATUREGENERATE) + (long * return_code, + long * reason_code, + long * exit_data_length, + unsigned char * exit_data, + long * rule_array_count, + unsigned char * rule_array, + long * PKA_private_key_id_length, + unsigned char * PKA_private_key_id, + long * hash_length, + unsigned char * hash, + long * signature_field_length, + long * signature_bit_length, + unsigned char * signature_field); + +/* Digital Signature Verify */ +typedef void (SECURITYAPI *F_DIGITALSIGNATUREVERIFY)( + long * return_code, + long * reason_code, + long * exit_data_length, + unsigned char * exit_data, + long * rule_array_count, + unsigned char * rule_array, + long * PKA_public_key_id_length, + unsigned char * PKA_public_key_id, + long * hash_length, + unsigned char * hash, + long * signature_field_length, + unsigned char * signature_field); + +/* PKA Public Key Extract */ +typedef void (SECURITYAPI *F_PUBLICKEYEXTRACT)( + long * return_code, + long * reason_code, + long * exit_data_length, + unsigned char * exit_data, + long * rule_array_count, + unsigned char * rule_array, + long * source_key_identifier_length, + unsigned char * source_key_identifier, + long * target_key_token_length, + unsigned char * target_key_token); + +/* PKA Encrypt */ +typedef void (SECURITYAPI *F_PKAENCRYPT) + (long * return_code, + long * reason_code, + long * exit_data_length, + unsigned char * exit_data, + long * rule_array_count, + unsigned char * rule_array, + long * key_value_length, + unsigned char * key_value, + long * data_struct_length, + unsigned char * data_struct, + long * RSA_public_key_length, + unsigned char * RSA_public_key, + long * RSA_encipher_length, + unsigned char * RSA_encipher ); + +/* PKA Decrypt */ +typedef void (SECURITYAPI *F_PKADECRYPT) + (long * return_code, + long * reason_code, + long * exit_data_length, + unsigned char * exit_data, + long * rule_array_count, + unsigned char * rule_array, + long * enciphered_key_length, + unsigned char * enciphered_key, + long * data_struct_length, + unsigned char * data_struct, + long * RSA_private_key_length, + unsigned char * RSA_private_key, + long * key_value_length, + unsigned char * key_value ); + + +#endif diff --git a/node-v0.8.14/deps/openssl/openssl/engines/vendor_defns/hw_ubsec.h b/node-v0.8.14/deps/openssl/openssl/engines/vendor_defns/hw_ubsec.h new file mode 100644 index 0000000..b6619d4 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/engines/vendor_defns/hw_ubsec.h @@ -0,0 +1,100 @@ +/****************************************************************************** + * + * Copyright 2000 + * Broadcom Corporation + * 16215 Alton Parkway + * PO Box 57013 + * Irvine CA 92619-7013 + * + *****************************************************************************/ +/* + * Broadcom Corporation uBSec SDK + */ +/* + * Character device header file. + */ +/* + * Revision History: + * + * October 2000 JTT Created. + */ + +#define MAX_PUBLIC_KEY_BITS (1024) +#define MAX_PUBLIC_KEY_BYTES (1024/8) +#define SHA_BIT_SIZE (160) +#define MAX_CRYPTO_KEY_LENGTH 24 +#define MAX_MAC_KEY_LENGTH 64 +#define UBSEC_CRYPTO_DEVICE_NAME ((unsigned char *)"/dev/ubscrypt") +#define UBSEC_KEY_DEVICE_NAME ((unsigned char *)"/dev/ubskey") + +/* Math command types. */ +#define UBSEC_MATH_MODADD 0x0001 +#define UBSEC_MATH_MODSUB 0x0002 +#define UBSEC_MATH_MODMUL 0x0004 +#define UBSEC_MATH_MODEXP 0x0008 +#define UBSEC_MATH_MODREM 0x0010 +#define UBSEC_MATH_MODINV 0x0020 + +typedef long ubsec_MathCommand_t; +typedef long ubsec_RNGCommand_t; + +typedef struct ubsec_crypto_context_s { + unsigned int flags; + unsigned char crypto[MAX_CRYPTO_KEY_LENGTH]; + unsigned char auth[MAX_MAC_KEY_LENGTH]; +} ubsec_crypto_context_t, *ubsec_crypto_context_p; + +/* + * Predeclare the function pointer types that we dynamically load from the DSO. + */ + +typedef int t_UBSEC_ubsec_bytes_to_bits(unsigned char *n, int bytes); + +typedef int t_UBSEC_ubsec_bits_to_bytes(int bits); + +typedef int t_UBSEC_ubsec_open(unsigned char *device); + +typedef int t_UBSEC_ubsec_close(int fd); + +typedef int t_UBSEC_diffie_hellman_generate_ioctl (int fd, + unsigned char *x, int *x_len, unsigned char *y, int *y_len, + unsigned char *g, int g_len, unsigned char *m, int m_len, + unsigned char *userX, int userX_len, int random_bits); + +typedef int t_UBSEC_diffie_hellman_agree_ioctl (int fd, + unsigned char *x, int x_len, unsigned char *y, int y_len, + unsigned char *m, int m_len, unsigned char *k, int *k_len); + +typedef int t_UBSEC_rsa_mod_exp_ioctl (int fd, + unsigned char *x, int x_len, unsigned char *m, int m_len, + unsigned char *e, int e_len, unsigned char *y, int *y_len); + +typedef int t_UBSEC_rsa_mod_exp_crt_ioctl (int fd, + unsigned char *x, int x_len, unsigned char *qinv, int qinv_len, + unsigned char *edq, int edq_len, unsigned char *q, int q_len, + unsigned char *edp, int edp_len, unsigned char *p, int p_len, + unsigned char *y, int *y_len); + +typedef int t_UBSEC_dsa_sign_ioctl (int fd, + int hash, unsigned char *data, int data_len, + unsigned char *rndom, int random_len, + unsigned char *p, int p_len, unsigned char *q, int q_len, + unsigned char *g, int g_len, unsigned char *key, int key_len, + unsigned char *r, int *r_len, unsigned char *s, int *s_len); + +typedef int t_UBSEC_dsa_verify_ioctl (int fd, + int hash, unsigned char *data, int data_len, + unsigned char *p, int p_len, unsigned char *q, int q_len, + unsigned char *g, int g_len, unsigned char *key, int key_len, + unsigned char *r, int r_len, unsigned char *s, int s_len, + unsigned char *v, int *v_len); + +typedef int t_UBSEC_math_accelerate_ioctl(int fd, ubsec_MathCommand_t command, + unsigned char *ModN, int *ModN_len, unsigned char *ExpE, int *ExpE_len, + unsigned char *ParamA, int *ParamA_len, unsigned char *ParamB, int *ParamB_len, + unsigned char *Result, int *Result_len); + +typedef int t_UBSEC_rng_ioctl(int fd, ubsec_RNGCommand_t command, + unsigned char *Result, int *Result_len); + +typedef int t_UBSEC_max_key_len_ioctl(int fd, int *max_key_len); diff --git a/node-v0.8.14/deps/openssl/openssl/engines/vendor_defns/hwcryptohook.h b/node-v0.8.14/deps/openssl/openssl/engines/vendor_defns/hwcryptohook.h new file mode 100644 index 0000000..482f1f2 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/engines/vendor_defns/hwcryptohook.h @@ -0,0 +1,486 @@ +/* + * ModExp / RSA (with/without KM) plugin API + * + * The application will load a dynamic library which + * exports entrypoint(s) defined in this file. + * + * This set of entrypoints provides only a multithreaded, + * synchronous-within-each-thread, facility. + * + * + * This file is Copyright 1998-2000 nCipher Corporation Limited. + * + * Redistribution and use in source and binary forms, with opr without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the copyright notice, + * this list of conditions, and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions, and the following + * disclaimer, in the documentation and/or other materials provided + * with the distribution + * + * IN NO EVENT SHALL NCIPHER CORPORATION LIMITED (`NCIPHER') AND/OR + * ANY OTHER AUTHORS OR DISTRIBUTORS OF THIS FILE BE LIABLE for any + * damages arising directly or indirectly from this file, its use or + * this licence. Without prejudice to the generality of the + * foregoing: all liability shall be excluded for direct, indirect, + * special, incidental, consequential or other damages or any loss of + * profits, business, revenue goodwill or anticipated savings; + * liability shall be excluded even if nCipher or anyone else has been + * advised of the possibility of damage. In any event, if the + * exclusion of liability is not effective, the liability of nCipher + * or any author or distributor shall be limited to the lesser of the + * price paid and 1,000 pounds sterling. This licence only fails to + * exclude or limit liability for death or personal injury arising out + * of negligence, and only to the extent that such an exclusion or + * limitation is not effective. + * + * NCIPHER AND THE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ALL + * AND ANY WARRANTIES (WHETHER EXPRESS OR IMPLIED), including, but not + * limited to, any implied warranties of merchantability, fitness for + * a particular purpose, satisfactory quality, and/or non-infringement + * of any third party rights. + * + * US Government use: This software and documentation is Commercial + * Computer Software and Computer Software Documentation, as defined in + * sub-paragraphs (a)(1) and (a)(5) of DFAR 252.227-7014, "Rights in + * Noncommercial Computer Software and Noncommercial Computer Software + * Documentation." Use, duplication or disclosure by the Government is + * subject to the terms and conditions specified here. + * + * By using or distributing this file you will be accepting these + * terms and conditions, including the limitation of liability and + * lack of warranty. If you do not wish to accept these terms and + * conditions, DO NOT USE THE FILE. + * + * + * The actual dynamically loadable plugin, and the library files for + * static linking, which are also provided in some distributions, are + * not covered by the licence described above. You should have + * received a separate licence with terms and conditions for these + * library files; if you received the library files without a licence, + * please contact nCipher. + * + * + * $Id: hwcryptohook.h,v 1.1 2002/10/11 17:10:59 levitte Exp $ + */ + +#ifndef HWCRYPTOHOOK_H +#define HWCRYPTOHOOK_H + +#include +#include + +#ifndef HWCRYPTOHOOK_DECLARE_APPTYPES +#define HWCRYPTOHOOK_DECLARE_APPTYPES 1 +#endif + +#define HWCRYPTOHOOK_ERROR_FAILED -1 +#define HWCRYPTOHOOK_ERROR_FALLBACK -2 +#define HWCRYPTOHOOK_ERROR_MPISIZE -3 + +#if HWCRYPTOHOOK_DECLARE_APPTYPES + +/* These structs are defined by the application and opaque to the + * crypto plugin. The application may define these as it sees fit. + * Default declarations are provided here, but the application may + * #define HWCRYPTOHOOK_DECLARE_APPTYPES 0 + * to prevent these declarations, and instead provide its own + * declarations of these types. (Pointers to them must still be + * ordinary pointers to structs or unions, or the resulting combined + * program will have a type inconsistency.) + */ +typedef struct HWCryptoHook_MutexValue HWCryptoHook_Mutex; +typedef struct HWCryptoHook_CondVarValue HWCryptoHook_CondVar; +typedef struct HWCryptoHook_PassphraseContextValue HWCryptoHook_PassphraseContext; +typedef struct HWCryptoHook_CallerContextValue HWCryptoHook_CallerContext; + +#endif /* HWCRYPTOHOOK_DECLARE_APPTYPES */ + +/* These next two structs are opaque to the application. The crypto + * plugin will return pointers to them; the caller simply manipulates + * the pointers. + */ +typedef struct HWCryptoHook_Context *HWCryptoHook_ContextHandle; +typedef struct HWCryptoHook_RSAKey *HWCryptoHook_RSAKeyHandle; + +typedef struct { + char *buf; + size_t size; +} HWCryptoHook_ErrMsgBuf; +/* Used for error reporting. When a HWCryptoHook function fails it + * will return a sentinel value (0 for pointer-valued functions, or a + * negative number, usually HWCRYPTOHOOK_ERROR_FAILED, for + * integer-valued ones). It will, if an ErrMsgBuf is passed, also put + * an error message there. + * + * size is the size of the buffer, and will not be modified. If you + * pass 0 for size you must pass 0 for buf, and nothing will be + * recorded (just as if you passed 0 for the struct pointer). + * Messages written to the buffer will always be null-terminated, even + * when truncated to fit within size bytes. + * + * The contents of the buffer are not defined if there is no error. + */ + +typedef struct HWCryptoHook_MPIStruct { + unsigned char *buf; + size_t size; +} HWCryptoHook_MPI; +/* When one of these is returned, a pointer is passed to the function. + * At call, size is the space available. Afterwards it is updated to + * be set to the actual length (which may be more than the space available, + * if there was not enough room and the result was truncated). + * buf (the pointer) is not updated. + * + * size is in bytes and may be zero at call or return, but must be a + * multiple of the limb size. Zero limbs at the MS end are not + * permitted. + */ + +#define HWCryptoHook_InitFlags_FallbackModExp 0x0002UL +#define HWCryptoHook_InitFlags_FallbackRSAImmed 0x0004UL +/* Enable requesting fallback to software in case of problems with the + * hardware support. This indicates to the crypto provider that the + * application is prepared to fall back to software operation if the + * ModExp* or RSAImmed* functions return HWCRYPTOHOOK_ERROR_FALLBACK. + * Without this flag those calls will never return + * HWCRYPTOHOOK_ERROR_FALLBACK. The flag will also cause the crypto + * provider to avoid repeatedly attempting to contact dead hardware + * within a short interval, if appropriate. + */ + +#define HWCryptoHook_InitFlags_SimpleForkCheck 0x0010UL +/* Without _SimpleForkCheck the library is allowed to assume that the + * application will not fork and call the library in the child(ren). + * + * When it is specified, this is allowed. However, after a fork + * neither parent nor child may unload any loaded keys or call + * _Finish. Instead, they should call exit (or die with a signal) + * without calling _Finish. After all the children have died the + * parent may unload keys or call _Finish. + * + * This flag only has any effect on UN*X platforms. + */ + +typedef struct { + unsigned long flags; + void *logstream; /* usually a FILE*. See below. */ + + size_t limbsize; /* bignum format - size of radix type, must be power of 2 */ + int mslimbfirst; /* 0 or 1 */ + int msbytefirst; /* 0 or 1; -1 = native */ + + /* All the callback functions should return 0 on success, or a + * nonzero integer (whose value will be visible in the error message + * put in the buffer passed to the call). + * + * If a callback is not available pass a null function pointer. + * + * The callbacks may not call down again into the crypto plugin. + */ + + /* For thread-safety. Set everything to 0 if you promise only to be + * singlethreaded. maxsimultaneous is the number of calls to + * ModExp[Crt]/RSAImmed{Priv,Pub}/RSA. If you don't know what to + * put there then say 0 and the hook library will use a default. + * + * maxmutexes is a small limit on the number of simultaneous mutexes + * which will be requested by the library. If there is no small + * limit, set it to 0. If the crypto plugin cannot create the + * advertised number of mutexes the calls to its functions may fail. + * If a low number of mutexes is advertised the plugin will try to + * do the best it can. Making larger numbers of mutexes available + * may improve performance and parallelism by reducing contention + * over critical sections. Unavailability of any mutexes, implying + * single-threaded operation, should be indicated by the setting + * mutex_init et al to 0. + */ + int maxmutexes; + int maxsimultaneous; + size_t mutexsize; + int (*mutex_init)(HWCryptoHook_Mutex*, HWCryptoHook_CallerContext *cactx); + int (*mutex_acquire)(HWCryptoHook_Mutex*); + void (*mutex_release)(HWCryptoHook_Mutex*); + void (*mutex_destroy)(HWCryptoHook_Mutex*); + + /* For greater efficiency, can use condition vars internally for + * synchronisation. In this case maxsimultaneous is ignored, but + * the other mutex stuff must be available. In singlethreaded + * programs, set everything to 0. + */ + size_t condvarsize; + int (*condvar_init)(HWCryptoHook_CondVar*, HWCryptoHook_CallerContext *cactx); + int (*condvar_wait)(HWCryptoHook_CondVar*, HWCryptoHook_Mutex*); + void (*condvar_signal)(HWCryptoHook_CondVar*); + void (*condvar_broadcast)(HWCryptoHook_CondVar*); + void (*condvar_destroy)(HWCryptoHook_CondVar*); + + /* The semantics of acquiring and releasing mutexes and broadcasting + * and waiting on condition variables are expected to be those from + * POSIX threads (pthreads). The mutexes may be (in pthread-speak) + * fast mutexes, recursive mutexes, or nonrecursive ones. + * + * The _release/_signal/_broadcast and _destroy functions must + * always succeed when given a valid argument; if they are given an + * invalid argument then the program (crypto plugin + application) + * has an internal error, and they should abort the program. + */ + + int (*getpassphrase)(const char *prompt_info, + int *len_io, char *buf, + HWCryptoHook_PassphraseContext *ppctx, + HWCryptoHook_CallerContext *cactx); + /* Passphrases and the prompt_info, if they contain high-bit-set + * characters, are UTF-8. The prompt_info may be a null pointer if + * no prompt information is available (it should not be an empty + * string). It will not contain text like `enter passphrase'; + * instead it might say something like `Operator Card for John + * Smith' or `SmartCard in nFast Module #1, Slot #1'. + * + * buf points to a buffer in which to return the passphrase; on + * entry *len_io is the length of the buffer. It should be updated + * by the callback. The returned passphrase should not be + * null-terminated by the callback. + */ + + int (*getphystoken)(const char *prompt_info, + const char *wrong_info, + HWCryptoHook_PassphraseContext *ppctx, + HWCryptoHook_CallerContext *cactx); + /* Requests that the human user physically insert a different + * smartcard, DataKey, etc. The plugin should check whether the + * currently inserted token(s) are appropriate, and if they are it + * should not make this call. + * + * prompt_info is as before. wrong_info is a description of the + * currently inserted token(s) so that the user is told what + * something is. wrong_info, like prompt_info, may be null, but + * should not be an empty string. Its contents should be + * syntactically similar to that of prompt_info. + */ + + /* Note that a single LoadKey operation might cause several calls to + * getpassphrase and/or requestphystoken. If requestphystoken is + * not provided (ie, a null pointer is passed) then the plugin may + * not support loading keys for which authorisation by several cards + * is required. If getpassphrase is not provided then cards with + * passphrases may not be supported. + * + * getpassphrase and getphystoken do not need to check that the + * passphrase has been entered correctly or the correct token + * inserted; the crypto plugin will do that. If this is not the + * case then the crypto plugin is responsible for calling these + * routines again as appropriate until the correct token(s) and + * passphrase(s) are supplied as required, or until any retry limits + * implemented by the crypto plugin are reached. + * + * In either case, the application must allow the user to say `no' + * or `cancel' to indicate that they do not know the passphrase or + * have the appropriate token; this should cause the callback to + * return nonzero indicating error. + */ + + void (*logmessage)(void *logstream, const char *message); + /* A log message will be generated at least every time something goes + * wrong and an ErrMsgBuf is filled in (or would be if one was + * provided). Other diagnostic information may be written there too, + * including more detailed reasons for errors which are reported in an + * ErrMsgBuf. + * + * When a log message is generated, this callback is called. It + * should write a message to the relevant logging arrangements. + * + * The message string passed will be null-terminated and may be of arbitrary + * length. It will not be prefixed by the time and date, nor by the + * name of the library that is generating it - if this is required, + * the logmessage callback must do it. The message will not have a + * trailing newline (though it may contain internal newlines). + * + * If a null pointer is passed for logmessage a default function is + * used. The default function treats logstream as a FILE* which has + * been converted to a void*. If logstream is 0 it does nothing. + * Otherwise it prepends the date and time and library name and + * writes the message to logstream. Each line will be prefixed by a + * descriptive string containing the date, time and identity of the + * crypto plugin. Errors on the logstream are not reported + * anywhere, and the default function doesn't flush the stream, so + * the application must set the buffering how it wants it. + * + * The crypto plugin may also provide a facility to have copies of + * log messages sent elsewhere, and or for adjusting the verbosity + * of the log messages; any such facilities will be configured by + * external means. + */ + +} HWCryptoHook_InitInfo; + +typedef +HWCryptoHook_ContextHandle HWCryptoHook_Init_t(const HWCryptoHook_InitInfo *initinfo, + size_t initinfosize, + const HWCryptoHook_ErrMsgBuf *errors, + HWCryptoHook_CallerContext *cactx); +extern HWCryptoHook_Init_t HWCryptoHook_Init; + +/* Caller should set initinfosize to the size of the HWCryptoHook struct, + * so it can be extended later. + * + * On success, a message for display or logging by the server, + * including the name and version number of the plugin, will be filled + * in into *errors; on failure *errors is used for error handling, as + * usual. + */ + +/* All these functions return 0 on success, HWCRYPTOHOOK_ERROR_FAILED + * on most failures. HWCRYPTOHOOK_ERROR_MPISIZE means at least one of + * the output MPI buffer(s) was too small; the sizes of all have been + * set to the desired size (and for those where the buffer was large + * enough, the value may have been copied in), and no error message + * has been recorded. + * + * You may pass 0 for the errors struct. In any case, unless you set + * _NoStderr at init time then messages may be reported to stderr. + */ + +/* The RSAImmed* functions (and key managed RSA) only work with + * modules which have an RSA patent licence - currently that means KM + * units; the ModExp* ones work with all modules, so you need a patent + * licence in the software in the US. They are otherwise identical. + */ + +typedef +void HWCryptoHook_Finish_t(HWCryptoHook_ContextHandle hwctx); +extern HWCryptoHook_Finish_t HWCryptoHook_Finish; +/* You must not have any calls going or keys loaded when you call this. */ + +typedef +int HWCryptoHook_RandomBytes_t(HWCryptoHook_ContextHandle hwctx, + unsigned char *buf, size_t len, + const HWCryptoHook_ErrMsgBuf *errors); +extern HWCryptoHook_RandomBytes_t HWCryptoHook_RandomBytes; + +typedef +int HWCryptoHook_ModExp_t(HWCryptoHook_ContextHandle hwctx, + HWCryptoHook_MPI a, + HWCryptoHook_MPI p, + HWCryptoHook_MPI n, + HWCryptoHook_MPI *r, + const HWCryptoHook_ErrMsgBuf *errors); +extern HWCryptoHook_ModExp_t HWCryptoHook_ModExp; + +typedef +int HWCryptoHook_RSAImmedPub_t(HWCryptoHook_ContextHandle hwctx, + HWCryptoHook_MPI m, + HWCryptoHook_MPI e, + HWCryptoHook_MPI n, + HWCryptoHook_MPI *r, + const HWCryptoHook_ErrMsgBuf *errors); +extern HWCryptoHook_RSAImmedPub_t HWCryptoHook_RSAImmedPub; + +typedef +int HWCryptoHook_ModExpCRT_t(HWCryptoHook_ContextHandle hwctx, + HWCryptoHook_MPI a, + HWCryptoHook_MPI p, + HWCryptoHook_MPI q, + HWCryptoHook_MPI dmp1, + HWCryptoHook_MPI dmq1, + HWCryptoHook_MPI iqmp, + HWCryptoHook_MPI *r, + const HWCryptoHook_ErrMsgBuf *errors); +extern HWCryptoHook_ModExpCRT_t HWCryptoHook_ModExpCRT; + +typedef +int HWCryptoHook_RSAImmedPriv_t(HWCryptoHook_ContextHandle hwctx, + HWCryptoHook_MPI m, + HWCryptoHook_MPI p, + HWCryptoHook_MPI q, + HWCryptoHook_MPI dmp1, + HWCryptoHook_MPI dmq1, + HWCryptoHook_MPI iqmp, + HWCryptoHook_MPI *r, + const HWCryptoHook_ErrMsgBuf *errors); +extern HWCryptoHook_RSAImmedPriv_t HWCryptoHook_RSAImmedPriv; + +/* The RSAImmed* and ModExp* functions may return E_FAILED or + * E_FALLBACK for failure. + * + * E_FAILED means the failure is permanent and definite and there + * should be no attempt to fall back to software. (Eg, for some + * applications, which support only the acceleration-only + * functions, the `key material' may actually be an encoded key + * identifier, and doing the operation in software would give wrong + * answers.) + * + * E_FALLBACK means that doing the computation in software would seem + * reasonable. If an application pays attention to this and is + * able to fall back, it should also set the Fallback init flags. + */ + +typedef +int HWCryptoHook_RSALoadKey_t(HWCryptoHook_ContextHandle hwctx, + const char *key_ident, + HWCryptoHook_RSAKeyHandle *keyhandle_r, + const HWCryptoHook_ErrMsgBuf *errors, + HWCryptoHook_PassphraseContext *ppctx); +extern HWCryptoHook_RSALoadKey_t HWCryptoHook_RSALoadKey; +/* The key_ident is a null-terminated string configured by the + * user via the application's usual configuration mechanisms. + * It is provided to the user by the crypto provider's key management + * system. The user must be able to enter at least any string of between + * 1 and 1023 characters inclusive, consisting of printable 7-bit + * ASCII characters. The provider should avoid using + * any characters except alphanumerics and the punctuation + * characters _ - + . / @ ~ (the user is expected to be able + * to enter these without quoting). The string may be case-sensitive. + * The application may allow the user to enter other NULL-terminated strings, + * and the provider must cope (returning an error if the string is not + * valid). + * + * If the key does not exist, no error is recorded and 0 is returned; + * keyhandle_r will be set to 0 instead of to a key handle. + */ + +typedef +int HWCryptoHook_RSAGetPublicKey_t(HWCryptoHook_RSAKeyHandle k, + HWCryptoHook_MPI *n, + HWCryptoHook_MPI *e, + const HWCryptoHook_ErrMsgBuf *errors); +extern HWCryptoHook_RSAGetPublicKey_t HWCryptoHook_RSAGetPublicKey; +/* The crypto plugin will not store certificates. + * + * Although this function for acquiring the public key value is + * provided, it is not the purpose of this API to deal fully with the + * handling of the public key. + * + * It is expected that the crypto supplier's key generation program + * will provide general facilities for producing X.509 + * self-certificates and certificate requests in PEM format. These + * will be given to the user so that they can configure them in the + * application, send them to CAs, or whatever. + * + * In case this kind of certificate handling is not appropriate, the + * crypto supplier's key generation program should be able to be + * configured not to generate such a self-certificate or certificate + * request. Then the application will need to do all of this, and + * will need to store and handle the public key and certificates + * itself. + */ + +typedef +int HWCryptoHook_RSAUnloadKey_t(HWCryptoHook_RSAKeyHandle k, + const HWCryptoHook_ErrMsgBuf *errors); +extern HWCryptoHook_RSAUnloadKey_t HWCryptoHook_RSAUnloadKey; +/* Might fail due to locking problems, or other serious internal problems. */ + +typedef +int HWCryptoHook_RSA_t(HWCryptoHook_MPI m, + HWCryptoHook_RSAKeyHandle k, + HWCryptoHook_MPI *r, + const HWCryptoHook_ErrMsgBuf *errors); +extern HWCryptoHook_RSA_t HWCryptoHook_RSA; +/* RSA private key operation (sign or decrypt) - raw, unpadded. */ + +#endif /*HWCRYPTOHOOK_H*/ diff --git a/node-v0.8.14/deps/openssl/openssl/engines/vendor_defns/sureware.h b/node-v0.8.14/deps/openssl/openssl/engines/vendor_defns/sureware.h new file mode 100644 index 0000000..e46b000 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/engines/vendor_defns/sureware.h @@ -0,0 +1,239 @@ +/* +* Written by Corinne Dive-Reclus(cdive@baltimore.com) +* +* Copyright@2001 Baltimore Technologies Ltd. +* * +* THIS FILE IS PROVIDED BY BALTIMORE TECHNOLOGIES ``AS IS'' AND * +* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * +* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * +* ARE DISCLAIMED. IN NO EVENT SHALL BALTIMORE TECHNOLOGIES BE LIABLE * +* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * +* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * +* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * +* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * +* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * +* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * +* SUCH DAMAGE. * +* +* +*/ +#ifdef WIN32 +#define SW_EXPORT __declspec ( dllexport ) +#else +#define SW_EXPORT +#endif + +/* +* List of exposed SureWare errors +*/ +#define SUREWAREHOOK_ERROR_FAILED -1 +#define SUREWAREHOOK_ERROR_FALLBACK -2 +#define SUREWAREHOOK_ERROR_UNIT_FAILURE -3 +#define SUREWAREHOOK_ERROR_DATA_SIZE -4 +#define SUREWAREHOOK_ERROR_INVALID_PAD -5 +/* +* -----------------WARNING----------------------------------- +* In all the following functions: +* msg is a string with at least 24 bytes free. +* A 24 bytes string will be concatenated to the existing content of msg. +*/ +/* +* SureWare Initialisation function +* in param threadsafe, if !=0, thread safe enabled +* return SureWareHOOK_ERROR_UNIT_FAILURE if failure, 1 if success +*/ +typedef int SureWareHook_Init_t(char*const msg,int threadsafe); +extern SW_EXPORT SureWareHook_Init_t SureWareHook_Init; +/* +* SureWare Finish function +*/ +typedef void SureWareHook_Finish_t(void); +extern SW_EXPORT SureWareHook_Finish_t SureWareHook_Finish; +/* +* PRE_CONDITION: +* DO NOT CALL ANY OF THE FOLLOWING FUNCTIONS IN CASE OF INIT FAILURE +*/ +/* +* SureWare RAND Bytes function +* In case of failure, the content of buf is unpredictable. +* return 1 if success +* SureWareHOOK_ERROR_FALLBACK if function not available in hardware +* SureWareHOOK_ERROR_FAILED if error while processing +* SureWareHOOK_ERROR_UNIT_FAILURE if hardware failure +* SUREWAREHOOK_ERROR_DATA_SIZE wrong size for buf +* +* in/out param buf : a num bytes long buffer where random bytes will be put +* in param num : the number of bytes into buf +*/ +typedef int SureWareHook_Rand_Bytes_t(char*const msg,unsigned char *buf, int num); +extern SW_EXPORT SureWareHook_Rand_Bytes_t SureWareHook_Rand_Bytes; + +/* +* SureWare RAND Seed function +* Adds some seed to the Hardware Random Number Generator +* return 1 if success +* SureWareHOOK_ERROR_FALLBACK if function not available in hardware +* SureWareHOOK_ERROR_FAILED if error while processing +* SureWareHOOK_ERROR_UNIT_FAILURE if hardware failure +* SUREWAREHOOK_ERROR_DATA_SIZE wrong size for buf +* +* in param buf : the seed to add into the HRNG +* in param num : the number of bytes into buf +*/ +typedef int SureWareHook_Rand_Seed_t(char*const msg,const void *buf, int num); +extern SW_EXPORT SureWareHook_Rand_Seed_t SureWareHook_Rand_Seed; + +/* +* SureWare Load Private Key function +* return 1 if success +* SureWareHOOK_ERROR_FAILED if error while processing +* No hardware is contact for this function. +* +* in param key_id :the name of the private protected key file without the extension + ".sws" +* out param hptr : a pointer to a buffer allocated by SureWare_Hook +* out param num: the effective key length in bytes +* out param keytype: 1 if RSA 2 if DSA +*/ +typedef int SureWareHook_Load_Privkey_t(char*const msg,const char *key_id,char **hptr,unsigned long *num,char *keytype); +extern SW_EXPORT SureWareHook_Load_Privkey_t SureWareHook_Load_Privkey; + +/* +* SureWare Info Public Key function +* return 1 if success +* SureWareHOOK_ERROR_FAILED if error while processing +* No hardware is contact for this function. +* +* in param key_id :the name of the private protected key file without the extension + ".swp" +* out param hptr : a pointer to a buffer allocated by SureWare_Hook +* out param num: the effective key length in bytes +* out param keytype: 1 if RSA 2 if DSA +*/ +typedef int SureWareHook_Info_Pubkey_t(char*const msg,const char *key_id,unsigned long *num, + char *keytype); +extern SW_EXPORT SureWareHook_Info_Pubkey_t SureWareHook_Info_Pubkey; + +/* +* SureWare Load Public Key function +* return 1 if success +* SureWareHOOK_ERROR_FAILED if error while processing +* No hardware is contact for this function. +* +* in param key_id :the name of the public protected key file without the extension + ".swp" +* in param num : the bytes size of n and e +* out param n: where to write modulus in bn format +* out param e: where to write exponent in bn format +*/ +typedef int SureWareHook_Load_Rsa_Pubkey_t(char*const msg,const char *key_id,unsigned long num, + unsigned long *n, unsigned long *e); +extern SW_EXPORT SureWareHook_Load_Rsa_Pubkey_t SureWareHook_Load_Rsa_Pubkey; + +/* +* SureWare Load DSA Public Key function +* return 1 if success +* SureWareHOOK_ERROR_FAILED if error while processing +* No hardware is contact for this function. +* +* in param key_id :the name of the public protected key file without the extension + ".swp" +* in param num : the bytes size of n and e +* out param pub: where to write pub key in bn format +* out param p: where to write prime in bn format +* out param q: where to write sunprime (length 20 bytes) in bn format +* out param g: where to write base in bn format +*/ +typedef int SureWareHook_Load_Dsa_Pubkey_t(char*const msg,const char *key_id,unsigned long num, + unsigned long *pub, unsigned long *p,unsigned long*q, + unsigned long *g); +extern SW_EXPORT SureWareHook_Load_Dsa_Pubkey_t SureWareHook_Load_Dsa_Pubkey; + +/* +* SureWare Free function +* Destroy the key into the hardware if destroy==1 +*/ +typedef void SureWareHook_Free_t(char *p,int destroy); +extern SW_EXPORT SureWareHook_Free_t SureWareHook_Free; + +#define SUREWARE_PKCS1_PAD 1 +#define SUREWARE_ISO9796_PAD 2 +#define SUREWARE_NO_PAD 0 +/* +* SureWare RSA Private Decryption +* return 1 if success +* SureWareHOOK_ERROR_FAILED if error while processing +* SureWareHOOK_ERROR_UNIT_FAILURE if hardware failure +* SUREWAREHOOK_ERROR_DATA_SIZE wrong size for buf +* +* in param flen : byte size of from and to +* in param from : encrypted data buffer, should be a not-null valid pointer +* out param tlen: byte size of decrypted data, if error, unexpected value +* out param to : decrypted data buffer, should be a not-null valid pointer +* in param prsa: a protected key pointer, should be a not-null valid pointer +* int padding: padding id as follow +* SUREWARE_PKCS1_PAD +* SUREWARE_NO_PAD +* +*/ +typedef int SureWareHook_Rsa_Priv_Dec_t(char*const msg,int flen,unsigned char *from, + int *tlen,unsigned char *to, + char *prsa,int padding); +extern SW_EXPORT SureWareHook_Rsa_Priv_Dec_t SureWareHook_Rsa_Priv_Dec; +/* +* SureWare RSA Signature +* return 1 if success +* SureWareHOOK_ERROR_FAILED if error while processing +* SureWareHOOK_ERROR_UNIT_FAILURE if hardware failure +* SUREWAREHOOK_ERROR_DATA_SIZE wrong size for buf +* +* in param flen : byte size of from and to +* in param from : encrypted data buffer, should be a not-null valid pointer +* out param tlen: byte size of decrypted data, if error, unexpected value +* out param to : decrypted data buffer, should be a not-null valid pointer +* in param prsa: a protected key pointer, should be a not-null valid pointer +* int padding: padding id as follow +* SUREWARE_PKCS1_PAD +* SUREWARE_ISO9796_PAD +* +*/ +typedef int SureWareHook_Rsa_Sign_t(char*const msg,int flen,unsigned char *from, + int *tlen,unsigned char *to, + char *prsa,int padding); +extern SW_EXPORT SureWareHook_Rsa_Sign_t SureWareHook_Rsa_Sign; +/* +* SureWare DSA Signature +* return 1 if success +* SureWareHOOK_ERROR_FAILED if error while processing +* SureWareHOOK_ERROR_UNIT_FAILURE if hardware failure +* SUREWAREHOOK_ERROR_DATA_SIZE wrong size for buf +* +* in param flen : byte size of from and to +* in param from : encrypted data buffer, should be a not-null valid pointer +* out param to : decrypted data buffer, should be a 40bytes valid pointer +* in param pdsa: a protected key pointer, should be a not-null valid pointer +* +*/ +typedef int SureWareHook_Dsa_Sign_t(char*const msg,int flen,const unsigned char *from, + unsigned long *r,unsigned long *s,char *pdsa); +extern SW_EXPORT SureWareHook_Dsa_Sign_t SureWareHook_Dsa_Sign; + + +/* +* SureWare Mod Exp +* return 1 if success +* SureWareHOOK_ERROR_FAILED if error while processing +* SureWareHOOK_ERROR_UNIT_FAILURE if hardware failure +* SUREWAREHOOK_ERROR_DATA_SIZE wrong size for buf +* +* mod and res are mlen bytes long. +* exp is elen bytes long +* data is dlen bytes long +* mlen,elen and dlen are all multiple of sizeof(unsigned long) +*/ +typedef int SureWareHook_Mod_Exp_t(char*const msg,int mlen,const unsigned long *mod, + int elen,const unsigned long *exponent, + int dlen,unsigned long *data, + unsigned long *res); +extern SW_EXPORT SureWareHook_Mod_Exp_t SureWareHook_Mod_Exp; + diff --git a/node-v0.8.14/deps/openssl/openssl/include/openssl/aes.h b/node-v0.8.14/deps/openssl/openssl/include/openssl/aes.h new file mode 100644 index 0000000..f646d41 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/include/openssl/aes.h @@ -0,0 +1 @@ +#include "../../crypto/aes/aes.h" diff --git a/node-v0.8.14/deps/openssl/openssl/include/openssl/asn1.h b/node-v0.8.14/deps/openssl/openssl/include/openssl/asn1.h new file mode 100644 index 0000000..5432ed8 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/include/openssl/asn1.h @@ -0,0 +1 @@ +#include "../../crypto/asn1/asn1.h" diff --git a/node-v0.8.14/deps/openssl/openssl/include/openssl/asn1_mac.h b/node-v0.8.14/deps/openssl/openssl/include/openssl/asn1_mac.h new file mode 100644 index 0000000..214787c --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/include/openssl/asn1_mac.h @@ -0,0 +1 @@ +#include "../../crypto/asn1/asn1_mac.h" diff --git a/node-v0.8.14/deps/openssl/openssl/include/openssl/asn1t.h b/node-v0.8.14/deps/openssl/openssl/include/openssl/asn1t.h new file mode 100644 index 0000000..4de87a9 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/include/openssl/asn1t.h @@ -0,0 +1 @@ +#include "../../crypto/asn1/asn1t.h" diff --git a/node-v0.8.14/deps/openssl/openssl/include/openssl/bio.h b/node-v0.8.14/deps/openssl/openssl/include/openssl/bio.h new file mode 100644 index 0000000..34f8a2d --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/include/openssl/bio.h @@ -0,0 +1 @@ +#include "../../crypto/bio/bio.h" diff --git a/node-v0.8.14/deps/openssl/openssl/include/openssl/blowfish.h b/node-v0.8.14/deps/openssl/openssl/include/openssl/blowfish.h new file mode 100644 index 0000000..8d515fe --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/include/openssl/blowfish.h @@ -0,0 +1 @@ +#include "../../crypto/bf/blowfish.h" diff --git a/node-v0.8.14/deps/openssl/openssl/include/openssl/bn.h b/node-v0.8.14/deps/openssl/openssl/include/openssl/bn.h new file mode 100644 index 0000000..f47d65a --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/include/openssl/bn.h @@ -0,0 +1 @@ +#include "../../crypto/bn/bn.h" diff --git a/node-v0.8.14/deps/openssl/openssl/include/openssl/buffer.h b/node-v0.8.14/deps/openssl/openssl/include/openssl/buffer.h new file mode 100644 index 0000000..1d2c2a2 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/include/openssl/buffer.h @@ -0,0 +1 @@ +#include "../../crypto/buffer/buffer.h" diff --git a/node-v0.8.14/deps/openssl/openssl/include/openssl/camellia.h b/node-v0.8.14/deps/openssl/openssl/include/openssl/camellia.h new file mode 100644 index 0000000..5a0a141 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/include/openssl/camellia.h @@ -0,0 +1 @@ +#include "../../crypto/camellia/camellia.h" diff --git a/node-v0.8.14/deps/openssl/openssl/include/openssl/cast.h b/node-v0.8.14/deps/openssl/openssl/include/openssl/cast.h new file mode 100644 index 0000000..12cf92c --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/include/openssl/cast.h @@ -0,0 +1 @@ +#include "../../crypto/cast/cast.h" diff --git a/node-v0.8.14/deps/openssl/openssl/include/openssl/cms.h b/node-v0.8.14/deps/openssl/openssl/include/openssl/cms.h new file mode 100644 index 0000000..8687c7f --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/include/openssl/cms.h @@ -0,0 +1 @@ +#include "../../crypto/cms/cms.h" diff --git a/node-v0.8.14/deps/openssl/openssl/include/openssl/comp.h b/node-v0.8.14/deps/openssl/openssl/include/openssl/comp.h new file mode 100644 index 0000000..d14e36c --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/include/openssl/comp.h @@ -0,0 +1 @@ +#include "../../crypto/comp/comp.h" diff --git a/node-v0.8.14/deps/openssl/openssl/include/openssl/conf.h b/node-v0.8.14/deps/openssl/openssl/include/openssl/conf.h new file mode 100644 index 0000000..3882c82 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/include/openssl/conf.h @@ -0,0 +1 @@ +#include "../../crypto/conf/conf.h" diff --git a/node-v0.8.14/deps/openssl/openssl/include/openssl/conf_api.h b/node-v0.8.14/deps/openssl/openssl/include/openssl/conf_api.h new file mode 100644 index 0000000..0393357 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/include/openssl/conf_api.h @@ -0,0 +1 @@ +#include "../../crypto/conf/conf_api.h" diff --git a/node-v0.8.14/deps/openssl/openssl/include/openssl/crypto.h b/node-v0.8.14/deps/openssl/openssl/include/openssl/crypto.h new file mode 100644 index 0000000..7e3d91e --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/include/openssl/crypto.h @@ -0,0 +1 @@ +#include "../../crypto/crypto.h" diff --git a/node-v0.8.14/deps/openssl/openssl/include/openssl/des.h b/node-v0.8.14/deps/openssl/openssl/include/openssl/des.h new file mode 100644 index 0000000..1d6631e --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/include/openssl/des.h @@ -0,0 +1 @@ +#include "../../crypto/des/des.h" diff --git a/node-v0.8.14/deps/openssl/openssl/include/openssl/des_old.h b/node-v0.8.14/deps/openssl/openssl/include/openssl/des_old.h new file mode 100644 index 0000000..e582873 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/include/openssl/des_old.h @@ -0,0 +1 @@ +#include "../../crypto/des/des_old.h" diff --git a/node-v0.8.14/deps/openssl/openssl/include/openssl/dh.h b/node-v0.8.14/deps/openssl/openssl/include/openssl/dh.h new file mode 100644 index 0000000..f70a767 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/include/openssl/dh.h @@ -0,0 +1 @@ +#include "../../crypto/dh/dh.h" diff --git a/node-v0.8.14/deps/openssl/openssl/include/openssl/dsa.h b/node-v0.8.14/deps/openssl/openssl/include/openssl/dsa.h new file mode 100644 index 0000000..0365acf --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/include/openssl/dsa.h @@ -0,0 +1 @@ +#include "../../crypto/dsa/dsa.h" diff --git a/node-v0.8.14/deps/openssl/openssl/include/openssl/dso.h b/node-v0.8.14/deps/openssl/openssl/include/openssl/dso.h new file mode 100644 index 0000000..f3c8de2 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/include/openssl/dso.h @@ -0,0 +1 @@ +#include "../../crypto/dso/dso.h" diff --git a/node-v0.8.14/deps/openssl/openssl/include/openssl/dtls1.h b/node-v0.8.14/deps/openssl/openssl/include/openssl/dtls1.h new file mode 100644 index 0000000..ac8ab57 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/include/openssl/dtls1.h @@ -0,0 +1 @@ +#include "../../ssl/dtls1.h" diff --git a/node-v0.8.14/deps/openssl/openssl/include/openssl/e_os2.h b/node-v0.8.14/deps/openssl/openssl/include/openssl/e_os2.h new file mode 100644 index 0000000..ab3f1ee --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/include/openssl/e_os2.h @@ -0,0 +1 @@ +#include "../../e_os2.h" diff --git a/node-v0.8.14/deps/openssl/openssl/include/openssl/ebcdic.h b/node-v0.8.14/deps/openssl/openssl/include/openssl/ebcdic.h new file mode 100644 index 0000000..6dedc70 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/include/openssl/ebcdic.h @@ -0,0 +1 @@ +#include "../../crypto/ebcdic.h" diff --git a/node-v0.8.14/deps/openssl/openssl/include/openssl/ec.h b/node-v0.8.14/deps/openssl/openssl/include/openssl/ec.h new file mode 100644 index 0000000..7d20614 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/include/openssl/ec.h @@ -0,0 +1 @@ +#include "../../crypto/ec/ec.h" diff --git a/node-v0.8.14/deps/openssl/openssl/include/openssl/ecdh.h b/node-v0.8.14/deps/openssl/openssl/include/openssl/ecdh.h new file mode 100644 index 0000000..ad6e3dc --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/include/openssl/ecdh.h @@ -0,0 +1 @@ +#include "../../crypto/ecdh/ecdh.h" diff --git a/node-v0.8.14/deps/openssl/openssl/include/openssl/ecdsa.h b/node-v0.8.14/deps/openssl/openssl/include/openssl/ecdsa.h new file mode 100644 index 0000000..da45123 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/include/openssl/ecdsa.h @@ -0,0 +1 @@ +#include "../../crypto/ecdsa/ecdsa.h" diff --git a/node-v0.8.14/deps/openssl/openssl/include/openssl/engine.h b/node-v0.8.14/deps/openssl/openssl/include/openssl/engine.h new file mode 100644 index 0000000..2dceaac --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/include/openssl/engine.h @@ -0,0 +1 @@ +#include "../../crypto/engine/engine.h" diff --git a/node-v0.8.14/deps/openssl/openssl/include/openssl/err.h b/node-v0.8.14/deps/openssl/openssl/include/openssl/err.h new file mode 100644 index 0000000..caf89a9 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/include/openssl/err.h @@ -0,0 +1 @@ +#include "../../crypto/err/err.h" diff --git a/node-v0.8.14/deps/openssl/openssl/include/openssl/evp.h b/node-v0.8.14/deps/openssl/openssl/include/openssl/evp.h new file mode 100644 index 0000000..dd7bcda --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/include/openssl/evp.h @@ -0,0 +1 @@ +#include "../../crypto/evp/evp.h" diff --git a/node-v0.8.14/deps/openssl/openssl/include/openssl/hmac.h b/node-v0.8.14/deps/openssl/openssl/include/openssl/hmac.h new file mode 100644 index 0000000..202128b --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/include/openssl/hmac.h @@ -0,0 +1 @@ +#include "../../crypto/hmac/hmac.h" diff --git a/node-v0.8.14/deps/openssl/openssl/include/openssl/idea.h b/node-v0.8.14/deps/openssl/openssl/include/openssl/idea.h new file mode 100644 index 0000000..bdf697d --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/include/openssl/idea.h @@ -0,0 +1 @@ +#include "../../crypto/idea/idea.h" diff --git a/node-v0.8.14/deps/openssl/openssl/include/openssl/krb5_asn.h b/node-v0.8.14/deps/openssl/openssl/include/openssl/krb5_asn.h new file mode 100644 index 0000000..0d3feea --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/include/openssl/krb5_asn.h @@ -0,0 +1 @@ +#include "../../crypto/krb5/krb5_asn.h" diff --git a/node-v0.8.14/deps/openssl/openssl/include/openssl/kssl.h b/node-v0.8.14/deps/openssl/openssl/include/openssl/kssl.h new file mode 100644 index 0000000..719634a --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/include/openssl/kssl.h @@ -0,0 +1 @@ +#include "../../ssl/kssl.h" diff --git a/node-v0.8.14/deps/openssl/openssl/include/openssl/lhash.h b/node-v0.8.14/deps/openssl/openssl/include/openssl/lhash.h new file mode 100644 index 0000000..2d3db87 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/include/openssl/lhash.h @@ -0,0 +1 @@ +#include "../../crypto/lhash/lhash.h" diff --git a/node-v0.8.14/deps/openssl/openssl/include/openssl/md2.h b/node-v0.8.14/deps/openssl/openssl/include/openssl/md2.h new file mode 100644 index 0000000..4c3398c --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/include/openssl/md2.h @@ -0,0 +1 @@ +#include "../../crypto/md2/md2.h" diff --git a/node-v0.8.14/deps/openssl/openssl/include/openssl/md4.h b/node-v0.8.14/deps/openssl/openssl/include/openssl/md4.h new file mode 100644 index 0000000..611806e --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/include/openssl/md4.h @@ -0,0 +1 @@ +#include "../../crypto/md4/md4.h" diff --git a/node-v0.8.14/deps/openssl/openssl/include/openssl/md5.h b/node-v0.8.14/deps/openssl/openssl/include/openssl/md5.h new file mode 100644 index 0000000..aa8cd0b --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/include/openssl/md5.h @@ -0,0 +1 @@ +#include "../../crypto/md5/md5.h" diff --git a/node-v0.8.14/deps/openssl/openssl/include/openssl/mdc2.h b/node-v0.8.14/deps/openssl/openssl/include/openssl/mdc2.h new file mode 100644 index 0000000..ac284a1 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/include/openssl/mdc2.h @@ -0,0 +1 @@ +#include "../../crypto/mdc2/mdc2.h" diff --git a/node-v0.8.14/deps/openssl/openssl/include/openssl/modes.h b/node-v0.8.14/deps/openssl/openssl/include/openssl/modes.h new file mode 100644 index 0000000..f57fcfe --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/include/openssl/modes.h @@ -0,0 +1 @@ +#include "../../crypto/modes/modes.h" diff --git a/node-v0.8.14/deps/openssl/openssl/include/openssl/obj_mac.h b/node-v0.8.14/deps/openssl/openssl/include/openssl/obj_mac.h new file mode 100644 index 0000000..3890fa9 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/include/openssl/obj_mac.h @@ -0,0 +1 @@ +#include "../../crypto/objects/obj_mac.h" diff --git a/node-v0.8.14/deps/openssl/openssl/include/openssl/objects.h b/node-v0.8.14/deps/openssl/openssl/include/openssl/objects.h new file mode 100644 index 0000000..5365a04 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/include/openssl/objects.h @@ -0,0 +1 @@ +#include "../../crypto/objects/objects.h" diff --git a/node-v0.8.14/deps/openssl/openssl/include/openssl/ocsp.h b/node-v0.8.14/deps/openssl/openssl/include/openssl/ocsp.h new file mode 100644 index 0000000..50e2885 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/include/openssl/ocsp.h @@ -0,0 +1 @@ +#include "../../crypto/ocsp/ocsp.h" diff --git a/node-v0.8.14/deps/openssl/openssl/include/openssl/opensslv.h b/node-v0.8.14/deps/openssl/openssl/include/openssl/opensslv.h new file mode 100644 index 0000000..c39a0c3 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/include/openssl/opensslv.h @@ -0,0 +1 @@ +#include "../../crypto/opensslv.h" diff --git a/node-v0.8.14/deps/openssl/openssl/include/openssl/ossl_typ.h b/node-v0.8.14/deps/openssl/openssl/include/openssl/ossl_typ.h new file mode 100644 index 0000000..ddd7e58 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/include/openssl/ossl_typ.h @@ -0,0 +1 @@ +#include "../../crypto/ossl_typ.h" diff --git a/node-v0.8.14/deps/openssl/openssl/include/openssl/pem.h b/node-v0.8.14/deps/openssl/openssl/include/openssl/pem.h new file mode 100644 index 0000000..5bcc5c5 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/include/openssl/pem.h @@ -0,0 +1 @@ +#include "../../crypto/pem/pem.h" diff --git a/node-v0.8.14/deps/openssl/openssl/include/openssl/pem2.h b/node-v0.8.14/deps/openssl/openssl/include/openssl/pem2.h new file mode 100644 index 0000000..bcd3acf --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/include/openssl/pem2.h @@ -0,0 +1 @@ +#include "../../crypto/pem/pem2.h" diff --git a/node-v0.8.14/deps/openssl/openssl/include/openssl/pkcs12.h b/node-v0.8.14/deps/openssl/openssl/include/openssl/pkcs12.h new file mode 100644 index 0000000..0b5fbbf --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/include/openssl/pkcs12.h @@ -0,0 +1 @@ +#include "../../crypto/pkcs12/pkcs12.h" diff --git a/node-v0.8.14/deps/openssl/openssl/include/openssl/pkcs7.h b/node-v0.8.14/deps/openssl/openssl/include/openssl/pkcs7.h new file mode 100644 index 0000000..2e19d7c --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/include/openssl/pkcs7.h @@ -0,0 +1 @@ +#include "../../crypto/pkcs7/pkcs7.h" diff --git a/node-v0.8.14/deps/openssl/openssl/include/openssl/pqueue.h b/node-v0.8.14/deps/openssl/openssl/include/openssl/pqueue.h new file mode 100644 index 0000000..9681ff5 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/include/openssl/pqueue.h @@ -0,0 +1 @@ +#include "../../crypto/pqueue/pqueue.h" diff --git a/node-v0.8.14/deps/openssl/openssl/include/openssl/rand.h b/node-v0.8.14/deps/openssl/openssl/include/openssl/rand.h new file mode 100644 index 0000000..9d1521b --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/include/openssl/rand.h @@ -0,0 +1 @@ +#include "../../crypto/rand/rand.h" diff --git a/node-v0.8.14/deps/openssl/openssl/include/openssl/rc2.h b/node-v0.8.14/deps/openssl/openssl/include/openssl/rc2.h new file mode 100644 index 0000000..f2f2bd1 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/include/openssl/rc2.h @@ -0,0 +1 @@ +#include "../../crypto/rc2/rc2.h" diff --git a/node-v0.8.14/deps/openssl/openssl/include/openssl/rc4.h b/node-v0.8.14/deps/openssl/openssl/include/openssl/rc4.h new file mode 100644 index 0000000..306de2f --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/include/openssl/rc4.h @@ -0,0 +1 @@ +#include "../../crypto/rc4/rc4.h" diff --git a/node-v0.8.14/deps/openssl/openssl/include/openssl/ripemd.h b/node-v0.8.14/deps/openssl/openssl/include/openssl/ripemd.h new file mode 100644 index 0000000..11351fc --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/include/openssl/ripemd.h @@ -0,0 +1 @@ +#include "../../crypto/ripemd/ripemd.h" diff --git a/node-v0.8.14/deps/openssl/openssl/include/openssl/rsa.h b/node-v0.8.14/deps/openssl/openssl/include/openssl/rsa.h new file mode 100644 index 0000000..975e5d3 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/include/openssl/rsa.h @@ -0,0 +1 @@ +#include "../../crypto/rsa/rsa.h" diff --git a/node-v0.8.14/deps/openssl/openssl/include/openssl/safestack.h b/node-v0.8.14/deps/openssl/openssl/include/openssl/safestack.h new file mode 100644 index 0000000..8a282b8 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/include/openssl/safestack.h @@ -0,0 +1 @@ +#include "../../crypto/stack/safestack.h" diff --git a/node-v0.8.14/deps/openssl/openssl/include/openssl/seed.h b/node-v0.8.14/deps/openssl/openssl/include/openssl/seed.h new file mode 100644 index 0000000..bbbf596 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/include/openssl/seed.h @@ -0,0 +1 @@ +#include "../../crypto/seed/seed.h" diff --git a/node-v0.8.14/deps/openssl/openssl/include/openssl/sha.h b/node-v0.8.14/deps/openssl/openssl/include/openssl/sha.h new file mode 100644 index 0000000..ab9d94c --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/include/openssl/sha.h @@ -0,0 +1 @@ +#include "../../crypto/sha/sha.h" diff --git a/node-v0.8.14/deps/openssl/openssl/include/openssl/ssl.h b/node-v0.8.14/deps/openssl/openssl/include/openssl/ssl.h new file mode 100644 index 0000000..0b0589c --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/include/openssl/ssl.h @@ -0,0 +1 @@ +#include "../../ssl/ssl.h" diff --git a/node-v0.8.14/deps/openssl/openssl/include/openssl/ssl2.h b/node-v0.8.14/deps/openssl/openssl/include/openssl/ssl2.h new file mode 100644 index 0000000..11b2205 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/include/openssl/ssl2.h @@ -0,0 +1 @@ +#include "../../ssl/ssl2.h" diff --git a/node-v0.8.14/deps/openssl/openssl/include/openssl/ssl23.h b/node-v0.8.14/deps/openssl/openssl/include/openssl/ssl23.h new file mode 100644 index 0000000..fe4dae6 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/include/openssl/ssl23.h @@ -0,0 +1 @@ +#include "../../ssl/ssl23.h" diff --git a/node-v0.8.14/deps/openssl/openssl/include/openssl/ssl3.h b/node-v0.8.14/deps/openssl/openssl/include/openssl/ssl3.h new file mode 100644 index 0000000..0fb66a6 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/include/openssl/ssl3.h @@ -0,0 +1 @@ +#include "../../ssl/ssl3.h" diff --git a/node-v0.8.14/deps/openssl/openssl/include/openssl/stack.h b/node-v0.8.14/deps/openssl/openssl/include/openssl/stack.h new file mode 100644 index 0000000..295968c --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/include/openssl/stack.h @@ -0,0 +1 @@ +#include "../../crypto/stack/stack.h" diff --git a/node-v0.8.14/deps/openssl/openssl/include/openssl/store.h b/node-v0.8.14/deps/openssl/openssl/include/openssl/store.h new file mode 100644 index 0000000..84dc39f --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/include/openssl/store.h @@ -0,0 +1 @@ +#include "../../crypto/store/store.h" diff --git a/node-v0.8.14/deps/openssl/openssl/include/openssl/symhacks.h b/node-v0.8.14/deps/openssl/openssl/include/openssl/symhacks.h new file mode 100644 index 0000000..f946f4f --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/include/openssl/symhacks.h @@ -0,0 +1 @@ +#include "../../crypto/symhacks.h" diff --git a/node-v0.8.14/deps/openssl/openssl/include/openssl/tls1.h b/node-v0.8.14/deps/openssl/openssl/include/openssl/tls1.h new file mode 100644 index 0000000..c43a70f --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/include/openssl/tls1.h @@ -0,0 +1 @@ +#include "../../ssl/tls1.h" diff --git a/node-v0.8.14/deps/openssl/openssl/include/openssl/ts.h b/node-v0.8.14/deps/openssl/openssl/include/openssl/ts.h new file mode 100644 index 0000000..fe8a2cb --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/include/openssl/ts.h @@ -0,0 +1 @@ +#include "../../crypto/ts/ts.h" diff --git a/node-v0.8.14/deps/openssl/openssl/include/openssl/txt_db.h b/node-v0.8.14/deps/openssl/openssl/include/openssl/txt_db.h new file mode 100644 index 0000000..167621b --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/include/openssl/txt_db.h @@ -0,0 +1 @@ +#include "../../crypto/txt_db/txt_db.h" diff --git a/node-v0.8.14/deps/openssl/openssl/include/openssl/ui.h b/node-v0.8.14/deps/openssl/openssl/include/openssl/ui.h new file mode 100644 index 0000000..43dd3ae --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/include/openssl/ui.h @@ -0,0 +1 @@ +#include "../../crypto/ui/ui.h" diff --git a/node-v0.8.14/deps/openssl/openssl/include/openssl/ui_compat.h b/node-v0.8.14/deps/openssl/openssl/include/openssl/ui_compat.h new file mode 100644 index 0000000..c83f160 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/include/openssl/ui_compat.h @@ -0,0 +1 @@ +#include "../../crypto/ui/ui_compat.h" diff --git a/node-v0.8.14/deps/openssl/openssl/include/openssl/whrlpool.h b/node-v0.8.14/deps/openssl/openssl/include/openssl/whrlpool.h new file mode 100644 index 0000000..e2424fa --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/include/openssl/whrlpool.h @@ -0,0 +1 @@ +#include "../../crypto/whrlpool/whrlpool.h" diff --git a/node-v0.8.14/deps/openssl/openssl/include/openssl/x509.h b/node-v0.8.14/deps/openssl/openssl/include/openssl/x509.h new file mode 100644 index 0000000..a4651a2 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/include/openssl/x509.h @@ -0,0 +1 @@ +#include "../../crypto/x509/x509.h" diff --git a/node-v0.8.14/deps/openssl/openssl/include/openssl/x509_vfy.h b/node-v0.8.14/deps/openssl/openssl/include/openssl/x509_vfy.h new file mode 100644 index 0000000..b897aa0 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/include/openssl/x509_vfy.h @@ -0,0 +1 @@ +#include "../../crypto/x509/x509_vfy.h" diff --git a/node-v0.8.14/deps/openssl/openssl/include/openssl/x509v3.h b/node-v0.8.14/deps/openssl/openssl/include/openssl/x509v3.h new file mode 100644 index 0000000..363795e --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/include/openssl/x509v3.h @@ -0,0 +1 @@ +#include "../../crypto/x509v3/x509v3.h" diff --git a/node-v0.8.14/deps/openssl/openssl/install.com b/node-v0.8.14/deps/openssl/openssl/install.com new file mode 100644 index 0000000..6a0ea2d --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/install.com @@ -0,0 +1,136 @@ +$! INSTALL.COM -- Installs the files in a given directory tree +$! +$! Author: Richard Levitte +$! Time of creation: 22-MAY-1998 10:13 +$! +$! P1 root of the directory tree +$! P2 "64" for 64-bit pointers. +$! +$! +$! Announce/identify. +$! +$ proc = f$environment( "procedure") +$ write sys$output "@@@ "+ - + f$parse( proc, , , "name")+ f$parse( proc, , , "type") +$! +$ def_orig = f$environment( "default") +$ on error then goto tidy +$ on control_c then goto tidy +$! +$ if (p1 .eqs. "") +$ then +$ write sys$output "First argument missing." +$ write sys$output - + "It should be the directory where you want things installed." +$ exit +$ endif +$! +$ if (f$getsyi("cpu") .lt. 128) +$ then +$ arch = "VAX" +$ else +$ arch = f$edit( f$getsyi( "arch_name"), "upcase") +$ if (arch .eqs. "") then arch = "UNK" +$ endif +$! +$ archd = arch +$! +$ if (p2 .nes. "") +$ then +$ if (p2 .eqs. "64") +$ then +$ archd = arch+ "_64" +$ else +$ if (p2 .nes. "32") +$ then +$ write sys$output "Second argument invalid." +$ write sys$output "It should be "32", "64", or nothing." +$ exit +$ endif +$ endif +$ endif +$! +$ root = f$parse( p1, "[]A.;0", , , "syntax_only, no_conceal") - "A.;0" +$ root_dev = f$parse( root, , , "device", "syntax_only") +$ root_dir = f$parse( root, , , "directory", "syntax_only") - + - ".][000000" - "[000000." - "][" - "[" - "]" +$ root = root_dev + "[" + root_dir +$! +$ define /nolog wrk_sslroot 'root'.] /trans=conc +$ define /nolog wrk_sslcerts wrk_sslroot:[certs] +$ define /nolog wrk_sslinclude wrk_sslroot:[include] +$ define /nolog wrk_ssllib wrk_sslroot:[lib] +$ define /nolog wrk_sslprivate wrk_sslroot:[private] +$ define /nolog wrk_sslxexe wrk_sslroot:['archd'_exe] +$ define /nolog wrk_sslxlib wrk_sslroot:['arch'_lib] +$! +$! Exhibit the destination directory. +$! +$ write sys$output " Installing to (WRK_SSLROOT) =" +$ write sys$output " ''f$trnlnm( "wrk_sslroot")'" +$ write sys$output "" +$! +$ if f$parse("wrk_sslroot:[000000]") .eqs. "" then - + create /directory /log wrk_sslroot:[000000] +$ if f$parse("wrk_sslxexe:") .eqs. "" then - + create /directory /log wrk_sslxexe: +$ if f$parse("wrk_sslxlib:") .eqs. "" then - + create /directory /log wrk_sslxlib: +$ if f$parse("wrk_ssllib:") .eqs. "" then - + create /directory /log wrk_ssllib: +$ if f$parse("wrk_sslinclude:") .eqs. "" then - + create /directory /log wrk_sslinclude: +$ if f$parse("wrk_sslcerts:") .eqs. "" then - + create /directory /log wrk_sslcerts: +$ if f$parse("wrk_sslprivate:") .eqs. "" then - + create /directory /log wrk_sslprivate: +$ if f$parse("wrk_sslroot:[VMS]") .EQS. "" THEN - + create /directory /log wrk_sslroot:[VMS] +$! +$ sdirs := CRYPTO, SSL, APPS, VMS !!!, RSAREF, TEST, TOOLS +$ exheader := e_os2.h +$! +$ copy /protection = w:re 'exheader' wrk_sslinclude: /log +$! +$ i = 0 +$ loop_sdirs: +$ d = f$edit( f$element(i, ",", sdirs), "trim") +$ i = i + 1 +$ if d .eqs. "," then goto loop_sdirs_end +$ write sys$output "Installing ", d, " files." +$ set default [.'d'] +$ @ install-'d'.com 'root'] 'p2' +$ set default 'def_orig' +$ goto loop_sdirs +$ loop_sdirs_end: +$! +$ write sys$output "" +$ write sys$output " Installation done!" +$ write sys$output "" +$ if (f$search( root+ "...]*.*;-1") .nes. "") +$ then +$ write sys$output " You might want to purge ", root, "...]" +$ write sys$output "" +$ endif +$! +$ tidy: +$! +$ set default 'def_orig' +$! +$ call deass wrk_sslroot +$ call deass wrk_sslcerts +$ call deass wrk_sslinclude +$ call deass wrk_ssllib +$ call deass wrk_sslprivate +$ call deass wrk_sslxexe +$ call deass wrk_sslxlib +$! +$ exit +$! +$ deass: subroutine +$ if (f$trnlnm( p1, "LNM$PROCESS") .nes. "") +$ then +$ deassign /process 'p1' +$ endif +$ endsubroutine +$! diff --git a/node-v0.8.14/deps/openssl/openssl/makevms.com b/node-v0.8.14/deps/openssl/openssl/makevms.com new file mode 100755 index 0000000..eb22f20 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/makevms.com @@ -0,0 +1,1533 @@ +$! +$! MAKEVMS.COM +$! Original Author: UNKNOWN +$! Rewritten By: Robert Byer +$! Vice-President +$! A-Com Computing, Inc. +$! byer@mail.all-net.net +$! +$! Changes by Richard Levitte +$! Zoltan Arpadffy +$! +$! This procedure creates the SSL libraries of "[.xxx.EXE.CRYPTO]LIBCRYPTO.OLB" +$! "[.xxx.EXE.SSL]LIBSSL.OLB" +$! The "xxx" denotes the machine architecture of ALPHA, IA64 or VAX. +$! +$! This procedures accepts two command line options listed below. +$! +$! P1 specifies one of the following build options: +$! +$! ALL Just build "everything". +$! CONFIG Just build the "[.CRYPTO._xxx]OPENSSLCONF.H" file. +$! BUILDINF Just build the "[.CRYPTO._xxx]BUILDINF.H" file. +$! SOFTLINKS Just fix the Unix soft links. +$! BUILDALL Same as ALL, except CONFIG, BUILDINF and SOFTILNKS aren't done. +$! CRYPTO Just build the "[.xxx.EXE.CRYPTO]LIBCRYPTO.OLB" library. +$! CRYPTO/x Just build the x part of the +$! "[.xxx.EXE.CRYPTO]LIBCRYPTO.OLB" library. +$! SSL Just build the "[.xxx.EXE.SSL]LIBSSL.OLB" library. +$! SSL_TASK Just build the "[.xxx.EXE.SSL]SSL_TASK.EXE" program. +$! TEST Just build the "[.xxx.EXE.TEST]" test programs for OpenSSL. +$! APPS Just build the "[.xxx.EXE.APPS]" application programs for OpenSSL. +$! ENGINES Just build the "[.xxx.EXE.ENGINES]" application programs for OpenSSL. +$! +$! P2, if defined, specifies the C pointer size. Ignored on VAX. +$! ("64=ARGV" gives more efficient code with HP C V7.3 or newer.) +$! Supported values are: +$! +$! "" Compile with default (/NOPOINTER_SIZE). +$! 32 Compile with /POINTER_SIZE=32 (SHORT). +$! 64 Compile with /POINTER_SIZE=64[=ARGV] (LONG[=ARGV]). +$! (Automatically select ARGV if compiler supports it.) +$! 64= Compile with /POINTER_SIZE=64 (LONG). +$! 64=ARGV Compile with /POINTER_SIZE=64=ARGV (LONG=ARGV). +$! +$! P3 specifies DEBUG or NODEBUG, to compile with or without debugging +$! information. +$! +$! P4 specifies which compiler to try to compile under. +$! +$! VAXC For VAX C. +$! DECC For DEC C. +$! GNUC For GNU C. +$! LINK To only link the programs from existing object files. +$! (not yet implemented) +$! +$! If you don't specify a compiler, it will try to determine which +$! "C" compiler to use. +$! +$! P5, if defined, sets a TCP/IP library to use, through one of the following +$! keywords: +$! +$! UCX for UCX or UCX emulation +$! TCPIP for TCP/IP Services or TCP/IP Services emulation +$! (this is prefered over UCX) +$! SOCKETSHR for SOCKETSHR+NETLIB +$! NONE to avoid specifying which TCP/IP implementation to +$! use at build time (this works with DEC C). This is +$! the default. +$! +$! P6, if defined, sets a compiler thread NOT needed on OpenVMS 7.1 (and up). +$! +$! P7, if defined, specifies a directory where ZLIB files (zlib.h, +$! libz.olb) may be found. Optionally, a non-default object library +$! name may be included ("dev:[dir]libz_64.olb", for example). +$! +$! +$! Announce/identify. +$! +$ proc = f$environment( "procedure") +$ write sys$output "@@@ "+ - + f$parse( proc, , , "name")+ f$parse( proc, , , "type") +$! +$ DEF_ORIG = F$ENVIRONMENT( "DEFAULT") +$ ON ERROR THEN GOTO TIDY +$ ON CONTROL_C THEN GOTO TIDY +$! +$! Check if we're in a batch job, and make sure we get to +$! the directory this script is in +$! +$ IF F$MODE() .EQS. "BATCH" +$ THEN +$ COMNAME=F$ENVIRONMENT("PROCEDURE") +$ COMPATH=F$PARSE("A.;",COMNAME) - "A.;" +$ SET DEF 'COMPATH' +$ ENDIF +$! +$! Check What Architecture We Are Using. +$! +$ IF (F$GETSYI("CPU").LT.128) +$ THEN +$! +$! The Architecture Is VAX. +$! +$ ARCH = "VAX" +$! +$! Else... +$! +$ ELSE +$! +$! The Architecture Is Alpha, IA64 or whatever comes in the future. +$! +$ ARCH = F$EDIT( F$GETSYI( "ARCH_NAME"), "UPCASE") +$ IF (ARCH .EQS. "") THEN ARCH = "UNK" +$! +$! End The Architecture Check. +$! +$ ENDIF +$! +$ ARCHD = ARCH +$ LIB32 = "32" +$ POINTER_SIZE = "" +$! +$! Get VMS version. +$! +$ VMS_VERSION = f$edit( f$getsyi( "VERSION"), "TRIM") +$! +$! Check To Make Sure We Have Valid Command Line Parameters. +$! +$ GOSUB CHECK_OPTIONS +$! +$! Check To See What We Are To Do. +$! +$ IF (BUILDCOMMAND.EQS."ALL") +$ THEN +$! +$! Start with building the OpenSSL configuration file. +$! +$ GOSUB CONFIG +$! +$! Create The "BUILDINF.H" Include File. +$! +$ GOSUB BUILDINF +$! +$! Fix The Unix Softlinks. +$! +$ GOSUB SOFTLINKS +$! +$ ENDIF +$! +$ IF (BUILDCOMMAND.EQS."ALL".OR.BUILDCOMMAND.EQS."BUILDALL") +$ THEN +$! +$! Build The [.xxx.EXE.CRYPTO]LIBCRYPTO.OLB Library. +$! +$ GOSUB CRYPTO +$! +$! Build The [.xxx.EXE.SSL]LIBSSL.OLB Library. +$! +$ GOSUB SSL +$! +$! Build The [.xxx.EXE.SSL]SSL_TASK.EXE DECNet SSL Engine. +$! +$ GOSUB SSL_TASK +$! +$! Build The [.xxx.EXE.TEST] OpenSSL Test Utilities. +$! +$ GOSUB TEST +$! +$! Build The [.xxx.EXE.APPS] OpenSSL Application Utilities. +$! +$ GOSUB APPS +$! +$! Build The [.xxx.EXE.ENGINES] OpenSSL Shareable Engines. +$! +$ GOSUB ENGINES +$! +$! Else... +$! +$ ELSE +$! +$! Build Just What The User Wants Us To Build. +$! +$ GOSUB 'BUILDCOMMAND' +$! +$ ENDIF +$! +$! Time To EXIT. +$! +$ GOTO TIDY +$! +$! Rebuild The [.CRYPTO._xxx]OPENSSLCONF.H" file. +$! +$ CONFIG: +$! +$! Tell The User We Are Creating The [.CRYPTO._xxx]OPENSSLCONF.H File. +$! +$ WRITE SYS$OUTPUT "Creating [.CRYPTO.''ARCHD']OPENSSLCONF.H Include File." +$! +$! First, make sure the directory exists. +$! +$ IF F$PARSE("SYS$DISK:[.CRYPTO.''ARCHD']") .EQS. "" THEN - + CREATE/DIRECTORY SYS$DISK:[.CRYPTO.'ARCHD'] +$! +$! Different tar/UnZip versions/option may have named the file differently +$ IF F$SEARCH("[.crypto]opensslconf.h_in") .NES. "" +$ THEN +$ OPENSSLCONF_H_IN = "[.crypto]opensslconf.h_in" +$ ELSE +$ IF F$SEARCH( "[.crypto]opensslconf_h.in") .NES. "" +$ THEN +$ OPENSSLCONF_H_IN = "[.crypto]opensslconf_h.in" +$ ELSE +$ ! For ODS-5 +$ IF F$SEARCH( "[.crypto]opensslconf.h.in") .NES. "" +$ THEN +$ OPENSSLCONF_H_IN = "[.crypto]opensslconf.h.in" +$ ELSE +$ WRITE SYS$ERROR "Couldn't find a [.crypto]opensslconf.h.in. Exiting!" +$ $STATUS = %X00018294 ! "%RMS-F-FNF, file not found". +$ GOTO TIDY +$ ENDIF +$ ENDIF +$ ENDIF +$! +$! Create The [.CRYPTO._xxx]OPENSSLCONF.H File. +$! Make sure it has the right format. +$! +$ OSCH_NAME = "SYS$DISK:[.CRYPTO.''ARCHD']OPENSSLCONF.H" +$ CREATE /FDL=SYS$INPUT: 'OSCH_NAME' +RECORD + FORMAT stream_lf +$ OPEN /APPEND H_FILE 'OSCH_NAME' +$! +$! Write The [.CRYPTO._xxx]OPENSSLCONF.H File. +$! +$ WRITE H_FILE "/* This file was automatically built using makevms.com */" +$ WRITE H_FILE "/* and ''OPENSSLCONF_H_IN' */" +$! +$! Write a few macros that indicate how this system was built. +$! +$ WRITE H_FILE "" +$ WRITE H_FILE "#ifndef OPENSSL_SYS_VMS" +$ WRITE H_FILE "# define OPENSSL_SYS_VMS" +$ WRITE H_FILE "#endif" +$ +$! One of the best way to figure out what the list should be is to do +$! the following on a Unix system: +$! grep OPENSSL_NO_ crypto/*/*.h ssl/*.h engines/*.h engines/*/*.h|grep ':# *if'|sed -e 's/^.*def //'|sort|uniq +$! For that reason, the list will also always end up in alphabetical order +$ CONFIG_LOGICALS := AES,- + ASM,INLINE_ASM,- + BF,- + BIO,- + BUFFER,- + BUF_FREELISTS,- + CAMELLIA,- + CAST,- + CMS,- + COMP,- + DEPRECATED,- + DES,- + DGRAM,- + DH,- + DSA,- + EC,- + ECDH,- + ECDSA,- + ENGINE,- + ERR,- + EVP,- + FP_API,- + GMP,- + GOST,- + HASH_COMP,- + HMAC,- + IDEA,- + JPAKE,- + KRB5,- + LHASH,- + MD2,- + MD4,- + MD5,- + MDC2,- + OCSP,- + PSK,- + RC2,- + RC4,- + RC5,- + RFC3779,- + RIPEMD,- + RSA,- + SEED,- + SHA,- + SHA0,- + SHA1,- + SHA256,- + SHA512,- + SOCK,- + SSL2,- + STACK,- + STATIC_ENGINE,- + STDIO,- + STORE,- + TLSEXT,- + WHIRLPOOL,- + X509 +$! Add a few that we know about +$ CONFIG_LOGICALS := 'CONFIG_LOGICALS',- + THREADS +$! The following rules, which dictate how some algorithm choices affect +$! others, are picked from Configure. +$! Quick syntax: +$! list = item[ ; list] +$! item = algos / dependents +$! algos = algo [, algos] +$! dependents = dependent [, dependents] +$! When a list of algos is specified in one item, it means that they must +$! all be disabled for the rule to apply. +$! When a list of dependents is specified in one item, it means that they +$! will all be disabled if the rule applies. +$! Rules are checked sequentially. If a rule disables an algorithm, it will +$! affect all following rules that depend on that algorithm being disabled. +$! To force something to be enabled or disabled, have no algorithms in the +$! algos part. +$ CONFIG_DISABLE_RULES := RIJNDAEL/AES;- + DES/MDC2;- + EC/ECDSA,ECDH;- + MD5/SSL2,SSL3,TLS1;- + SHA/SSL3,TLS1;- + RSA/SSL2;- + RSA,DSA/SSL2;- + DH/SSL3,TLS1;- + TLS1/TLSEXT;- + EC/GOST;- + DSA/GOST;- + DH/GOST;- + /STATIC_ENGINE;- + /KRB5 +$ CONFIG_ENABLE_RULES := ZLIB_DYNAMIC/ZLIB;- + /THREADS +$ +$! Architecture specific rule addtions +$ IF ARCH .EQS. "VAX" +$ THEN +$ ! Disable algorithms that require 64-bit integers in C +$ CONFIG_DISABLE_RULES = CONFIG_DISABLE_RULES + - + ";/GOST" + - + ";/WHIRLPOOL" +$ ENDIF +$ +$ CONFIG_LOG_I = 0 +$ CONFIG_LOG_LOOP1: +$ CONFIG_LOG_E = F$EDIT(F$ELEMENT(CONFIG_LOG_I,",",CONFIG_LOGICALS),"TRIM") +$ CONFIG_LOG_I = CONFIG_LOG_I + 1 +$ IF CONFIG_LOG_E .EQS. "" THEN GOTO CONFIG_LOG_LOOP1 +$ IF CONFIG_LOG_E .EQS. "," THEN GOTO CONFIG_LOG_LOOP1_END +$ IF F$TRNLNM("OPENSSL_NO_"+CONFIG_LOG_E) +$ THEN +$ CONFIG_DISABLED_'CONFIG_LOG_E' := YES +$ CONFIG_ENABLED_'CONFIG_LOG_E' := NO +$ CONFIG_CHANGED_'CONFIG_LOG_E' := YES +$ ELSE +$ CONFIG_DISABLED_'CONFIG_LOG_E' := NO +$ CONFIG_ENABLED_'CONFIG_LOG_E' := YES +$ ! Because all algorithms are assumed enabled by default +$ CONFIG_CHANGED_'CONFIG_LOG_E' := NO +$ ENDIF +$ GOTO CONFIG_LOG_LOOP1 +$ CONFIG_LOG_LOOP1_END: +$ +$! Apply cascading disable rules +$ CONFIG_DISABLE_I = 0 +$ CONFIG_DISABLE_LOOP0: +$ CONFIG_DISABLE_E = F$EDIT(F$ELEMENT(CONFIG_DISABLE_I,";", - + CONFIG_DISABLE_RULES),"TRIM") +$ CONFIG_DISABLE_I = CONFIG_DISABLE_I + 1 +$ IF CONFIG_DISABLE_E .EQS. "" THEN GOTO CONFIG_DISABLE_LOOP0 +$ IF CONFIG_DISABLE_E .EQS. ";" THEN GOTO CONFIG_DISABLE_LOOP0_END +$ +$ CONFIG_DISABLE_ALGOS = F$EDIT(F$ELEMENT(0,"/",CONFIG_DISABLE_E),"TRIM") +$ CONFIG_DISABLE_DEPENDENTS = F$EDIT(F$ELEMENT(1,"/",CONFIG_DISABLE_E),"TRIM") +$ TO_DISABLE := YES +$ CONFIG_ALGO_I = 0 +$ CONFIG_DISABLE_LOOP1: +$ CONFIG_ALGO_E = F$EDIT(F$ELEMENT(CONFIG_ALGO_I,",", - + CONFIG_DISABLE_ALGOS),"TRIM") +$ CONFIG_ALGO_I = CONFIG_ALGO_I + 1 +$ IF CONFIG_ALGO_E .EQS. "" THEN GOTO CONFIG_DISABLE_LOOP1 +$ IF CONFIG_ALGO_E .EQS. "," THEN GOTO CONFIG_DISABLE_LOOP1_END +$ IF F$TYPE(CONFIG_DISABLED_'CONFIG_ALGO_E') .EQS. "" +$ THEN +$ TO_DISABLE := NO +$ ELSE +$ IF .NOT. CONFIG_DISABLED_'CONFIG_ALGO_E' THEN TO_DISABLE := NO +$ ENDIF +$ GOTO CONFIG_DISABLE_LOOP1 +$ CONFIG_DISABLE_LOOP1_END: +$ +$ IF TO_DISABLE +$ THEN +$ CONFIG_DEPENDENT_I = 0 +$ CONFIG_DISABLE_LOOP2: +$ CONFIG_DEPENDENT_E = F$EDIT(F$ELEMENT(CONFIG_DEPENDENT_I,",", - + CONFIG_DISABLE_DEPENDENTS),"TRIM") +$ CONFIG_DEPENDENT_I = CONFIG_DEPENDENT_I + 1 +$ IF CONFIG_DEPENDENT_E .EQS. "" THEN GOTO CONFIG_DISABLE_LOOP2 +$ IF CONFIG_DEPENDENT_E .EQS. "," THEN GOTO CONFIG_DISABLE_LOOP2_END +$ CONFIG_DISABLED_'CONFIG_DEPENDENT_E' := YES +$ CONFIG_ENABLED_'CONFIG_DEPENDENT_E' := NO +$ ! Better not to assume defaults at this point... +$ CONFIG_CHANGED_'CONFIG_DEPENDENT_E' := YES +$ WRITE SYS$ERROR - + "''CONFIG_DEPENDENT_E' disabled by rule ''CONFIG_DISABLE_E'" +$ GOTO CONFIG_DISABLE_LOOP2 +$ CONFIG_DISABLE_LOOP2_END: +$ ENDIF +$ GOTO CONFIG_DISABLE_LOOP0 +$ CONFIG_DISABLE_LOOP0_END: +$ +$! Apply cascading enable rules +$ CONFIG_ENABLE_I = 0 +$ CONFIG_ENABLE_LOOP0: +$ CONFIG_ENABLE_E = F$EDIT(F$ELEMENT(CONFIG_ENABLE_I,";", - + CONFIG_ENABLE_RULES),"TRIM") +$ CONFIG_ENABLE_I = CONFIG_ENABLE_I + 1 +$ IF CONFIG_ENABLE_E .EQS. "" THEN GOTO CONFIG_ENABLE_LOOP0 +$ IF CONFIG_ENABLE_E .EQS. ";" THEN GOTO CONFIG_ENABLE_LOOP0_END +$ +$ CONFIG_ENABLE_ALGOS = F$EDIT(F$ELEMENT(0,"/",CONFIG_ENABLE_E),"TRIM") +$ CONFIG_ENABLE_DEPENDENTS = F$EDIT(F$ELEMENT(1,"/",CONFIG_ENABLE_E),"TRIM") +$ TO_ENABLE := YES +$ CONFIG_ALGO_I = 0 +$ CONFIG_ENABLE_LOOP1: +$ CONFIG_ALGO_E = F$EDIT(F$ELEMENT(CONFIG_ALGO_I,",", - + CONFIG_ENABLE_ALGOS),"TRIM") +$ CONFIG_ALGO_I = CONFIG_ALGO_I + 1 +$ IF CONFIG_ALGO_E .EQS. "" THEN GOTO CONFIG_ENABLE_LOOP1 +$ IF CONFIG_ALGO_E .EQS. "," THEN GOTO CONFIG_ENABLE_LOOP1_END +$ IF F$TYPE(CONFIG_ENABLED_'CONFIG_ALGO_E') .EQS. "" +$ THEN +$ TO_ENABLE := NO +$ ELSE +$ IF .NOT. CONFIG_ENABLED_'CONFIG_ALGO_E' THEN TO_ENABLE := NO +$ ENDIF +$ GOTO CONFIG_ENABLE_LOOP1 +$ CONFIG_ENABLE_LOOP1_END: +$ +$ IF TO_ENABLE +$ THEN +$ CONFIG_DEPENDENT_I = 0 +$ CONFIG_ENABLE_LOOP2: +$ CONFIG_DEPENDENT_E = F$EDIT(F$ELEMENT(CONFIG_DEPENDENT_I,",", - + CONFIG_ENABLE_DEPENDENTS),"TRIM") +$ CONFIG_DEPENDENT_I = CONFIG_DEPENDENT_I + 1 +$ IF CONFIG_DEPENDENT_E .EQS. "" THEN GOTO CONFIG_ENABLE_LOOP2 +$ IF CONFIG_DEPENDENT_E .EQS. "," THEN GOTO CONFIG_ENABLE_LOOP2_END +$ CONFIG_DISABLED_'CONFIG_DEPENDENT_E' := NO +$ CONFIG_ENABLED_'CONFIG_DEPENDENT_E' := YES +$ ! Better not to assume defaults at this point... +$ CONFIG_CHANGED_'CONFIG_DEPENDENT_E' := YES +$ WRITE SYS$ERROR - + "''CONFIG_DEPENDENT_E' enabled by rule ''CONFIG_ENABLE_E'" +$ GOTO CONFIG_ENABLE_LOOP2 +$ CONFIG_ENABLE_LOOP2_END: +$ ENDIF +$ GOTO CONFIG_ENABLE_LOOP0 +$ CONFIG_ENABLE_LOOP0_END: +$ +$! Write to the configuration +$ CONFIG_LOG_I = 0 +$ CONFIG_LOG_LOOP2: +$ CONFIG_LOG_E = F$EDIT(F$ELEMENT(CONFIG_LOG_I,",",CONFIG_LOGICALS),"TRIM") +$ CONFIG_LOG_I = CONFIG_LOG_I + 1 +$ IF CONFIG_LOG_E .EQS. "" THEN GOTO CONFIG_LOG_LOOP2 +$ IF CONFIG_LOG_E .EQS. "," THEN GOTO CONFIG_LOG_LOOP2_END +$ IF CONFIG_CHANGED_'CONFIG_LOG_E' +$ THEN +$ IF CONFIG_DISABLED_'CONFIG_LOG_E' +$ THEN +$ WRITE H_FILE "#ifndef OPENSSL_NO_",CONFIG_LOG_E +$ WRITE H_FILE "# define OPENSSL_NO_",CONFIG_LOG_E +$ WRITE H_FILE "#endif" +$ ELSE +$ WRITE H_FILE "#ifndef OPENSSL_",CONFIG_LOG_E +$ WRITE H_FILE "# define OPENSSL_",CONFIG_LOG_E +$ WRITE H_FILE "#endif" +$ ENDIF +$ ENDIF +$ GOTO CONFIG_LOG_LOOP2 +$ CONFIG_LOG_LOOP2_END: +$! +$ WRITE H_FILE "" +$ WRITE H_FILE "/* 2011-02-23 SMS." +$ WRITE H_FILE " * On VMS (V8.3), setvbuf() doesn't support a 64-bit" +$ WRITE H_FILE " * ""in"" pointer, and the help says:" +$ WRITE H_FILE " * Please note that the previously documented" +$ WRITE H_FILE " * value _IONBF is not supported." +$ WRITE H_FILE " * So, skip it on VMS." +$ WRITE H_FILE " */" +$ WRITE H_FILE "#define OPENSSL_NO_SETVBUF_IONBF" +$ WRITE H_FILE "" +$! +$! Add in the common "crypto/opensslconf.h.in". +$! +$ TYPE 'OPENSSLCONF_H_IN' /OUTPUT=H_FILE: +$! +$ IF ARCH .NES. "VAX" +$ THEN +$! +$! Write the non-VAX specific data +$! +$ WRITE H_FILE "#if defined(HEADER_RC4_H)" +$ WRITE H_FILE "#undef RC4_INT" +$ WRITE H_FILE "#define RC4_INT unsigned int" +$ WRITE H_FILE "#undef RC4_CHUNK" +$ WRITE H_FILE "#define RC4_CHUNK unsigned long long" +$ WRITE H_FILE "#endif" +$! +$ WRITE H_FILE "#if defined(HEADER_DES_LOCL_H)" +$ WRITE H_FILE "#undef DES_LONG" +$ WRITE H_FILE "#define DES_LONG unsigned int" +$ WRITE H_FILE "#undef DES_PTR" +$ WRITE H_FILE "#define DES_PTR" +$ WRITE H_FILE "#undef DES_RISC1" +$ WRITE H_FILE "#undef DES_RISC2" +$ WRITE H_FILE "#define DES_RISC1" +$ WRITE H_FILE "#undef DES_UNROLL" +$ WRITE H_FILE "#define DES_UNROLL" +$ WRITE H_FILE "#endif" +$! +$ WRITE H_FILE "#if defined(HEADER_BN_H)" +$ WRITE H_FILE "#undef BN_LLONG" ! Never define with SIXTY_FOUR_BIT +$ WRITE H_FILE "#undef SIXTY_FOUR_BIT_LONG" +$ WRITE H_FILE "#undef SIXTY_FOUR_BIT" +$ WRITE H_FILE "#define SIXTY_FOUR_BIT" +$ WRITE H_FILE "#undef THIRTY_TWO_BIT" +$ WRITE H_FILE "#undef SIXTEEN_BIT" +$ WRITE H_FILE "#undef EIGHT_BIT" +$ WRITE H_FILE "#endif" +$ +$ WRITE H_FILE "#undef OPENSSL_EXPORT_VAR_AS_FUNCTION" +$! +$! Else... +$! +$ ELSE +$! +$! Write the VAX specific data +$! +$ WRITE H_FILE "#if defined(HEADER_RC4_H)" +$ WRITE H_FILE "#undef RC4_INT" +$ WRITE H_FILE "#define RC4_INT unsigned char" +$ WRITE H_FILE "#undef RC4_CHUNK" +$ WRITE H_FILE "#define RC4_CHUNK unsigned long" +$ WRITE H_FILE "#endif" +$! +$ WRITE H_FILE "#if defined(HEADER_DES_LOCL_H)" +$ WRITE H_FILE "#undef DES_LONG" +$ WRITE H_FILE "#define DES_LONG unsigned long" +$ WRITE H_FILE "#undef DES_PTR" +$ WRITE H_FILE "#define DES_PTR" +$ WRITE H_FILE "#undef DES_RISC1" +$ WRITE H_FILE "#undef DES_RISC2" +$ WRITE H_FILE "#undef DES_UNROLL" +$ WRITE H_FILE "#endif" +$! +$ WRITE H_FILE "#if defined(HEADER_BN_H)" +$ WRITE H_FILE "#undef BN_LLONG" ! VAX C/DEC C doesn't have long long +$ WRITE H_FILE "#undef SIXTY_FOUR_BIT_LONG" +$ WRITE H_FILE "#undef SIXTY_FOUR_BIT" +$ WRITE H_FILE "#undef THIRTY_TWO_BIT" +$ WRITE H_FILE "#define THIRTY_TWO_BIT" +$ WRITE H_FILE "#undef SIXTEEN_BIT" +$ WRITE H_FILE "#undef EIGHT_BIT" +$ WRITE H_FILE "#endif" +$! +$! Oddly enough, the following symbol is tested in crypto/sha/sha512.c +$! before sha.h gets included (and HEADER_SHA_H defined), so we will not +$! protect this one... +$ WRITE H_FILE "#undef OPENSSL_NO_SHA512" +$ WRITE H_FILE "#define OPENSSL_NO_SHA512" +$! +$ WRITE H_FILE "#undef OPENSSL_EXPORT_VAR_AS_FUNCTION" +$ WRITE H_FILE "#define OPENSSL_EXPORT_VAR_AS_FUNCTION" +$! +$! End +$! +$ ENDIF +$! +$! Close the [.CRYPTO._xxx]OPENSSLCONF.H file +$! +$ CLOSE H_FILE +$! +$! Purge The [.CRYPTO._xxx]OPENSSLCONF.H file +$! +$ PURGE SYS$DISK:[.CRYPTO.'ARCHD']OPENSSLCONF.H +$! +$! That's All, Time To RETURN. +$! +$ RETURN +$! +$! Rebuild The "[.CRYPTO._xxx]BUILDINF.H" file. +$! +$ BUILDINF: +$! +$! Tell The User We Are Creating The [.CRYPTO._xxx]BUILDINF.H File. +$! +$ WRITE SYS$OUTPUT "Creating [.CRYPTO.''ARCHD']BUILDINF.H Include File." +$! +$! Create The [.CRYPTO._xxx]BUILDINF.H File. +$! +$ BIH_NAME = "SYS$DISK:[.CRYPTO.''ARCHD']BUILDINF.H" +$ CREATE /FDL=SYS$INPUT: 'BIH_NAME' +RECORD + FORMAT stream_lf +$! +$ OPEN /APPEND H_FILE 'bih_name' +$! +$! Get The Current Date & Time. +$! +$ TIME = F$TIME() +$! +$! Write The [.CRYPTO._xxx]BUILDINF.H File. +$! +$ CFLAGS = "" +$ if (POINTER_SIZE .nes. "") +$ then +$ CFLAGS = CFLAGS+ "/POINTER_SIZE=''POINTER_SIZE'" +$ endif +$ if (ZLIB .nes. "") +$ then +$ if (CFLAGS .nes. "") then CFLAGS = CFLAGS+ " " +$ CFLAGS = CFLAGS+ "/DEFINE=ZLIB" +$ endif +$! +$ WRITE H_FILE "#define CFLAGS ""''CFLAGS'""" +$ WRITE H_FILE "#define PLATFORM ""VMS ''ARCHD' ''VMS_VERSION'""" +$ WRITE H_FILE "#define DATE ""''TIME'"" " +$! +$! Close The [.CRYPTO._xxx]BUILDINF.H File. +$! +$ CLOSE H_FILE +$! +$! Purge The [.CRYPTO._xxx]BUILDINF.H File. +$! +$ PURGE SYS$DISK:[.CRYPTO.'ARCHD']BUILDINF.H +$! +$! Delete [.CRYPTO]BUILDINF.H File, as there might be some residue from Unix. +$! +$ IF F$SEARCH("[.CRYPTO]BUILDINF.H") .NES. "" THEN - + DELETE SYS$DISK:[.CRYPTO]BUILDINF.H;* +$! +$! That's All, Time To RETURN. +$! +$ RETURN +$! +$! Copy a lot of files around. +$! +$ SOFTLINKS: +$! +$!!!! Tell The User We Are Partly Rebuilding The [.APPS] Directory. +$!!!! +$!!! WRITE SYS$OUTPUT "Rebuilding The '[.APPS]MD4.C' File." +$!!!! +$!!! DELETE SYS$DISK:[.APPS]MD4.C;* +$!!!! +$!!!! Copy MD4.C from [.CRYPTO.MD4] into [.APPS] +$!!!! +$!!! COPY SYS$DISK:[.CRYPTO.MD4]MD4.C SYS$DISK:[.APPS] +$! +$! Ensure that the [.include.openssl] directory contains a full set of +$! real header files. The distribution kit may have left real or fake +$! symlinks there. Rather than think about what's there, simply delete +$! the destination files (fake or real symlinks) before copying the real +$! header files in. (Copying a real header file onto a real symlink +$! merely duplicates the real header file at its source.) +$! +$! Tell The User We Are Rebuilding The [.include.openssl] Directory. +$! +$ WRITE SYS$OUTPUT "Rebuilding The '[.include.openssl]' Directory." +$! +$! First, make sure the directory exists. If it did exist, delete all +$! the existing header files (or fake or real symlinks). +$! +$ if f$parse( "sys$disk:[.include.openssl]") .eqs. "" +$ then +$ create /directory sys$disk:[.include.openssl] +$ else +$ delete sys$disk:[.include.openssl]*.h;* +$ endif +$! +$! Copy All The ".H" Files From The Main Directory. +$! +$ EXHEADER := e_os2.h +$ copy 'exheader' sys$disk:[.include.openssl] +$! +$! Copy All The ".H" Files From The [.CRYPTO] Directory Tree. +$! +$ SDIRS := , - + 'ARCHD', - + OBJECTS, - + MD2, MD4, MD5, SHA, MDC2, HMAC, RIPEMD, WHRLPOOL, - + DES, AES, RC2, RC4, RC5, IDEA, BF, CAST, CAMELLIA, SEED, MODES, - + BN, EC, RSA, DSA, ECDSA, DH, ECDH, DSO, ENGINE, - + BUFFER, BIO, STACK, LHASH, RAND, ERR, - + EVP, ASN1, PEM, X509, X509V3, CONF, TXT_DB, PKCS7, PKCS12, - + COMP, OCSP, UI, KRB5, - + STORE, CMS, PQUEUE, TS, JPAKE +$! +$ EXHEADER_ := crypto.h, opensslv.h, ebcdic.h, symhacks.h, ossl_typ.h +$ EXHEADER_'ARCHD' := opensslconf.h +$ EXHEADER_OBJECTS := objects.h, obj_mac.h +$ EXHEADER_MD2 := md2.h +$ EXHEADER_MD4 := md4.h +$ EXHEADER_MD5 := md5.h +$ EXHEADER_SHA := sha.h +$ EXHEADER_MDC2 := mdc2.h +$ EXHEADER_HMAC := hmac.h +$ EXHEADER_RIPEMD := ripemd.h +$ EXHEADER_WHRLPOOL := whrlpool.h +$ EXHEADER_DES := des.h, des_old.h +$ EXHEADER_AES := aes.h +$ EXHEADER_RC2 := rc2.h +$ EXHEADER_RC4 := rc4.h +$ EXHEADER_RC5 := rc5.h +$ EXHEADER_IDEA := idea.h +$ EXHEADER_BF := blowfish.h +$ EXHEADER_CAST := cast.h +$ EXHEADER_CAMELLIA := camellia.h +$ EXHEADER_SEED := seed.h +$ EXHEADER_MODES := modes.h +$ EXHEADER_BN := bn.h +$ EXHEADER_EC := ec.h +$ EXHEADER_RSA := rsa.h +$ EXHEADER_DSA := dsa.h +$ EXHEADER_ECDSA := ecdsa.h +$ EXHEADER_DH := dh.h +$ EXHEADER_ECDH := ecdh.h +$ EXHEADER_DSO := dso.h +$ EXHEADER_ENGINE := engine.h +$ EXHEADER_BUFFER := buffer.h +$ EXHEADER_BIO := bio.h +$ EXHEADER_STACK := stack.h, safestack.h +$ EXHEADER_LHASH := lhash.h +$ EXHEADER_RAND := rand.h +$ EXHEADER_ERR := err.h +$ EXHEADER_EVP := evp.h +$ EXHEADER_ASN1 := asn1.h, asn1_mac.h, asn1t.h +$ EXHEADER_PEM := pem.h, pem2.h +$ EXHEADER_X509 := x509.h, x509_vfy.h +$ EXHEADER_X509V3 := x509v3.h +$ EXHEADER_CONF := conf.h, conf_api.h +$ EXHEADER_TXT_DB := txt_db.h +$ EXHEADER_PKCS7 := pkcs7.h +$ EXHEADER_PKCS12 := pkcs12.h +$ EXHEADER_COMP := comp.h +$ EXHEADER_OCSP := ocsp.h +$ EXHEADER_UI := ui.h, ui_compat.h +$ EXHEADER_KRB5 := krb5_asn.h +$!!! EXHEADER_STORE := store.h, str_compat.h +$ EXHEADER_STORE := store.h +$ EXHEADER_CMS := cms.h +$ EXHEADER_PQUEUE := pqueue.h +$ EXHEADER_TS := ts.h +$ EXHEADER_JPAKE := jpake.h +$! +$ i = 0 +$ loop_sdirs: +$ sdir = f$edit( f$element( i, ",", sdirs), "trim") +$ i = i + 1 +$ if (sdir .eqs. ",") then goto loop_sdirs_end +$ hdr_list = exheader_'sdir' +$ if (sdir .nes. "") then sdir = "."+ sdir +$ copy [.crypto'sdir']'hdr_list' sys$disk:[.include.openssl] +$ goto loop_sdirs +$ loop_sdirs_end: +$! +$! Copy All The ".H" Files From The [.SSL] Directory. +$! +$! (keep these in the same order as ssl/Makefile) +$ EXHEADER := ssl.h, ssl2.h, ssl3.h, ssl23.h, tls1.h, dtls1.h, kssl.h +$ copy sys$disk:[.ssl]'exheader' sys$disk:[.include.openssl] +$! +$! Purge the [.include.openssl] header files. +$! +$ purge sys$disk:[.include.openssl]*.h +$! +$! That's All, Time To RETURN. +$! +$ RETURN +$! +$! Build The "[.xxx.EXE.CRYPTO]SSL_LIBCRYPTO''LIB32'.OLB" Library. +$! +$ CRYPTO: +$! +$! Tell The User What We Are Doing. +$! +$ WRITE SYS$OUTPUT "" +$ WRITE SYS$OUTPUT - + "Building The [.",ARCHD,".EXE.CRYPTO]SSL_LIBCRYPTO''LIB32'.OLB Library." +$! +$! Go To The [.CRYPTO] Directory. +$! +$ SET DEFAULT SYS$DISK:[.CRYPTO] +$! +$! Build The [.xxx.EXE.CRYPTO]LIBCRYPTO.OLB Library. +$! +$ @CRYPTO-LIB LIBRARY 'DEBUGGER' "''COMPILER'" "''TCPIP_TYPE'" - + "''ISSEVEN'" "''BUILDPART'" "''POINTER_SIZE'" "''ZLIB'" +$! +$! Build The [.xxx.EXE.CRYPTO]*.EXE Test Applications. +$! +$ @CRYPTO-LIB APPS 'DEBUGGER' "''COMPILER'" "''TCPIP_TYPE'" - + "''ISSEVEN'" "''BUILDPART'" "''POINTER_SIZE'" "''ZLIB'" +$! +$! Go Back To The Main Directory. +$! +$ SET DEFAULT [-] +$! +$! Time To RETURN. +$! +$ RETURN +$! +$! Build The "[.xxx.EXE.SSL]SSL_LIBSSL''LIB32'.OLB" Library. +$! +$ SSL: +$! +$! Tell The User What We Are Doing. +$! +$ WRITE SYS$OUTPUT "" +$ WRITE SYS$OUTPUT - + "Building The [.",ARCHD,".EXE.SSL]SSL_LIBSSL''LIB32'.OLB Library." +$! +$! Go To The [.SSL] Directory. +$! +$ SET DEFAULT SYS$DISK:[.SSL] +$! +$! Build The [.xxx.EXE.SSL]LIBSSL.OLB Library. +$! +$ @SSL-LIB LIBRARY 'DEBUGGER' "''COMPILER'" "''TCPIP_TYPE'" - + "''ISSEVEN'" "''POINTER_SIZE'" "''ZLIB'" +$! +$! Go Back To The Main Directory. +$! +$ SET DEFAULT [-] +$! +$! Time To Return. +$! +$ RETURN +$! +$! Build The "[.xxx.EXE.SSL]SSL_TASK.EXE" Program. +$! +$ SSL_TASK: +$! +$! Tell The User What We Are Doing. +$! +$ WRITE SYS$OUTPUT "" +$ WRITE SYS$OUTPUT - + "Building DECNet Based SSL Engine, [.",ARCHD,".EXE.SSL]SSL_TASK.EXE" +$! +$! Go To The [.SSL] Directory. +$! +$ SET DEFAULT SYS$DISK:[.SSL] +$! +$! Build The [.xxx.EXE.SSL]SSL_TASK.EXE +$! +$ @SSL-LIB SSL_TASK 'DEBUGGER' "''COMPILER'" "''TCPIP_TYPE'" - + "''ISSEVEN'" "''POINTER_SIZE'" "''ZLIB'" +$! +$! Go Back To The Main Directory. +$! +$ SET DEFAULT [-] +$! +$! That's All, Time To RETURN. +$! +$ RETURN +$! +$! Build The OpenSSL Test Programs. +$! +$ TEST: +$! +$! Tell The User What We Are Doing. +$! +$ WRITE SYS$OUTPUT "" +$ WRITE SYS$OUTPUT "Building The OpenSSL [.",ARCHD,".EXE.TEST] Test Utilities." +$! +$! Go To The [.TEST] Directory. +$! +$ SET DEFAULT SYS$DISK:[.TEST] +$! +$! Build The Test Programs. +$! +$ @MAKETESTS 'DEBUGGER' "''COMPILER'" "''TCPIP_TYPE'" "''ISSEVEN'" - + "''POINTER_SIZE'" "''ZLIB'" +$! +$! Go Back To The Main Directory. +$! +$ SET DEFAULT [-] +$! +$! That's All, Time To RETURN. +$! +$ RETURN +$! +$! Build The OpenSSL Application Programs. +$! +$ APPS: +$! +$! Tell The User What We Are Doing. +$! +$ WRITE SYS$OUTPUT "" +$ WRITE SYS$OUTPUT "Building OpenSSL [.",ARCHD,".EXE.APPS] Applications." +$! +$! Go To The [.APPS] Directory. +$! +$ SET DEFAULT SYS$DISK:[.APPS] +$! +$! Build The Application Programs. +$! +$ @MAKEAPPS 'DEBUGGER' "''COMPILER'" "''TCPIP_TYPE'" "''ISSEVEN'" - + "" "''POINTER_SIZE'" "''ZLIB'" +$! +$! Go Back To The Main Directory. +$! +$ SET DEFAULT [-] +$! +$! That's All, Time To RETURN. +$! +$ RETURN +$! +$! Build The OpenSSL Application Programs. +$! +$ ENGINES: +$! +$! Tell The User What We Are Doing. +$! +$ WRITE SYS$OUTPUT "" +$ WRITE SYS$OUTPUT "Building OpenSSL [.",ARCHD,".EXE.ENGINES] Engines." +$! +$! Go To The [.ENGINES] Directory. +$! +$ SET DEFAULT SYS$DISK:[.ENGINES] +$! +$! Build The Application Programs. +$! +$ @MAKEENGINES ENGINES 'DEBUGGER' "''COMPILER'" "''TCPIP_TYPE'" - + "''ISSEVEN'" "''BUILDPART'" "''POINTER_SIZE'" "''ZLIB'" +$! +$! Go Back To The Main Directory. +$! +$ SET DEFAULT [-] +$! +$! That's All, Time To RETURN. +$! +$ RETURN +$! +$! Check The User's Options. +$! +$ CHECK_OPTIONS: +$! +$! Check if there's a "part", and separate it out +$! +$ BUILDPART = F$ELEMENT(1,"/",P1) +$ IF BUILDPART .EQS. "/" +$ THEN +$ BUILDPART = "" +$ ELSE +$ P1 = F$EXTRACT(0,F$LENGTH(P1) - F$LENGTH(BUILDPART) - 1, P1) +$ ENDIF +$! +$! Check To See If P1 Is Blank. +$! +$ IF (P1.EQS."ALL") +$ THEN +$! +$! P1 Is ALL, So Build Everything. +$! +$ BUILDCOMMAND = "ALL" +$! +$! Else... +$! +$ ELSE +$! +$! Else, Check To See If P1 Has A Valid Argument. +$! +$ IF (P1.EQS."CONFIG").OR.(P1.EQS."BUILDINF").OR.(P1.EQS."SOFTLINKS") - + .OR.(P1.EQS."BUILDALL") - + .OR.(P1.EQS."CRYPTO").OR.(P1.EQS."SSL") - + .OR.(P1.EQS."SSL_TASK").OR.(P1.EQS."TEST").OR.(P1.EQS."APPS") - + .OR.(P1.EQS."ENGINES") +$ THEN +$! +$! A Valid Argument. +$! +$ BUILDCOMMAND = P1 +$! +$! Else... +$! +$ ELSE +$! +$! Tell The User We Don't Know What They Want. +$! +$ WRITE SYS$OUTPUT "" +$ WRITE SYS$OUTPUT "USAGE: @MAKEVMS.COM [Target] [Pointer size] [Debug option] " +$ WRITE SYS$OUTPUT "" +$ WRITE SYS$OUTPUT "Example: @MAKEVMS.COM ALL """" NODEBUG " +$ WRITE SYS$OUTPUT "" +$ WRITE SYS$OUTPUT "The Target ",P1," Is Invalid. The Valid Target Options Are:" +$ WRITE SYS$OUTPUT "" +$ WRITE SYS$OUTPUT " ALL : Just Build Everything." +$ WRITE SYS$OUTPUT " CONFIG : Just build the [.CRYPTO._xxx]OPENSSLCONF.H file." +$ WRITE SYS$OUTPUT " BUILDINF : Just build the [.CRYPTO._xxx]BUILDINF.H file." +$ WRITE SYS$OUTPUT " SOFTLINKS: Just Fix The Unix soft links." +$ WRITE SYS$OUTPUT " BUILDALL : Same as ALL, except CONFIG, BUILDINF and SOFTILNKS aren't done." +$ WRITE SYS$OUTPUT " CRYPTO : To Build Just The [.xxx.EXE.CRYPTO]LIBCRYPTO.OLB Library." +$ WRITE SYS$OUTPUT " CRYPTO/x : To Build Just The x Part Of The" +$ WRITE SYS$OUTPUT " [.xxx.EXE.CRYPTO]LIBCRYPTO.OLB Library." +$ WRITE SYS$OUTPUT " SSL : To Build Just The [.xxx.EXE.SSL]LIBSSL.OLB Library." +$ WRITE SYS$OUTPUT " SSL_TASK : To Build Just The [.xxx.EXE.SSL]SSL_TASK.EXE Program." +$ WRITE SYS$OUTPUT " TEST : To Build Just The OpenSSL Test Programs." +$ WRITE SYS$OUTPUT " APPS : To Build Just The OpenSSL Application Programs." +$ WRITE SYS$OUTPUT " ENGINES : To Build Just The ENGINES" +$ WRITE SYS$OUTPUT "" +$ WRITE SYS$OUTPUT " Where 'xxx' Stands For:" +$ WRITE SYS$OUTPUT "" +$ WRITE SYS$OUTPUT " ALPHA[64]: Alpha Architecture." +$ WRITE SYS$OUTPUT " IA64[64] : IA64 Architecture." +$ WRITE SYS$OUTPUT " VAX : VAX Architecture." +$ WRITE SYS$OUTPUT "" +$! +$! Time To EXIT. +$! +$ GOTO TIDY +$! +$! End The Valid Argument Check. +$! +$ ENDIF +$! +$! End The P1 Check. +$! +$ ENDIF +$! +$! Check P2 (POINTER_SIZE). +$! +$ IF (P2 .NES. "") .AND. (ARCH .NES. "VAX") +$ THEN +$! +$ IF (P2 .EQS. "32") +$ THEN +$ POINTER_SIZE = "32" +$ ELSE +$ POINTER_SIZE = F$EDIT( P2, "COLLAPSE, UPCASE") +$ IF ((POINTER_SIZE .EQS. "64") .OR. - + (POINTER_SIZE .EQS. "64=") .OR. - + (POINTER_SIZE .EQS. "64=ARGV")) +$ THEN +$ ARCHD = ARCH+ "_64" +$ LIB32 = "" +$ ELSE +$! +$! Tell The User Entered An Invalid Option. +$! +$ WRITE SYS$OUTPUT "" +$ WRITE SYS$OUTPUT "The Option ", P2, - + " Is Invalid. The Valid Options Are:" +$ WRITE SYS$OUTPUT "" +$ WRITE SYS$OUTPUT - + " """" : Compile with default (short) pointers." +$ WRITE SYS$OUTPUT - + " 32 : Compile with 32-bit (short) pointers." +$ WRITE SYS$OUTPUT - + " 64 : Compile with 64-bit (long) pointers (auto ARGV)." +$ WRITE SYS$OUTPUT - + " 64= : Compile with 64-bit (long) pointers (no ARGV)." +$ WRITE SYS$OUTPUT - + " 64=ARGV : Compile with 64-bit (long) pointers (ARGV)." +$ WRITE SYS$OUTPUT "" +$! +$! Time To EXIT. +$! +$ GOTO TIDY +$! +$ ENDIF +$! +$ ENDIF +$! +$! End The P2 (POINTER_SIZE) Check. +$! +$ ENDIF +$! +$! Check To See If P3 Is Blank. +$! +$ IF (P3.EQS."NODEBUG") +$ THEN +$! +$! P3 Is NODEBUG, So Compile Without Debugger Information. +$! +$ DEBUGGER = "NODEBUG" +$! +$! Else... +$! +$ ELSE +$! +$! Check To See If We Are To Compile With Debugger Information. +$! +$ IF (P3.EQS."DEBUG") +$ THEN +$! +$! Compile With Debugger Information. +$! +$ DEBUGGER = "DEBUG" +$! +$! Else... +$! +$ ELSE +$! +$! Tell The User Entered An Invalid Option. +$! +$ WRITE SYS$OUTPUT "" +$ WRITE SYS$OUTPUT "The Option ",P3," Is Invalid. The Valid Options Are:" +$ WRITE SYS$OUTPUT "" +$ WRITE SYS$OUTPUT " DEBUG : Compile With The Debugger Information." +$ WRITE SYS$OUTPUT " NODEBUG : Compile Without The Debugger Information." +$ WRITE SYS$OUTPUT "" +$! +$! Time To EXIT. +$! +$ GOTO TIDY +$! +$! End The Valid Argument Check. +$! +$ ENDIF +$! +$! End The P3 Check. +$! +$ ENDIF +$! +$! Check To See If P4 Is Blank. +$! +$ IF (P4.EQS."") +$ THEN +$! +$! O.K., The User Didn't Specify A Compiler, Let's Try To +$! Find Out Which One To Use. +$! +$! Check To See If We Have GNU C. +$! +$ IF (F$TRNLNM("GNU_CC").NES."") +$ THEN +$! +$! Looks Like GNUC, Set To Use GNUC. +$! +$ COMPILER = "GNUC" +$! +$! Tell The User We Are Using GNUC. +$! +$ WRITE SYS$OUTPUT "Using GNU 'C' Compiler." +$! +$! End The GNU C Compiler Check. +$! +$ ENDIF +$! +$! Check To See If We Have VAXC Or DECC. +$! +$ IF (F$GETSYI("CPU").GE.128).OR.(F$TRNLNM("DECC$CC_DEFAULT").EQS."/DECC") +$ THEN +$! +$! Looks Like DECC, Set To Use DECC. +$! +$ COMPILER = "DECC" +$! +$! Tell The User We Are Using DECC. +$! +$ WRITE SYS$OUTPUT "Using DECC 'C' Compiler." +$! +$! Else... +$! +$ ELSE +$! +$! Looks Like VAXC, Set To Use VAXC. +$! +$ COMPILER = "VAXC" +$! +$! Tell The User We Are Using VAX C. +$! +$ WRITE SYS$OUTPUT "Using VAXC 'C' Compiler." +$! +$! End The DECC & VAXC Compiler Check. +$! +$ ENDIF +$! +$! Else... +$! +$ ELSE +$! +$! Check To See If The User Entered A Valid Parameter. +$! +$ IF (P4.EQS."VAXC").OR.(P4.EQS."DECC").OR.(P4.EQS."GNUC")!.OR.(P4.EQS."LINK") +$ THEN +$! +$! Check To See If The User Wanted To Just LINK. +$! +$ IF (P4.EQS."LINK") +$ THEN +$! +$! Looks Like LINK-only +$! +$ COMPILER = "LINK" +$! +$! Tell The User We Are Only Linking. +$! +$ WRITE SYS$OUTPUT "LINK Only. This actually NOT YET SUPPORTED!" +$! +$! End LINK Check. +$! +$ ENDIF +$! +$! Check To See If The User Wanted DECC. +$! +$ IF (P4.EQS."DECC") +$ THEN +$! +$! Looks Like DECC, Set To Use DECC. +$! +$ COMPILER = "DECC" +$! +$! Tell The User We Are Using DECC. +$! +$ WRITE SYS$OUTPUT "Using DECC 'C' Compiler." +$! +$! End DECC Check. +$! +$ ENDIF +$! +$! Check To See If We Are To Use VAXC. +$! +$ IF (P4.EQS."VAXC") +$ THEN +$! +$! Looks Like VAXC, Set To Use VAXC. +$! +$ COMPILER = "VAXC" +$! +$! Tell The User We Are Using VAX C. +$! +$ WRITE SYS$OUTPUT "Using VAXC 'C' Compiler." +$! +$! End VAXC Check +$! +$ ENDIF +$! +$! Check To See If We Are To Use GNU C. +$! +$ IF (P4.EQS."GNUC") +$ THEN +$! +$! Looks Like GNUC, Set To Use GNUC. +$! +$ COMPILER = "GNUC" +$! +$! Tell The User We Are Using GNUC. +$! +$ WRITE SYS$OUTPUT "Using GNU 'C' Compiler." +$! +$! End The GNU C Check. +$! +$ ENDIF +$! +$! Else The User Entered An Invalid Argument. +$! +$ ELSE +$! +$! Tell The User We Don't Know What They Want. +$! +$ WRITE SYS$OUTPUT "" +$ WRITE SYS$OUTPUT "The Option ",P4," Is Invalid. The Valid Options Are:" +$ WRITE SYS$OUTPUT "" +$ WRITE SYS$OUTPUT " VAXC : To Compile With VAX C." +$ WRITE SYS$OUTPUT " DECC : To Compile With DEC C." +$ WRITE SYS$OUTPUT " GNUC : To Compile With GNU C." +$ WRITE SYS$OUTPUT "" +$! +$! Time To EXIT. +$! +$ GOTO TIDY +$! +$! End The Valid Argument Check. +$! +$ ENDIF +$! +$! End The P4 Check. +$! +$ ENDIF +$! +$! Time to check the contents of P5, and to make sure we get the correct +$! library. +$! +$ IF P5.EQS."SOCKETSHR" .OR. P5.EQS."MULTINET" .OR. P5.EQS."UCX" - + .OR. P5.EQS."TCPIP" .OR. P5.EQS."NONE" +$ THEN +$! +$! Check to see if SOCKETSHR was chosen +$! +$ IF P5.EQS."SOCKETSHR" +$ THEN +$! +$! Set the library to use SOCKETSHR +$! +$ TCPIP_LIB = "SYS$DISK:[-.VMS]SOCKETSHR_SHR.OPT /OPTIONS" +$! +$! Tell the user +$! +$ WRITE SYS$OUTPUT "Using SOCKETSHR for TCP/IP" +$! +$! Done with SOCKETSHR +$! +$ ENDIF +$! +$! Check to see if MULTINET was chosen +$! +$ IF P5.EQS."MULTINET" +$ THEN +$! +$! Set the library to use UCX emulation. +$! +$ P5 = "UCX" +$! +$! Tell the user +$! +$ WRITE SYS$OUTPUT "Using MultiNet via UCX emulation for TCP/IP" +$! +$! Done with MULTINET +$! +$ ENDIF +$! +$! Check to see if UCX was chosen +$! +$ IF P5.EQS."UCX" +$ THEN +$! +$! Set the library to use UCX. +$! +$ TCPIP_LIB = "SYS$DISK:[-.VMS]UCX_SHR_DECC.OPT /OPTIONS" +$! +$! Tell the user +$! +$ WRITE SYS$OUTPUT "Using UCX or an emulation thereof for TCP/IP" +$! +$! Done with UCX +$! +$ ENDIF +$! +$! Check to see if TCPIP was chosen +$! +$ IF P5.EQS."TCPIP" +$ THEN +$! +$! Set the library to use TCPIP (post UCX). +$! +$ TCPIP_LIB = "SYS$DISK:[-.VMS]TCPIP_SHR_DECC.OPT /OPTIONS" +$! +$! Tell the user +$! +$ WRITE SYS$OUTPUT "Using TCPIP (post UCX) for TCP/IP" +$! +$! Done with TCPIP +$! +$ ENDIF +$! +$! Check to see if NONE was chosen +$! +$ IF P5.EQS."NONE" +$ THEN +$! +$! Do not use a TCPIP library. +$! +$ TCPIP_LIB = "" +$! +$! Tell the user +$! +$ WRITE SYS$OUTPUT "A specific TCPIP library will not be used." +$! +$! Done with NONE. +$! +$ ENDIF +$! +$! Set the TCPIP_TYPE symbol +$! +$ TCPIP_TYPE = P5 +$! +$! Print info +$! +$ WRITE SYS$OUTPUT "TCP/IP library spec: ", TCPIP_LIB +$! +$! Else The User Entered An Invalid Argument. +$! +$ ELSE +$ IF P5 .NES. "" +$ THEN +$! +$! Tell The User We Don't Know What They Want. +$! +$ WRITE SYS$OUTPUT "" +$ WRITE SYS$OUTPUT "The Option ",P5," Is Invalid. The Valid Options Are:" +$ WRITE SYS$OUTPUT "" +$ WRITE SYS$OUTPUT " SOCKETSHR : To link with SOCKETSHR TCP/IP library." +$ WRITE SYS$OUTPUT " UCX : To link with UCX TCP/IP library." +$ WRITE SYS$OUTPUT " TCPIP : To link with TCPIP TCP/IP (post UCX) library." +$ WRITE SYS$OUTPUT " NONE : To not link with a specific TCP/IP library." +$ WRITE SYS$OUTPUT "" +$! +$! Time To EXIT. +$! +$ GOTO TIDY +$ ELSE +$! +$! If TCPIP is not defined, then hardcode it to make +$! it clear that no TCPIP is desired. +$! +$ IF P5 .EQS. "" +$ THEN +$ TCPIP_LIB = "" +$ TCPIP_TYPE = "NONE" +$ ELSE +$! +$! Set the TCPIP_TYPE symbol +$! +$ TCPIP_TYPE = P5 +$ ENDIF +$ ENDIF +$! +$! Done with TCP/IP libraries +$! +$ ENDIF +$! +$! Special Threads For OpenVMS v7.1 Or Later +$! +$! Written By: Richard Levitte +$! richard@levitte.org +$! +$! +$! Check To See If We Have A Option For P6. +$! +$ IF (P6.EQS."") +$ THEN +$! +$! Get The Version Of VMS We Are Using. +$! +$ ISSEVEN := +$ TMP = F$ELEMENT(0,"-",F$EXTRACT(1,4,VMS_VERSION)) +$ TMP = F$INTEGER(F$ELEMENT(0,".",TMP)+F$ELEMENT(1,".",TMP)) +$! +$! Check To See If The VMS Version Is v7.1 Or Later. +$! +$ IF (TMP.GE.71) +$ THEN +$! +$! We Have OpenVMS v7.1 Or Later, So Use The Special Threads. +$! +$ ISSEVEN := ,PTHREAD_USE_D4 +$! +$! End The VMS Version Check. +$! +$ ENDIF +$! +$! End The P6 Check. +$! +$ ENDIF +$! +$! +$! Check To See If We Have A ZLIB Option. +$! +$ ZLIB = P7 +$ IF (ZLIB .NES. "") +$ THEN +$! +$! Check for expected ZLIB files. +$! +$ err = 0 +$ file1 = f$parse( "zlib.h", ZLIB, , , "SYNTAX_ONLY") +$ if (f$search( file1) .eqs. "") +$ then +$ WRITE SYS$OUTPUT "" +$ WRITE SYS$OUTPUT "The Option ", ZLIB, " Is Invalid." +$ WRITE SYS$OUTPUT " Can't find header: ''file1'" +$ err = 1 +$ endif +$! +$ file2 = f$parse( ZLIB, "libz.olb", , , "SYNTAX_ONLY") +$ if (f$search( file2) .eqs. "") +$ then +$ if (err .eq. 0) +$ then +$ WRITE SYS$OUTPUT "" +$ WRITE SYS$OUTPUT "The Option ", ZLIB, " Is Invalid." +$ endif +$ WRITE SYS$OUTPUT " Can't find library: ''file2'" +$ WRITE SYS$OUTPUT "" +$ err = err+ 2 +$ endif +$ if (err .eq. 1) +$ then +$ WRITE SYS$OUTPUT "" +$ endif +$! +$ if (err .ne. 0) +$ then +$ GOTO TIDY +$ endif +$! +$! Print info +$! +$ WRITE SYS$OUTPUT "ZLIB library spec: ", file2 +$! +$! End The ZLIB Check. +$! +$ ENDIF +$! +$! Time To RETURN... +$! +$ RETURN +$! +$ TIDY: +$! +$! Close any open files. +$! +$ if (f$trnlnm( "h_file", "LNM$PROCESS", 0, "SUPERVISOR") .nes. "") then - + close h_file +$! +$! Restore the original default device:[directory]. +$! +$ SET DEFAULT 'DEF_ORIG' +$! +$ EXIT +$! diff --git a/node-v0.8.14/deps/openssl/openssl/ms/.rnd b/node-v0.8.14/deps/openssl/openssl/ms/.rnd new file mode 100644 index 0000000000000000000000000000000000000000..0566b46dfe64e7ac1e6a6c49610d2d5e08e57c93 GIT binary patch literal 1024 zcmV+b1poUdN$RkC7kV^=SXx>N=2lzx_KLf**VV@3Q?)s68QAgBa;I%PPc^WyZS7HW zz+5!%-uU6;Y!y5_19D6i2+rT(JTttt6n%P>mN&K)VqU{Rzb8l;)_LUtvgi%FwV~+)Bg;`5zjWITKXGr*~)Lzg& z_K9^{i9Hgq^_4w@rnw%kRtR#pDcM0#&ng}UtC1B9a~DFTtw3?<89i*R5m_BI`RUN5rn6IUEyCLE6tE|9*rItR(QzsK!MiO& zuviVK%&FgeKvQH{OrzSRadJPZ{Ar{YogP;E7>gQe0;r3I^FXcEjspdfEB0}+jfpGT zP*c2vHk+*rlfiL*5 zv{_rsf@Ac;w=harwF|8#XG|jN4@%t?3j#IlW0{aYNlp?5;w7*(ycBa;U`l(kkHrdwJa`Vx% z#don@7N~&J`8P+5g4%W?z5@M|qZU?+wczb8m)%2|)Iucrq$xmuETCSS|NK)QD#ET| z>0k18>4rEi&cnAF=lE@VKKNDIly=ums~Lb9#MDj#V~DHHR?o5VkCfZ!5cN4Ah_CyO zTL??7Z|8%j>Gs~S^Rtv1b%UwMINFO +perl util\mk1mf.pl %OPTS% debug VC-WIN32 >d32.mak +perl util\mk1mf.pl %OPTS% VC-WIN32 >32.mak +perl util\mk1mf.pl %OPTS% debug dll VC-WIN32 >d32dll.mak +perl util\mk1mf.pl %OPTS% dll VC-WIN32 >32dll.mak +perl util\mkdef.pl 32 libeay > ms\libeay32.def +perl util\mkdef.pl 32 ssleay > ms\ssleay32.def + +nmake -f d32.mak +@if errorlevel 1 goto end +nmake -f 32.mak +@if errorlevel 1 goto end +nmake -f d32dll.mak +@if errorlevel 1 goto end +nmake -f 32dll.mak + +:end diff --git a/node-v0.8.14/deps/openssl/openssl/ms/README b/node-v0.8.14/deps/openssl/openssl/ms/README new file mode 100644 index 0000000..07f1925 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/ms/README @@ -0,0 +1,13 @@ +Run these makefiles from the top level as in +nmake -f ms\makefilename +to build with visual C++ 4.[01]. + +The results will be in the out directory. + +These makefiles and def files were generated by typing + +perl util\mk1mf.pl VC-NT >ms/nt.mak +perl util\mk1mf.pl VC-NT dll >ms/ntdll.mak + +perl util\mkdef.pl 32 crypto > ms/crypto32.def +perl util\mkdef.pl 32 ssl > ms/ssl32.def diff --git a/node-v0.8.14/deps/openssl/openssl/ms/applink.c b/node-v0.8.14/deps/openssl/openssl/ms/applink.c new file mode 100644 index 0000000..54a0a64 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/ms/applink.c @@ -0,0 +1,94 @@ +#define APPLINK_STDIN 1 +#define APPLINK_STDOUT 2 +#define APPLINK_STDERR 3 +#define APPLINK_FPRINTF 4 +#define APPLINK_FGETS 5 +#define APPLINK_FREAD 6 +#define APPLINK_FWRITE 7 +#define APPLINK_FSETMOD 8 +#define APPLINK_FEOF 9 +#define APPLINK_FCLOSE 10 /* should not be used */ + +#define APPLINK_FOPEN 11 /* solely for completeness */ +#define APPLINK_FSEEK 12 +#define APPLINK_FTELL 13 +#define APPLINK_FFLUSH 14 +#define APPLINK_FERROR 15 +#define APPLINK_CLEARERR 16 +#define APPLINK_FILENO 17 /* to be used with below */ + +#define APPLINK_OPEN 18 /* formally can't be used, as flags can vary */ +#define APPLINK_READ 19 +#define APPLINK_WRITE 20 +#define APPLINK_LSEEK 21 +#define APPLINK_CLOSE 22 +#define APPLINK_MAX 22 /* always same as last macro */ + +#ifndef APPMACROS_ONLY +#include +#include +#include + +static void *app_stdin(void) { return stdin; } +static void *app_stdout(void) { return stdout; } +static void *app_stderr(void) { return stderr; } +static int app_feof(FILE *fp) { return feof(fp); } +static int app_ferror(FILE *fp) { return ferror(fp); } +static void app_clearerr(FILE *fp) { clearerr(fp); } +static int app_fileno(FILE *fp) { return _fileno(fp); } +static int app_fsetmod(FILE *fp,char mod) +{ return _setmode (_fileno(fp),mod=='b'?_O_BINARY:_O_TEXT); } + +#ifdef __cplusplus +extern "C" { +#endif + +__declspec(dllexport) +void ** +#if defined(__BORLANDC__) +__stdcall /* __stdcall appears to be the only way to get the name + * decoration right with Borland C. Otherwise it works + * purely incidentally, as we pass no parameters. */ +#else +__cdecl +#endif +OPENSSL_Applink(void) +{ static int once=1; + static void *OPENSSL_ApplinkTable[APPLINK_MAX+1]={(void *)APPLINK_MAX}; + + if (once) + { OPENSSL_ApplinkTable[APPLINK_STDIN] = app_stdin; + OPENSSL_ApplinkTable[APPLINK_STDOUT] = app_stdout; + OPENSSL_ApplinkTable[APPLINK_STDERR] = app_stderr; + OPENSSL_ApplinkTable[APPLINK_FPRINTF] = fprintf; + OPENSSL_ApplinkTable[APPLINK_FGETS] = fgets; + OPENSSL_ApplinkTable[APPLINK_FREAD] = fread; + OPENSSL_ApplinkTable[APPLINK_FWRITE] = fwrite; + OPENSSL_ApplinkTable[APPLINK_FSETMOD] = app_fsetmod; + OPENSSL_ApplinkTable[APPLINK_FEOF] = app_feof; + OPENSSL_ApplinkTable[APPLINK_FCLOSE] = fclose; + + OPENSSL_ApplinkTable[APPLINK_FOPEN] = fopen; + OPENSSL_ApplinkTable[APPLINK_FSEEK] = fseek; + OPENSSL_ApplinkTable[APPLINK_FTELL] = ftell; + OPENSSL_ApplinkTable[APPLINK_FFLUSH] = fflush; + OPENSSL_ApplinkTable[APPLINK_FERROR] = app_ferror; + OPENSSL_ApplinkTable[APPLINK_CLEARERR] = app_clearerr; + OPENSSL_ApplinkTable[APPLINK_FILENO] = app_fileno; + + OPENSSL_ApplinkTable[APPLINK_OPEN] = _open; + OPENSSL_ApplinkTable[APPLINK_READ] = _read; + OPENSSL_ApplinkTable[APPLINK_WRITE] = _write; + OPENSSL_ApplinkTable[APPLINK_LSEEK] = _lseek; + OPENSSL_ApplinkTable[APPLINK_CLOSE] = _close; + + once = 0; + } + + return OPENSSL_ApplinkTable; +} + +#ifdef __cplusplus +} +#endif +#endif diff --git a/node-v0.8.14/deps/openssl/openssl/ms/bcb4.bat b/node-v0.8.14/deps/openssl/openssl/ms/bcb4.bat new file mode 100755 index 0000000..00fb9e8 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/ms/bcb4.bat @@ -0,0 +1,6 @@ +perl Configure BC-32 +perl util\mkfiles.pl > MINFO + +@rem create make file +perl util\mk1mf.pl no-asm BC-NT > bcb.mak + diff --git a/node-v0.8.14/deps/openssl/openssl/ms/certCA.srl b/node-v0.8.14/deps/openssl/openssl/ms/certCA.srl new file mode 100644 index 0000000..2cfaa3b --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/ms/certCA.srl @@ -0,0 +1 @@ +1D diff --git a/node-v0.8.14/deps/openssl/openssl/ms/certCA.ss b/node-v0.8.14/deps/openssl/openssl/ms/certCA.ss new file mode 100644 index 0000000..b48c657 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/ms/certCA.ss @@ -0,0 +1,10 @@ +-----BEGIN CERTIFICATE----- +MIIBXDCCAQYCAQAwDQYJKoZIhvcNAQEEBQAwOTELMAkGA1UEBhMCQVUxFzAVBgNV +BAoTDkRvZGd5IEJyb3RoZXJzMREwDwYDVQQDEwhEb2RneSBDQTAeFw05ODA3MjEw +NjUwMTZaFw05ODA4MjAwNjUwMTZaMDkxCzAJBgNVBAYTAkFVMRcwFQYDVQQKEw5E +b2RneSBCcm90aGVyczERMA8GA1UEAxMIRG9kZ3kgQ0EwXDANBgkqhkiG9w0BAQEF +AANLADBIAkEA0DQLenM/ncK6CwSEJhOO1WfZUPUEi4pvos9fHW459jh3rRDADgi3 +fiCYxoRVSQhvB47kDZ3ViNg5yrDhy7F9ywIDAQABMA0GCSqGSIb3DQEBBAUAA0EA +S564l3SBxJ+QcIXthGGDyP5zkxTf/1fHfelW9LNgu6lZTdy9Dlp/NecPekzRmZEM +WiGXGkKNeuo8PsnGJHP9Qg== +-----END CERTIFICATE----- diff --git a/node-v0.8.14/deps/openssl/openssl/ms/certU.ss b/node-v0.8.14/deps/openssl/openssl/ms/certU.ss new file mode 100644 index 0000000..095ea14 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/ms/certU.ss @@ -0,0 +1,10 @@ +-----BEGIN CERTIFICATE----- +MIIBcTCCARsCARwwDQYJKoZIhvcNAQEEBQAwOTELMAkGA1UEBhMCQVUxFzAVBgNV +BAoTDkRvZGd5IEJyb3RoZXJzMREwDwYDVQQDEwhEb2RneSBDQTAeFw05ODA3MjEw +NjUwMjdaFw05ODA4MjAwNjUwMjdaME4xCzAJBgNVBAYTAkFVMRcwFQYDVQQKEw5E +b2RneSBCcm90aGVyczESMBAGA1UEAxMJQnJvdGhlciAxMRIwEAYDVQQDEwlCcm90 +aGVyIDIwXDANBgkqhkiG9w0BAQEFAANLADBIAkEA0e4qorOr/zuLB9NvRaXhJVaI +HaGGasa7eMAjVPitWAXkN+DxXiGH1CnMgQraKiYzsEVP15xtxkevEvK5jJpOwwID +AQABMA0GCSqGSIb3DQEBBAUAA0EAZhcPV+SWwaszFuDTYc6fUurcV9OeXUqoxSQy +MnLZPTyWubHbbkUr9fUfdf7Cc7dFqGzag05VHkNQUS9VjMzjIQ== +-----END CERTIFICATE----- diff --git a/node-v0.8.14/deps/openssl/openssl/ms/cmp.pl b/node-v0.8.14/deps/openssl/openssl/ms/cmp.pl new file mode 100644 index 0000000..95b257f --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/ms/cmp.pl @@ -0,0 +1,47 @@ +#!/usr/local/bin/perl + +($#ARGV == 1) || die "usage: cmp.pl \n"; + +open(IN0,"<$ARGV[0]") || die "unable to open $ARGV[0]\n"; +open(IN1,"<$ARGV[1]") || die "unable to open $ARGV[1]\n"; +binmode IN0; +binmode IN1; + +$tot=0; +$ret=1; +for (;;) + { + $n1=sysread(IN0,$b1,4096); + $n2=sysread(IN1,$b2,4096); + + last if ($n1 != $n2); + last if ($b1 ne $b2); + last if ($n1 < 0); + if ($n1 == 0) + { + $ret=0; + last; + } + $tot+=$n1; + } + +close(IN0); +close(IN1); +if ($ret) + { + printf STDERR "$ARGV[0] and $ARGV[1] are different\n"; + @a1=unpack("C*",$b1); + @a2=unpack("C*",$b2); + for ($i=0; $i<=$#a1; $i++) + { + if ($a1[$i] ne $a2[$i]) + { + printf "%02X %02X <<\n",$a1[$i],$a2[$i]; + last; + } + } + $nm=$tot+$n1; + $tot+=$i+1; + printf STDERR "diff at char $tot of $nm\n"; + } +exit($ret); diff --git a/node-v0.8.14/deps/openssl/openssl/ms/do_ms.bat b/node-v0.8.14/deps/openssl/openssl/ms/do_ms.bat new file mode 100755 index 0000000..55014d3 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/ms/do_ms.bat @@ -0,0 +1,11 @@ + +perl util\mkfiles.pl >MINFO +perl util\mk1mf.pl no-asm VC-WIN32 >ms\nt.mak +perl util\mk1mf.pl dll no-asm VC-WIN32 >ms\ntdll.mak +if x%OSVERSION% == x goto skipce +perl util\mk1mf.pl no-asm VC-CE >ms\ce.mak +perl util\mk1mf.pl dll no-asm VC-CE >ms\cedll.mak +:skipce + +perl util\mkdef.pl 32 libeay > ms\libeay32.def +perl util\mkdef.pl 32 ssleay > ms\ssleay32.def diff --git a/node-v0.8.14/deps/openssl/openssl/ms/do_nasm.bat b/node-v0.8.14/deps/openssl/openssl/ms/do_nasm.bat new file mode 100755 index 0000000..7b3f3ed --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/ms/do_nasm.bat @@ -0,0 +1,8 @@ + +perl util\mkfiles.pl >MINFO +perl util\mk1mf.pl nasm VC-WIN32 >ms\nt.mak +perl util\mk1mf.pl dll nasm VC-WIN32 >ms\ntdll.mak +perl util\mk1mf.pl nasm BC-NT >ms\bcb.mak + +perl util\mkdef.pl 32 libeay > ms\libeay32.def +perl util\mkdef.pl 32 ssleay > ms\ssleay32.def diff --git a/node-v0.8.14/deps/openssl/openssl/ms/do_nt.bat b/node-v0.8.14/deps/openssl/openssl/ms/do_nt.bat new file mode 100755 index 0000000..e2d525e --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/ms/do_nt.bat @@ -0,0 +1,7 @@ + +perl util\mkfiles.pl >MINFO +perl util\mk1mf.pl no-asm VC-NT >ms\nt.mak +perl util\mk1mf.pl dll no-asm VC-NT >ms\ntdll.mak + +perl util\mkdef.pl libeay NT > ms\libeay32.def +perl util\mkdef.pl ssleay NT > ms\ssleay32.def diff --git a/node-v0.8.14/deps/openssl/openssl/ms/do_win64a.bat b/node-v0.8.14/deps/openssl/openssl/ms/do_win64a.bat new file mode 100755 index 0000000..495f1ea --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/ms/do_win64a.bat @@ -0,0 +1,9 @@ + +perl util\mkfiles.pl >MINFO +perl ms\uplink.pl win64a > ms\uptable.asm +ml64 -c -Foms\uptable.obj ms\uptable.asm +perl util\mk1mf.pl no-asm VC-WIN64A >ms\nt.mak +perl util\mk1mf.pl dll no-asm VC-WIN64A >ms\ntdll.mak + +perl util\mkdef.pl 32 libeay > ms\libeay32.def +perl util\mkdef.pl 32 ssleay > ms\ssleay32.def diff --git a/node-v0.8.14/deps/openssl/openssl/ms/do_win64i.bat b/node-v0.8.14/deps/openssl/openssl/ms/do_win64i.bat new file mode 100755 index 0000000..15ebcaa --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/ms/do_win64i.bat @@ -0,0 +1,9 @@ + +perl util\mkfiles.pl >MINFO +perl ms\uplink.pl win64i > ms\uptable.asm +ias -o ms\uptable.obj ms\uptable.asm +perl util\mk1mf.pl no-asm VC-WIN64I >ms\nt.mak +perl util\mk1mf.pl dll no-asm VC-WIN64I >ms\ntdll.mak + +perl util\mkdef.pl 32 libeay > ms\libeay32.def +perl util\mkdef.pl 32 ssleay > ms\ssleay32.def diff --git a/node-v0.8.14/deps/openssl/openssl/ms/keyCA.ss b/node-v0.8.14/deps/openssl/openssl/ms/keyCA.ss new file mode 100644 index 0000000..933c2cd --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/ms/keyCA.ss @@ -0,0 +1,9 @@ +-----BEGIN RSA PRIVATE KEY----- +MIIBOwIBAAJBANA0C3pzP53CugsEhCYTjtVn2VD1BIuKb6LPXx1uOfY4d60QwA4I +t34gmMaEVUkIbweO5A2d1YjYOcqw4cuxfcsCAwEAAQJAOT9WOKEfyN0WEpl3TJDs +ITmgw2XbjhLOh1HFsW3xegWlaOuhL/wGamz7n7zzL/RQF3JP/VvpGk2F8VD9JhwT +wQIhAPmqM3fLttBoCQuwQRdIPfB7Ps3THqx6N8AJ04z3I1ejAiEA1XyDd7bLpWrw +/oA8CmR4b/KCGfvRwAL/Qej/rQliw7kCIQCYRzSvO8ScpuflhjKdZcXJuRJcbgnG +f6Ejc5rh3xdiawIhALMmLdzEFNjXiSzIx5mg/kBTLUJIw5dx7GqO8B9xBORhAiA5 +oTN/hgvvrkkmRsHQpNBmzAEGBzhMEEq9lD6ZWrTSRg== +-----END RSA PRIVATE KEY----- diff --git a/node-v0.8.14/deps/openssl/openssl/ms/keyU.ss b/node-v0.8.14/deps/openssl/openssl/ms/keyU.ss new file mode 100644 index 0000000..05d356e --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/ms/keyU.ss @@ -0,0 +1,9 @@ +-----BEGIN RSA PRIVATE KEY----- +MIIBPAIBAAJBANHuKqKzq/87iwfTb0Wl4SVWiB2hhmrGu3jAI1T4rVgF5Dfg8V4h +h9QpzIEK2iomM7BFT9ecbcZHrxLyuYyaTsMCAwEAAQJBAIxtM6n4ZCJscxj+D13Y +k13Fn3Gqvd6pJ3ijlj7dxh6tRBBQ3W9qmQflyvEc81giI2XtbVYBOEJKtJ1cWWZm +gAkCIQDpEoOuc4KCI5ti6aMJvtxlXWNHbkXCxtbeIjH4+FnH9QIhAOaU3XVeWWOK +PnnO87KniDjHQqWLnooivDGRK+FUKeDXAiEA2MjEvFVqFVvDIsxHPkBNROcI+Z6i +ulkx76kErBtrfqUCIHN5uBLQZmngUPuFtiwRlLoCqJDphENfs+oK7vPQx4xPAiEA +hnY2Ulrpld83IG6bUs95Loc8Fk81hez5YwmhsFEXVtk= +-----END RSA PRIVATE KEY----- diff --git a/node-v0.8.14/deps/openssl/openssl/ms/mingw32.bat b/node-v0.8.14/deps/openssl/openssl/ms/mingw32.bat new file mode 100644 index 0000000..06b5733 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/ms/mingw32.bat @@ -0,0 +1,90 @@ +@rem OpenSSL with Mingw32+GNU as +@rem --------------------------- + +perl Configure mingw %1 %2 %3 %4 %5 %6 %7 %8 + +@echo off + +perl -e "exit 1 if '%1' eq 'no-asm'" +if errorlevel 1 goto noasm + +echo Generating x86 for GNU assember + +echo Bignum +cd crypto\bn\asm +perl bn-586.pl gaswin > bn-win32.s +perl co-586.pl gaswin > co-win32.s +cd ..\..\.. + +echo DES +cd crypto\des\asm +perl des-586.pl gaswin > d-win32.s +cd ..\..\.. + +echo crypt +cd crypto\des\asm +perl crypt586.pl gaswin > y-win32.s +cd ..\..\.. + +echo Blowfish +cd crypto\bf\asm +perl bf-586.pl gaswin > b-win32.s +cd ..\..\.. + +echo CAST5 +cd crypto\cast\asm +perl cast-586.pl gaswin > c-win32.s +cd ..\..\.. + +echo RC4 +cd crypto\rc4\asm +perl rc4-586.pl gaswin > r4-win32.s +cd ..\..\.. + +echo MD5 +cd crypto\md5\asm +perl md5-586.pl gaswin > m5-win32.s +cd ..\..\.. + +echo SHA1 +cd crypto\sha\asm +perl sha1-586.pl gaswin > s1-win32.s +cd ..\..\.. + +echo RIPEMD160 +cd crypto\ripemd\asm +perl rmd-586.pl gaswin > rm-win32.s +cd ..\..\.. + +echo RC5\32 +cd crypto\rc5\asm +perl rc5-586.pl gaswin > r5-win32.s +cd ..\..\.. + +:noasm + +echo Generating makefile +perl util\mkfiles.pl >MINFO +perl util\mk1mf.pl gaswin Mingw32 >ms\mingw32a.mak +echo Generating DLL definition files +perl util\mkdef.pl 32 libeay >ms\libeay32.def +if errorlevel 1 goto end +perl util\mkdef.pl 32 ssleay >ms\ssleay32.def +if errorlevel 1 goto end + +rem copy ms\tlhelp32.h outinc + +echo Building the libraries +mingw32-make -f ms/mingw32a.mak +if errorlevel 1 goto end + +echo Generating the DLLs and input libraries +dllwrap --dllname libeay32.dll --output-lib out/libeay32.a --def ms/libeay32.def out/libcrypto.a -lws2_32 -lgdi32 +if errorlevel 1 goto end +dllwrap --dllname libssl32.dll --output-lib out/libssl32.a --def ms/ssleay32.def out/libssl.a out/libeay32.a +if errorlevel 1 goto end + +echo Done compiling OpenSSL + +:end + diff --git a/node-v0.8.14/deps/openssl/openssl/ms/mw.bat b/node-v0.8.14/deps/openssl/openssl/ms/mw.bat new file mode 100644 index 0000000..35e00a4 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/ms/mw.bat @@ -0,0 +1,26 @@ +@rem OpenSSL with Mingw32 +@rem -------------------- + +@rem Makefile +perl util\mkfiles.pl >MINFO +perl util\mk1mf.pl Mingw32 >ms\mingw32.mak +@rem DLL definition files +perl util\mkdef.pl 32 libeay >ms\libeay32.def +if errorlevel 1 goto end +perl util\mkdef.pl 32 ssleay >ms\ssleay32.def +if errorlevel 1 goto end + +@rem Build the libraries +make -f ms/mingw32.mak +if errorlevel 1 goto end + +@rem Generate the DLLs and input libraries +dllwrap --dllname libeay32.dll --output-lib out/libeay32.a --def ms/libeay32.def out/libcrypto.a -lws2_32 -lgdi32 +if errorlevel 1 goto end +dllwrap --dllname libssl32.dll --output-lib out/libssl32.a --def ms/ssleay32.def out/libssl.a out/libeay32.a +if errorlevel 1 goto end + +echo Done compiling OpenSSL + +:end + diff --git a/node-v0.8.14/deps/openssl/openssl/ms/req2CA.ss b/node-v0.8.14/deps/openssl/openssl/ms/req2CA.ss new file mode 100644 index 0000000..d061fb2 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/ms/req2CA.ss @@ -0,0 +1,29 @@ +Certificate Request: + Data: + Version: 0 (0x0) + Subject: C=AU, O=Dodgy Brothers, CN=Dodgy CA + Subject Public Key Info: + Public Key Algorithm: rsaEncryption + RSA Public Key: (512 bit) + Modulus (512 bit): + 00:d0:34:0b:7a:73:3f:9d:c2:ba:0b:04:84:26:13: + 8e:d5:67:d9:50:f5:04:8b:8a:6f:a2:cf:5f:1d:6e: + 39:f6:38:77:ad:10:c0:0e:08:b7:7e:20:98:c6:84: + 55:49:08:6f:07:8e:e4:0d:9d:d5:88:d8:39:ca:b0: + e1:cb:b1:7d:cb + Exponent: 65537 (0x10001) + Attributes: + a0:00 + Signature Algorithm: md5WithRSAEncryption + 8d:15:e6:8e:49:0f:07:fb:e0:72:ad:f0:04:9a:c8:5d:e7:1b: + ed:99:c9:c3:3c:f5:8e:4d:a1:5e:e1:40:75:2c:24:f0:c6:dd: + 10:87:35:26:1d:cc:79:3f:a2:c6:a0:04:c8:52:78:ed:26:32: + d3:1b:a7:cd:5e:8c:55:92:dd:88 +-----BEGIN CERTIFICATE REQUEST----- +MIHzMIGeAgEAMDkxCzAJBgNVBAYTAkFVMRcwFQYDVQQKEw5Eb2RneSBCcm90aGVy +czERMA8GA1UEAxMIRG9kZ3kgQ0EwXDANBgkqhkiG9w0BAQEFAANLADBIAkEA0DQL +enM/ncK6CwSEJhOO1WfZUPUEi4pvos9fHW459jh3rRDADgi3fiCYxoRVSQhvB47k +DZ3ViNg5yrDhy7F9ywIDAQABoAAwDQYJKoZIhvcNAQEEBQADQQCNFeaOSQ8H++By +rfAEmshd5xvtmcnDPPWOTaFe4UB1LCTwxt0QhzUmHcx5P6LGoATIUnjtJjLTG6fN +XoxVkt2I +-----END CERTIFICATE REQUEST----- diff --git a/node-v0.8.14/deps/openssl/openssl/ms/reqCA.ss b/node-v0.8.14/deps/openssl/openssl/ms/reqCA.ss new file mode 100644 index 0000000..1f7138c --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/ms/reqCA.ss @@ -0,0 +1,8 @@ +-----BEGIN CERTIFICATE REQUEST----- +MIHzMIGeAgEAMDkxCzAJBgNVBAYTAkFVMRcwFQYDVQQKEw5Eb2RneSBCcm90aGVy +czERMA8GA1UEAxMIRG9kZ3kgQ0EwXDANBgkqhkiG9w0BAQEFAANLADBIAkEA0DQL +enM/ncK6CwSEJhOO1WfZUPUEi4pvos9fHW459jh3rRDADgi3fiCYxoRVSQhvB47k +DZ3ViNg5yrDhy7F9ywIDAQABoAAwDQYJKoZIhvcNAQEFBQADQQA5DZSZgDXs8flG +GZf4SGr8QpqkxSu9bZOYp/ySuz1khj7aupBrvZBmqZcZx4ZjAUN7UQpMWu2gyfKa +mAiiLPFN +-----END CERTIFICATE REQUEST----- diff --git a/node-v0.8.14/deps/openssl/openssl/ms/reqU.ss b/node-v0.8.14/deps/openssl/openssl/ms/reqU.ss new file mode 100644 index 0000000..91cce59 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/ms/reqU.ss @@ -0,0 +1,8 @@ +-----BEGIN CERTIFICATE REQUEST----- +MIIBCDCBswIBADBOMQswCQYDVQQGEwJBVTEXMBUGA1UEChMORG9kZ3kgQnJvdGhl +cnMxEjAQBgNVBAMTCUJyb3RoZXIgMTESMBAGA1UEAxMJQnJvdGhlciAyMFwwDQYJ +KoZIhvcNAQEBBQADSwAwSAJBANHuKqKzq/87iwfTb0Wl4SVWiB2hhmrGu3jAI1T4 +rVgF5Dfg8V4hh9QpzIEK2iomM7BFT9ecbcZHrxLyuYyaTsMCAwEAAaAAMA0GCSqG +SIb3DQEBAgUAA0EAhB0p6LbiVq+XshLo5sBQN0rsROC1OgWrdS6ZUmMaigOKK069 +r1o+dGwbM5VCYGTZf0PW9OtGuArGct0laL5h4w== +-----END CERTIFICATE REQUEST----- diff --git a/node-v0.8.14/deps/openssl/openssl/ms/speed32.bat b/node-v0.8.14/deps/openssl/openssl/ms/speed32.bat new file mode 100755 index 0000000..95f7ce9 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/ms/speed32.bat @@ -0,0 +1,37 @@ +set makefile=ms\nt.mak + +perl Configure b +del tmp\*.obj +nmake -f %makefile% +nmake -f %makefile% +nmake -f %makefile% +out\ssleay version -v -b -f >speed.1 +out\ssleay speed >speed.1l + +perl Configure bl-4c-2c +del tmp\rc4*.obj tmp\bn*.obj tmp\md2_dgst.obj +nmake -f %makefile% +nmake -f %makefile% +nmake -f %makefile% +out\ssleay speed rc4 rsa md2 >speed.2l + +perl Configure bl-4c-ri +del tmp\rc4*.obj +nmake -f %makefile% +nmake -f %makefile% +nmake -f %makefile% +out\ssleay speed rc4 >speed.3l + +perl Configure b2-is-ri-dp +del tmp\i_*.obj tmp\rc4*.obj tmp\ecb_enc.obj tmp\bn*.obj +nmake -f %makefile% +nmake -f %makefile% +nmake -f %makefile% +out\ssleay speed rsa rc4 idea des >speed.4l + +type speed.1 >speed.log +type speed.1l >>speed.log +perl util\sp-diff.pl speed.1l speed.2l >>speed.log +perl util\sp-diff.pl speed.1l speed.3l >>speed.log +perl util\sp-diff.pl speed.1l speed.4l >>speed.log + diff --git a/node-v0.8.14/deps/openssl/openssl/ms/tenc.bat b/node-v0.8.14/deps/openssl/openssl/ms/tenc.bat new file mode 100755 index 0000000..a4fa7f3 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/ms/tenc.bat @@ -0,0 +1,14 @@ +rem called by testenc + +echo test %1 %2 %3 %4 %5 %6 +%ssleay% %1 %2 %3 %4 %5 %6 -e -bufsize 113 -k test -in %input% -out %tmp1% +%ssleay% %1 %2 %3 %4 %5 %6 -d -bufsize 157 -k test -in %tmp1% -out %out1% +%cmp% %input% %out1% +if errorlevel 1 goto err + +echo test base64 %1 %2 %3 %4 %5 %6 +%ssleay% %1 %2 %3 %4 %5 %6 -a -e -bufsize 113 -k test -in %input% -out %tmp1% +%ssleay% %1 %2 %3 %4 %5 %6 -a -d -bufsize 157 -k test -in %tmp1% -out %out1% +%cmp% %input% %out1% + +:err diff --git a/node-v0.8.14/deps/openssl/openssl/ms/tencce.bat b/node-v0.8.14/deps/openssl/openssl/ms/tencce.bat new file mode 100644 index 0000000..c8b1acd --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/ms/tencce.bat @@ -0,0 +1,19 @@ +rem called by testencce + +echo test %1 %2 %3 %4 %5 %6 +cecopy %input% CE:\OpenSSL +cerun CE:\OpenSSL\%ssleay% %1 %2 %3 %4 %5 %6 -e -bufsize 113 -k test -in \OpenSSL\%input% -out \OpenSSL\%tmp1% +cerun CE:\OpenSSL\%ssleay% %1 %2 %3 %4 %5 %6 -d -bufsize 157 -k test -in \OpenSSL\%tmp1% -out \OpenSSL\%out1% +del %out1% >nul 2>&1 +cecopy CE:\OpenSSL\%out1% . +%cmp% %input% %out1% +if errorlevel 1 goto err + +echo test base64 %1 %2 %3 %4 %5 %6 +cerun CE:\OpenSSL\%ssleay% %1 %2 %3 %4 %5 %6 -a -e -bufsize 113 -k test -in \OpenSSL\%input% -out \OpenSSL\%tmp1% +cerun CE:\OpenSSL\%ssleay% %1 %2 %3 %4 %5 %6 -a -d -bufsize 157 -k test -in \OpenSSL\%tmp1% -out \OpenSSL\%out1% +del %out1% >nul 2>&1 +cecopy CE:\OpenSSL\%out1% . +%cmp% %input% %out1% + +:err diff --git a/node-v0.8.14/deps/openssl/openssl/ms/test.bat b/node-v0.8.14/deps/openssl/openssl/ms/test.bat new file mode 100755 index 0000000..f490546 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/ms/test.bat @@ -0,0 +1,185 @@ +@echo off + +set test=..\ms +set opath=%PATH% +PATH=..\ms;%PATH% +set OPENSSL_CONF=..\apps\openssl.cnf + +rem run this from inside the bin directory + +echo rsa_test +rsa_test +if errorlevel 1 goto done + +echo destest +destest +if errorlevel 1 goto done + +echo ideatest +ideatest +if errorlevel 1 goto done + +echo bftest +bftest +if errorlevel 1 goto done + +echo shatest +shatest +if errorlevel 1 goto done + +echo sha1test +sha1test +if errorlevel 1 goto done + +echo md5test +md5test +if errorlevel 1 goto done + +echo rc2test +rc2test +if errorlevel 1 goto done + +echo rc4test +rc4test +if errorlevel 1 goto done + +echo randtest +randtest +if errorlevel 1 goto done + +echo dhtest +dhtest +if errorlevel 1 goto done + +echo exptest +exptest +if errorlevel 1 goto done + +echo dsatest +dsatest +if errorlevel 1 goto done + +echo ectest +ectest +if errorlevel 1 goto done + +echo testenc +call %test%\testenc openssl +if errorlevel 1 goto done + +echo testpem +call %test%\testpem openssl +if errorlevel 1 goto done + +echo testss +call %test%\testss openssl +if errorlevel 1 goto done + +set SSL_TEST=ssltest -key keyU.ss -cert certU.ss -c_key keyU.ss -c_cert certU.ss -CAfile certCA.ss + +echo test sslv2 +ssltest -ssl2 +if errorlevel 1 goto done + +echo test sslv2 with server authentication +%SSL_TEST% -ssl2 -server_auth +if errorlevel 1 goto done + +echo test sslv2 with client authentication +%SSL_TEST% -ssl2 -client_auth +if errorlevel 1 goto done + +echo test sslv2 with both client and server authentication +%SSL_TEST% -ssl2 -server_auth -client_auth +if errorlevel 1 goto done + +echo test sslv3 +ssltest -ssl3 +if errorlevel 1 goto done + +echo test sslv3 with server authentication +%SSL_TEST% -ssl3 -server_auth +if errorlevel 1 goto done + +echo test sslv3 with client authentication +%SSL_TEST% -ssl3 -client_auth +if errorlevel 1 goto done + +echo test sslv3 with both client and server authentication +%SSL_TEST% -ssl3 -server_auth -client_auth +if errorlevel 1 goto done + +echo test sslv2/sslv3 +ssltest +if errorlevel 1 goto done + +echo test sslv2/sslv3 with server authentication +%SSL_TEST% -server_auth +if errorlevel 1 goto done + +echo test sslv2/sslv3 with client authentication +%SSL_TEST% -client_auth +if errorlevel 1 goto done + +echo test sslv2/sslv3 with both client and server authentication +%SSL_TEST% -server_auth -client_auth +if errorlevel 1 goto done + +echo test sslv2 via BIO pair +ssltest -bio_pair -ssl2 +if errorlevel 1 goto done + +echo test sslv2/sslv3 with 1024 bit DHE via BIO pair +ssltest -bio_pair -dhe1024dsa -v +if errorlevel 1 goto done + +echo test sslv2 with server authentication via BIO pair +%SSL_TEST% -bio_pair -ssl2 -server_auth +if errorlevel 1 goto done + +echo test sslv2 with client authentication via BIO pair +%SSL_TEST% -bio_pair -ssl2 -client_auth +if errorlevel 1 goto done + +echo test sslv2 with both client and server authentication via BIO pair +%SSL_TEST% -bio_pair -ssl2 -server_auth -client_auth +if errorlevel 1 goto done + +echo test sslv3 via BIO pair +ssltest -bio_pair -ssl3 +if errorlevel 1 goto done + +echo test sslv3 with server authentication via BIO pair +%SSL_TEST% -bio_pair -ssl3 -server_auth +if errorlevel 1 goto done + +echo test sslv3 with client authentication via BIO pair +%SSL_TEST% -bio_pair -ssl3 -client_auth +if errorlevel 1 goto done + +echo test sslv3 with both client and server authentication via BIO pair +%SSL_TEST% -bio_pair -ssl3 -server_auth -client_auth +if errorlevel 1 goto done + +echo test sslv2/sslv3 via BIO pair +ssltest -bio_pair +if errorlevel 1 goto done + +echo test sslv2/sslv3 with server authentication +%SSL_TEST% -bio_pair -server_auth +if errorlevel 1 goto done + +echo test sslv2/sslv3 with client authentication via BIO pair +%SSL_TEST% -bio_pair -client_auth +if errorlevel 1 goto done + +echo test sslv2/sslv3 with both client and server authentication via BIO pair +%SSL_TEST% -bio_pair -server_auth -client_auth +if errorlevel 1 goto done + +echo passed all tests +goto end +:done +echo problems..... +:end +PATH=%opath% diff --git a/node-v0.8.14/deps/openssl/openssl/ms/testce.bat b/node-v0.8.14/deps/openssl/openssl/ms/testce.bat new file mode 100644 index 0000000..2ab010b --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/ms/testce.bat @@ -0,0 +1,234 @@ +@echo off + +cemkdir CE:\OpenSSL + +set test=..\ms +set opath=%PATH% +PATH=..\ms;%PATH% +cecopy ..\apps\openssl.cnf CE:\OpenSSL +set OPENSSL_CONF=\OpenSSL\openssl.cnf +set HOME=\OpenSSL +set CERUN_PASS_ENV=OPENSSL_CONF HOME + +rem run this from inside the bin directory + +rem Copy the DLL's (though they'll only exist if we're in out32dll) +if exist libeay32.dll cecopy libeay32.dll CE:\OpenSSL +if exist ssleay32.dll cecopy ssleay32.dll CE:\OpenSSL + +echo rsa_test +call %test%\testce2 rsa_test +if errorlevel 1 goto done + +echo destest +call %test%\testce2 destest +if errorlevel 1 goto done + +echo ideatest +call %test%\testce2 ideatest +if errorlevel 1 goto done + +echo bftest +call %test%\testce2 bftest +if errorlevel 1 goto done + +echo shatest +call %test%\testce2 shatest +if errorlevel 1 goto done + +echo sha1test +call %test%\testce2 sha1test +if errorlevel 1 goto done + +echo md5test +call %test%\testce2 md5test +if errorlevel 1 goto done + +echo md2test +call %test%\testce2 md2test +if errorlevel 1 goto done + +echo mdc2test +call %test%\testce2 mdc2test +if errorlevel 1 goto done + +echo rc2test +call %test%\testce2 rc2test +if errorlevel 1 goto done + +echo rc4test +call %test%\testce2 rc4test +if errorlevel 1 goto done + +echo randtest +call %test%\testce2 randtest +if errorlevel 1 goto done + +echo dhtest +call %test%\testce2 dhtest +if errorlevel 1 goto done + +echo exptest +call %test%\testce2 exptest +if errorlevel 1 goto done + +echo dsatest +call %test%\testce2 dsatest +if errorlevel 1 goto done + +echo testenc +call %test%\testencce openssl.exe +if errorlevel 1 goto done + +echo testpem +call %test%\testpemce openssl.exe +if errorlevel 1 goto done + +cecopy openssl.exe CE:\OpenSSL + +echo verify +copy ..\certs\*.pem cert.tmp >nul +cecopy cert.tmp CE:\OpenSSL +cemkdir CE:\OpenSSL\certs +rem cecopy ..\certs\*.pem CE:\OpenSSL\certs +cecopy ..\certs\ca-cert.pem CE:\OpenSSL\certs +cecopy ..\certs\dsa-ca.pem CE:\OpenSSL\certs +cecopy ..\certs\dsa-pca.pem CE:\OpenSSL\certs +cecopy ..\certs\factory.pem CE:\OpenSSL\certs +cecopy ..\certs\ICE-CA.pem CE:\OpenSSL\certs +cecopy ..\certs\ICE-root.pem CE:\OpenSSL\certs +cecopy ..\certs\ICE-user.pem CE:\OpenSSL\certs +cecopy ..\certs\nortelCA.pem CE:\OpenSSL\certs +cecopy ..\certs\pca-cert.pem CE:\OpenSSL\certs +cecopy ..\certs\RegTP-4R.pem CE:\OpenSSL\certs +cecopy ..\certs\RegTP-5R.pem CE:\OpenSSL\certs +cecopy ..\certs\RegTP-6R.pem CE:\OpenSSL\certs +cecopy ..\certs\rsa-cca.pem CE:\OpenSSL\certs +cecopy ..\certs\thawteCb.pem CE:\OpenSSL\certs +cecopy ..\certs\thawteCp.pem CE:\OpenSSL\certs +cecopy ..\certs\timCA.pem CE:\OpenSSL\certs +cecopy ..\certs\tjhCA.pem CE:\OpenSSL\certs +cecopy ..\certs\vsign1.pem CE:\OpenSSL\certs +cecopy ..\certs\vsign2.pem CE:\OpenSSL\certs +cecopy ..\certs\vsign3.pem CE:\OpenSSL\certs +cecopy ..\certs\vsignss.pem CE:\OpenSSL\certs +cecopy ..\certs\vsigntca.pem CE:\OpenSSL\certs +cerun CE:\OpenSSL\openssl verify -CAfile \OpenSSL\cert.tmp \OpenSSL\certs\*.pem + +echo testss +call %test%\testssce openssl.exe +if errorlevel 1 goto done + +cecopy ssltest.exe CE:\OpenSSL +cecopy ..\apps\server.pem CE:\OpenSSL +cecopy ..\apps\client.pem CE:\OpenSSL + +echo test sslv2 +cerun CE:\OpenSSL\ssltest -ssl2 +if errorlevel 1 goto done + +echo test sslv2 with server authentication +cerun CE:\OpenSSL\ssltest -ssl2 -server_auth -CAfile \OpenSSL\cert.tmp +if errorlevel 1 goto done + +echo test sslv2 with client authentication +cerun CE:\OpenSSL\ssltest -ssl2 -client_auth -CAfile \OpenSSL\cert.tmp +if errorlevel 1 goto done + +echo test sslv2 with both client and server authentication +cerun CE:\OpenSSL\ssltest -ssl2 -server_auth -client_auth -CAfile \OpenSSL\cert.tmp +if errorlevel 1 goto done + +echo test sslv3 +cerun CE:\OpenSSL\ssltest -ssl3 +if errorlevel 1 goto done + +echo test sslv3 with server authentication +cerun CE:\OpenSSL\ssltest -ssl3 -server_auth -CAfile \OpenSSL\cert.tmp +if errorlevel 1 goto done + +echo test sslv3 with client authentication +cerun CE:\OpenSSL\ssltest -ssl3 -client_auth -CAfile \OpenSSL\cert.tmp +if errorlevel 1 goto done + +echo test sslv3 with both client and server authentication +cerun CE:\OpenSSL\ssltest -ssl3 -server_auth -client_auth -CAfile \OpenSSL\cert.tmp +if errorlevel 1 goto done + +echo test sslv2/sslv3 +cerun CE:\OpenSSL\ssltest +if errorlevel 1 goto done + +echo test sslv2/sslv3 with server authentication +cerun CE:\OpenSSL\ssltest -server_auth -CAfile \OpenSSL\cert.tmp +if errorlevel 1 goto done + +echo test sslv2/sslv3 with client authentication +cerun CE:\OpenSSL\ssltest -client_auth -CAfile \OpenSSL\cert.tmp +if errorlevel 1 goto done + +echo test sslv2/sslv3 with both client and server authentication +cerun CE:\OpenSSL\ssltest -server_auth -client_auth -CAfile \OpenSSL\cert.tmp +if errorlevel 1 goto done + +echo test sslv2 via BIO pair +cerun CE:\OpenSSL\ssltest -bio_pair -ssl2 +if errorlevel 1 goto done + +echo test sslv2/sslv3 with 1024 bit DHE via BIO pair +cerun CE:\OpenSSL\ssltest -bio_pair -dhe1024dsa -v +if errorlevel 1 goto done + +echo test sslv2 with server authentication via BIO pair +cerun CE:\OpenSSL\ssltest -bio_pair -ssl2 -server_auth -CAfile \OpenSSL\cert.tmp +if errorlevel 1 goto done + +echo test sslv2 with client authentication via BIO pair +cerun CE:\OpenSSL\ssltest -bio_pair -ssl2 -client_auth -CAfile \OpenSSL\cert.tmp +if errorlevel 1 goto done + +echo test sslv2 with both client and server authentication via BIO pair +cerun CE:\OpenSSL\ssltest -bio_pair -ssl2 -server_auth -client_auth -CAfile \OpenSSL\cert.tmp +if errorlevel 1 goto done + +echo test sslv3 via BIO pair +cerun CE:\OpenSSL\ssltest -bio_pair -ssl3 +if errorlevel 1 goto done + +echo test sslv3 with server authentication via BIO pair +cerun CE:\OpenSSL\ssltest -bio_pair -ssl3 -server_auth -CAfile \OpenSSL\cert.tmp +if errorlevel 1 goto done + +echo test sslv3 with client authentication via BIO pair +cerun CE:\OpenSSL\ssltest -bio_pair -ssl3 -client_auth -CAfile \OpenSSL\cert.tmp +if errorlevel 1 goto done + +echo test sslv3 with both client and server authentication via BIO pair +cerun CE:\OpenSSL\ssltest -bio_pair -ssl3 -server_auth -client_auth -CAfile \OpenSSL\cert.tmp +if errorlevel 1 goto done + +echo test sslv2/sslv3 via BIO pair +cerun CE:\OpenSSL\ssltest +if errorlevel 1 goto done + +echo test sslv2/sslv3 with server authentication +cerun CE:\OpenSSL\ssltest -bio_pair -server_auth -CAfile \OpenSSL\cert.tmp +if errorlevel 1 goto done + +echo test sslv2/sslv3 with client authentication via BIO pair +cerun CE:\OpenSSL\ssltest -bio_pair -client_auth -CAfile \OpenSSL\cert.tmp +if errorlevel 1 goto done + +echo test sslv2/sslv3 with both client and server authentication via BIO pair +cerun CE:\OpenSSL\ssltest -bio_pair -server_auth -client_auth -CAfile \OpenSSL\cert.tmp +if errorlevel 1 goto done + +del cert.tmp + +echo passed all tests +goto end +:done +echo problems..... +:end +PATH=%opath% + diff --git a/node-v0.8.14/deps/openssl/openssl/ms/testce2.bat b/node-v0.8.14/deps/openssl/openssl/ms/testce2.bat new file mode 100644 index 0000000..24265b9 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/ms/testce2.bat @@ -0,0 +1,2 @@ +cecopy %1.exe CE:\OpenSSL +cerun CE:\OpenSSL\%1 %2 %3 %4 %5 %6 %7 %8 %9 diff --git a/node-v0.8.14/deps/openssl/openssl/ms/testenc.bat b/node-v0.8.14/deps/openssl/openssl/ms/testenc.bat new file mode 100755 index 0000000..f8e9093 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/ms/testenc.bat @@ -0,0 +1,94 @@ +@echo off +echo start testenc + +path=..\ms;%path% +set ssleay=%1% +set input=..\ms\testenc.bat +set tmp1=..\ms\cipher.out +set out1=..\ms\clear.out +set cmp=perl ..\ms\cmp.pl + +cd +call tenc.bat enc +if errorlevel 1 goto err + +call tenc.bat rc4 +if errorlevel 1 goto err + +call tenc.bat des-cfb +if errorlevel 1 goto err + +call tenc.bat des-ede-cfb +if errorlevel 1 goto err + +call tenc.bat des-ede3-cfb +if errorlevel 1 goto err + +call tenc.bat des-ofb +if errorlevel 1 goto err + +call tenc.bat des-ede-ofb +if errorlevel 1 goto err + +call tenc.bat des-ede3-ofb +if errorlevel 1 goto err + +call tenc.bat des-ecb +if errorlevel 1 goto err + +call tenc.bat des-ede +if errorlevel 1 goto err + +call tenc.bat des-ede3 +if errorlevel 1 goto err + +call tenc.bat des-cbc +if errorlevel 1 goto err + +call tenc.bat des-ede-cbc +if errorlevel 1 goto err + +call tenc.bat des-ede3-cbc +if errorlevel 1 goto err + +call tenc.bat idea-ecb +if errorlevel 1 goto err + +call tenc.bat idea-cfb +if errorlevel 1 goto err + +call tenc.bat idea-ofb +if errorlevel 1 goto err + +call tenc.bat idea-cbc +if errorlevel 1 goto err + +call tenc.bat rc2-ecb +if errorlevel 1 goto err + +call tenc.bat rc2-cfb +if errorlevel 1 goto err + +call tenc.bat rc2-ofb +if errorlevel 1 goto err + +call tenc.bat rc2-cbc +if errorlevel 1 goto err + +call tenc.bat bf-ecb +if errorlevel 1 goto err + +call tenc.bat bf-cfb +if errorlevel 1 goto err + +call tenc.bat bf-ofb +if errorlevel 1 goto err + +call tenc.bat bf-cbc +if errorlevel 1 goto err + +echo OK +del %out1% +del %tmp1% +:err + diff --git a/node-v0.8.14/deps/openssl/openssl/ms/testencce.bat b/node-v0.8.14/deps/openssl/openssl/ms/testencce.bat new file mode 100644 index 0000000..1da3e08 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/ms/testencce.bat @@ -0,0 +1,97 @@ +@echo off +echo start testenc + +path=..\ms;%path% +set ssleay=%1% +copy ..\ms\testenc.bat >nul +set input=testenc.bat +set tmp1=cipher.out +set out1=clear.out +set cmp=perl ..\ms\cmp.pl + +cecopy %ssleay% CE:\OpenSSL + +cd +call tencce.bat enc +if errorlevel 1 goto err + +call tencce.bat rc4 +if errorlevel 1 goto err + +call tencce.bat des-cfb +if errorlevel 1 goto err + +call tencce.bat des-ede-cfb +if errorlevel 1 goto err + +call tencce.bat des-ede3-cfb +if errorlevel 1 goto err + +call tencce.bat des-ofb +if errorlevel 1 goto err + +call tencce.bat des-ede-ofb +if errorlevel 1 goto err + +call tencce.bat des-ede3-ofb +if errorlevel 1 goto err + +call tencce.bat des-ecb +if errorlevel 1 goto err + +call tencce.bat des-ede +if errorlevel 1 goto err + +call tencce.bat des-ede3 +if errorlevel 1 goto err + +call tencce.bat des-cbc +if errorlevel 1 goto err + +call tencce.bat des-ede-cbc +if errorlevel 1 goto err + +call tencce.bat des-ede3-cbc +if errorlevel 1 goto err + +call tencce.bat idea-ecb +if errorlevel 1 goto err + +call tencce.bat idea-cfb +if errorlevel 1 goto err + +call tencce.bat idea-ofb +if errorlevel 1 goto err + +call tencce.bat idea-cbc +if errorlevel 1 goto err + +call tencce.bat rc2-ecb +if errorlevel 1 goto err + +call tencce.bat rc2-cfb +if errorlevel 1 goto err + +call tencce.bat rc2-ofb +if errorlevel 1 goto err + +call tencce.bat rc2-cbc +if errorlevel 1 goto err + +call tencce.bat bf-ecb +if errorlevel 1 goto err + +call tencce.bat bf-cfb +if errorlevel 1 goto err + +call tencce.bat bf-ofb +if errorlevel 1 goto err + +call tencce.bat bf-cbc +if errorlevel 1 goto err + +echo OK +del %out1% >nul 2>&1 +del %tmp1% >nul 2>&1 +:err + diff --git a/node-v0.8.14/deps/openssl/openssl/ms/testpem.bat b/node-v0.8.14/deps/openssl/openssl/ms/testpem.bat new file mode 100755 index 0000000..8b2e844 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/ms/testpem.bat @@ -0,0 +1,32 @@ +@echo off +set ssleay=%1% +set tmp1=pem.out +set cmp=fc.exe + +call tpem.bat crl ..\test\testcrl.pem +if errorlevel 1 goto err + +call tpem.bat pkcs7 ..\test\testp7.pem +if errorlevel 1 goto err + +call tpem.bat req ..\test\testreq2.pem +if errorlevel 1 goto err + +call tpem.bat rsa ..\test\testrsa.pem +if errorlevel 1 goto err + +call tpem.bat x509 ..\test\testx509.pem +if errorlevel 1 goto err + +call tpem.bat x509 ..\test\v3-cert1.pem +if errorlevel 1 goto err + +call tpem.bat x509 ..\test\v3-cert1.pem +if errorlevel 1 goto err + +call tpem.bat sess_id ..\test\testsid.pem +if errorlevel 1 goto err + +echo OK +del %tmp1% +:err diff --git a/node-v0.8.14/deps/openssl/openssl/ms/testpemce.bat b/node-v0.8.14/deps/openssl/openssl/ms/testpemce.bat new file mode 100644 index 0000000..ac64a79 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/ms/testpemce.bat @@ -0,0 +1,42 @@ +@echo off +set ssleay=%1% +set tmp1=pem.out +set cmp=fc.exe + +cecopy %ssleay% CE:\OpenSSL + +copy ..\test\testcrl.pem >nul +call tpemce.bat crl testcrl.pem +if errorlevel 1 goto err + +copy ..\test\testp7.pem >nul +call tpemce.bat pkcs7 testp7.pem +if errorlevel 1 goto err + +copy ..\test\testreq2.pem >nul +call tpemce.bat req testreq2.pem +if errorlevel 1 goto err + +copy ..\test\testrsa.pem >nul +call tpemce.bat rsa testrsa.pem +if errorlevel 1 goto err + +copy ..\test\testx509.pem >nul +call tpemce.bat x509 testx509.pem +if errorlevel 1 goto err + +copy ..\test\v3-cert1.pem >nul +call tpemce.bat x509 v3-cert1.pem +if errorlevel 1 goto err + +copy ..\test\v3-cert1.pem >nul +call tpemce.bat x509 v3-cert1.pem +if errorlevel 1 goto err + +copy ..\test\testsid.pem >nul +call tpemce.bat sess_id testsid.pem +if errorlevel 1 goto err + +echo OK +del %tmp1% >nul 2>&1 +:err diff --git a/node-v0.8.14/deps/openssl/openssl/ms/testss.bat b/node-v0.8.14/deps/openssl/openssl/ms/testss.bat new file mode 100755 index 0000000..5afa131 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/ms/testss.bat @@ -0,0 +1,98 @@ +@echo off + +rem set ssleay=..\out\ssleay +set ssleay=%1 + +set reqcmd=%ssleay% req +set x509cmd=%ssleay% x509 -sha1 +set verifycmd=%ssleay% verify + +set CAkey=keyCA.ss +set CAcert=certCA.ss +set CAserial=certCA.srl +set CAreq=reqCA.ss +set CAconf=..\test\CAss.cnf +set CAreq2=req2CA.ss + +set Uconf=..\test\Uss.cnf +set Ukey=keyU.ss +set Ureq=reqU.ss +set Ucert=certU.ss + +echo make a certificate request using 'req' +%reqcmd% -config %CAconf% -out %CAreq% -keyout %CAkey% -new +if errorlevel 1 goto e_req + +echo convert the certificate request into a self signed certificate using 'x509' +%x509cmd% -CAcreateserial -in %CAreq% -days 30 -req -out %CAcert% -signkey %CAkey% >err.ss +if errorlevel 1 goto e_x509 + +echo -- +echo convert a certificate into a certificate request using 'x509' +%x509cmd% -in %CAcert% -x509toreq -signkey %CAkey% -out %CAreq2% >err.ss +if errorlevel 1 goto e_x509_2 + +%reqcmd% -verify -in %CAreq% -noout +if errorlevel 1 goto e_vrfy_1 + +%reqcmd% -verify -in %CAreq2% -noout +if errorlevel 1 goto e_vrfy_2 + +%verifycmd% -CAfile %CAcert% %CAcert% +if errorlevel 1 goto e_vrfy_3 + +echo -- +echo make another certificate request using 'req' +%reqcmd% -config %Uconf% -out %Ureq% -keyout %Ukey% -new >err.ss +if errorlevel 1 goto e_req_gen + +echo -- +echo sign certificate request with the just created CA via 'x509' +%x509cmd% -CAcreateserial -in %Ureq% -days 30 -req -out %Ucert% -CA %CAcert% -CAkey %CAkey% -CAserial %CAserial% +if errorlevel 1 goto e_x_sign + +%verifycmd% -CAfile %CAcert% %Ucert% +echo -- +echo Certificate details +%x509cmd% -subject -issuer -startdate -enddate -noout -in %Ucert% + +echo Everything appeared to work +echo -- +echo The generated CA certificate is %CAcert% +echo The generated CA private key is %CAkey% +echo The current CA signing serial number is in %CAserial% + +echo The generated user certificate is %Ucert% +echo The generated user private key is %Ukey% +echo -- + +del err.ss + +goto end + +:e_req +echo error using 'req' to generate a certificate request +goto end +:e_x509 +echo error using 'x509' to self sign a certificate request +goto end +:e_x509_2 +echo error using 'x509' convert a certificate to a certificate request +goto end +:e_vrfy_1 +echo first generated request is invalid +goto end +:e_vrfy_2 +echo second generated request is invalid +goto end +:e_vrfy_3 +echo first generated cert is invalid +goto end +:e_req_gen +echo error using 'req' to generate a certificate request +goto end +:e_x_sign +echo error using 'x509' to sign a certificate request +goto end + +:end diff --git a/node-v0.8.14/deps/openssl/openssl/ms/testssce.bat b/node-v0.8.14/deps/openssl/openssl/ms/testssce.bat new file mode 100644 index 0000000..18381ed --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/ms/testssce.bat @@ -0,0 +1,104 @@ +rem set ssleay=..\out\ssleay +set ssleay=%1 + +set reqcmd=%ssleay% req +set x509cmd=%ssleay% x509 +set verifycmd=%ssleay% verify + +set CAkey=\OpenSSL\keyCA.ss +set CAcert=\OpenSSL\certCA.ss +set CAserial=\OpenSSL\certCA.srl +set CAreq=\OpenSSL\reqCA.ss +cecopy ..\test\CAss.cnf CE:\OpenSSL +set CAconf=\OpenSSL\CAss.cnf +set CAreq2=\OpenSSL\req2CA.ss + +cecopy ..\test\Uss.cnf CE:\OpenSSL +set Uconf=\OpenSSL\Uss.cnf +set Ukey=\OpenSSL\keyU.ss +set Ureq=\OpenSSL\reqU.ss +set Ucert=\OpenSSL\certU.ss + +echo make a certificate request using 'req' +cerun CE:\OpenSSL\%reqcmd% -config %CAconf% -out %CAreq% -keyout %CAkey% -new +if errorlevel 1 goto e_req + +echo convert the certificate request into a self signed certificate using 'x509' +cerun CE:\OpenSSL\%x509cmd% -CAcreateserial -in %CAreq% -days 30 -req -out %CAcert% -signkey %CAkey% "> \OpenSSL\err.ss" +if errorlevel 1 goto e_x509 + +echo -- +echo convert a certificate into a certificate request using 'x509' +cerun CE:\OpenSSL\%x509cmd% -in %CAcert% -x509toreq -signkey %CAkey% -out %CAreq2% "> \OpenSSL\err.ss" +if errorlevel 1 goto e_x509_2 + +cerun CE:\OpenSSL\%reqcmd% -verify -in %CAreq% -noout +if errorlevel 1 goto e_vrfy_1 + +cerun CE:\OpenSSL\%reqcmd% -verify -in %CAreq2% -noout +if errorlevel 1 goto e_vrfy_2 + +cerun CE:\OpenSSL\%verifycmd% -CAfile %CAcert% %CAcert% +if errorlevel 1 goto e_vrfy_3 + +echo -- +echo make another certificate request using 'req' +cerun CE:\OpenSSL\%reqcmd% -config %Uconf% -out %Ureq% -keyout %Ukey% -new "> \OpenSSL\err.ss" +if errorlevel 1 goto e_req_gen + +echo -- +echo sign certificate request with the just created CA via 'x509' +cerun CE:\OpenSSL\%x509cmd% -CAcreateserial -in %Ureq% -days 30 -req -out %Ucert% -CA %CAcert% -CAkey %CAkey% -CAserial %CAserial% +if errorlevel 1 goto e_x_sign + +cerun CE:\OpenSSL\%verifycmd% -CAfile %CAcert% %Ucert% +echo -- +echo Certificate details +cerun CE:\OpenSSL\%x509cmd% -subject -issuer -startdate -enddate -noout -in %Ucert% + +cecopy CE:%CAcert% . +cecopy CE:%CAkey% . +cecopy CE:%CAserial% . +cecopy CE:%Ucert% . +cecopy CE:%Ukey% . + +echo Everything appeared to work +echo -- +echo The generated CA certificate is %CAcert% +echo The generated CA private key is %CAkey% +echo The current CA signing serial number is in %CAserial% + +echo The generated user certificate is %Ucert% +echo The generated user private key is %Ukey% +echo -- + +cedel CE:\OpenSSL\err.ss + +goto end + +:e_req +echo error using 'req' to generate a certificate request +goto end +:e_x509 +echo error using 'x509' to self sign a certificate request +goto end +:e_x509_2 +echo error using 'x509' convert a certificate to a certificate request +goto end +:e_vrfy_1 +echo first generated request is invalid +goto end +:e_vrfy_2 +echo second generated request is invalid +goto end +:e_vrfy_3 +echo first generated cert is invalid +goto end +:e_req_gen +echo error using 'req' to generate a certificate request +goto end +:e_x_sign +echo error using 'x509' to sign a certificate request +goto end + +:end diff --git a/node-v0.8.14/deps/openssl/openssl/ms/tlhelp32.h b/node-v0.8.14/deps/openssl/openssl/ms/tlhelp32.h new file mode 100644 index 0000000..8f4222e --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/ms/tlhelp32.h @@ -0,0 +1,136 @@ +/* + tlhelp32.h - Include file for Tool help functions. + + Written by Mumit Khan + + This file is part of a free library for the Win32 API. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + +*/ +#ifndef _TLHELP32_H +#define _TLHELP32_H +#ifdef __cplusplus +extern "C" { +#endif +#define HF32_DEFAULT 1 +#define HF32_SHARED 2 +#define LF32_FIXED 0x1 +#define LF32_FREE 0x2 +#define LF32_MOVEABLE 0x4 +#define MAX_MODULE_NAME32 255 +#define TH32CS_SNAPHEAPLIST 0x1 +#define TH32CS_SNAPPROCESS 0x2 +#define TH32CS_SNAPTHREAD 0x4 +#define TH32CS_SNAPMODULE 0x8 +#define TH32CS_SNAPALL (TH32CS_SNAPHEAPLIST|TH32CS_SNAPPROCESS|TH32CS_SNAPTHREAD|TH32CS_SNAPMODULE) +#define TH32CS_INHERIT 0x80000000 +typedef struct tagHEAPLIST32 { + DWORD dwSize; + DWORD th32ProcessID; + DWORD th32HeapID; + DWORD dwFlags; +} HEAPLIST32,*PHEAPLIST32,*LPHEAPLIST32; +typedef struct tagHEAPENTRY32 { + DWORD dwSize; + HANDLE hHandle; + DWORD dwAddress; + DWORD dwBlockSize; + DWORD dwFlags; + DWORD dwLockCount; + DWORD dwResvd; + DWORD th32ProcessID; + DWORD th32HeapID; +} HEAPENTRY32,*PHEAPENTRY32,*LPHEAPENTRY32; +typedef struct tagPROCESSENTRY32W { + DWORD dwSize; + DWORD cntUsage; + DWORD th32ProcessID; + DWORD th32DefaultHeapID; + DWORD th32ModuleID; + DWORD cntThreads; + DWORD th32ParentProcessID; + LONG pcPriClassBase; + DWORD dwFlags; + WCHAR szExeFile[MAX_PATH]; +} PROCESSENTRY32W,*PPROCESSENTRY32W,*LPPROCESSENTRY32W; +typedef struct tagPROCESSENTRY32 { + DWORD dwSize; + DWORD cntUsage; + DWORD th32ProcessID; + DWORD th32DefaultHeapID; + DWORD th32ModuleID; + DWORD cntThreads; + DWORD th32ParentProcessID; + LONG pcPriClassBase; + DWORD dwFlags; + CHAR szExeFile[MAX_PATH]; +} PROCESSENTRY32,*PPROCESSENTRY32,*LPPROCESSENTRY32; +typedef struct tagTHREADENTRY32 { + DWORD dwSize; + DWORD cntUsage; + DWORD th32ThreadID; + DWORD th32OwnerProcessID; + LONG tpBasePri; + LONG tpDeltaPri; + DWORD dwFlags; +} THREADENTRY32,*PTHREADENTRY32,*LPTHREADENTRY32; +typedef struct tagMODULEENTRY32W { + DWORD dwSize; + DWORD th32ModuleID; + DWORD th32ProcessID; + DWORD GlblcntUsage; + DWORD ProccntUsage; + BYTE *modBaseAddr; + DWORD modBaseSize; + HMODULE hModule; + WCHAR szModule[MAX_MODULE_NAME32 + 1]; + WCHAR szExePath[MAX_PATH]; +} MODULEENTRY32W,*PMODULEENTRY32W,*LPMODULEENTRY32W; +typedef struct tagMODULEENTRY32 { + DWORD dwSize; + DWORD th32ModuleID; + DWORD th32ProcessID; + DWORD GlblcntUsage; + DWORD ProccntUsage; + BYTE *modBaseAddr; + DWORD modBaseSize; + HMODULE hModule; + char szModule[MAX_MODULE_NAME32 + 1]; + char szExePath[MAX_PATH]; +} MODULEENTRY32,*PMODULEENTRY32,*LPMODULEENTRY32; +BOOL WINAPI Heap32First(LPHEAPENTRY32,DWORD,DWORD); +BOOL WINAPI Heap32ListFirst(HANDLE,LPHEAPLIST32); +BOOL WINAPI Heap32ListNext(HANDLE,LPHEAPLIST32); +BOOL WINAPI Heap32Next(LPHEAPENTRY32); +BOOL WINAPI Module32First(HANDLE,LPMODULEENTRY32); +BOOL WINAPI Module32FirstW(HANDLE,LPMODULEENTRY32W); +BOOL WINAPI Module32Next(HANDLE,LPMODULEENTRY32); +BOOL WINAPI Module32NextW(HANDLE,LPMODULEENTRY32W); +BOOL WINAPI Process32First(HANDLE,LPPROCESSENTRY32); +BOOL WINAPI Process32FirstW(HANDLE,LPPROCESSENTRY32W); +BOOL WINAPI Process32Next(HANDLE,LPPROCESSENTRY32); +BOOL WINAPI Process32NextW(HANDLE,LPPROCESSENTRY32W); +BOOL WINAPI Thread32First(HANDLE,LPTHREADENTRY32); +BOOL WINAPI Thread32Next(HANDLE,LPTHREADENTRY32); +BOOL WINAPI Toolhelp32ReadProcessMemory(DWORD,LPCVOID,LPVOID,DWORD,LPDWORD); +HANDLE WINAPI CreateToolhelp32Snapshot(DWORD,DWORD); +#ifdef UNICODE +#define LPMODULEENTRY32 LPMODULEENTRY32W +#define LPPROCESSENTRY32 LPPROCESSENTRY32W +#define MODULEENTRY32 MODULEENTRY32W +#define Module32First Module32FirstW +#define Module32Next Module32NextW +#define PMODULEENTRY32 PMODULEENTRY32W +#define PPROCESSENTRY32 PPROCESSENTRY32W +#define PROCESSENTRY32 PROCESSENTRY32W +#define Process32First Process32FirstW +#define Process32Next Process32NextW +#endif /* UNICODE */ +#ifdef __cplusplus +} +#endif +#endif /* _TLHELP32_H */ + diff --git a/node-v0.8.14/deps/openssl/openssl/ms/tpem.bat b/node-v0.8.14/deps/openssl/openssl/ms/tpem.bat new file mode 100755 index 0000000..cd01792 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/ms/tpem.bat @@ -0,0 +1,6 @@ +rem called by testpem + +echo test %1 %2 +%ssleay% %1 -in %2 -out %tmp1% +%cmp% %2 %tmp1% + diff --git a/node-v0.8.14/deps/openssl/openssl/ms/tpemce.bat b/node-v0.8.14/deps/openssl/openssl/ms/tpemce.bat new file mode 100644 index 0000000..483f559 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/ms/tpemce.bat @@ -0,0 +1,8 @@ +rem called by testpemce + +echo test %1 %2 +cecopy %2 CE:\OpenSSL +cerun CE:\OpenSSL\%ssleay% %1 -in \OpenSSL\%2 -out \OpenSSL\%tmp1% +del %tmp1% >nul 2>&1 +cecopy CE:\OpenSSL\%tmp1% . +%cmp% %2 %tmp1% diff --git a/node-v0.8.14/deps/openssl/openssl/ms/uplink-common.pl b/node-v0.8.14/deps/openssl/openssl/ms/uplink-common.pl new file mode 100644 index 0000000..1d20e6e --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/ms/uplink-common.pl @@ -0,0 +1,22 @@ +#!/usr/bin/env perl +# +# pull APPLINK_MAX value from applink.c... +$applink_c=$0; +$applink_c=~s|[^/\\]+$||g; +$applink_c.="applink.c"; +open(INPUT,$applink_c) || die "can't open $applink_c: $!"; +@max=grep {/APPLINK_MAX\s+(\d+)/} ; +close(INPUT); +($#max==0) or die "can't find APPLINK_MAX in $applink_c"; + +$max[0]=~/APPLINK_MAX\s+(\d+)/; +$N=$1; # number of entries in OPENSSL_UplinkTable not including + # OPENSSL_UplinkTable[0], which contains this value... + +1; + +# Idea is to fill the OPENSSL_UplinkTable with pointers to stubs +# which invoke 'void OPENSSL_Uplink (ULONG_PTR *table,int index)'; +# and then dereference themselves. Latter shall result in endless +# loop *unless* OPENSSL_Uplink does not replace 'table[index]' with +# something else, e.g. as 'table[index]=unimplemented;'... diff --git a/node-v0.8.14/deps/openssl/openssl/ms/uplink-ia64.pl b/node-v0.8.14/deps/openssl/openssl/ms/uplink-ia64.pl new file mode 100644 index 0000000..4204c73 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/ms/uplink-ia64.pl @@ -0,0 +1,50 @@ +#!/usr/bin/env perl + +$0 =~ m/(.*[\/\\])[^\/\\]+$/; $dir=$1; +push(@INC,"${dir}."); + +require "uplink-common.pl"; + +local $V=8; # max number of args uplink functions may accept... +my $loc0 = "r".(32+$V); +print <<___; +.text +.global OPENSSL_Uplink# +.type OPENSSL_Uplink#,\@function + +___ +for ($i=1;$i<=$N;$i++) { +print <<___; +.proc lazy$i# +lazy$i: + .prologue +{ .mii; .save ar.pfs,$loc0 + alloc loc0=ar.pfs,$V,3,2,0 + .save b0,loc1 + mov loc1=b0 + addl loc2=\@ltoff(OPENSSL_UplinkTable#),gp };; + .body +{ .mmi; ld8 out0=[loc2] + mov out1=$i };; +{ .mib; add loc2=8*$i,out0 + br.call.sptk.many b0=OPENSSL_Uplink# };; +{ .mmi; ld8 r31=[loc2];; + ld8 r30=[r31],8 };; +{ .mii; ld8 gp=[r31] + mov b6=r30 + mov b0=loc1 };; +{ .mib; mov ar.pfs=loc0 + br.many b6 };; +.endp lazy$i# + +___ +} +print <<___; +.data +.global OPENSSL_UplinkTable# +OPENSSL_UplinkTable: data8 $N // amount of following entries +___ +for ($i=1;$i<=$N;$i++) { print " data8 \@fptr(lazy$i#)\n"; } +print <<___; +.size OPENSSL_UplinkTable,.-OPENSSL_UplinkTable# +___ diff --git a/node-v0.8.14/deps/openssl/openssl/ms/uplink-x86.pl b/node-v0.8.14/deps/openssl/openssl/ms/uplink-x86.pl new file mode 100644 index 0000000..0dffc14 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/ms/uplink-x86.pl @@ -0,0 +1,33 @@ +#!/usr/bin/env perl + +$0 =~ m/(.*[\/\\])[^\/\\]+$/; $dir=$1; +push(@INC, "${dir}.", "${dir}../crypto/perlasm"); +require "x86asm.pl"; + +require "uplink-common.pl"; + +&asm_init($ARGV[0],"uplink-x86"); + +&external_label("OPENSSL_Uplink"); +&public_label("OPENSSL_UplinkTable"); + +for ($i=1;$i<=$N;$i++) { +&function_begin_B("_\$lazy${i}"); + &lea ("eax",&DWP(&label("OPENSSL_UplinkTable"))); + &push ("eax"); + &push ($i); + &call (&label("OPENSSL_Uplink")); + &add ("esp",8); + &pop ("eax"); + &jmp_ptr(&DWP(4*$i,"eax")); +&function_end_B("_\$lazy${i}"); +} + +&dataseg(); +&align(4); +&set_label("OPENSSL_UplinkTable"); +&data_word($N); +for ($i=1;$i<=$N;$i++) { +&data_word(&label("_\$lazy${i}")); +} +&asm_finish(); diff --git a/node-v0.8.14/deps/openssl/openssl/ms/uplink-x86_64.pl b/node-v0.8.14/deps/openssl/openssl/ms/uplink-x86_64.pl new file mode 100644 index 0000000..9acbf6b --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/ms/uplink-x86_64.pl @@ -0,0 +1,64 @@ +#!/usr/bin/env perl + +$output=shift; +$0 =~ m/(.*[\/\\])[^\/\\]+$/; $dir=$1; +open STDOUT,"| $^X ${dir}../crypto/perlasm/x86_64-xlate.pl $output"; +push(@INC,"${dir}."); + +require "uplink-common.pl"; + +$prefix="_lazy"; + +print <<___; +.text +.extern OPENSSL_Uplink +.globl OPENSSL_UplinkTable +___ +for ($i=1;$i<=$N;$i++) { +print <<___; +.type $prefix${i},\@abi-omnipotent +.align 16 +$prefix${i}: + .byte 0x48,0x83,0xEC,0x28 # sub rsp,40 + mov %rcx,48(%rsp) + mov %rdx,56(%rsp) + mov %r8,64(%rsp) + mov %r9,72(%rsp) + lea OPENSSL_UplinkTable(%rip),%rcx + mov \$$i,%rdx + call OPENSSL_Uplink + mov 48(%rsp),%rcx + mov 56(%rsp),%rdx + mov 64(%rsp),%r8 + mov 72(%rsp),%r9 + lea OPENSSL_UplinkTable(%rip),%rax + add \$40,%rsp + jmp *8*$i(%rax) +$prefix${i}_end: +.size $prefix${i},.-$prefix${i} +___ +} +print <<___; +.data +OPENSSL_UplinkTable: + .quad $N +___ +for ($i=1;$i<=$N;$i++) { print " .quad $prefix$i\n"; } +print <<___; +.section .pdata,"r" +.align 4 +___ +for ($i=1;$i<=$N;$i++) { +print <<___; + .rva $prefix${i},$prefix${i}_end,${prefix}_unwind_info +___ +} +print <<___; +.section .xdata,"r" +.align 8 +${prefix}_unwind_info: + .byte 0x01,0x04,0x01,0x00 + .byte 0x04,0x42,0x00,0x00 +___ + +close STDOUT; diff --git a/node-v0.8.14/deps/openssl/openssl/ms/uplink.c b/node-v0.8.14/deps/openssl/openssl/ms/uplink.c new file mode 100644 index 0000000..6d59cb1 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/ms/uplink.c @@ -0,0 +1,117 @@ +#if (defined(_WIN64) || defined(_WIN32_WCE)) && !defined(UNICODE) +#define UNICODE +#endif +#if defined(UNICODE) && !defined(_UNICODE) +#define _UNICODE +#endif +#if defined(_UNICODE) && !defined(UNICODE) +#define UNICODE +#endif + +#include +#include +#include +#include "uplink.h" +void OPENSSL_showfatal(const char *,...); + +static TCHAR msg[128]; + +static void unimplemented (void) +{ OPENSSL_showfatal (sizeof(TCHAR)==sizeof(char)?"%s\n":"%S\n",msg); + ExitProcess (1); +} + +void OPENSSL_Uplink (volatile void **table, int index) +{ static HMODULE volatile apphandle=NULL; + static void ** volatile applinktable=NULL; + int len; + void (*func)(void)=unimplemented; + HANDLE h; + void **p; + + /* Note that the below code is not MT-safe in respect to msg + * buffer, but what's the worst thing that can happen? Error + * message might be misleading or corrupted. As error condition + * is fatal and should never be risen, I accept the risk... */ + /* One can argue that I should have used InterlockedExchangePointer + * or something to update static variables and table[]. Well, + * store instructions are as atomic as they can get and assigned + * values are effectively constant... So that volatile qualifier + * should be sufficient [it prohibits compiler to reorder memory + * access instructions]. */ + do { + len = _sntprintf (msg,sizeof(msg)/sizeof(TCHAR), + _T("OPENSSL_Uplink(%p,%02X): "),table,index); + _tcscpy (msg+len,_T("unimplemented function")); + + if ((h=apphandle)==NULL) + { if ((h=GetModuleHandle(NULL))==NULL) + { apphandle=(HMODULE)-1; + _tcscpy (msg+len,_T("no host application")); + break; + } + apphandle = h; + } + if ((h=apphandle)==(HMODULE)-1) /* revalidate */ + break; + + if (applinktable==NULL) + { void**(*applink)(); + + applink=(void**(*)())GetProcAddress(h,"OPENSSL_Applink"); + if (applink==NULL) + { apphandle=(HMODULE)-1; + _tcscpy (msg+len,_T("no OPENSSL_Applink")); + break; + } + p = (*applink)(); + if (p==NULL) + { apphandle=(HMODULE)-1; + _tcscpy (msg+len,_T("no ApplinkTable")); + break; + } + applinktable = p; + } + else + p = applinktable; + + if (index > (int)p[0]) + break; + + if (p[index]) func = p[index]; + } while (0); + + table[index] = func; +} + +#if defined(_MSC_VER) && defined(_M_IX86) && !defined(OPENSSL_NO_INLINE_ASM) +#define LAZY(i) \ +__declspec(naked) static void lazy##i (void) { \ + _asm push i \ + _asm push OFFSET OPENSSL_UplinkTable \ + _asm call OPENSSL_Uplink \ + _asm add esp,8 \ + _asm jmp OPENSSL_UplinkTable+4*i } + +#if APPLINK_MAX>25 +#error "Add more stubs..." +#endif +/* make some in advance... */ +LAZY(1) LAZY(2) LAZY(3) LAZY(4) LAZY(5) +LAZY(6) LAZY(7) LAZY(8) LAZY(9) LAZY(10) +LAZY(11) LAZY(12) LAZY(13) LAZY(14) LAZY(15) +LAZY(16) LAZY(17) LAZY(18) LAZY(19) LAZY(20) +LAZY(21) LAZY(22) LAZY(23) LAZY(24) LAZY(25) +void *OPENSSL_UplinkTable[] = { + (void *)APPLINK_MAX, + lazy1, lazy2, lazy3, lazy4, lazy5, + lazy6, lazy7, lazy8, lazy9, lazy10, + lazy11,lazy12,lazy13,lazy14,lazy15, + lazy16,lazy17,lazy18,lazy19,lazy20, + lazy21,lazy22,lazy23,lazy24,lazy25, +}; +#endif + +#ifdef SELFTEST +main() { UP_fprintf(UP_stdout,"hello, world!\n"); } +#endif diff --git a/node-v0.8.14/deps/openssl/openssl/ms/uplink.h b/node-v0.8.14/deps/openssl/openssl/ms/uplink.h new file mode 100644 index 0000000..a4a67d3 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/ms/uplink.h @@ -0,0 +1,29 @@ +#define APPMACROS_ONLY +#include "applink.c" + +extern void *OPENSSL_UplinkTable[]; + +#define UP_stdin (*(void *(*)(void))OPENSSL_UplinkTable[APPLINK_STDIN])() +#define UP_stdout (*(void *(*)(void))OPENSSL_UplinkTable[APPLINK_STDOUT])() +#define UP_stderr (*(void *(*)(void))OPENSSL_UplinkTable[APPLINK_STDERR])() +#define UP_fprintf (*(int (*)(void *,const char *,...))OPENSSL_UplinkTable[APPLINK_FPRINTF]) +#define UP_fgets (*(char *(*)(char *,int,void *))OPENSSL_UplinkTable[APPLINK_FGETS]) +#define UP_fread (*(size_t (*)(void *,size_t,size_t,void *))OPENSSL_UplinkTable[APPLINK_FREAD]) +#define UP_fwrite (*(size_t (*)(const void *,size_t,size_t,void *))OPENSSL_UplinkTable[APPLINK_FWRITE]) +#define UP_fsetmod (*(int (*)(void *,char))OPENSSL_UplinkTable[APPLINK_FSETMOD]) +#define UP_feof (*(int (*)(void *))OPENSSL_UplinkTable[APPLINK_FEOF]) +#define UP_fclose (*(int (*)(void *))OPENSSL_UplinkTable[APPLINK_FCLOSE]) + +#define UP_fopen (*(void *(*)(const char *,const char *))OPENSSL_UplinkTable[APPLINK_FOPEN]) +#define UP_fseek (*(int (*)(void *,long,int))OPENSSL_UplinkTable[APPLINK_FSEEK]) +#define UP_ftell (*(long (*)(void *))OPENSSL_UplinkTable[APPLINK_FTELL]) +#define UP_fflush (*(int (*)(void *))OPENSSL_UplinkTable[APPLINK_FFLUSH]) +#define UP_ferror (*(int (*)(void *))OPENSSL_UplinkTable[APPLINK_FERROR]) +#define UP_clearerr (*(void (*)(void *))OPENSSL_UplinkTable[APPLINK_CLEARERR]) +#define UP_fileno (*(int (*)(void *))OPENSSL_UplinkTable[APPLINK_FILENO]) + +#define UP_open (*(int (*)(const char *,int,...))OPENSSL_UplinkTable[APPLINK_OPEN]) +#define UP_read (*(ssize_t (*)(int,void *,size_t))OPENSSL_UplinkTable[APPLINK_READ]) +#define UP_write (*(ssize_t (*)(int,const void *,size_t))OPENSSL_UplinkTable[APPLINK_WRITE]) +#define UP_lseek (*(long (*)(int,long,int))OPENSSL_UplinkTable[APPLINK_LSEEK]) +#define UP_close (*(int (*)(int))OPENSSL_UplinkTable[APPLINK_CLOSE]) diff --git a/node-v0.8.14/deps/openssl/openssl/ms/uplink.pl b/node-v0.8.14/deps/openssl/openssl/ms/uplink.pl new file mode 100755 index 0000000..102400e --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/ms/uplink.pl @@ -0,0 +1,204 @@ +#!/usr/bin/env perl +# +# For Microsoft CL this is implemented as inline assembler. So that +# even though this script can generate even Win32 code, we'll be +# using it primarily to generate Win64 modules. Both IA-64 and AMD64 +# are supported... + +# pull APPLINK_MAX value from applink.c... +$applink_c=$0; +$applink_c=~s|[^/\\]+$||g; +$applink_c.="applink.c"; +open(INPUT,$applink_c) || die "can't open $applink_c: $!"; +@max=grep {/APPLINK_MAX\s+(\d+)/} ; +close(INPUT); +($#max==0) or die "can't find APPLINK_MAX in $applink_c"; + +$max[0]=~/APPLINK_MAX\s+(\d+)/; +$N=$1; # number of entries in OPENSSL_UplinkTable not including + # OPENSSL_UplinkTable[0], which contains this value... + +# Idea is to fill the OPENSSL_UplinkTable with pointers to stubs +# which invoke 'void OPENSSL_Uplink (ULONG_PTR *table,int index)'; +# and then dereference themselves. Latter shall result in endless +# loop *unless* OPENSSL_Uplink does not replace 'table[index]' with +# something else, e.g. as 'table[index]=unimplemented;'... + +$arg = shift; +#( defined shift || open STDOUT,">$arg" ) || die "can't open $arg: $!"; + +if ($arg =~ /win32n/) { ia32nasm(); } +elsif ($arg =~ /win32/) { ia32masm(); } +elsif ($arg =~ /coff/) { ia32gas(); } +elsif ($arg =~ /win64i/ or $arg =~ /ia64/) { ia64ias(); } +elsif ($arg =~ /win64a/ or $arg =~ /amd64/) { amd64masm(); } +else { die "nonsense $arg"; } + +sub ia32gas() { +print <<___; +.text +___ +for ($i=1;$i<=$N;$i++) { +print <<___; +.def .Lazy$i; .scl 3; .type 32; .endef +.align 4 +.Lazy$i: + pushl \$$i + pushl \$_OPENSSL_UplinkTable + call _OPENSSL_Uplink + addl \$8,%esp + jmp *(_OPENSSL_UplinkTable+4*$i) +___ +} +print <<___; +.data +.align 4 +.globl _OPENSSL_UplinkTable +_OPENSSL_UplinkTable: + .long $N +___ +for ($i=1;$i<=$N;$i++) { print " .long .Lazy$i\n"; } +} + +sub ia32masm() { +print <<___; +.386P +.model FLAT + +_DATA SEGMENT +PUBLIC _OPENSSL_UplinkTable +_OPENSSL_UplinkTable DD $N ; amount of following entries +___ +for ($i=1;$i<=$N;$i++) { print " DD FLAT:\$lazy$i\n"; } +print <<___; +_DATA ENDS + +_TEXT SEGMENT +EXTRN _OPENSSL_Uplink:NEAR +___ +for ($i=1;$i<=$N;$i++) { +print <<___; +ALIGN 4 +\$lazy$i PROC NEAR + push $i + push OFFSET FLAT:_OPENSSL_UplinkTable + call _OPENSSL_Uplink + add esp,8 + jmp DWORD PTR _OPENSSL_UplinkTable+4*$i +\$lazy$i ENDP +___ +} +print <<___; +ALIGN 4 +_TEXT ENDS +END +___ +} + +sub ia32nasm() { +print <<___; +SEGMENT .data +GLOBAL _OPENSSL_UplinkTable +_OPENSSL_UplinkTable DD $N ; amount of following entries +___ +for ($i=1;$i<=$N;$i++) { print " DD \$lazy$i\n"; } +print <<___; + +SEGMENT .text +EXTERN _OPENSSL_Uplink +___ +for ($i=1;$i<=$N;$i++) { +print <<___; +ALIGN 4 +\$lazy$i: + push $i + push _OPENSSL_UplinkTable + call _OPENSSL_Uplink + add esp,8 + jmp [_OPENSSL_UplinkTable+4*$i] +___ +} +print <<___; +ALIGN 4 +END +___ +} + +sub ia64ias () { +local $V=8; # max number of args uplink functions may accept... +print <<___; +.data +.global OPENSSL_UplinkTable# +OPENSSL_UplinkTable: data8 $N // amount of following entries +___ +for ($i=1;$i<=$N;$i++) { print " data8 \@fptr(lazy$i#)\n"; } +print <<___; +.size OPENSSL_UplinkTable,.-OPENSSL_UplinkTable# + +.text +.global OPENSSL_Uplink# +.type OPENSSL_Uplink#,\@function +___ +for ($i=1;$i<=$N;$i++) { +print <<___; +.proc lazy$i +lazy$i: +{ .mii; alloc loc0=ar.pfs,$V,3,2,0 + mov loc1=b0 + addl loc2=\@ltoff(OPENSSL_UplinkTable#),gp };; +{ .mmi; ld8 out0=[loc2] + mov out1=$i };; +{ .mib; adds loc2=8*$i,out0 + br.call.sptk.many b0=OPENSSL_Uplink# };; +{ .mmi; ld8 r31=[loc2];; + ld8 r30=[r31],8 };; +{ .mii; ld8 gp=[r31] + mov b6=r30 + mov b0=loc1 };; +{ .mib; mov ar.pfs=loc0 + br.many b6 };; +.endp lazy$i# +___ +} +} + +sub amd64masm() { +print <<___; +_DATA SEGMENT +PUBLIC OPENSSL_UplinkTable +OPENSSL_UplinkTable DQ $N +___ +for ($i=1;$i<=$N;$i++) { print " DQ \$lazy$i\n"; } +print <<___; +_DATA ENDS + +_TEXT SEGMENT +EXTERN OPENSSL_Uplink:PROC +___ +for ($i=1;$i<=$N;$i++) { +print <<___; +ALIGN 4 +\$lazy$i PROC + push r9 + push r8 + push rdx + push rcx + sub rsp,40 + lea rcx,OFFSET OPENSSL_UplinkTable + mov rdx,$i + call OPENSSL_Uplink + add rsp,40 + pop rcx + pop rdx + pop r8 + pop r9 + jmp QWORD PTR OPENSSL_UplinkTable+8*$i +\$lazy$i ENDP +___ +} +print <<___; +_TEXT ENDS +END +___ +} + diff --git a/node-v0.8.14/deps/openssl/openssl/ms/x86asm.bat b/node-v0.8.14/deps/openssl/openssl/ms/x86asm.bat new file mode 100755 index 0000000..03563c6 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/ms/x86asm.bat @@ -0,0 +1,57 @@ + +@echo off +echo Generating x86 assember + +echo Bignum +cd crypto\bn\asm +perl x86.pl win32n > bn-win32.asm +cd ..\..\.. + +echo DES +cd crypto\des\asm +perl des-586.pl win32n > d-win32.asm +cd ..\..\.. + +echo "crypt(3)" + +cd crypto\des\asm +perl crypt586.pl win32n > y-win32.asm +cd ..\..\.. + +echo Blowfish + +cd crypto\bf\asm +perl bf-586.pl win32n > b-win32.asm +cd ..\..\.. + +echo CAST5 +cd crypto\cast\asm +perl cast-586.pl win32n > c-win32.asm +cd ..\..\.. + +echo RC4 +cd crypto\rc4\asm +perl rc4-586.pl win32n > r4-win32.asm +cd ..\..\.. + +echo MD5 +cd crypto\md5\asm +perl md5-586.pl win32n > m5-win32.asm +cd ..\..\.. + +echo SHA1 +cd crypto\sha\asm +perl sha1-586.pl win32n > s1-win32.asm +cd ..\..\.. + +echo RIPEMD160 +cd crypto\ripemd\asm +perl rmd-586.pl win32n > rm-win32.asm +cd ..\..\.. + +echo RC5\32 +cd crypto\rc5\asm +perl rc5-586.pl win32n > r5-win32.asm +cd ..\..\.. + +echo on diff --git a/node-v0.8.14/deps/openssl/openssl/openssl.doxy b/node-v0.8.14/deps/openssl/openssl/openssl.doxy new file mode 100644 index 0000000..479c311 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/openssl.doxy @@ -0,0 +1,7 @@ +PROJECT_NAME=OpenSSL +GENERATE_LATEX=no +OUTPUT_DIRECTORY=doxygen +INPUT=ssl include +FILE_PATTERNS=*.c *.h +RECURSIVE=yes +PREDEFINED=DOXYGEN diff --git a/node-v0.8.14/deps/openssl/openssl/openssl.spec b/node-v0.8.14/deps/openssl/openssl/openssl.spec new file mode 100644 index 0000000..703cea2 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/openssl.spec @@ -0,0 +1,213 @@ +%define _unpackaged_files_terminate_build 0 +%define libmaj 1 +%define libmin 0 +%define librel 0 +%define librev f +Release: 1 + +%define openssldir /var/ssl + +Summary: Secure Sockets Layer and cryptography libraries and tools +Name: openssl +#Version: %{libmaj}.%{libmin}.%{librel} +Version: %{libmaj}.%{libmin}.%{librel}%{librev} +Source0: ftp://ftp.openssl.org/source/%{name}-%{version}.tar.gz +Copyright: Freely distributable +Group: System Environment/Libraries +Provides: SSL +URL: http://www.openssl.org/ +Packager: Damien Miller +BuildRoot: /var/tmp/%{name}-%{version}-root + +%description +The OpenSSL Project is a collaborative effort to develop a robust, +commercial-grade, fully featured, and Open Source toolkit implementing the +Secure Sockets Layer (SSL v2/v3) and Transport Layer Security (TLS v1) +protocols as well as a full-strength general purpose cryptography library. +The project is managed by a worldwide community of volunteers that use the +Internet to communicate, plan, and develop the OpenSSL tookit and its related +documentation. + +OpenSSL is based on the excellent SSLeay library developed from Eric A. +Young and Tim J. Hudson. The OpenSSL toolkit is licensed under an +Apache-style licence, which basically means that you are free to get and +use it for commercial and non-commercial purposes. + +This package contains the base OpenSSL cryptography and SSL/TLS +libraries and tools. + +%package devel +Summary: Secure Sockets Layer and cryptography static libraries and headers +Group: Development/Libraries +Requires: openssl +%description devel +The OpenSSL Project is a collaborative effort to develop a robust, +commercial-grade, fully featured, and Open Source toolkit implementing the +Secure Sockets Layer (SSL v2/v3) and Transport Layer Security (TLS v1) +protocols as well as a full-strength general purpose cryptography library. +The project is managed by a worldwide community of volunteers that use the +Internet to communicate, plan, and develop the OpenSSL tookit and its related +documentation. + +OpenSSL is based on the excellent SSLeay library developed from Eric A. +Young and Tim J. Hudson. The OpenSSL toolkit is licensed under an +Apache-style licence, which basically means that you are free to get and +use it for commercial and non-commercial purposes. + +This package contains the the OpenSSL cryptography and SSL/TLS +static libraries and header files required when developing applications. + +%package doc +Summary: OpenSSL miscellaneous files +Group: Documentation +Requires: openssl +%description doc +The OpenSSL Project is a collaborative effort to develop a robust, +commercial-grade, fully featured, and Open Source toolkit implementing the +Secure Sockets Layer (SSL v2/v3) and Transport Layer Security (TLS v1) +protocols as well as a full-strength general purpose cryptography library. +The project is managed by a worldwide community of volunteers that use the +Internet to communicate, plan, and develop the OpenSSL tookit and its related +documentation. + +OpenSSL is based on the excellent SSLeay library developed from Eric A. +Young and Tim J. Hudson. The OpenSSL toolkit is licensed under an +Apache-style licence, which basically means that you are free to get and +use it for commercial and non-commercial purposes. + +This package contains the the OpenSSL cryptography and SSL/TLS extra +documentation and POD files from which the man pages were produced. + +%prep + +%setup -q + +%build + +%define CONFIG_FLAGS -DSSL_ALLOW_ADH --prefix=/usr --openssldir=%{openssldir} + +perl util/perlpath.pl /usr/bin/perl + +%ifarch i386 i486 i586 i686 +./Configure %{CONFIG_FLAGS} linux-elf shared +%endif +%ifarch ppc +./Configure %{CONFIG_FLAGS} linux-ppc shared +%endif +%ifarch alpha +./Configure %{CONFIG_FLAGS} linux-alpha shared +%endif +%ifarch x86_64 +./Configure %{CONFIG_FLAGS} linux-x86_64 shared +%endif +LD_LIBRARY_PATH=`pwd` make +LD_LIBRARY_PATH=`pwd` make rehash +LD_LIBRARY_PATH=`pwd` make test + +%install +rm -rf $RPM_BUILD_ROOT +make MANDIR=/usr/man MANSUFFIX=ssl INSTALL_PREFIX="$RPM_BUILD_ROOT" install + +# Make backwards-compatibility symlink to ssleay +ln -sf /usr/bin/openssl $RPM_BUILD_ROOT/usr/bin/ssleay + +%clean +rm -rf $RPM_BUILD_ROOT + +%files +%defattr(0644,root,root,0755) +%doc CHANGES CHANGES.SSLeay LICENSE NEWS README + +%attr(0755,root,root) /usr/bin/* +%attr(0755,root,root) /usr/lib/*.so* +%attr(0755,root,root) %{openssldir}/misc/* +%attr(0644,root,root) /usr/man/man[157]/* + +%config %attr(0644,root,root) %{openssldir}/openssl.cnf +%dir %attr(0755,root,root) %{openssldir}/certs +%dir %attr(0755,root,root) %{openssldir}/misc +%dir %attr(0750,root,root) %{openssldir}/private + +%files devel +%defattr(0644,root,root,0755) +%doc CHANGES CHANGES.SSLeay LICENSE NEWS README + +%attr(0644,root,root) /usr/lib/*.a +%attr(0644,root,root) /usr/lib/pkgconfig/openssl.pc +%attr(0644,root,root) /usr/include/openssl/* +%attr(0644,root,root) /usr/man/man[3]/* + +%files doc +%defattr(0644,root,root,0755) +%doc CHANGES CHANGES.SSLeay LICENSE NEWS README +%doc doc + +%post +ldconfig + +%postun +ldconfig + +%changelog +* Sun Jun 6 2005 Richard Levitte +- Remove the incorrect installation of '%{openssldir}/lib'. +* Wed May 7 2003 Richard Levitte +- Add /usr/lib/pkgconfig/openssl.pc to the development section. +* Thu Mar 22 2001 Richard Levitte +- Removed redundant subsection that re-installed libcrypto.a and libssl.a + as well. Also remove RSAref stuff completely, since it's not needed + any more. +* Thu Mar 15 2001 Jeremiah Johnson +- Removed redundant subsection that re-installed libcrypto.so.0.9.6 and + libssl.so.0.9.6. As well as the subsection that created symlinks for + these. make install handles all this. +* Sat Oct 21 2000 Horms +- Make sure symlinks are created by using -f flag to ln. + Otherwise some .so libraries are copied rather than + linked in the resulting binary RPM. This causes the package + to be larger than neccessary and makes ldconfig complain. +* Fri Oct 13 2000 Horms +- Make defattr is set for files in all packages so packages built as + non-root will still be installed with files owned by root. +* Thu Sep 14 2000 Richard Levitte +- Changed to adapt to the new (supported) way of making shared libraries +- Installs all static libraries, not just libRSAglue.a +- Extra documents now end up in a separate document package +* Sun Feb 27 2000 Damien Miller +- Merged patches to spec +- Updated to 0.9.5beta2 (now with manpages) +* Sat Feb 5 2000 Michal Jaegermann +- added 'linux-alpha' to configuration +- fixed nasty absolute links +* Tue Jan 25 2000 Bennett Todd +- Added -DSSL_ALLOW_ADH, bumped Release to 4 +* Thu Oct 14 1999 Damien Miller +- Set default permissions +- Removed documentation from devel sub-package +* Thu Sep 30 1999 Damien Miller +- Added "make test" stage +- GPG signed +* Tue Sep 10 1999 Damien Miller +- Updated to version 0.9.4 +* Tue May 25 1999 Damien Miller +- Updated to version 0.9.3 +- Added attributes for all files +- Paramatised openssl directory +* Sat Mar 20 1999 Carlo M. Arenas Belon +- Added "official" bnrec patch and taking other out +- making a link from ssleay to openssl binary +- putting all changelog together on SPEC file +* Fri Mar 5 1999 Henri Gomez +- Added bnrec patch +* Tue Dec 29 1998 Jonathan Ruano +- minimum spec and patches changes for openssl +- modified for openssl sources +* Sat Aug 8 1998 Khimenko Victor +- shared library creating process honours $RPM_OPT_FLAGS +- shared libarry supports threads (as well as static library) +* Wed Jul 22 1998 Khimenko Victor +- building of shared library completely reworked +* Tue Jul 21 1998 Khimenko Victor +- RPM is BuildRoot'ed +* Tue Feb 10 1998 Khimenko Victor +- all stuff is moved out of /usr/local diff --git a/node-v0.8.14/deps/openssl/openssl/os2/OS2-EMX.cmd b/node-v0.8.14/deps/openssl/openssl/os2/OS2-EMX.cmd new file mode 100644 index 0000000..5924b50 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/os2/OS2-EMX.cmd @@ -0,0 +1,102 @@ +@echo off + +perl Configure OS2-EMX +perl util\mkfiles.pl > MINFO + +@rem create make file +perl util\mk1mf.pl OS2-EMX > OS2-EMX.mak +perl util\mk1mf.pl dll OS2-EMX > OS2-EMX-DLL.mak + +echo Generating export definition files +perl util\mkdef.pl crypto OS2 > os2\crypto.def +perl util\mkdef.pl ssl OS2 > os2\ssl.def + +echo Generating x86 for GNU assember + +echo Bignum +cd crypto\bn\asm +rem perl x86.pl a.out > bn-os2.asm +perl bn-586.pl a.out > bn-os2.asm +perl co-586.pl a.out > co-os2.asm +cd ..\..\.. + +echo DES +cd crypto\des\asm +perl des-586.pl a.out > d-os2.asm +cd ..\..\.. + +echo crypt(3) +cd crypto\des\asm +perl crypt586.pl a.out > y-os2.asm +cd ..\..\.. + +echo Blowfish +cd crypto\bf\asm +perl bf-586.pl a.out > b-os2.asm +cd ..\..\.. + +echo CAST5 +cd crypto\cast\asm +perl cast-586.pl a.out > c-os2.asm +cd ..\..\.. + +echo RC4 +cd crypto\rc4\asm +perl rc4-586.pl a.out > r4-os2.asm +cd ..\..\.. + +echo MD5 +cd crypto\md5\asm +perl md5-586.pl a.out > m5-os2.asm +cd ..\..\.. + +echo SHA1 +cd crypto\sha\asm +perl sha1-586.pl a.out > s1-os2.asm +cd ..\..\.. + +echo RIPEMD160 +cd crypto\ripemd\asm +perl rmd-586.pl a.out > rm-os2.asm +cd ..\..\.. + +echo RC5\32 +cd crypto\rc5\asm +perl rc5-586.pl a.out > r5-os2.asm +cd ..\..\.. + +cd os2 + +if exist noname\backward_ssl.def goto nomkdir +mkdir noname +:nomkdir + +perl backwardify.pl crypto.def >backward_crypto.def +perl backwardify.pl ssl.def >backward_ssl.def +perl backwardify.pl -noname crypto.def >noname\backward_crypto.def +perl backwardify.pl -noname ssl.def >noname\backward_ssl.def + +echo Creating backward compatibility forwarder dlls: +echo crypto.dll +gcc -Zomf -Zdll -Zcrtdll -o crypto.dll backward_crypto.def 2>&1 | grep -v L4085 +echo ssl.dll +gcc -Zomf -Zdll -Zcrtdll -o ssl.dll backward_ssl.def 2>&1 | grep -v L4085 + +echo Creating smaller backward compatibility forwarder dlls: +echo These DLLs are not good for runtime resolution of symbols. +echo noname\crypto.dll +gcc -Zomf -Zdll -Zcrtdll -o noname/crypto.dll noname/backward_crypto.def 2>&1 | grep -v L4085 +echo noname\ssl.dll +gcc -Zomf -Zdll -Zcrtdll -o noname/ssl.dll noname/backward_ssl.def 2>&1 | grep -v L4085 + +echo Compressing forwarders (it is ok if lxlite is not found): +lxlite *.dll noname/*.dll + +cd .. + +echo Now run: +echo For static build: +echo make -f OS2-EMX.mak +echo For dynamic build: +echo make -f OS2-EMX-DLL.mak +echo then rename crypto.dll to cryptssl.dll, ssl.dll to open_ssl.dll diff --git a/node-v0.8.14/deps/openssl/openssl/os2/backwardify.pl b/node-v0.8.14/deps/openssl/openssl/os2/backwardify.pl new file mode 100644 index 0000000..272423c --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/os2/backwardify.pl @@ -0,0 +1,32 @@ +#!/usr/bin/perl -w +use strict; + +# Use as $0 +# Use as $0 -noname + +my $did_library; +my $did_description; +my $do_exports; +my @imports; +my $noname = (@ARGV and $ARGV[0] eq '-noname' and shift); +while (<>) { + unless ($did_library) { + s/\b(cryptssl)\b/crypto/ and $did_library = $1 if /^LIBRARY\s+cryptssl\b/; + s/\b(open_ssl)\b/ssl/ and $did_library = $1 if /^LIBRARY\s+open_ssl\b/; + } + unless ($did_description) { + s&^(DESCRIPTION\s+(['"])).*&${1}\@#www.openssl.org/:#\@forwarder DLL for pre-0.9.7c+ OpenSSL to the new dll naming scheme$2& and $did_description++; + } + if ($do_exports) {{ + last unless /\S/; + warn, last unless /^ \s* ( \w+ ) \s+ \@(\d+)\s*$/x; + push @imports, [$1, $2]; + s/$/ NONAME/ if $noname; + }} + $do_exports++ if not $do_exports and /^EXPORTS/; + print $_; +} +print "IMPORTS\n"; +for my $imp (@imports) { + print "\t$imp->[0]=$did_library.$imp->[1]\n"; +} diff --git a/node-v0.8.14/deps/openssl/openssl/shlib/Makefile.hpux10-cc b/node-v0.8.14/deps/openssl/openssl/shlib/Makefile.hpux10-cc new file mode 100644 index 0000000..89c28dc --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/shlib/Makefile.hpux10-cc @@ -0,0 +1,34 @@ +# Makefile.hpux-cc + +major=0.9.8 + +slib=libssl +sh_slib=$(slib).sl.$(major) + +clib=libcrypto +sh_clib=$(clib).sl.$(major) + +all : $(clib).sl $(slib).sl + + +$(clib)_pic.a : $(clib).a + echo "Copying $? to $@" + cp -p $? $@ + +$(slib)_pic.a : $(slib).a + echo "Copying $? to $@" + cp -p $? $@ + +$(sh_clib) : $(clib)_pic.a + ld -b -s -z +h $@ -o $@ -Fl $(clib)_pic.a -ldld -lc + +$(clib).sl : $(sh_clib) + rm -f $@ + ln -s $? $@ + +$(sh_slib) : $(slib)_pic.a $(clib).sl + ld -b -s -z +h $@ -o $@ -Fl $(slib)_pic.a -ldld -lc + +$(slib).sl : $(sh_slib) + rm -f $@ + ln -s $? $@ diff --git a/node-v0.8.14/deps/openssl/openssl/shlib/README b/node-v0.8.14/deps/openssl/openssl/shlib/README new file mode 100644 index 0000000..fea07a5 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/shlib/README @@ -0,0 +1 @@ +Only the windows NT and, linux builds have been tested for SSLeay 0.8.0 diff --git a/node-v0.8.14/deps/openssl/openssl/shlib/hpux10-cc.sh b/node-v0.8.14/deps/openssl/openssl/shlib/hpux10-cc.sh new file mode 100644 index 0000000..ceeb8c5 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/shlib/hpux10-cc.sh @@ -0,0 +1,92 @@ +#!/usr/bin/sh +# +# Run this script from the OpenSSL root directory: +# sh shlib/hpux10-cc.sh +# +# HP-UX (10.20) shared library installation: +# Compile and install OpenSSL with best possible optimization: +# - shared libraries are compiled and installed with +O4 optimization +# - executable(s) are compiled and installed with +O4 optimization +# - static libraries are compiled and installed with +O3 optimization, +# to avoid the time consuming +O4 link-time optimization when using +# these libraries. (The shared libs are already optimized during build +# at +O4.) +# +# This script must be run with appropriate privileges to install into +# /usr/local/ssl. HP-UX prevents used executables and shared libraries +# from being deleted or overwritten. Stop all processes using already +# installed items of OpenSSL. +# +# WARNING: At high optimization levels, HP's ANSI-C compiler can chew up +# large amounts of memory and CPU time. Make sure to have at least +# 128MB of RAM available and that your kernel is configured to allow +# at least 128MB data size (maxdsiz parameter which can be obtained +# by multiplying 'echo maxdsiz/D | adb -k /stand/vmunix /dev/kmem' +# by 'getconf PAGE_SIZE'). +# The installation process can take several hours, even on fast +# machines. +O4 optimization of the libcrypto.sl shared library may +# take 1 hour on a C200 (200MHz PA8200 CPU), +O3 compilation of +# fcrypt_b.c can take 20 minutes on this machine. Stay patient. +# +# SITEFLAGS: site specific flags. I do use +DAportable, since I have to +# support older PA1.1-type CPUs. Your mileage may vary. +# +w1 enables enhanced warnings, useful when working with snaphots. +# +SITEFLAGS="+DAportable +w1" +# +# Set the default additions to build with HP-UX. +# -D_REENTRANT must/should be defined on HP-UX manually, since we do call +# Configure directly. +# +Oall increases the optimization done. +# +MYFLAGS="-D_REENTRANT +Oall $SITEFLAGS" + +# Configure for pic and build the static pic libraries +perl5 Configure no-shared hpux-parisc-cc-o4 +Z ${MYFLAGS} +make clean +make DIRS="crypto ssl" +# Rename the static pic libs and build dynamic libraries from them +# Be prepared to see a lot of warnings about shared libraries being built +# with optimizations higher than +O2. When using these libraries, it is +# not possible to replace internal library functions with functions from +# the program to be linked. +# +make -f shlib/Makefile.hpux10-cc + +# Copy the libraries to /usr/local/ssl/lib (they have to be in their +# final location when linking applications). +# If the directories are still there, no problem. +mkdir /usr/local +mkdir /usr/local/ssl +mkdir /usr/local/ssl/lib +chmod 444 lib*_pic.a +chmod 555 lib*.sl.0.9.8 +cp -p lib*_pic.a lib*.sl.0.9.8 /usr/local/ssl/lib +(cd /usr/local/ssl/lib ; ln -sf libcrypto.sl.0.9.8 libcrypto.sl ; ln -sf libssl.sl.0.9.8 libssl.sl) + +# Reconfigure without pic to compile the executables. Unfortunately, while +# performing this task we have to recompile the library components, even +# though we use the already installed shared libs anyway. +# +perl5 Configure no-shared hpux-parisc-cc-o4 ${MYFLAGS} + +make clean + +# Hack the Makefiles to pick up the dynamic libraries during linking +# +sed 's/^PEX_LIBS=.*$/PEX_LIBS=-L\/usr\/local\/ssl\/lib/' Makefile.ssl >xxx; mv xxx Makefile.ssl +sed 's/-L\.\.//' apps/Makefile.ssl >xxx; mv xxx apps/Makefile.ssl +sed 's/-L\.\.//' test/Makefile.ssl >xxx; mv xxx test/Makefile.ssl +# Build the static libs and the executables in one make. +make +# Install everything +make install + +# Finally build the static libs with +O3. This time we only need the libraries, +# once created, they are simply copied into place. +# +perl5 Configure no-shared hpux-parisc-cc ${MYFLAGS} +make clean +make DIRS="crypto ssl" +chmod 644 libcrypto.a libssl.a +cp -p libcrypto.a libssl.a /usr/local/ssl/lib diff --git a/node-v0.8.14/deps/openssl/openssl/shlib/irix.sh b/node-v0.8.14/deps/openssl/openssl/shlib/irix.sh new file mode 100644 index 0000000..22e4e6a --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/shlib/irix.sh @@ -0,0 +1,7 @@ +FLAGS="-DTERMIOS -O2 -mips2 -DB_ENDIAN -fomit-frame-pointer -Wall -Iinclude" +SHFLAGS="-DPIC -fpic" + +gcc -c -Icrypto $SHFLAGS $FLAGS -o crypto.o crypto/crypto.c +ld -shared -o libcrypto.so crypto.o +gcc -c -Issl $SHFLAGS $FLAGS -o ssl.o ssl/ssl.c +ld -shared -o libssl.so ssl.o diff --git a/node-v0.8.14/deps/openssl/openssl/shlib/sco5-shared-gcc.sh b/node-v0.8.14/deps/openssl/openssl/shlib/sco5-shared-gcc.sh new file mode 100755 index 0000000..fe4a457 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/shlib/sco5-shared-gcc.sh @@ -0,0 +1,48 @@ +#!/bin/sh + +major="0" +minor="9.7b" + +slib=libssl +sh_slib=$slib.so.$major.$minor + +clib=libcrypto +sh_clib=$clib.so.$major.$minor + +FLAGS="-O3 -fomit-frame-pointer" +SHFLAGS="-DPIC -fPIC" + +touch $sh_clib +touch $sh_slib + +echo collecting all object files for $clib.so +OBJS= +find . -name \*.o -print > allobjs +for obj in `ar t libcrypto.a` +do + OBJS="$OBJS `grep $obj allobjs`" +done + +echo linking $clib.so +gcc -G -o $sh_clib -h $sh_clib $OBJS -lnsl -lsocket + +rm -f $clib.so +ln -s $sh_clib $clib.so + +echo collecting all object files for $slib.so +OBJS= +for obj in `ar t libssl.a` +do + OBJS="$OBJS `grep $obj allobjs`" +done + +echo linking $slib.so +gcc -G -o $sh_slib -h $sh_slib $OBJS -L. -lcrypto + +rm -f $slib.so +ln -s $sh_slib $slib.so + +mv libRSAglue.a libRSAglue.a.orig +mv libcrypto.a libcrypto.a.orig +mv libssl.a libssl.a.orig + diff --git a/node-v0.8.14/deps/openssl/openssl/shlib/sco5-shared-installed b/node-v0.8.14/deps/openssl/openssl/shlib/sco5-shared-installed new file mode 100755 index 0000000..5099028 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/shlib/sco5-shared-installed @@ -0,0 +1,28 @@ +#!/bin/sh + +major="0" +minor="9.7b" + +slib=libssl +sh_slib=$slib.so.$major.$minor + +clib=libcrypto +sh_clib=$clib.so.$major.$minor + +# If you want them in /usr/local/lib then change INSTALLTOP to point there. +#INSTALLTOP=/usr/local/ssl/lib +INSTALLTOP=/usr/local/lib + +cp -p $sh_clib $INSTALLTOP +cp -p $sh_slib $INSTALLTOP + +PWD=`pwd` +cd $INSTALLTOP +rm -f $INSTALLTOP/$clib.so +ln -s $INSTALLTOP/$sh_clib $clib.so + +rm -f $INSTALLTOP/$slib.so +ln -s $INSTALLTOP/$sh_slib $slib.so + +cd $PWD + diff --git a/node-v0.8.14/deps/openssl/openssl/shlib/sco5-shared.sh b/node-v0.8.14/deps/openssl/openssl/shlib/sco5-shared.sh new file mode 100755 index 0000000..b3365d9 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/shlib/sco5-shared.sh @@ -0,0 +1,48 @@ +#!/bin/sh + +major="0" +minor="9.7b" + +slib=libssl +sh_slib=$slib.so.$major.$minor + +clib=libcrypto +sh_clib=$clib.so.$major.$minor + +FLAGS="-O -DFILIO_H -Kalloca" +SHFLAGS="-Kpic -DPIC" + +touch $sh_clib +touch $sh_slib + +echo collecting all object files for $clib.so +OBJS= +find . -name \*.o -print > allobjs +for obj in `ar t libcrypto.a` +do + OBJS="$OBJS `grep $obj allobjs`" +done + +echo linking $clib.so +cc -G -o $sh_clib -h $sh_clib $OBJS -lnsl -lsocket + +rm -f $clib.so +ln -s $sh_clib $clib.so + +echo collecting all object files for $slib.so +OBJS= +for obj in `ar t libssl.a` +do + OBJS="$OBJS `grep $obj allobjs`" +done + +echo linking $slib.so +cc -G -o $sh_slib -h $sh_slib $OBJS -L. -lcrypto + +rm -f $slib.so +ln -s $sh_slib $slib.so + +mv libRSAglue.a libRSAglue.a.orig +mv libcrypto.a libcrypto.a.orig +mv libssl.a libssl.a.orig + diff --git a/node-v0.8.14/deps/openssl/openssl/shlib/solaris-sc4.sh b/node-v0.8.14/deps/openssl/openssl/shlib/solaris-sc4.sh new file mode 100755 index 0000000..b0766b3 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/shlib/solaris-sc4.sh @@ -0,0 +1,42 @@ +#!/bin/sh + +major="1" + +slib=libssl +sh_slib=$slib.so.$major + +clib=libcrypto +sh_clib=$clib.so.$major + +echo collecting all object files for $clib.so +OBJS= +find . -name \*.o -print > allobjs +for obj in `ar t libcrypto.a` +do + OBJS="$OBJS `grep $obj allobjs`" +done + +echo linking $clib.so +cc -G -o $sh_clib -h $sh_clib $OBJS -lnsl -lsocket + +rm -f $clib.so +ln -s $sh_clib $clib.so + +echo collecting all object files for $slib.so +OBJS= +for obj in `ar t libssl.a` +do + OBJS="$OBJS `grep $obj allobjs`" +done + +echo linking $slib.so +cc -G -o $sh_slib -h $sh_slib $OBJS -L. -lcrypto + +rm -f $slib.so +ln -s $sh_slib $slib.so + +rm -f allobjs + +mv libRSAglue.a libRSAglue.a.orig +mv libcrypto.a libcrypto.a.orig +mv libssl.a libssl.a.orig diff --git a/node-v0.8.14/deps/openssl/openssl/shlib/solaris.sh b/node-v0.8.14/deps/openssl/openssl/shlib/solaris.sh new file mode 100644 index 0000000..03475f1 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/shlib/solaris.sh @@ -0,0 +1,36 @@ +#!/bin/sh + +echo "#define DATE \"`date`\"" >crypto/date.h + +major="0" +minor="8.0" +slib=libssl +clib=libcrypto +CC=gcc +CPP='gcc -E' +AS=as +#FLAGS='-DTERMIO -O3 -DL_ENDIAN -fomit-frame-pointer -mv8 -Wall' +FLAGS='-DTERMIO -g2 -ggdb -DL_ENDIAN -Wall -DREF_CHECK -DCRYPTO_MDEBUG' +INCLUDE='-Iinclude -Icrypto -Issl' +SHFLAGS='-DPIC -fpic' + +CFLAGS="$FLAGS $INCLUDE $SHFLAGS" +ASM_OBJ=""; + +echo compiling bignum assember +$AS -o bn_asm.o crypto/bn/asm/sparc.s +CFLAGS="$CFLAGS -DBN_ASM" +ASM_OBJ="$ASM_OBJ bn_asm.o" + +echo compiling $clib +$CC -c $CFLAGS -DCFLAGS="\"$FLAGS\"" -o crypto.o crypto/crypto.c + +echo linking $clib.so +gcc $CFLAGS -shared -o $clib.so.$major.$minor crypto.o $ASM_OBJ -lnsl -lsocket + +echo compiling $slib.so +$CC -c $CFLAGS -o ssl.o ssl/ssl.c + +echo building $slib.so +gcc $CFLAGS -shared -o $slib.so ssl.o -L. -lcrypto + diff --git a/node-v0.8.14/deps/openssl/openssl/shlib/sun.sh b/node-v0.8.14/deps/openssl/openssl/shlib/sun.sh new file mode 100644 index 0000000..a890bbd --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/shlib/sun.sh @@ -0,0 +1,8 @@ +FLAGS="-DTERMIO -O3 -DB_ENDIAN -fomit-frame-pointer -mv8 -Wall -Iinclude" +SHFLAGS="-DPIC -fpic" + +gcc -c -Icrypto $SHFLAGS -fpic $FLAGS -o crypto.o crypto/crypto.c +ld -G -z text -o libcrypto.so crypto.o + +gcc -c -Issl $SHFLAGS $FLAGS -o ssl.o ssl/ssl.c +ld -G -z text -o libssl.so ssl.o diff --git a/node-v0.8.14/deps/openssl/openssl/shlib/svr5-shared-gcc.sh b/node-v0.8.14/deps/openssl/openssl/shlib/svr5-shared-gcc.sh new file mode 100755 index 0000000..c5d0cc5 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/shlib/svr5-shared-gcc.sh @@ -0,0 +1,48 @@ +#!/usr/bin/sh + +major="0" +minor="9.7b" + +slib=libssl +sh_slib=$slib.so.$major.$minor + +clib=libcrypto +sh_clib=$clib.so.$major.$minor + +FLAGS="-O3 -DFILIO_H -fomit-frame-pointer -pthread" +SHFLAGS="-DPIC -fPIC" + +touch $sh_clib +touch $sh_slib + +echo collecting all object files for $clib.so +OBJS= +find . -name \*.o -print > allobjs +for obj in `ar t libcrypto.a` +do + OBJS="$OBJS `grep $obj allobjs`" +done + +echo linking $clib.so +gcc -G -o $sh_clib -h $sh_clib $OBJS -lnsl -lsocket + +rm -f $clib.so +ln -s $sh_clib $clib.so + +echo collecting all object files for $slib.so +OBJS= +for obj in `ar t libssl.a` +do + OBJS="$OBJS `grep $obj allobjs`" +done + +echo linking $slib.so +gcc -G -o $sh_slib -h $sh_slib $OBJS -L. -lcrypto + +rm -f $slib.so +ln -s $sh_slib $slib.so + +mv libRSAglue.a libRSAglue.a.orig +mv libcrypto.a libcrypto.a.orig +mv libssl.a libssl.a.orig + diff --git a/node-v0.8.14/deps/openssl/openssl/shlib/svr5-shared-installed b/node-v0.8.14/deps/openssl/openssl/shlib/svr5-shared-installed new file mode 100755 index 0000000..b1def35 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/shlib/svr5-shared-installed @@ -0,0 +1,27 @@ +#!/usr/bin/sh + +major="0" +minor="9.7b" + +slib=libssl +sh_slib=$slib.so.$major.$minor + +clib=libcrypto +sh_clib=$clib.so.$major.$minor + +# If you want them in /usr/local/lib then change INSTALLTOP to point there. +#INSTALLTOP=/usr/local/ssl/lib +INSTALLTOP=/usr/local/lib + +cp -p $sh_clib $INSTALLTOP +cp -p $sh_slib $INSTALLTOP + +PWD=`pwd` +cd $INSTALLTOP +rm -f $INSTALLTOP/$clib.so +ln -s $INSTALLTOP/$sh_clib $clib.so + +rm -f $INSTALLTOP/$slib.so +ln -s $INSTALLTOP/$sh_slib $slib.so + +cd $PWD diff --git a/node-v0.8.14/deps/openssl/openssl/shlib/svr5-shared.sh b/node-v0.8.14/deps/openssl/openssl/shlib/svr5-shared.sh new file mode 100755 index 0000000..9edf26e --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/shlib/svr5-shared.sh @@ -0,0 +1,48 @@ +#!/usr/bin/sh + +major="0" +minor="9.7b" + +slib=libssl +sh_slib=$slib.so.$major.$minor + +clib=libcrypto +sh_clib=$clib.so.$major.$minor + +FLAGS="-O -DFILIO_H -Kalloca -Kthread" +SHFLAGS="-Kpic -DPIC" + +touch $sh_clib +touch $sh_slib + +echo collecting all object files for $clib.so +OBJS= +find . -name \*.o -print > allobjs +for obj in `ar t libcrypto.a` +do + OBJS="$OBJS `grep $obj allobjs`" +done + +echo linking $clib.so +cc -G -o $sh_clib -h $sh_clib $OBJS -lnsl -lsocket + +rm -f $clib.so +ln -s $sh_clib $clib.so + +echo collecting all object files for $slib.so +OBJS= +for obj in `ar t libssl.a` +do + OBJS="$OBJS `grep $obj allobjs`" +done + +echo linking $slib.so +cc -G -o $sh_slib -h $sh_slib $OBJS -L. -lcrypto + +rm -f $slib.so +ln -s $sh_slib $slib.so + +mv libRSAglue.a libRSAglue.a.orig +mv libcrypto.a libcrypto.a.orig +mv libssl.a libssl.a.orig + diff --git a/node-v0.8.14/deps/openssl/openssl/shlib/win32.bat b/node-v0.8.14/deps/openssl/openssl/shlib/win32.bat new file mode 100755 index 0000000..2b0faaa --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/shlib/win32.bat @@ -0,0 +1,18 @@ +rem win32 dll build + +set OPTIONS1=-DDES_ASM -DBN_ASM -DBF_ASM -DFLAT_INC -Iout -Itmp -DL_ENDIAN +set OPTIONS2=/W3 /WX /Ox /Gs0 /GF /Gy /nologo + +set OPTIONS=%OPTIONS1% %OPTIONS2% + +rem ml /coff /c crypto\bf\asm\b-win32.asm +rem ml /coff /c crypto\des\asm\c-win32.asm +rem ml /coff /c crypto\des\asm\d-win32.asm +rem ml /coff /c crypto\bn\asm\x86nt32.asm + +cl /Focrypto.obj -DWIN32 %OPTIONS% -c crypto\crypto.c +cl /Fossl.obj -DWIN32 %OPTIONS% -c ssl\ssl.c +cl /Foeay.obj -DWIN32 %OPTIONS% -c apps\eay.c + +cl /Fessleay.exe %OPTIONS% eay.obj ssl.obj crypto.obj crypto\bf\asm\b-win32.obj crypto\des\asm\c-win32.obj crypto\des\asm\d-win32.obj crypto\bn\asm\x86nt32.obj user32.lib gdi32.lib ws2_32.lib + diff --git a/node-v0.8.14/deps/openssl/openssl/shlib/win32dll.bat b/node-v0.8.14/deps/openssl/openssl/shlib/win32dll.bat new file mode 100755 index 0000000..844e353 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/shlib/win32dll.bat @@ -0,0 +1,13 @@ +rem win32 dll build + +set OPTIONS1=-DDES_ASM -DBN_ASM -DBF_ASM -DFLAT_INC -Iout -Itmp -DL_ENDIAN +set OPTIONS2=/W3 /WX /Ox /Gf /nologo + +set OPTIONS=%OPTIONS1% %OPTIONS2% + +cl /Felibeay32.dll /GD /MD /LD -DWIN32 %OPTIONS% ms\libeay32.def crypto\crypto.c crypto\bf\asm\b-win32.obj crypto\des\asm\c-win32.obj crypto\des\asm\d-win32.obj crypto\bn\asm\x86nt32.obj user32.lib gdi32.lib ws2_32.lib + +cl /Fessleay32.dll /GD /MD /LD -DWIN32 %OPTIONS% ms\ssleay32.def ssl\ssl.c libeay32.lib + +cl /Fessleay.exe /MD -DWIN32 %OPTIONS% apps\eay.c ssleay32.lib libeay32.lib user32.lib ws2_32.lib + diff --git a/node-v0.8.14/deps/openssl/openssl/ssl/Makefile b/node-v0.8.14/deps/openssl/openssl/ssl/Makefile new file mode 100644 index 0000000..2b275fa --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/ssl/Makefile @@ -0,0 +1,975 @@ +# +# OpenSSL/ssl/Makefile +# + +DIR= ssl +TOP= .. +CC= cc +INCLUDES= -I../crypto -I$(TOP) -I../include $(KRB5_INCLUDES) +CFLAG=-g +MAKEFILE= Makefile +AR= ar r +# KRB5 stuff +KRB5_INCLUDES= + +CFLAGS= $(INCLUDES) $(CFLAG) + +GENERAL=Makefile README ssl-lib.com install.com +TEST=ssltest.c +APPS= + +LIB=$(TOP)/libssl.a +SHARED_LIB= libssl$(SHLIB_EXT) +LIBSRC= \ + s2_meth.c s2_srvr.c s2_clnt.c s2_lib.c s2_enc.c s2_pkt.c \ + s3_meth.c s3_srvr.c s3_clnt.c s3_lib.c s3_enc.c s3_pkt.c s3_both.c \ + s23_meth.c s23_srvr.c s23_clnt.c s23_lib.c s23_pkt.c \ + t1_meth.c t1_srvr.c t1_clnt.c t1_lib.c t1_enc.c \ + d1_meth.c d1_srvr.c d1_clnt.c d1_lib.c d1_pkt.c \ + d1_both.c d1_enc.c \ + ssl_lib.c ssl_err2.c ssl_cert.c ssl_sess.c \ + ssl_ciph.c ssl_stat.c ssl_rsa.c \ + ssl_asn1.c ssl_txt.c ssl_algs.c \ + bio_ssl.c ssl_err.c kssl.c t1_reneg.c +LIBOBJ= \ + s2_meth.o s2_srvr.o s2_clnt.o s2_lib.o s2_enc.o s2_pkt.o \ + s3_meth.o s3_srvr.o s3_clnt.o s3_lib.o s3_enc.o s3_pkt.o s3_both.o \ + s23_meth.o s23_srvr.o s23_clnt.o s23_lib.o s23_pkt.o \ + t1_meth.o t1_srvr.o t1_clnt.o t1_lib.o t1_enc.o \ + d1_meth.o d1_srvr.o d1_clnt.o d1_lib.o d1_pkt.o \ + d1_both.o d1_enc.o \ + ssl_lib.o ssl_err2.o ssl_cert.o ssl_sess.o \ + ssl_ciph.o ssl_stat.o ssl_rsa.o \ + ssl_asn1.o ssl_txt.o ssl_algs.o \ + bio_ssl.o ssl_err.o kssl.o t1_reneg.o + +SRC= $(LIBSRC) + +EXHEADER= ssl.h ssl2.h ssl3.h ssl23.h tls1.h dtls1.h kssl.h +HEADER= $(EXHEADER) ssl_locl.h kssl_lcl.h + +ALL= $(GENERAL) $(SRC) $(HEADER) + +top: + (cd ..; $(MAKE) DIRS=$(DIR) all) + +all: shared + +lib: $(LIBOBJ) + $(AR) $(LIB) $(LIBOBJ) + $(RANLIB) $(LIB) || echo Never mind. + @touch lib + +shared: lib + if [ -n "$(SHARED_LIBS)" ]; then \ + (cd ..; $(MAKE) $(SHARED_LIB)); \ + fi + +files: + $(PERL) $(TOP)/util/files.pl Makefile >> $(TOP)/MINFO + +links: + @$(PERL) $(TOP)/util/mklink.pl ../include/openssl $(EXHEADER) + @$(PERL) $(TOP)/util/mklink.pl ../test $(TEST) + @$(PERL) $(TOP)/util/mklink.pl ../apps $(APPS) + +install: + @[ -n "$(INSTALLTOP)" ] # should be set by top Makefile... + @headerlist="$(EXHEADER)"; for i in $$headerlist ; \ + do \ + (cp $$i $(INSTALL_PREFIX)$(INSTALLTOP)/include/openssl/$$i; \ + chmod 644 $(INSTALL_PREFIX)$(INSTALLTOP)/include/openssl/$$i ); \ + done; + +tags: + ctags $(SRC) + +tests: + +lint: + lint -DLINT $(INCLUDES) $(SRC)>fluff + +depend: + @if [ -z "$(THIS)" ]; then \ + $(MAKE) -f $(TOP)/Makefile reflect THIS=$@; \ + else \ + $(MAKEDEPEND) -- $(CFLAG) $(INCLUDES) $(DEPFLAG) -- $(PROGS) $(LIBSRC); \ + fi + +dclean: + $(PERL) -pe 'if (/^# DO NOT DELETE THIS LINE/) {print; exit(0);}' $(MAKEFILE) >Makefile.new + mv -f Makefile.new $(MAKEFILE) + +clean: + rm -f *.o *.obj lib tags core .pure .nfs* *.old *.bak fluff + +# DO NOT DELETE THIS LINE -- make depend depends on it. + +bio_ssl.o: ../include/openssl/asn1.h ../include/openssl/bio.h +bio_ssl.o: ../include/openssl/buffer.h ../include/openssl/comp.h +bio_ssl.o: ../include/openssl/crypto.h ../include/openssl/dtls1.h +bio_ssl.o: ../include/openssl/e_os2.h ../include/openssl/ec.h +bio_ssl.o: ../include/openssl/ecdh.h ../include/openssl/ecdsa.h +bio_ssl.o: ../include/openssl/err.h ../include/openssl/evp.h +bio_ssl.o: ../include/openssl/hmac.h ../include/openssl/kssl.h +bio_ssl.o: ../include/openssl/lhash.h ../include/openssl/obj_mac.h +bio_ssl.o: ../include/openssl/objects.h ../include/openssl/opensslconf.h +bio_ssl.o: ../include/openssl/opensslv.h ../include/openssl/ossl_typ.h +bio_ssl.o: ../include/openssl/pem.h ../include/openssl/pem2.h +bio_ssl.o: ../include/openssl/pkcs7.h ../include/openssl/pqueue.h +bio_ssl.o: ../include/openssl/safestack.h ../include/openssl/sha.h +bio_ssl.o: ../include/openssl/ssl.h ../include/openssl/ssl2.h +bio_ssl.o: ../include/openssl/ssl23.h ../include/openssl/ssl3.h +bio_ssl.o: ../include/openssl/stack.h ../include/openssl/symhacks.h +bio_ssl.o: ../include/openssl/tls1.h ../include/openssl/x509.h +bio_ssl.o: ../include/openssl/x509_vfy.h bio_ssl.c +d1_both.o: ../e_os.h ../include/openssl/asn1.h ../include/openssl/bio.h +d1_both.o: ../include/openssl/buffer.h ../include/openssl/comp.h +d1_both.o: ../include/openssl/crypto.h ../include/openssl/dsa.h +d1_both.o: ../include/openssl/dtls1.h ../include/openssl/e_os2.h +d1_both.o: ../include/openssl/ec.h ../include/openssl/ecdh.h +d1_both.o: ../include/openssl/ecdsa.h ../include/openssl/err.h +d1_both.o: ../include/openssl/evp.h ../include/openssl/hmac.h +d1_both.o: ../include/openssl/kssl.h ../include/openssl/lhash.h +d1_both.o: ../include/openssl/obj_mac.h ../include/openssl/objects.h +d1_both.o: ../include/openssl/opensslconf.h ../include/openssl/opensslv.h +d1_both.o: ../include/openssl/ossl_typ.h ../include/openssl/pem.h +d1_both.o: ../include/openssl/pem2.h ../include/openssl/pkcs7.h +d1_both.o: ../include/openssl/pqueue.h ../include/openssl/rand.h +d1_both.o: ../include/openssl/rsa.h ../include/openssl/safestack.h +d1_both.o: ../include/openssl/sha.h ../include/openssl/ssl.h +d1_both.o: ../include/openssl/ssl2.h ../include/openssl/ssl23.h +d1_both.o: ../include/openssl/ssl3.h ../include/openssl/stack.h +d1_both.o: ../include/openssl/symhacks.h ../include/openssl/tls1.h +d1_both.o: ../include/openssl/x509.h ../include/openssl/x509_vfy.h d1_both.c +d1_both.o: ssl_locl.h +d1_clnt.o: ../e_os.h ../include/openssl/asn1.h ../include/openssl/bio.h +d1_clnt.o: ../include/openssl/bn.h ../include/openssl/buffer.h +d1_clnt.o: ../include/openssl/comp.h ../include/openssl/crypto.h +d1_clnt.o: ../include/openssl/dh.h ../include/openssl/dsa.h +d1_clnt.o: ../include/openssl/dtls1.h ../include/openssl/e_os2.h +d1_clnt.o: ../include/openssl/ec.h ../include/openssl/ecdh.h +d1_clnt.o: ../include/openssl/ecdsa.h ../include/openssl/err.h +d1_clnt.o: ../include/openssl/evp.h ../include/openssl/hmac.h +d1_clnt.o: ../include/openssl/kssl.h ../include/openssl/lhash.h +d1_clnt.o: ../include/openssl/md5.h ../include/openssl/obj_mac.h +d1_clnt.o: ../include/openssl/objects.h ../include/openssl/opensslconf.h +d1_clnt.o: ../include/openssl/opensslv.h ../include/openssl/ossl_typ.h +d1_clnt.o: ../include/openssl/pem.h ../include/openssl/pem2.h +d1_clnt.o: ../include/openssl/pkcs7.h ../include/openssl/pqueue.h +d1_clnt.o: ../include/openssl/rand.h ../include/openssl/rsa.h +d1_clnt.o: ../include/openssl/safestack.h ../include/openssl/sha.h +d1_clnt.o: ../include/openssl/ssl.h ../include/openssl/ssl2.h +d1_clnt.o: ../include/openssl/ssl23.h ../include/openssl/ssl3.h +d1_clnt.o: ../include/openssl/stack.h ../include/openssl/symhacks.h +d1_clnt.o: ../include/openssl/tls1.h ../include/openssl/x509.h +d1_clnt.o: ../include/openssl/x509_vfy.h d1_clnt.c kssl_lcl.h ssl_locl.h +d1_enc.o: ../e_os.h ../include/openssl/asn1.h ../include/openssl/bio.h +d1_enc.o: ../include/openssl/buffer.h ../include/openssl/comp.h +d1_enc.o: ../include/openssl/crypto.h ../include/openssl/dsa.h +d1_enc.o: ../include/openssl/dtls1.h ../include/openssl/e_os2.h +d1_enc.o: ../include/openssl/ec.h ../include/openssl/ecdh.h +d1_enc.o: ../include/openssl/ecdsa.h ../include/openssl/err.h +d1_enc.o: ../include/openssl/evp.h ../include/openssl/hmac.h +d1_enc.o: ../include/openssl/kssl.h ../include/openssl/lhash.h +d1_enc.o: ../include/openssl/md5.h ../include/openssl/obj_mac.h +d1_enc.o: ../include/openssl/objects.h ../include/openssl/opensslconf.h +d1_enc.o: ../include/openssl/opensslv.h ../include/openssl/ossl_typ.h +d1_enc.o: ../include/openssl/pem.h ../include/openssl/pem2.h +d1_enc.o: ../include/openssl/pkcs7.h ../include/openssl/pqueue.h +d1_enc.o: ../include/openssl/rand.h ../include/openssl/rsa.h +d1_enc.o: ../include/openssl/safestack.h ../include/openssl/sha.h +d1_enc.o: ../include/openssl/ssl.h ../include/openssl/ssl2.h +d1_enc.o: ../include/openssl/ssl23.h ../include/openssl/ssl3.h +d1_enc.o: ../include/openssl/stack.h ../include/openssl/symhacks.h +d1_enc.o: ../include/openssl/tls1.h ../include/openssl/x509.h +d1_enc.o: ../include/openssl/x509_vfy.h d1_enc.c ssl_locl.h +d1_lib.o: ../e_os.h ../include/openssl/asn1.h ../include/openssl/bio.h +d1_lib.o: ../include/openssl/buffer.h ../include/openssl/comp.h +d1_lib.o: ../include/openssl/crypto.h ../include/openssl/dsa.h +d1_lib.o: ../include/openssl/dtls1.h ../include/openssl/e_os2.h +d1_lib.o: ../include/openssl/ec.h ../include/openssl/ecdh.h +d1_lib.o: ../include/openssl/ecdsa.h ../include/openssl/err.h +d1_lib.o: ../include/openssl/evp.h ../include/openssl/hmac.h +d1_lib.o: ../include/openssl/kssl.h ../include/openssl/lhash.h +d1_lib.o: ../include/openssl/obj_mac.h ../include/openssl/objects.h +d1_lib.o: ../include/openssl/opensslconf.h ../include/openssl/opensslv.h +d1_lib.o: ../include/openssl/ossl_typ.h ../include/openssl/pem.h +d1_lib.o: ../include/openssl/pem2.h ../include/openssl/pkcs7.h +d1_lib.o: ../include/openssl/pqueue.h ../include/openssl/rsa.h +d1_lib.o: ../include/openssl/safestack.h ../include/openssl/sha.h +d1_lib.o: ../include/openssl/ssl.h ../include/openssl/ssl2.h +d1_lib.o: ../include/openssl/ssl23.h ../include/openssl/ssl3.h +d1_lib.o: ../include/openssl/stack.h ../include/openssl/symhacks.h +d1_lib.o: ../include/openssl/tls1.h ../include/openssl/x509.h +d1_lib.o: ../include/openssl/x509_vfy.h d1_lib.c ssl_locl.h +d1_meth.o: ../e_os.h ../include/openssl/asn1.h ../include/openssl/bio.h +d1_meth.o: ../include/openssl/buffer.h ../include/openssl/comp.h +d1_meth.o: ../include/openssl/crypto.h ../include/openssl/dsa.h +d1_meth.o: ../include/openssl/dtls1.h ../include/openssl/e_os2.h +d1_meth.o: ../include/openssl/ec.h ../include/openssl/ecdh.h +d1_meth.o: ../include/openssl/ecdsa.h ../include/openssl/err.h +d1_meth.o: ../include/openssl/evp.h ../include/openssl/hmac.h +d1_meth.o: ../include/openssl/kssl.h ../include/openssl/lhash.h +d1_meth.o: ../include/openssl/obj_mac.h ../include/openssl/objects.h +d1_meth.o: ../include/openssl/opensslconf.h ../include/openssl/opensslv.h +d1_meth.o: ../include/openssl/ossl_typ.h ../include/openssl/pem.h +d1_meth.o: ../include/openssl/pem2.h ../include/openssl/pkcs7.h +d1_meth.o: ../include/openssl/pqueue.h ../include/openssl/rsa.h +d1_meth.o: ../include/openssl/safestack.h ../include/openssl/sha.h +d1_meth.o: ../include/openssl/ssl.h ../include/openssl/ssl2.h +d1_meth.o: ../include/openssl/ssl23.h ../include/openssl/ssl3.h +d1_meth.o: ../include/openssl/stack.h ../include/openssl/symhacks.h +d1_meth.o: ../include/openssl/tls1.h ../include/openssl/x509.h +d1_meth.o: ../include/openssl/x509_vfy.h d1_meth.c ssl_locl.h +d1_pkt.o: ../e_os.h ../include/openssl/asn1.h ../include/openssl/bio.h +d1_pkt.o: ../include/openssl/buffer.h ../include/openssl/comp.h +d1_pkt.o: ../include/openssl/crypto.h ../include/openssl/dsa.h +d1_pkt.o: ../include/openssl/dtls1.h ../include/openssl/e_os2.h +d1_pkt.o: ../include/openssl/ec.h ../include/openssl/ecdh.h +d1_pkt.o: ../include/openssl/ecdsa.h ../include/openssl/err.h +d1_pkt.o: ../include/openssl/evp.h ../include/openssl/hmac.h +d1_pkt.o: ../include/openssl/kssl.h ../include/openssl/lhash.h +d1_pkt.o: ../include/openssl/obj_mac.h ../include/openssl/objects.h +d1_pkt.o: ../include/openssl/opensslconf.h ../include/openssl/opensslv.h +d1_pkt.o: ../include/openssl/ossl_typ.h ../include/openssl/pem.h +d1_pkt.o: ../include/openssl/pem2.h ../include/openssl/pkcs7.h +d1_pkt.o: ../include/openssl/pqueue.h ../include/openssl/rand.h +d1_pkt.o: ../include/openssl/rsa.h ../include/openssl/safestack.h +d1_pkt.o: ../include/openssl/sha.h ../include/openssl/ssl.h +d1_pkt.o: ../include/openssl/ssl2.h ../include/openssl/ssl23.h +d1_pkt.o: ../include/openssl/ssl3.h ../include/openssl/stack.h +d1_pkt.o: ../include/openssl/symhacks.h ../include/openssl/tls1.h +d1_pkt.o: ../include/openssl/x509.h ../include/openssl/x509_vfy.h d1_pkt.c +d1_pkt.o: ssl_locl.h +d1_srvr.o: ../e_os.h ../include/openssl/asn1.h ../include/openssl/bio.h +d1_srvr.o: ../include/openssl/bn.h ../include/openssl/buffer.h +d1_srvr.o: ../include/openssl/comp.h ../include/openssl/crypto.h +d1_srvr.o: ../include/openssl/dh.h ../include/openssl/dsa.h +d1_srvr.o: ../include/openssl/dtls1.h ../include/openssl/e_os2.h +d1_srvr.o: ../include/openssl/ec.h ../include/openssl/ecdh.h +d1_srvr.o: ../include/openssl/ecdsa.h ../include/openssl/err.h +d1_srvr.o: ../include/openssl/evp.h ../include/openssl/hmac.h +d1_srvr.o: ../include/openssl/kssl.h ../include/openssl/lhash.h +d1_srvr.o: ../include/openssl/md5.h ../include/openssl/obj_mac.h +d1_srvr.o: ../include/openssl/objects.h ../include/openssl/opensslconf.h +d1_srvr.o: ../include/openssl/opensslv.h ../include/openssl/ossl_typ.h +d1_srvr.o: ../include/openssl/pem.h ../include/openssl/pem2.h +d1_srvr.o: ../include/openssl/pkcs7.h ../include/openssl/pqueue.h +d1_srvr.o: ../include/openssl/rand.h ../include/openssl/rsa.h +d1_srvr.o: ../include/openssl/safestack.h ../include/openssl/sha.h +d1_srvr.o: ../include/openssl/ssl.h ../include/openssl/ssl2.h +d1_srvr.o: ../include/openssl/ssl23.h ../include/openssl/ssl3.h +d1_srvr.o: ../include/openssl/stack.h ../include/openssl/symhacks.h +d1_srvr.o: ../include/openssl/tls1.h ../include/openssl/x509.h +d1_srvr.o: ../include/openssl/x509_vfy.h d1_srvr.c ssl_locl.h +kssl.o: ../include/openssl/asn1.h ../include/openssl/bio.h +kssl.o: ../include/openssl/buffer.h ../include/openssl/comp.h +kssl.o: ../include/openssl/crypto.h ../include/openssl/dtls1.h +kssl.o: ../include/openssl/e_os2.h ../include/openssl/ec.h +kssl.o: ../include/openssl/ecdh.h ../include/openssl/ecdsa.h +kssl.o: ../include/openssl/evp.h ../include/openssl/hmac.h +kssl.o: ../include/openssl/krb5_asn.h ../include/openssl/kssl.h +kssl.o: ../include/openssl/lhash.h ../include/openssl/obj_mac.h +kssl.o: ../include/openssl/objects.h ../include/openssl/opensslconf.h +kssl.o: ../include/openssl/opensslv.h ../include/openssl/ossl_typ.h +kssl.o: ../include/openssl/pem.h ../include/openssl/pem2.h +kssl.o: ../include/openssl/pkcs7.h ../include/openssl/pqueue.h +kssl.o: ../include/openssl/safestack.h ../include/openssl/sha.h +kssl.o: ../include/openssl/ssl.h ../include/openssl/ssl2.h +kssl.o: ../include/openssl/ssl23.h ../include/openssl/ssl3.h +kssl.o: ../include/openssl/stack.h ../include/openssl/symhacks.h +kssl.o: ../include/openssl/tls1.h ../include/openssl/x509.h +kssl.o: ../include/openssl/x509_vfy.h kssl.c kssl_lcl.h +s23_clnt.o: ../e_os.h ../include/openssl/asn1.h ../include/openssl/bio.h +s23_clnt.o: ../include/openssl/buffer.h ../include/openssl/comp.h +s23_clnt.o: ../include/openssl/crypto.h ../include/openssl/dsa.h +s23_clnt.o: ../include/openssl/dtls1.h ../include/openssl/e_os2.h +s23_clnt.o: ../include/openssl/ec.h ../include/openssl/ecdh.h +s23_clnt.o: ../include/openssl/ecdsa.h ../include/openssl/err.h +s23_clnt.o: ../include/openssl/evp.h ../include/openssl/hmac.h +s23_clnt.o: ../include/openssl/kssl.h ../include/openssl/lhash.h +s23_clnt.o: ../include/openssl/obj_mac.h ../include/openssl/objects.h +s23_clnt.o: ../include/openssl/opensslconf.h ../include/openssl/opensslv.h +s23_clnt.o: ../include/openssl/ossl_typ.h ../include/openssl/pem.h +s23_clnt.o: ../include/openssl/pem2.h ../include/openssl/pkcs7.h +s23_clnt.o: ../include/openssl/pqueue.h ../include/openssl/rand.h +s23_clnt.o: ../include/openssl/rsa.h ../include/openssl/safestack.h +s23_clnt.o: ../include/openssl/sha.h ../include/openssl/ssl.h +s23_clnt.o: ../include/openssl/ssl2.h ../include/openssl/ssl23.h +s23_clnt.o: ../include/openssl/ssl3.h ../include/openssl/stack.h +s23_clnt.o: ../include/openssl/symhacks.h ../include/openssl/tls1.h +s23_clnt.o: ../include/openssl/x509.h ../include/openssl/x509_vfy.h s23_clnt.c +s23_clnt.o: ssl_locl.h +s23_lib.o: ../e_os.h ../include/openssl/asn1.h ../include/openssl/bio.h +s23_lib.o: ../include/openssl/buffer.h ../include/openssl/comp.h +s23_lib.o: ../include/openssl/crypto.h ../include/openssl/dsa.h +s23_lib.o: ../include/openssl/dtls1.h ../include/openssl/e_os2.h +s23_lib.o: ../include/openssl/ec.h ../include/openssl/ecdh.h +s23_lib.o: ../include/openssl/ecdsa.h ../include/openssl/err.h +s23_lib.o: ../include/openssl/evp.h ../include/openssl/hmac.h +s23_lib.o: ../include/openssl/kssl.h ../include/openssl/lhash.h +s23_lib.o: ../include/openssl/obj_mac.h ../include/openssl/objects.h +s23_lib.o: ../include/openssl/opensslconf.h ../include/openssl/opensslv.h +s23_lib.o: ../include/openssl/ossl_typ.h ../include/openssl/pem.h +s23_lib.o: ../include/openssl/pem2.h ../include/openssl/pkcs7.h +s23_lib.o: ../include/openssl/pqueue.h ../include/openssl/rsa.h +s23_lib.o: ../include/openssl/safestack.h ../include/openssl/sha.h +s23_lib.o: ../include/openssl/ssl.h ../include/openssl/ssl2.h +s23_lib.o: ../include/openssl/ssl23.h ../include/openssl/ssl3.h +s23_lib.o: ../include/openssl/stack.h ../include/openssl/symhacks.h +s23_lib.o: ../include/openssl/tls1.h ../include/openssl/x509.h +s23_lib.o: ../include/openssl/x509_vfy.h s23_lib.c ssl_locl.h +s23_meth.o: ../e_os.h ../include/openssl/asn1.h ../include/openssl/bio.h +s23_meth.o: ../include/openssl/buffer.h ../include/openssl/comp.h +s23_meth.o: ../include/openssl/crypto.h ../include/openssl/dsa.h +s23_meth.o: ../include/openssl/dtls1.h ../include/openssl/e_os2.h +s23_meth.o: ../include/openssl/ec.h ../include/openssl/ecdh.h +s23_meth.o: ../include/openssl/ecdsa.h ../include/openssl/err.h +s23_meth.o: ../include/openssl/evp.h ../include/openssl/hmac.h +s23_meth.o: ../include/openssl/kssl.h ../include/openssl/lhash.h +s23_meth.o: ../include/openssl/obj_mac.h ../include/openssl/objects.h +s23_meth.o: ../include/openssl/opensslconf.h ../include/openssl/opensslv.h +s23_meth.o: ../include/openssl/ossl_typ.h ../include/openssl/pem.h +s23_meth.o: ../include/openssl/pem2.h ../include/openssl/pkcs7.h +s23_meth.o: ../include/openssl/pqueue.h ../include/openssl/rsa.h +s23_meth.o: ../include/openssl/safestack.h ../include/openssl/sha.h +s23_meth.o: ../include/openssl/ssl.h ../include/openssl/ssl2.h +s23_meth.o: ../include/openssl/ssl23.h ../include/openssl/ssl3.h +s23_meth.o: ../include/openssl/stack.h ../include/openssl/symhacks.h +s23_meth.o: ../include/openssl/tls1.h ../include/openssl/x509.h +s23_meth.o: ../include/openssl/x509_vfy.h s23_meth.c ssl_locl.h +s23_pkt.o: ../e_os.h ../include/openssl/asn1.h ../include/openssl/bio.h +s23_pkt.o: ../include/openssl/buffer.h ../include/openssl/comp.h +s23_pkt.o: ../include/openssl/crypto.h ../include/openssl/dsa.h +s23_pkt.o: ../include/openssl/dtls1.h ../include/openssl/e_os2.h +s23_pkt.o: ../include/openssl/ec.h ../include/openssl/ecdh.h +s23_pkt.o: ../include/openssl/ecdsa.h ../include/openssl/err.h +s23_pkt.o: ../include/openssl/evp.h ../include/openssl/hmac.h +s23_pkt.o: ../include/openssl/kssl.h ../include/openssl/lhash.h +s23_pkt.o: ../include/openssl/obj_mac.h ../include/openssl/objects.h +s23_pkt.o: ../include/openssl/opensslconf.h ../include/openssl/opensslv.h +s23_pkt.o: ../include/openssl/ossl_typ.h ../include/openssl/pem.h +s23_pkt.o: ../include/openssl/pem2.h ../include/openssl/pkcs7.h +s23_pkt.o: ../include/openssl/pqueue.h ../include/openssl/rsa.h +s23_pkt.o: ../include/openssl/safestack.h ../include/openssl/sha.h +s23_pkt.o: ../include/openssl/ssl.h ../include/openssl/ssl2.h +s23_pkt.o: ../include/openssl/ssl23.h ../include/openssl/ssl3.h +s23_pkt.o: ../include/openssl/stack.h ../include/openssl/symhacks.h +s23_pkt.o: ../include/openssl/tls1.h ../include/openssl/x509.h +s23_pkt.o: ../include/openssl/x509_vfy.h s23_pkt.c ssl_locl.h +s23_srvr.o: ../e_os.h ../include/openssl/asn1.h ../include/openssl/bio.h +s23_srvr.o: ../include/openssl/buffer.h ../include/openssl/comp.h +s23_srvr.o: ../include/openssl/crypto.h ../include/openssl/dsa.h +s23_srvr.o: ../include/openssl/dtls1.h ../include/openssl/e_os2.h +s23_srvr.o: ../include/openssl/ec.h ../include/openssl/ecdh.h +s23_srvr.o: ../include/openssl/ecdsa.h ../include/openssl/err.h +s23_srvr.o: ../include/openssl/evp.h ../include/openssl/hmac.h +s23_srvr.o: ../include/openssl/kssl.h ../include/openssl/lhash.h +s23_srvr.o: ../include/openssl/obj_mac.h ../include/openssl/objects.h +s23_srvr.o: ../include/openssl/opensslconf.h ../include/openssl/opensslv.h +s23_srvr.o: ../include/openssl/ossl_typ.h ../include/openssl/pem.h +s23_srvr.o: ../include/openssl/pem2.h ../include/openssl/pkcs7.h +s23_srvr.o: ../include/openssl/pqueue.h ../include/openssl/rand.h +s23_srvr.o: ../include/openssl/rsa.h ../include/openssl/safestack.h +s23_srvr.o: ../include/openssl/sha.h ../include/openssl/ssl.h +s23_srvr.o: ../include/openssl/ssl2.h ../include/openssl/ssl23.h +s23_srvr.o: ../include/openssl/ssl3.h ../include/openssl/stack.h +s23_srvr.o: ../include/openssl/symhacks.h ../include/openssl/tls1.h +s23_srvr.o: ../include/openssl/x509.h ../include/openssl/x509_vfy.h s23_srvr.c +s23_srvr.o: ssl_locl.h +s2_clnt.o: ../e_os.h ../include/openssl/asn1.h ../include/openssl/bio.h +s2_clnt.o: ../include/openssl/buffer.h ../include/openssl/comp.h +s2_clnt.o: ../include/openssl/crypto.h ../include/openssl/dsa.h +s2_clnt.o: ../include/openssl/dtls1.h ../include/openssl/e_os2.h +s2_clnt.o: ../include/openssl/ec.h ../include/openssl/ecdh.h +s2_clnt.o: ../include/openssl/ecdsa.h ../include/openssl/err.h +s2_clnt.o: ../include/openssl/evp.h ../include/openssl/hmac.h +s2_clnt.o: ../include/openssl/kssl.h ../include/openssl/lhash.h +s2_clnt.o: ../include/openssl/obj_mac.h ../include/openssl/objects.h +s2_clnt.o: ../include/openssl/opensslconf.h ../include/openssl/opensslv.h +s2_clnt.o: ../include/openssl/ossl_typ.h ../include/openssl/pem.h +s2_clnt.o: ../include/openssl/pem2.h ../include/openssl/pkcs7.h +s2_clnt.o: ../include/openssl/pqueue.h ../include/openssl/rand.h +s2_clnt.o: ../include/openssl/rsa.h ../include/openssl/safestack.h +s2_clnt.o: ../include/openssl/sha.h ../include/openssl/ssl.h +s2_clnt.o: ../include/openssl/ssl2.h ../include/openssl/ssl23.h +s2_clnt.o: ../include/openssl/ssl3.h ../include/openssl/stack.h +s2_clnt.o: ../include/openssl/symhacks.h ../include/openssl/tls1.h +s2_clnt.o: ../include/openssl/x509.h ../include/openssl/x509_vfy.h s2_clnt.c +s2_clnt.o: ssl_locl.h +s2_enc.o: ../e_os.h ../include/openssl/asn1.h ../include/openssl/bio.h +s2_enc.o: ../include/openssl/buffer.h ../include/openssl/comp.h +s2_enc.o: ../include/openssl/crypto.h ../include/openssl/dsa.h +s2_enc.o: ../include/openssl/dtls1.h ../include/openssl/e_os2.h +s2_enc.o: ../include/openssl/ec.h ../include/openssl/ecdh.h +s2_enc.o: ../include/openssl/ecdsa.h ../include/openssl/err.h +s2_enc.o: ../include/openssl/evp.h ../include/openssl/hmac.h +s2_enc.o: ../include/openssl/kssl.h ../include/openssl/lhash.h +s2_enc.o: ../include/openssl/obj_mac.h ../include/openssl/objects.h +s2_enc.o: ../include/openssl/opensslconf.h ../include/openssl/opensslv.h +s2_enc.o: ../include/openssl/ossl_typ.h ../include/openssl/pem.h +s2_enc.o: ../include/openssl/pem2.h ../include/openssl/pkcs7.h +s2_enc.o: ../include/openssl/pqueue.h ../include/openssl/rsa.h +s2_enc.o: ../include/openssl/safestack.h ../include/openssl/sha.h +s2_enc.o: ../include/openssl/ssl.h ../include/openssl/ssl2.h +s2_enc.o: ../include/openssl/ssl23.h ../include/openssl/ssl3.h +s2_enc.o: ../include/openssl/stack.h ../include/openssl/symhacks.h +s2_enc.o: ../include/openssl/tls1.h ../include/openssl/x509.h +s2_enc.o: ../include/openssl/x509_vfy.h s2_enc.c ssl_locl.h +s2_lib.o: ../e_os.h ../include/openssl/asn1.h ../include/openssl/bio.h +s2_lib.o: ../include/openssl/buffer.h ../include/openssl/comp.h +s2_lib.o: ../include/openssl/crypto.h ../include/openssl/dsa.h +s2_lib.o: ../include/openssl/dtls1.h ../include/openssl/e_os2.h +s2_lib.o: ../include/openssl/ec.h ../include/openssl/ecdh.h +s2_lib.o: ../include/openssl/ecdsa.h ../include/openssl/err.h +s2_lib.o: ../include/openssl/evp.h ../include/openssl/hmac.h +s2_lib.o: ../include/openssl/kssl.h ../include/openssl/lhash.h +s2_lib.o: ../include/openssl/md5.h ../include/openssl/obj_mac.h +s2_lib.o: ../include/openssl/objects.h ../include/openssl/opensslconf.h +s2_lib.o: ../include/openssl/opensslv.h ../include/openssl/ossl_typ.h +s2_lib.o: ../include/openssl/pem.h ../include/openssl/pem2.h +s2_lib.o: ../include/openssl/pkcs7.h ../include/openssl/pqueue.h +s2_lib.o: ../include/openssl/rsa.h ../include/openssl/safestack.h +s2_lib.o: ../include/openssl/sha.h ../include/openssl/ssl.h +s2_lib.o: ../include/openssl/ssl2.h ../include/openssl/ssl23.h +s2_lib.o: ../include/openssl/ssl3.h ../include/openssl/stack.h +s2_lib.o: ../include/openssl/symhacks.h ../include/openssl/tls1.h +s2_lib.o: ../include/openssl/x509.h ../include/openssl/x509_vfy.h s2_lib.c +s2_lib.o: ssl_locl.h +s2_meth.o: ../e_os.h ../include/openssl/asn1.h ../include/openssl/bio.h +s2_meth.o: ../include/openssl/buffer.h ../include/openssl/comp.h +s2_meth.o: ../include/openssl/crypto.h ../include/openssl/dsa.h +s2_meth.o: ../include/openssl/dtls1.h ../include/openssl/e_os2.h +s2_meth.o: ../include/openssl/ec.h ../include/openssl/ecdh.h +s2_meth.o: ../include/openssl/ecdsa.h ../include/openssl/err.h +s2_meth.o: ../include/openssl/evp.h ../include/openssl/hmac.h +s2_meth.o: ../include/openssl/kssl.h ../include/openssl/lhash.h +s2_meth.o: ../include/openssl/obj_mac.h ../include/openssl/objects.h +s2_meth.o: ../include/openssl/opensslconf.h ../include/openssl/opensslv.h +s2_meth.o: ../include/openssl/ossl_typ.h ../include/openssl/pem.h +s2_meth.o: ../include/openssl/pem2.h ../include/openssl/pkcs7.h +s2_meth.o: ../include/openssl/pqueue.h ../include/openssl/rsa.h +s2_meth.o: ../include/openssl/safestack.h ../include/openssl/sha.h +s2_meth.o: ../include/openssl/ssl.h ../include/openssl/ssl2.h +s2_meth.o: ../include/openssl/ssl23.h ../include/openssl/ssl3.h +s2_meth.o: ../include/openssl/stack.h ../include/openssl/symhacks.h +s2_meth.o: ../include/openssl/tls1.h ../include/openssl/x509.h +s2_meth.o: ../include/openssl/x509_vfy.h s2_meth.c ssl_locl.h +s2_pkt.o: ../e_os.h ../include/openssl/asn1.h ../include/openssl/bio.h +s2_pkt.o: ../include/openssl/buffer.h ../include/openssl/comp.h +s2_pkt.o: ../include/openssl/crypto.h ../include/openssl/dsa.h +s2_pkt.o: ../include/openssl/dtls1.h ../include/openssl/e_os2.h +s2_pkt.o: ../include/openssl/ec.h ../include/openssl/ecdh.h +s2_pkt.o: ../include/openssl/ecdsa.h ../include/openssl/err.h +s2_pkt.o: ../include/openssl/evp.h ../include/openssl/hmac.h +s2_pkt.o: ../include/openssl/kssl.h ../include/openssl/lhash.h +s2_pkt.o: ../include/openssl/obj_mac.h ../include/openssl/objects.h +s2_pkt.o: ../include/openssl/opensslconf.h ../include/openssl/opensslv.h +s2_pkt.o: ../include/openssl/ossl_typ.h ../include/openssl/pem.h +s2_pkt.o: ../include/openssl/pem2.h ../include/openssl/pkcs7.h +s2_pkt.o: ../include/openssl/pqueue.h ../include/openssl/rsa.h +s2_pkt.o: ../include/openssl/safestack.h ../include/openssl/sha.h +s2_pkt.o: ../include/openssl/ssl.h ../include/openssl/ssl2.h +s2_pkt.o: ../include/openssl/ssl23.h ../include/openssl/ssl3.h +s2_pkt.o: ../include/openssl/stack.h ../include/openssl/symhacks.h +s2_pkt.o: ../include/openssl/tls1.h ../include/openssl/x509.h +s2_pkt.o: ../include/openssl/x509_vfy.h s2_pkt.c ssl_locl.h +s2_srvr.o: ../e_os.h ../include/openssl/asn1.h ../include/openssl/bio.h +s2_srvr.o: ../include/openssl/buffer.h ../include/openssl/comp.h +s2_srvr.o: ../include/openssl/crypto.h ../include/openssl/dsa.h +s2_srvr.o: ../include/openssl/dtls1.h ../include/openssl/e_os2.h +s2_srvr.o: ../include/openssl/ec.h ../include/openssl/ecdh.h +s2_srvr.o: ../include/openssl/ecdsa.h ../include/openssl/err.h +s2_srvr.o: ../include/openssl/evp.h ../include/openssl/hmac.h +s2_srvr.o: ../include/openssl/kssl.h ../include/openssl/lhash.h +s2_srvr.o: ../include/openssl/obj_mac.h ../include/openssl/objects.h +s2_srvr.o: ../include/openssl/opensslconf.h ../include/openssl/opensslv.h +s2_srvr.o: ../include/openssl/ossl_typ.h ../include/openssl/pem.h +s2_srvr.o: ../include/openssl/pem2.h ../include/openssl/pkcs7.h +s2_srvr.o: ../include/openssl/pqueue.h ../include/openssl/rand.h +s2_srvr.o: ../include/openssl/rsa.h ../include/openssl/safestack.h +s2_srvr.o: ../include/openssl/sha.h ../include/openssl/ssl.h +s2_srvr.o: ../include/openssl/ssl2.h ../include/openssl/ssl23.h +s2_srvr.o: ../include/openssl/ssl3.h ../include/openssl/stack.h +s2_srvr.o: ../include/openssl/symhacks.h ../include/openssl/tls1.h +s2_srvr.o: ../include/openssl/x509.h ../include/openssl/x509_vfy.h s2_srvr.c +s2_srvr.o: ssl_locl.h +s3_both.o: ../e_os.h ../include/openssl/asn1.h ../include/openssl/bio.h +s3_both.o: ../include/openssl/buffer.h ../include/openssl/comp.h +s3_both.o: ../include/openssl/crypto.h ../include/openssl/dsa.h +s3_both.o: ../include/openssl/dtls1.h ../include/openssl/e_os2.h +s3_both.o: ../include/openssl/ec.h ../include/openssl/ecdh.h +s3_both.o: ../include/openssl/ecdsa.h ../include/openssl/err.h +s3_both.o: ../include/openssl/evp.h ../include/openssl/hmac.h +s3_both.o: ../include/openssl/kssl.h ../include/openssl/lhash.h +s3_both.o: ../include/openssl/obj_mac.h ../include/openssl/objects.h +s3_both.o: ../include/openssl/opensslconf.h ../include/openssl/opensslv.h +s3_both.o: ../include/openssl/ossl_typ.h ../include/openssl/pem.h +s3_both.o: ../include/openssl/pem2.h ../include/openssl/pkcs7.h +s3_both.o: ../include/openssl/pqueue.h ../include/openssl/rand.h +s3_both.o: ../include/openssl/rsa.h ../include/openssl/safestack.h +s3_both.o: ../include/openssl/sha.h ../include/openssl/ssl.h +s3_both.o: ../include/openssl/ssl2.h ../include/openssl/ssl23.h +s3_both.o: ../include/openssl/ssl3.h ../include/openssl/stack.h +s3_both.o: ../include/openssl/symhacks.h ../include/openssl/tls1.h +s3_both.o: ../include/openssl/x509.h ../include/openssl/x509_vfy.h s3_both.c +s3_both.o: ssl_locl.h +s3_clnt.o: ../e_os.h ../include/openssl/asn1.h ../include/openssl/bio.h +s3_clnt.o: ../include/openssl/bn.h ../include/openssl/buffer.h +s3_clnt.o: ../include/openssl/comp.h ../include/openssl/crypto.h +s3_clnt.o: ../include/openssl/dh.h ../include/openssl/dsa.h +s3_clnt.o: ../include/openssl/dtls1.h ../include/openssl/e_os2.h +s3_clnt.o: ../include/openssl/ec.h ../include/openssl/ecdh.h +s3_clnt.o: ../include/openssl/ecdsa.h ../include/openssl/engine.h +s3_clnt.o: ../include/openssl/err.h ../include/openssl/evp.h +s3_clnt.o: ../include/openssl/hmac.h ../include/openssl/kssl.h +s3_clnt.o: ../include/openssl/lhash.h ../include/openssl/md5.h +s3_clnt.o: ../include/openssl/obj_mac.h ../include/openssl/objects.h +s3_clnt.o: ../include/openssl/opensslconf.h ../include/openssl/opensslv.h +s3_clnt.o: ../include/openssl/ossl_typ.h ../include/openssl/pem.h +s3_clnt.o: ../include/openssl/pem2.h ../include/openssl/pkcs7.h +s3_clnt.o: ../include/openssl/pqueue.h ../include/openssl/rand.h +s3_clnt.o: ../include/openssl/rsa.h ../include/openssl/safestack.h +s3_clnt.o: ../include/openssl/sha.h ../include/openssl/ssl.h +s3_clnt.o: ../include/openssl/ssl2.h ../include/openssl/ssl23.h +s3_clnt.o: ../include/openssl/ssl3.h ../include/openssl/stack.h +s3_clnt.o: ../include/openssl/symhacks.h ../include/openssl/tls1.h +s3_clnt.o: ../include/openssl/x509.h ../include/openssl/x509_vfy.h kssl_lcl.h +s3_clnt.o: s3_clnt.c ssl_locl.h +s3_enc.o: ../e_os.h ../include/openssl/asn1.h ../include/openssl/bio.h +s3_enc.o: ../include/openssl/buffer.h ../include/openssl/comp.h +s3_enc.o: ../include/openssl/crypto.h ../include/openssl/dsa.h +s3_enc.o: ../include/openssl/dtls1.h ../include/openssl/e_os2.h +s3_enc.o: ../include/openssl/ec.h ../include/openssl/ecdh.h +s3_enc.o: ../include/openssl/ecdsa.h ../include/openssl/err.h +s3_enc.o: ../include/openssl/evp.h ../include/openssl/hmac.h +s3_enc.o: ../include/openssl/kssl.h ../include/openssl/lhash.h +s3_enc.o: ../include/openssl/md5.h ../include/openssl/obj_mac.h +s3_enc.o: ../include/openssl/objects.h ../include/openssl/opensslconf.h +s3_enc.o: ../include/openssl/opensslv.h ../include/openssl/ossl_typ.h +s3_enc.o: ../include/openssl/pem.h ../include/openssl/pem2.h +s3_enc.o: ../include/openssl/pkcs7.h ../include/openssl/pqueue.h +s3_enc.o: ../include/openssl/rsa.h ../include/openssl/safestack.h +s3_enc.o: ../include/openssl/sha.h ../include/openssl/ssl.h +s3_enc.o: ../include/openssl/ssl2.h ../include/openssl/ssl23.h +s3_enc.o: ../include/openssl/ssl3.h ../include/openssl/stack.h +s3_enc.o: ../include/openssl/symhacks.h ../include/openssl/tls1.h +s3_enc.o: ../include/openssl/x509.h ../include/openssl/x509_vfy.h s3_enc.c +s3_enc.o: ssl_locl.h +s3_lib.o: ../crypto/ec/ec_lcl.h ../e_os.h ../include/openssl/asn1.h +s3_lib.o: ../include/openssl/bio.h ../include/openssl/bn.h +s3_lib.o: ../include/openssl/buffer.h ../include/openssl/comp.h +s3_lib.o: ../include/openssl/crypto.h ../include/openssl/dh.h +s3_lib.o: ../include/openssl/dsa.h ../include/openssl/dtls1.h +s3_lib.o: ../include/openssl/e_os2.h ../include/openssl/ec.h +s3_lib.o: ../include/openssl/ecdh.h ../include/openssl/ecdsa.h +s3_lib.o: ../include/openssl/err.h ../include/openssl/evp.h +s3_lib.o: ../include/openssl/hmac.h ../include/openssl/kssl.h +s3_lib.o: ../include/openssl/lhash.h ../include/openssl/md5.h +s3_lib.o: ../include/openssl/obj_mac.h ../include/openssl/objects.h +s3_lib.o: ../include/openssl/opensslconf.h ../include/openssl/opensslv.h +s3_lib.o: ../include/openssl/ossl_typ.h ../include/openssl/pem.h +s3_lib.o: ../include/openssl/pem2.h ../include/openssl/pkcs7.h +s3_lib.o: ../include/openssl/pqueue.h ../include/openssl/rsa.h +s3_lib.o: ../include/openssl/safestack.h ../include/openssl/sha.h +s3_lib.o: ../include/openssl/ssl.h ../include/openssl/ssl2.h +s3_lib.o: ../include/openssl/ssl23.h ../include/openssl/ssl3.h +s3_lib.o: ../include/openssl/stack.h ../include/openssl/symhacks.h +s3_lib.o: ../include/openssl/tls1.h ../include/openssl/x509.h +s3_lib.o: ../include/openssl/x509_vfy.h kssl_lcl.h s3_lib.c ssl_locl.h +s3_meth.o: ../e_os.h ../include/openssl/asn1.h ../include/openssl/bio.h +s3_meth.o: ../include/openssl/buffer.h ../include/openssl/comp.h +s3_meth.o: ../include/openssl/crypto.h ../include/openssl/dsa.h +s3_meth.o: ../include/openssl/dtls1.h ../include/openssl/e_os2.h +s3_meth.o: ../include/openssl/ec.h ../include/openssl/ecdh.h +s3_meth.o: ../include/openssl/ecdsa.h ../include/openssl/err.h +s3_meth.o: ../include/openssl/evp.h ../include/openssl/hmac.h +s3_meth.o: ../include/openssl/kssl.h ../include/openssl/lhash.h +s3_meth.o: ../include/openssl/obj_mac.h ../include/openssl/objects.h +s3_meth.o: ../include/openssl/opensslconf.h ../include/openssl/opensslv.h +s3_meth.o: ../include/openssl/ossl_typ.h ../include/openssl/pem.h +s3_meth.o: ../include/openssl/pem2.h ../include/openssl/pkcs7.h +s3_meth.o: ../include/openssl/pqueue.h ../include/openssl/rsa.h +s3_meth.o: ../include/openssl/safestack.h ../include/openssl/sha.h +s3_meth.o: ../include/openssl/ssl.h ../include/openssl/ssl2.h +s3_meth.o: ../include/openssl/ssl23.h ../include/openssl/ssl3.h +s3_meth.o: ../include/openssl/stack.h ../include/openssl/symhacks.h +s3_meth.o: ../include/openssl/tls1.h ../include/openssl/x509.h +s3_meth.o: ../include/openssl/x509_vfy.h s3_meth.c ssl_locl.h +s3_pkt.o: ../e_os.h ../include/openssl/asn1.h ../include/openssl/bio.h +s3_pkt.o: ../include/openssl/buffer.h ../include/openssl/comp.h +s3_pkt.o: ../include/openssl/crypto.h ../include/openssl/dsa.h +s3_pkt.o: ../include/openssl/dtls1.h ../include/openssl/e_os2.h +s3_pkt.o: ../include/openssl/ec.h ../include/openssl/ecdh.h +s3_pkt.o: ../include/openssl/ecdsa.h ../include/openssl/err.h +s3_pkt.o: ../include/openssl/evp.h ../include/openssl/hmac.h +s3_pkt.o: ../include/openssl/kssl.h ../include/openssl/lhash.h +s3_pkt.o: ../include/openssl/obj_mac.h ../include/openssl/objects.h +s3_pkt.o: ../include/openssl/opensslconf.h ../include/openssl/opensslv.h +s3_pkt.o: ../include/openssl/ossl_typ.h ../include/openssl/pem.h +s3_pkt.o: ../include/openssl/pem2.h ../include/openssl/pkcs7.h +s3_pkt.o: ../include/openssl/pqueue.h ../include/openssl/rsa.h +s3_pkt.o: ../include/openssl/safestack.h ../include/openssl/sha.h +s3_pkt.o: ../include/openssl/ssl.h ../include/openssl/ssl2.h +s3_pkt.o: ../include/openssl/ssl23.h ../include/openssl/ssl3.h +s3_pkt.o: ../include/openssl/stack.h ../include/openssl/symhacks.h +s3_pkt.o: ../include/openssl/tls1.h ../include/openssl/x509.h +s3_pkt.o: ../include/openssl/x509_vfy.h s3_pkt.c ssl_locl.h +s3_srvr.o: ../e_os.h ../include/openssl/asn1.h ../include/openssl/bio.h +s3_srvr.o: ../include/openssl/bn.h ../include/openssl/buffer.h +s3_srvr.o: ../include/openssl/comp.h ../include/openssl/crypto.h +s3_srvr.o: ../include/openssl/dh.h ../include/openssl/dsa.h +s3_srvr.o: ../include/openssl/dtls1.h ../include/openssl/e_os2.h +s3_srvr.o: ../include/openssl/ec.h ../include/openssl/ecdh.h +s3_srvr.o: ../include/openssl/ecdsa.h ../include/openssl/err.h +s3_srvr.o: ../include/openssl/evp.h ../include/openssl/hmac.h +s3_srvr.o: ../include/openssl/krb5_asn.h ../include/openssl/kssl.h +s3_srvr.o: ../include/openssl/lhash.h ../include/openssl/md5.h +s3_srvr.o: ../include/openssl/obj_mac.h ../include/openssl/objects.h +s3_srvr.o: ../include/openssl/opensslconf.h ../include/openssl/opensslv.h +s3_srvr.o: ../include/openssl/ossl_typ.h ../include/openssl/pem.h +s3_srvr.o: ../include/openssl/pem2.h ../include/openssl/pkcs7.h +s3_srvr.o: ../include/openssl/pqueue.h ../include/openssl/rand.h +s3_srvr.o: ../include/openssl/rsa.h ../include/openssl/safestack.h +s3_srvr.o: ../include/openssl/sha.h ../include/openssl/ssl.h +s3_srvr.o: ../include/openssl/ssl2.h ../include/openssl/ssl23.h +s3_srvr.o: ../include/openssl/ssl3.h ../include/openssl/stack.h +s3_srvr.o: ../include/openssl/symhacks.h ../include/openssl/tls1.h +s3_srvr.o: ../include/openssl/x509.h ../include/openssl/x509_vfy.h kssl_lcl.h +s3_srvr.o: s3_srvr.c ssl_locl.h +ssl_algs.o: ../e_os.h ../include/openssl/asn1.h ../include/openssl/bio.h +ssl_algs.o: ../include/openssl/buffer.h ../include/openssl/comp.h +ssl_algs.o: ../include/openssl/crypto.h ../include/openssl/dsa.h +ssl_algs.o: ../include/openssl/dtls1.h ../include/openssl/e_os2.h +ssl_algs.o: ../include/openssl/ec.h ../include/openssl/ecdh.h +ssl_algs.o: ../include/openssl/ecdsa.h ../include/openssl/err.h +ssl_algs.o: ../include/openssl/evp.h ../include/openssl/hmac.h +ssl_algs.o: ../include/openssl/kssl.h ../include/openssl/lhash.h +ssl_algs.o: ../include/openssl/obj_mac.h ../include/openssl/objects.h +ssl_algs.o: ../include/openssl/opensslconf.h ../include/openssl/opensslv.h +ssl_algs.o: ../include/openssl/ossl_typ.h ../include/openssl/pem.h +ssl_algs.o: ../include/openssl/pem2.h ../include/openssl/pkcs7.h +ssl_algs.o: ../include/openssl/pqueue.h ../include/openssl/rsa.h +ssl_algs.o: ../include/openssl/safestack.h ../include/openssl/sha.h +ssl_algs.o: ../include/openssl/ssl.h ../include/openssl/ssl2.h +ssl_algs.o: ../include/openssl/ssl23.h ../include/openssl/ssl3.h +ssl_algs.o: ../include/openssl/stack.h ../include/openssl/symhacks.h +ssl_algs.o: ../include/openssl/tls1.h ../include/openssl/x509.h +ssl_algs.o: ../include/openssl/x509_vfy.h ssl_algs.c ssl_locl.h +ssl_asn1.o: ../e_os.h ../include/openssl/asn1.h ../include/openssl/asn1_mac.h +ssl_asn1.o: ../include/openssl/bio.h ../include/openssl/buffer.h +ssl_asn1.o: ../include/openssl/comp.h ../include/openssl/crypto.h +ssl_asn1.o: ../include/openssl/dsa.h ../include/openssl/dtls1.h +ssl_asn1.o: ../include/openssl/e_os2.h ../include/openssl/ec.h +ssl_asn1.o: ../include/openssl/ecdh.h ../include/openssl/ecdsa.h +ssl_asn1.o: ../include/openssl/err.h ../include/openssl/evp.h +ssl_asn1.o: ../include/openssl/hmac.h ../include/openssl/kssl.h +ssl_asn1.o: ../include/openssl/lhash.h ../include/openssl/obj_mac.h +ssl_asn1.o: ../include/openssl/objects.h ../include/openssl/opensslconf.h +ssl_asn1.o: ../include/openssl/opensslv.h ../include/openssl/ossl_typ.h +ssl_asn1.o: ../include/openssl/pem.h ../include/openssl/pem2.h +ssl_asn1.o: ../include/openssl/pkcs7.h ../include/openssl/pqueue.h +ssl_asn1.o: ../include/openssl/rsa.h ../include/openssl/safestack.h +ssl_asn1.o: ../include/openssl/sha.h ../include/openssl/ssl.h +ssl_asn1.o: ../include/openssl/ssl2.h ../include/openssl/ssl23.h +ssl_asn1.o: ../include/openssl/ssl3.h ../include/openssl/stack.h +ssl_asn1.o: ../include/openssl/symhacks.h ../include/openssl/tls1.h +ssl_asn1.o: ../include/openssl/x509.h ../include/openssl/x509_vfy.h ssl_asn1.c +ssl_asn1.o: ssl_locl.h +ssl_cert.o: ../crypto/o_dir.h ../e_os.h ../include/openssl/asn1.h +ssl_cert.o: ../include/openssl/bio.h ../include/openssl/bn.h +ssl_cert.o: ../include/openssl/buffer.h ../include/openssl/comp.h +ssl_cert.o: ../include/openssl/conf.h ../include/openssl/crypto.h +ssl_cert.o: ../include/openssl/dh.h ../include/openssl/dsa.h +ssl_cert.o: ../include/openssl/dtls1.h ../include/openssl/e_os2.h +ssl_cert.o: ../include/openssl/ec.h ../include/openssl/ecdh.h +ssl_cert.o: ../include/openssl/ecdsa.h ../include/openssl/err.h +ssl_cert.o: ../include/openssl/evp.h ../include/openssl/hmac.h +ssl_cert.o: ../include/openssl/kssl.h ../include/openssl/lhash.h +ssl_cert.o: ../include/openssl/obj_mac.h ../include/openssl/objects.h +ssl_cert.o: ../include/openssl/opensslconf.h ../include/openssl/opensslv.h +ssl_cert.o: ../include/openssl/ossl_typ.h ../include/openssl/pem.h +ssl_cert.o: ../include/openssl/pem2.h ../include/openssl/pkcs7.h +ssl_cert.o: ../include/openssl/pqueue.h ../include/openssl/rsa.h +ssl_cert.o: ../include/openssl/safestack.h ../include/openssl/sha.h +ssl_cert.o: ../include/openssl/ssl.h ../include/openssl/ssl2.h +ssl_cert.o: ../include/openssl/ssl23.h ../include/openssl/ssl3.h +ssl_cert.o: ../include/openssl/stack.h ../include/openssl/symhacks.h +ssl_cert.o: ../include/openssl/tls1.h ../include/openssl/x509.h +ssl_cert.o: ../include/openssl/x509_vfy.h ../include/openssl/x509v3.h +ssl_cert.o: ssl_cert.c ssl_locl.h +ssl_ciph.o: ../e_os.h ../include/openssl/asn1.h ../include/openssl/bio.h +ssl_ciph.o: ../include/openssl/buffer.h ../include/openssl/comp.h +ssl_ciph.o: ../include/openssl/crypto.h ../include/openssl/dsa.h +ssl_ciph.o: ../include/openssl/dtls1.h ../include/openssl/e_os2.h +ssl_ciph.o: ../include/openssl/ec.h ../include/openssl/ecdh.h +ssl_ciph.o: ../include/openssl/ecdsa.h ../include/openssl/engine.h +ssl_ciph.o: ../include/openssl/err.h ../include/openssl/evp.h +ssl_ciph.o: ../include/openssl/hmac.h ../include/openssl/kssl.h +ssl_ciph.o: ../include/openssl/lhash.h ../include/openssl/obj_mac.h +ssl_ciph.o: ../include/openssl/objects.h ../include/openssl/opensslconf.h +ssl_ciph.o: ../include/openssl/opensslv.h ../include/openssl/ossl_typ.h +ssl_ciph.o: ../include/openssl/pem.h ../include/openssl/pem2.h +ssl_ciph.o: ../include/openssl/pkcs7.h ../include/openssl/pqueue.h +ssl_ciph.o: ../include/openssl/rsa.h ../include/openssl/safestack.h +ssl_ciph.o: ../include/openssl/sha.h ../include/openssl/ssl.h +ssl_ciph.o: ../include/openssl/ssl2.h ../include/openssl/ssl23.h +ssl_ciph.o: ../include/openssl/ssl3.h ../include/openssl/stack.h +ssl_ciph.o: ../include/openssl/symhacks.h ../include/openssl/tls1.h +ssl_ciph.o: ../include/openssl/x509.h ../include/openssl/x509_vfy.h ssl_ciph.c +ssl_ciph.o: ssl_locl.h +ssl_err.o: ../include/openssl/asn1.h ../include/openssl/bio.h +ssl_err.o: ../include/openssl/buffer.h ../include/openssl/comp.h +ssl_err.o: ../include/openssl/crypto.h ../include/openssl/dtls1.h +ssl_err.o: ../include/openssl/e_os2.h ../include/openssl/ec.h +ssl_err.o: ../include/openssl/ecdh.h ../include/openssl/ecdsa.h +ssl_err.o: ../include/openssl/err.h ../include/openssl/evp.h +ssl_err.o: ../include/openssl/hmac.h ../include/openssl/kssl.h +ssl_err.o: ../include/openssl/lhash.h ../include/openssl/obj_mac.h +ssl_err.o: ../include/openssl/objects.h ../include/openssl/opensslconf.h +ssl_err.o: ../include/openssl/opensslv.h ../include/openssl/ossl_typ.h +ssl_err.o: ../include/openssl/pem.h ../include/openssl/pem2.h +ssl_err.o: ../include/openssl/pkcs7.h ../include/openssl/pqueue.h +ssl_err.o: ../include/openssl/safestack.h ../include/openssl/sha.h +ssl_err.o: ../include/openssl/ssl.h ../include/openssl/ssl2.h +ssl_err.o: ../include/openssl/ssl23.h ../include/openssl/ssl3.h +ssl_err.o: ../include/openssl/stack.h ../include/openssl/symhacks.h +ssl_err.o: ../include/openssl/tls1.h ../include/openssl/x509.h +ssl_err.o: ../include/openssl/x509_vfy.h ssl_err.c +ssl_err2.o: ../include/openssl/asn1.h ../include/openssl/bio.h +ssl_err2.o: ../include/openssl/buffer.h ../include/openssl/comp.h +ssl_err2.o: ../include/openssl/crypto.h ../include/openssl/dtls1.h +ssl_err2.o: ../include/openssl/e_os2.h ../include/openssl/ec.h +ssl_err2.o: ../include/openssl/ecdh.h ../include/openssl/ecdsa.h +ssl_err2.o: ../include/openssl/err.h ../include/openssl/evp.h +ssl_err2.o: ../include/openssl/hmac.h ../include/openssl/kssl.h +ssl_err2.o: ../include/openssl/lhash.h ../include/openssl/obj_mac.h +ssl_err2.o: ../include/openssl/objects.h ../include/openssl/opensslconf.h +ssl_err2.o: ../include/openssl/opensslv.h ../include/openssl/ossl_typ.h +ssl_err2.o: ../include/openssl/pem.h ../include/openssl/pem2.h +ssl_err2.o: ../include/openssl/pkcs7.h ../include/openssl/pqueue.h +ssl_err2.o: ../include/openssl/safestack.h ../include/openssl/sha.h +ssl_err2.o: ../include/openssl/ssl.h ../include/openssl/ssl2.h +ssl_err2.o: ../include/openssl/ssl23.h ../include/openssl/ssl3.h +ssl_err2.o: ../include/openssl/stack.h ../include/openssl/symhacks.h +ssl_err2.o: ../include/openssl/tls1.h ../include/openssl/x509.h +ssl_err2.o: ../include/openssl/x509_vfy.h ssl_err2.c +ssl_lib.o: ../e_os.h ../include/openssl/asn1.h ../include/openssl/bio.h +ssl_lib.o: ../include/openssl/buffer.h ../include/openssl/comp.h +ssl_lib.o: ../include/openssl/conf.h ../include/openssl/crypto.h +ssl_lib.o: ../include/openssl/dh.h ../include/openssl/dsa.h +ssl_lib.o: ../include/openssl/dtls1.h ../include/openssl/e_os2.h +ssl_lib.o: ../include/openssl/ec.h ../include/openssl/ecdh.h +ssl_lib.o: ../include/openssl/ecdsa.h ../include/openssl/engine.h +ssl_lib.o: ../include/openssl/err.h ../include/openssl/evp.h +ssl_lib.o: ../include/openssl/hmac.h ../include/openssl/kssl.h +ssl_lib.o: ../include/openssl/lhash.h ../include/openssl/obj_mac.h +ssl_lib.o: ../include/openssl/objects.h ../include/openssl/ocsp.h +ssl_lib.o: ../include/openssl/opensslconf.h ../include/openssl/opensslv.h +ssl_lib.o: ../include/openssl/ossl_typ.h ../include/openssl/pem.h +ssl_lib.o: ../include/openssl/pem2.h ../include/openssl/pkcs7.h +ssl_lib.o: ../include/openssl/pqueue.h ../include/openssl/rand.h +ssl_lib.o: ../include/openssl/rsa.h ../include/openssl/safestack.h +ssl_lib.o: ../include/openssl/sha.h ../include/openssl/ssl.h +ssl_lib.o: ../include/openssl/ssl2.h ../include/openssl/ssl23.h +ssl_lib.o: ../include/openssl/ssl3.h ../include/openssl/stack.h +ssl_lib.o: ../include/openssl/symhacks.h ../include/openssl/tls1.h +ssl_lib.o: ../include/openssl/x509.h ../include/openssl/x509_vfy.h +ssl_lib.o: ../include/openssl/x509v3.h kssl_lcl.h ssl_lib.c ssl_locl.h +ssl_rsa.o: ../e_os.h ../include/openssl/asn1.h ../include/openssl/bio.h +ssl_rsa.o: ../include/openssl/buffer.h ../include/openssl/comp.h +ssl_rsa.o: ../include/openssl/crypto.h ../include/openssl/dsa.h +ssl_rsa.o: ../include/openssl/dtls1.h ../include/openssl/e_os2.h +ssl_rsa.o: ../include/openssl/ec.h ../include/openssl/ecdh.h +ssl_rsa.o: ../include/openssl/ecdsa.h ../include/openssl/err.h +ssl_rsa.o: ../include/openssl/evp.h ../include/openssl/hmac.h +ssl_rsa.o: ../include/openssl/kssl.h ../include/openssl/lhash.h +ssl_rsa.o: ../include/openssl/obj_mac.h ../include/openssl/objects.h +ssl_rsa.o: ../include/openssl/opensslconf.h ../include/openssl/opensslv.h +ssl_rsa.o: ../include/openssl/ossl_typ.h ../include/openssl/pem.h +ssl_rsa.o: ../include/openssl/pem2.h ../include/openssl/pkcs7.h +ssl_rsa.o: ../include/openssl/pqueue.h ../include/openssl/rsa.h +ssl_rsa.o: ../include/openssl/safestack.h ../include/openssl/sha.h +ssl_rsa.o: ../include/openssl/ssl.h ../include/openssl/ssl2.h +ssl_rsa.o: ../include/openssl/ssl23.h ../include/openssl/ssl3.h +ssl_rsa.o: ../include/openssl/stack.h ../include/openssl/symhacks.h +ssl_rsa.o: ../include/openssl/tls1.h ../include/openssl/x509.h +ssl_rsa.o: ../include/openssl/x509_vfy.h ssl_locl.h ssl_rsa.c +ssl_sess.o: ../e_os.h ../include/openssl/asn1.h ../include/openssl/bio.h +ssl_sess.o: ../include/openssl/buffer.h ../include/openssl/comp.h +ssl_sess.o: ../include/openssl/crypto.h ../include/openssl/dsa.h +ssl_sess.o: ../include/openssl/dtls1.h ../include/openssl/e_os2.h +ssl_sess.o: ../include/openssl/ec.h ../include/openssl/ecdh.h +ssl_sess.o: ../include/openssl/ecdsa.h ../include/openssl/engine.h +ssl_sess.o: ../include/openssl/err.h ../include/openssl/evp.h +ssl_sess.o: ../include/openssl/hmac.h ../include/openssl/kssl.h +ssl_sess.o: ../include/openssl/lhash.h ../include/openssl/obj_mac.h +ssl_sess.o: ../include/openssl/objects.h ../include/openssl/opensslconf.h +ssl_sess.o: ../include/openssl/opensslv.h ../include/openssl/ossl_typ.h +ssl_sess.o: ../include/openssl/pem.h ../include/openssl/pem2.h +ssl_sess.o: ../include/openssl/pkcs7.h ../include/openssl/pqueue.h +ssl_sess.o: ../include/openssl/rand.h ../include/openssl/rsa.h +ssl_sess.o: ../include/openssl/safestack.h ../include/openssl/sha.h +ssl_sess.o: ../include/openssl/ssl.h ../include/openssl/ssl2.h +ssl_sess.o: ../include/openssl/ssl23.h ../include/openssl/ssl3.h +ssl_sess.o: ../include/openssl/stack.h ../include/openssl/symhacks.h +ssl_sess.o: ../include/openssl/tls1.h ../include/openssl/x509.h +ssl_sess.o: ../include/openssl/x509_vfy.h ssl_locl.h ssl_sess.c +ssl_stat.o: ../e_os.h ../include/openssl/asn1.h ../include/openssl/bio.h +ssl_stat.o: ../include/openssl/buffer.h ../include/openssl/comp.h +ssl_stat.o: ../include/openssl/crypto.h ../include/openssl/dsa.h +ssl_stat.o: ../include/openssl/dtls1.h ../include/openssl/e_os2.h +ssl_stat.o: ../include/openssl/ec.h ../include/openssl/ecdh.h +ssl_stat.o: ../include/openssl/ecdsa.h ../include/openssl/err.h +ssl_stat.o: ../include/openssl/evp.h ../include/openssl/hmac.h +ssl_stat.o: ../include/openssl/kssl.h ../include/openssl/lhash.h +ssl_stat.o: ../include/openssl/obj_mac.h ../include/openssl/objects.h +ssl_stat.o: ../include/openssl/opensslconf.h ../include/openssl/opensslv.h +ssl_stat.o: ../include/openssl/ossl_typ.h ../include/openssl/pem.h +ssl_stat.o: ../include/openssl/pem2.h ../include/openssl/pkcs7.h +ssl_stat.o: ../include/openssl/pqueue.h ../include/openssl/rsa.h +ssl_stat.o: ../include/openssl/safestack.h ../include/openssl/sha.h +ssl_stat.o: ../include/openssl/ssl.h ../include/openssl/ssl2.h +ssl_stat.o: ../include/openssl/ssl23.h ../include/openssl/ssl3.h +ssl_stat.o: ../include/openssl/stack.h ../include/openssl/symhacks.h +ssl_stat.o: ../include/openssl/tls1.h ../include/openssl/x509.h +ssl_stat.o: ../include/openssl/x509_vfy.h ssl_locl.h ssl_stat.c +ssl_txt.o: ../e_os.h ../include/openssl/asn1.h ../include/openssl/bio.h +ssl_txt.o: ../include/openssl/buffer.h ../include/openssl/comp.h +ssl_txt.o: ../include/openssl/crypto.h ../include/openssl/dsa.h +ssl_txt.o: ../include/openssl/dtls1.h ../include/openssl/e_os2.h +ssl_txt.o: ../include/openssl/ec.h ../include/openssl/ecdh.h +ssl_txt.o: ../include/openssl/ecdsa.h ../include/openssl/err.h +ssl_txt.o: ../include/openssl/evp.h ../include/openssl/hmac.h +ssl_txt.o: ../include/openssl/kssl.h ../include/openssl/lhash.h +ssl_txt.o: ../include/openssl/obj_mac.h ../include/openssl/objects.h +ssl_txt.o: ../include/openssl/opensslconf.h ../include/openssl/opensslv.h +ssl_txt.o: ../include/openssl/ossl_typ.h ../include/openssl/pem.h +ssl_txt.o: ../include/openssl/pem2.h ../include/openssl/pkcs7.h +ssl_txt.o: ../include/openssl/pqueue.h ../include/openssl/rsa.h +ssl_txt.o: ../include/openssl/safestack.h ../include/openssl/sha.h +ssl_txt.o: ../include/openssl/ssl.h ../include/openssl/ssl2.h +ssl_txt.o: ../include/openssl/ssl23.h ../include/openssl/ssl3.h +ssl_txt.o: ../include/openssl/stack.h ../include/openssl/symhacks.h +ssl_txt.o: ../include/openssl/tls1.h ../include/openssl/x509.h +ssl_txt.o: ../include/openssl/x509_vfy.h ssl_locl.h ssl_txt.c +t1_clnt.o: ../e_os.h ../include/openssl/asn1.h ../include/openssl/bio.h +t1_clnt.o: ../include/openssl/buffer.h ../include/openssl/comp.h +t1_clnt.o: ../include/openssl/crypto.h ../include/openssl/dsa.h +t1_clnt.o: ../include/openssl/dtls1.h ../include/openssl/e_os2.h +t1_clnt.o: ../include/openssl/ec.h ../include/openssl/ecdh.h +t1_clnt.o: ../include/openssl/ecdsa.h ../include/openssl/err.h +t1_clnt.o: ../include/openssl/evp.h ../include/openssl/hmac.h +t1_clnt.o: ../include/openssl/kssl.h ../include/openssl/lhash.h +t1_clnt.o: ../include/openssl/obj_mac.h ../include/openssl/objects.h +t1_clnt.o: ../include/openssl/opensslconf.h ../include/openssl/opensslv.h +t1_clnt.o: ../include/openssl/ossl_typ.h ../include/openssl/pem.h +t1_clnt.o: ../include/openssl/pem2.h ../include/openssl/pkcs7.h +t1_clnt.o: ../include/openssl/pqueue.h ../include/openssl/rand.h +t1_clnt.o: ../include/openssl/rsa.h ../include/openssl/safestack.h +t1_clnt.o: ../include/openssl/sha.h ../include/openssl/ssl.h +t1_clnt.o: ../include/openssl/ssl2.h ../include/openssl/ssl23.h +t1_clnt.o: ../include/openssl/ssl3.h ../include/openssl/stack.h +t1_clnt.o: ../include/openssl/symhacks.h ../include/openssl/tls1.h +t1_clnt.o: ../include/openssl/x509.h ../include/openssl/x509_vfy.h ssl_locl.h +t1_clnt.o: t1_clnt.c +t1_enc.o: ../e_os.h ../include/openssl/asn1.h ../include/openssl/bio.h +t1_enc.o: ../include/openssl/buffer.h ../include/openssl/comp.h +t1_enc.o: ../include/openssl/crypto.h ../include/openssl/dsa.h +t1_enc.o: ../include/openssl/dtls1.h ../include/openssl/e_os2.h +t1_enc.o: ../include/openssl/ec.h ../include/openssl/ecdh.h +t1_enc.o: ../include/openssl/ecdsa.h ../include/openssl/err.h +t1_enc.o: ../include/openssl/evp.h ../include/openssl/hmac.h +t1_enc.o: ../include/openssl/kssl.h ../include/openssl/lhash.h +t1_enc.o: ../include/openssl/md5.h ../include/openssl/obj_mac.h +t1_enc.o: ../include/openssl/objects.h ../include/openssl/opensslconf.h +t1_enc.o: ../include/openssl/opensslv.h ../include/openssl/ossl_typ.h +t1_enc.o: ../include/openssl/pem.h ../include/openssl/pem2.h +t1_enc.o: ../include/openssl/pkcs7.h ../include/openssl/pqueue.h +t1_enc.o: ../include/openssl/rsa.h ../include/openssl/safestack.h +t1_enc.o: ../include/openssl/sha.h ../include/openssl/ssl.h +t1_enc.o: ../include/openssl/ssl2.h ../include/openssl/ssl23.h +t1_enc.o: ../include/openssl/ssl3.h ../include/openssl/stack.h +t1_enc.o: ../include/openssl/symhacks.h ../include/openssl/tls1.h +t1_enc.o: ../include/openssl/x509.h ../include/openssl/x509_vfy.h ssl_locl.h +t1_enc.o: t1_enc.c +t1_lib.o: ../e_os.h ../include/openssl/asn1.h ../include/openssl/bio.h +t1_lib.o: ../include/openssl/buffer.h ../include/openssl/comp.h +t1_lib.o: ../include/openssl/conf.h ../include/openssl/crypto.h +t1_lib.o: ../include/openssl/dsa.h ../include/openssl/dtls1.h +t1_lib.o: ../include/openssl/e_os2.h ../include/openssl/ec.h +t1_lib.o: ../include/openssl/ecdh.h ../include/openssl/ecdsa.h +t1_lib.o: ../include/openssl/err.h ../include/openssl/evp.h +t1_lib.o: ../include/openssl/hmac.h ../include/openssl/kssl.h +t1_lib.o: ../include/openssl/lhash.h ../include/openssl/obj_mac.h +t1_lib.o: ../include/openssl/objects.h ../include/openssl/ocsp.h +t1_lib.o: ../include/openssl/opensslconf.h ../include/openssl/opensslv.h +t1_lib.o: ../include/openssl/ossl_typ.h ../include/openssl/pem.h +t1_lib.o: ../include/openssl/pem2.h ../include/openssl/pkcs7.h +t1_lib.o: ../include/openssl/pqueue.h ../include/openssl/rsa.h +t1_lib.o: ../include/openssl/safestack.h ../include/openssl/sha.h +t1_lib.o: ../include/openssl/ssl.h ../include/openssl/ssl2.h +t1_lib.o: ../include/openssl/ssl23.h ../include/openssl/ssl3.h +t1_lib.o: ../include/openssl/stack.h ../include/openssl/symhacks.h +t1_lib.o: ../include/openssl/tls1.h ../include/openssl/x509.h +t1_lib.o: ../include/openssl/x509_vfy.h ../include/openssl/x509v3.h ssl_locl.h +t1_lib.o: t1_lib.c +t1_meth.o: ../e_os.h ../include/openssl/asn1.h ../include/openssl/bio.h +t1_meth.o: ../include/openssl/buffer.h ../include/openssl/comp.h +t1_meth.o: ../include/openssl/crypto.h ../include/openssl/dsa.h +t1_meth.o: ../include/openssl/dtls1.h ../include/openssl/e_os2.h +t1_meth.o: ../include/openssl/ec.h ../include/openssl/ecdh.h +t1_meth.o: ../include/openssl/ecdsa.h ../include/openssl/err.h +t1_meth.o: ../include/openssl/evp.h ../include/openssl/hmac.h +t1_meth.o: ../include/openssl/kssl.h ../include/openssl/lhash.h +t1_meth.o: ../include/openssl/obj_mac.h ../include/openssl/objects.h +t1_meth.o: ../include/openssl/opensslconf.h ../include/openssl/opensslv.h +t1_meth.o: ../include/openssl/ossl_typ.h ../include/openssl/pem.h +t1_meth.o: ../include/openssl/pem2.h ../include/openssl/pkcs7.h +t1_meth.o: ../include/openssl/pqueue.h ../include/openssl/rsa.h +t1_meth.o: ../include/openssl/safestack.h ../include/openssl/sha.h +t1_meth.o: ../include/openssl/ssl.h ../include/openssl/ssl2.h +t1_meth.o: ../include/openssl/ssl23.h ../include/openssl/ssl3.h +t1_meth.o: ../include/openssl/stack.h ../include/openssl/symhacks.h +t1_meth.o: ../include/openssl/tls1.h ../include/openssl/x509.h +t1_meth.o: ../include/openssl/x509_vfy.h ssl_locl.h t1_meth.c +t1_reneg.o: ../e_os.h ../include/openssl/asn1.h ../include/openssl/bio.h +t1_reneg.o: ../include/openssl/buffer.h ../include/openssl/comp.h +t1_reneg.o: ../include/openssl/crypto.h ../include/openssl/dsa.h +t1_reneg.o: ../include/openssl/dtls1.h ../include/openssl/e_os2.h +t1_reneg.o: ../include/openssl/ec.h ../include/openssl/ecdh.h +t1_reneg.o: ../include/openssl/ecdsa.h ../include/openssl/err.h +t1_reneg.o: ../include/openssl/evp.h ../include/openssl/hmac.h +t1_reneg.o: ../include/openssl/kssl.h ../include/openssl/lhash.h +t1_reneg.o: ../include/openssl/obj_mac.h ../include/openssl/objects.h +t1_reneg.o: ../include/openssl/opensslconf.h ../include/openssl/opensslv.h +t1_reneg.o: ../include/openssl/ossl_typ.h ../include/openssl/pem.h +t1_reneg.o: ../include/openssl/pem2.h ../include/openssl/pkcs7.h +t1_reneg.o: ../include/openssl/pqueue.h ../include/openssl/rsa.h +t1_reneg.o: ../include/openssl/safestack.h ../include/openssl/sha.h +t1_reneg.o: ../include/openssl/ssl.h ../include/openssl/ssl2.h +t1_reneg.o: ../include/openssl/ssl23.h ../include/openssl/ssl3.h +t1_reneg.o: ../include/openssl/stack.h ../include/openssl/symhacks.h +t1_reneg.o: ../include/openssl/tls1.h ../include/openssl/x509.h +t1_reneg.o: ../include/openssl/x509_vfy.h ssl_locl.h t1_reneg.c +t1_srvr.o: ../e_os.h ../include/openssl/asn1.h ../include/openssl/bio.h +t1_srvr.o: ../include/openssl/buffer.h ../include/openssl/comp.h +t1_srvr.o: ../include/openssl/crypto.h ../include/openssl/dsa.h +t1_srvr.o: ../include/openssl/dtls1.h ../include/openssl/e_os2.h +t1_srvr.o: ../include/openssl/ec.h ../include/openssl/ecdh.h +t1_srvr.o: ../include/openssl/ecdsa.h ../include/openssl/err.h +t1_srvr.o: ../include/openssl/evp.h ../include/openssl/hmac.h +t1_srvr.o: ../include/openssl/kssl.h ../include/openssl/lhash.h +t1_srvr.o: ../include/openssl/obj_mac.h ../include/openssl/objects.h +t1_srvr.o: ../include/openssl/opensslconf.h ../include/openssl/opensslv.h +t1_srvr.o: ../include/openssl/ossl_typ.h ../include/openssl/pem.h +t1_srvr.o: ../include/openssl/pem2.h ../include/openssl/pkcs7.h +t1_srvr.o: ../include/openssl/pqueue.h ../include/openssl/rand.h +t1_srvr.o: ../include/openssl/rsa.h ../include/openssl/safestack.h +t1_srvr.o: ../include/openssl/sha.h ../include/openssl/ssl.h +t1_srvr.o: ../include/openssl/ssl2.h ../include/openssl/ssl23.h +t1_srvr.o: ../include/openssl/ssl3.h ../include/openssl/stack.h +t1_srvr.o: ../include/openssl/symhacks.h ../include/openssl/tls1.h +t1_srvr.o: ../include/openssl/x509.h ../include/openssl/x509_vfy.h ssl_locl.h +t1_srvr.o: t1_srvr.c diff --git a/node-v0.8.14/deps/openssl/openssl/ssl/bio_ssl.c b/node-v0.8.14/deps/openssl/openssl/ssl/bio_ssl.c new file mode 100644 index 0000000..e9552ca --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/ssl/bio_ssl.c @@ -0,0 +1,605 @@ +/* ssl/bio_ssl.c */ +/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com) + * All rights reserved. + * + * This package is an SSL implementation written + * by Eric Young (eay@cryptsoft.com). + * The implementation was written so as to conform with Netscapes SSL. + * + * This library is free for commercial and non-commercial use as long as + * the following conditions are aheared to. The following conditions + * apply to all code found in this distribution, be it the RC4, RSA, + * lhash, DES, etc., code; not just the SSL code. The SSL documentation + * included with this distribution is covered by the same copyright terms + * except that the holder is Tim Hudson (tjh@cryptsoft.com). + * + * Copyright remains Eric Young's, and as such any Copyright notices in + * the code are not to be removed. + * If this package is used in a product, Eric Young should be given attribution + * as the author of the parts of the library used. + * This can be in the form of a textual message at program startup or + * in documentation (online or textual) provided with the package. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * "This product includes cryptographic software written by + * Eric Young (eay@cryptsoft.com)" + * The word 'cryptographic' can be left out if the rouines from the library + * being used are not cryptographic related :-). + * 4. If you include any Windows specific code (or a derivative thereof) from + * the apps directory (application code) you must include an acknowledgement: + * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)" + * + * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * + * The licence and distribution terms for any publically available version or + * derivative of this code cannot be changed. i.e. this code cannot simply be + * copied and put under another distribution licence + * [including the GNU Public Licence.] + */ + +#include +#include +#include +#include +#include +#include +#include +#include + +static int ssl_write(BIO *h, const char *buf, int num); +static int ssl_read(BIO *h, char *buf, int size); +static int ssl_puts(BIO *h, const char *str); +static long ssl_ctrl(BIO *h, int cmd, long arg1, void *arg2); +static int ssl_new(BIO *h); +static int ssl_free(BIO *data); +static long ssl_callback_ctrl(BIO *h, int cmd, bio_info_cb *fp); +typedef struct bio_ssl_st + { + SSL *ssl; /* The ssl handle :-) */ + /* re-negotiate every time the total number of bytes is this size */ + int num_renegotiates; + unsigned long renegotiate_count; + unsigned long byte_count; + unsigned long renegotiate_timeout; + unsigned long last_time; + } BIO_SSL; + +static BIO_METHOD methods_sslp= + { + BIO_TYPE_SSL,"ssl", + ssl_write, + ssl_read, + ssl_puts, + NULL, /* ssl_gets, */ + ssl_ctrl, + ssl_new, + ssl_free, + ssl_callback_ctrl, + }; + +BIO_METHOD *BIO_f_ssl(void) + { + return(&methods_sslp); + } + +static int ssl_new(BIO *bi) + { + BIO_SSL *bs; + + bs=(BIO_SSL *)OPENSSL_malloc(sizeof(BIO_SSL)); + if (bs == NULL) + { + BIOerr(BIO_F_SSL_NEW,ERR_R_MALLOC_FAILURE); + return(0); + } + memset(bs,0,sizeof(BIO_SSL)); + bi->init=0; + bi->ptr=(char *)bs; + bi->flags=0; + return(1); + } + +static int ssl_free(BIO *a) + { + BIO_SSL *bs; + + if (a == NULL) return(0); + bs=(BIO_SSL *)a->ptr; + if (bs->ssl != NULL) SSL_shutdown(bs->ssl); + if (a->shutdown) + { + if (a->init && (bs->ssl != NULL)) + SSL_free(bs->ssl); + a->init=0; + a->flags=0; + } + if (a->ptr != NULL) + OPENSSL_free(a->ptr); + return(1); + } + +static int ssl_read(BIO *b, char *out, int outl) + { + int ret=1; + BIO_SSL *sb; + SSL *ssl; + int retry_reason=0; + int r=0; + + if (out == NULL) return(0); + sb=(BIO_SSL *)b->ptr; + ssl=sb->ssl; + + BIO_clear_retry_flags(b); + +#if 0 + if (!SSL_is_init_finished(ssl)) + { +/* ret=SSL_do_handshake(ssl); */ + if (ret > 0) + { + + outflags=(BIO_FLAGS_READ|BIO_FLAGS_SHOULD_RETRY); + ret= -1; + goto end; + } + } +#endif +/* if (ret > 0) */ + ret=SSL_read(ssl,out,outl); + + switch (SSL_get_error(ssl,ret)) + { + case SSL_ERROR_NONE: + if (ret <= 0) break; + if (sb->renegotiate_count > 0) + { + sb->byte_count+=ret; + if (sb->byte_count > sb->renegotiate_count) + { + sb->byte_count=0; + sb->num_renegotiates++; + SSL_renegotiate(ssl); + r=1; + } + } + if ((sb->renegotiate_timeout > 0) && (!r)) + { + unsigned long tm; + + tm=(unsigned long)time(NULL); + if (tm > sb->last_time+sb->renegotiate_timeout) + { + sb->last_time=tm; + sb->num_renegotiates++; + SSL_renegotiate(ssl); + } + } + + break; + case SSL_ERROR_WANT_READ: + BIO_set_retry_read(b); + break; + case SSL_ERROR_WANT_WRITE: + BIO_set_retry_write(b); + break; + case SSL_ERROR_WANT_X509_LOOKUP: + BIO_set_retry_special(b); + retry_reason=BIO_RR_SSL_X509_LOOKUP; + break; + case SSL_ERROR_WANT_ACCEPT: + BIO_set_retry_special(b); + retry_reason=BIO_RR_ACCEPT; + break; + case SSL_ERROR_WANT_CONNECT: + BIO_set_retry_special(b); + retry_reason=BIO_RR_CONNECT; + break; + case SSL_ERROR_SYSCALL: + case SSL_ERROR_SSL: + case SSL_ERROR_ZERO_RETURN: + default: + break; + } + + b->retry_reason=retry_reason; + return(ret); + } + +static int ssl_write(BIO *b, const char *out, int outl) + { + int ret,r=0; + int retry_reason=0; + SSL *ssl; + BIO_SSL *bs; + + if (out == NULL) return(0); + bs=(BIO_SSL *)b->ptr; + ssl=bs->ssl; + + BIO_clear_retry_flags(b); + +/* ret=SSL_do_handshake(ssl); + if (ret > 0) */ + ret=SSL_write(ssl,out,outl); + + switch (SSL_get_error(ssl,ret)) + { + case SSL_ERROR_NONE: + if (ret <= 0) break; + if (bs->renegotiate_count > 0) + { + bs->byte_count+=ret; + if (bs->byte_count > bs->renegotiate_count) + { + bs->byte_count=0; + bs->num_renegotiates++; + SSL_renegotiate(ssl); + r=1; + } + } + if ((bs->renegotiate_timeout > 0) && (!r)) + { + unsigned long tm; + + tm=(unsigned long)time(NULL); + if (tm > bs->last_time+bs->renegotiate_timeout) + { + bs->last_time=tm; + bs->num_renegotiates++; + SSL_renegotiate(ssl); + } + } + break; + case SSL_ERROR_WANT_WRITE: + BIO_set_retry_write(b); + break; + case SSL_ERROR_WANT_READ: + BIO_set_retry_read(b); + break; + case SSL_ERROR_WANT_X509_LOOKUP: + BIO_set_retry_special(b); + retry_reason=BIO_RR_SSL_X509_LOOKUP; + break; + case SSL_ERROR_WANT_CONNECT: + BIO_set_retry_special(b); + retry_reason=BIO_RR_CONNECT; + case SSL_ERROR_SYSCALL: + case SSL_ERROR_SSL: + default: + break; + } + + b->retry_reason=retry_reason; + return(ret); + } + +static long ssl_ctrl(BIO *b, int cmd, long num, void *ptr) + { + SSL **sslp,*ssl; + BIO_SSL *bs; + BIO *dbio,*bio; + long ret=1; + + bs=(BIO_SSL *)b->ptr; + ssl=bs->ssl; + if ((ssl == NULL) && (cmd != BIO_C_SET_SSL)) + return(0); + switch (cmd) + { + case BIO_CTRL_RESET: + SSL_shutdown(ssl); + + if (ssl->handshake_func == ssl->method->ssl_connect) + SSL_set_connect_state(ssl); + else if (ssl->handshake_func == ssl->method->ssl_accept) + SSL_set_accept_state(ssl); + + SSL_clear(ssl); + + if (b->next_bio != NULL) + ret=BIO_ctrl(b->next_bio,cmd,num,ptr); + else if (ssl->rbio != NULL) + ret=BIO_ctrl(ssl->rbio,cmd,num,ptr); + else + ret=1; + break; + case BIO_CTRL_INFO: + ret=0; + break; + case BIO_C_SSL_MODE: + if (num) /* client mode */ + SSL_set_connect_state(ssl); + else + SSL_set_accept_state(ssl); + break; + case BIO_C_SET_SSL_RENEGOTIATE_TIMEOUT: + ret=bs->renegotiate_timeout; + if (num < 60) num=5; + bs->renegotiate_timeout=(unsigned long)num; + bs->last_time=(unsigned long)time(NULL); + break; + case BIO_C_SET_SSL_RENEGOTIATE_BYTES: + ret=bs->renegotiate_count; + if ((long)num >=512) + bs->renegotiate_count=(unsigned long)num; + break; + case BIO_C_GET_SSL_NUM_RENEGOTIATES: + ret=bs->num_renegotiates; + break; + case BIO_C_SET_SSL: + if (ssl != NULL) + { + ssl_free(b); + if (!ssl_new(b)) + return 0; + } + b->shutdown=(int)num; + ssl=(SSL *)ptr; + ((BIO_SSL *)b->ptr)->ssl=ssl; + bio=SSL_get_rbio(ssl); + if (bio != NULL) + { + if (b->next_bio != NULL) + BIO_push(bio,b->next_bio); + b->next_bio=bio; + CRYPTO_add(&bio->references,1,CRYPTO_LOCK_BIO); + } + b->init=1; + break; + case BIO_C_GET_SSL: + if (ptr != NULL) + { + sslp=(SSL **)ptr; + *sslp=ssl; + } + else + ret=0; + break; + case BIO_CTRL_GET_CLOSE: + ret=b->shutdown; + break; + case BIO_CTRL_SET_CLOSE: + b->shutdown=(int)num; + break; + case BIO_CTRL_WPENDING: + ret=BIO_ctrl(ssl->wbio,cmd,num,ptr); + break; + case BIO_CTRL_PENDING: + ret=SSL_pending(ssl); + if (ret == 0) + ret=BIO_pending(ssl->rbio); + break; + case BIO_CTRL_FLUSH: + BIO_clear_retry_flags(b); + ret=BIO_ctrl(ssl->wbio,cmd,num,ptr); + BIO_copy_next_retry(b); + break; + case BIO_CTRL_PUSH: + if ((b->next_bio != NULL) && (b->next_bio != ssl->rbio)) + { + SSL_set_bio(ssl,b->next_bio,b->next_bio); + CRYPTO_add(&b->next_bio->references,1,CRYPTO_LOCK_BIO); + } + break; + case BIO_CTRL_POP: + /* Only detach if we are the BIO explicitly being popped */ + if (b == ptr) + { + /* Shouldn't happen in practice because the + * rbio and wbio are the same when pushed. + */ + if (ssl->rbio != ssl->wbio) + BIO_free_all(ssl->wbio); + if (b->next_bio != NULL) + CRYPTO_add(&b->next_bio->references,-1,CRYPTO_LOCK_BIO); + ssl->wbio=NULL; + ssl->rbio=NULL; + } + break; + case BIO_C_DO_STATE_MACHINE: + BIO_clear_retry_flags(b); + + b->retry_reason=0; + ret=(int)SSL_do_handshake(ssl); + + switch (SSL_get_error(ssl,(int)ret)) + { + case SSL_ERROR_WANT_READ: + BIO_set_flags(b, + BIO_FLAGS_READ|BIO_FLAGS_SHOULD_RETRY); + break; + case SSL_ERROR_WANT_WRITE: + BIO_set_flags(b, + BIO_FLAGS_WRITE|BIO_FLAGS_SHOULD_RETRY); + break; + case SSL_ERROR_WANT_CONNECT: + BIO_set_flags(b, + BIO_FLAGS_IO_SPECIAL|BIO_FLAGS_SHOULD_RETRY); + b->retry_reason=b->next_bio->retry_reason; + break; + default: + break; + } + break; + case BIO_CTRL_DUP: + dbio=(BIO *)ptr; + if (((BIO_SSL *)dbio->ptr)->ssl != NULL) + SSL_free(((BIO_SSL *)dbio->ptr)->ssl); + ((BIO_SSL *)dbio->ptr)->ssl=SSL_dup(ssl); + ((BIO_SSL *)dbio->ptr)->renegotiate_count= + ((BIO_SSL *)b->ptr)->renegotiate_count; + ((BIO_SSL *)dbio->ptr)->byte_count= + ((BIO_SSL *)b->ptr)->byte_count; + ((BIO_SSL *)dbio->ptr)->renegotiate_timeout= + ((BIO_SSL *)b->ptr)->renegotiate_timeout; + ((BIO_SSL *)dbio->ptr)->last_time= + ((BIO_SSL *)b->ptr)->last_time; + ret=(((BIO_SSL *)dbio->ptr)->ssl != NULL); + break; + case BIO_C_GET_FD: + ret=BIO_ctrl(ssl->rbio,cmd,num,ptr); + break; + case BIO_CTRL_SET_CALLBACK: + { +#if 0 /* FIXME: Should this be used? -- Richard Levitte */ + SSLerr(SSL_F_SSL_CTRL, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED); + ret = -1; +#else + ret=0; +#endif + } + break; + case BIO_CTRL_GET_CALLBACK: + { + void (**fptr)(const SSL *xssl,int type,int val); + + fptr=(void (**)(const SSL *xssl,int type,int val))ptr; + *fptr=SSL_get_info_callback(ssl); + } + break; + default: + ret=BIO_ctrl(ssl->rbio,cmd,num,ptr); + break; + } + return(ret); + } + +static long ssl_callback_ctrl(BIO *b, int cmd, bio_info_cb *fp) + { + SSL *ssl; + BIO_SSL *bs; + long ret=1; + + bs=(BIO_SSL *)b->ptr; + ssl=bs->ssl; + switch (cmd) + { + case BIO_CTRL_SET_CALLBACK: + { + /* FIXME: setting this via a completely different prototype + seems like a crap idea */ + SSL_set_info_callback(ssl,(void (*)(const SSL *,int,int))fp); + } + break; + default: + ret=BIO_callback_ctrl(ssl->rbio,cmd,fp); + break; + } + return(ret); + } + +static int ssl_puts(BIO *bp, const char *str) + { + int n,ret; + + n=strlen(str); + ret=BIO_write(bp,str,n); + return(ret); + } + +BIO *BIO_new_buffer_ssl_connect(SSL_CTX *ctx) + { +#ifndef OPENSSL_NO_SOCK + BIO *ret=NULL,*buf=NULL,*ssl=NULL; + + if ((buf=BIO_new(BIO_f_buffer())) == NULL) + return(NULL); + if ((ssl=BIO_new_ssl_connect(ctx)) == NULL) + goto err; + if ((ret=BIO_push(buf,ssl)) == NULL) + goto err; + return(ret); +err: + if (buf != NULL) BIO_free(buf); + if (ssl != NULL) BIO_free(ssl); +#endif + return(NULL); + } + +BIO *BIO_new_ssl_connect(SSL_CTX *ctx) + { +#ifndef OPENSSL_NO_SOCK + BIO *ret=NULL,*con=NULL,*ssl=NULL; + + if ((con=BIO_new(BIO_s_connect())) == NULL) + return(NULL); + if ((ssl=BIO_new_ssl(ctx,1)) == NULL) + goto err; + if ((ret=BIO_push(ssl,con)) == NULL) + goto err; + return(ret); +err: + if (con != NULL) BIO_free(con); +#endif + return(NULL); + } + +BIO *BIO_new_ssl(SSL_CTX *ctx, int client) + { + BIO *ret; + SSL *ssl; + + if ((ret=BIO_new(BIO_f_ssl())) == NULL) + return(NULL); + if ((ssl=SSL_new(ctx)) == NULL) + { + BIO_free(ret); + return(NULL); + } + if (client) + SSL_set_connect_state(ssl); + else + SSL_set_accept_state(ssl); + + BIO_set_ssl(ret,ssl,BIO_CLOSE); + return(ret); + } + +int BIO_ssl_copy_session_id(BIO *t, BIO *f) + { + t=BIO_find_type(t,BIO_TYPE_SSL); + f=BIO_find_type(f,BIO_TYPE_SSL); + if ((t == NULL) || (f == NULL)) + return(0); + if ( (((BIO_SSL *)t->ptr)->ssl == NULL) || + (((BIO_SSL *)f->ptr)->ssl == NULL)) + return(0); + SSL_copy_session_id(((BIO_SSL *)t->ptr)->ssl,((BIO_SSL *)f->ptr)->ssl); + return(1); + } + +void BIO_ssl_shutdown(BIO *b) + { + SSL *s; + + while (b != NULL) + { + if (b->method->type == BIO_TYPE_SSL) + { + s=((BIO_SSL *)b->ptr)->ssl; + SSL_shutdown(s); + break; + } + b=b->next_bio; + } + } diff --git a/node-v0.8.14/deps/openssl/openssl/ssl/d1_both.c b/node-v0.8.14/deps/openssl/openssl/ssl/d1_both.c new file mode 100644 index 0000000..9f898d6 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/ssl/d1_both.c @@ -0,0 +1,1419 @@ +/* ssl/d1_both.c */ +/* + * DTLS implementation written by Nagendra Modadugu + * (nagendra@cs.stanford.edu) for the OpenSSL project 2005. + */ +/* ==================================================================== + * Copyright (c) 1998-2005 The OpenSSL Project. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. All advertising materials mentioning features or use of this + * software must display the following acknowledgment: + * "This product includes software developed by the OpenSSL Project + * for use in the OpenSSL Toolkit. (http://www.openssl.org/)" + * + * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to + * endorse or promote products derived from this software without + * prior written permission. For written permission, please contact + * openssl-core@openssl.org. + * + * 5. Products derived from this software may not be called "OpenSSL" + * nor may "OpenSSL" appear in their names without prior written + * permission of the OpenSSL Project. + * + * 6. Redistributions of any form whatsoever must retain the following + * acknowledgment: + * "This product includes software developed by the OpenSSL Project + * for use in the OpenSSL Toolkit (http://www.openssl.org/)" + * + * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY + * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR + * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, + * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * ==================================================================== + * + * This product includes cryptographic software written by Eric Young + * (eay@cryptsoft.com). This product includes software written by Tim + * Hudson (tjh@cryptsoft.com). + * + */ +/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com) + * All rights reserved. + * + * This package is an SSL implementation written + * by Eric Young (eay@cryptsoft.com). + * The implementation was written so as to conform with Netscapes SSL. + * + * This library is free for commercial and non-commercial use as long as + * the following conditions are aheared to. The following conditions + * apply to all code found in this distribution, be it the RC4, RSA, + * lhash, DES, etc., code; not just the SSL code. The SSL documentation + * included with this distribution is covered by the same copyright terms + * except that the holder is Tim Hudson (tjh@cryptsoft.com). + * + * Copyright remains Eric Young's, and as such any Copyright notices in + * the code are not to be removed. + * If this package is used in a product, Eric Young should be given attribution + * as the author of the parts of the library used. + * This can be in the form of a textual message at program startup or + * in documentation (online or textual) provided with the package. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * "This product includes cryptographic software written by + * Eric Young (eay@cryptsoft.com)" + * The word 'cryptographic' can be left out if the rouines from the library + * being used are not cryptographic related :-). + * 4. If you include any Windows specific code (or a derivative thereof) from + * the apps directory (application code) you must include an acknowledgement: + * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)" + * + * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * + * The licence and distribution terms for any publically available version or + * derivative of this code cannot be changed. i.e. this code cannot simply be + * copied and put under another distribution licence + * [including the GNU Public Licence.] + */ + +#include +#include +#include +#include "ssl_locl.h" +#include +#include +#include +#include +#include + +#define RSMBLY_BITMASK_SIZE(msg_len) (((msg_len) + 7) / 8) + +#define RSMBLY_BITMASK_MARK(bitmask, start, end) { \ + if ((end) - (start) <= 8) { \ + long ii; \ + for (ii = (start); ii < (end); ii++) bitmask[((ii) >> 3)] |= (1 << ((ii) & 7)); \ + } else { \ + long ii; \ + bitmask[((start) >> 3)] |= bitmask_start_values[((start) & 7)]; \ + for (ii = (((start) >> 3) + 1); ii < ((((end) - 1)) >> 3); ii++) bitmask[ii] = 0xff; \ + bitmask[(((end) - 1) >> 3)] |= bitmask_end_values[((end) & 7)]; \ + } } + +#define RSMBLY_BITMASK_IS_COMPLETE(bitmask, msg_len, is_complete) { \ + long ii; \ + OPENSSL_assert((msg_len) > 0); \ + is_complete = 1; \ + if (bitmask[(((msg_len) - 1) >> 3)] != bitmask_end_values[((msg_len) & 7)]) is_complete = 0; \ + if (is_complete) for (ii = (((msg_len) - 1) >> 3) - 1; ii >= 0 ; ii--) \ + if (bitmask[ii] != 0xff) { is_complete = 0; break; } } + +#if 0 +#define RSMBLY_BITMASK_PRINT(bitmask, msg_len) { \ + long ii; \ + printf("bitmask: "); for (ii = 0; ii < (msg_len); ii++) \ + printf("%d ", (bitmask[ii >> 3] & (1 << (ii & 7))) >> (ii & 7)); \ + printf("\n"); } +#endif + +static unsigned char bitmask_start_values[] = {0xff, 0xfe, 0xfc, 0xf8, 0xf0, 0xe0, 0xc0, 0x80}; +static unsigned char bitmask_end_values[] = {0xff, 0x01, 0x03, 0x07, 0x0f, 0x1f, 0x3f, 0x7f}; + +/* XDTLS: figure out the right values */ +static unsigned int g_probable_mtu[] = {1500 - 28, 512 - 28, 256 - 28}; + +static unsigned int dtls1_guess_mtu(unsigned int curr_mtu); +static void dtls1_fix_message_header(SSL *s, unsigned long frag_off, + unsigned long frag_len); +static unsigned char *dtls1_write_message_header(SSL *s, + unsigned char *p); +static void dtls1_set_message_header_int(SSL *s, unsigned char mt, + unsigned long len, unsigned short seq_num, unsigned long frag_off, + unsigned long frag_len); +static long dtls1_get_message_fragment(SSL *s, int st1, int stn, + long max, int *ok); + +static hm_fragment * +dtls1_hm_fragment_new(unsigned long frag_len, int reassembly) + { + hm_fragment *frag = NULL; + unsigned char *buf = NULL; + unsigned char *bitmask = NULL; + + frag = (hm_fragment *)OPENSSL_malloc(sizeof(hm_fragment)); + if ( frag == NULL) + return NULL; + + if (frag_len) + { + buf = (unsigned char *)OPENSSL_malloc(frag_len); + if ( buf == NULL) + { + OPENSSL_free(frag); + return NULL; + } + } + + /* zero length fragment gets zero frag->fragment */ + frag->fragment = buf; + + /* Initialize reassembly bitmask if necessary */ + if (reassembly) + { + bitmask = (unsigned char *)OPENSSL_malloc(RSMBLY_BITMASK_SIZE(frag_len)); + if (bitmask == NULL) + { + if (buf != NULL) OPENSSL_free(buf); + OPENSSL_free(frag); + return NULL; + } + memset(bitmask, 0, RSMBLY_BITMASK_SIZE(frag_len)); + } + + frag->reassembly = bitmask; + + return frag; + } + +static void +dtls1_hm_fragment_free(hm_fragment *frag) + { + if (frag->fragment) OPENSSL_free(frag->fragment); + if (frag->reassembly) OPENSSL_free(frag->reassembly); + OPENSSL_free(frag); + } + +/* send s->init_buf in records of type 'type' (SSL3_RT_HANDSHAKE or SSL3_RT_CHANGE_CIPHER_SPEC) */ +int dtls1_do_write(SSL *s, int type) + { + int ret; + int curr_mtu; + unsigned int len, frag_off, mac_size, blocksize; + + /* AHA! Figure out the MTU, and stick to the right size */ + if ( ! (SSL_get_options(s) & SSL_OP_NO_QUERY_MTU)) + { + s->d1->mtu = + BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_QUERY_MTU, 0, NULL); + + /* I've seen the kernel return bogus numbers when it doesn't know + * (initial write), so just make sure we have a reasonable number */ + if ( s->d1->mtu < dtls1_min_mtu()) + { + s->d1->mtu = 0; + s->d1->mtu = dtls1_guess_mtu(s->d1->mtu); + BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_SET_MTU, + s->d1->mtu, NULL); + } + } +#if 0 + mtu = s->d1->mtu; + + fprintf(stderr, "using MTU = %d\n", mtu); + + mtu -= (DTLS1_HM_HEADER_LENGTH + DTLS1_RT_HEADER_LENGTH); + + curr_mtu = mtu - BIO_wpending(SSL_get_wbio(s)); + + if ( curr_mtu > 0) + mtu = curr_mtu; + else if ( ( ret = BIO_flush(SSL_get_wbio(s))) <= 0) + return ret; + + if ( BIO_wpending(SSL_get_wbio(s)) + s->init_num >= mtu) + { + ret = BIO_flush(SSL_get_wbio(s)); + if ( ret <= 0) + return ret; + mtu = s->d1->mtu - (DTLS1_HM_HEADER_LENGTH + DTLS1_RT_HEADER_LENGTH); + } +#endif + + OPENSSL_assert(s->d1->mtu >= dtls1_min_mtu()); /* should have something reasonable now */ + + if ( s->init_off == 0 && type == SSL3_RT_HANDSHAKE) + OPENSSL_assert(s->init_num == + (int)s->d1->w_msg_hdr.msg_len + DTLS1_HM_HEADER_LENGTH); + + if (s->write_hash) + mac_size = EVP_MD_CTX_size(s->write_hash); + else + mac_size = 0; + + if (s->enc_write_ctx && + (EVP_CIPHER_mode( s->enc_write_ctx->cipher) & EVP_CIPH_CBC_MODE)) + blocksize = 2 * EVP_CIPHER_block_size(s->enc_write_ctx->cipher); + else + blocksize = 0; + + frag_off = 0; + while( s->init_num) + { + curr_mtu = s->d1->mtu - BIO_wpending(SSL_get_wbio(s)) - + DTLS1_RT_HEADER_LENGTH - mac_size - blocksize; + + if ( curr_mtu <= DTLS1_HM_HEADER_LENGTH) + { + /* grr.. we could get an error if MTU picked was wrong */ + ret = BIO_flush(SSL_get_wbio(s)); + if ( ret <= 0) + return ret; + curr_mtu = s->d1->mtu - DTLS1_RT_HEADER_LENGTH - + mac_size - blocksize; + } + + if ( s->init_num > curr_mtu) + len = curr_mtu; + else + len = s->init_num; + + + /* XDTLS: this function is too long. split out the CCS part */ + if ( type == SSL3_RT_HANDSHAKE) + { + if ( s->init_off != 0) + { + OPENSSL_assert(s->init_off > DTLS1_HM_HEADER_LENGTH); + s->init_off -= DTLS1_HM_HEADER_LENGTH; + s->init_num += DTLS1_HM_HEADER_LENGTH; + + /* write atleast DTLS1_HM_HEADER_LENGTH bytes */ + if ( len <= DTLS1_HM_HEADER_LENGTH) + len += DTLS1_HM_HEADER_LENGTH; + } + + dtls1_fix_message_header(s, frag_off, + len - DTLS1_HM_HEADER_LENGTH); + + dtls1_write_message_header(s, (unsigned char *)&s->init_buf->data[s->init_off]); + + OPENSSL_assert(len >= DTLS1_HM_HEADER_LENGTH); + } + + ret=dtls1_write_bytes(s,type,&s->init_buf->data[s->init_off], + len); + if (ret < 0) + { + /* might need to update MTU here, but we don't know + * which previous packet caused the failure -- so can't + * really retransmit anything. continue as if everything + * is fine and wait for an alert to handle the + * retransmit + */ + if ( BIO_ctrl(SSL_get_wbio(s), + BIO_CTRL_DGRAM_MTU_EXCEEDED, 0, NULL) > 0 ) + s->d1->mtu = BIO_ctrl(SSL_get_wbio(s), + BIO_CTRL_DGRAM_QUERY_MTU, 0, NULL); + else + return(-1); + } + else + { + + /* bad if this assert fails, only part of the handshake + * message got sent. but why would this happen? */ + OPENSSL_assert(len == (unsigned int)ret); + + if (type == SSL3_RT_HANDSHAKE && ! s->d1->retransmitting) + { + /* should not be done for 'Hello Request's, but in that case + * we'll ignore the result anyway */ + unsigned char *p = (unsigned char *)&s->init_buf->data[s->init_off]; + const struct hm_header_st *msg_hdr = &s->d1->w_msg_hdr; + int xlen; + + if (frag_off == 0 && s->version != DTLS1_BAD_VER) + { + /* reconstruct message header is if it + * is being sent in single fragment */ + *p++ = msg_hdr->type; + l2n3(msg_hdr->msg_len,p); + s2n (msg_hdr->seq,p); + l2n3(0,p); + l2n3(msg_hdr->msg_len,p); + p -= DTLS1_HM_HEADER_LENGTH; + xlen = ret; + } + else + { + p += DTLS1_HM_HEADER_LENGTH; + xlen = ret - DTLS1_HM_HEADER_LENGTH; + } + + ssl3_finish_mac(s, p, xlen); + } + + if (ret == s->init_num) + { + if (s->msg_callback) + s->msg_callback(1, s->version, type, s->init_buf->data, + (size_t)(s->init_off + s->init_num), s, + s->msg_callback_arg); + + s->init_off = 0; /* done writing this message */ + s->init_num = 0; + + return(1); + } + s->init_off+=ret; + s->init_num-=ret; + frag_off += (ret -= DTLS1_HM_HEADER_LENGTH); + } + } + return(0); + } + + +/* Obtain handshake message of message type 'mt' (any if mt == -1), + * maximum acceptable body length 'max'. + * Read an entire handshake message. Handshake messages arrive in + * fragments. + */ +long dtls1_get_message(SSL *s, int st1, int stn, int mt, long max, int *ok) + { + int i, al; + struct hm_header_st *msg_hdr; + unsigned char *p; + unsigned long msg_len; + + /* s3->tmp is used to store messages that are unexpected, caused + * by the absence of an optional handshake message */ + if (s->s3->tmp.reuse_message) + { + s->s3->tmp.reuse_message=0; + if ((mt >= 0) && (s->s3->tmp.message_type != mt)) + { + al=SSL_AD_UNEXPECTED_MESSAGE; + SSLerr(SSL_F_DTLS1_GET_MESSAGE,SSL_R_UNEXPECTED_MESSAGE); + goto f_err; + } + *ok=1; + s->init_msg = s->init_buf->data + DTLS1_HM_HEADER_LENGTH; + s->init_num = (int)s->s3->tmp.message_size; + return s->init_num; + } + + msg_hdr = &s->d1->r_msg_hdr; + memset(msg_hdr, 0x00, sizeof(struct hm_header_st)); + +again: + i = dtls1_get_message_fragment(s, st1, stn, max, ok); + if ( i == DTLS1_HM_BAD_FRAGMENT || + i == DTLS1_HM_FRAGMENT_RETRY) /* bad fragment received */ + goto again; + else if ( i <= 0 && !*ok) + return i; + + p = (unsigned char *)s->init_buf->data; + msg_len = msg_hdr->msg_len; + + /* reconstruct message header */ + *(p++) = msg_hdr->type; + l2n3(msg_len,p); + s2n (msg_hdr->seq,p); + l2n3(0,p); + l2n3(msg_len,p); + if (s->version != DTLS1_BAD_VER) { + p -= DTLS1_HM_HEADER_LENGTH; + msg_len += DTLS1_HM_HEADER_LENGTH; + } + + ssl3_finish_mac(s, p, msg_len); + if (s->msg_callback) + s->msg_callback(0, s->version, SSL3_RT_HANDSHAKE, + p, msg_len, + s, s->msg_callback_arg); + + memset(msg_hdr, 0x00, sizeof(struct hm_header_st)); + + /* Don't change sequence numbers while listening */ + if (!s->d1->listen) + s->d1->handshake_read_seq++; + + s->init_msg = s->init_buf->data + DTLS1_HM_HEADER_LENGTH; + return s->init_num; + +f_err: + ssl3_send_alert(s,SSL3_AL_FATAL,al); + *ok = 0; + return -1; + } + + +static int dtls1_preprocess_fragment(SSL *s,struct hm_header_st *msg_hdr,int max) + { + size_t frag_off,frag_len,msg_len; + + msg_len = msg_hdr->msg_len; + frag_off = msg_hdr->frag_off; + frag_len = msg_hdr->frag_len; + + /* sanity checking */ + if ( (frag_off+frag_len) > msg_len) + { + SSLerr(SSL_F_DTLS1_PREPROCESS_FRAGMENT,SSL_R_EXCESSIVE_MESSAGE_SIZE); + return SSL_AD_ILLEGAL_PARAMETER; + } + + if ( (frag_off+frag_len) > (unsigned long)max) + { + SSLerr(SSL_F_DTLS1_PREPROCESS_FRAGMENT,SSL_R_EXCESSIVE_MESSAGE_SIZE); + return SSL_AD_ILLEGAL_PARAMETER; + } + + if ( s->d1->r_msg_hdr.frag_off == 0) /* first fragment */ + { + /* msg_len is limited to 2^24, but is effectively checked + * against max above */ + if (!BUF_MEM_grow_clean(s->init_buf,msg_len+DTLS1_HM_HEADER_LENGTH)) + { + SSLerr(SSL_F_DTLS1_PREPROCESS_FRAGMENT,ERR_R_BUF_LIB); + return SSL_AD_INTERNAL_ERROR; + } + + s->s3->tmp.message_size = msg_len; + s->d1->r_msg_hdr.msg_len = msg_len; + s->s3->tmp.message_type = msg_hdr->type; + s->d1->r_msg_hdr.type = msg_hdr->type; + s->d1->r_msg_hdr.seq = msg_hdr->seq; + } + else if (msg_len != s->d1->r_msg_hdr.msg_len) + { + /* They must be playing with us! BTW, failure to enforce + * upper limit would open possibility for buffer overrun. */ + SSLerr(SSL_F_DTLS1_PREPROCESS_FRAGMENT,SSL_R_EXCESSIVE_MESSAGE_SIZE); + return SSL_AD_ILLEGAL_PARAMETER; + } + + return 0; /* no error */ + } + + +static int +dtls1_retrieve_buffered_fragment(SSL *s, long max, int *ok) + { + /* (0) check whether the desired fragment is available + * if so: + * (1) copy over the fragment to s->init_buf->data[] + * (2) update s->init_num + */ + pitem *item; + hm_fragment *frag; + int al; + + *ok = 0; + item = pqueue_peek(s->d1->buffered_messages); + if ( item == NULL) + return 0; + + frag = (hm_fragment *)item->data; + + /* Don't return if reassembly still in progress */ + if (frag->reassembly != NULL) + return 0; + + if ( s->d1->handshake_read_seq == frag->msg_header.seq) + { + unsigned long frag_len = frag->msg_header.frag_len; + pqueue_pop(s->d1->buffered_messages); + + al=dtls1_preprocess_fragment(s,&frag->msg_header,max); + + if (al==0) /* no alert */ + { + unsigned char *p = (unsigned char *)s->init_buf->data+DTLS1_HM_HEADER_LENGTH; + memcpy(&p[frag->msg_header.frag_off], + frag->fragment,frag->msg_header.frag_len); + } + + dtls1_hm_fragment_free(frag); + pitem_free(item); + + if (al==0) + { + *ok = 1; + return frag_len; + } + + ssl3_send_alert(s,SSL3_AL_FATAL,al); + s->init_num = 0; + *ok = 0; + return -1; + } + else + return 0; + } + + +static int +dtls1_reassemble_fragment(SSL *s, struct hm_header_st* msg_hdr, int *ok) + { + hm_fragment *frag = NULL; + pitem *item = NULL; + int i = -1, is_complete; + unsigned char seq64be[8]; + unsigned long frag_len = msg_hdr->frag_len, max_len; + + if ((msg_hdr->frag_off+frag_len) > msg_hdr->msg_len) + goto err; + + /* Determine maximum allowed message size. Depends on (user set) + * maximum certificate length, but 16k is minimum. + */ + if (DTLS1_HM_HEADER_LENGTH + SSL3_RT_MAX_ENCRYPTED_LENGTH < s->max_cert_list) + max_len = s->max_cert_list; + else + max_len = DTLS1_HM_HEADER_LENGTH + SSL3_RT_MAX_ENCRYPTED_LENGTH; + + if ((msg_hdr->frag_off+frag_len) > max_len) + goto err; + + /* Try to find item in queue */ + memset(seq64be,0,sizeof(seq64be)); + seq64be[6] = (unsigned char) (msg_hdr->seq>>8); + seq64be[7] = (unsigned char) msg_hdr->seq; + item = pqueue_find(s->d1->buffered_messages, seq64be); + + if (item == NULL) + { + frag = dtls1_hm_fragment_new(msg_hdr->msg_len, 1); + if ( frag == NULL) + goto err; + memcpy(&(frag->msg_header), msg_hdr, sizeof(*msg_hdr)); + frag->msg_header.frag_len = frag->msg_header.msg_len; + frag->msg_header.frag_off = 0; + } + else + frag = (hm_fragment*) item->data; + + /* If message is already reassembled, this must be a + * retransmit and can be dropped. + */ + if (frag->reassembly == NULL) + { + unsigned char devnull [256]; + + while (frag_len) + { + i = s->method->ssl_read_bytes(s,SSL3_RT_HANDSHAKE, + devnull, + frag_len>sizeof(devnull)?sizeof(devnull):frag_len,0); + if (i<=0) goto err; + frag_len -= i; + } + return DTLS1_HM_FRAGMENT_RETRY; + } + + /* read the body of the fragment (header has already been read */ + i = s->method->ssl_read_bytes(s,SSL3_RT_HANDSHAKE, + frag->fragment + msg_hdr->frag_off,frag_len,0); + if (i<=0 || (unsigned long)i!=frag_len) + goto err; + + RSMBLY_BITMASK_MARK(frag->reassembly, (long)msg_hdr->frag_off, + (long)(msg_hdr->frag_off + frag_len)); + + RSMBLY_BITMASK_IS_COMPLETE(frag->reassembly, (long)msg_hdr->msg_len, + is_complete); + + if (is_complete) + { + OPENSSL_free(frag->reassembly); + frag->reassembly = NULL; + } + + if (item == NULL) + { + memset(seq64be,0,sizeof(seq64be)); + seq64be[6] = (unsigned char)(msg_hdr->seq>>8); + seq64be[7] = (unsigned char)(msg_hdr->seq); + + item = pitem_new(seq64be, frag); + if (item == NULL) + { + goto err; + i = -1; + } + + pqueue_insert(s->d1->buffered_messages, item); + } + + return DTLS1_HM_FRAGMENT_RETRY; + +err: + if (frag != NULL) dtls1_hm_fragment_free(frag); + if (item != NULL) OPENSSL_free(item); + *ok = 0; + return i; + } + + +static int +dtls1_process_out_of_seq_message(SSL *s, struct hm_header_st* msg_hdr, int *ok) +{ + int i=-1; + hm_fragment *frag = NULL; + pitem *item = NULL; + unsigned char seq64be[8]; + unsigned long frag_len = msg_hdr->frag_len; + + if ((msg_hdr->frag_off+frag_len) > msg_hdr->msg_len) + goto err; + + /* Try to find item in queue, to prevent duplicate entries */ + memset(seq64be,0,sizeof(seq64be)); + seq64be[6] = (unsigned char) (msg_hdr->seq>>8); + seq64be[7] = (unsigned char) msg_hdr->seq; + item = pqueue_find(s->d1->buffered_messages, seq64be); + + /* If we already have an entry and this one is a fragment, + * don't discard it and rather try to reassemble it. + */ + if (item != NULL && frag_len < msg_hdr->msg_len) + item = NULL; + + /* Discard the message if sequence number was already there, is + * too far in the future, already in the queue or if we received + * a FINISHED before the SERVER_HELLO, which then must be a stale + * retransmit. + */ + if (msg_hdr->seq <= s->d1->handshake_read_seq || + msg_hdr->seq > s->d1->handshake_read_seq + 10 || item != NULL || + (s->d1->handshake_read_seq == 0 && msg_hdr->type == SSL3_MT_FINISHED)) + { + unsigned char devnull [256]; + + while (frag_len) + { + i = s->method->ssl_read_bytes(s,SSL3_RT_HANDSHAKE, + devnull, + frag_len>sizeof(devnull)?sizeof(devnull):frag_len,0); + if (i<=0) goto err; + frag_len -= i; + } + } + else + { + if (frag_len && frag_len < msg_hdr->msg_len) + return dtls1_reassemble_fragment(s, msg_hdr, ok); + + frag = dtls1_hm_fragment_new(frag_len, 0); + if ( frag == NULL) + goto err; + + memcpy(&(frag->msg_header), msg_hdr, sizeof(*msg_hdr)); + + if (frag_len) + { + /* read the body of the fragment (header has already been read */ + i = s->method->ssl_read_bytes(s,SSL3_RT_HANDSHAKE, + frag->fragment,frag_len,0); + if (i<=0 || (unsigned long)i!=frag_len) + goto err; + } + + memset(seq64be,0,sizeof(seq64be)); + seq64be[6] = (unsigned char)(msg_hdr->seq>>8); + seq64be[7] = (unsigned char)(msg_hdr->seq); + + item = pitem_new(seq64be, frag); + if ( item == NULL) + goto err; + + pqueue_insert(s->d1->buffered_messages, item); + } + + return DTLS1_HM_FRAGMENT_RETRY; + +err: + if ( frag != NULL) dtls1_hm_fragment_free(frag); + if ( item != NULL) OPENSSL_free(item); + *ok = 0; + return i; + } + + +static long +dtls1_get_message_fragment(SSL *s, int st1, int stn, long max, int *ok) + { + unsigned char wire[DTLS1_HM_HEADER_LENGTH]; + unsigned long len, frag_off, frag_len; + int i,al; + struct hm_header_st msg_hdr; + + /* see if we have the required fragment already */ + if ((frag_len = dtls1_retrieve_buffered_fragment(s,max,ok)) || *ok) + { + if (*ok) s->init_num = frag_len; + return frag_len; + } + + /* read handshake message header */ + i=s->method->ssl_read_bytes(s,SSL3_RT_HANDSHAKE,wire, + DTLS1_HM_HEADER_LENGTH, 0); + if (i <= 0) /* nbio, or an error */ + { + s->rwstate=SSL_READING; + *ok = 0; + return i; + } + /* Handshake fails if message header is incomplete */ + if (i != DTLS1_HM_HEADER_LENGTH) + { + al=SSL_AD_UNEXPECTED_MESSAGE; + SSLerr(SSL_F_DTLS1_GET_MESSAGE_FRAGMENT,SSL_R_UNEXPECTED_MESSAGE); + goto f_err; + } + + /* parse the message fragment header */ + dtls1_get_message_header(wire, &msg_hdr); + + /* + * if this is a future (or stale) message it gets buffered + * (or dropped)--no further processing at this time + * While listening, we accept seq 1 (ClientHello with cookie) + * although we're still expecting seq 0 (ClientHello) + */ + if (msg_hdr.seq != s->d1->handshake_read_seq && !(s->d1->listen && msg_hdr.seq == 1)) + return dtls1_process_out_of_seq_message(s, &msg_hdr, ok); + + len = msg_hdr.msg_len; + frag_off = msg_hdr.frag_off; + frag_len = msg_hdr.frag_len; + + if (frag_len && frag_len < len) + return dtls1_reassemble_fragment(s, &msg_hdr, ok); + + if (!s->server && s->d1->r_msg_hdr.frag_off == 0 && + wire[0] == SSL3_MT_HELLO_REQUEST) + { + /* The server may always send 'Hello Request' messages -- + * we are doing a handshake anyway now, so ignore them + * if their format is correct. Does not count for + * 'Finished' MAC. */ + if (wire[1] == 0 && wire[2] == 0 && wire[3] == 0) + { + if (s->msg_callback) + s->msg_callback(0, s->version, SSL3_RT_HANDSHAKE, + wire, DTLS1_HM_HEADER_LENGTH, s, + s->msg_callback_arg); + + s->init_num = 0; + return dtls1_get_message_fragment(s, st1, stn, + max, ok); + } + else /* Incorrectly formated Hello request */ + { + al=SSL_AD_UNEXPECTED_MESSAGE; + SSLerr(SSL_F_DTLS1_GET_MESSAGE_FRAGMENT,SSL_R_UNEXPECTED_MESSAGE); + goto f_err; + } + } + + if ((al=dtls1_preprocess_fragment(s,&msg_hdr,max))) + goto f_err; + + /* XDTLS: ressurect this when restart is in place */ + s->state=stn; + + if ( frag_len > 0) + { + unsigned char *p=(unsigned char *)s->init_buf->data+DTLS1_HM_HEADER_LENGTH; + + i=s->method->ssl_read_bytes(s,SSL3_RT_HANDSHAKE, + &p[frag_off],frag_len,0); + /* XDTLS: fix this--message fragments cannot span multiple packets */ + if (i <= 0) + { + s->rwstate=SSL_READING; + *ok = 0; + return i; + } + } + else + i = 0; + + /* XDTLS: an incorrectly formatted fragment should cause the + * handshake to fail */ + if (i != (int)frag_len) + { + al=SSL3_AD_ILLEGAL_PARAMETER; + SSLerr(SSL_F_DTLS1_GET_MESSAGE_FRAGMENT,SSL3_AD_ILLEGAL_PARAMETER); + goto f_err; + } + + *ok = 1; + + /* Note that s->init_num is *not* used as current offset in + * s->init_buf->data, but as a counter summing up fragments' + * lengths: as soon as they sum up to handshake packet + * length, we assume we have got all the fragments. */ + s->init_num = frag_len; + return frag_len; + +f_err: + ssl3_send_alert(s,SSL3_AL_FATAL,al); + s->init_num = 0; + + *ok=0; + return(-1); + } + +int dtls1_send_finished(SSL *s, int a, int b, const char *sender, int slen) + { + unsigned char *p,*d; + int i; + unsigned long l; + + if (s->state == a) + { + d=(unsigned char *)s->init_buf->data; + p= &(d[DTLS1_HM_HEADER_LENGTH]); + + i=s->method->ssl3_enc->final_finish_mac(s, + sender,slen,s->s3->tmp.finish_md); + s->s3->tmp.finish_md_len = i; + memcpy(p, s->s3->tmp.finish_md, i); + p+=i; + l=i; + + /* Copy the finished so we can use it for + * renegotiation checks + */ + if(s->type == SSL_ST_CONNECT) + { + OPENSSL_assert(i <= EVP_MAX_MD_SIZE); + memcpy(s->s3->previous_client_finished, + s->s3->tmp.finish_md, i); + s->s3->previous_client_finished_len=i; + } + else + { + OPENSSL_assert(i <= EVP_MAX_MD_SIZE); + memcpy(s->s3->previous_server_finished, + s->s3->tmp.finish_md, i); + s->s3->previous_server_finished_len=i; + } + +#ifdef OPENSSL_SYS_WIN16 + /* MSVC 1.5 does not clear the top bytes of the word unless + * I do this. + */ + l&=0xffff; +#endif + + d = dtls1_set_message_header(s, d, SSL3_MT_FINISHED, l, 0, l); + s->init_num=(int)l+DTLS1_HM_HEADER_LENGTH; + s->init_off=0; + + /* buffer the message to handle re-xmits */ + dtls1_buffer_message(s, 0); + + s->state=b; + } + + /* SSL3_ST_SEND_xxxxxx_HELLO_B */ + return(dtls1_do_write(s,SSL3_RT_HANDSHAKE)); + } + +/* for these 2 messages, we need to + * ssl->enc_read_ctx re-init + * ssl->s3->read_sequence zero + * ssl->s3->read_mac_secret re-init + * ssl->session->read_sym_enc assign + * ssl->session->read_compression assign + * ssl->session->read_hash assign + */ +int dtls1_send_change_cipher_spec(SSL *s, int a, int b) + { + unsigned char *p; + + if (s->state == a) + { + p=(unsigned char *)s->init_buf->data; + *p++=SSL3_MT_CCS; + s->d1->handshake_write_seq = s->d1->next_handshake_write_seq; + s->init_num=DTLS1_CCS_HEADER_LENGTH; + + if (s->version == DTLS1_BAD_VER) { + s->d1->next_handshake_write_seq++; + s2n(s->d1->handshake_write_seq,p); + s->init_num+=2; + } + + s->init_off=0; + + dtls1_set_message_header_int(s, SSL3_MT_CCS, 0, + s->d1->handshake_write_seq, 0, 0); + + /* buffer the message to handle re-xmits */ + dtls1_buffer_message(s, 1); + + s->state=b; + } + + /* SSL3_ST_CW_CHANGE_B */ + return(dtls1_do_write(s,SSL3_RT_CHANGE_CIPHER_SPEC)); + } + +static int dtls1_add_cert_to_buf(BUF_MEM *buf, unsigned long *l, X509 *x) + { + int n; + unsigned char *p; + + n=i2d_X509(x,NULL); + if (!BUF_MEM_grow_clean(buf,(int)(n+(*l)+3))) + { + SSLerr(SSL_F_DTLS1_ADD_CERT_TO_BUF,ERR_R_BUF_LIB); + return 0; + } + p=(unsigned char *)&(buf->data[*l]); + l2n3(n,p); + i2d_X509(x,&p); + *l+=n+3; + + return 1; + } +unsigned long dtls1_output_cert_chain(SSL *s, X509 *x) + { + unsigned char *p; + int i; + unsigned long l= 3 + DTLS1_HM_HEADER_LENGTH; + BUF_MEM *buf; + + /* TLSv1 sends a chain with nothing in it, instead of an alert */ + buf=s->init_buf; + if (!BUF_MEM_grow_clean(buf,10)) + { + SSLerr(SSL_F_DTLS1_OUTPUT_CERT_CHAIN,ERR_R_BUF_LIB); + return(0); + } + if (x != NULL) + { + X509_STORE_CTX xs_ctx; + + if (!X509_STORE_CTX_init(&xs_ctx,s->ctx->cert_store,x,NULL)) + { + SSLerr(SSL_F_DTLS1_OUTPUT_CERT_CHAIN,ERR_R_X509_LIB); + return(0); + } + + X509_verify_cert(&xs_ctx); + /* Don't leave errors in the queue */ + ERR_clear_error(); + for (i=0; i < sk_X509_num(xs_ctx.chain); i++) + { + x = sk_X509_value(xs_ctx.chain, i); + + if (!dtls1_add_cert_to_buf(buf, &l, x)) + { + X509_STORE_CTX_cleanup(&xs_ctx); + return 0; + } + } + X509_STORE_CTX_cleanup(&xs_ctx); + } + /* Thawte special :-) */ + for (i=0; ictx->extra_certs); i++) + { + x=sk_X509_value(s->ctx->extra_certs,i); + if (!dtls1_add_cert_to_buf(buf, &l, x)) + return 0; + } + + l-= (3 + DTLS1_HM_HEADER_LENGTH); + + p=(unsigned char *)&(buf->data[DTLS1_HM_HEADER_LENGTH]); + l2n3(l,p); + l+=3; + p=(unsigned char *)&(buf->data[0]); + p = dtls1_set_message_header(s, p, SSL3_MT_CERTIFICATE, l, 0, l); + + l+=DTLS1_HM_HEADER_LENGTH; + return(l); + } + +int dtls1_read_failed(SSL *s, int code) + { + if ( code > 0) + { + fprintf( stderr, "invalid state reached %s:%d", __FILE__, __LINE__); + return 1; + } + + if (!dtls1_is_timer_expired(s)) + { + /* not a timeout, none of our business, + let higher layers handle this. in fact it's probably an error */ + return code; + } + + if ( ! SSL_in_init(s)) /* done, no need to send a retransmit */ + { + BIO_set_flags(SSL_get_rbio(s), BIO_FLAGS_READ); + return code; + } + +#if 0 /* for now, each alert contains only one record number */ + item = pqueue_peek(state->rcvd_records); + if ( item ) + { + /* send an alert immediately for all the missing records */ + } + else +#endif + +#if 0 /* no more alert sending, just retransmit the last set of messages */ + if ( state->timeout.read_timeouts >= DTLS1_TMO_READ_COUNT) + ssl3_send_alert(s,SSL3_AL_WARNING, + DTLS1_AD_MISSING_HANDSHAKE_MESSAGE); +#endif + + return dtls1_handle_timeout(s); + } + +int +dtls1_get_queue_priority(unsigned short seq, int is_ccs) + { + /* The index of the retransmission queue actually is the message sequence number, + * since the queue only contains messages of a single handshake. However, the + * ChangeCipherSpec has no message sequence number and so using only the sequence + * will result in the CCS and Finished having the same index. To prevent this, + * the sequence number is multiplied by 2. In case of a CCS 1 is subtracted. + * This does not only differ CSS and Finished, it also maintains the order of the + * index (important for priority queues) and fits in the unsigned short variable. + */ + return seq * 2 - is_ccs; + } + +int +dtls1_retransmit_buffered_messages(SSL *s) + { + pqueue sent = s->d1->sent_messages; + piterator iter; + pitem *item; + hm_fragment *frag; + int found = 0; + + iter = pqueue_iterator(sent); + + for ( item = pqueue_next(&iter); item != NULL; item = pqueue_next(&iter)) + { + frag = (hm_fragment *)item->data; + if ( dtls1_retransmit_message(s, + (unsigned short)dtls1_get_queue_priority(frag->msg_header.seq, frag->msg_header.is_ccs), + 0, &found) <= 0 && found) + { + fprintf(stderr, "dtls1_retransmit_message() failed\n"); + return -1; + } + } + + return 1; + } + +int +dtls1_buffer_message(SSL *s, int is_ccs) + { + pitem *item; + hm_fragment *frag; + unsigned char seq64be[8]; + + /* this function is called immediately after a message has + * been serialized */ + OPENSSL_assert(s->init_off == 0); + + frag = dtls1_hm_fragment_new(s->init_num, 0); + + memcpy(frag->fragment, s->init_buf->data, s->init_num); + + if ( is_ccs) + { + OPENSSL_assert(s->d1->w_msg_hdr.msg_len + + ((s->version==DTLS1_VERSION)?DTLS1_CCS_HEADER_LENGTH:3) == (unsigned int)s->init_num); + } + else + { + OPENSSL_assert(s->d1->w_msg_hdr.msg_len + + DTLS1_HM_HEADER_LENGTH == (unsigned int)s->init_num); + } + + frag->msg_header.msg_len = s->d1->w_msg_hdr.msg_len; + frag->msg_header.seq = s->d1->w_msg_hdr.seq; + frag->msg_header.type = s->d1->w_msg_hdr.type; + frag->msg_header.frag_off = 0; + frag->msg_header.frag_len = s->d1->w_msg_hdr.msg_len; + frag->msg_header.is_ccs = is_ccs; + + /* save current state*/ + frag->msg_header.saved_retransmit_state.enc_write_ctx = s->enc_write_ctx; + frag->msg_header.saved_retransmit_state.write_hash = s->write_hash; + frag->msg_header.saved_retransmit_state.compress = s->compress; + frag->msg_header.saved_retransmit_state.session = s->session; + frag->msg_header.saved_retransmit_state.epoch = s->d1->w_epoch; + + memset(seq64be,0,sizeof(seq64be)); + seq64be[6] = (unsigned char)(dtls1_get_queue_priority(frag->msg_header.seq, + frag->msg_header.is_ccs)>>8); + seq64be[7] = (unsigned char)(dtls1_get_queue_priority(frag->msg_header.seq, + frag->msg_header.is_ccs)); + + item = pitem_new(seq64be, frag); + if ( item == NULL) + { + dtls1_hm_fragment_free(frag); + return 0; + } + +#if 0 + fprintf( stderr, "buffered messge: \ttype = %xx\n", msg_buf->type); + fprintf( stderr, "\t\t\t\t\tlen = %d\n", msg_buf->len); + fprintf( stderr, "\t\t\t\t\tseq_num = %d\n", msg_buf->seq_num); +#endif + + pqueue_insert(s->d1->sent_messages, item); + return 1; + } + +int +dtls1_retransmit_message(SSL *s, unsigned short seq, unsigned long frag_off, + int *found) + { + int ret; + /* XDTLS: for now assuming that read/writes are blocking */ + pitem *item; + hm_fragment *frag ; + unsigned long header_length; + unsigned char seq64be[8]; + struct dtls1_retransmit_state saved_state; + unsigned char save_write_sequence[8]; + + /* + OPENSSL_assert(s->init_num == 0); + OPENSSL_assert(s->init_off == 0); + */ + + /* XDTLS: the requested message ought to be found, otherwise error */ + memset(seq64be,0,sizeof(seq64be)); + seq64be[6] = (unsigned char)(seq>>8); + seq64be[7] = (unsigned char)seq; + + item = pqueue_find(s->d1->sent_messages, seq64be); + if ( item == NULL) + { + fprintf(stderr, "retransmit: message %d non-existant\n", seq); + *found = 0; + return 0; + } + + *found = 1; + frag = (hm_fragment *)item->data; + + if ( frag->msg_header.is_ccs) + header_length = DTLS1_CCS_HEADER_LENGTH; + else + header_length = DTLS1_HM_HEADER_LENGTH; + + memcpy(s->init_buf->data, frag->fragment, + frag->msg_header.msg_len + header_length); + s->init_num = frag->msg_header.msg_len + header_length; + + dtls1_set_message_header_int(s, frag->msg_header.type, + frag->msg_header.msg_len, frag->msg_header.seq, 0, + frag->msg_header.frag_len); + + /* save current state */ + saved_state.enc_write_ctx = s->enc_write_ctx; + saved_state.write_hash = s->write_hash; + saved_state.compress = s->compress; + saved_state.session = s->session; + saved_state.epoch = s->d1->w_epoch; + saved_state.epoch = s->d1->w_epoch; + + s->d1->retransmitting = 1; + + /* restore state in which the message was originally sent */ + s->enc_write_ctx = frag->msg_header.saved_retransmit_state.enc_write_ctx; + s->write_hash = frag->msg_header.saved_retransmit_state.write_hash; + s->compress = frag->msg_header.saved_retransmit_state.compress; + s->session = frag->msg_header.saved_retransmit_state.session; + s->d1->w_epoch = frag->msg_header.saved_retransmit_state.epoch; + + if (frag->msg_header.saved_retransmit_state.epoch == saved_state.epoch - 1) + { + memcpy(save_write_sequence, s->s3->write_sequence, sizeof(s->s3->write_sequence)); + memcpy(s->s3->write_sequence, s->d1->last_write_sequence, sizeof(s->s3->write_sequence)); + } + + ret = dtls1_do_write(s, frag->msg_header.is_ccs ? + SSL3_RT_CHANGE_CIPHER_SPEC : SSL3_RT_HANDSHAKE); + + /* restore current state */ + s->enc_write_ctx = saved_state.enc_write_ctx; + s->write_hash = saved_state.write_hash; + s->compress = saved_state.compress; + s->session = saved_state.session; + s->d1->w_epoch = saved_state.epoch; + + if (frag->msg_header.saved_retransmit_state.epoch == saved_state.epoch - 1) + { + memcpy(s->d1->last_write_sequence, s->s3->write_sequence, sizeof(s->s3->write_sequence)); + memcpy(s->s3->write_sequence, save_write_sequence, sizeof(s->s3->write_sequence)); + } + + s->d1->retransmitting = 0; + + (void)BIO_flush(SSL_get_wbio(s)); + return ret; + } + +/* call this function when the buffered messages are no longer needed */ +void +dtls1_clear_record_buffer(SSL *s) + { + pitem *item; + + for(item = pqueue_pop(s->d1->sent_messages); + item != NULL; item = pqueue_pop(s->d1->sent_messages)) + { + dtls1_hm_fragment_free((hm_fragment *)item->data); + pitem_free(item); + } + } + + +unsigned char * +dtls1_set_message_header(SSL *s, unsigned char *p, unsigned char mt, + unsigned long len, unsigned long frag_off, unsigned long frag_len) + { + /* Don't change sequence numbers while listening */ + if (frag_off == 0 && !s->d1->listen) + { + s->d1->handshake_write_seq = s->d1->next_handshake_write_seq; + s->d1->next_handshake_write_seq++; + } + + dtls1_set_message_header_int(s, mt, len, s->d1->handshake_write_seq, + frag_off, frag_len); + + return p += DTLS1_HM_HEADER_LENGTH; + } + + +/* don't actually do the writing, wait till the MTU has been retrieved */ +static void +dtls1_set_message_header_int(SSL *s, unsigned char mt, + unsigned long len, unsigned short seq_num, unsigned long frag_off, + unsigned long frag_len) + { + struct hm_header_st *msg_hdr = &s->d1->w_msg_hdr; + + msg_hdr->type = mt; + msg_hdr->msg_len = len; + msg_hdr->seq = seq_num; + msg_hdr->frag_off = frag_off; + msg_hdr->frag_len = frag_len; + } + +static void +dtls1_fix_message_header(SSL *s, unsigned long frag_off, + unsigned long frag_len) + { + struct hm_header_st *msg_hdr = &s->d1->w_msg_hdr; + + msg_hdr->frag_off = frag_off; + msg_hdr->frag_len = frag_len; + } + +static unsigned char * +dtls1_write_message_header(SSL *s, unsigned char *p) + { + struct hm_header_st *msg_hdr = &s->d1->w_msg_hdr; + + *p++ = msg_hdr->type; + l2n3(msg_hdr->msg_len, p); + + s2n(msg_hdr->seq, p); + l2n3(msg_hdr->frag_off, p); + l2n3(msg_hdr->frag_len, p); + + return p; + } + +unsigned int +dtls1_min_mtu(void) + { + return (g_probable_mtu[(sizeof(g_probable_mtu) / + sizeof(g_probable_mtu[0])) - 1]); + } + +static unsigned int +dtls1_guess_mtu(unsigned int curr_mtu) + { + unsigned int i; + + if ( curr_mtu == 0 ) + return g_probable_mtu[0] ; + + for ( i = 0; i < sizeof(g_probable_mtu)/sizeof(g_probable_mtu[0]); i++) + if ( curr_mtu > g_probable_mtu[i]) + return g_probable_mtu[i]; + + return curr_mtu; + } + +void +dtls1_get_message_header(unsigned char *data, struct hm_header_st *msg_hdr) + { + memset(msg_hdr, 0x00, sizeof(struct hm_header_st)); + msg_hdr->type = *(data++); + n2l3(data, msg_hdr->msg_len); + + n2s(data, msg_hdr->seq); + n2l3(data, msg_hdr->frag_off); + n2l3(data, msg_hdr->frag_len); + } + +void +dtls1_get_ccs_header(unsigned char *data, struct ccs_header_st *ccs_hdr) + { + memset(ccs_hdr, 0x00, sizeof(struct ccs_header_st)); + + ccs_hdr->type = *(data++); + } diff --git a/node-v0.8.14/deps/openssl/openssl/ssl/d1_clnt.c b/node-v0.8.14/deps/openssl/openssl/ssl/d1_clnt.c new file mode 100644 index 0000000..5776671 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/ssl/d1_clnt.c @@ -0,0 +1,1542 @@ +/* ssl/d1_clnt.c */ +/* + * DTLS implementation written by Nagendra Modadugu + * (nagendra@cs.stanford.edu) for the OpenSSL project 2005. + */ +/* ==================================================================== + * Copyright (c) 1999-2007 The OpenSSL Project. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. All advertising materials mentioning features or use of this + * software must display the following acknowledgment: + * "This product includes software developed by the OpenSSL Project + * for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)" + * + * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to + * endorse or promote products derived from this software without + * prior written permission. For written permission, please contact + * openssl-core@OpenSSL.org. + * + * 5. Products derived from this software may not be called "OpenSSL" + * nor may "OpenSSL" appear in their names without prior written + * permission of the OpenSSL Project. + * + * 6. Redistributions of any form whatsoever must retain the following + * acknowledgment: + * "This product includes software developed by the OpenSSL Project + * for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)" + * + * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY + * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR + * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, + * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * ==================================================================== + * + * This product includes cryptographic software written by Eric Young + * (eay@cryptsoft.com). This product includes software written by Tim + * Hudson (tjh@cryptsoft.com). + * + */ +/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com) + * All rights reserved. + * + * This package is an SSL implementation written + * by Eric Young (eay@cryptsoft.com). + * The implementation was written so as to conform with Netscapes SSL. + * + * This library is free for commercial and non-commercial use as long as + * the following conditions are aheared to. The following conditions + * apply to all code found in this distribution, be it the RC4, RSA, + * lhash, DES, etc., code; not just the SSL code. The SSL documentation + * included with this distribution is covered by the same copyright terms + * except that the holder is Tim Hudson (tjh@cryptsoft.com). + * + * Copyright remains Eric Young's, and as such any Copyright notices in + * the code are not to be removed. + * If this package is used in a product, Eric Young should be given attribution + * as the author of the parts of the library used. + * This can be in the form of a textual message at program startup or + * in documentation (online or textual) provided with the package. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * "This product includes cryptographic software written by + * Eric Young (eay@cryptsoft.com)" + * The word 'cryptographic' can be left out if the rouines from the library + * being used are not cryptographic related :-). + * 4. If you include any Windows specific code (or a derivative thereof) from + * the apps directory (application code) you must include an acknowledgement: + * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)" + * + * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * + * The licence and distribution terms for any publically available version or + * derivative of this code cannot be changed. i.e. this code cannot simply be + * copied and put under another distribution licence + * [including the GNU Public Licence.] + */ + +#include +#include "ssl_locl.h" +#ifndef OPENSSL_NO_KRB5 +#include "kssl_lcl.h" +#endif +#include +#include +#include +#include +#include +#include +#ifndef OPENSSL_NO_DH +#include +#endif + +static const SSL_METHOD *dtls1_get_client_method(int ver); +static int dtls1_get_hello_verify(SSL *s); + +static const SSL_METHOD *dtls1_get_client_method(int ver) + { + if (ver == DTLS1_VERSION || ver == DTLS1_BAD_VER) + return(DTLSv1_client_method()); + else + return(NULL); + } + +IMPLEMENT_dtls1_meth_func(DTLSv1_client_method, + ssl_undefined_function, + dtls1_connect, + dtls1_get_client_method) + +int dtls1_connect(SSL *s) + { + BUF_MEM *buf=NULL; + unsigned long Time=(unsigned long)time(NULL); + void (*cb)(const SSL *ssl,int type,int val)=NULL; + int ret= -1; + int new_state,state,skip=0;; + + RAND_add(&Time,sizeof(Time),0); + ERR_clear_error(); + clear_sys_error(); + + if (s->info_callback != NULL) + cb=s->info_callback; + else if (s->ctx->info_callback != NULL) + cb=s->ctx->info_callback; + + s->in_handshake++; + if (!SSL_in_init(s) || SSL_in_before(s)) SSL_clear(s); + + for (;;) + { + state=s->state; + + switch(s->state) + { + case SSL_ST_RENEGOTIATE: + s->new_session=1; + s->state=SSL_ST_CONNECT; + s->ctx->stats.sess_connect_renegotiate++; + /* break */ + case SSL_ST_BEFORE: + case SSL_ST_CONNECT: + case SSL_ST_BEFORE|SSL_ST_CONNECT: + case SSL_ST_OK|SSL_ST_CONNECT: + + s->server=0; + if (cb != NULL) cb(s,SSL_CB_HANDSHAKE_START,1); + + if ((s->version & 0xff00 ) != (DTLS1_VERSION & 0xff00) && + (s->version & 0xff00 ) != (DTLS1_BAD_VER & 0xff00)) + { + SSLerr(SSL_F_DTLS1_CONNECT, ERR_R_INTERNAL_ERROR); + ret = -1; + goto end; + } + + /* s->version=SSL3_VERSION; */ + s->type=SSL_ST_CONNECT; + + if (s->init_buf == NULL) + { + if ((buf=BUF_MEM_new()) == NULL) + { + ret= -1; + goto end; + } + if (!BUF_MEM_grow(buf,SSL3_RT_MAX_PLAIN_LENGTH)) + { + ret= -1; + goto end; + } + s->init_buf=buf; + buf=NULL; + } + + if (!ssl3_setup_buffers(s)) { ret= -1; goto end; } + + /* setup buffing BIO */ + if (!ssl_init_wbio_buffer(s,0)) { ret= -1; goto end; } + + /* don't push the buffering BIO quite yet */ + + s->state=SSL3_ST_CW_CLNT_HELLO_A; + s->ctx->stats.sess_connect++; + s->init_num=0; + /* mark client_random uninitialized */ + memset(s->s3->client_random,0,sizeof(s->s3->client_random)); + s->d1->send_cookie = 0; + s->hit = 0; + break; + + case SSL3_ST_CW_CLNT_HELLO_A: + case SSL3_ST_CW_CLNT_HELLO_B: + + s->shutdown=0; + + /* every DTLS ClientHello resets Finished MAC */ + ssl3_init_finished_mac(s); + + dtls1_start_timer(s); + ret=dtls1_client_hello(s); + if (ret <= 0) goto end; + + if ( s->d1->send_cookie) + { + s->state=SSL3_ST_CW_FLUSH; + s->s3->tmp.next_state=SSL3_ST_CR_SRVR_HELLO_A; + } + else + s->state=SSL3_ST_CR_SRVR_HELLO_A; + + s->init_num=0; + + /* turn on buffering for the next lot of output */ + if (s->bbio != s->wbio) + s->wbio=BIO_push(s->bbio,s->wbio); + + break; + + case SSL3_ST_CR_SRVR_HELLO_A: + case SSL3_ST_CR_SRVR_HELLO_B: + ret=ssl3_get_server_hello(s); + if (ret <= 0) goto end; + else + { + dtls1_stop_timer(s); + if (s->hit) + s->state=SSL3_ST_CR_FINISHED_A; + else + s->state=DTLS1_ST_CR_HELLO_VERIFY_REQUEST_A; + } + s->init_num=0; + break; + + case DTLS1_ST_CR_HELLO_VERIFY_REQUEST_A: + case DTLS1_ST_CR_HELLO_VERIFY_REQUEST_B: + + ret = dtls1_get_hello_verify(s); + if ( ret <= 0) + goto end; + dtls1_stop_timer(s); + if ( s->d1->send_cookie) /* start again, with a cookie */ + s->state=SSL3_ST_CW_CLNT_HELLO_A; + else + s->state = SSL3_ST_CR_CERT_A; + s->init_num = 0; + break; + + case SSL3_ST_CR_CERT_A: + case SSL3_ST_CR_CERT_B: +#ifndef OPENSSL_NO_TLSEXT + ret=ssl3_check_finished(s); + if (ret <= 0) goto end; + if (ret == 2) + { + s->hit = 1; + if (s->tlsext_ticket_expected) + s->state=SSL3_ST_CR_SESSION_TICKET_A; + else + s->state=SSL3_ST_CR_FINISHED_A; + s->init_num=0; + break; + } +#endif + /* Check if it is anon DH or PSK */ + if (!(s->s3->tmp.new_cipher->algorithm_auth & SSL_aNULL) && + !(s->s3->tmp.new_cipher->algorithm_mkey & SSL_kPSK)) + { + ret=ssl3_get_server_certificate(s); + if (ret <= 0) goto end; +#ifndef OPENSSL_NO_TLSEXT + if (s->tlsext_status_expected) + s->state=SSL3_ST_CR_CERT_STATUS_A; + else + s->state=SSL3_ST_CR_KEY_EXCH_A; + } + else + { + skip = 1; + s->state=SSL3_ST_CR_KEY_EXCH_A; + } +#else + } + else + skip=1; + + s->state=SSL3_ST_CR_KEY_EXCH_A; +#endif + s->init_num=0; + break; + + case SSL3_ST_CR_KEY_EXCH_A: + case SSL3_ST_CR_KEY_EXCH_B: + ret=ssl3_get_key_exchange(s); + if (ret <= 0) goto end; + s->state=SSL3_ST_CR_CERT_REQ_A; + s->init_num=0; + + /* at this point we check that we have the + * required stuff from the server */ + if (!ssl3_check_cert_and_algorithm(s)) + { + ret= -1; + goto end; + } + break; + + case SSL3_ST_CR_CERT_REQ_A: + case SSL3_ST_CR_CERT_REQ_B: + ret=ssl3_get_certificate_request(s); + if (ret <= 0) goto end; + s->state=SSL3_ST_CR_SRVR_DONE_A; + s->init_num=0; + break; + + case SSL3_ST_CR_SRVR_DONE_A: + case SSL3_ST_CR_SRVR_DONE_B: + ret=ssl3_get_server_done(s); + if (ret <= 0) goto end; + if (s->s3->tmp.cert_req) + s->state=SSL3_ST_CW_CERT_A; + else + s->state=SSL3_ST_CW_KEY_EXCH_A; + s->init_num=0; + + break; + + case SSL3_ST_CW_CERT_A: + case SSL3_ST_CW_CERT_B: + case SSL3_ST_CW_CERT_C: + case SSL3_ST_CW_CERT_D: + dtls1_start_timer(s); + ret=dtls1_send_client_certificate(s); + if (ret <= 0) goto end; + s->state=SSL3_ST_CW_KEY_EXCH_A; + s->init_num=0; + break; + + case SSL3_ST_CW_KEY_EXCH_A: + case SSL3_ST_CW_KEY_EXCH_B: + dtls1_start_timer(s); + ret=dtls1_send_client_key_exchange(s); + if (ret <= 0) goto end; + /* EAY EAY EAY need to check for DH fix cert + * sent back */ + /* For TLS, cert_req is set to 2, so a cert chain + * of nothing is sent, but no verify packet is sent */ + if (s->s3->tmp.cert_req == 1) + { + s->state=SSL3_ST_CW_CERT_VRFY_A; + } + else + { + s->state=SSL3_ST_CW_CHANGE_A; + s->s3->change_cipher_spec=0; + } + + s->init_num=0; + break; + + case SSL3_ST_CW_CERT_VRFY_A: + case SSL3_ST_CW_CERT_VRFY_B: + dtls1_start_timer(s); + ret=dtls1_send_client_verify(s); + if (ret <= 0) goto end; + s->state=SSL3_ST_CW_CHANGE_A; + s->init_num=0; + s->s3->change_cipher_spec=0; + break; + + case SSL3_ST_CW_CHANGE_A: + case SSL3_ST_CW_CHANGE_B: + if (!s->hit) + dtls1_start_timer(s); + ret=dtls1_send_change_cipher_spec(s, + SSL3_ST_CW_CHANGE_A,SSL3_ST_CW_CHANGE_B); + if (ret <= 0) goto end; + s->state=SSL3_ST_CW_FINISHED_A; + s->init_num=0; + + s->session->cipher=s->s3->tmp.new_cipher; +#ifdef OPENSSL_NO_COMP + s->session->compress_meth=0; +#else + if (s->s3->tmp.new_compression == NULL) + s->session->compress_meth=0; + else + s->session->compress_meth= + s->s3->tmp.new_compression->id; +#endif + if (!s->method->ssl3_enc->setup_key_block(s)) + { + ret= -1; + goto end; + } + + if (!s->method->ssl3_enc->change_cipher_state(s, + SSL3_CHANGE_CIPHER_CLIENT_WRITE)) + { + ret= -1; + goto end; + } + + dtls1_reset_seq_numbers(s, SSL3_CC_WRITE); + break; + + case SSL3_ST_CW_FINISHED_A: + case SSL3_ST_CW_FINISHED_B: + if (!s->hit) + dtls1_start_timer(s); + ret=dtls1_send_finished(s, + SSL3_ST_CW_FINISHED_A,SSL3_ST_CW_FINISHED_B, + s->method->ssl3_enc->client_finished_label, + s->method->ssl3_enc->client_finished_label_len); + if (ret <= 0) goto end; + s->state=SSL3_ST_CW_FLUSH; + + /* clear flags */ + s->s3->flags&= ~SSL3_FLAGS_POP_BUFFER; + if (s->hit) + { + s->s3->tmp.next_state=SSL_ST_OK; + if (s->s3->flags & SSL3_FLAGS_DELAY_CLIENT_FINISHED) + { + s->state=SSL_ST_OK; + s->s3->flags|=SSL3_FLAGS_POP_BUFFER; + s->s3->delay_buf_pop_ret=0; + } + } + else + { +#ifndef OPENSSL_NO_TLSEXT + /* Allow NewSessionTicket if ticket expected */ + if (s->tlsext_ticket_expected) + s->s3->tmp.next_state=SSL3_ST_CR_SESSION_TICKET_A; + else +#endif + + s->s3->tmp.next_state=SSL3_ST_CR_FINISHED_A; + } + s->init_num=0; + break; + +#ifndef OPENSSL_NO_TLSEXT + case SSL3_ST_CR_SESSION_TICKET_A: + case SSL3_ST_CR_SESSION_TICKET_B: + ret=ssl3_get_new_session_ticket(s); + if (ret <= 0) goto end; + s->state=SSL3_ST_CR_FINISHED_A; + s->init_num=0; + break; + + case SSL3_ST_CR_CERT_STATUS_A: + case SSL3_ST_CR_CERT_STATUS_B: + ret=ssl3_get_cert_status(s); + if (ret <= 0) goto end; + s->state=SSL3_ST_CR_KEY_EXCH_A; + s->init_num=0; + break; +#endif + + case SSL3_ST_CR_FINISHED_A: + case SSL3_ST_CR_FINISHED_B: + s->d1->change_cipher_spec_ok = 1; + ret=ssl3_get_finished(s,SSL3_ST_CR_FINISHED_A, + SSL3_ST_CR_FINISHED_B); + if (ret <= 0) goto end; + dtls1_stop_timer(s); + + if (s->hit) + s->state=SSL3_ST_CW_CHANGE_A; + else + s->state=SSL_ST_OK; + s->init_num=0; + break; + + case SSL3_ST_CW_FLUSH: + s->rwstate=SSL_WRITING; + if (BIO_flush(s->wbio) <= 0) + { + ret= -1; + goto end; + } + s->rwstate=SSL_NOTHING; + s->state=s->s3->tmp.next_state; + break; + + case SSL_ST_OK: + /* clean a few things up */ + ssl3_cleanup_key_block(s); + +#if 0 + if (s->init_buf != NULL) + { + BUF_MEM_free(s->init_buf); + s->init_buf=NULL; + } +#endif + + /* If we are not 'joining' the last two packets, + * remove the buffering now */ + if (!(s->s3->flags & SSL3_FLAGS_POP_BUFFER)) + ssl_free_wbio_buffer(s); + /* else do it later in ssl3_write */ + + s->init_num=0; + s->new_session=0; + + ssl_update_cache(s,SSL_SESS_CACHE_CLIENT); + if (s->hit) s->ctx->stats.sess_hit++; + + ret=1; + /* s->server=0; */ + s->handshake_func=dtls1_connect; + s->ctx->stats.sess_connect_good++; + + if (cb != NULL) cb(s,SSL_CB_HANDSHAKE_DONE,1); + + /* done with handshaking */ + s->d1->handshake_read_seq = 0; + s->d1->next_handshake_write_seq = 0; + goto end; + /* break; */ + + default: + SSLerr(SSL_F_DTLS1_CONNECT,SSL_R_UNKNOWN_STATE); + ret= -1; + goto end; + /* break; */ + } + + /* did we do anything */ + if (!s->s3->tmp.reuse_message && !skip) + { + if (s->debug) + { + if ((ret=BIO_flush(s->wbio)) <= 0) + goto end; + } + + if ((cb != NULL) && (s->state != state)) + { + new_state=s->state; + s->state=state; + cb(s,SSL_CB_CONNECT_LOOP,1); + s->state=new_state; + } + } + skip=0; + } +end: + s->in_handshake--; + if (buf != NULL) + BUF_MEM_free(buf); + if (cb != NULL) + cb(s,SSL_CB_CONNECT_EXIT,ret); + return(ret); + } + +int dtls1_client_hello(SSL *s) + { + unsigned char *buf; + unsigned char *p,*d; + unsigned int i,j; + unsigned long Time,l; + SSL_COMP *comp; + + buf=(unsigned char *)s->init_buf->data; + if (s->state == SSL3_ST_CW_CLNT_HELLO_A) + { + SSL_SESSION *sess = s->session; + if ((s->session == NULL) || + (s->session->ssl_version != s->version) || +#ifdef OPENSSL_NO_TLSEXT + !sess->session_id_length || +#else + (!sess->session_id_length && !sess->tlsext_tick) || +#endif + (s->session->not_resumable)) + { + if (!s->session_creation_enabled) + { + ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_HANDSHAKE_FAILURE); + SSLerr(SSL_F_DTLS1_CLIENT_HELLO,SSL_R_SESSION_MAY_NOT_BE_CREATED); + goto err; + } + if (!ssl_get_new_session(s,0)) + goto err; + } + /* else use the pre-loaded session */ + + p=s->s3->client_random; + + /* if client_random is initialized, reuse it, we are + * required to use same upon reply to HelloVerify */ + for (i=0;p[i]=='\0' && is3->client_random);i++) ; + if (i==sizeof(s->s3->client_random)) + { + Time=(unsigned long)time(NULL); /* Time */ + l2n(Time,p); + RAND_pseudo_bytes(p,sizeof(s->s3->client_random)-4); + } + + /* Do the message type and length last */ + d=p= &(buf[DTLS1_HM_HEADER_LENGTH]); + + *(p++)=s->version>>8; + *(p++)=s->version&0xff; + s->client_version=s->version; + + /* Random stuff */ + memcpy(p,s->s3->client_random,SSL3_RANDOM_SIZE); + p+=SSL3_RANDOM_SIZE; + + /* Session ID */ + if (s->new_session) + i=0; + else + i=s->session->session_id_length; + *(p++)=i; + if (i != 0) + { + if (i > sizeof s->session->session_id) + { + SSLerr(SSL_F_DTLS1_CLIENT_HELLO, ERR_R_INTERNAL_ERROR); + goto err; + } + memcpy(p,s->session->session_id,i); + p+=i; + } + + /* cookie stuff */ + if ( s->d1->cookie_len > sizeof(s->d1->cookie)) + { + SSLerr(SSL_F_DTLS1_CLIENT_HELLO, ERR_R_INTERNAL_ERROR); + goto err; + } + *(p++) = s->d1->cookie_len; + memcpy(p, s->d1->cookie, s->d1->cookie_len); + p += s->d1->cookie_len; + + /* Ciphers supported */ + i=ssl_cipher_list_to_bytes(s,SSL_get_ciphers(s),&(p[2]),0); + if (i == 0) + { + SSLerr(SSL_F_DTLS1_CLIENT_HELLO,SSL_R_NO_CIPHERS_AVAILABLE); + goto err; + } + s2n(i,p); + p+=i; + + /* COMPRESSION */ + if (s->ctx->comp_methods == NULL) + j=0; + else + j=sk_SSL_COMP_num(s->ctx->comp_methods); + *(p++)=1+j; + for (i=0; ictx->comp_methods,i); + *(p++)=comp->id; + } + *(p++)=0; /* Add the NULL method */ + +#ifndef OPENSSL_NO_TLSEXT + if ((p = ssl_add_clienthello_tlsext(s, p, buf+SSL3_RT_MAX_PLAIN_LENGTH)) == NULL) + { + SSLerr(SSL_F_DTLS1_CLIENT_HELLO,ERR_R_INTERNAL_ERROR); + goto err; + } +#endif + + l=(p-d); + d=buf; + + d = dtls1_set_message_header(s, d, SSL3_MT_CLIENT_HELLO, l, 0, l); + + s->state=SSL3_ST_CW_CLNT_HELLO_B; + /* number of bytes to write */ + s->init_num=p-buf; + s->init_off=0; + + /* buffer the message to handle re-xmits */ + dtls1_buffer_message(s, 0); + } + + /* SSL3_ST_CW_CLNT_HELLO_B */ + return(dtls1_do_write(s,SSL3_RT_HANDSHAKE)); +err: + return(-1); + } + +static int dtls1_get_hello_verify(SSL *s) + { + int n, al, ok = 0; + unsigned char *data; + unsigned int cookie_len; + + n=s->method->ssl_get_message(s, + DTLS1_ST_CR_HELLO_VERIFY_REQUEST_A, + DTLS1_ST_CR_HELLO_VERIFY_REQUEST_B, + -1, + s->max_cert_list, + &ok); + + if (!ok) return((int)n); + + if (s->s3->tmp.message_type != DTLS1_MT_HELLO_VERIFY_REQUEST) + { + s->d1->send_cookie = 0; + s->s3->tmp.reuse_message=1; + return(1); + } + + data = (unsigned char *)s->init_msg; + + if ((data[0] != (s->version>>8)) || (data[1] != (s->version&0xff))) + { + SSLerr(SSL_F_DTLS1_GET_HELLO_VERIFY,SSL_R_WRONG_SSL_VERSION); + s->version=(s->version&0xff00)|data[1]; + al = SSL_AD_PROTOCOL_VERSION; + goto f_err; + } + data+=2; + + cookie_len = *(data++); + if ( cookie_len > sizeof(s->d1->cookie)) + { + al=SSL_AD_ILLEGAL_PARAMETER; + goto f_err; + } + + memcpy(s->d1->cookie, data, cookie_len); + s->d1->cookie_len = cookie_len; + + s->d1->send_cookie = 1; + return 1; + +f_err: + ssl3_send_alert(s, SSL3_AL_FATAL, al); + return -1; + } + +int dtls1_send_client_key_exchange(SSL *s) + { + unsigned char *p,*d; + int n; + unsigned long alg_k; +#ifndef OPENSSL_NO_RSA + unsigned char *q; + EVP_PKEY *pkey=NULL; +#endif +#ifndef OPENSSL_NO_KRB5 + KSSL_ERR kssl_err; +#endif /* OPENSSL_NO_KRB5 */ +#ifndef OPENSSL_NO_ECDH + EC_KEY *clnt_ecdh = NULL; + const EC_POINT *srvr_ecpoint = NULL; + EVP_PKEY *srvr_pub_pkey = NULL; + unsigned char *encodedPoint = NULL; + int encoded_pt_len = 0; + BN_CTX * bn_ctx = NULL; +#endif + + if (s->state == SSL3_ST_CW_KEY_EXCH_A) + { + d=(unsigned char *)s->init_buf->data; + p= &(d[DTLS1_HM_HEADER_LENGTH]); + + alg_k=s->s3->tmp.new_cipher->algorithm_mkey; + + /* Fool emacs indentation */ + if (0) {} +#ifndef OPENSSL_NO_RSA + else if (alg_k & SSL_kRSA) + { + RSA *rsa; + unsigned char tmp_buf[SSL_MAX_MASTER_KEY_LENGTH]; + + if (s->session->sess_cert->peer_rsa_tmp != NULL) + rsa=s->session->sess_cert->peer_rsa_tmp; + else + { + pkey=X509_get_pubkey(s->session->sess_cert->peer_pkeys[SSL_PKEY_RSA_ENC].x509); + if ((pkey == NULL) || + (pkey->type != EVP_PKEY_RSA) || + (pkey->pkey.rsa == NULL)) + { + SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE,ERR_R_INTERNAL_ERROR); + goto err; + } + rsa=pkey->pkey.rsa; + EVP_PKEY_free(pkey); + } + + tmp_buf[0]=s->client_version>>8; + tmp_buf[1]=s->client_version&0xff; + if (RAND_bytes(&(tmp_buf[2]),sizeof tmp_buf-2) <= 0) + goto err; + + s->session->master_key_length=sizeof tmp_buf; + + q=p; + /* Fix buf for TLS and [incidentally] DTLS */ + if (s->version > SSL3_VERSION) + p+=2; + n=RSA_public_encrypt(sizeof tmp_buf, + tmp_buf,p,rsa,RSA_PKCS1_PADDING); +#ifdef PKCS1_CHECK + if (s->options & SSL_OP_PKCS1_CHECK_1) p[1]++; + if (s->options & SSL_OP_PKCS1_CHECK_2) tmp_buf[0]=0x70; +#endif + if (n <= 0) + { + SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE,SSL_R_BAD_RSA_ENCRYPT); + goto err; + } + + /* Fix buf for TLS and [incidentally] DTLS */ + if (s->version > SSL3_VERSION) + { + s2n(n,q); + n+=2; + } + + s->session->master_key_length= + s->method->ssl3_enc->generate_master_secret(s, + s->session->master_key, + tmp_buf,sizeof tmp_buf); + OPENSSL_cleanse(tmp_buf,sizeof tmp_buf); + } +#endif +#ifndef OPENSSL_NO_KRB5 + else if (alg_k & SSL_kKRB5) + { + krb5_error_code krb5rc; + KSSL_CTX *kssl_ctx = s->kssl_ctx; + /* krb5_data krb5_ap_req; */ + krb5_data *enc_ticket; + krb5_data authenticator, *authp = NULL; + EVP_CIPHER_CTX ciph_ctx; + const EVP_CIPHER *enc = NULL; + unsigned char iv[EVP_MAX_IV_LENGTH]; + unsigned char tmp_buf[SSL_MAX_MASTER_KEY_LENGTH]; + unsigned char epms[SSL_MAX_MASTER_KEY_LENGTH + + EVP_MAX_IV_LENGTH]; + int padl, outl = sizeof(epms); + + EVP_CIPHER_CTX_init(&ciph_ctx); + +#ifdef KSSL_DEBUG + printf("ssl3_send_client_key_exchange(%lx & %lx)\n", + alg_k, SSL_kKRB5); +#endif /* KSSL_DEBUG */ + + authp = NULL; +#ifdef KRB5SENDAUTH + if (KRB5SENDAUTH) authp = &authenticator; +#endif /* KRB5SENDAUTH */ + + krb5rc = kssl_cget_tkt(kssl_ctx, &enc_ticket, authp, + &kssl_err); + enc = kssl_map_enc(kssl_ctx->enctype); + if (enc == NULL) + goto err; +#ifdef KSSL_DEBUG + { + printf("kssl_cget_tkt rtn %d\n", krb5rc); + if (krb5rc && kssl_err.text) + printf("kssl_cget_tkt kssl_err=%s\n", kssl_err.text); + } +#endif /* KSSL_DEBUG */ + + if (krb5rc) + { + ssl3_send_alert(s,SSL3_AL_FATAL, + SSL_AD_HANDSHAKE_FAILURE); + SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE, + kssl_err.reason); + goto err; + } + + /* 20010406 VRS - Earlier versions used KRB5 AP_REQ + ** in place of RFC 2712 KerberosWrapper, as in: + ** + ** Send ticket (copy to *p, set n = length) + ** n = krb5_ap_req.length; + ** memcpy(p, krb5_ap_req.data, krb5_ap_req.length); + ** if (krb5_ap_req.data) + ** kssl_krb5_free_data_contents(NULL,&krb5_ap_req); + ** + ** Now using real RFC 2712 KerberosWrapper + ** (Thanks to Simon Wilkinson ) + ** Note: 2712 "opaque" types are here replaced + ** with a 2-byte length followed by the value. + ** Example: + ** KerberosWrapper= xx xx asn1ticket 0 0 xx xx encpms + ** Where "xx xx" = length bytes. Shown here with + ** optional authenticator omitted. + */ + + /* KerberosWrapper.Ticket */ + s2n(enc_ticket->length,p); + memcpy(p, enc_ticket->data, enc_ticket->length); + p+= enc_ticket->length; + n = enc_ticket->length + 2; + + /* KerberosWrapper.Authenticator */ + if (authp && authp->length) + { + s2n(authp->length,p); + memcpy(p, authp->data, authp->length); + p+= authp->length; + n+= authp->length + 2; + + free(authp->data); + authp->data = NULL; + authp->length = 0; + } + else + { + s2n(0,p);/* null authenticator length */ + n+=2; + } + + if (RAND_bytes(tmp_buf,sizeof tmp_buf) <= 0) + goto err; + + /* 20010420 VRS. Tried it this way; failed. + ** EVP_EncryptInit_ex(&ciph_ctx,enc, NULL,NULL); + ** EVP_CIPHER_CTX_set_key_length(&ciph_ctx, + ** kssl_ctx->length); + ** EVP_EncryptInit_ex(&ciph_ctx,NULL, key,iv); + */ + + memset(iv, 0, sizeof iv); /* per RFC 1510 */ + EVP_EncryptInit_ex(&ciph_ctx,enc, NULL, + kssl_ctx->key,iv); + EVP_EncryptUpdate(&ciph_ctx,epms,&outl,tmp_buf, + sizeof tmp_buf); + EVP_EncryptFinal_ex(&ciph_ctx,&(epms[outl]),&padl); + outl += padl; + if (outl > (int)sizeof epms) + { + SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR); + goto err; + } + EVP_CIPHER_CTX_cleanup(&ciph_ctx); + + /* KerberosWrapper.EncryptedPreMasterSecret */ + s2n(outl,p); + memcpy(p, epms, outl); + p+=outl; + n+=outl + 2; + + s->session->master_key_length= + s->method->ssl3_enc->generate_master_secret(s, + s->session->master_key, + tmp_buf, sizeof tmp_buf); + + OPENSSL_cleanse(tmp_buf, sizeof tmp_buf); + OPENSSL_cleanse(epms, outl); + } +#endif +#ifndef OPENSSL_NO_DH + else if (alg_k & (SSL_kEDH|SSL_kDHr|SSL_kDHd)) + { + DH *dh_srvr,*dh_clnt; + + if (s->session->sess_cert->peer_dh_tmp != NULL) + dh_srvr=s->session->sess_cert->peer_dh_tmp; + else + { + /* we get them from the cert */ + ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_HANDSHAKE_FAILURE); + SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE,SSL_R_UNABLE_TO_FIND_DH_PARAMETERS); + goto err; + } + + /* generate a new random key */ + if ((dh_clnt=DHparams_dup(dh_srvr)) == NULL) + { + SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE,ERR_R_DH_LIB); + goto err; + } + if (!DH_generate_key(dh_clnt)) + { + SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE,ERR_R_DH_LIB); + goto err; + } + + /* use the 'p' output buffer for the DH key, but + * make sure to clear it out afterwards */ + + n=DH_compute_key(p,dh_srvr->pub_key,dh_clnt); + + if (n <= 0) + { + SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE,ERR_R_DH_LIB); + goto err; + } + + /* generate master key from the result */ + s->session->master_key_length= + s->method->ssl3_enc->generate_master_secret(s, + s->session->master_key,p,n); + /* clean up */ + memset(p,0,n); + + /* send off the data */ + n=BN_num_bytes(dh_clnt->pub_key); + s2n(n,p); + BN_bn2bin(dh_clnt->pub_key,p); + n+=2; + + DH_free(dh_clnt); + + /* perhaps clean things up a bit EAY EAY EAY EAY*/ + } +#endif +#ifndef OPENSSL_NO_ECDH + else if (alg_k & (SSL_kEECDH|SSL_kECDHr|SSL_kECDHe)) + { + const EC_GROUP *srvr_group = NULL; + EC_KEY *tkey; + int ecdh_clnt_cert = 0; + int field_size = 0; + + /* Did we send out the client's + * ECDH share for use in premaster + * computation as part of client certificate? + * If so, set ecdh_clnt_cert to 1. + */ + if ((alg_k & (SSL_kECDHr|SSL_kECDHe)) && (s->cert != NULL)) + { + /* XXX: For now, we do not support client + * authentication using ECDH certificates. + * To add such support, one needs to add + * code that checks for appropriate + * conditions and sets ecdh_clnt_cert to 1. + * For example, the cert have an ECC + * key on the same curve as the server's + * and the key should be authorized for + * key agreement. + * + * One also needs to add code in ssl3_connect + * to skip sending the certificate verify + * message. + * + * if ((s->cert->key->privatekey != NULL) && + * (s->cert->key->privatekey->type == + * EVP_PKEY_EC) && ...) + * ecdh_clnt_cert = 1; + */ + } + + if (s->session->sess_cert->peer_ecdh_tmp != NULL) + { + tkey = s->session->sess_cert->peer_ecdh_tmp; + } + else + { + /* Get the Server Public Key from Cert */ + srvr_pub_pkey = X509_get_pubkey(s->session-> \ + sess_cert->peer_pkeys[SSL_PKEY_ECC].x509); + if ((srvr_pub_pkey == NULL) || + (srvr_pub_pkey->type != EVP_PKEY_EC) || + (srvr_pub_pkey->pkey.ec == NULL)) + { + SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE, + ERR_R_INTERNAL_ERROR); + goto err; + } + + tkey = srvr_pub_pkey->pkey.ec; + } + + srvr_group = EC_KEY_get0_group(tkey); + srvr_ecpoint = EC_KEY_get0_public_key(tkey); + + if ((srvr_group == NULL) || (srvr_ecpoint == NULL)) + { + SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE, + ERR_R_INTERNAL_ERROR); + goto err; + } + + if ((clnt_ecdh=EC_KEY_new()) == NULL) + { + SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE,ERR_R_MALLOC_FAILURE); + goto err; + } + + if (!EC_KEY_set_group(clnt_ecdh, srvr_group)) + { + SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE,ERR_R_EC_LIB); + goto err; + } + if (ecdh_clnt_cert) + { + /* Reuse key info from our certificate + * We only need our private key to perform + * the ECDH computation. + */ + const BIGNUM *priv_key; + tkey = s->cert->key->privatekey->pkey.ec; + priv_key = EC_KEY_get0_private_key(tkey); + if (priv_key == NULL) + { + SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE,ERR_R_MALLOC_FAILURE); + goto err; + } + if (!EC_KEY_set_private_key(clnt_ecdh, priv_key)) + { + SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE,ERR_R_EC_LIB); + goto err; + } + } + else + { + /* Generate a new ECDH key pair */ + if (!(EC_KEY_generate_key(clnt_ecdh))) + { + SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE, ERR_R_ECDH_LIB); + goto err; + } + } + + /* use the 'p' output buffer for the ECDH key, but + * make sure to clear it out afterwards + */ + + field_size = EC_GROUP_get_degree(srvr_group); + if (field_size <= 0) + { + SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE, + ERR_R_ECDH_LIB); + goto err; + } + n=ECDH_compute_key(p, (field_size+7)/8, srvr_ecpoint, clnt_ecdh, NULL); + if (n <= 0) + { + SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE, + ERR_R_ECDH_LIB); + goto err; + } + + /* generate master key from the result */ + s->session->master_key_length = s->method->ssl3_enc \ + -> generate_master_secret(s, + s->session->master_key, + p, n); + + memset(p, 0, n); /* clean up */ + + if (ecdh_clnt_cert) + { + /* Send empty client key exch message */ + n = 0; + } + else + { + /* First check the size of encoding and + * allocate memory accordingly. + */ + encoded_pt_len = + EC_POINT_point2oct(srvr_group, + EC_KEY_get0_public_key(clnt_ecdh), + POINT_CONVERSION_UNCOMPRESSED, + NULL, 0, NULL); + + encodedPoint = (unsigned char *) + OPENSSL_malloc(encoded_pt_len * + sizeof(unsigned char)); + bn_ctx = BN_CTX_new(); + if ((encodedPoint == NULL) || + (bn_ctx == NULL)) + { + SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE,ERR_R_MALLOC_FAILURE); + goto err; + } + + /* Encode the public key */ + n = EC_POINT_point2oct(srvr_group, + EC_KEY_get0_public_key(clnt_ecdh), + POINT_CONVERSION_UNCOMPRESSED, + encodedPoint, encoded_pt_len, bn_ctx); + + *p = n; /* length of encoded point */ + /* Encoded point will be copied here */ + p += 1; + /* copy the point */ + memcpy((unsigned char *)p, encodedPoint, n); + /* increment n to account for length field */ + n += 1; + } + + /* Free allocated memory */ + BN_CTX_free(bn_ctx); + if (encodedPoint != NULL) OPENSSL_free(encodedPoint); + if (clnt_ecdh != NULL) + EC_KEY_free(clnt_ecdh); + EVP_PKEY_free(srvr_pub_pkey); + } +#endif /* !OPENSSL_NO_ECDH */ + +#ifndef OPENSSL_NO_PSK + else if (alg_k & SSL_kPSK) + { + char identity[PSK_MAX_IDENTITY_LEN]; + unsigned char *t = NULL; + unsigned char psk_or_pre_ms[PSK_MAX_PSK_LEN*2+4]; + unsigned int pre_ms_len = 0, psk_len = 0; + int psk_err = 1; + + n = 0; + if (s->psk_client_callback == NULL) + { + SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE, + SSL_R_PSK_NO_CLIENT_CB); + goto err; + } + + psk_len = s->psk_client_callback(s, s->ctx->psk_identity_hint, + identity, PSK_MAX_IDENTITY_LEN, + psk_or_pre_ms, sizeof(psk_or_pre_ms)); + if (psk_len > PSK_MAX_PSK_LEN) + { + SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE, + ERR_R_INTERNAL_ERROR); + goto psk_err; + } + else if (psk_len == 0) + { + SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE, + SSL_R_PSK_IDENTITY_NOT_FOUND); + goto psk_err; + } + + /* create PSK pre_master_secret */ + pre_ms_len = 2+psk_len+2+psk_len; + t = psk_or_pre_ms; + memmove(psk_or_pre_ms+psk_len+4, psk_or_pre_ms, psk_len); + s2n(psk_len, t); + memset(t, 0, psk_len); + t+=psk_len; + s2n(psk_len, t); + + if (s->session->psk_identity_hint != NULL) + OPENSSL_free(s->session->psk_identity_hint); + s->session->psk_identity_hint = BUF_strdup(s->ctx->psk_identity_hint); + if (s->ctx->psk_identity_hint != NULL && + s->session->psk_identity_hint == NULL) + { + SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE, + ERR_R_MALLOC_FAILURE); + goto psk_err; + } + + if (s->session->psk_identity != NULL) + OPENSSL_free(s->session->psk_identity); + s->session->psk_identity = BUF_strdup(identity); + if (s->session->psk_identity == NULL) + { + SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE, + ERR_R_MALLOC_FAILURE); + goto psk_err; + } + + s->session->master_key_length = + s->method->ssl3_enc->generate_master_secret(s, + s->session->master_key, + psk_or_pre_ms, pre_ms_len); + n = strlen(identity); + s2n(n, p); + memcpy(p, identity, n); + n+=2; + psk_err = 0; + psk_err: + OPENSSL_cleanse(identity, PSK_MAX_IDENTITY_LEN); + OPENSSL_cleanse(psk_or_pre_ms, sizeof(psk_or_pre_ms)); + if (psk_err != 0) + { + ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE); + goto err; + } + } +#endif + else + { + ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_HANDSHAKE_FAILURE); + SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE,ERR_R_INTERNAL_ERROR); + goto err; + } + + d = dtls1_set_message_header(s, d, + SSL3_MT_CLIENT_KEY_EXCHANGE, n, 0, n); + /* + *(d++)=SSL3_MT_CLIENT_KEY_EXCHANGE; + l2n3(n,d); + l2n(s->d1->handshake_write_seq,d); + s->d1->handshake_write_seq++; + */ + + s->state=SSL3_ST_CW_KEY_EXCH_B; + /* number of bytes to write */ + s->init_num=n+DTLS1_HM_HEADER_LENGTH; + s->init_off=0; + + /* buffer the message to handle re-xmits */ + dtls1_buffer_message(s, 0); + } + + /* SSL3_ST_CW_KEY_EXCH_B */ + return(dtls1_do_write(s,SSL3_RT_HANDSHAKE)); +err: +#ifndef OPENSSL_NO_ECDH + BN_CTX_free(bn_ctx); + if (encodedPoint != NULL) OPENSSL_free(encodedPoint); + if (clnt_ecdh != NULL) + EC_KEY_free(clnt_ecdh); + EVP_PKEY_free(srvr_pub_pkey); +#endif + return(-1); + } + +int dtls1_send_client_verify(SSL *s) + { + unsigned char *p,*d; + unsigned char data[MD5_DIGEST_LENGTH+SHA_DIGEST_LENGTH]; + EVP_PKEY *pkey; +#ifndef OPENSSL_NO_RSA + unsigned u=0; +#endif + unsigned long n; +#if !defined(OPENSSL_NO_DSA) || !defined(OPENSSL_NO_ECDSA) + int j; +#endif + + if (s->state == SSL3_ST_CW_CERT_VRFY_A) + { + d=(unsigned char *)s->init_buf->data; + p= &(d[DTLS1_HM_HEADER_LENGTH]); + pkey=s->cert->key->privatekey; + + s->method->ssl3_enc->cert_verify_mac(s, + NID_sha1, + &(data[MD5_DIGEST_LENGTH])); + +#ifndef OPENSSL_NO_RSA + if (pkey->type == EVP_PKEY_RSA) + { + s->method->ssl3_enc->cert_verify_mac(s, + NID_md5, + &(data[0])); + if (RSA_sign(NID_md5_sha1, data, + MD5_DIGEST_LENGTH+SHA_DIGEST_LENGTH, + &(p[2]), &u, pkey->pkey.rsa) <= 0 ) + { + SSLerr(SSL_F_DTLS1_SEND_CLIENT_VERIFY,ERR_R_RSA_LIB); + goto err; + } + s2n(u,p); + n=u+2; + } + else +#endif +#ifndef OPENSSL_NO_DSA + if (pkey->type == EVP_PKEY_DSA) + { + if (!DSA_sign(pkey->save_type, + &(data[MD5_DIGEST_LENGTH]), + SHA_DIGEST_LENGTH,&(p[2]), + (unsigned int *)&j,pkey->pkey.dsa)) + { + SSLerr(SSL_F_DTLS1_SEND_CLIENT_VERIFY,ERR_R_DSA_LIB); + goto err; + } + s2n(j,p); + n=j+2; + } + else +#endif +#ifndef OPENSSL_NO_ECDSA + if (pkey->type == EVP_PKEY_EC) + { + if (!ECDSA_sign(pkey->save_type, + &(data[MD5_DIGEST_LENGTH]), + SHA_DIGEST_LENGTH,&(p[2]), + (unsigned int *)&j,pkey->pkey.ec)) + { + SSLerr(SSL_F_DTLS1_SEND_CLIENT_VERIFY, + ERR_R_ECDSA_LIB); + goto err; + } + s2n(j,p); + n=j+2; + } + else +#endif + { + SSLerr(SSL_F_DTLS1_SEND_CLIENT_VERIFY,ERR_R_INTERNAL_ERROR); + goto err; + } + + d = dtls1_set_message_header(s, d, + SSL3_MT_CERTIFICATE_VERIFY, n, 0, n) ; + + s->init_num=(int)n+DTLS1_HM_HEADER_LENGTH; + s->init_off=0; + + /* buffer the message to handle re-xmits */ + dtls1_buffer_message(s, 0); + + s->state = SSL3_ST_CW_CERT_VRFY_B; + } + + /* s->state = SSL3_ST_CW_CERT_VRFY_B */ + return(dtls1_do_write(s,SSL3_RT_HANDSHAKE)); +err: + return(-1); + } + +int dtls1_send_client_certificate(SSL *s) + { + X509 *x509=NULL; + EVP_PKEY *pkey=NULL; + int i; + unsigned long l; + + if (s->state == SSL3_ST_CW_CERT_A) + { + if ((s->cert == NULL) || + (s->cert->key->x509 == NULL) || + (s->cert->key->privatekey == NULL)) + s->state=SSL3_ST_CW_CERT_B; + else + s->state=SSL3_ST_CW_CERT_C; + } + + /* We need to get a client cert */ + if (s->state == SSL3_ST_CW_CERT_B) + { + /* If we get an error, we need to + * ssl->rwstate=SSL_X509_LOOKUP; return(-1); + * We then get retied later */ + i=0; + i = ssl_do_client_cert_cb(s, &x509, &pkey); + if (i < 0) + { + s->rwstate=SSL_X509_LOOKUP; + return(-1); + } + s->rwstate=SSL_NOTHING; + if ((i == 1) && (pkey != NULL) && (x509 != NULL)) + { + s->state=SSL3_ST_CW_CERT_B; + if ( !SSL_use_certificate(s,x509) || + !SSL_use_PrivateKey(s,pkey)) + i=0; + } + else if (i == 1) + { + i=0; + SSLerr(SSL_F_DTLS1_SEND_CLIENT_CERTIFICATE,SSL_R_BAD_DATA_RETURNED_BY_CALLBACK); + } + + if (x509 != NULL) X509_free(x509); + if (pkey != NULL) EVP_PKEY_free(pkey); + if (i == 0) + { + if (s->version == SSL3_VERSION) + { + s->s3->tmp.cert_req=0; + ssl3_send_alert(s,SSL3_AL_WARNING,SSL_AD_NO_CERTIFICATE); + return(1); + } + else + { + s->s3->tmp.cert_req=2; + } + } + + /* Ok, we have a cert */ + s->state=SSL3_ST_CW_CERT_C; + } + + if (s->state == SSL3_ST_CW_CERT_C) + { + s->state=SSL3_ST_CW_CERT_D; + l=dtls1_output_cert_chain(s, + (s->s3->tmp.cert_req == 2)?NULL:s->cert->key->x509); + s->init_num=(int)l; + s->init_off=0; + + /* set header called by dtls1_output_cert_chain() */ + + /* buffer the message to handle re-xmits */ + dtls1_buffer_message(s, 0); + } + /* SSL3_ST_CW_CERT_D */ + return(dtls1_do_write(s,SSL3_RT_HANDSHAKE)); + } + + diff --git a/node-v0.8.14/deps/openssl/openssl/ssl/d1_enc.c b/node-v0.8.14/deps/openssl/openssl/ssl/d1_enc.c new file mode 100644 index 0000000..becbab9 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/ssl/d1_enc.c @@ -0,0 +1,289 @@ +/* ssl/d1_enc.c */ +/* + * DTLS implementation written by Nagendra Modadugu + * (nagendra@cs.stanford.edu) for the OpenSSL project 2005. + */ +/* ==================================================================== + * Copyright (c) 1998-2005 The OpenSSL Project. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. All advertising materials mentioning features or use of this + * software must display the following acknowledgment: + * "This product includes software developed by the OpenSSL Project + * for use in the OpenSSL Toolkit. (http://www.openssl.org/)" + * + * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to + * endorse or promote products derived from this software without + * prior written permission. For written permission, please contact + * openssl-core@openssl.org. + * + * 5. Products derived from this software may not be called "OpenSSL" + * nor may "OpenSSL" appear in their names without prior written + * permission of the OpenSSL Project. + * + * 6. Redistributions of any form whatsoever must retain the following + * acknowledgment: + * "This product includes software developed by the OpenSSL Project + * for use in the OpenSSL Toolkit (http://www.openssl.org/)" + * + * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY + * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR + * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, + * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * ==================================================================== + * + * This product includes cryptographic software written by Eric Young + * (eay@cryptsoft.com). This product includes software written by Tim + * Hudson (tjh@cryptsoft.com). + * + */ +/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com) + * All rights reserved. + * + * This package is an SSL implementation written + * by Eric Young (eay@cryptsoft.com). + * The implementation was written so as to conform with Netscapes SSL. + * + * This library is free for commercial and non-commercial use as long as + * the following conditions are aheared to. The following conditions + * apply to all code found in this distribution, be it the RC4, RSA, + * lhash, DES, etc., code; not just the SSL code. The SSL documentation + * included with this distribution is covered by the same copyright terms + * except that the holder is Tim Hudson (tjh@cryptsoft.com). + * + * Copyright remains Eric Young's, and as such any Copyright notices in + * the code are not to be removed. + * If this package is used in a product, Eric Young should be given attribution + * as the author of the parts of the library used. + * This can be in the form of a textual message at program startup or + * in documentation (online or textual) provided with the package. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * "This product includes cryptographic software written by + * Eric Young (eay@cryptsoft.com)" + * The word 'cryptographic' can be left out if the rouines from the library + * being used are not cryptographic related :-). + * 4. If you include any Windows specific code (or a derivative thereof) from + * the apps directory (application code) you must include an acknowledgement: + * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)" + * + * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * + * The licence and distribution terms for any publically available version or + * derivative of this code cannot be changed. i.e. this code cannot simply be + * copied and put under another distribution licence + * [including the GNU Public Licence.] + */ + +#include +#include "ssl_locl.h" +#ifndef OPENSSL_NO_COMP +#include +#endif +#include +#include +#include +#include +#ifdef KSSL_DEBUG +#include +#endif + +int dtls1_enc(SSL *s, int send) + { + SSL3_RECORD *rec; + EVP_CIPHER_CTX *ds; + unsigned long l; + int bs,i,ii,j,k,n=0; + const EVP_CIPHER *enc; + + if (send) + { + if (EVP_MD_CTX_md(s->write_hash)) + { + n=EVP_MD_CTX_size(s->write_hash); + if (n < 0) + return -1; + } + ds=s->enc_write_ctx; + rec= &(s->s3->wrec); + if (s->enc_write_ctx == NULL) + enc=NULL; + else + { + enc=EVP_CIPHER_CTX_cipher(s->enc_write_ctx); + if ( rec->data != rec->input) + /* we can't write into the input stream */ + fprintf(stderr, "%s:%d: rec->data != rec->input\n", + __FILE__, __LINE__); + else if ( EVP_CIPHER_block_size(ds->cipher) > 1) + { + if (RAND_bytes(rec->input, EVP_CIPHER_block_size(ds->cipher)) <= 0) + return -1; + } + } + } + else + { + if (EVP_MD_CTX_md(s->read_hash)) + { + n=EVP_MD_CTX_size(s->read_hash); + if (n < 0) + return -1; + } + ds=s->enc_read_ctx; + rec= &(s->s3->rrec); + if (s->enc_read_ctx == NULL) + enc=NULL; + else + enc=EVP_CIPHER_CTX_cipher(s->enc_read_ctx); + } + +#ifdef KSSL_DEBUG + printf("dtls1_enc(%d)\n", send); +#endif /* KSSL_DEBUG */ + + if ((s->session == NULL) || (ds == NULL) || + (enc == NULL)) + { + memmove(rec->data,rec->input,rec->length); + rec->input=rec->data; + } + else + { + l=rec->length; + bs=EVP_CIPHER_block_size(ds->cipher); + + if ((bs != 1) && send) + { + i=bs-((int)l%bs); + + /* Add weird padding of upto 256 bytes */ + + /* we need to add 'i' padding bytes of value j */ + j=i-1; + if (s->options & SSL_OP_TLS_BLOCK_PADDING_BUG) + { + if (s->s3->flags & TLS1_FLAGS_TLS_PADDING_BUG) + j++; + } + for (k=(int)l; k<(int)(l+i); k++) + rec->input[k]=j; + l+=i; + rec->length+=i; + } + +#ifdef KSSL_DEBUG + { + unsigned long ui; + printf("EVP_Cipher(ds=%p,rec->data=%p,rec->input=%p,l=%ld) ==>\n", + ds,rec->data,rec->input,l); + printf("\tEVP_CIPHER_CTX: %d buf_len, %d key_len [%d %d], %d iv_len\n", + ds->buf_len, ds->cipher->key_len, + DES_KEY_SZ, DES_SCHEDULE_SZ, + ds->cipher->iv_len); + printf("\t\tIV: "); + for (i=0; icipher->iv_len; i++) printf("%02X", ds->iv[i]); + printf("\n"); + printf("\trec->input="); + for (ui=0; uiinput[ui]); + printf("\n"); + } +#endif /* KSSL_DEBUG */ + + if (!send) + { + if (l == 0 || l%bs != 0) + return -1; + } + + EVP_Cipher(ds,rec->data,rec->input,l); + +#ifdef KSSL_DEBUG + { + unsigned long i; + printf("\trec->data="); + for (i=0; idata[i]); printf("\n"); + } +#endif /* KSSL_DEBUG */ + + if ((bs != 1) && !send) + { + ii=i=rec->data[l-1]; /* padding_length */ + i++; + if (s->options&SSL_OP_TLS_BLOCK_PADDING_BUG) + { + /* First packet is even in size, so check */ + if ((memcmp(s->s3->read_sequence, + "\0\0\0\0\0\0\0\0",8) == 0) && !(ii & 1)) + s->s3->flags|=TLS1_FLAGS_TLS_PADDING_BUG; + if (s->s3->flags & TLS1_FLAGS_TLS_PADDING_BUG) + i--; + } + /* TLS 1.0 does not bound the number of padding bytes by the block size. + * All of them must have value 'padding_length'. */ + if (i > (int)rec->length) + { + /* Incorrect padding. SSLerr() and ssl3_alert are done + * by caller: we don't want to reveal whether this is + * a decryption error or a MAC verification failure + * (see http://www.openssl.org/~bodo/tls-cbc.txt) + */ + return -1; + } + for (j=(int)(l-i); j<(int)l; j++) + { + if (rec->data[j] != ii) + { + /* Incorrect padding */ + return -1; + } + } + rec->length-=i; + + rec->data += bs; /* skip the implicit IV */ + rec->input += bs; + rec->length -= bs; + } + } + return(1); + } + diff --git a/node-v0.8.14/deps/openssl/openssl/ssl/d1_lib.c b/node-v0.8.14/deps/openssl/openssl/ssl/d1_lib.c new file mode 100644 index 0000000..a94290a --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/ssl/d1_lib.c @@ -0,0 +1,451 @@ +/* ssl/d1_lib.c */ +/* + * DTLS implementation written by Nagendra Modadugu + * (nagendra@cs.stanford.edu) for the OpenSSL project 2005. + */ +/* ==================================================================== + * Copyright (c) 1999-2005 The OpenSSL Project. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. All advertising materials mentioning features or use of this + * software must display the following acknowledgment: + * "This product includes software developed by the OpenSSL Project + * for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)" + * + * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to + * endorse or promote products derived from this software without + * prior written permission. For written permission, please contact + * openssl-core@OpenSSL.org. + * + * 5. Products derived from this software may not be called "OpenSSL" + * nor may "OpenSSL" appear in their names without prior written + * permission of the OpenSSL Project. + * + * 6. Redistributions of any form whatsoever must retain the following + * acknowledgment: + * "This product includes software developed by the OpenSSL Project + * for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)" + * + * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY + * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR + * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, + * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * ==================================================================== + * + * This product includes cryptographic software written by Eric Young + * (eay@cryptsoft.com). This product includes software written by Tim + * Hudson (tjh@cryptsoft.com). + * + */ + +#include +#define USE_SOCKETS +#include +#include "ssl_locl.h" + +#if defined(OPENSSL_SYS_WIN32) || defined(OPENSSL_SYS_VMS) +#include +#endif + +static void get_current_time(struct timeval *t); +const char dtls1_version_str[]="DTLSv1" OPENSSL_VERSION_PTEXT; +int dtls1_listen(SSL *s, struct sockaddr *client); + +SSL3_ENC_METHOD DTLSv1_enc_data={ + dtls1_enc, + tls1_mac, + tls1_setup_key_block, + tls1_generate_master_secret, + tls1_change_cipher_state, + tls1_final_finish_mac, + TLS1_FINISH_MAC_LENGTH, + tls1_cert_verify_mac, + TLS_MD_CLIENT_FINISH_CONST,TLS_MD_CLIENT_FINISH_CONST_SIZE, + TLS_MD_SERVER_FINISH_CONST,TLS_MD_SERVER_FINISH_CONST_SIZE, + tls1_alert_code, + tls1_export_keying_material, + }; + +long dtls1_default_timeout(void) + { + /* 2 hours, the 24 hours mentioned in the DTLSv1 spec + * is way too long for http, the cache would over fill */ + return(60*60*2); + } + +int dtls1_new(SSL *s) + { + DTLS1_STATE *d1; + + if (!ssl3_new(s)) return(0); + if ((d1=OPENSSL_malloc(sizeof *d1)) == NULL) return (0); + memset(d1,0, sizeof *d1); + + /* d1->handshake_epoch=0; */ + + d1->unprocessed_rcds.q=pqueue_new(); + d1->processed_rcds.q=pqueue_new(); + d1->buffered_messages = pqueue_new(); + d1->sent_messages=pqueue_new(); + d1->buffered_app_data.q=pqueue_new(); + + if ( s->server) + { + d1->cookie_len = sizeof(s->d1->cookie); + } + + if( ! d1->unprocessed_rcds.q || ! d1->processed_rcds.q + || ! d1->buffered_messages || ! d1->sent_messages || ! d1->buffered_app_data.q) + { + if ( d1->unprocessed_rcds.q) pqueue_free(d1->unprocessed_rcds.q); + if ( d1->processed_rcds.q) pqueue_free(d1->processed_rcds.q); + if ( d1->buffered_messages) pqueue_free(d1->buffered_messages); + if ( d1->sent_messages) pqueue_free(d1->sent_messages); + if ( d1->buffered_app_data.q) pqueue_free(d1->buffered_app_data.q); + OPENSSL_free(d1); + return (0); + } + + s->d1=d1; + s->method->ssl_clear(s); + return(1); + } + +static void dtls1_clear_queues(SSL *s) + { + pitem *item = NULL; + hm_fragment *frag = NULL; + DTLS1_RECORD_DATA *rdata; + + while( (item = pqueue_pop(s->d1->unprocessed_rcds.q)) != NULL) + { + rdata = (DTLS1_RECORD_DATA *) item->data; + if (rdata->rbuf.buf) + { + OPENSSL_free(rdata->rbuf.buf); + } + OPENSSL_free(item->data); + pitem_free(item); + } + + while( (item = pqueue_pop(s->d1->processed_rcds.q)) != NULL) + { + rdata = (DTLS1_RECORD_DATA *) item->data; + if (rdata->rbuf.buf) + { + OPENSSL_free(rdata->rbuf.buf); + } + OPENSSL_free(item->data); + pitem_free(item); + } + + while( (item = pqueue_pop(s->d1->buffered_messages)) != NULL) + { + frag = (hm_fragment *)item->data; + OPENSSL_free(frag->fragment); + OPENSSL_free(frag); + pitem_free(item); + } + + while ( (item = pqueue_pop(s->d1->sent_messages)) != NULL) + { + frag = (hm_fragment *)item->data; + OPENSSL_free(frag->fragment); + OPENSSL_free(frag); + pitem_free(item); + } + + while ( (item = pqueue_pop(s->d1->buffered_app_data.q)) != NULL) + { + frag = (hm_fragment *)item->data; + OPENSSL_free(frag->fragment); + OPENSSL_free(frag); + pitem_free(item); + } + } + +void dtls1_free(SSL *s) + { + ssl3_free(s); + + dtls1_clear_queues(s); + + pqueue_free(s->d1->unprocessed_rcds.q); + pqueue_free(s->d1->processed_rcds.q); + pqueue_free(s->d1->buffered_messages); + pqueue_free(s->d1->sent_messages); + pqueue_free(s->d1->buffered_app_data.q); + + OPENSSL_free(s->d1); + } + +void dtls1_clear(SSL *s) + { + pqueue unprocessed_rcds; + pqueue processed_rcds; + pqueue buffered_messages; + pqueue sent_messages; + pqueue buffered_app_data; + unsigned int mtu; + + if (s->d1) + { + unprocessed_rcds = s->d1->unprocessed_rcds.q; + processed_rcds = s->d1->processed_rcds.q; + buffered_messages = s->d1->buffered_messages; + sent_messages = s->d1->sent_messages; + buffered_app_data = s->d1->buffered_app_data.q; + mtu = s->d1->mtu; + + dtls1_clear_queues(s); + + memset(s->d1, 0, sizeof(*(s->d1))); + + if (s->server) + { + s->d1->cookie_len = sizeof(s->d1->cookie); + } + + if (SSL_get_options(s) & SSL_OP_NO_QUERY_MTU) + { + s->d1->mtu = mtu; + } + + s->d1->unprocessed_rcds.q = unprocessed_rcds; + s->d1->processed_rcds.q = processed_rcds; + s->d1->buffered_messages = buffered_messages; + s->d1->sent_messages = sent_messages; + s->d1->buffered_app_data.q = buffered_app_data; + } + + ssl3_clear(s); + if (s->options & SSL_OP_CISCO_ANYCONNECT) + s->version=DTLS1_BAD_VER; + else + s->version=DTLS1_VERSION; + } + +long dtls1_ctrl(SSL *s, int cmd, long larg, void *parg) + { + int ret=0; + + switch (cmd) + { + case DTLS_CTRL_GET_TIMEOUT: + if (dtls1_get_timeout(s, (struct timeval*) parg) != NULL) + { + ret = 1; + } + break; + case DTLS_CTRL_HANDLE_TIMEOUT: + ret = dtls1_handle_timeout(s); + break; + case DTLS_CTRL_LISTEN: + ret = dtls1_listen(s, parg); + break; + + default: + ret = ssl3_ctrl(s, cmd, larg, parg); + break; + } + return(ret); + } + +/* + * As it's impossible to use stream ciphers in "datagram" mode, this + * simple filter is designed to disengage them in DTLS. Unfortunately + * there is no universal way to identify stream SSL_CIPHER, so we have + * to explicitly list their SSL_* codes. Currently RC4 is the only one + * available, but if new ones emerge, they will have to be added... + */ +const SSL_CIPHER *dtls1_get_cipher(unsigned int u) + { + const SSL_CIPHER *ciph = ssl3_get_cipher(u); + + if (ciph != NULL) + { + if (ciph->algorithm_enc == SSL_RC4) + return NULL; + } + + return ciph; + } + +void dtls1_start_timer(SSL *s) + { + /* If timer is not set, initialize duration with 1 second */ + if (s->d1->next_timeout.tv_sec == 0 && s->d1->next_timeout.tv_usec == 0) + { + s->d1->timeout_duration = 1; + } + + /* Set timeout to current time */ + get_current_time(&(s->d1->next_timeout)); + + /* Add duration to current time */ + s->d1->next_timeout.tv_sec += s->d1->timeout_duration; + BIO_ctrl(SSL_get_rbio(s), BIO_CTRL_DGRAM_SET_NEXT_TIMEOUT, 0, &(s->d1->next_timeout)); + } + +struct timeval* dtls1_get_timeout(SSL *s, struct timeval* timeleft) + { + struct timeval timenow; + + /* If no timeout is set, just return NULL */ + if (s->d1->next_timeout.tv_sec == 0 && s->d1->next_timeout.tv_usec == 0) + { + return NULL; + } + + /* Get current time */ + get_current_time(&timenow); + + /* If timer already expired, set remaining time to 0 */ + if (s->d1->next_timeout.tv_sec < timenow.tv_sec || + (s->d1->next_timeout.tv_sec == timenow.tv_sec && + s->d1->next_timeout.tv_usec <= timenow.tv_usec)) + { + memset(timeleft, 0, sizeof(struct timeval)); + return timeleft; + } + + /* Calculate time left until timer expires */ + memcpy(timeleft, &(s->d1->next_timeout), sizeof(struct timeval)); + timeleft->tv_sec -= timenow.tv_sec; + timeleft->tv_usec -= timenow.tv_usec; + if (timeleft->tv_usec < 0) + { + timeleft->tv_sec--; + timeleft->tv_usec += 1000000; + } + + /* If remaining time is less than 15 ms, set it to 0 + * to prevent issues because of small devergences with + * socket timeouts. + */ + if (timeleft->tv_sec == 0 && timeleft->tv_usec < 15000) + { + memset(timeleft, 0, sizeof(struct timeval)); + } + + + return timeleft; + } + +int dtls1_is_timer_expired(SSL *s) + { + struct timeval timeleft; + + /* Get time left until timeout, return false if no timer running */ + if (dtls1_get_timeout(s, &timeleft) == NULL) + { + return 0; + } + + /* Return false if timer is not expired yet */ + if (timeleft.tv_sec > 0 || timeleft.tv_usec > 0) + { + return 0; + } + + /* Timer expired, so return true */ + return 1; + } + +void dtls1_double_timeout(SSL *s) + { + s->d1->timeout_duration *= 2; + if (s->d1->timeout_duration > 60) + s->d1->timeout_duration = 60; + dtls1_start_timer(s); + } + +void dtls1_stop_timer(SSL *s) + { + /* Reset everything */ + memset(&(s->d1->next_timeout), 0, sizeof(struct timeval)); + s->d1->timeout_duration = 1; + BIO_ctrl(SSL_get_rbio(s), BIO_CTRL_DGRAM_SET_NEXT_TIMEOUT, 0, &(s->d1->next_timeout)); + /* Clear retransmission buffer */ + dtls1_clear_record_buffer(s); + } + +int dtls1_handle_timeout(SSL *s) + { + DTLS1_STATE *state; + + /* if no timer is expired, don't do anything */ + if (!dtls1_is_timer_expired(s)) + { + return 0; + } + + dtls1_double_timeout(s); + state = s->d1; + state->timeout.num_alerts++; + if ( state->timeout.num_alerts > DTLS1_TMO_ALERT_COUNT) + { + /* fail the connection, enough alerts have been sent */ + SSLerr(SSL_F_DTLS1_HANDLE_TIMEOUT,SSL_R_READ_TIMEOUT_EXPIRED); + return -1; + } + + state->timeout.read_timeouts++; + if ( state->timeout.read_timeouts > DTLS1_TMO_READ_COUNT) + { + state->timeout.read_timeouts = 1; + } + + dtls1_start_timer(s); + return dtls1_retransmit_buffered_messages(s); + } + +static void get_current_time(struct timeval *t) +{ +#ifdef OPENSSL_SYS_WIN32 + struct _timeb tb; + _ftime(&tb); + t->tv_sec = (long)tb.time; + t->tv_usec = (long)tb.millitm * 1000; +#elif defined(OPENSSL_SYS_VMS) + struct timeb tb; + ftime(&tb); + t->tv_sec = (long)tb.time; + t->tv_usec = (long)tb.millitm * 1000; +#else + gettimeofday(t, NULL); +#endif +} + +int dtls1_listen(SSL *s, struct sockaddr *client) + { + int ret; + + SSL_set_options(s, SSL_OP_COOKIE_EXCHANGE); + s->d1->listen = 1; + + ret = SSL_accept(s); + if (ret <= 0) return ret; + + (void) BIO_dgram_get_peer(SSL_get_rbio(s), client); + return 1; + } diff --git a/node-v0.8.14/deps/openssl/openssl/ssl/d1_meth.c b/node-v0.8.14/deps/openssl/openssl/ssl/d1_meth.c new file mode 100644 index 0000000..5c4004b --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/ssl/d1_meth.c @@ -0,0 +1,77 @@ +/* ssl/d1_meth.h */ +/* + * DTLS implementation written by Nagendra Modadugu + * (nagendra@cs.stanford.edu) for the OpenSSL project 2005. + */ +/* ==================================================================== + * Copyright (c) 1999-2005 The OpenSSL Project. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. All advertising materials mentioning features or use of this + * software must display the following acknowledgment: + * "This product includes software developed by the OpenSSL Project + * for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)" + * + * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to + * endorse or promote products derived from this software without + * prior written permission. For written permission, please contact + * openssl-core@OpenSSL.org. + * + * 5. Products derived from this software may not be called "OpenSSL" + * nor may "OpenSSL" appear in their names without prior written + * permission of the OpenSSL Project. + * + * 6. Redistributions of any form whatsoever must retain the following + * acknowledgment: + * "This product includes software developed by the OpenSSL Project + * for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)" + * + * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY + * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR + * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, + * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * ==================================================================== + * + * This product includes cryptographic software written by Eric Young + * (eay@cryptsoft.com). This product includes software written by Tim + * Hudson (tjh@cryptsoft.com). + * + */ + +#include +#include +#include "ssl_locl.h" + +static const SSL_METHOD *dtls1_get_method(int ver); +static const SSL_METHOD *dtls1_get_method(int ver) + { + if (ver == DTLS1_VERSION) + return(DTLSv1_method()); + else + return(NULL); + } + +IMPLEMENT_dtls1_meth_func(DTLSv1_method, + dtls1_accept, + dtls1_connect, + dtls1_get_method) + diff --git a/node-v0.8.14/deps/openssl/openssl/ssl/d1_pkt.c b/node-v0.8.14/deps/openssl/openssl/ssl/d1_pkt.c new file mode 100644 index 0000000..3927dad --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/ssl/d1_pkt.c @@ -0,0 +1,1806 @@ +/* ssl/d1_pkt.c */ +/* + * DTLS implementation written by Nagendra Modadugu + * (nagendra@cs.stanford.edu) for the OpenSSL project 2005. + */ +/* ==================================================================== + * Copyright (c) 1998-2005 The OpenSSL Project. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. All advertising materials mentioning features or use of this + * software must display the following acknowledgment: + * "This product includes software developed by the OpenSSL Project + * for use in the OpenSSL Toolkit. (http://www.openssl.org/)" + * + * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to + * endorse or promote products derived from this software without + * prior written permission. For written permission, please contact + * openssl-core@openssl.org. + * + * 5. Products derived from this software may not be called "OpenSSL" + * nor may "OpenSSL" appear in their names without prior written + * permission of the OpenSSL Project. + * + * 6. Redistributions of any form whatsoever must retain the following + * acknowledgment: + * "This product includes software developed by the OpenSSL Project + * for use in the OpenSSL Toolkit (http://www.openssl.org/)" + * + * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY + * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR + * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, + * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * ==================================================================== + * + * This product includes cryptographic software written by Eric Young + * (eay@cryptsoft.com). This product includes software written by Tim + * Hudson (tjh@cryptsoft.com). + * + */ +/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com) + * All rights reserved. + * + * This package is an SSL implementation written + * by Eric Young (eay@cryptsoft.com). + * The implementation was written so as to conform with Netscapes SSL. + * + * This library is free for commercial and non-commercial use as long as + * the following conditions are aheared to. The following conditions + * apply to all code found in this distribution, be it the RC4, RSA, + * lhash, DES, etc., code; not just the SSL code. The SSL documentation + * included with this distribution is covered by the same copyright terms + * except that the holder is Tim Hudson (tjh@cryptsoft.com). + * + * Copyright remains Eric Young's, and as such any Copyright notices in + * the code are not to be removed. + * If this package is used in a product, Eric Young should be given attribution + * as the author of the parts of the library used. + * This can be in the form of a textual message at program startup or + * in documentation (online or textual) provided with the package. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * "This product includes cryptographic software written by + * Eric Young (eay@cryptsoft.com)" + * The word 'cryptographic' can be left out if the rouines from the library + * being used are not cryptographic related :-). + * 4. If you include any Windows specific code (or a derivative thereof) from + * the apps directory (application code) you must include an acknowledgement: + * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)" + * + * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * + * The licence and distribution terms for any publically available version or + * derivative of this code cannot be changed. i.e. this code cannot simply be + * copied and put under another distribution licence + * [including the GNU Public Licence.] + */ + +#include +#include +#define USE_SOCKETS +#include "ssl_locl.h" +#include +#include +#include +#include + +/* mod 128 saturating subtract of two 64-bit values in big-endian order */ +static int satsub64be(const unsigned char *v1,const unsigned char *v2) +{ int ret,sat,brw,i; + + if (sizeof(long) == 8) do + { const union { long one; char little; } is_endian = {1}; + long l; + + if (is_endian.little) break; + /* not reached on little-endians */ + /* following test is redundant, because input is + * always aligned, but I take no chances... */ + if (((size_t)v1|(size_t)v2)&0x7) break; + + l = *((long *)v1); + l -= *((long *)v2); + if (l>128) return 128; + else if (l<-128) return -128; + else return (int)l; + } while (0); + + ret = (int)v1[7]-(int)v2[7]; + sat = 0; + brw = ret>>8; /* brw is either 0 or -1 */ + if (ret & 0x80) + { for (i=6;i>=0;i--) + { brw += (int)v1[i]-(int)v2[i]; + sat |= ~brw; + brw >>= 8; + } + } + else + { for (i=6;i>=0;i--) + { brw += (int)v1[i]-(int)v2[i]; + sat |= brw; + brw >>= 8; + } + } + brw <<= 8; /* brw is either 0 or -256 */ + + if (sat&0xff) return brw | 0x80; + else return brw + (ret&0xFF); +} + +static int have_handshake_fragment(SSL *s, int type, unsigned char *buf, + int len, int peek); +static int dtls1_record_replay_check(SSL *s, DTLS1_BITMAP *bitmap); +static void dtls1_record_bitmap_update(SSL *s, DTLS1_BITMAP *bitmap); +static DTLS1_BITMAP *dtls1_get_bitmap(SSL *s, SSL3_RECORD *rr, + unsigned int *is_next_epoch); +#if 0 +static int dtls1_record_needs_buffering(SSL *s, SSL3_RECORD *rr, + unsigned short *priority, unsigned long *offset); +#endif +static int dtls1_buffer_record(SSL *s, record_pqueue *q, + unsigned char *priority); +static int dtls1_process_record(SSL *s); +static void dtls1_clear_timeouts(SSL *s); + +/* copy buffered record into SSL structure */ +static int +dtls1_copy_record(SSL *s, pitem *item) + { + DTLS1_RECORD_DATA *rdata; + + rdata = (DTLS1_RECORD_DATA *)item->data; + + if (s->s3->rbuf.buf != NULL) + OPENSSL_free(s->s3->rbuf.buf); + + s->packet = rdata->packet; + s->packet_length = rdata->packet_length; + memcpy(&(s->s3->rbuf), &(rdata->rbuf), sizeof(SSL3_BUFFER)); + memcpy(&(s->s3->rrec), &(rdata->rrec), sizeof(SSL3_RECORD)); + + /* Set proper sequence number for mac calculation */ + memcpy(&(s->s3->read_sequence[2]), &(rdata->packet[5]), 6); + + return(1); + } + + +static int +dtls1_buffer_record(SSL *s, record_pqueue *queue, unsigned char *priority) + { + DTLS1_RECORD_DATA *rdata; + pitem *item; + + /* Limit the size of the queue to prevent DOS attacks */ + if (pqueue_size(queue->q) >= 100) + return 0; + + rdata = OPENSSL_malloc(sizeof(DTLS1_RECORD_DATA)); + item = pitem_new(priority, rdata); + if (rdata == NULL || item == NULL) + { + if (rdata != NULL) OPENSSL_free(rdata); + if (item != NULL) pitem_free(item); + + SSLerr(SSL_F_DTLS1_BUFFER_RECORD, ERR_R_INTERNAL_ERROR); + return(0); + } + + rdata->packet = s->packet; + rdata->packet_length = s->packet_length; + memcpy(&(rdata->rbuf), &(s->s3->rbuf), sizeof(SSL3_BUFFER)); + memcpy(&(rdata->rrec), &(s->s3->rrec), sizeof(SSL3_RECORD)); + + item->data = rdata; + + /* insert should not fail, since duplicates are dropped */ + if (pqueue_insert(queue->q, item) == NULL) + { + OPENSSL_free(rdata); + pitem_free(item); + return(0); + } + + s->packet = NULL; + s->packet_length = 0; + memset(&(s->s3->rbuf), 0, sizeof(SSL3_BUFFER)); + memset(&(s->s3->rrec), 0, sizeof(SSL3_RECORD)); + + if (!ssl3_setup_buffers(s)) + { + SSLerr(SSL_F_DTLS1_BUFFER_RECORD, ERR_R_INTERNAL_ERROR); + OPENSSL_free(rdata); + pitem_free(item); + return(0); + } + + return(1); + } + + +static int +dtls1_retrieve_buffered_record(SSL *s, record_pqueue *queue) + { + pitem *item; + + item = pqueue_pop(queue->q); + if (item) + { + dtls1_copy_record(s, item); + + OPENSSL_free(item->data); + pitem_free(item); + + return(1); + } + + return(0); + } + + +/* retrieve a buffered record that belongs to the new epoch, i.e., not processed + * yet */ +#define dtls1_get_unprocessed_record(s) \ + dtls1_retrieve_buffered_record((s), \ + &((s)->d1->unprocessed_rcds)) + +/* retrieve a buffered record that belongs to the current epoch, ie, processed */ +#define dtls1_get_processed_record(s) \ + dtls1_retrieve_buffered_record((s), \ + &((s)->d1->processed_rcds)) + +static int +dtls1_process_buffered_records(SSL *s) + { + pitem *item; + + item = pqueue_peek(s->d1->unprocessed_rcds.q); + if (item) + { + /* Check if epoch is current. */ + if (s->d1->unprocessed_rcds.epoch != s->d1->r_epoch) + return(1); /* Nothing to do. */ + + /* Process all the records. */ + while (pqueue_peek(s->d1->unprocessed_rcds.q)) + { + dtls1_get_unprocessed_record(s); + if ( ! dtls1_process_record(s)) + return(0); + dtls1_buffer_record(s, &(s->d1->processed_rcds), + s->s3->rrec.seq_num); + } + } + + /* sync epoch numbers once all the unprocessed records + * have been processed */ + s->d1->processed_rcds.epoch = s->d1->r_epoch; + s->d1->unprocessed_rcds.epoch = s->d1->r_epoch + 1; + + return(1); + } + + +#if 0 + +static int +dtls1_get_buffered_record(SSL *s) + { + pitem *item; + PQ_64BIT priority = + (((PQ_64BIT)s->d1->handshake_read_seq) << 32) | + ((PQ_64BIT)s->d1->r_msg_hdr.frag_off); + + if ( ! SSL_in_init(s)) /* if we're not (re)negotiating, + nothing buffered */ + return 0; + + + item = pqueue_peek(s->d1->rcvd_records); + if (item && item->priority == priority) + { + /* Check if we've received the record of interest. It must be + * a handshake record, since data records as passed up without + * buffering */ + DTLS1_RECORD_DATA *rdata; + item = pqueue_pop(s->d1->rcvd_records); + rdata = (DTLS1_RECORD_DATA *)item->data; + + if (s->s3->rbuf.buf != NULL) + OPENSSL_free(s->s3->rbuf.buf); + + s->packet = rdata->packet; + s->packet_length = rdata->packet_length; + memcpy(&(s->s3->rbuf), &(rdata->rbuf), sizeof(SSL3_BUFFER)); + memcpy(&(s->s3->rrec), &(rdata->rrec), sizeof(SSL3_RECORD)); + + OPENSSL_free(item->data); + pitem_free(item); + + /* s->d1->next_expected_seq_num++; */ + return(1); + } + + return 0; + } + +#endif + +static int +dtls1_process_record(SSL *s) +{ + int i,al; + int clear=0; + int enc_err; + SSL_SESSION *sess; + SSL3_RECORD *rr; + unsigned int mac_size; + unsigned char md[EVP_MAX_MD_SIZE]; + int decryption_failed_or_bad_record_mac = 0; + + + rr= &(s->s3->rrec); + sess = s->session; + + /* At this point, s->packet_length == SSL3_RT_HEADER_LNGTH + rr->length, + * and we have that many bytes in s->packet + */ + rr->input= &(s->packet[DTLS1_RT_HEADER_LENGTH]); + + /* ok, we can now read from 's->packet' data into 'rr' + * rr->input points at rr->length bytes, which + * need to be copied into rr->data by either + * the decryption or by the decompression + * When the data is 'copied' into the rr->data buffer, + * rr->input will be pointed at the new buffer */ + + /* We now have - encrypted [ MAC [ compressed [ plain ] ] ] + * rr->length bytes of encrypted compressed stuff. */ + + /* check is not needed I believe */ + if (rr->length > SSL3_RT_MAX_ENCRYPTED_LENGTH) + { + al=SSL_AD_RECORD_OVERFLOW; + SSLerr(SSL_F_DTLS1_PROCESS_RECORD,SSL_R_ENCRYPTED_LENGTH_TOO_LONG); + goto f_err; + } + + /* decrypt in place in 'rr->input' */ + rr->data=rr->input; + + enc_err = s->method->ssl3_enc->enc(s,0); + if (enc_err <= 0) + { + /* To minimize information leaked via timing, we will always + * perform all computations before discarding the message. + */ + decryption_failed_or_bad_record_mac = 1; + } + +#ifdef TLS_DEBUG +printf("dec %d\n",rr->length); +{ unsigned int z; for (z=0; zlength; z++) printf("%02X%c",rr->data[z],((z+1)%16)?' ':'\n'); } +printf("\n"); +#endif + + /* r->length is now the compressed data plus mac */ + if ( (sess == NULL) || + (s->enc_read_ctx == NULL) || + (s->read_hash == NULL)) + clear=1; + + if (!clear) + { + /* !clear => s->read_hash != NULL => mac_size != -1 */ + int t; + t=EVP_MD_CTX_size(s->read_hash); + OPENSSL_assert(t >= 0); + mac_size=t; + + if (rr->length > SSL3_RT_MAX_COMPRESSED_LENGTH+mac_size) + { +#if 0 /* OK only for stream ciphers (then rr->length is visible from ciphertext anyway) */ + al=SSL_AD_RECORD_OVERFLOW; + SSLerr(SSL_F_DTLS1_PROCESS_RECORD,SSL_R_PRE_MAC_LENGTH_TOO_LONG); + goto f_err; +#else + decryption_failed_or_bad_record_mac = 1; +#endif + } + /* check the MAC for rr->input (it's in mac_size bytes at the tail) */ + if (rr->length < mac_size) + { +#if 0 /* OK only for stream ciphers */ + al=SSL_AD_DECODE_ERROR; + SSLerr(SSL_F_DTLS1_PROCESS_RECORD,SSL_R_LENGTH_TOO_SHORT); + goto f_err; +#else + decryption_failed_or_bad_record_mac = 1; +#endif + } + rr->length-=mac_size; + i=s->method->ssl3_enc->mac(s,md,0); + if (i < 0 || memcmp(md,&(rr->data[rr->length]),mac_size) != 0) + { + decryption_failed_or_bad_record_mac = 1; + } + } + + if (decryption_failed_or_bad_record_mac) + { + /* decryption failed, silently discard message */ + rr->length = 0; + s->packet_length = 0; + goto err; + } + + /* r->length is now just compressed */ + if (s->expand != NULL) + { + if (rr->length > SSL3_RT_MAX_COMPRESSED_LENGTH) + { + al=SSL_AD_RECORD_OVERFLOW; + SSLerr(SSL_F_DTLS1_PROCESS_RECORD,SSL_R_COMPRESSED_LENGTH_TOO_LONG); + goto f_err; + } + if (!ssl3_do_uncompress(s)) + { + al=SSL_AD_DECOMPRESSION_FAILURE; + SSLerr(SSL_F_DTLS1_PROCESS_RECORD,SSL_R_BAD_DECOMPRESSION); + goto f_err; + } + } + + if (rr->length > SSL3_RT_MAX_PLAIN_LENGTH) + { + al=SSL_AD_RECORD_OVERFLOW; + SSLerr(SSL_F_DTLS1_PROCESS_RECORD,SSL_R_DATA_LENGTH_TOO_LONG); + goto f_err; + } + + rr->off=0; + /* So at this point the following is true + * ssl->s3->rrec.type is the type of record + * ssl->s3->rrec.length == number of bytes in record + * ssl->s3->rrec.off == offset to first valid byte + * ssl->s3->rrec.data == where to take bytes from, increment + * after use :-). + */ + + /* we have pulled in a full packet so zero things */ + s->packet_length=0; + dtls1_record_bitmap_update(s, &(s->d1->bitmap));/* Mark receipt of record. */ + return(1); + +f_err: + ssl3_send_alert(s,SSL3_AL_FATAL,al); +err: + return(0); +} + + +/* Call this to get a new input record. + * It will return <= 0 if more data is needed, normally due to an error + * or non-blocking IO. + * When it finishes, one packet has been decoded and can be found in + * ssl->s3->rrec.type - is the type of record + * ssl->s3->rrec.data, - data + * ssl->s3->rrec.length, - number of bytes + */ +/* used only by dtls1_read_bytes */ +int dtls1_get_record(SSL *s) + { + int ssl_major,ssl_minor; + int i,n; + SSL3_RECORD *rr; + unsigned char *p = NULL; + unsigned short version; + DTLS1_BITMAP *bitmap; + unsigned int is_next_epoch; + + rr= &(s->s3->rrec); + + /* The epoch may have changed. If so, process all the + * pending records. This is a non-blocking operation. */ + dtls1_process_buffered_records(s); + + /* if we're renegotiating, then there may be buffered records */ + if (dtls1_get_processed_record(s)) + return 1; + + /* get something from the wire */ +again: + /* check if we have the header */ + if ( (s->rstate != SSL_ST_READ_BODY) || + (s->packet_length < DTLS1_RT_HEADER_LENGTH)) + { + n=ssl3_read_n(s, DTLS1_RT_HEADER_LENGTH, s->s3->rbuf.len, 0); + /* read timeout is handled by dtls1_read_bytes */ + if (n <= 0) return(n); /* error or non-blocking */ + + /* this packet contained a partial record, dump it */ + if (s->packet_length != DTLS1_RT_HEADER_LENGTH) + { + s->packet_length = 0; + goto again; + } + + s->rstate=SSL_ST_READ_BODY; + + p=s->packet; + + /* Pull apart the header into the DTLS1_RECORD */ + rr->type= *(p++); + ssl_major= *(p++); + ssl_minor= *(p++); + version=(ssl_major<<8)|ssl_minor; + + /* sequence number is 64 bits, with top 2 bytes = epoch */ + n2s(p,rr->epoch); + + memcpy(&(s->s3->read_sequence[2]), p, 6); + p+=6; + + n2s(p,rr->length); + + /* Lets check version */ + if (!s->first_packet) + { + if (version != s->version) + { + /* unexpected version, silently discard */ + rr->length = 0; + s->packet_length = 0; + goto again; + } + } + + if ((version & 0xff00) != (s->version & 0xff00)) + { + /* wrong version, silently discard record */ + rr->length = 0; + s->packet_length = 0; + goto again; + } + + if (rr->length > SSL3_RT_MAX_ENCRYPTED_LENGTH) + { + /* record too long, silently discard it */ + rr->length = 0; + s->packet_length = 0; + goto again; + } + + /* If we receive a valid record larger than the current buffer size, + * allocate some memory for it. + */ + if (rr->length > s->s3->rbuf.len - DTLS1_RT_HEADER_LENGTH) + { + unsigned char *pp; + unsigned int newlen = rr->length + DTLS1_RT_HEADER_LENGTH; + if ((pp=OPENSSL_realloc(s->s3->rbuf.buf, newlen))==NULL) + { + SSLerr(SSL_F_DTLS1_GET_RECORD,ERR_R_MALLOC_FAILURE); + return(-1); + } + p = pp + (p - s->s3->rbuf.buf); + s->s3->rbuf.buf=pp; + s->s3->rbuf.len=newlen; + s->packet= &(s->s3->rbuf.buf[0]); + } + + /* now s->rstate == SSL_ST_READ_BODY */ + } + + /* s->rstate == SSL_ST_READ_BODY, get and decode the data */ + + if (rr->length > s->packet_length-DTLS1_RT_HEADER_LENGTH) + { + /* now s->packet_length == DTLS1_RT_HEADER_LENGTH */ + i=rr->length; + n=ssl3_read_n(s,i,i,1); + if (n <= 0) return(n); /* error or non-blocking io */ + + /* this packet contained a partial record, dump it */ + if ( n != i) + { + rr->length = 0; + s->packet_length = 0; + goto again; + } + + /* now n == rr->length, + * and s->packet_length == DTLS1_RT_HEADER_LENGTH + rr->length */ + } + s->rstate=SSL_ST_READ_HEADER; /* set state for later operations */ + + /* match epochs. NULL means the packet is dropped on the floor */ + bitmap = dtls1_get_bitmap(s, rr, &is_next_epoch); + if ( bitmap == NULL) + { + rr->length = 0; + s->packet_length = 0; /* dump this record */ + goto again; /* get another record */ + } + + /* Check whether this is a repeat, or aged record. + * Don't check if we're listening and this message is + * a ClientHello. They can look as if they're replayed, + * since they arrive from different connections and + * would be dropped unnecessarily. + */ + if (!(s->d1->listen && rr->type == SSL3_RT_HANDSHAKE && + *p == SSL3_MT_CLIENT_HELLO) && + !dtls1_record_replay_check(s, bitmap)) + { + rr->length = 0; + s->packet_length=0; /* dump this record */ + goto again; /* get another record */ + } + + /* just read a 0 length packet */ + if (rr->length == 0) goto again; + + /* If this record is from the next epoch (either HM or ALERT), + * and a handshake is currently in progress, buffer it since it + * cannot be processed at this time. However, do not buffer + * anything while listening. + */ + if (is_next_epoch) + { + if ((SSL_in_init(s) || s->in_handshake) && !s->d1->listen) + { + dtls1_buffer_record(s, &(s->d1->unprocessed_rcds), rr->seq_num); + } + rr->length = 0; + s->packet_length = 0; + goto again; + } + + if (!dtls1_process_record(s)) + { + rr->length = 0; + s->packet_length = 0; /* dump this record */ + goto again; /* get another record */ + } + + dtls1_clear_timeouts(s); /* done waiting */ + return(1); + + } + +/* Return up to 'len' payload bytes received in 'type' records. + * 'type' is one of the following: + * + * - SSL3_RT_HANDSHAKE (when ssl3_get_message calls us) + * - SSL3_RT_APPLICATION_DATA (when ssl3_read calls us) + * - 0 (during a shutdown, no data has to be returned) + * + * If we don't have stored data to work from, read a SSL/TLS record first + * (possibly multiple records if we still don't have anything to return). + * + * This function must handle any surprises the peer may have for us, such as + * Alert records (e.g. close_notify), ChangeCipherSpec records (not really + * a surprise, but handled as if it were), or renegotiation requests. + * Also if record payloads contain fragments too small to process, we store + * them until there is enough for the respective protocol (the record protocol + * may use arbitrary fragmentation and even interleaving): + * Change cipher spec protocol + * just 1 byte needed, no need for keeping anything stored + * Alert protocol + * 2 bytes needed (AlertLevel, AlertDescription) + * Handshake protocol + * 4 bytes needed (HandshakeType, uint24 length) -- we just have + * to detect unexpected Client Hello and Hello Request messages + * here, anything else is handled by higher layers + * Application data protocol + * none of our business + */ +int dtls1_read_bytes(SSL *s, int type, unsigned char *buf, int len, int peek) + { + int al,i,j,ret; + unsigned int n; + SSL3_RECORD *rr; + void (*cb)(const SSL *ssl,int type2,int val)=NULL; + + if (s->s3->rbuf.buf == NULL) /* Not initialized yet */ + if (!ssl3_setup_buffers(s)) + return(-1); + + /* XXX: check what the second '&& type' is about */ + if ((type && (type != SSL3_RT_APPLICATION_DATA) && + (type != SSL3_RT_HANDSHAKE) && type) || + (peek && (type != SSL3_RT_APPLICATION_DATA))) + { + SSLerr(SSL_F_DTLS1_READ_BYTES, ERR_R_INTERNAL_ERROR); + return -1; + } + + /* check whether there's a handshake message (client hello?) waiting */ + if ( (ret = have_handshake_fragment(s, type, buf, len, peek))) + return ret; + + /* Now s->d1->handshake_fragment_len == 0 if type == SSL3_RT_HANDSHAKE. */ + + if (!s->in_handshake && SSL_in_init(s)) + { + /* type == SSL3_RT_APPLICATION_DATA */ + i=s->handshake_func(s); + if (i < 0) return(i); + if (i == 0) + { + SSLerr(SSL_F_DTLS1_READ_BYTES,SSL_R_SSL_HANDSHAKE_FAILURE); + return(-1); + } + } + +start: + s->rwstate=SSL_NOTHING; + + /* s->s3->rrec.type - is the type of record + * s->s3->rrec.data, - data + * s->s3->rrec.off, - offset into 'data' for next read + * s->s3->rrec.length, - number of bytes. */ + rr = &(s->s3->rrec); + + /* We are not handshaking and have no data yet, + * so process data buffered during the last handshake + * in advance, if any. + */ + if (s->state == SSL_ST_OK && rr->length == 0) + { + pitem *item; + item = pqueue_pop(s->d1->buffered_app_data.q); + if (item) + { + dtls1_copy_record(s, item); + + OPENSSL_free(item->data); + pitem_free(item); + } + } + + /* Check for timeout */ + if (dtls1_handle_timeout(s) > 0) + goto start; + + /* get new packet if necessary */ + if ((rr->length == 0) || (s->rstate == SSL_ST_READ_BODY)) + { + ret=dtls1_get_record(s); + if (ret <= 0) + { + ret = dtls1_read_failed(s, ret); + /* anything other than a timeout is an error */ + if (ret <= 0) + return(ret); + else + goto start; + } + } + + /* we now have a packet which can be read and processed */ + + if (s->s3->change_cipher_spec /* set when we receive ChangeCipherSpec, + * reset by ssl3_get_finished */ + && (rr->type != SSL3_RT_HANDSHAKE)) + { + /* We now have application data between CCS and Finished. + * Most likely the packets were reordered on their way, so + * buffer the application data for later processing rather + * than dropping the connection. + */ + dtls1_buffer_record(s, &(s->d1->buffered_app_data), rr->seq_num); + rr->length = 0; + goto start; + } + + /* If the other end has shut down, throw anything we read away + * (even in 'peek' mode) */ + if (s->shutdown & SSL_RECEIVED_SHUTDOWN) + { + rr->length=0; + s->rwstate=SSL_NOTHING; + return(0); + } + + + if (type == rr->type) /* SSL3_RT_APPLICATION_DATA or SSL3_RT_HANDSHAKE */ + { + /* make sure that we are not getting application data when we + * are doing a handshake for the first time */ + if (SSL_in_init(s) && (type == SSL3_RT_APPLICATION_DATA) && + (s->enc_read_ctx == NULL)) + { + al=SSL_AD_UNEXPECTED_MESSAGE; + SSLerr(SSL_F_DTLS1_READ_BYTES,SSL_R_APP_DATA_IN_HANDSHAKE); + goto f_err; + } + + if (len <= 0) return(len); + + if ((unsigned int)len > rr->length) + n = rr->length; + else + n = (unsigned int)len; + + memcpy(buf,&(rr->data[rr->off]),n); + if (!peek) + { + rr->length-=n; + rr->off+=n; + if (rr->length == 0) + { + s->rstate=SSL_ST_READ_HEADER; + rr->off=0; + } + } + return(n); + } + + + /* If we get here, then type != rr->type; if we have a handshake + * message, then it was unexpected (Hello Request or Client Hello). */ + + /* In case of record types for which we have 'fragment' storage, + * fill that so that we can process the data at a fixed place. + */ + { + unsigned int k, dest_maxlen = 0; + unsigned char *dest = NULL; + unsigned int *dest_len = NULL; + + if (rr->type == SSL3_RT_HANDSHAKE) + { + dest_maxlen = sizeof s->d1->handshake_fragment; + dest = s->d1->handshake_fragment; + dest_len = &s->d1->handshake_fragment_len; + } + else if (rr->type == SSL3_RT_ALERT) + { + dest_maxlen = sizeof(s->d1->alert_fragment); + dest = s->d1->alert_fragment; + dest_len = &s->d1->alert_fragment_len; + } + /* else it's a CCS message, or application data or wrong */ + else if (rr->type != SSL3_RT_CHANGE_CIPHER_SPEC) + { + /* Application data while renegotiating + * is allowed. Try again reading. + */ + if (rr->type == SSL3_RT_APPLICATION_DATA) + { + BIO *bio; + s->s3->in_read_app_data=2; + bio=SSL_get_rbio(s); + s->rwstate=SSL_READING; + BIO_clear_retry_flags(bio); + BIO_set_retry_read(bio); + return(-1); + } + + /* Not certain if this is the right error handling */ + al=SSL_AD_UNEXPECTED_MESSAGE; + SSLerr(SSL_F_DTLS1_READ_BYTES,SSL_R_UNEXPECTED_RECORD); + goto f_err; + } + + if (dest_maxlen > 0) + { + /* XDTLS: In a pathalogical case, the Client Hello + * may be fragmented--don't always expect dest_maxlen bytes */ + if ( rr->length < dest_maxlen) + { +#ifdef DTLS1_AD_MISSING_HANDSHAKE_MESSAGE + /* + * for normal alerts rr->length is 2, while + * dest_maxlen is 7 if we were to handle this + * non-existing alert... + */ + FIX ME +#endif + s->rstate=SSL_ST_READ_HEADER; + rr->length = 0; + goto start; + } + + /* now move 'n' bytes: */ + for ( k = 0; k < dest_maxlen; k++) + { + dest[k] = rr->data[rr->off++]; + rr->length--; + } + *dest_len = dest_maxlen; + } + } + + /* s->d1->handshake_fragment_len == 12 iff rr->type == SSL3_RT_HANDSHAKE; + * s->d1->alert_fragment_len == 7 iff rr->type == SSL3_RT_ALERT. + * (Possibly rr is 'empty' now, i.e. rr->length may be 0.) */ + + /* If we are a client, check for an incoming 'Hello Request': */ + if ((!s->server) && + (s->d1->handshake_fragment_len >= DTLS1_HM_HEADER_LENGTH) && + (s->d1->handshake_fragment[0] == SSL3_MT_HELLO_REQUEST) && + (s->session != NULL) && (s->session->cipher != NULL)) + { + s->d1->handshake_fragment_len = 0; + + if ((s->d1->handshake_fragment[1] != 0) || + (s->d1->handshake_fragment[2] != 0) || + (s->d1->handshake_fragment[3] != 0)) + { + al=SSL_AD_DECODE_ERROR; + SSLerr(SSL_F_DTLS1_READ_BYTES,SSL_R_BAD_HELLO_REQUEST); + goto err; + } + + /* no need to check sequence number on HELLO REQUEST messages */ + + if (s->msg_callback) + s->msg_callback(0, s->version, SSL3_RT_HANDSHAKE, + s->d1->handshake_fragment, 4, s, s->msg_callback_arg); + + if (SSL_is_init_finished(s) && + !(s->s3->flags & SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS) && + !s->s3->renegotiate) + { + ssl3_renegotiate(s); + if (ssl3_renegotiate_check(s)) + { + i=s->handshake_func(s); + if (i < 0) return(i); + if (i == 0) + { + SSLerr(SSL_F_DTLS1_READ_BYTES,SSL_R_SSL_HANDSHAKE_FAILURE); + return(-1); + } + + if (!(s->mode & SSL_MODE_AUTO_RETRY)) + { + if (s->s3->rbuf.left == 0) /* no read-ahead left? */ + { + BIO *bio; + /* In the case where we try to read application data, + * but we trigger an SSL handshake, we return -1 with + * the retry option set. Otherwise renegotiation may + * cause nasty problems in the blocking world */ + s->rwstate=SSL_READING; + bio=SSL_get_rbio(s); + BIO_clear_retry_flags(bio); + BIO_set_retry_read(bio); + return(-1); + } + } + } + } + /* we either finished a handshake or ignored the request, + * now try again to obtain the (application) data we were asked for */ + goto start; + } + + if (s->d1->alert_fragment_len >= DTLS1_AL_HEADER_LENGTH) + { + int alert_level = s->d1->alert_fragment[0]; + int alert_descr = s->d1->alert_fragment[1]; + + s->d1->alert_fragment_len = 0; + + if (s->msg_callback) + s->msg_callback(0, s->version, SSL3_RT_ALERT, + s->d1->alert_fragment, 2, s, s->msg_callback_arg); + + if (s->info_callback != NULL) + cb=s->info_callback; + else if (s->ctx->info_callback != NULL) + cb=s->ctx->info_callback; + + if (cb != NULL) + { + j = (alert_level << 8) | alert_descr; + cb(s, SSL_CB_READ_ALERT, j); + } + + if (alert_level == 1) /* warning */ + { + s->s3->warn_alert = alert_descr; + if (alert_descr == SSL_AD_CLOSE_NOTIFY) + { + s->shutdown |= SSL_RECEIVED_SHUTDOWN; + return(0); + } +#if 0 + /* XXX: this is a possible improvement in the future */ + /* now check if it's a missing record */ + if (alert_descr == DTLS1_AD_MISSING_HANDSHAKE_MESSAGE) + { + unsigned short seq; + unsigned int frag_off; + unsigned char *p = &(s->d1->alert_fragment[2]); + + n2s(p, seq); + n2l3(p, frag_off); + + dtls1_retransmit_message(s, + dtls1_get_queue_priority(frag->msg_header.seq, 0), + frag_off, &found); + if ( ! found && SSL_in_init(s)) + { + /* fprintf( stderr,"in init = %d\n", SSL_in_init(s)); */ + /* requested a message not yet sent, + send an alert ourselves */ + ssl3_send_alert(s,SSL3_AL_WARNING, + DTLS1_AD_MISSING_HANDSHAKE_MESSAGE); + } + } +#endif + } + else if (alert_level == 2) /* fatal */ + { + char tmp[16]; + + s->rwstate=SSL_NOTHING; + s->s3->fatal_alert = alert_descr; + SSLerr(SSL_F_DTLS1_READ_BYTES, SSL_AD_REASON_OFFSET + alert_descr); + BIO_snprintf(tmp,sizeof tmp,"%d",alert_descr); + ERR_add_error_data(2,"SSL alert number ",tmp); + s->shutdown|=SSL_RECEIVED_SHUTDOWN; + SSL_CTX_remove_session(s->ctx,s->session); + return(0); + } + else + { + al=SSL_AD_ILLEGAL_PARAMETER; + SSLerr(SSL_F_DTLS1_READ_BYTES,SSL_R_UNKNOWN_ALERT_TYPE); + goto f_err; + } + + goto start; + } + + if (s->shutdown & SSL_SENT_SHUTDOWN) /* but we have not received a shutdown */ + { + s->rwstate=SSL_NOTHING; + rr->length=0; + return(0); + } + + if (rr->type == SSL3_RT_CHANGE_CIPHER_SPEC) + { + struct ccs_header_st ccs_hdr; + unsigned int ccs_hdr_len = DTLS1_CCS_HEADER_LENGTH; + + dtls1_get_ccs_header(rr->data, &ccs_hdr); + + if (s->version == DTLS1_BAD_VER) + ccs_hdr_len = 3; + + /* 'Change Cipher Spec' is just a single byte, so we know + * exactly what the record payload has to look like */ + /* XDTLS: check that epoch is consistent */ + if ( (rr->length != ccs_hdr_len) || + (rr->off != 0) || (rr->data[0] != SSL3_MT_CCS)) + { + i=SSL_AD_ILLEGAL_PARAMETER; + SSLerr(SSL_F_DTLS1_READ_BYTES,SSL_R_BAD_CHANGE_CIPHER_SPEC); + goto err; + } + + rr->length=0; + + if (s->msg_callback) + s->msg_callback(0, s->version, SSL3_RT_CHANGE_CIPHER_SPEC, + rr->data, 1, s, s->msg_callback_arg); + + /* We can't process a CCS now, because previous handshake + * messages are still missing, so just drop it. + */ + if (!s->d1->change_cipher_spec_ok) + { + goto start; + } + + s->d1->change_cipher_spec_ok = 0; + + s->s3->change_cipher_spec=1; + if (!ssl3_do_change_cipher_spec(s)) + goto err; + + /* do this whenever CCS is processed */ + dtls1_reset_seq_numbers(s, SSL3_CC_READ); + + if (s->version == DTLS1_BAD_VER) + s->d1->handshake_read_seq++; + + goto start; + } + + /* Unexpected handshake message (Client Hello, or protocol violation) */ + if ((s->d1->handshake_fragment_len >= DTLS1_HM_HEADER_LENGTH) && + !s->in_handshake) + { + struct hm_header_st msg_hdr; + + /* this may just be a stale retransmit */ + dtls1_get_message_header(rr->data, &msg_hdr); + if( rr->epoch != s->d1->r_epoch) + { + rr->length = 0; + goto start; + } + + /* If we are server, we may have a repeated FINISHED of the + * client here, then retransmit our CCS and FINISHED. + */ + if (msg_hdr.type == SSL3_MT_FINISHED) + { + dtls1_retransmit_buffered_messages(s); + rr->length = 0; + goto start; + } + + if (((s->state&SSL_ST_MASK) == SSL_ST_OK) && + !(s->s3->flags & SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS)) + { +#if 0 /* worked only because C operator preferences are not as expected (and + * because this is not really needed for clients except for detecting + * protocol violations): */ + s->state=SSL_ST_BEFORE|(s->server) + ?SSL_ST_ACCEPT + :SSL_ST_CONNECT; +#else + s->state = s->server ? SSL_ST_ACCEPT : SSL_ST_CONNECT; +#endif + s->new_session=1; + } + i=s->handshake_func(s); + if (i < 0) return(i); + if (i == 0) + { + SSLerr(SSL_F_DTLS1_READ_BYTES,SSL_R_SSL_HANDSHAKE_FAILURE); + return(-1); + } + + if (!(s->mode & SSL_MODE_AUTO_RETRY)) + { + if (s->s3->rbuf.left == 0) /* no read-ahead left? */ + { + BIO *bio; + /* In the case where we try to read application data, + * but we trigger an SSL handshake, we return -1 with + * the retry option set. Otherwise renegotiation may + * cause nasty problems in the blocking world */ + s->rwstate=SSL_READING; + bio=SSL_get_rbio(s); + BIO_clear_retry_flags(bio); + BIO_set_retry_read(bio); + return(-1); + } + } + goto start; + } + + switch (rr->type) + { + default: +#ifndef OPENSSL_NO_TLS + /* TLS just ignores unknown message types */ + if (s->version == TLS1_VERSION) + { + rr->length = 0; + goto start; + } +#endif + al=SSL_AD_UNEXPECTED_MESSAGE; + SSLerr(SSL_F_DTLS1_READ_BYTES,SSL_R_UNEXPECTED_RECORD); + goto f_err; + case SSL3_RT_CHANGE_CIPHER_SPEC: + case SSL3_RT_ALERT: + case SSL3_RT_HANDSHAKE: + /* we already handled all of these, with the possible exception + * of SSL3_RT_HANDSHAKE when s->in_handshake is set, but that + * should not happen when type != rr->type */ + al=SSL_AD_UNEXPECTED_MESSAGE; + SSLerr(SSL_F_DTLS1_READ_BYTES,ERR_R_INTERNAL_ERROR); + goto f_err; + case SSL3_RT_APPLICATION_DATA: + /* At this point, we were expecting handshake data, + * but have application data. If the library was + * running inside ssl3_read() (i.e. in_read_app_data + * is set) and it makes sense to read application data + * at this point (session renegotiation not yet started), + * we will indulge it. + */ + if (s->s3->in_read_app_data && + (s->s3->total_renegotiations != 0) && + (( + (s->state & SSL_ST_CONNECT) && + (s->state >= SSL3_ST_CW_CLNT_HELLO_A) && + (s->state <= SSL3_ST_CR_SRVR_HELLO_A) + ) || ( + (s->state & SSL_ST_ACCEPT) && + (s->state <= SSL3_ST_SW_HELLO_REQ_A) && + (s->state >= SSL3_ST_SR_CLNT_HELLO_A) + ) + )) + { + s->s3->in_read_app_data=2; + return(-1); + } + else + { + al=SSL_AD_UNEXPECTED_MESSAGE; + SSLerr(SSL_F_DTLS1_READ_BYTES,SSL_R_UNEXPECTED_RECORD); + goto f_err; + } + } + /* not reached */ + +f_err: + ssl3_send_alert(s,SSL3_AL_FATAL,al); +err: + return(-1); + } + +int +dtls1_write_app_data_bytes(SSL *s, int type, const void *buf_, int len) + { + int i; + + if (SSL_in_init(s) && !s->in_handshake) + { + i=s->handshake_func(s); + if (i < 0) return(i); + if (i == 0) + { + SSLerr(SSL_F_DTLS1_WRITE_APP_DATA_BYTES,SSL_R_SSL_HANDSHAKE_FAILURE); + return -1; + } + } + + if (len > SSL3_RT_MAX_PLAIN_LENGTH) + { + SSLerr(SSL_F_DTLS1_WRITE_APP_DATA_BYTES,SSL_R_DTLS_MESSAGE_TOO_BIG); + return -1; + } + + i = dtls1_write_bytes(s, type, buf_, len); + return i; + } + + + /* this only happens when a client hello is received and a handshake + * is started. */ +static int +have_handshake_fragment(SSL *s, int type, unsigned char *buf, + int len, int peek) + { + + if ((type == SSL3_RT_HANDSHAKE) && (s->d1->handshake_fragment_len > 0)) + /* (partially) satisfy request from storage */ + { + unsigned char *src = s->d1->handshake_fragment; + unsigned char *dst = buf; + unsigned int k,n; + + /* peek == 0 */ + n = 0; + while ((len > 0) && (s->d1->handshake_fragment_len > 0)) + { + *dst++ = *src++; + len--; s->d1->handshake_fragment_len--; + n++; + } + /* move any remaining fragment bytes: */ + for (k = 0; k < s->d1->handshake_fragment_len; k++) + s->d1->handshake_fragment[k] = *src++; + return n; + } + + return 0; + } + + + + +/* Call this to write data in records of type 'type' + * It will return <= 0 if not all data has been sent or non-blocking IO. + */ +int dtls1_write_bytes(SSL *s, int type, const void *buf, int len) + { + int i; + + OPENSSL_assert(len <= SSL3_RT_MAX_PLAIN_LENGTH); + s->rwstate=SSL_NOTHING; + i=do_dtls1_write(s, type, buf, len, 0); + return i; + } + +int do_dtls1_write(SSL *s, int type, const unsigned char *buf, unsigned int len, int create_empty_fragment) + { + unsigned char *p,*pseq; + int i,mac_size,clear=0; + int prefix_len = 0; + SSL3_RECORD *wr; + SSL3_BUFFER *wb; + SSL_SESSION *sess; + int bs; + unsigned int len_with_overhead = len + SSL3_RT_DEFAULT_WRITE_OVERHEAD; + + /* first check if there is a SSL3_BUFFER still being written + * out. This will happen with non blocking IO */ + if (s->s3->wbuf.left != 0) + { + OPENSSL_assert(0); /* XDTLS: want to see if we ever get here */ + return(ssl3_write_pending(s,type,buf,len)); + } + + if (s->s3->wbuf.len < len_with_overhead) + { + if ((p=OPENSSL_realloc(s->s3->wbuf.buf, len_with_overhead)) == NULL) { + SSLerr(SSL_F_DO_DTLS1_WRITE,ERR_R_MALLOC_FAILURE); + goto err; + } + s->s3->wbuf.buf = p; + s->s3->wbuf.len = len_with_overhead; + } + + /* If we have an alert to send, lets send it */ + if (s->s3->alert_dispatch) + { + i=s->method->ssl_dispatch_alert(s); + if (i <= 0) + return(i); + /* if it went, fall through and send more stuff */ + } + + if (len == 0 && !create_empty_fragment) + return 0; + + wr= &(s->s3->wrec); + wb= &(s->s3->wbuf); + sess=s->session; + + if ( (sess == NULL) || + (s->enc_write_ctx == NULL) || + (EVP_MD_CTX_md(s->write_hash) == NULL)) + clear=1; + + if (clear) + mac_size=0; + else + { + mac_size=EVP_MD_CTX_size(s->write_hash); + if (mac_size < 0) + goto err; + } + + /* DTLS implements explicit IV, so no need for empty fragments */ +#if 0 + /* 'create_empty_fragment' is true only when this function calls itself */ + if (!clear && !create_empty_fragment && !s->s3->empty_fragment_done + && SSL_version(s) != DTLS1_VERSION && SSL_version(s) != DTLS1_BAD_VER) + { + /* countermeasure against known-IV weakness in CBC ciphersuites + * (see http://www.openssl.org/~bodo/tls-cbc.txt) + */ + + if (s->s3->need_empty_fragments && type == SSL3_RT_APPLICATION_DATA) + { + /* recursive function call with 'create_empty_fragment' set; + * this prepares and buffers the data for an empty fragment + * (these 'prefix_len' bytes are sent out later + * together with the actual payload) */ + prefix_len = s->method->do_ssl_write(s, type, buf, 0, 1); + if (prefix_len <= 0) + goto err; + + if (s->s3->wbuf.len < (size_t)prefix_len + SSL3_RT_MAX_PACKET_SIZE) + { + /* insufficient space */ + SSLerr(SSL_F_DO_DTLS1_WRITE, ERR_R_INTERNAL_ERROR); + goto err; + } + } + + s->s3->empty_fragment_done = 1; + } +#endif + p = wb->buf + prefix_len; + + /* write the header */ + + *(p++)=type&0xff; + wr->type=type; + + *(p++)=(s->version>>8); + *(p++)=s->version&0xff; + + /* field where we are to write out packet epoch, seq num and len */ + pseq=p; + p+=10; + + /* lets setup the record stuff. */ + + /* Make space for the explicit IV in case of CBC. + * (this is a bit of a boundary violation, but what the heck). + */ + if ( s->enc_write_ctx && + (EVP_CIPHER_mode( s->enc_write_ctx->cipher ) & EVP_CIPH_CBC_MODE)) + bs = EVP_CIPHER_block_size(s->enc_write_ctx->cipher); + else + bs = 0; + + wr->data=p + bs; /* make room for IV in case of CBC */ + wr->length=(int)len; + wr->input=(unsigned char *)buf; + + /* we now 'read' from wr->input, wr->length bytes into + * wr->data */ + + /* first we compress */ + if (s->compress != NULL) + { + if (!ssl3_do_compress(s)) + { + SSLerr(SSL_F_DO_DTLS1_WRITE,SSL_R_COMPRESSION_FAILURE); + goto err; + } + } + else + { + memcpy(wr->data,wr->input,wr->length); + wr->input=wr->data; + } + + /* we should still have the output to wr->data and the input + * from wr->input. Length should be wr->length. + * wr->data still points in the wb->buf */ + + if (mac_size != 0) + { + if(s->method->ssl3_enc->mac(s,&(p[wr->length + bs]),1) < 0) + goto err; + wr->length+=mac_size; + } + + /* this is true regardless of mac size */ + wr->input=p; + wr->data=p; + + + /* ssl3_enc can only have an error on read */ + if (bs) /* bs != 0 in case of CBC */ + { + RAND_pseudo_bytes(p,bs); + /* master IV and last CBC residue stand for + * the rest of randomness */ + wr->length += bs; + } + + s->method->ssl3_enc->enc(s,1); + + /* record length after mac and block padding */ +/* if (type == SSL3_RT_APPLICATION_DATA || + (type == SSL3_RT_ALERT && ! SSL_in_init(s))) */ + + /* there's only one epoch between handshake and app data */ + + s2n(s->d1->w_epoch, pseq); + + /* XDTLS: ?? */ +/* else + s2n(s->d1->handshake_epoch, pseq); */ + + memcpy(pseq, &(s->s3->write_sequence[2]), 6); + pseq+=6; + s2n(wr->length,pseq); + + /* we should now have + * wr->data pointing to the encrypted data, which is + * wr->length long */ + wr->type=type; /* not needed but helps for debugging */ + wr->length+=DTLS1_RT_HEADER_LENGTH; + +#if 0 /* this is now done at the message layer */ + /* buffer the record, making it easy to handle retransmits */ + if ( type == SSL3_RT_HANDSHAKE || type == SSL3_RT_CHANGE_CIPHER_SPEC) + dtls1_buffer_record(s, wr->data, wr->length, + *((PQ_64BIT *)&(s->s3->write_sequence[0]))); +#endif + + ssl3_record_sequence_update(&(s->s3->write_sequence[0])); + + if (create_empty_fragment) + { + /* we are in a recursive call; + * just return the length, don't write out anything here + */ + return wr->length; + } + + /* now let's set up wb */ + wb->left = prefix_len + wr->length; + wb->offset = 0; + + /* memorize arguments so that ssl3_write_pending can detect bad write retries later */ + s->s3->wpend_tot=len; + s->s3->wpend_buf=buf; + s->s3->wpend_type=type; + s->s3->wpend_ret=len; + + /* we now just need to write the buffer */ + return ssl3_write_pending(s,type,buf,len); +err: + return -1; + } + + + +static int dtls1_record_replay_check(SSL *s, DTLS1_BITMAP *bitmap) + { + int cmp; + unsigned int shift; + const unsigned char *seq = s->s3->read_sequence; + + cmp = satsub64be(seq,bitmap->max_seq_num); + if (cmp > 0) + { + memcpy (s->s3->rrec.seq_num,seq,8); + return 1; /* this record in new */ + } + shift = -cmp; + if (shift >= sizeof(bitmap->map)*8) + return 0; /* stale, outside the window */ + else if (bitmap->map & (1UL<s3->rrec.seq_num,seq,8); + return 1; + } + + +static void dtls1_record_bitmap_update(SSL *s, DTLS1_BITMAP *bitmap) + { + int cmp; + unsigned int shift; + const unsigned char *seq = s->s3->read_sequence; + + cmp = satsub64be(seq,bitmap->max_seq_num); + if (cmp > 0) + { + shift = cmp; + if (shift < sizeof(bitmap->map)*8) + bitmap->map <<= shift, bitmap->map |= 1UL; + else + bitmap->map = 1UL; + memcpy(bitmap->max_seq_num,seq,8); + } + else { + shift = -cmp; + if (shift < sizeof(bitmap->map)*8) + bitmap->map |= 1UL<s3->alert_dispatch=0; + + memset(buf, 0x00, sizeof(buf)); + *ptr++ = s->s3->send_alert[0]; + *ptr++ = s->s3->send_alert[1]; + +#ifdef DTLS1_AD_MISSING_HANDSHAKE_MESSAGE + if (s->s3->send_alert[1] == DTLS1_AD_MISSING_HANDSHAKE_MESSAGE) + { + s2n(s->d1->handshake_read_seq, ptr); +#if 0 + if ( s->d1->r_msg_hdr.frag_off == 0) /* waiting for a new msg */ + + else + s2n(s->d1->r_msg_hdr.seq, ptr); /* partial msg read */ +#endif + +#if 0 + fprintf(stderr, "s->d1->handshake_read_seq = %d, s->d1->r_msg_hdr.seq = %d\n",s->d1->handshake_read_seq,s->d1->r_msg_hdr.seq); +#endif + l2n3(s->d1->r_msg_hdr.frag_off, ptr); + } +#endif + + i = do_dtls1_write(s, SSL3_RT_ALERT, &buf[0], sizeof(buf), 0); + if (i <= 0) + { + s->s3->alert_dispatch=1; + /* fprintf( stderr, "not done with alert\n" ); */ + } + else + { + if (s->s3->send_alert[0] == SSL3_AL_FATAL +#ifdef DTLS1_AD_MISSING_HANDSHAKE_MESSAGE + || s->s3->send_alert[1] == DTLS1_AD_MISSING_HANDSHAKE_MESSAGE +#endif + ) + (void)BIO_flush(s->wbio); + + if (s->msg_callback) + s->msg_callback(1, s->version, SSL3_RT_ALERT, s->s3->send_alert, + 2, s, s->msg_callback_arg); + + if (s->info_callback != NULL) + cb=s->info_callback; + else if (s->ctx->info_callback != NULL) + cb=s->ctx->info_callback; + + if (cb != NULL) + { + j=(s->s3->send_alert[0]<<8)|s->s3->send_alert[1]; + cb(s,SSL_CB_WRITE_ALERT,j); + } + } + return(i); + } + + +static DTLS1_BITMAP * +dtls1_get_bitmap(SSL *s, SSL3_RECORD *rr, unsigned int *is_next_epoch) + { + + *is_next_epoch = 0; + + /* In current epoch, accept HM, CCS, DATA, & ALERT */ + if (rr->epoch == s->d1->r_epoch) + return &s->d1->bitmap; + + /* Only HM and ALERT messages can be from the next epoch */ + else if (rr->epoch == (unsigned long)(s->d1->r_epoch + 1) && + (rr->type == SSL3_RT_HANDSHAKE || + rr->type == SSL3_RT_ALERT)) + { + *is_next_epoch = 1; + return &s->d1->next_bitmap; + } + + return NULL; + } + +#if 0 +static int +dtls1_record_needs_buffering(SSL *s, SSL3_RECORD *rr, unsigned short *priority, + unsigned long *offset) + { + + /* alerts are passed up immediately */ + if ( rr->type == SSL3_RT_APPLICATION_DATA || + rr->type == SSL3_RT_ALERT) + return 0; + + /* Only need to buffer if a handshake is underway. + * (this implies that Hello Request and Client Hello are passed up + * immediately) */ + if ( SSL_in_init(s)) + { + unsigned char *data = rr->data; + /* need to extract the HM/CCS sequence number here */ + if ( rr->type == SSL3_RT_HANDSHAKE || + rr->type == SSL3_RT_CHANGE_CIPHER_SPEC) + { + unsigned short seq_num; + struct hm_header_st msg_hdr; + struct ccs_header_st ccs_hdr; + + if ( rr->type == SSL3_RT_HANDSHAKE) + { + dtls1_get_message_header(data, &msg_hdr); + seq_num = msg_hdr.seq; + *offset = msg_hdr.frag_off; + } + else + { + dtls1_get_ccs_header(data, &ccs_hdr); + seq_num = ccs_hdr.seq; + *offset = 0; + } + + /* this is either a record we're waiting for, or a + * retransmit of something we happened to previously + * receive (higher layers will drop the repeat silently */ + if ( seq_num < s->d1->handshake_read_seq) + return 0; + if (rr->type == SSL3_RT_HANDSHAKE && + seq_num == s->d1->handshake_read_seq && + msg_hdr.frag_off < s->d1->r_msg_hdr.frag_off) + return 0; + else if ( seq_num == s->d1->handshake_read_seq && + (rr->type == SSL3_RT_CHANGE_CIPHER_SPEC || + msg_hdr.frag_off == s->d1->r_msg_hdr.frag_off)) + return 0; + else + { + *priority = seq_num; + return 1; + } + } + else /* unknown record type */ + return 0; + } + + return 0; + } +#endif + +void +dtls1_reset_seq_numbers(SSL *s, int rw) + { + unsigned char *seq; + unsigned int seq_bytes = sizeof(s->s3->read_sequence); + + if ( rw & SSL3_CC_READ) + { + seq = s->s3->read_sequence; + s->d1->r_epoch++; + memcpy(&(s->d1->bitmap), &(s->d1->next_bitmap), sizeof(DTLS1_BITMAP)); + memset(&(s->d1->next_bitmap), 0x00, sizeof(DTLS1_BITMAP)); + } + else + { + seq = s->s3->write_sequence; + memcpy(s->d1->last_write_sequence, seq, sizeof(s->s3->write_sequence)); + s->d1->w_epoch++; + } + + memset(seq, 0x00, seq_bytes); + } + + +static void +dtls1_clear_timeouts(SSL *s) + { + memset(&(s->d1->timeout), 0x00, sizeof(struct dtls1_timeout_st)); + } diff --git a/node-v0.8.14/deps/openssl/openssl/ssl/d1_srvr.c b/node-v0.8.14/deps/openssl/openssl/ssl/d1_srvr.c new file mode 100644 index 0000000..149983b --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/ssl/d1_srvr.c @@ -0,0 +1,1563 @@ +/* ssl/d1_srvr.c */ +/* + * DTLS implementation written by Nagendra Modadugu + * (nagendra@cs.stanford.edu) for the OpenSSL project 2005. + */ +/* ==================================================================== + * Copyright (c) 1999-2007 The OpenSSL Project. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. All advertising materials mentioning features or use of this + * software must display the following acknowledgment: + * "This product includes software developed by the OpenSSL Project + * for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)" + * + * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to + * endorse or promote products derived from this software without + * prior written permission. For written permission, please contact + * openssl-core@OpenSSL.org. + * + * 5. Products derived from this software may not be called "OpenSSL" + * nor may "OpenSSL" appear in their names without prior written + * permission of the OpenSSL Project. + * + * 6. Redistributions of any form whatsoever must retain the following + * acknowledgment: + * "This product includes software developed by the OpenSSL Project + * for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)" + * + * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY + * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR + * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, + * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * ==================================================================== + * + * This product includes cryptographic software written by Eric Young + * (eay@cryptsoft.com). This product includes software written by Tim + * Hudson (tjh@cryptsoft.com). + * + */ +/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com) + * All rights reserved. + * + * This package is an SSL implementation written + * by Eric Young (eay@cryptsoft.com). + * The implementation was written so as to conform with Netscapes SSL. + * + * This library is free for commercial and non-commercial use as long as + * the following conditions are aheared to. The following conditions + * apply to all code found in this distribution, be it the RC4, RSA, + * lhash, DES, etc., code; not just the SSL code. The SSL documentation + * included with this distribution is covered by the same copyright terms + * except that the holder is Tim Hudson (tjh@cryptsoft.com). + * + * Copyright remains Eric Young's, and as such any Copyright notices in + * the code are not to be removed. + * If this package is used in a product, Eric Young should be given attribution + * as the author of the parts of the library used. + * This can be in the form of a textual message at program startup or + * in documentation (online or textual) provided with the package. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * "This product includes cryptographic software written by + * Eric Young (eay@cryptsoft.com)" + * The word 'cryptographic' can be left out if the rouines from the library + * being used are not cryptographic related :-). + * 4. If you include any Windows specific code (or a derivative thereof) from + * the apps directory (application code) you must include an acknowledgement: + * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)" + * + * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * + * The licence and distribution terms for any publically available version or + * derivative of this code cannot be changed. i.e. this code cannot simply be + * copied and put under another distribution licence + * [including the GNU Public Licence.] + */ + +#include +#include "ssl_locl.h" +#include +#include +#include +#include +#include +#include +#include +#ifndef OPENSSL_NO_DH +#include +#endif + +static const SSL_METHOD *dtls1_get_server_method(int ver); +static int dtls1_send_hello_verify_request(SSL *s); + +static const SSL_METHOD *dtls1_get_server_method(int ver) + { + if (ver == DTLS1_VERSION) + return(DTLSv1_server_method()); + else + return(NULL); + } + +IMPLEMENT_dtls1_meth_func(DTLSv1_server_method, + dtls1_accept, + ssl_undefined_function, + dtls1_get_server_method) + +int dtls1_accept(SSL *s) + { + BUF_MEM *buf; + unsigned long Time=(unsigned long)time(NULL); + void (*cb)(const SSL *ssl,int type,int val)=NULL; + unsigned long alg_k; + int ret= -1; + int new_state,state,skip=0; + int listen; + + RAND_add(&Time,sizeof(Time),0); + ERR_clear_error(); + clear_sys_error(); + + if (s->info_callback != NULL) + cb=s->info_callback; + else if (s->ctx->info_callback != NULL) + cb=s->ctx->info_callback; + + listen = s->d1->listen; + + /* init things to blank */ + s->in_handshake++; + if (!SSL_in_init(s) || SSL_in_before(s)) SSL_clear(s); + + s->d1->listen = listen; + + if (s->cert == NULL) + { + SSLerr(SSL_F_DTLS1_ACCEPT,SSL_R_NO_CERTIFICATE_SET); + return(-1); + } + + for (;;) + { + state=s->state; + + switch (s->state) + { + case SSL_ST_RENEGOTIATE: + s->new_session=1; + /* s->state=SSL_ST_ACCEPT; */ + + case SSL_ST_BEFORE: + case SSL_ST_ACCEPT: + case SSL_ST_BEFORE|SSL_ST_ACCEPT: + case SSL_ST_OK|SSL_ST_ACCEPT: + + s->server=1; + if (cb != NULL) cb(s,SSL_CB_HANDSHAKE_START,1); + + if ((s->version & 0xff00) != (DTLS1_VERSION & 0xff00)) + { + SSLerr(SSL_F_DTLS1_ACCEPT, ERR_R_INTERNAL_ERROR); + return -1; + } + s->type=SSL_ST_ACCEPT; + + if (s->init_buf == NULL) + { + if ((buf=BUF_MEM_new()) == NULL) + { + ret= -1; + goto end; + } + if (!BUF_MEM_grow(buf,SSL3_RT_MAX_PLAIN_LENGTH)) + { + ret= -1; + goto end; + } + s->init_buf=buf; + } + + if (!ssl3_setup_buffers(s)) + { + ret= -1; + goto end; + } + + s->init_num=0; + + if (s->state != SSL_ST_RENEGOTIATE) + { + /* Ok, we now need to push on a buffering BIO so that + * the output is sent in a way that TCP likes :-) + */ + if (!ssl_init_wbio_buffer(s,1)) { ret= -1; goto end; } + + ssl3_init_finished_mac(s); + s->state=SSL3_ST_SR_CLNT_HELLO_A; + s->ctx->stats.sess_accept++; + } + else + { + /* s->state == SSL_ST_RENEGOTIATE, + * we will just send a HelloRequest */ + s->ctx->stats.sess_accept_renegotiate++; + s->state=SSL3_ST_SW_HELLO_REQ_A; + } + + break; + + case SSL3_ST_SW_HELLO_REQ_A: + case SSL3_ST_SW_HELLO_REQ_B: + + s->shutdown=0; + dtls1_start_timer(s); + ret=dtls1_send_hello_request(s); + if (ret <= 0) goto end; + s->s3->tmp.next_state=SSL3_ST_SW_HELLO_REQ_C; + s->state=SSL3_ST_SW_FLUSH; + s->init_num=0; + + ssl3_init_finished_mac(s); + break; + + case SSL3_ST_SW_HELLO_REQ_C: + s->state=SSL_ST_OK; + break; + + case SSL3_ST_SR_CLNT_HELLO_A: + case SSL3_ST_SR_CLNT_HELLO_B: + case SSL3_ST_SR_CLNT_HELLO_C: + + s->shutdown=0; + ret=ssl3_get_client_hello(s); + if (ret <= 0) goto end; + dtls1_stop_timer(s); + + if (ret == 1 && (SSL_get_options(s) & SSL_OP_COOKIE_EXCHANGE)) + s->state = DTLS1_ST_SW_HELLO_VERIFY_REQUEST_A; + else + s->state = SSL3_ST_SW_SRVR_HELLO_A; + + s->init_num=0; + + /* Reflect ClientHello sequence to remain stateless while listening */ + if (listen) + { + memcpy(s->s3->write_sequence, s->s3->read_sequence, sizeof(s->s3->write_sequence)); + } + + /* If we're just listening, stop here */ + if (listen && s->state == SSL3_ST_SW_SRVR_HELLO_A) + { + ret = 2; + s->d1->listen = 0; + /* Set expected sequence numbers + * to continue the handshake. + */ + s->d1->handshake_read_seq = 2; + s->d1->handshake_write_seq = 1; + s->d1->next_handshake_write_seq = 1; + goto end; + } + + break; + + case DTLS1_ST_SW_HELLO_VERIFY_REQUEST_A: + case DTLS1_ST_SW_HELLO_VERIFY_REQUEST_B: + + ret = dtls1_send_hello_verify_request(s); + if ( ret <= 0) goto end; + s->state=SSL3_ST_SW_FLUSH; + s->s3->tmp.next_state=SSL3_ST_SR_CLNT_HELLO_A; + + /* HelloVerifyRequest resets Finished MAC */ + if (s->version != DTLS1_BAD_VER) + ssl3_init_finished_mac(s); + break; + + case SSL3_ST_SW_SRVR_HELLO_A: + case SSL3_ST_SW_SRVR_HELLO_B: + s->new_session = 2; + dtls1_start_timer(s); + ret=dtls1_send_server_hello(s); + if (ret <= 0) goto end; + +#ifndef OPENSSL_NO_TLSEXT + if (s->hit) + { + if (s->tlsext_ticket_expected) + s->state=SSL3_ST_SW_SESSION_TICKET_A; + else + s->state=SSL3_ST_SW_CHANGE_A; + } +#else + if (s->hit) + s->state=SSL3_ST_SW_CHANGE_A; +#endif + else + s->state=SSL3_ST_SW_CERT_A; + s->init_num=0; + break; + + case SSL3_ST_SW_CERT_A: + case SSL3_ST_SW_CERT_B: + /* Check if it is anon DH or normal PSK */ + if (!(s->s3->tmp.new_cipher->algorithm_auth & SSL_aNULL) + && !(s->s3->tmp.new_cipher->algorithm_mkey & SSL_kPSK)) + { + dtls1_start_timer(s); + ret=dtls1_send_server_certificate(s); + if (ret <= 0) goto end; +#ifndef OPENSSL_NO_TLSEXT + if (s->tlsext_status_expected) + s->state=SSL3_ST_SW_CERT_STATUS_A; + else + s->state=SSL3_ST_SW_KEY_EXCH_A; + } + else + { + skip = 1; + s->state=SSL3_ST_SW_KEY_EXCH_A; + } +#else + } + else + skip=1; + + s->state=SSL3_ST_SW_KEY_EXCH_A; +#endif + s->init_num=0; + break; + + case SSL3_ST_SW_KEY_EXCH_A: + case SSL3_ST_SW_KEY_EXCH_B: + alg_k = s->s3->tmp.new_cipher->algorithm_mkey; + + /* clear this, it may get reset by + * send_server_key_exchange */ + if ((s->options & SSL_OP_EPHEMERAL_RSA) +#ifndef OPENSSL_NO_KRB5 + && !(alg_k & SSL_kKRB5) +#endif /* OPENSSL_NO_KRB5 */ + ) + /* option SSL_OP_EPHEMERAL_RSA sends temporary RSA key + * even when forbidden by protocol specs + * (handshake may fail as clients are not required to + * be able to handle this) */ + s->s3->tmp.use_rsa_tmp=1; + else + s->s3->tmp.use_rsa_tmp=0; + + /* only send if a DH key exchange or + * RSA but we have a sign only certificate */ + if (s->s3->tmp.use_rsa_tmp + /* PSK: send ServerKeyExchange if PSK identity + * hint if provided */ +#ifndef OPENSSL_NO_PSK + || ((alg_k & SSL_kPSK) && s->ctx->psk_identity_hint) +#endif + || (alg_k & (SSL_kEDH|SSL_kDHr|SSL_kDHd)) + || (alg_k & SSL_kEECDH) + || ((alg_k & SSL_kRSA) + && (s->cert->pkeys[SSL_PKEY_RSA_ENC].privatekey == NULL + || (SSL_C_IS_EXPORT(s->s3->tmp.new_cipher) + && EVP_PKEY_size(s->cert->pkeys[SSL_PKEY_RSA_ENC].privatekey)*8 > SSL_C_EXPORT_PKEYLENGTH(s->s3->tmp.new_cipher) + ) + ) + ) + ) + { + dtls1_start_timer(s); + ret=dtls1_send_server_key_exchange(s); + if (ret <= 0) goto end; + } + else + skip=1; + + s->state=SSL3_ST_SW_CERT_REQ_A; + s->init_num=0; + break; + + case SSL3_ST_SW_CERT_REQ_A: + case SSL3_ST_SW_CERT_REQ_B: + if (/* don't request cert unless asked for it: */ + !(s->verify_mode & SSL_VERIFY_PEER) || + /* if SSL_VERIFY_CLIENT_ONCE is set, + * don't request cert during re-negotiation: */ + ((s->session->peer != NULL) && + (s->verify_mode & SSL_VERIFY_CLIENT_ONCE)) || + /* never request cert in anonymous ciphersuites + * (see section "Certificate request" in SSL 3 drafts + * and in RFC 2246): */ + ((s->s3->tmp.new_cipher->algorithm_auth & SSL_aNULL) && + /* ... except when the application insists on verification + * (against the specs, but s3_clnt.c accepts this for SSL 3) */ + !(s->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT)) || + /* never request cert in Kerberos ciphersuites */ + (s->s3->tmp.new_cipher->algorithm_auth & SSL_aKRB5) + /* With normal PSK Certificates and + * Certificate Requests are omitted */ + || (s->s3->tmp.new_cipher->algorithm_mkey & SSL_kPSK)) + { + /* no cert request */ + skip=1; + s->s3->tmp.cert_request=0; + s->state=SSL3_ST_SW_SRVR_DONE_A; + } + else + { + s->s3->tmp.cert_request=1; + dtls1_start_timer(s); + ret=dtls1_send_certificate_request(s); + if (ret <= 0) goto end; +#ifndef NETSCAPE_HANG_BUG + s->state=SSL3_ST_SW_SRVR_DONE_A; +#else + s->state=SSL3_ST_SW_FLUSH; + s->s3->tmp.next_state=SSL3_ST_SR_CERT_A; +#endif + s->init_num=0; + } + break; + + case SSL3_ST_SW_SRVR_DONE_A: + case SSL3_ST_SW_SRVR_DONE_B: + dtls1_start_timer(s); + ret=dtls1_send_server_done(s); + if (ret <= 0) goto end; + s->s3->tmp.next_state=SSL3_ST_SR_CERT_A; + s->state=SSL3_ST_SW_FLUSH; + s->init_num=0; + break; + + case SSL3_ST_SW_FLUSH: + s->rwstate=SSL_WRITING; + if (BIO_flush(s->wbio) <= 0) + { + ret= -1; + goto end; + } + s->rwstate=SSL_NOTHING; + s->state=s->s3->tmp.next_state; + break; + + case SSL3_ST_SR_CERT_A: + case SSL3_ST_SR_CERT_B: + /* Check for second client hello (MS SGC) */ + ret = ssl3_check_client_hello(s); + if (ret <= 0) + goto end; + dtls1_stop_timer(s); + if (ret == 2) + s->state = SSL3_ST_SR_CLNT_HELLO_C; + else { + /* could be sent for a DH cert, even if we + * have not asked for it :-) */ + ret=ssl3_get_client_certificate(s); + if (ret <= 0) goto end; + dtls1_stop_timer(s); + s->init_num=0; + s->state=SSL3_ST_SR_KEY_EXCH_A; + } + break; + + case SSL3_ST_SR_KEY_EXCH_A: + case SSL3_ST_SR_KEY_EXCH_B: + ret=ssl3_get_client_key_exchange(s); + if (ret <= 0) goto end; + dtls1_stop_timer(s); + s->state=SSL3_ST_SR_CERT_VRFY_A; + s->init_num=0; + + if (ret == 2) + { + /* For the ECDH ciphersuites when + * the client sends its ECDH pub key in + * a certificate, the CertificateVerify + * message is not sent. + */ + s->state=SSL3_ST_SR_FINISHED_A; + s->init_num = 0; + } + else + { + s->state=SSL3_ST_SR_CERT_VRFY_A; + s->init_num=0; + + /* We need to get hashes here so if there is + * a client cert, it can be verified */ + s->method->ssl3_enc->cert_verify_mac(s, + NID_md5, + &(s->s3->tmp.cert_verify_md[0])); + s->method->ssl3_enc->cert_verify_mac(s, + NID_sha1, + &(s->s3->tmp.cert_verify_md[MD5_DIGEST_LENGTH])); + } + break; + + case SSL3_ST_SR_CERT_VRFY_A: + case SSL3_ST_SR_CERT_VRFY_B: + + s->d1->change_cipher_spec_ok = 1; + /* we should decide if we expected this one */ + ret=ssl3_get_cert_verify(s); + if (ret <= 0) goto end; + dtls1_stop_timer(s); + + s->state=SSL3_ST_SR_FINISHED_A; + s->init_num=0; + break; + + case SSL3_ST_SR_FINISHED_A: + case SSL3_ST_SR_FINISHED_B: + s->d1->change_cipher_spec_ok = 1; + ret=ssl3_get_finished(s,SSL3_ST_SR_FINISHED_A, + SSL3_ST_SR_FINISHED_B); + if (ret <= 0) goto end; + dtls1_stop_timer(s); + if (s->hit) + s->state=SSL_ST_OK; +#ifndef OPENSSL_NO_TLSEXT + else if (s->tlsext_ticket_expected) + s->state=SSL3_ST_SW_SESSION_TICKET_A; +#endif + else + s->state=SSL3_ST_SW_CHANGE_A; + s->init_num=0; + break; + +#ifndef OPENSSL_NO_TLSEXT + case SSL3_ST_SW_SESSION_TICKET_A: + case SSL3_ST_SW_SESSION_TICKET_B: + ret=dtls1_send_newsession_ticket(s); + if (ret <= 0) goto end; + s->state=SSL3_ST_SW_CHANGE_A; + s->init_num=0; + break; + + case SSL3_ST_SW_CERT_STATUS_A: + case SSL3_ST_SW_CERT_STATUS_B: + ret=ssl3_send_cert_status(s); + if (ret <= 0) goto end; + s->state=SSL3_ST_SW_KEY_EXCH_A; + s->init_num=0; + break; + +#endif + + case SSL3_ST_SW_CHANGE_A: + case SSL3_ST_SW_CHANGE_B: + + s->session->cipher=s->s3->tmp.new_cipher; + if (!s->method->ssl3_enc->setup_key_block(s)) + { ret= -1; goto end; } + + ret=dtls1_send_change_cipher_spec(s, + SSL3_ST_SW_CHANGE_A,SSL3_ST_SW_CHANGE_B); + + if (ret <= 0) goto end; + s->state=SSL3_ST_SW_FINISHED_A; + s->init_num=0; + + if (!s->method->ssl3_enc->change_cipher_state(s, + SSL3_CHANGE_CIPHER_SERVER_WRITE)) + { + ret= -1; + goto end; + } + + dtls1_reset_seq_numbers(s, SSL3_CC_WRITE); + break; + + case SSL3_ST_SW_FINISHED_A: + case SSL3_ST_SW_FINISHED_B: + ret=dtls1_send_finished(s, + SSL3_ST_SW_FINISHED_A,SSL3_ST_SW_FINISHED_B, + s->method->ssl3_enc->server_finished_label, + s->method->ssl3_enc->server_finished_label_len); + if (ret <= 0) goto end; + s->state=SSL3_ST_SW_FLUSH; + if (s->hit) + s->s3->tmp.next_state=SSL3_ST_SR_FINISHED_A; + else + s->s3->tmp.next_state=SSL_ST_OK; + s->init_num=0; + break; + + case SSL_ST_OK: + /* clean a few things up */ + ssl3_cleanup_key_block(s); + +#if 0 + BUF_MEM_free(s->init_buf); + s->init_buf=NULL; +#endif + + /* remove buffering on output */ + ssl_free_wbio_buffer(s); + + s->init_num=0; + + if (s->new_session == 2) /* skipped if we just sent a HelloRequest */ + { + /* actually not necessarily a 'new' session unless + * SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION is set */ + + s->new_session=0; + + ssl_update_cache(s,SSL_SESS_CACHE_SERVER); + + s->ctx->stats.sess_accept_good++; + /* s->server=1; */ + s->handshake_func=dtls1_accept; + + if (cb != NULL) cb(s,SSL_CB_HANDSHAKE_DONE,1); + } + + ret = 1; + + /* done handshaking, next message is client hello */ + s->d1->handshake_read_seq = 0; + /* next message is server hello */ + s->d1->handshake_write_seq = 0; + s->d1->next_handshake_write_seq = 0; + goto end; + /* break; */ + + default: + SSLerr(SSL_F_DTLS1_ACCEPT,SSL_R_UNKNOWN_STATE); + ret= -1; + goto end; + /* break; */ + } + + if (!s->s3->tmp.reuse_message && !skip) + { + if (s->debug) + { + if ((ret=BIO_flush(s->wbio)) <= 0) + goto end; + } + + + if ((cb != NULL) && (s->state != state)) + { + new_state=s->state; + s->state=state; + cb(s,SSL_CB_ACCEPT_LOOP,1); + s->state=new_state; + } + } + skip=0; + } +end: + /* BIO_flush(s->wbio); */ + + s->in_handshake--; + if (cb != NULL) + cb(s,SSL_CB_ACCEPT_EXIT,ret); + return(ret); + } + +int dtls1_send_hello_request(SSL *s) + { + unsigned char *p; + + if (s->state == SSL3_ST_SW_HELLO_REQ_A) + { + p=(unsigned char *)s->init_buf->data; + p = dtls1_set_message_header(s, p, SSL3_MT_HELLO_REQUEST, 0, 0, 0); + + s->state=SSL3_ST_SW_HELLO_REQ_B; + /* number of bytes to write */ + s->init_num=DTLS1_HM_HEADER_LENGTH; + s->init_off=0; + + /* no need to buffer this message, since there are no retransmit + * requests for it */ + } + + /* SSL3_ST_SW_HELLO_REQ_B */ + return(dtls1_do_write(s,SSL3_RT_HANDSHAKE)); + } + +int dtls1_send_hello_verify_request(SSL *s) + { + unsigned int msg_len; + unsigned char *msg, *buf, *p; + + if (s->state == DTLS1_ST_SW_HELLO_VERIFY_REQUEST_A) + { + buf = (unsigned char *)s->init_buf->data; + + msg = p = &(buf[DTLS1_HM_HEADER_LENGTH]); + *(p++) = s->version >> 8; + *(p++) = s->version & 0xFF; + + if (s->ctx->app_gen_cookie_cb == NULL || + s->ctx->app_gen_cookie_cb(s, s->d1->cookie, + &(s->d1->cookie_len)) == 0) + { + SSLerr(SSL_F_DTLS1_SEND_HELLO_VERIFY_REQUEST,ERR_R_INTERNAL_ERROR); + return 0; + } + + *(p++) = (unsigned char) s->d1->cookie_len; + memcpy(p, s->d1->cookie, s->d1->cookie_len); + p += s->d1->cookie_len; + msg_len = p - msg; + + dtls1_set_message_header(s, buf, + DTLS1_MT_HELLO_VERIFY_REQUEST, msg_len, 0, msg_len); + + s->state=DTLS1_ST_SW_HELLO_VERIFY_REQUEST_B; + /* number of bytes to write */ + s->init_num=p-buf; + s->init_off=0; + } + + /* s->state = DTLS1_ST_SW_HELLO_VERIFY_REQUEST_B */ + return(dtls1_do_write(s,SSL3_RT_HANDSHAKE)); + } + +int dtls1_send_server_hello(SSL *s) + { + unsigned char *buf; + unsigned char *p,*d; + int i; + unsigned int sl; + unsigned long l,Time; + + if (s->state == SSL3_ST_SW_SRVR_HELLO_A) + { + buf=(unsigned char *)s->init_buf->data; + p=s->s3->server_random; + Time=(unsigned long)time(NULL); /* Time */ + l2n(Time,p); + RAND_pseudo_bytes(p,SSL3_RANDOM_SIZE-sizeof(Time)); + /* Do the message type and length last */ + d=p= &(buf[DTLS1_HM_HEADER_LENGTH]); + + *(p++)=s->version>>8; + *(p++)=s->version&0xff; + + /* Random stuff */ + memcpy(p,s->s3->server_random,SSL3_RANDOM_SIZE); + p+=SSL3_RANDOM_SIZE; + + /* now in theory we have 3 options to sending back the + * session id. If it is a re-use, we send back the + * old session-id, if it is a new session, we send + * back the new session-id or we send back a 0 length + * session-id if we want it to be single use. + * Currently I will not implement the '0' length session-id + * 12-Jan-98 - I'll now support the '0' length stuff. + */ + if (!(s->ctx->session_cache_mode & SSL_SESS_CACHE_SERVER)) + s->session->session_id_length=0; + + sl=s->session->session_id_length; + if (sl > sizeof s->session->session_id) + { + SSLerr(SSL_F_DTLS1_SEND_SERVER_HELLO, ERR_R_INTERNAL_ERROR); + return -1; + } + *(p++)=sl; + memcpy(p,s->session->session_id,sl); + p+=sl; + + /* put the cipher */ + if (s->s3->tmp.new_cipher == NULL) + return -1; + i=ssl3_put_cipher_by_char(s->s3->tmp.new_cipher,p); + p+=i; + + /* put the compression method */ +#ifdef OPENSSL_NO_COMP + *(p++)=0; +#else + if (s->s3->tmp.new_compression == NULL) + *(p++)=0; + else + *(p++)=s->s3->tmp.new_compression->id; +#endif + +#ifndef OPENSSL_NO_TLSEXT + if ((p = ssl_add_serverhello_tlsext(s, p, buf+SSL3_RT_MAX_PLAIN_LENGTH)) == NULL) + { + SSLerr(SSL_F_DTLS1_SEND_SERVER_HELLO,ERR_R_INTERNAL_ERROR); + return -1; + } +#endif + + /* do the header */ + l=(p-d); + d=buf; + + d = dtls1_set_message_header(s, d, SSL3_MT_SERVER_HELLO, l, 0, l); + + s->state=SSL3_ST_SW_SRVR_HELLO_B; + /* number of bytes to write */ + s->init_num=p-buf; + s->init_off=0; + + /* buffer the message to handle re-xmits */ + dtls1_buffer_message(s, 0); + } + + /* SSL3_ST_SW_SRVR_HELLO_B */ + return(dtls1_do_write(s,SSL3_RT_HANDSHAKE)); + } + +int dtls1_send_server_done(SSL *s) + { + unsigned char *p; + + if (s->state == SSL3_ST_SW_SRVR_DONE_A) + { + p=(unsigned char *)s->init_buf->data; + + /* do the header */ + p = dtls1_set_message_header(s, p, SSL3_MT_SERVER_DONE, 0, 0, 0); + + s->state=SSL3_ST_SW_SRVR_DONE_B; + /* number of bytes to write */ + s->init_num=DTLS1_HM_HEADER_LENGTH; + s->init_off=0; + + /* buffer the message to handle re-xmits */ + dtls1_buffer_message(s, 0); + } + + /* SSL3_ST_SW_SRVR_DONE_B */ + return(dtls1_do_write(s,SSL3_RT_HANDSHAKE)); + } + +int dtls1_send_server_key_exchange(SSL *s) + { +#ifndef OPENSSL_NO_RSA + unsigned char *q; + int j,num; + RSA *rsa; + unsigned char md_buf[MD5_DIGEST_LENGTH+SHA_DIGEST_LENGTH]; + unsigned int u; +#endif +#ifndef OPENSSL_NO_DH + DH *dh=NULL,*dhp; +#endif +#ifndef OPENSSL_NO_ECDH + EC_KEY *ecdh=NULL, *ecdhp; + unsigned char *encodedPoint = NULL; + int encodedlen = 0; + int curve_id = 0; + BN_CTX *bn_ctx = NULL; +#endif + EVP_PKEY *pkey; + unsigned char *p,*d; + int al,i; + unsigned long type; + int n; + CERT *cert; + BIGNUM *r[4]; + int nr[4],kn; + BUF_MEM *buf; + EVP_MD_CTX md_ctx; + + EVP_MD_CTX_init(&md_ctx); + if (s->state == SSL3_ST_SW_KEY_EXCH_A) + { + type=s->s3->tmp.new_cipher->algorithm_mkey; + cert=s->cert; + + buf=s->init_buf; + + r[0]=r[1]=r[2]=r[3]=NULL; + n=0; +#ifndef OPENSSL_NO_RSA + if (type & SSL_kRSA) + { + rsa=cert->rsa_tmp; + if ((rsa == NULL) && (s->cert->rsa_tmp_cb != NULL)) + { + rsa=s->cert->rsa_tmp_cb(s, + SSL_C_IS_EXPORT(s->s3->tmp.new_cipher), + SSL_C_EXPORT_PKEYLENGTH(s->s3->tmp.new_cipher)); + if(rsa == NULL) + { + al=SSL_AD_HANDSHAKE_FAILURE; + SSLerr(SSL_F_DTLS1_SEND_SERVER_KEY_EXCHANGE,SSL_R_ERROR_GENERATING_TMP_RSA_KEY); + goto f_err; + } + RSA_up_ref(rsa); + cert->rsa_tmp=rsa; + } + if (rsa == NULL) + { + al=SSL_AD_HANDSHAKE_FAILURE; + SSLerr(SSL_F_DTLS1_SEND_SERVER_KEY_EXCHANGE,SSL_R_MISSING_TMP_RSA_KEY); + goto f_err; + } + r[0]=rsa->n; + r[1]=rsa->e; + s->s3->tmp.use_rsa_tmp=1; + } + else +#endif +#ifndef OPENSSL_NO_DH + if (type & SSL_kEDH) + { + dhp=cert->dh_tmp; + if ((dhp == NULL) && (s->cert->dh_tmp_cb != NULL)) + dhp=s->cert->dh_tmp_cb(s, + SSL_C_IS_EXPORT(s->s3->tmp.new_cipher), + SSL_C_EXPORT_PKEYLENGTH(s->s3->tmp.new_cipher)); + if (dhp == NULL) + { + al=SSL_AD_HANDSHAKE_FAILURE; + SSLerr(SSL_F_DTLS1_SEND_SERVER_KEY_EXCHANGE,SSL_R_MISSING_TMP_DH_KEY); + goto f_err; + } + + if (s->s3->tmp.dh != NULL) + { + DH_free(dh); + SSLerr(SSL_F_DTLS1_SEND_SERVER_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR); + goto err; + } + + if ((dh=DHparams_dup(dhp)) == NULL) + { + SSLerr(SSL_F_DTLS1_SEND_SERVER_KEY_EXCHANGE,ERR_R_DH_LIB); + goto err; + } + + s->s3->tmp.dh=dh; + if ((dhp->pub_key == NULL || + dhp->priv_key == NULL || + (s->options & SSL_OP_SINGLE_DH_USE))) + { + if(!DH_generate_key(dh)) + { + SSLerr(SSL_F_DTLS1_SEND_SERVER_KEY_EXCHANGE, + ERR_R_DH_LIB); + goto err; + } + } + else + { + dh->pub_key=BN_dup(dhp->pub_key); + dh->priv_key=BN_dup(dhp->priv_key); + if ((dh->pub_key == NULL) || + (dh->priv_key == NULL)) + { + SSLerr(SSL_F_DTLS1_SEND_SERVER_KEY_EXCHANGE,ERR_R_DH_LIB); + goto err; + } + } + r[0]=dh->p; + r[1]=dh->g; + r[2]=dh->pub_key; + } + else +#endif +#ifndef OPENSSL_NO_ECDH + if (type & SSL_kEECDH) + { + const EC_GROUP *group; + + ecdhp=cert->ecdh_tmp; + if ((ecdhp == NULL) && (s->cert->ecdh_tmp_cb != NULL)) + { + ecdhp=s->cert->ecdh_tmp_cb(s, + SSL_C_IS_EXPORT(s->s3->tmp.new_cipher), + SSL_C_EXPORT_PKEYLENGTH(s->s3->tmp.new_cipher)); + } + if (ecdhp == NULL) + { + al=SSL_AD_HANDSHAKE_FAILURE; + SSLerr(SSL_F_DTLS1_SEND_SERVER_KEY_EXCHANGE,SSL_R_MISSING_TMP_ECDH_KEY); + goto f_err; + } + + if (s->s3->tmp.ecdh != NULL) + { + EC_KEY_free(s->s3->tmp.ecdh); + SSLerr(SSL_F_DTLS1_SEND_SERVER_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR); + goto err; + } + + /* Duplicate the ECDH structure. */ + if (ecdhp == NULL) + { + SSLerr(SSL_F_DTLS1_SEND_SERVER_KEY_EXCHANGE,ERR_R_ECDH_LIB); + goto err; + } + if ((ecdh = EC_KEY_dup(ecdhp)) == NULL) + { + SSLerr(SSL_F_DTLS1_SEND_SERVER_KEY_EXCHANGE,ERR_R_ECDH_LIB); + goto err; + } + + s->s3->tmp.ecdh=ecdh; + if ((EC_KEY_get0_public_key(ecdh) == NULL) || + (EC_KEY_get0_private_key(ecdh) == NULL) || + (s->options & SSL_OP_SINGLE_ECDH_USE)) + { + if(!EC_KEY_generate_key(ecdh)) + { + SSLerr(SSL_F_DTLS1_SEND_SERVER_KEY_EXCHANGE,ERR_R_ECDH_LIB); + goto err; + } + } + + if (((group = EC_KEY_get0_group(ecdh)) == NULL) || + (EC_KEY_get0_public_key(ecdh) == NULL) || + (EC_KEY_get0_private_key(ecdh) == NULL)) + { + SSLerr(SSL_F_DTLS1_SEND_SERVER_KEY_EXCHANGE,ERR_R_ECDH_LIB); + goto err; + } + + if (SSL_C_IS_EXPORT(s->s3->tmp.new_cipher) && + (EC_GROUP_get_degree(group) > 163)) + { + SSLerr(SSL_F_DTLS1_SEND_SERVER_KEY_EXCHANGE,SSL_R_ECGROUP_TOO_LARGE_FOR_CIPHER); + goto err; + } + + /* XXX: For now, we only support ephemeral ECDH + * keys over named (not generic) curves. For + * supported named curves, curve_id is non-zero. + */ + if ((curve_id = + tls1_ec_nid2curve_id(EC_GROUP_get_curve_name(group))) + == 0) + { + SSLerr(SSL_F_DTLS1_SEND_SERVER_KEY_EXCHANGE,SSL_R_UNSUPPORTED_ELLIPTIC_CURVE); + goto err; + } + + /* Encode the public key. + * First check the size of encoding and + * allocate memory accordingly. + */ + encodedlen = EC_POINT_point2oct(group, + EC_KEY_get0_public_key(ecdh), + POINT_CONVERSION_UNCOMPRESSED, + NULL, 0, NULL); + + encodedPoint = (unsigned char *) + OPENSSL_malloc(encodedlen*sizeof(unsigned char)); + bn_ctx = BN_CTX_new(); + if ((encodedPoint == NULL) || (bn_ctx == NULL)) + { + SSLerr(SSL_F_DTLS1_SEND_SERVER_KEY_EXCHANGE,ERR_R_MALLOC_FAILURE); + goto err; + } + + + encodedlen = EC_POINT_point2oct(group, + EC_KEY_get0_public_key(ecdh), + POINT_CONVERSION_UNCOMPRESSED, + encodedPoint, encodedlen, bn_ctx); + + if (encodedlen == 0) + { + SSLerr(SSL_F_DTLS1_SEND_SERVER_KEY_EXCHANGE,ERR_R_ECDH_LIB); + goto err; + } + + BN_CTX_free(bn_ctx); bn_ctx=NULL; + + /* XXX: For now, we only support named (not + * generic) curves in ECDH ephemeral key exchanges. + * In this situation, we need four additional bytes + * to encode the entire ServerECDHParams + * structure. + */ + n = 4 + encodedlen; + + /* We'll generate the serverKeyExchange message + * explicitly so we can set these to NULLs + */ + r[0]=NULL; + r[1]=NULL; + r[2]=NULL; + r[3]=NULL; + } + else +#endif /* !OPENSSL_NO_ECDH */ +#ifndef OPENSSL_NO_PSK + if (type & SSL_kPSK) + { + /* reserve size for record length and PSK identity hint*/ + n+=2+strlen(s->ctx->psk_identity_hint); + } + else +#endif /* !OPENSSL_NO_PSK */ + { + al=SSL_AD_HANDSHAKE_FAILURE; + SSLerr(SSL_F_DTLS1_SEND_SERVER_KEY_EXCHANGE,SSL_R_UNKNOWN_KEY_EXCHANGE_TYPE); + goto f_err; + } + for (i=0; r[i] != NULL; i++) + { + nr[i]=BN_num_bytes(r[i]); + n+=2+nr[i]; + } + + if (!(s->s3->tmp.new_cipher->algorithm_auth & SSL_aNULL) + && !(s->s3->tmp.new_cipher->algorithm_mkey & SSL_kPSK)) + { + if ((pkey=ssl_get_sign_pkey(s,s->s3->tmp.new_cipher)) + == NULL) + { + al=SSL_AD_DECODE_ERROR; + goto f_err; + } + kn=EVP_PKEY_size(pkey); + } + else + { + pkey=NULL; + kn=0; + } + + if (!BUF_MEM_grow_clean(buf,n+DTLS1_HM_HEADER_LENGTH+kn)) + { + SSLerr(SSL_F_DTLS1_SEND_SERVER_KEY_EXCHANGE,ERR_LIB_BUF); + goto err; + } + d=(unsigned char *)s->init_buf->data; + p= &(d[DTLS1_HM_HEADER_LENGTH]); + + for (i=0; r[i] != NULL; i++) + { + s2n(nr[i],p); + BN_bn2bin(r[i],p); + p+=nr[i]; + } + +#ifndef OPENSSL_NO_ECDH + if (type & SSL_kEECDH) + { + /* XXX: For now, we only support named (not generic) curves. + * In this situation, the serverKeyExchange message has: + * [1 byte CurveType], [2 byte CurveName] + * [1 byte length of encoded point], followed by + * the actual encoded point itself + */ + *p = NAMED_CURVE_TYPE; + p += 1; + *p = 0; + p += 1; + *p = curve_id; + p += 1; + *p = encodedlen; + p += 1; + memcpy((unsigned char*)p, + (unsigned char *)encodedPoint, + encodedlen); + OPENSSL_free(encodedPoint); + p += encodedlen; + } +#endif + +#ifndef OPENSSL_NO_PSK + if (type & SSL_kPSK) + { + /* copy PSK identity hint */ + s2n(strlen(s->ctx->psk_identity_hint), p); + strncpy((char *)p, s->ctx->psk_identity_hint, strlen(s->ctx->psk_identity_hint)); + p+=strlen(s->ctx->psk_identity_hint); + } +#endif + + /* not anonymous */ + if (pkey != NULL) + { + /* n is the length of the params, they start at + * &(d[DTLS1_HM_HEADER_LENGTH]) and p points to the space + * at the end. */ +#ifndef OPENSSL_NO_RSA + if (pkey->type == EVP_PKEY_RSA) + { + q=md_buf; + j=0; + for (num=2; num > 0; num--) + { + EVP_DigestInit_ex(&md_ctx,(num == 2) + ?s->ctx->md5:s->ctx->sha1, NULL); + EVP_DigestUpdate(&md_ctx,&(s->s3->client_random[0]),SSL3_RANDOM_SIZE); + EVP_DigestUpdate(&md_ctx,&(s->s3->server_random[0]),SSL3_RANDOM_SIZE); + EVP_DigestUpdate(&md_ctx,&(d[DTLS1_HM_HEADER_LENGTH]),n); + EVP_DigestFinal_ex(&md_ctx,q, + (unsigned int *)&i); + q+=i; + j+=i; + } + if (RSA_sign(NID_md5_sha1, md_buf, j, + &(p[2]), &u, pkey->pkey.rsa) <= 0) + { + SSLerr(SSL_F_DTLS1_SEND_SERVER_KEY_EXCHANGE,ERR_LIB_RSA); + goto err; + } + s2n(u,p); + n+=u+2; + } + else +#endif +#if !defined(OPENSSL_NO_DSA) + if (pkey->type == EVP_PKEY_DSA) + { + /* lets do DSS */ + EVP_SignInit_ex(&md_ctx,EVP_dss1(), NULL); + EVP_SignUpdate(&md_ctx,&(s->s3->client_random[0]),SSL3_RANDOM_SIZE); + EVP_SignUpdate(&md_ctx,&(s->s3->server_random[0]),SSL3_RANDOM_SIZE); + EVP_SignUpdate(&md_ctx,&(d[DTLS1_HM_HEADER_LENGTH]),n); + if (!EVP_SignFinal(&md_ctx,&(p[2]), + (unsigned int *)&i,pkey)) + { + SSLerr(SSL_F_DTLS1_SEND_SERVER_KEY_EXCHANGE,ERR_LIB_DSA); + goto err; + } + s2n(i,p); + n+=i+2; + } + else +#endif +#if !defined(OPENSSL_NO_ECDSA) + if (pkey->type == EVP_PKEY_EC) + { + /* let's do ECDSA */ + EVP_SignInit_ex(&md_ctx,EVP_ecdsa(), NULL); + EVP_SignUpdate(&md_ctx,&(s->s3->client_random[0]),SSL3_RANDOM_SIZE); + EVP_SignUpdate(&md_ctx,&(s->s3->server_random[0]),SSL3_RANDOM_SIZE); + EVP_SignUpdate(&md_ctx,&(d[DTLS1_HM_HEADER_LENGTH]),n); + if (!EVP_SignFinal(&md_ctx,&(p[2]), + (unsigned int *)&i,pkey)) + { + SSLerr(SSL_F_DTLS1_SEND_SERVER_KEY_EXCHANGE,ERR_LIB_ECDSA); + goto err; + } + s2n(i,p); + n+=i+2; + } + else +#endif + { + /* Is this error check actually needed? */ + al=SSL_AD_HANDSHAKE_FAILURE; + SSLerr(SSL_F_DTLS1_SEND_SERVER_KEY_EXCHANGE,SSL_R_UNKNOWN_PKEY_TYPE); + goto f_err; + } + } + + d = dtls1_set_message_header(s, d, + SSL3_MT_SERVER_KEY_EXCHANGE, n, 0, n); + + /* we should now have things packed up, so lets send + * it off */ + s->init_num=n+DTLS1_HM_HEADER_LENGTH; + s->init_off=0; + + /* buffer the message to handle re-xmits */ + dtls1_buffer_message(s, 0); + } + + s->state = SSL3_ST_SW_KEY_EXCH_B; + EVP_MD_CTX_cleanup(&md_ctx); + return(dtls1_do_write(s,SSL3_RT_HANDSHAKE)); +f_err: + ssl3_send_alert(s,SSL3_AL_FATAL,al); +err: +#ifndef OPENSSL_NO_ECDH + if (encodedPoint != NULL) OPENSSL_free(encodedPoint); + BN_CTX_free(bn_ctx); +#endif + EVP_MD_CTX_cleanup(&md_ctx); + return(-1); + } + +int dtls1_send_certificate_request(SSL *s) + { + unsigned char *p,*d; + int i,j,nl,off,n; + STACK_OF(X509_NAME) *sk=NULL; + X509_NAME *name; + BUF_MEM *buf; + unsigned int msg_len; + + if (s->state == SSL3_ST_SW_CERT_REQ_A) + { + buf=s->init_buf; + + d=p=(unsigned char *)&(buf->data[DTLS1_HM_HEADER_LENGTH]); + + /* get the list of acceptable cert types */ + p++; + n=ssl3_get_req_cert_type(s,p); + d[0]=n; + p+=n; + n++; + + off=n; + p+=2; + n+=2; + + sk=SSL_get_client_CA_list(s); + nl=0; + if (sk != NULL) + { + for (i=0; idata[DTLS1_HM_HEADER_LENGTH+n]); + if (!(s->options & SSL_OP_NETSCAPE_CA_DN_BUG)) + { + s2n(j,p); + i2d_X509_NAME(name,&p); + n+=2+j; + nl+=2+j; + } + else + { + d=p; + i2d_X509_NAME(name,&p); + j-=2; s2n(j,d); j+=2; + n+=j; + nl+=j; + } + } + } + /* else no CA names */ + p=(unsigned char *)&(buf->data[DTLS1_HM_HEADER_LENGTH+off]); + s2n(nl,p); + + d=(unsigned char *)buf->data; + *(d++)=SSL3_MT_CERTIFICATE_REQUEST; + l2n3(n,d); + s2n(s->d1->handshake_write_seq,d); + s->d1->handshake_write_seq++; + + /* we should now have things packed up, so lets send + * it off */ + + s->init_num=n+DTLS1_HM_HEADER_LENGTH; + s->init_off=0; +#ifdef NETSCAPE_HANG_BUG +/* XXX: what to do about this? */ + p=(unsigned char *)s->init_buf->data + s->init_num; + + /* do the header */ + *(p++)=SSL3_MT_SERVER_DONE; + *(p++)=0; + *(p++)=0; + *(p++)=0; + s->init_num += 4; +#endif + + /* XDTLS: set message header ? */ + msg_len = s->init_num - DTLS1_HM_HEADER_LENGTH; + dtls1_set_message_header(s, (void *)s->init_buf->data, + SSL3_MT_CERTIFICATE_REQUEST, msg_len, 0, msg_len); + + /* buffer the message to handle re-xmits */ + dtls1_buffer_message(s, 0); + + s->state = SSL3_ST_SW_CERT_REQ_B; + } + + /* SSL3_ST_SW_CERT_REQ_B */ + return(dtls1_do_write(s,SSL3_RT_HANDSHAKE)); +err: + return(-1); + } + +int dtls1_send_server_certificate(SSL *s) + { + unsigned long l; + X509 *x; + + if (s->state == SSL3_ST_SW_CERT_A) + { + x=ssl_get_server_send_cert(s); + if (x == NULL) + { + /* VRS: allow null cert if auth == KRB5 */ + if ((s->s3->tmp.new_cipher->algorithm_mkey != SSL_kKRB5) || + (s->s3->tmp.new_cipher->algorithm_auth != SSL_aKRB5)) + { + SSLerr(SSL_F_DTLS1_SEND_SERVER_CERTIFICATE,ERR_R_INTERNAL_ERROR); + return(0); + } + } + + l=dtls1_output_cert_chain(s,x); + s->state=SSL3_ST_SW_CERT_B; + s->init_num=(int)l; + s->init_off=0; + + /* buffer the message to handle re-xmits */ + dtls1_buffer_message(s, 0); + } + + /* SSL3_ST_SW_CERT_B */ + return(dtls1_do_write(s,SSL3_RT_HANDSHAKE)); + } + +#ifndef OPENSSL_NO_TLSEXT +int dtls1_send_newsession_ticket(SSL *s) + { + if (s->state == SSL3_ST_SW_SESSION_TICKET_A) + { + unsigned char *p, *senc, *macstart; + int len, slen; + unsigned int hlen, msg_len; + EVP_CIPHER_CTX ctx; + HMAC_CTX hctx; + SSL_CTX *tctx = s->initial_ctx; + unsigned char iv[EVP_MAX_IV_LENGTH]; + unsigned char key_name[16]; + + /* get session encoding length */ + slen = i2d_SSL_SESSION(s->session, NULL); + /* Some length values are 16 bits, so forget it if session is + * too long + */ + if (slen > 0xFF00) + return -1; + /* Grow buffer if need be: the length calculation is as + * follows 12 (DTLS handshake message header) + + * 4 (ticket lifetime hint) + 2 (ticket length) + + * 16 (key name) + max_iv_len (iv length) + + * session_length + max_enc_block_size (max encrypted session + * length) + max_md_size (HMAC). + */ + if (!BUF_MEM_grow(s->init_buf, + DTLS1_HM_HEADER_LENGTH + 22 + EVP_MAX_IV_LENGTH + + EVP_MAX_BLOCK_LENGTH + EVP_MAX_MD_SIZE + slen)) + return -1; + senc = OPENSSL_malloc(slen); + if (!senc) + return -1; + p = senc; + i2d_SSL_SESSION(s->session, &p); + + p=(unsigned char *)&(s->init_buf->data[DTLS1_HM_HEADER_LENGTH]); + EVP_CIPHER_CTX_init(&ctx); + HMAC_CTX_init(&hctx); + /* Initialize HMAC and cipher contexts. If callback present + * it does all the work otherwise use generated values + * from parent ctx. + */ + if (tctx->tlsext_ticket_key_cb) + { + if (tctx->tlsext_ticket_key_cb(s, key_name, iv, &ctx, + &hctx, 1) < 0) + { + OPENSSL_free(senc); + return -1; + } + } + else + { + RAND_pseudo_bytes(iv, 16); + EVP_EncryptInit_ex(&ctx, EVP_aes_128_cbc(), NULL, + tctx->tlsext_tick_aes_key, iv); + HMAC_Init_ex(&hctx, tctx->tlsext_tick_hmac_key, 16, + tlsext_tick_md(), NULL); + memcpy(key_name, tctx->tlsext_tick_key_name, 16); + } + l2n(s->session->tlsext_tick_lifetime_hint, p); + /* Skip ticket length for now */ + p += 2; + /* Output key name */ + macstart = p; + memcpy(p, key_name, 16); + p += 16; + /* output IV */ + memcpy(p, iv, EVP_CIPHER_CTX_iv_length(&ctx)); + p += EVP_CIPHER_CTX_iv_length(&ctx); + /* Encrypt session data */ + EVP_EncryptUpdate(&ctx, p, &len, senc, slen); + p += len; + EVP_EncryptFinal(&ctx, p, &len); + p += len; + EVP_CIPHER_CTX_cleanup(&ctx); + + HMAC_Update(&hctx, macstart, p - macstart); + HMAC_Final(&hctx, p, &hlen); + HMAC_CTX_cleanup(&hctx); + + p += hlen; + /* Now write out lengths: p points to end of data written */ + /* Total length */ + len = p - (unsigned char *)(s->init_buf->data); + /* Ticket length */ + p=(unsigned char *)&(s->init_buf->data[DTLS1_HM_HEADER_LENGTH]) + 4; + s2n(len - DTLS1_HM_HEADER_LENGTH - 6, p); + + /* number of bytes to write */ + s->init_num= len; + s->state=SSL3_ST_SW_SESSION_TICKET_B; + s->init_off=0; + OPENSSL_free(senc); + + /* XDTLS: set message header ? */ + msg_len = s->init_num - DTLS1_HM_HEADER_LENGTH; + dtls1_set_message_header(s, (void *)s->init_buf->data, + SSL3_MT_NEWSESSION_TICKET, msg_len, 0, msg_len); + + /* buffer the message to handle re-xmits */ + dtls1_buffer_message(s, 0); + } + + /* SSL3_ST_SW_SESSION_TICKET_B */ + return(dtls1_do_write(s,SSL3_RT_HANDSHAKE)); + } +#endif diff --git a/node-v0.8.14/deps/openssl/openssl/ssl/dtls1.h b/node-v0.8.14/deps/openssl/openssl/ssl/dtls1.h new file mode 100644 index 0000000..2900d1d --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/ssl/dtls1.h @@ -0,0 +1,267 @@ +/* ssl/dtls1.h */ +/* + * DTLS implementation written by Nagendra Modadugu + * (nagendra@cs.stanford.edu) for the OpenSSL project 2005. + */ +/* ==================================================================== + * Copyright (c) 1999-2005 The OpenSSL Project. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. All advertising materials mentioning features or use of this + * software must display the following acknowledgment: + * "This product includes software developed by the OpenSSL Project + * for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)" + * + * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to + * endorse or promote products derived from this software without + * prior written permission. For written permission, please contact + * openssl-core@OpenSSL.org. + * + * 5. Products derived from this software may not be called "OpenSSL" + * nor may "OpenSSL" appear in their names without prior written + * permission of the OpenSSL Project. + * + * 6. Redistributions of any form whatsoever must retain the following + * acknowledgment: + * "This product includes software developed by the OpenSSL Project + * for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)" + * + * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY + * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR + * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, + * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * ==================================================================== + * + * This product includes cryptographic software written by Eric Young + * (eay@cryptsoft.com). This product includes software written by Tim + * Hudson (tjh@cryptsoft.com). + * + */ + +#ifndef HEADER_DTLS1_H +#define HEADER_DTLS1_H + +#include +#include +#ifdef OPENSSL_SYS_VMS +#include +#include +#endif +#ifdef OPENSSL_SYS_WIN32 +/* Needed for struct timeval */ +#include +#elif defined(OPENSSL_SYS_NETWARE) && !defined(_WINSOCK2API_) +#include +#else +#include +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +#define DTLS1_VERSION 0xFEFF +#define DTLS1_BAD_VER 0x0100 + +#if 0 +/* this alert description is not specified anywhere... */ +#define DTLS1_AD_MISSING_HANDSHAKE_MESSAGE 110 +#endif + +/* lengths of messages */ +#define DTLS1_COOKIE_LENGTH 256 + +#define DTLS1_RT_HEADER_LENGTH 13 + +#define DTLS1_HM_HEADER_LENGTH 12 + +#define DTLS1_HM_BAD_FRAGMENT -2 +#define DTLS1_HM_FRAGMENT_RETRY -3 + +#define DTLS1_CCS_HEADER_LENGTH 1 + +#ifdef DTLS1_AD_MISSING_HANDSHAKE_MESSAGE +#define DTLS1_AL_HEADER_LENGTH 7 +#else +#define DTLS1_AL_HEADER_LENGTH 2 +#endif + + +typedef struct dtls1_bitmap_st + { + unsigned long map; /* track 32 packets on 32-bit systems + and 64 - on 64-bit systems */ + unsigned char max_seq_num[8]; /* max record number seen so far, + 64-bit value in big-endian + encoding */ + } DTLS1_BITMAP; + +struct dtls1_retransmit_state + { + EVP_CIPHER_CTX *enc_write_ctx; /* cryptographic state */ + EVP_MD_CTX *write_hash; /* used for mac generation */ +#ifndef OPENSSL_NO_COMP + COMP_CTX *compress; /* compression */ +#else + char *compress; +#endif + SSL_SESSION *session; + unsigned short epoch; + }; + +struct hm_header_st + { + unsigned char type; + unsigned long msg_len; + unsigned short seq; + unsigned long frag_off; + unsigned long frag_len; + unsigned int is_ccs; + struct dtls1_retransmit_state saved_retransmit_state; + }; + +struct ccs_header_st + { + unsigned char type; + unsigned short seq; + }; + +struct dtls1_timeout_st + { + /* Number of read timeouts so far */ + unsigned int read_timeouts; + + /* Number of write timeouts so far */ + unsigned int write_timeouts; + + /* Number of alerts received so far */ + unsigned int num_alerts; + }; + +typedef struct record_pqueue_st + { + unsigned short epoch; + pqueue q; + } record_pqueue; + +typedef struct hm_fragment_st + { + struct hm_header_st msg_header; + unsigned char *fragment; + unsigned char *reassembly; + } hm_fragment; + +typedef struct dtls1_state_st + { + unsigned int send_cookie; + unsigned char cookie[DTLS1_COOKIE_LENGTH]; + unsigned char rcvd_cookie[DTLS1_COOKIE_LENGTH]; + unsigned int cookie_len; + + /* + * The current data and handshake epoch. This is initially + * undefined, and starts at zero once the initial handshake is + * completed + */ + unsigned short r_epoch; + unsigned short w_epoch; + + /* records being received in the current epoch */ + DTLS1_BITMAP bitmap; + + /* renegotiation starts a new set of sequence numbers */ + DTLS1_BITMAP next_bitmap; + + /* handshake message numbers */ + unsigned short handshake_write_seq; + unsigned short next_handshake_write_seq; + + unsigned short handshake_read_seq; + + /* save last sequence number for retransmissions */ + unsigned char last_write_sequence[8]; + + /* Received handshake records (processed and unprocessed) */ + record_pqueue unprocessed_rcds; + record_pqueue processed_rcds; + + /* Buffered handshake messages */ + pqueue buffered_messages; + + /* Buffered (sent) handshake records */ + pqueue sent_messages; + + /* Buffered application records. + * Only for records between CCS and Finished + * to prevent either protocol violation or + * unnecessary message loss. + */ + record_pqueue buffered_app_data; + + /* Is set when listening for new connections with dtls1_listen() */ + unsigned int listen; + + unsigned int mtu; /* max DTLS packet size */ + + struct hm_header_st w_msg_hdr; + struct hm_header_st r_msg_hdr; + + struct dtls1_timeout_st timeout; + + /* Indicates when the last handshake msg sent will timeout */ + struct timeval next_timeout; + + /* Timeout duration */ + unsigned short timeout_duration; + + /* storage for Alert/Handshake protocol data received but not + * yet processed by ssl3_read_bytes: */ + unsigned char alert_fragment[DTLS1_AL_HEADER_LENGTH]; + unsigned int alert_fragment_len; + unsigned char handshake_fragment[DTLS1_HM_HEADER_LENGTH]; + unsigned int handshake_fragment_len; + + unsigned int retransmitting; + unsigned int change_cipher_spec_ok; + + } DTLS1_STATE; + +typedef struct dtls1_record_data_st + { + unsigned char *packet; + unsigned int packet_length; + SSL3_BUFFER rbuf; + SSL3_RECORD rrec; + } DTLS1_RECORD_DATA; + + +/* Timeout multipliers (timeout slice is defined in apps/timeouts.h */ +#define DTLS1_TMO_READ_COUNT 2 +#define DTLS1_TMO_WRITE_COUNT 2 + +#define DTLS1_TMO_ALERT_COUNT 12 + +#ifdef __cplusplus +} +#endif +#endif + diff --git a/node-v0.8.14/deps/openssl/openssl/ssl/install-ssl.com b/node-v0.8.14/deps/openssl/openssl/ssl/install-ssl.com new file mode 100644 index 0000000..1bd6cca --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/ssl/install-ssl.com @@ -0,0 +1,136 @@ +$! INSTALL-SSL.COM -- Installs the files in a given directory tree +$! +$! Author: Richard Levitte +$! Time of creation: 22-MAY-1998 10:13 +$! +$! P1 root of the directory tree +$! P2 "64" for 64-bit pointers. +$! +$! +$! Announce/identify. +$! +$ proc = f$environment( "procedure") +$ write sys$output "@@@ "+ - + f$parse( proc, , , "name")+ f$parse( proc, , , "type") +$! +$ on error then goto tidy +$ on control_c then goto tidy +$! +$ if p1 .eqs. "" +$ then +$ write sys$output "First argument missing." +$ write sys$output - + "It should be the directory where you want things installed." +$ exit +$ endif +$! +$ if (f$getsyi( "cpu") .lt. 128) +$ then +$ arch = "VAX" +$ else +$ arch = f$edit( f$getsyi( "arch_name"), "upcase") +$ if (arch .eqs. "") then arch = "UNK" +$ endif +$! +$ archd = arch +$ lib32 = "32" +$ shr = "_SHR32" +$! +$ if (p2 .nes. "") +$ then +$ if (p2 .eqs. "64") +$ then +$ archd = arch+ "_64" +$ lib32 = "" +$ shr = "_SHR" +$ else +$ if (p2 .nes. "32") +$ then +$ write sys$output "Second argument invalid." +$ write sys$output "It should be "32", "64", or nothing." +$ exit +$ endif +$ endif +$ endif +$! +$ root = f$parse( p1, "[]A.;0", , , "syntax_only, no_conceal") - "A.;0" +$ root_dev = f$parse(root,,,"device","syntax_only") +$ root_dir = f$parse(root,,,"directory","syntax_only") - - + "[000000." - "][" - "[" - "]" +$ root = root_dev + "[" + root_dir +$! +$ define /nolog wrk_sslroot 'root'.] /trans=conc +$ define /nolog wrk_sslinclude wrk_sslroot:[include] +$ define /nolog wrk_sslxexe wrk_sslroot:['archd'_exe] +$ define /nolog wrk_sslxlib wrk_sslroot:['arch'_lib] +$! +$ if f$parse("wrk_sslroot:[000000]") .eqs. "" then - + create /directory /log wrk_sslroot:[000000] +$ if f$parse("wrk_sslinclude:") .eqs. "" then - + create /directory /log wrk_sslinclude: +$ if f$parse("wrk_sslxexe:") .eqs. "" then - + create /directory /log wrk_sslxexe: +$ if f$parse("wrk_sslxlib:") .eqs. "" then - + create /directory /log wrk_sslxlib: +$! +$ exheader := ssl.h, ssl2.h, ssl3.h, ssl23.h, tls1.h, dtls1.h, kssl.h +$ e_exe := ssl_task +$ libs := ssl_libssl +$! +$ xexe_dir := [-.'archd'.exe.ssl] +$! +$ copy /protection = w:re 'exheader' wrk_sslinclude: /log +$! +$ i = 0 +$ loop_exe: +$ e = f$edit( f$element( i, ",", e_exe), "trim") +$ i = i + 1 +$ if e .eqs. "," then goto loop_exe_end +$ set noon +$ file = xexe_dir+ e+ ".exe" +$ if f$search( file) .nes. "" +$ then +$ copy /protection = w:re 'file' wrk_sslxexe: /log +$ endif +$ set on +$ goto loop_exe +$ loop_exe_end: +$! +$ i = 0 +$ loop_lib: +$ e = f$edit(f$element(i, ",", libs),"trim") +$ i = i + 1 +$ if e .eqs. "," then goto loop_lib_end +$ set noon +$! Object library. +$ file = xexe_dir+ e+ lib32+ ".olb" +$ if f$search( file) .nes. "" +$ then +$ copy /protection = w:re 'file' wrk_sslxlib: /log +$ endif +$! Shareable image. +$ file = xexe_dir+ e+ shr+ ".exe" +$ if f$search( file) .nes. "" +$ then +$ copy /protection = w:re 'file' wrk_sslxlib: /log +$ endif +$ set on +$ goto loop_lib +$ loop_lib_end: +$! +$ tidy: +$! +$ call deass wrk_sslroot +$ call deass wrk_sslinclude +$ call deass wrk_sslxexe +$ call deass wrk_sslxlib +$! +$ exit +$! +$ deass: subroutine +$ if (f$trnlnm( p1, "LNM$PROCESS") .nes. "") +$ then +$ deassign /process 'p1' +$ endif +$ endsubroutine +$! diff --git a/node-v0.8.14/deps/openssl/openssl/ssl/kssl.c b/node-v0.8.14/deps/openssl/openssl/ssl/kssl.c new file mode 100644 index 0000000..b820e37 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/ssl/kssl.c @@ -0,0 +1,2205 @@ +/* ssl/kssl.c -*- mode: C; c-file-style: "eay" -*- */ +/* Written by Vern Staats for the OpenSSL project 2000. + */ +/* ==================================================================== + * Copyright (c) 2000 The OpenSSL Project. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. All advertising materials mentioning features or use of this + * software must display the following acknowledgment: + * "This product includes software developed by the OpenSSL Project + * for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)" + * + * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to + * endorse or promote products derived from this software without + * prior written permission. For written permission, please contact + * licensing@OpenSSL.org. + * + * 5. Products derived from this software may not be called "OpenSSL" + * nor may "OpenSSL" appear in their names without prior written + * permission of the OpenSSL Project. + * + * 6. Redistributions of any form whatsoever must retain the following + * acknowledgment: + * "This product includes software developed by the OpenSSL Project + * for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)" + * + * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY + * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR + * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, + * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * ==================================================================== + * + * This product includes cryptographic software written by Eric Young + * (eay@cryptsoft.com). This product includes software written by Tim + * Hudson (tjh@cryptsoft.com). + * + */ + + +/* ssl/kssl.c -- Routines to support (& debug) Kerberos5 auth for openssl +** +** 19990701 VRS Started. +** 200011?? Jeffrey Altman, Richard Levitte +** Generalized for Heimdal, Newer MIT, & Win32. +** Integrated into main OpenSSL 0.9.7 snapshots. +** 20010413 Simon Wilkinson, VRS +** Real RFC2712 KerberosWrapper replaces AP_REQ. +*/ + +#include + +#include + +#define KRB5_PRIVATE 1 + +#include +#include +#include +#include +#include "kssl_lcl.h" + +#ifndef OPENSSL_NO_KRB5 + +#ifndef ENOMEM +#define ENOMEM KRB5KRB_ERR_GENERIC +#endif + +/* + * When OpenSSL is built on Windows, we do not want to require that + * the Kerberos DLLs be available in order for the OpenSSL DLLs to + * work. Therefore, all Kerberos routines are loaded at run time + * and we do not link to a .LIB file. + */ + +#if defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_WIN32) +/* + * The purpose of the following pre-processor statements is to provide + * compatibility with different releases of MIT Kerberos for Windows. + * All versions up to 1.2 used macros. But macros do not allow for + * a binary compatible interface for DLLs. Therefore, all macros are + * being replaced by function calls. The following code will allow + * an OpenSSL DLL built on Windows to work whether or not the macro + * or function form of the routines are utilized. + */ +#ifdef krb5_cc_get_principal +#define NO_DEF_KRB5_CCACHE +#undef krb5_cc_get_principal +#endif +#define krb5_cc_get_principal kssl_krb5_cc_get_principal + +#define krb5_free_data_contents kssl_krb5_free_data_contents +#define krb5_free_context kssl_krb5_free_context +#define krb5_auth_con_free kssl_krb5_auth_con_free +#define krb5_free_principal kssl_krb5_free_principal +#define krb5_mk_req_extended kssl_krb5_mk_req_extended +#define krb5_get_credentials kssl_krb5_get_credentials +#define krb5_cc_default kssl_krb5_cc_default +#define krb5_sname_to_principal kssl_krb5_sname_to_principal +#define krb5_init_context kssl_krb5_init_context +#define krb5_free_ticket kssl_krb5_free_ticket +#define krb5_rd_req kssl_krb5_rd_req +#define krb5_kt_default kssl_krb5_kt_default +#define krb5_kt_resolve kssl_krb5_kt_resolve +/* macros in mit 1.2.2 and earlier; functions in mit 1.2.3 and greater */ +#ifndef krb5_kt_close +#define krb5_kt_close kssl_krb5_kt_close +#endif /* krb5_kt_close */ +#ifndef krb5_kt_get_entry +#define krb5_kt_get_entry kssl_krb5_kt_get_entry +#endif /* krb5_kt_get_entry */ +#define krb5_auth_con_init kssl_krb5_auth_con_init + +#define krb5_principal_compare kssl_krb5_principal_compare +#define krb5_decrypt_tkt_part kssl_krb5_decrypt_tkt_part +#define krb5_timeofday kssl_krb5_timeofday +#define krb5_rc_default kssl_krb5_rc_default + +#ifdef krb5_rc_initialize +#undef krb5_rc_initialize +#endif +#define krb5_rc_initialize kssl_krb5_rc_initialize + +#ifdef krb5_rc_get_lifespan +#undef krb5_rc_get_lifespan +#endif +#define krb5_rc_get_lifespan kssl_krb5_rc_get_lifespan + +#ifdef krb5_rc_destroy +#undef krb5_rc_destroy +#endif +#define krb5_rc_destroy kssl_krb5_rc_destroy + +#define valid_cksumtype kssl_valid_cksumtype +#define krb5_checksum_size kssl_krb5_checksum_size +#define krb5_kt_free_entry kssl_krb5_kt_free_entry +#define krb5_auth_con_setrcache kssl_krb5_auth_con_setrcache +#define krb5_auth_con_getrcache kssl_krb5_auth_con_getrcache +#define krb5_get_server_rcache kssl_krb5_get_server_rcache + +/* Prototypes for built in stubs */ +void kssl_krb5_free_data_contents(krb5_context, krb5_data *); +void kssl_krb5_free_principal(krb5_context, krb5_principal ); +krb5_error_code kssl_krb5_kt_resolve(krb5_context, + krb5_const char *, + krb5_keytab *); +krb5_error_code kssl_krb5_kt_default(krb5_context, + krb5_keytab *); +krb5_error_code kssl_krb5_free_ticket(krb5_context, krb5_ticket *); +krb5_error_code kssl_krb5_rd_req(krb5_context, krb5_auth_context *, + krb5_const krb5_data *, + krb5_const_principal, krb5_keytab, + krb5_flags *,krb5_ticket **); + +krb5_boolean kssl_krb5_principal_compare(krb5_context, krb5_const_principal, + krb5_const_principal); +krb5_error_code kssl_krb5_mk_req_extended(krb5_context, + krb5_auth_context *, + krb5_const krb5_flags, + krb5_data *, + krb5_creds *, + krb5_data * ); +krb5_error_code kssl_krb5_init_context(krb5_context *); +void kssl_krb5_free_context(krb5_context); +krb5_error_code kssl_krb5_cc_default(krb5_context,krb5_ccache *); +krb5_error_code kssl_krb5_sname_to_principal(krb5_context, + krb5_const char *, + krb5_const char *, + krb5_int32, + krb5_principal *); +krb5_error_code kssl_krb5_get_credentials(krb5_context, + krb5_const krb5_flags, + krb5_ccache, + krb5_creds *, + krb5_creds * *); +krb5_error_code kssl_krb5_auth_con_init(krb5_context, + krb5_auth_context *); +krb5_error_code kssl_krb5_cc_get_principal(krb5_context context, + krb5_ccache cache, + krb5_principal *principal); +krb5_error_code kssl_krb5_auth_con_free(krb5_context,krb5_auth_context); +size_t kssl_krb5_checksum_size(krb5_context context,krb5_cksumtype ctype); +krb5_boolean kssl_valid_cksumtype(krb5_cksumtype ctype); +krb5_error_code krb5_kt_free_entry(krb5_context,krb5_keytab_entry FAR * ); +krb5_error_code kssl_krb5_auth_con_setrcache(krb5_context, + krb5_auth_context, + krb5_rcache); +krb5_error_code kssl_krb5_get_server_rcache(krb5_context, + krb5_const krb5_data *, + krb5_rcache *); +krb5_error_code kssl_krb5_auth_con_getrcache(krb5_context, + krb5_auth_context, + krb5_rcache *); + +/* Function pointers (almost all Kerberos functions are _stdcall) */ +static void (_stdcall *p_krb5_free_data_contents)(krb5_context, krb5_data *) + =NULL; +static void (_stdcall *p_krb5_free_principal)(krb5_context, krb5_principal ) + =NULL; +static krb5_error_code(_stdcall *p_krb5_kt_resolve) + (krb5_context, krb5_const char *, krb5_keytab *)=NULL; +static krb5_error_code (_stdcall *p_krb5_kt_default)(krb5_context, + krb5_keytab *)=NULL; +static krb5_error_code (_stdcall *p_krb5_free_ticket)(krb5_context, + krb5_ticket *)=NULL; +static krb5_error_code (_stdcall *p_krb5_rd_req)(krb5_context, + krb5_auth_context *, + krb5_const krb5_data *, + krb5_const_principal, + krb5_keytab, krb5_flags *, + krb5_ticket **)=NULL; +static krb5_error_code (_stdcall *p_krb5_mk_req_extended) + (krb5_context, krb5_auth_context *, + krb5_const krb5_flags, krb5_data *, krb5_creds *, + krb5_data * )=NULL; +static krb5_error_code (_stdcall *p_krb5_init_context)(krb5_context *)=NULL; +static void (_stdcall *p_krb5_free_context)(krb5_context)=NULL; +static krb5_error_code (_stdcall *p_krb5_cc_default)(krb5_context, + krb5_ccache *)=NULL; +static krb5_error_code (_stdcall *p_krb5_sname_to_principal) + (krb5_context, krb5_const char *, krb5_const char *, + krb5_int32, krb5_principal *)=NULL; +static krb5_error_code (_stdcall *p_krb5_get_credentials) + (krb5_context, krb5_const krb5_flags, krb5_ccache, + krb5_creds *, krb5_creds **)=NULL; +static krb5_error_code (_stdcall *p_krb5_auth_con_init) + (krb5_context, krb5_auth_context *)=NULL; +static krb5_error_code (_stdcall *p_krb5_cc_get_principal) + (krb5_context context, krb5_ccache cache, + krb5_principal *principal)=NULL; +static krb5_error_code (_stdcall *p_krb5_auth_con_free) + (krb5_context, krb5_auth_context)=NULL; +static krb5_error_code (_stdcall *p_krb5_decrypt_tkt_part) + (krb5_context, krb5_const krb5_keyblock *, + krb5_ticket *)=NULL; +static krb5_error_code (_stdcall *p_krb5_timeofday) + (krb5_context context, krb5_int32 *timeret)=NULL; +static krb5_error_code (_stdcall *p_krb5_rc_default) + (krb5_context context, krb5_rcache *rc)=NULL; +static krb5_error_code (_stdcall *p_krb5_rc_initialize) + (krb5_context context, krb5_rcache rc, + krb5_deltat lifespan)=NULL; +static krb5_error_code (_stdcall *p_krb5_rc_get_lifespan) + (krb5_context context, krb5_rcache rc, + krb5_deltat *lifespan)=NULL; +static krb5_error_code (_stdcall *p_krb5_rc_destroy) + (krb5_context context, krb5_rcache rc)=NULL; +static krb5_boolean (_stdcall *p_krb5_principal_compare) + (krb5_context, krb5_const_principal, krb5_const_principal)=NULL; +static size_t (_stdcall *p_krb5_checksum_size)(krb5_context context,krb5_cksumtype ctype)=NULL; +static krb5_boolean (_stdcall *p_valid_cksumtype)(krb5_cksumtype ctype)=NULL; +static krb5_error_code (_stdcall *p_krb5_kt_free_entry) + (krb5_context,krb5_keytab_entry * )=NULL; +static krb5_error_code (_stdcall * p_krb5_auth_con_setrcache)(krb5_context, + krb5_auth_context, + krb5_rcache)=NULL; +static krb5_error_code (_stdcall * p_krb5_get_server_rcache)(krb5_context, + krb5_const krb5_data *, + krb5_rcache *)=NULL; +static krb5_error_code (* p_krb5_auth_con_getrcache)(krb5_context, + krb5_auth_context, + krb5_rcache *)=NULL; +static krb5_error_code (_stdcall * p_krb5_kt_close)(krb5_context context, + krb5_keytab keytab)=NULL; +static krb5_error_code (_stdcall * p_krb5_kt_get_entry)(krb5_context context, + krb5_keytab keytab, + krb5_const_principal principal, krb5_kvno vno, + krb5_enctype enctype, krb5_keytab_entry *entry)=NULL; +static int krb5_loaded = 0; /* only attempt to initialize func ptrs once */ + +/* Function to Load the Kerberos 5 DLL and initialize function pointers */ +void +load_krb5_dll(void) + { + HANDLE hKRB5_32; + + krb5_loaded++; + hKRB5_32 = LoadLibrary(TEXT("KRB5_32")); + if (!hKRB5_32) + return; + + (FARPROC) p_krb5_free_data_contents = + GetProcAddress( hKRB5_32, "krb5_free_data_contents" ); + (FARPROC) p_krb5_free_context = + GetProcAddress( hKRB5_32, "krb5_free_context" ); + (FARPROC) p_krb5_auth_con_free = + GetProcAddress( hKRB5_32, "krb5_auth_con_free" ); + (FARPROC) p_krb5_free_principal = + GetProcAddress( hKRB5_32, "krb5_free_principal" ); + (FARPROC) p_krb5_mk_req_extended = + GetProcAddress( hKRB5_32, "krb5_mk_req_extended" ); + (FARPROC) p_krb5_get_credentials = + GetProcAddress( hKRB5_32, "krb5_get_credentials" ); + (FARPROC) p_krb5_cc_get_principal = + GetProcAddress( hKRB5_32, "krb5_cc_get_principal" ); + (FARPROC) p_krb5_cc_default = + GetProcAddress( hKRB5_32, "krb5_cc_default" ); + (FARPROC) p_krb5_sname_to_principal = + GetProcAddress( hKRB5_32, "krb5_sname_to_principal" ); + (FARPROC) p_krb5_init_context = + GetProcAddress( hKRB5_32, "krb5_init_context" ); + (FARPROC) p_krb5_free_ticket = + GetProcAddress( hKRB5_32, "krb5_free_ticket" ); + (FARPROC) p_krb5_rd_req = + GetProcAddress( hKRB5_32, "krb5_rd_req" ); + (FARPROC) p_krb5_principal_compare = + GetProcAddress( hKRB5_32, "krb5_principal_compare" ); + (FARPROC) p_krb5_decrypt_tkt_part = + GetProcAddress( hKRB5_32, "krb5_decrypt_tkt_part" ); + (FARPROC) p_krb5_timeofday = + GetProcAddress( hKRB5_32, "krb5_timeofday" ); + (FARPROC) p_krb5_rc_default = + GetProcAddress( hKRB5_32, "krb5_rc_default" ); + (FARPROC) p_krb5_rc_initialize = + GetProcAddress( hKRB5_32, "krb5_rc_initialize" ); + (FARPROC) p_krb5_rc_get_lifespan = + GetProcAddress( hKRB5_32, "krb5_rc_get_lifespan" ); + (FARPROC) p_krb5_rc_destroy = + GetProcAddress( hKRB5_32, "krb5_rc_destroy" ); + (FARPROC) p_krb5_kt_default = + GetProcAddress( hKRB5_32, "krb5_kt_default" ); + (FARPROC) p_krb5_kt_resolve = + GetProcAddress( hKRB5_32, "krb5_kt_resolve" ); + (FARPROC) p_krb5_auth_con_init = + GetProcAddress( hKRB5_32, "krb5_auth_con_init" ); + (FARPROC) p_valid_cksumtype = + GetProcAddress( hKRB5_32, "valid_cksumtype" ); + (FARPROC) p_krb5_checksum_size = + GetProcAddress( hKRB5_32, "krb5_checksum_size" ); + (FARPROC) p_krb5_kt_free_entry = + GetProcAddress( hKRB5_32, "krb5_kt_free_entry" ); + (FARPROC) p_krb5_auth_con_setrcache = + GetProcAddress( hKRB5_32, "krb5_auth_con_setrcache" ); + (FARPROC) p_krb5_get_server_rcache = + GetProcAddress( hKRB5_32, "krb5_get_server_rcache" ); + (FARPROC) p_krb5_auth_con_getrcache = + GetProcAddress( hKRB5_32, "krb5_auth_con_getrcache" ); + (FARPROC) p_krb5_kt_close = + GetProcAddress( hKRB5_32, "krb5_kt_close" ); + (FARPROC) p_krb5_kt_get_entry = + GetProcAddress( hKRB5_32, "krb5_kt_get_entry" ); + } + +/* Stubs for each function to be dynamicly loaded */ +void +kssl_krb5_free_data_contents(krb5_context CO, krb5_data * data) + { + if (!krb5_loaded) + load_krb5_dll(); + + if ( p_krb5_free_data_contents ) + p_krb5_free_data_contents(CO,data); + } + +krb5_error_code +kssl_krb5_mk_req_extended (krb5_context CO, + krb5_auth_context * pACO, + krb5_const krb5_flags F, + krb5_data * pD1, + krb5_creds * pC, + krb5_data * pD2) + { + if (!krb5_loaded) + load_krb5_dll(); + + if ( p_krb5_mk_req_extended ) + return(p_krb5_mk_req_extended(CO,pACO,F,pD1,pC,pD2)); + else + return KRB5KRB_ERR_GENERIC; + } +krb5_error_code +kssl_krb5_auth_con_init(krb5_context CO, + krb5_auth_context * pACO) + { + if (!krb5_loaded) + load_krb5_dll(); + + if ( p_krb5_auth_con_init ) + return(p_krb5_auth_con_init(CO,pACO)); + else + return KRB5KRB_ERR_GENERIC; + } +krb5_error_code +kssl_krb5_auth_con_free (krb5_context CO, + krb5_auth_context ACO) + { + if (!krb5_loaded) + load_krb5_dll(); + + if ( p_krb5_auth_con_free ) + return(p_krb5_auth_con_free(CO,ACO)); + else + return KRB5KRB_ERR_GENERIC; + } +krb5_error_code +kssl_krb5_get_credentials(krb5_context CO, + krb5_const krb5_flags F, + krb5_ccache CC, + krb5_creds * pCR, + krb5_creds ** ppCR) + { + if (!krb5_loaded) + load_krb5_dll(); + + if ( p_krb5_get_credentials ) + return(p_krb5_get_credentials(CO,F,CC,pCR,ppCR)); + else + return KRB5KRB_ERR_GENERIC; + } +krb5_error_code +kssl_krb5_sname_to_principal(krb5_context CO, + krb5_const char * pC1, + krb5_const char * pC2, + krb5_int32 I, + krb5_principal * pPR) + { + if (!krb5_loaded) + load_krb5_dll(); + + if ( p_krb5_sname_to_principal ) + return(p_krb5_sname_to_principal(CO,pC1,pC2,I,pPR)); + else + return KRB5KRB_ERR_GENERIC; + } + +krb5_error_code +kssl_krb5_cc_default(krb5_context CO, + krb5_ccache * pCC) + { + if (!krb5_loaded) + load_krb5_dll(); + + if ( p_krb5_cc_default ) + return(p_krb5_cc_default(CO,pCC)); + else + return KRB5KRB_ERR_GENERIC; + } + +krb5_error_code +kssl_krb5_init_context(krb5_context * pCO) + { + if (!krb5_loaded) + load_krb5_dll(); + + if ( p_krb5_init_context ) + return(p_krb5_init_context(pCO)); + else + return KRB5KRB_ERR_GENERIC; + } + +void +kssl_krb5_free_context(krb5_context CO) + { + if (!krb5_loaded) + load_krb5_dll(); + + if ( p_krb5_free_context ) + p_krb5_free_context(CO); + } + +void +kssl_krb5_free_principal(krb5_context c, krb5_principal p) + { + if (!krb5_loaded) + load_krb5_dll(); + + if ( p_krb5_free_principal ) + p_krb5_free_principal(c,p); + } + +krb5_error_code +kssl_krb5_kt_resolve(krb5_context con, + krb5_const char * sz, + krb5_keytab * kt) + { + if (!krb5_loaded) + load_krb5_dll(); + + if ( p_krb5_kt_resolve ) + return(p_krb5_kt_resolve(con,sz,kt)); + else + return KRB5KRB_ERR_GENERIC; + } + +krb5_error_code +kssl_krb5_kt_default(krb5_context con, + krb5_keytab * kt) + { + if (!krb5_loaded) + load_krb5_dll(); + + if ( p_krb5_kt_default ) + return(p_krb5_kt_default(con,kt)); + else + return KRB5KRB_ERR_GENERIC; + } + +krb5_error_code +kssl_krb5_free_ticket(krb5_context con, + krb5_ticket * kt) + { + if (!krb5_loaded) + load_krb5_dll(); + + if ( p_krb5_free_ticket ) + return(p_krb5_free_ticket(con,kt)); + else + return KRB5KRB_ERR_GENERIC; + } + +krb5_error_code +kssl_krb5_rd_req(krb5_context con, krb5_auth_context * pacon, + krb5_const krb5_data * data, + krb5_const_principal princ, krb5_keytab keytab, + krb5_flags * flags, krb5_ticket ** pptkt) + { + if (!krb5_loaded) + load_krb5_dll(); + + if ( p_krb5_rd_req ) + return(p_krb5_rd_req(con,pacon,data,princ,keytab,flags,pptkt)); + else + return KRB5KRB_ERR_GENERIC; + } + +krb5_boolean +krb5_principal_compare(krb5_context con, krb5_const_principal princ1, + krb5_const_principal princ2) + { + if (!krb5_loaded) + load_krb5_dll(); + + if ( p_krb5_principal_compare ) + return(p_krb5_principal_compare(con,princ1,princ2)); + else + return KRB5KRB_ERR_GENERIC; + } + +krb5_error_code +krb5_decrypt_tkt_part(krb5_context con, krb5_const krb5_keyblock *keys, + krb5_ticket *ticket) + { + if (!krb5_loaded) + load_krb5_dll(); + + if ( p_krb5_decrypt_tkt_part ) + return(p_krb5_decrypt_tkt_part(con,keys,ticket)); + else + return KRB5KRB_ERR_GENERIC; + } + +krb5_error_code +krb5_timeofday(krb5_context con, krb5_int32 *timeret) + { + if (!krb5_loaded) + load_krb5_dll(); + + if ( p_krb5_timeofday ) + return(p_krb5_timeofday(con,timeret)); + else + return KRB5KRB_ERR_GENERIC; + } + +krb5_error_code +krb5_rc_default(krb5_context con, krb5_rcache *rc) + { + if (!krb5_loaded) + load_krb5_dll(); + + if ( p_krb5_rc_default ) + return(p_krb5_rc_default(con,rc)); + else + return KRB5KRB_ERR_GENERIC; + } + +krb5_error_code +krb5_rc_initialize(krb5_context con, krb5_rcache rc, krb5_deltat lifespan) + { + if (!krb5_loaded) + load_krb5_dll(); + + if ( p_krb5_rc_initialize ) + return(p_krb5_rc_initialize(con, rc, lifespan)); + else + return KRB5KRB_ERR_GENERIC; + } + +krb5_error_code +krb5_rc_get_lifespan(krb5_context con, krb5_rcache rc, krb5_deltat *lifespanp) + { + if (!krb5_loaded) + load_krb5_dll(); + + if ( p_krb5_rc_get_lifespan ) + return(p_krb5_rc_get_lifespan(con, rc, lifespanp)); + else + return KRB5KRB_ERR_GENERIC; + } + +krb5_error_code +krb5_rc_destroy(krb5_context con, krb5_rcache rc) + { + if (!krb5_loaded) + load_krb5_dll(); + + if ( p_krb5_rc_destroy ) + return(p_krb5_rc_destroy(con, rc)); + else + return KRB5KRB_ERR_GENERIC; + } + +size_t +krb5_checksum_size(krb5_context context,krb5_cksumtype ctype) + { + if (!krb5_loaded) + load_krb5_dll(); + + if ( p_krb5_checksum_size ) + return(p_krb5_checksum_size(context, ctype)); + else + return KRB5KRB_ERR_GENERIC; + } + +krb5_boolean +valid_cksumtype(krb5_cksumtype ctype) + { + if (!krb5_loaded) + load_krb5_dll(); + + if ( p_valid_cksumtype ) + return(p_valid_cksumtype(ctype)); + else + return KRB5KRB_ERR_GENERIC; + } + +krb5_error_code +krb5_kt_free_entry(krb5_context con,krb5_keytab_entry * entry) + { + if (!krb5_loaded) + load_krb5_dll(); + + if ( p_krb5_kt_free_entry ) + return(p_krb5_kt_free_entry(con,entry)); + else + return KRB5KRB_ERR_GENERIC; + } + +/* Structure definitions */ +#ifndef NO_DEF_KRB5_CCACHE +#ifndef krb5_x +#define krb5_x(ptr,args) ((ptr)?((*(ptr)) args):(abort(),1)) +#define krb5_xc(ptr,args) ((ptr)?((*(ptr)) args):(abort(),(char*)0)) +#endif + +typedef krb5_pointer krb5_cc_cursor; /* cursor for sequential lookup */ + +typedef struct _krb5_ccache + { + krb5_magic magic; + struct _krb5_cc_ops FAR *ops; + krb5_pointer data; + } *krb5_ccache; + +typedef struct _krb5_cc_ops + { + krb5_magic magic; + char *prefix; + char * (KRB5_CALLCONV *get_name) + (krb5_context, krb5_ccache); + krb5_error_code (KRB5_CALLCONV *resolve) + (krb5_context, krb5_ccache *, const char *); + krb5_error_code (KRB5_CALLCONV *gen_new) + (krb5_context, krb5_ccache *); + krb5_error_code (KRB5_CALLCONV *init) + (krb5_context, krb5_ccache, krb5_principal); + krb5_error_code (KRB5_CALLCONV *destroy) + (krb5_context, krb5_ccache); + krb5_error_code (KRB5_CALLCONV *close) + (krb5_context, krb5_ccache); + krb5_error_code (KRB5_CALLCONV *store) + (krb5_context, krb5_ccache, krb5_creds *); + krb5_error_code (KRB5_CALLCONV *retrieve) + (krb5_context, krb5_ccache, + krb5_flags, krb5_creds *, krb5_creds *); + krb5_error_code (KRB5_CALLCONV *get_princ) + (krb5_context, krb5_ccache, krb5_principal *); + krb5_error_code (KRB5_CALLCONV *get_first) + (krb5_context, krb5_ccache, krb5_cc_cursor *); + krb5_error_code (KRB5_CALLCONV *get_next) + (krb5_context, krb5_ccache, + krb5_cc_cursor *, krb5_creds *); + krb5_error_code (KRB5_CALLCONV *end_get) + (krb5_context, krb5_ccache, krb5_cc_cursor *); + krb5_error_code (KRB5_CALLCONV *remove_cred) + (krb5_context, krb5_ccache, + krb5_flags, krb5_creds *); + krb5_error_code (KRB5_CALLCONV *set_flags) + (krb5_context, krb5_ccache, krb5_flags); + } krb5_cc_ops; +#endif /* NO_DEF_KRB5_CCACHE */ + +krb5_error_code +kssl_krb5_cc_get_principal + (krb5_context context, krb5_ccache cache, + krb5_principal *principal) + { + if ( p_krb5_cc_get_principal ) + return(p_krb5_cc_get_principal(context,cache,principal)); + else + return(krb5_x + ((cache)->ops->get_princ,(context, cache, principal))); + } + +krb5_error_code +kssl_krb5_auth_con_setrcache(krb5_context con, krb5_auth_context acon, + krb5_rcache rcache) + { + if ( p_krb5_auth_con_setrcache ) + return(p_krb5_auth_con_setrcache(con,acon,rcache)); + else + return KRB5KRB_ERR_GENERIC; + } + +krb5_error_code +kssl_krb5_get_server_rcache(krb5_context con, krb5_const krb5_data * data, + krb5_rcache * rcache) + { + if ( p_krb5_get_server_rcache ) + return(p_krb5_get_server_rcache(con,data,rcache)); + else + return KRB5KRB_ERR_GENERIC; + } + +krb5_error_code +kssl_krb5_auth_con_getrcache(krb5_context con, krb5_auth_context acon, + krb5_rcache * prcache) + { + if ( p_krb5_auth_con_getrcache ) + return(p_krb5_auth_con_getrcache(con,acon, prcache)); + else + return KRB5KRB_ERR_GENERIC; + } + +krb5_error_code +kssl_krb5_kt_close(krb5_context context, krb5_keytab keytab) + { + if ( p_krb5_kt_close ) + return(p_krb5_kt_close(context,keytab)); + else + return KRB5KRB_ERR_GENERIC; + } + +krb5_error_code +kssl_krb5_kt_get_entry(krb5_context context, krb5_keytab keytab, + krb5_const_principal principal, krb5_kvno vno, + krb5_enctype enctype, krb5_keytab_entry *entry) + { + if ( p_krb5_kt_get_entry ) + return(p_krb5_kt_get_entry(context,keytab,principal,vno,enctype,entry)); + else + return KRB5KRB_ERR_GENERIC; + } +#endif /* OPENSSL_SYS_WINDOWS || OPENSSL_SYS_WIN32 */ + + +/* memory allocation functions for non-temporary storage + * (e.g. stuff that gets saved into the kssl context) */ +static void* kssl_calloc(size_t nmemb, size_t size) +{ + void* p; + + p=OPENSSL_malloc(nmemb*size); + if (p){ + memset(p, 0, nmemb*size); + } + return p; +} + +#define kssl_malloc(size) OPENSSL_malloc((size)) +#define kssl_realloc(ptr, size) OPENSSL_realloc(ptr, size) +#define kssl_free(ptr) OPENSSL_free((ptr)) + + +char +*kstring(char *string) + { + static char *null = "[NULL]"; + + return ((string == NULL)? null: string); + } + +/* Given KRB5 enctype (basically DES or 3DES), +** return closest match openssl EVP_ encryption algorithm. +** Return NULL for unknown or problematic (krb5_dk_encrypt) enctypes. +** Assume ENCTYPE_*_RAW (krb5_raw_encrypt) are OK. +*/ +const EVP_CIPHER * +kssl_map_enc(krb5_enctype enctype) + { + switch (enctype) + { + case ENCTYPE_DES_HMAC_SHA1: /* EVP_des_cbc(); */ + case ENCTYPE_DES_CBC_CRC: + case ENCTYPE_DES_CBC_MD4: + case ENCTYPE_DES_CBC_MD5: + case ENCTYPE_DES_CBC_RAW: + return EVP_des_cbc(); + break; + case ENCTYPE_DES3_CBC_SHA1: /* EVP_des_ede3_cbc(); */ + case ENCTYPE_DES3_CBC_SHA: + case ENCTYPE_DES3_CBC_RAW: + return EVP_des_ede3_cbc(); + break; + default: return NULL; + break; + } + } + + +/* Return true:1 if p "looks like" the start of the real authenticator +** described in kssl_skip_confound() below. The ASN.1 pattern is +** "62 xx 30 yy" (APPLICATION-2, SEQUENCE), where xx-yy =~ 2, and +** xx and yy are possibly multi-byte length fields. +*/ +static int kssl_test_confound(unsigned char *p) + { + int len = 2; + int xx = 0, yy = 0; + + if (*p++ != 0x62) return 0; + if (*p > 0x82) return 0; + switch(*p) { + case 0x82: p++; xx = (*p++ << 8); xx += *p++; break; + case 0x81: p++; xx = *p++; break; + case 0x80: return 0; + default: xx = *p++; break; + } + if (*p++ != 0x30) return 0; + if (*p > 0x82) return 0; + switch(*p) { + case 0x82: p++; len+=2; yy = (*p++ << 8); yy += *p++; break; + case 0x81: p++; len++; yy = *p++; break; + case 0x80: return 0; + default: yy = *p++; break; + } + + return (xx - len == yy)? 1: 0; + } + +/* Allocate, fill, and return cksumlens array of checksum lengths. +** This array holds just the unique elements from the krb5_cksumarray[]. +** array[n] == 0 signals end of data. +** +** The krb5_cksumarray[] was an internal variable that has since been +** replaced by a more general method for storing the data. It should +** not be used. Instead we use real API calls and make a guess for +** what the highest assigned CKSUMTYPE_ constant is. As of 1.2.2 +** it is 0x000c (CKSUMTYPE_HMAC_SHA1_DES3). So we will use 0x0010. +*/ +static size_t *populate_cksumlens(void) + { + int i, j, n; + static size_t *cklens = NULL; + +#ifdef KRB5_MIT_OLD11 + n = krb5_max_cksum; +#else + n = 0x0010; +#endif /* KRB5_MIT_OLD11 */ + +#ifdef KRB5CHECKAUTH + if (!cklens && !(cklens = (size_t *) calloc(sizeof(int),n+1))) return NULL; + + for (i=0; i < n; i++) { + if (!valid_cksumtype(i)) continue; /* array has holes */ + for (j=0; j < n; j++) { + if (cklens[j] == 0) { + cklens[j] = krb5_checksum_size(NULL,i); + break; /* krb5 elem was new: add */ + } + if (cklens[j] == krb5_checksum_size(NULL,i)) { + break; /* ignore duplicate elements */ + } + } + } +#endif /* KRB5CHECKAUTH */ + + return cklens; + } + +/* Return pointer to start of real authenticator within authenticator, or +** return NULL on error. +** Decrypted authenticator looks like this: +** [0 or 8 byte confounder] [4-24 byte checksum] [real authent'r] +** This hackery wouldn't be necessary if MIT KRB5 1.0.6 had the +** krb5_auth_con_getcksumtype() function advertised in its krb5.h. +*/ +unsigned char *kssl_skip_confound(krb5_enctype etype, unsigned char *a) + { + int i, conlen; + size_t cklen; + static size_t *cksumlens = NULL; + unsigned char *test_auth; + + conlen = (etype)? 8: 0; + + if (!cksumlens && !(cksumlens = populate_cksumlens())) return NULL; + for (i=0; (cklen = cksumlens[i]) != 0; i++) + { + test_auth = a + conlen + cklen; + if (kssl_test_confound(test_auth)) return test_auth; + } + + return NULL; + } + + +/* Set kssl_err error info when reason text is a simple string +** kssl_err = struct { int reason; char text[KSSL_ERR_MAX+1]; } +*/ +void +kssl_err_set(KSSL_ERR *kssl_err, int reason, char *text) + { + if (kssl_err == NULL) return; + + kssl_err->reason = reason; + BIO_snprintf(kssl_err->text, KSSL_ERR_MAX, "%s", text); + return; + } + + +/* Display contents of krb5_data struct, for debugging +*/ +void +print_krb5_data(char *label, krb5_data *kdata) + { + int i; + + printf("%s[%d] ", label, kdata->length); + for (i=0; i < (int)kdata->length; i++) + { + if (0 && isprint((int) kdata->data[i])) + printf( "%c ", kdata->data[i]); + else + printf( "%02x ", (unsigned char) kdata->data[i]); + } + printf("\n"); + } + + +/* Display contents of krb5_authdata struct, for debugging +*/ +void +print_krb5_authdata(char *label, krb5_authdata **adata) + { + if (adata == NULL) + { + printf("%s, authdata==0\n", label); + return; + } + printf("%s [%p]\n", label, (void *)adata); +#if 0 + { + int i; + printf("%s[at%d:%d] ", label, adata->ad_type, adata->length); + for (i=0; i < adata->length; i++) + { + printf((isprint(adata->contents[i]))? "%c ": "%02x", + adata->contents[i]); + } + printf("\n"); + } +#endif + } + + +/* Display contents of krb5_keyblock struct, for debugging +*/ +void +print_krb5_keyblock(char *label, krb5_keyblock *keyblk) + { + int i; + + if (keyblk == NULL) + { + printf("%s, keyblk==0\n", label); + return; + } +#ifdef KRB5_HEIMDAL + printf("%s\n\t[et%d:%d]: ", label, keyblk->keytype, + keyblk->keyvalue->length); + for (i=0; i < (int)keyblk->keyvalue->length; i++) + { + printf("%02x",(unsigned char *)(keyblk->keyvalue->contents)[i]); + } + printf("\n"); +#else + printf("%s\n\t[et%d:%d]: ", label, keyblk->enctype, keyblk->length); + for (i=0; i < (int)keyblk->length; i++) + { + printf("%02x",keyblk->contents[i]); + } + printf("\n"); +#endif + } + + +/* Display contents of krb5_principal_data struct, for debugging +** (krb5_principal is typedef'd == krb5_principal_data *) +*/ +static void +print_krb5_princ(char *label, krb5_principal_data *princ) + { + int i, ui, uj; + + printf("%s principal Realm: ", label); + if (princ == NULL) return; + for (ui=0; ui < (int)princ->realm.length; ui++) putchar(princ->realm.data[ui]); + printf(" (nametype %d) has %d strings:\n", princ->type,princ->length); + for (i=0; i < (int)princ->length; i++) + { + printf("\t%d [%d]: ", i, princ->data[i].length); + for (uj=0; uj < (int)princ->data[i].length; uj++) { + putchar(princ->data[i].data[uj]); + } + printf("\n"); + } + return; + } + + +/* Given krb5 service (typically "kssl") and hostname in kssl_ctx, +** Return encrypted Kerberos ticket for service @ hostname. +** If authenp is non-NULL, also return encrypted authenticator, +** whose data should be freed by caller. +** (Originally was: Create Kerberos AP_REQ message for SSL Client.) +** +** 19990628 VRS Started; Returns Kerberos AP_REQ message. +** 20010409 VRS Modified for RFC2712; Returns enc tkt. +** 20010606 VRS May also return optional authenticator. +*/ +krb5_error_code +kssl_cget_tkt( /* UPDATE */ KSSL_CTX *kssl_ctx, + /* OUT */ krb5_data **enc_ticketp, + /* UPDATE */ krb5_data *authenp, + /* OUT */ KSSL_ERR *kssl_err) + { + krb5_error_code krb5rc = KRB5KRB_ERR_GENERIC; + krb5_context krb5context = NULL; + krb5_auth_context krb5auth_context = NULL; + krb5_ccache krb5ccdef = NULL; + krb5_creds krb5creds, *krb5credsp = NULL; + krb5_data krb5_app_req; + + kssl_err_set(kssl_err, 0, ""); + memset((char *)&krb5creds, 0, sizeof(krb5creds)); + + if (!kssl_ctx) + { + kssl_err_set(kssl_err, SSL_R_KRB5_S_INIT, + "No kssl_ctx defined.\n"); + goto err; + } + else if (!kssl_ctx->service_host) + { + kssl_err_set(kssl_err, SSL_R_KRB5_S_INIT, + "kssl_ctx service_host undefined.\n"); + goto err; + } + + if ((krb5rc = krb5_init_context(&krb5context)) != 0) + { + BIO_snprintf(kssl_err->text,KSSL_ERR_MAX, + "krb5_init_context() fails: %d\n", krb5rc); + kssl_err->reason = SSL_R_KRB5_C_INIT; + goto err; + } + + if ((krb5rc = krb5_sname_to_principal(krb5context, + kssl_ctx->service_host, + (kssl_ctx->service_name)? kssl_ctx->service_name: KRB5SVC, + KRB5_NT_SRV_HST, &krb5creds.server)) != 0) + { + BIO_snprintf(kssl_err->text,KSSL_ERR_MAX, + "krb5_sname_to_principal() fails for %s/%s\n", + kssl_ctx->service_host, + (kssl_ctx->service_name)? kssl_ctx->service_name: + KRB5SVC); + kssl_err->reason = SSL_R_KRB5_C_INIT; + goto err; + } + + if ((krb5rc = krb5_cc_default(krb5context, &krb5ccdef)) != 0) + { + kssl_err_set(kssl_err, SSL_R_KRB5_C_CC_PRINC, + "krb5_cc_default fails.\n"); + goto err; + } + + if ((krb5rc = krb5_cc_get_principal(krb5context, krb5ccdef, + &krb5creds.client)) != 0) + { + kssl_err_set(kssl_err, SSL_R_KRB5_C_CC_PRINC, + "krb5_cc_get_principal() fails.\n"); + goto err; + } + + if ((krb5rc = krb5_get_credentials(krb5context, 0, krb5ccdef, + &krb5creds, &krb5credsp)) != 0) + { + kssl_err_set(kssl_err, SSL_R_KRB5_C_GET_CRED, + "krb5_get_credentials() fails.\n"); + goto err; + } + + *enc_ticketp = &krb5credsp->ticket; +#ifdef KRB5_HEIMDAL + kssl_ctx->enctype = krb5credsp->session.keytype; +#else + kssl_ctx->enctype = krb5credsp->keyblock.enctype; +#endif + + krb5rc = KRB5KRB_ERR_GENERIC; + /* caller should free data of krb5_app_req */ + /* 20010406 VRS deleted for real KerberosWrapper + ** 20010605 VRS reinstated to offer Authenticator to KerberosWrapper + */ + krb5_app_req.length = 0; + if (authenp) + { + krb5_data krb5in_data; + const unsigned char *p; + long arlen; + KRB5_APREQBODY *ap_req; + + authenp->length = 0; + krb5in_data.data = NULL; + krb5in_data.length = 0; + if ((krb5rc = krb5_mk_req_extended(krb5context, + &krb5auth_context, 0, &krb5in_data, krb5credsp, + &krb5_app_req)) != 0) + { + kssl_err_set(kssl_err, SSL_R_KRB5_C_MK_REQ, + "krb5_mk_req_extended() fails.\n"); + goto err; + } + + arlen = krb5_app_req.length; + p = (unsigned char *)krb5_app_req.data; + ap_req = (KRB5_APREQBODY *) d2i_KRB5_APREQ(NULL, &p, arlen); + if (ap_req) + { + authenp->length = i2d_KRB5_ENCDATA( + ap_req->authenticator, NULL); + if (authenp->length && + (authenp->data = malloc(authenp->length))) + { + unsigned char *adp = (unsigned char *)authenp->data; + authenp->length = i2d_KRB5_ENCDATA( + ap_req->authenticator, &adp); + } + } + + if (ap_req) KRB5_APREQ_free((KRB5_APREQ *) ap_req); + if (krb5_app_req.length) + kssl_krb5_free_data_contents(krb5context,&krb5_app_req); + } +#ifdef KRB5_HEIMDAL + if (kssl_ctx_setkey(kssl_ctx, &krb5credsp->session)) + { + kssl_err_set(kssl_err, SSL_R_KRB5_C_INIT, + "kssl_ctx_setkey() fails.\n"); + } +#else + if (kssl_ctx_setkey(kssl_ctx, &krb5credsp->keyblock)) + { + kssl_err_set(kssl_err, SSL_R_KRB5_C_INIT, + "kssl_ctx_setkey() fails.\n"); + } +#endif + else krb5rc = 0; + + err: +#ifdef KSSL_DEBUG + kssl_ctx_show(kssl_ctx); +#endif /* KSSL_DEBUG */ + + if (krb5creds.client) krb5_free_principal(krb5context, + krb5creds.client); + if (krb5creds.server) krb5_free_principal(krb5context, + krb5creds.server); + if (krb5auth_context) krb5_auth_con_free(krb5context, + krb5auth_context); + if (krb5context) krb5_free_context(krb5context); + return (krb5rc); + } + + +/* Given d2i_-decoded asn1ticket, allocate and return a new krb5_ticket. +** Return Kerberos error code and kssl_err struct on error. +** Allocates krb5_ticket and krb5_principal; caller should free these. +** +** 20010410 VRS Implemented krb5_decode_ticket() as +** old_krb5_decode_ticket(). Missing from MIT1.0.6. +** 20010615 VRS Re-cast as openssl/asn1 d2i_*() functions. +** Re-used some of the old krb5_decode_ticket() +** code here. This tkt should alloc/free just +** like the real thing. +*/ +static krb5_error_code +kssl_TKT2tkt( /* IN */ krb5_context krb5context, + /* IN */ KRB5_TKTBODY *asn1ticket, + /* OUT */ krb5_ticket **krb5ticket, + /* OUT */ KSSL_ERR *kssl_err ) + { + krb5_error_code krb5rc = KRB5KRB_ERR_GENERIC; + krb5_ticket *new5ticket = NULL; + ASN1_GENERALSTRING *gstr_svc, *gstr_host; + + *krb5ticket = NULL; + + if (asn1ticket == NULL || asn1ticket->realm == NULL || + asn1ticket->sname == NULL || + sk_ASN1_GENERALSTRING_num(asn1ticket->sname->namestring) < 2) + { + BIO_snprintf(kssl_err->text, KSSL_ERR_MAX, + "Null field in asn1ticket.\n"); + kssl_err->reason = SSL_R_KRB5_S_RD_REQ; + return KRB5KRB_ERR_GENERIC; + } + + if ((new5ticket = (krb5_ticket *) calloc(1, sizeof(krb5_ticket)))==NULL) + { + BIO_snprintf(kssl_err->text, KSSL_ERR_MAX, + "Unable to allocate new krb5_ticket.\n"); + kssl_err->reason = SSL_R_KRB5_S_RD_REQ; + return ENOMEM; /* or KRB5KRB_ERR_GENERIC; */ + } + + gstr_svc = sk_ASN1_GENERALSTRING_value(asn1ticket->sname->namestring, 0); + gstr_host = sk_ASN1_GENERALSTRING_value(asn1ticket->sname->namestring, 1); + + if ((krb5rc = kssl_build_principal_2(krb5context, + &new5ticket->server, + asn1ticket->realm->length, (char *)asn1ticket->realm->data, + gstr_svc->length, (char *)gstr_svc->data, + gstr_host->length, (char *)gstr_host->data)) != 0) + { + free(new5ticket); + BIO_snprintf(kssl_err->text, KSSL_ERR_MAX, + "Error building ticket server principal.\n"); + kssl_err->reason = SSL_R_KRB5_S_RD_REQ; + return krb5rc; /* or KRB5KRB_ERR_GENERIC; */ + } + + krb5_princ_type(krb5context, new5ticket->server) = + asn1ticket->sname->nametype->data[0]; + new5ticket->enc_part.enctype = asn1ticket->encdata->etype->data[0]; + new5ticket->enc_part.kvno = asn1ticket->encdata->kvno->data[0]; + new5ticket->enc_part.ciphertext.length = + asn1ticket->encdata->cipher->length; + if ((new5ticket->enc_part.ciphertext.data = + calloc(1, asn1ticket->encdata->cipher->length)) == NULL) + { + free(new5ticket); + BIO_snprintf(kssl_err->text, KSSL_ERR_MAX, + "Error allocating cipher in krb5ticket.\n"); + kssl_err->reason = SSL_R_KRB5_S_RD_REQ; + return KRB5KRB_ERR_GENERIC; + } + else + { + memcpy(new5ticket->enc_part.ciphertext.data, + asn1ticket->encdata->cipher->data, + asn1ticket->encdata->cipher->length); + } + + *krb5ticket = new5ticket; + return 0; + } + + +/* Given krb5 service name in KSSL_CTX *kssl_ctx (typically "kssl"), +** and krb5 AP_REQ message & message length, +** Return Kerberos session key and client principle +** to SSL Server in KSSL_CTX *kssl_ctx. +** +** 19990702 VRS Started. +*/ +krb5_error_code +kssl_sget_tkt( /* UPDATE */ KSSL_CTX *kssl_ctx, + /* IN */ krb5_data *indata, + /* OUT */ krb5_ticket_times *ttimes, + /* OUT */ KSSL_ERR *kssl_err ) + { + krb5_error_code krb5rc = KRB5KRB_ERR_GENERIC; + static krb5_context krb5context = NULL; + static krb5_auth_context krb5auth_context = NULL; + krb5_ticket *krb5ticket = NULL; + KRB5_TKTBODY *asn1ticket = NULL; + const unsigned char *p; + krb5_keytab krb5keytab = NULL; + krb5_keytab_entry kt_entry; + krb5_principal krb5server; + krb5_rcache rcache = NULL; + + kssl_err_set(kssl_err, 0, ""); + + if (!kssl_ctx) + { + kssl_err_set(kssl_err, SSL_R_KRB5_S_INIT, + "No kssl_ctx defined.\n"); + goto err; + } + +#ifdef KSSL_DEBUG + printf("in kssl_sget_tkt(%s)\n", kstring(kssl_ctx->service_name)); +#endif /* KSSL_DEBUG */ + + if (!krb5context && (krb5rc = krb5_init_context(&krb5context))) + { + kssl_err_set(kssl_err, SSL_R_KRB5_S_INIT, + "krb5_init_context() fails.\n"); + goto err; + } + if (krb5auth_context && + (krb5rc = krb5_auth_con_free(krb5context, krb5auth_context))) + { + kssl_err_set(kssl_err, SSL_R_KRB5_S_INIT, + "krb5_auth_con_free() fails.\n"); + goto err; + } + else krb5auth_context = NULL; + if (!krb5auth_context && + (krb5rc = krb5_auth_con_init(krb5context, &krb5auth_context))) + { + kssl_err_set(kssl_err, SSL_R_KRB5_S_INIT, + "krb5_auth_con_init() fails.\n"); + goto err; + } + + + if ((krb5rc = krb5_auth_con_getrcache(krb5context, krb5auth_context, + &rcache))) + { + kssl_err_set(kssl_err, SSL_R_KRB5_S_INIT, + "krb5_auth_con_getrcache() fails.\n"); + goto err; + } + + if ((krb5rc = krb5_sname_to_principal(krb5context, NULL, + (kssl_ctx->service_name)? kssl_ctx->service_name: KRB5SVC, + KRB5_NT_SRV_HST, &krb5server)) != 0) + { + kssl_err_set(kssl_err, SSL_R_KRB5_S_INIT, + "krb5_sname_to_principal() fails.\n"); + goto err; + } + + if (rcache == NULL) + { + if ((krb5rc = krb5_get_server_rcache(krb5context, + krb5_princ_component(krb5context, krb5server, 0), + &rcache))) + { + kssl_err_set(kssl_err, SSL_R_KRB5_S_INIT, + "krb5_get_server_rcache() fails.\n"); + goto err; + } + } + + if ((krb5rc = krb5_auth_con_setrcache(krb5context, krb5auth_context, rcache))) + { + kssl_err_set(kssl_err, SSL_R_KRB5_S_INIT, + "krb5_auth_con_setrcache() fails.\n"); + goto err; + } + + + /* kssl_ctx->keytab_file == NULL ==> use Kerberos default + */ + if (kssl_ctx->keytab_file) + { + krb5rc = krb5_kt_resolve(krb5context, kssl_ctx->keytab_file, + &krb5keytab); + if (krb5rc) + { + kssl_err_set(kssl_err, SSL_R_KRB5_S_INIT, + "krb5_kt_resolve() fails.\n"); + goto err; + } + } + else + { + krb5rc = krb5_kt_default(krb5context,&krb5keytab); + if (krb5rc) + { + kssl_err_set(kssl_err, SSL_R_KRB5_S_INIT, + "krb5_kt_default() fails.\n"); + goto err; + } + } + + /* Actual Kerberos5 krb5_recvauth() has initial conversation here + ** o check KRB5_SENDAUTH_BADAUTHVERS + ** unless KRB5_RECVAUTH_SKIP_VERSION + ** o check KRB5_SENDAUTH_BADAPPLVERS + ** o send "0" msg if all OK + */ + + /* 20010411 was using AP_REQ instead of true KerberosWrapper + ** + ** if ((krb5rc = krb5_rd_req(krb5context, &krb5auth_context, + ** &krb5in_data, krb5server, krb5keytab, + ** &ap_option, &krb5ticket)) != 0) { Error } + */ + + p = (unsigned char *)indata->data; + if ((asn1ticket = (KRB5_TKTBODY *) d2i_KRB5_TICKET(NULL, &p, + (long) indata->length)) == NULL) + { + BIO_snprintf(kssl_err->text, KSSL_ERR_MAX, + "d2i_KRB5_TICKET() ASN.1 decode failure.\n"); + kssl_err->reason = SSL_R_KRB5_S_RD_REQ; + goto err; + } + + /* Was: krb5rc = krb5_decode_ticket(krb5in_data,&krb5ticket)) != 0) */ + if ((krb5rc = kssl_TKT2tkt(krb5context, asn1ticket, &krb5ticket, + kssl_err)) != 0) + { + BIO_snprintf(kssl_err->text, KSSL_ERR_MAX, + "Error converting ASN.1 ticket to krb5_ticket.\n"); + kssl_err->reason = SSL_R_KRB5_S_RD_REQ; + goto err; + } + + if (! krb5_principal_compare(krb5context, krb5server, + krb5ticket->server)) { + krb5rc = KRB5_PRINC_NOMATCH; + BIO_snprintf(kssl_err->text, KSSL_ERR_MAX, + "server principal != ticket principal\n"); + kssl_err->reason = SSL_R_KRB5_S_RD_REQ; + goto err; + } + if ((krb5rc = krb5_kt_get_entry(krb5context, krb5keytab, + krb5ticket->server, krb5ticket->enc_part.kvno, + krb5ticket->enc_part.enctype, &kt_entry)) != 0) { + BIO_snprintf(kssl_err->text, KSSL_ERR_MAX, + "krb5_kt_get_entry() fails with %x.\n", krb5rc); + kssl_err->reason = SSL_R_KRB5_S_RD_REQ; + goto err; + } + if ((krb5rc = krb5_decrypt_tkt_part(krb5context, &kt_entry.key, + krb5ticket)) != 0) { + BIO_snprintf(kssl_err->text, KSSL_ERR_MAX, + "krb5_decrypt_tkt_part() failed.\n"); + kssl_err->reason = SSL_R_KRB5_S_RD_REQ; + goto err; + } + else { + krb5_kt_free_entry(krb5context, &kt_entry); +#ifdef KSSL_DEBUG + { + int i; krb5_address **paddr = krb5ticket->enc_part2->caddrs; + printf("Decrypted ticket fields:\n"); + printf("\tflags: %X, transit-type: %X", + krb5ticket->enc_part2->flags, + krb5ticket->enc_part2->transited.tr_type); + print_krb5_data("\ttransit-data: ", + &(krb5ticket->enc_part2->transited.tr_contents)); + printf("\tcaddrs: %p, authdata: %p\n", + krb5ticket->enc_part2->caddrs, + krb5ticket->enc_part2->authorization_data); + if (paddr) + { + printf("\tcaddrs:\n"); + for (i=0; paddr[i] != NULL; i++) + { + krb5_data d; + d.length=paddr[i]->length; + d.data=paddr[i]->contents; + print_krb5_data("\t\tIP: ", &d); + } + } + printf("\tstart/auth/end times: %d / %d / %d\n", + krb5ticket->enc_part2->times.starttime, + krb5ticket->enc_part2->times.authtime, + krb5ticket->enc_part2->times.endtime); + } +#endif /* KSSL_DEBUG */ + } + + krb5rc = KRB5_NO_TKT_SUPPLIED; + if (!krb5ticket || !krb5ticket->enc_part2 || + !krb5ticket->enc_part2->client || + !krb5ticket->enc_part2->client->data || + !krb5ticket->enc_part2->session) + { + kssl_err_set(kssl_err, SSL_R_KRB5_S_BAD_TICKET, + "bad ticket from krb5_rd_req.\n"); + } + else if (kssl_ctx_setprinc(kssl_ctx, KSSL_CLIENT, + &krb5ticket->enc_part2->client->realm, + krb5ticket->enc_part2->client->data, + krb5ticket->enc_part2->client->length)) + { + kssl_err_set(kssl_err, SSL_R_KRB5_S_BAD_TICKET, + "kssl_ctx_setprinc() fails.\n"); + } + else if (kssl_ctx_setkey(kssl_ctx, krb5ticket->enc_part2->session)) + { + kssl_err_set(kssl_err, SSL_R_KRB5_S_BAD_TICKET, + "kssl_ctx_setkey() fails.\n"); + } + else if (krb5ticket->enc_part2->flags & TKT_FLG_INVALID) + { + krb5rc = KRB5KRB_AP_ERR_TKT_INVALID; + kssl_err_set(kssl_err, SSL_R_KRB5_S_BAD_TICKET, + "invalid ticket from krb5_rd_req.\n"); + } + else krb5rc = 0; + + kssl_ctx->enctype = krb5ticket->enc_part.enctype; + ttimes->authtime = krb5ticket->enc_part2->times.authtime; + ttimes->starttime = krb5ticket->enc_part2->times.starttime; + ttimes->endtime = krb5ticket->enc_part2->times.endtime; + ttimes->renew_till = krb5ticket->enc_part2->times.renew_till; + + err: +#ifdef KSSL_DEBUG + kssl_ctx_show(kssl_ctx); +#endif /* KSSL_DEBUG */ + + if (asn1ticket) KRB5_TICKET_free((KRB5_TICKET *) asn1ticket); + if (krb5keytab) krb5_kt_close(krb5context, krb5keytab); + if (krb5ticket) krb5_free_ticket(krb5context, krb5ticket); + if (krb5server) krb5_free_principal(krb5context, krb5server); + return (krb5rc); + } + + +/* Allocate & return a new kssl_ctx struct. +*/ +KSSL_CTX * +kssl_ctx_new(void) + { + return ((KSSL_CTX *) kssl_calloc(1, sizeof(KSSL_CTX))); + } + + +/* Frees a kssl_ctx struct and any allocated memory it holds. +** Returns NULL. +*/ +KSSL_CTX * +kssl_ctx_free(KSSL_CTX *kssl_ctx) + { + if (kssl_ctx == NULL) return kssl_ctx; + + if (kssl_ctx->key) OPENSSL_cleanse(kssl_ctx->key, + kssl_ctx->length); + if (kssl_ctx->key) kssl_free(kssl_ctx->key); + if (kssl_ctx->client_princ) kssl_free(kssl_ctx->client_princ); + if (kssl_ctx->service_host) kssl_free(kssl_ctx->service_host); + if (kssl_ctx->service_name) kssl_free(kssl_ctx->service_name); + if (kssl_ctx->keytab_file) kssl_free(kssl_ctx->keytab_file); + + kssl_free(kssl_ctx); + return (KSSL_CTX *) NULL; + } + + +/* Given an array of (krb5_data *) entity (and optional realm), +** set the plain (char *) client_princ or service_host member +** of the kssl_ctx struct. +*/ +krb5_error_code +kssl_ctx_setprinc(KSSL_CTX *kssl_ctx, int which, + krb5_data *realm, krb5_data *entity, int nentities) + { + char **princ; + int length; + int i; + + if (kssl_ctx == NULL || entity == NULL) return KSSL_CTX_ERR; + + switch (which) + { + case KSSL_CLIENT: princ = &kssl_ctx->client_princ; break; + case KSSL_SERVER: princ = &kssl_ctx->service_host; break; + default: return KSSL_CTX_ERR; break; + } + if (*princ) kssl_free(*princ); + + /* Add up all the entity->lengths */ + length = 0; + for (i=0; i < nentities; i++) + { + length += entity[i].length; + } + /* Add in space for the '/' character(s) (if any) */ + length += nentities-1; + /* Space for the ('@'+realm+NULL | NULL) */ + length += ((realm)? realm->length + 2: 1); + + if ((*princ = kssl_calloc(1, length)) == NULL) + return KSSL_CTX_ERR; + else + { + for (i = 0; i < nentities; i++) + { + strncat(*princ, entity[i].data, entity[i].length); + if (i < nentities-1) + { + strcat (*princ, "/"); + } + } + if (realm) + { + strcat (*princ, "@"); + (void) strncat(*princ, realm->data, realm->length); + } + } + + return KSSL_CTX_OK; + } + + +/* Set one of the plain (char *) string members of the kssl_ctx struct. +** Default values should be: +** which == KSSL_SERVICE => "khost" (KRB5SVC) +** which == KSSL_KEYTAB => "/etc/krb5.keytab" (KRB5KEYTAB) +*/ +krb5_error_code +kssl_ctx_setstring(KSSL_CTX *kssl_ctx, int which, char *text) + { + char **string; + + if (!kssl_ctx) return KSSL_CTX_ERR; + + switch (which) + { + case KSSL_SERVICE: string = &kssl_ctx->service_name; break; + case KSSL_SERVER: string = &kssl_ctx->service_host; break; + case KSSL_CLIENT: string = &kssl_ctx->client_princ; break; + case KSSL_KEYTAB: string = &kssl_ctx->keytab_file; break; + default: return KSSL_CTX_ERR; break; + } + if (*string) kssl_free(*string); + + if (!text) + { + *string = '\0'; + return KSSL_CTX_OK; + } + + if ((*string = kssl_calloc(1, strlen(text) + 1)) == NULL) + return KSSL_CTX_ERR; + else + strcpy(*string, text); + + return KSSL_CTX_OK; + } + + +/* Copy the Kerberos session key from a (krb5_keyblock *) to a kssl_ctx +** struct. Clear kssl_ctx->key if Kerberos session key is NULL. +*/ +krb5_error_code +kssl_ctx_setkey(KSSL_CTX *kssl_ctx, krb5_keyblock *session) + { + int length; + krb5_enctype enctype; + krb5_octet FAR *contents = NULL; + + if (!kssl_ctx) return KSSL_CTX_ERR; + + if (kssl_ctx->key) + { + OPENSSL_cleanse(kssl_ctx->key, kssl_ctx->length); + kssl_free(kssl_ctx->key); + } + + if (session) + { + +#ifdef KRB5_HEIMDAL + length = session->keyvalue->length; + enctype = session->keytype; + contents = session->keyvalue->contents; +#else + length = session->length; + enctype = session->enctype; + contents = session->contents; +#endif + kssl_ctx->enctype = enctype; + kssl_ctx->length = length; + } + else + { + kssl_ctx->enctype = ENCTYPE_UNKNOWN; + kssl_ctx->length = 0; + return KSSL_CTX_OK; + } + + if ((kssl_ctx->key = + (krb5_octet FAR *) kssl_calloc(1, kssl_ctx->length)) == NULL) + { + kssl_ctx->length = 0; + return KSSL_CTX_ERR; + } + else + memcpy(kssl_ctx->key, contents, length); + + return KSSL_CTX_OK; + } + + +/* Display contents of kssl_ctx struct +*/ +void +kssl_ctx_show(KSSL_CTX *kssl_ctx) + { + int i; + + printf("kssl_ctx: "); + if (kssl_ctx == NULL) + { + printf("NULL\n"); + return; + } + else + printf("%p\n", (void *)kssl_ctx); + + printf("\tservice:\t%s\n", + (kssl_ctx->service_name)? kssl_ctx->service_name: "NULL"); + printf("\tclient:\t%s\n", + (kssl_ctx->client_princ)? kssl_ctx->client_princ: "NULL"); + printf("\tserver:\t%s\n", + (kssl_ctx->service_host)? kssl_ctx->service_host: "NULL"); + printf("\tkeytab:\t%s\n", + (kssl_ctx->keytab_file)? kssl_ctx->keytab_file: "NULL"); + printf("\tkey [%d:%d]:\t", + kssl_ctx->enctype, kssl_ctx->length); + + for (i=0; i < kssl_ctx->length && kssl_ctx->key; i++) + { + printf("%02x", kssl_ctx->key[i]); + } + printf("\n"); + return; + } + + int + kssl_keytab_is_available(KSSL_CTX *kssl_ctx) +{ + krb5_context krb5context = NULL; + krb5_keytab krb5keytab = NULL; + krb5_keytab_entry entry; + krb5_principal princ = NULL; + krb5_error_code krb5rc = KRB5KRB_ERR_GENERIC; + int rc = 0; + + if ((krb5rc = krb5_init_context(&krb5context))) + return(0); + + /* kssl_ctx->keytab_file == NULL ==> use Kerberos default + */ + if (kssl_ctx->keytab_file) + { + krb5rc = krb5_kt_resolve(krb5context, kssl_ctx->keytab_file, + &krb5keytab); + if (krb5rc) + goto exit; + } + else + { + krb5rc = krb5_kt_default(krb5context,&krb5keytab); + if (krb5rc) + goto exit; + } + + /* the host key we are looking for */ + krb5rc = krb5_sname_to_principal(krb5context, NULL, + kssl_ctx->service_name ? kssl_ctx->service_name: KRB5SVC, + KRB5_NT_SRV_HST, &princ); + + if (krb5rc) + goto exit; + + krb5rc = krb5_kt_get_entry(krb5context, krb5keytab, + princ, + 0 /* IGNORE_VNO */, + 0 /* IGNORE_ENCTYPE */, + &entry); + if ( krb5rc == KRB5_KT_NOTFOUND ) { + rc = 1; + goto exit; + } else if ( krb5rc ) + goto exit; + + krb5_kt_free_entry(krb5context, &entry); + rc = 1; + + exit: + if (krb5keytab) krb5_kt_close(krb5context, krb5keytab); + if (princ) krb5_free_principal(krb5context, princ); + if (krb5context) krb5_free_context(krb5context); + return(rc); +} + +int +kssl_tgt_is_available(KSSL_CTX *kssl_ctx) + { + krb5_error_code krb5rc = KRB5KRB_ERR_GENERIC; + krb5_context krb5context = NULL; + krb5_ccache krb5ccdef = NULL; + krb5_creds krb5creds, *krb5credsp = NULL; + int rc = 0; + + memset((char *)&krb5creds, 0, sizeof(krb5creds)); + + if (!kssl_ctx) + return(0); + + if (!kssl_ctx->service_host) + return(0); + + if ((krb5rc = krb5_init_context(&krb5context)) != 0) + goto err; + + if ((krb5rc = krb5_sname_to_principal(krb5context, + kssl_ctx->service_host, + (kssl_ctx->service_name)? kssl_ctx->service_name: KRB5SVC, + KRB5_NT_SRV_HST, &krb5creds.server)) != 0) + goto err; + + if ((krb5rc = krb5_cc_default(krb5context, &krb5ccdef)) != 0) + goto err; + + if ((krb5rc = krb5_cc_get_principal(krb5context, krb5ccdef, + &krb5creds.client)) != 0) + goto err; + + if ((krb5rc = krb5_get_credentials(krb5context, 0, krb5ccdef, + &krb5creds, &krb5credsp)) != 0) + goto err; + + rc = 1; + + err: +#ifdef KSSL_DEBUG + kssl_ctx_show(kssl_ctx); +#endif /* KSSL_DEBUG */ + + if (krb5creds.client) krb5_free_principal(krb5context, krb5creds.client); + if (krb5creds.server) krb5_free_principal(krb5context, krb5creds.server); + if (krb5context) krb5_free_context(krb5context); + return(rc); + } + +#if !defined(OPENSSL_SYS_WINDOWS) && !defined(OPENSSL_SYS_WIN32) +void kssl_krb5_free_data_contents(krb5_context context, krb5_data *data) + { +#ifdef KRB5_HEIMDAL + data->length = 0; + if (data->data) + free(data->data); +#elif defined(KRB5_MIT_OLD11) + if (data->data) { + krb5_xfree(data->data); + data->data = 0; + } +#else + krb5_free_data_contents(NULL, data); +#endif + } +#endif /* !OPENSSL_SYS_WINDOWS && !OPENSSL_SYS_WIN32 */ + + +/* Given pointers to KerberosTime and struct tm structs, convert the +** KerberosTime string to struct tm. Note that KerberosTime is a +** ASN1_GENERALIZEDTIME value, constrained to GMT with no fractional +** seconds as defined in RFC 1510. +** Return pointer to the (partially) filled in struct tm on success, +** return NULL on failure. +*/ +static struct tm *k_gmtime(ASN1_GENERALIZEDTIME *gtime, struct tm *k_tm) + { + char c, *p; + + if (!k_tm) return NULL; + if (gtime == NULL || gtime->length < 14) return NULL; + if (gtime->data == NULL) return NULL; + + p = (char *)>ime->data[14]; + + c = *p; *p = '\0'; p -= 2; k_tm->tm_sec = atoi(p); *(p+2) = c; + c = *p; *p = '\0'; p -= 2; k_tm->tm_min = atoi(p); *(p+2) = c; + c = *p; *p = '\0'; p -= 2; k_tm->tm_hour = atoi(p); *(p+2) = c; + c = *p; *p = '\0'; p -= 2; k_tm->tm_mday = atoi(p); *(p+2) = c; + c = *p; *p = '\0'; p -= 2; k_tm->tm_mon = atoi(p)-1; *(p+2) = c; + c = *p; *p = '\0'; p -= 4; k_tm->tm_year = atoi(p)-1900; *(p+4) = c; + + return k_tm; + } + + +/* Helper function for kssl_validate_times(). +** We need context->clockskew, but krb5_context is an opaque struct. +** So we try to sneek the clockskew out through the replay cache. +** If that fails just return a likely default (300 seconds). +*/ +static krb5_deltat get_rc_clockskew(krb5_context context) + { + krb5_rcache rc; + krb5_deltat clockskew; + + if (krb5_rc_default(context, &rc)) return KSSL_CLOCKSKEW; + if (krb5_rc_initialize(context, rc, 0)) return KSSL_CLOCKSKEW; + if (krb5_rc_get_lifespan(context, rc, &clockskew)) { + clockskew = KSSL_CLOCKSKEW; + } + (void) krb5_rc_destroy(context, rc); + return clockskew; + } + + +/* kssl_validate_times() combines (and more importantly exposes) +** the MIT KRB5 internal function krb5_validate_times() and the +** in_clock_skew() macro. The authenticator client time is checked +** to be within clockskew secs of the current time and the current +** time is checked to be within the ticket start and expire times. +** Either check may be omitted by supplying a NULL value. +** Returns 0 for valid times, SSL_R_KRB5* error codes otherwise. +** See Also: (Kerberos source)/krb5/lib/krb5/krb/valid_times.c +** 20010420 VRS +*/ +krb5_error_code kssl_validate_times( krb5_timestamp atime, + krb5_ticket_times *ttimes) + { + krb5_deltat skew; + krb5_timestamp start, now; + krb5_error_code rc; + krb5_context context; + + if ((rc = krb5_init_context(&context))) return SSL_R_KRB5_S_BAD_TICKET; + skew = get_rc_clockskew(context); + if ((rc = krb5_timeofday(context,&now))) return SSL_R_KRB5_S_BAD_TICKET; + krb5_free_context(context); + + if (atime && labs(atime - now) >= skew) return SSL_R_KRB5_S_TKT_SKEW; + + if (! ttimes) return 0; + + start = (ttimes->starttime != 0)? ttimes->starttime: ttimes->authtime; + if (start - now > skew) return SSL_R_KRB5_S_TKT_NYV; + if ((now - ttimes->endtime) > skew) return SSL_R_KRB5_S_TKT_EXPIRED; + +#ifdef KSSL_DEBUG + printf("kssl_validate_times: %d |<- | %d - %d | < %d ->| %d\n", + start, atime, now, skew, ttimes->endtime); +#endif /* KSSL_DEBUG */ + + return 0; + } + + +/* Decode and decrypt given DER-encoded authenticator, then pass +** authenticator ctime back in *atimep (or 0 if time unavailable). +** Returns krb5_error_code and kssl_err on error. A NULL +** authenticator (authentp->length == 0) is not considered an error. +** Note that kssl_check_authent() makes use of the KRB5 session key; +** you must call kssl_sget_tkt() to get the key before calling this routine. +*/ +krb5_error_code kssl_check_authent( + /* IN */ KSSL_CTX *kssl_ctx, + /* IN */ krb5_data *authentp, + /* OUT */ krb5_timestamp *atimep, + /* OUT */ KSSL_ERR *kssl_err ) + { + krb5_error_code krb5rc = 0; + KRB5_ENCDATA *dec_authent = NULL; + KRB5_AUTHENTBODY *auth = NULL; + krb5_enctype enctype; + EVP_CIPHER_CTX ciph_ctx; + const EVP_CIPHER *enc = NULL; + unsigned char iv[EVP_MAX_IV_LENGTH]; + const unsigned char *p; + unsigned char *unenc_authent; + int outl, unencbufsize; + struct tm tm_time, *tm_l, *tm_g; + time_t now, tl, tg, tr, tz_offset; + + EVP_CIPHER_CTX_init(&ciph_ctx); + *atimep = 0; + kssl_err_set(kssl_err, 0, ""); + +#ifndef KRB5CHECKAUTH + authentp = NULL; +#else +#if KRB5CHECKAUTH == 0 + authentp = NULL; +#endif +#endif /* KRB5CHECKAUTH */ + + if (authentp == NULL || authentp->length == 0) return 0; + +#ifdef KSSL_DEBUG + { + unsigned int ui; + printf("kssl_check_authent: authenticator[%d]:\n",authentp->length); + p = authentp->data; + for (ui=0; ui < authentp->length; ui++) printf("%02x ",p[ui]); + printf("\n"); + } +#endif /* KSSL_DEBUG */ + + unencbufsize = 2 * authentp->length; + if ((unenc_authent = calloc(1, unencbufsize)) == NULL) + { + kssl_err_set(kssl_err, SSL_R_KRB5_S_INIT, + "Unable to allocate authenticator buffer.\n"); + krb5rc = KRB5KRB_ERR_GENERIC; + goto err; + } + + p = (unsigned char *)authentp->data; + if ((dec_authent = d2i_KRB5_ENCDATA(NULL, &p, + (long) authentp->length)) == NULL) + { + kssl_err_set(kssl_err, SSL_R_KRB5_S_INIT, + "Error decoding authenticator.\n"); + krb5rc = KRB5KRB_AP_ERR_BAD_INTEGRITY; + goto err; + } + + enctype = dec_authent->etype->data[0]; /* should = kssl_ctx->enctype */ +#if !defined(KRB5_MIT_OLD11) + switch ( enctype ) { + case ENCTYPE_DES3_CBC_SHA1: /* EVP_des_ede3_cbc(); */ + case ENCTYPE_DES3_CBC_SHA: + case ENCTYPE_DES3_CBC_RAW: + krb5rc = 0; /* Skip, can't handle derived keys */ + goto err; + } +#endif + enc = kssl_map_enc(enctype); + memset(iv, 0, sizeof iv); /* per RFC 1510 */ + + if (enc == NULL) + { + /* Disable kssl_check_authent for ENCTYPE_DES3_CBC_SHA1. + ** This enctype indicates the authenticator was encrypted + ** using key-usage derived keys which openssl cannot decrypt. + */ + goto err; + } + + if (!EVP_CipherInit(&ciph_ctx,enc,kssl_ctx->key,iv,0)) + { + kssl_err_set(kssl_err, SSL_R_KRB5_S_INIT, + "EVP_CipherInit error decrypting authenticator.\n"); + krb5rc = KRB5KRB_AP_ERR_BAD_INTEGRITY; + goto err; + } + outl = dec_authent->cipher->length; + if (!EVP_Cipher(&ciph_ctx,unenc_authent,dec_authent->cipher->data,outl)) + { + kssl_err_set(kssl_err, SSL_R_KRB5_S_INIT, + "EVP_Cipher error decrypting authenticator.\n"); + krb5rc = KRB5KRB_AP_ERR_BAD_INTEGRITY; + goto err; + } + EVP_CIPHER_CTX_cleanup(&ciph_ctx); + +#ifdef KSSL_DEBUG + { + int padl; + printf("kssl_check_authent: decrypted authenticator[%d] =\n", outl); + for (padl=0; padl < outl; padl++) printf("%02x ",unenc_authent[padl]); + printf("\n"); + } +#endif /* KSSL_DEBUG */ + + if ((p = kssl_skip_confound(enctype, unenc_authent)) == NULL) + { + kssl_err_set(kssl_err, SSL_R_KRB5_S_INIT, + "confounded by authenticator.\n"); + krb5rc = KRB5KRB_AP_ERR_BAD_INTEGRITY; + goto err; + } + outl -= p - unenc_authent; + + if ((auth = (KRB5_AUTHENTBODY *) d2i_KRB5_AUTHENT(NULL, &p, + (long) outl))==NULL) + { + kssl_err_set(kssl_err, SSL_R_KRB5_S_INIT, + "Error decoding authenticator body.\n"); + krb5rc = KRB5KRB_AP_ERR_BAD_INTEGRITY; + goto err; + } + + memset(&tm_time,0,sizeof(struct tm)); + if (k_gmtime(auth->ctime, &tm_time) && + ((tr = mktime(&tm_time)) != (time_t)(-1))) + { + now = time(&now); + tm_l = localtime(&now); tl = mktime(tm_l); + tm_g = gmtime(&now); tg = mktime(tm_g); + tz_offset = tg - tl; + + *atimep = (krb5_timestamp)(tr - tz_offset); + } + +#ifdef KSSL_DEBUG + printf("kssl_check_authent: returns %d for client time ", *atimep); + if (auth && auth->ctime && auth->ctime->length && auth->ctime->data) + printf("%.*s\n", auth->ctime->length, auth->ctime->data); + else printf("NULL\n"); +#endif /* KSSL_DEBUG */ + + err: + if (auth) KRB5_AUTHENT_free((KRB5_AUTHENT *) auth); + if (dec_authent) KRB5_ENCDATA_free(dec_authent); + if (unenc_authent) free(unenc_authent); + EVP_CIPHER_CTX_cleanup(&ciph_ctx); + return krb5rc; + } + + +/* Replaces krb5_build_principal_ext(), with varargs length == 2 (svc, host), +** because I dont't know how to stub varargs. +** Returns krb5_error_code == ENOMEM on alloc error, otherwise +** passes back newly constructed principal, which should be freed by caller. +*/ +krb5_error_code kssl_build_principal_2( + /* UPDATE */ krb5_context context, + /* OUT */ krb5_principal *princ, + /* IN */ int rlen, const char *realm, + /* IN */ int slen, const char *svc, + /* IN */ int hlen, const char *host) + { + krb5_data *p_data = NULL; + krb5_principal new_p = NULL; + char *new_r = NULL; + + if ((p_data = (krb5_data *) calloc(2, sizeof(krb5_data))) == NULL || + (new_p = (krb5_principal) calloc(1, sizeof(krb5_principal_data))) + == NULL) goto err; + new_p->length = 2; + new_p->data = p_data; + + if ((new_r = calloc(1, rlen + 1)) == NULL) goto err; + memcpy(new_r, realm, rlen); + krb5_princ_set_realm_length(context, new_p, rlen); + krb5_princ_set_realm_data(context, new_p, new_r); + + if ((new_p->data[0].data = calloc(1, slen + 1)) == NULL) goto err; + memcpy(new_p->data[0].data, svc, slen); + new_p->data[0].length = slen; + + if ((new_p->data[1].data = calloc(1, hlen + 1)) == NULL) goto err; + memcpy(new_p->data[1].data, host, hlen); + new_p->data[1].length = hlen; + + krb5_princ_type(context, new_p) = KRB5_NT_UNKNOWN; + *princ = new_p; + return 0; + + err: + if (new_p && new_p[0].data) free(new_p[0].data); + if (new_p && new_p[1].data) free(new_p[1].data); + if (new_p) free(new_p); + if (new_r) free(new_r); + return ENOMEM; + } + + +#else /* !OPENSSL_NO_KRB5 */ + +#if defined(PEDANTIC) || defined(OPENSSL_SYS_VMS) +static void *dummy=&dummy; +#endif + +#endif /* !OPENSSL_NO_KRB5 */ + diff --git a/node-v0.8.14/deps/openssl/openssl/ssl/kssl.h b/node-v0.8.14/deps/openssl/openssl/ssl/kssl.h new file mode 100644 index 0000000..a3d20e1 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/ssl/kssl.h @@ -0,0 +1,179 @@ +/* ssl/kssl.h -*- mode: C; c-file-style: "eay" -*- */ +/* Written by Vern Staats for the OpenSSL project 2000. + * project 2000. + */ +/* ==================================================================== + * Copyright (c) 2000 The OpenSSL Project. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. All advertising materials mentioning features or use of this + * software must display the following acknowledgment: + * "This product includes software developed by the OpenSSL Project + * for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)" + * + * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to + * endorse or promote products derived from this software without + * prior written permission. For written permission, please contact + * licensing@OpenSSL.org. + * + * 5. Products derived from this software may not be called "OpenSSL" + * nor may "OpenSSL" appear in their names without prior written + * permission of the OpenSSL Project. + * + * 6. Redistributions of any form whatsoever must retain the following + * acknowledgment: + * "This product includes software developed by the OpenSSL Project + * for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)" + * + * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY + * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR + * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, + * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * ==================================================================== + * + * This product includes cryptographic software written by Eric Young + * (eay@cryptsoft.com). This product includes software written by Tim + * Hudson (tjh@cryptsoft.com). + * + */ + +/* +** 19990701 VRS Started. +*/ + +#ifndef KSSL_H +#define KSSL_H + +#include + +#ifndef OPENSSL_NO_KRB5 + +#include +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/* +** Depending on which KRB5 implementation used, some types from +** the other may be missing. Resolve that here and now +*/ +#ifdef KRB5_HEIMDAL +typedef unsigned char krb5_octet; +#define FAR +#else + +#ifndef FAR +#define FAR +#endif + +#endif + +/* Uncomment this to debug kssl problems or +** to trace usage of the Kerberos session key +** +** #define KSSL_DEBUG +*/ + +#ifndef KRB5SVC +#define KRB5SVC "host" +#endif + +#ifndef KRB5KEYTAB +#define KRB5KEYTAB "/etc/krb5.keytab" +#endif + +#ifndef KRB5SENDAUTH +#define KRB5SENDAUTH 1 +#endif + +#ifndef KRB5CHECKAUTH +#define KRB5CHECKAUTH 1 +#endif + +#ifndef KSSL_CLOCKSKEW +#define KSSL_CLOCKSKEW 300; +#endif + +#define KSSL_ERR_MAX 255 +typedef struct kssl_err_st { + int reason; + char text[KSSL_ERR_MAX+1]; + } KSSL_ERR; + + +/* Context for passing +** (1) Kerberos session key to SSL, and +** (2) Config data between application and SSL lib +*/ +typedef struct kssl_ctx_st + { + /* used by: disposition: */ + char *service_name; /* C,S default ok (kssl) */ + char *service_host; /* C input, REQUIRED */ + char *client_princ; /* S output from krb5 ticket */ + char *keytab_file; /* S NULL (/etc/krb5.keytab) */ + char *cred_cache; /* C NULL (default) */ + krb5_enctype enctype; + int length; + krb5_octet FAR *key; + } KSSL_CTX; + +#define KSSL_CLIENT 1 +#define KSSL_SERVER 2 +#define KSSL_SERVICE 3 +#define KSSL_KEYTAB 4 + +#define KSSL_CTX_OK 0 +#define KSSL_CTX_ERR 1 +#define KSSL_NOMEM 2 + +/* Public (for use by applications that use OpenSSL with Kerberos 5 support */ +krb5_error_code kssl_ctx_setstring(KSSL_CTX *kssl_ctx, int which, char *text); +KSSL_CTX *kssl_ctx_new(void); +KSSL_CTX *kssl_ctx_free(KSSL_CTX *kssl_ctx); +void kssl_ctx_show(KSSL_CTX *kssl_ctx); +krb5_error_code kssl_ctx_setprinc(KSSL_CTX *kssl_ctx, int which, + krb5_data *realm, krb5_data *entity, int nentities); +krb5_error_code kssl_cget_tkt(KSSL_CTX *kssl_ctx, krb5_data **enc_tktp, + krb5_data *authenp, KSSL_ERR *kssl_err); +krb5_error_code kssl_sget_tkt(KSSL_CTX *kssl_ctx, krb5_data *indata, + krb5_ticket_times *ttimes, KSSL_ERR *kssl_err); +krb5_error_code kssl_ctx_setkey(KSSL_CTX *kssl_ctx, krb5_keyblock *session); +void kssl_err_set(KSSL_ERR *kssl_err, int reason, char *text); +void kssl_krb5_free_data_contents(krb5_context context, krb5_data *data); +krb5_error_code kssl_build_principal_2(krb5_context context, + krb5_principal *princ, int rlen, const char *realm, + int slen, const char *svc, int hlen, const char *host); +krb5_error_code kssl_validate_times(krb5_timestamp atime, + krb5_ticket_times *ttimes); +krb5_error_code kssl_check_authent(KSSL_CTX *kssl_ctx, krb5_data *authentp, + krb5_timestamp *atimep, KSSL_ERR *kssl_err); +unsigned char *kssl_skip_confound(krb5_enctype enctype, unsigned char *authn); + +#ifdef __cplusplus +} +#endif +#endif /* OPENSSL_NO_KRB5 */ +#endif /* KSSL_H */ diff --git a/node-v0.8.14/deps/openssl/openssl/ssl/kssl_lcl.h b/node-v0.8.14/deps/openssl/openssl/ssl/kssl_lcl.h new file mode 100644 index 0000000..c039c91 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/ssl/kssl_lcl.h @@ -0,0 +1,87 @@ +/* ssl/kssl.h -*- mode: C; c-file-style: "eay" -*- */ +/* Written by Vern Staats for the OpenSSL project 2000. + * project 2000. + */ +/* ==================================================================== + * Copyright (c) 2000 The OpenSSL Project. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. All advertising materials mentioning features or use of this + * software must display the following acknowledgment: + * "This product includes software developed by the OpenSSL Project + * for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)" + * + * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to + * endorse or promote products derived from this software without + * prior written permission. For written permission, please contact + * licensing@OpenSSL.org. + * + * 5. Products derived from this software may not be called "OpenSSL" + * nor may "OpenSSL" appear in their names without prior written + * permission of the OpenSSL Project. + * + * 6. Redistributions of any form whatsoever must retain the following + * acknowledgment: + * "This product includes software developed by the OpenSSL Project + * for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)" + * + * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY + * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR + * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, + * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * ==================================================================== + * + * This product includes cryptographic software written by Eric Young + * (eay@cryptsoft.com). This product includes software written by Tim + * Hudson (tjh@cryptsoft.com). + * + */ + +#ifndef KSSL_LCL_H +#define KSSL_LCL_H + +#include + +#ifndef OPENSSL_NO_KRB5 + +#ifdef __cplusplus +extern "C" { +#endif + +/* Private (internal to OpenSSL) */ +void print_krb5_data(char *label, krb5_data *kdata); +void print_krb5_authdata(char *label, krb5_authdata **adata); +void print_krb5_keyblock(char *label, krb5_keyblock *keyblk); + +char *kstring(char *string); +char *knumber(int len, krb5_octet *contents); + +const EVP_CIPHER *kssl_map_enc(krb5_enctype enctype); + +int kssl_keytab_is_available(KSSL_CTX *kssl_ctx); +int kssl_tgt_is_available(KSSL_CTX *kssl_ctx); + +#ifdef __cplusplus +} +#endif +#endif /* OPENSSL_NO_KRB5 */ +#endif /* KSSL_LCL_H */ diff --git a/node-v0.8.14/deps/openssl/openssl/ssl/s23_clnt.c b/node-v0.8.14/deps/openssl/openssl/ssl/s23_clnt.c new file mode 100644 index 0000000..f41fe3a --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/ssl/s23_clnt.c @@ -0,0 +1,703 @@ +/* ssl/s23_clnt.c */ +/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com) + * All rights reserved. + * + * This package is an SSL implementation written + * by Eric Young (eay@cryptsoft.com). + * The implementation was written so as to conform with Netscapes SSL. + * + * This library is free for commercial and non-commercial use as long as + * the following conditions are aheared to. The following conditions + * apply to all code found in this distribution, be it the RC4, RSA, + * lhash, DES, etc., code; not just the SSL code. The SSL documentation + * included with this distribution is covered by the same copyright terms + * except that the holder is Tim Hudson (tjh@cryptsoft.com). + * + * Copyright remains Eric Young's, and as such any Copyright notices in + * the code are not to be removed. + * If this package is used in a product, Eric Young should be given attribution + * as the author of the parts of the library used. + * This can be in the form of a textual message at program startup or + * in documentation (online or textual) provided with the package. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * "This product includes cryptographic software written by + * Eric Young (eay@cryptsoft.com)" + * The word 'cryptographic' can be left out if the rouines from the library + * being used are not cryptographic related :-). + * 4. If you include any Windows specific code (or a derivative thereof) from + * the apps directory (application code) you must include an acknowledgement: + * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)" + * + * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * + * The licence and distribution terms for any publically available version or + * derivative of this code cannot be changed. i.e. this code cannot simply be + * copied and put under another distribution licence + * [including the GNU Public Licence.] + */ +/* ==================================================================== + * Copyright (c) 1998-2006 The OpenSSL Project. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. All advertising materials mentioning features or use of this + * software must display the following acknowledgment: + * "This product includes software developed by the OpenSSL Project + * for use in the OpenSSL Toolkit. (http://www.openssl.org/)" + * + * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to + * endorse or promote products derived from this software without + * prior written permission. For written permission, please contact + * openssl-core@openssl.org. + * + * 5. Products derived from this software may not be called "OpenSSL" + * nor may "OpenSSL" appear in their names without prior written + * permission of the OpenSSL Project. + * + * 6. Redistributions of any form whatsoever must retain the following + * acknowledgment: + * "This product includes software developed by the OpenSSL Project + * for use in the OpenSSL Toolkit (http://www.openssl.org/)" + * + * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY + * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR + * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, + * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * ==================================================================== + * + * This product includes cryptographic software written by Eric Young + * (eay@cryptsoft.com). This product includes software written by Tim + * Hudson (tjh@cryptsoft.com). + * + */ + +#include +#include "ssl_locl.h" +#include +#include +#include +#include + +static const SSL_METHOD *ssl23_get_client_method(int ver); +static int ssl23_client_hello(SSL *s); +static int ssl23_get_server_hello(SSL *s); +static const SSL_METHOD *ssl23_get_client_method(int ver) + { +#ifndef OPENSSL_NO_SSL2 + if (ver == SSL2_VERSION) + return(SSLv2_client_method()); +#endif + if (ver == SSL3_VERSION) + return(SSLv3_client_method()); + else if (ver == TLS1_VERSION) + return(TLSv1_client_method()); + else + return(NULL); + } + +IMPLEMENT_ssl23_meth_func(SSLv23_client_method, + ssl_undefined_function, + ssl23_connect, + ssl23_get_client_method) + +int ssl23_connect(SSL *s) + { + BUF_MEM *buf=NULL; + unsigned long Time=(unsigned long)time(NULL); + void (*cb)(const SSL *ssl,int type,int val)=NULL; + int ret= -1; + int new_state,state; + + RAND_add(&Time,sizeof(Time),0); + ERR_clear_error(); + clear_sys_error(); + + if (s->info_callback != NULL) + cb=s->info_callback; + else if (s->ctx->info_callback != NULL) + cb=s->ctx->info_callback; + + s->in_handshake++; + if (!SSL_in_init(s) || SSL_in_before(s)) SSL_clear(s); + + for (;;) + { + state=s->state; + + switch(s->state) + { + case SSL_ST_BEFORE: + case SSL_ST_CONNECT: + case SSL_ST_BEFORE|SSL_ST_CONNECT: + case SSL_ST_OK|SSL_ST_CONNECT: + + if (s->session != NULL) + { + SSLerr(SSL_F_SSL23_CONNECT,SSL_R_SSL23_DOING_SESSION_ID_REUSE); + ret= -1; + goto end; + } + s->server=0; + if (cb != NULL) cb(s,SSL_CB_HANDSHAKE_START,1); + + /* s->version=TLS1_VERSION; */ + s->type=SSL_ST_CONNECT; + + if (s->init_buf == NULL) + { + if ((buf=BUF_MEM_new()) == NULL) + { + ret= -1; + goto end; + } + if (!BUF_MEM_grow(buf,SSL3_RT_MAX_PLAIN_LENGTH)) + { + ret= -1; + goto end; + } + s->init_buf=buf; + buf=NULL; + } + + if (!ssl3_setup_buffers(s)) { ret= -1; goto end; } + + ssl3_init_finished_mac(s); + + s->state=SSL23_ST_CW_CLNT_HELLO_A; + s->ctx->stats.sess_connect++; + s->init_num=0; + break; + + case SSL23_ST_CW_CLNT_HELLO_A: + case SSL23_ST_CW_CLNT_HELLO_B: + + s->shutdown=0; + ret=ssl23_client_hello(s); + if (ret <= 0) goto end; + s->state=SSL23_ST_CR_SRVR_HELLO_A; + s->init_num=0; + + break; + + case SSL23_ST_CR_SRVR_HELLO_A: + case SSL23_ST_CR_SRVR_HELLO_B: + ret=ssl23_get_server_hello(s); + if (ret >= 0) cb=NULL; + goto end; + /* break; */ + + default: + SSLerr(SSL_F_SSL23_CONNECT,SSL_R_UNKNOWN_STATE); + ret= -1; + goto end; + /* break; */ + } + + if (s->debug) { (void)BIO_flush(s->wbio); } + + if ((cb != NULL) && (s->state != state)) + { + new_state=s->state; + s->state=state; + cb(s,SSL_CB_CONNECT_LOOP,1); + s->state=new_state; + } + } +end: + s->in_handshake--; + if (buf != NULL) + BUF_MEM_free(buf); + if (cb != NULL) + cb(s,SSL_CB_CONNECT_EXIT,ret); + return(ret); + } + +static int ssl23_no_ssl2_ciphers(SSL *s) + { + SSL_CIPHER *cipher; + STACK_OF(SSL_CIPHER) *ciphers; + int i; + ciphers = SSL_get_ciphers(s); + for (i = 0; i < sk_SSL_CIPHER_num(ciphers); i++) + { + cipher = sk_SSL_CIPHER_value(ciphers, i); + if (cipher->algorithm_ssl == SSL_SSLV2) + return 0; + } + return 1; + } + +static int ssl23_client_hello(SSL *s) + { + unsigned char *buf; + unsigned char *p,*d; + int i,ch_len; + unsigned long Time,l; + int ssl2_compat; + int version = 0, version_major, version_minor; +#ifndef OPENSSL_NO_COMP + int j; + SSL_COMP *comp; +#endif + int ret; + + ssl2_compat = (s->options & SSL_OP_NO_SSLv2) ? 0 : 1; + + if (ssl2_compat && ssl23_no_ssl2_ciphers(s)) + ssl2_compat = 0; + + if (!(s->options & SSL_OP_NO_TLSv1)) + { + version = TLS1_VERSION; + } + else if (!(s->options & SSL_OP_NO_SSLv3)) + { + version = SSL3_VERSION; + } + else if (!(s->options & SSL_OP_NO_SSLv2)) + { + version = SSL2_VERSION; + } +#ifndef OPENSSL_NO_TLSEXT + if (version != SSL2_VERSION) + { + /* have to disable SSL 2.0 compatibility if we need TLS extensions */ + + if (s->tlsext_hostname != NULL) + ssl2_compat = 0; + if (s->tlsext_status_type != -1) + ssl2_compat = 0; +#ifdef TLSEXT_TYPE_opaque_prf_input + if (s->ctx->tlsext_opaque_prf_input_callback != 0 || s->tlsext_opaque_prf_input != NULL) + ssl2_compat = 0; +#endif + } +#endif + + buf=(unsigned char *)s->init_buf->data; + if (s->state == SSL23_ST_CW_CLNT_HELLO_A) + { +#if 0 + /* don't reuse session-id's */ + if (!ssl_get_new_session(s,0)) + { + return(-1); + } +#endif + + p=s->s3->client_random; + Time=(unsigned long)time(NULL); /* Time */ + l2n(Time,p); + if (RAND_pseudo_bytes(p,SSL3_RANDOM_SIZE-4) <= 0) + return -1; + + if (version == TLS1_VERSION) + { + version_major = TLS1_VERSION_MAJOR; + version_minor = TLS1_VERSION_MINOR; + } + else if (version == SSL3_VERSION) + { + version_major = SSL3_VERSION_MAJOR; + version_minor = SSL3_VERSION_MINOR; + } + else if (version == SSL2_VERSION) + { + version_major = SSL2_VERSION_MAJOR; + version_minor = SSL2_VERSION_MINOR; + } + else + { + SSLerr(SSL_F_SSL23_CLIENT_HELLO,SSL_R_NO_PROTOCOLS_AVAILABLE); + return(-1); + } + + s->client_version = version; + + if (ssl2_compat) + { + /* create SSL 2.0 compatible Client Hello */ + + /* two byte record header will be written last */ + d = &(buf[2]); + p = d + 9; /* leave space for message type, version, individual length fields */ + + *(d++) = SSL2_MT_CLIENT_HELLO; + *(d++) = version_major; + *(d++) = version_minor; + + /* Ciphers supported */ + i=ssl_cipher_list_to_bytes(s,SSL_get_ciphers(s),p,0); + if (i == 0) + { + /* no ciphers */ + SSLerr(SSL_F_SSL23_CLIENT_HELLO,SSL_R_NO_CIPHERS_AVAILABLE); + return -1; + } + s2n(i,d); + p+=i; + + /* put in the session-id length (zero since there is no reuse) */ +#if 0 + s->session->session_id_length=0; +#endif + s2n(0,d); + + if (s->options & SSL_OP_NETSCAPE_CHALLENGE_BUG) + ch_len=SSL2_CHALLENGE_LENGTH; + else + ch_len=SSL2_MAX_CHALLENGE_LENGTH; + + /* write out sslv2 challenge */ + /* Note that ch_len must be <= SSL3_RANDOM_SIZE (32), + because it is one of SSL2_MAX_CHALLENGE_LENGTH (32) + or SSL2_MAX_CHALLENGE_LENGTH (16), but leave the + check in for futurproofing */ + if (SSL3_RANDOM_SIZE < ch_len) + i=SSL3_RANDOM_SIZE; + else + i=ch_len; + s2n(i,d); + memset(&(s->s3->client_random[0]),0,SSL3_RANDOM_SIZE); + if (RAND_pseudo_bytes(&(s->s3->client_random[SSL3_RANDOM_SIZE-i]),i) <= 0) + return -1; + + memcpy(p,&(s->s3->client_random[SSL3_RANDOM_SIZE-i]),i); + p+=i; + + i= p- &(buf[2]); + buf[0]=((i>>8)&0xff)|0x80; + buf[1]=(i&0xff); + + /* number of bytes to write */ + s->init_num=i+2; + s->init_off=0; + + ssl3_finish_mac(s,&(buf[2]),i); + } + else + { + /* create Client Hello in SSL 3.0/TLS 1.0 format */ + + /* do the record header (5 bytes) and handshake message header (4 bytes) last */ + d = p = &(buf[9]); + + *(p++) = version_major; + *(p++) = version_minor; + + /* Random stuff */ + memcpy(p, s->s3->client_random, SSL3_RANDOM_SIZE); + p += SSL3_RANDOM_SIZE; + + /* Session ID (zero since there is no reuse) */ + *(p++) = 0; + + /* Ciphers supported (using SSL 3.0/TLS 1.0 format) */ + i=ssl_cipher_list_to_bytes(s,SSL_get_ciphers(s),&(p[2]),ssl3_put_cipher_by_char); + if (i == 0) + { + SSLerr(SSL_F_SSL23_CLIENT_HELLO,SSL_R_NO_CIPHERS_AVAILABLE); + return -1; + } + s2n(i,p); + p+=i; + + /* COMPRESSION */ +#ifdef OPENSSL_NO_COMP + *(p++)=1; +#else + if ((s->options & SSL_OP_NO_COMPRESSION) + || !s->ctx->comp_methods) + j=0; + else + j=sk_SSL_COMP_num(s->ctx->comp_methods); + *(p++)=1+j; + for (i=0; ictx->comp_methods,i); + *(p++)=comp->id; + } +#endif + *(p++)=0; /* Add the NULL method */ + +#ifndef OPENSSL_NO_TLSEXT + /* TLS extensions*/ + if (ssl_prepare_clienthello_tlsext(s) <= 0) + { + SSLerr(SSL_F_SSL23_CLIENT_HELLO,SSL_R_CLIENTHELLO_TLSEXT); + return -1; + } + if ((p = ssl_add_clienthello_tlsext(s, p, buf+SSL3_RT_MAX_PLAIN_LENGTH)) == NULL) + { + SSLerr(SSL_F_SSL23_CLIENT_HELLO,ERR_R_INTERNAL_ERROR); + return -1; + } +#endif + + l = p-d; + + /* fill in 4-byte handshake header */ + d=&(buf[5]); + *(d++)=SSL3_MT_CLIENT_HELLO; + l2n3(l,d); + + l += 4; + + if (l > SSL3_RT_MAX_PLAIN_LENGTH) + { + SSLerr(SSL_F_SSL23_CLIENT_HELLO,ERR_R_INTERNAL_ERROR); + return -1; + } + + /* fill in 5-byte record header */ + d=buf; + *(d++) = SSL3_RT_HANDSHAKE; + *(d++) = version_major; + *(d++) = version_minor; /* arguably we should send the *lowest* suported version here + * (indicating, e.g., TLS 1.0 in "SSL 3.0 format") */ + s2n((int)l,d); + + /* number of bytes to write */ + s->init_num=p-buf; + s->init_off=0; + + ssl3_finish_mac(s,&(buf[5]), s->init_num - 5); + } + + s->state=SSL23_ST_CW_CLNT_HELLO_B; + s->init_off=0; + } + + /* SSL3_ST_CW_CLNT_HELLO_B */ + ret = ssl23_write_bytes(s); + + if ((ret >= 2) && s->msg_callback) + { + /* Client Hello has been sent; tell msg_callback */ + + if (ssl2_compat) + s->msg_callback(1, SSL2_VERSION, 0, s->init_buf->data+2, ret-2, s, s->msg_callback_arg); + else + s->msg_callback(1, version, SSL3_RT_HANDSHAKE, s->init_buf->data+5, ret-5, s, s->msg_callback_arg); + } + + return ret; + } + +static int ssl23_get_server_hello(SSL *s) + { + char buf[8]; + unsigned char *p; + int i; + int n; + + n=ssl23_read_bytes(s,7); + + if (n != 7) return(n); + p=s->packet; + + memcpy(buf,p,n); + + if ((p[0] & 0x80) && (p[2] == SSL2_MT_SERVER_HELLO) && + (p[5] == 0x00) && (p[6] == 0x02)) + { +#ifdef OPENSSL_NO_SSL2 + SSLerr(SSL_F_SSL23_GET_SERVER_HELLO,SSL_R_UNSUPPORTED_PROTOCOL); + goto err; +#else + /* we are talking sslv2 */ + /* we need to clean up the SSLv3 setup and put in the + * sslv2 stuff. */ + int ch_len; + + if (s->options & SSL_OP_NO_SSLv2) + { + SSLerr(SSL_F_SSL23_GET_SERVER_HELLO,SSL_R_UNSUPPORTED_PROTOCOL); + goto err; + } + if (s->s2 == NULL) + { + if (!ssl2_new(s)) + goto err; + } + else + ssl2_clear(s); + + if (s->options & SSL_OP_NETSCAPE_CHALLENGE_BUG) + ch_len=SSL2_CHALLENGE_LENGTH; + else + ch_len=SSL2_MAX_CHALLENGE_LENGTH; + + /* write out sslv2 challenge */ + /* Note that ch_len must be <= SSL3_RANDOM_SIZE (32), because + it is one of SSL2_MAX_CHALLENGE_LENGTH (32) or + SSL2_MAX_CHALLENGE_LENGTH (16), but leave the check in for + futurproofing */ + i=(SSL3_RANDOM_SIZE < ch_len) + ?SSL3_RANDOM_SIZE:ch_len; + s->s2->challenge_length=i; + memcpy(s->s2->challenge, + &(s->s3->client_random[SSL3_RANDOM_SIZE-i]),i); + + if (s->s3 != NULL) ssl3_free(s); + + if (!BUF_MEM_grow_clean(s->init_buf, + SSL2_MAX_RECORD_LENGTH_3_BYTE_HEADER)) + { + SSLerr(SSL_F_SSL23_GET_SERVER_HELLO,ERR_R_BUF_LIB); + goto err; + } + + s->state=SSL2_ST_GET_SERVER_HELLO_A; + if (!(s->client_version == SSL2_VERSION)) + /* use special padding (SSL 3.0 draft/RFC 2246, App. E.2) */ + s->s2->ssl2_rollback=1; + + /* setup the 7 bytes we have read so we get them from + * the sslv2 buffer */ + s->rstate=SSL_ST_READ_HEADER; + s->packet_length=n; + s->packet= &(s->s2->rbuf[0]); + memcpy(s->packet,buf,n); + s->s2->rbuf_left=n; + s->s2->rbuf_offs=0; + + /* we have already written one */ + s->s2->write_sequence=1; + + s->method=SSLv2_client_method(); + s->handshake_func=s->method->ssl_connect; +#endif + } + else if (p[1] == SSL3_VERSION_MAJOR && + (p[2] == SSL3_VERSION_MINOR || p[2] == TLS1_VERSION_MINOR) && + ((p[0] == SSL3_RT_HANDSHAKE && p[5] == SSL3_MT_SERVER_HELLO) || + (p[0] == SSL3_RT_ALERT && p[3] == 0 && p[4] == 2))) + { + /* we have sslv3 or tls1 (server hello or alert) */ + + if ((p[2] == SSL3_VERSION_MINOR) && + !(s->options & SSL_OP_NO_SSLv3)) + { + s->version=SSL3_VERSION; + s->method=SSLv3_client_method(); + } + else if ((p[2] == TLS1_VERSION_MINOR) && + !(s->options & SSL_OP_NO_TLSv1)) + { + s->version=TLS1_VERSION; + s->method=TLSv1_client_method(); + } + else + { + SSLerr(SSL_F_SSL23_GET_SERVER_HELLO,SSL_R_UNSUPPORTED_PROTOCOL); + goto err; + } + + if (p[0] == SSL3_RT_ALERT && p[5] != SSL3_AL_WARNING) + { + /* fatal alert */ + + void (*cb)(const SSL *ssl,int type,int val)=NULL; + int j; + + if (s->info_callback != NULL) + cb=s->info_callback; + else if (s->ctx->info_callback != NULL) + cb=s->ctx->info_callback; + + i=p[5]; + if (cb != NULL) + { + j=(i<<8)|p[6]; + cb(s,SSL_CB_READ_ALERT,j); + } + + if (s->msg_callback) + s->msg_callback(0, s->version, SSL3_RT_ALERT, p+5, 2, s, s->msg_callback_arg); + + s->rwstate=SSL_NOTHING; + SSLerr(SSL_F_SSL23_GET_SERVER_HELLO,SSL_AD_REASON_OFFSET+p[6]); + goto err; + } + + if (!ssl_init_wbio_buffer(s,1)) goto err; + + /* we are in this state */ + s->state=SSL3_ST_CR_SRVR_HELLO_A; + + /* put the 7 bytes we have read into the input buffer + * for SSLv3 */ + s->rstate=SSL_ST_READ_HEADER; + s->packet_length=n; + if (s->s3->rbuf.buf == NULL) + if (!ssl3_setup_read_buffer(s)) + goto err; + s->packet= &(s->s3->rbuf.buf[0]); + memcpy(s->packet,buf,n); + s->s3->rbuf.left=n; + s->s3->rbuf.offset=0; + + s->handshake_func=s->method->ssl_connect; + } + else + { + SSLerr(SSL_F_SSL23_GET_SERVER_HELLO,SSL_R_UNKNOWN_PROTOCOL); + goto err; + } + s->init_num=0; + + /* Since, if we are sending a ssl23 client hello, we are not + * reusing a session-id */ + if (!s->session_creation_enabled) + { + if (!(s->client_version == SSL2_VERSION)) + ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_HANDSHAKE_FAILURE); + SSLerr(SSL_F_SSL23_GET_SERVER_HELLO,SSL_R_SESSION_MAY_NOT_BE_CREATED); + goto err; + } + if (!ssl_get_new_session(s,0)) + goto err; + + return(SSL_connect(s)); +err: + return(-1); + } diff --git a/node-v0.8.14/deps/openssl/openssl/ssl/s23_lib.c b/node-v0.8.14/deps/openssl/openssl/ssl/s23_lib.c new file mode 100644 index 0000000..3bf7283 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/ssl/s23_lib.c @@ -0,0 +1,187 @@ +/* ssl/s23_lib.c */ +/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com) + * All rights reserved. + * + * This package is an SSL implementation written + * by Eric Young (eay@cryptsoft.com). + * The implementation was written so as to conform with Netscapes SSL. + * + * This library is free for commercial and non-commercial use as long as + * the following conditions are aheared to. The following conditions + * apply to all code found in this distribution, be it the RC4, RSA, + * lhash, DES, etc., code; not just the SSL code. The SSL documentation + * included with this distribution is covered by the same copyright terms + * except that the holder is Tim Hudson (tjh@cryptsoft.com). + * + * Copyright remains Eric Young's, and as such any Copyright notices in + * the code are not to be removed. + * If this package is used in a product, Eric Young should be given attribution + * as the author of the parts of the library used. + * This can be in the form of a textual message at program startup or + * in documentation (online or textual) provided with the package. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * "This product includes cryptographic software written by + * Eric Young (eay@cryptsoft.com)" + * The word 'cryptographic' can be left out if the rouines from the library + * being used are not cryptographic related :-). + * 4. If you include any Windows specific code (or a derivative thereof) from + * the apps directory (application code) you must include an acknowledgement: + * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)" + * + * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * + * The licence and distribution terms for any publically available version or + * derivative of this code cannot be changed. i.e. this code cannot simply be + * copied and put under another distribution licence + * [including the GNU Public Licence.] + */ + +#include +#include +#include "ssl_locl.h" + +long ssl23_default_timeout(void) + { + return(300); + } + +int ssl23_num_ciphers(void) + { + return(ssl3_num_ciphers() +#ifndef OPENSSL_NO_SSL2 + + ssl2_num_ciphers() +#endif + ); + } + +const SSL_CIPHER *ssl23_get_cipher(unsigned int u) + { + unsigned int uu=ssl3_num_ciphers(); + + if (u < uu) + return(ssl3_get_cipher(u)); + else +#ifndef OPENSSL_NO_SSL2 + return(ssl2_get_cipher(u-uu)); +#else + return(NULL); +#endif + } + +/* This function needs to check if the ciphers required are actually + * available */ +const SSL_CIPHER *ssl23_get_cipher_by_char(const unsigned char *p) + { + const SSL_CIPHER *cp; + + cp=ssl3_get_cipher_by_char(p); +#ifndef OPENSSL_NO_SSL2 + if (cp == NULL) + cp=ssl2_get_cipher_by_char(p); +#endif + return(cp); + } + +int ssl23_put_cipher_by_char(const SSL_CIPHER *c, unsigned char *p) + { + long l; + + /* We can write SSLv2 and SSLv3 ciphers */ + if (p != NULL) + { + l=c->id; + p[0]=((unsigned char)(l>>16L))&0xFF; + p[1]=((unsigned char)(l>> 8L))&0xFF; + p[2]=((unsigned char)(l ))&0xFF; + } + return(3); + } + +int ssl23_read(SSL *s, void *buf, int len) + { + int n; + + clear_sys_error(); + if (SSL_in_init(s) && (!s->in_handshake)) + { + n=s->handshake_func(s); + if (n < 0) return(n); + if (n == 0) + { + SSLerr(SSL_F_SSL23_READ,SSL_R_SSL_HANDSHAKE_FAILURE); + return(-1); + } + return(SSL_read(s,buf,len)); + } + else + { + ssl_undefined_function(s); + return(-1); + } + } + +int ssl23_peek(SSL *s, void *buf, int len) + { + int n; + + clear_sys_error(); + if (SSL_in_init(s) && (!s->in_handshake)) + { + n=s->handshake_func(s); + if (n < 0) return(n); + if (n == 0) + { + SSLerr(SSL_F_SSL23_PEEK,SSL_R_SSL_HANDSHAKE_FAILURE); + return(-1); + } + return(SSL_peek(s,buf,len)); + } + else + { + ssl_undefined_function(s); + return(-1); + } + } + +int ssl23_write(SSL *s, const void *buf, int len) + { + int n; + + clear_sys_error(); + if (SSL_in_init(s) && (!s->in_handshake)) + { + n=s->handshake_func(s); + if (n < 0) return(n); + if (n == 0) + { + SSLerr(SSL_F_SSL23_WRITE,SSL_R_SSL_HANDSHAKE_FAILURE); + return(-1); + } + return(SSL_write(s,buf,len)); + } + else + { + ssl_undefined_function(s); + return(-1); + } + } diff --git a/node-v0.8.14/deps/openssl/openssl/ssl/s23_meth.c b/node-v0.8.14/deps/openssl/openssl/ssl/s23_meth.c new file mode 100644 index 0000000..c6099ef --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/ssl/s23_meth.c @@ -0,0 +1,88 @@ +/* ssl/s23_meth.c */ +/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com) + * All rights reserved. + * + * This package is an SSL implementation written + * by Eric Young (eay@cryptsoft.com). + * The implementation was written so as to conform with Netscapes SSL. + * + * This library is free for commercial and non-commercial use as long as + * the following conditions are aheared to. The following conditions + * apply to all code found in this distribution, be it the RC4, RSA, + * lhash, DES, etc., code; not just the SSL code. The SSL documentation + * included with this distribution is covered by the same copyright terms + * except that the holder is Tim Hudson (tjh@cryptsoft.com). + * + * Copyright remains Eric Young's, and as such any Copyright notices in + * the code are not to be removed. + * If this package is used in a product, Eric Young should be given attribution + * as the author of the parts of the library used. + * This can be in the form of a textual message at program startup or + * in documentation (online or textual) provided with the package. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * "This product includes cryptographic software written by + * Eric Young (eay@cryptsoft.com)" + * The word 'cryptographic' can be left out if the rouines from the library + * being used are not cryptographic related :-). + * 4. If you include any Windows specific code (or a derivative thereof) from + * the apps directory (application code) you must include an acknowledgement: + * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)" + * + * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * + * The licence and distribution terms for any publically available version or + * derivative of this code cannot be changed. i.e. this code cannot simply be + * copied and put under another distribution licence + * [including the GNU Public Licence.] + */ + +#include +#include +#include "ssl_locl.h" + +static const SSL_METHOD *ssl23_get_method(int ver); +static const SSL_METHOD *ssl23_get_method(int ver) + { +#ifndef OPENSSL_NO_SSL2 + if (ver == SSL2_VERSION) + return(SSLv2_method()); + else +#endif +#ifndef OPENSSL_NO_SSL3 + if (ver == SSL3_VERSION) + return(SSLv3_method()); + else +#endif +#ifndef OPENSSL_NO_TLS1 + if (ver == TLS1_VERSION) + return(TLSv1_method()); + else +#endif + return(NULL); + } + +IMPLEMENT_ssl23_meth_func(SSLv23_method, + ssl23_accept, + ssl23_connect, + ssl23_get_method) + diff --git a/node-v0.8.14/deps/openssl/openssl/ssl/s23_pkt.c b/node-v0.8.14/deps/openssl/openssl/ssl/s23_pkt.c new file mode 100644 index 0000000..4ca6a1b --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/ssl/s23_pkt.c @@ -0,0 +1,117 @@ +/* ssl/s23_pkt.c */ +/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com) + * All rights reserved. + * + * This package is an SSL implementation written + * by Eric Young (eay@cryptsoft.com). + * The implementation was written so as to conform with Netscapes SSL. + * + * This library is free for commercial and non-commercial use as long as + * the following conditions are aheared to. The following conditions + * apply to all code found in this distribution, be it the RC4, RSA, + * lhash, DES, etc., code; not just the SSL code. The SSL documentation + * included with this distribution is covered by the same copyright terms + * except that the holder is Tim Hudson (tjh@cryptsoft.com). + * + * Copyright remains Eric Young's, and as such any Copyright notices in + * the code are not to be removed. + * If this package is used in a product, Eric Young should be given attribution + * as the author of the parts of the library used. + * This can be in the form of a textual message at program startup or + * in documentation (online or textual) provided with the package. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * "This product includes cryptographic software written by + * Eric Young (eay@cryptsoft.com)" + * The word 'cryptographic' can be left out if the rouines from the library + * being used are not cryptographic related :-). + * 4. If you include any Windows specific code (or a derivative thereof) from + * the apps directory (application code) you must include an acknowledgement: + * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)" + * + * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * + * The licence and distribution terms for any publically available version or + * derivative of this code cannot be changed. i.e. this code cannot simply be + * copied and put under another distribution licence + * [including the GNU Public Licence.] + */ + +#include +#include +#define USE_SOCKETS +#include "ssl_locl.h" +#include +#include + +int ssl23_write_bytes(SSL *s) + { + int i,num,tot; + char *buf; + + buf=s->init_buf->data; + tot=s->init_off; + num=s->init_num; + for (;;) + { + s->rwstate=SSL_WRITING; + i=BIO_write(s->wbio,&(buf[tot]),num); + if (i <= 0) + { + s->init_off=tot; + s->init_num=num; + return(i); + } + s->rwstate=SSL_NOTHING; + if (i == num) return(tot+i); + + num-=i; + tot+=i; + } + } + +/* return regularly only when we have read (at least) 'n' bytes */ +int ssl23_read_bytes(SSL *s, int n) + { + unsigned char *p; + int j; + + if (s->packet_length < (unsigned int)n) + { + p=s->packet; + + for (;;) + { + s->rwstate=SSL_READING; + j=BIO_read(s->rbio,(char *)&(p[s->packet_length]), + n-s->packet_length); + if (j <= 0) + return(j); + s->rwstate=SSL_NOTHING; + s->packet_length+=j; + if (s->packet_length >= (unsigned int)n) + return(s->packet_length); + } + } + return(n); + } + diff --git a/node-v0.8.14/deps/openssl/openssl/ssl/s23_srvr.c b/node-v0.8.14/deps/openssl/openssl/ssl/s23_srvr.c new file mode 100644 index 0000000..e22879c --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/ssl/s23_srvr.c @@ -0,0 +1,599 @@ +/* ssl/s23_srvr.c */ +/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com) + * All rights reserved. + * + * This package is an SSL implementation written + * by Eric Young (eay@cryptsoft.com). + * The implementation was written so as to conform with Netscapes SSL. + * + * This library is free for commercial and non-commercial use as long as + * the following conditions are aheared to. The following conditions + * apply to all code found in this distribution, be it the RC4, RSA, + * lhash, DES, etc., code; not just the SSL code. The SSL documentation + * included with this distribution is covered by the same copyright terms + * except that the holder is Tim Hudson (tjh@cryptsoft.com). + * + * Copyright remains Eric Young's, and as such any Copyright notices in + * the code are not to be removed. + * If this package is used in a product, Eric Young should be given attribution + * as the author of the parts of the library used. + * This can be in the form of a textual message at program startup or + * in documentation (online or textual) provided with the package. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * "This product includes cryptographic software written by + * Eric Young (eay@cryptsoft.com)" + * The word 'cryptographic' can be left out if the rouines from the library + * being used are not cryptographic related :-). + * 4. If you include any Windows specific code (or a derivative thereof) from + * the apps directory (application code) you must include an acknowledgement: + * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)" + * + * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * + * The licence and distribution terms for any publically available version or + * derivative of this code cannot be changed. i.e. this code cannot simply be + * copied and put under another distribution licence + * [including the GNU Public Licence.] + */ +/* ==================================================================== + * Copyright (c) 1998-2006 The OpenSSL Project. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. All advertising materials mentioning features or use of this + * software must display the following acknowledgment: + * "This product includes software developed by the OpenSSL Project + * for use in the OpenSSL Toolkit. (http://www.openssl.org/)" + * + * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to + * endorse or promote products derived from this software without + * prior written permission. For written permission, please contact + * openssl-core@openssl.org. + * + * 5. Products derived from this software may not be called "OpenSSL" + * nor may "OpenSSL" appear in their names without prior written + * permission of the OpenSSL Project. + * + * 6. Redistributions of any form whatsoever must retain the following + * acknowledgment: + * "This product includes software developed by the OpenSSL Project + * for use in the OpenSSL Toolkit (http://www.openssl.org/)" + * + * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY + * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR + * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, + * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * ==================================================================== + * + * This product includes cryptographic software written by Eric Young + * (eay@cryptsoft.com). This product includes software written by Tim + * Hudson (tjh@cryptsoft.com). + * + */ + +#include +#include "ssl_locl.h" +#include +#include +#include +#include + +static const SSL_METHOD *ssl23_get_server_method(int ver); +int ssl23_get_client_hello(SSL *s); +static const SSL_METHOD *ssl23_get_server_method(int ver) + { +#ifndef OPENSSL_NO_SSL2 + if (ver == SSL2_VERSION) + return(SSLv2_server_method()); +#endif + if (ver == SSL3_VERSION) + return(SSLv3_server_method()); + else if (ver == TLS1_VERSION) + return(TLSv1_server_method()); + else + return(NULL); + } + +IMPLEMENT_ssl23_meth_func(SSLv23_server_method, + ssl23_accept, + ssl_undefined_function, + ssl23_get_server_method) + +int ssl23_accept(SSL *s) + { + BUF_MEM *buf; + unsigned long Time=(unsigned long)time(NULL); + void (*cb)(const SSL *ssl,int type,int val)=NULL; + int ret= -1; + int new_state,state; + + RAND_add(&Time,sizeof(Time),0); + ERR_clear_error(); + clear_sys_error(); + + if (s->info_callback != NULL) + cb=s->info_callback; + else if (s->ctx->info_callback != NULL) + cb=s->ctx->info_callback; + + s->in_handshake++; + if (!SSL_in_init(s) || SSL_in_before(s)) SSL_clear(s); + + for (;;) + { + state=s->state; + + switch(s->state) + { + case SSL_ST_BEFORE: + case SSL_ST_ACCEPT: + case SSL_ST_BEFORE|SSL_ST_ACCEPT: + case SSL_ST_OK|SSL_ST_ACCEPT: + + s->server=1; + if (cb != NULL) cb(s,SSL_CB_HANDSHAKE_START,1); + + /* s->version=SSL3_VERSION; */ + s->type=SSL_ST_ACCEPT; + + if (s->init_buf == NULL) + { + if ((buf=BUF_MEM_new()) == NULL) + { + ret= -1; + goto end; + } + if (!BUF_MEM_grow(buf,SSL3_RT_MAX_PLAIN_LENGTH)) + { + ret= -1; + goto end; + } + s->init_buf=buf; + } + + ssl3_init_finished_mac(s); + + s->state=SSL23_ST_SR_CLNT_HELLO_A; + s->ctx->stats.sess_accept++; + s->init_num=0; + break; + + case SSL23_ST_SR_CLNT_HELLO_A: + case SSL23_ST_SR_CLNT_HELLO_B: + + s->shutdown=0; + ret=ssl23_get_client_hello(s); + if (ret >= 0) cb=NULL; + goto end; + /* break; */ + + default: + SSLerr(SSL_F_SSL23_ACCEPT,SSL_R_UNKNOWN_STATE); + ret= -1; + goto end; + /* break; */ + } + + if ((cb != NULL) && (s->state != state)) + { + new_state=s->state; + s->state=state; + cb(s,SSL_CB_ACCEPT_LOOP,1); + s->state=new_state; + } + } +end: + s->in_handshake--; + if (cb != NULL) + cb(s,SSL_CB_ACCEPT_EXIT,ret); + return(ret); + } + + +int ssl23_get_client_hello(SSL *s) + { + char buf_space[11]; /* Request this many bytes in initial read. + * We can detect SSL 3.0/TLS 1.0 Client Hellos + * ('type == 3') correctly only when the following + * is in a single record, which is not guaranteed by + * the protocol specification: + * Byte Content + * 0 type \ + * 1/2 version > record header + * 3/4 length / + * 5 msg_type \ + * 6-8 length > Client Hello message + * 9/10 client_version / + */ + char *buf= &(buf_space[0]); + unsigned char *p,*d,*d_len,*dd; + unsigned int i; + unsigned int csl,sil,cl; + int n=0,j; + int type=0; + int v[2]; + + if (s->state == SSL23_ST_SR_CLNT_HELLO_A) + { + /* read the initial header */ + v[0]=v[1]=0; + + if (!ssl3_setup_buffers(s)) goto err; + + n=ssl23_read_bytes(s, sizeof buf_space); + if (n != sizeof buf_space) return(n); /* n == -1 || n == 0 */ + + p=s->packet; + + memcpy(buf,p,n); + + if ((p[0] & 0x80) && (p[2] == SSL2_MT_CLIENT_HELLO)) + { + /* + * SSLv2 header + */ + if ((p[3] == 0x00) && (p[4] == 0x02)) + { + v[0]=p[3]; v[1]=p[4]; + /* SSLv2 */ + if (!(s->options & SSL_OP_NO_SSLv2)) + type=1; + } + else if (p[3] == SSL3_VERSION_MAJOR) + { + v[0]=p[3]; v[1]=p[4]; + /* SSLv3/TLSv1 */ + if (p[4] >= TLS1_VERSION_MINOR) + { + if (!(s->options & SSL_OP_NO_TLSv1)) + { + s->version=TLS1_VERSION; + /* type=2; */ /* done later to survive restarts */ + s->state=SSL23_ST_SR_CLNT_HELLO_B; + } + else if (!(s->options & SSL_OP_NO_SSLv3)) + { + s->version=SSL3_VERSION; + /* type=2; */ + s->state=SSL23_ST_SR_CLNT_HELLO_B; + } + else if (!(s->options & SSL_OP_NO_SSLv2)) + { + type=1; + } + } + else if (!(s->options & SSL_OP_NO_SSLv3)) + { + s->version=SSL3_VERSION; + /* type=2; */ + s->state=SSL23_ST_SR_CLNT_HELLO_B; + } + else if (!(s->options & SSL_OP_NO_SSLv2)) + type=1; + + } + } + else if ((p[0] == SSL3_RT_HANDSHAKE) && + (p[1] == SSL3_VERSION_MAJOR) && + (p[5] == SSL3_MT_CLIENT_HELLO) && + ((p[3] == 0 && p[4] < 5 /* silly record length? */) + || (p[9] >= p[1]))) + { + /* + * SSLv3 or tls1 header + */ + + v[0]=p[1]; /* major version (= SSL3_VERSION_MAJOR) */ + /* We must look at client_version inside the Client Hello message + * to get the correct minor version. + * However if we have only a pathologically small fragment of the + * Client Hello message, this would be difficult, and we'd have + * to read more records to find out. + * No known SSL 3.0 client fragments ClientHello like this, + * so we simply assume TLS 1.0 to avoid protocol version downgrade + * attacks. */ + if (p[3] == 0 && p[4] < 6) + { +#if 0 + SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO,SSL_R_RECORD_TOO_SMALL); + goto err; +#else + v[1] = TLS1_VERSION_MINOR; +#endif + } + /* if major version number > 3 set minor to a value + * which will use the highest version 3 we support. + * If TLS 2.0 ever appears we will need to revise + * this.... + */ + else if (p[9] > SSL3_VERSION_MAJOR) + v[1]=0xff; + else + v[1]=p[10]; /* minor version according to client_version */ + if (v[1] >= TLS1_VERSION_MINOR) + { + if (!(s->options & SSL_OP_NO_TLSv1)) + { + s->version=TLS1_VERSION; + type=3; + } + else if (!(s->options & SSL_OP_NO_SSLv3)) + { + s->version=SSL3_VERSION; + type=3; + } + } + else + { + /* client requests SSL 3.0 */ + if (!(s->options & SSL_OP_NO_SSLv3)) + { + s->version=SSL3_VERSION; + type=3; + } + else if (!(s->options & SSL_OP_NO_TLSv1)) + { + /* we won't be able to use TLS of course, + * but this will send an appropriate alert */ + s->version=TLS1_VERSION; + type=3; + } + } + } + else if ((strncmp("GET ", (char *)p,4) == 0) || + (strncmp("POST ",(char *)p,5) == 0) || + (strncmp("HEAD ",(char *)p,5) == 0) || + (strncmp("PUT ", (char *)p,4) == 0)) + { + SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO,SSL_R_HTTP_REQUEST); + goto err; + } + else if (strncmp("CONNECT",(char *)p,7) == 0) + { + SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO,SSL_R_HTTPS_PROXY_REQUEST); + goto err; + } + } + + if (s->state == SSL23_ST_SR_CLNT_HELLO_B) + { + /* we have SSLv3/TLSv1 in an SSLv2 header + * (other cases skip this state) */ + + type=2; + p=s->packet; + v[0] = p[3]; /* == SSL3_VERSION_MAJOR */ + v[1] = p[4]; + +/* The SSL2 protocol allows n to be larger, just pick + * a reasonable buffer size. */ +#if SSL3_RT_DEFAULT_PACKET_SIZE < 1024*4 - SSL3_RT_DEFAULT_WRITE_OVERHEAD +#error "SSL3_RT_DEFAULT_PACKET_SIZE is too small." +#endif + n=((p[0]&0x7f)<<8)|p[1]; + if (n > SSL3_RT_DEFAULT_PACKET_SIZE - 2) + { + SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO,SSL_R_RECORD_TOO_LARGE); + goto err; + } + + j=ssl23_read_bytes(s,n+2); + if (j <= 0) return(j); + + ssl3_finish_mac(s, s->packet+2, s->packet_length-2); + if (s->msg_callback) + s->msg_callback(0, SSL2_VERSION, 0, s->packet+2, s->packet_length-2, s, s->msg_callback_arg); /* CLIENT-HELLO */ + + p=s->packet; + p+=5; + n2s(p,csl); + n2s(p,sil); + n2s(p,cl); + d=(unsigned char *)s->init_buf->data; + if ((csl+sil+cl+11) != s->packet_length) /* We can't have TLS extensions in SSL 2.0 format + * Client Hello, can we? Error condition should be + * '>' otherweise */ + { + SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO,SSL_R_RECORD_LENGTH_MISMATCH); + goto err; + } + + /* record header: msg_type ... */ + *(d++) = SSL3_MT_CLIENT_HELLO; + /* ... and length (actual value will be written later) */ + d_len = d; + d += 3; + + /* client_version */ + *(d++) = SSL3_VERSION_MAJOR; /* == v[0] */ + *(d++) = v[1]; + + /* lets populate the random area */ + /* get the challenge_length */ + i=(cl > SSL3_RANDOM_SIZE)?SSL3_RANDOM_SIZE:cl; + memset(d,0,SSL3_RANDOM_SIZE); + memcpy(&(d[SSL3_RANDOM_SIZE-i]),&(p[csl+sil]),i); + d+=SSL3_RANDOM_SIZE; + + /* no session-id reuse */ + *(d++)=0; + + /* ciphers */ + j=0; + dd=d; + d+=2; + for (i=0; ipacket+s->packet_length) + { + *(d++)=*(p++); + } +#endif + + i = (d-(unsigned char *)s->init_buf->data) - 4; + l2n3((long)i, d_len); + + /* get the data reused from the init_buf */ + s->s3->tmp.reuse_message=1; + s->s3->tmp.message_type=SSL3_MT_CLIENT_HELLO; + s->s3->tmp.message_size=i; + } + + /* imaginary new state (for program structure): */ + /* s->state = SSL23_SR_CLNT_HELLO_C */ + + if (type == 1) + { +#ifdef OPENSSL_NO_SSL2 + SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO,SSL_R_UNSUPPORTED_PROTOCOL); + goto err; +#else + /* we are talking sslv2 */ + /* we need to clean up the SSLv3/TLSv1 setup and put in the + * sslv2 stuff. */ + + if (s->s2 == NULL) + { + if (!ssl2_new(s)) + goto err; + } + else + ssl2_clear(s); + + if (s->s3 != NULL) ssl3_free(s); + + if (!BUF_MEM_grow_clean(s->init_buf, + SSL2_MAX_RECORD_LENGTH_3_BYTE_HEADER)) + { + goto err; + } + + s->state=SSL2_ST_GET_CLIENT_HELLO_A; + if (s->options & SSL_OP_NO_TLSv1 && s->options & SSL_OP_NO_SSLv3) + s->s2->ssl2_rollback=0; + else + /* reject SSL 2.0 session if client supports SSL 3.0 or TLS 1.0 + * (SSL 3.0 draft/RFC 2246, App. E.2) */ + s->s2->ssl2_rollback=1; + + /* setup the n bytes we have read so we get them from + * the sslv2 buffer */ + s->rstate=SSL_ST_READ_HEADER; + s->packet_length=n; + s->packet= &(s->s2->rbuf[0]); + memcpy(s->packet,buf,n); + s->s2->rbuf_left=n; + s->s2->rbuf_offs=0; + + s->method=SSLv2_server_method(); + s->handshake_func=s->method->ssl_accept; +#endif + } + + if ((type == 2) || (type == 3)) + { + /* we have SSLv3/TLSv1 (type 2: SSL2 style, type 3: SSL3/TLS style) */ + + if (!ssl_init_wbio_buffer(s,1)) goto err; + + /* we are in this state */ + s->state=SSL3_ST_SR_CLNT_HELLO_A; + + if (type == 3) + { + /* put the 'n' bytes we have read into the input buffer + * for SSLv3 */ + s->rstate=SSL_ST_READ_HEADER; + s->packet_length=n; + if (s->s3->rbuf.buf == NULL) + if (!ssl3_setup_read_buffer(s)) + goto err; + + s->packet= &(s->s3->rbuf.buf[0]); + memcpy(s->packet,buf,n); + s->s3->rbuf.left=n; + s->s3->rbuf.offset=0; + } + else + { + s->packet_length=0; + s->s3->rbuf.left=0; + s->s3->rbuf.offset=0; + } + + if (s->version == TLS1_VERSION) + s->method = TLSv1_server_method(); + else + s->method = SSLv3_server_method(); +#if 0 /* ssl3_get_client_hello does this */ + s->client_version=(v[0]<<8)|v[1]; +#endif + s->handshake_func=s->method->ssl_accept; + } + + if ((type < 1) || (type > 3)) + { + /* bad, very bad */ + SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO,SSL_R_UNKNOWN_PROTOCOL); + goto err; + } + s->init_num=0; + + if (buf != buf_space) OPENSSL_free(buf); + return(SSL_accept(s)); +err: + if (buf != buf_space) OPENSSL_free(buf); + return(-1); + } diff --git a/node-v0.8.14/deps/openssl/openssl/ssl/s2_clnt.c b/node-v0.8.14/deps/openssl/openssl/ssl/s2_clnt.c new file mode 100644 index 0000000..00ac158 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/ssl/s2_clnt.c @@ -0,0 +1,1125 @@ +/* ssl/s2_clnt.c */ +/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com) + * All rights reserved. + * + * This package is an SSL implementation written + * by Eric Young (eay@cryptsoft.com). + * The implementation was written so as to conform with Netscapes SSL. + * + * This library is free for commercial and non-commercial use as long as + * the following conditions are aheared to. The following conditions + * apply to all code found in this distribution, be it the RC4, RSA, + * lhash, DES, etc., code; not just the SSL code. The SSL documentation + * included with this distribution is covered by the same copyright terms + * except that the holder is Tim Hudson (tjh@cryptsoft.com). + * + * Copyright remains Eric Young's, and as such any Copyright notices in + * the code are not to be removed. + * If this package is used in a product, Eric Young should be given attribution + * as the author of the parts of the library used. + * This can be in the form of a textual message at program startup or + * in documentation (online or textual) provided with the package. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * "This product includes cryptographic software written by + * Eric Young (eay@cryptsoft.com)" + * The word 'cryptographic' can be left out if the rouines from the library + * being used are not cryptographic related :-). + * 4. If you include any Windows specific code (or a derivative thereof) from + * the apps directory (application code) you must include an acknowledgement: + * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)" + * + * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * + * The licence and distribution terms for any publically available version or + * derivative of this code cannot be changed. i.e. this code cannot simply be + * copied and put under another distribution licence + * [including the GNU Public Licence.] + */ +/* ==================================================================== + * Copyright (c) 1998-2001 The OpenSSL Project. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. All advertising materials mentioning features or use of this + * software must display the following acknowledgment: + * "This product includes software developed by the OpenSSL Project + * for use in the OpenSSL Toolkit. (http://www.openssl.org/)" + * + * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to + * endorse or promote products derived from this software without + * prior written permission. For written permission, please contact + * openssl-core@openssl.org. + * + * 5. Products derived from this software may not be called "OpenSSL" + * nor may "OpenSSL" appear in their names without prior written + * permission of the OpenSSL Project. + * + * 6. Redistributions of any form whatsoever must retain the following + * acknowledgment: + * "This product includes software developed by the OpenSSL Project + * for use in the OpenSSL Toolkit (http://www.openssl.org/)" + * + * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY + * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR + * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, + * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * ==================================================================== + * + * This product includes cryptographic software written by Eric Young + * (eay@cryptsoft.com). This product includes software written by Tim + * Hudson (tjh@cryptsoft.com). + * + */ + +#include "ssl_locl.h" +#ifndef OPENSSL_NO_SSL2 +#include +#include +#include +#include +#include + +static const SSL_METHOD *ssl2_get_client_method(int ver); +static int get_server_finished(SSL *s); +static int get_server_verify(SSL *s); +static int get_server_hello(SSL *s); +static int client_hello(SSL *s); +static int client_master_key(SSL *s); +static int client_finished(SSL *s); +static int client_certificate(SSL *s); +static int ssl_rsa_public_encrypt(SESS_CERT *sc, int len, unsigned char *from, + unsigned char *to,int padding); +#define BREAK break + +static const SSL_METHOD *ssl2_get_client_method(int ver) + { + if (ver == SSL2_VERSION) + return(SSLv2_client_method()); + else + return(NULL); + } + +IMPLEMENT_ssl2_meth_func(SSLv2_client_method, + ssl_undefined_function, + ssl2_connect, + ssl2_get_client_method) + +int ssl2_connect(SSL *s) + { + unsigned long l=(unsigned long)time(NULL); + BUF_MEM *buf=NULL; + int ret= -1; + void (*cb)(const SSL *ssl,int type,int val)=NULL; + int new_state,state; + + RAND_add(&l,sizeof(l),0); + ERR_clear_error(); + clear_sys_error(); + + if (s->info_callback != NULL) + cb=s->info_callback; + else if (s->ctx->info_callback != NULL) + cb=s->ctx->info_callback; + + /* init things to blank */ + s->in_handshake++; + if (!SSL_in_init(s) || SSL_in_before(s)) SSL_clear(s); + + for (;;) + { + state=s->state; + + switch (s->state) + { + case SSL_ST_BEFORE: + case SSL_ST_CONNECT: + case SSL_ST_BEFORE|SSL_ST_CONNECT: + case SSL_ST_OK|SSL_ST_CONNECT: + + s->server=0; + if (cb != NULL) cb(s,SSL_CB_HANDSHAKE_START,1); + + s->version=SSL2_VERSION; + s->type=SSL_ST_CONNECT; + + buf=s->init_buf; + if ((buf == NULL) && ((buf=BUF_MEM_new()) == NULL)) + { + ret= -1; + goto end; + } + if (!BUF_MEM_grow(buf, + SSL2_MAX_RECORD_LENGTH_3_BYTE_HEADER)) + { + if (buf == s->init_buf) + buf=NULL; + ret= -1; + goto end; + } + s->init_buf=buf; + buf=NULL; + s->init_num=0; + s->state=SSL2_ST_SEND_CLIENT_HELLO_A; + s->ctx->stats.sess_connect++; + s->handshake_func=ssl2_connect; + BREAK; + + case SSL2_ST_SEND_CLIENT_HELLO_A: + case SSL2_ST_SEND_CLIENT_HELLO_B: + s->shutdown=0; + ret=client_hello(s); + if (ret <= 0) goto end; + s->init_num=0; + s->state=SSL2_ST_GET_SERVER_HELLO_A; + BREAK; + + case SSL2_ST_GET_SERVER_HELLO_A: + case SSL2_ST_GET_SERVER_HELLO_B: + ret=get_server_hello(s); + if (ret <= 0) goto end; + s->init_num=0; + if (!s->hit) /* new session */ + { + s->state=SSL2_ST_SEND_CLIENT_MASTER_KEY_A; + BREAK; + } + else + { + s->state=SSL2_ST_CLIENT_START_ENCRYPTION; + break; + } + + case SSL2_ST_SEND_CLIENT_MASTER_KEY_A: + case SSL2_ST_SEND_CLIENT_MASTER_KEY_B: + ret=client_master_key(s); + if (ret <= 0) goto end; + s->init_num=0; + s->state=SSL2_ST_CLIENT_START_ENCRYPTION; + break; + + case SSL2_ST_CLIENT_START_ENCRYPTION: + /* Ok, we now have all the stuff needed to + * start encrypting, so lets fire it up :-) */ + if (!ssl2_enc_init(s,1)) + { + ret= -1; + goto end; + } + s->s2->clear_text=0; + s->state=SSL2_ST_SEND_CLIENT_FINISHED_A; + break; + + case SSL2_ST_SEND_CLIENT_FINISHED_A: + case SSL2_ST_SEND_CLIENT_FINISHED_B: + ret=client_finished(s); + if (ret <= 0) goto end; + s->init_num=0; + s->state=SSL2_ST_GET_SERVER_VERIFY_A; + break; + + case SSL2_ST_GET_SERVER_VERIFY_A: + case SSL2_ST_GET_SERVER_VERIFY_B: + ret=get_server_verify(s); + if (ret <= 0) goto end; + s->init_num=0; + s->state=SSL2_ST_GET_SERVER_FINISHED_A; + break; + + case SSL2_ST_GET_SERVER_FINISHED_A: + case SSL2_ST_GET_SERVER_FINISHED_B: + ret=get_server_finished(s); + if (ret <= 0) goto end; + break; + + case SSL2_ST_SEND_CLIENT_CERTIFICATE_A: + case SSL2_ST_SEND_CLIENT_CERTIFICATE_B: + case SSL2_ST_SEND_CLIENT_CERTIFICATE_C: + case SSL2_ST_SEND_CLIENT_CERTIFICATE_D: + case SSL2_ST_X509_GET_CLIENT_CERTIFICATE: + ret=client_certificate(s); + if (ret <= 0) goto end; + s->init_num=0; + s->state=SSL2_ST_GET_SERVER_FINISHED_A; + break; + + case SSL_ST_OK: + if (s->init_buf != NULL) + { + BUF_MEM_free(s->init_buf); + s->init_buf=NULL; + } + s->init_num=0; + /* ERR_clear_error();*/ + + /* If we want to cache session-ids in the client + * and we successfully add the session-id to the + * cache, and there is a callback, then pass it out. + * 26/11/96 - eay - only add if not a re-used session. + */ + + ssl_update_cache(s,SSL_SESS_CACHE_CLIENT); + if (s->hit) s->ctx->stats.sess_hit++; + + ret=1; + /* s->server=0; */ + s->ctx->stats.sess_connect_good++; + + if (cb != NULL) cb(s,SSL_CB_HANDSHAKE_DONE,1); + + goto end; + /* break; */ + default: + SSLerr(SSL_F_SSL2_CONNECT,SSL_R_UNKNOWN_STATE); + return(-1); + /* break; */ + } + + if ((cb != NULL) && (s->state != state)) + { + new_state=s->state; + s->state=state; + cb(s,SSL_CB_CONNECT_LOOP,1); + s->state=new_state; + } + } +end: + s->in_handshake--; + if (buf != NULL) + BUF_MEM_free(buf); + if (cb != NULL) + cb(s,SSL_CB_CONNECT_EXIT,ret); + return(ret); + } + +static int get_server_hello(SSL *s) + { + unsigned char *buf; + unsigned char *p; + int i,j; + unsigned long len; + STACK_OF(SSL_CIPHER) *sk=NULL,*cl, *prio, *allow; + + buf=(unsigned char *)s->init_buf->data; + p=buf; + if (s->state == SSL2_ST_GET_SERVER_HELLO_A) + { + i=ssl2_read(s,(char *)&(buf[s->init_num]),11-s->init_num); + if (i < (11-s->init_num)) + return(ssl2_part_read(s,SSL_F_GET_SERVER_HELLO,i)); + s->init_num = 11; + + if (*(p++) != SSL2_MT_SERVER_HELLO) + { + if (p[-1] != SSL2_MT_ERROR) + { + ssl2_return_error(s,SSL2_PE_UNDEFINED_ERROR); + SSLerr(SSL_F_GET_SERVER_HELLO, + SSL_R_READ_WRONG_PACKET_TYPE); + } + else + SSLerr(SSL_F_GET_SERVER_HELLO, + SSL_R_PEER_ERROR); + return(-1); + } +#ifdef __APPLE_CC__ + /* The Rhapsody 5.5 (a.k.a. MacOS X) compiler bug + * workaround. */ + s->hit=(i=*(p++))?1:0; +#else + s->hit=(*(p++))?1:0; +#endif + s->s2->tmp.cert_type= *(p++); + n2s(p,i); + if (i < s->version) s->version=i; + n2s(p,i); s->s2->tmp.cert_length=i; + n2s(p,i); s->s2->tmp.csl=i; + n2s(p,i); s->s2->tmp.conn_id_length=i; + s->state=SSL2_ST_GET_SERVER_HELLO_B; + } + + /* SSL2_ST_GET_SERVER_HELLO_B */ + len = 11 + (unsigned long)s->s2->tmp.cert_length + (unsigned long)s->s2->tmp.csl + (unsigned long)s->s2->tmp.conn_id_length; + if (len > SSL2_MAX_RECORD_LENGTH_3_BYTE_HEADER) + { + SSLerr(SSL_F_GET_SERVER_HELLO,SSL_R_MESSAGE_TOO_LONG); + return -1; + } + j = (int)len - s->init_num; + i = ssl2_read(s,(char *)&(buf[s->init_num]),j); + if (i != j) return(ssl2_part_read(s,SSL_F_GET_SERVER_HELLO,i)); + if (s->msg_callback) + s->msg_callback(0, s->version, 0, buf, (size_t)len, s, s->msg_callback_arg); /* SERVER-HELLO */ + + /* things are looking good */ + + p = buf + 11; + if (s->hit) + { + if (s->s2->tmp.cert_length != 0) + { + SSLerr(SSL_F_GET_SERVER_HELLO,SSL_R_REUSE_CERT_LENGTH_NOT_ZERO); + return(-1); + } + if (s->s2->tmp.cert_type != 0) + { + if (!(s->options & + SSL_OP_SSLREF2_REUSE_CERT_TYPE_BUG)) + { + SSLerr(SSL_F_GET_SERVER_HELLO,SSL_R_REUSE_CERT_TYPE_NOT_ZERO); + return(-1); + } + } + if (s->s2->tmp.csl != 0) + { + SSLerr(SSL_F_GET_SERVER_HELLO,SSL_R_REUSE_CIPHER_LIST_NOT_ZERO); + return(-1); + } + } + else + { +#ifdef undef + /* very bad */ + memset(s->session->session_id,0, + SSL_MAX_SSL_SESSION_ID_LENGTH_IN_BYTES); + s->session->session_id_length=0; + */ +#endif + + /* we need to do this in case we were trying to reuse a + * client session but others are already reusing it. + * If this was a new 'blank' session ID, the session-id + * length will still be 0 */ + if (s->session->session_id_length > 0) + { + if (!ssl_get_new_session(s,0)) + { + ssl2_return_error(s,SSL2_PE_UNDEFINED_ERROR); + return(-1); + } + } + + if (ssl2_set_certificate(s,s->s2->tmp.cert_type, + s->s2->tmp.cert_length,p) <= 0) + { + ssl2_return_error(s,SSL2_PE_BAD_CERTIFICATE); + return(-1); + } + p+=s->s2->tmp.cert_length; + + if (s->s2->tmp.csl == 0) + { + ssl2_return_error(s,SSL2_PE_NO_CIPHER); + SSLerr(SSL_F_GET_SERVER_HELLO,SSL_R_NO_CIPHER_LIST); + return(-1); + } + + /* We have just received a list of ciphers back from the + * server. We need to get the ones that match, then select + * the one we want the most :-). */ + + /* load the ciphers */ + sk=ssl_bytes_to_cipher_list(s,p,s->s2->tmp.csl, + &s->session->ciphers); + p+=s->s2->tmp.csl; + if (sk == NULL) + { + ssl2_return_error(s,SSL2_PE_UNDEFINED_ERROR); + SSLerr(SSL_F_GET_SERVER_HELLO,ERR_R_MALLOC_FAILURE); + return(-1); + } + + (void)sk_SSL_CIPHER_set_cmp_func(sk,ssl_cipher_ptr_id_cmp); + + /* get the array of ciphers we will accept */ + cl=SSL_get_ciphers(s); + (void)sk_SSL_CIPHER_set_cmp_func(cl,ssl_cipher_ptr_id_cmp); + + /* + * If server preference flag set, choose the first + * (highest priority) cipher the server sends, otherwise + * client preference has priority. + */ + if (s->options & SSL_OP_CIPHER_SERVER_PREFERENCE) + { + prio = sk; + allow = cl; + } + else + { + prio = cl; + allow = sk; + } + /* In theory we could have ciphers sent back that we + * don't want to use but that does not matter since we + * will check against the list we originally sent and + * for performance reasons we should not bother to match + * the two lists up just to check. */ + for (i=0; i= 0) + break; + } + + if (i >= sk_SSL_CIPHER_num(prio)) + { + ssl2_return_error(s,SSL2_PE_NO_CIPHER); + SSLerr(SSL_F_GET_SERVER_HELLO,SSL_R_NO_CIPHER_MATCH); + return(-1); + } + s->session->cipher=sk_SSL_CIPHER_value(prio,i); + + + if (s->session->peer != NULL) /* can't happen*/ + { + ssl2_return_error(s, SSL2_PE_UNDEFINED_ERROR); + SSLerr(SSL_F_GET_SERVER_HELLO, ERR_R_INTERNAL_ERROR); + return(-1); + } + + s->session->peer = s->session->sess_cert->peer_key->x509; + /* peer_key->x509 has been set by ssl2_set_certificate. */ + CRYPTO_add(&s->session->peer->references, 1, CRYPTO_LOCK_X509); + } + + if (s->session->sess_cert == NULL + || s->session->peer != s->session->sess_cert->peer_key->x509) + /* can't happen */ + { + ssl2_return_error(s, SSL2_PE_UNDEFINED_ERROR); + SSLerr(SSL_F_GET_SERVER_HELLO, ERR_R_INTERNAL_ERROR); + return(-1); + } + + s->s2->conn_id_length=s->s2->tmp.conn_id_length; + if (s->s2->conn_id_length > sizeof s->s2->conn_id) + { + ssl2_return_error(s, SSL2_PE_UNDEFINED_ERROR); + SSLerr(SSL_F_GET_SERVER_HELLO, SSL_R_SSL2_CONNECTION_ID_TOO_LONG); + return -1; + } + memcpy(s->s2->conn_id,p,s->s2->tmp.conn_id_length); + return(1); + } + +static int client_hello(SSL *s) + { + unsigned char *buf; + unsigned char *p,*d; +/* CIPHER **cipher;*/ + int i,n,j; + + buf=(unsigned char *)s->init_buf->data; + if (s->state == SSL2_ST_SEND_CLIENT_HELLO_A) + { + if ((s->session == NULL) || + (s->session->ssl_version != s->version)) + { + if (!ssl_get_new_session(s,0)) + { + ssl2_return_error(s,SSL2_PE_UNDEFINED_ERROR); + return(-1); + } + } + /* else use the pre-loaded session */ + + p=buf; /* header */ + d=p+9; /* data section */ + *(p++)=SSL2_MT_CLIENT_HELLO; /* type */ + s2n(SSL2_VERSION,p); /* version */ + n=j=0; + + n=ssl_cipher_list_to_bytes(s,SSL_get_ciphers(s),d,0); + d+=n; + + if (n == 0) + { + SSLerr(SSL_F_CLIENT_HELLO,SSL_R_NO_CIPHERS_AVAILABLE); + return(-1); + } + + s2n(n,p); /* cipher spec num bytes */ + + if ((s->session->session_id_length > 0) && + (s->session->session_id_length <= + SSL2_MAX_SSL_SESSION_ID_LENGTH)) + { + i=s->session->session_id_length; + s2n(i,p); /* session id length */ + memcpy(d,s->session->session_id,(unsigned int)i); + d+=i; + } + else + { + s2n(0,p); + } + + s->s2->challenge_length=SSL2_CHALLENGE_LENGTH; + s2n(SSL2_CHALLENGE_LENGTH,p); /* challenge length */ + /*challenge id data*/ + if (RAND_pseudo_bytes(s->s2->challenge,SSL2_CHALLENGE_LENGTH) <= 0) + return -1; + memcpy(d,s->s2->challenge,SSL2_CHALLENGE_LENGTH); + d+=SSL2_CHALLENGE_LENGTH; + + s->state=SSL2_ST_SEND_CLIENT_HELLO_B; + s->init_num=d-buf; + s->init_off=0; + } + /* SSL2_ST_SEND_CLIENT_HELLO_B */ + return(ssl2_do_write(s)); + } + +static int client_master_key(SSL *s) + { + unsigned char *buf; + unsigned char *p,*d; + int clear,enc,karg,i; + SSL_SESSION *sess; + const EVP_CIPHER *c; + const EVP_MD *md; + + buf=(unsigned char *)s->init_buf->data; + if (s->state == SSL2_ST_SEND_CLIENT_MASTER_KEY_A) + { + + if (!ssl_cipher_get_evp(s->session,&c,&md,NULL,NULL,NULL)) + { + ssl2_return_error(s,SSL2_PE_NO_CIPHER); + SSLerr(SSL_F_CLIENT_MASTER_KEY,SSL_R_PROBLEMS_MAPPING_CIPHER_FUNCTIONS); + return(-1); + } + sess=s->session; + p=buf; + d=p+10; + *(p++)=SSL2_MT_CLIENT_MASTER_KEY;/* type */ + + i=ssl_put_cipher_by_char(s,sess->cipher,p); + p+=i; + + /* make key_arg data */ + i=EVP_CIPHER_iv_length(c); + sess->key_arg_length=i; + if (i > SSL_MAX_KEY_ARG_LENGTH) + { + ssl2_return_error(s, SSL2_PE_UNDEFINED_ERROR); + SSLerr(SSL_F_CLIENT_MASTER_KEY, ERR_R_INTERNAL_ERROR); + return -1; + } + if (i > 0) + if (RAND_pseudo_bytes(sess->key_arg,i) <= 0) + return -1; + + /* make a master key */ + i=EVP_CIPHER_key_length(c); + sess->master_key_length=i; + if (i > 0) + { + if (i > (int)sizeof(sess->master_key)) + { + ssl2_return_error(s, SSL2_PE_UNDEFINED_ERROR); + SSLerr(SSL_F_CLIENT_MASTER_KEY, ERR_R_INTERNAL_ERROR); + return -1; + } + if (RAND_bytes(sess->master_key,i) <= 0) + { + ssl2_return_error(s,SSL2_PE_UNDEFINED_ERROR); + return(-1); + } + } + + if (sess->cipher->algorithm2 & SSL2_CF_8_BYTE_ENC) + enc=8; + else if (SSL_C_IS_EXPORT(sess->cipher)) + enc=5; + else + enc=i; + + if ((int)i < enc) + { + ssl2_return_error(s,SSL2_PE_UNDEFINED_ERROR); + SSLerr(SSL_F_CLIENT_MASTER_KEY,SSL_R_CIPHER_TABLE_SRC_ERROR); + return(-1); + } + clear=i-enc; + s2n(clear,p); + memcpy(d,sess->master_key,(unsigned int)clear); + d+=clear; + + enc=ssl_rsa_public_encrypt(sess->sess_cert,enc, + &(sess->master_key[clear]),d, + (s->s2->ssl2_rollback)?RSA_SSLV23_PADDING:RSA_PKCS1_PADDING); + if (enc <= 0) + { + ssl2_return_error(s,SSL2_PE_UNDEFINED_ERROR); + SSLerr(SSL_F_CLIENT_MASTER_KEY,SSL_R_PUBLIC_KEY_ENCRYPT_ERROR); + return(-1); + } +#ifdef PKCS1_CHECK + if (s->options & SSL_OP_PKCS1_CHECK_1) d[1]++; + if (s->options & SSL_OP_PKCS1_CHECK_2) + sess->master_key[clear]++; +#endif + s2n(enc,p); + d+=enc; + karg=sess->key_arg_length; + s2n(karg,p); /* key arg size */ + if (karg > (int)sizeof(sess->key_arg)) + { + ssl2_return_error(s,SSL2_PE_UNDEFINED_ERROR); + SSLerr(SSL_F_CLIENT_MASTER_KEY, ERR_R_INTERNAL_ERROR); + return -1; + } + memcpy(d,sess->key_arg,(unsigned int)karg); + d+=karg; + + s->state=SSL2_ST_SEND_CLIENT_MASTER_KEY_B; + s->init_num=d-buf; + s->init_off=0; + } + + /* SSL2_ST_SEND_CLIENT_MASTER_KEY_B */ + return(ssl2_do_write(s)); + } + +static int client_finished(SSL *s) + { + unsigned char *p; + + if (s->state == SSL2_ST_SEND_CLIENT_FINISHED_A) + { + p=(unsigned char *)s->init_buf->data; + *(p++)=SSL2_MT_CLIENT_FINISHED; + if (s->s2->conn_id_length > sizeof s->s2->conn_id) + { + SSLerr(SSL_F_CLIENT_FINISHED, ERR_R_INTERNAL_ERROR); + return -1; + } + memcpy(p,s->s2->conn_id,(unsigned int)s->s2->conn_id_length); + + s->state=SSL2_ST_SEND_CLIENT_FINISHED_B; + s->init_num=s->s2->conn_id_length+1; + s->init_off=0; + } + return(ssl2_do_write(s)); + } + +/* read the data and then respond */ +static int client_certificate(SSL *s) + { + unsigned char *buf; + unsigned char *p,*d; + int i; + unsigned int n; + int cert_ch_len; + unsigned char *cert_ch; + + buf=(unsigned char *)s->init_buf->data; + + /* We have a cert associated with the SSL, so attach it to + * the session if it does not have one */ + + if (s->state == SSL2_ST_SEND_CLIENT_CERTIFICATE_A) + { + i=ssl2_read(s,(char *)&(buf[s->init_num]), + SSL2_MAX_CERT_CHALLENGE_LENGTH+2-s->init_num); + if (i<(SSL2_MIN_CERT_CHALLENGE_LENGTH+2-s->init_num)) + return(ssl2_part_read(s,SSL_F_CLIENT_CERTIFICATE,i)); + s->init_num += i; + if (s->msg_callback) + s->msg_callback(0, s->version, 0, buf, (size_t)s->init_num, s, s->msg_callback_arg); /* REQUEST-CERTIFICATE */ + + /* type=buf[0]; */ + /* type eq x509 */ + if (buf[1] != SSL2_AT_MD5_WITH_RSA_ENCRYPTION) + { + ssl2_return_error(s,SSL2_PE_UNSUPPORTED_CERTIFICATE_TYPE); + SSLerr(SSL_F_CLIENT_CERTIFICATE,SSL_R_BAD_AUTHENTICATION_TYPE); + return(-1); + } + + if ((s->cert == NULL) || + (s->cert->key->x509 == NULL) || + (s->cert->key->privatekey == NULL)) + { + s->state=SSL2_ST_X509_GET_CLIENT_CERTIFICATE; + } + else + s->state=SSL2_ST_SEND_CLIENT_CERTIFICATE_C; + } + + cert_ch = buf + 2; + cert_ch_len = s->init_num - 2; + + if (s->state == SSL2_ST_X509_GET_CLIENT_CERTIFICATE) + { + X509 *x509=NULL; + EVP_PKEY *pkey=NULL; + + /* If we get an error we need to + * ssl->rwstate=SSL_X509_LOOKUP; + * return(error); + * We should then be retried when things are ok and we + * can get a cert or not */ + + i=0; + if (s->ctx->client_cert_cb != NULL) + { + i=s->ctx->client_cert_cb(s,&(x509),&(pkey)); + } + + if (i < 0) + { + s->rwstate=SSL_X509_LOOKUP; + return(-1); + } + s->rwstate=SSL_NOTHING; + + if ((i == 1) && (pkey != NULL) && (x509 != NULL)) + { + s->state=SSL2_ST_SEND_CLIENT_CERTIFICATE_C; + if ( !SSL_use_certificate(s,x509) || + !SSL_use_PrivateKey(s,pkey)) + { + i=0; + } + X509_free(x509); + EVP_PKEY_free(pkey); + } + else if (i == 1) + { + if (x509 != NULL) X509_free(x509); + if (pkey != NULL) EVP_PKEY_free(pkey); + SSLerr(SSL_F_CLIENT_CERTIFICATE,SSL_R_BAD_DATA_RETURNED_BY_CALLBACK); + i=0; + } + + if (i == 0) + { + /* We have no client certificate to respond with + * so send the correct error message back */ + s->state=SSL2_ST_SEND_CLIENT_CERTIFICATE_B; + p=buf; + *(p++)=SSL2_MT_ERROR; + s2n(SSL2_PE_NO_CERTIFICATE,p); + s->init_off=0; + s->init_num=3; + /* Write is done at the end */ + } + } + + if (s->state == SSL2_ST_SEND_CLIENT_CERTIFICATE_B) + { + return(ssl2_do_write(s)); + } + + if (s->state == SSL2_ST_SEND_CLIENT_CERTIFICATE_C) + { + EVP_MD_CTX ctx; + + /* ok, now we calculate the checksum + * do it first so we can reuse buf :-) */ + p=buf; + EVP_MD_CTX_init(&ctx); + EVP_SignInit_ex(&ctx,s->ctx->rsa_md5, NULL); + EVP_SignUpdate(&ctx,s->s2->key_material, + s->s2->key_material_length); + EVP_SignUpdate(&ctx,cert_ch,(unsigned int)cert_ch_len); + i=i2d_X509(s->session->sess_cert->peer_key->x509,&p); + /* Don't update the signature if it fails - FIXME: probably should handle this better */ + if(i > 0) + EVP_SignUpdate(&ctx,buf,(unsigned int)i); + + p=buf; + d=p+6; + *(p++)=SSL2_MT_CLIENT_CERTIFICATE; + *(p++)=SSL2_CT_X509_CERTIFICATE; + n=i2d_X509(s->cert->key->x509,&d); + s2n(n,p); + + if (!EVP_SignFinal(&ctx,d,&n,s->cert->key->privatekey)) + { + /* this is not good. If things have failed it + * means there so something wrong with the key. + * We will continue with a 0 length signature + */ + } + EVP_MD_CTX_cleanup(&ctx); + s2n(n,p); + d+=n; + + s->state=SSL2_ST_SEND_CLIENT_CERTIFICATE_D; + s->init_num=d-buf; + s->init_off=0; + } + /* if (s->state == SSL2_ST_SEND_CLIENT_CERTIFICATE_D) */ + return(ssl2_do_write(s)); + } + +static int get_server_verify(SSL *s) + { + unsigned char *p; + int i, n, len; + + p=(unsigned char *)s->init_buf->data; + if (s->state == SSL2_ST_GET_SERVER_VERIFY_A) + { + i=ssl2_read(s,(char *)&(p[s->init_num]),1-s->init_num); + if (i < (1-s->init_num)) + return(ssl2_part_read(s,SSL_F_GET_SERVER_VERIFY,i)); + s->init_num += i; + + s->state= SSL2_ST_GET_SERVER_VERIFY_B; + if (*p != SSL2_MT_SERVER_VERIFY) + { + if (p[0] != SSL2_MT_ERROR) + { + ssl2_return_error(s,SSL2_PE_UNDEFINED_ERROR); + SSLerr(SSL_F_GET_SERVER_VERIFY, + SSL_R_READ_WRONG_PACKET_TYPE); + } + else + { + SSLerr(SSL_F_GET_SERVER_VERIFY,SSL_R_PEER_ERROR); + /* try to read the error message */ + i=ssl2_read(s,(char *)&(p[s->init_num]),3-s->init_num); + return ssl2_part_read(s,SSL_F_GET_SERVER_VERIFY,i); + } + return(-1); + } + } + + p=(unsigned char *)s->init_buf->data; + len = 1 + s->s2->challenge_length; + n = len - s->init_num; + i = ssl2_read(s,(char *)&(p[s->init_num]),n); + if (i < n) + return(ssl2_part_read(s,SSL_F_GET_SERVER_VERIFY,i)); + if (s->msg_callback) + s->msg_callback(0, s->version, 0, p, len, s, s->msg_callback_arg); /* SERVER-VERIFY */ + p += 1; + + if (memcmp(p,s->s2->challenge,s->s2->challenge_length) != 0) + { + ssl2_return_error(s,SSL2_PE_UNDEFINED_ERROR); + SSLerr(SSL_F_GET_SERVER_VERIFY,SSL_R_CHALLENGE_IS_DIFFERENT); + return(-1); + } + return(1); + } + +static int get_server_finished(SSL *s) + { + unsigned char *buf; + unsigned char *p; + int i, n, len; + + buf=(unsigned char *)s->init_buf->data; + p=buf; + if (s->state == SSL2_ST_GET_SERVER_FINISHED_A) + { + i=ssl2_read(s,(char *)&(buf[s->init_num]),1-s->init_num); + if (i < (1-s->init_num)) + return(ssl2_part_read(s,SSL_F_GET_SERVER_FINISHED,i)); + s->init_num += i; + + if (*p == SSL2_MT_REQUEST_CERTIFICATE) + { + s->state=SSL2_ST_SEND_CLIENT_CERTIFICATE_A; + return(1); + } + else if (*p != SSL2_MT_SERVER_FINISHED) + { + if (p[0] != SSL2_MT_ERROR) + { + ssl2_return_error(s,SSL2_PE_UNDEFINED_ERROR); + SSLerr(SSL_F_GET_SERVER_FINISHED,SSL_R_READ_WRONG_PACKET_TYPE); + } + else + { + SSLerr(SSL_F_GET_SERVER_FINISHED,SSL_R_PEER_ERROR); + /* try to read the error message */ + i=ssl2_read(s,(char *)&(p[s->init_num]),3-s->init_num); + return ssl2_part_read(s,SSL_F_GET_SERVER_VERIFY,i); + } + return(-1); + } + s->state=SSL2_ST_GET_SERVER_FINISHED_B; + } + + len = 1 + SSL2_SSL_SESSION_ID_LENGTH; + n = len - s->init_num; + i = ssl2_read(s,(char *)&(buf[s->init_num]), n); + if (i < n) /* XXX could be shorter than SSL2_SSL_SESSION_ID_LENGTH, that's the maximum */ + return(ssl2_part_read(s,SSL_F_GET_SERVER_FINISHED,i)); + s->init_num += i; + if (s->msg_callback) + s->msg_callback(0, s->version, 0, buf, (size_t)s->init_num, s, s->msg_callback_arg); /* SERVER-FINISHED */ + + if (!s->hit) /* new session */ + { + /* new session-id */ + /* Make sure we were not trying to re-use an old SSL_SESSION + * or bad things can happen */ + /* ZZZZZZZZZZZZZ */ + s->session->session_id_length=SSL2_SSL_SESSION_ID_LENGTH; + memcpy(s->session->session_id,p+1,SSL2_SSL_SESSION_ID_LENGTH); + } + else + { + if (!(s->options & SSL_OP_MICROSOFT_SESS_ID_BUG)) + { + if ((s->session->session_id_length > sizeof s->session->session_id) + || (0 != memcmp(buf + 1, s->session->session_id, + (unsigned int)s->session->session_id_length))) + { + ssl2_return_error(s,SSL2_PE_UNDEFINED_ERROR); + SSLerr(SSL_F_GET_SERVER_FINISHED,SSL_R_SSL_SESSION_ID_IS_DIFFERENT); + return(-1); + } + } + } + s->state = SSL_ST_OK; + return(1); + } + +/* loads in the certificate from the server */ +int ssl2_set_certificate(SSL *s, int type, int len, const unsigned char *data) + { + STACK_OF(X509) *sk=NULL; + EVP_PKEY *pkey=NULL; + SESS_CERT *sc=NULL; + int i; + X509 *x509=NULL; + int ret=0; + + x509=d2i_X509(NULL,&data,(long)len); + if (x509 == NULL) + { + SSLerr(SSL_F_SSL2_SET_CERTIFICATE,ERR_R_X509_LIB); + goto err; + } + + if ((sk=sk_X509_new_null()) == NULL || !sk_X509_push(sk,x509)) + { + SSLerr(SSL_F_SSL2_SET_CERTIFICATE,ERR_R_MALLOC_FAILURE); + goto err; + } + + i=ssl_verify_cert_chain(s,sk); + + if ((s->verify_mode != SSL_VERIFY_NONE) && (i <= 0)) + { + SSLerr(SSL_F_SSL2_SET_CERTIFICATE,SSL_R_CERTIFICATE_VERIFY_FAILED); + goto err; + } + ERR_clear_error(); /* but we keep s->verify_result */ + s->session->verify_result = s->verify_result; + + /* server's cert for this session */ + sc=ssl_sess_cert_new(); + if (sc == NULL) + { + ret= -1; + goto err; + } + if (s->session->sess_cert) ssl_sess_cert_free(s->session->sess_cert); + s->session->sess_cert=sc; + + sc->peer_pkeys[SSL_PKEY_RSA_ENC].x509=x509; + sc->peer_key= &(sc->peer_pkeys[SSL_PKEY_RSA_ENC]); + + pkey=X509_get_pubkey(x509); + x509=NULL; + if (pkey == NULL) + { + SSLerr(SSL_F_SSL2_SET_CERTIFICATE,SSL_R_UNABLE_TO_EXTRACT_PUBLIC_KEY); + goto err; + } + if (pkey->type != EVP_PKEY_RSA) + { + SSLerr(SSL_F_SSL2_SET_CERTIFICATE,SSL_R_PUBLIC_KEY_NOT_RSA); + goto err; + } + + if (!ssl_set_peer_cert_type(sc,SSL2_CT_X509_CERTIFICATE)) + goto err; + ret=1; +err: + sk_X509_free(sk); + X509_free(x509); + EVP_PKEY_free(pkey); + return(ret); + } + +static int ssl_rsa_public_encrypt(SESS_CERT *sc, int len, unsigned char *from, + unsigned char *to, int padding) + { + EVP_PKEY *pkey=NULL; + int i= -1; + + if ((sc == NULL) || (sc->peer_key->x509 == NULL) || + ((pkey=X509_get_pubkey(sc->peer_key->x509)) == NULL)) + { + SSLerr(SSL_F_SSL_RSA_PUBLIC_ENCRYPT,SSL_R_NO_PUBLICKEY); + return(-1); + } + if (pkey->type != EVP_PKEY_RSA) + { + SSLerr(SSL_F_SSL_RSA_PUBLIC_ENCRYPT,SSL_R_PUBLIC_KEY_IS_NOT_RSA); + goto end; + } + + /* we have the public key */ + i=RSA_public_encrypt(len,from,to,pkey->pkey.rsa,padding); + if (i < 0) + SSLerr(SSL_F_SSL_RSA_PUBLIC_ENCRYPT,ERR_R_RSA_LIB); +end: + EVP_PKEY_free(pkey); + return(i); + } +#else /* !OPENSSL_NO_SSL2 */ + +# if PEDANTIC +static void *dummy=&dummy; +# endif + +#endif diff --git a/node-v0.8.14/deps/openssl/openssl/ssl/s2_enc.c b/node-v0.8.14/deps/openssl/openssl/ssl/s2_enc.c new file mode 100644 index 0000000..ff3395f --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/ssl/s2_enc.c @@ -0,0 +1,193 @@ +/* ssl/s2_enc.c */ +/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com) + * All rights reserved. + * + * This package is an SSL implementation written + * by Eric Young (eay@cryptsoft.com). + * The implementation was written so as to conform with Netscapes SSL. + * + * This library is free for commercial and non-commercial use as long as + * the following conditions are aheared to. The following conditions + * apply to all code found in this distribution, be it the RC4, RSA, + * lhash, DES, etc., code; not just the SSL code. The SSL documentation + * included with this distribution is covered by the same copyright terms + * except that the holder is Tim Hudson (tjh@cryptsoft.com). + * + * Copyright remains Eric Young's, and as such any Copyright notices in + * the code are not to be removed. + * If this package is used in a product, Eric Young should be given attribution + * as the author of the parts of the library used. + * This can be in the form of a textual message at program startup or + * in documentation (online or textual) provided with the package. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * "This product includes cryptographic software written by + * Eric Young (eay@cryptsoft.com)" + * The word 'cryptographic' can be left out if the rouines from the library + * being used are not cryptographic related :-). + * 4. If you include any Windows specific code (or a derivative thereof) from + * the apps directory (application code) you must include an acknowledgement: + * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)" + * + * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * + * The licence and distribution terms for any publically available version or + * derivative of this code cannot be changed. i.e. this code cannot simply be + * copied and put under another distribution licence + * [including the GNU Public Licence.] + */ + +#include "ssl_locl.h" +#ifndef OPENSSL_NO_SSL2 +#include + +int ssl2_enc_init(SSL *s, int client) + { + /* Max number of bytes needed */ + EVP_CIPHER_CTX *rs,*ws; + const EVP_CIPHER *c; + const EVP_MD *md; + int num; + + if (!ssl_cipher_get_evp(s->session,&c,&md,NULL,NULL,NULL)) + { + ssl2_return_error(s,SSL2_PE_NO_CIPHER); + SSLerr(SSL_F_SSL2_ENC_INIT,SSL_R_PROBLEMS_MAPPING_CIPHER_FUNCTIONS); + return(0); + } + ssl_replace_hash(&s->read_hash,md); + ssl_replace_hash(&s->write_hash,md); + + if ((s->enc_read_ctx == NULL) && + ((s->enc_read_ctx=(EVP_CIPHER_CTX *) + OPENSSL_malloc(sizeof(EVP_CIPHER_CTX))) == NULL)) + goto err; + + /* make sure it's intialized in case the malloc for enc_write_ctx fails + * and we exit with an error */ + rs= s->enc_read_ctx; + EVP_CIPHER_CTX_init(rs); + + if ((s->enc_write_ctx == NULL) && + ((s->enc_write_ctx=(EVP_CIPHER_CTX *) + OPENSSL_malloc(sizeof(EVP_CIPHER_CTX))) == NULL)) + goto err; + + ws= s->enc_write_ctx; + EVP_CIPHER_CTX_init(ws); + + num=c->key_len; + s->s2->key_material_length=num*2; + OPENSSL_assert(s->s2->key_material_length <= sizeof s->s2->key_material); + + if (ssl2_generate_key_material(s) <= 0) + return 0; + + OPENSSL_assert(c->iv_len <= (int)sizeof(s->session->key_arg)); + EVP_EncryptInit_ex(ws,c,NULL,&(s->s2->key_material[(client)?num:0]), + s->session->key_arg); + EVP_DecryptInit_ex(rs,c,NULL,&(s->s2->key_material[(client)?0:num]), + s->session->key_arg); + s->s2->read_key= &(s->s2->key_material[(client)?0:num]); + s->s2->write_key= &(s->s2->key_material[(client)?num:0]); + return(1); +err: + SSLerr(SSL_F_SSL2_ENC_INIT,ERR_R_MALLOC_FAILURE); + return(0); + } + +/* read/writes from s->s2->mac_data using length for encrypt and + * decrypt. It sets s->s2->padding and s->[rw]length + * if we are encrypting */ +void ssl2_enc(SSL *s, int send) + { + EVP_CIPHER_CTX *ds; + unsigned long l; + int bs; + + if (send) + { + ds=s->enc_write_ctx; + l=s->s2->wlength; + } + else + { + ds=s->enc_read_ctx; + l=s->s2->rlength; + } + + /* check for NULL cipher */ + if (ds == NULL) return; + + + bs=ds->cipher->block_size; + /* This should be using (bs-1) and bs instead of 7 and 8, but + * what the hell. */ + if (bs == 8) + l=(l+7)/8*8; + + EVP_Cipher(ds,s->s2->mac_data,s->s2->mac_data,l); + } + +void ssl2_mac(SSL *s, unsigned char *md, int send) + { + EVP_MD_CTX c; + unsigned char sequence[4],*p,*sec,*act; + unsigned long seq; + unsigned int len; + + if (send) + { + seq=s->s2->write_sequence; + sec=s->s2->write_key; + len=s->s2->wact_data_length; + act=s->s2->wact_data; + } + else + { + seq=s->s2->read_sequence; + sec=s->s2->read_key; + len=s->s2->ract_data_length; + act=s->s2->ract_data; + } + + p= &(sequence[0]); + l2n(seq,p); + + /* There has to be a MAC algorithm. */ + EVP_MD_CTX_init(&c); + EVP_MD_CTX_copy(&c, s->read_hash); + EVP_DigestUpdate(&c,sec, + EVP_CIPHER_CTX_key_length(s->enc_read_ctx)); + EVP_DigestUpdate(&c,act,len); + /* the above line also does the pad data */ + EVP_DigestUpdate(&c,sequence,4); + EVP_DigestFinal_ex(&c,md,NULL); + EVP_MD_CTX_cleanup(&c); + } +#else /* !OPENSSL_NO_SSL2 */ + +# if PEDANTIC +static void *dummy=&dummy; +# endif + +#endif diff --git a/node-v0.8.14/deps/openssl/openssl/ssl/s2_lib.c b/node-v0.8.14/deps/openssl/openssl/ssl/s2_lib.c new file mode 100644 index 0000000..9914604 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/ssl/s2_lib.c @@ -0,0 +1,556 @@ +/* ssl/s2_lib.c */ +/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com) + * All rights reserved. + * + * This package is an SSL implementation written + * by Eric Young (eay@cryptsoft.com). + * The implementation was written so as to conform with Netscapes SSL. + * + * This library is free for commercial and non-commercial use as long as + * the following conditions are aheared to. The following conditions + * apply to all code found in this distribution, be it the RC4, RSA, + * lhash, DES, etc., code; not just the SSL code. The SSL documentation + * included with this distribution is covered by the same copyright terms + * except that the holder is Tim Hudson (tjh@cryptsoft.com). + * + * Copyright remains Eric Young's, and as such any Copyright notices in + * the code are not to be removed. + * If this package is used in a product, Eric Young should be given attribution + * as the author of the parts of the library used. + * This can be in the form of a textual message at program startup or + * in documentation (online or textual) provided with the package. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * "This product includes cryptographic software written by + * Eric Young (eay@cryptsoft.com)" + * The word 'cryptographic' can be left out if the rouines from the library + * being used are not cryptographic related :-). + * 4. If you include any Windows specific code (or a derivative thereof) from + * the apps directory (application code) you must include an acknowledgement: + * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)" + * + * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * + * The licence and distribution terms for any publically available version or + * derivative of this code cannot be changed. i.e. this code cannot simply be + * copied and put under another distribution licence + * [including the GNU Public Licence.] + */ +/* ==================================================================== + * Copyright (c) 1998-2007 The OpenSSL Project. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. All advertising materials mentioning features or use of this + * software must display the following acknowledgment: + * "This product includes software developed by the OpenSSL Project + * for use in the OpenSSL Toolkit. (http://www.openssl.org/)" + * + * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to + * endorse or promote products derived from this software without + * prior written permission. For written permission, please contact + * openssl-core@openssl.org. + * + * 5. Products derived from this software may not be called "OpenSSL" + * nor may "OpenSSL" appear in their names without prior written + * permission of the OpenSSL Project. + * + * 6. Redistributions of any form whatsoever must retain the following + * acknowledgment: + * "This product includes software developed by the OpenSSL Project + * for use in the OpenSSL Toolkit (http://www.openssl.org/)" + * + * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY + * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR + * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, + * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * ==================================================================== + * + * This product includes cryptographic software written by Eric Young + * (eay@cryptsoft.com). This product includes software written by Tim + * Hudson (tjh@cryptsoft.com). + * + */ + +#include "ssl_locl.h" +#ifndef OPENSSL_NO_SSL2 +#include +#include +#include +#include + +const char ssl2_version_str[]="SSLv2" OPENSSL_VERSION_PTEXT; + +#define SSL2_NUM_CIPHERS (sizeof(ssl2_ciphers)/sizeof(SSL_CIPHER)) + +/* list of available SSLv2 ciphers (sorted by id) */ +OPENSSL_GLOBAL const SSL_CIPHER ssl2_ciphers[]={ +#if 0 +/* NULL_WITH_MD5 v3 */ + { + 1, + SSL2_TXT_NULL_WITH_MD5, + SSL2_CK_NULL_WITH_MD5, + SSL_kRSA, + SSL_aRSA, + SSL_eNULL, + SSL_MD5, + SSL_SSLV2, + SSL_EXPORT|SSL_EXP40|SSL_STRONG_NONE, + 0, + 0, + 0, + }, +#endif + +/* RC4_128_WITH_MD5 */ + { + 1, + SSL2_TXT_RC4_128_WITH_MD5, + SSL2_CK_RC4_128_WITH_MD5, + SSL_kRSA, + SSL_aRSA, + SSL_RC4, + SSL_MD5, + SSL_SSLV2, + SSL_NOT_EXP|SSL_MEDIUM, + 0, + 128, + 128, + }, + +/* RC4_128_EXPORT40_WITH_MD5 */ + { + 1, + SSL2_TXT_RC4_128_EXPORT40_WITH_MD5, + SSL2_CK_RC4_128_EXPORT40_WITH_MD5, + SSL_kRSA, + SSL_aRSA, + SSL_RC4, + SSL_MD5, + SSL_SSLV2, + SSL_EXPORT|SSL_EXP40, + SSL2_CF_5_BYTE_ENC, + 40, + 128, + }, + +/* RC2_128_CBC_WITH_MD5 */ + { + 1, + SSL2_TXT_RC2_128_CBC_WITH_MD5, + SSL2_CK_RC2_128_CBC_WITH_MD5, + SSL_kRSA, + SSL_aRSA, + SSL_RC2, + SSL_MD5, + SSL_SSLV2, + SSL_NOT_EXP|SSL_MEDIUM, + 0, + 128, + 128, + }, + +/* RC2_128_CBC_EXPORT40_WITH_MD5 */ + { + 1, + SSL2_TXT_RC2_128_CBC_EXPORT40_WITH_MD5, + SSL2_CK_RC2_128_CBC_EXPORT40_WITH_MD5, + SSL_kRSA, + SSL_aRSA, + SSL_RC2, + SSL_MD5, + SSL_SSLV2, + SSL_EXPORT|SSL_EXP40, + SSL2_CF_5_BYTE_ENC, + 40, + 128, + }, + +#ifndef OPENSSL_NO_IDEA +/* IDEA_128_CBC_WITH_MD5 */ + { + 1, + SSL2_TXT_IDEA_128_CBC_WITH_MD5, + SSL2_CK_IDEA_128_CBC_WITH_MD5, + SSL_kRSA, + SSL_aRSA, + SSL_IDEA, + SSL_MD5, + SSL_SSLV2, + SSL_NOT_EXP|SSL_MEDIUM, + 0, + 128, + 128, + }, +#endif + +/* DES_64_CBC_WITH_MD5 */ + { + 1, + SSL2_TXT_DES_64_CBC_WITH_MD5, + SSL2_CK_DES_64_CBC_WITH_MD5, + SSL_kRSA, + SSL_aRSA, + SSL_DES, + SSL_MD5, + SSL_SSLV2, + SSL_NOT_EXP|SSL_LOW, + 0, + 56, + 56, + }, + +/* DES_192_EDE3_CBC_WITH_MD5 */ + { + 1, + SSL2_TXT_DES_192_EDE3_CBC_WITH_MD5, + SSL2_CK_DES_192_EDE3_CBC_WITH_MD5, + SSL_kRSA, + SSL_aRSA, + SSL_3DES, + SSL_MD5, + SSL_SSLV2, + SSL_NOT_EXP|SSL_HIGH, + 0, + 168, + 168, + }, + +#if 0 +/* RC4_64_WITH_MD5 */ + { + 1, + SSL2_TXT_RC4_64_WITH_MD5, + SSL2_CK_RC4_64_WITH_MD5, + SSL_kRSA, + SSL_aRSA, + SSL_RC4, + SSL_MD5, + SSL_SSLV2, + SSL_NOT_EXP|SSL_LOW, + SSL2_CF_8_BYTE_ENC, + 64, + 64, + }, +#endif + +#if 0 +/* NULL SSLeay (testing) */ + { + 0, + SSL2_TXT_NULL, + SSL2_CK_NULL, + 0, + 0, + 0, + 0, + SSL_SSLV2, + SSL_STRONG_NONE, + 0, + 0, + 0, + }, +#endif + +/* end of list :-) */ + }; + +long ssl2_default_timeout(void) + { + return(300); + } + +int ssl2_num_ciphers(void) + { + return(SSL2_NUM_CIPHERS); + } + +const SSL_CIPHER *ssl2_get_cipher(unsigned int u) + { + if (u < SSL2_NUM_CIPHERS) + return(&(ssl2_ciphers[SSL2_NUM_CIPHERS-1-u])); + else + return(NULL); + } + +int ssl2_pending(const SSL *s) + { + return SSL_in_init(s) ? 0 : s->s2->ract_data_length; + } + +int ssl2_new(SSL *s) + { + SSL2_STATE *s2; + + if ((s2=OPENSSL_malloc(sizeof *s2)) == NULL) goto err; + memset(s2,0,sizeof *s2); + +#if SSL2_MAX_RECORD_LENGTH_3_BYTE_HEADER + 3 > SSL2_MAX_RECORD_LENGTH_2_BYTE_HEADER + 2 +# error "assertion failed" +#endif + + if ((s2->rbuf=OPENSSL_malloc( + SSL2_MAX_RECORD_LENGTH_2_BYTE_HEADER+2)) == NULL) goto err; + /* wbuf needs one byte more because when using two-byte headers, + * we leave the first byte unused in do_ssl_write (s2_pkt.c) */ + if ((s2->wbuf=OPENSSL_malloc( + SSL2_MAX_RECORD_LENGTH_2_BYTE_HEADER+3)) == NULL) goto err; + s->s2=s2; + + ssl2_clear(s); + return(1); +err: + if (s2 != NULL) + { + if (s2->wbuf != NULL) OPENSSL_free(s2->wbuf); + if (s2->rbuf != NULL) OPENSSL_free(s2->rbuf); + OPENSSL_free(s2); + } + return(0); + } + +void ssl2_free(SSL *s) + { + SSL2_STATE *s2; + + if(s == NULL) + return; + + s2=s->s2; + if (s2->rbuf != NULL) OPENSSL_free(s2->rbuf); + if (s2->wbuf != NULL) OPENSSL_free(s2->wbuf); + OPENSSL_cleanse(s2,sizeof *s2); + OPENSSL_free(s2); + s->s2=NULL; + } + +void ssl2_clear(SSL *s) + { + SSL2_STATE *s2; + unsigned char *rbuf,*wbuf; + + s2=s->s2; + + rbuf=s2->rbuf; + wbuf=s2->wbuf; + + memset(s2,0,sizeof *s2); + + s2->rbuf=rbuf; + s2->wbuf=wbuf; + s2->clear_text=1; + s->packet=s2->rbuf; + s->version=SSL2_VERSION; + s->packet_length=0; + } + +long ssl2_ctrl(SSL *s, int cmd, long larg, void *parg) + { + int ret=0; + + switch(cmd) + { + case SSL_CTRL_GET_SESSION_REUSED: + ret=s->hit; + break; + default: + break; + } + return(ret); + } + +long ssl2_callback_ctrl(SSL *s, int cmd, void (*fp)(void)) + { + return(0); + } + +long ssl2_ctx_ctrl(SSL_CTX *ctx, int cmd, long larg, void *parg) + { + return(0); + } + +long ssl2_ctx_callback_ctrl(SSL_CTX *ctx, int cmd, void (*fp)(void)) + { + return(0); + } + +/* This function needs to check if the ciphers required are actually + * available */ +const SSL_CIPHER *ssl2_get_cipher_by_char(const unsigned char *p) + { + SSL_CIPHER c; + const SSL_CIPHER *cp; + unsigned long id; + + id=0x02000000L|((unsigned long)p[0]<<16L)| + ((unsigned long)p[1]<<8L)|(unsigned long)p[2]; + c.id=id; + cp = OBJ_bsearch_ssl_cipher_id(&c, ssl2_ciphers, SSL2_NUM_CIPHERS); + if ((cp == NULL) || (cp->valid == 0)) + return NULL; + else + return cp; + } + +int ssl2_put_cipher_by_char(const SSL_CIPHER *c, unsigned char *p) + { + long l; + + if (p != NULL) + { + l=c->id; + if ((l & 0xff000000) != 0x02000000) return(0); + p[0]=((unsigned char)(l>>16L))&0xFF; + p[1]=((unsigned char)(l>> 8L))&0xFF; + p[2]=((unsigned char)(l ))&0xFF; + } + return(3); + } + +int ssl2_generate_key_material(SSL *s) + { + unsigned int i; + EVP_MD_CTX ctx; + unsigned char *km; + unsigned char c='0'; + const EVP_MD *md5; + int md_size; + + md5 = EVP_md5(); + +#ifdef CHARSET_EBCDIC + c = os_toascii['0']; /* Must be an ASCII '0', not EBCDIC '0', + see SSLv2 docu */ +#endif + EVP_MD_CTX_init(&ctx); + km=s->s2->key_material; + + if (s->session->master_key_length < 0 || + s->session->master_key_length > (int)sizeof(s->session->master_key)) + { + SSLerr(SSL_F_SSL2_GENERATE_KEY_MATERIAL, ERR_R_INTERNAL_ERROR); + return 0; + } + md_size = EVP_MD_size(md5); + if (md_size < 0) + return 0; + for (i=0; is2->key_material_length; i += md_size) + { + if (((km - s->s2->key_material) + md_size) > + (int)sizeof(s->s2->key_material)) + { + /* EVP_DigestFinal_ex() below would write beyond buffer */ + SSLerr(SSL_F_SSL2_GENERATE_KEY_MATERIAL, ERR_R_INTERNAL_ERROR); + return 0; + } + + EVP_DigestInit_ex(&ctx, md5, NULL); + + OPENSSL_assert(s->session->master_key_length >= 0 + && s->session->master_key_length + < (int)sizeof(s->session->master_key)); + EVP_DigestUpdate(&ctx,s->session->master_key,s->session->master_key_length); + EVP_DigestUpdate(&ctx,&c,1); + c++; + EVP_DigestUpdate(&ctx,s->s2->challenge,s->s2->challenge_length); + EVP_DigestUpdate(&ctx,s->s2->conn_id,s->s2->conn_id_length); + EVP_DigestFinal_ex(&ctx,km,NULL); + km += md_size; + } + + EVP_MD_CTX_cleanup(&ctx); + return 1; + } + +void ssl2_return_error(SSL *s, int err) + { + if (!s->error) + { + s->error=3; + s->error_code=err; + + ssl2_write_error(s); + } + } + + +void ssl2_write_error(SSL *s) + { + unsigned char buf[3]; + int i,error; + + buf[0]=SSL2_MT_ERROR; + buf[1]=(s->error_code>>8)&0xff; + buf[2]=(s->error_code)&0xff; + +/* state=s->rwstate;*/ + + error=s->error; /* number of bytes left to write */ + s->error=0; + OPENSSL_assert(error >= 0 && error <= (int)sizeof(buf)); + i=ssl2_write(s,&(buf[3-error]),error); + +/* if (i == error) s->rwstate=state; */ + + if (i < 0) + s->error=error; + else + { + s->error=error-i; + + if (s->error == 0) + if (s->msg_callback) + s->msg_callback(1, s->version, 0, buf, 3, s, s->msg_callback_arg); /* ERROR */ + } + } + +int ssl2_shutdown(SSL *s) + { + s->shutdown=(SSL_SENT_SHUTDOWN|SSL_RECEIVED_SHUTDOWN); + return(1); + } +#else /* !OPENSSL_NO_SSL2 */ + +# if PEDANTIC +static void *dummy=&dummy; +# endif + +#endif diff --git a/node-v0.8.14/deps/openssl/openssl/ssl/s2_meth.c b/node-v0.8.14/deps/openssl/openssl/ssl/s2_meth.c new file mode 100644 index 0000000..f0e8ca5 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/ssl/s2_meth.c @@ -0,0 +1,84 @@ +/* ssl/s2_meth.c */ +/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com) + * All rights reserved. + * + * This package is an SSL implementation written + * by Eric Young (eay@cryptsoft.com). + * The implementation was written so as to conform with Netscapes SSL. + * + * This library is free for commercial and non-commercial use as long as + * the following conditions are aheared to. The following conditions + * apply to all code found in this distribution, be it the RC4, RSA, + * lhash, DES, etc., code; not just the SSL code. The SSL documentation + * included with this distribution is covered by the same copyright terms + * except that the holder is Tim Hudson (tjh@cryptsoft.com). + * + * Copyright remains Eric Young's, and as such any Copyright notices in + * the code are not to be removed. + * If this package is used in a product, Eric Young should be given attribution + * as the author of the parts of the library used. + * This can be in the form of a textual message at program startup or + * in documentation (online or textual) provided with the package. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * "This product includes cryptographic software written by + * Eric Young (eay@cryptsoft.com)" + * The word 'cryptographic' can be left out if the rouines from the library + * being used are not cryptographic related :-). + * 4. If you include any Windows specific code (or a derivative thereof) from + * the apps directory (application code) you must include an acknowledgement: + * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)" + * + * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * + * The licence and distribution terms for any publically available version or + * derivative of this code cannot be changed. i.e. this code cannot simply be + * copied and put under another distribution licence + * [including the GNU Public Licence.] + */ + +#include "ssl_locl.h" +#ifndef OPENSSL_NO_SSL2 +#include +#include + +static const SSL_METHOD *ssl2_get_method(int ver); +static const SSL_METHOD *ssl2_get_method(int ver) + { + if (ver == SSL2_VERSION) + return(SSLv2_method()); + else + return(NULL); + } + +IMPLEMENT_ssl2_meth_func(SSLv2_method, + ssl2_accept, + ssl2_connect, + ssl2_get_method) + +#else /* !OPENSSL_NO_SSL2 */ + +# if PEDANTIC +static void *dummy=&dummy; +# endif + +#endif diff --git a/node-v0.8.14/deps/openssl/openssl/ssl/s2_pkt.c b/node-v0.8.14/deps/openssl/openssl/ssl/s2_pkt.c new file mode 100644 index 0000000..ac963b2 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/ssl/s2_pkt.c @@ -0,0 +1,744 @@ +/* ssl/s2_pkt.c */ +/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com) + * All rights reserved. + * + * This package is an SSL implementation written + * by Eric Young (eay@cryptsoft.com). + * The implementation was written so as to conform with Netscapes SSL. + * + * This library is free for commercial and non-commercial use as long as + * the following conditions are aheared to. The following conditions + * apply to all code found in this distribution, be it the RC4, RSA, + * lhash, DES, etc., code; not just the SSL code. The SSL documentation + * included with this distribution is covered by the same copyright terms + * except that the holder is Tim Hudson (tjh@cryptsoft.com). + * + * Copyright remains Eric Young's, and as such any Copyright notices in + * the code are not to be removed. + * If this package is used in a product, Eric Young should be given attribution + * as the author of the parts of the library used. + * This can be in the form of a textual message at program startup or + * in documentation (online or textual) provided with the package. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * "This product includes cryptographic software written by + * Eric Young (eay@cryptsoft.com)" + * The word 'cryptographic' can be left out if the rouines from the library + * being used are not cryptographic related :-). + * 4. If you include any Windows specific code (or a derivative thereof) from + * the apps directory (application code) you must include an acknowledgement: + * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)" + * + * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * + * The licence and distribution terms for any publically available version or + * derivative of this code cannot be changed. i.e. this code cannot simply be + * copied and put under another distribution licence + * [including the GNU Public Licence.] + */ +/* ==================================================================== + * Copyright (c) 1998-2001 The OpenSSL Project. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. All advertising materials mentioning features or use of this + * software must display the following acknowledgment: + * "This product includes software developed by the OpenSSL Project + * for use in the OpenSSL Toolkit. (http://www.openssl.org/)" + * + * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to + * endorse or promote products derived from this software without + * prior written permission. For written permission, please contact + * openssl-core@openssl.org. + * + * 5. Products derived from this software may not be called "OpenSSL" + * nor may "OpenSSL" appear in their names without prior written + * permission of the OpenSSL Project. + * + * 6. Redistributions of any form whatsoever must retain the following + * acknowledgment: + * "This product includes software developed by the OpenSSL Project + * for use in the OpenSSL Toolkit (http://www.openssl.org/)" + * + * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY + * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR + * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, + * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * ==================================================================== + * + * This product includes cryptographic software written by Eric Young + * (eay@cryptsoft.com). This product includes software written by Tim + * Hudson (tjh@cryptsoft.com). + * + */ + +#include "ssl_locl.h" +#ifndef OPENSSL_NO_SSL2 +#include +#include +#define USE_SOCKETS + +static int read_n(SSL *s,unsigned int n,unsigned int max,unsigned int extend); +static int n_do_ssl_write(SSL *s, const unsigned char *buf, unsigned int len); +static int write_pending(SSL *s, const unsigned char *buf, unsigned int len); +static int ssl_mt_error(int n); + + +/* SSL 2.0 imlementation for SSL_read/SSL_peek - + * This routine will return 0 to len bytes, decrypted etc if required. + */ +static int ssl2_read_internal(SSL *s, void *buf, int len, int peek) + { + int n; + unsigned char mac[MAX_MAC_SIZE]; + unsigned char *p; + int i; + int mac_size; + + ssl2_read_again: + if (SSL_in_init(s) && !s->in_handshake) + { + n=s->handshake_func(s); + if (n < 0) return(n); + if (n == 0) + { + SSLerr(SSL_F_SSL2_READ_INTERNAL,SSL_R_SSL_HANDSHAKE_FAILURE); + return(-1); + } + } + + clear_sys_error(); + s->rwstate=SSL_NOTHING; + if (len <= 0) return(len); + + if (s->s2->ract_data_length != 0) /* read from buffer */ + { + if (len > s->s2->ract_data_length) + n=s->s2->ract_data_length; + else + n=len; + + memcpy(buf,s->s2->ract_data,(unsigned int)n); + if (!peek) + { + s->s2->ract_data_length-=n; + s->s2->ract_data+=n; + if (s->s2->ract_data_length == 0) + s->rstate=SSL_ST_READ_HEADER; + } + + return(n); + } + + /* s->s2->ract_data_length == 0 + * + * Fill the buffer, then goto ssl2_read_again. + */ + + if (s->rstate == SSL_ST_READ_HEADER) + { + if (s->first_packet) + { + n=read_n(s,5,SSL2_MAX_RECORD_LENGTH_2_BYTE_HEADER+2,0); + if (n <= 0) return(n); /* error or non-blocking */ + s->first_packet=0; + p=s->packet; + if (!((p[0] & 0x80) && ( + (p[2] == SSL2_MT_CLIENT_HELLO) || + (p[2] == SSL2_MT_SERVER_HELLO)))) + { + SSLerr(SSL_F_SSL2_READ_INTERNAL,SSL_R_NON_SSLV2_INITIAL_PACKET); + return(-1); + } + } + else + { + n=read_n(s,2,SSL2_MAX_RECORD_LENGTH_2_BYTE_HEADER+2,0); + if (n <= 0) return(n); /* error or non-blocking */ + } + /* part read stuff */ + + s->rstate=SSL_ST_READ_BODY; + p=s->packet; + /* Do header */ + /*s->s2->padding=0;*/ + s->s2->escape=0; + s->s2->rlength=(((unsigned int)p[0])<<8)|((unsigned int)p[1]); + if ((p[0] & TWO_BYTE_BIT)) /* Two byte header? */ + { + s->s2->three_byte_header=0; + s->s2->rlength&=TWO_BYTE_MASK; + } + else + { + s->s2->three_byte_header=1; + s->s2->rlength&=THREE_BYTE_MASK; + + /* security >s2->escape */ + s->s2->escape=((p[0] & SEC_ESC_BIT))?1:0; + } + } + + if (s->rstate == SSL_ST_READ_BODY) + { + n=s->s2->rlength+2+s->s2->three_byte_header; + if (n > (int)s->packet_length) + { + n-=s->packet_length; + i=read_n(s,(unsigned int)n,(unsigned int)n,1); + if (i <= 0) return(i); /* ERROR */ + } + + p= &(s->packet[2]); + s->rstate=SSL_ST_READ_HEADER; + if (s->s2->three_byte_header) + s->s2->padding= *(p++); + else s->s2->padding=0; + + /* Data portion */ + if (s->s2->clear_text) + { + mac_size = 0; + s->s2->mac_data=p; + s->s2->ract_data=p; + if (s->s2->padding) + { + SSLerr(SSL_F_SSL2_READ_INTERNAL,SSL_R_ILLEGAL_PADDING); + return(-1); + } + } + else + { + mac_size=EVP_MD_CTX_size(s->read_hash); + if (mac_size < 0) + return -1; + OPENSSL_assert(mac_size <= MAX_MAC_SIZE); + s->s2->mac_data=p; + s->s2->ract_data= &p[mac_size]; + if (s->s2->padding + mac_size > s->s2->rlength) + { + SSLerr(SSL_F_SSL2_READ_INTERNAL,SSL_R_ILLEGAL_PADDING); + return(-1); + } + } + + s->s2->ract_data_length=s->s2->rlength; + /* added a check for length > max_size in case + * encryption was not turned on yet due to an error */ + if ((!s->s2->clear_text) && + (s->s2->rlength >= (unsigned int)mac_size)) + { + ssl2_enc(s,0); + s->s2->ract_data_length-=mac_size; + ssl2_mac(s,mac,0); + s->s2->ract_data_length-=s->s2->padding; + if ( (memcmp(mac,s->s2->mac_data, + (unsigned int)mac_size) != 0) || + (s->s2->rlength%EVP_CIPHER_CTX_block_size(s->enc_read_ctx) != 0)) + { + SSLerr(SSL_F_SSL2_READ_INTERNAL,SSL_R_BAD_MAC_DECODE); + return(-1); + } + } + INC32(s->s2->read_sequence); /* expect next number */ + /* s->s2->ract_data is now available for processing */ + + /* Possibly the packet that we just read had 0 actual data bytes. + * (SSLeay/OpenSSL itself never sends such packets; see ssl2_write.) + * In this case, returning 0 would be interpreted by the caller + * as indicating EOF, so it's not a good idea. Instead, we just + * continue reading; thus ssl2_read_internal may have to process + * multiple packets before it can return. + * + * [Note that using select() for blocking sockets *never* guarantees + * that the next SSL_read will not block -- the available + * data may contain incomplete packets, and except for SSL 2, + * renegotiation can confuse things even more.] */ + + goto ssl2_read_again; /* This should really be + * "return ssl2_read(s,buf,len)", + * but that would allow for + * denial-of-service attacks if a + * C compiler is used that does not + * recognize end-recursion. */ + } + else + { + SSLerr(SSL_F_SSL2_READ_INTERNAL,SSL_R_BAD_STATE); + return(-1); + } + } + +int ssl2_read(SSL *s, void *buf, int len) + { + return ssl2_read_internal(s, buf, len, 0); + } + +int ssl2_peek(SSL *s, void *buf, int len) + { + return ssl2_read_internal(s, buf, len, 1); + } + +static int read_n(SSL *s, unsigned int n, unsigned int max, + unsigned int extend) + { + int i,off,newb; + + /* if there is stuff still in the buffer from a previous read, + * and there is more than we want, take some. */ + if (s->s2->rbuf_left >= (int)n) + { + if (extend) + s->packet_length+=n; + else + { + s->packet= &(s->s2->rbuf[s->s2->rbuf_offs]); + s->packet_length=n; + } + s->s2->rbuf_left-=n; + s->s2->rbuf_offs+=n; + return(n); + } + + if (!s->read_ahead) max=n; + if (max > (unsigned int)(SSL2_MAX_RECORD_LENGTH_2_BYTE_HEADER+2)) + max=SSL2_MAX_RECORD_LENGTH_2_BYTE_HEADER+2; + + + /* Else we want more than we have. + * First, if there is some left or we want to extend */ + off=0; + if ((s->s2->rbuf_left != 0) || ((s->packet_length != 0) && extend)) + { + newb=s->s2->rbuf_left; + if (extend) + { + off=s->packet_length; + if (s->packet != s->s2->rbuf) + memcpy(s->s2->rbuf,s->packet, + (unsigned int)newb+off); + } + else if (s->s2->rbuf_offs != 0) + { + memcpy(s->s2->rbuf,&(s->s2->rbuf[s->s2->rbuf_offs]), + (unsigned int)newb); + s->s2->rbuf_offs=0; + } + s->s2->rbuf_left=0; + } + else + newb=0; + + /* off is the offset to start writing too. + * r->s2->rbuf_offs is the 'unread data', now 0. + * newb is the number of new bytes so far + */ + s->packet=s->s2->rbuf; + while (newb < (int)n) + { + clear_sys_error(); + if (s->rbio != NULL) + { + s->rwstate=SSL_READING; + i=BIO_read(s->rbio,(char *)&(s->s2->rbuf[off+newb]), + max-newb); + } + else + { + SSLerr(SSL_F_READ_N,SSL_R_READ_BIO_NOT_SET); + i= -1; + } +#ifdef PKT_DEBUG + if (s->debug & 0x01) sleep(1); +#endif + if (i <= 0) + { + s->s2->rbuf_left+=newb; + return(i); + } + newb+=i; + } + + /* record unread data */ + if (newb > (int)n) + { + s->s2->rbuf_offs=n+off; + s->s2->rbuf_left=newb-n; + } + else + { + s->s2->rbuf_offs=0; + s->s2->rbuf_left=0; + } + if (extend) + s->packet_length+=n; + else + s->packet_length=n; + s->rwstate=SSL_NOTHING; + return(n); + } + +int ssl2_write(SSL *s, const void *_buf, int len) + { + const unsigned char *buf=_buf; + unsigned int n,tot; + int i; + + if (SSL_in_init(s) && !s->in_handshake) + { + i=s->handshake_func(s); + if (i < 0) return(i); + if (i == 0) + { + SSLerr(SSL_F_SSL2_WRITE,SSL_R_SSL_HANDSHAKE_FAILURE); + return(-1); + } + } + + if (s->error) + { + ssl2_write_error(s); + if (s->error) + return(-1); + } + + clear_sys_error(); + s->rwstate=SSL_NOTHING; + if (len <= 0) return(len); + + tot=s->s2->wnum; + s->s2->wnum=0; + + n=(len-tot); + for (;;) + { + i=n_do_ssl_write(s,&(buf[tot]),n); + if (i <= 0) + { + s->s2->wnum=tot; + return(i); + } + if ((i == (int)n) || + (s->mode & SSL_MODE_ENABLE_PARTIAL_WRITE)) + { + return(tot+i); + } + + n-=i; + tot+=i; + } + } + +static int write_pending(SSL *s, const unsigned char *buf, unsigned int len) + { + int i; + + /* s->s2->wpend_len != 0 MUST be true. */ + + /* check that they have given us the same buffer to + * write */ + if ((s->s2->wpend_tot > (int)len) || + ((s->s2->wpend_buf != buf) && + !(s->mode & SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER))) + { + SSLerr(SSL_F_WRITE_PENDING,SSL_R_BAD_WRITE_RETRY); + return(-1); + } + + for (;;) + { + clear_sys_error(); + if (s->wbio != NULL) + { + s->rwstate=SSL_WRITING; + i=BIO_write(s->wbio, + (char *)&(s->s2->write_ptr[s->s2->wpend_off]), + (unsigned int)s->s2->wpend_len); + } + else + { + SSLerr(SSL_F_WRITE_PENDING,SSL_R_WRITE_BIO_NOT_SET); + i= -1; + } +#ifdef PKT_DEBUG + if (s->debug & 0x01) sleep(1); +#endif + if (i == s->s2->wpend_len) + { + s->s2->wpend_len=0; + s->rwstate=SSL_NOTHING; + return(s->s2->wpend_ret); + } + else if (i <= 0) + return(i); + s->s2->wpend_off+=i; + s->s2->wpend_len-=i; + } + } + +static int n_do_ssl_write(SSL *s, const unsigned char *buf, unsigned int len) + { + unsigned int j,k,olen,p,bs; + int mac_size; + register unsigned char *pp; + + olen=len; + + /* first check if there is data from an encryption waiting to + * be sent - it must be sent because the other end is waiting. + * This will happen with non-blocking IO. We print it and then + * return. + */ + if (s->s2->wpend_len != 0) return(write_pending(s,buf,len)); + + /* set mac_size to mac size */ + if (s->s2->clear_text) + mac_size=0; + else + { + mac_size=EVP_MD_CTX_size(s->write_hash); + if (mac_size < 0) + return -1; + } + + /* lets set the pad p */ + if (s->s2->clear_text) + { + if (len > SSL2_MAX_RECORD_LENGTH_2_BYTE_HEADER) + len=SSL2_MAX_RECORD_LENGTH_2_BYTE_HEADER; + p=0; + s->s2->three_byte_header=0; + /* len=len; */ + } + else + { + bs=EVP_CIPHER_CTX_block_size(s->enc_read_ctx); + j=len+mac_size; + /* Two-byte headers allow for a larger record length than + * three-byte headers, but we can't use them if we need + * padding or if we have to set the escape bit. */ + if ((j > SSL2_MAX_RECORD_LENGTH_3_BYTE_HEADER) && + (!s->s2->escape)) + { + if (j > SSL2_MAX_RECORD_LENGTH_2_BYTE_HEADER) + j=SSL2_MAX_RECORD_LENGTH_2_BYTE_HEADER; + /* set k to the max number of bytes with 2 + * byte header */ + k=j-(j%bs); + /* how many data bytes? */ + len=k-mac_size; + s->s2->three_byte_header=0; + p=0; + } + else if ((bs <= 1) && (!s->s2->escape)) + { + /* j <= SSL2_MAX_RECORD_LENGTH_3_BYTE_HEADER, thus + * j < SSL2_MAX_RECORD_LENGTH_2_BYTE_HEADER */ + s->s2->three_byte_header=0; + p=0; + } + else /* we may have to use a 3 byte header */ + { + /* If s->s2->escape is not set, then + * j <= SSL2_MAX_RECORD_LENGTH_3_BYTE_HEADER, and thus + * j < SSL2_MAX_RECORD_LENGTH_2_BYTE_HEADER. */ + p=(j%bs); + p=(p == 0)?0:(bs-p); + if (s->s2->escape) + { + s->s2->three_byte_header=1; + if (j > SSL2_MAX_RECORD_LENGTH_3_BYTE_HEADER) + j=SSL2_MAX_RECORD_LENGTH_3_BYTE_HEADER; + } + else + s->s2->three_byte_header=(p == 0)?0:1; + } + } + + /* Now + * j <= SSL2_MAX_RECORD_LENGTH_2_BYTE_HEADER + * holds, and if s->s2->three_byte_header is set, then even + * j <= SSL2_MAX_RECORD_LENGTH_3_BYTE_HEADER. + */ + + /* mac_size is the number of MAC bytes + * len is the number of data bytes we are going to send + * p is the number of padding bytes + * (if it is a two-byte header, then p == 0) */ + + s->s2->wlength=len; + s->s2->padding=p; + s->s2->mac_data= &(s->s2->wbuf[3]); + s->s2->wact_data= &(s->s2->wbuf[3+mac_size]); + /* we copy the data into s->s2->wbuf */ + memcpy(s->s2->wact_data,buf,len); + if (p) + memset(&(s->s2->wact_data[len]),0,p); /* arbitrary padding */ + + if (!s->s2->clear_text) + { + s->s2->wact_data_length=len+p; + ssl2_mac(s,s->s2->mac_data,1); + s->s2->wlength+=p+mac_size; + ssl2_enc(s,1); + } + + /* package up the header */ + s->s2->wpend_len=s->s2->wlength; + if (s->s2->three_byte_header) /* 3 byte header */ + { + pp=s->s2->mac_data; + pp-=3; + pp[0]=(s->s2->wlength>>8)&(THREE_BYTE_MASK>>8); + if (s->s2->escape) pp[0]|=SEC_ESC_BIT; + pp[1]=s->s2->wlength&0xff; + pp[2]=s->s2->padding; + s->s2->wpend_len+=3; + } + else + { + pp=s->s2->mac_data; + pp-=2; + pp[0]=((s->s2->wlength>>8)&(TWO_BYTE_MASK>>8))|TWO_BYTE_BIT; + pp[1]=s->s2->wlength&0xff; + s->s2->wpend_len+=2; + } + s->s2->write_ptr=pp; + + INC32(s->s2->write_sequence); /* expect next number */ + + /* lets try to actually write the data */ + s->s2->wpend_tot=olen; + s->s2->wpend_buf=buf; + + s->s2->wpend_ret=len; + + s->s2->wpend_off=0; + return(write_pending(s,buf,olen)); + } + +int ssl2_part_read(SSL *s, unsigned long f, int i) + { + unsigned char *p; + int j; + + if (i < 0) + { + /* ssl2_return_error(s); */ + /* for non-blocking io, + * this is not necessarily fatal */ + return(i); + } + else + { + s->init_num+=i; + + /* Check for error. While there are recoverable errors, + * this function is not called when those must be expected; + * any error detected here is fatal. */ + if (s->init_num >= 3) + { + p=(unsigned char *)s->init_buf->data; + if (p[0] == SSL2_MT_ERROR) + { + j=(p[1]<<8)|p[2]; + SSLerr((int)f,ssl_mt_error(j)); + s->init_num -= 3; + if (s->init_num > 0) + memmove(p, p+3, s->init_num); + } + } + + /* If it's not an error message, we have some error anyway -- + * the message was shorter than expected. This too is treated + * as fatal (at least if SSL_get_error is asked for its opinion). */ + return(0); + } + } + +int ssl2_do_write(SSL *s) + { + int ret; + + ret=ssl2_write(s,&s->init_buf->data[s->init_off],s->init_num); + if (ret == s->init_num) + { + if (s->msg_callback) + s->msg_callback(1, s->version, 0, s->init_buf->data, (size_t)(s->init_off + s->init_num), s, s->msg_callback_arg); + return(1); + } + if (ret < 0) + return(-1); + s->init_off+=ret; + s->init_num-=ret; + return(0); + } + +static int ssl_mt_error(int n) + { + int ret; + + switch (n) + { + case SSL2_PE_NO_CIPHER: + ret=SSL_R_PEER_ERROR_NO_CIPHER; + break; + case SSL2_PE_NO_CERTIFICATE: + ret=SSL_R_PEER_ERROR_NO_CERTIFICATE; + break; + case SSL2_PE_BAD_CERTIFICATE: + ret=SSL_R_PEER_ERROR_CERTIFICATE; + break; + case SSL2_PE_UNSUPPORTED_CERTIFICATE_TYPE: + ret=SSL_R_PEER_ERROR_UNSUPPORTED_CERTIFICATE_TYPE; + break; + default: + ret=SSL_R_UNKNOWN_REMOTE_ERROR_TYPE; + break; + } + return(ret); + } +#else /* !OPENSSL_NO_SSL2 */ + +# if PEDANTIC +static void *dummy=&dummy; +# endif + +#endif diff --git a/node-v0.8.14/deps/openssl/openssl/ssl/s2_srvr.c b/node-v0.8.14/deps/openssl/openssl/ssl/s2_srvr.c new file mode 100644 index 0000000..bc885e8 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/ssl/s2_srvr.c @@ -0,0 +1,1142 @@ +/* ssl/s2_srvr.c */ +/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com) + * All rights reserved. + * + * This package is an SSL implementation written + * by Eric Young (eay@cryptsoft.com). + * The implementation was written so as to conform with Netscapes SSL. + * + * This library is free for commercial and non-commercial use as long as + * the following conditions are aheared to. The following conditions + * apply to all code found in this distribution, be it the RC4, RSA, + * lhash, DES, etc., code; not just the SSL code. The SSL documentation + * included with this distribution is covered by the same copyright terms + * except that the holder is Tim Hudson (tjh@cryptsoft.com). + * + * Copyright remains Eric Young's, and as such any Copyright notices in + * the code are not to be removed. + * If this package is used in a product, Eric Young should be given attribution + * as the author of the parts of the library used. + * This can be in the form of a textual message at program startup or + * in documentation (online or textual) provided with the package. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * "This product includes cryptographic software written by + * Eric Young (eay@cryptsoft.com)" + * The word 'cryptographic' can be left out if the rouines from the library + * being used are not cryptographic related :-). + * 4. If you include any Windows specific code (or a derivative thereof) from + * the apps directory (application code) you must include an acknowledgement: + * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)" + * + * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * + * The licence and distribution terms for any publically available version or + * derivative of this code cannot be changed. i.e. this code cannot simply be + * copied and put under another distribution licence + * [including the GNU Public Licence.] + */ +/* ==================================================================== + * Copyright (c) 1998-2001 The OpenSSL Project. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. All advertising materials mentioning features or use of this + * software must display the following acknowledgment: + * "This product includes software developed by the OpenSSL Project + * for use in the OpenSSL Toolkit. (http://www.openssl.org/)" + * + * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to + * endorse or promote products derived from this software without + * prior written permission. For written permission, please contact + * openssl-core@openssl.org. + * + * 5. Products derived from this software may not be called "OpenSSL" + * nor may "OpenSSL" appear in their names without prior written + * permission of the OpenSSL Project. + * + * 6. Redistributions of any form whatsoever must retain the following + * acknowledgment: + * "This product includes software developed by the OpenSSL Project + * for use in the OpenSSL Toolkit (http://www.openssl.org/)" + * + * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY + * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR + * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, + * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * ==================================================================== + * + * This product includes cryptographic software written by Eric Young + * (eay@cryptsoft.com). This product includes software written by Tim + * Hudson (tjh@cryptsoft.com). + * + */ + +#include "ssl_locl.h" +#ifndef OPENSSL_NO_SSL2 +#include +#include +#include +#include +#include + +static const SSL_METHOD *ssl2_get_server_method(int ver); +static int get_client_master_key(SSL *s); +static int get_client_hello(SSL *s); +static int server_hello(SSL *s); +static int get_client_finished(SSL *s); +static int server_verify(SSL *s); +static int server_finish(SSL *s); +static int request_certificate(SSL *s); +static int ssl_rsa_private_decrypt(CERT *c, int len, unsigned char *from, + unsigned char *to,int padding); +#define BREAK break + +static const SSL_METHOD *ssl2_get_server_method(int ver) + { + if (ver == SSL2_VERSION) + return(SSLv2_server_method()); + else + return(NULL); + } + +IMPLEMENT_ssl2_meth_func(SSLv2_server_method, + ssl2_accept, + ssl_undefined_function, + ssl2_get_server_method) + +int ssl2_accept(SSL *s) + { + unsigned long l=(unsigned long)time(NULL); + BUF_MEM *buf=NULL; + int ret= -1; + long num1; + void (*cb)(const SSL *ssl,int type,int val)=NULL; + int new_state,state; + + RAND_add(&l,sizeof(l),0); + ERR_clear_error(); + clear_sys_error(); + + if (s->info_callback != NULL) + cb=s->info_callback; + else if (s->ctx->info_callback != NULL) + cb=s->ctx->info_callback; + + /* init things to blank */ + s->in_handshake++; + if (!SSL_in_init(s) || SSL_in_before(s)) SSL_clear(s); + + if (s->cert == NULL) + { + SSLerr(SSL_F_SSL2_ACCEPT,SSL_R_NO_CERTIFICATE_SET); + return(-1); + } + + clear_sys_error(); + for (;;) + { + state=s->state; + + switch (s->state) + { + case SSL_ST_BEFORE: + case SSL_ST_ACCEPT: + case SSL_ST_BEFORE|SSL_ST_ACCEPT: + case SSL_ST_OK|SSL_ST_ACCEPT: + + s->server=1; + if (cb != NULL) cb(s,SSL_CB_HANDSHAKE_START,1); + + s->version=SSL2_VERSION; + s->type=SSL_ST_ACCEPT; + + buf=s->init_buf; + if ((buf == NULL) && ((buf=BUF_MEM_new()) == NULL)) + { ret= -1; goto end; } + if (!BUF_MEM_grow(buf,(int) + SSL2_MAX_RECORD_LENGTH_3_BYTE_HEADER)) + { ret= -1; goto end; } + s->init_buf=buf; + s->init_num=0; + s->ctx->stats.sess_accept++; + s->handshake_func=ssl2_accept; + s->state=SSL2_ST_GET_CLIENT_HELLO_A; + BREAK; + + case SSL2_ST_GET_CLIENT_HELLO_A: + case SSL2_ST_GET_CLIENT_HELLO_B: + case SSL2_ST_GET_CLIENT_HELLO_C: + s->shutdown=0; + ret=get_client_hello(s); + if (ret <= 0) goto end; + s->init_num=0; + s->state=SSL2_ST_SEND_SERVER_HELLO_A; + BREAK; + + case SSL2_ST_SEND_SERVER_HELLO_A: + case SSL2_ST_SEND_SERVER_HELLO_B: + ret=server_hello(s); + if (ret <= 0) goto end; + s->init_num=0; + if (!s->hit) + { + s->state=SSL2_ST_GET_CLIENT_MASTER_KEY_A; + BREAK; + } + else + { + s->state=SSL2_ST_SERVER_START_ENCRYPTION; + BREAK; + } + case SSL2_ST_GET_CLIENT_MASTER_KEY_A: + case SSL2_ST_GET_CLIENT_MASTER_KEY_B: + ret=get_client_master_key(s); + if (ret <= 0) goto end; + s->init_num=0; + s->state=SSL2_ST_SERVER_START_ENCRYPTION; + BREAK; + + case SSL2_ST_SERVER_START_ENCRYPTION: + /* Ok we how have sent all the stuff needed to + * start encrypting, the next packet back will + * be encrypted. */ + if (!ssl2_enc_init(s,0)) + { ret= -1; goto end; } + s->s2->clear_text=0; + s->state=SSL2_ST_SEND_SERVER_VERIFY_A; + BREAK; + + case SSL2_ST_SEND_SERVER_VERIFY_A: + case SSL2_ST_SEND_SERVER_VERIFY_B: + ret=server_verify(s); + if (ret <= 0) goto end; + s->init_num=0; + if (s->hit) + { + /* If we are in here, we have been + * buffering the output, so we need to + * flush it and remove buffering from + * future traffic */ + s->state=SSL2_ST_SEND_SERVER_VERIFY_C; + BREAK; + } + else + { + s->state=SSL2_ST_GET_CLIENT_FINISHED_A; + break; + } + + case SSL2_ST_SEND_SERVER_VERIFY_C: + /* get the number of bytes to write */ + num1=BIO_ctrl(s->wbio,BIO_CTRL_INFO,0,NULL); + if (num1 > 0) + { + s->rwstate=SSL_WRITING; + num1=BIO_flush(s->wbio); + if (num1 <= 0) { ret= -1; goto end; } + s->rwstate=SSL_NOTHING; + } + + /* flushed and now remove buffering */ + s->wbio=BIO_pop(s->wbio); + + s->state=SSL2_ST_GET_CLIENT_FINISHED_A; + BREAK; + + case SSL2_ST_GET_CLIENT_FINISHED_A: + case SSL2_ST_GET_CLIENT_FINISHED_B: + ret=get_client_finished(s); + if (ret <= 0) + goto end; + s->init_num=0; + s->state=SSL2_ST_SEND_REQUEST_CERTIFICATE_A; + BREAK; + + case SSL2_ST_SEND_REQUEST_CERTIFICATE_A: + case SSL2_ST_SEND_REQUEST_CERTIFICATE_B: + case SSL2_ST_SEND_REQUEST_CERTIFICATE_C: + case SSL2_ST_SEND_REQUEST_CERTIFICATE_D: + /* don't do a 'request certificate' if we + * don't want to, or we already have one, and + * we only want to do it once. */ + if (!(s->verify_mode & SSL_VERIFY_PEER) || + ((s->session->peer != NULL) && + (s->verify_mode & SSL_VERIFY_CLIENT_ONCE))) + { + s->state=SSL2_ST_SEND_SERVER_FINISHED_A; + break; + } + else + { + ret=request_certificate(s); + if (ret <= 0) goto end; + s->init_num=0; + s->state=SSL2_ST_SEND_SERVER_FINISHED_A; + } + BREAK; + + case SSL2_ST_SEND_SERVER_FINISHED_A: + case SSL2_ST_SEND_SERVER_FINISHED_B: + ret=server_finish(s); + if (ret <= 0) goto end; + s->init_num=0; + s->state=SSL_ST_OK; + break; + + case SSL_ST_OK: + BUF_MEM_free(s->init_buf); + ssl_free_wbio_buffer(s); + s->init_buf=NULL; + s->init_num=0; + /* ERR_clear_error();*/ + + ssl_update_cache(s,SSL_SESS_CACHE_SERVER); + + s->ctx->stats.sess_accept_good++; + /* s->server=1; */ + ret=1; + + if (cb != NULL) cb(s,SSL_CB_HANDSHAKE_DONE,1); + + goto end; + /* BREAK; */ + + default: + SSLerr(SSL_F_SSL2_ACCEPT,SSL_R_UNKNOWN_STATE); + ret= -1; + goto end; + /* BREAK; */ + } + + if ((cb != NULL) && (s->state != state)) + { + new_state=s->state; + s->state=state; + cb(s,SSL_CB_ACCEPT_LOOP,1); + s->state=new_state; + } + } +end: + s->in_handshake--; + if (cb != NULL) + cb(s,SSL_CB_ACCEPT_EXIT,ret); + return(ret); + } + +static int get_client_master_key(SSL *s) + { + int is_export,i,n,keya,ek; + unsigned long len; + unsigned char *p; + const SSL_CIPHER *cp; + const EVP_CIPHER *c; + const EVP_MD *md; + + p=(unsigned char *)s->init_buf->data; + if (s->state == SSL2_ST_GET_CLIENT_MASTER_KEY_A) + { + i=ssl2_read(s,(char *)&(p[s->init_num]),10-s->init_num); + + if (i < (10-s->init_num)) + return(ssl2_part_read(s,SSL_F_GET_CLIENT_MASTER_KEY,i)); + s->init_num = 10; + + if (*(p++) != SSL2_MT_CLIENT_MASTER_KEY) + { + if (p[-1] != SSL2_MT_ERROR) + { + ssl2_return_error(s,SSL2_PE_UNDEFINED_ERROR); + SSLerr(SSL_F_GET_CLIENT_MASTER_KEY,SSL_R_READ_WRONG_PACKET_TYPE); + } + else + SSLerr(SSL_F_GET_CLIENT_MASTER_KEY, SSL_R_PEER_ERROR); + return(-1); + } + + cp=ssl2_get_cipher_by_char(p); + if (cp == NULL) + { + ssl2_return_error(s,SSL2_PE_NO_CIPHER); + SSLerr(SSL_F_GET_CLIENT_MASTER_KEY, SSL_R_NO_CIPHER_MATCH); + return(-1); + } + s->session->cipher= cp; + + p+=3; + n2s(p,i); s->s2->tmp.clear=i; + n2s(p,i); s->s2->tmp.enc=i; + n2s(p,i); + if(i > SSL_MAX_KEY_ARG_LENGTH) + { + ssl2_return_error(s,SSL2_PE_UNDEFINED_ERROR); + SSLerr(SSL_F_GET_CLIENT_MASTER_KEY, SSL_R_KEY_ARG_TOO_LONG); + return -1; + } + s->session->key_arg_length=i; + s->state=SSL2_ST_GET_CLIENT_MASTER_KEY_B; + } + + /* SSL2_ST_GET_CLIENT_MASTER_KEY_B */ + p=(unsigned char *)s->init_buf->data; + if (s->init_buf->length < SSL2_MAX_RECORD_LENGTH_3_BYTE_HEADER) + { + ssl2_return_error(s,SSL2_PE_UNDEFINED_ERROR); + SSLerr(SSL_F_GET_CLIENT_MASTER_KEY, ERR_R_INTERNAL_ERROR); + return -1; + } + keya=s->session->key_arg_length; + len = 10 + (unsigned long)s->s2->tmp.clear + (unsigned long)s->s2->tmp.enc + (unsigned long)keya; + if (len > SSL2_MAX_RECORD_LENGTH_3_BYTE_HEADER) + { + ssl2_return_error(s,SSL2_PE_UNDEFINED_ERROR); + SSLerr(SSL_F_GET_CLIENT_MASTER_KEY,SSL_R_MESSAGE_TOO_LONG); + return -1; + } + n = (int)len - s->init_num; + i = ssl2_read(s,(char *)&(p[s->init_num]),n); + if (i != n) return(ssl2_part_read(s,SSL_F_GET_CLIENT_MASTER_KEY,i)); + if (s->msg_callback) + s->msg_callback(0, s->version, 0, p, (size_t)len, s, s->msg_callback_arg); /* CLIENT-MASTER-KEY */ + p += 10; + + memcpy(s->session->key_arg,&(p[s->s2->tmp.clear+s->s2->tmp.enc]), + (unsigned int)keya); + + if (s->cert->pkeys[SSL_PKEY_RSA_ENC].privatekey == NULL) + { + ssl2_return_error(s,SSL2_PE_UNDEFINED_ERROR); + SSLerr(SSL_F_GET_CLIENT_MASTER_KEY,SSL_R_NO_PRIVATEKEY); + return(-1); + } + i=ssl_rsa_private_decrypt(s->cert,s->s2->tmp.enc, + &(p[s->s2->tmp.clear]),&(p[s->s2->tmp.clear]), + (s->s2->ssl2_rollback)?RSA_SSLV23_PADDING:RSA_PKCS1_PADDING); + + is_export=SSL_C_IS_EXPORT(s->session->cipher); + + if (!ssl_cipher_get_evp(s->session,&c,&md,NULL,NULL,NULL)) + { + ssl2_return_error(s,SSL2_PE_NO_CIPHER); + SSLerr(SSL_F_GET_CLIENT_MASTER_KEY,SSL_R_PROBLEMS_MAPPING_CIPHER_FUNCTIONS); + return(0); + } + + if (s->session->cipher->algorithm2 & SSL2_CF_8_BYTE_ENC) + { + is_export=1; + ek=8; + } + else + ek=5; + + /* bad decrypt */ +#if 1 + /* If a bad decrypt, continue with protocol but with a + * random master secret (Bleichenbacher attack) */ + if ((i < 0) || + ((!is_export && (i != EVP_CIPHER_key_length(c))) + || (is_export && ((i != ek) || (s->s2->tmp.clear+(unsigned int)i != + (unsigned int)EVP_CIPHER_key_length(c)))))) + { + ERR_clear_error(); + if (is_export) + i=ek; + else + i=EVP_CIPHER_key_length(c); + if (RAND_pseudo_bytes(p,i) <= 0) + return 0; + } +#else + if (i < 0) + { + error=1; + SSLerr(SSL_F_GET_CLIENT_MASTER_KEY,SSL_R_BAD_RSA_DECRYPT); + } + /* incorrect number of key bytes for non export cipher */ + else if ((!is_export && (i != EVP_CIPHER_key_length(c))) + || (is_export && ((i != ek) || (s->s2->tmp.clear+i != + EVP_CIPHER_key_length(c))))) + { + error=1; + SSLerr(SSL_F_GET_CLIENT_MASTER_KEY,SSL_R_WRONG_NUMBER_OF_KEY_BITS); + } + if (error) + { + ssl2_return_error(s,SSL2_PE_UNDEFINED_ERROR); + return(-1); + } +#endif + + if (is_export) i+=s->s2->tmp.clear; + + if (i > SSL_MAX_MASTER_KEY_LENGTH) + { + ssl2_return_error(s,SSL2_PE_UNDEFINED_ERROR); + SSLerr(SSL_F_GET_CLIENT_MASTER_KEY, ERR_R_INTERNAL_ERROR); + return -1; + } + s->session->master_key_length=i; + memcpy(s->session->master_key,p,(unsigned int)i); + return(1); + } + +static int get_client_hello(SSL *s) + { + int i,n; + unsigned long len; + unsigned char *p; + STACK_OF(SSL_CIPHER) *cs; /* a stack of SSL_CIPHERS */ + STACK_OF(SSL_CIPHER) *cl; /* the ones we want to use */ + STACK_OF(SSL_CIPHER) *prio, *allow; + int z; + + /* This is a bit of a hack to check for the correct packet + * type the first time round. */ + if (s->state == SSL2_ST_GET_CLIENT_HELLO_A) + { + s->first_packet=1; + s->state=SSL2_ST_GET_CLIENT_HELLO_B; + } + + p=(unsigned char *)s->init_buf->data; + if (s->state == SSL2_ST_GET_CLIENT_HELLO_B) + { + i=ssl2_read(s,(char *)&(p[s->init_num]),9-s->init_num); + if (i < (9-s->init_num)) + return(ssl2_part_read(s,SSL_F_GET_CLIENT_HELLO,i)); + s->init_num = 9; + + if (*(p++) != SSL2_MT_CLIENT_HELLO) + { + if (p[-1] != SSL2_MT_ERROR) + { + ssl2_return_error(s,SSL2_PE_UNDEFINED_ERROR); + SSLerr(SSL_F_GET_CLIENT_HELLO,SSL_R_READ_WRONG_PACKET_TYPE); + } + else + SSLerr(SSL_F_GET_CLIENT_HELLO,SSL_R_PEER_ERROR); + return(-1); + } + n2s(p,i); + if (i < s->version) s->version=i; + n2s(p,i); s->s2->tmp.cipher_spec_length=i; + n2s(p,i); s->s2->tmp.session_id_length=i; + n2s(p,i); s->s2->challenge_length=i; + if ( (i < SSL2_MIN_CHALLENGE_LENGTH) || + (i > SSL2_MAX_CHALLENGE_LENGTH)) + { + ssl2_return_error(s,SSL2_PE_UNDEFINED_ERROR); + SSLerr(SSL_F_GET_CLIENT_HELLO,SSL_R_INVALID_CHALLENGE_LENGTH); + return(-1); + } + s->state=SSL2_ST_GET_CLIENT_HELLO_C; + } + + /* SSL2_ST_GET_CLIENT_HELLO_C */ + p=(unsigned char *)s->init_buf->data; + len = 9 + (unsigned long)s->s2->tmp.cipher_spec_length + (unsigned long)s->s2->challenge_length + (unsigned long)s->s2->tmp.session_id_length; + if (len > SSL2_MAX_RECORD_LENGTH_3_BYTE_HEADER) + { + ssl2_return_error(s,SSL2_PE_UNDEFINED_ERROR); + SSLerr(SSL_F_GET_CLIENT_HELLO,SSL_R_MESSAGE_TOO_LONG); + return -1; + } + n = (int)len - s->init_num; + i = ssl2_read(s,(char *)&(p[s->init_num]),n); + if (i != n) return(ssl2_part_read(s,SSL_F_GET_CLIENT_HELLO,i)); + if (s->msg_callback) + s->msg_callback(0, s->version, 0, p, (size_t)len, s, s->msg_callback_arg); /* CLIENT-HELLO */ + p += 9; + + /* get session-id before cipher stuff so we can get out session + * structure if it is cached */ + /* session-id */ + if ((s->s2->tmp.session_id_length != 0) && + (s->s2->tmp.session_id_length != SSL2_SSL_SESSION_ID_LENGTH)) + { + ssl2_return_error(s,SSL2_PE_UNDEFINED_ERROR); + SSLerr(SSL_F_GET_CLIENT_HELLO,SSL_R_BAD_SSL_SESSION_ID_LENGTH); + return(-1); + } + + if (s->s2->tmp.session_id_length == 0) + { + if (!ssl_get_new_session(s,1)) + { + ssl2_return_error(s,SSL2_PE_UNDEFINED_ERROR); + return(-1); + } + } + else + { + i=ssl_get_prev_session(s,&(p[s->s2->tmp.cipher_spec_length]), + s->s2->tmp.session_id_length, NULL); + if (i == 1) + { /* previous session */ + s->hit=1; + } + else if (i == -1) + { + ssl2_return_error(s,SSL2_PE_UNDEFINED_ERROR); + return(-1); + } + else + { + if (s->cert == NULL) + { + ssl2_return_error(s,SSL2_PE_NO_CERTIFICATE); + SSLerr(SSL_F_GET_CLIENT_HELLO,SSL_R_NO_CERTIFICATE_SET); + return(-1); + } + + if (!ssl_get_new_session(s,1)) + { + ssl2_return_error(s,SSL2_PE_UNDEFINED_ERROR); + return(-1); + } + } + } + + if (!s->hit) + { + cs=ssl_bytes_to_cipher_list(s,p,s->s2->tmp.cipher_spec_length, + &s->session->ciphers); + if (cs == NULL) goto mem_err; + + cl=SSL_get_ciphers(s); + + if (s->options & SSL_OP_CIPHER_SERVER_PREFERENCE) + { + prio=sk_SSL_CIPHER_dup(cl); + if (prio == NULL) goto mem_err; + allow = cs; + } + else + { + prio = cs; + allow = cl; + } + for (z=0; zoptions & SSL_OP_CIPHER_SERVER_PREFERENCE) + { + sk_SSL_CIPHER_free(s->session->ciphers); + s->session->ciphers = prio; + } + /* s->session->ciphers should now have a list of + * ciphers that are on both the client and server. + * This list is ordered by the order the client sent + * the ciphers or in the order of the server's preference + * if SSL_OP_CIPHER_SERVER_PREFERENCE was set. + */ + } + p+=s->s2->tmp.cipher_spec_length; + /* done cipher selection */ + + /* session id extracted already */ + p+=s->s2->tmp.session_id_length; + + /* challenge */ + if (s->s2->challenge_length > sizeof s->s2->challenge) + { + ssl2_return_error(s,SSL2_PE_UNDEFINED_ERROR); + SSLerr(SSL_F_GET_CLIENT_HELLO, ERR_R_INTERNAL_ERROR); + return -1; + } + memcpy(s->s2->challenge,p,(unsigned int)s->s2->challenge_length); + return(1); +mem_err: + SSLerr(SSL_F_GET_CLIENT_HELLO,ERR_R_MALLOC_FAILURE); + return(0); + } + +static int server_hello(SSL *s) + { + unsigned char *p,*d; + int n,hit; + + p=(unsigned char *)s->init_buf->data; + if (s->state == SSL2_ST_SEND_SERVER_HELLO_A) + { + d=p+11; + *(p++)=SSL2_MT_SERVER_HELLO; /* type */ + hit=s->hit; + *(p++)=(unsigned char)hit; +#if 1 + if (!hit) + { + if (s->session->sess_cert != NULL) + /* This can't really happen because get_client_hello + * has called ssl_get_new_session, which does not set + * sess_cert. */ + ssl_sess_cert_free(s->session->sess_cert); + s->session->sess_cert = ssl_sess_cert_new(); + if (s->session->sess_cert == NULL) + { + SSLerr(SSL_F_SERVER_HELLO, ERR_R_MALLOC_FAILURE); + return(-1); + } + } + /* If 'hit' is set, then s->sess_cert may be non-NULL or NULL, + * depending on whether it survived in the internal cache + * or was retrieved from an external cache. + * If it is NULL, we cannot put any useful data in it anyway, + * so we don't touch it. + */ + +#else /* That's what used to be done when cert_st and sess_cert_st were + * the same. */ + if (!hit) + { /* else add cert to session */ + CRYPTO_add(&s->cert->references,1,CRYPTO_LOCK_SSL_CERT); + if (s->session->sess_cert != NULL) + ssl_cert_free(s->session->sess_cert); + s->session->sess_cert=s->cert; + } + else /* We have a session id-cache hit, if the + * session-id has no certificate listed against + * the 'cert' structure, grab the 'old' one + * listed against the SSL connection */ + { + if (s->session->sess_cert == NULL) + { + CRYPTO_add(&s->cert->references,1, + CRYPTO_LOCK_SSL_CERT); + s->session->sess_cert=s->cert; + } + } +#endif + + if (s->cert == NULL) + { + ssl2_return_error(s,SSL2_PE_NO_CERTIFICATE); + SSLerr(SSL_F_SERVER_HELLO,SSL_R_NO_CERTIFICATE_SPECIFIED); + return(-1); + } + + if (hit) + { + *(p++)=0; /* no certificate type */ + s2n(s->version,p); /* version */ + s2n(0,p); /* cert len */ + s2n(0,p); /* ciphers len */ + } + else + { + /* EAY EAY */ + /* put certificate type */ + *(p++)=SSL2_CT_X509_CERTIFICATE; + s2n(s->version,p); /* version */ + n=i2d_X509(s->cert->pkeys[SSL_PKEY_RSA_ENC].x509,NULL); + s2n(n,p); /* certificate length */ + i2d_X509(s->cert->pkeys[SSL_PKEY_RSA_ENC].x509,&d); + n=0; + + /* lets send out the ciphers we like in the + * prefered order */ + n=ssl_cipher_list_to_bytes(s,s->session->ciphers,d,0); + d+=n; + s2n(n,p); /* add cipher length */ + } + + /* make and send conn_id */ + s2n(SSL2_CONNECTION_ID_LENGTH,p); /* add conn_id length */ + s->s2->conn_id_length=SSL2_CONNECTION_ID_LENGTH; + if (RAND_pseudo_bytes(s->s2->conn_id,(int)s->s2->conn_id_length) <= 0) + return -1; + memcpy(d,s->s2->conn_id,SSL2_CONNECTION_ID_LENGTH); + d+=SSL2_CONNECTION_ID_LENGTH; + + s->state=SSL2_ST_SEND_SERVER_HELLO_B; + s->init_num=d-(unsigned char *)s->init_buf->data; + s->init_off=0; + } + /* SSL2_ST_SEND_SERVER_HELLO_B */ + /* If we are using TCP/IP, the performance is bad if we do 2 + * writes without a read between them. This occurs when + * Session-id reuse is used, so I will put in a buffering module + */ + if (s->hit) + { + if (!ssl_init_wbio_buffer(s,1)) return(-1); + } + + return(ssl2_do_write(s)); + } + +static int get_client_finished(SSL *s) + { + unsigned char *p; + int i, n; + unsigned long len; + + p=(unsigned char *)s->init_buf->data; + if (s->state == SSL2_ST_GET_CLIENT_FINISHED_A) + { + i=ssl2_read(s,(char *)&(p[s->init_num]),1-s->init_num); + if (i < 1-s->init_num) + return(ssl2_part_read(s,SSL_F_GET_CLIENT_FINISHED,i)); + s->init_num += i; + + if (*p != SSL2_MT_CLIENT_FINISHED) + { + if (*p != SSL2_MT_ERROR) + { + ssl2_return_error(s,SSL2_PE_UNDEFINED_ERROR); + SSLerr(SSL_F_GET_CLIENT_FINISHED,SSL_R_READ_WRONG_PACKET_TYPE); + } + else + { + SSLerr(SSL_F_GET_CLIENT_FINISHED,SSL_R_PEER_ERROR); + /* try to read the error message */ + i=ssl2_read(s,(char *)&(p[s->init_num]),3-s->init_num); + return ssl2_part_read(s,SSL_F_GET_SERVER_VERIFY,i); + } + return(-1); + } + s->state=SSL2_ST_GET_CLIENT_FINISHED_B; + } + + /* SSL2_ST_GET_CLIENT_FINISHED_B */ + if (s->s2->conn_id_length > sizeof s->s2->conn_id) + { + ssl2_return_error(s,SSL2_PE_UNDEFINED_ERROR); + SSLerr(SSL_F_GET_CLIENT_FINISHED, ERR_R_INTERNAL_ERROR); + return -1; + } + len = 1 + (unsigned long)s->s2->conn_id_length; + n = (int)len - s->init_num; + i = ssl2_read(s,(char *)&(p[s->init_num]),n); + if (i < n) + { + return(ssl2_part_read(s,SSL_F_GET_CLIENT_FINISHED,i)); + } + if (s->msg_callback) + s->msg_callback(0, s->version, 0, p, len, s, s->msg_callback_arg); /* CLIENT-FINISHED */ + p += 1; + if (memcmp(p,s->s2->conn_id,s->s2->conn_id_length) != 0) + { + ssl2_return_error(s,SSL2_PE_UNDEFINED_ERROR); + SSLerr(SSL_F_GET_CLIENT_FINISHED,SSL_R_CONNECTION_ID_IS_DIFFERENT); + return(-1); + } + return(1); + } + +static int server_verify(SSL *s) + { + unsigned char *p; + + if (s->state == SSL2_ST_SEND_SERVER_VERIFY_A) + { + p=(unsigned char *)s->init_buf->data; + *(p++)=SSL2_MT_SERVER_VERIFY; + if (s->s2->challenge_length > sizeof s->s2->challenge) + { + SSLerr(SSL_F_SERVER_VERIFY, ERR_R_INTERNAL_ERROR); + return -1; + } + memcpy(p,s->s2->challenge,(unsigned int)s->s2->challenge_length); + /* p+=s->s2->challenge_length; */ + + s->state=SSL2_ST_SEND_SERVER_VERIFY_B; + s->init_num=s->s2->challenge_length+1; + s->init_off=0; + } + return(ssl2_do_write(s)); + } + +static int server_finish(SSL *s) + { + unsigned char *p; + + if (s->state == SSL2_ST_SEND_SERVER_FINISHED_A) + { + p=(unsigned char *)s->init_buf->data; + *(p++)=SSL2_MT_SERVER_FINISHED; + + if (s->session->session_id_length > sizeof s->session->session_id) + { + SSLerr(SSL_F_SERVER_FINISH, ERR_R_INTERNAL_ERROR); + return -1; + } + memcpy(p,s->session->session_id, (unsigned int)s->session->session_id_length); + /* p+=s->session->session_id_length; */ + + s->state=SSL2_ST_SEND_SERVER_FINISHED_B; + s->init_num=s->session->session_id_length+1; + s->init_off=0; + } + + /* SSL2_ST_SEND_SERVER_FINISHED_B */ + return(ssl2_do_write(s)); + } + +/* send the request and check the response */ +static int request_certificate(SSL *s) + { + const unsigned char *cp; + unsigned char *p,*p2,*buf2; + unsigned char *ccd; + int i,j,ctype,ret= -1; + unsigned long len; + X509 *x509=NULL; + STACK_OF(X509) *sk=NULL; + + ccd=s->s2->tmp.ccl; + if (s->state == SSL2_ST_SEND_REQUEST_CERTIFICATE_A) + { + p=(unsigned char *)s->init_buf->data; + *(p++)=SSL2_MT_REQUEST_CERTIFICATE; + *(p++)=SSL2_AT_MD5_WITH_RSA_ENCRYPTION; + if (RAND_pseudo_bytes(ccd,SSL2_MIN_CERT_CHALLENGE_LENGTH) <= 0) + return -1; + memcpy(p,ccd,SSL2_MIN_CERT_CHALLENGE_LENGTH); + + s->state=SSL2_ST_SEND_REQUEST_CERTIFICATE_B; + s->init_num=SSL2_MIN_CERT_CHALLENGE_LENGTH+2; + s->init_off=0; + } + + if (s->state == SSL2_ST_SEND_REQUEST_CERTIFICATE_B) + { + i=ssl2_do_write(s); + if (i <= 0) + { + ret=i; + goto end; + } + + s->init_num=0; + s->state=SSL2_ST_SEND_REQUEST_CERTIFICATE_C; + } + + if (s->state == SSL2_ST_SEND_REQUEST_CERTIFICATE_C) + { + p=(unsigned char *)s->init_buf->data; + i=ssl2_read(s,(char *)&(p[s->init_num]),6-s->init_num); /* try to read 6 octets ... */ + if (i < 3-s->init_num) /* ... but don't call ssl2_part_read now if we got at least 3 + * (probably NO-CERTIFICATE-ERROR) */ + { + ret=ssl2_part_read(s,SSL_F_REQUEST_CERTIFICATE,i); + goto end; + } + s->init_num += i; + + if ((s->init_num >= 3) && (p[0] == SSL2_MT_ERROR)) + { + n2s(p,i); + if (i != SSL2_PE_NO_CERTIFICATE) + { + /* not the error message we expected -- let ssl2_part_read handle it */ + s->init_num -= 3; + ret = ssl2_part_read(s,SSL_F_REQUEST_CERTIFICATE, 3); + goto end; + } + + if (s->msg_callback) + s->msg_callback(0, s->version, 0, p, 3, s, s->msg_callback_arg); /* ERROR */ + + /* this is the one place where we can recover from an SSL 2.0 error */ + + if (s->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT) + { + ssl2_return_error(s,SSL2_PE_BAD_CERTIFICATE); + SSLerr(SSL_F_REQUEST_CERTIFICATE,SSL_R_PEER_DID_NOT_RETURN_A_CERTIFICATE); + goto end; + } + ret=1; + goto end; + } + if ((*(p++) != SSL2_MT_CLIENT_CERTIFICATE) || (s->init_num < 6)) + { + ssl2_return_error(s,SSL2_PE_UNDEFINED_ERROR); + SSLerr(SSL_F_REQUEST_CERTIFICATE,SSL_R_SHORT_READ); + goto end; + } + if (s->init_num != 6) + { + SSLerr(SSL_F_REQUEST_CERTIFICATE, ERR_R_INTERNAL_ERROR); + goto end; + } + + /* ok we have a response */ + /* certificate type, there is only one right now. */ + ctype= *(p++); + if (ctype != SSL2_AT_MD5_WITH_RSA_ENCRYPTION) + { + ssl2_return_error(s,SSL2_PE_UNSUPPORTED_CERTIFICATE_TYPE); + SSLerr(SSL_F_REQUEST_CERTIFICATE,SSL_R_BAD_RESPONSE_ARGUMENT); + goto end; + } + n2s(p,i); s->s2->tmp.clen=i; + n2s(p,i); s->s2->tmp.rlen=i; + s->state=SSL2_ST_SEND_REQUEST_CERTIFICATE_D; + } + + /* SSL2_ST_SEND_REQUEST_CERTIFICATE_D */ + p=(unsigned char *)s->init_buf->data; + len = 6 + (unsigned long)s->s2->tmp.clen + (unsigned long)s->s2->tmp.rlen; + if (len > SSL2_MAX_RECORD_LENGTH_3_BYTE_HEADER) + { + SSLerr(SSL_F_REQUEST_CERTIFICATE,SSL_R_MESSAGE_TOO_LONG); + goto end; + } + j = (int)len - s->init_num; + i = ssl2_read(s,(char *)&(p[s->init_num]),j); + if (i < j) + { + ret=ssl2_part_read(s,SSL_F_REQUEST_CERTIFICATE,i); + goto end; + } + if (s->msg_callback) + s->msg_callback(0, s->version, 0, p, len, s, s->msg_callback_arg); /* CLIENT-CERTIFICATE */ + p += 6; + + cp = p; + x509=(X509 *)d2i_X509(NULL,&cp,(long)s->s2->tmp.clen); + if (x509 == NULL) + { + SSLerr(SSL_F_REQUEST_CERTIFICATE,ERR_R_X509_LIB); + goto msg_end; + } + + if (((sk=sk_X509_new_null()) == NULL) || (!sk_X509_push(sk,x509))) + { + SSLerr(SSL_F_REQUEST_CERTIFICATE,ERR_R_MALLOC_FAILURE); + goto msg_end; + } + + i=ssl_verify_cert_chain(s,sk); + + if (i > 0) /* we like the packet, now check the chksum */ + { + EVP_MD_CTX ctx; + EVP_PKEY *pkey=NULL; + + EVP_MD_CTX_init(&ctx); + EVP_VerifyInit_ex(&ctx,s->ctx->rsa_md5, NULL); + EVP_VerifyUpdate(&ctx,s->s2->key_material, + s->s2->key_material_length); + EVP_VerifyUpdate(&ctx,ccd,SSL2_MIN_CERT_CHALLENGE_LENGTH); + + i=i2d_X509(s->cert->pkeys[SSL_PKEY_RSA_ENC].x509,NULL); + buf2=OPENSSL_malloc((unsigned int)i); + if (buf2 == NULL) + { + SSLerr(SSL_F_REQUEST_CERTIFICATE,ERR_R_MALLOC_FAILURE); + goto msg_end; + } + p2=buf2; + i=i2d_X509(s->cert->pkeys[SSL_PKEY_RSA_ENC].x509,&p2); + EVP_VerifyUpdate(&ctx,buf2,(unsigned int)i); + OPENSSL_free(buf2); + + pkey=X509_get_pubkey(x509); + if (pkey == NULL) goto end; + i=EVP_VerifyFinal(&ctx,cp,s->s2->tmp.rlen,pkey); + EVP_PKEY_free(pkey); + EVP_MD_CTX_cleanup(&ctx); + + if (i > 0) + { + if (s->session->peer != NULL) + X509_free(s->session->peer); + s->session->peer=x509; + CRYPTO_add(&x509->references,1,CRYPTO_LOCK_X509); + s->session->verify_result = s->verify_result; + ret=1; + goto end; + } + else + { + SSLerr(SSL_F_REQUEST_CERTIFICATE,SSL_R_BAD_CHECKSUM); + goto msg_end; + } + } + else + { +msg_end: + ssl2_return_error(s,SSL2_PE_BAD_CERTIFICATE); + } +end: + sk_X509_free(sk); + X509_free(x509); + return(ret); + } + +static int ssl_rsa_private_decrypt(CERT *c, int len, unsigned char *from, + unsigned char *to, int padding) + { + RSA *rsa; + int i; + + if ((c == NULL) || (c->pkeys[SSL_PKEY_RSA_ENC].privatekey == NULL)) + { + SSLerr(SSL_F_SSL_RSA_PRIVATE_DECRYPT,SSL_R_NO_PRIVATEKEY); + return(-1); + } + if (c->pkeys[SSL_PKEY_RSA_ENC].privatekey->type != EVP_PKEY_RSA) + { + SSLerr(SSL_F_SSL_RSA_PRIVATE_DECRYPT,SSL_R_PUBLIC_KEY_IS_NOT_RSA); + return(-1); + } + rsa=c->pkeys[SSL_PKEY_RSA_ENC].privatekey->pkey.rsa; + + /* we have the public key */ + i=RSA_private_decrypt(len,from,to,rsa,padding); + if (i < 0) + SSLerr(SSL_F_SSL_RSA_PRIVATE_DECRYPT,ERR_R_RSA_LIB); + return(i); + } +#else /* !OPENSSL_NO_SSL2 */ + +# if PEDANTIC +static void *dummy=&dummy; +# endif + +#endif diff --git a/node-v0.8.14/deps/openssl/openssl/ssl/s3_both.c b/node-v0.8.14/deps/openssl/openssl/ssl/s3_both.c new file mode 100644 index 0000000..508e390 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/ssl/s3_both.c @@ -0,0 +1,867 @@ +/* ssl/s3_both.c */ +/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com) + * All rights reserved. + * + * This package is an SSL implementation written + * by Eric Young (eay@cryptsoft.com). + * The implementation was written so as to conform with Netscapes SSL. + * + * This library is free for commercial and non-commercial use as long as + * the following conditions are aheared to. The following conditions + * apply to all code found in this distribution, be it the RC4, RSA, + * lhash, DES, etc., code; not just the SSL code. The SSL documentation + * included with this distribution is covered by the same copyright terms + * except that the holder is Tim Hudson (tjh@cryptsoft.com). + * + * Copyright remains Eric Young's, and as such any Copyright notices in + * the code are not to be removed. + * If this package is used in a product, Eric Young should be given attribution + * as the author of the parts of the library used. + * This can be in the form of a textual message at program startup or + * in documentation (online or textual) provided with the package. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * "This product includes cryptographic software written by + * Eric Young (eay@cryptsoft.com)" + * The word 'cryptographic' can be left out if the rouines from the library + * being used are not cryptographic related :-). + * 4. If you include any Windows specific code (or a derivative thereof) from + * the apps directory (application code) you must include an acknowledgement: + * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)" + * + * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * + * The licence and distribution terms for any publically available version or + * derivative of this code cannot be changed. i.e. this code cannot simply be + * copied and put under another distribution licence + * [including the GNU Public Licence.] + */ +/* ==================================================================== + * Copyright (c) 1998-2002 The OpenSSL Project. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. All advertising materials mentioning features or use of this + * software must display the following acknowledgment: + * "This product includes software developed by the OpenSSL Project + * for use in the OpenSSL Toolkit. (http://www.openssl.org/)" + * + * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to + * endorse or promote products derived from this software without + * prior written permission. For written permission, please contact + * openssl-core@openssl.org. + * + * 5. Products derived from this software may not be called "OpenSSL" + * nor may "OpenSSL" appear in their names without prior written + * permission of the OpenSSL Project. + * + * 6. Redistributions of any form whatsoever must retain the following + * acknowledgment: + * "This product includes software developed by the OpenSSL Project + * for use in the OpenSSL Toolkit (http://www.openssl.org/)" + * + * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY + * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR + * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, + * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * ==================================================================== + * + * This product includes cryptographic software written by Eric Young + * (eay@cryptsoft.com). This product includes software written by Tim + * Hudson (tjh@cryptsoft.com). + * + */ +/* ==================================================================== + * Copyright 2002 Sun Microsystems, Inc. ALL RIGHTS RESERVED. + * ECC cipher suite support in OpenSSL originally developed by + * SUN MICROSYSTEMS, INC., and contributed to the OpenSSL project. + */ + +#include +#include +#include +#include "ssl_locl.h" +#include +#include +#include +#include +#include + +/* send s->init_buf in records of type 'type' (SSL3_RT_HANDSHAKE or SSL3_RT_CHANGE_CIPHER_SPEC) */ +int ssl3_do_write(SSL *s, int type) + { + int ret; + + ret=ssl3_write_bytes(s,type,&s->init_buf->data[s->init_off], + s->init_num); + if (ret < 0) return(-1); + if (type == SSL3_RT_HANDSHAKE) + /* should not be done for 'Hello Request's, but in that case + * we'll ignore the result anyway */ + ssl3_finish_mac(s,(unsigned char *)&s->init_buf->data[s->init_off],ret); + + if (ret == s->init_num) + { + if (s->msg_callback) + s->msg_callback(1, s->version, type, s->init_buf->data, (size_t)(s->init_off + s->init_num), s, s->msg_callback_arg); + return(1); + } + s->init_off+=ret; + s->init_num-=ret; + return(0); + } + +int ssl3_send_finished(SSL *s, int a, int b, const char *sender, int slen) + { + unsigned char *p,*d; + int i; + unsigned long l; + + if (s->state == a) + { + d=(unsigned char *)s->init_buf->data; + p= &(d[4]); + + i=s->method->ssl3_enc->final_finish_mac(s, + sender,slen,s->s3->tmp.finish_md); + s->s3->tmp.finish_md_len = i; + memcpy(p, s->s3->tmp.finish_md, i); + p+=i; + l=i; + + /* Copy the finished so we can use it for + renegotiation checks */ + if(s->type == SSL_ST_CONNECT) + { + OPENSSL_assert(i <= EVP_MAX_MD_SIZE); + memcpy(s->s3->previous_client_finished, + s->s3->tmp.finish_md, i); + s->s3->previous_client_finished_len=i; + } + else + { + OPENSSL_assert(i <= EVP_MAX_MD_SIZE); + memcpy(s->s3->previous_server_finished, + s->s3->tmp.finish_md, i); + s->s3->previous_server_finished_len=i; + } + +#ifdef OPENSSL_SYS_WIN16 + /* MSVC 1.5 does not clear the top bytes of the word unless + * I do this. + */ + l&=0xffff; +#endif + + *(d++)=SSL3_MT_FINISHED; + l2n3(l,d); + s->init_num=(int)l+4; + s->init_off=0; + + s->state=b; + } + + /* SSL3_ST_SEND_xxxxxx_HELLO_B */ + return(ssl3_do_write(s,SSL3_RT_HANDSHAKE)); + } + +#ifndef OPENSSL_NO_NEXTPROTONEG +/* ssl3_take_mac calculates the Finished MAC for the handshakes messages seen to far. */ +static void ssl3_take_mac(SSL *s) + { + const char *sender; + int slen; + + if (s->state & SSL_ST_CONNECT) + { + sender=s->method->ssl3_enc->server_finished_label; + slen=s->method->ssl3_enc->server_finished_label_len; + } + else + { + sender=s->method->ssl3_enc->client_finished_label; + slen=s->method->ssl3_enc->client_finished_label_len; + } + + s->s3->tmp.peer_finish_md_len = s->method->ssl3_enc->final_finish_mac(s, + sender,slen,s->s3->tmp.peer_finish_md); + } +#endif + +int ssl3_get_finished(SSL *s, int a, int b) + { + int al,i,ok; + long n; + unsigned char *p; + +#ifdef OPENSSL_NO_NEXTPROTONEG + /* the mac has already been generated when we received the + * change cipher spec message and is in s->s3->tmp.peer_finish_md + */ +#endif + + n=s->method->ssl_get_message(s, + a, + b, + SSL3_MT_FINISHED, + 64, /* should actually be 36+4 :-) */ + &ok); + + if (!ok) return((int)n); + + /* If this occurs, we have missed a message */ + if (!s->s3->change_cipher_spec) + { + al=SSL_AD_UNEXPECTED_MESSAGE; + SSLerr(SSL_F_SSL3_GET_FINISHED,SSL_R_GOT_A_FIN_BEFORE_A_CCS); + goto f_err; + } + s->s3->change_cipher_spec=0; + + p = (unsigned char *)s->init_msg; + i = s->s3->tmp.peer_finish_md_len; + + if (i != n) + { + al=SSL_AD_DECODE_ERROR; + SSLerr(SSL_F_SSL3_GET_FINISHED,SSL_R_BAD_DIGEST_LENGTH); + goto f_err; + } + + if (memcmp(p, s->s3->tmp.peer_finish_md, i) != 0) + { + al=SSL_AD_DECRYPT_ERROR; + SSLerr(SSL_F_SSL3_GET_FINISHED,SSL_R_DIGEST_CHECK_FAILED); + goto f_err; + } + + /* Copy the finished so we can use it for + renegotiation checks */ + if(s->type == SSL_ST_ACCEPT) + { + OPENSSL_assert(i <= EVP_MAX_MD_SIZE); + memcpy(s->s3->previous_client_finished, + s->s3->tmp.peer_finish_md, i); + s->s3->previous_client_finished_len=i; + } + else + { + OPENSSL_assert(i <= EVP_MAX_MD_SIZE); + memcpy(s->s3->previous_server_finished, + s->s3->tmp.peer_finish_md, i); + s->s3->previous_server_finished_len=i; + } + + return(1); +f_err: + ssl3_send_alert(s,SSL3_AL_FATAL,al); + return(0); + } + +/* for these 2 messages, we need to + * ssl->enc_read_ctx re-init + * ssl->s3->read_sequence zero + * ssl->s3->read_mac_secret re-init + * ssl->session->read_sym_enc assign + * ssl->session->read_compression assign + * ssl->session->read_hash assign + */ +int ssl3_send_change_cipher_spec(SSL *s, int a, int b) + { + unsigned char *p; + + if (s->state == a) + { + p=(unsigned char *)s->init_buf->data; + *p=SSL3_MT_CCS; + s->init_num=1; + s->init_off=0; + + s->state=b; + } + + /* SSL3_ST_CW_CHANGE_B */ + return(ssl3_do_write(s,SSL3_RT_CHANGE_CIPHER_SPEC)); + } + +static int ssl3_add_cert_to_buf(BUF_MEM *buf, unsigned long *l, X509 *x) + { + int n; + unsigned char *p; + + n=i2d_X509(x,NULL); + if (!BUF_MEM_grow_clean(buf,(int)(n+(*l)+3))) + { + SSLerr(SSL_F_SSL3_ADD_CERT_TO_BUF,ERR_R_BUF_LIB); + return(-1); + } + p=(unsigned char *)&(buf->data[*l]); + l2n3(n,p); + i2d_X509(x,&p); + *l+=n+3; + + return(0); + } + +unsigned long ssl3_output_cert_chain(SSL *s, X509 *x) + { + unsigned char *p; + int i; + unsigned long l=7; + BUF_MEM *buf; + int no_chain; + STACK_OF(X509) *cert_chain; + + cert_chain = SSL_get_certificate_chain(s, x); + + if ((s->mode & SSL_MODE_NO_AUTO_CHAIN) || s->ctx->extra_certs || cert_chain) + no_chain = 1; + else + no_chain = 0; + + /* TLSv1 sends a chain with nothing in it, instead of an alert */ + buf=s->init_buf; + if (!BUF_MEM_grow_clean(buf,10)) + { + SSLerr(SSL_F_SSL3_OUTPUT_CERT_CHAIN,ERR_R_BUF_LIB); + return(0); + } + if (x != NULL) + { + if (no_chain) + { + if (ssl3_add_cert_to_buf(buf, &l, x)) + return(0); + } + else + { + X509_STORE_CTX xs_ctx; + + if (!X509_STORE_CTX_init(&xs_ctx,s->ctx->cert_store,x,NULL)) + { + SSLerr(SSL_F_SSL3_OUTPUT_CERT_CHAIN,ERR_R_X509_LIB); + return(0); + } + X509_verify_cert(&xs_ctx); + /* Don't leave errors in the queue */ + ERR_clear_error(); + for (i=0; i < sk_X509_num(xs_ctx.chain); i++) + { + x = sk_X509_value(xs_ctx.chain, i); + + if (ssl3_add_cert_to_buf(buf, &l, x)) + { + X509_STORE_CTX_cleanup(&xs_ctx); + return 0; + } + } + X509_STORE_CTX_cleanup(&xs_ctx); + } + } + /* Thawte special :-) */ + for (i=0; ictx->extra_certs); i++) + { + x=sk_X509_value(s->ctx->extra_certs,i); + if (ssl3_add_cert_to_buf(buf, &l, x)) + return(0); + } + + for (i=0; idata[4]); + l2n3(l,p); + l+=3; + p=(unsigned char *)&(buf->data[0]); + *(p++)=SSL3_MT_CERTIFICATE; + l2n3(l,p); + l+=4; + return(l); + } + +/* Obtain handshake message of message type 'mt' (any if mt == -1), + * maximum acceptable body length 'max'. + * The first four bytes (msg_type and length) are read in state 'st1', + * the body is read in state 'stn'. + */ +long ssl3_get_message(SSL *s, int st1, int stn, int mt, long max, int *ok) + { + unsigned char *p; + unsigned long l; + long n; + int i,al; + + if (s->s3->tmp.reuse_message) + { + s->s3->tmp.reuse_message=0; + if ((mt >= 0) && (s->s3->tmp.message_type != mt)) + { + al=SSL_AD_UNEXPECTED_MESSAGE; + SSLerr(SSL_F_SSL3_GET_MESSAGE,SSL_R_UNEXPECTED_MESSAGE); + goto f_err; + } + *ok=1; + s->init_msg = s->init_buf->data + 4; + s->init_num = (int)s->s3->tmp.message_size; + return s->init_num; + } + + p=(unsigned char *)s->init_buf->data; + + if (s->state == st1) /* s->init_num < 4 */ + { + int skip_message; + + do + { + while (s->init_num < 4) + { + i=s->method->ssl_read_bytes(s,SSL3_RT_HANDSHAKE, + &p[s->init_num],4 - s->init_num, 0); + if (i <= 0) + { + s->rwstate=SSL_READING; + *ok = 0; + return i; + } + s->init_num+=i; + } + + skip_message = 0; + if (!s->server) + if (p[0] == SSL3_MT_HELLO_REQUEST) + /* The server may always send 'Hello Request' messages -- + * we are doing a handshake anyway now, so ignore them + * if their format is correct. Does not count for + * 'Finished' MAC. */ + if (p[1] == 0 && p[2] == 0 &&p[3] == 0) + { + s->init_num = 0; + skip_message = 1; + + if (s->msg_callback) + s->msg_callback(0, s->version, SSL3_RT_HANDSHAKE, p, 4, s, s->msg_callback_arg); + } + } + while (skip_message); + + /* s->init_num == 4 */ + + if ((mt >= 0) && (*p != mt)) + { + al=SSL_AD_UNEXPECTED_MESSAGE; + SSLerr(SSL_F_SSL3_GET_MESSAGE,SSL_R_UNEXPECTED_MESSAGE); + goto f_err; + } + if ((mt < 0) && (*p == SSL3_MT_CLIENT_HELLO) && + (st1 == SSL3_ST_SR_CERT_A) && + (stn == SSL3_ST_SR_CERT_B)) + { + /* At this point we have got an MS SGC second client + * hello (maybe we should always allow the client to + * start a new handshake?). We need to restart the mac. + * Don't increment {num,total}_renegotiations because + * we have not completed the handshake. */ + ssl3_init_finished_mac(s); + } + + s->s3->tmp.message_type= *(p++); + + n2l3(p,l); + if (l > (unsigned long)max) + { + al=SSL_AD_ILLEGAL_PARAMETER; + SSLerr(SSL_F_SSL3_GET_MESSAGE,SSL_R_EXCESSIVE_MESSAGE_SIZE); + goto f_err; + } + if (l > (INT_MAX-4)) /* BUF_MEM_grow takes an 'int' parameter */ + { + al=SSL_AD_ILLEGAL_PARAMETER; + SSLerr(SSL_F_SSL3_GET_MESSAGE,SSL_R_EXCESSIVE_MESSAGE_SIZE); + goto f_err; + } + if (l && !BUF_MEM_grow_clean(s->init_buf,(int)l+4)) + { + SSLerr(SSL_F_SSL3_GET_MESSAGE,ERR_R_BUF_LIB); + goto err; + } + s->s3->tmp.message_size=l; + s->state=stn; + + s->init_msg = s->init_buf->data + 4; + s->init_num = 0; + } + + /* next state (stn) */ + p = s->init_msg; + n = s->s3->tmp.message_size - s->init_num; + while (n > 0) + { + i=s->method->ssl_read_bytes(s,SSL3_RT_HANDSHAKE,&p[s->init_num],n,0); + if (i <= 0) + { + s->rwstate=SSL_READING; + *ok = 0; + return i; + } + s->init_num += i; + n -= i; + } + +#ifndef OPENSSL_NO_NEXTPROTONEG + /* If receiving Finished, record MAC of prior handshake messages for + * Finished verification. */ + if (*s->init_buf->data == SSL3_MT_FINISHED) + ssl3_take_mac(s); +#endif + + /* Feed this message into MAC computation. */ + ssl3_finish_mac(s, (unsigned char *)s->init_buf->data, s->init_num + 4); + if (s->msg_callback) + s->msg_callback(0, s->version, SSL3_RT_HANDSHAKE, s->init_buf->data, (size_t)s->init_num + 4, s, s->msg_callback_arg); + *ok=1; + return s->init_num; +f_err: + ssl3_send_alert(s,SSL3_AL_FATAL,al); +err: + *ok=0; + return(-1); + } + +int ssl_cert_type(X509 *x, EVP_PKEY *pkey) + { + EVP_PKEY *pk; + int ret= -1,i; + + if (pkey == NULL) + pk=X509_get_pubkey(x); + else + pk=pkey; + if (pk == NULL) goto err; + + i=pk->type; + if (i == EVP_PKEY_RSA) + { + ret=SSL_PKEY_RSA_ENC; + } + else if (i == EVP_PKEY_DSA) + { + ret=SSL_PKEY_DSA_SIGN; + } +#ifndef OPENSSL_NO_EC + else if (i == EVP_PKEY_EC) + { + ret = SSL_PKEY_ECC; + } +#endif + else if (i == NID_id_GostR3410_94 || i == NID_id_GostR3410_94_cc) + { + ret = SSL_PKEY_GOST94; + } + else if (i == NID_id_GostR3410_2001 || i == NID_id_GostR3410_2001_cc) + { + ret = SSL_PKEY_GOST01; + } +err: + if(!pkey) EVP_PKEY_free(pk); + return(ret); + } + +int ssl_verify_alarm_type(long type) + { + int al; + + switch(type) + { + case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT: + case X509_V_ERR_UNABLE_TO_GET_CRL: + case X509_V_ERR_UNABLE_TO_GET_CRL_ISSUER: + al=SSL_AD_UNKNOWN_CA; + break; + case X509_V_ERR_UNABLE_TO_DECRYPT_CERT_SIGNATURE: + case X509_V_ERR_UNABLE_TO_DECRYPT_CRL_SIGNATURE: + case X509_V_ERR_UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY: + case X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD: + case X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD: + case X509_V_ERR_ERROR_IN_CRL_LAST_UPDATE_FIELD: + case X509_V_ERR_ERROR_IN_CRL_NEXT_UPDATE_FIELD: + case X509_V_ERR_CERT_NOT_YET_VALID: + case X509_V_ERR_CRL_NOT_YET_VALID: + case X509_V_ERR_CERT_UNTRUSTED: + case X509_V_ERR_CERT_REJECTED: + al=SSL_AD_BAD_CERTIFICATE; + break; + case X509_V_ERR_CERT_SIGNATURE_FAILURE: + case X509_V_ERR_CRL_SIGNATURE_FAILURE: + al=SSL_AD_DECRYPT_ERROR; + break; + case X509_V_ERR_CERT_HAS_EXPIRED: + case X509_V_ERR_CRL_HAS_EXPIRED: + al=SSL_AD_CERTIFICATE_EXPIRED; + break; + case X509_V_ERR_CERT_REVOKED: + al=SSL_AD_CERTIFICATE_REVOKED; + break; + case X509_V_ERR_OUT_OF_MEM: + al=SSL_AD_INTERNAL_ERROR; + break; + case X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT: + case X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN: + case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY: + case X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE: + case X509_V_ERR_CERT_CHAIN_TOO_LONG: + case X509_V_ERR_PATH_LENGTH_EXCEEDED: + case X509_V_ERR_INVALID_CA: + al=SSL_AD_UNKNOWN_CA; + break; + case X509_V_ERR_APPLICATION_VERIFICATION: + al=SSL_AD_HANDSHAKE_FAILURE; + break; + case X509_V_ERR_INVALID_PURPOSE: + al=SSL_AD_UNSUPPORTED_CERTIFICATE; + break; + default: + al=SSL_AD_CERTIFICATE_UNKNOWN; + break; + } + return(al); + } + +#ifndef OPENSSL_NO_BUF_FREELISTS +/* On some platforms, malloc() performance is bad enough that you can't just + * free() and malloc() buffers all the time, so we need to use freelists from + * unused buffers. Currently, each freelist holds memory chunks of only a + * given size (list->chunklen); other sized chunks are freed and malloced. + * This doesn't help much if you're using many different SSL option settings + * with a given context. (The options affecting buffer size are + * max_send_fragment, read buffer vs write buffer, + * SSL_OP_MICROSOFT_BIG_WRITE_BUFFER, SSL_OP_NO_COMPRESSION, and + * SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS.) Using a separate freelist for every + * possible size is not an option, since max_send_fragment can take on many + * different values. + * + * If you are on a platform with a slow malloc(), and you're using SSL + * connections with many different settings for these options, and you need to + * use the SSL_MOD_RELEASE_BUFFERS feature, you have a few options: + * - Link against a faster malloc implementation. + * - Use a separate SSL_CTX for each option set. + * - Improve this code. + */ +static void * +freelist_extract(SSL_CTX *ctx, int for_read, int sz) + { + SSL3_BUF_FREELIST *list; + SSL3_BUF_FREELIST_ENTRY *ent = NULL; + void *result = NULL; + + CRYPTO_w_lock(CRYPTO_LOCK_SSL_CTX); + list = for_read ? ctx->rbuf_freelist : ctx->wbuf_freelist; + if (list != NULL && sz == (int)list->chunklen) + ent = list->head; + if (ent != NULL) + { + list->head = ent->next; + result = ent; + if (--list->len == 0) + list->chunklen = 0; + } + CRYPTO_w_unlock(CRYPTO_LOCK_SSL_CTX); + if (!result) + result = OPENSSL_malloc(sz); + return result; +} + +static void +freelist_insert(SSL_CTX *ctx, int for_read, size_t sz, void *mem) + { + SSL3_BUF_FREELIST *list; + SSL3_BUF_FREELIST_ENTRY *ent; + + CRYPTO_w_lock(CRYPTO_LOCK_SSL_CTX); + list = for_read ? ctx->rbuf_freelist : ctx->wbuf_freelist; + if (list != NULL && + (sz == list->chunklen || list->chunklen == 0) && + list->len < ctx->freelist_max_len && + sz >= sizeof(*ent)) + { + list->chunklen = sz; + ent = mem; + ent->next = list->head; + list->head = ent; + ++list->len; + mem = NULL; + } + + CRYPTO_w_unlock(CRYPTO_LOCK_SSL_CTX); + if (mem) + OPENSSL_free(mem); + } +#else +#define freelist_extract(c,fr,sz) OPENSSL_malloc(sz) +#define freelist_insert(c,fr,sz,m) OPENSSL_free(m) +#endif + +int ssl3_setup_read_buffer(SSL *s) + { + unsigned char *p; + size_t len,align=0,headerlen; + + if (SSL_version(s) == DTLS1_VERSION || SSL_version(s) == DTLS1_BAD_VER) + headerlen = DTLS1_RT_HEADER_LENGTH; + else + headerlen = SSL3_RT_HEADER_LENGTH; + +#if defined(SSL3_ALIGN_PAYLOAD) && SSL3_ALIGN_PAYLOAD!=0 + align = (-SSL3_RT_HEADER_LENGTH)&(SSL3_ALIGN_PAYLOAD-1); +#endif + + if (s->s3->rbuf.buf == NULL) + { + if (SSL_get_mode(s) & SSL_MODE_SMALL_BUFFERS) + { + len = SSL3_RT_DEFAULT_PACKET_SIZE; + } + else + { + len = SSL3_RT_MAX_PLAIN_LENGTH + + SSL3_RT_MAX_ENCRYPTED_OVERHEAD + + headerlen + align; + if (s->options & SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER) + { + s->s3->init_extra = 1; + len += SSL3_RT_MAX_EXTRA; + } + } +#ifndef OPENSSL_NO_COMP + if (!(s->options & SSL_OP_NO_COMPRESSION)) + len += SSL3_RT_MAX_COMPRESSED_OVERHEAD; +#endif + if ((p=freelist_extract(s->ctx, 1, len)) == NULL) + goto err; + s->s3->rbuf.buf = p; + s->s3->rbuf.len = len; + } + + s->packet= &(s->s3->rbuf.buf[0]); + return 1; + +err: + SSLerr(SSL_F_SSL3_SETUP_READ_BUFFER,ERR_R_MALLOC_FAILURE); + return 0; + } + +int ssl3_setup_write_buffer(SSL *s) + { + unsigned char *p; + size_t len,align=0,headerlen; + + if (SSL_version(s) == DTLS1_VERSION || SSL_version(s) == DTLS1_BAD_VER) + headerlen = DTLS1_RT_HEADER_LENGTH + 1; + else + headerlen = SSL3_RT_HEADER_LENGTH; + +#if defined(SSL3_ALIGN_PAYLOAD) && SSL3_ALIGN_PAYLOAD!=0 + align = (-SSL3_RT_HEADER_LENGTH)&(SSL3_ALIGN_PAYLOAD-1); +#endif + + if (s->s3->wbuf.buf == NULL) + { + if (SSL_get_mode(s) & SSL_MODE_SMALL_BUFFERS) + { + len = SSL3_RT_DEFAULT_PACKET_SIZE; + } + else + { + len = s->max_send_fragment; + } + len += 0 + + SSL3_RT_SEND_MAX_ENCRYPTED_OVERHEAD + + headerlen + align; +#ifndef OPENSSL_NO_COMP + if (!(s->options & SSL_OP_NO_COMPRESSION)) + len += SSL3_RT_MAX_COMPRESSED_OVERHEAD; +#endif + if (!(s->options & SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS)) + len += headerlen + align + + SSL3_RT_SEND_MAX_ENCRYPTED_OVERHEAD; + if ((p=freelist_extract(s->ctx, 0, len)) == NULL) + goto err; + s->s3->wbuf.buf = p; + s->s3->wbuf.len = len; + } + + return 1; + +err: + SSLerr(SSL_F_SSL3_SETUP_WRITE_BUFFER,ERR_R_MALLOC_FAILURE); + return 0; + } + + +int ssl3_setup_buffers(SSL *s) + { + if (!ssl3_setup_read_buffer(s)) + return 0; + if (!ssl3_setup_write_buffer(s)) + return 0; + return 1; + } + +int ssl3_release_write_buffer(SSL *s) + { + if (s->s3->wbuf.buf != NULL) + { + freelist_insert(s->ctx, 0, s->s3->wbuf.len, s->s3->wbuf.buf); + s->s3->wbuf.buf = NULL; + } + return 1; + } + +int ssl3_release_read_buffer(SSL *s) + { + if (s->s3->rbuf.buf != NULL) + { + freelist_insert(s->ctx, 1, s->s3->rbuf.len, s->s3->rbuf.buf); + s->s3->rbuf.buf = NULL; + } + return 1; + } diff --git a/node-v0.8.14/deps/openssl/openssl/ssl/s3_clnt.c b/node-v0.8.14/deps/openssl/openssl/ssl/s3_clnt.c new file mode 100644 index 0000000..04d6e5b --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/ssl/s3_clnt.c @@ -0,0 +1,3153 @@ +/* ssl/s3_clnt.c */ +/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com) + * All rights reserved. + * + * This package is an SSL implementation written + * by Eric Young (eay@cryptsoft.com). + * The implementation was written so as to conform with Netscapes SSL. + * + * This library is free for commercial and non-commercial use as long as + * the following conditions are aheared to. The following conditions + * apply to all code found in this distribution, be it the RC4, RSA, + * lhash, DES, etc., code; not just the SSL code. The SSL documentation + * included with this distribution is covered by the same copyright terms + * except that the holder is Tim Hudson (tjh@cryptsoft.com). + * + * Copyright remains Eric Young's, and as such any Copyright notices in + * the code are not to be removed. + * If this package is used in a product, Eric Young should be given attribution + * as the author of the parts of the library used. + * This can be in the form of a textual message at program startup or + * in documentation (online or textual) provided with the package. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * "This product includes cryptographic software written by + * Eric Young (eay@cryptsoft.com)" + * The word 'cryptographic' can be left out if the rouines from the library + * being used are not cryptographic related :-). + * 4. If you include any Windows specific code (or a derivative thereof) from + * the apps directory (application code) you must include an acknowledgement: + * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)" + * + * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * + * The licence and distribution terms for any publically available version or + * derivative of this code cannot be changed. i.e. this code cannot simply be + * copied and put under another distribution licence + * [including the GNU Public Licence.] + */ +/* ==================================================================== + * Copyright (c) 1998-2007 The OpenSSL Project. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. All advertising materials mentioning features or use of this + * software must display the following acknowledgment: + * "This product includes software developed by the OpenSSL Project + * for use in the OpenSSL Toolkit. (http://www.openssl.org/)" + * + * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to + * endorse or promote products derived from this software without + * prior written permission. For written permission, please contact + * openssl-core@openssl.org. + * + * 5. Products derived from this software may not be called "OpenSSL" + * nor may "OpenSSL" appear in their names without prior written + * permission of the OpenSSL Project. + * + * 6. Redistributions of any form whatsoever must retain the following + * acknowledgment: + * "This product includes software developed by the OpenSSL Project + * for use in the OpenSSL Toolkit (http://www.openssl.org/)" + * + * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY + * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR + * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, + * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * ==================================================================== + * + * This product includes cryptographic software written by Eric Young + * (eay@cryptsoft.com). This product includes software written by Tim + * Hudson (tjh@cryptsoft.com). + * + */ +/* ==================================================================== + * Copyright 2002 Sun Microsystems, Inc. ALL RIGHTS RESERVED. + * + * Portions of the attached software ("Contribution") are developed by + * SUN MICROSYSTEMS, INC., and are contributed to the OpenSSL project. + * + * The Contribution is licensed pursuant to the OpenSSL open source + * license provided above. + * + * ECC cipher suite support in OpenSSL originally written by + * Vipul Gupta and Sumit Gupta of Sun Microsystems Laboratories. + * + */ +/* ==================================================================== + * Copyright 2005 Nokia. All rights reserved. + * + * The portions of the attached software ("Contribution") is developed by + * Nokia Corporation and is licensed pursuant to the OpenSSL open source + * license. + * + * The Contribution, originally written by Mika Kousa and Pasi Eronen of + * Nokia Corporation, consists of the "PSK" (Pre-Shared Key) ciphersuites + * support (see RFC 4279) to OpenSSL. + * + * No patent licenses or other rights except those expressly stated in + * the OpenSSL open source license shall be deemed granted or received + * expressly, by implication, estoppel, or otherwise. + * + * No assurances are provided by Nokia that the Contribution does not + * infringe the patent or other intellectual property rights of any third + * party or that the license provides you with all the necessary rights + * to make use of the Contribution. + * + * THE SOFTWARE IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND. IN + * ADDITION TO THE DISCLAIMERS INCLUDED IN THE LICENSE, NOKIA + * SPECIFICALLY DISCLAIMS ANY LIABILITY FOR CLAIMS BROUGHT BY YOU OR ANY + * OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL PROPERTY RIGHTS OR + * OTHERWISE. + */ + +#include +#include "ssl_locl.h" +#include "kssl_lcl.h" +#include +#include +#include +#include +#include +#ifndef OPENSSL_NO_DH +#include +#endif +#include +#ifndef OPENSSL_NO_ENGINE +#include +#endif + +static const SSL_METHOD *ssl3_get_client_method(int ver); +static int ca_dn_cmp(const X509_NAME * const *a,const X509_NAME * const *b); + +static const SSL_METHOD *ssl3_get_client_method(int ver) + { + if (ver == SSL3_VERSION) + return(SSLv3_client_method()); + else + return(NULL); + } + +IMPLEMENT_ssl3_meth_func(SSLv3_client_method, + ssl_undefined_function, + ssl3_connect, + ssl3_get_client_method) + +int ssl3_connect(SSL *s) + { + BUF_MEM *buf=NULL; + unsigned long Time=(unsigned long)time(NULL); + void (*cb)(const SSL *ssl,int type,int val)=NULL; + int ret= -1; + int new_state,state,skip=0; + + RAND_add(&Time,sizeof(Time),0); + ERR_clear_error(); + clear_sys_error(); + + if (s->info_callback != NULL) + cb=s->info_callback; + else if (s->ctx->info_callback != NULL) + cb=s->ctx->info_callback; + + s->in_handshake++; + if (!SSL_in_init(s) || SSL_in_before(s)) SSL_clear(s); +#if 0 /* Send app data in separate packet, otherwise, some particular site + * (only one site so far) closes the socket. + * Note: there is a very small chance that two TCP packets + * could be arriving at server combined into a single TCP packet, + * then trigger that site to break. We haven't encounter that though. + */ + if (SSL_get_mode(s) & SSL_MODE_HANDSHAKE_CUTTHROUGH) + { + /* Send app data along with CCS/Finished */ + s->s3->flags |= SSL3_FLAGS_DELAY_CLIENT_FINISHED; + } +#endif + + for (;;) + { + state=s->state; + + switch(s->state) + { + case SSL_ST_RENEGOTIATE: + s->new_session=1; + s->state=SSL_ST_CONNECT; + s->ctx->stats.sess_connect_renegotiate++; + /* break */ + case SSL_ST_BEFORE: + case SSL_ST_CONNECT: + case SSL_ST_BEFORE|SSL_ST_CONNECT: + case SSL_ST_OK|SSL_ST_CONNECT: + + s->server=0; + if (cb != NULL) cb(s,SSL_CB_HANDSHAKE_START,1); + + if ((s->version & 0xff00 ) != 0x0300) + { + SSLerr(SSL_F_SSL3_CONNECT, ERR_R_INTERNAL_ERROR); + ret = -1; + goto end; + } + + /* s->version=SSL3_VERSION; */ + s->type=SSL_ST_CONNECT; + + if (s->init_buf == NULL) + { + if ((buf=BUF_MEM_new()) == NULL) + { + ret= -1; + goto end; + } + if (!BUF_MEM_grow(buf,SSL3_RT_MAX_PLAIN_LENGTH)) + { + ret= -1; + goto end; + } + s->init_buf=buf; + buf=NULL; + } + + if (!ssl3_setup_buffers(s)) { ret= -1; goto end; } + + /* setup buffing BIO */ + if (!ssl_init_wbio_buffer(s,0)) { ret= -1; goto end; } + + /* don't push the buffering BIO quite yet */ + + ssl3_init_finished_mac(s); + + s->state=SSL3_ST_CW_CLNT_HELLO_A; + s->ctx->stats.sess_connect++; + s->init_num=0; + break; + + case SSL3_ST_CW_CLNT_HELLO_A: + case SSL3_ST_CW_CLNT_HELLO_B: + + s->shutdown=0; + ret=ssl3_client_hello(s); + if (ret <= 0) goto end; + s->state=SSL3_ST_CR_SRVR_HELLO_A; + s->init_num=0; + + /* turn on buffering for the next lot of output */ + if (s->bbio != s->wbio) + s->wbio=BIO_push(s->bbio,s->wbio); + + break; + + case SSL3_ST_CR_SRVR_HELLO_A: + case SSL3_ST_CR_SRVR_HELLO_B: + ret=ssl3_get_server_hello(s); + if (ret <= 0) goto end; + + if (s->hit) + s->state=SSL3_ST_CR_FINISHED_A; + else + s->state=SSL3_ST_CR_CERT_A; + s->init_num=0; + break; + + case SSL3_ST_CR_CERT_A: + case SSL3_ST_CR_CERT_B: +#ifndef OPENSSL_NO_TLSEXT + ret=ssl3_check_finished(s); + if (ret <= 0) goto end; + if (ret == 2) + { + s->hit = 1; + if (s->tlsext_ticket_expected) + s->state=SSL3_ST_CR_SESSION_TICKET_A; + else + s->state=SSL3_ST_CR_FINISHED_A; + s->init_num=0; + break; + } +#endif + /* Check if it is anon DH/ECDH */ + /* or PSK */ + if (!(s->s3->tmp.new_cipher->algorithm_auth & SSL_aNULL) && + !(s->s3->tmp.new_cipher->algorithm_mkey & SSL_kPSK)) + { + ret=ssl3_get_server_certificate(s); + if (ret <= 0) goto end; +#ifndef OPENSSL_NO_TLSEXT + if (s->tlsext_status_expected) + s->state=SSL3_ST_CR_CERT_STATUS_A; + else + s->state=SSL3_ST_CR_KEY_EXCH_A; + } + else + { + skip = 1; + s->state=SSL3_ST_CR_KEY_EXCH_A; + } +#else + } + else + skip=1; + + s->state=SSL3_ST_CR_KEY_EXCH_A; +#endif + s->init_num=0; + break; + + case SSL3_ST_CR_KEY_EXCH_A: + case SSL3_ST_CR_KEY_EXCH_B: + ret=ssl3_get_key_exchange(s); + if (ret <= 0) goto end; + s->state=SSL3_ST_CR_CERT_REQ_A; + s->init_num=0; + + /* at this point we check that we have the + * required stuff from the server */ + if (!ssl3_check_cert_and_algorithm(s)) + { + ret= -1; + goto end; + } + break; + + case SSL3_ST_CR_CERT_REQ_A: + case SSL3_ST_CR_CERT_REQ_B: + ret=ssl3_get_certificate_request(s); + if (ret <= 0) goto end; + s->state=SSL3_ST_CR_SRVR_DONE_A; + s->init_num=0; + break; + + case SSL3_ST_CR_SRVR_DONE_A: + case SSL3_ST_CR_SRVR_DONE_B: + ret=ssl3_get_server_done(s); + if (ret <= 0) goto end; + if (s->s3->tmp.cert_req) + s->state=SSL3_ST_CW_CERT_A; + else + s->state=SSL3_ST_CW_KEY_EXCH_A; + s->init_num=0; + + break; + + case SSL3_ST_CW_CERT_A: + case SSL3_ST_CW_CERT_B: + case SSL3_ST_CW_CERT_C: + case SSL3_ST_CW_CERT_D: + ret=ssl3_send_client_certificate(s); + if (ret <= 0) goto end; + s->state=SSL3_ST_CW_KEY_EXCH_A; + s->init_num=0; + break; + + case SSL3_ST_CW_KEY_EXCH_A: + case SSL3_ST_CW_KEY_EXCH_B: + ret=ssl3_send_client_key_exchange(s); + if (ret <= 0) goto end; + /* EAY EAY EAY need to check for DH fix cert + * sent back */ + /* For TLS, cert_req is set to 2, so a cert chain + * of nothing is sent, but no verify packet is sent */ + /* XXX: For now, we do not support client + * authentication in ECDH cipher suites with + * ECDH (rather than ECDSA) certificates. + * We need to skip the certificate verify + * message when client's ECDH public key is sent + * inside the client certificate. + */ + if (s->s3->tmp.cert_req == 1) + { + s->state=SSL3_ST_CW_CERT_VRFY_A; + } + else + { + s->state=SSL3_ST_CW_CHANGE_A; + s->s3->change_cipher_spec=0; + } + if (s->s3->flags & TLS1_FLAGS_SKIP_CERT_VERIFY) + { + s->state=SSL3_ST_CW_CHANGE_A; + s->s3->change_cipher_spec=0; + } + + s->init_num=0; + break; + + case SSL3_ST_CW_CERT_VRFY_A: + case SSL3_ST_CW_CERT_VRFY_B: + ret=ssl3_send_client_verify(s); + if (ret <= 0) goto end; + s->state=SSL3_ST_CW_CHANGE_A; + s->init_num=0; + s->s3->change_cipher_spec=0; + break; + + case SSL3_ST_CW_CHANGE_A: + case SSL3_ST_CW_CHANGE_B: + ret=ssl3_send_change_cipher_spec(s, + SSL3_ST_CW_CHANGE_A,SSL3_ST_CW_CHANGE_B); + if (ret <= 0) goto end; + +#if defined(OPENSSL_NO_TLSEXT) || defined(OPENSSL_NO_NEXTPROTONEG) + s->state=SSL3_ST_CW_FINISHED_A; +#else + if (s->next_proto_negotiated) + s->state=SSL3_ST_CW_NEXT_PROTO_A; + else + s->state=SSL3_ST_CW_FINISHED_A; +#endif + + s->init_num=0; + + s->session->cipher=s->s3->tmp.new_cipher; +#ifdef OPENSSL_NO_COMP + s->session->compress_meth=0; +#else + if (s->s3->tmp.new_compression == NULL) + s->session->compress_meth=0; + else + s->session->compress_meth= + s->s3->tmp.new_compression->id; +#endif + if (!s->method->ssl3_enc->setup_key_block(s)) + { + ret= -1; + goto end; + } + + if (!s->method->ssl3_enc->change_cipher_state(s, + SSL3_CHANGE_CIPHER_CLIENT_WRITE)) + { + ret= -1; + goto end; + } + + break; + +#if !defined(OPENSSL_NO_TLSEXT) && !defined(OPENSSL_NO_NEXTPROTONEG) + case SSL3_ST_CW_NEXT_PROTO_A: + case SSL3_ST_CW_NEXT_PROTO_B: + ret=ssl3_send_next_proto(s); + if (ret <= 0) goto end; + s->state=SSL3_ST_CW_FINISHED_A; + break; +#endif + + case SSL3_ST_CW_FINISHED_A: + case SSL3_ST_CW_FINISHED_B: + ret=ssl3_send_finished(s, + SSL3_ST_CW_FINISHED_A,SSL3_ST_CW_FINISHED_B, + s->method->ssl3_enc->client_finished_label, + s->method->ssl3_enc->client_finished_label_len); + if (ret <= 0) goto end; + s->state=SSL3_ST_CW_FLUSH; + + /* clear flags */ + s->s3->flags&= ~SSL3_FLAGS_POP_BUFFER; + if (s->hit) + { + s->s3->tmp.next_state=SSL_ST_OK; + if (s->s3->flags & SSL3_FLAGS_DELAY_CLIENT_FINISHED) + { + s->state=SSL_ST_OK; + s->s3->flags|=SSL3_FLAGS_POP_BUFFER; + s->s3->delay_buf_pop_ret=0; + } + } + else + { + if ((SSL_get_mode(s) & SSL_MODE_HANDSHAKE_CUTTHROUGH) && SSL_get_cipher_bits(s, NULL) >= 128 + && s->s3->previous_server_finished_len == 0 /* no cutthrough on renegotiation (would complicate the state machine) */ + ) + { + if (s->s3->flags & SSL3_FLAGS_DELAY_CLIENT_FINISHED) + { + s->state=SSL3_ST_CUTTHROUGH_COMPLETE; + s->s3->flags|=SSL3_FLAGS_POP_BUFFER; + s->s3->delay_buf_pop_ret=0; + } + else + { + s->s3->tmp.next_state=SSL3_ST_CUTTHROUGH_COMPLETE; + } + } + else + { +#ifndef OPENSSL_NO_TLSEXT + /* Allow NewSessionTicket if ticket expected */ + if (s->tlsext_ticket_expected) + s->s3->tmp.next_state=SSL3_ST_CR_SESSION_TICKET_A; + else +#endif + s->s3->tmp.next_state=SSL3_ST_CR_FINISHED_A; + } + } + s->init_num=0; + break; + +#ifndef OPENSSL_NO_TLSEXT + case SSL3_ST_CR_SESSION_TICKET_A: + case SSL3_ST_CR_SESSION_TICKET_B: + ret=ssl3_get_new_session_ticket(s); + if (ret <= 0) goto end; + s->state=SSL3_ST_CR_FINISHED_A; + s->init_num=0; + break; + + case SSL3_ST_CR_CERT_STATUS_A: + case SSL3_ST_CR_CERT_STATUS_B: + ret=ssl3_get_cert_status(s); + if (ret <= 0) goto end; + s->state=SSL3_ST_CR_KEY_EXCH_A; + s->init_num=0; + break; +#endif + + case SSL3_ST_CR_FINISHED_A: + case SSL3_ST_CR_FINISHED_B: + + ret=ssl3_get_finished(s,SSL3_ST_CR_FINISHED_A, + SSL3_ST_CR_FINISHED_B); + if (ret <= 0) goto end; + + if (s->hit) + s->state=SSL3_ST_CW_CHANGE_A; + else + s->state=SSL_ST_OK; + s->init_num=0; + break; + + case SSL3_ST_CW_FLUSH: + s->rwstate=SSL_WRITING; + if (BIO_flush(s->wbio) <= 0) + { + ret= -1; + goto end; + } + s->rwstate=SSL_NOTHING; + s->state=s->s3->tmp.next_state; + break; + + case SSL3_ST_CUTTHROUGH_COMPLETE: +#ifndef OPENSSL_NO_TLSEXT + /* Allow NewSessionTicket if ticket expected */ + if (s->tlsext_ticket_expected) + s->state=SSL3_ST_CR_SESSION_TICKET_A; + else +#endif + s->state=SSL3_ST_CR_FINISHED_A; + + /* SSL_write() will take care of flushing buffered data if + * DELAY_CLIENT_FINISHED is set. + */ + if (!(s->s3->flags & SSL3_FLAGS_DELAY_CLIENT_FINISHED)) + ssl_free_wbio_buffer(s); + ret = 1; + goto end; + /* break; */ + + case SSL_ST_OK: + /* clean a few things up */ + ssl3_cleanup_key_block(s); + + if (s->init_buf != NULL) + { + BUF_MEM_free(s->init_buf); + s->init_buf=NULL; + } + + /* If we are not 'joining' the last two packets, + * remove the buffering now */ + if (!(s->s3->flags & SSL3_FLAGS_POP_BUFFER)) + ssl_free_wbio_buffer(s); + /* else do it later in ssl3_write */ + + s->init_num=0; + s->new_session=0; + + ssl_update_cache(s,SSL_SESS_CACHE_CLIENT); + if (s->hit) s->ctx->stats.sess_hit++; + + ret=1; + /* s->server=0; */ + s->handshake_func=ssl3_connect; + s->ctx->stats.sess_connect_good++; + + if (cb != NULL) cb(s,SSL_CB_HANDSHAKE_DONE,1); + + goto end; + /* break; */ + + default: + SSLerr(SSL_F_SSL3_CONNECT,SSL_R_UNKNOWN_STATE); + ret= -1; + goto end; + /* break; */ + } + + /* did we do anything */ + if (!s->s3->tmp.reuse_message && !skip) + { + if (s->debug) + { + if ((ret=BIO_flush(s->wbio)) <= 0) + goto end; + } + + if ((cb != NULL) && (s->state != state)) + { + new_state=s->state; + s->state=state; + cb(s,SSL_CB_CONNECT_LOOP,1); + s->state=new_state; + } + } + skip=0; + } +end: + s->in_handshake--; + if (buf != NULL) + BUF_MEM_free(buf); + if (cb != NULL) + cb(s,SSL_CB_CONNECT_EXIT,ret); + return(ret); + } + + +int ssl3_client_hello(SSL *s) + { + unsigned char *buf; + unsigned char *p,*d; + int i; + unsigned long Time,l; +#ifndef OPENSSL_NO_COMP + int j; + SSL_COMP *comp; +#endif + + buf=(unsigned char *)s->init_buf->data; + if (s->state == SSL3_ST_CW_CLNT_HELLO_A) + { + SSL_SESSION *sess = s->session; + if ((sess == NULL) || + (sess->ssl_version != s->version) || +#ifdef OPENSSL_NO_TLSEXT + !sess->session_id_length || +#else + (!sess->session_id_length && !sess->tlsext_tick) || +#endif + (sess->not_resumable)) + { + if (!s->session_creation_enabled) + { + ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_HANDSHAKE_FAILURE); + SSLerr(SSL_F_SSL3_CLIENT_HELLO,SSL_R_SESSION_MAY_NOT_BE_CREATED); + goto err; + } + if (!ssl_get_new_session(s,0)) + goto err; + } + /* else use the pre-loaded session */ + + p=s->s3->client_random; + Time=(unsigned long)time(NULL); /* Time */ + l2n(Time,p); + if (RAND_pseudo_bytes(p,SSL3_RANDOM_SIZE-4) <= 0) + goto err; + + /* Do the message type and length last */ + d=p= &(buf[4]); + + *(p++)=s->version>>8; + *(p++)=s->version&0xff; + s->client_version=s->version; + + /* Random stuff */ + memcpy(p,s->s3->client_random,SSL3_RANDOM_SIZE); + p+=SSL3_RANDOM_SIZE; + + /* Session ID */ + if (s->new_session) + i=0; + else + i=s->session->session_id_length; + *(p++)=i; + if (i != 0) + { + if (i > (int)sizeof(s->session->session_id)) + { + SSLerr(SSL_F_SSL3_CLIENT_HELLO, ERR_R_INTERNAL_ERROR); + goto err; + } + memcpy(p,s->session->session_id,i); + p+=i; + } + + /* Ciphers supported */ + i=ssl_cipher_list_to_bytes(s,SSL_get_ciphers(s),&(p[2]),0); + if (i == 0) + { + SSLerr(SSL_F_SSL3_CLIENT_HELLO,SSL_R_NO_CIPHERS_AVAILABLE); + goto err; + } + s2n(i,p); + p+=i; + + /* COMPRESSION */ +#ifdef OPENSSL_NO_COMP + *(p++)=1; +#else + + if ((s->options & SSL_OP_NO_COMPRESSION) + || !s->ctx->comp_methods) + j=0; + else + j=sk_SSL_COMP_num(s->ctx->comp_methods); + *(p++)=1+j; + for (i=0; ictx->comp_methods,i); + *(p++)=comp->id; + } +#endif + *(p++)=0; /* Add the NULL method */ + +#ifndef OPENSSL_NO_TLSEXT + /* TLS extensions*/ + if (ssl_prepare_clienthello_tlsext(s) <= 0) + { + SSLerr(SSL_F_SSL3_CLIENT_HELLO,SSL_R_CLIENTHELLO_TLSEXT); + goto err; + } + if ((p = ssl_add_clienthello_tlsext(s, p, buf+SSL3_RT_MAX_PLAIN_LENGTH)) == NULL) + { + SSLerr(SSL_F_SSL3_CLIENT_HELLO,ERR_R_INTERNAL_ERROR); + goto err; + } +#endif + + l=(p-d); + d=buf; + *(d++)=SSL3_MT_CLIENT_HELLO; + l2n3(l,d); + + s->state=SSL3_ST_CW_CLNT_HELLO_B; + /* number of bytes to write */ + s->init_num=p-buf; + s->init_off=0; + } + + /* SSL3_ST_CW_CLNT_HELLO_B */ + return(ssl3_do_write(s,SSL3_RT_HANDSHAKE)); +err: + return(-1); + } + +int ssl3_get_server_hello(SSL *s) + { + STACK_OF(SSL_CIPHER) *sk; + const SSL_CIPHER *c; + unsigned char *p,*d; + int i,al,ok; + unsigned int j; + long n; +#ifndef OPENSSL_NO_COMP + SSL_COMP *comp; +#endif + + n=s->method->ssl_get_message(s, + SSL3_ST_CR_SRVR_HELLO_A, + SSL3_ST_CR_SRVR_HELLO_B, + -1, + 20000, /* ?? */ + &ok); + + if (!ok) return((int)n); + + if ( SSL_version(s) == DTLS1_VERSION || SSL_version(s) == DTLS1_BAD_VER) + { + if ( s->s3->tmp.message_type == DTLS1_MT_HELLO_VERIFY_REQUEST) + { + if ( s->d1->send_cookie == 0) + { + s->s3->tmp.reuse_message = 1; + return 1; + } + else /* already sent a cookie */ + { + al=SSL_AD_UNEXPECTED_MESSAGE; + SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_BAD_MESSAGE_TYPE); + goto f_err; + } + } + } + + if ( s->s3->tmp.message_type != SSL3_MT_SERVER_HELLO) + { + al=SSL_AD_UNEXPECTED_MESSAGE; + SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_BAD_MESSAGE_TYPE); + goto f_err; + } + + d=p=(unsigned char *)s->init_msg; + + if ((p[0] != (s->version>>8)) || (p[1] != (s->version&0xff))) + { + SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_WRONG_SSL_VERSION); + s->version=(s->version&0xff00)|p[1]; + al=SSL_AD_PROTOCOL_VERSION; + goto f_err; + } + p+=2; + + /* load the server hello data */ + /* load the server random */ + memcpy(s->s3->server_random,p,SSL3_RANDOM_SIZE); + p+=SSL3_RANDOM_SIZE; + + /* get the session-id */ + j= *(p++); + + if ((j > sizeof s->session->session_id) || (j > SSL3_SESSION_ID_SIZE)) + { + al=SSL_AD_ILLEGAL_PARAMETER; + SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_SSL3_SESSION_ID_TOO_LONG); + goto f_err; + } + +#ifndef OPENSSL_NO_TLSEXT + /* check if we want to resume the session based on external pre-shared secret */ + if (s->version >= TLS1_VERSION && s->tls_session_secret_cb) + { + SSL_CIPHER *pref_cipher=NULL; + s->session->master_key_length=sizeof(s->session->master_key); + if (s->tls_session_secret_cb(s, s->session->master_key, + &s->session->master_key_length, + NULL, &pref_cipher, + s->tls_session_secret_cb_arg)) + { + s->session->cipher = pref_cipher ? + pref_cipher : ssl_get_cipher_by_char(s, p+j); + } + } +#endif /* OPENSSL_NO_TLSEXT */ + + if (j != 0 && j == s->session->session_id_length + && memcmp(p,s->session->session_id,j) == 0) + { + if(s->sid_ctx_length != s->session->sid_ctx_length + || memcmp(s->session->sid_ctx,s->sid_ctx,s->sid_ctx_length)) + { + /* actually a client application bug */ + al=SSL_AD_ILLEGAL_PARAMETER; + SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_ATTEMPT_TO_REUSE_SESSION_IN_DIFFERENT_CONTEXT); + goto f_err; + } + s->hit=1; + } + else /* a miss or crap from the other end */ + { + /* If we were trying for session-id reuse, make a new + * SSL_SESSION so we don't stuff up other people */ + s->hit=0; + if (s->session->session_id_length > 0) + { + if (!s->session_creation_enabled) + { + ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_HANDSHAKE_FAILURE); + SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_SESSION_MAY_NOT_BE_CREATED); + goto err; + } + if (!ssl_get_new_session(s,0)) + { + al=SSL_AD_INTERNAL_ERROR; + goto f_err; + } + } + s->session->session_id_length=j; + memcpy(s->session->session_id,p,j); /* j could be 0 */ + } + p+=j; + c=ssl_get_cipher_by_char(s,p); + if (c == NULL) + { + /* unknown cipher */ + al=SSL_AD_ILLEGAL_PARAMETER; + SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_UNKNOWN_CIPHER_RETURNED); + goto f_err; + } + p+=ssl_put_cipher_by_char(s,NULL,NULL); + + sk=ssl_get_ciphers_by_id(s); + i=sk_SSL_CIPHER_find(sk,c); + if (i < 0) + { + /* we did not say we would use this cipher */ + al=SSL_AD_ILLEGAL_PARAMETER; + SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_WRONG_CIPHER_RETURNED); + goto f_err; + } + + /* Depending on the session caching (internal/external), the cipher + and/or cipher_id values may not be set. Make sure that + cipher_id is set and use it for comparison. */ + if (s->session->cipher) + s->session->cipher_id = s->session->cipher->id; + if (s->hit && (s->session->cipher_id != c->id)) + { +/* Workaround is now obsolete */ +#if 0 + if (!(s->options & + SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG)) +#endif + { + al=SSL_AD_ILLEGAL_PARAMETER; + SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_OLD_SESSION_CIPHER_NOT_RETURNED); + goto f_err; + } + } + s->s3->tmp.new_cipher=c; + if (!ssl3_digest_cached_records(s)) + goto f_err; + + /* lets get the compression algorithm */ + /* COMPRESSION */ +#ifdef OPENSSL_NO_COMP + if (*(p++) != 0) + { + al=SSL_AD_ILLEGAL_PARAMETER; + SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_UNSUPPORTED_COMPRESSION_ALGORITHM); + goto f_err; + } + /* If compression is disabled we'd better not try to resume a session + * using compression. + */ + if (s->session->compress_meth != 0) + { + al=SSL_AD_INTERNAL_ERROR; + SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_INCONSISTENT_COMPRESSION); + goto f_err; + } +#else + j= *(p++); + if (s->hit && j != s->session->compress_meth) + { + al=SSL_AD_ILLEGAL_PARAMETER; + SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_OLD_SESSION_COMPRESSION_ALGORITHM_NOT_RETURNED); + goto f_err; + } + if (j == 0) + comp=NULL; + else if (s->options & SSL_OP_NO_COMPRESSION) + { + al=SSL_AD_ILLEGAL_PARAMETER; + SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_COMPRESSION_DISABLED); + goto f_err; + } + else + comp=ssl3_comp_find(s->ctx->comp_methods,j); + + if ((j != 0) && (comp == NULL)) + { + al=SSL_AD_ILLEGAL_PARAMETER; + SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_UNSUPPORTED_COMPRESSION_ALGORITHM); + goto f_err; + } + else + { + s->s3->tmp.new_compression=comp; + } +#endif + +#ifndef OPENSSL_NO_TLSEXT + /* TLS extensions*/ + if (s->version >= SSL3_VERSION) + { + if (!ssl_parse_serverhello_tlsext(s,&p,d,n, &al)) + { + /* 'al' set by ssl_parse_serverhello_tlsext */ + SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_PARSE_TLSEXT); + goto f_err; + } + if (ssl_check_serverhello_tlsext(s) <= 0) + { + SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_SERVERHELLO_TLSEXT); + goto err; + } + } +#endif + + if (p != (d+n)) + { + /* wrong packet length */ + al=SSL_AD_DECODE_ERROR; + SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_BAD_PACKET_LENGTH); + goto f_err; + } + + return(1); +f_err: + ssl3_send_alert(s,SSL3_AL_FATAL,al); +err: + return(-1); + } + +int ssl3_get_server_certificate(SSL *s) + { + int al,i,ok,ret= -1; + unsigned long n,nc,llen,l; + X509 *x=NULL; + const unsigned char *q,*p; + unsigned char *d; + STACK_OF(X509) *sk=NULL; + SESS_CERT *sc; + EVP_PKEY *pkey=NULL; + int need_cert = 1; /* VRS: 0=> will allow null cert if auth == KRB5 */ + + n=s->method->ssl_get_message(s, + SSL3_ST_CR_CERT_A, + SSL3_ST_CR_CERT_B, + -1, + s->max_cert_list, + &ok); + + if (!ok) return((int)n); + + if ((s->s3->tmp.message_type == SSL3_MT_SERVER_KEY_EXCHANGE) || + ((s->s3->tmp.new_cipher->algorithm_auth & SSL_aKRB5) && + (s->s3->tmp.message_type == SSL3_MT_SERVER_DONE))) + { + s->s3->tmp.reuse_message=1; + return(1); + } + + if (s->s3->tmp.message_type != SSL3_MT_CERTIFICATE) + { + al=SSL_AD_UNEXPECTED_MESSAGE; + SSLerr(SSL_F_SSL3_GET_SERVER_CERTIFICATE,SSL_R_BAD_MESSAGE_TYPE); + goto f_err; + } + p=d=(unsigned char *)s->init_msg; + + if ((sk=sk_X509_new_null()) == NULL) + { + SSLerr(SSL_F_SSL3_GET_SERVER_CERTIFICATE,ERR_R_MALLOC_FAILURE); + goto err; + } + + n2l3(p,llen); + if (llen+3 != n) + { + al=SSL_AD_DECODE_ERROR; + SSLerr(SSL_F_SSL3_GET_SERVER_CERTIFICATE,SSL_R_LENGTH_MISMATCH); + goto f_err; + } + for (nc=0; nc llen) + { + al=SSL_AD_DECODE_ERROR; + SSLerr(SSL_F_SSL3_GET_SERVER_CERTIFICATE,SSL_R_CERT_LENGTH_MISMATCH); + goto f_err; + } + + q=p; + x=d2i_X509(NULL,&q,l); + if (x == NULL) + { + al=SSL_AD_BAD_CERTIFICATE; + SSLerr(SSL_F_SSL3_GET_SERVER_CERTIFICATE,ERR_R_ASN1_LIB); + goto f_err; + } + if (q != (p+l)) + { + al=SSL_AD_DECODE_ERROR; + SSLerr(SSL_F_SSL3_GET_SERVER_CERTIFICATE,SSL_R_CERT_LENGTH_MISMATCH); + goto f_err; + } + if (!sk_X509_push(sk,x)) + { + SSLerr(SSL_F_SSL3_GET_SERVER_CERTIFICATE,ERR_R_MALLOC_FAILURE); + goto err; + } + x=NULL; + nc+=l+3; + p=q; + } + + i=ssl_verify_cert_chain(s,sk); + if ((s->verify_mode != SSL_VERIFY_NONE) && (i <= 0) +#ifndef OPENSSL_NO_KRB5 + && !((s->s3->tmp.new_cipher->algorithm_mkey & SSL_kKRB5) && + (s->s3->tmp.new_cipher->algorithm_auth & SSL_aKRB5)) +#endif /* OPENSSL_NO_KRB5 */ + ) + { + al=ssl_verify_alarm_type(s->verify_result); + SSLerr(SSL_F_SSL3_GET_SERVER_CERTIFICATE,SSL_R_CERTIFICATE_VERIFY_FAILED); + goto f_err; + } + ERR_clear_error(); /* but we keep s->verify_result */ + + sc=ssl_sess_cert_new(); + if (sc == NULL) goto err; + + if (s->session->sess_cert) ssl_sess_cert_free(s->session->sess_cert); + s->session->sess_cert=sc; + + sc->cert_chain=sk; + /* Inconsistency alert: cert_chain does include the peer's + * certificate, which we don't include in s3_srvr.c */ + x=sk_X509_value(sk,0); + sk=NULL; + /* VRS 19990621: possible memory leak; sk=null ==> !sk_pop_free() @end*/ + + pkey=X509_get_pubkey(x); + + /* VRS: allow null cert if auth == KRB5 */ + need_cert = ((s->s3->tmp.new_cipher->algorithm_mkey & SSL_kKRB5) && + (s->s3->tmp.new_cipher->algorithm_auth & SSL_aKRB5)) + ? 0 : 1; + +#ifdef KSSL_DEBUG + printf("pkey,x = %p, %p\n", pkey,x); + printf("ssl_cert_type(x,pkey) = %d\n", ssl_cert_type(x,pkey)); + printf("cipher, alg, nc = %s, %lx, %lx, %d\n", s->s3->tmp.new_cipher->name, + s->s3->tmp.new_cipher->algorithm_mkey, s->s3->tmp.new_cipher->algorithm_auth, need_cert); +#endif /* KSSL_DEBUG */ + + if (need_cert && ((pkey == NULL) || EVP_PKEY_missing_parameters(pkey))) + { + x=NULL; + al=SSL3_AL_FATAL; + SSLerr(SSL_F_SSL3_GET_SERVER_CERTIFICATE, + SSL_R_UNABLE_TO_FIND_PUBLIC_KEY_PARAMETERS); + goto f_err; + } + + i=ssl_cert_type(x,pkey); + if (need_cert && i < 0) + { + x=NULL; + al=SSL3_AL_FATAL; + SSLerr(SSL_F_SSL3_GET_SERVER_CERTIFICATE, + SSL_R_UNKNOWN_CERTIFICATE_TYPE); + goto f_err; + } + + if (need_cert) + { + sc->peer_cert_type=i; + CRYPTO_add(&x->references,1,CRYPTO_LOCK_X509); + /* Why would the following ever happen? + * We just created sc a couple of lines ago. */ + if (sc->peer_pkeys[i].x509 != NULL) + X509_free(sc->peer_pkeys[i].x509); + sc->peer_pkeys[i].x509=x; + sc->peer_key= &(sc->peer_pkeys[i]); + + if (s->session->peer != NULL) + X509_free(s->session->peer); + CRYPTO_add(&x->references,1,CRYPTO_LOCK_X509); + s->session->peer=x; + } + else + { + sc->peer_cert_type=i; + sc->peer_key= NULL; + + if (s->session->peer != NULL) + X509_free(s->session->peer); + s->session->peer=NULL; + } + s->session->verify_result = s->verify_result; + + x=NULL; + ret=1; + + if (0) + { +f_err: + ssl3_send_alert(s,SSL3_AL_FATAL,al); + } +err: + EVP_PKEY_free(pkey); + X509_free(x); + sk_X509_pop_free(sk,X509_free); + return(ret); + } + +int ssl3_get_key_exchange(SSL *s) + { +#ifndef OPENSSL_NO_RSA + unsigned char *q,md_buf[EVP_MAX_MD_SIZE*2]; +#endif + EVP_MD_CTX md_ctx; + unsigned char *param,*p; + int al,i,j,param_len,ok; + long n,alg_k,alg_a; + EVP_PKEY *pkey=NULL; +#ifndef OPENSSL_NO_RSA + RSA *rsa=NULL; +#endif +#ifndef OPENSSL_NO_DH + DH *dh=NULL; +#endif +#ifndef OPENSSL_NO_ECDH + EC_KEY *ecdh = NULL; + BN_CTX *bn_ctx = NULL; + EC_POINT *srvr_ecpoint = NULL; + int curve_nid = 0; + int encoded_pt_len = 0; +#endif + + /* use same message size as in ssl3_get_certificate_request() + * as ServerKeyExchange message may be skipped */ + n=s->method->ssl_get_message(s, + SSL3_ST_CR_KEY_EXCH_A, + SSL3_ST_CR_KEY_EXCH_B, + -1, + s->max_cert_list, + &ok); + if (!ok) return((int)n); + + if (s->s3->tmp.message_type != SSL3_MT_SERVER_KEY_EXCHANGE) + { +#ifndef OPENSSL_NO_PSK + /* In plain PSK ciphersuite, ServerKeyExchange can be + omitted if no identity hint is sent. Set + session->sess_cert anyway to avoid problems + later.*/ + if (s->s3->tmp.new_cipher->algorithm_mkey & SSL_kPSK) + { + s->session->sess_cert=ssl_sess_cert_new(); + if (s->ctx->psk_identity_hint) + OPENSSL_free(s->ctx->psk_identity_hint); + s->ctx->psk_identity_hint = NULL; + } +#endif + s->s3->tmp.reuse_message=1; + return(1); + } + + param=p=(unsigned char *)s->init_msg; + if (s->session->sess_cert != NULL) + { +#ifndef OPENSSL_NO_RSA + if (s->session->sess_cert->peer_rsa_tmp != NULL) + { + RSA_free(s->session->sess_cert->peer_rsa_tmp); + s->session->sess_cert->peer_rsa_tmp=NULL; + } +#endif +#ifndef OPENSSL_NO_DH + if (s->session->sess_cert->peer_dh_tmp) + { + DH_free(s->session->sess_cert->peer_dh_tmp); + s->session->sess_cert->peer_dh_tmp=NULL; + } +#endif +#ifndef OPENSSL_NO_ECDH + if (s->session->sess_cert->peer_ecdh_tmp) + { + EC_KEY_free(s->session->sess_cert->peer_ecdh_tmp); + s->session->sess_cert->peer_ecdh_tmp=NULL; + } +#endif + } + else + { + s->session->sess_cert=ssl_sess_cert_new(); + } + + param_len=0; + alg_k=s->s3->tmp.new_cipher->algorithm_mkey; + alg_a=s->s3->tmp.new_cipher->algorithm_auth; + EVP_MD_CTX_init(&md_ctx); + +#ifndef OPENSSL_NO_PSK + if (alg_k & SSL_kPSK) + { + char tmp_id_hint[PSK_MAX_IDENTITY_LEN+1]; + + al=SSL_AD_HANDSHAKE_FAILURE; + n2s(p,i); + param_len=i+2; + /* Store PSK identity hint for later use, hint is used + * in ssl3_send_client_key_exchange. Assume that the + * maximum length of a PSK identity hint can be as + * long as the maximum length of a PSK identity. */ + if (i > PSK_MAX_IDENTITY_LEN) + { + SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, + SSL_R_DATA_LENGTH_TOO_LONG); + goto f_err; + } + if (param_len > n) + { + al=SSL_AD_DECODE_ERROR; + SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, + SSL_R_BAD_PSK_IDENTITY_HINT_LENGTH); + goto f_err; + } + /* If received PSK identity hint contains NULL + * characters, the hint is truncated from the first + * NULL. p may not be ending with NULL, so create a + * NULL-terminated string. */ + memcpy(tmp_id_hint, p, i); + memset(tmp_id_hint+i, 0, PSK_MAX_IDENTITY_LEN+1-i); + if (s->ctx->psk_identity_hint != NULL) + OPENSSL_free(s->ctx->psk_identity_hint); + s->ctx->psk_identity_hint = BUF_strdup(tmp_id_hint); + if (s->ctx->psk_identity_hint == NULL) + { + SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE); + goto f_err; + } + + p+=i; + n-=param_len; + } + else +#endif /* !OPENSSL_NO_PSK */ +#ifndef OPENSSL_NO_RSA + if (alg_k & SSL_kRSA) + { + if ((rsa=RSA_new()) == NULL) + { + SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_MALLOC_FAILURE); + goto err; + } + n2s(p,i); + param_len=i+2; + if (param_len > n) + { + al=SSL_AD_DECODE_ERROR; + SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_RSA_MODULUS_LENGTH); + goto f_err; + } + if (!(rsa->n=BN_bin2bn(p,i,rsa->n))) + { + SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_BN_LIB); + goto err; + } + p+=i; + + n2s(p,i); + param_len+=i+2; + if (param_len > n) + { + al=SSL_AD_DECODE_ERROR; + SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_RSA_E_LENGTH); + goto f_err; + } + if (!(rsa->e=BN_bin2bn(p,i,rsa->e))) + { + SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_BN_LIB); + goto err; + } + p+=i; + n-=param_len; + + /* this should be because we are using an export cipher */ + if (alg_a & SSL_aRSA) + pkey=X509_get_pubkey(s->session->sess_cert->peer_pkeys[SSL_PKEY_RSA_ENC].x509); + else + { + SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_INTERNAL_ERROR); + goto err; + } + s->session->sess_cert->peer_rsa_tmp=rsa; + rsa=NULL; + } +#else /* OPENSSL_NO_RSA */ + if (0) + ; +#endif +#ifndef OPENSSL_NO_DH + else if (alg_k & SSL_kEDH) + { + if ((dh=DH_new()) == NULL) + { + SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_DH_LIB); + goto err; + } + n2s(p,i); + param_len=i+2; + if (param_len > n) + { + al=SSL_AD_DECODE_ERROR; + SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_DH_P_LENGTH); + goto f_err; + } + if (!(dh->p=BN_bin2bn(p,i,NULL))) + { + SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_BN_LIB); + goto err; + } + p+=i; + + n2s(p,i); + param_len+=i+2; + if (param_len > n) + { + al=SSL_AD_DECODE_ERROR; + SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_DH_G_LENGTH); + goto f_err; + } + if (!(dh->g=BN_bin2bn(p,i,NULL))) + { + SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_BN_LIB); + goto err; + } + p+=i; + + n2s(p,i); + param_len+=i+2; + if (param_len > n) + { + al=SSL_AD_DECODE_ERROR; + SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_DH_PUB_KEY_LENGTH); + goto f_err; + } + if (!(dh->pub_key=BN_bin2bn(p,i,NULL))) + { + SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_BN_LIB); + goto err; + } + p+=i; + n-=param_len; + +#ifndef OPENSSL_NO_RSA + if (alg_a & SSL_aRSA) + pkey=X509_get_pubkey(s->session->sess_cert->peer_pkeys[SSL_PKEY_RSA_ENC].x509); +#else + if (0) + ; +#endif +#ifndef OPENSSL_NO_DSA + else if (alg_a & SSL_aDSS) + pkey=X509_get_pubkey(s->session->sess_cert->peer_pkeys[SSL_PKEY_DSA_SIGN].x509); +#endif + /* else anonymous DH, so no certificate or pkey. */ + + s->session->sess_cert->peer_dh_tmp=dh; + dh=NULL; + } + else if ((alg_k & SSL_kDHr) || (alg_k & SSL_kDHd)) + { + al=SSL_AD_ILLEGAL_PARAMETER; + SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_TRIED_TO_USE_UNSUPPORTED_CIPHER); + goto f_err; + } +#endif /* !OPENSSL_NO_DH */ + +#ifndef OPENSSL_NO_ECDH + else if (alg_k & SSL_kEECDH) + { + EC_GROUP *ngroup; + const EC_GROUP *group; + + if ((ecdh=EC_KEY_new()) == NULL) + { + SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_MALLOC_FAILURE); + goto err; + } + + /* Extract elliptic curve parameters and the + * server's ephemeral ECDH public key. + * Keep accumulating lengths of various components in + * param_len and make sure it never exceeds n. + */ + + /* XXX: For now we only support named (not generic) curves + * and the ECParameters in this case is just three bytes. + */ + param_len=3; + if ((param_len > n) || + (*p != NAMED_CURVE_TYPE) || + ((curve_nid = tls1_ec_curve_id2nid(*(p + 2))) == 0)) + { + al=SSL_AD_INTERNAL_ERROR; + SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_UNABLE_TO_FIND_ECDH_PARAMETERS); + goto f_err; + } + + ngroup = EC_GROUP_new_by_curve_name(curve_nid); + if (ngroup == NULL) + { + SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_EC_LIB); + goto err; + } + if (EC_KEY_set_group(ecdh, ngroup) == 0) + { + SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_EC_LIB); + goto err; + } + EC_GROUP_free(ngroup); + + group = EC_KEY_get0_group(ecdh); + + if (SSL_C_IS_EXPORT(s->s3->tmp.new_cipher) && + (EC_GROUP_get_degree(group) > 163)) + { + al=SSL_AD_EXPORT_RESTRICTION; + SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_ECGROUP_TOO_LARGE_FOR_CIPHER); + goto f_err; + } + + p+=3; + + /* Next, get the encoded ECPoint */ + if (((srvr_ecpoint = EC_POINT_new(group)) == NULL) || + ((bn_ctx = BN_CTX_new()) == NULL)) + { + SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_MALLOC_FAILURE); + goto err; + } + + encoded_pt_len = *p; /* length of encoded point */ + p+=1; + param_len += (1 + encoded_pt_len); + if ((param_len > n) || + (EC_POINT_oct2point(group, srvr_ecpoint, + p, encoded_pt_len, bn_ctx) == 0)) + { + al=SSL_AD_DECODE_ERROR; + SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_ECPOINT); + goto f_err; + } + + n-=param_len; + p+=encoded_pt_len; + + /* The ECC/TLS specification does not mention + * the use of DSA to sign ECParameters in the server + * key exchange message. We do support RSA and ECDSA. + */ + if (0) ; +#ifndef OPENSSL_NO_RSA + else if (alg_a & SSL_aRSA) + pkey=X509_get_pubkey(s->session->sess_cert->peer_pkeys[SSL_PKEY_RSA_ENC].x509); +#endif +#ifndef OPENSSL_NO_ECDSA + else if (alg_a & SSL_aECDSA) + pkey=X509_get_pubkey(s->session->sess_cert->peer_pkeys[SSL_PKEY_ECC].x509); +#endif + /* else anonymous ECDH, so no certificate or pkey. */ + EC_KEY_set_public_key(ecdh, srvr_ecpoint); + s->session->sess_cert->peer_ecdh_tmp=ecdh; + ecdh=NULL; + BN_CTX_free(bn_ctx); + bn_ctx = NULL; + EC_POINT_free(srvr_ecpoint); + srvr_ecpoint = NULL; + } + else if (alg_k) + { + al=SSL_AD_UNEXPECTED_MESSAGE; + SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_UNEXPECTED_MESSAGE); + goto f_err; + } +#endif /* !OPENSSL_NO_ECDH */ + + + /* p points to the next byte, there are 'n' bytes left */ + + /* if it was signed, check the signature */ + if (pkey != NULL) + { + n2s(p,i); + n-=2; + j=EVP_PKEY_size(pkey); + + if ((i != n) || (n > j) || (n <= 0)) + { + /* wrong packet length */ + al=SSL_AD_DECODE_ERROR; + SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_WRONG_SIGNATURE_LENGTH); + goto f_err; + } + +#ifndef OPENSSL_NO_RSA + if (pkey->type == EVP_PKEY_RSA) + { + int num; + + j=0; + q=md_buf; + for (num=2; num > 0; num--) + { + EVP_DigestInit_ex(&md_ctx,(num == 2) + ?s->ctx->md5:s->ctx->sha1, NULL); + EVP_DigestUpdate(&md_ctx,&(s->s3->client_random[0]),SSL3_RANDOM_SIZE); + EVP_DigestUpdate(&md_ctx,&(s->s3->server_random[0]),SSL3_RANDOM_SIZE); + EVP_DigestUpdate(&md_ctx,param,param_len); + EVP_DigestFinal_ex(&md_ctx,q,(unsigned int *)&i); + q+=i; + j+=i; + } + i=RSA_verify(NID_md5_sha1, md_buf, j, p, n, + pkey->pkey.rsa); + if (i < 0) + { + al=SSL_AD_DECRYPT_ERROR; + SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_RSA_DECRYPT); + goto f_err; + } + if (i == 0) + { + /* bad signature */ + al=SSL_AD_DECRYPT_ERROR; + SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_SIGNATURE); + goto f_err; + } + } + else +#endif +#ifndef OPENSSL_NO_DSA + if (pkey->type == EVP_PKEY_DSA) + { + /* lets do DSS */ + EVP_VerifyInit_ex(&md_ctx,EVP_dss1(), NULL); + EVP_VerifyUpdate(&md_ctx,&(s->s3->client_random[0]),SSL3_RANDOM_SIZE); + EVP_VerifyUpdate(&md_ctx,&(s->s3->server_random[0]),SSL3_RANDOM_SIZE); + EVP_VerifyUpdate(&md_ctx,param,param_len); + if (EVP_VerifyFinal(&md_ctx,p,(int)n,pkey) <= 0) + { + /* bad signature */ + al=SSL_AD_DECRYPT_ERROR; + SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_SIGNATURE); + goto f_err; + } + } + else +#endif +#ifndef OPENSSL_NO_ECDSA + if (pkey->type == EVP_PKEY_EC) + { + /* let's do ECDSA */ + EVP_VerifyInit_ex(&md_ctx,EVP_ecdsa(), NULL); + EVP_VerifyUpdate(&md_ctx,&(s->s3->client_random[0]),SSL3_RANDOM_SIZE); + EVP_VerifyUpdate(&md_ctx,&(s->s3->server_random[0]),SSL3_RANDOM_SIZE); + EVP_VerifyUpdate(&md_ctx,param,param_len); + if (EVP_VerifyFinal(&md_ctx,p,(int)n,pkey) <= 0) + { + /* bad signature */ + al=SSL_AD_DECRYPT_ERROR; + SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_SIGNATURE); + goto f_err; + } + } + else +#endif + { + SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_INTERNAL_ERROR); + goto err; + } + } + else + { + if (!(alg_a & SSL_aNULL) && !(alg_k & SSL_kPSK)) + /* aNULL or kPSK do not need public keys */ + { + SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_INTERNAL_ERROR); + goto err; + } + /* still data left over */ + if (n != 0) + { + al=SSL_AD_DECODE_ERROR; + SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_EXTRA_DATA_IN_MESSAGE); + goto f_err; + } + } + EVP_PKEY_free(pkey); + EVP_MD_CTX_cleanup(&md_ctx); + return(1); +f_err: + ssl3_send_alert(s,SSL3_AL_FATAL,al); +err: + EVP_PKEY_free(pkey); +#ifndef OPENSSL_NO_RSA + if (rsa != NULL) + RSA_free(rsa); +#endif +#ifndef OPENSSL_NO_DH + if (dh != NULL) + DH_free(dh); +#endif +#ifndef OPENSSL_NO_ECDH + BN_CTX_free(bn_ctx); + EC_POINT_free(srvr_ecpoint); + if (ecdh != NULL) + EC_KEY_free(ecdh); +#endif + EVP_MD_CTX_cleanup(&md_ctx); + return(-1); + } + +int ssl3_get_certificate_request(SSL *s) + { + int ok,ret=0; + unsigned long n,nc,l; + unsigned int llen,ctype_num,i; + X509_NAME *xn=NULL; + const unsigned char *p,*q; + unsigned char *d; + STACK_OF(X509_NAME) *ca_sk=NULL; + + n=s->method->ssl_get_message(s, + SSL3_ST_CR_CERT_REQ_A, + SSL3_ST_CR_CERT_REQ_B, + -1, + s->max_cert_list, + &ok); + + if (!ok) return((int)n); + + s->s3->tmp.cert_req=0; + + if (s->s3->tmp.message_type == SSL3_MT_SERVER_DONE) + { + s->s3->tmp.reuse_message=1; + return(1); + } + + if (s->s3->tmp.message_type != SSL3_MT_CERTIFICATE_REQUEST) + { + ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_UNEXPECTED_MESSAGE); + SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST,SSL_R_WRONG_MESSAGE_TYPE); + goto err; + } + + /* TLS does not like anon-DH with client cert */ + if (s->version > SSL3_VERSION) + { + if (s->s3->tmp.new_cipher->algorithm_auth & SSL_aNULL) + { + ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_UNEXPECTED_MESSAGE); + SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST,SSL_R_TLS_CLIENT_CERT_REQ_WITH_ANON_CIPHER); + goto err; + } + } + + p=d=(unsigned char *)s->init_msg; + + if ((ca_sk=sk_X509_NAME_new(ca_dn_cmp)) == NULL) + { + SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST,ERR_R_MALLOC_FAILURE); + goto err; + } + + /* get the certificate types */ + ctype_num= *(p++); + if (ctype_num > SSL3_CT_NUMBER) + ctype_num=SSL3_CT_NUMBER; + for (i=0; is3->tmp.ctype[i]= p[i]; + p+=ctype_num; + + /* get the CA RDNs */ + n2s(p,llen); +#if 0 +{ +FILE *out; +out=fopen("/tmp/vsign.der","w"); +fwrite(p,1,llen,out); +fclose(out); +} +#endif + + if ((llen+ctype_num+2+1) != n) + { + ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_DECODE_ERROR); + SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST,SSL_R_LENGTH_MISMATCH); + goto err; + } + + for (nc=0; nc llen) + { + if ((s->options & SSL_OP_NETSCAPE_CA_DN_BUG)) + goto cont; /* netscape bugs */ + ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_DECODE_ERROR); + SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST,SSL_R_CA_DN_TOO_LONG); + goto err; + } + + q=p; + + if ((xn=d2i_X509_NAME(NULL,&q,l)) == NULL) + { + /* If netscape tolerance is on, ignore errors */ + if (s->options & SSL_OP_NETSCAPE_CA_DN_BUG) + goto cont; + else + { + ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_DECODE_ERROR); + SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST,ERR_R_ASN1_LIB); + goto err; + } + } + + if (q != (p+l)) + { + ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_DECODE_ERROR); + SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST,SSL_R_CA_DN_LENGTH_MISMATCH); + goto err; + } + if (!sk_X509_NAME_push(ca_sk,xn)) + { + SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST,ERR_R_MALLOC_FAILURE); + goto err; + } + + p+=l; + nc+=l+2; + } + + if (0) + { +cont: + ERR_clear_error(); + } + + /* we should setup a certificate to return.... */ + s->s3->tmp.cert_req=1; + s->s3->tmp.ctype_num=ctype_num; + if (s->s3->tmp.ca_names != NULL) + sk_X509_NAME_pop_free(s->s3->tmp.ca_names,X509_NAME_free); + s->s3->tmp.ca_names=ca_sk; + ca_sk=NULL; + + ret=1; +err: + if (ca_sk != NULL) sk_X509_NAME_pop_free(ca_sk,X509_NAME_free); + return(ret); + } + +static int ca_dn_cmp(const X509_NAME * const *a, const X509_NAME * const *b) + { + return(X509_NAME_cmp(*a,*b)); + } +#ifndef OPENSSL_NO_TLSEXT +int ssl3_get_new_session_ticket(SSL *s) + { + int ok,al,ret=0, ticklen; + long n; + const unsigned char *p; + unsigned char *d; + + n=s->method->ssl_get_message(s, + SSL3_ST_CR_SESSION_TICKET_A, + SSL3_ST_CR_SESSION_TICKET_B, + -1, + 16384, + &ok); + + if (!ok) + return((int)n); + + if (s->s3->tmp.message_type == SSL3_MT_FINISHED) + { + s->s3->tmp.reuse_message=1; + return(1); + } + if (s->s3->tmp.message_type != SSL3_MT_NEWSESSION_TICKET) + { + al=SSL_AD_UNEXPECTED_MESSAGE; + SSLerr(SSL_F_SSL3_GET_NEW_SESSION_TICKET,SSL_R_BAD_MESSAGE_TYPE); + goto f_err; + } + if (n < 6) + { + /* need at least ticket_lifetime_hint + ticket length */ + al = SSL_AD_DECODE_ERROR; + SSLerr(SSL_F_SSL3_GET_NEW_SESSION_TICKET,SSL_R_LENGTH_MISMATCH); + goto f_err; + } + + p=d=(unsigned char *)s->init_msg; + n2l(p, s->session->tlsext_tick_lifetime_hint); + n2s(p, ticklen); + /* ticket_lifetime_hint + ticket_length + ticket */ + if (ticklen + 6 != n) + { + al = SSL_AD_DECODE_ERROR; + SSLerr(SSL_F_SSL3_GET_NEW_SESSION_TICKET,SSL_R_LENGTH_MISMATCH); + goto f_err; + } + if (s->session->tlsext_tick) + { + OPENSSL_free(s->session->tlsext_tick); + s->session->tlsext_ticklen = 0; + } + s->session->tlsext_tick = OPENSSL_malloc(ticklen); + if (!s->session->tlsext_tick) + { + SSLerr(SSL_F_SSL3_GET_NEW_SESSION_TICKET,ERR_R_MALLOC_FAILURE); + goto err; + } + memcpy(s->session->tlsext_tick, p, ticklen); + s->session->tlsext_ticklen = ticklen; + /* There are two ways to detect a resumed ticket sesion. + * One is to set an appropriate session ID and then the server + * must return a match in ServerHello. This allows the normal + * client session ID matching to work and we know much + * earlier that the ticket has been accepted. + * + * The other way is to set zero length session ID when the + * ticket is presented and rely on the handshake to determine + * session resumption. + * + * We choose the former approach because this fits in with + * assumptions elsewhere in OpenSSL. The session ID is set + * to the SHA256 (or SHA1 is SHA256 is disabled) hash of the + * ticket. + */ + EVP_Digest(p, ticklen, + s->session->session_id, &s->session->session_id_length, +#ifndef OPENSSL_NO_SHA256 + EVP_sha256(), NULL); +#else + EVP_sha1(), NULL); +#endif + ret=1; + return(ret); +f_err: + ssl3_send_alert(s,SSL3_AL_FATAL,al); +err: + return(-1); + } + +int ssl3_get_cert_status(SSL *s) + { + int ok, al; + unsigned long resplen,n; + const unsigned char *p; + + n=s->method->ssl_get_message(s, + SSL3_ST_CR_CERT_STATUS_A, + SSL3_ST_CR_CERT_STATUS_B, + SSL3_MT_CERTIFICATE_STATUS, + 16384, + &ok); + + if (!ok) return((int)n); + if (n < 4) + { + /* need at least status type + length */ + al = SSL_AD_DECODE_ERROR; + SSLerr(SSL_F_SSL3_GET_CERT_STATUS,SSL_R_LENGTH_MISMATCH); + goto f_err; + } + p = (unsigned char *)s->init_msg; + if (*p++ != TLSEXT_STATUSTYPE_ocsp) + { + al = SSL_AD_DECODE_ERROR; + SSLerr(SSL_F_SSL3_GET_CERT_STATUS,SSL_R_UNSUPPORTED_STATUS_TYPE); + goto f_err; + } + n2l3(p, resplen); + if (resplen + 4 != n) + { + al = SSL_AD_DECODE_ERROR; + SSLerr(SSL_F_SSL3_GET_CERT_STATUS,SSL_R_LENGTH_MISMATCH); + goto f_err; + } + if (s->tlsext_ocsp_resp) + OPENSSL_free(s->tlsext_ocsp_resp); + s->tlsext_ocsp_resp = BUF_memdup(p, resplen); + if (!s->tlsext_ocsp_resp) + { + al = SSL_AD_INTERNAL_ERROR; + SSLerr(SSL_F_SSL3_GET_CERT_STATUS,ERR_R_MALLOC_FAILURE); + goto f_err; + } + s->tlsext_ocsp_resplen = resplen; + if (s->ctx->tlsext_status_cb) + { + int ret; + ret = s->ctx->tlsext_status_cb(s, s->ctx->tlsext_status_arg); + if (ret == 0) + { + al = SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE; + SSLerr(SSL_F_SSL3_GET_CERT_STATUS,SSL_R_INVALID_STATUS_RESPONSE); + goto f_err; + } + if (ret < 0) + { + al = SSL_AD_INTERNAL_ERROR; + SSLerr(SSL_F_SSL3_GET_CERT_STATUS,ERR_R_MALLOC_FAILURE); + goto f_err; + } + } + return 1; +f_err: + ssl3_send_alert(s,SSL3_AL_FATAL,al); + return(-1); + } +#endif + +int ssl3_get_server_done(SSL *s) + { + int ok,ret=0; + long n; + + n=s->method->ssl_get_message(s, + SSL3_ST_CR_SRVR_DONE_A, + SSL3_ST_CR_SRVR_DONE_B, + SSL3_MT_SERVER_DONE, + 30, /* should be very small, like 0 :-) */ + &ok); + + if (!ok) return((int)n); + if (n > 0) + { + /* should contain no data */ + ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_DECODE_ERROR); + SSLerr(SSL_F_SSL3_GET_SERVER_DONE,SSL_R_LENGTH_MISMATCH); + return -1; + } + ret=1; + return(ret); + } + + +int ssl3_send_client_key_exchange(SSL *s) + { + unsigned char *p,*d; + int n; + unsigned long alg_k; +#ifndef OPENSSL_NO_RSA + unsigned char *q; + EVP_PKEY *pkey=NULL; +#endif +#ifndef OPENSSL_NO_KRB5 + KSSL_ERR kssl_err; +#endif /* OPENSSL_NO_KRB5 */ +#ifndef OPENSSL_NO_ECDH + EC_KEY *clnt_ecdh = NULL; + const EC_POINT *srvr_ecpoint = NULL; + EVP_PKEY *srvr_pub_pkey = NULL; + unsigned char *encodedPoint = NULL; + int encoded_pt_len = 0; + BN_CTX * bn_ctx = NULL; +#endif + + if (s->state == SSL3_ST_CW_KEY_EXCH_A) + { + d=(unsigned char *)s->init_buf->data; + p= &(d[4]); + + alg_k=s->s3->tmp.new_cipher->algorithm_mkey; + + /* Fool emacs indentation */ + if (0) {} +#ifndef OPENSSL_NO_RSA + else if (alg_k & SSL_kRSA) + { + RSA *rsa; + unsigned char tmp_buf[SSL_MAX_MASTER_KEY_LENGTH]; + + if (s->session->sess_cert->peer_rsa_tmp != NULL) + rsa=s->session->sess_cert->peer_rsa_tmp; + else + { + pkey=X509_get_pubkey(s->session->sess_cert->peer_pkeys[SSL_PKEY_RSA_ENC].x509); + if ((pkey == NULL) || + (pkey->type != EVP_PKEY_RSA) || + (pkey->pkey.rsa == NULL)) + { + SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,ERR_R_INTERNAL_ERROR); + goto err; + } + rsa=pkey->pkey.rsa; + EVP_PKEY_free(pkey); + } + + tmp_buf[0]=s->client_version>>8; + tmp_buf[1]=s->client_version&0xff; + if (RAND_bytes(&(tmp_buf[2]),sizeof tmp_buf-2) <= 0) + goto err; + + s->session->master_key_length=sizeof tmp_buf; + + q=p; + /* Fix buf for TLS and beyond */ + if (s->version > SSL3_VERSION) + p+=2; + n=RSA_public_encrypt(sizeof tmp_buf, + tmp_buf,p,rsa,RSA_PKCS1_PADDING); +#ifdef PKCS1_CHECK + if (s->options & SSL_OP_PKCS1_CHECK_1) p[1]++; + if (s->options & SSL_OP_PKCS1_CHECK_2) tmp_buf[0]=0x70; +#endif + if (n <= 0) + { + SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,SSL_R_BAD_RSA_ENCRYPT); + goto err; + } + + /* Fix buf for TLS and beyond */ + if (s->version > SSL3_VERSION) + { + s2n(n,q); + n+=2; + } + + s->session->master_key_length= + s->method->ssl3_enc->generate_master_secret(s, + s->session->master_key, + tmp_buf,sizeof tmp_buf); + OPENSSL_cleanse(tmp_buf,sizeof tmp_buf); + } +#endif +#ifndef OPENSSL_NO_KRB5 + else if (alg_k & SSL_kKRB5) + { + krb5_error_code krb5rc; + KSSL_CTX *kssl_ctx = s->kssl_ctx; + /* krb5_data krb5_ap_req; */ + krb5_data *enc_ticket; + krb5_data authenticator, *authp = NULL; + EVP_CIPHER_CTX ciph_ctx; + const EVP_CIPHER *enc = NULL; + unsigned char iv[EVP_MAX_IV_LENGTH]; + unsigned char tmp_buf[SSL_MAX_MASTER_KEY_LENGTH]; + unsigned char epms[SSL_MAX_MASTER_KEY_LENGTH + + EVP_MAX_IV_LENGTH]; + int padl, outl = sizeof(epms); + + EVP_CIPHER_CTX_init(&ciph_ctx); + +#ifdef KSSL_DEBUG + printf("ssl3_send_client_key_exchange(%lx & %lx)\n", + alg_k, SSL_kKRB5); +#endif /* KSSL_DEBUG */ + + authp = NULL; +#ifdef KRB5SENDAUTH + if (KRB5SENDAUTH) authp = &authenticator; +#endif /* KRB5SENDAUTH */ + + krb5rc = kssl_cget_tkt(kssl_ctx, &enc_ticket, authp, + &kssl_err); + enc = kssl_map_enc(kssl_ctx->enctype); + if (enc == NULL) + goto err; +#ifdef KSSL_DEBUG + { + printf("kssl_cget_tkt rtn %d\n", krb5rc); + if (krb5rc && kssl_err.text) + printf("kssl_cget_tkt kssl_err=%s\n", kssl_err.text); + } +#endif /* KSSL_DEBUG */ + + if (krb5rc) + { + ssl3_send_alert(s,SSL3_AL_FATAL, + SSL_AD_HANDSHAKE_FAILURE); + SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, + kssl_err.reason); + goto err; + } + + /* 20010406 VRS - Earlier versions used KRB5 AP_REQ + ** in place of RFC 2712 KerberosWrapper, as in: + ** + ** Send ticket (copy to *p, set n = length) + ** n = krb5_ap_req.length; + ** memcpy(p, krb5_ap_req.data, krb5_ap_req.length); + ** if (krb5_ap_req.data) + ** kssl_krb5_free_data_contents(NULL,&krb5_ap_req); + ** + ** Now using real RFC 2712 KerberosWrapper + ** (Thanks to Simon Wilkinson ) + ** Note: 2712 "opaque" types are here replaced + ** with a 2-byte length followed by the value. + ** Example: + ** KerberosWrapper= xx xx asn1ticket 0 0 xx xx encpms + ** Where "xx xx" = length bytes. Shown here with + ** optional authenticator omitted. + */ + + /* KerberosWrapper.Ticket */ + s2n(enc_ticket->length,p); + memcpy(p, enc_ticket->data, enc_ticket->length); + p+= enc_ticket->length; + n = enc_ticket->length + 2; + + /* KerberosWrapper.Authenticator */ + if (authp && authp->length) + { + s2n(authp->length,p); + memcpy(p, authp->data, authp->length); + p+= authp->length; + n+= authp->length + 2; + + free(authp->data); + authp->data = NULL; + authp->length = 0; + } + else + { + s2n(0,p);/* null authenticator length */ + n+=2; + } + + tmp_buf[0]=s->client_version>>8; + tmp_buf[1]=s->client_version&0xff; + if (RAND_bytes(&(tmp_buf[2]),sizeof tmp_buf-2) <= 0) + goto err; + + /* 20010420 VRS. Tried it this way; failed. + ** EVP_EncryptInit_ex(&ciph_ctx,enc, NULL,NULL); + ** EVP_CIPHER_CTX_set_key_length(&ciph_ctx, + ** kssl_ctx->length); + ** EVP_EncryptInit_ex(&ciph_ctx,NULL, key,iv); + */ + + memset(iv, 0, sizeof iv); /* per RFC 1510 */ + EVP_EncryptInit_ex(&ciph_ctx,enc, NULL, + kssl_ctx->key,iv); + EVP_EncryptUpdate(&ciph_ctx,epms,&outl,tmp_buf, + sizeof tmp_buf); + EVP_EncryptFinal_ex(&ciph_ctx,&(epms[outl]),&padl); + outl += padl; + if (outl > (int)sizeof epms) + { + SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR); + goto err; + } + EVP_CIPHER_CTX_cleanup(&ciph_ctx); + + /* KerberosWrapper.EncryptedPreMasterSecret */ + s2n(outl,p); + memcpy(p, epms, outl); + p+=outl; + n+=outl + 2; + + s->session->master_key_length= + s->method->ssl3_enc->generate_master_secret(s, + s->session->master_key, + tmp_buf, sizeof tmp_buf); + + OPENSSL_cleanse(tmp_buf, sizeof tmp_buf); + OPENSSL_cleanse(epms, outl); + } +#endif +#ifndef OPENSSL_NO_DH + else if (alg_k & (SSL_kEDH|SSL_kDHr|SSL_kDHd)) + { + DH *dh_srvr,*dh_clnt; + + if (s->session->sess_cert == NULL) + { + ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_UNEXPECTED_MESSAGE); + SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,SSL_R_UNEXPECTED_MESSAGE); + goto err; + } + + if (s->session->sess_cert->peer_dh_tmp != NULL) + dh_srvr=s->session->sess_cert->peer_dh_tmp; + else + { + /* we get them from the cert */ + ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_HANDSHAKE_FAILURE); + SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,SSL_R_UNABLE_TO_FIND_DH_PARAMETERS); + goto err; + } + + /* generate a new random key */ + if ((dh_clnt=DHparams_dup(dh_srvr)) == NULL) + { + SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,ERR_R_DH_LIB); + goto err; + } + if (!DH_generate_key(dh_clnt)) + { + SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,ERR_R_DH_LIB); + DH_free(dh_clnt); + goto err; + } + + /* use the 'p' output buffer for the DH key, but + * make sure to clear it out afterwards */ + + n=DH_compute_key(p,dh_srvr->pub_key,dh_clnt); + + if (n <= 0) + { + SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,ERR_R_DH_LIB); + DH_free(dh_clnt); + goto err; + } + + /* generate master key from the result */ + s->session->master_key_length= + s->method->ssl3_enc->generate_master_secret(s, + s->session->master_key,p,n); + /* clean up */ + memset(p,0,n); + + /* send off the data */ + n=BN_num_bytes(dh_clnt->pub_key); + s2n(n,p); + BN_bn2bin(dh_clnt->pub_key,p); + n+=2; + + DH_free(dh_clnt); + + /* perhaps clean things up a bit EAY EAY EAY EAY*/ + } +#endif + +#ifndef OPENSSL_NO_ECDH + else if (alg_k & (SSL_kEECDH|SSL_kECDHr|SSL_kECDHe)) + { + const EC_GROUP *srvr_group = NULL; + EC_KEY *tkey; + int ecdh_clnt_cert = 0; + int field_size = 0; + + /* Did we send out the client's + * ECDH share for use in premaster + * computation as part of client certificate? + * If so, set ecdh_clnt_cert to 1. + */ + if ((alg_k & (SSL_kECDHr|SSL_kECDHe)) && (s->cert != NULL)) + { + /* XXX: For now, we do not support client + * authentication using ECDH certificates. + * To add such support, one needs to add + * code that checks for appropriate + * conditions and sets ecdh_clnt_cert to 1. + * For example, the cert have an ECC + * key on the same curve as the server's + * and the key should be authorized for + * key agreement. + * + * One also needs to add code in ssl3_connect + * to skip sending the certificate verify + * message. + * + * if ((s->cert->key->privatekey != NULL) && + * (s->cert->key->privatekey->type == + * EVP_PKEY_EC) && ...) + * ecdh_clnt_cert = 1; + */ + } + + if (s->session->sess_cert->peer_ecdh_tmp != NULL) + { + tkey = s->session->sess_cert->peer_ecdh_tmp; + } + else + { + /* Get the Server Public Key from Cert */ + srvr_pub_pkey = X509_get_pubkey(s->session-> \ + sess_cert->peer_pkeys[SSL_PKEY_ECC].x509); + if ((srvr_pub_pkey == NULL) || + (srvr_pub_pkey->type != EVP_PKEY_EC) || + (srvr_pub_pkey->pkey.ec == NULL)) + { + SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, + ERR_R_INTERNAL_ERROR); + goto err; + } + + tkey = srvr_pub_pkey->pkey.ec; + } + + srvr_group = EC_KEY_get0_group(tkey); + srvr_ecpoint = EC_KEY_get0_public_key(tkey); + + if ((srvr_group == NULL) || (srvr_ecpoint == NULL)) + { + SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, + ERR_R_INTERNAL_ERROR); + goto err; + } + + if ((clnt_ecdh=EC_KEY_new()) == NULL) + { + SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,ERR_R_MALLOC_FAILURE); + goto err; + } + + if (!EC_KEY_set_group(clnt_ecdh, srvr_group)) + { + SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,ERR_R_EC_LIB); + goto err; + } + if (ecdh_clnt_cert) + { + /* Reuse key info from our certificate + * We only need our private key to perform + * the ECDH computation. + */ + const BIGNUM *priv_key; + tkey = s->cert->key->privatekey->pkey.ec; + priv_key = EC_KEY_get0_private_key(tkey); + if (priv_key == NULL) + { + SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,ERR_R_MALLOC_FAILURE); + goto err; + } + if (!EC_KEY_set_private_key(clnt_ecdh, priv_key)) + { + SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,ERR_R_EC_LIB); + goto err; + } + } + else + { + /* Generate a new ECDH key pair */ + if (!(EC_KEY_generate_key(clnt_ecdh))) + { + SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, ERR_R_ECDH_LIB); + goto err; + } + } + + /* use the 'p' output buffer for the ECDH key, but + * make sure to clear it out afterwards + */ + + field_size = EC_GROUP_get_degree(srvr_group); + if (field_size <= 0) + { + SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, + ERR_R_ECDH_LIB); + goto err; + } + n=ECDH_compute_key(p, (field_size+7)/8, srvr_ecpoint, clnt_ecdh, NULL); + if (n <= 0) + { + SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, + ERR_R_ECDH_LIB); + goto err; + } + + /* generate master key from the result */ + s->session->master_key_length = s->method->ssl3_enc \ + -> generate_master_secret(s, + s->session->master_key, + p, n); + + memset(p, 0, n); /* clean up */ + + if (ecdh_clnt_cert) + { + /* Send empty client key exch message */ + n = 0; + } + else + { + /* First check the size of encoding and + * allocate memory accordingly. + */ + encoded_pt_len = + EC_POINT_point2oct(srvr_group, + EC_KEY_get0_public_key(clnt_ecdh), + POINT_CONVERSION_UNCOMPRESSED, + NULL, 0, NULL); + + encodedPoint = (unsigned char *) + OPENSSL_malloc(encoded_pt_len * + sizeof(unsigned char)); + bn_ctx = BN_CTX_new(); + if ((encodedPoint == NULL) || + (bn_ctx == NULL)) + { + SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,ERR_R_MALLOC_FAILURE); + goto err; + } + + /* Encode the public key */ + n = EC_POINT_point2oct(srvr_group, + EC_KEY_get0_public_key(clnt_ecdh), + POINT_CONVERSION_UNCOMPRESSED, + encodedPoint, encoded_pt_len, bn_ctx); + + *p = n; /* length of encoded point */ + /* Encoded point will be copied here */ + p += 1; + /* copy the point */ + memcpy((unsigned char *)p, encodedPoint, n); + /* increment n to account for length field */ + n += 1; + } + + /* Free allocated memory */ + BN_CTX_free(bn_ctx); + if (encodedPoint != NULL) OPENSSL_free(encodedPoint); + if (clnt_ecdh != NULL) + EC_KEY_free(clnt_ecdh); + EVP_PKEY_free(srvr_pub_pkey); + } +#endif /* !OPENSSL_NO_ECDH */ + else if (alg_k & SSL_kGOST) + { + /* GOST key exchange message creation */ + EVP_PKEY_CTX *pkey_ctx; + X509 *peer_cert; + size_t msglen; + unsigned int md_len; + int keytype; + unsigned char premaster_secret[32],shared_ukm[32], tmp[256]; + EVP_MD_CTX *ukm_hash; + EVP_PKEY *pub_key; + + /* Get server sertificate PKEY and create ctx from it */ + peer_cert=s->session->sess_cert->peer_pkeys[(keytype=SSL_PKEY_GOST01)].x509; + if (!peer_cert) + peer_cert=s->session->sess_cert->peer_pkeys[(keytype=SSL_PKEY_GOST94)].x509; + if (!peer_cert) { + SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,SSL_R_NO_GOST_CERTIFICATE_SENT_BY_PEER); + goto err; + } + + pkey_ctx=EVP_PKEY_CTX_new(pub_key=X509_get_pubkey(peer_cert),NULL); + /* If we have send a certificate, and certificate key + + * parameters match those of server certificate, use + * certificate key for key exchange + */ + + /* Otherwise, generate ephemeral key pair */ + + EVP_PKEY_encrypt_init(pkey_ctx); + /* Generate session key */ + RAND_bytes(premaster_secret,32); + /* If we have client certificate, use its secret as peer key */ + if (s->s3->tmp.cert_req && s->cert->key->privatekey) { + if (EVP_PKEY_derive_set_peer(pkey_ctx,s->cert->key->privatekey) <=0) { + /* If there was an error - just ignore it. Ephemeral key + * would be used + */ + ERR_clear_error(); + } + } + /* Compute shared IV and store it in algorithm-specific + * context data */ + ukm_hash = EVP_MD_CTX_create(); + EVP_DigestInit(ukm_hash,EVP_get_digestbynid(NID_id_GostR3411_94)); + EVP_DigestUpdate(ukm_hash,s->s3->client_random,SSL3_RANDOM_SIZE); + EVP_DigestUpdate(ukm_hash,s->s3->server_random,SSL3_RANDOM_SIZE); + EVP_DigestFinal_ex(ukm_hash, shared_ukm, &md_len); + EVP_MD_CTX_destroy(ukm_hash); + if (EVP_PKEY_CTX_ctrl(pkey_ctx,-1,EVP_PKEY_OP_ENCRYPT,EVP_PKEY_CTRL_SET_IV, + 8,shared_ukm)<0) { + SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, + SSL_R_LIBRARY_BUG); + goto err; + } + /* Make GOST keytransport blob message */ + /*Encapsulate it into sequence */ + *(p++)=V_ASN1_SEQUENCE | V_ASN1_CONSTRUCTED; + msglen=255; + if (EVP_PKEY_encrypt(pkey_ctx,tmp,&msglen,premaster_secret,32)<0) { + SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, + SSL_R_LIBRARY_BUG); + goto err; + } + if (msglen >= 0x80) + { + *(p++)=0x81; + *(p++)= msglen & 0xff; + n=msglen+3; + } + else + { + *(p++)= msglen & 0xff; + n=msglen+2; + } + memcpy(p, tmp, msglen); + /* Check if pubkey from client certificate was used */ + if (EVP_PKEY_CTX_ctrl(pkey_ctx, -1, -1, EVP_PKEY_CTRL_PEER_KEY, 2, NULL) > 0) + { + /* Set flag "skip certificate verify" */ + s->s3->flags |= TLS1_FLAGS_SKIP_CERT_VERIFY; + } + EVP_PKEY_CTX_free(pkey_ctx); + s->session->master_key_length= + s->method->ssl3_enc->generate_master_secret(s, + s->session->master_key,premaster_secret,32); + EVP_PKEY_free(pub_key); + + } +#ifndef OPENSSL_NO_PSK + else if (alg_k & SSL_kPSK) + { + char identity[PSK_MAX_IDENTITY_LEN]; + unsigned char *t = NULL; + unsigned char psk_or_pre_ms[PSK_MAX_PSK_LEN*2+4]; + unsigned int pre_ms_len = 0, psk_len = 0; + int psk_err = 1; + + n = 0; + if (s->psk_client_callback == NULL) + { + SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, + SSL_R_PSK_NO_CLIENT_CB); + goto err; + } + + psk_len = s->psk_client_callback(s, s->ctx->psk_identity_hint, + identity, PSK_MAX_IDENTITY_LEN, + psk_or_pre_ms, sizeof(psk_or_pre_ms)); + if (psk_len > PSK_MAX_PSK_LEN) + { + SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, + ERR_R_INTERNAL_ERROR); + goto psk_err; + } + else if (psk_len == 0) + { + SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, + SSL_R_PSK_IDENTITY_NOT_FOUND); + goto psk_err; + } + + /* create PSK pre_master_secret */ + pre_ms_len = 2+psk_len+2+psk_len; + t = psk_or_pre_ms; + memmove(psk_or_pre_ms+psk_len+4, psk_or_pre_ms, psk_len); + s2n(psk_len, t); + memset(t, 0, psk_len); + t+=psk_len; + s2n(psk_len, t); + + if (s->session->psk_identity_hint != NULL) + OPENSSL_free(s->session->psk_identity_hint); + s->session->psk_identity_hint = BUF_strdup(s->ctx->psk_identity_hint); + if (s->ctx->psk_identity_hint != NULL && + s->session->psk_identity_hint == NULL) + { + SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, + ERR_R_MALLOC_FAILURE); + goto psk_err; + } + + if (s->session->psk_identity != NULL) + OPENSSL_free(s->session->psk_identity); + s->session->psk_identity = BUF_strdup(identity); + if (s->session->psk_identity == NULL) + { + SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, + ERR_R_MALLOC_FAILURE); + goto psk_err; + } + + s->session->master_key_length = + s->method->ssl3_enc->generate_master_secret(s, + s->session->master_key, + psk_or_pre_ms, pre_ms_len); + n = strlen(identity); + s2n(n, p); + memcpy(p, identity, n); + n+=2; + psk_err = 0; + psk_err: + OPENSSL_cleanse(identity, PSK_MAX_IDENTITY_LEN); + OPENSSL_cleanse(psk_or_pre_ms, sizeof(psk_or_pre_ms)); + if (psk_err != 0) + { + ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE); + goto err; + } + } +#endif + else + { + ssl3_send_alert(s, SSL3_AL_FATAL, + SSL_AD_HANDSHAKE_FAILURE); + SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, + ERR_R_INTERNAL_ERROR); + goto err; + } + + *(d++)=SSL3_MT_CLIENT_KEY_EXCHANGE; + l2n3(n,d); + + s->state=SSL3_ST_CW_KEY_EXCH_B; + /* number of bytes to write */ + s->init_num=n+4; + s->init_off=0; + } + + /* SSL3_ST_CW_KEY_EXCH_B */ + return(ssl3_do_write(s,SSL3_RT_HANDSHAKE)); +err: +#ifndef OPENSSL_NO_ECDH + BN_CTX_free(bn_ctx); + if (encodedPoint != NULL) OPENSSL_free(encodedPoint); + if (clnt_ecdh != NULL) + EC_KEY_free(clnt_ecdh); + EVP_PKEY_free(srvr_pub_pkey); +#endif + return(-1); + } + +int ssl3_send_client_verify(SSL *s) + { + unsigned char *p,*d; + unsigned char data[MD5_DIGEST_LENGTH+SHA_DIGEST_LENGTH]; + EVP_PKEY *pkey; + EVP_PKEY_CTX *pctx=NULL; +#ifndef OPENSSL_NO_RSA + unsigned u=0; +#endif + unsigned long n; + int j; + + if (s->state == SSL3_ST_CW_CERT_VRFY_A) + { + d=(unsigned char *)s->init_buf->data; + p= &(d[4]); + pkey=s->cert->key->privatekey; +/* Create context from key and test if sha1 is allowed as digest */ + pctx = EVP_PKEY_CTX_new(pkey,NULL); + EVP_PKEY_sign_init(pctx); + if (EVP_PKEY_CTX_set_signature_md(pctx, EVP_sha1())>0) + { + s->method->ssl3_enc->cert_verify_mac(s, + NID_sha1, + &(data[MD5_DIGEST_LENGTH])); + } + else + { + ERR_clear_error(); + } +#ifndef OPENSSL_NO_RSA + if (pkey->type == EVP_PKEY_RSA) + { + s->method->ssl3_enc->cert_verify_mac(s, + NID_md5, + &(data[0])); + if (RSA_sign(NID_md5_sha1, data, + MD5_DIGEST_LENGTH+SHA_DIGEST_LENGTH, + &(p[2]), &u, pkey->pkey.rsa) <= 0 ) + { + SSLerr(SSL_F_SSL3_SEND_CLIENT_VERIFY,ERR_R_RSA_LIB); + goto err; + } + s2n(u,p); + n=u+2; + } + else +#endif +#ifndef OPENSSL_NO_DSA + if (pkey->type == EVP_PKEY_DSA) + { + if (!DSA_sign(pkey->save_type, + &(data[MD5_DIGEST_LENGTH]), + SHA_DIGEST_LENGTH,&(p[2]), + (unsigned int *)&j,pkey->pkey.dsa)) + { + SSLerr(SSL_F_SSL3_SEND_CLIENT_VERIFY,ERR_R_DSA_LIB); + goto err; + } + s2n(j,p); + n=j+2; + } + else +#endif +#ifndef OPENSSL_NO_ECDSA + if (pkey->type == EVP_PKEY_EC) + { + if (!ECDSA_sign(pkey->save_type, + &(data[MD5_DIGEST_LENGTH]), + SHA_DIGEST_LENGTH,&(p[2]), + (unsigned int *)&j,pkey->pkey.ec)) + { + SSLerr(SSL_F_SSL3_SEND_CLIENT_VERIFY, + ERR_R_ECDSA_LIB); + goto err; + } + s2n(j,p); + n=j+2; + } + else +#endif + if (pkey->type == NID_id_GostR3410_94 || pkey->type == NID_id_GostR3410_2001) + { + unsigned char signbuf[64]; + int i; + size_t sigsize=64; + s->method->ssl3_enc->cert_verify_mac(s, + NID_id_GostR3411_94, + data); + if (EVP_PKEY_sign(pctx, signbuf, &sigsize, data, 32) <= 0) { + SSLerr(SSL_F_SSL3_SEND_CLIENT_VERIFY, + ERR_R_INTERNAL_ERROR); + goto err; + } + for (i=63,j=0; i>=0; j++, i--) { + p[2+j]=signbuf[i]; + } + s2n(j,p); + n=j+2; + } + else + { + SSLerr(SSL_F_SSL3_SEND_CLIENT_VERIFY,ERR_R_INTERNAL_ERROR); + goto err; + } + *(d++)=SSL3_MT_CERTIFICATE_VERIFY; + l2n3(n,d); + + s->state=SSL3_ST_CW_CERT_VRFY_B; + s->init_num=(int)n+4; + s->init_off=0; + } + EVP_PKEY_CTX_free(pctx); + return(ssl3_do_write(s,SSL3_RT_HANDSHAKE)); +err: + EVP_PKEY_CTX_free(pctx); + return(-1); + } + +int ssl3_send_client_certificate(SSL *s) + { + X509 *x509=NULL; + EVP_PKEY *pkey=NULL; + int i; + unsigned long l; + + if (s->state == SSL3_ST_CW_CERT_A) + { + if ((s->cert == NULL) || + (s->cert->key->x509 == NULL) || + (s->cert->key->privatekey == NULL)) + s->state=SSL3_ST_CW_CERT_B; + else + s->state=SSL3_ST_CW_CERT_C; + } + + /* We need to get a client cert */ + if (s->state == SSL3_ST_CW_CERT_B) + { + /* If we get an error, we need to + * ssl->rwstate=SSL_X509_LOOKUP; return(-1); + * We then get retied later */ + i=0; + i = ssl_do_client_cert_cb(s, &x509, &pkey); + if (i < 0) + { + s->rwstate=SSL_X509_LOOKUP; + return(-1); + } + s->rwstate=SSL_NOTHING; + if ((i == 1) && (pkey != NULL) && (x509 != NULL)) + { + s->state=SSL3_ST_CW_CERT_B; + if ( !SSL_use_certificate(s,x509) || + !SSL_use_PrivateKey(s,pkey)) + i=0; + } + else if (i == 1) + { + i=0; + SSLerr(SSL_F_SSL3_SEND_CLIENT_CERTIFICATE,SSL_R_BAD_DATA_RETURNED_BY_CALLBACK); + } + + if (x509 != NULL) X509_free(x509); + if (pkey != NULL) EVP_PKEY_free(pkey); + if (i == 0) + { + if (s->version == SSL3_VERSION) + { + s->s3->tmp.cert_req=0; + ssl3_send_alert(s,SSL3_AL_WARNING,SSL_AD_NO_CERTIFICATE); + return(1); + } + else + { + s->s3->tmp.cert_req=2; + } + } + + /* Ok, we have a cert */ + s->state=SSL3_ST_CW_CERT_C; + } + + if (s->state == SSL3_ST_CW_CERT_C) + { + s->state=SSL3_ST_CW_CERT_D; + l=ssl3_output_cert_chain(s, + (s->s3->tmp.cert_req == 2)?NULL:s->cert->key->x509); + s->init_num=(int)l; + s->init_off=0; + } + /* SSL3_ST_CW_CERT_D */ + return(ssl3_do_write(s,SSL3_RT_HANDSHAKE)); + } + +#define has_bits(i,m) (((i)&(m)) == (m)) + +int ssl3_check_cert_and_algorithm(SSL *s) + { + int i,idx; + long alg_k,alg_a; + EVP_PKEY *pkey=NULL; + SESS_CERT *sc; +#ifndef OPENSSL_NO_RSA + RSA *rsa; +#endif +#ifndef OPENSSL_NO_DH + DH *dh; +#endif + + alg_k=s->s3->tmp.new_cipher->algorithm_mkey; + alg_a=s->s3->tmp.new_cipher->algorithm_auth; + + /* we don't have a certificate */ + if ((alg_a & (SSL_aDH|SSL_aNULL|SSL_aKRB5)) || (alg_k & SSL_kPSK)) + return(1); + + sc=s->session->sess_cert; + if (sc == NULL) + { + SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,ERR_R_INTERNAL_ERROR); + goto err; + } + +#ifndef OPENSSL_NO_RSA + rsa=s->session->sess_cert->peer_rsa_tmp; +#endif +#ifndef OPENSSL_NO_DH + dh=s->session->sess_cert->peer_dh_tmp; +#endif + + /* This is the passed certificate */ + + idx=sc->peer_cert_type; +#ifndef OPENSSL_NO_ECDH + if (idx == SSL_PKEY_ECC) + { + if (ssl_check_srvr_ecc_cert_and_alg(sc->peer_pkeys[idx].x509, + s->s3->tmp.new_cipher) == 0) + { /* check failed */ + SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,SSL_R_BAD_ECC_CERT); + goto f_err; + } + else + { + return 1; + } + } +#endif + pkey=X509_get_pubkey(sc->peer_pkeys[idx].x509); + i=X509_certificate_type(sc->peer_pkeys[idx].x509,pkey); + EVP_PKEY_free(pkey); + + + /* Check that we have a certificate if we require one */ + if ((alg_a & SSL_aRSA) && !has_bits(i,EVP_PK_RSA|EVP_PKT_SIGN)) + { + SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,SSL_R_MISSING_RSA_SIGNING_CERT); + goto f_err; + } +#ifndef OPENSSL_NO_DSA + else if ((alg_a & SSL_aDSS) && !has_bits(i,EVP_PK_DSA|EVP_PKT_SIGN)) + { + SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,SSL_R_MISSING_DSA_SIGNING_CERT); + goto f_err; + } +#endif +#ifndef OPENSSL_NO_RSA + if ((alg_k & SSL_kRSA) && + !(has_bits(i,EVP_PK_RSA|EVP_PKT_ENC) || (rsa != NULL))) + { + SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,SSL_R_MISSING_RSA_ENCRYPTING_CERT); + goto f_err; + } +#endif +#ifndef OPENSSL_NO_DH + if ((alg_k & SSL_kEDH) && + !(has_bits(i,EVP_PK_DH|EVP_PKT_EXCH) || (dh != NULL))) + { + SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,SSL_R_MISSING_DH_KEY); + goto f_err; + } + else if ((alg_k & SSL_kDHr) && !has_bits(i,EVP_PK_DH|EVP_PKS_RSA)) + { + SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,SSL_R_MISSING_DH_RSA_CERT); + goto f_err; + } +#ifndef OPENSSL_NO_DSA + else if ((alg_k & SSL_kDHd) && !has_bits(i,EVP_PK_DH|EVP_PKS_DSA)) + { + SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,SSL_R_MISSING_DH_DSA_CERT); + goto f_err; + } +#endif +#endif + + if (SSL_C_IS_EXPORT(s->s3->tmp.new_cipher) && !has_bits(i,EVP_PKT_EXP)) + { +#ifndef OPENSSL_NO_RSA + if (alg_k & SSL_kRSA) + { + if (rsa == NULL + || RSA_size(rsa)*8 > SSL_C_EXPORT_PKEYLENGTH(s->s3->tmp.new_cipher)) + { + SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,SSL_R_MISSING_EXPORT_TMP_RSA_KEY); + goto f_err; + } + } + else +#endif +#ifndef OPENSSL_NO_DH + if (alg_k & (SSL_kEDH|SSL_kDHr|SSL_kDHd)) + { + if (dh == NULL + || DH_size(dh)*8 > SSL_C_EXPORT_PKEYLENGTH(s->s3->tmp.new_cipher)) + { + SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,SSL_R_MISSING_EXPORT_TMP_DH_KEY); + goto f_err; + } + } + else +#endif + { + SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,SSL_R_UNKNOWN_KEY_EXCHANGE_TYPE); + goto f_err; + } + } + return(1); +f_err: + ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_HANDSHAKE_FAILURE); +err: + return(0); + } + +/* Check to see if handshake is full or resumed. Usually this is just a + * case of checking to see if a cache hit has occurred. In the case of + * session tickets we have to check the next message to be sure. + */ + +#ifndef OPENSSL_NO_TLSEXT +# ifndef OPENSSL_NO_NEXTPROTONEG +int ssl3_send_next_proto(SSL *s) + { + unsigned int len, padding_len; + unsigned char *d; + + if (s->state == SSL3_ST_CW_NEXT_PROTO_A) + { + len = s->next_proto_negotiated_len; + padding_len = 32 - ((len + 2) % 32); + d = (unsigned char *)s->init_buf->data; + d[4] = len; + memcpy(d + 5, s->next_proto_negotiated, len); + d[5 + len] = padding_len; + memset(d + 6 + len, 0, padding_len); + *(d++)=SSL3_MT_NEXT_PROTO; + l2n3(2 + len + padding_len, d); + s->state = SSL3_ST_CW_NEXT_PROTO_B; + s->init_num = 4 + 2 + len + padding_len; + s->init_off = 0; + } + + return ssl3_do_write(s, SSL3_RT_HANDSHAKE); + } +# endif + +int ssl3_check_finished(SSL *s) + { + int ok; + long n; + /* If we have no ticket it cannot be a resumed session. */ + if (!s->session->tlsext_tick) + return 1; + /* this function is called when we really expect a Certificate + * message, so permit appropriate message length */ + n=s->method->ssl_get_message(s, + SSL3_ST_CR_CERT_A, + SSL3_ST_CR_CERT_B, + -1, + s->max_cert_list, + &ok); + if (!ok) return((int)n); + s->s3->tmp.reuse_message = 1; + if ((s->s3->tmp.message_type == SSL3_MT_FINISHED) + || (s->s3->tmp.message_type == SSL3_MT_NEWSESSION_TICKET)) + return 2; + + return 1; + } +#endif + +int ssl_do_client_cert_cb(SSL *s, X509 **px509, EVP_PKEY **ppkey) + { + int i = 0; +#ifndef OPENSSL_NO_ENGINE + if (s->ctx->client_cert_engine) + { + i = ENGINE_load_ssl_client_cert(s->ctx->client_cert_engine, s, + SSL_get_client_CA_list(s), + px509, ppkey, NULL, NULL, NULL); + if (i != 0) + return i; + } +#endif + if (s->ctx->client_cert_cb) + i = s->ctx->client_cert_cb(s,px509,ppkey); + return i; + } diff --git a/node-v0.8.14/deps/openssl/openssl/ssl/s3_enc.c b/node-v0.8.14/deps/openssl/openssl/ssl/s3_enc.c new file mode 100644 index 0000000..b145970 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/ssl/s3_enc.c @@ -0,0 +1,849 @@ +/* ssl/s3_enc.c */ +/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com) + * All rights reserved. + * + * This package is an SSL implementation written + * by Eric Young (eay@cryptsoft.com). + * The implementation was written so as to conform with Netscapes SSL. + * + * This library is free for commercial and non-commercial use as long as + * the following conditions are aheared to. The following conditions + * apply to all code found in this distribution, be it the RC4, RSA, + * lhash, DES, etc., code; not just the SSL code. The SSL documentation + * included with this distribution is covered by the same copyright terms + * except that the holder is Tim Hudson (tjh@cryptsoft.com). + * + * Copyright remains Eric Young's, and as such any Copyright notices in + * the code are not to be removed. + * If this package is used in a product, Eric Young should be given attribution + * as the author of the parts of the library used. + * This can be in the form of a textual message at program startup or + * in documentation (online or textual) provided with the package. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * "This product includes cryptographic software written by + * Eric Young (eay@cryptsoft.com)" + * The word 'cryptographic' can be left out if the rouines from the library + * being used are not cryptographic related :-). + * 4. If you include any Windows specific code (or a derivative thereof) from + * the apps directory (application code) you must include an acknowledgement: + * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)" + * + * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * + * The licence and distribution terms for any publically available version or + * derivative of this code cannot be changed. i.e. this code cannot simply be + * copied and put under another distribution licence + * [including the GNU Public Licence.] + */ +/* ==================================================================== + * Copyright (c) 1998-2007 The OpenSSL Project. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. All advertising materials mentioning features or use of this + * software must display the following acknowledgment: + * "This product includes software developed by the OpenSSL Project + * for use in the OpenSSL Toolkit. (http://www.openssl.org/)" + * + * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to + * endorse or promote products derived from this software without + * prior written permission. For written permission, please contact + * openssl-core@openssl.org. + * + * 5. Products derived from this software may not be called "OpenSSL" + * nor may "OpenSSL" appear in their names without prior written + * permission of the OpenSSL Project. + * + * 6. Redistributions of any form whatsoever must retain the following + * acknowledgment: + * "This product includes software developed by the OpenSSL Project + * for use in the OpenSSL Toolkit (http://www.openssl.org/)" + * + * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY + * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR + * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, + * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * ==================================================================== + * + * This product includes cryptographic software written by Eric Young + * (eay@cryptsoft.com). This product includes software written by Tim + * Hudson (tjh@cryptsoft.com). + * + */ +/* ==================================================================== + * Copyright 2005 Nokia. All rights reserved. + * + * The portions of the attached software ("Contribution") is developed by + * Nokia Corporation and is licensed pursuant to the OpenSSL open source + * license. + * + * The Contribution, originally written by Mika Kousa and Pasi Eronen of + * Nokia Corporation, consists of the "PSK" (Pre-Shared Key) ciphersuites + * support (see RFC 4279) to OpenSSL. + * + * No patent licenses or other rights except those expressly stated in + * the OpenSSL open source license shall be deemed granted or received + * expressly, by implication, estoppel, or otherwise. + * + * No assurances are provided by Nokia that the Contribution does not + * infringe the patent or other intellectual property rights of any third + * party or that the license provides you with all the necessary rights + * to make use of the Contribution. + * + * THE SOFTWARE IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND. IN + * ADDITION TO THE DISCLAIMERS INCLUDED IN THE LICENSE, NOKIA + * SPECIFICALLY DISCLAIMS ANY LIABILITY FOR CLAIMS BROUGHT BY YOU OR ANY + * OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL PROPERTY RIGHTS OR + * OTHERWISE. + */ + +#include +#include "ssl_locl.h" +#include +#include + +static unsigned char ssl3_pad_1[48]={ + 0x36,0x36,0x36,0x36,0x36,0x36,0x36,0x36, + 0x36,0x36,0x36,0x36,0x36,0x36,0x36,0x36, + 0x36,0x36,0x36,0x36,0x36,0x36,0x36,0x36, + 0x36,0x36,0x36,0x36,0x36,0x36,0x36,0x36, + 0x36,0x36,0x36,0x36,0x36,0x36,0x36,0x36, + 0x36,0x36,0x36,0x36,0x36,0x36,0x36,0x36 }; + +static unsigned char ssl3_pad_2[48]={ + 0x5c,0x5c,0x5c,0x5c,0x5c,0x5c,0x5c,0x5c, + 0x5c,0x5c,0x5c,0x5c,0x5c,0x5c,0x5c,0x5c, + 0x5c,0x5c,0x5c,0x5c,0x5c,0x5c,0x5c,0x5c, + 0x5c,0x5c,0x5c,0x5c,0x5c,0x5c,0x5c,0x5c, + 0x5c,0x5c,0x5c,0x5c,0x5c,0x5c,0x5c,0x5c, + 0x5c,0x5c,0x5c,0x5c,0x5c,0x5c,0x5c,0x5c }; +static int ssl3_handshake_mac(SSL *s, int md_nid, + const char *sender, int len, unsigned char *p); +static int ssl3_generate_key_block(SSL *s, unsigned char *km, int num) + { + EVP_MD_CTX m5; + EVP_MD_CTX s1; + unsigned char buf[16],smd[SHA_DIGEST_LENGTH]; + unsigned char c='A'; + unsigned int i,j,k; + +#ifdef CHARSET_EBCDIC + c = os_toascii[c]; /*'A' in ASCII */ +#endif + k=0; + EVP_MD_CTX_init(&m5); + EVP_MD_CTX_init(&s1); + for (i=0; (int)i sizeof buf) + { + /* bug: 'buf' is too small for this ciphersuite */ + SSLerr(SSL_F_SSL3_GENERATE_KEY_BLOCK, ERR_R_INTERNAL_ERROR); + return 0; + } + + for (j=0; jsession->master_key, + s->session->master_key_length); + EVP_DigestUpdate(&s1,s->s3->server_random,SSL3_RANDOM_SIZE); + EVP_DigestUpdate(&s1,s->s3->client_random,SSL3_RANDOM_SIZE); + EVP_DigestFinal_ex(&s1,smd,NULL); + + EVP_DigestInit_ex(&m5,EVP_md5(), NULL); + EVP_DigestUpdate(&m5,s->session->master_key, + s->session->master_key_length); + EVP_DigestUpdate(&m5,smd,SHA_DIGEST_LENGTH); + if ((int)(i+MD5_DIGEST_LENGTH) > num) + { + EVP_DigestFinal_ex(&m5,smd,NULL); + memcpy(km,smd,(num-i)); + } + else + EVP_DigestFinal_ex(&m5,km,NULL); + + km+=MD5_DIGEST_LENGTH; + } + OPENSSL_cleanse(smd,SHA_DIGEST_LENGTH); + EVP_MD_CTX_cleanup(&m5); + EVP_MD_CTX_cleanup(&s1); + return 1; + } + +int ssl3_change_cipher_state(SSL *s, int which) + { + unsigned char *p,*mac_secret; + unsigned char exp_key[EVP_MAX_KEY_LENGTH]; + unsigned char exp_iv[EVP_MAX_IV_LENGTH]; + unsigned char *ms,*key,*iv,*er1,*er2; + EVP_CIPHER_CTX *dd; + const EVP_CIPHER *c; +#ifndef OPENSSL_NO_COMP + COMP_METHOD *comp; +#endif + const EVP_MD *m; + EVP_MD_CTX md; + int is_exp,n,i,j,k,cl; + int reuse_dd = 0; + + is_exp=SSL_C_IS_EXPORT(s->s3->tmp.new_cipher); + c=s->s3->tmp.new_sym_enc; + m=s->s3->tmp.new_hash; + /* m == NULL will lead to a crash later */ + OPENSSL_assert(m); +#ifndef OPENSSL_NO_COMP + if (s->s3->tmp.new_compression == NULL) + comp=NULL; + else + comp=s->s3->tmp.new_compression->method; +#endif + + if (which & SSL3_CC_READ) + { + if (s->enc_read_ctx != NULL) + reuse_dd = 1; + else if ((s->enc_read_ctx=OPENSSL_malloc(sizeof(EVP_CIPHER_CTX))) == NULL) + goto err; + else + /* make sure it's intialized in case we exit later with an error */ + EVP_CIPHER_CTX_init(s->enc_read_ctx); + dd= s->enc_read_ctx; + + ssl_replace_hash(&s->read_hash,m); +#ifndef OPENSSL_NO_COMP + /* COMPRESS */ + if (s->expand != NULL) + { + COMP_CTX_free(s->expand); + s->expand=NULL; + } + if (comp != NULL) + { + s->expand=COMP_CTX_new(comp); + if (s->expand == NULL) + { + SSLerr(SSL_F_SSL3_CHANGE_CIPHER_STATE,SSL_R_COMPRESSION_LIBRARY_ERROR); + goto err2; + } + if (s->s3->rrec.comp == NULL) + s->s3->rrec.comp=(unsigned char *) + OPENSSL_malloc(SSL3_RT_MAX_PLAIN_LENGTH); + if (s->s3->rrec.comp == NULL) + goto err; + } +#endif + memset(&(s->s3->read_sequence[0]),0,8); + mac_secret= &(s->s3->read_mac_secret[0]); + } + else + { + if (s->enc_write_ctx != NULL) + reuse_dd = 1; + else if ((s->enc_write_ctx=OPENSSL_malloc(sizeof(EVP_CIPHER_CTX))) == NULL) + goto err; + else + /* make sure it's intialized in case we exit later with an error */ + EVP_CIPHER_CTX_init(s->enc_write_ctx); + dd= s->enc_write_ctx; + ssl_replace_hash(&s->write_hash,m); +#ifndef OPENSSL_NO_COMP + /* COMPRESS */ + if (s->compress != NULL) + { + COMP_CTX_free(s->compress); + s->compress=NULL; + } + if (comp != NULL) + { + s->compress=COMP_CTX_new(comp); + if (s->compress == NULL) + { + SSLerr(SSL_F_SSL3_CHANGE_CIPHER_STATE,SSL_R_COMPRESSION_LIBRARY_ERROR); + goto err2; + } + } +#endif + memset(&(s->s3->write_sequence[0]),0,8); + mac_secret= &(s->s3->write_mac_secret[0]); + } + + if (reuse_dd) + EVP_CIPHER_CTX_cleanup(dd); + + p=s->s3->tmp.key_block; + i=EVP_MD_size(m); + if (i < 0) + goto err2; + cl=EVP_CIPHER_key_length(c); + j=is_exp ? (cl < SSL_C_EXPORT_KEYLENGTH(s->s3->tmp.new_cipher) ? + cl : SSL_C_EXPORT_KEYLENGTH(s->s3->tmp.new_cipher)) : cl; + /* Was j=(is_exp)?5:EVP_CIPHER_key_length(c); */ + k=EVP_CIPHER_iv_length(c); + if ( (which == SSL3_CHANGE_CIPHER_CLIENT_WRITE) || + (which == SSL3_CHANGE_CIPHER_SERVER_READ)) + { + ms= &(p[ 0]); n=i+i; + key= &(p[ n]); n+=j+j; + iv= &(p[ n]); n+=k+k; + er1= &(s->s3->client_random[0]); + er2= &(s->s3->server_random[0]); + } + else + { + n=i; + ms= &(p[ n]); n+=i+j; + key= &(p[ n]); n+=j+k; + iv= &(p[ n]); n+=k; + er1= &(s->s3->server_random[0]); + er2= &(s->s3->client_random[0]); + } + + if (n > s->s3->tmp.key_block_length) + { + SSLerr(SSL_F_SSL3_CHANGE_CIPHER_STATE,ERR_R_INTERNAL_ERROR); + goto err2; + } + + EVP_MD_CTX_init(&md); + memcpy(mac_secret,ms,i); + if (is_exp) + { + /* In here I set both the read and write key/iv to the + * same value since only the correct one will be used :-). + */ + EVP_DigestInit_ex(&md,EVP_md5(), NULL); + EVP_DigestUpdate(&md,key,j); + EVP_DigestUpdate(&md,er1,SSL3_RANDOM_SIZE); + EVP_DigestUpdate(&md,er2,SSL3_RANDOM_SIZE); + EVP_DigestFinal_ex(&md,&(exp_key[0]),NULL); + key= &(exp_key[0]); + + if (k > 0) + { + EVP_DigestInit_ex(&md,EVP_md5(), NULL); + EVP_DigestUpdate(&md,er1,SSL3_RANDOM_SIZE); + EVP_DigestUpdate(&md,er2,SSL3_RANDOM_SIZE); + EVP_DigestFinal_ex(&md,&(exp_iv[0]),NULL); + iv= &(exp_iv[0]); + } + } + + s->session->key_arg_length=0; + + EVP_CipherInit_ex(dd,c,NULL,key,iv,(which & SSL3_CC_WRITE)); + + OPENSSL_cleanse(&(exp_key[0]),sizeof(exp_key)); + OPENSSL_cleanse(&(exp_iv[0]),sizeof(exp_iv)); + EVP_MD_CTX_cleanup(&md); + return(1); +err: + SSLerr(SSL_F_SSL3_CHANGE_CIPHER_STATE,ERR_R_MALLOC_FAILURE); +err2: + return(0); + } + +int ssl3_setup_key_block(SSL *s) + { + unsigned char *p; + const EVP_CIPHER *c; + const EVP_MD *hash; + int num; + int ret = 0; + SSL_COMP *comp; + + if (s->s3->tmp.key_block_length != 0) + return(1); + + if (!ssl_cipher_get_evp(s->session,&c,&hash,NULL,NULL,&comp)) + { + SSLerr(SSL_F_SSL3_SETUP_KEY_BLOCK,SSL_R_CIPHER_OR_HASH_UNAVAILABLE); + return(0); + } + + s->s3->tmp.new_sym_enc=c; + s->s3->tmp.new_hash=hash; +#ifdef OPENSSL_NO_COMP + s->s3->tmp.new_compression=NULL; +#else + s->s3->tmp.new_compression=comp; +#endif + + num=EVP_MD_size(hash); + if (num < 0) + return 0; + + num=EVP_CIPHER_key_length(c)+num+EVP_CIPHER_iv_length(c); + num*=2; + + ssl3_cleanup_key_block(s); + + if ((p=OPENSSL_malloc(num)) == NULL) + goto err; + + s->s3->tmp.key_block_length=num; + s->s3->tmp.key_block=p; + + ret = ssl3_generate_key_block(s,p,num); + + if (!(s->options & SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS)) + { + /* enable vulnerability countermeasure for CBC ciphers with + * known-IV problem (http://www.openssl.org/~bodo/tls-cbc.txt) + */ + s->s3->need_empty_fragments = 1; + + if (s->session->cipher != NULL) + { + if (s->session->cipher->algorithm_enc == SSL_eNULL) + s->s3->need_empty_fragments = 0; + +#ifndef OPENSSL_NO_RC4 + if (s->session->cipher->algorithm_enc == SSL_RC4) + s->s3->need_empty_fragments = 0; +#endif + } + } + + return ret; + +err: + SSLerr(SSL_F_SSL3_SETUP_KEY_BLOCK,ERR_R_MALLOC_FAILURE); + return(0); + } + +void ssl3_cleanup_key_block(SSL *s) + { + if (s->s3->tmp.key_block != NULL) + { + OPENSSL_cleanse(s->s3->tmp.key_block, + s->s3->tmp.key_block_length); + OPENSSL_free(s->s3->tmp.key_block); + s->s3->tmp.key_block=NULL; + } + s->s3->tmp.key_block_length=0; + } + +int ssl3_enc(SSL *s, int send) + { + SSL3_RECORD *rec; + EVP_CIPHER_CTX *ds; + unsigned long l; + int bs,i; + const EVP_CIPHER *enc; + + if (send) + { + ds=s->enc_write_ctx; + rec= &(s->s3->wrec); + if (s->enc_write_ctx == NULL) + enc=NULL; + else + enc=EVP_CIPHER_CTX_cipher(s->enc_write_ctx); + } + else + { + ds=s->enc_read_ctx; + rec= &(s->s3->rrec); + if (s->enc_read_ctx == NULL) + enc=NULL; + else + enc=EVP_CIPHER_CTX_cipher(s->enc_read_ctx); + } + + if ((s->session == NULL) || (ds == NULL) || + (enc == NULL)) + { + memmove(rec->data,rec->input,rec->length); + rec->input=rec->data; + } + else + { + l=rec->length; + bs=EVP_CIPHER_block_size(ds->cipher); + + /* COMPRESS */ + + if ((bs != 1) && send) + { + i=bs-((int)l%bs); + + /* we need to add 'i-1' padding bytes */ + l+=i; + /* the last of these zero bytes will be overwritten + * with the padding length. */ + memset(&rec->input[rec->length], 0, i); + rec->length+=i; + rec->input[l-1]=(i-1); + } + + if (!send) + { + if (l == 0 || l%bs != 0) + { + SSLerr(SSL_F_SSL3_ENC,SSL_R_BLOCK_CIPHER_PAD_IS_WRONG); + ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_DECRYPTION_FAILED); + return 0; + } + /* otherwise, rec->length >= bs */ + } + + EVP_Cipher(ds,rec->data,rec->input,l); + + if ((bs != 1) && !send) + { + i=rec->data[l-1]+1; + /* SSL 3.0 bounds the number of padding bytes by the block size; + * padding bytes (except the last one) are arbitrary */ + if (i > bs) + { + /* Incorrect padding. SSLerr() and ssl3_alert are done + * by caller: we don't want to reveal whether this is + * a decryption error or a MAC verification failure + * (see http://www.openssl.org/~bodo/tls-cbc.txt) */ + return -1; + } + /* now i <= bs <= rec->length */ + rec->length-=i; + } + } + return(1); + } + +void ssl3_init_finished_mac(SSL *s) + { + if (s->s3->handshake_buffer) BIO_free(s->s3->handshake_buffer); + if (s->s3->handshake_dgst) ssl3_free_digest_list(s); + s->s3->handshake_buffer=BIO_new(BIO_s_mem()); + (void)BIO_set_close(s->s3->handshake_buffer,BIO_CLOSE); + } + +void ssl3_free_digest_list(SSL *s) + { + int i; + if (!s->s3->handshake_dgst) return; + for (i=0;is3->handshake_dgst[i]) + EVP_MD_CTX_destroy(s->s3->handshake_dgst[i]); + } + OPENSSL_free(s->s3->handshake_dgst); + s->s3->handshake_dgst=NULL; + } + + + +void ssl3_finish_mac(SSL *s, const unsigned char *buf, int len) + { + if (s->s3->handshake_buffer) + { + BIO_write (s->s3->handshake_buffer,(void *)buf,len); + } + else + { + int i; + for (i=0;i< SSL_MAX_DIGEST;i++) + { + if (s->s3->handshake_dgst[i]!= NULL) + EVP_DigestUpdate(s->s3->handshake_dgst[i],buf,len); + } + } + } + +int ssl3_digest_cached_records(SSL *s) + { + int i; + long mask; + const EVP_MD *md; + long hdatalen; + void *hdata; + + /* Allocate handshake_dgst array */ + ssl3_free_digest_list(s); + s->s3->handshake_dgst = OPENSSL_malloc(SSL_MAX_DIGEST * sizeof(EVP_MD_CTX *)); + memset(s->s3->handshake_dgst,0,SSL_MAX_DIGEST *sizeof(EVP_MD_CTX *)); + hdatalen = BIO_get_mem_data(s->s3->handshake_buffer,&hdata); + if (hdatalen <= 0) + { + SSLerr(SSL_F_SSL3_DIGEST_CACHED_RECORDS, SSL_R_BAD_HANDSHAKE_LENGTH); + return 0; + } + + /* Loop through bitso of algorithm2 field and create MD_CTX-es */ + for (i=0;ssl_get_handshake_digest(i,&mask,&md); i++) + { + if ((mask & s->s3->tmp.new_cipher->algorithm2) && md) + { + s->s3->handshake_dgst[i]=EVP_MD_CTX_create(); + EVP_DigestInit_ex(s->s3->handshake_dgst[i],md,NULL); + EVP_DigestUpdate(s->s3->handshake_dgst[i],hdata,hdatalen); + } + else + { + s->s3->handshake_dgst[i]=NULL; + } + } + /* Free handshake_buffer BIO */ + BIO_free(s->s3->handshake_buffer); + s->s3->handshake_buffer = NULL; + + return 1; + } + +int ssl3_cert_verify_mac(SSL *s, int md_nid, unsigned char *p) + { + return(ssl3_handshake_mac(s,md_nid,NULL,0,p)); + } +int ssl3_final_finish_mac(SSL *s, + const char *sender, int len, unsigned char *p) + { + int ret; + ret=ssl3_handshake_mac(s,NID_md5,sender,len,p); + p+=ret; + ret+=ssl3_handshake_mac(s,NID_sha1,sender,len,p); + return(ret); + } +static int ssl3_handshake_mac(SSL *s, int md_nid, + const char *sender, int len, unsigned char *p) + { + unsigned int ret; + int npad,n; + unsigned int i; + unsigned char md_buf[EVP_MAX_MD_SIZE]; + EVP_MD_CTX ctx,*d=NULL; + + if (s->s3->handshake_buffer) + if (!ssl3_digest_cached_records(s)) + return 0; + + /* Search for digest of specified type in the handshake_dgst + * array*/ + for (i=0;is3->handshake_dgst[i]&&EVP_MD_CTX_type(s->s3->handshake_dgst[i])==md_nid) + { + d=s->s3->handshake_dgst[i]; + break; + } + } + if (!d) { + SSLerr(SSL_F_SSL3_HANDSHAKE_MAC,SSL_R_NO_REQUIRED_DIGEST); + return 0; + } + EVP_MD_CTX_init(&ctx); + EVP_MD_CTX_copy_ex(&ctx,d); + n=EVP_MD_CTX_size(&ctx); + if (n < 0) + return 0; + + npad=(48/n)*n; + if (sender != NULL) + EVP_DigestUpdate(&ctx,sender,len); + EVP_DigestUpdate(&ctx,s->session->master_key, + s->session->master_key_length); + EVP_DigestUpdate(&ctx,ssl3_pad_1,npad); + EVP_DigestFinal_ex(&ctx,md_buf,&i); + + EVP_DigestInit_ex(&ctx,EVP_MD_CTX_md(&ctx), NULL); + EVP_DigestUpdate(&ctx,s->session->master_key, + s->session->master_key_length); + EVP_DigestUpdate(&ctx,ssl3_pad_2,npad); + EVP_DigestUpdate(&ctx,md_buf,i); + EVP_DigestFinal_ex(&ctx,p,&ret); + + EVP_MD_CTX_cleanup(&ctx); + + return((int)ret); + } + +int n_ssl3_mac(SSL *ssl, unsigned char *md, int send) + { + SSL3_RECORD *rec; + unsigned char *mac_sec,*seq; + EVP_MD_CTX md_ctx; + const EVP_MD_CTX *hash; + unsigned char *p,rec_char; + unsigned int md_size; + int npad; + int t; + + if (send) + { + rec= &(ssl->s3->wrec); + mac_sec= &(ssl->s3->write_mac_secret[0]); + seq= &(ssl->s3->write_sequence[0]); + hash=ssl->write_hash; + } + else + { + rec= &(ssl->s3->rrec); + mac_sec= &(ssl->s3->read_mac_secret[0]); + seq= &(ssl->s3->read_sequence[0]); + hash=ssl->read_hash; + } + + t=EVP_MD_CTX_size(hash); + if (t < 0) + return -1; + md_size=t; + npad=(48/md_size)*md_size; + + /* Chop the digest off the end :-) */ + EVP_MD_CTX_init(&md_ctx); + + EVP_MD_CTX_copy_ex( &md_ctx,hash); + EVP_DigestUpdate(&md_ctx,mac_sec,md_size); + EVP_DigestUpdate(&md_ctx,ssl3_pad_1,npad); + EVP_DigestUpdate(&md_ctx,seq,8); + rec_char=rec->type; + EVP_DigestUpdate(&md_ctx,&rec_char,1); + p=md; + s2n(rec->length,p); + EVP_DigestUpdate(&md_ctx,md,2); + EVP_DigestUpdate(&md_ctx,rec->input,rec->length); + EVP_DigestFinal_ex( &md_ctx,md,NULL); + + EVP_MD_CTX_copy_ex( &md_ctx,hash); + EVP_DigestUpdate(&md_ctx,mac_sec,md_size); + EVP_DigestUpdate(&md_ctx,ssl3_pad_2,npad); + EVP_DigestUpdate(&md_ctx,md,md_size); + EVP_DigestFinal_ex( &md_ctx,md,&md_size); + + EVP_MD_CTX_cleanup(&md_ctx); + + ssl3_record_sequence_update(seq); + return(md_size); + } + +void ssl3_record_sequence_update(unsigned char *seq) + { + int i; + + for (i=7; i>=0; i--) + { + ++seq[i]; + if (seq[i] != 0) break; + } + } + +int ssl3_generate_master_secret(SSL *s, unsigned char *out, unsigned char *p, + int len) + { + static const unsigned char *salt[3]={ +#ifndef CHARSET_EBCDIC + (const unsigned char *)"A", + (const unsigned char *)"BB", + (const unsigned char *)"CCC", +#else + (const unsigned char *)"\x41", + (const unsigned char *)"\x42\x42", + (const unsigned char *)"\x43\x43\x43", +#endif + }; + unsigned char buf[EVP_MAX_MD_SIZE]; + EVP_MD_CTX ctx; + int i,ret=0; + unsigned int n; + + EVP_MD_CTX_init(&ctx); + for (i=0; i<3; i++) + { + EVP_DigestInit_ex(&ctx,s->ctx->sha1, NULL); + EVP_DigestUpdate(&ctx,salt[i],strlen((const char *)salt[i])); + EVP_DigestUpdate(&ctx,p,len); + EVP_DigestUpdate(&ctx,&(s->s3->client_random[0]), + SSL3_RANDOM_SIZE); + EVP_DigestUpdate(&ctx,&(s->s3->server_random[0]), + SSL3_RANDOM_SIZE); + EVP_DigestFinal_ex(&ctx,buf,&n); + + EVP_DigestInit_ex(&ctx,s->ctx->md5, NULL); + EVP_DigestUpdate(&ctx,p,len); + EVP_DigestUpdate(&ctx,buf,n); + EVP_DigestFinal_ex(&ctx,out,&n); + out+=n; + ret+=n; + } + EVP_MD_CTX_cleanup(&ctx); + return(ret); + } + +int ssl3_alert_code(int code) + { + switch (code) + { + case SSL_AD_CLOSE_NOTIFY: return(SSL3_AD_CLOSE_NOTIFY); + case SSL_AD_UNEXPECTED_MESSAGE: return(SSL3_AD_UNEXPECTED_MESSAGE); + case SSL_AD_BAD_RECORD_MAC: return(SSL3_AD_BAD_RECORD_MAC); + case SSL_AD_DECRYPTION_FAILED: return(SSL3_AD_BAD_RECORD_MAC); + case SSL_AD_RECORD_OVERFLOW: return(SSL3_AD_BAD_RECORD_MAC); + case SSL_AD_DECOMPRESSION_FAILURE:return(SSL3_AD_DECOMPRESSION_FAILURE); + case SSL_AD_HANDSHAKE_FAILURE: return(SSL3_AD_HANDSHAKE_FAILURE); + case SSL_AD_NO_CERTIFICATE: return(SSL3_AD_NO_CERTIFICATE); + case SSL_AD_BAD_CERTIFICATE: return(SSL3_AD_BAD_CERTIFICATE); + case SSL_AD_UNSUPPORTED_CERTIFICATE:return(SSL3_AD_UNSUPPORTED_CERTIFICATE); + case SSL_AD_CERTIFICATE_REVOKED:return(SSL3_AD_CERTIFICATE_REVOKED); + case SSL_AD_CERTIFICATE_EXPIRED:return(SSL3_AD_CERTIFICATE_EXPIRED); + case SSL_AD_CERTIFICATE_UNKNOWN:return(SSL3_AD_CERTIFICATE_UNKNOWN); + case SSL_AD_ILLEGAL_PARAMETER: return(SSL3_AD_ILLEGAL_PARAMETER); + case SSL_AD_UNKNOWN_CA: return(SSL3_AD_BAD_CERTIFICATE); + case SSL_AD_ACCESS_DENIED: return(SSL3_AD_HANDSHAKE_FAILURE); + case SSL_AD_DECODE_ERROR: return(SSL3_AD_HANDSHAKE_FAILURE); + case SSL_AD_DECRYPT_ERROR: return(SSL3_AD_HANDSHAKE_FAILURE); + case SSL_AD_EXPORT_RESTRICTION: return(SSL3_AD_HANDSHAKE_FAILURE); + case SSL_AD_PROTOCOL_VERSION: return(SSL3_AD_HANDSHAKE_FAILURE); + case SSL_AD_INSUFFICIENT_SECURITY:return(SSL3_AD_HANDSHAKE_FAILURE); + case SSL_AD_INTERNAL_ERROR: return(SSL3_AD_HANDSHAKE_FAILURE); + case SSL_AD_USER_CANCELLED: return(SSL3_AD_HANDSHAKE_FAILURE); + case SSL_AD_NO_RENEGOTIATION: return(-1); /* Don't send it :-) */ + case SSL_AD_UNSUPPORTED_EXTENSION: return(SSL3_AD_HANDSHAKE_FAILURE); + case SSL_AD_CERTIFICATE_UNOBTAINABLE: return(SSL3_AD_HANDSHAKE_FAILURE); + case SSL_AD_UNRECOGNIZED_NAME: return(SSL3_AD_HANDSHAKE_FAILURE); + case SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE: return(SSL3_AD_HANDSHAKE_FAILURE); + case SSL_AD_BAD_CERTIFICATE_HASH_VALUE: return(SSL3_AD_HANDSHAKE_FAILURE); + case SSL_AD_UNKNOWN_PSK_IDENTITY:return(TLS1_AD_UNKNOWN_PSK_IDENTITY); + default: return(-1); + } + } + diff --git a/node-v0.8.14/deps/openssl/openssl/ssl/s3_lib.c b/node-v0.8.14/deps/openssl/openssl/ssl/s3_lib.c new file mode 100644 index 0000000..72d3f1f --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/ssl/s3_lib.c @@ -0,0 +1,3363 @@ +/* ssl/s3_lib.c */ +/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com) + * All rights reserved. + * + * This package is an SSL implementation written + * by Eric Young (eay@cryptsoft.com). + * The implementation was written so as to conform with Netscapes SSL. + * + * This library is free for commercial and non-commercial use as long as + * the following conditions are aheared to. The following conditions + * apply to all code found in this distribution, be it the RC4, RSA, + * lhash, DES, etc., code; not just the SSL code. The SSL documentation + * included with this distribution is covered by the same copyright terms + * except that the holder is Tim Hudson (tjh@cryptsoft.com). + * + * Copyright remains Eric Young's, and as such any Copyright notices in + * the code are not to be removed. + * If this package is used in a product, Eric Young should be given attribution + * as the author of the parts of the library used. + * This can be in the form of a textual message at program startup or + * in documentation (online or textual) provided with the package. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * "This product includes cryptographic software written by + * Eric Young (eay@cryptsoft.com)" + * The word 'cryptographic' can be left out if the rouines from the library + * being used are not cryptographic related :-). + * 4. If you include any Windows specific code (or a derivative thereof) from + * the apps directory (application code) you must include an acknowledgement: + * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)" + * + * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * + * The licence and distribution terms for any publically available version or + * derivative of this code cannot be changed. i.e. this code cannot simply be + * copied and put under another distribution licence + * [including the GNU Public Licence.] + */ +/* ==================================================================== + * Copyright (c) 1998-2007 The OpenSSL Project. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. All advertising materials mentioning features or use of this + * software must display the following acknowledgment: + * "This product includes software developed by the OpenSSL Project + * for use in the OpenSSL Toolkit. (http://www.openssl.org/)" + * + * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to + * endorse or promote products derived from this software without + * prior written permission. For written permission, please contact + * openssl-core@openssl.org. + * + * 5. Products derived from this software may not be called "OpenSSL" + * nor may "OpenSSL" appear in their names without prior written + * permission of the OpenSSL Project. + * + * 6. Redistributions of any form whatsoever must retain the following + * acknowledgment: + * "This product includes software developed by the OpenSSL Project + * for use in the OpenSSL Toolkit (http://www.openssl.org/)" + * + * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY + * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR + * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, + * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * ==================================================================== + * + * This product includes cryptographic software written by Eric Young + * (eay@cryptsoft.com). This product includes software written by Tim + * Hudson (tjh@cryptsoft.com). + * + */ +/* ==================================================================== + * Copyright 2002 Sun Microsystems, Inc. ALL RIGHTS RESERVED. + * + * Portions of the attached software ("Contribution") are developed by + * SUN MICROSYSTEMS, INC., and are contributed to the OpenSSL project. + * + * The Contribution is licensed pursuant to the OpenSSL open source + * license provided above. + * + * ECC cipher suite support in OpenSSL originally written by + * Vipul Gupta and Sumit Gupta of Sun Microsystems Laboratories. + * + */ +/* ==================================================================== + * Copyright 2005 Nokia. All rights reserved. + * + * The portions of the attached software ("Contribution") is developed by + * Nokia Corporation and is licensed pursuant to the OpenSSL open source + * license. + * + * The Contribution, originally written by Mika Kousa and Pasi Eronen of + * Nokia Corporation, consists of the "PSK" (Pre-Shared Key) ciphersuites + * support (see RFC 4279) to OpenSSL. + * + * No patent licenses or other rights except those expressly stated in + * the OpenSSL open source license shall be deemed granted or received + * expressly, by implication, estoppel, or otherwise. + * + * No assurances are provided by Nokia that the Contribution does not + * infringe the patent or other intellectual property rights of any third + * party or that the license provides you with all the necessary rights + * to make use of the Contribution. + * + * THE SOFTWARE IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND. IN + * ADDITION TO THE DISCLAIMERS INCLUDED IN THE LICENSE, NOKIA + * SPECIFICALLY DISCLAIMS ANY LIABILITY FOR CLAIMS BROUGHT BY YOU OR ANY + * OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL PROPERTY RIGHTS OR + * OTHERWISE. + */ + +#include +#include +#include "ssl_locl.h" +#include "kssl_lcl.h" +#ifndef OPENSSL_NO_TLSEXT +#ifndef OPENSSL_NO_EC +#include "../crypto/ec/ec_lcl.h" +#endif /* OPENSSL_NO_EC */ +#endif /* OPENSSL_NO_TLSEXT */ +#include +#ifndef OPENSSL_NO_DH +#include +#endif + +const char ssl3_version_str[]="SSLv3" OPENSSL_VERSION_PTEXT; + +#define SSL3_NUM_CIPHERS (sizeof(ssl3_ciphers)/sizeof(SSL_CIPHER)) + +/* list of available SSLv3 ciphers (sorted by id) */ +OPENSSL_GLOBAL SSL_CIPHER ssl3_ciphers[]={ + +/* The RSA ciphers */ +/* Cipher 01 */ + { + 1, + SSL3_TXT_RSA_NULL_MD5, + SSL3_CK_RSA_NULL_MD5, + SSL_kRSA, + SSL_aRSA, + SSL_eNULL, + SSL_MD5, + SSL_SSLV3, + SSL_NOT_EXP|SSL_STRONG_NONE, + SSL_HANDSHAKE_MAC_DEFAULT|TLS1_PRF, + 0, + 0, + }, + +/* Cipher 02 */ + { + 1, + SSL3_TXT_RSA_NULL_SHA, + SSL3_CK_RSA_NULL_SHA, + SSL_kRSA, + SSL_aRSA, + SSL_eNULL, + SSL_SHA1, + SSL_SSLV3, + SSL_NOT_EXP|SSL_STRONG_NONE|SSL_FIPS, + SSL_HANDSHAKE_MAC_DEFAULT|TLS1_PRF, + 0, + 0, + }, + +/* Cipher 03 */ + { + 1, + SSL3_TXT_RSA_RC4_40_MD5, + SSL3_CK_RSA_RC4_40_MD5, + SSL_kRSA, + SSL_aRSA, + SSL_RC4, + SSL_MD5, + SSL_SSLV3, + SSL_EXPORT|SSL_EXP40, + SSL_HANDSHAKE_MAC_DEFAULT|TLS1_PRF, + 40, + 128, + }, + +/* Cipher 04 */ + { + 1, + SSL3_TXT_RSA_RC4_128_MD5, + SSL3_CK_RSA_RC4_128_MD5, + SSL_kRSA, + SSL_aRSA, + SSL_RC4, + SSL_MD5, + SSL_SSLV3, + SSL_NOT_EXP|SSL_MEDIUM, + SSL_HANDSHAKE_MAC_DEFAULT|TLS1_PRF, + 128, + 128, + }, + +/* Cipher 05 */ + { + 1, + SSL3_TXT_RSA_RC4_128_SHA, + SSL3_CK_RSA_RC4_128_SHA, + SSL_kRSA, + SSL_aRSA, + SSL_RC4, + SSL_SHA1, + SSL_SSLV3, + SSL_NOT_EXP|SSL_MEDIUM, + SSL_HANDSHAKE_MAC_DEFAULT|TLS1_PRF, + 128, + 128, + }, + +/* Cipher 06 */ + { + 1, + SSL3_TXT_RSA_RC2_40_MD5, + SSL3_CK_RSA_RC2_40_MD5, + SSL_kRSA, + SSL_aRSA, + SSL_RC2, + SSL_MD5, + SSL_SSLV3, + SSL_EXPORT|SSL_EXP40, + SSL_HANDSHAKE_MAC_DEFAULT|TLS1_PRF, + 40, + 128, + }, + +/* Cipher 07 */ +#ifndef OPENSSL_NO_IDEA + { + 1, + SSL3_TXT_RSA_IDEA_128_SHA, + SSL3_CK_RSA_IDEA_128_SHA, + SSL_kRSA, + SSL_aRSA, + SSL_IDEA, + SSL_SHA1, + SSL_SSLV3, + SSL_NOT_EXP|SSL_MEDIUM, + SSL_HANDSHAKE_MAC_DEFAULT|TLS1_PRF, + 128, + 128, + }, +#endif + +/* Cipher 08 */ + { + 1, + SSL3_TXT_RSA_DES_40_CBC_SHA, + SSL3_CK_RSA_DES_40_CBC_SHA, + SSL_kRSA, + SSL_aRSA, + SSL_DES, + SSL_SHA1, + SSL_SSLV3, + SSL_EXPORT|SSL_EXP40, + SSL_HANDSHAKE_MAC_DEFAULT|TLS1_PRF, + 40, + 56, + }, + +/* Cipher 09 */ + { + 1, + SSL3_TXT_RSA_DES_64_CBC_SHA, + SSL3_CK_RSA_DES_64_CBC_SHA, + SSL_kRSA, + SSL_aRSA, + SSL_DES, + SSL_SHA1, + SSL_SSLV3, + SSL_NOT_EXP|SSL_LOW, + SSL_HANDSHAKE_MAC_DEFAULT|TLS1_PRF, + 56, + 56, + }, + +/* Cipher 0A */ + { + 1, + SSL3_TXT_RSA_DES_192_CBC3_SHA, + SSL3_CK_RSA_DES_192_CBC3_SHA, + SSL_kRSA, + SSL_aRSA, + SSL_3DES, + SSL_SHA1, + SSL_SSLV3, + SSL_NOT_EXP|SSL_HIGH|SSL_FIPS, + SSL_HANDSHAKE_MAC_DEFAULT|TLS1_PRF, + 168, + 168, + }, + +/* The DH ciphers */ +/* Cipher 0B */ + { + 0, + SSL3_TXT_DH_DSS_DES_40_CBC_SHA, + SSL3_CK_DH_DSS_DES_40_CBC_SHA, + SSL_kDHd, + SSL_aDH, + SSL_DES, + SSL_SHA1, + SSL_SSLV3, + SSL_EXPORT|SSL_EXP40, + SSL_HANDSHAKE_MAC_DEFAULT|TLS1_PRF, + 40, + 56, + }, + +/* Cipher 0C */ + { + 0, /* not implemented (non-ephemeral DH) */ + SSL3_TXT_DH_DSS_DES_64_CBC_SHA, + SSL3_CK_DH_DSS_DES_64_CBC_SHA, + SSL_kDHd, + SSL_aDH, + SSL_DES, + SSL_SHA1, + SSL_SSLV3, + SSL_NOT_EXP|SSL_LOW, + SSL_HANDSHAKE_MAC_DEFAULT|TLS1_PRF, + 56, + 56, + }, + +/* Cipher 0D */ + { + 0, /* not implemented (non-ephemeral DH) */ + SSL3_TXT_DH_DSS_DES_192_CBC3_SHA, + SSL3_CK_DH_DSS_DES_192_CBC3_SHA, + SSL_kDHd, + SSL_aDH, + SSL_3DES, + SSL_SHA1, + SSL_SSLV3, + SSL_NOT_EXP|SSL_HIGH|SSL_FIPS, + SSL_HANDSHAKE_MAC_DEFAULT|TLS1_PRF, + 168, + 168, + }, + +/* Cipher 0E */ + { + 0, /* not implemented (non-ephemeral DH) */ + SSL3_TXT_DH_RSA_DES_40_CBC_SHA, + SSL3_CK_DH_RSA_DES_40_CBC_SHA, + SSL_kDHr, + SSL_aDH, + SSL_DES, + SSL_SHA1, + SSL_SSLV3, + SSL_EXPORT|SSL_EXP40, + SSL_HANDSHAKE_MAC_DEFAULT|TLS1_PRF, + 40, + 56, + }, + +/* Cipher 0F */ + { + 0, /* not implemented (non-ephemeral DH) */ + SSL3_TXT_DH_RSA_DES_64_CBC_SHA, + SSL3_CK_DH_RSA_DES_64_CBC_SHA, + SSL_kDHr, + SSL_aDH, + SSL_DES, + SSL_SHA1, + SSL_SSLV3, + SSL_NOT_EXP|SSL_LOW, + SSL_HANDSHAKE_MAC_DEFAULT|TLS1_PRF, + 56, + 56, + }, + +/* Cipher 10 */ + { + 0, /* not implemented (non-ephemeral DH) */ + SSL3_TXT_DH_RSA_DES_192_CBC3_SHA, + SSL3_CK_DH_RSA_DES_192_CBC3_SHA, + SSL_kDHr, + SSL_aDH, + SSL_3DES, + SSL_SHA1, + SSL_SSLV3, + SSL_NOT_EXP|SSL_HIGH|SSL_FIPS, + SSL_HANDSHAKE_MAC_DEFAULT|TLS1_PRF, + 168, + 168, + }, + +/* The Ephemeral DH ciphers */ +/* Cipher 11 */ + { + 1, + SSL3_TXT_EDH_DSS_DES_40_CBC_SHA, + SSL3_CK_EDH_DSS_DES_40_CBC_SHA, + SSL_kEDH, + SSL_aDSS, + SSL_DES, + SSL_SHA1, + SSL_SSLV3, + SSL_EXPORT|SSL_EXP40, + SSL_HANDSHAKE_MAC_DEFAULT|TLS1_PRF, + 40, + 56, + }, + +/* Cipher 12 */ + { + 1, + SSL3_TXT_EDH_DSS_DES_64_CBC_SHA, + SSL3_CK_EDH_DSS_DES_64_CBC_SHA, + SSL_kEDH, + SSL_aDSS, + SSL_DES, + SSL_SHA1, + SSL_SSLV3, + SSL_NOT_EXP|SSL_LOW, + SSL_HANDSHAKE_MAC_DEFAULT|TLS1_PRF, + 56, + 56, + }, + +/* Cipher 13 */ + { + 1, + SSL3_TXT_EDH_DSS_DES_192_CBC3_SHA, + SSL3_CK_EDH_DSS_DES_192_CBC3_SHA, + SSL_kEDH, + SSL_aDSS, + SSL_3DES, + SSL_SHA1, + SSL_SSLV3, + SSL_NOT_EXP|SSL_HIGH|SSL_FIPS, + SSL_HANDSHAKE_MAC_DEFAULT|TLS1_PRF, + 168, + 168, + }, + +/* Cipher 14 */ + { + 1, + SSL3_TXT_EDH_RSA_DES_40_CBC_SHA, + SSL3_CK_EDH_RSA_DES_40_CBC_SHA, + SSL_kEDH, + SSL_aRSA, + SSL_DES, + SSL_SHA1, + SSL_SSLV3, + SSL_EXPORT|SSL_EXP40, + SSL_HANDSHAKE_MAC_DEFAULT|TLS1_PRF, + 40, + 56, + }, + +/* Cipher 15 */ + { + 1, + SSL3_TXT_EDH_RSA_DES_64_CBC_SHA, + SSL3_CK_EDH_RSA_DES_64_CBC_SHA, + SSL_kEDH, + SSL_aRSA, + SSL_DES, + SSL_SHA1, + SSL_SSLV3, + SSL_NOT_EXP|SSL_LOW, + SSL_HANDSHAKE_MAC_DEFAULT|TLS1_PRF, + 56, + 56, + }, + +/* Cipher 16 */ + { + 1, + SSL3_TXT_EDH_RSA_DES_192_CBC3_SHA, + SSL3_CK_EDH_RSA_DES_192_CBC3_SHA, + SSL_kEDH, + SSL_aRSA, + SSL_3DES, + SSL_SHA1, + SSL_SSLV3, + SSL_NOT_EXP|SSL_HIGH|SSL_FIPS, + SSL_HANDSHAKE_MAC_DEFAULT|TLS1_PRF, + 168, + 168, + }, + +/* Cipher 17 */ + { + 1, + SSL3_TXT_ADH_RC4_40_MD5, + SSL3_CK_ADH_RC4_40_MD5, + SSL_kEDH, + SSL_aNULL, + SSL_RC4, + SSL_MD5, + SSL_SSLV3, + SSL_EXPORT|SSL_EXP40, + SSL_HANDSHAKE_MAC_DEFAULT|TLS1_PRF, + 40, + 128, + }, + +/* Cipher 18 */ + { + 1, + SSL3_TXT_ADH_RC4_128_MD5, + SSL3_CK_ADH_RC4_128_MD5, + SSL_kEDH, + SSL_aNULL, + SSL_RC4, + SSL_MD5, + SSL_SSLV3, + SSL_NOT_EXP|SSL_MEDIUM, + SSL_HANDSHAKE_MAC_DEFAULT|TLS1_PRF, + 128, + 128, + }, + +/* Cipher 19 */ + { + 1, + SSL3_TXT_ADH_DES_40_CBC_SHA, + SSL3_CK_ADH_DES_40_CBC_SHA, + SSL_kEDH, + SSL_aNULL, + SSL_DES, + SSL_SHA1, + SSL_SSLV3, + SSL_EXPORT|SSL_EXP40, + SSL_HANDSHAKE_MAC_DEFAULT|TLS1_PRF, + 40, + 128, + }, + +/* Cipher 1A */ + { + 1, + SSL3_TXT_ADH_DES_64_CBC_SHA, + SSL3_CK_ADH_DES_64_CBC_SHA, + SSL_kEDH, + SSL_aNULL, + SSL_DES, + SSL_SHA1, + SSL_SSLV3, + SSL_NOT_EXP|SSL_LOW, + SSL_HANDSHAKE_MAC_DEFAULT|TLS1_PRF, + 56, + 56, + }, + +/* Cipher 1B */ + { + 1, + SSL3_TXT_ADH_DES_192_CBC_SHA, + SSL3_CK_ADH_DES_192_CBC_SHA, + SSL_kEDH, + SSL_aNULL, + SSL_3DES, + SSL_SHA1, + SSL_SSLV3, + SSL_NOT_EXP|SSL_HIGH|SSL_FIPS, + SSL_HANDSHAKE_MAC_DEFAULT|TLS1_PRF, + 168, + 168, + }, + +/* Fortezza ciphersuite from SSL 3.0 spec */ +#if 0 +/* Cipher 1C */ + { + 0, + SSL3_TXT_FZA_DMS_NULL_SHA, + SSL3_CK_FZA_DMS_NULL_SHA, + SSL_kFZA, + SSL_aFZA, + SSL_eNULL, + SSL_SHA1, + SSL_SSLV3, + SSL_NOT_EXP|SSL_STRONG_NONE, + SSL_HANDSHAKE_MAC_DEFAULT|TLS1_PRF, + 0, + 0, + }, + +/* Cipher 1D */ + { + 0, + SSL3_TXT_FZA_DMS_FZA_SHA, + SSL3_CK_FZA_DMS_FZA_SHA, + SSL_kFZA, + SSL_aFZA, + SSL_eFZA, + SSL_SHA1, + SSL_SSLV3, + SSL_NOT_EXP|SSL_STRONG_NONE, + SSL_HANDSHAKE_MAC_DEFAULT|TLS1_PRF, + 0, + 0, + }, + +/* Cipher 1E */ + { + 0, + SSL3_TXT_FZA_DMS_RC4_SHA, + SSL3_CK_FZA_DMS_RC4_SHA, + SSL_kFZA, + SSL_aFZA, + SSL_RC4, + SSL_SHA1, + SSL_SSLV3, + SSL_NOT_EXP|SSL_MEDIUM, + SSL_HANDSHAKE_MAC_DEFAULT|TLS1_PRF, + 128, + 128, + }, +#endif + +#ifndef OPENSSL_NO_KRB5 +/* The Kerberos ciphers*/ +/* Cipher 1E */ + { + 1, + SSL3_TXT_KRB5_DES_64_CBC_SHA, + SSL3_CK_KRB5_DES_64_CBC_SHA, + SSL_kKRB5, + SSL_aKRB5, + SSL_DES, + SSL_SHA1, + SSL_SSLV3, + SSL_NOT_EXP|SSL_LOW, + SSL_HANDSHAKE_MAC_DEFAULT|TLS1_PRF, + 56, + 56, + }, + +/* Cipher 1F */ + { + 1, + SSL3_TXT_KRB5_DES_192_CBC3_SHA, + SSL3_CK_KRB5_DES_192_CBC3_SHA, + SSL_kKRB5, + SSL_aKRB5, + SSL_3DES, + SSL_SHA1, + SSL_SSLV3, + SSL_NOT_EXP|SSL_HIGH|SSL_FIPS, + SSL_HANDSHAKE_MAC_DEFAULT|TLS1_PRF, + 168, + 168, + }, + +/* Cipher 20 */ + { + 1, + SSL3_TXT_KRB5_RC4_128_SHA, + SSL3_CK_KRB5_RC4_128_SHA, + SSL_kKRB5, + SSL_aKRB5, + SSL_RC4, + SSL_SHA1, + SSL_SSLV3, + SSL_NOT_EXP|SSL_MEDIUM, + SSL_HANDSHAKE_MAC_DEFAULT|TLS1_PRF, + 128, + 128, + }, + +/* Cipher 21 */ + { + 1, + SSL3_TXT_KRB5_IDEA_128_CBC_SHA, + SSL3_CK_KRB5_IDEA_128_CBC_SHA, + SSL_kKRB5, + SSL_aKRB5, + SSL_IDEA, + SSL_SHA1, + SSL_SSLV3, + SSL_NOT_EXP|SSL_MEDIUM, + SSL_HANDSHAKE_MAC_DEFAULT|TLS1_PRF, + 128, + 128, + }, + +/* Cipher 22 */ + { + 1, + SSL3_TXT_KRB5_DES_64_CBC_MD5, + SSL3_CK_KRB5_DES_64_CBC_MD5, + SSL_kKRB5, + SSL_aKRB5, + SSL_DES, + SSL_MD5, + SSL_SSLV3, + SSL_NOT_EXP|SSL_LOW, + SSL_HANDSHAKE_MAC_DEFAULT|TLS1_PRF, + 56, + 56, + }, + +/* Cipher 23 */ + { + 1, + SSL3_TXT_KRB5_DES_192_CBC3_MD5, + SSL3_CK_KRB5_DES_192_CBC3_MD5, + SSL_kKRB5, + SSL_aKRB5, + SSL_3DES, + SSL_MD5, + SSL_SSLV3, + SSL_NOT_EXP|SSL_HIGH, + SSL_HANDSHAKE_MAC_DEFAULT|TLS1_PRF, + 168, + 168, + }, + +/* Cipher 24 */ + { + 1, + SSL3_TXT_KRB5_RC4_128_MD5, + SSL3_CK_KRB5_RC4_128_MD5, + SSL_kKRB5, + SSL_aKRB5, + SSL_RC4, + SSL_MD5, + SSL_SSLV3, + SSL_NOT_EXP|SSL_MEDIUM, + SSL_HANDSHAKE_MAC_DEFAULT|TLS1_PRF, + 128, + 128, + }, + +/* Cipher 25 */ + { + 1, + SSL3_TXT_KRB5_IDEA_128_CBC_MD5, + SSL3_CK_KRB5_IDEA_128_CBC_MD5, + SSL_kKRB5, + SSL_aKRB5, + SSL_IDEA, + SSL_MD5, + SSL_SSLV3, + SSL_NOT_EXP|SSL_MEDIUM, + SSL_HANDSHAKE_MAC_DEFAULT|TLS1_PRF, + 128, + 128, + }, + +/* Cipher 26 */ + { + 1, + SSL3_TXT_KRB5_DES_40_CBC_SHA, + SSL3_CK_KRB5_DES_40_CBC_SHA, + SSL_kKRB5, + SSL_aKRB5, + SSL_DES, + SSL_SHA1, + SSL_SSLV3, + SSL_EXPORT|SSL_EXP40, + SSL_HANDSHAKE_MAC_DEFAULT|TLS1_PRF, + 40, + 56, + }, + +/* Cipher 27 */ + { + 1, + SSL3_TXT_KRB5_RC2_40_CBC_SHA, + SSL3_CK_KRB5_RC2_40_CBC_SHA, + SSL_kKRB5, + SSL_aKRB5, + SSL_RC2, + SSL_SHA1, + SSL_SSLV3, + SSL_EXPORT|SSL_EXP40, + SSL_HANDSHAKE_MAC_DEFAULT|TLS1_PRF, + 40, + 128, + }, + +/* Cipher 28 */ + { + 1, + SSL3_TXT_KRB5_RC4_40_SHA, + SSL3_CK_KRB5_RC4_40_SHA, + SSL_kKRB5, + SSL_aKRB5, + SSL_RC4, + SSL_SHA1, + SSL_SSLV3, + SSL_EXPORT|SSL_EXP40, + SSL_HANDSHAKE_MAC_DEFAULT|TLS1_PRF, + 40, + 128, + }, + +/* Cipher 29 */ + { + 1, + SSL3_TXT_KRB5_DES_40_CBC_MD5, + SSL3_CK_KRB5_DES_40_CBC_MD5, + SSL_kKRB5, + SSL_aKRB5, + SSL_DES, + SSL_MD5, + SSL_SSLV3, + SSL_EXPORT|SSL_EXP40, + SSL_HANDSHAKE_MAC_DEFAULT|TLS1_PRF, + 40, + 56, + }, + +/* Cipher 2A */ + { + 1, + SSL3_TXT_KRB5_RC2_40_CBC_MD5, + SSL3_CK_KRB5_RC2_40_CBC_MD5, + SSL_kKRB5, + SSL_aKRB5, + SSL_RC2, + SSL_MD5, + SSL_SSLV3, + SSL_EXPORT|SSL_EXP40, + SSL_HANDSHAKE_MAC_DEFAULT|TLS1_PRF, + 40, + 128, + }, + +/* Cipher 2B */ + { + 1, + SSL3_TXT_KRB5_RC4_40_MD5, + SSL3_CK_KRB5_RC4_40_MD5, + SSL_kKRB5, + SSL_aKRB5, + SSL_RC4, + SSL_MD5, + SSL_SSLV3, + SSL_EXPORT|SSL_EXP40, + SSL_HANDSHAKE_MAC_DEFAULT|TLS1_PRF, + 40, + 128, + }, +#endif /* OPENSSL_NO_KRB5 */ + +/* New AES ciphersuites */ +/* Cipher 2F */ + { + 1, + TLS1_TXT_RSA_WITH_AES_128_SHA, + TLS1_CK_RSA_WITH_AES_128_SHA, + SSL_kRSA, + SSL_aRSA, + SSL_AES128, + SSL_SHA1, + SSL_TLSV1, + SSL_NOT_EXP|SSL_HIGH|SSL_FIPS, + SSL_HANDSHAKE_MAC_DEFAULT|TLS1_PRF, + 128, + 128, + }, +/* Cipher 30 */ + { + 0, + TLS1_TXT_DH_DSS_WITH_AES_128_SHA, + TLS1_CK_DH_DSS_WITH_AES_128_SHA, + SSL_kDHd, + SSL_aDH, + SSL_AES128, + SSL_SHA1, + SSL_TLSV1, + SSL_NOT_EXP|SSL_HIGH|SSL_FIPS, + SSL_HANDSHAKE_MAC_DEFAULT|TLS1_PRF, + 128, + 128, + }, +/* Cipher 31 */ + { + 0, + TLS1_TXT_DH_RSA_WITH_AES_128_SHA, + TLS1_CK_DH_RSA_WITH_AES_128_SHA, + SSL_kDHr, + SSL_aDH, + SSL_AES128, + SSL_SHA1, + SSL_TLSV1, + SSL_NOT_EXP|SSL_HIGH|SSL_FIPS, + SSL_HANDSHAKE_MAC_DEFAULT|TLS1_PRF, + 128, + 128, + }, +/* Cipher 32 */ + { + 1, + TLS1_TXT_DHE_DSS_WITH_AES_128_SHA, + TLS1_CK_DHE_DSS_WITH_AES_128_SHA, + SSL_kEDH, + SSL_aDSS, + SSL_AES128, + SSL_SHA1, + SSL_TLSV1, + SSL_NOT_EXP|SSL_HIGH|SSL_FIPS, + SSL_HANDSHAKE_MAC_DEFAULT|TLS1_PRF, + 128, + 128, + }, +/* Cipher 33 */ + { + 1, + TLS1_TXT_DHE_RSA_WITH_AES_128_SHA, + TLS1_CK_DHE_RSA_WITH_AES_128_SHA, + SSL_kEDH, + SSL_aRSA, + SSL_AES128, + SSL_SHA1, + SSL_TLSV1, + SSL_NOT_EXP|SSL_HIGH|SSL_FIPS, + SSL_HANDSHAKE_MAC_DEFAULT|TLS1_PRF, + 128, + 128, + }, +/* Cipher 34 */ + { + 1, + TLS1_TXT_ADH_WITH_AES_128_SHA, + TLS1_CK_ADH_WITH_AES_128_SHA, + SSL_kEDH, + SSL_aNULL, + SSL_AES128, + SSL_SHA1, + SSL_TLSV1, + SSL_NOT_EXP|SSL_HIGH|SSL_FIPS, + SSL_HANDSHAKE_MAC_DEFAULT|TLS1_PRF, + 128, + 128, + }, + +/* Cipher 35 */ + { + 1, + TLS1_TXT_RSA_WITH_AES_256_SHA, + TLS1_CK_RSA_WITH_AES_256_SHA, + SSL_kRSA, + SSL_aRSA, + SSL_AES256, + SSL_SHA1, + SSL_TLSV1, + SSL_NOT_EXP|SSL_HIGH|SSL_FIPS, + SSL_HANDSHAKE_MAC_DEFAULT|TLS1_PRF, + 256, + 256, + }, +/* Cipher 36 */ + { + 0, + TLS1_TXT_DH_DSS_WITH_AES_256_SHA, + TLS1_CK_DH_DSS_WITH_AES_256_SHA, + SSL_kDHd, + SSL_aDH, + SSL_AES256, + SSL_SHA1, + SSL_TLSV1, + SSL_NOT_EXP|SSL_HIGH|SSL_FIPS, + SSL_HANDSHAKE_MAC_DEFAULT|TLS1_PRF, + 256, + 256, + }, + +/* Cipher 37 */ + { + 0, /* not implemented (non-ephemeral DH) */ + TLS1_TXT_DH_RSA_WITH_AES_256_SHA, + TLS1_CK_DH_RSA_WITH_AES_256_SHA, + SSL_kDHr, + SSL_aDH, + SSL_AES256, + SSL_SHA1, + SSL_TLSV1, + SSL_NOT_EXP|SSL_HIGH|SSL_FIPS, + SSL_HANDSHAKE_MAC_DEFAULT|TLS1_PRF, + 256, + 256, + }, + +/* Cipher 38 */ + { + 1, + TLS1_TXT_DHE_DSS_WITH_AES_256_SHA, + TLS1_CK_DHE_DSS_WITH_AES_256_SHA, + SSL_kEDH, + SSL_aDSS, + SSL_AES256, + SSL_SHA1, + SSL_TLSV1, + SSL_NOT_EXP|SSL_HIGH|SSL_FIPS, + SSL_HANDSHAKE_MAC_DEFAULT|TLS1_PRF, + 256, + 256, + }, + +/* Cipher 39 */ + { + 1, + TLS1_TXT_DHE_RSA_WITH_AES_256_SHA, + TLS1_CK_DHE_RSA_WITH_AES_256_SHA, + SSL_kEDH, + SSL_aRSA, + SSL_AES256, + SSL_SHA1, + SSL_TLSV1, + SSL_NOT_EXP|SSL_HIGH|SSL_FIPS, + SSL_HANDSHAKE_MAC_DEFAULT|TLS1_PRF, + 256, + 256, + }, + + /* Cipher 3A */ + { + 1, + TLS1_TXT_ADH_WITH_AES_256_SHA, + TLS1_CK_ADH_WITH_AES_256_SHA, + SSL_kEDH, + SSL_aNULL, + SSL_AES256, + SSL_SHA1, + SSL_TLSV1, + SSL_NOT_EXP|SSL_HIGH|SSL_FIPS, + SSL_HANDSHAKE_MAC_DEFAULT|TLS1_PRF, + 256, + 256, + }, + +#ifndef OPENSSL_NO_CAMELLIA + /* Camellia ciphersuites from RFC4132 (128-bit portion) */ + + /* Cipher 41 */ + { + 1, + TLS1_TXT_RSA_WITH_CAMELLIA_128_CBC_SHA, + TLS1_CK_RSA_WITH_CAMELLIA_128_CBC_SHA, + SSL_kRSA, + SSL_aRSA, + SSL_CAMELLIA128, + SSL_SHA1, + SSL_TLSV1, + SSL_NOT_EXP|SSL_HIGH, + SSL_HANDSHAKE_MAC_DEFAULT|TLS1_PRF, + 128, + 128, + }, + + /* Cipher 42 */ + { + 0, /* not implemented (non-ephemeral DH) */ + TLS1_TXT_DH_DSS_WITH_CAMELLIA_128_CBC_SHA, + TLS1_CK_DH_DSS_WITH_CAMELLIA_128_CBC_SHA, + SSL_kDHd, + SSL_aDH, + SSL_CAMELLIA128, + SSL_SHA1, + SSL_TLSV1, + SSL_NOT_EXP|SSL_HIGH, + SSL_HANDSHAKE_MAC_DEFAULT|TLS1_PRF, + 128, + 128, + }, + + /* Cipher 43 */ + { + 0, /* not implemented (non-ephemeral DH) */ + TLS1_TXT_DH_RSA_WITH_CAMELLIA_128_CBC_SHA, + TLS1_CK_DH_RSA_WITH_CAMELLIA_128_CBC_SHA, + SSL_kDHr, + SSL_aDH, + SSL_CAMELLIA128, + SSL_SHA1, + SSL_TLSV1, + SSL_NOT_EXP|SSL_HIGH, + SSL_HANDSHAKE_MAC_DEFAULT|TLS1_PRF, + 128, + 128, + }, + + /* Cipher 44 */ + { + 1, + TLS1_TXT_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA, + TLS1_CK_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA, + SSL_kEDH, + SSL_aDSS, + SSL_CAMELLIA128, + SSL_SHA1, + SSL_TLSV1, + SSL_NOT_EXP|SSL_HIGH, + SSL_HANDSHAKE_MAC_DEFAULT|TLS1_PRF, + 128, + 128, + }, + + /* Cipher 45 */ + { + 1, + TLS1_TXT_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA, + TLS1_CK_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA, + SSL_kEDH, + SSL_aRSA, + SSL_CAMELLIA128, + SSL_SHA1, + SSL_TLSV1, + SSL_NOT_EXP|SSL_HIGH, + SSL_HANDSHAKE_MAC_DEFAULT|TLS1_PRF, + 128, + 128, + }, + + /* Cipher 46 */ + { + 1, + TLS1_TXT_ADH_WITH_CAMELLIA_128_CBC_SHA, + TLS1_CK_ADH_WITH_CAMELLIA_128_CBC_SHA, + SSL_kEDH, + SSL_aNULL, + SSL_CAMELLIA128, + SSL_SHA1, + SSL_TLSV1, + SSL_NOT_EXP|SSL_HIGH, + SSL_HANDSHAKE_MAC_DEFAULT|TLS1_PRF, + 128, + 128, + }, +#endif /* OPENSSL_NO_CAMELLIA */ + +#if TLS1_ALLOW_EXPERIMENTAL_CIPHERSUITES + /* New TLS Export CipherSuites from expired ID */ +#if 0 + /* Cipher 60 */ + { + 1, + TLS1_TXT_RSA_EXPORT1024_WITH_RC4_56_MD5, + TLS1_CK_RSA_EXPORT1024_WITH_RC4_56_MD5, + SSL_kRSA, + SSL_aRSA, + SSL_RC4, + SSL_MD5, + SSL_TLSV1, + SSL_EXPORT|SSL_EXP56, + SSL_HANDSHAKE_MAC_DEFAULT|TLS1_PRF, + 56, + 128, + }, + + /* Cipher 61 */ + { + 1, + TLS1_TXT_RSA_EXPORT1024_WITH_RC2_CBC_56_MD5, + TLS1_CK_RSA_EXPORT1024_WITH_RC2_CBC_56_MD5, + SSL_kRSA, + SSL_aRSA, + SSL_RC2, + SSL_MD5, + SSL_TLSV1, + SSL_EXPORT|SSL_EXP56, + SSL_HANDSHAKE_MAC_DEFAULT|TLS1_PRF, + 56, + 128, + }, +#endif + + /* Cipher 62 */ + { + 1, + TLS1_TXT_RSA_EXPORT1024_WITH_DES_CBC_SHA, + TLS1_CK_RSA_EXPORT1024_WITH_DES_CBC_SHA, + SSL_kRSA, + SSL_aRSA, + SSL_DES, + SSL_SHA1, + SSL_TLSV1, + SSL_EXPORT|SSL_EXP56, + SSL_HANDSHAKE_MAC_DEFAULT|TLS1_PRF, + 56, + 56, + }, + + /* Cipher 63 */ + { + 1, + TLS1_TXT_DHE_DSS_EXPORT1024_WITH_DES_CBC_SHA, + TLS1_CK_DHE_DSS_EXPORT1024_WITH_DES_CBC_SHA, + SSL_kEDH, + SSL_aDSS, + SSL_DES, + SSL_SHA1, + SSL_TLSV1, + SSL_EXPORT|SSL_EXP56, + SSL_HANDSHAKE_MAC_DEFAULT|TLS1_PRF, + 56, + 56, + }, + + /* Cipher 64 */ + { + 1, + TLS1_TXT_RSA_EXPORT1024_WITH_RC4_56_SHA, + TLS1_CK_RSA_EXPORT1024_WITH_RC4_56_SHA, + SSL_kRSA, + SSL_aRSA, + SSL_RC4, + SSL_SHA1, + SSL_TLSV1, + SSL_EXPORT|SSL_EXP56, + SSL_HANDSHAKE_MAC_DEFAULT|TLS1_PRF, + 56, + 128, + }, + + /* Cipher 65 */ + { + 1, + TLS1_TXT_DHE_DSS_EXPORT1024_WITH_RC4_56_SHA, + TLS1_CK_DHE_DSS_EXPORT1024_WITH_RC4_56_SHA, + SSL_kEDH, + SSL_aDSS, + SSL_RC4, + SSL_SHA1, + SSL_TLSV1, + SSL_EXPORT|SSL_EXP56, + SSL_HANDSHAKE_MAC_DEFAULT|TLS1_PRF, + 56, + 128, + }, + + /* Cipher 66 */ + { + 1, + TLS1_TXT_DHE_DSS_WITH_RC4_128_SHA, + TLS1_CK_DHE_DSS_WITH_RC4_128_SHA, + SSL_kEDH, + SSL_aDSS, + SSL_RC4, + SSL_SHA1, + SSL_TLSV1, + SSL_NOT_EXP|SSL_MEDIUM, + SSL_HANDSHAKE_MAC_DEFAULT|TLS1_PRF, + 128, + 128, + }, +#endif + { + 1, + "GOST94-GOST89-GOST89", + 0x3000080, + SSL_kGOST, + SSL_aGOST94, + SSL_eGOST2814789CNT, + SSL_GOST89MAC, + SSL_TLSV1, + SSL_NOT_EXP|SSL_HIGH, + SSL_HANDSHAKE_MAC_GOST94|TLS1_PRF_GOST94|TLS1_STREAM_MAC, + 256, + 256 + }, + { + 1, + "GOST2001-GOST89-GOST89", + 0x3000081, + SSL_kGOST, + SSL_aGOST01, + SSL_eGOST2814789CNT, + SSL_GOST89MAC, + SSL_TLSV1, + SSL_NOT_EXP|SSL_HIGH, + SSL_HANDSHAKE_MAC_GOST94|TLS1_PRF_GOST94|TLS1_STREAM_MAC, + 256, + 256 + }, + { + 1, + "GOST94-NULL-GOST94", + 0x3000082, + SSL_kGOST, + SSL_aGOST94, + SSL_eNULL, + SSL_GOST94, + SSL_TLSV1, + SSL_NOT_EXP|SSL_STRONG_NONE, + SSL_HANDSHAKE_MAC_GOST94|TLS1_PRF_GOST94, + 0, + 0 + }, + { + 1, + "GOST2001-NULL-GOST94", + 0x3000083, + SSL_kGOST, + SSL_aGOST01, + SSL_eNULL, + SSL_GOST94, + SSL_TLSV1, + SSL_NOT_EXP|SSL_STRONG_NONE, + SSL_HANDSHAKE_MAC_GOST94|TLS1_PRF_GOST94, + 0, + 0 + }, + +#ifndef OPENSSL_NO_CAMELLIA + /* Camellia ciphersuites from RFC4132 (256-bit portion) */ + + /* Cipher 84 */ + { + 1, + TLS1_TXT_RSA_WITH_CAMELLIA_256_CBC_SHA, + TLS1_CK_RSA_WITH_CAMELLIA_256_CBC_SHA, + SSL_kRSA, + SSL_aRSA, + SSL_CAMELLIA256, + SSL_SHA1, + SSL_TLSV1, + SSL_NOT_EXP|SSL_HIGH, + SSL_HANDSHAKE_MAC_DEFAULT|TLS1_PRF, + 256, + 256, + }, + /* Cipher 85 */ + { + 0, /* not implemented (non-ephemeral DH) */ + TLS1_TXT_DH_DSS_WITH_CAMELLIA_256_CBC_SHA, + TLS1_CK_DH_DSS_WITH_CAMELLIA_256_CBC_SHA, + SSL_kDHd, + SSL_aDH, + SSL_CAMELLIA256, + SSL_SHA1, + SSL_TLSV1, + SSL_NOT_EXP|SSL_HIGH, + SSL_HANDSHAKE_MAC_DEFAULT|TLS1_PRF, + 256, + 256, + }, + + /* Cipher 86 */ + { + 0, /* not implemented (non-ephemeral DH) */ + TLS1_TXT_DH_RSA_WITH_CAMELLIA_256_CBC_SHA, + TLS1_CK_DH_RSA_WITH_CAMELLIA_256_CBC_SHA, + SSL_kDHr, + SSL_aDH, + SSL_CAMELLIA256, + SSL_SHA1, + SSL_TLSV1, + SSL_NOT_EXP|SSL_HIGH, + SSL_HANDSHAKE_MAC_DEFAULT|TLS1_PRF, + 256, + 256, + }, + + /* Cipher 87 */ + { + 1, + TLS1_TXT_DHE_DSS_WITH_CAMELLIA_256_CBC_SHA, + TLS1_CK_DHE_DSS_WITH_CAMELLIA_256_CBC_SHA, + SSL_kEDH, + SSL_aDSS, + SSL_CAMELLIA256, + SSL_SHA1, + SSL_TLSV1, + SSL_NOT_EXP|SSL_HIGH, + SSL_HANDSHAKE_MAC_DEFAULT|TLS1_PRF, + 256, + 256, + }, + + /* Cipher 88 */ + { + 1, + TLS1_TXT_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA, + TLS1_CK_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA, + SSL_kEDH, + SSL_aRSA, + SSL_CAMELLIA256, + SSL_SHA1, + SSL_TLSV1, + SSL_NOT_EXP|SSL_HIGH, + SSL_HANDSHAKE_MAC_DEFAULT|TLS1_PRF, + 256, + 256, + }, + + /* Cipher 89 */ + { + 1, + TLS1_TXT_ADH_WITH_CAMELLIA_256_CBC_SHA, + TLS1_CK_ADH_WITH_CAMELLIA_256_CBC_SHA, + SSL_kEDH, + SSL_aNULL, + SSL_CAMELLIA256, + SSL_SHA1, + SSL_TLSV1, + SSL_NOT_EXP|SSL_HIGH, + SSL_HANDSHAKE_MAC_DEFAULT|TLS1_PRF, + 256, + 256, + }, +#endif /* OPENSSL_NO_CAMELLIA */ + +#ifndef OPENSSL_NO_PSK + /* Cipher 8A */ + { + 1, + TLS1_TXT_PSK_WITH_RC4_128_SHA, + TLS1_CK_PSK_WITH_RC4_128_SHA, + SSL_kPSK, + SSL_aPSK, + SSL_RC4, + SSL_SHA1, + SSL_TLSV1, + SSL_NOT_EXP|SSL_MEDIUM, + SSL_HANDSHAKE_MAC_DEFAULT|TLS1_PRF, + 128, + 128, + }, + + /* Cipher 8B */ + { + 1, + TLS1_TXT_PSK_WITH_3DES_EDE_CBC_SHA, + TLS1_CK_PSK_WITH_3DES_EDE_CBC_SHA, + SSL_kPSK, + SSL_aPSK, + SSL_3DES, + SSL_SHA1, + SSL_TLSV1, + SSL_NOT_EXP|SSL_HIGH, + SSL_HANDSHAKE_MAC_DEFAULT|TLS1_PRF, + 168, + 168, + }, + + /* Cipher 8C */ + { + 1, + TLS1_TXT_PSK_WITH_AES_128_CBC_SHA, + TLS1_CK_PSK_WITH_AES_128_CBC_SHA, + SSL_kPSK, + SSL_aPSK, + SSL_AES128, + SSL_SHA1, + SSL_TLSV1, + SSL_NOT_EXP|SSL_HIGH, + SSL_HANDSHAKE_MAC_DEFAULT|TLS1_PRF, + 128, + 128, + }, + + /* Cipher 8D */ + { + 1, + TLS1_TXT_PSK_WITH_AES_256_CBC_SHA, + TLS1_CK_PSK_WITH_AES_256_CBC_SHA, + SSL_kPSK, + SSL_aPSK, + SSL_AES256, + SSL_SHA1, + SSL_TLSV1, + SSL_NOT_EXP|SSL_HIGH, + SSL_HANDSHAKE_MAC_DEFAULT|TLS1_PRF, + 256, + 256, + }, +#endif /* OPENSSL_NO_PSK */ + +#ifndef OPENSSL_NO_SEED + /* SEED ciphersuites from RFC4162 */ + + /* Cipher 96 */ + { + 1, + TLS1_TXT_RSA_WITH_SEED_SHA, + TLS1_CK_RSA_WITH_SEED_SHA, + SSL_kRSA, + SSL_aRSA, + SSL_SEED, + SSL_SHA1, + SSL_TLSV1, + SSL_NOT_EXP|SSL_MEDIUM, + SSL_HANDSHAKE_MAC_DEFAULT|TLS1_PRF, + 128, + 128, + }, + + /* Cipher 97 */ + { + 0, /* not implemented (non-ephemeral DH) */ + TLS1_TXT_DH_DSS_WITH_SEED_SHA, + TLS1_CK_DH_DSS_WITH_SEED_SHA, + SSL_kDHd, + SSL_aDH, + SSL_SEED, + SSL_SHA1, + SSL_TLSV1, + SSL_NOT_EXP|SSL_MEDIUM, + SSL_HANDSHAKE_MAC_DEFAULT|TLS1_PRF, + 128, + 128, + }, + + /* Cipher 98 */ + { + 0, /* not implemented (non-ephemeral DH) */ + TLS1_TXT_DH_RSA_WITH_SEED_SHA, + TLS1_CK_DH_RSA_WITH_SEED_SHA, + SSL_kDHr, + SSL_aDH, + SSL_SEED, + SSL_SHA1, + SSL_TLSV1, + SSL_NOT_EXP|SSL_MEDIUM, + SSL_HANDSHAKE_MAC_DEFAULT|TLS1_PRF, + 128, + 128, + }, + + /* Cipher 99 */ + { + 1, + TLS1_TXT_DHE_DSS_WITH_SEED_SHA, + TLS1_CK_DHE_DSS_WITH_SEED_SHA, + SSL_kEDH, + SSL_aDSS, + SSL_SEED, + SSL_SHA1, + SSL_TLSV1, + SSL_NOT_EXP|SSL_MEDIUM, + SSL_HANDSHAKE_MAC_DEFAULT|TLS1_PRF, + 128, + 128, + }, + + /* Cipher 9A */ + { + 1, + TLS1_TXT_DHE_RSA_WITH_SEED_SHA, + TLS1_CK_DHE_RSA_WITH_SEED_SHA, + SSL_kEDH, + SSL_aRSA, + SSL_SEED, + SSL_SHA1, + SSL_TLSV1, + SSL_NOT_EXP|SSL_MEDIUM, + SSL_HANDSHAKE_MAC_DEFAULT|TLS1_PRF, + 128, + 128, + }, + + /* Cipher 9B */ + { + 1, + TLS1_TXT_ADH_WITH_SEED_SHA, + TLS1_CK_ADH_WITH_SEED_SHA, + SSL_kEDH, + SSL_aNULL, + SSL_SEED, + SSL_SHA1, + SSL_TLSV1, + SSL_NOT_EXP|SSL_MEDIUM, + SSL_HANDSHAKE_MAC_DEFAULT|TLS1_PRF, + 128, + 128, + }, + +#endif /* OPENSSL_NO_SEED */ + +#ifndef OPENSSL_NO_ECDH + /* Cipher C001 */ + { + 1, + TLS1_TXT_ECDH_ECDSA_WITH_NULL_SHA, + TLS1_CK_ECDH_ECDSA_WITH_NULL_SHA, + SSL_kECDHe, + SSL_aECDH, + SSL_eNULL, + SSL_SHA1, + SSL_TLSV1, + SSL_NOT_EXP|SSL_STRONG_NONE, + SSL_HANDSHAKE_MAC_DEFAULT|TLS1_PRF, + 0, + 0, + }, + + /* Cipher C002 */ + { + 1, + TLS1_TXT_ECDH_ECDSA_WITH_RC4_128_SHA, + TLS1_CK_ECDH_ECDSA_WITH_RC4_128_SHA, + SSL_kECDHe, + SSL_aECDH, + SSL_RC4, + SSL_SHA1, + SSL_TLSV1, + SSL_NOT_EXP|SSL_MEDIUM, + SSL_HANDSHAKE_MAC_DEFAULT|TLS1_PRF, + 128, + 128, + }, + + /* Cipher C003 */ + { + 1, + TLS1_TXT_ECDH_ECDSA_WITH_DES_192_CBC3_SHA, + TLS1_CK_ECDH_ECDSA_WITH_DES_192_CBC3_SHA, + SSL_kECDHe, + SSL_aECDH, + SSL_3DES, + SSL_SHA1, + SSL_TLSV1, + SSL_NOT_EXP|SSL_HIGH, + SSL_HANDSHAKE_MAC_DEFAULT|TLS1_PRF, + 168, + 168, + }, + + /* Cipher C004 */ + { + 1, + TLS1_TXT_ECDH_ECDSA_WITH_AES_128_CBC_SHA, + TLS1_CK_ECDH_ECDSA_WITH_AES_128_CBC_SHA, + SSL_kECDHe, + SSL_aECDH, + SSL_AES128, + SSL_SHA1, + SSL_TLSV1, + SSL_NOT_EXP|SSL_HIGH, + SSL_HANDSHAKE_MAC_DEFAULT|TLS1_PRF, + 128, + 128, + }, + + /* Cipher C005 */ + { + 1, + TLS1_TXT_ECDH_ECDSA_WITH_AES_256_CBC_SHA, + TLS1_CK_ECDH_ECDSA_WITH_AES_256_CBC_SHA, + SSL_kECDHe, + SSL_aECDH, + SSL_AES256, + SSL_SHA1, + SSL_TLSV1, + SSL_NOT_EXP|SSL_HIGH, + SSL_HANDSHAKE_MAC_DEFAULT|TLS1_PRF, + 256, + 256, + }, + + /* Cipher C006 */ + { + 1, + TLS1_TXT_ECDHE_ECDSA_WITH_NULL_SHA, + TLS1_CK_ECDHE_ECDSA_WITH_NULL_SHA, + SSL_kEECDH, + SSL_aECDSA, + SSL_eNULL, + SSL_SHA1, + SSL_TLSV1, + SSL_NOT_EXP|SSL_STRONG_NONE, + SSL_HANDSHAKE_MAC_DEFAULT|TLS1_PRF, + 0, + 0, + }, + + /* Cipher C007 */ + { + 1, + TLS1_TXT_ECDHE_ECDSA_WITH_RC4_128_SHA, + TLS1_CK_ECDHE_ECDSA_WITH_RC4_128_SHA, + SSL_kEECDH, + SSL_aECDSA, + SSL_RC4, + SSL_SHA1, + SSL_TLSV1, + SSL_NOT_EXP|SSL_MEDIUM, + SSL_HANDSHAKE_MAC_DEFAULT|TLS1_PRF, + 128, + 128, + }, + + /* Cipher C008 */ + { + 1, + TLS1_TXT_ECDHE_ECDSA_WITH_DES_192_CBC3_SHA, + TLS1_CK_ECDHE_ECDSA_WITH_DES_192_CBC3_SHA, + SSL_kEECDH, + SSL_aECDSA, + SSL_3DES, + SSL_SHA1, + SSL_TLSV1, + SSL_NOT_EXP|SSL_HIGH, + SSL_HANDSHAKE_MAC_DEFAULT|TLS1_PRF, + 168, + 168, + }, + + /* Cipher C009 */ + { + 1, + TLS1_TXT_ECDHE_ECDSA_WITH_AES_128_CBC_SHA, + TLS1_CK_ECDHE_ECDSA_WITH_AES_128_CBC_SHA, + SSL_kEECDH, + SSL_aECDSA, + SSL_AES128, + SSL_SHA1, + SSL_TLSV1, + SSL_NOT_EXP|SSL_HIGH, + SSL_HANDSHAKE_MAC_DEFAULT|TLS1_PRF, + 128, + 128, + }, + + /* Cipher C00A */ + { + 1, + TLS1_TXT_ECDHE_ECDSA_WITH_AES_256_CBC_SHA, + TLS1_CK_ECDHE_ECDSA_WITH_AES_256_CBC_SHA, + SSL_kEECDH, + SSL_aECDSA, + SSL_AES256, + SSL_SHA1, + SSL_TLSV1, + SSL_NOT_EXP|SSL_HIGH, + SSL_HANDSHAKE_MAC_DEFAULT|TLS1_PRF, + 256, + 256, + }, + + /* Cipher C00B */ + { + 1, + TLS1_TXT_ECDH_RSA_WITH_NULL_SHA, + TLS1_CK_ECDH_RSA_WITH_NULL_SHA, + SSL_kECDHr, + SSL_aECDH, + SSL_eNULL, + SSL_SHA1, + SSL_TLSV1, + SSL_NOT_EXP|SSL_STRONG_NONE, + SSL_HANDSHAKE_MAC_DEFAULT|TLS1_PRF, + 0, + 0, + }, + + /* Cipher C00C */ + { + 1, + TLS1_TXT_ECDH_RSA_WITH_RC4_128_SHA, + TLS1_CK_ECDH_RSA_WITH_RC4_128_SHA, + SSL_kECDHr, + SSL_aECDH, + SSL_RC4, + SSL_SHA1, + SSL_TLSV1, + SSL_NOT_EXP|SSL_MEDIUM, + SSL_HANDSHAKE_MAC_DEFAULT|TLS1_PRF, + 128, + 128, + }, + + /* Cipher C00D */ + { + 1, + TLS1_TXT_ECDH_RSA_WITH_DES_192_CBC3_SHA, + TLS1_CK_ECDH_RSA_WITH_DES_192_CBC3_SHA, + SSL_kECDHr, + SSL_aECDH, + SSL_3DES, + SSL_SHA1, + SSL_TLSV1, + SSL_NOT_EXP|SSL_HIGH, + SSL_HANDSHAKE_MAC_DEFAULT|TLS1_PRF, + 168, + 168, + }, + + /* Cipher C00E */ + { + 1, + TLS1_TXT_ECDH_RSA_WITH_AES_128_CBC_SHA, + TLS1_CK_ECDH_RSA_WITH_AES_128_CBC_SHA, + SSL_kECDHr, + SSL_aECDH, + SSL_AES128, + SSL_SHA1, + SSL_TLSV1, + SSL_NOT_EXP|SSL_HIGH, + SSL_HANDSHAKE_MAC_DEFAULT|TLS1_PRF, + 128, + 128, + }, + + /* Cipher C00F */ + { + 1, + TLS1_TXT_ECDH_RSA_WITH_AES_256_CBC_SHA, + TLS1_CK_ECDH_RSA_WITH_AES_256_CBC_SHA, + SSL_kECDHr, + SSL_aECDH, + SSL_AES256, + SSL_SHA1, + SSL_TLSV1, + SSL_NOT_EXP|SSL_HIGH, + SSL_HANDSHAKE_MAC_DEFAULT|TLS1_PRF, + 256, + 256, + }, + + /* Cipher C010 */ + { + 1, + TLS1_TXT_ECDHE_RSA_WITH_NULL_SHA, + TLS1_CK_ECDHE_RSA_WITH_NULL_SHA, + SSL_kEECDH, + SSL_aRSA, + SSL_eNULL, + SSL_SHA1, + SSL_TLSV1, + SSL_NOT_EXP|SSL_STRONG_NONE, + SSL_HANDSHAKE_MAC_DEFAULT|TLS1_PRF, + 0, + 0, + }, + + /* Cipher C011 */ + { + 1, + TLS1_TXT_ECDHE_RSA_WITH_RC4_128_SHA, + TLS1_CK_ECDHE_RSA_WITH_RC4_128_SHA, + SSL_kEECDH, + SSL_aRSA, + SSL_RC4, + SSL_SHA1, + SSL_TLSV1, + SSL_NOT_EXP|SSL_MEDIUM, + SSL_HANDSHAKE_MAC_DEFAULT|TLS1_PRF, + 128, + 128, + }, + + /* Cipher C012 */ + { + 1, + TLS1_TXT_ECDHE_RSA_WITH_DES_192_CBC3_SHA, + TLS1_CK_ECDHE_RSA_WITH_DES_192_CBC3_SHA, + SSL_kEECDH, + SSL_aRSA, + SSL_3DES, + SSL_SHA1, + SSL_TLSV1, + SSL_NOT_EXP|SSL_HIGH, + SSL_HANDSHAKE_MAC_DEFAULT|TLS1_PRF, + 168, + 168, + }, + + /* Cipher C013 */ + { + 1, + TLS1_TXT_ECDHE_RSA_WITH_AES_128_CBC_SHA, + TLS1_CK_ECDHE_RSA_WITH_AES_128_CBC_SHA, + SSL_kEECDH, + SSL_aRSA, + SSL_AES128, + SSL_SHA1, + SSL_TLSV1, + SSL_NOT_EXP|SSL_HIGH, + SSL_HANDSHAKE_MAC_DEFAULT|TLS1_PRF, + 128, + 128, + }, + + /* Cipher C014 */ + { + 1, + TLS1_TXT_ECDHE_RSA_WITH_AES_256_CBC_SHA, + TLS1_CK_ECDHE_RSA_WITH_AES_256_CBC_SHA, + SSL_kEECDH, + SSL_aRSA, + SSL_AES256, + SSL_SHA1, + SSL_TLSV1, + SSL_NOT_EXP|SSL_HIGH, + SSL_HANDSHAKE_MAC_DEFAULT|TLS1_PRF, + 256, + 256, + }, + + /* Cipher C015 */ + { + 1, + TLS1_TXT_ECDH_anon_WITH_NULL_SHA, + TLS1_CK_ECDH_anon_WITH_NULL_SHA, + SSL_kEECDH, + SSL_aNULL, + SSL_eNULL, + SSL_SHA1, + SSL_TLSV1, + SSL_NOT_EXP|SSL_STRONG_NONE, + SSL_HANDSHAKE_MAC_DEFAULT|TLS1_PRF, + 0, + 0, + }, + + /* Cipher C016 */ + { + 1, + TLS1_TXT_ECDH_anon_WITH_RC4_128_SHA, + TLS1_CK_ECDH_anon_WITH_RC4_128_SHA, + SSL_kEECDH, + SSL_aNULL, + SSL_RC4, + SSL_SHA1, + SSL_TLSV1, + SSL_NOT_EXP|SSL_MEDIUM, + SSL_HANDSHAKE_MAC_DEFAULT|TLS1_PRF, + 128, + 128, + }, + + /* Cipher C017 */ + { + 1, + TLS1_TXT_ECDH_anon_WITH_DES_192_CBC3_SHA, + TLS1_CK_ECDH_anon_WITH_DES_192_CBC3_SHA, + SSL_kEECDH, + SSL_aNULL, + SSL_3DES, + SSL_SHA1, + SSL_TLSV1, + SSL_NOT_EXP|SSL_HIGH, + SSL_HANDSHAKE_MAC_DEFAULT|TLS1_PRF, + 168, + 168, + }, + + /* Cipher C018 */ + { + 1, + TLS1_TXT_ECDH_anon_WITH_AES_128_CBC_SHA, + TLS1_CK_ECDH_anon_WITH_AES_128_CBC_SHA, + SSL_kEECDH, + SSL_aNULL, + SSL_AES128, + SSL_SHA1, + SSL_TLSV1, + SSL_NOT_EXP|SSL_HIGH, + SSL_HANDSHAKE_MAC_DEFAULT|TLS1_PRF, + 128, + 128, + }, + + /* Cipher C019 */ + { + 1, + TLS1_TXT_ECDH_anon_WITH_AES_256_CBC_SHA, + TLS1_CK_ECDH_anon_WITH_AES_256_CBC_SHA, + SSL_kEECDH, + SSL_aNULL, + SSL_AES256, + SSL_SHA1, + SSL_TLSV1, + SSL_NOT_EXP|SSL_HIGH, + SSL_HANDSHAKE_MAC_DEFAULT|TLS1_PRF, + 256, + 256, + }, +#endif /* OPENSSL_NO_ECDH */ + +#ifdef TEMP_GOST_TLS +/* Cipher FF00 */ + { + 1, + "GOST-MD5", + 0x0300ff00, + SSL_kRSA, + SSL_aRSA, + SSL_eGOST2814789CNT, + SSL_MD5, + SSL_TLSV1, + SSL_NOT_EXP|SSL_HIGH, + SSL_HANDSHAKE_MAC_DEFAULT|TLS1_PRF, + 256, + 256, + }, + { + 1, + "GOST-GOST94", + 0x0300ff01, + SSL_kRSA, + SSL_aRSA, + SSL_eGOST2814789CNT, + SSL_GOST94, + SSL_TLSV1, + SSL_NOT_EXP|SSL_HIGH, + SSL_HANDSHAKE_MAC_DEFAULT|TLS1_PRF, + 256, + 256 + }, + { + 1, + "GOST-GOST89MAC", + 0x0300ff02, + SSL_kRSA, + SSL_aRSA, + SSL_eGOST2814789CNT, + SSL_GOST89MAC, + SSL_TLSV1, + SSL_NOT_EXP|SSL_HIGH, + SSL_HANDSHAKE_MAC_DEFAULT|TLS1_PRF, + 256, + 256 + }, + { + 1, + "GOST-GOST89STREAM", + 0x0300ff03, + SSL_kRSA, + SSL_aRSA, + SSL_eGOST2814789CNT, + SSL_GOST89MAC, + SSL_TLSV1, + SSL_NOT_EXP|SSL_HIGH, + SSL_HANDSHAKE_MAC_DEFAULT|TLS1_PRF|TLS1_STREAM_MAC, + 256, + 256 + }, +#endif + +/* end of list */ + }; + +SSL3_ENC_METHOD SSLv3_enc_data={ + ssl3_enc, + n_ssl3_mac, + ssl3_setup_key_block, + ssl3_generate_master_secret, + ssl3_change_cipher_state, + ssl3_final_finish_mac, + MD5_DIGEST_LENGTH+SHA_DIGEST_LENGTH, + ssl3_cert_verify_mac, + SSL3_MD_CLIENT_FINISHED_CONST,4, + SSL3_MD_SERVER_FINISHED_CONST,4, + ssl3_alert_code, + (int (*)(SSL *, unsigned char *, size_t, const char *, + size_t, const unsigned char *, size_t, + int use_context)) ssl_undefined_function, + }; + +long ssl3_default_timeout(void) + { + /* 2 hours, the 24 hours mentioned in the SSLv3 spec + * is way too long for http, the cache would over fill */ + return(60*60*2); + } + +int ssl3_num_ciphers(void) + { + return(SSL3_NUM_CIPHERS); + } + +const SSL_CIPHER *ssl3_get_cipher(unsigned int u) + { + if (u < SSL3_NUM_CIPHERS) + return(&(ssl3_ciphers[SSL3_NUM_CIPHERS-1-u])); + else + return(NULL); + } + +int ssl3_pending(const SSL *s) + { + if (s->rstate == SSL_ST_READ_BODY) + return 0; + + return (s->s3->rrec.type == SSL3_RT_APPLICATION_DATA) ? s->s3->rrec.length : 0; + } + +int ssl3_new(SSL *s) + { + SSL3_STATE *s3; + + if ((s3=OPENSSL_malloc(sizeof *s3)) == NULL) goto err; + memset(s3,0,sizeof *s3); + memset(s3->rrec.seq_num,0,sizeof(s3->rrec.seq_num)); + memset(s3->wrec.seq_num,0,sizeof(s3->wrec.seq_num)); + + s->s3=s3; + + s->method->ssl_clear(s); + return(1); +err: + return(0); + } + +void ssl3_free(SSL *s) + { + if(s == NULL) + return; + +#ifdef TLSEXT_TYPE_opaque_prf_input + if (s->s3->client_opaque_prf_input != NULL) + OPENSSL_free(s->s3->client_opaque_prf_input); + if (s->s3->server_opaque_prf_input != NULL) + OPENSSL_free(s->s3->server_opaque_prf_input); +#endif + + ssl3_cleanup_key_block(s); + if (s->s3->rbuf.buf != NULL) + ssl3_release_read_buffer(s); + if (s->s3->wbuf.buf != NULL) + ssl3_release_write_buffer(s); + if (s->s3->rrec.comp != NULL) + OPENSSL_free(s->s3->rrec.comp); +#ifndef OPENSSL_NO_DH + if (s->s3->tmp.dh != NULL) + DH_free(s->s3->tmp.dh); +#endif +#ifndef OPENSSL_NO_ECDH + if (s->s3->tmp.ecdh != NULL) + EC_KEY_free(s->s3->tmp.ecdh); +#endif + + if (s->s3->tmp.ca_names != NULL) + sk_X509_NAME_pop_free(s->s3->tmp.ca_names,X509_NAME_free); + if (s->s3->handshake_buffer) { + BIO_free(s->s3->handshake_buffer); + } + if (s->s3->handshake_dgst) ssl3_free_digest_list(s); + OPENSSL_cleanse(s->s3,sizeof *s->s3); + OPENSSL_free(s->s3); + s->s3=NULL; + } + +void ssl3_clear(SSL *s) + { + unsigned char *rp,*wp; + size_t rlen, wlen; + int init_extra; + +#ifdef TLSEXT_TYPE_opaque_prf_input + if (s->s3->client_opaque_prf_input != NULL) + OPENSSL_free(s->s3->client_opaque_prf_input); + s->s3->client_opaque_prf_input = NULL; + if (s->s3->server_opaque_prf_input != NULL) + OPENSSL_free(s->s3->server_opaque_prf_input); + s->s3->server_opaque_prf_input = NULL; +#endif + + ssl3_cleanup_key_block(s); + if (s->s3->tmp.ca_names != NULL) + sk_X509_NAME_pop_free(s->s3->tmp.ca_names,X509_NAME_free); + + if (s->s3->rrec.comp != NULL) + { + OPENSSL_free(s->s3->rrec.comp); + s->s3->rrec.comp=NULL; + } +#ifndef OPENSSL_NO_DH + if (s->s3->tmp.dh != NULL) + { + DH_free(s->s3->tmp.dh); + s->s3->tmp.dh = NULL; + } +#endif +#ifndef OPENSSL_NO_ECDH + if (s->s3->tmp.ecdh != NULL) + { + EC_KEY_free(s->s3->tmp.ecdh); + s->s3->tmp.ecdh = NULL; + } +#endif + + rp = s->s3->rbuf.buf; + wp = s->s3->wbuf.buf; + rlen = s->s3->rbuf.len; + wlen = s->s3->wbuf.len; + init_extra = s->s3->init_extra; + if (s->s3->handshake_buffer) { + BIO_free(s->s3->handshake_buffer); + s->s3->handshake_buffer = NULL; + } + if (s->s3->handshake_dgst) { + ssl3_free_digest_list(s); + } + memset(s->s3,0,sizeof *s->s3); + s->s3->rbuf.buf = rp; + s->s3->wbuf.buf = wp; + s->s3->rbuf.len = rlen; + s->s3->wbuf.len = wlen; + s->s3->init_extra = init_extra; + + ssl_free_wbio_buffer(s); + + s->packet_length=0; + s->s3->renegotiate=0; + s->s3->total_renegotiations=0; + s->s3->num_renegotiations=0; + s->s3->in_read_app_data=0; + s->version=SSL3_VERSION; + +#if !defined(OPENSSL_NO_TLSEXT) && !defined(OPENSSL_NO_NEXTPROTONEG) + if (s->next_proto_negotiated) + { + OPENSSL_free(s->next_proto_negotiated); + s->next_proto_negotiated = NULL; + s->next_proto_negotiated_len = 0; + } +#endif + } + +long ssl3_ctrl(SSL *s, int cmd, long larg, void *parg) + { + int ret=0; + +#if !defined(OPENSSL_NO_DSA) || !defined(OPENSSL_NO_RSA) + if ( +#ifndef OPENSSL_NO_RSA + cmd == SSL_CTRL_SET_TMP_RSA || + cmd == SSL_CTRL_SET_TMP_RSA_CB || +#endif +#ifndef OPENSSL_NO_DSA + cmd == SSL_CTRL_SET_TMP_DH || + cmd == SSL_CTRL_SET_TMP_DH_CB || +#endif + 0) + { + if (!ssl_cert_inst(&s->cert)) + { + SSLerr(SSL_F_SSL3_CTRL, ERR_R_MALLOC_FAILURE); + return(0); + } + } +#endif + + switch (cmd) + { + case SSL_CTRL_GET_SESSION_REUSED: + ret=s->hit; + break; + case SSL_CTRL_GET_CLIENT_CERT_REQUEST: + break; + case SSL_CTRL_GET_NUM_RENEGOTIATIONS: + ret=s->s3->num_renegotiations; + break; + case SSL_CTRL_CLEAR_NUM_RENEGOTIATIONS: + ret=s->s3->num_renegotiations; + s->s3->num_renegotiations=0; + break; + case SSL_CTRL_GET_TOTAL_RENEGOTIATIONS: + ret=s->s3->total_renegotiations; + break; + case SSL_CTRL_GET_FLAGS: + ret=(int)(s->s3->flags); + break; +#ifndef OPENSSL_NO_RSA + case SSL_CTRL_NEED_TMP_RSA: + if ((s->cert != NULL) && (s->cert->rsa_tmp == NULL) && + ((s->cert->pkeys[SSL_PKEY_RSA_ENC].privatekey == NULL) || + (EVP_PKEY_size(s->cert->pkeys[SSL_PKEY_RSA_ENC].privatekey) > (512/8)))) + ret = 1; + break; + case SSL_CTRL_SET_TMP_RSA: + { + RSA *rsa = (RSA *)parg; + if (rsa == NULL) + { + SSLerr(SSL_F_SSL3_CTRL, ERR_R_PASSED_NULL_PARAMETER); + return(ret); + } + if ((rsa = RSAPrivateKey_dup(rsa)) == NULL) + { + SSLerr(SSL_F_SSL3_CTRL, ERR_R_RSA_LIB); + return(ret); + } + if (s->cert->rsa_tmp != NULL) + RSA_free(s->cert->rsa_tmp); + s->cert->rsa_tmp = rsa; + ret = 1; + } + break; + case SSL_CTRL_SET_TMP_RSA_CB: + { + SSLerr(SSL_F_SSL3_CTRL, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED); + return(ret); + } + break; +#endif +#ifndef OPENSSL_NO_DH + case SSL_CTRL_SET_TMP_DH: + { + DH *dh = (DH *)parg; + if (dh == NULL) + { + SSLerr(SSL_F_SSL3_CTRL, ERR_R_PASSED_NULL_PARAMETER); + return(ret); + } + if ((dh = DHparams_dup(dh)) == NULL) + { + SSLerr(SSL_F_SSL3_CTRL, ERR_R_DH_LIB); + return(ret); + } + if (!(s->options & SSL_OP_SINGLE_DH_USE)) + { + if (!DH_generate_key(dh)) + { + DH_free(dh); + SSLerr(SSL_F_SSL3_CTRL, ERR_R_DH_LIB); + return(ret); + } + } + if (s->cert->dh_tmp != NULL) + DH_free(s->cert->dh_tmp); + s->cert->dh_tmp = dh; + ret = 1; + } + break; + case SSL_CTRL_SET_TMP_DH_CB: + { + SSLerr(SSL_F_SSL3_CTRL, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED); + return(ret); + } + break; +#endif +#ifndef OPENSSL_NO_ECDH + case SSL_CTRL_SET_TMP_ECDH: + { + EC_KEY *ecdh = NULL; + + if (parg == NULL) + { + SSLerr(SSL_F_SSL3_CTRL, ERR_R_PASSED_NULL_PARAMETER); + return(ret); + } + if (!EC_KEY_up_ref((EC_KEY *)parg)) + { + SSLerr(SSL_F_SSL3_CTRL,ERR_R_ECDH_LIB); + return(ret); + } + ecdh = (EC_KEY *)parg; + if (!(s->options & SSL_OP_SINGLE_ECDH_USE)) + { + if (!EC_KEY_generate_key(ecdh)) + { + EC_KEY_free(ecdh); + SSLerr(SSL_F_SSL3_CTRL,ERR_R_ECDH_LIB); + return(ret); + } + } + if (s->cert->ecdh_tmp != NULL) + EC_KEY_free(s->cert->ecdh_tmp); + s->cert->ecdh_tmp = ecdh; + ret = 1; + } + break; + case SSL_CTRL_SET_TMP_ECDH_CB: + { + SSLerr(SSL_F_SSL3_CTRL, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED); + return(ret); + } + break; +#endif /* !OPENSSL_NO_ECDH */ +#ifndef OPENSSL_NO_TLSEXT + case SSL_CTRL_SET_TLSEXT_HOSTNAME: + if (larg == TLSEXT_NAMETYPE_host_name) + { + if (s->tlsext_hostname != NULL) + OPENSSL_free(s->tlsext_hostname); + s->tlsext_hostname = NULL; + + ret = 1; + if (parg == NULL) + break; + if (strlen((char *)parg) > TLSEXT_MAXLEN_host_name) + { + SSLerr(SSL_F_SSL3_CTRL, SSL_R_SSL3_EXT_INVALID_SERVERNAME); + return 0; + } + if ((s->tlsext_hostname = BUF_strdup((char *)parg)) == NULL) + { + SSLerr(SSL_F_SSL3_CTRL, ERR_R_INTERNAL_ERROR); + return 0; + } + } + else + { + SSLerr(SSL_F_SSL3_CTRL, SSL_R_SSL3_EXT_INVALID_SERVERNAME_TYPE); + return 0; + } + break; + case SSL_CTRL_SET_TLSEXT_DEBUG_ARG: + s->tlsext_debug_arg=parg; + ret = 1; + break; + +#ifdef TLSEXT_TYPE_opaque_prf_input + case SSL_CTRL_SET_TLSEXT_OPAQUE_PRF_INPUT: + if (larg > 12288) /* actual internal limit is 2^16 for the complete hello message + * (including the cert chain and everything) */ + { + SSLerr(SSL_F_SSL3_CTRL, SSL_R_OPAQUE_PRF_INPUT_TOO_LONG); + break; + } + if (s->tlsext_opaque_prf_input != NULL) + OPENSSL_free(s->tlsext_opaque_prf_input); + if ((size_t)larg == 0) + s->tlsext_opaque_prf_input = OPENSSL_malloc(1); /* dummy byte just to get non-NULL */ + else + s->tlsext_opaque_prf_input = BUF_memdup(parg, (size_t)larg); + if (s->tlsext_opaque_prf_input != NULL) + { + s->tlsext_opaque_prf_input_len = (size_t)larg; + ret = 1; + } + else + s->tlsext_opaque_prf_input_len = 0; + break; +#endif + + case SSL_CTRL_SET_TLSEXT_STATUS_REQ_TYPE: + s->tlsext_status_type=larg; + ret = 1; + break; + + case SSL_CTRL_GET_TLSEXT_STATUS_REQ_EXTS: + *(STACK_OF(X509_EXTENSION) **)parg = s->tlsext_ocsp_exts; + ret = 1; + break; + + case SSL_CTRL_SET_TLSEXT_STATUS_REQ_EXTS: + s->tlsext_ocsp_exts = parg; + ret = 1; + break; + + case SSL_CTRL_GET_TLSEXT_STATUS_REQ_IDS: + *(STACK_OF(OCSP_RESPID) **)parg = s->tlsext_ocsp_ids; + ret = 1; + break; + + case SSL_CTRL_SET_TLSEXT_STATUS_REQ_IDS: + s->tlsext_ocsp_ids = parg; + ret = 1; + break; + + case SSL_CTRL_GET_TLSEXT_STATUS_REQ_OCSP_RESP: + *(unsigned char **)parg = s->tlsext_ocsp_resp; + return s->tlsext_ocsp_resplen; + + case SSL_CTRL_SET_TLSEXT_STATUS_REQ_OCSP_RESP: + if (s->tlsext_ocsp_resp) + OPENSSL_free(s->tlsext_ocsp_resp); + s->tlsext_ocsp_resp = parg; + s->tlsext_ocsp_resplen = larg; + ret = 1; + break; + +#endif /* !OPENSSL_NO_TLSEXT */ + default: + break; + } + return(ret); + } + +long ssl3_callback_ctrl(SSL *s, int cmd, void (*fp)(void)) + { + int ret=0; + +#if !defined(OPENSSL_NO_DSA) || !defined(OPENSSL_NO_RSA) + if ( +#ifndef OPENSSL_NO_RSA + cmd == SSL_CTRL_SET_TMP_RSA_CB || +#endif +#ifndef OPENSSL_NO_DSA + cmd == SSL_CTRL_SET_TMP_DH_CB || +#endif + 0) + { + if (!ssl_cert_inst(&s->cert)) + { + SSLerr(SSL_F_SSL3_CALLBACK_CTRL, ERR_R_MALLOC_FAILURE); + return(0); + } + } +#endif + + switch (cmd) + { +#ifndef OPENSSL_NO_RSA + case SSL_CTRL_SET_TMP_RSA_CB: + { + s->cert->rsa_tmp_cb = (RSA *(*)(SSL *, int, int))fp; + } + break; +#endif +#ifndef OPENSSL_NO_DH + case SSL_CTRL_SET_TMP_DH_CB: + { + s->cert->dh_tmp_cb = (DH *(*)(SSL *, int, int))fp; + } + break; +#endif +#ifndef OPENSSL_NO_ECDH + case SSL_CTRL_SET_TMP_ECDH_CB: + { + s->cert->ecdh_tmp_cb = (EC_KEY *(*)(SSL *, int, int))fp; + } + break; +#endif +#ifndef OPENSSL_NO_TLSEXT + case SSL_CTRL_SET_TLSEXT_DEBUG_CB: + s->tlsext_debug_cb=(void (*)(SSL *,int ,int, + unsigned char *, int, void *))fp; + break; +#endif + default: + break; + } + return(ret); + } + +long ssl3_ctx_ctrl(SSL_CTX *ctx, int cmd, long larg, void *parg) + { + CERT *cert; + + cert=ctx->cert; + + switch (cmd) + { +#ifndef OPENSSL_NO_RSA + case SSL_CTRL_NEED_TMP_RSA: + if ( (cert->rsa_tmp == NULL) && + ((cert->pkeys[SSL_PKEY_RSA_ENC].privatekey == NULL) || + (EVP_PKEY_size(cert->pkeys[SSL_PKEY_RSA_ENC].privatekey) > (512/8))) + ) + return(1); + else + return(0); + /* break; */ + case SSL_CTRL_SET_TMP_RSA: + { + RSA *rsa; + int i; + + rsa=(RSA *)parg; + i=1; + if (rsa == NULL) + i=0; + else + { + if ((rsa=RSAPrivateKey_dup(rsa)) == NULL) + i=0; + } + if (!i) + { + SSLerr(SSL_F_SSL3_CTX_CTRL,ERR_R_RSA_LIB); + return(0); + } + else + { + if (cert->rsa_tmp != NULL) + RSA_free(cert->rsa_tmp); + cert->rsa_tmp=rsa; + return(1); + } + } + /* break; */ + case SSL_CTRL_SET_TMP_RSA_CB: + { + SSLerr(SSL_F_SSL3_CTX_CTRL, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED); + return(0); + } + break; +#endif +#ifndef OPENSSL_NO_DH + case SSL_CTRL_SET_TMP_DH: + { + DH *new=NULL,*dh; + + dh=(DH *)parg; + if ((new=DHparams_dup(dh)) == NULL) + { + SSLerr(SSL_F_SSL3_CTX_CTRL,ERR_R_DH_LIB); + return 0; + } + if (!(ctx->options & SSL_OP_SINGLE_DH_USE)) + { + if (!DH_generate_key(new)) + { + SSLerr(SSL_F_SSL3_CTX_CTRL,ERR_R_DH_LIB); + DH_free(new); + return 0; + } + } + if (cert->dh_tmp != NULL) + DH_free(cert->dh_tmp); + cert->dh_tmp=new; + return 1; + } + /*break; */ + case SSL_CTRL_SET_TMP_DH_CB: + { + SSLerr(SSL_F_SSL3_CTX_CTRL, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED); + return(0); + } + break; +#endif +#ifndef OPENSSL_NO_ECDH + case SSL_CTRL_SET_TMP_ECDH: + { + EC_KEY *ecdh = NULL; + + if (parg == NULL) + { + SSLerr(SSL_F_SSL3_CTX_CTRL,ERR_R_ECDH_LIB); + return 0; + } + ecdh = EC_KEY_dup((EC_KEY *)parg); + if (ecdh == NULL) + { + SSLerr(SSL_F_SSL3_CTX_CTRL,ERR_R_EC_LIB); + return 0; + } + if (!(ctx->options & SSL_OP_SINGLE_ECDH_USE)) + { + if (!EC_KEY_generate_key(ecdh)) + { + EC_KEY_free(ecdh); + SSLerr(SSL_F_SSL3_CTX_CTRL,ERR_R_ECDH_LIB); + return 0; + } + } + + if (cert->ecdh_tmp != NULL) + { + EC_KEY_free(cert->ecdh_tmp); + } + cert->ecdh_tmp = ecdh; + return 1; + } + /* break; */ + case SSL_CTRL_SET_TMP_ECDH_CB: + { + SSLerr(SSL_F_SSL3_CTX_CTRL, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED); + return(0); + } + break; +#endif /* !OPENSSL_NO_ECDH */ +#ifndef OPENSSL_NO_TLSEXT + case SSL_CTRL_SET_TLSEXT_SERVERNAME_ARG: + ctx->tlsext_servername_arg=parg; + break; + case SSL_CTRL_SET_TLSEXT_TICKET_KEYS: + case SSL_CTRL_GET_TLSEXT_TICKET_KEYS: + { + unsigned char *keys = parg; + if (!keys) + return 48; + if (larg != 48) + { + SSLerr(SSL_F_SSL3_CTX_CTRL, SSL_R_INVALID_TICKET_KEYS_LENGTH); + return 0; + } + if (cmd == SSL_CTRL_SET_TLSEXT_TICKET_KEYS) + { + memcpy(ctx->tlsext_tick_key_name, keys, 16); + memcpy(ctx->tlsext_tick_hmac_key, keys + 16, 16); + memcpy(ctx->tlsext_tick_aes_key, keys + 32, 16); + } + else + { + memcpy(keys, ctx->tlsext_tick_key_name, 16); + memcpy(keys + 16, ctx->tlsext_tick_hmac_key, 16); + memcpy(keys + 32, ctx->tlsext_tick_aes_key, 16); + } + return 1; + } + +#ifdef TLSEXT_TYPE_opaque_prf_input + case SSL_CTRL_SET_TLSEXT_OPAQUE_PRF_INPUT_CB_ARG: + ctx->tlsext_opaque_prf_input_callback_arg = parg; + return 1; +#endif + + case SSL_CTRL_SET_TLSEXT_STATUS_REQ_CB_ARG: + ctx->tlsext_status_arg=parg; + return 1; + break; + +#endif /* !OPENSSL_NO_TLSEXT */ + + /* A Thawte special :-) */ + case SSL_CTRL_EXTRA_CHAIN_CERT: + if (ctx->extra_certs == NULL) + { + if ((ctx->extra_certs=sk_X509_new_null()) == NULL) + return(0); + } + sk_X509_push(ctx->extra_certs,(X509 *)parg); + break; + + default: + return(0); + } + return(1); + } + +long ssl3_ctx_callback_ctrl(SSL_CTX *ctx, int cmd, void (*fp)(void)) + { + CERT *cert; + + cert=ctx->cert; + + switch (cmd) + { +#ifndef OPENSSL_NO_RSA + case SSL_CTRL_SET_TMP_RSA_CB: + { + cert->rsa_tmp_cb = (RSA *(*)(SSL *, int, int))fp; + } + break; +#endif +#ifndef OPENSSL_NO_DH + case SSL_CTRL_SET_TMP_DH_CB: + { + cert->dh_tmp_cb = (DH *(*)(SSL *, int, int))fp; + } + break; +#endif +#ifndef OPENSSL_NO_ECDH + case SSL_CTRL_SET_TMP_ECDH_CB: + { + cert->ecdh_tmp_cb = (EC_KEY *(*)(SSL *, int, int))fp; + } + break; +#endif +#ifndef OPENSSL_NO_TLSEXT + case SSL_CTRL_SET_TLSEXT_SERVERNAME_CB: + ctx->tlsext_servername_callback=(int (*)(SSL *,int *,void *))fp; + break; + +#ifdef TLSEXT_TYPE_opaque_prf_input + case SSL_CTRL_SET_TLSEXT_OPAQUE_PRF_INPUT_CB: + ctx->tlsext_opaque_prf_input_callback = (int (*)(SSL *,void *, size_t, void *))fp; + break; +#endif + + case SSL_CTRL_SET_TLSEXT_STATUS_REQ_CB: + ctx->tlsext_status_cb=(int (*)(SSL *,void *))fp; + break; + + case SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB: + ctx->tlsext_ticket_key_cb=(int (*)(SSL *,unsigned char *, + unsigned char *, + EVP_CIPHER_CTX *, + HMAC_CTX *, int))fp; + break; + +#endif + default: + return(0); + } + return(1); + } + +/* This function needs to check if the ciphers required are actually + * available */ +const SSL_CIPHER *ssl3_get_cipher_by_char(const unsigned char *p) + { + SSL_CIPHER c; + const SSL_CIPHER *cp; + unsigned long id; + + id=0x03000000L|((unsigned long)p[0]<<8L)|(unsigned long)p[1]; + c.id=id; + cp = OBJ_bsearch_ssl_cipher_id(&c, ssl3_ciphers, SSL3_NUM_CIPHERS); + if (cp == NULL || cp->valid == 0) + return NULL; + else + return cp; + } + +int ssl3_put_cipher_by_char(const SSL_CIPHER *c, unsigned char *p) + { + long l; + + if (p != NULL) + { + l=c->id; + if ((l & 0xff000000) != 0x03000000) return(0); + p[0]=((unsigned char)(l>> 8L))&0xFF; + p[1]=((unsigned char)(l ))&0xFF; + } + return(2); + } + +SSL_CIPHER *ssl3_choose_cipher(SSL *s, STACK_OF(SSL_CIPHER) *clnt, + STACK_OF(SSL_CIPHER) *srvr) + { + SSL_CIPHER *c,*ret=NULL; + STACK_OF(SSL_CIPHER) *prio, *allow; + int i,ii,ok; +#if !defined(OPENSSL_NO_TLSEXT) && !defined(OPENSSL_NO_EC) + unsigned int j; + int ec_ok, ec_nid; + unsigned char ec_search1 = 0, ec_search2 = 0; +#endif + CERT *cert; + unsigned long alg_k,alg_a,mask_k,mask_a,emask_k,emask_a; + + /* Let's see which ciphers we can support */ + cert=s->cert; + +#if 0 + /* Do not set the compare functions, because this may lead to a + * reordering by "id". We want to keep the original ordering. + * We may pay a price in performance during sk_SSL_CIPHER_find(), + * but would have to pay with the price of sk_SSL_CIPHER_dup(). + */ + sk_SSL_CIPHER_set_cmp_func(srvr, ssl_cipher_ptr_id_cmp); + sk_SSL_CIPHER_set_cmp_func(clnt, ssl_cipher_ptr_id_cmp); +#endif + +#ifdef CIPHER_DEBUG + printf("Server has %d from %p:\n", sk_SSL_CIPHER_num(srvr), (void *)srvr); + for(i=0 ; i < sk_SSL_CIPHER_num(srvr) ; ++i) + { + c=sk_SSL_CIPHER_value(srvr,i); + printf("%p:%s\n",(void *)c,c->name); + } + printf("Client sent %d from %p:\n", sk_SSL_CIPHER_num(clnt), (void *)clnt); + for(i=0 ; i < sk_SSL_CIPHER_num(clnt) ; ++i) + { + c=sk_SSL_CIPHER_value(clnt,i); + printf("%p:%s\n",(void *)c,c->name); + } +#endif + + if (s->options & SSL_OP_CIPHER_SERVER_PREFERENCE) + { + prio = srvr; + allow = clnt; + } + else + { + prio = clnt; + allow = srvr; + } + + for (i=0; imask_k; + mask_a = cert->mask_a; + emask_k = cert->export_mask_k; + emask_a = cert->export_mask_a; + +#ifdef KSSL_DEBUG +/* printf("ssl3_choose_cipher %d alg= %lx\n", i,c->algorithms);*/ +#endif /* KSSL_DEBUG */ + + alg_k=c->algorithm_mkey; + alg_a=c->algorithm_auth; + +#ifndef OPENSSL_NO_KRB5 + if (alg_k & SSL_kKRB5) + { + if ( !kssl_keytab_is_available(s->kssl_ctx) ) + continue; + } +#endif /* OPENSSL_NO_KRB5 */ +#ifndef OPENSSL_NO_PSK + /* with PSK there must be server callback set */ + if ((alg_k & SSL_kPSK) && s->psk_server_callback == NULL) + continue; +#endif /* OPENSSL_NO_PSK */ + + if (SSL_C_IS_EXPORT(c)) + { + ok = (alg_k & emask_k) && (alg_a & emask_a); +#ifdef CIPHER_DEBUG + printf("%d:[%08lX:%08lX:%08lX:%08lX]%p:%s (export)\n",ok,alg_k,alg_a,emask_k,emask_a, + (void *)c,c->name); +#endif + } + else + { + ok = (alg_k & mask_k) && (alg_a & mask_a); +#ifdef CIPHER_DEBUG + printf("%d:[%08lX:%08lX:%08lX:%08lX]%p:%s\n",ok,alg_k,alg_a,mask_k,mask_a,(void *)c, + c->name); +#endif + } + +#ifndef OPENSSL_NO_TLSEXT +#ifndef OPENSSL_NO_EC + if ( + /* if we are considering an ECC cipher suite that uses our certificate */ + (alg_a & SSL_aECDSA || alg_a & SSL_aECDH) + /* and we have an ECC certificate */ + && (s->cert->pkeys[SSL_PKEY_ECC].x509 != NULL) + /* and the client specified a Supported Point Formats extension */ + && ((s->session->tlsext_ecpointformatlist_length > 0) && (s->session->tlsext_ecpointformatlist != NULL)) + /* and our certificate's point is compressed */ + && ( + (s->cert->pkeys[SSL_PKEY_ECC].x509->cert_info != NULL) + && (s->cert->pkeys[SSL_PKEY_ECC].x509->cert_info->key != NULL) + && (s->cert->pkeys[SSL_PKEY_ECC].x509->cert_info->key->public_key != NULL) + && (s->cert->pkeys[SSL_PKEY_ECC].x509->cert_info->key->public_key->data != NULL) + && ( + (*(s->cert->pkeys[SSL_PKEY_ECC].x509->cert_info->key->public_key->data) == POINT_CONVERSION_COMPRESSED) + || (*(s->cert->pkeys[SSL_PKEY_ECC].x509->cert_info->key->public_key->data) == POINT_CONVERSION_COMPRESSED + 1) + ) + ) + ) + { + ec_ok = 0; + /* if our certificate's curve is over a field type that the client does not support + * then do not allow this cipher suite to be negotiated */ + if ( + (s->cert->pkeys[SSL_PKEY_ECC].privatekey->pkey.ec != NULL) + && (s->cert->pkeys[SSL_PKEY_ECC].privatekey->pkey.ec->group != NULL) + && (s->cert->pkeys[SSL_PKEY_ECC].privatekey->pkey.ec->group->meth != NULL) + && (EC_METHOD_get_field_type(s->cert->pkeys[SSL_PKEY_ECC].privatekey->pkey.ec->group->meth) == NID_X9_62_prime_field) + ) + { + for (j = 0; j < s->session->tlsext_ecpointformatlist_length; j++) + { + if (s->session->tlsext_ecpointformatlist[j] == TLSEXT_ECPOINTFORMAT_ansiX962_compressed_prime) + { + ec_ok = 1; + break; + } + } + } + else if (EC_METHOD_get_field_type(s->cert->pkeys[SSL_PKEY_ECC].privatekey->pkey.ec->group->meth) == NID_X9_62_characteristic_two_field) + { + for (j = 0; j < s->session->tlsext_ecpointformatlist_length; j++) + { + if (s->session->tlsext_ecpointformatlist[j] == TLSEXT_ECPOINTFORMAT_ansiX962_compressed_char2) + { + ec_ok = 1; + break; + } + } + } + ok = ok && ec_ok; + } + if ( + /* if we are considering an ECC cipher suite that uses our certificate */ + (alg_a & SSL_aECDSA || alg_a & SSL_aECDH) + /* and we have an ECC certificate */ + && (s->cert->pkeys[SSL_PKEY_ECC].x509 != NULL) + /* and the client specified an EllipticCurves extension */ + && ((s->session->tlsext_ellipticcurvelist_length > 0) && (s->session->tlsext_ellipticcurvelist != NULL)) + ) + { + ec_ok = 0; + if ( + (s->cert->pkeys[SSL_PKEY_ECC].privatekey->pkey.ec != NULL) + && (s->cert->pkeys[SSL_PKEY_ECC].privatekey->pkey.ec->group != NULL) + ) + { + ec_nid = EC_GROUP_get_curve_name(s->cert->pkeys[SSL_PKEY_ECC].privatekey->pkey.ec->group); + if ((ec_nid == 0) + && (s->cert->pkeys[SSL_PKEY_ECC].privatekey->pkey.ec->group->meth != NULL) + ) + { + if (EC_METHOD_get_field_type(s->cert->pkeys[SSL_PKEY_ECC].privatekey->pkey.ec->group->meth) == NID_X9_62_prime_field) + { + ec_search1 = 0xFF; + ec_search2 = 0x01; + } + else if (EC_METHOD_get_field_type(s->cert->pkeys[SSL_PKEY_ECC].privatekey->pkey.ec->group->meth) == NID_X9_62_characteristic_two_field) + { + ec_search1 = 0xFF; + ec_search2 = 0x02; + } + } + else + { + ec_search1 = 0x00; + ec_search2 = tls1_ec_nid2curve_id(ec_nid); + } + if ((ec_search1 != 0) || (ec_search2 != 0)) + { + for (j = 0; j < s->session->tlsext_ellipticcurvelist_length / 2; j++) + { + if ((s->session->tlsext_ellipticcurvelist[2*j] == ec_search1) && (s->session->tlsext_ellipticcurvelist[2*j+1] == ec_search2)) + { + ec_ok = 1; + break; + } + } + } + } + ok = ok && ec_ok; + } + if ( + /* if we are considering an ECC cipher suite that uses an ephemeral EC key */ + (alg_k & SSL_kEECDH) + /* and we have an ephemeral EC key */ + && (s->cert->ecdh_tmp != NULL) + /* and the client specified an EllipticCurves extension */ + && ((s->session->tlsext_ellipticcurvelist_length > 0) && (s->session->tlsext_ellipticcurvelist != NULL)) + ) + { + ec_ok = 0; + if (s->cert->ecdh_tmp->group != NULL) + { + ec_nid = EC_GROUP_get_curve_name(s->cert->ecdh_tmp->group); + if ((ec_nid == 0) + && (s->cert->ecdh_tmp->group->meth != NULL) + ) + { + if (EC_METHOD_get_field_type(s->cert->ecdh_tmp->group->meth) == NID_X9_62_prime_field) + { + ec_search1 = 0xFF; + ec_search2 = 0x01; + } + else if (EC_METHOD_get_field_type(s->cert->ecdh_tmp->group->meth) == NID_X9_62_characteristic_two_field) + { + ec_search1 = 0xFF; + ec_search2 = 0x02; + } + } + else + { + ec_search1 = 0x00; + ec_search2 = tls1_ec_nid2curve_id(ec_nid); + } + if ((ec_search1 != 0) || (ec_search2 != 0)) + { + for (j = 0; j < s->session->tlsext_ellipticcurvelist_length / 2; j++) + { + if ((s->session->tlsext_ellipticcurvelist[2*j] == ec_search1) && (s->session->tlsext_ellipticcurvelist[2*j+1] == ec_search2)) + { + ec_ok = 1; + break; + } + } + } + } + ok = ok && ec_ok; + } +#endif /* OPENSSL_NO_EC */ +#endif /* OPENSSL_NO_TLSEXT */ + + if (!ok) continue; + ii=sk_SSL_CIPHER_find(allow,c); + if (ii >= 0) + { + ret=sk_SSL_CIPHER_value(allow,ii); + break; + } + } + return(ret); + } + +int ssl3_get_req_cert_type(SSL *s, unsigned char *p) + { + int ret=0; + unsigned long alg_k; + + alg_k = s->s3->tmp.new_cipher->algorithm_mkey; + +#ifndef OPENSSL_NO_GOST + if (s->version >= TLS1_VERSION) + { + if (alg_k & SSL_kGOST) + { + p[ret++]=TLS_CT_GOST94_SIGN; + p[ret++]=TLS_CT_GOST01_SIGN; + return(ret); + } + } +#endif + +#ifndef OPENSSL_NO_DH + if (alg_k & (SSL_kDHr|SSL_kEDH)) + { +# ifndef OPENSSL_NO_RSA + p[ret++]=SSL3_CT_RSA_FIXED_DH; +# endif +# ifndef OPENSSL_NO_DSA + p[ret++]=SSL3_CT_DSS_FIXED_DH; +# endif + } + if ((s->version == SSL3_VERSION) && + (alg_k & (SSL_kEDH|SSL_kDHd|SSL_kDHr))) + { +# ifndef OPENSSL_NO_RSA + p[ret++]=SSL3_CT_RSA_EPHEMERAL_DH; +# endif +# ifndef OPENSSL_NO_DSA + p[ret++]=SSL3_CT_DSS_EPHEMERAL_DH; +# endif + } +#endif /* !OPENSSL_NO_DH */ +#ifndef OPENSSL_NO_RSA + p[ret++]=SSL3_CT_RSA_SIGN; +#endif +#ifndef OPENSSL_NO_DSA + p[ret++]=SSL3_CT_DSS_SIGN; +#endif +#ifndef OPENSSL_NO_ECDH + if ((alg_k & (SSL_kECDHr|SSL_kECDHe)) && (s->version >= TLS1_VERSION)) + { + p[ret++]=TLS_CT_RSA_FIXED_ECDH; + p[ret++]=TLS_CT_ECDSA_FIXED_ECDH; + } +#endif + +#ifndef OPENSSL_NO_ECDSA + /* ECDSA certs can be used with RSA cipher suites as well + * so we don't need to check for SSL_kECDH or SSL_kEECDH + */ + if (s->version >= TLS1_VERSION) + { + p[ret++]=TLS_CT_ECDSA_SIGN; + } +#endif + return(ret); + } + +int ssl3_shutdown(SSL *s) + { + int ret; + + /* Don't do anything much if we have not done the handshake or + * we don't want to send messages :-) */ + if ((s->quiet_shutdown) || (s->state == SSL_ST_BEFORE)) + { + s->shutdown=(SSL_SENT_SHUTDOWN|SSL_RECEIVED_SHUTDOWN); + return(1); + } + + if (!(s->shutdown & SSL_SENT_SHUTDOWN)) + { + s->shutdown|=SSL_SENT_SHUTDOWN; +#if 1 + ssl3_send_alert(s,SSL3_AL_WARNING,SSL_AD_CLOSE_NOTIFY); +#endif + /* our shutdown alert has been sent now, and if it still needs + * to be written, s->s3->alert_dispatch will be true */ + if (s->s3->alert_dispatch) + return(-1); /* return WANT_WRITE */ + } + else if (s->s3->alert_dispatch) + { + /* resend it if not sent */ +#if 1 + ret=s->method->ssl_dispatch_alert(s); + if(ret == -1) + { + /* we only get to return -1 here the 2nd/Nth + * invocation, we must have already signalled + * return 0 upon a previous invoation, + * return WANT_WRITE */ + return(ret); + } +#endif + } + else if (!(s->shutdown & SSL_RECEIVED_SHUTDOWN)) + { + /* If we are waiting for a close from our peer, we are closed */ + s->method->ssl_read_bytes(s,0,NULL,0,0); + if(!(s->shutdown & SSL_RECEIVED_SHUTDOWN)) + { + return(-1); /* return WANT_READ */ + } + } + + if ((s->shutdown == (SSL_SENT_SHUTDOWN|SSL_RECEIVED_SHUTDOWN)) && + !s->s3->alert_dispatch) + return(1); + else + return(0); + } + +int ssl3_write(SSL *s, const void *buf, int len) + { + int ret,n; + +#if 0 + if (s->shutdown & SSL_SEND_SHUTDOWN) + { + s->rwstate=SSL_NOTHING; + return(0); + } +#endif + clear_sys_error(); + if (s->s3->renegotiate) ssl3_renegotiate_check(s); + + /* This is an experimental flag that sends the + * last handshake message in the same packet as the first + * use data - used to see if it helps the TCP protocol during + * session-id reuse */ + /* The second test is because the buffer may have been removed */ + if ((s->s3->flags & SSL3_FLAGS_POP_BUFFER) && (s->wbio == s->bbio)) + { + /* First time through, we write into the buffer */ + if (s->s3->delay_buf_pop_ret == 0) + { + ret=ssl3_write_bytes(s,SSL3_RT_APPLICATION_DATA, + buf,len); + if (ret <= 0) return(ret); + + s->s3->delay_buf_pop_ret=ret; + } + + s->rwstate=SSL_WRITING; + n=BIO_flush(s->wbio); + if (n <= 0) return(n); + s->rwstate=SSL_NOTHING; + + /* We have flushed the buffer, so remove it */ + ssl_free_wbio_buffer(s); + s->s3->flags&= ~SSL3_FLAGS_POP_BUFFER; + + ret=s->s3->delay_buf_pop_ret; + s->s3->delay_buf_pop_ret=0; + } + else + { + ret=s->method->ssl_write_bytes(s,SSL3_RT_APPLICATION_DATA, + buf,len); + if (ret <= 0) return(ret); + } + + return(ret); + } + +static int ssl3_read_internal(SSL *s, void *buf, int len, int peek) + { + int n,ret; + + clear_sys_error(); + if ((s->s3->flags & SSL3_FLAGS_POP_BUFFER) && (s->wbio == s->bbio)) + { + /* Deal with an application that calls SSL_read() when handshake data + * is yet to be written. + */ + if (BIO_wpending(s->wbio) > 0) + { + s->rwstate=SSL_WRITING; + n=BIO_flush(s->wbio); + if (n <= 0) return(n); + s->rwstate=SSL_NOTHING; + } + } + if (s->s3->renegotiate) ssl3_renegotiate_check(s); + s->s3->in_read_app_data=1; + ret=s->method->ssl_read_bytes(s,SSL3_RT_APPLICATION_DATA,buf,len,peek); + if ((ret == -1) && (s->s3->in_read_app_data == 2)) + { + /* ssl3_read_bytes decided to call s->handshake_func, which + * called ssl3_read_bytes to read handshake data. + * However, ssl3_read_bytes actually found application data + * and thinks that application data makes sense here; so disable + * handshake processing and try to read application data again. */ + s->in_handshake++; + ret=s->method->ssl_read_bytes(s,SSL3_RT_APPLICATION_DATA,buf,len,peek); + s->in_handshake--; + } + else + s->s3->in_read_app_data=0; + + return(ret); + } + +int ssl3_read(SSL *s, void *buf, int len) + { + return ssl3_read_internal(s, buf, len, 0); + } + +int ssl3_peek(SSL *s, void *buf, int len) + { + return ssl3_read_internal(s, buf, len, 1); + } + +int ssl3_renegotiate(SSL *s) + { + if (s->handshake_func == NULL) + return(1); + + if (s->s3->flags & SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS) + return(0); + + s->s3->renegotiate=1; + return(1); + } + +int ssl3_renegotiate_check(SSL *s) + { + int ret=0; + + if (s->s3->renegotiate) + { + if ( (s->s3->rbuf.left == 0) && + (s->s3->wbuf.left == 0) && + !SSL_in_init(s)) + { +/* +if we are the server, and we have sent a 'RENEGOTIATE' message, we +need to go to SSL_ST_ACCEPT. +*/ + /* SSL_ST_ACCEPT */ + s->state=SSL_ST_RENEGOTIATE; + s->s3->renegotiate=0; + s->s3->num_renegotiations++; + s->s3->total_renegotiations++; + ret=1; + } + } + return(ret); + } + diff --git a/node-v0.8.14/deps/openssl/openssl/ssl/s3_meth.c b/node-v0.8.14/deps/openssl/openssl/ssl/s3_meth.c new file mode 100644 index 0000000..cdddb17 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/ssl/s3_meth.c @@ -0,0 +1,77 @@ +/* ssl/s3_meth.c */ +/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com) + * All rights reserved. + * + * This package is an SSL implementation written + * by Eric Young (eay@cryptsoft.com). + * The implementation was written so as to conform with Netscapes SSL. + * + * This library is free for commercial and non-commercial use as long as + * the following conditions are aheared to. The following conditions + * apply to all code found in this distribution, be it the RC4, RSA, + * lhash, DES, etc., code; not just the SSL code. The SSL documentation + * included with this distribution is covered by the same copyright terms + * except that the holder is Tim Hudson (tjh@cryptsoft.com). + * + * Copyright remains Eric Young's, and as such any Copyright notices in + * the code are not to be removed. + * If this package is used in a product, Eric Young should be given attribution + * as the author of the parts of the library used. + * This can be in the form of a textual message at program startup or + * in documentation (online or textual) provided with the package. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * "This product includes cryptographic software written by + * Eric Young (eay@cryptsoft.com)" + * The word 'cryptographic' can be left out if the rouines from the library + * being used are not cryptographic related :-). + * 4. If you include any Windows specific code (or a derivative thereof) from + * the apps directory (application code) you must include an acknowledgement: + * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)" + * + * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * + * The licence and distribution terms for any publically available version or + * derivative of this code cannot be changed. i.e. this code cannot simply be + * copied and put under another distribution licence + * [including the GNU Public Licence.] + */ + +#include +#include +#include "ssl_locl.h" + +static const SSL_METHOD *ssl3_get_method(int ver); +static const SSL_METHOD *ssl3_get_method(int ver) + { + if (ver == SSL3_VERSION) + return(SSLv3_method()); + else + return(NULL); + } + +IMPLEMENT_ssl3_meth_func(SSLv3_method, + ssl3_accept, + ssl3_connect, + ssl3_get_method) + + diff --git a/node-v0.8.14/deps/openssl/openssl/ssl/s3_pkt.c b/node-v0.8.14/deps/openssl/openssl/ssl/s3_pkt.c new file mode 100644 index 0000000..0d3874a --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/ssl/s3_pkt.c @@ -0,0 +1,1502 @@ +/* ssl/s3_pkt.c */ +/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com) + * All rights reserved. + * + * This package is an SSL implementation written + * by Eric Young (eay@cryptsoft.com). + * The implementation was written so as to conform with Netscapes SSL. + * + * This library is free for commercial and non-commercial use as long as + * the following conditions are aheared to. The following conditions + * apply to all code found in this distribution, be it the RC4, RSA, + * lhash, DES, etc., code; not just the SSL code. The SSL documentation + * included with this distribution is covered by the same copyright terms + * except that the holder is Tim Hudson (tjh@cryptsoft.com). + * + * Copyright remains Eric Young's, and as such any Copyright notices in + * the code are not to be removed. + * If this package is used in a product, Eric Young should be given attribution + * as the author of the parts of the library used. + * This can be in the form of a textual message at program startup or + * in documentation (online or textual) provided with the package. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * "This product includes cryptographic software written by + * Eric Young (eay@cryptsoft.com)" + * The word 'cryptographic' can be left out if the rouines from the library + * being used are not cryptographic related :-). + * 4. If you include any Windows specific code (or a derivative thereof) from + * the apps directory (application code) you must include an acknowledgement: + * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)" + * + * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * + * The licence and distribution terms for any publically available version or + * derivative of this code cannot be changed. i.e. this code cannot simply be + * copied and put under another distribution licence + * [including the GNU Public Licence.] + */ +/* ==================================================================== + * Copyright (c) 1998-2002 The OpenSSL Project. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. All advertising materials mentioning features or use of this + * software must display the following acknowledgment: + * "This product includes software developed by the OpenSSL Project + * for use in the OpenSSL Toolkit. (http://www.openssl.org/)" + * + * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to + * endorse or promote products derived from this software without + * prior written permission. For written permission, please contact + * openssl-core@openssl.org. + * + * 5. Products derived from this software may not be called "OpenSSL" + * nor may "OpenSSL" appear in their names without prior written + * permission of the OpenSSL Project. + * + * 6. Redistributions of any form whatsoever must retain the following + * acknowledgment: + * "This product includes software developed by the OpenSSL Project + * for use in the OpenSSL Toolkit (http://www.openssl.org/)" + * + * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY + * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR + * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, + * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * ==================================================================== + * + * This product includes cryptographic software written by Eric Young + * (eay@cryptsoft.com). This product includes software written by Tim + * Hudson (tjh@cryptsoft.com). + * + */ + +#include +#include +#define USE_SOCKETS +#include "ssl_locl.h" +#include +#include + +static int do_ssl3_write(SSL *s, int type, const unsigned char *buf, + unsigned int len, int create_empty_fragment); +static int ssl3_get_record(SSL *s); + +int ssl3_read_n(SSL *s, int n, int max, int extend) + { + /* If extend == 0, obtain new n-byte packet; if extend == 1, increase + * packet by another n bytes. + * The packet will be in the sub-array of s->s3->rbuf.buf specified + * by s->packet and s->packet_length. + * (If s->read_ahead is set, 'max' bytes may be stored in rbuf + * [plus s->packet_length bytes if extend == 1].) + */ + int i,len,left; + long align=0; + unsigned char *pkt; + SSL3_BUFFER *rb; + + if (n <= 0) return n; + + rb = &(s->s3->rbuf); + if (rb->buf == NULL) + if (!ssl3_setup_read_buffer(s)) + return -1; + + left = rb->left; +#if defined(SSL3_ALIGN_PAYLOAD) && SSL3_ALIGN_PAYLOAD!=0 + align = (long)rb->buf + SSL3_RT_HEADER_LENGTH; + align = (-align)&(SSL3_ALIGN_PAYLOAD-1); +#endif + + if (!extend) + { + /* start with empty packet ... */ + if (left == 0) + rb->offset = align; + else if (align != 0 && left >= SSL3_RT_HEADER_LENGTH) + { + /* check if next packet length is large + * enough to justify payload alignment... */ + pkt = rb->buf + rb->offset; + if (pkt[0] == SSL3_RT_APPLICATION_DATA + && (pkt[3]<<8|pkt[4]) >= 128) + { + /* Note that even if packet is corrupted + * and its length field is insane, we can + * only be led to wrong decision about + * whether memmove will occur or not. + * Header values has no effect on memmove + * arguments and therefore no buffer + * overrun can be triggered. */ + memmove (rb->buf+align,pkt,left); + rb->offset = align; + } + } + s->packet = rb->buf + rb->offset; + s->packet_length = 0; + /* ... now we can act as if 'extend' was set */ + } + + /* For DTLS/UDP reads should not span multiple packets + * because the read operation returns the whole packet + * at once (as long as it fits into the buffer). */ + if (SSL_version(s) == DTLS1_VERSION || SSL_version(s) == DTLS1_BAD_VER) + { + if (left > 0 && n > left) + n = left; + } + + /* if there is enough in the buffer from a previous read, take some */ + if (left >= n) + { + s->packet_length+=n; + rb->left=left-n; + rb->offset+=n; + return(n); + } + + /* else we need to read more data */ + + len = s->packet_length; + pkt = rb->buf+align; + /* Move any available bytes to front of buffer: + * 'len' bytes already pointed to by 'packet', + * 'left' extra ones at the end */ + if (s->packet != pkt) /* len > 0 */ + { + memmove(pkt, s->packet, len+left); + s->packet = pkt; + rb->offset = len + align; + } + + if (n > (int)(rb->len - rb->offset)) /* does not happen */ + { + SSLerr(SSL_F_SSL3_READ_N,ERR_R_INTERNAL_ERROR); + return -1; + } + + if (!s->read_ahead) + /* ignore max parameter */ + max = n; + else + { + if (max < n) + max = n; + if (max > (int)(rb->len - rb->offset)) + max = rb->len - rb->offset; + } + + while (left < n) + { + /* Now we have len+left bytes at the front of s->s3->rbuf.buf + * and need to read in more until we have len+n (up to + * len+max if possible) */ + + clear_sys_error(); + if (s->rbio != NULL) + { + s->rwstate=SSL_READING; + i=BIO_read(s->rbio,pkt+len+left, max-left); + } + else + { + SSLerr(SSL_F_SSL3_READ_N,SSL_R_READ_BIO_NOT_SET); + i = -1; + } + + if (i <= 0) + { + rb->left = left; + if (s->mode & SSL_MODE_RELEASE_BUFFERS && + SSL_version(s) != DTLS1_VERSION && SSL_version(s) != DTLS1_BAD_VER) + if (len+left == 0) + ssl3_release_read_buffer(s); + return(i); + } + left+=i; + /* reads should *never* span multiple packets for DTLS because + * the underlying transport protocol is message oriented as opposed + * to byte oriented as in the TLS case. */ + if (SSL_version(s) == DTLS1_VERSION || SSL_version(s) == DTLS1_BAD_VER) + { + if (n > left) + n = left; /* makes the while condition false */ + } + } + + /* done reading, now the book-keeping */ + rb->offset += n; + rb->left = left - n; + s->packet_length += n; + s->rwstate=SSL_NOTHING; + return(n); + } + +/* Call this to get a new input record. + * It will return <= 0 if more data is needed, normally due to an error + * or non-blocking IO. + * When it finishes, one packet has been decoded and can be found in + * ssl->s3->rrec.type - is the type of record + * ssl->s3->rrec.data, - data + * ssl->s3->rrec.length, - number of bytes + */ +/* used only by ssl3_read_bytes */ +static int ssl3_get_record(SSL *s) + { + int ssl_major,ssl_minor,al; + int enc_err,n,i,ret= -1; + SSL3_RECORD *rr; + SSL_SESSION *sess; + unsigned char *p; + unsigned char md[EVP_MAX_MD_SIZE]; + short version; + int mac_size; + int clear=0; + size_t extra; + int decryption_failed_or_bad_record_mac = 0; + unsigned char *mac = NULL; +#if defined(SSL3_ALIGN_PAYLOAD) && SSL3_ALIGN_PAYLOAD!=0 + long align=SSL3_ALIGN_PAYLOAD; +#else + long align=0; +#endif + + rr= &(s->s3->rrec); + sess=s->session; + + if (s->options & SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER) + extra=SSL3_RT_MAX_EXTRA; + else + extra=0; + if (!(SSL_get_mode(s) & SSL_MODE_SMALL_BUFFERS) && + extra && !s->s3->init_extra) + { + /* An application error: SLS_OP_MICROSOFT_BIG_SSLV3_BUFFER + * set after ssl3_setup_buffers() was done */ + SSLerr(SSL_F_SSL3_GET_RECORD, ERR_R_INTERNAL_ERROR); + return -1; + } + +again: + /* check if we have the header */ + if ( (s->rstate != SSL_ST_READ_BODY) || + (s->packet_length < SSL3_RT_HEADER_LENGTH)) + { + n=ssl3_read_n(s, SSL3_RT_HEADER_LENGTH, s->s3->rbuf.len, 0); + if (n <= 0) return(n); /* error or non-blocking */ + s->rstate=SSL_ST_READ_BODY; + + p=s->packet; + + /* Pull apart the header into the SSL3_RECORD */ + rr->type= *(p++); + ssl_major= *(p++); + ssl_minor= *(p++); + version=(ssl_major<<8)|ssl_minor; + n2s(p,rr->length); +#if 0 +fprintf(stderr, "Record type=%d, Length=%d\n", rr->type, rr->length); +#endif + + /* Lets check version */ + if (!s->first_packet) + { + if (version != s->version) + { + SSLerr(SSL_F_SSL3_GET_RECORD,SSL_R_WRONG_VERSION_NUMBER); + if ((s->version & 0xFF00) == (version & 0xFF00)) + /* Send back error using their minor version number :-) */ + s->version = (unsigned short)version; + al=SSL_AD_PROTOCOL_VERSION; + goto f_err; + } + } + + if ((version>>8) != SSL3_VERSION_MAJOR) + { + SSLerr(SSL_F_SSL3_GET_RECORD,SSL_R_WRONG_VERSION_NUMBER); + goto err; + } + + /* If we receive a valid record larger than the current buffer size, + * allocate some memory for it. + */ + if (rr->length > s->s3->rbuf.len - SSL3_RT_HEADER_LENGTH - align) + { + if ((p=OPENSSL_realloc(s->s3->rbuf.buf, rr->length + SSL3_RT_HEADER_LENGTH + align))==NULL) + { + SSLerr(SSL_F_SSL3_GET_RECORD,ERR_R_MALLOC_FAILURE); + goto err; + } + s->s3->rbuf.buf=p; + s->s3->rbuf.len=rr->length + SSL3_RT_HEADER_LENGTH + align; + s->packet= &(s->s3->rbuf.buf[0]); + } + + if (rr->length > s->s3->rbuf.len - SSL3_RT_HEADER_LENGTH) + { + al=SSL_AD_RECORD_OVERFLOW; + SSLerr(SSL_F_SSL3_GET_RECORD,SSL_R_PACKET_LENGTH_TOO_LONG); + goto f_err; + } + + /* now s->rstate == SSL_ST_READ_BODY */ + } + + /* s->rstate == SSL_ST_READ_BODY, get and decode the data */ + + if (rr->length > s->packet_length-SSL3_RT_HEADER_LENGTH) + { + /* now s->packet_length == SSL3_RT_HEADER_LENGTH */ + i=rr->length; + n=ssl3_read_n(s,i,i,1); + if (n <= 0) return(n); /* error or non-blocking io */ + /* now n == rr->length, + * and s->packet_length == SSL3_RT_HEADER_LENGTH + rr->length */ + } + + s->rstate=SSL_ST_READ_HEADER; /* set state for later operations */ + + /* At this point, s->packet_length == SSL3_RT_HEADER_LNGTH + rr->length, + * and we have that many bytes in s->packet + */ + rr->input= &(s->packet[SSL3_RT_HEADER_LENGTH]); + + /* ok, we can now read from 's->packet' data into 'rr' + * rr->input points at rr->length bytes, which + * need to be copied into rr->data by either + * the decryption or by the decompression + * When the data is 'copied' into the rr->data buffer, + * rr->input will be pointed at the new buffer */ + + /* We now have - encrypted [ MAC [ compressed [ plain ] ] ] + * rr->length bytes of encrypted compressed stuff. */ + + /* check is not needed I believe */ + if (rr->length > SSL3_RT_MAX_ENCRYPTED_LENGTH+extra) + { + al=SSL_AD_RECORD_OVERFLOW; + SSLerr(SSL_F_SSL3_GET_RECORD,SSL_R_ENCRYPTED_LENGTH_TOO_LONG); + goto f_err; + } + + /* decrypt in place in 'rr->input' */ + rr->data=rr->input; + + enc_err = s->method->ssl3_enc->enc(s,0); + if (enc_err <= 0) + { + if (enc_err == 0) + /* SSLerr() and ssl3_send_alert() have been called */ + goto err; + + /* Otherwise enc_err == -1, which indicates bad padding + * (rec->length has not been changed in this case). + * To minimize information leaked via timing, we will perform + * the MAC computation anyway. */ + decryption_failed_or_bad_record_mac = 1; + } + +#ifdef TLS_DEBUG +printf("dec %d\n",rr->length); +{ unsigned int z; for (z=0; zlength; z++) printf("%02X%c",rr->data[z],((z+1)%16)?' ':'\n'); } +printf("\n"); +#endif + + /* r->length is now the compressed data plus mac */ + if ( (sess == NULL) || + (s->enc_read_ctx == NULL) || + (EVP_MD_CTX_md(s->read_hash) == NULL)) + clear=1; + + if (!clear) + { + /* !clear => s->read_hash != NULL => mac_size != -1 */ + mac_size=EVP_MD_CTX_size(s->read_hash); + OPENSSL_assert(mac_size >= 0); + + if (rr->length > SSL3_RT_MAX_COMPRESSED_LENGTH+extra+mac_size) + { +#if 0 /* OK only for stream ciphers (then rr->length is visible from ciphertext anyway) */ + al=SSL_AD_RECORD_OVERFLOW; + SSLerr(SSL_F_SSL3_GET_RECORD,SSL_R_PRE_MAC_LENGTH_TOO_LONG); + goto f_err; +#else + decryption_failed_or_bad_record_mac = 1; +#endif + } + /* check the MAC for rr->input (it's in mac_size bytes at the tail) */ + if (rr->length >= (unsigned int)mac_size) + { + rr->length -= mac_size; + mac = &rr->data[rr->length]; + } + else + { + /* record (minus padding) is too short to contain a MAC */ +#if 0 /* OK only for stream ciphers */ + al=SSL_AD_DECODE_ERROR; + SSLerr(SSL_F_SSL3_GET_RECORD,SSL_R_LENGTH_TOO_SHORT); + goto f_err; +#else + decryption_failed_or_bad_record_mac = 1; + rr->length = 0; +#endif + } + i=s->method->ssl3_enc->mac(s,md,0); + if (i < 0 || mac == NULL || memcmp(md, mac, (size_t)mac_size) != 0) + { + decryption_failed_or_bad_record_mac = 1; + } + } + + if (decryption_failed_or_bad_record_mac) + { + /* A separate 'decryption_failed' alert was introduced with TLS 1.0, + * SSL 3.0 only has 'bad_record_mac'. But unless a decryption + * failure is directly visible from the ciphertext anyway, + * we should not reveal which kind of error occured -- this + * might become visible to an attacker (e.g. via a logfile) */ + al=SSL_AD_BAD_RECORD_MAC; + SSLerr(SSL_F_SSL3_GET_RECORD,SSL_R_DECRYPTION_FAILED_OR_BAD_RECORD_MAC); + goto f_err; + } + + /* r->length is now just compressed */ + if (s->expand != NULL) + { + if (rr->length > SSL3_RT_MAX_COMPRESSED_LENGTH+extra) + { + al=SSL_AD_RECORD_OVERFLOW; + SSLerr(SSL_F_SSL3_GET_RECORD,SSL_R_COMPRESSED_LENGTH_TOO_LONG); + goto f_err; + } + if (!ssl3_do_uncompress(s)) + { + al=SSL_AD_DECOMPRESSION_FAILURE; + SSLerr(SSL_F_SSL3_GET_RECORD,SSL_R_BAD_DECOMPRESSION); + goto f_err; + } + } + + if (rr->length > SSL3_RT_MAX_PLAIN_LENGTH+extra) + { + al=SSL_AD_RECORD_OVERFLOW; + SSLerr(SSL_F_SSL3_GET_RECORD,SSL_R_DATA_LENGTH_TOO_LONG); + goto f_err; + } + + rr->off=0; + /* So at this point the following is true + * ssl->s3->rrec.type is the type of record + * ssl->s3->rrec.length == number of bytes in record + * ssl->s3->rrec.off == offset to first valid byte + * ssl->s3->rrec.data == where to take bytes from, increment + * after use :-). + */ + + /* we have pulled in a full packet so zero things */ + s->packet_length=0; + + /* just read a 0 length packet */ + if (rr->length == 0) goto again; + +#if 0 +fprintf(stderr, "Ultimate Record type=%d, Length=%d\n", rr->type, rr->length); +#endif + + return(1); + +f_err: + ssl3_send_alert(s,SSL3_AL_FATAL,al); +err: + return(ret); + } + +int ssl3_do_uncompress(SSL *ssl) + { +#ifndef OPENSSL_NO_COMP + int i; + SSL3_RECORD *rr; + + rr= &(ssl->s3->rrec); + i=COMP_expand_block(ssl->expand,rr->comp, + SSL3_RT_MAX_PLAIN_LENGTH,rr->data,(int)rr->length); + if (i < 0) + return(0); + else + rr->length=i; + rr->data=rr->comp; +#endif + return(1); + } + +int ssl3_do_compress(SSL *ssl) + { +#ifndef OPENSSL_NO_COMP + int i; + SSL3_RECORD *wr; + + wr= &(ssl->s3->wrec); + i=COMP_compress_block(ssl->compress,wr->data, + SSL3_RT_MAX_COMPRESSED_LENGTH, + wr->input,(int)wr->length); + if (i < 0) + return(0); + else + wr->length=i; + + wr->input=wr->data; +#endif + return(1); + } + +/* Call this to write data in records of type 'type' + * It will return <= 0 if not all data has been sent or non-blocking IO. + */ +int ssl3_write_bytes(SSL *s, int type, const void *buf_, int len) + { + const unsigned char *buf=buf_; + unsigned int tot,n,nw; + int i; + unsigned int max_plain_length; + + s->rwstate=SSL_NOTHING; + tot=s->s3->wnum; + s->s3->wnum=0; + + if (SSL_in_init(s) && !s->in_handshake) + { + i=s->handshake_func(s); + if (i < 0) return(i); + if (i == 0) + { + SSLerr(SSL_F_SSL3_WRITE_BYTES,SSL_R_SSL_HANDSHAKE_FAILURE); + return -1; + } + } + + n=(len-tot); + for (;;) + { + if (type == SSL3_RT_APPLICATION_DATA && (SSL_get_mode(s) & SSL_MODE_SMALL_BUFFERS)) + max_plain_length = SSL3_RT_DEFAULT_PLAIN_LENGTH; + else + max_plain_length = s->max_send_fragment; + + if (n > max_plain_length) + nw = max_plain_length; + else + nw=n; + + i=do_ssl3_write(s, type, &(buf[tot]), nw, 0); + if (i <= 0) + { + s->s3->wnum=tot; + return i; + } + + if ((i == (int)n) || + (type == SSL3_RT_APPLICATION_DATA && + (s->mode & SSL_MODE_ENABLE_PARTIAL_WRITE))) + { + /* next chunk of data should get another prepended empty fragment + * in ciphersuites with known-IV weakness: */ + s->s3->empty_fragment_done = 0; + + return tot+i; + } + + n-=i; + tot+=i; + } + } + +static int do_ssl3_write(SSL *s, int type, const unsigned char *buf, + unsigned int len, int create_empty_fragment) + { + unsigned char *p,*plen; + int i,mac_size,clear=0; + int prefix_len=0; + long align=0; + SSL3_RECORD *wr; + SSL3_BUFFER *wb=&(s->s3->wbuf); + SSL_SESSION *sess; + + if (wb->buf == NULL) + if (!ssl3_setup_write_buffer(s)) + return -1; + + /* first check if there is a SSL3_BUFFER still being written + * out. This will happen with non blocking IO */ + if (wb->left != 0) + return(ssl3_write_pending(s,type,buf,len)); + + /* If we have an alert to send, lets send it */ + if (s->s3->alert_dispatch) + { + i=s->method->ssl_dispatch_alert(s); + if (i <= 0) + return(i); + /* if it went, fall through and send more stuff */ + } + + if (len == 0 && !create_empty_fragment) + return 0; + + wr= &(s->s3->wrec); + sess=s->session; + + if ( (sess == NULL) || + (s->enc_write_ctx == NULL) || + (EVP_MD_CTX_md(s->write_hash) == NULL)) + clear=1; + + if (clear) + mac_size=0; + else + { + mac_size=EVP_MD_CTX_size(s->write_hash); + if (mac_size < 0) + goto err; + } + + /* 'create_empty_fragment' is true only when this function calls itself */ + if (!clear && !create_empty_fragment && !s->s3->empty_fragment_done) + { + /* countermeasure against known-IV weakness in CBC ciphersuites + * (see http://www.openssl.org/~bodo/tls-cbc.txt) */ + + if (s->s3->need_empty_fragments && type == SSL3_RT_APPLICATION_DATA) + { + /* recursive function call with 'create_empty_fragment' set; + * this prepares and buffers the data for an empty fragment + * (these 'prefix_len' bytes are sent out later + * together with the actual payload) */ + prefix_len = do_ssl3_write(s, type, buf, 0, 1); + if (prefix_len <= 0) + goto err; + + if (prefix_len > + (SSL3_RT_HEADER_LENGTH + SSL3_RT_SEND_MAX_ENCRYPTED_OVERHEAD)) + { + /* insufficient space */ + SSLerr(SSL_F_DO_SSL3_WRITE, ERR_R_INTERNAL_ERROR); + goto err; + } + } + + s->s3->empty_fragment_done = 1; + } + + /* resize if necessary to hold the data. */ + if (len + SSL3_RT_DEFAULT_WRITE_OVERHEAD > wb->len) + { + if ((p=OPENSSL_realloc(wb->buf, len + SSL3_RT_DEFAULT_WRITE_OVERHEAD))==NULL) + { + SSLerr(SSL_F_DO_SSL3_WRITE,ERR_R_MALLOC_FAILURE); + goto err; + } + wb->buf = p; + wb->len = len + SSL3_RT_DEFAULT_WRITE_OVERHEAD; + } + + if (create_empty_fragment) + { +#if defined(SSL3_ALIGN_PAYLOAD) && SSL3_ALIGN_PAYLOAD!=0 + /* extra fragment would be couple of cipher blocks, + * which would be multiple of SSL3_ALIGN_PAYLOAD, so + * if we want to align the real payload, then we can + * just pretent we simply have two headers. */ + align = (long)wb->buf + 2*SSL3_RT_HEADER_LENGTH; + align = (-align)&(SSL3_ALIGN_PAYLOAD-1); +#endif + p = wb->buf + align; + wb->offset = align; + } + else if (prefix_len) + { + p = wb->buf + wb->offset + prefix_len; + } + else + { +#if defined(SSL3_ALIGN_PAYLOAD) && SSL3_ALIGN_PAYLOAD!=0 + align = (long)wb->buf + SSL3_RT_HEADER_LENGTH; + align = (-align)&(SSL3_ALIGN_PAYLOAD-1); +#endif + p = wb->buf + align; + wb->offset = align; + } + + /* write the header */ + + *(p++)=type&0xff; + wr->type=type; + + *(p++)=(s->version>>8); + *(p++)=s->version&0xff; + + /* field where we are to write out packet length */ + plen=p; + p+=2; + + /* lets setup the record stuff. */ + wr->data=p; + wr->length=(int)len; + wr->input=(unsigned char *)buf; + + /* we now 'read' from wr->input, wr->length bytes into + * wr->data */ + + /* first we compress */ + if (s->compress != NULL) + { + if (!ssl3_do_compress(s)) + { + SSLerr(SSL_F_DO_SSL3_WRITE,SSL_R_COMPRESSION_FAILURE); + goto err; + } + } + else + { + memcpy(wr->data,wr->input,wr->length); + wr->input=wr->data; + } + + /* we should still have the output to wr->data and the input + * from wr->input. Length should be wr->length. + * wr->data still points in the wb->buf */ + + if (mac_size != 0) + { + if (s->method->ssl3_enc->mac(s,&(p[wr->length]),1) < 0) + goto err; + wr->length+=mac_size; + wr->input=p; + wr->data=p; + } + + /* ssl3_enc can only have an error on read */ + s->method->ssl3_enc->enc(s,1); + + /* record length after mac and block padding */ + s2n(wr->length,plen); + + /* we should now have + * wr->data pointing to the encrypted data, which is + * wr->length long */ + wr->type=type; /* not needed but helps for debugging */ + wr->length+=SSL3_RT_HEADER_LENGTH; + + if (create_empty_fragment) + { + /* we are in a recursive call; + * just return the length, don't write out anything here + */ + return wr->length; + } + + /* now let's set up wb */ + wb->left = prefix_len + wr->length; + + /* memorize arguments so that ssl3_write_pending can detect bad write retries later */ + s->s3->wpend_tot=len; + s->s3->wpend_buf=buf; + s->s3->wpend_type=type; + s->s3->wpend_ret=len; + + /* we now just need to write the buffer */ + return ssl3_write_pending(s,type,buf,len); +err: + return -1; + } + +/* if s->s3->wbuf.left != 0, we need to call this */ +int ssl3_write_pending(SSL *s, int type, const unsigned char *buf, + unsigned int len) + { + int i; + SSL3_BUFFER *wb=&(s->s3->wbuf); + +/* XXXX */ + if ((s->s3->wpend_tot > (int)len) + || ((s->s3->wpend_buf != buf) && + !(s->mode & SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER)) + || (s->s3->wpend_type != type)) + { + SSLerr(SSL_F_SSL3_WRITE_PENDING,SSL_R_BAD_WRITE_RETRY); + return(-1); + } + + for (;;) + { + clear_sys_error(); + if (s->wbio != NULL) + { + s->rwstate=SSL_WRITING; + i=BIO_write(s->wbio, + (char *)&(wb->buf[wb->offset]), + (unsigned int)wb->left); + } + else + { + SSLerr(SSL_F_SSL3_WRITE_PENDING,SSL_R_BIO_NOT_SET); + i= -1; + } + if (i == wb->left) + { + wb->left=0; + wb->offset+=i; + if (s->mode & SSL_MODE_RELEASE_BUFFERS && + SSL_version(s) != DTLS1_VERSION && SSL_version(s) != DTLS1_BAD_VER) + ssl3_release_write_buffer(s); + s->rwstate=SSL_NOTHING; + return(s->s3->wpend_ret); + } + else if (i <= 0) { + if (s->version == DTLS1_VERSION || + s->version == DTLS1_BAD_VER) { + /* For DTLS, just drop it. That's kind of the whole + point in using a datagram service */ + wb->left = 0; + } + return(i); + } + wb->offset+=i; + wb->left-=i; + } + } + +/* Return up to 'len' payload bytes received in 'type' records. + * 'type' is one of the following: + * + * - SSL3_RT_HANDSHAKE (when ssl3_get_message calls us) + * - SSL3_RT_APPLICATION_DATA (when ssl3_read calls us) + * - 0 (during a shutdown, no data has to be returned) + * + * If we don't have stored data to work from, read a SSL/TLS record first + * (possibly multiple records if we still don't have anything to return). + * + * This function must handle any surprises the peer may have for us, such as + * Alert records (e.g. close_notify), ChangeCipherSpec records (not really + * a surprise, but handled as if it were), or renegotiation requests. + * Also if record payloads contain fragments too small to process, we store + * them until there is enough for the respective protocol (the record protocol + * may use arbitrary fragmentation and even interleaving): + * Change cipher spec protocol + * just 1 byte needed, no need for keeping anything stored + * Alert protocol + * 2 bytes needed (AlertLevel, AlertDescription) + * Handshake protocol + * 4 bytes needed (HandshakeType, uint24 length) -- we just have + * to detect unexpected Client Hello and Hello Request messages + * here, anything else is handled by higher layers + * Application data protocol + * none of our business + */ +int ssl3_read_bytes(SSL *s, int type, unsigned char *buf, int len, int peek) + { + int al,i,j,ret; + unsigned int n; + SSL3_RECORD *rr; + void (*cb)(const SSL *ssl,int type2,int val)=NULL; + + if (s->s3->rbuf.buf == NULL) /* Not initialized yet */ + if (!ssl3_setup_read_buffer(s)) + return(-1); + + if ((type && (type != SSL3_RT_APPLICATION_DATA) && (type != SSL3_RT_HANDSHAKE) && type) || + (peek && (type != SSL3_RT_APPLICATION_DATA))) + { + SSLerr(SSL_F_SSL3_READ_BYTES, ERR_R_INTERNAL_ERROR); + return -1; + } + + if ((type == SSL3_RT_HANDSHAKE) && (s->s3->handshake_fragment_len > 0)) + /* (partially) satisfy request from storage */ + { + unsigned char *src = s->s3->handshake_fragment; + unsigned char *dst = buf; + unsigned int k; + + /* peek == 0 */ + n = 0; + while ((len > 0) && (s->s3->handshake_fragment_len > 0)) + { + *dst++ = *src++; + len--; s->s3->handshake_fragment_len--; + n++; + } + /* move any remaining fragment bytes: */ + for (k = 0; k < s->s3->handshake_fragment_len; k++) + s->s3->handshake_fragment[k] = *src++; + return n; + } + + /* Now s->s3->handshake_fragment_len == 0 if type == SSL3_RT_HANDSHAKE. */ + + if (!s->in_handshake && SSL_in_init(s)) + { + /* type == SSL3_RT_APPLICATION_DATA */ + i=s->handshake_func(s); + if (i < 0) return(i); + if (i == 0) + { + SSLerr(SSL_F_SSL3_READ_BYTES,SSL_R_SSL_HANDSHAKE_FAILURE); + return(-1); + } + } +start: + s->rwstate=SSL_NOTHING; + + /* s->s3->rrec.type - is the type of record + * s->s3->rrec.data, - data + * s->s3->rrec.off, - offset into 'data' for next read + * s->s3->rrec.length, - number of bytes. */ + rr = &(s->s3->rrec); + + /* get new packet if necessary */ + if ((rr->length == 0) || (s->rstate == SSL_ST_READ_BODY)) + { + ret=ssl3_get_record(s); + if (ret <= 0) return(ret); + } + + /* we now have a packet which can be read and processed */ + + if (s->s3->change_cipher_spec /* set when we receive ChangeCipherSpec, + * reset by ssl3_get_finished */ + && (rr->type != SSL3_RT_HANDSHAKE)) + { + al=SSL_AD_UNEXPECTED_MESSAGE; + SSLerr(SSL_F_SSL3_READ_BYTES,SSL_R_DATA_BETWEEN_CCS_AND_FINISHED); + goto f_err; + } + + /* If the other end has shut down, throw anything we read away + * (even in 'peek' mode) */ + if (s->shutdown & SSL_RECEIVED_SHUTDOWN) + { + rr->length=0; + s->rwstate=SSL_NOTHING; + return(0); + } + + + if (type == rr->type) /* SSL3_RT_APPLICATION_DATA or SSL3_RT_HANDSHAKE */ + { + /* make sure that we are not getting application data when we + * are doing a handshake for the first time */ + if (SSL_in_init(s) && (type == SSL3_RT_APPLICATION_DATA) && + (s->enc_read_ctx == NULL)) + { + al=SSL_AD_UNEXPECTED_MESSAGE; + SSLerr(SSL_F_SSL3_READ_BYTES,SSL_R_APP_DATA_IN_HANDSHAKE); + goto f_err; + } + + if (len <= 0) return(len); + + if ((unsigned int)len > rr->length) + n = rr->length; + else + n = (unsigned int)len; + + memcpy(buf,&(rr->data[rr->off]),n); + if (!peek) + { + rr->length-=n; + rr->off+=n; + if (rr->length == 0) + { + s->rstate=SSL_ST_READ_HEADER; + rr->off=0; + if (s->mode & SSL_MODE_RELEASE_BUFFERS) + ssl3_release_read_buffer(s); + } + } + return(n); + } + + + /* If we get here, then type != rr->type; if we have a handshake + * message, then it was unexpected (Hello Request or Client Hello). */ + + /* In case of record types for which we have 'fragment' storage, + * fill that so that we can process the data at a fixed place. + */ + { + unsigned int dest_maxlen = 0; + unsigned char *dest = NULL; + unsigned int *dest_len = NULL; + + if (rr->type == SSL3_RT_HANDSHAKE) + { + dest_maxlen = sizeof s->s3->handshake_fragment; + dest = s->s3->handshake_fragment; + dest_len = &s->s3->handshake_fragment_len; + } + else if (rr->type == SSL3_RT_ALERT) + { + dest_maxlen = sizeof s->s3->alert_fragment; + dest = s->s3->alert_fragment; + dest_len = &s->s3->alert_fragment_len; + } + + if (dest_maxlen > 0) + { + n = dest_maxlen - *dest_len; /* available space in 'dest' */ + if (rr->length < n) + n = rr->length; /* available bytes */ + + /* now move 'n' bytes: */ + while (n-- > 0) + { + dest[(*dest_len)++] = rr->data[rr->off++]; + rr->length--; + } + + if (*dest_len < dest_maxlen) + goto start; /* fragment was too small */ + } + } + + /* s->s3->handshake_fragment_len == 4 iff rr->type == SSL3_RT_HANDSHAKE; + * s->s3->alert_fragment_len == 2 iff rr->type == SSL3_RT_ALERT. + * (Possibly rr is 'empty' now, i.e. rr->length may be 0.) */ + + /* If we are a client, check for an incoming 'Hello Request': */ + if ((!s->server) && + (s->s3->handshake_fragment_len >= 4) && + (s->s3->handshake_fragment[0] == SSL3_MT_HELLO_REQUEST) && + (s->session != NULL) && (s->session->cipher != NULL)) + { + s->s3->handshake_fragment_len = 0; + + if ((s->s3->handshake_fragment[1] != 0) || + (s->s3->handshake_fragment[2] != 0) || + (s->s3->handshake_fragment[3] != 0)) + { + al=SSL_AD_DECODE_ERROR; + SSLerr(SSL_F_SSL3_READ_BYTES,SSL_R_BAD_HELLO_REQUEST); + goto f_err; + } + + if (s->msg_callback) + s->msg_callback(0, s->version, SSL3_RT_HANDSHAKE, s->s3->handshake_fragment, 4, s, s->msg_callback_arg); + + if (SSL_is_init_finished(s) && + !(s->s3->flags & SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS) && + !s->s3->renegotiate) + { + ssl3_renegotiate(s); + if (ssl3_renegotiate_check(s)) + { + i=s->handshake_func(s); + if (i < 0) return(i); + if (i == 0) + { + SSLerr(SSL_F_SSL3_READ_BYTES,SSL_R_SSL_HANDSHAKE_FAILURE); + return(-1); + } + + if (!(s->mode & SSL_MODE_AUTO_RETRY)) + { + if (s->s3->rbuf.left == 0) /* no read-ahead left? */ + { + BIO *bio; + /* In the case where we try to read application data, + * but we trigger an SSL handshake, we return -1 with + * the retry option set. Otherwise renegotiation may + * cause nasty problems in the blocking world */ + s->rwstate=SSL_READING; + bio=SSL_get_rbio(s); + BIO_clear_retry_flags(bio); + BIO_set_retry_read(bio); + return(-1); + } + } + } + } + /* we either finished a handshake or ignored the request, + * now try again to obtain the (application) data we were asked for */ + goto start; + } + /* If we are a server and get a client hello when renegotiation isn't + * allowed send back a no renegotiation alert and carry on. + * WARNING: experimental code, needs reviewing (steve) + */ + if (s->server && + SSL_is_init_finished(s) && + !s->s3->send_connection_binding && + (s->version > SSL3_VERSION) && + (s->s3->handshake_fragment_len >= 4) && + (s->s3->handshake_fragment[0] == SSL3_MT_CLIENT_HELLO) && + (s->session != NULL) && (s->session->cipher != NULL) && + !(s->ctx->options & SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION)) + + { + /*s->s3->handshake_fragment_len = 0;*/ + rr->length = 0; + ssl3_send_alert(s,SSL3_AL_WARNING, SSL_AD_NO_RENEGOTIATION); + goto start; + } + if (s->s3->alert_fragment_len >= 2) + { + int alert_level = s->s3->alert_fragment[0]; + int alert_descr = s->s3->alert_fragment[1]; + + s->s3->alert_fragment_len = 0; + + if (s->msg_callback) + s->msg_callback(0, s->version, SSL3_RT_ALERT, s->s3->alert_fragment, 2, s, s->msg_callback_arg); + + if (s->info_callback != NULL) + cb=s->info_callback; + else if (s->ctx->info_callback != NULL) + cb=s->ctx->info_callback; + + if (cb != NULL) + { + j = (alert_level << 8) | alert_descr; + cb(s, SSL_CB_READ_ALERT, j); + } + + if (alert_level == 1) /* warning */ + { + s->s3->warn_alert = alert_descr; + if (alert_descr == SSL_AD_CLOSE_NOTIFY) + { + s->shutdown |= SSL_RECEIVED_SHUTDOWN; + return(0); + } + /* This is a warning but we receive it if we requested + * renegotiation and the peer denied it. Terminate with + * a fatal alert because if application tried to + * renegotiatie it presumably had a good reason and + * expects it to succeed. + * + * In future we might have a renegotiation where we + * don't care if the peer refused it where we carry on. + */ + else if (alert_descr == SSL_AD_NO_RENEGOTIATION) + { + al = SSL_AD_HANDSHAKE_FAILURE; + SSLerr(SSL_F_SSL3_READ_BYTES,SSL_R_NO_RENEGOTIATION); + goto f_err; + } + } + else if (alert_level == 2) /* fatal */ + { + char tmp[16]; + + s->rwstate=SSL_NOTHING; + s->s3->fatal_alert = alert_descr; + SSLerr(SSL_F_SSL3_READ_BYTES, SSL_AD_REASON_OFFSET + alert_descr); + BIO_snprintf(tmp,sizeof tmp,"%d",alert_descr); + ERR_add_error_data(2,"SSL alert number ",tmp); + s->shutdown|=SSL_RECEIVED_SHUTDOWN; + SSL_CTX_remove_session(s->ctx,s->session); + return(0); + } + else + { + al=SSL_AD_ILLEGAL_PARAMETER; + SSLerr(SSL_F_SSL3_READ_BYTES,SSL_R_UNKNOWN_ALERT_TYPE); + goto f_err; + } + + goto start; + } + + if (s->shutdown & SSL_SENT_SHUTDOWN) /* but we have not received a shutdown */ + { + s->rwstate=SSL_NOTHING; + rr->length=0; + return(0); + } + + if (rr->type == SSL3_RT_CHANGE_CIPHER_SPEC) + { + /* 'Change Cipher Spec' is just a single byte, so we know + * exactly what the record payload has to look like */ + if ( (rr->length != 1) || (rr->off != 0) || + (rr->data[0] != SSL3_MT_CCS)) + { + al=SSL_AD_ILLEGAL_PARAMETER; + SSLerr(SSL_F_SSL3_READ_BYTES,SSL_R_BAD_CHANGE_CIPHER_SPEC); + goto f_err; + } + + /* Check we have a cipher to change to */ + if (s->s3->tmp.new_cipher == NULL) + { + al=SSL_AD_UNEXPECTED_MESSAGE; + SSLerr(SSL_F_SSL3_READ_BYTES,SSL_R_CCS_RECEIVED_EARLY); + goto f_err; + } + + rr->length=0; + + if (s->msg_callback) + s->msg_callback(0, s->version, SSL3_RT_CHANGE_CIPHER_SPEC, rr->data, 1, s, s->msg_callback_arg); + + s->s3->change_cipher_spec=1; + if (!ssl3_do_change_cipher_spec(s)) + goto err; + else + goto start; + } + + /* Unexpected handshake message (Client Hello, or protocol violation) */ + if ((s->s3->handshake_fragment_len >= 4) && !s->in_handshake) + { + if (((s->state&SSL_ST_MASK) == SSL_ST_OK) && + !(s->s3->flags & SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS)) + { +#if 0 /* worked only because C operator preferences are not as expected (and + * because this is not really needed for clients except for detecting + * protocol violations): */ + s->state=SSL_ST_BEFORE|(s->server) + ?SSL_ST_ACCEPT + :SSL_ST_CONNECT; +#else + s->state = s->server ? SSL_ST_ACCEPT : SSL_ST_CONNECT; +#endif + s->new_session=1; + } + i=s->handshake_func(s); + if (i < 0) return(i); + if (i == 0) + { + SSLerr(SSL_F_SSL3_READ_BYTES,SSL_R_SSL_HANDSHAKE_FAILURE); + return(-1); + } + + if (!(s->mode & SSL_MODE_AUTO_RETRY)) + { + if (s->s3->rbuf.left == 0) /* no read-ahead left? */ + { + BIO *bio; + /* In the case where we try to read application data, + * but we trigger an SSL handshake, we return -1 with + * the retry option set. Otherwise renegotiation may + * cause nasty problems in the blocking world */ + s->rwstate=SSL_READING; + bio=SSL_get_rbio(s); + BIO_clear_retry_flags(bio); + BIO_set_retry_read(bio); + return(-1); + } + } + goto start; + } + + switch (rr->type) + { + default: +#ifndef OPENSSL_NO_TLS + /* TLS just ignores unknown message types */ + if (s->version == TLS1_VERSION) + { + rr->length = 0; + goto start; + } +#endif + al=SSL_AD_UNEXPECTED_MESSAGE; + SSLerr(SSL_F_SSL3_READ_BYTES,SSL_R_UNEXPECTED_RECORD); + goto f_err; + case SSL3_RT_CHANGE_CIPHER_SPEC: + case SSL3_RT_ALERT: + case SSL3_RT_HANDSHAKE: + /* we already handled all of these, with the possible exception + * of SSL3_RT_HANDSHAKE when s->in_handshake is set, but that + * should not happen when type != rr->type */ + al=SSL_AD_UNEXPECTED_MESSAGE; + SSLerr(SSL_F_SSL3_READ_BYTES,ERR_R_INTERNAL_ERROR); + goto f_err; + case SSL3_RT_APPLICATION_DATA: + /* At this point, we were expecting handshake data, + * but have application data. If the library was + * running inside ssl3_read() (i.e. in_read_app_data + * is set) and it makes sense to read application data + * at this point (session renegotiation not yet started), + * we will indulge it. + */ + if (s->s3->in_read_app_data && + (s->s3->total_renegotiations != 0) && + (( + (s->state & SSL_ST_CONNECT) && + (s->state >= SSL3_ST_CW_CLNT_HELLO_A) && + (s->state <= SSL3_ST_CR_SRVR_HELLO_A) + ) || ( + (s->state & SSL_ST_ACCEPT) && + (s->state <= SSL3_ST_SW_HELLO_REQ_A) && + (s->state >= SSL3_ST_SR_CLNT_HELLO_A) + ) + )) + { + s->s3->in_read_app_data=2; + return(-1); + } + else + { + al=SSL_AD_UNEXPECTED_MESSAGE; + SSLerr(SSL_F_SSL3_READ_BYTES,SSL_R_UNEXPECTED_RECORD); + goto f_err; + } + } + /* not reached */ + +f_err: + ssl3_send_alert(s,SSL3_AL_FATAL,al); +err: + return(-1); + } + +int ssl3_do_change_cipher_spec(SSL *s) + { + int i; +#ifdef OPENSSL_NO_NEXTPROTONEG + const char *sender; + int slen; +#endif + + if (s->state & SSL_ST_ACCEPT) + i=SSL3_CHANGE_CIPHER_SERVER_READ; + else + i=SSL3_CHANGE_CIPHER_CLIENT_READ; + + if (s->s3->tmp.key_block == NULL) + { + if (s->session == NULL) + { + /* might happen if dtls1_read_bytes() calls this */ + SSLerr(SSL_F_SSL3_DO_CHANGE_CIPHER_SPEC,SSL_R_CCS_RECEIVED_EARLY); + return (0); + } + + s->session->cipher=s->s3->tmp.new_cipher; + if (!s->method->ssl3_enc->setup_key_block(s)) return(0); + } + + if (!s->method->ssl3_enc->change_cipher_state(s,i)) + return(0); + +#ifdef OPENSSL_NO_NEXTPROTONEG + /* we have to record the message digest at + * this point so we can get it before we read + * the finished message */ + if (s->state & SSL_ST_CONNECT) + { + sender=s->method->ssl3_enc->server_finished_label; + slen=s->method->ssl3_enc->server_finished_label_len; + } + else + { + sender=s->method->ssl3_enc->client_finished_label; + slen=s->method->ssl3_enc->client_finished_label_len; + } + + s->s3->tmp.peer_finish_md_len = s->method->ssl3_enc->final_finish_mac(s, + sender,slen,s->s3->tmp.peer_finish_md); +#endif + + return(1); + } + +int ssl3_send_alert(SSL *s, int level, int desc) + { + /* Map tls/ssl alert value to correct one */ + desc=s->method->ssl3_enc->alert_value(desc); + if (s->version == SSL3_VERSION && desc == SSL_AD_PROTOCOL_VERSION) + desc = SSL_AD_HANDSHAKE_FAILURE; /* SSL 3.0 does not have protocol_version alerts */ + if (desc < 0) return -1; + /* If a fatal one, remove from cache */ + if ((level == 2) && (s->session != NULL)) + SSL_CTX_remove_session(s->ctx,s->session); + + s->s3->alert_dispatch=1; + s->s3->send_alert[0]=level; + s->s3->send_alert[1]=desc; + if (s->s3->wbuf.left == 0) /* data still being written out? */ + return s->method->ssl_dispatch_alert(s); + /* else data is still being written out, we will get written + * some time in the future */ + return -1; + } + +int ssl3_dispatch_alert(SSL *s) + { + int i,j; + void (*cb)(const SSL *ssl,int type,int val)=NULL; + + s->s3->alert_dispatch=0; + i = do_ssl3_write(s, SSL3_RT_ALERT, &s->s3->send_alert[0], 2, 0); + if (i <= 0) + { + s->s3->alert_dispatch=1; + } + else + { + /* Alert sent to BIO. If it is important, flush it now. + * If the message does not get sent due to non-blocking IO, + * we will not worry too much. */ + if (s->s3->send_alert[0] == SSL3_AL_FATAL) + (void)BIO_flush(s->wbio); + + if (s->msg_callback) + s->msg_callback(1, s->version, SSL3_RT_ALERT, s->s3->send_alert, 2, s, s->msg_callback_arg); + + if (s->info_callback != NULL) + cb=s->info_callback; + else if (s->ctx->info_callback != NULL) + cb=s->ctx->info_callback; + + if (cb != NULL) + { + j=(s->s3->send_alert[0]<<8)|s->s3->send_alert[1]; + cb(s,SSL_CB_WRITE_ALERT,j); + } + } + return(i); + } diff --git a/node-v0.8.14/deps/openssl/openssl/ssl/s3_srvr.c b/node-v0.8.14/deps/openssl/openssl/ssl/s3_srvr.c new file mode 100644 index 0000000..41e597f --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/ssl/s3_srvr.c @@ -0,0 +1,3325 @@ +/* ssl/s3_srvr.c -*- mode:C; c-file-style: "eay" -*- */ +/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com) + * All rights reserved. + * + * This package is an SSL implementation written + * by Eric Young (eay@cryptsoft.com). + * The implementation was written so as to conform with Netscapes SSL. + * + * This library is free for commercial and non-commercial use as long as + * the following conditions are aheared to. The following conditions + * apply to all code found in this distribution, be it the RC4, RSA, + * lhash, DES, etc., code; not just the SSL code. The SSL documentation + * included with this distribution is covered by the same copyright terms + * except that the holder is Tim Hudson (tjh@cryptsoft.com). + * + * Copyright remains Eric Young's, and as such any Copyright notices in + * the code are not to be removed. + * If this package is used in a product, Eric Young should be given attribution + * as the author of the parts of the library used. + * This can be in the form of a textual message at program startup or + * in documentation (online or textual) provided with the package. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * "This product includes cryptographic software written by + * Eric Young (eay@cryptsoft.com)" + * The word 'cryptographic' can be left out if the rouines from the library + * being used are not cryptographic related :-). + * 4. If you include any Windows specific code (or a derivative thereof) from + * the apps directory (application code) you must include an acknowledgement: + * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)" + * + * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * + * The licence and distribution terms for any publically available version or + * derivative of this code cannot be changed. i.e. this code cannot simply be + * copied and put under another distribution licence + * [including the GNU Public Licence.] + */ +/* ==================================================================== + * Copyright (c) 1998-2007 The OpenSSL Project. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. All advertising materials mentioning features or use of this + * software must display the following acknowledgment: + * "This product includes software developed by the OpenSSL Project + * for use in the OpenSSL Toolkit. (http://www.openssl.org/)" + * + * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to + * endorse or promote products derived from this software without + * prior written permission. For written permission, please contact + * openssl-core@openssl.org. + * + * 5. Products derived from this software may not be called "OpenSSL" + * nor may "OpenSSL" appear in their names without prior written + * permission of the OpenSSL Project. + * + * 6. Redistributions of any form whatsoever must retain the following + * acknowledgment: + * "This product includes software developed by the OpenSSL Project + * for use in the OpenSSL Toolkit (http://www.openssl.org/)" + * + * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY + * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR + * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, + * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * ==================================================================== + * + * This product includes cryptographic software written by Eric Young + * (eay@cryptsoft.com). This product includes software written by Tim + * Hudson (tjh@cryptsoft.com). + * + */ +/* ==================================================================== + * Copyright 2002 Sun Microsystems, Inc. ALL RIGHTS RESERVED. + * + * Portions of the attached software ("Contribution") are developed by + * SUN MICROSYSTEMS, INC., and are contributed to the OpenSSL project. + * + * The Contribution is licensed pursuant to the OpenSSL open source + * license provided above. + * + * ECC cipher suite support in OpenSSL originally written by + * Vipul Gupta and Sumit Gupta of Sun Microsystems Laboratories. + * + */ +/* ==================================================================== + * Copyright 2005 Nokia. All rights reserved. + * + * The portions of the attached software ("Contribution") is developed by + * Nokia Corporation and is licensed pursuant to the OpenSSL open source + * license. + * + * The Contribution, originally written by Mika Kousa and Pasi Eronen of + * Nokia Corporation, consists of the "PSK" (Pre-Shared Key) ciphersuites + * support (see RFC 4279) to OpenSSL. + * + * No patent licenses or other rights except those expressly stated in + * the OpenSSL open source license shall be deemed granted or received + * expressly, by implication, estoppel, or otherwise. + * + * No assurances are provided by Nokia that the Contribution does not + * infringe the patent or other intellectual property rights of any third + * party or that the license provides you with all the necessary rights + * to make use of the Contribution. + * + * THE SOFTWARE IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND. IN + * ADDITION TO THE DISCLAIMERS INCLUDED IN THE LICENSE, NOKIA + * SPECIFICALLY DISCLAIMS ANY LIABILITY FOR CLAIMS BROUGHT BY YOU OR ANY + * OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL PROPERTY RIGHTS OR + * OTHERWISE. + */ + +#define REUSE_CIPHER_BUG +#define NETSCAPE_HANG_BUG + +#include +#include "ssl_locl.h" +#include "kssl_lcl.h" +#include +#include +#include +#include +#include +#include +#ifndef OPENSSL_NO_DH +#include +#endif +#include +#ifndef OPENSSL_NO_KRB5 +#include +#endif +#include + +static const SSL_METHOD *ssl3_get_server_method(int ver); + +static const SSL_METHOD *ssl3_get_server_method(int ver) + { + if (ver == SSL3_VERSION) + return(SSLv3_server_method()); + else + return(NULL); + } + +IMPLEMENT_ssl3_meth_func(SSLv3_server_method, + ssl3_accept, + ssl_undefined_function, + ssl3_get_server_method) + +int ssl3_accept(SSL *s) + { + BUF_MEM *buf; + unsigned long alg_k,Time=(unsigned long)time(NULL); + void (*cb)(const SSL *ssl,int type,int val)=NULL; + int ret= -1; + int new_state,state,skip=0; + + RAND_add(&Time,sizeof(Time),0); + ERR_clear_error(); + clear_sys_error(); + + if (s->info_callback != NULL) + cb=s->info_callback; + else if (s->ctx->info_callback != NULL) + cb=s->ctx->info_callback; + + /* init things to blank */ + s->in_handshake++; + if (!SSL_in_init(s) || SSL_in_before(s)) SSL_clear(s); + + if (s->cert == NULL) + { + SSLerr(SSL_F_SSL3_ACCEPT,SSL_R_NO_CERTIFICATE_SET); + return(-1); + } + + for (;;) + { + state=s->state; + + switch (s->state) + { + case SSL_ST_RENEGOTIATE: + s->new_session=1; + /* s->state=SSL_ST_ACCEPT; */ + + case SSL_ST_BEFORE: + case SSL_ST_ACCEPT: + case SSL_ST_BEFORE|SSL_ST_ACCEPT: + case SSL_ST_OK|SSL_ST_ACCEPT: + + s->server=1; + if (cb != NULL) cb(s,SSL_CB_HANDSHAKE_START,1); + + if ((s->version>>8) != 3) + { + SSLerr(SSL_F_SSL3_ACCEPT, ERR_R_INTERNAL_ERROR); + return -1; + } + s->type=SSL_ST_ACCEPT; + + if (s->init_buf == NULL) + { + if ((buf=BUF_MEM_new()) == NULL) + { + ret= -1; + goto end; + } + if (!BUF_MEM_grow(buf,SSL3_RT_MAX_PLAIN_LENGTH)) + { + ret= -1; + goto end; + } + s->init_buf=buf; + } + + if (!ssl3_setup_buffers(s)) + { + ret= -1; + goto end; + } + + s->init_num=0; + s->s3->flags &= ~SSL3_FLAGS_SGC_RESTART_DONE; + + if (s->state != SSL_ST_RENEGOTIATE) + { + /* Ok, we now need to push on a buffering BIO so that + * the output is sent in a way that TCP likes :-) + */ + if (!ssl_init_wbio_buffer(s,1)) { ret= -1; goto end; } + + ssl3_init_finished_mac(s); + s->state=SSL3_ST_SR_CLNT_HELLO_A; + s->ctx->stats.sess_accept++; + } + else if (!s->s3->send_connection_binding && + !(s->options & SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION)) + { + /* Server attempting to renegotiate with + * client that doesn't support secure + * renegotiation. + */ + SSLerr(SSL_F_SSL3_ACCEPT, SSL_R_UNSAFE_LEGACY_RENEGOTIATION_DISABLED); + ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_HANDSHAKE_FAILURE); + ret = -1; + goto end; + } + else + { + /* s->state == SSL_ST_RENEGOTIATE, + * we will just send a HelloRequest */ + s->ctx->stats.sess_accept_renegotiate++; + s->state=SSL3_ST_SW_HELLO_REQ_A; + } + break; + + case SSL3_ST_SW_HELLO_REQ_A: + case SSL3_ST_SW_HELLO_REQ_B: + + s->shutdown=0; + ret=ssl3_send_hello_request(s); + if (ret <= 0) goto end; + s->s3->tmp.next_state=SSL3_ST_SW_HELLO_REQ_C; + s->state=SSL3_ST_SW_FLUSH; + s->init_num=0; + + ssl3_init_finished_mac(s); + break; + + case SSL3_ST_SW_HELLO_REQ_C: + s->state=SSL_ST_OK; + break; + + case SSL3_ST_SR_CLNT_HELLO_A: + case SSL3_ST_SR_CLNT_HELLO_B: + case SSL3_ST_SR_CLNT_HELLO_C: + + s->shutdown=0; + ret=ssl3_get_client_hello(s); + if (ret <= 0) goto end; + + s->new_session = 2; + s->state=SSL3_ST_SW_SRVR_HELLO_A; + s->init_num=0; + break; + + case SSL3_ST_SW_SRVR_HELLO_A: + case SSL3_ST_SW_SRVR_HELLO_B: + ret=ssl3_send_server_hello(s); + if (ret <= 0) goto end; +#ifndef OPENSSL_NO_TLSEXT + if (s->hit) + { + if (s->tlsext_ticket_expected) + s->state=SSL3_ST_SW_SESSION_TICKET_A; + else + s->state=SSL3_ST_SW_CHANGE_A; + } +#else + if (s->hit) + s->state=SSL3_ST_SW_CHANGE_A; +#endif + else + s->state=SSL3_ST_SW_CERT_A; + s->init_num=0; + break; + + case SSL3_ST_SW_CERT_A: + case SSL3_ST_SW_CERT_B: + /* Check if it is anon DH or anon ECDH, */ + /* normal PSK or KRB5 */ + if (!(s->s3->tmp.new_cipher->algorithm_auth & SSL_aNULL) + && !(s->s3->tmp.new_cipher->algorithm_mkey & SSL_kPSK) + && !(s->s3->tmp.new_cipher->algorithm_auth & SSL_aKRB5)) + { + ret=ssl3_send_server_certificate(s); + if (ret <= 0) goto end; +#ifndef OPENSSL_NO_TLSEXT + if (s->tlsext_status_expected) + s->state=SSL3_ST_SW_CERT_STATUS_A; + else + s->state=SSL3_ST_SW_KEY_EXCH_A; + } + else + { + skip = 1; + s->state=SSL3_ST_SW_KEY_EXCH_A; + } +#else + } + else + skip=1; + + s->state=SSL3_ST_SW_KEY_EXCH_A; +#endif + s->init_num=0; + break; + + case SSL3_ST_SW_KEY_EXCH_A: + case SSL3_ST_SW_KEY_EXCH_B: + alg_k = s->s3->tmp.new_cipher->algorithm_mkey; + + /* clear this, it may get reset by + * send_server_key_exchange */ + if ((s->options & SSL_OP_EPHEMERAL_RSA) +#ifndef OPENSSL_NO_KRB5 + && !(alg_k & SSL_kKRB5) +#endif /* OPENSSL_NO_KRB5 */ + ) + /* option SSL_OP_EPHEMERAL_RSA sends temporary RSA key + * even when forbidden by protocol specs + * (handshake may fail as clients are not required to + * be able to handle this) */ + s->s3->tmp.use_rsa_tmp=1; + else + s->s3->tmp.use_rsa_tmp=0; + + + /* only send if a DH key exchange, fortezza or + * RSA but we have a sign only certificate + * + * PSK: may send PSK identity hints + * + * For ECC ciphersuites, we send a serverKeyExchange + * message only if the cipher suite is either + * ECDH-anon or ECDHE. In other cases, the + * server certificate contains the server's + * public key for key exchange. + */ + if (s->s3->tmp.use_rsa_tmp + /* PSK: send ServerKeyExchange if PSK identity + * hint if provided */ +#ifndef OPENSSL_NO_PSK + || ((alg_k & SSL_kPSK) && s->ctx->psk_identity_hint) +#endif + || (alg_k & (SSL_kDHr|SSL_kDHd|SSL_kEDH)) + || (alg_k & SSL_kEECDH) + || ((alg_k & SSL_kRSA) + && (s->cert->pkeys[SSL_PKEY_RSA_ENC].privatekey == NULL + || (SSL_C_IS_EXPORT(s->s3->tmp.new_cipher) + && EVP_PKEY_size(s->cert->pkeys[SSL_PKEY_RSA_ENC].privatekey)*8 > SSL_C_EXPORT_PKEYLENGTH(s->s3->tmp.new_cipher) + ) + ) + ) + ) + { + ret=ssl3_send_server_key_exchange(s); + if (ret <= 0) goto end; + } + else + skip=1; + + s->state=SSL3_ST_SW_CERT_REQ_A; + s->init_num=0; + break; + + case SSL3_ST_SW_CERT_REQ_A: + case SSL3_ST_SW_CERT_REQ_B: + if (/* don't request cert unless asked for it: */ + !(s->verify_mode & SSL_VERIFY_PEER) || + /* if SSL_VERIFY_CLIENT_ONCE is set, + * don't request cert during re-negotiation: */ + ((s->session->peer != NULL) && + (s->verify_mode & SSL_VERIFY_CLIENT_ONCE)) || + /* never request cert in anonymous ciphersuites + * (see section "Certificate request" in SSL 3 drafts + * and in RFC 2246): */ + ((s->s3->tmp.new_cipher->algorithm_auth & SSL_aNULL) && + /* ... except when the application insists on verification + * (against the specs, but s3_clnt.c accepts this for SSL 3) */ + !(s->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT)) || + /* never request cert in Kerberos ciphersuites */ + (s->s3->tmp.new_cipher->algorithm_auth & SSL_aKRB5) + /* With normal PSK Certificates and + * Certificate Requests are omitted */ + || (s->s3->tmp.new_cipher->algorithm_mkey & SSL_kPSK)) + { + /* no cert request */ + skip=1; + s->s3->tmp.cert_request=0; + s->state=SSL3_ST_SW_SRVR_DONE_A; + } + else + { + s->s3->tmp.cert_request=1; + ret=ssl3_send_certificate_request(s); + if (ret <= 0) goto end; +#ifndef NETSCAPE_HANG_BUG + s->state=SSL3_ST_SW_SRVR_DONE_A; +#else + s->state=SSL3_ST_SW_FLUSH; + s->s3->tmp.next_state=SSL3_ST_SR_CERT_A; +#endif + s->init_num=0; + } + break; + + case SSL3_ST_SW_SRVR_DONE_A: + case SSL3_ST_SW_SRVR_DONE_B: + ret=ssl3_send_server_done(s); + if (ret <= 0) goto end; + s->s3->tmp.next_state=SSL3_ST_SR_CERT_A; + s->state=SSL3_ST_SW_FLUSH; + s->init_num=0; + break; + + case SSL3_ST_SW_FLUSH: + + /* This code originally checked to see if + * any data was pending using BIO_CTRL_INFO + * and then flushed. This caused problems + * as documented in PR#1939. The proposed + * fix doesn't completely resolve this issue + * as buggy implementations of BIO_CTRL_PENDING + * still exist. So instead we just flush + * unconditionally. + */ + + s->rwstate=SSL_WRITING; + if (BIO_flush(s->wbio) <= 0) + { + ret= -1; + goto end; + } + s->rwstate=SSL_NOTHING; + + s->state=s->s3->tmp.next_state; + break; + + case SSL3_ST_SR_CERT_A: + case SSL3_ST_SR_CERT_B: + /* Check for second client hello (MS SGC) */ + ret = ssl3_check_client_hello(s); + if (ret <= 0) + goto end; + if (ret == 2) + s->state = SSL3_ST_SR_CLNT_HELLO_C; + else { + if (s->s3->tmp.cert_request) + { + ret=ssl3_get_client_certificate(s); + if (ret <= 0) goto end; + } + s->init_num=0; + s->state=SSL3_ST_SR_KEY_EXCH_A; + } + break; + + case SSL3_ST_SR_KEY_EXCH_A: + case SSL3_ST_SR_KEY_EXCH_B: + ret=ssl3_get_client_key_exchange(s); + if (ret <= 0) + goto end; + if (ret == 2) + { + /* For the ECDH ciphersuites when + * the client sends its ECDH pub key in + * a certificate, the CertificateVerify + * message is not sent. + * Also for GOST ciphersuites when + * the client uses its key from the certificate + * for key exchange. + */ +#if defined(OPENSSL_NO_TLSEXT) || defined(OPENSSL_NO_NEXTPROTONEG) + s->state=SSL3_ST_SR_FINISHED_A; +#else + if (s->s3->next_proto_neg_seen) + s->state=SSL3_ST_SR_NEXT_PROTO_A; + else + s->state=SSL3_ST_SR_FINISHED_A; +#endif + s->init_num = 0; + } + else + { + int offset=0; + int dgst_num; + + s->state=SSL3_ST_SR_CERT_VRFY_A; + s->init_num=0; + + /* We need to get hashes here so if there is + * a client cert, it can be verified + * FIXME - digest processing for CertificateVerify + * should be generalized. But it is next step + */ + if (s->s3->handshake_buffer) + if (!ssl3_digest_cached_records(s)) + return -1; + for (dgst_num=0; dgst_nums3->handshake_dgst[dgst_num]) + { + int dgst_size; + + s->method->ssl3_enc->cert_verify_mac(s,EVP_MD_CTX_type(s->s3->handshake_dgst[dgst_num]),&(s->s3->tmp.cert_verify_md[offset])); + dgst_size=EVP_MD_CTX_size(s->s3->handshake_dgst[dgst_num]); + if (dgst_size < 0) + { + ret = -1; + goto end; + } + offset+=dgst_size; + } + } + break; + + case SSL3_ST_SR_CERT_VRFY_A: + case SSL3_ST_SR_CERT_VRFY_B: + + /* we should decide if we expected this one */ + ret=ssl3_get_cert_verify(s); + if (ret <= 0) goto end; + +#if defined(OPENSSL_NO_TLSEXT) || defined(OPENSSL_NO_NEXTPROTONEG) + s->state=SSL3_ST_SR_FINISHED_A; +#else + if (s->s3->next_proto_neg_seen) + s->state=SSL3_ST_SR_NEXT_PROTO_A; + else + s->state=SSL3_ST_SR_FINISHED_A; +#endif + s->init_num=0; + break; + +#if !defined(OPENSSL_NO_TLSEXT) && !defined(OPENSSL_NO_NEXTPROTONEG) + case SSL3_ST_SR_NEXT_PROTO_A: + case SSL3_ST_SR_NEXT_PROTO_B: + ret=ssl3_get_next_proto(s); + if (ret <= 0) goto end; + s->init_num = 0; + s->state=SSL3_ST_SR_FINISHED_A; + break; +#endif + + case SSL3_ST_SR_FINISHED_A: + case SSL3_ST_SR_FINISHED_B: + ret=ssl3_get_finished(s,SSL3_ST_SR_FINISHED_A, + SSL3_ST_SR_FINISHED_B); + if (ret <= 0) goto end; +#ifndef OPENSSL_NO_TLSEXT + if (s->tlsext_ticket_expected) + s->state=SSL3_ST_SW_SESSION_TICKET_A; + else if (s->hit) + s->state=SSL_ST_OK; +#else + if (s->hit) + s->state=SSL_ST_OK; +#endif + else + s->state=SSL3_ST_SW_CHANGE_A; + s->init_num=0; + break; + +#ifndef OPENSSL_NO_TLSEXT + case SSL3_ST_SW_SESSION_TICKET_A: + case SSL3_ST_SW_SESSION_TICKET_B: + ret=ssl3_send_newsession_ticket(s); + if (ret <= 0) goto end; + s->state=SSL3_ST_SW_CHANGE_A; + s->init_num=0; + break; + + case SSL3_ST_SW_CERT_STATUS_A: + case SSL3_ST_SW_CERT_STATUS_B: + ret=ssl3_send_cert_status(s); + if (ret <= 0) goto end; + s->state=SSL3_ST_SW_KEY_EXCH_A; + s->init_num=0; + break; + +#endif + + case SSL3_ST_SW_CHANGE_A: + case SSL3_ST_SW_CHANGE_B: + + s->session->cipher=s->s3->tmp.new_cipher; + if (!s->method->ssl3_enc->setup_key_block(s)) + { ret= -1; goto end; } + + ret=ssl3_send_change_cipher_spec(s, + SSL3_ST_SW_CHANGE_A,SSL3_ST_SW_CHANGE_B); + + if (ret <= 0) goto end; + s->state=SSL3_ST_SW_FINISHED_A; + s->init_num=0; + + if (!s->method->ssl3_enc->change_cipher_state(s, + SSL3_CHANGE_CIPHER_SERVER_WRITE)) + { + ret= -1; + goto end; + } + + break; + + case SSL3_ST_SW_FINISHED_A: + case SSL3_ST_SW_FINISHED_B: + ret=ssl3_send_finished(s, + SSL3_ST_SW_FINISHED_A,SSL3_ST_SW_FINISHED_B, + s->method->ssl3_enc->server_finished_label, + s->method->ssl3_enc->server_finished_label_len); + if (ret <= 0) goto end; + s->state=SSL3_ST_SW_FLUSH; + if (s->hit) + { +#if defined(OPENSSL_NO_TLSEXT) || defined(OPENSSL_NO_NEXTPROTONEG) + s->s3->tmp.next_state=SSL3_ST_SR_FINISHED_A; +#else + if (s->s3->next_proto_neg_seen) + s->s3->tmp.next_state=SSL3_ST_SR_NEXT_PROTO_A; + else + s->s3->tmp.next_state=SSL3_ST_SR_FINISHED_A; +#endif + } + else + s->s3->tmp.next_state=SSL_ST_OK; + s->init_num=0; + break; + + case SSL_ST_OK: + /* clean a few things up */ + ssl3_cleanup_key_block(s); + + BUF_MEM_free(s->init_buf); + s->init_buf=NULL; + + /* remove buffering on output */ + ssl_free_wbio_buffer(s); + + s->init_num=0; + + if (s->new_session == 2) /* skipped if we just sent a HelloRequest */ + { + /* actually not necessarily a 'new' session unless + * SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION is set */ + + s->new_session=0; + + ssl_update_cache(s,SSL_SESS_CACHE_SERVER); + + s->ctx->stats.sess_accept_good++; + /* s->server=1; */ + s->handshake_func=ssl3_accept; + + if (cb != NULL) cb(s,SSL_CB_HANDSHAKE_DONE,1); + } + + ret = 1; + goto end; + /* break; */ + + default: + SSLerr(SSL_F_SSL3_ACCEPT,SSL_R_UNKNOWN_STATE); + ret= -1; + goto end; + /* break; */ + } + + if (!s->s3->tmp.reuse_message && !skip) + { + if (s->debug) + { + if ((ret=BIO_flush(s->wbio)) <= 0) + goto end; + } + + + if ((cb != NULL) && (s->state != state)) + { + new_state=s->state; + s->state=state; + cb(s,SSL_CB_ACCEPT_LOOP,1); + s->state=new_state; + } + } + skip=0; + } +end: + /* BIO_flush(s->wbio); */ + + s->in_handshake--; + if (cb != NULL) + cb(s,SSL_CB_ACCEPT_EXIT,ret); + return(ret); + } + +int ssl3_send_hello_request(SSL *s) + { + unsigned char *p; + + if (s->state == SSL3_ST_SW_HELLO_REQ_A) + { + p=(unsigned char *)s->init_buf->data; + *(p++)=SSL3_MT_HELLO_REQUEST; + *(p++)=0; + *(p++)=0; + *(p++)=0; + + s->state=SSL3_ST_SW_HELLO_REQ_B; + /* number of bytes to write */ + s->init_num=4; + s->init_off=0; + } + + /* SSL3_ST_SW_HELLO_REQ_B */ + return(ssl3_do_write(s,SSL3_RT_HANDSHAKE)); + } + +int ssl3_check_client_hello(SSL *s) + { + int ok; + long n; + + /* We only allow the client to restart the handshake once per + * negotiation. */ + if (s->s3->flags & SSL3_FLAGS_SGC_RESTART_DONE) + { + SSLerr(SSL_F_SSL3_CHECK_CLIENT_HELLO, SSL_R_MULTIPLE_SGC_RESTARTS); + return -1; + } + + /* this function is called when we really expect a Certificate message, + * so permit appropriate message length */ + n=s->method->ssl_get_message(s, + SSL3_ST_SR_CERT_A, + SSL3_ST_SR_CERT_B, + -1, + s->max_cert_list, + &ok); + if (!ok) return((int)n); + s->s3->tmp.reuse_message = 1; + if (s->s3->tmp.message_type == SSL3_MT_CLIENT_HELLO) + { + /* Throw away what we have done so far in the current handshake, + * which will now be aborted. (A full SSL_clear would be too much.) */ +#ifndef OPENSSL_NO_DH + if (s->s3->tmp.dh != NULL) + { + DH_free(s->s3->tmp.dh); + s->s3->tmp.dh = NULL; + } +#endif +#ifndef OPENSSL_NO_ECDH + if (s->s3->tmp.ecdh != NULL) + { + EC_KEY_free(s->s3->tmp.ecdh); + s->s3->tmp.ecdh = NULL; + } +#endif + s->s3->flags |= SSL3_FLAGS_SGC_RESTART_DONE; + return 2; + } + return 1; +} + +int ssl3_get_client_hello(SSL *s) + { + int i,j,ok,al,ret= -1; + unsigned int cookie_len; + long n; + unsigned long id; + unsigned char *p,*d,*q; + SSL_CIPHER *c; +#ifndef OPENSSL_NO_COMP + SSL_COMP *comp=NULL; +#endif + STACK_OF(SSL_CIPHER) *ciphers=NULL; + + /* We do this so that we will respond with our native type. + * If we are TLSv1 and we get SSLv3, we will respond with TLSv1, + * This down switching should be handled by a different method. + * If we are SSLv3, we will respond with SSLv3, even if prompted with + * TLSv1. + */ + if (s->state == SSL3_ST_SR_CLNT_HELLO_A) + { + s->state=SSL3_ST_SR_CLNT_HELLO_B; + } + s->first_packet=1; + n=s->method->ssl_get_message(s, + SSL3_ST_SR_CLNT_HELLO_B, + SSL3_ST_SR_CLNT_HELLO_C, + SSL3_MT_CLIENT_HELLO, + SSL3_RT_MAX_PLAIN_LENGTH, + &ok); + + if (!ok) return((int)n); + s->first_packet=0; + d=p=(unsigned char *)s->init_msg; + + /* use version from inside client hello, not from record header + * (may differ: see RFC 2246, Appendix E, second paragraph) */ + s->client_version=(((int)p[0])<<8)|(int)p[1]; + p+=2; + + if ((s->version == DTLS1_VERSION && s->client_version > s->version) || + (s->version != DTLS1_VERSION && s->client_version < s->version)) + { + SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_WRONG_VERSION_NUMBER); + if ((s->client_version>>8) == SSL3_VERSION_MAJOR) + { + /* similar to ssl3_get_record, send alert using remote version number */ + s->version = s->client_version; + } + al = SSL_AD_PROTOCOL_VERSION; + goto f_err; + } + + /* If we require cookies and this ClientHello doesn't + * contain one, just return since we do not want to + * allocate any memory yet. So check cookie length... + */ + if (SSL_get_options(s) & SSL_OP_COOKIE_EXCHANGE) + { + unsigned int session_length, cookie_length; + + session_length = *(p + SSL3_RANDOM_SIZE); + cookie_length = *(p + SSL3_RANDOM_SIZE + session_length + 1); + + if (cookie_length == 0) + return 1; + } + + /* load the client random */ + memcpy(s->s3->client_random,p,SSL3_RANDOM_SIZE); + p+=SSL3_RANDOM_SIZE; + + /* get the session-id */ + j= *(p++); + + s->hit=0; + /* Versions before 0.9.7 always allow session reuse during renegotiation + * (i.e. when s->new_session is true), option + * SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION is new with 0.9.7. + * Maybe this optional behaviour should always have been the default, + * but we cannot safely change the default behaviour (or new applications + * might be written that become totally unsecure when compiled with + * an earlier library version) + */ + if ((s->new_session && (s->options & SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION))) + { + if (!s->session_creation_enabled) + { + ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_HANDSHAKE_FAILURE); + SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_SESSION_MAY_NOT_BE_CREATED); + goto err; + } + if (!ssl_get_new_session(s,1)) + goto err; + } + else + { + i=ssl_get_prev_session(s, p, j, d + n); + if (i == 1) + { /* previous session */ + s->hit=1; + } + else if (i == -1) + goto err; + else /* i == 0 */ + { + if (!s->session_creation_enabled) + { + ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_HANDSHAKE_FAILURE); + SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_SESSION_MAY_NOT_BE_CREATED); + goto err; + } + if (!ssl_get_new_session(s,1)) + goto err; + } + } + + p+=j; + + if (s->version == DTLS1_VERSION || s->version == DTLS1_BAD_VER) + { + /* cookie stuff */ + cookie_len = *(p++); + + /* + * The ClientHello may contain a cookie even if the + * HelloVerify message has not been sent--make sure that it + * does not cause an overflow. + */ + if ( cookie_len > sizeof(s->d1->rcvd_cookie)) + { + /* too much data */ + al = SSL_AD_DECODE_ERROR; + SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_COOKIE_MISMATCH); + goto f_err; + } + + /* verify the cookie if appropriate option is set. */ + if ((SSL_get_options(s) & SSL_OP_COOKIE_EXCHANGE) && + cookie_len > 0) + { + memcpy(s->d1->rcvd_cookie, p, cookie_len); + + if ( s->ctx->app_verify_cookie_cb != NULL) + { + if ( s->ctx->app_verify_cookie_cb(s, s->d1->rcvd_cookie, + cookie_len) == 0) + { + al=SSL_AD_HANDSHAKE_FAILURE; + SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, + SSL_R_COOKIE_MISMATCH); + goto f_err; + } + /* else cookie verification succeeded */ + } + else if ( memcmp(s->d1->rcvd_cookie, s->d1->cookie, + s->d1->cookie_len) != 0) /* default verification */ + { + al=SSL_AD_HANDSHAKE_FAILURE; + SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, + SSL_R_COOKIE_MISMATCH); + goto f_err; + } + + ret = 2; + } + + p += cookie_len; + } + + n2s(p,i); + if ((i == 0) && (j != 0)) + { + /* we need a cipher if we are not resuming a session */ + al=SSL_AD_ILLEGAL_PARAMETER; + SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_NO_CIPHERS_SPECIFIED); + goto f_err; + } + if ((p+i) >= (d+n)) + { + /* not enough data */ + al=SSL_AD_DECODE_ERROR; + SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_LENGTH_MISMATCH); + goto f_err; + } + if ((i > 0) && (ssl_bytes_to_cipher_list(s,p,i,&(ciphers)) + == NULL)) + { + goto err; + } + p+=i; + + /* If it is a hit, check that the cipher is in the list */ + if ((s->hit) && (i > 0)) + { + j=0; + id=s->session->cipher->id; + +#ifdef CIPHER_DEBUG + printf("client sent %d ciphers\n",sk_num(ciphers)); +#endif + for (i=0; iid == id) + { + j=1; + break; + } + } +/* Disabled because it can be used in a ciphersuite downgrade + * attack: CVE-2010-4180. + */ +#if 0 + if (j == 0 && (s->options & SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG) && (sk_SSL_CIPHER_num(ciphers) == 1)) + { + /* Special case as client bug workaround: the previously used cipher may + * not be in the current list, the client instead might be trying to + * continue using a cipher that before wasn't chosen due to server + * preferences. We'll have to reject the connection if the cipher is not + * enabled, though. */ + c = sk_SSL_CIPHER_value(ciphers, 0); + if (sk_SSL_CIPHER_find(SSL_get_ciphers(s), c) >= 0) + { + s->session->cipher = c; + j = 1; + } + } +#endif + if (j == 0) + { + /* we need to have the cipher in the cipher + * list if we are asked to reuse it */ + al=SSL_AD_ILLEGAL_PARAMETER; + SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_REQUIRED_CIPHER_MISSING); + goto f_err; + } + } + + /* compression */ + i= *(p++); + if ((p+i) > (d+n)) + { + /* not enough data */ + al=SSL_AD_DECODE_ERROR; + SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_LENGTH_MISMATCH); + goto f_err; + } + q=p; + for (j=0; j= i) + { + /* no compress */ + al=SSL_AD_DECODE_ERROR; + SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_NO_COMPRESSION_SPECIFIED); + goto f_err; + } + +#ifndef OPENSSL_NO_TLSEXT + /* TLS extensions*/ + if (s->version >= SSL3_VERSION) + { + if (!ssl_parse_clienthello_tlsext(s,&p,d,n, &al)) + { + /* 'al' set by ssl_parse_clienthello_tlsext */ + SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_PARSE_TLSEXT); + goto f_err; + } + } + if (ssl_check_clienthello_tlsext(s) <= 0) { + SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_CLIENTHELLO_TLSEXT); + goto err; + } + + /* Check if we want to use external pre-shared secret for this + * handshake for not reused session only. We need to generate + * server_random before calling tls_session_secret_cb in order to allow + * SessionTicket processing to use it in key derivation. */ + { + unsigned long Time; + unsigned char *pos; + Time=(unsigned long)time(NULL); /* Time */ + pos=s->s3->server_random; + l2n(Time,pos); + if (RAND_pseudo_bytes(pos,SSL3_RANDOM_SIZE-4) <= 0) + { + al=SSL_AD_INTERNAL_ERROR; + goto f_err; + } + } + + if (!s->hit && s->version >= TLS1_VERSION && s->tls_session_secret_cb) + { + SSL_CIPHER *pref_cipher=NULL; + + s->session->master_key_length=sizeof(s->session->master_key); + if(s->tls_session_secret_cb(s, s->session->master_key, &s->session->master_key_length, + ciphers, &pref_cipher, s->tls_session_secret_cb_arg)) + { + s->hit=1; + s->session->ciphers=ciphers; + s->session->verify_result=X509_V_OK; + + ciphers=NULL; + + /* check if some cipher was preferred by call back */ + pref_cipher=pref_cipher ? pref_cipher : ssl3_choose_cipher(s, s->session->ciphers, SSL_get_ciphers(s)); + if (pref_cipher == NULL) + { + al=SSL_AD_HANDSHAKE_FAILURE; + SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_NO_SHARED_CIPHER); + goto f_err; + } + + s->session->cipher=pref_cipher; + + if (s->cipher_list) + sk_SSL_CIPHER_free(s->cipher_list); + + if (s->cipher_list_by_id) + sk_SSL_CIPHER_free(s->cipher_list_by_id); + + s->cipher_list = sk_SSL_CIPHER_dup(s->session->ciphers); + s->cipher_list_by_id = sk_SSL_CIPHER_dup(s->session->ciphers); + } + } +#endif + + /* Worst case, we will use the NULL compression, but if we have other + * options, we will now look for them. We have i-1 compression + * algorithms from the client, starting at q. */ + s->s3->tmp.new_compression=NULL; +#ifndef OPENSSL_NO_COMP + /* This only happens if we have a cache hit */ + if (s->session->compress_meth != 0) + { + int m, comp_id = s->session->compress_meth; + /* Perform sanity checks on resumed compression algorithm */ + /* Can't disable compression */ + if (s->options & SSL_OP_NO_COMPRESSION) + { + al=SSL_AD_INTERNAL_ERROR; + SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_INCONSISTENT_COMPRESSION); + goto f_err; + } + /* Look for resumed compression method */ + for (m = 0; m < sk_SSL_COMP_num(s->ctx->comp_methods); m++) + { + comp=sk_SSL_COMP_value(s->ctx->comp_methods,m); + if (comp_id == comp->id) + { + s->s3->tmp.new_compression=comp; + break; + } + } + if (s->s3->tmp.new_compression == NULL) + { + al=SSL_AD_INTERNAL_ERROR; + SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_INVALID_COMPRESSION_ALGORITHM); + goto f_err; + } + /* Look for resumed method in compression list */ + for (m = 0; m < i; m++) + { + if (q[m] == comp_id) + break; + } + if (m >= i) + { + al=SSL_AD_ILLEGAL_PARAMETER; + SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_REQUIRED_COMPRESSSION_ALGORITHM_MISSING); + goto f_err; + } + } + else if (s->hit) + comp = NULL; + else if (!(s->options & SSL_OP_NO_COMPRESSION) && s->ctx->comp_methods) + { /* See if we have a match */ + int m,nn,o,v,done=0; + + nn=sk_SSL_COMP_num(s->ctx->comp_methods); + for (m=0; mctx->comp_methods,m); + v=comp->id; + for (o=0; os3->tmp.new_compression=comp; + else + comp=NULL; + } +#else + /* If compression is disabled we'd better not try to resume a session + * using compression. + */ + if (s->session->compress_meth != 0) + { + al=SSL_AD_INTERNAL_ERROR; + SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_INCONSISTENT_COMPRESSION); + goto f_err; + } +#endif + + /* Given s->session->ciphers and SSL_get_ciphers, we must + * pick a cipher */ + + if (!s->hit) + { +#ifdef OPENSSL_NO_COMP + s->session->compress_meth=0; +#else + s->session->compress_meth=(comp == NULL)?0:comp->id; +#endif + if (s->session->ciphers != NULL) + sk_SSL_CIPHER_free(s->session->ciphers); + s->session->ciphers=ciphers; + if (ciphers == NULL) + { + al=SSL_AD_ILLEGAL_PARAMETER; + SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_NO_CIPHERS_PASSED); + goto f_err; + } + ciphers=NULL; + c=ssl3_choose_cipher(s,s->session->ciphers, + SSL_get_ciphers(s)); + + if (c == NULL) + { + al=SSL_AD_HANDSHAKE_FAILURE; + SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_NO_SHARED_CIPHER); + goto f_err; + } + s->s3->tmp.new_cipher=c; + } + else + { + /* Session-id reuse */ +#ifdef REUSE_CIPHER_BUG + STACK_OF(SSL_CIPHER) *sk; + SSL_CIPHER *nc=NULL; + SSL_CIPHER *ec=NULL; + + if (s->options & SSL_OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG) + { + sk=s->session->ciphers; + for (i=0; ialgorithm_enc & SSL_eNULL) + nc=c; + if (SSL_C_IS_EXPORT(c)) + ec=c; + } + if (nc != NULL) + s->s3->tmp.new_cipher=nc; + else if (ec != NULL) + s->s3->tmp.new_cipher=ec; + else + s->s3->tmp.new_cipher=s->session->cipher; + } + else +#endif + s->s3->tmp.new_cipher=s->session->cipher; + } + + if (!ssl3_digest_cached_records(s)) + goto f_err; + + /* we now have the following setup. + * client_random + * cipher_list - our prefered list of ciphers + * ciphers - the clients prefered list of ciphers + * compression - basically ignored right now + * ssl version is set - sslv3 + * s->session - The ssl session has been setup. + * s->hit - session reuse flag + * s->tmp.new_cipher - the new cipher to use. + */ + + if (ret < 0) ret=1; + if (0) + { +f_err: + ssl3_send_alert(s,SSL3_AL_FATAL,al); + } +err: + if (ciphers != NULL) sk_SSL_CIPHER_free(ciphers); + return(ret); + } + +int ssl3_send_server_hello(SSL *s) + { + unsigned char *buf; + unsigned char *p,*d; + int i,sl; + unsigned long l; +#ifdef OPENSSL_NO_TLSEXT + unsigned long Time; +#endif + + if (s->state == SSL3_ST_SW_SRVR_HELLO_A) + { + buf=(unsigned char *)s->init_buf->data; +#ifdef OPENSSL_NO_TLSEXT + p=s->s3->server_random; + /* Generate server_random if it was not needed previously */ + Time=(unsigned long)time(NULL); /* Time */ + l2n(Time,p); + if (RAND_pseudo_bytes(p,SSL3_RANDOM_SIZE-4) <= 0) + return -1; +#endif + /* Do the message type and length last */ + d=p= &(buf[4]); + + *(p++)=s->version>>8; + *(p++)=s->version&0xff; + + /* Random stuff */ + memcpy(p,s->s3->server_random,SSL3_RANDOM_SIZE); + p+=SSL3_RANDOM_SIZE; + + /* now in theory we have 3 options to sending back the + * session id. If it is a re-use, we send back the + * old session-id, if it is a new session, we send + * back the new session-id or we send back a 0 length + * session-id if we want it to be single use. + * Currently I will not implement the '0' length session-id + * 12-Jan-98 - I'll now support the '0' length stuff. + * + * We also have an additional case where stateless session + * resumption is successful: we always send back the old + * session id. In this case s->hit is non zero: this can + * only happen if stateless session resumption is succesful + * if session caching is disabled so existing functionality + * is unaffected. + */ + if (!(s->ctx->session_cache_mode & SSL_SESS_CACHE_SERVER) + && !s->hit) + s->session->session_id_length=0; + + sl=s->session->session_id_length; + if (sl > (int)sizeof(s->session->session_id)) + { + SSLerr(SSL_F_SSL3_SEND_SERVER_HELLO, ERR_R_INTERNAL_ERROR); + return -1; + } + *(p++)=sl; + memcpy(p,s->session->session_id,sl); + p+=sl; + + /* put the cipher */ + i=ssl3_put_cipher_by_char(s->s3->tmp.new_cipher,p); + p+=i; + + /* put the compression method */ +#ifdef OPENSSL_NO_COMP + *(p++)=0; +#else + if (s->s3->tmp.new_compression == NULL) + *(p++)=0; + else + *(p++)=s->s3->tmp.new_compression->id; +#endif +#ifndef OPENSSL_NO_TLSEXT + if (ssl_prepare_serverhello_tlsext(s) <= 0) + { + SSLerr(SSL_F_SSL3_SEND_SERVER_HELLO,SSL_R_SERVERHELLO_TLSEXT); + return -1; + } + if ((p = ssl_add_serverhello_tlsext(s, p, buf+SSL3_RT_MAX_PLAIN_LENGTH)) == NULL) + { + SSLerr(SSL_F_SSL3_SEND_SERVER_HELLO,ERR_R_INTERNAL_ERROR); + return -1; + } +#endif + /* do the header */ + l=(p-d); + d=buf; + *(d++)=SSL3_MT_SERVER_HELLO; + l2n3(l,d); + + s->state=SSL3_ST_SW_SRVR_HELLO_B; + /* number of bytes to write */ + s->init_num=p-buf; + s->init_off=0; + } + + /* SSL3_ST_SW_SRVR_HELLO_B */ + return(ssl3_do_write(s,SSL3_RT_HANDSHAKE)); + } + +int ssl3_send_server_done(SSL *s) + { + unsigned char *p; + + if (s->state == SSL3_ST_SW_SRVR_DONE_A) + { + p=(unsigned char *)s->init_buf->data; + + /* do the header */ + *(p++)=SSL3_MT_SERVER_DONE; + *(p++)=0; + *(p++)=0; + *(p++)=0; + + s->state=SSL3_ST_SW_SRVR_DONE_B; + /* number of bytes to write */ + s->init_num=4; + s->init_off=0; + } + + /* SSL3_ST_SW_SRVR_DONE_B */ + return(ssl3_do_write(s,SSL3_RT_HANDSHAKE)); + } + +int ssl3_send_server_key_exchange(SSL *s) + { +#ifndef OPENSSL_NO_RSA + unsigned char *q; + int j,num; + RSA *rsa; + unsigned char md_buf[MD5_DIGEST_LENGTH+SHA_DIGEST_LENGTH]; + unsigned int u; +#endif +#ifndef OPENSSL_NO_DH + DH *dh=NULL,*dhp; +#endif +#ifndef OPENSSL_NO_ECDH + EC_KEY *ecdh=NULL, *ecdhp; + unsigned char *encodedPoint = NULL; + int encodedlen = 0; + int curve_id = 0; + BN_CTX *bn_ctx = NULL; +#endif + EVP_PKEY *pkey; + unsigned char *p,*d; + int al,i; + unsigned long type; + int n; + CERT *cert; + BIGNUM *r[4]; + int nr[4],kn; + BUF_MEM *buf; + EVP_MD_CTX md_ctx; + + EVP_MD_CTX_init(&md_ctx); + if (s->state == SSL3_ST_SW_KEY_EXCH_A) + { + type=s->s3->tmp.new_cipher->algorithm_mkey; + cert=s->cert; + + buf=s->init_buf; + + r[0]=r[1]=r[2]=r[3]=NULL; + n=0; +#ifndef OPENSSL_NO_RSA + if (type & SSL_kRSA) + { + rsa=cert->rsa_tmp; + if ((rsa == NULL) && (s->cert->rsa_tmp_cb != NULL)) + { + rsa=s->cert->rsa_tmp_cb(s, + SSL_C_IS_EXPORT(s->s3->tmp.new_cipher), + SSL_C_EXPORT_PKEYLENGTH(s->s3->tmp.new_cipher)); + if(rsa == NULL) + { + al=SSL_AD_HANDSHAKE_FAILURE; + SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,SSL_R_ERROR_GENERATING_TMP_RSA_KEY); + goto f_err; + } + RSA_up_ref(rsa); + cert->rsa_tmp=rsa; + } + if (rsa == NULL) + { + al=SSL_AD_HANDSHAKE_FAILURE; + SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,SSL_R_MISSING_TMP_RSA_KEY); + goto f_err; + } + r[0]=rsa->n; + r[1]=rsa->e; + s->s3->tmp.use_rsa_tmp=1; + } + else +#endif +#ifndef OPENSSL_NO_DH + if (type & SSL_kEDH) + { + dhp=cert->dh_tmp; + if ((dhp == NULL) && (s->cert->dh_tmp_cb != NULL)) + dhp=s->cert->dh_tmp_cb(s, + SSL_C_IS_EXPORT(s->s3->tmp.new_cipher), + SSL_C_EXPORT_PKEYLENGTH(s->s3->tmp.new_cipher)); + if (dhp == NULL) + { + al=SSL_AD_HANDSHAKE_FAILURE; + SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,SSL_R_MISSING_TMP_DH_KEY); + goto f_err; + } + + if (s->s3->tmp.dh != NULL) + { + SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR); + goto err; + } + + if ((dh=DHparams_dup(dhp)) == NULL) + { + SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,ERR_R_DH_LIB); + goto err; + } + + s->s3->tmp.dh=dh; + if ((dhp->pub_key == NULL || + dhp->priv_key == NULL || + (s->options & SSL_OP_SINGLE_DH_USE))) + { + if(!DH_generate_key(dh)) + { + SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, + ERR_R_DH_LIB); + goto err; + } + } + else + { + dh->pub_key=BN_dup(dhp->pub_key); + dh->priv_key=BN_dup(dhp->priv_key); + if ((dh->pub_key == NULL) || + (dh->priv_key == NULL)) + { + SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,ERR_R_DH_LIB); + goto err; + } + } + r[0]=dh->p; + r[1]=dh->g; + r[2]=dh->pub_key; + } + else +#endif +#ifndef OPENSSL_NO_ECDH + if (type & SSL_kEECDH) + { + const EC_GROUP *group; + + ecdhp=cert->ecdh_tmp; + if ((ecdhp == NULL) && (s->cert->ecdh_tmp_cb != NULL)) + { + ecdhp=s->cert->ecdh_tmp_cb(s, + SSL_C_IS_EXPORT(s->s3->tmp.new_cipher), + SSL_C_EXPORT_PKEYLENGTH(s->s3->tmp.new_cipher)); + } + if (ecdhp == NULL) + { + al=SSL_AD_HANDSHAKE_FAILURE; + SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,SSL_R_MISSING_TMP_ECDH_KEY); + goto f_err; + } + + if (s->s3->tmp.ecdh != NULL) + { + SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR); + goto err; + } + + /* Duplicate the ECDH structure. */ + if (ecdhp == NULL) + { + SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,ERR_R_ECDH_LIB); + goto err; + } + if ((ecdh = EC_KEY_dup(ecdhp)) == NULL) + { + SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,ERR_R_ECDH_LIB); + goto err; + } + + s->s3->tmp.ecdh=ecdh; + if ((EC_KEY_get0_public_key(ecdh) == NULL) || + (EC_KEY_get0_private_key(ecdh) == NULL) || + (s->options & SSL_OP_SINGLE_ECDH_USE)) + { + if(!EC_KEY_generate_key(ecdh)) + { + SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,ERR_R_ECDH_LIB); + goto err; + } + } + + if (((group = EC_KEY_get0_group(ecdh)) == NULL) || + (EC_KEY_get0_public_key(ecdh) == NULL) || + (EC_KEY_get0_private_key(ecdh) == NULL)) + { + SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,ERR_R_ECDH_LIB); + goto err; + } + + if (SSL_C_IS_EXPORT(s->s3->tmp.new_cipher) && + (EC_GROUP_get_degree(group) > 163)) + { + SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,SSL_R_ECGROUP_TOO_LARGE_FOR_CIPHER); + goto err; + } + + /* XXX: For now, we only support ephemeral ECDH + * keys over named (not generic) curves. For + * supported named curves, curve_id is non-zero. + */ + if ((curve_id = + tls1_ec_nid2curve_id(EC_GROUP_get_curve_name(group))) + == 0) + { + SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,SSL_R_UNSUPPORTED_ELLIPTIC_CURVE); + goto err; + } + + /* Encode the public key. + * First check the size of encoding and + * allocate memory accordingly. + */ + encodedlen = EC_POINT_point2oct(group, + EC_KEY_get0_public_key(ecdh), + POINT_CONVERSION_UNCOMPRESSED, + NULL, 0, NULL); + + encodedPoint = (unsigned char *) + OPENSSL_malloc(encodedlen*sizeof(unsigned char)); + bn_ctx = BN_CTX_new(); + if ((encodedPoint == NULL) || (bn_ctx == NULL)) + { + SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,ERR_R_MALLOC_FAILURE); + goto err; + } + + + encodedlen = EC_POINT_point2oct(group, + EC_KEY_get0_public_key(ecdh), + POINT_CONVERSION_UNCOMPRESSED, + encodedPoint, encodedlen, bn_ctx); + + if (encodedlen == 0) + { + SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,ERR_R_ECDH_LIB); + goto err; + } + + BN_CTX_free(bn_ctx); bn_ctx=NULL; + + /* XXX: For now, we only support named (not + * generic) curves in ECDH ephemeral key exchanges. + * In this situation, we need four additional bytes + * to encode the entire ServerECDHParams + * structure. + */ + n = 4 + encodedlen; + + /* We'll generate the serverKeyExchange message + * explicitly so we can set these to NULLs + */ + r[0]=NULL; + r[1]=NULL; + r[2]=NULL; + r[3]=NULL; + } + else +#endif /* !OPENSSL_NO_ECDH */ +#ifndef OPENSSL_NO_PSK + if (type & SSL_kPSK) + { + /* reserve size for record length and PSK identity hint*/ + n+=2+strlen(s->ctx->psk_identity_hint); + } + else +#endif /* !OPENSSL_NO_PSK */ + { + al=SSL_AD_HANDSHAKE_FAILURE; + SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,SSL_R_UNKNOWN_KEY_EXCHANGE_TYPE); + goto f_err; + } + for (i=0; r[i] != NULL; i++) + { + nr[i]=BN_num_bytes(r[i]); + n+=2+nr[i]; + } + + if (!(s->s3->tmp.new_cipher->algorithm_auth & SSL_aNULL) + && !(s->s3->tmp.new_cipher->algorithm_mkey & SSL_kPSK)) + { + if ((pkey=ssl_get_sign_pkey(s,s->s3->tmp.new_cipher)) + == NULL) + { + al=SSL_AD_DECODE_ERROR; + goto f_err; + } + kn=EVP_PKEY_size(pkey); + } + else + { + pkey=NULL; + kn=0; + } + + if (!BUF_MEM_grow_clean(buf,n+4+kn)) + { + SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,ERR_LIB_BUF); + goto err; + } + d=(unsigned char *)s->init_buf->data; + p= &(d[4]); + + for (i=0; r[i] != NULL; i++) + { + s2n(nr[i],p); + BN_bn2bin(r[i],p); + p+=nr[i]; + } + +#ifndef OPENSSL_NO_ECDH + if (type & SSL_kEECDH) + { + /* XXX: For now, we only support named (not generic) curves. + * In this situation, the serverKeyExchange message has: + * [1 byte CurveType], [2 byte CurveName] + * [1 byte length of encoded point], followed by + * the actual encoded point itself + */ + *p = NAMED_CURVE_TYPE; + p += 1; + *p = 0; + p += 1; + *p = curve_id; + p += 1; + *p = encodedlen; + p += 1; + memcpy((unsigned char*)p, + (unsigned char *)encodedPoint, + encodedlen); + OPENSSL_free(encodedPoint); + encodedPoint = NULL; + p += encodedlen; + } +#endif + +#ifndef OPENSSL_NO_PSK + if (type & SSL_kPSK) + { + /* copy PSK identity hint */ + s2n(strlen(s->ctx->psk_identity_hint), p); + strncpy((char *)p, s->ctx->psk_identity_hint, strlen(s->ctx->psk_identity_hint)); + p+=strlen(s->ctx->psk_identity_hint); + } +#endif + + /* not anonymous */ + if (pkey != NULL) + { + /* n is the length of the params, they start at &(d[4]) + * and p points to the space at the end. */ +#ifndef OPENSSL_NO_RSA + if (pkey->type == EVP_PKEY_RSA) + { + q=md_buf; + j=0; + for (num=2; num > 0; num--) + { + EVP_DigestInit_ex(&md_ctx,(num == 2) + ?s->ctx->md5:s->ctx->sha1, NULL); + EVP_DigestUpdate(&md_ctx,&(s->s3->client_random[0]),SSL3_RANDOM_SIZE); + EVP_DigestUpdate(&md_ctx,&(s->s3->server_random[0]),SSL3_RANDOM_SIZE); + EVP_DigestUpdate(&md_ctx,&(d[4]),n); + EVP_DigestFinal_ex(&md_ctx,q, + (unsigned int *)&i); + q+=i; + j+=i; + } + if (RSA_sign(NID_md5_sha1, md_buf, j, + &(p[2]), &u, pkey->pkey.rsa) <= 0) + { + SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,ERR_LIB_RSA); + goto err; + } + s2n(u,p); + n+=u+2; + } + else +#endif +#if !defined(OPENSSL_NO_DSA) + if (pkey->type == EVP_PKEY_DSA) + { + /* lets do DSS */ + EVP_SignInit_ex(&md_ctx,EVP_dss1(), NULL); + EVP_SignUpdate(&md_ctx,&(s->s3->client_random[0]),SSL3_RANDOM_SIZE); + EVP_SignUpdate(&md_ctx,&(s->s3->server_random[0]),SSL3_RANDOM_SIZE); + EVP_SignUpdate(&md_ctx,&(d[4]),n); + if (!EVP_SignFinal(&md_ctx,&(p[2]), + (unsigned int *)&i,pkey)) + { + SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,ERR_LIB_DSA); + goto err; + } + s2n(i,p); + n+=i+2; + } + else +#endif +#if !defined(OPENSSL_NO_ECDSA) + if (pkey->type == EVP_PKEY_EC) + { + /* let's do ECDSA */ + EVP_SignInit_ex(&md_ctx,EVP_ecdsa(), NULL); + EVP_SignUpdate(&md_ctx,&(s->s3->client_random[0]),SSL3_RANDOM_SIZE); + EVP_SignUpdate(&md_ctx,&(s->s3->server_random[0]),SSL3_RANDOM_SIZE); + EVP_SignUpdate(&md_ctx,&(d[4]),n); + if (!EVP_SignFinal(&md_ctx,&(p[2]), + (unsigned int *)&i,pkey)) + { + SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,ERR_LIB_ECDSA); + goto err; + } + s2n(i,p); + n+=i+2; + } + else +#endif + { + /* Is this error check actually needed? */ + al=SSL_AD_HANDSHAKE_FAILURE; + SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,SSL_R_UNKNOWN_PKEY_TYPE); + goto f_err; + } + } + + *(d++)=SSL3_MT_SERVER_KEY_EXCHANGE; + l2n3(n,d); + + /* we should now have things packed up, so lets send + * it off */ + s->init_num=n+4; + s->init_off=0; + } + + s->state = SSL3_ST_SW_KEY_EXCH_B; + EVP_MD_CTX_cleanup(&md_ctx); + return(ssl3_do_write(s,SSL3_RT_HANDSHAKE)); +f_err: + ssl3_send_alert(s,SSL3_AL_FATAL,al); +err: +#ifndef OPENSSL_NO_ECDH + if (encodedPoint != NULL) OPENSSL_free(encodedPoint); + BN_CTX_free(bn_ctx); +#endif + EVP_MD_CTX_cleanup(&md_ctx); + return(-1); + } + +int ssl3_send_certificate_request(SSL *s) + { + unsigned char *p,*d; + int i,j,nl,off,n; + STACK_OF(X509_NAME) *sk=NULL; + X509_NAME *name; + BUF_MEM *buf; + + if (s->state == SSL3_ST_SW_CERT_REQ_A) + { + buf=s->init_buf; + + d=p=(unsigned char *)&(buf->data[4]); + + /* get the list of acceptable cert types */ + p++; + n=ssl3_get_req_cert_type(s,p); + d[0]=n; + p+=n; + n++; + + off=n; + p+=2; + n+=2; + + sk=SSL_get_client_CA_list(s); + nl=0; + if (sk != NULL) + { + for (i=0; idata[4+n]); + if (!(s->options & SSL_OP_NETSCAPE_CA_DN_BUG)) + { + s2n(j,p); + i2d_X509_NAME(name,&p); + n+=2+j; + nl+=2+j; + } + else + { + d=p; + i2d_X509_NAME(name,&p); + j-=2; s2n(j,d); j+=2; + n+=j; + nl+=j; + } + } + } + /* else no CA names */ + p=(unsigned char *)&(buf->data[4+off]); + s2n(nl,p); + + d=(unsigned char *)buf->data; + *(d++)=SSL3_MT_CERTIFICATE_REQUEST; + l2n3(n,d); + + /* we should now have things packed up, so lets send + * it off */ + + s->init_num=n+4; + s->init_off=0; +#ifdef NETSCAPE_HANG_BUG + p=(unsigned char *)s->init_buf->data + s->init_num; + + /* do the header */ + *(p++)=SSL3_MT_SERVER_DONE; + *(p++)=0; + *(p++)=0; + *(p++)=0; + s->init_num += 4; +#endif + + s->state = SSL3_ST_SW_CERT_REQ_B; + } + + /* SSL3_ST_SW_CERT_REQ_B */ + return(ssl3_do_write(s,SSL3_RT_HANDSHAKE)); +err: + return(-1); + } + +int ssl3_get_client_key_exchange(SSL *s) + { + int i,al,ok; + long n; + unsigned long alg_k; + unsigned char *p; +#ifndef OPENSSL_NO_RSA + RSA *rsa=NULL; + EVP_PKEY *pkey=NULL; +#endif +#ifndef OPENSSL_NO_DH + BIGNUM *pub=NULL; + DH *dh_srvr; +#endif +#ifndef OPENSSL_NO_KRB5 + KSSL_ERR kssl_err; +#endif /* OPENSSL_NO_KRB5 */ + +#ifndef OPENSSL_NO_ECDH + EC_KEY *srvr_ecdh = NULL; + EVP_PKEY *clnt_pub_pkey = NULL; + EC_POINT *clnt_ecpoint = NULL; + BN_CTX *bn_ctx = NULL; +#endif + + n=s->method->ssl_get_message(s, + SSL3_ST_SR_KEY_EXCH_A, + SSL3_ST_SR_KEY_EXCH_B, + SSL3_MT_CLIENT_KEY_EXCHANGE, + 2048, /* ??? */ + &ok); + + if (!ok) return((int)n); + p=(unsigned char *)s->init_msg; + + alg_k=s->s3->tmp.new_cipher->algorithm_mkey; + +#ifndef OPENSSL_NO_RSA + if (alg_k & SSL_kRSA) + { + /* FIX THIS UP EAY EAY EAY EAY */ + if (s->s3->tmp.use_rsa_tmp) + { + if ((s->cert != NULL) && (s->cert->rsa_tmp != NULL)) + rsa=s->cert->rsa_tmp; + /* Don't do a callback because rsa_tmp should + * be sent already */ + if (rsa == NULL) + { + al=SSL_AD_HANDSHAKE_FAILURE; + SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_MISSING_TMP_RSA_PKEY); + goto f_err; + + } + } + else + { + pkey=s->cert->pkeys[SSL_PKEY_RSA_ENC].privatekey; + if ( (pkey == NULL) || + (pkey->type != EVP_PKEY_RSA) || + (pkey->pkey.rsa == NULL)) + { + al=SSL_AD_HANDSHAKE_FAILURE; + SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_MISSING_RSA_CERTIFICATE); + goto f_err; + } + rsa=pkey->pkey.rsa; + } + + /* TLS and [incidentally] DTLS{0xFEFF} */ + if (s->version > SSL3_VERSION && s->version != DTLS1_BAD_VER) + { + n2s(p,i); + if (n != i+2) + { + if (!(s->options & SSL_OP_TLS_D5_BUG)) + { + SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_TLS_RSA_ENCRYPTED_VALUE_LENGTH_IS_WRONG); + goto err; + } + else + p-=2; + } + else + n=i; + } + + i=RSA_private_decrypt((int)n,p,p,rsa,RSA_PKCS1_PADDING); + + al = -1; + + if (i != SSL_MAX_MASTER_KEY_LENGTH) + { + al=SSL_AD_DECODE_ERROR; + /* SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_BAD_RSA_DECRYPT); */ + } + + if ((al == -1) && !((p[0] == (s->client_version>>8)) && (p[1] == (s->client_version & 0xff)))) + { + /* The premaster secret must contain the same version number as the + * ClientHello to detect version rollback attacks (strangely, the + * protocol does not offer such protection for DH ciphersuites). + * However, buggy clients exist that send the negotiated protocol + * version instead if the server does not support the requested + * protocol version. + * If SSL_OP_TLS_ROLLBACK_BUG is set, tolerate such clients. */ + if (!((s->options & SSL_OP_TLS_ROLLBACK_BUG) && + (p[0] == (s->version>>8)) && (p[1] == (s->version & 0xff)))) + { + al=SSL_AD_DECODE_ERROR; + /* SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_BAD_PROTOCOL_VERSION_NUMBER); */ + + /* The Klima-Pokorny-Rosa extension of Bleichenbacher's attack + * (http://eprint.iacr.org/2003/052/) exploits the version + * number check as a "bad version oracle" -- an alert would + * reveal that the plaintext corresponding to some ciphertext + * made up by the adversary is properly formatted except + * that the version number is wrong. To avoid such attacks, + * we should treat this just like any other decryption error. */ + } + } + + if (al != -1) + { + /* Some decryption failure -- use random value instead as countermeasure + * against Bleichenbacher's attack on PKCS #1 v1.5 RSA padding + * (see RFC 2246, section 7.4.7.1). */ + ERR_clear_error(); + i = SSL_MAX_MASTER_KEY_LENGTH; + p[0] = s->client_version >> 8; + p[1] = s->client_version & 0xff; + if (RAND_pseudo_bytes(p+2, i-2) <= 0) /* should be RAND_bytes, but we cannot work around a failure */ + goto err; + } + + s->session->master_key_length= + s->method->ssl3_enc->generate_master_secret(s, + s->session->master_key, + p,i); + OPENSSL_cleanse(p,i); + } + else +#endif +#ifndef OPENSSL_NO_DH + if (alg_k & (SSL_kEDH|SSL_kDHr|SSL_kDHd)) + { + n2s(p,i); + if (n != i+2) + { + if (!(s->options & SSL_OP_SSLEAY_080_CLIENT_DH_BUG)) + { + SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_DH_PUBLIC_VALUE_LENGTH_IS_WRONG); + goto err; + } + else + { + p-=2; + i=(int)n; + } + } + + if (n == 0L) /* the parameters are in the cert */ + { + al=SSL_AD_HANDSHAKE_FAILURE; + SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_UNABLE_TO_DECODE_DH_CERTS); + goto f_err; + } + else + { + if (s->s3->tmp.dh == NULL) + { + al=SSL_AD_HANDSHAKE_FAILURE; + SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_MISSING_TMP_DH_KEY); + goto f_err; + } + else + dh_srvr=s->s3->tmp.dh; + } + + pub=BN_bin2bn(p,i,NULL); + if (pub == NULL) + { + SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_BN_LIB); + goto err; + } + + i=DH_compute_key(p,pub,dh_srvr); + + if (i <= 0) + { + SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,ERR_R_DH_LIB); + BN_clear_free(pub); + goto err; + } + + DH_free(s->s3->tmp.dh); + s->s3->tmp.dh=NULL; + + BN_clear_free(pub); + pub=NULL; + s->session->master_key_length= + s->method->ssl3_enc->generate_master_secret(s, + s->session->master_key,p,i); + OPENSSL_cleanse(p,i); + } + else +#endif +#ifndef OPENSSL_NO_KRB5 + if (alg_k & SSL_kKRB5) + { + krb5_error_code krb5rc; + krb5_data enc_ticket; + krb5_data authenticator; + krb5_data enc_pms; + KSSL_CTX *kssl_ctx = s->kssl_ctx; + EVP_CIPHER_CTX ciph_ctx; + const EVP_CIPHER *enc = NULL; + unsigned char iv[EVP_MAX_IV_LENGTH]; + unsigned char pms[SSL_MAX_MASTER_KEY_LENGTH + + EVP_MAX_BLOCK_LENGTH]; + int padl, outl; + krb5_timestamp authtime = 0; + krb5_ticket_times ttimes; + + EVP_CIPHER_CTX_init(&ciph_ctx); + + if (!kssl_ctx) kssl_ctx = kssl_ctx_new(); + + n2s(p,i); + enc_ticket.length = i; + + if (n < (long)(enc_ticket.length + 6)) + { + SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, + SSL_R_DATA_LENGTH_TOO_LONG); + goto err; + } + + enc_ticket.data = (char *)p; + p+=enc_ticket.length; + + n2s(p,i); + authenticator.length = i; + + if (n < (long)(enc_ticket.length + authenticator.length + 6)) + { + SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, + SSL_R_DATA_LENGTH_TOO_LONG); + goto err; + } + + authenticator.data = (char *)p; + p+=authenticator.length; + + n2s(p,i); + enc_pms.length = i; + enc_pms.data = (char *)p; + p+=enc_pms.length; + + /* Note that the length is checked again below, + ** after decryption + */ + if(enc_pms.length > sizeof pms) + { + SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, + SSL_R_DATA_LENGTH_TOO_LONG); + goto err; + } + + if (n != (long)(enc_ticket.length + authenticator.length + + enc_pms.length + 6)) + { + SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, + SSL_R_DATA_LENGTH_TOO_LONG); + goto err; + } + + if ((krb5rc = kssl_sget_tkt(kssl_ctx, &enc_ticket, &ttimes, + &kssl_err)) != 0) + { +#ifdef KSSL_DEBUG + printf("kssl_sget_tkt rtn %d [%d]\n", + krb5rc, kssl_err.reason); + if (kssl_err.text) + printf("kssl_err text= %s\n", kssl_err.text); +#endif /* KSSL_DEBUG */ + SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, + kssl_err.reason); + goto err; + } + + /* Note: no authenticator is not considered an error, + ** but will return authtime == 0. + */ + if ((krb5rc = kssl_check_authent(kssl_ctx, &authenticator, + &authtime, &kssl_err)) != 0) + { +#ifdef KSSL_DEBUG + printf("kssl_check_authent rtn %d [%d]\n", + krb5rc, kssl_err.reason); + if (kssl_err.text) + printf("kssl_err text= %s\n", kssl_err.text); +#endif /* KSSL_DEBUG */ + SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, + kssl_err.reason); + goto err; + } + + if ((krb5rc = kssl_validate_times(authtime, &ttimes)) != 0) + { + SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, krb5rc); + goto err; + } + +#ifdef KSSL_DEBUG + kssl_ctx_show(kssl_ctx); +#endif /* KSSL_DEBUG */ + + enc = kssl_map_enc(kssl_ctx->enctype); + if (enc == NULL) + goto err; + + memset(iv, 0, sizeof iv); /* per RFC 1510 */ + + if (!EVP_DecryptInit_ex(&ciph_ctx,enc,NULL,kssl_ctx->key,iv)) + { + SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, + SSL_R_DECRYPTION_FAILED); + goto err; + } + if (!EVP_DecryptUpdate(&ciph_ctx, pms,&outl, + (unsigned char *)enc_pms.data, enc_pms.length)) + { + SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, + SSL_R_DECRYPTION_FAILED); + goto err; + } + if (outl > SSL_MAX_MASTER_KEY_LENGTH) + { + SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, + SSL_R_DATA_LENGTH_TOO_LONG); + goto err; + } + if (!EVP_DecryptFinal_ex(&ciph_ctx,&(pms[outl]),&padl)) + { + SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, + SSL_R_DECRYPTION_FAILED); + goto err; + } + outl += padl; + if (outl > SSL_MAX_MASTER_KEY_LENGTH) + { + SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, + SSL_R_DATA_LENGTH_TOO_LONG); + goto err; + } + if (!((pms[0] == (s->client_version>>8)) && (pms[1] == (s->client_version & 0xff)))) + { + /* The premaster secret must contain the same version number as the + * ClientHello to detect version rollback attacks (strangely, the + * protocol does not offer such protection for DH ciphersuites). + * However, buggy clients exist that send random bytes instead of + * the protocol version. + * If SSL_OP_TLS_ROLLBACK_BUG is set, tolerate such clients. + * (Perhaps we should have a separate BUG value for the Kerberos cipher) + */ + if (!(s->options & SSL_OP_TLS_ROLLBACK_BUG)) + { + SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, + SSL_AD_DECODE_ERROR); + goto err; + } + } + + EVP_CIPHER_CTX_cleanup(&ciph_ctx); + + s->session->master_key_length= + s->method->ssl3_enc->generate_master_secret(s, + s->session->master_key, pms, outl); + + if (kssl_ctx->client_princ) + { + size_t len = strlen(kssl_ctx->client_princ); + if ( len < SSL_MAX_KRB5_PRINCIPAL_LENGTH ) + { + s->session->krb5_client_princ_len = len; + memcpy(s->session->krb5_client_princ,kssl_ctx->client_princ,len); + } + } + + + /* Was doing kssl_ctx_free() here, + ** but it caused problems for apache. + ** kssl_ctx = kssl_ctx_free(kssl_ctx); + ** if (s->kssl_ctx) s->kssl_ctx = NULL; + */ + } + else +#endif /* OPENSSL_NO_KRB5 */ + +#ifndef OPENSSL_NO_ECDH + if (alg_k & (SSL_kEECDH|SSL_kECDHr|SSL_kECDHe)) + { + int ret = 1; + int field_size = 0; + const EC_KEY *tkey; + const EC_GROUP *group; + const BIGNUM *priv_key; + + /* initialize structures for server's ECDH key pair */ + if ((srvr_ecdh = EC_KEY_new()) == NULL) + { + SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, + ERR_R_MALLOC_FAILURE); + goto err; + } + + /* Let's get server private key and group information */ + if (alg_k & (SSL_kECDHr|SSL_kECDHe)) + { + /* use the certificate */ + tkey = s->cert->pkeys[SSL_PKEY_ECC].privatekey->pkey.ec; + } + else + { + /* use the ephermeral values we saved when + * generating the ServerKeyExchange msg. + */ + tkey = s->s3->tmp.ecdh; + } + + group = EC_KEY_get0_group(tkey); + priv_key = EC_KEY_get0_private_key(tkey); + + if (!EC_KEY_set_group(srvr_ecdh, group) || + !EC_KEY_set_private_key(srvr_ecdh, priv_key)) + { + SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, + ERR_R_EC_LIB); + goto err; + } + + /* Let's get client's public key */ + if ((clnt_ecpoint = EC_POINT_new(group)) == NULL) + { + SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, + ERR_R_MALLOC_FAILURE); + goto err; + } + + if (n == 0L) + { + /* Client Publickey was in Client Certificate */ + + if (alg_k & SSL_kEECDH) + { + al=SSL_AD_HANDSHAKE_FAILURE; + SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_MISSING_TMP_ECDH_KEY); + goto f_err; + } + if (((clnt_pub_pkey=X509_get_pubkey(s->session->peer)) + == NULL) || + (clnt_pub_pkey->type != EVP_PKEY_EC)) + { + /* XXX: For now, we do not support client + * authentication using ECDH certificates + * so this branch (n == 0L) of the code is + * never executed. When that support is + * added, we ought to ensure the key + * received in the certificate is + * authorized for key agreement. + * ECDH_compute_key implicitly checks that + * the two ECDH shares are for the same + * group. + */ + al=SSL_AD_HANDSHAKE_FAILURE; + SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, + SSL_R_UNABLE_TO_DECODE_ECDH_CERTS); + goto f_err; + } + + if (EC_POINT_copy(clnt_ecpoint, + EC_KEY_get0_public_key(clnt_pub_pkey->pkey.ec)) == 0) + { + SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, + ERR_R_EC_LIB); + goto err; + } + ret = 2; /* Skip certificate verify processing */ + } + else + { + /* Get client's public key from encoded point + * in the ClientKeyExchange message. + */ + if ((bn_ctx = BN_CTX_new()) == NULL) + { + SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, + ERR_R_MALLOC_FAILURE); + goto err; + } + + /* Get encoded point length */ + i = *p; + p += 1; + if (n != 1 + i) + { + SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, + ERR_R_EC_LIB); + goto err; + } + if (EC_POINT_oct2point(group, + clnt_ecpoint, p, i, bn_ctx) == 0) + { + SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, + ERR_R_EC_LIB); + goto err; + } + /* p is pointing to somewhere in the buffer + * currently, so set it to the start + */ + p=(unsigned char *)s->init_buf->data; + } + + /* Compute the shared pre-master secret */ + field_size = EC_GROUP_get_degree(group); + if (field_size <= 0) + { + SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, + ERR_R_ECDH_LIB); + goto err; + } + i = ECDH_compute_key(p, (field_size+7)/8, clnt_ecpoint, srvr_ecdh, NULL); + if (i <= 0) + { + SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, + ERR_R_ECDH_LIB); + goto err; + } + + EVP_PKEY_free(clnt_pub_pkey); + EC_POINT_free(clnt_ecpoint); + EC_KEY_free(srvr_ecdh); + BN_CTX_free(bn_ctx); + EC_KEY_free(s->s3->tmp.ecdh); + s->s3->tmp.ecdh = NULL; + + /* Compute the master secret */ + s->session->master_key_length = s->method->ssl3_enc-> \ + generate_master_secret(s, s->session->master_key, p, i); + + OPENSSL_cleanse(p, i); + return (ret); + } + else +#endif +#ifndef OPENSSL_NO_PSK + if (alg_k & SSL_kPSK) + { + unsigned char *t = NULL; + unsigned char psk_or_pre_ms[PSK_MAX_PSK_LEN*2+4]; + unsigned int pre_ms_len = 0, psk_len = 0; + int psk_err = 1; + char tmp_id[PSK_MAX_IDENTITY_LEN+1]; + + al=SSL_AD_HANDSHAKE_FAILURE; + + n2s(p,i); + if (n != i+2) + { + SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, + SSL_R_LENGTH_MISMATCH); + goto psk_err; + } + if (i > PSK_MAX_IDENTITY_LEN) + { + SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, + SSL_R_DATA_LENGTH_TOO_LONG); + goto psk_err; + } + if (s->psk_server_callback == NULL) + { + SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, + SSL_R_PSK_NO_SERVER_CB); + goto psk_err; + } + + /* Create guaranteed NULL-terminated identity + * string for the callback */ + memcpy(tmp_id, p, i); + memset(tmp_id+i, 0, PSK_MAX_IDENTITY_LEN+1-i); + psk_len = s->psk_server_callback(s, tmp_id, + psk_or_pre_ms, sizeof(psk_or_pre_ms)); + OPENSSL_cleanse(tmp_id, PSK_MAX_IDENTITY_LEN+1); + + if (psk_len > PSK_MAX_PSK_LEN) + { + SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, + ERR_R_INTERNAL_ERROR); + goto psk_err; + } + else if (psk_len == 0) + { + /* PSK related to the given identity not found */ + SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, + SSL_R_PSK_IDENTITY_NOT_FOUND); + al=SSL_AD_UNKNOWN_PSK_IDENTITY; + goto psk_err; + } + + /* create PSK pre_master_secret */ + pre_ms_len=2+psk_len+2+psk_len; + t = psk_or_pre_ms; + memmove(psk_or_pre_ms+psk_len+4, psk_or_pre_ms, psk_len); + s2n(psk_len, t); + memset(t, 0, psk_len); + t+=psk_len; + s2n(psk_len, t); + + if (s->session->psk_identity != NULL) + OPENSSL_free(s->session->psk_identity); + s->session->psk_identity = BUF_strdup((char *)p); + if (s->session->psk_identity == NULL) + { + SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, + ERR_R_MALLOC_FAILURE); + goto psk_err; + } + + if (s->session->psk_identity_hint != NULL) + OPENSSL_free(s->session->psk_identity_hint); + s->session->psk_identity_hint = BUF_strdup(s->ctx->psk_identity_hint); + if (s->ctx->psk_identity_hint != NULL && + s->session->psk_identity_hint == NULL) + { + SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, + ERR_R_MALLOC_FAILURE); + goto psk_err; + } + + s->session->master_key_length= + s->method->ssl3_enc->generate_master_secret(s, + s->session->master_key, psk_or_pre_ms, pre_ms_len); + psk_err = 0; + psk_err: + OPENSSL_cleanse(psk_or_pre_ms, sizeof(psk_or_pre_ms)); + if (psk_err != 0) + goto f_err; + } + else +#endif + if (alg_k & SSL_kGOST) + { + int ret = 0; + EVP_PKEY_CTX *pkey_ctx; + EVP_PKEY *client_pub_pkey = NULL, *pk = NULL; + unsigned char premaster_secret[32], *start; + size_t outlen=32, inlen; + unsigned long alg_a; + + /* Get our certificate private key*/ + alg_a = s->s3->tmp.new_cipher->algorithm_auth; + if (alg_a & SSL_aGOST94) + pk = s->cert->pkeys[SSL_PKEY_GOST94].privatekey; + else if (alg_a & SSL_aGOST01) + pk = s->cert->pkeys[SSL_PKEY_GOST01].privatekey; + + pkey_ctx = EVP_PKEY_CTX_new(pk,NULL); + EVP_PKEY_decrypt_init(pkey_ctx); + /* If client certificate is present and is of the same type, maybe + * use it for key exchange. Don't mind errors from + * EVP_PKEY_derive_set_peer, because it is completely valid to use + * a client certificate for authorization only. */ + client_pub_pkey = X509_get_pubkey(s->session->peer); + if (client_pub_pkey) + { + if (EVP_PKEY_derive_set_peer(pkey_ctx, client_pub_pkey) <= 0) + ERR_clear_error(); + } + /* Decrypt session key */ + if ((*p!=( V_ASN1_SEQUENCE| V_ASN1_CONSTRUCTED))) + { + SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_DECRYPTION_FAILED); + goto gerr; + } + if (p[1] == 0x81) + { + start = p+3; + inlen = p[2]; + } + else if (p[1] < 0x80) + { + start = p+2; + inlen = p[1]; + } + else + { + SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_DECRYPTION_FAILED); + goto gerr; + } + if (EVP_PKEY_decrypt(pkey_ctx,premaster_secret,&outlen,start,inlen) <=0) + + { + SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_DECRYPTION_FAILED); + goto gerr; + } + /* Generate master secret */ + s->session->master_key_length= + s->method->ssl3_enc->generate_master_secret(s, + s->session->master_key,premaster_secret,32); + /* Check if pubkey from client certificate was used */ + if (EVP_PKEY_CTX_ctrl(pkey_ctx, -1, -1, EVP_PKEY_CTRL_PEER_KEY, 2, NULL) > 0) + ret = 2; + else + ret = 1; + gerr: + EVP_PKEY_free(client_pub_pkey); + EVP_PKEY_CTX_free(pkey_ctx); + if (ret) + return ret; + else + goto err; + } + else + { + al=SSL_AD_HANDSHAKE_FAILURE; + SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, + SSL_R_UNKNOWN_CIPHER_TYPE); + goto f_err; + } + + return(1); +f_err: + ssl3_send_alert(s,SSL3_AL_FATAL,al); +#if !defined(OPENSSL_NO_DH) || !defined(OPENSSL_NO_RSA) || !defined(OPENSSL_NO_ECDH) +err: +#endif +#ifndef OPENSSL_NO_ECDH + EVP_PKEY_free(clnt_pub_pkey); + EC_POINT_free(clnt_ecpoint); + if (srvr_ecdh != NULL) + EC_KEY_free(srvr_ecdh); + BN_CTX_free(bn_ctx); +#endif + return(-1); + } + +int ssl3_get_cert_verify(SSL *s) + { + EVP_PKEY *pkey=NULL; + unsigned char *p; + int al,ok,ret=0; + long n; + int type=0,i,j; + X509 *peer; + + n=s->method->ssl_get_message(s, + SSL3_ST_SR_CERT_VRFY_A, + SSL3_ST_SR_CERT_VRFY_B, + -1, + 514, /* 514? */ + &ok); + + if (!ok) return((int)n); + + if (s->session->peer != NULL) + { + peer=s->session->peer; + pkey=X509_get_pubkey(peer); + type=X509_certificate_type(peer,pkey); + } + else + { + peer=NULL; + pkey=NULL; + } + + if (s->s3->tmp.message_type != SSL3_MT_CERTIFICATE_VERIFY) + { + s->s3->tmp.reuse_message=1; + if ((peer != NULL) && (type | EVP_PKT_SIGN)) + { + al=SSL_AD_UNEXPECTED_MESSAGE; + SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_MISSING_VERIFY_MESSAGE); + goto f_err; + } + ret=1; + goto end; + } + + if (peer == NULL) + { + SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_NO_CLIENT_CERT_RECEIVED); + al=SSL_AD_UNEXPECTED_MESSAGE; + goto f_err; + } + + if (!(type & EVP_PKT_SIGN)) + { + SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_SIGNATURE_FOR_NON_SIGNING_CERTIFICATE); + al=SSL_AD_ILLEGAL_PARAMETER; + goto f_err; + } + + if (s->s3->change_cipher_spec) + { + SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_CCS_RECEIVED_EARLY); + al=SSL_AD_UNEXPECTED_MESSAGE; + goto f_err; + } + + /* we now have a signature that we need to verify */ + p=(unsigned char *)s->init_msg; + /* Check for broken implementations of GOST ciphersuites */ + /* If key is GOST and n is exactly 64, it is bare + * signature without length field */ + if (n==64 && (pkey->type==NID_id_GostR3410_94 || + pkey->type == NID_id_GostR3410_2001) ) + { + i=64; + } + else + { + n2s(p,i); + n-=2; + if (i > n) + { + SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_LENGTH_MISMATCH); + al=SSL_AD_DECODE_ERROR; + goto f_err; + } + } + j=EVP_PKEY_size(pkey); + if ((i > j) || (n > j) || (n <= 0)) + { + SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_WRONG_SIGNATURE_SIZE); + al=SSL_AD_DECODE_ERROR; + goto f_err; + } + +#ifndef OPENSSL_NO_RSA + if (pkey->type == EVP_PKEY_RSA) + { + i=RSA_verify(NID_md5_sha1, s->s3->tmp.cert_verify_md, + MD5_DIGEST_LENGTH+SHA_DIGEST_LENGTH, p, i, + pkey->pkey.rsa); + if (i < 0) + { + al=SSL_AD_DECRYPT_ERROR; + SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_BAD_RSA_DECRYPT); + goto f_err; + } + if (i == 0) + { + al=SSL_AD_DECRYPT_ERROR; + SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_BAD_RSA_SIGNATURE); + goto f_err; + } + } + else +#endif +#ifndef OPENSSL_NO_DSA + if (pkey->type == EVP_PKEY_DSA) + { + j=DSA_verify(pkey->save_type, + &(s->s3->tmp.cert_verify_md[MD5_DIGEST_LENGTH]), + SHA_DIGEST_LENGTH,p,i,pkey->pkey.dsa); + if (j <= 0) + { + /* bad signature */ + al=SSL_AD_DECRYPT_ERROR; + SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_BAD_DSA_SIGNATURE); + goto f_err; + } + } + else +#endif +#ifndef OPENSSL_NO_ECDSA + if (pkey->type == EVP_PKEY_EC) + { + j=ECDSA_verify(pkey->save_type, + &(s->s3->tmp.cert_verify_md[MD5_DIGEST_LENGTH]), + SHA_DIGEST_LENGTH,p,i,pkey->pkey.ec); + if (j <= 0) + { + /* bad signature */ + al=SSL_AD_DECRYPT_ERROR; + SSLerr(SSL_F_SSL3_GET_CERT_VERIFY, + SSL_R_BAD_ECDSA_SIGNATURE); + goto f_err; + } + } + else +#endif + if (pkey->type == NID_id_GostR3410_94 || pkey->type == NID_id_GostR3410_2001) + { unsigned char signature[64]; + int idx; + EVP_PKEY_CTX *pctx = EVP_PKEY_CTX_new(pkey,NULL); + EVP_PKEY_verify_init(pctx); + if (i!=64) { + fprintf(stderr,"GOST signature length is %d",i); + } + for (idx=0;idx<64;idx++) { + signature[63-idx]=p[idx]; + } + j=EVP_PKEY_verify(pctx,signature,64,s->s3->tmp.cert_verify_md,32); + EVP_PKEY_CTX_free(pctx); + if (j<=0) + { + al=SSL_AD_DECRYPT_ERROR; + SSLerr(SSL_F_SSL3_GET_CERT_VERIFY, + SSL_R_BAD_ECDSA_SIGNATURE); + goto f_err; + } + } + else + { + SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,ERR_R_INTERNAL_ERROR); + al=SSL_AD_UNSUPPORTED_CERTIFICATE; + goto f_err; + } + + + ret=1; + if (0) + { +f_err: + ssl3_send_alert(s,SSL3_AL_FATAL,al); + } +end: + EVP_PKEY_free(pkey); + return(ret); + } + +int ssl3_get_client_certificate(SSL *s) + { + int i,ok,al,ret= -1; + X509 *x=NULL; + unsigned long l,nc,llen,n; + const unsigned char *p,*q; + unsigned char *d; + STACK_OF(X509) *sk=NULL; + + n=s->method->ssl_get_message(s, + SSL3_ST_SR_CERT_A, + SSL3_ST_SR_CERT_B, + -1, + s->max_cert_list, + &ok); + + if (!ok) return((int)n); + + if (s->s3->tmp.message_type == SSL3_MT_CLIENT_KEY_EXCHANGE) + { + if ( (s->verify_mode & SSL_VERIFY_PEER) && + (s->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT)) + { + SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,SSL_R_PEER_DID_NOT_RETURN_A_CERTIFICATE); + al=SSL_AD_HANDSHAKE_FAILURE; + goto f_err; + } + /* If tls asked for a client cert, the client must return a 0 list */ + if ((s->version > SSL3_VERSION) && s->s3->tmp.cert_request) + { + SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,SSL_R_TLS_PEER_DID_NOT_RESPOND_WITH_CERTIFICATE_LIST); + al=SSL_AD_UNEXPECTED_MESSAGE; + goto f_err; + } + s->s3->tmp.reuse_message=1; + return(1); + } + + if (s->s3->tmp.message_type != SSL3_MT_CERTIFICATE) + { + al=SSL_AD_UNEXPECTED_MESSAGE; + SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,SSL_R_WRONG_MESSAGE_TYPE); + goto f_err; + } + p=d=(unsigned char *)s->init_msg; + + if ((sk=sk_X509_new_null()) == NULL) + { + SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,ERR_R_MALLOC_FAILURE); + goto err; + } + + n2l3(p,llen); + if (llen+3 != n) + { + al=SSL_AD_DECODE_ERROR; + SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,SSL_R_LENGTH_MISMATCH); + goto f_err; + } + for (nc=0; nc llen) + { + al=SSL_AD_DECODE_ERROR; + SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,SSL_R_CERT_LENGTH_MISMATCH); + goto f_err; + } + + q=p; + x=d2i_X509(NULL,&p,l); + if (x == NULL) + { + SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,ERR_R_ASN1_LIB); + goto err; + } + if (p != (q+l)) + { + al=SSL_AD_DECODE_ERROR; + SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,SSL_R_CERT_LENGTH_MISMATCH); + goto f_err; + } + if (!sk_X509_push(sk,x)) + { + SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,ERR_R_MALLOC_FAILURE); + goto err; + } + x=NULL; + nc+=l+3; + } + + if (sk_X509_num(sk) <= 0) + { + /* TLS does not mind 0 certs returned */ + if (s->version == SSL3_VERSION) + { + al=SSL_AD_HANDSHAKE_FAILURE; + SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,SSL_R_NO_CERTIFICATES_RETURNED); + goto f_err; + } + /* Fail for TLS only if we required a certificate */ + else if ((s->verify_mode & SSL_VERIFY_PEER) && + (s->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT)) + { + SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,SSL_R_PEER_DID_NOT_RETURN_A_CERTIFICATE); + al=SSL_AD_HANDSHAKE_FAILURE; + goto f_err; + } + } + else + { + i=ssl_verify_cert_chain(s,sk); + if (i <= 0) + { + al=ssl_verify_alarm_type(s->verify_result); + SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,SSL_R_NO_CERTIFICATE_RETURNED); + goto f_err; + } + } + + if (s->session->peer != NULL) /* This should not be needed */ + X509_free(s->session->peer); + s->session->peer=sk_X509_shift(sk); + s->session->verify_result = s->verify_result; + + /* With the current implementation, sess_cert will always be NULL + * when we arrive here. */ + if (s->session->sess_cert == NULL) + { + s->session->sess_cert = ssl_sess_cert_new(); + if (s->session->sess_cert == NULL) + { + SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE, ERR_R_MALLOC_FAILURE); + goto err; + } + } + if (s->session->sess_cert->cert_chain != NULL) + sk_X509_pop_free(s->session->sess_cert->cert_chain, X509_free); + s->session->sess_cert->cert_chain=sk; + /* Inconsistency alert: cert_chain does *not* include the + * peer's own certificate, while we do include it in s3_clnt.c */ + + sk=NULL; + + ret=1; + if (0) + { +f_err: + ssl3_send_alert(s,SSL3_AL_FATAL,al); + } +err: + if (x != NULL) X509_free(x); + if (sk != NULL) sk_X509_pop_free(sk,X509_free); + return(ret); + } + +int ssl3_send_server_certificate(SSL *s) + { + unsigned long l; + X509 *x; + + if (s->state == SSL3_ST_SW_CERT_A) + { + x=ssl_get_server_send_cert(s); + if (x == NULL) + { + /* VRS: allow null cert if auth == KRB5 */ + if ((s->s3->tmp.new_cipher->algorithm_auth != SSL_aKRB5) || + (s->s3->tmp.new_cipher->algorithm_mkey & SSL_kKRB5)) + { + SSLerr(SSL_F_SSL3_SEND_SERVER_CERTIFICATE,ERR_R_INTERNAL_ERROR); + return(0); + } + } + + l=ssl3_output_cert_chain(s,x); + s->state=SSL3_ST_SW_CERT_B; + s->init_num=(int)l; + s->init_off=0; + } + + /* SSL3_ST_SW_CERT_B */ + return(ssl3_do_write(s,SSL3_RT_HANDSHAKE)); + } +#ifndef OPENSSL_NO_TLSEXT +int ssl3_send_newsession_ticket(SSL *s) + { + if (s->state == SSL3_ST_SW_SESSION_TICKET_A) + { + unsigned char *p, *senc, *macstart; + int len, slen; + unsigned int hlen; + EVP_CIPHER_CTX ctx; + HMAC_CTX hctx; + SSL_CTX *tctx = s->initial_ctx; + unsigned char iv[EVP_MAX_IV_LENGTH]; + unsigned char key_name[16]; + + /* get session encoding length */ + slen = i2d_SSL_SESSION(s->session, NULL); + /* Some length values are 16 bits, so forget it if session is + * too long + */ + if (slen > 0xFF00) + return -1; + /* Grow buffer if need be: the length calculation is as + * follows 1 (size of message name) + 3 (message length + * bytes) + 4 (ticket lifetime hint) + 2 (ticket length) + + * 16 (key name) + max_iv_len (iv length) + + * session_length + max_enc_block_size (max encrypted session + * length) + max_md_size (HMAC). + */ + if (!BUF_MEM_grow(s->init_buf, + 26 + EVP_MAX_IV_LENGTH + EVP_MAX_BLOCK_LENGTH + + EVP_MAX_MD_SIZE + slen)) + return -1; + senc = OPENSSL_malloc(slen); + if (!senc) + return -1; + p = senc; + i2d_SSL_SESSION(s->session, &p); + + p=(unsigned char *)s->init_buf->data; + /* do the header */ + *(p++)=SSL3_MT_NEWSESSION_TICKET; + /* Skip message length for now */ + p += 3; + EVP_CIPHER_CTX_init(&ctx); + HMAC_CTX_init(&hctx); + /* Initialize HMAC and cipher contexts. If callback present + * it does all the work otherwise use generated values + * from parent ctx. + */ + if (tctx->tlsext_ticket_key_cb) + { + if (tctx->tlsext_ticket_key_cb(s, key_name, iv, &ctx, + &hctx, 1) < 0) + { + OPENSSL_free(senc); + return -1; + } + } + else + { + RAND_pseudo_bytes(iv, 16); + EVP_EncryptInit_ex(&ctx, EVP_aes_128_cbc(), NULL, + tctx->tlsext_tick_aes_key, iv); + HMAC_Init_ex(&hctx, tctx->tlsext_tick_hmac_key, 16, + tlsext_tick_md(), NULL); + memcpy(key_name, tctx->tlsext_tick_key_name, 16); + } + l2n(s->session->tlsext_tick_lifetime_hint, p); + /* Skip ticket length for now */ + p += 2; + /* Output key name */ + macstart = p; + memcpy(p, key_name, 16); + p += 16; + /* output IV */ + memcpy(p, iv, EVP_CIPHER_CTX_iv_length(&ctx)); + p += EVP_CIPHER_CTX_iv_length(&ctx); + /* Encrypt session data */ + EVP_EncryptUpdate(&ctx, p, &len, senc, slen); + p += len; + EVP_EncryptFinal(&ctx, p, &len); + p += len; + EVP_CIPHER_CTX_cleanup(&ctx); + + HMAC_Update(&hctx, macstart, p - macstart); + HMAC_Final(&hctx, p, &hlen); + HMAC_CTX_cleanup(&hctx); + + p += hlen; + /* Now write out lengths: p points to end of data written */ + /* Total length */ + len = p - (unsigned char *)s->init_buf->data; + p=(unsigned char *)s->init_buf->data + 1; + l2n3(len - 4, p); /* Message length */ + p += 4; + s2n(len - 10, p); /* Ticket length */ + + /* number of bytes to write */ + s->init_num= len; + s->state=SSL3_ST_SW_SESSION_TICKET_B; + s->init_off=0; + OPENSSL_free(senc); + } + + /* SSL3_ST_SW_SESSION_TICKET_B */ + return(ssl3_do_write(s,SSL3_RT_HANDSHAKE)); + } + +int ssl3_send_cert_status(SSL *s) + { + if (s->state == SSL3_ST_SW_CERT_STATUS_A) + { + unsigned char *p; + /* Grow buffer if need be: the length calculation is as + * follows 1 (message type) + 3 (message length) + + * 1 (ocsp response type) + 3 (ocsp response length) + * + (ocsp response) + */ + if (!BUF_MEM_grow(s->init_buf, 8 + s->tlsext_ocsp_resplen)) + return -1; + + p=(unsigned char *)s->init_buf->data; + + /* do the header */ + *(p++)=SSL3_MT_CERTIFICATE_STATUS; + /* message length */ + l2n3(s->tlsext_ocsp_resplen + 4, p); + /* status type */ + *(p++)= s->tlsext_status_type; + /* length of OCSP response */ + l2n3(s->tlsext_ocsp_resplen, p); + /* actual response */ + memcpy(p, s->tlsext_ocsp_resp, s->tlsext_ocsp_resplen); + /* number of bytes to write */ + s->init_num = 8 + s->tlsext_ocsp_resplen; + s->state=SSL3_ST_SW_CERT_STATUS_B; + s->init_off = 0; + } + + /* SSL3_ST_SW_CERT_STATUS_B */ + return(ssl3_do_write(s,SSL3_RT_HANDSHAKE)); + } + +# ifndef OPENSSL_NO_NPN +/* ssl3_get_next_proto reads a Next Protocol Negotiation handshake message. It + * sets the next_proto member in s if found */ +int ssl3_get_next_proto(SSL *s) + { + int ok; + unsigned proto_len, padding_len; + long n; + const unsigned char *p; + + /* Clients cannot send a NextProtocol message if we didn't see the + * extension in their ClientHello */ + if (!s->s3->next_proto_neg_seen) + { + SSLerr(SSL_F_SSL3_GET_NEXT_PROTO,SSL_R_GOT_NEXT_PROTO_WITHOUT_EXTENSION); + return -1; + } + + n=s->method->ssl_get_message(s, + SSL3_ST_SR_NEXT_PROTO_A, + SSL3_ST_SR_NEXT_PROTO_B, + SSL3_MT_NEXT_PROTO, + 514, /* See the payload format below */ + &ok); + + if (!ok) + return((int)n); + + /* s->state doesn't reflect whether ChangeCipherSpec has been received + * in this handshake, but s->s3->change_cipher_spec does (will be reset + * by ssl3_get_finished). */ + if (!s->s3->change_cipher_spec) + { + SSLerr(SSL_F_SSL3_GET_NEXT_PROTO,SSL_R_GOT_NEXT_PROTO_BEFORE_A_CCS); + return -1; + } + + if (n < 2) + return 0; /* The body must be > 1 bytes long */ + + p=(unsigned char *)s->init_msg; + + /* The payload looks like: + * uint8 proto_len; + * uint8 proto[proto_len]; + * uint8 padding_len; + * uint8 padding[padding_len]; + */ + proto_len = p[0]; + if (proto_len + 2 > s->init_num) + return 0; + padding_len = p[proto_len + 1]; + if (proto_len + padding_len + 2 != s->init_num) + return 0; + + s->next_proto_negotiated = OPENSSL_malloc(proto_len); + if (!s->next_proto_negotiated) + { + SSLerr(SSL_F_SSL3_GET_NEXT_PROTO,ERR_R_MALLOC_FAILURE); + return 0; + } + memcpy(s->next_proto_negotiated, p + 1, proto_len); + s->next_proto_negotiated_len = proto_len; + + return 1; + } +# endif +#endif diff --git a/node-v0.8.14/deps/openssl/openssl/ssl/ssl-lib.com b/node-v0.8.14/deps/openssl/openssl/ssl/ssl-lib.com new file mode 100644 index 0000000..180f3a2 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/ssl/ssl-lib.com @@ -0,0 +1,1214 @@ +$! +$! SSL-LIB.COM +$! Written By: Robert Byer +$! Vice-President +$! A-Com Computing, Inc. +$! byer@mail.all-net.net +$! +$! Changes by Richard Levitte +$! +$! This command file compiles and creates the "[.xxx.EXE.SSL]LIBSSL.OLB" +$! library for OpenSSL. The "xxx" denotes the machine architecture of +$! ALPHA, IA64 or VAX. +$! +$! It is written to detect what type of machine you are compiling on +$! (i.e. ALPHA or VAX) and which "C" compiler you have (i.e. VAXC, DECC +$! or GNU C) or you can specify which compiler to use. +$! +$! Specify the following as P1 to build just that part or ALL to just +$! build everything. +$! +$! LIBRARY To just compile the [.xxx.EXE.SSL]LIBSSL.OLB Library. +$! SSL_TASK To just compile the [.xxx.EXE.SSL]SSL_TASK.EXE +$! +$! Specify DEBUG or NODEBUG as P2 to compile with or without debugger +$! information. +$! +$! Specify which compiler at P3 to try to compile under. +$! +$! VAXC For VAX C. +$! DECC For DEC C. +$! GNUC For GNU C. +$! +$! If you don't specify a compiler, it will try to determine which +$! "C" compiler to use. +$! +$! P4, if defined, sets a TCP/IP library to use, through one of the following +$! keywords: +$! +$! UCX for UCX +$! TCPIP for TCPIP (post UCX) +$! SOCKETSHR for SOCKETSHR+NETLIB +$! +$! P5, if defined, sets a compiler thread NOT needed on OpenVMS 7.1 (and up) +$! +$! P6, if defined, specifies the C pointer size. Ignored on VAX. +$! ("64=ARGV" gives more efficient code with HP C V7.3 or newer.) +$! Supported values are: +$! +$! "" Compile with default (/NOPOINTER_SIZE) +$! 32 Compile with /POINTER_SIZE=32 (SHORT) +$! 64 Compile with /POINTER_SIZE=64[=ARGV] (LONG[=ARGV]) +$! (Automatically select ARGV if compiler supports it.) +$! 64= Compile with /POINTER_SIZE=64 (LONG). +$! 64=ARGV Compile with /POINTER_SIZE=64=ARGV (LONG=ARGV). +$! +$! P7, if defined, specifies a directory where ZLIB files (zlib.h, +$! libz.olb) may be found. Optionally, a non-default object library +$! name may be included ("dev:[dir]libz_64.olb", for example). +$! +$! +$! Announce/identify. +$! +$ proc = f$environment( "procedure") +$ write sys$output "@@@ "+ - + f$parse( proc, , , "name")+ f$parse( proc, , , "type") +$! +$! Define A TCP/IP Library That We Will Need To Link To. +$! (That Is, If We Need To Link To One.) +$! +$ TCPIP_LIB = "" +$ ZLIB_LIB = "" +$! +$! Check What Architecture We Are Using. +$! +$ IF (F$GETSYI("CPU").LT.128) +$ THEN +$! +$! The Architecture Is VAX. +$! +$ ARCH = "VAX" +$! +$! Else... +$! +$ ELSE +$! +$! The Architecture Is Alpha, IA64 or whatever comes in the future. +$! +$ ARCH = F$EDIT( F$GETSYI( "ARCH_NAME"), "UPCASE") +$ IF (ARCH .EQS. "") THEN ARCH = "UNK" +$! +$! End The Architecture Check. +$! +$ ENDIF +$! +$ ARCHD = ARCH +$ LIB32 = "32" +$ OPT_FILE = "" +$ POINTER_SIZE = "" +$! +$! Check To Make Sure We Have Valid Command Line Parameters. +$! +$ GOSUB CHECK_OPTIONS +$! +$! Define The OBJ and EXE Directories. +$! +$ OBJ_DIR := SYS$DISK:[-.'ARCHD'.OBJ.SSL] +$ EXE_DIR := SYS$DISK:[-.'ARCHD'.EXE.SSL] +$! +$! Specify the destination directory in any /MAP option. +$! +$ if (LINKMAP .eqs. "MAP") +$ then +$ LINKMAP = LINKMAP+ "=''EXE_DIR'" +$ endif +$! +$! Add the location prefix to the linker options file name. +$! +$ if (OPT_FILE .nes. "") +$ then +$ OPT_FILE = EXE_DIR+ OPT_FILE +$ endif +$! +$! Initialise logical names and such +$! +$ GOSUB INITIALISE +$! +$! Tell The User What Kind of Machine We Run On. +$! +$ WRITE SYS$OUTPUT "Host system architecture: ''ARCHD'" +$! +$! Check To See If The Architecture Specific OBJ Directory Exists. +$! +$ IF (F$PARSE(OBJ_DIR).EQS."") +$ THEN +$! +$! It Dosen't Exist, So Create It. +$! +$ CREATE/DIR 'OBJ_DIR' +$! +$! End The Architecture Specific OBJ Directory Check. +$! +$ ENDIF +$! +$! Check To See If The Architecture Specific Directory Exists. +$! +$ IF (F$PARSE(EXE_DIR).EQS."") +$ THEN +$! +$! It Dosen't Exist, So Create It. +$! +$ CREATE/DIR 'EXE_DIR' +$! +$! End The Architecture Specific Directory Check. +$! +$ ENDIF +$! +$! Define The Library Name. +$! +$ SSL_LIB := 'EXE_DIR'SSL_LIBSSL'LIB32'.OLB +$! +$! Define The CRYPTO-LIB We Are To Use. +$! +$ CRYPTO_LIB := SYS$DISK:[-.'ARCHD'.EXE.CRYPTO]SSL_LIBCRYPTO'LIB32'.OLB +$! +$! Set up exceptional compilations. +$! +$ CC5_SHOWN = 0 +$! +$! Check To See What We Are To Do. +$! +$ IF (BUILDALL.EQS."TRUE") +$ THEN +$! +$! Since Nothing Special Was Specified, Do Everything. +$! +$ GOSUB LIBRARY +$ GOSUB SSL_TASK +$! +$! Else... +$! +$ ELSE +$! +$! Build Just What The User Wants Us To Build. +$! +$ GOSUB 'BUILDALL' +$! +$! End The BUILDALL Check. +$! +$ ENDIF +$! +$! Time To EXIT. +$! +$ EXIT: +$ GOSUB CLEANUP +$ EXIT +$! +$! Compile The Library. +$! +$ LIBRARY: +$! +$! Check To See If We Already Have A "[.xxx.EXE.SSL]SSL_LIBSSL''LIB32'.OLB" Library... +$! +$ IF (F$SEARCH(SSL_LIB).EQS."") +$ THEN +$! +$! Guess Not, Create The Library. +$! +$ LIBRARY/CREATE/OBJECT 'SSL_LIB' +$! +$! End The Library Exist Check. +$! +$ ENDIF +$! +$! Define The Different SSL "library" Files. +$! +$ LIB_SSL = "s2_meth,s2_srvr,s2_clnt,s2_lib,s2_enc,s2_pkt,"+ - + "s3_meth,s3_srvr,s3_clnt,s3_lib,s3_enc,s3_pkt,s3_both,"+ - + "s23_meth,s23_srvr,s23_clnt,s23_lib,s23_pkt,"+ - + "t1_meth,t1_srvr,t1_clnt,t1_lib,t1_enc,"+ - + "d1_meth,d1_srvr,d1_clnt,d1_lib,d1_pkt,"+ - + "d1_both,d1_enc,"+ - + "ssl_lib,ssl_err2,ssl_cert,ssl_sess,"+ - + "ssl_ciph,ssl_stat,ssl_rsa,"+ - + "ssl_asn1,ssl_txt,ssl_algs,"+ - + "bio_ssl,ssl_err,kssl,t1_reneg" +$! +$ COMPILEWITH_CC5 = "" +$! +$! Tell The User That We Are Compiling The Library. +$! +$ WRITE SYS$OUTPUT "Building The ",SSL_LIB," Library." +$! +$! Define A File Counter And Set It To "0" +$! +$ FILE_COUNTER = 0 +$! +$! Top Of The File Loop. +$! +$ NEXT_FILE: +$! +$! O.K, Extract The File Name From The File List. +$! +$ FILE_NAME = F$ELEMENT(FILE_COUNTER,",",LIB_SSL) +$! +$! Check To See If We Are At The End Of The File List. +$! +$ IF (FILE_NAME.EQS.",") THEN GOTO FILE_DONE +$! +$! Increment The Counter. +$! +$ FILE_COUNTER = FILE_COUNTER + 1 +$! +$! Create The Source File Name. +$! +$ SOURCE_FILE = "SYS$DISK:[]" + FILE_NAME + ".C" +$! +$! Create The Object File Name. +$! +$ OBJECT_FILE = OBJ_DIR + FILE_NAME + ".OBJ" +$ ON WARNING THEN GOTO NEXT_FILE +$! +$! Check To See If The File We Want To Compile Is Actually There. +$! +$ IF (F$SEARCH(SOURCE_FILE).EQS."") +$ THEN +$! +$! Tell The User That The File Dosen't Exist. +$! +$ WRITE SYS$OUTPUT "" +$ WRITE SYS$OUTPUT "The File ",SOURCE_FILE," Dosen't Exist." +$ WRITE SYS$OUTPUT "" +$! +$! Exit The Build. +$! +$ EXIT +$! +$! End The File Exists Check. +$! +$ ENDIF +$! +$! Tell The User What File We Are Compiling. +$! +$ WRITE SYS$OUTPUT " ",FILE_NAME,".c" +$! +$! Compile The File. +$! +$ ON ERROR THEN GOTO NEXT_FILE +$ CC/OBJECT='OBJECT_FILE' 'SOURCE_FILE' +$! +$! Add It To The Library. +$! +$ LIBRARY/REPLACE/OBJECT 'SSL_LIB' 'OBJECT_FILE' +$! +$! Time To Clean Up The Object File. +$! +$ DELETE 'OBJECT_FILE';* +$! +$! Go Back And Get The Next File Name. +$! +$ GOTO NEXT_FILE +$! +$! All Done With This Library. +$! +$ FILE_DONE: +$! +$! Tell The User That We Are All Done. +$! +$ WRITE SYS$OUTPUT "Library ",SSL_LIB," Compiled." +$! +$! Time To RETURN. +$! +$ RETURN +$ SSL_TASK: +$! +$! Check To See If We Have The Proper Libraries. +$! +$ GOSUB LIB_CHECK +$! +$! Check To See If We Have A Linker Option File. +$! +$ GOSUB CHECK_OPT_FILE +$! +$! Check To See If The File We Want To Compile Is Actually There. +$! +$ IF (F$SEARCH("SYS$DISK:[]SSL_TASK.C").EQS."") +$ THEN +$! +$! Tell The User That The File Dosen't Exist. +$! +$ WRITE SYS$OUTPUT "" +$ WRITE SYS$OUTPUT "The File SSL_TASK.C Dosen't Exist." +$ WRITE SYS$OUTPUT "" +$! +$! Exit The Build. +$! +$ EXIT +$! +$! End The SSL_TASK.C File Check. +$! +$ ENDIF +$! +$ COMPILEWITH_CC5 = "" !!! ",ssl_task," +$! +$! Tell The User We Are Creating The SSL_TASK. +$! +$! Tell The User We Are Creating The SSL_TASK. +$! +$ WRITE SYS$OUTPUT "Creating SSL_TASK OSU HTTP SSL Engine." +$! +$! Tell The User What File We Are Compiling. +$! +$ FILE_NAME = "ssl_task" +$ WRITE SYS$OUTPUT " ",FILE_NAME,".c" +$! +$! Compile The File. +$! +$ ON ERROR THEN GOTO SSL_TASK_END +$! +$ FILE_NAME0 = ","+ F$ELEMENT(0,".",FILE_NAME)+ "," +$ IF COMPILEWITH_CC5 - FILE_NAME0 .NES. COMPILEWITH_CC5 +$ THEN +$ if (.not. CC5_SHOWN) +$ then +$ CC5_SHOWN = 1 +$ write sys$output " \Using special rule (5)" +$ x = " "+ CC5 +$ write /symbol sys$output x +$ endif +$ CC5 /OBJECT='OBJ_DIR''FILE_NAME'.OBJ SYS$DISK:[]'FILE_NAME'.C +$ ELSE +$ CC /OBJECT='OBJ_DIR''FILE_NAME'.OBJ SYS$DISK:[]'FILE_NAME'.C +$ ENDIF +$! +$! Link The Program. +$! +$ LINK /'DEBUGGER' /'LINKMAP' /'TRACEBACK' /EXE='EXE_DIR'SSL_TASK.EXE - + 'OBJ_DIR'SSL_TASK.OBJ, - + 'SSL_LIB'/LIBRARY, - + 'CRYPTO_LIB'/LIBRARY - + 'TCPIP_LIB' - + 'ZLIB_LIB' - + ,'OPT_FILE' /OPTIONS +$! +$! Time To Return. +$! +$SSL_TASK_END: +$ RETURN +$! +$! Check For The Link Option FIle. +$! +$ CHECK_OPT_FILE: +$! +$! Check To See If We Need To Make A VAX C Option File. +$! +$ IF (COMPILER.EQS."VAXC") +$ THEN +$! +$! Check To See If We Already Have A VAX C Linker Option File. +$! +$ IF (F$SEARCH(OPT_FILE).EQS."") +$ THEN +$! +$! We Need A VAX C Linker Option File. +$! +$ CREATE 'OPT_FILE' +$DECK +! +! Default System Options File To Link Against +! The Sharable VAX C Runtime Library. +! +SYS$SHARE:VAXCRTL.EXE/SHARE +$EOD +$! +$! End The Option File Check. +$! +$ ENDIF +$! +$! End The VAXC Check. +$! +$ ENDIF +$! +$! Check To See If We Need A GNU C Option File. +$! +$ IF (COMPILER.EQS."GNUC") +$ THEN +$! +$! Check To See If We Already Have A GNU C Linker Option File. +$! +$ IF (F$SEARCH(OPT_FILE).EQS."") +$ THEN +$! +$! We Need A GNU C Linker Option File. +$! +$ CREATE 'OPT_FILE' +$DECK +! +! Default System Options File To Link Against +! The Sharable C Runtime Library. +! +GNU_CC:[000000]GCCLIB/LIBRARY +SYS$SHARE:VAXCRTL/SHARE +$EOD +$! +$! End The Option File Check. +$! +$ ENDIF +$! +$! End The GNU C Check. +$! +$ ENDIF +$! +$! Check To See If We Need A DEC C Option File. +$! +$ IF (COMPILER.EQS."DECC") +$ THEN +$! +$! Check To See If We Already Have A DEC C Linker Option File. +$! +$ IF (F$SEARCH(OPT_FILE).EQS."") +$ THEN +$! +$! Figure Out If We Need A non-VAX Or A VAX Linker Option File. +$! +$ IF (ARCH.EQS."VAX") +$ THEN +$! +$! We Need A DEC C Linker Option File For VAX. +$! +$ CREATE 'OPT_FILE' +$DECK +! +! Default System Options File To Link Against +! The Sharable DEC C Runtime Library. +! +SYS$SHARE:DECC$SHR.EXE/SHARE +$EOD +$! +$! Else... +$! +$ ELSE +$! +$! Create The non-VAX Linker Option File. +$! +$ CREATE 'OPT_FILE' +$DECK +! +! Default System Options File For non-VAX To Link Against +! The Sharable C Runtime Library. +! +SYS$SHARE:CMA$OPEN_LIB_SHR/SHARE +SYS$SHARE:CMA$OPEN_RTL/SHARE +$EOD +$! +$! End The DEC C Option File Check. +$! +$ ENDIF +$! +$! End The Option File Search. +$! +$ ENDIF +$! +$! End The DEC C Check. +$! +$ ENDIF +$! +$! Tell The User What Linker Option File We Are Using. +$! +$ WRITE SYS$OUTPUT "Using Linker Option File ",OPT_FILE,"." +$! +$! Time To RETURN. +$! +$ RETURN +$ LIB_CHECK: +$! +$! Look For The VAX Library LIBSSL.OLB. +$! +$ IF (F$SEARCH(SSL_LIB).EQS."") +$ THEN +$! +$! Tell The User We Can't Find The LIBSSL.OLB Library. +$! +$ WRITE SYS$OUTPUT "" +$ WRITE SYS$OUTPUT "Can't Find The Library ",SSL_LIB,"." +$ WRITE SYS$OUTPUT "We Can't Link Without It." +$ WRITE SYS$OUTPUT "" +$! +$! Since We Can't Link Without It, Exit. +$! +$ EXIT +$! +$! End The LIBSSL.OLB Library Check. +$! +$ ENDIF +$! +$! Look For The Library LIBCRYPTO.OLB. +$! +$ IF (F$SEARCH(CRYPTO_LIB).EQS."") +$ THEN +$! +$! Tell The User We Can't Find The LIBCRYPTO.OLB Library. +$! +$ WRITE SYS$OUTPUT "" +$ WRITE SYS$OUTPUT "Can't Find The Library ",CRYPTO_LIB,"." +$ WRITE SYS$OUTPUT "We Can't Link Without It." +$ WRITE SYS$OUTPUT "" +$! +$! Since We Can't Link Without It, Exit. +$! +$ EXIT +$! +$! End The LIBCRYPTO.OLB Library Check. +$! +$ ENDIF +$! +$! Time To Return. +$! +$ RETURN +$! +$! Check The User's Options. +$! +$ CHECK_OPTIONS: +$! +$! Check To See If P1 Is Blank. +$! +$ IF (P1.EQS."ALL") +$ THEN +$! +$! P1 Is Blank, So Build Everything. +$! +$ BUILDALL = "TRUE" +$! +$! Else... +$! +$ ELSE +$! +$! Else, Check To See If P1 Has A Valid Argument. +$! +$ IF (P1.EQS."LIBRARY").OR.(P1.EQS."SSL_TASK") +$ THEN +$! +$! A Valid Argument. +$! +$ BUILDALL = P1 +$! +$! Else... +$! +$ ELSE +$! +$! Tell The User We Don't Know What They Want. +$! +$ WRITE SYS$OUTPUT "" +$ WRITE SYS$OUTPUT "The Option ",P1," Is Invalid. The Valid Options Are:" +$ WRITE SYS$OUTPUT "" +$ WRITE SYS$OUTPUT " ALL : Just Build Everything." +$ WRITE SYS$OUTPUT " LIBRARY : To Compile Just The [.xxx.EXE.SSL]LIBSSL.OLB Library." +$ WRITE SYS$OUTPUT " SSL_TASK : To Compile Just The [.xxx.EXE.SSL]SSL_TASK.EXE Program." +$ WRITE SYS$OUTPUT "" +$ WRITE SYS$OUTPUT " Where 'xxx' Stands For:" +$ WRITE SYS$OUTPUT "" +$ WRITE SYS$OUTPUT " ALPHA[64]: Alpha Architecture." +$ WRITE SYS$OUTPUT " IA64[64] : IA64 Architecture." +$ WRITE SYS$OUTPUT " VAX : VAX Architecture." +$ WRITE SYS$OUTPUT "" +$! +$! Time To EXIT. +$! +$ EXIT +$! +$! End The Valid Argument Check. +$! +$ ENDIF +$! +$! End The P1 Check. +$! +$ ENDIF +$! +$! Check To See If P2 Is Blank. +$! +$ IF (P2.EQS."NODEBUG") +$ THEN +$! +$! P2 Is NODEBUG, So Compile Without Debugger Information. +$! +$ DEBUGGER = "NODEBUG" +$ LINKMAP = "NOMAP" +$ TRACEBACK = "NOTRACEBACK" +$ GCC_OPTIMIZE = "OPTIMIZE" +$ CC_OPTIMIZE = "OPTIMIZE" +$ WRITE SYS$OUTPUT "No Debugger Information Will Be Produced During Compile." +$ WRITE SYS$OUTPUT "Compiling With Compiler Optimization." +$! +$! Else... +$! +$ ELSE +$! +$! Check To See If We Are To Compile With Debugger Information. +$! +$ IF (P2.EQS."DEBUG") +$ THEN +$! +$! Compile With Debugger Information. +$! +$ DEBUGGER = "DEBUG" +$ LINKMAP = "MAP" +$ TRACEBACK = "TRACEBACK" +$ GCC_OPTIMIZE = "NOOPTIMIZE" +$ CC_OPTIMIZE = "NOOPTIMIZE" +$ WRITE SYS$OUTPUT "Debugger Information Will Be Produced During Compile." +$ WRITE SYS$OUTPUT "Compiling Without Compiler Optimization." +$ ELSE +$! +$! Tell The User Entered An Invalid Option. +$! +$ WRITE SYS$OUTPUT "" +$ WRITE SYS$OUTPUT "The Option ",P2," Is Invalid. The Valid Options Are:" +$ WRITE SYS$OUTPUT "" +$ WRITE SYS$OUTPUT " DEBUG : Compile With The Debugger Information." +$ WRITE SYS$OUTPUT " NODEBUG : Compile Without The Debugger Information." +$ WRITE SYS$OUTPUT "" +$! +$! Time To EXIT. +$! +$ EXIT +$! +$! End The Valid Argument Check. +$! +$ ENDIF +$! +$! End The P2 Check. +$! +$ ENDIF +$! +$! Special Threads For OpenVMS v7.1 Or Later +$! +$! Written By: Richard Levitte +$! richard@levitte.org +$! +$! +$! Check To See If We Have A Option For P5. +$! +$ IF (P5.EQS."") +$ THEN +$! +$! Get The Version Of VMS We Are Using. +$! +$ ISSEVEN := +$ TMP = F$ELEMENT(0,"-",F$EXTRACT(1,4,F$GETSYI("VERSION"))) +$ TMP = F$INTEGER(F$ELEMENT(0,".",TMP)+F$ELEMENT(1,".",TMP)) +$! +$! Check To See If The VMS Version Is v7.1 Or Later. +$! +$ IF (TMP.GE.71) +$ THEN +$! +$! We Have OpenVMS v7.1 Or Later, So Use The Special Threads. +$! +$ ISSEVEN := ,PTHREAD_USE_D4 +$! +$! End The VMS Version Check. +$! +$ ENDIF +$! +$! End The P5 Check. +$! +$ ENDIF +$! +$! Check P6 (POINTER_SIZE). +$! +$ IF (P6 .NES. "") .AND. (ARCH .NES. "VAX") +$ THEN +$! +$ IF (P6 .EQS. "32") +$ THEN +$ POINTER_SIZE = " /POINTER_SIZE=32" +$ ELSE +$ POINTER_SIZE = F$EDIT( P6, "COLLAPSE, UPCASE") +$ IF ((POINTER_SIZE .EQS. "64") .OR. - + (POINTER_SIZE .EQS. "64=") .OR. - + (POINTER_SIZE .EQS. "64=ARGV")) +$ THEN +$ ARCHD = ARCH+ "_64" +$ LIB32 = "" +$ POINTER_SIZE = " /POINTER_SIZE=64" +$ ELSE +$! +$! Tell The User Entered An Invalid Option. +$! +$ WRITE SYS$OUTPUT "" +$ WRITE SYS$OUTPUT "The Option ", P6, - + " Is Invalid. The Valid Options Are:" +$ WRITE SYS$OUTPUT "" +$ WRITE SYS$OUTPUT - + " """" : Compile with default (short) pointers." +$ WRITE SYS$OUTPUT - + " 32 : Compile with 32-bit (short) pointers." +$ WRITE SYS$OUTPUT - + " 64 : Compile with 64-bit (long) pointers (auto ARGV)." +$ WRITE SYS$OUTPUT - + " 64= : Compile with 64-bit (long) pointers (no ARGV)." +$ WRITE SYS$OUTPUT - + " 64=ARGV : Compile with 64-bit (long) pointers (ARGV)." +$ WRITE SYS$OUTPUT "" +$! +$! Time To EXIT. +$! +$ EXIT +$! +$ ENDIF +$! +$ ENDIF +$! +$! End The P6 (POINTER_SIZE) Check. +$! +$ ENDIF +$! +$! Set basic C compiler /INCLUDE directories. +$! +$ CC_INCLUDES = "SYS$DISK:[-.CRYPTO],SYS$DISK:[-]" +$! +$! Check To See If P3 Is Blank. +$! +$ IF (P3.EQS."") +$ THEN +$! +$! O.K., The User Didn't Specify A Compiler, Let's Try To +$! Find Out Which One To Use. +$! +$! Check To See If We Have GNU C. +$! +$ IF (F$TRNLNM("GNU_CC").NES."") +$ THEN +$! +$! Looks Like GNUC, Set To Use GNUC. +$! +$ P3 = "GNUC" +$! +$! End The GNU C Compiler Check. +$! +$ ELSE +$! +$! Check To See If We Have VAXC Or DECC. +$! +$ IF (ARCH.NES."VAX").OR.(F$TRNLNM("DECC$CC_DEFAULT").NES."") +$ THEN +$! +$! Looks Like DECC, Set To Use DECC. +$! +$ P3 = "DECC" +$! +$! Else... +$! +$ ELSE +$! +$! Looks Like VAXC, Set To Use VAXC. +$! +$ P3 = "VAXC" +$! +$! End The VAXC Compiler Check. +$! +$ ENDIF +$! +$! End The DECC & VAXC Compiler Check. +$! +$ ENDIF +$! +$! End The Compiler Check. +$! +$ ENDIF +$! +$! Check To See If We Have A Option For P4. +$! +$ IF (P4.EQS."") +$ THEN +$! +$! Find out what socket library we have available +$! +$ IF F$PARSE("SOCKETSHR:") .NES. "" +$ THEN +$! +$! We have SOCKETSHR, and it is my opinion that it's the best to use. +$! +$ P4 = "SOCKETSHR" +$! +$! Tell the user +$! +$ WRITE SYS$OUTPUT "Using SOCKETSHR for TCP/IP" +$! +$! Else, let's look for something else +$! +$ ELSE +$! +$! Like UCX (the reason to do this before Multinet is that the UCX +$! emulation is easier to use...) +$! +$ IF F$TRNLNM("UCX$IPC_SHR") .NES. "" - + .OR. F$PARSE("SYS$SHARE:UCX$IPC_SHR.EXE") .NES. "" - + .OR. F$PARSE("SYS$LIBRARY:UCX$IPC.OLB") .NES. "" +$ THEN +$! +$! Last resort: a UCX or UCX-compatible library +$! +$ P4 = "UCX" +$! +$! Tell the user +$! +$ WRITE SYS$OUTPUT "Using UCX or an emulation thereof for TCP/IP" +$! +$! That was all... +$! +$ ENDIF +$ ENDIF +$ ENDIF +$! +$! Set Up Initial CC Definitions, Possibly With User Ones +$! +$ CCDEFS = "TCPIP_TYPE_''P4'" +$ IF F$TYPE(USER_CCDEFS) .NES. "" THEN CCDEFS = CCDEFS + "," + USER_CCDEFS +$ CCEXTRAFLAGS = "" +$ IF F$TYPE(USER_CCFLAGS) .NES. "" THEN CCEXTRAFLAGS = USER_CCFLAGS +$ CCDISABLEWARNINGS = "" !!! "LONGLONGTYPE,LONGLONGSUFX,FOUNDCR" +$ IF F$TYPE(USER_CCDISABLEWARNINGS) .NES. "" THEN - + CCDISABLEWARNINGS = CCDISABLEWARNINGS + "," + USER_CCDISABLEWARNINGS +$! +$! Check To See If We Have A ZLIB Option. +$! +$ ZLIB = P7 +$ IF (ZLIB .NES. "") +$ THEN +$! +$! Check for expected ZLIB files. +$! +$ err = 0 +$ file1 = f$parse( "zlib.h", ZLIB, , , "SYNTAX_ONLY") +$ if (f$search( file1) .eqs. "") +$ then +$ WRITE SYS$OUTPUT "" +$ WRITE SYS$OUTPUT "The Option ", ZLIB, " Is Invalid." +$ WRITE SYS$OUTPUT " Can't find header: ''file1'" +$ err = 1 +$ endif +$ file1 = f$parse( "A.;", ZLIB)- "A.;" +$! +$ file2 = f$parse( ZLIB, "libz.olb", , , "SYNTAX_ONLY") +$ if (f$search( file2) .eqs. "") +$ then +$ if (err .eq. 0) +$ then +$ WRITE SYS$OUTPUT "" +$ WRITE SYS$OUTPUT "The Option ", ZLIB, " Is Invalid." +$ endif +$ WRITE SYS$OUTPUT " Can't find library: ''file2'" +$ WRITE SYS$OUTPUT "" +$ err = err+ 2 +$ endif +$ if (err .eq. 1) +$ then +$ WRITE SYS$OUTPUT "" +$ endif +$! +$ if (err .ne. 0) +$ then +$ EXIT +$ endif +$! +$ CCDEFS = """ZLIB=1"", "+ CCDEFS +$ CC_INCLUDES = CC_INCLUDES+ ", "+ file1 +$ ZLIB_LIB = ", ''file2' /library" +$! +$! Print info +$! +$ WRITE SYS$OUTPUT "ZLIB library spec: ", file2 +$! +$! End The ZLIB Check. +$! +$ ENDIF +$! +$! Check To See If The User Entered A Valid Parameter. +$! +$ IF (P3.EQS."VAXC").OR.(P3.EQS."DECC").OR.(P3.EQS."GNUC") +$ THEN +$! +$! Check To See If The User Wanted DECC. +$! +$ IF (P3.EQS."DECC") +$ THEN +$! +$! Looks Like DECC, Set To Use DECC. +$! +$ COMPILER = "DECC" +$! +$! Tell The User We Are Using DECC. +$! +$ WRITE SYS$OUTPUT "Using DECC 'C' Compiler." +$! +$! Use DECC... +$! +$ CC = "CC" +$ IF ARCH.EQS."VAX" .AND. F$TRNLNM("DECC$CC_DEFAULT").NES."/DECC" - + THEN CC = "CC/DECC" +$ CC = CC + " /''CC_OPTIMIZE' /''DEBUGGER' /STANDARD=RELAXED"+ - + "''POINTER_SIZE' /NOLIST /PREFIX=ALL" + - + " /INCLUDE=(''CC_INCLUDES') " + CCEXTRAFLAGS +$! +$! Define The Linker Options File Name. +$! +$ OPT_FILE = "VAX_DECC_OPTIONS.OPT" +$! +$! End DECC Check. +$! +$ ENDIF +$! +$! Check To See If We Are To Use VAXC. +$! +$ IF (P3.EQS."VAXC") +$ THEN +$! +$! Looks Like VAXC, Set To Use VAXC. +$! +$ COMPILER = "VAXC" +$! +$! Tell The User We Are Using VAX C. +$! +$ WRITE SYS$OUTPUT "Using VAXC 'C' Compiler." +$! +$! Compile Using VAXC. +$! +$ CC = "CC" +$ IF ARCH.NES."VAX" +$ THEN +$ WRITE SYS$OUTPUT "There is no VAX C on ''ARCH'!" +$ EXIT +$ ENDIF +$ IF F$TRNLNM("DECC$CC_DEFAULT").EQS."/DECC" THEN CC = "CC/VAXC" +$ CC = CC + "/''CC_OPTIMIZE'/''DEBUGGER'/NOLIST" + - + "/INCLUDE=(''CC_INCLUDES')" + CCEXTRAFLAGS +$ CCDEFS = CCDEFS + ",""VAXC""" +$! +$! Define As SYS$COMMON:[SYSLIB] +$! +$ DEFINE/NOLOG SYS SYS$COMMON:[SYSLIB] +$! +$! Define The Linker Options File Name. +$! +$ OPT_FILE = "VAX_VAXC_OPTIONS.OPT" +$! +$! End VAXC Check +$! +$ ENDIF +$! +$! Check To See If We Are To Use GNU C. +$! +$ IF (P3.EQS."GNUC") +$ THEN +$! +$! Looks Like GNUC, Set To Use GNUC. +$! +$ COMPILER = "GNUC" +$! +$! Tell The User We Are Using GNUC. +$! +$ WRITE SYS$OUTPUT "Using GNU 'C' Compiler." +$! +$! Use GNU C... +$! +$ IF F$TYPE(GCC) .EQS. "" THEN GCC := GCC +$ CC = GCC+"/NOCASE_HACK/''GCC_OPTIMIZE'/''DEBUGGER'/NOLIST" + - + "/INCLUDE=(''CC_INCLUDES')" + CCEXTRAFLAGS +$! +$! Define The Linker Options File Name. +$! +$ OPT_FILE = "VAX_GNUC_OPTIONS.OPT" +$! +$! End The GNU C Check. +$! +$ ENDIF +$! +$! Set up default defines +$! +$ CCDEFS = """FLAT_INC=1""," + CCDEFS +$! +$! Finish up the definition of CC. +$! +$ IF COMPILER .EQS. "DECC" +$ THEN +$ IF CCDISABLEWARNINGS .EQS. "" +$ THEN +$ CC4DISABLEWARNINGS = "DOLLARID" +$ ELSE +$ CC4DISABLEWARNINGS = CCDISABLEWARNINGS + ",DOLLARID" +$ CCDISABLEWARNINGS = " /WARNING=(DISABLE=(" + CCDISABLEWARNINGS + "))" +$ ENDIF +$ CC4DISABLEWARNINGS = " /WARNING=(DISABLE=(" + CC4DISABLEWARNINGS + "))" +$ ELSE +$ CCDISABLEWARNINGS = "" +$ CC4DISABLEWARNINGS = "" +$ ENDIF +$ CC2 = CC + " /DEFINE=(" + CCDEFS + ",_POSIX_C_SOURCE)" + CCDISABLEWARNINGS +$ CC3 = CC + " /DEFINE=(" + CCDEFS + ISSEVEN + ")" + CCDISABLEWARNINGS +$ CC = CC + " /DEFINE=(" + CCDEFS + ")" + CCDISABLEWARNINGS +$ IF COMPILER .EQS. "DECC" +$ THEN +$ CC4 = CC - CCDISABLEWARNINGS + CC4DISABLEWARNINGS +$ CC5 = CC3 - CCDISABLEWARNINGS + CC4DISABLEWARNINGS +$ ELSE +$ CC4 = CC +$ CC5 = CC3 +$ ENDIF +$! +$! Show user the result +$! +$ WRITE/SYMBOL SYS$OUTPUT "Main Compiling Command: ",CC +$! +$! Else The User Entered An Invalid Argument. +$! +$ ELSE +$! +$! Tell The User We Don't Know What They Want. +$! +$ WRITE SYS$OUTPUT "" +$ WRITE SYS$OUTPUT "The Option ",P3," Is Invalid. The Valid Options Are:" +$ WRITE SYS$OUTPUT "" +$ WRITE SYS$OUTPUT " VAXC : To Compile With VAX C." +$ WRITE SYS$OUTPUT " DECC : To Compile With DEC C." +$ WRITE SYS$OUTPUT " GNUC : To Compile With GNU C." +$ WRITE SYS$OUTPUT "" +$! +$! Time To EXIT. +$! +$ EXIT +$ ENDIF +$! +$! Time to check the contents, and to make sure we get the correct library. +$! +$ IF P4.EQS."SOCKETSHR" .OR. P4.EQS."MULTINET" .OR. P4.EQS."UCX" - + .OR. P4.EQS."TCPIP" .OR. P4.EQS."NONE" +$ THEN +$! +$! Check to see if SOCKETSHR was chosen +$! +$ IF P4.EQS."SOCKETSHR" +$ THEN +$! +$! Set the library to use SOCKETSHR +$! +$ TCPIP_LIB = ",SYS$DISK:[-.VMS]SOCKETSHR_SHR.OPT /OPTIONS" +$! +$! Done with SOCKETSHR +$! +$ ENDIF +$! +$! Check to see if MULTINET was chosen +$! +$ IF P4.EQS."MULTINET" +$ THEN +$! +$! Set the library to use UCX emulation. +$! +$ P4 = "UCX" +$! +$! Done with MULTINET +$! +$ ENDIF +$! +$! Check to see if UCX was chosen +$! +$ IF P4.EQS."UCX" +$ THEN +$! +$! Set the library to use UCX. +$! +$ TCPIP_LIB = ",SYS$DISK:[-.VMS]UCX_SHR_DECC.OPT /OPTIONS" +$ IF F$TRNLNM("UCX$IPC_SHR") .NES. "" +$ THEN +$ TCPIP_LIB = ",SYS$DISK:[-.VMS]UCX_SHR_DECC_LOG.OPT /OPTIONS" +$ ELSE +$ IF COMPILER .NES. "DECC" .AND. ARCH .EQS. "VAX" THEN - + TCPIP_LIB = ",SYS$DISK:[-.VMS]UCX_SHR_VAXC.OPT /OPTIONS" +$ ENDIF +$! +$! Done with UCX +$! +$ ENDIF +$! +$! Check to see if TCPIP was chosen +$! +$ IF P4.EQS."TCPIP" +$ THEN +$! +$! Set the library to use TCPIP (post UCX). +$! +$ TCPIP_LIB = ",SYS$DISK:[-.VMS]TCPIP_SHR_DECC.OPT /OPTIONS" +$! +$! Done with TCPIP +$! +$ ENDIF +$! +$! Check to see if NONE was chosen +$! +$ IF P4.EQS."NONE" +$ THEN +$! +$! Do not use a TCPIP library. +$! +$ TCPIP_LIB = "" +$! +$! Done with NONE +$! +$ ENDIF +$! +$! Print info +$! +$ WRITE SYS$OUTPUT "TCP/IP library spec: ", TCPIP_LIB- "," +$! +$! Else The User Entered An Invalid Argument. +$! +$ ELSE +$! +$! Tell The User We Don't Know What They Want. +$! +$ WRITE SYS$OUTPUT "" +$ WRITE SYS$OUTPUT "The Option ",P4," Is Invalid. The Valid Options Are:" +$ WRITE SYS$OUTPUT "" +$ WRITE SYS$OUTPUT " SOCKETSHR : To link with SOCKETSHR TCP/IP library." +$ WRITE SYS$OUTPUT " UCX : To link with UCX TCP/IP library." +$ WRITE SYS$OUTPUT " TCPIP : To link with TCPIP (post UCX) TCP/IP library." +$ WRITE SYS$OUTPUT "" +$! +$! Time To EXIT. +$! +$ EXIT +$! +$! Done with TCP/IP libraries +$! +$ ENDIF +$! +$! Time To RETURN... +$! +$ RETURN +$! +$ INITIALISE: +$! +$! Save old value of the logical name OPENSSL +$! +$ __SAVE_OPENSSL = F$TRNLNM("OPENSSL","LNM$PROCESS_TABLE") +$! +$! Save directory information +$! +$ __HERE = F$PARSE(F$PARSE("A.;",F$ENVIRONMENT("PROCEDURE"))-"A.;","[]A.;") - "A.;" +$ __HERE = F$EDIT(__HERE,"UPCASE") +$ __TOP = __HERE - "SSL]" +$ __INCLUDE = __TOP + "INCLUDE.OPENSSL]" +$! +$! Set up the logical name OPENSSL to point at the include directory +$! +$ DEFINE OPENSSL/NOLOG '__INCLUDE' +$! +$! Done +$! +$ RETURN +$! +$ CLEANUP: +$! +$! Restore the logical name OPENSSL if it had a value +$! +$ IF __SAVE_OPENSSL .EQS. "" +$ THEN +$ DEASSIGN OPENSSL +$ ELSE +$ DEFINE/NOLOG OPENSSL '__SAVE_OPENSSL' +$ ENDIF +$! +$! Done +$! +$ RETURN diff --git a/node-v0.8.14/deps/openssl/openssl/ssl/ssl.h b/node-v0.8.14/deps/openssl/openssl/ssl/ssl.h new file mode 100644 index 0000000..fdcab6f --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/ssl/ssl.h @@ -0,0 +1,2386 @@ +/* ssl/ssl.h */ +/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com) + * All rights reserved. + * + * This package is an SSL implementation written + * by Eric Young (eay@cryptsoft.com). + * The implementation was written so as to conform with Netscapes SSL. + * + * This library is free for commercial and non-commercial use as long as + * the following conditions are aheared to. The following conditions + * apply to all code found in this distribution, be it the RC4, RSA, + * lhash, DES, etc., code; not just the SSL code. The SSL documentation + * included with this distribution is covered by the same copyright terms + * except that the holder is Tim Hudson (tjh@cryptsoft.com). + * + * Copyright remains Eric Young's, and as such any Copyright notices in + * the code are not to be removed. + * If this package is used in a product, Eric Young should be given attribution + * as the author of the parts of the library used. + * This can be in the form of a textual message at program startup or + * in documentation (online or textual) provided with the package. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * "This product includes cryptographic software written by + * Eric Young (eay@cryptsoft.com)" + * The word 'cryptographic' can be left out if the rouines from the library + * being used are not cryptographic related :-). + * 4. If you include any Windows specific code (or a derivative thereof) from + * the apps directory (application code) you must include an acknowledgement: + * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)" + * + * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * + * The licence and distribution terms for any publically available version or + * derivative of this code cannot be changed. i.e. this code cannot simply be + * copied and put under another distribution licence + * [including the GNU Public Licence.] + */ +/* ==================================================================== + * Copyright (c) 1998-2007 The OpenSSL Project. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. All advertising materials mentioning features or use of this + * software must display the following acknowledgment: + * "This product includes software developed by the OpenSSL Project + * for use in the OpenSSL Toolkit. (http://www.openssl.org/)" + * + * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to + * endorse or promote products derived from this software without + * prior written permission. For written permission, please contact + * openssl-core@openssl.org. + * + * 5. Products derived from this software may not be called "OpenSSL" + * nor may "OpenSSL" appear in their names without prior written + * permission of the OpenSSL Project. + * + * 6. Redistributions of any form whatsoever must retain the following + * acknowledgment: + * "This product includes software developed by the OpenSSL Project + * for use in the OpenSSL Toolkit (http://www.openssl.org/)" + * + * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY + * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR + * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, + * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * ==================================================================== + * + * This product includes cryptographic software written by Eric Young + * (eay@cryptsoft.com). This product includes software written by Tim + * Hudson (tjh@cryptsoft.com). + * + */ +/* ==================================================================== + * Copyright 2002 Sun Microsystems, Inc. ALL RIGHTS RESERVED. + * ECC cipher suite support in OpenSSL originally developed by + * SUN MICROSYSTEMS, INC., and contributed to the OpenSSL project. + */ +/* ==================================================================== + * Copyright 2005 Nokia. All rights reserved. + * + * The portions of the attached software ("Contribution") is developed by + * Nokia Corporation and is licensed pursuant to the OpenSSL open source + * license. + * + * The Contribution, originally written by Mika Kousa and Pasi Eronen of + * Nokia Corporation, consists of the "PSK" (Pre-Shared Key) ciphersuites + * support (see RFC 4279) to OpenSSL. + * + * No patent licenses or other rights except those expressly stated in + * the OpenSSL open source license shall be deemed granted or received + * expressly, by implication, estoppel, or otherwise. + * + * No assurances are provided by Nokia that the Contribution does not + * infringe the patent or other intellectual property rights of any third + * party or that the license provides you with all the necessary rights + * to make use of the Contribution. + * + * THE SOFTWARE IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND. IN + * ADDITION TO THE DISCLAIMERS INCLUDED IN THE LICENSE, NOKIA + * SPECIFICALLY DISCLAIMS ANY LIABILITY FOR CLAIMS BROUGHT BY YOU OR ANY + * OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL PROPERTY RIGHTS OR + * OTHERWISE. + */ + +#ifndef HEADER_SSL_H +#define HEADER_SSL_H + +#include + +#ifndef OPENSSL_NO_COMP +#include +#endif +#ifndef OPENSSL_NO_BIO +#include +#endif +#ifndef OPENSSL_NO_DEPRECATED +#ifndef OPENSSL_NO_X509 +#include +#endif +#include +#include +#include +#endif +#include +#include + +#include +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/* SSLeay version number for ASN.1 encoding of the session information */ +/* Version 0 - initial version + * Version 1 - added the optional peer certificate + */ +#define SSL_SESSION_ASN1_VERSION 0x0001 + +/* text strings for the ciphers */ +#define SSL_TXT_NULL_WITH_MD5 SSL2_TXT_NULL_WITH_MD5 +#define SSL_TXT_RC4_128_WITH_MD5 SSL2_TXT_RC4_128_WITH_MD5 +#define SSL_TXT_RC4_128_EXPORT40_WITH_MD5 SSL2_TXT_RC4_128_EXPORT40_WITH_MD5 +#define SSL_TXT_RC2_128_CBC_WITH_MD5 SSL2_TXT_RC2_128_CBC_WITH_MD5 +#define SSL_TXT_RC2_128_CBC_EXPORT40_WITH_MD5 SSL2_TXT_RC2_128_CBC_EXPORT40_WITH_MD5 +#define SSL_TXT_IDEA_128_CBC_WITH_MD5 SSL2_TXT_IDEA_128_CBC_WITH_MD5 +#define SSL_TXT_DES_64_CBC_WITH_MD5 SSL2_TXT_DES_64_CBC_WITH_MD5 +#define SSL_TXT_DES_64_CBC_WITH_SHA SSL2_TXT_DES_64_CBC_WITH_SHA +#define SSL_TXT_DES_192_EDE3_CBC_WITH_MD5 SSL2_TXT_DES_192_EDE3_CBC_WITH_MD5 +#define SSL_TXT_DES_192_EDE3_CBC_WITH_SHA SSL2_TXT_DES_192_EDE3_CBC_WITH_SHA + +/* VRS Additional Kerberos5 entries + */ +#define SSL_TXT_KRB5_DES_64_CBC_SHA SSL3_TXT_KRB5_DES_64_CBC_SHA +#define SSL_TXT_KRB5_DES_192_CBC3_SHA SSL3_TXT_KRB5_DES_192_CBC3_SHA +#define SSL_TXT_KRB5_RC4_128_SHA SSL3_TXT_KRB5_RC4_128_SHA +#define SSL_TXT_KRB5_IDEA_128_CBC_SHA SSL3_TXT_KRB5_IDEA_128_CBC_SHA +#define SSL_TXT_KRB5_DES_64_CBC_MD5 SSL3_TXT_KRB5_DES_64_CBC_MD5 +#define SSL_TXT_KRB5_DES_192_CBC3_MD5 SSL3_TXT_KRB5_DES_192_CBC3_MD5 +#define SSL_TXT_KRB5_RC4_128_MD5 SSL3_TXT_KRB5_RC4_128_MD5 +#define SSL_TXT_KRB5_IDEA_128_CBC_MD5 SSL3_TXT_KRB5_IDEA_128_CBC_MD5 + +#define SSL_TXT_KRB5_DES_40_CBC_SHA SSL3_TXT_KRB5_DES_40_CBC_SHA +#define SSL_TXT_KRB5_RC2_40_CBC_SHA SSL3_TXT_KRB5_RC2_40_CBC_SHA +#define SSL_TXT_KRB5_RC4_40_SHA SSL3_TXT_KRB5_RC4_40_SHA +#define SSL_TXT_KRB5_DES_40_CBC_MD5 SSL3_TXT_KRB5_DES_40_CBC_MD5 +#define SSL_TXT_KRB5_RC2_40_CBC_MD5 SSL3_TXT_KRB5_RC2_40_CBC_MD5 +#define SSL_TXT_KRB5_RC4_40_MD5 SSL3_TXT_KRB5_RC4_40_MD5 + +#define SSL_TXT_KRB5_DES_40_CBC_SHA SSL3_TXT_KRB5_DES_40_CBC_SHA +#define SSL_TXT_KRB5_DES_40_CBC_MD5 SSL3_TXT_KRB5_DES_40_CBC_MD5 +#define SSL_TXT_KRB5_DES_64_CBC_SHA SSL3_TXT_KRB5_DES_64_CBC_SHA +#define SSL_TXT_KRB5_DES_64_CBC_MD5 SSL3_TXT_KRB5_DES_64_CBC_MD5 +#define SSL_TXT_KRB5_DES_192_CBC3_SHA SSL3_TXT_KRB5_DES_192_CBC3_SHA +#define SSL_TXT_KRB5_DES_192_CBC3_MD5 SSL3_TXT_KRB5_DES_192_CBC3_MD5 +#define SSL_MAX_KRB5_PRINCIPAL_LENGTH 256 + +#define SSL_MAX_SSL_SESSION_ID_LENGTH 32 +#define SSL_MAX_SID_CTX_LENGTH 32 + +#define SSL_MIN_RSA_MODULUS_LENGTH_IN_BYTES (512/8) +#define SSL_MAX_KEY_ARG_LENGTH 8 +#define SSL_MAX_MASTER_KEY_LENGTH 48 + + +/* These are used to specify which ciphers to use and not to use */ + +#define SSL_TXT_EXP40 "EXPORT40" +#define SSL_TXT_EXP56 "EXPORT56" +#define SSL_TXT_LOW "LOW" +#define SSL_TXT_MEDIUM "MEDIUM" +#define SSL_TXT_HIGH "HIGH" +#define SSL_TXT_FIPS "FIPS" + +#define SSL_TXT_kFZA "kFZA" /* unused! */ +#define SSL_TXT_aFZA "aFZA" /* unused! */ +#define SSL_TXT_eFZA "eFZA" /* unused! */ +#define SSL_TXT_FZA "FZA" /* unused! */ + +#define SSL_TXT_aNULL "aNULL" +#define SSL_TXT_eNULL "eNULL" +#define SSL_TXT_NULL "NULL" + +#define SSL_TXT_kRSA "kRSA" +#define SSL_TXT_kDHr "kDHr" /* no such ciphersuites supported! */ +#define SSL_TXT_kDHd "kDHd" /* no such ciphersuites supported! */ +#define SSL_TXT_kDH "kDH" /* no such ciphersuites supported! */ +#define SSL_TXT_kEDH "kEDH" +#define SSL_TXT_kKRB5 "kKRB5" +#define SSL_TXT_kECDHr "kECDHr" +#define SSL_TXT_kECDHe "kECDHe" +#define SSL_TXT_kECDH "kECDH" +#define SSL_TXT_kEECDH "kEECDH" +#define SSL_TXT_kPSK "kPSK" +#define SSL_TXT_kGOST "kGOST" + +#define SSL_TXT_aRSA "aRSA" +#define SSL_TXT_aDSS "aDSS" +#define SSL_TXT_aDH "aDH" /* no such ciphersuites supported! */ +#define SSL_TXT_aECDH "aECDH" +#define SSL_TXT_aKRB5 "aKRB5" +#define SSL_TXT_aECDSA "aECDSA" +#define SSL_TXT_aPSK "aPSK" +#define SSL_TXT_aGOST94 "aGOST94" +#define SSL_TXT_aGOST01 "aGOST01" +#define SSL_TXT_aGOST "aGOST" + +#define SSL_TXT_DSS "DSS" +#define SSL_TXT_DH "DH" +#define SSL_TXT_EDH "EDH" /* same as "kEDH:-ADH" */ +#define SSL_TXT_ADH "ADH" +#define SSL_TXT_RSA "RSA" +#define SSL_TXT_ECDH "ECDH" +#define SSL_TXT_EECDH "EECDH" /* same as "kEECDH:-AECDH" */ +#define SSL_TXT_AECDH "AECDH" +#define SSL_TXT_ECDSA "ECDSA" +#define SSL_TXT_KRB5 "KRB5" +#define SSL_TXT_PSK "PSK" + +#define SSL_TXT_DES "DES" +#define SSL_TXT_3DES "3DES" +#define SSL_TXT_RC4 "RC4" +#define SSL_TXT_RC2 "RC2" +#define SSL_TXT_IDEA "IDEA" +#define SSL_TXT_SEED "SEED" +#define SSL_TXT_AES128 "AES128" +#define SSL_TXT_AES256 "AES256" +#define SSL_TXT_AES "AES" +#define SSL_TXT_CAMELLIA128 "CAMELLIA128" +#define SSL_TXT_CAMELLIA256 "CAMELLIA256" +#define SSL_TXT_CAMELLIA "CAMELLIA" + +#define SSL_TXT_MD5 "MD5" +#define SSL_TXT_SHA1 "SHA1" +#define SSL_TXT_SHA "SHA" /* same as "SHA1" */ +#define SSL_TXT_GOST94 "GOST94" +#define SSL_TXT_GOST89MAC "GOST89MAC" + +#define SSL_TXT_SSLV2 "SSLv2" +#define SSL_TXT_SSLV3 "SSLv3" +#define SSL_TXT_TLSV1 "TLSv1" + +#define SSL_TXT_EXP "EXP" +#define SSL_TXT_EXPORT "EXPORT" + +#define SSL_TXT_ALL "ALL" + +/* + * COMPLEMENTOF* definitions. These identifiers are used to (de-select) + * ciphers normally not being used. + * Example: "RC4" will activate all ciphers using RC4 including ciphers + * without authentication, which would normally disabled by DEFAULT (due + * the "!ADH" being part of default). Therefore "RC4:!COMPLEMENTOFDEFAULT" + * will make sure that it is also disabled in the specific selection. + * COMPLEMENTOF* identifiers are portable between version, as adjustments + * to the default cipher setup will also be included here. + * + * COMPLEMENTOFDEFAULT does not experience the same special treatment that + * DEFAULT gets, as only selection is being done and no sorting as needed + * for DEFAULT. + */ +#define SSL_TXT_CMPALL "COMPLEMENTOFALL" +#define SSL_TXT_CMPDEF "COMPLEMENTOFDEFAULT" + +/* The following cipher list is used by default. + * It also is substituted when an application-defined cipher list string + * starts with 'DEFAULT'. */ +#define SSL_DEFAULT_CIPHER_LIST "ALL:!aNULL:!eNULL:!SSLv2" +/* As of OpenSSL 1.0.0, ssl_create_cipher_list() in ssl/ssl_ciph.c always + * starts with a reasonable order, and all we have to do for DEFAULT is + * throwing out anonymous and unencrypted ciphersuites! + * (The latter are not actually enabled by ALL, but "ALL:RSA" would enable + * some of them.) + */ + +/* Used in SSL_set_shutdown()/SSL_get_shutdown(); */ +#define SSL_SENT_SHUTDOWN 1 +#define SSL_RECEIVED_SHUTDOWN 2 + +#ifdef __cplusplus +} +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +#if (defined(OPENSSL_NO_RSA) || defined(OPENSSL_NO_MD5)) && !defined(OPENSSL_NO_SSL2) +#define OPENSSL_NO_SSL2 +#endif + +#define SSL_FILETYPE_ASN1 X509_FILETYPE_ASN1 +#define SSL_FILETYPE_PEM X509_FILETYPE_PEM + +/* This is needed to stop compilers complaining about the + * 'struct ssl_st *' function parameters used to prototype callbacks + * in SSL_CTX. */ +typedef struct ssl_st *ssl_crock_st; +typedef struct tls_session_ticket_ext_st TLS_SESSION_TICKET_EXT; + +/* used to hold info on the particular ciphers used */ +typedef struct ssl_cipher_st + { + int valid; + const char *name; /* text name */ + unsigned long id; /* id, 4 bytes, first is version */ + + /* changed in 0.9.9: these four used to be portions of a single value 'algorithms' */ + unsigned long algorithm_mkey; /* key exchange algorithm */ + unsigned long algorithm_auth; /* server authentication */ + unsigned long algorithm_enc; /* symmetric encryption */ + unsigned long algorithm_mac; /* symmetric authentication */ + unsigned long algorithm_ssl; /* (major) protocol version */ + + unsigned long algo_strength; /* strength and export flags */ + unsigned long algorithm2; /* Extra flags */ + int strength_bits; /* Number of bits really used */ + int alg_bits; /* Number of bits for algorithm */ + } SSL_CIPHER; + +DECLARE_STACK_OF(SSL_CIPHER) + +typedef int (*tls_session_ticket_ext_cb_fn)(SSL *s, const unsigned char *data, int len, void *arg); +typedef int (*tls_session_secret_cb_fn)(SSL *s, void *secret, int *secret_len, STACK_OF(SSL_CIPHER) *peer_ciphers, SSL_CIPHER **cipher, void *arg); + +/* Used to hold functions for SSLv2 or SSLv3/TLSv1 functions */ +typedef struct ssl_method_st + { + int version; + int (*ssl_new)(SSL *s); + void (*ssl_clear)(SSL *s); + void (*ssl_free)(SSL *s); + int (*ssl_accept)(SSL *s); + int (*ssl_connect)(SSL *s); + int (*ssl_read)(SSL *s,void *buf,int len); + int (*ssl_peek)(SSL *s,void *buf,int len); + int (*ssl_write)(SSL *s,const void *buf,int len); + int (*ssl_shutdown)(SSL *s); + int (*ssl_renegotiate)(SSL *s); + int (*ssl_renegotiate_check)(SSL *s); + long (*ssl_get_message)(SSL *s, int st1, int stn, int mt, long + max, int *ok); + int (*ssl_read_bytes)(SSL *s, int type, unsigned char *buf, int len, + int peek); + int (*ssl_write_bytes)(SSL *s, int type, const void *buf_, int len); + int (*ssl_dispatch_alert)(SSL *s); + long (*ssl_ctrl)(SSL *s,int cmd,long larg,void *parg); + long (*ssl_ctx_ctrl)(SSL_CTX *ctx,int cmd,long larg,void *parg); + const SSL_CIPHER *(*get_cipher_by_char)(const unsigned char *ptr); + int (*put_cipher_by_char)(const SSL_CIPHER *cipher,unsigned char *ptr); + int (*ssl_pending)(const SSL *s); + int (*num_ciphers)(void); + const SSL_CIPHER *(*get_cipher)(unsigned ncipher); + const struct ssl_method_st *(*get_ssl_method)(int version); + long (*get_timeout)(void); + struct ssl3_enc_method *ssl3_enc; /* Extra SSLv3/TLS stuff */ + int (*ssl_version)(void); + long (*ssl_callback_ctrl)(SSL *s, int cb_id, void (*fp)(void)); + long (*ssl_ctx_callback_ctrl)(SSL_CTX *s, int cb_id, void (*fp)(void)); + } SSL_METHOD; + +/* Lets make this into an ASN.1 type structure as follows + * SSL_SESSION_ID ::= SEQUENCE { + * version INTEGER, -- structure version number + * SSLversion INTEGER, -- SSL version number + * Cipher OCTET STRING, -- the 3 byte cipher ID + * Session_ID OCTET STRING, -- the Session ID + * Master_key OCTET STRING, -- the master key + * KRB5_principal OCTET STRING -- optional Kerberos principal + * Key_Arg [ 0 ] IMPLICIT OCTET STRING, -- the optional Key argument + * Time [ 1 ] EXPLICIT INTEGER, -- optional Start Time + * Timeout [ 2 ] EXPLICIT INTEGER, -- optional Timeout ins seconds + * Peer [ 3 ] EXPLICIT X509, -- optional Peer Certificate + * Session_ID_context [ 4 ] EXPLICIT OCTET STRING, -- the Session ID context + * Verify_result [ 5 ] EXPLICIT INTEGER, -- X509_V_... code for `Peer' + * HostName [ 6 ] EXPLICIT OCTET STRING, -- optional HostName from servername TLS extension + * ECPointFormatList [ 7 ] OCTET STRING, -- optional EC point format list from TLS extension + * PSK_identity_hint [ 8 ] EXPLICIT OCTET STRING, -- optional PSK identity hint + * PSK_identity [ 9 ] EXPLICIT OCTET STRING -- optional PSK identity + * } + * Look in ssl/ssl_asn1.c for more details + * I'm using EXPLICIT tags so I can read the damn things using asn1parse :-). + */ +typedef struct ssl_session_st + { + int ssl_version; /* what ssl version session info is + * being kept in here? */ + + /* only really used in SSLv2 */ + unsigned int key_arg_length; + unsigned char key_arg[SSL_MAX_KEY_ARG_LENGTH]; + int master_key_length; + unsigned char master_key[SSL_MAX_MASTER_KEY_LENGTH]; + /* session_id - valid? */ + unsigned int session_id_length; + unsigned char session_id[SSL_MAX_SSL_SESSION_ID_LENGTH]; + /* this is used to determine whether the session is being reused in + * the appropriate context. It is up to the application to set this, + * via SSL_new */ + unsigned int sid_ctx_length; + unsigned char sid_ctx[SSL_MAX_SID_CTX_LENGTH]; + +#ifndef OPENSSL_NO_KRB5 + unsigned int krb5_client_princ_len; + unsigned char krb5_client_princ[SSL_MAX_KRB5_PRINCIPAL_LENGTH]; +#endif /* OPENSSL_NO_KRB5 */ +#ifndef OPENSSL_NO_PSK + char *psk_identity_hint; + char *psk_identity; +#endif + int not_resumable; + + /* The cert is the certificate used to establish this connection */ + struct sess_cert_st /* SESS_CERT */ *sess_cert; + + /* This is the cert for the other end. + * On clients, it will be the same as sess_cert->peer_key->x509 + * (the latter is not enough as sess_cert is not retained + * in the external representation of sessions, see ssl_asn1.c). */ + X509 *peer; + /* when app_verify_callback accepts a session where the peer's certificate + * is not ok, we must remember the error for session reuse: */ + long verify_result; /* only for servers */ + + int references; + long timeout; + long time; + + unsigned int compress_meth; /* Need to lookup the method */ + + const SSL_CIPHER *cipher; + unsigned long cipher_id; /* when ASN.1 loaded, this + * needs to be used to load + * the 'cipher' structure */ + + STACK_OF(SSL_CIPHER) *ciphers; /* shared ciphers? */ + + CRYPTO_EX_DATA ex_data; /* application specific data */ + + /* These are used to make removal of session-ids more + * efficient and to implement a maximum cache size. */ + struct ssl_session_st *prev,*next; +#ifndef OPENSSL_NO_TLSEXT + char *tlsext_hostname; +#ifndef OPENSSL_NO_EC + size_t tlsext_ecpointformatlist_length; + unsigned char *tlsext_ecpointformatlist; /* peer's list */ + size_t tlsext_ellipticcurvelist_length; + unsigned char *tlsext_ellipticcurvelist; /* peer's list */ +#endif /* OPENSSL_NO_EC */ + /* RFC4507 info */ + unsigned char *tlsext_tick; /* Session ticket */ + size_t tlsext_ticklen; /* Session ticket length */ + long tlsext_tick_lifetime_hint; /* Session lifetime hint in seconds */ +#endif + } SSL_SESSION; + + +#define SSL_OP_MICROSOFT_SESS_ID_BUG 0x00000001L +#define SSL_OP_NETSCAPE_CHALLENGE_BUG 0x00000002L +/* Allow initial connection to servers that don't support RI */ +#define SSL_OP_LEGACY_SERVER_CONNECT 0x00000004L +#define SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG 0x00000008L +#define SSL_OP_SSLREF2_REUSE_CERT_TYPE_BUG 0x00000010L +#define SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER 0x00000020L +#define SSL_OP_MSIE_SSLV2_RSA_PADDING 0x00000040L /* no effect since 0.9.7h and 0.9.8b */ +#define SSL_OP_SSLEAY_080_CLIENT_DH_BUG 0x00000080L +#define SSL_OP_TLS_D5_BUG 0x00000100L +#define SSL_OP_TLS_BLOCK_PADDING_BUG 0x00000200L + +/* Disable SSL 3.0/TLS 1.0 CBC vulnerability workaround that was added + * in OpenSSL 0.9.6d. Usually (depending on the application protocol) + * the workaround is not needed. Unfortunately some broken SSL/TLS + * implementations cannot handle it at all, which is why we include + * it in SSL_OP_ALL. */ +#define SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS 0x00000800L /* added in 0.9.6e */ + +/* SSL_OP_ALL: various bug workarounds that should be rather harmless. + * This used to be 0x000FFFFFL before 0.9.7. */ +#define SSL_OP_ALL 0x80000FFFL + +/* DTLS options */ +#define SSL_OP_NO_QUERY_MTU 0x00001000L +/* Turn on Cookie Exchange (on relevant for servers) */ +#define SSL_OP_COOKIE_EXCHANGE 0x00002000L +/* Don't use RFC4507 ticket extension */ +#define SSL_OP_NO_TICKET 0x00004000L +/* Use Cisco's "speshul" version of DTLS_BAD_VER (as client) */ +#define SSL_OP_CISCO_ANYCONNECT 0x00008000L + +/* As server, disallow session resumption on renegotiation */ +#define SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION 0x00010000L +/* Don't use compression even if supported */ +#define SSL_OP_NO_COMPRESSION 0x00020000L +/* Permit unsafe legacy renegotiation */ +#define SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION 0x00040000L +/* If set, always create a new key when using tmp_ecdh parameters */ +#define SSL_OP_SINGLE_ECDH_USE 0x00080000L +/* If set, always create a new key when using tmp_dh parameters */ +#define SSL_OP_SINGLE_DH_USE 0x00100000L +/* Set to always use the tmp_rsa key when doing RSA operations, + * even when this violates protocol specs */ +#define SSL_OP_EPHEMERAL_RSA 0x00200000L +/* Set on servers to choose the cipher according to the server's + * preferences */ +#define SSL_OP_CIPHER_SERVER_PREFERENCE 0x00400000L +/* If set, a server will allow a client to issue a SSLv3.0 version number + * as latest version supported in the premaster secret, even when TLSv1.0 + * (version 3.1) was announced in the client hello. Normally this is + * forbidden to prevent version rollback attacks. */ +#define SSL_OP_TLS_ROLLBACK_BUG 0x00800000L + +#define SSL_OP_NO_SSLv2 0x01000000L +#define SSL_OP_NO_SSLv3 0x02000000L +#define SSL_OP_NO_TLSv1 0x04000000L + +/* The next flag deliberately changes the ciphertest, this is a check + * for the PKCS#1 attack */ +#define SSL_OP_PKCS1_CHECK_1 0x08000000L +#define SSL_OP_PKCS1_CHECK_2 0x10000000L +#define SSL_OP_NETSCAPE_CA_DN_BUG 0x20000000L +#define SSL_OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG 0x40000000L +/* Make server add server-hello extension from early version of + * cryptopro draft, when GOST ciphersuite is negotiated. + * Required for interoperability with CryptoPro CSP 3.x + */ +#define SSL_OP_CRYPTOPRO_TLSEXT_BUG 0x80000000L + +/* Allow SSL_write(..., n) to return r with 0 < r < n (i.e. report success + * when just a single record has been written): */ +#define SSL_MODE_ENABLE_PARTIAL_WRITE 0x00000001L +/* Make it possible to retry SSL_write() with changed buffer location + * (buffer contents must stay the same!); this is not the default to avoid + * the misconception that non-blocking SSL_write() behaves like + * non-blocking write(): */ +#define SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER 0x00000002L +/* Never bother the application with retries if the transport + * is blocking: */ +#define SSL_MODE_AUTO_RETRY 0x00000004L +/* Don't attempt to automatically build certificate chain */ +#define SSL_MODE_NO_AUTO_CHAIN 0x00000008L +/* Save RAM by releasing read and write buffers when they're empty. (SSL3 and + * TLS only.) "Released" buffers are put onto a free-list in the context + * or just freed (depending on the context's setting for freelist_max_len). */ +#define SSL_MODE_RELEASE_BUFFERS 0x00000010L +/* Use small read and write buffers: (a) lazy allocate read buffers for + * large incoming records, and (b) limit the size of outgoing records. */ +#define SSL_MODE_SMALL_BUFFERS 0x00000020L +/* When set, clients may send application data before receipt of CCS + * and Finished. This mode enables full-handshakes to 'complete' in + * one RTT. */ +#define SSL_MODE_HANDSHAKE_CUTTHROUGH 0x00000040L + +/* Note: SSL[_CTX]_set_{options,mode} use |= op on the previous value, + * they cannot be used to clear bits. */ + +#define SSL_CTX_set_options(ctx,op) \ + SSL_CTX_ctrl((ctx),SSL_CTRL_OPTIONS,(op),NULL) +#define SSL_CTX_clear_options(ctx,op) \ + SSL_CTX_ctrl((ctx),SSL_CTRL_CLEAR_OPTIONS,(op),NULL) +#define SSL_CTX_get_options(ctx) \ + SSL_CTX_ctrl((ctx),SSL_CTRL_OPTIONS,0,NULL) +#define SSL_set_options(ssl,op) \ + SSL_ctrl((ssl),SSL_CTRL_OPTIONS,(op),NULL) +#define SSL_clear_options(ssl,op) \ + SSL_ctrl((ssl),SSL_CTRL_CLEAR_OPTIONS,(op),NULL) +#define SSL_get_options(ssl) \ + SSL_ctrl((ssl),SSL_CTRL_OPTIONS,0,NULL) + +#define SSL_CTX_set_mode(ctx,op) \ + SSL_CTX_ctrl((ctx),SSL_CTRL_MODE,(op),NULL) +#define SSL_CTX_clear_mode(ctx,op) \ + SSL_CTX_ctrl((ctx),SSL_CTRL_CLEAR_MODE,(op),NULL) +#define SSL_CTX_get_mode(ctx) \ + SSL_CTX_ctrl((ctx),SSL_CTRL_MODE,0,NULL) +#define SSL_clear_mode(ssl,op) \ + SSL_ctrl((ssl),SSL_CTRL_CLEAR_MODE,(op),NULL) +#define SSL_set_mode(ssl,op) \ + SSL_ctrl((ssl),SSL_CTRL_MODE,(op),NULL) +#define SSL_get_mode(ssl) \ + SSL_ctrl((ssl),SSL_CTRL_MODE,0,NULL) +#define SSL_set_mtu(ssl, mtu) \ + SSL_ctrl((ssl),SSL_CTRL_SET_MTU,(mtu),NULL) + +#define SSL_get_secure_renegotiation_support(ssl) \ + SSL_ctrl((ssl), SSL_CTRL_GET_RI_SUPPORT, 0, NULL) + +void SSL_CTX_set_msg_callback(SSL_CTX *ctx, void (*cb)(int write_p, int version, int content_type, const void *buf, size_t len, SSL *ssl, void *arg)); +void SSL_set_msg_callback(SSL *ssl, void (*cb)(int write_p, int version, int content_type, const void *buf, size_t len, SSL *ssl, void *arg)); +#define SSL_CTX_set_msg_callback_arg(ctx, arg) SSL_CTX_ctrl((ctx), SSL_CTRL_SET_MSG_CALLBACK_ARG, 0, (arg)) +#define SSL_set_msg_callback_arg(ssl, arg) SSL_ctrl((ssl), SSL_CTRL_SET_MSG_CALLBACK_ARG, 0, (arg)) + + + +#if defined(OPENSSL_SYS_MSDOS) && !defined(OPENSSL_SYS_WIN32) +#define SSL_MAX_CERT_LIST_DEFAULT 1024*30 /* 30k max cert list :-) */ +#else +#define SSL_MAX_CERT_LIST_DEFAULT 1024*100 /* 100k max cert list :-) */ +#endif + +#define SSL_SESSION_CACHE_MAX_SIZE_DEFAULT (1024*20) + +/* This callback type is used inside SSL_CTX, SSL, and in the functions that set + * them. It is used to override the generation of SSL/TLS session IDs in a + * server. Return value should be zero on an error, non-zero to proceed. Also, + * callbacks should themselves check if the id they generate is unique otherwise + * the SSL handshake will fail with an error - callbacks can do this using the + * 'ssl' value they're passed by; + * SSL_has_matching_session_id(ssl, id, *id_len) + * The length value passed in is set at the maximum size the session ID can be. + * In SSLv2 this is 16 bytes, whereas SSLv3/TLSv1 it is 32 bytes. The callback + * can alter this length to be less if desired, but under SSLv2 session IDs are + * supposed to be fixed at 16 bytes so the id will be padded after the callback + * returns in this case. It is also an error for the callback to set the size to + * zero. */ +typedef int (*GEN_SESSION_CB)(const SSL *ssl, unsigned char *id, + unsigned int *id_len); + +typedef struct ssl_comp_st + { + int id; + const char *name; +#ifndef OPENSSL_NO_COMP + COMP_METHOD *method; +#else + char *method; +#endif + } SSL_COMP; + +DECLARE_STACK_OF(SSL_COMP) +DECLARE_LHASH_OF(SSL_SESSION); + +struct ssl_ctx_st + { + const SSL_METHOD *method; + + STACK_OF(SSL_CIPHER) *cipher_list; + /* same as above but sorted for lookup */ + STACK_OF(SSL_CIPHER) *cipher_list_by_id; + + struct x509_store_st /* X509_STORE */ *cert_store; + LHASH_OF(SSL_SESSION) *sessions; + /* Most session-ids that will be cached, default is + * SSL_SESSION_CACHE_MAX_SIZE_DEFAULT. 0 is unlimited. */ + unsigned long session_cache_size; + struct ssl_session_st *session_cache_head; + struct ssl_session_st *session_cache_tail; + + /* This can have one of 2 values, ored together, + * SSL_SESS_CACHE_CLIENT, + * SSL_SESS_CACHE_SERVER, + * Default is SSL_SESSION_CACHE_SERVER, which means only + * SSL_accept which cache SSL_SESSIONS. */ + int session_cache_mode; + + /* If timeout is not 0, it is the default timeout value set + * when SSL_new() is called. This has been put in to make + * life easier to set things up */ + long session_timeout; + + /* If this callback is not null, it will be called each + * time a session id is added to the cache. If this function + * returns 1, it means that the callback will do a + * SSL_SESSION_free() when it has finished using it. Otherwise, + * on 0, it means the callback has finished with it. + * If remove_session_cb is not null, it will be called when + * a session-id is removed from the cache. After the call, + * OpenSSL will SSL_SESSION_free() it. */ + int (*new_session_cb)(struct ssl_st *ssl,SSL_SESSION *sess); + void (*remove_session_cb)(struct ssl_ctx_st *ctx,SSL_SESSION *sess); + SSL_SESSION *(*get_session_cb)(struct ssl_st *ssl, + unsigned char *data,int len,int *copy); + + struct + { + int sess_connect; /* SSL new conn - started */ + int sess_connect_renegotiate;/* SSL reneg - requested */ + int sess_connect_good; /* SSL new conne/reneg - finished */ + int sess_accept; /* SSL new accept - started */ + int sess_accept_renegotiate;/* SSL reneg - requested */ + int sess_accept_good; /* SSL accept/reneg - finished */ + int sess_miss; /* session lookup misses */ + int sess_timeout; /* reuse attempt on timeouted session */ + int sess_cache_full; /* session removed due to full cache */ + int sess_hit; /* session reuse actually done */ + int sess_cb_hit; /* session-id that was not + * in the cache was + * passed back via the callback. This + * indicates that the application is + * supplying session-id's from other + * processes - spooky :-) */ + } stats; + + int references; + + /* if defined, these override the X509_verify_cert() calls */ + int (*app_verify_callback)(X509_STORE_CTX *, void *); + void *app_verify_arg; + /* before OpenSSL 0.9.7, 'app_verify_arg' was ignored + * ('app_verify_callback' was called with just one argument) */ + + /* Default password callback. */ + pem_password_cb *default_passwd_callback; + + /* Default password callback user data. */ + void *default_passwd_callback_userdata; + + /* get client cert callback */ + int (*client_cert_cb)(SSL *ssl, X509 **x509, EVP_PKEY **pkey); + + /* cookie generate callback */ + int (*app_gen_cookie_cb)(SSL *ssl, unsigned char *cookie, + unsigned int *cookie_len); + + /* verify cookie callback */ + int (*app_verify_cookie_cb)(SSL *ssl, unsigned char *cookie, + unsigned int cookie_len); + + CRYPTO_EX_DATA ex_data; + + const EVP_MD *rsa_md5;/* For SSLv2 - name is 'ssl2-md5' */ + const EVP_MD *md5; /* For SSLv3/TLSv1 'ssl3-md5' */ + const EVP_MD *sha1; /* For SSLv3/TLSv1 'ssl3->sha1' */ + + STACK_OF(X509) *extra_certs; + STACK_OF(SSL_COMP) *comp_methods; /* stack of SSL_COMP, SSLv3/TLSv1 */ + + + /* Default values used when no per-SSL value is defined follow */ + + void (*info_callback)(const SSL *ssl,int type,int val); /* used if SSL's info_callback is NULL */ + + /* what we put in client cert requests */ + STACK_OF(X509_NAME) *client_CA; + + + /* Default values to use in SSL structures follow (these are copied by SSL_new) */ + + unsigned long options; + unsigned long mode; + long max_cert_list; + + struct cert_st /* CERT */ *cert; + int read_ahead; + + /* callback that allows applications to peek at protocol messages */ + void (*msg_callback)(int write_p, int version, int content_type, const void *buf, size_t len, SSL *ssl, void *arg); + void *msg_callback_arg; + + int verify_mode; + unsigned int sid_ctx_length; + unsigned char sid_ctx[SSL_MAX_SID_CTX_LENGTH]; + int (*default_verify_callback)(int ok,X509_STORE_CTX *ctx); /* called 'verify_callback' in the SSL */ + + /* Default generate session ID callback. */ + GEN_SESSION_CB generate_session_id; + + X509_VERIFY_PARAM *param; + +#if 0 + int purpose; /* Purpose setting */ + int trust; /* Trust setting */ +#endif + + int quiet_shutdown; + + /* Maximum amount of data to send in one fragment. + * actual record size can be more than this due to + * padding and MAC overheads. + */ + unsigned int max_send_fragment; + +#ifndef OPENSSL_ENGINE + /* Engine to pass requests for client certs to + */ + ENGINE *client_cert_engine; +#endif + +#ifndef OPENSSL_NO_TLSEXT + /* TLS extensions servername callback */ + int (*tlsext_servername_callback)(SSL*, int *, void *); + void *tlsext_servername_arg; + /* RFC 4507 session ticket keys */ + unsigned char tlsext_tick_key_name[16]; + unsigned char tlsext_tick_hmac_key[16]; + unsigned char tlsext_tick_aes_key[16]; + /* Callback to support customisation of ticket key setting */ + int (*tlsext_ticket_key_cb)(SSL *ssl, + unsigned char *name, unsigned char *iv, + EVP_CIPHER_CTX *ectx, + HMAC_CTX *hctx, int enc); + + /* certificate status request info */ + /* Callback for status request */ + int (*tlsext_status_cb)(SSL *ssl, void *arg); + void *tlsext_status_arg; + + /* draft-rescorla-tls-opaque-prf-input-00.txt information */ + int (*tlsext_opaque_prf_input_callback)(SSL *, void *peerinput, size_t len, void *arg); + void *tlsext_opaque_prf_input_callback_arg; + +# ifndef OPENSSL_NO_NEXTPROTONEG + /* Next protocol negotiation information */ + /* (for experimental NPN extension). */ + + /* For a server, this contains a callback function by which the set of + * advertised protocols can be provided. */ + int (*next_protos_advertised_cb)(SSL *s, const unsigned char **buf, + unsigned int *len, void *arg); + void *next_protos_advertised_cb_arg; + /* For a client, this contains a callback function that selects the + * next protocol from the list provided by the server. */ + int (*next_proto_select_cb)(SSL *s, unsigned char **out, + unsigned char *outlen, + const unsigned char *in, + unsigned int inlen, + void *arg); + void *next_proto_select_cb_arg; +# endif +#endif + +#ifndef OPENSSL_NO_PSK + char *psk_identity_hint; + unsigned int (*psk_client_callback)(SSL *ssl, const char *hint, char *identity, + unsigned int max_identity_len, unsigned char *psk, + unsigned int max_psk_len); + unsigned int (*psk_server_callback)(SSL *ssl, const char *identity, + unsigned char *psk, unsigned int max_psk_len); +#endif + +#ifndef OPENSSL_NO_BUF_FREELISTS +#define SSL_MAX_BUF_FREELIST_LEN_DEFAULT 32 + unsigned int freelist_max_len; + struct ssl3_buf_freelist_st *wbuf_freelist; + struct ssl3_buf_freelist_st *rbuf_freelist; +#endif + }; + +#define SSL_SESS_CACHE_OFF 0x0000 +#define SSL_SESS_CACHE_CLIENT 0x0001 +#define SSL_SESS_CACHE_SERVER 0x0002 +#define SSL_SESS_CACHE_BOTH (SSL_SESS_CACHE_CLIENT|SSL_SESS_CACHE_SERVER) +#define SSL_SESS_CACHE_NO_AUTO_CLEAR 0x0080 +/* enough comments already ... see SSL_CTX_set_session_cache_mode(3) */ +#define SSL_SESS_CACHE_NO_INTERNAL_LOOKUP 0x0100 +#define SSL_SESS_CACHE_NO_INTERNAL_STORE 0x0200 +#define SSL_SESS_CACHE_NO_INTERNAL \ + (SSL_SESS_CACHE_NO_INTERNAL_LOOKUP|SSL_SESS_CACHE_NO_INTERNAL_STORE) + +LHASH_OF(SSL_SESSION) *SSL_CTX_sessions(SSL_CTX *ctx); +#define SSL_CTX_sess_number(ctx) \ + SSL_CTX_ctrl(ctx,SSL_CTRL_SESS_NUMBER,0,NULL) +#define SSL_CTX_sess_connect(ctx) \ + SSL_CTX_ctrl(ctx,SSL_CTRL_SESS_CONNECT,0,NULL) +#define SSL_CTX_sess_connect_good(ctx) \ + SSL_CTX_ctrl(ctx,SSL_CTRL_SESS_CONNECT_GOOD,0,NULL) +#define SSL_CTX_sess_connect_renegotiate(ctx) \ + SSL_CTX_ctrl(ctx,SSL_CTRL_SESS_CONNECT_RENEGOTIATE,0,NULL) +#define SSL_CTX_sess_accept(ctx) \ + SSL_CTX_ctrl(ctx,SSL_CTRL_SESS_ACCEPT,0,NULL) +#define SSL_CTX_sess_accept_renegotiate(ctx) \ + SSL_CTX_ctrl(ctx,SSL_CTRL_SESS_ACCEPT_RENEGOTIATE,0,NULL) +#define SSL_CTX_sess_accept_good(ctx) \ + SSL_CTX_ctrl(ctx,SSL_CTRL_SESS_ACCEPT_GOOD,0,NULL) +#define SSL_CTX_sess_hits(ctx) \ + SSL_CTX_ctrl(ctx,SSL_CTRL_SESS_HIT,0,NULL) +#define SSL_CTX_sess_cb_hits(ctx) \ + SSL_CTX_ctrl(ctx,SSL_CTRL_SESS_CB_HIT,0,NULL) +#define SSL_CTX_sess_misses(ctx) \ + SSL_CTX_ctrl(ctx,SSL_CTRL_SESS_MISSES,0,NULL) +#define SSL_CTX_sess_timeouts(ctx) \ + SSL_CTX_ctrl(ctx,SSL_CTRL_SESS_TIMEOUTS,0,NULL) +#define SSL_CTX_sess_cache_full(ctx) \ + SSL_CTX_ctrl(ctx,SSL_CTRL_SESS_CACHE_FULL,0,NULL) + +void SSL_CTX_sess_set_new_cb(SSL_CTX *ctx, int (*new_session_cb)(struct ssl_st *ssl,SSL_SESSION *sess)); +int (*SSL_CTX_sess_get_new_cb(SSL_CTX *ctx))(struct ssl_st *ssl, SSL_SESSION *sess); +void SSL_CTX_sess_set_remove_cb(SSL_CTX *ctx, void (*remove_session_cb)(struct ssl_ctx_st *ctx,SSL_SESSION *sess)); +void (*SSL_CTX_sess_get_remove_cb(SSL_CTX *ctx))(struct ssl_ctx_st *ctx, SSL_SESSION *sess); +void SSL_CTX_sess_set_get_cb(SSL_CTX *ctx, SSL_SESSION *(*get_session_cb)(struct ssl_st *ssl, unsigned char *data,int len,int *copy)); +SSL_SESSION *(*SSL_CTX_sess_get_get_cb(SSL_CTX *ctx))(struct ssl_st *ssl, unsigned char *Data, int len, int *copy); +void SSL_CTX_set_info_callback(SSL_CTX *ctx, void (*cb)(const SSL *ssl,int type,int val)); +void (*SSL_CTX_get_info_callback(SSL_CTX *ctx))(const SSL *ssl,int type,int val); +void SSL_CTX_set_client_cert_cb(SSL_CTX *ctx, int (*client_cert_cb)(SSL *ssl, X509 **x509, EVP_PKEY **pkey)); +int (*SSL_CTX_get_client_cert_cb(SSL_CTX *ctx))(SSL *ssl, X509 **x509, EVP_PKEY **pkey); +#ifndef OPENSSL_NO_ENGINE +int SSL_CTX_set_client_cert_engine(SSL_CTX *ctx, ENGINE *e); +#endif +void SSL_CTX_set_cookie_generate_cb(SSL_CTX *ctx, int (*app_gen_cookie_cb)(SSL *ssl, unsigned char *cookie, unsigned int *cookie_len)); +void SSL_CTX_set_cookie_verify_cb(SSL_CTX *ctx, int (*app_verify_cookie_cb)(SSL *ssl, unsigned char *cookie, unsigned int cookie_len)); +#ifndef OPENSSL_NO_NEXTPROTONEG +void SSL_CTX_set_next_protos_advertised_cb(SSL_CTX *s, + int (*cb) (SSL *ssl, + const unsigned char **out, + unsigned int *outlen, + void *arg), void *arg); +void SSL_CTX_set_next_proto_select_cb(SSL_CTX *s, + int (*cb) (SSL *ssl, unsigned char **out, + unsigned char *outlen, + const unsigned char *in, + unsigned int inlen, void *arg), + void *arg); + +int SSL_select_next_proto(unsigned char **out, unsigned char *outlen, + const unsigned char *in, unsigned int inlen, + const unsigned char *client, unsigned int client_len); +void SSL_get0_next_proto_negotiated(const SSL *s, const unsigned char **data, + unsigned *len); + +#define OPENSSL_NPN_UNSUPPORTED 0 +#define OPENSSL_NPN_NEGOTIATED 1 +#define OPENSSL_NPN_NO_OVERLAP 2 + +#endif + +#ifndef OPENSSL_NO_PSK +/* the maximum length of the buffer given to callbacks containing the + * resulting identity/psk */ +#define PSK_MAX_IDENTITY_LEN 128 +#define PSK_MAX_PSK_LEN 256 +void SSL_CTX_set_psk_client_callback(SSL_CTX *ctx, + unsigned int (*psk_client_callback)(SSL *ssl, const char *hint, + char *identity, unsigned int max_identity_len, unsigned char *psk, + unsigned int max_psk_len)); +void SSL_set_psk_client_callback(SSL *ssl, + unsigned int (*psk_client_callback)(SSL *ssl, const char *hint, + char *identity, unsigned int max_identity_len, unsigned char *psk, + unsigned int max_psk_len)); +void SSL_CTX_set_psk_server_callback(SSL_CTX *ctx, + unsigned int (*psk_server_callback)(SSL *ssl, const char *identity, + unsigned char *psk, unsigned int max_psk_len)); +void SSL_set_psk_server_callback(SSL *ssl, + unsigned int (*psk_server_callback)(SSL *ssl, const char *identity, + unsigned char *psk, unsigned int max_psk_len)); +int SSL_CTX_use_psk_identity_hint(SSL_CTX *ctx, const char *identity_hint); +int SSL_use_psk_identity_hint(SSL *s, const char *identity_hint); +const char *SSL_get_psk_identity_hint(const SSL *s); +const char *SSL_get_psk_identity(const SSL *s); +#endif + +#define SSL_NOTHING 1 +#define SSL_WRITING 2 +#define SSL_READING 3 +#define SSL_X509_LOOKUP 4 + +/* These will only be used when doing non-blocking IO */ +#define SSL_want_nothing(s) (SSL_want(s) == SSL_NOTHING) +#define SSL_want_read(s) (SSL_want(s) == SSL_READING) +#define SSL_want_write(s) (SSL_want(s) == SSL_WRITING) +#define SSL_want_x509_lookup(s) (SSL_want(s) == SSL_X509_LOOKUP) + +#define SSL_MAC_FLAG_READ_MAC_STREAM 1 +#define SSL_MAC_FLAG_WRITE_MAC_STREAM 2 + +struct ssl_st + { + /* protocol version + * (one of SSL2_VERSION, SSL3_VERSION, TLS1_VERSION, DTLS1_VERSION) + */ + int version; + int type; /* SSL_ST_CONNECT or SSL_ST_ACCEPT */ + + const SSL_METHOD *method; /* SSLv3 */ + + /* There are 2 BIO's even though they are normally both the + * same. This is so data can be read and written to different + * handlers */ + +#ifndef OPENSSL_NO_BIO + BIO *rbio; /* used by SSL_read */ + BIO *wbio; /* used by SSL_write */ + BIO *bbio; /* used during session-id reuse to concatenate + * messages */ +#else + char *rbio; /* used by SSL_read */ + char *wbio; /* used by SSL_write */ + char *bbio; +#endif + /* This holds a variable that indicates what we were doing + * when a 0 or -1 is returned. This is needed for + * non-blocking IO so we know what request needs re-doing when + * in SSL_accept or SSL_connect */ + int rwstate; + + /* true when we are actually in SSL_accept() or SSL_connect() */ + int in_handshake; + int (*handshake_func)(SSL *); + + /* Imagine that here's a boolean member "init" that is + * switched as soon as SSL_set_{accept/connect}_state + * is called for the first time, so that "state" and + * "handshake_func" are properly initialized. But as + * handshake_func is == 0 until then, we use this + * test instead of an "init" member. + */ + + int server; /* are we the server side? - mostly used by SSL_clear*/ + + int new_session;/* 1 if we are to use a new session. + * 2 if we are a server and are inside a handshake + * (i.e. not just sending a HelloRequest) + * NB: For servers, the 'new' session may actually be a previously + * cached session or even the previous session unless + * SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION is set */ + int quiet_shutdown;/* don't send shutdown packets */ + int shutdown; /* we have shut things down, 0x01 sent, 0x02 + * for received */ + int state; /* where we are */ + int rstate; /* where we are when reading */ + + BUF_MEM *init_buf; /* buffer used during init */ + void *init_msg; /* pointer to handshake message body, set by ssl3_get_message() */ + int init_num; /* amount read/written */ + int init_off; /* amount read/written */ + + /* used internally to point at a raw packet */ + unsigned char *packet; + unsigned int packet_length; + + struct ssl2_state_st *s2; /* SSLv2 variables */ + struct ssl3_state_st *s3; /* SSLv3 variables */ + struct dtls1_state_st *d1; /* DTLSv1 variables */ + + int read_ahead; /* Read as many input bytes as possible + * (for non-blocking reads) */ + + /* callback that allows applications to peek at protocol messages */ + void (*msg_callback)(int write_p, int version, int content_type, const void *buf, size_t len, SSL *ssl, void *arg); + void *msg_callback_arg; + + int hit; /* reusing a previous session */ + + X509_VERIFY_PARAM *param; + +#if 0 + int purpose; /* Purpose setting */ + int trust; /* Trust setting */ +#endif + + /* crypto */ + STACK_OF(SSL_CIPHER) *cipher_list; + STACK_OF(SSL_CIPHER) *cipher_list_by_id; + + /* These are the ones being used, the ones in SSL_SESSION are + * the ones to be 'copied' into these ones */ + int mac_flags; + EVP_CIPHER_CTX *enc_read_ctx; /* cryptographic state */ + EVP_MD_CTX *read_hash; /* used for mac generation */ +#ifndef OPENSSL_NO_COMP + COMP_CTX *expand; /* uncompress */ +#else + char *expand; +#endif + + EVP_CIPHER_CTX *enc_write_ctx; /* cryptographic state */ + EVP_MD_CTX *write_hash; /* used for mac generation */ +#ifndef OPENSSL_NO_COMP + COMP_CTX *compress; /* compression */ +#else + char *compress; +#endif + + /* session info */ + + /* client cert? */ + /* This is used to hold the server certificate used */ + struct cert_st /* CERT */ *cert; + + /* the session_id_context is used to ensure sessions are only reused + * in the appropriate context */ + unsigned int sid_ctx_length; + unsigned char sid_ctx[SSL_MAX_SID_CTX_LENGTH]; + + /* This can also be in the session once a session is established */ + SSL_SESSION *session; + + /* This can be disabled to prevent the use of uncached sessions */ + int session_creation_enabled; + + /* Default generate session ID callback. */ + GEN_SESSION_CB generate_session_id; + + /* Used in SSL2 and SSL3 */ + int verify_mode; /* 0 don't care about verify failure. + * 1 fail if verify fails */ + int (*verify_callback)(int ok,X509_STORE_CTX *ctx); /* fail if callback returns 0 */ + + void (*info_callback)(const SSL *ssl,int type,int val); /* optional informational callback */ + + int error; /* error bytes to be written */ + int error_code; /* actual code */ + +#ifndef OPENSSL_NO_KRB5 + KSSL_CTX *kssl_ctx; /* Kerberos 5 context */ +#endif /* OPENSSL_NO_KRB5 */ + +#ifndef OPENSSL_NO_PSK + unsigned int (*psk_client_callback)(SSL *ssl, const char *hint, char *identity, + unsigned int max_identity_len, unsigned char *psk, + unsigned int max_psk_len); + unsigned int (*psk_server_callback)(SSL *ssl, const char *identity, + unsigned char *psk, unsigned int max_psk_len); +#endif + + SSL_CTX *ctx; + /* set this flag to 1 and a sleep(1) is put into all SSL_read() + * and SSL_write() calls, good for nbio debuging :-) */ + int debug; + + /* extra application data */ + long verify_result; + CRYPTO_EX_DATA ex_data; + + /* for server side, keep the list of CA_dn we can use */ + STACK_OF(X509_NAME) *client_CA; + + int references; + unsigned long options; /* protocol behaviour */ + unsigned long mode; /* API behaviour */ + long max_cert_list; + int first_packet; + int client_version; /* what was passed, used for + * SSLv3/TLS rollback check */ + unsigned int max_send_fragment; +#ifndef OPENSSL_NO_TLSEXT + /* TLS extension debug callback */ + void (*tlsext_debug_cb)(SSL *s, int client_server, int type, + unsigned char *data, int len, + void *arg); + void *tlsext_debug_arg; + char *tlsext_hostname; + int servername_done; /* no further mod of servername + 0 : call the servername extension callback. + 1 : prepare 2, allow last ack just after in server callback. + 2 : don't call servername callback, no ack in server hello + */ + /* certificate status request info */ + /* Status type or -1 if no status type */ + int tlsext_status_type; + /* Expect OCSP CertificateStatus message */ + int tlsext_status_expected; + /* OCSP status request only */ + STACK_OF(OCSP_RESPID) *tlsext_ocsp_ids; + X509_EXTENSIONS *tlsext_ocsp_exts; + /* OCSP response received or to be sent */ + unsigned char *tlsext_ocsp_resp; + int tlsext_ocsp_resplen; + + /* RFC4507 session ticket expected to be received or sent */ + int tlsext_ticket_expected; +#ifndef OPENSSL_NO_EC + size_t tlsext_ecpointformatlist_length; + unsigned char *tlsext_ecpointformatlist; /* our list */ + size_t tlsext_ellipticcurvelist_length; + unsigned char *tlsext_ellipticcurvelist; /* our list */ +#endif /* OPENSSL_NO_EC */ + + /* draft-rescorla-tls-opaque-prf-input-00.txt information to be used for handshakes */ + void *tlsext_opaque_prf_input; + size_t tlsext_opaque_prf_input_len; + + /* TLS Session Ticket extension override */ + TLS_SESSION_TICKET_EXT *tlsext_session_ticket; + + /* TLS Session Ticket extension callback */ + tls_session_ticket_ext_cb_fn tls_session_ticket_ext_cb; + void *tls_session_ticket_ext_cb_arg; + + /* TLS pre-shared secret session resumption */ + tls_session_secret_cb_fn tls_session_secret_cb; + void *tls_session_secret_cb_arg; + + SSL_CTX * initial_ctx; /* initial ctx, used to store sessions */ + +#ifndef OPENSSL_NO_NEXTPROTONEG + /* Next protocol negotiation. For the client, this is the protocol that + * we sent in NextProtocol and is set when handling ServerHello + * extensions. + * + * For a server, this is the client's selected_protocol from + * NextProtocol and is set when handling the NextProtocol message, + * before the Finished message. */ + unsigned char *next_proto_negotiated; + unsigned char next_proto_negotiated_len; +#endif + +#define session_ctx initial_ctx +#else +#define session_ctx ctx +#endif /* OPENSSL_NO_TLSEXT */ + }; + +#ifdef __cplusplus +} +#endif + +#include +#include +#include /* This is mostly sslv3 with a few tweaks */ +#include /* Datagram TLS */ +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/* compatibility */ +#define SSL_set_app_data(s,arg) (SSL_set_ex_data(s,0,(char *)arg)) +#define SSL_get_app_data(s) (SSL_get_ex_data(s,0)) +#define SSL_SESSION_set_app_data(s,a) (SSL_SESSION_set_ex_data(s,0,(char *)a)) +#define SSL_SESSION_get_app_data(s) (SSL_SESSION_get_ex_data(s,0)) +#define SSL_CTX_get_app_data(ctx) (SSL_CTX_get_ex_data(ctx,0)) +#define SSL_CTX_set_app_data(ctx,arg) (SSL_CTX_set_ex_data(ctx,0,(char *)arg)) + +/* The following are the possible values for ssl->state are are + * used to indicate where we are up to in the SSL connection establishment. + * The macros that follow are about the only things you should need to use + * and even then, only when using non-blocking IO. + * It can also be useful to work out where you were when the connection + * failed */ + +#define SSL_ST_CONNECT 0x1000 +#define SSL_ST_ACCEPT 0x2000 +#define SSL_ST_MASK 0x0FFF +#define SSL_ST_INIT (SSL_ST_CONNECT|SSL_ST_ACCEPT) +#define SSL_ST_BEFORE 0x4000 +#define SSL_ST_OK 0x03 +#define SSL_ST_RENEGOTIATE (0x04|SSL_ST_INIT) + +#define SSL_CB_LOOP 0x01 +#define SSL_CB_EXIT 0x02 +#define SSL_CB_READ 0x04 +#define SSL_CB_WRITE 0x08 +#define SSL_CB_ALERT 0x4000 /* used in callback */ +#define SSL_CB_READ_ALERT (SSL_CB_ALERT|SSL_CB_READ) +#define SSL_CB_WRITE_ALERT (SSL_CB_ALERT|SSL_CB_WRITE) +#define SSL_CB_ACCEPT_LOOP (SSL_ST_ACCEPT|SSL_CB_LOOP) +#define SSL_CB_ACCEPT_EXIT (SSL_ST_ACCEPT|SSL_CB_EXIT) +#define SSL_CB_CONNECT_LOOP (SSL_ST_CONNECT|SSL_CB_LOOP) +#define SSL_CB_CONNECT_EXIT (SSL_ST_CONNECT|SSL_CB_EXIT) +#define SSL_CB_HANDSHAKE_START 0x10 +#define SSL_CB_HANDSHAKE_DONE 0x20 + +/* Is the SSL_connection established? */ +#define SSL_get_state(a) SSL_state(a) +#define SSL_is_init_finished(a) (SSL_state(a) == SSL_ST_OK) +#define SSL_in_init(a) ((SSL_state(a)&SSL_ST_INIT) && \ + !SSL_cutthrough_complete(a)) +#define SSL_in_before(a) (SSL_state(a)&SSL_ST_BEFORE) +#define SSL_in_connect_init(a) (SSL_state(a)&SSL_ST_CONNECT) +#define SSL_in_accept_init(a) (SSL_state(a)&SSL_ST_ACCEPT) +int SSL_cutthrough_complete(const SSL *s); + +/* The following 2 states are kept in ssl->rstate when reads fail, + * you should not need these */ +#define SSL_ST_READ_HEADER 0xF0 +#define SSL_ST_READ_BODY 0xF1 +#define SSL_ST_READ_DONE 0xF2 + +/* Obtain latest Finished message + * -- that we sent (SSL_get_finished) + * -- that we expected from peer (SSL_get_peer_finished). + * Returns length (0 == no Finished so far), copies up to 'count' bytes. */ +size_t SSL_get_finished(const SSL *s, void *buf, size_t count); +size_t SSL_get_peer_finished(const SSL *s, void *buf, size_t count); + +/* use either SSL_VERIFY_NONE or SSL_VERIFY_PEER, the last 2 options + * are 'ored' with SSL_VERIFY_PEER if they are desired */ +#define SSL_VERIFY_NONE 0x00 +#define SSL_VERIFY_PEER 0x01 +#define SSL_VERIFY_FAIL_IF_NO_PEER_CERT 0x02 +#define SSL_VERIFY_CLIENT_ONCE 0x04 + +#define OpenSSL_add_ssl_algorithms() SSL_library_init() +#define SSLeay_add_ssl_algorithms() SSL_library_init() + +/* this is for backward compatibility */ +#if 0 /* NEW_SSLEAY */ +#define SSL_CTX_set_default_verify(a,b,c) SSL_CTX_set_verify(a,b,c) +#define SSL_set_pref_cipher(c,n) SSL_set_cipher_list(c,n) +#define SSL_add_session(a,b) SSL_CTX_add_session((a),(b)) +#define SSL_remove_session(a,b) SSL_CTX_remove_session((a),(b)) +#define SSL_flush_sessions(a,b) SSL_CTX_flush_sessions((a),(b)) +#endif +/* More backward compatibility */ +#define SSL_get_cipher(s) \ + SSL_CIPHER_get_name(SSL_get_current_cipher(s)) +#define SSL_get_cipher_bits(s,np) \ + SSL_CIPHER_get_bits(SSL_get_current_cipher(s),np) +#define SSL_get_cipher_version(s) \ + SSL_CIPHER_get_version(SSL_get_current_cipher(s)) +#define SSL_get_cipher_name(s) \ + SSL_CIPHER_get_name(SSL_get_current_cipher(s)) +#define SSL_get_time(a) SSL_SESSION_get_time(a) +#define SSL_set_time(a,b) SSL_SESSION_set_time((a),(b)) +#define SSL_get_timeout(a) SSL_SESSION_get_timeout(a) +#define SSL_set_timeout(a,b) SSL_SESSION_set_timeout((a),(b)) + +#define d2i_SSL_SESSION_bio(bp,s_id) ASN1_d2i_bio_of(SSL_SESSION,SSL_SESSION_new,d2i_SSL_SESSION,bp,s_id) +#define i2d_SSL_SESSION_bio(bp,s_id) ASN1_i2d_bio_of(SSL_SESSION,i2d_SSL_SESSION,bp,s_id) + +DECLARE_PEM_rw(SSL_SESSION, SSL_SESSION) + +#define SSL_AD_REASON_OFFSET 1000 /* offset to get SSL_R_... value from SSL_AD_... */ + +/* These alert types are for SSLv3 and TLSv1 */ +#define SSL_AD_CLOSE_NOTIFY SSL3_AD_CLOSE_NOTIFY +#define SSL_AD_UNEXPECTED_MESSAGE SSL3_AD_UNEXPECTED_MESSAGE /* fatal */ +#define SSL_AD_BAD_RECORD_MAC SSL3_AD_BAD_RECORD_MAC /* fatal */ +#define SSL_AD_DECRYPTION_FAILED TLS1_AD_DECRYPTION_FAILED +#define SSL_AD_RECORD_OVERFLOW TLS1_AD_RECORD_OVERFLOW +#define SSL_AD_DECOMPRESSION_FAILURE SSL3_AD_DECOMPRESSION_FAILURE/* fatal */ +#define SSL_AD_HANDSHAKE_FAILURE SSL3_AD_HANDSHAKE_FAILURE/* fatal */ +#define SSL_AD_NO_CERTIFICATE SSL3_AD_NO_CERTIFICATE /* Not for TLS */ +#define SSL_AD_BAD_CERTIFICATE SSL3_AD_BAD_CERTIFICATE +#define SSL_AD_UNSUPPORTED_CERTIFICATE SSL3_AD_UNSUPPORTED_CERTIFICATE +#define SSL_AD_CERTIFICATE_REVOKED SSL3_AD_CERTIFICATE_REVOKED +#define SSL_AD_CERTIFICATE_EXPIRED SSL3_AD_CERTIFICATE_EXPIRED +#define SSL_AD_CERTIFICATE_UNKNOWN SSL3_AD_CERTIFICATE_UNKNOWN +#define SSL_AD_ILLEGAL_PARAMETER SSL3_AD_ILLEGAL_PARAMETER /* fatal */ +#define SSL_AD_UNKNOWN_CA TLS1_AD_UNKNOWN_CA /* fatal */ +#define SSL_AD_ACCESS_DENIED TLS1_AD_ACCESS_DENIED /* fatal */ +#define SSL_AD_DECODE_ERROR TLS1_AD_DECODE_ERROR /* fatal */ +#define SSL_AD_DECRYPT_ERROR TLS1_AD_DECRYPT_ERROR +#define SSL_AD_EXPORT_RESTRICTION TLS1_AD_EXPORT_RESTRICTION/* fatal */ +#define SSL_AD_PROTOCOL_VERSION TLS1_AD_PROTOCOL_VERSION /* fatal */ +#define SSL_AD_INSUFFICIENT_SECURITY TLS1_AD_INSUFFICIENT_SECURITY/* fatal */ +#define SSL_AD_INTERNAL_ERROR TLS1_AD_INTERNAL_ERROR /* fatal */ +#define SSL_AD_USER_CANCELLED TLS1_AD_USER_CANCELLED +#define SSL_AD_NO_RENEGOTIATION TLS1_AD_NO_RENEGOTIATION +#define SSL_AD_UNSUPPORTED_EXTENSION TLS1_AD_UNSUPPORTED_EXTENSION +#define SSL_AD_CERTIFICATE_UNOBTAINABLE TLS1_AD_CERTIFICATE_UNOBTAINABLE +#define SSL_AD_UNRECOGNIZED_NAME TLS1_AD_UNRECOGNIZED_NAME +#define SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE TLS1_AD_BAD_CERTIFICATE_STATUS_RESPONSE +#define SSL_AD_BAD_CERTIFICATE_HASH_VALUE TLS1_AD_BAD_CERTIFICATE_HASH_VALUE +#define SSL_AD_UNKNOWN_PSK_IDENTITY TLS1_AD_UNKNOWN_PSK_IDENTITY /* fatal */ + +#define SSL_ERROR_NONE 0 +#define SSL_ERROR_SSL 1 +#define SSL_ERROR_WANT_READ 2 +#define SSL_ERROR_WANT_WRITE 3 +#define SSL_ERROR_WANT_X509_LOOKUP 4 +#define SSL_ERROR_SYSCALL 5 /* look at error stack/return value/errno */ +#define SSL_ERROR_ZERO_RETURN 6 +#define SSL_ERROR_WANT_CONNECT 7 +#define SSL_ERROR_WANT_ACCEPT 8 + +#define SSL_CTRL_NEED_TMP_RSA 1 +#define SSL_CTRL_SET_TMP_RSA 2 +#define SSL_CTRL_SET_TMP_DH 3 +#define SSL_CTRL_SET_TMP_ECDH 4 +#define SSL_CTRL_SET_TMP_RSA_CB 5 +#define SSL_CTRL_SET_TMP_DH_CB 6 +#define SSL_CTRL_SET_TMP_ECDH_CB 7 + +#define SSL_CTRL_GET_SESSION_REUSED 8 +#define SSL_CTRL_GET_CLIENT_CERT_REQUEST 9 +#define SSL_CTRL_GET_NUM_RENEGOTIATIONS 10 +#define SSL_CTRL_CLEAR_NUM_RENEGOTIATIONS 11 +#define SSL_CTRL_GET_TOTAL_RENEGOTIATIONS 12 +#define SSL_CTRL_GET_FLAGS 13 +#define SSL_CTRL_EXTRA_CHAIN_CERT 14 + +#define SSL_CTRL_SET_MSG_CALLBACK 15 +#define SSL_CTRL_SET_MSG_CALLBACK_ARG 16 + +/* only applies to datagram connections */ +#define SSL_CTRL_SET_MTU 17 +/* Stats */ +#define SSL_CTRL_SESS_NUMBER 20 +#define SSL_CTRL_SESS_CONNECT 21 +#define SSL_CTRL_SESS_CONNECT_GOOD 22 +#define SSL_CTRL_SESS_CONNECT_RENEGOTIATE 23 +#define SSL_CTRL_SESS_ACCEPT 24 +#define SSL_CTRL_SESS_ACCEPT_GOOD 25 +#define SSL_CTRL_SESS_ACCEPT_RENEGOTIATE 26 +#define SSL_CTRL_SESS_HIT 27 +#define SSL_CTRL_SESS_CB_HIT 28 +#define SSL_CTRL_SESS_MISSES 29 +#define SSL_CTRL_SESS_TIMEOUTS 30 +#define SSL_CTRL_SESS_CACHE_FULL 31 +#define SSL_CTRL_OPTIONS 32 +#define SSL_CTRL_MODE 33 + +#define SSL_CTRL_GET_READ_AHEAD 40 +#define SSL_CTRL_SET_READ_AHEAD 41 +#define SSL_CTRL_SET_SESS_CACHE_SIZE 42 +#define SSL_CTRL_GET_SESS_CACHE_SIZE 43 +#define SSL_CTRL_SET_SESS_CACHE_MODE 44 +#define SSL_CTRL_GET_SESS_CACHE_MODE 45 + +#define SSL_CTRL_GET_MAX_CERT_LIST 50 +#define SSL_CTRL_SET_MAX_CERT_LIST 51 + +#define SSL_CTRL_SET_MAX_SEND_FRAGMENT 52 + +/* see tls1.h for macros based on these */ +#ifndef OPENSSL_NO_TLSEXT +#define SSL_CTRL_SET_TLSEXT_SERVERNAME_CB 53 +#define SSL_CTRL_SET_TLSEXT_SERVERNAME_ARG 54 +#define SSL_CTRL_SET_TLSEXT_HOSTNAME 55 +#define SSL_CTRL_SET_TLSEXT_DEBUG_CB 56 +#define SSL_CTRL_SET_TLSEXT_DEBUG_ARG 57 +#define SSL_CTRL_GET_TLSEXT_TICKET_KEYS 58 +#define SSL_CTRL_SET_TLSEXT_TICKET_KEYS 59 +#define SSL_CTRL_SET_TLSEXT_OPAQUE_PRF_INPUT 60 +#define SSL_CTRL_SET_TLSEXT_OPAQUE_PRF_INPUT_CB 61 +#define SSL_CTRL_SET_TLSEXT_OPAQUE_PRF_INPUT_CB_ARG 62 +#define SSL_CTRL_SET_TLSEXT_STATUS_REQ_CB 63 +#define SSL_CTRL_SET_TLSEXT_STATUS_REQ_CB_ARG 64 +#define SSL_CTRL_SET_TLSEXT_STATUS_REQ_TYPE 65 +#define SSL_CTRL_GET_TLSEXT_STATUS_REQ_EXTS 66 +#define SSL_CTRL_SET_TLSEXT_STATUS_REQ_EXTS 67 +#define SSL_CTRL_GET_TLSEXT_STATUS_REQ_IDS 68 +#define SSL_CTRL_SET_TLSEXT_STATUS_REQ_IDS 69 +#define SSL_CTRL_GET_TLSEXT_STATUS_REQ_OCSP_RESP 70 +#define SSL_CTRL_SET_TLSEXT_STATUS_REQ_OCSP_RESP 71 + +#define SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB 72 +#endif + +#define DTLS_CTRL_GET_TIMEOUT 73 +#define DTLS_CTRL_HANDLE_TIMEOUT 74 +#define DTLS_CTRL_LISTEN 75 + +#define SSL_CTRL_GET_RI_SUPPORT 76 +#define SSL_CTRL_CLEAR_OPTIONS 77 +#define SSL_CTRL_CLEAR_MODE 78 + +#define DTLSv1_get_timeout(ssl, arg) \ + SSL_ctrl(ssl,DTLS_CTRL_GET_TIMEOUT,0, (void *)arg) +#define DTLSv1_handle_timeout(ssl) \ + SSL_ctrl(ssl,DTLS_CTRL_HANDLE_TIMEOUT,0, NULL) +#define DTLSv1_listen(ssl, peer) \ + SSL_ctrl(ssl,DTLS_CTRL_LISTEN,0, (void *)peer) + +#define SSL_session_reused(ssl) \ + SSL_ctrl((ssl),SSL_CTRL_GET_SESSION_REUSED,0,NULL) +#define SSL_num_renegotiations(ssl) \ + SSL_ctrl((ssl),SSL_CTRL_GET_NUM_RENEGOTIATIONS,0,NULL) +#define SSL_clear_num_renegotiations(ssl) \ + SSL_ctrl((ssl),SSL_CTRL_CLEAR_NUM_RENEGOTIATIONS,0,NULL) +#define SSL_total_renegotiations(ssl) \ + SSL_ctrl((ssl),SSL_CTRL_GET_TOTAL_RENEGOTIATIONS,0,NULL) + +#define SSL_CTX_need_tmp_RSA(ctx) \ + SSL_CTX_ctrl(ctx,SSL_CTRL_NEED_TMP_RSA,0,NULL) +#define SSL_CTX_set_tmp_rsa(ctx,rsa) \ + SSL_CTX_ctrl(ctx,SSL_CTRL_SET_TMP_RSA,0,(char *)rsa) +#define SSL_CTX_set_tmp_dh(ctx,dh) \ + SSL_CTX_ctrl(ctx,SSL_CTRL_SET_TMP_DH,0,(char *)dh) +#define SSL_CTX_set_tmp_ecdh(ctx,ecdh) \ + SSL_CTX_ctrl(ctx,SSL_CTRL_SET_TMP_ECDH,0,(char *)ecdh) + +#define SSL_need_tmp_RSA(ssl) \ + SSL_ctrl(ssl,SSL_CTRL_NEED_TMP_RSA,0,NULL) +#define SSL_set_tmp_rsa(ssl,rsa) \ + SSL_ctrl(ssl,SSL_CTRL_SET_TMP_RSA,0,(char *)rsa) +#define SSL_set_tmp_dh(ssl,dh) \ + SSL_ctrl(ssl,SSL_CTRL_SET_TMP_DH,0,(char *)dh) +#define SSL_set_tmp_ecdh(ssl,ecdh) \ + SSL_ctrl(ssl,SSL_CTRL_SET_TMP_ECDH,0,(char *)ecdh) + +#define SSL_CTX_add_extra_chain_cert(ctx,x509) \ + SSL_CTX_ctrl(ctx,SSL_CTRL_EXTRA_CHAIN_CERT,0,(char *)x509) + +#ifndef OPENSSL_NO_BIO +BIO_METHOD *BIO_f_ssl(void); +BIO *BIO_new_ssl(SSL_CTX *ctx,int client); +BIO *BIO_new_ssl_connect(SSL_CTX *ctx); +BIO *BIO_new_buffer_ssl_connect(SSL_CTX *ctx); +int BIO_ssl_copy_session_id(BIO *to,BIO *from); +void BIO_ssl_shutdown(BIO *ssl_bio); + +#endif + +int SSL_CTX_set_cipher_list(SSL_CTX *,const char *str); +SSL_CTX *SSL_CTX_new(const SSL_METHOD *meth); +void SSL_CTX_free(SSL_CTX *); +long SSL_CTX_set_timeout(SSL_CTX *ctx,long t); +long SSL_CTX_get_timeout(const SSL_CTX *ctx); +X509_STORE *SSL_CTX_get_cert_store(const SSL_CTX *); +void SSL_CTX_set_cert_store(SSL_CTX *,X509_STORE *); +int SSL_want(const SSL *s); +int SSL_clear(SSL *s); + +void SSL_CTX_flush_sessions(SSL_CTX *ctx,long tm); + +const SSL_CIPHER *SSL_get_current_cipher(const SSL *s); +int SSL_CIPHER_get_bits(const SSL_CIPHER *c,int *alg_bits); +char * SSL_CIPHER_get_version(const SSL_CIPHER *c); +const char * SSL_CIPHER_get_name(const SSL_CIPHER *c); +const char * SSL_CIPHER_authentication_method(const SSL_CIPHER *c); + +int SSL_get_fd(const SSL *s); +int SSL_get_rfd(const SSL *s); +int SSL_get_wfd(const SSL *s); +const char * SSL_get_cipher_list(const SSL *s,int n); +char * SSL_get_shared_ciphers(const SSL *s, char *buf, int len); +int SSL_get_read_ahead(const SSL * s); +int SSL_pending(const SSL *s); +const char * SSL_authentication_method(const SSL *c); +#ifndef OPENSSL_NO_SOCK +int SSL_set_fd(SSL *s, int fd); +int SSL_set_rfd(SSL *s, int fd); +int SSL_set_wfd(SSL *s, int fd); +#endif +#ifndef OPENSSL_NO_BIO +void SSL_set_bio(SSL *s, BIO *rbio,BIO *wbio); +BIO * SSL_get_rbio(const SSL *s); +BIO * SSL_get_wbio(const SSL *s); +#endif +int SSL_set_cipher_list(SSL *s, const char *str); +int SSL_set_cipher_lists(SSL *s, STACK_OF(SSL_CIPHER) *sk); +void SSL_set_read_ahead(SSL *s, int yes); +int SSL_get_verify_mode(const SSL *s); +int SSL_get_verify_depth(const SSL *s); +int (*SSL_get_verify_callback(const SSL *s))(int,X509_STORE_CTX *); +void SSL_set_verify(SSL *s, int mode, + int (*callback)(int ok,X509_STORE_CTX *ctx)); +void SSL_set_verify_depth(SSL *s, int depth); +#ifndef OPENSSL_NO_RSA +int SSL_use_RSAPrivateKey(SSL *ssl, RSA *rsa); +#endif +int SSL_use_RSAPrivateKey_ASN1(SSL *ssl, unsigned char *d, long len); +int SSL_use_PrivateKey(SSL *ssl, EVP_PKEY *pkey); +int SSL_use_PrivateKey_ASN1(int pk,SSL *ssl, const unsigned char *d, long len); +int SSL_use_certificate(SSL *ssl, X509 *x); +int SSL_use_certificate_ASN1(SSL *ssl, const unsigned char *d, int len); +int SSL_use_certificate_chain(SSL *ssl, STACK_OF(X509) *cert_chain); +STACK_OF(X509) * SSL_get_certificate_chain(SSL *ssl, X509 *x); + +#ifndef OPENSSL_NO_STDIO +int SSL_use_RSAPrivateKey_file(SSL *ssl, const char *file, int type); +int SSL_use_PrivateKey_file(SSL *ssl, const char *file, int type); +int SSL_use_certificate_file(SSL *ssl, const char *file, int type); +int SSL_CTX_use_RSAPrivateKey_file(SSL_CTX *ctx, const char *file, int type); +int SSL_CTX_use_PrivateKey_file(SSL_CTX *ctx, const char *file, int type); +int SSL_CTX_use_certificate_file(SSL_CTX *ctx, const char *file, int type); +int SSL_CTX_use_certificate_chain_file(SSL_CTX *ctx, const char *file); /* PEM type */ +STACK_OF(X509_NAME) *SSL_load_client_CA_file(const char *file); +int SSL_add_file_cert_subjects_to_stack(STACK_OF(X509_NAME) *stackCAs, + const char *file); +#ifndef OPENSSL_SYS_VMS +#ifndef OPENSSL_SYS_MACINTOSH_CLASSIC /* XXXXX: Better scheme needed! [was: #ifndef MAC_OS_pre_X] */ +int SSL_add_dir_cert_subjects_to_stack(STACK_OF(X509_NAME) *stackCAs, + const char *dir); +#endif +#endif + +#endif + +void SSL_load_error_strings(void ); +const char *SSL_state_string(const SSL *s); +const char *SSL_rstate_string(const SSL *s); +const char *SSL_state_string_long(const SSL *s); +const char *SSL_rstate_string_long(const SSL *s); +long SSL_SESSION_get_time(const SSL_SESSION *s); +long SSL_SESSION_set_time(SSL_SESSION *s, long t); +long SSL_SESSION_get_timeout(const SSL_SESSION *s); +long SSL_SESSION_set_timeout(SSL_SESSION *s, long t); +void SSL_copy_session_id(SSL *to,const SSL *from); + +SSL_SESSION *SSL_SESSION_new(void); +const unsigned char *SSL_SESSION_get_id(const SSL_SESSION *s, + unsigned int *len); +const char * SSL_SESSION_get_version(const SSL_SESSION *s); +#ifndef OPENSSL_NO_FP_API +int SSL_SESSION_print_fp(FILE *fp,const SSL_SESSION *ses); +#endif +#ifndef OPENSSL_NO_BIO +int SSL_SESSION_print(BIO *fp,const SSL_SESSION *ses); +#endif +void SSL_SESSION_free(SSL_SESSION *ses); +int i2d_SSL_SESSION(SSL_SESSION *in,unsigned char **pp); +int SSL_set_session(SSL *to, SSL_SESSION *session); +void SSL_set_session_creation_enabled(SSL *, int); +int SSL_CTX_add_session(SSL_CTX *s, SSL_SESSION *c); +int SSL_CTX_remove_session(SSL_CTX *,SSL_SESSION *c); +int SSL_CTX_set_generate_session_id(SSL_CTX *, GEN_SESSION_CB); +int SSL_set_generate_session_id(SSL *, GEN_SESSION_CB); +int SSL_has_matching_session_id(const SSL *ssl, const unsigned char *id, + unsigned int id_len); +SSL_SESSION *d2i_SSL_SESSION(SSL_SESSION **a,const unsigned char **pp, + long length); + +#ifdef HEADER_X509_H +X509 * SSL_get_peer_certificate(const SSL *s); +#endif + +STACK_OF(X509) *SSL_get_peer_cert_chain(const SSL *s); + +int SSL_CTX_get_verify_mode(const SSL_CTX *ctx); +int SSL_CTX_get_verify_depth(const SSL_CTX *ctx); +int (*SSL_CTX_get_verify_callback(const SSL_CTX *ctx))(int,X509_STORE_CTX *); +void SSL_CTX_set_verify(SSL_CTX *ctx,int mode, + int (*callback)(int, X509_STORE_CTX *)); +void SSL_CTX_set_verify_depth(SSL_CTX *ctx,int depth); +void SSL_CTX_set_cert_verify_callback(SSL_CTX *ctx, int (*cb)(X509_STORE_CTX *,void *), void *arg); +#ifndef OPENSSL_NO_RSA +int SSL_CTX_use_RSAPrivateKey(SSL_CTX *ctx, RSA *rsa); +#endif +int SSL_CTX_use_RSAPrivateKey_ASN1(SSL_CTX *ctx, const unsigned char *d, long len); +int SSL_CTX_use_PrivateKey(SSL_CTX *ctx, EVP_PKEY *pkey); +int SSL_CTX_use_PrivateKey_ASN1(int pk,SSL_CTX *ctx, + const unsigned char *d, long len); +int SSL_CTX_use_certificate(SSL_CTX *ctx, X509 *x); +int SSL_CTX_use_certificate_ASN1(SSL_CTX *ctx, int len, const unsigned char *d); + +void SSL_CTX_set_default_passwd_cb(SSL_CTX *ctx, pem_password_cb *cb); +void SSL_CTX_set_default_passwd_cb_userdata(SSL_CTX *ctx, void *u); + +int SSL_CTX_check_private_key(const SSL_CTX *ctx); +int SSL_check_private_key(const SSL *ctx); + +int SSL_CTX_set_session_id_context(SSL_CTX *ctx,const unsigned char *sid_ctx, + unsigned int sid_ctx_len); + +SSL * SSL_new(SSL_CTX *ctx); +int SSL_set_session_id_context(SSL *ssl,const unsigned char *sid_ctx, + unsigned int sid_ctx_len); + +int SSL_CTX_set_purpose(SSL_CTX *s, int purpose); +int SSL_set_purpose(SSL *s, int purpose); +int SSL_CTX_set_trust(SSL_CTX *s, int trust); +int SSL_set_trust(SSL *s, int trust); + +int SSL_CTX_set1_param(SSL_CTX *ctx, X509_VERIFY_PARAM *vpm); +int SSL_set1_param(SSL *ssl, X509_VERIFY_PARAM *vpm); + +void SSL_free(SSL *ssl); +int SSL_accept(SSL *ssl); +int SSL_connect(SSL *ssl); +int SSL_read(SSL *ssl,void *buf,int num); +int SSL_peek(SSL *ssl,void *buf,int num); +int SSL_write(SSL *ssl,const void *buf,int num); +long SSL_ctrl(SSL *ssl,int cmd, long larg, void *parg); +long SSL_callback_ctrl(SSL *, int, void (*)(void)); +long SSL_CTX_ctrl(SSL_CTX *ctx,int cmd, long larg, void *parg); +long SSL_CTX_callback_ctrl(SSL_CTX *, int, void (*)(void)); + +int SSL_get_error(const SSL *s,int ret_code); +const char *SSL_get_version(const SSL *s); + +/* This sets the 'default' SSL version that SSL_new() will create */ +int SSL_CTX_set_ssl_version(SSL_CTX *ctx, const SSL_METHOD *meth); + +#ifndef OPENSSL_NO_SSL2 +const SSL_METHOD *SSLv2_method(void); /* SSLv2 */ +const SSL_METHOD *SSLv2_server_method(void); /* SSLv2 */ +const SSL_METHOD *SSLv2_client_method(void); /* SSLv2 */ +#endif + +const SSL_METHOD *SSLv3_method(void); /* SSLv3 */ +const SSL_METHOD *SSLv3_server_method(void); /* SSLv3 */ +const SSL_METHOD *SSLv3_client_method(void); /* SSLv3 */ + +const SSL_METHOD *SSLv23_method(void); /* SSLv3 but can rollback to v2 */ +const SSL_METHOD *SSLv23_server_method(void); /* SSLv3 but can rollback to v2 */ +const SSL_METHOD *SSLv23_client_method(void); /* SSLv3 but can rollback to v2 */ + +const SSL_METHOD *TLSv1_method(void); /* TLSv1.0 */ +const SSL_METHOD *TLSv1_server_method(void); /* TLSv1.0 */ +const SSL_METHOD *TLSv1_client_method(void); /* TLSv1.0 */ + +const SSL_METHOD *DTLSv1_method(void); /* DTLSv1.0 */ +const SSL_METHOD *DTLSv1_server_method(void); /* DTLSv1.0 */ +const SSL_METHOD *DTLSv1_client_method(void); /* DTLSv1.0 */ + +STACK_OF(SSL_CIPHER) *SSL_get_ciphers(const SSL *s); + +int SSL_do_handshake(SSL *s); +int SSL_renegotiate(SSL *s); +int SSL_renegotiate_pending(SSL *s); +int SSL_shutdown(SSL *s); + +const SSL_METHOD *SSL_get_ssl_method(SSL *s); +int SSL_set_ssl_method(SSL *s, const SSL_METHOD *method); +const char *SSL_alert_type_string_long(int value); +const char *SSL_alert_type_string(int value); +const char *SSL_alert_desc_string_long(int value); +const char *SSL_alert_desc_string(int value); + +void SSL_set_client_CA_list(SSL *s, STACK_OF(X509_NAME) *name_list); +void SSL_CTX_set_client_CA_list(SSL_CTX *ctx, STACK_OF(X509_NAME) *name_list); +STACK_OF(X509_NAME) *SSL_get_client_CA_list(const SSL *s); +STACK_OF(X509_NAME) *SSL_CTX_get_client_CA_list(const SSL_CTX *s); +int SSL_add_client_CA(SSL *ssl,X509 *x); +int SSL_CTX_add_client_CA(SSL_CTX *ctx,X509 *x); + +void SSL_set_connect_state(SSL *s); +void SSL_set_accept_state(SSL *s); + +long SSL_get_default_timeout(const SSL *s); + +int SSL_library_init(void ); + +char *SSL_CIPHER_description(const SSL_CIPHER *,char *buf,int size); +STACK_OF(X509_NAME) *SSL_dup_CA_list(STACK_OF(X509_NAME) *sk); + +SSL *SSL_dup(SSL *ssl); + +X509 *SSL_get_certificate(const SSL *ssl); +/* EVP_PKEY */ struct evp_pkey_st *SSL_get_privatekey(SSL *ssl); + +void SSL_CTX_set_quiet_shutdown(SSL_CTX *ctx,int mode); +int SSL_CTX_get_quiet_shutdown(const SSL_CTX *ctx); +void SSL_set_quiet_shutdown(SSL *ssl,int mode); +int SSL_get_quiet_shutdown(const SSL *ssl); +void SSL_set_shutdown(SSL *ssl,int mode); +int SSL_get_shutdown(const SSL *ssl); +int SSL_version(const SSL *ssl); +int SSL_CTX_set_default_verify_paths(SSL_CTX *ctx); +int SSL_CTX_load_verify_locations(SSL_CTX *ctx, const char *CAfile, + const char *CApath); +#define SSL_get0_session SSL_get_session /* just peek at pointer */ +SSL_SESSION *SSL_get_session(const SSL *ssl); +SSL_SESSION *SSL_get1_session(SSL *ssl); /* obtain a reference count */ +SSL_CTX *SSL_get_SSL_CTX(const SSL *ssl); +SSL_CTX *SSL_set_SSL_CTX(SSL *ssl, SSL_CTX* ctx); +void SSL_set_info_callback(SSL *ssl, + void (*cb)(const SSL *ssl,int type,int val)); +void (*SSL_get_info_callback(const SSL *ssl))(const SSL *ssl,int type,int val); +int SSL_state(const SSL *ssl); + +void SSL_set_verify_result(SSL *ssl,long v); +long SSL_get_verify_result(const SSL *ssl); + +int SSL_set_ex_data(SSL *ssl,int idx,void *data); +void *SSL_get_ex_data(const SSL *ssl,int idx); +int SSL_get_ex_new_index(long argl, void *argp, CRYPTO_EX_new *new_func, + CRYPTO_EX_dup *dup_func, CRYPTO_EX_free *free_func); + +int SSL_SESSION_set_ex_data(SSL_SESSION *ss,int idx,void *data); +void *SSL_SESSION_get_ex_data(const SSL_SESSION *ss,int idx); +int SSL_SESSION_get_ex_new_index(long argl, void *argp, CRYPTO_EX_new *new_func, + CRYPTO_EX_dup *dup_func, CRYPTO_EX_free *free_func); + +int SSL_CTX_set_ex_data(SSL_CTX *ssl,int idx,void *data); +void *SSL_CTX_get_ex_data(const SSL_CTX *ssl,int idx); +int SSL_CTX_get_ex_new_index(long argl, void *argp, CRYPTO_EX_new *new_func, + CRYPTO_EX_dup *dup_func, CRYPTO_EX_free *free_func); + +int SSL_get_ex_data_X509_STORE_CTX_idx(void ); + +#define SSL_CTX_sess_set_cache_size(ctx,t) \ + SSL_CTX_ctrl(ctx,SSL_CTRL_SET_SESS_CACHE_SIZE,t,NULL) +#define SSL_CTX_sess_get_cache_size(ctx) \ + SSL_CTX_ctrl(ctx,SSL_CTRL_GET_SESS_CACHE_SIZE,0,NULL) +#define SSL_CTX_set_session_cache_mode(ctx,m) \ + SSL_CTX_ctrl(ctx,SSL_CTRL_SET_SESS_CACHE_MODE,m,NULL) +#define SSL_CTX_get_session_cache_mode(ctx) \ + SSL_CTX_ctrl(ctx,SSL_CTRL_GET_SESS_CACHE_MODE,0,NULL) + +#define SSL_CTX_get_default_read_ahead(ctx) SSL_CTX_get_read_ahead(ctx) +#define SSL_CTX_set_default_read_ahead(ctx,m) SSL_CTX_set_read_ahead(ctx,m) +#define SSL_CTX_get_read_ahead(ctx) \ + SSL_CTX_ctrl(ctx,SSL_CTRL_GET_READ_AHEAD,0,NULL) +#define SSL_CTX_set_read_ahead(ctx,m) \ + SSL_CTX_ctrl(ctx,SSL_CTRL_SET_READ_AHEAD,m,NULL) +#define SSL_CTX_get_max_cert_list(ctx) \ + SSL_CTX_ctrl(ctx,SSL_CTRL_GET_MAX_CERT_LIST,0,NULL) +#define SSL_CTX_set_max_cert_list(ctx,m) \ + SSL_CTX_ctrl(ctx,SSL_CTRL_SET_MAX_CERT_LIST,m,NULL) +#define SSL_get_max_cert_list(ssl) \ + SSL_ctrl(ssl,SSL_CTRL_GET_MAX_CERT_LIST,0,NULL) +#define SSL_set_max_cert_list(ssl,m) \ + SSL_ctrl(ssl,SSL_CTRL_SET_MAX_CERT_LIST,m,NULL) + +#define SSL_CTX_set_max_send_fragment(ctx,m) \ + SSL_CTX_ctrl(ctx,SSL_CTRL_SET_MAX_SEND_FRAGMENT,m,NULL) +#define SSL_set_max_send_fragment(ssl,m) \ + SSL_ctrl(ssl,SSL_CTRL_SET_MAX_SEND_FRAGMENT,m,NULL) + + /* NB: the keylength is only applicable when is_export is true */ +#ifndef OPENSSL_NO_RSA +void SSL_CTX_set_tmp_rsa_callback(SSL_CTX *ctx, + RSA *(*cb)(SSL *ssl,int is_export, + int keylength)); + +void SSL_set_tmp_rsa_callback(SSL *ssl, + RSA *(*cb)(SSL *ssl,int is_export, + int keylength)); +#endif +#ifndef OPENSSL_NO_DH +void SSL_CTX_set_tmp_dh_callback(SSL_CTX *ctx, + DH *(*dh)(SSL *ssl,int is_export, + int keylength)); +void SSL_set_tmp_dh_callback(SSL *ssl, + DH *(*dh)(SSL *ssl,int is_export, + int keylength)); +#endif +#ifndef OPENSSL_NO_ECDH +void SSL_CTX_set_tmp_ecdh_callback(SSL_CTX *ctx, + EC_KEY *(*ecdh)(SSL *ssl,int is_export, + int keylength)); +void SSL_set_tmp_ecdh_callback(SSL *ssl, + EC_KEY *(*ecdh)(SSL *ssl,int is_export, + int keylength)); +#endif + +#ifndef OPENSSL_NO_COMP +const COMP_METHOD *SSL_get_current_compression(SSL *s); +const COMP_METHOD *SSL_get_current_expansion(SSL *s); +const char *SSL_COMP_get_name(const COMP_METHOD *comp); +STACK_OF(SSL_COMP) *SSL_COMP_get_compression_methods(void); +int SSL_COMP_add_compression_method(int id,COMP_METHOD *cm); +#else +const void *SSL_get_current_compression(SSL *s); +const void *SSL_get_current_expansion(SSL *s); +const char *SSL_COMP_get_name(const void *comp); +void *SSL_COMP_get_compression_methods(void); +int SSL_COMP_add_compression_method(int id,void *cm); +#endif + +/* TLS extensions functions */ +int SSL_set_session_ticket_ext(SSL *s, void *ext_data, int ext_len); + +int SSL_set_session_ticket_ext_cb(SSL *s, tls_session_ticket_ext_cb_fn cb, + void *arg); + +/* Pre-shared secret session resumption functions */ +int SSL_set_session_secret_cb(SSL *s, tls_session_secret_cb_fn tls_session_secret_cb, void *arg); + +/* BEGIN ERROR CODES */ +/* The following lines are auto generated by the script mkerr.pl. Any changes + * made after this point may be overwritten when the script is next run. + */ +void ERR_load_SSL_strings(void); + +/* Error codes for the SSL functions. */ + +/* Function codes. */ +#define SSL_F_CLIENT_CERTIFICATE 100 +#define SSL_F_CLIENT_FINISHED 167 +#define SSL_F_CLIENT_HELLO 101 +#define SSL_F_CLIENT_MASTER_KEY 102 +#define SSL_F_D2I_SSL_SESSION 103 +#define SSL_F_DO_DTLS1_WRITE 245 +#define SSL_F_DO_SSL3_WRITE 104 +#define SSL_F_DTLS1_ACCEPT 246 +#define SSL_F_DTLS1_ADD_CERT_TO_BUF 295 +#define SSL_F_DTLS1_BUFFER_RECORD 247 +#define SSL_F_DTLS1_CLIENT_HELLO 248 +#define SSL_F_DTLS1_CONNECT 249 +#define SSL_F_DTLS1_ENC 250 +#define SSL_F_DTLS1_GET_HELLO_VERIFY 251 +#define SSL_F_DTLS1_GET_MESSAGE 252 +#define SSL_F_DTLS1_GET_MESSAGE_FRAGMENT 253 +#define SSL_F_DTLS1_GET_RECORD 254 +#define SSL_F_DTLS1_HANDLE_TIMEOUT 297 +#define SSL_F_DTLS1_OUTPUT_CERT_CHAIN 255 +#define SSL_F_DTLS1_PREPROCESS_FRAGMENT 288 +#define SSL_F_DTLS1_PROCESS_OUT_OF_SEQ_MESSAGE 256 +#define SSL_F_DTLS1_PROCESS_RECORD 257 +#define SSL_F_DTLS1_READ_BYTES 258 +#define SSL_F_DTLS1_READ_FAILED 259 +#define SSL_F_DTLS1_SEND_CERTIFICATE_REQUEST 260 +#define SSL_F_DTLS1_SEND_CLIENT_CERTIFICATE 261 +#define SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE 262 +#define SSL_F_DTLS1_SEND_CLIENT_VERIFY 263 +#define SSL_F_DTLS1_SEND_HELLO_VERIFY_REQUEST 264 +#define SSL_F_DTLS1_SEND_SERVER_CERTIFICATE 265 +#define SSL_F_DTLS1_SEND_SERVER_HELLO 266 +#define SSL_F_DTLS1_SEND_SERVER_KEY_EXCHANGE 267 +#define SSL_F_DTLS1_WRITE_APP_DATA_BYTES 268 +#define SSL_F_GET_CLIENT_FINISHED 105 +#define SSL_F_GET_CLIENT_HELLO 106 +#define SSL_F_GET_CLIENT_MASTER_KEY 107 +#define SSL_F_GET_SERVER_FINISHED 108 +#define SSL_F_GET_SERVER_HELLO 109 +#define SSL_F_GET_SERVER_VERIFY 110 +#define SSL_F_I2D_SSL_SESSION 111 +#define SSL_F_READ_N 112 +#define SSL_F_REQUEST_CERTIFICATE 113 +#define SSL_F_SERVER_FINISH 239 +#define SSL_F_SERVER_HELLO 114 +#define SSL_F_SERVER_VERIFY 240 +#define SSL_F_SSL23_ACCEPT 115 +#define SSL_F_SSL23_CLIENT_HELLO 116 +#define SSL_F_SSL23_CONNECT 117 +#define SSL_F_SSL23_GET_CLIENT_HELLO 118 +#define SSL_F_SSL23_GET_SERVER_HELLO 119 +#define SSL_F_SSL23_PEEK 237 +#define SSL_F_SSL23_READ 120 +#define SSL_F_SSL23_WRITE 121 +#define SSL_F_SSL2_ACCEPT 122 +#define SSL_F_SSL2_CONNECT 123 +#define SSL_F_SSL2_ENC_INIT 124 +#define SSL_F_SSL2_GENERATE_KEY_MATERIAL 241 +#define SSL_F_SSL2_PEEK 234 +#define SSL_F_SSL2_READ 125 +#define SSL_F_SSL2_READ_INTERNAL 236 +#define SSL_F_SSL2_SET_CERTIFICATE 126 +#define SSL_F_SSL2_WRITE 127 +#define SSL_F_SSL3_ACCEPT 128 +#define SSL_F_SSL3_ADD_CERT_TO_BUF 296 +#define SSL_F_SSL3_CALLBACK_CTRL 233 +#define SSL_F_SSL3_CHANGE_CIPHER_STATE 129 +#define SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM 130 +#define SSL_F_SSL3_CHECK_CLIENT_HELLO 304 +#define SSL_F_SSL3_CLIENT_HELLO 131 +#define SSL_F_SSL3_CONNECT 132 +#define SSL_F_SSL3_CTRL 213 +#define SSL_F_SSL3_CTX_CTRL 133 +#define SSL_F_SSL3_DIGEST_CACHED_RECORDS 293 +#define SSL_F_SSL3_DO_CHANGE_CIPHER_SPEC 292 +#define SSL_F_SSL3_ENC 134 +#define SSL_F_SSL3_GENERATE_KEY_BLOCK 238 +#define SSL_F_SSL3_GET_CERTIFICATE_REQUEST 135 +#define SSL_F_SSL3_GET_CERT_STATUS 289 +#define SSL_F_SSL3_GET_CERT_VERIFY 136 +#define SSL_F_SSL3_GET_CLIENT_CERTIFICATE 137 +#define SSL_F_SSL3_GET_CLIENT_HELLO 138 +#define SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE 139 +#define SSL_F_SSL3_GET_FINISHED 140 +#define SSL_F_SSL3_GET_KEY_EXCHANGE 141 +#define SSL_F_SSL3_GET_MESSAGE 142 +#define SSL_F_SSL3_GET_NEW_SESSION_TICKET 283 +#define SSL_F_SSL3_GET_NEXT_PROTO 304 +#define SSL_F_SSL3_GET_RECORD 143 +#define SSL_F_SSL3_GET_SERVER_CERTIFICATE 144 +#define SSL_F_SSL3_GET_SERVER_DONE 145 +#define SSL_F_SSL3_GET_SERVER_HELLO 146 +#define SSL_F_SSL3_HANDSHAKE_MAC 285 +#define SSL_F_SSL3_NEW_SESSION_TICKET 287 +#define SSL_F_SSL3_OUTPUT_CERT_CHAIN 147 +#define SSL_F_SSL3_PEEK 235 +#define SSL_F_SSL3_READ_BYTES 148 +#define SSL_F_SSL3_READ_N 149 +#define SSL_F_SSL3_SEND_CERTIFICATE_REQUEST 150 +#define SSL_F_SSL3_SEND_CLIENT_CERTIFICATE 151 +#define SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE 152 +#define SSL_F_SSL3_SEND_CLIENT_VERIFY 153 +#define SSL_F_SSL3_SEND_SERVER_CERTIFICATE 154 +#define SSL_F_SSL3_SEND_SERVER_HELLO 242 +#define SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE 155 +#define SSL_F_SSL3_SETUP_KEY_BLOCK 157 +#define SSL_F_SSL3_SETUP_READ_BUFFER 156 +#define SSL_F_SSL3_SETUP_WRITE_BUFFER 291 +#define SSL_F_SSL3_WRITE_BYTES 158 +#define SSL_F_SSL3_WRITE_PENDING 159 +#define SSL_F_SSL_ADD_CLIENTHELLO_RENEGOTIATE_EXT 298 +#define SSL_F_SSL_ADD_CLIENTHELLO_TLSEXT 277 +#define SSL_F_SSL_ADD_DIR_CERT_SUBJECTS_TO_STACK 215 +#define SSL_F_SSL_ADD_FILE_CERT_SUBJECTS_TO_STACK 216 +#define SSL_F_SSL_ADD_SERVERHELLO_RENEGOTIATE_EXT 299 +#define SSL_F_SSL_ADD_SERVERHELLO_TLSEXT 278 +#define SSL_F_SSL_BAD_METHOD 160 +#define SSL_F_SSL_BYTES_TO_CIPHER_LIST 161 +#define SSL_F_SSL_CERT_DUP 221 +#define SSL_F_SSL_CERT_INST 222 +#define SSL_F_SSL_CERT_INSTANTIATE 214 +#define SSL_F_SSL_CERT_NEW 162 +#define SSL_F_SSL_CHECK_PRIVATE_KEY 163 +#define SSL_F_SSL_CHECK_SERVERHELLO_TLSEXT 280 +#define SSL_F_SSL_CHECK_SRVR_ECC_CERT_AND_ALG 279 +#define SSL_F_SSL_CIPHER_PROCESS_RULESTR 230 +#define SSL_F_SSL_CIPHER_STRENGTH_SORT 231 +#define SSL_F_SSL_CLEAR 164 +#define SSL_F_SSL_COMP_ADD_COMPRESSION_METHOD 165 +#define SSL_F_SSL_CREATE_CIPHER_LIST 166 +#define SSL_F_SSL_CTRL 232 +#define SSL_F_SSL_CTX_CHECK_PRIVATE_KEY 168 +#define SSL_F_SSL_CTX_NEW 169 +#define SSL_F_SSL_CTX_SET_CIPHER_LIST 269 +#define SSL_F_SSL_CTX_SET_CLIENT_CERT_ENGINE 290 +#define SSL_F_SSL_CTX_SET_PURPOSE 226 +#define SSL_F_SSL_CTX_SET_SESSION_ID_CONTEXT 219 +#define SSL_F_SSL_CTX_SET_SSL_VERSION 170 +#define SSL_F_SSL_CTX_SET_TRUST 229 +#define SSL_F_SSL_CTX_USE_CERTIFICATE 171 +#define SSL_F_SSL_CTX_USE_CERTIFICATE_ASN1 172 +#define SSL_F_SSL_CTX_USE_CERTIFICATE_CHAIN_FILE 220 +#define SSL_F_SSL_CTX_USE_CERTIFICATE_FILE 173 +#define SSL_F_SSL_CTX_USE_PRIVATEKEY 174 +#define SSL_F_SSL_CTX_USE_PRIVATEKEY_ASN1 175 +#define SSL_F_SSL_CTX_USE_PRIVATEKEY_FILE 176 +#define SSL_F_SSL_CTX_USE_PSK_IDENTITY_HINT 272 +#define SSL_F_SSL_CTX_USE_RSAPRIVATEKEY 177 +#define SSL_F_SSL_CTX_USE_RSAPRIVATEKEY_ASN1 178 +#define SSL_F_SSL_CTX_USE_RSAPRIVATEKEY_FILE 179 +#define SSL_F_SSL_DO_HANDSHAKE 180 +#define SSL_F_SSL_GET_NEW_SESSION 181 +#define SSL_F_SSL_GET_PREV_SESSION 217 +#define SSL_F_SSL_GET_SERVER_SEND_CERT 182 +#define SSL_F_SSL_GET_SIGN_PKEY 183 +#define SSL_F_SSL_INIT_WBIO_BUFFER 184 +#define SSL_F_SSL_LOAD_CLIENT_CA_FILE 185 +#define SSL_F_SSL_NEW 186 +#define SSL_F_SSL_PARSE_CLIENTHELLO_RENEGOTIATE_EXT 300 +#define SSL_F_SSL_PARSE_CLIENTHELLO_TLSEXT 302 +#define SSL_F_SSL_PARSE_SERVERHELLO_RENEGOTIATE_EXT 301 +#define SSL_F_SSL_PARSE_SERVERHELLO_TLSEXT 303 +#define SSL_F_SSL_PEEK 270 +#define SSL_F_TLS1_EXPORT_KEYING_MATERIAL 312 +#define SSL_F_SSL_PREPARE_CLIENTHELLO_TLSEXT 281 +#define SSL_F_SSL_PREPARE_SERVERHELLO_TLSEXT 282 +#define SSL_F_SSL_READ 223 +#define SSL_F_SSL_RSA_PRIVATE_DECRYPT 187 +#define SSL_F_SSL_RSA_PUBLIC_ENCRYPT 188 +#define SSL_F_SSL_SESSION_NEW 189 +#define SSL_F_SSL_SESSION_PRINT_FP 190 +#define SSL_F_SSL_SESS_CERT_NEW 225 +#define SSL_F_SSL_SET_CERT 191 +#define SSL_F_SSL_SET_CIPHER_LIST 271 +#define SSL_F_SSL_SET_FD 192 +#define SSL_F_SSL_SET_PKEY 193 +#define SSL_F_SSL_SET_PURPOSE 227 +#define SSL_F_SSL_SET_RFD 194 +#define SSL_F_SSL_SET_SESSION 195 +#define SSL_F_SSL_SET_SESSION_ID_CONTEXT 218 +#define SSL_F_SSL_SET_SESSION_TICKET_EXT 294 +#define SSL_F_SSL_SET_TRUST 228 +#define SSL_F_SSL_SET_WFD 196 +#define SSL_F_SSL_SHUTDOWN 224 +#define SSL_F_SSL_UNDEFINED_CONST_FUNCTION 243 +#define SSL_F_SSL_UNDEFINED_FUNCTION 197 +#define SSL_F_SSL_UNDEFINED_VOID_FUNCTION 244 +#define SSL_F_SSL_USE_CERTIFICATE 198 +#define SSL_F_SSL_USE_CERTIFICATE_ASN1 199 +#define SSL_F_SSL_USE_CERTIFICATE_CHAIN 2000 +#define SSL_F_SSL_USE_CERTIFICATE_FILE 200 +#define SSL_F_SSL_USE_PRIVATEKEY 201 +#define SSL_F_SSL_USE_PRIVATEKEY_ASN1 202 +#define SSL_F_SSL_USE_PRIVATEKEY_FILE 203 +#define SSL_F_SSL_USE_PSK_IDENTITY_HINT 273 +#define SSL_F_SSL_USE_RSAPRIVATEKEY 204 +#define SSL_F_SSL_USE_RSAPRIVATEKEY_ASN1 205 +#define SSL_F_SSL_USE_RSAPRIVATEKEY_FILE 206 +#define SSL_F_SSL_VERIFY_CERT_CHAIN 207 +#define SSL_F_SSL_WRITE 208 +#define SSL_F_TLS1_CERT_VERIFY_MAC 286 +#define SSL_F_TLS1_CHANGE_CIPHER_STATE 209 +#define SSL_F_TLS1_CHECK_SERVERHELLO_TLSEXT 274 +#define SSL_F_TLS1_ENC 210 +#define SSL_F_TLS1_PREPARE_CLIENTHELLO_TLSEXT 275 +#define SSL_F_TLS1_PREPARE_SERVERHELLO_TLSEXT 276 +#define SSL_F_TLS1_PRF 284 +#define SSL_F_TLS1_SETUP_KEY_BLOCK 211 +#define SSL_F_WRITE_PENDING 212 + +/* Reason codes. */ +#define SSL_R_APP_DATA_IN_HANDSHAKE 100 +#define SSL_R_ATTEMPT_TO_REUSE_SESSION_IN_DIFFERENT_CONTEXT 272 +#define SSL_R_BAD_ALERT_RECORD 101 +#define SSL_R_BAD_AUTHENTICATION_TYPE 102 +#define SSL_R_BAD_CHANGE_CIPHER_SPEC 103 +#define SSL_R_BAD_CHECKSUM 104 +#define SSL_R_BAD_DATA_RETURNED_BY_CALLBACK 106 +#define SSL_R_BAD_DECOMPRESSION 107 +#define SSL_R_BAD_DH_G_LENGTH 108 +#define SSL_R_BAD_DH_PUB_KEY_LENGTH 109 +#define SSL_R_BAD_DH_P_LENGTH 110 +#define SSL_R_BAD_DIGEST_LENGTH 111 +#define SSL_R_BAD_DSA_SIGNATURE 112 +#define SSL_R_BAD_ECC_CERT 304 +#define SSL_R_BAD_ECDSA_SIGNATURE 305 +#define SSL_R_BAD_ECPOINT 306 +#define SSL_R_BAD_HANDSHAKE_LENGTH 332 +#define SSL_R_BAD_HELLO_REQUEST 105 +#define SSL_R_BAD_LENGTH 271 +#define SSL_R_BAD_MAC_DECODE 113 +#define SSL_R_BAD_MAC_LENGTH 333 +#define SSL_R_BAD_MESSAGE_TYPE 114 +#define SSL_R_BAD_PACKET_LENGTH 115 +#define SSL_R_BAD_PROTOCOL_VERSION_NUMBER 116 +#define SSL_R_BAD_PSK_IDENTITY_HINT_LENGTH 316 +#define SSL_R_BAD_RESPONSE_ARGUMENT 117 +#define SSL_R_BAD_RSA_DECRYPT 118 +#define SSL_R_BAD_RSA_ENCRYPT 119 +#define SSL_R_BAD_RSA_E_LENGTH 120 +#define SSL_R_BAD_RSA_MODULUS_LENGTH 121 +#define SSL_R_BAD_RSA_SIGNATURE 122 +#define SSL_R_BAD_SIGNATURE 123 +#define SSL_R_BAD_SSL_FILETYPE 124 +#define SSL_R_BAD_SSL_SESSION_ID_LENGTH 125 +#define SSL_R_BAD_STATE 126 +#define SSL_R_BAD_WRITE_RETRY 127 +#define SSL_R_BIO_NOT_SET 128 +#define SSL_R_BLOCK_CIPHER_PAD_IS_WRONG 129 +#define SSL_R_BN_LIB 130 +#define SSL_R_CA_DN_LENGTH_MISMATCH 131 +#define SSL_R_CA_DN_TOO_LONG 132 +#define SSL_R_CCS_RECEIVED_EARLY 133 +#define SSL_R_CERTIFICATE_VERIFY_FAILED 134 +#define SSL_R_CERT_LENGTH_MISMATCH 135 +#define SSL_R_CHALLENGE_IS_DIFFERENT 136 +#define SSL_R_CIPHER_CODE_WRONG_LENGTH 137 +#define SSL_R_CIPHER_OR_HASH_UNAVAILABLE 138 +#define SSL_R_CIPHER_TABLE_SRC_ERROR 139 +#define SSL_R_CLIENTHELLO_TLSEXT 226 +#define SSL_R_COMPRESSED_LENGTH_TOO_LONG 140 +#define SSL_R_COMPRESSION_DISABLED 343 +#define SSL_R_COMPRESSION_FAILURE 141 +#define SSL_R_COMPRESSION_ID_NOT_WITHIN_PRIVATE_RANGE 307 +#define SSL_R_COMPRESSION_LIBRARY_ERROR 142 +#define SSL_R_CONNECTION_ID_IS_DIFFERENT 143 +#define SSL_R_CONNECTION_TYPE_NOT_SET 144 +#define SSL_R_COOKIE_MISMATCH 308 +#define SSL_R_DATA_BETWEEN_CCS_AND_FINISHED 145 +#define SSL_R_DATA_LENGTH_TOO_LONG 146 +#define SSL_R_DECRYPTION_FAILED 147 +#define SSL_R_DECRYPTION_FAILED_OR_BAD_RECORD_MAC 281 +#define SSL_R_DH_PUBLIC_VALUE_LENGTH_IS_WRONG 148 +#define SSL_R_DIGEST_CHECK_FAILED 149 +#define SSL_R_DTLS_MESSAGE_TOO_BIG 334 +#define SSL_R_DUPLICATE_COMPRESSION_ID 309 +#define SSL_R_ECC_CERT_NOT_FOR_KEY_AGREEMENT 317 +#define SSL_R_ECC_CERT_NOT_FOR_SIGNING 318 +#define SSL_R_ECC_CERT_SHOULD_HAVE_RSA_SIGNATURE 322 +#define SSL_R_ECC_CERT_SHOULD_HAVE_SHA1_SIGNATURE 323 +#define SSL_R_ECGROUP_TOO_LARGE_FOR_CIPHER 310 +#define SSL_R_ENCRYPTED_LENGTH_TOO_LONG 150 +#define SSL_R_ERROR_GENERATING_TMP_RSA_KEY 282 +#define SSL_R_ERROR_IN_RECEIVED_CIPHER_LIST 151 +#define SSL_R_EXCESSIVE_MESSAGE_SIZE 152 +#define SSL_R_EXTRA_DATA_IN_MESSAGE 153 +#define SSL_R_GOT_A_FIN_BEFORE_A_CCS 154 +#define SSL_R_GOT_NEXT_PROTO_BEFORE_A_CCS 346 +#define SSL_R_GOT_NEXT_PROTO_WITHOUT_EXTENSION 347 +#define SSL_R_HTTPS_PROXY_REQUEST 155 +#define SSL_R_HTTP_REQUEST 156 +#define SSL_R_ILLEGAL_PADDING 283 +#define SSL_R_INCONSISTENT_COMPRESSION 340 +#define SSL_R_INVALID_CHALLENGE_LENGTH 158 +#define SSL_R_INVALID_COMMAND 280 +#define SSL_R_INVALID_COMPRESSION_ALGORITHM 341 +#define SSL_R_INVALID_PURPOSE 278 +#define SSL_R_INVALID_STATUS_RESPONSE 328 +#define SSL_R_INVALID_TICKET_KEYS_LENGTH 325 +#define SSL_R_INVALID_TRUST 279 +#define SSL_R_KEY_ARG_TOO_LONG 284 +#define SSL_R_KRB5 285 +#define SSL_R_KRB5_C_CC_PRINC 286 +#define SSL_R_KRB5_C_GET_CRED 287 +#define SSL_R_KRB5_C_INIT 288 +#define SSL_R_KRB5_C_MK_REQ 289 +#define SSL_R_KRB5_S_BAD_TICKET 290 +#define SSL_R_KRB5_S_INIT 291 +#define SSL_R_KRB5_S_RD_REQ 292 +#define SSL_R_KRB5_S_TKT_EXPIRED 293 +#define SSL_R_KRB5_S_TKT_NYV 294 +#define SSL_R_KRB5_S_TKT_SKEW 295 +#define SSL_R_LENGTH_MISMATCH 159 +#define SSL_R_LENGTH_TOO_SHORT 160 +#define SSL_R_LIBRARY_BUG 274 +#define SSL_R_LIBRARY_HAS_NO_CIPHERS 161 +#define SSL_R_MESSAGE_TOO_LONG 296 +#define SSL_R_MISSING_DH_DSA_CERT 162 +#define SSL_R_MISSING_DH_KEY 163 +#define SSL_R_MISSING_DH_RSA_CERT 164 +#define SSL_R_MISSING_DSA_SIGNING_CERT 165 +#define SSL_R_MISSING_EXPORT_TMP_DH_KEY 166 +#define SSL_R_MISSING_EXPORT_TMP_RSA_KEY 167 +#define SSL_R_MISSING_RSA_CERTIFICATE 168 +#define SSL_R_MISSING_RSA_ENCRYPTING_CERT 169 +#define SSL_R_MISSING_RSA_SIGNING_CERT 170 +#define SSL_R_MISSING_TMP_DH_KEY 171 +#define SSL_R_MISSING_TMP_ECDH_KEY 311 +#define SSL_R_MISSING_TMP_RSA_KEY 172 +#define SSL_R_MISSING_TMP_RSA_PKEY 173 +#define SSL_R_MISSING_VERIFY_MESSAGE 174 +#define SSL_R_MULTIPLE_SGC_RESTARTS 346 +#define SSL_R_NON_SSLV2_INITIAL_PACKET 175 +#define SSL_R_NO_CERTIFICATES_RETURNED 176 +#define SSL_R_NO_CERTIFICATE_ASSIGNED 177 +#define SSL_R_NO_CERTIFICATE_RETURNED 178 +#define SSL_R_NO_CERTIFICATE_SET 179 +#define SSL_R_NO_CERTIFICATE_SPECIFIED 180 +#define SSL_R_NO_CIPHERS_AVAILABLE 181 +#define SSL_R_NO_CIPHERS_PASSED 182 +#define SSL_R_NO_CIPHERS_SPECIFIED 183 +#define SSL_R_NO_CIPHER_LIST 184 +#define SSL_R_NO_CIPHER_MATCH 185 +#define SSL_R_NO_CLIENT_CERT_METHOD 331 +#define SSL_R_NO_CLIENT_CERT_RECEIVED 186 +#define SSL_R_NO_COMPRESSION_SPECIFIED 187 +#define SSL_R_NO_GOST_CERTIFICATE_SENT_BY_PEER 330 +#define SSL_R_NO_METHOD_SPECIFIED 188 +#define SSL_R_NO_PRIVATEKEY 189 +#define SSL_R_NO_PRIVATE_KEY_ASSIGNED 190 +#define SSL_R_NO_PROTOCOLS_AVAILABLE 191 +#define SSL_R_NO_PUBLICKEY 192 +#define SSL_R_NO_RENEGOTIATION 339 +#define SSL_R_NO_REQUIRED_DIGEST 324 +#define SSL_R_NO_SHARED_CIPHER 193 +#define SSL_R_NO_VERIFY_CALLBACK 194 +#define SSL_R_NULL_SSL_CTX 195 +#define SSL_R_NULL_SSL_METHOD_PASSED 196 +#define SSL_R_OLD_SESSION_CIPHER_NOT_RETURNED 197 +#define SSL_R_OLD_SESSION_COMPRESSION_ALGORITHM_NOT_RETURNED 344 +#define SSL_R_ONLY_TLS_ALLOWED_IN_FIPS_MODE 297 +#define SSL_R_OPAQUE_PRF_INPUT_TOO_LONG 327 +#define SSL_R_PACKET_LENGTH_TOO_LONG 198 +#define SSL_R_PARSE_TLSEXT 227 +#define SSL_R_PATH_TOO_LONG 270 +#define SSL_R_PEER_DID_NOT_RETURN_A_CERTIFICATE 199 +#define SSL_R_PEER_ERROR 200 +#define SSL_R_PEER_ERROR_CERTIFICATE 201 +#define SSL_R_PEER_ERROR_NO_CERTIFICATE 202 +#define SSL_R_PEER_ERROR_NO_CIPHER 203 +#define SSL_R_PEER_ERROR_UNSUPPORTED_CERTIFICATE_TYPE 204 +#define SSL_R_PRE_MAC_LENGTH_TOO_LONG 205 +#define SSL_R_PROBLEMS_MAPPING_CIPHER_FUNCTIONS 206 +#define SSL_R_PROTOCOL_IS_SHUTDOWN 207 +#define SSL_R_PSK_IDENTITY_NOT_FOUND 223 +#define SSL_R_PSK_NO_CLIENT_CB 224 +#define SSL_R_PSK_NO_SERVER_CB 225 +#define SSL_R_PUBLIC_KEY_ENCRYPT_ERROR 208 +#define SSL_R_PUBLIC_KEY_IS_NOT_RSA 209 +#define SSL_R_PUBLIC_KEY_NOT_RSA 210 +#define SSL_R_READ_BIO_NOT_SET 211 +#define SSL_R_READ_TIMEOUT_EXPIRED 312 +#define SSL_R_READ_WRONG_PACKET_TYPE 212 +#define SSL_R_RECORD_LENGTH_MISMATCH 213 +#define SSL_R_RECORD_TOO_LARGE 214 +#define SSL_R_RECORD_TOO_SMALL 298 +#define SSL_R_RENEGOTIATE_EXT_TOO_LONG 335 +#define SSL_R_RENEGOTIATION_ENCODING_ERR 336 +#define SSL_R_RENEGOTIATION_MISMATCH 337 +#define SSL_R_REQUIRED_CIPHER_MISSING 215 +#define SSL_R_REQUIRED_COMPRESSSION_ALGORITHM_MISSING 342 +#define SSL_R_REUSE_CERT_LENGTH_NOT_ZERO 216 +#define SSL_R_REUSE_CERT_TYPE_NOT_ZERO 217 +#define SSL_R_REUSE_CIPHER_LIST_NOT_ZERO 218 +#define SSL_R_SCSV_RECEIVED_WHEN_RENEGOTIATING 345 +#define SSL_R_SERVERHELLO_TLSEXT 275 +#define SSL_R_SESSION_ID_CONTEXT_UNINITIALIZED 277 +#define SSL_R_SESSION_MAY_NOT_BE_CREATED 2000 +#define SSL_R_SHORT_READ 219 +#define SSL_R_SIGNATURE_FOR_NON_SIGNING_CERTIFICATE 220 +#define SSL_R_SSL23_DOING_SESSION_ID_REUSE 221 +#define SSL_R_SSL2_CONNECTION_ID_TOO_LONG 299 +#define SSL_R_SSL3_EXT_INVALID_ECPOINTFORMAT 321 +#define SSL_R_SSL3_EXT_INVALID_SERVERNAME 319 +#define SSL_R_SSL3_EXT_INVALID_SERVERNAME_TYPE 320 +#define SSL_R_SSL3_SESSION_ID_TOO_LONG 300 +#define SSL_R_SSL3_SESSION_ID_TOO_SHORT 222 +#define SSL_R_SSLV3_ALERT_BAD_CERTIFICATE 1042 +#define SSL_R_SSLV3_ALERT_BAD_RECORD_MAC 1020 +#define SSL_R_SSLV3_ALERT_CERTIFICATE_EXPIRED 1045 +#define SSL_R_SSLV3_ALERT_CERTIFICATE_REVOKED 1044 +#define SSL_R_SSLV3_ALERT_CERTIFICATE_UNKNOWN 1046 +#define SSL_R_SSLV3_ALERT_DECOMPRESSION_FAILURE 1030 +#define SSL_R_SSLV3_ALERT_HANDSHAKE_FAILURE 1040 +#define SSL_R_SSLV3_ALERT_ILLEGAL_PARAMETER 1047 +#define SSL_R_SSLV3_ALERT_NO_CERTIFICATE 1041 +#define SSL_R_SSLV3_ALERT_UNEXPECTED_MESSAGE 1010 +#define SSL_R_SSLV3_ALERT_UNSUPPORTED_CERTIFICATE 1043 +#define SSL_R_SSL_CTX_HAS_NO_DEFAULT_SSL_VERSION 228 +#define SSL_R_SSL_HANDSHAKE_FAILURE 229 +#define SSL_R_SSL_LIBRARY_HAS_NO_CIPHERS 230 +#define SSL_R_SSL_SESSION_ID_CALLBACK_FAILED 301 +#define SSL_R_SSL_SESSION_ID_CONFLICT 302 +#define SSL_R_SSL_SESSION_ID_CONTEXT_TOO_LONG 273 +#define SSL_R_SSL_SESSION_ID_HAS_BAD_LENGTH 303 +#define SSL_R_SSL_SESSION_ID_IS_DIFFERENT 231 +#define SSL_R_TLSV1_ALERT_ACCESS_DENIED 1049 +#define SSL_R_TLSV1_ALERT_DECODE_ERROR 1050 +#define SSL_R_TLSV1_ALERT_DECRYPTION_FAILED 1021 +#define SSL_R_TLSV1_ALERT_DECRYPT_ERROR 1051 +#define SSL_R_TLSV1_ALERT_EXPORT_RESTRICTION 1060 +#define SSL_R_TLSV1_ALERT_INSUFFICIENT_SECURITY 1071 +#define SSL_R_TLSV1_ALERT_INTERNAL_ERROR 1080 +#define SSL_R_TLSV1_ALERT_NO_RENEGOTIATION 1100 +#define SSL_R_TLSV1_ALERT_PROTOCOL_VERSION 1070 +#define SSL_R_TLSV1_ALERT_RECORD_OVERFLOW 1022 +#define SSL_R_TLSV1_ALERT_UNKNOWN_CA 1048 +#define SSL_R_TLSV1_ALERT_USER_CANCELLED 1090 +#define SSL_R_TLSV1_BAD_CERTIFICATE_HASH_VALUE 1114 +#define SSL_R_TLSV1_BAD_CERTIFICATE_STATUS_RESPONSE 1113 +#define SSL_R_TLSV1_CERTIFICATE_UNOBTAINABLE 1111 +#define SSL_R_TLSV1_UNRECOGNIZED_NAME 1112 +#define SSL_R_TLSV1_UNSUPPORTED_EXTENSION 1110 +#define SSL_R_TLS_CLIENT_CERT_REQ_WITH_ANON_CIPHER 232 +#define SSL_R_TLS_ILLEGAL_EXPORTER_LABEL 367 +#define SSL_R_TLS_INVALID_ECPOINTFORMAT_LIST 157 +#define SSL_R_TLS_PEER_DID_NOT_RESPOND_WITH_CERTIFICATE_LIST 233 +#define SSL_R_TLS_RSA_ENCRYPTED_VALUE_LENGTH_IS_WRONG 234 +#define SSL_R_TRIED_TO_USE_UNSUPPORTED_CIPHER 235 +#define SSL_R_UNABLE_TO_DECODE_DH_CERTS 236 +#define SSL_R_UNABLE_TO_DECODE_ECDH_CERTS 313 +#define SSL_R_UNABLE_TO_EXTRACT_PUBLIC_KEY 237 +#define SSL_R_UNABLE_TO_FIND_DH_PARAMETERS 238 +#define SSL_R_UNABLE_TO_FIND_ECDH_PARAMETERS 314 +#define SSL_R_UNABLE_TO_FIND_PUBLIC_KEY_PARAMETERS 239 +#define SSL_R_UNABLE_TO_FIND_SSL_METHOD 240 +#define SSL_R_UNABLE_TO_LOAD_SSL2_MD5_ROUTINES 241 +#define SSL_R_UNABLE_TO_LOAD_SSL3_MD5_ROUTINES 242 +#define SSL_R_UNABLE_TO_LOAD_SSL3_SHA1_ROUTINES 243 +#define SSL_R_UNEXPECTED_MESSAGE 244 +#define SSL_R_UNEXPECTED_RECORD 245 +#define SSL_R_UNINITIALIZED 276 +#define SSL_R_UNKNOWN_ALERT_TYPE 246 +#define SSL_R_UNKNOWN_CERTIFICATE_TYPE 247 +#define SSL_R_UNKNOWN_CIPHER_RETURNED 248 +#define SSL_R_UNKNOWN_CIPHER_TYPE 249 +#define SSL_R_UNKNOWN_KEY_EXCHANGE_TYPE 250 +#define SSL_R_UNKNOWN_PKEY_TYPE 251 +#define SSL_R_UNKNOWN_PROTOCOL 252 +#define SSL_R_UNKNOWN_REMOTE_ERROR_TYPE 253 +#define SSL_R_UNKNOWN_SSL_VERSION 254 +#define SSL_R_UNKNOWN_STATE 255 +#define SSL_R_UNSAFE_LEGACY_RENEGOTIATION_DISABLED 338 +#define SSL_R_UNSUPPORTED_CIPHER 256 +#define SSL_R_UNSUPPORTED_COMPRESSION_ALGORITHM 257 +#define SSL_R_UNSUPPORTED_DIGEST_TYPE 326 +#define SSL_R_UNSUPPORTED_ELLIPTIC_CURVE 315 +#define SSL_R_UNSUPPORTED_PROTOCOL 258 +#define SSL_R_UNSUPPORTED_SSL_VERSION 259 +#define SSL_R_UNSUPPORTED_STATUS_TYPE 329 +#define SSL_R_WRITE_BIO_NOT_SET 260 +#define SSL_R_WRONG_CIPHER_RETURNED 261 +#define SSL_R_WRONG_MESSAGE_TYPE 262 +#define SSL_R_WRONG_NUMBER_OF_KEY_BITS 263 +#define SSL_R_WRONG_SIGNATURE_LENGTH 264 +#define SSL_R_WRONG_SIGNATURE_SIZE 265 +#define SSL_R_WRONG_SSL_VERSION 266 +#define SSL_R_WRONG_VERSION_NUMBER 267 +#define SSL_R_X509_LIB 268 +#define SSL_R_X509_VERIFICATION_SETUP_PROBLEMS 269 + +#ifdef __cplusplus +} +#endif +#endif diff --git a/node-v0.8.14/deps/openssl/openssl/ssl/ssl2.h b/node-v0.8.14/deps/openssl/openssl/ssl/ssl2.h new file mode 100644 index 0000000..99a52ea --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/ssl/ssl2.h @@ -0,0 +1,268 @@ +/* ssl/ssl2.h */ +/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com) + * All rights reserved. + * + * This package is an SSL implementation written + * by Eric Young (eay@cryptsoft.com). + * The implementation was written so as to conform with Netscapes SSL. + * + * This library is free for commercial and non-commercial use as long as + * the following conditions are aheared to. The following conditions + * apply to all code found in this distribution, be it the RC4, RSA, + * lhash, DES, etc., code; not just the SSL code. The SSL documentation + * included with this distribution is covered by the same copyright terms + * except that the holder is Tim Hudson (tjh@cryptsoft.com). + * + * Copyright remains Eric Young's, and as such any Copyright notices in + * the code are not to be removed. + * If this package is used in a product, Eric Young should be given attribution + * as the author of the parts of the library used. + * This can be in the form of a textual message at program startup or + * in documentation (online or textual) provided with the package. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * "This product includes cryptographic software written by + * Eric Young (eay@cryptsoft.com)" + * The word 'cryptographic' can be left out if the rouines from the library + * being used are not cryptographic related :-). + * 4. If you include any Windows specific code (or a derivative thereof) from + * the apps directory (application code) you must include an acknowledgement: + * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)" + * + * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * + * The licence and distribution terms for any publically available version or + * derivative of this code cannot be changed. i.e. this code cannot simply be + * copied and put under another distribution licence + * [including the GNU Public Licence.] + */ + +#ifndef HEADER_SSL2_H +#define HEADER_SSL2_H + +#ifdef __cplusplus +extern "C" { +#endif + +/* Protocol Version Codes */ +#define SSL2_VERSION 0x0002 +#define SSL2_VERSION_MAJOR 0x00 +#define SSL2_VERSION_MINOR 0x02 +/* #define SSL2_CLIENT_VERSION 0x0002 */ +/* #define SSL2_SERVER_VERSION 0x0002 */ + +/* Protocol Message Codes */ +#define SSL2_MT_ERROR 0 +#define SSL2_MT_CLIENT_HELLO 1 +#define SSL2_MT_CLIENT_MASTER_KEY 2 +#define SSL2_MT_CLIENT_FINISHED 3 +#define SSL2_MT_SERVER_HELLO 4 +#define SSL2_MT_SERVER_VERIFY 5 +#define SSL2_MT_SERVER_FINISHED 6 +#define SSL2_MT_REQUEST_CERTIFICATE 7 +#define SSL2_MT_CLIENT_CERTIFICATE 8 + +/* Error Message Codes */ +#define SSL2_PE_UNDEFINED_ERROR 0x0000 +#define SSL2_PE_NO_CIPHER 0x0001 +#define SSL2_PE_NO_CERTIFICATE 0x0002 +#define SSL2_PE_BAD_CERTIFICATE 0x0004 +#define SSL2_PE_UNSUPPORTED_CERTIFICATE_TYPE 0x0006 + +/* Cipher Kind Values */ +#define SSL2_CK_NULL_WITH_MD5 0x02000000 /* v3 */ +#define SSL2_CK_RC4_128_WITH_MD5 0x02010080 +#define SSL2_CK_RC4_128_EXPORT40_WITH_MD5 0x02020080 +#define SSL2_CK_RC2_128_CBC_WITH_MD5 0x02030080 +#define SSL2_CK_RC2_128_CBC_EXPORT40_WITH_MD5 0x02040080 +#define SSL2_CK_IDEA_128_CBC_WITH_MD5 0x02050080 +#define SSL2_CK_DES_64_CBC_WITH_MD5 0x02060040 +#define SSL2_CK_DES_64_CBC_WITH_SHA 0x02060140 /* v3 */ +#define SSL2_CK_DES_192_EDE3_CBC_WITH_MD5 0x020700c0 +#define SSL2_CK_DES_192_EDE3_CBC_WITH_SHA 0x020701c0 /* v3 */ +#define SSL2_CK_RC4_64_WITH_MD5 0x02080080 /* MS hack */ + +#define SSL2_CK_DES_64_CFB64_WITH_MD5_1 0x02ff0800 /* SSLeay */ +#define SSL2_CK_NULL 0x02ff0810 /* SSLeay */ + +#define SSL2_TXT_DES_64_CFB64_WITH_MD5_1 "DES-CFB-M1" +#define SSL2_TXT_NULL_WITH_MD5 "NULL-MD5" +#define SSL2_TXT_RC4_128_WITH_MD5 "RC4-MD5" +#define SSL2_TXT_RC4_128_EXPORT40_WITH_MD5 "EXP-RC4-MD5" +#define SSL2_TXT_RC2_128_CBC_WITH_MD5 "RC2-CBC-MD5" +#define SSL2_TXT_RC2_128_CBC_EXPORT40_WITH_MD5 "EXP-RC2-CBC-MD5" +#define SSL2_TXT_IDEA_128_CBC_WITH_MD5 "IDEA-CBC-MD5" +#define SSL2_TXT_DES_64_CBC_WITH_MD5 "DES-CBC-MD5" +#define SSL2_TXT_DES_64_CBC_WITH_SHA "DES-CBC-SHA" +#define SSL2_TXT_DES_192_EDE3_CBC_WITH_MD5 "DES-CBC3-MD5" +#define SSL2_TXT_DES_192_EDE3_CBC_WITH_SHA "DES-CBC3-SHA" +#define SSL2_TXT_RC4_64_WITH_MD5 "RC4-64-MD5" + +#define SSL2_TXT_NULL "NULL" + +/* Flags for the SSL_CIPHER.algorithm2 field */ +#define SSL2_CF_5_BYTE_ENC 0x01 +#define SSL2_CF_8_BYTE_ENC 0x02 + +/* Certificate Type Codes */ +#define SSL2_CT_X509_CERTIFICATE 0x01 + +/* Authentication Type Code */ +#define SSL2_AT_MD5_WITH_RSA_ENCRYPTION 0x01 + +#define SSL2_MAX_SSL_SESSION_ID_LENGTH 32 + +/* Upper/Lower Bounds */ +#define SSL2_MAX_MASTER_KEY_LENGTH_IN_BITS 256 +#ifdef OPENSSL_SYS_MPE +#define SSL2_MAX_RECORD_LENGTH_2_BYTE_HEADER 29998u +#else +#define SSL2_MAX_RECORD_LENGTH_2_BYTE_HEADER 32767u /* 2^15-1 */ +#endif +#define SSL2_MAX_RECORD_LENGTH_3_BYTE_HEADER 16383 /* 2^14-1 */ + +#define SSL2_CHALLENGE_LENGTH 16 +/*#define SSL2_CHALLENGE_LENGTH 32 */ +#define SSL2_MIN_CHALLENGE_LENGTH 16 +#define SSL2_MAX_CHALLENGE_LENGTH 32 +#define SSL2_CONNECTION_ID_LENGTH 16 +#define SSL2_MAX_CONNECTION_ID_LENGTH 16 +#define SSL2_SSL_SESSION_ID_LENGTH 16 +#define SSL2_MAX_CERT_CHALLENGE_LENGTH 32 +#define SSL2_MIN_CERT_CHALLENGE_LENGTH 16 +#define SSL2_MAX_KEY_MATERIAL_LENGTH 24 + +#ifndef HEADER_SSL_LOCL_H +#define CERT char +#endif + +typedef struct ssl2_state_st + { + int three_byte_header; + int clear_text; /* clear text */ + int escape; /* not used in SSLv2 */ + int ssl2_rollback; /* used if SSLv23 rolled back to SSLv2 */ + + /* non-blocking io info, used to make sure the same + * args were passwd */ + unsigned int wnum; /* number of bytes sent so far */ + int wpend_tot; + const unsigned char *wpend_buf; + + int wpend_off; /* offset to data to write */ + int wpend_len; /* number of bytes passwd to write */ + int wpend_ret; /* number of bytes to return to caller */ + + /* buffer raw data */ + int rbuf_left; + int rbuf_offs; + unsigned char *rbuf; + unsigned char *wbuf; + + unsigned char *write_ptr;/* used to point to the start due to + * 2/3 byte header. */ + + unsigned int padding; + unsigned int rlength; /* passed to ssl2_enc */ + int ract_data_length; /* Set when things are encrypted. */ + unsigned int wlength; /* passed to ssl2_enc */ + int wact_data_length; /* Set when things are decrypted. */ + unsigned char *ract_data; + unsigned char *wact_data; + unsigned char *mac_data; + + unsigned char *read_key; + unsigned char *write_key; + + /* Stuff specifically to do with this SSL session */ + unsigned int challenge_length; + unsigned char challenge[SSL2_MAX_CHALLENGE_LENGTH]; + unsigned int conn_id_length; + unsigned char conn_id[SSL2_MAX_CONNECTION_ID_LENGTH]; + unsigned int key_material_length; + unsigned char key_material[SSL2_MAX_KEY_MATERIAL_LENGTH*2]; + + unsigned long read_sequence; + unsigned long write_sequence; + + struct { + unsigned int conn_id_length; + unsigned int cert_type; + unsigned int cert_length; + unsigned int csl; + unsigned int clear; + unsigned int enc; + unsigned char ccl[SSL2_MAX_CERT_CHALLENGE_LENGTH]; + unsigned int cipher_spec_length; + unsigned int session_id_length; + unsigned int clen; + unsigned int rlen; + } tmp; + } SSL2_STATE; + +/* SSLv2 */ +/* client */ +#define SSL2_ST_SEND_CLIENT_HELLO_A (0x10|SSL_ST_CONNECT) +#define SSL2_ST_SEND_CLIENT_HELLO_B (0x11|SSL_ST_CONNECT) +#define SSL2_ST_GET_SERVER_HELLO_A (0x20|SSL_ST_CONNECT) +#define SSL2_ST_GET_SERVER_HELLO_B (0x21|SSL_ST_CONNECT) +#define SSL2_ST_SEND_CLIENT_MASTER_KEY_A (0x30|SSL_ST_CONNECT) +#define SSL2_ST_SEND_CLIENT_MASTER_KEY_B (0x31|SSL_ST_CONNECT) +#define SSL2_ST_SEND_CLIENT_FINISHED_A (0x40|SSL_ST_CONNECT) +#define SSL2_ST_SEND_CLIENT_FINISHED_B (0x41|SSL_ST_CONNECT) +#define SSL2_ST_SEND_CLIENT_CERTIFICATE_A (0x50|SSL_ST_CONNECT) +#define SSL2_ST_SEND_CLIENT_CERTIFICATE_B (0x51|SSL_ST_CONNECT) +#define SSL2_ST_SEND_CLIENT_CERTIFICATE_C (0x52|SSL_ST_CONNECT) +#define SSL2_ST_SEND_CLIENT_CERTIFICATE_D (0x53|SSL_ST_CONNECT) +#define SSL2_ST_GET_SERVER_VERIFY_A (0x60|SSL_ST_CONNECT) +#define SSL2_ST_GET_SERVER_VERIFY_B (0x61|SSL_ST_CONNECT) +#define SSL2_ST_GET_SERVER_FINISHED_A (0x70|SSL_ST_CONNECT) +#define SSL2_ST_GET_SERVER_FINISHED_B (0x71|SSL_ST_CONNECT) +#define SSL2_ST_CLIENT_START_ENCRYPTION (0x80|SSL_ST_CONNECT) +#define SSL2_ST_X509_GET_CLIENT_CERTIFICATE (0x90|SSL_ST_CONNECT) +/* server */ +#define SSL2_ST_GET_CLIENT_HELLO_A (0x10|SSL_ST_ACCEPT) +#define SSL2_ST_GET_CLIENT_HELLO_B (0x11|SSL_ST_ACCEPT) +#define SSL2_ST_GET_CLIENT_HELLO_C (0x12|SSL_ST_ACCEPT) +#define SSL2_ST_SEND_SERVER_HELLO_A (0x20|SSL_ST_ACCEPT) +#define SSL2_ST_SEND_SERVER_HELLO_B (0x21|SSL_ST_ACCEPT) +#define SSL2_ST_GET_CLIENT_MASTER_KEY_A (0x30|SSL_ST_ACCEPT) +#define SSL2_ST_GET_CLIENT_MASTER_KEY_B (0x31|SSL_ST_ACCEPT) +#define SSL2_ST_SEND_SERVER_VERIFY_A (0x40|SSL_ST_ACCEPT) +#define SSL2_ST_SEND_SERVER_VERIFY_B (0x41|SSL_ST_ACCEPT) +#define SSL2_ST_SEND_SERVER_VERIFY_C (0x42|SSL_ST_ACCEPT) +#define SSL2_ST_GET_CLIENT_FINISHED_A (0x50|SSL_ST_ACCEPT) +#define SSL2_ST_GET_CLIENT_FINISHED_B (0x51|SSL_ST_ACCEPT) +#define SSL2_ST_SEND_SERVER_FINISHED_A (0x60|SSL_ST_ACCEPT) +#define SSL2_ST_SEND_SERVER_FINISHED_B (0x61|SSL_ST_ACCEPT) +#define SSL2_ST_SEND_REQUEST_CERTIFICATE_A (0x70|SSL_ST_ACCEPT) +#define SSL2_ST_SEND_REQUEST_CERTIFICATE_B (0x71|SSL_ST_ACCEPT) +#define SSL2_ST_SEND_REQUEST_CERTIFICATE_C (0x72|SSL_ST_ACCEPT) +#define SSL2_ST_SEND_REQUEST_CERTIFICATE_D (0x73|SSL_ST_ACCEPT) +#define SSL2_ST_SERVER_START_ENCRYPTION (0x80|SSL_ST_ACCEPT) +#define SSL2_ST_X509_GET_SERVER_CERTIFICATE (0x90|SSL_ST_ACCEPT) + +#ifdef __cplusplus +} +#endif +#endif + diff --git a/node-v0.8.14/deps/openssl/openssl/ssl/ssl23.h b/node-v0.8.14/deps/openssl/openssl/ssl/ssl23.h new file mode 100644 index 0000000..d322898 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/ssl/ssl23.h @@ -0,0 +1,83 @@ +/* ssl/ssl23.h */ +/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com) + * All rights reserved. + * + * This package is an SSL implementation written + * by Eric Young (eay@cryptsoft.com). + * The implementation was written so as to conform with Netscapes SSL. + * + * This library is free for commercial and non-commercial use as long as + * the following conditions are aheared to. The following conditions + * apply to all code found in this distribution, be it the RC4, RSA, + * lhash, DES, etc., code; not just the SSL code. The SSL documentation + * included with this distribution is covered by the same copyright terms + * except that the holder is Tim Hudson (tjh@cryptsoft.com). + * + * Copyright remains Eric Young's, and as such any Copyright notices in + * the code are not to be removed. + * If this package is used in a product, Eric Young should be given attribution + * as the author of the parts of the library used. + * This can be in the form of a textual message at program startup or + * in documentation (online or textual) provided with the package. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * "This product includes cryptographic software written by + * Eric Young (eay@cryptsoft.com)" + * The word 'cryptographic' can be left out if the rouines from the library + * being used are not cryptographic related :-). + * 4. If you include any Windows specific code (or a derivative thereof) from + * the apps directory (application code) you must include an acknowledgement: + * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)" + * + * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * + * The licence and distribution terms for any publically available version or + * derivative of this code cannot be changed. i.e. this code cannot simply be + * copied and put under another distribution licence + * [including the GNU Public Licence.] + */ + +#ifndef HEADER_SSL23_H +#define HEADER_SSL23_H + +#ifdef __cplusplus +extern "C" { +#endif + +/*client */ +/* write to server */ +#define SSL23_ST_CW_CLNT_HELLO_A (0x210|SSL_ST_CONNECT) +#define SSL23_ST_CW_CLNT_HELLO_B (0x211|SSL_ST_CONNECT) +/* read from server */ +#define SSL23_ST_CR_SRVR_HELLO_A (0x220|SSL_ST_CONNECT) +#define SSL23_ST_CR_SRVR_HELLO_B (0x221|SSL_ST_CONNECT) + +/* server */ +/* read from client */ +#define SSL23_ST_SR_CLNT_HELLO_A (0x210|SSL_ST_ACCEPT) +#define SSL23_ST_SR_CLNT_HELLO_B (0x211|SSL_ST_ACCEPT) + +#ifdef __cplusplus +} +#endif +#endif + diff --git a/node-v0.8.14/deps/openssl/openssl/ssl/ssl3.h b/node-v0.8.14/deps/openssl/openssl/ssl/ssl3.h new file mode 100644 index 0000000..d6425e5 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/ssl/ssl3.h @@ -0,0 +1,675 @@ +/* ssl/ssl3.h */ +/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com) + * All rights reserved. + * + * This package is an SSL implementation written + * by Eric Young (eay@cryptsoft.com). + * The implementation was written so as to conform with Netscapes SSL. + * + * This library is free for commercial and non-commercial use as long as + * the following conditions are aheared to. The following conditions + * apply to all code found in this distribution, be it the RC4, RSA, + * lhash, DES, etc., code; not just the SSL code. The SSL documentation + * included with this distribution is covered by the same copyright terms + * except that the holder is Tim Hudson (tjh@cryptsoft.com). + * + * Copyright remains Eric Young's, and as such any Copyright notices in + * the code are not to be removed. + * If this package is used in a product, Eric Young should be given attribution + * as the author of the parts of the library used. + * This can be in the form of a textual message at program startup or + * in documentation (online or textual) provided with the package. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * "This product includes cryptographic software written by + * Eric Young (eay@cryptsoft.com)" + * The word 'cryptographic' can be left out if the rouines from the library + * being used are not cryptographic related :-). + * 4. If you include any Windows specific code (or a derivative thereof) from + * the apps directory (application code) you must include an acknowledgement: + * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)" + * + * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * + * The licence and distribution terms for any publically available version or + * derivative of this code cannot be changed. i.e. this code cannot simply be + * copied and put under another distribution licence + * [including the GNU Public Licence.] + */ +/* ==================================================================== + * Copyright (c) 1998-2002 The OpenSSL Project. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. All advertising materials mentioning features or use of this + * software must display the following acknowledgment: + * "This product includes software developed by the OpenSSL Project + * for use in the OpenSSL Toolkit. (http://www.openssl.org/)" + * + * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to + * endorse or promote products derived from this software without + * prior written permission. For written permission, please contact + * openssl-core@openssl.org. + * + * 5. Products derived from this software may not be called "OpenSSL" + * nor may "OpenSSL" appear in their names without prior written + * permission of the OpenSSL Project. + * + * 6. Redistributions of any form whatsoever must retain the following + * acknowledgment: + * "This product includes software developed by the OpenSSL Project + * for use in the OpenSSL Toolkit (http://www.openssl.org/)" + * + * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY + * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR + * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, + * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * ==================================================================== + * + * This product includes cryptographic software written by Eric Young + * (eay@cryptsoft.com). This product includes software written by Tim + * Hudson (tjh@cryptsoft.com). + * + */ +/* ==================================================================== + * Copyright 2002 Sun Microsystems, Inc. ALL RIGHTS RESERVED. + * ECC cipher suite support in OpenSSL originally developed by + * SUN MICROSYSTEMS, INC., and contributed to the OpenSSL project. + */ + +#ifndef HEADER_SSL3_H +#define HEADER_SSL3_H + +#ifndef OPENSSL_NO_COMP +#include +#endif +#include +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/* Signalling cipher suite value: from draft-ietf-tls-renegotiation-03.txt */ +#define SSL3_CK_SCSV 0x030000FF + +#define SSL3_CK_RSA_NULL_MD5 0x03000001 +#define SSL3_CK_RSA_NULL_SHA 0x03000002 +#define SSL3_CK_RSA_RC4_40_MD5 0x03000003 +#define SSL3_CK_RSA_RC4_128_MD5 0x03000004 +#define SSL3_CK_RSA_RC4_128_SHA 0x03000005 +#define SSL3_CK_RSA_RC2_40_MD5 0x03000006 +#define SSL3_CK_RSA_IDEA_128_SHA 0x03000007 +#define SSL3_CK_RSA_DES_40_CBC_SHA 0x03000008 +#define SSL3_CK_RSA_DES_64_CBC_SHA 0x03000009 +#define SSL3_CK_RSA_DES_192_CBC3_SHA 0x0300000A + +#define SSL3_CK_DH_DSS_DES_40_CBC_SHA 0x0300000B +#define SSL3_CK_DH_DSS_DES_64_CBC_SHA 0x0300000C +#define SSL3_CK_DH_DSS_DES_192_CBC3_SHA 0x0300000D +#define SSL3_CK_DH_RSA_DES_40_CBC_SHA 0x0300000E +#define SSL3_CK_DH_RSA_DES_64_CBC_SHA 0x0300000F +#define SSL3_CK_DH_RSA_DES_192_CBC3_SHA 0x03000010 + +#define SSL3_CK_EDH_DSS_DES_40_CBC_SHA 0x03000011 +#define SSL3_CK_EDH_DSS_DES_64_CBC_SHA 0x03000012 +#define SSL3_CK_EDH_DSS_DES_192_CBC3_SHA 0x03000013 +#define SSL3_CK_EDH_RSA_DES_40_CBC_SHA 0x03000014 +#define SSL3_CK_EDH_RSA_DES_64_CBC_SHA 0x03000015 +#define SSL3_CK_EDH_RSA_DES_192_CBC3_SHA 0x03000016 + +#define SSL3_CK_ADH_RC4_40_MD5 0x03000017 +#define SSL3_CK_ADH_RC4_128_MD5 0x03000018 +#define SSL3_CK_ADH_DES_40_CBC_SHA 0x03000019 +#define SSL3_CK_ADH_DES_64_CBC_SHA 0x0300001A +#define SSL3_CK_ADH_DES_192_CBC_SHA 0x0300001B + +#if 0 + #define SSL3_CK_FZA_DMS_NULL_SHA 0x0300001C + #define SSL3_CK_FZA_DMS_FZA_SHA 0x0300001D + #if 0 /* Because it clashes with KRB5, is never used any more, and is safe + to remove according to David Hopwood + of the ietf-tls list */ + #define SSL3_CK_FZA_DMS_RC4_SHA 0x0300001E + #endif +#endif + +/* VRS Additional Kerberos5 entries + */ +#define SSL3_CK_KRB5_DES_64_CBC_SHA 0x0300001E +#define SSL3_CK_KRB5_DES_192_CBC3_SHA 0x0300001F +#define SSL3_CK_KRB5_RC4_128_SHA 0x03000020 +#define SSL3_CK_KRB5_IDEA_128_CBC_SHA 0x03000021 +#define SSL3_CK_KRB5_DES_64_CBC_MD5 0x03000022 +#define SSL3_CK_KRB5_DES_192_CBC3_MD5 0x03000023 +#define SSL3_CK_KRB5_RC4_128_MD5 0x03000024 +#define SSL3_CK_KRB5_IDEA_128_CBC_MD5 0x03000025 + +#define SSL3_CK_KRB5_DES_40_CBC_SHA 0x03000026 +#define SSL3_CK_KRB5_RC2_40_CBC_SHA 0x03000027 +#define SSL3_CK_KRB5_RC4_40_SHA 0x03000028 +#define SSL3_CK_KRB5_DES_40_CBC_MD5 0x03000029 +#define SSL3_CK_KRB5_RC2_40_CBC_MD5 0x0300002A +#define SSL3_CK_KRB5_RC4_40_MD5 0x0300002B + +#define SSL3_TXT_RSA_NULL_MD5 "NULL-MD5" +#define SSL3_TXT_RSA_NULL_SHA "NULL-SHA" +#define SSL3_TXT_RSA_RC4_40_MD5 "EXP-RC4-MD5" +#define SSL3_TXT_RSA_RC4_128_MD5 "RC4-MD5" +#define SSL3_TXT_RSA_RC4_128_SHA "RC4-SHA" +#define SSL3_TXT_RSA_RC2_40_MD5 "EXP-RC2-CBC-MD5" +#define SSL3_TXT_RSA_IDEA_128_SHA "IDEA-CBC-SHA" +#define SSL3_TXT_RSA_DES_40_CBC_SHA "EXP-DES-CBC-SHA" +#define SSL3_TXT_RSA_DES_64_CBC_SHA "DES-CBC-SHA" +#define SSL3_TXT_RSA_DES_192_CBC3_SHA "DES-CBC3-SHA" + +#define SSL3_TXT_DH_DSS_DES_40_CBC_SHA "EXP-DH-DSS-DES-CBC-SHA" +#define SSL3_TXT_DH_DSS_DES_64_CBC_SHA "DH-DSS-DES-CBC-SHA" +#define SSL3_TXT_DH_DSS_DES_192_CBC3_SHA "DH-DSS-DES-CBC3-SHA" +#define SSL3_TXT_DH_RSA_DES_40_CBC_SHA "EXP-DH-RSA-DES-CBC-SHA" +#define SSL3_TXT_DH_RSA_DES_64_CBC_SHA "DH-RSA-DES-CBC-SHA" +#define SSL3_TXT_DH_RSA_DES_192_CBC3_SHA "DH-RSA-DES-CBC3-SHA" + +#define SSL3_TXT_EDH_DSS_DES_40_CBC_SHA "EXP-EDH-DSS-DES-CBC-SHA" +#define SSL3_TXT_EDH_DSS_DES_64_CBC_SHA "EDH-DSS-DES-CBC-SHA" +#define SSL3_TXT_EDH_DSS_DES_192_CBC3_SHA "EDH-DSS-DES-CBC3-SHA" +#define SSL3_TXT_EDH_RSA_DES_40_CBC_SHA "EXP-EDH-RSA-DES-CBC-SHA" +#define SSL3_TXT_EDH_RSA_DES_64_CBC_SHA "EDH-RSA-DES-CBC-SHA" +#define SSL3_TXT_EDH_RSA_DES_192_CBC3_SHA "EDH-RSA-DES-CBC3-SHA" + +#define SSL3_TXT_ADH_RC4_40_MD5 "EXP-ADH-RC4-MD5" +#define SSL3_TXT_ADH_RC4_128_MD5 "ADH-RC4-MD5" +#define SSL3_TXT_ADH_DES_40_CBC_SHA "EXP-ADH-DES-CBC-SHA" +#define SSL3_TXT_ADH_DES_64_CBC_SHA "ADH-DES-CBC-SHA" +#define SSL3_TXT_ADH_DES_192_CBC_SHA "ADH-DES-CBC3-SHA" + +#if 0 + #define SSL3_TXT_FZA_DMS_NULL_SHA "FZA-NULL-SHA" + #define SSL3_TXT_FZA_DMS_FZA_SHA "FZA-FZA-CBC-SHA" + #define SSL3_TXT_FZA_DMS_RC4_SHA "FZA-RC4-SHA" +#endif + +#define SSL3_TXT_KRB5_DES_64_CBC_SHA "KRB5-DES-CBC-SHA" +#define SSL3_TXT_KRB5_DES_192_CBC3_SHA "KRB5-DES-CBC3-SHA" +#define SSL3_TXT_KRB5_RC4_128_SHA "KRB5-RC4-SHA" +#define SSL3_TXT_KRB5_IDEA_128_CBC_SHA "KRB5-IDEA-CBC-SHA" +#define SSL3_TXT_KRB5_DES_64_CBC_MD5 "KRB5-DES-CBC-MD5" +#define SSL3_TXT_KRB5_DES_192_CBC3_MD5 "KRB5-DES-CBC3-MD5" +#define SSL3_TXT_KRB5_RC4_128_MD5 "KRB5-RC4-MD5" +#define SSL3_TXT_KRB5_IDEA_128_CBC_MD5 "KRB5-IDEA-CBC-MD5" + +#define SSL3_TXT_KRB5_DES_40_CBC_SHA "EXP-KRB5-DES-CBC-SHA" +#define SSL3_TXT_KRB5_RC2_40_CBC_SHA "EXP-KRB5-RC2-CBC-SHA" +#define SSL3_TXT_KRB5_RC4_40_SHA "EXP-KRB5-RC4-SHA" +#define SSL3_TXT_KRB5_DES_40_CBC_MD5 "EXP-KRB5-DES-CBC-MD5" +#define SSL3_TXT_KRB5_RC2_40_CBC_MD5 "EXP-KRB5-RC2-CBC-MD5" +#define SSL3_TXT_KRB5_RC4_40_MD5 "EXP-KRB5-RC4-MD5" + +#define SSL3_SSL_SESSION_ID_LENGTH 32 +#define SSL3_MAX_SSL_SESSION_ID_LENGTH 32 + +#define SSL3_MASTER_SECRET_SIZE 48 +#define SSL3_RANDOM_SIZE 32 +#define SSL3_SESSION_ID_SIZE 32 +#define SSL3_RT_HEADER_LENGTH 5 + +#ifndef SSL3_ALIGN_PAYLOAD + /* Some will argue that this increases memory footprint, but it's + * not actually true. Point is that malloc has to return at least + * 64-bit aligned pointers, meaning that allocating 5 bytes wastes + * 3 bytes in either case. Suggested pre-gaping simply moves these + * wasted bytes from the end of allocated region to its front, + * but makes data payload aligned, which improves performance:-) */ +# define SSL3_ALIGN_PAYLOAD 8 +#else +# if (SSL3_ALIGN_PAYLOAD&(SSL3_ALIGN_PAYLOAD-1))!=0 +# error "insane SSL3_ALIGN_PAYLOAD" +# undef SSL3_ALIGN_PAYLOAD +# endif +#endif + +/* This is the maximum MAC (digest) size used by the SSL library. + * Currently maximum of 20 is used by SHA1, but we reserve for + * future extension for 512-bit hashes. + */ + +#define SSL3_RT_MAX_MD_SIZE 64 + +/* Maximum block size used in all ciphersuites. Currently 16 for AES. + */ + +#define SSL_RT_MAX_CIPHER_BLOCK_SIZE 16 + +#define SSL3_RT_MAX_EXTRA (16384) + +/* Default buffer length used for writen records. Thus a generated record + * will contain plaintext no larger than this value. */ +#define SSL3_RT_DEFAULT_PLAIN_LENGTH 2048 +/* Maximum plaintext length: defined by SSL/TLS standards */ +#define SSL3_RT_MAX_PLAIN_LENGTH 16384 +/* Maximum compression overhead: defined by SSL/TLS standards */ +#define SSL3_RT_MAX_COMPRESSED_OVERHEAD 1024 + +/* The standards give a maximum encryption overhead of 1024 bytes. + * In practice the value is lower than this. The overhead is the maximum + * number of padding bytes (256) plus the mac size. + */ +#define SSL3_RT_MAX_ENCRYPTED_OVERHEAD (256 + SSL3_RT_MAX_MD_SIZE) + +/* OpenSSL currently only uses a padding length of at most one block so + * the send overhead is smaller. + */ + +#define SSL3_RT_SEND_MAX_ENCRYPTED_OVERHEAD \ + (SSL_RT_MAX_CIPHER_BLOCK_SIZE + SSL3_RT_MAX_MD_SIZE) + +/* If compression isn't used don't include the compression overhead */ + +#ifdef OPENSSL_NO_COMP +#define SSL3_RT_MAX_COMPRESSED_LENGTH SSL3_RT_MAX_PLAIN_LENGTH +#else +#define SSL3_RT_MAX_COMPRESSED_LENGTH \ + (SSL3_RT_MAX_PLAIN_LENGTH+SSL3_RT_MAX_COMPRESSED_OVERHEAD) +#endif +#define SSL3_RT_MAX_ENCRYPTED_LENGTH \ + (SSL3_RT_MAX_ENCRYPTED_OVERHEAD+SSL3_RT_MAX_COMPRESSED_LENGTH) +#define SSL3_RT_MAX_PACKET_SIZE \ + (SSL3_RT_MAX_ENCRYPTED_LENGTH+SSL3_RT_HEADER_LENGTH) + +/* Extra space for empty fragment, headers, MAC, and padding. */ +#define SSL3_RT_DEFAULT_WRITE_OVERHEAD 256 +#define SSL3_RT_DEFAULT_PACKET_SIZE 4096 - SSL3_RT_DEFAULT_WRITE_OVERHEAD +#if SSL3_RT_DEFAULT_PLAIN_LENGTH + SSL3_RT_DEFAULT_WRITE_OVERHEAD > SSL3_RT_DEFAULT_PACKET_SIZE +#error "Insufficient space allocated for write buffers." +#endif + +#define SSL3_MD_CLIENT_FINISHED_CONST "\x43\x4C\x4E\x54" +#define SSL3_MD_SERVER_FINISHED_CONST "\x53\x52\x56\x52" + +#define SSL3_VERSION 0x0300 +#define SSL3_VERSION_MAJOR 0x03 +#define SSL3_VERSION_MINOR 0x00 + +#define SSL3_RT_CHANGE_CIPHER_SPEC 20 +#define SSL3_RT_ALERT 21 +#define SSL3_RT_HANDSHAKE 22 +#define SSL3_RT_APPLICATION_DATA 23 + +#define SSL3_AL_WARNING 1 +#define SSL3_AL_FATAL 2 + +#define SSL3_AD_CLOSE_NOTIFY 0 +#define SSL3_AD_UNEXPECTED_MESSAGE 10 /* fatal */ +#define SSL3_AD_BAD_RECORD_MAC 20 /* fatal */ +#define SSL3_AD_DECOMPRESSION_FAILURE 30 /* fatal */ +#define SSL3_AD_HANDSHAKE_FAILURE 40 /* fatal */ +#define SSL3_AD_NO_CERTIFICATE 41 +#define SSL3_AD_BAD_CERTIFICATE 42 +#define SSL3_AD_UNSUPPORTED_CERTIFICATE 43 +#define SSL3_AD_CERTIFICATE_REVOKED 44 +#define SSL3_AD_CERTIFICATE_EXPIRED 45 +#define SSL3_AD_CERTIFICATE_UNKNOWN 46 +#define SSL3_AD_ILLEGAL_PARAMETER 47 /* fatal */ + +typedef struct ssl3_record_st + { +/*r */ int type; /* type of record */ +/*rw*/ unsigned int length; /* How many bytes available */ +/*r */ unsigned int off; /* read/write offset into 'buf' */ +/*rw*/ unsigned char *data; /* pointer to the record data */ +/*rw*/ unsigned char *input; /* where the decode bytes are */ +/*r */ unsigned char *comp; /* only used with decompression - malloc()ed */ +/*r */ unsigned long epoch; /* epoch number, needed by DTLS1 */ +/*r */ unsigned char seq_num[8]; /* sequence number, needed by DTLS1 */ + } SSL3_RECORD; + +typedef struct ssl3_buffer_st + { + unsigned char *buf; /* at least SSL3_RT_MAX_PACKET_SIZE bytes, + * see ssl3_setup_buffers() */ + size_t len; /* buffer size */ + int offset; /* where to 'copy from' */ + int left; /* how many bytes left */ + } SSL3_BUFFER; + +#define SSL3_CT_RSA_SIGN 1 +#define SSL3_CT_DSS_SIGN 2 +#define SSL3_CT_RSA_FIXED_DH 3 +#define SSL3_CT_DSS_FIXED_DH 4 +#define SSL3_CT_RSA_EPHEMERAL_DH 5 +#define SSL3_CT_DSS_EPHEMERAL_DH 6 +#define SSL3_CT_FORTEZZA_DMS 20 +/* SSL3_CT_NUMBER is used to size arrays and it must be large + * enough to contain all of the cert types defined either for + * SSLv3 and TLSv1. + */ +#define SSL3_CT_NUMBER 9 + + +#define SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS 0x0001 +#define SSL3_FLAGS_DELAY_CLIENT_FINISHED 0x0002 +#define SSL3_FLAGS_POP_BUFFER 0x0004 +#define TLS1_FLAGS_TLS_PADDING_BUG 0x0008 +#define TLS1_FLAGS_SKIP_CERT_VERIFY 0x0010 + +/* SSL3_FLAGS_SGC_RESTART_DONE is set when we + * restart a handshake because of MS SGC and so prevents us + * from restarting the handshake in a loop. It's reset on a + * renegotiation, so effectively limits the client to one restart + * per negotiation. This limits the possibility of a DDoS + * attack where the client handshakes in a loop using SGC to + * restart. Servers which permit renegotiation can still be + * effected, but we can't prevent that. + */ +#define SSL3_FLAGS_SGC_RESTART_DONE 0x0040 + +typedef struct ssl3_state_st + { + long flags; + int delay_buf_pop_ret; + + unsigned char read_sequence[8]; + int read_mac_secret_size; + unsigned char read_mac_secret[EVP_MAX_MD_SIZE]; + unsigned char write_sequence[8]; + int write_mac_secret_size; + unsigned char write_mac_secret[EVP_MAX_MD_SIZE]; + + unsigned char server_random[SSL3_RANDOM_SIZE]; + unsigned char client_random[SSL3_RANDOM_SIZE]; + + /* flags for countermeasure against known-IV weakness */ + int need_empty_fragments; + int empty_fragment_done; + + /* The value of 'extra' when the buffers were initialized */ + int init_extra; + + SSL3_BUFFER rbuf; /* read IO goes into here */ + SSL3_BUFFER wbuf; /* write IO goes into here */ + + SSL3_RECORD rrec; /* each decoded record goes in here */ + SSL3_RECORD wrec; /* goes out from here */ + + /* storage for Alert/Handshake protocol data received but not + * yet processed by ssl3_read_bytes: */ + unsigned char alert_fragment[2]; + unsigned int alert_fragment_len; + unsigned char handshake_fragment[4]; + unsigned int handshake_fragment_len; + + /* partial write - check the numbers match */ + unsigned int wnum; /* number of bytes sent so far */ + int wpend_tot; /* number bytes written */ + int wpend_type; + int wpend_ret; /* number of bytes submitted */ + const unsigned char *wpend_buf; + + /* used during startup, digest all incoming/outgoing packets */ + BIO *handshake_buffer; + /* When set of handshake digests is determined, buffer is hashed + * and freed and MD_CTX-es for all required digests are stored in + * this array */ + EVP_MD_CTX **handshake_dgst; + /* this is set whenerver we see a change_cipher_spec message + * come in when we are not looking for one */ + int change_cipher_spec; + + int warn_alert; + int fatal_alert; + /* we allow one fatal and one warning alert to be outstanding, + * send close alert via the warning alert */ + int alert_dispatch; + unsigned char send_alert[2]; + + /* This flag is set when we should renegotiate ASAP, basically when + * there is no more data in the read or write buffers */ + int renegotiate; + int total_renegotiations; + int num_renegotiations; + + int in_read_app_data; + + /* Opaque PRF input as used for the current handshake. + * These fields are used only if TLSEXT_TYPE_opaque_prf_input is defined + * (otherwise, they are merely present to improve binary compatibility) */ + void *client_opaque_prf_input; + size_t client_opaque_prf_input_len; + void *server_opaque_prf_input; + size_t server_opaque_prf_input_len; + +#ifndef OPENSSL_NO_NEXTPROTONEG + /* Set if we saw the Next Protocol Negotiation extension from + our peer. */ + int next_proto_neg_seen; +#endif + + struct { + /* actually only needs to be 16+20 */ + unsigned char cert_verify_md[EVP_MAX_MD_SIZE*2]; + + /* actually only need to be 16+20 for SSLv3 and 12 for TLS */ + unsigned char finish_md[EVP_MAX_MD_SIZE*2]; + int finish_md_len; + unsigned char peer_finish_md[EVP_MAX_MD_SIZE*2]; + int peer_finish_md_len; + + unsigned long message_size; + int message_type; + + /* used to hold the new cipher we are going to use */ + const SSL_CIPHER *new_cipher; +#ifndef OPENSSL_NO_DH + DH *dh; +#endif + +#ifndef OPENSSL_NO_ECDH + EC_KEY *ecdh; /* holds short lived ECDH key */ +#endif + + /* used when SSL_ST_FLUSH_DATA is entered */ + int next_state; + + int reuse_message; + + /* used for certificate requests */ + int cert_req; + int ctype_num; + char ctype[SSL3_CT_NUMBER]; + STACK_OF(X509_NAME) *ca_names; + + int use_rsa_tmp; + + int key_block_length; + unsigned char *key_block; + + const EVP_CIPHER *new_sym_enc; + const EVP_MD *new_hash; + int new_mac_pkey_type; + int new_mac_secret_size; +#ifndef OPENSSL_NO_COMP + const SSL_COMP *new_compression; +#else + char *new_compression; +#endif + int cert_request; + } tmp; + + /* Connection binding to prevent renegotiation attacks */ + unsigned char previous_client_finished[EVP_MAX_MD_SIZE]; + unsigned char previous_client_finished_len; + unsigned char previous_server_finished[EVP_MAX_MD_SIZE]; + unsigned char previous_server_finished_len; + int send_connection_binding; /* TODOEKR */ + } SSL3_STATE; + + +/* SSLv3 */ +/*client */ +/* extra state */ +#define SSL3_ST_CW_FLUSH (0x100|SSL_ST_CONNECT) +#define SSL3_ST_CUTTHROUGH_COMPLETE (0x101|SSL_ST_CONNECT) +/* write to server */ +#define SSL3_ST_CW_CLNT_HELLO_A (0x110|SSL_ST_CONNECT) +#define SSL3_ST_CW_CLNT_HELLO_B (0x111|SSL_ST_CONNECT) +/* read from server */ +#define SSL3_ST_CR_SRVR_HELLO_A (0x120|SSL_ST_CONNECT) +#define SSL3_ST_CR_SRVR_HELLO_B (0x121|SSL_ST_CONNECT) +#define DTLS1_ST_CR_HELLO_VERIFY_REQUEST_A (0x126|SSL_ST_CONNECT) +#define DTLS1_ST_CR_HELLO_VERIFY_REQUEST_B (0x127|SSL_ST_CONNECT) +#define SSL3_ST_CR_CERT_A (0x130|SSL_ST_CONNECT) +#define SSL3_ST_CR_CERT_B (0x131|SSL_ST_CONNECT) +#define SSL3_ST_CR_KEY_EXCH_A (0x140|SSL_ST_CONNECT) +#define SSL3_ST_CR_KEY_EXCH_B (0x141|SSL_ST_CONNECT) +#define SSL3_ST_CR_CERT_REQ_A (0x150|SSL_ST_CONNECT) +#define SSL3_ST_CR_CERT_REQ_B (0x151|SSL_ST_CONNECT) +#define SSL3_ST_CR_SRVR_DONE_A (0x160|SSL_ST_CONNECT) +#define SSL3_ST_CR_SRVR_DONE_B (0x161|SSL_ST_CONNECT) +/* write to server */ +#define SSL3_ST_CW_CERT_A (0x170|SSL_ST_CONNECT) +#define SSL3_ST_CW_CERT_B (0x171|SSL_ST_CONNECT) +#define SSL3_ST_CW_CERT_C (0x172|SSL_ST_CONNECT) +#define SSL3_ST_CW_CERT_D (0x173|SSL_ST_CONNECT) +#define SSL3_ST_CW_KEY_EXCH_A (0x180|SSL_ST_CONNECT) +#define SSL3_ST_CW_KEY_EXCH_B (0x181|SSL_ST_CONNECT) +#define SSL3_ST_CW_CERT_VRFY_A (0x190|SSL_ST_CONNECT) +#define SSL3_ST_CW_CERT_VRFY_B (0x191|SSL_ST_CONNECT) +#define SSL3_ST_CW_CHANGE_A (0x1A0|SSL_ST_CONNECT) +#define SSL3_ST_CW_CHANGE_B (0x1A1|SSL_ST_CONNECT) +#ifndef OPENSSL_NO_NEXTPROTONEG +#define SSL3_ST_CW_NEXT_PROTO_A (0x200|SSL_ST_CONNECT) +#define SSL3_ST_CW_NEXT_PROTO_B (0x201|SSL_ST_CONNECT) +#endif +#define SSL3_ST_CW_FINISHED_A (0x1B0|SSL_ST_CONNECT) +#define SSL3_ST_CW_FINISHED_B (0x1B1|SSL_ST_CONNECT) +/* read from server */ +#define SSL3_ST_CR_CHANGE_A (0x1C0|SSL_ST_CONNECT) +#define SSL3_ST_CR_CHANGE_B (0x1C1|SSL_ST_CONNECT) +#define SSL3_ST_CR_FINISHED_A (0x1D0|SSL_ST_CONNECT) +#define SSL3_ST_CR_FINISHED_B (0x1D1|SSL_ST_CONNECT) +#define SSL3_ST_CR_SESSION_TICKET_A (0x1E0|SSL_ST_CONNECT) +#define SSL3_ST_CR_SESSION_TICKET_B (0x1E1|SSL_ST_CONNECT) +#define SSL3_ST_CR_CERT_STATUS_A (0x1F0|SSL_ST_CONNECT) +#define SSL3_ST_CR_CERT_STATUS_B (0x1F1|SSL_ST_CONNECT) + +/* server */ +/* extra state */ +#define SSL3_ST_SW_FLUSH (0x100|SSL_ST_ACCEPT) +/* read from client */ +/* Do not change the number values, they do matter */ +#define SSL3_ST_SR_CLNT_HELLO_A (0x110|SSL_ST_ACCEPT) +#define SSL3_ST_SR_CLNT_HELLO_B (0x111|SSL_ST_ACCEPT) +#define SSL3_ST_SR_CLNT_HELLO_C (0x112|SSL_ST_ACCEPT) +/* write to client */ +#define DTLS1_ST_SW_HELLO_VERIFY_REQUEST_A (0x113|SSL_ST_ACCEPT) +#define DTLS1_ST_SW_HELLO_VERIFY_REQUEST_B (0x114|SSL_ST_ACCEPT) +#define SSL3_ST_SW_HELLO_REQ_A (0x120|SSL_ST_ACCEPT) +#define SSL3_ST_SW_HELLO_REQ_B (0x121|SSL_ST_ACCEPT) +#define SSL3_ST_SW_HELLO_REQ_C (0x122|SSL_ST_ACCEPT) +#define SSL3_ST_SW_SRVR_HELLO_A (0x130|SSL_ST_ACCEPT) +#define SSL3_ST_SW_SRVR_HELLO_B (0x131|SSL_ST_ACCEPT) +#define SSL3_ST_SW_CERT_A (0x140|SSL_ST_ACCEPT) +#define SSL3_ST_SW_CERT_B (0x141|SSL_ST_ACCEPT) +#define SSL3_ST_SW_KEY_EXCH_A (0x150|SSL_ST_ACCEPT) +#define SSL3_ST_SW_KEY_EXCH_B (0x151|SSL_ST_ACCEPT) +#define SSL3_ST_SW_CERT_REQ_A (0x160|SSL_ST_ACCEPT) +#define SSL3_ST_SW_CERT_REQ_B (0x161|SSL_ST_ACCEPT) +#define SSL3_ST_SW_SRVR_DONE_A (0x170|SSL_ST_ACCEPT) +#define SSL3_ST_SW_SRVR_DONE_B (0x171|SSL_ST_ACCEPT) +/* read from client */ +#define SSL3_ST_SR_CERT_A (0x180|SSL_ST_ACCEPT) +#define SSL3_ST_SR_CERT_B (0x181|SSL_ST_ACCEPT) +#define SSL3_ST_SR_KEY_EXCH_A (0x190|SSL_ST_ACCEPT) +#define SSL3_ST_SR_KEY_EXCH_B (0x191|SSL_ST_ACCEPT) +#define SSL3_ST_SR_CERT_VRFY_A (0x1A0|SSL_ST_ACCEPT) +#define SSL3_ST_SR_CERT_VRFY_B (0x1A1|SSL_ST_ACCEPT) +#define SSL3_ST_SR_CHANGE_A (0x1B0|SSL_ST_ACCEPT) +#define SSL3_ST_SR_CHANGE_B (0x1B1|SSL_ST_ACCEPT) +#ifndef OPENSSL_NO_NEXTPROTONEG +#define SSL3_ST_SR_NEXT_PROTO_A (0x210|SSL_ST_ACCEPT) +#define SSL3_ST_SR_NEXT_PROTO_B (0x211|SSL_ST_ACCEPT) +#endif +#define SSL3_ST_SR_FINISHED_A (0x1C0|SSL_ST_ACCEPT) +#define SSL3_ST_SR_FINISHED_B (0x1C1|SSL_ST_ACCEPT) +/* write to client */ +#define SSL3_ST_SW_CHANGE_A (0x1D0|SSL_ST_ACCEPT) +#define SSL3_ST_SW_CHANGE_B (0x1D1|SSL_ST_ACCEPT) +#define SSL3_ST_SW_FINISHED_A (0x1E0|SSL_ST_ACCEPT) +#define SSL3_ST_SW_FINISHED_B (0x1E1|SSL_ST_ACCEPT) +#define SSL3_ST_SW_SESSION_TICKET_A (0x1F0|SSL_ST_ACCEPT) +#define SSL3_ST_SW_SESSION_TICKET_B (0x1F1|SSL_ST_ACCEPT) +#define SSL3_ST_SW_CERT_STATUS_A (0x200|SSL_ST_ACCEPT) +#define SSL3_ST_SW_CERT_STATUS_B (0x201|SSL_ST_ACCEPT) + +#define SSL3_MT_HELLO_REQUEST 0 +#define SSL3_MT_CLIENT_HELLO 1 +#define SSL3_MT_SERVER_HELLO 2 +#define SSL3_MT_NEWSESSION_TICKET 4 +#define SSL3_MT_CERTIFICATE 11 +#define SSL3_MT_SERVER_KEY_EXCHANGE 12 +#define SSL3_MT_CERTIFICATE_REQUEST 13 +#define SSL3_MT_SERVER_DONE 14 +#define SSL3_MT_CERTIFICATE_VERIFY 15 +#define SSL3_MT_CLIENT_KEY_EXCHANGE 16 +#define SSL3_MT_FINISHED 20 +#define SSL3_MT_CERTIFICATE_STATUS 22 +#ifndef OPENSSL_NO_NEXTPROTONEG +#define SSL3_MT_NEXT_PROTO 67 +#endif +#define DTLS1_MT_HELLO_VERIFY_REQUEST 3 + + +#define SSL3_MT_CCS 1 + +/* These are used when changing over to a new cipher */ +#define SSL3_CC_READ 0x01 +#define SSL3_CC_WRITE 0x02 +#define SSL3_CC_CLIENT 0x10 +#define SSL3_CC_SERVER 0x20 +#define SSL3_CHANGE_CIPHER_CLIENT_WRITE (SSL3_CC_CLIENT|SSL3_CC_WRITE) +#define SSL3_CHANGE_CIPHER_SERVER_READ (SSL3_CC_SERVER|SSL3_CC_READ) +#define SSL3_CHANGE_CIPHER_CLIENT_READ (SSL3_CC_CLIENT|SSL3_CC_READ) +#define SSL3_CHANGE_CIPHER_SERVER_WRITE (SSL3_CC_SERVER|SSL3_CC_WRITE) + +#ifdef __cplusplus +} +#endif +#endif diff --git a/node-v0.8.14/deps/openssl/openssl/ssl/ssl_algs.c b/node-v0.8.14/deps/openssl/openssl/ssl/ssl_algs.c new file mode 100644 index 0000000..0967b2d --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/ssl/ssl_algs.c @@ -0,0 +1,140 @@ +/* ssl/ssl_algs.c */ +/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com) + * All rights reserved. + * + * This package is an SSL implementation written + * by Eric Young (eay@cryptsoft.com). + * The implementation was written so as to conform with Netscapes SSL. + * + * This library is free for commercial and non-commercial use as long as + * the following conditions are aheared to. The following conditions + * apply to all code found in this distribution, be it the RC4, RSA, + * lhash, DES, etc., code; not just the SSL code. The SSL documentation + * included with this distribution is covered by the same copyright terms + * except that the holder is Tim Hudson (tjh@cryptsoft.com). + * + * Copyright remains Eric Young's, and as such any Copyright notices in + * the code are not to be removed. + * If this package is used in a product, Eric Young should be given attribution + * as the author of the parts of the library used. + * This can be in the form of a textual message at program startup or + * in documentation (online or textual) provided with the package. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * "This product includes cryptographic software written by + * Eric Young (eay@cryptsoft.com)" + * The word 'cryptographic' can be left out if the rouines from the library + * being used are not cryptographic related :-). + * 4. If you include any Windows specific code (or a derivative thereof) from + * the apps directory (application code) you must include an acknowledgement: + * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)" + * + * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * + * The licence and distribution terms for any publically available version or + * derivative of this code cannot be changed. i.e. this code cannot simply be + * copied and put under another distribution licence + * [including the GNU Public Licence.] + */ + +#include +#include +#include +#include "ssl_locl.h" + +int SSL_library_init(void) + { + +#ifndef OPENSSL_NO_DES + EVP_add_cipher(EVP_des_cbc()); + EVP_add_cipher(EVP_des_ede3_cbc()); +#endif +#ifndef OPENSSL_NO_IDEA + EVP_add_cipher(EVP_idea_cbc()); +#endif +#ifndef OPENSSL_NO_RC4 + EVP_add_cipher(EVP_rc4()); +#endif +#ifndef OPENSSL_NO_RC2 + EVP_add_cipher(EVP_rc2_cbc()); + /* Not actually used for SSL/TLS but this makes PKCS#12 work + * if an application only calls SSL_library_init(). + */ + EVP_add_cipher(EVP_rc2_40_cbc()); +#endif +#ifndef OPENSSL_NO_AES + EVP_add_cipher(EVP_aes_128_cbc()); + EVP_add_cipher(EVP_aes_192_cbc()); + EVP_add_cipher(EVP_aes_256_cbc()); +#endif +#ifndef OPENSSL_NO_CAMELLIA + EVP_add_cipher(EVP_camellia_128_cbc()); + EVP_add_cipher(EVP_camellia_256_cbc()); +#endif + +#ifndef OPENSSL_NO_SEED + EVP_add_cipher(EVP_seed_cbc()); +#endif + +#ifndef OPENSSL_NO_MD5 + EVP_add_digest(EVP_md5()); + EVP_add_digest_alias(SN_md5,"ssl2-md5"); + EVP_add_digest_alias(SN_md5,"ssl3-md5"); +#endif +#ifndef OPENSSL_NO_SHA + EVP_add_digest(EVP_sha1()); /* RSA with sha1 */ + EVP_add_digest_alias(SN_sha1,"ssl3-sha1"); + EVP_add_digest_alias(SN_sha1WithRSAEncryption,SN_sha1WithRSA); +#endif +#ifndef OPENSSL_NO_SHA256 + EVP_add_digest(EVP_sha224()); + EVP_add_digest(EVP_sha256()); +#endif +#ifndef OPENSSL_NO_SHA512 + EVP_add_digest(EVP_sha384()); + EVP_add_digest(EVP_sha512()); +#endif +#if !defined(OPENSSL_NO_SHA) && !defined(OPENSSL_NO_DSA) + EVP_add_digest(EVP_dss1()); /* DSA with sha1 */ + EVP_add_digest_alias(SN_dsaWithSHA1,SN_dsaWithSHA1_2); + EVP_add_digest_alias(SN_dsaWithSHA1,"DSS1"); + EVP_add_digest_alias(SN_dsaWithSHA1,"dss1"); +#endif +#ifndef OPENSSL_NO_ECDSA + EVP_add_digest(EVP_ecdsa()); +#endif + /* If you want support for phased out ciphers, add the following */ +#if 0 + EVP_add_digest(EVP_sha()); + EVP_add_digest(EVP_dss()); +#endif +#ifndef OPENSSL_NO_COMP + /* This will initialise the built-in compression algorithms. + The value returned is a STACK_OF(SSL_COMP), but that can + be discarded safely */ + (void)SSL_COMP_get_compression_methods(); +#endif + /* initialize cipher/digest methods table */ + ssl_load_ciphers(); + return(1); + } + diff --git a/node-v0.8.14/deps/openssl/openssl/ssl/ssl_asn1.c b/node-v0.8.14/deps/openssl/openssl/ssl/ssl_asn1.c new file mode 100644 index 0000000..d7f4c60 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/ssl/ssl_asn1.c @@ -0,0 +1,592 @@ +/* ssl/ssl_asn1.c */ +/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com) + * All rights reserved. + * + * This package is an SSL implementation written + * by Eric Young (eay@cryptsoft.com). + * The implementation was written so as to conform with Netscapes SSL. + * + * This library is free for commercial and non-commercial use as long as + * the following conditions are aheared to. The following conditions + * apply to all code found in this distribution, be it the RC4, RSA, + * lhash, DES, etc., code; not just the SSL code. The SSL documentation + * included with this distribution is covered by the same copyright terms + * except that the holder is Tim Hudson (tjh@cryptsoft.com). + * + * Copyright remains Eric Young's, and as such any Copyright notices in + * the code are not to be removed. + * If this package is used in a product, Eric Young should be given attribution + * as the author of the parts of the library used. + * This can be in the form of a textual message at program startup or + * in documentation (online or textual) provided with the package. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * "This product includes cryptographic software written by + * Eric Young (eay@cryptsoft.com)" + * The word 'cryptographic' can be left out if the rouines from the library + * being used are not cryptographic related :-). + * 4. If you include any Windows specific code (or a derivative thereof) from + * the apps directory (application code) you must include an acknowledgement: + * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)" + * + * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * + * The licence and distribution terms for any publically available version or + * derivative of this code cannot be changed. i.e. this code cannot simply be + * copied and put under another distribution licence + * [including the GNU Public Licence.] + */ +/* ==================================================================== + * Copyright 2005 Nokia. All rights reserved. + * + * The portions of the attached software ("Contribution") is developed by + * Nokia Corporation and is licensed pursuant to the OpenSSL open source + * license. + * + * The Contribution, originally written by Mika Kousa and Pasi Eronen of + * Nokia Corporation, consists of the "PSK" (Pre-Shared Key) ciphersuites + * support (see RFC 4279) to OpenSSL. + * + * No patent licenses or other rights except those expressly stated in + * the OpenSSL open source license shall be deemed granted or received + * expressly, by implication, estoppel, or otherwise. + * + * No assurances are provided by Nokia that the Contribution does not + * infringe the patent or other intellectual property rights of any third + * party or that the license provides you with all the necessary rights + * to make use of the Contribution. + * + * THE SOFTWARE IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND. IN + * ADDITION TO THE DISCLAIMERS INCLUDED IN THE LICENSE, NOKIA + * SPECIFICALLY DISCLAIMS ANY LIABILITY FOR CLAIMS BROUGHT BY YOU OR ANY + * OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL PROPERTY RIGHTS OR + * OTHERWISE. + */ + +#include +#include +#include "ssl_locl.h" +#include +#include +#include + +typedef struct ssl_session_asn1_st + { + ASN1_INTEGER version; + ASN1_INTEGER ssl_version; + ASN1_OCTET_STRING cipher; + ASN1_OCTET_STRING comp_id; + ASN1_OCTET_STRING master_key; + ASN1_OCTET_STRING session_id; + ASN1_OCTET_STRING session_id_context; + ASN1_OCTET_STRING key_arg; +#ifndef OPENSSL_NO_KRB5 + ASN1_OCTET_STRING krb5_princ; +#endif /* OPENSSL_NO_KRB5 */ + ASN1_INTEGER time; + ASN1_INTEGER timeout; + ASN1_INTEGER verify_result; +#ifndef OPENSSL_NO_TLSEXT + ASN1_OCTET_STRING tlsext_hostname; + ASN1_INTEGER tlsext_tick_lifetime; + ASN1_OCTET_STRING tlsext_tick; +#endif /* OPENSSL_NO_TLSEXT */ +#ifndef OPENSSL_NO_PSK + ASN1_OCTET_STRING psk_identity_hint; + ASN1_OCTET_STRING psk_identity; +#endif /* OPENSSL_NO_PSK */ + } SSL_SESSION_ASN1; + +int i2d_SSL_SESSION(SSL_SESSION *in, unsigned char **pp) + { +#define LSIZE2 (sizeof(long)*2) + int v1=0,v2=0,v3=0,v4=0,v5=0,v7=0,v8=0; + unsigned char buf[4],ibuf1[LSIZE2],ibuf2[LSIZE2]; + unsigned char ibuf3[LSIZE2],ibuf4[LSIZE2],ibuf5[LSIZE2]; +#ifndef OPENSSL_NO_TLSEXT + int v6=0,v9=0,v10=0; + unsigned char ibuf6[LSIZE2]; +#endif +#ifndef OPENSSL_NO_COMP + unsigned char cbuf; + int v11=0; +#endif + long l; + SSL_SESSION_ASN1 a; + M_ASN1_I2D_vars(in); + + if ((in == NULL) || ((in->cipher == NULL) && (in->cipher_id == 0))) + return(0); + + /* Note that I cheat in the following 2 assignments. I know + * that if the ASN1_INTEGER passed to ASN1_INTEGER_set + * is > sizeof(long)+1, the buffer will not be re-OPENSSL_malloc()ed. + * This is a bit evil but makes things simple, no dynamic allocation + * to clean up :-) */ + a.version.length=LSIZE2; + a.version.type=V_ASN1_INTEGER; + a.version.data=ibuf1; + ASN1_INTEGER_set(&(a.version),SSL_SESSION_ASN1_VERSION); + + a.ssl_version.length=LSIZE2; + a.ssl_version.type=V_ASN1_INTEGER; + a.ssl_version.data=ibuf2; + ASN1_INTEGER_set(&(a.ssl_version),in->ssl_version); + + a.cipher.type=V_ASN1_OCTET_STRING; + a.cipher.data=buf; + + if (in->cipher == NULL) + l=in->cipher_id; + else + l=in->cipher->id; + if (in->ssl_version == SSL2_VERSION) + { + a.cipher.length=3; + buf[0]=((unsigned char)(l>>16L))&0xff; + buf[1]=((unsigned char)(l>> 8L))&0xff; + buf[2]=((unsigned char)(l ))&0xff; + } + else + { + a.cipher.length=2; + buf[0]=((unsigned char)(l>>8L))&0xff; + buf[1]=((unsigned char)(l ))&0xff; + } + +#ifndef OPENSSL_NO_COMP + if (in->compress_meth) + { + cbuf = (unsigned char)in->compress_meth; + a.comp_id.length = 1; + a.comp_id.type = V_ASN1_OCTET_STRING; + a.comp_id.data = &cbuf; + } +#endif + + a.master_key.length=in->master_key_length; + a.master_key.type=V_ASN1_OCTET_STRING; + a.master_key.data=in->master_key; + + a.session_id.length=in->session_id_length; + a.session_id.type=V_ASN1_OCTET_STRING; + a.session_id.data=in->session_id; + + a.session_id_context.length=in->sid_ctx_length; + a.session_id_context.type=V_ASN1_OCTET_STRING; + a.session_id_context.data=in->sid_ctx; + + a.key_arg.length=in->key_arg_length; + a.key_arg.type=V_ASN1_OCTET_STRING; + a.key_arg.data=in->key_arg; + +#ifndef OPENSSL_NO_KRB5 + if (in->krb5_client_princ_len) + { + a.krb5_princ.length=in->krb5_client_princ_len; + a.krb5_princ.type=V_ASN1_OCTET_STRING; + a.krb5_princ.data=in->krb5_client_princ; + } +#endif /* OPENSSL_NO_KRB5 */ + + if (in->time != 0L) + { + a.time.length=LSIZE2; + a.time.type=V_ASN1_INTEGER; + a.time.data=ibuf3; + ASN1_INTEGER_set(&(a.time),in->time); + } + + if (in->timeout != 0L) + { + a.timeout.length=LSIZE2; + a.timeout.type=V_ASN1_INTEGER; + a.timeout.data=ibuf4; + ASN1_INTEGER_set(&(a.timeout),in->timeout); + } + + if (in->verify_result != X509_V_OK) + { + a.verify_result.length=LSIZE2; + a.verify_result.type=V_ASN1_INTEGER; + a.verify_result.data=ibuf5; + ASN1_INTEGER_set(&a.verify_result,in->verify_result); + } + +#ifndef OPENSSL_NO_TLSEXT + if (in->tlsext_hostname) + { + a.tlsext_hostname.length=strlen(in->tlsext_hostname); + a.tlsext_hostname.type=V_ASN1_OCTET_STRING; + a.tlsext_hostname.data=(unsigned char *)in->tlsext_hostname; + } + if (in->tlsext_tick) + { + a.tlsext_tick.length= in->tlsext_ticklen; + a.tlsext_tick.type=V_ASN1_OCTET_STRING; + a.tlsext_tick.data=(unsigned char *)in->tlsext_tick; + } + if (in->tlsext_tick_lifetime_hint > 0) + { + a.tlsext_tick_lifetime.length=LSIZE2; + a.tlsext_tick_lifetime.type=V_ASN1_INTEGER; + a.tlsext_tick_lifetime.data=ibuf6; + ASN1_INTEGER_set(&a.tlsext_tick_lifetime,in->tlsext_tick_lifetime_hint); + } +#endif /* OPENSSL_NO_TLSEXT */ +#ifndef OPENSSL_NO_PSK + if (in->psk_identity_hint) + { + a.psk_identity_hint.length=strlen(in->psk_identity_hint); + a.psk_identity_hint.type=V_ASN1_OCTET_STRING; + a.psk_identity_hint.data=(unsigned char *)(in->psk_identity_hint); + } + if (in->psk_identity) + { + a.psk_identity.length=strlen(in->psk_identity); + a.psk_identity.type=V_ASN1_OCTET_STRING; + a.psk_identity.data=(unsigned char *)(in->psk_identity); + } +#endif /* OPENSSL_NO_PSK */ + + M_ASN1_I2D_len(&(a.version), i2d_ASN1_INTEGER); + M_ASN1_I2D_len(&(a.ssl_version), i2d_ASN1_INTEGER); + M_ASN1_I2D_len(&(a.cipher), i2d_ASN1_OCTET_STRING); + M_ASN1_I2D_len(&(a.session_id), i2d_ASN1_OCTET_STRING); + M_ASN1_I2D_len(&(a.master_key), i2d_ASN1_OCTET_STRING); +#ifndef OPENSSL_NO_KRB5 + if (in->krb5_client_princ_len) + M_ASN1_I2D_len(&(a.krb5_princ), i2d_ASN1_OCTET_STRING); +#endif /* OPENSSL_NO_KRB5 */ + if (in->key_arg_length > 0) + M_ASN1_I2D_len_IMP_opt(&(a.key_arg),i2d_ASN1_OCTET_STRING); + if (in->time != 0L) + M_ASN1_I2D_len_EXP_opt(&(a.time),i2d_ASN1_INTEGER,1,v1); + if (in->timeout != 0L) + M_ASN1_I2D_len_EXP_opt(&(a.timeout),i2d_ASN1_INTEGER,2,v2); + if (in->peer != NULL) + M_ASN1_I2D_len_EXP_opt(in->peer,i2d_X509,3,v3); + M_ASN1_I2D_len_EXP_opt(&a.session_id_context,i2d_ASN1_OCTET_STRING,4,v4); + if (in->verify_result != X509_V_OK) + M_ASN1_I2D_len_EXP_opt(&(a.verify_result),i2d_ASN1_INTEGER,5,v5); + +#ifndef OPENSSL_NO_TLSEXT + if (in->tlsext_tick_lifetime_hint > 0) + M_ASN1_I2D_len_EXP_opt(&a.tlsext_tick_lifetime, i2d_ASN1_INTEGER,9,v9); + if (in->tlsext_tick) + M_ASN1_I2D_len_EXP_opt(&(a.tlsext_tick), i2d_ASN1_OCTET_STRING,10,v10); + if (in->tlsext_hostname) + M_ASN1_I2D_len_EXP_opt(&(a.tlsext_hostname), i2d_ASN1_OCTET_STRING,6,v6); +#ifndef OPENSSL_NO_COMP + if (in->compress_meth) + M_ASN1_I2D_len_EXP_opt(&(a.comp_id), i2d_ASN1_OCTET_STRING,11,v11); +#endif +#endif /* OPENSSL_NO_TLSEXT */ +#ifndef OPENSSL_NO_PSK + if (in->psk_identity_hint) + M_ASN1_I2D_len_EXP_opt(&(a.psk_identity_hint), i2d_ASN1_OCTET_STRING,7,v7); + if (in->psk_identity) + M_ASN1_I2D_len_EXP_opt(&(a.psk_identity), i2d_ASN1_OCTET_STRING,8,v8); +#endif /* OPENSSL_NO_PSK */ + + M_ASN1_I2D_seq_total(); + + M_ASN1_I2D_put(&(a.version), i2d_ASN1_INTEGER); + M_ASN1_I2D_put(&(a.ssl_version), i2d_ASN1_INTEGER); + M_ASN1_I2D_put(&(a.cipher), i2d_ASN1_OCTET_STRING); + M_ASN1_I2D_put(&(a.session_id), i2d_ASN1_OCTET_STRING); + M_ASN1_I2D_put(&(a.master_key), i2d_ASN1_OCTET_STRING); +#ifndef OPENSSL_NO_KRB5 + if (in->krb5_client_princ_len) + M_ASN1_I2D_put(&(a.krb5_princ), i2d_ASN1_OCTET_STRING); +#endif /* OPENSSL_NO_KRB5 */ + if (in->key_arg_length > 0) + M_ASN1_I2D_put_IMP_opt(&(a.key_arg),i2d_ASN1_OCTET_STRING,0); + if (in->time != 0L) + M_ASN1_I2D_put_EXP_opt(&(a.time),i2d_ASN1_INTEGER,1,v1); + if (in->timeout != 0L) + M_ASN1_I2D_put_EXP_opt(&(a.timeout),i2d_ASN1_INTEGER,2,v2); + if (in->peer != NULL) + M_ASN1_I2D_put_EXP_opt(in->peer,i2d_X509,3,v3); + M_ASN1_I2D_put_EXP_opt(&a.session_id_context,i2d_ASN1_OCTET_STRING,4, + v4); + if (in->verify_result != X509_V_OK) + M_ASN1_I2D_put_EXP_opt(&a.verify_result,i2d_ASN1_INTEGER,5,v5); +#ifndef OPENSSL_NO_TLSEXT + if (in->tlsext_hostname) + M_ASN1_I2D_put_EXP_opt(&(a.tlsext_hostname), i2d_ASN1_OCTET_STRING,6,v6); +#endif /* OPENSSL_NO_TLSEXT */ +#ifndef OPENSSL_NO_PSK + if (in->psk_identity_hint) + M_ASN1_I2D_put_EXP_opt(&(a.psk_identity_hint), i2d_ASN1_OCTET_STRING,7,v7); + if (in->psk_identity) + M_ASN1_I2D_put_EXP_opt(&(a.psk_identity), i2d_ASN1_OCTET_STRING,8,v8); +#endif /* OPENSSL_NO_PSK */ +#ifndef OPENSSL_NO_TLSEXT + if (in->tlsext_tick_lifetime_hint > 0) + M_ASN1_I2D_put_EXP_opt(&a.tlsext_tick_lifetime, i2d_ASN1_INTEGER,9,v9); + if (in->tlsext_tick) + M_ASN1_I2D_put_EXP_opt(&(a.tlsext_tick), i2d_ASN1_OCTET_STRING,10,v10); +#endif /* OPENSSL_NO_TLSEXT */ +#ifndef OPENSSL_NO_COMP + if (in->compress_meth) + M_ASN1_I2D_put_EXP_opt(&(a.comp_id), i2d_ASN1_OCTET_STRING,11,v11); +#endif + M_ASN1_I2D_finish(); + } + +SSL_SESSION *d2i_SSL_SESSION(SSL_SESSION **a, const unsigned char **pp, + long length) + { + int ssl_version=0,i; + long id; + ASN1_INTEGER ai,*aip; + ASN1_OCTET_STRING os,*osp; + M_ASN1_D2I_vars(a,SSL_SESSION *,SSL_SESSION_new); + + aip= &ai; + osp= &os; + + M_ASN1_D2I_Init(); + M_ASN1_D2I_start_sequence(); + + ai.data=NULL; ai.length=0; + M_ASN1_D2I_get_x(ASN1_INTEGER,aip,d2i_ASN1_INTEGER); + if (ai.data != NULL) { OPENSSL_free(ai.data); ai.data=NULL; ai.length=0; } + + /* we don't care about the version right now :-) */ + M_ASN1_D2I_get_x(ASN1_INTEGER,aip,d2i_ASN1_INTEGER); + ssl_version=(int)ASN1_INTEGER_get(aip); + ret->ssl_version=ssl_version; + if (ai.data != NULL) { OPENSSL_free(ai.data); ai.data=NULL; ai.length=0; } + + os.data=NULL; os.length=0; + M_ASN1_D2I_get_x(ASN1_OCTET_STRING,osp,d2i_ASN1_OCTET_STRING); + if (ssl_version == SSL2_VERSION) + { + if (os.length != 3) + { + c.error=SSL_R_CIPHER_CODE_WRONG_LENGTH; + goto err; + } + id=0x02000000L| + ((unsigned long)os.data[0]<<16L)| + ((unsigned long)os.data[1]<< 8L)| + (unsigned long)os.data[2]; + } + else if ((ssl_version>>8) >= SSL3_VERSION_MAJOR) + { + if (os.length != 2) + { + c.error=SSL_R_CIPHER_CODE_WRONG_LENGTH; + goto err; + } + id=0x03000000L| + ((unsigned long)os.data[0]<<8L)| + (unsigned long)os.data[1]; + } + else + { + c.error=SSL_R_UNKNOWN_SSL_VERSION; + goto err; + } + + ret->cipher=NULL; + ret->cipher_id=id; + + M_ASN1_D2I_get_x(ASN1_OCTET_STRING,osp,d2i_ASN1_OCTET_STRING); + if ((ssl_version>>8) >= SSL3_VERSION_MAJOR) + i=SSL3_MAX_SSL_SESSION_ID_LENGTH; + else /* if (ssl_version>>8 == SSL2_VERSION_MAJOR) */ + i=SSL2_MAX_SSL_SESSION_ID_LENGTH; + + if (os.length > i) + os.length = i; + if (os.length > (int)sizeof(ret->session_id)) /* can't happen */ + os.length = sizeof(ret->session_id); + + ret->session_id_length=os.length; + OPENSSL_assert(os.length <= (int)sizeof(ret->session_id)); + memcpy(ret->session_id,os.data,os.length); + + M_ASN1_D2I_get_x(ASN1_OCTET_STRING,osp,d2i_ASN1_OCTET_STRING); + if (os.length > SSL_MAX_MASTER_KEY_LENGTH) + ret->master_key_length=SSL_MAX_MASTER_KEY_LENGTH; + else + ret->master_key_length=os.length; + memcpy(ret->master_key,os.data,ret->master_key_length); + + os.length=0; + +#ifndef OPENSSL_NO_KRB5 + os.length=0; + M_ASN1_D2I_get_opt(osp,d2i_ASN1_OCTET_STRING,V_ASN1_OCTET_STRING); + if (os.data) + { + if (os.length > SSL_MAX_KRB5_PRINCIPAL_LENGTH) + ret->krb5_client_princ_len=0; + else + ret->krb5_client_princ_len=os.length; + memcpy(ret->krb5_client_princ,os.data,ret->krb5_client_princ_len); + OPENSSL_free(os.data); + os.data = NULL; + os.length = 0; + } + else + ret->krb5_client_princ_len=0; +#endif /* OPENSSL_NO_KRB5 */ + + M_ASN1_D2I_get_IMP_opt(osp,d2i_ASN1_OCTET_STRING,0,V_ASN1_OCTET_STRING); + if (os.length > SSL_MAX_KEY_ARG_LENGTH) + ret->key_arg_length=SSL_MAX_KEY_ARG_LENGTH; + else + ret->key_arg_length=os.length; + memcpy(ret->key_arg,os.data,ret->key_arg_length); + if (os.data != NULL) OPENSSL_free(os.data); + + ai.length=0; + M_ASN1_D2I_get_EXP_opt(aip,d2i_ASN1_INTEGER,1); + if (ai.data != NULL) + { + ret->time=ASN1_INTEGER_get(aip); + OPENSSL_free(ai.data); ai.data=NULL; ai.length=0; + } + else + ret->time=(unsigned long)time(NULL); + + ai.length=0; + M_ASN1_D2I_get_EXP_opt(aip,d2i_ASN1_INTEGER,2); + if (ai.data != NULL) + { + ret->timeout=ASN1_INTEGER_get(aip); + OPENSSL_free(ai.data); ai.data=NULL; ai.length=0; + } + else + ret->timeout=3; + + if (ret->peer != NULL) + { + X509_free(ret->peer); + ret->peer=NULL; + } + M_ASN1_D2I_get_EXP_opt(ret->peer,d2i_X509,3); + + os.length=0; + os.data=NULL; + M_ASN1_D2I_get_EXP_opt(osp,d2i_ASN1_OCTET_STRING,4); + + if(os.data != NULL) + { + if (os.length > SSL_MAX_SID_CTX_LENGTH) + { + c.error=SSL_R_BAD_LENGTH; + goto err; + } + else + { + ret->sid_ctx_length=os.length; + memcpy(ret->sid_ctx,os.data,os.length); + } + OPENSSL_free(os.data); os.data=NULL; os.length=0; + } + else + ret->sid_ctx_length=0; + + ai.length=0; + M_ASN1_D2I_get_EXP_opt(aip,d2i_ASN1_INTEGER,5); + if (ai.data != NULL) + { + ret->verify_result=ASN1_INTEGER_get(aip); + OPENSSL_free(ai.data); ai.data=NULL; ai.length=0; + } + else + ret->verify_result=X509_V_OK; + +#ifndef OPENSSL_NO_TLSEXT + os.length=0; + os.data=NULL; + M_ASN1_D2I_get_EXP_opt(osp,d2i_ASN1_OCTET_STRING,6); + if (os.data) + { + ret->tlsext_hostname = BUF_strndup((char *)os.data, os.length); + OPENSSL_free(os.data); + os.data = NULL; + os.length = 0; + } + else + ret->tlsext_hostname=NULL; +#endif /* OPENSSL_NO_TLSEXT */ + +#ifndef OPENSSL_NO_PSK + os.length=0; + os.data=NULL; + M_ASN1_D2I_get_EXP_opt(osp,d2i_ASN1_OCTET_STRING,7); + if (os.data) + { + ret->psk_identity_hint = BUF_strndup((char *)os.data, os.length); + OPENSSL_free(os.data); + os.data = NULL; + os.length = 0; + } + else + ret->psk_identity_hint=NULL; +#endif /* OPENSSL_NO_PSK */ + +#ifndef OPENSSL_NO_TLSEXT + ai.length=0; + M_ASN1_D2I_get_EXP_opt(aip,d2i_ASN1_INTEGER,9); + if (ai.data != NULL) + { + ret->tlsext_tick_lifetime_hint=ASN1_INTEGER_get(aip); + OPENSSL_free(ai.data); ai.data=NULL; ai.length=0; + } + else if (ret->tlsext_ticklen && ret->session_id_length) + ret->tlsext_tick_lifetime_hint = -1; + else + ret->tlsext_tick_lifetime_hint=0; + os.length=0; + os.data=NULL; + M_ASN1_D2I_get_EXP_opt(osp,d2i_ASN1_OCTET_STRING,10); + if (os.data) + { + ret->tlsext_tick = os.data; + ret->tlsext_ticklen = os.length; + os.data = NULL; + os.length = 0; + } + else + ret->tlsext_tick=NULL; +#endif /* OPENSSL_NO_TLSEXT */ +#ifndef OPENSSL_NO_COMP + os.length=0; + os.data=NULL; + M_ASN1_D2I_get_EXP_opt(osp,d2i_ASN1_OCTET_STRING,11); + if (os.data) + { + ret->compress_meth = os.data[0]; + OPENSSL_free(os.data); + os.data = NULL; + } +#endif + + M_ASN1_D2I_Finish(a,SSL_SESSION_free,SSL_F_D2I_SSL_SESSION); + } diff --git a/node-v0.8.14/deps/openssl/openssl/ssl/ssl_cert.c b/node-v0.8.14/deps/openssl/openssl/ssl/ssl_cert.c new file mode 100644 index 0000000..27256ee --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/ssl/ssl_cert.c @@ -0,0 +1,834 @@ +/*! \file ssl/ssl_cert.c */ +/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com) + * All rights reserved. + * + * This package is an SSL implementation written + * by Eric Young (eay@cryptsoft.com). + * The implementation was written so as to conform with Netscapes SSL. + * + * This library is free for commercial and non-commercial use as long as + * the following conditions are aheared to. The following conditions + * apply to all code found in this distribution, be it the RC4, RSA, + * lhash, DES, etc., code; not just the SSL code. The SSL documentation + * included with this distribution is covered by the same copyright terms + * except that the holder is Tim Hudson (tjh@cryptsoft.com). + * + * Copyright remains Eric Young's, and as such any Copyright notices in + * the code are not to be removed. + * If this package is used in a product, Eric Young should be given attribution + * as the author of the parts of the library used. + * This can be in the form of a textual message at program startup or + * in documentation (online or textual) provided with the package. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * "This product includes cryptographic software written by + * Eric Young (eay@cryptsoft.com)" + * The word 'cryptographic' can be left out if the rouines from the library + * being used are not cryptographic related :-). + * 4. If you include any Windows specific code (or a derivative thereof) from + * the apps directory (application code) you must include an acknowledgement: + * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)" + * + * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * + * The licence and distribution terms for any publically available version or + * derivative of this code cannot be changed. i.e. this code cannot simply be + * copied and put under another distribution licence + * [including the GNU Public Licence.] + */ +/* ==================================================================== + * Copyright (c) 1998-2007 The OpenSSL Project. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. All advertising materials mentioning features or use of this + * software must display the following acknowledgment: + * "This product includes software developed by the OpenSSL Project + * for use in the OpenSSL Toolkit. (http://www.openssl.org/)" + * + * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to + * endorse or promote products derived from this software without + * prior written permission. For written permission, please contact + * openssl-core@openssl.org. + * + * 5. Products derived from this software may not be called "OpenSSL" + * nor may "OpenSSL" appear in their names without prior written + * permission of the OpenSSL Project. + * + * 6. Redistributions of any form whatsoever must retain the following + * acknowledgment: + * "This product includes software developed by the OpenSSL Project + * for use in the OpenSSL Toolkit (http://www.openssl.org/)" + * + * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY + * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR + * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, + * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * ==================================================================== + * + * This product includes cryptographic software written by Eric Young + * (eay@cryptsoft.com). This product includes software written by Tim + * Hudson (tjh@cryptsoft.com). + * + */ +/* ==================================================================== + * Copyright 2002 Sun Microsystems, Inc. ALL RIGHTS RESERVED. + * ECC cipher suite support in OpenSSL originally developed by + * SUN MICROSYSTEMS, INC., and contributed to the OpenSSL project. + */ + +#include + +#include "e_os.h" +#ifndef NO_SYS_TYPES_H +# include +#endif + +#include "o_dir.h" +#include +#include +#include +#include +#ifndef OPENSSL_NO_DH +#include +#endif +#include +#include "ssl_locl.h" + +int SSL_get_ex_data_X509_STORE_CTX_idx(void) + { + static volatile int ssl_x509_store_ctx_idx= -1; + int got_write_lock = 0; + + CRYPTO_r_lock(CRYPTO_LOCK_SSL_CTX); + + if (ssl_x509_store_ctx_idx < 0) + { + CRYPTO_r_unlock(CRYPTO_LOCK_SSL_CTX); + CRYPTO_w_lock(CRYPTO_LOCK_SSL_CTX); + got_write_lock = 1; + + if (ssl_x509_store_ctx_idx < 0) + { + ssl_x509_store_ctx_idx=X509_STORE_CTX_get_ex_new_index( + 0,"SSL for verify callback",NULL,NULL,NULL); + } + } + + if (got_write_lock) + CRYPTO_w_unlock(CRYPTO_LOCK_SSL_CTX); + else + CRYPTO_r_unlock(CRYPTO_LOCK_SSL_CTX); + + return ssl_x509_store_ctx_idx; + } + +CERT *ssl_cert_new(void) + { + CERT *ret; + + ret=(CERT *)OPENSSL_malloc(sizeof(CERT)); + if (ret == NULL) + { + SSLerr(SSL_F_SSL_CERT_NEW,ERR_R_MALLOC_FAILURE); + return(NULL); + } + memset(ret,0,sizeof(CERT)); + + ret->key= &(ret->pkeys[SSL_PKEY_RSA_ENC]); + ret->references=1; + + return(ret); + } + +CERT *ssl_cert_dup(CERT *cert) + { + CERT *ret; + int i; + + ret = (CERT *)OPENSSL_malloc(sizeof(CERT)); + if (ret == NULL) + { + SSLerr(SSL_F_SSL_CERT_DUP, ERR_R_MALLOC_FAILURE); + return(NULL); + } + + memset(ret, 0, sizeof(CERT)); + + ret->key = &ret->pkeys[cert->key - &cert->pkeys[0]]; + /* or ret->key = ret->pkeys + (cert->key - cert->pkeys), + * if you find that more readable */ + + ret->valid = cert->valid; + ret->mask_k = cert->mask_k; + ret->mask_a = cert->mask_a; + ret->export_mask_k = cert->export_mask_k; + ret->export_mask_a = cert->export_mask_a; + +#ifndef OPENSSL_NO_RSA + if (cert->rsa_tmp != NULL) + { + RSA_up_ref(cert->rsa_tmp); + ret->rsa_tmp = cert->rsa_tmp; + } + ret->rsa_tmp_cb = cert->rsa_tmp_cb; +#endif + +#ifndef OPENSSL_NO_DH + if (cert->dh_tmp != NULL) + { + ret->dh_tmp = DHparams_dup(cert->dh_tmp); + if (ret->dh_tmp == NULL) + { + SSLerr(SSL_F_SSL_CERT_DUP, ERR_R_DH_LIB); + goto err; + } + if (cert->dh_tmp->priv_key) + { + BIGNUM *b = BN_dup(cert->dh_tmp->priv_key); + if (!b) + { + SSLerr(SSL_F_SSL_CERT_DUP, ERR_R_BN_LIB); + goto err; + } + ret->dh_tmp->priv_key = b; + } + if (cert->dh_tmp->pub_key) + { + BIGNUM *b = BN_dup(cert->dh_tmp->pub_key); + if (!b) + { + SSLerr(SSL_F_SSL_CERT_DUP, ERR_R_BN_LIB); + goto err; + } + ret->dh_tmp->pub_key = b; + } + } + ret->dh_tmp_cb = cert->dh_tmp_cb; +#endif + +#ifndef OPENSSL_NO_ECDH + if (cert->ecdh_tmp) + { + ret->ecdh_tmp = EC_KEY_dup(cert->ecdh_tmp); + if (ret->ecdh_tmp == NULL) + { + SSLerr(SSL_F_SSL_CERT_DUP, ERR_R_EC_LIB); + goto err; + } + } + ret->ecdh_tmp_cb = cert->ecdh_tmp_cb; +#endif + + for (i = 0; i < SSL_PKEY_NUM; i++) + { + if (cert->pkeys[i].x509 != NULL) + { + ret->pkeys[i].x509 = cert->pkeys[i].x509; + CRYPTO_add(&ret->pkeys[i].x509->references, 1, + CRYPTO_LOCK_X509); + } + + if (cert->pkeys[i].privatekey != NULL) + { + ret->pkeys[i].privatekey = cert->pkeys[i].privatekey; + CRYPTO_add(&ret->pkeys[i].privatekey->references, 1, + CRYPTO_LOCK_EVP_PKEY); + + switch(i) + { + /* If there was anything special to do for + * certain types of keys, we'd do it here. + * (Nothing at the moment, I think.) */ + + case SSL_PKEY_RSA_ENC: + case SSL_PKEY_RSA_SIGN: + /* We have an RSA key. */ + break; + + case SSL_PKEY_DSA_SIGN: + /* We have a DSA key. */ + break; + + case SSL_PKEY_DH_RSA: + case SSL_PKEY_DH_DSA: + /* We have a DH key. */ + break; + + case SSL_PKEY_ECC: + /* We have an ECC key */ + break; + + default: + /* Can't happen. */ + SSLerr(SSL_F_SSL_CERT_DUP, SSL_R_LIBRARY_BUG); + } + } + } + + /* ret->extra_certs *should* exist, but currently the own certificate + * chain is held inside SSL_CTX */ + + ret->references=1; + + return(ret); + +#if !defined(OPENSSL_NO_DH) || !defined(OPENSSL_NO_ECDH) +err: +#endif +#ifndef OPENSSL_NO_RSA + if (ret->rsa_tmp != NULL) + RSA_free(ret->rsa_tmp); +#endif +#ifndef OPENSSL_NO_DH + if (ret->dh_tmp != NULL) + DH_free(ret->dh_tmp); +#endif +#ifndef OPENSSL_NO_ECDH + if (ret->ecdh_tmp != NULL) + EC_KEY_free(ret->ecdh_tmp); +#endif + + for (i = 0; i < SSL_PKEY_NUM; i++) + { + if (ret->pkeys[i].x509 != NULL) + X509_free(ret->pkeys[i].x509); + if (ret->pkeys[i].privatekey != NULL) + EVP_PKEY_free(ret->pkeys[i].privatekey); + } + + return NULL; + } + + +void ssl_cert_free(CERT *c) + { + int i; + + if(c == NULL) + return; + + i=CRYPTO_add(&c->references,-1,CRYPTO_LOCK_SSL_CERT); +#ifdef REF_PRINT + REF_PRINT("CERT",c); +#endif + if (i > 0) return; +#ifdef REF_CHECK + if (i < 0) + { + fprintf(stderr,"ssl_cert_free, bad reference count\n"); + abort(); /* ok */ + } +#endif + +#ifndef OPENSSL_NO_RSA + if (c->rsa_tmp) RSA_free(c->rsa_tmp); +#endif +#ifndef OPENSSL_NO_DH + if (c->dh_tmp) DH_free(c->dh_tmp); +#endif +#ifndef OPENSSL_NO_ECDH + if (c->ecdh_tmp) EC_KEY_free(c->ecdh_tmp); +#endif + + for (i=0; ipkeys[i].x509 != NULL) + X509_free(c->pkeys[i].x509); + if (c->pkeys[i].privatekey != NULL) + EVP_PKEY_free(c->pkeys[i].privatekey); +#if 0 + if (c->pkeys[i].publickey != NULL) + EVP_PKEY_free(c->pkeys[i].publickey); +#endif + } + OPENSSL_free(c); + } + +int ssl_cert_inst(CERT **o) + { + /* Create a CERT if there isn't already one + * (which cannot really happen, as it is initially created in + * SSL_CTX_new; but the earlier code usually allows for that one + * being non-existant, so we follow that behaviour, as it might + * turn out that there actually is a reason for it -- but I'm + * not sure that *all* of the existing code could cope with + * s->cert being NULL, otherwise we could do without the + * initialization in SSL_CTX_new). + */ + + if (o == NULL) + { + SSLerr(SSL_F_SSL_CERT_INST, ERR_R_PASSED_NULL_PARAMETER); + return(0); + } + if (*o == NULL) + { + if ((*o = ssl_cert_new()) == NULL) + { + SSLerr(SSL_F_SSL_CERT_INST, ERR_R_MALLOC_FAILURE); + return(0); + } + } + return(1); + } + + +SESS_CERT *ssl_sess_cert_new(void) + { + SESS_CERT *ret; + + ret = OPENSSL_malloc(sizeof *ret); + if (ret == NULL) + { + SSLerr(SSL_F_SSL_SESS_CERT_NEW, ERR_R_MALLOC_FAILURE); + return NULL; + } + + memset(ret, 0 ,sizeof *ret); + ret->peer_key = &(ret->peer_pkeys[SSL_PKEY_RSA_ENC]); + ret->references = 1; + + return ret; + } + +void ssl_sess_cert_free(SESS_CERT *sc) + { + int i; + + if (sc == NULL) + return; + + i = CRYPTO_add(&sc->references, -1, CRYPTO_LOCK_SSL_SESS_CERT); +#ifdef REF_PRINT + REF_PRINT("SESS_CERT", sc); +#endif + if (i > 0) + return; +#ifdef REF_CHECK + if (i < 0) + { + fprintf(stderr,"ssl_sess_cert_free, bad reference count\n"); + abort(); /* ok */ + } +#endif + + /* i == 0 */ + if (sc->cert_chain != NULL) + sk_X509_pop_free(sc->cert_chain, X509_free); + for (i = 0; i < SSL_PKEY_NUM; i++) + { + if (sc->peer_pkeys[i].x509 != NULL) + X509_free(sc->peer_pkeys[i].x509); +#if 0 /* We don't have the peer's private key. These lines are just + * here as a reminder that we're still using a not-quite-appropriate + * data structure. */ + if (sc->peer_pkeys[i].privatekey != NULL) + EVP_PKEY_free(sc->peer_pkeys[i].privatekey); +#endif + } + +#ifndef OPENSSL_NO_RSA + if (sc->peer_rsa_tmp != NULL) + RSA_free(sc->peer_rsa_tmp); +#endif +#ifndef OPENSSL_NO_DH + if (sc->peer_dh_tmp != NULL) + DH_free(sc->peer_dh_tmp); +#endif +#ifndef OPENSSL_NO_ECDH + if (sc->peer_ecdh_tmp != NULL) + EC_KEY_free(sc->peer_ecdh_tmp); +#endif + + OPENSSL_free(sc); + } + +int ssl_set_peer_cert_type(SESS_CERT *sc,int type) + { + sc->peer_cert_type = type; + return(1); + } + +int ssl_verify_cert_chain(SSL *s,STACK_OF(X509) *sk) + { + X509 *x; + int i; + X509_STORE_CTX ctx; + + if ((sk == NULL) || (sk_X509_num(sk) == 0)) + return(0); + + x=sk_X509_value(sk,0); + if(!X509_STORE_CTX_init(&ctx,s->ctx->cert_store,x,sk)) + { + SSLerr(SSL_F_SSL_VERIFY_CERT_CHAIN,ERR_R_X509_LIB); + return(0); + } +#if 0 + if (SSL_get_verify_depth(s) >= 0) + X509_STORE_CTX_set_depth(&ctx, SSL_get_verify_depth(s)); +#endif + X509_STORE_CTX_set_ex_data(&ctx,SSL_get_ex_data_X509_STORE_CTX_idx(),s); + + /* We need to inherit the verify parameters. These can be determined by + * the context: if its a server it will verify SSL client certificates + * or vice versa. + */ + + X509_STORE_CTX_set_default(&ctx, + s->server ? "ssl_client" : "ssl_server"); + /* Anything non-default in "param" should overwrite anything in the + * ctx. + */ + X509_VERIFY_PARAM_set1(X509_STORE_CTX_get0_param(&ctx), s->param); + + if (s->verify_callback) + X509_STORE_CTX_set_verify_cb(&ctx, s->verify_callback); + + if (s->ctx->app_verify_callback != NULL) +#if 1 /* new with OpenSSL 0.9.7 */ + i=s->ctx->app_verify_callback(&ctx, s->ctx->app_verify_arg); +#else + i=s->ctx->app_verify_callback(&ctx); /* should pass app_verify_arg */ +#endif + else + { +#ifndef OPENSSL_NO_X509_VERIFY + i=X509_verify_cert(&ctx); +#else + i=0; + ctx.error=X509_V_ERR_APPLICATION_VERIFICATION; + SSLerr(SSL_F_SSL_VERIFY_CERT_CHAIN,SSL_R_NO_VERIFY_CALLBACK); +#endif + } + + s->verify_result=ctx.error; + X509_STORE_CTX_cleanup(&ctx); + + return(i); + } + +static void set_client_CA_list(STACK_OF(X509_NAME) **ca_list,STACK_OF(X509_NAME) *name_list) + { + if (*ca_list != NULL) + sk_X509_NAME_pop_free(*ca_list,X509_NAME_free); + + *ca_list=name_list; + } + +STACK_OF(X509_NAME) *SSL_dup_CA_list(STACK_OF(X509_NAME) *sk) + { + int i; + STACK_OF(X509_NAME) *ret; + X509_NAME *name; + + ret=sk_X509_NAME_new_null(); + for (i=0; iclient_CA),name_list); + } + +void SSL_CTX_set_client_CA_list(SSL_CTX *ctx,STACK_OF(X509_NAME) *name_list) + { + set_client_CA_list(&(ctx->client_CA),name_list); + } + +STACK_OF(X509_NAME) *SSL_CTX_get_client_CA_list(const SSL_CTX *ctx) + { + return(ctx->client_CA); + } + +STACK_OF(X509_NAME) *SSL_get_client_CA_list(const SSL *s) + { + if (s->type == SSL_ST_CONNECT) + { /* we are in the client */ + if (((s->version>>8) == SSL3_VERSION_MAJOR) && + (s->s3 != NULL)) + return(s->s3->tmp.ca_names); + else + return(NULL); + } + else + { + if (s->client_CA != NULL) + return(s->client_CA); + else + return(s->ctx->client_CA); + } + } + +static int add_client_CA(STACK_OF(X509_NAME) **sk,X509 *x) + { + X509_NAME *name; + + if (x == NULL) return(0); + if ((*sk == NULL) && ((*sk=sk_X509_NAME_new_null()) == NULL)) + return(0); + + if ((name=X509_NAME_dup(X509_get_subject_name(x))) == NULL) + return(0); + + if (!sk_X509_NAME_push(*sk,name)) + { + X509_NAME_free(name); + return(0); + } + return(1); + } + +int SSL_add_client_CA(SSL *ssl,X509 *x) + { + return(add_client_CA(&(ssl->client_CA),x)); + } + +int SSL_CTX_add_client_CA(SSL_CTX *ctx,X509 *x) + { + return(add_client_CA(&(ctx->client_CA),x)); + } + +static int xname_cmp(const X509_NAME * const *a, const X509_NAME * const *b) + { + return(X509_NAME_cmp(*a,*b)); + } + +#ifndef OPENSSL_NO_STDIO +/*! + * Load CA certs from a file into a ::STACK. Note that it is somewhat misnamed; + * it doesn't really have anything to do with clients (except that a common use + * for a stack of CAs is to send it to the client). Actually, it doesn't have + * much to do with CAs, either, since it will load any old cert. + * \param file the file containing one or more certs. + * \return a ::STACK containing the certs. + */ +STACK_OF(X509_NAME) *SSL_load_client_CA_file(const char *file) + { + BIO *in; + X509 *x=NULL; + X509_NAME *xn=NULL; + STACK_OF(X509_NAME) *ret = NULL,*sk; + + sk=sk_X509_NAME_new(xname_cmp); + + in=BIO_new(BIO_s_file_internal()); + + if ((sk == NULL) || (in == NULL)) + { + SSLerr(SSL_F_SSL_LOAD_CLIENT_CA_FILE,ERR_R_MALLOC_FAILURE); + goto err; + } + + if (!BIO_read_filename(in,file)) + goto err; + + for (;;) + { + if (PEM_read_bio_X509(in,&x,NULL,NULL) == NULL) + break; + if (ret == NULL) + { + ret = sk_X509_NAME_new_null(); + if (ret == NULL) + { + SSLerr(SSL_F_SSL_LOAD_CLIENT_CA_FILE,ERR_R_MALLOC_FAILURE); + goto err; + } + } + if ((xn=X509_get_subject_name(x)) == NULL) goto err; + /* check for duplicates */ + xn=X509_NAME_dup(xn); + if (xn == NULL) goto err; + if (sk_X509_NAME_find(sk,xn) >= 0) + X509_NAME_free(xn); + else + { + sk_X509_NAME_push(sk,xn); + sk_X509_NAME_push(ret,xn); + } + } + + if (0) + { +err: + if (ret != NULL) sk_X509_NAME_pop_free(ret,X509_NAME_free); + ret=NULL; + } + if (sk != NULL) sk_X509_NAME_free(sk); + if (in != NULL) BIO_free(in); + if (x != NULL) X509_free(x); + if (ret != NULL) + ERR_clear_error(); + return(ret); + } +#endif + +/*! + * Add a file of certs to a stack. + * \param stack the stack to add to. + * \param file the file to add from. All certs in this file that are not + * already in the stack will be added. + * \return 1 for success, 0 for failure. Note that in the case of failure some + * certs may have been added to \c stack. + */ + +int SSL_add_file_cert_subjects_to_stack(STACK_OF(X509_NAME) *stack, + const char *file) + { + BIO *in; + X509 *x=NULL; + X509_NAME *xn=NULL; + int ret=1; + int (*oldcmp)(const X509_NAME * const *a, const X509_NAME * const *b); + + oldcmp=sk_X509_NAME_set_cmp_func(stack,xname_cmp); + + in=BIO_new(BIO_s_file_internal()); + + if (in == NULL) + { + SSLerr(SSL_F_SSL_ADD_FILE_CERT_SUBJECTS_TO_STACK,ERR_R_MALLOC_FAILURE); + goto err; + } + + if (!BIO_read_filename(in,file)) + goto err; + + for (;;) + { + if (PEM_read_bio_X509(in,&x,NULL,NULL) == NULL) + break; + if ((xn=X509_get_subject_name(x)) == NULL) goto err; + xn=X509_NAME_dup(xn); + if (xn == NULL) goto err; + if (sk_X509_NAME_find(stack,xn) >= 0) + X509_NAME_free(xn); + else + sk_X509_NAME_push(stack,xn); + } + + ERR_clear_error(); + + if (0) + { +err: + ret=0; + } + if(in != NULL) + BIO_free(in); + if(x != NULL) + X509_free(x); + + (void)sk_X509_NAME_set_cmp_func(stack,oldcmp); + + return ret; + } + +/*! + * Add a directory of certs to a stack. + * \param stack the stack to append to. + * \param dir the directory to append from. All files in this directory will be + * examined as potential certs. Any that are acceptable to + * SSL_add_dir_cert_subjects_to_stack() that are not already in the stack will be + * included. + * \return 1 for success, 0 for failure. Note that in the case of failure some + * certs may have been added to \c stack. + */ + +int SSL_add_dir_cert_subjects_to_stack(STACK_OF(X509_NAME) *stack, + const char *dir) + { + OPENSSL_DIR_CTX *d = NULL; + const char *filename; + int ret = 0; + + CRYPTO_w_lock(CRYPTO_LOCK_READDIR); + + /* Note that a side effect is that the CAs will be sorted by name */ + + while((filename = OPENSSL_DIR_read(&d, dir))) + { + char buf[1024]; + int r; + + if(strlen(dir)+strlen(filename)+2 > sizeof buf) + { + SSLerr(SSL_F_SSL_ADD_DIR_CERT_SUBJECTS_TO_STACK,SSL_R_PATH_TOO_LONG); + goto err; + } + +#ifdef OPENSSL_SYS_VMS + r = BIO_snprintf(buf,sizeof buf,"%s%s",dir,filename); +#else + r = BIO_snprintf(buf,sizeof buf,"%s/%s",dir,filename); +#endif + if (r <= 0 || r >= (int)sizeof(buf)) + goto err; + if(!SSL_add_file_cert_subjects_to_stack(stack,buf)) + goto err; + } + + if (errno) + { + SYSerr(SYS_F_OPENDIR, get_last_sys_error()); + ERR_add_error_data(3, "OPENSSL_DIR_read(&ctx, '", dir, "')"); + SSLerr(SSL_F_SSL_ADD_DIR_CERT_SUBJECTS_TO_STACK, ERR_R_SYS_LIB); + goto err; + } + + ret = 1; + +err: + if (d) OPENSSL_DIR_end(&d); + CRYPTO_w_unlock(CRYPTO_LOCK_READDIR); + return ret; + } + diff --git a/node-v0.8.14/deps/openssl/openssl/ssl/ssl_ciph.c b/node-v0.8.14/deps/openssl/openssl/ssl/ssl_ciph.c new file mode 100644 index 0000000..462c45a --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/ssl/ssl_ciph.c @@ -0,0 +1,1793 @@ +/* ssl/ssl_ciph.c */ +/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com) + * All rights reserved. + * + * This package is an SSL implementation written + * by Eric Young (eay@cryptsoft.com). + * The implementation was written so as to conform with Netscapes SSL. + * + * This library is free for commercial and non-commercial use as long as + * the following conditions are aheared to. The following conditions + * apply to all code found in this distribution, be it the RC4, RSA, + * lhash, DES, etc., code; not just the SSL code. The SSL documentation + * included with this distribution is covered by the same copyright terms + * except that the holder is Tim Hudson (tjh@cryptsoft.com). + * + * Copyright remains Eric Young's, and as such any Copyright notices in + * the code are not to be removed. + * If this package is used in a product, Eric Young should be given attribution + * as the author of the parts of the library used. + * This can be in the form of a textual message at program startup or + * in documentation (online or textual) provided with the package. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * "This product includes cryptographic software written by + * Eric Young (eay@cryptsoft.com)" + * The word 'cryptographic' can be left out if the rouines from the library + * being used are not cryptographic related :-). + * 4. If you include any Windows specific code (or a derivative thereof) from + * the apps directory (application code) you must include an acknowledgement: + * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)" + * + * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * + * The licence and distribution terms for any publically available version or + * derivative of this code cannot be changed. i.e. this code cannot simply be + * copied and put under another distribution licence + * [including the GNU Public Licence.] + */ +/* ==================================================================== + * Copyright (c) 1998-2007 The OpenSSL Project. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. All advertising materials mentioning features or use of this + * software must display the following acknowledgment: + * "This product includes software developed by the OpenSSL Project + * for use in the OpenSSL Toolkit. (http://www.openssl.org/)" + * + * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to + * endorse or promote products derived from this software without + * prior written permission. For written permission, please contact + * openssl-core@openssl.org. + * + * 5. Products derived from this software may not be called "OpenSSL" + * nor may "OpenSSL" appear in their names without prior written + * permission of the OpenSSL Project. + * + * 6. Redistributions of any form whatsoever must retain the following + * acknowledgment: + * "This product includes software developed by the OpenSSL Project + * for use in the OpenSSL Toolkit (http://www.openssl.org/)" + * + * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY + * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR + * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, + * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * ==================================================================== + * + * This product includes cryptographic software written by Eric Young + * (eay@cryptsoft.com). This product includes software written by Tim + * Hudson (tjh@cryptsoft.com). + * + */ +/* ==================================================================== + * Copyright 2002 Sun Microsystems, Inc. ALL RIGHTS RESERVED. + * ECC cipher suite support in OpenSSL originally developed by + * SUN MICROSYSTEMS, INC., and contributed to the OpenSSL project. + */ +/* ==================================================================== + * Copyright 2005 Nokia. All rights reserved. + * + * The portions of the attached software ("Contribution") is developed by + * Nokia Corporation and is licensed pursuant to the OpenSSL open source + * license. + * + * The Contribution, originally written by Mika Kousa and Pasi Eronen of + * Nokia Corporation, consists of the "PSK" (Pre-Shared Key) ciphersuites + * support (see RFC 4279) to OpenSSL. + * + * No patent licenses or other rights except those expressly stated in + * the OpenSSL open source license shall be deemed granted or received + * expressly, by implication, estoppel, or otherwise. + * + * No assurances are provided by Nokia that the Contribution does not + * infringe the patent or other intellectual property rights of any third + * party or that the license provides you with all the necessary rights + * to make use of the Contribution. + * + * THE SOFTWARE IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND. IN + * ADDITION TO THE DISCLAIMERS INCLUDED IN THE LICENSE, NOKIA + * SPECIFICALLY DISCLAIMS ANY LIABILITY FOR CLAIMS BROUGHT BY YOU OR ANY + * OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL PROPERTY RIGHTS OR + * OTHERWISE. + */ + +#include +#include +#ifndef OPENSSL_NO_COMP +#include +#endif +#ifndef OPENSSL_NO_ENGINE +#include +#endif +#include "ssl_locl.h" + +#define SSL_ENC_DES_IDX 0 +#define SSL_ENC_3DES_IDX 1 +#define SSL_ENC_RC4_IDX 2 +#define SSL_ENC_RC2_IDX 3 +#define SSL_ENC_IDEA_IDX 4 +#define SSL_ENC_NULL_IDX 5 +#define SSL_ENC_AES128_IDX 6 +#define SSL_ENC_AES256_IDX 7 +#define SSL_ENC_CAMELLIA128_IDX 8 +#define SSL_ENC_CAMELLIA256_IDX 9 +#define SSL_ENC_GOST89_IDX 10 +#define SSL_ENC_SEED_IDX 11 +#define SSL_ENC_NUM_IDX 12 + + +static const EVP_CIPHER *ssl_cipher_methods[SSL_ENC_NUM_IDX]={ + NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL, + }; + +#define SSL_COMP_NULL_IDX 0 +#define SSL_COMP_ZLIB_IDX 1 +#define SSL_COMP_NUM_IDX 2 + +static STACK_OF(SSL_COMP) *ssl_comp_methods=NULL; + +#define SSL_MD_MD5_IDX 0 +#define SSL_MD_SHA1_IDX 1 +#define SSL_MD_GOST94_IDX 2 +#define SSL_MD_GOST89MAC_IDX 3 +/*Constant SSL_MAX_DIGEST equal to size of digests array should be + * defined in the + * ssl_locl.h */ +#define SSL_MD_NUM_IDX SSL_MAX_DIGEST +static const EVP_MD *ssl_digest_methods[SSL_MD_NUM_IDX]={ + NULL,NULL,NULL,NULL + }; +/* PKEY_TYPE for GOST89MAC is known in advance, but, because + * implementation is engine-provided, we'll fill it only if + * corresponding EVP_PKEY_METHOD is found + */ +static int ssl_mac_pkey_id[SSL_MD_NUM_IDX]={ + EVP_PKEY_HMAC,EVP_PKEY_HMAC,EVP_PKEY_HMAC,NID_undef + }; + +static int ssl_mac_secret_size[SSL_MD_NUM_IDX]={ + 0,0,0,0 + }; + +static int ssl_handshake_digest_flag[SSL_MD_NUM_IDX]={ + SSL_HANDSHAKE_MAC_MD5,SSL_HANDSHAKE_MAC_SHA, + SSL_HANDSHAKE_MAC_GOST94,0 + }; + +#define CIPHER_ADD 1 +#define CIPHER_KILL 2 +#define CIPHER_DEL 3 +#define CIPHER_ORD 4 +#define CIPHER_SPECIAL 5 + +typedef struct cipher_order_st + { + const SSL_CIPHER *cipher; + int active; + int dead; + struct cipher_order_st *next,*prev; + } CIPHER_ORDER; + +static const SSL_CIPHER cipher_aliases[]={ + /* "ALL" doesn't include eNULL (must be specifically enabled) */ + {0,SSL_TXT_ALL,0, 0,0,~SSL_eNULL,0,0,0,0,0,0}, + /* "COMPLEMENTOFALL" */ + {0,SSL_TXT_CMPALL,0, 0,0,SSL_eNULL,0,0,0,0,0,0}, + + /* "COMPLEMENTOFDEFAULT" (does *not* include ciphersuites not found in ALL!) */ + {0,SSL_TXT_CMPDEF,0, SSL_kEDH|SSL_kEECDH,SSL_aNULL,~SSL_eNULL,0,0,0,0,0,0}, + + /* key exchange aliases + * (some of those using only a single bit here combine + * multiple key exchange algs according to the RFCs, + * e.g. kEDH combines DHE_DSS and DHE_RSA) */ + {0,SSL_TXT_kRSA,0, SSL_kRSA, 0,0,0,0,0,0,0,0}, + + {0,SSL_TXT_kDHr,0, SSL_kDHr, 0,0,0,0,0,0,0,0}, /* no such ciphersuites supported! */ + {0,SSL_TXT_kDHd,0, SSL_kDHd, 0,0,0,0,0,0,0,0}, /* no such ciphersuites supported! */ + {0,SSL_TXT_kDH,0, SSL_kDHr|SSL_kDHd,0,0,0,0,0,0,0,0}, /* no such ciphersuites supported! */ + {0,SSL_TXT_kEDH,0, SSL_kEDH, 0,0,0,0,0,0,0,0}, + {0,SSL_TXT_DH,0, SSL_kDHr|SSL_kDHd|SSL_kEDH,0,0,0,0,0,0,0,0}, + + {0,SSL_TXT_kKRB5,0, SSL_kKRB5, 0,0,0,0,0,0,0,0}, + + {0,SSL_TXT_kECDHr,0, SSL_kECDHr,0,0,0,0,0,0,0,0}, + {0,SSL_TXT_kECDHe,0, SSL_kECDHe,0,0,0,0,0,0,0,0}, + {0,SSL_TXT_kECDH,0, SSL_kECDHr|SSL_kECDHe,0,0,0,0,0,0,0,0}, + {0,SSL_TXT_kEECDH,0, SSL_kEECDH,0,0,0,0,0,0,0,0}, + {0,SSL_TXT_ECDH,0, SSL_kECDHr|SSL_kECDHe|SSL_kEECDH,0,0,0,0,0,0,0,0}, + + {0,SSL_TXT_kPSK,0, SSL_kPSK, 0,0,0,0,0,0,0,0}, + {0,SSL_TXT_kGOST,0, SSL_kGOST,0,0,0,0,0,0,0,0}, + + /* server authentication aliases */ + {0,SSL_TXT_aRSA,0, 0,SSL_aRSA, 0,0,0,0,0,0,0}, + {0,SSL_TXT_aDSS,0, 0,SSL_aDSS, 0,0,0,0,0,0,0}, + {0,SSL_TXT_DSS,0, 0,SSL_aDSS, 0,0,0,0,0,0,0}, + {0,SSL_TXT_aKRB5,0, 0,SSL_aKRB5, 0,0,0,0,0,0,0}, + {0,SSL_TXT_aNULL,0, 0,SSL_aNULL, 0,0,0,0,0,0,0}, + {0,SSL_TXT_aDH,0, 0,SSL_aDH, 0,0,0,0,0,0,0}, /* no such ciphersuites supported! */ + {0,SSL_TXT_aECDH,0, 0,SSL_aECDH, 0,0,0,0,0,0,0}, + {0,SSL_TXT_aECDSA,0, 0,SSL_aECDSA,0,0,0,0,0,0,0}, + {0,SSL_TXT_ECDSA,0, 0,SSL_aECDSA, 0,0,0,0,0,0,0}, + {0,SSL_TXT_aPSK,0, 0,SSL_aPSK, 0,0,0,0,0,0,0}, + {0,SSL_TXT_aGOST94,0,0,SSL_aGOST94,0,0,0,0,0,0,0}, + {0,SSL_TXT_aGOST01,0,0,SSL_aGOST01,0,0,0,0,0,0,0}, + {0,SSL_TXT_aGOST,0,0,SSL_aGOST94|SSL_aGOST01,0,0,0,0,0,0,0}, + + /* aliases combining key exchange and server authentication */ + {0,SSL_TXT_EDH,0, SSL_kEDH,~SSL_aNULL,0,0,0,0,0,0,0}, + {0,SSL_TXT_EECDH,0, SSL_kEECDH,~SSL_aNULL,0,0,0,0,0,0,0}, + {0,SSL_TXT_NULL,0, 0,0,SSL_eNULL, 0,0,0,0,0,0}, + {0,SSL_TXT_KRB5,0, SSL_kKRB5,SSL_aKRB5,0,0,0,0,0,0,0}, + {0,SSL_TXT_RSA,0, SSL_kRSA,SSL_aRSA,0,0,0,0,0,0,0}, + {0,SSL_TXT_ADH,0, SSL_kEDH,SSL_aNULL,0,0,0,0,0,0,0}, + {0,SSL_TXT_AECDH,0, SSL_kEECDH,SSL_aNULL,0,0,0,0,0,0,0}, + {0,SSL_TXT_PSK,0, SSL_kPSK,SSL_aPSK,0,0,0,0,0,0,0}, + + + /* symmetric encryption aliases */ + {0,SSL_TXT_DES,0, 0,0,SSL_DES, 0,0,0,0,0,0}, + {0,SSL_TXT_3DES,0, 0,0,SSL_3DES, 0,0,0,0,0,0}, + {0,SSL_TXT_RC4,0, 0,0,SSL_RC4, 0,0,0,0,0,0}, + {0,SSL_TXT_RC2,0, 0,0,SSL_RC2, 0,0,0,0,0,0}, + {0,SSL_TXT_IDEA,0, 0,0,SSL_IDEA, 0,0,0,0,0,0}, + {0,SSL_TXT_SEED,0, 0,0,SSL_SEED, 0,0,0,0,0,0}, + {0,SSL_TXT_eNULL,0, 0,0,SSL_eNULL, 0,0,0,0,0,0}, + {0,SSL_TXT_AES128,0, 0,0,SSL_AES128,0,0,0,0,0,0}, + {0,SSL_TXT_AES256,0, 0,0,SSL_AES256,0,0,0,0,0,0}, + {0,SSL_TXT_AES,0, 0,0,SSL_AES128|SSL_AES256,0,0,0,0,0,0}, + {0,SSL_TXT_CAMELLIA128,0,0,0,SSL_CAMELLIA128,0,0,0,0,0,0}, + {0,SSL_TXT_CAMELLIA256,0,0,0,SSL_CAMELLIA256,0,0,0,0,0,0}, + {0,SSL_TXT_CAMELLIA ,0,0,0,SSL_CAMELLIA128|SSL_CAMELLIA256,0,0,0,0,0,0}, + + /* MAC aliases */ + {0,SSL_TXT_MD5,0, 0,0,0,SSL_MD5, 0,0,0,0,0}, + {0,SSL_TXT_SHA1,0, 0,0,0,SSL_SHA1, 0,0,0,0,0}, + {0,SSL_TXT_SHA,0, 0,0,0,SSL_SHA1, 0,0,0,0,0}, + {0,SSL_TXT_GOST94,0, 0,0,0,SSL_GOST94, 0,0,0,0,0}, + {0,SSL_TXT_GOST89MAC,0, 0,0,0,SSL_GOST89MAC, 0,0,0,0,0}, + + /* protocol version aliases */ + {0,SSL_TXT_SSLV2,0, 0,0,0,0,SSL_SSLV2, 0,0,0,0}, + {0,SSL_TXT_SSLV3,0, 0,0,0,0,SSL_SSLV3, 0,0,0,0}, + {0,SSL_TXT_TLSV1,0, 0,0,0,0,SSL_TLSV1, 0,0,0,0}, + + /* export flag */ + {0,SSL_TXT_EXP,0, 0,0,0,0,0,SSL_EXPORT,0,0,0}, + {0,SSL_TXT_EXPORT,0, 0,0,0,0,0,SSL_EXPORT,0,0,0}, + + /* strength classes */ + {0,SSL_TXT_EXP40,0, 0,0,0,0,0,SSL_EXP40, 0,0,0}, + {0,SSL_TXT_EXP56,0, 0,0,0,0,0,SSL_EXP56, 0,0,0}, + {0,SSL_TXT_LOW,0, 0,0,0,0,0,SSL_LOW, 0,0,0}, + {0,SSL_TXT_MEDIUM,0, 0,0,0,0,0,SSL_MEDIUM,0,0,0}, + {0,SSL_TXT_HIGH,0, 0,0,0,0,0,SSL_HIGH, 0,0,0}, + /* FIPS 140-2 approved ciphersuite */ + {0,SSL_TXT_FIPS,0, 0,0,~SSL_eNULL,0,0,SSL_FIPS, 0,0,0}, + }; +/* Search for public key algorithm with given name and + * return its pkey_id if it is available. Otherwise return 0 + */ +#ifdef OPENSSL_NO_ENGINE + +static int get_optional_pkey_id(const char *pkey_name) + { + const EVP_PKEY_ASN1_METHOD *ameth; + int pkey_id=0; + ameth = EVP_PKEY_asn1_find_str(NULL,pkey_name,-1); + if (ameth) + { + EVP_PKEY_asn1_get0_info(&pkey_id, NULL,NULL,NULL,NULL,ameth); + } + return pkey_id; + } + +#else + +static int get_optional_pkey_id(const char *pkey_name) + { + const EVP_PKEY_ASN1_METHOD *ameth; + ENGINE *tmpeng = NULL; + int pkey_id=0; + ameth = EVP_PKEY_asn1_find_str(&tmpeng,pkey_name,-1); + if (ameth) + { + EVP_PKEY_asn1_get0_info(&pkey_id, NULL,NULL,NULL,NULL,ameth); + } + if (tmpeng) ENGINE_finish(tmpeng); + return pkey_id; + } + +#endif + +void ssl_load_ciphers(void) + { + ssl_cipher_methods[SSL_ENC_DES_IDX]= + EVP_get_cipherbyname(SN_des_cbc); + ssl_cipher_methods[SSL_ENC_3DES_IDX]= + EVP_get_cipherbyname(SN_des_ede3_cbc); + ssl_cipher_methods[SSL_ENC_RC4_IDX]= + EVP_get_cipherbyname(SN_rc4); + ssl_cipher_methods[SSL_ENC_RC2_IDX]= + EVP_get_cipherbyname(SN_rc2_cbc); +#ifndef OPENSSL_NO_IDEA + ssl_cipher_methods[SSL_ENC_IDEA_IDX]= + EVP_get_cipherbyname(SN_idea_cbc); +#else + ssl_cipher_methods[SSL_ENC_IDEA_IDX]= NULL; +#endif + ssl_cipher_methods[SSL_ENC_AES128_IDX]= + EVP_get_cipherbyname(SN_aes_128_cbc); + ssl_cipher_methods[SSL_ENC_AES256_IDX]= + EVP_get_cipherbyname(SN_aes_256_cbc); + ssl_cipher_methods[SSL_ENC_CAMELLIA128_IDX]= + EVP_get_cipherbyname(SN_camellia_128_cbc); + ssl_cipher_methods[SSL_ENC_CAMELLIA256_IDX]= + EVP_get_cipherbyname(SN_camellia_256_cbc); + ssl_cipher_methods[SSL_ENC_GOST89_IDX]= + EVP_get_cipherbyname(SN_gost89_cnt); + ssl_cipher_methods[SSL_ENC_SEED_IDX]= + EVP_get_cipherbyname(SN_seed_cbc); + + ssl_digest_methods[SSL_MD_MD5_IDX]= + EVP_get_digestbyname(SN_md5); + ssl_mac_secret_size[SSL_MD_MD5_IDX]= + EVP_MD_size(ssl_digest_methods[SSL_MD_MD5_IDX]); + OPENSSL_assert(ssl_mac_secret_size[SSL_MD_MD5_IDX] >= 0); + ssl_digest_methods[SSL_MD_SHA1_IDX]= + EVP_get_digestbyname(SN_sha1); + ssl_mac_secret_size[SSL_MD_SHA1_IDX]= + EVP_MD_size(ssl_digest_methods[SSL_MD_SHA1_IDX]); + OPENSSL_assert(ssl_mac_secret_size[SSL_MD_SHA1_IDX] >= 0); + ssl_digest_methods[SSL_MD_GOST94_IDX]= + EVP_get_digestbyname(SN_id_GostR3411_94); + if (ssl_digest_methods[SSL_MD_GOST94_IDX]) + { + ssl_mac_secret_size[SSL_MD_GOST94_IDX]= + EVP_MD_size(ssl_digest_methods[SSL_MD_GOST94_IDX]); + OPENSSL_assert(ssl_mac_secret_size[SSL_MD_GOST94_IDX] >= 0); + } + ssl_digest_methods[SSL_MD_GOST89MAC_IDX]= + EVP_get_digestbyname(SN_id_Gost28147_89_MAC); + ssl_mac_pkey_id[SSL_MD_GOST89MAC_IDX] = get_optional_pkey_id("gost-mac"); + if (ssl_mac_pkey_id[SSL_MD_GOST89MAC_IDX]) { + ssl_mac_secret_size[SSL_MD_GOST89MAC_IDX]=32; + } + + } +#ifndef OPENSSL_NO_COMP + +static int sk_comp_cmp(const SSL_COMP * const *a, + const SSL_COMP * const *b) + { + return((*a)->id-(*b)->id); + } + +static void load_builtin_compressions(void) + { + int got_write_lock = 0; + + CRYPTO_r_lock(CRYPTO_LOCK_SSL); + if (ssl_comp_methods == NULL) + { + CRYPTO_r_unlock(CRYPTO_LOCK_SSL); + CRYPTO_w_lock(CRYPTO_LOCK_SSL); + got_write_lock = 1; + + if (ssl_comp_methods == NULL) + { + SSL_COMP *comp = NULL; + + MemCheck_off(); + ssl_comp_methods=sk_SSL_COMP_new(sk_comp_cmp); + if (ssl_comp_methods != NULL) + { + comp=(SSL_COMP *)OPENSSL_malloc(sizeof(SSL_COMP)); + if (comp != NULL) + { + comp->method=COMP_zlib(); + if (comp->method + && comp->method->type == NID_undef) + OPENSSL_free(comp); + else + { + comp->id=SSL_COMP_ZLIB_IDX; + comp->name=comp->method->name; + sk_SSL_COMP_push(ssl_comp_methods,comp); + } + } + sk_SSL_COMP_sort(ssl_comp_methods); + } + MemCheck_on(); + } + } + + if (got_write_lock) + CRYPTO_w_unlock(CRYPTO_LOCK_SSL); + else + CRYPTO_r_unlock(CRYPTO_LOCK_SSL); + } +#endif + +int ssl_cipher_get_evp(const SSL_SESSION *s, const EVP_CIPHER **enc, + const EVP_MD **md, int *mac_pkey_type, int *mac_secret_size,SSL_COMP **comp) + { + int i; + const SSL_CIPHER *c; + + c=s->cipher; + if (c == NULL) return(0); + if (comp != NULL) + { + SSL_COMP ctmp; +#ifndef OPENSSL_NO_COMP + load_builtin_compressions(); +#endif + + *comp=NULL; + ctmp.id=s->compress_meth; + if (ssl_comp_methods != NULL) + { + i=sk_SSL_COMP_find(ssl_comp_methods,&ctmp); + if (i >= 0) + *comp=sk_SSL_COMP_value(ssl_comp_methods,i); + else + *comp=NULL; + } + } + + if ((enc == NULL) || (md == NULL)) return(0); + + switch (c->algorithm_enc) + { + case SSL_DES: + i=SSL_ENC_DES_IDX; + break; + case SSL_3DES: + i=SSL_ENC_3DES_IDX; + break; + case SSL_RC4: + i=SSL_ENC_RC4_IDX; + break; + case SSL_RC2: + i=SSL_ENC_RC2_IDX; + break; + case SSL_IDEA: + i=SSL_ENC_IDEA_IDX; + break; + case SSL_eNULL: + i=SSL_ENC_NULL_IDX; + break; + case SSL_AES128: + i=SSL_ENC_AES128_IDX; + break; + case SSL_AES256: + i=SSL_ENC_AES256_IDX; + break; + case SSL_CAMELLIA128: + i=SSL_ENC_CAMELLIA128_IDX; + break; + case SSL_CAMELLIA256: + i=SSL_ENC_CAMELLIA256_IDX; + break; + case SSL_eGOST2814789CNT: + i=SSL_ENC_GOST89_IDX; + break; + case SSL_SEED: + i=SSL_ENC_SEED_IDX; + break; + default: + i= -1; + break; + } + + if ((i < 0) || (i > SSL_ENC_NUM_IDX)) + *enc=NULL; + else + { + if (i == SSL_ENC_NULL_IDX) + *enc=EVP_enc_null(); + else + *enc=ssl_cipher_methods[i]; + } + + switch (c->algorithm_mac) + { + case SSL_MD5: + i=SSL_MD_MD5_IDX; + break; + case SSL_SHA1: + i=SSL_MD_SHA1_IDX; + break; + case SSL_GOST94: + i = SSL_MD_GOST94_IDX; + break; + case SSL_GOST89MAC: + i = SSL_MD_GOST89MAC_IDX; + break; + default: + i= -1; + break; + } + if ((i < 0) || (i > SSL_MD_NUM_IDX)) + { + *md=NULL; + if (mac_pkey_type!=NULL) *mac_pkey_type = NID_undef; + if (mac_secret_size!=NULL) *mac_secret_size = 0; + + } + else + { + *md=ssl_digest_methods[i]; + if (mac_pkey_type!=NULL) *mac_pkey_type = ssl_mac_pkey_id[i]; + if (mac_secret_size!=NULL) *mac_secret_size = ssl_mac_secret_size[i]; + } + + if ((*enc != NULL) && (*md != NULL) && (!mac_pkey_type||*mac_pkey_type != NID_undef)) + return(1); + else + return(0); + } + +int ssl_get_handshake_digest(int idx, long *mask, const EVP_MD **md) +{ + if (idx <0||idx>=SSL_MD_NUM_IDX) + { + return 0; + } + if (ssl_handshake_digest_flag[idx]==0) return 0; + *mask = ssl_handshake_digest_flag[idx]; + *md = ssl_digest_methods[idx]; + return 1; +} + +#define ITEM_SEP(a) \ + (((a) == ':') || ((a) == ' ') || ((a) == ';') || ((a) == ',')) + +static void ll_append_tail(CIPHER_ORDER **head, CIPHER_ORDER *curr, + CIPHER_ORDER **tail) + { + if (curr == *tail) return; + if (curr == *head) + *head=curr->next; + if (curr->prev != NULL) + curr->prev->next=curr->next; + if (curr->next != NULL) + curr->next->prev=curr->prev; + (*tail)->next=curr; + curr->prev= *tail; + curr->next=NULL; + *tail=curr; + } + +static void ll_append_head(CIPHER_ORDER **head, CIPHER_ORDER *curr, + CIPHER_ORDER **tail) + { + if (curr == *head) return; + if (curr == *tail) + *tail=curr->prev; + if (curr->next != NULL) + curr->next->prev=curr->prev; + if (curr->prev != NULL) + curr->prev->next=curr->next; + (*head)->prev=curr; + curr->next= *head; + curr->prev=NULL; + *head=curr; + } + +static void ssl_cipher_get_disabled(unsigned long *mkey, unsigned long *auth, unsigned long *enc, unsigned long *mac, unsigned long *ssl) + { + *mkey = 0; + *auth = 0; + *enc = 0; + *mac = 0; + *ssl = 0; + +#ifdef OPENSSL_NO_RSA + *mkey |= SSL_kRSA; + *auth |= SSL_aRSA; +#endif +#ifdef OPENSSL_NO_DSA + *auth |= SSL_aDSS; +#endif + *mkey |= SSL_kDHr|SSL_kDHd; /* no such ciphersuites supported! */ + *auth |= SSL_aDH; +#ifdef OPENSSL_NO_DH + *mkey |= SSL_kDHr|SSL_kDHd|SSL_kEDH; + *auth |= SSL_aDH; +#endif +#ifdef OPENSSL_NO_KRB5 + *mkey |= SSL_kKRB5; + *auth |= SSL_aKRB5; +#endif +#ifdef OPENSSL_NO_ECDSA + *auth |= SSL_aECDSA; +#endif +#ifdef OPENSSL_NO_ECDH + *mkey |= SSL_kECDHe|SSL_kECDHr; + *auth |= SSL_aECDH; +#endif +#ifdef OPENSSL_NO_PSK + *mkey |= SSL_kPSK; + *auth |= SSL_aPSK; +#endif + /* Check for presence of GOST 34.10 algorithms, and if they + * do not present, disable appropriate auth and key exchange */ + if (!get_optional_pkey_id("gost94")) { + *auth |= SSL_aGOST94; + } + if (!get_optional_pkey_id("gost2001")) { + *auth |= SSL_aGOST01; + } + /* Disable GOST key exchange if no GOST signature algs are available * */ + if ((*auth & (SSL_aGOST94|SSL_aGOST01)) == (SSL_aGOST94|SSL_aGOST01)) { + *mkey |= SSL_kGOST; + } +#ifdef SSL_FORBID_ENULL + *enc |= SSL_eNULL; +#endif + + + + *enc |= (ssl_cipher_methods[SSL_ENC_DES_IDX ] == NULL) ? SSL_DES :0; + *enc |= (ssl_cipher_methods[SSL_ENC_3DES_IDX] == NULL) ? SSL_3DES:0; + *enc |= (ssl_cipher_methods[SSL_ENC_RC4_IDX ] == NULL) ? SSL_RC4 :0; + *enc |= (ssl_cipher_methods[SSL_ENC_RC2_IDX ] == NULL) ? SSL_RC2 :0; + *enc |= (ssl_cipher_methods[SSL_ENC_IDEA_IDX] == NULL) ? SSL_IDEA:0; + *enc |= (ssl_cipher_methods[SSL_ENC_AES128_IDX] == NULL) ? SSL_AES128:0; + *enc |= (ssl_cipher_methods[SSL_ENC_AES256_IDX] == NULL) ? SSL_AES256:0; + *enc |= (ssl_cipher_methods[SSL_ENC_CAMELLIA128_IDX] == NULL) ? SSL_CAMELLIA128:0; + *enc |= (ssl_cipher_methods[SSL_ENC_CAMELLIA256_IDX] == NULL) ? SSL_CAMELLIA256:0; + *enc |= (ssl_cipher_methods[SSL_ENC_GOST89_IDX] == NULL) ? SSL_eGOST2814789CNT:0; + *enc |= (ssl_cipher_methods[SSL_ENC_SEED_IDX] == NULL) ? SSL_SEED:0; + + *mac |= (ssl_digest_methods[SSL_MD_MD5_IDX ] == NULL) ? SSL_MD5 :0; + *mac |= (ssl_digest_methods[SSL_MD_SHA1_IDX] == NULL) ? SSL_SHA1:0; + *mac |= (ssl_digest_methods[SSL_MD_GOST94_IDX] == NULL) ? SSL_GOST94:0; + *mac |= (ssl_digest_methods[SSL_MD_GOST89MAC_IDX] == NULL || ssl_mac_pkey_id[SSL_MD_GOST89MAC_IDX]==NID_undef)? SSL_GOST89MAC:0; + + } + +static void ssl_cipher_collect_ciphers(const SSL_METHOD *ssl_method, + int num_of_ciphers, + unsigned long disabled_mkey, unsigned long disabled_auth, + unsigned long disabled_enc, unsigned long disabled_mac, + unsigned long disabled_ssl, + CIPHER_ORDER *co_list, + CIPHER_ORDER **head_p, CIPHER_ORDER **tail_p) + { + int i, co_list_num; + const SSL_CIPHER *c; + + /* + * We have num_of_ciphers descriptions compiled in, depending on the + * method selected (SSLv2 and/or SSLv3, TLSv1 etc). + * These will later be sorted in a linked list with at most num + * entries. + */ + + /* Get the initial list of ciphers */ + co_list_num = 0; /* actual count of ciphers */ + for (i = 0; i < num_of_ciphers; i++) + { + c = ssl_method->get_cipher(i); + /* drop those that use any of that is not available */ + if ((c != NULL) && c->valid && + !(c->algorithm_mkey & disabled_mkey) && + !(c->algorithm_auth & disabled_auth) && + !(c->algorithm_enc & disabled_enc) && + !(c->algorithm_mac & disabled_mac) && + !(c->algorithm_ssl & disabled_ssl)) + { + co_list[co_list_num].cipher = c; + co_list[co_list_num].next = NULL; + co_list[co_list_num].prev = NULL; + co_list[co_list_num].active = 0; + co_list_num++; +#ifdef KSSL_DEBUG + printf("\t%d: %s %lx %lx %lx\n",i,c->name,c->id,c->algorithm_mkey,c->algorithm_auth); +#endif /* KSSL_DEBUG */ + /* + if (!sk_push(ca_list,(char *)c)) goto err; + */ + } + } + + /* + * Prepare linked list from list entries + */ + if (co_list_num > 0) + { + co_list[0].prev = NULL; + + if (co_list_num > 1) + { + co_list[0].next = &co_list[1]; + + for (i = 1; i < co_list_num - 1; i++) + { + co_list[i].prev = &co_list[i - 1]; + co_list[i].next = &co_list[i + 1]; + } + + co_list[co_list_num - 1].prev = &co_list[co_list_num - 2]; + } + + co_list[co_list_num - 1].next = NULL; + + *head_p = &co_list[0]; + *tail_p = &co_list[co_list_num - 1]; + } + } + +static void ssl_cipher_collect_aliases(const SSL_CIPHER **ca_list, + int num_of_group_aliases, + unsigned long disabled_mkey, unsigned long disabled_auth, + unsigned long disabled_enc, unsigned long disabled_mac, + unsigned long disabled_ssl, + CIPHER_ORDER *head) + { + CIPHER_ORDER *ciph_curr; + const SSL_CIPHER **ca_curr; + int i; + unsigned long mask_mkey = ~disabled_mkey; + unsigned long mask_auth = ~disabled_auth; + unsigned long mask_enc = ~disabled_enc; + unsigned long mask_mac = ~disabled_mac; + unsigned long mask_ssl = ~disabled_ssl; + + /* + * First, add the real ciphers as already collected + */ + ciph_curr = head; + ca_curr = ca_list; + while (ciph_curr != NULL) + { + *ca_curr = ciph_curr->cipher; + ca_curr++; + ciph_curr = ciph_curr->next; + } + + /* + * Now we add the available ones from the cipher_aliases[] table. + * They represent either one or more algorithms, some of which + * in any affected category must be supported (set in enabled_mask), + * or represent a cipher strength value (will be added in any case because algorithms=0). + */ + for (i = 0; i < num_of_group_aliases; i++) + { + unsigned long algorithm_mkey = cipher_aliases[i].algorithm_mkey; + unsigned long algorithm_auth = cipher_aliases[i].algorithm_auth; + unsigned long algorithm_enc = cipher_aliases[i].algorithm_enc; + unsigned long algorithm_mac = cipher_aliases[i].algorithm_mac; + unsigned long algorithm_ssl = cipher_aliases[i].algorithm_ssl; + + if (algorithm_mkey) + if ((algorithm_mkey & mask_mkey) == 0) + continue; + + if (algorithm_auth) + if ((algorithm_auth & mask_auth) == 0) + continue; + + if (algorithm_enc) + if ((algorithm_enc & mask_enc) == 0) + continue; + + if (algorithm_mac) + if ((algorithm_mac & mask_mac) == 0) + continue; + + if (algorithm_ssl) + if ((algorithm_ssl & mask_ssl) == 0) + continue; + + *ca_curr = (SSL_CIPHER *)(cipher_aliases + i); + ca_curr++; + } + + *ca_curr = NULL; /* end of list */ + } + +static void ssl_cipher_apply_rule(unsigned long cipher_id, + unsigned long alg_mkey, unsigned long alg_auth, + unsigned long alg_enc, unsigned long alg_mac, + unsigned long alg_ssl, + unsigned long algo_strength, + int rule, int strength_bits, + CIPHER_ORDER **head_p, CIPHER_ORDER **tail_p) + { + CIPHER_ORDER *head, *tail, *curr, *curr2, *last; + const SSL_CIPHER *cp; + int reverse = 0; + +#ifdef CIPHER_DEBUG + printf("Applying rule %d with %08lx/%08lx/%08lx/%08lx/%08lx %08lx (%d)\n", + rule, alg_mkey, alg_auth, alg_enc, alg_mac, alg_ssl, algo_strength, strength_bits); +#endif + + if (rule == CIPHER_DEL) + reverse = 1; /* needed to maintain sorting between currently deleted ciphers */ + + head = *head_p; + tail = *tail_p; + + if (reverse) + { + curr = tail; + last = head; + } + else + { + curr = head; + last = tail; + } + + curr2 = curr; + for (;;) + { + if ((curr == NULL) || (curr == last)) break; + curr = curr2; + curr2 = reverse ? curr->prev : curr->next; + + cp = curr->cipher; + + /* + * Selection criteria is either the value of strength_bits + * or the algorithms used. + */ + if (strength_bits >= 0) + { + if (strength_bits != cp->strength_bits) + continue; + } + else + { +#ifdef CIPHER_DEBUG + printf("\nName: %s:\nAlgo = %08lx/%08lx/%08lx/%08lx/%08lx Algo_strength = %08lx\n", cp->name, cp->algorithm_mkey, cp->algorithm_auth, cp->algorithm_enc, cp->algorithm_mac, cp->algorithm_ssl, cp->algo_strength); +#endif + + if (alg_mkey && !(alg_mkey & cp->algorithm_mkey)) + continue; + if (alg_auth && !(alg_auth & cp->algorithm_auth)) + continue; + if (alg_enc && !(alg_enc & cp->algorithm_enc)) + continue; + if (alg_mac && !(alg_mac & cp->algorithm_mac)) + continue; + if (alg_ssl && !(alg_ssl & cp->algorithm_ssl)) + continue; + if ((algo_strength & SSL_EXP_MASK) && !(algo_strength & SSL_EXP_MASK & cp->algo_strength)) + continue; + if ((algo_strength & SSL_STRONG_MASK) && !(algo_strength & SSL_STRONG_MASK & cp->algo_strength)) + continue; + } + +#ifdef CIPHER_DEBUG + printf("Action = %d\n", rule); +#endif + + /* add the cipher if it has not been added yet. */ + if (rule == CIPHER_ADD) + { + /* reverse == 0 */ + if (!curr->active) + { + ll_append_tail(&head, curr, &tail); + curr->active = 1; + } + } + /* Move the added cipher to this location */ + else if (rule == CIPHER_ORD) + { + /* reverse == 0 */ + if (curr->active) + { + ll_append_tail(&head, curr, &tail); + } + } + else if (rule == CIPHER_DEL) + { + /* reverse == 1 */ + if (curr->active) + { + /* most recently deleted ciphersuites get best positions + * for any future CIPHER_ADD (note that the CIPHER_DEL loop + * works in reverse to maintain the order) */ + ll_append_head(&head, curr, &tail); + curr->active = 0; + } + } + else if (rule == CIPHER_KILL) + { + /* reverse == 0 */ + if (head == curr) + head = curr->next; + else + curr->prev->next = curr->next; + if (tail == curr) + tail = curr->prev; + curr->active = 0; + if (curr->next != NULL) + curr->next->prev = curr->prev; + if (curr->prev != NULL) + curr->prev->next = curr->next; + curr->next = NULL; + curr->prev = NULL; + } + } + + *head_p = head; + *tail_p = tail; + } + +static int ssl_cipher_strength_sort(CIPHER_ORDER **head_p, + CIPHER_ORDER **tail_p) + { + int max_strength_bits, i, *number_uses; + CIPHER_ORDER *curr; + + /* + * This routine sorts the ciphers with descending strength. The sorting + * must keep the pre-sorted sequence, so we apply the normal sorting + * routine as '+' movement to the end of the list. + */ + max_strength_bits = 0; + curr = *head_p; + while (curr != NULL) + { + if (curr->active && + (curr->cipher->strength_bits > max_strength_bits)) + max_strength_bits = curr->cipher->strength_bits; + curr = curr->next; + } + + number_uses = OPENSSL_malloc((max_strength_bits + 1) * sizeof(int)); + if (!number_uses) + { + SSLerr(SSL_F_SSL_CIPHER_STRENGTH_SORT,ERR_R_MALLOC_FAILURE); + return(0); + } + memset(number_uses, 0, (max_strength_bits + 1) * sizeof(int)); + + /* + * Now find the strength_bits values actually used + */ + curr = *head_p; + while (curr != NULL) + { + if (curr->active) + number_uses[curr->cipher->strength_bits]++; + curr = curr->next; + } + /* + * Go through the list of used strength_bits values in descending + * order. + */ + for (i = max_strength_bits; i >= 0; i--) + if (number_uses[i] > 0) + ssl_cipher_apply_rule(0, 0, 0, 0, 0, 0, 0, CIPHER_ORD, i, head_p, tail_p); + + OPENSSL_free(number_uses); + return(1); + } + +static int ssl_cipher_process_rulestr(const char *rule_str, + CIPHER_ORDER **head_p, CIPHER_ORDER **tail_p, + const SSL_CIPHER **ca_list) + { + unsigned long alg_mkey, alg_auth, alg_enc, alg_mac, alg_ssl, algo_strength; + const char *l, *buf; + int j, multi, found, rule, retval, ok, buflen; + unsigned long cipher_id = 0; + char ch; + + retval = 1; + l = rule_str; + for (;;) + { + ch = *l; + + if (ch == '\0') + break; /* done */ + if (ch == '-') + { rule = CIPHER_DEL; l++; } + else if (ch == '+') + { rule = CIPHER_ORD; l++; } + else if (ch == '!') + { rule = CIPHER_KILL; l++; } + else if (ch == '@') + { rule = CIPHER_SPECIAL; l++; } + else + { rule = CIPHER_ADD; } + + if (ITEM_SEP(ch)) + { + l++; + continue; + } + + alg_mkey = 0; + alg_auth = 0; + alg_enc = 0; + alg_mac = 0; + alg_ssl = 0; + algo_strength = 0; + + for (;;) + { + ch = *l; + buf = l; + buflen = 0; +#ifndef CHARSET_EBCDIC + while ( ((ch >= 'A') && (ch <= 'Z')) || + ((ch >= '0') && (ch <= '9')) || + ((ch >= 'a') && (ch <= 'z')) || + (ch == '-')) +#else + while ( isalnum(ch) || (ch == '-')) +#endif + { + ch = *(++l); + buflen++; + } + + if (buflen == 0) + { + /* + * We hit something we cannot deal with, + * it is no command or separator nor + * alphanumeric, so we call this an error. + */ + SSLerr(SSL_F_SSL_CIPHER_PROCESS_RULESTR, + SSL_R_INVALID_COMMAND); + retval = found = 0; + l++; + break; + } + + if (rule == CIPHER_SPECIAL) + { + found = 0; /* unused -- avoid compiler warning */ + break; /* special treatment */ + } + + /* check for multi-part specification */ + if (ch == '+') + { + multi=1; + l++; + } + else + multi=0; + + /* + * Now search for the cipher alias in the ca_list. Be careful + * with the strncmp, because the "buflen" limitation + * will make the rule "ADH:SOME" and the cipher + * "ADH-MY-CIPHER" look like a match for buflen=3. + * So additionally check whether the cipher name found + * has the correct length. We can save a strlen() call: + * just checking for the '\0' at the right place is + * sufficient, we have to strncmp() anyway. (We cannot + * use strcmp(), because buf is not '\0' terminated.) + */ + j = found = 0; + cipher_id = 0; + while (ca_list[j]) + { + if (!strncmp(buf, ca_list[j]->name, buflen) && + (ca_list[j]->name[buflen] == '\0')) + { + found = 1; + break; + } + else + j++; + } + + if (!found) + break; /* ignore this entry */ + + if (ca_list[j]->algorithm_mkey) + { + if (alg_mkey) + { + alg_mkey &= ca_list[j]->algorithm_mkey; + if (!alg_mkey) { found = 0; break; } + } + else + alg_mkey = ca_list[j]->algorithm_mkey; + } + + if (ca_list[j]->algorithm_auth) + { + if (alg_auth) + { + alg_auth &= ca_list[j]->algorithm_auth; + if (!alg_auth) { found = 0; break; } + } + else + alg_auth = ca_list[j]->algorithm_auth; + } + + if (ca_list[j]->algorithm_enc) + { + if (alg_enc) + { + alg_enc &= ca_list[j]->algorithm_enc; + if (!alg_enc) { found = 0; break; } + } + else + alg_enc = ca_list[j]->algorithm_enc; + } + + if (ca_list[j]->algorithm_mac) + { + if (alg_mac) + { + alg_mac &= ca_list[j]->algorithm_mac; + if (!alg_mac) { found = 0; break; } + } + else + alg_mac = ca_list[j]->algorithm_mac; + } + + if (ca_list[j]->algo_strength & SSL_EXP_MASK) + { + if (algo_strength & SSL_EXP_MASK) + { + algo_strength &= (ca_list[j]->algo_strength & SSL_EXP_MASK) | ~SSL_EXP_MASK; + if (!(algo_strength & SSL_EXP_MASK)) { found = 0; break; } + } + else + algo_strength |= ca_list[j]->algo_strength & SSL_EXP_MASK; + } + + if (ca_list[j]->algo_strength & SSL_STRONG_MASK) + { + if (algo_strength & SSL_STRONG_MASK) + { + algo_strength &= (ca_list[j]->algo_strength & SSL_STRONG_MASK) | ~SSL_STRONG_MASK; + if (!(algo_strength & SSL_STRONG_MASK)) { found = 0; break; } + } + else + algo_strength |= ca_list[j]->algo_strength & SSL_STRONG_MASK; + } + + if (ca_list[j]->valid) + { + /* explicit ciphersuite found; its protocol version + * does not become part of the search pattern!*/ + + cipher_id = ca_list[j]->id; + } + else + { + /* not an explicit ciphersuite; only in this case, the + * protocol version is considered part of the search pattern */ + + if (ca_list[j]->algorithm_ssl) + { + if (alg_ssl) + { + alg_ssl &= ca_list[j]->algorithm_ssl; + if (!alg_ssl) { found = 0; break; } + } + else + alg_ssl = ca_list[j]->algorithm_ssl; + } + } + + if (!multi) break; + } + + /* + * Ok, we have the rule, now apply it + */ + if (rule == CIPHER_SPECIAL) + { /* special command */ + ok = 0; + if ((buflen == 8) && + !strncmp(buf, "STRENGTH", 8)) + ok = ssl_cipher_strength_sort(head_p, tail_p); + else + SSLerr(SSL_F_SSL_CIPHER_PROCESS_RULESTR, + SSL_R_INVALID_COMMAND); + if (ok == 0) + retval = 0; + /* + * We do not support any "multi" options + * together with "@", so throw away the + * rest of the command, if any left, until + * end or ':' is found. + */ + while ((*l != '\0') && !ITEM_SEP(*l)) + l++; + } + else if (found) + { + ssl_cipher_apply_rule(cipher_id, + alg_mkey, alg_auth, alg_enc, alg_mac, alg_ssl, algo_strength, + rule, -1, head_p, tail_p); + } + else + { + while ((*l != '\0') && !ITEM_SEP(*l)) + l++; + } + if (*l == '\0') break; /* done */ + } + + return(retval); + } + +STACK_OF(SSL_CIPHER) *ssl_create_cipher_list(const SSL_METHOD *ssl_method, + STACK_OF(SSL_CIPHER) **cipher_list, + STACK_OF(SSL_CIPHER) **cipher_list_by_id, + const char *rule_str) + { + int ok, num_of_ciphers, num_of_alias_max, num_of_group_aliases; + unsigned long disabled_mkey, disabled_auth, disabled_enc, disabled_mac, disabled_ssl; + STACK_OF(SSL_CIPHER) *cipherstack, *tmp_cipher_list; + const char *rule_p; + CIPHER_ORDER *co_list = NULL, *head = NULL, *tail = NULL, *curr; + const SSL_CIPHER **ca_list = NULL; + + /* + * Return with error if nothing to do. + */ + if (rule_str == NULL || cipher_list == NULL || cipher_list_by_id == NULL) + return NULL; + + /* + * To reduce the work to do we only want to process the compiled + * in algorithms, so we first get the mask of disabled ciphers. + */ + ssl_cipher_get_disabled(&disabled_mkey, &disabled_auth, &disabled_enc, &disabled_mac, &disabled_ssl); + + /* + * Now we have to collect the available ciphers from the compiled + * in ciphers. We cannot get more than the number compiled in, so + * it is used for allocation. + */ + num_of_ciphers = ssl_method->num_ciphers(); +#ifdef KSSL_DEBUG + printf("ssl_create_cipher_list() for %d ciphers\n", num_of_ciphers); +#endif /* KSSL_DEBUG */ + co_list = (CIPHER_ORDER *)OPENSSL_malloc(sizeof(CIPHER_ORDER) * num_of_ciphers); + if (co_list == NULL) + { + SSLerr(SSL_F_SSL_CREATE_CIPHER_LIST,ERR_R_MALLOC_FAILURE); + return(NULL); /* Failure */ + } + + ssl_cipher_collect_ciphers(ssl_method, num_of_ciphers, + disabled_mkey, disabled_auth, disabled_enc, disabled_mac, disabled_ssl, + co_list, &head, &tail); + + + /* Now arrange all ciphers by preference: */ + + /* Everything else being equal, prefer ephemeral ECDH over other key exchange mechanisms */ + ssl_cipher_apply_rule(0, SSL_kEECDH, 0, 0, 0, 0, 0, CIPHER_ADD, -1, &head, &tail); + ssl_cipher_apply_rule(0, SSL_kEECDH, 0, 0, 0, 0, 0, CIPHER_DEL, -1, &head, &tail); + + /* AES is our preferred symmetric cipher */ + ssl_cipher_apply_rule(0, 0, 0, SSL_AES, 0, 0, 0, CIPHER_ADD, -1, &head, &tail); + + /* Temporarily enable everything else for sorting */ + ssl_cipher_apply_rule(0, 0, 0, 0, 0, 0, 0, CIPHER_ADD, -1, &head, &tail); + + /* Low priority for MD5 */ + ssl_cipher_apply_rule(0, 0, 0, 0, SSL_MD5, 0, 0, CIPHER_ORD, -1, &head, &tail); + + /* Move anonymous ciphers to the end. Usually, these will remain disabled. + * (For applications that allow them, they aren't too bad, but we prefer + * authenticated ciphers.) */ + ssl_cipher_apply_rule(0, 0, SSL_aNULL, 0, 0, 0, 0, CIPHER_ORD, -1, &head, &tail); + + /* Move ciphers without forward secrecy to the end */ + ssl_cipher_apply_rule(0, 0, SSL_aECDH, 0, 0, 0, 0, CIPHER_ORD, -1, &head, &tail); + /* ssl_cipher_apply_rule(0, 0, SSL_aDH, 0, 0, 0, 0, CIPHER_ORD, -1, &head, &tail); */ + ssl_cipher_apply_rule(0, SSL_kRSA, 0, 0, 0, 0, 0, CIPHER_ORD, -1, &head, &tail); + ssl_cipher_apply_rule(0, SSL_kPSK, 0,0, 0, 0, 0, CIPHER_ORD, -1, &head, &tail); + ssl_cipher_apply_rule(0, SSL_kKRB5, 0,0, 0, 0, 0, CIPHER_ORD, -1, &head, &tail); + + /* RC4 is sort-of broken -- move the the end */ + ssl_cipher_apply_rule(0, 0, 0, SSL_RC4, 0, 0, 0, CIPHER_ORD, -1, &head, &tail); + + /* Now sort by symmetric encryption strength. The above ordering remains + * in force within each class */ + if (!ssl_cipher_strength_sort(&head, &tail)) + { + OPENSSL_free(co_list); + return NULL; + } + + /* Now disable everything (maintaining the ordering!) */ + ssl_cipher_apply_rule(0, 0, 0, 0, 0, 0, 0, CIPHER_DEL, -1, &head, &tail); + + + /* + * We also need cipher aliases for selecting based on the rule_str. + * There might be two types of entries in the rule_str: 1) names + * of ciphers themselves 2) aliases for groups of ciphers. + * For 1) we need the available ciphers and for 2) the cipher + * groups of cipher_aliases added together in one list (otherwise + * we would be happy with just the cipher_aliases table). + */ + num_of_group_aliases = sizeof(cipher_aliases) / sizeof(SSL_CIPHER); + num_of_alias_max = num_of_ciphers + num_of_group_aliases + 1; + ca_list = OPENSSL_malloc(sizeof(SSL_CIPHER *) * num_of_alias_max); + if (ca_list == NULL) + { + OPENSSL_free(co_list); + SSLerr(SSL_F_SSL_CREATE_CIPHER_LIST,ERR_R_MALLOC_FAILURE); + return(NULL); /* Failure */ + } + ssl_cipher_collect_aliases(ca_list, num_of_group_aliases, + disabled_mkey, disabled_auth, disabled_enc, + disabled_mac, disabled_ssl, head); + + /* + * If the rule_string begins with DEFAULT, apply the default rule + * before using the (possibly available) additional rules. + */ + ok = 1; + rule_p = rule_str; + if (strncmp(rule_str,"DEFAULT",7) == 0) + { + ok = ssl_cipher_process_rulestr(SSL_DEFAULT_CIPHER_LIST, + &head, &tail, ca_list); + rule_p += 7; + if (*rule_p == ':') + rule_p++; + } + + if (ok && (strlen(rule_p) > 0)) + ok = ssl_cipher_process_rulestr(rule_p, &head, &tail, ca_list); + + OPENSSL_free((void *)ca_list); /* Not needed anymore */ + + if (!ok) + { /* Rule processing failure */ + OPENSSL_free(co_list); + return(NULL); + } + + /* + * Allocate new "cipherstack" for the result, return with error + * if we cannot get one. + */ + if ((cipherstack = sk_SSL_CIPHER_new_null()) == NULL) + { + OPENSSL_free(co_list); + return(NULL); + } + + /* + * The cipher selection for the list is done. The ciphers are added + * to the resulting precedence to the STACK_OF(SSL_CIPHER). + */ + for (curr = head; curr != NULL; curr = curr->next) + { + if (curr->active) + { + sk_SSL_CIPHER_push(cipherstack, curr->cipher); +#ifdef CIPHER_DEBUG + printf("<%s>\n",curr->cipher->name); +#endif + } + } + OPENSSL_free(co_list); /* Not needed any longer */ + + tmp_cipher_list = sk_SSL_CIPHER_dup(cipherstack); + if (tmp_cipher_list == NULL) + { + sk_SSL_CIPHER_free(cipherstack); + return NULL; + } + if (*cipher_list != NULL) + sk_SSL_CIPHER_free(*cipher_list); + *cipher_list = cipherstack; + if (*cipher_list_by_id != NULL) + sk_SSL_CIPHER_free(*cipher_list_by_id); + *cipher_list_by_id = tmp_cipher_list; + (void)sk_SSL_CIPHER_set_cmp_func(*cipher_list_by_id,ssl_cipher_ptr_id_cmp); + + sk_SSL_CIPHER_sort(*cipher_list_by_id); + return(cipherstack); + } + +char *SSL_CIPHER_description(const SSL_CIPHER *cipher, char *buf, int len) + { + int is_export,pkl,kl; + const char *ver,*exp_str; + const char *kx,*au,*enc,*mac; + unsigned long alg_mkey,alg_auth,alg_enc,alg_mac,alg_ssl,alg2; +#ifdef KSSL_DEBUG + static const char *format="%-23s %s Kx=%-8s Au=%-4s Enc=%-9s Mac=%-4s%s AL=%lx/%lx/%lx/%lx/%lx\n"; +#else + static const char *format="%-23s %s Kx=%-8s Au=%-4s Enc=%-9s Mac=%-4s%s\n"; +#endif /* KSSL_DEBUG */ + + alg_mkey = cipher->algorithm_mkey; + alg_auth = cipher->algorithm_auth; + alg_enc = cipher->algorithm_enc; + alg_mac = cipher->algorithm_mac; + alg_ssl = cipher->algorithm_ssl; + + alg2=cipher->algorithm2; + + is_export=SSL_C_IS_EXPORT(cipher); + pkl=SSL_C_EXPORT_PKEYLENGTH(cipher); + kl=SSL_C_EXPORT_KEYLENGTH(cipher); + exp_str=is_export?" export":""; + + if (alg_ssl & SSL_SSLV2) + ver="SSLv2"; + else if (alg_ssl & SSL_SSLV3) + ver="SSLv3"; + else + ver="unknown"; + + switch (alg_mkey) + { + case SSL_kRSA: + kx=is_export?(pkl == 512 ? "RSA(512)" : "RSA(1024)"):"RSA"; + break; + case SSL_kDHr: + kx="DH/RSA"; + break; + case SSL_kDHd: + kx="DH/DSS"; + break; + case SSL_kKRB5: + kx="KRB5"; + break; + case SSL_kEDH: + kx=is_export?(pkl == 512 ? "DH(512)" : "DH(1024)"):"DH"; + break; + case SSL_kECDHr: + kx="ECDH/RSA"; + break; + case SSL_kECDHe: + kx="ECDH/ECDSA"; + break; + case SSL_kEECDH: + kx="ECDH"; + break; + case SSL_kPSK: + kx="PSK"; + break; + default: + kx="unknown"; + } + + switch (alg_auth) + { + case SSL_aRSA: + au="RSA"; + break; + case SSL_aDSS: + au="DSS"; + break; + case SSL_aDH: + au="DH"; + break; + case SSL_aKRB5: + au="KRB5"; + break; + case SSL_aECDH: + au="ECDH"; + break; + case SSL_aNULL: + au="None"; + break; + case SSL_aECDSA: + au="ECDSA"; + break; + case SSL_aPSK: + au="PSK"; + break; + default: + au="unknown"; + break; + } + + switch (alg_enc) + { + case SSL_DES: + enc=(is_export && kl == 5)?"DES(40)":"DES(56)"; + break; + case SSL_3DES: + enc="3DES(168)"; + break; + case SSL_RC4: + enc=is_export?(kl == 5 ? "RC4(40)" : "RC4(56)") + :((alg2&SSL2_CF_8_BYTE_ENC)?"RC4(64)":"RC4(128)"); + break; + case SSL_RC2: + enc=is_export?(kl == 5 ? "RC2(40)" : "RC2(56)"):"RC2(128)"; + break; + case SSL_IDEA: + enc="IDEA(128)"; + break; + case SSL_eNULL: + enc="None"; + break; + case SSL_AES128: + enc="AES(128)"; + break; + case SSL_AES256: + enc="AES(256)"; + break; + case SSL_CAMELLIA128: + enc="Camellia(128)"; + break; + case SSL_CAMELLIA256: + enc="Camellia(256)"; + break; + case SSL_SEED: + enc="SEED(128)"; + break; + default: + enc="unknown"; + break; + } + + switch (alg_mac) + { + case SSL_MD5: + mac="MD5"; + break; + case SSL_SHA1: + mac="SHA1"; + break; + default: + mac="unknown"; + break; + } + + if (buf == NULL) + { + len=128; + buf=OPENSSL_malloc(len); + if (buf == NULL) return("OPENSSL_malloc Error"); + } + else if (len < 128) + return("Buffer too small"); + +#ifdef KSSL_DEBUG + BIO_snprintf(buf,len,format,cipher->name,ver,kx,au,enc,mac,exp_str,alg_mkey,alg_auth,alg_enc,alg_mac,alg_ssl); +#else + BIO_snprintf(buf,len,format,cipher->name,ver,kx,au,enc,mac,exp_str); +#endif /* KSSL_DEBUG */ + return(buf); + } + +char *SSL_CIPHER_get_version(const SSL_CIPHER *c) + { + int i; + + if (c == NULL) return("(NONE)"); + i=(int)(c->id>>24L); + if (i == 3) + return("TLSv1/SSLv3"); + else if (i == 2) + return("SSLv2"); + else + return("unknown"); + } + +/* return the actual cipher being used */ +const char *SSL_CIPHER_get_name(const SSL_CIPHER *c) + { + if (c != NULL) + return(c->name); + return("(NONE)"); + } + +/* number of bits for symmetric cipher */ +int SSL_CIPHER_get_bits(const SSL_CIPHER *c, int *alg_bits) + { + int ret=0; + + if (c != NULL) + { + if (alg_bits != NULL) *alg_bits = c->alg_bits; + ret = c->strength_bits; + } + return(ret); + } + +/* return string version of key exchange algorithm */ +const char* SSL_CIPHER_authentication_method(const SSL_CIPHER* cipher) + { + switch (cipher->algorithm_mkey) + { + case SSL_kRSA: + return SSL_TXT_RSA; + case SSL_kDHr: + return SSL_TXT_DH "_" SSL_TXT_RSA; + case SSL_kDHd: + return SSL_TXT_DH "_" SSL_TXT_DSS; + case SSL_kEDH: + switch (cipher->algorithm_auth) + { + case SSL_aDSS: + return "DHE_" SSL_TXT_DSS; + case SSL_aRSA: + return "DHE_" SSL_TXT_RSA; + case SSL_aNULL: + return SSL_TXT_DH "_anon"; + default: + return "UNKNOWN"; + } + case SSL_kKRB5: + return SSL_TXT_KRB5; + case SSL_kECDHr: + return SSL_TXT_ECDH "_" SSL_TXT_RSA; + case SSL_kECDHe: + return SSL_TXT_ECDH "_" SSL_TXT_ECDSA; + case SSL_kEECDH: + switch (cipher->algorithm_auth) + { + case SSL_aECDSA: + return "ECDHE_" SSL_TXT_ECDSA; + case SSL_aRSA: + return "ECDHE_" SSL_TXT_RSA; + case SSL_aNULL: + return SSL_TXT_ECDH "_anon"; + default: + return "UNKNOWN"; + } + default: + return "UNKNOWN"; + } + } + +SSL_COMP *ssl3_comp_find(STACK_OF(SSL_COMP) *sk, int n) + { + SSL_COMP *ctmp; + int i,nn; + + if ((n == 0) || (sk == NULL)) return(NULL); + nn=sk_SSL_COMP_num(sk); + for (i=0; iid == n) + return(ctmp); + } + return(NULL); + } + +#ifdef OPENSSL_NO_COMP +void *SSL_COMP_get_compression_methods(void) + { + return NULL; + } +int SSL_COMP_add_compression_method(int id, void *cm) + { + return 1; + } + +const char *SSL_COMP_get_name(const void *comp) + { + return NULL; + } +#else +STACK_OF(SSL_COMP) *SSL_COMP_get_compression_methods(void) + { + load_builtin_compressions(); + return(ssl_comp_methods); + } + +int SSL_COMP_add_compression_method(int id, COMP_METHOD *cm) + { + SSL_COMP *comp; + + if (cm == NULL || cm->type == NID_undef) + return 1; + + /* According to draft-ietf-tls-compression-04.txt, the + compression number ranges should be the following: + + 0 to 63: methods defined by the IETF + 64 to 192: external party methods assigned by IANA + 193 to 255: reserved for private use */ + if (id < 193 || id > 255) + { + SSLerr(SSL_F_SSL_COMP_ADD_COMPRESSION_METHOD,SSL_R_COMPRESSION_ID_NOT_WITHIN_PRIVATE_RANGE); + return 0; + } + + MemCheck_off(); + comp=(SSL_COMP *)OPENSSL_malloc(sizeof(SSL_COMP)); + comp->id=id; + comp->method=cm; + load_builtin_compressions(); + if (ssl_comp_methods + && sk_SSL_COMP_find(ssl_comp_methods,comp) >= 0) + { + OPENSSL_free(comp); + MemCheck_on(); + SSLerr(SSL_F_SSL_COMP_ADD_COMPRESSION_METHOD,SSL_R_DUPLICATE_COMPRESSION_ID); + return(1); + } + else if ((ssl_comp_methods == NULL) + || !sk_SSL_COMP_push(ssl_comp_methods,comp)) + { + OPENSSL_free(comp); + MemCheck_on(); + SSLerr(SSL_F_SSL_COMP_ADD_COMPRESSION_METHOD,ERR_R_MALLOC_FAILURE); + return(1); + } + else + { + MemCheck_on(); + return(0); + } + } + +const char *SSL_COMP_get_name(const COMP_METHOD *comp) + { + if (comp) + return comp->name; + return NULL; + } + +#endif diff --git a/node-v0.8.14/deps/openssl/openssl/ssl/ssl_err.c b/node-v0.8.14/deps/openssl/openssl/ssl/ssl_err.c new file mode 100644 index 0000000..4fcd5c0 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/ssl/ssl_err.c @@ -0,0 +1,577 @@ +/* ssl/ssl_err.c */ +/* ==================================================================== + * Copyright (c) 1999-2011 The OpenSSL Project. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. All advertising materials mentioning features or use of this + * software must display the following acknowledgment: + * "This product includes software developed by the OpenSSL Project + * for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)" + * + * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to + * endorse or promote products derived from this software without + * prior written permission. For written permission, please contact + * openssl-core@OpenSSL.org. + * + * 5. Products derived from this software may not be called "OpenSSL" + * nor may "OpenSSL" appear in their names without prior written + * permission of the OpenSSL Project. + * + * 6. Redistributions of any form whatsoever must retain the following + * acknowledgment: + * "This product includes software developed by the OpenSSL Project + * for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)" + * + * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY + * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR + * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, + * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * ==================================================================== + * + * This product includes cryptographic software written by Eric Young + * (eay@cryptsoft.com). This product includes software written by Tim + * Hudson (tjh@cryptsoft.com). + * + */ + +/* NOTE: this file was auto generated by the mkerr.pl script: any changes + * made to it will be overwritten when the script next updates this file, + * only reason strings will be preserved. + */ + +#include +#include +#include + +/* BEGIN ERROR CODES */ +#ifndef OPENSSL_NO_ERR + +#define ERR_FUNC(func) ERR_PACK(ERR_LIB_SSL,func,0) +#define ERR_REASON(reason) ERR_PACK(ERR_LIB_SSL,0,reason) + +static ERR_STRING_DATA SSL_str_functs[]= + { +{ERR_FUNC(SSL_F_CLIENT_CERTIFICATE), "CLIENT_CERTIFICATE"}, +{ERR_FUNC(SSL_F_CLIENT_FINISHED), "CLIENT_FINISHED"}, +{ERR_FUNC(SSL_F_CLIENT_HELLO), "CLIENT_HELLO"}, +{ERR_FUNC(SSL_F_CLIENT_MASTER_KEY), "CLIENT_MASTER_KEY"}, +{ERR_FUNC(SSL_F_D2I_SSL_SESSION), "d2i_SSL_SESSION"}, +{ERR_FUNC(SSL_F_DO_DTLS1_WRITE), "DO_DTLS1_WRITE"}, +{ERR_FUNC(SSL_F_DO_SSL3_WRITE), "DO_SSL3_WRITE"}, +{ERR_FUNC(SSL_F_DTLS1_ACCEPT), "DTLS1_ACCEPT"}, +{ERR_FUNC(SSL_F_DTLS1_ADD_CERT_TO_BUF), "DTLS1_ADD_CERT_TO_BUF"}, +{ERR_FUNC(SSL_F_DTLS1_BUFFER_RECORD), "DTLS1_BUFFER_RECORD"}, +{ERR_FUNC(SSL_F_DTLS1_CLIENT_HELLO), "DTLS1_CLIENT_HELLO"}, +{ERR_FUNC(SSL_F_DTLS1_CONNECT), "DTLS1_CONNECT"}, +{ERR_FUNC(SSL_F_DTLS1_ENC), "DTLS1_ENC"}, +{ERR_FUNC(SSL_F_DTLS1_GET_HELLO_VERIFY), "DTLS1_GET_HELLO_VERIFY"}, +{ERR_FUNC(SSL_F_DTLS1_GET_MESSAGE), "DTLS1_GET_MESSAGE"}, +{ERR_FUNC(SSL_F_DTLS1_GET_MESSAGE_FRAGMENT), "DTLS1_GET_MESSAGE_FRAGMENT"}, +{ERR_FUNC(SSL_F_DTLS1_GET_RECORD), "DTLS1_GET_RECORD"}, +{ERR_FUNC(SSL_F_DTLS1_HANDLE_TIMEOUT), "DTLS1_HANDLE_TIMEOUT"}, +{ERR_FUNC(SSL_F_DTLS1_OUTPUT_CERT_CHAIN), "DTLS1_OUTPUT_CERT_CHAIN"}, +{ERR_FUNC(SSL_F_DTLS1_PREPROCESS_FRAGMENT), "DTLS1_PREPROCESS_FRAGMENT"}, +{ERR_FUNC(SSL_F_DTLS1_PROCESS_OUT_OF_SEQ_MESSAGE), "DTLS1_PROCESS_OUT_OF_SEQ_MESSAGE"}, +{ERR_FUNC(SSL_F_DTLS1_PROCESS_RECORD), "DTLS1_PROCESS_RECORD"}, +{ERR_FUNC(SSL_F_DTLS1_READ_BYTES), "DTLS1_READ_BYTES"}, +{ERR_FUNC(SSL_F_DTLS1_READ_FAILED), "DTLS1_READ_FAILED"}, +{ERR_FUNC(SSL_F_DTLS1_SEND_CERTIFICATE_REQUEST), "DTLS1_SEND_CERTIFICATE_REQUEST"}, +{ERR_FUNC(SSL_F_DTLS1_SEND_CLIENT_CERTIFICATE), "DTLS1_SEND_CLIENT_CERTIFICATE"}, +{ERR_FUNC(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE), "DTLS1_SEND_CLIENT_KEY_EXCHANGE"}, +{ERR_FUNC(SSL_F_DTLS1_SEND_CLIENT_VERIFY), "DTLS1_SEND_CLIENT_VERIFY"}, +{ERR_FUNC(SSL_F_DTLS1_SEND_HELLO_VERIFY_REQUEST), "DTLS1_SEND_HELLO_VERIFY_REQUEST"}, +{ERR_FUNC(SSL_F_DTLS1_SEND_SERVER_CERTIFICATE), "DTLS1_SEND_SERVER_CERTIFICATE"}, +{ERR_FUNC(SSL_F_DTLS1_SEND_SERVER_HELLO), "DTLS1_SEND_SERVER_HELLO"}, +{ERR_FUNC(SSL_F_DTLS1_SEND_SERVER_KEY_EXCHANGE), "DTLS1_SEND_SERVER_KEY_EXCHANGE"}, +{ERR_FUNC(SSL_F_DTLS1_WRITE_APP_DATA_BYTES), "DTLS1_WRITE_APP_DATA_BYTES"}, +{ERR_FUNC(SSL_F_GET_CLIENT_FINISHED), "GET_CLIENT_FINISHED"}, +{ERR_FUNC(SSL_F_GET_CLIENT_HELLO), "GET_CLIENT_HELLO"}, +{ERR_FUNC(SSL_F_GET_CLIENT_MASTER_KEY), "GET_CLIENT_MASTER_KEY"}, +{ERR_FUNC(SSL_F_GET_SERVER_FINISHED), "GET_SERVER_FINISHED"}, +{ERR_FUNC(SSL_F_GET_SERVER_HELLO), "GET_SERVER_HELLO"}, +{ERR_FUNC(SSL_F_GET_SERVER_VERIFY), "GET_SERVER_VERIFY"}, +{ERR_FUNC(SSL_F_I2D_SSL_SESSION), "i2d_SSL_SESSION"}, +{ERR_FUNC(SSL_F_READ_N), "READ_N"}, +{ERR_FUNC(SSL_F_REQUEST_CERTIFICATE), "REQUEST_CERTIFICATE"}, +{ERR_FUNC(SSL_F_SERVER_FINISH), "SERVER_FINISH"}, +{ERR_FUNC(SSL_F_SERVER_HELLO), "SERVER_HELLO"}, +{ERR_FUNC(SSL_F_SERVER_VERIFY), "SERVER_VERIFY"}, +{ERR_FUNC(SSL_F_SSL23_ACCEPT), "SSL23_ACCEPT"}, +{ERR_FUNC(SSL_F_SSL23_CLIENT_HELLO), "SSL23_CLIENT_HELLO"}, +{ERR_FUNC(SSL_F_SSL23_CONNECT), "SSL23_CONNECT"}, +{ERR_FUNC(SSL_F_SSL23_GET_CLIENT_HELLO), "SSL23_GET_CLIENT_HELLO"}, +{ERR_FUNC(SSL_F_SSL23_GET_SERVER_HELLO), "SSL23_GET_SERVER_HELLO"}, +{ERR_FUNC(SSL_F_SSL23_PEEK), "SSL23_PEEK"}, +{ERR_FUNC(SSL_F_SSL23_READ), "SSL23_READ"}, +{ERR_FUNC(SSL_F_SSL23_WRITE), "SSL23_WRITE"}, +{ERR_FUNC(SSL_F_SSL2_ACCEPT), "SSL2_ACCEPT"}, +{ERR_FUNC(SSL_F_SSL2_CONNECT), "SSL2_CONNECT"}, +{ERR_FUNC(SSL_F_SSL2_ENC_INIT), "SSL2_ENC_INIT"}, +{ERR_FUNC(SSL_F_SSL2_GENERATE_KEY_MATERIAL), "SSL2_GENERATE_KEY_MATERIAL"}, +{ERR_FUNC(SSL_F_SSL2_PEEK), "SSL2_PEEK"}, +{ERR_FUNC(SSL_F_SSL2_READ), "SSL2_READ"}, +{ERR_FUNC(SSL_F_SSL2_READ_INTERNAL), "SSL2_READ_INTERNAL"}, +{ERR_FUNC(SSL_F_SSL2_SET_CERTIFICATE), "SSL2_SET_CERTIFICATE"}, +{ERR_FUNC(SSL_F_SSL2_WRITE), "SSL2_WRITE"}, +{ERR_FUNC(SSL_F_SSL3_ACCEPT), "SSL3_ACCEPT"}, +{ERR_FUNC(SSL_F_SSL3_ADD_CERT_TO_BUF), "SSL3_ADD_CERT_TO_BUF"}, +{ERR_FUNC(SSL_F_SSL3_CALLBACK_CTRL), "SSL3_CALLBACK_CTRL"}, +{ERR_FUNC(SSL_F_SSL3_CHANGE_CIPHER_STATE), "SSL3_CHANGE_CIPHER_STATE"}, +{ERR_FUNC(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM), "SSL3_CHECK_CERT_AND_ALGORITHM"}, +{ERR_FUNC(SSL_F_SSL3_CHECK_CLIENT_HELLO), "SSL3_CHECK_CLIENT_HELLO"}, +{ERR_FUNC(SSL_F_SSL3_CLIENT_HELLO), "SSL3_CLIENT_HELLO"}, +{ERR_FUNC(SSL_F_SSL3_CONNECT), "SSL3_CONNECT"}, +{ERR_FUNC(SSL_F_SSL3_CTRL), "SSL3_CTRL"}, +{ERR_FUNC(SSL_F_SSL3_CTX_CTRL), "SSL3_CTX_CTRL"}, +{ERR_FUNC(SSL_F_SSL3_DIGEST_CACHED_RECORDS), "SSL3_DIGEST_CACHED_RECORDS"}, +{ERR_FUNC(SSL_F_SSL3_DO_CHANGE_CIPHER_SPEC), "SSL3_DO_CHANGE_CIPHER_SPEC"}, +{ERR_FUNC(SSL_F_SSL3_ENC), "SSL3_ENC"}, +{ERR_FUNC(SSL_F_SSL3_GENERATE_KEY_BLOCK), "SSL3_GENERATE_KEY_BLOCK"}, +{ERR_FUNC(SSL_F_SSL3_GET_CERTIFICATE_REQUEST), "SSL3_GET_CERTIFICATE_REQUEST"}, +{ERR_FUNC(SSL_F_SSL3_GET_CERT_STATUS), "SSL3_GET_CERT_STATUS"}, +{ERR_FUNC(SSL_F_SSL3_GET_CERT_VERIFY), "SSL3_GET_CERT_VERIFY"}, +{ERR_FUNC(SSL_F_SSL3_GET_CLIENT_CERTIFICATE), "SSL3_GET_CLIENT_CERTIFICATE"}, +{ERR_FUNC(SSL_F_SSL3_GET_CLIENT_HELLO), "SSL3_GET_CLIENT_HELLO"}, +{ERR_FUNC(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE), "SSL3_GET_CLIENT_KEY_EXCHANGE"}, +{ERR_FUNC(SSL_F_SSL3_GET_FINISHED), "SSL3_GET_FINISHED"}, +{ERR_FUNC(SSL_F_SSL3_GET_KEY_EXCHANGE), "SSL3_GET_KEY_EXCHANGE"}, +{ERR_FUNC(SSL_F_SSL3_GET_MESSAGE), "SSL3_GET_MESSAGE"}, +{ERR_FUNC(SSL_F_SSL3_GET_NEW_SESSION_TICKET), "SSL3_GET_NEW_SESSION_TICKET"}, +{ERR_FUNC(SSL_F_SSL3_GET_NEXT_PROTO), "SSL3_GET_NEXT_PROTO"}, +{ERR_FUNC(SSL_F_SSL3_GET_RECORD), "SSL3_GET_RECORD"}, +{ERR_FUNC(SSL_F_SSL3_GET_SERVER_CERTIFICATE), "SSL3_GET_SERVER_CERTIFICATE"}, +{ERR_FUNC(SSL_F_SSL3_GET_SERVER_DONE), "SSL3_GET_SERVER_DONE"}, +{ERR_FUNC(SSL_F_SSL3_GET_SERVER_HELLO), "SSL3_GET_SERVER_HELLO"}, +{ERR_FUNC(SSL_F_SSL3_HANDSHAKE_MAC), "ssl3_handshake_mac"}, +{ERR_FUNC(SSL_F_SSL3_NEW_SESSION_TICKET), "SSL3_NEW_SESSION_TICKET"}, +{ERR_FUNC(SSL_F_SSL3_OUTPUT_CERT_CHAIN), "SSL3_OUTPUT_CERT_CHAIN"}, +{ERR_FUNC(SSL_F_SSL3_PEEK), "SSL3_PEEK"}, +{ERR_FUNC(SSL_F_SSL3_READ_BYTES), "SSL3_READ_BYTES"}, +{ERR_FUNC(SSL_F_SSL3_READ_N), "SSL3_READ_N"}, +{ERR_FUNC(SSL_F_SSL3_SEND_CERTIFICATE_REQUEST), "SSL3_SEND_CERTIFICATE_REQUEST"}, +{ERR_FUNC(SSL_F_SSL3_SEND_CLIENT_CERTIFICATE), "SSL3_SEND_CLIENT_CERTIFICATE"}, +{ERR_FUNC(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE), "SSL3_SEND_CLIENT_KEY_EXCHANGE"}, +{ERR_FUNC(SSL_F_SSL3_SEND_CLIENT_VERIFY), "SSL3_SEND_CLIENT_VERIFY"}, +{ERR_FUNC(SSL_F_SSL3_SEND_SERVER_CERTIFICATE), "SSL3_SEND_SERVER_CERTIFICATE"}, +{ERR_FUNC(SSL_F_SSL3_SEND_SERVER_HELLO), "SSL3_SEND_SERVER_HELLO"}, +{ERR_FUNC(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE), "SSL3_SEND_SERVER_KEY_EXCHANGE"}, +{ERR_FUNC(SSL_F_SSL3_SETUP_KEY_BLOCK), "SSL3_SETUP_KEY_BLOCK"}, +{ERR_FUNC(SSL_F_SSL3_SETUP_READ_BUFFER), "SSL3_SETUP_READ_BUFFER"}, +{ERR_FUNC(SSL_F_SSL3_SETUP_WRITE_BUFFER), "SSL3_SETUP_WRITE_BUFFER"}, +{ERR_FUNC(SSL_F_SSL3_WRITE_BYTES), "SSL3_WRITE_BYTES"}, +{ERR_FUNC(SSL_F_SSL3_WRITE_PENDING), "SSL3_WRITE_PENDING"}, +{ERR_FUNC(SSL_F_SSL_ADD_CLIENTHELLO_RENEGOTIATE_EXT), "SSL_ADD_CLIENTHELLO_RENEGOTIATE_EXT"}, +{ERR_FUNC(SSL_F_SSL_ADD_CLIENTHELLO_TLSEXT), "SSL_ADD_CLIENTHELLO_TLSEXT"}, +{ERR_FUNC(SSL_F_SSL_ADD_DIR_CERT_SUBJECTS_TO_STACK), "SSL_add_dir_cert_subjects_to_stack"}, +{ERR_FUNC(SSL_F_SSL_ADD_FILE_CERT_SUBJECTS_TO_STACK), "SSL_add_file_cert_subjects_to_stack"}, +{ERR_FUNC(SSL_F_SSL_ADD_SERVERHELLO_RENEGOTIATE_EXT), "SSL_ADD_SERVERHELLO_RENEGOTIATE_EXT"}, +{ERR_FUNC(SSL_F_SSL_ADD_SERVERHELLO_TLSEXT), "SSL_ADD_SERVERHELLO_TLSEXT"}, +{ERR_FUNC(SSL_F_SSL_BAD_METHOD), "SSL_BAD_METHOD"}, +{ERR_FUNC(SSL_F_SSL_BYTES_TO_CIPHER_LIST), "SSL_BYTES_TO_CIPHER_LIST"}, +{ERR_FUNC(SSL_F_SSL_CERT_DUP), "SSL_CERT_DUP"}, +{ERR_FUNC(SSL_F_SSL_CERT_INST), "SSL_CERT_INST"}, +{ERR_FUNC(SSL_F_SSL_CERT_INSTANTIATE), "SSL_CERT_INSTANTIATE"}, +{ERR_FUNC(SSL_F_SSL_CERT_NEW), "SSL_CERT_NEW"}, +{ERR_FUNC(SSL_F_SSL_CHECK_PRIVATE_KEY), "SSL_check_private_key"}, +{ERR_FUNC(SSL_F_SSL_CHECK_SERVERHELLO_TLSEXT), "SSL_CHECK_SERVERHELLO_TLSEXT"}, +{ERR_FUNC(SSL_F_SSL_CHECK_SRVR_ECC_CERT_AND_ALG), "SSL_CHECK_SRVR_ECC_CERT_AND_ALG"}, +{ERR_FUNC(SSL_F_SSL_CIPHER_PROCESS_RULESTR), "SSL_CIPHER_PROCESS_RULESTR"}, +{ERR_FUNC(SSL_F_SSL_CIPHER_STRENGTH_SORT), "SSL_CIPHER_STRENGTH_SORT"}, +{ERR_FUNC(SSL_F_SSL_CLEAR), "SSL_clear"}, +{ERR_FUNC(SSL_F_SSL_COMP_ADD_COMPRESSION_METHOD), "SSL_COMP_add_compression_method"}, +{ERR_FUNC(SSL_F_SSL_CREATE_CIPHER_LIST), "SSL_CREATE_CIPHER_LIST"}, +{ERR_FUNC(SSL_F_SSL_CTRL), "SSL_ctrl"}, +{ERR_FUNC(SSL_F_SSL_CTX_CHECK_PRIVATE_KEY), "SSL_CTX_check_private_key"}, +{ERR_FUNC(SSL_F_SSL_CTX_NEW), "SSL_CTX_new"}, +{ERR_FUNC(SSL_F_SSL_CTX_SET_CIPHER_LIST), "SSL_CTX_set_cipher_list"}, +{ERR_FUNC(SSL_F_SSL_CTX_SET_CLIENT_CERT_ENGINE), "SSL_CTX_set_client_cert_engine"}, +{ERR_FUNC(SSL_F_SSL_CTX_SET_PURPOSE), "SSL_CTX_set_purpose"}, +{ERR_FUNC(SSL_F_SSL_CTX_SET_SESSION_ID_CONTEXT), "SSL_CTX_set_session_id_context"}, +{ERR_FUNC(SSL_F_SSL_CTX_SET_SSL_VERSION), "SSL_CTX_set_ssl_version"}, +{ERR_FUNC(SSL_F_SSL_CTX_SET_TRUST), "SSL_CTX_set_trust"}, +{ERR_FUNC(SSL_F_SSL_CTX_USE_CERTIFICATE), "SSL_CTX_use_certificate"}, +{ERR_FUNC(SSL_F_SSL_CTX_USE_CERTIFICATE_ASN1), "SSL_CTX_use_certificate_ASN1"}, +{ERR_FUNC(SSL_F_SSL_CTX_USE_CERTIFICATE_CHAIN_FILE), "SSL_CTX_use_certificate_chain_file"}, +{ERR_FUNC(SSL_F_SSL_CTX_USE_CERTIFICATE_FILE), "SSL_CTX_use_certificate_file"}, +{ERR_FUNC(SSL_F_SSL_CTX_USE_PRIVATEKEY), "SSL_CTX_use_PrivateKey"}, +{ERR_FUNC(SSL_F_SSL_CTX_USE_PRIVATEKEY_ASN1), "SSL_CTX_use_PrivateKey_ASN1"}, +{ERR_FUNC(SSL_F_SSL_CTX_USE_PRIVATEKEY_FILE), "SSL_CTX_use_PrivateKey_file"}, +{ERR_FUNC(SSL_F_SSL_CTX_USE_PSK_IDENTITY_HINT), "SSL_CTX_use_psk_identity_hint"}, +{ERR_FUNC(SSL_F_SSL_CTX_USE_RSAPRIVATEKEY), "SSL_CTX_use_RSAPrivateKey"}, +{ERR_FUNC(SSL_F_SSL_CTX_USE_RSAPRIVATEKEY_ASN1), "SSL_CTX_use_RSAPrivateKey_ASN1"}, +{ERR_FUNC(SSL_F_SSL_CTX_USE_RSAPRIVATEKEY_FILE), "SSL_CTX_use_RSAPrivateKey_file"}, +{ERR_FUNC(SSL_F_SSL_DO_HANDSHAKE), "SSL_do_handshake"}, +{ERR_FUNC(SSL_F_SSL_GET_NEW_SESSION), "SSL_GET_NEW_SESSION"}, +{ERR_FUNC(SSL_F_SSL_GET_PREV_SESSION), "SSL_GET_PREV_SESSION"}, +{ERR_FUNC(SSL_F_SSL_GET_SERVER_SEND_CERT), "SSL_GET_SERVER_SEND_CERT"}, +{ERR_FUNC(SSL_F_SSL_GET_SIGN_PKEY), "SSL_GET_SIGN_PKEY"}, +{ERR_FUNC(SSL_F_SSL_INIT_WBIO_BUFFER), "SSL_INIT_WBIO_BUFFER"}, +{ERR_FUNC(SSL_F_SSL_LOAD_CLIENT_CA_FILE), "SSL_load_client_CA_file"}, +{ERR_FUNC(SSL_F_SSL_NEW), "SSL_new"}, +{ERR_FUNC(SSL_F_SSL_PARSE_CLIENTHELLO_RENEGOTIATE_EXT), "SSL_PARSE_CLIENTHELLO_RENEGOTIATE_EXT"}, +{ERR_FUNC(SSL_F_SSL_PARSE_CLIENTHELLO_TLSEXT), "SSL_PARSE_CLIENTHELLO_TLSEXT"}, +{ERR_FUNC(SSL_F_SSL_PARSE_SERVERHELLO_RENEGOTIATE_EXT), "SSL_PARSE_SERVERHELLO_RENEGOTIATE_EXT"}, +{ERR_FUNC(SSL_F_SSL_PARSE_SERVERHELLO_TLSEXT), "SSL_PARSE_SERVERHELLO_TLSEXT"}, +{ERR_FUNC(SSL_F_SSL_PEEK), "SSL_peek"}, +{ERR_FUNC(SSL_F_SSL_PREPARE_CLIENTHELLO_TLSEXT), "SSL_PREPARE_CLIENTHELLO_TLSEXT"}, +{ERR_FUNC(SSL_F_SSL_PREPARE_SERVERHELLO_TLSEXT), "SSL_PREPARE_SERVERHELLO_TLSEXT"}, +{ERR_FUNC(SSL_F_SSL_READ), "SSL_read"}, +{ERR_FUNC(SSL_F_SSL_RSA_PRIVATE_DECRYPT), "SSL_RSA_PRIVATE_DECRYPT"}, +{ERR_FUNC(SSL_F_SSL_RSA_PUBLIC_ENCRYPT), "SSL_RSA_PUBLIC_ENCRYPT"}, +{ERR_FUNC(SSL_F_SSL_SESSION_NEW), "SSL_SESSION_new"}, +{ERR_FUNC(SSL_F_SSL_SESSION_PRINT_FP), "SSL_SESSION_print_fp"}, +{ERR_FUNC(SSL_F_SSL_SESS_CERT_NEW), "SSL_SESS_CERT_NEW"}, +{ERR_FUNC(SSL_F_SSL_SET_CERT), "SSL_SET_CERT"}, +{ERR_FUNC(SSL_F_SSL_SET_CIPHER_LIST), "SSL_set_cipher_list"}, +{ERR_FUNC(SSL_F_SSL_SET_FD), "SSL_set_fd"}, +{ERR_FUNC(SSL_F_SSL_SET_PKEY), "SSL_SET_PKEY"}, +{ERR_FUNC(SSL_F_SSL_SET_PURPOSE), "SSL_set_purpose"}, +{ERR_FUNC(SSL_F_SSL_SET_RFD), "SSL_set_rfd"}, +{ERR_FUNC(SSL_F_SSL_SET_SESSION), "SSL_set_session"}, +{ERR_FUNC(SSL_F_SSL_SET_SESSION_ID_CONTEXT), "SSL_set_session_id_context"}, +{ERR_FUNC(SSL_F_SSL_SET_SESSION_TICKET_EXT), "SSL_set_session_ticket_ext"}, +{ERR_FUNC(SSL_F_SSL_SET_TRUST), "SSL_set_trust"}, +{ERR_FUNC(SSL_F_SSL_SET_WFD), "SSL_set_wfd"}, +{ERR_FUNC(SSL_F_SSL_SHUTDOWN), "SSL_shutdown"}, +{ERR_FUNC(SSL_F_SSL_UNDEFINED_CONST_FUNCTION), "SSL_UNDEFINED_CONST_FUNCTION"}, +{ERR_FUNC(SSL_F_SSL_UNDEFINED_FUNCTION), "SSL_UNDEFINED_FUNCTION"}, +{ERR_FUNC(SSL_F_SSL_UNDEFINED_VOID_FUNCTION), "SSL_UNDEFINED_VOID_FUNCTION"}, +{ERR_FUNC(SSL_F_SSL_USE_CERTIFICATE), "SSL_use_certificate"}, +{ERR_FUNC(SSL_F_SSL_USE_CERTIFICATE_ASN1), "SSL_use_certificate_ASN1"}, +{ERR_FUNC(SSL_F_SSL_USE_CERTIFICATE_FILE), "SSL_use_certificate_file"}, +{ERR_FUNC(SSL_F_SSL_USE_PRIVATEKEY), "SSL_use_PrivateKey"}, +{ERR_FUNC(SSL_F_SSL_USE_PRIVATEKEY_ASN1), "SSL_use_PrivateKey_ASN1"}, +{ERR_FUNC(SSL_F_SSL_USE_PRIVATEKEY_FILE), "SSL_use_PrivateKey_file"}, +{ERR_FUNC(SSL_F_SSL_USE_PSK_IDENTITY_HINT), "SSL_use_psk_identity_hint"}, +{ERR_FUNC(SSL_F_SSL_USE_RSAPRIVATEKEY), "SSL_use_RSAPrivateKey"}, +{ERR_FUNC(SSL_F_SSL_USE_RSAPRIVATEKEY_ASN1), "SSL_use_RSAPrivateKey_ASN1"}, +{ERR_FUNC(SSL_F_SSL_USE_RSAPRIVATEKEY_FILE), "SSL_use_RSAPrivateKey_file"}, +{ERR_FUNC(SSL_F_SSL_VERIFY_CERT_CHAIN), "SSL_VERIFY_CERT_CHAIN"}, +{ERR_FUNC(SSL_F_SSL_WRITE), "SSL_write"}, +{ERR_FUNC(SSL_F_TLS1_CERT_VERIFY_MAC), "tls1_cert_verify_mac"}, +{ERR_FUNC(SSL_F_TLS1_CHANGE_CIPHER_STATE), "TLS1_CHANGE_CIPHER_STATE"}, +{ERR_FUNC(SSL_F_TLS1_CHECK_SERVERHELLO_TLSEXT), "TLS1_CHECK_SERVERHELLO_TLSEXT"}, +{ERR_FUNC(SSL_F_TLS1_ENC), "TLS1_ENC"}, +{ERR_FUNC(SSL_F_TLS1_PREPARE_CLIENTHELLO_TLSEXT), "TLS1_PREPARE_CLIENTHELLO_TLSEXT"}, +{ERR_FUNC(SSL_F_TLS1_PREPARE_SERVERHELLO_TLSEXT), "TLS1_PREPARE_SERVERHELLO_TLSEXT"}, +{ERR_FUNC(SSL_F_TLS1_PRF), "tls1_prf"}, +{ERR_FUNC(SSL_F_TLS1_SETUP_KEY_BLOCK), "TLS1_SETUP_KEY_BLOCK"}, +{ERR_FUNC(SSL_F_WRITE_PENDING), "WRITE_PENDING"}, +{0,NULL} + }; + +static ERR_STRING_DATA SSL_str_reasons[]= + { +{ERR_REASON(SSL_R_APP_DATA_IN_HANDSHAKE) ,"app data in handshake"}, +{ERR_REASON(SSL_R_ATTEMPT_TO_REUSE_SESSION_IN_DIFFERENT_CONTEXT),"attempt to reuse session in different context"}, +{ERR_REASON(SSL_R_BAD_ALERT_RECORD) ,"bad alert record"}, +{ERR_REASON(SSL_R_BAD_AUTHENTICATION_TYPE),"bad authentication type"}, +{ERR_REASON(SSL_R_BAD_CHANGE_CIPHER_SPEC),"bad change cipher spec"}, +{ERR_REASON(SSL_R_BAD_CHECKSUM) ,"bad checksum"}, +{ERR_REASON(SSL_R_BAD_DATA_RETURNED_BY_CALLBACK),"bad data returned by callback"}, +{ERR_REASON(SSL_R_BAD_DECOMPRESSION) ,"bad decompression"}, +{ERR_REASON(SSL_R_BAD_DH_G_LENGTH) ,"bad dh g length"}, +{ERR_REASON(SSL_R_BAD_DH_PUB_KEY_LENGTH) ,"bad dh pub key length"}, +{ERR_REASON(SSL_R_BAD_DH_P_LENGTH) ,"bad dh p length"}, +{ERR_REASON(SSL_R_BAD_DIGEST_LENGTH) ,"bad digest length"}, +{ERR_REASON(SSL_R_BAD_DSA_SIGNATURE) ,"bad dsa signature"}, +{ERR_REASON(SSL_R_BAD_ECC_CERT) ,"bad ecc cert"}, +{ERR_REASON(SSL_R_BAD_ECDSA_SIGNATURE) ,"bad ecdsa signature"}, +{ERR_REASON(SSL_R_BAD_ECPOINT) ,"bad ecpoint"}, +{ERR_REASON(SSL_R_BAD_HANDSHAKE_LENGTH) ,"bad handshake length"}, +{ERR_REASON(SSL_R_BAD_HELLO_REQUEST) ,"bad hello request"}, +{ERR_REASON(SSL_R_BAD_LENGTH) ,"bad length"}, +{ERR_REASON(SSL_R_BAD_MAC_DECODE) ,"bad mac decode"}, +{ERR_REASON(SSL_R_BAD_MAC_LENGTH) ,"bad mac length"}, +{ERR_REASON(SSL_R_BAD_MESSAGE_TYPE) ,"bad message type"}, +{ERR_REASON(SSL_R_BAD_PACKET_LENGTH) ,"bad packet length"}, +{ERR_REASON(SSL_R_BAD_PROTOCOL_VERSION_NUMBER),"bad protocol version number"}, +{ERR_REASON(SSL_R_BAD_PSK_IDENTITY_HINT_LENGTH),"bad psk identity hint length"}, +{ERR_REASON(SSL_R_BAD_RESPONSE_ARGUMENT) ,"bad response argument"}, +{ERR_REASON(SSL_R_BAD_RSA_DECRYPT) ,"bad rsa decrypt"}, +{ERR_REASON(SSL_R_BAD_RSA_ENCRYPT) ,"bad rsa encrypt"}, +{ERR_REASON(SSL_R_BAD_RSA_E_LENGTH) ,"bad rsa e length"}, +{ERR_REASON(SSL_R_BAD_RSA_MODULUS_LENGTH),"bad rsa modulus length"}, +{ERR_REASON(SSL_R_BAD_RSA_SIGNATURE) ,"bad rsa signature"}, +{ERR_REASON(SSL_R_BAD_SIGNATURE) ,"bad signature"}, +{ERR_REASON(SSL_R_BAD_SSL_FILETYPE) ,"bad ssl filetype"}, +{ERR_REASON(SSL_R_BAD_SSL_SESSION_ID_LENGTH),"bad ssl session id length"}, +{ERR_REASON(SSL_R_BAD_STATE) ,"bad state"}, +{ERR_REASON(SSL_R_BAD_WRITE_RETRY) ,"bad write retry"}, +{ERR_REASON(SSL_R_BIO_NOT_SET) ,"bio not set"}, +{ERR_REASON(SSL_R_BLOCK_CIPHER_PAD_IS_WRONG),"block cipher pad is wrong"}, +{ERR_REASON(SSL_R_BN_LIB) ,"bn lib"}, +{ERR_REASON(SSL_R_CA_DN_LENGTH_MISMATCH) ,"ca dn length mismatch"}, +{ERR_REASON(SSL_R_CA_DN_TOO_LONG) ,"ca dn too long"}, +{ERR_REASON(SSL_R_CCS_RECEIVED_EARLY) ,"ccs received early"}, +{ERR_REASON(SSL_R_CERTIFICATE_VERIFY_FAILED),"certificate verify failed"}, +{ERR_REASON(SSL_R_CERT_LENGTH_MISMATCH) ,"cert length mismatch"}, +{ERR_REASON(SSL_R_CHALLENGE_IS_DIFFERENT),"challenge is different"}, +{ERR_REASON(SSL_R_CIPHER_CODE_WRONG_LENGTH),"cipher code wrong length"}, +{ERR_REASON(SSL_R_CIPHER_OR_HASH_UNAVAILABLE),"cipher or hash unavailable"}, +{ERR_REASON(SSL_R_CIPHER_TABLE_SRC_ERROR),"cipher table src error"}, +{ERR_REASON(SSL_R_CLIENTHELLO_TLSEXT) ,"clienthello tlsext"}, +{ERR_REASON(SSL_R_COMPRESSED_LENGTH_TOO_LONG),"compressed length too long"}, +{ERR_REASON(SSL_R_COMPRESSION_DISABLED) ,"compression disabled"}, +{ERR_REASON(SSL_R_COMPRESSION_FAILURE) ,"compression failure"}, +{ERR_REASON(SSL_R_COMPRESSION_ID_NOT_WITHIN_PRIVATE_RANGE),"compression id not within private range"}, +{ERR_REASON(SSL_R_COMPRESSION_LIBRARY_ERROR),"compression library error"}, +{ERR_REASON(SSL_R_CONNECTION_ID_IS_DIFFERENT),"connection id is different"}, +{ERR_REASON(SSL_R_CONNECTION_TYPE_NOT_SET),"connection type not set"}, +{ERR_REASON(SSL_R_COOKIE_MISMATCH) ,"cookie mismatch"}, +{ERR_REASON(SSL_R_DATA_BETWEEN_CCS_AND_FINISHED),"data between ccs and finished"}, +{ERR_REASON(SSL_R_DATA_LENGTH_TOO_LONG) ,"data length too long"}, +{ERR_REASON(SSL_R_DECRYPTION_FAILED) ,"decryption failed"}, +{ERR_REASON(SSL_R_DECRYPTION_FAILED_OR_BAD_RECORD_MAC),"decryption failed or bad record mac"}, +{ERR_REASON(SSL_R_DH_PUBLIC_VALUE_LENGTH_IS_WRONG),"dh public value length is wrong"}, +{ERR_REASON(SSL_R_DIGEST_CHECK_FAILED) ,"digest check failed"}, +{ERR_REASON(SSL_R_DTLS_MESSAGE_TOO_BIG) ,"dtls message too big"}, +{ERR_REASON(SSL_R_DUPLICATE_COMPRESSION_ID),"duplicate compression id"}, +{ERR_REASON(SSL_R_ECC_CERT_NOT_FOR_KEY_AGREEMENT),"ecc cert not for key agreement"}, +{ERR_REASON(SSL_R_ECC_CERT_NOT_FOR_SIGNING),"ecc cert not for signing"}, +{ERR_REASON(SSL_R_ECC_CERT_SHOULD_HAVE_RSA_SIGNATURE),"ecc cert should have rsa signature"}, +{ERR_REASON(SSL_R_ECC_CERT_SHOULD_HAVE_SHA1_SIGNATURE),"ecc cert should have sha1 signature"}, +{ERR_REASON(SSL_R_ECGROUP_TOO_LARGE_FOR_CIPHER),"ecgroup too large for cipher"}, +{ERR_REASON(SSL_R_ENCRYPTED_LENGTH_TOO_LONG),"encrypted length too long"}, +{ERR_REASON(SSL_R_ERROR_GENERATING_TMP_RSA_KEY),"error generating tmp rsa key"}, +{ERR_REASON(SSL_R_ERROR_IN_RECEIVED_CIPHER_LIST),"error in received cipher list"}, +{ERR_REASON(SSL_R_EXCESSIVE_MESSAGE_SIZE),"excessive message size"}, +{ERR_REASON(SSL_R_EXTRA_DATA_IN_MESSAGE) ,"extra data in message"}, +{ERR_REASON(SSL_R_GOT_A_FIN_BEFORE_A_CCS),"got a fin before a ccs"}, +{ERR_REASON(SSL_R_GOT_NEXT_PROTO_BEFORE_A_CCS),"got next proto before a ccs"}, +{ERR_REASON(SSL_R_GOT_NEXT_PROTO_WITHOUT_EXTENSION),"got next proto without seeing extension"}, +{ERR_REASON(SSL_R_HTTPS_PROXY_REQUEST) ,"https proxy request"}, +{ERR_REASON(SSL_R_HTTP_REQUEST) ,"http request"}, +{ERR_REASON(SSL_R_ILLEGAL_PADDING) ,"illegal padding"}, +{ERR_REASON(SSL_R_INCONSISTENT_COMPRESSION),"inconsistent compression"}, +{ERR_REASON(SSL_R_INVALID_CHALLENGE_LENGTH),"invalid challenge length"}, +{ERR_REASON(SSL_R_INVALID_COMMAND) ,"invalid command"}, +{ERR_REASON(SSL_R_INVALID_COMPRESSION_ALGORITHM),"invalid compression algorithm"}, +{ERR_REASON(SSL_R_INVALID_PURPOSE) ,"invalid purpose"}, +{ERR_REASON(SSL_R_INVALID_STATUS_RESPONSE),"invalid status response"}, +{ERR_REASON(SSL_R_INVALID_TICKET_KEYS_LENGTH),"invalid ticket keys length"}, +{ERR_REASON(SSL_R_INVALID_TRUST) ,"invalid trust"}, +{ERR_REASON(SSL_R_KEY_ARG_TOO_LONG) ,"key arg too long"}, +{ERR_REASON(SSL_R_KRB5) ,"krb5"}, +{ERR_REASON(SSL_R_KRB5_C_CC_PRINC) ,"krb5 client cc principal (no tkt?)"}, +{ERR_REASON(SSL_R_KRB5_C_GET_CRED) ,"krb5 client get cred"}, +{ERR_REASON(SSL_R_KRB5_C_INIT) ,"krb5 client init"}, +{ERR_REASON(SSL_R_KRB5_C_MK_REQ) ,"krb5 client mk_req (expired tkt?)"}, +{ERR_REASON(SSL_R_KRB5_S_BAD_TICKET) ,"krb5 server bad ticket"}, +{ERR_REASON(SSL_R_KRB5_S_INIT) ,"krb5 server init"}, +{ERR_REASON(SSL_R_KRB5_S_RD_REQ) ,"krb5 server rd_req (keytab perms?)"}, +{ERR_REASON(SSL_R_KRB5_S_TKT_EXPIRED) ,"krb5 server tkt expired"}, +{ERR_REASON(SSL_R_KRB5_S_TKT_NYV) ,"krb5 server tkt not yet valid"}, +{ERR_REASON(SSL_R_KRB5_S_TKT_SKEW) ,"krb5 server tkt skew"}, +{ERR_REASON(SSL_R_LENGTH_MISMATCH) ,"length mismatch"}, +{ERR_REASON(SSL_R_LENGTH_TOO_SHORT) ,"length too short"}, +{ERR_REASON(SSL_R_LIBRARY_BUG) ,"library bug"}, +{ERR_REASON(SSL_R_LIBRARY_HAS_NO_CIPHERS),"library has no ciphers"}, +{ERR_REASON(SSL_R_MESSAGE_TOO_LONG) ,"message too long"}, +{ERR_REASON(SSL_R_MISSING_DH_DSA_CERT) ,"missing dh dsa cert"}, +{ERR_REASON(SSL_R_MISSING_DH_KEY) ,"missing dh key"}, +{ERR_REASON(SSL_R_MISSING_DH_RSA_CERT) ,"missing dh rsa cert"}, +{ERR_REASON(SSL_R_MISSING_DSA_SIGNING_CERT),"missing dsa signing cert"}, +{ERR_REASON(SSL_R_MISSING_EXPORT_TMP_DH_KEY),"missing export tmp dh key"}, +{ERR_REASON(SSL_R_MISSING_EXPORT_TMP_RSA_KEY),"missing export tmp rsa key"}, +{ERR_REASON(SSL_R_MISSING_RSA_CERTIFICATE),"missing rsa certificate"}, +{ERR_REASON(SSL_R_MISSING_RSA_ENCRYPTING_CERT),"missing rsa encrypting cert"}, +{ERR_REASON(SSL_R_MISSING_RSA_SIGNING_CERT),"missing rsa signing cert"}, +{ERR_REASON(SSL_R_MISSING_TMP_DH_KEY) ,"missing tmp dh key"}, +{ERR_REASON(SSL_R_MISSING_TMP_ECDH_KEY) ,"missing tmp ecdh key"}, +{ERR_REASON(SSL_R_MISSING_TMP_RSA_KEY) ,"missing tmp rsa key"}, +{ERR_REASON(SSL_R_MISSING_TMP_RSA_PKEY) ,"missing tmp rsa pkey"}, +{ERR_REASON(SSL_R_MISSING_VERIFY_MESSAGE),"missing verify message"}, +{ERR_REASON(SSL_R_MULTIPLE_SGC_RESTARTS) ,"multiple sgc restarts"}, +{ERR_REASON(SSL_R_NON_SSLV2_INITIAL_PACKET),"non sslv2 initial packet"}, +{ERR_REASON(SSL_R_NO_CERTIFICATES_RETURNED),"no certificates returned"}, +{ERR_REASON(SSL_R_NO_CERTIFICATE_ASSIGNED),"no certificate assigned"}, +{ERR_REASON(SSL_R_NO_CERTIFICATE_RETURNED),"no certificate returned"}, +{ERR_REASON(SSL_R_NO_CERTIFICATE_SET) ,"no certificate set"}, +{ERR_REASON(SSL_R_NO_CERTIFICATE_SPECIFIED),"no certificate specified"}, +{ERR_REASON(SSL_R_NO_CIPHERS_AVAILABLE) ,"no ciphers available"}, +{ERR_REASON(SSL_R_NO_CIPHERS_PASSED) ,"no ciphers passed"}, +{ERR_REASON(SSL_R_NO_CIPHERS_SPECIFIED) ,"no ciphers specified"}, +{ERR_REASON(SSL_R_NO_CIPHER_LIST) ,"no cipher list"}, +{ERR_REASON(SSL_R_NO_CIPHER_MATCH) ,"no cipher match"}, +{ERR_REASON(SSL_R_NO_CLIENT_CERT_METHOD) ,"no client cert method"}, +{ERR_REASON(SSL_R_NO_CLIENT_CERT_RECEIVED),"no client cert received"}, +{ERR_REASON(SSL_R_NO_COMPRESSION_SPECIFIED),"no compression specified"}, +{ERR_REASON(SSL_R_NO_GOST_CERTIFICATE_SENT_BY_PEER),"Peer haven't sent GOST certificate, required for selected ciphersuite"}, +{ERR_REASON(SSL_R_NO_METHOD_SPECIFIED) ,"no method specified"}, +{ERR_REASON(SSL_R_NO_PRIVATEKEY) ,"no privatekey"}, +{ERR_REASON(SSL_R_NO_PRIVATE_KEY_ASSIGNED),"no private key assigned"}, +{ERR_REASON(SSL_R_NO_PROTOCOLS_AVAILABLE),"no protocols available"}, +{ERR_REASON(SSL_R_NO_PUBLICKEY) ,"no publickey"}, +{ERR_REASON(SSL_R_NO_RENEGOTIATION) ,"no renegotiation"}, +{ERR_REASON(SSL_R_NO_REQUIRED_DIGEST) ,"digest requred for handshake isn't computed"}, +{ERR_REASON(SSL_R_NO_SHARED_CIPHER) ,"no shared cipher"}, +{ERR_REASON(SSL_R_NO_VERIFY_CALLBACK) ,"no verify callback"}, +{ERR_REASON(SSL_R_NULL_SSL_CTX) ,"null ssl ctx"}, +{ERR_REASON(SSL_R_NULL_SSL_METHOD_PASSED),"null ssl method passed"}, +{ERR_REASON(SSL_R_OLD_SESSION_CIPHER_NOT_RETURNED),"old session cipher not returned"}, +{ERR_REASON(SSL_R_OLD_SESSION_COMPRESSION_ALGORITHM_NOT_RETURNED),"old session compression algorithm not returned"}, +{ERR_REASON(SSL_R_ONLY_TLS_ALLOWED_IN_FIPS_MODE),"only tls allowed in fips mode"}, +{ERR_REASON(SSL_R_OPAQUE_PRF_INPUT_TOO_LONG),"opaque PRF input too long"}, +{ERR_REASON(SSL_R_PACKET_LENGTH_TOO_LONG),"packet length too long"}, +{ERR_REASON(SSL_R_PARSE_TLSEXT) ,"parse tlsext"}, +{ERR_REASON(SSL_R_PATH_TOO_LONG) ,"path too long"}, +{ERR_REASON(SSL_R_PEER_DID_NOT_RETURN_A_CERTIFICATE),"peer did not return a certificate"}, +{ERR_REASON(SSL_R_PEER_ERROR) ,"peer error"}, +{ERR_REASON(SSL_R_PEER_ERROR_CERTIFICATE),"peer error certificate"}, +{ERR_REASON(SSL_R_PEER_ERROR_NO_CERTIFICATE),"peer error no certificate"}, +{ERR_REASON(SSL_R_PEER_ERROR_NO_CIPHER) ,"peer error no cipher"}, +{ERR_REASON(SSL_R_PEER_ERROR_UNSUPPORTED_CERTIFICATE_TYPE),"peer error unsupported certificate type"}, +{ERR_REASON(SSL_R_PRE_MAC_LENGTH_TOO_LONG),"pre mac length too long"}, +{ERR_REASON(SSL_R_PROBLEMS_MAPPING_CIPHER_FUNCTIONS),"problems mapping cipher functions"}, +{ERR_REASON(SSL_R_PROTOCOL_IS_SHUTDOWN) ,"protocol is shutdown"}, +{ERR_REASON(SSL_R_PSK_IDENTITY_NOT_FOUND),"psk identity not found"}, +{ERR_REASON(SSL_R_PSK_NO_CLIENT_CB) ,"psk no client cb"}, +{ERR_REASON(SSL_R_PSK_NO_SERVER_CB) ,"psk no server cb"}, +{ERR_REASON(SSL_R_PUBLIC_KEY_ENCRYPT_ERROR),"public key encrypt error"}, +{ERR_REASON(SSL_R_PUBLIC_KEY_IS_NOT_RSA) ,"public key is not rsa"}, +{ERR_REASON(SSL_R_PUBLIC_KEY_NOT_RSA) ,"public key not rsa"}, +{ERR_REASON(SSL_R_READ_BIO_NOT_SET) ,"read bio not set"}, +{ERR_REASON(SSL_R_READ_TIMEOUT_EXPIRED) ,"read timeout expired"}, +{ERR_REASON(SSL_R_READ_WRONG_PACKET_TYPE),"read wrong packet type"}, +{ERR_REASON(SSL_R_RECORD_LENGTH_MISMATCH),"record length mismatch"}, +{ERR_REASON(SSL_R_RECORD_TOO_LARGE) ,"record too large"}, +{ERR_REASON(SSL_R_RECORD_TOO_SMALL) ,"record too small"}, +{ERR_REASON(SSL_R_RENEGOTIATE_EXT_TOO_LONG),"renegotiate ext too long"}, +{ERR_REASON(SSL_R_RENEGOTIATION_ENCODING_ERR),"renegotiation encoding err"}, +{ERR_REASON(SSL_R_RENEGOTIATION_MISMATCH),"renegotiation mismatch"}, +{ERR_REASON(SSL_R_REQUIRED_CIPHER_MISSING),"required cipher missing"}, +{ERR_REASON(SSL_R_REQUIRED_COMPRESSSION_ALGORITHM_MISSING),"required compresssion algorithm missing"}, +{ERR_REASON(SSL_R_REUSE_CERT_LENGTH_NOT_ZERO),"reuse cert length not zero"}, +{ERR_REASON(SSL_R_REUSE_CERT_TYPE_NOT_ZERO),"reuse cert type not zero"}, +{ERR_REASON(SSL_R_REUSE_CIPHER_LIST_NOT_ZERO),"reuse cipher list not zero"}, +{ERR_REASON(SSL_R_SCSV_RECEIVED_WHEN_RENEGOTIATING),"scsv received when renegotiating"}, +{ERR_REASON(SSL_R_SERVERHELLO_TLSEXT) ,"serverhello tlsext"}, +{ERR_REASON(SSL_R_SESSION_ID_CONTEXT_UNINITIALIZED),"session id context uninitialized"}, +{ERR_REASON(SSL_R_SESSION_MAY_NOT_BE_CREATED),"session may not be created"}, +{ERR_REASON(SSL_R_SHORT_READ) ,"short read"}, +{ERR_REASON(SSL_R_SIGNATURE_FOR_NON_SIGNING_CERTIFICATE),"signature for non signing certificate"}, +{ERR_REASON(SSL_R_SSL23_DOING_SESSION_ID_REUSE),"ssl23 doing session id reuse"}, +{ERR_REASON(SSL_R_SSL2_CONNECTION_ID_TOO_LONG),"ssl2 connection id too long"}, +{ERR_REASON(SSL_R_SSL3_EXT_INVALID_ECPOINTFORMAT),"ssl3 ext invalid ecpointformat"}, +{ERR_REASON(SSL_R_SSL3_EXT_INVALID_SERVERNAME),"ssl3 ext invalid servername"}, +{ERR_REASON(SSL_R_SSL3_EXT_INVALID_SERVERNAME_TYPE),"ssl3 ext invalid servername type"}, +{ERR_REASON(SSL_R_SSL3_SESSION_ID_TOO_LONG),"ssl3 session id too long"}, +{ERR_REASON(SSL_R_SSL3_SESSION_ID_TOO_SHORT),"ssl3 session id too short"}, +{ERR_REASON(SSL_R_SSLV3_ALERT_BAD_CERTIFICATE),"sslv3 alert bad certificate"}, +{ERR_REASON(SSL_R_SSLV3_ALERT_BAD_RECORD_MAC),"sslv3 alert bad record mac"}, +{ERR_REASON(SSL_R_SSLV3_ALERT_CERTIFICATE_EXPIRED),"sslv3 alert certificate expired"}, +{ERR_REASON(SSL_R_SSLV3_ALERT_CERTIFICATE_REVOKED),"sslv3 alert certificate revoked"}, +{ERR_REASON(SSL_R_SSLV3_ALERT_CERTIFICATE_UNKNOWN),"sslv3 alert certificate unknown"}, +{ERR_REASON(SSL_R_SSLV3_ALERT_DECOMPRESSION_FAILURE),"sslv3 alert decompression failure"}, +{ERR_REASON(SSL_R_SSLV3_ALERT_HANDSHAKE_FAILURE),"sslv3 alert handshake failure"}, +{ERR_REASON(SSL_R_SSLV3_ALERT_ILLEGAL_PARAMETER),"sslv3 alert illegal parameter"}, +{ERR_REASON(SSL_R_SSLV3_ALERT_NO_CERTIFICATE),"sslv3 alert no certificate"}, +{ERR_REASON(SSL_R_SSLV3_ALERT_UNEXPECTED_MESSAGE),"sslv3 alert unexpected message"}, +{ERR_REASON(SSL_R_SSLV3_ALERT_UNSUPPORTED_CERTIFICATE),"sslv3 alert unsupported certificate"}, +{ERR_REASON(SSL_R_SSL_CTX_HAS_NO_DEFAULT_SSL_VERSION),"ssl ctx has no default ssl version"}, +{ERR_REASON(SSL_R_SSL_HANDSHAKE_FAILURE) ,"ssl handshake failure"}, +{ERR_REASON(SSL_R_SSL_LIBRARY_HAS_NO_CIPHERS),"ssl library has no ciphers"}, +{ERR_REASON(SSL_R_SSL_SESSION_ID_CALLBACK_FAILED),"ssl session id callback failed"}, +{ERR_REASON(SSL_R_SSL_SESSION_ID_CONFLICT),"ssl session id conflict"}, +{ERR_REASON(SSL_R_SSL_SESSION_ID_CONTEXT_TOO_LONG),"ssl session id context too long"}, +{ERR_REASON(SSL_R_SSL_SESSION_ID_HAS_BAD_LENGTH),"ssl session id has bad length"}, +{ERR_REASON(SSL_R_SSL_SESSION_ID_IS_DIFFERENT),"ssl session id is different"}, +{ERR_REASON(SSL_R_TLSV1_ALERT_ACCESS_DENIED),"tlsv1 alert access denied"}, +{ERR_REASON(SSL_R_TLSV1_ALERT_DECODE_ERROR),"tlsv1 alert decode error"}, +{ERR_REASON(SSL_R_TLSV1_ALERT_DECRYPTION_FAILED),"tlsv1 alert decryption failed"}, +{ERR_REASON(SSL_R_TLSV1_ALERT_DECRYPT_ERROR),"tlsv1 alert decrypt error"}, +{ERR_REASON(SSL_R_TLSV1_ALERT_EXPORT_RESTRICTION),"tlsv1 alert export restriction"}, +{ERR_REASON(SSL_R_TLSV1_ALERT_INSUFFICIENT_SECURITY),"tlsv1 alert insufficient security"}, +{ERR_REASON(SSL_R_TLSV1_ALERT_INTERNAL_ERROR),"tlsv1 alert internal error"}, +{ERR_REASON(SSL_R_TLSV1_ALERT_NO_RENEGOTIATION),"tlsv1 alert no renegotiation"}, +{ERR_REASON(SSL_R_TLSV1_ALERT_PROTOCOL_VERSION),"tlsv1 alert protocol version"}, +{ERR_REASON(SSL_R_TLSV1_ALERT_RECORD_OVERFLOW),"tlsv1 alert record overflow"}, +{ERR_REASON(SSL_R_TLSV1_ALERT_UNKNOWN_CA),"tlsv1 alert unknown ca"}, +{ERR_REASON(SSL_R_TLSV1_ALERT_USER_CANCELLED),"tlsv1 alert user cancelled"}, +{ERR_REASON(SSL_R_TLSV1_BAD_CERTIFICATE_HASH_VALUE),"tlsv1 bad certificate hash value"}, +{ERR_REASON(SSL_R_TLSV1_BAD_CERTIFICATE_STATUS_RESPONSE),"tlsv1 bad certificate status response"}, +{ERR_REASON(SSL_R_TLSV1_CERTIFICATE_UNOBTAINABLE),"tlsv1 certificate unobtainable"}, +{ERR_REASON(SSL_R_TLSV1_UNRECOGNIZED_NAME),"tlsv1 unrecognized name"}, +{ERR_REASON(SSL_R_TLSV1_UNSUPPORTED_EXTENSION),"tlsv1 unsupported extension"}, +{ERR_REASON(SSL_R_TLS_CLIENT_CERT_REQ_WITH_ANON_CIPHER),"tls client cert req with anon cipher"}, +{ERR_REASON(SSL_R_TLS_INVALID_ECPOINTFORMAT_LIST),"tls invalid ecpointformat list"}, +{ERR_REASON(SSL_R_TLS_PEER_DID_NOT_RESPOND_WITH_CERTIFICATE_LIST),"tls peer did not respond with certificate list"}, +{ERR_REASON(SSL_R_TLS_RSA_ENCRYPTED_VALUE_LENGTH_IS_WRONG),"tls rsa encrypted value length is wrong"}, +{ERR_REASON(SSL_R_TRIED_TO_USE_UNSUPPORTED_CIPHER),"tried to use unsupported cipher"}, +{ERR_REASON(SSL_R_UNABLE_TO_DECODE_DH_CERTS),"unable to decode dh certs"}, +{ERR_REASON(SSL_R_UNABLE_TO_DECODE_ECDH_CERTS),"unable to decode ecdh certs"}, +{ERR_REASON(SSL_R_UNABLE_TO_EXTRACT_PUBLIC_KEY),"unable to extract public key"}, +{ERR_REASON(SSL_R_UNABLE_TO_FIND_DH_PARAMETERS),"unable to find dh parameters"}, +{ERR_REASON(SSL_R_UNABLE_TO_FIND_ECDH_PARAMETERS),"unable to find ecdh parameters"}, +{ERR_REASON(SSL_R_UNABLE_TO_FIND_PUBLIC_KEY_PARAMETERS),"unable to find public key parameters"}, +{ERR_REASON(SSL_R_UNABLE_TO_FIND_SSL_METHOD),"unable to find ssl method"}, +{ERR_REASON(SSL_R_UNABLE_TO_LOAD_SSL2_MD5_ROUTINES),"unable to load ssl2 md5 routines"}, +{ERR_REASON(SSL_R_UNABLE_TO_LOAD_SSL3_MD5_ROUTINES),"unable to load ssl3 md5 routines"}, +{ERR_REASON(SSL_R_UNABLE_TO_LOAD_SSL3_SHA1_ROUTINES),"unable to load ssl3 sha1 routines"}, +{ERR_REASON(SSL_R_UNEXPECTED_MESSAGE) ,"unexpected message"}, +{ERR_REASON(SSL_R_UNEXPECTED_RECORD) ,"unexpected record"}, +{ERR_REASON(SSL_R_UNINITIALIZED) ,"uninitialized"}, +{ERR_REASON(SSL_R_UNKNOWN_ALERT_TYPE) ,"unknown alert type"}, +{ERR_REASON(SSL_R_UNKNOWN_CERTIFICATE_TYPE),"unknown certificate type"}, +{ERR_REASON(SSL_R_UNKNOWN_CIPHER_RETURNED),"unknown cipher returned"}, +{ERR_REASON(SSL_R_UNKNOWN_CIPHER_TYPE) ,"unknown cipher type"}, +{ERR_REASON(SSL_R_UNKNOWN_KEY_EXCHANGE_TYPE),"unknown key exchange type"}, +{ERR_REASON(SSL_R_UNKNOWN_PKEY_TYPE) ,"unknown pkey type"}, +{ERR_REASON(SSL_R_UNKNOWN_PROTOCOL) ,"unknown protocol"}, +{ERR_REASON(SSL_R_UNKNOWN_REMOTE_ERROR_TYPE),"unknown remote error type"}, +{ERR_REASON(SSL_R_UNKNOWN_SSL_VERSION) ,"unknown ssl version"}, +{ERR_REASON(SSL_R_UNKNOWN_STATE) ,"unknown state"}, +{ERR_REASON(SSL_R_UNSAFE_LEGACY_RENEGOTIATION_DISABLED),"unsafe legacy renegotiation disabled"}, +{ERR_REASON(SSL_R_UNSUPPORTED_CIPHER) ,"unsupported cipher"}, +{ERR_REASON(SSL_R_UNSUPPORTED_COMPRESSION_ALGORITHM),"unsupported compression algorithm"}, +{ERR_REASON(SSL_R_UNSUPPORTED_DIGEST_TYPE),"unsupported digest type"}, +{ERR_REASON(SSL_R_UNSUPPORTED_ELLIPTIC_CURVE),"unsupported elliptic curve"}, +{ERR_REASON(SSL_R_UNSUPPORTED_PROTOCOL) ,"unsupported protocol"}, +{ERR_REASON(SSL_R_UNSUPPORTED_SSL_VERSION),"unsupported ssl version"}, +{ERR_REASON(SSL_R_UNSUPPORTED_STATUS_TYPE),"unsupported status type"}, +{ERR_REASON(SSL_R_WRITE_BIO_NOT_SET) ,"write bio not set"}, +{ERR_REASON(SSL_R_WRONG_CIPHER_RETURNED) ,"wrong cipher returned"}, +{ERR_REASON(SSL_R_WRONG_MESSAGE_TYPE) ,"wrong message type"}, +{ERR_REASON(SSL_R_WRONG_NUMBER_OF_KEY_BITS),"wrong number of key bits"}, +{ERR_REASON(SSL_R_WRONG_SIGNATURE_LENGTH),"wrong signature length"}, +{ERR_REASON(SSL_R_WRONG_SIGNATURE_SIZE) ,"wrong signature size"}, +{ERR_REASON(SSL_R_WRONG_SSL_VERSION) ,"wrong ssl version"}, +{ERR_REASON(SSL_R_WRONG_VERSION_NUMBER) ,"wrong version number"}, +{ERR_REASON(SSL_R_X509_LIB) ,"x509 lib"}, +{ERR_REASON(SSL_R_X509_VERIFICATION_SETUP_PROBLEMS),"x509 verification setup problems"}, +{0,NULL} + }; + +#endif + +void ERR_load_SSL_strings(void) + { +#ifndef OPENSSL_NO_ERR + + if (ERR_func_error_string(SSL_str_functs[0].error) == NULL) + { + ERR_load_strings(0,SSL_str_functs); + ERR_load_strings(0,SSL_str_reasons); + } +#endif + } diff --git a/node-v0.8.14/deps/openssl/openssl/ssl/ssl_err2.c b/node-v0.8.14/deps/openssl/openssl/ssl/ssl_err2.c new file mode 100644 index 0000000..ea95a5f --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/ssl/ssl_err2.c @@ -0,0 +1,70 @@ +/* ssl/ssl_err2.c */ +/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com) + * All rights reserved. + * + * This package is an SSL implementation written + * by Eric Young (eay@cryptsoft.com). + * The implementation was written so as to conform with Netscapes SSL. + * + * This library is free for commercial and non-commercial use as long as + * the following conditions are aheared to. The following conditions + * apply to all code found in this distribution, be it the RC4, RSA, + * lhash, DES, etc., code; not just the SSL code. The SSL documentation + * included with this distribution is covered by the same copyright terms + * except that the holder is Tim Hudson (tjh@cryptsoft.com). + * + * Copyright remains Eric Young's, and as such any Copyright notices in + * the code are not to be removed. + * If this package is used in a product, Eric Young should be given attribution + * as the author of the parts of the library used. + * This can be in the form of a textual message at program startup or + * in documentation (online or textual) provided with the package. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * "This product includes cryptographic software written by + * Eric Young (eay@cryptsoft.com)" + * The word 'cryptographic' can be left out if the rouines from the library + * being used are not cryptographic related :-). + * 4. If you include any Windows specific code (or a derivative thereof) from + * the apps directory (application code) you must include an acknowledgement: + * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)" + * + * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * + * The licence and distribution terms for any publically available version or + * derivative of this code cannot be changed. i.e. this code cannot simply be + * copied and put under another distribution licence + * [including the GNU Public Licence.] + */ + +#include +#include +#include + +void SSL_load_error_strings(void) + { +#ifndef OPENSSL_NO_ERR + ERR_load_crypto_strings(); + ERR_load_SSL_strings(); +#endif + } + diff --git a/node-v0.8.14/deps/openssl/openssl/ssl/ssl_lib.c b/node-v0.8.14/deps/openssl/openssl/ssl/ssl_lib.c new file mode 100644 index 0000000..add3058 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/ssl/ssl_lib.c @@ -0,0 +1,3259 @@ +/*! \file ssl/ssl_lib.c + * \brief Version independent SSL functions. + */ +/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com) + * All rights reserved. + * + * This package is an SSL implementation written + * by Eric Young (eay@cryptsoft.com). + * The implementation was written so as to conform with Netscapes SSL. + * + * This library is free for commercial and non-commercial use as long as + * the following conditions are aheared to. The following conditions + * apply to all code found in this distribution, be it the RC4, RSA, + * lhash, DES, etc., code; not just the SSL code. The SSL documentation + * included with this distribution is covered by the same copyright terms + * except that the holder is Tim Hudson (tjh@cryptsoft.com). + * + * Copyright remains Eric Young's, and as such any Copyright notices in + * the code are not to be removed. + * If this package is used in a product, Eric Young should be given attribution + * as the author of the parts of the library used. + * This can be in the form of a textual message at program startup or + * in documentation (online or textual) provided with the package. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * "This product includes cryptographic software written by + * Eric Young (eay@cryptsoft.com)" + * The word 'cryptographic' can be left out if the rouines from the library + * being used are not cryptographic related :-). + * 4. If you include any Windows specific code (or a derivative thereof) from + * the apps directory (application code) you must include an acknowledgement: + * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)" + * + * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * + * The licence and distribution terms for any publically available version or + * derivative of this code cannot be changed. i.e. this code cannot simply be + * copied and put under another distribution licence + * [including the GNU Public Licence.] + */ +/* ==================================================================== + * Copyright (c) 1998-2007 The OpenSSL Project. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. All advertising materials mentioning features or use of this + * software must display the following acknowledgment: + * "This product includes software developed by the OpenSSL Project + * for use in the OpenSSL Toolkit. (http://www.openssl.org/)" + * + * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to + * endorse or promote products derived from this software without + * prior written permission. For written permission, please contact + * openssl-core@openssl.org. + * + * 5. Products derived from this software may not be called "OpenSSL" + * nor may "OpenSSL" appear in their names without prior written + * permission of the OpenSSL Project. + * + * 6. Redistributions of any form whatsoever must retain the following + * acknowledgment: + * "This product includes software developed by the OpenSSL Project + * for use in the OpenSSL Toolkit (http://www.openssl.org/)" + * + * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY + * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR + * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, + * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * ==================================================================== + * + * This product includes cryptographic software written by Eric Young + * (eay@cryptsoft.com). This product includes software written by Tim + * Hudson (tjh@cryptsoft.com). + * + */ +/* ==================================================================== + * Copyright 2002 Sun Microsystems, Inc. ALL RIGHTS RESERVED. + * ECC cipher suite support in OpenSSL originally developed by + * SUN MICROSYSTEMS, INC., and contributed to the OpenSSL project. + */ +/* ==================================================================== + * Copyright 2005 Nokia. All rights reserved. + * + * The portions of the attached software ("Contribution") is developed by + * Nokia Corporation and is licensed pursuant to the OpenSSL open source + * license. + * + * The Contribution, originally written by Mika Kousa and Pasi Eronen of + * Nokia Corporation, consists of the "PSK" (Pre-Shared Key) ciphersuites + * support (see RFC 4279) to OpenSSL. + * + * No patent licenses or other rights except those expressly stated in + * the OpenSSL open source license shall be deemed granted or received + * expressly, by implication, estoppel, or otherwise. + * + * No assurances are provided by Nokia that the Contribution does not + * infringe the patent or other intellectual property rights of any third + * party or that the license provides you with all the necessary rights + * to make use of the Contribution. + * + * THE SOFTWARE IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND. IN + * ADDITION TO THE DISCLAIMERS INCLUDED IN THE LICENSE, NOKIA + * SPECIFICALLY DISCLAIMS ANY LIABILITY FOR CLAIMS BROUGHT BY YOU OR ANY + * OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL PROPERTY RIGHTS OR + * OTHERWISE. + */ + +#ifdef REF_CHECK +# include +#endif +#include +#include "ssl_locl.h" +#include "kssl_lcl.h" +#include +#include +#include +#include +#include +#ifndef OPENSSL_NO_DH +#include +#endif +#ifndef OPENSSL_NO_ENGINE +#include +#endif + +const char *SSL_version_str=OPENSSL_VERSION_TEXT; + +SSL3_ENC_METHOD ssl3_undef_enc_method={ + /* evil casts, but these functions are only called if there's a library bug */ + (int (*)(SSL *,int))ssl_undefined_function, + (int (*)(SSL *, unsigned char *, int))ssl_undefined_function, + ssl_undefined_function, + (int (*)(SSL *, unsigned char *, unsigned char *, int))ssl_undefined_function, + (int (*)(SSL*, int))ssl_undefined_function, + (int (*)(SSL *, const char*, int, unsigned char *))ssl_undefined_function, + 0, /* finish_mac_length */ + (int (*)(SSL *, int, unsigned char *))ssl_undefined_function, + NULL, /* client_finished_label */ + 0, /* client_finished_label_len */ + NULL, /* server_finished_label */ + 0, /* server_finished_label_len */ + (int (*)(int))ssl_undefined_function + }; + +int SSL_clear(SSL *s) + { + + if (s->method == NULL) + { + SSLerr(SSL_F_SSL_CLEAR,SSL_R_NO_METHOD_SPECIFIED); + return(0); + } + + if (ssl_clear_bad_session(s)) + { + SSL_SESSION_free(s->session); + s->session=NULL; + } + + s->error=0; + s->hit=0; + s->shutdown=0; + +#if 0 /* Disabled since version 1.10 of this file (early return not + * needed because SSL_clear is not called when doing renegotiation) */ + /* This is set if we are doing dynamic renegotiation so keep + * the old cipher. It is sort of a SSL_clear_lite :-) */ + if (s->new_session) return(1); +#else + if (s->new_session) + { + SSLerr(SSL_F_SSL_CLEAR,ERR_R_INTERNAL_ERROR); + return 0; + } +#endif + + s->type=0; + + s->state=SSL_ST_BEFORE|((s->server)?SSL_ST_ACCEPT:SSL_ST_CONNECT); + + s->version=s->method->version; + s->client_version=s->version; + s->rwstate=SSL_NOTHING; + s->rstate=SSL_ST_READ_HEADER; +#if 0 + s->read_ahead=s->ctx->read_ahead; +#endif + + if (s->init_buf != NULL) + { + BUF_MEM_free(s->init_buf); + s->init_buf=NULL; + } + + ssl_clear_cipher_ctx(s); + ssl_clear_hash_ctx(&s->read_hash); + ssl_clear_hash_ctx(&s->write_hash); + + s->first_packet=0; + +#if 1 + /* Check to see if we were changed into a different method, if + * so, revert back if we are not doing session-id reuse. */ + if (!s->in_handshake && (s->session == NULL) && (s->method != s->ctx->method)) + { + s->method->ssl_free(s); + s->method=s->ctx->method; + if (!s->method->ssl_new(s)) + return(0); + } + else +#endif + s->method->ssl_clear(s); + return(1); + } + +/** Used to change an SSL_CTXs default SSL method type */ +int SSL_CTX_set_ssl_version(SSL_CTX *ctx,const SSL_METHOD *meth) + { + STACK_OF(SSL_CIPHER) *sk; + + ctx->method=meth; + + sk=ssl_create_cipher_list(ctx->method,&(ctx->cipher_list), + &(ctx->cipher_list_by_id), + meth->version == SSL2_VERSION ? "SSLv2" : SSL_DEFAULT_CIPHER_LIST); + if ((sk == NULL) || (sk_SSL_CIPHER_num(sk) <= 0)) + { + SSLerr(SSL_F_SSL_CTX_SET_SSL_VERSION,SSL_R_SSL_LIBRARY_HAS_NO_CIPHERS); + return(0); + } + return(1); + } + +SSL *SSL_new(SSL_CTX *ctx) + { + SSL *s; + + if (ctx == NULL) + { + SSLerr(SSL_F_SSL_NEW,SSL_R_NULL_SSL_CTX); + return(NULL); + } + if (ctx->method == NULL) + { + SSLerr(SSL_F_SSL_NEW,SSL_R_SSL_CTX_HAS_NO_DEFAULT_SSL_VERSION); + return(NULL); + } + + s=(SSL *)OPENSSL_malloc(sizeof(SSL)); + if (s == NULL) goto err; + memset(s,0,sizeof(SSL)); + +#ifndef OPENSSL_NO_KRB5 + s->kssl_ctx = kssl_ctx_new(); +#endif /* OPENSSL_NO_KRB5 */ + + s->options=ctx->options; + s->mode=ctx->mode; + s->max_cert_list=ctx->max_cert_list; + + if (ctx->cert != NULL) + { + /* Earlier library versions used to copy the pointer to + * the CERT, not its contents; only when setting new + * parameters for the per-SSL copy, ssl_cert_new would be + * called (and the direct reference to the per-SSL_CTX + * settings would be lost, but those still were indirectly + * accessed for various purposes, and for that reason they + * used to be known as s->ctx->default_cert). + * Now we don't look at the SSL_CTX's CERT after having + * duplicated it once. */ + + s->cert = ssl_cert_dup(ctx->cert); + if (s->cert == NULL) + goto err; + } + else + s->cert=NULL; /* Cannot really happen (see SSL_CTX_new) */ + + s->read_ahead=ctx->read_ahead; + s->msg_callback=ctx->msg_callback; + s->msg_callback_arg=ctx->msg_callback_arg; + s->verify_mode=ctx->verify_mode; +#if 0 + s->verify_depth=ctx->verify_depth; +#endif + s->sid_ctx_length=ctx->sid_ctx_length; + OPENSSL_assert(s->sid_ctx_length <= sizeof s->sid_ctx); + memcpy(&s->sid_ctx,&ctx->sid_ctx,sizeof(s->sid_ctx)); + s->verify_callback=ctx->default_verify_callback; + s->session_creation_enabled=1; + s->generate_session_id=ctx->generate_session_id; + + s->param = X509_VERIFY_PARAM_new(); + if (!s->param) + goto err; + X509_VERIFY_PARAM_inherit(s->param, ctx->param); +#if 0 + s->purpose = ctx->purpose; + s->trust = ctx->trust; +#endif + s->quiet_shutdown=ctx->quiet_shutdown; + s->max_send_fragment = ctx->max_send_fragment; + + CRYPTO_add(&ctx->references,1,CRYPTO_LOCK_SSL_CTX); + s->ctx=ctx; +#ifndef OPENSSL_NO_TLSEXT + s->tlsext_debug_cb = 0; + s->tlsext_debug_arg = NULL; + s->tlsext_ticket_expected = 0; + s->tlsext_status_type = -1; + s->tlsext_status_expected = 0; + s->tlsext_ocsp_ids = NULL; + s->tlsext_ocsp_exts = NULL; + s->tlsext_ocsp_resp = NULL; + s->tlsext_ocsp_resplen = -1; + CRYPTO_add(&ctx->references,1,CRYPTO_LOCK_SSL_CTX); + s->initial_ctx=ctx; +# ifndef OPENSSL_NO_NEXTPROTONEG + s->next_proto_negotiated = NULL; +# endif +#endif + + s->verify_result=X509_V_OK; + + s->method=ctx->method; + + if (!s->method->ssl_new(s)) + goto err; + + s->references=1; + s->server=(ctx->method->ssl_accept == ssl_undefined_function)?0:1; + + SSL_clear(s); + + CRYPTO_new_ex_data(CRYPTO_EX_INDEX_SSL, s, &s->ex_data); + +#ifndef OPENSSL_NO_PSK + s->psk_client_callback=ctx->psk_client_callback; + s->psk_server_callback=ctx->psk_server_callback; +#endif + + return(s); +err: + if (s != NULL) + { + if (s->cert != NULL) + ssl_cert_free(s->cert); + if (s->ctx != NULL) + SSL_CTX_free(s->ctx); /* decrement reference count */ + OPENSSL_free(s); + } + SSLerr(SSL_F_SSL_NEW,ERR_R_MALLOC_FAILURE); + return(NULL); + } + +int SSL_CTX_set_session_id_context(SSL_CTX *ctx,const unsigned char *sid_ctx, + unsigned int sid_ctx_len) + { + if(sid_ctx_len > sizeof ctx->sid_ctx) + { + SSLerr(SSL_F_SSL_CTX_SET_SESSION_ID_CONTEXT,SSL_R_SSL_SESSION_ID_CONTEXT_TOO_LONG); + return 0; + } + ctx->sid_ctx_length=sid_ctx_len; + memcpy(ctx->sid_ctx,sid_ctx,sid_ctx_len); + + return 1; + } + +int SSL_set_session_id_context(SSL *ssl,const unsigned char *sid_ctx, + unsigned int sid_ctx_len) + { + if(sid_ctx_len > SSL_MAX_SID_CTX_LENGTH) + { + SSLerr(SSL_F_SSL_SET_SESSION_ID_CONTEXT,SSL_R_SSL_SESSION_ID_CONTEXT_TOO_LONG); + return 0; + } + ssl->sid_ctx_length=sid_ctx_len; + memcpy(ssl->sid_ctx,sid_ctx,sid_ctx_len); + + return 1; + } + +int SSL_CTX_set_generate_session_id(SSL_CTX *ctx, GEN_SESSION_CB cb) + { + CRYPTO_w_lock(CRYPTO_LOCK_SSL_CTX); + ctx->generate_session_id = cb; + CRYPTO_w_unlock(CRYPTO_LOCK_SSL_CTX); + return 1; + } + +int SSL_set_generate_session_id(SSL *ssl, GEN_SESSION_CB cb) + { + CRYPTO_w_lock(CRYPTO_LOCK_SSL); + ssl->generate_session_id = cb; + CRYPTO_w_unlock(CRYPTO_LOCK_SSL); + return 1; + } + +int SSL_has_matching_session_id(const SSL *ssl, const unsigned char *id, + unsigned int id_len) + { + /* A quick examination of SSL_SESSION_hash and SSL_SESSION_cmp shows how + * we can "construct" a session to give us the desired check - ie. to + * find if there's a session in the hash table that would conflict with + * any new session built out of this id/id_len and the ssl_version in + * use by this SSL. */ + SSL_SESSION r, *p; + + if(id_len > sizeof r.session_id) + return 0; + + r.ssl_version = ssl->version; + r.session_id_length = id_len; + memcpy(r.session_id, id, id_len); + /* NB: SSLv2 always uses a fixed 16-byte session ID, so even if a + * callback is calling us to check the uniqueness of a shorter ID, it + * must be compared as a padded-out ID because that is what it will be + * converted to when the callback has finished choosing it. */ + if((r.ssl_version == SSL2_VERSION) && + (id_len < SSL2_SSL_SESSION_ID_LENGTH)) + { + memset(r.session_id + id_len, 0, + SSL2_SSL_SESSION_ID_LENGTH - id_len); + r.session_id_length = SSL2_SSL_SESSION_ID_LENGTH; + } + + CRYPTO_r_lock(CRYPTO_LOCK_SSL_CTX); + p = lh_SSL_SESSION_retrieve(ssl->ctx->sessions, &r); + CRYPTO_r_unlock(CRYPTO_LOCK_SSL_CTX); + return (p != NULL); + } + +int SSL_CTX_set_purpose(SSL_CTX *s, int purpose) + { + return X509_VERIFY_PARAM_set_purpose(s->param, purpose); + } + +int SSL_set_purpose(SSL *s, int purpose) + { + return X509_VERIFY_PARAM_set_purpose(s->param, purpose); + } + +int SSL_CTX_set_trust(SSL_CTX *s, int trust) + { + return X509_VERIFY_PARAM_set_trust(s->param, trust); + } + +int SSL_set_trust(SSL *s, int trust) + { + return X509_VERIFY_PARAM_set_trust(s->param, trust); + } + +int SSL_CTX_set1_param(SSL_CTX *ctx, X509_VERIFY_PARAM *vpm) + { + return X509_VERIFY_PARAM_set1(ctx->param, vpm); + } + +int SSL_set1_param(SSL *ssl, X509_VERIFY_PARAM *vpm) + { + return X509_VERIFY_PARAM_set1(ssl->param, vpm); + } + +void SSL_free(SSL *s) + { + int i; + + if(s == NULL) + return; + + i=CRYPTO_add(&s->references,-1,CRYPTO_LOCK_SSL); +#ifdef REF_PRINT + REF_PRINT("SSL",s); +#endif + if (i > 0) return; +#ifdef REF_CHECK + if (i < 0) + { + fprintf(stderr,"SSL_free, bad reference count\n"); + abort(); /* ok */ + } +#endif + + if (s->param) + X509_VERIFY_PARAM_free(s->param); + + CRYPTO_free_ex_data(CRYPTO_EX_INDEX_SSL, s, &s->ex_data); + + if (s->bbio != NULL) + { + /* If the buffering BIO is in place, pop it off */ + if (s->bbio == s->wbio) + { + s->wbio=BIO_pop(s->wbio); + } + BIO_free(s->bbio); + s->bbio=NULL; + } + if (s->rbio != NULL) + BIO_free_all(s->rbio); + if ((s->wbio != NULL) && (s->wbio != s->rbio)) + BIO_free_all(s->wbio); + + if (s->init_buf != NULL) BUF_MEM_free(s->init_buf); + + /* add extra stuff */ + if (s->cipher_list != NULL) sk_SSL_CIPHER_free(s->cipher_list); + if (s->cipher_list_by_id != NULL) sk_SSL_CIPHER_free(s->cipher_list_by_id); + + /* Make the next call work :-) */ + if (s->session != NULL) + { + ssl_clear_bad_session(s); + SSL_SESSION_free(s->session); + } + + ssl_clear_cipher_ctx(s); + ssl_clear_hash_ctx(&s->read_hash); + ssl_clear_hash_ctx(&s->write_hash); + + if (s->cert != NULL) ssl_cert_free(s->cert); + /* Free up if allocated */ + +#ifndef OPENSSL_NO_TLSEXT + if (s->tlsext_hostname) + OPENSSL_free(s->tlsext_hostname); + if (s->initial_ctx) SSL_CTX_free(s->initial_ctx); +#ifndef OPENSSL_NO_EC + if (s->tlsext_ecpointformatlist) OPENSSL_free(s->tlsext_ecpointformatlist); + if (s->tlsext_ellipticcurvelist) OPENSSL_free(s->tlsext_ellipticcurvelist); +#endif /* OPENSSL_NO_EC */ + if (s->tlsext_opaque_prf_input) OPENSSL_free(s->tlsext_opaque_prf_input); + if (s->tlsext_ocsp_exts) + sk_X509_EXTENSION_pop_free(s->tlsext_ocsp_exts, + X509_EXTENSION_free); + if (s->tlsext_ocsp_ids) + sk_OCSP_RESPID_pop_free(s->tlsext_ocsp_ids, OCSP_RESPID_free); + if (s->tlsext_ocsp_resp) + OPENSSL_free(s->tlsext_ocsp_resp); +#endif + + if (s->client_CA != NULL) + sk_X509_NAME_pop_free(s->client_CA,X509_NAME_free); + + if (s->method != NULL) s->method->ssl_free(s); + + if (s->ctx) SSL_CTX_free(s->ctx); + +#ifndef OPENSSL_NO_KRB5 + if (s->kssl_ctx != NULL) + kssl_ctx_free(s->kssl_ctx); +#endif /* OPENSSL_NO_KRB5 */ + +#if !defined(OPENSSL_NO_TLSEXT) && !defined(OPENSSL_NO_NEXTPROTONEG) + if (s->next_proto_negotiated) + OPENSSL_free(s->next_proto_negotiated); +#endif + + OPENSSL_free(s); + } + +void SSL_set_bio(SSL *s,BIO *rbio,BIO *wbio) + { + /* If the output buffering BIO is still in place, remove it + */ + if (s->bbio != NULL) + { + if (s->wbio == s->bbio) + { + s->wbio=s->wbio->next_bio; + s->bbio->next_bio=NULL; + } + } + if ((s->rbio != NULL) && (s->rbio != rbio)) + BIO_free_all(s->rbio); + if ((s->wbio != NULL) && (s->wbio != wbio) && (s->rbio != s->wbio)) + BIO_free_all(s->wbio); + s->rbio=rbio; + s->wbio=wbio; + } + +BIO *SSL_get_rbio(const SSL *s) + { return(s->rbio); } + +BIO *SSL_get_wbio(const SSL *s) + { return(s->wbio); } + +int SSL_get_fd(const SSL *s) + { + return(SSL_get_rfd(s)); + } + +int SSL_get_rfd(const SSL *s) + { + int ret= -1; + BIO *b,*r; + + b=SSL_get_rbio(s); + r=BIO_find_type(b,BIO_TYPE_DESCRIPTOR); + if (r != NULL) + BIO_get_fd(r,&ret); + return(ret); + } + +int SSL_get_wfd(const SSL *s) + { + int ret= -1; + BIO *b,*r; + + b=SSL_get_wbio(s); + r=BIO_find_type(b,BIO_TYPE_DESCRIPTOR); + if (r != NULL) + BIO_get_fd(r,&ret); + return(ret); + } + +#ifndef OPENSSL_NO_SOCK +int SSL_set_fd(SSL *s,int fd) + { + int ret=0; + BIO *bio=NULL; + + bio=BIO_new(BIO_s_socket()); + + if (bio == NULL) + { + SSLerr(SSL_F_SSL_SET_FD,ERR_R_BUF_LIB); + goto err; + } + BIO_set_fd(bio,fd,BIO_NOCLOSE); + SSL_set_bio(s,bio,bio); + ret=1; +err: + return(ret); + } + +int SSL_set_wfd(SSL *s,int fd) + { + int ret=0; + BIO *bio=NULL; + + if ((s->rbio == NULL) || (BIO_method_type(s->rbio) != BIO_TYPE_SOCKET) + || ((int)BIO_get_fd(s->rbio,NULL) != fd)) + { + bio=BIO_new(BIO_s_socket()); + + if (bio == NULL) + { SSLerr(SSL_F_SSL_SET_WFD,ERR_R_BUF_LIB); goto err; } + BIO_set_fd(bio,fd,BIO_NOCLOSE); + SSL_set_bio(s,SSL_get_rbio(s),bio); + } + else + SSL_set_bio(s,SSL_get_rbio(s),SSL_get_rbio(s)); + ret=1; +err: + return(ret); + } + +int SSL_set_rfd(SSL *s,int fd) + { + int ret=0; + BIO *bio=NULL; + + if ((s->wbio == NULL) || (BIO_method_type(s->wbio) != BIO_TYPE_SOCKET) + || ((int)BIO_get_fd(s->wbio,NULL) != fd)) + { + bio=BIO_new(BIO_s_socket()); + + if (bio == NULL) + { + SSLerr(SSL_F_SSL_SET_RFD,ERR_R_BUF_LIB); + goto err; + } + BIO_set_fd(bio,fd,BIO_NOCLOSE); + SSL_set_bio(s,bio,SSL_get_wbio(s)); + } + else + SSL_set_bio(s,SSL_get_wbio(s),SSL_get_wbio(s)); + ret=1; +err: + return(ret); + } +#endif + + +/* return length of latest Finished message we sent, copy to 'buf' */ +size_t SSL_get_finished(const SSL *s, void *buf, size_t count) + { + size_t ret = 0; + + if (s->s3 != NULL) + { + ret = s->s3->tmp.finish_md_len; + if (count > ret) + count = ret; + memcpy(buf, s->s3->tmp.finish_md, count); + } + return ret; + } + +/* return length of latest Finished message we expected, copy to 'buf' */ +size_t SSL_get_peer_finished(const SSL *s, void *buf, size_t count) + { + size_t ret = 0; + + if (s->s3 != NULL) + { + ret = s->s3->tmp.peer_finish_md_len; + if (count > ret) + count = ret; + memcpy(buf, s->s3->tmp.peer_finish_md, count); + } + return ret; + } + + +int SSL_get_verify_mode(const SSL *s) + { + return(s->verify_mode); + } + +int SSL_get_verify_depth(const SSL *s) + { + return X509_VERIFY_PARAM_get_depth(s->param); + } + +int (*SSL_get_verify_callback(const SSL *s))(int,X509_STORE_CTX *) + { + return(s->verify_callback); + } + +int SSL_CTX_get_verify_mode(const SSL_CTX *ctx) + { + return(ctx->verify_mode); + } + +int SSL_CTX_get_verify_depth(const SSL_CTX *ctx) + { + return X509_VERIFY_PARAM_get_depth(ctx->param); + } + +int (*SSL_CTX_get_verify_callback(const SSL_CTX *ctx))(int,X509_STORE_CTX *) + { + return(ctx->default_verify_callback); + } + +void SSL_set_verify(SSL *s,int mode, + int (*callback)(int ok,X509_STORE_CTX *ctx)) + { + s->verify_mode=mode; + if (callback != NULL) + s->verify_callback=callback; + } + +void SSL_set_verify_depth(SSL *s,int depth) + { + X509_VERIFY_PARAM_set_depth(s->param, depth); + } + +void SSL_set_read_ahead(SSL *s,int yes) + { + s->read_ahead=yes; + } + +int SSL_get_read_ahead(const SSL *s) + { + return(s->read_ahead); + } + +int SSL_pending(const SSL *s) + { + /* SSL_pending cannot work properly if read-ahead is enabled + * (SSL_[CTX_]ctrl(..., SSL_CTRL_SET_READ_AHEAD, 1, NULL)), + * and it is impossible to fix since SSL_pending cannot report + * errors that may be observed while scanning the new data. + * (Note that SSL_pending() is often used as a boolean value, + * so we'd better not return -1.) + */ + return(s->method->ssl_pending(s)); + } + +X509 *SSL_get_peer_certificate(const SSL *s) + { + X509 *r; + + if ((s == NULL) || (s->session == NULL)) + r=NULL; + else + r=s->session->peer; + + if (r == NULL) return(r); + + CRYPTO_add(&r->references,1,CRYPTO_LOCK_X509); + + return(r); + } + +STACK_OF(X509) *SSL_get_peer_cert_chain(const SSL *s) + { + STACK_OF(X509) *r; + + if ((s == NULL) || (s->session == NULL) || (s->session->sess_cert == NULL)) + r=NULL; + else + r=s->session->sess_cert->cert_chain; + + /* If we are a client, cert_chain includes the peer's own + * certificate; if we are a server, it does not. */ + + return(r); + } + +/* Now in theory, since the calling process own 't' it should be safe to + * modify. We need to be able to read f without being hassled */ +void SSL_copy_session_id(SSL *t,const SSL *f) + { + CERT *tmp; + + /* Do we need to to SSL locking? */ + SSL_set_session(t,SSL_get_session(f)); + + /* what if we are setup as SSLv2 but want to talk SSLv3 or + * vice-versa */ + if (t->method != f->method) + { + t->method->ssl_free(t); /* cleanup current */ + t->method=f->method; /* change method */ + t->method->ssl_new(t); /* setup new */ + } + + tmp=t->cert; + if (f->cert != NULL) + { + CRYPTO_add(&f->cert->references,1,CRYPTO_LOCK_SSL_CERT); + t->cert=f->cert; + } + else + t->cert=NULL; + if (tmp != NULL) ssl_cert_free(tmp); + SSL_set_session_id_context(t,f->sid_ctx,f->sid_ctx_length); + } + +/* Fix this so it checks all the valid key/cert options */ +int SSL_CTX_check_private_key(const SSL_CTX *ctx) + { + if ( (ctx == NULL) || + (ctx->cert == NULL) || + (ctx->cert->key->x509 == NULL)) + { + SSLerr(SSL_F_SSL_CTX_CHECK_PRIVATE_KEY,SSL_R_NO_CERTIFICATE_ASSIGNED); + return(0); + } + if (ctx->cert->key->privatekey == NULL) + { + SSLerr(SSL_F_SSL_CTX_CHECK_PRIVATE_KEY,SSL_R_NO_PRIVATE_KEY_ASSIGNED); + return(0); + } + return(X509_check_private_key(ctx->cert->key->x509, ctx->cert->key->privatekey)); + } + +/* Fix this function so that it takes an optional type parameter */ +int SSL_check_private_key(const SSL *ssl) + { + if (ssl == NULL) + { + SSLerr(SSL_F_SSL_CHECK_PRIVATE_KEY,ERR_R_PASSED_NULL_PARAMETER); + return(0); + } + if (ssl->cert == NULL) + { + SSLerr(SSL_F_SSL_CHECK_PRIVATE_KEY,SSL_R_NO_CERTIFICATE_ASSIGNED); + return 0; + } + if (ssl->cert->key->x509 == NULL) + { + SSLerr(SSL_F_SSL_CHECK_PRIVATE_KEY,SSL_R_NO_CERTIFICATE_ASSIGNED); + return(0); + } + if (ssl->cert->key->privatekey == NULL) + { + SSLerr(SSL_F_SSL_CHECK_PRIVATE_KEY,SSL_R_NO_PRIVATE_KEY_ASSIGNED); + return(0); + } + return(X509_check_private_key(ssl->cert->key->x509, + ssl->cert->key->privatekey)); + } + +int SSL_accept(SSL *s) + { + if (s->handshake_func == 0) + /* Not properly initialized yet */ + SSL_set_accept_state(s); + + return(s->method->ssl_accept(s)); + } + +int SSL_connect(SSL *s) + { + if (s->handshake_func == 0) + /* Not properly initialized yet */ + SSL_set_connect_state(s); + + return(s->method->ssl_connect(s)); + } + +long SSL_get_default_timeout(const SSL *s) + { + return(s->method->get_timeout()); + } + +int SSL_read(SSL *s,void *buf,int num) + { + if (s->handshake_func == 0) + { + SSLerr(SSL_F_SSL_READ, SSL_R_UNINITIALIZED); + return -1; + } + + if (s->shutdown & SSL_RECEIVED_SHUTDOWN) + { + s->rwstate=SSL_NOTHING; + return(0); + } + return(s->method->ssl_read(s,buf,num)); + } + +int SSL_peek(SSL *s,void *buf,int num) + { + if (s->handshake_func == 0) + { + SSLerr(SSL_F_SSL_PEEK, SSL_R_UNINITIALIZED); + return -1; + } + + if (s->shutdown & SSL_RECEIVED_SHUTDOWN) + { + return(0); + } + return(s->method->ssl_peek(s,buf,num)); + } + +int SSL_write(SSL *s,const void *buf,int num) + { + if (s->handshake_func == 0) + { + SSLerr(SSL_F_SSL_WRITE, SSL_R_UNINITIALIZED); + return -1; + } + + if (s->shutdown & SSL_SENT_SHUTDOWN) + { + s->rwstate=SSL_NOTHING; + SSLerr(SSL_F_SSL_WRITE,SSL_R_PROTOCOL_IS_SHUTDOWN); + return(-1); + } + return(s->method->ssl_write(s,buf,num)); + } + +int SSL_shutdown(SSL *s) + { + /* Note that this function behaves differently from what one might + * expect. Return values are 0 for no success (yet), + * 1 for success; but calling it once is usually not enough, + * even if blocking I/O is used (see ssl3_shutdown). + */ + + if (s->handshake_func == 0) + { + SSLerr(SSL_F_SSL_SHUTDOWN, SSL_R_UNINITIALIZED); + return -1; + } + + if ((s != NULL) && !SSL_in_init(s)) + return(s->method->ssl_shutdown(s)); + else + return(1); + } + +int SSL_renegotiate(SSL *s) + { + if (s->new_session == 0) + { + s->new_session=1; + } + return(s->method->ssl_renegotiate(s)); + } + +int SSL_renegotiate_pending(SSL *s) + { + /* becomes true when negotiation is requested; + * false again once a handshake has finished */ + return (s->new_session != 0); + } + +long SSL_ctrl(SSL *s,int cmd,long larg,void *parg) + { + long l; + + switch (cmd) + { + case SSL_CTRL_GET_READ_AHEAD: + return(s->read_ahead); + case SSL_CTRL_SET_READ_AHEAD: + l=s->read_ahead; + s->read_ahead=larg; + return(l); + + case SSL_CTRL_SET_MSG_CALLBACK_ARG: + s->msg_callback_arg = parg; + return 1; + + case SSL_CTRL_OPTIONS: + return(s->options|=larg); + case SSL_CTRL_CLEAR_OPTIONS: + return(s->options&=~larg); + case SSL_CTRL_MODE: + return(s->mode|=larg); + case SSL_CTRL_CLEAR_MODE: + return(s->mode &=~larg); + case SSL_CTRL_GET_MAX_CERT_LIST: + return(s->max_cert_list); + case SSL_CTRL_SET_MAX_CERT_LIST: + l=s->max_cert_list; + s->max_cert_list=larg; + return(l); + case SSL_CTRL_SET_MTU: +#ifndef OPENSSL_NO_DTLS1 + if (larg < (long)dtls1_min_mtu()) + return 0; +#endif + + if (SSL_version(s) == DTLS1_VERSION || + SSL_version(s) == DTLS1_BAD_VER) + { + s->d1->mtu = larg; + return larg; + } + return 0; + case SSL_CTRL_SET_MAX_SEND_FRAGMENT: + if (larg < 512 || larg > SSL3_RT_MAX_PLAIN_LENGTH) + return 0; + s->max_send_fragment = larg; + return 1; + case SSL_CTRL_GET_RI_SUPPORT: + if (s->s3) + return s->s3->send_connection_binding; + else return 0; + default: + return(s->method->ssl_ctrl(s,cmd,larg,parg)); + } + } + +long SSL_callback_ctrl(SSL *s, int cmd, void (*fp)(void)) + { + switch(cmd) + { + case SSL_CTRL_SET_MSG_CALLBACK: + s->msg_callback = (void (*)(int write_p, int version, int content_type, const void *buf, size_t len, SSL *ssl, void *arg))(fp); + return 1; + + default: + return(s->method->ssl_callback_ctrl(s,cmd,fp)); + } + } + +LHASH_OF(SSL_SESSION) *SSL_CTX_sessions(SSL_CTX *ctx) + { + return ctx->sessions; + } + +long SSL_CTX_ctrl(SSL_CTX *ctx,int cmd,long larg,void *parg) + { + long l; + + switch (cmd) + { + case SSL_CTRL_GET_READ_AHEAD: + return(ctx->read_ahead); + case SSL_CTRL_SET_READ_AHEAD: + l=ctx->read_ahead; + ctx->read_ahead=larg; + return(l); + + case SSL_CTRL_SET_MSG_CALLBACK_ARG: + ctx->msg_callback_arg = parg; + return 1; + + case SSL_CTRL_GET_MAX_CERT_LIST: + return(ctx->max_cert_list); + case SSL_CTRL_SET_MAX_CERT_LIST: + l=ctx->max_cert_list; + ctx->max_cert_list=larg; + return(l); + + case SSL_CTRL_SET_SESS_CACHE_SIZE: + l=ctx->session_cache_size; + ctx->session_cache_size=larg; + return(l); + case SSL_CTRL_GET_SESS_CACHE_SIZE: + return(ctx->session_cache_size); + case SSL_CTRL_SET_SESS_CACHE_MODE: + l=ctx->session_cache_mode; + ctx->session_cache_mode=larg; + return(l); + case SSL_CTRL_GET_SESS_CACHE_MODE: + return(ctx->session_cache_mode); + + case SSL_CTRL_SESS_NUMBER: + return(lh_SSL_SESSION_num_items(ctx->sessions)); + case SSL_CTRL_SESS_CONNECT: + return(ctx->stats.sess_connect); + case SSL_CTRL_SESS_CONNECT_GOOD: + return(ctx->stats.sess_connect_good); + case SSL_CTRL_SESS_CONNECT_RENEGOTIATE: + return(ctx->stats.sess_connect_renegotiate); + case SSL_CTRL_SESS_ACCEPT: + return(ctx->stats.sess_accept); + case SSL_CTRL_SESS_ACCEPT_GOOD: + return(ctx->stats.sess_accept_good); + case SSL_CTRL_SESS_ACCEPT_RENEGOTIATE: + return(ctx->stats.sess_accept_renegotiate); + case SSL_CTRL_SESS_HIT: + return(ctx->stats.sess_hit); + case SSL_CTRL_SESS_CB_HIT: + return(ctx->stats.sess_cb_hit); + case SSL_CTRL_SESS_MISSES: + return(ctx->stats.sess_miss); + case SSL_CTRL_SESS_TIMEOUTS: + return(ctx->stats.sess_timeout); + case SSL_CTRL_SESS_CACHE_FULL: + return(ctx->stats.sess_cache_full); + case SSL_CTRL_OPTIONS: + return(ctx->options|=larg); + case SSL_CTRL_CLEAR_OPTIONS: + return(ctx->options&=~larg); + case SSL_CTRL_MODE: + return(ctx->mode|=larg); + case SSL_CTRL_CLEAR_MODE: + return(ctx->mode&=~larg); + case SSL_CTRL_SET_MAX_SEND_FRAGMENT: + if (larg < 512 || larg > SSL3_RT_MAX_PLAIN_LENGTH) + return 0; + ctx->max_send_fragment = larg; + return 1; + default: + return(ctx->method->ssl_ctx_ctrl(ctx,cmd,larg,parg)); + } + } + +long SSL_CTX_callback_ctrl(SSL_CTX *ctx, int cmd, void (*fp)(void)) + { + switch(cmd) + { + case SSL_CTRL_SET_MSG_CALLBACK: + ctx->msg_callback = (void (*)(int write_p, int version, int content_type, const void *buf, size_t len, SSL *ssl, void *arg))(fp); + return 1; + + default: + return(ctx->method->ssl_ctx_callback_ctrl(ctx,cmd,fp)); + } + } + +int ssl_cipher_id_cmp(const SSL_CIPHER *a, const SSL_CIPHER *b) + { + long l; + + l=a->id-b->id; + if (l == 0L) + return(0); + else + return((l > 0)?1:-1); + } + +int ssl_cipher_ptr_id_cmp(const SSL_CIPHER * const *ap, + const SSL_CIPHER * const *bp) + { + long l; + + l=(*ap)->id-(*bp)->id; + if (l == 0L) + return(0); + else + return((l > 0)?1:-1); + } + +/** return a STACK of the ciphers available for the SSL and in order of + * preference */ +STACK_OF(SSL_CIPHER) *SSL_get_ciphers(const SSL *s) + { + if (s != NULL) + { + if (s->cipher_list != NULL) + { + return(s->cipher_list); + } + else if ((s->ctx != NULL) && + (s->ctx->cipher_list != NULL)) + { + return(s->ctx->cipher_list); + } + } + return(NULL); + } + +/** return a STACK of the ciphers available for the SSL and in order of + * algorithm id */ +STACK_OF(SSL_CIPHER) *ssl_get_ciphers_by_id(SSL *s) + { + if (s != NULL) + { + if (s->cipher_list_by_id != NULL) + { + return(s->cipher_list_by_id); + } + else if ((s->ctx != NULL) && + (s->ctx->cipher_list_by_id != NULL)) + { + return(s->ctx->cipher_list_by_id); + } + } + return(NULL); + } + +/** The old interface to get the same thing as SSL_get_ciphers() */ +const char *SSL_get_cipher_list(const SSL *s,int n) + { + SSL_CIPHER *c; + STACK_OF(SSL_CIPHER) *sk; + + if (s == NULL) return(NULL); + sk=SSL_get_ciphers(s); + if ((sk == NULL) || (sk_SSL_CIPHER_num(sk) <= n)) + return(NULL); + c=sk_SSL_CIPHER_value(sk,n); + if (c == NULL) return(NULL); + return(c->name); + } + +/** specify the ciphers to be used by default by the SSL_CTX */ +int SSL_CTX_set_cipher_list(SSL_CTX *ctx, const char *str) + { + STACK_OF(SSL_CIPHER) *sk; + + sk=ssl_create_cipher_list(ctx->method,&ctx->cipher_list, + &ctx->cipher_list_by_id,str); + /* ssl_create_cipher_list may return an empty stack if it + * was unable to find a cipher matching the given rule string + * (for example if the rule string specifies a cipher which + * has been disabled). This is not an error as far as + * ssl_create_cipher_list is concerned, and hence + * ctx->cipher_list and ctx->cipher_list_by_id has been + * updated. */ + if (sk == NULL) + return 0; + else if (sk_SSL_CIPHER_num(sk) == 0) + { + SSLerr(SSL_F_SSL_CTX_SET_CIPHER_LIST, SSL_R_NO_CIPHER_MATCH); + return 0; + } + return 1; + } + +/** specify the ciphers to be used by the SSL */ +int SSL_set_cipher_list(SSL *s,const char *str) + { + STACK_OF(SSL_CIPHER) *sk; + + sk=ssl_create_cipher_list(s->ctx->method,&s->cipher_list, + &s->cipher_list_by_id,str); + /* see comment in SSL_CTX_set_cipher_list */ + if (sk == NULL) + return 0; + else if (sk_SSL_CIPHER_num(sk) == 0) + { + SSLerr(SSL_F_SSL_SET_CIPHER_LIST, SSL_R_NO_CIPHER_MATCH); + return 0; + } + return 1; + } + +/** specify the ciphers to be used by the SSL */ +int SSL_set_cipher_lists(SSL *s,STACK_OF(SSL_CIPHER) *sk) + { + STACK_OF(SSL_CIPHER) *tmp_cipher_list; + + if (sk == NULL) + return 0; + + /* Based on end of ssl_create_cipher_list */ + tmp_cipher_list = sk_SSL_CIPHER_dup(sk); + if (tmp_cipher_list == NULL) + { + return 0; + } + if (s->cipher_list != NULL) + sk_SSL_CIPHER_free(s->cipher_list); + s->cipher_list = sk; + if (s->cipher_list_by_id != NULL) + sk_SSL_CIPHER_free(s->cipher_list_by_id); + s->cipher_list_by_id = tmp_cipher_list; + (void)sk_SSL_CIPHER_set_cmp_func(s->cipher_list_by_id,ssl_cipher_ptr_id_cmp); + + sk_SSL_CIPHER_sort(s->cipher_list_by_id); + return 1; + } + +/* works well for SSLv2, not so good for SSLv3 */ +char *SSL_get_shared_ciphers(const SSL *s,char *buf,int len) + { + char *p; + STACK_OF(SSL_CIPHER) *sk; + SSL_CIPHER *c; + int i; + + if ((s->session == NULL) || (s->session->ciphers == NULL) || + (len < 2)) + return(NULL); + + p=buf; + sk=s->session->ciphers; + for (i=0; iname); + if (n+1 > len) + { + if (p != buf) + --p; + *p='\0'; + return buf; + } + strcpy(p,c->name); + p+=n; + *(p++)=':'; + len-=n+1; + } + p[-1]='\0'; + return(buf); + } + +int ssl_cipher_list_to_bytes(SSL *s,STACK_OF(SSL_CIPHER) *sk,unsigned char *p, + int (*put_cb)(const SSL_CIPHER *, unsigned char *)) + { + int i,j=0; + SSL_CIPHER *c; + unsigned char *q; +#ifndef OPENSSL_NO_KRB5 + int nokrb5 = !kssl_tgt_is_available(s->kssl_ctx); +#endif /* OPENSSL_NO_KRB5 */ + + if (sk == NULL) return(0); + q=p; + + for (i=0; ialgorithm_mkey & SSL_kKRB5) || (c->algorithm_auth & SSL_aKRB5)) && + nokrb5) + continue; +#endif /* OPENSSL_NO_KRB5 */ +#ifndef OPENSSL_NO_PSK + /* with PSK there must be client callback set */ + if (((c->algorithm_mkey & SSL_kPSK) || (c->algorithm_auth & SSL_aPSK)) && + s->psk_client_callback == NULL) + continue; +#endif /* OPENSSL_NO_PSK */ + j = put_cb ? put_cb(c,p) : ssl_put_cipher_by_char(s,c,p); + p+=j; + } + /* If p == q, no ciphers and caller indicates an error. Otherwise + * add SCSV if not renegotiating. + */ + if (p != q && !s->new_session) + { + static SSL_CIPHER scsv = + { + 0, NULL, SSL3_CK_SCSV, 0, 0, 0, 0, 0, 0, 0, 0, 0 + }; + j = put_cb ? put_cb(&scsv,p) : ssl_put_cipher_by_char(s,&scsv,p); + p+=j; +#ifdef OPENSSL_RI_DEBUG + fprintf(stderr, "SCSV sent by client\n"); +#endif + } + + return(p-q); + } + +STACK_OF(SSL_CIPHER) *ssl_bytes_to_cipher_list(SSL *s,unsigned char *p,int num, + STACK_OF(SSL_CIPHER) **skp) + { + const SSL_CIPHER *c; + STACK_OF(SSL_CIPHER) *sk; + int i,n; + if (s->s3) + s->s3->send_connection_binding = 0; + + n=ssl_put_cipher_by_char(s,NULL,NULL); + if ((num%n) != 0) + { + SSLerr(SSL_F_SSL_BYTES_TO_CIPHER_LIST,SSL_R_ERROR_IN_RECEIVED_CIPHER_LIST); + return(NULL); + } + if ((skp == NULL) || (*skp == NULL)) + sk=sk_SSL_CIPHER_new_null(); /* change perhaps later */ + else + { + sk= *skp; + sk_SSL_CIPHER_zero(sk); + } + + for (i=0; is3 && (n != 3 || !p[0]) && + (p[n-2] == ((SSL3_CK_SCSV >> 8) & 0xff)) && + (p[n-1] == (SSL3_CK_SCSV & 0xff))) + { + /* SCSV fatal if renegotiating */ + if (s->new_session) + { + SSLerr(SSL_F_SSL_BYTES_TO_CIPHER_LIST,SSL_R_SCSV_RECEIVED_WHEN_RENEGOTIATING); + ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_HANDSHAKE_FAILURE); + goto err; + } + s->s3->send_connection_binding = 1; + p += n; +#ifdef OPENSSL_RI_DEBUG + fprintf(stderr, "SCSV received by server\n"); +#endif + continue; + } + + c=ssl_get_cipher_by_char(s,p); + p+=n; + if (c != NULL) + { + if (!sk_SSL_CIPHER_push(sk,c)) + { + SSLerr(SSL_F_SSL_BYTES_TO_CIPHER_LIST,ERR_R_MALLOC_FAILURE); + goto err; + } + } + } + + if (skp != NULL) + *skp=sk; + return(sk); +err: + if ((skp == NULL) || (*skp == NULL)) + sk_SSL_CIPHER_free(sk); + return(NULL); + } + + +#ifndef OPENSSL_NO_TLSEXT +/** return a servername extension value if provided in Client Hello, or NULL. + * So far, only host_name types are defined (RFC 3546). + */ + +const char *SSL_get_servername(const SSL *s, const int type) + { + if (type != TLSEXT_NAMETYPE_host_name) + return NULL; + + return s->session && !s->tlsext_hostname ? + s->session->tlsext_hostname : + s->tlsext_hostname; + } + +int SSL_get_servername_type(const SSL *s) + { + if (s->session && (!s->tlsext_hostname ? s->session->tlsext_hostname : s->tlsext_hostname)) + return TLSEXT_NAMETYPE_host_name; + return -1; + } + +# ifndef OPENSSL_NO_NEXTPROTONEG +/* SSL_select_next_proto implements the standard protocol selection. It is + * expected that this function is called from the callback set by + * SSL_CTX_set_next_proto_select_cb. + * + * The protocol data is assumed to be a vector of 8-bit, length prefixed byte + * strings. The length byte itself is not included in the length. A byte + * string of length 0 is invalid. No byte string may be truncated. + * + * The current, but experimental algorithm for selecting the protocol is: + * + * 1) If the server doesn't support NPN then this is indicated to the + * callback. In this case, the client application has to abort the connection + * or have a default application level protocol. + * + * 2) If the server supports NPN, but advertises an empty list then the + * client selects the first protcol in its list, but indicates via the + * API that this fallback case was enacted. + * + * 3) Otherwise, the client finds the first protocol in the server's list + * that it supports and selects this protocol. This is because it's + * assumed that the server has better information about which protocol + * a client should use. + * + * 4) If the client doesn't support any of the server's advertised + * protocols, then this is treated the same as case 2. + * + * It returns either + * OPENSSL_NPN_NEGOTIATED if a common protocol was found, or + * OPENSSL_NPN_NO_OVERLAP if the fallback case was reached. + */ +int SSL_select_next_proto(unsigned char **out, unsigned char *outlen, const unsigned char *server, unsigned int server_len, const unsigned char *client, unsigned int client_len) + { + unsigned int i, j; + const unsigned char *result; + int status = OPENSSL_NPN_UNSUPPORTED; + + /* For each protocol in server preference order, see if we support it. */ + for (i = 0; i < server_len; ) + { + for (j = 0; j < client_len; ) + { + if (server[i] == client[j] && + memcmp(&server[i+1], &client[j+1], server[i]) == 0) + { + /* We found a match */ + result = &server[i]; + status = OPENSSL_NPN_NEGOTIATED; + goto found; + } + j += client[j]; + j++; + } + i += server[i]; + i++; + } + + /* There's no overlap between our protocols and the server's list. */ + result = client; + status = OPENSSL_NPN_NO_OVERLAP; + + found: + *out = (unsigned char *) result + 1; + *outlen = result[0]; + return status; + } + +/* SSL_get0_next_proto_negotiated sets *data and *len to point to the client's + * requested protocol for this connection and returns 0. If the client didn't + * request any protocol, then *data is set to NULL. + * + * Note that the client can request any protocol it chooses. The value returned + * from this function need not be a member of the list of supported protocols + * provided by the callback. + */ +void SSL_get0_next_proto_negotiated(const SSL *s, const unsigned char **data, unsigned *len) + { + *data = s->next_proto_negotiated; + if (!*data) { + *len = 0; + } else { + *len = s->next_proto_negotiated_len; + } +} + +/* SSL_CTX_set_next_protos_advertised_cb sets a callback that is called when a + * TLS server needs a list of supported protocols for Next Protocol + * Negotiation. The returned list must be in wire format. The list is returned + * by setting |out| to point to it and |outlen| to its length. This memory will + * not be modified, but one should assume that the SSL* keeps a reference to + * it. + * + * The callback should return SSL_TLSEXT_ERR_OK if it wishes to advertise. Otherwise, no + * such extension will be included in the ServerHello. */ +void SSL_CTX_set_next_protos_advertised_cb(SSL_CTX *ctx, int (*cb) (SSL *ssl, const unsigned char **out, unsigned int *outlen, void *arg), void *arg) + { + ctx->next_protos_advertised_cb = cb; + ctx->next_protos_advertised_cb_arg = arg; + } + +/* SSL_CTX_set_next_proto_select_cb sets a callback that is called when a + * client needs to select a protocol from the server's provided list. |out| + * must be set to point to the selected protocol (which may be within |in|). + * The length of the protocol name must be written into |outlen|. The server's + * advertised protocols are provided in |in| and |inlen|. The callback can + * assume that |in| is syntactically valid. + * + * The client must select a protocol. It is fatal to the connection if this + * callback returns a value other than SSL_TLSEXT_ERR_OK. + */ +void SSL_CTX_set_next_proto_select_cb(SSL_CTX *ctx, int (*cb) (SSL *s, unsigned char **out, unsigned char *outlen, const unsigned char *in, unsigned int inlen, void *arg), void *arg) + { + ctx->next_proto_select_cb = cb; + ctx->next_proto_select_cb_arg = arg; + } + +# endif +#endif + +static unsigned long ssl_session_hash(const SSL_SESSION *a) + { + unsigned long l; + + l=(unsigned long) + ((unsigned int) a->session_id[0] )| + ((unsigned int) a->session_id[1]<< 8L)| + ((unsigned long)a->session_id[2]<<16L)| + ((unsigned long)a->session_id[3]<<24L); + return(l); + } + +/* NB: If this function (or indeed the hash function which uses a sort of + * coarser function than this one) is changed, ensure + * SSL_CTX_has_matching_session_id() is checked accordingly. It relies on being + * able to construct an SSL_SESSION that will collide with any existing session + * with a matching session ID. */ +static int ssl_session_cmp(const SSL_SESSION *a,const SSL_SESSION *b) + { + if (a->ssl_version != b->ssl_version) + return(1); + if (a->session_id_length != b->session_id_length) + return(1); + return(memcmp(a->session_id,b->session_id,a->session_id_length)); + } + +/* These wrapper functions should remain rather than redeclaring + * SSL_SESSION_hash and SSL_SESSION_cmp for void* types and casting each + * variable. The reason is that the functions aren't static, they're exposed via + * ssl.h. */ +static IMPLEMENT_LHASH_HASH_FN(ssl_session, SSL_SESSION) +static IMPLEMENT_LHASH_COMP_FN(ssl_session, SSL_SESSION) + +SSL_CTX *SSL_CTX_new(const SSL_METHOD *meth) + { + SSL_CTX *ret=NULL; + + if (meth == NULL) + { + SSLerr(SSL_F_SSL_CTX_NEW,SSL_R_NULL_SSL_METHOD_PASSED); + return(NULL); + } + + if (SSL_get_ex_data_X509_STORE_CTX_idx() < 0) + { + SSLerr(SSL_F_SSL_CTX_NEW,SSL_R_X509_VERIFICATION_SETUP_PROBLEMS); + goto err; + } + ret=(SSL_CTX *)OPENSSL_malloc(sizeof(SSL_CTX)); + if (ret == NULL) + goto err; + + memset(ret,0,sizeof(SSL_CTX)); + + ret->method=meth; + + ret->cert_store=NULL; + ret->session_cache_mode=SSL_SESS_CACHE_SERVER; + ret->session_cache_size=SSL_SESSION_CACHE_MAX_SIZE_DEFAULT; + ret->session_cache_head=NULL; + ret->session_cache_tail=NULL; + + /* We take the system default */ + ret->session_timeout=meth->get_timeout(); + + ret->new_session_cb=0; + ret->remove_session_cb=0; + ret->get_session_cb=0; + ret->generate_session_id=0; + + memset((char *)&ret->stats,0,sizeof(ret->stats)); + + ret->references=1; + ret->quiet_shutdown=0; + +/* ret->cipher=NULL;*/ +/* ret->s2->challenge=NULL; + ret->master_key=NULL; + ret->key_arg=NULL; + ret->s2->conn_id=NULL; */ + + ret->info_callback=NULL; + + ret->app_verify_callback=0; + ret->app_verify_arg=NULL; + + ret->max_cert_list=SSL_MAX_CERT_LIST_DEFAULT; + ret->read_ahead=0; + ret->msg_callback=0; + ret->msg_callback_arg=NULL; + ret->verify_mode=SSL_VERIFY_NONE; +#if 0 + ret->verify_depth=-1; /* Don't impose a limit (but x509_lu.c does) */ +#endif + ret->sid_ctx_length=0; + ret->default_verify_callback=NULL; + if ((ret->cert=ssl_cert_new()) == NULL) + goto err; + + ret->default_passwd_callback=0; + ret->default_passwd_callback_userdata=NULL; + ret->client_cert_cb=0; + ret->app_gen_cookie_cb=0; + ret->app_verify_cookie_cb=0; + + ret->sessions=lh_SSL_SESSION_new(); + if (ret->sessions == NULL) goto err; + ret->cert_store=X509_STORE_new(); + if (ret->cert_store == NULL) goto err; + + ssl_create_cipher_list(ret->method, + &ret->cipher_list,&ret->cipher_list_by_id, + meth->version == SSL2_VERSION ? "SSLv2" : SSL_DEFAULT_CIPHER_LIST); + if (ret->cipher_list == NULL + || sk_SSL_CIPHER_num(ret->cipher_list) <= 0) + { + SSLerr(SSL_F_SSL_CTX_NEW,SSL_R_LIBRARY_HAS_NO_CIPHERS); + goto err2; + } + + ret->param = X509_VERIFY_PARAM_new(); + if (!ret->param) + goto err; + + if ((ret->rsa_md5=EVP_get_digestbyname("ssl2-md5")) == NULL) + { + SSLerr(SSL_F_SSL_CTX_NEW,SSL_R_UNABLE_TO_LOAD_SSL2_MD5_ROUTINES); + goto err2; + } + if ((ret->md5=EVP_get_digestbyname("ssl3-md5")) == NULL) + { + SSLerr(SSL_F_SSL_CTX_NEW,SSL_R_UNABLE_TO_LOAD_SSL3_MD5_ROUTINES); + goto err2; + } + if ((ret->sha1=EVP_get_digestbyname("ssl3-sha1")) == NULL) + { + SSLerr(SSL_F_SSL_CTX_NEW,SSL_R_UNABLE_TO_LOAD_SSL3_SHA1_ROUTINES); + goto err2; + } + + if ((ret->client_CA=sk_X509_NAME_new_null()) == NULL) + goto err; + + CRYPTO_new_ex_data(CRYPTO_EX_INDEX_SSL_CTX, ret, &ret->ex_data); + + ret->extra_certs=NULL; + ret->comp_methods=SSL_COMP_get_compression_methods(); + + ret->max_send_fragment = SSL3_RT_MAX_PLAIN_LENGTH; + +#ifndef OPENSSL_NO_TLSEXT + ret->tlsext_servername_callback = 0; + ret->tlsext_servername_arg = NULL; + /* Setup RFC4507 ticket keys */ + if ((RAND_pseudo_bytes(ret->tlsext_tick_key_name, 16) <= 0) + || (RAND_bytes(ret->tlsext_tick_hmac_key, 16) <= 0) + || (RAND_bytes(ret->tlsext_tick_aes_key, 16) <= 0)) + ret->options |= SSL_OP_NO_TICKET; + + ret->tlsext_status_cb = 0; + ret->tlsext_status_arg = NULL; + +# ifndef OPENSSL_NO_NEXTPROTONEG + ret->next_protos_advertised_cb = 0; + ret->next_proto_select_cb = 0; +# endif +#endif +#ifndef OPENSSL_NO_PSK + ret->psk_identity_hint=NULL; + ret->psk_client_callback=NULL; + ret->psk_server_callback=NULL; +#endif +#ifndef OPENSSL_NO_BUF_FREELISTS + ret->freelist_max_len = SSL_MAX_BUF_FREELIST_LEN_DEFAULT; + ret->rbuf_freelist = OPENSSL_malloc(sizeof(SSL3_BUF_FREELIST)); + if (!ret->rbuf_freelist) + goto err; + ret->rbuf_freelist->chunklen = 0; + ret->rbuf_freelist->len = 0; + ret->rbuf_freelist->head = NULL; + ret->wbuf_freelist = OPENSSL_malloc(sizeof(SSL3_BUF_FREELIST)); + if (!ret->wbuf_freelist) + { + OPENSSL_free(ret->rbuf_freelist); + goto err; + } + ret->wbuf_freelist->chunklen = 0; + ret->wbuf_freelist->len = 0; + ret->wbuf_freelist->head = NULL; +#endif +#ifndef OPENSSL_NO_ENGINE + ret->client_cert_engine = NULL; +#ifdef OPENSSL_SSL_CLIENT_ENGINE_AUTO +#define eng_strx(x) #x +#define eng_str(x) eng_strx(x) + /* Use specific client engine automatically... ignore errors */ + { + ENGINE *eng; + eng = ENGINE_by_id(eng_str(OPENSSL_SSL_CLIENT_ENGINE_AUTO)); + if (!eng) + { + ERR_clear_error(); + ENGINE_load_builtin_engines(); + eng = ENGINE_by_id(eng_str(OPENSSL_SSL_CLIENT_ENGINE_AUTO)); + } + if (!eng || !SSL_CTX_set_client_cert_engine(ret, eng)) + ERR_clear_error(); + } +#endif +#endif + /* Default is to connect to non-RI servers. When RI is more widely + * deployed might change this. + */ + ret->options |= SSL_OP_LEGACY_SERVER_CONNECT; + + return(ret); +err: + SSLerr(SSL_F_SSL_CTX_NEW,ERR_R_MALLOC_FAILURE); +err2: + if (ret != NULL) SSL_CTX_free(ret); + return(NULL); + } + +#if 0 +static void SSL_COMP_free(SSL_COMP *comp) + { OPENSSL_free(comp); } +#endif + +#ifndef OPENSSL_NO_BUF_FREELISTS +static void +ssl_buf_freelist_free(SSL3_BUF_FREELIST *list) + { + SSL3_BUF_FREELIST_ENTRY *ent, *next; + for (ent = list->head; ent; ent = next) + { + next = ent->next; + OPENSSL_free(ent); + } + OPENSSL_free(list); + } +#endif + +void SSL_CTX_free(SSL_CTX *a) + { + int i; + + if (a == NULL) return; + + i=CRYPTO_add(&a->references,-1,CRYPTO_LOCK_SSL_CTX); +#ifdef REF_PRINT + REF_PRINT("SSL_CTX",a); +#endif + if (i > 0) return; +#ifdef REF_CHECK + if (i < 0) + { + fprintf(stderr,"SSL_CTX_free, bad reference count\n"); + abort(); /* ok */ + } +#endif + + if (a->param) + X509_VERIFY_PARAM_free(a->param); + + /* + * Free internal session cache. However: the remove_cb() may reference + * the ex_data of SSL_CTX, thus the ex_data store can only be removed + * after the sessions were flushed. + * As the ex_data handling routines might also touch the session cache, + * the most secure solution seems to be: empty (flush) the cache, then + * free ex_data, then finally free the cache. + * (See ticket [openssl.org #212].) + */ + if (a->sessions != NULL) + SSL_CTX_flush_sessions(a,0); + + CRYPTO_free_ex_data(CRYPTO_EX_INDEX_SSL_CTX, a, &a->ex_data); + + if (a->sessions != NULL) + lh_SSL_SESSION_free(a->sessions); + + if (a->cert_store != NULL) + X509_STORE_free(a->cert_store); + if (a->cipher_list != NULL) + sk_SSL_CIPHER_free(a->cipher_list); + if (a->cipher_list_by_id != NULL) + sk_SSL_CIPHER_free(a->cipher_list_by_id); + if (a->cert != NULL) + ssl_cert_free(a->cert); + if (a->client_CA != NULL) + sk_X509_NAME_pop_free(a->client_CA,X509_NAME_free); + if (a->extra_certs != NULL) + sk_X509_pop_free(a->extra_certs,X509_free); +#if 0 /* This should never be done, since it removes a global database */ + if (a->comp_methods != NULL) + sk_SSL_COMP_pop_free(a->comp_methods,SSL_COMP_free); +#else + a->comp_methods = NULL; +#endif + +#ifndef OPENSSL_NO_PSK + if (a->psk_identity_hint) + OPENSSL_free(a->psk_identity_hint); +#endif +#ifndef OPENSSL_NO_ENGINE + if (a->client_cert_engine) + ENGINE_finish(a->client_cert_engine); +#endif + +#ifndef OPENSSL_NO_BUF_FREELISTS + if (a->wbuf_freelist) + ssl_buf_freelist_free(a->wbuf_freelist); + if (a->rbuf_freelist) + ssl_buf_freelist_free(a->rbuf_freelist); +#endif + + OPENSSL_free(a); + } + +void SSL_CTX_set_default_passwd_cb(SSL_CTX *ctx, pem_password_cb *cb) + { + ctx->default_passwd_callback=cb; + } + +void SSL_CTX_set_default_passwd_cb_userdata(SSL_CTX *ctx,void *u) + { + ctx->default_passwd_callback_userdata=u; + } + +void SSL_CTX_set_cert_verify_callback(SSL_CTX *ctx, int (*cb)(X509_STORE_CTX *,void *), void *arg) + { + ctx->app_verify_callback=cb; + ctx->app_verify_arg=arg; + } + +void SSL_CTX_set_verify(SSL_CTX *ctx,int mode,int (*cb)(int, X509_STORE_CTX *)) + { + ctx->verify_mode=mode; + ctx->default_verify_callback=cb; + } + +void SSL_CTX_set_verify_depth(SSL_CTX *ctx,int depth) + { + X509_VERIFY_PARAM_set_depth(ctx->param, depth); + } + +void ssl_set_cert_masks(CERT *c, const SSL_CIPHER *cipher) + { + CERT_PKEY *cpk; + int rsa_enc,rsa_tmp,rsa_sign,dh_tmp,dh_rsa,dh_dsa,dsa_sign; + int rsa_enc_export,dh_rsa_export,dh_dsa_export; + int rsa_tmp_export,dh_tmp_export,kl; + unsigned long mask_k,mask_a,emask_k,emask_a; + int have_ecc_cert, ecdh_ok, ecdsa_ok, ecc_pkey_size; +#ifndef OPENSSL_NO_ECDH + int have_ecdh_tmp; +#endif + X509 *x = NULL; + EVP_PKEY *ecc_pkey = NULL; + int signature_nid = 0, pk_nid = 0, md_nid = 0; + + if (c == NULL) return; + + kl=SSL_C_EXPORT_PKEYLENGTH(cipher); + +#ifndef OPENSSL_NO_RSA + rsa_tmp=(c->rsa_tmp != NULL || c->rsa_tmp_cb != NULL); + rsa_tmp_export=(c->rsa_tmp_cb != NULL || + (rsa_tmp && RSA_size(c->rsa_tmp)*8 <= kl)); +#else + rsa_tmp=rsa_tmp_export=0; +#endif +#ifndef OPENSSL_NO_DH + dh_tmp=(c->dh_tmp != NULL || c->dh_tmp_cb != NULL); + dh_tmp_export=(c->dh_tmp_cb != NULL || + (dh_tmp && DH_size(c->dh_tmp)*8 <= kl)); +#else + dh_tmp=dh_tmp_export=0; +#endif + +#ifndef OPENSSL_NO_ECDH + have_ecdh_tmp=(c->ecdh_tmp != NULL || c->ecdh_tmp_cb != NULL); +#endif + cpk= &(c->pkeys[SSL_PKEY_RSA_ENC]); + rsa_enc= (cpk->x509 != NULL && cpk->privatekey != NULL); + rsa_enc_export=(rsa_enc && EVP_PKEY_size(cpk->privatekey)*8 <= kl); + cpk= &(c->pkeys[SSL_PKEY_RSA_SIGN]); + rsa_sign=(cpk->x509 != NULL && cpk->privatekey != NULL); + cpk= &(c->pkeys[SSL_PKEY_DSA_SIGN]); + dsa_sign=(cpk->x509 != NULL && cpk->privatekey != NULL); + cpk= &(c->pkeys[SSL_PKEY_DH_RSA]); + dh_rsa= (cpk->x509 != NULL && cpk->privatekey != NULL); + dh_rsa_export=(dh_rsa && EVP_PKEY_size(cpk->privatekey)*8 <= kl); + cpk= &(c->pkeys[SSL_PKEY_DH_DSA]); +/* FIX THIS EAY EAY EAY */ + dh_dsa= (cpk->x509 != NULL && cpk->privatekey != NULL); + dh_dsa_export=(dh_dsa && EVP_PKEY_size(cpk->privatekey)*8 <= kl); + cpk= &(c->pkeys[SSL_PKEY_ECC]); + have_ecc_cert= (cpk->x509 != NULL && cpk->privatekey != NULL); + mask_k=0; + mask_a=0; + emask_k=0; + emask_a=0; + + + +#ifdef CIPHER_DEBUG + printf("rt=%d rte=%d dht=%d ecdht=%d re=%d ree=%d rs=%d ds=%d dhr=%d dhd=%d\n", + rsa_tmp,rsa_tmp_export,dh_tmp,have_ecdh_tmp, + rsa_enc,rsa_enc_export,rsa_sign,dsa_sign,dh_rsa,dh_dsa); +#endif + + cpk = &(c->pkeys[SSL_PKEY_GOST01]); + if (cpk->x509 != NULL && cpk->privatekey !=NULL) { + mask_k |= SSL_kGOST; + mask_a |= SSL_aGOST01; + } + cpk = &(c->pkeys[SSL_PKEY_GOST94]); + if (cpk->x509 != NULL && cpk->privatekey !=NULL) { + mask_k |= SSL_kGOST; + mask_a |= SSL_aGOST94; + } + + if (rsa_enc || (rsa_tmp && rsa_sign)) + mask_k|=SSL_kRSA; + if (rsa_enc_export || (rsa_tmp_export && (rsa_sign || rsa_enc))) + emask_k|=SSL_kRSA; + +#if 0 + /* The match needs to be both kEDH and aRSA or aDSA, so don't worry */ + if ( (dh_tmp || dh_rsa || dh_dsa) && + (rsa_enc || rsa_sign || dsa_sign)) + mask_k|=SSL_kEDH; + if ((dh_tmp_export || dh_rsa_export || dh_dsa_export) && + (rsa_enc || rsa_sign || dsa_sign)) + emask_k|=SSL_kEDH; +#endif + + if (dh_tmp_export) + emask_k|=SSL_kEDH; + + if (dh_tmp) + mask_k|=SSL_kEDH; + + if (dh_rsa) mask_k|=SSL_kDHr; + if (dh_rsa_export) emask_k|=SSL_kDHr; + + if (dh_dsa) mask_k|=SSL_kDHd; + if (dh_dsa_export) emask_k|=SSL_kDHd; + + if (rsa_enc || rsa_sign) + { + mask_a|=SSL_aRSA; + emask_a|=SSL_aRSA; + } + + if (dsa_sign) + { + mask_a|=SSL_aDSS; + emask_a|=SSL_aDSS; + } + + mask_a|=SSL_aNULL; + emask_a|=SSL_aNULL; + +#ifndef OPENSSL_NO_KRB5 + mask_k|=SSL_kKRB5; + mask_a|=SSL_aKRB5; + emask_k|=SSL_kKRB5; + emask_a|=SSL_aKRB5; +#endif + + /* An ECC certificate may be usable for ECDH and/or + * ECDSA cipher suites depending on the key usage extension. + */ + if (have_ecc_cert) + { + /* This call populates extension flags (ex_flags) */ + x = (c->pkeys[SSL_PKEY_ECC]).x509; + X509_check_purpose(x, -1, 0); + ecdh_ok = (x->ex_flags & EXFLAG_KUSAGE) ? + (x->ex_kusage & X509v3_KU_KEY_AGREEMENT) : 1; + ecdsa_ok = (x->ex_flags & EXFLAG_KUSAGE) ? + (x->ex_kusage & X509v3_KU_DIGITAL_SIGNATURE) : 1; + ecc_pkey = X509_get_pubkey(x); + ecc_pkey_size = (ecc_pkey != NULL) ? + EVP_PKEY_bits(ecc_pkey) : 0; + EVP_PKEY_free(ecc_pkey); + if ((x->sig_alg) && (x->sig_alg->algorithm)) + { + signature_nid = OBJ_obj2nid(x->sig_alg->algorithm); + OBJ_find_sigid_algs(signature_nid, &md_nid, &pk_nid); + } +#ifndef OPENSSL_NO_ECDH + if (ecdh_ok) + { + + if (pk_nid == NID_rsaEncryption || pk_nid == NID_rsa) + { + mask_k|=SSL_kECDHr; + mask_a|=SSL_aECDH; + if (ecc_pkey_size <= 163) + { + emask_k|=SSL_kECDHr; + emask_a|=SSL_aECDH; + } + } + + if (pk_nid == NID_X9_62_id_ecPublicKey) + { + mask_k|=SSL_kECDHe; + mask_a|=SSL_aECDH; + if (ecc_pkey_size <= 163) + { + emask_k|=SSL_kECDHe; + emask_a|=SSL_aECDH; + } + } + } +#endif +#ifndef OPENSSL_NO_ECDSA + if (ecdsa_ok) + { + mask_a|=SSL_aECDSA; + emask_a|=SSL_aECDSA; + } +#endif + } + +#ifndef OPENSSL_NO_ECDH + if (have_ecdh_tmp) + { + mask_k|=SSL_kEECDH; + emask_k|=SSL_kEECDH; + } +#endif + +#ifndef OPENSSL_NO_PSK + mask_k |= SSL_kPSK; + mask_a |= SSL_aPSK; + emask_k |= SSL_kPSK; + emask_a |= SSL_aPSK; +#endif + + c->mask_k=mask_k; + c->mask_a=mask_a; + c->export_mask_k=emask_k; + c->export_mask_a=emask_a; + c->valid=1; + } + +/* This handy macro borrowed from crypto/x509v3/v3_purp.c */ +#define ku_reject(x, usage) \ + (((x)->ex_flags & EXFLAG_KUSAGE) && !((x)->ex_kusage & (usage))) + +#ifndef OPENSSL_NO_EC + +int ssl_check_srvr_ecc_cert_and_alg(X509 *x, const SSL_CIPHER *cs) + { + unsigned long alg_k, alg_a; + EVP_PKEY *pkey = NULL; + int keysize = 0; + int signature_nid = 0, md_nid = 0, pk_nid = 0; + + alg_k = cs->algorithm_mkey; + alg_a = cs->algorithm_auth; + + if (SSL_C_IS_EXPORT(cs)) + { + /* ECDH key length in export ciphers must be <= 163 bits */ + pkey = X509_get_pubkey(x); + if (pkey == NULL) return 0; + keysize = EVP_PKEY_bits(pkey); + EVP_PKEY_free(pkey); + if (keysize > 163) return 0; + } + + /* This call populates the ex_flags field correctly */ + X509_check_purpose(x, -1, 0); + if ((x->sig_alg) && (x->sig_alg->algorithm)) + { + signature_nid = OBJ_obj2nid(x->sig_alg->algorithm); + OBJ_find_sigid_algs(signature_nid, &md_nid, &pk_nid); + } + if (alg_k & SSL_kECDHe || alg_k & SSL_kECDHr) + { + /* key usage, if present, must allow key agreement */ + if (ku_reject(x, X509v3_KU_KEY_AGREEMENT)) + { + SSLerr(SSL_F_SSL_CHECK_SRVR_ECC_CERT_AND_ALG, SSL_R_ECC_CERT_NOT_FOR_KEY_AGREEMENT); + return 0; + } + if (alg_k & SSL_kECDHe) + { + /* signature alg must be ECDSA */ + if (pk_nid != NID_X9_62_id_ecPublicKey) + { + SSLerr(SSL_F_SSL_CHECK_SRVR_ECC_CERT_AND_ALG, SSL_R_ECC_CERT_SHOULD_HAVE_SHA1_SIGNATURE); + return 0; + } + } + if (alg_k & SSL_kECDHr) + { + /* signature alg must be RSA */ + + if (pk_nid != NID_rsaEncryption && pk_nid != NID_rsa) + { + SSLerr(SSL_F_SSL_CHECK_SRVR_ECC_CERT_AND_ALG, SSL_R_ECC_CERT_SHOULD_HAVE_RSA_SIGNATURE); + return 0; + } + } + } + if (alg_a & SSL_aECDSA) + { + /* key usage, if present, must allow signing */ + if (ku_reject(x, X509v3_KU_DIGITAL_SIGNATURE)) + { + SSLerr(SSL_F_SSL_CHECK_SRVR_ECC_CERT_AND_ALG, SSL_R_ECC_CERT_NOT_FOR_SIGNING); + return 0; + } + } + + return 1; /* all checks are ok */ + } + +#endif + +/* THIS NEEDS CLEANING UP */ +X509 *ssl_get_server_send_cert(SSL *s) + { + unsigned long alg_k,alg_a; + CERT *c; + int i; + + c=s->cert; + ssl_set_cert_masks(c, s->s3->tmp.new_cipher); + + alg_k = s->s3->tmp.new_cipher->algorithm_mkey; + alg_a = s->s3->tmp.new_cipher->algorithm_auth; + + if (alg_k & (SSL_kECDHr|SSL_kECDHe)) + { + /* we don't need to look at SSL_kEECDH + * since no certificate is needed for + * anon ECDH and for authenticated + * EECDH, the check for the auth + * algorithm will set i correctly + * NOTE: For ECDH-RSA, we need an ECC + * not an RSA cert but for EECDH-RSA + * we need an RSA cert. Placing the + * checks for SSL_kECDH before RSA + * checks ensures the correct cert is chosen. + */ + i=SSL_PKEY_ECC; + } + else if (alg_a & SSL_aECDSA) + { + i=SSL_PKEY_ECC; + } + else if (alg_k & SSL_kDHr) + i=SSL_PKEY_DH_RSA; + else if (alg_k & SSL_kDHd) + i=SSL_PKEY_DH_DSA; + else if (alg_a & SSL_aDSS) + i=SSL_PKEY_DSA_SIGN; + else if (alg_a & SSL_aRSA) + { + if (c->pkeys[SSL_PKEY_RSA_ENC].x509 == NULL) + i=SSL_PKEY_RSA_SIGN; + else + i=SSL_PKEY_RSA_ENC; + } + else if (alg_a & SSL_aKRB5) + { + /* VRS something else here? */ + return(NULL); + } + else if (alg_a & SSL_aGOST94) + i=SSL_PKEY_GOST94; + else if (alg_a & SSL_aGOST01) + i=SSL_PKEY_GOST01; + else /* if (alg_a & SSL_aNULL) */ + { + SSLerr(SSL_F_SSL_GET_SERVER_SEND_CERT,ERR_R_INTERNAL_ERROR); + return(NULL); + } + if (c->pkeys[i].x509 == NULL) return(NULL); + + return(c->pkeys[i].x509); + } + +EVP_PKEY *ssl_get_sign_pkey(SSL *s,const SSL_CIPHER *cipher) + { + unsigned long alg_a; + CERT *c; + + alg_a = cipher->algorithm_auth; + c=s->cert; + + if ((alg_a & SSL_aDSS) && + (c->pkeys[SSL_PKEY_DSA_SIGN].privatekey != NULL)) + return(c->pkeys[SSL_PKEY_DSA_SIGN].privatekey); + else if (alg_a & SSL_aRSA) + { + if (c->pkeys[SSL_PKEY_RSA_SIGN].privatekey != NULL) + return(c->pkeys[SSL_PKEY_RSA_SIGN].privatekey); + else if (c->pkeys[SSL_PKEY_RSA_ENC].privatekey != NULL) + return(c->pkeys[SSL_PKEY_RSA_ENC].privatekey); + else + return(NULL); + } + else if ((alg_a & SSL_aECDSA) && + (c->pkeys[SSL_PKEY_ECC].privatekey != NULL)) + return(c->pkeys[SSL_PKEY_ECC].privatekey); + else /* if (alg_a & SSL_aNULL) */ + { + SSLerr(SSL_F_SSL_GET_SIGN_PKEY,ERR_R_INTERNAL_ERROR); + return(NULL); + } + } + +void ssl_update_cache(SSL *s,int mode) + { + int i; + + /* If the session_id_length is 0, we are not supposed to cache it, + * and it would be rather hard to do anyway :-) */ + if (s->session->session_id_length == 0) return; + + i=s->session_ctx->session_cache_mode; + if ((i & mode) && (!s->hit) + && ((i & SSL_SESS_CACHE_NO_INTERNAL_STORE) + || SSL_CTX_add_session(s->session_ctx,s->session)) + && (s->session_ctx->new_session_cb != NULL)) + { + CRYPTO_add(&s->session->references,1,CRYPTO_LOCK_SSL_SESSION); + if (!s->session_ctx->new_session_cb(s,s->session)) + SSL_SESSION_free(s->session); + } + + /* auto flush every 255 connections */ + if ((!(i & SSL_SESS_CACHE_NO_AUTO_CLEAR)) && + ((i & mode) == mode)) + { + if ( (((mode & SSL_SESS_CACHE_CLIENT) + ?s->session_ctx->stats.sess_connect_good + :s->session_ctx->stats.sess_accept_good) & 0xff) == 0xff) + { + SSL_CTX_flush_sessions(s->session_ctx,(unsigned long)time(NULL)); + } + } + } + +const SSL_METHOD *SSL_get_ssl_method(SSL *s) + { + return(s->method); + } + +int SSL_set_ssl_method(SSL *s, const SSL_METHOD *meth) + { + int conn= -1; + int ret=1; + + if (s->method != meth) + { + if (s->handshake_func != NULL) + conn=(s->handshake_func == s->method->ssl_connect); + + if (s->method->version == meth->version) + s->method=meth; + else + { + s->method->ssl_free(s); + s->method=meth; + ret=s->method->ssl_new(s); + } + + if (conn == 1) + s->handshake_func=meth->ssl_connect; + else if (conn == 0) + s->handshake_func=meth->ssl_accept; + } + return(ret); + } + +int SSL_get_error(const SSL *s,int i) + { + int reason; + unsigned long l; + BIO *bio; + + if (i > 0) return(SSL_ERROR_NONE); + + /* Make things return SSL_ERROR_SYSCALL when doing SSL_do_handshake + * etc, where we do encode the error */ + if ((l=ERR_peek_error()) != 0) + { + if (ERR_GET_LIB(l) == ERR_LIB_SYS) + return(SSL_ERROR_SYSCALL); + else + return(SSL_ERROR_SSL); + } + + if ((i < 0) && SSL_want_read(s)) + { + bio=SSL_get_rbio(s); + if (BIO_should_read(bio)) + return(SSL_ERROR_WANT_READ); + else if (BIO_should_write(bio)) + /* This one doesn't make too much sense ... We never try + * to write to the rbio, and an application program where + * rbio and wbio are separate couldn't even know what it + * should wait for. + * However if we ever set s->rwstate incorrectly + * (so that we have SSL_want_read(s) instead of + * SSL_want_write(s)) and rbio and wbio *are* the same, + * this test works around that bug; so it might be safer + * to keep it. */ + return(SSL_ERROR_WANT_WRITE); + else if (BIO_should_io_special(bio)) + { + reason=BIO_get_retry_reason(bio); + if (reason == BIO_RR_CONNECT) + return(SSL_ERROR_WANT_CONNECT); + else if (reason == BIO_RR_ACCEPT) + return(SSL_ERROR_WANT_ACCEPT); + else + return(SSL_ERROR_SYSCALL); /* unknown */ + } + } + + if ((i < 0) && SSL_want_write(s)) + { + bio=SSL_get_wbio(s); + if (BIO_should_write(bio)) + return(SSL_ERROR_WANT_WRITE); + else if (BIO_should_read(bio)) + /* See above (SSL_want_read(s) with BIO_should_write(bio)) */ + return(SSL_ERROR_WANT_READ); + else if (BIO_should_io_special(bio)) + { + reason=BIO_get_retry_reason(bio); + if (reason == BIO_RR_CONNECT) + return(SSL_ERROR_WANT_CONNECT); + else if (reason == BIO_RR_ACCEPT) + return(SSL_ERROR_WANT_ACCEPT); + else + return(SSL_ERROR_SYSCALL); + } + } + if ((i < 0) && SSL_want_x509_lookup(s)) + { + return(SSL_ERROR_WANT_X509_LOOKUP); + } + + if (i == 0) + { + if (s->version == SSL2_VERSION) + { + /* assume it is the socket being closed */ + return(SSL_ERROR_ZERO_RETURN); + } + else + { + if ((s->shutdown & SSL_RECEIVED_SHUTDOWN) && + (s->s3->warn_alert == SSL_AD_CLOSE_NOTIFY)) + return(SSL_ERROR_ZERO_RETURN); + } + } + return(SSL_ERROR_SYSCALL); + } + +int SSL_do_handshake(SSL *s) + { + int ret=1; + + if (s->handshake_func == NULL) + { + SSLerr(SSL_F_SSL_DO_HANDSHAKE,SSL_R_CONNECTION_TYPE_NOT_SET); + return(-1); + } + + s->method->ssl_renegotiate_check(s); + + if (SSL_in_init(s) || SSL_in_before(s)) + { + ret=s->handshake_func(s); + } + return(ret); + } + +/* For the next 2 functions, SSL_clear() sets shutdown and so + * one of these calls will reset it */ +void SSL_set_accept_state(SSL *s) + { + s->server=1; + s->shutdown=0; + s->state=SSL_ST_ACCEPT|SSL_ST_BEFORE; + s->handshake_func=s->method->ssl_accept; + /* clear the current cipher */ + ssl_clear_cipher_ctx(s); + ssl_clear_hash_ctx(&s->read_hash); + ssl_clear_hash_ctx(&s->write_hash); + } + +void SSL_set_connect_state(SSL *s) + { + s->server=0; + s->shutdown=0; + s->state=SSL_ST_CONNECT|SSL_ST_BEFORE; + s->handshake_func=s->method->ssl_connect; + /* clear the current cipher */ + ssl_clear_cipher_ctx(s); + ssl_clear_hash_ctx(&s->read_hash); + ssl_clear_hash_ctx(&s->write_hash); + } + +int ssl_undefined_function(SSL *s) + { + SSLerr(SSL_F_SSL_UNDEFINED_FUNCTION,ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED); + return(0); + } + +int ssl_undefined_void_function(void) + { + SSLerr(SSL_F_SSL_UNDEFINED_VOID_FUNCTION,ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED); + return(0); + } + +int ssl_undefined_const_function(const SSL *s) + { + SSLerr(SSL_F_SSL_UNDEFINED_CONST_FUNCTION,ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED); + return(0); + } + +SSL_METHOD *ssl_bad_method(int ver) + { + SSLerr(SSL_F_SSL_BAD_METHOD,ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED); + return(NULL); + } + +static const char *ssl_get_version(int version) + { + if (version == TLS1_VERSION) + return("TLSv1"); + else if (version == SSL3_VERSION) + return("SSLv3"); + else if (version == SSL2_VERSION) + return("SSLv2"); + else + return("unknown"); + } + +const char *SSL_get_version(const SSL *s) + { + return ssl_get_version(s->version); + } + +const char *SSL_SESSION_get_version(const SSL_SESSION *s) + { + return ssl_get_version(s->ssl_version); + } + +const char* SSL_authentication_method(const SSL* ssl) + { + if (ssl->cert != NULL && ssl->cert->rsa_tmp != NULL) + return SSL_TXT_RSA "_" SSL_TXT_EXPORT; + switch (ssl->version) + { + case SSL2_VERSION: + return SSL_TXT_RSA; + case SSL3_VERSION: + case TLS1_VERSION: + case DTLS1_VERSION: + return SSL_CIPHER_authentication_method(ssl->s3->tmp.new_cipher); + default: + return "UNKNOWN"; + } + } + +SSL *SSL_dup(SSL *s) + { + STACK_OF(X509_NAME) *sk; + X509_NAME *xn; + SSL *ret; + int i; + + if ((ret=SSL_new(SSL_get_SSL_CTX(s))) == NULL) + return(NULL); + + ret->version = s->version; + ret->type = s->type; + ret->method = s->method; + + if (s->session != NULL) + { + /* This copies session-id, SSL_METHOD, sid_ctx, and 'cert' */ + SSL_copy_session_id(ret,s); + } + else + { + /* No session has been established yet, so we have to expect + * that s->cert or ret->cert will be changed later -- + * they should not both point to the same object, + * and thus we can't use SSL_copy_session_id. */ + + ret->method->ssl_free(ret); + ret->method = s->method; + ret->method->ssl_new(ret); + + if (s->cert != NULL) + { + if (ret->cert != NULL) + { + ssl_cert_free(ret->cert); + } + ret->cert = ssl_cert_dup(s->cert); + if (ret->cert == NULL) + goto err; + } + + SSL_set_session_id_context(ret, + s->sid_ctx, s->sid_ctx_length); + } + + ret->options=s->options; + ret->mode=s->mode; + SSL_set_max_cert_list(ret,SSL_get_max_cert_list(s)); + SSL_set_read_ahead(ret,SSL_get_read_ahead(s)); + ret->msg_callback = s->msg_callback; + ret->msg_callback_arg = s->msg_callback_arg; + SSL_set_verify(ret,SSL_get_verify_mode(s), + SSL_get_verify_callback(s)); + SSL_set_verify_depth(ret,SSL_get_verify_depth(s)); + ret->generate_session_id = s->generate_session_id; + + SSL_set_info_callback(ret,SSL_get_info_callback(s)); + + ret->debug=s->debug; + + /* copy app data, a little dangerous perhaps */ + if (!CRYPTO_dup_ex_data(CRYPTO_EX_INDEX_SSL, &ret->ex_data, &s->ex_data)) + goto err; + + /* setup rbio, and wbio */ + if (s->rbio != NULL) + { + if (!BIO_dup_state(s->rbio,(char *)&ret->rbio)) + goto err; + } + if (s->wbio != NULL) + { + if (s->wbio != s->rbio) + { + if (!BIO_dup_state(s->wbio,(char *)&ret->wbio)) + goto err; + } + else + ret->wbio=ret->rbio; + } + ret->rwstate = s->rwstate; + ret->in_handshake = s->in_handshake; + ret->handshake_func = s->handshake_func; + ret->server = s->server; + ret->new_session = s->new_session; + ret->quiet_shutdown = s->quiet_shutdown; + ret->shutdown=s->shutdown; + ret->state=s->state; /* SSL_dup does not really work at any state, though */ + ret->rstate=s->rstate; + ret->init_num = 0; /* would have to copy ret->init_buf, ret->init_msg, ret->init_num, ret->init_off */ + ret->hit=s->hit; + + X509_VERIFY_PARAM_inherit(ret->param, s->param); + + /* dup the cipher_list and cipher_list_by_id stacks */ + if (s->cipher_list != NULL) + { + if ((ret->cipher_list=sk_SSL_CIPHER_dup(s->cipher_list)) == NULL) + goto err; + } + if (s->cipher_list_by_id != NULL) + if ((ret->cipher_list_by_id=sk_SSL_CIPHER_dup(s->cipher_list_by_id)) + == NULL) + goto err; + + /* Dup the client_CA list */ + if (s->client_CA != NULL) + { + if ((sk=sk_X509_NAME_dup(s->client_CA)) == NULL) goto err; + ret->client_CA=sk; + for (i=0; ienc_read_ctx != NULL) + { + EVP_CIPHER_CTX_cleanup(s->enc_read_ctx); + OPENSSL_free(s->enc_read_ctx); + s->enc_read_ctx=NULL; + } + if (s->enc_write_ctx != NULL) + { + EVP_CIPHER_CTX_cleanup(s->enc_write_ctx); + OPENSSL_free(s->enc_write_ctx); + s->enc_write_ctx=NULL; + } +#ifndef OPENSSL_NO_COMP + if (s->expand != NULL) + { + COMP_CTX_free(s->expand); + s->expand=NULL; + } + if (s->compress != NULL) + { + COMP_CTX_free(s->compress); + s->compress=NULL; + } +#endif + } + +/* Fix this function so that it takes an optional type parameter */ +X509 *SSL_get_certificate(const SSL *s) + { + if (s->cert != NULL) + return(s->cert->key->x509); + else + return(NULL); + } + +/* Fix this function so that it takes an optional type parameter */ +EVP_PKEY *SSL_get_privatekey(SSL *s) + { + if (s->cert != NULL) + return(s->cert->key->privatekey); + else + return(NULL); + } + +const SSL_CIPHER *SSL_get_current_cipher(const SSL *s) + { + if ((s->session != NULL) && (s->session->cipher != NULL)) + return(s->session->cipher); + return(NULL); + } +#ifdef OPENSSL_NO_COMP +const void *SSL_get_current_compression(SSL *s) + { + return NULL; + } +const void *SSL_get_current_expansion(SSL *s) + { + return NULL; + } +#else + +const COMP_METHOD *SSL_get_current_compression(SSL *s) + { + if (s->compress != NULL) + return(s->compress->meth); + return(NULL); + } + +const COMP_METHOD *SSL_get_current_expansion(SSL *s) + { + if (s->expand != NULL) + return(s->expand->meth); + return(NULL); + } +#endif + +int ssl_init_wbio_buffer(SSL *s,int push) + { + BIO *bbio; + + if (s->bbio == NULL) + { + bbio=BIO_new(BIO_f_buffer()); + if (bbio == NULL) return(0); + s->bbio=bbio; + } + else + { + bbio=s->bbio; + if (s->bbio == s->wbio) + s->wbio=BIO_pop(s->wbio); + } + (void)BIO_reset(bbio); +/* if (!BIO_set_write_buffer_size(bbio,16*1024)) */ + if (!BIO_set_read_buffer_size(bbio,1)) + { + SSLerr(SSL_F_SSL_INIT_WBIO_BUFFER,ERR_R_BUF_LIB); + return(0); + } + if (push) + { + if (s->wbio != bbio) + s->wbio=BIO_push(bbio,s->wbio); + } + else + { + if (s->wbio == bbio) + s->wbio=BIO_pop(bbio); + } + return(1); + } + +void ssl_free_wbio_buffer(SSL *s) + { + if (s->bbio == NULL) return; + + if (s->bbio == s->wbio) + { + /* remove buffering */ + s->wbio=BIO_pop(s->wbio); +#ifdef REF_CHECK /* not the usual REF_CHECK, but this avoids adding one more preprocessor symbol */ + assert(s->wbio != NULL); +#endif + } + BIO_free(s->bbio); + s->bbio=NULL; + } + +void SSL_CTX_set_quiet_shutdown(SSL_CTX *ctx,int mode) + { + ctx->quiet_shutdown=mode; + } + +int SSL_CTX_get_quiet_shutdown(const SSL_CTX *ctx) + { + return(ctx->quiet_shutdown); + } + +void SSL_set_quiet_shutdown(SSL *s,int mode) + { + s->quiet_shutdown=mode; + } + +int SSL_get_quiet_shutdown(const SSL *s) + { + return(s->quiet_shutdown); + } + +void SSL_set_shutdown(SSL *s,int mode) + { + s->shutdown=mode; + } + +int SSL_get_shutdown(const SSL *s) + { + return(s->shutdown); + } + +int SSL_version(const SSL *s) + { + return(s->version); + } + +SSL_CTX *SSL_get_SSL_CTX(const SSL *ssl) + { + return(ssl->ctx); + } + +SSL_CTX *SSL_set_SSL_CTX(SSL *ssl, SSL_CTX* ctx) + { + if (ssl->ctx == ctx) + return ssl->ctx; +#ifndef OPENSSL_NO_TLSEXT + if (ctx == NULL) + ctx = ssl->initial_ctx; +#endif + if (ssl->cert != NULL) + ssl_cert_free(ssl->cert); + ssl->cert = ssl_cert_dup(ctx->cert); + CRYPTO_add(&ctx->references,1,CRYPTO_LOCK_SSL_CTX); + if (ssl->ctx != NULL) + SSL_CTX_free(ssl->ctx); /* decrement reference count */ + ssl->ctx = ctx; + return(ssl->ctx); + } + +#ifndef OPENSSL_NO_STDIO +int SSL_CTX_set_default_verify_paths(SSL_CTX *ctx) + { + return(X509_STORE_set_default_paths(ctx->cert_store)); + } + +int SSL_CTX_load_verify_locations(SSL_CTX *ctx, const char *CAfile, + const char *CApath) + { + return(X509_STORE_load_locations(ctx->cert_store,CAfile,CApath)); + } +#endif + +void SSL_set_info_callback(SSL *ssl, + void (*cb)(const SSL *ssl,int type,int val)) + { + ssl->info_callback=cb; + } + +/* One compiler (Diab DCC) doesn't like argument names in returned + function pointer. */ +void (*SSL_get_info_callback(const SSL *ssl))(const SSL * /*ssl*/,int /*type*/,int /*val*/) + { + return ssl->info_callback; + } + +int SSL_state(const SSL *ssl) + { + return(ssl->state); + } + +void SSL_set_verify_result(SSL *ssl,long arg) + { + ssl->verify_result=arg; + } + +long SSL_get_verify_result(const SSL *ssl) + { + return(ssl->verify_result); + } + +int SSL_get_ex_new_index(long argl,void *argp,CRYPTO_EX_new *new_func, + CRYPTO_EX_dup *dup_func,CRYPTO_EX_free *free_func) + { + return CRYPTO_get_ex_new_index(CRYPTO_EX_INDEX_SSL, argl, argp, + new_func, dup_func, free_func); + } + +int SSL_set_ex_data(SSL *s,int idx,void *arg) + { + return(CRYPTO_set_ex_data(&s->ex_data,idx,arg)); + } + +void *SSL_get_ex_data(const SSL *s,int idx) + { + return(CRYPTO_get_ex_data(&s->ex_data,idx)); + } + +int SSL_CTX_get_ex_new_index(long argl,void *argp,CRYPTO_EX_new *new_func, + CRYPTO_EX_dup *dup_func,CRYPTO_EX_free *free_func) + { + return CRYPTO_get_ex_new_index(CRYPTO_EX_INDEX_SSL_CTX, argl, argp, + new_func, dup_func, free_func); + } + +int SSL_CTX_set_ex_data(SSL_CTX *s,int idx,void *arg) + { + return(CRYPTO_set_ex_data(&s->ex_data,idx,arg)); + } + +void *SSL_CTX_get_ex_data(const SSL_CTX *s,int idx) + { + return(CRYPTO_get_ex_data(&s->ex_data,idx)); + } + +int ssl_ok(SSL *s) + { + return(1); + } + +X509_STORE *SSL_CTX_get_cert_store(const SSL_CTX *ctx) + { + return(ctx->cert_store); + } + +void SSL_CTX_set_cert_store(SSL_CTX *ctx,X509_STORE *store) + { + if (ctx->cert_store != NULL) + X509_STORE_free(ctx->cert_store); + ctx->cert_store=store; + } + +int SSL_want(const SSL *s) + { + return(s->rwstate); + } + +/*! + * \brief Set the callback for generating temporary RSA keys. + * \param ctx the SSL context. + * \param cb the callback + */ + +#ifndef OPENSSL_NO_RSA +void SSL_CTX_set_tmp_rsa_callback(SSL_CTX *ctx,RSA *(*cb)(SSL *ssl, + int is_export, + int keylength)) + { + SSL_CTX_callback_ctrl(ctx,SSL_CTRL_SET_TMP_RSA_CB,(void (*)(void))cb); + } + +void SSL_set_tmp_rsa_callback(SSL *ssl,RSA *(*cb)(SSL *ssl, + int is_export, + int keylength)) + { + SSL_callback_ctrl(ssl,SSL_CTRL_SET_TMP_RSA_CB,(void (*)(void))cb); + } +#endif + +#ifdef DOXYGEN +/*! + * \brief The RSA temporary key callback function. + * \param ssl the SSL session. + * \param is_export \c TRUE if the temp RSA key is for an export ciphersuite. + * \param keylength if \c is_export is \c TRUE, then \c keylength is the size + * of the required key in bits. + * \return the temporary RSA key. + * \sa SSL_CTX_set_tmp_rsa_callback, SSL_set_tmp_rsa_callback + */ + +RSA *cb(SSL *ssl,int is_export,int keylength) + {} +#endif + +/*! + * \brief Set the callback for generating temporary DH keys. + * \param ctx the SSL context. + * \param dh the callback + */ + +#ifndef OPENSSL_NO_DH +void SSL_CTX_set_tmp_dh_callback(SSL_CTX *ctx,DH *(*dh)(SSL *ssl,int is_export, + int keylength)) + { + SSL_CTX_callback_ctrl(ctx,SSL_CTRL_SET_TMP_DH_CB,(void (*)(void))dh); + } + +void SSL_set_tmp_dh_callback(SSL *ssl,DH *(*dh)(SSL *ssl,int is_export, + int keylength)) + { + SSL_callback_ctrl(ssl,SSL_CTRL_SET_TMP_DH_CB,(void (*)(void))dh); + } +#endif + +#ifndef OPENSSL_NO_ECDH +void SSL_CTX_set_tmp_ecdh_callback(SSL_CTX *ctx,EC_KEY *(*ecdh)(SSL *ssl,int is_export, + int keylength)) + { + SSL_CTX_callback_ctrl(ctx,SSL_CTRL_SET_TMP_ECDH_CB,(void (*)(void))ecdh); + } + +void SSL_set_tmp_ecdh_callback(SSL *ssl,EC_KEY *(*ecdh)(SSL *ssl,int is_export, + int keylength)) + { + SSL_callback_ctrl(ssl,SSL_CTRL_SET_TMP_ECDH_CB,(void (*)(void))ecdh); + } +#endif + +#ifndef OPENSSL_NO_PSK +int SSL_CTX_use_psk_identity_hint(SSL_CTX *ctx, const char *identity_hint) + { + if (identity_hint != NULL && strlen(identity_hint) > PSK_MAX_IDENTITY_LEN) + { + SSLerr(SSL_F_SSL_CTX_USE_PSK_IDENTITY_HINT, SSL_R_DATA_LENGTH_TOO_LONG); + return 0; + } + if (ctx->psk_identity_hint != NULL) + OPENSSL_free(ctx->psk_identity_hint); + if (identity_hint != NULL) + { + ctx->psk_identity_hint = BUF_strdup(identity_hint); + if (ctx->psk_identity_hint == NULL) + return 0; + } + else + ctx->psk_identity_hint = NULL; + return 1; + } + +int SSL_use_psk_identity_hint(SSL *s, const char *identity_hint) + { + if (s == NULL) + return 0; + + if (s->session == NULL) + return 1; /* session not created yet, ignored */ + + if (identity_hint != NULL && strlen(identity_hint) > PSK_MAX_IDENTITY_LEN) + { + SSLerr(SSL_F_SSL_USE_PSK_IDENTITY_HINT, SSL_R_DATA_LENGTH_TOO_LONG); + return 0; + } + if (s->session->psk_identity_hint != NULL) + OPENSSL_free(s->session->psk_identity_hint); + if (identity_hint != NULL) + { + s->session->psk_identity_hint = BUF_strdup(identity_hint); + if (s->session->psk_identity_hint == NULL) + return 0; + } + else + s->session->psk_identity_hint = NULL; + return 1; + } + +const char *SSL_get_psk_identity_hint(const SSL *s) + { + if (s == NULL || s->session == NULL) + return NULL; + return(s->session->psk_identity_hint); + } + +const char *SSL_get_psk_identity(const SSL *s) + { + if (s == NULL || s->session == NULL) + return NULL; + return(s->session->psk_identity); + } + +void SSL_set_psk_client_callback(SSL *s, + unsigned int (*cb)(SSL *ssl, const char *hint, + char *identity, unsigned int max_identity_len, unsigned char *psk, + unsigned int max_psk_len)) + { + s->psk_client_callback = cb; + } + +void SSL_CTX_set_psk_client_callback(SSL_CTX *ctx, + unsigned int (*cb)(SSL *ssl, const char *hint, + char *identity, unsigned int max_identity_len, unsigned char *psk, + unsigned int max_psk_len)) + { + ctx->psk_client_callback = cb; + } + +void SSL_set_psk_server_callback(SSL *s, + unsigned int (*cb)(SSL *ssl, const char *identity, + unsigned char *psk, unsigned int max_psk_len)) + { + s->psk_server_callback = cb; + } + +void SSL_CTX_set_psk_server_callback(SSL_CTX *ctx, + unsigned int (*cb)(SSL *ssl, const char *identity, + unsigned char *psk, unsigned int max_psk_len)) + { + ctx->psk_server_callback = cb; + } +#endif + +void SSL_CTX_set_msg_callback(SSL_CTX *ctx, void (*cb)(int write_p, int version, int content_type, const void *buf, size_t len, SSL *ssl, void *arg)) + { + SSL_CTX_callback_ctrl(ctx, SSL_CTRL_SET_MSG_CALLBACK, (void (*)(void))cb); + } +void SSL_set_msg_callback(SSL *ssl, void (*cb)(int write_p, int version, int content_type, const void *buf, size_t len, SSL *ssl, void *arg)) + { + SSL_callback_ctrl(ssl, SSL_CTRL_SET_MSG_CALLBACK, (void (*)(void))cb); + } + +int SSL_export_keying_material(SSL *s, unsigned char *out, size_t olen, + const char *label, size_t llen, const unsigned char *p, size_t plen, + int use_context) + { + if (s->version < TLS1_VERSION) + return -1; + + return s->method->ssl3_enc->export_keying_material(s, out, olen, label, + llen, p, plen, + use_context); + } + +int SSL_cutthrough_complete(const SSL *s) + { + return (!s->server && /* cutthrough only applies to clients */ + !s->hit && /* full-handshake */ + s->version >= SSL3_VERSION && + s->s3->in_read_app_data == 0 && /* cutthrough only applies to write() */ + (SSL_get_mode((SSL*)s) & SSL_MODE_HANDSHAKE_CUTTHROUGH) && /* cutthrough enabled */ + SSL_get_cipher_bits(s, NULL) >= 128 && /* strong cipher choosen */ + s->s3->previous_server_finished_len == 0 && /* not a renegotiation handshake */ + (s->state == SSL3_ST_CR_SESSION_TICKET_A || /* ready to write app-data*/ + s->state == SSL3_ST_CR_FINISHED_A)); + } + +/* Allocates new EVP_MD_CTX and sets pointer to it into given pointer + * vairable, freeing EVP_MD_CTX previously stored in that variable, if + * any. If EVP_MD pointer is passed, initializes ctx with this md + * Returns newly allocated ctx; + */ + +EVP_MD_CTX *ssl_replace_hash(EVP_MD_CTX **hash,const EVP_MD *md) +{ + ssl_clear_hash_ctx(hash); + *hash = EVP_MD_CTX_create(); + if (md) EVP_DigestInit_ex(*hash,md,NULL); + return *hash; +} +void ssl_clear_hash_ctx(EVP_MD_CTX **hash) +{ + + if (*hash) EVP_MD_CTX_destroy(*hash); + *hash=NULL; +} + +#if defined(_WINDLL) && defined(OPENSSL_SYS_WIN16) +#include "../crypto/bio/bss_file.c" +#endif + +IMPLEMENT_STACK_OF(SSL_CIPHER) +IMPLEMENT_STACK_OF(SSL_COMP) +IMPLEMENT_OBJ_BSEARCH_GLOBAL_CMP_FN(SSL_CIPHER, SSL_CIPHER, + ssl_cipher_id); + diff --git a/node-v0.8.14/deps/openssl/openssl/ssl/ssl_locl.h b/node-v0.8.14/deps/openssl/openssl/ssl/ssl_locl.h new file mode 100644 index 0000000..af607e6 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/ssl/ssl_locl.h @@ -0,0 +1,1093 @@ +/* ssl/ssl_locl.h */ +/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com) + * All rights reserved. + * + * This package is an SSL implementation written + * by Eric Young (eay@cryptsoft.com). + * The implementation was written so as to conform with Netscapes SSL. + * + * This library is free for commercial and non-commercial use as long as + * the following conditions are aheared to. The following conditions + * apply to all code found in this distribution, be it the RC4, RSA, + * lhash, DES, etc., code; not just the SSL code. The SSL documentation + * included with this distribution is covered by the same copyright terms + * except that the holder is Tim Hudson (tjh@cryptsoft.com). + * + * Copyright remains Eric Young's, and as such any Copyright notices in + * the code are not to be removed. + * If this package is used in a product, Eric Young should be given attribution + * as the author of the parts of the library used. + * This can be in the form of a textual message at program startup or + * in documentation (online or textual) provided with the package. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * "This product includes cryptographic software written by + * Eric Young (eay@cryptsoft.com)" + * The word 'cryptographic' can be left out if the rouines from the library + * being used are not cryptographic related :-). + * 4. If you include any Windows specific code (or a derivative thereof) from + * the apps directory (application code) you must include an acknowledgement: + * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)" + * + * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * + * The licence and distribution terms for any publically available version or + * derivative of this code cannot be changed. i.e. this code cannot simply be + * copied and put under another distribution licence + * [including the GNU Public Licence.] + */ +/* ==================================================================== + * Copyright (c) 1998-2007 The OpenSSL Project. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. All advertising materials mentioning features or use of this + * software must display the following acknowledgment: + * "This product includes software developed by the OpenSSL Project + * for use in the OpenSSL Toolkit. (http://www.openssl.org/)" + * + * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to + * endorse or promote products derived from this software without + * prior written permission. For written permission, please contact + * openssl-core@openssl.org. + * + * 5. Products derived from this software may not be called "OpenSSL" + * nor may "OpenSSL" appear in their names without prior written + * permission of the OpenSSL Project. + * + * 6. Redistributions of any form whatsoever must retain the following + * acknowledgment: + * "This product includes software developed by the OpenSSL Project + * for use in the OpenSSL Toolkit (http://www.openssl.org/)" + * + * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY + * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR + * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, + * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * ==================================================================== + * + * This product includes cryptographic software written by Eric Young + * (eay@cryptsoft.com). This product includes software written by Tim + * Hudson (tjh@cryptsoft.com). + * + */ +/* ==================================================================== + * Copyright 2002 Sun Microsystems, Inc. ALL RIGHTS RESERVED. + * ECC cipher suite support in OpenSSL originally developed by + * SUN MICROSYSTEMS, INC., and contributed to the OpenSSL project. + */ +/* ==================================================================== + * Copyright 2005 Nokia. All rights reserved. + * + * The portions of the attached software ("Contribution") is developed by + * Nokia Corporation and is licensed pursuant to the OpenSSL open source + * license. + * + * The Contribution, originally written by Mika Kousa and Pasi Eronen of + * Nokia Corporation, consists of the "PSK" (Pre-Shared Key) ciphersuites + * support (see RFC 4279) to OpenSSL. + * + * No patent licenses or other rights except those expressly stated in + * the OpenSSL open source license shall be deemed granted or received + * expressly, by implication, estoppel, or otherwise. + * + * No assurances are provided by Nokia that the Contribution does not + * infringe the patent or other intellectual property rights of any third + * party or that the license provides you with all the necessary rights + * to make use of the Contribution. + * + * THE SOFTWARE IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND. IN + * ADDITION TO THE DISCLAIMERS INCLUDED IN THE LICENSE, NOKIA + * SPECIFICALLY DISCLAIMS ANY LIABILITY FOR CLAIMS BROUGHT BY YOU OR ANY + * OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL PROPERTY RIGHTS OR + * OTHERWISE. + */ + +#ifndef HEADER_SSL_LOCL_H +#define HEADER_SSL_LOCL_H +#include +#include +#include +#include + +#include "e_os.h" + +#include +#ifndef OPENSSL_NO_COMP +#include +#endif +#include +#include +#ifndef OPENSSL_NO_RSA +#include +#endif +#ifndef OPENSSL_NO_DSA +#include +#endif +#include +#include +#include + +#ifdef OPENSSL_BUILD_SHLIBSSL +# undef OPENSSL_EXTERN +# define OPENSSL_EXTERN OPENSSL_EXPORT +#endif + +#define PKCS1_CHECK + +#define c2l(c,l) (l = ((unsigned long)(*((c)++))) , \ + l|=(((unsigned long)(*((c)++)))<< 8), \ + l|=(((unsigned long)(*((c)++)))<<16), \ + l|=(((unsigned long)(*((c)++)))<<24)) + +/* NOTE - c is not incremented as per c2l */ +#define c2ln(c,l1,l2,n) { \ + c+=n; \ + l1=l2=0; \ + switch (n) { \ + case 8: l2 =((unsigned long)(*(--(c))))<<24; \ + case 7: l2|=((unsigned long)(*(--(c))))<<16; \ + case 6: l2|=((unsigned long)(*(--(c))))<< 8; \ + case 5: l2|=((unsigned long)(*(--(c)))); \ + case 4: l1 =((unsigned long)(*(--(c))))<<24; \ + case 3: l1|=((unsigned long)(*(--(c))))<<16; \ + case 2: l1|=((unsigned long)(*(--(c))))<< 8; \ + case 1: l1|=((unsigned long)(*(--(c)))); \ + } \ + } + +#define l2c(l,c) (*((c)++)=(unsigned char)(((l) )&0xff), \ + *((c)++)=(unsigned char)(((l)>> 8)&0xff), \ + *((c)++)=(unsigned char)(((l)>>16)&0xff), \ + *((c)++)=(unsigned char)(((l)>>24)&0xff)) + +#define n2l(c,l) (l =((unsigned long)(*((c)++)))<<24, \ + l|=((unsigned long)(*((c)++)))<<16, \ + l|=((unsigned long)(*((c)++)))<< 8, \ + l|=((unsigned long)(*((c)++)))) + +#define l2n(l,c) (*((c)++)=(unsigned char)(((l)>>24)&0xff), \ + *((c)++)=(unsigned char)(((l)>>16)&0xff), \ + *((c)++)=(unsigned char)(((l)>> 8)&0xff), \ + *((c)++)=(unsigned char)(((l) )&0xff)) + +#define l2n6(l,c) (*((c)++)=(unsigned char)(((l)>>40)&0xff), \ + *((c)++)=(unsigned char)(((l)>>32)&0xff), \ + *((c)++)=(unsigned char)(((l)>>24)&0xff), \ + *((c)++)=(unsigned char)(((l)>>16)&0xff), \ + *((c)++)=(unsigned char)(((l)>> 8)&0xff), \ + *((c)++)=(unsigned char)(((l) )&0xff)) + +#define n2l6(c,l) (l =((BN_ULLONG)(*((c)++)))<<40, \ + l|=((BN_ULLONG)(*((c)++)))<<32, \ + l|=((BN_ULLONG)(*((c)++)))<<24, \ + l|=((BN_ULLONG)(*((c)++)))<<16, \ + l|=((BN_ULLONG)(*((c)++)))<< 8, \ + l|=((BN_ULLONG)(*((c)++)))) + +/* NOTE - c is not incremented as per l2c */ +#define l2cn(l1,l2,c,n) { \ + c+=n; \ + switch (n) { \ + case 8: *(--(c))=(unsigned char)(((l2)>>24)&0xff); \ + case 7: *(--(c))=(unsigned char)(((l2)>>16)&0xff); \ + case 6: *(--(c))=(unsigned char)(((l2)>> 8)&0xff); \ + case 5: *(--(c))=(unsigned char)(((l2) )&0xff); \ + case 4: *(--(c))=(unsigned char)(((l1)>>24)&0xff); \ + case 3: *(--(c))=(unsigned char)(((l1)>>16)&0xff); \ + case 2: *(--(c))=(unsigned char)(((l1)>> 8)&0xff); \ + case 1: *(--(c))=(unsigned char)(((l1) )&0xff); \ + } \ + } + +#define n2s(c,s) ((s=(((unsigned int)(c[0]))<< 8)| \ + (((unsigned int)(c[1])) )),c+=2) +#define s2n(s,c) ((c[0]=(unsigned char)(((s)>> 8)&0xff), \ + c[1]=(unsigned char)(((s) )&0xff)),c+=2) + +#define n2l3(c,l) ((l =(((unsigned long)(c[0]))<<16)| \ + (((unsigned long)(c[1]))<< 8)| \ + (((unsigned long)(c[2])) )),c+=3) + +#define l2n3(l,c) ((c[0]=(unsigned char)(((l)>>16)&0xff), \ + c[1]=(unsigned char)(((l)>> 8)&0xff), \ + c[2]=(unsigned char)(((l) )&0xff)),c+=3) + +/* LOCAL STUFF */ + +#define SSL_DECRYPT 0 +#define SSL_ENCRYPT 1 + +#define TWO_BYTE_BIT 0x80 +#define SEC_ESC_BIT 0x40 +#define TWO_BYTE_MASK 0x7fff +#define THREE_BYTE_MASK 0x3fff + +#define INC32(a) ((a)=((a)+1)&0xffffffffL) +#define DEC32(a) ((a)=((a)-1)&0xffffffffL) +#define MAX_MAC_SIZE 20 /* up from 16 for SSLv3 */ + +/* + * Define the Bitmasks for SSL_CIPHER.algorithms. + * This bits are used packed as dense as possible. If new methods/ciphers + * etc will be added, the bits a likely to change, so this information + * is for internal library use only, even though SSL_CIPHER.algorithms + * can be publicly accessed. + * Use the according functions for cipher management instead. + * + * The bit mask handling in the selection and sorting scheme in + * ssl_create_cipher_list() has only limited capabilities, reflecting + * that the different entities within are mutually exclusive: + * ONLY ONE BIT PER MASK CAN BE SET AT A TIME. + */ + +/* Bits for algorithm_mkey (key exchange algorithm) */ +#define SSL_kRSA 0x00000001L /* RSA key exchange */ +#define SSL_kDHr 0x00000002L /* DH cert, RSA CA cert */ /* no such ciphersuites supported! */ +#define SSL_kDHd 0x00000004L /* DH cert, DSA CA cert */ /* no such ciphersuite supported! */ +#define SSL_kEDH 0x00000008L /* tmp DH key no DH cert */ +#define SSL_kKRB5 0x00000010L /* Kerberos5 key exchange */ +#define SSL_kECDHr 0x00000020L /* ECDH cert, RSA CA cert */ +#define SSL_kECDHe 0x00000040L /* ECDH cert, ECDSA CA cert */ +#define SSL_kEECDH 0x00000080L /* ephemeral ECDH */ +#define SSL_kPSK 0x00000100L /* PSK */ +#define SSL_kGOST 0x00000200L /* GOST key exchange */ + +/* Bits for algorithm_auth (server authentication) */ +#define SSL_aRSA 0x00000001L /* RSA auth */ +#define SSL_aDSS 0x00000002L /* DSS auth */ +#define SSL_aNULL 0x00000004L /* no auth (i.e. use ADH or AECDH) */ +#define SSL_aDH 0x00000008L /* Fixed DH auth (kDHd or kDHr) */ /* no such ciphersuites supported! */ +#define SSL_aECDH 0x00000010L /* Fixed ECDH auth (kECDHe or kECDHr) */ +#define SSL_aKRB5 0x00000020L /* KRB5 auth */ +#define SSL_aECDSA 0x00000040L /* ECDSA auth*/ +#define SSL_aPSK 0x00000080L /* PSK auth */ +#define SSL_aGOST94 0x00000100L /* GOST R 34.10-94 signature auth */ +#define SSL_aGOST01 0x00000200L /* GOST R 34.10-2001 signature auth */ + + +/* Bits for algorithm_enc (symmetric encryption) */ +#define SSL_DES 0x00000001L +#define SSL_3DES 0x00000002L +#define SSL_RC4 0x00000004L +#define SSL_RC2 0x00000008L +#define SSL_IDEA 0x00000010L +#define SSL_eNULL 0x00000020L +#define SSL_AES128 0x00000040L +#define SSL_AES256 0x00000080L +#define SSL_CAMELLIA128 0x00000100L +#define SSL_CAMELLIA256 0x00000200L +#define SSL_eGOST2814789CNT 0x00000400L +#define SSL_SEED 0x00000800L + +#define SSL_AES (SSL_AES128|SSL_AES256) +#define SSL_CAMELLIA (SSL_CAMELLIA128|SSL_CAMELLIA256) + + +/* Bits for algorithm_mac (symmetric authentication) */ +#define SSL_MD5 0x00000001L +#define SSL_SHA1 0x00000002L +#define SSL_GOST94 0x00000004L +#define SSL_GOST89MAC 0x00000008L + +/* Bits for algorithm_ssl (protocol version) */ +#define SSL_SSLV2 0x00000001L +#define SSL_SSLV3 0x00000002L +#define SSL_TLSV1 SSL_SSLV3 /* for now */ + + +/* Bits for algorithm2 (handshake digests and other extra flags) */ + +#define SSL_HANDSHAKE_MAC_MD5 0x10 +#define SSL_HANDSHAKE_MAC_SHA 0x20 +#define SSL_HANDSHAKE_MAC_GOST94 0x40 +#define SSL_HANDSHAKE_MAC_DEFAULT (SSL_HANDSHAKE_MAC_MD5 | SSL_HANDSHAKE_MAC_SHA) + +/* When adding new digest in the ssl_ciph.c and increment SSM_MD_NUM_IDX + * make sure to update this constant too */ +#define SSL_MAX_DIGEST 4 + +#define TLS1_PRF_DGST_SHIFT 8 +#define TLS1_PRF_MD5 (SSL_HANDSHAKE_MAC_MD5 << TLS1_PRF_DGST_SHIFT) +#define TLS1_PRF_SHA1 (SSL_HANDSHAKE_MAC_SHA << TLS1_PRF_DGST_SHIFT) +#define TLS1_PRF_GOST94 (SSL_HANDSHAKE_MAC_GOST94 << TLS1_PRF_DGST_SHIFT) +#define TLS1_PRF (TLS1_PRF_MD5 | TLS1_PRF_SHA1) + +/* Stream MAC for GOST ciphersuites from cryptopro draft + * (currently this also goes into algorithm2) */ +#define TLS1_STREAM_MAC 0x04 + + + +/* + * Export and cipher strength information. For each cipher we have to decide + * whether it is exportable or not. This information is likely to change + * over time, since the export control rules are no static technical issue. + * + * Independent of the export flag the cipher strength is sorted into classes. + * SSL_EXP40 was denoting the 40bit US export limit of past times, which now + * is at 56bit (SSL_EXP56). If the exportable cipher class is going to change + * again (eg. to 64bit) the use of "SSL_EXP*" becomes blurred even more, + * since SSL_EXP64 could be similar to SSL_LOW. + * For this reason SSL_MICRO and SSL_MINI macros are included to widen the + * namespace of SSL_LOW-SSL_HIGH to lower values. As development of speed + * and ciphers goes, another extension to SSL_SUPER and/or SSL_ULTRA would + * be possible. + */ +#define SSL_EXP_MASK 0x00000003L +#define SSL_STRONG_MASK 0x000001fcL + +#define SSL_NOT_EXP 0x00000001L +#define SSL_EXPORT 0x00000002L + +#define SSL_STRONG_NONE 0x00000004L +#define SSL_EXP40 0x00000008L +#define SSL_MICRO (SSL_EXP40) +#define SSL_EXP56 0x00000010L +#define SSL_MINI (SSL_EXP56) +#define SSL_LOW 0x00000020L +#define SSL_MEDIUM 0x00000040L +#define SSL_HIGH 0x00000080L +#define SSL_FIPS 0x00000100L + +/* we have used 000001ff - 23 bits left to go */ + +/* + * Macros to check the export status and cipher strength for export ciphers. + * Even though the macros for EXPORT and EXPORT40/56 have similar names, + * their meaning is different: + * *_EXPORT macros check the 'exportable' status. + * *_EXPORT40/56 macros are used to check whether a certain cipher strength + * is given. + * Since the SSL_IS_EXPORT* and SSL_EXPORT* macros depend on the correct + * algorithm structure element to be passed (algorithms, algo_strength) and no + * typechecking can be done as they are all of type unsigned long, their + * direct usage is discouraged. + * Use the SSL_C_* macros instead. + */ +#define SSL_IS_EXPORT(a) ((a)&SSL_EXPORT) +#define SSL_IS_EXPORT56(a) ((a)&SSL_EXP56) +#define SSL_IS_EXPORT40(a) ((a)&SSL_EXP40) +#define SSL_C_IS_EXPORT(c) SSL_IS_EXPORT((c)->algo_strength) +#define SSL_C_IS_EXPORT56(c) SSL_IS_EXPORT56((c)->algo_strength) +#define SSL_C_IS_EXPORT40(c) SSL_IS_EXPORT40((c)->algo_strength) + +#define SSL_EXPORT_KEYLENGTH(a,s) (SSL_IS_EXPORT40(s) ? 5 : \ + (a) == SSL_DES ? 8 : 7) +#define SSL_EXPORT_PKEYLENGTH(a) (SSL_IS_EXPORT40(a) ? 512 : 1024) +#define SSL_C_EXPORT_KEYLENGTH(c) SSL_EXPORT_KEYLENGTH((c)->algorithm_enc, \ + (c)->algo_strength) +#define SSL_C_EXPORT_PKEYLENGTH(c) SSL_EXPORT_PKEYLENGTH((c)->algo_strength) + + + + +/* Mostly for SSLv3 */ +#define SSL_PKEY_RSA_ENC 0 +#define SSL_PKEY_RSA_SIGN 1 +#define SSL_PKEY_DSA_SIGN 2 +#define SSL_PKEY_DH_RSA 3 +#define SSL_PKEY_DH_DSA 4 +#define SSL_PKEY_ECC 5 +#define SSL_PKEY_GOST94 6 +#define SSL_PKEY_GOST01 7 +#define SSL_PKEY_NUM 8 + +/* SSL_kRSA <- RSA_ENC | (RSA_TMP & RSA_SIGN) | + * <- (EXPORT & (RSA_ENC | RSA_TMP) & RSA_SIGN) + * SSL_kDH <- DH_ENC & (RSA_ENC | RSA_SIGN | DSA_SIGN) + * SSL_kEDH <- RSA_ENC | RSA_SIGN | DSA_SIGN + * SSL_aRSA <- RSA_ENC | RSA_SIGN + * SSL_aDSS <- DSA_SIGN + */ + +/* +#define CERT_INVALID 0 +#define CERT_PUBLIC_KEY 1 +#define CERT_PRIVATE_KEY 2 +*/ + +#ifndef OPENSSL_NO_EC +/* From ECC-TLS draft, used in encoding the curve type in + * ECParameters + */ +#define EXPLICIT_PRIME_CURVE_TYPE 1 +#define EXPLICIT_CHAR2_CURVE_TYPE 2 +#define NAMED_CURVE_TYPE 3 +#endif /* OPENSSL_NO_EC */ + +typedef struct cert_pkey_st + { + X509 *x509; + STACK_OF(X509) *cert_chain; + EVP_PKEY *privatekey; + } CERT_PKEY; + +typedef struct cert_st + { + /* Current active set */ + CERT_PKEY *key; /* ALWAYS points to an element of the pkeys array + * Probably it would make more sense to store + * an index, not a pointer. */ + + /* The following masks are for the key and auth + * algorithms that are supported by the certs below */ + int valid; + unsigned long mask_k; + unsigned long mask_a; + unsigned long export_mask_k; + unsigned long export_mask_a; +#ifndef OPENSSL_NO_RSA + RSA *rsa_tmp; + RSA *(*rsa_tmp_cb)(SSL *ssl,int is_export,int keysize); +#endif +#ifndef OPENSSL_NO_DH + DH *dh_tmp; + DH *(*dh_tmp_cb)(SSL *ssl,int is_export,int keysize); +#endif +#ifndef OPENSSL_NO_ECDH + EC_KEY *ecdh_tmp; + /* Callback for generating ephemeral ECDH keys */ + EC_KEY *(*ecdh_tmp_cb)(SSL *ssl,int is_export,int keysize); +#endif + + CERT_PKEY pkeys[SSL_PKEY_NUM]; + + int references; /* >1 only if SSL_copy_session_id is used */ + } CERT; + + +typedef struct sess_cert_st + { + STACK_OF(X509) *cert_chain; /* as received from peer (not for SSL2) */ + + /* The 'peer_...' members are used only by clients. */ + int peer_cert_type; + + CERT_PKEY *peer_key; /* points to an element of peer_pkeys (never NULL!) */ + CERT_PKEY peer_pkeys[SSL_PKEY_NUM]; + /* Obviously we don't have the private keys of these, + * so maybe we shouldn't even use the CERT_PKEY type here. */ + +#ifndef OPENSSL_NO_RSA + RSA *peer_rsa_tmp; /* not used for SSL 2 */ +#endif +#ifndef OPENSSL_NO_DH + DH *peer_dh_tmp; /* not used for SSL 2 */ +#endif +#ifndef OPENSSL_NO_ECDH + EC_KEY *peer_ecdh_tmp; +#endif + + int references; /* actually always 1 at the moment */ + } SESS_CERT; + + +/*#define MAC_DEBUG */ + +/*#define ERR_DEBUG */ +/*#define ABORT_DEBUG */ +/*#define PKT_DEBUG 1 */ +/*#define DES_DEBUG */ +/*#define DES_OFB_DEBUG */ +/*#define SSL_DEBUG */ +/*#define RSA_DEBUG */ +/*#define IDEA_DEBUG */ + +#define FP_ICC (int (*)(const void *,const void *)) +#define ssl_put_cipher_by_char(ssl,ciph,ptr) \ + ((ssl)->method->put_cipher_by_char((ciph),(ptr))) +#define ssl_get_cipher_by_char(ssl,ptr) \ + ((ssl)->method->get_cipher_by_char(ptr)) + +/* This is for the SSLv3/TLSv1.0 differences in crypto/hash stuff + * It is a bit of a mess of functions, but hell, think of it as + * an opaque structure :-) */ +typedef struct ssl3_enc_method + { + int (*enc)(SSL *, int); + int (*mac)(SSL *, unsigned char *, int); + int (*setup_key_block)(SSL *); + int (*generate_master_secret)(SSL *, unsigned char *, unsigned char *, int); + int (*change_cipher_state)(SSL *, int); + int (*final_finish_mac)(SSL *, const char *, int, unsigned char *); + int finish_mac_length; + int (*cert_verify_mac)(SSL *, int, unsigned char *); + const char *client_finished_label; + int client_finished_label_len; + const char *server_finished_label; + int server_finished_label_len; + int (*alert_value)(int); + int (*export_keying_material)(SSL *, unsigned char *, size_t, + const char *, size_t, + const unsigned char *, size_t, + int use_context); + } SSL3_ENC_METHOD; + +#ifndef OPENSSL_NO_COMP +/* Used for holding the relevant compression methods loaded into SSL_CTX */ +typedef struct ssl3_comp_st + { + int comp_id; /* The identifier byte for this compression type */ + char *name; /* Text name used for the compression type */ + COMP_METHOD *method; /* The method :-) */ + } SSL3_COMP; +#endif + +#ifndef OPENSSL_NO_BUF_FREELISTS +typedef struct ssl3_buf_freelist_st + { + size_t chunklen; + unsigned int len; + struct ssl3_buf_freelist_entry_st *head; + } SSL3_BUF_FREELIST; + +typedef struct ssl3_buf_freelist_entry_st + { + struct ssl3_buf_freelist_entry_st *next; + } SSL3_BUF_FREELIST_ENTRY; +#endif + +extern SSL3_ENC_METHOD ssl3_undef_enc_method; +OPENSSL_EXTERN const SSL_CIPHER ssl2_ciphers[]; +OPENSSL_EXTERN SSL_CIPHER ssl3_ciphers[]; + + +SSL_METHOD *ssl_bad_method(int ver); + +extern SSL3_ENC_METHOD TLSv1_enc_data; +extern SSL3_ENC_METHOD SSLv3_enc_data; +extern SSL3_ENC_METHOD DTLSv1_enc_data; + +#define IMPLEMENT_tls1_meth_func(func_name, s_accept, s_connect, s_get_meth) \ +const SSL_METHOD *func_name(void) \ + { \ + static const SSL_METHOD func_name##_data= { \ + TLS1_VERSION, \ + tls1_new, \ + tls1_clear, \ + tls1_free, \ + s_accept, \ + s_connect, \ + ssl3_read, \ + ssl3_peek, \ + ssl3_write, \ + ssl3_shutdown, \ + ssl3_renegotiate, \ + ssl3_renegotiate_check, \ + ssl3_get_message, \ + ssl3_read_bytes, \ + ssl3_write_bytes, \ + ssl3_dispatch_alert, \ + ssl3_ctrl, \ + ssl3_ctx_ctrl, \ + ssl3_get_cipher_by_char, \ + ssl3_put_cipher_by_char, \ + ssl3_pending, \ + ssl3_num_ciphers, \ + ssl3_get_cipher, \ + s_get_meth, \ + tls1_default_timeout, \ + &TLSv1_enc_data, \ + ssl_undefined_void_function, \ + ssl3_callback_ctrl, \ + ssl3_ctx_callback_ctrl, \ + }; \ + return &func_name##_data; \ + } + +#define IMPLEMENT_ssl3_meth_func(func_name, s_accept, s_connect, s_get_meth) \ +const SSL_METHOD *func_name(void) \ + { \ + static const SSL_METHOD func_name##_data= { \ + SSL3_VERSION, \ + ssl3_new, \ + ssl3_clear, \ + ssl3_free, \ + s_accept, \ + s_connect, \ + ssl3_read, \ + ssl3_peek, \ + ssl3_write, \ + ssl3_shutdown, \ + ssl3_renegotiate, \ + ssl3_renegotiate_check, \ + ssl3_get_message, \ + ssl3_read_bytes, \ + ssl3_write_bytes, \ + ssl3_dispatch_alert, \ + ssl3_ctrl, \ + ssl3_ctx_ctrl, \ + ssl3_get_cipher_by_char, \ + ssl3_put_cipher_by_char, \ + ssl3_pending, \ + ssl3_num_ciphers, \ + ssl3_get_cipher, \ + s_get_meth, \ + ssl3_default_timeout, \ + &SSLv3_enc_data, \ + ssl_undefined_void_function, \ + ssl3_callback_ctrl, \ + ssl3_ctx_callback_ctrl, \ + }; \ + return &func_name##_data; \ + } + +#define IMPLEMENT_ssl23_meth_func(func_name, s_accept, s_connect, s_get_meth) \ +const SSL_METHOD *func_name(void) \ + { \ + static const SSL_METHOD func_name##_data= { \ + TLS1_VERSION, \ + tls1_new, \ + tls1_clear, \ + tls1_free, \ + s_accept, \ + s_connect, \ + ssl23_read, \ + ssl23_peek, \ + ssl23_write, \ + ssl_undefined_function, \ + ssl_undefined_function, \ + ssl_ok, \ + ssl3_get_message, \ + ssl3_read_bytes, \ + ssl3_write_bytes, \ + ssl3_dispatch_alert, \ + ssl3_ctrl, \ + ssl3_ctx_ctrl, \ + ssl23_get_cipher_by_char, \ + ssl23_put_cipher_by_char, \ + ssl_undefined_const_function, \ + ssl23_num_ciphers, \ + ssl23_get_cipher, \ + s_get_meth, \ + ssl23_default_timeout, \ + &ssl3_undef_enc_method, \ + ssl_undefined_void_function, \ + ssl3_callback_ctrl, \ + ssl3_ctx_callback_ctrl, \ + }; \ + return &func_name##_data; \ + } + +#define IMPLEMENT_ssl2_meth_func(func_name, s_accept, s_connect, s_get_meth) \ +const SSL_METHOD *func_name(void) \ + { \ + static const SSL_METHOD func_name##_data= { \ + SSL2_VERSION, \ + ssl2_new, /* local */ \ + ssl2_clear, /* local */ \ + ssl2_free, /* local */ \ + s_accept, \ + s_connect, \ + ssl2_read, \ + ssl2_peek, \ + ssl2_write, \ + ssl2_shutdown, \ + ssl_ok, /* NULL - renegotiate */ \ + ssl_ok, /* NULL - check renegotiate */ \ + NULL, /* NULL - ssl_get_message */ \ + NULL, /* NULL - ssl_get_record */ \ + NULL, /* NULL - ssl_write_bytes */ \ + NULL, /* NULL - dispatch_alert */ \ + ssl2_ctrl, /* local */ \ + ssl2_ctx_ctrl, /* local */ \ + ssl2_get_cipher_by_char, \ + ssl2_put_cipher_by_char, \ + ssl2_pending, \ + ssl2_num_ciphers, \ + ssl2_get_cipher, \ + s_get_meth, \ + ssl2_default_timeout, \ + &ssl3_undef_enc_method, \ + ssl_undefined_void_function, \ + ssl2_callback_ctrl, /* local */ \ + ssl2_ctx_callback_ctrl, /* local */ \ + }; \ + return &func_name##_data; \ + } + +#define IMPLEMENT_dtls1_meth_func(func_name, s_accept, s_connect, s_get_meth) \ +const SSL_METHOD *func_name(void) \ + { \ + static const SSL_METHOD func_name##_data= { \ + DTLS1_VERSION, \ + dtls1_new, \ + dtls1_clear, \ + dtls1_free, \ + s_accept, \ + s_connect, \ + ssl3_read, \ + ssl3_peek, \ + ssl3_write, \ + ssl3_shutdown, \ + ssl3_renegotiate, \ + ssl3_renegotiate_check, \ + dtls1_get_message, \ + dtls1_read_bytes, \ + dtls1_write_app_data_bytes, \ + dtls1_dispatch_alert, \ + dtls1_ctrl, \ + ssl3_ctx_ctrl, \ + ssl3_get_cipher_by_char, \ + ssl3_put_cipher_by_char, \ + ssl3_pending, \ + ssl3_num_ciphers, \ + dtls1_get_cipher, \ + s_get_meth, \ + dtls1_default_timeout, \ + &DTLSv1_enc_data, \ + ssl_undefined_void_function, \ + ssl3_callback_ctrl, \ + ssl3_ctx_callback_ctrl, \ + }; \ + return &func_name##_data; \ + } + +void ssl_clear_cipher_ctx(SSL *s); +int ssl_clear_bad_session(SSL *s); +CERT *ssl_cert_new(void); +CERT *ssl_cert_dup(CERT *cert); +int ssl_cert_inst(CERT **o); +void ssl_cert_free(CERT *c); +SESS_CERT *ssl_sess_cert_new(void); +void ssl_sess_cert_free(SESS_CERT *sc); +int ssl_set_peer_cert_type(SESS_CERT *c, int type); +int ssl_get_new_session(SSL *s, int session); +int ssl_get_prev_session(SSL *s, unsigned char *session,int len, const unsigned char *limit); +int ssl_cipher_id_cmp(const SSL_CIPHER *a,const SSL_CIPHER *b); +DECLARE_OBJ_BSEARCH_GLOBAL_CMP_FN(SSL_CIPHER, SSL_CIPHER, + ssl_cipher_id); +int ssl_cipher_ptr_id_cmp(const SSL_CIPHER * const *ap, + const SSL_CIPHER * const *bp); +STACK_OF(SSL_CIPHER) *ssl_bytes_to_cipher_list(SSL *s,unsigned char *p,int num, + STACK_OF(SSL_CIPHER) **skp); +int ssl_cipher_list_to_bytes(SSL *s,STACK_OF(SSL_CIPHER) *sk,unsigned char *p, + int (*put_cb)(const SSL_CIPHER *, unsigned char *)); +STACK_OF(SSL_CIPHER) *ssl_create_cipher_list(const SSL_METHOD *meth, + STACK_OF(SSL_CIPHER) **pref, + STACK_OF(SSL_CIPHER) **sorted, + const char *rule_str); +void ssl_update_cache(SSL *s, int mode); +int ssl_cipher_get_evp(const SSL_SESSION *s,const EVP_CIPHER **enc, + const EVP_MD **md,int *mac_pkey_type,int *mac_secret_size, SSL_COMP **comp); +int ssl_get_handshake_digest(int i,long *mask,const EVP_MD **md); +int ssl_verify_cert_chain(SSL *s,STACK_OF(X509) *sk); +int ssl_undefined_function(SSL *s); +int ssl_undefined_void_function(void); +int ssl_undefined_const_function(const SSL *s); +X509 *ssl_get_server_send_cert(SSL *); +EVP_PKEY *ssl_get_sign_pkey(SSL *,const SSL_CIPHER *); +int ssl_cert_type(X509 *x,EVP_PKEY *pkey); +void ssl_set_cert_masks(CERT *c, const SSL_CIPHER *cipher); +STACK_OF(SSL_CIPHER) *ssl_get_ciphers_by_id(SSL *s); +int ssl_verify_alarm_type(long type); +void ssl_load_ciphers(void); + +int ssl2_enc_init(SSL *s, int client); +int ssl2_generate_key_material(SSL *s); +void ssl2_enc(SSL *s,int send_data); +void ssl2_mac(SSL *s,unsigned char *mac,int send_data); +const SSL_CIPHER *ssl2_get_cipher_by_char(const unsigned char *p); +int ssl2_put_cipher_by_char(const SSL_CIPHER *c,unsigned char *p); +int ssl2_part_read(SSL *s, unsigned long f, int i); +int ssl2_do_write(SSL *s); +int ssl2_set_certificate(SSL *s, int type, int len, const unsigned char *data); +void ssl2_return_error(SSL *s,int reason); +void ssl2_write_error(SSL *s); +int ssl2_num_ciphers(void); +const SSL_CIPHER *ssl2_get_cipher(unsigned int u); +int ssl2_new(SSL *s); +void ssl2_free(SSL *s); +int ssl2_accept(SSL *s); +int ssl2_connect(SSL *s); +int ssl2_read(SSL *s, void *buf, int len); +int ssl2_peek(SSL *s, void *buf, int len); +int ssl2_write(SSL *s, const void *buf, int len); +int ssl2_shutdown(SSL *s); +void ssl2_clear(SSL *s); +long ssl2_ctrl(SSL *s,int cmd, long larg, void *parg); +long ssl2_ctx_ctrl(SSL_CTX *s,int cmd, long larg, void *parg); +long ssl2_callback_ctrl(SSL *s,int cmd, void (*fp)(void)); +long ssl2_ctx_callback_ctrl(SSL_CTX *s,int cmd, void (*fp)(void)); +int ssl2_pending(const SSL *s); +long ssl2_default_timeout(void ); + +const SSL_CIPHER *ssl3_get_cipher_by_char(const unsigned char *p); +int ssl3_put_cipher_by_char(const SSL_CIPHER *c,unsigned char *p); +void ssl3_init_finished_mac(SSL *s); +int ssl3_send_server_certificate(SSL *s); +int ssl3_send_newsession_ticket(SSL *s); +int ssl3_send_cert_status(SSL *s); +int ssl3_get_finished(SSL *s,int state_a,int state_b); +int ssl3_setup_key_block(SSL *s); +int ssl3_send_change_cipher_spec(SSL *s,int state_a,int state_b); +int ssl3_change_cipher_state(SSL *s,int which); +void ssl3_cleanup_key_block(SSL *s); +int ssl3_do_write(SSL *s,int type); +int ssl3_send_alert(SSL *s,int level, int desc); +int ssl3_generate_master_secret(SSL *s, unsigned char *out, + unsigned char *p, int len); +int ssl3_get_req_cert_type(SSL *s,unsigned char *p); +long ssl3_get_message(SSL *s, int st1, int stn, int mt, long max, int *ok); +int ssl3_send_finished(SSL *s, int a, int b, const char *sender,int slen); +int ssl3_num_ciphers(void); +const SSL_CIPHER *ssl3_get_cipher(unsigned int u); +int ssl3_renegotiate(SSL *ssl); +int ssl3_renegotiate_check(SSL *ssl); +int ssl3_dispatch_alert(SSL *s); +int ssl3_read_bytes(SSL *s, int type, unsigned char *buf, int len, int peek); +int ssl3_write_bytes(SSL *s, int type, const void *buf, int len); +int ssl3_final_finish_mac(SSL *s, const char *sender, int slen,unsigned char *p); +int ssl3_cert_verify_mac(SSL *s, int md_nid, unsigned char *p); +void ssl3_finish_mac(SSL *s, const unsigned char *buf, int len); +int ssl3_enc(SSL *s, int send_data); +int n_ssl3_mac(SSL *ssl, unsigned char *md, int send_data); +void ssl3_free_digest_list(SSL *s); +unsigned long ssl3_output_cert_chain(SSL *s, X509 *x); +SSL_CIPHER *ssl3_choose_cipher(SSL *ssl,STACK_OF(SSL_CIPHER) *clnt, + STACK_OF(SSL_CIPHER) *srvr); +int ssl3_setup_buffers(SSL *s); +int ssl3_setup_read_buffer(SSL *s); +int ssl3_setup_write_buffer(SSL *s); +int ssl3_release_read_buffer(SSL *s); +int ssl3_release_write_buffer(SSL *s); +int ssl3_digest_cached_records(SSL *s); +int ssl3_new(SSL *s); +void ssl3_free(SSL *s); +int ssl3_accept(SSL *s); +int ssl3_connect(SSL *s); +int ssl3_read(SSL *s, void *buf, int len); +int ssl3_peek(SSL *s, void *buf, int len); +int ssl3_write(SSL *s, const void *buf, int len); +int ssl3_shutdown(SSL *s); +void ssl3_clear(SSL *s); +long ssl3_ctrl(SSL *s,int cmd, long larg, void *parg); +long ssl3_ctx_ctrl(SSL_CTX *s,int cmd, long larg, void *parg); +long ssl3_callback_ctrl(SSL *s,int cmd, void (*fp)(void)); +long ssl3_ctx_callback_ctrl(SSL_CTX *s,int cmd, void (*fp)(void)); +int ssl3_pending(const SSL *s); + +void ssl3_record_sequence_update(unsigned char *seq); +int ssl3_do_change_cipher_spec(SSL *ssl); +long ssl3_default_timeout(void ); + +int ssl23_num_ciphers(void ); +const SSL_CIPHER *ssl23_get_cipher(unsigned int u); +int ssl23_read(SSL *s, void *buf, int len); +int ssl23_peek(SSL *s, void *buf, int len); +int ssl23_write(SSL *s, const void *buf, int len); +int ssl23_put_cipher_by_char(const SSL_CIPHER *c, unsigned char *p); +const SSL_CIPHER *ssl23_get_cipher_by_char(const unsigned char *p); +long ssl23_default_timeout(void ); + +long tls1_default_timeout(void); +int dtls1_do_write(SSL *s,int type); +int ssl3_read_n(SSL *s, int n, int max, int extend); +int dtls1_read_bytes(SSL *s, int type, unsigned char *buf, int len, int peek); +int ssl3_do_compress(SSL *ssl); +int ssl3_do_uncompress(SSL *ssl); +int ssl3_write_pending(SSL *s, int type, const unsigned char *buf, + unsigned int len); +unsigned char *dtls1_set_message_header(SSL *s, + unsigned char *p, unsigned char mt, unsigned long len, + unsigned long frag_off, unsigned long frag_len); + +int dtls1_write_app_data_bytes(SSL *s, int type, const void *buf, int len); +int dtls1_write_bytes(SSL *s, int type, const void *buf, int len); + +int dtls1_send_change_cipher_spec(SSL *s, int a, int b); +int dtls1_send_finished(SSL *s, int a, int b, const char *sender, int slen); +unsigned long dtls1_output_cert_chain(SSL *s, X509 *x); +int dtls1_read_failed(SSL *s, int code); +int dtls1_buffer_message(SSL *s, int ccs); +int dtls1_retransmit_message(SSL *s, unsigned short seq, + unsigned long frag_off, int *found); +int dtls1_get_queue_priority(unsigned short seq, int is_ccs); +int dtls1_retransmit_buffered_messages(SSL *s); +void dtls1_clear_record_buffer(SSL *s); +void dtls1_get_message_header(unsigned char *data, struct hm_header_st *msg_hdr); +void dtls1_get_ccs_header(unsigned char *data, struct ccs_header_st *ccs_hdr); +void dtls1_reset_seq_numbers(SSL *s, int rw); +long dtls1_default_timeout(void); +struct timeval* dtls1_get_timeout(SSL *s, struct timeval* timeleft); +int dtls1_handle_timeout(SSL *s); +const SSL_CIPHER *dtls1_get_cipher(unsigned int u); +void dtls1_start_timer(SSL *s); +void dtls1_stop_timer(SSL *s); +int dtls1_is_timer_expired(SSL *s); +void dtls1_double_timeout(SSL *s); +int dtls1_send_newsession_ticket(SSL *s); +unsigned int dtls1_min_mtu(void); + +/* some client-only functions */ +int ssl3_client_hello(SSL *s); +int ssl3_get_server_hello(SSL *s); +int ssl3_get_certificate_request(SSL *s); +int ssl3_get_new_session_ticket(SSL *s); +int ssl3_get_cert_status(SSL *s); +int ssl3_get_server_done(SSL *s); +int ssl3_send_client_verify(SSL *s); +int ssl3_send_client_certificate(SSL *s); +int ssl_do_client_cert_cb(SSL *s, X509 **px509, EVP_PKEY **ppkey); +int ssl3_send_client_key_exchange(SSL *s); +int ssl3_get_key_exchange(SSL *s); +int ssl3_get_server_certificate(SSL *s); +int ssl3_check_cert_and_algorithm(SSL *s); +#ifndef OPENSSL_NO_TLSEXT +int ssl3_check_finished(SSL *s); +# ifndef OPENSSL_NO_NEXTPROTONEG +int ssl3_send_next_proto(SSL *s); +# endif +#endif + +int dtls1_client_hello(SSL *s); +int dtls1_send_client_certificate(SSL *s); +int dtls1_send_client_key_exchange(SSL *s); +int dtls1_send_client_verify(SSL *s); + +/* some server-only functions */ +int ssl3_get_client_hello(SSL *s); +int ssl3_send_server_hello(SSL *s); +int ssl3_send_hello_request(SSL *s); +int ssl3_send_server_key_exchange(SSL *s); +int ssl3_send_certificate_request(SSL *s); +int ssl3_send_server_done(SSL *s); +int ssl3_check_client_hello(SSL *s); +int ssl3_get_client_certificate(SSL *s); +int ssl3_get_client_key_exchange(SSL *s); +int ssl3_get_cert_verify(SSL *s); +#ifndef OPENSSL_NO_NEXTPROTONEG +int ssl3_get_next_proto(SSL *s); +#endif + +int dtls1_send_hello_request(SSL *s); +int dtls1_send_server_hello(SSL *s); +int dtls1_send_server_certificate(SSL *s); +int dtls1_send_server_key_exchange(SSL *s); +int dtls1_send_certificate_request(SSL *s); +int dtls1_send_server_done(SSL *s); + + + +int ssl23_accept(SSL *s); +int ssl23_connect(SSL *s); +int ssl23_read_bytes(SSL *s, int n); +int ssl23_write_bytes(SSL *s); + +int tls1_new(SSL *s); +void tls1_free(SSL *s); +void tls1_clear(SSL *s); +long tls1_ctrl(SSL *s,int cmd, long larg, void *parg); +long tls1_callback_ctrl(SSL *s,int cmd, void (*fp)(void)); + +int dtls1_new(SSL *s); +int dtls1_accept(SSL *s); +int dtls1_connect(SSL *s); +void dtls1_free(SSL *s); +void dtls1_clear(SSL *s); +long dtls1_ctrl(SSL *s,int cmd, long larg, void *parg); + +long dtls1_get_message(SSL *s, int st1, int stn, int mt, long max, int *ok); +int dtls1_get_record(SSL *s); +int do_dtls1_write(SSL *s, int type, const unsigned char *buf, + unsigned int len, int create_empty_fragement); +int dtls1_dispatch_alert(SSL *s); +int dtls1_enc(SSL *s, int snd); + +int ssl_init_wbio_buffer(SSL *s, int push); +void ssl_free_wbio_buffer(SSL *s); + +int tls1_change_cipher_state(SSL *s, int which); +int tls1_setup_key_block(SSL *s); +int tls1_enc(SSL *s, int snd); +int tls1_final_finish_mac(SSL *s, + const char *str, int slen, unsigned char *p); +int tls1_cert_verify_mac(SSL *s, int md_nid, unsigned char *p); +int tls1_mac(SSL *ssl, unsigned char *md, int snd); +int tls1_generate_master_secret(SSL *s, unsigned char *out, + unsigned char *p, int len); +int tls1_export_keying_material(SSL *s, unsigned char *out, size_t olen, + const char *label, size_t llen, const unsigned char *p, + size_t plen, int use_context); +int tls1_alert_code(int code); +int ssl3_alert_code(int code); +int ssl_ok(SSL *s); + +#ifndef OPENSSL_NO_ECDH +int ssl_check_srvr_ecc_cert_and_alg(X509 *x, const SSL_CIPHER *cs); +#endif + +SSL_COMP *ssl3_comp_find(STACK_OF(SSL_COMP) *sk, int n); + +#ifndef OPENSSL_NO_EC +int tls1_ec_curve_id2nid(int curve_id); +int tls1_ec_nid2curve_id(int nid); +#endif /* OPENSSL_NO_EC */ + +#ifndef OPENSSL_NO_TLSEXT +unsigned char *ssl_add_clienthello_tlsext(SSL *s, unsigned char *p, unsigned char *limit); +unsigned char *ssl_add_serverhello_tlsext(SSL *s, unsigned char *p, unsigned char *limit); +int ssl_parse_clienthello_tlsext(SSL *s, unsigned char **data, unsigned char *d, int n, int *al); +int ssl_parse_serverhello_tlsext(SSL *s, unsigned char **data, unsigned char *d, int n, int *al); +int ssl_prepare_clienthello_tlsext(SSL *s); +int ssl_prepare_serverhello_tlsext(SSL *s); +int ssl_check_clienthello_tlsext(SSL *s); +int ssl_check_serverhello_tlsext(SSL *s); + +#ifdef OPENSSL_NO_SHA256 +#define tlsext_tick_md EVP_sha1 +#else +#define tlsext_tick_md EVP_sha256 +#endif +int tls1_process_ticket(SSL *s, unsigned char *session_id, int len, + const unsigned char *limit, SSL_SESSION **ret); +#endif +EVP_MD_CTX* ssl_replace_hash(EVP_MD_CTX **hash,const EVP_MD *md) ; +void ssl_clear_hash_ctx(EVP_MD_CTX **hash); +int ssl_add_serverhello_renegotiate_ext(SSL *s, unsigned char *p, int *len, + int maxlen); +int ssl_parse_serverhello_renegotiate_ext(SSL *s, unsigned char *d, int len, + int *al); +int ssl_add_clienthello_renegotiate_ext(SSL *s, unsigned char *p, int *len, + int maxlen); +int ssl_parse_clienthello_renegotiate_ext(SSL *s, unsigned char *d, int len, + int *al); +#endif diff --git a/node-v0.8.14/deps/openssl/openssl/ssl/ssl_rsa.c b/node-v0.8.14/deps/openssl/openssl/ssl/ssl_rsa.c new file mode 100644 index 0000000..c43f3e2 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/ssl/ssl_rsa.c @@ -0,0 +1,815 @@ +/* ssl/ssl_rsa.c */ +/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com) + * All rights reserved. + * + * This package is an SSL implementation written + * by Eric Young (eay@cryptsoft.com). + * The implementation was written so as to conform with Netscapes SSL. + * + * This library is free for commercial and non-commercial use as long as + * the following conditions are aheared to. The following conditions + * apply to all code found in this distribution, be it the RC4, RSA, + * lhash, DES, etc., code; not just the SSL code. The SSL documentation + * included with this distribution is covered by the same copyright terms + * except that the holder is Tim Hudson (tjh@cryptsoft.com). + * + * Copyright remains Eric Young's, and as such any Copyright notices in + * the code are not to be removed. + * If this package is used in a product, Eric Young should be given attribution + * as the author of the parts of the library used. + * This can be in the form of a textual message at program startup or + * in documentation (online or textual) provided with the package. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * "This product includes cryptographic software written by + * Eric Young (eay@cryptsoft.com)" + * The word 'cryptographic' can be left out if the rouines from the library + * being used are not cryptographic related :-). + * 4. If you include any Windows specific code (or a derivative thereof) from + * the apps directory (application code) you must include an acknowledgement: + * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)" + * + * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * + * The licence and distribution terms for any publically available version or + * derivative of this code cannot be changed. i.e. this code cannot simply be + * copied and put under another distribution licence + * [including the GNU Public Licence.] + */ + +#include +#include "ssl_locl.h" +#include +#include +#include +#include +#include + +static int ssl_set_cert(CERT *c, X509 *x509); +static int ssl_set_pkey(CERT *c, EVP_PKEY *pkey); +int SSL_use_certificate(SSL *ssl, X509 *x) + { + if (x == NULL) + { + SSLerr(SSL_F_SSL_USE_CERTIFICATE,ERR_R_PASSED_NULL_PARAMETER); + return(0); + } + if (!ssl_cert_inst(&ssl->cert)) + { + SSLerr(SSL_F_SSL_USE_CERTIFICATE,ERR_R_MALLOC_FAILURE); + return(0); + } + return(ssl_set_cert(ssl->cert,x)); + } + +#ifndef OPENSSL_NO_STDIO +int SSL_use_certificate_file(SSL *ssl, const char *file, int type) + { + int j; + BIO *in; + int ret=0; + X509 *x=NULL; + + in=BIO_new(BIO_s_file_internal()); + if (in == NULL) + { + SSLerr(SSL_F_SSL_USE_CERTIFICATE_FILE,ERR_R_BUF_LIB); + goto end; + } + + if (BIO_read_filename(in,file) <= 0) + { + SSLerr(SSL_F_SSL_USE_CERTIFICATE_FILE,ERR_R_SYS_LIB); + goto end; + } + if (type == SSL_FILETYPE_ASN1) + { + j=ERR_R_ASN1_LIB; + x=d2i_X509_bio(in,NULL); + } + else if (type == SSL_FILETYPE_PEM) + { + j=ERR_R_PEM_LIB; + x=PEM_read_bio_X509(in,NULL,ssl->ctx->default_passwd_callback,ssl->ctx->default_passwd_callback_userdata); + } + else + { + SSLerr(SSL_F_SSL_USE_CERTIFICATE_FILE,SSL_R_BAD_SSL_FILETYPE); + goto end; + } + + if (x == NULL) + { + SSLerr(SSL_F_SSL_USE_CERTIFICATE_FILE,j); + goto end; + } + + ret=SSL_use_certificate(ssl,x); +end: + if (x != NULL) X509_free(x); + if (in != NULL) BIO_free(in); + return(ret); + } +#endif + +int SSL_use_certificate_ASN1(SSL *ssl, const unsigned char *d, int len) + { + X509 *x; + int ret; + + x=d2i_X509(NULL,&d,(long)len); + if (x == NULL) + { + SSLerr(SSL_F_SSL_USE_CERTIFICATE_ASN1,ERR_R_ASN1_LIB); + return(0); + } + + ret=SSL_use_certificate(ssl,x); + X509_free(x); + return(ret); + } + +#ifndef OPENSSL_NO_RSA +int SSL_use_RSAPrivateKey(SSL *ssl, RSA *rsa) + { + EVP_PKEY *pkey; + int ret; + + if (rsa == NULL) + { + SSLerr(SSL_F_SSL_USE_RSAPRIVATEKEY,ERR_R_PASSED_NULL_PARAMETER); + return(0); + } + if (!ssl_cert_inst(&ssl->cert)) + { + SSLerr(SSL_F_SSL_USE_RSAPRIVATEKEY,ERR_R_MALLOC_FAILURE); + return(0); + } + if ((pkey=EVP_PKEY_new()) == NULL) + { + SSLerr(SSL_F_SSL_USE_RSAPRIVATEKEY,ERR_R_EVP_LIB); + return(0); + } + + RSA_up_ref(rsa); + EVP_PKEY_assign_RSA(pkey,rsa); + + ret=ssl_set_pkey(ssl->cert,pkey); + EVP_PKEY_free(pkey); + return(ret); + } +#endif + +static int ssl_set_pkey(CERT *c, EVP_PKEY *pkey) + { + int i; + + i=ssl_cert_type(NULL,pkey); + if (i < 0) + { + SSLerr(SSL_F_SSL_SET_PKEY,SSL_R_UNKNOWN_CERTIFICATE_TYPE); + return(0); + } + + if (c->pkeys[i].x509 != NULL) + { + EVP_PKEY *pktmp; + pktmp = X509_get_pubkey(c->pkeys[i].x509); + EVP_PKEY_copy_parameters(pktmp,pkey); + EVP_PKEY_free(pktmp); + ERR_clear_error(); + +#ifndef OPENSSL_NO_RSA + /* Don't check the public/private key, this is mostly + * for smart cards. */ + if ((pkey->type == EVP_PKEY_RSA) && + (RSA_flags(pkey->pkey.rsa) & RSA_METHOD_FLAG_NO_CHECK)) + ; + else +#endif + if (!X509_check_private_key(c->pkeys[i].x509,pkey)) + { + X509_free(c->pkeys[i].x509); + c->pkeys[i].x509 = NULL; + return 0; + } + } + + if (c->pkeys[i].privatekey != NULL) + EVP_PKEY_free(c->pkeys[i].privatekey); + CRYPTO_add(&pkey->references,1,CRYPTO_LOCK_EVP_PKEY); + c->pkeys[i].privatekey=pkey; + c->key= &(c->pkeys[i]); + + c->valid=0; + return(1); + } + +#ifndef OPENSSL_NO_RSA +#ifndef OPENSSL_NO_STDIO +int SSL_use_RSAPrivateKey_file(SSL *ssl, const char *file, int type) + { + int j,ret=0; + BIO *in; + RSA *rsa=NULL; + + in=BIO_new(BIO_s_file_internal()); + if (in == NULL) + { + SSLerr(SSL_F_SSL_USE_RSAPRIVATEKEY_FILE,ERR_R_BUF_LIB); + goto end; + } + + if (BIO_read_filename(in,file) <= 0) + { + SSLerr(SSL_F_SSL_USE_RSAPRIVATEKEY_FILE,ERR_R_SYS_LIB); + goto end; + } + if (type == SSL_FILETYPE_ASN1) + { + j=ERR_R_ASN1_LIB; + rsa=d2i_RSAPrivateKey_bio(in,NULL); + } + else if (type == SSL_FILETYPE_PEM) + { + j=ERR_R_PEM_LIB; + rsa=PEM_read_bio_RSAPrivateKey(in,NULL, + ssl->ctx->default_passwd_callback,ssl->ctx->default_passwd_callback_userdata); + } + else + { + SSLerr(SSL_F_SSL_USE_RSAPRIVATEKEY_FILE,SSL_R_BAD_SSL_FILETYPE); + goto end; + } + if (rsa == NULL) + { + SSLerr(SSL_F_SSL_USE_RSAPRIVATEKEY_FILE,j); + goto end; + } + ret=SSL_use_RSAPrivateKey(ssl,rsa); + RSA_free(rsa); +end: + if (in != NULL) BIO_free(in); + return(ret); + } +#endif + +int SSL_use_RSAPrivateKey_ASN1(SSL *ssl, unsigned char *d, long len) + { + int ret; + const unsigned char *p; + RSA *rsa; + + p=d; + if ((rsa=d2i_RSAPrivateKey(NULL,&p,(long)len)) == NULL) + { + SSLerr(SSL_F_SSL_USE_RSAPRIVATEKEY_ASN1,ERR_R_ASN1_LIB); + return(0); + } + + ret=SSL_use_RSAPrivateKey(ssl,rsa); + RSA_free(rsa); + return(ret); + } +#endif /* !OPENSSL_NO_RSA */ + +int SSL_use_PrivateKey(SSL *ssl, EVP_PKEY *pkey) + { + int ret; + + if (pkey == NULL) + { + SSLerr(SSL_F_SSL_USE_PRIVATEKEY,ERR_R_PASSED_NULL_PARAMETER); + return(0); + } + if (!ssl_cert_inst(&ssl->cert)) + { + SSLerr(SSL_F_SSL_USE_PRIVATEKEY,ERR_R_MALLOC_FAILURE); + return(0); + } + ret=ssl_set_pkey(ssl->cert,pkey); + return(ret); + } + +#ifndef OPENSSL_NO_STDIO +int SSL_use_PrivateKey_file(SSL *ssl, const char *file, int type) + { + int j,ret=0; + BIO *in; + EVP_PKEY *pkey=NULL; + + in=BIO_new(BIO_s_file_internal()); + if (in == NULL) + { + SSLerr(SSL_F_SSL_USE_PRIVATEKEY_FILE,ERR_R_BUF_LIB); + goto end; + } + + if (BIO_read_filename(in,file) <= 0) + { + SSLerr(SSL_F_SSL_USE_PRIVATEKEY_FILE,ERR_R_SYS_LIB); + goto end; + } + if (type == SSL_FILETYPE_PEM) + { + j=ERR_R_PEM_LIB; + pkey=PEM_read_bio_PrivateKey(in,NULL, + ssl->ctx->default_passwd_callback,ssl->ctx->default_passwd_callback_userdata); + } + else if (type == SSL_FILETYPE_ASN1) + { + j = ERR_R_ASN1_LIB; + pkey = d2i_PrivateKey_bio(in,NULL); + } + else + { + SSLerr(SSL_F_SSL_USE_PRIVATEKEY_FILE,SSL_R_BAD_SSL_FILETYPE); + goto end; + } + if (pkey == NULL) + { + SSLerr(SSL_F_SSL_USE_PRIVATEKEY_FILE,j); + goto end; + } + ret=SSL_use_PrivateKey(ssl,pkey); + EVP_PKEY_free(pkey); +end: + if (in != NULL) BIO_free(in); + return(ret); + } +#endif + +int SSL_use_PrivateKey_ASN1(int type, SSL *ssl, const unsigned char *d, long len) + { + int ret; + const unsigned char *p; + EVP_PKEY *pkey; + + p=d; + if ((pkey=d2i_PrivateKey(type,NULL,&p,(long)len)) == NULL) + { + SSLerr(SSL_F_SSL_USE_PRIVATEKEY_ASN1,ERR_R_ASN1_LIB); + return(0); + } + + ret=SSL_use_PrivateKey(ssl,pkey); + EVP_PKEY_free(pkey); + return(ret); + } + +int SSL_CTX_use_certificate(SSL_CTX *ctx, X509 *x) + { + if (x == NULL) + { + SSLerr(SSL_F_SSL_CTX_USE_CERTIFICATE,ERR_R_PASSED_NULL_PARAMETER); + return(0); + } + if (!ssl_cert_inst(&ctx->cert)) + { + SSLerr(SSL_F_SSL_CTX_USE_CERTIFICATE,ERR_R_MALLOC_FAILURE); + return(0); + } + return(ssl_set_cert(ctx->cert, x)); + } + +static int ssl_set_cert(CERT *c, X509 *x) + { + EVP_PKEY *pkey; + int i; + + pkey=X509_get_pubkey(x); + if (pkey == NULL) + { + SSLerr(SSL_F_SSL_SET_CERT,SSL_R_X509_LIB); + return(0); + } + + i=ssl_cert_type(x,pkey); + if (i < 0) + { + SSLerr(SSL_F_SSL_SET_CERT,SSL_R_UNKNOWN_CERTIFICATE_TYPE); + EVP_PKEY_free(pkey); + return(0); + } + + if (c->pkeys[i].privatekey != NULL) + { + EVP_PKEY_copy_parameters(pkey,c->pkeys[i].privatekey); + ERR_clear_error(); + +#ifndef OPENSSL_NO_RSA + /* Don't check the public/private key, this is mostly + * for smart cards. */ + if ((c->pkeys[i].privatekey->type == EVP_PKEY_RSA) && + (RSA_flags(c->pkeys[i].privatekey->pkey.rsa) & + RSA_METHOD_FLAG_NO_CHECK)) + ; + else +#endif /* OPENSSL_NO_RSA */ + if (!X509_check_private_key(x,c->pkeys[i].privatekey)) + { + /* don't fail for a cert/key mismatch, just free + * current private key (when switching to a different + * cert & key, first this function should be used, + * then ssl_set_pkey */ + EVP_PKEY_free(c->pkeys[i].privatekey); + c->pkeys[i].privatekey=NULL; + /* clear error queue */ + ERR_clear_error(); + } + } + + EVP_PKEY_free(pkey); + + if (c->pkeys[i].x509 != NULL) + X509_free(c->pkeys[i].x509); + CRYPTO_add(&x->references,1,CRYPTO_LOCK_X509); + c->pkeys[i].x509=x; + c->key= &(c->pkeys[i]); + + c->valid=0; + return(1); + } + +#ifndef OPENSSL_NO_STDIO +int SSL_CTX_use_certificate_file(SSL_CTX *ctx, const char *file, int type) + { + int j; + BIO *in; + int ret=0; + X509 *x=NULL; + + in=BIO_new(BIO_s_file_internal()); + if (in == NULL) + { + SSLerr(SSL_F_SSL_CTX_USE_CERTIFICATE_FILE,ERR_R_BUF_LIB); + goto end; + } + + if (BIO_read_filename(in,file) <= 0) + { + SSLerr(SSL_F_SSL_CTX_USE_CERTIFICATE_FILE,ERR_R_SYS_LIB); + goto end; + } + if (type == SSL_FILETYPE_ASN1) + { + j=ERR_R_ASN1_LIB; + x=d2i_X509_bio(in,NULL); + } + else if (type == SSL_FILETYPE_PEM) + { + j=ERR_R_PEM_LIB; + x=PEM_read_bio_X509(in,NULL,ctx->default_passwd_callback,ctx->default_passwd_callback_userdata); + } + else + { + SSLerr(SSL_F_SSL_CTX_USE_CERTIFICATE_FILE,SSL_R_BAD_SSL_FILETYPE); + goto end; + } + + if (x == NULL) + { + SSLerr(SSL_F_SSL_CTX_USE_CERTIFICATE_FILE,j); + goto end; + } + + ret=SSL_CTX_use_certificate(ctx,x); +end: + if (x != NULL) X509_free(x); + if (in != NULL) BIO_free(in); + return(ret); + } +#endif + +int SSL_CTX_use_certificate_ASN1(SSL_CTX *ctx, int len, const unsigned char *d) + { + X509 *x; + int ret; + + x=d2i_X509(NULL,&d,(long)len); + if (x == NULL) + { + SSLerr(SSL_F_SSL_CTX_USE_CERTIFICATE_ASN1,ERR_R_ASN1_LIB); + return(0); + } + + ret=SSL_CTX_use_certificate(ctx,x); + X509_free(x); + return(ret); + } + +#ifndef OPENSSL_NO_RSA +int SSL_CTX_use_RSAPrivateKey(SSL_CTX *ctx, RSA *rsa) + { + int ret; + EVP_PKEY *pkey; + + if (rsa == NULL) + { + SSLerr(SSL_F_SSL_CTX_USE_RSAPRIVATEKEY,ERR_R_PASSED_NULL_PARAMETER); + return(0); + } + if (!ssl_cert_inst(&ctx->cert)) + { + SSLerr(SSL_F_SSL_CTX_USE_RSAPRIVATEKEY,ERR_R_MALLOC_FAILURE); + return(0); + } + if ((pkey=EVP_PKEY_new()) == NULL) + { + SSLerr(SSL_F_SSL_CTX_USE_RSAPRIVATEKEY,ERR_R_EVP_LIB); + return(0); + } + + RSA_up_ref(rsa); + EVP_PKEY_assign_RSA(pkey,rsa); + + ret=ssl_set_pkey(ctx->cert, pkey); + EVP_PKEY_free(pkey); + return(ret); + } + +#ifndef OPENSSL_NO_STDIO +int SSL_CTX_use_RSAPrivateKey_file(SSL_CTX *ctx, const char *file, int type) + { + int j,ret=0; + BIO *in; + RSA *rsa=NULL; + + in=BIO_new(BIO_s_file_internal()); + if (in == NULL) + { + SSLerr(SSL_F_SSL_CTX_USE_RSAPRIVATEKEY_FILE,ERR_R_BUF_LIB); + goto end; + } + + if (BIO_read_filename(in,file) <= 0) + { + SSLerr(SSL_F_SSL_CTX_USE_RSAPRIVATEKEY_FILE,ERR_R_SYS_LIB); + goto end; + } + if (type == SSL_FILETYPE_ASN1) + { + j=ERR_R_ASN1_LIB; + rsa=d2i_RSAPrivateKey_bio(in,NULL); + } + else if (type == SSL_FILETYPE_PEM) + { + j=ERR_R_PEM_LIB; + rsa=PEM_read_bio_RSAPrivateKey(in,NULL, + ctx->default_passwd_callback,ctx->default_passwd_callback_userdata); + } + else + { + SSLerr(SSL_F_SSL_CTX_USE_RSAPRIVATEKEY_FILE,SSL_R_BAD_SSL_FILETYPE); + goto end; + } + if (rsa == NULL) + { + SSLerr(SSL_F_SSL_CTX_USE_RSAPRIVATEKEY_FILE,j); + goto end; + } + ret=SSL_CTX_use_RSAPrivateKey(ctx,rsa); + RSA_free(rsa); +end: + if (in != NULL) BIO_free(in); + return(ret); + } +#endif + +int SSL_CTX_use_RSAPrivateKey_ASN1(SSL_CTX *ctx, const unsigned char *d, long len) + { + int ret; + const unsigned char *p; + RSA *rsa; + + p=d; + if ((rsa=d2i_RSAPrivateKey(NULL,&p,(long)len)) == NULL) + { + SSLerr(SSL_F_SSL_CTX_USE_RSAPRIVATEKEY_ASN1,ERR_R_ASN1_LIB); + return(0); + } + + ret=SSL_CTX_use_RSAPrivateKey(ctx,rsa); + RSA_free(rsa); + return(ret); + } +#endif /* !OPENSSL_NO_RSA */ + +int SSL_CTX_use_PrivateKey(SSL_CTX *ctx, EVP_PKEY *pkey) + { + if (pkey == NULL) + { + SSLerr(SSL_F_SSL_CTX_USE_PRIVATEKEY,ERR_R_PASSED_NULL_PARAMETER); + return(0); + } + if (!ssl_cert_inst(&ctx->cert)) + { + SSLerr(SSL_F_SSL_CTX_USE_PRIVATEKEY,ERR_R_MALLOC_FAILURE); + return(0); + } + return(ssl_set_pkey(ctx->cert,pkey)); + } + +#ifndef OPENSSL_NO_STDIO +int SSL_CTX_use_PrivateKey_file(SSL_CTX *ctx, const char *file, int type) + { + int j,ret=0; + BIO *in; + EVP_PKEY *pkey=NULL; + + in=BIO_new(BIO_s_file_internal()); + if (in == NULL) + { + SSLerr(SSL_F_SSL_CTX_USE_PRIVATEKEY_FILE,ERR_R_BUF_LIB); + goto end; + } + + if (BIO_read_filename(in,file) <= 0) + { + SSLerr(SSL_F_SSL_CTX_USE_PRIVATEKEY_FILE,ERR_R_SYS_LIB); + goto end; + } + if (type == SSL_FILETYPE_PEM) + { + j=ERR_R_PEM_LIB; + pkey=PEM_read_bio_PrivateKey(in,NULL, + ctx->default_passwd_callback,ctx->default_passwd_callback_userdata); + } + else if (type == SSL_FILETYPE_ASN1) + { + j = ERR_R_ASN1_LIB; + pkey = d2i_PrivateKey_bio(in,NULL); + } + else + { + SSLerr(SSL_F_SSL_CTX_USE_PRIVATEKEY_FILE,SSL_R_BAD_SSL_FILETYPE); + goto end; + } + if (pkey == NULL) + { + SSLerr(SSL_F_SSL_CTX_USE_PRIVATEKEY_FILE,j); + goto end; + } + ret=SSL_CTX_use_PrivateKey(ctx,pkey); + EVP_PKEY_free(pkey); +end: + if (in != NULL) BIO_free(in); + return(ret); + } +#endif + +int SSL_CTX_use_PrivateKey_ASN1(int type, SSL_CTX *ctx, const unsigned char *d, + long len) + { + int ret; + const unsigned char *p; + EVP_PKEY *pkey; + + p=d; + if ((pkey=d2i_PrivateKey(type,NULL,&p,(long)len)) == NULL) + { + SSLerr(SSL_F_SSL_CTX_USE_PRIVATEKEY_ASN1,ERR_R_ASN1_LIB); + return(0); + } + + ret=SSL_CTX_use_PrivateKey(ctx,pkey); + EVP_PKEY_free(pkey); + return(ret); + } + + +int SSL_use_certificate_chain(SSL *ssl, STACK_OF(X509) *cert_chain) + { + if (ssl == NULL) + { + SSLerr(SSL_F_SSL_USE_CERTIFICATE_CHAIN,ERR_R_PASSED_NULL_PARAMETER); + return(0); + } + if (ssl->cert == NULL) + { + SSLerr(SSL_F_SSL_USE_CERTIFICATE_CHAIN,SSL_R_NO_CERTIFICATE_ASSIGNED); + return(0); + } + if (ssl->cert->key == NULL) + { + SSLerr(SSL_F_SSL_USE_CERTIFICATE_CHAIN,SSL_R_NO_CERTIFICATE_ASSIGNED); + return(0); + } + ssl->cert->key->cert_chain = cert_chain; + return(1); + } + +STACK_OF(X509) *SSL_get_certificate_chain(SSL *ssl, X509 *x) + { + int i; + if (x == NULL) + return NULL; + if (ssl == NULL) + return NULL; + if (ssl->cert == NULL) + return NULL; + for (i = 0; i < SSL_PKEY_NUM; i++) + if (ssl->cert->pkeys[i].x509 == x) + return ssl->cert->pkeys[i].cert_chain; + return NULL; + } + +#ifndef OPENSSL_NO_STDIO +/* Read a file that contains our certificate in "PEM" format, + * possibly followed by a sequence of CA certificates that should be + * sent to the peer in the Certificate message. + */ +int SSL_CTX_use_certificate_chain_file(SSL_CTX *ctx, const char *file) + { + BIO *in; + int ret=0; + X509 *x=NULL; + + ERR_clear_error(); /* clear error stack for SSL_CTX_use_certificate() */ + + in=BIO_new(BIO_s_file_internal()); + if (in == NULL) + { + SSLerr(SSL_F_SSL_CTX_USE_CERTIFICATE_CHAIN_FILE,ERR_R_BUF_LIB); + goto end; + } + + if (BIO_read_filename(in,file) <= 0) + { + SSLerr(SSL_F_SSL_CTX_USE_CERTIFICATE_CHAIN_FILE,ERR_R_SYS_LIB); + goto end; + } + + x=PEM_read_bio_X509_AUX(in,NULL,ctx->default_passwd_callback,ctx->default_passwd_callback_userdata); + if (x == NULL) + { + SSLerr(SSL_F_SSL_CTX_USE_CERTIFICATE_CHAIN_FILE,ERR_R_PEM_LIB); + goto end; + } + + ret=SSL_CTX_use_certificate(ctx,x); + if (ERR_peek_error() != 0) + ret = 0; /* Key/certificate mismatch doesn't imply ret==0 ... */ + if (ret) + { + /* If we could set up our certificate, now proceed to + * the CA certificates. + */ + X509 *ca; + int r; + unsigned long err; + + if (ctx->extra_certs != NULL) + { + sk_X509_pop_free(ctx->extra_certs, X509_free); + ctx->extra_certs = NULL; + } + + while ((ca = PEM_read_bio_X509(in,NULL,ctx->default_passwd_callback,ctx->default_passwd_callback_userdata)) + != NULL) + { + r = SSL_CTX_add_extra_chain_cert(ctx, ca); + if (!r) + { + X509_free(ca); + ret = 0; + goto end; + } + /* Note that we must not free r if it was successfully + * added to the chain (while we must free the main + * certificate, since its reference count is increased + * by SSL_CTX_use_certificate). */ + } + /* When the while loop ends, it's usually just EOF. */ + err = ERR_peek_last_error(); + if (ERR_GET_LIB(err) == ERR_LIB_PEM && ERR_GET_REASON(err) == PEM_R_NO_START_LINE) + ERR_clear_error(); + else + ret = 0; /* some real error */ + } + +end: + if (x != NULL) X509_free(x); + if (in != NULL) BIO_free(in); + return(ret); + } +#endif diff --git a/node-v0.8.14/deps/openssl/openssl/ssl/ssl_sess.c b/node-v0.8.14/deps/openssl/openssl/ssl/ssl_sess.c new file mode 100644 index 0000000..93954e4 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/ssl/ssl_sess.c @@ -0,0 +1,1102 @@ +/* ssl/ssl_sess.c */ +/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com) + * All rights reserved. + * + * This package is an SSL implementation written + * by Eric Young (eay@cryptsoft.com). + * The implementation was written so as to conform with Netscapes SSL. + * + * This library is free for commercial and non-commercial use as long as + * the following conditions are aheared to. The following conditions + * apply to all code found in this distribution, be it the RC4, RSA, + * lhash, DES, etc., code; not just the SSL code. The SSL documentation + * included with this distribution is covered by the same copyright terms + * except that the holder is Tim Hudson (tjh@cryptsoft.com). + * + * Copyright remains Eric Young's, and as such any Copyright notices in + * the code are not to be removed. + * If this package is used in a product, Eric Young should be given attribution + * as the author of the parts of the library used. + * This can be in the form of a textual message at program startup or + * in documentation (online or textual) provided with the package. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * "This product includes cryptographic software written by + * Eric Young (eay@cryptsoft.com)" + * The word 'cryptographic' can be left out if the rouines from the library + * being used are not cryptographic related :-). + * 4. If you include any Windows specific code (or a derivative thereof) from + * the apps directory (application code) you must include an acknowledgement: + * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)" + * + * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * + * The licence and distribution terms for any publically available version or + * derivative of this code cannot be changed. i.e. this code cannot simply be + * copied and put under another distribution licence + * [including the GNU Public Licence.] + */ +/* ==================================================================== + * Copyright (c) 1998-2006 The OpenSSL Project. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. All advertising materials mentioning features or use of this + * software must display the following acknowledgment: + * "This product includes software developed by the OpenSSL Project + * for use in the OpenSSL Toolkit. (http://www.openssl.org/)" + * + * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to + * endorse or promote products derived from this software without + * prior written permission. For written permission, please contact + * openssl-core@openssl.org. + * + * 5. Products derived from this software may not be called "OpenSSL" + * nor may "OpenSSL" appear in their names without prior written + * permission of the OpenSSL Project. + * + * 6. Redistributions of any form whatsoever must retain the following + * acknowledgment: + * "This product includes software developed by the OpenSSL Project + * for use in the OpenSSL Toolkit (http://www.openssl.org/)" + * + * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY + * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR + * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, + * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * ==================================================================== + * + * This product includes cryptographic software written by Eric Young + * (eay@cryptsoft.com). This product includes software written by Tim + * Hudson (tjh@cryptsoft.com). + * + */ +/* ==================================================================== + * Copyright 2005 Nokia. All rights reserved. + * + * The portions of the attached software ("Contribution") is developed by + * Nokia Corporation and is licensed pursuant to the OpenSSL open source + * license. + * + * The Contribution, originally written by Mika Kousa and Pasi Eronen of + * Nokia Corporation, consists of the "PSK" (Pre-Shared Key) ciphersuites + * support (see RFC 4279) to OpenSSL. + * + * No patent licenses or other rights except those expressly stated in + * the OpenSSL open source license shall be deemed granted or received + * expressly, by implication, estoppel, or otherwise. + * + * No assurances are provided by Nokia that the Contribution does not + * infringe the patent or other intellectual property rights of any third + * party or that the license provides you with all the necessary rights + * to make use of the Contribution. + * + * THE SOFTWARE IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND. IN + * ADDITION TO THE DISCLAIMERS INCLUDED IN THE LICENSE, NOKIA + * SPECIFICALLY DISCLAIMS ANY LIABILITY FOR CLAIMS BROUGHT BY YOU OR ANY + * OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL PROPERTY RIGHTS OR + * OTHERWISE. + */ + +#include +#include +#include +#ifndef OPENSSL_NO_ENGINE +#include +#endif +#include "ssl_locl.h" + +static void SSL_SESSION_list_remove(SSL_CTX *ctx, SSL_SESSION *s); +static void SSL_SESSION_list_add(SSL_CTX *ctx,SSL_SESSION *s); +static int remove_session_lock(SSL_CTX *ctx, SSL_SESSION *c, int lck); + +SSL_SESSION *SSL_get_session(const SSL *ssl) +/* aka SSL_get0_session; gets 0 objects, just returns a copy of the pointer */ + { + return(ssl->session); + } + +SSL_SESSION *SSL_get1_session(SSL *ssl) +/* variant of SSL_get_session: caller really gets something */ + { + SSL_SESSION *sess; + /* Need to lock this all up rather than just use CRYPTO_add so that + * somebody doesn't free ssl->session between when we check it's + * non-null and when we up the reference count. */ + CRYPTO_w_lock(CRYPTO_LOCK_SSL_SESSION); + sess = ssl->session; + if(sess) + sess->references++; + CRYPTO_w_unlock(CRYPTO_LOCK_SSL_SESSION); + return(sess); + } + +int SSL_SESSION_get_ex_new_index(long argl, void *argp, CRYPTO_EX_new *new_func, + CRYPTO_EX_dup *dup_func, CRYPTO_EX_free *free_func) + { + return CRYPTO_get_ex_new_index(CRYPTO_EX_INDEX_SSL_SESSION, argl, argp, + new_func, dup_func, free_func); + } + +int SSL_SESSION_set_ex_data(SSL_SESSION *s, int idx, void *arg) + { + return(CRYPTO_set_ex_data(&s->ex_data,idx,arg)); + } + +void *SSL_SESSION_get_ex_data(const SSL_SESSION *s, int idx) + { + return(CRYPTO_get_ex_data(&s->ex_data,idx)); + } + +SSL_SESSION *SSL_SESSION_new(void) + { + SSL_SESSION *ss; + + ss=(SSL_SESSION *)OPENSSL_malloc(sizeof(SSL_SESSION)); + if (ss == NULL) + { + SSLerr(SSL_F_SSL_SESSION_NEW,ERR_R_MALLOC_FAILURE); + return(0); + } + memset(ss,0,sizeof(SSL_SESSION)); + + ss->verify_result = 1; /* avoid 0 (= X509_V_OK) just in case */ + ss->references=1; + ss->timeout=60*5+4; /* 5 minute timeout by default */ + ss->time=(unsigned long)time(NULL); + ss->prev=NULL; + ss->next=NULL; + ss->compress_meth=0; +#ifndef OPENSSL_NO_TLSEXT + ss->tlsext_hostname = NULL; +#ifndef OPENSSL_NO_EC + ss->tlsext_ecpointformatlist_length = 0; + ss->tlsext_ecpointformatlist = NULL; + ss->tlsext_ellipticcurvelist_length = 0; + ss->tlsext_ellipticcurvelist = NULL; +#endif +#endif + CRYPTO_new_ex_data(CRYPTO_EX_INDEX_SSL_SESSION, ss, &ss->ex_data); +#ifndef OPENSSL_NO_PSK + ss->psk_identity_hint=NULL; + ss->psk_identity=NULL; +#endif + return(ss); + } + +const unsigned char *SSL_SESSION_get_id(const SSL_SESSION *s, unsigned int *len) + { + if(len) + *len = s->session_id_length; + return s->session_id; + } + +/* Even with SSLv2, we have 16 bytes (128 bits) of session ID space. SSLv3/TLSv1 + * has 32 bytes (256 bits). As such, filling the ID with random gunk repeatedly + * until we have no conflict is going to complete in one iteration pretty much + * "most" of the time (btw: understatement). So, if it takes us 10 iterations + * and we still can't avoid a conflict - well that's a reasonable point to call + * it quits. Either the RAND code is broken or someone is trying to open roughly + * very close to 2^128 (or 2^256) SSL sessions to our server. How you might + * store that many sessions is perhaps a more interesting question ... */ + +#define MAX_SESS_ID_ATTEMPTS 10 +static int def_generate_session_id(const SSL *ssl, unsigned char *id, + unsigned int *id_len) +{ + unsigned int retry = 0; + do + if (RAND_pseudo_bytes(id, *id_len) <= 0) + return 0; + while(SSL_has_matching_session_id(ssl, id, *id_len) && + (++retry < MAX_SESS_ID_ATTEMPTS)); + if(retry < MAX_SESS_ID_ATTEMPTS) + return 1; + /* else - woops a session_id match */ + /* XXX We should also check the external cache -- + * but the probability of a collision is negligible, and + * we could not prevent the concurrent creation of sessions + * with identical IDs since we currently don't have means + * to atomically check whether a session ID already exists + * and make a reservation for it if it does not + * (this problem applies to the internal cache as well). + */ + return 0; +} + +void SSL_set_session_creation_enabled (SSL *s, int creation_enabled) + { + s->session_creation_enabled = creation_enabled; + } + +int ssl_get_new_session(SSL *s, int session) + { + /* This gets used by clients and servers. */ + + unsigned int tmp; + SSL_SESSION *ss=NULL; + GEN_SESSION_CB cb = def_generate_session_id; + + /* caller should check this if they can do better error handling */ + if (!s->session_creation_enabled) return(0); + if ((ss=SSL_SESSION_new()) == NULL) return(0); + + /* If the context has a default timeout, use it */ + if (s->session_ctx->session_timeout == 0) + ss->timeout=SSL_get_default_timeout(s); + else + ss->timeout=s->session_ctx->session_timeout; + + if (s->session != NULL) + { + SSL_SESSION_free(s->session); + s->session=NULL; + } + + if (session) + { + if (s->version == SSL2_VERSION) + { + ss->ssl_version=SSL2_VERSION; + ss->session_id_length=SSL2_SSL_SESSION_ID_LENGTH; + } + else if (s->version == SSL3_VERSION) + { + ss->ssl_version=SSL3_VERSION; + ss->session_id_length=SSL3_SSL_SESSION_ID_LENGTH; + } + else if (s->version == TLS1_VERSION) + { + ss->ssl_version=TLS1_VERSION; + ss->session_id_length=SSL3_SSL_SESSION_ID_LENGTH; + } + else if (s->version == DTLS1_BAD_VER) + { + ss->ssl_version=DTLS1_BAD_VER; + ss->session_id_length=SSL3_SSL_SESSION_ID_LENGTH; + } + else if (s->version == DTLS1_VERSION) + { + ss->ssl_version=DTLS1_VERSION; + ss->session_id_length=SSL3_SSL_SESSION_ID_LENGTH; + } + else + { + SSLerr(SSL_F_SSL_GET_NEW_SESSION,SSL_R_UNSUPPORTED_SSL_VERSION); + SSL_SESSION_free(ss); + return(0); + } +#ifndef OPENSSL_NO_TLSEXT + /* If RFC4507 ticket use empty session ID */ + if (s->tlsext_ticket_expected) + { + ss->session_id_length = 0; + goto sess_id_done; + } +#endif + /* Choose which callback will set the session ID */ + CRYPTO_r_lock(CRYPTO_LOCK_SSL_CTX); + if(s->generate_session_id) + cb = s->generate_session_id; + else if(s->session_ctx->generate_session_id) + cb = s->session_ctx->generate_session_id; + CRYPTO_r_unlock(CRYPTO_LOCK_SSL_CTX); + /* Choose a session ID */ + tmp = ss->session_id_length; + if(!cb(s, ss->session_id, &tmp)) + { + /* The callback failed */ + SSLerr(SSL_F_SSL_GET_NEW_SESSION, + SSL_R_SSL_SESSION_ID_CALLBACK_FAILED); + SSL_SESSION_free(ss); + return(0); + } + /* Don't allow the callback to set the session length to zero. + * nor set it higher than it was. */ + if(!tmp || (tmp > ss->session_id_length)) + { + /* The callback set an illegal length */ + SSLerr(SSL_F_SSL_GET_NEW_SESSION, + SSL_R_SSL_SESSION_ID_HAS_BAD_LENGTH); + SSL_SESSION_free(ss); + return(0); + } + /* If the session length was shrunk and we're SSLv2, pad it */ + if((tmp < ss->session_id_length) && (s->version == SSL2_VERSION)) + memset(ss->session_id + tmp, 0, ss->session_id_length - tmp); + else + ss->session_id_length = tmp; + /* Finally, check for a conflict */ + if(SSL_has_matching_session_id(s, ss->session_id, + ss->session_id_length)) + { + SSLerr(SSL_F_SSL_GET_NEW_SESSION, + SSL_R_SSL_SESSION_ID_CONFLICT); + SSL_SESSION_free(ss); + return(0); + } +#ifndef OPENSSL_NO_TLSEXT + sess_id_done: + if (s->tlsext_hostname) { + ss->tlsext_hostname = BUF_strdup(s->tlsext_hostname); + if (ss->tlsext_hostname == NULL) { + SSLerr(SSL_F_SSL_GET_NEW_SESSION, ERR_R_INTERNAL_ERROR); + SSL_SESSION_free(ss); + return 0; + } + } +#ifndef OPENSSL_NO_EC + if (s->tlsext_ecpointformatlist) + { + if (ss->tlsext_ecpointformatlist != NULL) OPENSSL_free(ss->tlsext_ecpointformatlist); + if ((ss->tlsext_ecpointformatlist = OPENSSL_malloc(s->tlsext_ecpointformatlist_length)) == NULL) + { + SSLerr(SSL_F_SSL_GET_NEW_SESSION, ERR_R_MALLOC_FAILURE); + SSL_SESSION_free(ss); + return 0; + } + ss->tlsext_ecpointformatlist_length = s->tlsext_ecpointformatlist_length; + memcpy(ss->tlsext_ecpointformatlist, s->tlsext_ecpointformatlist, s->tlsext_ecpointformatlist_length); + } + if (s->tlsext_ellipticcurvelist) + { + if (ss->tlsext_ellipticcurvelist != NULL) OPENSSL_free(ss->tlsext_ellipticcurvelist); + if ((ss->tlsext_ellipticcurvelist = OPENSSL_malloc(s->tlsext_ellipticcurvelist_length)) == NULL) + { + SSLerr(SSL_F_SSL_GET_NEW_SESSION, ERR_R_MALLOC_FAILURE); + SSL_SESSION_free(ss); + return 0; + } + ss->tlsext_ellipticcurvelist_length = s->tlsext_ellipticcurvelist_length; + memcpy(ss->tlsext_ellipticcurvelist, s->tlsext_ellipticcurvelist, s->tlsext_ellipticcurvelist_length); + } +#endif +#endif + } + else + { + ss->session_id_length=0; + } + + if (s->sid_ctx_length > sizeof ss->sid_ctx) + { + SSLerr(SSL_F_SSL_GET_NEW_SESSION, ERR_R_INTERNAL_ERROR); + SSL_SESSION_free(ss); + return 0; + } + memcpy(ss->sid_ctx,s->sid_ctx,s->sid_ctx_length); + ss->sid_ctx_length=s->sid_ctx_length; + s->session=ss; + ss->ssl_version=s->version; + ss->verify_result = X509_V_OK; + + return(1); + } + +int ssl_get_prev_session(SSL *s, unsigned char *session_id, int len, + const unsigned char *limit) + { + /* This is used only by servers. */ + + SSL_SESSION *ret=NULL; + int fatal = 0; +#ifndef OPENSSL_NO_TLSEXT + int r; +#endif + + if (len > SSL_MAX_SSL_SESSION_ID_LENGTH) + goto err; +#ifndef OPENSSL_NO_TLSEXT + r = tls1_process_ticket(s, session_id, len, limit, &ret); + if (r == -1) + { + fatal = 1; + goto err; + } + else if (r == 0 || (!ret && !len)) + goto err; + else if (!ret && !(s->session_ctx->session_cache_mode & SSL_SESS_CACHE_NO_INTERNAL_LOOKUP)) +#else + if (len == 0) + goto err; + if (!(s->session_ctx->session_cache_mode & SSL_SESS_CACHE_NO_INTERNAL_LOOKUP)) +#endif + { + SSL_SESSION data; + data.ssl_version=s->version; + data.session_id_length=len; + if (len == 0) + return 0; + memcpy(data.session_id,session_id,len); + CRYPTO_r_lock(CRYPTO_LOCK_SSL_CTX); + ret=lh_SSL_SESSION_retrieve(s->session_ctx->sessions,&data); + if (ret != NULL) + /* don't allow other threads to steal it: */ + CRYPTO_add(&ret->references,1,CRYPTO_LOCK_SSL_SESSION); + CRYPTO_r_unlock(CRYPTO_LOCK_SSL_CTX); + } + + if (ret == NULL) + { + int copy=1; + + s->session_ctx->stats.sess_miss++; + ret=NULL; + if (s->session_ctx->get_session_cb != NULL + && (ret=s->session_ctx->get_session_cb(s,session_id,len,©)) + != NULL) + { + s->session_ctx->stats.sess_cb_hit++; + + /* Increment reference count now if the session callback + * asks us to do so (note that if the session structures + * returned by the callback are shared between threads, + * it must handle the reference count itself [i.e. copy == 0], + * or things won't be thread-safe). */ + if (copy) + CRYPTO_add(&ret->references,1,CRYPTO_LOCK_SSL_SESSION); + + /* Add the externally cached session to the internal + * cache as well if and only if we are supposed to. */ + if(!(s->session_ctx->session_cache_mode & SSL_SESS_CACHE_NO_INTERNAL_STORE)) + /* The following should not return 1, otherwise, + * things are very strange */ + SSL_CTX_add_session(s->session_ctx,ret); + } + if (ret == NULL) + goto err; + } + + /* Now ret is non-NULL, and we own one of its reference counts. */ + + if (ret->sid_ctx_length != s->sid_ctx_length + || memcmp(ret->sid_ctx,s->sid_ctx,ret->sid_ctx_length)) + { + /* We've found the session named by the client, but we don't + * want to use it in this context. */ + +#if 0 /* The client cannot always know when a session is not appropriate, + * so we shouldn't generate an error message. */ + + SSLerr(SSL_F_SSL_GET_PREV_SESSION,SSL_R_ATTEMPT_TO_REUSE_SESSION_IN_DIFFERENT_CONTEXT); +#endif + goto err; /* treat like cache miss */ + } + + if((s->verify_mode & SSL_VERIFY_PEER) && s->sid_ctx_length == 0) + { + /* We can't be sure if this session is being used out of + * context, which is especially important for SSL_VERIFY_PEER. + * The application should have used SSL[_CTX]_set_session_id_context. + * + * For this error case, we generate an error instead of treating + * the event like a cache miss (otherwise it would be easy for + * applications to effectively disable the session cache by + * accident without anyone noticing). + */ + + SSLerr(SSL_F_SSL_GET_PREV_SESSION,SSL_R_SESSION_ID_CONTEXT_UNINITIALIZED); + fatal = 1; + goto err; + } + + if (ret->cipher == NULL) + { + unsigned char buf[5],*p; + unsigned long l; + + p=buf; + l=ret->cipher_id; + l2n(l,p); + if ((ret->ssl_version>>8) >= SSL3_VERSION_MAJOR) + ret->cipher=ssl_get_cipher_by_char(s,&(buf[2])); + else + ret->cipher=ssl_get_cipher_by_char(s,&(buf[1])); + if (ret->cipher == NULL) + goto err; + } + + +#if 0 /* This is way too late. */ + + /* If a thread got the session, then 'swaped', and another got + * it and then due to a time-out decided to 'OPENSSL_free' it we could + * be in trouble. So I'll increment it now, then double decrement + * later - am I speaking rubbish?. */ + CRYPTO_add(&ret->references,1,CRYPTO_LOCK_SSL_SESSION); +#endif + + if (ret->timeout < (long)(time(NULL) - ret->time)) /* timeout */ + { + s->session_ctx->stats.sess_timeout++; + /* remove it from the cache */ + SSL_CTX_remove_session(s->session_ctx,ret); + goto err; + } + + s->session_ctx->stats.sess_hit++; + + /* ret->time=time(NULL); */ /* rezero timeout? */ + /* again, just leave the session + * if it is the same session, we have just incremented and + * then decremented the reference count :-) */ + if (s->session != NULL) + SSL_SESSION_free(s->session); + s->session=ret; + s->verify_result = s->session->verify_result; + return(1); + + err: + if (ret != NULL) + SSL_SESSION_free(ret); + if (fatal) + return -1; + else + return 0; + } + +int SSL_CTX_add_session(SSL_CTX *ctx, SSL_SESSION *c) + { + int ret=0; + SSL_SESSION *s; + + /* add just 1 reference count for the SSL_CTX's session cache + * even though it has two ways of access: each session is in a + * doubly linked list and an lhash */ + CRYPTO_add(&c->references,1,CRYPTO_LOCK_SSL_SESSION); + /* if session c is in already in cache, we take back the increment later */ + + CRYPTO_w_lock(CRYPTO_LOCK_SSL_CTX); + s=lh_SSL_SESSION_insert(ctx->sessions,c); + + /* s != NULL iff we already had a session with the given PID. + * In this case, s == c should hold (then we did not really modify + * ctx->sessions), or we're in trouble. */ + if (s != NULL && s != c) + { + /* We *are* in trouble ... */ + SSL_SESSION_list_remove(ctx,s); + SSL_SESSION_free(s); + /* ... so pretend the other session did not exist in cache + * (we cannot handle two SSL_SESSION structures with identical + * session ID in the same cache, which could happen e.g. when + * two threads concurrently obtain the same session from an external + * cache) */ + s = NULL; + } + + /* Put at the head of the queue unless it is already in the cache */ + if (s == NULL) + SSL_SESSION_list_add(ctx,c); + + if (s != NULL) + { + /* existing cache entry -- decrement previously incremented reference + * count because it already takes into account the cache */ + + SSL_SESSION_free(s); /* s == c */ + ret=0; + } + else + { + /* new cache entry -- remove old ones if cache has become too large */ + + ret=1; + + if (SSL_CTX_sess_get_cache_size(ctx) > 0) + { + while (SSL_CTX_sess_number(ctx) > + SSL_CTX_sess_get_cache_size(ctx)) + { + if (!remove_session_lock(ctx, + ctx->session_cache_tail, 0)) + break; + else + ctx->stats.sess_cache_full++; + } + } + } + CRYPTO_w_unlock(CRYPTO_LOCK_SSL_CTX); + return(ret); + } + +int SSL_CTX_remove_session(SSL_CTX *ctx, SSL_SESSION *c) +{ + return remove_session_lock(ctx, c, 1); +} + +static int remove_session_lock(SSL_CTX *ctx, SSL_SESSION *c, int lck) + { + SSL_SESSION *r; + int ret=0; + + if ((c != NULL) && (c->session_id_length != 0)) + { + if(lck) CRYPTO_w_lock(CRYPTO_LOCK_SSL_CTX); + if ((r = lh_SSL_SESSION_retrieve(ctx->sessions,c)) == c) + { + ret=1; + r=lh_SSL_SESSION_delete(ctx->sessions,c); + SSL_SESSION_list_remove(ctx,c); + } + + if(lck) CRYPTO_w_unlock(CRYPTO_LOCK_SSL_CTX); + + if (ret) + { + r->not_resumable=1; + if (ctx->remove_session_cb != NULL) + ctx->remove_session_cb(ctx,r); + SSL_SESSION_free(r); + } + } + else + ret=0; + return(ret); + } + +void SSL_SESSION_free(SSL_SESSION *ss) + { + int i; + + if(ss == NULL) + return; + + i=CRYPTO_add(&ss->references,-1,CRYPTO_LOCK_SSL_SESSION); +#ifdef REF_PRINT + REF_PRINT("SSL_SESSION",ss); +#endif + if (i > 0) return; +#ifdef REF_CHECK + if (i < 0) + { + fprintf(stderr,"SSL_SESSION_free, bad reference count\n"); + abort(); /* ok */ + } +#endif + + CRYPTO_free_ex_data(CRYPTO_EX_INDEX_SSL_SESSION, ss, &ss->ex_data); + + OPENSSL_cleanse(ss->key_arg,sizeof ss->key_arg); + OPENSSL_cleanse(ss->master_key,sizeof ss->master_key); + OPENSSL_cleanse(ss->session_id,sizeof ss->session_id); + if (ss->sess_cert != NULL) ssl_sess_cert_free(ss->sess_cert); + if (ss->peer != NULL) X509_free(ss->peer); + if (ss->ciphers != NULL) sk_SSL_CIPHER_free(ss->ciphers); +#ifndef OPENSSL_NO_TLSEXT + if (ss->tlsext_hostname != NULL) OPENSSL_free(ss->tlsext_hostname); + if (ss->tlsext_tick != NULL) OPENSSL_free(ss->tlsext_tick); +#ifndef OPENSSL_NO_EC + ss->tlsext_ecpointformatlist_length = 0; + if (ss->tlsext_ecpointformatlist != NULL) OPENSSL_free(ss->tlsext_ecpointformatlist); + ss->tlsext_ellipticcurvelist_length = 0; + if (ss->tlsext_ellipticcurvelist != NULL) OPENSSL_free(ss->tlsext_ellipticcurvelist); +#endif /* OPENSSL_NO_EC */ +#endif +#ifndef OPENSSL_NO_PSK + if (ss->psk_identity_hint != NULL) + OPENSSL_free(ss->psk_identity_hint); + if (ss->psk_identity != NULL) + OPENSSL_free(ss->psk_identity); +#endif + OPENSSL_cleanse(ss,sizeof(*ss)); + OPENSSL_free(ss); + } + +int SSL_set_session(SSL *s, SSL_SESSION *session) + { + int ret=0; + const SSL_METHOD *meth; + + if (session != NULL) + { + meth=s->ctx->method->get_ssl_method(session->ssl_version); + if (meth == NULL) + meth=s->method->get_ssl_method(session->ssl_version); + if (meth == NULL) + { + SSLerr(SSL_F_SSL_SET_SESSION,SSL_R_UNABLE_TO_FIND_SSL_METHOD); + return(0); + } + + if (meth != s->method) + { + if (!SSL_set_ssl_method(s,meth)) + return(0); + if (s->ctx->session_timeout == 0) + session->timeout=SSL_get_default_timeout(s); + else + session->timeout=s->ctx->session_timeout; + } + +#ifndef OPENSSL_NO_KRB5 + if (s->kssl_ctx && !s->kssl_ctx->client_princ && + session->krb5_client_princ_len > 0) + { + s->kssl_ctx->client_princ = (char *)OPENSSL_malloc(session->krb5_client_princ_len + 1); + memcpy(s->kssl_ctx->client_princ,session->krb5_client_princ, + session->krb5_client_princ_len); + s->kssl_ctx->client_princ[session->krb5_client_princ_len] = '\0'; + } +#endif /* OPENSSL_NO_KRB5 */ + + /* CRYPTO_w_lock(CRYPTO_LOCK_SSL);*/ + CRYPTO_add(&session->references,1,CRYPTO_LOCK_SSL_SESSION); + if (s->session != NULL) + SSL_SESSION_free(s->session); + s->session=session; + s->verify_result = s->session->verify_result; + /* CRYPTO_w_unlock(CRYPTO_LOCK_SSL);*/ + ret=1; + } + else + { + if (s->session != NULL) + { + SSL_SESSION_free(s->session); + s->session=NULL; + } + + meth=s->ctx->method; + if (meth != s->method) + { + if (!SSL_set_ssl_method(s,meth)) + return(0); + } + ret=1; + } + return(ret); + } + +long SSL_SESSION_set_timeout(SSL_SESSION *s, long t) + { + if (s == NULL) return(0); + s->timeout=t; + return(1); + } + +long SSL_SESSION_get_timeout(const SSL_SESSION *s) + { + if (s == NULL) return(0); + return(s->timeout); + } + +long SSL_SESSION_get_time(const SSL_SESSION *s) + { + if (s == NULL) return(0); + return(s->time); + } + +long SSL_SESSION_set_time(SSL_SESSION *s, long t) + { + if (s == NULL) return(0); + s->time=t; + return(t); + } + +long SSL_CTX_set_timeout(SSL_CTX *s, long t) + { + long l; + if (s == NULL) return(0); + l=s->session_timeout; + s->session_timeout=t; + return(l); + } + +long SSL_CTX_get_timeout(const SSL_CTX *s) + { + if (s == NULL) return(0); + return(s->session_timeout); + } + +#ifndef OPENSSL_NO_TLSEXT +int SSL_set_session_secret_cb(SSL *s, int (*tls_session_secret_cb)(SSL *s, void *secret, int *secret_len, + STACK_OF(SSL_CIPHER) *peer_ciphers, SSL_CIPHER **cipher, void *arg), void *arg) + { + if (s == NULL) return(0); + s->tls_session_secret_cb = tls_session_secret_cb; + s->tls_session_secret_cb_arg = arg; + return(1); + } + +int SSL_set_session_ticket_ext_cb(SSL *s, tls_session_ticket_ext_cb_fn cb, + void *arg) + { + if (s == NULL) return(0); + s->tls_session_ticket_ext_cb = cb; + s->tls_session_ticket_ext_cb_arg = arg; + return(1); + } + +int SSL_set_session_ticket_ext(SSL *s, void *ext_data, int ext_len) + { + if (s->version >= TLS1_VERSION) + { + if (s->tlsext_session_ticket) + { + OPENSSL_free(s->tlsext_session_ticket); + s->tlsext_session_ticket = NULL; + } + + s->tlsext_session_ticket = OPENSSL_malloc(sizeof(TLS_SESSION_TICKET_EXT) + ext_len); + if (!s->tlsext_session_ticket) + { + SSLerr(SSL_F_SSL_SET_SESSION_TICKET_EXT, ERR_R_MALLOC_FAILURE); + return 0; + } + + if (ext_data) + { + s->tlsext_session_ticket->length = ext_len; + s->tlsext_session_ticket->data = s->tlsext_session_ticket + 1; + memcpy(s->tlsext_session_ticket->data, ext_data, ext_len); + } + else + { + s->tlsext_session_ticket->length = 0; + s->tlsext_session_ticket->data = NULL; + } + + return 1; + } + + return 0; + } +#endif /* OPENSSL_NO_TLSEXT */ + +typedef struct timeout_param_st + { + SSL_CTX *ctx; + long time; + LHASH_OF(SSL_SESSION) *cache; + } TIMEOUT_PARAM; + +static void timeout_doall_arg(SSL_SESSION *s, TIMEOUT_PARAM *p) + { + if ((p->time == 0) || (p->time > (s->time+s->timeout))) /* timeout */ + { + /* The reason we don't call SSL_CTX_remove_session() is to + * save on locking overhead */ + (void)lh_SSL_SESSION_delete(p->cache,s); + SSL_SESSION_list_remove(p->ctx,s); + s->not_resumable=1; + if (p->ctx->remove_session_cb != NULL) + p->ctx->remove_session_cb(p->ctx,s); + SSL_SESSION_free(s); + } + } + +static IMPLEMENT_LHASH_DOALL_ARG_FN(timeout, SSL_SESSION, TIMEOUT_PARAM) + +void SSL_CTX_flush_sessions(SSL_CTX *s, long t) + { + unsigned long i; + TIMEOUT_PARAM tp; + + tp.ctx=s; + tp.cache=s->sessions; + if (tp.cache == NULL) return; + tp.time=t; + CRYPTO_w_lock(CRYPTO_LOCK_SSL_CTX); + i=CHECKED_LHASH_OF(SSL_SESSION, tp.cache)->down_load; + CHECKED_LHASH_OF(SSL_SESSION, tp.cache)->down_load=0; + lh_SSL_SESSION_doall_arg(tp.cache, LHASH_DOALL_ARG_FN(timeout), + TIMEOUT_PARAM, &tp); + CHECKED_LHASH_OF(SSL_SESSION, tp.cache)->down_load=i; + CRYPTO_w_unlock(CRYPTO_LOCK_SSL_CTX); + } + +int ssl_clear_bad_session(SSL *s) + { + if ( (s->session != NULL) && + !(s->shutdown & SSL_SENT_SHUTDOWN) && + !(SSL_in_init(s) || SSL_in_before(s))) + { + SSL_CTX_remove_session(s->ctx,s->session); + return(1); + } + else + return(0); + } + +/* locked by SSL_CTX in the calling function */ +static void SSL_SESSION_list_remove(SSL_CTX *ctx, SSL_SESSION *s) + { + if ((s->next == NULL) || (s->prev == NULL)) return; + + if (s->next == (SSL_SESSION *)&(ctx->session_cache_tail)) + { /* last element in list */ + if (s->prev == (SSL_SESSION *)&(ctx->session_cache_head)) + { /* only one element in list */ + ctx->session_cache_head=NULL; + ctx->session_cache_tail=NULL; + } + else + { + ctx->session_cache_tail=s->prev; + s->prev->next=(SSL_SESSION *)&(ctx->session_cache_tail); + } + } + else + { + if (s->prev == (SSL_SESSION *)&(ctx->session_cache_head)) + { /* first element in list */ + ctx->session_cache_head=s->next; + s->next->prev=(SSL_SESSION *)&(ctx->session_cache_head); + } + else + { /* middle of list */ + s->next->prev=s->prev; + s->prev->next=s->next; + } + } + s->prev=s->next=NULL; + } + +static void SSL_SESSION_list_add(SSL_CTX *ctx, SSL_SESSION *s) + { + if ((s->next != NULL) && (s->prev != NULL)) + SSL_SESSION_list_remove(ctx,s); + + if (ctx->session_cache_head == NULL) + { + ctx->session_cache_head=s; + ctx->session_cache_tail=s; + s->prev=(SSL_SESSION *)&(ctx->session_cache_head); + s->next=(SSL_SESSION *)&(ctx->session_cache_tail); + } + else + { + s->next=ctx->session_cache_head; + s->next->prev=s; + s->prev=(SSL_SESSION *)&(ctx->session_cache_head); + ctx->session_cache_head=s; + } + } + +void SSL_CTX_sess_set_new_cb(SSL_CTX *ctx, + int (*cb)(struct ssl_st *ssl,SSL_SESSION *sess)) + { + ctx->new_session_cb=cb; + } + +int (*SSL_CTX_sess_get_new_cb(SSL_CTX *ctx))(SSL *ssl, SSL_SESSION *sess) + { + return ctx->new_session_cb; + } + +void SSL_CTX_sess_set_remove_cb(SSL_CTX *ctx, + void (*cb)(SSL_CTX *ctx,SSL_SESSION *sess)) + { + ctx->remove_session_cb=cb; + } + +void (*SSL_CTX_sess_get_remove_cb(SSL_CTX *ctx))(SSL_CTX * ctx,SSL_SESSION *sess) + { + return ctx->remove_session_cb; + } + +void SSL_CTX_sess_set_get_cb(SSL_CTX *ctx, + SSL_SESSION *(*cb)(struct ssl_st *ssl, + unsigned char *data,int len,int *copy)) + { + ctx->get_session_cb=cb; + } + +SSL_SESSION * (*SSL_CTX_sess_get_get_cb(SSL_CTX *ctx))(SSL *ssl, + unsigned char *data,int len,int *copy) + { + return ctx->get_session_cb; + } + +void SSL_CTX_set_info_callback(SSL_CTX *ctx, + void (*cb)(const SSL *ssl,int type,int val)) + { + ctx->info_callback=cb; + } + +void (*SSL_CTX_get_info_callback(SSL_CTX *ctx))(const SSL *ssl,int type,int val) + { + return ctx->info_callback; + } + +void SSL_CTX_set_client_cert_cb(SSL_CTX *ctx, + int (*cb)(SSL *ssl, X509 **x509, EVP_PKEY **pkey)) + { + ctx->client_cert_cb=cb; + } + +int (*SSL_CTX_get_client_cert_cb(SSL_CTX *ctx))(SSL * ssl, X509 ** x509 , EVP_PKEY **pkey) + { + return ctx->client_cert_cb; + } + +#ifndef OPENSSL_NO_ENGINE +int SSL_CTX_set_client_cert_engine(SSL_CTX *ctx, ENGINE *e) + { + if (!ENGINE_init(e)) + { + SSLerr(SSL_F_SSL_CTX_SET_CLIENT_CERT_ENGINE, ERR_R_ENGINE_LIB); + return 0; + } + if(!ENGINE_get_ssl_client_cert_function(e)) + { + SSLerr(SSL_F_SSL_CTX_SET_CLIENT_CERT_ENGINE, SSL_R_NO_CLIENT_CERT_METHOD); + ENGINE_finish(e); + return 0; + } + ctx->client_cert_engine = e; + return 1; + } +#endif + +void SSL_CTX_set_cookie_generate_cb(SSL_CTX *ctx, + int (*cb)(SSL *ssl, unsigned char *cookie, unsigned int *cookie_len)) + { + ctx->app_gen_cookie_cb=cb; + } + +void SSL_CTX_set_cookie_verify_cb(SSL_CTX *ctx, + int (*cb)(SSL *ssl, unsigned char *cookie, unsigned int cookie_len)) + { + ctx->app_verify_cookie_cb=cb; + } + +IMPLEMENT_PEM_rw(SSL_SESSION, SSL_SESSION, PEM_STRING_SSL_SESSION, SSL_SESSION) diff --git a/node-v0.8.14/deps/openssl/openssl/ssl/ssl_stat.c b/node-v0.8.14/deps/openssl/openssl/ssl/ssl_stat.c new file mode 100644 index 0000000..144b81e --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/ssl/ssl_stat.c @@ -0,0 +1,567 @@ +/* ssl/ssl_stat.c */ +/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com) + * All rights reserved. + * + * This package is an SSL implementation written + * by Eric Young (eay@cryptsoft.com). + * The implementation was written so as to conform with Netscapes SSL. + * + * This library is free for commercial and non-commercial use as long as + * the following conditions are aheared to. The following conditions + * apply to all code found in this distribution, be it the RC4, RSA, + * lhash, DES, etc., code; not just the SSL code. The SSL documentation + * included with this distribution is covered by the same copyright terms + * except that the holder is Tim Hudson (tjh@cryptsoft.com). + * + * Copyright remains Eric Young's, and as such any Copyright notices in + * the code are not to be removed. + * If this package is used in a product, Eric Young should be given attribution + * as the author of the parts of the library used. + * This can be in the form of a textual message at program startup or + * in documentation (online or textual) provided with the package. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * "This product includes cryptographic software written by + * Eric Young (eay@cryptsoft.com)" + * The word 'cryptographic' can be left out if the rouines from the library + * being used are not cryptographic related :-). + * 4. If you include any Windows specific code (or a derivative thereof) from + * the apps directory (application code) you must include an acknowledgement: + * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)" + * + * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * + * The licence and distribution terms for any publically available version or + * derivative of this code cannot be changed. i.e. this code cannot simply be + * copied and put under another distribution licence + * [including the GNU Public Licence.] + */ +/* ==================================================================== + * Copyright 2005 Nokia. All rights reserved. + * + * The portions of the attached software ("Contribution") is developed by + * Nokia Corporation and is licensed pursuant to the OpenSSL open source + * license. + * + * The Contribution, originally written by Mika Kousa and Pasi Eronen of + * Nokia Corporation, consists of the "PSK" (Pre-Shared Key) ciphersuites + * support (see RFC 4279) to OpenSSL. + * + * No patent licenses or other rights except those expressly stated in + * the OpenSSL open source license shall be deemed granted or received + * expressly, by implication, estoppel, or otherwise. + * + * No assurances are provided by Nokia that the Contribution does not + * infringe the patent or other intellectual property rights of any third + * party or that the license provides you with all the necessary rights + * to make use of the Contribution. + * + * THE SOFTWARE IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND. IN + * ADDITION TO THE DISCLAIMERS INCLUDED IN THE LICENSE, NOKIA + * SPECIFICALLY DISCLAIMS ANY LIABILITY FOR CLAIMS BROUGHT BY YOU OR ANY + * OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL PROPERTY RIGHTS OR + * OTHERWISE. + */ + +#include +#include "ssl_locl.h" + +const char *SSL_state_string_long(const SSL *s) + { + const char *str; + + switch (s->state) + { +case SSL_ST_BEFORE: str="before SSL initialization"; break; +case SSL_ST_ACCEPT: str="before accept initialization"; break; +case SSL_ST_CONNECT: str="before connect initialization"; break; +case SSL_ST_OK: str="SSL negotiation finished successfully"; break; +case SSL_ST_RENEGOTIATE: str="SSL renegotiate ciphers"; break; +case SSL_ST_BEFORE|SSL_ST_CONNECT: str="before/connect initialization"; break; +case SSL_ST_OK|SSL_ST_CONNECT: str="ok/connect SSL initialization"; break; +case SSL_ST_BEFORE|SSL_ST_ACCEPT: str="before/accept initialization"; break; +case SSL_ST_OK|SSL_ST_ACCEPT: str="ok/accept SSL initialization"; break; +#ifndef OPENSSL_NO_SSL2 +case SSL2_ST_CLIENT_START_ENCRYPTION: str="SSLv2 client start encryption"; break; +case SSL2_ST_SERVER_START_ENCRYPTION: str="SSLv2 server start encryption"; break; +case SSL2_ST_SEND_CLIENT_HELLO_A: str="SSLv2 write client hello A"; break; +case SSL2_ST_SEND_CLIENT_HELLO_B: str="SSLv2 write client hello B"; break; +case SSL2_ST_GET_SERVER_HELLO_A: str="SSLv2 read server hello A"; break; +case SSL2_ST_GET_SERVER_HELLO_B: str="SSLv2 read server hello B"; break; +case SSL2_ST_SEND_CLIENT_MASTER_KEY_A: str="SSLv2 write client master key A"; break; +case SSL2_ST_SEND_CLIENT_MASTER_KEY_B: str="SSLv2 write client master key B"; break; +case SSL2_ST_SEND_CLIENT_FINISHED_A: str="SSLv2 write client finished A"; break; +case SSL2_ST_SEND_CLIENT_FINISHED_B: str="SSLv2 write client finished B"; break; +case SSL2_ST_SEND_CLIENT_CERTIFICATE_A: str="SSLv2 write client certificate A"; break; +case SSL2_ST_SEND_CLIENT_CERTIFICATE_B: str="SSLv2 write client certificate B"; break; +case SSL2_ST_SEND_CLIENT_CERTIFICATE_C: str="SSLv2 write client certificate C"; break; +case SSL2_ST_SEND_CLIENT_CERTIFICATE_D: str="SSLv2 write client certificate D"; break; +case SSL2_ST_GET_SERVER_VERIFY_A: str="SSLv2 read server verify A"; break; +case SSL2_ST_GET_SERVER_VERIFY_B: str="SSLv2 read server verify B"; break; +case SSL2_ST_GET_SERVER_FINISHED_A: str="SSLv2 read server finished A"; break; +case SSL2_ST_GET_SERVER_FINISHED_B: str="SSLv2 read server finished B"; break; +case SSL2_ST_GET_CLIENT_HELLO_A: str="SSLv2 read client hello A"; break; +case SSL2_ST_GET_CLIENT_HELLO_B: str="SSLv2 read client hello B"; break; +case SSL2_ST_GET_CLIENT_HELLO_C: str="SSLv2 read client hello C"; break; +case SSL2_ST_SEND_SERVER_HELLO_A: str="SSLv2 write server hello A"; break; +case SSL2_ST_SEND_SERVER_HELLO_B: str="SSLv2 write server hello B"; break; +case SSL2_ST_GET_CLIENT_MASTER_KEY_A: str="SSLv2 read client master key A"; break; +case SSL2_ST_GET_CLIENT_MASTER_KEY_B: str="SSLv2 read client master key B"; break; +case SSL2_ST_SEND_SERVER_VERIFY_A: str="SSLv2 write server verify A"; break; +case SSL2_ST_SEND_SERVER_VERIFY_B: str="SSLv2 write server verify B"; break; +case SSL2_ST_SEND_SERVER_VERIFY_C: str="SSLv2 write server verify C"; break; +case SSL2_ST_GET_CLIENT_FINISHED_A: str="SSLv2 read client finished A"; break; +case SSL2_ST_GET_CLIENT_FINISHED_B: str="SSLv2 read client finished B"; break; +case SSL2_ST_SEND_SERVER_FINISHED_A: str="SSLv2 write server finished A"; break; +case SSL2_ST_SEND_SERVER_FINISHED_B: str="SSLv2 write server finished B"; break; +case SSL2_ST_SEND_REQUEST_CERTIFICATE_A: str="SSLv2 write request certificate A"; break; +case SSL2_ST_SEND_REQUEST_CERTIFICATE_B: str="SSLv2 write request certificate B"; break; +case SSL2_ST_SEND_REQUEST_CERTIFICATE_C: str="SSLv2 write request certificate C"; break; +case SSL2_ST_SEND_REQUEST_CERTIFICATE_D: str="SSLv2 write request certificate D"; break; +case SSL2_ST_X509_GET_SERVER_CERTIFICATE: str="SSLv2 X509 read server certificate"; break; +case SSL2_ST_X509_GET_CLIENT_CERTIFICATE: str="SSLv2 X509 read client certificate"; break; +#endif + +#ifndef OPENSSL_NO_SSL3 +/* SSLv3 additions */ +case SSL3_ST_CW_CLNT_HELLO_A: str="SSLv3 write client hello A"; break; +case SSL3_ST_CW_CLNT_HELLO_B: str="SSLv3 write client hello B"; break; +case SSL3_ST_CR_SRVR_HELLO_A: str="SSLv3 read server hello A"; break; +case SSL3_ST_CR_SRVR_HELLO_B: str="SSLv3 read server hello B"; break; +case SSL3_ST_CR_CERT_A: str="SSLv3 read server certificate A"; break; +case SSL3_ST_CR_CERT_B: str="SSLv3 read server certificate B"; break; +case SSL3_ST_CR_KEY_EXCH_A: str="SSLv3 read server key exchange A"; break; +case SSL3_ST_CR_KEY_EXCH_B: str="SSLv3 read server key exchange B"; break; +case SSL3_ST_CR_CERT_REQ_A: str="SSLv3 read server certificate request A"; break; +case SSL3_ST_CR_CERT_REQ_B: str="SSLv3 read server certificate request B"; break; +case SSL3_ST_CR_SESSION_TICKET_A: str="SSLv3 read server session ticket A";break; +case SSL3_ST_CR_SESSION_TICKET_B: str="SSLv3 read server session ticket B";break; +case SSL3_ST_CR_SRVR_DONE_A: str="SSLv3 read server done A"; break; +case SSL3_ST_CR_SRVR_DONE_B: str="SSLv3 read server done B"; break; +case SSL3_ST_CW_CERT_A: str="SSLv3 write client certificate A"; break; +case SSL3_ST_CW_CERT_B: str="SSLv3 write client certificate B"; break; +case SSL3_ST_CW_CERT_C: str="SSLv3 write client certificate C"; break; +case SSL3_ST_CW_CERT_D: str="SSLv3 write client certificate D"; break; +case SSL3_ST_CW_KEY_EXCH_A: str="SSLv3 write client key exchange A"; break; +case SSL3_ST_CW_KEY_EXCH_B: str="SSLv3 write client key exchange B"; break; +case SSL3_ST_CW_CERT_VRFY_A: str="SSLv3 write certificate verify A"; break; +case SSL3_ST_CW_CERT_VRFY_B: str="SSLv3 write certificate verify B"; break; + +case SSL3_ST_CW_CHANGE_A: +case SSL3_ST_SW_CHANGE_A: str="SSLv3 write change cipher spec A"; break; +case SSL3_ST_CW_CHANGE_B: +case SSL3_ST_SW_CHANGE_B: str="SSLv3 write change cipher spec B"; break; +case SSL3_ST_CW_FINISHED_A: +case SSL3_ST_SW_FINISHED_A: str="SSLv3 write finished A"; break; +case SSL3_ST_CW_FINISHED_B: +case SSL3_ST_SW_FINISHED_B: str="SSLv3 write finished B"; break; +case SSL3_ST_CR_CHANGE_A: +case SSL3_ST_SR_CHANGE_A: str="SSLv3 read change cipher spec A"; break; +case SSL3_ST_CR_CHANGE_B: +case SSL3_ST_SR_CHANGE_B: str="SSLv3 read change cipher spec B"; break; +case SSL3_ST_CR_FINISHED_A: +case SSL3_ST_SR_FINISHED_A: str="SSLv3 read finished A"; break; +case SSL3_ST_CR_FINISHED_B: +case SSL3_ST_SR_FINISHED_B: str="SSLv3 read finished B"; break; + +case SSL3_ST_CW_FLUSH: +case SSL3_ST_SW_FLUSH: str="SSLv3 flush data"; break; + +case SSL3_ST_SR_CLNT_HELLO_A: str="SSLv3 read client hello A"; break; +case SSL3_ST_SR_CLNT_HELLO_B: str="SSLv3 read client hello B"; break; +case SSL3_ST_SR_CLNT_HELLO_C: str="SSLv3 read client hello C"; break; +case SSL3_ST_SW_HELLO_REQ_A: str="SSLv3 write hello request A"; break; +case SSL3_ST_SW_HELLO_REQ_B: str="SSLv3 write hello request B"; break; +case SSL3_ST_SW_HELLO_REQ_C: str="SSLv3 write hello request C"; break; +case SSL3_ST_SW_SRVR_HELLO_A: str="SSLv3 write server hello A"; break; +case SSL3_ST_SW_SRVR_HELLO_B: str="SSLv3 write server hello B"; break; +case SSL3_ST_SW_CERT_A: str="SSLv3 write certificate A"; break; +case SSL3_ST_SW_CERT_B: str="SSLv3 write certificate B"; break; +case SSL3_ST_SW_KEY_EXCH_A: str="SSLv3 write key exchange A"; break; +case SSL3_ST_SW_KEY_EXCH_B: str="SSLv3 write key exchange B"; break; +case SSL3_ST_SW_CERT_REQ_A: str="SSLv3 write certificate request A"; break; +case SSL3_ST_SW_CERT_REQ_B: str="SSLv3 write certificate request B"; break; +case SSL3_ST_SW_SESSION_TICKET_A: str="SSLv3 write session ticket A"; break; +case SSL3_ST_SW_SESSION_TICKET_B: str="SSLv3 write session ticket B"; break; +case SSL3_ST_SW_SRVR_DONE_A: str="SSLv3 write server done A"; break; +case SSL3_ST_SW_SRVR_DONE_B: str="SSLv3 write server done B"; break; +case SSL3_ST_SR_CERT_A: str="SSLv3 read client certificate A"; break; +case SSL3_ST_SR_CERT_B: str="SSLv3 read client certificate B"; break; +case SSL3_ST_SR_KEY_EXCH_A: str="SSLv3 read client key exchange A"; break; +case SSL3_ST_SR_KEY_EXCH_B: str="SSLv3 read client key exchange B"; break; +case SSL3_ST_SR_CERT_VRFY_A: str="SSLv3 read certificate verify A"; break; +case SSL3_ST_SR_CERT_VRFY_B: str="SSLv3 read certificate verify B"; break; +#endif + +#if !defined(OPENSSL_NO_SSL2) && !defined(OPENSSL_NO_SSL3) +/* SSLv2/v3 compatibility states */ +/* client */ +case SSL23_ST_CW_CLNT_HELLO_A: str="SSLv2/v3 write client hello A"; break; +case SSL23_ST_CW_CLNT_HELLO_B: str="SSLv2/v3 write client hello B"; break; +case SSL23_ST_CR_SRVR_HELLO_A: str="SSLv2/v3 read server hello A"; break; +case SSL23_ST_CR_SRVR_HELLO_B: str="SSLv2/v3 read server hello B"; break; +/* server */ +case SSL23_ST_SR_CLNT_HELLO_A: str="SSLv2/v3 read client hello A"; break; +case SSL23_ST_SR_CLNT_HELLO_B: str="SSLv2/v3 read client hello B"; break; +#endif + +/* DTLS */ +case DTLS1_ST_CR_HELLO_VERIFY_REQUEST_A: str="DTLS1 read hello verify request A"; break; +case DTLS1_ST_CR_HELLO_VERIFY_REQUEST_B: str="DTLS1 read hello verify request B"; break; +case DTLS1_ST_SW_HELLO_VERIFY_REQUEST_A: str="DTLS1 write hello verify request A"; break; +case DTLS1_ST_SW_HELLO_VERIFY_REQUEST_B: str="DTLS1 write hello verify request B"; break; + +default: str="unknown state"; break; + } + return(str); + } + +const char *SSL_rstate_string_long(const SSL *s) + { + const char *str; + + switch (s->rstate) + { + case SSL_ST_READ_HEADER: str="read header"; break; + case SSL_ST_READ_BODY: str="read body"; break; + case SSL_ST_READ_DONE: str="read done"; break; + default: str="unknown"; break; + } + return(str); + } + +const char *SSL_state_string(const SSL *s) + { + const char *str; + + switch (s->state) + { +case SSL_ST_BEFORE: str="PINIT "; break; +case SSL_ST_ACCEPT: str="AINIT "; break; +case SSL_ST_CONNECT: str="CINIT "; break; +case SSL_ST_OK: str="SSLOK "; break; +#ifndef OPENSSL_NO_SSL2 +case SSL2_ST_CLIENT_START_ENCRYPTION: str="2CSENC"; break; +case SSL2_ST_SERVER_START_ENCRYPTION: str="2SSENC"; break; +case SSL2_ST_SEND_CLIENT_HELLO_A: str="2SCH_A"; break; +case SSL2_ST_SEND_CLIENT_HELLO_B: str="2SCH_B"; break; +case SSL2_ST_GET_SERVER_HELLO_A: str="2GSH_A"; break; +case SSL2_ST_GET_SERVER_HELLO_B: str="2GSH_B"; break; +case SSL2_ST_SEND_CLIENT_MASTER_KEY_A: str="2SCMKA"; break; +case SSL2_ST_SEND_CLIENT_MASTER_KEY_B: str="2SCMKB"; break; +case SSL2_ST_SEND_CLIENT_FINISHED_A: str="2SCF_A"; break; +case SSL2_ST_SEND_CLIENT_FINISHED_B: str="2SCF_B"; break; +case SSL2_ST_SEND_CLIENT_CERTIFICATE_A: str="2SCC_A"; break; +case SSL2_ST_SEND_CLIENT_CERTIFICATE_B: str="2SCC_B"; break; +case SSL2_ST_SEND_CLIENT_CERTIFICATE_C: str="2SCC_C"; break; +case SSL2_ST_SEND_CLIENT_CERTIFICATE_D: str="2SCC_D"; break; +case SSL2_ST_GET_SERVER_VERIFY_A: str="2GSV_A"; break; +case SSL2_ST_GET_SERVER_VERIFY_B: str="2GSV_B"; break; +case SSL2_ST_GET_SERVER_FINISHED_A: str="2GSF_A"; break; +case SSL2_ST_GET_SERVER_FINISHED_B: str="2GSF_B"; break; +case SSL2_ST_GET_CLIENT_HELLO_A: str="2GCH_A"; break; +case SSL2_ST_GET_CLIENT_HELLO_B: str="2GCH_B"; break; +case SSL2_ST_GET_CLIENT_HELLO_C: str="2GCH_C"; break; +case SSL2_ST_SEND_SERVER_HELLO_A: str="2SSH_A"; break; +case SSL2_ST_SEND_SERVER_HELLO_B: str="2SSH_B"; break; +case SSL2_ST_GET_CLIENT_MASTER_KEY_A: str="2GCMKA"; break; +case SSL2_ST_GET_CLIENT_MASTER_KEY_B: str="2GCMKA"; break; +case SSL2_ST_SEND_SERVER_VERIFY_A: str="2SSV_A"; break; +case SSL2_ST_SEND_SERVER_VERIFY_B: str="2SSV_B"; break; +case SSL2_ST_SEND_SERVER_VERIFY_C: str="2SSV_C"; break; +case SSL2_ST_GET_CLIENT_FINISHED_A: str="2GCF_A"; break; +case SSL2_ST_GET_CLIENT_FINISHED_B: str="2GCF_B"; break; +case SSL2_ST_SEND_SERVER_FINISHED_A: str="2SSF_A"; break; +case SSL2_ST_SEND_SERVER_FINISHED_B: str="2SSF_B"; break; +case SSL2_ST_SEND_REQUEST_CERTIFICATE_A: str="2SRC_A"; break; +case SSL2_ST_SEND_REQUEST_CERTIFICATE_B: str="2SRC_B"; break; +case SSL2_ST_SEND_REQUEST_CERTIFICATE_C: str="2SRC_C"; break; +case SSL2_ST_SEND_REQUEST_CERTIFICATE_D: str="2SRC_D"; break; +case SSL2_ST_X509_GET_SERVER_CERTIFICATE: str="2X9GSC"; break; +case SSL2_ST_X509_GET_CLIENT_CERTIFICATE: str="2X9GCC"; break; +#endif + +#ifndef OPENSSL_NO_SSL3 +/* SSLv3 additions */ +case SSL3_ST_SW_FLUSH: +case SSL3_ST_CW_FLUSH: str="3FLUSH"; break; +case SSL3_ST_CW_CLNT_HELLO_A: str="3WCH_A"; break; +case SSL3_ST_CW_CLNT_HELLO_B: str="3WCH_B"; break; +case SSL3_ST_CR_SRVR_HELLO_A: str="3RSH_A"; break; +case SSL3_ST_CR_SRVR_HELLO_B: str="3RSH_B"; break; +case SSL3_ST_CR_CERT_A: str="3RSC_A"; break; +case SSL3_ST_CR_CERT_B: str="3RSC_B"; break; +case SSL3_ST_CR_KEY_EXCH_A: str="3RSKEA"; break; +case SSL3_ST_CR_KEY_EXCH_B: str="3RSKEB"; break; +case SSL3_ST_CR_CERT_REQ_A: str="3RCR_A"; break; +case SSL3_ST_CR_CERT_REQ_B: str="3RCR_B"; break; +case SSL3_ST_CR_SRVR_DONE_A: str="3RSD_A"; break; +case SSL3_ST_CR_SRVR_DONE_B: str="3RSD_B"; break; +case SSL3_ST_CW_CERT_A: str="3WCC_A"; break; +case SSL3_ST_CW_CERT_B: str="3WCC_B"; break; +case SSL3_ST_CW_CERT_C: str="3WCC_C"; break; +case SSL3_ST_CW_CERT_D: str="3WCC_D"; break; +case SSL3_ST_CW_KEY_EXCH_A: str="3WCKEA"; break; +case SSL3_ST_CW_KEY_EXCH_B: str="3WCKEB"; break; +case SSL3_ST_CW_CERT_VRFY_A: str="3WCV_A"; break; +case SSL3_ST_CW_CERT_VRFY_B: str="3WCV_B"; break; + +case SSL3_ST_SW_CHANGE_A: +case SSL3_ST_CW_CHANGE_A: str="3WCCSA"; break; +case SSL3_ST_SW_CHANGE_B: +case SSL3_ST_CW_CHANGE_B: str="3WCCSB"; break; +case SSL3_ST_SW_FINISHED_A: +case SSL3_ST_CW_FINISHED_A: str="3WFINA"; break; +case SSL3_ST_SW_FINISHED_B: +case SSL3_ST_CW_FINISHED_B: str="3WFINB"; break; +case SSL3_ST_SR_CHANGE_A: +case SSL3_ST_CR_CHANGE_A: str="3RCCSA"; break; +case SSL3_ST_SR_CHANGE_B: +case SSL3_ST_CR_CHANGE_B: str="3RCCSB"; break; +case SSL3_ST_SR_FINISHED_A: +case SSL3_ST_CR_FINISHED_A: str="3RFINA"; break; +case SSL3_ST_SR_FINISHED_B: +case SSL3_ST_CR_FINISHED_B: str="3RFINB"; break; + +case SSL3_ST_SW_HELLO_REQ_A: str="3WHR_A"; break; +case SSL3_ST_SW_HELLO_REQ_B: str="3WHR_B"; break; +case SSL3_ST_SW_HELLO_REQ_C: str="3WHR_C"; break; +case SSL3_ST_SR_CLNT_HELLO_A: str="3RCH_A"; break; +case SSL3_ST_SR_CLNT_HELLO_B: str="3RCH_B"; break; +case SSL3_ST_SR_CLNT_HELLO_C: str="3RCH_C"; break; +case SSL3_ST_SW_SRVR_HELLO_A: str="3WSH_A"; break; +case SSL3_ST_SW_SRVR_HELLO_B: str="3WSH_B"; break; +case SSL3_ST_SW_CERT_A: str="3WSC_A"; break; +case SSL3_ST_SW_CERT_B: str="3WSC_B"; break; +case SSL3_ST_SW_KEY_EXCH_A: str="3WSKEA"; break; +case SSL3_ST_SW_KEY_EXCH_B: str="3WSKEB"; break; +case SSL3_ST_SW_CERT_REQ_A: str="3WCR_A"; break; +case SSL3_ST_SW_CERT_REQ_B: str="3WCR_B"; break; +case SSL3_ST_SW_SRVR_DONE_A: str="3WSD_A"; break; +case SSL3_ST_SW_SRVR_DONE_B: str="3WSD_B"; break; +case SSL3_ST_SR_CERT_A: str="3RCC_A"; break; +case SSL3_ST_SR_CERT_B: str="3RCC_B"; break; +case SSL3_ST_SR_KEY_EXCH_A: str="3RCKEA"; break; +case SSL3_ST_SR_KEY_EXCH_B: str="3RCKEB"; break; +case SSL3_ST_SR_CERT_VRFY_A: str="3RCV_A"; break; +case SSL3_ST_SR_CERT_VRFY_B: str="3RCV_B"; break; +#endif + +#if !defined(OPENSSL_NO_SSL2) && !defined(OPENSSL_NO_SSL3) +/* SSLv2/v3 compatibility states */ +/* client */ +case SSL23_ST_CW_CLNT_HELLO_A: str="23WCHA"; break; +case SSL23_ST_CW_CLNT_HELLO_B: str="23WCHB"; break; +case SSL23_ST_CR_SRVR_HELLO_A: str="23RSHA"; break; +case SSL23_ST_CR_SRVR_HELLO_B: str="23RSHA"; break; +/* server */ +case SSL23_ST_SR_CLNT_HELLO_A: str="23RCHA"; break; +case SSL23_ST_SR_CLNT_HELLO_B: str="23RCHB"; break; +#endif +/* DTLS */ +case DTLS1_ST_CR_HELLO_VERIFY_REQUEST_A: str="DRCHVA"; break; +case DTLS1_ST_CR_HELLO_VERIFY_REQUEST_B: str="DRCHVB"; break; +case DTLS1_ST_SW_HELLO_VERIFY_REQUEST_A: str="DWCHVA"; break; +case DTLS1_ST_SW_HELLO_VERIFY_REQUEST_B: str="DWCHVB"; break; + +default: str="UNKWN "; break; + } + return(str); + } + +const char *SSL_alert_type_string_long(int value) + { + value>>=8; + if (value == SSL3_AL_WARNING) + return("warning"); + else if (value == SSL3_AL_FATAL) + return("fatal"); + else + return("unknown"); + } + +const char *SSL_alert_type_string(int value) + { + value>>=8; + if (value == SSL3_AL_WARNING) + return("W"); + else if (value == SSL3_AL_FATAL) + return("F"); + else + return("U"); + } + +const char *SSL_alert_desc_string(int value) + { + const char *str; + + switch (value & 0xff) + { + case SSL3_AD_CLOSE_NOTIFY: str="CN"; break; + case SSL3_AD_UNEXPECTED_MESSAGE: str="UM"; break; + case SSL3_AD_BAD_RECORD_MAC: str="BM"; break; + case SSL3_AD_DECOMPRESSION_FAILURE: str="DF"; break; + case SSL3_AD_HANDSHAKE_FAILURE: str="HF"; break; + case SSL3_AD_NO_CERTIFICATE: str="NC"; break; + case SSL3_AD_BAD_CERTIFICATE: str="BC"; break; + case SSL3_AD_UNSUPPORTED_CERTIFICATE: str="UC"; break; + case SSL3_AD_CERTIFICATE_REVOKED: str="CR"; break; + case SSL3_AD_CERTIFICATE_EXPIRED: str="CE"; break; + case SSL3_AD_CERTIFICATE_UNKNOWN: str="CU"; break; + case SSL3_AD_ILLEGAL_PARAMETER: str="IP"; break; + case TLS1_AD_DECRYPTION_FAILED: str="DC"; break; + case TLS1_AD_RECORD_OVERFLOW: str="RO"; break; + case TLS1_AD_UNKNOWN_CA: str="CA"; break; + case TLS1_AD_ACCESS_DENIED: str="AD"; break; + case TLS1_AD_DECODE_ERROR: str="DE"; break; + case TLS1_AD_DECRYPT_ERROR: str="CY"; break; + case TLS1_AD_EXPORT_RESTRICTION: str="ER"; break; + case TLS1_AD_PROTOCOL_VERSION: str="PV"; break; + case TLS1_AD_INSUFFICIENT_SECURITY: str="IS"; break; + case TLS1_AD_INTERNAL_ERROR: str="IE"; break; + case TLS1_AD_USER_CANCELLED: str="US"; break; + case TLS1_AD_NO_RENEGOTIATION: str="NR"; break; + case TLS1_AD_UNSUPPORTED_EXTENSION: str="UE"; break; + case TLS1_AD_CERTIFICATE_UNOBTAINABLE: str="CO"; break; + case TLS1_AD_UNRECOGNIZED_NAME: str="UN"; break; + case TLS1_AD_BAD_CERTIFICATE_STATUS_RESPONSE: str="BR"; break; + case TLS1_AD_BAD_CERTIFICATE_HASH_VALUE: str="BH"; break; + case TLS1_AD_UNKNOWN_PSK_IDENTITY: str="UP"; break; + default: str="UK"; break; + } + return(str); + } + +const char *SSL_alert_desc_string_long(int value) + { + const char *str; + + switch (value & 0xff) + { + case SSL3_AD_CLOSE_NOTIFY: + str="close notify"; + break; + case SSL3_AD_UNEXPECTED_MESSAGE: + str="unexpected_message"; + break; + case SSL3_AD_BAD_RECORD_MAC: + str="bad record mac"; + break; + case SSL3_AD_DECOMPRESSION_FAILURE: + str="decompression failure"; + break; + case SSL3_AD_HANDSHAKE_FAILURE: + str="handshake failure"; + break; + case SSL3_AD_NO_CERTIFICATE: + str="no certificate"; + break; + case SSL3_AD_BAD_CERTIFICATE: + str="bad certificate"; + break; + case SSL3_AD_UNSUPPORTED_CERTIFICATE: + str="unsupported certificate"; + break; + case SSL3_AD_CERTIFICATE_REVOKED: + str="certificate revoked"; + break; + case SSL3_AD_CERTIFICATE_EXPIRED: + str="certificate expired"; + break; + case SSL3_AD_CERTIFICATE_UNKNOWN: + str="certificate unknown"; + break; + case SSL3_AD_ILLEGAL_PARAMETER: + str="illegal parameter"; + break; + case TLS1_AD_DECRYPTION_FAILED: + str="decryption failed"; + break; + case TLS1_AD_RECORD_OVERFLOW: + str="record overflow"; + break; + case TLS1_AD_UNKNOWN_CA: + str="unknown CA"; + break; + case TLS1_AD_ACCESS_DENIED: + str="access denied"; + break; + case TLS1_AD_DECODE_ERROR: + str="decode error"; + break; + case TLS1_AD_DECRYPT_ERROR: + str="decrypt error"; + break; + case TLS1_AD_EXPORT_RESTRICTION: + str="export restriction"; + break; + case TLS1_AD_PROTOCOL_VERSION: + str="protocol version"; + break; + case TLS1_AD_INSUFFICIENT_SECURITY: + str="insufficient security"; + break; + case TLS1_AD_INTERNAL_ERROR: + str="internal error"; + break; + case TLS1_AD_USER_CANCELLED: + str="user canceled"; + break; + case TLS1_AD_NO_RENEGOTIATION: + str="no renegotiation"; + break; + case TLS1_AD_UNSUPPORTED_EXTENSION: + str="unsupported extension"; + break; + case TLS1_AD_CERTIFICATE_UNOBTAINABLE: + str="certificate unobtainable"; + break; + case TLS1_AD_UNRECOGNIZED_NAME: + str="unrecognized name"; + break; + case TLS1_AD_BAD_CERTIFICATE_STATUS_RESPONSE: + str="bad certificate status response"; + break; + case TLS1_AD_BAD_CERTIFICATE_HASH_VALUE: + str="bad certificate hash value"; + break; + case TLS1_AD_UNKNOWN_PSK_IDENTITY: + str="unknown PSK identity"; + break; + default: str="unknown"; break; + } + return(str); + } + +const char *SSL_rstate_string(const SSL *s) + { + const char *str; + + switch (s->rstate) + { + case SSL_ST_READ_HEADER:str="RH"; break; + case SSL_ST_READ_BODY: str="RB"; break; + case SSL_ST_READ_DONE: str="RD"; break; + default: str="unknown"; break; + } + return(str); + } diff --git a/node-v0.8.14/deps/openssl/openssl/ssl/ssl_task.c b/node-v0.8.14/deps/openssl/openssl/ssl/ssl_task.c new file mode 100644 index 0000000..b5ce44b --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/ssl/ssl_task.c @@ -0,0 +1,369 @@ +/* ssl/ssl_task.c */ +/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com) + * All rights reserved. + * + * This package is an SSL implementation written + * by Eric Young (eay@cryptsoft.com). + * The implementation was written so as to conform with Netscapes SSL. + * + * This library is free for commercial and non-commercial use as long as + * the following conditions are aheared to. The following conditions + * apply to all code found in this distribution, be it the RC4, RSA, + * lhash, DES, etc., code; not just the SSL code. The SSL documentation + * included with this distribution is covered by the same copyright terms + * except that the holder is Tim Hudson (tjh@cryptsoft.com). + * + * Copyright remains Eric Young's, and as such any Copyright notices in + * the code are not to be removed. + * If this package is used in a product, Eric Young should be given attribution + * as the author of the parts of the library used. + * This can be in the form of a textual message at program startup or + * in documentation (online or textual) provided with the package. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * "This product includes cryptographic software written by + * Eric Young (eay@cryptsoft.com)" + * The word 'cryptographic' can be left out if the rouines from the library + * being used are not cryptographic related :-). + * 4. If you include any Windows specific code (or a derivative thereof) from + * the apps directory (application code) you must include an acknowledgement: + * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)" + * + * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * + * The licence and distribution terms for any publically available version or + * derivative of this code cannot be changed. i.e. this code cannot simply be + * copied and put under another distribution licence + * [including the GNU Public Licence.] + */ + +/* VMS */ +/* + * DECnet object for servicing SSL. We accept the inbound and speak a + * simple protocol for multiplexing the 2 data streams (application and + * ssl data) over this logical link. + * + * Logical names: + * SSL_CIPHER Defines a list of cipher specifications the server + * will support in order of preference. + * SSL_SERVER_CERTIFICATE + * Points to PEM (privacy enhanced mail) file that + * contains the server certificate and private password. + * SYS$NET Logical created by netserver.exe as hook for completing + * DECnet logical link. + * + * Each NSP message sent over the DECnet link has the following structure: + * struct rpc_msg { + * char channel; + * char function; + * short length; + * char data[MAX_DATA]; + * } msg; + * + * The channel field designates the virtual data stream this message applies + * to and is one of: + * A - Application data (payload). + * R - Remote client connection that initiated the SSL connection. Encrypted + * data is sent over this connection. + * G - General data, reserved for future use. + * + * The data streams are half-duplex read/write and have following functions: + * G - Get, requests that up to msg.length bytes of data be returned. The + * data is returned in the next 'C' function response that matches the + * requesting channel. + * P - Put, requests that the first msg.length bytes of msg.data be appended + * to the designated stream. + * C - Confirms a get or put. Every get and put will get a confirm response, + * you cannot initiate another function on a channel until the previous + * operation has been confirmed. + * + * The 2 channels may interleave their operations, for example: + * Server msg Client msg + * A, Get, 4092 ----> + * <---- R, get, 4092 + * R, Confirm, {hello} ----> + * <---- R, put, {srv hello} + * R, Confirm, 0 ----> + * . (SSL handshake completed) + * . (read first app data). + * <---- A, confirm, {http data} + * A, Put, {http data} ----> + * <---- A, confirm, 0 + * + * The length field is not permitted to be larger that 4092 bytes. + * + * Author: Dave Jones + * Date: 22-JUL-1996 + */ +#include +#include +#include /* VMS IO$_ definitions */ +#include /* VMS string descriptors */ +extern int SYS$QIOW(), SYS$ASSIGN(); +int LIB$INIT_TIMER(), LIB$SHOW_TIMER(); + +#include /* from ssltest.c */ +#include + +#include "e_os.h" + +#include +#include +#include +#include + +int MS_CALLBACK verify_callback(int ok, X509 *xs, X509 *xi, int depth, + int error); +BIO *bio_err=NULL; +BIO *bio_stdout=NULL; +BIO_METHOD *BIO_s_rtcp(); + +static char *cipher=NULL; +int verbose=1; +#ifdef FIONBIO +static int s_nbio=0; +#endif +#define TEST_SERVER_CERT "SSL_SERVER_CERTIFICATE" +/*************************************************************************/ +struct rpc_msg { /* Should have member alignment inhibited */ + char channel; /* 'A'-app data. 'R'-remote client 'G'-global */ + char function; /* 'G'-get, 'P'-put, 'C'-confirm, 'X'-close */ + unsigned short int length; /* Amount of data returned or max to return */ + char data[4092]; /* variable data */ +}; +#define RPC_HDR_SIZE (sizeof(struct rpc_msg) - 4092) + +static $DESCRIPTOR(sysnet, "SYS$NET"); +typedef unsigned short io_channel; + +struct io_status { + unsigned short status; + unsigned short count; + unsigned long stsval; +}; +int doit(io_channel chan, SSL_CTX *s_ctx ); +/*****************************************************************************/ +/* Decnet I/O routines. + */ +static int get ( io_channel chan, char *buffer, int maxlen, int *length ) +{ + int status; + struct io_status iosb; + status = SYS$QIOW ( 0, chan, IO$_READVBLK, &iosb, 0, 0, + buffer, maxlen, 0, 0, 0, 0 ); + if ( (status&1) == 1 ) status = iosb.status; + if ( (status&1) == 1 ) *length = iosb.count; + return status; +} + +static int put ( io_channel chan, char *buffer, int length ) +{ + int status; + struct io_status iosb; + status = SYS$QIOW ( 0, chan, IO$_WRITEVBLK, &iosb, 0, 0, + buffer, length, 0, 0, 0, 0 ); + if ( (status&1) == 1 ) status = iosb.status; + return status; +} +/***************************************************************************/ +/* Handle operations on the 'G' channel. + */ +static int general_request ( io_channel chan, struct rpc_msg *msg, int length ) +{ + return 48; +} +/***************************************************************************/ +int main ( int argc, char **argv ) +{ + int status, length; + io_channel chan; + struct rpc_msg msg; + + char *CApath=NULL,*CAfile=NULL; + int badop=0; + int ret=1; + int client_auth=0; + int server_auth=0; + SSL_CTX *s_ctx=NULL; + /* + * Confirm logical link with initiating client. + */ + LIB$INIT_TIMER(); + status = SYS$ASSIGN ( &sysnet, &chan, 0, 0, 0 ); + printf("status of assign to SYS$NET: %d\n", status ); + /* + * Initialize standard out and error files. + */ + if (bio_err == NULL) + if ((bio_err=BIO_new(BIO_s_file())) != NULL) + BIO_set_fp(bio_err,stderr,BIO_NOCLOSE); + if (bio_stdout == NULL) + if ((bio_stdout=BIO_new(BIO_s_file())) != NULL) + BIO_set_fp(bio_stdout,stdout,BIO_NOCLOSE); + /* + * get the preferred cipher list and other initialization + */ + if (cipher == NULL) cipher=getenv("SSL_CIPHER"); + printf("cipher list: %s\n", cipher ? cipher : "{undefined}" ); + + SSL_load_error_strings(); + OpenSSL_add_all_algorithms(); + +/* DRM, this was the original, but there is no such thing as SSLv2() + s_ctx=SSL_CTX_new(SSLv2()); +*/ + s_ctx=SSL_CTX_new(SSLv2_server_method()); + + if (s_ctx == NULL) goto end; + + SSL_CTX_use_certificate_file(s_ctx,TEST_SERVER_CERT,SSL_FILETYPE_PEM); + SSL_CTX_use_RSAPrivateKey_file(s_ctx,TEST_SERVER_CERT,SSL_FILETYPE_PEM); + printf("Loaded server certificate: '%s'\n", TEST_SERVER_CERT ); + + /* + * Take commands from client until bad status. + */ + LIB$SHOW_TIMER(); + status = doit ( chan, s_ctx ); + LIB$SHOW_TIMER(); + /* + * do final cleanup and exit. + */ +end: + if (s_ctx != NULL) SSL_CTX_free(s_ctx); + LIB$SHOW_TIMER(); + return 1; +} + +int doit(io_channel chan, SSL_CTX *s_ctx ) +{ + int status, length, link_state; + struct rpc_msg msg; + + SSL *s_ssl=NULL; + BIO *c_to_s=NULL; + BIO *s_to_c=NULL; + BIO *c_bio=NULL; + BIO *s_bio=NULL; + int i; + int done=0; + + s_ssl=SSL_new(s_ctx); + if (s_ssl == NULL) goto err; + + c_to_s=BIO_new(BIO_s_rtcp()); + s_to_c=BIO_new(BIO_s_rtcp()); + if ((s_to_c == NULL) || (c_to_s == NULL)) goto err; +/* original, DRM 24-SEP-1997 + BIO_set_fd ( c_to_s, "", chan ); + BIO_set_fd ( s_to_c, "", chan ); +*/ + BIO_set_fd ( c_to_s, 0, chan ); + BIO_set_fd ( s_to_c, 0, chan ); + + c_bio=BIO_new(BIO_f_ssl()); + s_bio=BIO_new(BIO_f_ssl()); + if ((c_bio == NULL) || (s_bio == NULL)) goto err; + + SSL_set_accept_state(s_ssl); + SSL_set_bio(s_ssl,c_to_s,s_to_c); + BIO_set_ssl(s_bio,s_ssl,BIO_CLOSE); + + /* We can always do writes */ + printf("Begin doit main loop\n"); + /* + * Link states: 0-idle, 1-read pending, 2-write pending, 3-closed. + */ + for (link_state = 0; link_state < 3; ) { + /* + * Wait for remote end to request data action on A channel. + */ + while ( link_state == 0 ) { + status = get ( chan, (char *) &msg, sizeof(msg), &length ); + if ( (status&1) == 0 ) { + printf("Error in main loop get: %d\n", status ); + link_state = 3; + break; + } + if ( length < RPC_HDR_SIZE ) { + printf("Error in main loop get size: %d\n", length ); + break; + link_state = 3; + } + if ( msg.channel != 'A' ) { + printf("Error in main loop, unexpected channel: %c\n", + msg.channel ); + break; + link_state = 3; + } + if ( msg.function == 'G' ) { + link_state = 1; + } else if ( msg.function == 'P' ) { + link_state = 2; /* write pending */ + } else if ( msg.function == 'X' ) { + link_state = 3; + } else { + link_state = 3; + } + } + if ( link_state == 1 ) { + i = BIO_read ( s_bio, msg.data, msg.length ); + if ( i < 0 ) link_state = 3; + else { + msg.channel = 'A'; + msg.function = 'C'; /* confirm */ + msg.length = i; + status = put ( chan, (char *) &msg, i+RPC_HDR_SIZE ); + if ( (status&1) == 0 ) break; + link_state = 0; + } + } else if ( link_state == 2 ) { + i = BIO_write ( s_bio, msg.data, msg.length ); + if ( i < 0 ) link_state = 3; + else { + msg.channel = 'A'; + msg.function = 'C'; /* confirm */ + msg.length = 0; + status = put ( chan, (char *) &msg, RPC_HDR_SIZE ); + if ( (status&1) == 0 ) break; + link_state = 0; + } + } + } + fprintf(stdout,"DONE\n"); +err: + /* We have to set the BIO's to NULL otherwise they will be + * free()ed twice. Once when th s_ssl is SSL_free()ed and + * again when c_ssl is SSL_free()ed. + * This is a hack required because s_ssl and c_ssl are sharing the same + * BIO structure and SSL_set_bio() and SSL_free() automatically + * BIO_free non NULL entries. + * You should not normally do this or be required to do this */ + s_ssl->rbio=NULL; + s_ssl->wbio=NULL; + + if (c_to_s != NULL) BIO_free(c_to_s); + if (s_to_c != NULL) BIO_free(s_to_c); + if (c_bio != NULL) BIO_free(c_bio); + if (s_bio != NULL) BIO_free(s_bio); + return(0); +} diff --git a/node-v0.8.14/deps/openssl/openssl/ssl/ssl_txt.c b/node-v0.8.14/deps/openssl/openssl/ssl/ssl_txt.c new file mode 100644 index 0000000..3122440 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/ssl/ssl_txt.c @@ -0,0 +1,240 @@ +/* ssl/ssl_txt.c */ +/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com) + * All rights reserved. + * + * This package is an SSL implementation written + * by Eric Young (eay@cryptsoft.com). + * The implementation was written so as to conform with Netscapes SSL. + * + * This library is free for commercial and non-commercial use as long as + * the following conditions are aheared to. The following conditions + * apply to all code found in this distribution, be it the RC4, RSA, + * lhash, DES, etc., code; not just the SSL code. The SSL documentation + * included with this distribution is covered by the same copyright terms + * except that the holder is Tim Hudson (tjh@cryptsoft.com). + * + * Copyright remains Eric Young's, and as such any Copyright notices in + * the code are not to be removed. + * If this package is used in a product, Eric Young should be given attribution + * as the author of the parts of the library used. + * This can be in the form of a textual message at program startup or + * in documentation (online or textual) provided with the package. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * "This product includes cryptographic software written by + * Eric Young (eay@cryptsoft.com)" + * The word 'cryptographic' can be left out if the rouines from the library + * being used are not cryptographic related :-). + * 4. If you include any Windows specific code (or a derivative thereof) from + * the apps directory (application code) you must include an acknowledgement: + * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)" + * + * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * + * The licence and distribution terms for any publically available version or + * derivative of this code cannot be changed. i.e. this code cannot simply be + * copied and put under another distribution licence + * [including the GNU Public Licence.] + */ +/* ==================================================================== + * Copyright 2005 Nokia. All rights reserved. + * + * The portions of the attached software ("Contribution") is developed by + * Nokia Corporation and is licensed pursuant to the OpenSSL open source + * license. + * + * The Contribution, originally written by Mika Kousa and Pasi Eronen of + * Nokia Corporation, consists of the "PSK" (Pre-Shared Key) ciphersuites + * support (see RFC 4279) to OpenSSL. + * + * No patent licenses or other rights except those expressly stated in + * the OpenSSL open source license shall be deemed granted or received + * expressly, by implication, estoppel, or otherwise. + * + * No assurances are provided by Nokia that the Contribution does not + * infringe the patent or other intellectual property rights of any third + * party or that the license provides you with all the necessary rights + * to make use of the Contribution. + * + * THE SOFTWARE IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND. IN + * ADDITION TO THE DISCLAIMERS INCLUDED IN THE LICENSE, NOKIA + * SPECIFICALLY DISCLAIMS ANY LIABILITY FOR CLAIMS BROUGHT BY YOU OR ANY + * OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL PROPERTY RIGHTS OR + * OTHERWISE. + */ + +#include +#include +#include "ssl_locl.h" + +#ifndef OPENSSL_NO_FP_API +int SSL_SESSION_print_fp(FILE *fp, const SSL_SESSION *x) + { + BIO *b; + int ret; + + if ((b=BIO_new(BIO_s_file_internal())) == NULL) + { + SSLerr(SSL_F_SSL_SESSION_PRINT_FP,ERR_R_BUF_LIB); + return(0); + } + BIO_set_fp(b,fp,BIO_NOCLOSE); + ret=SSL_SESSION_print(b,x); + BIO_free(b); + return(ret); + } +#endif + +int SSL_SESSION_print(BIO *bp, const SSL_SESSION *x) + { + unsigned int i; + const char *s; + + if (x == NULL) goto err; + if (BIO_puts(bp,"SSL-Session:\n") <= 0) goto err; + if (x->ssl_version == SSL2_VERSION) + s="SSLv2"; + else if (x->ssl_version == SSL3_VERSION) + s="SSLv3"; + else if (x->ssl_version == TLS1_VERSION) + s="TLSv1"; + else if (x->ssl_version == DTLS1_VERSION) + s="DTLSv1"; + else if (x->ssl_version == DTLS1_BAD_VER) + s="DTLSv1-bad"; + else + s="unknown"; + if (BIO_printf(bp," Protocol : %s\n",s) <= 0) goto err; + + if (x->cipher == NULL) + { + if (((x->cipher_id) & 0xff000000) == 0x02000000) + { + if (BIO_printf(bp," Cipher : %06lX\n",x->cipher_id&0xffffff) <= 0) + goto err; + } + else + { + if (BIO_printf(bp," Cipher : %04lX\n",x->cipher_id&0xffff) <= 0) + goto err; + } + } + else + { + if (BIO_printf(bp," Cipher : %s\n",((x->cipher == NULL)?"unknown":x->cipher->name)) <= 0) + goto err; + } + if (BIO_puts(bp," Session-ID: ") <= 0) goto err; + for (i=0; isession_id_length; i++) + { + if (BIO_printf(bp,"%02X",x->session_id[i]) <= 0) goto err; + } + if (BIO_puts(bp,"\n Session-ID-ctx: ") <= 0) goto err; + for (i=0; isid_ctx_length; i++) + { + if (BIO_printf(bp,"%02X",x->sid_ctx[i]) <= 0) + goto err; + } + if (BIO_puts(bp,"\n Master-Key: ") <= 0) goto err; + for (i=0; i<(unsigned int)x->master_key_length; i++) + { + if (BIO_printf(bp,"%02X",x->master_key[i]) <= 0) goto err; + } + if (BIO_puts(bp,"\n Key-Arg : ") <= 0) goto err; + if (x->key_arg_length == 0) + { + if (BIO_puts(bp,"None") <= 0) goto err; + } + else + for (i=0; ikey_arg_length; i++) + { + if (BIO_printf(bp,"%02X",x->key_arg[i]) <= 0) goto err; + } +#ifndef OPENSSL_NO_KRB5 + if (BIO_puts(bp,"\n Krb5 Principal: ") <= 0) goto err; + if (x->krb5_client_princ_len == 0) + { + if (BIO_puts(bp,"None") <= 0) goto err; + } + else + for (i=0; ikrb5_client_princ_len; i++) + { + if (BIO_printf(bp,"%02X",x->krb5_client_princ[i]) <= 0) goto err; + } +#endif /* OPENSSL_NO_KRB5 */ +#ifndef OPENSSL_NO_PSK + if (BIO_puts(bp,"\n PSK identity: ") <= 0) goto err; + if (BIO_printf(bp, "%s", x->psk_identity ? x->psk_identity : "None") <= 0) goto err; + if (BIO_puts(bp,"\n PSK identity hint: ") <= 0) goto err; + if (BIO_printf(bp, "%s", x->psk_identity_hint ? x->psk_identity_hint : "None") <= 0) goto err; +#endif +#ifndef OPENSSL_NO_TLSEXT + if (x->tlsext_tick_lifetime_hint) + { + if (BIO_printf(bp, + "\n TLS session ticket lifetime hint: %ld (seconds)", + x->tlsext_tick_lifetime_hint) <=0) + goto err; + } + if (x->tlsext_tick) + { + if (BIO_puts(bp, "\n TLS session ticket:\n") <= 0) goto err; + if (BIO_dump_indent(bp, (char *)x->tlsext_tick, x->tlsext_ticklen, 4) <= 0) + goto err; + } +#endif + +#ifndef OPENSSL_NO_COMP + if (x->compress_meth != 0) + { + SSL_COMP *comp = NULL; + + ssl_cipher_get_evp(x,NULL,NULL,NULL,NULL,&comp); + if (comp == NULL) + { + if (BIO_printf(bp,"\n Compression: %d",x->compress_meth) <= 0) goto err; + } + else + { + if (BIO_printf(bp,"\n Compression: %d (%s)", comp->id,comp->method->name) <= 0) goto err; + } + } +#endif + if (x->time != 0L) + { + if (BIO_printf(bp, "\n Start Time: %ld",x->time) <= 0) goto err; + } + if (x->timeout != 0L) + { + if (BIO_printf(bp, "\n Timeout : %ld (sec)",x->timeout) <= 0) goto err; + } + if (BIO_puts(bp,"\n") <= 0) goto err; + + if (BIO_puts(bp, " Verify return code: ") <= 0) goto err; + if (BIO_printf(bp, "%ld (%s)\n", x->verify_result, + X509_verify_cert_error_string(x->verify_result)) <= 0) goto err; + + return(1); +err: + return(0); + } + diff --git a/node-v0.8.14/deps/openssl/openssl/ssl/ssltest.c b/node-v0.8.14/deps/openssl/openssl/ssl/ssltest.c new file mode 100644 index 0000000..f6a2c79 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/ssl/ssltest.c @@ -0,0 +1,2503 @@ +/* ssl/ssltest.c */ +/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com) + * All rights reserved. + * + * This package is an SSL implementation written + * by Eric Young (eay@cryptsoft.com). + * The implementation was written so as to conform with Netscapes SSL. + * + * This library is free for commercial and non-commercial use as long as + * the following conditions are aheared to. The following conditions + * apply to all code found in this distribution, be it the RC4, RSA, + * lhash, DES, etc., code; not just the SSL code. The SSL documentation + * included with this distribution is covered by the same copyright terms + * except that the holder is Tim Hudson (tjh@cryptsoft.com). + * + * Copyright remains Eric Young's, and as such any Copyright notices in + * the code are not to be removed. + * If this package is used in a product, Eric Young should be given attribution + * as the author of the parts of the library used. + * This can be in the form of a textual message at program startup or + * in documentation (online or textual) provided with the package. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * "This product includes cryptographic software written by + * Eric Young (eay@cryptsoft.com)" + * The word 'cryptographic' can be left out if the rouines from the library + * being used are not cryptographic related :-). + * 4. If you include any Windows specific code (or a derivative thereof) from + * the apps directory (application code) you must include an acknowledgement: + * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)" + * + * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * + * The licence and distribution terms for any publically available version or + * derivative of this code cannot be changed. i.e. this code cannot simply be + * copied and put under another distribution licence + * [including the GNU Public Licence.] + */ +/* ==================================================================== + * Copyright (c) 1998-2000 The OpenSSL Project. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. All advertising materials mentioning features or use of this + * software must display the following acknowledgment: + * "This product includes software developed by the OpenSSL Project + * for use in the OpenSSL Toolkit. (http://www.openssl.org/)" + * + * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to + * endorse or promote products derived from this software without + * prior written permission. For written permission, please contact + * openssl-core@openssl.org. + * + * 5. Products derived from this software may not be called "OpenSSL" + * nor may "OpenSSL" appear in their names without prior written + * permission of the OpenSSL Project. + * + * 6. Redistributions of any form whatsoever must retain the following + * acknowledgment: + * "This product includes software developed by the OpenSSL Project + * for use in the OpenSSL Toolkit (http://www.openssl.org/)" + * + * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY + * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR + * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, + * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * ==================================================================== + * + * This product includes cryptographic software written by Eric Young + * (eay@cryptsoft.com). This product includes software written by Tim + * Hudson (tjh@cryptsoft.com). + * + */ +/* ==================================================================== + * Copyright 2002 Sun Microsystems, Inc. ALL RIGHTS RESERVED. + * ECC cipher suite support in OpenSSL originally developed by + * SUN MICROSYSTEMS, INC., and contributed to the OpenSSL project. + */ +/* ==================================================================== + * Copyright 2005 Nokia. All rights reserved. + * + * The portions of the attached software ("Contribution") is developed by + * Nokia Corporation and is licensed pursuant to the OpenSSL open source + * license. + * + * The Contribution, originally written by Mika Kousa and Pasi Eronen of + * Nokia Corporation, consists of the "PSK" (Pre-Shared Key) ciphersuites + * support (see RFC 4279) to OpenSSL. + * + * No patent licenses or other rights except those expressly stated in + * the OpenSSL open source license shall be deemed granted or received + * expressly, by implication, estoppel, or otherwise. + * + * No assurances are provided by Nokia that the Contribution does not + * infringe the patent or other intellectual property rights of any third + * party or that the license provides you with all the necessary rights + * to make use of the Contribution. + * + * THE SOFTWARE IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND. IN + * ADDITION TO THE DISCLAIMERS INCLUDED IN THE LICENSE, NOKIA + * SPECIFICALLY DISCLAIMS ANY LIABILITY FOR CLAIMS BROUGHT BY YOU OR ANY + * OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL PROPERTY RIGHTS OR + * OTHERWISE. + */ + +#define _BSD_SOURCE 1 /* Or gethostname won't be declared properly + on Linux and GNU platforms. */ + +#include +#include +#include +#include +#include +#include +#include + +#define USE_SOCKETS +#include "e_os.h" + +#ifdef OPENSSL_SYS_VMS +#define _XOPEN_SOURCE 500 /* Or isascii won't be declared properly on + VMS (at least with DECompHP C). */ +#endif + +#include + +#include +#include +#include +#include +#include +#include +#ifndef OPENSSL_NO_ENGINE +#include +#endif +#include +#include +#ifndef OPENSSL_NO_RSA +#include +#endif +#ifndef OPENSSL_NO_DSA +#include +#endif +#ifndef OPENSSL_NO_DH +#include +#endif +#include + +#define _XOPEN_SOURCE_EXTENDED 1 /* Or gethostname won't be declared properly + on Compaq platforms (at least with DEC C). + Do not try to put it earlier, or IPv6 includes + get screwed... + */ + +#ifdef OPENSSL_SYS_WINDOWS +#include +#else +#include OPENSSL_UNISTD +#endif + +#ifdef OPENSSL_SYS_VMS +# define TEST_SERVER_CERT "SYS$DISK:[-.APPS]SERVER.PEM" +# define TEST_CLIENT_CERT "SYS$DISK:[-.APPS]CLIENT.PEM" +#elif defined(OPENSSL_SYS_WINCE) +# define TEST_SERVER_CERT "\\OpenSSL\\server.pem" +# define TEST_CLIENT_CERT "\\OpenSSL\\client.pem" +#elif defined(OPENSSL_SYS_NETWARE) +# define TEST_SERVER_CERT "\\openssl\\apps\\server.pem" +# define TEST_CLIENT_CERT "\\openssl\\apps\\client.pem" +#else +# define TEST_SERVER_CERT "../apps/server.pem" +# define TEST_CLIENT_CERT "../apps/client.pem" +#endif + +/* There is really no standard for this, so let's assign some tentative + numbers. In any case, these numbers are only for this test */ +#define COMP_RLE 255 +#define COMP_ZLIB 1 + +static int MS_CALLBACK verify_callback(int ok, X509_STORE_CTX *ctx); +#ifndef OPENSSL_NO_RSA +static RSA MS_CALLBACK *tmp_rsa_cb(SSL *s, int is_export,int keylength); +static void free_tmp_rsa(void); +#endif +static int MS_CALLBACK app_verify_callback(X509_STORE_CTX *ctx, void *arg); +#define APP_CALLBACK_STRING "Test Callback Argument" +struct app_verify_arg + { + char *string; + int app_verify; + int allow_proxy_certs; + char *proxy_auth; + char *proxy_cond; + }; + +#ifndef OPENSSL_NO_DH +static DH *get_dh512(void); +static DH *get_dh1024(void); +static DH *get_dh1024dsa(void); +#endif + + +static char *psk_key=NULL; /* by default PSK is not used */ +#ifndef OPENSSL_NO_PSK +static unsigned int psk_client_callback(SSL *ssl, const char *hint, char *identity, + unsigned int max_identity_len, unsigned char *psk, + unsigned int max_psk_len); +static unsigned int psk_server_callback(SSL *ssl, const char *identity, unsigned char *psk, + unsigned int max_psk_len); +#endif + +static BIO *bio_err=NULL; +static BIO *bio_stdout=NULL; + +static char *cipher=NULL; +static int verbose=0; +static int debug=0; +#if 0 +/* Not used yet. */ +#ifdef FIONBIO +static int s_nbio=0; +#endif +#endif + +static const char rnd_seed[] = "string to make the random number generator think it has entropy"; + +int doit_biopair(SSL *s_ssl,SSL *c_ssl,long bytes,clock_t *s_time,clock_t *c_time); +int doit(SSL *s_ssl,SSL *c_ssl,long bytes); +static int do_test_cipherlist(void); +static void sv_usage(void) + { + fprintf(stderr,"usage: ssltest [args ...]\n"); + fprintf(stderr,"\n"); + fprintf(stderr," -server_auth - check server certificate\n"); + fprintf(stderr," -client_auth - do client authentication\n"); + fprintf(stderr," -proxy - allow proxy certificates\n"); + fprintf(stderr," -proxy_auth - set proxy policy rights\n"); + fprintf(stderr," -proxy_cond - experssion to test proxy policy rights\n"); + fprintf(stderr," -v - more output\n"); + fprintf(stderr," -d - debug output\n"); + fprintf(stderr," -reuse - use session-id reuse\n"); + fprintf(stderr," -num - number of connections to perform\n"); + fprintf(stderr," -bytes - number of bytes to swap between client/server\n"); +#ifndef OPENSSL_NO_DH + fprintf(stderr," -dhe1024 - use 1024 bit key (safe prime) for DHE\n"); + fprintf(stderr," -dhe1024dsa - use 1024 bit key (with 160-bit subprime) for DHE\n"); + fprintf(stderr," -no_dhe - disable DHE\n"); +#endif +#ifndef OPENSSL_NO_ECDH + fprintf(stderr," -no_ecdhe - disable ECDHE\n"); +#endif +#ifndef OPENSSL_NO_PSK + fprintf(stderr," -psk arg - PSK in hex (without 0x)\n"); +#endif +#ifndef OPENSSL_NO_SSL2 + fprintf(stderr," -ssl2 - use SSLv2\n"); +#endif +#ifndef OPENSSL_NO_SSL3 + fprintf(stderr," -ssl3 - use SSLv3\n"); +#endif +#ifndef OPENSSL_NO_TLS1 + fprintf(stderr," -tls1 - use TLSv1\n"); +#endif + fprintf(stderr," -CApath arg - PEM format directory of CA's\n"); + fprintf(stderr," -CAfile arg - PEM format file of CA's\n"); + fprintf(stderr," -cert arg - Server certificate file\n"); + fprintf(stderr," -key arg - Server key file (default: same as -cert)\n"); + fprintf(stderr," -c_cert arg - Client certificate file\n"); + fprintf(stderr," -c_key arg - Client key file (default: same as -c_cert)\n"); + fprintf(stderr," -cipher arg - The cipher list\n"); + fprintf(stderr," -bio_pair - Use BIO pairs\n"); + fprintf(stderr," -f - Test even cases that can't work\n"); + fprintf(stderr," -time - measure processor time used by client and server\n"); + fprintf(stderr," -zlib - use zlib compression\n"); + fprintf(stderr," -rle - use rle compression\n"); +#ifndef OPENSSL_NO_ECDH + fprintf(stderr," -named_curve arg - Elliptic curve name to use for ephemeral ECDH keys.\n" \ + " Use \"openssl ecparam -list_curves\" for all names\n" \ + " (default is sect163r2).\n"); +#endif + fprintf(stderr," -test_cipherlist - verifies the order of the ssl cipher lists\n"); + fprintf(stderr," -c_small_records - enable client side use of small SSL record buffers\n"); + fprintf(stderr," -s_small_records - enable server side use of small SSL record buffers\n"); + fprintf(stderr," -cutthrough - enable 1-RTT full-handshake for strong ciphers\n"); + } + +static void print_details(SSL *c_ssl, const char *prefix) + { + const SSL_CIPHER *ciph; + X509 *cert; + + ciph=SSL_get_current_cipher(c_ssl); + BIO_printf(bio_stdout,"%s%s, cipher %s %s", + prefix, + SSL_get_version(c_ssl), + SSL_CIPHER_get_version(ciph), + SSL_CIPHER_get_name(ciph)); + cert=SSL_get_peer_certificate(c_ssl); + if (cert != NULL) + { + EVP_PKEY *pkey = X509_get_pubkey(cert); + if (pkey != NULL) + { + if (0) + ; +#ifndef OPENSSL_NO_RSA + else if (pkey->type == EVP_PKEY_RSA && pkey->pkey.rsa != NULL + && pkey->pkey.rsa->n != NULL) + { + BIO_printf(bio_stdout, ", %d bit RSA", + BN_num_bits(pkey->pkey.rsa->n)); + } +#endif +#ifndef OPENSSL_NO_DSA + else if (pkey->type == EVP_PKEY_DSA && pkey->pkey.dsa != NULL + && pkey->pkey.dsa->p != NULL) + { + BIO_printf(bio_stdout, ", %d bit DSA", + BN_num_bits(pkey->pkey.dsa->p)); + } +#endif + EVP_PKEY_free(pkey); + } + X509_free(cert); + } + /* The SSL API does not allow us to look at temporary RSA/DH keys, + * otherwise we should print their lengths too */ + BIO_printf(bio_stdout,"\n"); + } + +static void lock_dbg_cb(int mode, int type, const char *file, int line) + { + static int modes[CRYPTO_NUM_LOCKS]; /* = {0, 0, ... } */ + const char *errstr = NULL; + int rw; + + rw = mode & (CRYPTO_READ|CRYPTO_WRITE); + if (!((rw == CRYPTO_READ) || (rw == CRYPTO_WRITE))) + { + errstr = "invalid mode"; + goto err; + } + + if (type < 0 || type >= CRYPTO_NUM_LOCKS) + { + errstr = "type out of bounds"; + goto err; + } + + if (mode & CRYPTO_LOCK) + { + if (modes[type]) + { + errstr = "already locked"; + /* must not happen in a single-threaded program + * (would deadlock) */ + goto err; + } + + modes[type] = rw; + } + else if (mode & CRYPTO_UNLOCK) + { + if (!modes[type]) + { + errstr = "not locked"; + goto err; + } + + if (modes[type] != rw) + { + errstr = (rw == CRYPTO_READ) ? + "CRYPTO_r_unlock on write lock" : + "CRYPTO_w_unlock on read lock"; + } + + modes[type] = 0; + } + else + { + errstr = "invalid mode"; + goto err; + } + + err: + if (errstr) + { + /* we cannot use bio_err here */ + fprintf(stderr, "openssl (lock_dbg_cb): %s (mode=%d, type=%d) at %s:%d\n", + errstr, mode, type, file, line); + } + } + +#ifdef TLSEXT_TYPE_opaque_prf_input +struct cb_info_st { void *input; size_t len; int ret; }; +struct cb_info_st co1 = { "C", 1, 1 }; /* try to negotiate oqaque PRF input */ +struct cb_info_st co2 = { "C", 1, 2 }; /* insist on oqaque PRF input */ +struct cb_info_st so1 = { "S", 1, 1 }; /* try to negotiate oqaque PRF input */ +struct cb_info_st so2 = { "S", 1, 2 }; /* insist on oqaque PRF input */ + +int opaque_prf_input_cb(SSL *ssl, void *peerinput, size_t len, void *arg_) + { + struct cb_info_st *arg = arg_; + + if (arg == NULL) + return 1; + + if (!SSL_set_tlsext_opaque_prf_input(ssl, arg->input, arg->len)) + return 0; + return arg->ret; + } +#endif + int ssl_mode = 0; + int c_small_records=0; + int s_small_records=0; + int cutthrough = 0; + +int main(int argc, char *argv[]) + { + char *CApath=NULL,*CAfile=NULL; + int badop=0; + int bio_pair=0; + int force=0; + int tls1=0,ssl2=0,ssl3=0,ret=1; + int client_auth=0; + int server_auth=0,i; + struct app_verify_arg app_verify_arg = + { APP_CALLBACK_STRING, 0, 0, NULL, NULL }; + char *server_cert=TEST_SERVER_CERT; + char *server_key=NULL; + char *client_cert=TEST_CLIENT_CERT; + char *client_key=NULL; +#ifndef OPENSSL_NO_ECDH + char *named_curve = NULL; +#endif + SSL_CTX *s_ctx=NULL; + SSL_CTX *c_ctx=NULL; + const SSL_METHOD *meth=NULL; + SSL *c_ssl,*s_ssl; + int number=1,reuse=0; + long bytes=256L; +#ifndef OPENSSL_NO_DH + DH *dh; + int dhe1024 = 0, dhe1024dsa = 0; +#endif +#ifndef OPENSSL_NO_ECDH + EC_KEY *ecdh = NULL; +#endif + int no_dhe = 0; + int no_ecdhe = 0; + int no_psk = 0; + int print_time = 0; + clock_t s_time = 0, c_time = 0; + int comp = 0; +#ifndef OPENSSL_NO_COMP + COMP_METHOD *cm = NULL; +#endif + STACK_OF(SSL_COMP) *ssl_comp_methods = NULL; + int test_cipherlist = 0; + + verbose = 0; + debug = 0; + cipher = 0; + + bio_err=BIO_new_fp(stderr,BIO_NOCLOSE|BIO_FP_TEXT); + + CRYPTO_set_locking_callback(lock_dbg_cb); + + /* enable memory leak checking unless explicitly disabled */ + if (!((getenv("OPENSSL_DEBUG_MEMORY") != NULL) && (0 == strcmp(getenv("OPENSSL_DEBUG_MEMORY"), "off")))) + { + CRYPTO_malloc_debug_init(); + CRYPTO_set_mem_debug_options(V_CRYPTO_MDEBUG_ALL); + } + else + { + /* OPENSSL_DEBUG_MEMORY=off */ + CRYPTO_set_mem_debug_functions(0, 0, 0, 0, 0); + } + CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_ON); + + RAND_seed(rnd_seed, sizeof rnd_seed); + + bio_stdout=BIO_new_fp(stdout,BIO_NOCLOSE|BIO_FP_TEXT); + + argc--; + argv++; + + while (argc >= 1) + { + if (strcmp(*argv,"-server_auth") == 0) + server_auth=1; + else if (strcmp(*argv,"-client_auth") == 0) + client_auth=1; + else if (strcmp(*argv,"-proxy_auth") == 0) + { + if (--argc < 1) goto bad; + app_verify_arg.proxy_auth= *(++argv); + } + else if (strcmp(*argv,"-proxy_cond") == 0) + { + if (--argc < 1) goto bad; + app_verify_arg.proxy_cond= *(++argv); + } + else if (strcmp(*argv,"-v") == 0) + verbose=1; + else if (strcmp(*argv,"-d") == 0) + debug=1; + else if (strcmp(*argv,"-reuse") == 0) + reuse=1; + else if (strcmp(*argv,"-dhe1024") == 0) + { +#ifndef OPENSSL_NO_DH + dhe1024=1; +#else + fprintf(stderr,"ignoring -dhe1024, since I'm compiled without DH\n"); +#endif + } + else if (strcmp(*argv,"-dhe1024dsa") == 0) + { +#ifndef OPENSSL_NO_DH + dhe1024dsa=1; +#else + fprintf(stderr,"ignoring -dhe1024, since I'm compiled without DH\n"); +#endif + } + else if (strcmp(*argv,"-no_dhe") == 0) + no_dhe=1; + else if (strcmp(*argv,"-no_ecdhe") == 0) + no_ecdhe=1; + else if (strcmp(*argv,"-psk") == 0) + { + if (--argc < 1) goto bad; + psk_key=*(++argv); +#ifndef OPENSSL_NO_PSK + if (strspn(psk_key, "abcdefABCDEF1234567890") != strlen(psk_key)) + { + BIO_printf(bio_err,"Not a hex number '%s'\n",*argv); + goto bad; + } +#else + no_psk=1; +#endif + } + else if (strcmp(*argv,"-ssl2") == 0) + ssl2=1; + else if (strcmp(*argv,"-tls1") == 0) + tls1=1; + else if (strcmp(*argv,"-ssl3") == 0) + ssl3=1; + else if (strncmp(*argv,"-num",4) == 0) + { + if (--argc < 1) goto bad; + number= atoi(*(++argv)); + if (number == 0) number=1; + } + else if (strcmp(*argv,"-bytes") == 0) + { + if (--argc < 1) goto bad; + bytes= atol(*(++argv)); + if (bytes == 0L) bytes=1L; + i=strlen(argv[0]); + if (argv[0][i-1] == 'k') bytes*=1024L; + if (argv[0][i-1] == 'm') bytes*=1024L*1024L; + } + else if (strcmp(*argv,"-cert") == 0) + { + if (--argc < 1) goto bad; + server_cert= *(++argv); + } + else if (strcmp(*argv,"-s_cert") == 0) + { + if (--argc < 1) goto bad; + server_cert= *(++argv); + } + else if (strcmp(*argv,"-key") == 0) + { + if (--argc < 1) goto bad; + server_key= *(++argv); + } + else if (strcmp(*argv,"-s_key") == 0) + { + if (--argc < 1) goto bad; + server_key= *(++argv); + } + else if (strcmp(*argv,"-c_cert") == 0) + { + if (--argc < 1) goto bad; + client_cert= *(++argv); + } + else if (strcmp(*argv,"-c_key") == 0) + { + if (--argc < 1) goto bad; + client_key= *(++argv); + } + else if (strcmp(*argv,"-cipher") == 0) + { + if (--argc < 1) goto bad; + cipher= *(++argv); + } + else if (strcmp(*argv,"-CApath") == 0) + { + if (--argc < 1) goto bad; + CApath= *(++argv); + } + else if (strcmp(*argv,"-CAfile") == 0) + { + if (--argc < 1) goto bad; + CAfile= *(++argv); + } + else if (strcmp(*argv,"-bio_pair") == 0) + { + bio_pair = 1; + } + else if (strcmp(*argv,"-f") == 0) + { + force = 1; + } + else if (strcmp(*argv,"-time") == 0) + { + print_time = 1; + } + else if (strcmp(*argv,"-zlib") == 0) + { + comp = COMP_ZLIB; + } + else if (strcmp(*argv,"-rle") == 0) + { + comp = COMP_RLE; + } + else if (strcmp(*argv,"-named_curve") == 0) + { + if (--argc < 1) goto bad; +#ifndef OPENSSL_NO_ECDH + named_curve = *(++argv); +#else + fprintf(stderr,"ignoring -named_curve, since I'm compiled without ECDH\n"); + ++argv; +#endif + } + else if (strcmp(*argv,"-app_verify") == 0) + { + app_verify_arg.app_verify = 1; + } + else if (strcmp(*argv,"-proxy") == 0) + { + app_verify_arg.allow_proxy_certs = 1; + } + else if (strcmp(*argv,"-test_cipherlist") == 0) + { + test_cipherlist = 1; + } + else if (strcmp(*argv, "-c_small_records") == 0) + { + c_small_records = 1; + } + else if (strcmp(*argv, "-s_small_records") == 0) + { + s_small_records = 1; + } + else if (strcmp(*argv, "-cutthrough") == 0) + { + cutthrough = 1; + } + else + { + fprintf(stderr,"unknown option %s\n",*argv); + badop=1; + break; + } + argc--; + argv++; + } + if (badop) + { +bad: + sv_usage(); + goto end; + } + + if (test_cipherlist == 1) + { + /* ensure that the cipher list are correctly sorted and exit */ + if (do_test_cipherlist() == 0) + EXIT(1); + ret = 0; + goto end; + } + + if (!ssl2 && !ssl3 && !tls1 && number > 1 && !reuse && !force) + { + fprintf(stderr, "This case cannot work. Use -f to perform " + "the test anyway (and\n-d to see what happens), " + "or add one of -ssl2, -ssl3, -tls1, -reuse\n" + "to avoid protocol mismatch.\n"); + EXIT(1); + } + + if (print_time) + { + if (!bio_pair) + { + fprintf(stderr, "Using BIO pair (-bio_pair)\n"); + bio_pair = 1; + } + if (number < 50 && !force) + fprintf(stderr, "Warning: For accurate timings, use more connections (e.g. -num 1000)\n"); + } + +/* if (cipher == NULL) cipher=getenv("SSL_CIPHER"); */ + + SSL_library_init(); + SSL_load_error_strings(); + +#ifndef OPENSSL_NO_COMP + if (comp == COMP_ZLIB) cm = COMP_zlib(); + if (comp == COMP_RLE) cm = COMP_rle(); + if (cm != NULL) + { + if (cm->type != NID_undef) + { + if (SSL_COMP_add_compression_method(comp, cm) != 0) + { + fprintf(stderr, + "Failed to add compression method\n"); + ERR_print_errors_fp(stderr); + } + } + else + { + fprintf(stderr, + "Warning: %s compression not supported\n", + (comp == COMP_RLE ? "rle" : + (comp == COMP_ZLIB ? "zlib" : + "unknown"))); + ERR_print_errors_fp(stderr); + } + } + ssl_comp_methods = SSL_COMP_get_compression_methods(); + fprintf(stderr, "Available compression methods:\n"); + { + int j, n = sk_SSL_COMP_num(ssl_comp_methods); + if (n == 0) + fprintf(stderr, " NONE\n"); + else + for (j = 0; j < n; j++) + { + SSL_COMP *c = sk_SSL_COMP_value(ssl_comp_methods, j); + fprintf(stderr, " %d: %s\n", c->id, c->name); + } + } +#endif + +#if !defined(OPENSSL_NO_SSL2) && !defined(OPENSSL_NO_SSL3) + if (ssl2) + meth=SSLv2_method(); + else + if (tls1) + meth=TLSv1_method(); + else + if (ssl3) + meth=SSLv3_method(); + else + meth=SSLv23_method(); +#else +#ifdef OPENSSL_NO_SSL2 + meth=SSLv3_method(); +#else + meth=SSLv2_method(); +#endif +#endif + + c_ctx=SSL_CTX_new(meth); + s_ctx=SSL_CTX_new(meth); + if ((c_ctx == NULL) || (s_ctx == NULL)) + { + ERR_print_errors(bio_err); + goto end; + } + + if (cipher != NULL) + { + SSL_CTX_set_cipher_list(c_ctx,cipher); + SSL_CTX_set_cipher_list(s_ctx,cipher); + } + + ssl_mode = 0; + if (c_small_records) + { + ssl_mode = SSL_CTX_get_mode(c_ctx); + ssl_mode |= SSL_MODE_SMALL_BUFFERS; + SSL_CTX_set_mode(c_ctx, ssl_mode); + } + ssl_mode = 0; + if (s_small_records) + { + ssl_mode = SSL_CTX_get_mode(s_ctx); + ssl_mode |= SSL_MODE_SMALL_BUFFERS; + SSL_CTX_set_mode(s_ctx, ssl_mode); + } + ssl_mode = 0; + if (cutthrough) + { + ssl_mode = SSL_CTX_get_mode(c_ctx); + ssl_mode = SSL_MODE_HANDSHAKE_CUTTHROUGH; + SSL_CTX_set_mode(c_ctx, ssl_mode); + } + +#ifndef OPENSSL_NO_DH + if (!no_dhe) + { + if (dhe1024dsa) + { + /* use SSL_OP_SINGLE_DH_USE to avoid small subgroup attacks */ + SSL_CTX_set_options(s_ctx, SSL_OP_SINGLE_DH_USE); + dh=get_dh1024dsa(); + } + else if (dhe1024) + dh=get_dh1024(); + else + dh=get_dh512(); + SSL_CTX_set_tmp_dh(s_ctx,dh); + DH_free(dh); + } +#else + (void)no_dhe; +#endif + +#ifndef OPENSSL_NO_ECDH + if (!no_ecdhe) + { + int nid; + + if (named_curve != NULL) + { + nid = OBJ_sn2nid(named_curve); + if (nid == 0) + { + BIO_printf(bio_err, "unknown curve name (%s)\n", named_curve); + goto end; + } + } + else + nid = NID_sect163r2; + + ecdh = EC_KEY_new_by_curve_name(nid); + if (ecdh == NULL) + { + BIO_printf(bio_err, "unable to create curve\n"); + goto end; + } + + SSL_CTX_set_tmp_ecdh(s_ctx, ecdh); + SSL_CTX_set_options(s_ctx, SSL_OP_SINGLE_ECDH_USE); + EC_KEY_free(ecdh); + } +#else + (void)no_ecdhe; +#endif + +#ifndef OPENSSL_NO_RSA + SSL_CTX_set_tmp_rsa_callback(s_ctx,tmp_rsa_cb); +#endif + +#ifdef TLSEXT_TYPE_opaque_prf_input + SSL_CTX_set_tlsext_opaque_prf_input_callback(c_ctx, opaque_prf_input_cb); + SSL_CTX_set_tlsext_opaque_prf_input_callback(s_ctx, opaque_prf_input_cb); + SSL_CTX_set_tlsext_opaque_prf_input_callback_arg(c_ctx, &co1); /* or &co2 or NULL */ + SSL_CTX_set_tlsext_opaque_prf_input_callback_arg(s_ctx, &so1); /* or &so2 or NULL */ +#endif + + if (!SSL_CTX_use_certificate_file(s_ctx,server_cert,SSL_FILETYPE_PEM)) + { + ERR_print_errors(bio_err); + } + else if (!SSL_CTX_use_PrivateKey_file(s_ctx, + (server_key?server_key:server_cert), SSL_FILETYPE_PEM)) + { + ERR_print_errors(bio_err); + goto end; + } + + if (client_auth) + { + SSL_CTX_use_certificate_file(c_ctx,client_cert, + SSL_FILETYPE_PEM); + SSL_CTX_use_PrivateKey_file(c_ctx, + (client_key?client_key:client_cert), + SSL_FILETYPE_PEM); + } + + if ( (!SSL_CTX_load_verify_locations(s_ctx,CAfile,CApath)) || + (!SSL_CTX_set_default_verify_paths(s_ctx)) || + (!SSL_CTX_load_verify_locations(c_ctx,CAfile,CApath)) || + (!SSL_CTX_set_default_verify_paths(c_ctx))) + { + /* fprintf(stderr,"SSL_load_verify_locations\n"); */ + ERR_print_errors(bio_err); + /* goto end; */ + } + + if (client_auth) + { + BIO_printf(bio_err,"client authentication\n"); + SSL_CTX_set_verify(s_ctx, + SSL_VERIFY_PEER|SSL_VERIFY_FAIL_IF_NO_PEER_CERT, + verify_callback); + SSL_CTX_set_cert_verify_callback(s_ctx, app_verify_callback, &app_verify_arg); + } + if (server_auth) + { + BIO_printf(bio_err,"server authentication\n"); + SSL_CTX_set_verify(c_ctx,SSL_VERIFY_PEER, + verify_callback); + SSL_CTX_set_cert_verify_callback(c_ctx, app_verify_callback, &app_verify_arg); + } + + { + int session_id_context = 0; + SSL_CTX_set_session_id_context(s_ctx, (void *)&session_id_context, sizeof session_id_context); + } + + /* Use PSK only if PSK key is given */ + if (psk_key != NULL) + { + /* no_psk is used to avoid putting psk command to openssl tool */ + if (no_psk) + { + /* if PSK is not compiled in and psk key is + * given, do nothing and exit successfully */ + ret=0; + goto end; + } +#ifndef OPENSSL_NO_PSK + SSL_CTX_set_psk_client_callback(c_ctx, psk_client_callback); + SSL_CTX_set_psk_server_callback(s_ctx, psk_server_callback); + if (debug) + BIO_printf(bio_err,"setting PSK identity hint to s_ctx\n"); + if (!SSL_CTX_use_psk_identity_hint(s_ctx, "ctx server identity_hint")) + { + BIO_printf(bio_err,"error setting PSK identity hint to s_ctx\n"); + ERR_print_errors(bio_err); + goto end; + } +#endif + } + + c_ssl=SSL_new(c_ctx); + s_ssl=SSL_new(s_ctx); + +#ifndef OPENSSL_NO_KRB5 + if (c_ssl && c_ssl->kssl_ctx) + { + char localhost[MAXHOSTNAMELEN+2]; + + if (gethostname(localhost, sizeof localhost-1) == 0) + { + localhost[sizeof localhost-1]='\0'; + if(strlen(localhost) == sizeof localhost-1) + { + BIO_printf(bio_err,"localhost name too long\n"); + goto end; + } + kssl_ctx_setstring(c_ssl->kssl_ctx, KSSL_SERVER, + localhost); + } + } +#endif /* OPENSSL_NO_KRB5 */ + + for (i=0; i 1) || (bytes > 1L)) + BIO_printf(bio_stdout, "%d handshakes of %ld bytes done\n",number,bytes); + if (print_time) + { +#ifdef CLOCKS_PER_SEC + /* "To determine the time in seconds, the value returned + * by the clock function should be divided by the value + * of the macro CLOCKS_PER_SEC." + * -- ISO/IEC 9899 */ + BIO_printf(bio_stdout, "Approximate total server time: %6.2f s\n" + "Approximate total client time: %6.2f s\n", + (double)s_time/CLOCKS_PER_SEC, + (double)c_time/CLOCKS_PER_SEC); +#else + /* "`CLOCKS_PER_SEC' undeclared (first use this function)" + * -- cc on NeXTstep/OpenStep */ + BIO_printf(bio_stdout, + "Approximate total server time: %6.2f units\n" + "Approximate total client time: %6.2f units\n", + (double)s_time, + (double)c_time); +#endif + } + + SSL_free(s_ssl); + SSL_free(c_ssl); + +end: + if (s_ctx != NULL) SSL_CTX_free(s_ctx); + if (c_ctx != NULL) SSL_CTX_free(c_ctx); + + if (bio_stdout != NULL) BIO_free(bio_stdout); + +#ifndef OPENSSL_NO_RSA + free_tmp_rsa(); +#endif +#ifndef OPENSSL_NO_ENGINE + ENGINE_cleanup(); +#endif + CRYPTO_cleanup_all_ex_data(); + ERR_free_strings(); + ERR_remove_thread_state(NULL); + EVP_cleanup(); + CRYPTO_mem_leaks(bio_err); + if (bio_err != NULL) BIO_free(bio_err); + EXIT(ret); + return ret; + } + +int doit_biopair(SSL *s_ssl, SSL *c_ssl, long count, + clock_t *s_time, clock_t *c_time) + { + long cw_num = count, cr_num = count, sw_num = count, sr_num = count; + BIO *s_ssl_bio = NULL, *c_ssl_bio = NULL; + BIO *server = NULL, *server_io = NULL, *client = NULL, *client_io = NULL; + int ret = 1; + + size_t bufsiz = 256; /* small buffer for testing */ + + if (!BIO_new_bio_pair(&server, bufsiz, &server_io, bufsiz)) + goto err; + if (!BIO_new_bio_pair(&client, bufsiz, &client_io, bufsiz)) + goto err; + + s_ssl_bio = BIO_new(BIO_f_ssl()); + if (!s_ssl_bio) + goto err; + + c_ssl_bio = BIO_new(BIO_f_ssl()); + if (!c_ssl_bio) + goto err; + + SSL_set_connect_state(c_ssl); + SSL_set_bio(c_ssl, client, client); + (void)BIO_set_ssl(c_ssl_bio, c_ssl, BIO_NOCLOSE); + + SSL_set_accept_state(s_ssl); + SSL_set_bio(s_ssl, server, server); + (void)BIO_set_ssl(s_ssl_bio, s_ssl, BIO_NOCLOSE); + + do + { + /* c_ssl_bio: SSL filter BIO + * + * client: pseudo-I/O for SSL library + * + * client_io: client's SSL communication; usually to be + * relayed over some I/O facility, but in this + * test program, we're the server, too: + * + * server_io: server's SSL communication + * + * server: pseudo-I/O for SSL library + * + * s_ssl_bio: SSL filter BIO + * + * The client and the server each employ a "BIO pair": + * client + client_io, server + server_io. + * BIO pairs are symmetric. A BIO pair behaves similar + * to a non-blocking socketpair (but both endpoints must + * be handled by the same thread). + * [Here we could connect client and server to the ends + * of a single BIO pair, but then this code would be less + * suitable as an example for BIO pairs in general.] + * + * Useful functions for querying the state of BIO pair endpoints: + * + * BIO_ctrl_pending(bio) number of bytes we can read now + * BIO_ctrl_get_read_request(bio) number of bytes needed to fulfil + * other side's read attempt + * BIO_ctrl_get_write_guarantee(bio) number of bytes we can write now + * + * ..._read_request is never more than ..._write_guarantee; + * it depends on the application which one you should use. + */ + + /* We have non-blocking behaviour throughout this test program, but + * can be sure that there is *some* progress in each iteration; so + * we don't have to worry about ..._SHOULD_READ or ..._SHOULD_WRITE + * -- we just try everything in each iteration + */ + + { + /* CLIENT */ + + MS_STATIC char cbuf[1024*8]; + int i, r; + clock_t c_clock = clock(); + + memset(cbuf, 0, sizeof(cbuf)); + + if (debug) + if (SSL_in_init(c_ssl)) + printf("client waiting in SSL_connect - %s\n", + SSL_state_string_long(c_ssl)); + + if (cw_num > 0) + { + /* Write to server. */ + + if (cw_num > (long)sizeof cbuf) + i = sizeof cbuf; + else + i = (int)cw_num; + r = BIO_write(c_ssl_bio, cbuf, i); + if (r < 0) + { + if (!BIO_should_retry(c_ssl_bio)) + { + fprintf(stderr,"ERROR in CLIENT\n"); + goto err; + } + /* BIO_should_retry(...) can just be ignored here. + * The library expects us to call BIO_write with + * the same arguments again, and that's what we will + * do in the next iteration. */ + } + else if (r == 0) + { + fprintf(stderr,"SSL CLIENT STARTUP FAILED\n"); + goto err; + } + else + { + if (debug) + printf("client wrote %d\n", r); + cw_num -= r; + } + } + + if (cr_num > 0) + { + /* Read from server. */ + + r = BIO_read(c_ssl_bio, cbuf, sizeof(cbuf)); + if (r < 0) + { + if (!BIO_should_retry(c_ssl_bio)) + { + fprintf(stderr,"ERROR in CLIENT\n"); + goto err; + } + /* Again, "BIO_should_retry" can be ignored. */ + } + else if (r == 0) + { + fprintf(stderr,"SSL CLIENT STARTUP FAILED\n"); + goto err; + } + else + { + if (debug) + printf("client read %d\n", r); + cr_num -= r; + } + } + + /* c_time and s_time increments will typically be very small + * (depending on machine speed and clock tick intervals), + * but sampling over a large number of connections should + * result in fairly accurate figures. We cannot guarantee + * a lot, however -- if each connection lasts for exactly + * one clock tick, it will be counted only for the client + * or only for the server or even not at all. + */ + *c_time += (clock() - c_clock); + } + + { + /* SERVER */ + + MS_STATIC char sbuf[1024*8]; + int i, r; + clock_t s_clock = clock(); + + memset(sbuf, 0, sizeof(sbuf)); + + if (debug) + if (SSL_in_init(s_ssl)) + printf("server waiting in SSL_accept - %s\n", + SSL_state_string_long(s_ssl)); + + if (sw_num > 0) + { + /* Write to client. */ + + if (sw_num > (long)sizeof sbuf) + i = sizeof sbuf; + else + i = (int)sw_num; + r = BIO_write(s_ssl_bio, sbuf, i); + if (r < 0) + { + if (!BIO_should_retry(s_ssl_bio)) + { + fprintf(stderr,"ERROR in SERVER\n"); + goto err; + } + /* Ignore "BIO_should_retry". */ + } + else if (r == 0) + { + fprintf(stderr,"SSL SERVER STARTUP FAILED\n"); + goto err; + } + else + { + if (debug) + printf("server wrote %d\n", r); + sw_num -= r; + } + } + + if (sr_num > 0) + { + /* Read from client. */ + + r = BIO_read(s_ssl_bio, sbuf, sizeof(sbuf)); + if (r < 0) + { + if (!BIO_should_retry(s_ssl_bio)) + { + fprintf(stderr,"ERROR in SERVER\n"); + goto err; + } + /* blah, blah */ + } + else if (r == 0) + { + fprintf(stderr,"SSL SERVER STARTUP FAILED\n"); + goto err; + } + else + { + if (debug) + printf("server read %d\n", r); + sr_num -= r; + } + } + + *s_time += (clock() - s_clock); + } + + { + /* "I/O" BETWEEN CLIENT AND SERVER. */ + + size_t r1, r2; + BIO *io1 = server_io, *io2 = client_io; + /* we use the non-copying interface for io1 + * and the standard BIO_write/BIO_read interface for io2 + */ + + static int prev_progress = 1; + int progress = 0; + + /* io1 to io2 */ + do + { + size_t num; + int r; + + r1 = BIO_ctrl_pending(io1); + r2 = BIO_ctrl_get_write_guarantee(io2); + + num = r1; + if (r2 < num) + num = r2; + if (num) + { + char *dataptr; + + if (INT_MAX < num) /* yeah, right */ + num = INT_MAX; + + r = BIO_nread(io1, &dataptr, (int)num); + assert(r > 0); + assert(r <= (int)num); + /* possibly r < num (non-contiguous data) */ + num = r; + r = BIO_write(io2, dataptr, (int)num); + if (r != (int)num) /* can't happen */ + { + fprintf(stderr, "ERROR: BIO_write could not write " + "BIO_ctrl_get_write_guarantee() bytes"); + goto err; + } + progress = 1; + + if (debug) + printf((io1 == client_io) ? + "C->S relaying: %d bytes\n" : + "S->C relaying: %d bytes\n", + (int)num); + } + } + while (r1 && r2); + + /* io2 to io1 */ + { + size_t num; + int r; + + r1 = BIO_ctrl_pending(io2); + r2 = BIO_ctrl_get_read_request(io1); + /* here we could use ..._get_write_guarantee instead of + * ..._get_read_request, but by using the latter + * we test restartability of the SSL implementation + * more thoroughly */ + num = r1; + if (r2 < num) + num = r2; + if (num) + { + char *dataptr; + + if (INT_MAX < num) + num = INT_MAX; + + if (num > 1) + --num; /* test restartability even more thoroughly */ + + r = BIO_nwrite0(io1, &dataptr); + assert(r > 0); + if (r < (int)num) + num = r; + r = BIO_read(io2, dataptr, (int)num); + if (r != (int)num) /* can't happen */ + { + fprintf(stderr, "ERROR: BIO_read could not read " + "BIO_ctrl_pending() bytes"); + goto err; + } + progress = 1; + r = BIO_nwrite(io1, &dataptr, (int)num); + if (r != (int)num) /* can't happen */ + { + fprintf(stderr, "ERROR: BIO_nwrite() did not accept " + "BIO_nwrite0() bytes"); + goto err; + } + + if (debug) + printf((io2 == client_io) ? + "C->S relaying: %d bytes\n" : + "S->C relaying: %d bytes\n", + (int)num); + } + } /* no loop, BIO_ctrl_get_read_request now returns 0 anyway */ + + if (!progress && !prev_progress) + if (cw_num > 0 || cr_num > 0 || sw_num > 0 || sr_num > 0) + { + fprintf(stderr, "ERROR: got stuck\n"); + if (strcmp("SSLv2", SSL_get_version(c_ssl)) == 0) + { + fprintf(stderr, "This can happen for SSL2 because " + "CLIENT-FINISHED and SERVER-VERIFY are written \n" + "concurrently ..."); + if (strncmp("2SCF", SSL_state_string(c_ssl), 4) == 0 + && strncmp("2SSV", SSL_state_string(s_ssl), 4) == 0) + { + fprintf(stderr, " ok.\n"); + goto end; + } + } + fprintf(stderr, " ERROR.\n"); + goto err; + } + prev_progress = progress; + } + } + while (cw_num > 0 || cr_num > 0 || sw_num > 0 || sr_num > 0); + + if (verbose) + print_details(c_ssl, "DONE via BIO pair: "); +end: + ret = 0; + + err: + ERR_print_errors(bio_err); + + if (server) + BIO_free(server); + if (server_io) + BIO_free(server_io); + if (client) + BIO_free(client); + if (client_io) + BIO_free(client_io); + if (s_ssl_bio) + BIO_free(s_ssl_bio); + if (c_ssl_bio) + BIO_free(c_ssl_bio); + + return ret; + } + + +#define W_READ 1 +#define W_WRITE 2 +#define C_DONE 1 +#define S_DONE 2 + +int doit(SSL *s_ssl, SSL *c_ssl, long count) + { + MS_STATIC char cbuf[1024*8],sbuf[1024*8]; + long cw_num=count,cr_num=count; + long sw_num=count,sr_num=count; + int ret=1; + BIO *c_to_s=NULL; + BIO *s_to_c=NULL; + BIO *c_bio=NULL; + BIO *s_bio=NULL; + int c_r,c_w,s_r,s_w; + int i,j; + int done=0; + int c_write,s_write; + int do_server=0,do_client=0; + + memset(cbuf,0,sizeof(cbuf)); + memset(sbuf,0,sizeof(sbuf)); + + c_to_s=BIO_new(BIO_s_mem()); + s_to_c=BIO_new(BIO_s_mem()); + if ((s_to_c == NULL) || (c_to_s == NULL)) + { + ERR_print_errors(bio_err); + goto err; + } + + c_bio=BIO_new(BIO_f_ssl()); + s_bio=BIO_new(BIO_f_ssl()); + if ((c_bio == NULL) || (s_bio == NULL)) + { + ERR_print_errors(bio_err); + goto err; + } + + SSL_set_connect_state(c_ssl); + SSL_set_bio(c_ssl,s_to_c,c_to_s); + BIO_set_ssl(c_bio,c_ssl,BIO_NOCLOSE); + + SSL_set_accept_state(s_ssl); + SSL_set_bio(s_ssl,c_to_s,s_to_c); + BIO_set_ssl(s_bio,s_ssl,BIO_NOCLOSE); + + c_r=0; s_r=1; + c_w=1; s_w=0; + c_write=1,s_write=0; + + /* We can always do writes */ + for (;;) + { + do_server=0; + do_client=0; + + i=(int)BIO_pending(s_bio); + if ((i && s_r) || s_w) do_server=1; + + i=(int)BIO_pending(c_bio); + if ((i && c_r) || c_w) do_client=1; + + if (do_server && debug) + { + if (SSL_in_init(s_ssl)) + printf("server waiting in SSL_accept - %s\n", + SSL_state_string_long(s_ssl)); +/* else if (s_write) + printf("server:SSL_write()\n"); + else + printf("server:SSL_read()\n"); */ + } + + if (do_client && debug) + { + if (SSL_in_init(c_ssl)) + printf("client waiting in SSL_connect - %s\n", + SSL_state_string_long(c_ssl)); +/* else if (c_write) + printf("client:SSL_write()\n"); + else + printf("client:SSL_read()\n"); */ + } + + if (!do_client && !do_server) + { + fprintf(stdout,"ERROR IN STARTUP\n"); + ERR_print_errors(bio_err); + break; + } + if (do_client && !(done & C_DONE)) + { + if (c_write) + { + j = (cw_num > (long)sizeof(cbuf)) ? + (int)sizeof(cbuf) : (int)cw_num; + i=BIO_write(c_bio,cbuf,j); + if (i < 0) + { + c_r=0; + c_w=0; + if (BIO_should_retry(c_bio)) + { + if (BIO_should_read(c_bio)) + c_r=1; + if (BIO_should_write(c_bio)) + c_w=1; + } + else + { + fprintf(stderr,"ERROR in CLIENT\n"); + ERR_print_errors(bio_err); + goto err; + } + } + else if (i == 0) + { + fprintf(stderr,"SSL CLIENT STARTUP FAILED\n"); + goto err; + } + else + { + if (debug) + printf("client wrote %d\n",i); + /* ok */ + s_r=1; + c_write=0; + cw_num-=i; + } + } + else + { + i=BIO_read(c_bio,cbuf,sizeof(cbuf)); + if (i < 0) + { + c_r=0; + c_w=0; + if (BIO_should_retry(c_bio)) + { + if (BIO_should_read(c_bio)) + c_r=1; + if (BIO_should_write(c_bio)) + c_w=1; + } + else + { + fprintf(stderr,"ERROR in CLIENT\n"); + ERR_print_errors(bio_err); + goto err; + } + } + else if (i == 0) + { + fprintf(stderr,"SSL CLIENT STARTUP FAILED\n"); + goto err; + } + else + { + if (debug) + printf("client read %d\n",i); + cr_num-=i; + if (sw_num > 0) + { + s_write=1; + s_w=1; + } + if (cr_num <= 0) + { + s_write=1; + s_w=1; + done=S_DONE|C_DONE; + } + } + } + } + + if (do_server && !(done & S_DONE)) + { + if (!s_write) + { + i=BIO_read(s_bio,sbuf,sizeof(cbuf)); + if (i < 0) + { + s_r=0; + s_w=0; + if (BIO_should_retry(s_bio)) + { + if (BIO_should_read(s_bio)) + s_r=1; + if (BIO_should_write(s_bio)) + s_w=1; + } + else + { + fprintf(stderr,"ERROR in SERVER\n"); + ERR_print_errors(bio_err); + goto err; + } + } + else if (i == 0) + { + ERR_print_errors(bio_err); + fprintf(stderr,"SSL SERVER STARTUP FAILED in SSL_read\n"); + goto err; + } + else + { + if (debug) + printf("server read %d\n",i); + sr_num-=i; + if (cw_num > 0) + { + c_write=1; + c_w=1; + } + if (sr_num <= 0) + { + s_write=1; + s_w=1; + c_write=0; + } + } + } + else + { + j = (sw_num > (long)sizeof(sbuf)) ? + (int)sizeof(sbuf) : (int)sw_num; + i=BIO_write(s_bio,sbuf,j); + if (i < 0) + { + s_r=0; + s_w=0; + if (BIO_should_retry(s_bio)) + { + if (BIO_should_read(s_bio)) + s_r=1; + if (BIO_should_write(s_bio)) + s_w=1; + } + else + { + fprintf(stderr,"ERROR in SERVER\n"); + ERR_print_errors(bio_err); + goto err; + } + } + else if (i == 0) + { + ERR_print_errors(bio_err); + fprintf(stderr,"SSL SERVER STARTUP FAILED in SSL_write\n"); + goto err; + } + else + { + if (debug) + printf("server wrote %d\n",i); + sw_num-=i; + s_write=0; + c_r=1; + if (sw_num <= 0) + done|=S_DONE; + } + } + } + + if ((done & S_DONE) && (done & C_DONE)) break; + } + + if (verbose) + print_details(c_ssl, "DONE: "); + ret=0; +err: + /* We have to set the BIO's to NULL otherwise they will be + * OPENSSL_free()ed twice. Once when th s_ssl is SSL_free()ed and + * again when c_ssl is SSL_free()ed. + * This is a hack required because s_ssl and c_ssl are sharing the same + * BIO structure and SSL_set_bio() and SSL_free() automatically + * BIO_free non NULL entries. + * You should not normally do this or be required to do this */ + if (s_ssl != NULL) + { + s_ssl->rbio=NULL; + s_ssl->wbio=NULL; + } + if (c_ssl != NULL) + { + c_ssl->rbio=NULL; + c_ssl->wbio=NULL; + } + + if (c_to_s != NULL) BIO_free(c_to_s); + if (s_to_c != NULL) BIO_free(s_to_c); + if (c_bio != NULL) BIO_free_all(c_bio); + if (s_bio != NULL) BIO_free_all(s_bio); + return(ret); + } + +static int get_proxy_auth_ex_data_idx(void) + { + static volatile int idx = -1; + if (idx < 0) + { + CRYPTO_w_lock(CRYPTO_LOCK_SSL_CTX); + if (idx < 0) + { + idx = X509_STORE_CTX_get_ex_new_index(0, + "SSLtest for verify callback", NULL,NULL,NULL); + } + CRYPTO_w_unlock(CRYPTO_LOCK_SSL_CTX); + } + return idx; + } + +static int MS_CALLBACK verify_callback(int ok, X509_STORE_CTX *ctx) + { + char *s,buf[256]; + + s=X509_NAME_oneline(X509_get_subject_name(ctx->current_cert),buf, + sizeof buf); + if (s != NULL) + { + if (ok) + fprintf(stderr,"depth=%d %s\n", + ctx->error_depth,buf); + else + { + fprintf(stderr,"depth=%d error=%d %s\n", + ctx->error_depth,ctx->error,buf); + } + } + + if (ok == 0) + { + fprintf(stderr,"Error string: %s\n", + X509_verify_cert_error_string(ctx->error)); + switch (ctx->error) + { + case X509_V_ERR_CERT_NOT_YET_VALID: + case X509_V_ERR_CERT_HAS_EXPIRED: + case X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT: + fprintf(stderr," ... ignored.\n"); + ok=1; + } + } + + if (ok == 1) + { + X509 *xs = ctx->current_cert; +#if 0 + X509 *xi = ctx->current_issuer; +#endif + + if (xs->ex_flags & EXFLAG_PROXY) + { + unsigned int *letters = + X509_STORE_CTX_get_ex_data(ctx, + get_proxy_auth_ex_data_idx()); + + if (letters) + { + int found_any = 0; + int i; + PROXY_CERT_INFO_EXTENSION *pci = + X509_get_ext_d2i(xs, NID_proxyCertInfo, + NULL, NULL); + + switch (OBJ_obj2nid(pci->proxyPolicy->policyLanguage)) + { + case NID_Independent: + /* Completely meaningless in this + program, as there's no way to + grant explicit rights to a + specific PrC. Basically, using + id-ppl-Independent is the perfect + way to grant no rights at all. */ + fprintf(stderr, " Independent proxy certificate"); + for (i = 0; i < 26; i++) + letters[i] = 0; + break; + case NID_id_ppl_inheritAll: + /* This is basically a NOP, we + simply let the current rights + stand as they are. */ + fprintf(stderr, " Proxy certificate inherits all"); + break; + default: + s = (char *) + pci->proxyPolicy->policy->data; + i = pci->proxyPolicy->policy->length; + + /* The algorithm works as follows: + it is assumed that previous + iterations or the initial granted + rights has already set some elements + of `letters'. What we need to do is + to clear those that weren't granted + by the current PrC as well. The + easiest way to do this is to add 1 + to all the elements whose letters + are given with the current policy. + That way, all elements that are set + by the current policy and were + already set by earlier policies and + through the original grant of rights + will get the value 2 or higher. + The last thing to do is to sweep + through `letters' and keep the + elements having the value 2 as set, + and clear all the others. */ + + fprintf(stderr, " Certificate proxy rights = %*.*s", i, i, s); + while(i-- > 0) + { + int c = *s++; + if (isascii(c) && isalpha(c)) + { + if (islower(c)) + c = toupper(c); + letters[c - 'A']++; + } + } + for (i = 0; i < 26; i++) + if (letters[i] < 2) + letters[i] = 0; + else + letters[i] = 1; + } + + found_any = 0; + fprintf(stderr, + ", resulting proxy rights = "); + for(i = 0; i < 26; i++) + if (letters[i]) + { + fprintf(stderr, "%c", i + 'A'); + found_any = 1; + } + if (!found_any) + fprintf(stderr, "none"); + fprintf(stderr, "\n"); + + PROXY_CERT_INFO_EXTENSION_free(pci); + } + } + } + + return(ok); + } + +static void process_proxy_debug(int indent, const char *format, ...) + { + static const char indentation[] = + ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>" + ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"; /* That's 80 > */ + char my_format[256]; + va_list args; + + BIO_snprintf(my_format, sizeof(my_format), "%*.*s %s", + indent, indent, indentation, format); + + va_start(args, format); + vfprintf(stderr, my_format, args); + va_end(args); + } +/* Priority levels: + 0 [!]var, () + 1 & ^ + 2 | +*/ +static int process_proxy_cond_adders(unsigned int letters[26], + const char *cond, const char **cond_end, int *pos, int indent); +static int process_proxy_cond_val(unsigned int letters[26], + const char *cond, const char **cond_end, int *pos, int indent) + { + int c; + int ok = 1; + int negate = 0; + + while(isspace((int)*cond)) + { + cond++; (*pos)++; + } + c = *cond; + + if (debug) + process_proxy_debug(indent, + "Start process_proxy_cond_val at position %d: %s\n", + *pos, cond); + + while(c == '!') + { + negate = !negate; + cond++; (*pos)++; + while(isspace((int)*cond)) + { + cond++; (*pos)++; + } + c = *cond; + } + + if (c == '(') + { + cond++; (*pos)++; + ok = process_proxy_cond_adders(letters, cond, cond_end, pos, + indent + 1); + cond = *cond_end; + if (ok < 0) + goto end; + while(isspace((int)*cond)) + { + cond++; (*pos)++; + } + c = *cond; + if (c != ')') + { + fprintf(stderr, + "Weird condition character in position %d: " + "%c\n", *pos, c); + ok = -1; + goto end; + } + cond++; (*pos)++; + } + else if (isascii(c) && isalpha(c)) + { + if (islower(c)) + c = toupper(c); + ok = letters[c - 'A']; + cond++; (*pos)++; + } + else + { + fprintf(stderr, + "Weird condition character in position %d: " + "%c\n", *pos, c); + ok = -1; + goto end; + } + end: + *cond_end = cond; + if (ok >= 0 && negate) + ok = !ok; + + if (debug) + process_proxy_debug(indent, + "End process_proxy_cond_val at position %d: %s, returning %d\n", + *pos, cond, ok); + + return ok; + } +static int process_proxy_cond_multipliers(unsigned int letters[26], + const char *cond, const char **cond_end, int *pos, int indent) + { + int ok; + char c; + + if (debug) + process_proxy_debug(indent, + "Start process_proxy_cond_multipliers at position %d: %s\n", + *pos, cond); + + ok = process_proxy_cond_val(letters, cond, cond_end, pos, indent + 1); + cond = *cond_end; + if (ok < 0) + goto end; + + while(ok >= 0) + { + while(isspace((int)*cond)) + { + cond++; (*pos)++; + } + c = *cond; + + switch(c) + { + case '&': + case '^': + { + int save_ok = ok; + + cond++; (*pos)++; + ok = process_proxy_cond_val(letters, + cond, cond_end, pos, indent + 1); + cond = *cond_end; + if (ok < 0) + break; + + switch(c) + { + case '&': + ok &= save_ok; + break; + case '^': + ok ^= save_ok; + break; + default: + fprintf(stderr, "SOMETHING IS SERIOUSLY WRONG!" + " STOPPING\n"); + EXIT(1); + } + } + break; + default: + goto end; + } + } + end: + if (debug) + process_proxy_debug(indent, + "End process_proxy_cond_multipliers at position %d: %s, returning %d\n", + *pos, cond, ok); + + *cond_end = cond; + return ok; + } +static int process_proxy_cond_adders(unsigned int letters[26], + const char *cond, const char **cond_end, int *pos, int indent) + { + int ok; + char c; + + if (debug) + process_proxy_debug(indent, + "Start process_proxy_cond_adders at position %d: %s\n", + *pos, cond); + + ok = process_proxy_cond_multipliers(letters, cond, cond_end, pos, + indent + 1); + cond = *cond_end; + if (ok < 0) + goto end; + + while(ok >= 0) + { + while(isspace((int)*cond)) + { + cond++; (*pos)++; + } + c = *cond; + + switch(c) + { + case '|': + { + int save_ok = ok; + + cond++; (*pos)++; + ok = process_proxy_cond_multipliers(letters, + cond, cond_end, pos, indent + 1); + cond = *cond_end; + if (ok < 0) + break; + + switch(c) + { + case '|': + ok |= save_ok; + break; + default: + fprintf(stderr, "SOMETHING IS SERIOUSLY WRONG!" + " STOPPING\n"); + EXIT(1); + } + } + break; + default: + goto end; + } + } + end: + if (debug) + process_proxy_debug(indent, + "End process_proxy_cond_adders at position %d: %s, returning %d\n", + *pos, cond, ok); + + *cond_end = cond; + return ok; + } + +static int process_proxy_cond(unsigned int letters[26], + const char *cond, const char **cond_end) + { + int pos = 1; + return process_proxy_cond_adders(letters, cond, cond_end, &pos, 1); + } + +static int MS_CALLBACK app_verify_callback(X509_STORE_CTX *ctx, void *arg) + { + int ok=1; + struct app_verify_arg *cb_arg = arg; + unsigned int letters[26]; /* only used with proxy_auth */ + + if (cb_arg->app_verify) + { + char *s = NULL,buf[256]; + + fprintf(stderr, "In app_verify_callback, allowing cert. "); + fprintf(stderr, "Arg is: %s\n", cb_arg->string); + fprintf(stderr, "Finished printing do we have a context? 0x%p a cert? 0x%p\n", + (void *)ctx, (void *)ctx->cert); + if (ctx->cert) + s=X509_NAME_oneline(X509_get_subject_name(ctx->cert),buf,256); + if (s != NULL) + { + fprintf(stderr,"cert depth=%d %s\n",ctx->error_depth,buf); + } + return(1); + } + if (cb_arg->proxy_auth) + { + int found_any = 0, i; + char *sp; + + for(i = 0; i < 26; i++) + letters[i] = 0; + for(sp = cb_arg->proxy_auth; *sp; sp++) + { + int c = *sp; + if (isascii(c) && isalpha(c)) + { + if (islower(c)) + c = toupper(c); + letters[c - 'A'] = 1; + } + } + + fprintf(stderr, + " Initial proxy rights = "); + for(i = 0; i < 26; i++) + if (letters[i]) + { + fprintf(stderr, "%c", i + 'A'); + found_any = 1; + } + if (!found_any) + fprintf(stderr, "none"); + fprintf(stderr, "\n"); + + X509_STORE_CTX_set_ex_data(ctx, + get_proxy_auth_ex_data_idx(),letters); + } + if (cb_arg->allow_proxy_certs) + { + X509_STORE_CTX_set_flags(ctx, X509_V_FLAG_ALLOW_PROXY_CERTS); + } + +#ifndef OPENSSL_NO_X509_VERIFY +# ifdef OPENSSL_FIPS + if(s->version == TLS1_VERSION) + FIPS_allow_md5(1); +# endif + ok = X509_verify_cert(ctx); +# ifdef OPENSSL_FIPS + if(s->version == TLS1_VERSION) + FIPS_allow_md5(0); +# endif +#endif + + if (cb_arg->proxy_auth) + { + if (ok > 0) + { + const char *cond_end = NULL; + + ok = process_proxy_cond(letters, + cb_arg->proxy_cond, &cond_end); + + if (ok < 0) + EXIT(3); + if (*cond_end) + { + fprintf(stderr, "Stopped processing condition before it's end.\n"); + ok = 0; + } + if (!ok) + fprintf(stderr, "Proxy rights check with condition '%s' proved invalid\n", + cb_arg->proxy_cond); + else + fprintf(stderr, "Proxy rights check with condition '%s' proved valid\n", + cb_arg->proxy_cond); + } + } + return(ok); + } + +#ifndef OPENSSL_NO_RSA +static RSA *rsa_tmp=NULL; + +static RSA MS_CALLBACK *tmp_rsa_cb(SSL *s, int is_export, int keylength) + { + BIGNUM *bn = NULL; + if (rsa_tmp == NULL) + { + bn = BN_new(); + rsa_tmp = RSA_new(); + if(!bn || !rsa_tmp || !BN_set_word(bn, RSA_F4)) + { + BIO_printf(bio_err, "Memory error..."); + goto end; + } + BIO_printf(bio_err,"Generating temp (%d bit) RSA key...",keylength); + (void)BIO_flush(bio_err); + if(!RSA_generate_key_ex(rsa_tmp,keylength,bn,NULL)) + { + BIO_printf(bio_err, "Error generating key."); + RSA_free(rsa_tmp); + rsa_tmp = NULL; + } +end: + BIO_printf(bio_err,"\n"); + (void)BIO_flush(bio_err); + } + if(bn) BN_free(bn); + return(rsa_tmp); + } + +static void free_tmp_rsa(void) + { + if (rsa_tmp != NULL) + { + RSA_free(rsa_tmp); + rsa_tmp = NULL; + } + } +#endif + +#ifndef OPENSSL_NO_DH +/* These DH parameters have been generated as follows: + * $ openssl dhparam -C -noout 512 + * $ openssl dhparam -C -noout 1024 + * $ openssl dhparam -C -noout -dsaparam 1024 + * (The third function has been renamed to avoid name conflicts.) + */ +static DH *get_dh512() + { + static unsigned char dh512_p[]={ + 0xCB,0xC8,0xE1,0x86,0xD0,0x1F,0x94,0x17,0xA6,0x99,0xF0,0xC6, + 0x1F,0x0D,0xAC,0xB6,0x25,0x3E,0x06,0x39,0xCA,0x72,0x04,0xB0, + 0x6E,0xDA,0xC0,0x61,0xE6,0x7A,0x77,0x25,0xE8,0x3B,0xB9,0x5F, + 0x9A,0xB6,0xB5,0xFE,0x99,0x0B,0xA1,0x93,0x4E,0x35,0x33,0xB8, + 0xE1,0xF1,0x13,0x4F,0x59,0x1A,0xD2,0x57,0xC0,0x26,0x21,0x33, + 0x02,0xC5,0xAE,0x23, + }; + static unsigned char dh512_g[]={ + 0x02, + }; + DH *dh; + + if ((dh=DH_new()) == NULL) return(NULL); + dh->p=BN_bin2bn(dh512_p,sizeof(dh512_p),NULL); + dh->g=BN_bin2bn(dh512_g,sizeof(dh512_g),NULL); + if ((dh->p == NULL) || (dh->g == NULL)) + { DH_free(dh); return(NULL); } + return(dh); + } + +static DH *get_dh1024() + { + static unsigned char dh1024_p[]={ + 0xF8,0x81,0x89,0x7D,0x14,0x24,0xC5,0xD1,0xE6,0xF7,0xBF,0x3A, + 0xE4,0x90,0xF4,0xFC,0x73,0xFB,0x34,0xB5,0xFA,0x4C,0x56,0xA2, + 0xEA,0xA7,0xE9,0xC0,0xC0,0xCE,0x89,0xE1,0xFA,0x63,0x3F,0xB0, + 0x6B,0x32,0x66,0xF1,0xD1,0x7B,0xB0,0x00,0x8F,0xCA,0x87,0xC2, + 0xAE,0x98,0x89,0x26,0x17,0xC2,0x05,0xD2,0xEC,0x08,0xD0,0x8C, + 0xFF,0x17,0x52,0x8C,0xC5,0x07,0x93,0x03,0xB1,0xF6,0x2F,0xB8, + 0x1C,0x52,0x47,0x27,0x1B,0xDB,0xD1,0x8D,0x9D,0x69,0x1D,0x52, + 0x4B,0x32,0x81,0xAA,0x7F,0x00,0xC8,0xDC,0xE6,0xD9,0xCC,0xC1, + 0x11,0x2D,0x37,0x34,0x6C,0xEA,0x02,0x97,0x4B,0x0E,0xBB,0xB1, + 0x71,0x33,0x09,0x15,0xFD,0xDD,0x23,0x87,0x07,0x5E,0x89,0xAB, + 0x6B,0x7C,0x5F,0xEC,0xA6,0x24,0xDC,0x53, + }; + static unsigned char dh1024_g[]={ + 0x02, + }; + DH *dh; + + if ((dh=DH_new()) == NULL) return(NULL); + dh->p=BN_bin2bn(dh1024_p,sizeof(dh1024_p),NULL); + dh->g=BN_bin2bn(dh1024_g,sizeof(dh1024_g),NULL); + if ((dh->p == NULL) || (dh->g == NULL)) + { DH_free(dh); return(NULL); } + return(dh); + } + +static DH *get_dh1024dsa() + { + static unsigned char dh1024_p[]={ + 0xC8,0x00,0xF7,0x08,0x07,0x89,0x4D,0x90,0x53,0xF3,0xD5,0x00, + 0x21,0x1B,0xF7,0x31,0xA6,0xA2,0xDA,0x23,0x9A,0xC7,0x87,0x19, + 0x3B,0x47,0xB6,0x8C,0x04,0x6F,0xFF,0xC6,0x9B,0xB8,0x65,0xD2, + 0xC2,0x5F,0x31,0x83,0x4A,0xA7,0x5F,0x2F,0x88,0x38,0xB6,0x55, + 0xCF,0xD9,0x87,0x6D,0x6F,0x9F,0xDA,0xAC,0xA6,0x48,0xAF,0xFC, + 0x33,0x84,0x37,0x5B,0x82,0x4A,0x31,0x5D,0xE7,0xBD,0x52,0x97, + 0xA1,0x77,0xBF,0x10,0x9E,0x37,0xEA,0x64,0xFA,0xCA,0x28,0x8D, + 0x9D,0x3B,0xD2,0x6E,0x09,0x5C,0x68,0xC7,0x45,0x90,0xFD,0xBB, + 0x70,0xC9,0x3A,0xBB,0xDF,0xD4,0x21,0x0F,0xC4,0x6A,0x3C,0xF6, + 0x61,0xCF,0x3F,0xD6,0x13,0xF1,0x5F,0xBC,0xCF,0xBC,0x26,0x9E, + 0xBC,0x0B,0xBD,0xAB,0x5D,0xC9,0x54,0x39, + }; + static unsigned char dh1024_g[]={ + 0x3B,0x40,0x86,0xE7,0xF3,0x6C,0xDE,0x67,0x1C,0xCC,0x80,0x05, + 0x5A,0xDF,0xFE,0xBD,0x20,0x27,0x74,0x6C,0x24,0xC9,0x03,0xF3, + 0xE1,0x8D,0xC3,0x7D,0x98,0x27,0x40,0x08,0xB8,0x8C,0x6A,0xE9, + 0xBB,0x1A,0x3A,0xD6,0x86,0x83,0x5E,0x72,0x41,0xCE,0x85,0x3C, + 0xD2,0xB3,0xFC,0x13,0xCE,0x37,0x81,0x9E,0x4C,0x1C,0x7B,0x65, + 0xD3,0xE6,0xA6,0x00,0xF5,0x5A,0x95,0x43,0x5E,0x81,0xCF,0x60, + 0xA2,0x23,0xFC,0x36,0xA7,0x5D,0x7A,0x4C,0x06,0x91,0x6E,0xF6, + 0x57,0xEE,0x36,0xCB,0x06,0xEA,0xF5,0x3D,0x95,0x49,0xCB,0xA7, + 0xDD,0x81,0xDF,0x80,0x09,0x4A,0x97,0x4D,0xA8,0x22,0x72,0xA1, + 0x7F,0xC4,0x70,0x56,0x70,0xE8,0x20,0x10,0x18,0x8F,0x2E,0x60, + 0x07,0xE7,0x68,0x1A,0x82,0x5D,0x32,0xA2, + }; + DH *dh; + + if ((dh=DH_new()) == NULL) return(NULL); + dh->p=BN_bin2bn(dh1024_p,sizeof(dh1024_p),NULL); + dh->g=BN_bin2bn(dh1024_g,sizeof(dh1024_g),NULL); + if ((dh->p == NULL) || (dh->g == NULL)) + { DH_free(dh); return(NULL); } + dh->length = 160; + return(dh); + } +#endif + +#ifndef OPENSSL_NO_PSK +/* convert the PSK key (psk_key) in ascii to binary (psk) */ +static int psk_key2bn(const char *pskkey, unsigned char *psk, + unsigned int max_psk_len) + { + int ret; + BIGNUM *bn = NULL; + + ret = BN_hex2bn(&bn, pskkey); + if (!ret) + { + BIO_printf(bio_err,"Could not convert PSK key '%s' to BIGNUM\n", pskkey); + if (bn) + BN_free(bn); + return 0; + } + if (BN_num_bytes(bn) > (int)max_psk_len) + { + BIO_printf(bio_err,"psk buffer of callback is too small (%d) for key (%d)\n", + max_psk_len, BN_num_bytes(bn)); + BN_free(bn); + return 0; + } + ret = BN_bn2bin(bn, psk); + BN_free(bn); + return ret; + } + +static unsigned int psk_client_callback(SSL *ssl, const char *hint, char *identity, + unsigned int max_identity_len, unsigned char *psk, + unsigned int max_psk_len) + { + int ret; + unsigned int psk_len = 0; + + ret = BIO_snprintf(identity, max_identity_len, "Client_identity"); + if (ret < 0) + goto out_err; + if (debug) + fprintf(stderr, "client: created identity '%s' len=%d\n", identity, ret); + ret = psk_key2bn(psk_key, psk, max_psk_len); + if (ret < 0) + goto out_err; + psk_len = ret; +out_err: + return psk_len; + } + +static unsigned int psk_server_callback(SSL *ssl, const char *identity, + unsigned char *psk, unsigned int max_psk_len) + { + unsigned int psk_len=0; + + if (strcmp(identity, "Client_identity") != 0) + { + BIO_printf(bio_err, "server: PSK error: client identity not found\n"); + return 0; + } + psk_len=psk_key2bn(psk_key, psk, max_psk_len); + return psk_len; + } +#endif + +static int do_test_cipherlist(void) + { + int i = 0; + const SSL_METHOD *meth; + const SSL_CIPHER *ci, *tci = NULL; + +#ifndef OPENSSL_NO_SSL2 + fprintf(stderr, "testing SSLv2 cipher list order: "); + meth = SSLv2_method(); + while ((ci = meth->get_cipher(i++)) != NULL) + { + if (tci != NULL) + if (ci->id >= tci->id) + { + fprintf(stderr, "failed %lx vs. %lx\n", ci->id, tci->id); + return 0; + } + tci = ci; + } + fprintf(stderr, "ok\n"); +#endif +#ifndef OPENSSL_NO_SSL3 + fprintf(stderr, "testing SSLv3 cipher list order: "); + meth = SSLv3_method(); + tci = NULL; + while ((ci = meth->get_cipher(i++)) != NULL) + { + if (tci != NULL) + if (ci->id >= tci->id) + { + fprintf(stderr, "failed %lx vs. %lx\n", ci->id, tci->id); + return 0; + } + tci = ci; + } + fprintf(stderr, "ok\n"); +#endif +#ifndef OPENSSL_NO_TLS1 + fprintf(stderr, "testing TLSv1 cipher list order: "); + meth = TLSv1_method(); + tci = NULL; + while ((ci = meth->get_cipher(i++)) != NULL) + { + if (tci != NULL) + if (ci->id >= tci->id) + { + fprintf(stderr, "failed %lx vs. %lx\n", ci->id, tci->id); + return 0; + } + tci = ci; + } + fprintf(stderr, "ok\n"); +#endif + + return 1; + } diff --git a/node-v0.8.14/deps/openssl/openssl/ssl/t1_clnt.c b/node-v0.8.14/deps/openssl/openssl/ssl/t1_clnt.c new file mode 100644 index 0000000..c87af17 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/ssl/t1_clnt.c @@ -0,0 +1,79 @@ +/* ssl/t1_clnt.c */ +/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com) + * All rights reserved. + * + * This package is an SSL implementation written + * by Eric Young (eay@cryptsoft.com). + * The implementation was written so as to conform with Netscapes SSL. + * + * This library is free for commercial and non-commercial use as long as + * the following conditions are aheared to. The following conditions + * apply to all code found in this distribution, be it the RC4, RSA, + * lhash, DES, etc., code; not just the SSL code. The SSL documentation + * included with this distribution is covered by the same copyright terms + * except that the holder is Tim Hudson (tjh@cryptsoft.com). + * + * Copyright remains Eric Young's, and as such any Copyright notices in + * the code are not to be removed. + * If this package is used in a product, Eric Young should be given attribution + * as the author of the parts of the library used. + * This can be in the form of a textual message at program startup or + * in documentation (online or textual) provided with the package. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * "This product includes cryptographic software written by + * Eric Young (eay@cryptsoft.com)" + * The word 'cryptographic' can be left out if the rouines from the library + * being used are not cryptographic related :-). + * 4. If you include any Windows specific code (or a derivative thereof) from + * the apps directory (application code) you must include an acknowledgement: + * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)" + * + * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * + * The licence and distribution terms for any publically available version or + * derivative of this code cannot be changed. i.e. this code cannot simply be + * copied and put under another distribution licence + * [including the GNU Public Licence.] + */ + +#include +#include "ssl_locl.h" +#include +#include +#include +#include + +static const SSL_METHOD *tls1_get_client_method(int ver); +static const SSL_METHOD *tls1_get_client_method(int ver) + { + if (ver == TLS1_VERSION) + return(TLSv1_client_method()); + else + return(NULL); + } + +IMPLEMENT_tls1_meth_func(TLSv1_client_method, + ssl_undefined_function, + ssl3_connect, + tls1_get_client_method) + diff --git a/node-v0.8.14/deps/openssl/openssl/ssl/t1_enc.c b/node-v0.8.14/deps/openssl/openssl/ssl/t1_enc.c new file mode 100644 index 0000000..b1d5b28 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/ssl/t1_enc.c @@ -0,0 +1,1134 @@ +/* ssl/t1_enc.c */ +/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com) + * All rights reserved. + * + * This package is an SSL implementation written + * by Eric Young (eay@cryptsoft.com). + * The implementation was written so as to conform with Netscapes SSL. + * + * This library is free for commercial and non-commercial use as long as + * the following conditions are aheared to. The following conditions + * apply to all code found in this distribution, be it the RC4, RSA, + * lhash, DES, etc., code; not just the SSL code. The SSL documentation + * included with this distribution is covered by the same copyright terms + * except that the holder is Tim Hudson (tjh@cryptsoft.com). + * + * Copyright remains Eric Young's, and as such any Copyright notices in + * the code are not to be removed. + * If this package is used in a product, Eric Young should be given attribution + * as the author of the parts of the library used. + * This can be in the form of a textual message at program startup or + * in documentation (online or textual) provided with the package. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * "This product includes cryptographic software written by + * Eric Young (eay@cryptsoft.com)" + * The word 'cryptographic' can be left out if the rouines from the library + * being used are not cryptographic related :-). + * 4. If you include any Windows specific code (or a derivative thereof) from + * the apps directory (application code) you must include an acknowledgement: + * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)" + * + * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * + * The licence and distribution terms for any publically available version or + * derivative of this code cannot be changed. i.e. this code cannot simply be + * copied and put under another distribution licence + * [including the GNU Public Licence.] + */ +/* ==================================================================== + * Copyright (c) 1998-2007 The OpenSSL Project. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. All advertising materials mentioning features or use of this + * software must display the following acknowledgment: + * "This product includes software developed by the OpenSSL Project + * for use in the OpenSSL Toolkit. (http://www.openssl.org/)" + * + * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to + * endorse or promote products derived from this software without + * prior written permission. For written permission, please contact + * openssl-core@openssl.org. + * + * 5. Products derived from this software may not be called "OpenSSL" + * nor may "OpenSSL" appear in their names without prior written + * permission of the OpenSSL Project. + * + * 6. Redistributions of any form whatsoever must retain the following + * acknowledgment: + * "This product includes software developed by the OpenSSL Project + * for use in the OpenSSL Toolkit (http://www.openssl.org/)" + * + * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY + * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR + * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, + * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * ==================================================================== + * + * This product includes cryptographic software written by Eric Young + * (eay@cryptsoft.com). This product includes software written by Tim + * Hudson (tjh@cryptsoft.com). + * + */ +/* ==================================================================== + * Copyright 2005 Nokia. All rights reserved. + * + * The portions of the attached software ("Contribution") is developed by + * Nokia Corporation and is licensed pursuant to the OpenSSL open source + * license. + * + * The Contribution, originally written by Mika Kousa and Pasi Eronen of + * Nokia Corporation, consists of the "PSK" (Pre-Shared Key) ciphersuites + * support (see RFC 4279) to OpenSSL. + * + * No patent licenses or other rights except those expressly stated in + * the OpenSSL open source license shall be deemed granted or received + * expressly, by implication, estoppel, or otherwise. + * + * No assurances are provided by Nokia that the Contribution does not + * infringe the patent or other intellectual property rights of any third + * party or that the license provides you with all the necessary rights + * to make use of the Contribution. + * + * THE SOFTWARE IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND. IN + * ADDITION TO THE DISCLAIMERS INCLUDED IN THE LICENSE, NOKIA + * SPECIFICALLY DISCLAIMS ANY LIABILITY FOR CLAIMS BROUGHT BY YOU OR ANY + * OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL PROPERTY RIGHTS OR + * OTHERWISE. + */ + +#include +#include "ssl_locl.h" +#ifndef OPENSSL_NO_COMP +#include +#endif +#include +#include +#include +#ifdef KSSL_DEBUG +#include +#endif + +/* seed1 through seed5 are virtually concatenated */ +static int tls1_P_hash(const EVP_MD *md, const unsigned char *sec, + int sec_len, + const void *seed1, int seed1_len, + const void *seed2, int seed2_len, + const void *seed3, int seed3_len, + const void *seed4, int seed4_len, + const void *seed5, int seed5_len, + unsigned char *out, int olen) + { + int chunk; + unsigned int j; + HMAC_CTX ctx; + HMAC_CTX ctx_tmp; + unsigned char A1[EVP_MAX_MD_SIZE]; + unsigned int A1_len; + int ret = 0; + + chunk=EVP_MD_size(md); + OPENSSL_assert(chunk >= 0); + + HMAC_CTX_init(&ctx); + HMAC_CTX_init(&ctx_tmp); + if (!HMAC_Init_ex(&ctx,sec,sec_len,md, NULL)) + goto err; + if (!HMAC_Init_ex(&ctx_tmp,sec,sec_len,md, NULL)) + goto err; + if (seed1 != NULL && !HMAC_Update(&ctx,seed1,seed1_len)) + goto err; + if (seed2 != NULL && !HMAC_Update(&ctx,seed2,seed2_len)) + goto err; + if (seed3 != NULL && !HMAC_Update(&ctx,seed3,seed3_len)) + goto err; + if (seed4 != NULL && !HMAC_Update(&ctx,seed4,seed4_len)) + goto err; + if (seed5 != NULL && !HMAC_Update(&ctx,seed5,seed5_len)) + goto err; + if (!HMAC_Final(&ctx,A1,&A1_len)) + goto err; + + for (;;) + { + if (!HMAC_Init_ex(&ctx,NULL,0,NULL,NULL)) /* re-init */ + goto err; + if (!HMAC_Init_ex(&ctx_tmp,NULL,0,NULL,NULL)) /* re-init */ + goto err; + if (!HMAC_Update(&ctx,A1,A1_len)) + goto err; + if (!HMAC_Update(&ctx_tmp,A1,A1_len)) + goto err; + if (seed1 != NULL && !HMAC_Update(&ctx,seed1,seed1_len)) + goto err; + if (seed2 != NULL && !HMAC_Update(&ctx,seed2,seed2_len)) + goto err; + if (seed3 != NULL && !HMAC_Update(&ctx,seed3,seed3_len)) + goto err; + if (seed4 != NULL && !HMAC_Update(&ctx,seed4,seed4_len)) + goto err; + if (seed5 != NULL && !HMAC_Update(&ctx,seed5,seed5_len)) + goto err; + + if (olen > chunk) + { + if (!HMAC_Final(&ctx,out,&j)) + goto err; + out+=j; + olen-=j; + if (!HMAC_Final(&ctx_tmp,A1,&A1_len)) /* calc the next A1 value */ + goto err; + } + else /* last one */ + { + if (!HMAC_Final(&ctx,A1,&A1_len)) + goto err; + memcpy(out,A1,olen); + break; + } + } + ret = 1; +err: + HMAC_CTX_cleanup(&ctx); + HMAC_CTX_cleanup(&ctx_tmp); + OPENSSL_cleanse(A1,sizeof(A1)); + return ret; + } + +/* seed1 through seed5 are virtually concatenated */ +static int tls1_PRF(long digest_mask, + const void *seed1, int seed1_len, + const void *seed2, int seed2_len, + const void *seed3, int seed3_len, + const void *seed4, int seed4_len, + const void *seed5, int seed5_len, + const unsigned char *sec, int slen, + unsigned char *out1, + unsigned char *out2, int olen) + { + int len,i,idx,count; + const unsigned char *S1; + long m; + const EVP_MD *md; + int ret = 0; + + /* Count number of digests and partition sec evenly */ + count=0; + for (idx=0;ssl_get_handshake_digest(idx,&m,&md);idx++) { + if ((m<s3->tmp.new_cipher->algorithm2, + TLS_MD_KEY_EXPANSION_CONST,TLS_MD_KEY_EXPANSION_CONST_SIZE, + s->s3->server_random,SSL3_RANDOM_SIZE, + s->s3->client_random,SSL3_RANDOM_SIZE, + NULL,0,NULL,0, + s->session->master_key,s->session->master_key_length, + km,tmp,num); +#ifdef KSSL_DEBUG + printf("tls1_generate_key_block() ==> %d byte master_key =\n\t", + s->session->master_key_length); + { + int i; + for (i=0; i < s->session->master_key_length; i++) + { + printf("%02X", s->session->master_key[i]); + } + printf("\n"); } +#endif /* KSSL_DEBUG */ + return ret; + } + +int tls1_change_cipher_state(SSL *s, int which) + { + static const unsigned char empty[]=""; + unsigned char *p,*mac_secret; + unsigned char *exp_label; + unsigned char tmp1[EVP_MAX_KEY_LENGTH]; + unsigned char tmp2[EVP_MAX_KEY_LENGTH]; + unsigned char iv1[EVP_MAX_IV_LENGTH*2]; + unsigned char iv2[EVP_MAX_IV_LENGTH*2]; + unsigned char *ms,*key,*iv; + int client_write; + EVP_CIPHER_CTX *dd; + const EVP_CIPHER *c; +#ifndef OPENSSL_NO_COMP + const SSL_COMP *comp; +#endif + const EVP_MD *m; + int mac_type; + int *mac_secret_size; + EVP_MD_CTX *mac_ctx; + EVP_PKEY *mac_key; + int is_export,n,i,j,k,exp_label_len,cl; + int reuse_dd = 0; + + is_export=SSL_C_IS_EXPORT(s->s3->tmp.new_cipher); + c=s->s3->tmp.new_sym_enc; + m=s->s3->tmp.new_hash; + mac_type = s->s3->tmp.new_mac_pkey_type; +#ifndef OPENSSL_NO_COMP + comp=s->s3->tmp.new_compression; +#endif + +#ifdef KSSL_DEBUG + printf("tls1_change_cipher_state(which= %d) w/\n", which); + printf("\talg= %ld/%ld, comp= %p\n", + s->s3->tmp.new_cipher->algorithm_mkey, + s->s3->tmp.new_cipher->algorithm_auth, + comp); + printf("\tevp_cipher == %p ==? &d_cbc_ede_cipher3\n", c); + printf("\tevp_cipher: nid, blksz= %d, %d, keylen=%d, ivlen=%d\n", + c->nid,c->block_size,c->key_len,c->iv_len); + printf("\tkey_block: len= %d, data= ", s->s3->tmp.key_block_length); + { + int i; + for (i=0; is3->tmp.key_block_length; i++) + printf("%02x", key_block[i]); printf("\n"); + } +#endif /* KSSL_DEBUG */ + + if (which & SSL3_CC_READ) + { + if (s->s3->tmp.new_cipher->algorithm2 & TLS1_STREAM_MAC) + s->mac_flags |= SSL_MAC_FLAG_READ_MAC_STREAM; + else + s->mac_flags &= ~SSL_MAC_FLAG_READ_MAC_STREAM; + + if (s->enc_read_ctx != NULL) + reuse_dd = 1; + else if ((s->enc_read_ctx=OPENSSL_malloc(sizeof(EVP_CIPHER_CTX))) == NULL) + goto err; + else + /* make sure it's intialized in case we exit later with an error */ + EVP_CIPHER_CTX_init(s->enc_read_ctx); + dd= s->enc_read_ctx; + mac_ctx=ssl_replace_hash(&s->read_hash,NULL); +#ifndef OPENSSL_NO_COMP + if (s->expand != NULL) + { + COMP_CTX_free(s->expand); + s->expand=NULL; + } + if (comp != NULL) + { + s->expand=COMP_CTX_new(comp->method); + if (s->expand == NULL) + { + SSLerr(SSL_F_TLS1_CHANGE_CIPHER_STATE,SSL_R_COMPRESSION_LIBRARY_ERROR); + goto err2; + } + if (s->s3->rrec.comp == NULL) + s->s3->rrec.comp=(unsigned char *) + OPENSSL_malloc(SSL3_RT_MAX_ENCRYPTED_LENGTH); + if (s->s3->rrec.comp == NULL) + goto err; + } +#endif + /* this is done by dtls1_reset_seq_numbers for DTLS1_VERSION */ + if (s->version != DTLS1_VERSION) + memset(&(s->s3->read_sequence[0]),0,8); + mac_secret= &(s->s3->read_mac_secret[0]); + mac_secret_size=&(s->s3->read_mac_secret_size); + } + else + { + if (s->s3->tmp.new_cipher->algorithm2 & TLS1_STREAM_MAC) + s->mac_flags |= SSL_MAC_FLAG_WRITE_MAC_STREAM; + else + s->mac_flags &= ~SSL_MAC_FLAG_WRITE_MAC_STREAM; + if (s->enc_write_ctx != NULL) + reuse_dd = 1; + else if ((s->enc_write_ctx=OPENSSL_malloc(sizeof(EVP_CIPHER_CTX))) == NULL) + goto err; + else + /* make sure it's intialized in case we exit later with an error */ + EVP_CIPHER_CTX_init(s->enc_write_ctx); + dd= s->enc_write_ctx; + mac_ctx = ssl_replace_hash(&s->write_hash,NULL); +#ifndef OPENSSL_NO_COMP + if (s->compress != NULL) + { + COMP_CTX_free(s->compress); + s->compress=NULL; + } + if (comp != NULL) + { + s->compress=COMP_CTX_new(comp->method); + if (s->compress == NULL) + { + SSLerr(SSL_F_TLS1_CHANGE_CIPHER_STATE,SSL_R_COMPRESSION_LIBRARY_ERROR); + goto err2; + } + } +#endif + /* this is done by dtls1_reset_seq_numbers for DTLS1_VERSION */ + if (s->version != DTLS1_VERSION) + memset(&(s->s3->write_sequence[0]),0,8); + mac_secret= &(s->s3->write_mac_secret[0]); + mac_secret_size = &(s->s3->write_mac_secret_size); + } + + if (reuse_dd) + EVP_CIPHER_CTX_cleanup(dd); + + p=s->s3->tmp.key_block; + i=*mac_secret_size=s->s3->tmp.new_mac_secret_size; + + cl=EVP_CIPHER_key_length(c); + j=is_export ? (cl < SSL_C_EXPORT_KEYLENGTH(s->s3->tmp.new_cipher) ? + cl : SSL_C_EXPORT_KEYLENGTH(s->s3->tmp.new_cipher)) : cl; + /* Was j=(exp)?5:EVP_CIPHER_key_length(c); */ + k=EVP_CIPHER_iv_length(c); + if ( (which == SSL3_CHANGE_CIPHER_CLIENT_WRITE) || + (which == SSL3_CHANGE_CIPHER_SERVER_READ)) + { + ms= &(p[ 0]); n=i+i; + key= &(p[ n]); n+=j+j; + iv= &(p[ n]); n+=k+k; + exp_label=(unsigned char *)TLS_MD_CLIENT_WRITE_KEY_CONST; + exp_label_len=TLS_MD_CLIENT_WRITE_KEY_CONST_SIZE; + client_write=1; + } + else + { + n=i; + ms= &(p[ n]); n+=i+j; + key= &(p[ n]); n+=j+k; + iv= &(p[ n]); n+=k; + exp_label=(unsigned char *)TLS_MD_SERVER_WRITE_KEY_CONST; + exp_label_len=TLS_MD_SERVER_WRITE_KEY_CONST_SIZE; + client_write=0; + } + + if (n > s->s3->tmp.key_block_length) + { + SSLerr(SSL_F_TLS1_CHANGE_CIPHER_STATE,ERR_R_INTERNAL_ERROR); + goto err2; + } + + memcpy(mac_secret,ms,i); + mac_key = EVP_PKEY_new_mac_key(mac_type, NULL, + mac_secret,*mac_secret_size); + EVP_DigestSignInit(mac_ctx,NULL,m,NULL,mac_key); + EVP_PKEY_free(mac_key); +#ifdef TLS_DEBUG +printf("which = %04X\nmac key=",which); +{ int z; for (z=0; zs3->tmp.new_cipher->algorithm2, + exp_label,exp_label_len, + s->s3->client_random,SSL3_RANDOM_SIZE, + s->s3->server_random,SSL3_RANDOM_SIZE, + NULL,0,NULL,0, + key,j,tmp1,tmp2,EVP_CIPHER_key_length(c))) + goto err2; + key=tmp1; + + if (k > 0) + { + if (!tls1_PRF(s->s3->tmp.new_cipher->algorithm2, + TLS_MD_IV_BLOCK_CONST,TLS_MD_IV_BLOCK_CONST_SIZE, + s->s3->client_random,SSL3_RANDOM_SIZE, + s->s3->server_random,SSL3_RANDOM_SIZE, + NULL,0,NULL,0, + empty,0,iv1,iv2,k*2)) + goto err2; + if (client_write) + iv=iv1; + else + iv= &(iv1[k]); + } + } + + s->session->key_arg_length=0; +#ifdef KSSL_DEBUG + { + int i; + printf("EVP_CipherInit_ex(dd,c,key=,iv=,which)\n"); + printf("\tkey= "); for (i=0; ikey_len; i++) printf("%02x", key[i]); + printf("\n"); + printf("\t iv= "); for (i=0; iiv_len; i++) printf("%02x", iv[i]); + printf("\n"); + } +#endif /* KSSL_DEBUG */ + + EVP_CipherInit_ex(dd,c,NULL,key,iv,(which & SSL3_CC_WRITE)); +#ifdef TLS_DEBUG +printf("which = %04X\nkey=",which); +{ int z; for (z=0; zs3->tmp.key_block_length != 0) + return(1); + + if (!ssl_cipher_get_evp(s->session,&c,&hash,&mac_type,&mac_secret_size,&comp)) + { + SSLerr(SSL_F_TLS1_SETUP_KEY_BLOCK,SSL_R_CIPHER_OR_HASH_UNAVAILABLE); + return(0); + } + + s->s3->tmp.new_sym_enc=c; + s->s3->tmp.new_hash=hash; + s->s3->tmp.new_mac_pkey_type = mac_type; + s->s3->tmp.new_mac_secret_size = mac_secret_size; + num=EVP_CIPHER_key_length(c)+mac_secret_size+EVP_CIPHER_iv_length(c); + num*=2; + + ssl3_cleanup_key_block(s); + + if ((p1=(unsigned char *)OPENSSL_malloc(num)) == NULL) + { + SSLerr(SSL_F_TLS1_SETUP_KEY_BLOCK,ERR_R_MALLOC_FAILURE); + goto err; + } + + s->s3->tmp.key_block_length=num; + s->s3->tmp.key_block=p1; + + if ((p2=(unsigned char *)OPENSSL_malloc(num)) == NULL) + { + SSLerr(SSL_F_TLS1_SETUP_KEY_BLOCK,ERR_R_MALLOC_FAILURE); + goto err; + } + +#ifdef TLS_DEBUG +printf("client random\n"); +{ int z; for (z=0; zs3->client_random[z],((z+1)%16)?' ':'\n'); } +printf("server random\n"); +{ int z; for (z=0; zs3->server_random[z],((z+1)%16)?' ':'\n'); } +printf("pre-master\n"); +{ int z; for (z=0; zsession->master_key_length; z++) printf("%02X%c",s->session->master_key[z],((z+1)%16)?' ':'\n'); } +#endif + if (!tls1_generate_key_block(s,p1,p2,num)) + goto err; +#ifdef TLS_DEBUG +printf("\nkey block\n"); +{ int z; for (z=0; zoptions & SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS)) + { + /* enable vulnerability countermeasure for CBC ciphers with + * known-IV problem (http://www.openssl.org/~bodo/tls-cbc.txt) + */ + s->s3->need_empty_fragments = 1; + + if (s->session->cipher != NULL) + { + if (s->session->cipher->algorithm_enc == SSL_eNULL) + s->s3->need_empty_fragments = 0; + +#ifndef OPENSSL_NO_RC4 + if (s->session->cipher->algorithm_enc == SSL_RC4) + s->s3->need_empty_fragments = 0; +#endif + } + } + + ret = 1; +err: + if (p2) + { + OPENSSL_cleanse(p2,num); + OPENSSL_free(p2); + } + return(ret); + } + +int tls1_enc(SSL *s, int send) + { + SSL3_RECORD *rec; + EVP_CIPHER_CTX *ds; + unsigned long l; + int bs,i,ii,j,k,n=0; + const EVP_CIPHER *enc; + + if (send) + { + if (EVP_MD_CTX_md(s->write_hash)) + { + n=EVP_MD_CTX_size(s->write_hash); + OPENSSL_assert(n >= 0); + } + ds=s->enc_write_ctx; + rec= &(s->s3->wrec); + if (s->enc_write_ctx == NULL) + enc=NULL; + else + enc=EVP_CIPHER_CTX_cipher(s->enc_write_ctx); + } + else + { + if (EVP_MD_CTX_md(s->read_hash)) + { + n=EVP_MD_CTX_size(s->read_hash); + OPENSSL_assert(n >= 0); + } + ds=s->enc_read_ctx; + rec= &(s->s3->rrec); + if (s->enc_read_ctx == NULL) + enc=NULL; + else + enc=EVP_CIPHER_CTX_cipher(s->enc_read_ctx); + } + +#ifdef KSSL_DEBUG + printf("tls1_enc(%d)\n", send); +#endif /* KSSL_DEBUG */ + + if ((s->session == NULL) || (ds == NULL) || + (enc == NULL)) + { + memmove(rec->data,rec->input,rec->length); + rec->input=rec->data; + } + else + { + l=rec->length; + bs=EVP_CIPHER_block_size(ds->cipher); + + if ((bs != 1) && send) + { + i=bs-((int)l%bs); + + /* Add weird padding of upto 256 bytes */ + + /* we need to add 'i' padding bytes of value j */ + j=i-1; + if (s->options & SSL_OP_TLS_BLOCK_PADDING_BUG) + { + if (s->s3->flags & TLS1_FLAGS_TLS_PADDING_BUG) + j++; + } + for (k=(int)l; k<(int)(l+i); k++) + rec->input[k]=j; + l+=i; + rec->length+=i; + } + +#ifdef KSSL_DEBUG + { + unsigned long ui; + printf("EVP_Cipher(ds=%p,rec->data=%p,rec->input=%p,l=%ld) ==>\n", + ds,rec->data,rec->input,l); + printf("\tEVP_CIPHER_CTX: %d buf_len, %d key_len [%d %d], %d iv_len\n", + ds->buf_len, ds->cipher->key_len, + DES_KEY_SZ, DES_SCHEDULE_SZ, + ds->cipher->iv_len); + printf("\t\tIV: "); + for (i=0; icipher->iv_len; i++) printf("%02X", ds->iv[i]); + printf("\n"); + printf("\trec->input="); + for (ui=0; uiinput[ui]); + printf("\n"); + } +#endif /* KSSL_DEBUG */ + + if (!send) + { + if (l == 0 || l%bs != 0) + { + SSLerr(SSL_F_TLS1_ENC,SSL_R_BLOCK_CIPHER_PAD_IS_WRONG); + ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_DECRYPTION_FAILED); + return 0; + } + } + + EVP_Cipher(ds,rec->data,rec->input,l); + +#ifdef KSSL_DEBUG + { + unsigned long i; + printf("\trec->data="); + for (i=0; idata[i]); printf("\n"); + } +#endif /* KSSL_DEBUG */ + + if ((bs != 1) && !send) + { + ii=i=rec->data[l-1]; /* padding_length */ + i++; + /* NB: if compression is in operation the first packet + * may not be of even length so the padding bug check + * cannot be performed. This bug workaround has been + * around since SSLeay so hopefully it is either fixed + * now or no buggy implementation supports compression + * [steve] + */ + if ( (s->options&SSL_OP_TLS_BLOCK_PADDING_BUG) + && !s->expand) + { + /* First packet is even in size, so check */ + if ((memcmp(s->s3->read_sequence, + "\0\0\0\0\0\0\0\0",8) == 0) && !(ii & 1)) + s->s3->flags|=TLS1_FLAGS_TLS_PADDING_BUG; + if (s->s3->flags & TLS1_FLAGS_TLS_PADDING_BUG) + i--; + } + /* TLS 1.0 does not bound the number of padding bytes by the block size. + * All of them must have value 'padding_length'. */ + if (i > (int)rec->length) + { + /* Incorrect padding. SSLerr() and ssl3_alert are done + * by caller: we don't want to reveal whether this is + * a decryption error or a MAC verification failure + * (see http://www.openssl.org/~bodo/tls-cbc.txt) */ + return -1; + } + for (j=(int)(l-i); j<(int)l; j++) + { + if (rec->data[j] != ii) + { + /* Incorrect padding */ + return -1; + } + } + rec->length-=i; + } + } + return(1); + } +int tls1_cert_verify_mac(SSL *s, int md_nid, unsigned char *out) + { + unsigned int ret; + EVP_MD_CTX ctx, *d=NULL; + int i; + + if (s->s3->handshake_buffer) + if (!ssl3_digest_cached_records(s)) + return 0; + + for (i=0;is3->handshake_dgst[i]&&EVP_MD_CTX_type(s->s3->handshake_dgst[i])==md_nid) + { + d=s->s3->handshake_dgst[i]; + break; + } + } + if (!d) { + SSLerr(SSL_F_TLS1_CERT_VERIFY_MAC,SSL_R_NO_REQUIRED_DIGEST); + return 0; + } + + EVP_MD_CTX_init(&ctx); + EVP_MD_CTX_copy_ex(&ctx,d); + EVP_DigestFinal_ex(&ctx,out,&ret); + EVP_MD_CTX_cleanup(&ctx); + return((int)ret); + } + +int tls1_final_finish_mac(SSL *s, + const char *str, int slen, unsigned char *out) + { + unsigned int i; + EVP_MD_CTX ctx; + unsigned char buf[2*EVP_MAX_MD_SIZE]; + unsigned char *q,buf2[12]; + int idx; + long mask; + int err=0; + const EVP_MD *md; + + q=buf; + + if (s->s3->handshake_buffer) + if (!ssl3_digest_cached_records(s)) + return 0; + + EVP_MD_CTX_init(&ctx); + + for (idx=0;ssl_get_handshake_digest(idx,&mask,&md);idx++) + { + if (mask & s->s3->tmp.new_cipher->algorithm2) + { + int hashsize = EVP_MD_size(md); + if (hashsize < 0 || hashsize > (int)(sizeof buf - (size_t)(q-buf))) + { + /* internal error: 'buf' is too small for this cipersuite! */ + err = 1; + } + else + { + EVP_MD_CTX_copy_ex(&ctx,s->s3->handshake_dgst[idx]); + EVP_DigestFinal_ex(&ctx,q,&i); + if (i != (unsigned int)hashsize) /* can't really happen */ + err = 1; + q+=i; + } + } + } + + if (!tls1_PRF(s->s3->tmp.new_cipher->algorithm2, + str,slen, buf,(int)(q-buf), NULL,0, NULL,0, NULL,0, + s->session->master_key,s->session->master_key_length, + out,buf2,sizeof buf2)) + err = 1; + EVP_MD_CTX_cleanup(&ctx); + + if (err) + return 0; + else + return sizeof buf2; + } + +int tls1_mac(SSL *ssl, unsigned char *md, int send) + { + SSL3_RECORD *rec; + unsigned char *seq; + EVP_MD_CTX *hash; + size_t md_size; + int i; + EVP_MD_CTX hmac, *mac_ctx; + unsigned char buf[5]; + int stream_mac = (send?(ssl->mac_flags & SSL_MAC_FLAG_WRITE_MAC_STREAM):(ssl->mac_flags&SSL_MAC_FLAG_READ_MAC_STREAM)); + int t; + + if (send) + { + rec= &(ssl->s3->wrec); + seq= &(ssl->s3->write_sequence[0]); + hash=ssl->write_hash; + } + else + { + rec= &(ssl->s3->rrec); + seq= &(ssl->s3->read_sequence[0]); + hash=ssl->read_hash; + } + + t=EVP_MD_CTX_size(hash); + OPENSSL_assert(t >= 0); + md_size=t; + + buf[0]=rec->type; + buf[1]=(unsigned char)(ssl->version>>8); + buf[2]=(unsigned char)(ssl->version); + buf[3]=rec->length>>8; + buf[4]=rec->length&0xff; + + /* I should fix this up TLS TLS TLS TLS TLS XXXXXXXX */ + if (stream_mac) + { + mac_ctx = hash; + } + else + { + EVP_MD_CTX_copy(&hmac,hash); + mac_ctx = &hmac; + } + + if (ssl->version == DTLS1_VERSION || ssl->version == DTLS1_BAD_VER) + { + unsigned char dtlsseq[8],*p=dtlsseq; + + s2n(send?ssl->d1->w_epoch:ssl->d1->r_epoch, p); + memcpy (p,&seq[2],6); + + EVP_DigestSignUpdate(mac_ctx,dtlsseq,8); + } + else + EVP_DigestSignUpdate(mac_ctx,seq,8); + + EVP_DigestSignUpdate(mac_ctx,buf,5); + EVP_DigestSignUpdate(mac_ctx,rec->input,rec->length); + t=EVP_DigestSignFinal(mac_ctx,md,&md_size); + OPENSSL_assert(t > 0); + + if (!stream_mac) EVP_MD_CTX_cleanup(&hmac); +#ifdef TLS_DEBUG +printf("sec="); +{unsigned int z; for (z=0; zversion != DTLS1_VERSION && ssl->version != DTLS1_BAD_VER) + { + for (i=7; i>=0; i--) + { + ++seq[i]; + if (seq[i] != 0) break; + } + } + +#ifdef TLS_DEBUG +{unsigned int z; for (z=0; zs3->client_opaque_prf_input != NULL && s->s3->server_opaque_prf_input != NULL && + s->s3->client_opaque_prf_input_len > 0 && + s->s3->client_opaque_prf_input_len == s->s3->server_opaque_prf_input_len) + { + co = s->s3->client_opaque_prf_input; + col = s->s3->server_opaque_prf_input_len; + so = s->s3->server_opaque_prf_input; + sol = s->s3->client_opaque_prf_input_len; /* must be same as col (see draft-rescorla-tls-opaque-prf-input-00.txt, section 3.1) */ + } +#endif + + tls1_PRF(s->s3->tmp.new_cipher->algorithm2, + TLS_MD_MASTER_SECRET_CONST,TLS_MD_MASTER_SECRET_CONST_SIZE, + s->s3->client_random,SSL3_RANDOM_SIZE, + co, col, + s->s3->server_random,SSL3_RANDOM_SIZE, + so, sol, + p,len, + s->session->master_key,buff,sizeof buff); + +#ifdef KSSL_DEBUG + printf ("tls1_generate_master_secret() complete\n"); +#endif /* KSSL_DEBUG */ + return(SSL3_MASTER_SECRET_SIZE); + } + +int tls1_export_keying_material(SSL *s, unsigned char *out, size_t olen, + const char *label, size_t llen, const unsigned char *context, + size_t contextlen, int use_context) + { + unsigned char *buff; + unsigned char *val = NULL; + size_t vallen, currentvalpos; + int rv; + +#ifdef KSSL_DEBUG + printf ("tls1_export_keying_material(%p,%p,%d,%s,%d,%p,%d)\n", s, out, olen, label, llen, p, plen); +#endif /* KSSL_DEBUG */ + + buff = OPENSSL_malloc(olen); + if (buff == NULL) goto err2; + + /* construct PRF arguments + * we construct the PRF argument ourself rather than passing separate + * values into the TLS PRF to ensure that the concatenation of values + * does not create a prohibited label. + */ + vallen = llen + SSL3_RANDOM_SIZE * 2; + if (use_context) + { + vallen += 2 + contextlen; + } + + val = OPENSSL_malloc(vallen); + if (val == NULL) goto err2; + currentvalpos = 0; + memcpy(val + currentvalpos, (unsigned char *) label, llen); + currentvalpos += llen; + memcpy(val + currentvalpos, s->s3->client_random, SSL3_RANDOM_SIZE); + currentvalpos += SSL3_RANDOM_SIZE; + memcpy(val + currentvalpos, s->s3->server_random, SSL3_RANDOM_SIZE); + currentvalpos += SSL3_RANDOM_SIZE; + + if (use_context) + { + val[currentvalpos] = (contextlen >> 8) & 0xff; + currentvalpos++; + val[currentvalpos] = contextlen & 0xff; + currentvalpos++; + if ((contextlen > 0) || (context != NULL)) + { + memcpy(val + currentvalpos, context, contextlen); + } + } + + /* disallow prohibited labels + * note that SSL3_RANDOM_SIZE > max(prohibited label len) = + * 15, so size of val > max(prohibited label len) = 15 and the + * comparisons won't have buffer overflow + */ + if (memcmp(val, TLS_MD_CLIENT_FINISH_CONST, + TLS_MD_CLIENT_FINISH_CONST_SIZE) == 0) goto err1; + if (memcmp(val, TLS_MD_SERVER_FINISH_CONST, + TLS_MD_SERVER_FINISH_CONST_SIZE) == 0) goto err1; + if (memcmp(val, TLS_MD_MASTER_SECRET_CONST, + TLS_MD_MASTER_SECRET_CONST_SIZE) == 0) goto err1; + if (memcmp(val, TLS_MD_KEY_EXPANSION_CONST, + TLS_MD_KEY_EXPANSION_CONST_SIZE) == 0) goto err1; + + rv = tls1_PRF(s->s3->tmp.new_cipher->algorithm2, + val, vallen, + NULL, 0, + NULL, 0, + NULL, 0, + NULL, 0, + s->session->master_key,s->session->master_key_length, + out,buff,olen); + +#ifdef KSSL_DEBUG + printf ("tls1_export_keying_material() complete\n"); +#endif /* KSSL_DEBUG */ + goto ret; +err1: + SSLerr(SSL_F_TLS1_EXPORT_KEYING_MATERIAL, SSL_R_TLS_ILLEGAL_EXPORTER_LABEL); + rv = 0; + goto ret; +err2: + SSLerr(SSL_F_TLS1_EXPORT_KEYING_MATERIAL, ERR_R_MALLOC_FAILURE); + rv = 0; +ret: + if (buff != NULL) OPENSSL_free(buff); + if (val != NULL) OPENSSL_free(val); + return(rv); + } + +int tls1_alert_code(int code) + { + switch (code) + { + case SSL_AD_CLOSE_NOTIFY: return(SSL3_AD_CLOSE_NOTIFY); + case SSL_AD_UNEXPECTED_MESSAGE: return(SSL3_AD_UNEXPECTED_MESSAGE); + case SSL_AD_BAD_RECORD_MAC: return(SSL3_AD_BAD_RECORD_MAC); + case SSL_AD_DECRYPTION_FAILED: return(TLS1_AD_DECRYPTION_FAILED); + case SSL_AD_RECORD_OVERFLOW: return(TLS1_AD_RECORD_OVERFLOW); + case SSL_AD_DECOMPRESSION_FAILURE:return(SSL3_AD_DECOMPRESSION_FAILURE); + case SSL_AD_HANDSHAKE_FAILURE: return(SSL3_AD_HANDSHAKE_FAILURE); + case SSL_AD_NO_CERTIFICATE: return(-1); + case SSL_AD_BAD_CERTIFICATE: return(SSL3_AD_BAD_CERTIFICATE); + case SSL_AD_UNSUPPORTED_CERTIFICATE:return(SSL3_AD_UNSUPPORTED_CERTIFICATE); + case SSL_AD_CERTIFICATE_REVOKED:return(SSL3_AD_CERTIFICATE_REVOKED); + case SSL_AD_CERTIFICATE_EXPIRED:return(SSL3_AD_CERTIFICATE_EXPIRED); + case SSL_AD_CERTIFICATE_UNKNOWN:return(SSL3_AD_CERTIFICATE_UNKNOWN); + case SSL_AD_ILLEGAL_PARAMETER: return(SSL3_AD_ILLEGAL_PARAMETER); + case SSL_AD_UNKNOWN_CA: return(TLS1_AD_UNKNOWN_CA); + case SSL_AD_ACCESS_DENIED: return(TLS1_AD_ACCESS_DENIED); + case SSL_AD_DECODE_ERROR: return(TLS1_AD_DECODE_ERROR); + case SSL_AD_DECRYPT_ERROR: return(TLS1_AD_DECRYPT_ERROR); + case SSL_AD_EXPORT_RESTRICTION: return(TLS1_AD_EXPORT_RESTRICTION); + case SSL_AD_PROTOCOL_VERSION: return(TLS1_AD_PROTOCOL_VERSION); + case SSL_AD_INSUFFICIENT_SECURITY:return(TLS1_AD_INSUFFICIENT_SECURITY); + case SSL_AD_INTERNAL_ERROR: return(TLS1_AD_INTERNAL_ERROR); + case SSL_AD_USER_CANCELLED: return(TLS1_AD_USER_CANCELLED); + case SSL_AD_NO_RENEGOTIATION: return(TLS1_AD_NO_RENEGOTIATION); + case SSL_AD_UNSUPPORTED_EXTENSION: return(TLS1_AD_UNSUPPORTED_EXTENSION); + case SSL_AD_CERTIFICATE_UNOBTAINABLE: return(TLS1_AD_CERTIFICATE_UNOBTAINABLE); + case SSL_AD_UNRECOGNIZED_NAME: return(TLS1_AD_UNRECOGNIZED_NAME); + case SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE: return(TLS1_AD_BAD_CERTIFICATE_STATUS_RESPONSE); + case SSL_AD_BAD_CERTIFICATE_HASH_VALUE: return(TLS1_AD_BAD_CERTIFICATE_HASH_VALUE); + case SSL_AD_UNKNOWN_PSK_IDENTITY:return(TLS1_AD_UNKNOWN_PSK_IDENTITY); +#if 0 /* not appropriate for TLS, not used for DTLS */ + case DTLS1_AD_MISSING_HANDSHAKE_MESSAGE: return + (DTLS1_AD_MISSING_HANDSHAKE_MESSAGE); +#endif + default: return(-1); + } + } + diff --git a/node-v0.8.14/deps/openssl/openssl/ssl/t1_lib.c b/node-v0.8.14/deps/openssl/openssl/ssl/t1_lib.c new file mode 100644 index 0000000..03becbc --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/ssl/t1_lib.c @@ -0,0 +1,1866 @@ +/* ssl/t1_lib.c */ +/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com) + * All rights reserved. + * + * This package is an SSL implementation written + * by Eric Young (eay@cryptsoft.com). + * The implementation was written so as to conform with Netscapes SSL. + * + * This library is free for commercial and non-commercial use as long as + * the following conditions are aheared to. The following conditions + * apply to all code found in this distribution, be it the RC4, RSA, + * lhash, DES, etc., code; not just the SSL code. The SSL documentation + * included with this distribution is covered by the same copyright terms + * except that the holder is Tim Hudson (tjh@cryptsoft.com). + * + * Copyright remains Eric Young's, and as such any Copyright notices in + * the code are not to be removed. + * If this package is used in a product, Eric Young should be given attribution + * as the author of the parts of the library used. + * This can be in the form of a textual message at program startup or + * in documentation (online or textual) provided with the package. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * "This product includes cryptographic software written by + * Eric Young (eay@cryptsoft.com)" + * The word 'cryptographic' can be left out if the rouines from the library + * being used are not cryptographic related :-). + * 4. If you include any Windows specific code (or a derivative thereof) from + * the apps directory (application code) you must include an acknowledgement: + * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)" + * + * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * + * The licence and distribution terms for any publically available version or + * derivative of this code cannot be changed. i.e. this code cannot simply be + * copied and put under another distribution licence + * [including the GNU Public Licence.] + */ +/* ==================================================================== + * Copyright (c) 1998-2007 The OpenSSL Project. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. All advertising materials mentioning features or use of this + * software must display the following acknowledgment: + * "This product includes software developed by the OpenSSL Project + * for use in the OpenSSL Toolkit. (http://www.openssl.org/)" + * + * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to + * endorse or promote products derived from this software without + * prior written permission. For written permission, please contact + * openssl-core@openssl.org. + * + * 5. Products derived from this software may not be called "OpenSSL" + * nor may "OpenSSL" appear in their names without prior written + * permission of the OpenSSL Project. + * + * 6. Redistributions of any form whatsoever must retain the following + * acknowledgment: + * "This product includes software developed by the OpenSSL Project + * for use in the OpenSSL Toolkit (http://www.openssl.org/)" + * + * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY + * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR + * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, + * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * ==================================================================== + * + * This product includes cryptographic software written by Eric Young + * (eay@cryptsoft.com). This product includes software written by Tim + * Hudson (tjh@cryptsoft.com). + * + */ + +#include +#include +#include +#include +#include +#include "ssl_locl.h" + +const char tls1_version_str[]="TLSv1" OPENSSL_VERSION_PTEXT; + +#ifndef OPENSSL_NO_TLSEXT +static int tls_decrypt_ticket(SSL *s, const unsigned char *tick, int ticklen, + const unsigned char *sess_id, int sesslen, + SSL_SESSION **psess); +#endif + +SSL3_ENC_METHOD TLSv1_enc_data={ + tls1_enc, + tls1_mac, + tls1_setup_key_block, + tls1_generate_master_secret, + tls1_change_cipher_state, + tls1_final_finish_mac, + TLS1_FINISH_MAC_LENGTH, + tls1_cert_verify_mac, + TLS_MD_CLIENT_FINISH_CONST,TLS_MD_CLIENT_FINISH_CONST_SIZE, + TLS_MD_SERVER_FINISH_CONST,TLS_MD_SERVER_FINISH_CONST_SIZE, + tls1_alert_code, + tls1_export_keying_material, + }; + +long tls1_default_timeout(void) + { + /* 2 hours, the 24 hours mentioned in the TLSv1 spec + * is way too long for http, the cache would over fill */ + return(60*60*2); + } + +int tls1_new(SSL *s) + { + if (!ssl3_new(s)) return(0); + s->method->ssl_clear(s); + return(1); + } + +void tls1_free(SSL *s) + { +#ifndef OPENSSL_NO_TLSEXT + if (s->tlsext_session_ticket) + { + OPENSSL_free(s->tlsext_session_ticket); + } +#endif /* OPENSSL_NO_TLSEXT */ + ssl3_free(s); + } + +void tls1_clear(SSL *s) + { + ssl3_clear(s); + s->version=TLS1_VERSION; + } + +#ifndef OPENSSL_NO_EC +static int nid_list[] = + { + NID_sect163k1, /* sect163k1 (1) */ + NID_sect163r1, /* sect163r1 (2) */ + NID_sect163r2, /* sect163r2 (3) */ + NID_sect193r1, /* sect193r1 (4) */ + NID_sect193r2, /* sect193r2 (5) */ + NID_sect233k1, /* sect233k1 (6) */ + NID_sect233r1, /* sect233r1 (7) */ + NID_sect239k1, /* sect239k1 (8) */ + NID_sect283k1, /* sect283k1 (9) */ + NID_sect283r1, /* sect283r1 (10) */ + NID_sect409k1, /* sect409k1 (11) */ + NID_sect409r1, /* sect409r1 (12) */ + NID_sect571k1, /* sect571k1 (13) */ + NID_sect571r1, /* sect571r1 (14) */ + NID_secp160k1, /* secp160k1 (15) */ + NID_secp160r1, /* secp160r1 (16) */ + NID_secp160r2, /* secp160r2 (17) */ + NID_secp192k1, /* secp192k1 (18) */ + NID_X9_62_prime192v1, /* secp192r1 (19) */ + NID_secp224k1, /* secp224k1 (20) */ + NID_secp224r1, /* secp224r1 (21) */ + NID_secp256k1, /* secp256k1 (22) */ + NID_X9_62_prime256v1, /* secp256r1 (23) */ + NID_secp384r1, /* secp384r1 (24) */ + NID_secp521r1 /* secp521r1 (25) */ + }; + +int tls1_ec_curve_id2nid(int curve_id) + { + /* ECC curves from draft-ietf-tls-ecc-12.txt (Oct. 17, 2005) */ + if ((curve_id < 1) || ((unsigned int)curve_id > + sizeof(nid_list)/sizeof(nid_list[0]))) + return 0; + return nid_list[curve_id-1]; + } + +int tls1_ec_nid2curve_id(int nid) + { + /* ECC curves from draft-ietf-tls-ecc-12.txt (Oct. 17, 2005) */ + switch (nid) + { + case NID_sect163k1: /* sect163k1 (1) */ + return 1; + case NID_sect163r1: /* sect163r1 (2) */ + return 2; + case NID_sect163r2: /* sect163r2 (3) */ + return 3; + case NID_sect193r1: /* sect193r1 (4) */ + return 4; + case NID_sect193r2: /* sect193r2 (5) */ + return 5; + case NID_sect233k1: /* sect233k1 (6) */ + return 6; + case NID_sect233r1: /* sect233r1 (7) */ + return 7; + case NID_sect239k1: /* sect239k1 (8) */ + return 8; + case NID_sect283k1: /* sect283k1 (9) */ + return 9; + case NID_sect283r1: /* sect283r1 (10) */ + return 10; + case NID_sect409k1: /* sect409k1 (11) */ + return 11; + case NID_sect409r1: /* sect409r1 (12) */ + return 12; + case NID_sect571k1: /* sect571k1 (13) */ + return 13; + case NID_sect571r1: /* sect571r1 (14) */ + return 14; + case NID_secp160k1: /* secp160k1 (15) */ + return 15; + case NID_secp160r1: /* secp160r1 (16) */ + return 16; + case NID_secp160r2: /* secp160r2 (17) */ + return 17; + case NID_secp192k1: /* secp192k1 (18) */ + return 18; + case NID_X9_62_prime192v1: /* secp192r1 (19) */ + return 19; + case NID_secp224k1: /* secp224k1 (20) */ + return 20; + case NID_secp224r1: /* secp224r1 (21) */ + return 21; + case NID_secp256k1: /* secp256k1 (22) */ + return 22; + case NID_X9_62_prime256v1: /* secp256r1 (23) */ + return 23; + case NID_secp384r1: /* secp384r1 (24) */ + return 24; + case NID_secp521r1: /* secp521r1 (25) */ + return 25; + default: + return 0; + } + } +#endif /* OPENSSL_NO_EC */ + +#ifndef OPENSSL_NO_TLSEXT +unsigned char *ssl_add_clienthello_tlsext(SSL *s, unsigned char *p, unsigned char *limit) + { + int extdatalen=0; + unsigned char *ret = p; + + /* don't add extensions for SSLv3 unless doing secure renegotiation */ + if (s->client_version == SSL3_VERSION + && !s->s3->send_connection_binding) + return p; + + ret+=2; + + if (ret>=limit) return NULL; /* this really never occurs, but ... */ + + if (s->tlsext_hostname != NULL) + { + /* Add TLS extension servername to the Client Hello message */ + unsigned long size_str; + long lenmax; + + /* check for enough space. + 4 for the servername type and entension length + 2 for servernamelist length + 1 for the hostname type + 2 for hostname length + + hostname length + */ + + if ((lenmax = limit - ret - 9) < 0 + || (size_str = strlen(s->tlsext_hostname)) > (unsigned long)lenmax) + return NULL; + + /* extension type and length */ + s2n(TLSEXT_TYPE_server_name,ret); + s2n(size_str+5,ret); + + /* length of servername list */ + s2n(size_str+3,ret); + + /* hostname type, length and hostname */ + *(ret++) = (unsigned char) TLSEXT_NAMETYPE_host_name; + s2n(size_str,ret); + memcpy(ret, s->tlsext_hostname, size_str); + ret+=size_str; + } + + /* Add RI if renegotiating */ + if (s->new_session) + { + int el; + + if(!ssl_add_clienthello_renegotiate_ext(s, 0, &el, 0)) + { + SSLerr(SSL_F_SSL_ADD_CLIENTHELLO_TLSEXT, ERR_R_INTERNAL_ERROR); + return NULL; + } + + if((limit - p - 4 - el) < 0) return NULL; + + s2n(TLSEXT_TYPE_renegotiate,ret); + s2n(el,ret); + + if(!ssl_add_clienthello_renegotiate_ext(s, ret, &el, el)) + { + SSLerr(SSL_F_SSL_ADD_CLIENTHELLO_TLSEXT, ERR_R_INTERNAL_ERROR); + return NULL; + } + + ret += el; + } + +#ifndef OPENSSL_NO_EC + if (s->tlsext_ecpointformatlist != NULL && + s->version != DTLS1_VERSION) + { + /* Add TLS extension ECPointFormats to the ClientHello message */ + long lenmax; + + if ((lenmax = limit - ret - 5) < 0) return NULL; + if (s->tlsext_ecpointformatlist_length > (unsigned long)lenmax) return NULL; + if (s->tlsext_ecpointformatlist_length > 255) + { + SSLerr(SSL_F_SSL_ADD_CLIENTHELLO_TLSEXT, ERR_R_INTERNAL_ERROR); + return NULL; + } + + s2n(TLSEXT_TYPE_ec_point_formats,ret); + s2n(s->tlsext_ecpointformatlist_length + 1,ret); + *(ret++) = (unsigned char) s->tlsext_ecpointformatlist_length; + memcpy(ret, s->tlsext_ecpointformatlist, s->tlsext_ecpointformatlist_length); + ret+=s->tlsext_ecpointformatlist_length; + } + if (s->tlsext_ellipticcurvelist != NULL && + s->version != DTLS1_VERSION) + { + /* Add TLS extension EllipticCurves to the ClientHello message */ + long lenmax; + + if ((lenmax = limit - ret - 6) < 0) return NULL; + if (s->tlsext_ellipticcurvelist_length > (unsigned long)lenmax) return NULL; + if (s->tlsext_ellipticcurvelist_length > 65532) + { + SSLerr(SSL_F_SSL_ADD_CLIENTHELLO_TLSEXT, ERR_R_INTERNAL_ERROR); + return NULL; + } + + s2n(TLSEXT_TYPE_elliptic_curves,ret); + s2n(s->tlsext_ellipticcurvelist_length + 2, ret); + + /* NB: draft-ietf-tls-ecc-12.txt uses a one-byte prefix for + * elliptic_curve_list, but the examples use two bytes. + * http://www1.ietf.org/mail-archive/web/tls/current/msg00538.html + * resolves this to two bytes. + */ + s2n(s->tlsext_ellipticcurvelist_length, ret); + memcpy(ret, s->tlsext_ellipticcurvelist, s->tlsext_ellipticcurvelist_length); + ret+=s->tlsext_ellipticcurvelist_length; + } +#endif /* OPENSSL_NO_EC */ + + if (!(SSL_get_options(s) & SSL_OP_NO_TICKET)) + { + int ticklen; + if (!s->new_session && s->session && s->session->tlsext_tick) + ticklen = s->session->tlsext_ticklen; + else if (s->session && s->tlsext_session_ticket && + s->tlsext_session_ticket->data) + { + ticklen = s->tlsext_session_ticket->length; + s->session->tlsext_tick = OPENSSL_malloc(ticklen); + if (!s->session->tlsext_tick) + return NULL; + memcpy(s->session->tlsext_tick, + s->tlsext_session_ticket->data, + ticklen); + s->session->tlsext_ticklen = ticklen; + } + else + ticklen = 0; + if (ticklen == 0 && s->tlsext_session_ticket && + s->tlsext_session_ticket->data == NULL) + goto skip_ext; + /* Check for enough room 2 for extension type, 2 for len + * rest for ticket + */ + if ((long)(limit - ret - 4 - ticklen) < 0) return NULL; + s2n(TLSEXT_TYPE_session_ticket,ret); + s2n(ticklen,ret); + if (ticklen) + { + memcpy(ret, s->session->tlsext_tick, ticklen); + ret += ticklen; + } + } + skip_ext: + +#ifdef TLSEXT_TYPE_opaque_prf_input + if (s->s3->client_opaque_prf_input != NULL && + s->version != DTLS1_VERSION) + { + size_t col = s->s3->client_opaque_prf_input_len; + + if ((long)(limit - ret - 6 - col < 0)) + return NULL; + if (col > 0xFFFD) /* can't happen */ + return NULL; + + s2n(TLSEXT_TYPE_opaque_prf_input, ret); + s2n(col + 2, ret); + s2n(col, ret); + memcpy(ret, s->s3->client_opaque_prf_input, col); + ret += col; + } +#endif + + if (s->tlsext_status_type == TLSEXT_STATUSTYPE_ocsp && + s->version != DTLS1_VERSION) + { + int i; + long extlen, idlen, itmp; + OCSP_RESPID *id; + + idlen = 0; + for (i = 0; i < sk_OCSP_RESPID_num(s->tlsext_ocsp_ids); i++) + { + id = sk_OCSP_RESPID_value(s->tlsext_ocsp_ids, i); + itmp = i2d_OCSP_RESPID(id, NULL); + if (itmp <= 0) + return NULL; + idlen += itmp + 2; + } + + if (s->tlsext_ocsp_exts) + { + extlen = i2d_X509_EXTENSIONS(s->tlsext_ocsp_exts, NULL); + if (extlen < 0) + return NULL; + } + else + extlen = 0; + + if ((long)(limit - ret - 7 - extlen - idlen) < 0) return NULL; + s2n(TLSEXT_TYPE_status_request, ret); + if (extlen + idlen > 0xFFF0) + return NULL; + s2n(extlen + idlen + 5, ret); + *(ret++) = TLSEXT_STATUSTYPE_ocsp; + s2n(idlen, ret); + for (i = 0; i < sk_OCSP_RESPID_num(s->tlsext_ocsp_ids); i++) + { + /* save position of id len */ + unsigned char *q = ret; + id = sk_OCSP_RESPID_value(s->tlsext_ocsp_ids, i); + /* skip over id len */ + ret += 2; + itmp = i2d_OCSP_RESPID(id, &ret); + /* write id len */ + s2n(itmp, q); + } + s2n(extlen, ret); + if (extlen > 0) + i2d_X509_EXTENSIONS(s->tlsext_ocsp_exts, &ret); + } + +#ifndef OPENSSL_NO_NEXTPROTONEG + if (s->ctx->next_proto_select_cb && !s->s3->tmp.finish_md_len) + { + /* The client advertises an emtpy extension to indicate its + * support for Next Protocol Negotiation */ + if (limit - ret - 4 < 0) + return NULL; + s2n(TLSEXT_TYPE_next_proto_neg,ret); + s2n(0,ret); + } +#endif + + if ((extdatalen = ret-p-2)== 0) + return p; + + s2n(extdatalen,p); + return ret; + } + +unsigned char *ssl_add_serverhello_tlsext(SSL *s, unsigned char *p, unsigned char *limit) + { + int extdatalen=0; + unsigned char *ret = p; +#ifndef OPENSSL_NO_NEXTPROTONEG + int next_proto_neg_seen; +#endif + + /* don't add extensions for SSLv3, unless doing secure renegotiation */ + if (s->version == SSL3_VERSION && !s->s3->send_connection_binding) + return p; + + ret+=2; + if (ret>=limit) return NULL; /* this really never occurs, but ... */ + + if (!s->hit && s->servername_done == 1 && s->session->tlsext_hostname != NULL) + { + if ((long)(limit - ret - 4) < 0) return NULL; + + s2n(TLSEXT_TYPE_server_name,ret); + s2n(0,ret); + } + + if(s->s3->send_connection_binding) + { + int el; + + if(!ssl_add_serverhello_renegotiate_ext(s, 0, &el, 0)) + { + SSLerr(SSL_F_SSL_ADD_SERVERHELLO_TLSEXT, ERR_R_INTERNAL_ERROR); + return NULL; + } + + if((limit - p - 4 - el) < 0) return NULL; + + s2n(TLSEXT_TYPE_renegotiate,ret); + s2n(el,ret); + + if(!ssl_add_serverhello_renegotiate_ext(s, ret, &el, el)) + { + SSLerr(SSL_F_SSL_ADD_SERVERHELLO_TLSEXT, ERR_R_INTERNAL_ERROR); + return NULL; + } + + ret += el; + } + +#ifndef OPENSSL_NO_EC + if (s->tlsext_ecpointformatlist != NULL && + s->version != DTLS1_VERSION) + { + /* Add TLS extension ECPointFormats to the ServerHello message */ + long lenmax; + + if ((lenmax = limit - ret - 5) < 0) return NULL; + if (s->tlsext_ecpointformatlist_length > (unsigned long)lenmax) return NULL; + if (s->tlsext_ecpointformatlist_length > 255) + { + SSLerr(SSL_F_SSL_ADD_SERVERHELLO_TLSEXT, ERR_R_INTERNAL_ERROR); + return NULL; + } + + s2n(TLSEXT_TYPE_ec_point_formats,ret); + s2n(s->tlsext_ecpointformatlist_length + 1,ret); + *(ret++) = (unsigned char) s->tlsext_ecpointformatlist_length; + memcpy(ret, s->tlsext_ecpointformatlist, s->tlsext_ecpointformatlist_length); + ret+=s->tlsext_ecpointformatlist_length; + + } + /* Currently the server should not respond with a SupportedCurves extension */ +#endif /* OPENSSL_NO_EC */ + + if (s->tlsext_ticket_expected + && !(SSL_get_options(s) & SSL_OP_NO_TICKET)) + { + if ((long)(limit - ret - 4) < 0) return NULL; + s2n(TLSEXT_TYPE_session_ticket,ret); + s2n(0,ret); + } + + if (s->tlsext_status_expected) + { + if ((long)(limit - ret - 4) < 0) return NULL; + s2n(TLSEXT_TYPE_status_request,ret); + s2n(0,ret); + } + +#ifdef TLSEXT_TYPE_opaque_prf_input + if (s->s3->server_opaque_prf_input != NULL && + s->version != DTLS1_VERSION) + { + size_t sol = s->s3->server_opaque_prf_input_len; + + if ((long)(limit - ret - 6 - sol) < 0) + return NULL; + if (sol > 0xFFFD) /* can't happen */ + return NULL; + + s2n(TLSEXT_TYPE_opaque_prf_input, ret); + s2n(sol + 2, ret); + s2n(sol, ret); + memcpy(ret, s->s3->server_opaque_prf_input, sol); + ret += sol; + } +#endif + if (((s->s3->tmp.new_cipher->id & 0xFFFF)==0x80 || (s->s3->tmp.new_cipher->id & 0xFFFF)==0x81) + && (SSL_get_options(s) & SSL_OP_CRYPTOPRO_TLSEXT_BUG)) + { const unsigned char cryptopro_ext[36] = { + 0xfd, 0xe8, /*65000*/ + 0x00, 0x20, /*32 bytes length*/ + 0x30, 0x1e, 0x30, 0x08, 0x06, 0x06, 0x2a, 0x85, + 0x03, 0x02, 0x02, 0x09, 0x30, 0x08, 0x06, 0x06, + 0x2a, 0x85, 0x03, 0x02, 0x02, 0x16, 0x30, 0x08, + 0x06, 0x06, 0x2a, 0x85, 0x03, 0x02, 0x02, 0x17}; + if (limit-ret<36) return NULL; + memcpy(ret,cryptopro_ext,36); + ret+=36; + + } + +#ifndef OPENSSL_NO_NEXTPROTONEG + next_proto_neg_seen = s->s3->next_proto_neg_seen; + s->s3->next_proto_neg_seen = 0; + if (next_proto_neg_seen && s->ctx->next_protos_advertised_cb) + { + const unsigned char *npa; + unsigned int npalen; + int r; + + r = s->ctx->next_protos_advertised_cb(s, &npa, &npalen, s->ctx->next_protos_advertised_cb_arg); + if (r == SSL_TLSEXT_ERR_OK) + { + if ((long)(limit - ret - 4 - npalen) < 0) return NULL; + s2n(TLSEXT_TYPE_next_proto_neg,ret); + s2n(npalen,ret); + memcpy(ret, npa, npalen); + ret += npalen; + s->s3->next_proto_neg_seen = 1; + } + } +#endif + + if ((extdatalen = ret-p-2)== 0) + return p; + + s2n(extdatalen,p); + return ret; + } + +int ssl_parse_clienthello_tlsext(SSL *s, unsigned char **p, unsigned char *d, int n, int *al) + { + unsigned short type; + unsigned short size; + unsigned short len; + unsigned char *data = *p; + int renegotiate_seen = 0; + + s->servername_done = 0; + s->tlsext_status_type = -1; + + if (data >= (d+n-2)) + goto ri_check; + n2s(data,len); + + if (data > (d+n-len)) + goto ri_check; + + while (data <= (d+n-4)) + { + n2s(data,type); + n2s(data,size); + + if (data+size > (d+n)) + goto ri_check; +#if 0 + fprintf(stderr,"Received extension type %d size %d\n",type,size); +#endif + if (s->tlsext_debug_cb) + s->tlsext_debug_cb(s, 0, type, data, size, + s->tlsext_debug_arg); +/* The servername extension is treated as follows: + + - Only the hostname type is supported with a maximum length of 255. + - The servername is rejected if too long or if it contains zeros, + in which case an fatal alert is generated. + - The servername field is maintained together with the session cache. + - When a session is resumed, the servername call back invoked in order + to allow the application to position itself to the right context. + - The servername is acknowledged if it is new for a session or when + it is identical to a previously used for the same session. + Applications can control the behaviour. They can at any time + set a 'desirable' servername for a new SSL object. This can be the + case for example with HTTPS when a Host: header field is received and + a renegotiation is requested. In this case, a possible servername + presented in the new client hello is only acknowledged if it matches + the value of the Host: field. + - Applications must use SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION + if they provide for changing an explicit servername context for the session, + i.e. when the session has been established with a servername extension. + - On session reconnect, the servername extension may be absent. + +*/ + + if (type == TLSEXT_TYPE_server_name) + { + unsigned char *sdata; + int servname_type; + int dsize; + + if (size < 2) + { + *al = SSL_AD_DECODE_ERROR; + return 0; + } + n2s(data,dsize); + size -= 2; + if (dsize > size ) + { + *al = SSL_AD_DECODE_ERROR; + return 0; + } + + sdata = data; + while (dsize > 3) + { + servname_type = *(sdata++); + n2s(sdata,len); + dsize -= 3; + + if (len > dsize) + { + *al = SSL_AD_DECODE_ERROR; + return 0; + } + if (s->servername_done == 0) + switch (servname_type) + { + case TLSEXT_NAMETYPE_host_name: + if (!s->hit) + { + if(s->session->tlsext_hostname) + { + *al = SSL_AD_DECODE_ERROR; + return 0; + } + if (len > TLSEXT_MAXLEN_host_name) + { + *al = TLS1_AD_UNRECOGNIZED_NAME; + return 0; + } + if ((s->session->tlsext_hostname = OPENSSL_malloc(len+1)) == NULL) + { + *al = TLS1_AD_INTERNAL_ERROR; + return 0; + } + memcpy(s->session->tlsext_hostname, sdata, len); + s->session->tlsext_hostname[len]='\0'; + if (strlen(s->session->tlsext_hostname) != len) { + OPENSSL_free(s->session->tlsext_hostname); + s->session->tlsext_hostname = NULL; + *al = TLS1_AD_UNRECOGNIZED_NAME; + return 0; + } + s->servername_done = 1; + + } + else + s->servername_done = s->session->tlsext_hostname + && strlen(s->session->tlsext_hostname) == len + && strncmp(s->session->tlsext_hostname, (char *)sdata, len) == 0; + + break; + + default: + break; + } + + dsize -= len; + } + if (dsize != 0) + { + *al = SSL_AD_DECODE_ERROR; + return 0; + } + + } + +#ifndef OPENSSL_NO_EC + else if (type == TLSEXT_TYPE_ec_point_formats && + s->version != DTLS1_VERSION) + { + unsigned char *sdata = data; + int ecpointformatlist_length = *(sdata++); + + if (ecpointformatlist_length != size - 1) + { + *al = TLS1_AD_DECODE_ERROR; + return 0; + } + if (!s->hit) + { + if(s->session->tlsext_ecpointformatlist) + { + OPENSSL_free(s->session->tlsext_ecpointformatlist); + s->session->tlsext_ecpointformatlist = NULL; + } + s->session->tlsext_ecpointformatlist_length = 0; + if ((s->session->tlsext_ecpointformatlist = OPENSSL_malloc(ecpointformatlist_length)) == NULL) + { + *al = TLS1_AD_INTERNAL_ERROR; + return 0; + } + s->session->tlsext_ecpointformatlist_length = ecpointformatlist_length; + memcpy(s->session->tlsext_ecpointformatlist, sdata, ecpointformatlist_length); + } +#if 0 + fprintf(stderr,"ssl_parse_clienthello_tlsext s->session->tlsext_ecpointformatlist (length=%i) ", s->session->tlsext_ecpointformatlist_length); + sdata = s->session->tlsext_ecpointformatlist; + for (i = 0; i < s->session->tlsext_ecpointformatlist_length; i++) + fprintf(stderr,"%i ",*(sdata++)); + fprintf(stderr,"\n"); +#endif + } + else if (type == TLSEXT_TYPE_elliptic_curves && + s->version != DTLS1_VERSION) + { + unsigned char *sdata = data; + int ellipticcurvelist_length = (*(sdata++) << 8); + ellipticcurvelist_length += (*(sdata++)); + + if (ellipticcurvelist_length != size - 2) + { + *al = TLS1_AD_DECODE_ERROR; + return 0; + } + if (!s->hit) + { + if(s->session->tlsext_ellipticcurvelist) + { + *al = TLS1_AD_DECODE_ERROR; + return 0; + } + s->session->tlsext_ellipticcurvelist_length = 0; + if ((s->session->tlsext_ellipticcurvelist = OPENSSL_malloc(ellipticcurvelist_length)) == NULL) + { + *al = TLS1_AD_INTERNAL_ERROR; + return 0; + } + s->session->tlsext_ellipticcurvelist_length = ellipticcurvelist_length; + memcpy(s->session->tlsext_ellipticcurvelist, sdata, ellipticcurvelist_length); + } +#if 0 + fprintf(stderr,"ssl_parse_clienthello_tlsext s->session->tlsext_ellipticcurvelist (length=%i) ", s->session->tlsext_ellipticcurvelist_length); + sdata = s->session->tlsext_ellipticcurvelist; + for (i = 0; i < s->session->tlsext_ellipticcurvelist_length; i++) + fprintf(stderr,"%i ",*(sdata++)); + fprintf(stderr,"\n"); +#endif + } +#endif /* OPENSSL_NO_EC */ +#ifdef TLSEXT_TYPE_opaque_prf_input + else if (type == TLSEXT_TYPE_opaque_prf_input && + s->version != DTLS1_VERSION) + { + unsigned char *sdata = data; + + if (size < 2) + { + *al = SSL_AD_DECODE_ERROR; + return 0; + } + n2s(sdata, s->s3->client_opaque_prf_input_len); + if (s->s3->client_opaque_prf_input_len != size - 2) + { + *al = SSL_AD_DECODE_ERROR; + return 0; + } + + if (s->s3->client_opaque_prf_input != NULL) /* shouldn't really happen */ + OPENSSL_free(s->s3->client_opaque_prf_input); + if (s->s3->client_opaque_prf_input_len == 0) + s->s3->client_opaque_prf_input = OPENSSL_malloc(1); /* dummy byte just to get non-NULL */ + else + s->s3->client_opaque_prf_input = BUF_memdup(sdata, s->s3->client_opaque_prf_input_len); + if (s->s3->client_opaque_prf_input == NULL) + { + *al = TLS1_AD_INTERNAL_ERROR; + return 0; + } + } +#endif + else if (type == TLSEXT_TYPE_session_ticket) + { + if (s->tls_session_ticket_ext_cb && + !s->tls_session_ticket_ext_cb(s, data, size, s->tls_session_ticket_ext_cb_arg)) + { + *al = TLS1_AD_INTERNAL_ERROR; + return 0; + } + } + else if (type == TLSEXT_TYPE_renegotiate) + { + if(!ssl_parse_clienthello_renegotiate_ext(s, data, size, al)) + return 0; + renegotiate_seen = 1; + } + else if (type == TLSEXT_TYPE_status_request && + s->version != DTLS1_VERSION && s->ctx->tlsext_status_cb) + { + + if (size < 5) + { + *al = SSL_AD_DECODE_ERROR; + return 0; + } + + s->tlsext_status_type = *data++; + size--; + if (s->tlsext_status_type == TLSEXT_STATUSTYPE_ocsp) + { + const unsigned char *sdata; + int dsize; + /* Read in responder_id_list */ + n2s(data,dsize); + size -= 2; + if (dsize > size ) + { + *al = SSL_AD_DECODE_ERROR; + return 0; + } + while (dsize > 0) + { + OCSP_RESPID *id; + int idsize; + if (dsize < 4) + { + *al = SSL_AD_DECODE_ERROR; + return 0; + } + n2s(data, idsize); + dsize -= 2 + idsize; + size -= 2 + idsize; + if (dsize < 0) + { + *al = SSL_AD_DECODE_ERROR; + return 0; + } + sdata = data; + data += idsize; + id = d2i_OCSP_RESPID(NULL, + &sdata, idsize); + if (!id) + { + *al = SSL_AD_DECODE_ERROR; + return 0; + } + if (data != sdata) + { + OCSP_RESPID_free(id); + *al = SSL_AD_DECODE_ERROR; + return 0; + } + if (!s->tlsext_ocsp_ids + && !(s->tlsext_ocsp_ids = + sk_OCSP_RESPID_new_null())) + { + OCSP_RESPID_free(id); + *al = SSL_AD_INTERNAL_ERROR; + return 0; + } + if (!sk_OCSP_RESPID_push( + s->tlsext_ocsp_ids, id)) + { + OCSP_RESPID_free(id); + *al = SSL_AD_INTERNAL_ERROR; + return 0; + } + } + + /* Read in request_extensions */ + if (size < 2) + { + *al = SSL_AD_DECODE_ERROR; + return 0; + } + n2s(data,dsize); + size -= 2; + if (dsize != size) + { + *al = SSL_AD_DECODE_ERROR; + return 0; + } + sdata = data; + if (dsize > 0) + { + if (s->tlsext_ocsp_exts) + { + sk_X509_EXTENSION_pop_free(s->tlsext_ocsp_exts, + X509_EXTENSION_free); + } + + s->tlsext_ocsp_exts = + d2i_X509_EXTENSIONS(NULL, + &sdata, dsize); + if (!s->tlsext_ocsp_exts + || (data + dsize != sdata)) + { + *al = SSL_AD_DECODE_ERROR; + return 0; + } + } + } + /* We don't know what to do with any other type + * so ignore it. + */ + else + s->tlsext_status_type = -1; + } +#ifndef OPENSSL_NO_NEXTPROTONEG + else if (type == TLSEXT_TYPE_next_proto_neg && + s->s3->tmp.finish_md_len == 0) + { + /* We shouldn't accept this extension on a + * renegotiation. + * + * s->new_session will be set on renegotiation, but we + * probably shouldn't rely that it couldn't be set on + * the initial renegotation too in certain cases (when + * there's some other reason to disallow resuming an + * earlier session -- the current code won't be doing + * anything like that, but this might change). + + * A valid sign that there's been a previous handshake + * in this connection is if s->s3->tmp.finish_md_len > + * 0. (We are talking about a check that will happen + * in the Hello protocol round, well before a new + * Finished message could have been computed.) */ + s->s3->next_proto_neg_seen = 1; + } +#endif + + /* session ticket processed earlier */ + data+=size; + } + + *p = data; + + ri_check: + + /* Need RI if renegotiating */ + + if (!renegotiate_seen && s->new_session && + !(s->options & SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION)) + { + *al = SSL_AD_HANDSHAKE_FAILURE; + SSLerr(SSL_F_SSL_PARSE_CLIENTHELLO_TLSEXT, + SSL_R_UNSAFE_LEGACY_RENEGOTIATION_DISABLED); + return 0; + } + + return 1; + } + +#ifndef OPENSSL_NO_NEXTPROTONEG +/* ssl_next_proto_validate validates a Next Protocol Negotiation block. No + * elements of zero length are allowed and the set of elements must exactly fill + * the length of the block. */ +static int ssl_next_proto_validate(unsigned char *d, unsigned len) + { + unsigned int off = 0; + + while (off < len) + { + if (d[off] == 0) + return 0; + off += d[off]; + off++; + } + + return off == len; + } +#endif + +int ssl_parse_serverhello_tlsext(SSL *s, unsigned char **p, unsigned char *d, int n, int *al) + { + unsigned short length; + unsigned short type; + unsigned short size; + unsigned char *data = *p; + int tlsext_servername = 0; + int renegotiate_seen = 0; + + if (data >= (d+n-2)) + goto ri_check; + + n2s(data,length); + if (data+length != d+n) + { + *al = SSL_AD_DECODE_ERROR; + return 0; + } + + while(data <= (d+n-4)) + { + n2s(data,type); + n2s(data,size); + + if (data+size > (d+n)) + goto ri_check; + + if (s->tlsext_debug_cb) + s->tlsext_debug_cb(s, 1, type, data, size, + s->tlsext_debug_arg); + + if (type == TLSEXT_TYPE_server_name) + { + if (s->tlsext_hostname == NULL || size > 0) + { + *al = TLS1_AD_UNRECOGNIZED_NAME; + return 0; + } + tlsext_servername = 1; + } + +#ifndef OPENSSL_NO_EC + else if (type == TLSEXT_TYPE_ec_point_formats && + s->version != DTLS1_VERSION) + { + unsigned char *sdata = data; + int ecpointformatlist_length = *(sdata++); + + if (ecpointformatlist_length != size - 1) + { + *al = TLS1_AD_DECODE_ERROR; + return 0; + } + s->session->tlsext_ecpointformatlist_length = 0; + if (s->session->tlsext_ecpointformatlist != NULL) OPENSSL_free(s->session->tlsext_ecpointformatlist); + if ((s->session->tlsext_ecpointformatlist = OPENSSL_malloc(ecpointformatlist_length)) == NULL) + { + *al = TLS1_AD_INTERNAL_ERROR; + return 0; + } + s->session->tlsext_ecpointformatlist_length = ecpointformatlist_length; + memcpy(s->session->tlsext_ecpointformatlist, sdata, ecpointformatlist_length); +#if 0 + fprintf(stderr,"ssl_parse_serverhello_tlsext s->session->tlsext_ecpointformatlist "); + sdata = s->session->tlsext_ecpointformatlist; + for (i = 0; i < s->session->tlsext_ecpointformatlist_length; i++) + fprintf(stderr,"%i ",*(sdata++)); + fprintf(stderr,"\n"); +#endif + } +#endif /* OPENSSL_NO_EC */ + + else if (type == TLSEXT_TYPE_session_ticket) + { + if (s->tls_session_ticket_ext_cb && + !s->tls_session_ticket_ext_cb(s, data, size, s->tls_session_ticket_ext_cb_arg)) + { + *al = TLS1_AD_INTERNAL_ERROR; + return 0; + } + if ((SSL_get_options(s) & SSL_OP_NO_TICKET) + || (size > 0)) + { + *al = TLS1_AD_UNSUPPORTED_EXTENSION; + return 0; + } + s->tlsext_ticket_expected = 1; + } +#ifdef TLSEXT_TYPE_opaque_prf_input + else if (type == TLSEXT_TYPE_opaque_prf_input && + s->version != DTLS1_VERSION) + { + unsigned char *sdata = data; + + if (size < 2) + { + *al = SSL_AD_DECODE_ERROR; + return 0; + } + n2s(sdata, s->s3->server_opaque_prf_input_len); + if (s->s3->server_opaque_prf_input_len != size - 2) + { + *al = SSL_AD_DECODE_ERROR; + return 0; + } + + if (s->s3->server_opaque_prf_input != NULL) /* shouldn't really happen */ + OPENSSL_free(s->s3->server_opaque_prf_input); + if (s->s3->server_opaque_prf_input_len == 0) + s->s3->server_opaque_prf_input = OPENSSL_malloc(1); /* dummy byte just to get non-NULL */ + else + s->s3->server_opaque_prf_input = BUF_memdup(sdata, s->s3->server_opaque_prf_input_len); + + if (s->s3->server_opaque_prf_input == NULL) + { + *al = TLS1_AD_INTERNAL_ERROR; + return 0; + } + } +#endif + else if (type == TLSEXT_TYPE_status_request && + s->version != DTLS1_VERSION) + { + /* MUST be empty and only sent if we've requested + * a status request message. + */ + if ((s->tlsext_status_type == -1) || (size > 0)) + { + *al = TLS1_AD_UNSUPPORTED_EXTENSION; + return 0; + } + /* Set flag to expect CertificateStatus message */ + s->tlsext_status_expected = 1; + } +#ifndef OPENSSL_NO_NEXTPROTONEG + else if (type == TLSEXT_TYPE_next_proto_neg) + { + unsigned char *selected; + unsigned char selected_len; + + /* We must have requested it. */ + if ((s->ctx->next_proto_select_cb == NULL)) + { + *al = TLS1_AD_UNSUPPORTED_EXTENSION; + return 0; + } + /* The data must be valid */ + if (!ssl_next_proto_validate(data, size)) + { + *al = TLS1_AD_DECODE_ERROR; + return 0; + } + if (s->ctx->next_proto_select_cb(s, &selected, &selected_len, data, size, s->ctx->next_proto_select_cb_arg) != SSL_TLSEXT_ERR_OK) + { + *al = TLS1_AD_INTERNAL_ERROR; + return 0; + } + s->next_proto_negotiated = OPENSSL_malloc(selected_len); + if (!s->next_proto_negotiated) + { + *al = TLS1_AD_INTERNAL_ERROR; + return 0; + } + memcpy(s->next_proto_negotiated, selected, selected_len); + s->next_proto_negotiated_len = selected_len; + } +#endif + else if (type == TLSEXT_TYPE_renegotiate) + { + if(!ssl_parse_serverhello_renegotiate_ext(s, data, size, al)) + return 0; + renegotiate_seen = 1; + } + data+=size; + } + + if (data != d+n) + { + *al = SSL_AD_DECODE_ERROR; + return 0; + } + + if (!s->hit && tlsext_servername == 1) + { + if (s->tlsext_hostname) + { + if (s->session->tlsext_hostname == NULL) + { + s->session->tlsext_hostname = BUF_strdup(s->tlsext_hostname); + if (!s->session->tlsext_hostname) + { + *al = SSL_AD_UNRECOGNIZED_NAME; + return 0; + } + } + else + { + *al = SSL_AD_DECODE_ERROR; + return 0; + } + } + } + + *p = data; + + ri_check: + + /* Determine if we need to see RI. Strictly speaking if we want to + * avoid an attack we should *always* see RI even on initial server + * hello because the client doesn't see any renegotiation during an + * attack. However this would mean we could not connect to any server + * which doesn't support RI so for the immediate future tolerate RI + * absence on initial connect only. + */ + if (!renegotiate_seen + && !(s->options & SSL_OP_LEGACY_SERVER_CONNECT) + && !(s->options & SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION)) + { + *al = SSL_AD_HANDSHAKE_FAILURE; + SSLerr(SSL_F_SSL_PARSE_SERVERHELLO_TLSEXT, + SSL_R_UNSAFE_LEGACY_RENEGOTIATION_DISABLED); + return 0; + } + + return 1; + } + + +int ssl_prepare_clienthello_tlsext(SSL *s) + { +#ifndef OPENSSL_NO_EC + /* If we are client and using an elliptic curve cryptography cipher suite, send the point formats + * and elliptic curves we support. + */ + int using_ecc = 0; + int i; + unsigned char *j; + unsigned long alg_k, alg_a; + STACK_OF(SSL_CIPHER) *cipher_stack = SSL_get_ciphers(s); + + for (i = 0; i < sk_SSL_CIPHER_num(cipher_stack); i++) + { + SSL_CIPHER *c = sk_SSL_CIPHER_value(cipher_stack, i); + + alg_k = c->algorithm_mkey; + alg_a = c->algorithm_auth; + if ((alg_k & (SSL_kEECDH|SSL_kECDHr|SSL_kECDHe) || (alg_a & SSL_aECDSA))) + { + using_ecc = 1; + break; + } + } + using_ecc = using_ecc && (s->version == TLS1_VERSION); + if (using_ecc) + { + if (s->tlsext_ecpointformatlist != NULL) OPENSSL_free(s->tlsext_ecpointformatlist); + if ((s->tlsext_ecpointformatlist = OPENSSL_malloc(3)) == NULL) + { + SSLerr(SSL_F_SSL_PREPARE_CLIENTHELLO_TLSEXT,ERR_R_MALLOC_FAILURE); + return -1; + } + s->tlsext_ecpointformatlist_length = 3; + s->tlsext_ecpointformatlist[0] = TLSEXT_ECPOINTFORMAT_uncompressed; + s->tlsext_ecpointformatlist[1] = TLSEXT_ECPOINTFORMAT_ansiX962_compressed_prime; + s->tlsext_ecpointformatlist[2] = TLSEXT_ECPOINTFORMAT_ansiX962_compressed_char2; + + /* we support all named elliptic curves in draft-ietf-tls-ecc-12 */ + if (s->tlsext_ellipticcurvelist != NULL) OPENSSL_free(s->tlsext_ellipticcurvelist); + s->tlsext_ellipticcurvelist_length = sizeof(nid_list)/sizeof(nid_list[0]) * 2; + if ((s->tlsext_ellipticcurvelist = OPENSSL_malloc(s->tlsext_ellipticcurvelist_length)) == NULL) + { + s->tlsext_ellipticcurvelist_length = 0; + SSLerr(SSL_F_SSL_PREPARE_CLIENTHELLO_TLSEXT,ERR_R_MALLOC_FAILURE); + return -1; + } + for (i = 1, j = s->tlsext_ellipticcurvelist; (unsigned int)i <= + sizeof(nid_list)/sizeof(nid_list[0]); i++) + s2n(i,j); + } +#endif /* OPENSSL_NO_EC */ + +#ifdef TLSEXT_TYPE_opaque_prf_input + { + int r = 1; + + if (s->ctx->tlsext_opaque_prf_input_callback != 0) + { + r = s->ctx->tlsext_opaque_prf_input_callback(s, NULL, 0, s->ctx->tlsext_opaque_prf_input_callback_arg); + if (!r) + return -1; + } + + if (s->tlsext_opaque_prf_input != NULL) + { + if (s->s3->client_opaque_prf_input != NULL) /* shouldn't really happen */ + OPENSSL_free(s->s3->client_opaque_prf_input); + + if (s->tlsext_opaque_prf_input_len == 0) + s->s3->client_opaque_prf_input = OPENSSL_malloc(1); /* dummy byte just to get non-NULL */ + else + s->s3->client_opaque_prf_input = BUF_memdup(s->tlsext_opaque_prf_input, s->tlsext_opaque_prf_input_len); + if (s->s3->client_opaque_prf_input == NULL) + { + SSLerr(SSL_F_SSL_PREPARE_CLIENTHELLO_TLSEXT,ERR_R_MALLOC_FAILURE); + return -1; + } + s->s3->client_opaque_prf_input_len = s->tlsext_opaque_prf_input_len; + } + + if (r == 2) + /* at callback's request, insist on receiving an appropriate server opaque PRF input */ + s->s3->server_opaque_prf_input_len = s->tlsext_opaque_prf_input_len; + } +#endif + + return 1; + } + +int ssl_prepare_serverhello_tlsext(SSL *s) + { +#ifndef OPENSSL_NO_EC + /* If we are server and using an ECC cipher suite, send the point formats we support + * if the client sent us an ECPointsFormat extension. Note that the server is not + * supposed to send an EllipticCurves extension. + */ + + unsigned long alg_k = s->s3->tmp.new_cipher->algorithm_mkey; + unsigned long alg_a = s->s3->tmp.new_cipher->algorithm_auth; + int using_ecc = (alg_k & (SSL_kEECDH|SSL_kECDHr|SSL_kECDHe)) || (alg_a & SSL_aECDSA); + using_ecc = using_ecc && (s->session->tlsext_ecpointformatlist != NULL); + + if (using_ecc) + { + if (s->tlsext_ecpointformatlist != NULL) OPENSSL_free(s->tlsext_ecpointformatlist); + if ((s->tlsext_ecpointformatlist = OPENSSL_malloc(3)) == NULL) + { + SSLerr(SSL_F_SSL_PREPARE_SERVERHELLO_TLSEXT,ERR_R_MALLOC_FAILURE); + return -1; + } + s->tlsext_ecpointformatlist_length = 3; + s->tlsext_ecpointformatlist[0] = TLSEXT_ECPOINTFORMAT_uncompressed; + s->tlsext_ecpointformatlist[1] = TLSEXT_ECPOINTFORMAT_ansiX962_compressed_prime; + s->tlsext_ecpointformatlist[2] = TLSEXT_ECPOINTFORMAT_ansiX962_compressed_char2; + } +#endif /* OPENSSL_NO_EC */ + + return 1; + } + +int ssl_check_clienthello_tlsext(SSL *s) + { + int ret=SSL_TLSEXT_ERR_NOACK; + int al = SSL_AD_UNRECOGNIZED_NAME; + +#ifndef OPENSSL_NO_EC + /* The handling of the ECPointFormats extension is done elsewhere, namely in + * ssl3_choose_cipher in s3_lib.c. + */ + /* The handling of the EllipticCurves extension is done elsewhere, namely in + * ssl3_choose_cipher in s3_lib.c. + */ +#endif + + if (s->ctx != NULL && s->ctx->tlsext_servername_callback != 0) + ret = s->ctx->tlsext_servername_callback(s, &al, s->ctx->tlsext_servername_arg); + else if (s->initial_ctx != NULL && s->initial_ctx->tlsext_servername_callback != 0) + ret = s->initial_ctx->tlsext_servername_callback(s, &al, s->initial_ctx->tlsext_servername_arg); + + /* If status request then ask callback what to do. + * Note: this must be called after servername callbacks in case + * the certificate has changed. + */ + if ((s->tlsext_status_type != -1) && s->ctx && s->ctx->tlsext_status_cb) + { + int r; + r = s->ctx->tlsext_status_cb(s, s->ctx->tlsext_status_arg); + switch (r) + { + /* We don't want to send a status request response */ + case SSL_TLSEXT_ERR_NOACK: + s->tlsext_status_expected = 0; + break; + /* status request response should be sent */ + case SSL_TLSEXT_ERR_OK: + if (s->tlsext_ocsp_resp) + s->tlsext_status_expected = 1; + else + s->tlsext_status_expected = 0; + break; + /* something bad happened */ + case SSL_TLSEXT_ERR_ALERT_FATAL: + ret = SSL_TLSEXT_ERR_ALERT_FATAL; + al = SSL_AD_INTERNAL_ERROR; + goto err; + } + } + else + s->tlsext_status_expected = 0; + +#ifdef TLSEXT_TYPE_opaque_prf_input + { + /* This sort of belongs into ssl_prepare_serverhello_tlsext(), + * but we might be sending an alert in response to the client hello, + * so this has to happen here in ssl_check_clienthello_tlsext(). */ + + int r = 1; + + if (s->ctx->tlsext_opaque_prf_input_callback != 0) + { + r = s->ctx->tlsext_opaque_prf_input_callback(s, NULL, 0, s->ctx->tlsext_opaque_prf_input_callback_arg); + if (!r) + { + ret = SSL_TLSEXT_ERR_ALERT_FATAL; + al = SSL_AD_INTERNAL_ERROR; + goto err; + } + } + + if (s->s3->server_opaque_prf_input != NULL) /* shouldn't really happen */ + OPENSSL_free(s->s3->server_opaque_prf_input); + s->s3->server_opaque_prf_input = NULL; + + if (s->tlsext_opaque_prf_input != NULL) + { + if (s->s3->client_opaque_prf_input != NULL && + s->s3->client_opaque_prf_input_len == s->tlsext_opaque_prf_input_len) + { + /* can only use this extension if we have a server opaque PRF input + * of the same length as the client opaque PRF input! */ + + if (s->tlsext_opaque_prf_input_len == 0) + s->s3->server_opaque_prf_input = OPENSSL_malloc(1); /* dummy byte just to get non-NULL */ + else + s->s3->server_opaque_prf_input = BUF_memdup(s->tlsext_opaque_prf_input, s->tlsext_opaque_prf_input_len); + if (s->s3->server_opaque_prf_input == NULL) + { + ret = SSL_TLSEXT_ERR_ALERT_FATAL; + al = SSL_AD_INTERNAL_ERROR; + goto err; + } + s->s3->server_opaque_prf_input_len = s->tlsext_opaque_prf_input_len; + } + } + + if (r == 2 && s->s3->server_opaque_prf_input == NULL) + { + /* The callback wants to enforce use of the extension, + * but we can't do that with the client opaque PRF input; + * abort the handshake. + */ + ret = SSL_TLSEXT_ERR_ALERT_FATAL; + al = SSL_AD_HANDSHAKE_FAILURE; + } + } + +#endif + err: + switch (ret) + { + case SSL_TLSEXT_ERR_ALERT_FATAL: + ssl3_send_alert(s,SSL3_AL_FATAL,al); + return -1; + + case SSL_TLSEXT_ERR_ALERT_WARNING: + ssl3_send_alert(s,SSL3_AL_WARNING,al); + return 1; + + case SSL_TLSEXT_ERR_NOACK: + s->servername_done=0; + default: + return 1; + } + } + +int ssl_check_serverhello_tlsext(SSL *s) + { + int ret=SSL_TLSEXT_ERR_NOACK; + int al = SSL_AD_UNRECOGNIZED_NAME; + +#ifndef OPENSSL_NO_EC + /* If we are client and using an elliptic curve cryptography cipher + * suite, then if server returns an EC point formats lists extension + * it must contain uncompressed. + */ + unsigned long alg_k = s->s3->tmp.new_cipher->algorithm_mkey; + unsigned long alg_a = s->s3->tmp.new_cipher->algorithm_auth; + if ((s->tlsext_ecpointformatlist != NULL) && (s->tlsext_ecpointformatlist_length > 0) && + (s->session->tlsext_ecpointformatlist != NULL) && (s->session->tlsext_ecpointformatlist_length > 0) && + ((alg_k & (SSL_kEECDH|SSL_kECDHr|SSL_kECDHe)) || (alg_a & SSL_aECDSA))) + { + /* we are using an ECC cipher */ + size_t i; + unsigned char *list; + int found_uncompressed = 0; + list = s->session->tlsext_ecpointformatlist; + for (i = 0; i < s->session->tlsext_ecpointformatlist_length; i++) + { + if (*(list++) == TLSEXT_ECPOINTFORMAT_uncompressed) + { + found_uncompressed = 1; + break; + } + } + if (!found_uncompressed) + { + SSLerr(SSL_F_SSL_CHECK_SERVERHELLO_TLSEXT,SSL_R_TLS_INVALID_ECPOINTFORMAT_LIST); + return -1; + } + } + ret = SSL_TLSEXT_ERR_OK; +#endif /* OPENSSL_NO_EC */ + + if (s->ctx != NULL && s->ctx->tlsext_servername_callback != 0) + ret = s->ctx->tlsext_servername_callback(s, &al, s->ctx->tlsext_servername_arg); + else if (s->initial_ctx != NULL && s->initial_ctx->tlsext_servername_callback != 0) + ret = s->initial_ctx->tlsext_servername_callback(s, &al, s->initial_ctx->tlsext_servername_arg); + +#ifdef TLSEXT_TYPE_opaque_prf_input + if (s->s3->server_opaque_prf_input_len > 0) + { + /* This case may indicate that we, as a client, want to insist on using opaque PRF inputs. + * So first verify that we really have a value from the server too. */ + + if (s->s3->server_opaque_prf_input == NULL) + { + ret = SSL_TLSEXT_ERR_ALERT_FATAL; + al = SSL_AD_HANDSHAKE_FAILURE; + } + + /* Anytime the server *has* sent an opaque PRF input, we need to check + * that we have a client opaque PRF input of the same size. */ + if (s->s3->client_opaque_prf_input == NULL || + s->s3->client_opaque_prf_input_len != s->s3->server_opaque_prf_input_len) + { + ret = SSL_TLSEXT_ERR_ALERT_FATAL; + al = SSL_AD_ILLEGAL_PARAMETER; + } + } +#endif + + /* If we've requested certificate status and we wont get one + * tell the callback + */ + if ((s->tlsext_status_type != -1) && !(s->tlsext_status_expected) + && s->ctx && s->ctx->tlsext_status_cb) + { + int r; + /* Set resp to NULL, resplen to -1 so callback knows + * there is no response. + */ + if (s->tlsext_ocsp_resp) + { + OPENSSL_free(s->tlsext_ocsp_resp); + s->tlsext_ocsp_resp = NULL; + } + s->tlsext_ocsp_resplen = -1; + r = s->ctx->tlsext_status_cb(s, s->ctx->tlsext_status_arg); + if (r == 0) + { + al = SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE; + ret = SSL_TLSEXT_ERR_ALERT_FATAL; + } + if (r < 0) + { + al = SSL_AD_INTERNAL_ERROR; + ret = SSL_TLSEXT_ERR_ALERT_FATAL; + } + } + + switch (ret) + { + case SSL_TLSEXT_ERR_ALERT_FATAL: + ssl3_send_alert(s,SSL3_AL_FATAL,al); + return -1; + + case SSL_TLSEXT_ERR_ALERT_WARNING: + ssl3_send_alert(s,SSL3_AL_WARNING,al); + return 1; + + case SSL_TLSEXT_ERR_NOACK: + s->servername_done=0; + default: + return 1; + } + } + +/* Since the server cache lookup is done early on in the processing of client + * hello and other operations depend on the result we need to handle any TLS + * session ticket extension at the same time. + */ + +int tls1_process_ticket(SSL *s, unsigned char *session_id, int len, + const unsigned char *limit, SSL_SESSION **ret) + { + /* Point after session ID in client hello */ + const unsigned char *p = session_id + len; + unsigned short i; + + /* If tickets disabled behave as if no ticket present + * to permit stateful resumption. + */ + if (SSL_get_options(s) & SSL_OP_NO_TICKET) + return 1; + + if ((s->version <= SSL3_VERSION) || !limit) + return 1; + if (p >= limit) + return -1; + /* Skip past DTLS cookie */ + if (s->version == DTLS1_VERSION || s->version == DTLS1_BAD_VER) + { + i = *(p++); + p+= i; + if (p >= limit) + return -1; + } + /* Skip past cipher list */ + n2s(p, i); + p+= i; + if (p >= limit) + return -1; + /* Skip past compression algorithm list */ + i = *(p++); + p += i; + if (p > limit) + return -1; + /* Now at start of extensions */ + if ((p + 2) >= limit) + return 1; + n2s(p, i); + while ((p + 4) <= limit) + { + unsigned short type, size; + n2s(p, type); + n2s(p, size); + if (p + size > limit) + return 1; + if (type == TLSEXT_TYPE_session_ticket) + { + /* If tickets disabled indicate cache miss which will + * trigger a full handshake + */ + if (SSL_get_options(s) & SSL_OP_NO_TICKET) + return 1; + /* If zero length note client will accept a ticket + * and indicate cache miss to trigger full handshake + */ + if (size == 0) + { + s->tlsext_ticket_expected = 1; + return 0; /* Cache miss */ + } + if (s->tls_session_secret_cb) + { + /* Indicate cache miss here and instead of + * generating the session from ticket now, + * trigger abbreviated handshake based on + * external mechanism to calculate the master + * secret later. */ + return 0; + } + return tls_decrypt_ticket(s, p, size, session_id, len, + ret); + } + p += size; + } + return 1; + } + +static int tls_decrypt_ticket(SSL *s, const unsigned char *etick, int eticklen, + const unsigned char *sess_id, int sesslen, + SSL_SESSION **psess) + { + SSL_SESSION *sess; + unsigned char *sdec; + const unsigned char *p; + int slen, mlen, renew_ticket = 0; + unsigned char tick_hmac[EVP_MAX_MD_SIZE]; + HMAC_CTX hctx; + EVP_CIPHER_CTX ctx; + SSL_CTX *tctx = s->initial_ctx; + /* Need at least keyname + iv + some encrypted data */ + if (eticklen < 48) + goto tickerr; + /* Initialize session ticket encryption and HMAC contexts */ + HMAC_CTX_init(&hctx); + EVP_CIPHER_CTX_init(&ctx); + if (tctx->tlsext_ticket_key_cb) + { + unsigned char *nctick = (unsigned char *)etick; + int rv = tctx->tlsext_ticket_key_cb(s, nctick, nctick + 16, + &ctx, &hctx, 0); + if (rv < 0) + return -1; + if (rv == 0) + goto tickerr; + if (rv == 2) + renew_ticket = 1; + } + else + { + /* Check key name matches */ + if (memcmp(etick, tctx->tlsext_tick_key_name, 16)) + goto tickerr; + HMAC_Init_ex(&hctx, tctx->tlsext_tick_hmac_key, 16, + tlsext_tick_md(), NULL); + EVP_DecryptInit_ex(&ctx, EVP_aes_128_cbc(), NULL, + tctx->tlsext_tick_aes_key, etick + 16); + } + /* Attempt to process session ticket, first conduct sanity and + * integrity checks on ticket. + */ + mlen = HMAC_size(&hctx); + if (mlen < 0) + { + EVP_CIPHER_CTX_cleanup(&ctx); + return -1; + } + eticklen -= mlen; + /* Check HMAC of encrypted ticket */ + HMAC_Update(&hctx, etick, eticklen); + HMAC_Final(&hctx, tick_hmac, NULL); + HMAC_CTX_cleanup(&hctx); + if (memcmp(tick_hmac, etick + eticklen, mlen)) + goto tickerr; + /* Attempt to decrypt session data */ + /* Move p after IV to start of encrypted ticket, update length */ + p = etick + 16 + EVP_CIPHER_CTX_iv_length(&ctx); + eticklen -= 16 + EVP_CIPHER_CTX_iv_length(&ctx); + sdec = OPENSSL_malloc(eticklen); + if (!sdec) + { + EVP_CIPHER_CTX_cleanup(&ctx); + return -1; + } + EVP_DecryptUpdate(&ctx, sdec, &slen, p, eticklen); + if (EVP_DecryptFinal(&ctx, sdec + slen, &mlen) <= 0) + goto tickerr; + slen += mlen; + EVP_CIPHER_CTX_cleanup(&ctx); + p = sdec; + + sess = d2i_SSL_SESSION(NULL, &p, slen); + OPENSSL_free(sdec); + if (sess) + { + /* The session ID if non-empty is used by some clients to + * detect that the ticket has been accepted. So we copy it to + * the session structure. If it is empty set length to zero + * as required by standard. + */ + if (sesslen) + memcpy(sess->session_id, sess_id, sesslen); + sess->session_id_length = sesslen; + *psess = sess; + s->tlsext_ticket_expected = renew_ticket; + return 1; + } + /* If session decrypt failure indicate a cache miss and set state to + * send a new ticket + */ + tickerr: + s->tlsext_ticket_expected = 1; + return 0; + } + +#endif diff --git a/node-v0.8.14/deps/openssl/openssl/ssl/t1_meth.c b/node-v0.8.14/deps/openssl/openssl/ssl/t1_meth.c new file mode 100644 index 0000000..6ce7c0b --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/ssl/t1_meth.c @@ -0,0 +1,76 @@ +/* ssl/t1_meth.c */ +/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com) + * All rights reserved. + * + * This package is an SSL implementation written + * by Eric Young (eay@cryptsoft.com). + * The implementation was written so as to conform with Netscapes SSL. + * + * This library is free for commercial and non-commercial use as long as + * the following conditions are aheared to. The following conditions + * apply to all code found in this distribution, be it the RC4, RSA, + * lhash, DES, etc., code; not just the SSL code. The SSL documentation + * included with this distribution is covered by the same copyright terms + * except that the holder is Tim Hudson (tjh@cryptsoft.com). + * + * Copyright remains Eric Young's, and as such any Copyright notices in + * the code are not to be removed. + * If this package is used in a product, Eric Young should be given attribution + * as the author of the parts of the library used. + * This can be in the form of a textual message at program startup or + * in documentation (online or textual) provided with the package. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * "This product includes cryptographic software written by + * Eric Young (eay@cryptsoft.com)" + * The word 'cryptographic' can be left out if the rouines from the library + * being used are not cryptographic related :-). + * 4. If you include any Windows specific code (or a derivative thereof) from + * the apps directory (application code) you must include an acknowledgement: + * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)" + * + * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * + * The licence and distribution terms for any publically available version or + * derivative of this code cannot be changed. i.e. this code cannot simply be + * copied and put under another distribution licence + * [including the GNU Public Licence.] + */ + +#include +#include +#include "ssl_locl.h" + +static const SSL_METHOD *tls1_get_method(int ver); +static const SSL_METHOD *tls1_get_method(int ver) + { + if (ver == TLS1_VERSION) + return(TLSv1_method()); + else + return(NULL); + } + +IMPLEMENT_tls1_meth_func(TLSv1_method, + ssl3_accept, + ssl3_connect, + tls1_get_method) + diff --git a/node-v0.8.14/deps/openssl/openssl/ssl/t1_reneg.c b/node-v0.8.14/deps/openssl/openssl/ssl/t1_reneg.c new file mode 100644 index 0000000..9c2cc3c --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/ssl/t1_reneg.c @@ -0,0 +1,292 @@ +/* ssl/t1_reneg.c */ +/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com) + * All rights reserved. + * + * This package is an SSL implementation written + * by Eric Young (eay@cryptsoft.com). + * The implementation was written so as to conform with Netscapes SSL. + * + * This library is free for commercial and non-commercial use as long as + * the following conditions are aheared to. The following conditions + * apply to all code found in this distribution, be it the RC4, RSA, + * lhash, DES, etc., code; not just the SSL code. The SSL documentation + * included with this distribution is covered by the same copyright terms + * except that the holder is Tim Hudson (tjh@cryptsoft.com). + * + * Copyright remains Eric Young's, and as such any Copyright notices in + * the code are not to be removed. + * If this package is used in a product, Eric Young should be given attribution + * as the author of the parts of the library used. + * This can be in the form of a textual message at program startup or + * in documentation (online or textual) provided with the package. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * "This product includes cryptographic software written by + * Eric Young (eay@cryptsoft.com)" + * The word 'cryptographic' can be left out if the rouines from the library + * being used are not cryptographic related :-). + * 4. If you include any Windows specific code (or a derivative thereof) from + * the apps directory (application code) you must include an acknowledgement: + * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)" + * + * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * + * The licence and distribution terms for any publically available version or + * derivative of this code cannot be changed. i.e. this code cannot simply be + * copied and put under another distribution licence + * [including the GNU Public Licence.] + */ +/* ==================================================================== + * Copyright (c) 1998-2009 The OpenSSL Project. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. All advertising materials mentioning features or use of this + * software must display the following acknowledgment: + * "This product includes software developed by the OpenSSL Project + * for use in the OpenSSL Toolkit. (http://www.openssl.org/)" + * + * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to + * endorse or promote products derived from this software without + * prior written permission. For written permission, please contact + * openssl-core@openssl.org. + * + * 5. Products derived from this software may not be called "OpenSSL" + * nor may "OpenSSL" appear in their names without prior written + * permission of the OpenSSL Project. + * + * 6. Redistributions of any form whatsoever must retain the following + * acknowledgment: + * "This product includes software developed by the OpenSSL Project + * for use in the OpenSSL Toolkit (http://www.openssl.org/)" + * + * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY + * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR + * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, + * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * ==================================================================== + * + * This product includes cryptographic software written by Eric Young + * (eay@cryptsoft.com). This product includes software written by Tim + * Hudson (tjh@cryptsoft.com). + * + */ +#include +#include +#include "ssl_locl.h" + +/* Add the client's renegotiation binding */ +int ssl_add_clienthello_renegotiate_ext(SSL *s, unsigned char *p, int *len, + int maxlen) + { + if(p) + { + if((s->s3->previous_client_finished_len+1) > maxlen) + { + SSLerr(SSL_F_SSL_ADD_CLIENTHELLO_RENEGOTIATE_EXT,SSL_R_RENEGOTIATE_EXT_TOO_LONG); + return 0; + } + + /* Length byte */ + *p = s->s3->previous_client_finished_len; + p++; + + memcpy(p, s->s3->previous_client_finished, + s->s3->previous_client_finished_len); +#ifdef OPENSSL_RI_DEBUG + fprintf(stderr, "%s RI extension sent by client\n", + s->s3->previous_client_finished_len ? "Non-empty" : "Empty"); +#endif + } + + *len=s->s3->previous_client_finished_len + 1; + + + return 1; + } + +/* Parse the client's renegotiation binding and abort if it's not + right */ +int ssl_parse_clienthello_renegotiate_ext(SSL *s, unsigned char *d, int len, + int *al) + { + int ilen; + + /* Parse the length byte */ + if(len < 1) + { + SSLerr(SSL_F_SSL_PARSE_CLIENTHELLO_RENEGOTIATE_EXT,SSL_R_RENEGOTIATION_ENCODING_ERR); + *al=SSL_AD_ILLEGAL_PARAMETER; + return 0; + } + ilen = *d; + d++; + + /* Consistency check */ + if((ilen+1) != len) + { + SSLerr(SSL_F_SSL_PARSE_CLIENTHELLO_RENEGOTIATE_EXT,SSL_R_RENEGOTIATION_ENCODING_ERR); + *al=SSL_AD_ILLEGAL_PARAMETER; + return 0; + } + + /* Check that the extension matches */ + if(ilen != s->s3->previous_client_finished_len) + { + SSLerr(SSL_F_SSL_PARSE_CLIENTHELLO_RENEGOTIATE_EXT,SSL_R_RENEGOTIATION_MISMATCH); + *al=SSL_AD_HANDSHAKE_FAILURE; + return 0; + } + + if(memcmp(d, s->s3->previous_client_finished, + s->s3->previous_client_finished_len)) + { + SSLerr(SSL_F_SSL_PARSE_CLIENTHELLO_RENEGOTIATE_EXT,SSL_R_RENEGOTIATION_MISMATCH); + *al=SSL_AD_HANDSHAKE_FAILURE; + return 0; + } +#ifdef OPENSSL_RI_DEBUG + fprintf(stderr, "%s RI extension received by server\n", + ilen ? "Non-empty" : "Empty"); +#endif + + s->s3->send_connection_binding=1; + + return 1; + } + +/* Add the server's renegotiation binding */ +int ssl_add_serverhello_renegotiate_ext(SSL *s, unsigned char *p, int *len, + int maxlen) + { + if(p) + { + if((s->s3->previous_client_finished_len + + s->s3->previous_server_finished_len + 1) > maxlen) + { + SSLerr(SSL_F_SSL_ADD_SERVERHELLO_RENEGOTIATE_EXT,SSL_R_RENEGOTIATE_EXT_TOO_LONG); + return 0; + } + + /* Length byte */ + *p = s->s3->previous_client_finished_len + s->s3->previous_server_finished_len; + p++; + + memcpy(p, s->s3->previous_client_finished, + s->s3->previous_client_finished_len); + p += s->s3->previous_client_finished_len; + + memcpy(p, s->s3->previous_server_finished, + s->s3->previous_server_finished_len); +#ifdef OPENSSL_RI_DEBUG + fprintf(stderr, "%s RI extension sent by server\n", + s->s3->previous_client_finished_len ? "Non-empty" : "Empty"); +#endif + } + + *len=s->s3->previous_client_finished_len + + s->s3->previous_server_finished_len + 1; + + return 1; + } + +/* Parse the server's renegotiation binding and abort if it's not + right */ +int ssl_parse_serverhello_renegotiate_ext(SSL *s, unsigned char *d, int len, + int *al) + { + int expected_len=s->s3->previous_client_finished_len + + s->s3->previous_server_finished_len; + int ilen; + + /* Check for logic errors */ + OPENSSL_assert(!expected_len || s->s3->previous_client_finished_len); + OPENSSL_assert(!expected_len || s->s3->previous_server_finished_len); + + /* Parse the length byte */ + if(len < 1) + { + SSLerr(SSL_F_SSL_PARSE_SERVERHELLO_RENEGOTIATE_EXT,SSL_R_RENEGOTIATION_ENCODING_ERR); + *al=SSL_AD_ILLEGAL_PARAMETER; + return 0; + } + ilen = *d; + d++; + + /* Consistency check */ + if(ilen+1 != len) + { + SSLerr(SSL_F_SSL_PARSE_SERVERHELLO_RENEGOTIATE_EXT,SSL_R_RENEGOTIATION_ENCODING_ERR); + *al=SSL_AD_ILLEGAL_PARAMETER; + return 0; + } + + /* Check that the extension matches */ + if(ilen != expected_len) + { + SSLerr(SSL_F_SSL_PARSE_SERVERHELLO_RENEGOTIATE_EXT,SSL_R_RENEGOTIATION_MISMATCH); + *al=SSL_AD_HANDSHAKE_FAILURE; + return 0; + } + + if(memcmp(d, s->s3->previous_client_finished, + s->s3->previous_client_finished_len)) + { + SSLerr(SSL_F_SSL_PARSE_SERVERHELLO_RENEGOTIATE_EXT,SSL_R_RENEGOTIATION_MISMATCH); + *al=SSL_AD_HANDSHAKE_FAILURE; + return 0; + } + d += s->s3->previous_client_finished_len; + + if(memcmp(d, s->s3->previous_server_finished, + s->s3->previous_server_finished_len)) + { + SSLerr(SSL_F_SSL_PARSE_SERVERHELLO_RENEGOTIATE_EXT,SSL_R_RENEGOTIATION_MISMATCH); + *al=SSL_AD_ILLEGAL_PARAMETER; + return 0; + } +#ifdef OPENSSL_RI_DEBUG + fprintf(stderr, "%s RI extension received by client\n", + ilen ? "Non-empty" : "Empty"); +#endif + s->s3->send_connection_binding=1; + + return 1; + } diff --git a/node-v0.8.14/deps/openssl/openssl/ssl/t1_srvr.c b/node-v0.8.14/deps/openssl/openssl/ssl/t1_srvr.c new file mode 100644 index 0000000..42525e9 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/ssl/t1_srvr.c @@ -0,0 +1,80 @@ +/* ssl/t1_srvr.c */ +/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com) + * All rights reserved. + * + * This package is an SSL implementation written + * by Eric Young (eay@cryptsoft.com). + * The implementation was written so as to conform with Netscapes SSL. + * + * This library is free for commercial and non-commercial use as long as + * the following conditions are aheared to. The following conditions + * apply to all code found in this distribution, be it the RC4, RSA, + * lhash, DES, etc., code; not just the SSL code. The SSL documentation + * included with this distribution is covered by the same copyright terms + * except that the holder is Tim Hudson (tjh@cryptsoft.com). + * + * Copyright remains Eric Young's, and as such any Copyright notices in + * the code are not to be removed. + * If this package is used in a product, Eric Young should be given attribution + * as the author of the parts of the library used. + * This can be in the form of a textual message at program startup or + * in documentation (online or textual) provided with the package. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * "This product includes cryptographic software written by + * Eric Young (eay@cryptsoft.com)" + * The word 'cryptographic' can be left out if the rouines from the library + * being used are not cryptographic related :-). + * 4. If you include any Windows specific code (or a derivative thereof) from + * the apps directory (application code) you must include an acknowledgement: + * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)" + * + * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * + * The licence and distribution terms for any publically available version or + * derivative of this code cannot be changed. i.e. this code cannot simply be + * copied and put under another distribution licence + * [including the GNU Public Licence.] + */ + +#include +#include "ssl_locl.h" +#include +#include +#include +#include +#include + +static const SSL_METHOD *tls1_get_server_method(int ver); +static const SSL_METHOD *tls1_get_server_method(int ver) + { + if (ver == TLS1_VERSION) + return(TLSv1_server_method()); + else + return(NULL); + } + +IMPLEMENT_tls1_meth_func(TLSv1_server_method, + ssl3_accept, + ssl_undefined_function, + tls1_get_server_method) + diff --git a/node-v0.8.14/deps/openssl/openssl/ssl/tls1.h b/node-v0.8.14/deps/openssl/openssl/ssl/tls1.h new file mode 100644 index 0000000..71f9722 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/ssl/tls1.h @@ -0,0 +1,540 @@ +/* ssl/tls1.h */ +/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com) + * All rights reserved. + * + * This package is an SSL implementation written + * by Eric Young (eay@cryptsoft.com). + * The implementation was written so as to conform with Netscapes SSL. + * + * This library is free for commercial and non-commercial use as long as + * the following conditions are aheared to. The following conditions + * apply to all code found in this distribution, be it the RC4, RSA, + * lhash, DES, etc., code; not just the SSL code. The SSL documentation + * included with this distribution is covered by the same copyright terms + * except that the holder is Tim Hudson (tjh@cryptsoft.com). + * + * Copyright remains Eric Young's, and as such any Copyright notices in + * the code are not to be removed. + * If this package is used in a product, Eric Young should be given attribution + * as the author of the parts of the library used. + * This can be in the form of a textual message at program startup or + * in documentation (online or textual) provided with the package. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * "This product includes cryptographic software written by + * Eric Young (eay@cryptsoft.com)" + * The word 'cryptographic' can be left out if the rouines from the library + * being used are not cryptographic related :-). + * 4. If you include any Windows specific code (or a derivative thereof) from + * the apps directory (application code) you must include an acknowledgement: + * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)" + * + * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * + * The licence and distribution terms for any publically available version or + * derivative of this code cannot be changed. i.e. this code cannot simply be + * copied and put under another distribution licence + * [including the GNU Public Licence.] + */ +/* ==================================================================== + * Copyright (c) 1998-2006 The OpenSSL Project. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. All advertising materials mentioning features or use of this + * software must display the following acknowledgment: + * "This product includes software developed by the OpenSSL Project + * for use in the OpenSSL Toolkit. (http://www.openssl.org/)" + * + * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to + * endorse or promote products derived from this software without + * prior written permission. For written permission, please contact + * openssl-core@openssl.org. + * + * 5. Products derived from this software may not be called "OpenSSL" + * nor may "OpenSSL" appear in their names without prior written + * permission of the OpenSSL Project. + * + * 6. Redistributions of any form whatsoever must retain the following + * acknowledgment: + * "This product includes software developed by the OpenSSL Project + * for use in the OpenSSL Toolkit (http://www.openssl.org/)" + * + * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY + * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR + * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, + * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * ==================================================================== + * + * This product includes cryptographic software written by Eric Young + * (eay@cryptsoft.com). This product includes software written by Tim + * Hudson (tjh@cryptsoft.com). + * + */ +/* ==================================================================== + * Copyright 2002 Sun Microsystems, Inc. ALL RIGHTS RESERVED. + * + * Portions of the attached software ("Contribution") are developed by + * SUN MICROSYSTEMS, INC., and are contributed to the OpenSSL project. + * + * The Contribution is licensed pursuant to the OpenSSL open source + * license provided above. + * + * ECC cipher suite support in OpenSSL originally written by + * Vipul Gupta and Sumit Gupta of Sun Microsystems Laboratories. + * + */ +/* ==================================================================== + * Copyright 2005 Nokia. All rights reserved. + * + * The portions of the attached software ("Contribution") is developed by + * Nokia Corporation and is licensed pursuant to the OpenSSL open source + * license. + * + * The Contribution, originally written by Mika Kousa and Pasi Eronen of + * Nokia Corporation, consists of the "PSK" (Pre-Shared Key) ciphersuites + * support (see RFC 4279) to OpenSSL. + * + * No patent licenses or other rights except those expressly stated in + * the OpenSSL open source license shall be deemed granted or received + * expressly, by implication, estoppel, or otherwise. + * + * No assurances are provided by Nokia that the Contribution does not + * infringe the patent or other intellectual property rights of any third + * party or that the license provides you with all the necessary rights + * to make use of the Contribution. + * + * THE SOFTWARE IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND. IN + * ADDITION TO THE DISCLAIMERS INCLUDED IN THE LICENSE, NOKIA + * SPECIFICALLY DISCLAIMS ANY LIABILITY FOR CLAIMS BROUGHT BY YOU OR ANY + * OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL PROPERTY RIGHTS OR + * OTHERWISE. + */ + +#ifndef HEADER_TLS1_H +#define HEADER_TLS1_H + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +#define TLS1_ALLOW_EXPERIMENTAL_CIPHERSUITES 0 + +#define TLS1_VERSION 0x0301 +#define TLS1_VERSION_MAJOR 0x03 +#define TLS1_VERSION_MINOR 0x01 + +#define TLS1_AD_DECRYPTION_FAILED 21 +#define TLS1_AD_RECORD_OVERFLOW 22 +#define TLS1_AD_UNKNOWN_CA 48 /* fatal */ +#define TLS1_AD_ACCESS_DENIED 49 /* fatal */ +#define TLS1_AD_DECODE_ERROR 50 /* fatal */ +#define TLS1_AD_DECRYPT_ERROR 51 +#define TLS1_AD_EXPORT_RESTRICTION 60 /* fatal */ +#define TLS1_AD_PROTOCOL_VERSION 70 /* fatal */ +#define TLS1_AD_INSUFFICIENT_SECURITY 71 /* fatal */ +#define TLS1_AD_INTERNAL_ERROR 80 /* fatal */ +#define TLS1_AD_USER_CANCELLED 90 +#define TLS1_AD_NO_RENEGOTIATION 100 +/* codes 110-114 are from RFC3546 */ +#define TLS1_AD_UNSUPPORTED_EXTENSION 110 +#define TLS1_AD_CERTIFICATE_UNOBTAINABLE 111 +#define TLS1_AD_UNRECOGNIZED_NAME 112 +#define TLS1_AD_BAD_CERTIFICATE_STATUS_RESPONSE 113 +#define TLS1_AD_BAD_CERTIFICATE_HASH_VALUE 114 +#define TLS1_AD_UNKNOWN_PSK_IDENTITY 115 /* fatal */ + +/* ExtensionType values from RFC3546 / RFC4366 */ +#define TLSEXT_TYPE_server_name 0 +#define TLSEXT_TYPE_max_fragment_length 1 +#define TLSEXT_TYPE_client_certificate_url 2 +#define TLSEXT_TYPE_trusted_ca_keys 3 +#define TLSEXT_TYPE_truncated_hmac 4 +#define TLSEXT_TYPE_status_request 5 +/* ExtensionType values from RFC4492 */ +#define TLSEXT_TYPE_elliptic_curves 10 +#define TLSEXT_TYPE_ec_point_formats 11 +#define TLSEXT_TYPE_session_ticket 35 +/* ExtensionType value from draft-rescorla-tls-opaque-prf-input-00.txt */ +#if 0 /* will have to be provided externally for now , + * i.e. build with -DTLSEXT_TYPE_opaque_prf_input=38183 + * using whatever extension number you'd like to try */ +# define TLSEXT_TYPE_opaque_prf_input ?? */ +#endif + +/* Temporary extension type */ +#define TLSEXT_TYPE_renegotiate 0xff01 + +#ifndef OPENSSL_NO_NEXTPROTONEG +/* This is not an IANA defined extension number */ +#define TLSEXT_TYPE_next_proto_neg 13172 +#endif + +/* NameType value from RFC 3546 */ +#define TLSEXT_NAMETYPE_host_name 0 +/* status request value from RFC 3546 */ +#define TLSEXT_STATUSTYPE_ocsp 1 + +/* ECPointFormat values from draft-ietf-tls-ecc-12 */ +#define TLSEXT_ECPOINTFORMAT_first 0 +#define TLSEXT_ECPOINTFORMAT_uncompressed 0 +#define TLSEXT_ECPOINTFORMAT_ansiX962_compressed_prime 1 +#define TLSEXT_ECPOINTFORMAT_ansiX962_compressed_char2 2 +#define TLSEXT_ECPOINTFORMAT_last 2 + +#ifndef OPENSSL_NO_TLSEXT + +#define TLSEXT_MAXLEN_host_name 255 + +const char *SSL_get_servername(const SSL *s, const int type) ; +int SSL_get_servername_type(const SSL *s) ; +int SSL_export_keying_material(SSL *s, unsigned char *out, size_t olen, + const char *label, size_t llen, const unsigned char *p, size_t plen, + int use_context); + +#define SSL_set_tlsext_host_name(s,name) \ +SSL_ctrl(s,SSL_CTRL_SET_TLSEXT_HOSTNAME,TLSEXT_NAMETYPE_host_name,(char *)name) + +#define SSL_set_tlsext_debug_callback(ssl, cb) \ +SSL_callback_ctrl(ssl,SSL_CTRL_SET_TLSEXT_DEBUG_CB,(void (*)(void))cb) + +#define SSL_set_tlsext_debug_arg(ssl, arg) \ +SSL_ctrl(ssl,SSL_CTRL_SET_TLSEXT_DEBUG_ARG,0, (void *)arg) + +#define SSL_set_tlsext_status_type(ssl, type) \ +SSL_ctrl(ssl,SSL_CTRL_SET_TLSEXT_STATUS_REQ_TYPE,type, NULL) + +#define SSL_get_tlsext_status_exts(ssl, arg) \ +SSL_ctrl(ssl,SSL_CTRL_GET_TLSEXT_STATUS_REQ_EXTS,0, (void *)arg) + +#define SSL_set_tlsext_status_exts(ssl, arg) \ +SSL_ctrl(ssl,SSL_CTRL_SET_TLSEXT_STATUS_REQ_EXTS,0, (void *)arg) + +#define SSL_get_tlsext_status_ids(ssl, arg) \ +SSL_ctrl(ssl,SSL_CTRL_GET_TLSEXT_STATUS_REQ_IDS,0, (void *)arg) + +#define SSL_set_tlsext_status_ids(ssl, arg) \ +SSL_ctrl(ssl,SSL_CTRL_SET_TLSEXT_STATUS_REQ_IDS,0, (void *)arg) + +#define SSL_get_tlsext_status_ocsp_resp(ssl, arg) \ +SSL_ctrl(ssl,SSL_CTRL_GET_TLSEXT_STATUS_REQ_OCSP_RESP,0, (void *)arg) + +#define SSL_set_tlsext_status_ocsp_resp(ssl, arg, arglen) \ +SSL_ctrl(ssl,SSL_CTRL_SET_TLSEXT_STATUS_REQ_OCSP_RESP,arglen, (void *)arg) + +#define SSL_CTX_set_tlsext_servername_callback(ctx, cb) \ +SSL_CTX_callback_ctrl(ctx,SSL_CTRL_SET_TLSEXT_SERVERNAME_CB,(void (*)(void))cb) + +#define SSL_TLSEXT_ERR_OK 0 +#define SSL_TLSEXT_ERR_ALERT_WARNING 1 +#define SSL_TLSEXT_ERR_ALERT_FATAL 2 +#define SSL_TLSEXT_ERR_NOACK 3 + +#define SSL_CTX_set_tlsext_servername_arg(ctx, arg) \ +SSL_CTX_ctrl(ctx,SSL_CTRL_SET_TLSEXT_SERVERNAME_ARG,0, (void *)arg) + +#define SSL_CTX_get_tlsext_ticket_keys(ctx, keys, keylen) \ + SSL_CTX_ctrl((ctx),SSL_CTRL_GET_TLSEXT_TICKET_KEYS,(keylen),(keys)) +#define SSL_CTX_set_tlsext_ticket_keys(ctx, keys, keylen) \ + SSL_CTX_ctrl((ctx),SSL_CTRL_SET_TLSEXT_TICKET_KEYS,(keylen),(keys)) + +#define SSL_CTX_set_tlsext_status_cb(ssl, cb) \ +SSL_CTX_callback_ctrl(ssl,SSL_CTRL_SET_TLSEXT_STATUS_REQ_CB,(void (*)(void))cb) + +#define SSL_CTX_set_tlsext_status_arg(ssl, arg) \ +SSL_CTX_ctrl(ssl,SSL_CTRL_SET_TLSEXT_STATUS_REQ_CB_ARG,0, (void *)arg) + +#define SSL_set_tlsext_opaque_prf_input(s, src, len) \ +SSL_ctrl(s,SSL_CTRL_SET_TLSEXT_OPAQUE_PRF_INPUT, len, src) +#define SSL_CTX_set_tlsext_opaque_prf_input_callback(ctx, cb) \ +SSL_CTX_callback_ctrl(ctx,SSL_CTRL_SET_TLSEXT_OPAQUE_PRF_INPUT_CB, (void (*)(void))cb) +#define SSL_CTX_set_tlsext_opaque_prf_input_callback_arg(ctx, arg) \ +SSL_CTX_ctrl(ctx,SSL_CTRL_SET_TLSEXT_OPAQUE_PRF_INPUT_CB_ARG, 0, arg) + +#define SSL_CTX_set_tlsext_ticket_key_cb(ssl, cb) \ +SSL_CTX_callback_ctrl(ssl,SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB,(void (*)(void))cb) + +#endif + +/* PSK ciphersuites from 4279 */ +#define TLS1_CK_PSK_WITH_RC4_128_SHA 0x0300008A +#define TLS1_CK_PSK_WITH_3DES_EDE_CBC_SHA 0x0300008B +#define TLS1_CK_PSK_WITH_AES_128_CBC_SHA 0x0300008C +#define TLS1_CK_PSK_WITH_AES_256_CBC_SHA 0x0300008D + +/* Additional TLS ciphersuites from expired Internet Draft + * draft-ietf-tls-56-bit-ciphersuites-01.txt + * (available if TLS1_ALLOW_EXPERIMENTAL_CIPHERSUITES is defined, see + * s3_lib.c). We actually treat them like SSL 3.0 ciphers, which we probably + * shouldn't. Note that the first two are actually not in the IDs. */ +#define TLS1_CK_RSA_EXPORT1024_WITH_RC4_56_MD5 0x03000060 /* not in ID */ +#define TLS1_CK_RSA_EXPORT1024_WITH_RC2_CBC_56_MD5 0x03000061 /* not in ID */ +#define TLS1_CK_RSA_EXPORT1024_WITH_DES_CBC_SHA 0x03000062 +#define TLS1_CK_DHE_DSS_EXPORT1024_WITH_DES_CBC_SHA 0x03000063 +#define TLS1_CK_RSA_EXPORT1024_WITH_RC4_56_SHA 0x03000064 +#define TLS1_CK_DHE_DSS_EXPORT1024_WITH_RC4_56_SHA 0x03000065 +#define TLS1_CK_DHE_DSS_WITH_RC4_128_SHA 0x03000066 + +/* AES ciphersuites from RFC3268 */ + +#define TLS1_CK_RSA_WITH_AES_128_SHA 0x0300002F +#define TLS1_CK_DH_DSS_WITH_AES_128_SHA 0x03000030 +#define TLS1_CK_DH_RSA_WITH_AES_128_SHA 0x03000031 +#define TLS1_CK_DHE_DSS_WITH_AES_128_SHA 0x03000032 +#define TLS1_CK_DHE_RSA_WITH_AES_128_SHA 0x03000033 +#define TLS1_CK_ADH_WITH_AES_128_SHA 0x03000034 + +#define TLS1_CK_RSA_WITH_AES_256_SHA 0x03000035 +#define TLS1_CK_DH_DSS_WITH_AES_256_SHA 0x03000036 +#define TLS1_CK_DH_RSA_WITH_AES_256_SHA 0x03000037 +#define TLS1_CK_DHE_DSS_WITH_AES_256_SHA 0x03000038 +#define TLS1_CK_DHE_RSA_WITH_AES_256_SHA 0x03000039 +#define TLS1_CK_ADH_WITH_AES_256_SHA 0x0300003A + +/* Camellia ciphersuites from RFC4132 */ +#define TLS1_CK_RSA_WITH_CAMELLIA_128_CBC_SHA 0x03000041 +#define TLS1_CK_DH_DSS_WITH_CAMELLIA_128_CBC_SHA 0x03000042 +#define TLS1_CK_DH_RSA_WITH_CAMELLIA_128_CBC_SHA 0x03000043 +#define TLS1_CK_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA 0x03000044 +#define TLS1_CK_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA 0x03000045 +#define TLS1_CK_ADH_WITH_CAMELLIA_128_CBC_SHA 0x03000046 + +#define TLS1_CK_RSA_WITH_CAMELLIA_256_CBC_SHA 0x03000084 +#define TLS1_CK_DH_DSS_WITH_CAMELLIA_256_CBC_SHA 0x03000085 +#define TLS1_CK_DH_RSA_WITH_CAMELLIA_256_CBC_SHA 0x03000086 +#define TLS1_CK_DHE_DSS_WITH_CAMELLIA_256_CBC_SHA 0x03000087 +#define TLS1_CK_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA 0x03000088 +#define TLS1_CK_ADH_WITH_CAMELLIA_256_CBC_SHA 0x03000089 + +/* SEED ciphersuites from RFC4162 */ +#define TLS1_CK_RSA_WITH_SEED_SHA 0x03000096 +#define TLS1_CK_DH_DSS_WITH_SEED_SHA 0x03000097 +#define TLS1_CK_DH_RSA_WITH_SEED_SHA 0x03000098 +#define TLS1_CK_DHE_DSS_WITH_SEED_SHA 0x03000099 +#define TLS1_CK_DHE_RSA_WITH_SEED_SHA 0x0300009A +#define TLS1_CK_ADH_WITH_SEED_SHA 0x0300009B + +/* ECC ciphersuites from draft-ietf-tls-ecc-12.txt with changes soon to be in draft 13 */ +#define TLS1_CK_ECDH_ECDSA_WITH_NULL_SHA 0x0300C001 +#define TLS1_CK_ECDH_ECDSA_WITH_RC4_128_SHA 0x0300C002 +#define TLS1_CK_ECDH_ECDSA_WITH_DES_192_CBC3_SHA 0x0300C003 +#define TLS1_CK_ECDH_ECDSA_WITH_AES_128_CBC_SHA 0x0300C004 +#define TLS1_CK_ECDH_ECDSA_WITH_AES_256_CBC_SHA 0x0300C005 + +#define TLS1_CK_ECDHE_ECDSA_WITH_NULL_SHA 0x0300C006 +#define TLS1_CK_ECDHE_ECDSA_WITH_RC4_128_SHA 0x0300C007 +#define TLS1_CK_ECDHE_ECDSA_WITH_DES_192_CBC3_SHA 0x0300C008 +#define TLS1_CK_ECDHE_ECDSA_WITH_AES_128_CBC_SHA 0x0300C009 +#define TLS1_CK_ECDHE_ECDSA_WITH_AES_256_CBC_SHA 0x0300C00A + +#define TLS1_CK_ECDH_RSA_WITH_NULL_SHA 0x0300C00B +#define TLS1_CK_ECDH_RSA_WITH_RC4_128_SHA 0x0300C00C +#define TLS1_CK_ECDH_RSA_WITH_DES_192_CBC3_SHA 0x0300C00D +#define TLS1_CK_ECDH_RSA_WITH_AES_128_CBC_SHA 0x0300C00E +#define TLS1_CK_ECDH_RSA_WITH_AES_256_CBC_SHA 0x0300C00F + +#define TLS1_CK_ECDHE_RSA_WITH_NULL_SHA 0x0300C010 +#define TLS1_CK_ECDHE_RSA_WITH_RC4_128_SHA 0x0300C011 +#define TLS1_CK_ECDHE_RSA_WITH_DES_192_CBC3_SHA 0x0300C012 +#define TLS1_CK_ECDHE_RSA_WITH_AES_128_CBC_SHA 0x0300C013 +#define TLS1_CK_ECDHE_RSA_WITH_AES_256_CBC_SHA 0x0300C014 + +#define TLS1_CK_ECDH_anon_WITH_NULL_SHA 0x0300C015 +#define TLS1_CK_ECDH_anon_WITH_RC4_128_SHA 0x0300C016 +#define TLS1_CK_ECDH_anon_WITH_DES_192_CBC3_SHA 0x0300C017 +#define TLS1_CK_ECDH_anon_WITH_AES_128_CBC_SHA 0x0300C018 +#define TLS1_CK_ECDH_anon_WITH_AES_256_CBC_SHA 0x0300C019 + +/* XXX + * Inconsistency alert: + * The OpenSSL names of ciphers with ephemeral DH here include the string + * "DHE", while elsewhere it has always been "EDH". + * (The alias for the list of all such ciphers also is "EDH".) + * The specifications speak of "EDH"; maybe we should allow both forms + * for everything. */ +#define TLS1_TXT_RSA_EXPORT1024_WITH_RC4_56_MD5 "EXP1024-RC4-MD5" +#define TLS1_TXT_RSA_EXPORT1024_WITH_RC2_CBC_56_MD5 "EXP1024-RC2-CBC-MD5" +#define TLS1_TXT_RSA_EXPORT1024_WITH_DES_CBC_SHA "EXP1024-DES-CBC-SHA" +#define TLS1_TXT_DHE_DSS_EXPORT1024_WITH_DES_CBC_SHA "EXP1024-DHE-DSS-DES-CBC-SHA" +#define TLS1_TXT_RSA_EXPORT1024_WITH_RC4_56_SHA "EXP1024-RC4-SHA" +#define TLS1_TXT_DHE_DSS_EXPORT1024_WITH_RC4_56_SHA "EXP1024-DHE-DSS-RC4-SHA" +#define TLS1_TXT_DHE_DSS_WITH_RC4_128_SHA "DHE-DSS-RC4-SHA" + +/* AES ciphersuites from RFC3268 */ +#define TLS1_TXT_RSA_WITH_AES_128_SHA "AES128-SHA" +#define TLS1_TXT_DH_DSS_WITH_AES_128_SHA "DH-DSS-AES128-SHA" +#define TLS1_TXT_DH_RSA_WITH_AES_128_SHA "DH-RSA-AES128-SHA" +#define TLS1_TXT_DHE_DSS_WITH_AES_128_SHA "DHE-DSS-AES128-SHA" +#define TLS1_TXT_DHE_RSA_WITH_AES_128_SHA "DHE-RSA-AES128-SHA" +#define TLS1_TXT_ADH_WITH_AES_128_SHA "ADH-AES128-SHA" + +#define TLS1_TXT_RSA_WITH_AES_256_SHA "AES256-SHA" +#define TLS1_TXT_DH_DSS_WITH_AES_256_SHA "DH-DSS-AES256-SHA" +#define TLS1_TXT_DH_RSA_WITH_AES_256_SHA "DH-RSA-AES256-SHA" +#define TLS1_TXT_DHE_DSS_WITH_AES_256_SHA "DHE-DSS-AES256-SHA" +#define TLS1_TXT_DHE_RSA_WITH_AES_256_SHA "DHE-RSA-AES256-SHA" +#define TLS1_TXT_ADH_WITH_AES_256_SHA "ADH-AES256-SHA" + +/* ECC ciphersuites from draft-ietf-tls-ecc-01.txt (Mar 15, 2001) */ +#define TLS1_TXT_ECDH_ECDSA_WITH_NULL_SHA "ECDH-ECDSA-NULL-SHA" +#define TLS1_TXT_ECDH_ECDSA_WITH_RC4_128_SHA "ECDH-ECDSA-RC4-SHA" +#define TLS1_TXT_ECDH_ECDSA_WITH_DES_192_CBC3_SHA "ECDH-ECDSA-DES-CBC3-SHA" +#define TLS1_TXT_ECDH_ECDSA_WITH_AES_128_CBC_SHA "ECDH-ECDSA-AES128-SHA" +#define TLS1_TXT_ECDH_ECDSA_WITH_AES_256_CBC_SHA "ECDH-ECDSA-AES256-SHA" + +#define TLS1_TXT_ECDHE_ECDSA_WITH_NULL_SHA "ECDHE-ECDSA-NULL-SHA" +#define TLS1_TXT_ECDHE_ECDSA_WITH_RC4_128_SHA "ECDHE-ECDSA-RC4-SHA" +#define TLS1_TXT_ECDHE_ECDSA_WITH_DES_192_CBC3_SHA "ECDHE-ECDSA-DES-CBC3-SHA" +#define TLS1_TXT_ECDHE_ECDSA_WITH_AES_128_CBC_SHA "ECDHE-ECDSA-AES128-SHA" +#define TLS1_TXT_ECDHE_ECDSA_WITH_AES_256_CBC_SHA "ECDHE-ECDSA-AES256-SHA" + +#define TLS1_TXT_ECDH_RSA_WITH_NULL_SHA "ECDH-RSA-NULL-SHA" +#define TLS1_TXT_ECDH_RSA_WITH_RC4_128_SHA "ECDH-RSA-RC4-SHA" +#define TLS1_TXT_ECDH_RSA_WITH_DES_192_CBC3_SHA "ECDH-RSA-DES-CBC3-SHA" +#define TLS1_TXT_ECDH_RSA_WITH_AES_128_CBC_SHA "ECDH-RSA-AES128-SHA" +#define TLS1_TXT_ECDH_RSA_WITH_AES_256_CBC_SHA "ECDH-RSA-AES256-SHA" + +#define TLS1_TXT_ECDHE_RSA_WITH_NULL_SHA "ECDHE-RSA-NULL-SHA" +#define TLS1_TXT_ECDHE_RSA_WITH_RC4_128_SHA "ECDHE-RSA-RC4-SHA" +#define TLS1_TXT_ECDHE_RSA_WITH_DES_192_CBC3_SHA "ECDHE-RSA-DES-CBC3-SHA" +#define TLS1_TXT_ECDHE_RSA_WITH_AES_128_CBC_SHA "ECDHE-RSA-AES128-SHA" +#define TLS1_TXT_ECDHE_RSA_WITH_AES_256_CBC_SHA "ECDHE-RSA-AES256-SHA" + +#define TLS1_TXT_ECDH_anon_WITH_NULL_SHA "AECDH-NULL-SHA" +#define TLS1_TXT_ECDH_anon_WITH_RC4_128_SHA "AECDH-RC4-SHA" +#define TLS1_TXT_ECDH_anon_WITH_DES_192_CBC3_SHA "AECDH-DES-CBC3-SHA" +#define TLS1_TXT_ECDH_anon_WITH_AES_128_CBC_SHA "AECDH-AES128-SHA" +#define TLS1_TXT_ECDH_anon_WITH_AES_256_CBC_SHA "AECDH-AES256-SHA" + +/* PSK ciphersuites from RFC 4279 */ +#define TLS1_TXT_PSK_WITH_RC4_128_SHA "PSK-RC4-SHA" +#define TLS1_TXT_PSK_WITH_3DES_EDE_CBC_SHA "PSK-3DES-EDE-CBC-SHA" +#define TLS1_TXT_PSK_WITH_AES_128_CBC_SHA "PSK-AES128-CBC-SHA" +#define TLS1_TXT_PSK_WITH_AES_256_CBC_SHA "PSK-AES256-CBC-SHA" + +/* Camellia ciphersuites from RFC4132 */ +#define TLS1_TXT_RSA_WITH_CAMELLIA_128_CBC_SHA "CAMELLIA128-SHA" +#define TLS1_TXT_DH_DSS_WITH_CAMELLIA_128_CBC_SHA "DH-DSS-CAMELLIA128-SHA" +#define TLS1_TXT_DH_RSA_WITH_CAMELLIA_128_CBC_SHA "DH-RSA-CAMELLIA128-SHA" +#define TLS1_TXT_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA "DHE-DSS-CAMELLIA128-SHA" +#define TLS1_TXT_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA "DHE-RSA-CAMELLIA128-SHA" +#define TLS1_TXT_ADH_WITH_CAMELLIA_128_CBC_SHA "ADH-CAMELLIA128-SHA" + +#define TLS1_TXT_RSA_WITH_CAMELLIA_256_CBC_SHA "CAMELLIA256-SHA" +#define TLS1_TXT_DH_DSS_WITH_CAMELLIA_256_CBC_SHA "DH-DSS-CAMELLIA256-SHA" +#define TLS1_TXT_DH_RSA_WITH_CAMELLIA_256_CBC_SHA "DH-RSA-CAMELLIA256-SHA" +#define TLS1_TXT_DHE_DSS_WITH_CAMELLIA_256_CBC_SHA "DHE-DSS-CAMELLIA256-SHA" +#define TLS1_TXT_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA "DHE-RSA-CAMELLIA256-SHA" +#define TLS1_TXT_ADH_WITH_CAMELLIA_256_CBC_SHA "ADH-CAMELLIA256-SHA" + +/* SEED ciphersuites from RFC4162 */ +#define TLS1_TXT_RSA_WITH_SEED_SHA "SEED-SHA" +#define TLS1_TXT_DH_DSS_WITH_SEED_SHA "DH-DSS-SEED-SHA" +#define TLS1_TXT_DH_RSA_WITH_SEED_SHA "DH-RSA-SEED-SHA" +#define TLS1_TXT_DHE_DSS_WITH_SEED_SHA "DHE-DSS-SEED-SHA" +#define TLS1_TXT_DHE_RSA_WITH_SEED_SHA "DHE-RSA-SEED-SHA" +#define TLS1_TXT_ADH_WITH_SEED_SHA "ADH-SEED-SHA" + + +#define TLS_CT_RSA_SIGN 1 +#define TLS_CT_DSS_SIGN 2 +#define TLS_CT_RSA_FIXED_DH 3 +#define TLS_CT_DSS_FIXED_DH 4 +#define TLS_CT_ECDSA_SIGN 64 +#define TLS_CT_RSA_FIXED_ECDH 65 +#define TLS_CT_ECDSA_FIXED_ECDH 66 +#define TLS_CT_GOST94_SIGN 21 +#define TLS_CT_GOST01_SIGN 22 +/* when correcting this number, correct also SSL3_CT_NUMBER in ssl3.h (see + * comment there) */ +#define TLS_CT_NUMBER 9 + +#define TLS1_FINISH_MAC_LENGTH 12 + +#define TLS_MD_MAX_CONST_SIZE 20 +#define TLS_MD_CLIENT_FINISH_CONST "client finished" +#define TLS_MD_CLIENT_FINISH_CONST_SIZE 15 +#define TLS_MD_SERVER_FINISH_CONST "server finished" +#define TLS_MD_SERVER_FINISH_CONST_SIZE 15 +#define TLS_MD_SERVER_WRITE_KEY_CONST "server write key" +#define TLS_MD_SERVER_WRITE_KEY_CONST_SIZE 16 +#define TLS_MD_KEY_EXPANSION_CONST "key expansion" +#define TLS_MD_KEY_EXPANSION_CONST_SIZE 13 +#define TLS_MD_CLIENT_WRITE_KEY_CONST "client write key" +#define TLS_MD_CLIENT_WRITE_KEY_CONST_SIZE 16 +#define TLS_MD_SERVER_WRITE_KEY_CONST "server write key" +#define TLS_MD_SERVER_WRITE_KEY_CONST_SIZE 16 +#define TLS_MD_IV_BLOCK_CONST "IV block" +#define TLS_MD_IV_BLOCK_CONST_SIZE 8 +#define TLS_MD_MASTER_SECRET_CONST "master secret" +#define TLS_MD_MASTER_SECRET_CONST_SIZE 13 + +#ifdef CHARSET_EBCDIC +#undef TLS_MD_CLIENT_FINISH_CONST +#define TLS_MD_CLIENT_FINISH_CONST "\x63\x6c\x69\x65\x6e\x74\x20\x66\x69\x6e\x69\x73\x68\x65\x64" /*client finished*/ +#undef TLS_MD_SERVER_FINISH_CONST +#define TLS_MD_SERVER_FINISH_CONST "\x73\x65\x72\x76\x65\x72\x20\x66\x69\x6e\x69\x73\x68\x65\x64" /*server finished*/ +#undef TLS_MD_SERVER_WRITE_KEY_CONST +#define TLS_MD_SERVER_WRITE_KEY_CONST "\x73\x65\x72\x76\x65\x72\x20\x77\x72\x69\x74\x65\x20\x6b\x65\x79" /*server write key*/ +#undef TLS_MD_KEY_EXPANSION_CONST +#define TLS_MD_KEY_EXPANSION_CONST "\x6b\x65\x79\x20\x65\x78\x70\x61\x6e\x73\x69\x6f\x6e" /*key expansion*/ +#undef TLS_MD_CLIENT_WRITE_KEY_CONST +#define TLS_MD_CLIENT_WRITE_KEY_CONST "\x63\x6c\x69\x65\x6e\x74\x20\x77\x72\x69\x74\x65\x20\x6b\x65\x79" /*client write key*/ +#undef TLS_MD_SERVER_WRITE_KEY_CONST +#define TLS_MD_SERVER_WRITE_KEY_CONST "\x73\x65\x72\x76\x65\x72\x20\x77\x72\x69\x74\x65\x20\x6b\x65\x79" /*server write key*/ +#undef TLS_MD_IV_BLOCK_CONST +#define TLS_MD_IV_BLOCK_CONST "\x49\x56\x20\x62\x6c\x6f\x63\x6b" /*IV block*/ +#undef TLS_MD_MASTER_SECRET_CONST +#define TLS_MD_MASTER_SECRET_CONST "\x6d\x61\x73\x74\x65\x72\x20\x73\x65\x63\x72\x65\x74" /*master secret*/ +#endif + +/* TLS Session Ticket extension struct */ +struct tls_session_ticket_ext_st + { + unsigned short length; + void *data; + }; + +#ifdef __cplusplus +} +#endif +#endif diff --git a/node-v0.8.14/deps/openssl/openssl/times/090/586-100.nt b/node-v0.8.14/deps/openssl/openssl/times/090/586-100.nt new file mode 100644 index 0000000..297ec3e --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/times/090/586-100.nt @@ -0,0 +1,32 @@ +SSLeay 0.9.0 08-Apr-1998 +built on Wed Apr 8 12:47:17 EST 1998 +options:bn(64,32) md2(int) rc4(idx,int) des(idx,cisc,4,long) idea(int) blowfish( +ptr2) +C flags:cl /MD /W3 /WX /G5 /Ox /O2 /Ob2 /Gs0 /GF /Gy /nologo -DWIN32 -DL_ENDIAN +-DBN_ASM -DMD5_ASM -DSHA1_ASM -DRMD160_ASM +The 'numbers' are in 1000s of bytes per second processed. +type 8 bytes 64 bytes 256 bytes 1024 bytes 8192 bytes +md2 92.25k 256.80k 347.01k 380.40k 390.31k +mdc2 240.72k 251.10k 252.00k 250.80k 251.40k +md5 1013.61k 5651.94k 11831.61k 16294.89k 17901.43k +hmac(md5) 419.50k 2828.07k 7770.11k 13824.34k 17091.70k +sha1 524.31k 2721.45k 5216.15k 6766.10k 7308.42k +rmd160 462.09k 2288.59k 4260.77k 5446.44k 5841.65k +rc4 7895.90k 10326.73k 10555.43k 10728.22k 10429.44k +des cbc 2036.86k 2208.92k 2237.68k 2237.20k 2181.35k +des ede3 649.92k 739.42k 749.07k 748.86k 738.27k +idea cbc 823.19k 885.10k 894.92k 896.45k 891.87k +rc2 cbc 792.63k 859.00k 867.45k 868.96k 865.30k +rc5-32/12 cbc 3502.26k 4026.79k 4107.23k 4121.76k 4073.72k +blowfish cbc 3752.96k 4026.79k 4075.31k 3965.87k 3892.26k +cast cbc 2566.27k 2807.43k 2821.79k 2792.48k 2719.34k + sign verify sign/s verify/s +rsa 512 bits 0.0179s 0.0020s 56.0 501.7 +rsa 1024 bits 0.0950s 0.0060s 10.5 166.6 +rsa 2048 bits 0.6299s 0.0209s 1.6 47.8 +rsa 4096 bits 4.5870s 0.0787s 0.2 12.7 + sign verify sign/s verify/s +dsa 512 bits 0.0180s 0.0339s 55.6 29.5 +dsa 1024 bits 0.0555s 0.1076s 18.0 9.3 +dsa 2048 bits 0.1971s 0.3918s 5.1 2.6 + diff --git a/node-v0.8.14/deps/openssl/openssl/times/091/486-50.nt b/node-v0.8.14/deps/openssl/openssl/times/091/486-50.nt new file mode 100644 index 0000000..84820d9 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/times/091/486-50.nt @@ -0,0 +1,30 @@ +486-50 NT 4.0 + +SSLeay 0.9.1a 06-Jul-1998 +built on Sat Jul 18 18:03:20 EST 1998 +options:bn(64,32) md2(int) rc4(idx,int) des(idx,cisc,4,long) idea(int) blowfish(ptr2) +C flags:cl /MD /W3 /WX /G5 /Ox /O2 /Ob2 /Gs0 /GF /Gy /nologo -DWIN32 -DWIN32_LEAN_AND_MEAN -DL_ENDIAN -DBN_ASM -DMD5_ASM -DSHA1_ASM -DRMD160_ASM /Fdout32 +The 'numbers' are in 1000s of bytes per second processed. +type 8 bytes 64 bytes 256 bytes 1024 bytes 8192 bytes +md2 28.77k 80.30k 108.50k 118.98k 122.47k +mdc2 51.52k 54.06k 54.54k 54.65k 54.62k +md5 304.39k 1565.04k 3061.54k 3996.10k 4240.10k +hmac(md5) 119.53k 793.23k 2061.29k 3454.95k 4121.76k +sha1 127.51k 596.93k 1055.54k 1313.84k 1413.18k +rmd160 128.50k 572.49k 1001.03k 1248.01k 1323.63k +rc4 1224.40k 1545.11k 1590.29k 1600.20k 1576.90k +des cbc 448.19k 503.45k 512.30k 513.30k 508.23k +des ede3 148.66k 162.48k 163.68k 163.94k 164.24k +idea cbc 194.18k 211.10k 212.99k 213.18k 212.64k +rc2 cbc 245.78k 271.01k 274.12k 274.38k 273.52k +rc5-32/12 cbc 1252.48k 1625.20k 1700.03k 1711.12k 1677.18k +blowfish cbc 725.16k 828.26k 850.01k 846.99k 833.79k +cast cbc 643.30k 717.22k 739.48k 741.57k 735.33k + sign verify sign/s verify/s +rsa 512 bits 0.0904s 0.0104s 11.1 96.2 +rsa 1024 bits 0.5968s 0.0352s 1.7 28.4 +rsa 2048 bits 3.8860s 0.1017s 0.3 9.8 + sign verify sign/s verify/s +dsa 512 bits 0.1006s 0.1249s 9.9 8.0 +dsa 1024 bits 0.3306s 0.4093s 3.0 2.4 +dsa 2048 bits 0.9454s 1.1707s 1.1 0.9 diff --git a/node-v0.8.14/deps/openssl/openssl/times/091/586-100.lnx b/node-v0.8.14/deps/openssl/openssl/times/091/586-100.lnx new file mode 100644 index 0000000..92892a6 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/times/091/586-100.lnx @@ -0,0 +1,32 @@ +Pentium 100mhz, linux + +SSLeay 0.9.0a 14-Apr-1998 +built on Fri Apr 17 08:47:07 EST 1998 +options:bn(64,32) md2(int) rc4(idx,int) des(ptr,risc1,16,long) idea(int) blowfish(ptr2) +C flags:gcc -DL_ENDIAN -DTERMIO -DBN_ASM -O3 -fomit-frame-pointer -m486 -Wall -Wuninitialized -DSHA1_ASM -DMD5_ASM -DRMD160_ASM +The 'numbers' are in 1000s of bytes per second processed. +type 8 bytes 64 bytes 256 bytes 1024 bytes 8192 bytes +md2 56.65k 153.88k 208.47k 229.03k 237.57k +mdc2 189.59k 204.95k 206.93k 208.90k 209.56k +md5 1019.48k 5882.41k 12085.42k 16376.49k 18295.47k +hmac(md5) 415.86k 2887.85k 7891.29k 13894.66k 17446.23k +sha1 540.68k 2791.96k 5289.30k 6813.01k 7432.87k +rmd160 298.37k 1846.87k 3869.10k 5273.94k 5892.78k +rc4 7870.87k 10438.10k 10857.13k 10729.47k 10788.86k +des cbc 1960.60k 2226.37k 2241.88k 2054.83k 2181.80k +des ede3 734.44k 739.69k 779.43k 750.25k 772.78k +idea cbc 654.07k 711.00k 716.89k 718.51k 720.90k +rc2 cbc 648.83k 701.91k 708.61k 708.95k 709.97k +rc5-32/12 cbc 3504.71k 4054.76k 4131.41k 4105.56k 4134.23k +blowfish cbc 3762.25k 4313.79k 4460.54k 4356.78k 4317.18k +cast cbc 2755.01k 3038.91k 3076.44k 3027.63k 2998.27k + sign verify sign/s verify/s +rsa 512 bits 0.0195s 0.0019s 51.4 519.9 +rsa 1024 bits 0.1000s 0.0059s 10.0 168.2 +rsa 2048 bits 0.6406s 0.0209s 1.6 47.8 +rsa 4096 bits 4.6100s 0.0787s 0.2 12.7 + sign verify sign/s verify/s +dsa 512 bits 0.0188s 0.0360s 53.1 27.8 +dsa 1024 bits 0.0570s 0.1126s 17.5 8.9 +dsa 2048 bits 0.1990s 0.3954s 5.0 2.5 + diff --git a/node-v0.8.14/deps/openssl/openssl/times/091/68000.bsd b/node-v0.8.14/deps/openssl/openssl/times/091/68000.bsd new file mode 100644 index 0000000..a3a14e8 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/times/091/68000.bsd @@ -0,0 +1,32 @@ +Motorolla 68020 20mhz, NetBSD + +SSLeay 0.9.0t 29-May-1998 +built on Fri Jun 5 12:42:23 EST 1998 +options:bn(64,32) md2(char) rc4(idx,int) des(idx,cisc,16,long) idea(int) blowfish(idx) +C flags:gcc -DTERMIOS -O3 -fomit-frame-pointer -Wall -DB_ENDIAN +The 'numbers' are in 1000s of bytes per second processed. +type 8 bytes 64 bytes 256 bytes 1024 bytes 8192 bytes +md2 2176.00 5994.67 8079.73 8845.18 9077.01 +mdc2 5730.67 6122.67 6167.66 6176.51 6174.87 +md5 29.10k 127.31k 209.66k 250.50k 263.99k +hmac(md5) 12.33k 73.02k 160.17k 228.04k 261.15k +sha1 11.27k 49.37k 84.31k 102.40k 109.23k +rmd160 11.69k 48.62k 78.76k 93.15k 98.41k +rc4 117.96k 148.94k 152.57k 153.09k 152.92k +des cbc 27.13k 30.06k 30.38k 30.38k 30.53k +des ede3 10.51k 10.94k 11.01k 11.01k 11.01k +idea cbc 26.74k 29.23k 29.45k 29.60k 29.74k +rc2 cbc 34.27k 39.39k 40.03k 40.07k 40.16k +rc5-32/12 cbc 64.31k 83.18k 85.70k 86.70k 87.09k +blowfish cbc 48.86k 59.18k 60.07k 60.42k 60.78k +cast cbc 42.67k 50.01k 50.86k 51.20k 51.37k + sign verify sign/s verify/s +rsa 512 bits 0.7738s 0.0774s 1.3 12.9 +rsa 1024 bits 4.3967s 0.2615s 0.2 3.8 +rsa 2048 bits 29.5200s 0.9664s 0.0 1.0 + sign verify sign/s verify/s +dsa 512 bits 0.7862s 0.9709s 1.3 1.0 +dsa 1024 bits 2.5375s 3.1625s 0.4 0.3 +dsa 2048 bits 9.2150s 11.8200s 0.1 0.1 + + diff --git a/node-v0.8.14/deps/openssl/openssl/times/091/686-200.lnx b/node-v0.8.14/deps/openssl/openssl/times/091/686-200.lnx new file mode 100644 index 0000000..bb857d4 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/times/091/686-200.lnx @@ -0,0 +1,32 @@ +Pentium Pro 200mhz, linux + +SSLeay 0.9.0d 26-Apr-1998 +built on Sun Apr 26 10:25:33 EST 1998 +options:bn(64,32) md2(int) rc4(idx,int) des(ptr,risc1,16,long) idea(int) blowfish(ptr2) +C flags:gcc -DL_ENDIAN -DTERMIO -DBN_ASM -O3 -fomit-frame-pointer -m486 -Wall -Wuninitialized -DSHA1_ASM -DMD5_ASM -DRMD160_ASM +The 'numbers' are in 1000s of bytes per second processed. +type 8 bytes 64 bytes 256 bytes 1024 bytes 8192 bytes +md2 130.58k 364.54k 499.24k 545.79k 561.66k +mdc2 526.68k 579.72k 588.37k 588.80k 589.82k +md5 1917.71k 11434.69k 22512.21k 29495.30k 32677.89k +hmac(md5) 749.18k 5264.83k 14227.20k 25018.71k 31760.38k +sha1 1343.83k 6436.29k 11702.78k 14664.70k 15829.67k +rmd160 1038.05k 5138.77k 8985.51k 10985.13k 11799.21k +rc4 14891.04k 21334.06k 22376.79k 22579.54k 22574.42k +des cbc 4131.97k 4568.31k 4645.29k 4631.21k 4572.73k +des ede3 1567.17k 1631.13k 1657.32k 1653.08k 1643.86k +idea cbc 2427.23k 2671.21k 2716.67k 2723.84k 2733.40k +rc2 cbc 1629.90k 1767.38k 1788.50k 1797.12k 1799.51k +rc5-32/12 cbc 10290.55k 13161.60k 13744.55k 14011.73k 14123.01k +blowfish cbc 5896.42k 6920.77k 7122.01k 7151.62k 7146.15k +cast cbc 6037.71k 6935.19k 7101.35k 7145.81k 7116.12k + sign verify sign/s verify/s +rsa 512 bits 0.0070s 0.0007s 142.6 1502.9 +rsa 1024 bits 0.0340s 0.0019s 29.4 513.3 +rsa 2048 bits 0.2087s 0.0066s 4.8 151.3 +rsa 4096 bits 1.4700s 0.0242s 0.7 41.2 + sign verify sign/s verify/s +dsa 512 bits 0.0064s 0.0121s 156.1 82.9 +dsa 1024 bits 0.0184s 0.0363s 54.4 27.5 +dsa 2048 bits 0.0629s 0.1250s 15.9 8.0 + diff --git a/node-v0.8.14/deps/openssl/openssl/times/091/alpha064.osf b/node-v0.8.14/deps/openssl/openssl/times/091/alpha064.osf new file mode 100644 index 0000000..a8e7fdf --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/times/091/alpha064.osf @@ -0,0 +1,32 @@ +Alpha EV4.5 (21064) 275mhz, OSF1 V4.0 +SSLeay 0.9.0g 01-May-1998 +built on Mon May 4 17:26:09 CST 1998 +options:bn(64,64) md2(int) rc4(ptr,int) des(idx,cisc,4,long) idea(int) blowfish(idx) +C flags:cc -tune host -O4 -readonly_strings +The 'numbers' are in 1000s of bytes per second processed. +type 8 bytes 64 bytes 256 bytes 1024 bytes 8192 bytes +md2 119.58k 327.48k 443.28k 480.09k 495.16k +mdc2 436.67k 456.35k 465.42k 466.57k 469.01k +md5 1459.34k 6566.46k 11111.91k 13375.30k 14072.60k +hmac(md5) 597.90k 3595.45k 8180.88k 12099.49k 13884.46k +sha1 707.01k 3253.09k 6131.73k 7798.23k 8439.67k +rmd160 618.57k 2729.07k 4711.33k 5825.16k 6119.23k +rc4 8796.43k 9393.62k 9548.88k 9378.77k 9472.57k +des cbc 2165.97k 2514.90k 2586.27k 2572.93k 2639.08k +des ede3 945.44k 1004.03k 1005.96k 1017.33k 1020.85k +idea cbc 1498.81k 1629.11k 1637.28k 1625.50k 1641.11k +rc2 cbc 1866.00k 2044.92k 2067.12k 2064.00k 2068.96k +rc5-32/12 cbc 4366.97k 5521.32k 5687.50k 5729.16k 5736.96k +blowfish cbc 3997.31k 4790.60k 4937.84k 4954.56k 5024.85k +cast cbc 2900.19k 3673.30k 3803.73k 3823.93k 3890.25k + sign verify sign/s verify/s +rsa 512 bits 0.0069s 0.0006s 144.2 1545.8 +rsa 1024 bits 0.0304s 0.0018s 32.9 552.6 +rsa 2048 bits 0.1887s 0.0062s 5.3 161.4 +rsa 4096 bits 1.3667s 0.0233s 0.7 42.9 + sign verify sign/s verify/s +dsa 512 bits 0.0067s 0.0123s 149.6 81.1 +dsa 1024 bits 0.0177s 0.0332s 56.6 30.1 +dsa 2048 bits 0.0590s 0.1162s 16.9 8.6 + + diff --git a/node-v0.8.14/deps/openssl/openssl/times/091/alpha164.lnx b/node-v0.8.14/deps/openssl/openssl/times/091/alpha164.lnx new file mode 100644 index 0000000..c994662 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/times/091/alpha164.lnx @@ -0,0 +1,32 @@ +Alpha EV5.6 (21164A) 533mhz, Linux 2.0.32 + +SSLeay 0.9.0p 22-May-1998 +built on Sun May 27 14:23:38 GMT 2018 +options:bn(64,64) md2(int) rc4(ptr,int) des(idx,risc1,16,long) idea(int) blowfish(idx) +C flags:gcc -O3 +The 'numbers' are in 1000s of bytes per second processed. +type 8 bytes 64 bytes 256 bytes 1024 bytes 8192 bytes +md2 295.78k 825.34k 1116.42k 1225.10k 1262.65k +mdc2 918.16k 1017.55k 1032.18k 1034.24k 1035.60k +md5 3574.93k 15517.05k 25482.67k 30434.31k 32210.51k +hmac(md5) 1261.54k 7757.15k 18025.46k 27081.21k 31653.27k +sha1 2251.89k 10056.84k 16990.19k 20651.04k 21973.29k +rmd160 1615.49k 7017.13k 11601.11k 13875.62k 14690.31k +rc4 22435.16k 24476.40k 24349.95k 23042.36k 24581.53k +des cbc 5198.38k 6559.04k 6775.43k 6827.87k 6875.82k +des ede3 2257.73k 2602.18k 2645.60k 2657.12k 2670.59k +idea cbc 3694.42k 4125.61k 4180.74k 4193.28k 4192.94k +rc2 cbc 4642.47k 5323.85k 5415.42k 5435.86k 5434.03k +rc5-32/12 cbc 9705.26k 13277.79k 13843.46k 13989.66k 13987.57k +blowfish cbc 7861.28k 10852.34k 11447.98k 11616.97k 11667.54k +cast cbc 6718.13k 8599.98k 8967.17k 9070.81k 9099.28k + sign verify sign/s verify/s +rsa 512 bits 0.0018s 0.0002s 555.9 6299.5 +rsa 1024 bits 0.0081s 0.0005s 123.3 2208.7 +rsa 2048 bits 0.0489s 0.0015s 20.4 648.5 +rsa 4096 bits 0.3402s 0.0057s 2.9 174.7 + sign verify sign/s verify/s +dsa 512 bits 0.0019s 0.0032s 529.0 310.2 +dsa 1024 bits 0.0047s 0.0086s 214.1 115.7 +dsa 2048 bits 0.0150s 0.0289s 66.7 34.6 + diff --git a/node-v0.8.14/deps/openssl/openssl/times/091/alpha164.osf b/node-v0.8.14/deps/openssl/openssl/times/091/alpha164.osf new file mode 100644 index 0000000..df712c6 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/times/091/alpha164.osf @@ -0,0 +1,31 @@ +Alpha EV5.6 (21164A) 400mhz, OSF1 V4.0 + +SSLeay 0.9.0 10-Apr-1998 +built on Sun Apr 19 07:54:37 EST 1998 +options:bn(64,64) md2(int) rc4(ptr,int) des(ptr,risc2,4,int) idea(int) blowfish(idx) +C flags:cc -O4 -tune host -fast +The 'numbers' are in 1000s of bytes per second processed. +type 8 bytes 64 bytes 256 bytes 1024 bytes 8192 bytes +md2 276.30k 762.07k 1034.35k 1134.07k 1160.53k +mdc2 814.99k 845.83k 849.09k 850.33k 849.24k +md5 2468.43k 10945.27k 17963.48k 21430.89k 22544.38k +hmac(md5) 1002.48k 6023.98k 13430.99k 19344.17k 22351.80k +sha1 1984.93k 8882.47k 14856.47k 17878.70k 18955.10k +rmd160 1286.96k 5595.52k 9167.00k 10957.74k 11582.30k +rc4 15948.15k 16710.29k 16793.20k 17929.50k 18474.56k +des cbc 3416.04k 4149.37k 4296.25k 4328.89k 4327.57k +des ede3 1540.14k 1683.36k 1691.14k 1705.90k 1705.22k +idea cbc 2795.87k 3192.93k 3238.13k 3238.17k 3256.66k +rc2 cbc 3529.00k 4069.93k 4135.79k 4135.25k 4160.07k +rc5-32/12 cbc 7212.35k 9849.71k 10260.91k 10423.38k 10439.99k +blowfish cbc 6061.75k 8363.50k 8706.80k 8779.40k 8784.55k +cast cbc 5401.75k 6433.31k 6638.18k 6662.40k 6702.80k + sign verify sign/s verify/s +rsa 512 bits 0.0022s 0.0002s 449.6 4916.2 +rsa 1024 bits 0.0105s 0.0006s 95.3 1661.2 +rsa 2048 bits 0.0637s 0.0020s 15.7 495.6 +rsa 4096 bits 0.4457s 0.0075s 2.2 132.7 + sign verify sign/s verify/s +dsa 512 bits 0.0028s 0.0048s 362.2 210.4 +dsa 1024 bits 0.0064s 0.0123s 155.2 81.6 +dsa 2048 bits 0.0201s 0.0394s 49.7 25.4 diff --git a/node-v0.8.14/deps/openssl/openssl/times/091/mips-rel.pl b/node-v0.8.14/deps/openssl/openssl/times/091/mips-rel.pl new file mode 100644 index 0000000..4b25093 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/times/091/mips-rel.pl @@ -0,0 +1,21 @@ +#!/usr/local/bin/perl + +&doit(100,"Pentium 100 32",0.0195,0.1000,0.6406,4.6100); # pentium-100 +&doit(200,"PPro 200 32",0.0070,0.0340,0.2087,1.4700); # pentium-100 +&doit( 25,"R3000 25 32",0.0860,0.4825,3.2417,23.8833); # R3000-25 +&doit(200,"R4400 200 32",0.0137,0.0717,0.4730,3.4367); # R4400 32bit +&doit(180,"R10000 180 32",0.0061,0.0311,0.1955,1.3871); # R10000 32bit +&doit(180,"R10000 180 64",0.0034,0.0149,0.0880,0.5933); # R10000 64bit +&doit(400,"DEC 21164 400 64",0.0022,0.0105,0.0637,0.4457); # R10000 64bit + +sub doit + { + local($mhz,$label,@data)=@_; + + for ($i=0; $i <= $#data; $i++) + { + $data[$i]=1/$data[$i]*200/$mhz; + } + printf("%s %6.1f %6.1f %6.1f %6.1f\n",$label,@data); + } + diff --git a/node-v0.8.14/deps/openssl/openssl/times/091/r10000.irx b/node-v0.8.14/deps/openssl/openssl/times/091/r10000.irx new file mode 100644 index 0000000..237ee5d --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/times/091/r10000.irx @@ -0,0 +1,37 @@ +MIPS R10000 32kI+32kD 180mhz, IRIX 6.4 + +Using crypto/bn/mips3.s + +This is built for n32, which is faster for all benchmarks than the n64 +compilation model + +SSLeay 0.9.0b 19-Apr-1998 +built on Sat Apr 25 12:43:14 EST 1998 +options:bn(64,64) md2(int) rc4(ptr,int) des(ptr,risc2,16,long) idea(int) blowfish(ptr) +C flags:cc -use_readonly_const -O2 -DTERMIOS -DB_ENDIAN +The 'numbers' are in 1000s of bytes per second processed. +type 8 bytes 64 bytes 256 bytes 1024 bytes 8192 bytes +md2 126.38k 349.38k 472.67k 517.01k 529.81k +mdc2 501.64k 545.87k 551.80k 553.64k 554.41k +md5 1825.77k 7623.64k 12630.47k 15111.74k 16012.09k +hmac(md5) 780.81k 4472.86k 9667.22k 13802.67k 15777.89k +sha1 1375.52k 6213.91k 11037.30k 13682.01k 14714.09k +rmd160 856.72k 3454.40k 5598.33k 6689.94k 7073.48k +rc4 11260.93k 13311.50k 13360.05k 13322.17k 13364.39k +des cbc 2770.78k 3055.42k 3095.18k 3092.48k 3103.03k +des ede3 1023.22k 1060.58k 1063.81k 1070.37k 1064.54k +idea cbc 3029.09k 3334.30k 3375.29k 3375.65k 3380.64k +rc2 cbc 2307.45k 2470.72k 2501.25k 2500.68k 2500.55k +rc5-32/12 cbc 6770.91k 8629.89k 8909.58k 9009.64k 9044.95k +blowfish cbc 4796.53k 5598.20k 5717.14k 5755.11k 5749.86k +cast cbc 3986.20k 4426.17k 4465.04k 4476.84k 4475.08k + sign verify sign/s verify/s +rsa 512 bits 0.0034s 0.0003s 296.1 3225.4 +rsa 1024 bits 0.0139s 0.0008s 71.8 1221.8 +rsa 2048 bits 0.0815s 0.0026s 12.3 380.3 +rsa 4096 bits 0.5656s 0.0096s 1.8 103.7 + sign verify sign/s verify/s +dsa 512 bits 0.0034s 0.0061s 290.8 164.9 +dsa 1024 bits 0.0084s 0.0161s 119.1 62.3 +dsa 2048 bits 0.0260s 0.0515s 38.5 19.4 + diff --git a/node-v0.8.14/deps/openssl/openssl/times/091/r3000.ult b/node-v0.8.14/deps/openssl/openssl/times/091/r3000.ult new file mode 100644 index 0000000..ecd3390 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/times/091/r3000.ult @@ -0,0 +1,32 @@ +MIPS R3000 64kI+64kD 25mhz, ultrix 4.3 + +SSLeay 0.9.0b 19-Apr-1998 +built on Thu Apr 23 07:22:31 EST 1998 +options:bn(32,32) md2(int) rc4(ptr,int) des(ptr,risc2,16,long) idea(int) blowfish(idx) +C flags:cc -O2 -DL_ENDIAN -DNOPROTO -DNOCONST +The 'numbers' are in 1000s of bytes per second processed. +type 8 bytes 64 bytes 256 bytes 1024 bytes 8192 bytes +md2 14.63k 40.65k 54.70k 60.07k 61.78k +mdc2 29.43k 37.27k 38.23k 38.57k 38.60k +md5 140.04k 676.59k 1283.84k 1654.10k 1802.24k +hmac(md5) 60.51k 378.90k 937.82k 1470.46k 1766.74k +sha1 60.77k 296.79k 525.40k 649.90k 699.05k +rmd160 48.82k 227.16k 417.19k 530.31k 572.05k +rc4 904.76k 996.20k 1007.53k 1015.65k 1010.35k +des cbc 178.87k 209.39k 213.42k 215.55k 214.53k +des ede3 74.25k 79.30k 80.40k 80.21k 80.14k +idea cbc 181.02k 209.37k 214.44k 214.36k 213.83k +rc2 cbc 161.52k 184.98k 187.99k 188.76k 189.05k +rc5-32/12 cbc 398.99k 582.91k 614.66k 626.07k 621.87k +blowfish cbc 296.38k 387.69k 405.50k 412.57k 410.05k +cast cbc 214.76k 260.63k 266.92k 268.63k 258.26k + sign verify sign/s verify/s +rsa 512 bits 0.0870s 0.0089s 11.5 112.4 +rsa 1024 bits 0.4881s 0.0295s 2.0 33.9 +rsa 2048 bits 3.2750s 0.1072s 0.3 9.3 +rsa 4096 bits 23.9833s 0.4093s 0.0 2.4 + sign verify sign/s verify/s +dsa 512 bits 0.0898s 0.1706s 11.1 5.9 +dsa 1024 bits 0.2847s 0.5565s 3.5 1.8 +dsa 2048 bits 1.0267s 2.0433s 1.0 0.5 + diff --git a/node-v0.8.14/deps/openssl/openssl/times/091/r4400.irx b/node-v0.8.14/deps/openssl/openssl/times/091/r4400.irx new file mode 100644 index 0000000..9b96ca1 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/times/091/r4400.irx @@ -0,0 +1,32 @@ +R4400 16kI+16kD 200mhz, Irix 5.3 + +SSLeay 0.9.0e 27-Apr-1998 +built on Sun Apr 26 07:26:05 PDT 1998 +options:bn(64,32) md2(int) rc4(ptr,int) des(ptr,risc2,16,long) idea(int) blowfish(ptr) +C flags:cc -O2 -use_readonly_const -DTERMIOS -DB_ENDIAN +The 'numbers' are in 1000s of bytes per second processed. +type 8 bytes 64 bytes 256 bytes 1024 bytes 8192 bytes +md2 79.80k 220.59k 298.01k 327.06k 338.60k +mdc2 262.74k 285.30k 289.16k 288.36k 288.49k +md5 930.35k 4167.13k 7167.91k 8678.23k 9235.86k +hmac(md5) 399.44k 2367.57k 5370.74k 7884.28k 9076.98k +sha1 550.96k 2488.17k 4342.76k 5362.50k 5745.40k +rmd160 424.58k 1752.83k 2909.67k 3486.08k 3702.89k +rc4 6687.79k 7834.63k 7962.61k 8035.65k 7915.28k +des cbc 1544.20k 1725.94k 1748.35k 1758.17k 1745.61k +des ede3 587.29k 637.75k 645.93k 643.17k 646.01k +idea cbc 1575.52k 1719.75k 1732.41k 1736.69k 1740.11k +rc2 cbc 1496.21k 1629.90k 1643.19k 1652.14k 1646.62k +rc5-32/12 cbc 3452.48k 4276.47k 4390.74k 4405.25k 4400.12k +blowfish cbc 2354.58k 3242.36k 3401.11k 3433.65k 3383.65k +cast cbc 1942.22k 2152.28k 2187.51k 2185.67k 2177.20k + sign verify sign/s verify/s +rsa 512 bits 0.0130s 0.0014s 76.9 729.8 +rsa 1024 bits 0.0697s 0.0043s 14.4 233.9 +rsa 2048 bits 0.4664s 0.0156s 2.1 64.0 +rsa 4096 bits 3.4067s 0.0586s 0.3 17.1 + sign verify sign/s verify/s +dsa 512 bits 0.0140s 0.0261s 71.4 38.4 +dsa 1024 bits 0.0417s 0.0794s 24.0 12.6 +dsa 2048 bits 0.1478s 0.2929s 6.8 3.4 + diff --git a/node-v0.8.14/deps/openssl/openssl/times/100.lnx b/node-v0.8.14/deps/openssl/openssl/times/100.lnx new file mode 100644 index 0000000..d0f4537 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/times/100.lnx @@ -0,0 +1,32 @@ +SSLeay 0.8.4c 03-Aug-1999 +built on Tue Nov 4 02:52:29 EST 1997 +options:bn(64,32) md2(int) rc4(ptr,int) des(ptr,risc1,16,long) idea(int) blowfish(ptr2) +C flags:gcc -DL_ENDIAN -DTERMIO -DBN_ASM -O3 -fomit-frame-pointer -m486 -Wall -Wuninitialized -DMD5_ASM -DSHA1_ASM +The 'numbers' are in 1000s of bytes per second processed. +type 8 bytes 64 bytes 256 bytes 1024 bytes 8192 bytes +md2 53.27k 155.95k 201.30k 216.41k 236.78k +mdc2 192.98k 207.98k 206.76k 206.17k 208.87k +md5 993.15k 5748.27k 11944.70k 16477.53k 18287.27k +hmac(md5) 404.97k 2787.58k 7690.07k 13744.43k 17601.88k +sha1 563.24k 2851.67k 5363.71k 6879.23k 7441.07k +rc4 7876.70k 10400.85k 10825.90k 10943.49k 10745.17k +des cbc 2047.39k 2188.25k 2188.29k 2239.49k 2233.69k +des ede3 660.55k 764.01k 773.55k 779.21k 780.97k +idea cbc 653.93k 708.48k 715.43k 719.87k 720.90k +rc2 cbc 648.08k 702.23k 708.78k 711.00k 709.97k +blowfish cbc 3764.39k 4288.66k 4375.04k 4497.07k 4423.68k +cast cbc 2757.14k 2993.75k 3035.31k 3078.90k 3055.62k + +blowfish cbc 3258.81k 3673.47k 3767.30k 3774.12k 3719.17k +cast cbc 2677.05k 3164.78k 3273.05k 3287.38k 3244.03k + + + sign verify +rsa 512 bits 0.0213s 0.0020s +rsa 1024 bits 0.1073s 0.0063s +rsa 2048 bits 0.6873s 0.0224s +rsa 4096 bits 4.9333s 0.0845s + sign verify +dsa 512 bits 0.0201s 0.0385s +dsa 1024 bits 0.0604s 0.1190s +dsa 2048 bits 0.2121s 0.4229s diff --git a/node-v0.8.14/deps/openssl/openssl/times/100.nt b/node-v0.8.14/deps/openssl/openssl/times/100.nt new file mode 100644 index 0000000..0dd7cfc --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/times/100.nt @@ -0,0 +1,29 @@ +SSLeay 0.8.4c 03-Aug-1999 +built on Tue Aug 3 09:49:58 EST 1999 +options:bn(64,32) md2(int) rc4(ptr,int) des(idx,cisc,4,long) idea(int) blowfish( +ptr2) +C flags:cl /W3 /WX /G5 /Ox /O2 /Ob2 /Gs0 /GF /Gy /nologo -DWIN32 -DL_ENDIAN -DBN +_ASM -DMD5_ASM -DSHA1_ASM +The 'numbers' are in 1000s of bytes per second processed. +type 8 bytes 64 bytes 256 bytes 1024 bytes 8192 bytes +md2 93.07k 258.38k 349.03k 382.83k 392.87k +mdc2 245.80k 259.02k 259.34k 259.16k 260.14k +md5 1103.42k 6017.65k 12210.49k 16552.11k 18291.77k +hmac(md5) 520.15k 3394.00k 8761.86k 14593.96k 17742.40k +sha1 538.06k 2726.76k 5242.22k 6821.12k 7426.18k +rc4 8283.90k 10513.09k 10886.38k 10929.50k 10816.75k +des cbc 2073.10k 2232.91k 2251.61k 2256.46k 2232.44k +des ede3 758.85k 782.46k 786.14k 786.08k 781.24k +idea cbc 831.02k 892.63k 901.07k 903.48k 901.85k +rc2 cbc 799.89k 866.09k 873.96k 876.22k 874.03k +blowfish cbc 3835.32k 4418.78k 4511.94k 4494.54k 4416.92k +cast cbc 2974.68k 3272.71k 3313.04k 3335.17k 3261.51k + sign verify +rsa 512 bits 0.0202s 0.0019s +rsa 1024 bits 0.1029s 0.0062s +rsa 2048 bits 0.6770s 0.0220s +rsa 4096 bits 4.8770s 0.0838s + sign verify +dsa 512 bits 0.0191s 0.0364s +dsa 1024 bits 0.0590s 0.1141s +dsa 2048 bits 0.2088s 0.4171s diff --git a/node-v0.8.14/deps/openssl/openssl/times/200.lnx b/node-v0.8.14/deps/openssl/openssl/times/200.lnx new file mode 100644 index 0000000..fd7e7f4 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/times/200.lnx @@ -0,0 +1,30 @@ +This machine was slightly loaded :-( + +SSLeay 0.8.4c 03-Aug-1999 +built on Tue Nov 4 02:52:29 EST 1997 +options:bn(64,32) md2(int) rc4(ptr,int) des(ptr,risc1,16,long) idea(int) blowfish(ptr2) +C flags:gcc -DL_ENDIAN -DTERMIO -DBN_ASM -O3 -fomit-frame-pointer -m486 -Wall -Wuninitialized -DMD5_ASM -DSHA1_ASM +The 'numbers' are in 1000s of bytes per second processed. +type 8 bytes 64 bytes 256 bytes 1024 bytes 8192 bytes +md2 130.86k 365.31k 499.60k 547.75k 561.41k +mdc2 526.03k 581.38k 587.12k 586.31k 589.60k +md5 1919.49k 11173.23k 22387.60k 29553.47k 32587.21k +hmac(md5) 747.09k 5248.35k 14275.44k 24713.26k 31737.13k +sha1 1336.63k 6400.50k 11668.67k 14648.83k 15700.85k +rc4 15002.32k 21327.21k 22301.63k 22503.78k 22549.26k +des cbc 4115.16k 4521.08k 4632.37k 4607.28k 4570.57k +des ede3 1540.29k 1609.76k 1623.64k 1620.76k 1624.18k +idea cbc 2405.08k 2664.78k 2704.22k 2713.95k 2716.29k +rc2 cbc 1634.07k 1764.30k 1780.23k 1790.27k 1788.12k +blowfish cbc 5993.98k 6927.27k 7083.61k 7088.40k 7123.72k +cast cbc 5981.52k 6900.44k 7079.70k 7110.40k 7057.72k + sign verify +rsa 512 bits 0.0085s 0.0007s +rsa 1024 bits 0.0377s 0.0020s +rsa 2048 bits 0.2176s 0.0067s +rsa 4096 bits 1.4800s 0.0242s +sign verify +dsa 512 bits 0.0071s 0.0132s +dsa 1024 bits 0.0192s 0.0376s +dsa 2048 bits 0.0638s 0.1280s + diff --git a/node-v0.8.14/deps/openssl/openssl/times/486-66.dos b/node-v0.8.14/deps/openssl/openssl/times/486-66.dos new file mode 100644 index 0000000..1644bf8 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/times/486-66.dos @@ -0,0 +1,22 @@ +MS-dos static libs, 16bit C build, 16bit assember + +SSLeay 0.6.1 +options:bn(32,16) md2(char) rc4(idx,int) des(ptr,long) idea(short) +C flags:cl /ALw /Gx- /Gf /f- /Ocgnotb2 /G2 /W3 /WX -DL_ENDIAN /nologo -DMSDOS -D +NO_SOCK +The 'numbers' are in 1000s of bytes per second processed. +type 8 bytes 64 bytes 256 bytes 1024 bytes 8192 bytes +md2 18.62k 55.54k 76.88k 85.39k 86.52k +md5 94.03k 442.06k 794.38k 974.51k 1061.31k +sha 38.37k 166.23k 272.78k 331.41k 353.77k +sha1 34.38k 147.77k 244.77k 292.57k 312.08k +rc4 641.25k 795.34k 817.16k 829.57k 817.16k +des cfb 111.46k 118.08k 120.69k 119.16k 119.37k +des cbc 122.96k 135.69k 137.10k 135.69k 135.40k +des ede3 48.01k 50.92k 50.32k 50.96k 50.96k +idea cfb 97.09k 100.21k 100.36k 101.14k 100.98k +idea cbc 102.08k 109.41k 111.46k 111.65k 110.52k +rc2 cfb 120.47k 125.55k 125.79k 125.55k 125.55k +rc2 cbc 129.77k 140.33k 143.72k 142.16k 141.85k +rsa 512 bits 0.264s +rsa 1024 bits 1.494s diff --git a/node-v0.8.14/deps/openssl/openssl/times/486-66.nt b/node-v0.8.14/deps/openssl/openssl/times/486-66.nt new file mode 100644 index 0000000..b26a900 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/times/486-66.nt @@ -0,0 +1,22 @@ +SSLeay 0.6.1 02-Jul-1996 +built on Fri Jul 10 09:53:15 EST 1996 +options:bn(64,32) md2(int) rc4(idx,int) des(idx,long) idea(int) +C flags:cl /W3 /WX /G5 /Ox /O2 /Ob2 /Gs0 /nologo -DWIN32 -DL_ENDIAN /MD +The 'numbers' are in 1000s of bytes per second processed. +type 8 bytes 64 bytes 256 bytes 1024 bytes 8192 bytes +md2 38.27k 107.28k 145.43k 159.60k 164.15k +md5 399.00k 1946.13k 3610.80k 4511.94k 4477.27k +sha 182.04k 851.26k 1470.65k 1799.20k 1876.48k +sha1 151.83k 756.55k 1289.76k 1567.38k 1625.70k +rc4 1853.92k 2196.25k 2232.91k 2241.31k 2152.96k +des cfb 360.58k 382.69k 384.94k 386.07k 377.19k +des cbc 376.10k 431.87k 436.32k 437.78k 430.45k +des ede3 152.55k 160.38k 161.51k 161.33k 159.98k +idea cfb 245.59k 255.60k 256.65k 257.16k 254.61k +idea cbc 257.16k 276.12k 279.05k 279.11k 276.70k +rc2 cfb 280.25k 293.49k 294.74k 294.15k 291.47k +rc2 cbc 295.47k 321.57k 324.76k 324.76k 320.00k +rsa 512 bits 0.084s +rsa 1024 bits 0.495s +rsa 2048 bits 3.435s + diff --git a/node-v0.8.14/deps/openssl/openssl/times/486-66.w31 b/node-v0.8.14/deps/openssl/openssl/times/486-66.w31 new file mode 100644 index 0000000..381f149 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/times/486-66.w31 @@ -0,0 +1,23 @@ +Windows 3.1 DLL's, 16 bit C with 32bit assember + +SSLeay 0.6.1 02-Jul-1996 +built on Wed Jul 10 09:53:15 EST 1996 +options:bn(32,32) md2(char) rc4(idx,int) des(ptr,long) idea(short) +C flags:cl /ALw /Gx- /Gf /G2 /f- /Ocgnotb2 /W3 /WX -DL_ENDIAN /nologo -DWIN16 +The 'numbers' are in 1000s of bytes per second processed. +type 8 bytes 64 bytes 256 bytes 1024 bytes 8192 bytes +md2 18.94k 54.27k 73.43k 80.91k 83.75k +md5 78.96k 391.26k 734.30k 919.80k 992.97k +sha 39.01k 168.04k 280.67k 336.08k 359.10k +sha1 35.20k 150.14k 247.31k 294.54k 313.94k +rc4 509.61k 655.36k 678.43k 677.02k 670.10k +des cfb 97.09k 104.69k 106.56k 105.70k 106.56k +des cbc 116.82k 129.77k 131.07k 131.07k 131.07k +des ede3 44.22k 47.90k 48.53k 48.47k 47.86k +idea cfb 83.49k 87.03k 87.03k 87.15k 87.73k +idea cbc 89.04k 96.23k 96.95k 97.81k 97.09k +rc2 cfb 108.32k 113.58k 113.78k 114.57k 114.77k +rc2 cbc 118.08k 131.07k 134.02k 134.02k 132.66k +rsa 512 bits 0.181s +rsa 1024 bits 0.846s + diff --git a/node-v0.8.14/deps/openssl/openssl/times/5.lnx b/node-v0.8.14/deps/openssl/openssl/times/5.lnx new file mode 100644 index 0000000..1c1e392 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/times/5.lnx @@ -0,0 +1,29 @@ +SSLeay 0.8.5g 24-Jan-1998 +built on Tue Jan 27 08:11:42 EST 1998 +options:bn(64,32) md2(int) rc4(idx,int) des(ptr,risc1,16,long) idea(int) blowfish(ptr2) +C flags:gcc -DL_ENDIAN -DTERMIO -DBN_ASM -O3 -fomit-frame-pointer -m486 -Wall -Wuninitialized -DSHA1_ASM -DMD5_ASM -DRMD160_ASM +The 'numbers' are in 1000s of bytes per second processed. +type 8 bytes 64 bytes 256 bytes 1024 bytes 8192 bytes +md2 56.55k 156.69k 211.63k 231.77k 238.71k +mdc2 192.26k 208.09k 210.09k 209.58k 210.26k +md5 991.04k 5745.51k 11932.67k 16465.24k 18306.39k +hmac(md5) 333.99k 2383.89k 6890.67k 13133.82k 17397.08k +sha1 571.68k 2883.88k 5379.07k 6880.26k 7443.80k +rmd160 409.41k 2212.91k 4225.45k 5456.55k 5928.28k +rc4 6847.57k 8596.22k 8901.80k 8912.90k 8850.09k +des cbc 2046.29k 2229.78k 2254.76k 2259.97k 2233.69k +des ede3 751.11k 779.95k 783.96k 784.38k 780.97k +idea cbc 653.40k 708.29k 718.42k 720.21k 720.90k +rc2 cbc 647.19k 702.46k 709.21k 710.66k 709.97k +rc5-32/12 cbc 3498.18k 4054.12k 4133.46k 4151.64k 4139.69k +blowfish cbc 3763.95k 4437.74k 4532.74k 4515.50k 4448.26k +cast cbc 2754.22k 3020.67k 3079.08k 3069.95k 3036.50k + sign verify sign/s verify/s +rsa 512 bits 0.0207s 0.0020s 48.3 511.3 +rsa 1024 bits 0.1018s 0.0059s 9.8 169.6 +rsa 2048 bits 0.6438s 0.0208s 1.6 48.0 +rsa 4096 bits 4.6033s 0.0793s 0.2 12.6 + sign verify sign/s verify/s +dsa 512 bits 0.0190s 0.0359s 52.6 27.8 +dsa 1024 bits 0.0566s 0.1109s 17.7 9.0 +dsa 2048 bits 0.1988s 0.3915s 5.0 2.6 diff --git a/node-v0.8.14/deps/openssl/openssl/times/586-085i.nt b/node-v0.8.14/deps/openssl/openssl/times/586-085i.nt new file mode 100644 index 0000000..8a57975 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/times/586-085i.nt @@ -0,0 +1,29 @@ +SSLeay 0.8.5i 28-Jan-1998 +built on Wed Jan 28 18:00:07 EST 1998 +options:bn(64,32) md2(int) rc4(idx,int) des(idx,cisc,4,long) idea(int) blowfish(ptr2) +C flags:cl /MT /W3 /WX /G5 /Ox /O2 /Ob2 /Gs0 /GF /Gy /nologo -DWIN32 -DL_ENDIAN -DBN_ASM -DMD5_ASM -DSHA1_ASM -DRMD160_ASM +The 'numbers' are in 1000s of bytes per second processed. +type 8 bytes 64 bytes 256 bytes 1024 bytes 8192 bytes +md2 92.74k 257.59k 348.16k 381.79k 392.14k +mdc2 227.65k 247.82k 249.90k 250.65k 250.20k +md5 1089.54k 5966.29k 12104.77k 16493.53k 18204.44k +hmac(md5) 513.53k 3361.36k 8725.41k 14543.36k 17593.56k +sha1 580.74k 2880.51k 5376.62k 6865.78k 7413.05k +rmd160 508.06k 2427.96k 4385.51k 5510.84k 5915.80k +rc4 8004.40k 10408.74k 10794.48k 10884.12k 10728.22k +des cbc 2057.24k 2222.97k 2246.79k 2209.39k 2223.44k +des ede3 739.42k 761.99k 765.48k 760.26k 760.97k +idea cbc 827.08k 889.60k 898.83k 901.15k 897.98k +rc2 cbc 795.64k 861.04k 871.13k 872.58k 871.13k +rc5-32/12 cbc 3597.17k 4139.66k 4204.39k 4223.02k 4204.39k +blowfish cbc 3807.47k 3996.10k 4156.07k 4204.39k 4105.62k +cast cbc 2777.68k 2814.21k 2892.62k 2916.76k 2868.88k + sign verify sign/s verify/s +rsa 512 bits 0.0178s 0.0018s 56.3 541.6 +rsa 1024 bits 0.0945s 0.0059s 10.6 168.3 +rsa 2048 bits 0.6269s 0.0208s 1.6 48.0 +rsa 4096 bits 4.5560s 0.0784s 0.2 12.8 + sign verify sign/s verify/s +dsa 512 bits 0.0178s 0.0340s 56.2 29.4 +dsa 1024 bits 0.0552s 0.1077s 18.1 9.3 +dsa 2048 bits 0.1963s 0.3811s 5.1 2.6 diff --git a/node-v0.8.14/deps/openssl/openssl/times/586-100.LN3 b/node-v0.8.14/deps/openssl/openssl/times/586-100.LN3 new file mode 100644 index 0000000..a6fa818 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/times/586-100.LN3 @@ -0,0 +1,26 @@ +SSLeay 0.8.3v 15-Oct-1997 +built on Wed Oct 15 10:05:00 EST 1997 +options:bn(64,32) md2(int) rc4(idx,int) des(ptr,risc1,16,long) idea(int) blowfish(ptr2) +C flags:gcc -DL_ENDIAN -DTERMIO -DX86_ASM -O3 -fomit-frame-pointer -m486 -Wall -Wuninitialized +The 'numbers' are in 1000s of bytes per second processed. +type 8 bytes 64 bytes 256 bytes 1024 bytes 8192 bytes +md2 56.27k 156.76k 211.46k 231.77k 238.71k +mdc2 188.74k 206.12k 207.70k 207.87k 208.18k +md5 991.56k 5718.31k 11748.61k 16090.79k 17850.37k +hmac(md5) 387.56k 2636.01k 7327.83k 13340.33k 17091.24k +sha1 463.55k 2274.18k 4071.17k 5072.90k 5447.68k +rc4 3673.94k 4314.52k 4402.26k 4427.09k 4407.30k +des cbc 2023.79k 2209.77k 2233.34k 2220.71k 2222.76k +des ede3 747.17k 778.54k 781.57k 778.24k 778.24k +idea cbc 614.64k 678.04k 683.52k 685.06k 685.40k +rc2 cbc 536.83k 574.10k 578.05k 579.24k 578.90k +blowfish cbc 3673.39k 4354.58k 4450.22k 4429.48k 4377.26k + sign verify +rsa 512 bits 0.0217s 0.0021s +rsa 1024 bits 0.1083s 0.0064s +rsa 2048 bits 0.6867s 0.0223s +rsa 4096 bits 4.9400s 0.0846s + sign verify +dsa 512 bits 0.0203s 0.0387s +dsa 1024 bits 0.0599s 0.1170s +dsa 2048 bits 0.2115s 0.4242s diff --git a/node-v0.8.14/deps/openssl/openssl/times/586-100.NT2 b/node-v0.8.14/deps/openssl/openssl/times/586-100.NT2 new file mode 100644 index 0000000..7f8c167 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/times/586-100.NT2 @@ -0,0 +1,26 @@ +SSLeay 0.8.3e 30-Sep-1997 +built on Tue Sep 30 14:52:58 EST 1997 +options:bn(64,32) md2(int) rc4(idx,int) des(idx,cisc,4,long) idea(int) blowfish(ptr2) +C flags:cl /W3 /WX /G5 /Ox /O2 /Ob2 /Gs0 /GF /Gy /nologo -DWIN32 -DL_ENDIAN -DX86_ASM +The 'numbers' are in 1000s of bytes per second processed. +type 8 bytes 64 bytes 256 bytes 1024 bytes 8192 bytes +md2 92.99k 257.59k 348.16k 381.47k 392.14k +mdc2 223.77k 235.30k 237.15k 236.77k 237.29k +md5 862.53k 4222.17k 7842.75k 9925.00k 10392.23k +sha 491.34k 2338.61k 4062.28k 4986.10k 5307.90k +sha1 494.38k 2234.94k 3838.83k 4679.58k 4980.18k +rc4 6338.10k 7489.83k 7676.25k 7698.80k 7631.56k +des cbc 1654.17k 1917.66k 1961.05k 1968.05k 1960.69k +des ede3 691.17k 739.42k 744.13k 745.82k 741.40k +idea cbc 788.46k 870.33k 879.16k 881.38k 879.90k +rc2 cbc 794.44k 859.63k 868.24k 869.68k 867.45k +blowfish cbc 2379.88k 3017.48k 3116.12k 3134.76k 3070.50k + sign verify +rsa 512 bits 0.0204s 0.0027s +rsa 1024 bits 0.1074s 0.0032s +rsa 2048 bits 0.6890s 0.0246s +rsa 4096 bits 5.0180s 0.0911s + sign verify +dsa 512 bits 0.0201s 0.0376s +dsa 1024 bits 0.0608s 0.1193s +dsa 2048 bits 0.2133s 0.4294s diff --git a/node-v0.8.14/deps/openssl/openssl/times/586-100.dos b/node-v0.8.14/deps/openssl/openssl/times/586-100.dos new file mode 100644 index 0000000..3085c25 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/times/586-100.dos @@ -0,0 +1,24 @@ +ms-dos static libs, 16 bit C and 16 bit assmber + +SSLeay 0.6.1 02-Jul-1996 +built on Tue Jul 9 22:52:54 EST 1996 +options:bn(32,16) md2(char) rc4(idx,int) des(ptr,long) idea(short) +C flags:cl /ALw /Gx- /Gf /G2 /f- /Ocgnotb2 /W3 /WX -DL_ENDIAN /nologo -DMSDOS -DNO_SOCK +The 'numbers' are in 1000s of bytes per second processed. +type 8 bytes 64 bytes 256 bytes 1024 bytes 8192 bytes +md2 45.99k 130.75k 176.53k 199.35k 203.21k +md5 236.17k 1072.16k 1839.61k 2221.56k 2383.13k +sha 107.97k 459.10k 757.64k 908.64k 954.99k +sha1 96.95k 409.92k 672.16k 788.40k 844.26k +rc4 1659.14k 1956.30k 2022.72k 2022.72k 2022.72k +des cfb 313.57k 326.86k 326.86k 331.83k 326.86k +des cbc 345.84k 378.82k 378.82k 384.38k 378.82k +des ede3 139.59k 144.66k 144.61k 144.45k 143.29k +idea cfb 262.67k 274.21k 274.21k 274.21k 274.21k +idea cbc 284.32k 318.14k 318.14k 318.14k 318.14k +rc2 cfb 265.33k 274.21k 277.69k 277.11k 277.69k +rc2 cbc 283.71k 310.60k 309.86k 313.57k 314.32k +rsa 512 bits 0.104s +rsa 1024 bits 0.566s +rsa 2048 bits 3.680s +rsa 4096 bits 26.740s diff --git a/node-v0.8.14/deps/openssl/openssl/times/586-100.ln4 b/node-v0.8.14/deps/openssl/openssl/times/586-100.ln4 new file mode 100644 index 0000000..14a9db9 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/times/586-100.ln4 @@ -0,0 +1,26 @@ +SSLeay 0.8.3aa 24-Oct-1997 +built on Mon Oct 27 10:16:25 EST 1997 +options:bn(64,32) md2(int) rc4(idx,int) des(ptr,risc1,16,long) idea(int) blowfish(ptr2) +C flags:gcc -DL_ENDIAN -DTERMIO -DBN_ASM -O3 -fomit-frame-pointer -m486 -Wall -Wuninitialized -DMD5_ASM -DSHA1_ASM +The 'numbers' are in 1000s of bytes per second processed. +type 8 bytes 64 bytes 256 bytes 1024 bytes 8192 bytes +md2 56.78k 156.71k 211.46k 231.77k 238.71k +mdc2 187.45k 200.49k 201.64k 202.75k 202.77k +md5 1002.51k 5798.66k 11967.15k 16449.19k 18251.78k +hmac(md5) 468.71k 3173.46k 8386.99k 14305.56k 17607.34k +sha1 586.98k 2934.87k 5393.58k 6863.19k 7408.30k +rc4 3675.10k 4314.15k 4402.77k 4427.78k 4404.57k +des cbc 1902.96k 2202.01k 2242.30k 2252.46k 2236.42k +des ede3 700.15k 774.23k 783.70k 781.62k 783.70k +idea cbc 618.46k 677.93k 683.61k 685.40k 685.40k +rc2 cbc 536.97k 573.87k 577.96k 579.24k 578.90k +blowfish cbc 3672.66k 4271.89k 4428.80k 4469.76k 4374.53k + sign verify +rsa 512 bits 0.0213s 0.0021s +rsa 1024 bits 0.1075s 0.0063s +rsa 2048 bits 0.6853s 0.0224s +rsa 4096 bits 4.9400s 0.0845s + sign verify +dsa 512 bits 0.0203s 0.0380s +dsa 1024 bits 0.0600s 0.1189s +dsa 2048 bits 0.2110s 0.4250s diff --git a/node-v0.8.14/deps/openssl/openssl/times/586-100.lnx b/node-v0.8.14/deps/openssl/openssl/times/586-100.lnx new file mode 100644 index 0000000..0c05173 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/times/586-100.lnx @@ -0,0 +1,23 @@ +SSLeay 0.7.3 30-Apr-1997 +built on Mon May 12 04:13:55 EST 1997 +options:bn(64,32) md2(char) rc4(idx,int) des(ptr,risc1,16,long) idea(int) blowfish(ptr2) +C flags:gcc -DL_ENDIAN -DTERMIO -O3 -fomit-frame-pointer -m486 -Wall -Wuninitialized +The 'numbers' are in 1000s of bytes per second processed. +type 8 bytes 64 bytes 256 bytes 1024 bytes 8192 bytes +md2 72.95k 202.77k 274.01k 300.37k 309.23k +md5 770.57k 4094.02k 7409.41k 9302.36k 9986.05k +sha 363.05k 1571.07k 2613.85k 3134.81k 3320.49k +sha1 340.94k 1462.85k 2419.20k 2892.12k 3042.35k +rc4 3676.91k 4314.94k 4407.47k 4430.51k 4412.76k +des cbc 1489.95k 1799.08k 1841.66k 1851.73k 1848.66k +des ede3 621.93k 711.19k 726.10k 729.77k 729.09k +idea cbc 618.16k 676.99k 683.09k 684.37k 683.59k +rc2 cbc 537.59k 573.93k 578.56k 579.58k 579.70k +blowfish cbc 2077.57k 2682.20k 2827.18k 2840.92k 2842.62k +rsa 512 bits 0.024s 0.003 +rsa 1024 bits 0.120s 0.003 +rsa 2048 bits 0.751s 0.026 +rsa 4096 bits 5.320s 0.096 +dsa 512 bits 0.022s 0.042 +dsa 1024 bits 0.065s 0.126 +dsa 2048 bits 0.227s 0.449 diff --git a/node-v0.8.14/deps/openssl/openssl/times/586-100.nt b/node-v0.8.14/deps/openssl/openssl/times/586-100.nt new file mode 100644 index 0000000..9adcac3 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/times/586-100.nt @@ -0,0 +1,23 @@ +SSLeay 0.7.3 30-Apr-1997 +built on Mon May 19 10:47:38 EST 1997 +options:bn(64,32) md2(char) rc4(idx,int) des(idx,cisc,4,long) idea(int) blowfish(ptr2) +C flags not available +The 'numbers' are in 1000s of bytes per second processed. +type 8 bytes 64 bytes 256 bytes 1024 bytes 8192 bytes +md2 89.57k 245.94k 331.59k 362.95k 373.29k +md5 858.93k 4175.51k 7700.21k 9715.78k 10369.11k +sha 466.18k 2103.67k 3607.69k 4399.31k 4669.16k +sha1 449.59k 2041.02k 3496.13k 4256.45k 4512.92k +rc4 5862.55k 7447.27k 7698.80k 7768.38k 7653.84k +des cbc 1562.71k 1879.84k 1928.24k 1938.93k 1911.02k +des ede3 680.27k 707.97k 728.62k 733.15k 725.98k +idea cbc 797.46k 885.85k 895.68k 898.06k 896.45k +rc2 cbc 609.46k 648.75k 654.01k 654.42k 653.60k +blowfish cbc 2357.94k 3000.22k 3106.89k 3134.76k 3080.42k +rsa 512 bits 0.022s 0.003 +rsa 1024 bits 0.112s 0.003 +rsa 2048 bits 0.726s 0.026 +rsa 4096 bits 5.268s 0.095 +dsa 512 bits 0.021s 0.039 +dsa 1024 bits 0.063s 0.127 +dsa 2048 bits 0.224s 0.451 diff --git a/node-v0.8.14/deps/openssl/openssl/times/586-100.ntx b/node-v0.8.14/deps/openssl/openssl/times/586-100.ntx new file mode 100644 index 0000000..35166a5 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/times/586-100.ntx @@ -0,0 +1,30 @@ +SSLeay 0.8.5f 22-Jan-1998 +built on Wed Jan 21 17:11:53 EST 1998 +options:bn(64,32) md2(int) rc4(idx,int) des(idx,cisc,4,long) idea(int) blowfish( +ptr2) +C flags:cl /MT /W3 /WX /G5 /Ox /O2 /Ob2 /Gs0 /GF /Gy /nologo -DWIN32 -DL_ENDIAN +-DBN_ASM -DMD5_ASM -DSHA1_ASM -DRMD160_ASM +The 'numbers' are in 1000s of bytes per second processed. +type 8 bytes 64 bytes 256 bytes 1024 bytes 8192 bytes +md2 92.99k 257.43k 347.84k 381.82k 392.14k +mdc2 232.19k 253.68k 257.57k 258.70k 258.70k +md5 1094.09k 5974.79k 12139.81k 16487.04k 18291.77k +hmac(md5) 375.70k 2590.04k 7309.70k 13469.18k 17447.19k +sha1 613.78k 2982.93k 5446.44k 6889.46k 7424.86k +rmd160 501.23k 2405.68k 4367.25k 5503.61k 5915.80k +rc4 8167.75k 10429.44k 10839.12k 10929.50k 10772.30k +des cbc 2057.24k 2218.27k 2237.20k 2227.69k 2213.59k +des ede3 719.63k 727.11k 728.77k 719.56k 722.97k +idea cbc 827.67k 888.85k 898.06k 900.30k 898.75k +rc2 cbc 797.46k 862.53k 870.33k 872.58k 870.40k +blowfish cbc 3835.32k 4435.60k 4513.89k 4513.89k 4416.92k +cast cbc 2785.06k 3052.62k 3088.59k 3034.95k 3034.95k + sign verify sign/s verify/s +rsa 512 bits 0.0202s 0.0020s 49.4 500.2 +rsa 1024 bits 0.1030s 0.0063s 9.7 159.4 +rsa 2048 bits 0.6740s 0.0223s 1.5 44.9 +rsa 4096 bits 4.8970s 0.0844s 0.2 11.8 + sign verify sign/s verify/s +dsa 512 bits 0.0191s 0.0361s 52.4 27.7 +dsa 1024 bits 0.0587s 0.1167s 17.0 8.6 +dsa 2048 bits 0.2091s 0.4123s 4.8 2.4 diff --git a/node-v0.8.14/deps/openssl/openssl/times/586-100.w31 b/node-v0.8.14/deps/openssl/openssl/times/586-100.w31 new file mode 100644 index 0000000..d5b1c10 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/times/586-100.w31 @@ -0,0 +1,27 @@ +Pentium 100, Windows 3.1 DLL's, 16 bit C, 32bit assember. + +Running under Windows NT 4.0 Beta 2 + +SSLeay 0.6.4 20-Aug-1996 +built on Thu Aug 22 08:44:21 EST 1996 +options:bn(32,32) md2(char) rc4(idx,int) des(ptr,long) idea(short) +C flags:cl /ALw /Gx- /Gf /G2 /f- /Ocgnotb2 /W3 /WX -DL_ENDIAN /nologo -DWIN16 +The 'numbers' are in 1000s of bytes per second processed. +type 8 bytes 64 bytes 256 bytes 1024 bytes 8192 bytes +md2 45.83k 128.82k 180.17k 194.90k 198.59k +md5 224.82k 1038.19k 1801.68k 2175.47k 2330.17k +sha 105.11k 448.11k 739.48k 884.13k 944.66k +sha1 94.71k 402.99k 667.88k 795.58k 844.26k +rc4 1614.19k 1956.30k 2022.72k 2022.72k 2022.72k +des cfb 291.27k 318.14k 318.14k 318.14k 322.84k +des cbc 326.86k 356.17k 362.08k 362.08k 367.15k +des ede3 132.40k 139.57k 139.53k 139.37k 140.97k +idea cfb 265.33k 280.67k 280.67k 277.69k 281.27k +idea cbc 274.21k 302.01k 306.24k 306.24k 305.53k +rc2 cfb 264.79k 274.21k 274.78k 274.21k 274.21k +rc2 cbc 281.27k 306.24k 309.86k 305.53k 309.86k +rsa 512 bits 0.058s +rsa 1024 bits 0.280s +rsa 2048 bits 1.430s +rsa 4096 bits 10.600s + diff --git a/node-v0.8.14/deps/openssl/openssl/times/586-1002.lnx b/node-v0.8.14/deps/openssl/openssl/times/586-1002.lnx new file mode 100644 index 0000000..d830bce --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/times/586-1002.lnx @@ -0,0 +1,26 @@ +SSLeay 0.8.3e 30-Sep-1997 +built on Wed Oct 1 03:01:44 EST 1997 +options:bn(64,32) md2(int) rc4(idx,int) des(ptr,risc1,16,long) idea(int) blowfish(ptr2) +C flags:gcc -DL_ENDIAN -DTERMIO -DX86_ASM -O3 -fomit-frame-pointer -m486 -Wall -Wuninitialized +The 'numbers' are in 1000s of bytes per second processed. +type 8 bytes 64 bytes 256 bytes 1024 bytes 8192 bytes +md2 56.21k 156.57k 211.29k 231.77k 237.92k +mdc2 170.99k 191.70k 193.90k 195.58k 195.95k +md5 770.50k 3961.96k 7291.22k 9250.82k 9942.36k +sha 344.93k 1520.77k 2569.81k 3108.52k 3295.91k +sha1 326.20k 1423.74k 2385.15k 2870.95k 3041.96k +rc4 3672.88k 4309.65k 4374.41k 4408.66k 4355.41k +des cbc 1349.73k 1689.05k 1735.34k 1748.99k 1739.43k +des ede3 638.70k 704.00k 711.85k 714.41k 712.70k +idea cbc 619.55k 677.33k 683.26k 685.06k 685.40k +rc2 cbc 521.18k 571.20k 573.46k 578.90k 578.90k +blowfish cbc 2079.67k 2592.49k 2702.34k 2730.33k 2695.17k + sign verify +rsa 512 bits 0.0213s 0.0026s +rsa 1024 bits 0.1099s 0.0031s +rsa 2048 bits 0.7007s 0.0248s +rsa 4096 bits 5.0500s 0.0921s + sign verify +dsa 512 bits 0.0203s 0.0389s +dsa 1024 bits 0.0614s 0.1222s +dsa 2048 bits 0.2149s 0.4283s diff --git a/node-v0.8.14/deps/openssl/openssl/times/586p-100.lnx b/node-v0.8.14/deps/openssl/openssl/times/586p-100.lnx new file mode 100644 index 0000000..561eb31 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/times/586p-100.lnx @@ -0,0 +1,26 @@ +Pentium 100 - Linux 1.2.13 - gcc 2.7.2p +This is the pentium specific version of gcc + +SSLeay 0.6.4 20-Aug-1996 +built on Thu Aug 22 08:27:58 EST 1996 +options:bn(64,32) md2(char) rc4(idx,int) des(idx,long) idea(int) +C flags:gcc -DL_ENDIAN -DTERMIO -O6 -fomit-frame-pointer -mpentium -Wall +The 'numbers' are in 1000s of bytes per second processed. +type 8 bytes 64 bytes 256 bytes 1024 bytes 8192 bytes +md2 74.90k 208.43k 282.11k 309.59k 318.43k +md5 807.08k 4205.67k 7801.51k 9958.06k 10810.71k +sha 405.98k 1821.55k 3119.10k 3799.04k 4052.31k +sha1 389.13k 1699.50k 2852.78k 3437.57k 3656.36k +rc4 3621.15k 4130.07k 4212.74k 4228.44k 4213.42k +des cfb 794.39k 828.37k 831.74k 832.51k 832.85k +des cbc 817.68k 886.17k 894.72k 896.00k 892.93k +des ede3 308.83k 323.29k 324.61k 324.95k 324.95k +idea cfb 690.41k 715.39k 718.51k 719.19k 718.17k +idea cbc 696.80k 760.60k 767.32k 768.68k 770.05k +rc2 cfb 619.91k 639.74k 642.30k 642.73k 641.71k +rc2 cbc 631.99k 671.42k 676.35k 676.18k 677.21k +rsa 512 bits 0.025s +rsa 1024 bits 0.123s +rsa 2048 bits 0.756s +rsa 4096 bits 5.365s + diff --git a/node-v0.8.14/deps/openssl/openssl/times/686-200.bsd b/node-v0.8.14/deps/openssl/openssl/times/686-200.bsd new file mode 100644 index 0000000..f23c580 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/times/686-200.bsd @@ -0,0 +1,25 @@ +Pentium Pro 200mhz +FreeBSD 2.1.5 +gcc 2.7.2.2 + +SSLeay 0.7.0 30-Jan-1997 +built on Tue Apr 22 12:14:36 EST 1997 +options:bn(64,32) md2(int) rc4(idx,int) des(ptr,risc1,16,long) idea(int) blowfish(ptr2) +C flags:gcc -DTERMIOS -D_ANSI_SOURCE -fomit-frame-pointer -O3 -m486 -Wall +The 'numbers' are in 1000s of bytes per second processed. +type 8 bytes 64 bytes 256 bytes 1024 bytes 8192 bytes +md2 130.99k 367.68k 499.09k 547.04k 566.50k +md5 1924.98k 8293.50k 13464.41k 16010.39k 16820.68k +sha 1250.75k 5330.43k 8636.88k 10227.36k 10779.14k +sha1 1071.55k 4572.50k 7459.98k 8791.96k 9341.61k +rc4 10724.22k 14546.25k 15240.18k 15259.50k 15265.63k +des cbc 3309.11k 3883.01k 3968.25k 3971.86k 3979.14k +des ede3 1442.98k 1548.33k 1562.48k 1562.00k 1563.33k +idea cbc 2195.69k 2506.39k 2529.59k 2545.66k 2546.54k +rc2 cbc 806.00k 833.52k 837.58k 838.52k 836.69k +blowfish cbc 4687.34k 5949.97k 6182.43k 6248.11k 6226.09k +rsa 512 bits 0.010s +rsa 1024 bits 0.045s +rsa 2048 bits 0.260s +rsa 4096 bits 1.690s + diff --git a/node-v0.8.14/deps/openssl/openssl/times/686-200.lnx b/node-v0.8.14/deps/openssl/openssl/times/686-200.lnx new file mode 100644 index 0000000..a10cc2f --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/times/686-200.lnx @@ -0,0 +1,26 @@ +SSLeay 0.8.2a 04-Sep-1997 +built on Fri Sep 5 17:37:05 EST 1997 +options:bn(64,32) md2(int) rc4(idx,int) des(ptr,risc1,16,long) idea(int) blowfish(ptr2) C flags:gcc -DL_ENDIAN -DTERMIO -O3 -fomit-frame-pointer -m486 -Wall -Wuninitialized +The 'numbers' are in 1000s of bytes per second processed. +type 8 bytes 64 bytes 256 bytes 1024 bytes 8192 bytes +md2 131.02k 368.41k 500.57k 549.21k 566.09k +mdc2 535.60k 589.10k 595.88k 595.97k 594.54k +md5 1801.53k 9674.77k 17484.03k 21849.43k 23592.96k +sha 1261.63k 5533.25k 9285.63k 11187.88k 11913.90k +sha1 1103.13k 4782.53k 7933.78k 9472.34k 10070.70k +rc4 10722.53k 14443.93k 15215.79k 15299.24k 15219.59k +des cbc 3286.57k 3827.73k 3913.39k 3931.82k 3926.70k +des ede3 1443.50k 1549.08k 1561.17k 1566.38k 1564.67k +idea cbc 2203.64k 2508.16k 2538.33k 2543.62k 2547.71k +rc2 cbc 1430.94k 1511.59k 1524.82k 1527.13k 1523.33k +blowfish cbc 4716.07k 5965.82k 6190.17k 6243.67k 6234.11k + sign verify +rsa 512 bits 0.0100s 0.0011s +rsa 1024 bits 0.0451s 0.0012s +rsa 2048 bits 0.2605s 0.0086s +rsa 4096 bits 1.6883s 0.0302s + sign verify +dsa 512 bits 0.0083s 0.0156s +dsa 1024 bits 0.0228s 0.0454s +dsa 2048 bits 0.0719s 0.1446s + diff --git a/node-v0.8.14/deps/openssl/openssl/times/686-200.nt b/node-v0.8.14/deps/openssl/openssl/times/686-200.nt new file mode 100644 index 0000000..c8cbaa0 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/times/686-200.nt @@ -0,0 +1,24 @@ +built on Tue May 13 08:24:51 EST 1997 +options:bn(64,32) md2(char) rc4(idx,int) des(ptr,risc1,16,long) idea(int) blowfi +sh(ptr2) +C flags not available +The 'numbers' are in 1000s of bytes per second processed. +type 8 bytes 64 bytes 256 bytes 1024 bytes 8192 bytes +md2 156.39k 427.99k 576.14k 628.36k 647.27k +md5 2120.48k 10255.02k 18396.07k 22795.13k 24244.53k +sha 1468.59k 6388.89k 10686.12k 12826.62k 13640.01k +sha1 1393.46k 6013.34k 9974.56k 11932.59k 12633.45k +rc4 13833.46k 19275.29k 20321.24k 20281.93k 20520.08k +des cbc 3382.50k 4104.02k 4152.78k 4194.30k 4194.30k +des ede3 1465.51k 1533.00k 1549.96k 1553.29k 1570.29k +idea cbc 2579.52k 3079.52k 3130.08k 3153.61k 3106.89k +rc2 cbc 1204.57k 1276.42k 1285.81k 1289.76k 1285.81k +blowfish cbc 5229.81k 6374.32k 6574.14k 6574.14k 6594.82k +rsa 512 bits 0.008s 0.001 +rsa 1024 bits 0.038s 0.001 +rsa 2048 bits 0.231s 0.008 +rsa 4096 bits 1.540s 0.027 +dsa 512 bits 0.007s 0.013 +dsa 1024 bits 0.021s 0.040 +dsa 2048 bits 0.066s 0.130 + diff --git a/node-v0.8.14/deps/openssl/openssl/times/L1 b/node-v0.8.14/deps/openssl/openssl/times/L1 new file mode 100644 index 0000000..09253d7 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/times/L1 @@ -0,0 +1,27 @@ +SSLeay 0.8.3ad 27-Oct-1997 +built on Wed Oct 29 00:36:17 EST 1997 +options:bn(64,32) md2(int) rc4(idx,int) des(ptr,risc1,16,long) idea(int) blowfish(ptr2) +C flags:gcc -DL_ENDIAN -DTERMIO -DBN_ASM -O3 -fomit-frame-pointer -m486 -Wall -Wuninitialized -DMD5_ASM -DSHA1_ASM +The 'numbers' are in 1000s of bytes per second processed. +type 8 bytes 64 bytes 256 bytes 1024 bytes 8192 bytes +md2 56.16k 156.50k 211.46k 231.77k 238.71k +mdc2 183.37k 205.21k 205.57k 209.92k 207.53k +md5 1003.65k 5605.56k 11628.54k 15887.70k 17522.69k +hmac(md5) 411.24k 2803.46k 7616.94k 13475.84k 16864.60k +sha1 542.66k 2843.50k 5320.53k 6833.49k 7389.18k +rc4 3677.15k 4313.73k 4407.89k 4429.82k 4404.57k +des cbc 1787.94k 2174.51k 2236.76k 2249.73k 2230.95k +des ede3 719.46k 777.26k 784.81k 780.29k 783.70k +idea cbc 619.56k 677.89k 684.12k 685.40k 685.40k +rc2 cbc 537.51k 573.93k 578.47k 579.24k 578.90k +blowfish cbc 3226.76k 4221.65k 4424.19k 4468.39k 4377.26k +cast cbc 2866.13k 3165.35k 3263.15k 3287.04k 3233.11k + sign verify +rsa 512 bits 0.0212s 0.0021s +rsa 1024 bits 0.1072s 0.0064s +rsa 2048 bits 0.6853s 0.0222s +rsa 4096 bits 4.9300s 0.0848s + sign verify +dsa 512 bits 0.0200s 0.0380s +dsa 1024 bits 0.0600s 0.1180s +dsa 2048 bits 0.2110s 0.4221s diff --git a/node-v0.8.14/deps/openssl/openssl/times/R10000.t b/node-v0.8.14/deps/openssl/openssl/times/R10000.t new file mode 100644 index 0000000..6b3874c --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/times/R10000.t @@ -0,0 +1,24 @@ +IRIX 6.2 - R10000 195mhz +SLeay 0.6.5a 06-Dec-1996 +built on Tue Dec 24 03:51:45 EST 1996 +options:bn(32,32) md2(int) rc4(ptr,int) des(ptr,risc2,16,long) idea(int) +C flags:cc -O2 -DTERMIOS -DB_ENDIAN +The 'numbers' are in 1000s of bytes per second processed. +type 8 bytes 64 bytes 256 bytes 1024 bytes 8192 bytes +md2 156.34k 424.03k 571.88k 628.88k 646.01k +md5 1885.02k 8181.72k 13440.53k 16020.60k 16947.54k +sha 1587.12k 7022.05k 11951.24k 14440.12k 15462.74k +sha1 1413.13k 6215.86k 10571.16k 12736.22k 13628.51k +rc4 10556.28k 11974.08k 12077.10k 12111.38k 12103.20k +des cfb 2977.71k 3252.27k 3284.36k 3302.66k 3290.54k +des cbc 3298.31k 3704.96k 3771.30k 3730.73k 3778.80k +des ede3 1278.28k 1328.82k 1342.66k 1339.82k 1343.27k +idea cfb 2843.34k 3138.04k 3180.95k 3176.46k 3188.54k +idea cbc 3115.21k 3558.03k 3590.61k 3591.24k 3601.18k +rc2 cfb 2006.66k 2133.33k 2149.03k 2159.36k 2149.71k +rc2 cbc 2167.07k 2315.30k 2338.05k 2329.34k 2333.90k +rsa 512 bits 0.008s +rsa 1024 bits 0.043s +rsa 2048 bits 0.280s +rsa 4096 bits 2.064s + diff --git a/node-v0.8.14/deps/openssl/openssl/times/R4400.t b/node-v0.8.14/deps/openssl/openssl/times/R4400.t new file mode 100644 index 0000000..af8848f --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/times/R4400.t @@ -0,0 +1,26 @@ +IRIX 5.3 +R4400 200mhz +cc -O2 +SSLeay 0.6.5a 06-Dec-1996 +built on Mon Dec 23 11:51:11 EST 1996 +options:bn(32,32) md2(int) rc4(ptr,int) des(ptr,risc2,16,long) idea(int) +C flags:cc -O2 -DTERMIOS -DB_ENDIAN +The 'numbers' are in 1000s of bytes per second processed. +type 8 bytes 64 bytes 256 bytes 1024 bytes 8192 bytes +md2 100.62k 280.25k 380.15k 416.02k 428.82k +md5 828.62k 3525.05k 6311.98k 7742.51k 8328.04k +sha 580.04k 2513.74k 4251.73k 5101.04k 5394.80k +sha1 520.23k 2382.94k 4107.82k 5024.62k 5362.56k +rc4 5871.53k 6323.08k 6357.49k 6392.04k 6305.45k +des cfb 1016.76k 1156.72k 1176.59k 1180.55k 1181.65k +des cbc 1016.38k 1303.81k 1349.10k 1359.41k 1356.62k +des ede3 607.39k 650.74k 655.11k 657.52k 654.18k +idea cfb 1296.10k 1348.66k 1353.80k 1358.75k 1355.40k +idea cbc 1453.90k 1554.68k 1567.84k 1569.89k 1573.57k +rc2 cfb 1199.86k 1251.69k 1253.57k 1259.56k 1251.31k +rc2 cbc 1334.60k 1428.55k 1441.89k 1445.42k 1441.45k +rsa 512 bits 0.024s +rsa 1024 bits 0.125s +rsa 2048 bits 0.806s +rsa 4096 bits 5.800s + diff --git a/node-v0.8.14/deps/openssl/openssl/times/aix.t b/node-v0.8.14/deps/openssl/openssl/times/aix.t new file mode 100644 index 0000000..4f24e39 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/times/aix.t @@ -0,0 +1,34 @@ +from Paco Garcia +This machine is a Bull Estrella Minitower Model MT604-100 +Processor : PPC604 +P.Speed : 100Mhz +Data/Instr Cache : 16 K +L2 Cache : 256 K +PCI BUS Speed : 33 Mhz +TransfRate PCI : 132 MB/s +Memory : 96 MB + +AIX 4.1.4 + +SSLeay 0.6.6 14-Jan-1997 +built on Mon Jan 13 21:36:03 CUT 1997 +options:bn(64,32) md2(int) rc4(ptr,char) des(idx,cisc,4,long) idea(int) blowfish +(idx) +C flags:cc -O -DAIX -DB_ENDIAN +The 'numbers' are in 1000s of bytes per second processed. +type 8 bytes 64 bytes 256 bytes 1024 bytes 8192 bytes +md2 53.83k 147.46k 197.63k 215.72k 221.70k +md5 1278.13k 5354.77k 8679.60k 10195.09k 10780.56k +sha 1055.34k 4600.37k 7721.30k 9298.94k 9868.63k +sha1 276.90k 1270.25k 2187.95k 2666.84k 2850.82k +rc4 4660.57k 5268.93k 5332.48k 5362.47k 5346.65k +des cbc 1774.16k 1981.10k 1979.56k 2032.71k 1972.25k +des ede3 748.81k 781.42k 785.66k 785.75k 780.84k +idea cbc 2066.19k 2329.58k 2378.91k 2379.86k 2380.89k +rc2 cbc 1278.53k 1379.69k 1389.99k 1393.66k 1389.91k +blowfish cbc 2812.91k 3307.90k 3364.91k 3386.37k 3374.32k +rsa 512 bits 0.019s +rsa 1024 bits 0.096s +rsa 2048 bits 0.614s +rsa 4096 bits 4.433s + diff --git a/node-v0.8.14/deps/openssl/openssl/times/aixold.t b/node-v0.8.14/deps/openssl/openssl/times/aixold.t new file mode 100644 index 0000000..0b51412 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/times/aixold.t @@ -0,0 +1,23 @@ +SSLeay 0.7.3r 20-May-1997 +built on Mon Jun 2 04:06:32 EST 1997 +options:bn(64,32) md2(int) rc4(ptr,char) des(idx,cisc,4,long) idea(int) blowfish(idx) +C flags:cc -O -DAIX -DB_ENDIAN +The 'numbers' are in 1000s of bytes per second processed. +type 8 bytes 64 bytes 256 bytes 1024 bytes 8192 bytes +md2 19.09k 52.47k 71.23k 77.49k 78.93k +md5 214.56k 941.21k 1585.43k 1883.12k 1988.70k +sha 118.35k 521.65k 860.28k 1042.27k 1100.46k +sha1 109.52k 478.98k 825.90k 995.48k 1049.69k +rc4 1263.63k 1494.24k 1545.70k 1521.66k 1518.99k +des cbc 259.62k 286.55k 287.15k 288.15k 289.45k +des ede3 104.92k 107.88k 109.27k 109.25k 109.96k +idea cbc 291.63k 320.07k 319.40k 320.51k 318.27k +rc2 cbc 220.04k 237.76k 241.44k 245.90k 244.08k +blowfish cbc 407.95k 474.83k 480.99k 485.71k 481.07k +rsa 512 bits 0.157s 0.019 +rsa 1024 bits 0.908s 0.023 +rsa 2048 bits 6.225s 0.218 +rsa 4096 bits 46.500s 0.830 +dsa 512 bits 0.159s 0.312 +dsa 1024 bits 0.536s 1.057 +dsa 2048 bits 1.970s 3.977 diff --git a/node-v0.8.14/deps/openssl/openssl/times/alpha.t b/node-v0.8.14/deps/openssl/openssl/times/alpha.t new file mode 100644 index 0000000..3a7c6c4 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/times/alpha.t @@ -0,0 +1,81 @@ +SSLeay-051 Alpha gcc -O3 64Bit (assember bn_mul) +type 8 bytes 64 bytes 256 bytes 1024 bytes 8192 bytes +md2 44.40k 121.56k 162.73k 179.20k 185.01k +md5 780.85k 3278.53k 5281.52k 6327.98k 6684.67k +sha 501.40k 2249.19k 3855.27k 4801.19k 5160.96k +sha-1 384.99k 1759.72k 3113.64k 3946.92k 4229.80k +rc4 3505.05k 3724.54k 3723.78k 3555.33k 3694.68k +des cfb 946.96k 1015.27k 1021.87k 1033.56k 1037.65k +des cbc 1001.24k 1220.20k 1243.31k 1272.73k 1265.87k +des ede3 445.34k 491.65k 500.53k 502.10k 502.44k +idea cfb 643.53k 667.49k 663.81k 666.28k 664.51k +idea cbc 650.42k 735.41k 733.27k 742.74k 745.47k +rsa 512 bits 0.031s +rsa 1024 bits 0.141s +rsa 2048 bits 0.844s +rsa 4096 bits 6.033s + +SSLeay-051 Alpha cc -O2 64bit (assember bn_mul) +type 8 bytes 64 bytes 256 bytes 1024 bytes 8192 bytes +md2 45.37k 122.86k 165.97k 182.95k 188.42k +md5 842.42k 3629.93k 5916.76k 7039.17k 7364.61k +sha 498.93k 2197.23k 3895.60k 4756.48k 5132.13k +sha-1 382.02k 1757.21k 3112.53k 3865.23k 4128.77k +rc4 2975.25k 3049.33k 3180.97k 3214.68k 3424.26k +des cfb 901.55k 990.83k 1006.08k 1011.19k 1004.89k +des cbc 947.84k 1127.84k 1163.67k 1162.24k 1157.80k +des ede3 435.62k 485.57k 493.67k 491.52k 491.52k +idea cfb 629.31k 648.66k 647.77k 648.53k 649.90k +idea cbc 565.15k 608.00k 613.46k 613.38k 617.13k +rsa 512 bits 0.030s +rsa 1024 bits 0.141s +rsa 2048 bits 0.854s +rsa 4096 bits 6.067s + +des cfb 718.28k 822.64k 833.11k 836.27k 841.05k +des cbc 806.10k 951.42k 975.83k 983.73k 991.23k +des ede3 329.50k 379.11k 387.95k 387.41k 388.33k + +des cfb 871.62k 948.65k 951.81k 953.00k 955.58k +des cbc 953.60k 1174.27k 1206.70k 1216.10k 1216.44k +des ede3 349.34k 418.05k 427.26k 429.74k 431.45k + + + + +SSLeay-045c Alpha gcc -O3 64Bit +type 8 bytes 64 bytes 256 bytes 1024 bytes 8192 bytes +md2 44.95k 122.22k 164.27k 180.62k 184.66k +md5 808.71k 3371.95k 5415.68k 6385.66k 6684.67k +sha 493.68k 2162.05k 3725.82k 4552.02k 4838.74k +rc4 3317.32k 3649.09k 3728.30k 3744.09k 3691.86k +cfb des 996.45k 1050.77k 1058.30k 1059.16k 1064.96k +cbc des 1096.52k 1255.49k 1282.13k 1289.90k 1299.80k +ede3 des 482.14k 513.51k 518.66k 520.19k 521.39k +cfb idea 519.90k 533.40k 535.21k 535.55k 535.21k +cbc idea 619.34k 682.21k 688.04k 689.15k 690.86k +rsa 512 bits 0.050s +rsa 1024 bits 0.279s +rsa 2048 bits 1.908s +rsa 4096 bits 14.750s + +type 8 bytes 64 bytes 256 bytes 1024 bytes 8192 bytes +md2 37.31k 102.77k 137.64k 151.55k 155.78k +md5 516.65k 2535.21k 4655.72k 5859.66k 6343.34k +rc4 3519.61k 3707.01k 3746.86k 3755.39k 3675.48k +cfb des 780.27k 894.68k 913.10k 921.26k 922.97k +cbc des 867.54k 1040.13k 1074.17k 1075.54k 1084.07k +ede3 des 357.19k 397.36k 398.08k 402.28k 401.41k +cbc idea 646.53k 686.44k 694.03k 691.20k 693.59k +rsa 512 bits 0.046s +rsa 1024 bits 0.270s +rsa 2048 bits 1.858s +rsa 4096 bits 14.350s + +md2 C 37.83k 103.17k 137.90k 150.87k 155.37k +md2 L 37.30k 102.04k 139.01k 152.74k 155.78k +rc4 I 3532.24k 3718.08k 3750.83k 3768.78k 3694.59k +rc4 CI 2662.97k 2873.26k 2907.22k 2920.63k 2886.31k +rc4 LI 3514.63k 3738.72k 3747.41k 3752.96k 3708.49k +cbc idea S 619.01k 658.68k 661.50k 662.53k 663.55k +cbc idea L 645.69k 684.22k 694.55k 692.57k 690.86k diff --git a/node-v0.8.14/deps/openssl/openssl/times/alpha400.t b/node-v0.8.14/deps/openssl/openssl/times/alpha400.t new file mode 100644 index 0000000..079e0d1 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/times/alpha400.t @@ -0,0 +1,25 @@ +Alpha EV5.6 (21164A) 400mhz + +SSLeay 0.7.3r 20-May-1997 +built on Mon Jun 2 03:39:58 EST 1997 +options:bn(64,64) md2(int) rc4(ptr,int) des(idx,cisc,4,long) idea(int) blowfish(idx) +C flags:cc -arch host -tune host -fast -std -O4 -inline speed +The 'numbers' are in 1000s of bytes per second processed. +type 8 bytes 64 bytes 256 bytes 1024 bytes 8192 bytes +md2 274.98k 760.96k 1034.27k 1124.69k 1148.69k +md5 2524.46k 11602.60k 19838.81k 24075.26k 25745.10k +sha 1848.46k 8335.66k 14232.49k 17247.91k 18530.30k +sha1 1639.67k 7336.53k 12371.80k 14807.72k 15870.63k +rc4 17950.93k 19390.66k 19652.44k 19700.39k 19412.31k +des cbc 4018.59k 4872.06k 4988.76k 5003.26k 4995.73k +des ede3 1809.11k 1965.67k 1984.26k 1986.90k 1982.46k +idea cbc 2848.82k 3204.33k 3250.26k 3257.34k 3260.42k +rc2 cbc 3766.08k 4349.50k 4432.21k 4448.94k 4448.26k +blowfish cbc 6694.88k 9042.35k 9486.93k 9598.98k 9624.91k +rsa 512 bits 0.003s 0.000 +rsa 1024 bits 0.013s 0.000 +rsa 2048 bits 0.081s 0.003 +rsa 4096 bits 0.577s 0.011 +dsa 512 bits 0.003s 0.005 +dsa 1024 bits 0.007s 0.014 +dsa 2048 bits 0.025s 0.050 diff --git a/node-v0.8.14/deps/openssl/openssl/times/cyrix100.lnx b/node-v0.8.14/deps/openssl/openssl/times/cyrix100.lnx new file mode 100644 index 0000000..010a221 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/times/cyrix100.lnx @@ -0,0 +1,22 @@ +SSLeay 0.6.6 06-Dec-1996 +built on Fri Dec 6 10:05:20 GMT 1996 +options:bn(64,32) md2(char) rc4(idx,int) des(idx,risc,16,long) idea(int) +C flags:gcc -DL_ENDIAN -DTERMIO -O3 -fomit-frame-pointer -m486 -Wall -Wuninitialized +The 'numbers' are in 1000s of bytes per second processed. +type 8 bytes 64 bytes 256 bytes 1024 bytes 8192 bytes +md2 36.77k 102.48k 138.00k 151.57k 155.78k +md5 513.59k 2577.22k 4623.51k 5768.99k 6214.53k +sha 259.89k 1105.45k 1814.97k 2156.16k 2292.13k +sha1 242.43k 1040.95k 1719.44k 2049.74k 2164.64k +rc4 1984.48k 2303.41k 2109.37k 2071.47k 1985.61k +des cfb 712.08k 758.29k 753.17k 752.06k 748.67k +des cbc 787.37k 937.64k 956.77k 961.61k 957.54k +des ede3 353.97k 377.28k 379.99k 379.34k 379.11k +idea cfb 403.80k 418.50k 416.60k 415.78k 415.03k +idea cbc 426.54k 466.40k 471.31k 472.67k 473.14k +rc2 cfb 405.15k 420.05k 418.16k 416.72k 416.36k +rc2 cbc 428.21k 468.43k 473.09k 472.59k 474.70k +rsa 512 bits 0.040s +rsa 1024 bits 0.195s +rsa 2048 bits 1.201s +rsa 4096 bits 8.700s diff --git a/node-v0.8.14/deps/openssl/openssl/times/dgux-x86.t b/node-v0.8.14/deps/openssl/openssl/times/dgux-x86.t new file mode 100644 index 0000000..70635c5 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/times/dgux-x86.t @@ -0,0 +1,23 @@ +version:SSLeay 0.5.2c 15-May-1996 +built Fri Jun 14 19:47:04 EST 1996 +options:bn(LLONG,thirty_two) md2(CHAR) rc4(IDX,int) des(ary,long) idea(int) +C flags:gcc -O3 -fomit-frame-pointer -DL_ENDIAN + +type 8 bytes 64 bytes 256 bytes 1024 bytes 8192 bytes +md2 113.86k 316.48k 428.36k 467.63k 481.56k +md5 1001.99k 5037.99k 9545.94k 12036.95k 11800.38k +sha 628.77k 2743.48k 5113.42k 6206.99k 6165.42k +sha1 583.83k 2638.66k 4538.85k 5532.09k 5917.04k +rc4 5493.27k 6369.39k 6511.30k 6577.83k 6486.73k +des cfb 1219.01k 1286.06k 1299.33k 1288.87k 1381.72k +des cbc 1360.58k 1469.04k 1456.96k 1454.08k 1513.57k +des ede3 544.45k 567.84k 568.99k 570.37k 566.09k +idea cfb 1012.39k 1056.30k 1063.52k 989.17k 863.24k +idea cbc 985.36k 1090.44k 1105.92k 1108.65k 1090.17k +rc2 cfb 963.86k 979.06k 995.30k 937.35k 827.39k +rc2 cbc 951.72k 1042.11k 1049.60k 1047.21k 1059.11k +rsa 512 bits 0.032s +rsa 1024 bits 0.159s +rsa 2048 bits 1.025s +rsa 4096 bits 7.270s + diff --git a/node-v0.8.14/deps/openssl/openssl/times/dgux.t b/node-v0.8.14/deps/openssl/openssl/times/dgux.t new file mode 100644 index 0000000..c7f7564 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/times/dgux.t @@ -0,0 +1,17 @@ +type 8 bytes 64 bytes 256 bytes 1024 bytes 8192 bytes +md2 38.54k 106.28k 144.00k 157.46k 161.72k +md5 323.23k 1471.62k 2546.11k 3100.20k 3309.57k +rc4 I 1902.74k 2055.20k 2080.42k 2077.88k 2065.46k +cfb des 456.23k 475.22k 481.79k 488.42k 487.17k +cbc des 484.30k 537.50k 553.09k 558.08k 558.67k +ede3 des 199.97k 209.05k 211.03k 211.85k 212.78k +cbc idea 478.50k 519.33k 523.42k 525.09k 526.44k +rsa 512 bits 0.159s !RSA_LLONG +rsa 1024 bits 1.053s +rsa 2048 bits 7.600s +rsa 4096 bits 59.760s + +md2 C 30.53k 83.58k 112.84k 123.22k 126.24k +rc4 1844.56k 1975.50k 1997.73k 1994.95k 1984.88k +rc4 C 1800.09k 1968.85k 1995.20k 1992.36k 1996.80k +rc4 CI 1830.81k 2035.75k 2067.28k 2070.23k 2062.77k diff --git a/node-v0.8.14/deps/openssl/openssl/times/hpux-acc.t b/node-v0.8.14/deps/openssl/openssl/times/hpux-acc.t new file mode 100644 index 0000000..0c0e936 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/times/hpux-acc.t @@ -0,0 +1,25 @@ +HPUX 887 + +SSLeay 0.7.3r 20-May-1997 +built on Mon Jun 2 02:59:45 EST 1997 +options:bn(32,32) md2(int) rc4(ptr,int) des(ptr,risc1,16,long) idea(int) blowfish(idx) +C flags:cc -DB_ENDIAN -D_HPUX_SOURCE -Aa -Ae +ESlit +O4 -Wl,-a,archive +The 'numbers' are in 1000s of bytes per second processed. +type 8 bytes 64 bytes 256 bytes 1024 bytes 8192 bytes +md2 58.99k 166.85k 225.07k 247.21k 253.76k +md5 639.22k 2726.98k 4477.25k 5312.69k 5605.20k +sha 381.08k 1661.49k 2793.84k 3368.86k 3581.23k +sha1 349.54k 1514.56k 2536.63k 3042.59k 3224.39k +rc4 2891.10k 4238.01k 4464.11k 4532.49k 4545.87k +des cbc 717.05k 808.76k 820.14k 821.97k 821.96k +des ede3 288.21k 303.50k 303.69k 305.82k 305.14k +idea cbc 325.83k 334.36k 335.89k 336.61k 333.43k +rc2 cbc 793.00k 915.81k 926.69k 933.28k 929.53k +blowfish cbc 1561.91k 2051.97k 2122.65k 2139.40k 2145.92k +rsa 512 bits 0.031s 0.004 +rsa 1024 bits 0.164s 0.004 +rsa 2048 bits 1.055s 0.037 +rsa 4096 bits 7.600s 0.137 +dsa 512 bits 0.029s 0.057 +dsa 1024 bits 0.092s 0.177 +dsa 2048 bits 0.325s 0.646 diff --git a/node-v0.8.14/deps/openssl/openssl/times/hpux-kr.t b/node-v0.8.14/deps/openssl/openssl/times/hpux-kr.t new file mode 100644 index 0000000..ad4a0ad --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/times/hpux-kr.t @@ -0,0 +1,23 @@ +SSLeay 0.7.3r 20-May-1997 +built on Mon Jun 2 02:17:35 EST 1997 +options:bn(32,32) md2(int) rc4(ptr,int) des(ptr,cisc,16,long) idea(int) blowfish(idx) +C flags:cc -DB_ENDIAN -DNOCONST -DNOPROTO -D_HPUX_SOURCE +The 'numbers' are in 1000s of bytes per second processed. +type 8 bytes 64 bytes 256 bytes 1024 bytes 8192 bytes +md2 35.30k 98.36k 133.41k 146.34k 150.69k +md5 391.20k 1737.31k 2796.65k 3313.75k 3503.74k +sha 189.55k 848.14k 1436.72k 1735.87k 1848.03k +sha1 175.30k 781.14k 1310.32k 1575.61k 1675.81k +rc4 2070.55k 2501.47k 2556.65k 2578.34k 2584.91k +des cbc 465.13k 536.85k 545.87k 547.86k 548.89k +des ede3 190.05k 200.99k 202.31k 202.22k 202.75k +idea cbc 263.44k 277.77k 282.13k 281.51k 283.15k +rc2 cbc 448.37k 511.39k 519.54k 522.00k 521.31k +blowfish cbc 839.98k 1097.70k 1131.16k 1145.64k 1144.67k +rsa 512 bits 0.048s 0.005 +rsa 1024 bits 0.222s 0.006 +rsa 2048 bits 1.272s 0.042 +rsa 4096 bits 8.445s 0.149 +dsa 512 bits 0.041s 0.077 +dsa 1024 bits 0.111s 0.220 +dsa 2048 bits 0.363s 0.726 diff --git a/node-v0.8.14/deps/openssl/openssl/times/hpux.t b/node-v0.8.14/deps/openssl/openssl/times/hpux.t new file mode 100644 index 0000000..dcf7615 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/times/hpux.t @@ -0,0 +1,86 @@ +HP-UX A.09.05 9000/712 + +SSLeay 0.6.6 14-Jan-1997 +built on Tue Jan 14 16:36:31 WET 1997 +options:bn(32,32) md2(int) rc4(ptr,int) des(ptr,risc1,16,long) idea(int) +blowfish(idx) +C flags:cc -DB_ENDIAN -D_HPUX_SOURCE -Aa +ESlit +O2 -Wl,-a,archive +The 'numbers' are in 1000s of bytes per second processed. +type 8 bytes 64 bytes 256 bytes 1024 bytes 8192 bytes +md2 66.56k 184.92k 251.82k 259.86k 282.62k +md5 615.54k 2805.92k 4764.30k 5724.21k 6084.39k +sha 358.23k 1616.46k 2781.50k 3325.72k 3640.89k +sha1 327.50k 1497.98k 2619.44k 3220.26k 3460.85k +rc4 3500.47k 3890.99k 3943.81k 3883.74k 3900.02k +des cbc 742.65k 871.66k 887.15k 891.21k 895.40k +des ede3 302.42k 322.50k 324.46k 326.66k 326.05k +idea cbc 664.41k 755.87k 765.61k 772.70k 773.69k +rc2 cbc 798.78k 931.04k 947.69k 950.31k 952.04k +blowfish cbc 1353.32k 1932.29k 2021.93k 2047.02k 2053.66k +rsa 512 bits 0.059s +rsa 1024 bits 0.372s +rsa 2048 bits 2.697s +rsa 4096 bits 20.790s + +SSLeay 0.6.6 14-Jan-1997 +built on Tue Jan 14 15:37:30 WET 1997 +options:bn(64,32) md2(int) rc4(ptr,int) des(ptr,risc1,16,long) idea(int) +blowfish(idx) +C flags:gcc -DB_ENDIAN -O3 +The 'numbers' are in 1000s of bytes per second processed. +type 8 bytes 64 bytes 256 bytes 1024 bytes 8192 bytes +md2 44.91k 122.57k 167.71k 183.89k 190.24k +md5 532.50k 2316.27k 3965.72k 4740.11k 5055.06k +sha 363.76k 1684.09k 2978.53k 3730.86k 3972.72k +sha1 385.76k 1743.53k 2997.69k 3650.74k 3899.08k +rc4 3178.84k 3621.31k 3672.71k 3684.01k 3571.54k +des cbc 733.00k 844.70k 863.28k 863.72k 868.73k +des ede3 289.99k 308.94k 310.11k 309.64k 312.08k +idea cbc 624.07k 713.91k 724.76k 723.35k 725.13k +rc2 cbc 704.34k 793.39k 804.25k 805.99k 782.63k +blowfish cbc 1371.24k 1823.66k 1890.05k 1915.51k 1920.12k +rsa 512 bits 0.030s +rsa 1024 bits 0.156s +rsa 2048 bits 1.113s +rsa 4096 bits 7.480s + + +HPUX B.10.01 V 9000/887 - HP92453-01 A.10.11 HP C Compiler +SSLeay 0.5.2 - -Aa +ESlit +Oall +O4 -Wl,-a,archive + +HPUX A.09.04 B 9000/887 + +ssleay 0.5.1 gcc v 2.7.0 -O3 -mpa-risc-1-1 +type 8 bytes 64 bytes 256 bytes 1024 bytes 8192 bytes +md2 53.00k 166.81k 205.66k 241.95k 242.20k +md5 743.22k 3128.44k 6031.85k 6142.07k 7025.26k +sha 481.30k 2008.24k 3361.31k 3985.07k 4180.74k +sha-1 463.60k 1916.15k 3139.24k 3786.27k 3997.70k +rc4 3708.61k 4125.16k 4547.53k 4206.21k 4390.07k +des cfb 665.91k 705.97k 698.48k 694.25k 666.08k +des cbc 679.80k 741.90k 769.85k 747.62k 719.47k +des ede3 264.31k 270.22k 265.63k 273.07k 273.07k +idea cfb 635.91k 673.40k 605.60k 699.53k 672.36k +idea cbc 705.85k 774.63k 750.60k 715.83k 721.50k +rsa 512 bits 0.066s +rsa 1024 bits 0.372s +rsa 2048 bits 2.177s +rsa 4096 bits 16.230s + +HP92453-01 A.09.61 HP C Compiler +ssleay 0.5.1 cc -Ae +ESlit +Oall -Wl,-a,archive +type 8 bytes 64 bytes 256 bytes 1024 bytes 8192 bytes +md2 58.69k 163.30k 213.57k 230.40k 254.23k +md5 608.60k 2596.82k 3871.43k 4684.10k 4763.88k +sha 343.26k 1482.43k 2316.80k 2766.27k 2860.26k +sha-1 319.15k 1324.13k 2106.03k 2527.82k 2747.95k +rc4 2467.47k 3374.41k 3265.49k 3354.39k 3368.55k +des cfb 812.05k 814.90k 851.20k 819.20k 854.56k +des cbc 836.35k 994.06k 916.02k 1020.01k 988.14k +des ede3 369.78k 389.15k 401.01k 382.94k 408.03k +idea cfb 290.40k 298.06k 286.11k 296.92k 299.46k +idea cbc 301.30k 297.72k 304.34k 300.10k 309.70k +rsa 512 bits 0.350s +rsa 1024 bits 2.635s +rsa 2048 bits 19.930s + diff --git a/node-v0.8.14/deps/openssl/openssl/times/p2.w95 b/node-v0.8.14/deps/openssl/openssl/times/p2.w95 new file mode 100644 index 0000000..82d1e55 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/times/p2.w95 @@ -0,0 +1,22 @@ +The 'numbers' are in 1000s of bytes per second processed. +type 8 bytes 64 bytes 256 bytes 1024 bytes 8192 bytes +md2 235.90k 652.30k 893.36k 985.74k 985.74k +mdc2 779.61k 816.81k 825.65k 816.01k 825.65k +md5 2788.77k 13508.23k 24672.38k 30504.03k 33156.55k +sha 1938.22k 8397.01k 14122.24k 16980.99k 18196.55k +sha1 1817.29k 7832.50k 13168.93k 15738.48k 16810.84k +rc4 15887.52k 21709.65k 22745.68k 22995.09k 22995.09k +des cbc 4599.02k 5377.31k 5377.31k 5533.38k 5533.38k +des ede3 1899.59k 2086.71k 2086.67k 2086.51k 2085.90k +idea cbc 3350.08k 3934.62k 3979.42k 4017.53k 4017.53k +rc2 cbc 1534.13k 1630.76k 1625.70k 1644.83k 1653.91k +blowfish cbc 6678.83k 8490.49k 8701.88k 8848.74k 8886.24k + sign verify +rsa 512 bits 0.0062s 0.0008s +rsa 1024 bits 0.0287s 0.0009s +rsa 2048 bits 0.1785s 0.0059s +rsa 4096 bits 1.1300s 0.0205s + sign verify +dsa 512 bits 0.0055s 0.0100s +dsa 1024 bits 0.0154s 0.0299s +dsa 2048 bits 0.0502s 0.0996s diff --git a/node-v0.8.14/deps/openssl/openssl/times/pent2.t b/node-v0.8.14/deps/openssl/openssl/times/pent2.t new file mode 100644 index 0000000..b6dc269 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/times/pent2.t @@ -0,0 +1,24 @@ +pentium 2, 266mhz, Visual C++ 5.0, Windows 95 + +The 'numbers' are in 1000s of bytes per second processed. +type 8 bytes 64 bytes 256 bytes 1024 bytes 8192 bytes +md2 235.90k 652.30k 893.36k 985.74k 985.74k +mdc2 779.61k 816.81k 825.65k 816.01k 825.65k +md5 2788.77k 13508.23k 24672.38k 30504.03k 33156.55k +sha 1938.22k 8397.01k 14122.24k 16980.99k 18196.55k +sha1 1817.29k 7832.50k 13168.93k 15738.48k 16810.84k +rc4 15887.52k 21709.65k 22745.68k 22995.09k 22995.09k +des cbc 4599.02k 5377.31k 5377.31k 5533.38k 5533.38k +des ede3 1899.59k 2086.71k 2086.67k 2086.51k 2085.90k +idea cbc 3350.08k 3934.62k 3979.42k 4017.53k 4017.53k +rc2 cbc 1534.13k 1630.76k 1625.70k 1644.83k 1653.91k +blowfish cbc 6678.83k 8490.49k 8701.88k 8848.74k 8886.24k + sign verify +rsa 512 bits 0.0062s 0.0008s +rsa 1024 bits 0.0287s 0.0009s +rsa 2048 bits 0.1785s 0.0059s +rsa 4096 bits 1.1300s 0.0205s + sign verify +dsa 512 bits 0.0055s 0.0100s +dsa 1024 bits 0.0154s 0.0299s +dsa 2048 bits 0.0502s 0.0996s diff --git a/node-v0.8.14/deps/openssl/openssl/times/readme b/node-v0.8.14/deps/openssl/openssl/times/readme new file mode 100644 index 0000000..7074f58 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/times/readme @@ -0,0 +1,11 @@ +The 'times' in this directory are not all for the most recent version of +the library and it should be noted that on some CPUs (specifically sparc +and Alpha), the locations of files in the application after linking can +make upto a %10 speed difference when running benchmarks on things like +cbc mode DES. To put it mildly this can be very anoying. + +About the only way to get around this would be to compile the library as one +object file, or to 'include' the source files in a specific order. + +The best way to get an idea of the 'raw' DES speed is to build the +'speed' program in crypto/des. diff --git a/node-v0.8.14/deps/openssl/openssl/times/s586-100.lnx b/node-v0.8.14/deps/openssl/openssl/times/s586-100.lnx new file mode 100644 index 0000000..cbc3e3c --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/times/s586-100.lnx @@ -0,0 +1,25 @@ +Shared library build + +SSLeay 0.7.3 30-Apr-1997 +built on Tue May 13 03:43:56 EST 1997 +options:bn(64,32) md2(char) rc4(idx,int) des(ptr,risc1,16,long) idea(int) blowfish(ptr2) +C flags:-DTERMIO -O3 -DL_ENDIAN -fomit-frame-pointer -m486 -Wall +The 'numbers' are in 1000s of bytes per second processed. +type 8 bytes 64 bytes 256 bytes 1024 bytes 8192 bytes +md2 68.95k 191.40k 258.22k 283.31k 291.21k +md5 627.37k 3064.75k 5370.15k 6765.91k 7255.38k +sha 323.35k 1431.32k 2417.07k 2916.69k 3102.04k +sha1 298.08k 1318.34k 2228.82k 2694.83k 2864.47k +rc4 3404.13k 4026.33k 4107.43k 4136.28k 4117.85k +des cbc 1414.60k 1782.53k 1824.24k 1847.64k 1840.47k +des ede3 588.36k 688.19k 700.33k 702.46k 704.51k +idea cbc 582.96k 636.71k 641.54k 642.39k 642.30k +rc2 cbc 569.34k 612.37k 617.64k 617.47k 619.86k +blowfish cbc 2015.77k 2534.49k 2609.65k 2607.10k 2615.98k +rsa 512 bits 0.027s 0.003 +rsa 1024 bits 0.128s 0.003 +rsa 2048 bits 0.779s 0.027 +rsa 4096 bits 5.450s 0.098 +dsa 512 bits 0.024s 0.045 +dsa 1024 bits 0.068s 0.132 +dsa 2048 bits 0.231s 0.469 diff --git a/node-v0.8.14/deps/openssl/openssl/times/s586-100.nt b/node-v0.8.14/deps/openssl/openssl/times/s586-100.nt new file mode 100644 index 0000000..8e3baf6 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/times/s586-100.nt @@ -0,0 +1,23 @@ +SSLeay 0.7.3 30-Apr-1997 +built on Mon May 19 10:47:38 EST 1997 +options:bn(64,32) md2(char) rc4(idx,int) des(idx,cisc,4,long) idea(int) blowfish(ptr2) +C flags not available +The 'numbers' are in 1000s of bytes per second processed. +type 8 bytes 64 bytes 256 bytes 1024 bytes 8192 bytes +md2 90.26k 248.57k 335.06k 366.09k 376.64k +md5 863.95k 4205.24k 7628.78k 9582.60k 10290.25k +sha 463.93k 2102.51k 3623.28k 4417.85k 4695.29k +sha1 458.23k 2005.88k 3385.78k 4094.00k 4340.13k +rc4 5843.60k 7543.71k 7790.31k 7836.89k 7791.47k +des cbc 1583.95k 1910.67k 1960.69k 1972.12k 1946.13k +des ede3 654.79k 722.60k 740.97k 745.82k 738.27k +idea cbc 792.04k 876.96k 887.35k 892.63k 890.36k +rc2 cbc 603.50k 652.38k 661.85k 662.69k 661.44k +blowfish cbc 2379.88k 3043.76k 3153.61k 3153.61k 3134.76k +rsa 512 bits 0.022s 0.003 +rsa 1024 bits 0.111s 0.003 +rsa 2048 bits 0.716s 0.025 +rsa 4096 bits 5.188s 0.094 +dsa 512 bits 0.020s 0.039 +dsa 1024 bits 0.062s 0.124 +dsa 2048 bits 0.221s 0.441 diff --git a/node-v0.8.14/deps/openssl/openssl/times/sgi.t b/node-v0.8.14/deps/openssl/openssl/times/sgi.t new file mode 100644 index 0000000..7963610 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/times/sgi.t @@ -0,0 +1,29 @@ +SGI Challenge R4400 200mhz IRIX 5.3 - gcc (2.6.3) +SSLeay 0.6.1 02-Jul-1996 +built on Tue Jul 2 16:25:30 EST 1996 +options:bn(64,32) md2(char) rc4(idx,char) des(idx,long) idea(int) +C flags:gcc -O2 -mips2 -DTERMIOS -DB_ENDIAN +The 'numbers' are in 1000s of bytes per second processed. +type 8 bytes 64 bytes 256 bytes 1024 bytes 8192 bytes +md2 96.53k 266.70k 360.09k 393.70k 405.07k +md5 971.15k 4382.56k 7406.90k 8979.99k 9559.18k +sha 596.86k 2832.26k 4997.30k 6277.75k 6712.89k +sha1 578.34k 2630.16k 4632.05k 5684.34k 6083.37k +rc4 5641.12k 6821.76k 6996.13k 7052.61k 6913.32k +des cfb 1354.86k 1422.11k 1434.58k 1433.24k 1432.89k +des cbc 1467.13k 1618.92k 1630.08k 1637.00k 1629.62k +des ede3 566.13k 591.91k 596.86k 596.18k 592.54k +idea cfb 1190.60k 1264.49k 1270.38k 1267.84k 1272.37k +idea cbc 1271.45k 1410.37k 1422.49k 1426.46k 1421.73k +rc2 cfb 1285.73k 1371.40k 1380.92k 1383.13k 1379.23k +rc2 cbc 1386.61k 1542.10k 1562.49k 1572.45k 1567.93k +rsa 512 bits 0.018s +rsa 1024 bits 0.106s +rsa 2048 bits 0.738s +rsa 4096 bits 5.535s + +version:SSLeay 0.5.2c 15-May-1996 +rsa 512 bits 0.035s +rsa 1024 bits 0.204s +rsa 2048 bits 1.423s +rsa 4096 bits 10.800s diff --git a/node-v0.8.14/deps/openssl/openssl/times/sparc.t b/node-v0.8.14/deps/openssl/openssl/times/sparc.t new file mode 100644 index 0000000..1611f76 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/times/sparc.t @@ -0,0 +1,26 @@ +gcc 2.7.2 +Sparc 10 - Solaris 2.3 - 50mhz +SSLeay 0.7.3r 20-May-1997 +built on Mon Jun 2 00:55:51 EST 1997 +options:bn(64,32) md2(int) rc4(ptr,char) des(idx,cisc,16,long) idea(int) blowfish(ptr) +C flags:gcc -O3 -fomit-frame-pointer -mv8 -Wall +The 'numbers' are in 1000s of bytes per second processed. +type 8 bytes 64 bytes 256 bytes 1024 bytes 8192 bytes +md2 54.88k 154.52k 210.35k 231.08k 237.21k +md5 550.75k 2460.49k 4116.01k 4988.74k 5159.86k +sha 340.28k 1461.76k 2430.10k 2879.87k 2999.15k +sha1 307.27k 1298.41k 2136.26k 2540.07k 2658.28k +rc4 2652.21k 2805.24k 3301.63k 4003.98k 4071.18k +des cbc 811.78k 903.93k 914.19k 921.60k 932.29k +des ede3 328.21k 344.93k 349.64k 351.48k 345.07k +idea cbc 685.06k 727.42k 734.41k 730.11k 739.21k +rc2 cbc 718.59k 777.02k 781.96k 784.38k 782.60k +blowfish cbc 1268.85k 1520.64k 1568.88k 1587.54k 1591.98k +rsa 512 bits 0.037s 0.005 +rsa 1024 bits 0.213s 0.006 +rsa 2048 bits 1.471s 0.053 +rsa 4096 bits 11.100s 0.202 +dsa 512 bits 0.038s 0.074 +dsa 1024 bits 0.128s 0.248 +dsa 2048 bits 0.473s 0.959 + diff --git a/node-v0.8.14/deps/openssl/openssl/times/sparc2 b/node-v0.8.14/deps/openssl/openssl/times/sparc2 new file mode 100644 index 0000000..4b0dd80 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/times/sparc2 @@ -0,0 +1,21 @@ +type 8 bytes 64 bytes 256 bytes 1024 bytes 8192 bytes +md2 14.56k 40.25k 54.95k 60.13k 62.18k +mdc2 53.59k 57.45k 58.11k 58.21k 58.51k +md5 176.95k 764.75k 1270.36k 1520.14k 1608.36k +hmac(md5) 55.88k 369.70k 881.15k 1337.05k 1567.40k +sha1 92.69k 419.75k 723.63k 878.82k 939.35k +rc4 1247.28k 1414.09k 1434.30k 1434.34k 1441.13k +des cbc 284.41k 318.58k 323.07k 324.09k 323.87k +des ede3 109.99k 119.99k 121.60k 121.87k 121.66k +idea cbc 43.06k 43.68k 43.84k 43.64k 44.07k +rc2 cbc 278.85k 311.44k 316.50k 316.57k 317.37k +blowfish cbc 468.89k 569.35k 581.61k 568.34k 559.54k +cast cbc 285.84k 338.79k 345.71k 346.19k 341.09k + sign verify +rsa 512 bits 0.4175s 0.0519s +rsa 1024 bits 2.9325s 0.1948s +rsa 2048 bits 22.3600s 0.7669s + sign verify +dsa 512 bits 0.5178s 1.0300s +dsa 1024 bits 1.8780s 3.7167s +dsa 2048 bits 7.3500s 14.4800s diff --git a/node-v0.8.14/deps/openssl/openssl/times/sparcLX.t b/node-v0.8.14/deps/openssl/openssl/times/sparcLX.t new file mode 100644 index 0000000..2fdaed7 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/times/sparcLX.t @@ -0,0 +1,22 @@ +Sparc Station LX +SSLeay 0.7.3 30-Apr-1997 +built on Thu May 1 10:44:02 EST 1997 +options:bn(64,32) md2(int) rc4(ptr,char) des(idx,cisc,16,long) idea(int) blowfish(ptr) +C flags:gcc -O3 -fomit-frame-pointer -mv8 -Wall +The 'numbers' are in 1000s of bytes per second processed. +type 8 bytes 64 bytes 256 bytes 1024 bytes 8192 bytes +md2 17.60k 48.72k 66.47k 72.70k 74.72k +md5 226.24k 1082.21k 1982.72k 2594.02k 2717.01k +sha 71.38k 320.71k 551.08k 677.76k 720.90k +sha1 63.08k 280.79k 473.86k 576.94k 608.94k +rc4 1138.30k 1257.67k 1304.49k 1377.78k 1364.42k +des cbc 265.34k 308.85k 314.28k 315.39k 317.20k +des ede3 83.23k 93.13k 94.04k 94.50k 94.63k +idea cbc 254.48k 274.26k 275.88k 274.68k 275.80k +rc2 cbc 328.27k 375.39k 381.43k 381.61k 380.83k +blowfish cbc 487.00k 498.02k 510.12k 515.41k 516.10k +rsa 512 bits 0.093s +rsa 1024 bits 0.537s +rsa 2048 bits 3.823s +rsa 4096 bits 28.650s + diff --git a/node-v0.8.14/deps/openssl/openssl/times/usparc.t b/node-v0.8.14/deps/openssl/openssl/times/usparc.t new file mode 100644 index 0000000..2215624 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/times/usparc.t @@ -0,0 +1,25 @@ +Sparc 2000? - Solaris 2.5.1 - 167mhz Ultra sparc + +SSLeay 0.7.3r 20-May-1997 +built on Mon Jun 2 02:25:48 EST 1997 +options:bn(64,32) md2(int) rc4(ptr,char) des(ptr,risc1,16,long) idea(int) blowfish(ptr) +C flags:cc cc -xtarget=ultra -xarch=v8plus -Xa -xO5 -Xa -DB_ENDIAN +The 'numbers' are in 1000s of bytes per second processed. +type 8 bytes 64 bytes 256 bytes 1024 bytes 8192 bytes +md2 135.23k 389.87k 536.66k 591.87k 603.48k +md5 1534.38k 6160.41k 9842.69k 11446.95k 11993.09k +sha 1178.30k 5020.74k 8532.22k 10275.50k 11010.05k +sha1 1114.22k 4703.94k 7703.81k 9236.14k 9756.67k +rc4 10818.03k 13327.57k 13711.10k 13810.69k 13836.29k +des cbc 3052.44k 3320.02k 3356.25k 3369.98k 3295.91k +des ede3 1310.32k 1359.98k 1367.47k 1362.94k 1362.60k +idea cbc 1749.52k 1833.13k 1844.74k 1848.32k 1848.66k +rc2 cbc 1950.25k 2053.23k 2064.21k 2072.58k 2072.58k +blowfish cbc 4927.16k 5659.75k 5762.73k 5797.55k 5805.40k +rsa 512 bits 0.021s 0.003 +rsa 1024 bits 0.126s 0.003 +rsa 2048 bits 0.888s 0.032 +rsa 4096 bits 6.770s 0.122 +dsa 512 bits 0.022s 0.043 +dsa 1024 bits 0.076s 0.151 +dsa 2048 bits 0.286s 0.574 diff --git a/node-v0.8.14/deps/openssl/openssl/times/x86/bfs.cpp b/node-v0.8.14/deps/openssl/openssl/times/x86/bfs.cpp new file mode 100644 index 0000000..d74c457 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/times/x86/bfs.cpp @@ -0,0 +1,67 @@ +// +// gettsc.inl +// +// gives access to the Pentium's (secret) cycle counter +// +// This software was written by Leonard Janke (janke@unixg.ubc.ca) +// in 1996-7 and is entered, by him, into the public domain. + +#if defined(__WATCOMC__) +void GetTSC(unsigned long&); +#pragma aux GetTSC = 0x0f 0x31 "mov [edi], eax" parm [edi] modify [edx eax]; +#elif defined(__GNUC__) +inline +void GetTSC(unsigned long& tsc) +{ + asm volatile(".byte 15, 49\n\t" + : "=eax" (tsc) + : + : "%edx", "%eax"); +} +#elif defined(_MSC_VER) +inline +void GetTSC(unsigned long& tsc) +{ + unsigned long a; + __asm _emit 0fh + __asm _emit 31h + __asm mov a, eax; + tsc=a; +} +#endif + +#include +#include +#include + +void main(int argc,char *argv[]) + { + BF_KEY key; + unsigned long s1,s2,e1,e2; + unsigned long data[2]; + int i,j; + + for (j=0; j<6; j++) + { + for (i=0; i<1000; i++) /**/ + { + BF_encrypt(&data[0],&key); + GetTSC(s1); + BF_encrypt(&data[0],&key); + BF_encrypt(&data[0],&key); + BF_encrypt(&data[0],&key); + GetTSC(e1); + GetTSC(s2); + BF_encrypt(&data[0],&key); + BF_encrypt(&data[0],&key); + BF_encrypt(&data[0],&key); + BF_encrypt(&data[0],&key); + GetTSC(e2); + BF_encrypt(&data[0],&key); + } + + printf("blowfish %d %d (%d)\n", + e1-s1,e2-s2,((e2-s2)-(e1-s1))); + } + } + diff --git a/node-v0.8.14/deps/openssl/openssl/times/x86/casts.cpp b/node-v0.8.14/deps/openssl/openssl/times/x86/casts.cpp new file mode 100644 index 0000000..7661191 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/times/x86/casts.cpp @@ -0,0 +1,67 @@ +// +// gettsc.inl +// +// gives access to the Pentium's (secret) cycle counter +// +// This software was written by Leonard Janke (janke@unixg.ubc.ca) +// in 1996-7 and is entered, by him, into the public domain. + +#if defined(__WATCOMC__) +void GetTSC(unsigned long&); +#pragma aux GetTSC = 0x0f 0x31 "mov [edi], eax" parm [edi] modify [edx eax]; +#elif defined(__GNUC__) +inline +void GetTSC(unsigned long& tsc) +{ + asm volatile(".byte 15, 49\n\t" + : "=eax" (tsc) + : + : "%edx", "%eax"); +} +#elif defined(_MSC_VER) +inline +void GetTSC(unsigned long& tsc) +{ + unsigned long a; + __asm _emit 0fh + __asm _emit 31h + __asm mov a, eax; + tsc=a; +} +#endif + +#include +#include +#include + +void main(int argc,char *argv[]) + { + CAST_KEY key; + unsigned long s1,s2,e1,e2; + unsigned long data[2]; + int i,j; + + for (j=0; j<6; j++) + { + for (i=0; i<1000; i++) /**/ + { + CAST_encrypt(&data[0],&key); + GetTSC(s1); + CAST_encrypt(&data[0],&key); + CAST_encrypt(&data[0],&key); + CAST_encrypt(&data[0],&key); + GetTSC(e1); + GetTSC(s2); + CAST_encrypt(&data[0],&key); + CAST_encrypt(&data[0],&key); + CAST_encrypt(&data[0],&key); + CAST_encrypt(&data[0],&key); + GetTSC(e2); + CAST_encrypt(&data[0],&key); + } + + printf("cast %d %d (%d)\n", + e1-s1,e2-s2,((e2-s2)-(e1-s1))); + } + } + diff --git a/node-v0.8.14/deps/openssl/openssl/times/x86/des3s.cpp b/node-v0.8.14/deps/openssl/openssl/times/x86/des3s.cpp new file mode 100644 index 0000000..cd2b112 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/times/x86/des3s.cpp @@ -0,0 +1,67 @@ +// +// gettsc.inl +// +// gives access to the Pentium's (secret) cycle counter +// +// This software was written by Leonard Janke (janke@unixg.ubc.ca) +// in 1996-7 and is entered, by him, into the public domain. + +#if defined(__WATCOMC__) +void GetTSC(unsigned long&); +#pragma aux GetTSC = 0x0f 0x31 "mov [edi], eax" parm [edi] modify [edx eax]; +#elif defined(__GNUC__) +inline +void GetTSC(unsigned long& tsc) +{ + asm volatile(".byte 15, 49\n\t" + : "=eax" (tsc) + : + : "%edx", "%eax"); +} +#elif defined(_MSC_VER) +inline +void GetTSC(unsigned long& tsc) +{ + unsigned long a; + __asm _emit 0fh + __asm _emit 31h + __asm mov a, eax; + tsc=a; +} +#endif + +#include +#include +#include + +void main(int argc,char *argv[]) + { + des_key_schedule key1,key2,key3; + unsigned long s1,s2,e1,e2; + unsigned long data[2]; + int i,j; + + for (j=0; j<6; j++) + { + for (i=0; i<1000; i++) /**/ + { + des_encrypt3(&data[0],key1,key2,key3); + GetTSC(s1); + des_encrypt3(&data[0],key1,key2,key3); + des_encrypt3(&data[0],key1,key2,key3); + des_encrypt3(&data[0],key1,key2,key3); + GetTSC(e1); + GetTSC(s2); + des_encrypt3(&data[0],key1,key2,key3); + des_encrypt3(&data[0],key1,key2,key3); + des_encrypt3(&data[0],key1,key2,key3); + des_encrypt3(&data[0],key1,key2,key3); + GetTSC(e2); + des_encrypt3(&data[0],key1,key2,key3); + } + + printf("des3 %d %d (%d)\n", + e1-s1,e2-s2,((e2-s2)-(e1-s1))); + } + } + diff --git a/node-v0.8.14/deps/openssl/openssl/times/x86/dess.cpp b/node-v0.8.14/deps/openssl/openssl/times/x86/dess.cpp new file mode 100644 index 0000000..753e67a --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/times/x86/dess.cpp @@ -0,0 +1,67 @@ +// +// gettsc.inl +// +// gives access to the Pentium's (secret) cycle counter +// +// This software was written by Leonard Janke (janke@unixg.ubc.ca) +// in 1996-7 and is entered, by him, into the public domain. + +#if defined(__WATCOMC__) +void GetTSC(unsigned long&); +#pragma aux GetTSC = 0x0f 0x31 "mov [edi], eax" parm [edi] modify [edx eax]; +#elif defined(__GNUC__) +inline +void GetTSC(unsigned long& tsc) +{ + asm volatile(".byte 15, 49\n\t" + : "=eax" (tsc) + : + : "%edx", "%eax"); +} +#elif defined(_MSC_VER) +inline +void GetTSC(unsigned long& tsc) +{ + unsigned long a; + __asm _emit 0fh + __asm _emit 31h + __asm mov a, eax; + tsc=a; +} +#endif + +#include +#include +#include + +void main(int argc,char *argv[]) + { + des_key_schedule key; + unsigned long s1,s2,e1,e2; + unsigned long data[2]; + int i,j; + + for (j=0; j<6; j++) + { + for (i=0; i<1000; i++) /**/ + { + des_encrypt(&data[0],key,1); + GetTSC(s1); + des_encrypt(&data[0],key,1); + des_encrypt(&data[0],key,1); + des_encrypt(&data[0],key,1); + GetTSC(e1); + GetTSC(s2); + des_encrypt(&data[0],key,1); + des_encrypt(&data[0],key,1); + des_encrypt(&data[0],key,1); + des_encrypt(&data[0],key,1); + GetTSC(e2); + des_encrypt(&data[0],key,1); + } + + printf("des %d %d (%d)\n", + e1-s1,e2-s2,((e2-s2)-(e1-s1))); + } + } + diff --git a/node-v0.8.14/deps/openssl/openssl/times/x86/md4s.cpp b/node-v0.8.14/deps/openssl/openssl/times/x86/md4s.cpp new file mode 100644 index 0000000..c0ec97f --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/times/x86/md4s.cpp @@ -0,0 +1,78 @@ +// +// gettsc.inl +// +// gives access to the Pentium's (secret) cycle counter +// +// This software was written by Leonard Janke (janke@unixg.ubc.ca) +// in 1996-7 and is entered, by him, into the public domain. + +#if defined(__WATCOMC__) +void GetTSC(unsigned long&); +#pragma aux GetTSC = 0x0f 0x31 "mov [edi], eax" parm [edi] modify [edx eax]; +#elif defined(__GNUC__) +inline +void GetTSC(unsigned long& tsc) +{ + asm volatile(".byte 15, 49\n\t" + : "=eax" (tsc) + : + : "%edx", "%eax"); +} +#elif defined(_MSC_VER) +inline +void GetTSC(unsigned long& tsc) +{ + unsigned long a; + __asm _emit 0fh + __asm _emit 31h + __asm mov a, eax; + tsc=a; +} +#endif + +#include +#include +#include + +extern "C" { +void md4_block_x86(MD4_CTX *ctx, unsigned char *buffer,int num); +} + +void main(int argc,char *argv[]) + { + unsigned char buffer[64*256]; + MD4_CTX ctx; + unsigned long s1,s2,e1,e2; + unsigned char k[16]; + unsigned long data[2]; + unsigned char iv[8]; + int i,num=0,numm; + int j=0; + + if (argc >= 2) + num=atoi(argv[1]); + + if (num == 0) num=16; + if (num > 250) num=16; + numm=num+2; + num*=64; + numm*=64; + + for (j=0; j<6; j++) + { + for (i=0; i<10; i++) /**/ + { + md4_block_x86(&ctx,buffer,numm); + GetTSC(s1); + md4_block_x86(&ctx,buffer,numm); + GetTSC(e1); + GetTSC(s2); + md4_block_x86(&ctx,buffer,num); + GetTSC(e2); + md4_block_x86(&ctx,buffer,num); + } + printf("md4 (%d bytes) %d %d (%.2f)\n",num, + e1-s1,e2-s2,(double)((e1-s1)-(e2-s2))/2); + } + } + diff --git a/node-v0.8.14/deps/openssl/openssl/times/x86/md5s.cpp b/node-v0.8.14/deps/openssl/openssl/times/x86/md5s.cpp new file mode 100644 index 0000000..dd343fd --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/times/x86/md5s.cpp @@ -0,0 +1,78 @@ +// +// gettsc.inl +// +// gives access to the Pentium's (secret) cycle counter +// +// This software was written by Leonard Janke (janke@unixg.ubc.ca) +// in 1996-7 and is entered, by him, into the public domain. + +#if defined(__WATCOMC__) +void GetTSC(unsigned long&); +#pragma aux GetTSC = 0x0f 0x31 "mov [edi], eax" parm [edi] modify [edx eax]; +#elif defined(__GNUC__) +inline +void GetTSC(unsigned long& tsc) +{ + asm volatile(".byte 15, 49\n\t" + : "=eax" (tsc) + : + : "%edx", "%eax"); +} +#elif defined(_MSC_VER) +inline +void GetTSC(unsigned long& tsc) +{ + unsigned long a; + __asm _emit 0fh + __asm _emit 31h + __asm mov a, eax; + tsc=a; +} +#endif + +#include +#include +#include + +extern "C" { +void md5_block_x86(MD5_CTX *ctx, unsigned char *buffer,int num); +} + +void main(int argc,char *argv[]) + { + unsigned char buffer[64*256]; + MD5_CTX ctx; + unsigned long s1,s2,e1,e2; + unsigned char k[16]; + unsigned long data[2]; + unsigned char iv[8]; + int i,num=0,numm; + int j=0; + + if (argc >= 2) + num=atoi(argv[1]); + + if (num == 0) num=16; + if (num > 250) num=16; + numm=num+2; + num*=64; + numm*=64; + + for (j=0; j<6; j++) + { + for (i=0; i<10; i++) /**/ + { + md5_block_x86(&ctx,buffer,numm); + GetTSC(s1); + md5_block_x86(&ctx,buffer,numm); + GetTSC(e1); + GetTSC(s2); + md5_block_x86(&ctx,buffer,num); + GetTSC(e2); + md5_block_x86(&ctx,buffer,num); + } + printf("md5 (%d bytes) %d %d (%.2f)\n",num, + e1-s1,e2-s2,(double)((e1-s1)-(e2-s2))/2); + } + } + diff --git a/node-v0.8.14/deps/openssl/openssl/times/x86/rc4s.cpp b/node-v0.8.14/deps/openssl/openssl/times/x86/rc4s.cpp new file mode 100644 index 0000000..3814fde --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/times/x86/rc4s.cpp @@ -0,0 +1,73 @@ +// +// gettsc.inl +// +// gives access to the Pentium's (secret) cycle counter +// +// This software was written by Leonard Janke (janke@unixg.ubc.ca) +// in 1996-7 and is entered, by him, into the public domain. + +#if defined(__WATCOMC__) +void GetTSC(unsigned long&); +#pragma aux GetTSC = 0x0f 0x31 "mov [edi], eax" parm [edi] modify [edx eax]; +#elif defined(__GNUC__) +inline +void GetTSC(unsigned long& tsc) +{ + asm volatile(".byte 15, 49\n\t" + : "=eax" (tsc) + : + : "%edx", "%eax"); +} +#elif defined(_MSC_VER) +inline +void GetTSC(unsigned long& tsc) +{ + unsigned long a; + __asm _emit 0fh + __asm _emit 31h + __asm mov a, eax; + tsc=a; +} +#endif + +#include +#include +#include + +void main(int argc,char *argv[]) + { + unsigned char buffer[1024]; + RC4_KEY ctx; + unsigned long s1,s2,e1,e2; + unsigned char k[16]; + unsigned long data[2]; + unsigned char iv[8]; + int i,num=64,numm; + int j=0; + + if (argc >= 2) + num=atoi(argv[1]); + + if (num == 0) num=256; + if (num > 1024-16) num=1024-16; + numm=num+8; + + for (j=0; j<6; j++) + { + for (i=0; i<10; i++) /**/ + { + RC4(&ctx,numm,buffer,buffer); + GetTSC(s1); + RC4(&ctx,numm,buffer,buffer); + GetTSC(e1); + GetTSC(s2); + RC4(&ctx,num,buffer,buffer); + GetTSC(e2); + RC4(&ctx,num,buffer,buffer); + } + + printf("RC4 (%d bytes) %d %d (%d) - 8 bytes\n",num, + e1-s1,e2-s2,(e1-s1)-(e2-s2)); + } + } + diff --git a/node-v0.8.14/deps/openssl/openssl/times/x86/sha1s.cpp b/node-v0.8.14/deps/openssl/openssl/times/x86/sha1s.cpp new file mode 100644 index 0000000..3103e18 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/times/x86/sha1s.cpp @@ -0,0 +1,79 @@ +// +// gettsc.inl +// +// gives access to the Pentium's (secret) cycle counter +// +// This software was written by Leonard Janke (janke@unixg.ubc.ca) +// in 1996-7 and is entered, by him, into the public domain. + +#if defined(__WATCOMC__) +void GetTSC(unsigned long&); +#pragma aux GetTSC = 0x0f 0x31 "mov [edi], eax" parm [edi] modify [edx eax]; +#elif defined(__GNUC__) +inline +void GetTSC(unsigned long& tsc) +{ + asm volatile(".byte 15, 49\n\t" + : "=eax" (tsc) + : + : "%edx", "%eax"); +} +#elif defined(_MSC_VER) +inline +void GetTSC(unsigned long& tsc) +{ + unsigned long a; + __asm _emit 0fh + __asm _emit 31h + __asm mov a, eax; + tsc=a; +} +#endif + +#include +#include +#include + +extern "C" { +void sha1_block_x86(SHA_CTX *ctx, unsigned char *buffer,int num); +} + +void main(int argc,char *argv[]) + { + unsigned char buffer[64*256]; + SHA_CTX ctx; + unsigned long s1,s2,e1,e2; + unsigned char k[16]; + unsigned long data[2]; + unsigned char iv[8]; + int i,num=0,numm; + int j=0; + + if (argc >= 2) + num=atoi(argv[1]); + + if (num == 0) num=16; + if (num > 250) num=16; + numm=num+2; + num*=64; + numm*=64; + + for (j=0; j<6; j++) + { + for (i=0; i<10; i++) /**/ + { + sha1_block_x86(&ctx,buffer,numm); + GetTSC(s1); + sha1_block_x86(&ctx,buffer,numm); + GetTSC(e1); + GetTSC(s2); + sha1_block_x86(&ctx,buffer,num); + GetTSC(e2); + sha1_block_x86(&ctx,buffer,num); + } + + printf("sha1 (%d bytes) %d %d (%.2f)\n",num, + e1-s1,e2-s2,(double)((e1-s1)-(e2-s2))/2); + } + } + diff --git a/node-v0.8.14/deps/openssl/openssl/tools/Makefile b/node-v0.8.14/deps/openssl/openssl/tools/Makefile new file mode 100644 index 0000000..bb6fb71 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/tools/Makefile @@ -0,0 +1,59 @@ +# +# OpenSSL/tools/Makefile +# + +DIR= tools +TOP= .. +CC= cc +INCLUDES= -I$(TOP) -I../../include +CFLAG=-g +MAKEFILE= Makefile + +CFLAGS= $(INCLUDES) $(CFLAG) + +GENERAL=Makefile +TEST= +APPS= c_rehash +MISC_APPS= c_hash c_info c_issuer c_name + +all: + +install: + @[ -n "$(INSTALLTOP)" ] # should be set by top Makefile... + @for i in $(APPS) ; \ + do \ + (cp $$i $(INSTALL_PREFIX)$(INSTALLTOP)/bin/$$i.new; \ + chmod 755 $(INSTALL_PREFIX)$(INSTALLTOP)/bin/$$i.new; \ + mv -f $(INSTALL_PREFIX)$(INSTALLTOP)/bin/$$i.new $(INSTALL_PREFIX)$(INSTALLTOP)/bin/$$i ); \ + done; + @for i in $(MISC_APPS) ; \ + do \ + (cp $$i $(INSTALL_PREFIX)$(OPENSSLDIR)/misc/$$i.new; \ + chmod 755 $(INSTALL_PREFIX)$(OPENSSLDIR)/misc/$$i.new; \ + mv -f $(INSTALL_PREFIX)$(OPENSSLDIR)/misc/$$i.new $(INSTALL_PREFIX)$(OPENSSLDIR)/misc/$$i ); \ + done; + +files: + $(PERL) $(TOP)/util/files.pl Makefile >> $(TOP)/MINFO + +links: + +lint: + +tags: + +errors: + +depend: + +dclean: + $(PERL) -pe 'if (/^# DO NOT DELETE THIS LINE/) {print; exit(0);}' $(MAKEFILE) >Makefile.new + mv -f Makefile.new $(MAKEFILE) + rm -f c_rehash + +clean: + rm -f *.o *.obj lib tags core .pure .nfs* *.old *.bak fluff + +errors: + +# DO NOT DELETE THIS LINE -- make depend depends on it. diff --git a/node-v0.8.14/deps/openssl/openssl/tools/c89.sh b/node-v0.8.14/deps/openssl/openssl/tools/c89.sh new file mode 100755 index 0000000..b25c9fd --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/tools/c89.sh @@ -0,0 +1,15 @@ +#!/bin/sh -k +# +# Re-order arguments so that -L comes first +# +opts="" +lopts="" + +for arg in $* ; do + case $arg in + -L*) lopts="$lopts $arg" ;; + *) opts="$opts $arg" ;; + esac +done + +c89 $lopts $opts diff --git a/node-v0.8.14/deps/openssl/openssl/tools/c_hash b/node-v0.8.14/deps/openssl/openssl/tools/c_hash new file mode 100644 index 0000000..5e0a908 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/tools/c_hash @@ -0,0 +1,9 @@ +#!/bin/sh +# print out the hash values +# + +for i in $* +do + h=`openssl x509 -hash -noout -in $i` + echo "$h.0 => $i" +done diff --git a/node-v0.8.14/deps/openssl/openssl/tools/c_info b/node-v0.8.14/deps/openssl/openssl/tools/c_info new file mode 100644 index 0000000..0e1e633 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/tools/c_info @@ -0,0 +1,12 @@ +#!/bin/sh +# +# print the subject +# + +for i in $* +do + n=`openssl x509 -subject -issuer -enddate -noout -in $i` + echo "$i" + echo "$n" + echo "--------" +done diff --git a/node-v0.8.14/deps/openssl/openssl/tools/c_issuer b/node-v0.8.14/deps/openssl/openssl/tools/c_issuer new file mode 100644 index 0000000..55821ab --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/tools/c_issuer @@ -0,0 +1,10 @@ +#!/bin/sh +# +# print out the issuer +# + +for i in $* +do + n=`openssl x509 -issuer -noout -in $i` + echo "$i $n" +done diff --git a/node-v0.8.14/deps/openssl/openssl/tools/c_name b/node-v0.8.14/deps/openssl/openssl/tools/c_name new file mode 100644 index 0000000..28800c0 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/tools/c_name @@ -0,0 +1,10 @@ +#!/bin/sh +# +# print the subject +# + +for i in $* +do + n=`openssl x509 -subject -noout -in $i` + echo "$i $n" +done diff --git a/node-v0.8.14/deps/openssl/openssl/tools/c_rehash b/node-v0.8.14/deps/openssl/openssl/tools/c_rehash new file mode 100644 index 0000000..6a20011 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/tools/c_rehash @@ -0,0 +1,180 @@ +#!/usr/bin/perl + + +# Perl c_rehash script, scan all files in a directory +# and add symbolic links to their hash values. + +my $openssl; + +my $dir = "/usr/local/ssl"; +my $prefix = "/usr/local/ssl"; + +if(defined $ENV{OPENSSL}) { + $openssl = $ENV{OPENSSL}; +} else { + $openssl = "openssl"; + $ENV{OPENSSL} = $openssl; +} + +my $pwd; +eval "require Cwd"; +if (defined(&Cwd::getcwd)) { + $pwd=Cwd::getcwd(); +} else { + $pwd=`pwd`; chomp($pwd); +} +my $path_delim = ($pwd =~ /^[a-z]\:/i) ? ';' : ':'; # DOS/Win32 or Unix delimiter? + +$ENV{PATH} = "$prefix/bin" . ($ENV{PATH} ? $path_delim . $ENV{PATH} : ""); # prefix our path + +if(! -x $openssl) { + my $found = 0; + foreach (split /$path_delim/, $ENV{PATH}) { + if(-x "$_/$openssl") { + $found = 1; + $openssl = "$_/$openssl"; + last; + } + } + if($found == 0) { + print STDERR "c_rehash: rehashing skipped ('openssl' program not available)\n"; + exit 0; + } +} + +if(@ARGV) { + @dirlist = @ARGV; +} elsif($ENV{SSL_CERT_DIR}) { + @dirlist = split /$path_delim/, $ENV{SSL_CERT_DIR}; +} else { + $dirlist[0] = "$dir/certs"; +} + +if (-d $dirlist[0]) { + chdir $dirlist[0]; + $openssl="$pwd/$openssl" if (!-x $openssl); + chdir $pwd; +} + +foreach (@dirlist) { + if(-d $_ and -w $_) { + hash_dir($_); + } +} + +sub hash_dir { + my %hashlist; + print "Doing $_[0]\n"; + chdir $_[0]; + opendir(DIR, "."); + my @flist = readdir(DIR); + # Delete any existing symbolic links + foreach (grep {/^[\da-f]+\.r{0,1}\d+$/} @flist) { + if(-l $_) { + unlink $_; + } + } + closedir DIR; + FILE: foreach $fname (grep {/\.pem$/} @flist) { + # Check to see if certificates and/or CRLs present. + my ($cert, $crl) = check_file($fname); + if(!$cert && !$crl) { + print STDERR "WARNING: $fname does not contain a certificate or CRL: skipping\n"; + next; + } + link_hash_cert($fname) if($cert); + link_hash_crl($fname) if($crl); + } +} + +sub check_file { + my ($is_cert, $is_crl) = (0,0); + my $fname = $_[0]; + open IN, $fname; + while() { + if(/^-----BEGIN (.*)-----/) { + my $hdr = $1; + if($hdr =~ /^(X509 |TRUSTED |)CERTIFICATE$/) { + $is_cert = 1; + last if($is_crl); + } elsif($hdr eq "X509 CRL") { + $is_crl = 1; + last if($is_cert); + } + } + } + close IN; + return ($is_cert, $is_crl); +} + + +# Link a certificate to its subject name hash value, each hash is of +# the form . where n is an integer. If the hash value already exists +# then we need to up the value of n, unless its a duplicate in which +# case we skip the link. We check for duplicates by comparing the +# certificate fingerprints + +sub link_hash_cert { + my $fname = $_[0]; + $fname =~ s/'/'\\''/g; + my ($hash, $fprint) = `"$openssl" x509 -hash -fingerprint -noout -in "$fname"`; + chomp $hash; + chomp $fprint; + $fprint =~ s/^.*=//; + $fprint =~ tr/://d; + my $suffix = 0; + # Search for an unused hash filename + while(exists $hashlist{"$hash.$suffix"}) { + # Hash matches: if fingerprint matches its a duplicate cert + if($hashlist{"$hash.$suffix"} eq $fprint) { + print STDERR "WARNING: Skipping duplicate certificate $fname\n"; + return; + } + $suffix++; + } + $hash .= ".$suffix"; + print "$fname => $hash\n"; + $symlink_exists=eval {symlink("",""); 1}; + if ($symlink_exists) { + symlink $fname, $hash; + } else { + open IN,"<$fname" or die "can't open $fname for read"; + open OUT,">$hash" or die "can't open $hash for write"; + print OUT ; # does the job for small text files + close OUT; + close IN; + } + $hashlist{$hash} = $fprint; +} + +# Same as above except for a CRL. CRL links are of the form .r + +sub link_hash_crl { + my $fname = $_[0]; + $fname =~ s/'/'\\''/g; + my ($hash, $fprint) = `"$openssl" crl -hash -fingerprint -noout -in '$fname'`; + chomp $hash; + chomp $fprint; + $fprint =~ s/^.*=//; + $fprint =~ tr/://d; + my $suffix = 0; + # Search for an unused hash filename + while(exists $hashlist{"$hash.r$suffix"}) { + # Hash matches: if fingerprint matches its a duplicate cert + if($hashlist{"$hash.r$suffix"} eq $fprint) { + print STDERR "WARNING: Skipping duplicate CRL $fname\n"; + return; + } + $suffix++; + } + $hash .= ".r$suffix"; + print "$fname => $hash\n"; + $symlink_exists=eval {symlink("",""); 1}; + if ($symlink_exists) { + symlink $fname, $hash; + } else { + system ("cp", $fname, $hash); + } + $hashlist{$hash} = $fprint; +} + diff --git a/node-v0.8.14/deps/openssl/openssl/tools/c_rehash.in b/node-v0.8.14/deps/openssl/openssl/tools/c_rehash.in new file mode 100644 index 0000000..bfc4a69 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/tools/c_rehash.in @@ -0,0 +1,180 @@ +#!/usr/local/bin/perl + + +# Perl c_rehash script, scan all files in a directory +# and add symbolic links to their hash values. + +my $openssl; + +my $dir; +my $prefix; + +if(defined $ENV{OPENSSL}) { + $openssl = $ENV{OPENSSL}; +} else { + $openssl = "openssl"; + $ENV{OPENSSL} = $openssl; +} + +my $pwd; +eval "require Cwd"; +if (defined(&Cwd::getcwd)) { + $pwd=Cwd::getcwd(); +} else { + $pwd=`pwd`; chomp($pwd); +} +my $path_delim = ($pwd =~ /^[a-z]\:/i) ? ';' : ':'; # DOS/Win32 or Unix delimiter? + +$ENV{PATH} = "$prefix/bin" . ($ENV{PATH} ? $path_delim . $ENV{PATH} : ""); # prefix our path + +if(! -x $openssl) { + my $found = 0; + foreach (split /$path_delim/, $ENV{PATH}) { + if(-x "$_/$openssl") { + $found = 1; + $openssl = "$_/$openssl"; + last; + } + } + if($found == 0) { + print STDERR "c_rehash: rehashing skipped ('openssl' program not available)\n"; + exit 0; + } +} + +if(@ARGV) { + @dirlist = @ARGV; +} elsif($ENV{SSL_CERT_DIR}) { + @dirlist = split /$path_delim/, $ENV{SSL_CERT_DIR}; +} else { + $dirlist[0] = "$dir/certs"; +} + +if (-d $dirlist[0]) { + chdir $dirlist[0]; + $openssl="$pwd/$openssl" if (!-x $openssl); + chdir $pwd; +} + +foreach (@dirlist) { + if(-d $_ and -w $_) { + hash_dir($_); + } +} + +sub hash_dir { + my %hashlist; + print "Doing $_[0]\n"; + chdir $_[0]; + opendir(DIR, "."); + my @flist = readdir(DIR); + # Delete any existing symbolic links + foreach (grep {/^[\da-f]+\.r{0,1}\d+$/} @flist) { + if(-l $_) { + unlink $_; + } + } + closedir DIR; + FILE: foreach $fname (grep {/\.pem$/} @flist) { + # Check to see if certificates and/or CRLs present. + my ($cert, $crl) = check_file($fname); + if(!$cert && !$crl) { + print STDERR "WARNING: $fname does not contain a certificate or CRL: skipping\n"; + next; + } + link_hash_cert($fname) if($cert); + link_hash_crl($fname) if($crl); + } +} + +sub check_file { + my ($is_cert, $is_crl) = (0,0); + my $fname = $_[0]; + open IN, $fname; + while() { + if(/^-----BEGIN (.*)-----/) { + my $hdr = $1; + if($hdr =~ /^(X509 |TRUSTED |)CERTIFICATE$/) { + $is_cert = 1; + last if($is_crl); + } elsif($hdr eq "X509 CRL") { + $is_crl = 1; + last if($is_cert); + } + } + } + close IN; + return ($is_cert, $is_crl); +} + + +# Link a certificate to its subject name hash value, each hash is of +# the form . where n is an integer. If the hash value already exists +# then we need to up the value of n, unless its a duplicate in which +# case we skip the link. We check for duplicates by comparing the +# certificate fingerprints + +sub link_hash_cert { + my $fname = $_[0]; + $fname =~ s/'/'\\''/g; + my ($hash, $fprint) = `"$openssl" x509 -hash -fingerprint -noout -in "$fname"`; + chomp $hash; + chomp $fprint; + $fprint =~ s/^.*=//; + $fprint =~ tr/://d; + my $suffix = 0; + # Search for an unused hash filename + while(exists $hashlist{"$hash.$suffix"}) { + # Hash matches: if fingerprint matches its a duplicate cert + if($hashlist{"$hash.$suffix"} eq $fprint) { + print STDERR "WARNING: Skipping duplicate certificate $fname\n"; + return; + } + $suffix++; + } + $hash .= ".$suffix"; + print "$fname => $hash\n"; + $symlink_exists=eval {symlink("",""); 1}; + if ($symlink_exists) { + symlink $fname, $hash; + } else { + open IN,"<$fname" or die "can't open $fname for read"; + open OUT,">$hash" or die "can't open $hash for write"; + print OUT ; # does the job for small text files + close OUT; + close IN; + } + $hashlist{$hash} = $fprint; +} + +# Same as above except for a CRL. CRL links are of the form .r + +sub link_hash_crl { + my $fname = $_[0]; + $fname =~ s/'/'\\''/g; + my ($hash, $fprint) = `"$openssl" crl -hash -fingerprint -noout -in '$fname'`; + chomp $hash; + chomp $fprint; + $fprint =~ s/^.*=//; + $fprint =~ tr/://d; + my $suffix = 0; + # Search for an unused hash filename + while(exists $hashlist{"$hash.r$suffix"}) { + # Hash matches: if fingerprint matches its a duplicate cert + if($hashlist{"$hash.r$suffix"} eq $fprint) { + print STDERR "WARNING: Skipping duplicate CRL $fname\n"; + return; + } + $suffix++; + } + $hash .= ".r$suffix"; + print "$fname => $hash\n"; + $symlink_exists=eval {symlink("",""); 1}; + if ($symlink_exists) { + symlink $fname, $hash; + } else { + system ("cp", $fname, $hash); + } + $hashlist{$hash} = $fprint; +} + diff --git a/node-v0.8.14/deps/openssl/openssl/util/FreeBSD.sh b/node-v0.8.14/deps/openssl/openssl/util/FreeBSD.sh new file mode 100755 index 0000000..db8edfc --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/util/FreeBSD.sh @@ -0,0 +1,6 @@ +#!/bin/sh + +perl util/perlpath.pl /usr/bin +perl util/ssldir.pl /usr/local +perl util/mk1mf.pl FreeBSD >Makefile.FreeBSD +perl Configure FreeBSD diff --git a/node-v0.8.14/deps/openssl/openssl/util/add_cr.pl b/node-v0.8.14/deps/openssl/openssl/util/add_cr.pl new file mode 100755 index 0000000..c7b62c1 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/util/add_cr.pl @@ -0,0 +1,123 @@ +#!/usr/local/bin/perl +# +# This adds a copyright message to a souce code file. +# It also gets the file name correct. +# +# perl util/add_cr.pl *.[ch] */*.[ch] */*/*.[ch] +# + +foreach (@ARGV) + { + &dofile($_); + } + +sub dofile + { + local($file)=@_; + + open(IN,"<$file") || die "unable to open $file:$!\n"; + + print STDERR "doing $file\n"; + @in=; + + return(1) if ($in[0] =~ / NOCW /); + + @out=(); + open(OUT,">$file.out") || die "unable to open $file.$$:$!\n"; + push(@out,"/* $file */\n"); + if (($in[1] !~ /^\/\* Copyright \(C\) [0-9-]+ Eric Young \(eay\@cryptsoft.com\)/)) + { + push(@out,&Copyright); + $i=2; + @a=grep(/ Copyright \(C\) /,@in); + if ($#a >= 0) + { + while (($i <= $#in) && ($in[$i] ne " */\n")) + { $i++; } + $i++ if ($in[$i] eq " */\n"); + + while (($i <= $#in) && ($in[$i] =~ /^\s*$/)) + { $i++; } + + push(@out,"\n"); + for ( ; $i <= $#in; $i++) + { push(@out,$in[$i]); } + } + else + { push(@out,@in); } + } + else + { + shift(@in); + push(@out,@in); + } + print OUT @out; + close(IN); + close(OUT); + rename("$file","$file.orig") || die "unable to rename $file:$!\n"; + rename("$file.out",$file) || die "unable to rename $file.out:$!\n"; + } + + + +sub Copyright + { + return <<'EOF'; +/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com) + * All rights reserved. + * + * This package is an SSL implementation written + * by Eric Young (eay@cryptsoft.com). + * The implementation was written so as to conform with Netscapes SSL. + * + * This library is free for commercial and non-commercial use as long as + * the following conditions are aheared to. The following conditions + * apply to all code found in this distribution, be it the RC4, RSA, + * lhash, DES, etc., code; not just the SSL code. The SSL documentation + * included with this distribution is covered by the same copyright terms + * except that the holder is Tim Hudson (tjh@cryptsoft.com). + * + * Copyright remains Eric Young's, and as such any Copyright notices in + * the code are not to be removed. + * If this package is used in a product, Eric Young should be given attribution + * as the author of the parts of the library used. + * This can be in the form of a textual message at program startup or + * in documentation (online or textual) provided with the package. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * "This product includes cryptographic software written by + * Eric Young (eay@cryptsoft.com)" + * The word 'cryptographic' can be left out if the rouines from the library + * being used are not cryptographic related :-). + * 4. If you include any Windows specific code (or a derivative thereof) from + * the apps directory (application code) you must include an acknowledgement: + * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)" + * + * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * + * The licence and distribution terms for any publically available version or + * derivative of this code cannot be changed. i.e. this code cannot simply be + * copied and put under another distribution licence + * [including the GNU Public Licence.] + */ +EOF + } diff --git a/node-v0.8.14/deps/openssl/openssl/util/bat.sh b/node-v0.8.14/deps/openssl/openssl/util/bat.sh new file mode 100755 index 0000000..4d9a828 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/util/bat.sh @@ -0,0 +1,134 @@ +#!/usr/local/bin/perl + +$infile="/home/eay/ssl/SSLeay/MINFO"; + +open(IN,"<$infile") || die "unable to open $infile:$!\n"; +$_=; +for (;;) + { + chop; + + ($key,$val)=/^([^=]+)=(.*)/; + if ($key eq "RELATIVE_DIRECTORY") + { + if ($lib ne "") + { + $uc=$lib; + $uc =~ s/^lib(.*)\.a/$1/; + $uc =~ tr/a-z/A-Z/; + $lib_nam{$uc}=$uc; + $lib_obj{$uc}.=$libobj." "; + } + last if ($val eq "FINISHED"); + $lib=""; + $libobj=""; + $dir=$val; + } + + if ($key eq "TEST") + { $test.=&var_add($dir,$val); } + + if (($key eq "PROGS") || ($key eq "E_OBJ")) + { $e_exe.=&var_add($dir,$val); } + + if ($key eq "LIB") + { + $lib=$val; + $lib =~ s/^.*\/([^\/]+)$/$1/; + } + + if ($key eq "EXHEADER") + { $exheader.=&var_add($dir,$val); } + + if ($key eq "HEADER") + { $header.=&var_add($dir,$val); } + + if ($key eq "LIBSRC") + { $libsrc.=&var_add($dir,$val); } + + if (!($_=)) + { $_="RELATIVE_DIRECTORY=FINISHED\n"; } + } +close(IN); + +@a=split(/\s+/,$libsrc); +foreach (@a) + { + print "${_}.c\n"; + } + +sub var_add + { + local($dir,$val)=@_; + local(@a,$_,$ret); + + return("") if $no_engine && $dir =~ /\/engine/; + return("") if $no_idea && $dir =~ /\/idea/; + return("") if $no_rc2 && $dir =~ /\/rc2/; + return("") if $no_rc4 && $dir =~ /\/rc4/; + return("") if $no_rsa && $dir =~ /\/rsa/; + return("") if $no_rsa && $dir =~ /^rsaref/; + return("") if $no_dsa && $dir =~ /\/dsa/; + return("") if $no_dh && $dir =~ /\/dh/; + if ($no_des && $dir =~ /\/des/) + { + if ($val =~ /read_pwd/) + { return("$dir/read_pwd "); } + else + { return(""); } + } + return("") if $no_mdc2 && $dir =~ /\/mdc2/; + return("") if $no_sock && $dir =~ /\/proxy/; + return("") if $no_bf && $dir =~ /\/bf/; + return("") if $no_cast && $dir =~ /\/cast/; + + $val =~ s/^\s*(.*)\s*$/$1/; + @a=split(/\s+/,$val); + grep(s/\.[och]$//,@a); + + @a=grep(!/^e_.*_3d$/,@a) if $no_des; + @a=grep(!/^e_.*_d$/,@a) if $no_des; + @a=grep(!/^e_.*_i$/,@a) if $no_idea; + @a=grep(!/^e_.*_r2$/,@a) if $no_rc2; + @a=grep(!/^e_.*_bf$/,@a) if $no_bf; + @a=grep(!/^e_.*_c$/,@a) if $no_cast; + @a=grep(!/^e_rc4$/,@a) if $no_rc4; + + @a=grep(!/(^s2_)|(^s23_)/,@a) if $no_ssl2; + @a=grep(!/(^s3_)|(^s23_)/,@a) if $no_ssl3; + + @a=grep(!/(_sock$)|(_acpt$)|(_conn$)|(^pxy_)/,@a) if $no_sock; + + @a=grep(!/(^md2)|(_md2$)/,@a) if $no_md2; + @a=grep(!/(^md5)|(_md5$)/,@a) if $no_md5; + + @a=grep(!/(^d2i_r_)|(^i2d_r_)/,@a) if $no_rsa; + @a=grep(!/(^p_open$)|(^p_seal$)/,@a) if $no_rsa; + @a=grep(!/(^pem_seal$)/,@a) if $no_rsa; + + @a=grep(!/(m_dss$)|(m_dss1$)/,@a) if $no_dsa; + @a=grep(!/(^d2i_s_)|(^i2d_s_)|(_dsap$)/,@a) if $no_dsa; + + @a=grep(!/^n_pkey$/,@a) if $no_rsa || $no_rc4; + + @a=grep(!/_dhp$/,@a) if $no_dh; + + @a=grep(!/(^sha[^1])|(_sha$)|(m_dss$)/,@a) if $no_sha; + @a=grep(!/(^sha1)|(_sha1$)|(m_dss1$)/,@a) if $no_sha1; + @a=grep(!/_mdc2$/,@a) if $no_mdc2; + + @a=grep(!/^engine$/,@a) if $no_engine; + @a=grep(!/(^rsa$)|(^genrsa$)|(^req$)|(^ca$)/,@a) if $no_rsa; + @a=grep(!/(^dsa$)|(^gendsa$)|(^dsaparam$)/,@a) if $no_dsa; + @a=grep(!/^gendsa$/,@a) if $no_sha1; + @a=grep(!/(^dh$)|(^gendh$)/,@a) if $no_dh; + + @a=grep(!/(^dh)|(_sha1$)|(m_dss1$)/,@a) if $no_sha1; + + grep($_="$dir/$_",@a); + @a=grep(!/(^|\/)s_/,@a) if $no_sock; + @a=grep(!/(^|\/)bio_sock/,@a) if $no_sock; + $ret=join(' ',@a)." "; + return($ret); + } + diff --git a/node-v0.8.14/deps/openssl/openssl/util/ck_errf.pl b/node-v0.8.14/deps/openssl/openssl/util/ck_errf.pl new file mode 100755 index 0000000..f13af5c --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/util/ck_errf.pl @@ -0,0 +1,64 @@ +#!/usr/local/bin/perl +# +# This is just a quick script to scan for cases where the 'error' +# function name in a XXXerr() macro is wrong. +# +# Run in the top level by going +# perl util/ck_errf.pl */*.c */*/*.c +# + +my $err_strict = 0; +my $bad = 0; + +foreach $file (@ARGV) + { + if ($file eq "-strict") + { + $err_strict = 1; + next; + } + open(IN,"<$file") || die "unable to open $file\n"; + $func=""; + while () + { + if (!/;$/ && /^([a-zA-Z].*[\s*])?([A-Za-z_0-9]+)\(.*[),]/) + { + /^([^()]*(\([^()]*\)[^()]*)*)\(/; + $1 =~ /([A-Za-z_0-9]*)$/; + $func = $1; + $func =~ tr/A-Z/a-z/; + } + if (/([A-Z0-9]+)err\(([^,]+)/ && ! /ckerr_ignore/) + { + $errlib=$1; + $n=$2; + + if ($func eq "") + { print "$file:$.:???:$n\n"; $bad = 1; next; } + + if ($n !~ /([^_]+)_F_(.+)$/) + { + # print "check -$file:$.:$func:$n\n"; + next; + } + $lib=$1; + $n=$2; + + if ($lib ne $errlib) + { print "$file:$.:$func:$n [${errlib}err]\n"; $bad = 1; next; } + + $n =~ tr/A-Z/a-z/; + if (($n ne $func) && ($errlib ne "SYS")) + { print "$file:$.:$func:$n\n"; $bad = 1; next; } + # print "$func:$1\n"; + } + } + close(IN); + } + +if ($bad && $err_strict) + { + print STDERR "FATAL: error discrepancy\n"; + exit 1; + } + diff --git a/node-v0.8.14/deps/openssl/openssl/util/clean-depend.pl b/node-v0.8.14/deps/openssl/openssl/util/clean-depend.pl new file mode 100755 index 0000000..d3525b0 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/util/clean-depend.pl @@ -0,0 +1,58 @@ +#!/usr/local/bin/perl -w +# Clean the dependency list in a makefile of standard includes... +# Written by Ben Laurie 19 Jan 1999 + +use strict; + +while() { + print; + last if /^# DO NOT DELETE THIS LINE/; +} + +my %files; + +my $thisfile=""; +while() { + my ($dummy, $file,$deps)=/^((.*):)? (.*)$/; + my $origfile=""; + $thisfile=$file if defined $file; + next if !defined $deps; + $origfile=$thisfile; + $origfile=~s/\.o$/.c/; + my @deps=split ' ',$deps; + @deps=grep(!/^\//,@deps); + @deps=grep(!/^\\$/,@deps); + @deps=grep(!/^$origfile$/,@deps); +# pull out the kludged kerberos header (if present). + @deps=grep(!/^[.\/]+\/krb5.h/,@deps); + push @{$files{$thisfile}},@deps; +} + +my $file; +foreach $file (sort keys %files) { + my $len=0; + my $dep; + my $origfile=$file; + $origfile=~s/\.o$/.c/; + $file=~s/^\.\///; + push @{$files{$file}},$origfile; + my $prevdep=""; + + # Remove leading ./ before sorting + my @deps = map { $_ =~ s/^\.\///; $_ } @{$files{$file}}; + + foreach $dep (sort @deps) { + $dep=~s/^\.\///; + next if $prevdep eq $dep; # to exterminate duplicates... + $prevdep = $dep; + $len=0 if $len+length($dep)+1 >= 80; + if($len == 0) { + print "\n$file:"; + $len=length($file)+1; + } + print " $dep"; + $len+=length($dep)+1; + } +} + +print "\n"; diff --git a/node-v0.8.14/deps/openssl/openssl/util/copy.pl b/node-v0.8.14/deps/openssl/openssl/util/copy.pl new file mode 100644 index 0000000..e20b455 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/util/copy.pl @@ -0,0 +1,59 @@ +#!/usr/local/bin/perl + +use Fcntl; + + +# copy.pl + +# Perl script 'copy' comment. On Windows the built in "copy" command also +# copies timestamps: this messes up Makefile dependencies. + +my $arg; + +foreach $arg (@ARGV) { + $arg =~ s|\\|/|g; # compensate for bug/feature in cygwin glob... + foreach (glob $arg) + { + push @filelist, $_; + } +} + +$fnum = @filelist; + +if ($fnum <= 1) + { + die "Need at least two filenames"; + } + +$dest = pop @filelist; + +if ($fnum > 2 && ! -d $dest) + { + die "Destination must be a directory"; + } + +foreach (@filelist) + { + if (-d $dest) + { + $dfile = $_; + $dfile =~ s|^.*[/\\]([^/\\]*)$|$1|; + $dfile = "$dest/$dfile"; + } + else + { + $dfile = $dest; + } + sysopen(IN, $_, O_RDONLY|O_BINARY) || die "Can't Open $_"; + sysopen(OUT, $dfile, O_WRONLY|O_CREAT|O_TRUNC|O_BINARY) + || die "Can't Open $dfile"; + while (sysread IN, $buf, 10240) + { + syswrite(OUT, $buf, length($buf)); + } + close(IN); + close(OUT); + print "Copying: $_ to $dfile\n"; + } + + diff --git a/node-v0.8.14/deps/openssl/openssl/util/cygwin.sh b/node-v0.8.14/deps/openssl/openssl/util/cygwin.sh new file mode 100755 index 0000000..d622852 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/util/cygwin.sh @@ -0,0 +1,146 @@ +#!/bin/bash +# +# This script configures, builds and packs the binary package for +# the Cygwin net distribution version of OpenSSL +# + +# Uncomment when debugging +#set -x + +CONFIG_OPTIONS="--prefix=/usr shared zlib no-idea no-rc5" +INSTALL_PREFIX=/tmp/install/INSTALL + +VERSION= +SUBVERSION=$1 + +function cleanup() +{ + rm -rf ${INSTALL_PREFIX}/etc + rm -rf ${INSTALL_PREFIX}/usr +} + +function get_openssl_version() +{ + eval `grep '^VERSION=' Makefile` + if [ -z "${VERSION}" ] + then + echo "Error: Couldn't retrieve OpenSSL version from Makefile." + echo " Check value of variable VERSION in Makefile." + exit 1 + fi +} + +function base_install() +{ + mkdir -p ${INSTALL_PREFIX} + cleanup + make install INSTALL_PREFIX="${INSTALL_PREFIX}" +} + +function doc_install() +{ + DOC_DIR=${INSTALL_PREFIX}/usr/share/doc/openssl + + mkdir -p ${DOC_DIR} + cp CHANGES CHANGES.SSLeay INSTALL LICENSE NEWS README ${DOC_DIR} + + create_cygwin_readme +} + +function certs_install() +{ + CERTS_DIR=${INSTALL_PREFIX}/usr/ssl/certs + + mkdir -p ${CERTS_DIR} + cp -rp certs/* ${CERTS_DIR} +} + +function create_cygwin_readme() +{ + README_DIR=${INSTALL_PREFIX}/usr/share/doc/Cygwin + README_FILE=${README_DIR}/openssl-${VERSION}.README + + mkdir -p ${README_DIR} + cat > ${README_FILE} <<- EOF + The Cygwin version has been built using the following configure: + + ./config ${CONFIG_OPTIONS} + + The IDEA and RC5 algorithms are disabled due to patent and/or + licensing issues. + EOF +} + +function create_profile_files() +{ + PROFILE_DIR=${INSTALL_PREFIX}/etc/profile.d + + mkdir -p $PROFILE_DIR + cat > ${PROFILE_DIR}/openssl.sh <<- "EOF" + export MANPATH="${MANPATH}:/usr/ssl/man" + EOF + cat > ${PROFILE_DIR}/openssl.csh <<- "EOF" + if ( $?MANPATH ) then + setenv MANPATH "${MANPATH}:/usr/ssl/man" + else + setenv MANPATH ":/usr/ssl/man" + endif + EOF +} + +if [ -z "${SUBVERSION}" ] +then + echo "Usage: $0 subversion" + exit 1 +fi + +if [ ! -f config ] +then + echo "You must start this script in the OpenSSL toplevel source dir." + exit 1 +fi + +./config ${CONFIG_OPTIONS} + +get_openssl_version + +make depend || exit 1 + +make || exit 1 + +base_install + +doc_install + +certs_install + +create_cygwin_readme + +create_profile_files + +cd ${INSTALL_PREFIX} +chmod u+w usr/lib/engines/*.so +strip usr/bin/*.exe usr/bin/*.dll usr/lib/engines/*.so +chmod u-w usr/lib/engines/*.so + +# Runtime package +tar cjf libopenssl${VERSION//[!0-9]/}-${VERSION}-${SUBVERSION}.tar.bz2 \ + usr/bin/cyg*dll +# Base package +find etc usr/bin/openssl.exe usr/bin/c_rehash usr/lib/engines usr/share/doc \ + usr/ssl/certs usr/ssl/man/man[157] usr/ssl/misc usr/ssl/openssl.cnf \ + usr/ssl/private \ + -empty -o \! -type d | +tar cjfT openssl-${VERSION}-${SUBVERSION}.tar.bz2 - +# Development package +find usr/include usr/lib/*.a usr/lib/pkgconfig usr/ssl/man/man3 \ + -empty -o \! -type d | +tar cjfT openssl-devel-${VERSION}-${SUBVERSION}.tar.bz2 - + +ls -l openssl-${VERSION}-${SUBVERSION}.tar.bz2 +ls -l openssl-devel-${VERSION}-${SUBVERSION}.tar.bz2 +ls -l libopenssl${VERSION//[!0-9]/}-${VERSION}-${SUBVERSION}.tar.bz2 + +cleanup + +exit 0 diff --git a/node-v0.8.14/deps/openssl/openssl/util/deleof.pl b/node-v0.8.14/deps/openssl/openssl/util/deleof.pl new file mode 100755 index 0000000..155acd8 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/util/deleof.pl @@ -0,0 +1,7 @@ +#!/usr/local/bin/perl + +while (<>) + { + print + last if (/^# DO NOT DELETE THIS LINE/); + } diff --git a/node-v0.8.14/deps/openssl/openssl/util/deltree.com b/node-v0.8.14/deps/openssl/openssl/util/deltree.com new file mode 100644 index 0000000..9f36b1a --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/util/deltree.com @@ -0,0 +1,34 @@ +$! DELTREE.COM +$ +$ call deltree 'p1' +$ exit $status +$ +$ deltree: subroutine ! P1 is a name of a directory +$ on control_y then goto dt_STOP +$ on warning then goto dt_exit +$ _dt_def = f$trnlnm("SYS$DISK")+f$directory() +$ if f$parse(p1) .eqs. "" then exit +$ set default 'f$parse(p1,,,"DEVICE")''f$parse(p1,,,"DIRECTORY")' +$ p1 = f$parse(p1,,,"NAME") + f$parse(p1,,,"TYPE") +$ _fp = f$parse(".DIR",p1) +$ dt_loop: +$ _f = f$search(_fp) +$ if _f .eqs. "" then goto dt_loopend +$ call deltree [.'f$parse(_f,,,"NAME")']*.* +$ goto dt_loop +$ dt_loopend: +$ _fp = f$parse(p1,".;*") +$ if f$search(_fp) .eqs. "" then goto dt_exit +$ set noon +$ set file/prot=(S:RWED,O:RWED,G:RWED,W:RWED) '_fp' +$ set on +$ delete/nolog '_fp' +$ dt_exit: +$ set default '_dt_def' +$ goto dt_end +$ dt_STOP: +$ set default '_dt_def' +$ stop/id="" +$ exit +$ dt_end: +$ endsubroutine diff --git a/node-v0.8.14/deps/openssl/openssl/util/dirname.pl b/node-v0.8.14/deps/openssl/openssl/util/dirname.pl new file mode 100644 index 0000000..d7a66d9 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/util/dirname.pl @@ -0,0 +1,18 @@ +#!/usr/local/bin/perl + +if ($#ARGV < 0) { + die "dirname.pl: too few arguments\n"; +} elsif ($#ARGV > 0) { + die "dirname.pl: too many arguments\n"; +} + +my $d = $ARGV[0]; + +if ($d =~ m|.*/.*|) { + $d =~ s|/[^/]*$||; +} else { + $d = "."; +} + +print $d,"\n"; +exit(0); diff --git a/node-v0.8.14/deps/openssl/openssl/util/do_ms.sh b/node-v0.8.14/deps/openssl/openssl/util/do_ms.sh new file mode 100755 index 0000000..515b074 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/util/do_ms.sh @@ -0,0 +1,19 @@ +#!/bin/sh +# +# generate the Microsoft makefiles and .def files +# + +PATH=util:../util:$PATH + +# perl util/mk1mf.pl no-sock VC-MSDOS >ms/msdos.mak +# perl util/mk1mf.pl VC-W31-32 >ms/w31.mak +perl util/mk1mf.pl dll VC-WIN16 >ms/w31dll.mak +# perl util/mk1mf.pl VC-WIN32 >ms/nt.mak +perl util/mk1mf.pl dll VC-WIN32 >ms/ntdll.mak +perl util/mk1mf.pl Mingw32 >ms/mingw32.mak +perl util/mk1mf.pl Mingw32-files >ms/mingw32f.mak + +perl util/mkdef.pl 16 libeay > ms/libeay16.def +perl util/mkdef.pl 32 libeay > ms/libeay32.def +perl util/mkdef.pl 16 ssleay > ms/ssleay16.def +perl util/mkdef.pl 32 ssleay > ms/ssleay32.def diff --git a/node-v0.8.14/deps/openssl/openssl/util/domd b/node-v0.8.14/deps/openssl/openssl/util/domd new file mode 100755 index 0000000..bab48cb --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/util/domd @@ -0,0 +1,38 @@ +#!/bin/sh +# Do a makedepend, only leave out the standard headers +# Written by Ben Laurie 19 Jan 1999 + +TOP=$1 +shift +if [ "$1" = "-MD" ]; then + shift + MAKEDEPEND=$1 + shift +fi +if [ "$MAKEDEPEND" = "" ]; then MAKEDEPEND=makedepend; fi + +cp Makefile Makefile.save +# fake the presence of Kerberos +touch $TOP/krb5.h +if expr "$MAKEDEPEND" : '.*gcc$' > /dev/null; then + args="" + while [ $# -gt 0 ]; do + if [ "$1" != "--" ]; then args="$args $1"; fi + shift + done + sed -e '/^# DO NOT DELETE.*/,$d' < Makefile > Makefile.tmp + echo '# DO NOT DELETE THIS LINE -- make depend depends on it.' >> Makefile.tmp + ${MAKEDEPEND} -Werror -D OPENSSL_DOING_MAKEDEPEND -M $args >> Makefile.tmp || exit 1 + ${PERL} $TOP/util/clean-depend.pl < Makefile.tmp > Makefile.new + RC=$? + rm -f Makefile.tmp +else + ${MAKEDEPEND} -D OPENSSL_DOING_MAKEDEPEND $@ && \ + ${PERL} $TOP/util/clean-depend.pl < Makefile > Makefile.new + RC=$? +fi +mv Makefile.new Makefile +# unfake the presence of Kerberos +rm $TOP/krb5.h + +exit $RC diff --git a/node-v0.8.14/deps/openssl/openssl/util/err-ins.pl b/node-v0.8.14/deps/openssl/openssl/util/err-ins.pl new file mode 100755 index 0000000..31b70df --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/util/err-ins.pl @@ -0,0 +1,33 @@ +#!/usr/local/bin/perl +# +# tack error codes onto the end of a file +# + +open(ERR,$ARGV[0]) || die "unable to open error file '$ARGV[0]':$!\n"; +@err=; +close(ERR); + +open(IN,$ARGV[1]) || die "unable to open header file '$ARGV[1]':$!\n"; + +@out=""; +while () + { + push(@out,$_); + last if /BEGIN ERROR CODES/; + } +close(IN); + +open(OUT,">$ARGV[1]") || die "unable to open header file '$ARGV[1]':$1\n"; +print OUT @out; +print OUT @err; +print OUT <<"EOF"; + +#ifdef __cplusplus +} +#endif +#endif + +EOF +close(OUT); + + diff --git a/node-v0.8.14/deps/openssl/openssl/util/extract-names.pl b/node-v0.8.14/deps/openssl/openssl/util/extract-names.pl new file mode 100644 index 0000000..35bd6ed --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/util/extract-names.pl @@ -0,0 +1,26 @@ +#!/usr/bin/perl + +$/ = ""; # Eat a paragraph at once. +while() { + chop; + s/\n/ /gm; + if (/^=head1 /) { + $name = 0; + } elsif ($name) { + if (/ - /) { + s/ - .*//; + s/,\s+/,/g; + s/\s+,/,/g; + s/^\s+//g; + s/\s+$//g; + s/\s/_/g; + push @words, split ','; + } + } + if (/^=head1 *NAME *$/) { + $name = 1; + } +} + +print join("\n", @words),"\n"; + diff --git a/node-v0.8.14/deps/openssl/openssl/util/extract-section.pl b/node-v0.8.14/deps/openssl/openssl/util/extract-section.pl new file mode 100644 index 0000000..7a0ba4f --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/util/extract-section.pl @@ -0,0 +1,12 @@ +#!/usr/bin/perl + +while() { + if (/=for\s+comment\s+openssl_manual_section:(\S+)/) + { + print "$1\n"; + exit 0; + } +} + +print "$ARGV[0]\n"; + diff --git a/node-v0.8.14/deps/openssl/openssl/util/files.pl b/node-v0.8.14/deps/openssl/openssl/util/files.pl new file mode 100755 index 0000000..41f033e --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/util/files.pl @@ -0,0 +1,61 @@ +#!/usr/local/bin/perl +# +# used to generate the file MINFO for use by util/mk1mf.pl +# It is basically a list of all variables from the passed makefile +# + +$s=""; +while (<>) + { + chop; + s/#.*//; + if (/^(\S+)\s*=\s*(.*)$/) + { + $o=""; + ($s,$b)=($1,$2); + for (;;) + { + if ($b =~ /\\$/) + { + chop($b); + $o.=$b." "; + $b=<>; + chop($b); + } + else + { + $o.=$b." "; + last; + } + } + $o =~ s/^\s+//; + $o =~ s/\s+$//; + $o =~ s/\s+/ /g; + + $o =~ s/\$[({]([^)}]+)[)}]/$sym{$1}/g; + $sym{$s}=$o; + } + } + +$pwd=`pwd`; chop($pwd); + +if ($sym{'TOP'} eq ".") + { + $n=0; + $dir="."; + } +else { + $n=split(/\//,$sym{'TOP'}); + @_=split(/\//,$pwd); + $z=$#_-$n+1; + foreach $i ($z .. $#_) { $dir.=$_[$i]."/"; } + chop($dir); + } + +print "RELATIVE_DIRECTORY=$dir\n"; + +foreach (sort keys %sym) + { + print "$_=$sym{$_}\n"; + } +print "RELATIVE_DIRECTORY=\n"; diff --git a/node-v0.8.14/deps/openssl/openssl/util/fixNT.sh b/node-v0.8.14/deps/openssl/openssl/util/fixNT.sh new file mode 100755 index 0000000..ab9e766 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/util/fixNT.sh @@ -0,0 +1,14 @@ +#!/bin/sh +# +# clean up the mess that NT makes of my source tree +# + +if [ -f makefile -a ! -f Makefile ]; then + /bin/mv makefile Makefile +fi +chmod +x Configure util/* +echo cleaning +/bin/rm -f `find . -name '*.$$$' -print` 2>/dev/null >/dev/null +echo 'removing those damn ^M' +perl -pi -e 's/\015//' `find . -type 'f' -print |grep -v '.obj$' |grep -v '.der$' |grep -v '.gz'` +make -f Makefile links diff --git a/node-v0.8.14/deps/openssl/openssl/util/install.sh b/node-v0.8.14/deps/openssl/openssl/util/install.sh new file mode 100755 index 0000000..e1d0c98 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/util/install.sh @@ -0,0 +1,108 @@ +#!/bin/sh +# +# install - install a program, script, or datafile +# This comes from X11R5; it is not part of GNU. +# +# $XConsortium: install.sh,v 1.2 89/12/18 14:47:22 jim Exp $ +# +# This script is compatible with the BSD install script, but was written +# from scratch. +# + + +# set DOITPROG to echo to test this script + +doit="${DOITPROG:-}" + + +# put in absolute paths if you don't have them in your path; or use env. vars. + +mvprog="${MVPROG:-mv}" +cpprog="${CPPROG:-cp}" +chmodprog="${CHMODPROG:-chmod}" +chownprog="${CHOWNPROG:-chown}" +chgrpprog="${CHGRPPROG:-chgrp}" +stripprog="${STRIPPROG:-strip}" +rmprog="${RMPROG:-rm}" + +instcmd="$mvprog" +chmodcmd="" +chowncmd="" +chgrpcmd="" +stripcmd="" +rmcmd="$rmprog -f" +src="" +dst="" + +while [ x"$1" != x ]; do + case $1 in + -c) instcmd="$cpprog" + shift + continue;; + + -m) chmodcmd="$chmodprog $2" + shift + shift + continue;; + + -o) chowncmd="$chownprog $2" + shift + shift + continue;; + + -g) chgrpcmd="$chgrpprog $2" + shift + shift + continue;; + + -s) stripcmd="$stripprog" + shift + continue;; + + *) if [ x"$src" = x ] + then + src=$1 + else + dst=$1 + fi + shift + continue;; + esac +done + +if [ x"$src" = x ] +then + echo "install: no input file specified" + exit 1 +fi + +if [ x"$dst" = x ] +then + echo "install: no destination specified" + exit 1 +fi + + +# if destination is a directory, append the input filename; if your system +# does not like double slashes in filenames, you may need to add some logic + +if [ -d $dst ] +then + dst="$dst"/`basename $src` +fi + + +# get rid of the old one and mode the new one in + +$doit $rmcmd $dst +$doit $instcmd $src $dst + + +# and set any options; do chmod last to preserve setuid bits + +if [ x"$chowncmd" != x ]; then $doit $chowncmd $dst; fi +if [ x"$chgrpcmd" != x ]; then $doit $chgrpcmd $dst; fi +if [ x"$stripcmd" != x ]; then $doit $stripcmd $dst; fi +if [ x"$chmodcmd" != x ]; then $doit $chmodcmd $dst; fi + +exit 0 diff --git a/node-v0.8.14/deps/openssl/openssl/util/libeay.num b/node-v0.8.14/deps/openssl/openssl/util/libeay.num new file mode 100755 index 0000000..b23619f --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/util/libeay.num @@ -0,0 +1,4196 @@ +SSLeay 1 EXIST::FUNCTION: +SSLeay_version 2 EXIST::FUNCTION: +ASN1_BIT_STRING_asn1_meth 3 NOEXIST::FUNCTION: +ASN1_HEADER_free 4 NOEXIST::FUNCTION: +ASN1_HEADER_new 5 NOEXIST::FUNCTION: +ASN1_IA5STRING_asn1_meth 6 NOEXIST::FUNCTION: +ASN1_INTEGER_get 7 EXIST::FUNCTION: +ASN1_INTEGER_set 8 EXIST::FUNCTION: +ASN1_INTEGER_to_BN 9 EXIST::FUNCTION: +ASN1_OBJECT_create 10 EXIST::FUNCTION: +ASN1_OBJECT_free 11 EXIST::FUNCTION: +ASN1_OBJECT_new 12 EXIST::FUNCTION: +ASN1_PRINTABLE_type 13 EXIST::FUNCTION: +ASN1_STRING_cmp 14 EXIST::FUNCTION: +ASN1_STRING_dup 15 EXIST::FUNCTION: +ASN1_STRING_free 16 EXIST::FUNCTION: +ASN1_STRING_new 17 EXIST::FUNCTION: +ASN1_STRING_print 18 EXIST::FUNCTION:BIO +ASN1_STRING_set 19 EXIST::FUNCTION: +ASN1_STRING_type_new 20 EXIST::FUNCTION: +ASN1_TYPE_free 21 EXIST::FUNCTION: +ASN1_TYPE_new 22 EXIST::FUNCTION: +ASN1_UNIVERSALSTRING_to_string 23 EXIST::FUNCTION: +ASN1_UTCTIME_check 24 EXIST::FUNCTION: +ASN1_UTCTIME_print 25 EXIST::FUNCTION:BIO +ASN1_UTCTIME_set 26 EXIST::FUNCTION: +ASN1_check_infinite_end 27 EXIST::FUNCTION: +ASN1_d2i_bio 28 EXIST::FUNCTION:BIO +ASN1_d2i_fp 29 EXIST::FUNCTION:FP_API +ASN1_digest 30 EXIST::FUNCTION:EVP +ASN1_dup 31 EXIST::FUNCTION: +ASN1_get_object 32 EXIST::FUNCTION: +ASN1_i2d_bio 33 EXIST::FUNCTION:BIO +ASN1_i2d_fp 34 EXIST::FUNCTION:FP_API +ASN1_object_size 35 EXIST::FUNCTION: +ASN1_parse 36 EXIST::FUNCTION:BIO +ASN1_put_object 37 EXIST::FUNCTION: +ASN1_sign 38 EXIST::FUNCTION:EVP +ASN1_verify 39 EXIST::FUNCTION:EVP +BF_cbc_encrypt 40 EXIST::FUNCTION:BF +BF_cfb64_encrypt 41 EXIST::FUNCTION:BF +BF_ecb_encrypt 42 EXIST::FUNCTION:BF +BF_encrypt 43 EXIST::FUNCTION:BF +BF_ofb64_encrypt 44 EXIST::FUNCTION:BF +BF_options 45 EXIST::FUNCTION:BF +BF_set_key 46 EXIST::FUNCTION:BF +BIO_CONNECT_free 47 NOEXIST::FUNCTION: +BIO_CONNECT_new 48 NOEXIST::FUNCTION: +BIO_accept 51 EXIST::FUNCTION: +BIO_ctrl 52 EXIST::FUNCTION: +BIO_int_ctrl 53 EXIST::FUNCTION: +BIO_debug_callback 54 EXIST::FUNCTION: +BIO_dump 55 EXIST::FUNCTION: +BIO_dup_chain 56 EXIST::FUNCTION: +BIO_f_base64 57 EXIST::FUNCTION:BIO +BIO_f_buffer 58 EXIST::FUNCTION: +BIO_f_cipher 59 EXIST::FUNCTION:BIO +BIO_f_md 60 EXIST::FUNCTION:BIO +BIO_f_null 61 EXIST::FUNCTION: +BIO_f_proxy_server 62 NOEXIST::FUNCTION: +BIO_fd_non_fatal_error 63 EXIST::FUNCTION: +BIO_fd_should_retry 64 EXIST::FUNCTION: +BIO_find_type 65 EXIST::FUNCTION: +BIO_free 66 EXIST::FUNCTION: +BIO_free_all 67 EXIST::FUNCTION: +BIO_get_accept_socket 69 EXIST::FUNCTION: +BIO_get_filter_bio 70 NOEXIST::FUNCTION: +BIO_get_host_ip 71 EXIST::FUNCTION: +BIO_get_port 72 EXIST::FUNCTION: +BIO_get_retry_BIO 73 EXIST::FUNCTION: +BIO_get_retry_reason 74 EXIST::FUNCTION: +BIO_gethostbyname 75 EXIST::FUNCTION: +BIO_gets 76 EXIST::FUNCTION: +BIO_new 78 EXIST::FUNCTION: +BIO_new_accept 79 EXIST::FUNCTION: +BIO_new_connect 80 EXIST::FUNCTION: +BIO_new_fd 81 EXIST::FUNCTION: +BIO_new_file 82 EXIST::FUNCTION:FP_API +BIO_new_fp 83 EXIST::FUNCTION:FP_API +BIO_new_socket 84 EXIST::FUNCTION: +BIO_pop 85 EXIST::FUNCTION: +BIO_printf 86 EXIST::FUNCTION: +BIO_push 87 EXIST::FUNCTION: +BIO_puts 88 EXIST::FUNCTION: +BIO_read 89 EXIST::FUNCTION: +BIO_s_accept 90 EXIST::FUNCTION: +BIO_s_connect 91 EXIST::FUNCTION: +BIO_s_fd 92 EXIST::FUNCTION: +BIO_s_file 93 EXIST::FUNCTION:FP_API +BIO_s_mem 95 EXIST::FUNCTION: +BIO_s_null 96 EXIST::FUNCTION: +BIO_s_proxy_client 97 NOEXIST::FUNCTION: +BIO_s_socket 98 EXIST::FUNCTION: +BIO_set 100 EXIST::FUNCTION: +BIO_set_cipher 101 EXIST::FUNCTION:BIO +BIO_set_tcp_ndelay 102 EXIST::FUNCTION: +BIO_sock_cleanup 103 EXIST::FUNCTION: +BIO_sock_error 104 EXIST::FUNCTION: +BIO_sock_init 105 EXIST::FUNCTION: +BIO_sock_non_fatal_error 106 EXIST::FUNCTION: +BIO_sock_should_retry 107 EXIST::FUNCTION: +BIO_socket_ioctl 108 EXIST::FUNCTION: +BIO_write 109 EXIST::FUNCTION: +BN_CTX_free 110 EXIST::FUNCTION: +BN_CTX_new 111 EXIST::FUNCTION: +BN_MONT_CTX_free 112 EXIST::FUNCTION: +BN_MONT_CTX_new 113 EXIST::FUNCTION: +BN_MONT_CTX_set 114 EXIST::FUNCTION: +BN_add 115 EXIST::FUNCTION: +BN_add_word 116 EXIST::FUNCTION: +BN_hex2bn 117 EXIST::FUNCTION: +BN_bin2bn 118 EXIST::FUNCTION: +BN_bn2hex 119 EXIST::FUNCTION: +BN_bn2bin 120 EXIST::FUNCTION: +BN_clear 121 EXIST::FUNCTION: +BN_clear_bit 122 EXIST::FUNCTION: +BN_clear_free 123 EXIST::FUNCTION: +BN_cmp 124 EXIST::FUNCTION: +BN_copy 125 EXIST::FUNCTION: +BN_div 126 EXIST::FUNCTION: +BN_div_word 127 EXIST::FUNCTION: +BN_dup 128 EXIST::FUNCTION: +BN_free 129 EXIST::FUNCTION: +BN_from_montgomery 130 EXIST::FUNCTION: +BN_gcd 131 EXIST::FUNCTION: +BN_generate_prime 132 EXIST::FUNCTION:DEPRECATED +BN_get_word 133 EXIST::FUNCTION: +BN_is_bit_set 134 EXIST::FUNCTION: +BN_is_prime 135 EXIST::FUNCTION:DEPRECATED +BN_lshift 136 EXIST::FUNCTION: +BN_lshift1 137 EXIST::FUNCTION: +BN_mask_bits 138 EXIST::FUNCTION: +BN_mod 139 NOEXIST::FUNCTION: +BN_mod_exp 140 EXIST::FUNCTION: +BN_mod_exp_mont 141 EXIST::FUNCTION: +BN_mod_exp_simple 143 EXIST::FUNCTION: +BN_mod_inverse 144 EXIST::FUNCTION: +BN_mod_mul 145 EXIST::FUNCTION: +BN_mod_mul_montgomery 146 EXIST::FUNCTION: +BN_mod_word 148 EXIST::FUNCTION: +BN_mul 149 EXIST::FUNCTION: +BN_new 150 EXIST::FUNCTION: +BN_num_bits 151 EXIST::FUNCTION: +BN_num_bits_word 152 EXIST::FUNCTION: +BN_options 153 EXIST::FUNCTION: +BN_print 154 EXIST::FUNCTION: +BN_print_fp 155 EXIST::FUNCTION:FP_API +BN_rand 156 EXIST::FUNCTION: +BN_reciprocal 157 EXIST::FUNCTION: +BN_rshift 158 EXIST::FUNCTION: +BN_rshift1 159 EXIST::FUNCTION: +BN_set_bit 160 EXIST::FUNCTION: +BN_set_word 161 EXIST::FUNCTION: +BN_sqr 162 EXIST::FUNCTION: +BN_sub 163 EXIST::FUNCTION: +BN_to_ASN1_INTEGER 164 EXIST::FUNCTION: +BN_ucmp 165 EXIST::FUNCTION: +BN_value_one 166 EXIST::FUNCTION: +BUF_MEM_free 167 EXIST::FUNCTION: +BUF_MEM_grow 168 EXIST::FUNCTION: +BUF_MEM_new 169 EXIST::FUNCTION: +BUF_strdup 170 EXIST::FUNCTION: +CONF_free 171 EXIST::FUNCTION: +CONF_get_number 172 EXIST::FUNCTION: +CONF_get_section 173 EXIST::FUNCTION: +CONF_get_string 174 EXIST::FUNCTION: +CONF_load 175 EXIST::FUNCTION: +CRYPTO_add_lock 176 EXIST::FUNCTION: +CRYPTO_dbg_free 177 EXIST::FUNCTION: +CRYPTO_dbg_malloc 178 EXIST::FUNCTION: +CRYPTO_dbg_realloc 179 EXIST::FUNCTION: +CRYPTO_dbg_remalloc 180 NOEXIST::FUNCTION: +CRYPTO_free 181 EXIST::FUNCTION: +CRYPTO_get_add_lock_callback 182 EXIST::FUNCTION: +CRYPTO_get_id_callback 183 EXIST::FUNCTION:DEPRECATED +CRYPTO_get_lock_name 184 EXIST::FUNCTION: +CRYPTO_get_locking_callback 185 EXIST::FUNCTION: +CRYPTO_get_mem_functions 186 EXIST::FUNCTION: +CRYPTO_lock 187 EXIST::FUNCTION: +CRYPTO_malloc 188 EXIST::FUNCTION: +CRYPTO_mem_ctrl 189 EXIST::FUNCTION: +CRYPTO_mem_leaks 190 EXIST::FUNCTION: +CRYPTO_mem_leaks_cb 191 EXIST::FUNCTION: +CRYPTO_mem_leaks_fp 192 EXIST::FUNCTION:FP_API +CRYPTO_realloc 193 EXIST::FUNCTION: +CRYPTO_remalloc 194 EXIST::FUNCTION: +CRYPTO_set_add_lock_callback 195 EXIST::FUNCTION: +CRYPTO_set_id_callback 196 EXIST::FUNCTION:DEPRECATED +CRYPTO_set_locking_callback 197 EXIST::FUNCTION: +CRYPTO_set_mem_functions 198 EXIST::FUNCTION: +CRYPTO_thread_id 199 EXIST::FUNCTION:DEPRECATED +DH_check 200 EXIST::FUNCTION:DH +DH_compute_key 201 EXIST::FUNCTION:DH +DH_free 202 EXIST::FUNCTION:DH +DH_generate_key 203 EXIST::FUNCTION:DH +DH_generate_parameters 204 EXIST::FUNCTION:DEPRECATED,DH +DH_new 205 EXIST::FUNCTION:DH +DH_size 206 EXIST::FUNCTION:DH +DHparams_print 207 EXIST::FUNCTION:BIO,DH +DHparams_print_fp 208 EXIST::FUNCTION:DH,FP_API +DSA_free 209 EXIST::FUNCTION:DSA +DSA_generate_key 210 EXIST::FUNCTION:DSA +DSA_generate_parameters 211 EXIST::FUNCTION:DEPRECATED,DSA +DSA_is_prime 212 NOEXIST::FUNCTION: +DSA_new 213 EXIST::FUNCTION:DSA +DSA_print 214 EXIST::FUNCTION:BIO,DSA +DSA_print_fp 215 EXIST::FUNCTION:DSA,FP_API +DSA_sign 216 EXIST::FUNCTION:DSA +DSA_sign_setup 217 EXIST::FUNCTION:DSA +DSA_size 218 EXIST::FUNCTION:DSA +DSA_verify 219 EXIST::FUNCTION:DSA +DSAparams_print 220 EXIST::FUNCTION:BIO,DSA +DSAparams_print_fp 221 EXIST::FUNCTION:DSA,FP_API +ERR_clear_error 222 EXIST::FUNCTION: +ERR_error_string 223 EXIST::FUNCTION: +ERR_free_strings 224 EXIST::FUNCTION: +ERR_func_error_string 225 EXIST::FUNCTION: +ERR_get_err_state_table 226 EXIST::FUNCTION:LHASH +ERR_get_error 227 EXIST::FUNCTION: +ERR_get_error_line 228 EXIST::FUNCTION: +ERR_get_state 229 EXIST::FUNCTION: +ERR_get_string_table 230 EXIST::FUNCTION:LHASH +ERR_lib_error_string 231 EXIST::FUNCTION: +ERR_load_ASN1_strings 232 EXIST::FUNCTION: +ERR_load_BIO_strings 233 EXIST::FUNCTION: +ERR_load_BN_strings 234 EXIST::FUNCTION: +ERR_load_BUF_strings 235 EXIST::FUNCTION: +ERR_load_CONF_strings 236 EXIST::FUNCTION: +ERR_load_DH_strings 237 EXIST::FUNCTION:DH +ERR_load_DSA_strings 238 EXIST::FUNCTION:DSA +ERR_load_ERR_strings 239 EXIST::FUNCTION: +ERR_load_EVP_strings 240 EXIST::FUNCTION: +ERR_load_OBJ_strings 241 EXIST::FUNCTION: +ERR_load_PEM_strings 242 EXIST::FUNCTION: +ERR_load_PROXY_strings 243 NOEXIST::FUNCTION: +ERR_load_RSA_strings 244 EXIST::FUNCTION:RSA +ERR_load_X509_strings 245 EXIST::FUNCTION: +ERR_load_crypto_strings 246 EXIST::FUNCTION: +ERR_load_strings 247 EXIST::FUNCTION: +ERR_peek_error 248 EXIST::FUNCTION: +ERR_peek_error_line 249 EXIST::FUNCTION: +ERR_print_errors 250 EXIST::FUNCTION:BIO +ERR_print_errors_fp 251 EXIST::FUNCTION:FP_API +ERR_put_error 252 EXIST::FUNCTION: +ERR_reason_error_string 253 EXIST::FUNCTION: +ERR_remove_state 254 EXIST::FUNCTION:DEPRECATED +EVP_BytesToKey 255 EXIST::FUNCTION: +EVP_CIPHER_CTX_cleanup 256 EXIST::FUNCTION: +EVP_CipherFinal 257 EXIST::FUNCTION: +EVP_CipherInit 258 EXIST::FUNCTION: +EVP_CipherUpdate 259 EXIST::FUNCTION: +EVP_DecodeBlock 260 EXIST::FUNCTION: +EVP_DecodeFinal 261 EXIST::FUNCTION: +EVP_DecodeInit 262 EXIST::FUNCTION: +EVP_DecodeUpdate 263 EXIST::FUNCTION: +EVP_DecryptFinal 264 EXIST::FUNCTION: +EVP_DecryptInit 265 EXIST::FUNCTION: +EVP_DecryptUpdate 266 EXIST::FUNCTION: +EVP_DigestFinal 267 EXIST::FUNCTION: +EVP_DigestInit 268 EXIST::FUNCTION: +EVP_DigestUpdate 269 EXIST::FUNCTION: +EVP_EncodeBlock 270 EXIST::FUNCTION: +EVP_EncodeFinal 271 EXIST::FUNCTION: +EVP_EncodeInit 272 EXIST::FUNCTION: +EVP_EncodeUpdate 273 EXIST::FUNCTION: +EVP_EncryptFinal 274 EXIST::FUNCTION: +EVP_EncryptInit 275 EXIST::FUNCTION: +EVP_EncryptUpdate 276 EXIST::FUNCTION: +EVP_OpenFinal 277 EXIST::FUNCTION:RSA +EVP_OpenInit 278 EXIST::FUNCTION:RSA +EVP_PKEY_assign 279 EXIST::FUNCTION: +EVP_PKEY_copy_parameters 280 EXIST::FUNCTION: +EVP_PKEY_free 281 EXIST::FUNCTION: +EVP_PKEY_missing_parameters 282 EXIST::FUNCTION: +EVP_PKEY_new 283 EXIST::FUNCTION: +EVP_PKEY_save_parameters 284 EXIST::FUNCTION: +EVP_PKEY_size 285 EXIST::FUNCTION: +EVP_PKEY_type 286 EXIST::FUNCTION: +EVP_SealFinal 287 EXIST::FUNCTION:RSA +EVP_SealInit 288 EXIST::FUNCTION:RSA +EVP_SignFinal 289 EXIST::FUNCTION: +EVP_VerifyFinal 290 EXIST::FUNCTION: +EVP_add_alias 291 NOEXIST::FUNCTION: +EVP_add_cipher 292 EXIST::FUNCTION: +EVP_add_digest 293 EXIST::FUNCTION: +EVP_bf_cbc 294 EXIST::FUNCTION:BF +EVP_bf_cfb64 295 EXIST::FUNCTION:BF +EVP_bf_ecb 296 EXIST::FUNCTION:BF +EVP_bf_ofb 297 EXIST::FUNCTION:BF +EVP_cleanup 298 EXIST::FUNCTION: +EVP_des_cbc 299 EXIST::FUNCTION:DES +EVP_des_cfb64 300 EXIST::FUNCTION:DES +EVP_des_ecb 301 EXIST::FUNCTION:DES +EVP_des_ede 302 EXIST::FUNCTION:DES +EVP_des_ede3 303 EXIST::FUNCTION:DES +EVP_des_ede3_cbc 304 EXIST::FUNCTION:DES +EVP_des_ede3_cfb64 305 EXIST::FUNCTION:DES +EVP_des_ede3_ofb 306 EXIST::FUNCTION:DES +EVP_des_ede_cbc 307 EXIST::FUNCTION:DES +EVP_des_ede_cfb64 308 EXIST::FUNCTION:DES +EVP_des_ede_ofb 309 EXIST::FUNCTION:DES +EVP_des_ofb 310 EXIST::FUNCTION:DES +EVP_desx_cbc 311 EXIST::FUNCTION:DES +EVP_dss 312 EXIST::FUNCTION:DSA,SHA +EVP_dss1 313 EXIST::FUNCTION:DSA,SHA +EVP_enc_null 314 EXIST::FUNCTION: +EVP_get_cipherbyname 315 EXIST::FUNCTION: +EVP_get_digestbyname 316 EXIST::FUNCTION: +EVP_get_pw_prompt 317 EXIST::FUNCTION: +EVP_idea_cbc 318 EXIST::FUNCTION:IDEA +EVP_idea_cfb64 319 EXIST::FUNCTION:IDEA +EVP_idea_ecb 320 EXIST::FUNCTION:IDEA +EVP_idea_ofb 321 EXIST::FUNCTION:IDEA +EVP_md2 322 EXIST::FUNCTION:MD2 +EVP_md5 323 EXIST::FUNCTION:MD5 +EVP_md_null 324 EXIST::FUNCTION: +EVP_rc2_cbc 325 EXIST::FUNCTION:RC2 +EVP_rc2_cfb64 326 EXIST::FUNCTION:RC2 +EVP_rc2_ecb 327 EXIST::FUNCTION:RC2 +EVP_rc2_ofb 328 EXIST::FUNCTION:RC2 +EVP_rc4 329 EXIST::FUNCTION:RC4 +EVP_read_pw_string 330 EXIST::FUNCTION: +EVP_set_pw_prompt 331 EXIST::FUNCTION: +EVP_sha 332 EXIST::FUNCTION:SHA +EVP_sha1 333 EXIST::FUNCTION:SHA +MD2 334 EXIST::FUNCTION:MD2 +MD2_Final 335 EXIST::FUNCTION:MD2 +MD2_Init 336 EXIST::FUNCTION:MD2 +MD2_Update 337 EXIST::FUNCTION:MD2 +MD2_options 338 EXIST::FUNCTION:MD2 +MD5 339 EXIST::FUNCTION:MD5 +MD5_Final 340 EXIST::FUNCTION:MD5 +MD5_Init 341 EXIST::FUNCTION:MD5 +MD5_Update 342 EXIST::FUNCTION:MD5 +MDC2 343 EXIST::FUNCTION:MDC2 +MDC2_Final 344 EXIST::FUNCTION:MDC2 +MDC2_Init 345 EXIST::FUNCTION:MDC2 +MDC2_Update 346 EXIST::FUNCTION:MDC2 +NETSCAPE_SPKAC_free 347 EXIST::FUNCTION: +NETSCAPE_SPKAC_new 348 EXIST::FUNCTION: +NETSCAPE_SPKI_free 349 EXIST::FUNCTION: +NETSCAPE_SPKI_new 350 EXIST::FUNCTION: +NETSCAPE_SPKI_sign 351 EXIST::FUNCTION:EVP +NETSCAPE_SPKI_verify 352 EXIST::FUNCTION:EVP +OBJ_add_object 353 EXIST::FUNCTION: +OBJ_bsearch 354 NOEXIST::FUNCTION: +OBJ_cleanup 355 EXIST::FUNCTION: +OBJ_cmp 356 EXIST::FUNCTION: +OBJ_create 357 EXIST::FUNCTION: +OBJ_dup 358 EXIST::FUNCTION: +OBJ_ln2nid 359 EXIST::FUNCTION: +OBJ_new_nid 360 EXIST::FUNCTION: +OBJ_nid2ln 361 EXIST::FUNCTION: +OBJ_nid2obj 362 EXIST::FUNCTION: +OBJ_nid2sn 363 EXIST::FUNCTION: +OBJ_obj2nid 364 EXIST::FUNCTION: +OBJ_sn2nid 365 EXIST::FUNCTION: +OBJ_txt2nid 366 EXIST::FUNCTION: +PEM_ASN1_read 367 EXIST::FUNCTION: +PEM_ASN1_read_bio 368 EXIST::FUNCTION:BIO +PEM_ASN1_write 369 EXIST::FUNCTION: +PEM_ASN1_write_bio 370 EXIST::FUNCTION:BIO +PEM_SealFinal 371 EXIST::FUNCTION:RSA +PEM_SealInit 372 EXIST::FUNCTION:RSA +PEM_SealUpdate 373 EXIST::FUNCTION:RSA +PEM_SignFinal 374 EXIST::FUNCTION: +PEM_SignInit 375 EXIST::FUNCTION: +PEM_SignUpdate 376 EXIST::FUNCTION: +PEM_X509_INFO_read 377 EXIST::FUNCTION: +PEM_X509_INFO_read_bio 378 EXIST::FUNCTION:BIO +PEM_X509_INFO_write_bio 379 EXIST::FUNCTION:BIO +PEM_dek_info 380 EXIST::FUNCTION: +PEM_do_header 381 EXIST::FUNCTION: +PEM_get_EVP_CIPHER_INFO 382 EXIST::FUNCTION: +PEM_proc_type 383 EXIST::FUNCTION: +PEM_read 384 EXIST::FUNCTION: +PEM_read_DHparams 385 EXIST:!WIN16:FUNCTION:DH +PEM_read_DSAPrivateKey 386 EXIST:!WIN16:FUNCTION:DSA +PEM_read_DSAparams 387 EXIST:!WIN16:FUNCTION:DSA +PEM_read_PKCS7 388 EXIST:!WIN16:FUNCTION: +PEM_read_PrivateKey 389 EXIST:!WIN16:FUNCTION: +PEM_read_RSAPrivateKey 390 EXIST:!WIN16:FUNCTION:RSA +PEM_read_X509 391 EXIST:!WIN16:FUNCTION: +PEM_read_X509_CRL 392 EXIST:!WIN16:FUNCTION: +PEM_read_X509_REQ 393 EXIST:!WIN16:FUNCTION: +PEM_read_bio 394 EXIST::FUNCTION:BIO +PEM_read_bio_DHparams 395 EXIST::FUNCTION:DH +PEM_read_bio_DSAPrivateKey 396 EXIST::FUNCTION:DSA +PEM_read_bio_DSAparams 397 EXIST::FUNCTION:DSA +PEM_read_bio_PKCS7 398 EXIST::FUNCTION: +PEM_read_bio_PrivateKey 399 EXIST::FUNCTION: +PEM_read_bio_RSAPrivateKey 400 EXIST::FUNCTION:RSA +PEM_read_bio_X509 401 EXIST::FUNCTION: +PEM_read_bio_X509_CRL 402 EXIST::FUNCTION: +PEM_read_bio_X509_REQ 403 EXIST::FUNCTION: +PEM_write 404 EXIST::FUNCTION: +PEM_write_DHparams 405 EXIST:!WIN16:FUNCTION:DH +PEM_write_DSAPrivateKey 406 EXIST:!WIN16:FUNCTION:DSA +PEM_write_DSAparams 407 EXIST:!WIN16:FUNCTION:DSA +PEM_write_PKCS7 408 EXIST:!WIN16:FUNCTION: +PEM_write_PrivateKey 409 EXIST:!WIN16:FUNCTION: +PEM_write_RSAPrivateKey 410 EXIST:!WIN16:FUNCTION:RSA +PEM_write_X509 411 EXIST:!WIN16:FUNCTION: +PEM_write_X509_CRL 412 EXIST:!WIN16:FUNCTION: +PEM_write_X509_REQ 413 EXIST:!WIN16:FUNCTION: +PEM_write_bio 414 EXIST::FUNCTION:BIO +PEM_write_bio_DHparams 415 EXIST::FUNCTION:DH +PEM_write_bio_DSAPrivateKey 416 EXIST::FUNCTION:DSA +PEM_write_bio_DSAparams 417 EXIST::FUNCTION:DSA +PEM_write_bio_PKCS7 418 EXIST::FUNCTION: +PEM_write_bio_PrivateKey 419 EXIST::FUNCTION: +PEM_write_bio_RSAPrivateKey 420 EXIST::FUNCTION:RSA +PEM_write_bio_X509 421 EXIST::FUNCTION: +PEM_write_bio_X509_CRL 422 EXIST::FUNCTION: +PEM_write_bio_X509_REQ 423 EXIST::FUNCTION: +PKCS7_DIGEST_free 424 EXIST::FUNCTION: +PKCS7_DIGEST_new 425 EXIST::FUNCTION: +PKCS7_ENCRYPT_free 426 EXIST::FUNCTION: +PKCS7_ENCRYPT_new 427 EXIST::FUNCTION: +PKCS7_ENC_CONTENT_free 428 EXIST::FUNCTION: +PKCS7_ENC_CONTENT_new 429 EXIST::FUNCTION: +PKCS7_ENVELOPE_free 430 EXIST::FUNCTION: +PKCS7_ENVELOPE_new 431 EXIST::FUNCTION: +PKCS7_ISSUER_AND_SERIAL_digest 432 EXIST::FUNCTION: +PKCS7_ISSUER_AND_SERIAL_free 433 EXIST::FUNCTION: +PKCS7_ISSUER_AND_SERIAL_new 434 EXIST::FUNCTION: +PKCS7_RECIP_INFO_free 435 EXIST::FUNCTION: +PKCS7_RECIP_INFO_new 436 EXIST::FUNCTION: +PKCS7_SIGNED_free 437 EXIST::FUNCTION: +PKCS7_SIGNED_new 438 EXIST::FUNCTION: +PKCS7_SIGNER_INFO_free 439 EXIST::FUNCTION: +PKCS7_SIGNER_INFO_new 440 EXIST::FUNCTION: +PKCS7_SIGN_ENVELOPE_free 441 EXIST::FUNCTION: +PKCS7_SIGN_ENVELOPE_new 442 EXIST::FUNCTION: +PKCS7_dup 443 EXIST::FUNCTION: +PKCS7_free 444 EXIST::FUNCTION: +PKCS7_new 445 EXIST::FUNCTION: +PROXY_ENTRY_add_noproxy 446 NOEXIST::FUNCTION: +PROXY_ENTRY_clear_noproxy 447 NOEXIST::FUNCTION: +PROXY_ENTRY_free 448 NOEXIST::FUNCTION: +PROXY_ENTRY_get_noproxy 449 NOEXIST::FUNCTION: +PROXY_ENTRY_new 450 NOEXIST::FUNCTION: +PROXY_ENTRY_set_server 451 NOEXIST::FUNCTION: +PROXY_add_noproxy 452 NOEXIST::FUNCTION: +PROXY_add_server 453 NOEXIST::FUNCTION: +PROXY_check_by_host 454 NOEXIST::FUNCTION: +PROXY_check_url 455 NOEXIST::FUNCTION: +PROXY_clear_noproxy 456 NOEXIST::FUNCTION: +PROXY_free 457 NOEXIST::FUNCTION: +PROXY_get_noproxy 458 NOEXIST::FUNCTION: +PROXY_get_proxies 459 NOEXIST::FUNCTION: +PROXY_get_proxy_entry 460 NOEXIST::FUNCTION: +PROXY_load_conf 461 NOEXIST::FUNCTION: +PROXY_new 462 NOEXIST::FUNCTION: +PROXY_print 463 NOEXIST::FUNCTION: +RAND_bytes 464 EXIST::FUNCTION: +RAND_cleanup 465 EXIST::FUNCTION: +RAND_file_name 466 EXIST::FUNCTION: +RAND_load_file 467 EXIST::FUNCTION: +RAND_screen 468 EXIST:WIN32:FUNCTION: +RAND_seed 469 EXIST::FUNCTION: +RAND_write_file 470 EXIST::FUNCTION: +RC2_cbc_encrypt 471 EXIST::FUNCTION:RC2 +RC2_cfb64_encrypt 472 EXIST::FUNCTION:RC2 +RC2_ecb_encrypt 473 EXIST::FUNCTION:RC2 +RC2_encrypt 474 EXIST::FUNCTION:RC2 +RC2_ofb64_encrypt 475 EXIST::FUNCTION:RC2 +RC2_set_key 476 EXIST::FUNCTION:RC2 +RC4 477 EXIST::FUNCTION:RC4 +RC4_options 478 EXIST::FUNCTION:RC4 +RC4_set_key 479 EXIST::FUNCTION:RC4 +RSAPrivateKey_asn1_meth 480 NOEXIST::FUNCTION: +RSAPrivateKey_dup 481 EXIST::FUNCTION:RSA +RSAPublicKey_dup 482 EXIST::FUNCTION:RSA +RSA_PKCS1_SSLeay 483 EXIST::FUNCTION:RSA +RSA_free 484 EXIST::FUNCTION:RSA +RSA_generate_key 485 EXIST::FUNCTION:DEPRECATED,RSA +RSA_new 486 EXIST::FUNCTION:RSA +RSA_new_method 487 EXIST::FUNCTION:RSA +RSA_print 488 EXIST::FUNCTION:BIO,RSA +RSA_print_fp 489 EXIST::FUNCTION:FP_API,RSA +RSA_private_decrypt 490 EXIST::FUNCTION:RSA +RSA_private_encrypt 491 EXIST::FUNCTION:RSA +RSA_public_decrypt 492 EXIST::FUNCTION:RSA +RSA_public_encrypt 493 EXIST::FUNCTION:RSA +RSA_set_default_method 494 EXIST::FUNCTION:RSA +RSA_sign 495 EXIST::FUNCTION:RSA +RSA_sign_ASN1_OCTET_STRING 496 EXIST::FUNCTION:RSA +RSA_size 497 EXIST::FUNCTION:RSA +RSA_verify 498 EXIST::FUNCTION:RSA +RSA_verify_ASN1_OCTET_STRING 499 EXIST::FUNCTION:RSA +SHA 500 EXIST::FUNCTION:SHA,SHA0 +SHA1 501 EXIST::FUNCTION:SHA,SHA1 +SHA1_Final 502 EXIST::FUNCTION:SHA,SHA1 +SHA1_Init 503 EXIST::FUNCTION:SHA,SHA1 +SHA1_Update 504 EXIST::FUNCTION:SHA,SHA1 +SHA_Final 505 EXIST::FUNCTION:SHA,SHA0 +SHA_Init 506 EXIST::FUNCTION:SHA,SHA0 +SHA_Update 507 EXIST::FUNCTION:SHA,SHA0 +OpenSSL_add_all_algorithms 508 NOEXIST::FUNCTION: +OpenSSL_add_all_ciphers 509 EXIST::FUNCTION: +OpenSSL_add_all_digests 510 EXIST::FUNCTION: +TXT_DB_create_index 511 EXIST::FUNCTION: +TXT_DB_free 512 EXIST::FUNCTION: +TXT_DB_get_by_index 513 EXIST::FUNCTION: +TXT_DB_insert 514 EXIST::FUNCTION: +TXT_DB_read 515 EXIST::FUNCTION:BIO +TXT_DB_write 516 EXIST::FUNCTION:BIO +X509_ALGOR_free 517 EXIST::FUNCTION: +X509_ALGOR_new 518 EXIST::FUNCTION: +X509_ATTRIBUTE_free 519 EXIST::FUNCTION: +X509_ATTRIBUTE_new 520 EXIST::FUNCTION: +X509_CINF_free 521 EXIST::FUNCTION: +X509_CINF_new 522 EXIST::FUNCTION: +X509_CRL_INFO_free 523 EXIST::FUNCTION: +X509_CRL_INFO_new 524 EXIST::FUNCTION: +X509_CRL_add_ext 525 EXIST::FUNCTION: +X509_CRL_cmp 526 EXIST::FUNCTION: +X509_CRL_delete_ext 527 EXIST::FUNCTION: +X509_CRL_dup 528 EXIST::FUNCTION: +X509_CRL_free 529 EXIST::FUNCTION: +X509_CRL_get_ext 530 EXIST::FUNCTION: +X509_CRL_get_ext_by_NID 531 EXIST::FUNCTION: +X509_CRL_get_ext_by_OBJ 532 EXIST::FUNCTION: +X509_CRL_get_ext_by_critical 533 EXIST::FUNCTION: +X509_CRL_get_ext_count 534 EXIST::FUNCTION: +X509_CRL_new 535 EXIST::FUNCTION: +X509_CRL_sign 536 EXIST::FUNCTION:EVP +X509_CRL_verify 537 EXIST::FUNCTION:EVP +X509_EXTENSION_create_by_NID 538 EXIST::FUNCTION: +X509_EXTENSION_create_by_OBJ 539 EXIST::FUNCTION: +X509_EXTENSION_dup 540 EXIST::FUNCTION: +X509_EXTENSION_free 541 EXIST::FUNCTION: +X509_EXTENSION_get_critical 542 EXIST::FUNCTION: +X509_EXTENSION_get_data 543 EXIST::FUNCTION: +X509_EXTENSION_get_object 544 EXIST::FUNCTION: +X509_EXTENSION_new 545 EXIST::FUNCTION: +X509_EXTENSION_set_critical 546 EXIST::FUNCTION: +X509_EXTENSION_set_data 547 EXIST::FUNCTION: +X509_EXTENSION_set_object 548 EXIST::FUNCTION: +X509_INFO_free 549 EXIST::FUNCTION:EVP +X509_INFO_new 550 EXIST::FUNCTION:EVP +X509_LOOKUP_by_alias 551 EXIST::FUNCTION: +X509_LOOKUP_by_fingerprint 552 EXIST::FUNCTION: +X509_LOOKUP_by_issuer_serial 553 EXIST::FUNCTION: +X509_LOOKUP_by_subject 554 EXIST::FUNCTION: +X509_LOOKUP_ctrl 555 EXIST::FUNCTION: +X509_LOOKUP_file 556 EXIST::FUNCTION: +X509_LOOKUP_free 557 EXIST::FUNCTION: +X509_LOOKUP_hash_dir 558 EXIST::FUNCTION: +X509_LOOKUP_init 559 EXIST::FUNCTION: +X509_LOOKUP_new 560 EXIST::FUNCTION: +X509_LOOKUP_shutdown 561 EXIST::FUNCTION: +X509_NAME_ENTRY_create_by_NID 562 EXIST::FUNCTION: +X509_NAME_ENTRY_create_by_OBJ 563 EXIST::FUNCTION: +X509_NAME_ENTRY_dup 564 EXIST::FUNCTION: +X509_NAME_ENTRY_free 565 EXIST::FUNCTION: +X509_NAME_ENTRY_get_data 566 EXIST::FUNCTION: +X509_NAME_ENTRY_get_object 567 EXIST::FUNCTION: +X509_NAME_ENTRY_new 568 EXIST::FUNCTION: +X509_NAME_ENTRY_set_data 569 EXIST::FUNCTION: +X509_NAME_ENTRY_set_object 570 EXIST::FUNCTION: +X509_NAME_add_entry 571 EXIST::FUNCTION: +X509_NAME_cmp 572 EXIST::FUNCTION: +X509_NAME_delete_entry 573 EXIST::FUNCTION: +X509_NAME_digest 574 EXIST::FUNCTION:EVP +X509_NAME_dup 575 EXIST::FUNCTION: +X509_NAME_entry_count 576 EXIST::FUNCTION: +X509_NAME_free 577 EXIST::FUNCTION: +X509_NAME_get_entry 578 EXIST::FUNCTION: +X509_NAME_get_index_by_NID 579 EXIST::FUNCTION: +X509_NAME_get_index_by_OBJ 580 EXIST::FUNCTION: +X509_NAME_get_text_by_NID 581 EXIST::FUNCTION: +X509_NAME_get_text_by_OBJ 582 EXIST::FUNCTION: +X509_NAME_hash 583 EXIST::FUNCTION: +X509_NAME_new 584 EXIST::FUNCTION: +X509_NAME_oneline 585 EXIST::FUNCTION:EVP +X509_NAME_print 586 EXIST::FUNCTION:BIO +X509_NAME_set 587 EXIST::FUNCTION: +X509_OBJECT_free_contents 588 EXIST::FUNCTION: +X509_OBJECT_retrieve_by_subject 589 EXIST::FUNCTION: +X509_OBJECT_up_ref_count 590 EXIST::FUNCTION: +X509_PKEY_free 591 EXIST::FUNCTION: +X509_PKEY_new 592 EXIST::FUNCTION: +X509_PUBKEY_free 593 EXIST::FUNCTION: +X509_PUBKEY_get 594 EXIST::FUNCTION: +X509_PUBKEY_new 595 EXIST::FUNCTION: +X509_PUBKEY_set 596 EXIST::FUNCTION: +X509_REQ_INFO_free 597 EXIST::FUNCTION: +X509_REQ_INFO_new 598 EXIST::FUNCTION: +X509_REQ_dup 599 EXIST::FUNCTION: +X509_REQ_free 600 EXIST::FUNCTION: +X509_REQ_get_pubkey 601 EXIST::FUNCTION: +X509_REQ_new 602 EXIST::FUNCTION: +X509_REQ_print 603 EXIST::FUNCTION:BIO +X509_REQ_print_fp 604 EXIST::FUNCTION:FP_API +X509_REQ_set_pubkey 605 EXIST::FUNCTION: +X509_REQ_set_subject_name 606 EXIST::FUNCTION: +X509_REQ_set_version 607 EXIST::FUNCTION: +X509_REQ_sign 608 EXIST::FUNCTION:EVP +X509_REQ_to_X509 609 EXIST::FUNCTION: +X509_REQ_verify 610 EXIST::FUNCTION:EVP +X509_REVOKED_add_ext 611 EXIST::FUNCTION: +X509_REVOKED_delete_ext 612 EXIST::FUNCTION: +X509_REVOKED_free 613 EXIST::FUNCTION: +X509_REVOKED_get_ext 614 EXIST::FUNCTION: +X509_REVOKED_get_ext_by_NID 615 EXIST::FUNCTION: +X509_REVOKED_get_ext_by_OBJ 616 EXIST::FUNCTION: +X509_REVOKED_get_ext_by_critical 617 EXIST:!VMS:FUNCTION: +X509_REVOKED_get_ext_by_critic 617 EXIST:VMS:FUNCTION: +X509_REVOKED_get_ext_count 618 EXIST::FUNCTION: +X509_REVOKED_new 619 EXIST::FUNCTION: +X509_SIG_free 620 EXIST::FUNCTION: +X509_SIG_new 621 EXIST::FUNCTION: +X509_STORE_CTX_cleanup 622 EXIST::FUNCTION: +X509_STORE_CTX_init 623 EXIST::FUNCTION: +X509_STORE_add_cert 624 EXIST::FUNCTION: +X509_STORE_add_lookup 625 EXIST::FUNCTION: +X509_STORE_free 626 EXIST::FUNCTION: +X509_STORE_get_by_subject 627 EXIST::FUNCTION: +X509_STORE_load_locations 628 EXIST::FUNCTION:STDIO +X509_STORE_new 629 EXIST::FUNCTION: +X509_STORE_set_default_paths 630 EXIST::FUNCTION:STDIO +X509_VAL_free 631 EXIST::FUNCTION: +X509_VAL_new 632 EXIST::FUNCTION: +X509_add_ext 633 EXIST::FUNCTION: +X509_asn1_meth 634 NOEXIST::FUNCTION: +X509_certificate_type 635 EXIST::FUNCTION: +X509_check_private_key 636 EXIST::FUNCTION: +X509_cmp_current_time 637 EXIST::FUNCTION: +X509_delete_ext 638 EXIST::FUNCTION: +X509_digest 639 EXIST::FUNCTION:EVP +X509_dup 640 EXIST::FUNCTION: +X509_free 641 EXIST::FUNCTION: +X509_get_default_cert_area 642 EXIST::FUNCTION: +X509_get_default_cert_dir 643 EXIST::FUNCTION: +X509_get_default_cert_dir_env 644 EXIST::FUNCTION: +X509_get_default_cert_file 645 EXIST::FUNCTION: +X509_get_default_cert_file_env 646 EXIST::FUNCTION: +X509_get_default_private_dir 647 EXIST::FUNCTION: +X509_get_ext 648 EXIST::FUNCTION: +X509_get_ext_by_NID 649 EXIST::FUNCTION: +X509_get_ext_by_OBJ 650 EXIST::FUNCTION: +X509_get_ext_by_critical 651 EXIST::FUNCTION: +X509_get_ext_count 652 EXIST::FUNCTION: +X509_get_issuer_name 653 EXIST::FUNCTION: +X509_get_pubkey 654 EXIST::FUNCTION: +X509_get_pubkey_parameters 655 EXIST::FUNCTION: +X509_get_serialNumber 656 EXIST::FUNCTION: +X509_get_subject_name 657 EXIST::FUNCTION: +X509_gmtime_adj 658 EXIST::FUNCTION: +X509_issuer_and_serial_cmp 659 EXIST::FUNCTION: +X509_issuer_and_serial_hash 660 EXIST::FUNCTION: +X509_issuer_name_cmp 661 EXIST::FUNCTION: +X509_issuer_name_hash 662 EXIST::FUNCTION: +X509_load_cert_file 663 EXIST::FUNCTION:STDIO +X509_new 664 EXIST::FUNCTION: +X509_print 665 EXIST::FUNCTION:BIO +X509_print_fp 666 EXIST::FUNCTION:FP_API +X509_set_issuer_name 667 EXIST::FUNCTION: +X509_set_notAfter 668 EXIST::FUNCTION: +X509_set_notBefore 669 EXIST::FUNCTION: +X509_set_pubkey 670 EXIST::FUNCTION: +X509_set_serialNumber 671 EXIST::FUNCTION: +X509_set_subject_name 672 EXIST::FUNCTION: +X509_set_version 673 EXIST::FUNCTION: +X509_sign 674 EXIST::FUNCTION:EVP +X509_subject_name_cmp 675 EXIST::FUNCTION: +X509_subject_name_hash 676 EXIST::FUNCTION: +X509_to_X509_REQ 677 EXIST::FUNCTION: +X509_verify 678 EXIST::FUNCTION:EVP +X509_verify_cert 679 EXIST::FUNCTION: +X509_verify_cert_error_string 680 EXIST::FUNCTION: +X509v3_add_ext 681 EXIST::FUNCTION: +X509v3_add_extension 682 NOEXIST::FUNCTION: +X509v3_add_netscape_extensions 683 NOEXIST::FUNCTION: +X509v3_add_standard_extensions 684 NOEXIST::FUNCTION: +X509v3_cleanup_extensions 685 NOEXIST::FUNCTION: +X509v3_data_type_by_NID 686 NOEXIST::FUNCTION: +X509v3_data_type_by_OBJ 687 NOEXIST::FUNCTION: +X509v3_delete_ext 688 EXIST::FUNCTION: +X509v3_get_ext 689 EXIST::FUNCTION: +X509v3_get_ext_by_NID 690 EXIST::FUNCTION: +X509v3_get_ext_by_OBJ 691 EXIST::FUNCTION: +X509v3_get_ext_by_critical 692 EXIST::FUNCTION: +X509v3_get_ext_count 693 EXIST::FUNCTION: +X509v3_pack_string 694 NOEXIST::FUNCTION: +X509v3_pack_type_by_NID 695 NOEXIST::FUNCTION: +X509v3_pack_type_by_OBJ 696 NOEXIST::FUNCTION: +X509v3_unpack_string 697 NOEXIST::FUNCTION: +_des_crypt 698 NOEXIST::FUNCTION: +a2d_ASN1_OBJECT 699 EXIST::FUNCTION: +a2i_ASN1_INTEGER 700 EXIST::FUNCTION:BIO +a2i_ASN1_STRING 701 EXIST::FUNCTION:BIO +asn1_Finish 702 EXIST::FUNCTION: +asn1_GetSequence 703 EXIST::FUNCTION: +bn_div_words 704 EXIST::FUNCTION: +bn_expand2 705 EXIST::FUNCTION: +bn_mul_add_words 706 EXIST::FUNCTION: +bn_mul_words 707 EXIST::FUNCTION: +BN_uadd 708 EXIST::FUNCTION: +BN_usub 709 EXIST::FUNCTION: +bn_sqr_words 710 EXIST::FUNCTION: +_ossl_old_crypt 711 EXIST:!NeXT,!PERL5:FUNCTION:DES +d2i_ASN1_BIT_STRING 712 EXIST::FUNCTION: +d2i_ASN1_BOOLEAN 713 EXIST::FUNCTION: +d2i_ASN1_HEADER 714 NOEXIST::FUNCTION: +d2i_ASN1_IA5STRING 715 EXIST::FUNCTION: +d2i_ASN1_INTEGER 716 EXIST::FUNCTION: +d2i_ASN1_OBJECT 717 EXIST::FUNCTION: +d2i_ASN1_OCTET_STRING 718 EXIST::FUNCTION: +d2i_ASN1_PRINTABLE 719 EXIST::FUNCTION: +d2i_ASN1_PRINTABLESTRING 720 EXIST::FUNCTION: +d2i_ASN1_SET 721 EXIST::FUNCTION: +d2i_ASN1_T61STRING 722 EXIST::FUNCTION: +d2i_ASN1_TYPE 723 EXIST::FUNCTION: +d2i_ASN1_UTCTIME 724 EXIST::FUNCTION: +d2i_ASN1_bytes 725 EXIST::FUNCTION: +d2i_ASN1_type_bytes 726 EXIST::FUNCTION: +d2i_DHparams 727 EXIST::FUNCTION:DH +d2i_DSAPrivateKey 728 EXIST::FUNCTION:DSA +d2i_DSAPrivateKey_bio 729 EXIST::FUNCTION:BIO,DSA +d2i_DSAPrivateKey_fp 730 EXIST::FUNCTION:DSA,FP_API +d2i_DSAPublicKey 731 EXIST::FUNCTION:DSA +d2i_DSAparams 732 EXIST::FUNCTION:DSA +d2i_NETSCAPE_SPKAC 733 EXIST::FUNCTION: +d2i_NETSCAPE_SPKI 734 EXIST::FUNCTION: +d2i_Netscape_RSA 735 EXIST::FUNCTION:RC4,RSA +d2i_PKCS7 736 EXIST::FUNCTION: +d2i_PKCS7_DIGEST 737 EXIST::FUNCTION: +d2i_PKCS7_ENCRYPT 738 EXIST::FUNCTION: +d2i_PKCS7_ENC_CONTENT 739 EXIST::FUNCTION: +d2i_PKCS7_ENVELOPE 740 EXIST::FUNCTION: +d2i_PKCS7_ISSUER_AND_SERIAL 741 EXIST::FUNCTION: +d2i_PKCS7_RECIP_INFO 742 EXIST::FUNCTION: +d2i_PKCS7_SIGNED 743 EXIST::FUNCTION: +d2i_PKCS7_SIGNER_INFO 744 EXIST::FUNCTION: +d2i_PKCS7_SIGN_ENVELOPE 745 EXIST::FUNCTION: +d2i_PKCS7_bio 746 EXIST::FUNCTION: +d2i_PKCS7_fp 747 EXIST::FUNCTION:FP_API +d2i_PrivateKey 748 EXIST::FUNCTION: +d2i_PublicKey 749 EXIST::FUNCTION: +d2i_RSAPrivateKey 750 EXIST::FUNCTION:RSA +d2i_RSAPrivateKey_bio 751 EXIST::FUNCTION:BIO,RSA +d2i_RSAPrivateKey_fp 752 EXIST::FUNCTION:FP_API,RSA +d2i_RSAPublicKey 753 EXIST::FUNCTION:RSA +d2i_X509 754 EXIST::FUNCTION: +d2i_X509_ALGOR 755 EXIST::FUNCTION: +d2i_X509_ATTRIBUTE 756 EXIST::FUNCTION: +d2i_X509_CINF 757 EXIST::FUNCTION: +d2i_X509_CRL 758 EXIST::FUNCTION: +d2i_X509_CRL_INFO 759 EXIST::FUNCTION: +d2i_X509_CRL_bio 760 EXIST::FUNCTION:BIO +d2i_X509_CRL_fp 761 EXIST::FUNCTION:FP_API +d2i_X509_EXTENSION 762 EXIST::FUNCTION: +d2i_X509_NAME 763 EXIST::FUNCTION: +d2i_X509_NAME_ENTRY 764 EXIST::FUNCTION: +d2i_X509_PKEY 765 EXIST::FUNCTION: +d2i_X509_PUBKEY 766 EXIST::FUNCTION: +d2i_X509_REQ 767 EXIST::FUNCTION: +d2i_X509_REQ_INFO 768 EXIST::FUNCTION: +d2i_X509_REQ_bio 769 EXIST::FUNCTION:BIO +d2i_X509_REQ_fp 770 EXIST::FUNCTION:FP_API +d2i_X509_REVOKED 771 EXIST::FUNCTION: +d2i_X509_SIG 772 EXIST::FUNCTION: +d2i_X509_VAL 773 EXIST::FUNCTION: +d2i_X509_bio 774 EXIST::FUNCTION:BIO +d2i_X509_fp 775 EXIST::FUNCTION:FP_API +DES_cbc_cksum 777 EXIST::FUNCTION:DES +DES_cbc_encrypt 778 EXIST::FUNCTION:DES +DES_cblock_print_file 779 NOEXIST::FUNCTION: +DES_cfb64_encrypt 780 EXIST::FUNCTION:DES +DES_cfb_encrypt 781 EXIST::FUNCTION:DES +DES_decrypt3 782 EXIST::FUNCTION:DES +DES_ecb3_encrypt 783 EXIST::FUNCTION:DES +DES_ecb_encrypt 784 EXIST::FUNCTION:DES +DES_ede3_cbc_encrypt 785 EXIST::FUNCTION:DES +DES_ede3_cfb64_encrypt 786 EXIST::FUNCTION:DES +DES_ede3_ofb64_encrypt 787 EXIST::FUNCTION:DES +DES_enc_read 788 EXIST::FUNCTION:DES +DES_enc_write 789 EXIST::FUNCTION:DES +DES_encrypt1 790 EXIST::FUNCTION:DES +DES_encrypt2 791 EXIST::FUNCTION:DES +DES_encrypt3 792 EXIST::FUNCTION:DES +DES_fcrypt 793 EXIST::FUNCTION:DES +DES_is_weak_key 794 EXIST::FUNCTION:DES +DES_key_sched 795 EXIST::FUNCTION:DES +DES_ncbc_encrypt 796 EXIST::FUNCTION:DES +DES_ofb64_encrypt 797 EXIST::FUNCTION:DES +DES_ofb_encrypt 798 EXIST::FUNCTION:DES +DES_options 799 EXIST::FUNCTION:DES +DES_pcbc_encrypt 800 EXIST::FUNCTION:DES +DES_quad_cksum 801 EXIST::FUNCTION:DES +DES_random_key 802 EXIST::FUNCTION:DES +_ossl_old_des_random_seed 803 EXIST::FUNCTION:DES +_ossl_old_des_read_2passwords 804 EXIST::FUNCTION:DES +_ossl_old_des_read_password 805 EXIST::FUNCTION:DES +_ossl_old_des_read_pw 806 EXIST::FUNCTION: +_ossl_old_des_read_pw_string 807 EXIST::FUNCTION: +DES_set_key 808 EXIST::FUNCTION:DES +DES_set_odd_parity 809 EXIST::FUNCTION:DES +DES_string_to_2keys 810 EXIST::FUNCTION:DES +DES_string_to_key 811 EXIST::FUNCTION:DES +DES_xcbc_encrypt 812 EXIST::FUNCTION:DES +DES_xwhite_in2out 813 NOEXIST::FUNCTION: +fcrypt_body 814 NOEXIST::FUNCTION: +i2a_ASN1_INTEGER 815 EXIST::FUNCTION:BIO +i2a_ASN1_OBJECT 816 EXIST::FUNCTION:BIO +i2a_ASN1_STRING 817 EXIST::FUNCTION:BIO +i2d_ASN1_BIT_STRING 818 EXIST::FUNCTION: +i2d_ASN1_BOOLEAN 819 EXIST::FUNCTION: +i2d_ASN1_HEADER 820 NOEXIST::FUNCTION: +i2d_ASN1_IA5STRING 821 EXIST::FUNCTION: +i2d_ASN1_INTEGER 822 EXIST::FUNCTION: +i2d_ASN1_OBJECT 823 EXIST::FUNCTION: +i2d_ASN1_OCTET_STRING 824 EXIST::FUNCTION: +i2d_ASN1_PRINTABLE 825 EXIST::FUNCTION: +i2d_ASN1_SET 826 EXIST::FUNCTION: +i2d_ASN1_TYPE 827 EXIST::FUNCTION: +i2d_ASN1_UTCTIME 828 EXIST::FUNCTION: +i2d_ASN1_bytes 829 EXIST::FUNCTION: +i2d_DHparams 830 EXIST::FUNCTION:DH +i2d_DSAPrivateKey 831 EXIST::FUNCTION:DSA +i2d_DSAPrivateKey_bio 832 EXIST::FUNCTION:BIO,DSA +i2d_DSAPrivateKey_fp 833 EXIST::FUNCTION:DSA,FP_API +i2d_DSAPublicKey 834 EXIST::FUNCTION:DSA +i2d_DSAparams 835 EXIST::FUNCTION:DSA +i2d_NETSCAPE_SPKAC 836 EXIST::FUNCTION: +i2d_NETSCAPE_SPKI 837 EXIST::FUNCTION: +i2d_Netscape_RSA 838 EXIST::FUNCTION:RC4,RSA +i2d_PKCS7 839 EXIST::FUNCTION: +i2d_PKCS7_DIGEST 840 EXIST::FUNCTION: +i2d_PKCS7_ENCRYPT 841 EXIST::FUNCTION: +i2d_PKCS7_ENC_CONTENT 842 EXIST::FUNCTION: +i2d_PKCS7_ENVELOPE 843 EXIST::FUNCTION: +i2d_PKCS7_ISSUER_AND_SERIAL 844 EXIST::FUNCTION: +i2d_PKCS7_RECIP_INFO 845 EXIST::FUNCTION: +i2d_PKCS7_SIGNED 846 EXIST::FUNCTION: +i2d_PKCS7_SIGNER_INFO 847 EXIST::FUNCTION: +i2d_PKCS7_SIGN_ENVELOPE 848 EXIST::FUNCTION: +i2d_PKCS7_bio 849 EXIST::FUNCTION: +i2d_PKCS7_fp 850 EXIST::FUNCTION:FP_API +i2d_PrivateKey 851 EXIST::FUNCTION: +i2d_PublicKey 852 EXIST::FUNCTION: +i2d_RSAPrivateKey 853 EXIST::FUNCTION:RSA +i2d_RSAPrivateKey_bio 854 EXIST::FUNCTION:BIO,RSA +i2d_RSAPrivateKey_fp 855 EXIST::FUNCTION:FP_API,RSA +i2d_RSAPublicKey 856 EXIST::FUNCTION:RSA +i2d_X509 857 EXIST::FUNCTION: +i2d_X509_ALGOR 858 EXIST::FUNCTION: +i2d_X509_ATTRIBUTE 859 EXIST::FUNCTION: +i2d_X509_CINF 860 EXIST::FUNCTION: +i2d_X509_CRL 861 EXIST::FUNCTION: +i2d_X509_CRL_INFO 862 EXIST::FUNCTION: +i2d_X509_CRL_bio 863 EXIST::FUNCTION:BIO +i2d_X509_CRL_fp 864 EXIST::FUNCTION:FP_API +i2d_X509_EXTENSION 865 EXIST::FUNCTION: +i2d_X509_NAME 866 EXIST::FUNCTION: +i2d_X509_NAME_ENTRY 867 EXIST::FUNCTION: +i2d_X509_PKEY 868 EXIST::FUNCTION: +i2d_X509_PUBKEY 869 EXIST::FUNCTION: +i2d_X509_REQ 870 EXIST::FUNCTION: +i2d_X509_REQ_INFO 871 EXIST::FUNCTION: +i2d_X509_REQ_bio 872 EXIST::FUNCTION:BIO +i2d_X509_REQ_fp 873 EXIST::FUNCTION:FP_API +i2d_X509_REVOKED 874 EXIST::FUNCTION: +i2d_X509_SIG 875 EXIST::FUNCTION: +i2d_X509_VAL 876 EXIST::FUNCTION: +i2d_X509_bio 877 EXIST::FUNCTION:BIO +i2d_X509_fp 878 EXIST::FUNCTION:FP_API +idea_cbc_encrypt 879 EXIST::FUNCTION:IDEA +idea_cfb64_encrypt 880 EXIST::FUNCTION:IDEA +idea_ecb_encrypt 881 EXIST::FUNCTION:IDEA +idea_encrypt 882 EXIST::FUNCTION:IDEA +idea_ofb64_encrypt 883 EXIST::FUNCTION:IDEA +idea_options 884 EXIST::FUNCTION:IDEA +idea_set_decrypt_key 885 EXIST::FUNCTION:IDEA +idea_set_encrypt_key 886 EXIST::FUNCTION:IDEA +lh_delete 887 EXIST::FUNCTION: +lh_doall 888 EXIST::FUNCTION: +lh_doall_arg 889 EXIST::FUNCTION: +lh_free 890 EXIST::FUNCTION: +lh_insert 891 EXIST::FUNCTION: +lh_new 892 EXIST::FUNCTION: +lh_node_stats 893 EXIST::FUNCTION:FP_API +lh_node_stats_bio 894 EXIST::FUNCTION:BIO +lh_node_usage_stats 895 EXIST::FUNCTION:FP_API +lh_node_usage_stats_bio 896 EXIST::FUNCTION:BIO +lh_retrieve 897 EXIST::FUNCTION: +lh_stats 898 EXIST::FUNCTION:FP_API +lh_stats_bio 899 EXIST::FUNCTION:BIO +lh_strhash 900 EXIST::FUNCTION: +sk_delete 901 EXIST::FUNCTION: +sk_delete_ptr 902 EXIST::FUNCTION: +sk_dup 903 EXIST::FUNCTION: +sk_find 904 EXIST::FUNCTION: +sk_free 905 EXIST::FUNCTION: +sk_insert 906 EXIST::FUNCTION: +sk_new 907 EXIST::FUNCTION: +sk_pop 908 EXIST::FUNCTION: +sk_pop_free 909 EXIST::FUNCTION: +sk_push 910 EXIST::FUNCTION: +sk_set_cmp_func 911 EXIST::FUNCTION: +sk_shift 912 EXIST::FUNCTION: +sk_unshift 913 EXIST::FUNCTION: +sk_zero 914 EXIST::FUNCTION: +BIO_f_nbio_test 915 EXIST::FUNCTION: +ASN1_TYPE_get 916 EXIST::FUNCTION: +ASN1_TYPE_set 917 EXIST::FUNCTION: +PKCS7_content_free 918 NOEXIST::FUNCTION: +ERR_load_PKCS7_strings 919 EXIST::FUNCTION: +X509_find_by_issuer_and_serial 920 EXIST::FUNCTION: +X509_find_by_subject 921 EXIST::FUNCTION: +PKCS7_ctrl 927 EXIST::FUNCTION: +PKCS7_set_type 928 EXIST::FUNCTION: +PKCS7_set_content 929 EXIST::FUNCTION: +PKCS7_SIGNER_INFO_set 930 EXIST::FUNCTION: +PKCS7_add_signer 931 EXIST::FUNCTION: +PKCS7_add_certificate 932 EXIST::FUNCTION: +PKCS7_add_crl 933 EXIST::FUNCTION: +PKCS7_content_new 934 EXIST::FUNCTION: +PKCS7_dataSign 935 NOEXIST::FUNCTION: +PKCS7_dataVerify 936 EXIST::FUNCTION: +PKCS7_dataInit 937 EXIST::FUNCTION: +PKCS7_add_signature 938 EXIST::FUNCTION: +PKCS7_cert_from_signer_info 939 EXIST::FUNCTION: +PKCS7_get_signer_info 940 EXIST::FUNCTION: +EVP_delete_alias 941 NOEXIST::FUNCTION: +EVP_mdc2 942 EXIST::FUNCTION:MDC2 +PEM_read_bio_RSAPublicKey 943 EXIST::FUNCTION:RSA +PEM_write_bio_RSAPublicKey 944 EXIST::FUNCTION:RSA +d2i_RSAPublicKey_bio 945 EXIST::FUNCTION:BIO,RSA +i2d_RSAPublicKey_bio 946 EXIST::FUNCTION:BIO,RSA +PEM_read_RSAPublicKey 947 EXIST:!WIN16:FUNCTION:RSA +PEM_write_RSAPublicKey 949 EXIST:!WIN16:FUNCTION:RSA +d2i_RSAPublicKey_fp 952 EXIST::FUNCTION:FP_API,RSA +i2d_RSAPublicKey_fp 954 EXIST::FUNCTION:FP_API,RSA +BIO_copy_next_retry 955 EXIST::FUNCTION: +RSA_flags 956 EXIST::FUNCTION:RSA +X509_STORE_add_crl 957 EXIST::FUNCTION: +X509_load_crl_file 958 EXIST::FUNCTION:STDIO +EVP_rc2_40_cbc 959 EXIST::FUNCTION:RC2 +EVP_rc4_40 960 EXIST::FUNCTION:RC4 +EVP_CIPHER_CTX_init 961 EXIST::FUNCTION: +HMAC 962 EXIST::FUNCTION:HMAC +HMAC_Init 963 EXIST::FUNCTION:HMAC +HMAC_Update 964 EXIST::FUNCTION:HMAC +HMAC_Final 965 EXIST::FUNCTION:HMAC +ERR_get_next_error_library 966 EXIST::FUNCTION: +EVP_PKEY_cmp_parameters 967 EXIST::FUNCTION: +HMAC_cleanup 968 NOEXIST::FUNCTION: +BIO_ptr_ctrl 969 EXIST::FUNCTION: +BIO_new_file_internal 970 NOEXIST::FUNCTION: +BIO_new_fp_internal 971 NOEXIST::FUNCTION: +BIO_s_file_internal 972 NOEXIST::FUNCTION: +BN_BLINDING_convert 973 EXIST::FUNCTION: +BN_BLINDING_invert 974 EXIST::FUNCTION: +BN_BLINDING_update 975 EXIST::FUNCTION: +RSA_blinding_on 977 EXIST::FUNCTION:RSA +RSA_blinding_off 978 EXIST::FUNCTION:RSA +i2t_ASN1_OBJECT 979 EXIST::FUNCTION: +BN_BLINDING_new 980 EXIST::FUNCTION: +BN_BLINDING_free 981 EXIST::FUNCTION: +EVP_cast5_cbc 983 EXIST::FUNCTION:CAST +EVP_cast5_cfb64 984 EXIST::FUNCTION:CAST +EVP_cast5_ecb 985 EXIST::FUNCTION:CAST +EVP_cast5_ofb 986 EXIST::FUNCTION:CAST +BF_decrypt 987 EXIST::FUNCTION:BF +CAST_set_key 988 EXIST::FUNCTION:CAST +CAST_encrypt 989 EXIST::FUNCTION:CAST +CAST_decrypt 990 EXIST::FUNCTION:CAST +CAST_ecb_encrypt 991 EXIST::FUNCTION:CAST +CAST_cbc_encrypt 992 EXIST::FUNCTION:CAST +CAST_cfb64_encrypt 993 EXIST::FUNCTION:CAST +CAST_ofb64_encrypt 994 EXIST::FUNCTION:CAST +RC2_decrypt 995 EXIST::FUNCTION:RC2 +OBJ_create_objects 997 EXIST::FUNCTION: +BN_exp 998 EXIST::FUNCTION: +BN_mul_word 999 EXIST::FUNCTION: +BN_sub_word 1000 EXIST::FUNCTION: +BN_dec2bn 1001 EXIST::FUNCTION: +BN_bn2dec 1002 EXIST::FUNCTION: +BIO_ghbn_ctrl 1003 NOEXIST::FUNCTION: +CRYPTO_free_ex_data 1004 EXIST::FUNCTION: +CRYPTO_get_ex_data 1005 EXIST::FUNCTION: +CRYPTO_set_ex_data 1007 EXIST::FUNCTION: +ERR_load_CRYPTO_strings 1009 EXIST:!OS2,!VMS:FUNCTION: +ERR_load_CRYPTOlib_strings 1009 EXIST:OS2,VMS:FUNCTION: +EVP_PKEY_bits 1010 EXIST::FUNCTION: +MD5_Transform 1011 EXIST::FUNCTION:MD5 +SHA1_Transform 1012 EXIST::FUNCTION:SHA,SHA1 +SHA_Transform 1013 EXIST::FUNCTION:SHA,SHA0 +X509_STORE_CTX_get_chain 1014 EXIST::FUNCTION: +X509_STORE_CTX_get_current_cert 1015 EXIST::FUNCTION: +X509_STORE_CTX_get_error 1016 EXIST::FUNCTION: +X509_STORE_CTX_get_error_depth 1017 EXIST::FUNCTION: +X509_STORE_CTX_get_ex_data 1018 EXIST::FUNCTION: +X509_STORE_CTX_set_cert 1020 EXIST::FUNCTION: +X509_STORE_CTX_set_chain 1021 EXIST::FUNCTION: +X509_STORE_CTX_set_error 1022 EXIST::FUNCTION: +X509_STORE_CTX_set_ex_data 1023 EXIST::FUNCTION: +CRYPTO_dup_ex_data 1025 EXIST::FUNCTION: +CRYPTO_get_new_lockid 1026 EXIST::FUNCTION: +CRYPTO_new_ex_data 1027 EXIST::FUNCTION: +RSA_set_ex_data 1028 EXIST::FUNCTION:RSA +RSA_get_ex_data 1029 EXIST::FUNCTION:RSA +RSA_get_ex_new_index 1030 EXIST::FUNCTION:RSA +RSA_padding_add_PKCS1_type_1 1031 EXIST::FUNCTION:RSA +RSA_padding_add_PKCS1_type_2 1032 EXIST::FUNCTION:RSA +RSA_padding_add_SSLv23 1033 EXIST::FUNCTION:RSA +RSA_padding_add_none 1034 EXIST::FUNCTION:RSA +RSA_padding_check_PKCS1_type_1 1035 EXIST::FUNCTION:RSA +RSA_padding_check_PKCS1_type_2 1036 EXIST::FUNCTION:RSA +RSA_padding_check_SSLv23 1037 EXIST::FUNCTION:RSA +RSA_padding_check_none 1038 EXIST::FUNCTION:RSA +bn_add_words 1039 EXIST::FUNCTION: +d2i_Netscape_RSA_2 1040 NOEXIST::FUNCTION: +CRYPTO_get_ex_new_index 1041 EXIST::FUNCTION: +RIPEMD160_Init 1042 EXIST::FUNCTION:RIPEMD +RIPEMD160_Update 1043 EXIST::FUNCTION:RIPEMD +RIPEMD160_Final 1044 EXIST::FUNCTION:RIPEMD +RIPEMD160 1045 EXIST::FUNCTION:RIPEMD +RIPEMD160_Transform 1046 EXIST::FUNCTION:RIPEMD +RC5_32_set_key 1047 EXIST::FUNCTION:RC5 +RC5_32_ecb_encrypt 1048 EXIST::FUNCTION:RC5 +RC5_32_encrypt 1049 EXIST::FUNCTION:RC5 +RC5_32_decrypt 1050 EXIST::FUNCTION:RC5 +RC5_32_cbc_encrypt 1051 EXIST::FUNCTION:RC5 +RC5_32_cfb64_encrypt 1052 EXIST::FUNCTION:RC5 +RC5_32_ofb64_encrypt 1053 EXIST::FUNCTION:RC5 +BN_bn2mpi 1058 EXIST::FUNCTION: +BN_mpi2bn 1059 EXIST::FUNCTION: +ASN1_BIT_STRING_get_bit 1060 EXIST::FUNCTION: +ASN1_BIT_STRING_set_bit 1061 EXIST::FUNCTION: +BIO_get_ex_data 1062 EXIST::FUNCTION: +BIO_get_ex_new_index 1063 EXIST::FUNCTION: +BIO_set_ex_data 1064 EXIST::FUNCTION: +X509v3_get_key_usage 1066 NOEXIST::FUNCTION: +X509v3_set_key_usage 1067 NOEXIST::FUNCTION: +a2i_X509v3_key_usage 1068 NOEXIST::FUNCTION: +i2a_X509v3_key_usage 1069 NOEXIST::FUNCTION: +EVP_PKEY_decrypt 1070 EXIST::FUNCTION: +EVP_PKEY_encrypt 1071 EXIST::FUNCTION: +PKCS7_RECIP_INFO_set 1072 EXIST::FUNCTION: +PKCS7_add_recipient 1073 EXIST::FUNCTION: +PKCS7_add_recipient_info 1074 EXIST::FUNCTION: +PKCS7_set_cipher 1075 EXIST::FUNCTION: +ASN1_TYPE_get_int_octetstring 1076 EXIST::FUNCTION: +ASN1_TYPE_get_octetstring 1077 EXIST::FUNCTION: +ASN1_TYPE_set_int_octetstring 1078 EXIST::FUNCTION: +ASN1_TYPE_set_octetstring 1079 EXIST::FUNCTION: +ASN1_UTCTIME_set_string 1080 EXIST::FUNCTION: +ERR_add_error_data 1081 EXIST::FUNCTION:BIO +ERR_set_error_data 1082 EXIST::FUNCTION: +EVP_CIPHER_asn1_to_param 1083 EXIST::FUNCTION: +EVP_CIPHER_param_to_asn1 1084 EXIST::FUNCTION: +EVP_CIPHER_get_asn1_iv 1085 EXIST::FUNCTION: +EVP_CIPHER_set_asn1_iv 1086 EXIST::FUNCTION: +EVP_rc5_32_12_16_cbc 1087 EXIST::FUNCTION:RC5 +EVP_rc5_32_12_16_cfb64 1088 EXIST::FUNCTION:RC5 +EVP_rc5_32_12_16_ecb 1089 EXIST::FUNCTION:RC5 +EVP_rc5_32_12_16_ofb 1090 EXIST::FUNCTION:RC5 +asn1_add_error 1091 EXIST::FUNCTION: +d2i_ASN1_BMPSTRING 1092 EXIST::FUNCTION: +i2d_ASN1_BMPSTRING 1093 EXIST::FUNCTION: +BIO_f_ber 1094 NOEXIST::FUNCTION: +BN_init 1095 EXIST::FUNCTION: +COMP_CTX_new 1096 EXIST::FUNCTION: +COMP_CTX_free 1097 EXIST::FUNCTION: +COMP_CTX_compress_block 1098 NOEXIST::FUNCTION: +COMP_CTX_expand_block 1099 NOEXIST::FUNCTION: +X509_STORE_CTX_get_ex_new_index 1100 EXIST::FUNCTION: +OBJ_NAME_add 1101 EXIST::FUNCTION: +BIO_socket_nbio 1102 EXIST::FUNCTION: +EVP_rc2_64_cbc 1103 EXIST::FUNCTION:RC2 +OBJ_NAME_cleanup 1104 EXIST::FUNCTION: +OBJ_NAME_get 1105 EXIST::FUNCTION: +OBJ_NAME_init 1106 EXIST::FUNCTION: +OBJ_NAME_new_index 1107 EXIST::FUNCTION: +OBJ_NAME_remove 1108 EXIST::FUNCTION: +BN_MONT_CTX_copy 1109 EXIST::FUNCTION: +BIO_new_socks4a_connect 1110 NOEXIST::FUNCTION: +BIO_s_socks4a_connect 1111 NOEXIST::FUNCTION: +PROXY_set_connect_mode 1112 NOEXIST::FUNCTION: +RAND_SSLeay 1113 EXIST::FUNCTION: +RAND_set_rand_method 1114 EXIST::FUNCTION: +RSA_memory_lock 1115 EXIST::FUNCTION:RSA +bn_sub_words 1116 EXIST::FUNCTION: +bn_mul_normal 1117 NOEXIST::FUNCTION: +bn_mul_comba8 1118 NOEXIST::FUNCTION: +bn_mul_comba4 1119 NOEXIST::FUNCTION: +bn_sqr_normal 1120 NOEXIST::FUNCTION: +bn_sqr_comba8 1121 NOEXIST::FUNCTION: +bn_sqr_comba4 1122 NOEXIST::FUNCTION: +bn_cmp_words 1123 NOEXIST::FUNCTION: +bn_mul_recursive 1124 NOEXIST::FUNCTION: +bn_mul_part_recursive 1125 NOEXIST::FUNCTION: +bn_sqr_recursive 1126 NOEXIST::FUNCTION: +bn_mul_low_normal 1127 NOEXIST::FUNCTION: +BN_RECP_CTX_init 1128 EXIST::FUNCTION: +BN_RECP_CTX_new 1129 EXIST::FUNCTION: +BN_RECP_CTX_free 1130 EXIST::FUNCTION: +BN_RECP_CTX_set 1131 EXIST::FUNCTION: +BN_mod_mul_reciprocal 1132 EXIST::FUNCTION: +BN_mod_exp_recp 1133 EXIST::FUNCTION: +BN_div_recp 1134 EXIST::FUNCTION: +BN_CTX_init 1135 EXIST::FUNCTION:DEPRECATED +BN_MONT_CTX_init 1136 EXIST::FUNCTION: +RAND_get_rand_method 1137 EXIST::FUNCTION: +PKCS7_add_attribute 1138 EXIST::FUNCTION: +PKCS7_add_signed_attribute 1139 EXIST::FUNCTION: +PKCS7_digest_from_attributes 1140 EXIST::FUNCTION: +PKCS7_get_attribute 1141 EXIST::FUNCTION: +PKCS7_get_issuer_and_serial 1142 EXIST::FUNCTION: +PKCS7_get_signed_attribute 1143 EXIST::FUNCTION: +COMP_compress_block 1144 EXIST::FUNCTION: +COMP_expand_block 1145 EXIST::FUNCTION: +COMP_rle 1146 EXIST::FUNCTION: +COMP_zlib 1147 EXIST::FUNCTION: +ms_time_diff 1148 NOEXIST::FUNCTION: +ms_time_new 1149 NOEXIST::FUNCTION: +ms_time_free 1150 NOEXIST::FUNCTION: +ms_time_cmp 1151 NOEXIST::FUNCTION: +ms_time_get 1152 NOEXIST::FUNCTION: +PKCS7_set_attributes 1153 EXIST::FUNCTION: +PKCS7_set_signed_attributes 1154 EXIST::FUNCTION: +X509_ATTRIBUTE_create 1155 EXIST::FUNCTION: +X509_ATTRIBUTE_dup 1156 EXIST::FUNCTION: +ASN1_GENERALIZEDTIME_check 1157 EXIST::FUNCTION: +ASN1_GENERALIZEDTIME_print 1158 EXIST::FUNCTION:BIO +ASN1_GENERALIZEDTIME_set 1159 EXIST::FUNCTION: +ASN1_GENERALIZEDTIME_set_string 1160 EXIST::FUNCTION: +ASN1_TIME_print 1161 EXIST::FUNCTION:BIO +BASIC_CONSTRAINTS_free 1162 EXIST::FUNCTION: +BASIC_CONSTRAINTS_new 1163 EXIST::FUNCTION: +ERR_load_X509V3_strings 1164 EXIST::FUNCTION: +NETSCAPE_CERT_SEQUENCE_free 1165 EXIST::FUNCTION: +NETSCAPE_CERT_SEQUENCE_new 1166 EXIST::FUNCTION: +OBJ_txt2obj 1167 EXIST::FUNCTION: +PEM_read_NETSCAPE_CERT_SEQUENCE 1168 EXIST:!VMS,!WIN16:FUNCTION: +PEM_read_NS_CERT_SEQ 1168 EXIST:VMS:FUNCTION: +PEM_read_bio_NETSCAPE_CERT_SEQUENCE 1169 EXIST:!VMS:FUNCTION: +PEM_read_bio_NS_CERT_SEQ 1169 EXIST:VMS:FUNCTION: +PEM_write_NETSCAPE_CERT_SEQUENCE 1170 EXIST:!VMS,!WIN16:FUNCTION: +PEM_write_NS_CERT_SEQ 1170 EXIST:VMS:FUNCTION: +PEM_write_bio_NETSCAPE_CERT_SEQUENCE 1171 EXIST:!VMS:FUNCTION: +PEM_write_bio_NS_CERT_SEQ 1171 EXIST:VMS:FUNCTION: +X509V3_EXT_add 1172 EXIST::FUNCTION: +X509V3_EXT_add_alias 1173 EXIST::FUNCTION: +X509V3_EXT_add_conf 1174 EXIST::FUNCTION: +X509V3_EXT_cleanup 1175 EXIST::FUNCTION: +X509V3_EXT_conf 1176 EXIST::FUNCTION: +X509V3_EXT_conf_nid 1177 EXIST::FUNCTION: +X509V3_EXT_get 1178 EXIST::FUNCTION: +X509V3_EXT_get_nid 1179 EXIST::FUNCTION: +X509V3_EXT_print 1180 EXIST::FUNCTION: +X509V3_EXT_print_fp 1181 EXIST::FUNCTION: +X509V3_add_standard_extensions 1182 EXIST::FUNCTION: +X509V3_add_value 1183 EXIST::FUNCTION: +X509V3_add_value_bool 1184 EXIST::FUNCTION: +X509V3_add_value_int 1185 EXIST::FUNCTION: +X509V3_conf_free 1186 EXIST::FUNCTION: +X509V3_get_value_bool 1187 EXIST::FUNCTION: +X509V3_get_value_int 1188 EXIST::FUNCTION: +X509V3_parse_list 1189 EXIST::FUNCTION: +d2i_ASN1_GENERALIZEDTIME 1190 EXIST::FUNCTION: +d2i_ASN1_TIME 1191 EXIST::FUNCTION: +d2i_BASIC_CONSTRAINTS 1192 EXIST::FUNCTION: +d2i_NETSCAPE_CERT_SEQUENCE 1193 EXIST::FUNCTION: +d2i_ext_ku 1194 NOEXIST::FUNCTION: +ext_ku_free 1195 NOEXIST::FUNCTION: +ext_ku_new 1196 NOEXIST::FUNCTION: +i2d_ASN1_GENERALIZEDTIME 1197 EXIST::FUNCTION: +i2d_ASN1_TIME 1198 EXIST::FUNCTION: +i2d_BASIC_CONSTRAINTS 1199 EXIST::FUNCTION: +i2d_NETSCAPE_CERT_SEQUENCE 1200 EXIST::FUNCTION: +i2d_ext_ku 1201 NOEXIST::FUNCTION: +EVP_MD_CTX_copy 1202 EXIST::FUNCTION: +i2d_ASN1_ENUMERATED 1203 EXIST::FUNCTION: +d2i_ASN1_ENUMERATED 1204 EXIST::FUNCTION: +ASN1_ENUMERATED_set 1205 EXIST::FUNCTION: +ASN1_ENUMERATED_get 1206 EXIST::FUNCTION: +BN_to_ASN1_ENUMERATED 1207 EXIST::FUNCTION: +ASN1_ENUMERATED_to_BN 1208 EXIST::FUNCTION: +i2a_ASN1_ENUMERATED 1209 EXIST::FUNCTION:BIO +a2i_ASN1_ENUMERATED 1210 EXIST::FUNCTION:BIO +i2d_GENERAL_NAME 1211 EXIST::FUNCTION: +d2i_GENERAL_NAME 1212 EXIST::FUNCTION: +GENERAL_NAME_new 1213 EXIST::FUNCTION: +GENERAL_NAME_free 1214 EXIST::FUNCTION: +GENERAL_NAMES_new 1215 EXIST::FUNCTION: +GENERAL_NAMES_free 1216 EXIST::FUNCTION: +d2i_GENERAL_NAMES 1217 EXIST::FUNCTION: +i2d_GENERAL_NAMES 1218 EXIST::FUNCTION: +i2v_GENERAL_NAMES 1219 EXIST::FUNCTION: +i2s_ASN1_OCTET_STRING 1220 EXIST::FUNCTION: +s2i_ASN1_OCTET_STRING 1221 EXIST::FUNCTION: +X509V3_EXT_check_conf 1222 NOEXIST::FUNCTION: +hex_to_string 1223 EXIST::FUNCTION: +string_to_hex 1224 EXIST::FUNCTION: +DES_ede3_cbcm_encrypt 1225 EXIST::FUNCTION:DES +RSA_padding_add_PKCS1_OAEP 1226 EXIST::FUNCTION:RSA +RSA_padding_check_PKCS1_OAEP 1227 EXIST::FUNCTION:RSA +X509_CRL_print_fp 1228 EXIST::FUNCTION:FP_API +X509_CRL_print 1229 EXIST::FUNCTION:BIO +i2v_GENERAL_NAME 1230 EXIST::FUNCTION: +v2i_GENERAL_NAME 1231 EXIST::FUNCTION: +i2d_PKEY_USAGE_PERIOD 1232 EXIST::FUNCTION: +d2i_PKEY_USAGE_PERIOD 1233 EXIST::FUNCTION: +PKEY_USAGE_PERIOD_new 1234 EXIST::FUNCTION: +PKEY_USAGE_PERIOD_free 1235 EXIST::FUNCTION: +v2i_GENERAL_NAMES 1236 EXIST::FUNCTION: +i2s_ASN1_INTEGER 1237 EXIST::FUNCTION: +X509V3_EXT_d2i 1238 EXIST::FUNCTION: +name_cmp 1239 EXIST::FUNCTION: +str_dup 1240 NOEXIST::FUNCTION: +i2s_ASN1_ENUMERATED 1241 EXIST::FUNCTION: +i2s_ASN1_ENUMERATED_TABLE 1242 EXIST::FUNCTION: +BIO_s_log 1243 EXIST:!OS2,!WIN16,!WIN32,!macintosh:FUNCTION: +BIO_f_reliable 1244 EXIST::FUNCTION:BIO +PKCS7_dataFinal 1245 EXIST::FUNCTION: +PKCS7_dataDecode 1246 EXIST::FUNCTION: +X509V3_EXT_CRL_add_conf 1247 EXIST::FUNCTION: +BN_set_params 1248 EXIST::FUNCTION:DEPRECATED +BN_get_params 1249 EXIST::FUNCTION:DEPRECATED +BIO_get_ex_num 1250 NOEXIST::FUNCTION: +BIO_set_ex_free_func 1251 NOEXIST::FUNCTION: +EVP_ripemd160 1252 EXIST::FUNCTION:RIPEMD +ASN1_TIME_set 1253 EXIST::FUNCTION: +i2d_AUTHORITY_KEYID 1254 EXIST::FUNCTION: +d2i_AUTHORITY_KEYID 1255 EXIST::FUNCTION: +AUTHORITY_KEYID_new 1256 EXIST::FUNCTION: +AUTHORITY_KEYID_free 1257 EXIST::FUNCTION: +ASN1_seq_unpack 1258 EXIST::FUNCTION: +ASN1_seq_pack 1259 EXIST::FUNCTION: +ASN1_unpack_string 1260 EXIST::FUNCTION: +ASN1_pack_string 1261 EXIST::FUNCTION: +PKCS12_pack_safebag 1262 NOEXIST::FUNCTION: +PKCS12_MAKE_KEYBAG 1263 EXIST::FUNCTION: +PKCS8_encrypt 1264 EXIST::FUNCTION: +PKCS12_MAKE_SHKEYBAG 1265 EXIST::FUNCTION: +PKCS12_pack_p7data 1266 EXIST::FUNCTION: +PKCS12_pack_p7encdata 1267 EXIST::FUNCTION: +PKCS12_add_localkeyid 1268 EXIST::FUNCTION: +PKCS12_add_friendlyname_asc 1269 EXIST::FUNCTION: +PKCS12_add_friendlyname_uni 1270 EXIST::FUNCTION: +PKCS12_get_friendlyname 1271 EXIST::FUNCTION: +PKCS12_pbe_crypt 1272 EXIST::FUNCTION: +PKCS12_decrypt_d2i 1273 NOEXIST::FUNCTION: +PKCS12_i2d_encrypt 1274 NOEXIST::FUNCTION: +PKCS12_init 1275 EXIST::FUNCTION: +PKCS12_key_gen_asc 1276 EXIST::FUNCTION: +PKCS12_key_gen_uni 1277 EXIST::FUNCTION: +PKCS12_gen_mac 1278 EXIST::FUNCTION: +PKCS12_verify_mac 1279 EXIST::FUNCTION: +PKCS12_set_mac 1280 EXIST::FUNCTION: +PKCS12_setup_mac 1281 EXIST::FUNCTION: +OPENSSL_asc2uni 1282 EXIST::FUNCTION: +OPENSSL_uni2asc 1283 EXIST::FUNCTION: +i2d_PKCS12_BAGS 1284 EXIST::FUNCTION: +PKCS12_BAGS_new 1285 EXIST::FUNCTION: +d2i_PKCS12_BAGS 1286 EXIST::FUNCTION: +PKCS12_BAGS_free 1287 EXIST::FUNCTION: +i2d_PKCS12 1288 EXIST::FUNCTION: +d2i_PKCS12 1289 EXIST::FUNCTION: +PKCS12_new 1290 EXIST::FUNCTION: +PKCS12_free 1291 EXIST::FUNCTION: +i2d_PKCS12_MAC_DATA 1292 EXIST::FUNCTION: +PKCS12_MAC_DATA_new 1293 EXIST::FUNCTION: +d2i_PKCS12_MAC_DATA 1294 EXIST::FUNCTION: +PKCS12_MAC_DATA_free 1295 EXIST::FUNCTION: +i2d_PKCS12_SAFEBAG 1296 EXIST::FUNCTION: +PKCS12_SAFEBAG_new 1297 EXIST::FUNCTION: +d2i_PKCS12_SAFEBAG 1298 EXIST::FUNCTION: +PKCS12_SAFEBAG_free 1299 EXIST::FUNCTION: +ERR_load_PKCS12_strings 1300 EXIST::FUNCTION: +PKCS12_PBE_add 1301 EXIST::FUNCTION: +PKCS8_add_keyusage 1302 EXIST::FUNCTION: +PKCS12_get_attr_gen 1303 EXIST::FUNCTION: +PKCS12_parse 1304 EXIST::FUNCTION: +PKCS12_create 1305 EXIST::FUNCTION: +i2d_PKCS12_bio 1306 EXIST::FUNCTION: +i2d_PKCS12_fp 1307 EXIST::FUNCTION: +d2i_PKCS12_bio 1308 EXIST::FUNCTION: +d2i_PKCS12_fp 1309 EXIST::FUNCTION: +i2d_PBEPARAM 1310 EXIST::FUNCTION: +PBEPARAM_new 1311 EXIST::FUNCTION: +d2i_PBEPARAM 1312 EXIST::FUNCTION: +PBEPARAM_free 1313 EXIST::FUNCTION: +i2d_PKCS8_PRIV_KEY_INFO 1314 EXIST::FUNCTION: +PKCS8_PRIV_KEY_INFO_new 1315 EXIST::FUNCTION: +d2i_PKCS8_PRIV_KEY_INFO 1316 EXIST::FUNCTION: +PKCS8_PRIV_KEY_INFO_free 1317 EXIST::FUNCTION: +EVP_PKCS82PKEY 1318 EXIST::FUNCTION: +EVP_PKEY2PKCS8 1319 EXIST::FUNCTION: +PKCS8_set_broken 1320 EXIST::FUNCTION: +EVP_PBE_ALGOR_CipherInit 1321 NOEXIST::FUNCTION: +EVP_PBE_alg_add 1322 EXIST::FUNCTION: +PKCS5_pbe_set 1323 EXIST::FUNCTION: +EVP_PBE_cleanup 1324 EXIST::FUNCTION: +i2d_SXNET 1325 EXIST::FUNCTION: +d2i_SXNET 1326 EXIST::FUNCTION: +SXNET_new 1327 EXIST::FUNCTION: +SXNET_free 1328 EXIST::FUNCTION: +i2d_SXNETID 1329 EXIST::FUNCTION: +d2i_SXNETID 1330 EXIST::FUNCTION: +SXNETID_new 1331 EXIST::FUNCTION: +SXNETID_free 1332 EXIST::FUNCTION: +DSA_SIG_new 1333 EXIST::FUNCTION:DSA +DSA_SIG_free 1334 EXIST::FUNCTION:DSA +DSA_do_sign 1335 EXIST::FUNCTION:DSA +DSA_do_verify 1336 EXIST::FUNCTION:DSA +d2i_DSA_SIG 1337 EXIST::FUNCTION:DSA +i2d_DSA_SIG 1338 EXIST::FUNCTION:DSA +i2d_ASN1_VISIBLESTRING 1339 EXIST::FUNCTION: +d2i_ASN1_VISIBLESTRING 1340 EXIST::FUNCTION: +i2d_ASN1_UTF8STRING 1341 EXIST::FUNCTION: +d2i_ASN1_UTF8STRING 1342 EXIST::FUNCTION: +i2d_DIRECTORYSTRING 1343 EXIST::FUNCTION: +d2i_DIRECTORYSTRING 1344 EXIST::FUNCTION: +i2d_DISPLAYTEXT 1345 EXIST::FUNCTION: +d2i_DISPLAYTEXT 1346 EXIST::FUNCTION: +d2i_ASN1_SET_OF_X509 1379 NOEXIST::FUNCTION: +i2d_ASN1_SET_OF_X509 1380 NOEXIST::FUNCTION: +i2d_PBKDF2PARAM 1397 EXIST::FUNCTION: +PBKDF2PARAM_new 1398 EXIST::FUNCTION: +d2i_PBKDF2PARAM 1399 EXIST::FUNCTION: +PBKDF2PARAM_free 1400 EXIST::FUNCTION: +i2d_PBE2PARAM 1401 EXIST::FUNCTION: +PBE2PARAM_new 1402 EXIST::FUNCTION: +d2i_PBE2PARAM 1403 EXIST::FUNCTION: +PBE2PARAM_free 1404 EXIST::FUNCTION: +d2i_ASN1_SET_OF_GENERAL_NAME 1421 NOEXIST::FUNCTION: +i2d_ASN1_SET_OF_GENERAL_NAME 1422 NOEXIST::FUNCTION: +d2i_ASN1_SET_OF_SXNETID 1439 NOEXIST::FUNCTION: +i2d_ASN1_SET_OF_SXNETID 1440 NOEXIST::FUNCTION: +d2i_ASN1_SET_OF_POLICYQUALINFO 1457 NOEXIST::FUNCTION: +i2d_ASN1_SET_OF_POLICYQUALINFO 1458 NOEXIST::FUNCTION: +d2i_ASN1_SET_OF_POLICYINFO 1475 NOEXIST::FUNCTION: +i2d_ASN1_SET_OF_POLICYINFO 1476 NOEXIST::FUNCTION: +SXNET_add_id_asc 1477 EXIST::FUNCTION: +SXNET_add_id_ulong 1478 EXIST::FUNCTION: +SXNET_add_id_INTEGER 1479 EXIST::FUNCTION: +SXNET_get_id_asc 1480 EXIST::FUNCTION: +SXNET_get_id_ulong 1481 EXIST::FUNCTION: +SXNET_get_id_INTEGER 1482 EXIST::FUNCTION: +X509V3_set_conf_lhash 1483 EXIST::FUNCTION: +i2d_CERTIFICATEPOLICIES 1484 EXIST::FUNCTION: +CERTIFICATEPOLICIES_new 1485 EXIST::FUNCTION: +CERTIFICATEPOLICIES_free 1486 EXIST::FUNCTION: +d2i_CERTIFICATEPOLICIES 1487 EXIST::FUNCTION: +i2d_POLICYINFO 1488 EXIST::FUNCTION: +POLICYINFO_new 1489 EXIST::FUNCTION: +d2i_POLICYINFO 1490 EXIST::FUNCTION: +POLICYINFO_free 1491 EXIST::FUNCTION: +i2d_POLICYQUALINFO 1492 EXIST::FUNCTION: +POLICYQUALINFO_new 1493 EXIST::FUNCTION: +d2i_POLICYQUALINFO 1494 EXIST::FUNCTION: +POLICYQUALINFO_free 1495 EXIST::FUNCTION: +i2d_USERNOTICE 1496 EXIST::FUNCTION: +USERNOTICE_new 1497 EXIST::FUNCTION: +d2i_USERNOTICE 1498 EXIST::FUNCTION: +USERNOTICE_free 1499 EXIST::FUNCTION: +i2d_NOTICEREF 1500 EXIST::FUNCTION: +NOTICEREF_new 1501 EXIST::FUNCTION: +d2i_NOTICEREF 1502 EXIST::FUNCTION: +NOTICEREF_free 1503 EXIST::FUNCTION: +X509V3_get_string 1504 EXIST::FUNCTION: +X509V3_get_section 1505 EXIST::FUNCTION: +X509V3_string_free 1506 EXIST::FUNCTION: +X509V3_section_free 1507 EXIST::FUNCTION: +X509V3_set_ctx 1508 EXIST::FUNCTION: +s2i_ASN1_INTEGER 1509 EXIST::FUNCTION: +CRYPTO_set_locked_mem_functions 1510 EXIST::FUNCTION: +CRYPTO_get_locked_mem_functions 1511 EXIST::FUNCTION: +CRYPTO_malloc_locked 1512 EXIST::FUNCTION: +CRYPTO_free_locked 1513 EXIST::FUNCTION: +BN_mod_exp2_mont 1514 EXIST::FUNCTION: +ERR_get_error_line_data 1515 EXIST::FUNCTION: +ERR_peek_error_line_data 1516 EXIST::FUNCTION: +PKCS12_PBE_keyivgen 1517 EXIST::FUNCTION: +X509_ALGOR_dup 1518 EXIST::FUNCTION: +d2i_ASN1_SET_OF_DIST_POINT 1535 NOEXIST::FUNCTION: +i2d_ASN1_SET_OF_DIST_POINT 1536 NOEXIST::FUNCTION: +i2d_CRL_DIST_POINTS 1537 EXIST::FUNCTION: +CRL_DIST_POINTS_new 1538 EXIST::FUNCTION: +CRL_DIST_POINTS_free 1539 EXIST::FUNCTION: +d2i_CRL_DIST_POINTS 1540 EXIST::FUNCTION: +i2d_DIST_POINT 1541 EXIST::FUNCTION: +DIST_POINT_new 1542 EXIST::FUNCTION: +d2i_DIST_POINT 1543 EXIST::FUNCTION: +DIST_POINT_free 1544 EXIST::FUNCTION: +i2d_DIST_POINT_NAME 1545 EXIST::FUNCTION: +DIST_POINT_NAME_new 1546 EXIST::FUNCTION: +DIST_POINT_NAME_free 1547 EXIST::FUNCTION: +d2i_DIST_POINT_NAME 1548 EXIST::FUNCTION: +X509V3_add_value_uchar 1549 EXIST::FUNCTION: +d2i_ASN1_SET_OF_X509_ATTRIBUTE 1555 NOEXIST::FUNCTION: +i2d_ASN1_SET_OF_ASN1_TYPE 1560 NOEXIST::FUNCTION: +d2i_ASN1_SET_OF_X509_EXTENSION 1567 NOEXIST::FUNCTION: +d2i_ASN1_SET_OF_X509_NAME_ENTRY 1574 NOEXIST::FUNCTION: +d2i_ASN1_SET_OF_ASN1_TYPE 1589 NOEXIST::FUNCTION: +i2d_ASN1_SET_OF_X509_ATTRIBUTE 1615 NOEXIST::FUNCTION: +i2d_ASN1_SET_OF_X509_EXTENSION 1624 NOEXIST::FUNCTION: +i2d_ASN1_SET_OF_X509_NAME_ENTRY 1633 NOEXIST::FUNCTION: +X509V3_EXT_i2d 1646 EXIST::FUNCTION: +X509V3_EXT_val_prn 1647 EXIST::FUNCTION: +X509V3_EXT_add_list 1648 EXIST::FUNCTION: +EVP_CIPHER_type 1649 EXIST::FUNCTION: +EVP_PBE_CipherInit 1650 EXIST::FUNCTION: +X509V3_add_value_bool_nf 1651 EXIST::FUNCTION: +d2i_ASN1_UINTEGER 1652 EXIST::FUNCTION: +sk_value 1653 EXIST::FUNCTION: +sk_num 1654 EXIST::FUNCTION: +sk_set 1655 EXIST::FUNCTION: +i2d_ASN1_SET_OF_X509_REVOKED 1661 NOEXIST::FUNCTION: +sk_sort 1671 EXIST::FUNCTION: +d2i_ASN1_SET_OF_X509_REVOKED 1674 NOEXIST::FUNCTION: +i2d_ASN1_SET_OF_X509_ALGOR 1682 NOEXIST::FUNCTION: +i2d_ASN1_SET_OF_X509_CRL 1685 NOEXIST::FUNCTION: +d2i_ASN1_SET_OF_X509_ALGOR 1696 NOEXIST::FUNCTION: +d2i_ASN1_SET_OF_X509_CRL 1702 NOEXIST::FUNCTION: +i2d_ASN1_SET_OF_PKCS7_SIGNER_INFO 1723 NOEXIST::FUNCTION: +i2d_ASN1_SET_OF_PKCS7_RECIP_INFO 1738 NOEXIST::FUNCTION: +d2i_ASN1_SET_OF_PKCS7_SIGNER_INFO 1748 NOEXIST::FUNCTION: +d2i_ASN1_SET_OF_PKCS7_RECIP_INFO 1753 NOEXIST::FUNCTION: +PKCS5_PBE_add 1775 EXIST::FUNCTION: +PEM_write_bio_PKCS8 1776 EXIST::FUNCTION: +i2d_PKCS8_fp 1777 EXIST::FUNCTION:FP_API +PEM_read_bio_PKCS8_PRIV_KEY_INFO 1778 EXIST:!VMS:FUNCTION: +PEM_read_bio_P8_PRIV_KEY_INFO 1778 EXIST:VMS:FUNCTION: +d2i_PKCS8_bio 1779 EXIST::FUNCTION:BIO +d2i_PKCS8_PRIV_KEY_INFO_fp 1780 EXIST::FUNCTION:FP_API +PEM_write_bio_PKCS8_PRIV_KEY_INFO 1781 EXIST:!VMS:FUNCTION: +PEM_write_bio_P8_PRIV_KEY_INFO 1781 EXIST:VMS:FUNCTION: +PEM_read_PKCS8 1782 EXIST:!WIN16:FUNCTION: +d2i_PKCS8_PRIV_KEY_INFO_bio 1783 EXIST::FUNCTION:BIO +d2i_PKCS8_fp 1784 EXIST::FUNCTION:FP_API +PEM_write_PKCS8 1785 EXIST:!WIN16:FUNCTION: +PEM_read_PKCS8_PRIV_KEY_INFO 1786 EXIST:!VMS,!WIN16:FUNCTION: +PEM_read_P8_PRIV_KEY_INFO 1786 EXIST:VMS:FUNCTION: +PEM_read_bio_PKCS8 1787 EXIST::FUNCTION: +PEM_write_PKCS8_PRIV_KEY_INFO 1788 EXIST:!VMS,!WIN16:FUNCTION: +PEM_write_P8_PRIV_KEY_INFO 1788 EXIST:VMS:FUNCTION: +PKCS5_PBE_keyivgen 1789 EXIST::FUNCTION: +i2d_PKCS8_bio 1790 EXIST::FUNCTION:BIO +i2d_PKCS8_PRIV_KEY_INFO_fp 1791 EXIST::FUNCTION:FP_API +i2d_PKCS8_PRIV_KEY_INFO_bio 1792 EXIST::FUNCTION:BIO +BIO_s_bio 1793 EXIST::FUNCTION: +PKCS5_pbe2_set 1794 EXIST::FUNCTION: +PKCS5_PBKDF2_HMAC_SHA1 1795 EXIST::FUNCTION: +PKCS5_v2_PBE_keyivgen 1796 EXIST::FUNCTION: +PEM_write_bio_PKCS8PrivateKey 1797 EXIST::FUNCTION: +PEM_write_PKCS8PrivateKey 1798 EXIST::FUNCTION: +BIO_ctrl_get_read_request 1799 EXIST::FUNCTION: +BIO_ctrl_pending 1800 EXIST::FUNCTION: +BIO_ctrl_wpending 1801 EXIST::FUNCTION: +BIO_new_bio_pair 1802 EXIST::FUNCTION: +BIO_ctrl_get_write_guarantee 1803 EXIST::FUNCTION: +CRYPTO_num_locks 1804 EXIST::FUNCTION: +CONF_load_bio 1805 EXIST::FUNCTION: +CONF_load_fp 1806 EXIST::FUNCTION:FP_API +i2d_ASN1_SET_OF_ASN1_OBJECT 1837 NOEXIST::FUNCTION: +d2i_ASN1_SET_OF_ASN1_OBJECT 1844 NOEXIST::FUNCTION: +PKCS7_signatureVerify 1845 EXIST::FUNCTION: +RSA_set_method 1846 EXIST::FUNCTION:RSA +RSA_get_method 1847 EXIST::FUNCTION:RSA +RSA_get_default_method 1848 EXIST::FUNCTION:RSA +RSA_check_key 1869 EXIST::FUNCTION:RSA +OBJ_obj2txt 1870 EXIST::FUNCTION: +DSA_dup_DH 1871 EXIST::FUNCTION:DH,DSA +X509_REQ_get_extensions 1872 EXIST::FUNCTION: +X509_REQ_set_extension_nids 1873 EXIST::FUNCTION: +BIO_nwrite 1874 EXIST::FUNCTION: +X509_REQ_extension_nid 1875 EXIST::FUNCTION: +BIO_nread 1876 EXIST::FUNCTION: +X509_REQ_get_extension_nids 1877 EXIST::FUNCTION: +BIO_nwrite0 1878 EXIST::FUNCTION: +X509_REQ_add_extensions_nid 1879 EXIST::FUNCTION: +BIO_nread0 1880 EXIST::FUNCTION: +X509_REQ_add_extensions 1881 EXIST::FUNCTION: +BIO_new_mem_buf 1882 EXIST::FUNCTION: +DH_set_ex_data 1883 EXIST::FUNCTION:DH +DH_set_method 1884 EXIST::FUNCTION:DH +DSA_OpenSSL 1885 EXIST::FUNCTION:DSA +DH_get_ex_data 1886 EXIST::FUNCTION:DH +DH_get_ex_new_index 1887 EXIST::FUNCTION:DH +DSA_new_method 1888 EXIST::FUNCTION:DSA +DH_new_method 1889 EXIST::FUNCTION:DH +DH_OpenSSL 1890 EXIST::FUNCTION:DH +DSA_get_ex_new_index 1891 EXIST::FUNCTION:DSA +DH_get_default_method 1892 EXIST::FUNCTION:DH +DSA_set_ex_data 1893 EXIST::FUNCTION:DSA +DH_set_default_method 1894 EXIST::FUNCTION:DH +DSA_get_ex_data 1895 EXIST::FUNCTION:DSA +X509V3_EXT_REQ_add_conf 1896 EXIST::FUNCTION: +NETSCAPE_SPKI_print 1897 EXIST::FUNCTION:EVP +NETSCAPE_SPKI_set_pubkey 1898 EXIST::FUNCTION:EVP +NETSCAPE_SPKI_b64_encode 1899 EXIST::FUNCTION:EVP +NETSCAPE_SPKI_get_pubkey 1900 EXIST::FUNCTION:EVP +NETSCAPE_SPKI_b64_decode 1901 EXIST::FUNCTION:EVP +UTF8_putc 1902 EXIST::FUNCTION: +UTF8_getc 1903 EXIST::FUNCTION: +RSA_null_method 1904 EXIST::FUNCTION:RSA +ASN1_tag2str 1905 EXIST::FUNCTION: +BIO_ctrl_reset_read_request 1906 EXIST::FUNCTION: +DISPLAYTEXT_new 1907 EXIST::FUNCTION: +ASN1_GENERALIZEDTIME_free 1908 EXIST::FUNCTION: +X509_REVOKED_get_ext_d2i 1909 EXIST::FUNCTION: +X509_set_ex_data 1910 EXIST::FUNCTION: +X509_reject_set_bit_asc 1911 NOEXIST::FUNCTION: +X509_NAME_add_entry_by_txt 1912 EXIST::FUNCTION: +X509_NAME_add_entry_by_NID 1914 EXIST::FUNCTION: +X509_PURPOSE_get0 1915 EXIST::FUNCTION: +PEM_read_X509_AUX 1917 EXIST:!WIN16:FUNCTION: +d2i_AUTHORITY_INFO_ACCESS 1918 EXIST::FUNCTION: +PEM_write_PUBKEY 1921 EXIST:!WIN16:FUNCTION: +ACCESS_DESCRIPTION_new 1925 EXIST::FUNCTION: +X509_CERT_AUX_free 1926 EXIST::FUNCTION: +d2i_ACCESS_DESCRIPTION 1927 EXIST::FUNCTION: +X509_trust_clear 1928 EXIST::FUNCTION: +X509_TRUST_add 1931 EXIST::FUNCTION: +ASN1_VISIBLESTRING_new 1932 EXIST::FUNCTION: +X509_alias_set1 1933 EXIST::FUNCTION: +ASN1_PRINTABLESTRING_free 1934 EXIST::FUNCTION: +EVP_PKEY_get1_DSA 1935 EXIST::FUNCTION:DSA +ASN1_BMPSTRING_new 1936 EXIST::FUNCTION: +ASN1_mbstring_copy 1937 EXIST::FUNCTION: +ASN1_UTF8STRING_new 1938 EXIST::FUNCTION: +DSA_get_default_method 1941 EXIST::FUNCTION:DSA +i2d_ASN1_SET_OF_ACCESS_DESCRIPTION 1945 NOEXIST::FUNCTION: +ASN1_T61STRING_free 1946 EXIST::FUNCTION: +DSA_set_method 1949 EXIST::FUNCTION:DSA +X509_get_ex_data 1950 EXIST::FUNCTION: +ASN1_STRING_type 1951 EXIST::FUNCTION: +X509_PURPOSE_get_by_sname 1952 EXIST::FUNCTION: +ASN1_TIME_free 1954 EXIST::FUNCTION: +ASN1_OCTET_STRING_cmp 1955 EXIST::FUNCTION: +ASN1_BIT_STRING_new 1957 EXIST::FUNCTION: +X509_get_ext_d2i 1958 EXIST::FUNCTION: +PEM_read_bio_X509_AUX 1959 EXIST::FUNCTION: +ASN1_STRING_set_default_mask_asc 1960 EXIST:!VMS:FUNCTION: +ASN1_STRING_set_def_mask_asc 1960 EXIST:VMS:FUNCTION: +PEM_write_bio_RSA_PUBKEY 1961 EXIST::FUNCTION:RSA +ASN1_INTEGER_cmp 1963 EXIST::FUNCTION: +d2i_RSA_PUBKEY_fp 1964 EXIST::FUNCTION:FP_API,RSA +X509_trust_set_bit_asc 1967 NOEXIST::FUNCTION: +PEM_write_bio_DSA_PUBKEY 1968 EXIST::FUNCTION:DSA +X509_STORE_CTX_free 1969 EXIST::FUNCTION: +EVP_PKEY_set1_DSA 1970 EXIST::FUNCTION:DSA +i2d_DSA_PUBKEY_fp 1971 EXIST::FUNCTION:DSA,FP_API +X509_load_cert_crl_file 1972 EXIST::FUNCTION:STDIO +ASN1_TIME_new 1973 EXIST::FUNCTION: +i2d_RSA_PUBKEY 1974 EXIST::FUNCTION:RSA +X509_STORE_CTX_purpose_inherit 1976 EXIST::FUNCTION: +PEM_read_RSA_PUBKEY 1977 EXIST:!WIN16:FUNCTION:RSA +d2i_X509_AUX 1980 EXIST::FUNCTION: +i2d_DSA_PUBKEY 1981 EXIST::FUNCTION:DSA +X509_CERT_AUX_print 1982 EXIST::FUNCTION:BIO +PEM_read_DSA_PUBKEY 1984 EXIST:!WIN16:FUNCTION:DSA +i2d_RSA_PUBKEY_bio 1985 EXIST::FUNCTION:BIO,RSA +ASN1_BIT_STRING_num_asc 1986 EXIST::FUNCTION: +i2d_PUBKEY 1987 EXIST::FUNCTION: +ASN1_UTCTIME_free 1988 EXIST::FUNCTION: +DSA_set_default_method 1989 EXIST::FUNCTION:DSA +X509_PURPOSE_get_by_id 1990 EXIST::FUNCTION: +ACCESS_DESCRIPTION_free 1994 EXIST::FUNCTION: +PEM_read_bio_PUBKEY 1995 EXIST::FUNCTION: +ASN1_STRING_set_by_NID 1996 EXIST::FUNCTION: +X509_PURPOSE_get_id 1997 EXIST::FUNCTION: +DISPLAYTEXT_free 1998 EXIST::FUNCTION: +OTHERNAME_new 1999 EXIST::FUNCTION: +X509_CERT_AUX_new 2001 EXIST::FUNCTION: +X509_TRUST_cleanup 2007 EXIST::FUNCTION: +X509_NAME_add_entry_by_OBJ 2008 EXIST::FUNCTION: +X509_CRL_get_ext_d2i 2009 EXIST::FUNCTION: +X509_PURPOSE_get0_name 2011 EXIST::FUNCTION: +PEM_read_PUBKEY 2012 EXIST:!WIN16:FUNCTION: +i2d_DSA_PUBKEY_bio 2014 EXIST::FUNCTION:BIO,DSA +i2d_OTHERNAME 2015 EXIST::FUNCTION: +ASN1_OCTET_STRING_free 2016 EXIST::FUNCTION: +ASN1_BIT_STRING_set_asc 2017 EXIST::FUNCTION: +X509_get_ex_new_index 2019 EXIST::FUNCTION: +ASN1_STRING_TABLE_cleanup 2020 EXIST::FUNCTION: +X509_TRUST_get_by_id 2021 EXIST::FUNCTION: +X509_PURPOSE_get_trust 2022 EXIST::FUNCTION: +ASN1_STRING_length 2023 EXIST::FUNCTION: +d2i_ASN1_SET_OF_ACCESS_DESCRIPTION 2024 NOEXIST::FUNCTION: +ASN1_PRINTABLESTRING_new 2025 EXIST::FUNCTION: +X509V3_get_d2i 2026 EXIST::FUNCTION: +ASN1_ENUMERATED_free 2027 EXIST::FUNCTION: +i2d_X509_CERT_AUX 2028 EXIST::FUNCTION: +X509_STORE_CTX_set_trust 2030 EXIST::FUNCTION: +ASN1_STRING_set_default_mask 2032 EXIST::FUNCTION: +X509_STORE_CTX_new 2033 EXIST::FUNCTION: +EVP_PKEY_get1_RSA 2034 EXIST::FUNCTION:RSA +DIRECTORYSTRING_free 2038 EXIST::FUNCTION: +PEM_write_X509_AUX 2039 EXIST:!WIN16:FUNCTION: +ASN1_OCTET_STRING_set 2040 EXIST::FUNCTION: +d2i_DSA_PUBKEY_fp 2041 EXIST::FUNCTION:DSA,FP_API +d2i_RSA_PUBKEY 2044 EXIST::FUNCTION:RSA +X509_TRUST_get0_name 2046 EXIST::FUNCTION: +X509_TRUST_get0 2047 EXIST::FUNCTION: +AUTHORITY_INFO_ACCESS_free 2048 EXIST::FUNCTION: +ASN1_IA5STRING_new 2049 EXIST::FUNCTION: +d2i_DSA_PUBKEY 2050 EXIST::FUNCTION:DSA +X509_check_purpose 2051 EXIST::FUNCTION: +ASN1_ENUMERATED_new 2052 EXIST::FUNCTION: +d2i_RSA_PUBKEY_bio 2053 EXIST::FUNCTION:BIO,RSA +d2i_PUBKEY 2054 EXIST::FUNCTION: +X509_TRUST_get_trust 2055 EXIST::FUNCTION: +X509_TRUST_get_flags 2056 EXIST::FUNCTION: +ASN1_BMPSTRING_free 2057 EXIST::FUNCTION: +ASN1_T61STRING_new 2058 EXIST::FUNCTION: +ASN1_UTCTIME_new 2060 EXIST::FUNCTION: +i2d_AUTHORITY_INFO_ACCESS 2062 EXIST::FUNCTION: +EVP_PKEY_set1_RSA 2063 EXIST::FUNCTION:RSA +X509_STORE_CTX_set_purpose 2064 EXIST::FUNCTION: +ASN1_IA5STRING_free 2065 EXIST::FUNCTION: +PEM_write_bio_X509_AUX 2066 EXIST::FUNCTION: +X509_PURPOSE_get_count 2067 EXIST::FUNCTION: +CRYPTO_add_info 2068 NOEXIST::FUNCTION: +X509_NAME_ENTRY_create_by_txt 2071 EXIST::FUNCTION: +ASN1_STRING_get_default_mask 2072 EXIST::FUNCTION: +X509_alias_get0 2074 EXIST::FUNCTION: +ASN1_STRING_data 2075 EXIST::FUNCTION: +i2d_ACCESS_DESCRIPTION 2077 EXIST::FUNCTION: +X509_trust_set_bit 2078 NOEXIST::FUNCTION: +ASN1_BIT_STRING_free 2080 EXIST::FUNCTION: +PEM_read_bio_RSA_PUBKEY 2081 EXIST::FUNCTION:RSA +X509_add1_reject_object 2082 EXIST::FUNCTION: +X509_check_trust 2083 EXIST::FUNCTION: +PEM_read_bio_DSA_PUBKEY 2088 EXIST::FUNCTION:DSA +X509_PURPOSE_add 2090 EXIST::FUNCTION: +ASN1_STRING_TABLE_get 2091 EXIST::FUNCTION: +ASN1_UTF8STRING_free 2092 EXIST::FUNCTION: +d2i_DSA_PUBKEY_bio 2093 EXIST::FUNCTION:BIO,DSA +PEM_write_RSA_PUBKEY 2095 EXIST:!WIN16:FUNCTION:RSA +d2i_OTHERNAME 2096 EXIST::FUNCTION: +X509_reject_set_bit 2098 NOEXIST::FUNCTION: +PEM_write_DSA_PUBKEY 2101 EXIST:!WIN16:FUNCTION:DSA +X509_PURPOSE_get0_sname 2105 EXIST::FUNCTION: +EVP_PKEY_set1_DH 2107 EXIST::FUNCTION:DH +ASN1_OCTET_STRING_dup 2108 EXIST::FUNCTION: +ASN1_BIT_STRING_set 2109 EXIST::FUNCTION: +X509_TRUST_get_count 2110 EXIST::FUNCTION: +ASN1_INTEGER_free 2111 EXIST::FUNCTION: +OTHERNAME_free 2112 EXIST::FUNCTION: +i2d_RSA_PUBKEY_fp 2113 EXIST::FUNCTION:FP_API,RSA +ASN1_INTEGER_dup 2114 EXIST::FUNCTION: +d2i_X509_CERT_AUX 2115 EXIST::FUNCTION: +PEM_write_bio_PUBKEY 2117 EXIST::FUNCTION: +ASN1_VISIBLESTRING_free 2118 EXIST::FUNCTION: +X509_PURPOSE_cleanup 2119 EXIST::FUNCTION: +ASN1_mbstring_ncopy 2123 EXIST::FUNCTION: +ASN1_GENERALIZEDTIME_new 2126 EXIST::FUNCTION: +EVP_PKEY_get1_DH 2128 EXIST::FUNCTION:DH +ASN1_OCTET_STRING_new 2130 EXIST::FUNCTION: +ASN1_INTEGER_new 2131 EXIST::FUNCTION: +i2d_X509_AUX 2132 EXIST::FUNCTION: +ASN1_BIT_STRING_name_print 2134 EXIST::FUNCTION:BIO +X509_cmp 2135 EXIST::FUNCTION: +ASN1_STRING_length_set 2136 EXIST::FUNCTION: +DIRECTORYSTRING_new 2137 EXIST::FUNCTION: +X509_add1_trust_object 2140 EXIST::FUNCTION: +PKCS12_newpass 2141 EXIST::FUNCTION: +SMIME_write_PKCS7 2142 EXIST::FUNCTION: +SMIME_read_PKCS7 2143 EXIST::FUNCTION: +DES_set_key_checked 2144 EXIST::FUNCTION:DES +PKCS7_verify 2145 EXIST::FUNCTION: +PKCS7_encrypt 2146 EXIST::FUNCTION: +DES_set_key_unchecked 2147 EXIST::FUNCTION:DES +SMIME_crlf_copy 2148 EXIST::FUNCTION: +i2d_ASN1_PRINTABLESTRING 2149 EXIST::FUNCTION: +PKCS7_get0_signers 2150 EXIST::FUNCTION: +PKCS7_decrypt 2151 EXIST::FUNCTION: +SMIME_text 2152 EXIST::FUNCTION: +PKCS7_simple_smimecap 2153 EXIST::FUNCTION: +PKCS7_get_smimecap 2154 EXIST::FUNCTION: +PKCS7_sign 2155 EXIST::FUNCTION: +PKCS7_add_attrib_smimecap 2156 EXIST::FUNCTION: +CRYPTO_dbg_set_options 2157 EXIST::FUNCTION: +CRYPTO_remove_all_info 2158 EXIST::FUNCTION: +CRYPTO_get_mem_debug_functions 2159 EXIST::FUNCTION: +CRYPTO_is_mem_check_on 2160 EXIST::FUNCTION: +CRYPTO_set_mem_debug_functions 2161 EXIST::FUNCTION: +CRYPTO_pop_info 2162 EXIST::FUNCTION: +CRYPTO_push_info_ 2163 EXIST::FUNCTION: +CRYPTO_set_mem_debug_options 2164 EXIST::FUNCTION: +PEM_write_PKCS8PrivateKey_nid 2165 EXIST::FUNCTION: +PEM_write_bio_PKCS8PrivateKey_nid 2166 EXIST:!VMS:FUNCTION: +PEM_write_bio_PKCS8PrivKey_nid 2166 EXIST:VMS:FUNCTION: +d2i_PKCS8PrivateKey_bio 2167 EXIST::FUNCTION: +ASN1_NULL_free 2168 EXIST::FUNCTION: +d2i_ASN1_NULL 2169 EXIST::FUNCTION: +ASN1_NULL_new 2170 EXIST::FUNCTION: +i2d_PKCS8PrivateKey_bio 2171 EXIST::FUNCTION: +i2d_PKCS8PrivateKey_fp 2172 EXIST::FUNCTION: +i2d_ASN1_NULL 2173 EXIST::FUNCTION: +i2d_PKCS8PrivateKey_nid_fp 2174 EXIST::FUNCTION: +d2i_PKCS8PrivateKey_fp 2175 EXIST::FUNCTION: +i2d_PKCS8PrivateKey_nid_bio 2176 EXIST::FUNCTION: +i2d_PKCS8PrivateKeyInfo_fp 2177 EXIST::FUNCTION:FP_API +i2d_PKCS8PrivateKeyInfo_bio 2178 EXIST::FUNCTION:BIO +PEM_cb 2179 NOEXIST::FUNCTION: +i2d_PrivateKey_fp 2180 EXIST::FUNCTION:FP_API +d2i_PrivateKey_bio 2181 EXIST::FUNCTION:BIO +d2i_PrivateKey_fp 2182 EXIST::FUNCTION:FP_API +i2d_PrivateKey_bio 2183 EXIST::FUNCTION:BIO +X509_reject_clear 2184 EXIST::FUNCTION: +X509_TRUST_set_default 2185 EXIST::FUNCTION: +d2i_AutoPrivateKey 2186 EXIST::FUNCTION: +X509_ATTRIBUTE_get0_type 2187 EXIST::FUNCTION: +X509_ATTRIBUTE_set1_data 2188 EXIST::FUNCTION: +X509at_get_attr 2189 EXIST::FUNCTION: +X509at_get_attr_count 2190 EXIST::FUNCTION: +X509_ATTRIBUTE_create_by_NID 2191 EXIST::FUNCTION: +X509_ATTRIBUTE_set1_object 2192 EXIST::FUNCTION: +X509_ATTRIBUTE_count 2193 EXIST::FUNCTION: +X509_ATTRIBUTE_create_by_OBJ 2194 EXIST::FUNCTION: +X509_ATTRIBUTE_get0_object 2195 EXIST::FUNCTION: +X509at_get_attr_by_NID 2196 EXIST::FUNCTION: +X509at_add1_attr 2197 EXIST::FUNCTION: +X509_ATTRIBUTE_get0_data 2198 EXIST::FUNCTION: +X509at_delete_attr 2199 EXIST::FUNCTION: +X509at_get_attr_by_OBJ 2200 EXIST::FUNCTION: +RAND_add 2201 EXIST::FUNCTION: +BIO_number_written 2202 EXIST::FUNCTION: +BIO_number_read 2203 EXIST::FUNCTION: +X509_STORE_CTX_get1_chain 2204 EXIST::FUNCTION: +ERR_load_RAND_strings 2205 EXIST::FUNCTION: +RAND_pseudo_bytes 2206 EXIST::FUNCTION: +X509_REQ_get_attr_by_NID 2207 EXIST::FUNCTION: +X509_REQ_get_attr 2208 EXIST::FUNCTION: +X509_REQ_add1_attr_by_NID 2209 EXIST::FUNCTION: +X509_REQ_get_attr_by_OBJ 2210 EXIST::FUNCTION: +X509at_add1_attr_by_NID 2211 EXIST::FUNCTION: +X509_REQ_add1_attr_by_OBJ 2212 EXIST::FUNCTION: +X509_REQ_get_attr_count 2213 EXIST::FUNCTION: +X509_REQ_add1_attr 2214 EXIST::FUNCTION: +X509_REQ_delete_attr 2215 EXIST::FUNCTION: +X509at_add1_attr_by_OBJ 2216 EXIST::FUNCTION: +X509_REQ_add1_attr_by_txt 2217 EXIST::FUNCTION: +X509_ATTRIBUTE_create_by_txt 2218 EXIST::FUNCTION: +X509at_add1_attr_by_txt 2219 EXIST::FUNCTION: +BN_pseudo_rand 2239 EXIST::FUNCTION: +BN_is_prime_fasttest 2240 EXIST::FUNCTION:DEPRECATED +BN_CTX_end 2241 EXIST::FUNCTION: +BN_CTX_start 2242 EXIST::FUNCTION: +BN_CTX_get 2243 EXIST::FUNCTION: +EVP_PKEY2PKCS8_broken 2244 EXIST::FUNCTION: +ASN1_STRING_TABLE_add 2245 EXIST::FUNCTION: +CRYPTO_dbg_get_options 2246 EXIST::FUNCTION: +AUTHORITY_INFO_ACCESS_new 2247 EXIST::FUNCTION: +CRYPTO_get_mem_debug_options 2248 EXIST::FUNCTION: +DES_crypt 2249 EXIST::FUNCTION:DES +PEM_write_bio_X509_REQ_NEW 2250 EXIST::FUNCTION: +PEM_write_X509_REQ_NEW 2251 EXIST:!WIN16:FUNCTION: +BIO_callback_ctrl 2252 EXIST::FUNCTION: +RAND_egd 2253 EXIST::FUNCTION: +RAND_status 2254 EXIST::FUNCTION: +bn_dump1 2255 NOEXIST::FUNCTION: +DES_check_key_parity 2256 EXIST::FUNCTION:DES +lh_num_items 2257 EXIST::FUNCTION: +RAND_event 2258 EXIST:WIN32:FUNCTION: +DSO_new 2259 EXIST::FUNCTION: +DSO_new_method 2260 EXIST::FUNCTION: +DSO_free 2261 EXIST::FUNCTION: +DSO_flags 2262 EXIST::FUNCTION: +DSO_up 2263 NOEXIST::FUNCTION: +DSO_set_default_method 2264 EXIST::FUNCTION: +DSO_get_default_method 2265 EXIST::FUNCTION: +DSO_get_method 2266 EXIST::FUNCTION: +DSO_set_method 2267 EXIST::FUNCTION: +DSO_load 2268 EXIST::FUNCTION: +DSO_bind_var 2269 EXIST::FUNCTION: +DSO_METHOD_null 2270 EXIST::FUNCTION: +DSO_METHOD_openssl 2271 EXIST::FUNCTION: +DSO_METHOD_dlfcn 2272 EXIST::FUNCTION: +DSO_METHOD_win32 2273 EXIST::FUNCTION: +ERR_load_DSO_strings 2274 EXIST::FUNCTION: +DSO_METHOD_dl 2275 EXIST::FUNCTION: +NCONF_load 2276 EXIST::FUNCTION: +NCONF_load_fp 2278 EXIST::FUNCTION:FP_API +NCONF_new 2279 EXIST::FUNCTION: +NCONF_get_string 2280 EXIST::FUNCTION: +NCONF_free 2281 EXIST::FUNCTION: +NCONF_get_number 2282 NOEXIST::FUNCTION: +CONF_dump_fp 2283 EXIST::FUNCTION: +NCONF_load_bio 2284 EXIST::FUNCTION: +NCONF_dump_fp 2285 EXIST::FUNCTION: +NCONF_get_section 2286 EXIST::FUNCTION: +NCONF_dump_bio 2287 EXIST::FUNCTION: +CONF_dump_bio 2288 EXIST::FUNCTION: +NCONF_free_data 2289 EXIST::FUNCTION: +CONF_set_default_method 2290 EXIST::FUNCTION: +ERR_error_string_n 2291 EXIST::FUNCTION: +BIO_snprintf 2292 EXIST::FUNCTION: +DSO_ctrl 2293 EXIST::FUNCTION: +i2d_ASN1_SET_OF_ASN1_INTEGER 2317 NOEXIST::FUNCTION: +i2d_ASN1_SET_OF_PKCS12_SAFEBAG 2320 NOEXIST::FUNCTION: +i2d_ASN1_SET_OF_PKCS7 2328 NOEXIST::FUNCTION: +BIO_vfree 2334 EXIST::FUNCTION: +d2i_ASN1_SET_OF_ASN1_INTEGER 2339 NOEXIST::FUNCTION: +d2i_ASN1_SET_OF_PKCS12_SAFEBAG 2341 NOEXIST::FUNCTION: +ASN1_UTCTIME_get 2350 NOEXIST::FUNCTION: +X509_REQ_digest 2362 EXIST::FUNCTION:EVP +X509_CRL_digest 2391 EXIST::FUNCTION:EVP +d2i_ASN1_SET_OF_PKCS7 2397 NOEXIST::FUNCTION: +EVP_CIPHER_CTX_set_key_length 2399 EXIST::FUNCTION: +EVP_CIPHER_CTX_ctrl 2400 EXIST::FUNCTION: +BN_mod_exp_mont_word 2401 EXIST::FUNCTION: +RAND_egd_bytes 2402 EXIST::FUNCTION: +X509_REQ_get1_email 2403 EXIST::FUNCTION: +X509_get1_email 2404 EXIST::FUNCTION: +X509_email_free 2405 EXIST::FUNCTION: +i2d_RSA_NET 2406 EXIST::FUNCTION:RC4,RSA +d2i_RSA_NET_2 2407 NOEXIST::FUNCTION: +d2i_RSA_NET 2408 EXIST::FUNCTION:RC4,RSA +DSO_bind_func 2409 EXIST::FUNCTION: +CRYPTO_get_new_dynlockid 2410 EXIST::FUNCTION: +sk_new_null 2411 EXIST::FUNCTION: +CRYPTO_set_dynlock_destroy_callback 2412 EXIST:!VMS:FUNCTION: +CRYPTO_set_dynlock_destroy_cb 2412 EXIST:VMS:FUNCTION: +CRYPTO_destroy_dynlockid 2413 EXIST::FUNCTION: +CRYPTO_set_dynlock_size 2414 NOEXIST::FUNCTION: +CRYPTO_set_dynlock_create_callback 2415 EXIST:!VMS:FUNCTION: +CRYPTO_set_dynlock_create_cb 2415 EXIST:VMS:FUNCTION: +CRYPTO_set_dynlock_lock_callback 2416 EXIST:!VMS:FUNCTION: +CRYPTO_set_dynlock_lock_cb 2416 EXIST:VMS:FUNCTION: +CRYPTO_get_dynlock_lock_callback 2417 EXIST:!VMS:FUNCTION: +CRYPTO_get_dynlock_lock_cb 2417 EXIST:VMS:FUNCTION: +CRYPTO_get_dynlock_destroy_callback 2418 EXIST:!VMS:FUNCTION: +CRYPTO_get_dynlock_destroy_cb 2418 EXIST:VMS:FUNCTION: +CRYPTO_get_dynlock_value 2419 EXIST::FUNCTION: +CRYPTO_get_dynlock_create_callback 2420 EXIST:!VMS:FUNCTION: +CRYPTO_get_dynlock_create_cb 2420 EXIST:VMS:FUNCTION: +c2i_ASN1_BIT_STRING 2421 EXIST::FUNCTION: +i2c_ASN1_BIT_STRING 2422 EXIST::FUNCTION: +RAND_poll 2423 EXIST::FUNCTION: +c2i_ASN1_INTEGER 2424 EXIST::FUNCTION: +i2c_ASN1_INTEGER 2425 EXIST::FUNCTION: +BIO_dump_indent 2426 EXIST::FUNCTION: +ASN1_parse_dump 2427 EXIST::FUNCTION:BIO +c2i_ASN1_OBJECT 2428 EXIST::FUNCTION: +X509_NAME_print_ex_fp 2429 EXIST::FUNCTION:FP_API +ASN1_STRING_print_ex_fp 2430 EXIST::FUNCTION:FP_API +X509_NAME_print_ex 2431 EXIST::FUNCTION:BIO +ASN1_STRING_print_ex 2432 EXIST::FUNCTION:BIO +MD4 2433 EXIST::FUNCTION:MD4 +MD4_Transform 2434 EXIST::FUNCTION:MD4 +MD4_Final 2435 EXIST::FUNCTION:MD4 +MD4_Update 2436 EXIST::FUNCTION:MD4 +MD4_Init 2437 EXIST::FUNCTION:MD4 +EVP_md4 2438 EXIST::FUNCTION:MD4 +i2d_PUBKEY_bio 2439 EXIST::FUNCTION:BIO +i2d_PUBKEY_fp 2440 EXIST::FUNCTION:FP_API +d2i_PUBKEY_bio 2441 EXIST::FUNCTION:BIO +ASN1_STRING_to_UTF8 2442 EXIST::FUNCTION: +BIO_vprintf 2443 EXIST::FUNCTION: +BIO_vsnprintf 2444 EXIST::FUNCTION: +d2i_PUBKEY_fp 2445 EXIST::FUNCTION:FP_API +X509_cmp_time 2446 EXIST::FUNCTION: +X509_STORE_CTX_set_time 2447 EXIST::FUNCTION: +X509_STORE_CTX_get1_issuer 2448 EXIST::FUNCTION: +X509_OBJECT_retrieve_match 2449 EXIST::FUNCTION: +X509_OBJECT_idx_by_subject 2450 EXIST::FUNCTION: +X509_STORE_CTX_set_flags 2451 EXIST::FUNCTION: +X509_STORE_CTX_trusted_stack 2452 EXIST::FUNCTION: +X509_time_adj 2453 EXIST::FUNCTION: +X509_check_issued 2454 EXIST::FUNCTION: +ASN1_UTCTIME_cmp_time_t 2455 EXIST::FUNCTION: +DES_set_weak_key_flag 2456 NOEXIST::FUNCTION: +DES_check_key 2457 NOEXIST::FUNCTION: +DES_rw_mode 2458 NOEXIST::FUNCTION: +RSA_PKCS1_RSAref 2459 NOEXIST::FUNCTION: +X509_keyid_set1 2460 EXIST::FUNCTION: +BIO_next 2461 EXIST::FUNCTION: +DSO_METHOD_vms 2462 EXIST::FUNCTION: +BIO_f_linebuffer 2463 EXIST:VMS:FUNCTION: +BN_bntest_rand 2464 EXIST::FUNCTION: +OPENSSL_issetugid 2465 EXIST::FUNCTION: +BN_rand_range 2466 EXIST::FUNCTION: +ERR_load_ENGINE_strings 2467 EXIST::FUNCTION:ENGINE +ENGINE_set_DSA 2468 EXIST::FUNCTION:ENGINE +ENGINE_get_finish_function 2469 EXIST::FUNCTION:ENGINE +ENGINE_get_default_RSA 2470 EXIST::FUNCTION:ENGINE +ENGINE_get_BN_mod_exp 2471 NOEXIST::FUNCTION: +DSA_get_default_openssl_method 2472 NOEXIST::FUNCTION: +ENGINE_set_DH 2473 EXIST::FUNCTION:ENGINE +ENGINE_set_def_BN_mod_exp_crt 2474 NOEXIST::FUNCTION: +ENGINE_set_default_BN_mod_exp_crt 2474 NOEXIST::FUNCTION: +ENGINE_init 2475 EXIST::FUNCTION:ENGINE +DH_get_default_openssl_method 2476 NOEXIST::FUNCTION: +RSA_set_default_openssl_method 2477 NOEXIST::FUNCTION: +ENGINE_finish 2478 EXIST::FUNCTION:ENGINE +ENGINE_load_public_key 2479 EXIST::FUNCTION:ENGINE +ENGINE_get_DH 2480 EXIST::FUNCTION:ENGINE +ENGINE_ctrl 2481 EXIST::FUNCTION:ENGINE +ENGINE_get_init_function 2482 EXIST::FUNCTION:ENGINE +ENGINE_set_init_function 2483 EXIST::FUNCTION:ENGINE +ENGINE_set_default_DSA 2484 EXIST::FUNCTION:ENGINE +ENGINE_get_name 2485 EXIST::FUNCTION:ENGINE +ENGINE_get_last 2486 EXIST::FUNCTION:ENGINE +ENGINE_get_prev 2487 EXIST::FUNCTION:ENGINE +ENGINE_get_default_DH 2488 EXIST::FUNCTION:ENGINE +ENGINE_get_RSA 2489 EXIST::FUNCTION:ENGINE +ENGINE_set_default 2490 EXIST::FUNCTION:ENGINE +ENGINE_get_RAND 2491 EXIST::FUNCTION:ENGINE +ENGINE_get_first 2492 EXIST::FUNCTION:ENGINE +ENGINE_by_id 2493 EXIST::FUNCTION:ENGINE +ENGINE_set_finish_function 2494 EXIST::FUNCTION:ENGINE +ENGINE_get_def_BN_mod_exp_crt 2495 NOEXIST::FUNCTION: +ENGINE_get_default_BN_mod_exp_crt 2495 NOEXIST::FUNCTION: +RSA_get_default_openssl_method 2496 NOEXIST::FUNCTION: +ENGINE_set_RSA 2497 EXIST::FUNCTION:ENGINE +ENGINE_load_private_key 2498 EXIST::FUNCTION:ENGINE +ENGINE_set_default_RAND 2499 EXIST::FUNCTION:ENGINE +ENGINE_set_BN_mod_exp 2500 NOEXIST::FUNCTION: +ENGINE_remove 2501 EXIST::FUNCTION:ENGINE +ENGINE_free 2502 EXIST::FUNCTION:ENGINE +ENGINE_get_BN_mod_exp_crt 2503 NOEXIST::FUNCTION: +ENGINE_get_next 2504 EXIST::FUNCTION:ENGINE +ENGINE_set_name 2505 EXIST::FUNCTION:ENGINE +ENGINE_get_default_DSA 2506 EXIST::FUNCTION:ENGINE +ENGINE_set_default_BN_mod_exp 2507 NOEXIST::FUNCTION: +ENGINE_set_default_RSA 2508 EXIST::FUNCTION:ENGINE +ENGINE_get_default_RAND 2509 EXIST::FUNCTION:ENGINE +ENGINE_get_default_BN_mod_exp 2510 NOEXIST::FUNCTION: +ENGINE_set_RAND 2511 EXIST::FUNCTION:ENGINE +ENGINE_set_id 2512 EXIST::FUNCTION:ENGINE +ENGINE_set_BN_mod_exp_crt 2513 NOEXIST::FUNCTION: +ENGINE_set_default_DH 2514 EXIST::FUNCTION:ENGINE +ENGINE_new 2515 EXIST::FUNCTION:ENGINE +ENGINE_get_id 2516 EXIST::FUNCTION:ENGINE +DSA_set_default_openssl_method 2517 NOEXIST::FUNCTION: +ENGINE_add 2518 EXIST::FUNCTION:ENGINE +DH_set_default_openssl_method 2519 NOEXIST::FUNCTION: +ENGINE_get_DSA 2520 EXIST::FUNCTION:ENGINE +ENGINE_get_ctrl_function 2521 EXIST::FUNCTION:ENGINE +ENGINE_set_ctrl_function 2522 EXIST::FUNCTION:ENGINE +BN_pseudo_rand_range 2523 EXIST::FUNCTION: +X509_STORE_CTX_set_verify_cb 2524 EXIST::FUNCTION: +ERR_load_COMP_strings 2525 EXIST::FUNCTION: +PKCS12_item_decrypt_d2i 2526 EXIST::FUNCTION: +ASN1_UTF8STRING_it 2527 EXIST:!EXPORT_VAR_AS_FUNCTION:VARIABLE: +ASN1_UTF8STRING_it 2527 EXIST:EXPORT_VAR_AS_FUNCTION:FUNCTION: +ENGINE_unregister_ciphers 2528 EXIST::FUNCTION:ENGINE +ENGINE_get_ciphers 2529 EXIST::FUNCTION:ENGINE +d2i_OCSP_BASICRESP 2530 EXIST::FUNCTION: +KRB5_CHECKSUM_it 2531 EXIST:!EXPORT_VAR_AS_FUNCTION:VARIABLE: +KRB5_CHECKSUM_it 2531 EXIST:EXPORT_VAR_AS_FUNCTION:FUNCTION: +EC_POINT_add 2532 EXIST::FUNCTION:EC +ASN1_item_ex_i2d 2533 EXIST::FUNCTION: +OCSP_CERTID_it 2534 EXIST:!EXPORT_VAR_AS_FUNCTION:VARIABLE: +OCSP_CERTID_it 2534 EXIST:EXPORT_VAR_AS_FUNCTION:FUNCTION: +d2i_OCSP_RESPBYTES 2535 EXIST::FUNCTION: +X509V3_add1_i2d 2536 EXIST::FUNCTION: +PKCS7_ENVELOPE_it 2537 EXIST:!EXPORT_VAR_AS_FUNCTION:VARIABLE: +PKCS7_ENVELOPE_it 2537 EXIST:EXPORT_VAR_AS_FUNCTION:FUNCTION: +UI_add_input_boolean 2538 EXIST::FUNCTION: +ENGINE_unregister_RSA 2539 EXIST::FUNCTION:ENGINE +X509V3_EXT_nconf 2540 EXIST::FUNCTION: +ASN1_GENERALSTRING_free 2541 EXIST::FUNCTION: +d2i_OCSP_CERTSTATUS 2542 EXIST::FUNCTION: +X509_REVOKED_set_serialNumber 2543 EXIST::FUNCTION: +X509_print_ex 2544 EXIST::FUNCTION:BIO +OCSP_ONEREQ_get1_ext_d2i 2545 EXIST::FUNCTION: +ENGINE_register_all_RAND 2546 EXIST::FUNCTION:ENGINE +ENGINE_load_dynamic 2547 EXIST::FUNCTION:ENGINE +PBKDF2PARAM_it 2548 EXIST:!EXPORT_VAR_AS_FUNCTION:VARIABLE: +PBKDF2PARAM_it 2548 EXIST:EXPORT_VAR_AS_FUNCTION:FUNCTION: +EXTENDED_KEY_USAGE_new 2549 EXIST::FUNCTION: +EC_GROUP_clear_free 2550 EXIST::FUNCTION:EC +OCSP_sendreq_bio 2551 EXIST::FUNCTION: +ASN1_item_digest 2552 EXIST::FUNCTION:EVP +OCSP_BASICRESP_delete_ext 2553 EXIST::FUNCTION: +OCSP_SIGNATURE_it 2554 EXIST:!EXPORT_VAR_AS_FUNCTION:VARIABLE: +OCSP_SIGNATURE_it 2554 EXIST:EXPORT_VAR_AS_FUNCTION:FUNCTION: +X509_CRL_it 2555 EXIST:!EXPORT_VAR_AS_FUNCTION:VARIABLE: +X509_CRL_it 2555 EXIST:EXPORT_VAR_AS_FUNCTION:FUNCTION: +OCSP_BASICRESP_add_ext 2556 EXIST::FUNCTION: +KRB5_ENCKEY_it 2557 EXIST:!EXPORT_VAR_AS_FUNCTION:VARIABLE: +KRB5_ENCKEY_it 2557 EXIST:EXPORT_VAR_AS_FUNCTION:FUNCTION: +UI_method_set_closer 2558 EXIST::FUNCTION: +X509_STORE_set_purpose 2559 EXIST::FUNCTION: +i2d_ASN1_GENERALSTRING 2560 EXIST::FUNCTION: +OCSP_response_status 2561 EXIST::FUNCTION: +i2d_OCSP_SERVICELOC 2562 EXIST::FUNCTION: +ENGINE_get_digest_engine 2563 EXIST::FUNCTION:ENGINE +EC_GROUP_set_curve_GFp 2564 EXIST::FUNCTION:EC +OCSP_REQUEST_get_ext_by_OBJ 2565 EXIST::FUNCTION: +_ossl_old_des_random_key 2566 EXIST::FUNCTION:DES +ASN1_T61STRING_it 2567 EXIST:!EXPORT_VAR_AS_FUNCTION:VARIABLE: +ASN1_T61STRING_it 2567 EXIST:EXPORT_VAR_AS_FUNCTION:FUNCTION: +EC_GROUP_method_of 2568 EXIST::FUNCTION:EC +i2d_KRB5_APREQ 2569 EXIST::FUNCTION: +_ossl_old_des_encrypt 2570 EXIST::FUNCTION:DES +ASN1_PRINTABLE_new 2571 EXIST::FUNCTION: +HMAC_Init_ex 2572 EXIST::FUNCTION:HMAC +d2i_KRB5_AUTHENT 2573 EXIST::FUNCTION: +OCSP_archive_cutoff_new 2574 EXIST::FUNCTION: +EC_POINT_set_Jprojective_coordinates_GFp 2575 EXIST:!VMS:FUNCTION:EC +EC_POINT_set_Jproj_coords_GFp 2575 EXIST:VMS:FUNCTION:EC +_ossl_old_des_is_weak_key 2576 EXIST::FUNCTION:DES +OCSP_BASICRESP_get_ext_by_OBJ 2577 EXIST::FUNCTION: +EC_POINT_oct2point 2578 EXIST::FUNCTION:EC +OCSP_SINGLERESP_get_ext_count 2579 EXIST::FUNCTION: +UI_ctrl 2580 EXIST::FUNCTION: +_shadow_DES_rw_mode 2581 EXIST:!EXPORT_VAR_AS_FUNCTION:VARIABLE:DES +_shadow_DES_rw_mode 2581 EXIST:EXPORT_VAR_AS_FUNCTION:FUNCTION:DES +asn1_do_adb 2582 EXIST::FUNCTION: +ASN1_template_i2d 2583 EXIST::FUNCTION: +ENGINE_register_DH 2584 EXIST::FUNCTION:ENGINE +UI_construct_prompt 2585 EXIST::FUNCTION: +X509_STORE_set_trust 2586 EXIST::FUNCTION: +UI_dup_input_string 2587 EXIST::FUNCTION: +d2i_KRB5_APREQ 2588 EXIST::FUNCTION: +EVP_MD_CTX_copy_ex 2589 EXIST::FUNCTION: +OCSP_request_is_signed 2590 EXIST::FUNCTION: +i2d_OCSP_REQINFO 2591 EXIST::FUNCTION: +KRB5_ENCKEY_free 2592 EXIST::FUNCTION: +OCSP_resp_get0 2593 EXIST::FUNCTION: +GENERAL_NAME_it 2594 EXIST:!EXPORT_VAR_AS_FUNCTION:VARIABLE: +GENERAL_NAME_it 2594 EXIST:EXPORT_VAR_AS_FUNCTION:FUNCTION: +ASN1_GENERALIZEDTIME_it 2595 EXIST:!EXPORT_VAR_AS_FUNCTION:VARIABLE: +ASN1_GENERALIZEDTIME_it 2595 EXIST:EXPORT_VAR_AS_FUNCTION:FUNCTION: +X509_STORE_set_flags 2596 EXIST::FUNCTION: +EC_POINT_set_compressed_coordinates_GFp 2597 EXIST:!VMS:FUNCTION:EC +EC_POINT_set_compr_coords_GFp 2597 EXIST:VMS:FUNCTION:EC +OCSP_response_status_str 2598 EXIST::FUNCTION: +d2i_OCSP_REVOKEDINFO 2599 EXIST::FUNCTION: +OCSP_basic_add1_cert 2600 EXIST::FUNCTION: +ERR_get_implementation 2601 EXIST::FUNCTION: +EVP_CipherFinal_ex 2602 EXIST::FUNCTION: +OCSP_CERTSTATUS_new 2603 EXIST::FUNCTION: +CRYPTO_cleanup_all_ex_data 2604 EXIST::FUNCTION: +OCSP_resp_find 2605 EXIST::FUNCTION: +BN_nnmod 2606 EXIST::FUNCTION: +X509_CRL_sort 2607 EXIST::FUNCTION: +X509_REVOKED_set_revocationDate 2608 EXIST::FUNCTION: +ENGINE_register_RAND 2609 EXIST::FUNCTION:ENGINE +OCSP_SERVICELOC_new 2610 EXIST::FUNCTION: +EC_POINT_set_affine_coordinates_GFp 2611 EXIST:!VMS:FUNCTION:EC +EC_POINT_set_affine_coords_GFp 2611 EXIST:VMS:FUNCTION:EC +_ossl_old_des_options 2612 EXIST::FUNCTION:DES +SXNET_it 2613 EXIST:!EXPORT_VAR_AS_FUNCTION:VARIABLE: +SXNET_it 2613 EXIST:EXPORT_VAR_AS_FUNCTION:FUNCTION: +UI_dup_input_boolean 2614 EXIST::FUNCTION: +PKCS12_add_CSPName_asc 2615 EXIST::FUNCTION: +EC_POINT_is_at_infinity 2616 EXIST::FUNCTION:EC +ENGINE_load_cryptodev 2617 EXIST::FUNCTION:ENGINE +DSO_convert_filename 2618 EXIST::FUNCTION: +POLICYQUALINFO_it 2619 EXIST:!EXPORT_VAR_AS_FUNCTION:VARIABLE: +POLICYQUALINFO_it 2619 EXIST:EXPORT_VAR_AS_FUNCTION:FUNCTION: +ENGINE_register_ciphers 2620 EXIST::FUNCTION:ENGINE +BN_mod_lshift_quick 2621 EXIST::FUNCTION: +DSO_set_filename 2622 EXIST::FUNCTION: +ASN1_item_free 2623 EXIST::FUNCTION: +KRB5_TKTBODY_free 2624 EXIST::FUNCTION: +AUTHORITY_KEYID_it 2625 EXIST:!EXPORT_VAR_AS_FUNCTION:VARIABLE: +AUTHORITY_KEYID_it 2625 EXIST:EXPORT_VAR_AS_FUNCTION:FUNCTION: +KRB5_APREQBODY_new 2626 EXIST::FUNCTION: +X509V3_EXT_REQ_add_nconf 2627 EXIST::FUNCTION: +ENGINE_ctrl_cmd_string 2628 EXIST::FUNCTION:ENGINE +i2d_OCSP_RESPDATA 2629 EXIST::FUNCTION: +EVP_MD_CTX_init 2630 EXIST::FUNCTION: +EXTENDED_KEY_USAGE_free 2631 EXIST::FUNCTION: +PKCS7_ATTR_SIGN_it 2632 EXIST:!EXPORT_VAR_AS_FUNCTION:VARIABLE: +PKCS7_ATTR_SIGN_it 2632 EXIST:EXPORT_VAR_AS_FUNCTION:FUNCTION: +UI_add_error_string 2633 EXIST::FUNCTION: +KRB5_CHECKSUM_free 2634 EXIST::FUNCTION: +OCSP_REQUEST_get_ext 2635 EXIST::FUNCTION: +ENGINE_load_ubsec 2636 EXIST::FUNCTION:ENGINE,STATIC_ENGINE +ENGINE_register_all_digests 2637 EXIST::FUNCTION:ENGINE +PKEY_USAGE_PERIOD_it 2638 EXIST:!EXPORT_VAR_AS_FUNCTION:VARIABLE: +PKEY_USAGE_PERIOD_it 2638 EXIST:EXPORT_VAR_AS_FUNCTION:FUNCTION: +PKCS12_unpack_authsafes 2639 EXIST::FUNCTION: +ASN1_item_unpack 2640 EXIST::FUNCTION: +NETSCAPE_SPKAC_it 2641 EXIST:!EXPORT_VAR_AS_FUNCTION:VARIABLE: +NETSCAPE_SPKAC_it 2641 EXIST:EXPORT_VAR_AS_FUNCTION:FUNCTION: +X509_REVOKED_it 2642 EXIST:!EXPORT_VAR_AS_FUNCTION:VARIABLE: +X509_REVOKED_it 2642 EXIST:EXPORT_VAR_AS_FUNCTION:FUNCTION: +ASN1_STRING_encode 2643 NOEXIST::FUNCTION: +EVP_aes_128_ecb 2644 EXIST::FUNCTION:AES +KRB5_AUTHENT_free 2645 EXIST::FUNCTION: +OCSP_BASICRESP_get_ext_by_critical 2646 EXIST:!VMS:FUNCTION: +OCSP_BASICRESP_get_ext_by_crit 2646 EXIST:VMS:FUNCTION: +OCSP_cert_status_str 2647 EXIST::FUNCTION: +d2i_OCSP_REQUEST 2648 EXIST::FUNCTION: +UI_dup_info_string 2649 EXIST::FUNCTION: +_ossl_old_des_xwhite_in2out 2650 NOEXIST::FUNCTION: +PKCS12_it 2651 EXIST:!EXPORT_VAR_AS_FUNCTION:VARIABLE: +PKCS12_it 2651 EXIST:EXPORT_VAR_AS_FUNCTION:FUNCTION: +OCSP_SINGLERESP_get_ext_by_critical 2652 EXIST:!VMS:FUNCTION: +OCSP_SINGLERESP_get_ext_by_crit 2652 EXIST:VMS:FUNCTION: +OCSP_CERTSTATUS_free 2653 EXIST::FUNCTION: +_ossl_old_des_crypt 2654 EXIST::FUNCTION:DES +ASN1_item_i2d 2655 EXIST::FUNCTION: +EVP_DecryptFinal_ex 2656 EXIST::FUNCTION: +ENGINE_load_openssl 2657 EXIST::FUNCTION:ENGINE +ENGINE_get_cmd_defns 2658 EXIST::FUNCTION:ENGINE +ENGINE_set_load_privkey_function 2659 EXIST:!VMS:FUNCTION:ENGINE +ENGINE_set_load_privkey_fn 2659 EXIST:VMS:FUNCTION:ENGINE +EVP_EncryptFinal_ex 2660 EXIST::FUNCTION: +ENGINE_set_default_digests 2661 EXIST::FUNCTION:ENGINE +X509_get0_pubkey_bitstr 2662 EXIST::FUNCTION: +asn1_ex_i2c 2663 EXIST::FUNCTION: +ENGINE_register_RSA 2664 EXIST::FUNCTION:ENGINE +ENGINE_unregister_DSA 2665 EXIST::FUNCTION:ENGINE +_ossl_old_des_key_sched 2666 EXIST::FUNCTION:DES +X509_EXTENSION_it 2667 EXIST:!EXPORT_VAR_AS_FUNCTION:VARIABLE: +X509_EXTENSION_it 2667 EXIST:EXPORT_VAR_AS_FUNCTION:FUNCTION: +i2d_KRB5_AUTHENT 2668 EXIST::FUNCTION: +SXNETID_it 2669 EXIST:!EXPORT_VAR_AS_FUNCTION:VARIABLE: +SXNETID_it 2669 EXIST:EXPORT_VAR_AS_FUNCTION:FUNCTION: +d2i_OCSP_SINGLERESP 2670 EXIST::FUNCTION: +EDIPARTYNAME_new 2671 EXIST::FUNCTION: +PKCS12_certbag2x509 2672 EXIST::FUNCTION: +_ossl_old_des_ofb64_encrypt 2673 EXIST::FUNCTION:DES +d2i_EXTENDED_KEY_USAGE 2674 EXIST::FUNCTION: +ERR_print_errors_cb 2675 EXIST::FUNCTION: +ENGINE_set_ciphers 2676 EXIST::FUNCTION:ENGINE +d2i_KRB5_APREQBODY 2677 EXIST::FUNCTION: +UI_method_get_flusher 2678 EXIST::FUNCTION: +X509_PUBKEY_it 2679 EXIST:!EXPORT_VAR_AS_FUNCTION:VARIABLE: +X509_PUBKEY_it 2679 EXIST:EXPORT_VAR_AS_FUNCTION:FUNCTION: +_ossl_old_des_enc_read 2680 EXIST::FUNCTION:DES +PKCS7_ENCRYPT_it 2681 EXIST:!EXPORT_VAR_AS_FUNCTION:VARIABLE: +PKCS7_ENCRYPT_it 2681 EXIST:EXPORT_VAR_AS_FUNCTION:FUNCTION: +i2d_OCSP_RESPONSE 2682 EXIST::FUNCTION: +EC_GROUP_get_cofactor 2683 EXIST::FUNCTION:EC +PKCS12_unpack_p7data 2684 EXIST::FUNCTION: +d2i_KRB5_AUTHDATA 2685 EXIST::FUNCTION: +OCSP_copy_nonce 2686 EXIST::FUNCTION: +KRB5_AUTHDATA_new 2687 EXIST::FUNCTION: +OCSP_RESPDATA_new 2688 EXIST::FUNCTION: +EC_GFp_mont_method 2689 EXIST::FUNCTION:EC +OCSP_REVOKEDINFO_free 2690 EXIST::FUNCTION: +UI_get_ex_data 2691 EXIST::FUNCTION: +KRB5_APREQBODY_free 2692 EXIST::FUNCTION: +EC_GROUP_get0_generator 2693 EXIST::FUNCTION:EC +UI_get_default_method 2694 EXIST::FUNCTION: +X509V3_set_nconf 2695 EXIST::FUNCTION: +PKCS12_item_i2d_encrypt 2696 EXIST::FUNCTION: +X509_add1_ext_i2d 2697 EXIST::FUNCTION: +PKCS7_SIGNER_INFO_it 2698 EXIST:!EXPORT_VAR_AS_FUNCTION:VARIABLE: +PKCS7_SIGNER_INFO_it 2698 EXIST:EXPORT_VAR_AS_FUNCTION:FUNCTION: +KRB5_PRINCNAME_new 2699 EXIST::FUNCTION: +PKCS12_SAFEBAG_it 2700 EXIST:!EXPORT_VAR_AS_FUNCTION:VARIABLE: +PKCS12_SAFEBAG_it 2700 EXIST:EXPORT_VAR_AS_FUNCTION:FUNCTION: +EC_GROUP_get_order 2701 EXIST::FUNCTION:EC +d2i_OCSP_RESPID 2702 EXIST::FUNCTION: +OCSP_request_verify 2703 EXIST::FUNCTION: +NCONF_get_number_e 2704 EXIST::FUNCTION: +_ossl_old_des_decrypt3 2705 EXIST::FUNCTION:DES +X509_signature_print 2706 EXIST::FUNCTION:EVP +OCSP_SINGLERESP_free 2707 EXIST::FUNCTION: +ENGINE_load_builtin_engines 2708 EXIST::FUNCTION:ENGINE +i2d_OCSP_ONEREQ 2709 EXIST::FUNCTION: +OCSP_REQUEST_add_ext 2710 EXIST::FUNCTION: +OCSP_RESPBYTES_new 2711 EXIST::FUNCTION: +EVP_MD_CTX_create 2712 EXIST::FUNCTION: +OCSP_resp_find_status 2713 EXIST::FUNCTION: +X509_ALGOR_it 2714 EXIST:!EXPORT_VAR_AS_FUNCTION:VARIABLE: +X509_ALGOR_it 2714 EXIST:EXPORT_VAR_AS_FUNCTION:FUNCTION: +ASN1_TIME_it 2715 EXIST:!EXPORT_VAR_AS_FUNCTION:VARIABLE: +ASN1_TIME_it 2715 EXIST:EXPORT_VAR_AS_FUNCTION:FUNCTION: +OCSP_request_set1_name 2716 EXIST::FUNCTION: +OCSP_ONEREQ_get_ext_count 2717 EXIST::FUNCTION: +UI_get0_result 2718 EXIST::FUNCTION: +PKCS12_AUTHSAFES_it 2719 EXIST:!EXPORT_VAR_AS_FUNCTION:VARIABLE: +PKCS12_AUTHSAFES_it 2719 EXIST:EXPORT_VAR_AS_FUNCTION:FUNCTION: +EVP_aes_256_ecb 2720 EXIST::FUNCTION:AES +PKCS12_pack_authsafes 2721 EXIST::FUNCTION: +ASN1_IA5STRING_it 2722 EXIST:!EXPORT_VAR_AS_FUNCTION:VARIABLE: +ASN1_IA5STRING_it 2722 EXIST:EXPORT_VAR_AS_FUNCTION:FUNCTION: +UI_get_input_flags 2723 EXIST::FUNCTION: +EC_GROUP_set_generator 2724 EXIST::FUNCTION:EC +_ossl_old_des_string_to_2keys 2725 EXIST::FUNCTION:DES +OCSP_CERTID_free 2726 EXIST::FUNCTION: +X509_CERT_AUX_it 2727 EXIST:!EXPORT_VAR_AS_FUNCTION:VARIABLE: +X509_CERT_AUX_it 2727 EXIST:EXPORT_VAR_AS_FUNCTION:FUNCTION: +CERTIFICATEPOLICIES_it 2728 EXIST:!EXPORT_VAR_AS_FUNCTION:VARIABLE: +CERTIFICATEPOLICIES_it 2728 EXIST:EXPORT_VAR_AS_FUNCTION:FUNCTION: +_ossl_old_des_ede3_cbc_encrypt 2729 EXIST::FUNCTION:DES +RAND_set_rand_engine 2730 EXIST::FUNCTION:ENGINE +DSO_get_loaded_filename 2731 EXIST::FUNCTION: +X509_ATTRIBUTE_it 2732 EXIST:!EXPORT_VAR_AS_FUNCTION:VARIABLE: +X509_ATTRIBUTE_it 2732 EXIST:EXPORT_VAR_AS_FUNCTION:FUNCTION: +OCSP_ONEREQ_get_ext_by_NID 2733 EXIST::FUNCTION: +PKCS12_decrypt_skey 2734 EXIST::FUNCTION: +KRB5_AUTHENT_it 2735 EXIST:!EXPORT_VAR_AS_FUNCTION:VARIABLE: +KRB5_AUTHENT_it 2735 EXIST:EXPORT_VAR_AS_FUNCTION:FUNCTION: +UI_dup_error_string 2736 EXIST::FUNCTION: +RSAPublicKey_it 2737 EXIST:!EXPORT_VAR_AS_FUNCTION:VARIABLE:RSA +RSAPublicKey_it 2737 EXIST:EXPORT_VAR_AS_FUNCTION:FUNCTION:RSA +i2d_OCSP_REQUEST 2738 EXIST::FUNCTION: +PKCS12_x509crl2certbag 2739 EXIST::FUNCTION: +OCSP_SERVICELOC_it 2740 EXIST:!EXPORT_VAR_AS_FUNCTION:VARIABLE: +OCSP_SERVICELOC_it 2740 EXIST:EXPORT_VAR_AS_FUNCTION:FUNCTION: +ASN1_item_sign 2741 EXIST::FUNCTION:EVP +X509_CRL_set_issuer_name 2742 EXIST::FUNCTION: +OBJ_NAME_do_all_sorted 2743 EXIST::FUNCTION: +i2d_OCSP_BASICRESP 2744 EXIST::FUNCTION: +i2d_OCSP_RESPBYTES 2745 EXIST::FUNCTION: +PKCS12_unpack_p7encdata 2746 EXIST::FUNCTION: +HMAC_CTX_init 2747 EXIST::FUNCTION:HMAC +ENGINE_get_digest 2748 EXIST::FUNCTION:ENGINE +OCSP_RESPONSE_print 2749 EXIST::FUNCTION: +KRB5_TKTBODY_it 2750 EXIST:!EXPORT_VAR_AS_FUNCTION:VARIABLE: +KRB5_TKTBODY_it 2750 EXIST:EXPORT_VAR_AS_FUNCTION:FUNCTION: +ACCESS_DESCRIPTION_it 2751 EXIST:!EXPORT_VAR_AS_FUNCTION:VARIABLE: +ACCESS_DESCRIPTION_it 2751 EXIST:EXPORT_VAR_AS_FUNCTION:FUNCTION: +PKCS7_ISSUER_AND_SERIAL_it 2752 EXIST:!EXPORT_VAR_AS_FUNCTION:VARIABLE: +PKCS7_ISSUER_AND_SERIAL_it 2752 EXIST:EXPORT_VAR_AS_FUNCTION:FUNCTION: +PBE2PARAM_it 2753 EXIST:!EXPORT_VAR_AS_FUNCTION:VARIABLE: +PBE2PARAM_it 2753 EXIST:EXPORT_VAR_AS_FUNCTION:FUNCTION: +PKCS12_certbag2x509crl 2754 EXIST::FUNCTION: +PKCS7_SIGNED_it 2755 EXIST:!EXPORT_VAR_AS_FUNCTION:VARIABLE: +PKCS7_SIGNED_it 2755 EXIST:EXPORT_VAR_AS_FUNCTION:FUNCTION: +ENGINE_get_cipher 2756 EXIST::FUNCTION:ENGINE +i2d_OCSP_CRLID 2757 EXIST::FUNCTION: +OCSP_SINGLERESP_new 2758 EXIST::FUNCTION: +ENGINE_cmd_is_executable 2759 EXIST::FUNCTION:ENGINE +RSA_up_ref 2760 EXIST::FUNCTION:RSA +ASN1_GENERALSTRING_it 2761 EXIST:!EXPORT_VAR_AS_FUNCTION:VARIABLE: +ASN1_GENERALSTRING_it 2761 EXIST:EXPORT_VAR_AS_FUNCTION:FUNCTION: +ENGINE_register_DSA 2762 EXIST::FUNCTION:ENGINE +X509V3_EXT_add_nconf_sk 2763 EXIST::FUNCTION: +ENGINE_set_load_pubkey_function 2764 EXIST::FUNCTION:ENGINE +PKCS8_decrypt 2765 EXIST::FUNCTION: +PEM_bytes_read_bio 2766 EXIST::FUNCTION:BIO +DIRECTORYSTRING_it 2767 EXIST:!EXPORT_VAR_AS_FUNCTION:VARIABLE: +DIRECTORYSTRING_it 2767 EXIST:EXPORT_VAR_AS_FUNCTION:FUNCTION: +d2i_OCSP_CRLID 2768 EXIST::FUNCTION: +EC_POINT_is_on_curve 2769 EXIST::FUNCTION:EC +CRYPTO_set_locked_mem_ex_functions 2770 EXIST:!VMS:FUNCTION: +CRYPTO_set_locked_mem_ex_funcs 2770 EXIST:VMS:FUNCTION: +d2i_KRB5_CHECKSUM 2771 EXIST::FUNCTION: +ASN1_item_dup 2772 EXIST::FUNCTION: +X509_it 2773 EXIST:!EXPORT_VAR_AS_FUNCTION:VARIABLE: +X509_it 2773 EXIST:EXPORT_VAR_AS_FUNCTION:FUNCTION: +BN_mod_add 2774 EXIST::FUNCTION: +KRB5_AUTHDATA_free 2775 EXIST::FUNCTION: +_ossl_old_des_cbc_cksum 2776 EXIST::FUNCTION:DES +ASN1_item_verify 2777 EXIST::FUNCTION:EVP +CRYPTO_set_mem_ex_functions 2778 EXIST::FUNCTION: +EC_POINT_get_Jprojective_coordinates_GFp 2779 EXIST:!VMS:FUNCTION:EC +EC_POINT_get_Jproj_coords_GFp 2779 EXIST:VMS:FUNCTION:EC +ZLONG_it 2780 EXIST:!EXPORT_VAR_AS_FUNCTION:VARIABLE: +ZLONG_it 2780 EXIST:EXPORT_VAR_AS_FUNCTION:FUNCTION: +CRYPTO_get_locked_mem_ex_functions 2781 EXIST:!VMS:FUNCTION: +CRYPTO_get_locked_mem_ex_funcs 2781 EXIST:VMS:FUNCTION: +ASN1_TIME_check 2782 EXIST::FUNCTION: +UI_get0_user_data 2783 EXIST::FUNCTION: +HMAC_CTX_cleanup 2784 EXIST::FUNCTION:HMAC +DSA_up_ref 2785 EXIST::FUNCTION:DSA +_ossl_old_des_ede3_cfb64_encrypt 2786 EXIST:!VMS:FUNCTION:DES +_ossl_odes_ede3_cfb64_encrypt 2786 EXIST:VMS:FUNCTION:DES +ASN1_BMPSTRING_it 2787 EXIST:!EXPORT_VAR_AS_FUNCTION:VARIABLE: +ASN1_BMPSTRING_it 2787 EXIST:EXPORT_VAR_AS_FUNCTION:FUNCTION: +ASN1_tag2bit 2788 EXIST::FUNCTION: +UI_method_set_flusher 2789 EXIST::FUNCTION: +X509_ocspid_print 2790 EXIST::FUNCTION:BIO +KRB5_ENCDATA_it 2791 EXIST:!EXPORT_VAR_AS_FUNCTION:VARIABLE: +KRB5_ENCDATA_it 2791 EXIST:EXPORT_VAR_AS_FUNCTION:FUNCTION: +ENGINE_get_load_pubkey_function 2792 EXIST::FUNCTION:ENGINE +UI_add_user_data 2793 EXIST::FUNCTION: +OCSP_REQUEST_delete_ext 2794 EXIST::FUNCTION: +UI_get_method 2795 EXIST::FUNCTION: +OCSP_ONEREQ_free 2796 EXIST::FUNCTION: +ASN1_PRINTABLESTRING_it 2797 EXIST:!EXPORT_VAR_AS_FUNCTION:VARIABLE: +ASN1_PRINTABLESTRING_it 2797 EXIST:EXPORT_VAR_AS_FUNCTION:FUNCTION: +X509_CRL_set_nextUpdate 2798 EXIST::FUNCTION: +OCSP_REQUEST_it 2799 EXIST:!EXPORT_VAR_AS_FUNCTION:VARIABLE: +OCSP_REQUEST_it 2799 EXIST:EXPORT_VAR_AS_FUNCTION:FUNCTION: +OCSP_BASICRESP_it 2800 EXIST:!EXPORT_VAR_AS_FUNCTION:VARIABLE: +OCSP_BASICRESP_it 2800 EXIST:EXPORT_VAR_AS_FUNCTION:FUNCTION: +AES_ecb_encrypt 2801 EXIST::FUNCTION:AES +BN_mod_sqr 2802 EXIST::FUNCTION: +NETSCAPE_CERT_SEQUENCE_it 2803 EXIST:!EXPORT_VAR_AS_FUNCTION:VARIABLE: +NETSCAPE_CERT_SEQUENCE_it 2803 EXIST:EXPORT_VAR_AS_FUNCTION:FUNCTION: +GENERAL_NAMES_it 2804 EXIST:!EXPORT_VAR_AS_FUNCTION:VARIABLE: +GENERAL_NAMES_it 2804 EXIST:EXPORT_VAR_AS_FUNCTION:FUNCTION: +AUTHORITY_INFO_ACCESS_it 2805 EXIST:!EXPORT_VAR_AS_FUNCTION:VARIABLE: +AUTHORITY_INFO_ACCESS_it 2805 EXIST:EXPORT_VAR_AS_FUNCTION:FUNCTION: +ASN1_FBOOLEAN_it 2806 EXIST:!EXPORT_VAR_AS_FUNCTION:VARIABLE: +ASN1_FBOOLEAN_it 2806 EXIST:EXPORT_VAR_AS_FUNCTION:FUNCTION: +UI_set_ex_data 2807 EXIST::FUNCTION: +_ossl_old_des_string_to_key 2808 EXIST::FUNCTION:DES +ENGINE_register_all_RSA 2809 EXIST::FUNCTION:ENGINE +d2i_KRB5_PRINCNAME 2810 EXIST::FUNCTION: +OCSP_RESPBYTES_it 2811 EXIST:!EXPORT_VAR_AS_FUNCTION:VARIABLE: +OCSP_RESPBYTES_it 2811 EXIST:EXPORT_VAR_AS_FUNCTION:FUNCTION: +X509_CINF_it 2812 EXIST:!EXPORT_VAR_AS_FUNCTION:VARIABLE: +X509_CINF_it 2812 EXIST:EXPORT_VAR_AS_FUNCTION:FUNCTION: +ENGINE_unregister_digests 2813 EXIST::FUNCTION:ENGINE +d2i_EDIPARTYNAME 2814 EXIST::FUNCTION: +d2i_OCSP_SERVICELOC 2815 EXIST::FUNCTION: +ENGINE_get_digests 2816 EXIST::FUNCTION:ENGINE +_ossl_old_des_set_odd_parity 2817 EXIST::FUNCTION:DES +OCSP_RESPDATA_free 2818 EXIST::FUNCTION: +d2i_KRB5_TICKET 2819 EXIST::FUNCTION: +OTHERNAME_it 2820 EXIST:!EXPORT_VAR_AS_FUNCTION:VARIABLE: +OTHERNAME_it 2820 EXIST:EXPORT_VAR_AS_FUNCTION:FUNCTION: +EVP_MD_CTX_cleanup 2821 EXIST::FUNCTION: +d2i_ASN1_GENERALSTRING 2822 EXIST::FUNCTION: +X509_CRL_set_version 2823 EXIST::FUNCTION: +BN_mod_sub 2824 EXIST::FUNCTION: +OCSP_SINGLERESP_get_ext_by_NID 2825 EXIST::FUNCTION: +ENGINE_get_ex_new_index 2826 EXIST::FUNCTION:ENGINE +OCSP_REQUEST_free 2827 EXIST::FUNCTION: +OCSP_REQUEST_add1_ext_i2d 2828 EXIST::FUNCTION: +X509_VAL_it 2829 EXIST:!EXPORT_VAR_AS_FUNCTION:VARIABLE: +X509_VAL_it 2829 EXIST:EXPORT_VAR_AS_FUNCTION:FUNCTION: +EC_POINTs_make_affine 2830 EXIST::FUNCTION:EC +EC_POINT_mul 2831 EXIST::FUNCTION:EC +X509V3_EXT_add_nconf 2832 EXIST::FUNCTION: +X509_TRUST_set 2833 EXIST::FUNCTION: +X509_CRL_add1_ext_i2d 2834 EXIST::FUNCTION: +_ossl_old_des_fcrypt 2835 EXIST::FUNCTION:DES +DISPLAYTEXT_it 2836 EXIST:!EXPORT_VAR_AS_FUNCTION:VARIABLE: +DISPLAYTEXT_it 2836 EXIST:EXPORT_VAR_AS_FUNCTION:FUNCTION: +X509_CRL_set_lastUpdate 2837 EXIST::FUNCTION: +OCSP_BASICRESP_free 2838 EXIST::FUNCTION: +OCSP_BASICRESP_add1_ext_i2d 2839 EXIST::FUNCTION: +d2i_KRB5_AUTHENTBODY 2840 EXIST::FUNCTION: +CRYPTO_set_ex_data_implementation 2841 EXIST:!VMS:FUNCTION: +CRYPTO_set_ex_data_impl 2841 EXIST:VMS:FUNCTION: +KRB5_ENCDATA_new 2842 EXIST::FUNCTION: +DSO_up_ref 2843 EXIST::FUNCTION: +OCSP_crl_reason_str 2844 EXIST::FUNCTION: +UI_get0_result_string 2845 EXIST::FUNCTION: +ASN1_GENERALSTRING_new 2846 EXIST::FUNCTION: +X509_SIG_it 2847 EXIST:!EXPORT_VAR_AS_FUNCTION:VARIABLE: +X509_SIG_it 2847 EXIST:EXPORT_VAR_AS_FUNCTION:FUNCTION: +ERR_set_implementation 2848 EXIST::FUNCTION: +ERR_load_EC_strings 2849 EXIST::FUNCTION:EC +UI_get0_action_string 2850 EXIST::FUNCTION: +OCSP_ONEREQ_get_ext 2851 EXIST::FUNCTION: +EC_POINT_method_of 2852 EXIST::FUNCTION:EC +i2d_KRB5_APREQBODY 2853 EXIST::FUNCTION: +_ossl_old_des_ecb3_encrypt 2854 EXIST::FUNCTION:DES +CRYPTO_get_mem_ex_functions 2855 EXIST::FUNCTION: +ENGINE_get_ex_data 2856 EXIST::FUNCTION:ENGINE +UI_destroy_method 2857 EXIST::FUNCTION: +ASN1_item_i2d_bio 2858 EXIST::FUNCTION:BIO +OCSP_ONEREQ_get_ext_by_OBJ 2859 EXIST::FUNCTION: +ASN1_primitive_new 2860 EXIST::FUNCTION: +ASN1_PRINTABLE_it 2861 EXIST:!EXPORT_VAR_AS_FUNCTION:VARIABLE: +ASN1_PRINTABLE_it 2861 EXIST:EXPORT_VAR_AS_FUNCTION:FUNCTION: +EVP_aes_192_ecb 2862 EXIST::FUNCTION:AES +OCSP_SIGNATURE_new 2863 EXIST::FUNCTION: +LONG_it 2864 EXIST:!EXPORT_VAR_AS_FUNCTION:VARIABLE: +LONG_it 2864 EXIST:EXPORT_VAR_AS_FUNCTION:FUNCTION: +ASN1_VISIBLESTRING_it 2865 EXIST:!EXPORT_VAR_AS_FUNCTION:VARIABLE: +ASN1_VISIBLESTRING_it 2865 EXIST:EXPORT_VAR_AS_FUNCTION:FUNCTION: +OCSP_SINGLERESP_add1_ext_i2d 2866 EXIST::FUNCTION: +d2i_OCSP_CERTID 2867 EXIST::FUNCTION: +ASN1_item_d2i_fp 2868 EXIST::FUNCTION:FP_API +CRL_DIST_POINTS_it 2869 EXIST:!EXPORT_VAR_AS_FUNCTION:VARIABLE: +CRL_DIST_POINTS_it 2869 EXIST:EXPORT_VAR_AS_FUNCTION:FUNCTION: +GENERAL_NAME_print 2870 EXIST::FUNCTION: +OCSP_SINGLERESP_delete_ext 2871 EXIST::FUNCTION: +PKCS12_SAFEBAGS_it 2872 EXIST:!EXPORT_VAR_AS_FUNCTION:VARIABLE: +PKCS12_SAFEBAGS_it 2872 EXIST:EXPORT_VAR_AS_FUNCTION:FUNCTION: +d2i_OCSP_SIGNATURE 2873 EXIST::FUNCTION: +OCSP_request_add1_nonce 2874 EXIST::FUNCTION: +ENGINE_set_cmd_defns 2875 EXIST::FUNCTION:ENGINE +OCSP_SERVICELOC_free 2876 EXIST::FUNCTION: +EC_GROUP_free 2877 EXIST::FUNCTION:EC +ASN1_BIT_STRING_it 2878 EXIST:!EXPORT_VAR_AS_FUNCTION:VARIABLE: +ASN1_BIT_STRING_it 2878 EXIST:EXPORT_VAR_AS_FUNCTION:FUNCTION: +X509_REQ_it 2879 EXIST:!EXPORT_VAR_AS_FUNCTION:VARIABLE: +X509_REQ_it 2879 EXIST:EXPORT_VAR_AS_FUNCTION:FUNCTION: +_ossl_old_des_cbc_encrypt 2880 EXIST::FUNCTION:DES +ERR_unload_strings 2881 EXIST::FUNCTION: +PKCS7_SIGN_ENVELOPE_it 2882 EXIST:!EXPORT_VAR_AS_FUNCTION:VARIABLE: +PKCS7_SIGN_ENVELOPE_it 2882 EXIST:EXPORT_VAR_AS_FUNCTION:FUNCTION: +EDIPARTYNAME_free 2883 EXIST::FUNCTION: +OCSP_REQINFO_free 2884 EXIST::FUNCTION: +EC_GROUP_new_curve_GFp 2885 EXIST::FUNCTION:EC +OCSP_REQUEST_get1_ext_d2i 2886 EXIST::FUNCTION: +PKCS12_item_pack_safebag 2887 EXIST::FUNCTION: +asn1_ex_c2i 2888 EXIST::FUNCTION: +ENGINE_register_digests 2889 EXIST::FUNCTION:ENGINE +i2d_OCSP_REVOKEDINFO 2890 EXIST::FUNCTION: +asn1_enc_restore 2891 EXIST::FUNCTION: +UI_free 2892 EXIST::FUNCTION: +UI_new_method 2893 EXIST::FUNCTION: +EVP_EncryptInit_ex 2894 EXIST::FUNCTION: +X509_pubkey_digest 2895 EXIST::FUNCTION:EVP +EC_POINT_invert 2896 EXIST::FUNCTION:EC +OCSP_basic_sign 2897 EXIST::FUNCTION: +i2d_OCSP_RESPID 2898 EXIST::FUNCTION: +OCSP_check_nonce 2899 EXIST::FUNCTION: +ENGINE_ctrl_cmd 2900 EXIST::FUNCTION:ENGINE +d2i_KRB5_ENCKEY 2901 EXIST::FUNCTION: +OCSP_parse_url 2902 EXIST::FUNCTION: +OCSP_SINGLERESP_get_ext 2903 EXIST::FUNCTION: +OCSP_CRLID_free 2904 EXIST::FUNCTION: +OCSP_BASICRESP_get1_ext_d2i 2905 EXIST::FUNCTION: +RSAPrivateKey_it 2906 EXIST:!EXPORT_VAR_AS_FUNCTION:VARIABLE:RSA +RSAPrivateKey_it 2906 EXIST:EXPORT_VAR_AS_FUNCTION:FUNCTION:RSA +ENGINE_register_all_DH 2907 EXIST::FUNCTION:ENGINE +i2d_EDIPARTYNAME 2908 EXIST::FUNCTION: +EC_POINT_get_affine_coordinates_GFp 2909 EXIST:!VMS:FUNCTION:EC +EC_POINT_get_affine_coords_GFp 2909 EXIST:VMS:FUNCTION:EC +OCSP_CRLID_new 2910 EXIST::FUNCTION: +ENGINE_get_flags 2911 EXIST::FUNCTION:ENGINE +OCSP_ONEREQ_it 2912 EXIST:!EXPORT_VAR_AS_FUNCTION:VARIABLE: +OCSP_ONEREQ_it 2912 EXIST:EXPORT_VAR_AS_FUNCTION:FUNCTION: +UI_process 2913 EXIST::FUNCTION: +ASN1_INTEGER_it 2914 EXIST:!EXPORT_VAR_AS_FUNCTION:VARIABLE: +ASN1_INTEGER_it 2914 EXIST:EXPORT_VAR_AS_FUNCTION:FUNCTION: +EVP_CipherInit_ex 2915 EXIST::FUNCTION: +UI_get_string_type 2916 EXIST::FUNCTION: +ENGINE_unregister_DH 2917 EXIST::FUNCTION:ENGINE +ENGINE_register_all_DSA 2918 EXIST::FUNCTION:ENGINE +OCSP_ONEREQ_get_ext_by_critical 2919 EXIST::FUNCTION: +bn_dup_expand 2920 EXIST::FUNCTION:DEPRECATED +OCSP_cert_id_new 2921 EXIST::FUNCTION: +BASIC_CONSTRAINTS_it 2922 EXIST:!EXPORT_VAR_AS_FUNCTION:VARIABLE: +BASIC_CONSTRAINTS_it 2922 EXIST:EXPORT_VAR_AS_FUNCTION:FUNCTION: +BN_mod_add_quick 2923 EXIST::FUNCTION: +EC_POINT_new 2924 EXIST::FUNCTION:EC +EVP_MD_CTX_destroy 2925 EXIST::FUNCTION: +OCSP_RESPBYTES_free 2926 EXIST::FUNCTION: +EVP_aes_128_cbc 2927 EXIST::FUNCTION:AES +OCSP_SINGLERESP_get1_ext_d2i 2928 EXIST::FUNCTION: +EC_POINT_free 2929 EXIST::FUNCTION:EC +DH_up_ref 2930 EXIST::FUNCTION:DH +X509_NAME_ENTRY_it 2931 EXIST:!EXPORT_VAR_AS_FUNCTION:VARIABLE: +X509_NAME_ENTRY_it 2931 EXIST:EXPORT_VAR_AS_FUNCTION:FUNCTION: +UI_get_ex_new_index 2932 EXIST::FUNCTION: +BN_mod_sub_quick 2933 EXIST::FUNCTION: +OCSP_ONEREQ_add_ext 2934 EXIST::FUNCTION: +OCSP_request_sign 2935 EXIST::FUNCTION: +EVP_DigestFinal_ex 2936 EXIST::FUNCTION: +ENGINE_set_digests 2937 EXIST::FUNCTION:ENGINE +OCSP_id_issuer_cmp 2938 EXIST::FUNCTION: +OBJ_NAME_do_all 2939 EXIST::FUNCTION: +EC_POINTs_mul 2940 EXIST::FUNCTION:EC +ENGINE_register_complete 2941 EXIST::FUNCTION:ENGINE +X509V3_EXT_nconf_nid 2942 EXIST::FUNCTION: +ASN1_SEQUENCE_it 2943 EXIST:!EXPORT_VAR_AS_FUNCTION:VARIABLE: +ASN1_SEQUENCE_it 2943 EXIST:EXPORT_VAR_AS_FUNCTION:FUNCTION: +UI_set_default_method 2944 EXIST::FUNCTION: +RAND_query_egd_bytes 2945 EXIST::FUNCTION: +UI_method_get_writer 2946 EXIST::FUNCTION: +UI_OpenSSL 2947 EXIST::FUNCTION: +PEM_def_callback 2948 EXIST::FUNCTION: +ENGINE_cleanup 2949 EXIST::FUNCTION:ENGINE +DIST_POINT_it 2950 EXIST:!EXPORT_VAR_AS_FUNCTION:VARIABLE: +DIST_POINT_it 2950 EXIST:EXPORT_VAR_AS_FUNCTION:FUNCTION: +OCSP_SINGLERESP_it 2951 EXIST:!EXPORT_VAR_AS_FUNCTION:VARIABLE: +OCSP_SINGLERESP_it 2951 EXIST:EXPORT_VAR_AS_FUNCTION:FUNCTION: +d2i_KRB5_TKTBODY 2952 EXIST::FUNCTION: +EC_POINT_cmp 2953 EXIST::FUNCTION:EC +OCSP_REVOKEDINFO_new 2954 EXIST::FUNCTION: +i2d_OCSP_CERTSTATUS 2955 EXIST::FUNCTION: +OCSP_basic_add1_nonce 2956 EXIST::FUNCTION: +ASN1_item_ex_d2i 2957 EXIST::FUNCTION: +BN_mod_lshift1_quick 2958 EXIST::FUNCTION: +UI_set_method 2959 EXIST::FUNCTION: +OCSP_id_get0_info 2960 EXIST::FUNCTION: +BN_mod_sqrt 2961 EXIST::FUNCTION: +EC_GROUP_copy 2962 EXIST::FUNCTION:EC +KRB5_ENCDATA_free 2963 EXIST::FUNCTION: +_ossl_old_des_cfb_encrypt 2964 EXIST::FUNCTION:DES +OCSP_SINGLERESP_get_ext_by_OBJ 2965 EXIST::FUNCTION: +OCSP_cert_to_id 2966 EXIST::FUNCTION: +OCSP_RESPID_new 2967 EXIST::FUNCTION: +OCSP_RESPDATA_it 2968 EXIST:!EXPORT_VAR_AS_FUNCTION:VARIABLE: +OCSP_RESPDATA_it 2968 EXIST:EXPORT_VAR_AS_FUNCTION:FUNCTION: +d2i_OCSP_RESPDATA 2969 EXIST::FUNCTION: +ENGINE_register_all_complete 2970 EXIST::FUNCTION:ENGINE +OCSP_check_validity 2971 EXIST::FUNCTION: +PKCS12_BAGS_it 2972 EXIST:!EXPORT_VAR_AS_FUNCTION:VARIABLE: +PKCS12_BAGS_it 2972 EXIST:EXPORT_VAR_AS_FUNCTION:FUNCTION: +OCSP_url_svcloc_new 2973 EXIST::FUNCTION: +ASN1_template_free 2974 EXIST::FUNCTION: +OCSP_SINGLERESP_add_ext 2975 EXIST::FUNCTION: +KRB5_AUTHENTBODY_it 2976 EXIST:!EXPORT_VAR_AS_FUNCTION:VARIABLE: +KRB5_AUTHENTBODY_it 2976 EXIST:EXPORT_VAR_AS_FUNCTION:FUNCTION: +X509_supported_extension 2977 EXIST::FUNCTION: +i2d_KRB5_AUTHDATA 2978 EXIST::FUNCTION: +UI_method_get_opener 2979 EXIST::FUNCTION: +ENGINE_set_ex_data 2980 EXIST::FUNCTION:ENGINE +OCSP_REQUEST_print 2981 EXIST::FUNCTION: +CBIGNUM_it 2982 EXIST:!EXPORT_VAR_AS_FUNCTION:VARIABLE: +CBIGNUM_it 2982 EXIST:EXPORT_VAR_AS_FUNCTION:FUNCTION: +KRB5_TICKET_new 2983 EXIST::FUNCTION: +KRB5_APREQ_new 2984 EXIST::FUNCTION: +EC_GROUP_get_curve_GFp 2985 EXIST::FUNCTION:EC +KRB5_ENCKEY_new 2986 EXIST::FUNCTION: +ASN1_template_d2i 2987 EXIST::FUNCTION: +_ossl_old_des_quad_cksum 2988 EXIST::FUNCTION:DES +OCSP_single_get0_status 2989 EXIST::FUNCTION: +BN_swap 2990 EXIST::FUNCTION: +POLICYINFO_it 2991 EXIST:!EXPORT_VAR_AS_FUNCTION:VARIABLE: +POLICYINFO_it 2991 EXIST:EXPORT_VAR_AS_FUNCTION:FUNCTION: +ENGINE_set_destroy_function 2992 EXIST::FUNCTION:ENGINE +asn1_enc_free 2993 EXIST::FUNCTION: +OCSP_RESPID_it 2994 EXIST:!EXPORT_VAR_AS_FUNCTION:VARIABLE: +OCSP_RESPID_it 2994 EXIST:EXPORT_VAR_AS_FUNCTION:FUNCTION: +EC_GROUP_new 2995 EXIST::FUNCTION:EC +EVP_aes_256_cbc 2996 EXIST::FUNCTION:AES +i2d_KRB5_PRINCNAME 2997 EXIST::FUNCTION: +_ossl_old_des_encrypt2 2998 EXIST::FUNCTION:DES +_ossl_old_des_encrypt3 2999 EXIST::FUNCTION:DES +PKCS8_PRIV_KEY_INFO_it 3000 EXIST:!EXPORT_VAR_AS_FUNCTION:VARIABLE: +PKCS8_PRIV_KEY_INFO_it 3000 EXIST:EXPORT_VAR_AS_FUNCTION:FUNCTION: +OCSP_REQINFO_it 3001 EXIST:!EXPORT_VAR_AS_FUNCTION:VARIABLE: +OCSP_REQINFO_it 3001 EXIST:EXPORT_VAR_AS_FUNCTION:FUNCTION: +PBEPARAM_it 3002 EXIST:!EXPORT_VAR_AS_FUNCTION:VARIABLE: +PBEPARAM_it 3002 EXIST:EXPORT_VAR_AS_FUNCTION:FUNCTION: +KRB5_AUTHENTBODY_new 3003 EXIST::FUNCTION: +X509_CRL_add0_revoked 3004 EXIST::FUNCTION: +EDIPARTYNAME_it 3005 EXIST:!EXPORT_VAR_AS_FUNCTION:VARIABLE: +EDIPARTYNAME_it 3005 EXIST:EXPORT_VAR_AS_FUNCTION:FUNCTION: +NETSCAPE_SPKI_it 3006 EXIST:!EXPORT_VAR_AS_FUNCTION:VARIABLE: +NETSCAPE_SPKI_it 3006 EXIST:EXPORT_VAR_AS_FUNCTION:FUNCTION: +UI_get0_test_string 3007 EXIST::FUNCTION: +ENGINE_get_cipher_engine 3008 EXIST::FUNCTION:ENGINE +ENGINE_register_all_ciphers 3009 EXIST::FUNCTION:ENGINE +EC_POINT_copy 3010 EXIST::FUNCTION:EC +BN_kronecker 3011 EXIST::FUNCTION: +_ossl_old_des_ede3_ofb64_encrypt 3012 EXIST:!VMS:FUNCTION:DES +_ossl_odes_ede3_ofb64_encrypt 3012 EXIST:VMS:FUNCTION:DES +UI_method_get_reader 3013 EXIST::FUNCTION: +OCSP_BASICRESP_get_ext_count 3014 EXIST::FUNCTION: +ASN1_ENUMERATED_it 3015 EXIST:!EXPORT_VAR_AS_FUNCTION:VARIABLE: +ASN1_ENUMERATED_it 3015 EXIST:EXPORT_VAR_AS_FUNCTION:FUNCTION: +UI_set_result 3016 EXIST::FUNCTION: +i2d_KRB5_TICKET 3017 EXIST::FUNCTION: +X509_print_ex_fp 3018 EXIST::FUNCTION:FP_API +EVP_CIPHER_CTX_set_padding 3019 EXIST::FUNCTION: +d2i_OCSP_RESPONSE 3020 EXIST::FUNCTION: +ASN1_UTCTIME_it 3021 EXIST:!EXPORT_VAR_AS_FUNCTION:VARIABLE: +ASN1_UTCTIME_it 3021 EXIST:EXPORT_VAR_AS_FUNCTION:FUNCTION: +_ossl_old_des_enc_write 3022 EXIST::FUNCTION:DES +OCSP_RESPONSE_new 3023 EXIST::FUNCTION: +AES_set_encrypt_key 3024 EXIST::FUNCTION:AES +OCSP_resp_count 3025 EXIST::FUNCTION: +KRB5_CHECKSUM_new 3026 EXIST::FUNCTION: +ENGINE_load_cswift 3027 EXIST::FUNCTION:ENGINE,STATIC_ENGINE +OCSP_onereq_get0_id 3028 EXIST::FUNCTION: +ENGINE_set_default_ciphers 3029 EXIST::FUNCTION:ENGINE +NOTICEREF_it 3030 EXIST:!EXPORT_VAR_AS_FUNCTION:VARIABLE: +NOTICEREF_it 3030 EXIST:EXPORT_VAR_AS_FUNCTION:FUNCTION: +X509V3_EXT_CRL_add_nconf 3031 EXIST::FUNCTION: +OCSP_REVOKEDINFO_it 3032 EXIST:!EXPORT_VAR_AS_FUNCTION:VARIABLE: +OCSP_REVOKEDINFO_it 3032 EXIST:EXPORT_VAR_AS_FUNCTION:FUNCTION: +AES_encrypt 3033 EXIST::FUNCTION:AES +OCSP_REQUEST_new 3034 EXIST::FUNCTION: +ASN1_ANY_it 3035 EXIST:!EXPORT_VAR_AS_FUNCTION:VARIABLE: +ASN1_ANY_it 3035 EXIST:EXPORT_VAR_AS_FUNCTION:FUNCTION: +CRYPTO_ex_data_new_class 3036 EXIST::FUNCTION: +_ossl_old_des_ncbc_encrypt 3037 EXIST::FUNCTION:DES +i2d_KRB5_TKTBODY 3038 EXIST::FUNCTION: +EC_POINT_clear_free 3039 EXIST::FUNCTION:EC +AES_decrypt 3040 EXIST::FUNCTION:AES +asn1_enc_init 3041 EXIST::FUNCTION: +UI_get_result_maxsize 3042 EXIST::FUNCTION: +OCSP_CERTID_new 3043 EXIST::FUNCTION: +ENGINE_unregister_RAND 3044 EXIST::FUNCTION:ENGINE +UI_method_get_closer 3045 EXIST::FUNCTION: +d2i_KRB5_ENCDATA 3046 EXIST::FUNCTION: +OCSP_request_onereq_count 3047 EXIST::FUNCTION: +OCSP_basic_verify 3048 EXIST::FUNCTION: +KRB5_AUTHENTBODY_free 3049 EXIST::FUNCTION: +ASN1_item_d2i 3050 EXIST::FUNCTION: +ASN1_primitive_free 3051 EXIST::FUNCTION: +i2d_EXTENDED_KEY_USAGE 3052 EXIST::FUNCTION: +i2d_OCSP_SIGNATURE 3053 EXIST::FUNCTION: +asn1_enc_save 3054 EXIST::FUNCTION: +ENGINE_load_nuron 3055 EXIST::FUNCTION:ENGINE,STATIC_ENGINE +_ossl_old_des_pcbc_encrypt 3056 EXIST::FUNCTION:DES +PKCS12_MAC_DATA_it 3057 EXIST:!EXPORT_VAR_AS_FUNCTION:VARIABLE: +PKCS12_MAC_DATA_it 3057 EXIST:EXPORT_VAR_AS_FUNCTION:FUNCTION: +OCSP_accept_responses_new 3058 EXIST::FUNCTION: +asn1_do_lock 3059 EXIST::FUNCTION: +PKCS7_ATTR_VERIFY_it 3060 EXIST:!EXPORT_VAR_AS_FUNCTION:VARIABLE: +PKCS7_ATTR_VERIFY_it 3060 EXIST:EXPORT_VAR_AS_FUNCTION:FUNCTION: +KRB5_APREQBODY_it 3061 EXIST:!EXPORT_VAR_AS_FUNCTION:VARIABLE: +KRB5_APREQBODY_it 3061 EXIST:EXPORT_VAR_AS_FUNCTION:FUNCTION: +i2d_OCSP_SINGLERESP 3062 EXIST::FUNCTION: +ASN1_item_ex_new 3063 EXIST::FUNCTION: +UI_add_verify_string 3064 EXIST::FUNCTION: +_ossl_old_des_set_key 3065 EXIST::FUNCTION:DES +KRB5_PRINCNAME_it 3066 EXIST:!EXPORT_VAR_AS_FUNCTION:VARIABLE: +KRB5_PRINCNAME_it 3066 EXIST:EXPORT_VAR_AS_FUNCTION:FUNCTION: +EVP_DecryptInit_ex 3067 EXIST::FUNCTION: +i2d_OCSP_CERTID 3068 EXIST::FUNCTION: +ASN1_item_d2i_bio 3069 EXIST::FUNCTION:BIO +EC_POINT_dbl 3070 EXIST::FUNCTION:EC +asn1_get_choice_selector 3071 EXIST::FUNCTION: +i2d_KRB5_CHECKSUM 3072 EXIST::FUNCTION: +ENGINE_set_table_flags 3073 EXIST::FUNCTION:ENGINE +AES_options 3074 EXIST::FUNCTION:AES +ENGINE_load_chil 3075 EXIST::FUNCTION:ENGINE,STATIC_ENGINE +OCSP_id_cmp 3076 EXIST::FUNCTION: +OCSP_BASICRESP_new 3077 EXIST::FUNCTION: +OCSP_REQUEST_get_ext_by_NID 3078 EXIST::FUNCTION: +KRB5_APREQ_it 3079 EXIST:!EXPORT_VAR_AS_FUNCTION:VARIABLE: +KRB5_APREQ_it 3079 EXIST:EXPORT_VAR_AS_FUNCTION:FUNCTION: +ENGINE_get_destroy_function 3080 EXIST::FUNCTION:ENGINE +CONF_set_nconf 3081 EXIST::FUNCTION: +ASN1_PRINTABLE_free 3082 EXIST::FUNCTION: +OCSP_BASICRESP_get_ext_by_NID 3083 EXIST::FUNCTION: +DIST_POINT_NAME_it 3084 EXIST:!EXPORT_VAR_AS_FUNCTION:VARIABLE: +DIST_POINT_NAME_it 3084 EXIST:EXPORT_VAR_AS_FUNCTION:FUNCTION: +X509V3_extensions_print 3085 EXIST::FUNCTION: +_ossl_old_des_cfb64_encrypt 3086 EXIST::FUNCTION:DES +X509_REVOKED_add1_ext_i2d 3087 EXIST::FUNCTION: +_ossl_old_des_ofb_encrypt 3088 EXIST::FUNCTION:DES +KRB5_TKTBODY_new 3089 EXIST::FUNCTION: +ASN1_OCTET_STRING_it 3090 EXIST:!EXPORT_VAR_AS_FUNCTION:VARIABLE: +ASN1_OCTET_STRING_it 3090 EXIST:EXPORT_VAR_AS_FUNCTION:FUNCTION: +ERR_load_UI_strings 3091 EXIST::FUNCTION: +i2d_KRB5_ENCKEY 3092 EXIST::FUNCTION: +ASN1_template_new 3093 EXIST::FUNCTION: +OCSP_SIGNATURE_free 3094 EXIST::FUNCTION: +ASN1_item_i2d_fp 3095 EXIST::FUNCTION:FP_API +KRB5_PRINCNAME_free 3096 EXIST::FUNCTION: +PKCS7_RECIP_INFO_it 3097 EXIST:!EXPORT_VAR_AS_FUNCTION:VARIABLE: +PKCS7_RECIP_INFO_it 3097 EXIST:EXPORT_VAR_AS_FUNCTION:FUNCTION: +EXTENDED_KEY_USAGE_it 3098 EXIST:!EXPORT_VAR_AS_FUNCTION:VARIABLE: +EXTENDED_KEY_USAGE_it 3098 EXIST:EXPORT_VAR_AS_FUNCTION:FUNCTION: +EC_GFp_simple_method 3099 EXIST::FUNCTION:EC +EC_GROUP_precompute_mult 3100 EXIST::FUNCTION:EC +OCSP_request_onereq_get0 3101 EXIST::FUNCTION: +UI_method_set_writer 3102 EXIST::FUNCTION: +KRB5_AUTHENT_new 3103 EXIST::FUNCTION: +X509_CRL_INFO_it 3104 EXIST:!EXPORT_VAR_AS_FUNCTION:VARIABLE: +X509_CRL_INFO_it 3104 EXIST:EXPORT_VAR_AS_FUNCTION:FUNCTION: +DSO_set_name_converter 3105 EXIST::FUNCTION: +AES_set_decrypt_key 3106 EXIST::FUNCTION:AES +PKCS7_DIGEST_it 3107 EXIST:!EXPORT_VAR_AS_FUNCTION:VARIABLE: +PKCS7_DIGEST_it 3107 EXIST:EXPORT_VAR_AS_FUNCTION:FUNCTION: +PKCS12_x5092certbag 3108 EXIST::FUNCTION: +EVP_DigestInit_ex 3109 EXIST::FUNCTION: +i2a_ACCESS_DESCRIPTION 3110 EXIST::FUNCTION: +OCSP_RESPONSE_it 3111 EXIST:!EXPORT_VAR_AS_FUNCTION:VARIABLE: +OCSP_RESPONSE_it 3111 EXIST:EXPORT_VAR_AS_FUNCTION:FUNCTION: +PKCS7_ENC_CONTENT_it 3112 EXIST:!EXPORT_VAR_AS_FUNCTION:VARIABLE: +PKCS7_ENC_CONTENT_it 3112 EXIST:EXPORT_VAR_AS_FUNCTION:FUNCTION: +OCSP_request_add0_id 3113 EXIST::FUNCTION: +EC_POINT_make_affine 3114 EXIST::FUNCTION:EC +DSO_get_filename 3115 EXIST::FUNCTION: +OCSP_CERTSTATUS_it 3116 EXIST:!EXPORT_VAR_AS_FUNCTION:VARIABLE: +OCSP_CERTSTATUS_it 3116 EXIST:EXPORT_VAR_AS_FUNCTION:FUNCTION: +OCSP_request_add1_cert 3117 EXIST::FUNCTION: +UI_get0_output_string 3118 EXIST::FUNCTION: +UI_dup_verify_string 3119 EXIST::FUNCTION: +BN_mod_lshift 3120 EXIST::FUNCTION: +KRB5_AUTHDATA_it 3121 EXIST:!EXPORT_VAR_AS_FUNCTION:VARIABLE: +KRB5_AUTHDATA_it 3121 EXIST:EXPORT_VAR_AS_FUNCTION:FUNCTION: +asn1_set_choice_selector 3122 EXIST::FUNCTION: +OCSP_basic_add1_status 3123 EXIST::FUNCTION: +OCSP_RESPID_free 3124 EXIST::FUNCTION: +asn1_get_field_ptr 3125 EXIST::FUNCTION: +UI_add_input_string 3126 EXIST::FUNCTION: +OCSP_CRLID_it 3127 EXIST:!EXPORT_VAR_AS_FUNCTION:VARIABLE: +OCSP_CRLID_it 3127 EXIST:EXPORT_VAR_AS_FUNCTION:FUNCTION: +i2d_KRB5_AUTHENTBODY 3128 EXIST::FUNCTION: +OCSP_REQUEST_get_ext_count 3129 EXIST::FUNCTION: +ENGINE_load_atalla 3130 EXIST::FUNCTION:ENGINE,STATIC_ENGINE +X509_NAME_it 3131 EXIST:!EXPORT_VAR_AS_FUNCTION:VARIABLE: +X509_NAME_it 3131 EXIST:EXPORT_VAR_AS_FUNCTION:FUNCTION: +USERNOTICE_it 3132 EXIST:!EXPORT_VAR_AS_FUNCTION:VARIABLE: +USERNOTICE_it 3132 EXIST:EXPORT_VAR_AS_FUNCTION:FUNCTION: +OCSP_REQINFO_new 3133 EXIST::FUNCTION: +OCSP_BASICRESP_get_ext 3134 EXIST::FUNCTION: +CRYPTO_get_ex_data_implementation 3135 EXIST:!VMS:FUNCTION: +CRYPTO_get_ex_data_impl 3135 EXIST:VMS:FUNCTION: +ASN1_item_pack 3136 EXIST::FUNCTION: +i2d_KRB5_ENCDATA 3137 EXIST::FUNCTION: +X509_PURPOSE_set 3138 EXIST::FUNCTION: +X509_REQ_INFO_it 3139 EXIST:!EXPORT_VAR_AS_FUNCTION:VARIABLE: +X509_REQ_INFO_it 3139 EXIST:EXPORT_VAR_AS_FUNCTION:FUNCTION: +UI_method_set_opener 3140 EXIST::FUNCTION: +ASN1_item_ex_free 3141 EXIST::FUNCTION: +ASN1_BOOLEAN_it 3142 EXIST:!EXPORT_VAR_AS_FUNCTION:VARIABLE: +ASN1_BOOLEAN_it 3142 EXIST:EXPORT_VAR_AS_FUNCTION:FUNCTION: +ENGINE_get_table_flags 3143 EXIST::FUNCTION:ENGINE +UI_create_method 3144 EXIST::FUNCTION: +OCSP_ONEREQ_add1_ext_i2d 3145 EXIST::FUNCTION: +_shadow_DES_check_key 3146 EXIST:!EXPORT_VAR_AS_FUNCTION:VARIABLE:DES +_shadow_DES_check_key 3146 EXIST:EXPORT_VAR_AS_FUNCTION:FUNCTION:DES +d2i_OCSP_REQINFO 3147 EXIST::FUNCTION: +UI_add_info_string 3148 EXIST::FUNCTION: +UI_get_result_minsize 3149 EXIST::FUNCTION: +ASN1_NULL_it 3150 EXIST:!EXPORT_VAR_AS_FUNCTION:VARIABLE: +ASN1_NULL_it 3150 EXIST:EXPORT_VAR_AS_FUNCTION:FUNCTION: +BN_mod_lshift1 3151 EXIST::FUNCTION: +d2i_OCSP_ONEREQ 3152 EXIST::FUNCTION: +OCSP_ONEREQ_new 3153 EXIST::FUNCTION: +KRB5_TICKET_it 3154 EXIST:!EXPORT_VAR_AS_FUNCTION:VARIABLE: +KRB5_TICKET_it 3154 EXIST:EXPORT_VAR_AS_FUNCTION:FUNCTION: +EVP_aes_192_cbc 3155 EXIST::FUNCTION:AES +KRB5_TICKET_free 3156 EXIST::FUNCTION: +UI_new 3157 EXIST::FUNCTION: +OCSP_response_create 3158 EXIST::FUNCTION: +_ossl_old_des_xcbc_encrypt 3159 EXIST::FUNCTION:DES +PKCS7_it 3160 EXIST:!EXPORT_VAR_AS_FUNCTION:VARIABLE: +PKCS7_it 3160 EXIST:EXPORT_VAR_AS_FUNCTION:FUNCTION: +OCSP_REQUEST_get_ext_by_critical 3161 EXIST:!VMS:FUNCTION: +OCSP_REQUEST_get_ext_by_crit 3161 EXIST:VMS:FUNCTION: +ENGINE_set_flags 3162 EXIST::FUNCTION:ENGINE +_ossl_old_des_ecb_encrypt 3163 EXIST::FUNCTION:DES +OCSP_response_get1_basic 3164 EXIST::FUNCTION: +EVP_Digest 3165 EXIST::FUNCTION: +OCSP_ONEREQ_delete_ext 3166 EXIST::FUNCTION: +ASN1_TBOOLEAN_it 3167 EXIST:!EXPORT_VAR_AS_FUNCTION:VARIABLE: +ASN1_TBOOLEAN_it 3167 EXIST:EXPORT_VAR_AS_FUNCTION:FUNCTION: +ASN1_item_new 3168 EXIST::FUNCTION: +ASN1_TIME_to_generalizedtime 3169 EXIST::FUNCTION: +BIGNUM_it 3170 EXIST:!EXPORT_VAR_AS_FUNCTION:VARIABLE: +BIGNUM_it 3170 EXIST:EXPORT_VAR_AS_FUNCTION:FUNCTION: +AES_cbc_encrypt 3171 EXIST::FUNCTION:AES +ENGINE_get_load_privkey_function 3172 EXIST:!VMS:FUNCTION:ENGINE +ENGINE_get_load_privkey_fn 3172 EXIST:VMS:FUNCTION:ENGINE +OCSP_RESPONSE_free 3173 EXIST::FUNCTION: +UI_method_set_reader 3174 EXIST::FUNCTION: +i2d_ASN1_T61STRING 3175 EXIST::FUNCTION: +EC_POINT_set_to_infinity 3176 EXIST::FUNCTION:EC +ERR_load_OCSP_strings 3177 EXIST::FUNCTION: +EC_POINT_point2oct 3178 EXIST::FUNCTION:EC +KRB5_APREQ_free 3179 EXIST::FUNCTION: +ASN1_OBJECT_it 3180 EXIST:!EXPORT_VAR_AS_FUNCTION:VARIABLE: +ASN1_OBJECT_it 3180 EXIST:EXPORT_VAR_AS_FUNCTION:FUNCTION: +OCSP_crlID_new 3181 EXIST:!OS2,!VMS:FUNCTION: +OCSP_crlID2_new 3181 EXIST:OS2,VMS:FUNCTION: +CONF_modules_load_file 3182 EXIST::FUNCTION: +CONF_imodule_set_usr_data 3183 EXIST::FUNCTION: +ENGINE_set_default_string 3184 EXIST::FUNCTION:ENGINE +CONF_module_get_usr_data 3185 EXIST::FUNCTION: +ASN1_add_oid_module 3186 EXIST::FUNCTION: +CONF_modules_finish 3187 EXIST::FUNCTION: +OPENSSL_config 3188 EXIST::FUNCTION: +CONF_modules_unload 3189 EXIST::FUNCTION: +CONF_imodule_get_value 3190 EXIST::FUNCTION: +CONF_module_set_usr_data 3191 EXIST::FUNCTION: +CONF_parse_list 3192 EXIST::FUNCTION: +CONF_module_add 3193 EXIST::FUNCTION: +CONF_get1_default_config_file 3194 EXIST::FUNCTION: +CONF_imodule_get_flags 3195 EXIST::FUNCTION: +CONF_imodule_get_module 3196 EXIST::FUNCTION: +CONF_modules_load 3197 EXIST::FUNCTION: +CONF_imodule_get_name 3198 EXIST::FUNCTION: +ERR_peek_top_error 3199 NOEXIST::FUNCTION: +CONF_imodule_get_usr_data 3200 EXIST::FUNCTION: +CONF_imodule_set_flags 3201 EXIST::FUNCTION: +ENGINE_add_conf_module 3202 EXIST::FUNCTION:ENGINE +ERR_peek_last_error_line 3203 EXIST::FUNCTION: +ERR_peek_last_error_line_data 3204 EXIST::FUNCTION: +ERR_peek_last_error 3205 EXIST::FUNCTION: +DES_read_2passwords 3206 EXIST::FUNCTION:DES +DES_read_password 3207 EXIST::FUNCTION:DES +UI_UTIL_read_pw 3208 EXIST::FUNCTION: +UI_UTIL_read_pw_string 3209 EXIST::FUNCTION: +ENGINE_load_aep 3210 EXIST::FUNCTION:ENGINE,STATIC_ENGINE +ENGINE_load_sureware 3211 EXIST::FUNCTION:ENGINE,STATIC_ENGINE +OPENSSL_add_all_algorithms_noconf 3212 EXIST:!VMS:FUNCTION: +OPENSSL_add_all_algo_noconf 3212 EXIST:VMS:FUNCTION: +OPENSSL_add_all_algorithms_conf 3213 EXIST:!VMS:FUNCTION: +OPENSSL_add_all_algo_conf 3213 EXIST:VMS:FUNCTION: +OPENSSL_load_builtin_modules 3214 EXIST::FUNCTION: +AES_ofb128_encrypt 3215 EXIST::FUNCTION:AES +AES_ctr128_encrypt 3216 EXIST::FUNCTION:AES +AES_cfb128_encrypt 3217 EXIST::FUNCTION:AES +ENGINE_load_4758cca 3218 EXIST::FUNCTION:ENGINE,STATIC_ENGINE +_ossl_096_des_random_seed 3219 EXIST::FUNCTION:DES +EVP_aes_256_ofb 3220 EXIST::FUNCTION:AES +EVP_aes_192_ofb 3221 EXIST::FUNCTION:AES +EVP_aes_128_cfb128 3222 EXIST::FUNCTION:AES +EVP_aes_256_cfb128 3223 EXIST::FUNCTION:AES +EVP_aes_128_ofb 3224 EXIST::FUNCTION:AES +EVP_aes_192_cfb128 3225 EXIST::FUNCTION:AES +CONF_modules_free 3226 EXIST::FUNCTION: +NCONF_default 3227 EXIST::FUNCTION: +OPENSSL_no_config 3228 EXIST::FUNCTION: +NCONF_WIN32 3229 EXIST::FUNCTION: +ASN1_UNIVERSALSTRING_new 3230 EXIST::FUNCTION: +EVP_des_ede_ecb 3231 EXIST::FUNCTION:DES +i2d_ASN1_UNIVERSALSTRING 3232 EXIST::FUNCTION: +ASN1_UNIVERSALSTRING_free 3233 EXIST::FUNCTION: +ASN1_UNIVERSALSTRING_it 3234 EXIST:!EXPORT_VAR_AS_FUNCTION:VARIABLE: +ASN1_UNIVERSALSTRING_it 3234 EXIST:EXPORT_VAR_AS_FUNCTION:FUNCTION: +d2i_ASN1_UNIVERSALSTRING 3235 EXIST::FUNCTION: +EVP_des_ede3_ecb 3236 EXIST::FUNCTION:DES +X509_REQ_print_ex 3237 EXIST::FUNCTION:BIO +ENGINE_up_ref 3238 EXIST::FUNCTION:ENGINE +BUF_MEM_grow_clean 3239 EXIST::FUNCTION: +CRYPTO_realloc_clean 3240 EXIST::FUNCTION: +BUF_strlcat 3241 EXIST::FUNCTION: +BIO_indent 3242 EXIST::FUNCTION: +BUF_strlcpy 3243 EXIST::FUNCTION: +OpenSSLDie 3244 EXIST::FUNCTION: +OPENSSL_cleanse 3245 EXIST::FUNCTION: +ENGINE_setup_bsd_cryptodev 3246 EXIST:__FreeBSD__:FUNCTION:ENGINE +ERR_release_err_state_table 3247 EXIST::FUNCTION:LHASH +EVP_aes_128_cfb8 3248 EXIST::FUNCTION:AES +FIPS_corrupt_rsa 3249 NOEXIST::FUNCTION: +FIPS_selftest_des 3250 NOEXIST::FUNCTION: +EVP_aes_128_cfb1 3251 EXIST::FUNCTION:AES +EVP_aes_192_cfb8 3252 EXIST::FUNCTION:AES +FIPS_mode_set 3253 NOEXIST::FUNCTION: +FIPS_selftest_dsa 3254 NOEXIST::FUNCTION: +EVP_aes_256_cfb8 3255 EXIST::FUNCTION:AES +FIPS_allow_md5 3256 NOEXIST::FUNCTION: +DES_ede3_cfb_encrypt 3257 EXIST::FUNCTION:DES +EVP_des_ede3_cfb8 3258 EXIST::FUNCTION:DES +FIPS_rand_seeded 3259 NOEXIST::FUNCTION: +AES_cfbr_encrypt_block 3260 NOEXIST::FUNCTION: +AES_cfb8_encrypt 3261 EXIST::FUNCTION:AES +FIPS_rand_seed 3262 NOEXIST::FUNCTION: +FIPS_corrupt_des 3263 NOEXIST::FUNCTION: +EVP_aes_192_cfb1 3264 EXIST::FUNCTION:AES +FIPS_selftest_aes 3265 NOEXIST::FUNCTION: +FIPS_set_prng_key 3266 NOEXIST::FUNCTION: +EVP_des_cfb8 3267 EXIST::FUNCTION:DES +FIPS_corrupt_dsa 3268 NOEXIST::FUNCTION: +FIPS_test_mode 3269 NOEXIST::FUNCTION: +FIPS_rand_method 3270 NOEXIST::FUNCTION: +EVP_aes_256_cfb1 3271 EXIST::FUNCTION:AES +ERR_load_FIPS_strings 3272 NOEXIST::FUNCTION: +FIPS_corrupt_aes 3273 NOEXIST::FUNCTION: +FIPS_selftest_sha1 3274 NOEXIST::FUNCTION: +FIPS_selftest_rsa 3275 NOEXIST::FUNCTION: +FIPS_corrupt_sha1 3276 NOEXIST::FUNCTION: +EVP_des_cfb1 3277 EXIST::FUNCTION:DES +FIPS_dsa_check 3278 NOEXIST::FUNCTION: +AES_cfb1_encrypt 3279 EXIST::FUNCTION:AES +EVP_des_ede3_cfb1 3280 EXIST::FUNCTION:DES +FIPS_rand_check 3281 NOEXIST::FUNCTION: +FIPS_md5_allowed 3282 NOEXIST::FUNCTION: +FIPS_mode 3283 NOEXIST::FUNCTION: +FIPS_selftest_failed 3284 NOEXIST::FUNCTION: +sk_is_sorted 3285 EXIST::FUNCTION: +X509_check_ca 3286 EXIST::FUNCTION: +private_idea_set_encrypt_key 3287 NOEXIST::FUNCTION: +HMAC_CTX_set_flags 3288 EXIST::FUNCTION:HMAC +private_SHA_Init 3289 NOEXIST::FUNCTION: +private_CAST_set_key 3290 NOEXIST::FUNCTION: +private_RIPEMD160_Init 3291 NOEXIST::FUNCTION: +private_RC5_32_set_key 3292 NOEXIST::FUNCTION: +private_MD5_Init 3293 NOEXIST::FUNCTION: +private_RC4_set_key 3294 NOEXIST::FUNCTION: +private_MDC2_Init 3295 NOEXIST::FUNCTION: +private_RC2_set_key 3296 NOEXIST::FUNCTION: +private_MD4_Init 3297 NOEXIST::FUNCTION: +private_BF_set_key 3298 NOEXIST::FUNCTION: +private_MD2_Init 3299 NOEXIST::FUNCTION: +d2i_PROXY_CERT_INFO_EXTENSION 3300 EXIST::FUNCTION: +PROXY_POLICY_it 3301 EXIST:!EXPORT_VAR_AS_FUNCTION:VARIABLE: +PROXY_POLICY_it 3301 EXIST:EXPORT_VAR_AS_FUNCTION:FUNCTION: +i2d_PROXY_POLICY 3302 EXIST::FUNCTION: +i2d_PROXY_CERT_INFO_EXTENSION 3303 EXIST::FUNCTION: +d2i_PROXY_POLICY 3304 EXIST::FUNCTION: +PROXY_CERT_INFO_EXTENSION_new 3305 EXIST::FUNCTION: +PROXY_CERT_INFO_EXTENSION_free 3306 EXIST::FUNCTION: +PROXY_CERT_INFO_EXTENSION_it 3307 EXIST:!EXPORT_VAR_AS_FUNCTION:VARIABLE: +PROXY_CERT_INFO_EXTENSION_it 3307 EXIST:EXPORT_VAR_AS_FUNCTION:FUNCTION: +PROXY_POLICY_free 3308 EXIST::FUNCTION: +PROXY_POLICY_new 3309 EXIST::FUNCTION: +BN_MONT_CTX_set_locked 3310 EXIST::FUNCTION: +FIPS_selftest_rng 3311 NOEXIST::FUNCTION: +EVP_sha384 3312 EXIST:!VMSVAX:FUNCTION:SHA,SHA512 +EVP_sha512 3313 EXIST:!VMSVAX:FUNCTION:SHA,SHA512 +EVP_sha224 3314 EXIST::FUNCTION:SHA,SHA256 +EVP_sha256 3315 EXIST::FUNCTION:SHA,SHA256 +FIPS_selftest_hmac 3316 NOEXIST::FUNCTION: +FIPS_corrupt_rng 3317 NOEXIST::FUNCTION: +BN_mod_exp_mont_consttime 3318 EXIST::FUNCTION: +RSA_X931_hash_id 3319 EXIST::FUNCTION:RSA +RSA_padding_check_X931 3320 EXIST::FUNCTION:RSA +RSA_verify_PKCS1_PSS 3321 EXIST::FUNCTION:RSA +RSA_padding_add_X931 3322 EXIST::FUNCTION:RSA +RSA_padding_add_PKCS1_PSS 3323 EXIST::FUNCTION:RSA +PKCS1_MGF1 3324 EXIST::FUNCTION:RSA +BN_X931_generate_Xpq 3325 NOEXIST::FUNCTION: +RSA_X931_generate_key 3326 NOEXIST::FUNCTION: +BN_X931_derive_prime 3327 NOEXIST::FUNCTION: +BN_X931_generate_prime 3328 NOEXIST::FUNCTION: +RSA_X931_derive 3329 NOEXIST::FUNCTION: +BIO_new_dgram 3330 EXIST::FUNCTION: +BN_get0_nist_prime_384 3331 EXIST::FUNCTION: +ERR_set_mark 3332 EXIST::FUNCTION: +X509_STORE_CTX_set0_crls 3333 EXIST::FUNCTION: +ENGINE_set_STORE 3334 EXIST::FUNCTION:ENGINE +ENGINE_register_ECDSA 3335 EXIST::FUNCTION:ENGINE +STORE_meth_set_list_start_fn 3336 NOEXIST::FUNCTION: +STORE_method_set_list_start_function 3336 NOEXIST::FUNCTION: +BN_BLINDING_invert_ex 3337 EXIST::FUNCTION: +NAME_CONSTRAINTS_free 3338 EXIST::FUNCTION: +STORE_ATTR_INFO_set_number 3339 NOEXIST::FUNCTION: +BN_BLINDING_get_thread_id 3340 EXIST::FUNCTION:DEPRECATED +X509_STORE_CTX_set0_param 3341 EXIST::FUNCTION: +POLICY_MAPPING_it 3342 EXIST:!EXPORT_VAR_AS_FUNCTION:VARIABLE: +POLICY_MAPPING_it 3342 EXIST:EXPORT_VAR_AS_FUNCTION:FUNCTION: +STORE_parse_attrs_start 3343 NOEXIST::FUNCTION: +POLICY_CONSTRAINTS_free 3344 EXIST::FUNCTION: +EVP_PKEY_add1_attr_by_NID 3345 EXIST::FUNCTION: +BN_nist_mod_192 3346 EXIST::FUNCTION: +EC_GROUP_get_trinomial_basis 3347 EXIST::FUNCTION:EC +STORE_set_method 3348 NOEXIST::FUNCTION: +GENERAL_SUBTREE_free 3349 EXIST::FUNCTION: +NAME_CONSTRAINTS_it 3350 EXIST:!EXPORT_VAR_AS_FUNCTION:VARIABLE: +NAME_CONSTRAINTS_it 3350 EXIST:EXPORT_VAR_AS_FUNCTION:FUNCTION: +ECDH_get_default_method 3351 EXIST::FUNCTION:ECDH +PKCS12_add_safe 3352 EXIST::FUNCTION: +EC_KEY_new_by_curve_name 3353 EXIST::FUNCTION:EC +STORE_meth_get_update_store_fn 3354 NOEXIST::FUNCTION: +STORE_method_get_update_store_function 3354 NOEXIST::FUNCTION: +ENGINE_register_ECDH 3355 EXIST::FUNCTION:ENGINE +SHA512_Update 3356 EXIST:!VMSVAX:FUNCTION:SHA,SHA512 +i2d_ECPrivateKey 3357 EXIST::FUNCTION:EC +BN_get0_nist_prime_192 3358 EXIST::FUNCTION: +STORE_modify_certificate 3359 NOEXIST::FUNCTION: +EC_POINT_set_affine_coordinates_GF2m 3360 EXIST:!VMS:FUNCTION:EC +EC_POINT_set_affine_coords_GF2m 3360 EXIST:VMS:FUNCTION:EC +BN_GF2m_mod_exp_arr 3361 EXIST::FUNCTION: +STORE_ATTR_INFO_modify_number 3362 NOEXIST::FUNCTION: +X509_keyid_get0 3363 EXIST::FUNCTION: +ENGINE_load_gmp 3364 EXIST::FUNCTION:ENGINE,GMP,STATIC_ENGINE +pitem_new 3365 EXIST::FUNCTION: +BN_GF2m_mod_mul_arr 3366 EXIST::FUNCTION: +STORE_list_public_key_endp 3367 NOEXIST::FUNCTION: +o2i_ECPublicKey 3368 EXIST::FUNCTION:EC +EC_KEY_copy 3369 EXIST::FUNCTION:EC +BIO_dump_fp 3370 EXIST::FUNCTION:FP_API +X509_policy_node_get0_parent 3371 EXIST::FUNCTION: +EC_GROUP_check_discriminant 3372 EXIST::FUNCTION:EC +i2o_ECPublicKey 3373 EXIST::FUNCTION:EC +EC_KEY_precompute_mult 3374 EXIST::FUNCTION:EC +a2i_IPADDRESS 3375 EXIST::FUNCTION: +STORE_meth_set_initialise_fn 3376 NOEXIST::FUNCTION: +STORE_method_set_initialise_function 3376 NOEXIST::FUNCTION: +X509_STORE_CTX_set_depth 3377 EXIST::FUNCTION: +X509_VERIFY_PARAM_inherit 3378 EXIST::FUNCTION: +EC_POINT_point2bn 3379 EXIST::FUNCTION:EC +STORE_ATTR_INFO_set_dn 3380 NOEXIST::FUNCTION: +X509_policy_tree_get0_policies 3381 EXIST::FUNCTION: +EC_GROUP_new_curve_GF2m 3382 EXIST::FUNCTION:EC +STORE_destroy_method 3383 NOEXIST::FUNCTION: +ENGINE_unregister_STORE 3384 EXIST::FUNCTION:ENGINE +EVP_PKEY_get1_EC_KEY 3385 EXIST::FUNCTION:EC +STORE_ATTR_INFO_get0_number 3386 NOEXIST::FUNCTION: +ENGINE_get_default_ECDH 3387 EXIST::FUNCTION:ENGINE +EC_KEY_get_conv_form 3388 EXIST::FUNCTION:EC +ASN1_OCTET_STRING_NDEF_it 3389 EXIST:!EXPORT_VAR_AS_FUNCTION:VARIABLE: +ASN1_OCTET_STRING_NDEF_it 3389 EXIST:EXPORT_VAR_AS_FUNCTION:FUNCTION: +STORE_delete_public_key 3390 NOEXIST::FUNCTION: +STORE_get_public_key 3391 NOEXIST::FUNCTION: +STORE_modify_arbitrary 3392 NOEXIST::FUNCTION: +ENGINE_get_static_state 3393 EXIST::FUNCTION:ENGINE +pqueue_iterator 3394 EXIST::FUNCTION: +ECDSA_SIG_new 3395 EXIST::FUNCTION:ECDSA +OPENSSL_DIR_end 3396 EXIST::FUNCTION: +BN_GF2m_mod_sqr 3397 EXIST::FUNCTION: +EC_POINT_bn2point 3398 EXIST::FUNCTION:EC +X509_VERIFY_PARAM_set_depth 3399 EXIST::FUNCTION: +EC_KEY_set_asn1_flag 3400 EXIST::FUNCTION:EC +STORE_get_method 3401 NOEXIST::FUNCTION: +EC_KEY_get_key_method_data 3402 EXIST::FUNCTION:EC +ECDSA_sign_ex 3403 EXIST::FUNCTION:ECDSA +STORE_parse_attrs_end 3404 NOEXIST::FUNCTION: +EC_GROUP_get_point_conversion_form 3405 EXIST:!VMS:FUNCTION:EC +EC_GROUP_get_point_conv_form 3405 EXIST:VMS:FUNCTION:EC +STORE_method_set_store_function 3406 NOEXIST::FUNCTION: +STORE_ATTR_INFO_in 3407 NOEXIST::FUNCTION: +PEM_read_bio_ECPKParameters 3408 EXIST::FUNCTION:EC +EC_GROUP_get_pentanomial_basis 3409 EXIST::FUNCTION:EC +EVP_PKEY_add1_attr_by_txt 3410 EXIST::FUNCTION: +BN_BLINDING_set_flags 3411 EXIST::FUNCTION: +X509_VERIFY_PARAM_set1_policies 3412 EXIST::FUNCTION: +X509_VERIFY_PARAM_set1_name 3413 EXIST::FUNCTION: +X509_VERIFY_PARAM_set_purpose 3414 EXIST::FUNCTION: +STORE_get_number 3415 NOEXIST::FUNCTION: +ECDSA_sign_setup 3416 EXIST::FUNCTION:ECDSA +BN_GF2m_mod_solve_quad_arr 3417 EXIST::FUNCTION: +EC_KEY_up_ref 3418 EXIST::FUNCTION:EC +POLICY_MAPPING_free 3419 EXIST::FUNCTION: +BN_GF2m_mod_div 3420 EXIST::FUNCTION: +X509_VERIFY_PARAM_set_flags 3421 EXIST::FUNCTION: +EC_KEY_free 3422 EXIST::FUNCTION:EC +STORE_meth_set_list_next_fn 3423 NOEXIST::FUNCTION: +STORE_method_set_list_next_function 3423 NOEXIST::FUNCTION: +PEM_write_bio_ECPrivateKey 3424 EXIST::FUNCTION:EC +d2i_EC_PUBKEY 3425 EXIST::FUNCTION:EC +STORE_meth_get_generate_fn 3426 NOEXIST::FUNCTION: +STORE_method_get_generate_function 3426 NOEXIST::FUNCTION: +STORE_meth_set_list_end_fn 3427 NOEXIST::FUNCTION: +STORE_method_set_list_end_function 3427 NOEXIST::FUNCTION: +pqueue_print 3428 EXIST::FUNCTION: +EC_GROUP_have_precompute_mult 3429 EXIST::FUNCTION:EC +EC_KEY_print_fp 3430 EXIST::FUNCTION:EC,FP_API +BN_GF2m_mod_arr 3431 EXIST::FUNCTION: +PEM_write_bio_X509_CERT_PAIR 3432 EXIST::FUNCTION: +EVP_PKEY_cmp 3433 EXIST::FUNCTION: +X509_policy_level_node_count 3434 EXIST::FUNCTION: +STORE_new_engine 3435 NOEXIST::FUNCTION: +STORE_list_public_key_start 3436 NOEXIST::FUNCTION: +X509_VERIFY_PARAM_new 3437 EXIST::FUNCTION: +ECDH_get_ex_data 3438 EXIST::FUNCTION:ECDH +EVP_PKEY_get_attr 3439 EXIST::FUNCTION: +ECDSA_do_sign 3440 EXIST::FUNCTION:ECDSA +ENGINE_unregister_ECDH 3441 EXIST::FUNCTION:ENGINE +ECDH_OpenSSL 3442 EXIST::FUNCTION:ECDH +EC_KEY_set_conv_form 3443 EXIST::FUNCTION:EC +EC_POINT_dup 3444 EXIST::FUNCTION:EC +GENERAL_SUBTREE_new 3445 EXIST::FUNCTION: +STORE_list_crl_endp 3446 NOEXIST::FUNCTION: +EC_get_builtin_curves 3447 EXIST::FUNCTION:EC +X509_policy_node_get0_qualifiers 3448 EXIST:!VMS:FUNCTION: +X509_pcy_node_get0_qualifiers 3448 EXIST:VMS:FUNCTION: +STORE_list_crl_end 3449 NOEXIST::FUNCTION: +EVP_PKEY_set1_EC_KEY 3450 EXIST::FUNCTION:EC +BN_GF2m_mod_sqrt_arr 3451 EXIST::FUNCTION: +i2d_ECPrivateKey_bio 3452 EXIST::FUNCTION:BIO,EC +ECPKParameters_print_fp 3453 EXIST::FUNCTION:EC,FP_API +pqueue_find 3454 EXIST::FUNCTION: +ECDSA_SIG_free 3455 EXIST::FUNCTION:ECDSA +PEM_write_bio_ECPKParameters 3456 EXIST::FUNCTION:EC +STORE_method_set_ctrl_function 3457 NOEXIST::FUNCTION: +STORE_list_public_key_end 3458 NOEXIST::FUNCTION: +EC_KEY_set_private_key 3459 EXIST::FUNCTION:EC +pqueue_peek 3460 EXIST::FUNCTION: +STORE_get_arbitrary 3461 NOEXIST::FUNCTION: +STORE_store_crl 3462 NOEXIST::FUNCTION: +X509_policy_node_get0_policy 3463 EXIST::FUNCTION: +PKCS12_add_safes 3464 EXIST::FUNCTION: +BN_BLINDING_convert_ex 3465 EXIST::FUNCTION: +X509_policy_tree_free 3466 EXIST::FUNCTION: +OPENSSL_ia32cap_loc 3467 EXIST::FUNCTION: +BN_GF2m_poly2arr 3468 EXIST::FUNCTION: +STORE_ctrl 3469 NOEXIST::FUNCTION: +STORE_ATTR_INFO_compare 3470 NOEXIST::FUNCTION: +BN_get0_nist_prime_224 3471 EXIST::FUNCTION: +i2d_ECParameters 3472 EXIST::FUNCTION:EC +i2d_ECPKParameters 3473 EXIST::FUNCTION:EC +BN_GENCB_call 3474 EXIST::FUNCTION: +d2i_ECPKParameters 3475 EXIST::FUNCTION:EC +STORE_meth_set_generate_fn 3476 NOEXIST::FUNCTION: +STORE_method_set_generate_function 3476 NOEXIST::FUNCTION: +ENGINE_set_ECDH 3477 EXIST::FUNCTION:ENGINE +NAME_CONSTRAINTS_new 3478 EXIST::FUNCTION: +SHA256_Init 3479 EXIST::FUNCTION:SHA,SHA256 +EC_KEY_get0_public_key 3480 EXIST::FUNCTION:EC +PEM_write_bio_EC_PUBKEY 3481 EXIST::FUNCTION:EC +STORE_ATTR_INFO_set_cstr 3482 NOEXIST::FUNCTION: +STORE_list_crl_next 3483 NOEXIST::FUNCTION: +STORE_ATTR_INFO_in_range 3484 NOEXIST::FUNCTION: +ECParameters_print 3485 EXIST::FUNCTION:BIO,EC +STORE_meth_set_delete_fn 3486 NOEXIST::FUNCTION: +STORE_method_set_delete_function 3486 NOEXIST::FUNCTION: +STORE_list_certificate_next 3487 NOEXIST::FUNCTION: +ASN1_generate_nconf 3488 EXIST::FUNCTION: +BUF_memdup 3489 EXIST::FUNCTION: +BN_GF2m_mod_mul 3490 EXIST::FUNCTION: +STORE_meth_get_list_next_fn 3491 NOEXIST::FUNCTION: +STORE_method_get_list_next_function 3491 NOEXIST::FUNCTION: +STORE_ATTR_INFO_get0_dn 3492 NOEXIST::FUNCTION: +STORE_list_private_key_next 3493 NOEXIST::FUNCTION: +EC_GROUP_set_seed 3494 EXIST::FUNCTION:EC +X509_VERIFY_PARAM_set_trust 3495 EXIST::FUNCTION: +STORE_ATTR_INFO_free 3496 NOEXIST::FUNCTION: +STORE_get_private_key 3497 NOEXIST::FUNCTION: +EVP_PKEY_get_attr_count 3498 EXIST::FUNCTION: +STORE_ATTR_INFO_new 3499 NOEXIST::FUNCTION: +EC_GROUP_get_curve_GF2m 3500 EXIST::FUNCTION:EC +STORE_meth_set_revoke_fn 3501 NOEXIST::FUNCTION: +STORE_method_set_revoke_function 3501 NOEXIST::FUNCTION: +STORE_store_number 3502 NOEXIST::FUNCTION: +BN_is_prime_ex 3503 EXIST::FUNCTION: +STORE_revoke_public_key 3504 NOEXIST::FUNCTION: +X509_STORE_CTX_get0_param 3505 EXIST::FUNCTION: +STORE_delete_arbitrary 3506 NOEXIST::FUNCTION: +PEM_read_X509_CERT_PAIR 3507 EXIST:!WIN16:FUNCTION: +X509_STORE_set_depth 3508 EXIST::FUNCTION: +ECDSA_get_ex_data 3509 EXIST::FUNCTION:ECDSA +SHA224 3510 EXIST::FUNCTION:SHA,SHA256 +BIO_dump_indent_fp 3511 EXIST::FUNCTION:FP_API +EC_KEY_set_group 3512 EXIST::FUNCTION:EC +BUF_strndup 3513 EXIST::FUNCTION: +STORE_list_certificate_start 3514 NOEXIST::FUNCTION: +BN_GF2m_mod 3515 EXIST::FUNCTION: +X509_REQ_check_private_key 3516 EXIST::FUNCTION: +EC_GROUP_get_seed_len 3517 EXIST::FUNCTION:EC +ERR_load_STORE_strings 3518 NOEXIST::FUNCTION: +PEM_read_bio_EC_PUBKEY 3519 EXIST::FUNCTION:EC +STORE_list_private_key_end 3520 NOEXIST::FUNCTION: +i2d_EC_PUBKEY 3521 EXIST::FUNCTION:EC +ECDSA_get_default_method 3522 EXIST::FUNCTION:ECDSA +ASN1_put_eoc 3523 EXIST::FUNCTION: +X509_STORE_CTX_get_explicit_policy 3524 EXIST:!VMS:FUNCTION: +X509_STORE_CTX_get_expl_policy 3524 EXIST:VMS:FUNCTION: +X509_VERIFY_PARAM_table_cleanup 3525 EXIST::FUNCTION: +STORE_modify_private_key 3526 NOEXIST::FUNCTION: +X509_VERIFY_PARAM_free 3527 EXIST::FUNCTION: +EC_METHOD_get_field_type 3528 EXIST::FUNCTION:EC +EC_GFp_nist_method 3529 EXIST::FUNCTION:EC +STORE_meth_set_modify_fn 3530 NOEXIST::FUNCTION: +STORE_method_set_modify_function 3530 NOEXIST::FUNCTION: +STORE_parse_attrs_next 3531 NOEXIST::FUNCTION: +ENGINE_load_padlock 3532 EXIST::FUNCTION:ENGINE,STATIC_ENGINE +EC_GROUP_set_curve_name 3533 EXIST::FUNCTION:EC +X509_CERT_PAIR_it 3534 EXIST:!EXPORT_VAR_AS_FUNCTION:VARIABLE: +X509_CERT_PAIR_it 3534 EXIST:EXPORT_VAR_AS_FUNCTION:FUNCTION: +STORE_meth_get_revoke_fn 3535 NOEXIST::FUNCTION: +STORE_method_get_revoke_function 3535 NOEXIST::FUNCTION: +STORE_method_set_get_function 3536 NOEXIST::FUNCTION: +STORE_modify_number 3537 NOEXIST::FUNCTION: +STORE_method_get_store_function 3538 NOEXIST::FUNCTION: +STORE_store_private_key 3539 NOEXIST::FUNCTION: +BN_GF2m_mod_sqr_arr 3540 EXIST::FUNCTION: +RSA_setup_blinding 3541 EXIST::FUNCTION:RSA +BIO_s_datagram 3542 EXIST::FUNCTION:DGRAM +STORE_Memory 3543 NOEXIST::FUNCTION: +sk_find_ex 3544 EXIST::FUNCTION: +EC_GROUP_set_curve_GF2m 3545 EXIST::FUNCTION:EC +ENGINE_set_default_ECDSA 3546 EXIST::FUNCTION:ENGINE +POLICY_CONSTRAINTS_new 3547 EXIST::FUNCTION: +BN_GF2m_mod_sqrt 3548 EXIST::FUNCTION: +ECDH_set_default_method 3549 EXIST::FUNCTION:ECDH +EC_KEY_generate_key 3550 EXIST::FUNCTION:EC +SHA384_Update 3551 EXIST:!VMSVAX:FUNCTION:SHA,SHA512 +BN_GF2m_arr2poly 3552 EXIST::FUNCTION: +STORE_method_get_get_function 3553 NOEXIST::FUNCTION: +STORE_meth_set_cleanup_fn 3554 NOEXIST::FUNCTION: +STORE_method_set_cleanup_function 3554 NOEXIST::FUNCTION: +EC_GROUP_check 3555 EXIST::FUNCTION:EC +d2i_ECPrivateKey_bio 3556 EXIST::FUNCTION:BIO,EC +EC_KEY_insert_key_method_data 3557 EXIST::FUNCTION:EC +STORE_meth_get_lock_store_fn 3558 NOEXIST::FUNCTION: +STORE_method_get_lock_store_function 3558 NOEXIST::FUNCTION: +X509_VERIFY_PARAM_get_depth 3559 EXIST::FUNCTION: +SHA224_Final 3560 EXIST::FUNCTION:SHA,SHA256 +STORE_meth_set_update_store_fn 3561 NOEXIST::FUNCTION: +STORE_method_set_update_store_function 3561 NOEXIST::FUNCTION: +SHA224_Update 3562 EXIST::FUNCTION:SHA,SHA256 +d2i_ECPrivateKey 3563 EXIST::FUNCTION:EC +ASN1_item_ndef_i2d 3564 EXIST::FUNCTION: +STORE_delete_private_key 3565 NOEXIST::FUNCTION: +ERR_pop_to_mark 3566 EXIST::FUNCTION: +ENGINE_register_all_STORE 3567 EXIST::FUNCTION:ENGINE +X509_policy_level_get0_node 3568 EXIST::FUNCTION: +i2d_PKCS7_NDEF 3569 EXIST::FUNCTION: +EC_GROUP_get_degree 3570 EXIST::FUNCTION:EC +ASN1_generate_v3 3571 EXIST::FUNCTION: +STORE_ATTR_INFO_modify_cstr 3572 NOEXIST::FUNCTION: +X509_policy_tree_level_count 3573 EXIST::FUNCTION: +BN_GF2m_add 3574 EXIST::FUNCTION: +EC_KEY_get0_group 3575 EXIST::FUNCTION:EC +STORE_generate_crl 3576 NOEXIST::FUNCTION: +STORE_store_public_key 3577 NOEXIST::FUNCTION: +X509_CERT_PAIR_free 3578 EXIST::FUNCTION: +STORE_revoke_private_key 3579 NOEXIST::FUNCTION: +BN_nist_mod_224 3580 EXIST::FUNCTION: +SHA512_Final 3581 EXIST:!VMSVAX:FUNCTION:SHA,SHA512 +STORE_ATTR_INFO_modify_dn 3582 NOEXIST::FUNCTION: +STORE_meth_get_initialise_fn 3583 NOEXIST::FUNCTION: +STORE_method_get_initialise_function 3583 NOEXIST::FUNCTION: +STORE_delete_number 3584 NOEXIST::FUNCTION: +i2d_EC_PUBKEY_bio 3585 EXIST::FUNCTION:BIO,EC +BIO_dgram_non_fatal_error 3586 EXIST::FUNCTION: +EC_GROUP_get_asn1_flag 3587 EXIST::FUNCTION:EC +STORE_ATTR_INFO_in_ex 3588 NOEXIST::FUNCTION: +STORE_list_crl_start 3589 NOEXIST::FUNCTION: +ECDH_get_ex_new_index 3590 EXIST::FUNCTION:ECDH +STORE_meth_get_modify_fn 3591 NOEXIST::FUNCTION: +STORE_method_get_modify_function 3591 NOEXIST::FUNCTION: +v2i_ASN1_BIT_STRING 3592 EXIST::FUNCTION: +STORE_store_certificate 3593 NOEXIST::FUNCTION: +OBJ_bsearch_ex 3594 NOEXIST::FUNCTION: +X509_STORE_CTX_set_default 3595 EXIST::FUNCTION: +STORE_ATTR_INFO_set_sha1str 3596 NOEXIST::FUNCTION: +BN_GF2m_mod_inv 3597 EXIST::FUNCTION: +BN_GF2m_mod_exp 3598 EXIST::FUNCTION: +STORE_modify_public_key 3599 NOEXIST::FUNCTION: +STORE_meth_get_list_start_fn 3600 NOEXIST::FUNCTION: +STORE_method_get_list_start_function 3600 NOEXIST::FUNCTION: +EC_GROUP_get0_seed 3601 EXIST::FUNCTION:EC +STORE_store_arbitrary 3602 NOEXIST::FUNCTION: +STORE_meth_set_unlock_store_fn 3603 NOEXIST::FUNCTION: +STORE_method_set_unlock_store_function 3603 NOEXIST::FUNCTION: +BN_GF2m_mod_div_arr 3604 EXIST::FUNCTION: +ENGINE_set_ECDSA 3605 EXIST::FUNCTION:ENGINE +STORE_create_method 3606 NOEXIST::FUNCTION: +ECPKParameters_print 3607 EXIST::FUNCTION:BIO,EC +EC_KEY_get0_private_key 3608 EXIST::FUNCTION:EC +PEM_write_EC_PUBKEY 3609 EXIST:!WIN16:FUNCTION:EC +X509_VERIFY_PARAM_set1 3610 EXIST::FUNCTION: +ECDH_set_method 3611 EXIST::FUNCTION:ECDH +v2i_GENERAL_NAME_ex 3612 EXIST::FUNCTION: +ECDH_set_ex_data 3613 EXIST::FUNCTION:ECDH +STORE_generate_key 3614 NOEXIST::FUNCTION: +BN_nist_mod_521 3615 EXIST::FUNCTION: +X509_policy_tree_get0_level 3616 EXIST::FUNCTION: +EC_GROUP_set_point_conversion_form 3617 EXIST:!VMS:FUNCTION:EC +EC_GROUP_set_point_conv_form 3617 EXIST:VMS:FUNCTION:EC +PEM_read_EC_PUBKEY 3618 EXIST:!WIN16:FUNCTION:EC +i2d_ECDSA_SIG 3619 EXIST::FUNCTION:ECDSA +ECDSA_OpenSSL 3620 EXIST::FUNCTION:ECDSA +STORE_delete_crl 3621 NOEXIST::FUNCTION: +EC_KEY_get_enc_flags 3622 EXIST::FUNCTION:EC +ASN1_const_check_infinite_end 3623 EXIST::FUNCTION: +EVP_PKEY_delete_attr 3624 EXIST::FUNCTION: +ECDSA_set_default_method 3625 EXIST::FUNCTION:ECDSA +EC_POINT_set_compressed_coordinates_GF2m 3626 EXIST:!VMS:FUNCTION:EC +EC_POINT_set_compr_coords_GF2m 3626 EXIST:VMS:FUNCTION:EC +EC_GROUP_cmp 3627 EXIST::FUNCTION:EC +STORE_revoke_certificate 3628 NOEXIST::FUNCTION: +BN_get0_nist_prime_256 3629 EXIST::FUNCTION: +STORE_meth_get_delete_fn 3630 NOEXIST::FUNCTION: +STORE_method_get_delete_function 3630 NOEXIST::FUNCTION: +SHA224_Init 3631 EXIST::FUNCTION:SHA,SHA256 +PEM_read_ECPrivateKey 3632 EXIST:!WIN16:FUNCTION:EC +SHA512_Init 3633 EXIST:!VMSVAX:FUNCTION:SHA,SHA512 +STORE_parse_attrs_endp 3634 NOEXIST::FUNCTION: +BN_set_negative 3635 EXIST::FUNCTION: +ERR_load_ECDSA_strings 3636 EXIST::FUNCTION:ECDSA +EC_GROUP_get_basis_type 3637 EXIST::FUNCTION:EC +STORE_list_public_key_next 3638 NOEXIST::FUNCTION: +i2v_ASN1_BIT_STRING 3639 EXIST::FUNCTION: +STORE_OBJECT_free 3640 NOEXIST::FUNCTION: +BN_nist_mod_384 3641 EXIST::FUNCTION: +i2d_X509_CERT_PAIR 3642 EXIST::FUNCTION: +PEM_write_ECPKParameters 3643 EXIST:!WIN16:FUNCTION:EC +ECDH_compute_key 3644 EXIST::FUNCTION:ECDH +STORE_ATTR_INFO_get0_sha1str 3645 NOEXIST::FUNCTION: +ENGINE_register_all_ECDH 3646 EXIST::FUNCTION:ENGINE +pqueue_pop 3647 EXIST::FUNCTION: +STORE_ATTR_INFO_get0_cstr 3648 NOEXIST::FUNCTION: +POLICY_CONSTRAINTS_it 3649 EXIST:!EXPORT_VAR_AS_FUNCTION:VARIABLE: +POLICY_CONSTRAINTS_it 3649 EXIST:EXPORT_VAR_AS_FUNCTION:FUNCTION: +STORE_get_ex_new_index 3650 NOEXIST::FUNCTION: +EVP_PKEY_get_attr_by_OBJ 3651 EXIST::FUNCTION: +X509_VERIFY_PARAM_add0_policy 3652 EXIST::FUNCTION: +BN_GF2m_mod_solve_quad 3653 EXIST::FUNCTION: +SHA256 3654 EXIST::FUNCTION:SHA,SHA256 +i2d_ECPrivateKey_fp 3655 EXIST::FUNCTION:EC,FP_API +X509_policy_tree_get0_user_policies 3656 EXIST:!VMS:FUNCTION: +X509_pcy_tree_get0_usr_policies 3656 EXIST:VMS:FUNCTION: +OPENSSL_DIR_read 3657 EXIST::FUNCTION: +ENGINE_register_all_ECDSA 3658 EXIST::FUNCTION:ENGINE +X509_VERIFY_PARAM_lookup 3659 EXIST::FUNCTION: +EC_POINT_get_affine_coordinates_GF2m 3660 EXIST:!VMS:FUNCTION:EC +EC_POINT_get_affine_coords_GF2m 3660 EXIST:VMS:FUNCTION:EC +EC_GROUP_dup 3661 EXIST::FUNCTION:EC +ENGINE_get_default_ECDSA 3662 EXIST::FUNCTION:ENGINE +EC_KEY_new 3663 EXIST::FUNCTION:EC +SHA256_Transform 3664 EXIST::FUNCTION:SHA,SHA256 +EC_KEY_set_enc_flags 3665 EXIST::FUNCTION:EC +ECDSA_verify 3666 EXIST::FUNCTION:ECDSA +EC_POINT_point2hex 3667 EXIST::FUNCTION:EC +ENGINE_get_STORE 3668 EXIST::FUNCTION:ENGINE +SHA512 3669 EXIST:!VMSVAX:FUNCTION:SHA,SHA512 +STORE_get_certificate 3670 NOEXIST::FUNCTION: +ECDSA_do_sign_ex 3671 EXIST::FUNCTION:ECDSA +ECDSA_do_verify 3672 EXIST::FUNCTION:ECDSA +d2i_ECPrivateKey_fp 3673 EXIST::FUNCTION:EC,FP_API +STORE_delete_certificate 3674 NOEXIST::FUNCTION: +SHA512_Transform 3675 EXIST:!VMSVAX:FUNCTION:SHA,SHA512 +X509_STORE_set1_param 3676 EXIST::FUNCTION: +STORE_method_get_ctrl_function 3677 NOEXIST::FUNCTION: +STORE_free 3678 NOEXIST::FUNCTION: +PEM_write_ECPrivateKey 3679 EXIST:!WIN16:FUNCTION:EC +STORE_meth_get_unlock_store_fn 3680 NOEXIST::FUNCTION: +STORE_method_get_unlock_store_function 3680 NOEXIST::FUNCTION: +STORE_get_ex_data 3681 NOEXIST::FUNCTION: +EC_KEY_set_public_key 3682 EXIST::FUNCTION:EC +PEM_read_ECPKParameters 3683 EXIST:!WIN16:FUNCTION:EC +X509_CERT_PAIR_new 3684 EXIST::FUNCTION: +ENGINE_register_STORE 3685 EXIST::FUNCTION:ENGINE +RSA_generate_key_ex 3686 EXIST::FUNCTION:RSA +DSA_generate_parameters_ex 3687 EXIST::FUNCTION:DSA +ECParameters_print_fp 3688 EXIST::FUNCTION:EC,FP_API +X509V3_NAME_from_section 3689 EXIST::FUNCTION: +EVP_PKEY_add1_attr 3690 EXIST::FUNCTION: +STORE_modify_crl 3691 NOEXIST::FUNCTION: +STORE_list_private_key_start 3692 NOEXIST::FUNCTION: +POLICY_MAPPINGS_it 3693 EXIST:!EXPORT_VAR_AS_FUNCTION:VARIABLE: +POLICY_MAPPINGS_it 3693 EXIST:EXPORT_VAR_AS_FUNCTION:FUNCTION: +GENERAL_SUBTREE_it 3694 EXIST:!EXPORT_VAR_AS_FUNCTION:VARIABLE: +GENERAL_SUBTREE_it 3694 EXIST:EXPORT_VAR_AS_FUNCTION:FUNCTION: +EC_GROUP_get_curve_name 3695 EXIST::FUNCTION:EC +PEM_write_X509_CERT_PAIR 3696 EXIST:!WIN16:FUNCTION: +BIO_dump_indent_cb 3697 EXIST::FUNCTION: +d2i_X509_CERT_PAIR 3698 EXIST::FUNCTION: +STORE_list_private_key_endp 3699 NOEXIST::FUNCTION: +asn1_const_Finish 3700 EXIST::FUNCTION: +i2d_EC_PUBKEY_fp 3701 EXIST::FUNCTION:EC,FP_API +BN_nist_mod_256 3702 EXIST::FUNCTION: +X509_VERIFY_PARAM_add0_table 3703 EXIST::FUNCTION: +pqueue_free 3704 EXIST::FUNCTION: +BN_BLINDING_create_param 3705 EXIST::FUNCTION: +ECDSA_size 3706 EXIST::FUNCTION:ECDSA +d2i_EC_PUBKEY_bio 3707 EXIST::FUNCTION:BIO,EC +BN_get0_nist_prime_521 3708 EXIST::FUNCTION: +STORE_ATTR_INFO_modify_sha1str 3709 NOEXIST::FUNCTION: +BN_generate_prime_ex 3710 EXIST::FUNCTION: +EC_GROUP_new_by_curve_name 3711 EXIST::FUNCTION:EC +SHA256_Final 3712 EXIST::FUNCTION:SHA,SHA256 +DH_generate_parameters_ex 3713 EXIST::FUNCTION:DH +PEM_read_bio_ECPrivateKey 3714 EXIST::FUNCTION:EC +STORE_meth_get_cleanup_fn 3715 NOEXIST::FUNCTION: +STORE_method_get_cleanup_function 3715 NOEXIST::FUNCTION: +ENGINE_get_ECDH 3716 EXIST::FUNCTION:ENGINE +d2i_ECDSA_SIG 3717 EXIST::FUNCTION:ECDSA +BN_is_prime_fasttest_ex 3718 EXIST::FUNCTION: +ECDSA_sign 3719 EXIST::FUNCTION:ECDSA +X509_policy_check 3720 EXIST::FUNCTION: +EVP_PKEY_get_attr_by_NID 3721 EXIST::FUNCTION: +STORE_set_ex_data 3722 NOEXIST::FUNCTION: +ENGINE_get_ECDSA 3723 EXIST::FUNCTION:ENGINE +EVP_ecdsa 3724 EXIST::FUNCTION:SHA +BN_BLINDING_get_flags 3725 EXIST::FUNCTION: +PKCS12_add_cert 3726 EXIST::FUNCTION: +STORE_OBJECT_new 3727 NOEXIST::FUNCTION: +ERR_load_ECDH_strings 3728 EXIST::FUNCTION:ECDH +EC_KEY_dup 3729 EXIST::FUNCTION:EC +EVP_CIPHER_CTX_rand_key 3730 EXIST::FUNCTION: +ECDSA_set_method 3731 EXIST::FUNCTION:ECDSA +a2i_IPADDRESS_NC 3732 EXIST::FUNCTION: +d2i_ECParameters 3733 EXIST::FUNCTION:EC +STORE_list_certificate_end 3734 NOEXIST::FUNCTION: +STORE_get_crl 3735 NOEXIST::FUNCTION: +X509_POLICY_NODE_print 3736 EXIST::FUNCTION: +SHA384_Init 3737 EXIST:!VMSVAX:FUNCTION:SHA,SHA512 +EC_GF2m_simple_method 3738 EXIST::FUNCTION:EC +ECDSA_set_ex_data 3739 EXIST::FUNCTION:ECDSA +SHA384_Final 3740 EXIST:!VMSVAX:FUNCTION:SHA,SHA512 +PKCS7_set_digest 3741 EXIST::FUNCTION: +EC_KEY_print 3742 EXIST::FUNCTION:BIO,EC +STORE_meth_set_lock_store_fn 3743 NOEXIST::FUNCTION: +STORE_method_set_lock_store_function 3743 NOEXIST::FUNCTION: +ECDSA_get_ex_new_index 3744 EXIST::FUNCTION:ECDSA +SHA384 3745 EXIST:!VMSVAX:FUNCTION:SHA,SHA512 +POLICY_MAPPING_new 3746 EXIST::FUNCTION: +STORE_list_certificate_endp 3747 NOEXIST::FUNCTION: +X509_STORE_CTX_get0_policy_tree 3748 EXIST::FUNCTION: +EC_GROUP_set_asn1_flag 3749 EXIST::FUNCTION:EC +EC_KEY_check_key 3750 EXIST::FUNCTION:EC +d2i_EC_PUBKEY_fp 3751 EXIST::FUNCTION:EC,FP_API +PKCS7_set0_type_other 3752 EXIST::FUNCTION: +PEM_read_bio_X509_CERT_PAIR 3753 EXIST::FUNCTION: +pqueue_next 3754 EXIST::FUNCTION: +STORE_meth_get_list_end_fn 3755 NOEXIST::FUNCTION: +STORE_method_get_list_end_function 3755 NOEXIST::FUNCTION: +EVP_PKEY_add1_attr_by_OBJ 3756 EXIST::FUNCTION: +X509_VERIFY_PARAM_set_time 3757 EXIST::FUNCTION: +pqueue_new 3758 EXIST::FUNCTION: +ENGINE_set_default_ECDH 3759 EXIST::FUNCTION:ENGINE +STORE_new_method 3760 NOEXIST::FUNCTION: +PKCS12_add_key 3761 EXIST::FUNCTION: +DSO_merge 3762 EXIST::FUNCTION: +EC_POINT_hex2point 3763 EXIST::FUNCTION:EC +BIO_dump_cb 3764 EXIST::FUNCTION: +SHA256_Update 3765 EXIST::FUNCTION:SHA,SHA256 +pqueue_insert 3766 EXIST::FUNCTION: +pitem_free 3767 EXIST::FUNCTION: +BN_GF2m_mod_inv_arr 3768 EXIST::FUNCTION: +ENGINE_unregister_ECDSA 3769 EXIST::FUNCTION:ENGINE +BN_BLINDING_set_thread_id 3770 EXIST::FUNCTION:DEPRECATED +get_rfc3526_prime_8192 3771 EXIST::FUNCTION: +X509_VERIFY_PARAM_clear_flags 3772 EXIST::FUNCTION: +get_rfc2409_prime_1024 3773 EXIST::FUNCTION: +DH_check_pub_key 3774 EXIST::FUNCTION:DH +get_rfc3526_prime_2048 3775 EXIST::FUNCTION: +get_rfc3526_prime_6144 3776 EXIST::FUNCTION: +get_rfc3526_prime_1536 3777 EXIST::FUNCTION: +get_rfc3526_prime_3072 3778 EXIST::FUNCTION: +get_rfc3526_prime_4096 3779 EXIST::FUNCTION: +get_rfc2409_prime_768 3780 EXIST::FUNCTION: +X509_VERIFY_PARAM_get_flags 3781 EXIST::FUNCTION: +EVP_CIPHER_CTX_new 3782 EXIST::FUNCTION: +EVP_CIPHER_CTX_free 3783 EXIST::FUNCTION: +Camellia_cbc_encrypt 3784 EXIST::FUNCTION:CAMELLIA +Camellia_cfb128_encrypt 3785 EXIST::FUNCTION:CAMELLIA +Camellia_cfb1_encrypt 3786 EXIST::FUNCTION:CAMELLIA +Camellia_cfb8_encrypt 3787 EXIST::FUNCTION:CAMELLIA +Camellia_ctr128_encrypt 3788 EXIST::FUNCTION:CAMELLIA +Camellia_cfbr_encrypt_block 3789 NOEXIST::FUNCTION: +Camellia_decrypt 3790 EXIST::FUNCTION:CAMELLIA +Camellia_ecb_encrypt 3791 EXIST::FUNCTION:CAMELLIA +Camellia_encrypt 3792 EXIST::FUNCTION:CAMELLIA +Camellia_ofb128_encrypt 3793 EXIST::FUNCTION:CAMELLIA +Camellia_set_key 3794 EXIST::FUNCTION:CAMELLIA +EVP_camellia_128_cbc 3795 EXIST::FUNCTION:CAMELLIA +EVP_camellia_128_cfb128 3796 EXIST::FUNCTION:CAMELLIA +EVP_camellia_128_cfb1 3797 EXIST::FUNCTION:CAMELLIA +EVP_camellia_128_cfb8 3798 EXIST::FUNCTION:CAMELLIA +EVP_camellia_128_ecb 3799 EXIST::FUNCTION:CAMELLIA +EVP_camellia_128_ofb 3800 EXIST::FUNCTION:CAMELLIA +EVP_camellia_192_cbc 3801 EXIST::FUNCTION:CAMELLIA +EVP_camellia_192_cfb128 3802 EXIST::FUNCTION:CAMELLIA +EVP_camellia_192_cfb1 3803 EXIST::FUNCTION:CAMELLIA +EVP_camellia_192_cfb8 3804 EXIST::FUNCTION:CAMELLIA +EVP_camellia_192_ecb 3805 EXIST::FUNCTION:CAMELLIA +EVP_camellia_192_ofb 3806 EXIST::FUNCTION:CAMELLIA +EVP_camellia_256_cbc 3807 EXIST::FUNCTION:CAMELLIA +EVP_camellia_256_cfb128 3808 EXIST::FUNCTION:CAMELLIA +EVP_camellia_256_cfb1 3809 EXIST::FUNCTION:CAMELLIA +EVP_camellia_256_cfb8 3810 EXIST::FUNCTION:CAMELLIA +EVP_camellia_256_ecb 3811 EXIST::FUNCTION:CAMELLIA +EVP_camellia_256_ofb 3812 EXIST::FUNCTION:CAMELLIA +a2i_ipadd 3813 EXIST::FUNCTION: +ASIdentifiers_free 3814 EXIST::FUNCTION:RFC3779 +i2d_ASIdOrRange 3815 EXIST::FUNCTION:RFC3779 +EVP_CIPHER_block_size 3816 EXIST::FUNCTION: +v3_asid_is_canonical 3817 EXIST::FUNCTION:RFC3779 +IPAddressChoice_free 3818 EXIST::FUNCTION:RFC3779 +EVP_CIPHER_CTX_set_app_data 3819 EXIST::FUNCTION: +BIO_set_callback_arg 3820 EXIST::FUNCTION: +v3_addr_add_prefix 3821 EXIST::FUNCTION:RFC3779 +IPAddressOrRange_it 3822 EXIST:!EXPORT_VAR_AS_FUNCTION:VARIABLE:RFC3779 +IPAddressOrRange_it 3822 EXIST:EXPORT_VAR_AS_FUNCTION:FUNCTION:RFC3779 +BIO_set_flags 3823 EXIST::FUNCTION: +ASIdentifiers_it 3824 EXIST:!EXPORT_VAR_AS_FUNCTION:VARIABLE:RFC3779 +ASIdentifiers_it 3824 EXIST:EXPORT_VAR_AS_FUNCTION:FUNCTION:RFC3779 +v3_addr_get_range 3825 EXIST::FUNCTION:RFC3779 +BIO_method_type 3826 EXIST::FUNCTION: +v3_addr_inherits 3827 EXIST::FUNCTION:RFC3779 +IPAddressChoice_it 3828 EXIST:!EXPORT_VAR_AS_FUNCTION:VARIABLE:RFC3779 +IPAddressChoice_it 3828 EXIST:EXPORT_VAR_AS_FUNCTION:FUNCTION:RFC3779 +AES_ige_encrypt 3829 EXIST::FUNCTION:AES +v3_addr_add_range 3830 EXIST::FUNCTION:RFC3779 +EVP_CIPHER_CTX_nid 3831 EXIST::FUNCTION: +d2i_ASRange 3832 EXIST::FUNCTION:RFC3779 +v3_addr_add_inherit 3833 EXIST::FUNCTION:RFC3779 +v3_asid_add_id_or_range 3834 EXIST::FUNCTION:RFC3779 +v3_addr_validate_resource_set 3835 EXIST::FUNCTION:RFC3779 +EVP_CIPHER_iv_length 3836 EXIST::FUNCTION: +EVP_MD_type 3837 EXIST::FUNCTION: +v3_asid_canonize 3838 EXIST::FUNCTION:RFC3779 +IPAddressRange_free 3839 EXIST::FUNCTION:RFC3779 +v3_asid_add_inherit 3840 EXIST::FUNCTION:RFC3779 +EVP_CIPHER_CTX_key_length 3841 EXIST::FUNCTION: +IPAddressRange_new 3842 EXIST::FUNCTION:RFC3779 +ASIdOrRange_new 3843 EXIST::FUNCTION:RFC3779 +EVP_MD_size 3844 EXIST::FUNCTION: +EVP_MD_CTX_test_flags 3845 EXIST::FUNCTION: +BIO_clear_flags 3846 EXIST::FUNCTION: +i2d_ASRange 3847 EXIST::FUNCTION:RFC3779 +IPAddressRange_it 3848 EXIST:!EXPORT_VAR_AS_FUNCTION:VARIABLE:RFC3779 +IPAddressRange_it 3848 EXIST:EXPORT_VAR_AS_FUNCTION:FUNCTION:RFC3779 +IPAddressChoice_new 3849 EXIST::FUNCTION:RFC3779 +ASIdentifierChoice_new 3850 EXIST::FUNCTION:RFC3779 +ASRange_free 3851 EXIST::FUNCTION:RFC3779 +EVP_MD_pkey_type 3852 EXIST::FUNCTION: +EVP_MD_CTX_clear_flags 3853 EXIST::FUNCTION: +IPAddressFamily_free 3854 EXIST::FUNCTION:RFC3779 +i2d_IPAddressFamily 3855 EXIST::FUNCTION:RFC3779 +IPAddressOrRange_new 3856 EXIST::FUNCTION:RFC3779 +EVP_CIPHER_flags 3857 EXIST::FUNCTION: +v3_asid_validate_resource_set 3858 EXIST::FUNCTION:RFC3779 +d2i_IPAddressRange 3859 EXIST::FUNCTION:RFC3779 +AES_bi_ige_encrypt 3860 EXIST::FUNCTION:AES +BIO_get_callback 3861 EXIST::FUNCTION: +IPAddressOrRange_free 3862 EXIST::FUNCTION:RFC3779 +v3_addr_subset 3863 EXIST::FUNCTION:RFC3779 +d2i_IPAddressFamily 3864 EXIST::FUNCTION:RFC3779 +v3_asid_subset 3865 EXIST::FUNCTION:RFC3779 +BIO_test_flags 3866 EXIST::FUNCTION: +i2d_ASIdentifierChoice 3867 EXIST::FUNCTION:RFC3779 +ASRange_it 3868 EXIST:!EXPORT_VAR_AS_FUNCTION:VARIABLE:RFC3779 +ASRange_it 3868 EXIST:EXPORT_VAR_AS_FUNCTION:FUNCTION:RFC3779 +d2i_ASIdentifiers 3869 EXIST::FUNCTION:RFC3779 +ASRange_new 3870 EXIST::FUNCTION:RFC3779 +d2i_IPAddressChoice 3871 EXIST::FUNCTION:RFC3779 +v3_addr_get_afi 3872 EXIST::FUNCTION:RFC3779 +EVP_CIPHER_key_length 3873 EXIST::FUNCTION: +EVP_Cipher 3874 EXIST::FUNCTION: +i2d_IPAddressOrRange 3875 EXIST::FUNCTION:RFC3779 +ASIdOrRange_it 3876 EXIST:!EXPORT_VAR_AS_FUNCTION:VARIABLE:RFC3779 +ASIdOrRange_it 3876 EXIST:EXPORT_VAR_AS_FUNCTION:FUNCTION:RFC3779 +EVP_CIPHER_nid 3877 EXIST::FUNCTION: +i2d_IPAddressChoice 3878 EXIST::FUNCTION:RFC3779 +EVP_CIPHER_CTX_block_size 3879 EXIST::FUNCTION: +ASIdentifiers_new 3880 EXIST::FUNCTION:RFC3779 +v3_addr_validate_path 3881 EXIST::FUNCTION:RFC3779 +IPAddressFamily_new 3882 EXIST::FUNCTION:RFC3779 +EVP_MD_CTX_set_flags 3883 EXIST::FUNCTION: +v3_addr_is_canonical 3884 EXIST::FUNCTION:RFC3779 +i2d_IPAddressRange 3885 EXIST::FUNCTION:RFC3779 +IPAddressFamily_it 3886 EXIST:!EXPORT_VAR_AS_FUNCTION:VARIABLE:RFC3779 +IPAddressFamily_it 3886 EXIST:EXPORT_VAR_AS_FUNCTION:FUNCTION:RFC3779 +v3_asid_inherits 3887 EXIST::FUNCTION:RFC3779 +EVP_CIPHER_CTX_cipher 3888 EXIST::FUNCTION: +EVP_CIPHER_CTX_get_app_data 3889 EXIST::FUNCTION: +EVP_MD_block_size 3890 EXIST::FUNCTION: +EVP_CIPHER_CTX_flags 3891 EXIST::FUNCTION: +v3_asid_validate_path 3892 EXIST::FUNCTION:RFC3779 +d2i_IPAddressOrRange 3893 EXIST::FUNCTION:RFC3779 +v3_addr_canonize 3894 EXIST::FUNCTION:RFC3779 +ASIdentifierChoice_it 3895 EXIST:!EXPORT_VAR_AS_FUNCTION:VARIABLE:RFC3779 +ASIdentifierChoice_it 3895 EXIST:EXPORT_VAR_AS_FUNCTION:FUNCTION:RFC3779 +EVP_MD_CTX_md 3896 EXIST::FUNCTION: +d2i_ASIdentifierChoice 3897 EXIST::FUNCTION:RFC3779 +BIO_method_name 3898 EXIST::FUNCTION: +EVP_CIPHER_CTX_iv_length 3899 EXIST::FUNCTION: +ASIdOrRange_free 3900 EXIST::FUNCTION:RFC3779 +ASIdentifierChoice_free 3901 EXIST::FUNCTION:RFC3779 +BIO_get_callback_arg 3902 EXIST::FUNCTION: +BIO_set_callback 3903 EXIST::FUNCTION: +d2i_ASIdOrRange 3904 EXIST::FUNCTION:RFC3779 +i2d_ASIdentifiers 3905 EXIST::FUNCTION:RFC3779 +SEED_decrypt 3908 EXIST::FUNCTION:SEED +SEED_encrypt 3909 EXIST::FUNCTION:SEED +SEED_cbc_encrypt 3910 EXIST::FUNCTION:SEED +EVP_seed_ofb 3911 EXIST::FUNCTION:SEED +SEED_cfb128_encrypt 3912 EXIST::FUNCTION:SEED +SEED_ofb128_encrypt 3913 EXIST::FUNCTION:SEED +EVP_seed_cbc 3914 EXIST::FUNCTION:SEED +SEED_ecb_encrypt 3915 EXIST::FUNCTION:SEED +EVP_seed_ecb 3916 EXIST::FUNCTION:SEED +SEED_set_key 3917 EXIST::FUNCTION:SEED +EVP_seed_cfb128 3918 EXIST::FUNCTION:SEED +X509_EXTENSIONS_it 3919 EXIST:!EXPORT_VAR_AS_FUNCTION:VARIABLE: +X509_EXTENSIONS_it 3919 EXIST:EXPORT_VAR_AS_FUNCTION:FUNCTION: +X509_get1_ocsp 3920 EXIST::FUNCTION: +OCSP_REQ_CTX_free 3921 EXIST::FUNCTION: +i2d_X509_EXTENSIONS 3922 EXIST::FUNCTION: +OCSP_sendreq_nbio 3923 EXIST::FUNCTION: +OCSP_sendreq_new 3924 EXIST::FUNCTION: +d2i_X509_EXTENSIONS 3925 EXIST::FUNCTION: +X509_ALGORS_it 3926 EXIST:!EXPORT_VAR_AS_FUNCTION:VARIABLE: +X509_ALGORS_it 3926 EXIST:EXPORT_VAR_AS_FUNCTION:FUNCTION: +X509_ALGOR_get0 3927 EXIST::FUNCTION: +X509_ALGOR_set0 3928 EXIST::FUNCTION: +AES_unwrap_key 3929 EXIST::FUNCTION:AES +AES_wrap_key 3930 EXIST::FUNCTION:AES +X509at_get0_data_by_OBJ 3931 EXIST::FUNCTION: +ASN1_TYPE_set1 3932 EXIST::FUNCTION: +ASN1_STRING_set0 3933 EXIST::FUNCTION: +i2d_X509_ALGORS 3934 EXIST::FUNCTION: +BIO_f_zlib 3935 EXIST:ZLIB:FUNCTION: +COMP_zlib_cleanup 3936 EXIST::FUNCTION: +d2i_X509_ALGORS 3937 EXIST::FUNCTION: +CMS_ReceiptRequest_free 3938 EXIST::FUNCTION:CMS +PEM_write_CMS 3939 EXIST:!WIN16:FUNCTION:CMS +CMS_add0_CertificateChoices 3940 EXIST::FUNCTION:CMS +CMS_unsigned_add1_attr_by_OBJ 3941 EXIST::FUNCTION:CMS +ERR_load_CMS_strings 3942 EXIST::FUNCTION:CMS +CMS_sign_receipt 3943 EXIST::FUNCTION:CMS +i2d_CMS_ContentInfo 3944 EXIST::FUNCTION:CMS +CMS_signed_delete_attr 3945 EXIST::FUNCTION:CMS +d2i_CMS_bio 3946 EXIST::FUNCTION:CMS +CMS_unsigned_get_attr_by_NID 3947 EXIST::FUNCTION:CMS +CMS_verify 3948 EXIST::FUNCTION:CMS +SMIME_read_CMS 3949 EXIST::FUNCTION:CMS +CMS_decrypt_set1_key 3950 EXIST::FUNCTION:CMS +CMS_SignerInfo_get0_algs 3951 EXIST::FUNCTION:CMS +CMS_add1_cert 3952 EXIST::FUNCTION:CMS +CMS_set_detached 3953 EXIST::FUNCTION:CMS +CMS_encrypt 3954 EXIST::FUNCTION:CMS +CMS_EnvelopedData_create 3955 EXIST::FUNCTION:CMS +CMS_uncompress 3956 EXIST::FUNCTION:CMS +CMS_add0_crl 3957 EXIST::FUNCTION:CMS +CMS_SignerInfo_verify_content 3958 EXIST::FUNCTION:CMS +CMS_unsigned_get0_data_by_OBJ 3959 EXIST::FUNCTION:CMS +PEM_write_bio_CMS 3960 EXIST::FUNCTION:CMS +CMS_unsigned_get_attr 3961 EXIST::FUNCTION:CMS +CMS_RecipientInfo_ktri_cert_cmp 3962 EXIST::FUNCTION:CMS +CMS_RecipientInfo_ktri_get0_algs 3963 EXIST:!VMS:FUNCTION:CMS +CMS_RecipInfo_ktri_get0_algs 3963 EXIST:VMS:FUNCTION:CMS +CMS_ContentInfo_free 3964 EXIST::FUNCTION:CMS +CMS_final 3965 EXIST::FUNCTION:CMS +CMS_add_simple_smimecap 3966 EXIST::FUNCTION:CMS +CMS_SignerInfo_verify 3967 EXIST::FUNCTION:CMS +CMS_data 3968 EXIST::FUNCTION:CMS +CMS_ContentInfo_it 3969 EXIST:!EXPORT_VAR_AS_FUNCTION:VARIABLE:CMS +CMS_ContentInfo_it 3969 EXIST:EXPORT_VAR_AS_FUNCTION:FUNCTION:CMS +d2i_CMS_ReceiptRequest 3970 EXIST::FUNCTION:CMS +CMS_compress 3971 EXIST::FUNCTION:CMS +CMS_digest_create 3972 EXIST::FUNCTION:CMS +CMS_SignerInfo_cert_cmp 3973 EXIST::FUNCTION:CMS +CMS_SignerInfo_sign 3974 EXIST::FUNCTION:CMS +CMS_data_create 3975 EXIST::FUNCTION:CMS +i2d_CMS_bio 3976 EXIST::FUNCTION:CMS +CMS_EncryptedData_set1_key 3977 EXIST::FUNCTION:CMS +CMS_decrypt 3978 EXIST::FUNCTION:CMS +int_smime_write_ASN1 3979 NOEXIST::FUNCTION: +CMS_unsigned_delete_attr 3980 EXIST::FUNCTION:CMS +CMS_unsigned_get_attr_count 3981 EXIST::FUNCTION:CMS +CMS_add_smimecap 3982 EXIST::FUNCTION:CMS +PEM_read_CMS 3983 EXIST:!WIN16:FUNCTION:CMS +CMS_signed_get_attr_by_OBJ 3984 EXIST::FUNCTION:CMS +d2i_CMS_ContentInfo 3985 EXIST::FUNCTION:CMS +CMS_add_standard_smimecap 3986 EXIST::FUNCTION:CMS +CMS_ContentInfo_new 3987 EXIST::FUNCTION:CMS +CMS_RecipientInfo_type 3988 EXIST::FUNCTION:CMS +CMS_get0_type 3989 EXIST::FUNCTION:CMS +CMS_is_detached 3990 EXIST::FUNCTION:CMS +CMS_sign 3991 EXIST::FUNCTION:CMS +CMS_signed_add1_attr 3992 EXIST::FUNCTION:CMS +CMS_unsigned_get_attr_by_OBJ 3993 EXIST::FUNCTION:CMS +SMIME_write_CMS 3994 EXIST::FUNCTION:CMS +CMS_EncryptedData_decrypt 3995 EXIST::FUNCTION:CMS +CMS_get0_RecipientInfos 3996 EXIST::FUNCTION:CMS +CMS_add0_RevocationInfoChoice 3997 EXIST::FUNCTION:CMS +CMS_decrypt_set1_pkey 3998 EXIST::FUNCTION:CMS +CMS_SignerInfo_set1_signer_cert 3999 EXIST::FUNCTION:CMS +CMS_get0_signers 4000 EXIST::FUNCTION:CMS +CMS_ReceiptRequest_get0_values 4001 EXIST::FUNCTION:CMS +CMS_signed_get0_data_by_OBJ 4002 EXIST::FUNCTION:CMS +CMS_get0_SignerInfos 4003 EXIST::FUNCTION:CMS +CMS_add0_cert 4004 EXIST::FUNCTION:CMS +CMS_EncryptedData_encrypt 4005 EXIST::FUNCTION:CMS +CMS_digest_verify 4006 EXIST::FUNCTION:CMS +CMS_set1_signers_certs 4007 EXIST::FUNCTION:CMS +CMS_signed_get_attr 4008 EXIST::FUNCTION:CMS +CMS_RecipientInfo_set0_key 4009 EXIST::FUNCTION:CMS +CMS_SignedData_init 4010 EXIST::FUNCTION:CMS +CMS_RecipientInfo_kekri_get0_id 4011 EXIST::FUNCTION:CMS +CMS_verify_receipt 4012 EXIST::FUNCTION:CMS +CMS_ReceiptRequest_it 4013 EXIST:!EXPORT_VAR_AS_FUNCTION:VARIABLE:CMS +CMS_ReceiptRequest_it 4013 EXIST:EXPORT_VAR_AS_FUNCTION:FUNCTION:CMS +PEM_read_bio_CMS 4014 EXIST::FUNCTION:CMS +CMS_get1_crls 4015 EXIST::FUNCTION:CMS +CMS_add0_recipient_key 4016 EXIST::FUNCTION:CMS +SMIME_read_ASN1 4017 EXIST::FUNCTION: +CMS_ReceiptRequest_new 4018 EXIST::FUNCTION:CMS +CMS_get0_content 4019 EXIST::FUNCTION:CMS +CMS_get1_ReceiptRequest 4020 EXIST::FUNCTION:CMS +CMS_signed_add1_attr_by_OBJ 4021 EXIST::FUNCTION:CMS +CMS_RecipientInfo_kekri_id_cmp 4022 EXIST::FUNCTION:CMS +CMS_add1_ReceiptRequest 4023 EXIST::FUNCTION:CMS +CMS_SignerInfo_get0_signer_id 4024 EXIST::FUNCTION:CMS +CMS_unsigned_add1_attr_by_NID 4025 EXIST::FUNCTION:CMS +CMS_unsigned_add1_attr 4026 EXIST::FUNCTION:CMS +CMS_signed_get_attr_by_NID 4027 EXIST::FUNCTION:CMS +CMS_get1_certs 4028 EXIST::FUNCTION:CMS +CMS_signed_add1_attr_by_NID 4029 EXIST::FUNCTION:CMS +CMS_unsigned_add1_attr_by_txt 4030 EXIST::FUNCTION:CMS +CMS_dataFinal 4031 EXIST::FUNCTION:CMS +CMS_RecipientInfo_ktri_get0_signer_id 4032 EXIST:!VMS:FUNCTION:CMS +CMS_RecipInfo_ktri_get0_sigr_id 4032 EXIST:VMS:FUNCTION:CMS +i2d_CMS_ReceiptRequest 4033 EXIST::FUNCTION:CMS +CMS_add1_recipient_cert 4034 EXIST::FUNCTION:CMS +CMS_dataInit 4035 EXIST::FUNCTION:CMS +CMS_signed_add1_attr_by_txt 4036 EXIST::FUNCTION:CMS +CMS_RecipientInfo_decrypt 4037 EXIST::FUNCTION:CMS +CMS_signed_get_attr_count 4038 EXIST::FUNCTION:CMS +CMS_get0_eContentType 4039 EXIST::FUNCTION:CMS +CMS_set1_eContentType 4040 EXIST::FUNCTION:CMS +CMS_ReceiptRequest_create0 4041 EXIST::FUNCTION:CMS +CMS_add1_signer 4042 EXIST::FUNCTION:CMS +CMS_RecipientInfo_set0_pkey 4043 EXIST::FUNCTION:CMS +ENGINE_set_load_ssl_client_cert_function 4044 EXIST:!VMS:FUNCTION:ENGINE +ENGINE_set_ld_ssl_clnt_cert_fn 4044 EXIST:VMS:FUNCTION:ENGINE +ENGINE_get_ssl_client_cert_function 4045 EXIST:!VMS:FUNCTION:ENGINE +ENGINE_get_ssl_client_cert_fn 4045 EXIST:VMS:FUNCTION:ENGINE +ENGINE_load_ssl_client_cert 4046 EXIST::FUNCTION:ENGINE +ENGINE_load_capi 4047 EXIST::FUNCTION:ENGINE,STATIC_ENGINE +OPENSSL_isservice 4048 EXIST::FUNCTION: +FIPS_dsa_sig_decode 4049 NOEXIST::FUNCTION: +EVP_CIPHER_CTX_clear_flags 4050 EXIST::FUNCTION: +FIPS_rand_status 4051 NOEXIST::FUNCTION: +FIPS_rand_set_key 4052 NOEXIST::FUNCTION: +CRYPTO_set_mem_info_functions 4053 NOEXIST::FUNCTION: +RSA_X931_generate_key_ex 4054 NOEXIST::FUNCTION: +int_ERR_set_state_func 4055 NOEXIST::FUNCTION: +int_EVP_MD_set_engine_callbacks 4056 NOEXIST::FUNCTION: +int_CRYPTO_set_do_dynlock_callback 4057 NOEXIST::FUNCTION: +FIPS_rng_stick 4058 NOEXIST::FUNCTION: +EVP_CIPHER_CTX_set_flags 4059 EXIST::FUNCTION: +BN_X931_generate_prime_ex 4060 NOEXIST::FUNCTION: +FIPS_selftest_check 4061 NOEXIST::FUNCTION: +FIPS_rand_set_dt 4062 NOEXIST::FUNCTION: +CRYPTO_dbg_pop_info 4063 NOEXIST::FUNCTION: +FIPS_dsa_free 4064 NOEXIST::FUNCTION: +RSA_X931_derive_ex 4065 NOEXIST::FUNCTION: +FIPS_rsa_new 4066 NOEXIST::FUNCTION: +FIPS_rand_bytes 4067 NOEXIST::FUNCTION: +fips_cipher_test 4068 NOEXIST::FUNCTION: +EVP_CIPHER_CTX_test_flags 4069 EXIST::FUNCTION: +CRYPTO_malloc_debug_init 4070 NOEXIST::FUNCTION: +CRYPTO_dbg_push_info 4071 NOEXIST::FUNCTION: +FIPS_corrupt_rsa_keygen 4072 NOEXIST::FUNCTION: +FIPS_dh_new 4073 NOEXIST::FUNCTION: +FIPS_corrupt_dsa_keygen 4074 NOEXIST::FUNCTION: +FIPS_dh_free 4075 NOEXIST::FUNCTION: +fips_pkey_signature_test 4076 NOEXIST::FUNCTION: +EVP_add_alg_module 4077 NOEXIST::FUNCTION: +int_RAND_init_engine_callbacks 4078 NOEXIST::FUNCTION: +int_EVP_CIPHER_set_engine_callbacks 4079 NOEXIST::FUNCTION: +int_EVP_MD_init_engine_callbacks 4080 NOEXIST::FUNCTION: +FIPS_rand_test_mode 4081 NOEXIST::FUNCTION: +FIPS_rand_reset 4082 NOEXIST::FUNCTION: +FIPS_dsa_new 4083 NOEXIST::FUNCTION: +int_RAND_set_callbacks 4084 NOEXIST::FUNCTION: +BN_X931_derive_prime_ex 4085 NOEXIST::FUNCTION: +int_ERR_lib_init 4086 NOEXIST::FUNCTION: +int_EVP_CIPHER_init_engine_callbacks 4087 NOEXIST::FUNCTION: +FIPS_rsa_free 4088 NOEXIST::FUNCTION: +FIPS_dsa_sig_encode 4089 NOEXIST::FUNCTION: +CRYPTO_dbg_remove_all_info 4090 NOEXIST::FUNCTION: +OPENSSL_init 4091 NOEXIST::FUNCTION: +private_Camellia_set_key 4092 NOEXIST::FUNCTION: +CRYPTO_strdup 4093 EXIST::FUNCTION: +JPAKE_STEP3A_process 4094 EXIST::FUNCTION:JPAKE +JPAKE_STEP1_release 4095 EXIST::FUNCTION:JPAKE +JPAKE_get_shared_key 4096 EXIST::FUNCTION:JPAKE +JPAKE_STEP3B_init 4097 EXIST::FUNCTION:JPAKE +JPAKE_STEP1_generate 4098 EXIST::FUNCTION:JPAKE +JPAKE_STEP1_init 4099 EXIST::FUNCTION:JPAKE +JPAKE_STEP3B_process 4100 EXIST::FUNCTION:JPAKE +JPAKE_STEP2_generate 4101 EXIST::FUNCTION:JPAKE +JPAKE_CTX_new 4102 EXIST::FUNCTION:JPAKE +JPAKE_CTX_free 4103 EXIST::FUNCTION:JPAKE +JPAKE_STEP3B_release 4104 EXIST::FUNCTION:JPAKE +JPAKE_STEP3A_release 4105 EXIST::FUNCTION:JPAKE +JPAKE_STEP2_process 4106 EXIST::FUNCTION:JPAKE +JPAKE_STEP3B_generate 4107 EXIST::FUNCTION:JPAKE +JPAKE_STEP1_process 4108 EXIST::FUNCTION:JPAKE +JPAKE_STEP3A_generate 4109 EXIST::FUNCTION:JPAKE +JPAKE_STEP2_release 4110 EXIST::FUNCTION:JPAKE +JPAKE_STEP3A_init 4111 EXIST::FUNCTION:JPAKE +ERR_load_JPAKE_strings 4112 EXIST::FUNCTION:JPAKE +JPAKE_STEP2_init 4113 EXIST::FUNCTION:JPAKE +pqueue_size 4114 EXIST::FUNCTION: +i2d_TS_ACCURACY 4115 EXIST::FUNCTION: +i2d_TS_MSG_IMPRINT_fp 4116 EXIST::FUNCTION: +i2d_TS_MSG_IMPRINT 4117 EXIST::FUNCTION: +EVP_PKEY_print_public 4118 EXIST::FUNCTION: +EVP_PKEY_CTX_new 4119 EXIST::FUNCTION: +i2d_TS_TST_INFO 4120 EXIST::FUNCTION: +EVP_PKEY_asn1_find 4121 EXIST::FUNCTION: +DSO_METHOD_beos 4122 EXIST::FUNCTION: +TS_CONF_load_cert 4123 EXIST::FUNCTION: +TS_REQ_get_ext 4124 EXIST::FUNCTION: +EVP_PKEY_sign_init 4125 EXIST::FUNCTION: +ASN1_item_print 4126 EXIST::FUNCTION: +TS_TST_INFO_set_nonce 4127 EXIST::FUNCTION: +TS_RESP_dup 4128 EXIST::FUNCTION: +ENGINE_register_pkey_meths 4129 EXIST::FUNCTION:ENGINE +EVP_PKEY_asn1_add0 4130 EXIST::FUNCTION: +PKCS7_add0_attrib_signing_time 4131 EXIST::FUNCTION: +i2d_TS_TST_INFO_fp 4132 EXIST::FUNCTION: +BIO_asn1_get_prefix 4133 EXIST::FUNCTION: +TS_TST_INFO_set_time 4134 EXIST::FUNCTION: +EVP_PKEY_meth_set_decrypt 4135 EXIST::FUNCTION: +EVP_PKEY_set_type_str 4136 EXIST::FUNCTION: +EVP_PKEY_CTX_get_keygen_info 4137 EXIST::FUNCTION: +TS_REQ_set_policy_id 4138 EXIST::FUNCTION: +d2i_TS_RESP_fp 4139 EXIST::FUNCTION: +ENGINE_get_pkey_asn1_meth_engine 4140 EXIST:!VMS:FUNCTION:ENGINE +ENGINE_get_pkey_asn1_meth_eng 4140 EXIST:VMS:FUNCTION:ENGINE +WHIRLPOOL_Init 4141 EXIST:!VMSVAX:FUNCTION:WHIRLPOOL +TS_RESP_set_status_info 4142 EXIST::FUNCTION: +EVP_PKEY_keygen 4143 EXIST::FUNCTION: +EVP_DigestSignInit 4144 EXIST::FUNCTION: +TS_ACCURACY_set_millis 4145 EXIST::FUNCTION: +TS_REQ_dup 4146 EXIST::FUNCTION: +GENERAL_NAME_dup 4147 EXIST::FUNCTION: +ASN1_SEQUENCE_ANY_it 4148 EXIST:!EXPORT_VAR_AS_FUNCTION:VARIABLE: +ASN1_SEQUENCE_ANY_it 4148 EXIST:EXPORT_VAR_AS_FUNCTION:FUNCTION: +WHIRLPOOL 4149 EXIST:!VMSVAX:FUNCTION:WHIRLPOOL +X509_STORE_get1_crls 4150 EXIST::FUNCTION: +ENGINE_get_pkey_asn1_meth 4151 EXIST::FUNCTION:ENGINE +EVP_PKEY_asn1_new 4152 EXIST::FUNCTION: +BIO_new_NDEF 4153 EXIST::FUNCTION: +ENGINE_get_pkey_meth 4154 EXIST::FUNCTION:ENGINE +TS_MSG_IMPRINT_set_algo 4155 EXIST::FUNCTION: +i2d_TS_TST_INFO_bio 4156 EXIST::FUNCTION: +TS_TST_INFO_set_ordering 4157 EXIST::FUNCTION: +TS_TST_INFO_get_ext_by_OBJ 4158 EXIST::FUNCTION: +CRYPTO_THREADID_set_pointer 4159 EXIST::FUNCTION: +TS_CONF_get_tsa_section 4160 EXIST::FUNCTION: +SMIME_write_ASN1 4161 EXIST::FUNCTION: +TS_RESP_CTX_set_signer_key 4162 EXIST::FUNCTION: +EVP_PKEY_encrypt_old 4163 EXIST::FUNCTION: +EVP_PKEY_encrypt_init 4164 EXIST::FUNCTION: +CRYPTO_THREADID_cpy 4165 EXIST::FUNCTION: +ASN1_PCTX_get_cert_flags 4166 EXIST::FUNCTION: +i2d_ESS_SIGNING_CERT 4167 EXIST::FUNCTION: +TS_CONF_load_key 4168 EXIST::FUNCTION: +i2d_ASN1_SEQUENCE_ANY 4169 EXIST::FUNCTION: +d2i_TS_MSG_IMPRINT_bio 4170 EXIST::FUNCTION: +EVP_PKEY_asn1_set_public 4171 EXIST::FUNCTION: +b2i_PublicKey_bio 4172 EXIST::FUNCTION: +BIO_asn1_set_prefix 4173 EXIST::FUNCTION: +EVP_PKEY_new_mac_key 4174 EXIST::FUNCTION: +BIO_new_CMS 4175 EXIST::FUNCTION:CMS +CRYPTO_THREADID_cmp 4176 EXIST::FUNCTION: +TS_REQ_ext_free 4177 EXIST::FUNCTION: +EVP_PKEY_asn1_set_free 4178 EXIST::FUNCTION: +EVP_PKEY_get0_asn1 4179 EXIST::FUNCTION: +d2i_NETSCAPE_X509 4180 EXIST::FUNCTION: +EVP_PKEY_verify_recover_init 4181 EXIST::FUNCTION: +EVP_PKEY_CTX_set_data 4182 EXIST::FUNCTION: +EVP_PKEY_keygen_init 4183 EXIST::FUNCTION: +TS_RESP_CTX_set_status_info 4184 EXIST::FUNCTION: +TS_MSG_IMPRINT_get_algo 4185 EXIST::FUNCTION: +TS_REQ_print_bio 4186 EXIST::FUNCTION: +EVP_PKEY_CTX_ctrl_str 4187 EXIST::FUNCTION: +EVP_PKEY_get_default_digest_nid 4188 EXIST::FUNCTION: +PEM_write_bio_PKCS7_stream 4189 EXIST::FUNCTION: +TS_MSG_IMPRINT_print_bio 4190 EXIST::FUNCTION: +BN_asc2bn 4191 EXIST::FUNCTION: +TS_REQ_get_policy_id 4192 EXIST::FUNCTION: +ENGINE_set_default_pkey_asn1_meths 4193 EXIST:!VMS:FUNCTION:ENGINE +ENGINE_set_def_pkey_asn1_meths 4193 EXIST:VMS:FUNCTION:ENGINE +d2i_TS_ACCURACY 4194 EXIST::FUNCTION: +DSO_global_lookup 4195 EXIST::FUNCTION: +TS_CONF_set_tsa_name 4196 EXIST::FUNCTION: +i2d_ASN1_SET_ANY 4197 EXIST::FUNCTION: +ENGINE_load_gost 4198 EXIST::FUNCTION:ENGINE,GOST,STATIC_ENGINE +WHIRLPOOL_BitUpdate 4199 EXIST:!VMSVAX:FUNCTION:WHIRLPOOL +ASN1_PCTX_get_flags 4200 EXIST::FUNCTION: +TS_TST_INFO_get_ext_by_NID 4201 EXIST::FUNCTION: +TS_RESP_new 4202 EXIST::FUNCTION: +ESS_CERT_ID_dup 4203 EXIST::FUNCTION: +TS_STATUS_INFO_dup 4204 EXIST::FUNCTION: +TS_REQ_delete_ext 4205 EXIST::FUNCTION: +EVP_DigestVerifyFinal 4206 EXIST::FUNCTION: +EVP_PKEY_print_params 4207 EXIST::FUNCTION: +i2d_CMS_bio_stream 4208 EXIST::FUNCTION:CMS +TS_REQ_get_msg_imprint 4209 EXIST::FUNCTION: +OBJ_find_sigid_by_algs 4210 EXIST::FUNCTION: +TS_TST_INFO_get_serial 4211 EXIST::FUNCTION: +TS_REQ_get_nonce 4212 EXIST::FUNCTION: +X509_PUBKEY_set0_param 4213 EXIST::FUNCTION: +EVP_PKEY_CTX_set0_keygen_info 4214 EXIST::FUNCTION: +DIST_POINT_set_dpname 4215 EXIST::FUNCTION: +i2d_ISSUING_DIST_POINT 4216 EXIST::FUNCTION: +ASN1_SET_ANY_it 4217 EXIST:!EXPORT_VAR_AS_FUNCTION:VARIABLE: +ASN1_SET_ANY_it 4217 EXIST:EXPORT_VAR_AS_FUNCTION:FUNCTION: +EVP_PKEY_CTX_get_data 4218 EXIST::FUNCTION: +TS_STATUS_INFO_print_bio 4219 EXIST::FUNCTION: +EVP_PKEY_derive_init 4220 EXIST::FUNCTION: +d2i_TS_TST_INFO 4221 EXIST::FUNCTION: +EVP_PKEY_asn1_add_alias 4222 EXIST::FUNCTION: +d2i_TS_RESP_bio 4223 EXIST::FUNCTION: +OTHERNAME_cmp 4224 EXIST::FUNCTION: +GENERAL_NAME_set0_value 4225 EXIST::FUNCTION: +PKCS7_RECIP_INFO_get0_alg 4226 EXIST::FUNCTION: +TS_RESP_CTX_new 4227 EXIST::FUNCTION: +TS_RESP_set_tst_info 4228 EXIST::FUNCTION: +PKCS7_final 4229 EXIST::FUNCTION: +EVP_PKEY_base_id 4230 EXIST::FUNCTION: +TS_RESP_CTX_set_signer_cert 4231 EXIST::FUNCTION: +TS_REQ_set_msg_imprint 4232 EXIST::FUNCTION: +EVP_PKEY_CTX_ctrl 4233 EXIST::FUNCTION: +TS_CONF_set_digests 4234 EXIST::FUNCTION: +d2i_TS_MSG_IMPRINT 4235 EXIST::FUNCTION: +EVP_PKEY_meth_set_ctrl 4236 EXIST::FUNCTION: +TS_REQ_get_ext_by_NID 4237 EXIST::FUNCTION: +PKCS5_pbe_set0_algor 4238 EXIST::FUNCTION: +BN_BLINDING_thread_id 4239 EXIST::FUNCTION: +TS_ACCURACY_new 4240 EXIST::FUNCTION: +X509_CRL_METHOD_free 4241 EXIST::FUNCTION: +ASN1_PCTX_get_nm_flags 4242 EXIST::FUNCTION: +EVP_PKEY_meth_set_sign 4243 EXIST::FUNCTION: +CRYPTO_THREADID_current 4244 EXIST::FUNCTION: +EVP_PKEY_decrypt_init 4245 EXIST::FUNCTION: +NETSCAPE_X509_free 4246 EXIST::FUNCTION: +i2b_PVK_bio 4247 EXIST::FUNCTION:RC4 +EVP_PKEY_print_private 4248 EXIST::FUNCTION: +GENERAL_NAME_get0_value 4249 EXIST::FUNCTION: +b2i_PVK_bio 4250 EXIST::FUNCTION:RC4 +ASN1_UTCTIME_adj 4251 EXIST::FUNCTION: +TS_TST_INFO_new 4252 EXIST::FUNCTION: +EVP_MD_do_all_sorted 4253 EXIST::FUNCTION: +TS_CONF_set_default_engine 4254 EXIST::FUNCTION: +TS_ACCURACY_set_seconds 4255 EXIST::FUNCTION: +TS_TST_INFO_get_time 4256 EXIST::FUNCTION: +PKCS8_pkey_get0 4257 EXIST::FUNCTION: +EVP_PKEY_asn1_get0 4258 EXIST::FUNCTION: +OBJ_add_sigid 4259 EXIST::FUNCTION: +PKCS7_SIGNER_INFO_sign 4260 EXIST::FUNCTION: +EVP_PKEY_paramgen_init 4261 EXIST::FUNCTION: +EVP_PKEY_sign 4262 EXIST::FUNCTION: +OBJ_sigid_free 4263 EXIST::FUNCTION: +EVP_PKEY_meth_set_init 4264 EXIST::FUNCTION: +d2i_ESS_ISSUER_SERIAL 4265 EXIST::FUNCTION: +ISSUING_DIST_POINT_new 4266 EXIST::FUNCTION: +ASN1_TIME_adj 4267 EXIST::FUNCTION: +TS_OBJ_print_bio 4268 EXIST::FUNCTION: +EVP_PKEY_meth_set_verify_recover 4269 EXIST:!VMS:FUNCTION: +EVP_PKEY_meth_set_vrfy_recover 4269 EXIST:VMS:FUNCTION: +TS_RESP_get_status_info 4270 EXIST::FUNCTION: +CMS_stream 4271 EXIST::FUNCTION:CMS +EVP_PKEY_CTX_set_cb 4272 EXIST::FUNCTION: +PKCS7_to_TS_TST_INFO 4273 EXIST::FUNCTION: +ASN1_PCTX_get_oid_flags 4274 EXIST::FUNCTION: +TS_TST_INFO_add_ext 4275 EXIST::FUNCTION: +EVP_PKEY_meth_set_derive 4276 EXIST::FUNCTION: +i2d_TS_RESP_fp 4277 EXIST::FUNCTION: +i2d_TS_MSG_IMPRINT_bio 4278 EXIST::FUNCTION: +TS_RESP_CTX_set_accuracy 4279 EXIST::FUNCTION: +TS_REQ_set_nonce 4280 EXIST::FUNCTION: +ESS_CERT_ID_new 4281 EXIST::FUNCTION: +ENGINE_pkey_asn1_find_str 4282 EXIST::FUNCTION:ENGINE +TS_REQ_get_ext_count 4283 EXIST::FUNCTION: +BUF_reverse 4284 EXIST::FUNCTION: +TS_TST_INFO_print_bio 4285 EXIST::FUNCTION: +d2i_ISSUING_DIST_POINT 4286 EXIST::FUNCTION: +ENGINE_get_pkey_meths 4287 EXIST::FUNCTION:ENGINE +i2b_PrivateKey_bio 4288 EXIST::FUNCTION: +i2d_TS_RESP 4289 EXIST::FUNCTION: +b2i_PublicKey 4290 EXIST::FUNCTION: +TS_VERIFY_CTX_cleanup 4291 EXIST::FUNCTION: +TS_STATUS_INFO_free 4292 EXIST::FUNCTION: +TS_RESP_verify_token 4293 EXIST::FUNCTION: +OBJ_bsearch_ex_ 4294 EXIST::FUNCTION: +ASN1_bn_print 4295 EXIST::FUNCTION:BIO +EVP_PKEY_asn1_get_count 4296 EXIST::FUNCTION: +ENGINE_register_pkey_asn1_meths 4297 EXIST::FUNCTION:ENGINE +ASN1_PCTX_set_nm_flags 4298 EXIST::FUNCTION: +EVP_DigestVerifyInit 4299 EXIST::FUNCTION: +ENGINE_set_default_pkey_meths 4300 EXIST::FUNCTION:ENGINE +TS_TST_INFO_get_policy_id 4301 EXIST::FUNCTION: +TS_REQ_get_cert_req 4302 EXIST::FUNCTION: +X509_CRL_set_meth_data 4303 EXIST::FUNCTION: +PKCS8_pkey_set0 4304 EXIST::FUNCTION: +ASN1_STRING_copy 4305 EXIST::FUNCTION: +d2i_TS_TST_INFO_fp 4306 EXIST::FUNCTION: +X509_CRL_match 4307 EXIST::FUNCTION: +EVP_PKEY_asn1_set_private 4308 EXIST::FUNCTION: +TS_TST_INFO_get_ext_d2i 4309 EXIST::FUNCTION: +TS_RESP_CTX_add_policy 4310 EXIST::FUNCTION: +d2i_TS_RESP 4311 EXIST::FUNCTION: +TS_CONF_load_certs 4312 EXIST::FUNCTION: +TS_TST_INFO_get_msg_imprint 4313 EXIST::FUNCTION: +ERR_load_TS_strings 4314 EXIST::FUNCTION: +TS_TST_INFO_get_version 4315 EXIST::FUNCTION: +EVP_PKEY_CTX_dup 4316 EXIST::FUNCTION: +EVP_PKEY_meth_set_verify 4317 EXIST::FUNCTION: +i2b_PublicKey_bio 4318 EXIST::FUNCTION: +TS_CONF_set_certs 4319 EXIST::FUNCTION: +EVP_PKEY_asn1_get0_info 4320 EXIST::FUNCTION: +TS_VERIFY_CTX_free 4321 EXIST::FUNCTION: +TS_REQ_get_ext_by_critical 4322 EXIST::FUNCTION: +TS_RESP_CTX_set_serial_cb 4323 EXIST::FUNCTION: +X509_CRL_get_meth_data 4324 EXIST::FUNCTION: +TS_RESP_CTX_set_time_cb 4325 EXIST::FUNCTION: +TS_MSG_IMPRINT_get_msg 4326 EXIST::FUNCTION: +TS_TST_INFO_ext_free 4327 EXIST::FUNCTION: +TS_REQ_get_version 4328 EXIST::FUNCTION: +TS_REQ_add_ext 4329 EXIST::FUNCTION: +EVP_PKEY_CTX_set_app_data 4330 EXIST::FUNCTION: +OBJ_bsearch_ 4331 EXIST::FUNCTION: +EVP_PKEY_meth_set_verifyctx 4332 EXIST::FUNCTION: +i2d_PKCS7_bio_stream 4333 EXIST::FUNCTION: +CRYPTO_THREADID_set_numeric 4334 EXIST::FUNCTION: +PKCS7_sign_add_signer 4335 EXIST::FUNCTION: +d2i_TS_TST_INFO_bio 4336 EXIST::FUNCTION: +TS_TST_INFO_get_ordering 4337 EXIST::FUNCTION: +TS_RESP_print_bio 4338 EXIST::FUNCTION: +TS_TST_INFO_get_exts 4339 EXIST::FUNCTION: +HMAC_CTX_copy 4340 EXIST::FUNCTION:HMAC +PKCS5_pbe2_set_iv 4341 EXIST::FUNCTION: +ENGINE_get_pkey_asn1_meths 4342 EXIST::FUNCTION:ENGINE +b2i_PrivateKey 4343 EXIST::FUNCTION: +EVP_PKEY_CTX_get_app_data 4344 EXIST::FUNCTION: +TS_REQ_set_cert_req 4345 EXIST::FUNCTION: +CRYPTO_THREADID_set_callback 4346 EXIST::FUNCTION: +TS_CONF_set_serial 4347 EXIST::FUNCTION: +TS_TST_INFO_free 4348 EXIST::FUNCTION: +d2i_TS_REQ_fp 4349 EXIST::FUNCTION: +TS_RESP_verify_response 4350 EXIST::FUNCTION: +i2d_ESS_ISSUER_SERIAL 4351 EXIST::FUNCTION: +TS_ACCURACY_get_seconds 4352 EXIST::FUNCTION: +EVP_CIPHER_do_all 4353 EXIST::FUNCTION: +b2i_PrivateKey_bio 4354 EXIST::FUNCTION: +OCSP_CERTID_dup 4355 EXIST::FUNCTION: +X509_PUBKEY_get0_param 4356 EXIST::FUNCTION: +TS_MSG_IMPRINT_dup 4357 EXIST::FUNCTION: +PKCS7_print_ctx 4358 EXIST::FUNCTION: +i2d_TS_REQ_bio 4359 EXIST::FUNCTION: +EVP_whirlpool 4360 EXIST:!VMSVAX:FUNCTION:WHIRLPOOL +EVP_PKEY_asn1_set_param 4361 EXIST::FUNCTION: +EVP_PKEY_meth_set_encrypt 4362 EXIST::FUNCTION: +ASN1_PCTX_set_flags 4363 EXIST::FUNCTION: +i2d_ESS_CERT_ID 4364 EXIST::FUNCTION: +TS_VERIFY_CTX_new 4365 EXIST::FUNCTION: +TS_RESP_CTX_set_extension_cb 4366 EXIST::FUNCTION: +ENGINE_register_all_pkey_meths 4367 EXIST::FUNCTION:ENGINE +TS_RESP_CTX_set_status_info_cond 4368 EXIST:!VMS:FUNCTION: +TS_RESP_CTX_set_stat_info_cond 4368 EXIST:VMS:FUNCTION: +EVP_PKEY_verify 4369 EXIST::FUNCTION: +WHIRLPOOL_Final 4370 EXIST:!VMSVAX:FUNCTION:WHIRLPOOL +X509_CRL_METHOD_new 4371 EXIST::FUNCTION: +EVP_DigestSignFinal 4372 EXIST::FUNCTION: +TS_RESP_CTX_set_def_policy 4373 EXIST::FUNCTION: +NETSCAPE_X509_it 4374 EXIST:!EXPORT_VAR_AS_FUNCTION:VARIABLE: +NETSCAPE_X509_it 4374 EXIST:EXPORT_VAR_AS_FUNCTION:FUNCTION: +TS_RESP_create_response 4375 EXIST::FUNCTION: +PKCS7_SIGNER_INFO_get0_algs 4376 EXIST::FUNCTION: +TS_TST_INFO_get_nonce 4377 EXIST::FUNCTION: +EVP_PKEY_decrypt_old 4378 EXIST::FUNCTION: +TS_TST_INFO_set_policy_id 4379 EXIST::FUNCTION: +TS_CONF_set_ess_cert_id_chain 4380 EXIST::FUNCTION: +EVP_PKEY_CTX_get0_pkey 4381 EXIST::FUNCTION: +d2i_TS_REQ 4382 EXIST::FUNCTION: +EVP_PKEY_asn1_find_str 4383 EXIST::FUNCTION: +BIO_f_asn1 4384 EXIST::FUNCTION: +ESS_SIGNING_CERT_new 4385 EXIST::FUNCTION: +EVP_PBE_find 4386 EXIST::FUNCTION: +X509_CRL_get0_by_cert 4387 EXIST::FUNCTION: +EVP_PKEY_derive 4388 EXIST::FUNCTION: +i2d_TS_REQ 4389 EXIST::FUNCTION: +TS_TST_INFO_delete_ext 4390 EXIST::FUNCTION: +ESS_ISSUER_SERIAL_free 4391 EXIST::FUNCTION: +ASN1_PCTX_set_str_flags 4392 EXIST::FUNCTION: +ENGINE_get_pkey_asn1_meth_str 4393 EXIST::FUNCTION:ENGINE +TS_CONF_set_signer_key 4394 EXIST::FUNCTION: +TS_ACCURACY_get_millis 4395 EXIST::FUNCTION: +TS_RESP_get_token 4396 EXIST::FUNCTION: +TS_ACCURACY_dup 4397 EXIST::FUNCTION: +ENGINE_register_all_pkey_asn1_meths 4398 EXIST:!VMS:FUNCTION:ENGINE +ENGINE_reg_all_pkey_asn1_meths 4398 EXIST:VMS:FUNCTION:ENGINE +X509_CRL_set_default_method 4399 EXIST::FUNCTION: +CRYPTO_THREADID_hash 4400 EXIST::FUNCTION: +CMS_ContentInfo_print_ctx 4401 EXIST::FUNCTION:CMS +TS_RESP_free 4402 EXIST::FUNCTION: +ISSUING_DIST_POINT_free 4403 EXIST::FUNCTION: +ESS_ISSUER_SERIAL_new 4404 EXIST::FUNCTION: +CMS_add1_crl 4405 EXIST::FUNCTION:CMS +PKCS7_add1_attrib_digest 4406 EXIST::FUNCTION: +TS_RESP_CTX_add_md 4407 EXIST::FUNCTION: +TS_TST_INFO_dup 4408 EXIST::FUNCTION: +ENGINE_set_pkey_asn1_meths 4409 EXIST::FUNCTION:ENGINE +PEM_write_bio_Parameters 4410 EXIST::FUNCTION: +TS_TST_INFO_get_accuracy 4411 EXIST::FUNCTION: +X509_CRL_get0_by_serial 4412 EXIST::FUNCTION: +TS_TST_INFO_set_version 4413 EXIST::FUNCTION: +TS_RESP_CTX_get_tst_info 4414 EXIST::FUNCTION: +TS_RESP_verify_signature 4415 EXIST::FUNCTION: +CRYPTO_THREADID_get_callback 4416 EXIST::FUNCTION: +TS_TST_INFO_get_tsa 4417 EXIST::FUNCTION: +TS_STATUS_INFO_new 4418 EXIST::FUNCTION: +EVP_PKEY_CTX_get_cb 4419 EXIST::FUNCTION: +TS_REQ_get_ext_d2i 4420 EXIST::FUNCTION: +GENERAL_NAME_set0_othername 4421 EXIST::FUNCTION: +TS_TST_INFO_get_ext_count 4422 EXIST::FUNCTION: +TS_RESP_CTX_get_request 4423 EXIST::FUNCTION: +i2d_NETSCAPE_X509 4424 EXIST::FUNCTION: +ENGINE_get_pkey_meth_engine 4425 EXIST::FUNCTION:ENGINE +EVP_PKEY_meth_set_signctx 4426 EXIST::FUNCTION: +EVP_PKEY_asn1_copy 4427 EXIST::FUNCTION: +ASN1_TYPE_cmp 4428 EXIST::FUNCTION: +EVP_CIPHER_do_all_sorted 4429 EXIST::FUNCTION: +EVP_PKEY_CTX_free 4430 EXIST::FUNCTION: +ISSUING_DIST_POINT_it 4431 EXIST:!EXPORT_VAR_AS_FUNCTION:VARIABLE: +ISSUING_DIST_POINT_it 4431 EXIST:EXPORT_VAR_AS_FUNCTION:FUNCTION: +d2i_TS_MSG_IMPRINT_fp 4432 EXIST::FUNCTION: +X509_STORE_get1_certs 4433 EXIST::FUNCTION: +EVP_PKEY_CTX_get_operation 4434 EXIST::FUNCTION: +d2i_ESS_SIGNING_CERT 4435 EXIST::FUNCTION: +TS_CONF_set_ordering 4436 EXIST::FUNCTION: +EVP_PBE_alg_add_type 4437 EXIST::FUNCTION: +TS_REQ_set_version 4438 EXIST::FUNCTION: +EVP_PKEY_get0 4439 EXIST::FUNCTION: +BIO_asn1_set_suffix 4440 EXIST::FUNCTION: +i2d_TS_STATUS_INFO 4441 EXIST::FUNCTION: +EVP_MD_do_all 4442 EXIST::FUNCTION: +TS_TST_INFO_set_accuracy 4443 EXIST::FUNCTION: +PKCS7_add_attrib_content_type 4444 EXIST::FUNCTION: +ERR_remove_thread_state 4445 EXIST::FUNCTION: +EVP_PKEY_meth_add0 4446 EXIST::FUNCTION: +TS_TST_INFO_set_tsa 4447 EXIST::FUNCTION: +EVP_PKEY_meth_new 4448 EXIST::FUNCTION: +WHIRLPOOL_Update 4449 EXIST:!VMSVAX:FUNCTION:WHIRLPOOL +TS_CONF_set_accuracy 4450 EXIST::FUNCTION: +ASN1_PCTX_set_oid_flags 4451 EXIST::FUNCTION: +ESS_SIGNING_CERT_dup 4452 EXIST::FUNCTION: +d2i_TS_REQ_bio 4453 EXIST::FUNCTION: +X509_time_adj_ex 4454 EXIST::FUNCTION: +TS_RESP_CTX_add_flags 4455 EXIST::FUNCTION: +d2i_TS_STATUS_INFO 4456 EXIST::FUNCTION: +TS_MSG_IMPRINT_set_msg 4457 EXIST::FUNCTION: +BIO_asn1_get_suffix 4458 EXIST::FUNCTION: +TS_REQ_free 4459 EXIST::FUNCTION: +EVP_PKEY_meth_free 4460 EXIST::FUNCTION: +TS_REQ_get_exts 4461 EXIST::FUNCTION: +TS_RESP_CTX_set_clock_precision_digits 4462 EXIST:!VMS:FUNCTION: +TS_RESP_CTX_set_clk_prec_digits 4462 EXIST:VMS:FUNCTION: +TS_RESP_CTX_add_failure_info 4463 EXIST::FUNCTION: +i2d_TS_RESP_bio 4464 EXIST::FUNCTION: +EVP_PKEY_CTX_get0_peerkey 4465 EXIST::FUNCTION: +PEM_write_bio_CMS_stream 4466 EXIST::FUNCTION:CMS +TS_REQ_new 4467 EXIST::FUNCTION: +TS_MSG_IMPRINT_new 4468 EXIST::FUNCTION: +EVP_PKEY_meth_find 4469 EXIST::FUNCTION: +EVP_PKEY_id 4470 EXIST::FUNCTION: +TS_TST_INFO_set_serial 4471 EXIST::FUNCTION: +a2i_GENERAL_NAME 4472 EXIST::FUNCTION: +TS_CONF_set_crypto_device 4473 EXIST::FUNCTION: +EVP_PKEY_verify_init 4474 EXIST::FUNCTION: +TS_CONF_set_policies 4475 EXIST::FUNCTION: +ASN1_PCTX_new 4476 EXIST::FUNCTION: +ESS_CERT_ID_free 4477 EXIST::FUNCTION: +ENGINE_unregister_pkey_meths 4478 EXIST::FUNCTION:ENGINE +TS_MSG_IMPRINT_free 4479 EXIST::FUNCTION: +TS_VERIFY_CTX_init 4480 EXIST::FUNCTION: +PKCS7_stream 4481 EXIST::FUNCTION: +TS_RESP_CTX_set_certs 4482 EXIST::FUNCTION: +TS_CONF_set_def_policy 4483 EXIST::FUNCTION: +ASN1_GENERALIZEDTIME_adj 4484 EXIST::FUNCTION: +NETSCAPE_X509_new 4485 EXIST::FUNCTION: +TS_ACCURACY_free 4486 EXIST::FUNCTION: +TS_RESP_get_tst_info 4487 EXIST::FUNCTION: +EVP_PKEY_derive_set_peer 4488 EXIST::FUNCTION: +PEM_read_bio_Parameters 4489 EXIST::FUNCTION: +TS_CONF_set_clock_precision_digits 4490 EXIST:!VMS:FUNCTION: +TS_CONF_set_clk_prec_digits 4490 EXIST:VMS:FUNCTION: +ESS_ISSUER_SERIAL_dup 4491 EXIST::FUNCTION: +TS_ACCURACY_get_micros 4492 EXIST::FUNCTION: +ASN1_PCTX_get_str_flags 4493 EXIST::FUNCTION: +NAME_CONSTRAINTS_check 4494 EXIST::FUNCTION: +ASN1_BIT_STRING_check 4495 EXIST::FUNCTION: +X509_check_akid 4496 EXIST::FUNCTION: +ENGINE_unregister_pkey_asn1_meths 4497 EXIST:!VMS:FUNCTION:ENGINE +ENGINE_unreg_pkey_asn1_meths 4497 EXIST:VMS:FUNCTION:ENGINE +ASN1_PCTX_free 4498 EXIST::FUNCTION: +PEM_write_bio_ASN1_stream 4499 EXIST::FUNCTION: +i2d_ASN1_bio_stream 4500 EXIST::FUNCTION: +TS_X509_ALGOR_print_bio 4501 EXIST::FUNCTION: +EVP_PKEY_meth_set_cleanup 4502 EXIST::FUNCTION: +EVP_PKEY_asn1_free 4503 EXIST::FUNCTION: +ESS_SIGNING_CERT_free 4504 EXIST::FUNCTION: +TS_TST_INFO_set_msg_imprint 4505 EXIST::FUNCTION: +GENERAL_NAME_cmp 4506 EXIST::FUNCTION: +d2i_ASN1_SET_ANY 4507 EXIST::FUNCTION: +ENGINE_set_pkey_meths 4508 EXIST::FUNCTION:ENGINE +i2d_TS_REQ_fp 4509 EXIST::FUNCTION: +d2i_ASN1_SEQUENCE_ANY 4510 EXIST::FUNCTION: +GENERAL_NAME_get0_otherName 4511 EXIST::FUNCTION: +d2i_ESS_CERT_ID 4512 EXIST::FUNCTION: +OBJ_find_sigid_algs 4513 EXIST::FUNCTION: +EVP_PKEY_meth_set_keygen 4514 EXIST::FUNCTION: +PKCS5_PBKDF2_HMAC 4515 EXIST::FUNCTION: +EVP_PKEY_paramgen 4516 EXIST::FUNCTION: +EVP_PKEY_meth_set_paramgen 4517 EXIST::FUNCTION: +BIO_new_PKCS7 4518 EXIST::FUNCTION: +EVP_PKEY_verify_recover 4519 EXIST::FUNCTION: +TS_ext_print_bio 4520 EXIST::FUNCTION: +TS_ASN1_INTEGER_print_bio 4521 EXIST::FUNCTION: +check_defer 4522 EXIST::FUNCTION: +DSO_pathbyaddr 4523 EXIST::FUNCTION: +EVP_PKEY_set_type 4524 EXIST::FUNCTION: +TS_ACCURACY_set_micros 4525 EXIST::FUNCTION: +TS_REQ_to_TS_VERIFY_CTX 4526 EXIST::FUNCTION: +EVP_PKEY_meth_set_copy 4527 EXIST::FUNCTION: +ASN1_PCTX_set_cert_flags 4528 EXIST::FUNCTION: +TS_TST_INFO_get_ext 4529 EXIST::FUNCTION: +EVP_PKEY_asn1_set_ctrl 4530 EXIST::FUNCTION: +TS_TST_INFO_get_ext_by_critical 4531 EXIST::FUNCTION: +EVP_PKEY_CTX_new_id 4532 EXIST::FUNCTION: +TS_REQ_get_ext_by_OBJ 4533 EXIST::FUNCTION: +TS_CONF_set_signer_cert 4534 EXIST::FUNCTION: +X509_NAME_hash_old 4535 EXIST::FUNCTION: +ASN1_TIME_set_string 4536 EXIST::FUNCTION: +EVP_MD_flags 4537 EXIST::FUNCTION: +TS_RESP_CTX_free 4538 EXIST::FUNCTION: +DSAparams_dup 4539 EXIST::FUNCTION:DSA +DHparams_dup 4540 EXIST::FUNCTION:DH +OCSP_REQ_CTX_add1_header 4541 EXIST::FUNCTION: +OCSP_REQ_CTX_set1_req 4542 EXIST::FUNCTION: +X509_STORE_set_verify_cb 4543 EXIST::FUNCTION: +X509_STORE_CTX_get0_current_crl 4544 EXIST::FUNCTION: +X509_STORE_CTX_get0_parent_ctx 4545 EXIST::FUNCTION: +X509_STORE_CTX_get0_current_issuer 4546 EXIST:!VMS:FUNCTION: +X509_STORE_CTX_get0_cur_issuer 4546 EXIST:VMS:FUNCTION: +X509_issuer_name_hash_old 4547 EXIST::FUNCTION:MD5 +X509_subject_name_hash_old 4548 EXIST::FUNCTION:MD5 +EVP_CIPHER_CTX_copy 4549 EXIST::FUNCTION: +UI_method_get_prompt_constructor 4550 EXIST:!VMS:FUNCTION: +UI_method_get_prompt_constructr 4550 EXIST:VMS:FUNCTION: +UI_method_set_prompt_constructor 4551 EXIST:!VMS:FUNCTION: +UI_method_set_prompt_constructr 4551 EXIST:VMS:FUNCTION: +EVP_read_pw_string_min 4552 EXIST::FUNCTION: +CRYPTO_cts128_encrypt 4553 EXIST::FUNCTION: +CRYPTO_cts128_decrypt_block 4554 EXIST::FUNCTION: +CRYPTO_cfb128_1_encrypt 4555 EXIST::FUNCTION: +CRYPTO_cbc128_encrypt 4556 EXIST::FUNCTION: +CRYPTO_ctr128_encrypt 4557 EXIST::FUNCTION: +CRYPTO_ofb128_encrypt 4558 EXIST::FUNCTION: +CRYPTO_cts128_decrypt 4559 EXIST::FUNCTION: +CRYPTO_cts128_encrypt_block 4560 EXIST::FUNCTION: +CRYPTO_cbc128_decrypt 4561 EXIST::FUNCTION: +CRYPTO_cfb128_encrypt 4562 EXIST::FUNCTION: +CRYPTO_cfb128_8_encrypt 4563 EXIST::FUNCTION: +OPENSSL_strcasecmp 4564 EXIST::FUNCTION: +OPENSSL_memcmp 4565 EXIST::FUNCTION: +OPENSSL_strncasecmp 4566 EXIST::FUNCTION: +OPENSSL_gmtime 4567 EXIST::FUNCTION: +OPENSSL_gmtime_adj 4568 EXIST::FUNCTION: diff --git a/node-v0.8.14/deps/openssl/openssl/util/mk1mf.pl b/node-v0.8.14/deps/openssl/openssl/util/mk1mf.pl new file mode 100755 index 0000000..afe8c73 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/util/mk1mf.pl @@ -0,0 +1,1164 @@ +#!/usr/local/bin/perl +# A bit of an evil hack but it post processes the file ../MINFO which +# is generated by `make files` in the top directory. +# This script outputs one mega makefile that has no shell stuff or any +# funny stuff +# + +$INSTALLTOP="/usr/local/ssl"; +$OPENSSLDIR="/usr/local/ssl"; +$OPTIONS=""; +$ssl_version=""; +$banner="\t\@echo Building OpenSSL"; + +my $no_static_engine = 1; +my $engines = ""; +my $otherlibs = ""; +local $zlib_opt = 0; # 0 = no zlib, 1 = static, 2 = dynamic +local $zlib_lib = ""; +local $perl_asm = 0; # 1 to autobuild asm files from perl scripts + +# Options to import from top level Makefile + +my %mf_import = ( + VERSION => \$ssl_version, + OPTIONS => \$OPTIONS, + INSTALLTOP => \$INSTALLTOP, + OPENSSLDIR => \$OPENSSLDIR, + PLATFORM => \$mf_platform, + CFLAG => \$mf_cflag, + DEPFLAG => \$mf_depflag, + CPUID_OBJ => \$mf_cpuid_asm, + BN_ASM => \$mf_bn_asm, + DES_ENC => \$mf_des_asm, + AES_ENC => \$mf_aes_asm, + BF_ENC => \$mf_bf_asm, + CAST_ENC => \$mf_cast_asm, + RC4_ENC => \$mf_rc4_asm, + RC5_ENC => \$mf_rc5_asm, + MD5_ASM_OBJ => \$mf_md5_asm, + SHA1_ASM_OBJ => \$mf_sha_asm, + RMD160_ASM_OBJ => \$mf_rmd_asm, + WP_ASM_OBJ => \$mf_wp_asm, + CMLL_ENC => \$mf_cm_asm +); + + +open(IN,") { + my ($mf_opt, $mf_ref); + while (($mf_opt, $mf_ref) = each %mf_import) { + if (/^$mf_opt\s*=\s*(.*)$/) { + $$mf_ref = $1; + } + } +} +close(IN); + +$debug = 1 if $mf_platform =~ /^debug-/; + +die "Makefile is not the toplevel Makefile!\n" if $ssl_version eq ""; + +$infile="MINFO"; + +%ops=( + "VC-WIN32", "Microsoft Visual C++ [4-6] - Windows NT or 9X", + "VC-WIN64I", "Microsoft C/C++ - Win64/IA-64", + "VC-WIN64A", "Microsoft C/C++ - Win64/x64", + "VC-CE", "Microsoft eMbedded Visual C++ 3.0 - Windows CE ONLY", + "VC-NT", "Microsoft Visual C++ [4-6] - Windows NT ONLY", + "Mingw32", "GNU C++ - Windows NT or 9x", + "Mingw32-files", "Create files with DOS copy ...", + "BC-NT", "Borland C++ 4.5 - Windows NT", + "linux-elf","Linux elf", + "ultrix-mips","DEC mips ultrix", + "FreeBSD","FreeBSD distribution", + "OS2-EMX", "EMX GCC OS/2", + "netware-clib", "CodeWarrior for NetWare - CLib - with WinSock Sockets", + "netware-clib-bsdsock", "CodeWarrior for NetWare - CLib - with BSD Sockets", + "netware-libc", "CodeWarrior for NetWare - LibC - with WinSock Sockets", + "netware-libc-bsdsock", "CodeWarrior for NetWare - LibC - with BSD Sockets", + "default","cc under unix", + "auto", "auto detect from top level Makefile" + ); + +$platform=""; +my $xcflags=""; +foreach (@ARGV) + { + if (!&read_options && !defined($ops{$_})) + { + print STDERR "unknown option - $_\n"; + print STDERR "usage: perl mk1mf.pl [options] [system]\n"; + print STDERR "\nwhere [system] can be one of the following\n"; + foreach $i (sort keys %ops) + { printf STDERR "\t%-10s\t%s\n",$i,$ops{$i}; } + print STDERR <<"EOF"; +and [options] can be one of + no-md2 no-md4 no-md5 no-sha no-mdc2 - Skip this digest + no-ripemd + no-rc2 no-rc4 no-rc5 no-idea no-des - Skip this symetric cipher + no-bf no-cast no-aes no-camellia no-seed + no-rsa no-dsa no-dh - Skip this public key cipher + no-ssl2 no-ssl3 - Skip this version of SSL + just-ssl - remove all non-ssl keys/digest + no-asm - No x86 asm + no-krb5 - No KRB5 + no-ec - No EC + no-ecdsa - No ECDSA + no-ecdh - No ECDH + no-engine - No engine + no-hw - No hw + nasm - Use NASM for x86 asm + nw-nasm - Use NASM x86 asm for NetWare + nw-mwasm - Use Metrowerks x86 asm for NetWare + gaswin - Use GNU as with Mingw32 + no-socks - No socket code + no-err - No error strings + dll/shlib - Build shared libraries (MS) + debug - Debug build + profile - Profiling build + gcc - Use Gcc (unix) + +Values that can be set +TMP=tmpdir OUT=outdir SRC=srcdir BIN=binpath INC=header-outdir CC=C-compiler + +-L -l - extra library flags (unix) +- - extra 'cc' flags, + added (MS), or replace (unix) +EOF + exit(1); + } + $platform=$_; + } +foreach (grep(!/^$/, split(/ /, $OPTIONS))) + { + print STDERR "unknown option - $_\n" if !&read_options; + } + +$no_static_engine = 0 if (!$shlib); + +$no_mdc2=1 if ($no_des); + +$no_ssl3=1 if ($no_md5 || $no_sha); +$no_ssl3=1 if ($no_rsa && $no_dh); + +$no_ssl2=1 if ($no_md5); +$no_ssl2=1 if ($no_rsa); + +$out_def="out"; +$inc_def="outinc"; +$tmp_def="tmp"; + +$perl="perl" unless defined $perl; +$mkdir="-mkdir" unless defined $mkdir; + +($ssl,$crypto)=("ssl","crypto"); +$ranlib="echo ranlib"; + +$cc=(defined($VARS{'CC'}))?$VARS{'CC'}:'cc'; +$src_dir=(defined($VARS{'SRC'}))?$VARS{'SRC'}:'.'; +$bin_dir=(defined($VARS{'BIN'}))?$VARS{'BIN'}:''; + +# $bin_dir.=$o causes a core dump on my sparc :-( + + +$NT=0; + +push(@INC,"util/pl","pl"); + +if ($platform eq "auto") { + $platform = $mf_platform; + print STDERR "Imported platform $mf_platform\n"; +} + +if (($platform =~ /VC-(.+)/)) + { + $FLAVOR=$1; + $NT = 1 if $1 eq "NT"; + require 'VC-32.pl'; + } +elsif ($platform eq "Mingw32") + { + require 'Mingw32.pl'; + } +elsif ($platform eq "Mingw32-files") + { + require 'Mingw32f.pl'; + } +elsif ($platform eq "BC-NT") + { + $bc=1; + require 'BC-32.pl'; + } +elsif ($platform eq "FreeBSD") + { + require 'unix.pl'; + $cflags='-DTERMIO -D_ANSI_SOURCE -O2 -fomit-frame-pointer'; + } +elsif ($platform eq "linux-elf") + { + require "unix.pl"; + require "linux.pl"; + $unix=1; + } +elsif ($platform eq "ultrix-mips") + { + require "unix.pl"; + require "ultrix.pl"; + $unix=1; + } +elsif ($platform eq "OS2-EMX") + { + $wc=1; + require 'OS2-EMX.pl'; + } +elsif (($platform eq "netware-clib") || ($platform eq "netware-libc") || + ($platform eq "netware-clib-bsdsock") || ($platform eq "netware-libc-bsdsock")) + { + $LIBC=1 if $platform eq "netware-libc" || $platform eq "netware-libc-bsdsock"; + $BSDSOCK=1 if ($platform eq "netware-libc-bsdsock") || ($platform eq "netware-clib-bsdsock"); + require 'netware.pl'; + } +else + { + require "unix.pl"; + + $unix=1; + $cflags.=' -DTERMIO'; + } + +$out_dir=(defined($VARS{'OUT'}))?$VARS{'OUT'}:$out_def.($debug?".dbg":""); +$tmp_dir=(defined($VARS{'TMP'}))?$VARS{'TMP'}:$tmp_def.($debug?".dbg":""); +$inc_dir=(defined($VARS{'INC'}))?$VARS{'INC'}:$inc_def; + +$bin_dir=$bin_dir.$o unless ((substr($bin_dir,-1,1) eq $o) || ($bin_dir eq '')); + +$cflags= "$xcflags$cflags" if $xcflags ne ""; + +$cflags.=" -DOPENSSL_NO_IDEA" if $no_idea; +$cflags.=" -DOPENSSL_NO_AES" if $no_aes; +$cflags.=" -DOPENSSL_NO_CAMELLIA" if $no_camellia; +$cflags.=" -DOPENSSL_NO_SEED" if $no_seed; +$cflags.=" -DOPENSSL_NO_RC2" if $no_rc2; +$cflags.=" -DOPENSSL_NO_RC4" if $no_rc4; +$cflags.=" -DOPENSSL_NO_RC5" if $no_rc5; +$cflags.=" -DOPENSSL_NO_MD2" if $no_md2; +$cflags.=" -DOPENSSL_NO_MD4" if $no_md4; +$cflags.=" -DOPENSSL_NO_MD5" if $no_md5; +$cflags.=" -DOPENSSL_NO_SHA" if $no_sha; +$cflags.=" -DOPENSSL_NO_SHA1" if $no_sha1; +$cflags.=" -DOPENSSL_NO_RIPEMD" if $no_ripemd; +$cflags.=" -DOPENSSL_NO_MDC2" if $no_mdc2; +$cflags.=" -DOPENSSL_NO_BF" if $no_bf; +$cflags.=" -DOPENSSL_NO_CAST" if $no_cast; +$cflags.=" -DOPENSSL_NO_DES" if $no_des; +$cflags.=" -DOPENSSL_NO_RSA" if $no_rsa; +$cflags.=" -DOPENSSL_NO_DSA" if $no_dsa; +$cflags.=" -DOPENSSL_NO_DH" if $no_dh; +$cflags.=" -DOPENSSL_NO_WHIRLPOOL" if $no_whirlpool; +$cflags.=" -DOPENSSL_NO_SOCK" if $no_sock; +$cflags.=" -DOPENSSL_NO_SSL2" if $no_ssl2; +$cflags.=" -DOPENSSL_NO_SSL3" if $no_ssl3; +$cflags.=" -DOPENSSL_NO_TLSEXT" if $no_tlsext; +$cflags.=" -DOPENSSL_NO_CMS" if $no_cms; +$cflags.=" -DOPENSSL_NO_ERR" if $no_err; +$cflags.=" -DOPENSSL_NO_KRB5" if $no_krb5; +$cflags.=" -DOPENSSL_NO_EC" if $no_ec; +$cflags.=" -DOPENSSL_NO_ECDSA" if $no_ecdsa; +$cflags.=" -DOPENSSL_NO_ECDH" if $no_ecdh; +$cflags.=" -DOPENSSL_NO_GOST" if $no_gost; +$cflags.=" -DOPENSSL_NO_ENGINE" if $no_engine; +$cflags.=" -DOPENSSL_NO_HW" if $no_hw; +$cflags.=" -DOPENSSL_NO_JPAKE" if $no_jpake; +$cflags.= " -DZLIB" if $zlib_opt; +$cflags.= " -DZLIB_SHARED" if $zlib_opt == 2; + +if ($no_static_engine) + { + $cflags .= " -DOPENSSL_NO_STATIC_ENGINE"; + } +else + { + $cflags .= " -DOPENSSL_NO_DYNAMIC_ENGINE"; + } + +#$cflags.=" -DRSAref" if $rsaref ne ""; + +## if ($unix) +## { $cflags="$c_flags" if ($c_flags ne ""); } +##else + { $cflags="$c_flags$cflags" if ($c_flags ne ""); } + +$ex_libs="$l_flags$ex_libs" if ($l_flags ne ""); + + +%shlib_ex_cflags=("SSL" => " -DOPENSSL_BUILD_SHLIBSSL", + "CRYPTO" => " -DOPENSSL_BUILD_SHLIBCRYPTO"); + +if ($msdos) + { + $banner ="\t\@echo Make sure you have run 'perl Configure $platform' in the\n"; + $banner.="\t\@echo top level directory, if you don't have perl, you will\n"; + $banner.="\t\@echo need to probably edit crypto/bn/bn.h, check the\n"; + $banner.="\t\@echo documentation for details.\n"; + } + +# have to do this to allow $(CC) under unix +$link="$bin_dir$link" if ($link !~ /^\$/); + +$INSTALLTOP =~ s|/|$o|g; +$OPENSSLDIR =~ s|/|$o|g; + +############################################# +# We parse in input file and 'store' info for later printing. +open(IN,"<$infile") || die "unable to open $infile:$!\n"; +$_=; +for (;;) + { + chop; + + ($key,$val)=/^([^=]+)=(.*)/; + if ($key eq "RELATIVE_DIRECTORY") + { + if ($lib ne "") + { + $uc=$lib; + $uc =~ s/^lib(.*)\.a/$1/; + $uc =~ tr/a-z/A-Z/; + $lib_nam{$uc}=$uc; + $lib_obj{$uc}.=$libobj." "; + } + last if ($val eq "FINISHED"); + $lib=""; + $libobj=""; + $dir=$val; + } + + if ($key eq "KRB5_INCLUDES") + { $cflags .= " $val";} + + if ($key eq "ZLIB_INCLUDE") + { $cflags .= " $val" if $val ne "";} + + if ($key eq "LIBZLIB") + { $zlib_lib = "$val" if $val ne "";} + + if ($key eq "LIBKRB5") + { $ex_libs .= " $val" if $val ne "";} + + if ($key eq "TEST") + { $test.=&var_add($dir,$val, 0); } + + if (($key eq "PROGS") || ($key eq "E_OBJ")) + { $e_exe.=&var_add($dir,$val, 0); } + + if ($key eq "LIB") + { + $lib=$val; + $lib =~ s/^.*\/([^\/]+)$/$1/; + } + if ($key eq "LIBNAME" && $no_static_engine) + { + $lib=$val; + $lib =~ s/^.*\/([^\/]+)$/$1/; + $otherlibs .= " $lib"; + } + + if ($key eq "EXHEADER") + { $exheader.=&var_add($dir,$val, 1); } + + if ($key eq "HEADER") + { $header.=&var_add($dir,$val, 1); } + + if ($key eq "LIBOBJ" && ($dir ne "engines" || !$no_static_engine)) + { $libobj=&var_add($dir,$val, 0); } + if ($key eq "LIBNAMES" && $dir eq "engines" && $no_static_engine) + { $engines.=$val } + + if (!($_=)) + { $_="RELATIVE_DIRECTORY=FINISHED\n"; } + } +close(IN); + +if ($shlib) + { + $extra_install= <<"EOF"; + \$(CP) \"\$(O_SSL)\" \"\$(INSTALLTOP)${o}bin\" + \$(CP) \"\$(O_CRYPTO)\" \"\$(INSTALLTOP)${o}bin\" + \$(CP) \"\$(L_SSL)\" \"\$(INSTALLTOP)${o}lib\" + \$(CP) \"\$(L_CRYPTO)\" \"\$(INSTALLTOP)${o}lib\" +EOF + if ($no_static_engine) + { + $extra_install .= <<"EOF" + \$(MKDIR) \"\$(INSTALLTOP)${o}lib${o}engines\" + \$(CP) \"\$(E_SHLIB)\" \"\$(INSTALLTOP)${o}lib${o}engines\" +EOF + } + } +else + { + $extra_install= <<"EOF"; + \$(CP) \"\$(O_SSL)\" \"\$(INSTALLTOP)${o}lib\" + \$(CP) \"\$(O_CRYPTO)\" \"\$(INSTALLTOP)${o}lib\" +EOF + $ex_libs .= " $zlib_lib" if $zlib_opt == 1; + } + +$defs= <<"EOF"; +# This makefile has been automatically generated from the OpenSSL distribution. +# This single makefile will build the complete OpenSSL distribution and +# by default leave the 'intertesting' output files in .${o}out and the stuff +# that needs deleting in .${o}tmp. +# The file was generated by running 'make makefile.one', which +# does a 'make files', which writes all the environment variables from all +# the makefiles to the file call MINFO. This file is used by +# util${o}mk1mf.pl to generate makefile.one. +# The 'makefile per directory' system suites me when developing this +# library and also so I can 'distribute' indervidual library sections. +# The one monster makefile better suits building in non-unix +# environments. + +EOF + +$defs .= $preamble if defined $preamble; + +$defs.= <<"EOF"; +INSTALLTOP=$INSTALLTOP +OPENSSLDIR=$OPENSSLDIR + +# Set your compiler options +PLATFORM=$platform +CC=$bin_dir${cc} +CFLAG=$cflags +APP_CFLAG=$app_cflag +LIB_CFLAG=$lib_cflag +SHLIB_CFLAG=$shl_cflag +APP_EX_OBJ=$app_ex_obj +SHLIB_EX_OBJ=$shlib_ex_obj +# add extra libraries to this define, for solaris -lsocket -lnsl would +# be added +EX_LIBS=$ex_libs + +# The OpenSSL directory +SRC_D=$src_dir + +LINK=$link +LFLAGS=$lflags +RSC=$rsc + +# The output directory for everything intersting +OUT_D=$out_dir +# The output directory for all the temporary muck +TMP_D=$tmp_dir +# The output directory for the header files +INC_D=$inc_dir +INCO_D=$inc_dir${o}openssl + +PERL=$perl +CP=$cp +RM=$rm +RANLIB=$ranlib +MKDIR=$mkdir +MKLIB=$bin_dir$mklib +MLFLAGS=$mlflags +ASM=$bin_dir$asm + +###################################################### +# You should not need to touch anything below this point +###################################################### + +E_EXE=openssl +SSL=$ssl +CRYPTO=$crypto + +# BIN_D - Binary output directory +# TEST_D - Binary test file output directory +# LIB_D - library output directory +# ENG_D - dynamic engine output directory +# Note: if you change these point to different directories then uncomment out +# the lines around the 'NB' comment below. +# +BIN_D=\$(OUT_D) +TEST_D=\$(OUT_D) +LIB_D=\$(OUT_D) +ENG_D=\$(OUT_D) + +# INCL_D - local library directory +# OBJ_D - temp object file directory +OBJ_D=\$(TMP_D) +INCL_D=\$(TMP_D) + +O_SSL= \$(LIB_D)$o$plib\$(SSL)$shlibp +O_CRYPTO= \$(LIB_D)$o$plib\$(CRYPTO)$shlibp +SO_SSL= $plib\$(SSL)$so_shlibp +SO_CRYPTO= $plib\$(CRYPTO)$so_shlibp +L_SSL= \$(LIB_D)$o$plib\$(SSL)$libp +L_CRYPTO= \$(LIB_D)$o$plib\$(CRYPTO)$libp + +L_LIBS= \$(L_SSL) \$(L_CRYPTO) + +###################################################### +# Don't touch anything below this point +###################################################### + +INC=-I\$(INC_D) -I\$(INCL_D) +APP_CFLAGS=\$(INC) \$(CFLAG) \$(APP_CFLAG) +LIB_CFLAGS=\$(INC) \$(CFLAG) \$(LIB_CFLAG) +SHLIB_CFLAGS=\$(INC) \$(CFLAG) \$(LIB_CFLAG) \$(SHLIB_CFLAG) +LIBS_DEP=\$(O_CRYPTO) \$(O_SSL) + +############################################# +EOF + +$rules=<<"EOF"; +all: banner \$(TMP_D) \$(BIN_D) \$(TEST_D) \$(LIB_D) \$(INCO_D) headers lib exe + +banner: +$banner + +\$(TMP_D): + \$(MKDIR) \"\$(TMP_D)\" +# NB: uncomment out these lines if BIN_D, TEST_D and LIB_D are different +#\$(BIN_D): +# \$(MKDIR) \$(BIN_D) +# +#\$(TEST_D): +# \$(MKDIR) \$(TEST_D) + +\$(LIB_D): + \$(MKDIR) \"\$(LIB_D)\" + +\$(INCO_D): \$(INC_D) + \$(MKDIR) \"\$(INCO_D)\" + +\$(INC_D): + \$(MKDIR) \"\$(INC_D)\" + +headers: \$(HEADER) \$(EXHEADER) + @ + +lib: \$(LIBS_DEP) \$(E_SHLIB) + +exe: \$(T_EXE) \$(BIN_D)$o\$(E_EXE)$exep + +install: all + \$(MKDIR) \"\$(INSTALLTOP)\" + \$(MKDIR) \"\$(INSTALLTOP)${o}bin\" + \$(MKDIR) \"\$(INSTALLTOP)${o}include\" + \$(MKDIR) \"\$(INSTALLTOP)${o}include${o}openssl\" + \$(MKDIR) \"\$(INSTALLTOP)${o}lib\" + \$(CP) \"\$(INCO_D)${o}*.\[ch\]\" \"\$(INSTALLTOP)${o}include${o}openssl\" + \$(CP) \"\$(BIN_D)$o\$(E_EXE)$exep \$(INSTALLTOP)${o}bin\" + \$(MKDIR) \"\$(OPENSSLDIR)\" + \$(CP) apps${o}openssl.cnf \"\$(OPENSSLDIR)\" +$extra_install + + +test: \$(T_EXE) + cd \$(BIN_D) + ..${o}ms${o}test + +clean: + \$(RM) \$(TMP_D)$o*.* + +vclean: + \$(RM) \$(TMP_D)$o*.* + \$(RM) \$(OUT_D)$o*.* + +EOF + +my $platform_cpp_symbol = "MK1MF_PLATFORM_$platform"; +$platform_cpp_symbol =~ s/-/_/g; +if (open(IN,"crypto/buildinf.h")) + { + # Remove entry for this platform in existing file buildinf.h. + + my $old_buildinf_h = ""; + while () + { + if (/^\#ifdef $platform_cpp_symbol$/) + { + while () { last if (/^\#endif/); } + } + else + { + $old_buildinf_h .= $_; + } + } + close(IN); + + open(OUT,">crypto/buildinf.h") || die "Can't open buildinf.h"; + print OUT $old_buildinf_h; + close(OUT); + } + +open (OUT,">>crypto/buildinf.h") || die "Can't open buildinf.h"; +printf OUT < \$no_rc2, + "no-rc4" => \$no_rc4, + "no-rc5" => \$no_rc5, + "no-idea" => \$no_idea, + "no-aes" => \$no_aes, + "no-camellia" => \$no_camellia, + "no-seed" => \$no_seed, + "no-des" => \$no_des, + "no-bf" => \$no_bf, + "no-cast" => \$no_cast, + "no-md2" => \$no_md2, + "no-md4" => \$no_md4, + "no-md5" => \$no_md5, + "no-sha" => \$no_sha, + "no-sha1" => \$no_sha1, + "no-ripemd" => \$no_ripemd, + "no-mdc2" => \$no_mdc2, + "no-whirlpool" => \$no_whirlpool, + "no-patents" => + [\$no_rc2, \$no_rc4, \$no_rc5, \$no_idea, \$no_rsa], + "no-rsa" => \$no_rsa, + "no-dsa" => \$no_dsa, + "no-dh" => \$no_dh, + "no-hmac" => \$no_hmac, + "no-asm" => \$no_asm, + "nasm" => \$nasm, + "nw-nasm" => \$nw_nasm, + "nw-mwasm" => \$nw_mwasm, + "gaswin" => \$gaswin, + "no-ssl2" => \$no_ssl2, + "no-ssl3" => \$no_ssl3, + "no-tlsext" => \$no_tlsext, + "no-cms" => \$no_cms, + "no-jpake" => \$no_jpake, + "no-err" => \$no_err, + "no-sock" => \$no_sock, + "no-krb5" => \$no_krb5, + "no-ec" => \$no_ec, + "no-ecdsa" => \$no_ecdsa, + "no-ecdh" => \$no_ecdh, + "no-gost" => \$no_gost, + "no-engine" => \$no_engine, + "no-hw" => \$no_hw, + "just-ssl" => + [\$no_rc2, \$no_idea, \$no_des, \$no_bf, \$no_cast, + \$no_md2, \$no_sha, \$no_mdc2, \$no_dsa, \$no_dh, + \$no_ssl2, \$no_err, \$no_ripemd, \$no_rc5, + \$no_aes, \$no_camellia, \$no_seed], + "rsaref" => 0, + "gcc" => \$gcc, + "debug" => \$debug, + "profile" => \$profile, + "shlib" => \$shlib, + "dll" => \$shlib, + "shared" => 0, + "no-gmp" => 0, + "no-rfc3779" => 0, + "no-montasm" => 0, + "no-shared" => 0, + "no-store" => 0, + "no-zlib" => 0, + "no-zlib-dynamic" => 0, + ); + + if (exists $valid_options{$_}) + { + my $r = $valid_options{$_}; + if ( ref $r eq "SCALAR") + { $$r = 1;} + elsif ( ref $r eq "ARRAY") + { + my $r2; + foreach $r2 (@$r) + { + $$r2 = 1; + } + } + } + elsif (/^no-comp$/) { $xcflags = "-DOPENSSL_NO_COMP $xcflags"; } + elsif (/^enable-zlib$/) { $zlib_opt = 1 if $zlib_opt == 0 } + elsif (/^enable-zlib-dynamic$/) + { + $zlib_opt = 2; + } + elsif (/^no-static-engine/) + { + $no_static_engine = 1; + } + elsif (/^enable-static-engine/) + { + $no_static_engine = 0; + } + # There are also enable-xxx options which correspond to + # the no-xxx. Since the scalars are enabled by default + # these can be ignored. + elsif (/^enable-/) + { + my $t = $_; + $t =~ s/^enable/no/; + if (exists $valid_options{$t}) + {return 1;} + return 0; + } + # experimental-xxx is mostly like enable-xxx, but opensslconf.v + # will still set OPENSSL_NO_xxx unless we set OPENSSL_EXPERIMENTAL_xxx. + # (No need to fail if we don't know the algorithm -- this is for adventurous users only.) + elsif (/^experimental-/) + { + my $algo, $ALGO; + ($algo = $_) =~ s/^experimental-//; + ($ALGO = $algo) =~ tr/[a-z]/[A-Z]/; + + $xcflags="-DOPENSSL_EXPERIMENTAL_$ALGO $xcflags"; + + } + elsif (/^--with-krb5-flavor=(.*)$/) + { + my $krb5_flavor = $1; + if ($krb5_flavor =~ /^force-[Hh]eimdal$/) + { + $xcflags="-DKRB5_HEIMDAL $xcflags"; + } + elsif ($krb5_flavor =~ /^MIT/i) + { + $xcflags="-DKRB5_MIT $xcflags"; + if ($krb5_flavor =~ /^MIT[._-]*1[._-]*[01]/i) + { + $xcflags="-DKRB5_MIT_OLD11 $xcflags" + } + } + } + elsif (/^([^=]*)=(.*)$/){ $VARS{$1}=$2; } + elsif (/^-[lL].*$/) { $l_flags.="$_ "; } + elsif ((!/^-help/) && (!/^-h/) && (!/^-\?/) && /^-.*$/) + { $c_flags.="$_ "; } + else { return(0); } + return(1); + } diff --git a/node-v0.8.14/deps/openssl/openssl/util/mkcerts.sh b/node-v0.8.14/deps/openssl/openssl/util/mkcerts.sh new file mode 100755 index 0000000..0184fcb --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/util/mkcerts.sh @@ -0,0 +1,220 @@ +#!/bin/sh + +# This script will re-make all the required certs. +# cd apps +# sh ../util/mkcerts.sh +# mv ca-cert.pem pca-cert.pem ../certs +# cd .. +# cat certs/*.pem >>apps/server.pem +# cat certs/*.pem >>apps/server2.pem +# SSLEAY=`pwd`/apps/ssleay; export SSLEAY +# sh tools/c_rehash certs +# + +CAbits=1024 +SSLEAY="../apps/openssl" +CONF="-config ../apps/openssl.cnf" + +# create pca request. +echo creating $CAbits bit PCA cert request +$SSLEAY req $CONF \ + -new -md5 -newkey $CAbits \ + -keyout pca-key.pem \ + -out pca-req.pem -nodes >/dev/null </dev/null </dev/null </dev/null </dev/null <> pca-cert.pem +cat ca-key.pem >> ca-cert.pem +cat s512-key.pem >> server.pem +cat s1024key.pem >> server2.pem +cat c512-key.pem >> client.pem + +for i in pca-cert.pem ca-cert.pem server.pem server2.pem client.pem +do +$SSLEAY x509 -issuer -subject -in $i -noout >$$ +cat $$ +/bin/cat $i >>$$ +/bin/mv $$ $i +done + +#/bin/rm -f *key.pem *req.pem *.srl + +echo Finished + diff --git a/node-v0.8.14/deps/openssl/openssl/util/mkdef.pl b/node-v0.8.14/deps/openssl/openssl/util/mkdef.pl new file mode 100755 index 0000000..ab47329 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/util/mkdef.pl @@ -0,0 +1,1509 @@ +#!/usr/local/bin/perl -w +# +# generate a .def file +# +# It does this by parsing the header files and looking for the +# prototyped functions: it then prunes the output. +# +# Intermediary files are created, call libeay.num and ssleay.num,... +# Previously, they had the following format: +# +# routine-name nnnn +# +# But that isn't enough for a number of reasons, the first on being that +# this format is (needlessly) very Win32-centric, and even then... +# One of the biggest problems is that there's no information about what +# routines should actually be used, which varies with what crypto algorithms +# are disabled. Also, some operating systems (for example VMS with VAX C) +# need to keep track of the global variables as well as the functions. +# +# So, a remake of this script is done so as to include information on the +# kind of symbol it is (function or variable) and what algorithms they're +# part of. This will allow easy translating to .def files or the corresponding +# file in other operating systems (a .opt file for VMS, possibly with a .mar +# file). +# +# The format now becomes: +# +# routine-name nnnn info +# +# and the "info" part is actually a colon-separated string of fields with +# the following meaning: +# +# existence:platform:kind:algorithms +# +# - "existence" can be "EXIST" or "NOEXIST" depending on if the symbol is +# found somewhere in the source, +# - "platforms" is empty if it exists on all platforms, otherwise it contains +# comma-separated list of the platform, just as they are if the symbol exists +# for those platforms, or prepended with a "!" if not. This helps resolve +# symbol name variants for platforms where the names are too long for the +# compiler or linker, or if the systems is case insensitive and there is a +# clash, or the symbol is implemented differently (see +# EXPORT_VAR_AS_FUNCTION). This script assumes renaming of symbols is found +# in the file crypto/symhacks.h. +# The semantics for the platforms is that every item is checked against the +# environment. For the negative items ("!FOO"), if any of them is false +# (i.e. "FOO" is true) in the environment, the corresponding symbol can't be +# used. For the positive itms, if all of them are false in the environment, +# the corresponding symbol can't be used. Any combination of positive and +# negative items are possible, and of course leave room for some redundancy. +# - "kind" is "FUNCTION" or "VARIABLE". The meaning of that is obvious. +# - "algorithms" is a comma-separated list of algorithm names. This helps +# exclude symbols that are part of an algorithm that some user wants to +# exclude. +# + +my $debug=0; + +my $crypto_num= "util/libeay.num"; +my $ssl_num= "util/ssleay.num"; +my $libname; + +my $do_update = 0; +my $do_rewrite = 1; +my $do_crypto = 0; +my $do_ssl = 0; +my $do_ctest = 0; +my $do_ctestall = 0; +my $do_checkexist = 0; + +my $VMSVAX=0; +my $VMSNonVAX=0; +my $VMS=0; +my $W32=0; +my $W16=0; +my $NT=0; +my $OS2=0; +# Set this to make typesafe STACK definitions appear in DEF +my $safe_stack_def = 0; + +my @known_platforms = ( "__FreeBSD__", "PERL5", "NeXT", + "EXPORT_VAR_AS_FUNCTION", "ZLIB" ); +my @known_ossl_platforms = ( "VMS", "WIN16", "WIN32", "WINNT", "OS2" ); +my @known_algorithms = ( "RC2", "RC4", "RC5", "IDEA", "DES", "BF", + "CAST", "MD2", "MD4", "MD5", "SHA", "SHA0", "SHA1", + "SHA256", "SHA512", "RIPEMD", + "MDC2", "WHIRLPOOL", "RSA", "DSA", "DH", "EC", "ECDH", "ECDSA", + "HMAC", "AES", "CAMELLIA", "SEED", "GOST", + # Envelope "algorithms" + "EVP", "X509", "ASN1_TYPEDEFS", + # Helper "algorithms" + "BIO", "COMP", "BUFFER", "LHASH", "STACK", "ERR", + "LOCKING", + # External "algorithms" + "FP_API", "STDIO", "SOCK", "KRB5", "DGRAM", + # Engines + "STATIC_ENGINE", "ENGINE", "HW", "GMP", + # RFC3779 + "RFC3779", + # TLS + "TLSEXT", "PSK", + # CMS + "CMS", + # CryptoAPI Engine + "CAPIENG", + # SSL v2 + "SSL2", + # JPAKE + "JPAKE", + # Deprecated functions + "DEPRECATED" ); + +my $options=""; +open(IN,") { + $options=$1 if (/^OPTIONS=(.*)$/); +} +close(IN); + +# The following ciphers may be excluded (by Configure). This means functions +# defined with ifndef(NO_XXX) are not included in the .def file, and everything +# in directory xxx is ignored. +my $no_rc2; my $no_rc4; my $no_rc5; my $no_idea; my $no_des; my $no_bf; +my $no_cast; my $no_whirlpool; my $no_camellia; my $no_seed; +my $no_md2; my $no_md4; my $no_md5; my $no_sha; my $no_ripemd; my $no_mdc2; +my $no_rsa; my $no_dsa; my $no_dh; my $no_hmac=0; my $no_aes; my $no_krb5; +my $no_ec; my $no_ecdsa; my $no_ecdh; my $no_engine; my $no_hw; +my $no_fp_api; my $no_static_engine=1; my $no_gmp; my $no_deprecated; +my $no_rfc3779; my $no_psk; my $no_tlsext; my $no_cms; my $no_capieng; +my $no_jpake; my $no_ssl2; + +my $zlib; + + +foreach (@ARGV, split(/ /, $options)) + { + $debug=1 if $_ eq "debug"; + $W32=1 if $_ eq "32"; + $W16=1 if $_ eq "16"; + if($_ eq "NT") { + $W32 = 1; + $NT = 1; + } + if ($_ eq "VMS-VAX") { + $VMS=1; + $VMSVAX=1; + } + if ($_ eq "VMS-NonVAX") { + $VMS=1; + $VMSNonVAX=1; + } + $VMS=1 if $_ eq "VMS"; + $OS2=1 if $_ eq "OS2"; + if ($_ eq "zlib" || $_ eq "enable-zlib" || $_ eq "zlib-dynamic" + || $_ eq "enable-zlib-dynamic") { + $zlib = 1; + } + + $do_ssl=1 if $_ eq "ssleay"; + if ($_ eq "ssl") { + $do_ssl=1; + $libname=$_ + } + $do_crypto=1 if $_ eq "libeay"; + if ($_ eq "crypto") { + $do_crypto=1; + $libname=$_; + } + $no_static_engine=1 if $_ eq "no-static-engine"; + $no_static_engine=0 if $_ eq "enable-static-engine"; + $do_update=1 if $_ eq "update"; + $do_rewrite=1 if $_ eq "rewrite"; + $do_ctest=1 if $_ eq "ctest"; + $do_ctestall=1 if $_ eq "ctestall"; + $do_checkexist=1 if $_ eq "exist"; + #$safe_stack_def=1 if $_ eq "-DDEBUG_SAFESTACK"; + + if (/^no-rc2$/) { $no_rc2=1; } + elsif (/^no-rc4$/) { $no_rc4=1; } + elsif (/^no-rc5$/) { $no_rc5=1; } + elsif (/^no-idea$/) { $no_idea=1; } + elsif (/^no-des$/) { $no_des=1; $no_mdc2=1; } + elsif (/^no-bf$/) { $no_bf=1; } + elsif (/^no-cast$/) { $no_cast=1; } + elsif (/^no-whirlpool$/) { $no_whirlpool=1; } + elsif (/^no-md2$/) { $no_md2=1; } + elsif (/^no-md4$/) { $no_md4=1; } + elsif (/^no-md5$/) { $no_md5=1; } + elsif (/^no-sha$/) { $no_sha=1; } + elsif (/^no-ripemd$/) { $no_ripemd=1; } + elsif (/^no-mdc2$/) { $no_mdc2=1; } + elsif (/^no-rsa$/) { $no_rsa=1; } + elsif (/^no-dsa$/) { $no_dsa=1; } + elsif (/^no-dh$/) { $no_dh=1; } + elsif (/^no-ec$/) { $no_ec=1; } + elsif (/^no-ecdsa$/) { $no_ecdsa=1; } + elsif (/^no-ecdh$/) { $no_ecdh=1; } + elsif (/^no-hmac$/) { $no_hmac=1; } + elsif (/^no-aes$/) { $no_aes=1; } + elsif (/^no-camellia$/) { $no_camellia=1; } + elsif (/^no-seed$/) { $no_seed=1; } + elsif (/^no-evp$/) { $no_evp=1; } + elsif (/^no-lhash$/) { $no_lhash=1; } + elsif (/^no-stack$/) { $no_stack=1; } + elsif (/^no-err$/) { $no_err=1; } + elsif (/^no-buffer$/) { $no_buffer=1; } + elsif (/^no-bio$/) { $no_bio=1; } + #elsif (/^no-locking$/) { $no_locking=1; } + elsif (/^no-comp$/) { $no_comp=1; } + elsif (/^no-dso$/) { $no_dso=1; } + elsif (/^no-krb5$/) { $no_krb5=1; } + elsif (/^no-engine$/) { $no_engine=1; } + elsif (/^no-hw$/) { $no_hw=1; } + elsif (/^no-gmp$/) { $no_gmp=1; } + elsif (/^no-rfc3779$/) { $no_rfc3779=1; } + elsif (/^no-tlsext$/) { $no_tlsext=1; } + elsif (/^no-cms$/) { $no_cms=1; } + elsif (/^no-ssl2$/) { $no_ssl2=1; } + elsif (/^no-capieng$/) { $no_capieng=1; } + elsif (/^no-jpake$/) { $no_jpake=1; } + } + + +if (!$libname) { + if ($do_ssl) { + $libname="SSLEAY"; + } + if ($do_crypto) { + $libname="LIBEAY"; + } +} + +# If no platform is given, assume WIN32 +if ($W32 + $W16 + $VMS + $OS2 == 0) { + $W32 = 1; +} + +# Add extra knowledge +if ($W16) { + $no_fp_api=1; +} + +if (!$do_ssl && !$do_crypto) + { + print STDERR "usage: $0 ( ssl | crypto ) [ 16 | 32 | NT | OS2 ]\n"; + exit(1); + } + +%ssl_list=&load_numbers($ssl_num); +$max_ssl = $max_num; +%crypto_list=&load_numbers($crypto_num); +$max_crypto = $max_num; + +my $ssl="ssl/ssl.h"; +$ssl.=" ssl/kssl.h"; +$ssl.=" ssl/tls1.h"; + +my $crypto ="crypto/crypto.h"; +$crypto.=" crypto/o_dir.h"; +$crypto.=" crypto/o_str.h"; +$crypto.=" crypto/o_time.h"; +$crypto.=" crypto/des/des.h crypto/des/des_old.h" ; # unless $no_des; +$crypto.=" crypto/idea/idea.h" ; # unless $no_idea; +$crypto.=" crypto/rc4/rc4.h" ; # unless $no_rc4; +$crypto.=" crypto/rc5/rc5.h" ; # unless $no_rc5; +$crypto.=" crypto/rc2/rc2.h" ; # unless $no_rc2; +$crypto.=" crypto/bf/blowfish.h" ; # unless $no_bf; +$crypto.=" crypto/cast/cast.h" ; # unless $no_cast; +$crypto.=" crypto/whrlpool/whrlpool.h" ; +$crypto.=" crypto/md2/md2.h" ; # unless $no_md2; +$crypto.=" crypto/md4/md4.h" ; # unless $no_md4; +$crypto.=" crypto/md5/md5.h" ; # unless $no_md5; +$crypto.=" crypto/mdc2/mdc2.h" ; # unless $no_mdc2; +$crypto.=" crypto/sha/sha.h" ; # unless $no_sha; +$crypto.=" crypto/ripemd/ripemd.h" ; # unless $no_ripemd; +$crypto.=" crypto/aes/aes.h" ; # unless $no_aes; +$crypto.=" crypto/camellia/camellia.h" ; # unless $no_camellia; +$crypto.=" crypto/seed/seed.h"; # unless $no_seed; + +$crypto.=" crypto/bn/bn.h"; +$crypto.=" crypto/rsa/rsa.h" ; # unless $no_rsa; +$crypto.=" crypto/dsa/dsa.h" ; # unless $no_dsa; +$crypto.=" crypto/dh/dh.h" ; # unless $no_dh; +$crypto.=" crypto/ec/ec.h" ; # unless $no_ec; +$crypto.=" crypto/ecdsa/ecdsa.h" ; # unless $no_ecdsa; +$crypto.=" crypto/ecdh/ecdh.h" ; # unless $no_ecdh; +$crypto.=" crypto/hmac/hmac.h" ; # unless $no_hmac; + +$crypto.=" crypto/engine/engine.h"; # unless $no_engine; +$crypto.=" crypto/stack/stack.h" ; # unless $no_stack; +$crypto.=" crypto/buffer/buffer.h" ; # unless $no_buffer; +$crypto.=" crypto/bio/bio.h" ; # unless $no_bio; +$crypto.=" crypto/dso/dso.h" ; # unless $no_dso; +$crypto.=" crypto/lhash/lhash.h" ; # unless $no_lhash; +$crypto.=" crypto/conf/conf.h"; +$crypto.=" crypto/txt_db/txt_db.h"; + +$crypto.=" crypto/evp/evp.h" ; # unless $no_evp; +$crypto.=" crypto/objects/objects.h"; +$crypto.=" crypto/pem/pem.h"; +#$crypto.=" crypto/meth/meth.h"; +$crypto.=" crypto/asn1/asn1.h"; +$crypto.=" crypto/asn1/asn1t.h"; +$crypto.=" crypto/asn1/asn1_mac.h"; +$crypto.=" crypto/err/err.h" ; # unless $no_err; +$crypto.=" crypto/pkcs7/pkcs7.h"; +$crypto.=" crypto/pkcs12/pkcs12.h"; +$crypto.=" crypto/x509/x509.h"; +$crypto.=" crypto/x509/x509_vfy.h"; +$crypto.=" crypto/x509v3/x509v3.h"; +$crypto.=" crypto/ts/ts.h"; +$crypto.=" crypto/rand/rand.h"; +$crypto.=" crypto/comp/comp.h" ; # unless $no_comp; +$crypto.=" crypto/ocsp/ocsp.h"; +$crypto.=" crypto/ui/ui.h crypto/ui/ui_compat.h"; +$crypto.=" crypto/krb5/krb5_asn.h"; +#$crypto.=" crypto/store/store.h"; +$crypto.=" crypto/pqueue/pqueue.h"; +$crypto.=" crypto/cms/cms.h"; +$crypto.=" crypto/jpake/jpake.h"; +$crypto.=" crypto/modes/modes.h"; + +my $symhacks="crypto/symhacks.h"; + +my @ssl_symbols = &do_defs("SSLEAY", $ssl, $symhacks); +my @crypto_symbols = &do_defs("LIBEAY", $crypto, $symhacks); + +if ($do_update) { + +if ($do_ssl == 1) { + + &maybe_add_info("SSLEAY",*ssl_list,@ssl_symbols); + if ($do_rewrite == 1) { + open(OUT, ">$ssl_num"); + &rewrite_numbers(*OUT,"SSLEAY",*ssl_list,@ssl_symbols); + } else { + open(OUT, ">>$ssl_num"); + } + &update_numbers(*OUT,"SSLEAY",*ssl_list,$max_ssl,@ssl_symbols); + close OUT; +} + +if($do_crypto == 1) { + + &maybe_add_info("LIBEAY",*crypto_list,@crypto_symbols); + if ($do_rewrite == 1) { + open(OUT, ">$crypto_num"); + &rewrite_numbers(*OUT,"LIBEAY",*crypto_list,@crypto_symbols); + } else { + open(OUT, ">>$crypto_num"); + } + &update_numbers(*OUT,"LIBEAY",*crypto_list,$max_crypto,@crypto_symbols); + close OUT; +} + +} elsif ($do_checkexist) { + &check_existing(*ssl_list, @ssl_symbols) + if $do_ssl == 1; + &check_existing(*crypto_list, @crypto_symbols) + if $do_crypto == 1; +} elsif ($do_ctest || $do_ctestall) { + + print <<"EOF"; + +/* Test file to check all DEF file symbols are present by trying + * to link to all of them. This is *not* intended to be run! + */ + +int main() +{ +EOF + &print_test_file(*STDOUT,"SSLEAY",*ssl_list,$do_ctestall,@ssl_symbols) + if $do_ssl == 1; + + &print_test_file(*STDOUT,"LIBEAY",*crypto_list,$do_ctestall,@crypto_symbols) + if $do_crypto == 1; + + print "}\n"; + +} else { + + &print_def_file(*STDOUT,$libname,*ssl_list,@ssl_symbols) + if $do_ssl == 1; + + &print_def_file(*STDOUT,$libname,*crypto_list,@crypto_symbols) + if $do_crypto == 1; + +} + + +sub do_defs +{ + my($name,$files,$symhacksfile)=@_; + my $file; + my @ret; + my %syms; + my %platform; # For anything undefined, we assume "" + my %kind; # For anything undefined, we assume "FUNCTION" + my %algorithm; # For anything undefined, we assume "" + my %variant; + my %variant_cnt; # To be able to allocate "name{n}" if "name" + # is the same name as the original. + my $cpp; + my %unknown_algorithms = (); + + foreach $file (split(/\s+/,$symhacksfile." ".$files)) + { + print STDERR "DEBUG: starting on $file:\n" if $debug; + open(IN,"<$file") || die "unable to open $file:$!\n"; + my $line = "", my $def= ""; + my %tag = ( + (map { $_ => 0 } @known_platforms), + (map { "OPENSSL_SYS_".$_ => 0 } @known_ossl_platforms), + (map { "OPENSSL_NO_".$_ => 0 } @known_algorithms), + NOPROTO => 0, + PERL5 => 0, + _WINDLL => 0, + CONST_STRICT => 0, + TRUE => 1, + ); + my $symhacking = $file eq $symhacksfile; + my @current_platforms = (); + my @current_algorithms = (); + + # params: symbol, alias, platforms, kind + # The reason to put this subroutine in a variable is that + # it will otherwise create it's own, unshared, version of + # %tag and %variant... + my $make_variant = sub + { + my ($s, $a, $p, $k) = @_; + my ($a1, $a2); + + print STDERR "DEBUG: make_variant: Entered with ",$s,", ",$a,", ",(defined($p)?$p:""),", ",(defined($k)?$k:""),"\n" if $debug; + if (defined($p)) + { + $a1 = join(",",$p, + grep(!/^$/, + map { $tag{$_} == 1 ? $_ : "" } + @known_platforms)); + } + else + { + $a1 = join(",", + grep(!/^$/, + map { $tag{$_} == 1 ? $_ : "" } + @known_platforms)); + } + $a2 = join(",", + grep(!/^$/, + map { $tag{"OPENSSL_SYS_".$_} == 1 ? $_ : "" } + @known_ossl_platforms)); + print STDERR "DEBUG: make_variant: a1 = $a1; a2 = $a2\n" if $debug; + if ($a1 eq "") { $a1 = $a2; } + elsif ($a1 ne "" && $a2 ne "") { $a1 .= ",".$a2; } + if ($a eq $s) + { + if (!defined($variant_cnt{$s})) + { + $variant_cnt{$s} = 0; + } + $variant_cnt{$s}++; + $a .= "{$variant_cnt{$s}}"; + } + my $toadd = $a.":".$a1.(defined($k)?":".$k:""); + my $togrep = $s.'(\{[0-9]+\})?:'.$a1.(defined($k)?":".$k:""); + if (!grep(/^$togrep$/, + split(/;/, defined($variant{$s})?$variant{$s}:""))) { + if (defined($variant{$s})) { $variant{$s} .= ";"; } + $variant{$s} .= $toadd; + } + print STDERR "DEBUG: make_variant: Exit with variant of ",$s," = ",$variant{$s},"\n" if $debug; + }; + + print STDERR "DEBUG: parsing ----------\n" if $debug; + while() { + if (/\/\* Error codes for the \w+ functions\. \*\//) + { + undef @tag; + last; + } + if ($line ne '') { + $_ = $line . $_; + $line = ''; + } + + if (/\\$/) { + chomp; # remove eol + chop; # remove ending backslash + $line = $_; + next; + } + + if(/\/\*/) { + if (not /\*\//) { # multiline comment... + $line = $_; # ... just accumulate + next; + } else { + s/\/\*.*?\*\///gs;# wipe it + } + } + + if ($cpp) { + $cpp++ if /^#\s*if/; + $cpp-- if /^#\s*endif/; + next; + } + $cpp = 1 if /^#.*ifdef.*cplusplus/; + + s/{[^{}]*}//gs; # ignore {} blocks + print STDERR "DEBUG: \$def=\"$def\"\n" if $debug && $def ne ""; + print STDERR "DEBUG: \$_=\"$_\"\n" if $debug; + if (/^\#\s*ifndef\s+(.*)/) { + push(@tag,"-"); + push(@tag,$1); + $tag{$1}=-1; + print STDERR "DEBUG: $file: found tag $1 = -1\n" if $debug; + } elsif (/^\#\s*if\s+!defined\(([^\)]+)\)/) { + push(@tag,"-"); + if (/^\#\s*if\s+(!defined\(([^\)]+)\)(\s+\&\&\s+!defined\(([^\)]+)\))*)$/) { + my $tmp_1 = $1; + my $tmp_; + foreach $tmp_ (split '\&\&',$tmp_1) { + $tmp_ =~ /!defined\(([^\)]+)\)/; + print STDERR "DEBUG: $file: found tag $1 = -1\n" if $debug; + push(@tag,$1); + $tag{$1}=-1; + } + } else { + print STDERR "Warning: $file: complicated expression: $_" if $debug; # because it is O... + print STDERR "DEBUG: $file: found tag $1 = -1\n" if $debug; + push(@tag,$1); + $tag{$1}=-1; + } + } elsif (/^\#\s*ifdef\s+(\S*)/) { + push(@tag,"-"); + push(@tag,$1); + $tag{$1}=1; + print STDERR "DEBUG: $file: found tag $1 = 1\n" if $debug; + } elsif (/^\#\s*if\s+defined\(([^\)]+)\)/) { + push(@tag,"-"); + if (/^\#\s*if\s+(defined\(([^\)]+)\)(\s+\|\|\s+defined\(([^\)]+)\))*)$/) { + my $tmp_1 = $1; + my $tmp_; + foreach $tmp_ (split '\|\|',$tmp_1) { + $tmp_ =~ /defined\(([^\)]+)\)/; + print STDERR "DEBUG: $file: found tag $1 = 1\n" if $debug; + push(@tag,$1); + $tag{$1}=1; + } + } else { + print STDERR "Warning: $file: complicated expression: $_\n" if $debug; # because it is O... + print STDERR "DEBUG: $file: found tag $1 = 1\n" if $debug; + push(@tag,$1); + $tag{$1}=1; + } + } elsif (/^\#\s*error\s+(\w+) is disabled\./) { + my $tag_i = $#tag; + while($tag[$tag_i] ne "-") { + if ($tag[$tag_i] eq "OPENSSL_NO_".$1) { + $tag{$tag[$tag_i]}=2; + print STDERR "DEBUG: $file: chaged tag $1 = 2\n" if $debug; + } + $tag_i--; + } + } elsif (/^\#\s*endif/) { + my $tag_i = $#tag; + while($tag_i > 0 && $tag[$tag_i] ne "-") { + my $t=$tag[$tag_i]; + print STDERR "DEBUG: \$t=\"$t\"\n" if $debug; + if ($tag{$t}==2) { + $tag{$t}=-1; + } else { + $tag{$t}=0; + } + print STDERR "DEBUG: $file: changed tag ",$t," = ",$tag{$t},"\n" if $debug; + pop(@tag); + if ($t =~ /^OPENSSL_NO_([A-Z0-9_]+)$/) { + $t=$1; + } else { + $t=""; + } + if ($t ne "" + && !grep(/^$t$/, @known_algorithms)) { + $unknown_algorithms{$t} = 1; + #print STDERR "DEBUG: Added as unknown algorithm: $t\n" if $debug; + } + $tag_i--; + } + pop(@tag); + } elsif (/^\#\s*else/) { + my $tag_i = $#tag; + while($tag[$tag_i] ne "-") { + my $t=$tag[$tag_i]; + $tag{$t}= -$tag{$t}; + print STDERR "DEBUG: $file: changed tag ",$t," = ",$tag{$t},"\n" if $debug; + $tag_i--; + } + } elsif (/^\#\s*if\s+1/) { + push(@tag,"-"); + # Dummy tag + push(@tag,"TRUE"); + $tag{"TRUE"}=1; + print STDERR "DEBUG: $file: found 1\n" if $debug; + } elsif (/^\#\s*if\s+0/) { + push(@tag,"-"); + # Dummy tag + push(@tag,"TRUE"); + $tag{"TRUE"}=-1; + print STDERR "DEBUG: $file: found 0\n" if $debug; + } elsif (/^\#\s*define\s+(\w+)\s+(\w+)/ + && $symhacking && $tag{'TRUE'} != -1) { + # This is for aliasing. When we find an alias, + # we have to invert + &$make_variant($1,$2); + print STDERR "DEBUG: $file: defined $1 = $2\n" if $debug; + } + if (/^\#/) { + @current_platforms = + grep(!/^$/, + map { $tag{$_} == 1 ? $_ : + $tag{$_} == -1 ? "!".$_ : "" } + @known_platforms); + push @current_platforms + , grep(!/^$/, + map { $tag{"OPENSSL_SYS_".$_} == 1 ? $_ : + $tag{"OPENSSL_SYS_".$_} == -1 ? "!".$_ : "" } + @known_ossl_platforms); + @current_algorithms = + grep(!/^$/, + map { $tag{"OPENSSL_NO_".$_} == -1 ? $_ : "" } + @known_algorithms); + $def .= + "#INFO:" + .join(',',@current_platforms).":" + .join(',',@current_algorithms).";"; + next; + } + if ($tag{'TRUE'} != -1) { + if (/^\s*DECLARE_STACK_OF\s*\(\s*(\w*)\s*\)/) { + next; + } elsif (/^\s*DECLARE_ASN1_ENCODE_FUNCTIONS\s*\(\s*(\w*)\s*,\s*(\w*)\s*,\s*(\w*)\s*\)/) { + $def .= "int d2i_$3(void);"; + $def .= "int i2d_$3(void);"; + # Variant for platforms that do not + # have to access globale variables + # in shared libraries through functions + $def .= + "#INFO:" + .join(',',"!EXPORT_VAR_AS_FUNCTION",@current_platforms).":" + .join(',',@current_algorithms).";"; + $def .= "OPENSSL_EXTERN int $2_it;"; + $def .= + "#INFO:" + .join(',',@current_platforms).":" + .join(',',@current_algorithms).";"; + # Variant for platforms that have to + # access globale variables in shared + # libraries through functions + &$make_variant("$2_it","$2_it", + "EXPORT_VAR_AS_FUNCTION", + "FUNCTION"); + next; + } elsif (/^\s*DECLARE_ASN1_FUNCTIONS_fname\s*\(\s*(\w*)\s*,\s*(\w*)\s*,\s*(\w*)\s*\)/) { + $def .= "int d2i_$3(void);"; + $def .= "int i2d_$3(void);"; + $def .= "int $3_free(void);"; + $def .= "int $3_new(void);"; + # Variant for platforms that do not + # have to access globale variables + # in shared libraries through functions + $def .= + "#INFO:" + .join(',',"!EXPORT_VAR_AS_FUNCTION",@current_platforms).":" + .join(',',@current_algorithms).";"; + $def .= "OPENSSL_EXTERN int $2_it;"; + $def .= + "#INFO:" + .join(',',@current_platforms).":" + .join(',',@current_algorithms).";"; + # Variant for platforms that have to + # access globale variables in shared + # libraries through functions + &$make_variant("$2_it","$2_it", + "EXPORT_VAR_AS_FUNCTION", + "FUNCTION"); + next; + } elsif (/^\s*DECLARE_ASN1_FUNCTIONS\s*\(\s*(\w*)\s*\)/ || + /^\s*DECLARE_ASN1_FUNCTIONS_const\s*\(\s*(\w*)\s*\)/) { + $def .= "int d2i_$1(void);"; + $def .= "int i2d_$1(void);"; + $def .= "int $1_free(void);"; + $def .= "int $1_new(void);"; + # Variant for platforms that do not + # have to access globale variables + # in shared libraries through functions + $def .= + "#INFO:" + .join(',',"!EXPORT_VAR_AS_FUNCTION",@current_platforms).":" + .join(',',@current_algorithms).";"; + $def .= "OPENSSL_EXTERN int $1_it;"; + $def .= + "#INFO:" + .join(',',@current_platforms).":" + .join(',',@current_algorithms).";"; + # Variant for platforms that have to + # access globale variables in shared + # libraries through functions + &$make_variant("$1_it","$1_it", + "EXPORT_VAR_AS_FUNCTION", + "FUNCTION"); + next; + } elsif (/^\s*DECLARE_ASN1_ENCODE_FUNCTIONS_const\s*\(\s*(\w*)\s*,\s*(\w*)\s*\)/) { + $def .= "int d2i_$2(void);"; + $def .= "int i2d_$2(void);"; + # Variant for platforms that do not + # have to access globale variables + # in shared libraries through functions + $def .= + "#INFO:" + .join(',',"!EXPORT_VAR_AS_FUNCTION",@current_platforms).":" + .join(',',@current_algorithms).";"; + $def .= "OPENSSL_EXTERN int $2_it;"; + $def .= + "#INFO:" + .join(',',@current_platforms).":" + .join(',',@current_algorithms).";"; + # Variant for platforms that have to + # access globale variables in shared + # libraries through functions + &$make_variant("$2_it","$2_it", + "EXPORT_VAR_AS_FUNCTION", + "FUNCTION"); + next; + } elsif (/^\s*DECLARE_ASN1_ALLOC_FUNCTIONS\s*\(\s*(\w*)\s*\)/) { + $def .= "int $1_free(void);"; + $def .= "int $1_new(void);"; + next; + } elsif (/^\s*DECLARE_ASN1_FUNCTIONS_name\s*\(\s*(\w*)\s*,\s*(\w*)\s*\)/) { + $def .= "int d2i_$2(void);"; + $def .= "int i2d_$2(void);"; + $def .= "int $2_free(void);"; + $def .= "int $2_new(void);"; + # Variant for platforms that do not + # have to access globale variables + # in shared libraries through functions + $def .= + "#INFO:" + .join(',',"!EXPORT_VAR_AS_FUNCTION",@current_platforms).":" + .join(',',@current_algorithms).";"; + $def .= "OPENSSL_EXTERN int $2_it;"; + $def .= + "#INFO:" + .join(',',@current_platforms).":" + .join(',',@current_algorithms).";"; + # Variant for platforms that have to + # access globale variables in shared + # libraries through functions + &$make_variant("$2_it","$2_it", + "EXPORT_VAR_AS_FUNCTION", + "FUNCTION"); + next; + } elsif (/^\s*DECLARE_ASN1_ITEM\s*\(\s*(\w*)\s*\)/) { + # Variant for platforms that do not + # have to access globale variables + # in shared libraries through functions + $def .= + "#INFO:" + .join(',',"!EXPORT_VAR_AS_FUNCTION",@current_platforms).":" + .join(',',@current_algorithms).";"; + $def .= "OPENSSL_EXTERN int $1_it;"; + $def .= + "#INFO:" + .join(',',@current_platforms).":" + .join(',',@current_algorithms).";"; + # Variant for platforms that have to + # access globale variables in shared + # libraries through functions + &$make_variant("$1_it","$1_it", + "EXPORT_VAR_AS_FUNCTION", + "FUNCTION"); + next; + } elsif (/^\s*DECLARE_ASN1_NDEF_FUNCTION\s*\(\s*(\w*)\s*\)/) { + $def .= "int i2d_$1_NDEF(void);"; + } elsif (/^\s*DECLARE_ASN1_SET_OF\s*\(\s*(\w*)\s*\)/) { + next; + } elsif (/^\s*DECLARE_ASN1_PRINT_FUNCTION\s*\(\s*(\w*)\s*\)/) { + $def .= "int $1_print_ctx(void);"; + next; + } elsif (/^\s*DECLARE_ASN1_PRINT_FUNCTION_name\s*\(\s*(\w*)\s*,\s*(\w*)\s*\)/) { + $def .= "int $2_print_ctx(void);"; + next; + } elsif (/^\s*DECLARE_PKCS12_STACK_OF\s*\(\s*(\w*)\s*\)/) { + next; + } elsif (/^DECLARE_PEM_rw\s*\(\s*(\w*)\s*,/ || + /^DECLARE_PEM_rw_cb\s*\(\s*(\w*)\s*,/ || + /^DECLARE_PEM_rw_const\s*\(\s*(\w*)\s*,/ ) { + # Things not in Win16 + $def .= + "#INFO:" + .join(',',"!WIN16",@current_platforms).":" + .join(',',@current_algorithms).";"; + $def .= "int PEM_read_$1(void);"; + $def .= "int PEM_write_$1(void);"; + $def .= + "#INFO:" + .join(',',@current_platforms).":" + .join(',',@current_algorithms).";"; + # Things that are everywhere + $def .= "int PEM_read_bio_$1(void);"; + $def .= "int PEM_write_bio_$1(void);"; + next; + } elsif (/^DECLARE_PEM_write\s*\(\s*(\w*)\s*,/ || + /^DECLARE_PEM_write_cb\s*\(\s*(\w*)\s*,/ ) { + # Things not in Win16 + $def .= + "#INFO:" + .join(',',"!WIN16",@current_platforms).":" + .join(',',@current_algorithms).";"; + $def .= "int PEM_write_$1(void);"; + $def .= + "#INFO:" + .join(',',@current_platforms).":" + .join(',',@current_algorithms).";"; + # Things that are everywhere + $def .= "int PEM_write_bio_$1(void);"; + next; + } elsif (/^DECLARE_PEM_read\s*\(\s*(\w*)\s*,/ || + /^DECLARE_PEM_read_cb\s*\(\s*(\w*)\s*,/ ) { + # Things not in Win16 + $def .= + "#INFO:" + .join(',',"!WIN16",@current_platforms).":" + .join(',',@current_algorithms).";"; + $def .= "int PEM_read_$1(void);"; + $def .= + "#INFO:" + .join(',',@current_platforms).":" + .join(',',@current_algorithms).";"; + # Things that are everywhere + $def .= "int PEM_read_bio_$1(void);"; + next; + } elsif (/^OPENSSL_DECLARE_GLOBAL\s*\(\s*(\w*)\s*,\s*(\w*)\s*\)/) { + # Variant for platforms that do not + # have to access globale variables + # in shared libraries through functions + $def .= + "#INFO:" + .join(',',"!EXPORT_VAR_AS_FUNCTION",@current_platforms).":" + .join(',',@current_algorithms).";"; + $def .= "OPENSSL_EXTERN int _shadow_$2;"; + $def .= + "#INFO:" + .join(',',@current_platforms).":" + .join(',',@current_algorithms).";"; + # Variant for platforms that have to + # access globale variables in shared + # libraries through functions + &$make_variant("_shadow_$2","_shadow_$2", + "EXPORT_VAR_AS_FUNCTION", + "FUNCTION"); + } elsif ($tag{'CONST_STRICT'} != 1) { + if (/\{|\/\*|\([^\)]*$/) { + $line = $_; + } else { + $def .= $_; + } + } + } + } + close(IN); + + my $algs; + my $plays; + + print STDERR "DEBUG: postprocessing ----------\n" if $debug; + foreach (split /;/, $def) { + my $s; my $k = "FUNCTION"; my $p; my $a; + s/^[\n\s]*//g; + s/[\n\s]*$//g; + next if(/\#undef/); + next if(/typedef\W/); + next if(/\#define/); + + # Reduce argument lists to empty () + # fold round brackets recursively: (t(*v)(t),t) -> (t{}{},t) -> {} + while(/\(.*\)/s) { + s/\([^\(\)]+\)/\{\}/gs; + s/\(\s*\*\s*(\w+)\s*\{\}\s*\)/$1/gs; #(*f{}) -> f + } + # pretend as we didn't use curly braces: {} -> () + s/\{\}/\(\)/gs; + + s/STACK_OF\(\)/void/gs; + s/LHASH_OF\(\)/void/gs; + + print STDERR "DEBUG: \$_ = \"$_\"\n" if $debug; + if (/^\#INFO:([^:]*):(.*)$/) { + $plats = $1; + $algs = $2; + print STDERR "DEBUG: found info on platforms ($plats) and algorithms ($algs)\n" if $debug; + next; + } elsif (/^\s*OPENSSL_EXTERN\s.*?(\w+(\{[0-9]+\})?)(\[[0-9]*\])*\s*$/) { + $s = $1; + $k = "VARIABLE"; + print STDERR "DEBUG: found external variable $s\n" if $debug; + } elsif (/TYPEDEF_\w+_OF/s) { + next; + } elsif (/(\w+)\s*\(\).*/s) { # first token prior [first] () is + $s = $1; # a function name! + print STDERR "DEBUG: found function $s\n" if $debug; + } elsif (/\(/ and not (/=/)) { + print STDERR "File $file: cannot parse: $_;\n"; + next; + } else { + next; + } + + $syms{$s} = 1; + $kind{$s} = $k; + + $p = $plats; + $a = $algs; + $a .= ",BF" if($s =~ /EVP_bf/); + $a .= ",CAST" if($s =~ /EVP_cast/); + $a .= ",DES" if($s =~ /EVP_des/); + $a .= ",DSA" if($s =~ /EVP_dss/); + $a .= ",IDEA" if($s =~ /EVP_idea/); + $a .= ",MD2" if($s =~ /EVP_md2/); + $a .= ",MD4" if($s =~ /EVP_md4/); + $a .= ",MD5" if($s =~ /EVP_md5/); + $a .= ",RC2" if($s =~ /EVP_rc2/); + $a .= ",RC4" if($s =~ /EVP_rc4/); + $a .= ",RC5" if($s =~ /EVP_rc5/); + $a .= ",RIPEMD" if($s =~ /EVP_ripemd/); + $a .= ",SHA" if($s =~ /EVP_sha/); + $a .= ",RSA" if($s =~ /EVP_(Open|Seal)(Final|Init)/); + $a .= ",RSA" if($s =~ /PEM_Seal(Final|Init|Update)/); + $a .= ",RSA" if($s =~ /RSAPrivateKey/); + $a .= ",RSA" if($s =~ /SSLv23?_((client|server)_)?method/); + + $platform{$s} = + &reduce_platforms((defined($platform{$s})?$platform{$s}.',':"").$p); + $algorithm{$s} .= ','.$a; + + if (defined($variant{$s})) { + foreach $v (split /;/,$variant{$s}) { + (my $r, my $p, my $k) = split(/:/,$v); + my $ip = join ',',map({ /^!(.*)$/ ? $1 : "!".$_ } split /,/, $p); + $syms{$r} = 1; + if (!defined($k)) { $k = $kind{$s}; } + $kind{$r} = $k."(".$s.")"; + $algorithm{$r} = $algorithm{$s}; + $platform{$r} = &reduce_platforms($platform{$s}.",".$p.",".$p); + $platform{$s} = &reduce_platforms($platform{$s}.','.$ip.','.$ip); + print STDERR "DEBUG: \$variant{\"$s\"} = ",$v,"; \$r = $r; \$p = ",$platform{$r},"; \$a = ",$algorithm{$r},"; \$kind = ",$kind{$r},"\n" if $debug; + } + } + print STDERR "DEBUG: \$s = $s; \$p = ",$platform{$s},"; \$a = ",$algorithm{$s},"; \$kind = ",$kind{$s},"\n" if $debug; + } + } + + # Prune the returned symbols + + delete $syms{"bn_dump1"}; + $platform{"BIO_s_log"} .= ",!WIN32,!WIN16,!macintosh"; + + $platform{"PEM_read_NS_CERT_SEQ"} = "VMS"; + $platform{"PEM_write_NS_CERT_SEQ"} = "VMS"; + $platform{"PEM_read_P8_PRIV_KEY_INFO"} = "VMS"; + $platform{"PEM_write_P8_PRIV_KEY_INFO"} = "VMS"; + $platform{"EVP_sha384"} = "!VMSVAX"; + $platform{"EVP_sha512"} = "!VMSVAX"; + $platform{"SHA384_Init"} = "!VMSVAX"; + $platform{"SHA384_Transform"} = "!VMSVAX"; + $platform{"SHA384_Update"} = "!VMSVAX"; + $platform{"SHA384_Final"} = "!VMSVAX"; + $platform{"SHA384"} = "!VMSVAX"; + $platform{"SHA512_Init"} = "!VMSVAX"; + $platform{"SHA512_Transform"} = "!VMSVAX"; + $platform{"SHA512_Update"} = "!VMSVAX"; + $platform{"SHA512_Final"} = "!VMSVAX"; + $platform{"SHA512"} = "!VMSVAX"; + $platform{"WHIRLPOOL_Init"} = "!VMSVAX"; + $platform{"WHIRLPOOL"} = "!VMSVAX"; + $platform{"WHIRLPOOL_BitUpdate"} = "!VMSVAX"; + $platform{"EVP_whirlpool"} = "!VMSVAX"; + $platform{"WHIRLPOOL_Final"} = "!VMSVAX"; + $platform{"WHIRLPOOL_Update"} = "!VMSVAX"; + + + # Info we know about + + push @ret, map { $_."\\".&info_string($_,"EXIST", + $platform{$_}, + $kind{$_}, + $algorithm{$_}) } keys %syms; + + if (keys %unknown_algorithms) { + print STDERR "WARNING: mkdef.pl doesn't know the following algorithms:\n"; + print STDERR "\t",join("\n\t",keys %unknown_algorithms),"\n"; + } + return(@ret); +} + +# Param: string of comma-separated platform-specs. +sub reduce_platforms +{ + my ($platforms) = @_; + my $pl = defined($platforms) ? $platforms : ""; + my %p = map { $_ => 0 } split /,/, $pl; + my $ret; + + print STDERR "DEBUG: Entered reduce_platforms with \"$platforms\"\n" + if $debug; + # We do this, because if there's code like the following, it really + # means the function exists in all cases and should therefore be + # everywhere. By increasing and decreasing, we may attain 0: + # + # ifndef WIN16 + # int foo(); + # else + # int _fat foo(); + # endif + foreach $platform (split /,/, $pl) { + if ($platform =~ /^!(.*)$/) { + $p{$1}--; + } else { + $p{$platform}++; + } + } + foreach $platform (keys %p) { + if ($p{$platform} == 0) { delete $p{$platform}; } + } + + delete $p{""}; + + $ret = join(',',sort(map { $p{$_} < 0 ? "!".$_ : $_ } keys %p)); + print STDERR "DEBUG: Exiting reduce_platforms with \"$ret\"\n" + if $debug; + return $ret; +} + +sub info_string { + (my $symbol, my $exist, my $platforms, my $kind, my $algorithms) = @_; + + my %a = defined($algorithms) ? + map { $_ => 1 } split /,/, $algorithms : (); + my $k = defined($kind) ? $kind : "FUNCTION"; + my $ret; + my $p = &reduce_platforms($platforms); + + delete $a{""}; + + $ret = $exist; + $ret .= ":".$p; + $ret .= ":".$k; + $ret .= ":".join(',',sort keys %a); + return $ret; +} + +sub maybe_add_info { + (my $name, *nums, my @symbols) = @_; + my $sym; + my $new_info = 0; + my %syms=(); + + print STDERR "Updating $name info\n"; + foreach $sym (@symbols) { + (my $s, my $i) = split /\\/, $sym; + if (defined($nums{$s})) { + $i =~ s/^(.*?:.*?:\w+)(\(\w+\))?/$1/; + (my $n, my $dummy) = split /\\/, $nums{$s}; + if (!defined($dummy) || $i ne $dummy) { + $nums{$s} = $n."\\".$i; + $new_info++; + print STDERR "DEBUG: maybe_add_info for $s: \"$dummy\" => \"$i\"\n" if $debug; + } + } + $syms{$s} = 1; + } + + my @s=sort { &parse_number($nums{$a},"n") <=> &parse_number($nums{$b},"n") } keys %nums; + foreach $sym (@s) { + (my $n, my $i) = split /\\/, $nums{$sym}; + if (!defined($syms{$sym}) && $i !~ /^NOEXIST:/) { + $new_info++; + print STDERR "DEBUG: maybe_add_info for $sym: -> undefined\n" if $debug; + } + } + if ($new_info) { + print STDERR "$new_info old symbols got an info update\n"; + if (!$do_rewrite) { + print STDERR "You should do a rewrite to fix this.\n"; + } + } else { + print STDERR "No old symbols needed info update\n"; + } +} + +# Param: string of comma-separated keywords, each possibly prefixed with a "!" +sub is_valid +{ + my ($keywords_txt,$platforms) = @_; + my (@keywords) = split /,/,$keywords_txt; + my ($falsesum, $truesum) = (0, 1); + + # Param: one keyword + sub recognise + { + my ($keyword,$platforms) = @_; + + if ($platforms) { + # platforms + if ($keyword eq "VMSVAX" && $VMSVAX) { return 1; } + if ($keyword eq "VMSNonVAX" && $VMSNonVAX) { return 1; } + if ($keyword eq "VMS" && $VMS) { return 1; } + if ($keyword eq "WIN32" && $W32) { return 1; } + if ($keyword eq "WIN16" && $W16) { return 1; } + if ($keyword eq "WINNT" && $NT) { return 1; } + if ($keyword eq "OS2" && $OS2) { return 1; } + # Special platforms: + # EXPORT_VAR_AS_FUNCTION means that global variables + # will be represented as functions. This currently + # only happens on VMS-VAX. + if ($keyword eq "EXPORT_VAR_AS_FUNCTION" && ($VMSVAX || $W32 || $W16)) { + return 1; + } + if ($keyword eq "ZLIB" && $zlib) { return 1; } + return 0; + } else { + # algorithms + if ($keyword eq "RC2" && $no_rc2) { return 0; } + if ($keyword eq "RC4" && $no_rc4) { return 0; } + if ($keyword eq "RC5" && $no_rc5) { return 0; } + if ($keyword eq "IDEA" && $no_idea) { return 0; } + if ($keyword eq "DES" && $no_des) { return 0; } + if ($keyword eq "BF" && $no_bf) { return 0; } + if ($keyword eq "CAST" && $no_cast) { return 0; } + if ($keyword eq "MD2" && $no_md2) { return 0; } + if ($keyword eq "MD4" && $no_md4) { return 0; } + if ($keyword eq "MD5" && $no_md5) { return 0; } + if ($keyword eq "SHA" && $no_sha) { return 0; } + if ($keyword eq "RIPEMD" && $no_ripemd) { return 0; } + if ($keyword eq "MDC2" && $no_mdc2) { return 0; } + if ($keyword eq "WHIRLPOOL" && $no_whirlpool) { return 0; } + if ($keyword eq "RSA" && $no_rsa) { return 0; } + if ($keyword eq "DSA" && $no_dsa) { return 0; } + if ($keyword eq "DH" && $no_dh) { return 0; } + if ($keyword eq "EC" && $no_ec) { return 0; } + if ($keyword eq "ECDSA" && $no_ecdsa) { return 0; } + if ($keyword eq "ECDH" && $no_ecdh) { return 0; } + if ($keyword eq "HMAC" && $no_hmac) { return 0; } + if ($keyword eq "AES" && $no_aes) { return 0; } + if ($keyword eq "CAMELLIA" && $no_camellia) { return 0; } + if ($keyword eq "SEED" && $no_seed) { return 0; } + if ($keyword eq "EVP" && $no_evp) { return 0; } + if ($keyword eq "LHASH" && $no_lhash) { return 0; } + if ($keyword eq "STACK" && $no_stack) { return 0; } + if ($keyword eq "ERR" && $no_err) { return 0; } + if ($keyword eq "BUFFER" && $no_buffer) { return 0; } + if ($keyword eq "BIO" && $no_bio) { return 0; } + if ($keyword eq "COMP" && $no_comp) { return 0; } + if ($keyword eq "DSO" && $no_dso) { return 0; } + if ($keyword eq "KRB5" && $no_krb5) { return 0; } + if ($keyword eq "ENGINE" && $no_engine) { return 0; } + if ($keyword eq "HW" && $no_hw) { return 0; } + if ($keyword eq "FP_API" && $no_fp_api) { return 0; } + if ($keyword eq "STATIC_ENGINE" && $no_static_engine) { return 0; } + if ($keyword eq "GMP" && $no_gmp) { return 0; } + if ($keyword eq "RFC3779" && $no_rfc3779) { return 0; } + if ($keyword eq "TLSEXT" && $no_tlsext) { return 0; } + if ($keyword eq "PSK" && $no_psk) { return 0; } + if ($keyword eq "CMS" && $no_cms) { return 0; } + if ($keyword eq "SSL2" && $no_ssl2) { return 0; } + if ($keyword eq "CAPIENG" && $no_capieng) { return 0; } + if ($keyword eq "JPAKE" && $no_jpake) { return 0; } + if ($keyword eq "DEPRECATED" && $no_deprecated) { return 0; } + + # Nothing recognise as true + return 1; + } + } + + foreach $k (@keywords) { + if ($k =~ /^!(.*)$/) { + $falsesum += &recognise($1,$platforms); + } else { + $truesum *= &recognise($k,$platforms); + } + } + print STDERR "DEBUG: [",$#keywords,",",$#keywords < 0,"] is_valid($keywords_txt) => (\!$falsesum) && $truesum = ",(!$falsesum) && $truesum,"\n" if $debug; + return (!$falsesum) && $truesum; +} + +sub print_test_file +{ + (*OUT,my $name,*nums,my $testall,my @symbols)=@_; + my $n = 1; my @e; my @r; + my $sym; my $prev = ""; my $prefSSLeay; + + (@e)=grep(/^SSLeay(\{[0-9]+\})?\\.*?:.*?:.*/,@symbols); + (@r)=grep(/^\w+(\{[0-9]+\})?\\.*?:.*?:.*/ && !/^SSLeay(\{[0-9]+\})?\\.*?:.*?:.*/,@symbols); + @symbols=((sort @e),(sort @r)); + + foreach $sym (@symbols) { + (my $s, my $i) = $sym =~ /^(.*?)\\(.*)$/; + my $v = 0; + $v = 1 if $i=~ /^.*?:.*?:VARIABLE/; + my $p = ($i =~ /^[^:]*:([^:]*):/,$1); + my $a = ($i =~ /^[^:]*:[^:]*:[^:]*:([^:]*)/,$1); + if (!defined($nums{$s})) { + print STDERR "Warning: $s does not have a number assigned\n" + if(!$do_update); + } elsif (is_valid($p,1) && is_valid($a,0)) { + my $s2 = ($s =~ /^(.*?)(\{[0-9]+\})?$/, $1); + if ($prev eq $s2) { + print OUT "\t/* The following has already appeared previously */\n"; + print STDERR "Warning: Symbol '",$s2,"' redefined. old=",($nums{$prev} =~ /^(.*?)\\/,$1),", new=",($nums{$s2} =~ /^(.*?)\\/,$1),"\n"; + } + $prev = $s2; # To warn about duplicates... + + ($nn,$ni)=($nums{$s2} =~ /^(.*?)\\(.*)$/); + if ($v) { + print OUT "\textern int $s2; /* type unknown */ /* $nn $ni */\n"; + } else { + print OUT "\textern int $s2(); /* type unknown */ /* $nn $ni */\n"; + } + } + } +} + +sub get_version { + local *MF; + my $v = '?'; + open MF, 'Makefile' or return $v; + while () { + $v = $1, last if /^VERSION=(.*?)\s*$/; + } + close MF; + return $v; +} + +sub print_def_file +{ + (*OUT,my $name,*nums,my @symbols)=@_; + my $n = 1; my @e; my @r; my @v; my $prev=""; + my $liboptions=""; + my $libname = $name; + my $http_vendor = 'www.openssl.org/'; + my $version = get_version(); + my $what = "OpenSSL: implementation of Secure Socket Layer"; + my $description = "$what $version, $name - http://$http_vendor"; + + if ($W32) + { $libname.="32"; } + elsif ($W16) + { $libname.="16"; } + elsif ($OS2) + { # DLL names should not clash on the whole system. + # However, they should not have any particular relationship + # to the name of the static library. Chose descriptive names + # (must be at most 8 chars). + my %translate = (ssl => 'open_ssl', crypto => 'cryptssl'); + $libname = $translate{$name} || $name; + $liboptions = <) { + chop; + s/#.*$//; + next if /^\s*$/; + @a=split; + if (defined $ret{$a[0]}) { + # This is actually perfectly OK + #print STDERR "Warning: Symbol '",$a[0],"' redefined. old=",$ret{$a[0]},", new=",$a[1],"\n"; + } + if ($max_num > $a[1]) { + print STDERR "Warning: Number decreased from ",$max_num," to ",$a[1],"\n"; + } + elsif ($max_num == $a[1]) { + # This is actually perfectly OK + #print STDERR "Warning: Symbol ",$a[0]," has same number as previous ",$prev,": ",$a[1],"\n"; + if ($a[0] eq $prev) { + $prev_cnt++; + $a[0] .= "{$prev_cnt}"; + } + } + else { + $prev_cnt = 0; + } + if ($#a < 2) { + # Existence will be proven later, in do_defs + $ret{$a[0]}=$a[1]; + $num_noinfo++; + } else { + $ret{$a[0]}=$a[1]."\\".$a[2]; # \\ is a special marker + } + $max_num = $a[1] if $a[1] > $max_num; + $prev=$a[0]; + } + if ($num_noinfo) { + print STDERR "Warning: $num_noinfo symbols were without info."; + if ($do_rewrite) { + printf STDERR " The rewrite will fix this.\n"; + } else { + printf STDERR " You should do a rewrite to fix this.\n"; + } + } + close(IN); + return(%ret); +} + +sub parse_number +{ + (my $str, my $what) = @_; + (my $n, my $i) = split(/\\/,$str); + if ($what eq "n") { + return $n; + } else { + return $i; + } +} + +sub rewrite_numbers +{ + (*OUT,$name,*nums,@symbols)=@_; + my $thing; + + print STDERR "Rewriting $name\n"; + + my @r = grep(/^\w+(\{[0-9]+\})?\\.*?:.*?:\w+\(\w+\)/,@symbols); + my $r; my %r; my %rsyms; + foreach $r (@r) { + (my $s, my $i) = split /\\/, $r; + my $a = $1 if $i =~ /^.*?:.*?:\w+\((\w+)\)/; + $i =~ s/^(.*?:.*?:\w+)\(\w+\)/$1/; + $r{$a} = $s."\\".$i; + $rsyms{$s} = 1; + } + + my %syms = (); + foreach $_ (@symbols) { + (my $n, my $i) = split /\\/; + $syms{$n} = 1; + } + + my @s=sort { + &parse_number($nums{$a},"n") <=> &parse_number($nums{$b},"n") + || $a cmp $b + } keys %nums; + foreach $sym (@s) { + (my $n, my $i) = split /\\/, $nums{$sym}; + next if defined($i) && $i =~ /^.*?:.*?:\w+\(\w+\)/; + next if defined($rsyms{$sym}); + print STDERR "DEBUG: rewrite_numbers for sym = ",$sym,": i = ",$i,", n = ",$n,", rsym{sym} = ",$rsyms{$sym},"syms{sym} = ",$syms{$sym},"\n" if $debug; + $i="NOEXIST::FUNCTION:" + if !defined($i) || $i eq "" || !defined($syms{$sym}); + my $s2 = $sym; + $s2 =~ s/\{[0-9]+\}$//; + printf OUT "%s%-39s %d\t%s\n","",$s2,$n,$i; + if (exists $r{$sym}) { + (my $s, $i) = split /\\/,$r{$sym}; + my $s2 = $s; + $s2 =~ s/\{[0-9]+\}$//; + printf OUT "%s%-39s %d\t%s\n","",$s2,$n,$i; + } + } +} + +sub update_numbers +{ + (*OUT,$name,*nums,my $start_num, my @symbols)=@_; + my $new_syms = 0; + + print STDERR "Updating $name numbers\n"; + + my @r = grep(/^\w+(\{[0-9]+\})?\\.*?:.*?:\w+\(\w+\)/,@symbols); + my $r; my %r; my %rsyms; + foreach $r (@r) { + (my $s, my $i) = split /\\/, $r; + my $a = $1 if $i =~ /^.*?:.*?:\w+\((\w+)\)/; + $i =~ s/^(.*?:.*?:\w+)\(\w+\)/$1/; + $r{$a} = $s."\\".$i; + $rsyms{$s} = 1; + } + + foreach $sym (@symbols) { + (my $s, my $i) = $sym =~ /^(.*?)\\(.*)$/; + next if $i =~ /^.*?:.*?:\w+\(\w+\)/; + next if defined($rsyms{$sym}); + die "ERROR: Symbol $sym had no info attached to it." + if $i eq ""; + if (!exists $nums{$s}) { + $new_syms++; + my $s2 = $s; + $s2 =~ s/\{[0-9]+\}$//; + printf OUT "%s%-39s %d\t%s\n","",$s2, ++$start_num,$i; + if (exists $r{$s}) { + ($s, $i) = split /\\/,$r{$s}; + $s =~ s/\{[0-9]+\}$//; + printf OUT "%s%-39s %d\t%s\n","",$s, $start_num,$i; + } + } + } + if($new_syms) { + print STDERR "$new_syms New symbols added\n"; + } else { + print STDERR "No New symbols Added\n"; + } +} + +sub check_existing +{ + (*nums, my @symbols)=@_; + my %existing; my @remaining; + @remaining=(); + foreach $sym (@symbols) { + (my $s, my $i) = $sym =~ /^(.*?)\\(.*)$/; + $existing{$s}=1; + } + foreach $sym (keys %nums) { + if (!exists $existing{$sym}) { + push @remaining, $sym; + } + } + if(@remaining) { + print STDERR "The following symbols do not seem to exist:\n"; + foreach $sym (@remaining) { + print STDERR "\t",$sym,"\n"; + } + } +} + diff --git a/node-v0.8.14/deps/openssl/openssl/util/mkdir-p.pl b/node-v0.8.14/deps/openssl/openssl/util/mkdir-p.pl new file mode 100755 index 0000000..e73d02b --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/util/mkdir-p.pl @@ -0,0 +1,34 @@ +#!/usr/local/bin/perl + +# mkdir-p.pl + +# On some systems, the -p option to mkdir (= also create any missing parent +# directories) is not available. + +my $arg; + +foreach $arg (@ARGV) { + $arg =~ tr|\\|/|; + &do_mkdir_p($arg); +} + + +sub do_mkdir_p { + local($dir) = @_; + + $dir =~ s|/*\Z(?!\n)||s; + + if (-d $dir) { + return; + } + + if ($dir =~ m|[^/]/|s) { + local($parent) = $dir; + $parent =~ s|[^/]*\Z(?!\n)||s; + + do_mkdir_p($parent); + } + + mkdir($dir, 0777) || die "Cannot create directory $dir: $!\n"; + print "created directory `$dir'\n"; +} diff --git a/node-v0.8.14/deps/openssl/openssl/util/mkerr.pl b/node-v0.8.14/deps/openssl/openssl/util/mkerr.pl new file mode 100644 index 0000000..aec401c --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/util/mkerr.pl @@ -0,0 +1,810 @@ +#!/usr/local/bin/perl -w + +my $config = "crypto/err/openssl.ec"; +my $hprefix = "openssl/"; +my $debug = 0; +my $rebuild = 0; +my $static = 1; +my $recurse = 0; +my $reindex = 0; +my $dowrite = 0; +my $staticloader = ""; + +my $pack_errcode; +my $load_errcode; + +my $errcount; + +while (@ARGV) { + my $arg = $ARGV[0]; + if($arg eq "-conf") { + shift @ARGV; + $config = shift @ARGV; + } elsif($arg eq "-hprefix") { + shift @ARGV; + $hprefix = shift @ARGV; + } elsif($arg eq "-debug") { + $debug = 1; + shift @ARGV; + } elsif($arg eq "-rebuild") { + $rebuild = 1; + shift @ARGV; + } elsif($arg eq "-recurse") { + $recurse = 1; + shift @ARGV; + } elsif($arg eq "-reindex") { + $reindex = 1; + shift @ARGV; + } elsif($arg eq "-nostatic") { + $static = 0; + shift @ARGV; + } elsif($arg eq "-staticloader") { + $staticloader = "static "; + shift @ARGV; + } elsif($arg eq "-write") { + $dowrite = 1; + shift @ARGV; + } elsif($arg eq "-help" || $arg eq "-h" || $arg eq "-?" || $arg eq "--help") { + print STDERR <<"EOF"; +mkerr.pl [options] ... + +Options: + + -conf F Use the config file F instead of the default one: + crypto/err/openssl.ec + + -hprefix P Prepend the filenames in generated #include
+ statements with prefix P. Default: 'openssl/' (without + the quotes, naturally) + + -debug Turn on debugging verbose output on stderr. + + -rebuild Rebuild all header and C source files, irrespective of the + fact if any error or function codes have been added/removed. + Default: only update files for libraries which saw change + (of course, this requires '-write' as well, or no + files will be touched!) + + -recurse scan a preconfigured set of directories / files for error and + function codes: + (, , , ) + When this option is NOT specified, the filelist is taken from + the commandline instead. Here, wildcards may be embedded. (Be + sure to escape those to prevent the shell from expanding them + for you when you wish mkerr.pl to do so instead.) + Default: take file list to scan from the command line. + + -reindex Discard the numeric values previously assigned to the error + and function codes as extracted from the scanned header files; + instead renumber all of them starting from 100. (Note that + the numbers assigned through 'R' records in the config file + remain intact.) + Default: keep previously assigned numbers. (You are warned + when collisions are detected.) + + -nostatic Generates a different source code, where these additional + functions are generated for each library specified in the + config file: + void ERR_load__strings(void); + void ERR_unload__strings(void); + void ERR__error(int f, int r, char *fn, int ln); + #define err(f,r) ERR__error(f,r,__FILE__,__LINE__) + while the code facilitates the use of these in an environment + where the error support routines are dynamically loaded at + runtime. + Default: 'static' code generation. + + -staticloader Prefix generated functions with the 'static' scope modifier. + Default: don't write any scope modifier prefix. + + -write Actually (over)write the generated code to the header and C + source files as assigned to each library through the config + file. + Default: don't write. + + -help / -h / -? / --help Show this help text. + + ... Additional arguments are added to the file list to scan, + assuming '-recurse' was NOT specified on the command line. + +EOF + exit 1; + } else { + last; + } +} + +if($recurse) { + @source = (, , ); +} else { + @source = @ARGV; +} + +# Read in the config file + +open(IN, "<$config") || die "Can't open config file $config"; + +# Parse config file + +while() +{ + if(/^L\s+(\S+)\s+(\S+)\s+(\S+)/) { + $hinc{$1} = $2; + $libinc{$2} = $1; + $cskip{$3} = $1; + if($3 ne "NONE") { + $csrc{$1} = $3; + $fmax{$1} = 100; + $rmax{$1} = 100; + $fassigned{$1} = ":"; + $rassigned{$1} = ":"; + $fnew{$1} = 0; + $rnew{$1} = 0; + } + } elsif (/^F\s+(\S+)/) { + # Add extra function with $1 + } elsif (/^R\s+(\S+)\s+(\S+)/) { + $rextra{$1} = $2; + $rcodes{$1} = $2; + } +} + +close IN; + +# Scan each header file in turn and make a list of error codes +# and function names + +while (($hdr, $lib) = each %libinc) +{ + next if($hdr eq "NONE"); + print STDERR "Scanning header file $hdr\n" if $debug; + my $line = "", $def= "", $linenr = 0, $gotfile = 0; + if (open(IN, "<$hdr")) { + $gotfile = 1; + while() { + $linenr++; + print STDERR "line: $linenr\r" if $debug; + + last if(/BEGIN\s+ERROR\s+CODES/); + if ($line ne '') { + $_ = $line . $_; + $line = ''; + } + + if (/\\$/) { + $line = $_; + next; + } + + if(/\/\*/) { + if (not /\*\//) { # multiline comment... + $line = $_; # ... just accumulate + next; + } else { + s/\/\*.*?\*\///gs; # wipe it + } + } + + if ($cpp) { + $cpp++ if /^#\s*if/; + $cpp-- if /^#\s*endif/; + next; + } + $cpp = 1 if /^#.*ifdef.*cplusplus/; # skip "C" declaration + + next if (/^\#/); # skip preprocessor directives + + s/{[^{}]*}//gs; # ignore {} blocks + + if (/\{|\/\*/) { # Add a } so editor works... + $line = $_; + } else { + $def .= $_; + } + } + } + + print STDERR " \r" if $debug; + $defnr = 0; + # Delete any DECLARE_ macros + $def =~ s/DECLARE_\w+\([\w,\s]+\)//gs; + foreach (split /;/, $def) { + $defnr++; + print STDERR "def: $defnr\r" if $debug; + + # The goal is to collect function names from function declarations. + + s/^[\n\s]*//g; + s/[\n\s]*$//g; + + # Skip over recognized non-function declarations + next if(/typedef\W/ or /DECLARE_STACK_OF/ or /TYPEDEF_.*_OF/); + + # Remove STACK_OF(foo) + s/STACK_OF\(\w+\)/void/; + + # Reduce argument lists to empty () + # fold round brackets recursively: (t(*v)(t),t) -> (t{}{},t) -> {} + while(/\(.*\)/s) { + s/\([^\(\)]+\)/\{\}/gs; + s/\(\s*\*\s*(\w+)\s*\{\}\s*\)/$1/gs; #(*f{}) -> f + } + # pretend as we didn't use curly braces: {} -> () + s/\{\}/\(\)/gs; + + if (/(\w+)\s*\(\).*/s) { # first token prior [first] () is + my $name = $1; # a function name! + $name =~ tr/[a-z]/[A-Z]/; + $ftrans{$name} = $1; + } elsif (/[\(\)]/ and not (/=/)) { + print STDERR "Header $hdr: cannot parse: $_;\n"; + } + } + + print STDERR " \r" if $debug; + + next if $reindex; + + # Scan function and reason codes and store them: keep a note of the + # maximum code used. + + if ($gotfile) { + while() { + if(/^\#define\s+(\S+)\s+(\S+)/) { + $name = $1; + $code = $2; + next if $name =~ /^${lib}err/; + unless($name =~ /^${lib}_([RF])_(\w+)$/) { + print STDERR "Invalid error code $name\n"; + next; + } + if($1 eq "R") { + $rcodes{$name} = $code; + if ($rassigned{$lib} =~ /:$code:/) { + print STDERR "!! ERROR: $lib reason code $code assigned twice (collision at $name)\n"; + ++$errcount; + } + $rassigned{$lib} .= "$code:"; + if(!(exists $rextra{$name}) && + ($code > $rmax{$lib}) ) { + $rmax{$lib} = $code; + } + } else { + if ($fassigned{$lib} =~ /:$code:/) { + print STDERR "!! ERROR: $lib function code $code assigned twice (collision at $name)\n"; + ++$errcount; + } + $fassigned{$lib} .= "$code:"; + if($code > $fmax{$lib}) { + $fmax{$lib} = $code; + } + $fcodes{$name} = $code; + } + } + } + } + + if ($debug) { + if (defined($fmax{$lib})) { + print STDERR "Max function code fmax" . "{" . "$lib" . "} = $fmax{$lib}\n"; + $fassigned{$lib} =~ m/^:(.*):$/; + @fassigned = sort {$a <=> $b} split(":", $1); + print STDERR " @fassigned\n"; + } + if (defined($rmax{$lib})) { + print STDERR "Max reason code rmax" . "{" . "$lib" . "} = $rmax{$lib}\n"; + $rassigned{$lib} =~ m/^:(.*):$/; + @rassigned = sort {$a <=> $b} split(":", $1); + print STDERR " @rassigned\n"; + } + } + + if ($lib eq "SSL") { + if ($rmax{$lib} >= 1000) { + print STDERR "!! ERROR: SSL error codes 1000+ are reserved for alerts.\n"; + print STDERR "!! Any new alerts must be added to $config.\n"; + ++$errcount; + print STDERR "\n"; + } + } + close IN; +} + +# Scan each C source file and look for function and reason codes +# This is done by looking for strings that "look like" function or +# reason codes: basically anything consisting of all upper case and +# numerics which has _F_ or _R_ in it and which has the name of an +# error library at the start. This seems to work fine except for the +# oddly named structure BIO_F_CTX which needs to be ignored. +# If a code doesn't exist in list compiled from headers then mark it +# with the value "X" as a place holder to give it a value later. +# Store all function and reason codes found in %ufcodes and %urcodes +# so all those unreferenced can be printed out. + + +foreach $file (@source) { + # Don't parse the error source file. + next if exists $cskip{$file}; + print STDERR "File loaded: ".$file."\r" if $debug; + open(IN, "<$file") || die "Can't open source file $file\n"; + while() { + # skip obsoleted source files entirely! + last if(/^#error\s+obsolete/); + + if(/(([A-Z0-9]+)_F_([A-Z0-9_]+))/) { + next unless exists $csrc{$2}; + next if($1 eq "BIO_F_BUFFER_CTX"); + $ufcodes{$1} = 1; + if(!exists $fcodes{$1}) { + $fcodes{$1} = "X"; + $fnew{$2}++; + } + $notrans{$1} = 1 unless exists $ftrans{$3}; + print STDERR "Function: $1\t= $fcodes{$1} (lib: $2, name: $3)\n" if $debug; + } + if(/(([A-Z0-9]+)_R_[A-Z0-9_]+)/) { + next unless exists $csrc{$2}; + $urcodes{$1} = 1; + if(!exists $rcodes{$1}) { + $rcodes{$1} = "X"; + $rnew{$2}++; + } + print STDERR "Reason: $1\t= $rcodes{$1} (lib: $2)\n" if $debug; + } + } + close IN; +} +print STDERR " \n" if $debug; + +# Now process each library in turn. + +foreach $lib (keys %csrc) +{ + my $hfile = $hinc{$lib}; + my $cfile = $csrc{$lib}; + if(!$fnew{$lib} && !$rnew{$lib}) { + print STDERR "$lib:\t\tNo new error codes\n"; + next unless $rebuild; + } else { + print STDERR "$lib:\t\t$fnew{$lib} New Functions,"; + print STDERR " $rnew{$lib} New Reasons.\n"; + next unless $dowrite; + } + + # If we get here then we have some new error codes so we + # need to rebuild the header file and C file. + + # Make a sorted list of error and reason codes for later use. + + my @function = sort grep(/^${lib}_/,keys %fcodes); + my @reasons = sort grep(/^${lib}_/,keys %rcodes); + + # Rewrite the header file + + if (open(IN, "<$hfile")) { + # Copy across the old file + while() { + push @out, $_; + last if (/BEGIN ERROR CODES/); + } + close IN; + } else { + push @out, +"/* ====================================================================\n", +" * Copyright (c) 2001-2011 The OpenSSL Project. All rights reserved.\n", +" *\n", +" * Redistribution and use in source and binary forms, with or without\n", +" * modification, are permitted provided that the following conditions\n", +" * are met:\n", +" *\n", +" * 1. Redistributions of source code must retain the above copyright\n", +" * notice, this list of conditions and the following disclaimer. \n", +" *\n", +" * 2. Redistributions in binary form must reproduce the above copyright\n", +" * notice, this list of conditions and the following disclaimer in\n", +" * the documentation and/or other materials provided with the\n", +" * distribution.\n", +" *\n", +" * 3. All advertising materials mentioning features or use of this\n", +" * software must display the following acknowledgment:\n", +" * \"This product includes software developed by the OpenSSL Project\n", +" * for use in the OpenSSL Toolkit. (http://www.openssl.org/)\"\n", +" *\n", +" * 4. The names \"OpenSSL Toolkit\" and \"OpenSSL Project\" must not be used to\n", +" * endorse or promote products derived from this software without\n", +" * prior written permission. For written permission, please contact\n", +" * openssl-core\@openssl.org.\n", +" *\n", +" * 5. Products derived from this software may not be called \"OpenSSL\"\n", +" * nor may \"OpenSSL\" appear in their names without prior written\n", +" * permission of the OpenSSL Project.\n", +" *\n", +" * 6. Redistributions of any form whatsoever must retain the following\n", +" * acknowledgment:\n", +" * \"This product includes software developed by the OpenSSL Project\n", +" * for use in the OpenSSL Toolkit (http://www.openssl.org/)\"\n", +" *\n", +" * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY\n", +" * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n", +" * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n", +" * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR\n", +" * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n", +" * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n", +" * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n", +" * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n", +" * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,\n", +" * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n", +" * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED\n", +" * OF THE POSSIBILITY OF SUCH DAMAGE.\n", +" * ====================================================================\n", +" *\n", +" * This product includes cryptographic software written by Eric Young\n", +" * (eay\@cryptsoft.com). This product includes software written by Tim\n", +" * Hudson (tjh\@cryptsoft.com).\n", +" *\n", +" */\n", +"\n", +"#ifndef HEADER_${lib}_ERR_H\n", +"#define HEADER_${lib}_ERR_H\n", +"\n", +"#ifdef __cplusplus\n", +"extern \"C\" {\n", +"#endif\n", +"\n", +"/* BEGIN ERROR CODES */\n"; + } + open (OUT, ">$hfile") || die "Can't Open File $hfile for writing\n"; + + print OUT @out; + undef @out; + print OUT <<"EOF"; +/* The following lines are auto generated by the script mkerr.pl. Any changes + * made after this point may be overwritten when the script is next run. + */ +EOF + if($static) { + print OUT <<"EOF"; +${staticloader}void ERR_load_${lib}_strings(void); + +EOF + } else { + print OUT <<"EOF"; +${staticloader}void ERR_load_${lib}_strings(void); +${staticloader}void ERR_unload_${lib}_strings(void); +${staticloader}void ERR_${lib}_error(int function, int reason, char *file, int line); +#define ${lib}err(f,r) ERR_${lib}_error((f),(r),__FILE__,__LINE__) + +EOF + } + print OUT <<"EOF"; +/* Error codes for the $lib functions. */ + +/* Function codes. */ +EOF + + foreach $i (@function) { + $z=6-int(length($i)/8); + if($fcodes{$i} eq "X") { + $fassigned{$lib} =~ m/^:([^:]*):/; + $findcode = $1; + if (!defined($findcode)) { + $findcode = $fmax{$lib}; + } + while ($fassigned{$lib} =~ m/:$findcode:/) { + $findcode++; + } + $fcodes{$i} = $findcode; + $fassigned{$lib} .= "$findcode:"; + print STDERR "New Function code $i\n" if $debug; + } + printf OUT "#define $i%s $fcodes{$i}\n","\t" x $z; + } + + print OUT "\n/* Reason codes. */\n"; + + foreach $i (@reasons) { + $z=6-int(length($i)/8); + if($rcodes{$i} eq "X") { + $rassigned{$lib} =~ m/^:([^:]*):/; + $findcode = $1; + if (!defined($findcode)) { + $findcode = $rmax{$lib}; + } + while ($rassigned{$lib} =~ m/:$findcode:/) { + $findcode++; + } + $rcodes{$i} = $findcode; + $rassigned{$lib} .= "$findcode:"; + print STDERR "New Reason code $i\n" if $debug; + } + printf OUT "#define $i%s $rcodes{$i}\n","\t" x $z; + } + print OUT <<"EOF"; + +#ifdef __cplusplus +} +#endif +#endif +EOF + close OUT; + + # Rewrite the C source file containing the error details. + + # First, read any existing reason string definitions: + my %err_reason_strings; + if (open(IN,"<$cfile")) { + while () { + if (/\b(${lib}_R_\w*)\b.*\"(.*)\"/) { + $err_reason_strings{$1} = $2; + } + if (/\b${lib}_F_(\w*)\b.*\"(.*)\"/) { + if (!exists $ftrans{$1} && ($1 ne $2)) { + print STDERR "WARNING: Mismatched function string $2\n"; + $ftrans{$1} = $2; + } + } + } + close(IN); + } + + + my $hincf; + if($static) { + $hfile =~ /([^\/]+)$/; + $hincf = "<${hprefix}$1>"; + } else { + $hincf = "\"$hfile\""; + } + + # If static we know the error code at compile time so use it + # in error definitions. + + if ($static) + { + $pack_errcode = "ERR_LIB_${lib}"; + $load_errcode = "0"; + } + else + { + $pack_errcode = "0"; + $load_errcode = "ERR_LIB_${lib}"; + } + + + open (OUT,">$cfile") || die "Can't open $cfile for writing"; + + print OUT <<"EOF"; +/* $cfile */ +/* ==================================================================== + * Copyright (c) 1999-2011 The OpenSSL Project. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. All advertising materials mentioning features or use of this + * software must display the following acknowledgment: + * "This product includes software developed by the OpenSSL Project + * for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)" + * + * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to + * endorse or promote products derived from this software without + * prior written permission. For written permission, please contact + * openssl-core\@OpenSSL.org. + * + * 5. Products derived from this software may not be called "OpenSSL" + * nor may "OpenSSL" appear in their names without prior written + * permission of the OpenSSL Project. + * + * 6. Redistributions of any form whatsoever must retain the following + * acknowledgment: + * "This product includes software developed by the OpenSSL Project + * for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)" + * + * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY + * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR + * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, + * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * ==================================================================== + * + * This product includes cryptographic software written by Eric Young + * (eay\@cryptsoft.com). This product includes software written by Tim + * Hudson (tjh\@cryptsoft.com). + * + */ + +/* NOTE: this file was auto generated by the mkerr.pl script: any changes + * made to it will be overwritten when the script next updates this file, + * only reason strings will be preserved. + */ + +#include +#include +#include $hincf + +/* BEGIN ERROR CODES */ +#ifndef OPENSSL_NO_ERR + +#define ERR_FUNC(func) ERR_PACK($pack_errcode,func,0) +#define ERR_REASON(reason) ERR_PACK($pack_errcode,0,reason) + +static ERR_STRING_DATA ${lib}_str_functs[]= + { +EOF + # Add each function code: if a function name is found then use it. + foreach $i (@function) { + my $fn; + $i =~ /^${lib}_F_(\S+)$/; + $fn = $1; + if(exists $ftrans{$fn}) { + $fn = $ftrans{$fn}; + } +# print OUT "{ERR_PACK($pack_errcode,$i,0),\t\"$fn\"},\n"; + print OUT "{ERR_FUNC($i),\t\"$fn\"},\n"; + } + print OUT <<"EOF"; +{0,NULL} + }; + +static ERR_STRING_DATA ${lib}_str_reasons[]= + { +EOF + # Add each reason code. + foreach $i (@reasons) { + my $rn; + my $rstr = "ERR_REASON($i)"; + my $nspc = 0; + if (exists $err_reason_strings{$i}) { + $rn = $err_reason_strings{$i}; + } else { + $i =~ /^${lib}_R_(\S+)$/; + $rn = $1; + $rn =~ tr/_[A-Z]/ [a-z]/; + } + $nspc = 40 - length($rstr) unless length($rstr) > 40; + $nspc = " " x $nspc; + print OUT "{${rstr}${nspc},\"$rn\"},\n"; + } +if($static) { + print OUT <<"EOF"; +{0,NULL} + }; + +#endif + +${staticloader}void ERR_load_${lib}_strings(void) + { +#ifndef OPENSSL_NO_ERR + + if (ERR_func_error_string(${lib}_str_functs[0].error) == NULL) + { + ERR_load_strings($load_errcode,${lib}_str_functs); + ERR_load_strings($load_errcode,${lib}_str_reasons); + } +#endif + } +EOF +} else { + print OUT <<"EOF"; +{0,NULL} + }; + +#endif + +#ifdef ${lib}_LIB_NAME +static ERR_STRING_DATA ${lib}_lib_name[]= + { +{0 ,${lib}_LIB_NAME}, +{0,NULL} + }; +#endif + + +static int ${lib}_lib_error_code=0; +static int ${lib}_error_init=1; + +${staticloader}void ERR_load_${lib}_strings(void) + { + if (${lib}_lib_error_code == 0) + ${lib}_lib_error_code=ERR_get_next_error_library(); + + if (${lib}_error_init) + { + ${lib}_error_init=0; +#ifndef OPENSSL_NO_ERR + ERR_load_strings(${lib}_lib_error_code,${lib}_str_functs); + ERR_load_strings(${lib}_lib_error_code,${lib}_str_reasons); +#endif + +#ifdef ${lib}_LIB_NAME + ${lib}_lib_name->error = ERR_PACK(${lib}_lib_error_code,0,0); + ERR_load_strings(0,${lib}_lib_name); +#endif + } + } + +${staticloader}void ERR_unload_${lib}_strings(void) + { + if (${lib}_error_init == 0) + { +#ifndef OPENSSL_NO_ERR + ERR_unload_strings(${lib}_lib_error_code,${lib}_str_functs); + ERR_unload_strings(${lib}_lib_error_code,${lib}_str_reasons); +#endif + +#ifdef ${lib}_LIB_NAME + ERR_unload_strings(0,${lib}_lib_name); +#endif + ${lib}_error_init=1; + } + } + +${staticloader}void ERR_${lib}_error(int function, int reason, char *file, int line) + { + if (${lib}_lib_error_code == 0) + ${lib}_lib_error_code=ERR_get_next_error_library(); + ERR_PUT_error(${lib}_lib_error_code,function,reason,file,line); + } +EOF + +} + + close OUT; + undef %err_reason_strings; +} + +if($debug && %notrans) { + print STDERR "The following function codes were not translated:\n"; + foreach(sort keys %notrans) + { + print STDERR "$_\n"; + } +} + +# Make a list of unreferenced function and reason codes + +foreach (keys %fcodes) { + push (@funref, $_) unless exists $ufcodes{$_}; +} + +foreach (keys %rcodes) { + push (@runref, $_) unless exists $urcodes{$_}; +} + +if($debug && defined(@funref) ) { + print STDERR "The following function codes were not referenced:\n"; + foreach(sort @funref) + { + print STDERR "$_\n"; + } +} + +if($debug && defined(@runref) ) { + print STDERR "The following reason codes were not referenced:\n"; + foreach(sort @runref) + { + print STDERR "$_\n"; + } +} + +if($errcount) { + print STDERR "There were errors, failing...\n\n"; + exit $errcount; +} + diff --git a/node-v0.8.14/deps/openssl/openssl/util/mkfiles.pl b/node-v0.8.14/deps/openssl/openssl/util/mkfiles.pl new file mode 100755 index 0000000..6d15831 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/util/mkfiles.pl @@ -0,0 +1,141 @@ +#!/usr/local/bin/perl +# +# This is a hacked version of files.pl for systems that can't do a 'make files'. +# Do a perl util/mkminfo.pl >MINFO to build MINFO +# Written by Steve Henson 1999. + +# List of directories to process + +my @dirs = ( +".", +"crypto", +"crypto/md2", +"crypto/md4", +"crypto/md5", +"crypto/sha", +"crypto/mdc2", +"crypto/hmac", +"crypto/ripemd", +"crypto/des", +"crypto/rc2", +"crypto/rc4", +"crypto/rc5", +"crypto/idea", +"crypto/bf", +"crypto/cast", +"crypto/aes", +"crypto/camellia", +"crypto/seed", +"crypto/modes", +"crypto/bn", +"crypto/rsa", +"crypto/dsa", +"crypto/dso", +"crypto/dh", +"crypto/ec", +"crypto/ecdh", +"crypto/ecdsa", +"crypto/buffer", +"crypto/bio", +"crypto/stack", +"crypto/lhash", +"crypto/rand", +"crypto/err", +"crypto/objects", +"crypto/evp", +"crypto/asn1", +"crypto/pem", +"crypto/x509", +"crypto/x509v3", +"crypto/cms", +"crypto/conf", +"crypto/jpake", +"crypto/txt_db", +"crypto/pkcs7", +"crypto/pkcs12", +"crypto/comp", +"crypto/engine", +"crypto/ocsp", +"crypto/ui", +"crypto/krb5", +#"crypto/store", +"crypto/pqueue", +"crypto/whrlpool", +"crypto/ts", +"ssl", +"apps", +"engines", +"engines/ccgost", +"test", +"tools" +); + +%top; + +foreach (@dirs) { + &files_dir ($_, "Makefile"); +} + +exit(0); + +sub files_dir +{ +my ($dir, $makefile) = @_; + +my %sym; + +open (IN, "$dir/$makefile") || die "Can't open $dir/$makefile"; + +my $s=""; + +while () + { + chop; + s/#.*//; + if (/^(\S+)\s*=\s*(.*)$/) + { + $o=""; + ($s,$b)=($1,$2); + for (;;) + { + if ($b =~ /\\$/) + { + chop($b); + $o.=$b." "; + $b=; + chop($b); + } + else + { + $o.=$b." "; + last; + } + } + $o =~ s/^\s+//; + $o =~ s/\s+$//; + $o =~ s/\s+/ /g; + + $o =~ s/\$[({]([^)}]+)[)}]/$top{$1} or $sym{$1}/ge; + $sym{$s}=($top{$s} or $o); + } + } + +print "RELATIVE_DIRECTORY=$dir\n"; + +foreach (sort keys %sym) + { + print "$_=$sym{$_}\n"; + } +if ($dir eq "." && defined($sym{"BUILDENV"})) + { + foreach (split(' ',$sym{"BUILDENV"})) + { + /^(.+)=/; + $top{$1}=$sym{$1}; + } + } + +print "RELATIVE_DIRECTORY=\n"; + +close (IN); +} diff --git a/node-v0.8.14/deps/openssl/openssl/util/mklink.pl b/node-v0.8.14/deps/openssl/openssl/util/mklink.pl new file mode 100755 index 0000000..61db12c --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/util/mklink.pl @@ -0,0 +1,73 @@ +#!/usr/local/bin/perl + +# mklink.pl + +# The first command line argument is a non-empty relative path +# specifying the "from" directory. +# Each other argument is a file name not containing / and +# names a file in the current directory. +# +# For each of these files, we create in the "from" directory a link +# of the same name pointing to the local file. +# +# We assume that the directory structure is a tree, i.e. that it does +# not contain symbolic links and that the parent of / is never referenced. +# Apart from this, this script should be able to handle even the most +# pathological cases. + +use Cwd; + +my $from = shift; +my @files = @ARGV; + +my @from_path = split(/[\\\/]/, $from); +my $pwd = getcwd(); +chomp($pwd); +my @pwd_path = split(/[\\\/]/, $pwd); + +my @to_path = (); + +my $dirname; +foreach $dirname (@from_path) { + + # In this loop, @to_path always is a relative path from + # @pwd_path (interpreted is an absolute path) to the original pwd. + + # At the end, @from_path (as a relative path from the original pwd) + # designates the same directory as the absolute path @pwd_path, + # which means that @to_path then is a path from there to the original pwd. + + next if ($dirname eq "" || $dirname eq "."); + + if ($dirname eq "..") { + @to_path = (pop(@pwd_path), @to_path); + } else { + @to_path = ("..", @to_path); + push(@pwd_path, $dirname); + } +} + +my $to = join('/', @to_path); + +my $file; +$symlink_exists=eval {symlink("",""); 1}; +if ($^O eq "msys") { $symlink_exists=0 }; +foreach $file (@files) { + my $err = ""; + if ($symlink_exists) { + unlink "$from/$file"; + symlink("$to/$file", "$from/$file") or $err = " [$!]"; + } else { + unlink "$from/$file"; + open (OLD, "<$file") or die "Can't open $file: $!"; + open (NEW, ">$from/$file") or die "Can't open $from/$file: $!"; + binmode(OLD); + binmode(NEW); + while () { + print NEW $_; + } + close (OLD) or die "Can't close $file: $!"; + close (NEW) or die "Can't close $from/$file: $!"; + } + print $file . " => $from/$file$err\n"; +} diff --git a/node-v0.8.14/deps/openssl/openssl/util/mkrc.pl b/node-v0.8.14/deps/openssl/openssl/util/mkrc.pl new file mode 100644 index 0000000..0ceadcf --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/util/mkrc.pl @@ -0,0 +1,71 @@ +#!/bin/env perl +# +open FD,"crypto/opensslv.h"; +while() { + if (/OPENSSL_VERSION_NUMBER\s+(0x[0-9a-f]+)/i) { + $ver = hex($1); + $v1 = ($ver>>28); + $v2 = ($ver>>20)&0xff; + $v3 = ($ver>>12)&0xff; + $v4 = ($ver>> 4)&0xff; + $beta = $ver&0xf; + $version = "$v1.$v2.$v3"; + if ($beta==0xf) { $version .= chr(ord('a')+$v4-1) if ($v4); } + elsif ($beta==0){ $version .= "-dev"; } + else { $version .= "-beta$beta"; } + last; + } +} +close(FD); + +$filename = $ARGV[0]; $filename =~ /(.*)\.([^.]+)$/; +$basename = $1; +$extname = $2; + +if ($extname =~ /dll/i) { $description = "OpenSSL shared library"; } +else { $description = "OpenSSL application"; } + +print <<___; +#include + +LANGUAGE 0x09,0x01 + +1 VERSIONINFO + FILEVERSION $v1,$v2,$v3,$v4 + PRODUCTVERSION $v1,$v2,$v3,$v4 + FILEFLAGSMASK 0x3fL +#ifdef _DEBUG + FILEFLAGS 0x01L +#else + FILEFLAGS 0x00L +#endif + FILEOS VOS__WINDOWS32 + FILETYPE VFT_DLL + FILESUBTYPE 0x0L +BEGIN + BLOCK "StringFileInfo" + BEGIN + BLOCK "040904b0" + BEGIN + // Required: + VALUE "CompanyName", "The OpenSSL Project, http://www.openssl.org/\\0" + VALUE "FileDescription", "$description\\0" + VALUE "FileVersion", "$version\\0" + VALUE "InternalName", "$basename\\0" + VALUE "OriginalFilename", "$filename\\0" + VALUE "ProductName", "The OpenSSL Toolkit\\0" + VALUE "ProductVersion", "$version\\0" + // Optional: + //VALUE "Comments", "\\0" + VALUE "LegalCopyright", "Copyright 1998-2006 The OpenSSL Project. Copyright 1995-1998 Eric A. Young, Tim J. Hudson. All rights reserved.\\0" + //VALUE "LegalTrademarks", "\\0" + //VALUE "PrivateBuild", "\\0" + //VALUE "SpecialBuild", "\\0" + END + END + BLOCK "VarFileInfo" + BEGIN + VALUE "Translation", 0x409, 0x4b0 + END +END +___ diff --git a/node-v0.8.14/deps/openssl/openssl/util/mkstack.pl b/node-v0.8.14/deps/openssl/openssl/util/mkstack.pl new file mode 100755 index 0000000..f708610 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/util/mkstack.pl @@ -0,0 +1,192 @@ +#!/usr/local/bin/perl -w + +# This is a utility that searches out "DECLARE_STACK_OF()" +# declarations in .h and .c files, and updates/creates/replaces +# the corresponding macro declarations in crypto/stack/safestack.h. +# As it's not generally possible to have macros that generate macros, +# we need to control this from the "outside", here in this script. +# +# Geoff Thorpe, June, 2000 (with massive Perl-hacking +# help from Steve Robb) + +my $safestack = "crypto/stack/safestack"; + +my $do_write; +while (@ARGV) { + my $arg = $ARGV[0]; + if($arg eq "-write") { + $do_write = 1; + } + shift @ARGV; +} + + +@source = (, , , ); +foreach $file (@source) { + next if -l $file; + + # Open the .c/.h file for reading + open(IN, "< $file") || die "Can't open $file for reading: $!"; + + while() { + if (/^DECLARE_STACK_OF\(([^)]+)\)/) { + push @stacklst, $1; + } + if (/^DECLARE_SPECIAL_STACK_OF\(([^,\s]+)\s*,\s*([^>\s]+)\)/) { + push @sstacklst, [$1, $2]; + } + if (/^DECLARE_ASN1_SET_OF\(([^)]+)\)/) { + push @asn1setlst, $1; + } + if (/^DECLARE_PKCS12_STACK_OF\(([^)]+)\)/) { + push @p12stklst, $1; + } + if (/^DECLARE_LHASH_OF\(([^)]+)\)/) { + push @lhashlst, $1; + } + } + close(IN); +} + + + +my $old_stackfile = ""; +my $new_stackfile = ""; +my $inside_block = 0; +my $type_thing; + +open(IN, "< $safestack.h") || die "Can't open input file: $!"; +while() { + $old_stackfile .= $_; + + if (m|^/\* This block of defines is updated by util/mkstack.pl, please do not touch! \*/|) { + $inside_block = 1; + } + if (m|^/\* End of util/mkstack.pl block, you may now edit :-\) \*/|) { + $inside_block = 0; + } elsif ($inside_block == 0) { + $new_stackfile .= $_; + } + next if($inside_block != 1); + $new_stackfile .= "/* This block of defines is updated by util/mkstack.pl, please do not touch! */"; + + foreach $type_thing (sort @stacklst) { + $new_stackfile .= <[0]; + my $t2 = $type_thing->[1]; + $new_stackfile .= <$safestack.h" || die "Can't open output file"; + print OUT $new_stackfile; + close OUT; +} diff --git a/node-v0.8.14/deps/openssl/openssl/util/opensslwrap.sh b/node-v0.8.14/deps/openssl/openssl/util/opensslwrap.sh new file mode 100755 index 0000000..b27cbb8 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/util/opensslwrap.sh @@ -0,0 +1,26 @@ +#!/bin/sh + +HERE="`echo $0 | sed -e 's|[^/]*$||'`" +OPENSSL="${HERE}../apps/openssl" + +if [ -d "${HERE}../engines" -a "x$OPENSSL_ENGINES" = "x" ]; then + OPENSSL_ENGINES="${HERE}../engines"; export OPENSSL_ENGINES +fi + +if [ -x "${OPENSSL}.exe" ]; then + # The original reason for this script existence is to work around + # certain caveats in run-time linker behaviour. On Windows platforms + # adjusting $PATH used to be sufficient, but with introduction of + # SafeDllSearchMode in XP/2003 the only way to get it right in + # *all* possible situations is to copy newly built .DLLs to apps/ + # and test/, which is now done elsewhere... The $PATH is adjusted + # for backward compatibility (and nostagical reasons:-). + if [ "$OSTYPE" != msdosdjgpp ]; then + PATH="${HERE}..:$PATH"; export PATH + fi + exec "${OPENSSL}.exe" "$@" +elif [ -x "${OPENSSL}" -a -x "${HERE}shlib_wrap.sh" ]; then + exec "${HERE}shlib_wrap.sh" "${OPENSSL}" "$@" +else + exec "${OPENSSL}" "$@" # hope for the best... +fi diff --git a/node-v0.8.14/deps/openssl/openssl/util/perlpath.pl b/node-v0.8.14/deps/openssl/openssl/util/perlpath.pl new file mode 100755 index 0000000..a1f236b --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/util/perlpath.pl @@ -0,0 +1,35 @@ +#!/usr/local/bin/perl +# +# modify the '#!/usr/local/bin/perl' +# line in all scripts that rely on perl. +# + +require "find.pl"; + +$#ARGV == 0 || print STDERR "usage: perlpath newpath (eg /usr/bin)\n"; +&find("."); + +sub wanted + { + return unless /\.pl$/ || /^[Cc]onfigur/; + + open(IN,"<$_") || die "unable to open $dir/$_:$!\n"; + @a=; + close(IN); + + if (-d $ARGV[0]) { + $a[0]="#!$ARGV[0]/perl\n"; + } + else { + $a[0]="#!$ARGV[0]\n"; + } + + # Playing it safe... + $new="$_.new"; + open(OUT,">$new") || die "unable to open $dir/$new:$!\n"; + print OUT @a; + close(OUT); + + rename($new,$_) || die "unable to rename $dir/$new:$!\n"; + chmod(0755,$_) || die "unable to chmod $dir/$new:$!\n"; + } diff --git a/node-v0.8.14/deps/openssl/openssl/util/pl/BC-32.pl b/node-v0.8.14/deps/openssl/openssl/util/pl/BC-32.pl new file mode 100644 index 0000000..1f1e13f --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/util/pl/BC-32.pl @@ -0,0 +1,139 @@ +#!/usr/local/bin/perl +# Borland C++ builder 3 and 4 -- Janez Jere +# + +$ssl= "ssleay32"; +$crypto="libeay32"; + +$o='\\'; +$cp='copy'; +$rm='del'; + +# C compiler stuff +$cc='bcc32'; +$lflags="-ap -Tpe -x -Gn "; +$mlflags=''; + +$out_def="out32"; +$tmp_def="tmp32"; +$inc_def="inc32"; +#enable max error messages, disable most common warnings +$cflags="-DWIN32_LEAN_AND_MEAN -q -w-ccc -w-rch -w-pia -w-aus -w-par -w-inl -c -tWC -tWM -DOPENSSL_SYSNAME_WIN32 -DL_ENDIAN -DDSO_WIN32 -D_stricmp=stricmp -D_strnicmp=strnicmp "; +if ($debug) +{ + $cflags.="-Od -y -v -vi- -D_DEBUG"; + $mlflags.=' '; +} +else +{ + $cflags.="-O2 -ff -fp"; +} + +$obj='.obj'; +$ofile="-o"; + +# EXE linking stuff +$link="ilink32"; +$efile=""; +$exep='.exe'; +if ($no_sock) + { $ex_libs=""; } +else { $ex_libs="cw32mt.lib import32.lib"; } + +# static library stuff +$mklib='tlib /P64'; +$ranlib=''; +$plib=""; +$libp=".lib"; +$shlibp=($shlib)?".dll":".lib"; +$lfile=''; + +$shlib_ex_obj=""; +$app_ex_obj="c0x32.obj"; + +$asm='nasmw -f obj -d__omf__'; +$asm.=" /Zi" if $debug; +$afile='-o'; + +$bn_mulw_obj=''; +$bn_mulw_src=''; +$des_enc_obj=''; +$des_enc_src=''; +$bf_enc_obj=''; +$bf_enc_src=''; + +if (!$no_asm) + { + $bn_mulw_obj='crypto\bn\asm\bn_win32.obj'; + $bn_mulw_src='crypto\bn\asm\bn_win32.asm'; + $des_enc_obj='crypto\des\asm\d_win32.obj crypto\des\asm\y_win32.obj'; + $des_enc_src='crypto\des\asm\d_win32.asm crypto\des\asm\y_win32.asm'; + $bf_enc_obj='crypto\bf\asm\b_win32.obj'; + $bf_enc_src='crypto\bf\asm\b_win32.asm'; + $cast_enc_obj='crypto\cast\asm\c_win32.obj'; + $cast_enc_src='crypto\cast\asm\c_win32.asm'; + $rc4_enc_obj='crypto\rc4\asm\r4_win32.obj'; + $rc4_enc_src='crypto\rc4\asm\r4_win32.asm'; + $rc5_enc_obj='crypto\rc5\asm\r5_win32.obj'; + $rc5_enc_src='crypto\rc5\asm\r5_win32.asm'; + $md5_asm_obj='crypto\md5\asm\m5_win32.obj'; + $md5_asm_src='crypto\md5\asm\m5_win32.asm'; + $sha1_asm_obj='crypto\sha\asm\s1_win32.obj'; + $sha1_asm_src='crypto\sha\asm\s1_win32.asm'; + $rmd160_asm_obj='crypto\ripemd\asm\rm_win32.obj'; + $rmd160_asm_src='crypto\ripemd\asm\rm_win32.asm'; + $cflags.=" -DBN_ASM -DMD5_ASM -DSHA1_ASM -DRMD160_ASM"; + } + +if ($shlib) + { + $mlflags.=" $lflags /dll"; +# $cflags =~ s| /MD| /MT|; + $lib_cflag=" /GD -D_WINDLL -D_DLL"; + $out_def="out32dll"; + $tmp_def="tmp32dll"; + } + +sub do_lib_rule + { + local($objs,$target,$name,$shlib)=@_; + local($ret,$Name); + + $taget =~ s/\//$o/g if $o ne '/'; + ($Name=$name) =~ tr/a-z/A-Z/; + +# $target="\$(LIB_D)$o$target"; + $ret.="$target: $objs\n"; + if (!$shlib) + { + $ret.=<<___; + -\$(RM) $lfile$target + \$(MKLIB) $lfile$target \@&&! ++\$(**: = &^ ++) +! +___ + } + else + { + local($ex)=($target =~ /O_SSL/)?' $(L_CRYPTO)':''; + $ex.=' ws2_32.lib gdi32.lib'; + $ret.="\t\$(LINK) \$(MLFLAGS) $efile$target /def:ms/${Name}.def @<<\n \$(SHLIB_EX_OBJ) $objs $ex\n<<\n"; + } + $ret.="\n"; + return($ret); + } + +sub do_link_rule + { + local($target,$files,$dep_libs,$libs)=@_; + local($ret,$_); + + $file =~ s/\//$o/g if $o ne '/'; + $n=&bname($targer); + $ret.="$target: $files $dep_libs\n"; + $ret.="\t\$(LINK) \$(LFLAGS) $files \$(APP_EX_OBJ), $target,, $libs\n\n"; + return($ret); + } + +1; diff --git a/node-v0.8.14/deps/openssl/openssl/util/pl/Mingw32.pl b/node-v0.8.14/deps/openssl/openssl/util/pl/Mingw32.pl new file mode 100644 index 0000000..fe3fb27 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/util/pl/Mingw32.pl @@ -0,0 +1,104 @@ +#!/usr/local/bin/perl +# +# Mingw32.pl -- Mingw +# + +$o='/'; +$cp='cp'; +$rm='rm -f'; +$mkdir='gmkdir'; + +$o='\\'; +$cp='copy'; +$rm='del'; +$mkdir='mkdir'; + +# C compiler stuff + +$cc='gcc'; +if ($debug) + { $cflags="-DL_ENDIAN -DDSO_WIN32 -g2 -ggdb"; } +else + { $cflags="-DL_ENDIAN -DDSO_WIN32 -fomit-frame-pointer -O3 -mcpu=i486 -Wall"; } + +if ($gaswin and !$no_asm) + { + $bn_asm_obj='$(OBJ_D)\bn-win32.o'; + $bn_asm_src='crypto/bn/asm/bn-win32.s'; + $bnco_asm_obj='$(OBJ_D)\co-win32.o'; + $bnco_asm_src='crypto/bn/asm/co-win32.s'; + $des_enc_obj='$(OBJ_D)\d-win32.o $(OBJ_D)\y-win32.o'; + $des_enc_src='crypto/des/asm/d-win32.s crypto/des/asm/y-win32.s'; + $bf_enc_obj='$(OBJ_D)\b-win32.o'; + $bf_enc_src='crypto/bf/asm/b-win32.s'; +# $cast_enc_obj='$(OBJ_D)\c-win32.o'; +# $cast_enc_src='crypto/cast/asm/c-win32.s'; + $rc4_enc_obj='$(OBJ_D)\r4-win32.o'; + $rc4_enc_src='crypto/rc4/asm/r4-win32.s'; + $rc5_enc_obj='$(OBJ_D)\r5-win32.o'; + $rc5_enc_src='crypto/rc5/asm/r5-win32.s'; + $md5_asm_obj='$(OBJ_D)\m5-win32.o'; + $md5_asm_src='crypto/md5/asm/m5-win32.s'; + $rmd160_asm_obj='$(OBJ_D)\rm-win32.o'; + $rmd160_asm_src='crypto/ripemd/asm/rm-win32.s'; + $sha1_asm_obj='$(OBJ_D)\s1-win32.o'; + $sha1_asm_src='crypto/sha/asm/s1-win32.s'; + $cflags.=" -DBN_ASM -DMD5_ASM -DSHA1_ASM -DOPENSSL_BN_ASM_PART_WORDS"; + } + + +$obj='.o'; +$ofile='-o '; + +# EXE linking stuff +$link='${CC}'; +$lflags='${CFLAGS}'; +$efile='-o '; +$exep=''; +$ex_libs="-lws2_32 -lgdi32"; + +# static library stuff +$mklib='ar r'; +$mlflags=''; +$ranlib='ranlib'; +$plib='lib'; +$libp=".a"; +$shlibp=".a"; +$lfile=''; + +$asm='as'; +$afile='-o '; +#$bn_asm_obj=""; +#$bn_asm_src=""; +#$des_enc_obj=""; +#$des_enc_src=""; +#$bf_enc_obj=""; +#$bf_enc_src=""; + +sub do_lib_rule + { + local($obj,$target,$name,$shlib)=@_; + local($ret,$_,$Name); + + $target =~ s/\//$o/g if $o ne '/'; + $target="$target"; + ($Name=$name) =~ tr/a-z/A-Z/; + + $ret.="$target: \$(${Name}OBJ)\n"; + $ret.="\tif exist $target \$(RM) $target\n"; + $ret.="\t\$(MKLIB) $target \$(${Name}OBJ)\n"; + $ret.="\t\$(RANLIB) $target\n\n"; + } + +sub do_link_rule + { + local($target,$files,$dep_libs,$libs)=@_; + local($ret,$_); + + $file =~ s/\//$o/g if $o ne '/'; + $n=&bname($target); + $ret.="$target: $files $dep_libs\n"; + $ret.="\t\$(LINK) ${efile}$target \$(LFLAGS) $files $libs\n\n"; + return($ret); + } +1; diff --git a/node-v0.8.14/deps/openssl/openssl/util/pl/OS2-EMX.pl b/node-v0.8.14/deps/openssl/openssl/util/pl/OS2-EMX.pl new file mode 100644 index 0000000..28cd116 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/util/pl/OS2-EMX.pl @@ -0,0 +1,120 @@ +#!/usr/local/bin/perl +# +# OS2-EMX.pl - for EMX GCC on OS/2 +# + +$o='/'; +$cp='cp'; +$rm='rm -f'; + +$preamble = "SHELL=sh\n"; + +# C compiler stuff + +$cc='gcc'; +$cflags="-DL_ENDIAN -O3 -fomit-frame-pointer -m486 -Zmtd -Wall "; +$cflags.="-Zomf " if $shlib; +$shl_cflag="-Zdll"; + +if ($debug) { + $cflags.="-g "; +} + +$obj=$shlib ? '.obj' : '.o'; +$ofile='-o '; + +# EXE linking stuff +$link='${CC}'; +$lflags='${CFLAGS} -Zbsd-signals -s'; +$efile='-o '; +$exep='.exe'; +$ex_libs="-lsocket"; + +# static library stuff +$mklib='ar r'; +$mlflags=''; +$ranlib="ar s"; +$plib=''; +$libp=$shlib ? ".lib" : ".a"; +$shlibp=$shlib ? ".dll" : ".a"; +$lfile=''; + +$asm=$shlib ? 'as -Zomf' : 'as'; +$afile='-o '; +$bn_asm_obj=""; +$bn_asm_src=""; +$des_enc_obj=""; +$des_enc_src=""; +$bf_enc_obj=""; +$bf_enc_src=""; + +if (!$no_asm) + { + $bn_asm_obj="crypto/bn/asm/bn-os2$obj crypto/bn/asm/co-os2$obj"; + $bn_asm_src="crypto/bn/asm/bn-os2.asm crypto/bn/asm/co-os2.asm"; + $des_enc_obj="crypto/des/asm/d-os2$obj crypto/des/asm/y-os2$obj"; + $des_enc_src="crypto/des/asm/d-os2.asm crypto/des/asm/y-os2.asm"; + $bf_enc_obj="crypto/bf/asm/b-os2$obj"; + $bf_enc_src="crypto/bf/asm/b-os2.asm"; + $cast_enc_obj="crypto/cast/asm/c-os2$obj"; + $cast_enc_src="crypto/cast/asm/c-os2.asm"; + $rc4_enc_obj="crypto/rc4/asm/r4-os2$obj"; + $rc4_enc_src="crypto/rc4/asm/r4-os2.asm"; + $rc5_enc_obj="crypto/rc5/asm/r5-os2$obj"; + $rc5_enc_src="crypto/rc5/asm/r5-os2.asm"; + $md5_asm_obj="crypto/md5/asm/m5-os2$obj"; + $md5_asm_src="crypto/md5/asm/m5-os2.asm"; + $sha1_asm_obj="crypto/sha/asm/s1-os2$obj"; + $sha1_asm_src="crypto/sha/asm/s1-os2.asm"; + $rmd160_asm_obj="crypto/ripemd/asm/rm-os2$obj"; + $rmd160_asm_src="crypto/ripemd/asm/rm-os2.asm"; + $cflags.=" -DBN_ASM -DMD5_ASM -DSHA1_ASM -DOPENSSL_BN_ASM_PART_WORDS"; + } + +if ($shlib) + { + $mlflags.=" $lflags -Zdll"; + $lib_cflag=" -D_DLL"; + $out_def="out_dll"; + $tmp_def="tmp_dll"; + } + +sub do_lib_rule + { + local($obj,$target,$name,$shlib)=@_; + local($ret,$_,$Name); + + $target =~ s/\//$o/g if $o ne '/'; + $target="$target"; + ($Name=$name) =~ tr/a-z/A-Z/; + + $ret.="$target: \$(${Name}OBJ)\n"; + if (!$shlib) + { + $ret.="\t\$(RM) $target\n"; + $ret.="\t\$(MKLIB) $target \$(${Name}OBJ)\n"; + $ret.="\t\$(RANLIB) $target\n\n"; + } + else + { + local($ex)=($target =~ /O_SSL/)?' $(L_CRYPTO)':''; + $ex.=' -lsocket'; + $ret.="\t\$(LINK) \$(SHLIB_CFLAGS) \$(MLFLAGS) $efile$target \$(SHLIB_EX_OBJ) \$(${Name}OBJ) $ex os2/${Name}.def\n"; + $ret.="\temximp -o $out_def/$name.a os2/${Name}.def\n"; + $ret.="\temximp -o $out_def/$name.lib os2/${Name}.def\n\n"; + } + } + +sub do_link_rule + { + local($target,$files,$dep_libs,$libs)=@_; + local($ret,$_); + + $file =~ s/\//$o/g if $o ne '/'; + $n=&bname($target); + $ret.="$target: $files $dep_libs\n"; + $ret.="\t\$(LINK) ${efile}$target \$(CFLAG) \$(LFLAGS) $files $libs\n\n"; + return($ret); + } + +1; diff --git a/node-v0.8.14/deps/openssl/openssl/util/pl/VC-32.pl b/node-v0.8.14/deps/openssl/openssl/util/pl/VC-32.pl new file mode 100644 index 0000000..5f25fc4 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/util/pl/VC-32.pl @@ -0,0 +1,338 @@ +#!/usr/local/bin/perl +# VC-32.pl - unified script for Microsoft Visual C++, covering Win32, +# Win64 and WinCE [follow $FLAVOR variable to trace the differences]. +# + +$ssl= "ssleay32"; +$crypto="libeay32"; + +$o='\\'; +$cp='$(PERL) util/copy.pl'; +$mkdir='$(PERL) util/mkdir-p.pl'; +$rm='del /Q'; + +$zlib_lib="zlib1.lib"; + +# Santize -L options for ms link +$l_flags =~ s/-L("\[^"]+")/\/libpath:$1/g; +$l_flags =~ s/-L(\S+)/\/libpath:$1/g; + +# C compiler stuff +$cc='cl'; +if ($FLAVOR =~ /WIN64/) + { + # Note that we currently don't have /WX on Win64! There is a lot of + # warnings, but only of two types: + # + # C4344: conversion from '__int64' to 'int/long', possible loss of data + # C4267: conversion from 'size_t' to 'int/long', possible loss of data + # + # Amount of latter type is minimized by aliasing strlen to function of + # own desing and limiting its return value to 2GB-1 (see e_os.h). As + # per 0.9.8 release remaining warnings were explicitly examined and + # considered safe to ignore. + # + $base_cflags= " $mf_cflag"; + my $f = $shlib?' /MD':' /MT'; + $lib_cflag='/Zl' if (!$shlib); # remove /DEFAULTLIBs from static lib + $opt_cflags=$f.' /Ox'; + $dbg_cflags=$f.'d /Od -DDEBUG -D_DEBUG'; + $lflags="/nologo /subsystem:console /opt:ref"; + + *::perlasm_compile_target = sub { + my ($target,$source,$bname)=@_; + my $ret; + + $bname =~ s/(.*)\.[^\.]$/$1/; + $ret=<<___; +\$(TMP_D)$o$bname.asm: $source + set ASM=\$(ASM) + \$(PERL) $source \$\@ + +$target: \$(TMP_D)$o$bname.asm + \$(ASM) $afile\$\@ \$(TMP_D)$o$bname.asm + +___ + } + } +elsif ($FLAVOR =~ /CE/) + { + # sanity check + die '%OSVERSION% is not defined' if (!defined($ENV{'OSVERSION'})); + die '%PLATFORM% is not defined' if (!defined($ENV{'PLATFORM'})); + die '%TARGETCPU% is not defined' if (!defined($ENV{'TARGETCPU'})); + + # + # Idea behind this is to mimic flags set by eVC++ IDE... + # + $wcevers = $ENV{'OSVERSION'}; # WCENNN + die '%OSVERSION% value is insane' if ($wcevers !~ /^WCE([1-9])([0-9]{2})$/); + $wcecdefs = "-D_WIN32_WCE=$1$2 -DUNDER_CE=$1$2"; # -D_WIN32_WCE=NNN + $wcelflag = "/subsystem:windowsce,$1.$2"; # ...,N.NN + + $wceplatf = $ENV{'PLATFORM'}; + $wceplatf =~ tr/a-z0-9 /A-Z0-9_/d; + $wcecdefs .= " -DWCE_PLATFORM_$wceplatf"; + + $wcetgt = $ENV{'TARGETCPU'}; # just shorter name... + SWITCH: for($wcetgt) { + /^X86/ && do { $wcecdefs.=" -Dx86 -D_X86_ -D_i386_ -Di_386_"; + $wcelflag.=" /machine:IX86"; last; }; + /^ARMV4[IT]/ && do { $wcecdefs.=" -DARM -D_ARM_ -D$wcetgt"; + $wcecdefs.=" -DTHUMB -D_THUMB_" if($wcetgt=~/T$/); + $wcecdefs.=" -QRarch4T -QRinterwork-return"; + $wcelflag.=" /machine:THUMB"; last; }; + /^ARM/ && do { $wcecdefs.=" -DARM -D_ARM_ -D$wcetgt"; + $wcelflag.=" /machine:ARM"; last; }; + /^MIPSIV/ && do { $wcecdefs.=" -DMIPS -D_MIPS_ -DR4000 -D$wcetgt"; + $wcecdefs.=" -D_MIPS64 -QMmips4 -QMn32"; + $wcelflag.=" /machine:MIPSFPU"; last; }; + /^MIPS16/ && do { $wcecdefs.=" -DMIPS -D_MIPS_ -DR4000 -D$wcetgt"; + $wcecdefs.=" -DMIPSII -QMmips16"; + $wcelflag.=" /machine:MIPS16"; last; }; + /^MIPSII/ && do { $wcecdefs.=" -DMIPS -D_MIPS_ -DR4000 -D$wcetgt"; + $wcecdefs.=" -QMmips2"; + $wcelflag.=" /machine:MIPS"; last; }; + /^R4[0-9]{3}/ && do { $wcecdefs.=" -DMIPS -D_MIPS_ -DR4000"; + $wcelflag.=" /machine:MIPS"; last; }; + /^SH[0-9]/ && do { $wcecdefs.=" -D$wcetgt -D_$wcetgt_ -DSHx"; + $wcecdefs.=" -Qsh4" if ($wcetgt =~ /^SH4/); + $wcelflag.=" /machine:$wcetgt"; last; }; + { $wcecdefs.=" -D$wcetgt -D_$wcetgt_"; + $wcelflag.=" /machine:$wcetgt"; last; }; + } + + $cc='$(CC)'; + $base_cflags=' /W3 /WX /GF /Gy /nologo -DUNICODE -D_UNICODE -DOPENSSL_SYSNAME_WINCE -DWIN32_LEAN_AND_MEAN -DL_ENDIAN -DDSO_WIN32 -DNO_CHMOD -DOPENSSL_SMALL_FOOTPRINT'; + $base_cflags.=" $wcecdefs"; + $base_cflags.=' -I$(WCECOMPAT)/include' if (defined($ENV{'WCECOMPAT'})); + $base_cflags.=' -I$(PORTSDK_LIBPATH)/../../include' if (defined($ENV{'PORTSDK_LIBPATH'})); + $opt_cflags=' /MC /O1i'; # optimize for space, but with intrinsics... + $dbg_clfags=' /MC /Od -DDEBUG -D_DEBUG'; + $lflags="/nologo /opt:ref $wcelflag"; + } +else # Win32 + { + $base_cflags= " $mf_cflag"; + my $f = $shlib?' /MD':' /MT'; + $lib_cflag='/Zl' if (!$shlib); # remove /DEFAULTLIBs from static lib + $opt_cflags=$f.' /Ox /O2 /Ob2'; + $dbg_cflags=$f.'d /Od -DDEBUG -D_DEBUG'; + $lflags="/nologo /subsystem:console /opt:ref"; + } +$mlflags=''; + +$out_def ="out32"; $out_def.="dll" if ($shlib); + $out_def.='_$(TARGETCPU)' if ($FLAVOR =~ /CE/); +$tmp_def ="tmp32"; $tmp_def.="dll" if ($shlib); + $tmp_def.='_$(TARGETCPU)' if ($FLAVOR =~ /CE/); +$inc_def="inc32"; + +if ($debug) + { + $cflags=$dbg_cflags.$base_cflags; + } +else + { + $cflags=$opt_cflags.$base_cflags; + } + +# generate symbols.pdb unconditionally +$app_cflag.=" /Zi /Fd\$(TMP_D)/app"; +$lib_cflag.=" /Zi /Fd\$(TMP_D)/lib"; +$lflags.=" /debug"; + +$obj='.obj'; +$asm_suffix='.asm'; +$ofile="/Fo"; + +# EXE linking stuff +$link="link"; +$rsc="rc"; +$efile="/out:"; +$exep='.exe'; +if ($no_sock) { $ex_libs=''; } +elsif ($FLAVOR =~ /CE/) { $ex_libs='winsock.lib'; } +else { $ex_libs='ws2_32.lib'; } + +if ($FLAVOR =~ /CE/) + { + $ex_libs.=' $(WCECOMPAT)/lib/wcecompatex.lib' if (defined($ENV{'WCECOMPAT'})); + $ex_libs.=' $(PORTSDK_LIBPATH)/portlib.lib' if (defined($ENV{'PORTSDK_LIBPATH'})); + $ex_libs.=' /nodefaultlib:oldnames.lib coredll.lib corelibc.lib' if ($ENV{'TARGETCPU'} eq "X86"); + } +else + { + $ex_libs.=' gdi32.lib advapi32.lib crypt32.lib user32.lib'; + $ex_libs.=' bufferoverflowu.lib' if ($FLAVOR =~ /WIN64/ and `cl 2>&1` =~ /14\.00\.4[0-9]{4}\./); + # WIN32 UNICODE build gets linked with unicows.lib for + # backward compatibility with Win9x. + $ex_libs="unicows.lib $ex_libs" if ($FLAVOR =~ /WIN32/ and $cflags =~ /\-DUNICODE/); + } + +# static library stuff +$mklib='lib /nologo'; +$ranlib=''; +$plib=""; +$libp=".lib"; +$shlibp=($shlib)?".dll":".lib"; +$lfile='/out:'; + +$shlib_ex_obj=""; +$app_ex_obj="setargv.obj" if ($FLAVOR !~ /CE/); +if ($FLAVOR =~ /WIN64A/) { + if (`nasm -v 2>NUL` =~ /NASM version ([0-9]+\.[0-9]+)/ && $1 >= 2.0) { + $asm='nasm -f win64 -DNEAR -Ox -g'; + $afile='-o '; + } else { + $asm='ml64 /c /Cp /Cx /Zi'; + $afile='/Fo'; + } +} elsif ($FLAVOR =~ /WIN64I/) { + $asm='ias -d debug'; + $afile="-o "; +} elsif ($nasm) { + my $ver=`nasm -v 2>NUL`; + my $vew=`nasmw -v 2>NUL`; + # pick newest version + $asm=($ver ge $vew?"nasm":"nasmw")." -f win32"; + $asmtype="win32n"; + $afile='-o '; +} else { + $asm='ml /nologo /Cp /coff /c /Cx /Zi'; + $afile='/Fo'; + $asmtype="win32"; +} + +$bn_asm_obj=''; +$bn_asm_src=''; +$des_enc_obj=''; +$des_enc_src=''; +$bf_enc_obj=''; +$bf_enc_src=''; + +if (!$no_asm) + { + win32_import_asm($mf_bn_asm, "bn", \$bn_asm_obj, \$bn_asm_src); + win32_import_asm($mf_aes_asm, "aes", \$aes_asm_obj, \$aes_asm_src); + win32_import_asm($mf_des_asm, "des", \$des_enc_obj, \$des_enc_src); + win32_import_asm($mf_bf_asm, "bf", \$bf_enc_obj, \$bf_enc_src); + win32_import_asm($mf_cast_asm, "cast", \$cast_enc_obj, \$cast_enc_src); + win32_import_asm($mf_rc4_asm, "rc4", \$rc4_enc_obj, \$rc4_enc_src); + win32_import_asm($mf_rc5_asm, "rc5", \$rc5_enc_obj, \$rc5_enc_src); + win32_import_asm($mf_md5_asm, "md5", \$md5_asm_obj, \$md5_asm_src); + win32_import_asm($mf_sha_asm, "sha", \$sha1_asm_obj, \$sha1_asm_src); + win32_import_asm($mf_rmd_asm, "ripemd", \$rmd160_asm_obj, \$rmd160_asm_src); + win32_import_asm($mf_wp_asm, "whrlpool", \$whirlpool_asm_obj, \$whirlpool_asm_src); + win32_import_asm($mf_cpuid_asm, "", \$cpuid_asm_obj, \$cpuid_asm_src); + $perl_asm = 1; + } + +if ($shlib && $FLAVOR !~ /CE/) + { + $mlflags.=" $lflags /dll"; + $lib_cflag.=" -D_WINDLL"; + # + # Engage Applink... + # + $app_ex_obj.=" \$(OBJ_D)\\applink.obj /implib:\$(TMP_D)\\junk.lib"; + $cflags.=" -DOPENSSL_USE_APPLINK -I."; + # I'm open for better suggestions than overriding $banner... + $banner=<<'___'; + @echo Building OpenSSL + +$(OBJ_D)\applink.obj: ms\applink.c + $(CC) /Fo$(OBJ_D)\applink.obj $(APP_CFLAGS) -c ms\applink.c +$(OBJ_D)\uplink.obj: ms\uplink.c ms\applink.c + $(CC) /Fo$(OBJ_D)\uplink.obj $(SHLIB_CFLAGS) -c ms\uplink.c +$(INCO_D)\applink.c: ms\applink.c + $(CP) ms\applink.c $(INCO_D)\applink.c + +EXHEADER= $(EXHEADER) $(INCO_D)\applink.c + +LIBS_DEP=$(LIBS_DEP) $(OBJ_D)\applink.obj +CRYPTOOBJ=$(OBJ_D)\uplink.obj $(CRYPTOOBJ) +___ + $banner.=<<'___' if ($FLAVOR =~ /WIN64/); +CRYPTOOBJ=ms\uptable.obj $(CRYPTOOBJ) +___ + } +elsif ($shlib && $FLAVOR =~ /CE/) + { + $mlflags.=" $lflags /dll"; + $lflags.=' /entry:mainCRTstartup' if(defined($ENV{'PORTSDK_LIBPATH'})); + $lib_cflag.=" -D_WINDLL -D_DLL"; + } + +sub do_lib_rule + { + local($objs,$target,$name,$shlib)=@_; + local($ret); + + $taget =~ s/\//$o/g if $o ne '/'; + if ($name ne "") + { + $name =~ tr/a-z/A-Z/; + $name = "/def:ms/${name}.def"; + } + +# $target="\$(LIB_D)$o$target"; + $ret.="$target: $objs\n"; + if (!$shlib) + { +# $ret.="\t\$(RM) \$(O_$Name)\n"; + $ret.="\t\$(MKLIB) $lfile$target @<<\n $objs\n<<\n"; + } + else + { + local($ex)=($target =~ /O_CRYPTO/)?'':' $(L_CRYPTO)'; + $ex.=" $zlib_lib" if $zlib_opt == 1 && $target =~ /O_CRYPTO/; + $ret.="\t\$(LINK) \$(MLFLAGS) $efile$target $name @<<\n \$(SHLIB_EX_OBJ) $objs $ex \$(EX_LIBS)\n<<\n"; + $ret.="\tIF EXIST \$@.manifest mt -nologo -manifest \$@.manifest -outputresource:\$@;2\n\n"; + } + $ret.="\n"; + return($ret); + } + +sub do_link_rule + { + local($target,$files,$dep_libs,$libs)=@_; + local($ret,$_); + + $file =~ s/\//$o/g if $o ne '/'; + $n=&bname($targer); + $ret.="$target: $files $dep_libs\n"; + $ret.="\t\$(LINK) \$(LFLAGS) $efile$target @<<\n"; + $ret.=" \$(APP_EX_OBJ) $files $libs\n<<\n"; + $ret.="\tIF EXIST \$@.manifest mt -nologo -manifest \$@.manifest -outputresource:\$@;1\n\n"; + return($ret); + } + +sub win32_import_asm + { + my ($mf_var, $asm_name, $oref, $sref) = @_; + my $asm_dir; + if ($asm_name eq "") + { + $asm_dir = "crypto\\"; + } + else + { + $asm_dir = "crypto\\$asm_name\\asm\\"; + } + + $$oref = ""; + $mf_var =~ s/\.o$/.obj/g; + + foreach (split(/ /, $mf_var)) + { + $$oref .= $asm_dir . $_ . " "; + } + $$oref =~ s/ $//; + $$sref = $$oref; + $$sref =~ s/\.obj/.asm/g; + + } + + +1; diff --git a/node-v0.8.14/deps/openssl/openssl/util/pl/linux.pl b/node-v0.8.14/deps/openssl/openssl/util/pl/linux.pl new file mode 100644 index 0000000..d24f7b7 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/util/pl/linux.pl @@ -0,0 +1,104 @@ +#!/usr/local/bin/perl +# +# linux.pl - the standard unix makefile stuff. +# + +$o='/'; +$cp='/bin/cp'; +$rm='/bin/rm -f'; + +# C compiler stuff + +$cc='gcc'; +if ($debug) + { $cflags="-g2 -ggdb -DREF_CHECK -DCRYPTO_MDEBUG"; } +elsif ($profile) + { $cflags="-pg -O3"; } +else + { $cflags="-O3 -fomit-frame-pointer"; } + +if (!$no_asm) + { + $bn_asm_obj='$(OBJ_D)/bn86-elf.o'; + $bn_asm_src='crypto/bn/asm/bn86unix.cpp'; + $bnco_asm_obj='$(OBJ_D)/co86-elf.o'; + $bnco_asm_src='crypto/bn/asm/co86unix.cpp'; + $des_enc_obj='$(OBJ_D)/dx86-elf.o $(OBJ_D)/yx86-elf.o'; + $des_enc_src='crypto/des/asm/dx86unix.cpp crypto/des/asm/yx86unix.cpp'; + $bf_enc_obj='$(OBJ_D)/bx86-elf.o'; + $bf_enc_src='crypto/bf/asm/bx86unix.cpp'; + $cast_enc_obj='$(OBJ_D)/cx86-elf.o'; + $cast_enc_src='crypto/cast/asm/cx86unix.cpp'; + $rc4_enc_obj='$(OBJ_D)/rx86-elf.o'; + $rc4_enc_src='crypto/rc4/asm/rx86unix.cpp'; + $rc5_enc_obj='$(OBJ_D)/r586-elf.o'; + $rc5_enc_src='crypto/rc5/asm/r586unix.cpp'; + $md5_asm_obj='$(OBJ_D)/mx86-elf.o'; + $md5_asm_src='crypto/md5/asm/mx86unix.cpp'; + $rmd160_asm_obj='$(OBJ_D)/rm86-elf.o'; + $rmd160_asm_src='crypto/ripemd/asm/rm86unix.cpp'; + $sha1_asm_obj='$(OBJ_D)/sx86-elf.o'; + $sha1_asm_src='crypto/sha/asm/sx86unix.cpp'; + $cflags.=" -DBN_ASM -DMD5_ASM -DSHA1_ASM -DOPENSSL_BN_ASM_PART_WORDS"; + } + +$cflags.=" -DTERMIO -DL_ENDIAN -m486 -Wall"; + +if ($shlib) + { + $shl_cflag=" -DPIC -fpic"; + $shlibp=".so.$ssl_version"; + $so_shlibp=".so"; + } + +sub do_shlib_rule + { + local($obj,$target,$name,$shlib,$so_name)=@_; + local($ret,$_,$Name); + + $target =~ s/\//$o/g if $o ne '/'; + ($Name=$name) =~ tr/a-z/A-Z/; + + $ret.="$target: \$(${Name}OBJ)\n"; + $ret.="\t\$(RM) target\n"; + $ret.="\tgcc \${CFLAGS} -shared -Wl,-soname,$target -o $target \$(${Name}OBJ)\n"; + ($t=$target) =~ s/(^.*)\/[^\/]*$/$1/; + if ($so_name ne "") + { + $ret.="\t\$(RM) \$(LIB_D)$o$so_name\n"; + $ret.="\tln -s $target \$(LIB_D)$o$so_name\n\n"; + } + } + +sub do_link_rule + { + local($target,$files,$dep_libs,$libs)=@_; + local($ret,$_); + + $file =~ s/\//$o/g if $o ne '/'; + $n=&bname($target); + $ret.="$target: $files $dep_libs\n"; + $ret.="\t\$(LINK) ${efile}$target \$(LFLAGS) $files $libs\n\n"; + return($ret); + } + +sub do_asm_rule + { + local($target,$src)=@_; + local($ret,@s,@t,$i); + + $target =~ s/\//$o/g if $o ne "/"; + $src =~ s/\//$o/g if $o ne "/"; + + @s=split(/\s+/,$src); + @t=split(/\s+/,$target); + + for ($i=0; $i<=$#s; $i++) + { + $ret.="$t[$i]: $s[$i]\n"; + $ret.="\tgcc -E -DELF \$(SRC_D)$o$s[$i]|\$(AS) $afile$t[$i]\n\n"; + } + return($ret); + } + +1; diff --git a/node-v0.8.14/deps/openssl/openssl/util/pl/netware.pl b/node-v0.8.14/deps/openssl/openssl/util/pl/netware.pl new file mode 100644 index 0000000..c78bcfc --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/util/pl/netware.pl @@ -0,0 +1,532 @@ +# Metrowerks Codewarrior or gcc / nlmconv for NetWare +# + +$version_header = "crypto/opensslv.h"; +open(IN, "$version_header") or die "Couldn't open $version_header: $!"; +while () { + if (/^#define[\s\t]+OPENSSL_VERSION_NUMBER[\s\t]+0x(\d)(\d{2})(\d{2})(\d{2})/) + { + # die "OpenSSL version detected: $1.$2.$3.$4\n"; + #$nlmvernum = "$1,$2,$3"; + $nlmvernum = "$1,".($2*10+$3).",".($4*1); + #$nlmverstr = "$1.".($2*1).".".($3*1).($4?(chr(96+$4)):""); + break; + } +} +close(IN) or die "Couldn't close $version_header: $!"; + +$readme_file = "README"; +open(IN, $readme_file) or die "Couldn't open $readme_file: $!"; +while () { + if (/^[\s\t]+OpenSSL[\s\t]+(\d)\.(\d{1,2})\.(\d{1,2})([a-z])(.*)/) + { + #$nlmvernum = "$1,$2,$3"; + #$nlmvernum = "$1,".($2*10+$3).",".($4*1); + $nlmverstr = "$1.$2.$3$4$5"; + } + elsif (/^[\s\t]+(Copyright \(c\) \d{4}\-\d{4} The OpenSSL Project)$/) + { + $nlmcpystr = $1; + } + break if ($nlmvernum && $nlmcpystr); +} +close(IN) or die "Couldn't close $readme_file: $!"; + +# Define stacksize here +$nlmstack = "32768"; + +# some default settings here in case we failed to find them in README +$nlmvernum = "1,0,0" if (!$nlmvernum); +$nlmverstr = "OpenSSL" if (!$nlmverstr); +$nlmcpystr = "Copyright (c) 1998-now The OpenSSL Project" if (!$nlmcpystr); + +# die "OpenSSL copyright: $nlmcpystr\nOpenSSL verstring: $nlmverstr\nOpenSSL vernumber: $nlmvernum\n"; + +# The import files and other misc imports needed to link +@misc_imports = ("GetProcessSwitchCount", "RunningProcess", + "GetSuperHighResolutionTimer"); +if ($LIBC) +{ + @import_files = ("libc.imp"); + @module_files = ("libc"); + $libarch = "LIBC"; +} +else +{ + # clib build + @import_files = ("clib.imp"); + push(@import_files, "socklib.imp") if ($BSDSOCK); + @module_files = ("clib"); + # push(@misc_imports, "_rt_modu64%16", "_rt_divu64%16"); + $libarch = "CLIB"; +} +if ($BSDSOCK) +{ + $libarch .= "-BSD"; +} +else +{ + $libarch .= "-WS2"; + push(@import_files, "ws2nlm.imp"); +} + +# The "IMPORTS" environment variable must be set and point to the location +# where import files (*.imp) can be found. +# Example: set IMPORTS=c:\ndk\nwsdk\imports +$import_path = $ENV{"IMPORTS"} || die ("IMPORTS environment variable not set\n"); + + +# The "PRELUDE" environment variable must be set and point to the location +# and name of the prelude source to link with ( nwpre.obj is recommended ). +# Example: set PRELUDE=c:\codewar\novell support\metrowerks support\libraries\runtime\nwpre.obj +$prelude = $ENV{"PRELUDE"} || die ("PRELUDE environment variable not set\n"); + +# The "INCLUDES" environment variable must be set and point to the location +# where import files (*.imp) can be found. +$include_path = $ENV{"INCLUDE"} || die ("INCLUDES environment variable not set\n"); +$include_path =~ s/\\/\//g; +$include_path = join(" -I", split(/;/, $include_path)); + +# check for gcc compiler +$gnuc = $ENV{"GNUC"}; + +#$ssl= "ssleay32"; +#$crypto="libeay32"; + +if ($gnuc) +{ + # C compiler + $cc='gcc'; + # Linker + $link='nlmconv'; + # librarian + $mklib='ar'; + $o='/'; + # cp command + $cp='cp -af'; + # rm command + $rm='rm -f'; + # mv command + $mv='mv -f'; + # mkdir command + $mkdir='gmkdir'; + #$ranlib='ranlib'; +} +else +{ + # C compiler + $cc='mwccnlm'; + # Linker + $link='mwldnlm'; + # librarian + $mklib='mwldnlm'; + # Path separator + $o='\\'; + # cp command + $cp='copy >nul:'; + # rm command + $rm='del /f /q'; +} + +# assembler +if ($nw_nasm) +{ + $asm=(`nasm -v 2>NUL` gt `nasmw -v 2>NUL`?"nasm":"nasmw"); + if ($gnuc) + { + $asm.=" -s -f elf"; + } + else + { + $asm.=" -s -f coff -d __coff__"; + } + $afile="-o "; + $asm.=" -g" if $debug; +} +elsif ($nw_mwasm) +{ + $asm="mwasmnlm -maxerrors 20"; + $afile="-o "; + $asm.=" -g" if $debug; +} +elsif ($nw_masm) +{ +# masm assembly settings - it should be possible to use masm but haven't +# got it working. +# $asm='ml /Cp /coff /c /Cx'; +# $asm.=" /Zi" if $debug; +# $afile='/Fo'; + die("Support for masm assembler not yet functional\n"); +} +else +{ + $asm=""; + $afile=""; +} + + + +if ($gnuc) +{ + # compile flags for GNUC + # additional flags based upon debug | non-debug + if ($debug) + { + $cflags="-g -DDEBUG"; + } + else + { + $cflags="-O2"; + } + $cflags.=" -nostdinc -I$include_path \\ + -fno-builtin -fpcc-struct-return -fno-strict-aliasing \\ + -funsigned-char -Wall -Wno-unused -Wno-uninitialized"; + + # link flags + $lflags="-T"; +} +else +{ + # compile flags for CodeWarrior + # additional flags based upon debug | non-debug + if ($debug) + { + $cflags="-opt off -g -sym internal -DDEBUG"; + } + else + { + # CodeWarrior compiler has a problem with optimizations for floating + # points - no optimizations until further investigation + # $cflags="-opt all"; + } + + # NOTES: Several c files in the crypto subdirectory include headers from + # their local directories. Metrowerks wouldn't find these h files + # without adding individual include directives as compile flags + # or modifying the c files. Instead of adding individual include + # paths for each subdirectory a recursive include directive + # is used ( -ir crypto ). + # + # A similar issue exists for the engines and apps subdirectories. + # + # Turned off the "possible" warnings ( -w nopossible ). Metrowerks + # complained a lot about various stuff. May want to turn back + # on for further development. + $cflags.=" -nostdinc -ir crypto -ir engines -ir apps -I$include_path \\ + -msgstyle gcc -align 4 -processor pentium -char unsigned \\ + -w on -w nolargeargs -w nopossible -w nounusedarg -w nounusedexpr \\ + -w noimplicitconv -relax_pointers -nosyspath -maxerrors 20"; + + # link flags + $lflags="-msgstyle gcc -zerobss -nostdlib -sym internal -commandfile"; +} + +# common defines +$cflags.=" -DL_ENDIAN -DOPENSSL_SYSNAME_NETWARE -U_WIN32"; + +# If LibC build add in NKS_LIBC define and set the entry/exit +# routines - The default entry/exit routines are for CLib and don't exist +# in LibC +if ($LIBC) +{ + $cflags.=" -DNETWARE_LIBC"; + $nlmstart = "_LibCPrelude"; + $nlmexit = "_LibCPostlude"; + @nlm_flags = ("pseudopreemption", "flag_on 64"); +} +else +{ + $cflags.=" -DNETWARE_CLIB"; + $nlmstart = "_Prelude"; + $nlmexit = "_Stop"; +} + +# If BSD Socket support is requested, set a define for the compiler +if ($BSDSOCK) +{ + $cflags.=" -DNETWARE_BSDSOCK"; + if (!$LIBC) + { + $cflags.=" -DNETDB_USE_INTERNET"; + } +} + + +# linking stuff +# for the output directories use the mk1mf.pl values with "_nw" appended +if ($shlib) +{ + if ($LIBC) + { + $out_def.="_nw_libc_nlm"; + $tmp_def.="_nw_libc_nlm"; + $inc_def.="_nw_libc_nlm"; + } + else # NETWARE_CLIB + { + $out_def.="_nw_clib_nlm"; + $tmp_def.="_nw_clib_nlm"; + $inc_def.="_nw_clib_nlm"; + } +} +else +{ + if ($gnuc) # GNUC Tools + { + $libp=".a"; + $shlibp=".a"; + $lib_flags="-cr"; + } + else # CodeWarrior + { + $libp=".lib"; + $shlibp=".lib"; + $lib_flags="-nodefaults -type library -o"; + } + if ($LIBC) + { + $out_def.="_nw_libc"; + $tmp_def.="_nw_libc"; + $inc_def.="_nw_libc"; + } + else # NETWARE_CLIB + { + $out_def.="_nw_clib"; + $tmp_def.="_nw_clib"; + $inc_def.="_nw_clib"; + } +} + +# used by mk1mf.pl +$obj='.o'; +$ofile='-o '; +$efile=''; +$exep='.nlm'; +$ex_libs=''; + +if (!$no_asm) +{ + $bn_asm_obj="\$(OBJ_D)${o}bn-nw${obj}"; + $bn_asm_src="crypto${o}bn${o}asm${o}bn-nw.asm"; + $bnco_asm_obj="\$(OBJ_D)${o}co-nw${obj}"; + $bnco_asm_src="crypto${o}bn${o}asm${o}co-nw.asm"; + $aes_asm_obj="\$(OBJ_D)${o}a-nw${obj}"; + $aes_asm_src="crypto${o}aes${o}asm${o}a-nw.asm"; + $des_enc_obj="\$(OBJ_D)${o}d-nw${obj} \$(OBJ_D)${o}y-nw${obj}"; + $des_enc_src="crypto${o}des${o}asm${o}d-nw.asm crypto${o}des${o}asm${o}y-nw.asm"; + $bf_enc_obj="\$(OBJ_D)${o}b-nw${obj}"; + $bf_enc_src="crypto${o}bf${o}asm${o}b-nw.asm"; + $cast_enc_obj="\$(OBJ_D)${o}c-nw${obj}"; + $cast_enc_src="crypto${o}cast${o}asm${o}c-nw.asm"; + $rc4_enc_obj="\$(OBJ_D)${o}r4-nw${obj}"; + $rc4_enc_src="crypto${o}rc4${o}asm${o}r4-nw.asm"; + $rc5_enc_obj="\$(OBJ_D)${o}r5-nw${obj}"; + $rc5_enc_src="crypto${o}rc5${o}asm${o}r5-nw.asm"; + $md5_asm_obj="\$(OBJ_D)${o}m5-nw${obj}"; + $md5_asm_src="crypto${o}md5${o}asm${o}m5-nw.asm"; + $sha1_asm_obj="\$(OBJ_D)${o}s1-nw${obj} \$(OBJ_D)${o}sha256-nw${obj} \$(OBJ_D)${o}sha512-nw${obj}"; + $sha1_asm_src="crypto${o}sha${o}asm${o}s1-nw.asm crypto${o}sha${o}asm${o}sha256-nw.asm crypto${o}sha${o}asm${o}sha512-nw.asm"; + $rmd160_asm_obj="\$(OBJ_D)${o}rm-nw${obj}"; + $rmd160_asm_src="crypto${o}ripemd${o}asm${o}rm-nw.asm"; + $whirlpool_asm_obj="\$(OBJ_D)${o}wp-nw${obj}"; + $whirlpool_asm_src="crypto${o}whrlpool${o}asm${o}wp-nw.asm"; + $cpuid_asm_obj="\$(OBJ_D)${o}x86cpuid-nw${obj}"; + $cpuid_asm_src="crypto${o}x86cpuid-nw.asm"; + $cflags.=" -DOPENSSL_CPUID_OBJ -DBN_ASM -DOPENSSL_BN_ASM_PART_WORDS -DMD5_ASM -DWHIRLPOOL_ASM"; + $cflags.=" -DSHA1_ASM -DSHA256_ASM -DSHA512_ASM"; + $cflags.=" -DAES_ASM -DRMD160_ASM"; +} +else +{ + $bn_asm_obj=''; + $bn_asm_src=''; + $bnco_asm_obj=''; + $bnco_asm_src=''; + $aes_asm_obj=''; + $aes_asm_src=''; + $des_enc_obj=''; + $des_enc_src=''; + $bf_enc_obj=''; + $bf_enc_src=''; + $cast_enc_obj=''; + $cast_enc_src=''; + $rc4_enc_obj=''; + $rc4_enc_src=''; + $rc5_enc_obj=''; + $rc5_enc_src=''; + $md5_asm_obj=''; + $md5_asm_src=''; + $sha1_asm_obj=''; + $sha1_asm_src=''; + $rmd160_asm_obj=''; + $rmd160_asm_src=''; + $whirlpool_asm_obj=''; + $whirlpool_asm_src=''; + $cpuid_asm_obj=''; + $cpuid_asm_src=''; +} + +# create the *.def linker command files in \openssl\netware\ directory +sub do_def_file +{ + # strip off the leading path + my($target) = bname(shift); + my($i); + + if ($target =~ /(.*).nlm/) + { + $target = $1; + } + + # special case for openssl - the mk1mf.pl defines E_EXE = openssl + if ($target =~ /E_EXE/) + { + $target =~ s/\$\(E_EXE\)/openssl/; + } + + # Note: originally tried to use full path ( \openssl\netware\$target.def ) + # Metrowerks linker choked on this with an assertion failure. bug??? + # + my($def_file) = "netware${o}$target.def"; + + open(DEF_OUT, ">$def_file") || die("unable to open file $def_file\n"); + + print( DEF_OUT "# command file generated by netware.pl for NLM target.\n" ); + print( DEF_OUT "# do not edit this file - all your changes will be lost!!\n" ); + print( DEF_OUT "#\n"); + print( DEF_OUT "DESCRIPTION \"$target ($libarch) - OpenSSL $nlmverstr\"\n"); + print( DEF_OUT "COPYRIGHT \"$nlmcpystr\"\n"); + print( DEF_OUT "VERSION $nlmvernum\n"); + print( DEF_OUT "STACK $nlmstack\n"); + print( DEF_OUT "START $nlmstart\n"); + print( DEF_OUT "EXIT $nlmexit\n"); + + # special case for openssl + if ($target eq "openssl") + { + print( DEF_OUT "SCREENNAME \"OpenSSL $nlmverstr\"\n"); + } + else + { + print( DEF_OUT "SCREENNAME \"DEFAULT\"\n"); + } + + foreach $i (@misc_imports) + { + print( DEF_OUT "IMPORT $i\n"); + } + + foreach $i (@import_files) + { + print( DEF_OUT "IMPORT \@$import_path${o}$i\n"); + } + + foreach $i (@module_files) + { + print( DEF_OUT "MODULE $i\n"); + } + + foreach $i (@nlm_flags) + { + print( DEF_OUT "$i\n"); + } + + if ($gnuc) + { + if ($target =~ /openssl/) + { + print( DEF_OUT "INPUT ${tmp_def}${o}openssl${obj}\n"); + print( DEF_OUT "INPUT ${tmp_def}${o}openssl${libp}\n"); + } + else + { + print( DEF_OUT "INPUT ${tmp_def}${o}${target}${obj}\n"); + } + print( DEF_OUT "INPUT $prelude\n"); + print( DEF_OUT "INPUT ${out_def}${o}${ssl}${libp} ${out_def}${o}${crypto}${libp}\n"); + print( DEF_OUT "OUTPUT $target.nlm\n"); + } + + close(DEF_OUT); + return($def_file); +} + +sub do_lib_rule +{ + my($objs,$target,$name,$shlib)=@_; + my($ret); + + $ret.="$target: $objs\n"; + if (!$shlib) + { + $ret.="\t\@echo Building Lib: $name\n"; + $ret.="\t\$(MKLIB) $lib_flags $target $objs\n"; + $ret.="\t\@echo .\n" + } + else + { + die( "Building as NLM not currently supported!" ); + } + + $ret.="\n"; + return($ret); +} + +sub do_link_rule +{ + my($target,$files,$dep_libs,$libs)=@_; + my($ret); + my($def_file) = do_def_file($target); + + $ret.="$target: $files $dep_libs\n"; + + # NOTE: When building the test nlms no screen name is given + # which causes the console screen to be used. By using the console + # screen there is no "" message which + # requires user interaction. The test script ( do_tests.pl ) needs + # to be able to run the tests without requiring user interaction. + # + # However, the sample program "openssl.nlm" is used by the tests and is + # a interactive sample so a screen is desired when not be run by the + # tests. To solve the problem, two versions of the program are built: + # openssl2 - no screen used by tests + # openssl - default screen - use for normal interactive modes + # + + # special case for openssl - the mk1mf.pl defines E_EXE = openssl + if ($target =~ /E_EXE/) + { + my($target2) = $target; + + $target2 =~ s/\(E_EXE\)/\(E_EXE\)2/; + + # openssl2 + my($def_file2) = do_def_file($target2); + + if ($gnuc) + { + $ret.="\t\$(MKLIB) $lib_flags \$(TMP_D)${o}\$(E_EXE).a \$(filter-out \$(TMP_D)${o}\$(E_EXE)${obj},$files)\n"; + $ret.="\t\$(LINK) \$(LFLAGS) $def_file2\n"; + $ret.="\t\@$mv \$(E_EXE)2.nlm \$(TEST_D)\n"; + } + else + { + $ret.="\t\$(LINK) \$(LFLAGS) $def_file2 $files \"$prelude\" $libs -o $target2\n"; + } + } + if ($gnuc) + { + $ret.="\t\$(LINK) \$(LFLAGS) $def_file\n"; + $ret.="\t\@$mv \$(\@F) \$(TEST_D)\n"; + } + else + { + $ret.="\t\$(LINK) \$(LFLAGS) $def_file $files \"$prelude\" $libs -o $target\n"; + } + + $ret.="\n"; + return($ret); + +} + +1; diff --git a/node-v0.8.14/deps/openssl/openssl/util/pl/ultrix.pl b/node-v0.8.14/deps/openssl/openssl/util/pl/ultrix.pl new file mode 100644 index 0000000..ea370c7 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/util/pl/ultrix.pl @@ -0,0 +1,38 @@ +#!/usr/local/bin/perl +# +# linux.pl - the standard unix makefile stuff. +# + +$o='/'; +$cp='/bin/cp'; +$rm='/bin/rm -f'; + +# C compiler stuff + +$cc='cc'; +if ($debug) + { $cflags="-g -DREF_CHECK -DCRYPTO_MDEBUG"; } +else + { $cflags="-O2"; } + +$cflags.=" -std1 -DL_ENDIAN"; + +if (!$no_asm) + { + $bn_asm_obj='$(OBJ_D)/mips1.o'; + $bn_asm_src='crypto/bn/asm/mips1.s'; + } + +sub do_link_rule + { + local($target,$files,$dep_libs,$libs)=@_; + local($ret,$_); + + $file =~ s/\//$o/g if $o ne '/'; + $n=&bname($target); + $ret.="$target: $files $dep_libs\n"; + $ret.="\t\$(LINK) ${efile}$target \$(LFLAGS) $files $libs\n\n"; + return($ret); + } + +1; diff --git a/node-v0.8.14/deps/openssl/openssl/util/pl/unix.pl b/node-v0.8.14/deps/openssl/openssl/util/pl/unix.pl new file mode 100644 index 0000000..146611a --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/util/pl/unix.pl @@ -0,0 +1,96 @@ +#!/usr/local/bin/perl +# +# unix.pl - the standard unix makefile stuff. +# + +$o='/'; +$cp='/bin/cp'; +$rm='/bin/rm -f'; + +# C compiler stuff + +if ($gcc) + { + $cc='gcc'; + if ($debug) + { $cflags="-g2 -ggdb"; } + else + { $cflags="-O3 -fomit-frame-pointer"; } + } +else + { + $cc='cc'; + if ($debug) + { $cflags="-g"; } + else + { $cflags="-O"; } + } +$obj='.o'; +$ofile='-o '; + +# EXE linking stuff +$link='${CC}'; +$lflags='${CFLAGS}'; +$efile='-o '; +$exep=''; +$ex_libs=""; + +# static library stuff +$mklib='ar r'; +$mlflags=''; +$ranlib=&which("ranlib") or $ranlib="true"; +$plib='lib'; +$libp=".a"; +$shlibp=".a"; +$lfile=''; + +$asm='as'; +$afile='-o '; +$bn_asm_obj=""; +$bn_asm_src=""; +$des_enc_obj=""; +$des_enc_src=""; +$bf_enc_obj=""; +$bf_enc_src=""; + +sub do_lib_rule + { + local($obj,$target,$name,$shlib)=@_; + local($ret,$_,$Name); + + $target =~ s/\//$o/g if $o ne '/'; + $target="$target"; + ($Name=$name) =~ tr/a-z/A-Z/; + + $ret.="$target: \$(${Name}OBJ)\n"; + $ret.="\t\$(RM) $target\n"; + $ret.="\t\$(MKLIB) $target \$(${Name}OBJ)\n"; + $ret.="\t\$(RANLIB) $target\n\n"; + } + +sub do_link_rule + { + local($target,$files,$dep_libs,$libs)=@_; + local($ret,$_); + + $file =~ s/\//$o/g if $o ne '/'; + $n=&bname($target); + $ret.="$target: $files $dep_libs\n"; + $ret.="\t\$(LINK) ${efile}$target \$(LFLAGS) $files $libs\n\n"; + return($ret); + } + +sub which + { + my ($name)=@_; + my $path; + foreach $path (split /:/, $ENV{PATH}) + { + if (-x "$path/$name") + { + return "$path/$name"; + } + } + } + +1; diff --git a/node-v0.8.14/deps/openssl/openssl/util/pod2man.pl b/node-v0.8.14/deps/openssl/openssl/util/pod2man.pl new file mode 100755 index 0000000..025d914 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/util/pod2man.pl @@ -0,0 +1,1184 @@ +: #!/usr/bin/perl-5.005 + eval 'exec /usr/bin/perl -S $0 ${1+"$@"}' + if $running_under_some_shell; + +$DEF_PM_SECTION = '3pm' || '3'; + +=head1 NAME + +pod2man - translate embedded Perl pod directives into man pages + +=head1 SYNOPSIS + +B +[ B<--section=>I ] +[ B<--release=>I ] +[ B<--center=>I ] +[ B<--date=>I ] +[ B<--fixed=>I ] +[ B<--official> ] +[ B<--lax> ] +I + +=head1 DESCRIPTION + +B converts its input file containing embedded pod directives (see +L) into nroff source suitable for viewing with nroff(1) or +troff(1) using the man(7) macro set. + +Besides the obvious pod conversions, B also takes care of +func(), func(n), and simple variable references like $foo or @bar so +you don't have to use code escapes for them; complex expressions like +C<$fred{'stuff'}> will still need to be escaped, though. Other nagging +little roffish things that it catches include translating the minus in +something like foo-bar, making a long dash--like this--into a real em +dash, fixing up "paired quotes", putting a little space after the +parens in something like func(), making C++ and PI look right, making +double underbars have a little tiny space between them, making ALLCAPS +a teeny bit smaller in troff(1), and escaping backslashes so you don't +have to. + +=head1 OPTIONS + +=over 8 + +=item center + +Set the centered header to a specific string. The default is +"User Contributed Perl Documentation", unless the C<--official> flag is +given, in which case the default is "Perl Programmers Reference Guide". + +=item date + +Set the left-hand footer string to this value. By default, +the modification date of the input file will be used. + +=item fixed + +The fixed font to use for code refs. Defaults to CW. + +=item official + +Set the default header to indicate that this page is of +the standard release in case C<--center> is not given. + +=item release + +Set the centered footer. By default, this is the current +perl release. + +=item section + +Set the section for the C<.TH> macro. The standard conventions on +sections are to use 1 for user commands, 2 for system calls, 3 for +functions, 4 for devices, 5 for file formats, 6 for games, 7 for +miscellaneous information, and 8 for administrator commands. This works +best if you put your Perl man pages in a separate tree, like +F. By default, section 1 will be used +unless the file ends in F<.pm> in which case section 3 will be selected. + +=item lax + +Don't complain when required sections aren't present. + +=back + +=head1 Anatomy of a Proper Man Page + +For those not sure of the proper layout of a man page, here's +an example of the skeleton of a proper man page. Head of the +major headers should be setout as a C<=head1> directive, and +are historically written in the rather startling ALL UPPER CASE +format, although this is not mandatory. +Minor headers may be included using C<=head2>, and are +typically in mixed case. + +=over 10 + +=item NAME + +Mandatory section; should be a comma-separated list of programs or +functions documented by this podpage, such as: + + foo, bar - programs to do something + +=item SYNOPSIS + +A short usage summary for programs and functions, which +may someday be deemed mandatory. + +=item DESCRIPTION + +Long drawn out discussion of the program. It's a good idea to break this +up into subsections using the C<=head2> directives, like + + =head2 A Sample Subection + + =head2 Yet Another Sample Subection + +=item OPTIONS + +Some people make this separate from the description. + +=item RETURN VALUE + +What the program or function returns if successful. + +=item ERRORS + +Exceptions, return codes, exit stati, and errno settings. + +=item EXAMPLES + +Give some example uses of the program. + +=item ENVIRONMENT + +Envariables this program might care about. + +=item FILES + +All files used by the program. You should probably use the FEE +for these. + +=item SEE ALSO + +Other man pages to check out, like man(1), man(7), makewhatis(8), or catman(8). + +=item NOTES + +Miscellaneous commentary. + +=item CAVEATS + +Things to take special care with; sometimes called WARNINGS. + +=item DIAGNOSTICS + +All possible messages the program can print out--and +what they mean. + +=item BUGS + +Things that are broken or just don't work quite right. + +=item RESTRICTIONS + +Bugs you don't plan to fix :-) + +=item AUTHOR + +Who wrote it (or AUTHORS if multiple). + +=item HISTORY + +Programs derived from other sources sometimes have this, or +you might keep a modification log here. + +=back + +=head1 EXAMPLES + + pod2man program > program.1 + pod2man some_module.pm > /usr/perl/man/man3/some_module.3 + pod2man --section=7 note.pod > note.7 + +=head1 DIAGNOSTICS + +The following diagnostics are generated by B. Items +marked "(W)" are non-fatal, whereas the "(F)" errors will cause +B to immediately exit with a non-zero status. + +=over 4 + +=item bad option in paragraph %d of %s: ``%s'' should be [%s]<%s> + +(W) If you start include an option, you should set it off +as bold, italic, or code. + +=item can't open %s: %s + +(F) The input file wasn't available for the given reason. + +=item Improper man page - no dash in NAME header in paragraph %d of %s + +(W) The NAME header did not have an isolated dash in it. This is +considered important. + +=item Invalid man page - no NAME line in %s + +(F) You did not include a NAME header, which is essential. + +=item roff font should be 1 or 2 chars, not `%s' (F) + +(F) The font specified with the C<--fixed> option was not +a one- or two-digit roff font. + +=item %s is missing required section: %s + +(W) Required sections include NAME, DESCRIPTION, and if you're +using a section starting with a 3, also a SYNOPSIS. Actually, +not having a NAME is a fatal. + +=item Unknown escape: %s in %s + +(W) An unknown HTML entity (probably for an 8-bit character) was given via +a CE> directive. Besides amp, lt, gt, and quot, recognized +entities are Aacute, aacute, Acirc, acirc, AElig, aelig, Agrave, agrave, +Aring, aring, Atilde, atilde, Auml, auml, Ccedil, ccedil, Eacute, eacute, +Ecirc, ecirc, Egrave, egrave, ETH, eth, Euml, euml, Iacute, iacute, Icirc, +icirc, Igrave, igrave, Iuml, iuml, Ntilde, ntilde, Oacute, oacute, Ocirc, +ocirc, Ograve, ograve, Oslash, oslash, Otilde, otilde, Ouml, ouml, szlig, +THORN, thorn, Uacute, uacute, Ucirc, ucirc, Ugrave, ugrave, Uuml, uuml, +Yacute, yacute, and yuml. + +=item Unmatched =back + +(W) You have a C<=back> without a corresponding C<=over>. + +=item Unrecognized pod directive: %s + +(W) You specified a pod directive that isn't in the known list of +C<=head1>, C<=head2>, C<=item>, C<=over>, C<=back>, or C<=cut>. + + +=back + +=head1 NOTES + +If you would like to print out a lot of man page continuously, you +probably want to set the C and D registers to set contiguous page +numbering and even/odd paging, at least on some versions of man(7). +Settting the F register will get you some additional experimental +indexing: + + troff -man -rC1 -rD1 -rF1 perl.1 perldata.1 perlsyn.1 ... + +The indexing merely outputs messages via C<.tm> for each +major page, section, subsection, item, and any CE> +directives. + + +=head1 RESTRICTIONS + +None at this time. + +=head1 BUGS + +The =over and =back directives don't really work right. They +take absolute positions instead of offsets, don't nest well, and +making people count is suboptimal in any event. + +=head1 AUTHORS + +Original prototype by Larry Wall, but so massively hacked over by +Tom Christiansen such that Larry probably doesn't recognize it anymore. + +=cut + +$/ = ""; +$cutting = 1; +@Indices = (); + +# We try first to get the version number from a local binary, in case we're +# running an installed version of Perl to produce documentation from an +# uninstalled newer version's pod files. +if ($^O ne 'plan9' and $^O ne 'dos' and $^O ne 'os2' and $^O ne 'MSWin32') { + my $perl = (-x './perl' && -f './perl' ) ? + './perl' : + ((-x '../perl' && -f '../perl') ? + '../perl' : + ''); + ($version,$patch) = `$perl -e 'print $]'` =~ /^(\d\.\d{3})(\d{2})?/ if $perl; +} +# No luck; we'll just go with the running Perl's version +($version,$patch) = $] =~ /^(.{5})(\d{2})?/ unless $version; +$DEF_RELEASE = "perl $version"; +$DEF_RELEASE .= ", patch $patch" if $patch; + + +sub makedate { + my $secs = shift; + my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime($secs); + my $mname = (qw{Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec})[$mon]; + $year += 1900; + return "$mday/$mname/$year"; +} + +use Getopt::Long; + +$DEF_SECTION = 1; +$DEF_CENTER = "User Contributed Perl Documentation"; +$STD_CENTER = "Perl Programmers Reference Guide"; +$DEF_FIXED = 'CW'; +$DEF_LAX = 0; + +sub usage { + warn "$0: @_\n" if @_; + die <"; +$Filename = $name; +if ($section =~ /^1/) { + require File::Basename; + $name = uc File::Basename::basename($name); +} +$name =~ s/\.(pod|p[lm])$//i; + +# Lose everything up to the first of +# */lib/*perl* standard or site_perl module +# */*perl*/lib from -D prefix=/opt/perl +# */*perl*/ random module hierarchy +# which works. +$name =~ s-//+-/-g; +if ($name =~ s-^.*?/lib/[^/]*perl[^/]*/--i + or $name =~ s-^.*?/[^/]*perl[^/]*/lib/--i + or $name =~ s-^.*?/[^/]*perl[^/]*/--i) { + # Lose ^site(_perl)?/. + $name =~ s-^site(_perl)?/--; + # Lose ^arch/. (XXX should we use Config? Just for archname?) + $name =~ s~^(.*-$^O|$^O-.*)/~~o; + # Lose ^version/. + $name =~ s-^\d+\.\d+/--; +} + +# Translate Getopt/Long to Getopt::Long, etc. +$name =~ s(/)(::)g; + +if ($name ne 'something') { + FCHECK: { + open(F, "< $ARGV[0]") || die "can't open $ARGV[0]: $!"; + while () { + next unless /^=\b/; + if (/^=head1\s+NAME\s*$/) { # an /m would forgive mistakes + $_ = ; + unless (/\s*-+\s+/) { + $oops++; + warn "$0: Improper man page - no dash in NAME header in paragraph $. of $ARGV[0]\n" + } else { + my @n = split /\s+-+\s+/; + if (@n != 2) { + $oops++; + warn "$0: Improper man page - malformed NAME header in paragraph $. of $ARGV[0]\n" + } + else { + $n[0] =~ s/\n/ /g; + $n[1] =~ s/\n/ /g; + %namedesc = @n; + } + } + last FCHECK; + } + next if /^=cut\b/; # DB_File and Net::Ping have =cut before NAME + next if /^=pod\b/; # It is OK to have =pod before NAME + next if /^=(for|begin|end)\s+comment\b/; # It is OK to have =for =begin or =end comment before NAME + die "$0: Invalid man page - 1st pod line is not NAME in $ARGV[0]\n" unless $lax; + } + die "$0: Invalid man page - no documentation in $ARGV[0]\n" unless $lax; + } + close F; +} + +print <<"END"; +.rn '' }` +''' \$RCSfile\$\$Revision\$\$Date\$ +''' +''' \$Log\$ +''' +.de Sh +.br +.if t .Sp +.ne 5 +.PP +\\fB\\\\\$1\\fR +.PP +.. +.de Sp +.if t .sp .5v +.if n .sp +.. +.de Ip +.br +.ie \\\\n(.\$>=3 .ne \\\\\$3 +.el .ne 3 +.IP "\\\\\$1" \\\\\$2 +.. +.de Vb +.ft $CFont +.nf +.ne \\\\\$1 +.. +.de Ve +.ft R + +.fi +.. +''' +''' +''' Set up \\*(-- to give an unbreakable dash; +''' string Tr holds user defined translation string. +''' Bell System Logo is used as a dummy character. +''' +.tr \\(*W-|\\(bv\\*(Tr +.ie n \\{\\ +.ds -- \\(*W- +.ds PI pi +.if (\\n(.H=4u)&(1m=24u) .ds -- \\(*W\\h'-12u'\\(*W\\h'-12u'-\\" diablo 10 pitch +.if (\\n(.H=4u)&(1m=20u) .ds -- \\(*W\\h'-12u'\\(*W\\h'-8u'-\\" diablo 12 pitch +.ds L" "" +.ds R" "" +''' \\*(M", \\*(S", \\*(N" and \\*(T" are the equivalent of +''' \\*(L" and \\*(R", except that they are used on ".xx" lines, +''' such as .IP and .SH, which do another additional levels of +''' double-quote interpretation +.ds M" """ +.ds S" """ +.ds N" """"" +.ds T" """"" +.ds L' ' +.ds R' ' +.ds M' ' +.ds S' ' +.ds N' ' +.ds T' ' +'br\\} +.el\\{\\ +.ds -- \\(em\\| +.tr \\*(Tr +.ds L" `` +.ds R" '' +.ds M" `` +.ds S" '' +.ds N" `` +.ds T" '' +.ds L' ` +.ds R' ' +.ds M' ` +.ds S' ' +.ds N' ` +.ds T' ' +.ds PI \\(*p +'br\\} +END + +print <<'END'; +.\" If the F register is turned on, we'll generate +.\" index entries out stderr for the following things: +.\" TH Title +.\" SH Header +.\" Sh Subsection +.\" Ip Item +.\" X<> Xref (embedded +.\" Of course, you have to process the output yourself +.\" in some meaninful fashion. +.if \nF \{ +.de IX +.tm Index:\\$1\t\\n%\t"\\$2" +.. +.nr % 0 +.rr F +.\} +END + +print <<"END"; +.TH $name $section "$RP" "$date" "$center" +.UC +END + +push(@Indices, qq{.IX Title "$name $section"}); + +while (($name, $desc) = each %namedesc) { + for ($name, $desc) { s/^\s+//; s/\s+$//; } + push(@Indices, qq(.IX Name "$name - $desc"\n)); +} + +print <<'END'; +.if n .hy 0 +.if n .na +.ds C+ C\v'-.1v'\h'-1p'\s-2+\h'-1p'+\s0\v'.1v'\h'-1p' +.de CQ \" put $1 in typewriter font +END +print ".ft $CFont\n"; +print <<'END'; +'if n "\c +'if t \\&\\$1\c +'if n \\&\\$1\c +'if n \&" +\\&\\$2 \\$3 \\$4 \\$5 \\$6 \\$7 +'.ft R +.. +.\" @(#)ms.acc 1.5 88/02/08 SMI; from UCB 4.2 +. \" AM - accent mark definitions +.bd B 3 +. \" fudge factors for nroff and troff +.if n \{\ +. ds #H 0 +. ds #V .8m +. ds #F .3m +. ds #[ \f1 +. ds #] \fP +.\} +.if t \{\ +. ds #H ((1u-(\\\\n(.fu%2u))*.13m) +. ds #V .6m +. ds #F 0 +. ds #[ \& +. ds #] \& +.\} +. \" simple accents for nroff and troff +.if n \{\ +. ds ' \& +. ds ` \& +. ds ^ \& +. ds , \& +. ds ~ ~ +. ds ? ? +. ds ! ! +. ds / +. ds q +.\} +.if t \{\ +. ds ' \\k:\h'-(\\n(.wu*8/10-\*(#H)'\'\h"|\\n:u" +. ds ` \\k:\h'-(\\n(.wu*8/10-\*(#H)'\`\h'|\\n:u' +. ds ^ \\k:\h'-(\\n(.wu*10/11-\*(#H)'^\h'|\\n:u' +. ds , \\k:\h'-(\\n(.wu*8/10)',\h'|\\n:u' +. ds ~ \\k:\h'-(\\n(.wu-\*(#H-.1m)'~\h'|\\n:u' +. ds ? \s-2c\h'-\w'c'u*7/10'\u\h'\*(#H'\zi\d\s+2\h'\w'c'u*8/10' +. ds ! \s-2\(or\s+2\h'-\w'\(or'u'\v'-.8m'.\v'.8m' +. ds / \\k:\h'-(\\n(.wu*8/10-\*(#H)'\z\(sl\h'|\\n:u' +. ds q o\h'-\w'o'u*8/10'\s-4\v'.4m'\z\(*i\v'-.4m'\s+4\h'\w'o'u*8/10' +.\} +. \" troff and (daisy-wheel) nroff accents +.ds : \\k:\h'-(\\n(.wu*8/10-\*(#H+.1m+\*(#F)'\v'-\*(#V'\z.\h'.2m+\*(#F'.\h'|\\n:u'\v'\*(#V' +.ds 8 \h'\*(#H'\(*b\h'-\*(#H' +.ds v \\k:\h'-(\\n(.wu*9/10-\*(#H)'\v'-\*(#V'\*(#[\s-4v\s0\v'\*(#V'\h'|\\n:u'\*(#] +.ds _ \\k:\h'-(\\n(.wu*9/10-\*(#H+(\*(#F*2/3))'\v'-.4m'\z\(hy\v'.4m'\h'|\\n:u' +.ds . \\k:\h'-(\\n(.wu*8/10)'\v'\*(#V*4/10'\z.\v'-\*(#V*4/10'\h'|\\n:u' +.ds 3 \*(#[\v'.2m'\s-2\&3\s0\v'-.2m'\*(#] +.ds o \\k:\h'-(\\n(.wu+\w'\(de'u-\*(#H)/2u'\v'-.3n'\*(#[\z\(de\v'.3n'\h'|\\n:u'\*(#] +.ds d- \h'\*(#H'\(pd\h'-\w'~'u'\v'-.25m'\f2\(hy\fP\v'.25m'\h'-\*(#H' +.ds D- D\\k:\h'-\w'D'u'\v'-.11m'\z\(hy\v'.11m'\h'|\\n:u' +.ds th \*(#[\v'.3m'\s+1I\s-1\v'-.3m'\h'-(\w'I'u*2/3)'\s-1o\s+1\*(#] +.ds Th \*(#[\s+2I\s-2\h'-\w'I'u*3/5'\v'-.3m'o\v'.3m'\*(#] +.ds ae a\h'-(\w'a'u*4/10)'e +.ds Ae A\h'-(\w'A'u*4/10)'E +.ds oe o\h'-(\w'o'u*4/10)'e +.ds Oe O\h'-(\w'O'u*4/10)'E +. \" corrections for vroff +.if v .ds ~ \\k:\h'-(\\n(.wu*9/10-\*(#H)'\s-2\u~\d\s+2\h'|\\n:u' +.if v .ds ^ \\k:\h'-(\\n(.wu*10/11-\*(#H)'\v'-.4m'^\v'.4m'\h'|\\n:u' +. \" for low resolution devices (crt and lpr) +.if \n(.H>23 .if \n(.V>19 \ +\{\ +. ds : e +. ds 8 ss +. ds v \h'-1'\o'\(aa\(ga' +. ds _ \h'-1'^ +. ds . \h'-1'. +. ds 3 3 +. ds o a +. ds d- d\h'-1'\(ga +. ds D- D\h'-1'\(hy +. ds th \o'bp' +. ds Th \o'LP' +. ds ae ae +. ds Ae AE +. ds oe oe +. ds Oe OE +.\} +.rm #[ #] #H #V #F C +END + +$indent = 0; + +$begun = ""; + +# Unrolling [^A-Z>]|[A-Z](?!<) gives: // MRE pp 165. +my $nonest = '(?:[^A-Z>]*(?:[A-Z](?!<)[^A-Z>]*)*)'; + +while (<>) { + if ($cutting) { + next unless /^=/; + $cutting = 0; + } + if ($begun) { + if (/^=end\s+$begun/) { + $begun = ""; + } + elsif ($begun =~ /^(roff|man)$/) { + print STDOUT $_; + } + next; + } + chomp; + + # Translate verbatim paragraph + + if (/^\s/) { + @lines = split(/\n/); + for (@lines) { + 1 while s + {^( [^\t]* ) \t ( \t* ) } + { $1 . ' ' x (8 - (length($1)%8) + 8 * (length($2))) }ex; + s/\\/\\e/g; + s/\A/\\&/s; + } + $lines = @lines; + makespace() unless $verbatim++; + print ".Vb $lines\n"; + print join("\n", @lines), "\n"; + print ".Ve\n"; + $needspace = 0; + next; + } + + $verbatim = 0; + + if (/^=for\s+(\S+)\s*/s) { + if ($1 eq "man" or $1 eq "roff") { + print STDOUT $',"\n\n"; + } else { + # ignore unknown for + } + next; + } + elsif (/^=begin\s+(\S+)\s*/s) { + $begun = $1; + if ($1 eq "man" or $1 eq "roff") { + print STDOUT $'."\n\n"; + } + next; + } + + # check for things that'll hosed our noremap scheme; affects $_ + init_noremap(); + + if (!/^=item/) { + + # trofficate backslashes; must do it before what happens below + s/\\/noremap('\\e')/ge; + + # protect leading periods and quotes against *roff + # mistaking them for directives + s/^(?:[A-Z]<)?[.']/\\&$&/gm; + + # first hide the escapes in case we need to + # intuit something and get it wrong due to fmting + + 1 while s/([A-Z]<$nonest>)/noremap($1)/ge; + + # func() is a reference to a perl function + s{ + \b + ( + [:\w]+ \(\) + ) + } {I<$1>}gx; + + # func(n) is a reference to a perl function or a man page + s{ + ([:\w]+) + ( + \( [^\051]+ \) + ) + } {I<$1>\\|$2}gx; + + # convert simple variable references + s/(\s+)([\$\@%][\w:]+)(?!\()/${1}C<$2>/g; + + if (m{ ( + [\-\w]+ + \( + [^\051]*? + [\@\$,] + [^\051]*? + \) + ) + }x && $` !~ /([LCI]<[^<>]*|-)$/ && !/^=\w/) + { + warn "$0: bad option in paragraph $. of $ARGV: ``$1'' should be [LCI]<$1>\n"; + $oops++; + } + + while (/(-[a-zA-Z])\b/g && $` !~ /[\w\-]$/) { + warn "$0: bad option in paragraph $. of $ARGV: ``$1'' should be [CB]<$1>\n"; + $oops++; + } + + # put it back so we get the <> processed again; + clear_noremap(0); # 0 means leave the E's + + } else { + # trofficate backslashes + s/\\/noremap('\\e')/ge; + + } + + # need to hide E<> first; they're processed in clear_noremap + s/(E<[^<>]+>)/noremap($1)/ge; + + + $maxnest = 10; + while ($maxnest-- && /[A-Z]/font($1) . $2 . font('R')/eg; + + # files and filelike refs in italics + s/F<($nonest)>/I<$1>/g; + + # no break -- usually we want C<> for this + s/S<($nonest)>/nobreak($1)/eg; + + # LREF: a la HREF L + s:L<([^|>]+)\|[^>]+>:$1:g; + + # LREF: a manpage(3f) + s:L<([a-zA-Z][^\s\/]+)(\([^\)]+\))?>:the I<$1>$2 manpage:g; + + # LREF: an =item on another manpage + s{ + L< + ([^/]+) + / + ( + [:\w]+ + (\(\))? + ) + > + } {the C<$2> entry in the I<$1> manpage}gx; + + # LREF: an =item on this manpage + s{ + ((?: + L< + / + ( + [:\w]+ + (\(\))? + ) + > + (,?\s+(and\s+)?)? + )+) + } { internal_lrefs($1) }gex; + + # LREF: a =head2 (head1?), maybe on a manpage, maybe right here + # the "func" can disambiguate + s{ + L< + (?: + ([a-zA-Z]\S+?) / + )? + "?(.*?)"? + > + }{ + do { + $1 # if no $1, assume it means on this page. + ? "the section on I<$2> in the I<$1> manpage" + : "the section on I<$2>" + } + }gesx; # s in case it goes over multiple lines, so . matches \n + + s/Z<>/\\&/g; + + # comes last because not subject to reprocessing + s/C<($nonest)>/noremap("${CFont_embed}${1}\\fR")/eg; + } + + if (s/^=//) { + $needspace = 0; # Assume this. + + s/\n/ /g; + + ($Cmd, $_) = split(' ', $_, 2); + + $dotlevel = 1; + if ($Cmd eq 'head1') { + $dotlevel = 1; + } + elsif ($Cmd eq 'head2') { + $dotlevel = 1; + } + elsif ($Cmd eq 'item') { + $dotlevel = 2; + } + + if (defined $_) { + &escapes($dotlevel); + s/"/""/g; + } + + clear_noremap(1); + + if ($Cmd eq 'cut') { + $cutting = 1; + } + elsif ($Cmd eq 'head1') { + s/\s+$//; + delete $wanna_see{$_} if exists $wanna_see{$_}; + print qq{.SH "$_"\n}; + push(@Indices, qq{.IX Header "$_"\n}); + } + elsif ($Cmd eq 'head2') { + print qq{.Sh "$_"\n}; + push(@Indices, qq{.IX Subsection "$_"\n}); + } + elsif ($Cmd eq 'over') { + push(@indent,$indent); + $indent += ($_ + 0) || 5; + } + elsif ($Cmd eq 'back') { + $indent = pop(@indent); + warn "$0: Unmatched =back in paragraph $. of $ARGV\n" unless defined $indent; + $needspace = 1; + } + elsif ($Cmd eq 'item') { + s/^\*( |$)/\\(bu$1/g; + # if you know how to get ":s please do + s/\\\*\(L"([^"]+?)\\\*\(R"/'$1'/g; + s/\\\*\(L"([^"]+?)""/'$1'/g; + s/[^"]""([^"]+?)""[^"]/'$1'/g; + # here do something about the $" in perlvar? + print STDOUT qq{.Ip "$_" $indent\n}; + push(@Indices, qq{.IX Item "$_"\n}); + } + elsif ($Cmd eq 'pod') { + # this is just a comment + } + else { + warn "$0: Unrecognized pod directive in paragraph $. of $ARGV: $Cmd\n"; + } + } + else { + if ($needspace) { + &makespace; + } + &escapes(0); + clear_noremap(1); + print $_, "\n"; + $needspace = 1; + } +} + +print <<"END"; + +.rn }` '' +END + +if (%wanna_see && !$lax) { + @missing = keys %wanna_see; + warn "$0: $Filename is missing required section" + . (@missing > 1 && "s") + . ": @missing\n"; + $oops++; +} + +foreach (@Indices) { print "$_\n"; } + +exit; +#exit ($oops != 0); + +######################################################################### + +sub nobreak { + my $string = shift; + $string =~ s/ /\\ /g; + $string; +} + +sub escapes { + my $indot = shift; + + s/X<(.*?)>/mkindex($1)/ge; + + # translate the minus in foo-bar into foo\-bar for roff + s/([^0-9a-z-])-([^-])/$1\\-$2/g; + + # make -- into the string version \*(-- (defined above) + s/\b--\b/\\*(--/g; + s/"--([^"])/"\\*(--$1/g; # should be a better way + s/([^"])--"/$1\\*(--"/g; + + # fix up quotes; this is somewhat tricky + my $dotmacroL = 'L'; + my $dotmacroR = 'R'; + if ( $indot == 1 ) { + $dotmacroL = 'M'; + $dotmacroR = 'S'; + } + elsif ( $indot >= 2 ) { + $dotmacroL = 'N'; + $dotmacroR = 'T'; + } + if (!/""/) { + s/(^|\s)(['"])/noremap("$1\\*($dotmacroL$2")/ge; + s/(['"])($|[\-\s,;\\!?.])/noremap("\\*($dotmacroR$1$2")/ge; + } + + #s/(?!")(?:.)--(?!")(?:.)/\\*(--/g; + #s/(?:(?!")(?:.)--(?:"))|(?:(?:")--(?!")(?:.))/\\*(--/g; + + + # make sure that func() keeps a bit a space tween the parens + ### s/\b\(\)/\\|()/g; + ### s/\b\(\)/(\\|)/g; + + # make C++ into \*C+, which is a squinched version (defined above) + s/\bC\+\+/\\*(C+/g; + + # make double underbars have a little tiny space between them + s/__/_\\|_/g; + + # PI goes to \*(PI (defined above) + s/\bPI\b/noremap('\\*(PI')/ge; + + # make all caps a teeny bit smaller, but don't muck with embedded code literals + my $hidCFont = font('C'); + if ($Cmd !~ /^head1/) { # SH already makes smaller + # /g isn't enough; 1 while or we'll be off + +# 1 while s{ +# (?!$hidCFont)(..|^.|^) +# \b +# ( +# [A-Z][\/A-Z+:\-\d_$.]+ +# ) +# (s?) +# \b +# } {$1\\s-1$2\\s0}gmox; + + 1 while s{ + (?!$hidCFont)(..|^.|^) + ( + \b[A-Z]{2,}[\/A-Z+:\-\d_\$]*\b + ) + } { + $1 . noremap( '\\s-1' . $2 . '\\s0' ) + }egmox; + + } +} + +# make troff just be normal, but make small nroff get quoted +# decided to just put the quotes in the text; sigh; +sub ccvt { + local($_,$prev) = @_; + noremap(qq{.CQ "$_" \n\\&}); +} + +sub makespace { + if ($indent) { + print ".Sp\n"; + } + else { + print ".PP\n"; + } +} + +sub mkindex { + my ($entry) = @_; + my @entries = split m:\s*/\s*:, $entry; + push @Indices, ".IX Xref " . join ' ', map {qq("$_")} @entries; + return ''; +} + +sub font { + local($font) = shift; + return '\\f' . noremap($font); +} + +sub noremap { + local($thing_to_hide) = shift; + $thing_to_hide =~ tr/\000-\177/\200-\377/; + return $thing_to_hide; +} + +sub init_noremap { + # escape high bit characters in input stream + s/([\200-\377])/"E<".ord($1).">"/ge; +} + +sub clear_noremap { + my $ready_to_print = $_[0]; + + tr/\200-\377/\000-\177/; + + # trofficate backslashes + # s/(?!\\e)(?:..|^.|^)\\/\\e/g; + + # now for the E<>s, which have been hidden until now + # otherwise the interative \w<> processing would have + # been hosed by the E + s { + E< + ( + ( \d + ) + | ( [A-Za-z]+ ) + ) + > + } { + do { + defined $2 + ? chr($2) + : + exists $HTML_Escapes{$3} + ? do { $HTML_Escapes{$3} } + : do { + warn "$0: Unknown escape in paragraph $. of $ARGV: ``$&''\n"; + "E<$1>"; + } + } + }egx if $ready_to_print; +} + +sub internal_lrefs { + local($_) = shift; + local $trailing_and = s/and\s+$// ? "and " : ""; + + s{L]+)>}{$1}g; + my(@items) = split( /(?:,?\s+(?:and\s+)?)/ ); + my $retstr = "the "; + my $i; + for ($i = 0; $i <= $#items; $i++) { + $retstr .= "C<$items[$i]>"; + $retstr .= ", " if @items > 2 && $i != $#items; + $retstr .= " and " if $i+2 == @items; + } + + $retstr .= " entr" . ( @items > 1 ? "ies" : "y" ) + . " elsewhere in this document"; + # terminal space to avoid words running together (pattern used + # strips terminal spaces) + $retstr .= " " if length $trailing_and; + $retstr .= $trailing_and; + + return $retstr; + +} + +BEGIN { +%HTML_Escapes = ( + 'amp' => '&', # ampersand + 'lt' => '<', # left chevron, less-than + 'gt' => '>', # right chevron, greater-than + 'quot' => '"', # double quote + + "Aacute" => "A\\*'", # capital A, acute accent + "aacute" => "a\\*'", # small a, acute accent + "Acirc" => "A\\*^", # capital A, circumflex accent + "acirc" => "a\\*^", # small a, circumflex accent + "AElig" => '\*(AE', # capital AE diphthong (ligature) + "aelig" => '\*(ae', # small ae diphthong (ligature) + "Agrave" => "A\\*`", # capital A, grave accent + "agrave" => "A\\*`", # small a, grave accent + "Aring" => 'A\\*o', # capital A, ring + "aring" => 'a\\*o', # small a, ring + "Atilde" => 'A\\*~', # capital A, tilde + "atilde" => 'a\\*~', # small a, tilde + "Auml" => 'A\\*:', # capital A, dieresis or umlaut mark + "auml" => 'a\\*:', # small a, dieresis or umlaut mark + "Ccedil" => 'C\\*,', # capital C, cedilla + "ccedil" => 'c\\*,', # small c, cedilla + "Eacute" => "E\\*'", # capital E, acute accent + "eacute" => "e\\*'", # small e, acute accent + "Ecirc" => "E\\*^", # capital E, circumflex accent + "ecirc" => "e\\*^", # small e, circumflex accent + "Egrave" => "E\\*`", # capital E, grave accent + "egrave" => "e\\*`", # small e, grave accent + "ETH" => '\\*(D-', # capital Eth, Icelandic + "eth" => '\\*(d-', # small eth, Icelandic + "Euml" => "E\\*:", # capital E, dieresis or umlaut mark + "euml" => "e\\*:", # small e, dieresis or umlaut mark + "Iacute" => "I\\*'", # capital I, acute accent + "iacute" => "i\\*'", # small i, acute accent + "Icirc" => "I\\*^", # capital I, circumflex accent + "icirc" => "i\\*^", # small i, circumflex accent + "Igrave" => "I\\*`", # capital I, grave accent + "igrave" => "i\\*`", # small i, grave accent + "Iuml" => "I\\*:", # capital I, dieresis or umlaut mark + "iuml" => "i\\*:", # small i, dieresis or umlaut mark + "Ntilde" => 'N\*~', # capital N, tilde + "ntilde" => 'n\*~', # small n, tilde + "Oacute" => "O\\*'", # capital O, acute accent + "oacute" => "o\\*'", # small o, acute accent + "Ocirc" => "O\\*^", # capital O, circumflex accent + "ocirc" => "o\\*^", # small o, circumflex accent + "Ograve" => "O\\*`", # capital O, grave accent + "ograve" => "o\\*`", # small o, grave accent + "Oslash" => "O\\*/", # capital O, slash + "oslash" => "o\\*/", # small o, slash + "Otilde" => "O\\*~", # capital O, tilde + "otilde" => "o\\*~", # small o, tilde + "Ouml" => "O\\*:", # capital O, dieresis or umlaut mark + "ouml" => "o\\*:", # small o, dieresis or umlaut mark + "szlig" => '\*8', # small sharp s, German (sz ligature) + "THORN" => '\\*(Th', # capital THORN, Icelandic + "thorn" => '\\*(th',, # small thorn, Icelandic + "Uacute" => "U\\*'", # capital U, acute accent + "uacute" => "u\\*'", # small u, acute accent + "Ucirc" => "U\\*^", # capital U, circumflex accent + "ucirc" => "u\\*^", # small u, circumflex accent + "Ugrave" => "U\\*`", # capital U, grave accent + "ugrave" => "u\\*`", # small u, grave accent + "Uuml" => "U\\*:", # capital U, dieresis or umlaut mark + "uuml" => "u\\*:", # small u, dieresis or umlaut mark + "Yacute" => "Y\\*'", # capital Y, acute accent + "yacute" => "y\\*'", # small y, acute accent + "yuml" => "y\\*:", # small y, dieresis or umlaut mark +); +} + diff --git a/node-v0.8.14/deps/openssl/openssl/util/pod2mantest b/node-v0.8.14/deps/openssl/openssl/util/pod2mantest new file mode 100755 index 0000000..384e683 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/util/pod2mantest @@ -0,0 +1,58 @@ +#!/bin/sh + +# This script is used by test/Makefile to check whether a sane 'pod2man' +# is installed. +# ('make install' should not try to run 'pod2man' if it does not exist or if +# it is a broken 'pod2man' version that is known to cause trouble. if we find +# the system 'pod2man' to be broken, we use our own copy instead) +# +# In any case, output an appropriate command line for running (or not +# running) pod2man. + + +IFS=: +if test "$OSTYPE" = "msdosdjgpp"; then IFS=";"; fi + +try_without_dir=true +# First we try "pod2man", then "$dir/pod2man" for each item in $PATH. +for dir in dummy${IFS}$PATH; do + if [ "$try_without_dir" = true ]; then + # first iteration + pod2man=pod2man + try_without_dir=false + else + # second and later iterations + pod2man="$dir/pod2man" + if [ ! -f "$pod2man" ]; then # '-x' is not available on Ultrix + pod2man='' + fi + fi + + if [ ! "$pod2man" = '' ]; then + failure=none + + if "$pod2man" --section=1 --center=OpenSSL --release=dev pod2mantest.pod | fgrep OpenSSL >/dev/null; then + : + else + failure=BasicTest + fi + + if [ "$failure" = none ]; then + if "$pod2man" --section=1 --center=OpenSSL --release=dev pod2mantest.pod | grep '^MARKER - ' >/dev/null; then + failure=MultilineTest + fi + fi + + + if [ "$failure" = none ]; then + echo "$pod2man" + exit 0 + fi + + echo "$pod2man does not work properly ('$failure' failed). Looking for another pod2man ..." >&2 + fi +done + +echo "No working pod2man found. Consider installing a new version." >&2 +echo "As a workaround, we'll use a bundled old copy of pod2man.pl." >&2 +echo "$1 ../../util/pod2man.pl" diff --git a/node-v0.8.14/deps/openssl/openssl/util/pod2mantest.pod b/node-v0.8.14/deps/openssl/openssl/util/pod2mantest.pod new file mode 100644 index 0000000..5d2539a --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/util/pod2mantest.pod @@ -0,0 +1,15 @@ +=pod + +=head1 NAME + +foo, bar, +MARKER - test of multiline name section + +=head1 DESCRIPTION + +This is a test .pod file to see if we have a buggy pod2man or not. +If we have a buggy implementation, we will get a line matching the +regular expression "^ +MARKER - test of multiline name section *$" +at the end of the resulting document. + +=cut diff --git a/node-v0.8.14/deps/openssl/openssl/util/point.sh b/node-v0.8.14/deps/openssl/openssl/util/point.sh new file mode 100755 index 0000000..da39899 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/util/point.sh @@ -0,0 +1,10 @@ +#!/bin/sh + +rm -f "$2" +if test "$OSTYPE" = msdosdjgpp || test "x$PLATFORM" = xmingw ; then + cp "$1" "$2" +else + ln -s "$1" "$2" +fi +echo "$2 => $1" + diff --git a/node-v0.8.14/deps/openssl/openssl/util/selftest.pl b/node-v0.8.14/deps/openssl/openssl/util/selftest.pl new file mode 100644 index 0000000..7b32e9f --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/util/selftest.pl @@ -0,0 +1,201 @@ +#!/usr/local/bin/perl -w +# +# Run the test suite and generate a report +# + +if (! -f "Configure") { + print "Please run perl util/selftest.pl in the OpenSSL directory.\n"; + exit 1; +} + +my $report="testlog"; +my $os="??"; +my $version="??"; +my $platform0="??"; +my $platform="??"; +my $options="??"; +my $last="??"; +my $ok=0; +my $cc="cc"; +my $cversion="??"; +my $sep="-----------------------------------------------------------------------------\n"; +my $not_our_fault="\nPlease ask your system administrator/vendor for more information.\n[Problems with your operating system setup should not be reported\nto the OpenSSL project.]\n"; + +open(OUT,">$report") or die; + +print OUT "OpenSSL self-test report:\n\n"; + +$uname=`uname -a`; +$uname="??\n" if $uname eq ""; + +$c=`sh config -t`; +foreach $_ (split("\n",$c)) { + $os=$1 if (/Operating system: (.*)$/); + $platform0=$1 if (/Configuring for (.*)$/); +} + +system "sh config" if (! -f "Makefile"); + +if (open(IN,") { + $version=$1 if (/^VERSION=(.*)$/); + $platform=$1 if (/^PLATFORM=(.*)$/); + $options=$1 if (/^OPTIONS=(.*)$/); + $cc=$1 if (/^CC= *(.*)$/); + } + close(IN); +} else { + print OUT "Error running config!\n"; +} + +$cversion=`$cc -v 2>&1`; +$cversion=`$cc -V 2>&1` if $cversion =~ "[Uu]sage"; +$cversion=`$cc -V |head -1` if $cversion =~ "Error"; +$cversion=`$cc --version` if $cversion eq ""; +$cversion =~ s/Reading specs.*\n//; +$cversion =~ s/usage.*\n//; +chomp $cversion; + +if (open(IN,") { + if (/\*\) (.{0,55})/ && !/applies to/) { + $last=$1; + last; + } + } + close(IN); +} + +print OUT "OpenSSL version: $version\n"; +print OUT "Last change: $last...\n"; +print OUT "Options: $options\n" if $options ne ""; +print OUT "OS (uname): $uname"; +print OUT "OS (config): $os\n"; +print OUT "Target (default): $platform0\n"; +print OUT "Target: $platform\n"; +print OUT "Compiler: $cversion\n"; +print OUT "\n"; + +print "Checking compiler...\n"; +if (open(TEST,">cctest.c")) { + print TEST "#include \n#include \n#include \nmain(){printf(\"Hello world\\n\");}\n"; + close(TEST); + system("$cc -o cctest cctest.c"); + if (`./cctest` !~ /Hello world/) { + print OUT "Compiler doesn't work.\n"; + print OUT $not_our_fault; + goto err; + } + system("ar r cctest.a /dev/null"); + if (not -f "cctest.a") { + print OUT "Check your archive tool (ar).\n"; + print OUT $not_our_fault; + goto err; + } +} else { + print OUT "Can't create cctest.c\n"; +} +if (open(TEST,">cctest.c")) { + print TEST "#include \n#include \n#include \nmain(){printf(OPENSSL_VERSION_TEXT);}\n"; + close(TEST); + system("$cc -o cctest -Iinclude cctest.c"); + $cctest = `./cctest`; + if ($cctest !~ /OpenSSL $version/) { + if ($cctest =~ /OpenSSL/) { + print OUT "#include uses headers from different OpenSSL version!\n"; + } else { + print OUT "Can't compile test program!\n"; + } + print OUT $not_our_fault; + goto err; + } +} else { + print OUT "Can't create cctest.c\n"; +} + +print "Running make...\n"; +if (system("make 2>&1 | tee make.log") > 255) { + + print OUT "make failed!\n"; + if (open(IN,") { + print OUT; + } + close(IN); + print OUT $sep; + } else { + print OUT "make.log not found!\n"; + } + goto err; +} + +# Not sure why this is here. The tests themselves can detect if their +# particular feature isn't included, and should therefore skip themselves. +# To skip *all* tests just because one algorithm isn't included is like +# shooting mosquito with an elephant gun... +# -- Richard Levitte, inspired by problem report 1089 +# +#$_=$options; +#s/no-asm//; +#s/no-shared//; +#s/no-krb5//; +#if (/no-/) +#{ +# print OUT "Test skipped.\n"; +# goto err; +#} + +print "Running make test...\n"; +if (system("make test 2>&1 | tee maketest.log") > 255) + { + print OUT "make test failed!\n"; +} else { + $ok=1; +} + +if ($ok and open(IN,") { + $ok=2 if /^platform: $platform/; + } + close(IN); +} + +if ($ok != 2) { + print OUT "Failure!\n"; + if (open(IN,") { + print OUT; + } + close(IN); + print OUT $sep; + } else { + print OUT "make.log not found!\n"; + } + if (open(IN,") { + print OUT; + } + close(IN); + print OUT $sep; + } else { + print OUT "maketest.log not found!\n"; + } +} else { + print OUT "Test passed.\n"; +} +err: +close(OUT); + +print "\n"; +open(IN,"<$report") or die; +while () { + if (/$sep/) { + print "[...]\n"; + last; + } + print; +} +print "\nTest report in file $report\n"; + diff --git a/node-v0.8.14/deps/openssl/openssl/util/shlib_wrap.sh b/node-v0.8.14/deps/openssl/openssl/util/shlib_wrap.sh new file mode 100755 index 0000000..9416d59 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/util/shlib_wrap.sh @@ -0,0 +1,93 @@ +#!/bin/sh + +[ $# -ne 0 ] || set -x # debug mode without arguments:-) + +THERE="`echo $0 | sed -e 's|[^/]*$||' 2>/dev/null`.." +[ -d "${THERE}" ] || exec "$@" # should never happen... + +# Alternative to this is to parse ${THERE}/Makefile... +LIBCRYPTOSO="${THERE}/libcrypto.so" +if [ -f "$LIBCRYPTOSO" ]; then + while [ -h "$LIBCRYPTOSO" ]; do + LIBCRYPTOSO="${THERE}/`ls -l "$LIBCRYPTOSO" | sed -e 's|.*\-> ||'`" + done + SOSUFFIX=`echo ${LIBCRYPTOSO} | sed -e 's|.*\.so||' 2>/dev/null` + LIBSSLSO="${THERE}/libssl.so${SOSUFFIX}" +fi + +SYSNAME=`(uname -s) 2>/dev/null`; +case "$SYSNAME" in +SunOS|IRIX*) + # SunOS and IRIX run-time linkers evaluate alternative + # variables depending on target ABI... + rld_var=LD_LIBRARY_PATH + case "`(/usr/bin/file "$LIBCRYPTOSO") 2>/dev/null`" in + *ELF\ 64*SPARC*|*ELF\ 64*AMD64*) + [ -n "$LD_LIBRARY_PATH_64" ] && rld_var=LD_LIBRARY_PATH_64 + LD_PRELOAD_64="$LIBCRYPTOSO $LIBSSLSO"; export LD_PRELOAD_64 + preload_var=LD_PRELOAD_64 + ;; + # Why are newly built .so's preloaded anyway? Because run-time + # .so lookup path embedded into application takes precedence + # over LD_LIBRARY_PATH and as result application ends up linking + # to previously installed .so's. On IRIX instead of preloading + # newly built .so's we trick run-time linker to fail to find + # the installed .so by setting _RLD_ROOT variable. + *ELF\ 32*MIPS*) + #_RLD_LIST="$LIBCRYPTOSO:$LIBSSLSO:DEFAULT"; export _RLD_LIST + _RLD_ROOT=/no/such/dir; export _RLD_ROOT + eval $rld_var=\"/usr/lib'${'$rld_var':+:$'$rld_var'}'\" + preload_var=_RLD_LIST + ;; + *ELF\ N32*MIPS*) + [ -n "$LD_LIBRARYN32_PATH" ] && rld_var=LD_LIBRARYN32_PATH + #_RLDN32_LIST="$LIBCRYPTOSO:$LIBSSLSO:DEFAULT"; export _RLDN32_LIST + _RLDN32_ROOT=/no/such/dir; export _RLDN32_ROOT + eval $rld_var=\"/usr/lib32'${'$rld_var':+:$'$rld_var'}'\" + preload_var=_RLDN32_LIST + ;; + *ELF\ 64*MIPS*) + [ -n "$LD_LIBRARY64_PATH" ] && rld_var=LD_LIBRARY64_PATH + #_RLD64_LIST="$LIBCRYPTOSO:$LIBSSLSO:DEFAULT"; export _RLD64_LIST + _RLD64_ROOT=/no/such/dir; export _RLD64_ROOT + eval $rld_var=\"/usr/lib64'${'$rld_var':+:$'$rld_var'}'\" + preload_var=_RLD64_LIST + ;; + esac + eval $rld_var=\"${THERE}'${'$rld_var':+:$'$rld_var'}'\"; export $rld_var + unset rld_var + ;; +*) LD_LIBRARY_PATH="${THERE}:$LD_LIBRARY_PATH" # Linux, ELF HP-UX + DYLD_LIBRARY_PATH="${THERE}:$DYLD_LIBRARY_PATH" # MacOS X + SHLIB_PATH="${THERE}:$SHLIB_PATH" # legacy HP-UX + LIBPATH="${THERE}:$LIBPATH" # AIX, OS/2 + export LD_LIBRARY_PATH DYLD_LIBRARY_PATH SHLIB_PATH LIBPATH + # Even though $PATH is adjusted [for Windows sake], it doesn't + # necessarily does the trick. Trouble is that with introduction + # of SafeDllSearchMode in XP/2003 it's more appropriate to copy + # .DLLs in vicinity of executable, which is done elsewhere... + if [ "$OSTYPE" != msdosdjgpp ]; then + PATH="${THERE}:$PATH"; export PATH + fi + ;; +esac + +if [ -f "$LIBCRYPTOSO" -a -z "$preload_var" ]; then + # Following three lines are major excuse for isolating them into + # this wrapper script. Original reason for setting LD_PRELOAD + # was to make it possible to pass 'make test' when user linked + # with -rpath pointing to previous version installation. Wrapping + # it into a script makes it possible to do so on multi-ABI + # platforms. + case "$SYSNAME" in + *BSD|QNX) LD_PRELOAD="$LIBCRYPTOSO:$LIBSSLSO" ;; # *BSD, QNX + *) LD_PRELOAD="$LIBCRYPTOSO $LIBSSLSO" ;; # SunOS, Linux, ELF HP-UX + esac + _RLD_LIST="$LIBCRYPTOSO:$LIBSSLSO:DEFAULT" # Tru64, o32 IRIX + DYLD_INSERT_LIBRARIES="$LIBCRYPTOSO:$LIBSSLSO" # MacOS X + export LD_PRELOAD _RLD_LIST DYLD_INSERT_LIBRARIES +fi + +cmd="$1${EXE_EXT}" +shift +exec "$cmd" "$@" diff --git a/node-v0.8.14/deps/openssl/openssl/util/sp-diff.pl b/node-v0.8.14/deps/openssl/openssl/util/sp-diff.pl new file mode 100755 index 0000000..9d6c603 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/util/sp-diff.pl @@ -0,0 +1,80 @@ +#!/usr/local/bin/perl +# +# This file takes as input, the files that have been output from +# ssleay speed. +# It prints a table of the relative differences with %100 being 'no difference' +# + +($#ARGV == 1) || die "$0 speedout1 speedout2\n"; + +%one=&loadfile($ARGV[0]); +%two=&loadfile($ARGV[1]); + +$line=0; +foreach $a ("md2","md4","md5","sha","sha1","rc4","des cfb","des cbc","des ede3", + "idea cfb","idea cbc","rc2 cfb","rc2 cbc","blowfish cbc","cast cbc") + { + if (defined($one{$a,8}) && defined($two{$a,8})) + { + print "type 8 byte% 64 byte% 256 byte% 1024 byte% 8192 byte%\n" + unless $line; + $line++; + printf "%-12s ",$a; + foreach $b (8,64,256,1024,8192) + { + $r=$two{$a,$b}/$one{$a,$b}*100; + printf "%12.2f",$r; + } + print "\n"; + } + } + +foreach $a ( + "rsa 512","rsa 1024","rsa 2048","rsa 4096", + "dsa 512","dsa 1024","dsa 2048", + ) + { + if (defined($one{$a,1}) && defined($two{$a,1})) + { + $r1=($one{$a,1}/$two{$a,1})*100; + $r2=($one{$a,2}/$two{$a,2})*100; + printf "$a bits %% %6.2f %% %6.2f\n",$r1,$r2; + } + } + +sub loadfile + { + local($file)=@_; + local($_,%ret); + + open(IN,"<$file") || die "unable to open '$file' for input\n"; + $header=1; + while () + { + $header=0 if /^[dr]sa/; + if (/^type/) { $header=0; next; } + next if $header; + chop; + @a=split; + if ($a[0] =~ /^[dr]sa$/) + { + ($n,$t1,$t2)=($_ =~ /^([dr]sa\s+\d+)\s+bits\s+([.\d]+)s\s+([.\d]+)/); + $ret{$n,1}=$t1; + $ret{$n,2}=$t2; + } + else + { + $n=join(' ',grep(/[^k]$/,@a)); + @k=grep(s/k$//,@a); + + $ret{$n, 8}=$k[0]; + $ret{$n, 64}=$k[1]; + $ret{$n, 256}=$k[2]; + $ret{$n,1024}=$k[3]; + $ret{$n,8192}=$k[4]; + } + } + close(IN); + return(%ret); + } + diff --git a/node-v0.8.14/deps/openssl/openssl/util/speed.sh b/node-v0.8.14/deps/openssl/openssl/util/speed.sh new file mode 100755 index 0000000..f489706 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/util/speed.sh @@ -0,0 +1,39 @@ +#!/bin/sh + +# +# This is a ugly script use, in conjuction with editing the 'b' +# configuration in the $(TOP)/Configure script which will +# output when finished a file called speed.log which is the +# timings of SSLeay with various options turned on or off. +# +# from the $(TOP) directory +# Edit Configure, modifying things to do with the b/bl-4c-2c etc +# configurations. +# + +make clean +perl Configure b +make +apps/ssleay version -v -b -f >speed.1 +apps/ssleay speed >speed.1l + +perl Configure bl-4c-2c +/bin/rm -f crypto/rc4/*.o crypto/bn/bn*.o crypto/md2/md2_dgst.o +make +apps/ssleay speed rc4 rsa md2 >speed.2l + +perl Configure bl-4c-ri +/bin/rm -f crypto/rc4/rc4*.o +make +apps/ssleay speed rc4 >speed.3l + +perl Configure b2-is-ri-dp +/bin/rm -f crypto/idea/i_*.o crypto/rc4/*.o crypto/des/ecb_enc.o crypto/bn/bn*.o +apps/ssleay speed rsa rc4 idea des >speed.4l + +cat speed.1 >speed.log +cat speed.1l >>speed.log +perl util/sp-diff.pl speed.1l speed.2l >>speed.log +perl util/sp-diff.pl speed.1l speed.3l >>speed.log +perl util/sp-diff.pl speed.1l speed.4l >>speed.log + diff --git a/node-v0.8.14/deps/openssl/openssl/util/src-dep.pl b/node-v0.8.14/deps/openssl/openssl/util/src-dep.pl new file mode 100755 index 0000000..ad997e4 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/util/src-dep.pl @@ -0,0 +1,147 @@ +#!/usr/local/bin/perl + +# we make up an array of +# $file{function_name}=filename; +# $unres{filename}="func1 func2 ...." +$debug=1; +#$nm_func="parse_linux"; +$nm_func="parse_solaris"; + +foreach (@ARGV) + { + &$nm_func($_); + } + +foreach $file (sort keys %unres) + { + @a=split(/\s+/,$unres{$file}); + %ff=(); + foreach $func (@a) + { + $f=$file{$func}; + $ff{$f}=1 if $f ne ""; + } + + foreach $a (keys %ff) + { $we_need{$file}.="$a "; } + } + +foreach $file (sort keys %we_need) + { +# print " $file $we_need{$file}\n"; + foreach $bit (split(/\s+/,$we_need{$file})) + { push(@final,&walk($bit)); } + + foreach (@final) { $fin{$_}=1; } + @final=""; + foreach (sort keys %fin) + { push(@final,$_); } + + print "$file: @final\n"; + } + +sub walk + { + local($f)=@_; + local(@a,%seen,@ret,$r); + + @ret=""; + $f =~ s/^\s+//; + $f =~ s/\s+$//; + return "" if ($f =~ "^\s*$"); + + return(split(/\s/,$done{$f})) if defined ($done{$f}); + + return if $in{$f} > 0; + $in{$f}++; + push(@ret,$f); + foreach $r (split(/\s+/,$we_need{$f})) + { + push(@ret,&walk($r)); + } + $in{$f}--; + $done{$f}=join(" ",@ret); + return(@ret); + } + +sub parse_linux + { + local($name)=@_; + + open(IN,"nm $name|") || die "unable to run 'nn $name':$!\n"; + while () + { + chop; + next if /^\s*$/; + if (/^[^[](.*):$/) + { + $file=$1; + $file="$1.c" if /\[(.*).o\]/; + print STDERR "$file\n"; + $we_need{$file}=" "; + next; + } + + @a=split(/\s*\|\s*/); + next unless $#a == 7; + next unless $a[4] eq "GLOB"; + if ($a[6] eq "UNDEF") + { + $unres{$file}.=$a[7]." "; + } + else + { + if ($file{$a[7]} ne "") + { + print STDERR "duplicate definition of $a[7],\n$file{$a[7]} and $file \n"; + } + else + { + $file{$a[7]}=$file; + } + } + } + close(IN); + } + +sub parse_solaris + { + local($name)=@_; + + open(IN,"nm $name|") || die "unable to run 'nn $name':$!\n"; + while () + { + chop; + next if /^\s*$/; + if (/^(\S+):$/) + { + $file=$1; + #$file="$1.c" if $file =~ /^(.*).o$/; + print STDERR "$file\n"; + $we_need{$file}=" "; + next; + } + @a=split(/\s*\|\s*/); + next unless $#a == 7; + next unless $a[4] eq "GLOB"; + if ($a[6] eq "UNDEF") + { + $unres{$file}.=$a[7]." "; + print STDERR "$file needs $a[7]\n" if $debug; + } + else + { + if ($file{$a[7]} ne "") + { + print STDERR "duplicate definition of $a[7],\n$file{$a[7]} and $file \n"; + } + else + { + $file{$a[7]}=$file; + print STDERR "$file has $a[7]\n" if $debug; + } + } + } + close(IN); + } + diff --git a/node-v0.8.14/deps/openssl/openssl/util/ssleay.num b/node-v0.8.14/deps/openssl/openssl/util/ssleay.num new file mode 100755 index 0000000..15a58e7 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/util/ssleay.num @@ -0,0 +1,261 @@ +ERR_load_SSL_strings 1 EXIST::FUNCTION: +SSL_CIPHER_description 2 EXIST::FUNCTION: +SSL_CTX_add_client_CA 3 EXIST::FUNCTION: +SSL_CTX_add_session 4 EXIST::FUNCTION: +SSL_CTX_check_private_key 5 EXIST::FUNCTION: +SSL_CTX_ctrl 6 EXIST::FUNCTION: +SSL_CTX_flush_sessions 7 EXIST::FUNCTION: +SSL_CTX_free 8 EXIST::FUNCTION: +SSL_CTX_get_client_CA_list 9 EXIST::FUNCTION: +SSL_CTX_get_verify_callback 10 EXIST::FUNCTION: +SSL_CTX_get_verify_mode 11 EXIST::FUNCTION: +SSL_CTX_new 12 EXIST::FUNCTION: +SSL_CTX_remove_session 13 EXIST::FUNCTION: +SSL_CTX_set_cipher_list 15 EXIST::FUNCTION: +SSL_CTX_set_client_CA_list 16 EXIST::FUNCTION: +SSL_CTX_set_default_passwd_cb 17 EXIST::FUNCTION: +SSL_CTX_set_ssl_version 19 EXIST::FUNCTION: +SSL_CTX_set_verify 21 EXIST::FUNCTION: +SSL_CTX_use_PrivateKey 22 EXIST::FUNCTION: +SSL_CTX_use_PrivateKey_ASN1 23 EXIST::FUNCTION: +SSL_CTX_use_PrivateKey_file 24 EXIST::FUNCTION:STDIO +SSL_CTX_use_RSAPrivateKey 25 EXIST::FUNCTION:RSA +SSL_CTX_use_RSAPrivateKey_ASN1 26 EXIST::FUNCTION:RSA +SSL_CTX_use_RSAPrivateKey_file 27 EXIST::FUNCTION:RSA,STDIO +SSL_CTX_use_certificate 28 EXIST::FUNCTION: +SSL_CTX_use_certificate_ASN1 29 EXIST::FUNCTION: +SSL_CTX_use_certificate_file 30 EXIST::FUNCTION:STDIO +SSL_SESSION_free 31 EXIST::FUNCTION: +SSL_SESSION_new 32 EXIST::FUNCTION: +SSL_SESSION_print 33 EXIST::FUNCTION:BIO +SSL_SESSION_print_fp 34 EXIST::FUNCTION:FP_API +SSL_accept 35 EXIST::FUNCTION: +SSL_add_client_CA 36 EXIST::FUNCTION: +SSL_alert_desc_string 37 EXIST::FUNCTION: +SSL_alert_desc_string_long 38 EXIST::FUNCTION: +SSL_alert_type_string 39 EXIST::FUNCTION: +SSL_alert_type_string_long 40 EXIST::FUNCTION: +SSL_check_private_key 41 EXIST::FUNCTION: +SSL_clear 42 EXIST::FUNCTION: +SSL_connect 43 EXIST::FUNCTION: +SSL_copy_session_id 44 EXIST::FUNCTION: +SSL_ctrl 45 EXIST::FUNCTION: +SSL_dup 46 EXIST::FUNCTION: +SSL_dup_CA_list 47 EXIST::FUNCTION: +SSL_free 48 EXIST::FUNCTION: +SSL_get_certificate 49 EXIST::FUNCTION: +SSL_get_cipher_list 52 EXIST::FUNCTION: +SSL_get_ciphers 55 EXIST::FUNCTION: +SSL_get_client_CA_list 56 EXIST::FUNCTION: +SSL_get_default_timeout 57 EXIST::FUNCTION: +SSL_get_error 58 EXIST::FUNCTION: +SSL_get_fd 59 EXIST::FUNCTION: +SSL_get_peer_cert_chain 60 EXIST::FUNCTION: +SSL_get_peer_certificate 61 EXIST::FUNCTION: +SSL_get_rbio 63 EXIST::FUNCTION:BIO +SSL_get_read_ahead 64 EXIST::FUNCTION: +SSL_get_shared_ciphers 65 EXIST::FUNCTION: +SSL_get_ssl_method 66 EXIST::FUNCTION: +SSL_get_verify_callback 69 EXIST::FUNCTION: +SSL_get_verify_mode 70 EXIST::FUNCTION: +SSL_get_version 71 EXIST::FUNCTION: +SSL_get_wbio 72 EXIST::FUNCTION:BIO +SSL_load_client_CA_file 73 EXIST::FUNCTION:STDIO +SSL_load_error_strings 74 EXIST::FUNCTION: +SSL_new 75 EXIST::FUNCTION: +SSL_peek 76 EXIST::FUNCTION: +SSL_pending 77 EXIST::FUNCTION: +SSL_read 78 EXIST::FUNCTION: +SSL_renegotiate 79 EXIST::FUNCTION: +SSL_rstate_string 80 EXIST::FUNCTION: +SSL_rstate_string_long 81 EXIST::FUNCTION: +SSL_set_accept_state 82 EXIST::FUNCTION: +SSL_set_bio 83 EXIST::FUNCTION:BIO +SSL_set_cipher_list 84 EXIST::FUNCTION: +SSL_set_client_CA_list 85 EXIST::FUNCTION: +SSL_set_connect_state 86 EXIST::FUNCTION: +SSL_set_fd 87 EXIST::FUNCTION:SOCK +SSL_set_read_ahead 88 EXIST::FUNCTION: +SSL_set_rfd 89 EXIST::FUNCTION:SOCK +SSL_set_session 90 EXIST::FUNCTION: +SSL_set_ssl_method 91 EXIST::FUNCTION: +SSL_set_verify 94 EXIST::FUNCTION: +SSL_set_wfd 95 EXIST::FUNCTION:SOCK +SSL_shutdown 96 EXIST::FUNCTION: +SSL_state_string 97 EXIST::FUNCTION: +SSL_state_string_long 98 EXIST::FUNCTION: +SSL_use_PrivateKey 99 EXIST::FUNCTION: +SSL_use_PrivateKey_ASN1 100 EXIST::FUNCTION: +SSL_use_PrivateKey_file 101 EXIST::FUNCTION:STDIO +SSL_use_RSAPrivateKey 102 EXIST::FUNCTION:RSA +SSL_use_RSAPrivateKey_ASN1 103 EXIST::FUNCTION:RSA +SSL_use_RSAPrivateKey_file 104 EXIST::FUNCTION:RSA,STDIO +SSL_use_certificate 105 EXIST::FUNCTION: +SSL_use_certificate_ASN1 106 EXIST::FUNCTION: +SSL_use_certificate_file 107 EXIST::FUNCTION:STDIO +SSL_write 108 EXIST::FUNCTION: +SSLeay_add_ssl_algorithms 109 NOEXIST::FUNCTION: +SSLv23_client_method 110 EXIST::FUNCTION:RSA +SSLv23_method 111 EXIST::FUNCTION:RSA +SSLv23_server_method 112 EXIST::FUNCTION:RSA +SSLv2_client_method 113 EXIST::FUNCTION:RSA,SSL2 +SSLv2_method 114 EXIST::FUNCTION:RSA,SSL2 +SSLv2_server_method 115 EXIST::FUNCTION:RSA,SSL2 +SSLv3_client_method 116 EXIST::FUNCTION: +SSLv3_method 117 EXIST::FUNCTION: +SSLv3_server_method 118 EXIST::FUNCTION: +d2i_SSL_SESSION 119 EXIST::FUNCTION: +i2d_SSL_SESSION 120 EXIST::FUNCTION: +BIO_f_ssl 121 EXIST::FUNCTION:BIO +BIO_new_ssl 122 EXIST::FUNCTION:BIO +BIO_proxy_ssl_copy_session_id 123 NOEXIST::FUNCTION: +BIO_ssl_copy_session_id 124 EXIST::FUNCTION:BIO +SSL_do_handshake 125 EXIST::FUNCTION: +SSL_get_privatekey 126 EXIST::FUNCTION: +SSL_get_current_cipher 127 EXIST::FUNCTION: +SSL_CIPHER_get_bits 128 EXIST::FUNCTION: +SSL_CIPHER_get_version 129 EXIST::FUNCTION: +SSL_CIPHER_get_name 130 EXIST::FUNCTION: +BIO_ssl_shutdown 131 EXIST::FUNCTION:BIO +SSL_SESSION_cmp 132 NOEXIST::FUNCTION: +SSL_SESSION_hash 133 NOEXIST::FUNCTION: +SSL_SESSION_get_time 134 EXIST::FUNCTION: +SSL_SESSION_set_time 135 EXIST::FUNCTION: +SSL_SESSION_get_timeout 136 EXIST::FUNCTION: +SSL_SESSION_set_timeout 137 EXIST::FUNCTION: +SSL_CTX_get_ex_data 138 EXIST::FUNCTION: +SSL_CTX_get_quiet_shutdown 140 EXIST::FUNCTION: +SSL_CTX_load_verify_locations 141 EXIST::FUNCTION: +SSL_CTX_set_default_verify_paths 142 EXIST:!VMS:FUNCTION: +SSL_CTX_set_def_verify_paths 142 EXIST:VMS:FUNCTION: +SSL_CTX_set_ex_data 143 EXIST::FUNCTION: +SSL_CTX_set_quiet_shutdown 145 EXIST::FUNCTION: +SSL_SESSION_get_ex_data 146 EXIST::FUNCTION: +SSL_SESSION_set_ex_data 148 EXIST::FUNCTION: +SSL_get_SSL_CTX 150 EXIST::FUNCTION: +SSL_get_ex_data 151 EXIST::FUNCTION: +SSL_get_quiet_shutdown 153 EXIST::FUNCTION: +SSL_get_session 154 EXIST::FUNCTION: +SSL_get_shutdown 155 EXIST::FUNCTION: +SSL_get_verify_result 157 EXIST::FUNCTION: +SSL_set_ex_data 158 EXIST::FUNCTION: +SSL_set_info_callback 160 EXIST::FUNCTION: +SSL_set_quiet_shutdown 161 EXIST::FUNCTION: +SSL_set_shutdown 162 EXIST::FUNCTION: +SSL_set_verify_result 163 EXIST::FUNCTION: +SSL_version 164 EXIST::FUNCTION: +SSL_get_info_callback 165 EXIST::FUNCTION: +SSL_state 166 EXIST::FUNCTION: +SSL_CTX_get_ex_new_index 167 EXIST::FUNCTION: +SSL_SESSION_get_ex_new_index 168 EXIST::FUNCTION: +SSL_get_ex_new_index 169 EXIST::FUNCTION: +TLSv1_method 170 EXIST::FUNCTION: +TLSv1_server_method 171 EXIST::FUNCTION: +TLSv1_client_method 172 EXIST::FUNCTION: +BIO_new_buffer_ssl_connect 173 EXIST::FUNCTION:BIO +BIO_new_ssl_connect 174 EXIST::FUNCTION:BIO +SSL_get_ex_data_X509_STORE_CTX_idx 175 EXIST:!VMS:FUNCTION: +SSL_get_ex_d_X509_STORE_CTX_idx 175 EXIST:VMS:FUNCTION: +SSL_CTX_set_tmp_dh_callback 176 EXIST::FUNCTION:DH +SSL_CTX_set_tmp_rsa_callback 177 EXIST::FUNCTION:RSA +SSL_CTX_set_timeout 178 EXIST::FUNCTION: +SSL_CTX_get_timeout 179 EXIST::FUNCTION: +SSL_CTX_get_cert_store 180 EXIST::FUNCTION: +SSL_CTX_set_cert_store 181 EXIST::FUNCTION: +SSL_want 182 EXIST::FUNCTION: +SSL_library_init 183 EXIST::FUNCTION: +SSL_COMP_add_compression_method 184 EXIST::FUNCTION:COMP +SSL_add_file_cert_subjects_to_stack 185 EXIST:!VMS:FUNCTION:STDIO +SSL_add_file_cert_subjs_to_stk 185 EXIST:VMS:FUNCTION:STDIO +SSL_set_tmp_rsa_callback 186 EXIST::FUNCTION:RSA +SSL_set_tmp_dh_callback 187 EXIST::FUNCTION:DH +SSL_add_dir_cert_subjects_to_stack 188 EXIST:!VMS:FUNCTION:STDIO +SSL_add_dir_cert_subjs_to_stk 188 EXIST:VMS:FUNCTION:STDIO +SSL_set_session_id_context 189 EXIST::FUNCTION: +SSL_CTX_use_certificate_chain_file 222 EXIST:!VMS:FUNCTION:STDIO +SSL_CTX_use_cert_chain_file 222 EXIST:VMS:FUNCTION:STDIO +SSL_CTX_set_verify_depth 225 EXIST::FUNCTION: +SSL_set_verify_depth 226 EXIST::FUNCTION: +SSL_CTX_get_verify_depth 228 EXIST::FUNCTION: +SSL_get_verify_depth 229 EXIST::FUNCTION: +SSL_CTX_set_session_id_context 231 EXIST::FUNCTION: +SSL_CTX_set_cert_verify_callback 232 EXIST:!VMS:FUNCTION: +SSL_CTX_set_cert_verify_cb 232 EXIST:VMS:FUNCTION: +SSL_CTX_set_default_passwd_cb_userdata 235 EXIST:!VMS:FUNCTION: +SSL_CTX_set_def_passwd_cb_ud 235 EXIST:VMS:FUNCTION: +SSL_set_purpose 236 EXIST::FUNCTION: +SSL_CTX_set_trust 237 EXIST::FUNCTION: +SSL_CTX_set_purpose 238 EXIST::FUNCTION: +SSL_set_trust 239 EXIST::FUNCTION: +SSL_get_finished 240 EXIST::FUNCTION: +SSL_get_peer_finished 241 EXIST::FUNCTION: +SSL_get1_session 242 EXIST::FUNCTION: +SSL_CTX_callback_ctrl 243 EXIST::FUNCTION: +SSL_callback_ctrl 244 EXIST::FUNCTION: +SSL_CTX_sessions 245 EXIST::FUNCTION: +SSL_get_rfd 246 EXIST::FUNCTION: +SSL_get_wfd 247 EXIST::FUNCTION: +kssl_cget_tkt 248 EXIST::FUNCTION:KRB5 +SSL_has_matching_session_id 249 EXIST::FUNCTION: +kssl_err_set 250 EXIST::FUNCTION:KRB5 +kssl_ctx_show 251 EXIST::FUNCTION:KRB5 +kssl_validate_times 252 EXIST::FUNCTION:KRB5 +kssl_check_authent 253 EXIST::FUNCTION:KRB5 +kssl_ctx_new 254 EXIST::FUNCTION:KRB5 +kssl_build_principal_2 255 EXIST::FUNCTION:KRB5 +kssl_skip_confound 256 EXIST::FUNCTION:KRB5 +kssl_sget_tkt 257 EXIST::FUNCTION:KRB5 +SSL_set_generate_session_id 258 EXIST::FUNCTION: +kssl_ctx_setkey 259 EXIST::FUNCTION:KRB5 +kssl_ctx_setprinc 260 EXIST::FUNCTION:KRB5 +kssl_ctx_free 261 EXIST::FUNCTION:KRB5 +kssl_krb5_free_data_contents 262 EXIST::FUNCTION:KRB5 +kssl_ctx_setstring 263 EXIST::FUNCTION:KRB5 +SSL_CTX_set_generate_session_id 264 EXIST::FUNCTION: +SSL_renegotiate_pending 265 EXIST::FUNCTION: +SSL_CTX_set_msg_callback 266 EXIST::FUNCTION: +SSL_set_msg_callback 267 EXIST::FUNCTION: +DTLSv1_client_method 268 EXIST::FUNCTION: +SSL_CTX_set_tmp_ecdh_callback 269 EXIST::FUNCTION:ECDH +SSL_set_tmp_ecdh_callback 270 EXIST::FUNCTION:ECDH +SSL_COMP_get_name 271 EXIST::FUNCTION:COMP +SSL_get_current_compression 272 EXIST::FUNCTION:COMP +DTLSv1_method 273 EXIST::FUNCTION: +SSL_get_current_expansion 274 EXIST::FUNCTION:COMP +DTLSv1_server_method 275 EXIST::FUNCTION: +SSL_COMP_get_compression_methods 276 EXIST:!VMS:FUNCTION:COMP +SSL_COMP_get_compress_methods 276 EXIST:VMS:FUNCTION:COMP +SSL_SESSION_get_id 277 EXIST::FUNCTION: +SSL_CTX_sess_set_new_cb 278 EXIST::FUNCTION: +SSL_CTX_sess_get_get_cb 279 EXIST::FUNCTION: +SSL_CTX_sess_set_get_cb 280 EXIST::FUNCTION: +SSL_CTX_set_cookie_verify_cb 281 EXIST::FUNCTION: +SSL_CTX_get_info_callback 282 EXIST::FUNCTION: +SSL_CTX_set_cookie_generate_cb 283 EXIST::FUNCTION: +SSL_CTX_set_client_cert_cb 284 EXIST::FUNCTION: +SSL_CTX_sess_set_remove_cb 285 EXIST::FUNCTION: +SSL_CTX_set_info_callback 286 EXIST::FUNCTION: +SSL_CTX_sess_get_new_cb 287 EXIST::FUNCTION: +SSL_CTX_get_client_cert_cb 288 EXIST::FUNCTION: +SSL_CTX_sess_get_remove_cb 289 EXIST::FUNCTION: +SSL_set_SSL_CTX 290 EXIST::FUNCTION: +SSL_get_servername 291 EXIST::FUNCTION:TLSEXT +SSL_get_servername_type 292 EXIST::FUNCTION:TLSEXT +SSL_CTX_set_client_cert_engine 293 EXIST::FUNCTION:ENGINE +SSL_CTX_use_psk_identity_hint 294 EXIST::FUNCTION:PSK +SSL_CTX_set_psk_client_callback 295 EXIST::FUNCTION:PSK +PEM_write_bio_SSL_SESSION 296 EXIST::FUNCTION: +SSL_get_psk_identity_hint 297 EXIST::FUNCTION:PSK +SSL_set_psk_server_callback 298 EXIST::FUNCTION:PSK +SSL_use_psk_identity_hint 299 EXIST::FUNCTION:PSK +SSL_set_psk_client_callback 300 EXIST::FUNCTION:PSK +PEM_read_SSL_SESSION 301 EXIST:!WIN16:FUNCTION: +PEM_read_bio_SSL_SESSION 302 EXIST::FUNCTION: +SSL_CTX_set_psk_server_callback 303 EXIST::FUNCTION:PSK +SSL_get_psk_identity 304 EXIST::FUNCTION:PSK +PEM_write_SSL_SESSION 305 EXIST:!WIN16:FUNCTION: +SSL_set_session_ticket_ext 306 EXIST::FUNCTION: +SSL_set_session_secret_cb 307 EXIST::FUNCTION: +SSL_set_session_ticket_ext_cb 308 EXIST::FUNCTION: +SSL_set1_param 309 EXIST::FUNCTION: +SSL_CTX_set1_param 310 EXIST::FUNCTION: diff --git a/node-v0.8.14/deps/openssl/openssl/util/tab_num.pl b/node-v0.8.14/deps/openssl/openssl/util/tab_num.pl new file mode 100755 index 0000000..a81ed0e --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/util/tab_num.pl @@ -0,0 +1,17 @@ +#!/usr/local/bin/perl + +$num=1; +$width=40; + +while (<>) + { + chop; + + $i=length($_); + + $n=$width-$i; + $i=int(($n+7)/8); + print $_.("\t" x $i).$num."\n"; + $num++; + } + diff --git a/node-v0.8.14/deps/openssl/openssl/util/x86asm.sh b/node-v0.8.14/deps/openssl/openssl/util/x86asm.sh new file mode 100755 index 0000000..d2090a9 --- /dev/null +++ b/node-v0.8.14/deps/openssl/openssl/util/x86asm.sh @@ -0,0 +1,42 @@ +#!/bin/sh + +echo Generating x86 assember +echo Bignum +(cd crypto/bn/asm; perl x86.pl cpp > bn86unix.cpp) +(cd crypto/bn/asm; perl x86.pl win32 > bn-win32.asm) + +echo DES +(cd crypto/des/asm; perl des-586.pl cpp > dx86unix.cpp) +(cd crypto/des/asm; perl des-586.pl win32 > d-win32.asm) + +echo "crypt(3)" +(cd crypto/des/asm; perl crypt586.pl cpp > yx86unix.cpp) +(cd crypto/des/asm; perl crypt586.pl win32 > y-win32.asm) + +echo Blowfish +(cd crypto/bf/asm; perl bf-586.pl cpp > bx86unix.cpp) +(cd crypto/bf/asm; perl bf-586.pl win32 > b-win32.asm) + +echo CAST5 +(cd crypto/cast/asm; perl cast-586.pl cpp > cx86unix.cpp) +(cd crypto/cast/asm; perl cast-586.pl win32 > c-win32.asm) + +echo RC4 +(cd crypto/rc4/asm; perl rc4-586.pl cpp > rx86unix.cpp) +(cd crypto/rc4/asm; perl rc4-586.pl win32 > r4-win32.asm) + +echo MD5 +(cd crypto/md5/asm; perl md5-586.pl cpp > mx86unix.cpp) +(cd crypto/md5/asm; perl md5-586.pl win32 > m5-win32.asm) + +echo SHA1 +(cd crypto/sha/asm; perl sha1-586.pl cpp > sx86unix.cpp) +(cd crypto/sha/asm; perl sha1-586.pl win32 > s1-win32.asm) + +echo RIPEMD160 +(cd crypto/ripemd/asm; perl rmd-586.pl cpp > rm86unix.cpp) +(cd crypto/ripemd/asm; perl rmd-586.pl win32 > rm-win32.asm) + +echo RC5/32 +(cd crypto/rc5/asm; perl rc5-586.pl cpp > r586unix.cpp) +(cd crypto/rc5/asm; perl rc5-586.pl win32 > r5-win32.asm) diff --git a/node-v0.8.14/deps/openssl/patches/handshake_cutthrough.patch b/node-v0.8.14/deps/openssl/patches/handshake_cutthrough.patch new file mode 100644 index 0000000..4f29839 --- /dev/null +++ b/node-v0.8.14/deps/openssl/patches/handshake_cutthrough.patch @@ -0,0 +1,275 @@ +diff -uarp openssl-1.0.0.orig/apps/s_client.c openssl-1.0.0/apps/s_client.c +--- openssl-1.0.0.orig/apps/s_client.c 2009-12-16 15:28:28.000000000 -0500 ++++ openssl-1.0.0/apps/s_client.c 2010-04-21 14:39:49.000000000 -0400 +@@ -248,6 +248,7 @@ static void sc_usage(void) + BIO_printf(bio_err," -tlsextdebug - hex dump of all TLS extensions received\n"); + BIO_printf(bio_err," -status - request certificate status from server\n"); + BIO_printf(bio_err," -no_ticket - disable use of RFC4507bis session tickets\n"); ++ BIO_printf(bio_err," -cutthrough - enable 1-RTT full-handshake for strong ciphers\n"); + #endif + } + +@@ -304,6 +305,7 @@ int MAIN(int argc, char **argv) + EVP_PKEY *key = NULL; + char *CApath=NULL,*CAfile=NULL,*cipher=NULL; + int reconnect=0,badop=0,verify=SSL_VERIFY_NONE,bugs=0; ++ int cutthrough=0; + int crlf=0; + int write_tty,read_tty,write_ssl,read_ssl,tty_on,ssl_pending; + SSL_CTX *ctx=NULL; +@@ -533,6 +535,8 @@ int MAIN(int argc, char **argv) + else if (strcmp(*argv,"-no_ticket") == 0) + { off|=SSL_OP_NO_TICKET; } + #endif ++ else if (strcmp(*argv,"-cutthrough") == 0) ++ cutthrough=1; + else if (strcmp(*argv,"-serverpref") == 0) + off|=SSL_OP_CIPHER_SERVER_PREFERENCE; + else if (strcmp(*argv,"-cipher") == 0) +@@ -714,6 +718,15 @@ bad: + */ + if (sock_type == SOCK_DGRAM) SSL_CTX_set_read_ahead(ctx, 1); + ++ /* Enable handshake cutthrough for client connections using ++ * strong ciphers. */ ++ if (cutthrough) ++ { ++ int ssl_mode = SSL_CTX_get_mode(ctx); ++ ssl_mode |= SSL_MODE_HANDSHAKE_CUTTHROUGH; ++ SSL_CTX_set_mode(ctx, ssl_mode); ++ } ++ + if (state) SSL_CTX_set_info_callback(ctx,apps_ssl_info_callback); + if (cipher != NULL) + if(!SSL_CTX_set_cipher_list(ctx,cipher)) { +diff -uarp openssl-1.0.0.orig/ssl/s3_clnt.c openssl-1.0.0/ssl/s3_clnt.c +--- openssl-1.0.0.orig/ssl/s3_clnt.c 2010-02-27 19:24:24.000000000 -0500 ++++ openssl-1.0.0/ssl/s3_clnt.c 2010-04-21 14:39:49.000000000 -0400 +@@ -186,6 +186,18 @@ int ssl3_connect(SSL *s) + + s->in_handshake++; + if (!SSL_in_init(s) || SSL_in_before(s)) SSL_clear(s); ++#if 0 /* Send app data in separate packet, otherwise, some particular site ++ * (only one site so far) closes the socket. ++ * Note: there is a very small chance that two TCP packets ++ * could be arriving at server combined into a single TCP packet, ++ * then trigger that site to break. We haven't encounter that though. ++ */ ++ if (SSL_get_mode(s) & SSL_MODE_HANDSHAKE_CUTTHROUGH) ++ { ++ /* Send app data along with CCS/Finished */ ++ s->s3->flags |= SSL3_FLAGS_DELAY_CLIENT_FINISHED; ++ } ++#endif + + for (;;) + { +@@ -454,14 +468,31 @@ int ssl3_connect(SSL *s) + } + else + { +-#ifndef OPENSSL_NO_TLSEXT +- /* Allow NewSessionTicket if ticket expected */ +- if (s->tlsext_ticket_expected) +- s->s3->tmp.next_state=SSL3_ST_CR_SESSION_TICKET_A; ++ if ((SSL_get_mode(s) & SSL_MODE_HANDSHAKE_CUTTHROUGH) && SSL_get_cipher_bits(s, NULL) >= 128 ++ && s->s3->previous_server_finished_len == 0 /* no cutthrough on renegotiation (would complicate the state machine) */ ++ ) ++ { ++ if (s->s3->flags & SSL3_FLAGS_DELAY_CLIENT_FINISHED) ++ { ++ s->state=SSL3_ST_CUTTHROUGH_COMPLETE; ++ s->s3->flags|=SSL3_FLAGS_POP_BUFFER; ++ s->s3->delay_buf_pop_ret=0; ++ } ++ else ++ { ++ s->s3->tmp.next_state=SSL3_ST_CUTTHROUGH_COMPLETE; ++ } ++ } + else ++ { ++#ifndef OPENSSL_NO_TLSEXT ++ /* Allow NewSessionTicket if ticket expected */ ++ if (s->tlsext_ticket_expected) ++ s->s3->tmp.next_state=SSL3_ST_CR_SESSION_TICKET_A; ++ else + #endif +- +- s->s3->tmp.next_state=SSL3_ST_CR_FINISHED_A; ++ s->s3->tmp.next_state=SSL3_ST_CR_FINISHED_A; ++ } + } + s->init_num=0; + break; +@@ -512,6 +541,24 @@ int ssl3_connect(SSL *s) + s->state=s->s3->tmp.next_state; + break; + ++ case SSL3_ST_CUTTHROUGH_COMPLETE: ++#ifndef OPENSSL_NO_TLSEXT ++ /* Allow NewSessionTicket if ticket expected */ ++ if (s->tlsext_ticket_expected) ++ s->state=SSL3_ST_CR_SESSION_TICKET_A; ++ else ++#endif ++ s->state=SSL3_ST_CR_FINISHED_A; ++ ++ /* SSL_write() will take care of flushing buffered data if ++ * DELAY_CLIENT_FINISHED is set. ++ */ ++ if (!(s->s3->flags & SSL3_FLAGS_DELAY_CLIENT_FINISHED)) ++ ssl_free_wbio_buffer(s); ++ ret = 1; ++ goto end; ++ /* break; */ ++ + case SSL_ST_OK: + /* clean a few things up */ + ssl3_cleanup_key_block(s); +diff -uarp openssl-1.0.0.orig/ssl/s3_lib.c openssl-1.0.0/ssl/s3_lib.c +-- openssl-1.0.0.orig/ssl/s3_lib.c 2009-10-16 11:24:19.000000000 -0400 ++++ openssl-1.0.0/ssl/s3_lib.c 2010-04-21 14:39:49.000000000 -0400 +@@ -2551,9 +2551,22 @@ int ssl3_write(SSL *s, const void *buf, + + static int ssl3_read_internal(SSL *s, void *buf, int len, int peek) + { +- int ret; ++ int n,ret; + + clear_sys_error(); ++ if ((s->s3->flags & SSL3_FLAGS_POP_BUFFER) && (s->wbio == s->bbio)) ++ { ++ /* Deal with an application that calls SSL_read() when handshake data ++ * is yet to be written. ++ */ ++ if (BIO_wpending(s->wbio) > 0) ++ { ++ s->rwstate=SSL_WRITING; ++ n=BIO_flush(s->wbio); ++ if (n <= 0) return(n); ++ s->rwstate=SSL_NOTHING; ++ } ++ } + if (s->s3->renegotiate) ssl3_renegotiate_check(s); + s->s3->in_read_app_data=1; + ret=s->method->ssl_read_bytes(s,SSL3_RT_APPLICATION_DATA,buf,len,peek); +diff -uarp openssl-1.0.0.orig/ssl/ssl.h openssl-1.0.0/ssl/ssl.h +--- openssl-1.0.0.orig/ssl/ssl.h 2010-01-06 12:37:38.000000000 -0500 ++++ openssl-1.0.0/ssl/ssl.h 2010-04-21 16:57:49.000000000 -0400 +@@ -605,6 +605,10 @@ typedef struct ssl_session_st + /* Use small read and write buffers: (a) lazy allocate read buffers for + * large incoming records, and (b) limit the size of outgoing records. */ + #define SSL_MODE_SMALL_BUFFERS 0x00000020L ++/* When set, clients may send application data before receipt of CCS ++ * and Finished. This mode enables full-handshakes to 'complete' in ++ * one RTT. */ ++#define SSL_MODE_HANDSHAKE_CUTTHROUGH 0x00000040L + + /* Note: SSL[_CTX]_set_{options,mode} use |= op on the previous value, + * they cannot be used to clear bits. */ +@@ -1097,10 +1101,12 @@ extern "C" { + /* Is the SSL_connection established? */ + #define SSL_get_state(a) SSL_state(a) + #define SSL_is_init_finished(a) (SSL_state(a) == SSL_ST_OK) +-#define SSL_in_init(a) (SSL_state(a)&SSL_ST_INIT) ++#define SSL_in_init(a) ((SSL_state(a)&SSL_ST_INIT) && \ ++ !SSL_cutthrough_complete(a)) + #define SSL_in_before(a) (SSL_state(a)&SSL_ST_BEFORE) + #define SSL_in_connect_init(a) (SSL_state(a)&SSL_ST_CONNECT) + #define SSL_in_accept_init(a) (SSL_state(a)&SSL_ST_ACCEPT) ++int SSL_cutthrough_complete(const SSL *s); + + /* The following 2 states are kept in ssl->rstate when reads fail, + * you should not need these */ +Only in openssl-1.0.0/ssl: ssl.h.orig +diff -uarp openssl-1.0.0.orig/ssl/ssl3.h openssl-1.0.0/ssl/ssl3.h +-- openssl-1.0.0.orig/ssl/ssl3.h 2010-01-06 12:37:38.000000000 -0500 ++++ openssl-1.0.0/ssl/ssl3.h 2010-04-21 14:39:49.000000000 -0400 +@@ -456,6 +456,7 @@ typedef struct ssl3_state_st + /*client */ + /* extra state */ + #define SSL3_ST_CW_FLUSH (0x100|SSL_ST_CONNECT) ++#define SSL3_ST_CUTTHROUGH_COMPLETE (0x101|SSL_ST_CONNECT) + /* write to server */ + #define SSL3_ST_CW_CLNT_HELLO_A (0x110|SSL_ST_CONNECT) + #define SSL3_ST_CW_CLNT_HELLO_B (0x111|SSL_ST_CONNECT) +diff -uarp openssl-1.0.0.orig/ssl/ssl_lib.c openssl-1.0.0/ssl/ssl_lib.c +--- openssl-1.0.0.orig/ssl/ssl_lib.c 2010-02-17 14:43:46.000000000 -0500 ++++ openssl-1.0.0/ssl/ssl_lib.c 2010-04-21 17:02:45.000000000 -0400 +@@ -3031,6 +3031,19 @@ void SSL_set_msg_callback(SSL *ssl, void + SSL_callback_ctrl(ssl, SSL_CTRL_SET_MSG_CALLBACK, (void (*)(void))cb); + } + ++int SSL_cutthrough_complete(const SSL *s) ++ { ++ return (!s->server && /* cutthrough only applies to clients */ ++ !s->hit && /* full-handshake */ ++ s->version >= SSL3_VERSION && ++ s->s3->in_read_app_data == 0 && /* cutthrough only applies to write() */ ++ (SSL_get_mode((SSL*)s) & SSL_MODE_HANDSHAKE_CUTTHROUGH) && /* cutthrough enabled */ ++ SSL_get_cipher_bits(s, NULL) >= 128 && /* strong cipher choosen */ ++ s->s3->previous_server_finished_len == 0 && /* not a renegotiation handshake */ ++ (s->state == SSL3_ST_CR_SESSION_TICKET_A || /* ready to write app-data*/ ++ s->state == SSL3_ST_CR_FINISHED_A)); ++ } ++ + /* Allocates new EVP_MD_CTX and sets pointer to it into given pointer + * vairable, freeing EVP_MD_CTX previously stored in that variable, if + * any. If EVP_MD pointer is passed, initializes ctx with this md +diff -uarp openssl-1.0.0.orig/ssl/ssltest.c openssl-1.0.0/ssl/ssltest.c +--- openssl-1.0.0.orig/ssl/ssltest.c 2010-01-24 11:57:38.000000000 -0500 ++++ openssl-1.0.0/ssl/ssltest.c 2010-04-21 17:06:35.000000000 -0400 +@@ -279,6 +279,7 @@ static void sv_usage(void) + fprintf(stderr," -test_cipherlist - verifies the order of the ssl cipher lists\n"); + fprintf(stderr," -c_small_records - enable client side use of small SSL record buffers\n"); + fprintf(stderr," -s_small_records - enable server side use of small SSL record buffers\n"); ++ fprintf(stderr," -cutthrough - enable 1-RTT full-handshake for strong ciphers\n"); + } + + static void print_details(SSL *c_ssl, const char *prefix) +@@ -436,6 +437,7 @@ int main(int argc, char *argv[]) + int ssl_mode = 0; + int c_small_records=0; + int s_small_records=0; ++ int cutthrough = 0; + + verbose = 0; + debug = 0; +@@ -632,6 +634,10 @@ int main(int argc, char *argv[]) + { + s_small_records = 1; + } ++ else if (strcmp(*argv, "-cutthrough") == 0) ++ { ++ cutthrough = 1; ++ } + else + { + fprintf(stderr,"unknown option %s\n",*argv); +@@ -782,6 +788,13 @@ bad: + ssl_mode |= SSL_MODE_SMALL_BUFFERS; + SSL_CTX_set_mode(s_ctx, ssl_mode); + } ++ ssl_mode = 0; ++ if (cutthrough) ++ { ++ ssl_mode = SSL_CTX_get_mode(c_ctx); ++ ssl_mode = SSL_MODE_HANDSHAKE_CUTTHROUGH; ++ SSL_CTX_set_mode(c_ctx, ssl_mode); ++ } + + #ifndef OPENSSL_NO_DH + if (!no_dhe) +diff -uarp openssl-1.0.0.orig/test/testssl openssl-1.0.0/test/testssl +--- openssl-1.0.0.orig/test/testssl 2006-03-10 18:06:27.000000000 -0500 ++++ openssl-1.0.0/test/testssl 2010-04-21 16:50:13.000000000 -0400 +@@ -79,6 +79,8 @@ $ssltest -server_auth -client_auth -s_sm + echo test sslv2/sslv3 with both client and server authentication and small client and server buffers + $ssltest -server_auth -client_auth -c_small_records -s_small_records $CA $extra || exit 1 + ++echo test sslv2/sslv3 with both client and server authentication and handshake cutthrough ++$ssltest -server_auth -client_auth -cutthrough $CA $extra || exit 1 + + echo test sslv2 via BIO pair + $ssltest -bio_pair -ssl2 $extra || exit 1 diff --git a/node-v0.8.14/deps/openssl/patches/jsse.patch b/node-v0.8.14/deps/openssl/patches/jsse.patch new file mode 100644 index 0000000..249fb5b --- /dev/null +++ b/node-v0.8.14/deps/openssl/patches/jsse.patch @@ -0,0 +1,426 @@ +--- openssl-1.0.0b.orig/ssl/ssl.h 2010-11-30 00:03:46.000000000 +0000 ++++ openssl-1.0.0b/ssl/ssl.h 2010-11-30 00:03:47.000000000 +0000 +@@ -1133,6 +1133,9 @@ struct ssl_st + /* This can also be in the session once a session is established */ + SSL_SESSION *session; + ++ /* This can be disabled to prevent the use of uncached sessions */ ++ int session_creation_enabled; ++ + /* Default generate session ID callback. */ + GEN_SESSION_CB generate_session_id; + +@@ -1546,6 +1549,7 @@ const SSL_CIPHER *SSL_get_current_cipher + int SSL_CIPHER_get_bits(const SSL_CIPHER *c,int *alg_bits); + char * SSL_CIPHER_get_version(const SSL_CIPHER *c); + const char * SSL_CIPHER_get_name(const SSL_CIPHER *c); ++const char * SSL_CIPHER_authentication_method(const SSL_CIPHER *c); + + int SSL_get_fd(const SSL *s); + int SSL_get_rfd(const SSL *s); +@@ -1554,6 +1558,7 @@ const char * SSL_get_cipher_list(const + char * SSL_get_shared_ciphers(const SSL *s, char *buf, int len); + int SSL_get_read_ahead(const SSL * s); + int SSL_pending(const SSL *s); ++const char * SSL_authentication_method(const SSL *c); + #ifndef OPENSSL_NO_SOCK + int SSL_set_fd(SSL *s, int fd); + int SSL_set_rfd(SSL *s, int fd); +@@ -1565,6 +1570,7 @@ BIO * SSL_get_rbio(const SSL *s); + BIO * SSL_get_wbio(const SSL *s); + #endif + int SSL_set_cipher_list(SSL *s, const char *str); ++int SSL_set_cipher_lists(SSL *s, STACK_OF(SSL_CIPHER) *sk); + void SSL_set_read_ahead(SSL *s, int yes); + int SSL_get_verify_mode(const SSL *s); + int SSL_get_verify_depth(const SSL *s); +@@ -1580,6 +1586,8 @@ int SSL_use_PrivateKey(SSL *ssl, EVP_PKE + int SSL_use_PrivateKey_ASN1(int pk,SSL *ssl, const unsigned char *d, long len); + int SSL_use_certificate(SSL *ssl, X509 *x); + int SSL_use_certificate_ASN1(SSL *ssl, const unsigned char *d, int len); ++int SSL_use_certificate_chain(SSL *ssl, STACK_OF(X509) *cert_chain); ++STACK_OF(X509) * SSL_get_certificate_chain(SSL *ssl, X509 *x); + + #ifndef OPENSSL_NO_STDIO + int SSL_use_RSAPrivateKey_file(SSL *ssl, const char *file, int type); +@@ -1615,6 +1623,7 @@ void SSL_copy_session_id(SSL *to,const S + SSL_SESSION *SSL_SESSION_new(void); + const unsigned char *SSL_SESSION_get_id(const SSL_SESSION *s, + unsigned int *len); ++const char * SSL_SESSION_get_version(const SSL_SESSION *s); + #ifndef OPENSSL_NO_FP_API + int SSL_SESSION_print_fp(FILE *fp,const SSL_SESSION *ses); + #endif +@@ -1624,6 +1633,7 @@ int SSL_SESSION_print(BIO *fp,const SSL_ + void SSL_SESSION_free(SSL_SESSION *ses); + int i2d_SSL_SESSION(SSL_SESSION *in,unsigned char **pp); + int SSL_set_session(SSL *to, SSL_SESSION *session); ++void SSL_set_session_creation_enabled(SSL *, int); + int SSL_CTX_add_session(SSL_CTX *s, SSL_SESSION *c); + int SSL_CTX_remove_session(SSL_CTX *,SSL_SESSION *c); + int SSL_CTX_set_generate_session_id(SSL_CTX *, GEN_SESSION_CB); +@@ -2066,6 +2076,7 @@ void ERR_load_SSL_strings(void); + #define SSL_F_SSL_UNDEFINED_VOID_FUNCTION 244 + #define SSL_F_SSL_USE_CERTIFICATE 198 + #define SSL_F_SSL_USE_CERTIFICATE_ASN1 199 ++#define SSL_F_SSL_USE_CERTIFICATE_CHAIN 2000 + #define SSL_F_SSL_USE_CERTIFICATE_FILE 200 + #define SSL_F_SSL_USE_PRIVATEKEY 201 + #define SSL_F_SSL_USE_PRIVATEKEY_ASN1 202 +@@ -2272,6 +2283,7 @@ void ERR_load_SSL_strings(void); + #define SSL_R_SCSV_RECEIVED_WHEN_RENEGOTIATING 345 + #define SSL_R_SERVERHELLO_TLSEXT 275 + #define SSL_R_SESSION_ID_CONTEXT_UNINITIALIZED 277 ++#define SSL_R_SESSION_MAY_NOT_BE_CREATED 2000 + #define SSL_R_SHORT_READ 219 + #define SSL_R_SIGNATURE_FOR_NON_SIGNING_CERTIFICATE 220 + #define SSL_R_SSL23_DOING_SESSION_ID_REUSE 221 +--- openssl-1.0.0b.orig/ssl/d1_clnt.c 2010-01-26 19:46:29.000000000 +0000 ++++ openssl-1.0.0b/ssl/d1_clnt.c 2010-11-30 00:03:47.000000000 +0000 +@@ -613,6 +613,12 @@ int dtls1_client_hello(SSL *s) + #endif + (s->session->not_resumable)) + { ++ if (!s->session_creation_enabled) ++ { ++ ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_HANDSHAKE_FAILURE); ++ SSLerr(SSL_F_DTLS1_CLIENT_HELLO,SSL_R_SESSION_MAY_NOT_BE_CREATED); ++ goto err; ++ } + if (!ssl_get_new_session(s,0)) + goto err; + } +--- openssl-1.0.0b.orig/ssl/s23_clnt.c 2010-02-16 14:20:40.000000000 +0000 ++++ openssl-1.0.0b/ssl/s23_clnt.c 2010-11-30 00:03:47.000000000 +0000 +@@ -687,6 +687,13 @@ static int ssl23_get_server_hello(SSL *s + + /* Since, if we are sending a ssl23 client hello, we are not + * reusing a session-id */ ++ if (!s->session_creation_enabled) ++ { ++ if (!(s->client_version == SSL2_VERSION)) ++ ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_HANDSHAKE_FAILURE); ++ SSLerr(SSL_F_SSL23_GET_SERVER_HELLO,SSL_R_SESSION_MAY_NOT_BE_CREATED); ++ goto err; ++ } + if (!ssl_get_new_session(s,0)) + goto err; + +--- openssl-1.0.0b.orig/ssl/s3_both.c 2010-11-30 00:03:46.000000000 +0000 ++++ openssl-1.0.0b/ssl/s3_both.c 2010-11-30 00:03:47.000000000 +0000 +@@ -347,8 +347,11 @@ unsigned long ssl3_output_cert_chain(SSL + unsigned long l=7; + BUF_MEM *buf; + int no_chain; ++ STACK_OF(X509) *cert_chain; + +- if ((s->mode & SSL_MODE_NO_AUTO_CHAIN) || s->ctx->extra_certs) ++ cert_chain = SSL_get_certificate_chain(s, x); ++ ++ if ((s->mode & SSL_MODE_NO_AUTO_CHAIN) || s->ctx->extra_certs || cert_chain) + no_chain = 1; + else + no_chain = 0; +@@ -400,6 +403,10 @@ unsigned long ssl3_output_cert_chain(SSL + return(0); + } + ++ for (i=0; idata[4]); + l2n3(l,p); +--- openssl-1.0.0b.orig/ssl/s3_clnt.c 2010-11-30 00:03:46.000000000 +0000 ++++ openssl-1.0.0b/ssl/s3_clnt.c 2010-11-30 00:03:47.000000000 +0000 +@@ -686,6 +686,12 @@ int ssl3_client_hello(SSL *s) + #endif + (sess->not_resumable)) + { ++ if (!s->session_creation_enabled) ++ { ++ ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_HANDSHAKE_FAILURE); ++ SSLerr(SSL_F_SSL3_CLIENT_HELLO,SSL_R_SESSION_MAY_NOT_BE_CREATED); ++ goto err; ++ } + if (!ssl_get_new_session(s,0)) + goto err; + } +@@ -894,6 +900,12 @@ int ssl3_get_server_hello(SSL *s) + s->hit=0; + if (s->session->session_id_length > 0) + { ++ if (!s->session_creation_enabled) ++ { ++ ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_HANDSHAKE_FAILURE); ++ SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_SESSION_MAY_NOT_BE_CREATED); ++ goto err; ++ } + if (!ssl_get_new_session(s,0)) + { + al=SSL_AD_INTERNAL_ERROR; +--- openssl-1.0.0b.orig/ssl/s3_srvr.c 2010-11-30 00:03:46.000000000 +0000 ++++ openssl-1.0.0b/ssl/s3_srvr.c 2010-11-30 00:03:47.000000000 +0000 +@@ -902,6 +902,12 @@ int ssl3_get_client_hello(SSL *s) + */ + if ((s->new_session && (s->options & SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION))) + { ++ if (!s->session_creation_enabled) ++ { ++ ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_HANDSHAKE_FAILURE); ++ SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_SESSION_MAY_NOT_BE_CREATED); ++ goto err; ++ } + if (!ssl_get_new_session(s,1)) + goto err; + } +@@ -916,6 +922,12 @@ int ssl3_get_client_hello(SSL *s) + goto err; + else /* i == 0 */ + { ++ if (!s->session_creation_enabled) ++ { ++ ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_HANDSHAKE_FAILURE); ++ SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_SESSION_MAY_NOT_BE_CREATED); ++ goto err; ++ } + if (!ssl_get_new_session(s,1)) + goto err; + } +--- openssl-1.0.0b.orig/ssl/ssl_ciph.c 2010-06-15 17:25:14.000000000 +0000 ++++ openssl-1.0.0b/ssl/ssl_ciph.c 2010-11-30 00:03:47.000000000 +0000 +@@ -1652,6 +1652,52 @@ int SSL_CIPHER_get_bits(const SSL_CIPHER + return(ret); + } + ++/* return string version of key exchange algorithm */ ++const char* SSL_CIPHER_authentication_method(const SSL_CIPHER* cipher) ++ { ++ switch (cipher->algorithm_mkey) ++ { ++ case SSL_kRSA: ++ return SSL_TXT_RSA; ++ case SSL_kDHr: ++ return SSL_TXT_DH "_" SSL_TXT_RSA; ++ case SSL_kDHd: ++ return SSL_TXT_DH "_" SSL_TXT_DSS; ++ case SSL_kEDH: ++ switch (cipher->algorithm_auth) ++ { ++ case SSL_aDSS: ++ return "DHE_" SSL_TXT_DSS; ++ case SSL_aRSA: ++ return "DHE_" SSL_TXT_RSA; ++ case SSL_aNULL: ++ return SSL_TXT_DH "_anon"; ++ default: ++ return "UNKNOWN"; ++ } ++ case SSL_kKRB5: ++ return SSL_TXT_KRB5; ++ case SSL_kECDHr: ++ return SSL_TXT_ECDH "_" SSL_TXT_RSA; ++ case SSL_kECDHe: ++ return SSL_TXT_ECDH "_" SSL_TXT_ECDSA; ++ case SSL_kEECDH: ++ switch (cipher->algorithm_auth) ++ { ++ case SSL_aECDSA: ++ return "ECDHE_" SSL_TXT_ECDSA; ++ case SSL_aRSA: ++ return "ECDHE_" SSL_TXT_RSA; ++ case SSL_aNULL: ++ return SSL_TXT_ECDH "_anon"; ++ default: ++ return "UNKNOWN"; ++ } ++ default: ++ return "UNKNOWN"; ++ } ++ } ++ + SSL_COMP *ssl3_comp_find(STACK_OF(SSL_COMP) *sk, int n) + { + SSL_COMP *ctmp; +--- openssl-1.0.0b.orig/ssl/ssl_err.c 2010-11-30 00:03:46.000000000 +0000 ++++ openssl-1.0.0b/ssl/ssl_err.c 2010-11-30 00:03:47.000000000 +0000 +@@ -465,6 +465,7 @@ static ERR_STRING_DATA SSL_str_reasons[] + {ERR_REASON(SSL_R_SCSV_RECEIVED_WHEN_RENEGOTIATING),"scsv received when renegotiating"}, + {ERR_REASON(SSL_R_SERVERHELLO_TLSEXT) ,"serverhello tlsext"}, + {ERR_REASON(SSL_R_SESSION_ID_CONTEXT_UNINITIALIZED),"session id context uninitialized"}, ++{ERR_REASON(SSL_R_SESSION_MAY_NOT_BE_CREATED),"session may not be created"}, + {ERR_REASON(SSL_R_SHORT_READ) ,"short read"}, + {ERR_REASON(SSL_R_SIGNATURE_FOR_NON_SIGNING_CERTIFICATE),"signature for non signing certificate"}, + {ERR_REASON(SSL_R_SSL23_DOING_SESSION_ID_REUSE),"ssl23 doing session id reuse"}, +--- openssl-1.0.0b.orig/ssl/ssl_lib.c 2010-11-30 00:03:46.000000000 +0000 ++++ openssl-1.0.0b/ssl/ssl_lib.c 2010-11-30 00:03:47.000000000 +0000 +@@ -326,6 +326,7 @@ SSL *SSL_new(SSL_CTX *ctx) + OPENSSL_assert(s->sid_ctx_length <= sizeof s->sid_ctx); + memcpy(&s->sid_ctx,&ctx->sid_ctx,sizeof(s->sid_ctx)); + s->verify_callback=ctx->default_verify_callback; ++ s->session_creation_enabled=1; + s->generate_session_id=ctx->generate_session_id; + + s->param = X509_VERIFY_PARAM_new(); +@@ -1311,6 +1312,32 @@ int SSL_set_cipher_list(SSL *s,const cha + return 1; + } + ++/** specify the ciphers to be used by the SSL */ ++int SSL_set_cipher_lists(SSL *s,STACK_OF(SSL_CIPHER) *sk) ++ { ++ STACK_OF(SSL_CIPHER) *tmp_cipher_list; ++ ++ if (sk == NULL) ++ return 0; ++ ++ /* Based on end of ssl_create_cipher_list */ ++ tmp_cipher_list = sk_SSL_CIPHER_dup(sk); ++ if (tmp_cipher_list == NULL) ++ { ++ return 0; ++ } ++ if (s->cipher_list != NULL) ++ sk_SSL_CIPHER_free(s->cipher_list); ++ s->cipher_list = sk; ++ if (s->cipher_list_by_id != NULL) ++ sk_SSL_CIPHER_free(s->cipher_list_by_id); ++ s->cipher_list_by_id = tmp_cipher_list; ++ (void)sk_SSL_CIPHER_set_cmp_func(s->cipher_list_by_id,ssl_cipher_ptr_id_cmp); ++ ++ sk_SSL_CIPHER_sort(s->cipher_list_by_id); ++ return 1; ++ } ++ + /* works well for SSLv2, not so good for SSLv3 */ + char *SSL_get_shared_ciphers(const SSL *s,char *buf,int len) + { +@@ -2551,18 +2578,45 @@ SSL_METHOD *ssl_bad_method(int ver) + return(NULL); + } + +-const char *SSL_get_version(const SSL *s) ++static const char *ssl_get_version(int version) + { +- if (s->version == TLS1_VERSION) ++ if (version == TLS1_VERSION) + return("TLSv1"); +- else if (s->version == SSL3_VERSION) ++ else if (version == SSL3_VERSION) + return("SSLv3"); +- else if (s->version == SSL2_VERSION) ++ else if (version == SSL2_VERSION) + return("SSLv2"); + else + return("unknown"); + } + ++const char *SSL_get_version(const SSL *s) ++ { ++ return ssl_get_version(s->version); ++ } ++ ++const char *SSL_SESSION_get_version(const SSL_SESSION *s) ++ { ++ return ssl_get_version(s->ssl_version); ++ } ++ ++const char* SSL_authentication_method(const SSL* ssl) ++ { ++ if (ssl->cert != NULL && ssl->cert->rsa_tmp != NULL) ++ return SSL_TXT_RSA "_" SSL_TXT_EXPORT; ++ switch (ssl->version) ++ { ++ case SSL2_VERSION: ++ return SSL_TXT_RSA; ++ case SSL3_VERSION: ++ case TLS1_VERSION: ++ case DTLS1_VERSION: ++ return SSL_CIPHER_authentication_method(ssl->s3->tmp.new_cipher); ++ default: ++ return "UNKNOWN"; ++ } ++ } ++ + SSL *SSL_dup(SSL *s) + { + STACK_OF(X509_NAME) *sk; +--- openssl-1.0.0b.orig/ssl/ssl_locl.h 2010-11-30 00:03:46.000000000 +0000 ++++ openssl-1.0.0b/ssl/ssl_locl.h 2010-11-30 00:03:47.000000000 +0000 +@@ -456,6 +456,7 @@ + typedef struct cert_pkey_st + { + X509 *x509; ++ STACK_OF(X509) *cert_chain; + EVP_PKEY *privatekey; + } CERT_PKEY; + +--- openssl-1.0.0b.orig/ssl/ssl_rsa.c 2009-09-12 23:09:26.000000000 +0000 ++++ openssl-1.0.0b/ssl/ssl_rsa.c 2010-11-30 00:03:47.000000000 +0000 +@@ -697,6 +697,42 @@ int SSL_CTX_use_PrivateKey_ASN1(int type + } + + ++int SSL_use_certificate_chain(SSL *ssl, STACK_OF(X509) *cert_chain) ++ { ++ if (ssl == NULL) ++ { ++ SSLerr(SSL_F_SSL_USE_CERTIFICATE_CHAIN,ERR_R_PASSED_NULL_PARAMETER); ++ return(0); ++ } ++ if (ssl->cert == NULL) ++ { ++ SSLerr(SSL_F_SSL_USE_CERTIFICATE_CHAIN,SSL_R_NO_CERTIFICATE_ASSIGNED); ++ return(0); ++ } ++ if (ssl->cert->key == NULL) ++ { ++ SSLerr(SSL_F_SSL_USE_CERTIFICATE_CHAIN,SSL_R_NO_CERTIFICATE_ASSIGNED); ++ return(0); ++ } ++ ssl->cert->key->cert_chain = cert_chain; ++ return(1); ++ } ++ ++STACK_OF(X509) *SSL_get_certificate_chain(SSL *ssl, X509 *x) ++ { ++ int i; ++ if (x == NULL) ++ return NULL; ++ if (ssl == NULL) ++ return NULL; ++ if (ssl->cert == NULL) ++ return NULL; ++ for (i = 0; i < SSL_PKEY_NUM; i++) ++ if (ssl->cert->pkeys[i].x509 == x) ++ return ssl->cert->pkeys[i].cert_chain; ++ return NULL; ++ } ++ + #ifndef OPENSSL_NO_STDIO + /* Read a file that contains our certificate in "PEM" format, + * possibly followed by a sequence of CA certificates that should be +--- openssl-1.0.0b.orig/ssl/ssl_sess.c 2010-02-01 16:49:42.000000000 +0000 ++++ openssl-1.0.0b/ssl/ssl_sess.c 2010-11-30 00:03:47.000000000 +0000 +@@ -261,6 +261,11 @@ static int def_generate_session_id(const + return 0; + } + ++void SSL_set_session_creation_enabled (SSL *s, int creation_enabled) ++ { ++ s->session_creation_enabled = creation_enabled; ++ } ++ + int ssl_get_new_session(SSL *s, int session) + { + /* This gets used by clients and servers. */ +@@ -269,6 +274,8 @@ int ssl_get_new_session(SSL *s, int sess + SSL_SESSION *ss=NULL; + GEN_SESSION_CB cb = def_generate_session_id; + ++ /* caller should check this if they can do better error handling */ ++ if (!s->session_creation_enabled) return(0); + if ((ss=SSL_SESSION_new()) == NULL) return(0); + + /* If the context has a default timeout, use it */ diff --git a/node-v0.8.14/deps/openssl/patches/npn.patch b/node-v0.8.14/deps/openssl/patches/npn.patch new file mode 100644 index 0000000..46b7a7d --- /dev/null +++ b/node-v0.8.14/deps/openssl/patches/npn.patch @@ -0,0 +1,1293 @@ +--- openssl-1.0.0b.orig/apps/apps.c 2010-11-11 14:42:19.000000000 +0000 ++++ openssl-1.0.0b/apps/apps.c 2010-11-29 19:56:04.902465346 +0000 +@@ -3012,3 +3012,46 @@ int raw_write_stdout(const void *buf,int + int raw_write_stdout(const void *buf,int siz) + { return write(fileno(stdout),buf,siz); } + #endif ++ ++#if !defined(OPENSSL_NO_TLSEXT) && !defined(OPENSSL_NO_NEXTPROTONEG) ++/* next_protos_parse parses a comma separated list of strings into a string ++ * in a format suitable for passing to SSL_CTX_set_next_protos_advertised. ++ * outlen: (output) set to the length of the resulting buffer on success. ++ * in: a NUL termianted string like "abc,def,ghi" ++ * ++ * returns: a malloced buffer or NULL on failure. ++ */ ++unsigned char *next_protos_parse(unsigned short *outlen, const char *in) ++ { ++ size_t len; ++ unsigned char *out; ++ size_t i, start = 0; ++ ++ len = strlen(in); ++ if (len >= 65535) ++ return NULL; ++ ++ out = OPENSSL_malloc(strlen(in) + 1); ++ if (!out) ++ return NULL; ++ ++ for (i = 0; i <= len; ++i) ++ { ++ if (i == len || in[i] == ',') ++ { ++ if (i - start > 255) ++ { ++ OPENSSL_free(out); ++ return NULL; ++ } ++ out[start] = i - start; ++ start = i + 1; ++ } ++ else ++ out[i+1] = in[i]; ++ } ++ ++ *outlen = len + 1; ++ return out; ++ } ++#endif /* !OPENSSL_NO_TLSEXT && !OPENSSL_NO_NEXTPROTONEG */ +--- openssl-1.0.0b.orig/apps/apps.h 2009-10-31 13:34:19.000000000 +0000 ++++ openssl-1.0.0b/apps/apps.h 2010-11-29 19:56:04.902465346 +0000 +@@ -358,3 +358,7 @@ int raw_write_stdout(const void *,int); + #define TM_STOP 1 + double app_tminterval (int stop,int usertime); + #endif ++ ++#ifndef OPENSSL_NO_NEXTPROTONEG ++unsigned char *next_protos_parse(unsigned short *outlen, const char *in); ++#endif +--- openssl-1.0.0b.orig/apps/s_client.c 2010-11-29 19:56:04.832465351 +0000 ++++ openssl-1.0.0b/apps/s_client.c 2010-11-29 19:56:04.902465346 +0000 +@@ -342,6 +342,9 @@ static void sc_usage(void) + BIO_printf(bio_err," -tlsextdebug - hex dump of all TLS extensions received\n"); + BIO_printf(bio_err," -status - request certificate status from server\n"); + BIO_printf(bio_err," -no_ticket - disable use of RFC4507bis session tickets\n"); ++# ifndef OPENSSL_NO_NEXTPROTONEG ++ BIO_printf(bio_err," -nextprotoneg arg - enable NPN extension, considering named protocols supported (comma-separated list)\n"); ++# endif + BIO_printf(bio_err," -cutthrough - enable 1-RTT full-handshake for strong ciphers\n"); + #endif + BIO_printf(bio_err," -legacy_renegotiation - enable use of legacy renegotiation (dangerous)\n"); +@@ -367,6 +370,40 @@ static int MS_CALLBACK ssl_servername_cb + + return SSL_TLSEXT_ERR_OK; + } ++ ++# ifndef OPENSSL_NO_NEXTPROTONEG ++/* This the context that we pass to next_proto_cb */ ++typedef struct tlsextnextprotoctx_st { ++ unsigned char *data; ++ unsigned short len; ++ int status; ++} tlsextnextprotoctx; ++ ++static tlsextnextprotoctx next_proto; ++ ++static int next_proto_cb(SSL *s, unsigned char **out, unsigned char *outlen, const unsigned char *in, unsigned int inlen, void *arg) ++ { ++ tlsextnextprotoctx *ctx = arg; ++ ++ if (!c_quiet) ++ { ++ /* We can assume that |in| is syntactically valid. */ ++ unsigned i; ++ BIO_printf(bio_c_out, "Protocols advertised by server: "); ++ for (i = 0; i < inlen; ) ++ { ++ if (i) ++ BIO_write(bio_c_out, ", ", 2); ++ BIO_write(bio_c_out, &in[i + 1], in[i]); ++ i += in[i] + 1; ++ } ++ BIO_write(bio_c_out, "\n", 1); ++ } ++ ++ ctx->status = SSL_select_next_proto(out, outlen, in, inlen, ctx->data, ctx->len); ++ return SSL_TLSEXT_ERR_OK; ++ } ++# endif /* ndef OPENSSL_NO_NEXTPROTONEG */ + #endif + + enum +@@ -431,6 +468,9 @@ int MAIN(int argc, char **argv) + char *servername = NULL; + tlsextctx tlsextcbp = + {NULL,0}; ++# ifndef OPENSSL_NO_NEXTPROTONEG ++ const char *next_proto_neg_in = NULL; ++# endif + #endif + char *sess_in = NULL; + char *sess_out = NULL; +@@ -658,6 +698,13 @@ int MAIN(int argc, char **argv) + #ifndef OPENSSL_NO_TLSEXT + else if (strcmp(*argv,"-no_ticket") == 0) + { off|=SSL_OP_NO_TICKET; } ++# ifndef OPENSSL_NO_NEXTPROTONEG ++ else if (strcmp(*argv,"-nextprotoneg") == 0) ++ { ++ if (--argc < 1) goto bad; ++ next_proto_neg_in = *(++argv); ++ } ++# endif + #endif + else if (strcmp(*argv,"-cutthrough") == 0) + cutthrough=1; +@@ -766,6 +813,21 @@ bad: + OpenSSL_add_ssl_algorithms(); + SSL_load_error_strings(); + ++#if !defined(OPENSSL_NO_TLSEXT) && !defined(OPENSSL_NO_NEXTPROTONEG) ++ next_proto.status = -1; ++ if (next_proto_neg_in) ++ { ++ next_proto.data = next_protos_parse(&next_proto.len, next_proto_neg_in); ++ if (next_proto.data == NULL) ++ { ++ BIO_printf(bio_err, "Error parsing -nextprotoneg argument\n"); ++ goto end; ++ } ++ } ++ else ++ next_proto.data = NULL; ++#endif ++ + #ifndef OPENSSL_NO_ENGINE + e = setup_engine(bio_err, engine_id, 1); + if (ssl_client_engine_id) +@@ -896,6 +958,11 @@ bad: + SSL_CTX_set_mode(ctx, ssl_mode); + } + ++#if !defined(OPENSSL_NO_TLSEXT) && !defined(OPENSSL_NO_NEXTPROTONEG) ++ if (next_proto.data) ++ SSL_CTX_set_next_proto_select_cb(ctx, next_proto_cb, &next_proto); ++#endif ++ + if (state) SSL_CTX_set_info_callback(ctx,apps_ssl_info_callback); + if (cipher != NULL) + if(!SSL_CTX_set_cipher_list(ctx,cipher)) { +@@ -1755,6 +1822,18 @@ static void print_stuff(BIO *bio, SSL *s + BIO_printf(bio,"Expansion: %s\n", + expansion ? SSL_COMP_get_name(expansion) : "NONE"); + #endif ++ ++#if !defined(OPENSSL_NO_TLSEXT) && !defined(OPENSSL_NO_NEXTPROTONEG) ++ if (next_proto.status != -1) { ++ const unsigned char *proto; ++ unsigned int proto_len; ++ SSL_get0_next_proto_negotiated(s, &proto, &proto_len); ++ BIO_printf(bio, "Next protocol: (%d) ", next_proto.status); ++ BIO_write(bio, proto, proto_len); ++ BIO_write(bio, "\n", 1); ++ } ++#endif ++ + SSL_SESSION_print(bio,SSL_get_session(s)); + BIO_printf(bio,"---\n"); + if (peer != NULL) +--- openssl-1.0.0b.orig/apps/s_server.c 2010-06-15 17:25:02.000000000 +0000 ++++ openssl-1.0.0b/apps/s_server.c 2010-11-29 19:56:04.902465346 +0000 +@@ -492,6 +492,9 @@ static void sv_usage(void) + BIO_printf(bio_err," -tlsextdebug - hex dump of all TLS extensions received\n"); + BIO_printf(bio_err," -no_ticket - disable use of RFC4507bis session tickets\n"); + BIO_printf(bio_err," -legacy_renegotiation - enable use of legacy renegotiation (dangerous)\n"); ++# ifndef OPENSSL_NO_NEXTPROTONEG ++ BIO_printf(bio_err," -nextprotoneg arg - set the advertised protocols for the NPN extension (comma-separated list)\n"); ++# endif + #endif + } + +@@ -826,6 +829,24 @@ BIO_printf(err, "cert_status: received % + ret = SSL_TLSEXT_ERR_ALERT_FATAL; + goto done; + } ++ ++# ifndef OPENSSL_NO_NEXTPROTONEG ++/* This is the context that we pass to next_proto_cb */ ++typedef struct tlsextnextprotoctx_st { ++ unsigned char *data; ++ unsigned int len; ++} tlsextnextprotoctx; ++ ++static int next_proto_cb(SSL *s, const unsigned char **data, unsigned int *len, void *arg) ++ { ++ tlsextnextprotoctx *next_proto = arg; ++ ++ *data = next_proto->data; ++ *len = next_proto->len; ++ ++ return SSL_TLSEXT_ERR_OK; ++ } ++# endif /* ndef OPENSSL_NO_NPN */ + #endif + + int MAIN(int, char **); +@@ -867,6 +888,10 @@ int MAIN(int argc, char *argv[]) + #endif + #ifndef OPENSSL_NO_TLSEXT + tlsextctx tlsextcbp = {NULL, NULL, SSL_TLSEXT_ERR_ALERT_WARNING}; ++# ifndef OPENSSL_NO_NEXTPROTONEG ++ const char *next_proto_neg_in = NULL; ++ tlsextnextprotoctx next_proto; ++# endif + #endif + #ifndef OPENSSL_NO_PSK + /* by default do not send a PSK identity hint */ +@@ -1191,7 +1216,13 @@ int MAIN(int argc, char *argv[]) + if (--argc < 1) goto bad; + s_key_file2= *(++argv); + } +- ++# ifndef OPENSSL_NO_NEXTPROTONEG ++ else if (strcmp(*argv,"-nextprotoneg") == 0) ++ { ++ if (--argc < 1) goto bad; ++ next_proto_neg_in = *(++argv); ++ } ++# endif + #endif + #if !defined(OPENSSL_NO_JPAKE) && !defined(OPENSSL_NO_PSK) + else if (strcmp(*argv,"-jpake") == 0) +@@ -1476,6 +1507,11 @@ bad: + if (vpm) + SSL_CTX_set1_param(ctx2, vpm); + } ++ ++# ifndef OPENSSL_NO_NEXTPROTONEG ++ if (next_proto.data) ++ SSL_CTX_set_next_protos_advertised_cb(ctx, next_proto_cb, &next_proto); ++# endif + #endif + + #ifndef OPENSSL_NO_DH +@@ -1617,6 +1653,21 @@ bad: + goto end; + } + } ++# ifndef OPENSSL_NO_NEXTPROTONEG ++ if (next_proto_neg_in) ++ { ++ unsigned short len; ++ next_proto.data = next_protos_parse(&len, ++ next_proto_neg_in); ++ if (next_proto.data == NULL) ++ goto end; ++ next_proto.len = len; ++ } ++ else ++ { ++ next_proto.data = NULL; ++ } ++# endif + #endif + RSA_free(rsa); + BIO_printf(bio_s_out,"\n"); +@@ -2159,6 +2210,10 @@ static int init_ssl_connection(SSL *con) + X509 *peer; + long verify_error; + MS_STATIC char buf[BUFSIZ]; ++#if !defined(OPENSSL_NO_TLSEXT) && !defined(OPENSSL_NO_NEXTPROTONEG) ++ const unsigned char *next_proto_neg; ++ unsigned next_proto_neg_len; ++#endif + + if ((i=SSL_accept(con)) <= 0) + { +@@ -2198,6 +2253,15 @@ static int init_ssl_connection(SSL *con) + BIO_printf(bio_s_out,"Shared ciphers:%s\n",buf); + str=SSL_CIPHER_get_name(SSL_get_current_cipher(con)); + BIO_printf(bio_s_out,"CIPHER is %s\n",(str != NULL)?str:"(NONE)"); ++#if !defined(OPENSSL_NO_TLSEXT) && !defined(OPENSSL_NO_NEXTPROTONEG) ++ SSL_get0_next_proto_negotiated(con, &next_proto_neg, &next_proto_neg_len); ++ if (next_proto_neg) ++ { ++ BIO_printf(bio_s_out,"NEXTPROTO is "); ++ BIO_write(bio_s_out, next_proto_neg, next_proto_neg_len); ++ BIO_printf(bio_s_out, "\n"); ++ } ++#endif + if (con->hit) BIO_printf(bio_s_out,"Reused session-id\n"); + if (SSL_ctrl(con,SSL_CTRL_GET_FLAGS,0,NULL) & + TLS1_FLAGS_TLS_PADDING_BUG) +--- openssl-1.0.0b.orig/include/openssl/ssl.h 2010-11-29 19:56:04.846517045 +0000 ++++ openssl-1.0.0b/include/openssl/ssl.h 2010-11-29 19:56:04.965928855 +0000 +@@ -857,6 +857,25 @@ struct ssl_ctx_st + /* draft-rescorla-tls-opaque-prf-input-00.txt information */ + int (*tlsext_opaque_prf_input_callback)(SSL *, void *peerinput, size_t len, void *arg); + void *tlsext_opaque_prf_input_callback_arg; ++ ++# ifndef OPENSSL_NO_NEXTPROTONEG ++ /* Next protocol negotiation information */ ++ /* (for experimental NPN extension). */ ++ ++ /* For a server, this contains a callback function by which the set of ++ * advertised protocols can be provided. */ ++ int (*next_protos_advertised_cb)(SSL *s, const unsigned char **buf, ++ unsigned int *len, void *arg); ++ void *next_protos_advertised_cb_arg; ++ /* For a client, this contains a callback function that selects the ++ * next protocol from the list provided by the server. */ ++ int (*next_proto_select_cb)(SSL *s, unsigned char **out, ++ unsigned char *outlen, ++ const unsigned char *in, ++ unsigned int inlen, ++ void *arg); ++ void *next_proto_select_cb_arg; ++# endif + #endif + + #ifndef OPENSSL_NO_PSK +@@ -928,6 +947,30 @@ int SSL_CTX_set_client_cert_engine(SSL_C + #endif + void SSL_CTX_set_cookie_generate_cb(SSL_CTX *ctx, int (*app_gen_cookie_cb)(SSL *ssl, unsigned char *cookie, unsigned int *cookie_len)); + void SSL_CTX_set_cookie_verify_cb(SSL_CTX *ctx, int (*app_verify_cookie_cb)(SSL *ssl, unsigned char *cookie, unsigned int cookie_len)); ++#ifndef OPENSSL_NO_NEXTPROTONEG ++void SSL_CTX_set_next_protos_advertised_cb(SSL_CTX *s, ++ int (*cb) (SSL *ssl, ++ const unsigned char **out, ++ unsigned int *outlen, ++ void *arg), void *arg); ++void SSL_CTX_set_next_proto_select_cb(SSL_CTX *s, ++ int (*cb) (SSL *ssl, unsigned char **out, ++ unsigned char *outlen, ++ const unsigned char *in, ++ unsigned int inlen, void *arg), ++ void *arg); ++ ++int SSL_select_next_proto(unsigned char **out, unsigned char *outlen, ++ const unsigned char *in, unsigned int inlen, ++ const unsigned char *client, unsigned int client_len); ++void SSL_get0_next_proto_negotiated(const SSL *s, const unsigned char **data, ++ unsigned *len); ++ ++#define OPENSSL_NPN_UNSUPPORTED 0 ++#define OPENSSL_NPN_NEGOTIATED 1 ++#define OPENSSL_NPN_NO_OVERLAP 2 ++ ++#endif + + #ifndef OPENSSL_NO_PSK + /* the maximum length of the buffer given to callbacks containing the +@@ -1187,6 +1230,19 @@ struct ssl_st + void *tls_session_secret_cb_arg; + + SSL_CTX * initial_ctx; /* initial ctx, used to store sessions */ ++ ++#ifndef OPENSSL_NO_NEXTPROTONEG ++ /* Next protocol negotiation. For the client, this is the protocol that ++ * we sent in NextProtocol and is set when handling ServerHello ++ * extensions. ++ * ++ * For a server, this is the client's selected_protocol from ++ * NextProtocol and is set when handling the NextProtocol message, ++ * before the Finished message. */ ++ unsigned char *next_proto_negotiated; ++ unsigned char next_proto_negotiated_len; ++#endif ++ + #define session_ctx initial_ctx + #else + #define session_ctx ctx +@@ -1919,6 +1975,7 @@ void ERR_load_SSL_strings(void); + #define SSL_F_SSL3_GET_KEY_EXCHANGE 141 + #define SSL_F_SSL3_GET_MESSAGE 142 + #define SSL_F_SSL3_GET_NEW_SESSION_TICKET 283 ++#define SSL_F_SSL3_GET_NEXT_PROTO 304 + #define SSL_F_SSL3_GET_RECORD 143 + #define SSL_F_SSL3_GET_SERVER_CERTIFICATE 144 + #define SSL_F_SSL3_GET_SERVER_DONE 145 +@@ -2117,6 +2174,8 @@ void ERR_load_SSL_strings(void); + #define SSL_R_EXCESSIVE_MESSAGE_SIZE 152 + #define SSL_R_EXTRA_DATA_IN_MESSAGE 153 + #define SSL_R_GOT_A_FIN_BEFORE_A_CCS 154 ++#define SSL_R_GOT_NEXT_PROTO_BEFORE_A_CCS 346 ++#define SSL_R_GOT_NEXT_PROTO_WITHOUT_EXTENSION 347 + #define SSL_R_HTTPS_PROXY_REQUEST 155 + #define SSL_R_HTTP_REQUEST 156 + #define SSL_R_ILLEGAL_PADDING 283 +--- openssl-1.0.0b.orig/include/openssl/ssl3.h 2010-11-29 19:56:04.832465351 +0000 ++++ openssl-1.0.0b/include/openssl/ssl3.h 2010-11-29 19:56:04.965928855 +0000 +@@ -465,6 +465,12 @@ typedef struct ssl3_state_st + void *server_opaque_prf_input; + size_t server_opaque_prf_input_len; + ++#ifndef OPENSSL_NO_NEXTPROTONEG ++ /* Set if we saw the Next Protocol Negotiation extension from ++ our peer. */ ++ int next_proto_neg_seen; ++#endif ++ + struct { + /* actually only needs to be 16+20 */ + unsigned char cert_verify_md[EVP_MAX_MD_SIZE*2]; +@@ -557,6 +563,10 @@ typedef struct ssl3_state_st + #define SSL3_ST_CW_CERT_VRFY_B (0x191|SSL_ST_CONNECT) + #define SSL3_ST_CW_CHANGE_A (0x1A0|SSL_ST_CONNECT) + #define SSL3_ST_CW_CHANGE_B (0x1A1|SSL_ST_CONNECT) ++#ifndef OPENSSL_NO_NEXTPROTONEG ++#define SSL3_ST_CW_NEXT_PROTO_A (0x200|SSL_ST_CONNECT) ++#define SSL3_ST_CW_NEXT_PROTO_B (0x201|SSL_ST_CONNECT) ++#endif + #define SSL3_ST_CW_FINISHED_A (0x1B0|SSL_ST_CONNECT) + #define SSL3_ST_CW_FINISHED_B (0x1B1|SSL_ST_CONNECT) + /* read from server */ +@@ -602,6 +612,10 @@ typedef struct ssl3_state_st + #define SSL3_ST_SR_CERT_VRFY_B (0x1A1|SSL_ST_ACCEPT) + #define SSL3_ST_SR_CHANGE_A (0x1B0|SSL_ST_ACCEPT) + #define SSL3_ST_SR_CHANGE_B (0x1B1|SSL_ST_ACCEPT) ++#ifndef OPENSSL_NO_NEXTPROTONEG ++#define SSL3_ST_SR_NEXT_PROTO_A (0x210|SSL_ST_ACCEPT) ++#define SSL3_ST_SR_NEXT_PROTO_B (0x211|SSL_ST_ACCEPT) ++#endif + #define SSL3_ST_SR_FINISHED_A (0x1C0|SSL_ST_ACCEPT) + #define SSL3_ST_SR_FINISHED_B (0x1C1|SSL_ST_ACCEPT) + /* write to client */ +@@ -626,6 +640,9 @@ typedef struct ssl3_state_st + #define SSL3_MT_CLIENT_KEY_EXCHANGE 16 + #define SSL3_MT_FINISHED 20 + #define SSL3_MT_CERTIFICATE_STATUS 22 ++#ifndef OPENSSL_NO_NEXTPROTONEG ++#define SSL3_MT_NEXT_PROTO 67 ++#endif + #define DTLS1_MT_HELLO_VERIFY_REQUEST 3 + + +--- openssl-1.0.0b.orig/include/openssl/tls1.h 2009-11-11 14:51:29.000000000 +0000 ++++ openssl-1.0.0b/include/openssl/tls1.h 2010-11-29 19:56:04.965928855 +0000 +@@ -204,6 +204,11 @@ extern "C" { + /* Temporary extension type */ + #define TLSEXT_TYPE_renegotiate 0xff01 + ++#ifndef OPENSSL_NO_NEXTPROTONEG ++/* This is not an IANA defined extension number */ ++#define TLSEXT_TYPE_next_proto_neg 13172 ++#endif ++ + /* NameType value from RFC 3546 */ + #define TLSEXT_NAMETYPE_host_name 0 + /* status request value from RFC 3546 */ +--- openssl-1.0.0b.orig/ssl/s3_both.c 2010-11-29 19:56:04.846517045 +0000 ++++ openssl-1.0.0b/ssl/s3_both.c 2010-11-29 19:56:04.965928855 +0000 +@@ -202,15 +202,40 @@ int ssl3_send_finished(SSL *s, int a, in + return(ssl3_do_write(s,SSL3_RT_HANDSHAKE)); + } + ++#ifndef OPENSSL_NO_NEXTPROTONEG ++/* ssl3_take_mac calculates the Finished MAC for the handshakes messages seen to far. */ ++static void ssl3_take_mac(SSL *s) ++ { ++ const char *sender; ++ int slen; ++ ++ if (s->state & SSL_ST_CONNECT) ++ { ++ sender=s->method->ssl3_enc->server_finished_label; ++ slen=s->method->ssl3_enc->server_finished_label_len; ++ } ++ else ++ { ++ sender=s->method->ssl3_enc->client_finished_label; ++ slen=s->method->ssl3_enc->client_finished_label_len; ++ } ++ ++ s->s3->tmp.peer_finish_md_len = s->method->ssl3_enc->final_finish_mac(s, ++ sender,slen,s->s3->tmp.peer_finish_md); ++ } ++#endif ++ + int ssl3_get_finished(SSL *s, int a, int b) + { + int al,i,ok; + long n; + unsigned char *p; + ++#ifdef OPENSSL_NO_NEXTPROTONEG + /* the mac has already been generated when we received the + * change cipher spec message and is in s->s3->tmp.peer_finish_md + */ ++#endif + + n=s->method->ssl_get_message(s, + a, +@@ -521,6 +546,15 @@ long ssl3_get_message(SSL *s, int st1, i + s->init_num += i; + n -= i; + } ++ ++#ifndef OPENSSL_NO_NEXTPROTONEG ++ /* If receiving Finished, record MAC of prior handshake messages for ++ * Finished verification. */ ++ if (*s->init_buf->data == SSL3_MT_FINISHED) ++ ssl3_take_mac(s); ++#endif ++ ++ /* Feed this message into MAC computation. */ + ssl3_finish_mac(s, (unsigned char *)s->init_buf->data, s->init_num + 4); + if (s->msg_callback) + s->msg_callback(0, s->version, SSL3_RT_HANDSHAKE, s->init_buf->data, (size_t)s->init_num + 4, s, s->msg_callback_arg); +--- openssl-1.0.0b.orig/ssl/s3_clnt.c 2010-11-29 19:56:04.846517045 +0000 ++++ openssl-1.0.0b/ssl/s3_clnt.c 2010-11-29 19:56:04.965928855 +0000 +@@ -435,7 +435,16 @@ int ssl3_connect(SSL *s) + ret=ssl3_send_change_cipher_spec(s, + SSL3_ST_CW_CHANGE_A,SSL3_ST_CW_CHANGE_B); + if (ret <= 0) goto end; ++ ++#if defined(OPENSSL_NO_TLSEXT) || defined(OPENSSL_NO_NEXTPROTONEG) + s->state=SSL3_ST_CW_FINISHED_A; ++#else ++ if (s->next_proto_negotiated) ++ s->state=SSL3_ST_CW_NEXT_PROTO_A; ++ else ++ s->state=SSL3_ST_CW_FINISHED_A; ++#endif ++ + s->init_num=0; + + s->session->cipher=s->s3->tmp.new_cipher; +@@ -463,6 +472,15 @@ int ssl3_connect(SSL *s) + + break; + ++#if !defined(OPENSSL_NO_TLSEXT) && !defined(OPENSSL_NO_NEXTPROTONEG) ++ case SSL3_ST_CW_NEXT_PROTO_A: ++ case SSL3_ST_CW_NEXT_PROTO_B: ++ ret=ssl3_send_next_proto(s); ++ if (ret <= 0) goto end; ++ s->state=SSL3_ST_CW_FINISHED_A; ++ break; ++#endif ++ + case SSL3_ST_CW_FINISHED_A: + case SSL3_ST_CW_FINISHED_B: + ret=ssl3_send_finished(s, +@@ -3060,6 +3078,32 @@ err: + */ + + #ifndef OPENSSL_NO_TLSEXT ++# ifndef OPENSSL_NO_NEXTPROTONEG ++int ssl3_send_next_proto(SSL *s) ++ { ++ unsigned int len, padding_len; ++ unsigned char *d; ++ ++ if (s->state == SSL3_ST_CW_NEXT_PROTO_A) ++ { ++ len = s->next_proto_negotiated_len; ++ padding_len = 32 - ((len + 2) % 32); ++ d = (unsigned char *)s->init_buf->data; ++ d[4] = len; ++ memcpy(d + 5, s->next_proto_negotiated, len); ++ d[5 + len] = padding_len; ++ memset(d + 6 + len, 0, padding_len); ++ *(d++)=SSL3_MT_NEXT_PROTO; ++ l2n3(2 + len + padding_len, d); ++ s->state = SSL3_ST_CW_NEXT_PROTO_B; ++ s->init_num = 4 + 2 + len + padding_len; ++ s->init_off = 0; ++ } ++ ++ return ssl3_do_write(s, SSL3_RT_HANDSHAKE); ++ } ++# endif ++ + int ssl3_check_finished(SSL *s) + { + int ok; +--- openssl-1.0.0b.orig/ssl/s3_lib.c 2010-11-29 19:56:04.832465351 +0000 ++++ openssl-1.0.0b/ssl/s3_lib.c 2010-11-29 19:56:04.965928855 +0000 +@@ -2230,6 +2230,15 @@ void ssl3_clear(SSL *s) + s->s3->num_renegotiations=0; + s->s3->in_read_app_data=0; + s->version=SSL3_VERSION; ++ ++#if !defined(OPENSSL_NO_TLSEXT) && !defined(OPENSSL_NO_NEXTPROTONEG) ++ if (s->next_proto_negotiated) ++ { ++ OPENSSL_free(s->next_proto_negotiated); ++ s->next_proto_negotiated = NULL; ++ s->next_proto_negotiated_len = 0; ++ } ++#endif + } + + long ssl3_ctrl(SSL *s, int cmd, long larg, void *parg) +--- openssl-1.0.0b.orig/ssl/s3_pkt.c 2010-11-29 19:56:04.832465351 +0000 ++++ openssl-1.0.0b/ssl/s3_pkt.c 2010-11-29 19:56:04.965928855 +0000 +@@ -1394,8 +1394,10 @@ err: + int ssl3_do_change_cipher_spec(SSL *s) + { + int i; ++#ifdef OPENSSL_NO_NEXTPROTONEG + const char *sender; + int slen; ++#endif + + if (s->state & SSL_ST_ACCEPT) + i=SSL3_CHANGE_CIPHER_SERVER_READ; +@@ -1418,6 +1420,7 @@ int ssl3_do_change_cipher_spec(SSL *s) + if (!s->method->ssl3_enc->change_cipher_state(s,i)) + return(0); + ++#ifdef OPENSSL_NO_NEXTPROTONEG + /* we have to record the message digest at + * this point so we can get it before we read + * the finished message */ +@@ -1434,6 +1437,7 @@ int ssl3_do_change_cipher_spec(SSL *s) + + s->s3->tmp.peer_finish_md_len = s->method->ssl3_enc->final_finish_mac(s, + sender,slen,s->s3->tmp.peer_finish_md); ++#endif + + return(1); + } +--- openssl-1.0.0b.orig/ssl/s3_srvr.c 2010-11-29 19:56:04.846517045 +0000 ++++ openssl-1.0.0b/ssl/s3_srvr.c 2010-11-29 19:56:04.965928855 +0000 +@@ -538,7 +538,14 @@ int ssl3_accept(SSL *s) + * the client uses its key from the certificate + * for key exchange. + */ ++#if defined(OPENSSL_NO_TLSEXT) || defined(OPENSSL_NO_NEXTPROTONEG) + s->state=SSL3_ST_SR_FINISHED_A; ++#else ++ if (s->s3->next_proto_neg_seen) ++ s->state=SSL3_ST_SR_NEXT_PROTO_A; ++ else ++ s->state=SSL3_ST_SR_FINISHED_A; ++#endif + s->init_num = 0; + } + else +@@ -581,10 +588,27 @@ int ssl3_accept(SSL *s) + ret=ssl3_get_cert_verify(s); + if (ret <= 0) goto end; + ++#if defined(OPENSSL_NO_TLSEXT) || defined(OPENSSL_NO_NEXTPROTONEG) + s->state=SSL3_ST_SR_FINISHED_A; ++#else ++ if (s->s3->next_proto_neg_seen) ++ s->state=SSL3_ST_SR_NEXT_PROTO_A; ++ else ++ s->state=SSL3_ST_SR_FINISHED_A; ++#endif + s->init_num=0; + break; + ++#if !defined(OPENSSL_NO_TLSEXT) && !defined(OPENSSL_NO_NEXTPROTONEG) ++ case SSL3_ST_SR_NEXT_PROTO_A: ++ case SSL3_ST_SR_NEXT_PROTO_B: ++ ret=ssl3_get_next_proto(s); ++ if (ret <= 0) goto end; ++ s->init_num = 0; ++ s->state=SSL3_ST_SR_FINISHED_A; ++ break; ++#endif ++ + case SSL3_ST_SR_FINISHED_A: + case SSL3_ST_SR_FINISHED_B: + ret=ssl3_get_finished(s,SSL3_ST_SR_FINISHED_A, +@@ -655,7 +679,16 @@ int ssl3_accept(SSL *s) + if (ret <= 0) goto end; + s->state=SSL3_ST_SW_FLUSH; + if (s->hit) ++ { ++#if defined(OPENSSL_NO_TLSEXT) || defined(OPENSSL_NO_NEXTPROTONEG) + s->s3->tmp.next_state=SSL3_ST_SR_FINISHED_A; ++#else ++ if (s->s3->next_proto_neg_seen) ++ s->s3->tmp.next_state=SSL3_ST_SR_NEXT_PROTO_A; ++ else ++ s->s3->tmp.next_state=SSL3_ST_SR_FINISHED_A; ++#endif ++ } + else + s->s3->tmp.next_state=SSL_ST_OK; + s->init_num=0; +@@ -3196,4 +3229,72 @@ int ssl3_send_cert_status(SSL *s) + /* SSL3_ST_SW_CERT_STATUS_B */ + return(ssl3_do_write(s,SSL3_RT_HANDSHAKE)); + } ++ ++# ifndef OPENSSL_NO_NPN ++/* ssl3_get_next_proto reads a Next Protocol Negotiation handshake message. It ++ * sets the next_proto member in s if found */ ++int ssl3_get_next_proto(SSL *s) ++ { ++ int ok; ++ unsigned proto_len, padding_len; ++ long n; ++ const unsigned char *p; ++ ++ /* Clients cannot send a NextProtocol message if we didn't see the ++ * extension in their ClientHello */ ++ if (!s->s3->next_proto_neg_seen) ++ { ++ SSLerr(SSL_F_SSL3_GET_NEXT_PROTO,SSL_R_GOT_NEXT_PROTO_WITHOUT_EXTENSION); ++ return -1; ++ } ++ ++ n=s->method->ssl_get_message(s, ++ SSL3_ST_SR_NEXT_PROTO_A, ++ SSL3_ST_SR_NEXT_PROTO_B, ++ SSL3_MT_NEXT_PROTO, ++ 514, /* See the payload format below */ ++ &ok); ++ ++ if (!ok) ++ return((int)n); ++ ++ /* s->state doesn't reflect whether ChangeCipherSpec has been received ++ * in this handshake, but s->s3->change_cipher_spec does (will be reset ++ * by ssl3_get_finished). */ ++ if (!s->s3->change_cipher_spec) ++ { ++ SSLerr(SSL_F_SSL3_GET_NEXT_PROTO,SSL_R_GOT_NEXT_PROTO_BEFORE_A_CCS); ++ return -1; ++ } ++ ++ if (n < 2) ++ return 0; /* The body must be > 1 bytes long */ ++ ++ p=(unsigned char *)s->init_msg; ++ ++ /* The payload looks like: ++ * uint8 proto_len; ++ * uint8 proto[proto_len]; ++ * uint8 padding_len; ++ * uint8 padding[padding_len]; ++ */ ++ proto_len = p[0]; ++ if (proto_len + 2 > s->init_num) ++ return 0; ++ padding_len = p[proto_len + 1]; ++ if (proto_len + padding_len + 2 != s->init_num) ++ return 0; ++ ++ s->next_proto_negotiated = OPENSSL_malloc(proto_len); ++ if (!s->next_proto_negotiated) ++ { ++ SSLerr(SSL_F_SSL3_GET_NEXT_PROTO,ERR_R_MALLOC_FAILURE); ++ return 0; ++ } ++ memcpy(s->next_proto_negotiated, p + 1, proto_len); ++ s->next_proto_negotiated_len = proto_len; ++ ++ return 1; ++ } ++# endif + #endif +--- openssl-1.0.0b.orig/ssl/ssl.h 2010-11-29 19:56:04.846517045 +0000 ++++ openssl-1.0.0b/ssl/ssl.h 2010-11-29 19:56:04.965928855 +0000 +@@ -857,6 +857,25 @@ struct ssl_ctx_st + /* draft-rescorla-tls-opaque-prf-input-00.txt information */ + int (*tlsext_opaque_prf_input_callback)(SSL *, void *peerinput, size_t len, void *arg); + void *tlsext_opaque_prf_input_callback_arg; ++ ++# ifndef OPENSSL_NO_NEXTPROTONEG ++ /* Next protocol negotiation information */ ++ /* (for experimental NPN extension). */ ++ ++ /* For a server, this contains a callback function by which the set of ++ * advertised protocols can be provided. */ ++ int (*next_protos_advertised_cb)(SSL *s, const unsigned char **buf, ++ unsigned int *len, void *arg); ++ void *next_protos_advertised_cb_arg; ++ /* For a client, this contains a callback function that selects the ++ * next protocol from the list provided by the server. */ ++ int (*next_proto_select_cb)(SSL *s, unsigned char **out, ++ unsigned char *outlen, ++ const unsigned char *in, ++ unsigned int inlen, ++ void *arg); ++ void *next_proto_select_cb_arg; ++# endif + #endif + + #ifndef OPENSSL_NO_PSK +@@ -928,6 +947,30 @@ int SSL_CTX_set_client_cert_engine(SSL_C + #endif + void SSL_CTX_set_cookie_generate_cb(SSL_CTX *ctx, int (*app_gen_cookie_cb)(SSL *ssl, unsigned char *cookie, unsigned int *cookie_len)); + void SSL_CTX_set_cookie_verify_cb(SSL_CTX *ctx, int (*app_verify_cookie_cb)(SSL *ssl, unsigned char *cookie, unsigned int cookie_len)); ++#ifndef OPENSSL_NO_NEXTPROTONEG ++void SSL_CTX_set_next_protos_advertised_cb(SSL_CTX *s, ++ int (*cb) (SSL *ssl, ++ const unsigned char **out, ++ unsigned int *outlen, ++ void *arg), void *arg); ++void SSL_CTX_set_next_proto_select_cb(SSL_CTX *s, ++ int (*cb) (SSL *ssl, unsigned char **out, ++ unsigned char *outlen, ++ const unsigned char *in, ++ unsigned int inlen, void *arg), ++ void *arg); ++ ++int SSL_select_next_proto(unsigned char **out, unsigned char *outlen, ++ const unsigned char *in, unsigned int inlen, ++ const unsigned char *client, unsigned int client_len); ++void SSL_get0_next_proto_negotiated(const SSL *s, const unsigned char **data, ++ unsigned *len); ++ ++#define OPENSSL_NPN_UNSUPPORTED 0 ++#define OPENSSL_NPN_NEGOTIATED 1 ++#define OPENSSL_NPN_NO_OVERLAP 2 ++ ++#endif + + #ifndef OPENSSL_NO_PSK + /* the maximum length of the buffer given to callbacks containing the +@@ -1187,6 +1230,19 @@ struct ssl_st + void *tls_session_secret_cb_arg; + + SSL_CTX * initial_ctx; /* initial ctx, used to store sessions */ ++ ++#ifndef OPENSSL_NO_NEXTPROTONEG ++ /* Next protocol negotiation. For the client, this is the protocol that ++ * we sent in NextProtocol and is set when handling ServerHello ++ * extensions. ++ * ++ * For a server, this is the client's selected_protocol from ++ * NextProtocol and is set when handling the NextProtocol message, ++ * before the Finished message. */ ++ unsigned char *next_proto_negotiated; ++ unsigned char next_proto_negotiated_len; ++#endif ++ + #define session_ctx initial_ctx + #else + #define session_ctx ctx +@@ -1919,6 +1975,7 @@ void ERR_load_SSL_strings(void); + #define SSL_F_SSL3_GET_KEY_EXCHANGE 141 + #define SSL_F_SSL3_GET_MESSAGE 142 + #define SSL_F_SSL3_GET_NEW_SESSION_TICKET 283 ++#define SSL_F_SSL3_GET_NEXT_PROTO 304 + #define SSL_F_SSL3_GET_RECORD 143 + #define SSL_F_SSL3_GET_SERVER_CERTIFICATE 144 + #define SSL_F_SSL3_GET_SERVER_DONE 145 +@@ -2117,6 +2174,8 @@ void ERR_load_SSL_strings(void); + #define SSL_R_EXCESSIVE_MESSAGE_SIZE 152 + #define SSL_R_EXTRA_DATA_IN_MESSAGE 153 + #define SSL_R_GOT_A_FIN_BEFORE_A_CCS 154 ++#define SSL_R_GOT_NEXT_PROTO_BEFORE_A_CCS 346 ++#define SSL_R_GOT_NEXT_PROTO_WITHOUT_EXTENSION 347 + #define SSL_R_HTTPS_PROXY_REQUEST 155 + #define SSL_R_HTTP_REQUEST 156 + #define SSL_R_ILLEGAL_PADDING 283 +--- openssl-1.0.0b.orig/ssl/ssl3.h 2010-11-29 19:56:04.832465351 +0000 ++++ openssl-1.0.0b/ssl/ssl3.h 2010-11-29 19:56:04.965928855 +0000 +@@ -465,6 +465,12 @@ typedef struct ssl3_state_st + void *server_opaque_prf_input; + size_t server_opaque_prf_input_len; + ++#ifndef OPENSSL_NO_NEXTPROTONEG ++ /* Set if we saw the Next Protocol Negotiation extension from ++ our peer. */ ++ int next_proto_neg_seen; ++#endif ++ + struct { + /* actually only needs to be 16+20 */ + unsigned char cert_verify_md[EVP_MAX_MD_SIZE*2]; +@@ -557,6 +563,10 @@ typedef struct ssl3_state_st + #define SSL3_ST_CW_CERT_VRFY_B (0x191|SSL_ST_CONNECT) + #define SSL3_ST_CW_CHANGE_A (0x1A0|SSL_ST_CONNECT) + #define SSL3_ST_CW_CHANGE_B (0x1A1|SSL_ST_CONNECT) ++#ifndef OPENSSL_NO_NEXTPROTONEG ++#define SSL3_ST_CW_NEXT_PROTO_A (0x200|SSL_ST_CONNECT) ++#define SSL3_ST_CW_NEXT_PROTO_B (0x201|SSL_ST_CONNECT) ++#endif + #define SSL3_ST_CW_FINISHED_A (0x1B0|SSL_ST_CONNECT) + #define SSL3_ST_CW_FINISHED_B (0x1B1|SSL_ST_CONNECT) + /* read from server */ +@@ -602,6 +612,10 @@ typedef struct ssl3_state_st + #define SSL3_ST_SR_CERT_VRFY_B (0x1A1|SSL_ST_ACCEPT) + #define SSL3_ST_SR_CHANGE_A (0x1B0|SSL_ST_ACCEPT) + #define SSL3_ST_SR_CHANGE_B (0x1B1|SSL_ST_ACCEPT) ++#ifndef OPENSSL_NO_NEXTPROTONEG ++#define SSL3_ST_SR_NEXT_PROTO_A (0x210|SSL_ST_ACCEPT) ++#define SSL3_ST_SR_NEXT_PROTO_B (0x211|SSL_ST_ACCEPT) ++#endif + #define SSL3_ST_SR_FINISHED_A (0x1C0|SSL_ST_ACCEPT) + #define SSL3_ST_SR_FINISHED_B (0x1C1|SSL_ST_ACCEPT) + /* write to client */ +@@ -626,6 +640,9 @@ typedef struct ssl3_state_st + #define SSL3_MT_CLIENT_KEY_EXCHANGE 16 + #define SSL3_MT_FINISHED 20 + #define SSL3_MT_CERTIFICATE_STATUS 22 ++#ifndef OPENSSL_NO_NEXTPROTONEG ++#define SSL3_MT_NEXT_PROTO 67 ++#endif + #define DTLS1_MT_HELLO_VERIFY_REQUEST 3 + + +--- openssl-1.0.0b.orig/ssl/ssl_err.c 2010-11-29 19:56:04.846517045 +0000 ++++ openssl-1.0.0b/ssl/ssl_err.c 2010-11-29 19:56:04.965928855 +0000 +@@ -155,6 +155,7 @@ static ERR_STRING_DATA SSL_str_functs[]= + {ERR_FUNC(SSL_F_SSL3_GET_KEY_EXCHANGE), "SSL3_GET_KEY_EXCHANGE"}, + {ERR_FUNC(SSL_F_SSL3_GET_MESSAGE), "SSL3_GET_MESSAGE"}, + {ERR_FUNC(SSL_F_SSL3_GET_NEW_SESSION_TICKET), "SSL3_GET_NEW_SESSION_TICKET"}, ++{ERR_FUNC(SSL_F_SSL3_GET_NEXT_PROTO), "SSL3_GET_NEXT_PROTO"}, + {ERR_FUNC(SSL_F_SSL3_GET_RECORD), "SSL3_GET_RECORD"}, + {ERR_FUNC(SSL_F_SSL3_GET_SERVER_CERTIFICATE), "SSL3_GET_SERVER_CERTIFICATE"}, + {ERR_FUNC(SSL_F_SSL3_GET_SERVER_DONE), "SSL3_GET_SERVER_DONE"}, +@@ -355,6 +356,8 @@ static ERR_STRING_DATA SSL_str_reasons[] + {ERR_REASON(SSL_R_EXCESSIVE_MESSAGE_SIZE),"excessive message size"}, + {ERR_REASON(SSL_R_EXTRA_DATA_IN_MESSAGE) ,"extra data in message"}, + {ERR_REASON(SSL_R_GOT_A_FIN_BEFORE_A_CCS),"got a fin before a ccs"}, ++{ERR_REASON(SSL_R_GOT_NEXT_PROTO_BEFORE_A_CCS),"got next proto before a ccs"}, ++{ERR_REASON(SSL_R_GOT_NEXT_PROTO_WITHOUT_EXTENSION),"got next proto without seeing extension"}, + {ERR_REASON(SSL_R_HTTPS_PROXY_REQUEST) ,"https proxy request"}, + {ERR_REASON(SSL_R_HTTP_REQUEST) ,"http request"}, + {ERR_REASON(SSL_R_ILLEGAL_PADDING) ,"illegal padding"}, +--- openssl-1.0.0b.orig/ssl/ssl_lib.c 2010-11-29 19:56:04.846517045 +0000 ++++ openssl-1.0.0b/ssl/ssl_lib.c 2010-11-29 19:56:04.965928855 +0000 +@@ -354,6 +354,9 @@ SSL *SSL_new(SSL_CTX *ctx) + s->tlsext_ocsp_resplen = -1; + CRYPTO_add(&ctx->references,1,CRYPTO_LOCK_SSL_CTX); + s->initial_ctx=ctx; ++# ifndef OPENSSL_NO_NEXTPROTONEG ++ s->next_proto_negotiated = NULL; ++# endif + #endif + + s->verify_result=X509_V_OK; +@@ -587,6 +590,11 @@ void SSL_free(SSL *s) + kssl_ctx_free(s->kssl_ctx); + #endif /* OPENSSL_NO_KRB5 */ + ++#if !defined(OPENSSL_NO_TLSEXT) && !defined(OPENSSL_NO_NEXTPROTONEG) ++ if (s->next_proto_negotiated) ++ OPENSSL_free(s->next_proto_negotiated); ++#endif ++ + OPENSSL_free(s); + } + +@@ -1503,6 +1511,124 @@ int SSL_get_servername_type(const SSL *s + return TLSEXT_NAMETYPE_host_name; + return -1; + } ++ ++# ifndef OPENSSL_NO_NEXTPROTONEG ++/* SSL_select_next_proto implements the standard protocol selection. It is ++ * expected that this function is called from the callback set by ++ * SSL_CTX_set_next_proto_select_cb. ++ * ++ * The protocol data is assumed to be a vector of 8-bit, length prefixed byte ++ * strings. The length byte itself is not included in the length. A byte ++ * string of length 0 is invalid. No byte string may be truncated. ++ * ++ * The current, but experimental algorithm for selecting the protocol is: ++ * ++ * 1) If the server doesn't support NPN then this is indicated to the ++ * callback. In this case, the client application has to abort the connection ++ * or have a default application level protocol. ++ * ++ * 2) If the server supports NPN, but advertises an empty list then the ++ * client selects the first protcol in its list, but indicates via the ++ * API that this fallback case was enacted. ++ * ++ * 3) Otherwise, the client finds the first protocol in the server's list ++ * that it supports and selects this protocol. This is because it's ++ * assumed that the server has better information about which protocol ++ * a client should use. ++ * ++ * 4) If the client doesn't support any of the server's advertised ++ * protocols, then this is treated the same as case 2. ++ * ++ * It returns either ++ * OPENSSL_NPN_NEGOTIATED if a common protocol was found, or ++ * OPENSSL_NPN_NO_OVERLAP if the fallback case was reached. ++ */ ++int SSL_select_next_proto(unsigned char **out, unsigned char *outlen, const unsigned char *server, unsigned int server_len, const unsigned char *client, unsigned int client_len) ++ { ++ unsigned int i, j; ++ const unsigned char *result; ++ int status = OPENSSL_NPN_UNSUPPORTED; ++ ++ /* For each protocol in server preference order, see if we support it. */ ++ for (i = 0; i < server_len; ) ++ { ++ for (j = 0; j < client_len; ) ++ { ++ if (server[i] == client[j] && ++ memcmp(&server[i+1], &client[j+1], server[i]) == 0) ++ { ++ /* We found a match */ ++ result = &server[i]; ++ status = OPENSSL_NPN_NEGOTIATED; ++ goto found; ++ } ++ j += client[j]; ++ j++; ++ } ++ i += server[i]; ++ i++; ++ } ++ ++ /* There's no overlap between our protocols and the server's list. */ ++ result = client; ++ status = OPENSSL_NPN_NO_OVERLAP; ++ ++ found: ++ *out = (unsigned char *) result + 1; ++ *outlen = result[0]; ++ return status; ++ } ++ ++/* SSL_get0_next_proto_negotiated sets *data and *len to point to the client's ++ * requested protocol for this connection and returns 0. If the client didn't ++ * request any protocol, then *data is set to NULL. ++ * ++ * Note that the client can request any protocol it chooses. The value returned ++ * from this function need not be a member of the list of supported protocols ++ * provided by the callback. ++ */ ++void SSL_get0_next_proto_negotiated(const SSL *s, const unsigned char **data, unsigned *len) ++ { ++ *data = s->next_proto_negotiated; ++ if (!*data) { ++ *len = 0; ++ } else { ++ *len = s->next_proto_negotiated_len; ++ } ++} ++ ++/* SSL_CTX_set_next_protos_advertised_cb sets a callback that is called when a ++ * TLS server needs a list of supported protocols for Next Protocol ++ * Negotiation. The returned list must be in wire format. The list is returned ++ * by setting |out| to point to it and |outlen| to its length. This memory will ++ * not be modified, but one should assume that the SSL* keeps a reference to ++ * it. ++ * ++ * The callback should return SSL_TLSEXT_ERR_OK if it wishes to advertise. Otherwise, no ++ * such extension will be included in the ServerHello. */ ++void SSL_CTX_set_next_protos_advertised_cb(SSL_CTX *ctx, int (*cb) (SSL *ssl, const unsigned char **out, unsigned int *outlen, void *arg), void *arg) ++ { ++ ctx->next_protos_advertised_cb = cb; ++ ctx->next_protos_advertised_cb_arg = arg; ++ } ++ ++/* SSL_CTX_set_next_proto_select_cb sets a callback that is called when a ++ * client needs to select a protocol from the server's provided list. |out| ++ * must be set to point to the selected protocol (which may be within |in|). ++ * The length of the protocol name must be written into |outlen|. The server's ++ * advertised protocols are provided in |in| and |inlen|. The callback can ++ * assume that |in| is syntactically valid. ++ * ++ * The client must select a protocol. It is fatal to the connection if this ++ * callback returns a value other than SSL_TLSEXT_ERR_OK. ++ */ ++void SSL_CTX_set_next_proto_select_cb(SSL_CTX *ctx, int (*cb) (SSL *s, unsigned char **out, unsigned char *outlen, const unsigned char *in, unsigned int inlen, void *arg), void *arg) ++ { ++ ctx->next_proto_select_cb = cb; ++ ctx->next_proto_select_cb_arg = arg; ++ } ++ ++# endif + #endif + + static unsigned long ssl_session_hash(const SSL_SESSION *a) +@@ -1667,6 +1793,10 @@ SSL_CTX *SSL_CTX_new(const SSL_METHOD *m + ret->tlsext_status_cb = 0; + ret->tlsext_status_arg = NULL; + ++# ifndef OPENSSL_NO_NEXTPROTONEG ++ ret->next_protos_advertised_cb = 0; ++ ret->next_proto_select_cb = 0; ++# endif + #endif + #ifndef OPENSSL_NO_PSK + ret->psk_identity_hint=NULL; +--- openssl-1.0.0b.orig/ssl/ssl_locl.h 2010-11-29 19:56:04.846517045 +0000 ++++ openssl-1.0.0b/ssl/ssl_locl.h 2010-11-29 19:56:04.965928855 +0000 +@@ -968,6 +968,9 @@ int ssl3_get_server_certificate(SSL *s); + int ssl3_check_cert_and_algorithm(SSL *s); + #ifndef OPENSSL_NO_TLSEXT + int ssl3_check_finished(SSL *s); ++# ifndef OPENSSL_NO_NEXTPROTONEG ++int ssl3_send_next_proto(SSL *s); ++# endif + #endif + + int dtls1_client_hello(SSL *s); +@@ -986,6 +989,9 @@ int ssl3_check_client_hello(SSL *s); + int ssl3_get_client_certificate(SSL *s); + int ssl3_get_client_key_exchange(SSL *s); + int ssl3_get_cert_verify(SSL *s); ++#ifndef OPENSSL_NO_NEXTPROTONEG ++int ssl3_get_next_proto(SSL *s); ++#endif + + int dtls1_send_hello_request(SSL *s); + int dtls1_send_server_hello(SSL *s); +--- openssl-1.0.0b.orig/ssl/t1_lib.c 2010-11-16 13:26:24.000000000 +0000 ++++ openssl-1.0.0b/ssl/t1_lib.c 2010-11-29 19:56:04.965928855 +0000 +@@ -494,6 +494,18 @@ unsigned char *ssl_add_clienthello_tlsex + i2d_X509_EXTENSIONS(s->tlsext_ocsp_exts, &ret); + } + ++#ifndef OPENSSL_NO_NEXTPROTONEG ++ if (s->ctx->next_proto_select_cb && !s->s3->tmp.finish_md_len) ++ { ++ /* The client advertises an emtpy extension to indicate its ++ * support for Next Protocol Negotiation */ ++ if (limit - ret - 4 < 0) ++ return NULL; ++ s2n(TLSEXT_TYPE_next_proto_neg,ret); ++ s2n(0,ret); ++ } ++#endif ++ + if ((extdatalen = ret-p-2)== 0) + return p; + +@@ -505,6 +517,9 @@ unsigned char *ssl_add_serverhello_tlsex + { + int extdatalen=0; + unsigned char *ret = p; ++#ifndef OPENSSL_NO_NEXTPROTONEG ++ int next_proto_neg_seen; ++#endif + + /* don't add extensions for SSLv3, unless doing secure renegotiation */ + if (s->version == SSL3_VERSION && !s->s3->send_connection_binding) +@@ -618,6 +633,28 @@ unsigned char *ssl_add_serverhello_tlsex + + } + ++#ifndef OPENSSL_NO_NEXTPROTONEG ++ next_proto_neg_seen = s->s3->next_proto_neg_seen; ++ s->s3->next_proto_neg_seen = 0; ++ if (next_proto_neg_seen && s->ctx->next_protos_advertised_cb) ++ { ++ const unsigned char *npa; ++ unsigned int npalen; ++ int r; ++ ++ r = s->ctx->next_protos_advertised_cb(s, &npa, &npalen, s->ctx->next_protos_advertised_cb_arg); ++ if (r == SSL_TLSEXT_ERR_OK) ++ { ++ if ((long)(limit - ret - 4 - npalen) < 0) return NULL; ++ s2n(TLSEXT_TYPE_next_proto_neg,ret); ++ s2n(npalen,ret); ++ memcpy(ret, npa, npalen); ++ ret += npalen; ++ s->s3->next_proto_neg_seen = 1; ++ } ++ } ++#endif ++ + if ((extdatalen = ret-p-2)== 0) + return p; + +@@ -982,6 +1019,28 @@ int ssl_parse_clienthello_tlsext(SSL *s, + else + s->tlsext_status_type = -1; + } ++#ifndef OPENSSL_NO_NEXTPROTONEG ++ else if (type == TLSEXT_TYPE_next_proto_neg && ++ s->s3->tmp.finish_md_len == 0) ++ { ++ /* We shouldn't accept this extension on a ++ * renegotiation. ++ * ++ * s->new_session will be set on renegotiation, but we ++ * probably shouldn't rely that it couldn't be set on ++ * the initial renegotation too in certain cases (when ++ * there's some other reason to disallow resuming an ++ * earlier session -- the current code won't be doing ++ * anything like that, but this might change). ++ ++ * A valid sign that there's been a previous handshake ++ * in this connection is if s->s3->tmp.finish_md_len > ++ * 0. (We are talking about a check that will happen ++ * in the Hello protocol round, well before a new ++ * Finished message could have been computed.) */ ++ s->s3->next_proto_neg_seen = 1; ++ } ++#endif + + /* session ticket processed earlier */ + data+=size; +@@ -1005,6 +1064,26 @@ int ssl_parse_clienthello_tlsext(SSL *s, + return 1; + } + ++#ifndef OPENSSL_NO_NEXTPROTONEG ++/* ssl_next_proto_validate validates a Next Protocol Negotiation block. No ++ * elements of zero length are allowed and the set of elements must exactly fill ++ * the length of the block. */ ++static int ssl_next_proto_validate(unsigned char *d, unsigned len) ++ { ++ unsigned int off = 0; ++ ++ while (off < len) ++ { ++ if (d[off] == 0) ++ return 0; ++ off += d[off]; ++ off++; ++ } ++ ++ return off == len; ++ } ++#endif ++ + int ssl_parse_serverhello_tlsext(SSL *s, unsigned char **p, unsigned char *d, int n, int *al) + { + unsigned short length; +@@ -1139,6 +1218,39 @@ int ssl_parse_serverhello_tlsext(SSL *s, + /* Set flag to expect CertificateStatus message */ + s->tlsext_status_expected = 1; + } ++#ifndef OPENSSL_NO_NEXTPROTONEG ++ else if (type == TLSEXT_TYPE_next_proto_neg) ++ { ++ unsigned char *selected; ++ unsigned char selected_len; ++ ++ /* We must have requested it. */ ++ if ((s->ctx->next_proto_select_cb == NULL)) ++ { ++ *al = TLS1_AD_UNSUPPORTED_EXTENSION; ++ return 0; ++ } ++ /* The data must be valid */ ++ if (!ssl_next_proto_validate(data, size)) ++ { ++ *al = TLS1_AD_DECODE_ERROR; ++ return 0; ++ } ++ if (s->ctx->next_proto_select_cb(s, &selected, &selected_len, data, size, s->ctx->next_proto_select_cb_arg) != SSL_TLSEXT_ERR_OK) ++ { ++ *al = TLS1_AD_INTERNAL_ERROR; ++ return 0; ++ } ++ s->next_proto_negotiated = OPENSSL_malloc(selected_len); ++ if (!s->next_proto_negotiated) ++ { ++ *al = TLS1_AD_INTERNAL_ERROR; ++ return 0; ++ } ++ memcpy(s->next_proto_negotiated, selected, selected_len); ++ s->next_proto_negotiated_len = selected_len; ++ } ++#endif + else if (type == TLSEXT_TYPE_renegotiate) + { + if(!ssl_parse_serverhello_renegotiate_ext(s, data, size, al)) +--- openssl-1.0.0b.orig/ssl/tls1.h 2009-11-11 14:51:29.000000000 +0000 ++++ openssl-1.0.0b/ssl/tls1.h 2010-11-29 19:56:04.965928855 +0000 +@@ -204,6 +204,11 @@ extern "C" { + /* Temporary extension type */ + #define TLSEXT_TYPE_renegotiate 0xff01 + ++#ifndef OPENSSL_NO_NEXTPROTONEG ++/* This is not an IANA defined extension number */ ++#define TLSEXT_TYPE_next_proto_neg 13172 ++#endif ++ + /* NameType value from RFC 3546 */ + #define TLSEXT_NAMETYPE_host_name 0 + /* status request value from RFC 3546 */ diff --git a/node-v0.8.14/deps/openssl/patches/openssl_no_dtls1.patch b/node-v0.8.14/deps/openssl/patches/openssl_no_dtls1.patch new file mode 100644 index 0000000..8b61cd3 --- /dev/null +++ b/node-v0.8.14/deps/openssl/patches/openssl_no_dtls1.patch @@ -0,0 +1,13 @@ +--- openssl-1.0.0f.orig/ssl/ssl_lib.c 2012-01-04 22:13:21.000000000 +0000 ++++ openssl-1.0.0f/ssl/ssl_lib.c 2012-01-04 22:13:21.000000000 +0000 +@@ -1063,8 +1063,10 @@ long SSL_ctrl(SSL *s,int cmd,long larg,v + s->max_cert_list=larg; + return(l); + case SSL_CTRL_SET_MTU: ++#ifndef OPENSSL_NO_DTLS1 + if (larg < (long)dtls1_min_mtu()) + return 0; ++#endif + + if (SSL_version(s) == DTLS1_VERSION || + SSL_version(s) == DTLS1_BAD_VER) diff --git a/node-v0.8.14/deps/openssl/patches/progs.patch b/node-v0.8.14/deps/openssl/patches/progs.patch new file mode 100644 index 0000000..16fd9b0 --- /dev/null +++ b/node-v0.8.14/deps/openssl/patches/progs.patch @@ -0,0 +1,54 @@ +--- openssl-1.0.0.orig/apps/openssl.c 2009-10-04 09:43:21.000000000 -0700 ++++ openssl-1.0.0/apps/openssl.c 2010-05-18 14:05:14.000000000 -0700 +@@ -275,8 +275,10 @@ int main(int Argc, char *Argv[]) + if (ERR_GET_REASON(ERR_peek_last_error()) + == CONF_R_NO_SUCH_FILE) + { ++#if 0 /* ANDROID */ + BIO_printf(bio_err, + "WARNING: can't open config file: %s\n",p); ++#endif + ERR_clear_error(); + NCONF_free(config); + config = NULL; +--- openssl-1.0.0.orig/apps/progs.h 2009-06-30 08:08:38.000000000 -0700 ++++ openssl-1.0.0/apps/progs.h 2010-05-18 14:05:38.000000000 -0700 +@@ -146,7 +152,9 @@ FUNCTION functions[] = { + {FUNC_TYPE_GENERAL,"ocsp",ocsp_main}, + #endif + {FUNC_TYPE_GENERAL,"prime",prime_main}, ++#if 0 /* ANDROID */ + {FUNC_TYPE_GENERAL,"ts",ts_main}, ++#endif + #ifndef OPENSSL_NO_MD2 + {FUNC_TYPE_MD,"md2",dgst_main}, + #endif +--- openssl-1.0.0.orig/apps/speed.c 2010-03-03 11:56:17.000000000 -0800 ++++ openssl-1.0.0/apps/speed.c 2010-05-18 14:05:57.000000000 -0700 +@@ -1718,6 +1718,7 @@ int MAIN(int argc, char **argv) + } + } + ++#if 0 /* ANDROID */ + if (doit[D_IGE_128_AES]) + { + for (j=0; jlength > s->s3->rbuf.len - DTLS1_RT_HEADER_LENGTH) ++ { ++ unsigned char *pp; ++ unsigned int newlen = rr->length + DTLS1_RT_HEADER_LENGTH; ++ if ((pp=OPENSSL_realloc(s->s3->rbuf.buf, newlen))==NULL) ++ { ++ SSLerr(SSL_F_DTLS1_GET_RECORD,ERR_R_MALLOC_FAILURE); ++ return(-1); ++ } ++ p = pp + (p - s->s3->rbuf.buf); ++ s->s3->rbuf.buf=pp; ++ s->s3->rbuf.len=newlen; ++ s->packet= &(s->s3->rbuf.buf[0]); ++ } ++ + /* now s->rstate == SSL_ST_READ_BODY */ + } + +@@ -1342,6 +1360,7 @@ int do_dtls1_write(SSL *s, int type, con + SSL3_BUFFER *wb; + SSL_SESSION *sess; + int bs; ++ unsigned int len_with_overhead = len + SSL3_RT_DEFAULT_WRITE_OVERHEAD; + + /* first check if there is a SSL3_BUFFER still being written + * out. This will happen with non blocking IO */ +@@ -1351,6 +1370,16 @@ int do_dtls1_write(SSL *s, int type, con + return(ssl3_write_pending(s,type,buf,len)); + } + ++ if (s->s3->wbuf.len < len_with_overhead) ++ { ++ if ((p=OPENSSL_realloc(s->s3->wbuf.buf, len_with_overhead)) == NULL) { ++ SSLerr(SSL_F_DO_DTLS1_WRITE,ERR_R_MALLOC_FAILURE); ++ goto err; ++ } ++ s->s3->wbuf.buf = p; ++ s->s3->wbuf.len = len_with_overhead; ++ } ++ + /* If we have an alert to send, lets send it */ + if (s->s3->alert_dispatch) + { +--- openssl-1.0.0a.orig/ssl/s23_srvr.c 2010-02-16 14:20:40.000000000 +0000 ++++ openssl-1.0.0a/ssl/s23_srvr.c 2010-08-25 21:12:39.000000000 +0000 +@@ -403,8 +403,13 @@ int ssl23_get_client_hello(SSL *s) + v[0] = p[3]; /* == SSL3_VERSION_MAJOR */ + v[1] = p[4]; + ++/* The SSL2 protocol allows n to be larger, just pick ++ * a reasonable buffer size. */ ++#if SSL3_RT_DEFAULT_PACKET_SIZE < 1024*4 - SSL3_RT_DEFAULT_WRITE_OVERHEAD ++#error "SSL3_RT_DEFAULT_PACKET_SIZE is too small." ++#endif + n=((p[0]&0x7f)<<8)|p[1]; +- if (n > (1024*4)) ++ if (n > SSL3_RT_DEFAULT_PACKET_SIZE - 2) + { + SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO,SSL_R_RECORD_TOO_LARGE); + goto err; +--- openssl-1.0.0a.orig/ssl/s3_both.c 2010-03-24 23:16:49.000000000 +0000 ++++ openssl-1.0.0a/ssl/s3_both.c 2010-08-25 21:12:39.000000000 +0000 +@@ -715,13 +722,20 @@ int ssl3_setup_read_buffer(SSL *s) + + if (s->s3->rbuf.buf == NULL) + { +- len = SSL3_RT_MAX_PLAIN_LENGTH +- + SSL3_RT_MAX_ENCRYPTED_OVERHEAD +- + headerlen + align; +- if (s->options & SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER) ++ if (SSL_get_mode(s) & SSL_MODE_SMALL_BUFFERS) + { +- s->s3->init_extra = 1; +- len += SSL3_RT_MAX_EXTRA; ++ len = SSL3_RT_DEFAULT_PACKET_SIZE; ++ } ++ else ++ { ++ len = SSL3_RT_MAX_PLAIN_LENGTH ++ + SSL3_RT_MAX_ENCRYPTED_OVERHEAD ++ + headerlen + align; ++ if (s->options & SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER) ++ { ++ s->s3->init_extra = 1; ++ len += SSL3_RT_MAX_EXTRA; ++ } + } + #ifndef OPENSSL_NO_COMP + if (!(s->options & SSL_OP_NO_COMPRESSION)) +@@ -757,7 +771,15 @@ int ssl3_setup_write_buffer(SSL *s) + + if (s->s3->wbuf.buf == NULL) + { +- len = s->max_send_fragment ++ if (SSL_get_mode(s) & SSL_MODE_SMALL_BUFFERS) ++ { ++ len = SSL3_RT_DEFAULT_PACKET_SIZE; ++ } ++ else ++ { ++ len = s->max_send_fragment; ++ } ++ len += 0 + + SSL3_RT_SEND_MAX_ENCRYPTED_OVERHEAD + + headerlen + align; + #ifndef OPENSSL_NO_COMP +@@ -767,7 +789,6 @@ int ssl3_setup_write_buffer(SSL *s) + if (!(s->options & SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS)) + len += headerlen + align + + SSL3_RT_SEND_MAX_ENCRYPTED_OVERHEAD; +- + if ((p=freelist_extract(s->ctx, 0, len)) == NULL) + goto err; + s->s3->wbuf.buf = p; +@@ -810,4 +831,3 @@ int ssl3_release_read_buffer(SSL *s) + } + return 1; + } +- +--- openssl-1.0.0a.orig/ssl/s3_pkt.c 2010-03-25 11:22:42.000000000 +0000 ++++ openssl-1.0.0a/ssl/s3_pkt.c 2010-08-25 21:12:39.000000000 +0000 +@@ -293,6 +293,11 @@ static int ssl3_get_record(SSL *s) + size_t extra; + int decryption_failed_or_bad_record_mac = 0; + unsigned char *mac = NULL; ++#if defined(SSL3_ALIGN_PAYLOAD) && SSL3_ALIGN_PAYLOAD!=0 ++ long align=SSL3_ALIGN_PAYLOAD; ++#else ++ long align=0; ++#endif + + rr= &(s->s3->rrec); + sess=s->session; +@@ -301,7 +306,8 @@ static int ssl3_get_record(SSL *s) + extra=SSL3_RT_MAX_EXTRA; + else + extra=0; +- if (extra && !s->s3->init_extra) ++ if (!(SSL_get_mode(s) & SSL_MODE_SMALL_BUFFERS) && ++ extra && !s->s3->init_extra) + { + /* An application error: SLS_OP_MICROSOFT_BIG_SSLV3_BUFFER + * set after ssl3_setup_buffers() was done */ +@@ -350,6 +356,21 @@ fprintf(stderr, "Record type=%d, Length= + goto err; + } + ++ /* If we receive a valid record larger than the current buffer size, ++ * allocate some memory for it. ++ */ ++ if (rr->length > s->s3->rbuf.len - SSL3_RT_HEADER_LENGTH - align) ++ { ++ if ((p=OPENSSL_realloc(s->s3->rbuf.buf, rr->length + SSL3_RT_HEADER_LENGTH + align))==NULL) ++ { ++ SSLerr(SSL_F_SSL3_GET_RECORD,ERR_R_MALLOC_FAILURE); ++ goto err; ++ } ++ s->s3->rbuf.buf=p; ++ s->s3->rbuf.len=rr->length + SSL3_RT_HEADER_LENGTH + align; ++ s->packet= &(s->s3->rbuf.buf[0]); ++ } ++ + if (rr->length > s->s3->rbuf.len - SSL3_RT_HEADER_LENGTH) + { + al=SSL_AD_RECORD_OVERFLOW; +@@ -576,6 +597,7 @@ int ssl3_write_bytes(SSL *s, int type, c + const unsigned char *buf=buf_; + unsigned int tot,n,nw; + int i; ++ unsigned int max_plain_length; + + s->rwstate=SSL_NOTHING; + tot=s->s3->wnum; +@@ -595,8 +617,13 @@ int ssl3_write_bytes(SSL *s, int type, c + n=(len-tot); + for (;;) + { +- if (n > s->max_send_fragment) +- nw=s->max_send_fragment; ++ if (type == SSL3_RT_APPLICATION_DATA && (SSL_get_mode(s) & SSL_MODE_SMALL_BUFFERS)) ++ max_plain_length = SSL3_RT_DEFAULT_PLAIN_LENGTH; ++ else ++ max_plain_length = s->max_send_fragment; ++ ++ if (n > max_plain_length) ++ nw = max_plain_length; + else + nw=n; + +@@ -727,6 +727,18 @@ static int do_ssl3_write(SSL *s, int type, const unsigned char *buf, + s->s3->empty_fragment_done = 1; + } + ++ /* resize if necessary to hold the data. */ ++ if (len + SSL3_RT_DEFAULT_WRITE_OVERHEAD > wb->len) ++ { ++ if ((p=OPENSSL_realloc(wb->buf, len + SSL3_RT_DEFAULT_WRITE_OVERHEAD))==NULL) ++ { ++ SSLerr(SSL_F_DO_SSL3_WRITE,ERR_R_MALLOC_FAILURE); ++ goto err; ++ } ++ wb->buf = p; ++ wb->len = len + SSL3_RT_DEFAULT_WRITE_OVERHEAD; ++ } ++ + if (create_empty_fragment) + { + #if defined(SSL3_ALIGN_PAYLOAD) && SSL3_ALIGN_PAYLOAD!=0 +--- openssl-1.0.0a.orig/ssl/ssl.h 2010-01-06 17:37:38.000000000 +0000 ++++ openssl-1.0.0a/ssl/ssl.h 2010-08-25 21:12:39.000000000 +0000 +@@ -602,6 +602,9 @@ typedef struct ssl_session_st + * TLS only.) "Released" buffers are put onto a free-list in the context + * or just freed (depending on the context's setting for freelist_max_len). */ + #define SSL_MODE_RELEASE_BUFFERS 0x00000010L ++/* Use small read and write buffers: (a) lazy allocate read buffers for ++ * large incoming records, and (b) limit the size of outgoing records. */ ++#define SSL_MODE_SMALL_BUFFERS 0x00000020L + + /* Note: SSL[_CTX]_set_{options,mode} use |= op on the previous value, + * they cannot be used to clear bits. */ +--- openssl-1.0.0a.orig/ssl/ssl3.h 2010-01-06 17:37:38.000000000 +0000 ++++ openssl-1.0.0a/ssl/ssl3.h 2010-08-25 21:12:39.000000000 +0000 +@@ -280,6 +280,9 @@ extern "C" { + + #define SSL3_RT_MAX_EXTRA (16384) + ++/* Default buffer length used for writen records. Thus a generated record ++ * will contain plaintext no larger than this value. */ ++#define SSL3_RT_DEFAULT_PLAIN_LENGTH 2048 + /* Maximum plaintext length: defined by SSL/TLS standards */ + #define SSL3_RT_MAX_PLAIN_LENGTH 16384 + /* Maximum compression overhead: defined by SSL/TLS standards */ +@@ -311,6 +314,13 @@ extern "C" { + #define SSL3_RT_MAX_PACKET_SIZE \ + (SSL3_RT_MAX_ENCRYPTED_LENGTH+SSL3_RT_HEADER_LENGTH) + ++/* Extra space for empty fragment, headers, MAC, and padding. */ ++#define SSL3_RT_DEFAULT_WRITE_OVERHEAD 256 ++#define SSL3_RT_DEFAULT_PACKET_SIZE 4096 - SSL3_RT_DEFAULT_WRITE_OVERHEAD ++#if SSL3_RT_DEFAULT_PLAIN_LENGTH + SSL3_RT_DEFAULT_WRITE_OVERHEAD > SSL3_RT_DEFAULT_PACKET_SIZE ++#error "Insufficient space allocated for write buffers." ++#endif ++ + #define SSL3_MD_CLIENT_FINISHED_CONST "\x43\x4C\x4E\x54" + #define SSL3_MD_SERVER_FINISHED_CONST "\x53\x52\x56\x52" + +@@ -634,4 +645,3 @@ typedef struct ssl3_state_st + } + #endif + #endif +- +--- openssl-1.0.0a.orig/ssl/ssltest.c 2010-01-24 16:57:38.000000000 +0000 ++++ openssl-1.0.0a/ssl/ssltest.c 2010-08-25 21:12:39.000000000 +0000 +@@ -316,6 +316,8 @@ static void sv_usage(void) + " (default is sect163r2).\n"); + #endif + fprintf(stderr," -test_cipherlist - verifies the order of the ssl cipher lists\n"); ++ fprintf(stderr," -c_small_records - enable client side use of small SSL record buffers\n"); ++ fprintf(stderr," -s_small_records - enable server side use of small SSL record buffers\n"); + } + + static void print_details(SSL *c_ssl, const char *prefix) +@@ -444,6 +447,9 @@ int opaque_prf_input_cb(SSL *ssl, void * + return arg->ret; + } + #endif ++ int ssl_mode = 0; ++ int c_small_records=0; ++ int s_small_records=0; + + int main(int argc, char *argv[]) + { +@@ -680,6 +687,14 @@ int main(int argc, char *argv[]) + { + test_cipherlist = 1; + } ++ else if (strcmp(*argv, "-c_small_records") == 0) ++ { ++ c_small_records = 1; ++ } ++ else if (strcmp(*argv, "-s_small_records") == 0) ++ { ++ s_small_records = 1; ++ } + else + { + fprintf(stderr,"unknown option %s\n",*argv); +@@ -802,6 +821,21 @@ bad: + SSL_CTX_set_cipher_list(s_ctx,cipher); + } + ++ ssl_mode = 0; ++ if (c_small_records) ++ { ++ ssl_mode = SSL_CTX_get_mode(c_ctx); ++ ssl_mode |= SSL_MODE_SMALL_BUFFERS; ++ SSL_CTX_set_mode(c_ctx, ssl_mode); ++ } ++ ssl_mode = 0; ++ if (s_small_records) ++ { ++ ssl_mode = SSL_CTX_get_mode(s_ctx); ++ ssl_mode |= SSL_MODE_SMALL_BUFFERS; ++ SSL_CTX_set_mode(s_ctx, ssl_mode); ++ } ++ + #ifndef OPENSSL_NO_DH + if (!no_dhe) + { +--- openssl-1.0.0.orig/test/testssl 2006-03-10 15:06:27.000000000 -0800 ++++ openssl-1.0.0/test/testssl 2010-04-26 10:24:55.000000000 -0700 +@@ -70,6 +70,16 @@ $ssltest -client_auth $CA $extra || exit + echo test sslv2/sslv3 with both client and server authentication + $ssltest -server_auth -client_auth $CA $extra || exit 1 + ++echo test sslv2/sslv3 with both client and server authentication and small client buffers ++$ssltest -server_auth -client_auth -c_small_records $CA $extra || exit 1 ++ ++echo test sslv2/sslv3 with both client and server authentication and small server buffers ++$ssltest -server_auth -client_auth -s_small_records $CA $extra || exit 1 ++ ++echo test sslv2/sslv3 with both client and server authentication and small client and server buffers ++$ssltest -server_auth -client_auth -c_small_records -s_small_records $CA $extra || exit 1 ++ ++ + echo test sslv2 via BIO pair + $ssltest -bio_pair -ssl2 $extra || exit 1 + diff --git a/node-v0.8.14/deps/openssl/patches/tls_exporter.patch b/node-v0.8.14/deps/openssl/patches/tls_exporter.patch new file mode 100755 index 0000000..a9e64a3 --- /dev/null +++ b/node-v0.8.14/deps/openssl/patches/tls_exporter.patch @@ -0,0 +1,220 @@ +diff --git a/ssl/d1_lib.c b/ssl/d1_lib.c +index c3b77c8..a94290a 100644 +--- a/ssl/d1_lib.c ++++ b/ssl/d1_lib.c +@@ -82,6 +82,7 @@ SSL3_ENC_METHOD DTLSv1_enc_data={ + TLS_MD_CLIENT_FINISH_CONST,TLS_MD_CLIENT_FINISH_CONST_SIZE, + TLS_MD_SERVER_FINISH_CONST,TLS_MD_SERVER_FINISH_CONST_SIZE, + tls1_alert_code, ++ tls1_export_keying_material, + }; + + long dtls1_default_timeout(void) +diff --git a/ssl/s3_lib.c b/ssl/s3_lib.c +index c19538a..1fecbbc 100644 +--- a/ssl/s3_lib.c ++++ b/ssl/s3_lib.c +@@ -2087,6 +2087,9 @@ SSL3_ENC_METHOD SSLv3_enc_data={ + SSL3_MD_CLIENT_FINISHED_CONST,4, + SSL3_MD_SERVER_FINISHED_CONST,4, + ssl3_alert_code, ++ (int (*)(SSL *, unsigned char *, size_t, const char *, ++ size_t, const unsigned char *, size_t, ++ int use_context)) ssl_undefined_function, + }; + + long ssl3_default_timeout(void) +diff --git a/ssl/ssl.h b/ssl/ssl.h +index 9336af8..be4af2f 100644 +--- a/ssl/ssl.h ++++ b/ssl/ssl.h +@@ -2116,6 +2116,7 @@ void ERR_load_SSL_strings(void); + #define SSL_F_SSL_PARSE_SERVERHELLO_RENEGOTIATE_EXT 301 + #define SSL_F_SSL_PARSE_SERVERHELLO_TLSEXT 303 + #define SSL_F_SSL_PEEK 270 ++#define SSL_F_TLS1_EXPORT_KEYING_MATERIAL 312 + #define SSL_F_SSL_PREPARE_CLIENTHELLO_TLSEXT 281 + #define SSL_F_SSL_PREPARE_SERVERHELLO_TLSEXT 282 + #define SSL_F_SSL_READ 223 +@@ -2394,6 +2395,7 @@ void ERR_load_SSL_strings(void); + #define SSL_R_TLSV1_UNRECOGNIZED_NAME 1112 + #define SSL_R_TLSV1_UNSUPPORTED_EXTENSION 1110 + #define SSL_R_TLS_CLIENT_CERT_REQ_WITH_ANON_CIPHER 232 ++#define SSL_R_TLS_ILLEGAL_EXPORTER_LABEL 367 + #define SSL_R_TLS_INVALID_ECPOINTFORMAT_LIST 157 + #define SSL_R_TLS_PEER_DID_NOT_RESPOND_WITH_CERTIFICATE_LIST 233 + #define SSL_R_TLS_RSA_ENCRYPTED_VALUE_LENGTH_IS_WRONG 234 +diff --git a/ssl/ssl_lib.c b/ssl/ssl_lib.c +index 17d2cde..d6ad3c1 100644 +--- a/ssl/ssl_lib.c ++++ b/ssl/ssl_lib.c +@@ -3127,6 +3127,18 @@ void SSL_CTX_set_next_proto_select_cb(SSL_CTX *ctx, int (*cb) (SSL *s, unsigned + } + #endif + ++int SSL_export_keying_material(SSL *s, unsigned char *out, size_t olen, ++ const char *label, size_t llen, const unsigned char *p, size_t plen, ++ int use_context) ++ { ++ if (s->version < TLS1_VERSION) ++ return -1; ++ ++ return s->method->ssl3_enc->export_keying_material(s, out, olen, label, ++ llen, p, plen, ++ use_context); ++ } ++ + int SSL_cutthrough_complete(const SSL *s) + { + return (!s->server && /* cutthrough only applies to clients */ +diff --git a/ssl/ssl_locl.h b/ssl/ssl_locl.h +index 146c89c..e7c6b9a 100644 +--- a/ssl/ssl_locl.h ++++ b/ssl/ssl_locl.h +@@ -557,6 +557,10 @@ typedef struct ssl3_enc_method + const char *server_finished_label; + int server_finished_label_len; + int (*alert_value)(int); ++ int (*export_keying_material)(SSL *, unsigned char *, size_t, ++ const char *, size_t, ++ const unsigned char *, size_t, ++ int use_context); + } SSL3_ENC_METHOD; + + #ifndef OPENSSL_NO_COMP +@@ -1041,6 +1045,9 @@ int tls1_cert_verify_mac(SSL *s, int md_nid, unsigned char *p); + int tls1_mac(SSL *ssl, unsigned char *md, int snd); + int tls1_generate_master_secret(SSL *s, unsigned char *out, + unsigned char *p, int len); ++int tls1_export_keying_material(SSL *s, unsigned char *out, size_t olen, ++ const char *label, size_t llen, const unsigned char *p, ++ size_t plen, int use_context); + int tls1_alert_code(int code); + int ssl3_alert_code(int code); + int ssl_ok(SSL *s); +diff --git a/ssl/t1_enc.c b/ssl/t1_enc.c +index 793ea43..b1d5b28 100644 +--- a/ssl/t1_enc.c ++++ b/ssl/t1_enc.c +@@ -1001,6 +1001,95 @@ int tls1_generate_master_secret(SSL *s, unsigned char *out, unsigned char *p, + return(SSL3_MASTER_SECRET_SIZE); + } + ++int tls1_export_keying_material(SSL *s, unsigned char *out, size_t olen, ++ const char *label, size_t llen, const unsigned char *context, ++ size_t contextlen, int use_context) ++ { ++ unsigned char *buff; ++ unsigned char *val = NULL; ++ size_t vallen, currentvalpos; ++ int rv; ++ ++#ifdef KSSL_DEBUG ++ printf ("tls1_export_keying_material(%p,%p,%d,%s,%d,%p,%d)\n", s, out, olen, label, llen, p, plen); ++#endif /* KSSL_DEBUG */ ++ ++ buff = OPENSSL_malloc(olen); ++ if (buff == NULL) goto err2; ++ ++ /* construct PRF arguments ++ * we construct the PRF argument ourself rather than passing separate ++ * values into the TLS PRF to ensure that the concatenation of values ++ * does not create a prohibited label. ++ */ ++ vallen = llen + SSL3_RANDOM_SIZE * 2; ++ if (use_context) ++ { ++ vallen += 2 + contextlen; ++ } ++ ++ val = OPENSSL_malloc(vallen); ++ if (val == NULL) goto err2; ++ currentvalpos = 0; ++ memcpy(val + currentvalpos, (unsigned char *) label, llen); ++ currentvalpos += llen; ++ memcpy(val + currentvalpos, s->s3->client_random, SSL3_RANDOM_SIZE); ++ currentvalpos += SSL3_RANDOM_SIZE; ++ memcpy(val + currentvalpos, s->s3->server_random, SSL3_RANDOM_SIZE); ++ currentvalpos += SSL3_RANDOM_SIZE; ++ ++ if (use_context) ++ { ++ val[currentvalpos] = (contextlen >> 8) & 0xff; ++ currentvalpos++; ++ val[currentvalpos] = contextlen & 0xff; ++ currentvalpos++; ++ if ((contextlen > 0) || (context != NULL)) ++ { ++ memcpy(val + currentvalpos, context, contextlen); ++ } ++ } ++ ++ /* disallow prohibited labels ++ * note that SSL3_RANDOM_SIZE > max(prohibited label len) = ++ * 15, so size of val > max(prohibited label len) = 15 and the ++ * comparisons won't have buffer overflow ++ */ ++ if (memcmp(val, TLS_MD_CLIENT_FINISH_CONST, ++ TLS_MD_CLIENT_FINISH_CONST_SIZE) == 0) goto err1; ++ if (memcmp(val, TLS_MD_SERVER_FINISH_CONST, ++ TLS_MD_SERVER_FINISH_CONST_SIZE) == 0) goto err1; ++ if (memcmp(val, TLS_MD_MASTER_SECRET_CONST, ++ TLS_MD_MASTER_SECRET_CONST_SIZE) == 0) goto err1; ++ if (memcmp(val, TLS_MD_KEY_EXPANSION_CONST, ++ TLS_MD_KEY_EXPANSION_CONST_SIZE) == 0) goto err1; ++ ++ rv = tls1_PRF(s->s3->tmp.new_cipher->algorithm2, ++ val, vallen, ++ NULL, 0, ++ NULL, 0, ++ NULL, 0, ++ NULL, 0, ++ s->session->master_key,s->session->master_key_length, ++ out,buff,olen); ++ ++#ifdef KSSL_DEBUG ++ printf ("tls1_export_keying_material() complete\n"); ++#endif /* KSSL_DEBUG */ ++ goto ret; ++err1: ++ SSLerr(SSL_F_TLS1_EXPORT_KEYING_MATERIAL, SSL_R_TLS_ILLEGAL_EXPORTER_LABEL); ++ rv = 0; ++ goto ret; ++err2: ++ SSLerr(SSL_F_TLS1_EXPORT_KEYING_MATERIAL, ERR_R_MALLOC_FAILURE); ++ rv = 0; ++ret: ++ if (buff != NULL) OPENSSL_free(buff); ++ if (val != NULL) OPENSSL_free(val); ++ return(rv); ++ } ++ + int tls1_alert_code(int code) + { + switch (code) +diff --git a/ssl/t1_lib.c b/ssl/t1_lib.c +index daa65c9..c094471 100644 +--- a/ssl/t1_lib.c ++++ b/ssl/t1_lib.c +@@ -209,6 +209,7 @@ SSL3_ENC_METHOD TLSv1_enc_data={ + TLS_MD_CLIENT_FINISH_CONST,TLS_MD_CLIENT_FINISH_CONST_SIZE, + TLS_MD_SERVER_FINISH_CONST,TLS_MD_SERVER_FINISH_CONST_SIZE, + tls1_alert_code, ++ tls1_export_keying_material, + }; + + long tls1_default_timeout(void) +diff --git a/ssl/tls1.h b/ssl/tls1.h +index 1fa96e5..7bbb875 100644 +--- a/ssl/tls1.h ++++ b/ssl/tls1.h +@@ -231,6 +231,9 @@ extern "C" { + + const char *SSL_get_servername(const SSL *s, const int type) ; + int SSL_get_servername_type(const SSL *s) ; ++int SSL_export_keying_material(SSL *s, unsigned char *out, size_t olen, ++ const char *label, size_t llen, const unsigned char *p, size_t plen, ++ int use_context); + + #define SSL_set_tlsext_host_name(s,name) \ + SSL_ctrl(s,SSL_CTRL_SET_TLSEXT_HOSTNAME,TLSEXT_NAMETYPE_host_name,(char *)name) \ No newline at end of file diff --git a/node-v0.8.14/deps/openssl/patches/x509_hash_name_algorithm_change.patch b/node-v0.8.14/deps/openssl/patches/x509_hash_name_algorithm_change.patch new file mode 100644 index 0000000..d960184 --- /dev/null +++ b/node-v0.8.14/deps/openssl/patches/x509_hash_name_algorithm_change.patch @@ -0,0 +1,31 @@ +--- openssl-1.0.0f-origin/crypto/x509/by_dir.c 2012-01-19 02:20:24.821550944 +0800 ++++ openssl-1.0.0f/crypto/x509/by_dir.c 2012-01-19 23:36:53.597870429 +0800 +@@ -287,6 +287,8 @@ + int ok=0; + int i,j,k; + unsigned long h; ++ unsigned long hash_array[2]; ++ int hash_index; + BUF_MEM *b=NULL; + X509_OBJECT stmp,*tmp; + const char *postfix=""; +@@ -323,6 +325,11 @@ + ctx=(BY_DIR *)xl->method_data; + + h=X509_NAME_hash(name); ++ hash_array[0]=h; ++ hash_array[1]=X509_NAME_hash_old(name); ++ for (hash_index=0; hash_index < 2; hash_index++) ++ { ++ h=hash_array[hash_index]; + for (i=0; i < sk_BY_DIR_ENTRY_num(ctx->dirs); i++) + { + BY_DIR_ENTRY *ent; +@@ -476,6 +483,7 @@ + goto finish; + } + } ++ } + finish: + if (b != NULL) BUF_MEM_free(b); + return(ok); diff --git a/node-v0.8.14/deps/uv/.gitignore b/node-v0.8.14/deps/uv/.gitignore new file mode 100644 index 0000000..fa9636d --- /dev/null +++ b/node-v0.8.14/deps/uv/.gitignore @@ -0,0 +1,33 @@ +*.swp +*.o +*.lo +*.la +*.a +*.opensdf +*.orig +*.sdf +*.suo +core +vgcore.* +/out/ +/build/gyp + +/test/run-tests +/test/run-tests.exe +/test/run-tests.dSYM +/test/run-benchmarks +/test/run-benchmarks.exe +/test/run-benchmarks.dSYM + +*.sln +*.vcproj +*.vcxproj +*.vcxproj.filters +*.vcxproj.user +_UpgradeReport_Files/ +UpgradeLog*.XML +Debug +Release +ipch +*.mk +*.Makefile diff --git a/node-v0.8.14/deps/uv/.mailmap b/node-v0.8.14/deps/uv/.mailmap new file mode 100644 index 0000000..2d98623 --- /dev/null +++ b/node-v0.8.14/deps/uv/.mailmap @@ -0,0 +1,13 @@ +# update AUTHORS with: +# git log --all --reverse --format='%aN <%aE>' | perl -ne 'BEGIN{print "# Authors ordered by first contribution.\n"} print unless $h{$_}; $h{$_} = 1' > AUTHORS + + + + +San-Tai Hsu +Isaac Z. Schlueter +Saúl Ibarra Corretgé +Yuki OKUMURA +Frank Denis +Ryan Emery +Yasuhiro Matsumoto diff --git a/node-v0.8.14/deps/uv/.travis.yml b/node-v0.8.14/deps/uv/.travis.yml new file mode 100644 index 0000000..f3b176f --- /dev/null +++ b/node-v0.8.14/deps/uv/.travis.yml @@ -0,0 +1,9 @@ +language: node_js + +script: + - "make test" + +notifications: + email: false + irc: + - "irc.freenode.net#libuv" diff --git a/node-v0.8.14/deps/uv/AUTHORS b/node-v0.8.14/deps/uv/AUTHORS new file mode 100644 index 0000000..37452ac --- /dev/null +++ b/node-v0.8.14/deps/uv/AUTHORS @@ -0,0 +1,45 @@ +# Authors ordered by first contribution. +Ryan Dahl +Bert Belder +Josh Roesslein +Alan Gutierrez +Joshua Peek +Igor Zinkovsky +San-Tai Hsu +Ben Noordhuis +Henry Rawas +Robert Mustacchi +Matt Stevens +Paul Querna +Shigeki Ohtsu +Tom Hughes +Peter Bright +Jeroen Janssen +Andrea Lattuada +Augusto Henrique Hentz +Clifford Heath +Jorge Chamorro Bieling +Luis Lavena +Matthew Sporleder +Erick Tryzelaar +Isaac Z. Schlueter +Pieter Noordhuis +Marek Jelen +Fedor Indutny +Saúl Ibarra Corretgé +Felix Geisendörfer +Yuki OKUMURA +Roman Shtylman +Frank Denis +Carter Allen +Tj Holowaychuk +Shimon Doodkin +Ryan Emery +Bruce Mitchener +Maciej Małecki +Yasuhiro Matsumoto +Daisuke Murase +Paddy Byers +Dan VerWeire +Brandon Benvie +Brandon Philips diff --git a/node-v0.8.14/deps/uv/LICENSE b/node-v0.8.14/deps/uv/LICENSE new file mode 100644 index 0000000..f62d7f1 --- /dev/null +++ b/node-v0.8.14/deps/uv/LICENSE @@ -0,0 +1,42 @@ +libuv is part of the Node project: http://nodejs.org/ +libuv may be distributed alone under Node's license: + +==== + +Copyright Joyent, Inc. and other Node contributors. All rights reserved. +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to +deal in the Software without restriction, including without limitation the +rights to use, copy, modify, merge, publish, distribute, sublicense, and/or +sell copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS +IN THE SOFTWARE. + +==== + +This license applies to all parts of libuv that are not externally +maintained libraries. + +The externally maintained libraries used by libuv are: + + - tree.h (from FreeBSD), copyright Niels Provos. Two clause BSD license. + + - ngx_queue.h (from Nginx), copyright Igor Sysoev. Two clause BSD license. + + - c-ares, copyright Daniel Stenberg and others. MIT licensed. + + - libev, located at ev/ is copyright Marc Alexander Lehmann, and + dual-licensed under the MIT license and GPL2. + + - libeio, located at eio/ is copyright Marc Alexander Lehmann, and + dual-licensed under the MIT license and GPL2. diff --git a/node-v0.8.14/deps/uv/Makefile b/node-v0.8.14/deps/uv/Makefile new file mode 100644 index 0000000..cf1e788 --- /dev/null +++ b/node-v0.8.14/deps/uv/Makefile @@ -0,0 +1,119 @@ +# Copyright Joyent, Inc. and other Node contributors. All rights reserved. +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to +# deal in the Software without restriction, including without limitation the +# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or +# sell copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS +# IN THE SOFTWARE. + +uname_S := $(shell sh -c 'uname -s 2>/dev/null || echo not') + +ifdef MSVC +uname_S := MINGW +endif + +CPPFLAGS += -Iinclude -Iinclude/uv-private + +CARES_OBJS = +CARES_OBJS += src/ares/ares__close_sockets.o +CARES_OBJS += src/ares/ares__get_hostent.o +CARES_OBJS += src/ares/ares__read_line.o +CARES_OBJS += src/ares/ares__timeval.o +CARES_OBJS += src/ares/ares_cancel.o +CARES_OBJS += src/ares/ares_data.o +CARES_OBJS += src/ares/ares_destroy.o +CARES_OBJS += src/ares/ares_expand_name.o +CARES_OBJS += src/ares/ares_expand_string.o +CARES_OBJS += src/ares/ares_fds.o +CARES_OBJS += src/ares/ares_free_hostent.o +CARES_OBJS += src/ares/ares_free_string.o +CARES_OBJS += src/ares/ares_gethostbyaddr.o +CARES_OBJS += src/ares/ares_gethostbyname.o +CARES_OBJS += src/ares/ares_getnameinfo.o +CARES_OBJS += src/ares/ares_getopt.o +CARES_OBJS += src/ares/ares_getsock.o +CARES_OBJS += src/ares/ares_init.o +CARES_OBJS += src/ares/ares_library_init.o +CARES_OBJS += src/ares/ares_llist.o +CARES_OBJS += src/ares/ares_mkquery.o +CARES_OBJS += src/ares/ares_nowarn.o +CARES_OBJS += src/ares/ares_options.o +CARES_OBJS += src/ares/ares_parse_a_reply.o +CARES_OBJS += src/ares/ares_parse_aaaa_reply.o +CARES_OBJS += src/ares/ares_parse_mx_reply.o +CARES_OBJS += src/ares/ares_parse_ns_reply.o +CARES_OBJS += src/ares/ares_parse_ptr_reply.o +CARES_OBJS += src/ares/ares_parse_srv_reply.o +CARES_OBJS += src/ares/ares_parse_txt_reply.o +CARES_OBJS += src/ares/ares_process.o +CARES_OBJS += src/ares/ares_query.o +CARES_OBJS += src/ares/ares_search.o +CARES_OBJS += src/ares/ares_send.o +CARES_OBJS += src/ares/ares_strcasecmp.o +CARES_OBJS += src/ares/ares_strdup.o +CARES_OBJS += src/ares/ares_strerror.o +CARES_OBJS += src/ares/ares_timeout.o +CARES_OBJS += src/ares/ares_version.o +CARES_OBJS += src/ares/ares_writev.o +CARES_OBJS += src/ares/bitncmp.o +CARES_OBJS += src/ares/inet_net_pton.o +CARES_OBJS += src/ares/inet_ntop.o + +ifneq (,$(findstring MINGW,$(uname_S))) +include config-mingw.mk +else +include config-unix.mk +endif + +TESTS=test/blackhole-server.c test/echo-server.c test/test-*.c +BENCHMARKS=test/blackhole-server.c test/echo-server.c test/dns-server.c test/benchmark-*.c + +all: uv.a + +$(CARES_OBJS): %.o: %.c + $(CC) -o $*.o -c $(CFLAGS) $(CPPFLAGS) $< -DHAVE_CONFIG_H + +test/run-tests$(E): test/*.h test/run-tests.c $(RUNNER_SRC) test/runner-unix.c $(TESTS) uv.a + $(CC) $(CPPFLAGS) $(RUNNER_CFLAGS) -o test/run-tests test/run-tests.c \ + test/runner.c $(RUNNER_SRC) $(TESTS) uv.a $(RUNNER_LIBS) $(RUNNER_LINKFLAGS) + +test/run-benchmarks$(E): test/*.h test/run-benchmarks.c test/runner.c $(RUNNER_SRC) $(BENCHMARKS) uv.a + $(CC) $(CPPFLAGS) $(RUNNER_CFLAGS) -o test/run-benchmarks test/run-benchmarks.c \ + test/runner.c $(RUNNER_SRC) $(BENCHMARKS) uv.a $(RUNNER_LIBS) $(RUNNER_LINKFLAGS) + +test/echo.o: test/echo.c test/echo.h + $(CC) $(CPPFLAGS) $(CFLAGS) -c test/echo.c -o test/echo.o + + +.PHONY: clean clean-platform distclean distclean-platform test bench + + +test: test/run-tests$(E) + test/run-tests + +#test-%: test/run-tests$(E) +# test/run-tests $(@:test-%=%) + +bench: test/run-benchmarks$(E) + test/run-benchmarks + +#bench-%: test/run-benchmarks$(E) +# test/run-benchmarks $(@:bench-%=%) + +clean: clean-platform + $(RM) -f src/*.o *.a test/run-tests$(E) test/run-benchmarks$(E) + +distclean: distclean-platform + $(RM) -f src/*.o *.a test/run-tests$(E) test/run-benchmarks$(E) diff --git a/node-v0.8.14/deps/uv/README.md b/node-v0.8.14/deps/uv/README.md new file mode 100644 index 0000000..f86a000 --- /dev/null +++ b/node-v0.8.14/deps/uv/README.md @@ -0,0 +1,88 @@ +# libuv [![Build Status](https://secure.travis-ci.org/joyent/libuv.png)](http://travis-ci.org/joyent/libuv) + +libuv is a new platform layer for Node. Its purpose is to abstract IOCP on +Windows and libev on Unix systems. We intend to eventually contain all +platform differences in this library. + +http://nodejs.org/ + +## Features + + * Non-blocking TCP sockets + + * Non-blocking named pipes + + * UDP + + * Timers + + * Child process spawning + + * Asynchronous DNS via c-ares or `uv_getaddrinfo`. + + * Asynchronous file system APIs `uv_fs_*` + + * High resolution time `uv_hrtime` + + * Current executable path look up `uv_exepath` + + * Thread pool scheduling `uv_queue_work` + + * ANSI escape code controlled TTY `uv_tty_t` + + * File system events Currently supports inotify, `ReadDirectoryChangesW` + and kqueue. Event ports in the near future. + `uv_fs_event_t` + + * IPC and socket sharing between processes `uv_write2` + + +## Documentation + +See `include/uv.h`. + + +## Build Instructions + +For GCC (including MinGW) there are two methods building: via normal +makefiles or via GYP. GYP is a meta-build system which can generate MSVS, +Makefile, and XCode backends. It is best used for integration into other +projects. The old (more stable) system is using Makefiles. + +To build via Makefile simply execute: + + make + +To build with Visual Studio run the vcbuilds.bat file which will +checkout the GYP code into build/gyp and generate the uv.sln and +related files. + +Windows users can also build from cmd-line using msbuild. This is +done by running vcbuild.bat from Visual Studio command prompt. + +To have GYP generate build script for another system you will need to +checkout GYP into the project tree manually: + + svn co http://gyp.googlecode.com/svn/trunk build/gyp + +Unix users run + + ./gyp_uv -f make + make + +Macintosh users run + + ./gyp_uv -f xcode + xcodebuild -project uv.xcodeproj -configuration Release -target All + + +## Supported Platforms + +Microsoft Windows operating systems since Windows XP SP2. It can be built +with either Visual Studio or MinGW. + +Linux 2.6 using the GCC toolchain. + +MacOS using the GCC or XCode toolchain. + +Solaris 121 and later using GCC toolchain. diff --git a/node-v0.8.14/deps/uv/common.gypi b/node-v0.8.14/deps/uv/common.gypi new file mode 100644 index 0000000..0ffb45e --- /dev/null +++ b/node-v0.8.14/deps/uv/common.gypi @@ -0,0 +1,178 @@ +{ + 'variables': { + 'visibility%': 'hidden', # V8's visibility setting + 'target_arch%': 'ia32', # set v8's target architecture + 'host_arch%': 'ia32', # set v8's host architecture + 'library%': 'static_library', # allow override to 'shared_library' for DLL/.so builds + 'component%': 'static_library', # NB. these names match with what V8 expects + 'msvs_multi_core_compile': '0', # we do enable multicore compiles, but not using the V8 way + 'gcc_version%': 'unknown', + 'clang%': 0, + }, + + 'target_defaults': { + 'default_configuration': 'Debug', + 'configurations': { + 'Debug': { + 'defines': [ 'DEBUG', '_DEBUG' ], + 'cflags': [ '-g', '-O0' ], + 'msvs_settings': { + 'VCCLCompilerTool': { + 'target_conditions': [ + ['library=="static_library"', { + 'RuntimeLibrary': 1, # static debug + }, { + 'RuntimeLibrary': 3, # DLL debug + }], + ], + 'Optimization': 0, # /Od, no optimization + 'MinimalRebuild': 'false', + 'OmitFramePointers': 'false', + 'BasicRuntimeChecks': 3, # /RTC1 + }, + 'VCLinkerTool': { + 'LinkIncremental': 2, # enable incremental linking + }, + }, + 'xcode_settings': { + 'GCC_OPTIMIZATION_LEVEL': '0', + }, + 'conditions': [ + ['OS != "win"', { + 'defines': [ 'EV_VERIFY=2' ], + }], + ] + }, + 'Release': { + 'defines': [ 'NDEBUG' ], + 'cflags': [ '-O3', '-fomit-frame-pointer', '-fdata-sections', '-ffunction-sections' ], + 'msvs_settings': { + 'VCCLCompilerTool': { + 'target_conditions': [ + ['library=="static_library"', { + 'RuntimeLibrary': 0, # static release + }, { + 'RuntimeLibrary': 2, # debug release + }], + ], + 'Optimization': 3, # /Ox, full optimization + 'FavorSizeOrSpeed': 1, # /Ot, favour speed over size + 'InlineFunctionExpansion': 2, # /Ob2, inline anything eligible + 'WholeProgramOptimization': 'true', # /GL, whole program optimization, needed for LTCG + 'OmitFramePointers': 'true', + 'EnableFunctionLevelLinking': 'true', + 'EnableIntrinsicFunctions': 'true', + }, + 'VCLibrarianTool': { + 'AdditionalOptions': [ + '/LTCG', # link time code generation + ], + }, + 'VCLinkerTool': { + 'LinkTimeCodeGeneration': 1, # link-time code generation + 'OptimizeReferences': 2, # /OPT:REF + 'EnableCOMDATFolding': 2, # /OPT:ICF + 'LinkIncremental': 1, # disable incremental linking + }, + }, + } + }, + 'msvs_settings': { + 'VCCLCompilerTool': { + 'StringPooling': 'true', # pool string literals + 'DebugInformationFormat': 3, # Generate a PDB + 'WarningLevel': 3, + 'BufferSecurityCheck': 'true', + 'ExceptionHandling': 1, # /EHsc + 'SuppressStartupBanner': 'true', + 'WarnAsError': 'false', + 'AdditionalOptions': [ + '/MP', # compile across multiple CPUs + ], + }, + 'VCLibrarianTool': { + }, + 'VCLinkerTool': { + 'GenerateDebugInformation': 'true', + 'RandomizedBaseAddress': 2, # enable ASLR + 'DataExecutionPrevention': 2, # enable DEP + 'AllowIsolation': 'true', + 'SuppressStartupBanner': 'true', + 'target_conditions': [ + ['_type=="executable"', { + 'SubSystem': 1, # console executable + }], + ], + }, + }, + 'conditions': [ + ['OS == "win"', { + 'msvs_cygwin_shell': 0, # prevent actions from trying to use cygwin + 'defines': [ + 'WIN32', + # we don't really want VC++ warning us about + # how dangerous C functions are... + '_CRT_SECURE_NO_DEPRECATE', + # ... or that C implementations shouldn't use + # POSIX names + '_CRT_NONSTDC_NO_DEPRECATE', + ], + }], + [ 'OS=="linux" or OS=="freebsd" or OS=="openbsd" or OS=="solaris"', { + 'cflags': [ '-Wall' ], + 'cflags_cc': [ '-fno-rtti', '-fno-exceptions' ], + 'conditions': [ + [ 'host_arch != target_arch and target_arch=="ia32"', { + 'cflags': [ '-m32' ], + 'ldflags': [ '-m32' ], + }], + [ 'OS=="linux"', { + 'cflags': [ '-ansi' ], + }], + [ 'OS=="solaris"', { + 'cflags': [ '-pthreads' ], + 'ldflags': [ '-pthreads' ], + }, { + 'cflags': [ '-pthread' ], + 'ldflags': [ '-pthread' ], + }], + [ 'visibility=="hidden" and (clang==1 or gcc_version >= 40)', { + 'cflags': [ '-fvisibility=hidden' ], + }], + ], + }], + ['OS=="mac"', { + 'xcode_settings': { + 'ALWAYS_SEARCH_USER_PATHS': 'NO', + 'GCC_CW_ASM_SYNTAX': 'NO', # No -fasm-blocks + 'GCC_DYNAMIC_NO_PIC': 'NO', # No -mdynamic-no-pic + # (Equivalent to -fPIC) + 'GCC_ENABLE_CPP_EXCEPTIONS': 'NO', # -fno-exceptions + 'GCC_ENABLE_CPP_RTTI': 'NO', # -fno-rtti + 'GCC_ENABLE_PASCAL_STRINGS': 'NO', # No -mpascal-strings + # GCC_INLINES_ARE_PRIVATE_EXTERN maps to -fvisibility-inlines-hidden + 'GCC_INLINES_ARE_PRIVATE_EXTERN': 'YES', + 'GCC_SYMBOLS_PRIVATE_EXTERN': 'YES', # -fvisibility=hidden + 'GCC_THREADSAFE_STATICS': 'NO', # -fno-threadsafe-statics + 'GCC_WARN_ABOUT_MISSING_NEWLINE': 'YES', # -Wnewline-eof + 'PREBINDING': 'NO', # No -Wl,-prebind + 'USE_HEADERMAP': 'NO', + 'OTHER_CFLAGS': [ + '-fno-strict-aliasing', + ], + 'WARNING_CFLAGS': [ + '-Wall', + '-Wendif-labels', + '-W', + '-Wno-unused-parameter', + ], + }, + 'target_conditions': [ + ['_type!="static_library"', { + 'xcode_settings': {'OTHER_LDFLAGS': ['-Wl,-search_paths_first']}, + }], + ], + }], + ], + }, +} diff --git a/node-v0.8.14/deps/uv/gyp_uv b/node-v0.8.14/deps/uv/gyp_uv new file mode 100755 index 0000000..d861cbc --- /dev/null +++ b/node-v0.8.14/deps/uv/gyp_uv @@ -0,0 +1,75 @@ +#!/usr/bin/env python + +import glob +import os +import subprocess +import sys + +CC = os.environ.get('CC', 'cc') +script_dir = os.path.dirname(__file__) +uv_root = os.path.normpath(script_dir) +output_dir = os.path.join(os.path.abspath(uv_root), 'out') + +sys.path.insert(0, os.path.join(uv_root, 'build', 'gyp', 'pylib')) +try: + import gyp +except ImportError: + print('You need to install gyp in build/gyp first. See the README.') + sys.exit(42) + + +def compiler_version(): + proc = subprocess.Popen(CC.split() + ['--version'], stdout=subprocess.PIPE) + is_clang = 'clang' in proc.communicate()[0].split('\n')[0] + proc = subprocess.Popen(CC.split() + ['-dumpversion'], stdout=subprocess.PIPE) + version = tuple(map(int, proc.communicate()[0].split('.'))) + return (version, is_clang) + + +def run_gyp(args): + rc = gyp.main(args) + if rc != 0: + print 'Error running GYP' + sys.exit(rc) + + +if __name__ == '__main__': + args = sys.argv[1:] + + # GYP bug. + # On msvs it will crash if it gets an absolute path. + # On Mac/make it will crash if it doesn't get an absolute path. + if sys.platform == 'win32': + args.append(os.path.join(uv_root, 'uv.gyp')) + common_fn = os.path.join(uv_root, 'common.gypi') + options_fn = os.path.join(uv_root, 'options.gypi') + else: + args.append(os.path.join(os.path.abspath(uv_root), 'uv.gyp')) + common_fn = os.path.join(os.path.abspath(uv_root), 'common.gypi') + options_fn = os.path.join(os.path.abspath(uv_root), 'options.gypi') + + if os.path.exists(common_fn): + args.extend(['-I', common_fn]) + + if os.path.exists(options_fn): + args.extend(['-I', options_fn]) + + args.append('--depth=' + uv_root) + + # There's a bug with windows which doesn't allow this feature. + if sys.platform != 'win32': + if '-f' not in args: + args.extend('-f make'.split()) + if 'ninja' not in args: + args.extend(['-Goutput_dir=' + output_dir]) + args.extend(['--generator-output', output_dir]) + (major, minor), is_clang = compiler_version() + args.append('-Dgcc_version=%d' % (10 * major + minor)) + args.append('-Dclang=%d' % int(is_clang)) + + args.append('-Dtarget_arch=ia32') + args.append('-Dcomponent=static_library') + args.append('-Dlibrary=static_library') + gyp_args = list(args) + print gyp_args + run_gyp(gyp_args) diff --git a/node-v0.8.14/deps/uv/include/ares.h b/node-v0.8.14/deps/uv/include/ares.h new file mode 100644 index 0000000..53ac861 --- /dev/null +++ b/node-v0.8.14/deps/uv/include/ares.h @@ -0,0 +1,591 @@ + +/* Copyright 1998, 2009 by the Massachusetts Institute of Technology. + * Copyright (C) 2007-2011 by Daniel Stenberg + * + * Permission to use, copy, modify, and distribute this + * software and its documentation for any purpose and without + * fee is hereby granted, provided that the above copyright + * notice appear in all copies and that both that copyright + * notice and this permission notice appear in supporting + * documentation, and that the name of M.I.T. not be used in + * advertising or publicity pertaining to distribution of the + * software without specific, written prior permission. + * M.I.T. makes no representations about the suitability of + * this software for any purpose. It is provided "as is" + * without express or implied warranty. + */ + +#ifndef ARES__H +#define ARES__H + +#include "ares_version.h" /* c-ares version defines */ + +/* + * Define WIN32 when build target is Win32 API + */ + +#if (defined(_WIN32) || defined(__WIN32__)) && \ + !defined(WIN32) && !defined(__SYMBIAN32__) +# define WIN32 +#endif + +/*************************** libuv patch ***************/ + +/* + * We want to avoid autoconf altogether since there are a finite number of + * operating systems and simply build c-ares. Therefore we do not want the + * configurations provided by ares_build.h since we are always statically + * linking c-ares into libuv. Having a system dependent ares_build.h forces + * all users of ares.h to include the correct ares_build.h. We do not care + * about the linking checks provided by ares_rules.h. This would complicate + * the libuv build process. + */ + + +#if defined(WIN32) +/* Configure process defines this to 1 when it finds out that system */ +/* header file ws2tcpip.h must be included by the external interface. */ +/* #undef CARES_PULL_WS2TCPIP_H */ +# include +# include +# include + +#else /* Not Windows */ + +# include +# include +# include +#endif + +#if 0 +/* The size of `long', as computed by sizeof. */ +#define CARES_SIZEOF_LONG 4 +#endif + +/* Integral data type used for ares_socklen_t. */ +#define CARES_TYPEOF_ARES_SOCKLEN_T socklen_t + +#if 0 +/* The size of `ares_socklen_t', as computed by sizeof. */ +#define CARES_SIZEOF_ARES_SOCKLEN_T 4 +#endif + +/* Data type definition of ares_socklen_t. */ +typedef int ares_socklen_t; + +#if 0 /* libuv disabled */ +#include "ares_rules.h" /* c-ares rules enforcement */ +#endif + +/*********************** end libuv patch ***************/ + +#include + +/* HP-UX systems version 9, 10 and 11 lack sys/select.h and so does oldish + libc5-based Linux systems. Only include it on system that are known to + require it! */ +#if defined(_AIX) || defined(__NOVELL_LIBC__) || defined(__NetBSD__) || \ + defined(__minix) || defined(__SYMBIAN32__) || defined(__INTEGRITY) +#include +#endif +#if (defined(NETWARE) && !defined(__NOVELL_LIBC__)) +#include +#endif + +#if defined(WATT32) +# include +# include +# include +#elif defined(_WIN32_WCE) +# ifndef WIN32_LEAN_AND_MEAN +# define WIN32_LEAN_AND_MEAN +# endif +# include +# include +#elif defined(WIN32) +# ifndef WIN32_LEAN_AND_MEAN +# define WIN32_LEAN_AND_MEAN +# endif +# include +# include +# include +#else +# include +# include +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +/* +** c-ares external API function linkage decorations. +*/ + +#if !defined(CARES_STATICLIB) && \ + (defined(WIN32) || defined(_WIN32) || defined(__SYMBIAN32__)) + /* __declspec function decoration for Win32 and Symbian DLL's */ +# if defined(CARES_BUILDING_LIBRARY) +# define CARES_EXTERN __declspec(dllexport) +# else +# define CARES_EXTERN __declspec(dllimport) +# endif +#else + /* visibility function decoration for other cases */ +# if !defined(CARES_SYMBOL_HIDING) || \ + defined(WIN32) || defined(_WIN32) || defined(__SYMBIAN32__) +# define CARES_EXTERN +# else +# define CARES_EXTERN CARES_SYMBOL_SCOPE_EXTERN +# endif +#endif + + +#define ARES_SUCCESS 0 + +/* Server error codes (ARES_ENODATA indicates no relevant answer) */ +#define ARES_ENODATA 1 +#define ARES_EFORMERR 2 +#define ARES_ESERVFAIL 3 +#define ARES_ENOTFOUND 4 +#define ARES_ENOTIMP 5 +#define ARES_EREFUSED 6 + +/* Locally generated error codes */ +#define ARES_EBADQUERY 7 +#define ARES_EBADNAME 8 +#define ARES_EBADFAMILY 9 +#define ARES_EBADRESP 10 +#define ARES_ECONNREFUSED 11 +#define ARES_ETIMEOUT 12 +#define ARES_EOF 13 +#define ARES_EFILE 14 +#define ARES_ENOMEM 15 +#define ARES_EDESTRUCTION 16 +#define ARES_EBADSTR 17 + +/* ares_getnameinfo error codes */ +#define ARES_EBADFLAGS 18 + +/* ares_getaddrinfo error codes */ +#define ARES_ENONAME 19 +#define ARES_EBADHINTS 20 + +/* Uninitialized library error code */ +#define ARES_ENOTINITIALIZED 21 /* introduced in 1.7.0 */ + +/* ares_library_init error codes */ +#define ARES_ELOADIPHLPAPI 22 /* introduced in 1.7.0 */ +#define ARES_EADDRGETNETWORKPARAMS 23 /* introduced in 1.7.0 */ + +/* More error codes */ +#define ARES_ECANCELLED 24 /* introduced in 1.7.0 */ + +/* Flag values */ +#define ARES_FLAG_USEVC (1 << 0) +#define ARES_FLAG_PRIMARY (1 << 1) +#define ARES_FLAG_IGNTC (1 << 2) +#define ARES_FLAG_NORECURSE (1 << 3) +#define ARES_FLAG_STAYOPEN (1 << 4) +#define ARES_FLAG_NOSEARCH (1 << 5) +#define ARES_FLAG_NOALIASES (1 << 6) +#define ARES_FLAG_NOCHECKRESP (1 << 7) + +/* Option mask values */ +#define ARES_OPT_FLAGS (1 << 0) +#define ARES_OPT_TIMEOUT (1 << 1) +#define ARES_OPT_TRIES (1 << 2) +#define ARES_OPT_NDOTS (1 << 3) +#define ARES_OPT_UDP_PORT (1 << 4) +#define ARES_OPT_TCP_PORT (1 << 5) +#define ARES_OPT_SERVERS (1 << 6) +#define ARES_OPT_DOMAINS (1 << 7) +#define ARES_OPT_LOOKUPS (1 << 8) +#define ARES_OPT_SOCK_STATE_CB (1 << 9) +#define ARES_OPT_SORTLIST (1 << 10) +#define ARES_OPT_SOCK_SNDBUF (1 << 11) +#define ARES_OPT_SOCK_RCVBUF (1 << 12) +#define ARES_OPT_TIMEOUTMS (1 << 13) +#define ARES_OPT_ROTATE (1 << 14) + +/* Nameinfo flag values */ +#define ARES_NI_NOFQDN (1 << 0) +#define ARES_NI_NUMERICHOST (1 << 1) +#define ARES_NI_NAMEREQD (1 << 2) +#define ARES_NI_NUMERICSERV (1 << 3) +#define ARES_NI_DGRAM (1 << 4) +#define ARES_NI_TCP 0 +#define ARES_NI_UDP ARES_NI_DGRAM +#define ARES_NI_SCTP (1 << 5) +#define ARES_NI_DCCP (1 << 6) +#define ARES_NI_NUMERICSCOPE (1 << 7) +#define ARES_NI_LOOKUPHOST (1 << 8) +#define ARES_NI_LOOKUPSERVICE (1 << 9) +/* Reserved for future use */ +#define ARES_NI_IDN (1 << 10) +#define ARES_NI_IDN_ALLOW_UNASSIGNED (1 << 11) +#define ARES_NI_IDN_USE_STD3_ASCII_RULES (1 << 12) + +/* Addrinfo flag values */ +#define ARES_AI_CANONNAME (1 << 0) +#define ARES_AI_NUMERICHOST (1 << 1) +#define ARES_AI_PASSIVE (1 << 2) +#define ARES_AI_NUMERICSERV (1 << 3) +#define ARES_AI_V4MAPPED (1 << 4) +#define ARES_AI_ALL (1 << 5) +#define ARES_AI_ADDRCONFIG (1 << 6) +/* Reserved for future use */ +#define ARES_AI_IDN (1 << 10) +#define ARES_AI_IDN_ALLOW_UNASSIGNED (1 << 11) +#define ARES_AI_IDN_USE_STD3_ASCII_RULES (1 << 12) +#define ARES_AI_CANONIDN (1 << 13) + +#define ARES_AI_MASK (ARES_AI_CANONNAME|ARES_AI_NUMERICHOST|ARES_AI_PASSIVE| \ + ARES_AI_NUMERICSERV|ARES_AI_V4MAPPED|ARES_AI_ALL| \ + ARES_AI_ADDRCONFIG) +#define ARES_GETSOCK_MAXNUM 16 /* ares_getsock() can return info about this + many sockets */ +#define ARES_GETSOCK_READABLE(bits,num) (bits & (1<< (num))) +#define ARES_GETSOCK_WRITABLE(bits,num) (bits & (1 << ((num) + \ + ARES_GETSOCK_MAXNUM))) + +/* c-ares library initialization flag values */ +#define ARES_LIB_INIT_NONE (0) +#define ARES_LIB_INIT_WIN32 (1 << 0) +#define ARES_LIB_INIT_ALL (ARES_LIB_INIT_WIN32) + + +/* + * Typedef our socket type + */ + +#ifndef ares_socket_typedef +#ifdef WIN32 +typedef SOCKET ares_socket_t; +#define ARES_SOCKET_BAD INVALID_SOCKET +#else +typedef int ares_socket_t; +#define ARES_SOCKET_BAD -1 +#endif +#define ares_socket_typedef +#endif /* ares_socket_typedef */ + +typedef void (*ares_sock_state_cb)(void *data, + ares_socket_t socket_fd, + int readable, + int writable); + +struct apattern; + +/* NOTE about the ares_options struct to users and developers. + + This struct will remain looking like this. It will not be extended nor + shrunk in future releases, but all new options will be set by ares_set_*() + options instead of with the ares_init_options() function. + + Eventually (in a galaxy far far away), all options will be settable by + ares_set_*() options and the ares_init_options() function will become + deprecated. + + When new options are added to c-ares, they are not added to this + struct. And they are not "saved" with the ares_save_options() function but + instead we encourage the use of the ares_dup() function. Needless to say, + if you add config options to c-ares you need to make sure ares_dup() + duplicates this new option. + + */ +struct ares_options { + int flags; + int timeout; /* in seconds or milliseconds, depending on options */ + int tries; + int ndots; + unsigned short udp_port; + unsigned short tcp_port; + int socket_send_buffer_size; + int socket_receive_buffer_size; + struct in_addr *servers; + int nservers; + char **domains; + int ndomains; + char *lookups; + ares_sock_state_cb sock_state_cb; + void *sock_state_cb_data; + struct apattern *sortlist; + int nsort; +}; + +struct hostent; +struct timeval; +struct sockaddr; +struct ares_channeldata; + +typedef struct ares_channeldata *ares_channel; + +typedef void (*ares_callback)(void *arg, + int status, + int timeouts, + unsigned char *abuf, + int alen); + +typedef void (*ares_host_callback)(void *arg, + int status, + int timeouts, + struct hostent *hostent); + +typedef void (*ares_nameinfo_callback)(void *arg, + int status, + int timeouts, + char *node, + char *service); + +typedef int (*ares_sock_create_callback)(ares_socket_t socket_fd, + int type, + void *data); + +CARES_EXTERN int ares_library_init(int flags); + +CARES_EXTERN void ares_library_cleanup(void); + +CARES_EXTERN const char *ares_version(int *version); + +CARES_EXTERN int ares_init(ares_channel *channelptr); + +CARES_EXTERN int ares_init_options(ares_channel *channelptr, + struct ares_options *options, + int optmask); + +CARES_EXTERN int ares_save_options(ares_channel channel, + struct ares_options *options, + int *optmask); + +CARES_EXTERN void ares_destroy_options(struct ares_options *options); + +CARES_EXTERN int ares_dup(ares_channel *dest, + ares_channel src); + +CARES_EXTERN void ares_destroy(ares_channel channel); + +CARES_EXTERN void ares_cancel(ares_channel channel); + +/* These next 3 configure local binding for the out-going socket + * connection. Use these to specify source IP and/or network device + * on multi-homed systems. + */ +CARES_EXTERN void ares_set_local_ip4(ares_channel channel, unsigned int local_ip); + +/* local_ip6 should be 16 bytes in length */ +CARES_EXTERN void ares_set_local_ip6(ares_channel channel, + const unsigned char* local_ip6); + +/* local_dev_name should be null terminated. */ +CARES_EXTERN void ares_set_local_dev(ares_channel channel, + const char* local_dev_name); + +CARES_EXTERN void ares_set_socket_callback(ares_channel channel, + ares_sock_create_callback callback, + void *user_data); + +CARES_EXTERN void ares_send(ares_channel channel, + const unsigned char *qbuf, + int qlen, + ares_callback callback, + void *arg); + +CARES_EXTERN void ares_query(ares_channel channel, + const char *name, + int dnsclass, + int type, + ares_callback callback, + void *arg); + +CARES_EXTERN void ares_search(ares_channel channel, + const char *name, + int dnsclass, + int type, + ares_callback callback, + void *arg); + +CARES_EXTERN void ares_gethostbyname(ares_channel channel, + const char *name, + int family, + ares_host_callback callback, + void *arg); + +CARES_EXTERN int ares_gethostbyname_file(ares_channel channel, + const char *name, + int family, + struct hostent **host); + +CARES_EXTERN void ares_gethostbyaddr(ares_channel channel, + const void *addr, + int addrlen, + int family, + ares_host_callback callback, + void *arg); + +CARES_EXTERN void ares_getnameinfo(ares_channel channel, + const struct sockaddr *sa, + ares_socklen_t salen, + int flags, + ares_nameinfo_callback callback, + void *arg); + +CARES_EXTERN int ares_fds(ares_channel channel, + fd_set *read_fds, + fd_set *write_fds); + +CARES_EXTERN int ares_getsock(ares_channel channel, + ares_socket_t *socks, + int numsocks); + +CARES_EXTERN struct timeval *ares_timeout(ares_channel channel, + struct timeval *maxtv, + struct timeval *tv); + +CARES_EXTERN void ares_process(ares_channel channel, + fd_set *read_fds, + fd_set *write_fds); + +CARES_EXTERN void ares_process_fd(ares_channel channel, + ares_socket_t read_fd, + ares_socket_t write_fd); + +CARES_EXTERN int ares_mkquery(const char *name, + int dnsclass, + int type, + unsigned short id, + int rd, + unsigned char **buf, + int *buflen); + +CARES_EXTERN int ares_expand_name(const unsigned char *encoded, + const unsigned char *abuf, + int alen, + char **s, + long *enclen); + +CARES_EXTERN int ares_expand_string(const unsigned char *encoded, + const unsigned char *abuf, + int alen, + unsigned char **s, + long *enclen); + +/* + * NOTE: before c-ares 1.7.0 we would most often use the system in6_addr + * struct below when ares itself was built, but many apps would use this + * private version since the header checked a HAVE_* define for it. Starting + * with 1.7.0 we always declare and use our own to stop relying on the + * system's one. + */ +struct ares_in6_addr { + union { + unsigned char _S6_u8[16]; + } _S6_un; +}; + +struct ares_addrttl { + struct in_addr ipaddr; + int ttl; +}; + +struct ares_addr6ttl { + struct ares_in6_addr ip6addr; + int ttl; +}; + +struct ares_srv_reply { + struct ares_srv_reply *next; + char *host; + unsigned short priority; + unsigned short weight; + unsigned short port; +}; + +struct ares_mx_reply { + struct ares_mx_reply *next; + char *host; + unsigned short priority; +}; + +struct ares_txt_reply { + struct ares_txt_reply *next; + unsigned char *txt; + size_t length; /* length excludes null termination */ +}; + +/* +** Parse the buffer, starting at *abuf and of length alen bytes, previously +** obtained from an ares_search call. Put the results in *host, if nonnull. +** Also, if addrttls is nonnull, put up to *naddrttls IPv4 addresses along with +** their TTLs in that array, and set *naddrttls to the number of addresses +** so written. +*/ + +CARES_EXTERN int ares_parse_a_reply(const unsigned char *abuf, + int alen, + struct hostent **host, + struct ares_addrttl *addrttls, + int *naddrttls); + +CARES_EXTERN int ares_parse_aaaa_reply(const unsigned char *abuf, + int alen, + struct hostent **host, + struct ares_addr6ttl *addrttls, + int *naddrttls); + +CARES_EXTERN int ares_parse_ptr_reply(const unsigned char *abuf, + int alen, + const void *addr, + int addrlen, + int family, + struct hostent **host); + +CARES_EXTERN int ares_parse_ns_reply(const unsigned char *abuf, + int alen, + struct hostent **host); + +CARES_EXTERN int ares_parse_srv_reply(const unsigned char* abuf, + int alen, + struct ares_srv_reply** srv_out); + +CARES_EXTERN int ares_parse_mx_reply(const unsigned char* abuf, + int alen, + struct ares_mx_reply** mx_out); + +CARES_EXTERN int ares_parse_txt_reply(const unsigned char* abuf, + int alen, + struct ares_txt_reply** txt_out); + +CARES_EXTERN void ares_free_string(void *str); + +CARES_EXTERN void ares_free_hostent(struct hostent *host); + +CARES_EXTERN void ares_free_data(void *dataptr); + +CARES_EXTERN const char *ares_strerror(int code); + +/* TODO: Hold port here as well. */ +struct ares_addr_node { + struct ares_addr_node *next; + int family; + union { + struct in_addr addr4; + struct ares_in6_addr addr6; + } addr; +}; + +CARES_EXTERN int ares_set_servers(ares_channel channel, + struct ares_addr_node *servers); + +/* Incomming string format: host[:port][,host[:port]]... */ +CARES_EXTERN int ares_set_servers_csv(ares_channel channel, + const char* servers); + +CARES_EXTERN int ares_get_servers(ares_channel channel, + struct ares_addr_node **servers); + +#ifdef __cplusplus +} +#endif + +#endif /* ARES__H */ diff --git a/node-v0.8.14/deps/uv/include/ares_version.h b/node-v0.8.14/deps/uv/include/ares_version.h new file mode 100644 index 0000000..efd0156 --- /dev/null +++ b/node-v0.8.14/deps/uv/include/ares_version.h @@ -0,0 +1,24 @@ + +#ifndef ARES__VERSION_H +#define ARES__VERSION_H + +/* This is the global package copyright */ +#define ARES_COPYRIGHT "2004 - 2010 Daniel Stenberg, ." + +#define ARES_VERSION_MAJOR 1 +#define ARES_VERSION_MINOR 7 +#define ARES_VERSION_PATCH 5 +#define ARES_VERSION ((ARES_VERSION_MAJOR<<16)|\ + (ARES_VERSION_MINOR<<8)|\ + (ARES_VERSION_PATCH)) +#define ARES_VERSION_STR "1.7.5-DEV" + +#if (ARES_VERSION >= 0x010700) +# define CARES_HAVE_ARES_LIBRARY_INIT 1 +# define CARES_HAVE_ARES_LIBRARY_CLEANUP 1 +#else +# undef CARES_HAVE_ARES_LIBRARY_INIT +# undef CARES_HAVE_ARES_LIBRARY_CLEANUP +#endif + +#endif diff --git a/node-v0.8.14/deps/uv/include/uv-private/eio.h b/node-v0.8.14/deps/uv/include/uv-private/eio.h new file mode 100644 index 0000000..aab9988 --- /dev/null +++ b/node-v0.8.14/deps/uv/include/uv-private/eio.h @@ -0,0 +1,403 @@ +/* + * libeio API header + * + * Copyright (c) 2007,2008,2009,2010,2011 Marc Alexander Lehmann + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modifica- + * tion, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MER- + * CHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO + * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPE- + * CIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTH- + * ERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * + * Alternatively, the contents of this file may be used under the terms of + * the GNU General Public License ("GPL") version 2 or any later version, + * in which case the provisions of the GPL are applicable instead of + * the above. If you wish to allow the use of your version of this file + * only under the terms of the GPL and not to allow others to use your + * version of this file under the BSD license, indicate your decision + * by deleting the provisions above and replace them with the notice + * and other provisions required by the GPL. If you do not delete the + * provisions above, a recipient may use your version of this file under + * either the BSD or the GPL. + */ + +#ifndef EIO_H_ +#define EIO_H_ + +#ifdef __cplusplus +extern "C" { +#endif + +#include +#include +#include + +typedef struct eio_req eio_req; +typedef struct eio_dirent eio_dirent; + +typedef int (*eio_cb)(eio_req *req); + +#ifndef EIO_REQ_MEMBERS +# define EIO_REQ_MEMBERS +#endif + +#ifndef EIO_STRUCT_STAT +# ifdef _WIN32 +# define EIO_STRUCT_STAT struct _stati64 +# define EIO_STRUCT_STATI64 +# else +# define EIO_STRUCT_STAT struct stat +# endif +#endif + +#ifdef _WIN32 + typedef int eio_uid_t; + typedef int eio_gid_t; + typedef int eio_mode_t; + #ifdef __MINGW32__ /* no intptr_t */ + typedef ssize_t eio_ssize_t; + #else + typedef intptr_t eio_ssize_t; /* or SSIZE_T */ + #endif + #if __GNUC__ + typedef long long eio_ino_t; + #else + typedef __int64 eio_ino_t; /* unsigned not supported by msvc */ + #endif +#else + typedef uid_t eio_uid_t; + typedef gid_t eio_gid_t; + typedef ssize_t eio_ssize_t; + typedef ino_t eio_ino_t; + typedef mode_t eio_mode_t; +#endif + +#ifndef EIO_STRUCT_STATVFS +# define EIO_STRUCT_STATVFS struct statvfs +#endif + +/* for readdir */ + +/* eio_readdir flags */ +enum +{ + EIO_READDIR_DENTS = 0x01, /* ptr2 contains eio_dirents, not just the (unsorted) names */ + EIO_READDIR_DIRS_FIRST = 0x02, /* dirents gets sorted into a good stat() ing order to find directories first */ + EIO_READDIR_STAT_ORDER = 0x04, /* dirents gets sorted into a good stat() ing order to quickly stat all files */ + EIO_READDIR_FOUND_UNKNOWN = 0x80, /* set by eio_readdir when *_ARRAY was set and any TYPE=UNKNOWN's were found */ + + EIO_READDIR_CUSTOM1 = 0x100, /* for use by apps */ + EIO_READDIR_CUSTOM2 = 0x200 /* for use by apps */ +}; + +/* using "typical" values in the hope that the compiler will do something sensible */ +enum eio_dtype +{ + EIO_DT_UNKNOWN = 0, + EIO_DT_FIFO = 1, + EIO_DT_CHR = 2, + EIO_DT_MPC = 3, /* multiplexed char device (v7+coherent) */ + EIO_DT_DIR = 4, + EIO_DT_NAM = 5, /* xenix special named file */ + EIO_DT_BLK = 6, + EIO_DT_MPB = 7, /* multiplexed block device (v7+coherent) */ + EIO_DT_REG = 8, + EIO_DT_NWK = 9, /* HP-UX network special */ + EIO_DT_CMP = 9, /* VxFS compressed */ + EIO_DT_LNK = 10, + /* DT_SHAD = 11,*/ + EIO_DT_SOCK = 12, + EIO_DT_DOOR = 13, /* solaris door */ + EIO_DT_WHT = 14, + EIO_DT_MAX = 15 /* highest DT_VALUE ever, hopefully */ +}; + +struct eio_dirent +{ + int nameofs; /* offset of null-terminated name string in (char *)req->ptr2 */ + unsigned short namelen; /* size of filename without trailing 0 */ + unsigned char type; /* one of EIO_DT_* */ + signed char score; /* internal use */ + eio_ino_t inode; /* the inode number, if available, otherwise unspecified */ +}; + +/* eio_msync flags */ +enum +{ + EIO_MS_ASYNC = 1, + EIO_MS_INVALIDATE = 2, + EIO_MS_SYNC = 4 +}; + +/* eio_mtouch flags */ +enum +{ + EIO_MT_MODIFY = 1 +}; + +/* eio_sync_file_range flags */ +enum +{ + EIO_SYNC_FILE_RANGE_WAIT_BEFORE = 1, + EIO_SYNC_FILE_RANGE_WRITE = 2, + EIO_SYNC_FILE_RANGE_WAIT_AFTER = 4 +}; + +/* eio_fallocate flags */ +enum +{ + EIO_FALLOC_FL_KEEP_SIZE = 1 /* MUST match the value in linux/falloc.h */ +}; + +/* timestamps and differences - feel free to use double in your code directly */ +typedef double eio_tstamp; + +/* the eio request structure */ +enum +{ + EIO_CUSTOM, + EIO_OPEN, EIO_CLOSE, EIO_DUP2, + EIO_READ, EIO_WRITE, + EIO_READAHEAD, EIO_SENDFILE, + EIO_STAT, EIO_LSTAT, EIO_FSTAT, + EIO_STATVFS, EIO_FSTATVFS, + EIO_TRUNCATE, EIO_FTRUNCATE, + EIO_UTIME, EIO_FUTIME, + EIO_CHMOD, EIO_FCHMOD, + EIO_CHOWN, EIO_FCHOWN, + EIO_SYNC, EIO_FSYNC, EIO_FDATASYNC, EIO_SYNCFS, + EIO_MSYNC, EIO_MTOUCH, EIO_SYNC_FILE_RANGE, EIO_FALLOCATE, + EIO_MLOCK, EIO_MLOCKALL, + EIO_UNLINK, EIO_RMDIR, EIO_MKDIR, EIO_RENAME, + EIO_MKNOD, EIO_READDIR, + EIO_LINK, EIO_SYMLINK, EIO_READLINK, EIO_REALPATH, + EIO_GROUP, EIO_NOP, + EIO_BUSY +}; + +/* mlockall constants */ +enum +{ + EIO_MCL_CURRENT = 1, + EIO_MCL_FUTURE = 2 +}; + +/* request priorities */ + +enum { + EIO_PRI_MIN = -4, + EIO_PRI_MAX = 4, + EIO_PRI_DEFAULT = 0 +}; + +#define ETP_PRI_MIN EIO_PRI_MIN +#define ETP_PRI_MAX EIO_PRI_MAX + +#define ETP_NUM_PRI (ETP_PRI_MAX - ETP_PRI_MIN + 1) + +#define ETP_REQ eio_req + +/* + * a somewhat faster data structure might be nice, but + * with 8 priorities this actually needs <20 insns + * per shift, the most expensive operation. + */ +typedef struct { + ETP_REQ *qs[ETP_NUM_PRI], *qe[ETP_NUM_PRI]; /* qstart, qend */ + int size; +} etp_reqq; + +typedef struct { + etp_reqq res_queue; /* queue of outstanding responses for this channel */ + void *data; /* use this for what you want */ +} eio_channel; + +/* eio request structure */ +/* this structure is mostly read-only */ +/* when initialising it, all members must be zero-initialised */ +struct eio_req +{ + eio_req volatile *next; /* private ETP */ + + eio_ssize_t result; /* result of syscall, e.g. result = read (... */ + off_t offs; /* read, write, truncate, readahead, sync_file_range, fallocate: file offset, mknod: dev_t */ + size_t size; /* read, write, readahead, sendfile, msync, mlock, sync_file_range, fallocate: length */ + void *ptr1; /* all applicable requests: pathname, old name; readdir: optional eio_dirents */ + void *ptr2; /* all applicable requests: new name or memory buffer; readdir: name strings */ + eio_tstamp nv1; /* utime, futime: atime; busy: sleep time */ + eio_tstamp nv2; /* utime, futime: mtime */ + + int type; /* EIO_xxx constant ETP */ + int int1; /* all applicable requests: file descriptor; sendfile: output fd; open, msync, mlockall, readdir: flags */ + long int2; /* chown, fchown: uid; sendfile: input fd; open, chmod, mkdir, mknod: file mode, sync_file_range, fallocate: flags */ + long int3; /* chown, fchown: gid */ + int errorno; /* errno value on syscall return */ + + eio_channel *channel; /* data used to direct poll callbacks arising from this req */ + +#if __i386 || __amd64 + unsigned char cancelled; +#else + sig_atomic_t cancelled; +#endif + + unsigned char flags; /* private */ + signed char pri; /* the priority */ + + void *data; + eio_cb finish; + void (*destroy)(eio_req *req); /* called when request no longer needed */ + void (*feed)(eio_req *req); /* only used for group requests */ + + EIO_REQ_MEMBERS + + eio_req *grp, *grp_prev, *grp_next, *grp_first; /* private */ +}; + +/* _private_ request flags */ +enum { + EIO_FLAG_PTR1_FREE = 0x01, /* need to free(ptr1) */ + EIO_FLAG_PTR2_FREE = 0x02, /* need to free(ptr2) */ + EIO_FLAG_GROUPADD = 0x04 /* some request was added to the group */ +}; + +/* undocumented/unsupported/private helper */ +/*void eio_page_align (void **addr, size_t *length);*/ + +/* returns < 0 on error, errno set + * need_poll, if non-zero, will be called when results are available + * and eio_poll_cb needs to be invoked (it MUST NOT call eio_poll_cb itself). + * done_poll is called when the need to poll is gone. + */ +int eio_init (void (*want_poll)(eio_channel *), void (*done_poll)(eio_channel *)); + +/* initialises a channel */ +void eio_channel_init(eio_channel *, void *data); + +/* must be called regularly to handle pending requests */ +/* returns 0 if all requests were handled, -1 if not, or the value of EIO_FINISH if != 0 */ +int eio_poll (eio_channel *channel); + +/* stop polling if poll took longer than duration seconds */ +void eio_set_max_poll_time (eio_tstamp nseconds); +/* do not handle more then count requests in one call to eio_poll_cb */ +void eio_set_max_poll_reqs (unsigned int nreqs); + +/* set minimum required number + * maximum wanted number + * or maximum idle number of threads */ +void eio_set_min_parallel (unsigned int nthreads); +void eio_set_max_parallel (unsigned int nthreads); +void eio_set_max_idle (unsigned int nthreads); +void eio_set_idle_timeout (unsigned int seconds); + +unsigned int eio_nreqs (void); /* number of requests in-flight */ +unsigned int eio_nready (void); /* number of not-yet handled requests */ +unsigned int eio_npending (void); /* number of finished but unhandled requests */ +unsigned int eio_nthreads (void); /* number of worker threads in use currently */ + +/*****************************************************************************/ +/* convenience wrappers */ + +#ifndef EIO_NO_WRAPPERS +eio_req *eio_nop (int pri, eio_cb cb, void *data, eio_channel *channel); /* does nothing except go through the whole process */ +eio_req *eio_busy (eio_tstamp delay, int pri, eio_cb cb, void *data, eio_channel *channel); /* ties a thread for this long, simulating busyness */ +eio_req *eio_sync (int pri, eio_cb cb, void *data, eio_channel *channel); +eio_req *eio_fsync (int fd, int pri, eio_cb cb, void *data, eio_channel *channel); +eio_req *eio_fdatasync (int fd, int pri, eio_cb cb, void *data, eio_channel *channel); +eio_req *eio_syncfs (int fd, int pri, eio_cb cb, void *data, eio_channel *channel); +eio_req *eio_msync (void *addr, size_t length, int flags, int pri, eio_cb cb, void *data, eio_channel *channel); +eio_req *eio_mtouch (void *addr, size_t length, int flags, int pri, eio_cb cb, void *data, eio_channel *channel); +eio_req *eio_mlock (void *addr, size_t length, int pri, eio_cb cb, void *data, eio_channel *channel); +eio_req *eio_mlockall (int flags, int pri, eio_cb cb, void *data, eio_channel *channel); +eio_req *eio_sync_file_range (int fd, off_t offset, size_t nbytes, unsigned int flags, int pri, eio_cb cb, void *data, eio_channel *channel); +eio_req *eio_fallocate (int fd, int mode, off_t offset, size_t len, int pri, eio_cb cb, void *data, eio_channel *channel); +eio_req *eio_close (int fd, int pri, eio_cb cb, void *data, eio_channel *channel); +eio_req *eio_readahead (int fd, off_t offset, size_t length, int pri, eio_cb cb, void *data, eio_channel *channel); +eio_req *eio_read (int fd, void *buf, size_t length, off_t offset, int pri, eio_cb cb, void *data, eio_channel *channel); +eio_req *eio_write (int fd, void *buf, size_t length, off_t offset, int pri, eio_cb cb, void *data, eio_channel *channel); +eio_req *eio_fstat (int fd, int pri, eio_cb cb, void *data, eio_channel *channel); /* stat buffer=ptr2 allocated dynamically */ +eio_req *eio_fstatvfs (int fd, int pri, eio_cb cb, void *data, eio_channel *channel); /* stat buffer=ptr2 allocated dynamically */ +eio_req *eio_futime (int fd, eio_tstamp atime, eio_tstamp mtime, int pri, eio_cb cb, void *data, eio_channel *channel); +eio_req *eio_ftruncate (int fd, off_t offset, int pri, eio_cb cb, void *data, eio_channel *channel); +eio_req *eio_fchmod (int fd, eio_mode_t mode, int pri, eio_cb cb, void *data, eio_channel *channel); +eio_req *eio_fchown (int fd, eio_uid_t uid, eio_gid_t gid, int pri, eio_cb cb, void *data, eio_channel *channel); +eio_req *eio_dup2 (int fd, int fd2, int pri, eio_cb cb, void *data, eio_channel *channel); +eio_req *eio_sendfile (int out_fd, int in_fd, off_t in_offset, size_t length, int pri, eio_cb cb, void *data, eio_channel *channel); +eio_req *eio_open (const char *path, int flags, eio_mode_t mode, int pri, eio_cb cb, void *data, eio_channel *channel); +eio_req *eio_utime (const char *path, eio_tstamp atime, eio_tstamp mtime, int pri, eio_cb cb, void *data, eio_channel *channel); +eio_req *eio_truncate (const char *path, off_t offset, int pri, eio_cb cb, void *data, eio_channel *channel); +eio_req *eio_chown (const char *path, eio_uid_t uid, eio_gid_t gid, int pri, eio_cb cb, void *data, eio_channel *channel); +eio_req *eio_chmod (const char *path, eio_mode_t mode, int pri, eio_cb cb, void *data, eio_channel *channel); +eio_req *eio_mkdir (const char *path, eio_mode_t mode, int pri, eio_cb cb, void *data, eio_channel *channel); +eio_req *eio_readdir (const char *path, int flags, int pri, eio_cb cb, void *data, eio_channel *channel); /* result=ptr2 allocated dynamically */ +eio_req *eio_rmdir (const char *path, int pri, eio_cb cb, void *data, eio_channel *channel); +eio_req *eio_unlink (const char *path, int pri, eio_cb cb, void *data, eio_channel *channel); +eio_req *eio_readlink (const char *path, int pri, eio_cb cb, void *data, eio_channel *channel); /* result=ptr2 allocated dynamically */ +eio_req *eio_realpath (const char *path, int pri, eio_cb cb, void *data, eio_channel *channel); /* result=ptr2 allocated dynamically */ +eio_req *eio_stat (const char *path, int pri, eio_cb cb, void *data, eio_channel *channel); /* stat buffer=ptr2 allocated dynamically */ +eio_req *eio_lstat (const char *path, int pri, eio_cb cb, void *data, eio_channel *channel); /* stat buffer=ptr2 allocated dynamically */ +eio_req *eio_statvfs (const char *path, int pri, eio_cb cb, void *data, eio_channel *channel); /* stat buffer=ptr2 allocated dynamically */ +eio_req *eio_mknod (const char *path, eio_mode_t mode, dev_t dev, int pri, eio_cb cb, void *data, eio_channel *channel); +eio_req *eio_link (const char *path, const char *new_path, int pri, eio_cb cb, void *data, eio_channel *channel); +eio_req *eio_symlink (const char *path, const char *new_path, int pri, eio_cb cb, void *data, eio_channel *channel); +eio_req *eio_rename (const char *path, const char *new_path, int pri, eio_cb cb, void *data, eio_channel *channel); +eio_req *eio_custom (void (*execute)(eio_req *), int pri, eio_cb cb, void *data, eio_channel *channel); +#endif + +/*****************************************************************************/ +/* groups */ + +eio_req *eio_grp (eio_cb cb, void *data, eio_channel *channel); +void eio_grp_feed (eio_req *grp, void (*feed)(eio_req *req), int limit); +void eio_grp_limit (eio_req *grp, int limit); +void eio_grp_add (eio_req *grp, eio_req *req); +void eio_grp_cancel (eio_req *grp); /* cancels all sub requests but not the group */ + +/*****************************************************************************/ +/* request api */ + +/* true if the request was cancelled, useful in the invoke callback */ +#define EIO_CANCELLED(req) ((req)->cancelled) + +#define EIO_RESULT(req) ((req)->result) +/* returns a pointer to the result buffer allocated by eio */ +#define EIO_BUF(req) ((req)->ptr2) +#define EIO_STAT_BUF(req) ((EIO_STRUCT_STAT *)EIO_BUF(req)) +#define EIO_STATVFS_BUF(req) ((EIO_STRUCT_STATVFS *)EIO_BUF(req)) +#define EIO_PATH(req) ((char *)(req)->ptr1) + +/* submit a request for execution */ +void eio_submit (eio_req *req); +/* cancel a request as soon fast as possible, if possible */ +void eio_cancel (eio_req *req); + +/*****************************************************************************/ +/* convenience functions */ + +eio_ssize_t eio_sendfile_sync (int ofd, int ifd, off_t offset, size_t count); +eio_ssize_t eio__pread (int fd, void *buf, size_t count, off_t offset); +eio_ssize_t eio__pwrite (int fd, void *buf, size_t count, off_t offset); + +#ifdef __cplusplus +} +#endif + +#endif + diff --git a/node-v0.8.14/deps/uv/include/uv-private/ev.h b/node-v0.8.14/deps/uv/include/uv-private/ev.h new file mode 100644 index 0000000..11e81cd --- /dev/null +++ b/node-v0.8.14/deps/uv/include/uv-private/ev.h @@ -0,0 +1,838 @@ +/* + * libev native API header + * + * Copyright (c) 2007,2008,2009,2010,2011 Marc Alexander Lehmann + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modifica- + * tion, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MER- + * CHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO + * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPE- + * CIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTH- + * ERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * + * Alternatively, the contents of this file may be used under the terms of + * the GNU General Public License ("GPL") version 2 or any later version, + * in which case the provisions of the GPL are applicable instead of + * the above. If you wish to allow the use of your version of this file + * only under the terms of the GPL and not to allow others to use your + * version of this file under the BSD license, indicate your decision + * by deleting the provisions above and replace them with the notice + * and other provisions required by the GPL. If you do not delete the + * provisions above, a recipient may use your version of this file under + * either the BSD or the GPL. + */ + +#ifndef EV_H_ +#define EV_H_ + +#ifdef __cplusplus +# define EV_CPP(x) x +#else +# define EV_CPP(x) +#endif + +EV_CPP(extern "C" {) + +#ifdef __GNUC__ +# define EV_MAYBE_UNUSED __attribute__ ((unused)) +#else +# define EV_MAYBE_UNUSED +#endif + +/*****************************************************************************/ + +/* pre-4.0 compatibility */ +#ifndef EV_COMPAT3 +# define EV_COMPAT3 1 +#endif + +#ifndef EV_FEATURES +# define EV_FEATURES 0x7f +#endif + +#define EV_FEATURE_CODE ((EV_FEATURES) & 1) +#define EV_FEATURE_DATA ((EV_FEATURES) & 2) +#define EV_FEATURE_CONFIG ((EV_FEATURES) & 4) +#define EV_FEATURE_API ((EV_FEATURES) & 8) +#define EV_FEATURE_WATCHERS ((EV_FEATURES) & 16) +#define EV_FEATURE_BACKENDS ((EV_FEATURES) & 32) +#define EV_FEATURE_OS ((EV_FEATURES) & 64) + +/* these priorities are inclusive, higher priorities will be invoked earlier */ +#ifndef EV_MINPRI +# define EV_MINPRI (EV_FEATURE_CONFIG ? -2 : 0) +#endif +#ifndef EV_MAXPRI +# define EV_MAXPRI (EV_FEATURE_CONFIG ? +2 : 0) +#endif + +#ifndef EV_MULTIPLICITY +# define EV_MULTIPLICITY EV_FEATURE_CONFIG +#endif + +#ifndef EV_PERIODIC_ENABLE +# define EV_PERIODIC_ENABLE EV_FEATURE_WATCHERS +#endif + +#ifndef EV_STAT_ENABLE +# define EV_STAT_ENABLE EV_FEATURE_WATCHERS +#endif + +#ifndef EV_PREPARE_ENABLE +# define EV_PREPARE_ENABLE EV_FEATURE_WATCHERS +#endif + +#ifndef EV_CHECK_ENABLE +# define EV_CHECK_ENABLE EV_FEATURE_WATCHERS +#endif + +#ifndef EV_IDLE_ENABLE +# define EV_IDLE_ENABLE EV_FEATURE_WATCHERS +#endif + +#ifndef EV_FORK_ENABLE +# define EV_FORK_ENABLE EV_FEATURE_WATCHERS +#endif + +#ifndef EV_CLEANUP_ENABLE +# define EV_CLEANUP_ENABLE EV_FEATURE_WATCHERS +#endif + +#ifndef EV_SIGNAL_ENABLE +# define EV_SIGNAL_ENABLE EV_FEATURE_WATCHERS +#endif + +#ifndef EV_CHILD_ENABLE +# ifdef _WIN32 +# define EV_CHILD_ENABLE 0 +# else +# define EV_CHILD_ENABLE EV_FEATURE_WATCHERS +#endif +#endif + +#ifndef EV_ASYNC_ENABLE +# define EV_ASYNC_ENABLE EV_FEATURE_WATCHERS +#endif + +#ifndef EV_EMBED_ENABLE +# define EV_EMBED_ENABLE EV_FEATURE_WATCHERS +#endif + +#ifndef EV_WALK_ENABLE +# define EV_WALK_ENABLE 0 /* not yet */ +#endif + +/*****************************************************************************/ + +#if EV_CHILD_ENABLE && !EV_SIGNAL_ENABLE +# undef EV_SIGNAL_ENABLE +# define EV_SIGNAL_ENABLE 1 +#endif + +/*****************************************************************************/ + +typedef double ev_tstamp; + +#ifndef EV_ATOMIC_T +# include +# define EV_ATOMIC_T sig_atomic_t volatile +#endif + +#if EV_STAT_ENABLE +# ifdef _WIN32 +# include +# include +# endif +# include +#endif + +/* support multiple event loops? */ +#if EV_MULTIPLICITY +struct ev_loop; +# define EV_P struct ev_loop *loop /* a loop as sole parameter in a declaration */ +# define EV_P_ EV_P, /* a loop as first of multiple parameters */ +# define EV_A loop /* a loop as sole argument to a function call */ +# define EV_A_ EV_A, /* a loop as first of multiple arguments */ +# define EV_DEFAULT_UC ev_default_loop_uc_ () /* the default loop, if initialised, as sole arg */ +# define EV_DEFAULT_UC_ EV_DEFAULT_UC, /* the default loop as first of multiple arguments */ +# define EV_DEFAULT ev_default_loop (0) /* the default loop as sole arg */ +# define EV_DEFAULT_ EV_DEFAULT, /* the default loop as first of multiple arguments */ +#else +# define EV_P void +# define EV_P_ +# define EV_A +# define EV_A_ +# define EV_DEFAULT +# define EV_DEFAULT_ +# define EV_DEFAULT_UC +# define EV_DEFAULT_UC_ +# undef EV_EMBED_ENABLE +#endif + +/* EV_INLINE is used for functions in header files */ +#if __STDC_VERSION__ >= 199901L && __GNUC__ >= 3 +# define EV_INLINE static inline +#else +# define EV_INLINE static +#endif + +/* EV_PROTOTYPES can be used to switch of prototype declarations */ +#ifndef EV_PROTOTYPES +# define EV_PROTOTYPES 1 +#endif + +/*****************************************************************************/ + +#define EV_VERSION_MAJOR 4 +#define EV_VERSION_MINOR 4 + +/* eventmask, revents, events... */ +enum { + EV_UNDEF = -1, /* guaranteed to be invalid */ + EV_NONE = 0x00, /* no events */ + EV_READ = 0x01, /* ev_io detected read will not block */ + EV_WRITE = 0x02, /* ev_io detected write will not block */ + EV_LIBUV_KQUEUE_HACK = 0x40, + EV__IOFDSET = 0x80, /* internal use only */ + EV_IO = EV_READ, /* alias for type-detection */ + EV_TIMER = 0x00000100, /* timer timed out */ +#if EV_COMPAT3 + EV_TIMEOUT = EV_TIMER, /* pre 4.0 API compatibility */ +#endif + EV_PERIODIC = 0x00000200, /* periodic timer timed out */ + EV_SIGNAL = 0x00000400, /* signal was received */ + EV_CHILD = 0x00000800, /* child/pid had status change */ + EV_STAT = 0x00001000, /* stat data changed */ + EV_IDLE = 0x00002000, /* event loop is idling */ + EV_PREPARE = 0x00004000, /* event loop about to poll */ + EV_CHECK = 0x00008000, /* event loop finished poll */ + EV_EMBED = 0x00010000, /* embedded event loop needs sweep */ + EV_FORK = 0x00020000, /* event loop resumed in child */ + EV_CLEANUP = 0x00040000, /* event loop resumed in child */ + EV_ASYNC = 0x00080000, /* async intra-loop signal */ + EV_CUSTOM = 0x01000000, /* for use by user code */ + EV_ERROR = (-2147483647 - 1) /* sent when an error occurs */ +}; + +/* can be used to add custom fields to all watchers, while losing binary compatibility */ +#ifndef EV_COMMON +# define EV_COMMON void *data; +#endif + +#ifndef EV_CB_DECLARE +# define EV_CB_DECLARE(type) void (*cb)(EV_P_ struct type *w, int revents); +#endif +#ifndef EV_CB_INVOKE +# define EV_CB_INVOKE(watcher,revents) (watcher)->cb (EV_A_ (watcher), (revents)) +#endif + +/* not official, do not use */ +#define EV_CB(type,name) void name (EV_P_ struct ev_ ## type *w, int revents) + +/* + * struct member types: + * private: you may look at them, but not change them, + * and they might not mean anything to you. + * ro: can be read anytime, but only changed when the watcher isn't active. + * rw: can be read and modified anytime, even when the watcher is active. + * + * some internal details that might be helpful for debugging: + * + * active is either 0, which means the watcher is not active, + * or the array index of the watcher (periodics, timers) + * or the array index + 1 (most other watchers) + * or simply 1 for watchers that aren't in some array. + * pending is either 0, in which case the watcher isn't, + * or the array index + 1 in the pendings array. + */ + +#if EV_MINPRI == EV_MAXPRI +# define EV_DECL_PRIORITY +#elif !defined (EV_DECL_PRIORITY) +# define EV_DECL_PRIORITY int priority; +#endif + +/* shared by all watchers */ +#define EV_WATCHER(type) \ + int active; /* private */ \ + int pending; /* private */ \ + EV_DECL_PRIORITY /* private */ \ + EV_COMMON /* rw */ \ + EV_CB_DECLARE (type) /* private */ + +#define EV_WATCHER_LIST(type) \ + EV_WATCHER (type) \ + struct ev_watcher_list *next; /* private */ + +#define EV_WATCHER_TIME(type) \ + EV_WATCHER (type) \ + ev_tstamp at; /* private */ + +/* base class, nothing to see here unless you subclass */ +typedef struct ev_watcher +{ + EV_WATCHER (ev_watcher) +} ev_watcher; + +/* base class, nothing to see here unless you subclass */ +typedef struct ev_watcher_list +{ + EV_WATCHER_LIST (ev_watcher_list) +} ev_watcher_list; + +/* base class, nothing to see here unless you subclass */ +typedef struct ev_watcher_time +{ + EV_WATCHER_TIME (ev_watcher_time) +} ev_watcher_time; + +/* invoked when fd is either EV_READable or EV_WRITEable */ +/* revent EV_READ, EV_WRITE */ +typedef struct ev_io +{ + EV_WATCHER_LIST (ev_io) + + int fd; /* ro */ + int events; /* ro */ +} ev_io; + +/* invoked after a specific time, repeatable (based on monotonic clock) */ +/* revent EV_TIMEOUT */ +typedef struct ev_timer +{ + EV_WATCHER_TIME (ev_timer) + + ev_tstamp repeat; /* rw */ +} ev_timer; + +/* invoked at some specific time, possibly repeating at regular intervals (based on UTC) */ +/* revent EV_PERIODIC */ +typedef struct ev_periodic +{ + EV_WATCHER_TIME (ev_periodic) + + ev_tstamp offset; /* rw */ + ev_tstamp interval; /* rw */ + ev_tstamp (*reschedule_cb)(struct ev_periodic *w, ev_tstamp now); /* rw */ +} ev_periodic; + +/* invoked when the given signal has been received */ +/* revent EV_SIGNAL */ +typedef struct ev_signal +{ + EV_WATCHER_LIST (ev_signal) + + int signum; /* ro */ +} ev_signal; + +/* invoked when sigchld is received and waitpid indicates the given pid */ +/* revent EV_CHILD */ +/* does not support priorities */ +typedef struct ev_child +{ + EV_WATCHER_LIST (ev_child) + + int flags; /* private */ + int pid; /* ro */ + int rpid; /* rw, holds the received pid */ + int rstatus; /* rw, holds the exit status, use the macros from sys/wait.h */ +} ev_child; + +#if EV_STAT_ENABLE +/* st_nlink = 0 means missing file or other error */ +# ifdef _WIN32 +typedef struct _stati64 ev_statdata; +# else +typedef struct stat ev_statdata; +# endif + +/* invoked each time the stat data changes for a given path */ +/* revent EV_STAT */ +typedef struct ev_stat +{ + EV_WATCHER_LIST (ev_stat) + + ev_timer timer; /* private */ + ev_tstamp interval; /* ro */ + const char *path; /* ro */ + ev_statdata prev; /* ro */ + ev_statdata attr; /* ro */ + + int wd; /* wd for inotify, fd for kqueue */ +} ev_stat; +#endif + +#if EV_IDLE_ENABLE +/* invoked when the nothing else needs to be done, keeps the process from blocking */ +/* revent EV_IDLE */ +typedef struct ev_idle +{ + EV_WATCHER (ev_idle) +} ev_idle; +#endif + +/* invoked for each run of the mainloop, just before the blocking call */ +/* you can still change events in any way you like */ +/* revent EV_PREPARE */ +typedef struct ev_prepare +{ + EV_WATCHER (ev_prepare) +} ev_prepare; + +/* invoked for each run of the mainloop, just after the blocking call */ +/* revent EV_CHECK */ +typedef struct ev_check +{ + EV_WATCHER (ev_check) +} ev_check; + +#if EV_FORK_ENABLE +/* the callback gets invoked before check in the child process when a fork was detected */ +/* revent EV_FORK */ +typedef struct ev_fork +{ + EV_WATCHER (ev_fork) +} ev_fork; +#endif + +#if EV_CLEANUP_ENABLE +/* is invoked just before the loop gets destroyed */ +/* revent EV_CLEANUP */ +typedef struct ev_cleanup +{ + EV_WATCHER (ev_cleanup) +} ev_cleanup; +#endif + +#if EV_EMBED_ENABLE +/* used to embed an event loop inside another */ +/* the callback gets invoked when the event loop has handled events, and can be 0 */ +typedef struct ev_embed +{ + EV_WATCHER (ev_embed) + + struct ev_loop *other; /* ro */ + ev_io io; /* private */ + ev_prepare prepare; /* private */ + ev_check check; /* unused */ + ev_timer timer; /* unused */ + ev_periodic periodic; /* unused */ + ev_idle idle; /* unused */ + ev_fork fork; /* private */ +#if EV_CLEANUP_ENABLE + ev_cleanup cleanup; /* unused */ +#endif +} ev_embed; +#endif + +#if EV_ASYNC_ENABLE +/* invoked when somebody calls ev_async_send on the watcher */ +/* revent EV_ASYNC */ +typedef struct ev_async +{ + EV_WATCHER (ev_async) + + EV_ATOMIC_T sent; /* private */ +} ev_async; + +# define ev_async_pending(w) (+(w)->sent) +#endif + +/* the presence of this union forces similar struct layout */ +union ev_any_watcher +{ + struct ev_watcher w; + struct ev_watcher_list wl; + + struct ev_io io; + struct ev_timer timer; + struct ev_periodic periodic; + struct ev_signal signal; + struct ev_child child; +#if EV_STAT_ENABLE + struct ev_stat stat; +#endif +#if EV_IDLE_ENABLE + struct ev_idle idle; +#endif + struct ev_prepare prepare; + struct ev_check check; +#if EV_FORK_ENABLE + struct ev_fork fork; +#endif +#if EV_CLEANUP_ENABLE + struct ev_cleanup cleanup; +#endif +#if EV_EMBED_ENABLE + struct ev_embed embed; +#endif +#if EV_ASYNC_ENABLE + struct ev_async async; +#endif +}; + +/* flag bits for ev_default_loop and ev_loop_new */ +enum { + /* the default */ + EVFLAG_AUTO = 0x00000000U, /* not quite a mask */ + /* flag bits */ + EVFLAG_NOENV = 0x01000000U, /* do NOT consult environment */ + EVFLAG_FORKCHECK = 0x02000000U, /* check for a fork in each iteration */ + /* debugging/feature disable */ + EVFLAG_NOINOTIFY = 0x00100000U, /* do not attempt to use inotify */ +#if EV_COMPAT3 + EVFLAG_NOSIGFD = 0, /* compatibility to pre-3.9 */ +#endif + EVFLAG_SIGNALFD = 0x00200000U, /* attempt to use signalfd */ + EVFLAG_NOSIGMASK = 0x00400000U /* avoid modifying the signal mask */ +}; + +/* method bits to be ored together */ +enum { + EVBACKEND_SELECT = 0x00000001U, /* about anywhere */ + EVBACKEND_POLL = 0x00000002U, /* !win */ + EVBACKEND_EPOLL = 0x00000004U, /* linux */ + EVBACKEND_KQUEUE = 0x00000008U, /* bsd */ + EVBACKEND_DEVPOLL = 0x00000010U, /* solaris 8 */ /* NYI */ + EVBACKEND_PORT = 0x00000020U, /* solaris 10 */ + EVBACKEND_ALL = 0x0000003FU, /* all known backends */ + EVBACKEND_MASK = 0x0000FFFFU /* all future backends */ +}; + +#if EV_PROTOTYPES +int ev_version_major (void); +int ev_version_minor (void); + +unsigned int ev_supported_backends (void); +unsigned int ev_recommended_backends (void); +unsigned int ev_embeddable_backends (void); + +ev_tstamp ev_time (void); +void ev_sleep (ev_tstamp delay); /* sleep for a while */ + +/* Sets the allocation function to use, works like realloc. + * It is used to allocate and free memory. + * If it returns zero when memory needs to be allocated, the library might abort + * or take some potentially destructive action. + * The default is your system realloc function. + */ +void ev_set_allocator (void *(*cb)(void *ptr, long size)); + +/* set the callback function to call on a + * retryable syscall error + * (such as failed select, poll, epoll_wait) + */ +void ev_set_syserr_cb (void (*cb)(const char *msg)); + +#if EV_MULTIPLICITY + +/* the default loop is the only one that handles signals and child watchers */ +/* you can call this as often as you like */ +struct ev_loop *ev_default_loop (unsigned int flags EV_CPP (= 0)); + +EV_INLINE struct ev_loop * +EV_MAYBE_UNUSED ev_default_loop_uc_ (void) +{ + extern struct ev_loop *ev_default_loop_ptr; + + return ev_default_loop_ptr; +} + +EV_INLINE int +EV_MAYBE_UNUSED ev_is_default_loop (EV_P) +{ + return EV_A == EV_DEFAULT_UC; +} + +/* create and destroy alternative loops that don't handle signals */ +struct ev_loop *ev_loop_new (unsigned int flags EV_CPP (= 0)); + +int ev_loop_refcount (EV_P); + +ev_tstamp ev_now (EV_P); /* time w.r.t. timers and the eventloop, updated after each poll */ + +#else + +int ev_default_loop (unsigned int flags EV_CPP (= 0)); /* returns true when successful */ + +EV_INLINE ev_tstamp +ev_now (void) +{ + extern ev_tstamp ev_rt_now; + + return ev_rt_now; +} + +/* looks weird, but ev_is_default_loop (EV_A) still works if this exists */ +EV_INLINE int +ev_is_default_loop (void) +{ + return 1; +} + +#endif /* multiplicity */ + +/* destroy event loops, also works for the default loop */ +void ev_loop_destroy (EV_P); + +/* this needs to be called after fork, to duplicate the loop */ +/* when you want to re-use it in the child */ +/* you can call it in either the parent or the child */ +/* you can actually call it at any time, anywhere :) */ +void ev_loop_fork (EV_P); + +unsigned int ev_backend (EV_P); /* backend in use by loop */ + +void ev_now_update (EV_P); /* update event loop time */ + +#if EV_WALK_ENABLE +/* walk (almost) all watchers in the loop of a given type, invoking the */ +/* callback on every such watcher. The callback might stop the watcher, */ +/* but do nothing else with the loop */ +void ev_walk (EV_P_ int types, void (*cb)(EV_P_ int type, void *w)); +#endif + +#endif /* prototypes */ + +/* ev_run flags values */ +enum { + EVRUN_NOWAIT = 1, /* do not block/wait */ + EVRUN_ONCE = 2 /* block *once* only */ +}; + +/* ev_break how values */ +enum { + EVBREAK_CANCEL = 0, /* undo unloop */ + EVBREAK_ONE = 1, /* unloop once */ + EVBREAK_ALL = 2 /* unloop all loops */ +}; + +#if EV_PROTOTYPES +void ev_run (EV_P_ int flags EV_CPP (= 0)); +void ev_break (EV_P_ int how EV_CPP (= EVBREAK_ONE)); /* break out of the loop */ + +/* + * ref/unref can be used to add or remove a refcount on the mainloop. every watcher + * keeps one reference. if you have a long-running watcher you never unregister that + * should not keep ev_loop from running, unref() after starting, and ref() before stopping. + */ +void ev_ref (EV_P); +void ev_unref (EV_P); + +/* + * convenience function, wait for a single event, without registering an event watcher + * if timeout is < 0, do wait indefinitely + */ +void ev_once (EV_P_ int fd, int events, ev_tstamp timeout, void (*cb)(int revents, void *arg), void *arg); + +# if EV_FEATURE_API +unsigned int ev_iteration (EV_P); /* number of loop iterations */ +unsigned int ev_depth (EV_P); /* #ev_loop enters - #ev_loop leaves */ +void ev_verify (EV_P); /* abort if loop data corrupted */ + +void ev_set_io_collect_interval (EV_P_ ev_tstamp interval); /* sleep at least this time, default 0 */ +void ev_set_timeout_collect_interval (EV_P_ ev_tstamp interval); /* sleep at least this time, default 0 */ + +/* advanced stuff for threading etc. support, see docs */ +void ev_set_userdata (EV_P_ void *data); +void *ev_userdata (EV_P); +void ev_set_invoke_pending_cb (EV_P_ void (*invoke_pending_cb)(EV_P)); +void ev_set_loop_release_cb (EV_P_ void (*release)(EV_P), void (*acquire)(EV_P)); + +unsigned int ev_pending_count (EV_P); /* number of pending events, if any */ +void ev_invoke_pending (EV_P); /* invoke all pending watchers */ + +/* + * stop/start the timer handling. + */ +void ev_suspend (EV_P); +void ev_resume (EV_P); +#endif + +#endif + +/* these may evaluate ev multiple times, and the other arguments at most once */ +/* either use ev_init + ev_TYPE_set, or the ev_TYPE_init macro, below, to first initialise a watcher */ +#define ev_init(ev,cb_) do { \ + ((ev_watcher *)(void *)(ev))->active = \ + ((ev_watcher *)(void *)(ev))->pending = 0; \ + ev_set_priority ((ev), 0); \ + ev_set_cb ((ev), cb_); \ +} while (0) + +#define ev_io_set(ev,fd_,events_) do { (ev)->fd = (fd_); (ev)->events = (events_) | EV__IOFDSET; } while (0) +#define ev_timer_set(ev,after_,repeat_) do { ((ev_watcher_time *)(ev))->at = (after_); (ev)->repeat = (repeat_); } while (0) +#define ev_periodic_set(ev,ofs_,ival_,rcb_) do { (ev)->offset = (ofs_); (ev)->interval = (ival_); (ev)->reschedule_cb = (rcb_); } while (0) +#define ev_signal_set(ev,signum_) do { (ev)->signum = (signum_); } while (0) +#define ev_child_set(ev,pid_,trace_) do { (ev)->pid = (pid_); (ev)->flags = !!(trace_); } while (0) +#define ev_stat_set(ev,path_,interval_) do { (ev)->path = (path_); (ev)->interval = (interval_); (ev)->wd = -2; } while (0) +#define ev_idle_set(ev) /* nop, yes, this is a serious in-joke */ +#define ev_prepare_set(ev) /* nop, yes, this is a serious in-joke */ +#define ev_check_set(ev) /* nop, yes, this is a serious in-joke */ +#define ev_embed_set(ev,other_) do { (ev)->other = (other_); } while (0) +#define ev_fork_set(ev) /* nop, yes, this is a serious in-joke */ +#define ev_cleanup_set(ev) /* nop, yes, this is a serious in-joke */ +#define ev_async_set(ev) /* nop, yes, this is a serious in-joke */ + +#define ev_io_init(ev,cb,fd,events) do { ev_init ((ev), (cb)); ev_io_set ((ev),(fd),(events)); } while (0) +#define ev_timer_init(ev,cb,after,repeat) do { ev_init ((ev), (cb)); ev_timer_set ((ev),(after),(repeat)); } while (0) +#define ev_periodic_init(ev,cb,ofs,ival,rcb) do { ev_init ((ev), (cb)); ev_periodic_set ((ev),(ofs),(ival),(rcb)); } while (0) +#define ev_signal_init(ev,cb,signum) do { ev_init ((ev), (cb)); ev_signal_set ((ev), (signum)); } while (0) +#define ev_child_init(ev,cb,pid,trace) do { ev_init ((ev), (cb)); ev_child_set ((ev),(pid),(trace)); } while (0) +#define ev_stat_init(ev,cb,path,interval) do { ev_init ((ev), (cb)); ev_stat_set ((ev),(path),(interval)); } while (0) +#define ev_idle_init(ev,cb) do { ev_init ((ev), (cb)); ev_idle_set ((ev)); } while (0) +#define ev_prepare_init(ev,cb) do { ev_init ((ev), (cb)); ev_prepare_set ((ev)); } while (0) +#define ev_check_init(ev,cb) do { ev_init ((ev), (cb)); ev_check_set ((ev)); } while (0) +#define ev_embed_init(ev,cb,other) do { ev_init ((ev), (cb)); ev_embed_set ((ev),(other)); } while (0) +#define ev_fork_init(ev,cb) do { ev_init ((ev), (cb)); ev_fork_set ((ev)); } while (0) +#define ev_cleanup_init(ev,cb) do { ev_init ((ev), (cb)); ev_cleanup_set ((ev)); } while (0) +#define ev_async_init(ev,cb) do { ev_init ((ev), (cb)); ev_async_set ((ev)); } while (0) + +#define ev_is_pending(ev) (0 + ((ev_watcher *)(void *)(ev))->pending) /* ro, true when watcher is waiting for callback invocation */ +#define ev_is_active(ev) (0 + ((ev_watcher *)(void *)(ev))->active) /* ro, true when the watcher has been started */ + +#define ev_cb(ev) (ev)->cb /* rw */ + +#if EV_MINPRI == EV_MAXPRI +# define ev_priority(ev) ((ev), EV_MINPRI) +# define ev_set_priority(ev,pri) ((ev), (pri)) +#else +# define ev_priority(ev) (+(((ev_watcher *)(void *)(ev))->priority)) +# define ev_set_priority(ev,pri) ( (ev_watcher *)(void *)(ev))->priority = (pri) +#endif + +#define ev_periodic_at(ev) (+((ev_watcher_time *)(ev))->at) + +#ifndef ev_set_cb +# define ev_set_cb(ev,cb_) ev_cb (ev) = (cb_) +#endif + +/* stopping (enabling, adding) a watcher does nothing if it is already running */ +/* stopping (disabling, deleting) a watcher does nothing unless its already running */ +#if EV_PROTOTYPES + +/* feeds an event into a watcher as if the event actually occured */ +/* accepts any ev_watcher type */ +void ev_feed_event (EV_P_ void *w, int revents); +void ev_feed_fd_event (EV_P_ int fd, int revents); +#if EV_SIGNAL_ENABLE +void ev_feed_signal (int signum); +void ev_feed_signal_event (EV_P_ int signum); +#endif +void ev_invoke (EV_P_ void *w, int revents); +int ev_clear_pending (EV_P_ void *w); + +void ev_io_start (EV_P_ ev_io *w); +void ev_io_stop (EV_P_ ev_io *w); + +void ev_timer_start (EV_P_ ev_timer *w); +void ev_timer_stop (EV_P_ ev_timer *w); +/* stops if active and no repeat, restarts if active and repeating, starts if inactive and repeating */ +void ev_timer_again (EV_P_ ev_timer *w); +/* return remaining time */ +ev_tstamp ev_timer_remaining (EV_P_ ev_timer *w); + +#if EV_PERIODIC_ENABLE +void ev_periodic_start (EV_P_ ev_periodic *w); +void ev_periodic_stop (EV_P_ ev_periodic *w); +void ev_periodic_again (EV_P_ ev_periodic *w); +#endif + +/* only supported in the default loop */ +#if EV_SIGNAL_ENABLE +void ev_signal_start (EV_P_ ev_signal *w); +void ev_signal_stop (EV_P_ ev_signal *w); +#endif + +/* only supported in the default loop */ +# if EV_CHILD_ENABLE +void ev_child_start (EV_P_ ev_child *w); +void ev_child_stop (EV_P_ ev_child *w); +# endif + +# if EV_STAT_ENABLE +void ev_stat_start (EV_P_ ev_stat *w); +void ev_stat_stop (EV_P_ ev_stat *w); +void ev_stat_stat (EV_P_ ev_stat *w); +# endif + +# if EV_IDLE_ENABLE +void ev_idle_start (EV_P_ ev_idle *w); +void ev_idle_stop (EV_P_ ev_idle *w); +# endif + +#if EV_PREPARE_ENABLE +void ev_prepare_start (EV_P_ ev_prepare *w); +void ev_prepare_stop (EV_P_ ev_prepare *w); +#endif + +#if EV_CHECK_ENABLE +void ev_check_start (EV_P_ ev_check *w); +void ev_check_stop (EV_P_ ev_check *w); +#endif + +# if EV_FORK_ENABLE +void ev_fork_start (EV_P_ ev_fork *w); +void ev_fork_stop (EV_P_ ev_fork *w); +# endif + +# if EV_CLEANUP_ENABLE +void ev_cleanup_start (EV_P_ ev_cleanup *w); +void ev_cleanup_stop (EV_P_ ev_cleanup *w); +# endif + +# if EV_EMBED_ENABLE +/* only supported when loop to be embedded is in fact embeddable */ +void ev_embed_start (EV_P_ ev_embed *w); +void ev_embed_stop (EV_P_ ev_embed *w); +void ev_embed_sweep (EV_P_ ev_embed *w); +# endif + +# if EV_ASYNC_ENABLE +void ev_async_start (EV_P_ ev_async *w); +void ev_async_stop (EV_P_ ev_async *w); +void ev_async_send (EV_P_ ev_async *w); +# endif + +#if EV_COMPAT3 + #define EVLOOP_NONBLOCK EVRUN_NOWAIT + #define EVLOOP_ONESHOT EVRUN_ONCE + #define EVUNLOOP_CANCEL EVBREAK_CANCEL + #define EVUNLOOP_ONE EVBREAK_ONE + #define EVUNLOOP_ALL EVBREAK_ALL + #if EV_PROTOTYPES + EV_INLINE void EV_MAYBE_UNUSED ev_loop (EV_P_ int flags) { ev_run (EV_A_ flags); } + EV_INLINE void EV_MAYBE_UNUSED ev_unloop (EV_P_ int how ) { ev_break (EV_A_ how ); } + EV_INLINE void EV_MAYBE_UNUSED ev_default_destroy (void) { ev_loop_destroy (EV_DEFAULT); } + EV_INLINE void EV_MAYBE_UNUSED ev_default_fork (void) { ev_loop_fork (EV_DEFAULT); } + #if EV_FEATURE_API + EV_INLINE unsigned int EV_MAYBE_UNUSED ev_loop_count (EV_P) { return ev_iteration (EV_A); } + EV_INLINE unsigned int EV_MAYBE_UNUSED ev_loop_depth (EV_P) { return ev_depth (EV_A); } + EV_INLINE void EV_MAYBE_UNUSED ev_loop_verify (EV_P) { ev_verify (EV_A); } + #endif + #endif +#else + typedef struct ev_loop ev_loop; +#endif + +#endif + +EV_CPP(}) + +#endif + diff --git a/node-v0.8.14/deps/uv/include/uv-private/ngx-queue.h b/node-v0.8.14/deps/uv/include/uv-private/ngx-queue.h new file mode 100644 index 0000000..6fd0071 --- /dev/null +++ b/node-v0.8.14/deps/uv/include/uv-private/ngx-queue.h @@ -0,0 +1,108 @@ + +/* + * Copyright (C) Igor Sysoev + */ + + +#ifndef NGX_QUEUE_H_INCLUDED_ +#define NGX_QUEUE_H_INCLUDED_ + + +typedef struct ngx_queue_s ngx_queue_t; + +struct ngx_queue_s { + ngx_queue_t *prev; + ngx_queue_t *next; +}; + + +#define ngx_queue_init(q) \ + (q)->prev = q; \ + (q)->next = q + + +#define ngx_queue_empty(h) \ + (h == (h)->prev) + + +#define ngx_queue_insert_head(h, x) \ + (x)->next = (h)->next; \ + (x)->next->prev = x; \ + (x)->prev = h; \ + (h)->next = x + + +#define ngx_queue_insert_after ngx_queue_insert_head + + +#define ngx_queue_insert_tail(h, x) \ + (x)->prev = (h)->prev; \ + (x)->prev->next = x; \ + (x)->next = h; \ + (h)->prev = x + + +#define ngx_queue_head(h) \ + (h)->next + + +#define ngx_queue_last(h) \ + (h)->prev + + +#define ngx_queue_sentinel(h) \ + (h) + + +#define ngx_queue_next(q) \ + (q)->next + + +#define ngx_queue_prev(q) \ + (q)->prev + + +#if (NGX_DEBUG) + +#define ngx_queue_remove(x) \ + (x)->next->prev = (x)->prev; \ + (x)->prev->next = (x)->next; \ + (x)->prev = NULL; \ + (x)->next = NULL + +#else + +#define ngx_queue_remove(x) \ + (x)->next->prev = (x)->prev; \ + (x)->prev->next = (x)->next + +#endif + + +#define ngx_queue_split(h, q, n) \ + (n)->prev = (h)->prev; \ + (n)->prev->next = n; \ + (n)->next = q; \ + (h)->prev = (q)->prev; \ + (h)->prev->next = h; \ + (q)->prev = n; + + +#define ngx_queue_add(h, n) \ + (h)->prev->next = (n)->next; \ + (n)->next->prev = (h)->prev; \ + (h)->prev = (n)->prev; \ + (h)->prev->next = h; + + +#define ngx_queue_data(q, type, link) \ + (type *) ((unsigned char *) q - offsetof(type, link)) + + +#define ngx_queue_foreach(q, h) \ + for ((q) = ngx_queue_head(h); \ + (q) != ngx_queue_sentinel(h); \ + (q) = ngx_queue_next(q)) + + +#endif /* NGX_QUEUE_H_INCLUDED_ */ diff --git a/node-v0.8.14/deps/uv/include/uv-private/tree.h b/node-v0.8.14/deps/uv/include/uv-private/tree.h new file mode 100644 index 0000000..f936416 --- /dev/null +++ b/node-v0.8.14/deps/uv/include/uv-private/tree.h @@ -0,0 +1,768 @@ +/*- + * Copyright 2002 Niels Provos + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef UV_TREE_H_ +#define UV_TREE_H_ + +#ifndef UV__UNUSED +# if __GNUC__ +# define UV__UNUSED __attribute__((unused)) +# else +# define UV__UNUSED +# endif +#endif + +/* + * This file defines data structures for different types of trees: + * splay trees and red-black trees. + * + * A splay tree is a self-organizing data structure. Every operation + * on the tree causes a splay to happen. The splay moves the requested + * node to the root of the tree and partly rebalances it. + * + * This has the benefit that request locality causes faster lookups as + * the requested nodes move to the top of the tree. On the other hand, + * every lookup causes memory writes. + * + * The Balance Theorem bounds the total access time for m operations + * and n inserts on an initially empty tree as O((m + n)lg n). The + * amortized cost for a sequence of m accesses to a splay tree is O(lg n); + * + * A red-black tree is a binary search tree with the node color as an + * extra attribute. It fulfills a set of conditions: + * - every search path from the root to a leaf consists of the + * same number of black nodes, + * - each red node (except for the root) has a black parent, + * - each leaf node is black. + * + * Every operation on a red-black tree is bounded as O(lg n). + * The maximum height of a red-black tree is 2lg (n+1). + */ + +#define SPLAY_HEAD(name, type) \ +struct name { \ + struct type *sph_root; /* root of the tree */ \ +} + +#define SPLAY_INITIALIZER(root) \ + { NULL } + +#define SPLAY_INIT(root) do { \ + (root)->sph_root = NULL; \ +} while (/*CONSTCOND*/ 0) + +#define SPLAY_ENTRY(type) \ +struct { \ + struct type *spe_left; /* left element */ \ + struct type *spe_right; /* right element */ \ +} + +#define SPLAY_LEFT(elm, field) (elm)->field.spe_left +#define SPLAY_RIGHT(elm, field) (elm)->field.spe_right +#define SPLAY_ROOT(head) (head)->sph_root +#define SPLAY_EMPTY(head) (SPLAY_ROOT(head) == NULL) + +/* SPLAY_ROTATE_{LEFT,RIGHT} expect that tmp hold SPLAY_{RIGHT,LEFT} */ +#define SPLAY_ROTATE_RIGHT(head, tmp, field) do { \ + SPLAY_LEFT((head)->sph_root, field) = SPLAY_RIGHT(tmp, field); \ + SPLAY_RIGHT(tmp, field) = (head)->sph_root; \ + (head)->sph_root = tmp; \ +} while (/*CONSTCOND*/ 0) + +#define SPLAY_ROTATE_LEFT(head, tmp, field) do { \ + SPLAY_RIGHT((head)->sph_root, field) = SPLAY_LEFT(tmp, field); \ + SPLAY_LEFT(tmp, field) = (head)->sph_root; \ + (head)->sph_root = tmp; \ +} while (/*CONSTCOND*/ 0) + +#define SPLAY_LINKLEFT(head, tmp, field) do { \ + SPLAY_LEFT(tmp, field) = (head)->sph_root; \ + tmp = (head)->sph_root; \ + (head)->sph_root = SPLAY_LEFT((head)->sph_root, field); \ +} while (/*CONSTCOND*/ 0) + +#define SPLAY_LINKRIGHT(head, tmp, field) do { \ + SPLAY_RIGHT(tmp, field) = (head)->sph_root; \ + tmp = (head)->sph_root; \ + (head)->sph_root = SPLAY_RIGHT((head)->sph_root, field); \ +} while (/*CONSTCOND*/ 0) + +#define SPLAY_ASSEMBLE(head, node, left, right, field) do { \ + SPLAY_RIGHT(left, field) = SPLAY_LEFT((head)->sph_root, field); \ + SPLAY_LEFT(right, field) = SPLAY_RIGHT((head)->sph_root, field); \ + SPLAY_LEFT((head)->sph_root, field) = SPLAY_RIGHT(node, field); \ + SPLAY_RIGHT((head)->sph_root, field) = SPLAY_LEFT(node, field); \ +} while (/*CONSTCOND*/ 0) + +/* Generates prototypes and inline functions */ + +#define SPLAY_PROTOTYPE(name, type, field, cmp) \ +void name##_SPLAY(struct name *, struct type *); \ +void name##_SPLAY_MINMAX(struct name *, int); \ +struct type *name##_SPLAY_INSERT(struct name *, struct type *); \ +struct type *name##_SPLAY_REMOVE(struct name *, struct type *); \ + \ +/* Finds the node with the same key as elm */ \ +static __inline struct type * \ +name##_SPLAY_FIND(struct name *head, struct type *elm) \ +{ \ + if (SPLAY_EMPTY(head)) \ + return(NULL); \ + name##_SPLAY(head, elm); \ + if ((cmp)(elm, (head)->sph_root) == 0) \ + return (head->sph_root); \ + return (NULL); \ +} \ + \ +static __inline struct type * \ +name##_SPLAY_NEXT(struct name *head, struct type *elm) \ +{ \ + name##_SPLAY(head, elm); \ + if (SPLAY_RIGHT(elm, field) != NULL) { \ + elm = SPLAY_RIGHT(elm, field); \ + while (SPLAY_LEFT(elm, field) != NULL) { \ + elm = SPLAY_LEFT(elm, field); \ + } \ + } else \ + elm = NULL; \ + return (elm); \ +} \ + \ +static __inline struct type * \ +name##_SPLAY_MIN_MAX(struct name *head, int val) \ +{ \ + name##_SPLAY_MINMAX(head, val); \ + return (SPLAY_ROOT(head)); \ +} + +/* Main splay operation. + * Moves node close to the key of elm to top + */ +#define SPLAY_GENERATE(name, type, field, cmp) \ +struct type * \ +name##_SPLAY_INSERT(struct name *head, struct type *elm) \ +{ \ + if (SPLAY_EMPTY(head)) { \ + SPLAY_LEFT(elm, field) = SPLAY_RIGHT(elm, field) = NULL; \ + } else { \ + int __comp; \ + name##_SPLAY(head, elm); \ + __comp = (cmp)(elm, (head)->sph_root); \ + if(__comp < 0) { \ + SPLAY_LEFT(elm, field) = SPLAY_LEFT((head)->sph_root, field); \ + SPLAY_RIGHT(elm, field) = (head)->sph_root; \ + SPLAY_LEFT((head)->sph_root, field) = NULL; \ + } else if (__comp > 0) { \ + SPLAY_RIGHT(elm, field) = SPLAY_RIGHT((head)->sph_root, field); \ + SPLAY_LEFT(elm, field) = (head)->sph_root; \ + SPLAY_RIGHT((head)->sph_root, field) = NULL; \ + } else \ + return ((head)->sph_root); \ + } \ + (head)->sph_root = (elm); \ + return (NULL); \ +} \ + \ +struct type * \ +name##_SPLAY_REMOVE(struct name *head, struct type *elm) \ +{ \ + struct type *__tmp; \ + if (SPLAY_EMPTY(head)) \ + return (NULL); \ + name##_SPLAY(head, elm); \ + if ((cmp)(elm, (head)->sph_root) == 0) { \ + if (SPLAY_LEFT((head)->sph_root, field) == NULL) { \ + (head)->sph_root = SPLAY_RIGHT((head)->sph_root, field); \ + } else { \ + __tmp = SPLAY_RIGHT((head)->sph_root, field); \ + (head)->sph_root = SPLAY_LEFT((head)->sph_root, field); \ + name##_SPLAY(head, elm); \ + SPLAY_RIGHT((head)->sph_root, field) = __tmp; \ + } \ + return (elm); \ + } \ + return (NULL); \ +} \ + \ +void \ +name##_SPLAY(struct name *head, struct type *elm) \ +{ \ + struct type __node, *__left, *__right, *__tmp; \ + int __comp; \ + \ + SPLAY_LEFT(&__node, field) = SPLAY_RIGHT(&__node, field) = NULL; \ + __left = __right = &__node; \ + \ + while ((__comp = (cmp)(elm, (head)->sph_root)) != 0) { \ + if (__comp < 0) { \ + __tmp = SPLAY_LEFT((head)->sph_root, field); \ + if (__tmp == NULL) \ + break; \ + if ((cmp)(elm, __tmp) < 0){ \ + SPLAY_ROTATE_RIGHT(head, __tmp, field); \ + if (SPLAY_LEFT((head)->sph_root, field) == NULL) \ + break; \ + } \ + SPLAY_LINKLEFT(head, __right, field); \ + } else if (__comp > 0) { \ + __tmp = SPLAY_RIGHT((head)->sph_root, field); \ + if (__tmp == NULL) \ + break; \ + if ((cmp)(elm, __tmp) > 0){ \ + SPLAY_ROTATE_LEFT(head, __tmp, field); \ + if (SPLAY_RIGHT((head)->sph_root, field) == NULL) \ + break; \ + } \ + SPLAY_LINKRIGHT(head, __left, field); \ + } \ + } \ + SPLAY_ASSEMBLE(head, &__node, __left, __right, field); \ +} \ + \ +/* Splay with either the minimum or the maximum element \ + * Used to find minimum or maximum element in tree. \ + */ \ +void name##_SPLAY_MINMAX(struct name *head, int __comp) \ +{ \ + struct type __node, *__left, *__right, *__tmp; \ + \ + SPLAY_LEFT(&__node, field) = SPLAY_RIGHT(&__node, field) = NULL; \ + __left = __right = &__node; \ + \ + while (1) { \ + if (__comp < 0) { \ + __tmp = SPLAY_LEFT((head)->sph_root, field); \ + if (__tmp == NULL) \ + break; \ + if (__comp < 0){ \ + SPLAY_ROTATE_RIGHT(head, __tmp, field); \ + if (SPLAY_LEFT((head)->sph_root, field) == NULL) \ + break; \ + } \ + SPLAY_LINKLEFT(head, __right, field); \ + } else if (__comp > 0) { \ + __tmp = SPLAY_RIGHT((head)->sph_root, field); \ + if (__tmp == NULL) \ + break; \ + if (__comp > 0) { \ + SPLAY_ROTATE_LEFT(head, __tmp, field); \ + if (SPLAY_RIGHT((head)->sph_root, field) == NULL) \ + break; \ + } \ + SPLAY_LINKRIGHT(head, __left, field); \ + } \ + } \ + SPLAY_ASSEMBLE(head, &__node, __left, __right, field); \ +} + +#define SPLAY_NEGINF -1 +#define SPLAY_INF 1 + +#define SPLAY_INSERT(name, x, y) name##_SPLAY_INSERT(x, y) +#define SPLAY_REMOVE(name, x, y) name##_SPLAY_REMOVE(x, y) +#define SPLAY_FIND(name, x, y) name##_SPLAY_FIND(x, y) +#define SPLAY_NEXT(name, x, y) name##_SPLAY_NEXT(x, y) +#define SPLAY_MIN(name, x) (SPLAY_EMPTY(x) ? NULL \ + : name##_SPLAY_MIN_MAX(x, SPLAY_NEGINF)) +#define SPLAY_MAX(name, x) (SPLAY_EMPTY(x) ? NULL \ + : name##_SPLAY_MIN_MAX(x, SPLAY_INF)) + +#define SPLAY_FOREACH(x, name, head) \ + for ((x) = SPLAY_MIN(name, head); \ + (x) != NULL; \ + (x) = SPLAY_NEXT(name, head, x)) + +/* Macros that define a red-black tree */ +#define RB_HEAD(name, type) \ +struct name { \ + struct type *rbh_root; /* root of the tree */ \ +} + +#define RB_INITIALIZER(root) \ + { NULL } + +#define RB_INIT(root) do { \ + (root)->rbh_root = NULL; \ +} while (/*CONSTCOND*/ 0) + +#define RB_BLACK 0 +#define RB_RED 1 +#define RB_ENTRY(type) \ +struct { \ + struct type *rbe_left; /* left element */ \ + struct type *rbe_right; /* right element */ \ + struct type *rbe_parent; /* parent element */ \ + int rbe_color; /* node color */ \ +} + +#define RB_LEFT(elm, field) (elm)->field.rbe_left +#define RB_RIGHT(elm, field) (elm)->field.rbe_right +#define RB_PARENT(elm, field) (elm)->field.rbe_parent +#define RB_COLOR(elm, field) (elm)->field.rbe_color +#define RB_ROOT(head) (head)->rbh_root +#define RB_EMPTY(head) (RB_ROOT(head) == NULL) + +#define RB_SET(elm, parent, field) do { \ + RB_PARENT(elm, field) = parent; \ + RB_LEFT(elm, field) = RB_RIGHT(elm, field) = NULL; \ + RB_COLOR(elm, field) = RB_RED; \ +} while (/*CONSTCOND*/ 0) + +#define RB_SET_BLACKRED(black, red, field) do { \ + RB_COLOR(black, field) = RB_BLACK; \ + RB_COLOR(red, field) = RB_RED; \ +} while (/*CONSTCOND*/ 0) + +#ifndef RB_AUGMENT +#define RB_AUGMENT(x) do {} while (0) +#endif + +#define RB_ROTATE_LEFT(head, elm, tmp, field) do { \ + (tmp) = RB_RIGHT(elm, field); \ + if ((RB_RIGHT(elm, field) = RB_LEFT(tmp, field)) != NULL) { \ + RB_PARENT(RB_LEFT(tmp, field), field) = (elm); \ + } \ + RB_AUGMENT(elm); \ + if ((RB_PARENT(tmp, field) = RB_PARENT(elm, field)) != NULL) { \ + if ((elm) == RB_LEFT(RB_PARENT(elm, field), field)) \ + RB_LEFT(RB_PARENT(elm, field), field) = (tmp); \ + else \ + RB_RIGHT(RB_PARENT(elm, field), field) = (tmp); \ + } else \ + (head)->rbh_root = (tmp); \ + RB_LEFT(tmp, field) = (elm); \ + RB_PARENT(elm, field) = (tmp); \ + RB_AUGMENT(tmp); \ + if ((RB_PARENT(tmp, field))) \ + RB_AUGMENT(RB_PARENT(tmp, field)); \ +} while (/*CONSTCOND*/ 0) + +#define RB_ROTATE_RIGHT(head, elm, tmp, field) do { \ + (tmp) = RB_LEFT(elm, field); \ + if ((RB_LEFT(elm, field) = RB_RIGHT(tmp, field)) != NULL) { \ + RB_PARENT(RB_RIGHT(tmp, field), field) = (elm); \ + } \ + RB_AUGMENT(elm); \ + if ((RB_PARENT(tmp, field) = RB_PARENT(elm, field)) != NULL) { \ + if ((elm) == RB_LEFT(RB_PARENT(elm, field), field)) \ + RB_LEFT(RB_PARENT(elm, field), field) = (tmp); \ + else \ + RB_RIGHT(RB_PARENT(elm, field), field) = (tmp); \ + } else \ + (head)->rbh_root = (tmp); \ + RB_RIGHT(tmp, field) = (elm); \ + RB_PARENT(elm, field) = (tmp); \ + RB_AUGMENT(tmp); \ + if ((RB_PARENT(tmp, field))) \ + RB_AUGMENT(RB_PARENT(tmp, field)); \ +} while (/*CONSTCOND*/ 0) + +/* Generates prototypes and inline functions */ +#define RB_PROTOTYPE(name, type, field, cmp) \ + RB_PROTOTYPE_INTERNAL(name, type, field, cmp,) +#define RB_PROTOTYPE_STATIC(name, type, field, cmp) \ + RB_PROTOTYPE_INTERNAL(name, type, field, cmp, UV__UNUSED static) +#define RB_PROTOTYPE_INTERNAL(name, type, field, cmp, attr) \ +attr void name##_RB_INSERT_COLOR(struct name *, struct type *); \ +attr void name##_RB_REMOVE_COLOR(struct name *, struct type *, struct type *);\ +attr struct type *name##_RB_REMOVE(struct name *, struct type *); \ +attr struct type *name##_RB_INSERT(struct name *, struct type *); \ +attr struct type *name##_RB_FIND(struct name *, struct type *); \ +attr struct type *name##_RB_NFIND(struct name *, struct type *); \ +attr struct type *name##_RB_NEXT(struct type *); \ +attr struct type *name##_RB_PREV(struct type *); \ +attr struct type *name##_RB_MINMAX(struct name *, int); \ + \ + +/* Main rb operation. + * Moves node close to the key of elm to top + */ +#define RB_GENERATE(name, type, field, cmp) \ + RB_GENERATE_INTERNAL(name, type, field, cmp,) +#define RB_GENERATE_STATIC(name, type, field, cmp) \ + RB_GENERATE_INTERNAL(name, type, field, cmp, UV__UNUSED static) +#define RB_GENERATE_INTERNAL(name, type, field, cmp, attr) \ +attr void \ +name##_RB_INSERT_COLOR(struct name *head, struct type *elm) \ +{ \ + struct type *parent, *gparent, *tmp; \ + while ((parent = RB_PARENT(elm, field)) != NULL && \ + RB_COLOR(parent, field) == RB_RED) { \ + gparent = RB_PARENT(parent, field); \ + if (parent == RB_LEFT(gparent, field)) { \ + tmp = RB_RIGHT(gparent, field); \ + if (tmp && RB_COLOR(tmp, field) == RB_RED) { \ + RB_COLOR(tmp, field) = RB_BLACK; \ + RB_SET_BLACKRED(parent, gparent, field); \ + elm = gparent; \ + continue; \ + } \ + if (RB_RIGHT(parent, field) == elm) { \ + RB_ROTATE_LEFT(head, parent, tmp, field); \ + tmp = parent; \ + parent = elm; \ + elm = tmp; \ + } \ + RB_SET_BLACKRED(parent, gparent, field); \ + RB_ROTATE_RIGHT(head, gparent, tmp, field); \ + } else { \ + tmp = RB_LEFT(gparent, field); \ + if (tmp && RB_COLOR(tmp, field) == RB_RED) { \ + RB_COLOR(tmp, field) = RB_BLACK; \ + RB_SET_BLACKRED(parent, gparent, field); \ + elm = gparent; \ + continue; \ + } \ + if (RB_LEFT(parent, field) == elm) { \ + RB_ROTATE_RIGHT(head, parent, tmp, field); \ + tmp = parent; \ + parent = elm; \ + elm = tmp; \ + } \ + RB_SET_BLACKRED(parent, gparent, field); \ + RB_ROTATE_LEFT(head, gparent, tmp, field); \ + } \ + } \ + RB_COLOR(head->rbh_root, field) = RB_BLACK; \ +} \ + \ +attr void \ +name##_RB_REMOVE_COLOR(struct name *head, struct type *parent, \ + struct type *elm) \ +{ \ + struct type *tmp; \ + while ((elm == NULL || RB_COLOR(elm, field) == RB_BLACK) && \ + elm != RB_ROOT(head)) { \ + if (RB_LEFT(parent, field) == elm) { \ + tmp = RB_RIGHT(parent, field); \ + if (RB_COLOR(tmp, field) == RB_RED) { \ + RB_SET_BLACKRED(tmp, parent, field); \ + RB_ROTATE_LEFT(head, parent, tmp, field); \ + tmp = RB_RIGHT(parent, field); \ + } \ + if ((RB_LEFT(tmp, field) == NULL || \ + RB_COLOR(RB_LEFT(tmp, field), field) == RB_BLACK) && \ + (RB_RIGHT(tmp, field) == NULL || \ + RB_COLOR(RB_RIGHT(tmp, field), field) == RB_BLACK)) { \ + RB_COLOR(tmp, field) = RB_RED; \ + elm = parent; \ + parent = RB_PARENT(elm, field); \ + } else { \ + if (RB_RIGHT(tmp, field) == NULL || \ + RB_COLOR(RB_RIGHT(tmp, field), field) == RB_BLACK) { \ + struct type *oleft; \ + if ((oleft = RB_LEFT(tmp, field)) \ + != NULL) \ + RB_COLOR(oleft, field) = RB_BLACK; \ + RB_COLOR(tmp, field) = RB_RED; \ + RB_ROTATE_RIGHT(head, tmp, oleft, field); \ + tmp = RB_RIGHT(parent, field); \ + } \ + RB_COLOR(tmp, field) = RB_COLOR(parent, field); \ + RB_COLOR(parent, field) = RB_BLACK; \ + if (RB_RIGHT(tmp, field)) \ + RB_COLOR(RB_RIGHT(tmp, field), field) = RB_BLACK; \ + RB_ROTATE_LEFT(head, parent, tmp, field); \ + elm = RB_ROOT(head); \ + break; \ + } \ + } else { \ + tmp = RB_LEFT(parent, field); \ + if (RB_COLOR(tmp, field) == RB_RED) { \ + RB_SET_BLACKRED(tmp, parent, field); \ + RB_ROTATE_RIGHT(head, parent, tmp, field); \ + tmp = RB_LEFT(parent, field); \ + } \ + if ((RB_LEFT(tmp, field) == NULL || \ + RB_COLOR(RB_LEFT(tmp, field), field) == RB_BLACK) && \ + (RB_RIGHT(tmp, field) == NULL || \ + RB_COLOR(RB_RIGHT(tmp, field), field) == RB_BLACK)) { \ + RB_COLOR(tmp, field) = RB_RED; \ + elm = parent; \ + parent = RB_PARENT(elm, field); \ + } else { \ + if (RB_LEFT(tmp, field) == NULL || \ + RB_COLOR(RB_LEFT(tmp, field), field) == RB_BLACK) { \ + struct type *oright; \ + if ((oright = RB_RIGHT(tmp, field)) \ + != NULL) \ + RB_COLOR(oright, field) = RB_BLACK; \ + RB_COLOR(tmp, field) = RB_RED; \ + RB_ROTATE_LEFT(head, tmp, oright, field); \ + tmp = RB_LEFT(parent, field); \ + } \ + RB_COLOR(tmp, field) = RB_COLOR(parent, field); \ + RB_COLOR(parent, field) = RB_BLACK; \ + if (RB_LEFT(tmp, field)) \ + RB_COLOR(RB_LEFT(tmp, field), field) = RB_BLACK; \ + RB_ROTATE_RIGHT(head, parent, tmp, field); \ + elm = RB_ROOT(head); \ + break; \ + } \ + } \ + } \ + if (elm) \ + RB_COLOR(elm, field) = RB_BLACK; \ +} \ + \ +attr struct type * \ +name##_RB_REMOVE(struct name *head, struct type *elm) \ +{ \ + struct type *child, *parent, *old = elm; \ + int color; \ + if (RB_LEFT(elm, field) == NULL) \ + child = RB_RIGHT(elm, field); \ + else if (RB_RIGHT(elm, field) == NULL) \ + child = RB_LEFT(elm, field); \ + else { \ + struct type *left; \ + elm = RB_RIGHT(elm, field); \ + while ((left = RB_LEFT(elm, field)) != NULL) \ + elm = left; \ + child = RB_RIGHT(elm, field); \ + parent = RB_PARENT(elm, field); \ + color = RB_COLOR(elm, field); \ + if (child) \ + RB_PARENT(child, field) = parent; \ + if (parent) { \ + if (RB_LEFT(parent, field) == elm) \ + RB_LEFT(parent, field) = child; \ + else \ + RB_RIGHT(parent, field) = child; \ + RB_AUGMENT(parent); \ + } else \ + RB_ROOT(head) = child; \ + if (RB_PARENT(elm, field) == old) \ + parent = elm; \ + (elm)->field = (old)->field; \ + if (RB_PARENT(old, field)) { \ + if (RB_LEFT(RB_PARENT(old, field), field) == old) \ + RB_LEFT(RB_PARENT(old, field), field) = elm; \ + else \ + RB_RIGHT(RB_PARENT(old, field), field) = elm; \ + RB_AUGMENT(RB_PARENT(old, field)); \ + } else \ + RB_ROOT(head) = elm; \ + RB_PARENT(RB_LEFT(old, field), field) = elm; \ + if (RB_RIGHT(old, field)) \ + RB_PARENT(RB_RIGHT(old, field), field) = elm; \ + if (parent) { \ + left = parent; \ + do { \ + RB_AUGMENT(left); \ + } while ((left = RB_PARENT(left, field)) != NULL); \ + } \ + goto color; \ + } \ + parent = RB_PARENT(elm, field); \ + color = RB_COLOR(elm, field); \ + if (child) \ + RB_PARENT(child, field) = parent; \ + if (parent) { \ + if (RB_LEFT(parent, field) == elm) \ + RB_LEFT(parent, field) = child; \ + else \ + RB_RIGHT(parent, field) = child; \ + RB_AUGMENT(parent); \ + } else \ + RB_ROOT(head) = child; \ +color: \ + if (color == RB_BLACK) \ + name##_RB_REMOVE_COLOR(head, parent, child); \ + return (old); \ +} \ + \ +/* Inserts a node into the RB tree */ \ +attr struct type * \ +name##_RB_INSERT(struct name *head, struct type *elm) \ +{ \ + struct type *tmp; \ + struct type *parent = NULL; \ + int comp = 0; \ + tmp = RB_ROOT(head); \ + while (tmp) { \ + parent = tmp; \ + comp = (cmp)(elm, parent); \ + if (comp < 0) \ + tmp = RB_LEFT(tmp, field); \ + else if (comp > 0) \ + tmp = RB_RIGHT(tmp, field); \ + else \ + return (tmp); \ + } \ + RB_SET(elm, parent, field); \ + if (parent != NULL) { \ + if (comp < 0) \ + RB_LEFT(parent, field) = elm; \ + else \ + RB_RIGHT(parent, field) = elm; \ + RB_AUGMENT(parent); \ + } else \ + RB_ROOT(head) = elm; \ + name##_RB_INSERT_COLOR(head, elm); \ + return (NULL); \ +} \ + \ +/* Finds the node with the same key as elm */ \ +attr struct type * \ +name##_RB_FIND(struct name *head, struct type *elm) \ +{ \ + struct type *tmp = RB_ROOT(head); \ + int comp; \ + while (tmp) { \ + comp = cmp(elm, tmp); \ + if (comp < 0) \ + tmp = RB_LEFT(tmp, field); \ + else if (comp > 0) \ + tmp = RB_RIGHT(tmp, field); \ + else \ + return (tmp); \ + } \ + return (NULL); \ +} \ + \ +/* Finds the first node greater than or equal to the search key */ \ +attr struct type * \ +name##_RB_NFIND(struct name *head, struct type *elm) \ +{ \ + struct type *tmp = RB_ROOT(head); \ + struct type *res = NULL; \ + int comp; \ + while (tmp) { \ + comp = cmp(elm, tmp); \ + if (comp < 0) { \ + res = tmp; \ + tmp = RB_LEFT(tmp, field); \ + } \ + else if (comp > 0) \ + tmp = RB_RIGHT(tmp, field); \ + else \ + return (tmp); \ + } \ + return (res); \ +} \ + \ +/* ARGSUSED */ \ +attr struct type * \ +name##_RB_NEXT(struct type *elm) \ +{ \ + if (RB_RIGHT(elm, field)) { \ + elm = RB_RIGHT(elm, field); \ + while (RB_LEFT(elm, field)) \ + elm = RB_LEFT(elm, field); \ + } else { \ + if (RB_PARENT(elm, field) && \ + (elm == RB_LEFT(RB_PARENT(elm, field), field))) \ + elm = RB_PARENT(elm, field); \ + else { \ + while (RB_PARENT(elm, field) && \ + (elm == RB_RIGHT(RB_PARENT(elm, field), field))) \ + elm = RB_PARENT(elm, field); \ + elm = RB_PARENT(elm, field); \ + } \ + } \ + return (elm); \ +} \ + \ +/* ARGSUSED */ \ +attr struct type * \ +name##_RB_PREV(struct type *elm) \ +{ \ + if (RB_LEFT(elm, field)) { \ + elm = RB_LEFT(elm, field); \ + while (RB_RIGHT(elm, field)) \ + elm = RB_RIGHT(elm, field); \ + } else { \ + if (RB_PARENT(elm, field) && \ + (elm == RB_RIGHT(RB_PARENT(elm, field), field))) \ + elm = RB_PARENT(elm, field); \ + else { \ + while (RB_PARENT(elm, field) && \ + (elm == RB_LEFT(RB_PARENT(elm, field), field))) \ + elm = RB_PARENT(elm, field); \ + elm = RB_PARENT(elm, field); \ + } \ + } \ + return (elm); \ +} \ + \ +attr struct type * \ +name##_RB_MINMAX(struct name *head, int val) \ +{ \ + struct type *tmp = RB_ROOT(head); \ + struct type *parent = NULL; \ + while (tmp) { \ + parent = tmp; \ + if (val < 0) \ + tmp = RB_LEFT(tmp, field); \ + else \ + tmp = RB_RIGHT(tmp, field); \ + } \ + return (parent); \ +} + +#define RB_NEGINF -1 +#define RB_INF 1 + +#define RB_INSERT(name, x, y) name##_RB_INSERT(x, y) +#define RB_REMOVE(name, x, y) name##_RB_REMOVE(x, y) +#define RB_FIND(name, x, y) name##_RB_FIND(x, y) +#define RB_NFIND(name, x, y) name##_RB_NFIND(x, y) +#define RB_NEXT(name, x, y) name##_RB_NEXT(y) +#define RB_PREV(name, x, y) name##_RB_PREV(y) +#define RB_MIN(name, x) name##_RB_MINMAX(x, RB_NEGINF) +#define RB_MAX(name, x) name##_RB_MINMAX(x, RB_INF) + +#define RB_FOREACH(x, name, head) \ + for ((x) = RB_MIN(name, head); \ + (x) != NULL; \ + (x) = name##_RB_NEXT(x)) + +#define RB_FOREACH_FROM(x, name, y) \ + for ((x) = (y); \ + ((x) != NULL) && ((y) = name##_RB_NEXT(x), (x) != NULL); \ + (x) = (y)) + +#define RB_FOREACH_SAFE(x, name, head, y) \ + for ((x) = RB_MIN(name, head); \ + ((x) != NULL) && ((y) = name##_RB_NEXT(x), (x) != NULL); \ + (x) = (y)) + +#define RB_FOREACH_REVERSE(x, name, head) \ + for ((x) = RB_MAX(name, head); \ + (x) != NULL; \ + (x) = name##_RB_PREV(x)) + +#define RB_FOREACH_REVERSE_FROM(x, name, y) \ + for ((x) = (y); \ + ((x) != NULL) && ((y) = name##_RB_PREV(x), (x) != NULL); \ + (x) = (y)) + +#define RB_FOREACH_REVERSE_SAFE(x, name, head, y) \ + for ((x) = RB_MAX(name, head); \ + ((x) != NULL) && ((y) = name##_RB_PREV(x), (x) != NULL); \ + (x) = (y)) + +#endif /* UV_TREE_H_ */ diff --git a/node-v0.8.14/deps/uv/include/uv-private/uv-unix.h b/node-v0.8.14/deps/uv/include/uv-private/uv-unix.h new file mode 100644 index 0000000..40bbdf6 --- /dev/null +++ b/node-v0.8.14/deps/uv/include/uv-private/uv-unix.h @@ -0,0 +1,314 @@ +/* Copyright Joyent, Inc. and other Node contributors. All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ + +#ifndef UV_UNIX_H +#define UV_UNIX_H + +#include "ngx-queue.h" + +#include "ev.h" +#include "eio.h" + +#include +#include +#include + +#include +#include +#include +#include +#include + +#include +#include + +#include +#include + +#if defined(__APPLE__) && defined(__MACH__) +# include +# include +# include +#else +# include +#endif + +#if __sun +# include +# include +#endif + +/* Note: May be cast to struct iovec. See writev(2). */ +typedef struct { + char* base; + size_t len; +} uv_buf_t; + +typedef int uv_file; + +typedef int uv_os_sock_t; + +typedef struct stat uv_statbuf_t; + +#define UV_ONCE_INIT PTHREAD_ONCE_INIT + +typedef pthread_once_t uv_once_t; +typedef pthread_t uv_thread_t; +typedef pthread_mutex_t uv_mutex_t; +typedef pthread_rwlock_t uv_rwlock_t; +#if defined(__APPLE__) && defined(__MACH__) +typedef semaphore_t uv_sem_t; +#else +typedef sem_t uv_sem_t; +#endif + +/* Platform-specific definitions for uv_spawn support. */ +typedef gid_t uv_gid_t; +typedef uid_t uv_uid_t; + +/* Platform-specific definitions for uv_dlopen support. */ +#define UV_DYNAMIC /* empty */ +typedef struct { + void* handle; + char* errmsg; +} uv_lib_t; + +struct uv__io_s; +struct uv_loop_s; + +typedef struct uv__io_s uv__io_t; +typedef void (*uv__io_cb)(struct uv_loop_s* loop, uv__io_t* handle, int events); + +struct uv__io_s { + ev_io io_watcher; +}; + +#define UV_REQ_TYPE_PRIVATE /* empty */ + +#if __linux__ +# define UV_LOOP_PRIVATE_PLATFORM_FIELDS \ + uv__io_t inotify_read_watcher; \ + void* inotify_watchers; \ + int inotify_fd; +#elif defined(PORT_SOURCE_FILE) +# define UV_LOOP_PRIVATE_PLATFORM_FIELDS \ + ev_io fs_event_watcher; \ + int fs_fd; +#else +# define UV_LOOP_PRIVATE_PLATFORM_FIELDS +#endif + +#define UV_LOOP_PRIVATE_FIELDS \ + /* Poll result queue */ \ + eio_channel uv_eio_channel; \ + struct ev_loop* ev; \ + /* Various thing for libeio. */ \ + uv_async_t uv_eio_want_poll_notifier; \ + uv_async_t uv_eio_done_poll_notifier; \ + uv_idle_t uv_eio_poller; \ + uv_handle_t* closing_handles; \ + ngx_queue_t prepare_handles; \ + ngx_queue_t check_handles; \ + ngx_queue_t idle_handles; \ + ngx_queue_t async_handles; \ + uv__io_t async_watcher; \ + int async_pipefd[2]; \ + /* RB_HEAD(uv__timers, uv_timer_s) */ \ + struct uv__timers { struct uv_timer_s* rbh_root; } timer_handles; \ + uint64_t time; \ + UV_LOOP_PRIVATE_PLATFORM_FIELDS + +#define UV_REQ_BUFSML_SIZE (4) + +#define UV_REQ_PRIVATE_FIELDS /* empty */ + +#define UV_WRITE_PRIVATE_FIELDS \ + ngx_queue_t queue; \ + int write_index; \ + uv_buf_t* bufs; \ + int bufcnt; \ + int error; \ + uv_buf_t bufsml[UV_REQ_BUFSML_SIZE]; + +#define UV_SHUTDOWN_PRIVATE_FIELDS /* empty */ + +#define UV_CONNECT_PRIVATE_FIELDS \ + ngx_queue_t queue; + +#define UV_UDP_SEND_PRIVATE_FIELDS \ + ngx_queue_t queue; \ + struct sockaddr_in6 addr; \ + int bufcnt; \ + uv_buf_t* bufs; \ + ssize_t status; \ + uv_udp_send_cb send_cb; \ + uv_buf_t bufsml[UV_REQ_BUFSML_SIZE]; \ + +#define UV_PRIVATE_REQ_TYPES /* empty */ + + +/* TODO: union or classes please! */ +#define UV_HANDLE_PRIVATE_FIELDS \ + int flags; \ + uv_handle_t* next_closing; \ + + +#define UV_STREAM_PRIVATE_FIELDS \ + uv_connect_t *connect_req; \ + uv_shutdown_t *shutdown_req; \ + uv__io_t read_watcher; \ + uv__io_t write_watcher; \ + ngx_queue_t write_queue; \ + ngx_queue_t write_completed_queue; \ + uv_connection_cb connection_cb; \ + int delayed_error; \ + int accepted_fd; \ + int fd; \ + + +/* UV_TCP */ +#define UV_TCP_PRIVATE_FIELDS + + +/* UV_UDP */ +#define UV_UDP_PRIVATE_FIELDS \ + int fd; \ + uv_alloc_cb alloc_cb; \ + uv_udp_recv_cb recv_cb; \ + uv__io_t read_watcher; \ + uv__io_t write_watcher; \ + ngx_queue_t write_queue; \ + ngx_queue_t write_completed_queue; \ + + +/* UV_NAMED_PIPE */ +#define UV_PIPE_PRIVATE_FIELDS \ + const char* pipe_fname; /* strdup'ed */ + + +/* UV_POLL */ +#define UV_POLL_PRIVATE_FIELDS \ + int fd; \ + uv__io_t io_watcher; + + +/* UV_PREPARE */ +#define UV_PREPARE_PRIVATE_FIELDS \ + uv_prepare_cb prepare_cb; \ + ngx_queue_t queue; + + +/* UV_CHECK */ +#define UV_CHECK_PRIVATE_FIELDS \ + uv_check_cb check_cb; \ + ngx_queue_t queue; + + +/* UV_IDLE */ +#define UV_IDLE_PRIVATE_FIELDS \ + uv_idle_cb idle_cb; \ + ngx_queue_t queue; + + +/* UV_ASYNC */ +#define UV_ASYNC_PRIVATE_FIELDS \ + volatile sig_atomic_t pending; \ + uv_async_cb async_cb; \ + ngx_queue_t queue; + + +/* UV_TIMER */ +#define UV_TIMER_PRIVATE_FIELDS \ + /* RB_ENTRY(uv_timer_s) node; */ \ + struct { \ + struct uv_timer_s* rbe_left; \ + struct uv_timer_s* rbe_right; \ + struct uv_timer_s* rbe_parent; \ + int rbe_color; \ + } tree_entry; \ + uv_timer_cb timer_cb; \ + uint64_t timeout; \ + uint64_t repeat; + +#define UV_GETADDRINFO_PRIVATE_FIELDS \ + uv_getaddrinfo_cb cb; \ + struct addrinfo* hints; \ + char* hostname; \ + char* service; \ + struct addrinfo* res; \ + int retcode; + +#define UV_PROCESS_PRIVATE_FIELDS \ + ev_child child_watcher; + +#define UV_FS_PRIVATE_FIELDS \ + struct stat statbuf; \ + eio_req* eio; + +#define UV_WORK_PRIVATE_FIELDS \ + eio_req* eio; + +#define UV_TTY_PRIVATE_FIELDS \ + struct termios orig_termios; \ + int mode; + +/* UV_FS_EVENT_PRIVATE_FIELDS */ +#if defined(__linux__) + +#define UV_FS_EVENT_PRIVATE_FIELDS \ + ngx_queue_t watchers; \ + uv_fs_event_cb cb; \ + int wd; \ + void* pad0; \ + void* pad1; \ + +#elif defined(__APPLE__) \ + || defined(__FreeBSD__) \ + || defined(__DragonFly__) \ + || defined(__OpenBSD__) \ + || defined(__NetBSD__) + +#define UV_FS_EVENT_PRIVATE_FIELDS \ + ev_io event_watcher; \ + uv_fs_event_cb cb; \ + int fflags; \ + int fd; + +#elif defined(__sun) + +#ifdef PORT_SOURCE_FILE +# define UV_FS_EVENT_PRIVATE_FIELDS \ + ev_io event_watcher; \ + uv_fs_event_cb cb; \ + file_obj_t fo; \ + int fd; +#else /* !PORT_SOURCE_FILE */ +# define UV_FS_EVENT_PRIVATE_FIELDS +#endif + +#else + +/* Stub for platforms where the file watcher isn't implemented yet. */ +#define UV_FS_EVENT_PRIVATE_FIELDS + +#endif + +#endif /* UV_UNIX_H */ diff --git a/node-v0.8.14/deps/uv/include/uv-private/uv-win.h b/node-v0.8.14/deps/uv/include/uv-private/uv-win.h new file mode 100644 index 0000000..5b0aba6 --- /dev/null +++ b/node-v0.8.14/deps/uv/include/uv-private/uv-win.h @@ -0,0 +1,517 @@ +/* Copyright Joyent, Inc. and other Node contributors. All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ + +#ifndef _WIN32_WINNT +# define _WIN32_WINNT 0x0502 +#endif + +#if !defined(_SSIZE_T_) && !defined(_SSIZE_T_DEFINED) +typedef intptr_t ssize_t; +# define _SSIZE_T_ +# define _SSIZE_T_DEFINED +#endif + +#include +#include +#include +#include +#include +#include +#include + +#include "tree.h" +#include "ngx-queue.h" + +#define MAX_PIPENAME_LEN 256 + +#ifndef S_IFLNK +# define S_IFLNK 0xA000 +#endif + +/* + * Guids and typedefs for winsock extension functions + * Mingw32 doesn't have these :-( + */ +#ifndef WSAID_ACCEPTEX +# define WSAID_ACCEPTEX \ + {0xb5367df1, 0xcbac, 0x11cf, \ + {0x95, 0xca, 0x00, 0x80, 0x5f, 0x48, 0xa1, 0x92}} + +# define WSAID_CONNECTEX \ + {0x25a207b9, 0xddf3, 0x4660, \ + {0x8e, 0xe9, 0x76, 0xe5, 0x8c, 0x74, 0x06, 0x3e}} + +# define WSAID_GETACCEPTEXSOCKADDRS \ + {0xb5367df2, 0xcbac, 0x11cf, \ + {0x95, 0xca, 0x00, 0x80, 0x5f, 0x48, 0xa1, 0x92}} + +# define WSAID_DISCONNECTEX \ + {0x7fda2e11, 0x8630, 0x436f, \ + {0xa0, 0x31, 0xf5, 0x36, 0xa6, 0xee, 0xc1, 0x57}} + +# define WSAID_TRANSMITFILE \ + {0xb5367df0, 0xcbac, 0x11cf, \ + {0x95, 0xca, 0x00, 0x80, 0x5f, 0x48, 0xa1, 0x92}} + + typedef BOOL PASCAL (*LPFN_ACCEPTEX) + (SOCKET sListenSocket, + SOCKET sAcceptSocket, + PVOID lpOutputBuffer, + DWORD dwReceiveDataLength, + DWORD dwLocalAddressLength, + DWORD dwRemoteAddressLength, + LPDWORD lpdwBytesReceived, + LPOVERLAPPED lpOverlapped); + + typedef BOOL PASCAL (*LPFN_CONNECTEX) + (SOCKET s, + const struct sockaddr* name, + int namelen, + PVOID lpSendBuffer, + DWORD dwSendDataLength, + LPDWORD lpdwBytesSent, + LPOVERLAPPED lpOverlapped); + + typedef void PASCAL (*LPFN_GETACCEPTEXSOCKADDRS) + (PVOID lpOutputBuffer, + DWORD dwReceiveDataLength, + DWORD dwLocalAddressLength, + DWORD dwRemoteAddressLength, + LPSOCKADDR* LocalSockaddr, + LPINT LocalSockaddrLength, + LPSOCKADDR* RemoteSockaddr, + LPINT RemoteSockaddrLength); + + typedef BOOL PASCAL (*LPFN_DISCONNECTEX) + (SOCKET hSocket, + LPOVERLAPPED lpOverlapped, + DWORD dwFlags, + DWORD reserved); + + typedef BOOL PASCAL (*LPFN_TRANSMITFILE) + (SOCKET hSocket, + HANDLE hFile, + DWORD nNumberOfBytesToWrite, + DWORD nNumberOfBytesPerSend, + LPOVERLAPPED lpOverlapped, + LPTRANSMIT_FILE_BUFFERS lpTransmitBuffers, + DWORD dwFlags); + + typedef PVOID RTL_SRWLOCK; + typedef RTL_SRWLOCK SRWLOCK, *PSRWLOCK; +#endif + +typedef int (WSAAPI* LPFN_WSARECV) + (SOCKET socket, + LPWSABUF buffers, + DWORD buffer_count, + LPDWORD bytes, + LPDWORD flags, + LPWSAOVERLAPPED overlapped, + LPWSAOVERLAPPED_COMPLETION_ROUTINE completion_routine); + +typedef int (WSAAPI* LPFN_WSARECVFROM) + (SOCKET socket, + LPWSABUF buffers, + DWORD buffer_count, + LPDWORD bytes, + LPDWORD flags, + struct sockaddr* addr, + LPINT addr_len, + LPWSAOVERLAPPED overlapped, + LPWSAOVERLAPPED_COMPLETION_ROUTINE completion_routine); + +#ifndef _NTDEF_ + typedef LONG NTSTATUS; + typedef NTSTATUS *PNTSTATUS; +#endif + +typedef struct _AFD_POLL_HANDLE_INFO { + HANDLE Handle; + ULONG Events; + NTSTATUS Status; +} AFD_POLL_HANDLE_INFO, *PAFD_POLL_HANDLE_INFO; + +typedef struct _AFD_POLL_INFO { + LARGE_INTEGER Timeout; + ULONG NumberOfHandles; + ULONG Exclusive; + AFD_POLL_HANDLE_INFO Handles[1]; +} AFD_POLL_INFO, *PAFD_POLL_INFO; + +#define UV_MSAFD_PROVIDER_COUNT 3 + + +/** + * It should be possible to cast uv_buf_t[] to WSABUF[] + * see http://msdn.microsoft.com/en-us/library/ms741542(v=vs.85).aspx + */ +typedef struct uv_buf_t { + ULONG len; + char* base; +} uv_buf_t; + +typedef int uv_file; + +typedef struct _stati64 uv_statbuf_t; + +typedef SOCKET uv_os_sock_t; + +typedef HANDLE uv_thread_t; + +typedef HANDLE uv_sem_t; + +typedef CRITICAL_SECTION uv_mutex_t; + +typedef union { + /* srwlock_ has type SRWLOCK, but not all toolchains define this type in */ + /* windows.h. */ + SRWLOCK srwlock_; + struct { + uv_mutex_t read_mutex_; + uv_mutex_t write_mutex_; + unsigned int num_readers_; + } fallback_; +} uv_rwlock_t; + +#define UV_ONCE_INIT { 0, NULL, NULL } + +typedef struct uv_once_s { + unsigned char ran; + /* The actual event handle must be aligned to sizeof(HANDLE), so in */ + /* practice it might overlap padding a little. */ + HANDLE event; + HANDLE padding; +} uv_once_t; + +/* Platform-specific definitions for uv_spawn support. */ +typedef unsigned char uv_uid_t; +typedef unsigned char uv_gid_t; + +/* Platform-specific definitions for uv_dlopen support. */ +#define UV_DYNAMIC FAR WINAPI +typedef struct { + HMODULE handle; + char* errmsg; +} uv_lib_t; + +RB_HEAD(uv_timer_tree_s, uv_timer_s); + +#define UV_LOOP_PRIVATE_FIELDS \ + /* The loop's I/O completion port */ \ + HANDLE iocp; \ + /* The current time according to the event loop. in msecs. */ \ + int64_t time; \ + /* Tail of a single-linked circular queue of pending reqs. If the queue */ \ + /* is empty, tail_ is NULL. If there is only one item, */ \ + /* tail_->next_req == tail_ */ \ + uv_req_t* pending_reqs_tail; \ + /* Head of a single-linked list of closed handles */ \ + uv_handle_t* endgame_handles; \ + /* The head of the timers tree */ \ + struct uv_timer_tree_s timers; \ + /* Lists of active loop (prepare / check / idle) watchers */ \ + uv_prepare_t* prepare_handles; \ + uv_check_t* check_handles; \ + uv_idle_t* idle_handles; \ + /* This pointer will refer to the prepare/check/idle handle whose */ \ + /* callback is scheduled to be called next. This is needed to allow */ \ + /* safe removal from one of the lists above while that list being */ \ + /* iterated over. */ \ + uv_prepare_t* next_prepare_handle; \ + uv_check_t* next_check_handle; \ + uv_idle_t* next_idle_handle; \ + /* This handle holds the peer sockets for the fast variant of uv_poll_t */ \ + SOCKET poll_peer_sockets[UV_MSAFD_PROVIDER_COUNT]; \ + /* Counter to keep track of active tcp streams */ \ + unsigned int active_tcp_streams; \ + /* Counter to keep track of active udp streams */ \ + unsigned int active_udp_streams; + +#define UV_REQ_TYPE_PRIVATE \ + /* TODO: remove the req suffix */ \ + UV_ACCEPT, \ + UV_FS_EVENT_REQ, \ + UV_POLL_REQ, \ + UV_PROCESS_EXIT, \ + UV_PROCESS_CLOSE, \ + UV_READ, \ + UV_UDP_RECV, \ + UV_WAKEUP, + +#define UV_REQ_PRIVATE_FIELDS \ + union { \ + /* Used by I/O operations */ \ + struct { \ + OVERLAPPED overlapped; \ + size_t queued_bytes; \ + }; \ + }; \ + struct uv_req_s* next_req; + +#define UV_WRITE_PRIVATE_FIELDS \ + int ipc_header; \ + uv_buf_t write_buffer; \ + HANDLE event_handle; \ + HANDLE wait_handle; + +#define UV_CONNECT_PRIVATE_FIELDS \ + /* empty */ + +#define UV_SHUTDOWN_PRIVATE_FIELDS \ + /* empty */ + +#define UV_UDP_SEND_PRIVATE_FIELDS \ + /* empty */ + +#define UV_PRIVATE_REQ_TYPES \ + typedef struct uv_pipe_accept_s { \ + UV_REQ_FIELDS \ + HANDLE pipeHandle; \ + struct uv_pipe_accept_s* next_pending; \ + } uv_pipe_accept_t; \ + \ + typedef struct uv_tcp_accept_s { \ + UV_REQ_FIELDS \ + SOCKET accept_socket; \ + char accept_buffer[sizeof(struct sockaddr_storage) * 2 + 32]; \ + HANDLE event_handle; \ + HANDLE wait_handle; \ + struct uv_tcp_accept_s* next_pending; \ + } uv_tcp_accept_t; \ + \ + typedef struct uv_read_s { \ + UV_REQ_FIELDS \ + HANDLE event_handle; \ + HANDLE wait_handle; \ + } uv_read_t; + +#define uv_stream_connection_fields \ + unsigned int write_reqs_pending; \ + uv_shutdown_t* shutdown_req; + +#define uv_stream_server_fields \ + uv_connection_cb connection_cb; + +#define UV_STREAM_PRIVATE_FIELDS \ + unsigned int reqs_pending; \ + int activecnt; \ + uv_read_t read_req; \ + union { \ + struct { uv_stream_connection_fields }; \ + struct { uv_stream_server_fields }; \ + }; + +#define uv_tcp_server_fields \ + uv_tcp_accept_t* accept_reqs; \ + unsigned int processed_accepts; \ + uv_tcp_accept_t* pending_accepts; \ + LPFN_ACCEPTEX func_acceptex; + +#define uv_tcp_connection_fields \ + uv_buf_t read_buffer; \ + LPFN_CONNECTEX func_connectex; + +#define UV_TCP_PRIVATE_FIELDS \ + SOCKET socket; \ + int bind_error; \ + union { \ + struct { uv_tcp_server_fields }; \ + struct { uv_tcp_connection_fields }; \ + }; + +#define UV_UDP_PRIVATE_FIELDS \ + SOCKET socket; \ + unsigned int reqs_pending; \ + int activecnt; \ + uv_req_t recv_req; \ + uv_buf_t recv_buffer; \ + struct sockaddr_storage recv_from; \ + int recv_from_len; \ + uv_udp_recv_cb recv_cb; \ + uv_alloc_cb alloc_cb; \ + LPFN_WSARECV func_wsarecv; \ + LPFN_WSARECVFROM func_wsarecvfrom; + +#define uv_pipe_server_fields \ + int pending_instances; \ + uv_pipe_accept_t* accept_reqs; \ + uv_pipe_accept_t* pending_accepts; + +#define uv_pipe_connection_fields \ + uv_timer_t* eof_timer; \ + uv_write_t ipc_header_write_req; \ + int ipc_pid; \ + uint64_t remaining_ipc_rawdata_bytes; \ + unsigned char reserved[sizeof(void*)]; \ + struct { \ + WSAPROTOCOL_INFOW* socket_info; \ + int tcp_connection; \ + } pending_ipc_info; \ + uv_write_t* non_overlapped_writes_tail; + +#define UV_PIPE_PRIVATE_FIELDS \ + HANDLE handle; \ + wchar_t* name; \ + union { \ + struct { uv_pipe_server_fields }; \ + struct { uv_pipe_connection_fields }; \ + }; + +/* TODO: put the parser states in an union - TTY handles are always */ +/* half-duplex so read-state can safely overlap write-state. */ +#define UV_TTY_PRIVATE_FIELDS \ + HANDLE handle; \ + HANDLE read_line_handle; \ + uv_buf_t read_line_buffer; \ + HANDLE read_raw_wait; \ + DWORD original_console_mode; \ + /* Fields used for translating win */ \ + /* keystrokes into vt100 characters */ \ + char last_key[8]; \ + unsigned char last_key_offset; \ + unsigned char last_key_len; \ + INPUT_RECORD last_input_record; \ + WCHAR last_utf16_high_surrogate; \ + /* utf8-to-utf16 conversion state */ \ + unsigned char utf8_bytes_left; \ + unsigned int utf8_codepoint; \ + /* eol conversion state */ \ + unsigned char previous_eol; \ + /* ansi parser state */ \ + unsigned char ansi_parser_state; \ + unsigned char ansi_csi_argc; \ + unsigned short ansi_csi_argv[4]; \ + COORD saved_position; \ + WORD saved_attributes; + +#define UV_POLL_PRIVATE_FIELDS \ + SOCKET socket; \ + /* Used in fast mode */ \ + SOCKET peer_socket; \ + AFD_POLL_INFO afd_poll_info_1; \ + AFD_POLL_INFO afd_poll_info_2; \ + /* Used in fast and slow mode. */ \ + uv_req_t poll_req_1; \ + uv_req_t poll_req_2; \ + unsigned char submitted_events_1; \ + unsigned char submitted_events_2; \ + unsigned char mask_events_1; \ + unsigned char mask_events_2; \ + unsigned char events; + +#define UV_TIMER_PRIVATE_FIELDS \ + RB_ENTRY(uv_timer_s) tree_entry; \ + int64_t due; \ + int64_t repeat; \ + uv_timer_cb timer_cb; + +#define UV_ASYNC_PRIVATE_FIELDS \ + struct uv_req_s async_req; \ + uv_async_cb async_cb; \ + /* char to avoid alignment issues */ \ + char volatile async_sent; + +#define UV_PREPARE_PRIVATE_FIELDS \ + uv_prepare_t* prepare_prev; \ + uv_prepare_t* prepare_next; \ + uv_prepare_cb prepare_cb; + +#define UV_CHECK_PRIVATE_FIELDS \ + uv_check_t* check_prev; \ + uv_check_t* check_next; \ + uv_check_cb check_cb; + +#define UV_IDLE_PRIVATE_FIELDS \ + uv_idle_t* idle_prev; \ + uv_idle_t* idle_next; \ + uv_idle_cb idle_cb; + +#define UV_HANDLE_PRIVATE_FIELDS \ + uv_handle_t* endgame_next; \ + unsigned int flags; + +#define UV_GETADDRINFO_PRIVATE_FIELDS \ + uv_getaddrinfo_cb getaddrinfo_cb; \ + void* alloc; \ + wchar_t* node; \ + wchar_t* service; \ + struct addrinfoW* hints; \ + struct addrinfoW* res; \ + int retcode; + +#define UV_PROCESS_PRIVATE_FIELDS \ + struct uv_process_exit_s { \ + UV_REQ_FIELDS \ + } exit_req; \ + struct uv_process_close_s { \ + UV_REQ_FIELDS \ + } close_req; \ + BYTE* child_stdio_buffer; \ + int exit_signal; \ + DWORD spawn_errno; \ + HANDLE wait_handle; \ + HANDLE process_handle; \ + HANDLE close_handle; + +#define UV_FS_PRIVATE_FIELDS \ + int flags; \ + DWORD sys_errno_; \ + union { \ + /* TODO: remove me in 0.9. */ \ + WCHAR* pathw; \ + int fd; \ + }; \ + union { \ + struct { \ + int mode; \ + WCHAR* new_pathw; \ + int file_flags; \ + int fd_out; \ + void* buf; \ + size_t length; \ + int64_t offset; \ + }; \ + struct _stati64 stat; \ + struct { \ + double atime; \ + double mtime; \ + }; \ + }; + +#define UV_WORK_PRIVATE_FIELDS \ + +#define UV_FS_EVENT_PRIVATE_FIELDS \ + struct uv_fs_event_req_s { \ + UV_REQ_FIELDS \ + } req; \ + HANDLE dir_handle; \ + int req_pending; \ + uv_fs_event_cb cb; \ + wchar_t* filew; \ + wchar_t* short_filew; \ + wchar_t* dirw; \ + char* buffer; + +int uv_utf16_to_utf8(const wchar_t* utf16Buffer, size_t utf16Size, + char* utf8Buffer, size_t utf8Size); +int uv_utf8_to_utf16(const char* utf8Buffer, wchar_t* utf16Buffer, + size_t utf16Size); diff --git a/node-v0.8.14/deps/uv/include/uv.h b/node-v0.8.14/deps/uv/include/uv.h new file mode 100644 index 0000000..49160b2 --- /dev/null +++ b/node-v0.8.14/deps/uv/include/uv.h @@ -0,0 +1,1808 @@ +/* Copyright Joyent, Inc. and other Node contributors. All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ + +/* See uv_loop_new for an introduction. */ + +#ifndef UV_H +#define UV_H +#ifdef __cplusplus +extern "C" { +#endif + +#ifdef _WIN32 + /* Windows - set up dll import/export decorators. */ +# if defined(BUILDING_UV_SHARED) + /* Building shared library. Export everything from c-ares as well. */ +# define UV_EXTERN __declspec(dllexport) +# define CARES_BUILDING_LIBRARY 1 +# elif defined(USING_UV_SHARED) + /* Using shared library. Use shared c-ares as well. */ +# define UV_EXTERN __declspec(dllimport) +# else + /* Building static library. Build c-ares statically as well. */ +# define UV_EXTERN /* nothing */ +# define CARES_STATICLIB 1 +# endif +#elif __GNUC__ >= 4 +# define UV_EXTERN __attribute__((visibility("default"))) +#else +# define UV_EXTERN /* nothing */ +#endif + + +#define UV_VERSION_MAJOR 0 +#define UV_VERSION_MINOR 8 + + +#include /* int64_t */ +#include /* size_t */ + +#include "ares.h" + +#if defined(__unix__) || defined(__POSIX__) || defined(__APPLE__) +# include "uv-private/uv-unix.h" +#else +# include "uv-private/uv-win.h" +#endif + +/* Expand this list if necessary. */ +#define UV_ERRNO_MAP(XX) \ + XX( -1, UNKNOWN, "unknown error") \ + XX( 0, OK, "success") \ + XX( 1, EOF, "end of file") \ + XX( 2, EADDRINFO, "getaddrinfo error") \ + XX( 3, EACCES, "permission denied") \ + XX( 4, EAGAIN, "no more processes") \ + XX( 5, EADDRINUSE, "address already in use") \ + XX( 6, EADDRNOTAVAIL, "") \ + XX( 7, EAFNOSUPPORT, "") \ + XX( 8, EALREADY, "") \ + XX( 9, EBADF, "bad file descriptor") \ + XX( 10, EBUSY, "resource busy or locked") \ + XX( 11, ECONNABORTED, "software caused connection abort") \ + XX( 12, ECONNREFUSED, "connection refused") \ + XX( 13, ECONNRESET, "connection reset by peer") \ + XX( 14, EDESTADDRREQ, "destination address required") \ + XX( 15, EFAULT, "bad address in system call argument") \ + XX( 16, EHOSTUNREACH, "host is unreachable") \ + XX( 17, EINTR, "interrupted system call") \ + XX( 18, EINVAL, "invalid argument") \ + XX( 19, EISCONN, "socket is already connected") \ + XX( 20, EMFILE, "too many open files") \ + XX( 21, EMSGSIZE, "message too long") \ + XX( 22, ENETDOWN, "network is down") \ + XX( 23, ENETUNREACH, "network is unreachable") \ + XX( 24, ENFILE, "file table overflow") \ + XX( 25, ENOBUFS, "no buffer space available") \ + XX( 26, ENOMEM, "not enough memory") \ + XX( 27, ENOTDIR, "not a directory") \ + XX( 28, EISDIR, "illegal operation on a directory") \ + XX( 29, ENONET, "machine is not on the network") \ + XX( 31, ENOTCONN, "socket is not connected") \ + XX( 32, ENOTSOCK, "socket operation on non-socket") \ + XX( 33, ENOTSUP, "operation not supported on socket") \ + XX( 34, ENOENT, "no such file or directory") \ + XX( 35, ENOSYS, "function not implemented") \ + XX( 36, EPIPE, "broken pipe") \ + XX( 37, EPROTO, "protocol error") \ + XX( 38, EPROTONOSUPPORT, "protocol not supported") \ + XX( 39, EPROTOTYPE, "protocol wrong type for socket") \ + XX( 40, ETIMEDOUT, "connection timed out") \ + XX( 41, ECHARSET, "") \ + XX( 42, EAIFAMNOSUPPORT, "") \ + XX( 44, EAISERVICE, "") \ + XX( 45, EAISOCKTYPE, "") \ + XX( 46, ESHUTDOWN, "") \ + XX( 47, EEXIST, "file already exists") \ + XX( 48, ESRCH, "no such process") \ + XX( 49, ENAMETOOLONG, "name too long") \ + XX( 50, EPERM, "operation not permitted") \ + XX( 51, ELOOP, "too many symbolic links encountered") \ + XX( 52, EXDEV, "cross-device link not permitted") \ + XX( 53, ENOTEMPTY, "directory not empty") \ + XX( 54, ENOSPC, "no space left on device") \ + XX( 55, EIO, "i/o error") \ + XX( 56, EROFS, "read-only file system") \ + XX( 57, ENODEV, "no such device") \ + XX( 58, ESPIPE, "invalid seek") \ + + +#define UV_ERRNO_GEN(val, name, s) UV_##name = val, +typedef enum { + UV_ERRNO_MAP(UV_ERRNO_GEN) + UV_MAX_ERRORS +} uv_err_code; +#undef UV_ERRNO_GEN + +#define UV_HANDLE_TYPE_MAP(XX) \ + XX(ASYNC, async) \ + XX(CHECK, check) \ + XX(FS_EVENT, fs_event) \ + XX(FS_POLL, fs_poll) \ + XX(IDLE, idle) \ + XX(NAMED_PIPE, pipe) \ + XX(POLL, poll) \ + XX(PREPARE, prepare) \ + XX(PROCESS, process) \ + XX(TCP, tcp) \ + XX(TIMER, timer) \ + XX(TTY, tty) \ + XX(UDP, udp) \ + +#define UV_REQ_TYPE_MAP(XX) \ + XX(CONNECT, connect) \ + XX(WRITE, write) \ + XX(SHUTDOWN, shutdown) \ + XX(UDP_SEND, udp_send) \ + XX(FS, fs) \ + XX(WORK, work) \ + XX(GETADDRINFO, getaddrinfo) \ + +typedef enum { + UV_UNKNOWN_HANDLE = 0, +#define XX(uc, lc) UV_##uc, + UV_HANDLE_TYPE_MAP(XX) +#undef XX + UV_ARES_TASK, + UV_FILE, + UV_HANDLE_TYPE_MAX +} uv_handle_type; + +typedef enum { + UV_UNKNOWN_REQ = 0, +#define XX(uc, lc) UV_##uc, + UV_REQ_TYPE_MAP(XX) +#undef XX + UV_REQ_TYPE_PRIVATE + UV_REQ_TYPE_MAX +} uv_req_type; + + + +typedef struct uv_loop_s uv_loop_t; +typedef struct uv_ares_task_s uv_ares_task_t; +typedef struct uv_err_s uv_err_t; +typedef struct uv_handle_s uv_handle_t; +typedef struct uv_stream_s uv_stream_t; +typedef struct uv_tcp_s uv_tcp_t; +typedef struct uv_udp_s uv_udp_t; +typedef struct uv_pipe_s uv_pipe_t; +typedef struct uv_tty_s uv_tty_t; +typedef struct uv_poll_s uv_poll_t; +typedef struct uv_timer_s uv_timer_t; +typedef struct uv_prepare_s uv_prepare_t; +typedef struct uv_check_s uv_check_t; +typedef struct uv_idle_s uv_idle_t; +typedef struct uv_async_s uv_async_t; +typedef struct uv_getaddrinfo_s uv_getaddrinfo_t; +typedef struct uv_process_s uv_process_t; +typedef struct uv_counters_s uv_counters_t; +typedef struct uv_cpu_info_s uv_cpu_info_t; +typedef struct uv_interface_address_s uv_interface_address_t; +/* Request types */ +typedef struct uv_req_s uv_req_t; +typedef struct uv_shutdown_s uv_shutdown_t; +typedef struct uv_write_s uv_write_t; +typedef struct uv_connect_s uv_connect_t; +typedef struct uv_udp_send_s uv_udp_send_t; +typedef struct uv_fs_s uv_fs_t; +/* uv_fs_event_t is a subclass of uv_handle_t. */ +typedef struct uv_fs_event_s uv_fs_event_t; +typedef struct uv_fs_poll_s uv_fs_poll_t; +typedef struct uv_work_s uv_work_t; + + +/* + * This function must be called before any other functions in libuv. + * + * All functions besides uv_run() are non-blocking. + * + * All callbacks in libuv are made asynchronously. That is they are never + * made by the function that takes them as a parameter. + */ +UV_EXTERN uv_loop_t* uv_loop_new(void); +UV_EXTERN void uv_loop_delete(uv_loop_t*); + +/* + * Returns the default loop. + */ +UV_EXTERN uv_loop_t* uv_default_loop(void); + +/* + * This function starts the event loop. It blocks until the reference count + * of the loop drops to zero. Always returns zero. + */ +UV_EXTERN int uv_run(uv_loop_t*); + +/* + * Poll for new events once. Note that this function blocks if there are no + * pending events. Returns zero when done (no active handles or requests left), + * or non-zero if more events are expected (meaning you should call + * uv_run_once() again sometime in the future). + */ +UV_EXTERN int uv_run_once(uv_loop_t*); + +/* + * Manually modify the event loop's reference count. Useful if the user wants + * to have a handle or timeout that doesn't keep the loop alive. + */ +UV_EXTERN void uv_ref(uv_handle_t*); +UV_EXTERN void uv_unref(uv_handle_t*); + +UV_EXTERN void uv_update_time(uv_loop_t*); +UV_EXTERN int64_t uv_now(uv_loop_t*); + + +/* + * Should return a buffer that libuv can use to read data into. + * + * `suggested_size` is a hint. Returning a buffer that is smaller is perfectly + * okay as long as `buf.len > 0`. + */ +typedef uv_buf_t (*uv_alloc_cb)(uv_handle_t* handle, size_t suggested_size); + +/* + * `nread` is > 0 if there is data available, 0 if libuv is done reading for now + * or -1 on error. + * + * Error details can be obtained by calling uv_last_error(). UV_EOF indicates + * that the stream has been closed. + * + * The callee is responsible for closing the stream when an error happens. + * Trying to read from the stream again is undefined. + * + * The callee is responsible for freeing the buffer, libuv does not reuse it. + */ +typedef void (*uv_read_cb)(uv_stream_t* stream, ssize_t nread, uv_buf_t buf); + +/* + * Just like the uv_read_cb except that if the pending parameter is true + * then you can use uv_accept() to pull the new handle into the process. + * If no handle is pending then pending will be UV_UNKNOWN_HANDLE. + */ +typedef void (*uv_read2_cb)(uv_pipe_t* pipe, ssize_t nread, uv_buf_t buf, + uv_handle_type pending); + +typedef void (*uv_write_cb)(uv_write_t* req, int status); +typedef void (*uv_connect_cb)(uv_connect_t* req, int status); +typedef void (*uv_shutdown_cb)(uv_shutdown_t* req, int status); +typedef void (*uv_connection_cb)(uv_stream_t* server, int status); +typedef void (*uv_close_cb)(uv_handle_t* handle); +typedef void (*uv_poll_cb)(uv_poll_t* handle, int status, int events); +typedef void (*uv_timer_cb)(uv_timer_t* handle, int status); +/* TODO: do these really need a status argument? */ +typedef void (*uv_async_cb)(uv_async_t* handle, int status); +typedef void (*uv_prepare_cb)(uv_prepare_t* handle, int status); +typedef void (*uv_check_cb)(uv_check_t* handle, int status); +typedef void (*uv_idle_cb)(uv_idle_t* handle, int status); +typedef void (*uv_getaddrinfo_cb)(uv_getaddrinfo_t* handle, int status, + struct addrinfo* res); +typedef void (*uv_exit_cb)(uv_process_t*, int exit_status, int term_signal); +typedef void (*uv_fs_cb)(uv_fs_t* req); +typedef void (*uv_work_cb)(uv_work_t* req); +typedef void (*uv_after_work_cb)(uv_work_t* req); +typedef void (*uv_walk_cb)(uv_handle_t* handle, void* arg); + +/* +* This will be called repeatedly after the uv_fs_event_t is initialized. +* If uv_fs_event_t was initialized with a directory the filename parameter +* will be a relative path to a file contained in the directory. +* The events parameter is an ORed mask of enum uv_fs_event elements. +*/ +typedef void (*uv_fs_event_cb)(uv_fs_event_t* handle, const char* filename, + int events, int status); + +typedef void (*uv_fs_poll_cb)(uv_fs_poll_t* handle, + int status, + const uv_statbuf_t* prev, + const uv_statbuf_t* curr); + +typedef enum { + UV_LEAVE_GROUP = 0, + UV_JOIN_GROUP +} uv_membership; + + +struct uv_err_s { + /* read-only */ + uv_err_code code; + /* private */ + int sys_errno_; +}; + + +/* + * Most functions return boolean: 0 for success and -1 for failure. + * On error the user should then call uv_last_error() to determine + * the error code. + */ +UV_EXTERN uv_err_t uv_last_error(uv_loop_t*); +UV_EXTERN const char* uv_strerror(uv_err_t err); +UV_EXTERN const char* uv_err_name(uv_err_t err); + + +#define UV_REQ_FIELDS \ + /* public */ \ + void* data; \ + /* private */ \ + ngx_queue_t active_queue; \ + UV_REQ_PRIVATE_FIELDS \ + /* read-only */ \ + uv_req_type type; \ + +/* Abstract base class of all requests. */ +struct uv_req_s { + UV_REQ_FIELDS +}; + + +/* Platform-specific request types */ +UV_PRIVATE_REQ_TYPES + + +/* + * uv_shutdown_t is a subclass of uv_req_t + * + * Shutdown the outgoing (write) side of a duplex stream. It waits for + * pending write requests to complete. The handle should refer to a + * initialized stream. req should be an uninitialized shutdown request + * struct. The cb is called after shutdown is complete. + */ +UV_EXTERN int uv_shutdown(uv_shutdown_t* req, uv_stream_t* handle, + uv_shutdown_cb cb); + +struct uv_shutdown_s { + UV_REQ_FIELDS + uv_stream_t* handle; + uv_shutdown_cb cb; + UV_SHUTDOWN_PRIVATE_FIELDS +}; + + +#define UV_HANDLE_FIELDS \ + /* read-only */ \ + uv_loop_t* loop; \ + /* public */ \ + uv_close_cb close_cb; \ + void* data; \ + /* read-only */ \ + uv_handle_type type; \ + /* private */ \ + ngx_queue_t handle_queue; \ + UV_HANDLE_PRIVATE_FIELDS \ + +/* The abstract base class of all handles. */ +struct uv_handle_s { + UV_HANDLE_FIELDS +}; + +/* + * Returns size of various handle types, useful for FFI + * bindings to allocate correct memory without copying struct + * definitions + */ +UV_EXTERN size_t uv_handle_size(uv_handle_type type); + +/* + * Returns size of request types, useful for dynamic lookup with FFI + */ +UV_EXTERN size_t uv_req_size(uv_req_type type); + +/* + * Returns 1 if the prepare/check/idle/timer handle has been started, 0 + * otherwise. For other handle types this always returns 1. + */ +UV_EXTERN int uv_is_active(const uv_handle_t* handle); + +/* + * Walk the list of open handles. + */ +UV_EXTERN void uv_walk(uv_loop_t* loop, uv_walk_cb walk_cb, void* arg); + + +/* + * Request handle to be closed. close_cb will be called asynchronously after + * this call. This MUST be called on each handle before memory is released. + * + * Note that handles that wrap file descriptors are closed immediately but + * close_cb will still be deferred to the next iteration of the event loop. + * It gives you a chance to free up any resources associated with the handle. + */ +UV_EXTERN void uv_close(uv_handle_t* handle, uv_close_cb close_cb); + + +/* + * Constructor for uv_buf_t. + * Due to platform differences the user cannot rely on the ordering of the + * base and len members of the uv_buf_t struct. The user is responsible for + * freeing base after the uv_buf_t is done. Return struct passed by value. + */ +UV_EXTERN uv_buf_t uv_buf_init(char* base, unsigned int len); + + +/* + * Utility function. Copies up to `size` characters from `src` to `dst` + * and ensures that `dst` is properly NUL terminated unless `size` is zero. + */ +UV_EXTERN size_t uv_strlcpy(char* dst, const char* src, size_t size); + +/* + * Utility function. Appends `src` to `dst` and ensures that `dst` is + * properly NUL terminated unless `size` is zero or `dst` does not + * contain a NUL byte. `size` is the total length of `dst` so at most + * `size - strlen(dst) - 1` characters will be copied from `src`. + */ +UV_EXTERN size_t uv_strlcat(char* dst, const char* src, size_t size); + + +#define UV_STREAM_FIELDS \ + /* number of bytes queued for writing */ \ + size_t write_queue_size; \ + uv_alloc_cb alloc_cb; \ + uv_read_cb read_cb; \ + uv_read2_cb read2_cb; \ + /* private */ \ + UV_STREAM_PRIVATE_FIELDS + +/* + * uv_stream_t is a subclass of uv_handle_t + * + * uv_stream is an abstract class. + * + * uv_stream_t is the parent class of uv_tcp_t, uv_pipe_t, uv_tty_t, and + * soon uv_file_t. + */ +struct uv_stream_s { + UV_HANDLE_FIELDS + UV_STREAM_FIELDS +}; + +UV_EXTERN int uv_listen(uv_stream_t* stream, int backlog, uv_connection_cb cb); + +/* + * This call is used in conjunction with uv_listen() to accept incoming + * connections. Call uv_accept after receiving a uv_connection_cb to accept + * the connection. Before calling uv_accept use uv_*_init() must be + * called on the client. Non-zero return value indicates an error. + * + * When the uv_connection_cb is called it is guaranteed that uv_accept will + * complete successfully the first time. If you attempt to use it more than + * once, it may fail. It is suggested to only call uv_accept once per + * uv_connection_cb call. + */ +UV_EXTERN int uv_accept(uv_stream_t* server, uv_stream_t* client); + +/* + * Read data from an incoming stream. The callback will be made several + * several times until there is no more data to read or uv_read_stop is + * called. When we've reached EOF nread will be set to -1 and the error is + * set to UV_EOF. When nread == -1 the buf parameter might not point to a + * valid buffer; in that case buf.len and buf.base are both set to 0. + * Note that nread might also be 0, which does *not* indicate an error or + * eof; it happens when libuv requested a buffer through the alloc callback + * but then decided that it didn't need that buffer. + */ +UV_EXTERN int uv_read_start(uv_stream_t*, uv_alloc_cb alloc_cb, + uv_read_cb read_cb); + +UV_EXTERN int uv_read_stop(uv_stream_t*); + +/* + * Extended read methods for receiving handles over a pipe. The pipe must be + * initialized with ipc == 1. + */ +UV_EXTERN int uv_read2_start(uv_stream_t*, uv_alloc_cb alloc_cb, + uv_read2_cb read_cb); + + +/* + * Write data to stream. Buffers are written in order. Example: + * + * uv_buf_t a[] = { + * { .base = "1", .len = 1 }, + * { .base = "2", .len = 1 } + * }; + * + * uv_buf_t b[] = { + * { .base = "3", .len = 1 }, + * { .base = "4", .len = 1 } + * }; + * + * // writes "1234" + * uv_write(req, stream, a, 2); + * uv_write(req, stream, b, 2); + * + */ +UV_EXTERN int uv_write(uv_write_t* req, uv_stream_t* handle, + uv_buf_t bufs[], int bufcnt, uv_write_cb cb); + +/* + * Extended write function for sending handles over a pipe. The pipe must be + * initialized with ipc == 1. + * send_handle must be a TCP socket or pipe, which is a server or a connection + * (listening or connected state). Bound sockets or pipes will be assumed to + * be servers. + */ +UV_EXTERN int uv_write2(uv_write_t* req, uv_stream_t* handle, uv_buf_t bufs[], + int bufcnt, uv_stream_t* send_handle, uv_write_cb cb); + +/* uv_write_t is a subclass of uv_req_t */ +struct uv_write_s { + UV_REQ_FIELDS + uv_write_cb cb; + uv_stream_t* send_handle; + uv_stream_t* handle; + UV_WRITE_PRIVATE_FIELDS +}; + + +/* + * Used to determine whether a stream is readable or writable. + */ +UV_EXTERN int uv_is_readable(const uv_stream_t* handle); +UV_EXTERN int uv_is_writable(const uv_stream_t* handle); + + +/* + * Used to determine whether a stream is closing or closed. + * + * N.B. is only valid between the initialization of the handle + * and the arrival of the close callback, and cannot be used + * to validate the handle. + */ +UV_EXTERN int uv_is_closing(const uv_handle_t* handle); + + +/* + * uv_tcp_t is a subclass of uv_stream_t + * + * Represents a TCP stream or TCP server. + */ +struct uv_tcp_s { + UV_HANDLE_FIELDS + UV_STREAM_FIELDS + UV_TCP_PRIVATE_FIELDS +}; + +UV_EXTERN int uv_tcp_init(uv_loop_t*, uv_tcp_t* handle); + +/* Enable/disable Nagle's algorithm. */ +UV_EXTERN int uv_tcp_nodelay(uv_tcp_t* handle, int enable); + +/* Enable/disable TCP keep-alive. + * + * `ms` is the initial delay in seconds, ignored when `enable` is zero. + */ +UV_EXTERN int uv_tcp_keepalive(uv_tcp_t* handle, int enable, + unsigned int delay); + +/* + * This setting applies to Windows only. + * Enable/disable simultaneous asynchronous accept requests that are + * queued by the operating system when listening for new tcp connections. + * This setting is used to tune a tcp server for the desired performance. + * Having simultaneous accepts can significantly improve the rate of + * accepting connections (which is why it is enabled by default). + */ +UV_EXTERN int uv_tcp_simultaneous_accepts(uv_tcp_t* handle, int enable); + +UV_EXTERN int uv_tcp_bind(uv_tcp_t* handle, struct sockaddr_in); +UV_EXTERN int uv_tcp_bind6(uv_tcp_t* handle, struct sockaddr_in6); +UV_EXTERN int uv_tcp_getsockname(uv_tcp_t* handle, struct sockaddr* name, + int* namelen); +UV_EXTERN int uv_tcp_getpeername(uv_tcp_t* handle, struct sockaddr* name, + int* namelen); + +/* + * uv_tcp_connect, uv_tcp_connect6 + * These functions establish IPv4 and IPv6 TCP connections. Provide an + * initialized TCP handle and an uninitialized uv_connect_t*. The callback + * will be made when the connection is established. + */ +UV_EXTERN int uv_tcp_connect(uv_connect_t* req, uv_tcp_t* handle, + struct sockaddr_in address, uv_connect_cb cb); +UV_EXTERN int uv_tcp_connect6(uv_connect_t* req, uv_tcp_t* handle, + struct sockaddr_in6 address, uv_connect_cb cb); + +/* uv_connect_t is a subclass of uv_req_t */ +struct uv_connect_s { + UV_REQ_FIELDS + uv_connect_cb cb; + uv_stream_t* handle; + UV_CONNECT_PRIVATE_FIELDS +}; + + +/* + * UDP support. + */ + +enum uv_udp_flags { + /* Disables dual stack mode. Used with uv_udp_bind6(). */ + UV_UDP_IPV6ONLY = 1, + /* + * Indicates message was truncated because read buffer was too small. The + * remainder was discarded by the OS. Used in uv_udp_recv_cb. + */ + UV_UDP_PARTIAL = 2 +}; + +/* + * Called after a uv_udp_send() or uv_udp_send6(). status 0 indicates + * success otherwise error. + */ +typedef void (*uv_udp_send_cb)(uv_udp_send_t* req, int status); + +/* + * Callback that is invoked when a new UDP datagram is received. + * + * handle UDP handle. + * nread Number of bytes that have been received. + * 0 if there is no more data to read. You may + * discard or repurpose the read buffer. + * -1 if a transmission error was detected. + * buf uv_buf_t with the received data. + * addr struct sockaddr_in or struct sockaddr_in6. + * Valid for the duration of the callback only. + * flags One or more OR'ed UV_UDP_* constants. + * Right now only UV_UDP_PARTIAL is used. + */ +typedef void (*uv_udp_recv_cb)(uv_udp_t* handle, ssize_t nread, uv_buf_t buf, + struct sockaddr* addr, unsigned flags); + +/* uv_udp_t is a subclass of uv_handle_t */ +struct uv_udp_s { + UV_HANDLE_FIELDS + UV_UDP_PRIVATE_FIELDS +}; + +/* uv_udp_send_t is a subclass of uv_req_t */ +struct uv_udp_send_s { + UV_REQ_FIELDS + uv_udp_t* handle; + uv_udp_send_cb cb; + UV_UDP_SEND_PRIVATE_FIELDS +}; + +/* + * Initialize a new UDP handle. The actual socket is created lazily. + * Returns 0 on success. + */ +UV_EXTERN int uv_udp_init(uv_loop_t*, uv_udp_t* handle); + +/* + * Bind to a IPv4 address and port. + * + * Arguments: + * handle UDP handle. Should have been initialized with `uv_udp_init`. + * addr struct sockaddr_in with the address and port to bind to. + * flags Unused. + * + * Returns: + * 0 on success, -1 on error. + */ +UV_EXTERN int uv_udp_bind(uv_udp_t* handle, struct sockaddr_in addr, + unsigned flags); + +/* + * Bind to a IPv6 address and port. + * + * Arguments: + * handle UDP handle. Should have been initialized with `uv_udp_init`. + * addr struct sockaddr_in with the address and port to bind to. + * flags Should be 0 or UV_UDP_IPV6ONLY. + * + * Returns: + * 0 on success, -1 on error. + */ +UV_EXTERN int uv_udp_bind6(uv_udp_t* handle, struct sockaddr_in6 addr, + unsigned flags); +UV_EXTERN int uv_udp_getsockname(uv_udp_t* handle, struct sockaddr* name, + int* namelen); + +/* + * Set membership for a multicast address + * + * Arguments: + * handle UDP handle. Should have been initialized with + * `uv_udp_init`. + * multicast_addr multicast address to set membership for + * interface_addr interface address + * membership Should be UV_JOIN_GROUP or UV_LEAVE_GROUP + * + * Returns: + * 0 on success, -1 on error. + */ +UV_EXTERN int uv_udp_set_membership(uv_udp_t* handle, + const char* multicast_addr, const char* interface_addr, + uv_membership membership); + +/* + * Set IP multicast loop flag. Makes multicast packets loop back to + * local sockets. + * + * Arguments: + * handle UDP handle. Should have been initialized with + * `uv_udp_init`. + * on 1 for on, 0 for off + * + * Returns: + * 0 on success, -1 on error. + */ +UV_EXTERN int uv_udp_set_multicast_loop(uv_udp_t* handle, int on); + +/* + * Set the multicast ttl + * + * Arguments: + * handle UDP handle. Should have been initialized with + * `uv_udp_init`. + * ttl 1 through 255 + * + * Returns: + * 0 on success, -1 on error. + */ +UV_EXTERN int uv_udp_set_multicast_ttl(uv_udp_t* handle, int ttl); + +/* + * Set broadcast on or off + * + * Arguments: + * handle UDP handle. Should have been initialized with + * `uv_udp_init`. + * on 1 for on, 0 for off + * + * Returns: + * 0 on success, -1 on error. + */ +UV_EXTERN int uv_udp_set_broadcast(uv_udp_t* handle, int on); + +/* + * Set the time to live + * + * Arguments: + * handle UDP handle. Should have been initialized with + * `uv_udp_init`. + * ttl 1 through 255 + * + * Returns: + * 0 on success, -1 on error. + */ +UV_EXTERN int uv_udp_set_ttl(uv_udp_t* handle, int ttl); + +/* + * Send data. If the socket has not previously been bound with `uv_udp_bind` + * or `uv_udp_bind6`, it is bound to 0.0.0.0 (the "all interfaces" address) + * and a random port number. + * + * Arguments: + * req UDP request handle. Need not be initialized. + * handle UDP handle. Should have been initialized with `uv_udp_init`. + * bufs List of buffers to send. + * bufcnt Number of buffers in `bufs`. + * addr Address of the remote peer. See `uv_ip4_addr`. + * send_cb Callback to invoke when the data has been sent out. + * + * Returns: + * 0 on success, -1 on error. + */ +UV_EXTERN int uv_udp_send(uv_udp_send_t* req, uv_udp_t* handle, + uv_buf_t bufs[], int bufcnt, struct sockaddr_in addr, + uv_udp_send_cb send_cb); + +/* + * Send data. If the socket has not previously been bound with `uv_udp_bind6`, + * it is bound to ::0 (the "all interfaces" address) and a random port number. + * + * Arguments: + * req UDP request handle. Need not be initialized. + * handle UDP handle. Should have been initialized with `uv_udp_init`. + * bufs List of buffers to send. + * bufcnt Number of buffers in `bufs`. + * addr Address of the remote peer. See `uv_ip6_addr`. + * send_cb Callback to invoke when the data has been sent out. + * + * Returns: + * 0 on success, -1 on error. + */ +UV_EXTERN int uv_udp_send6(uv_udp_send_t* req, uv_udp_t* handle, + uv_buf_t bufs[], int bufcnt, struct sockaddr_in6 addr, + uv_udp_send_cb send_cb); + +/* + * Receive data. If the socket has not previously been bound with `uv_udp_bind` + * or `uv_udp_bind6`, it is bound to 0.0.0.0 (the "all interfaces" address) + * and a random port number. + * + * Arguments: + * handle UDP handle. Should have been initialized with `uv_udp_init`. + * alloc_cb Callback to invoke when temporary storage is needed. + * recv_cb Callback to invoke with received data. + * + * Returns: + * 0 on success, -1 on error. + */ +UV_EXTERN int uv_udp_recv_start(uv_udp_t* handle, uv_alloc_cb alloc_cb, + uv_udp_recv_cb recv_cb); + +/* + * Stop listening for incoming datagrams. + * + * Arguments: + * handle UDP handle. Should have been initialized with `uv_udp_init`. + * + * Returns: + * 0 on success, -1 on error. + */ +UV_EXTERN int uv_udp_recv_stop(uv_udp_t* handle); + + +/* + * uv_tty_t is a subclass of uv_stream_t + * + * Representing a stream for the console. + */ +struct uv_tty_s { + UV_HANDLE_FIELDS + UV_STREAM_FIELDS + UV_TTY_PRIVATE_FIELDS +}; + +/* + * Initialize a new TTY stream with the given file descriptor. Usually the + * file descriptor will be + * 0 = stdin + * 1 = stdout + * 2 = stderr + * The last argument, readable, specifies if you plan on calling + * uv_read_start with this stream. stdin is readable, stdout is not. + * + * TTY streams which are not readable have blocking writes. + */ +UV_EXTERN int uv_tty_init(uv_loop_t*, uv_tty_t*, uv_file fd, int readable); + +/* + * Set mode. 0 for normal, 1 for raw. + */ +UV_EXTERN int uv_tty_set_mode(uv_tty_t*, int mode); + +/* + * To be called when the program exits. Resets TTY settings to default + * values for the next process to take over. + */ +UV_EXTERN void uv_tty_reset_mode(void); + +/* + * Gets the current Window size. On success zero is returned. + */ +UV_EXTERN int uv_tty_get_winsize(uv_tty_t*, int* width, int* height); + +/* + * Used to detect what type of stream should be used with a given file + * descriptor. Usually this will be used during initialization to guess the + * type of the stdio streams. + * For isatty() functionality use this function and test for UV_TTY. + */ +UV_EXTERN uv_handle_type uv_guess_handle(uv_file file); + +/* + * uv_pipe_t is a subclass of uv_stream_t + * + * Representing a pipe stream or pipe server. On Windows this is a Named + * Pipe. On Unix this is a UNIX domain socket. + */ +struct uv_pipe_s { + UV_HANDLE_FIELDS + UV_STREAM_FIELDS + UV_PIPE_PRIVATE_FIELDS + int ipc; /* non-zero if this pipe is used for passing handles */ +}; + +/* + * Initialize a pipe. The last argument is a boolean to indicate if + * this pipe will be used for handle passing between processes. + */ +UV_EXTERN int uv_pipe_init(uv_loop_t*, uv_pipe_t* handle, int ipc); + +/* + * Opens an existing file descriptor or HANDLE as a pipe. + */ +UV_EXTERN void uv_pipe_open(uv_pipe_t*, uv_file file); + +UV_EXTERN int uv_pipe_bind(uv_pipe_t* handle, const char* name); + +UV_EXTERN void uv_pipe_connect(uv_connect_t* req, uv_pipe_t* handle, + const char* name, uv_connect_cb cb); + +/* + * This setting applies to Windows only. + * Set the number of pending pipe instance handles when the pipe server + * is waiting for connections. + */ +UV_EXTERN void uv_pipe_pending_instances(uv_pipe_t* handle, int count); + + +/* + * uv_poll_t is a subclass of uv_handle_t. + * + * The uv_poll watcher is used to watch file descriptors for readability and + * writability, similar to the purpose of poll(2). + * + * The purpose of uv_poll is to enable integrating external libraries that + * rely on the event loop to signal it about the socket status changes, like + * c-ares or libssh2. Using uv_poll_t for any other other purpose is not + * recommended; uv_tcp_t, uv_udp_t, etc. provide an implementation that is + * much faster and more scalable than what can be achieved with uv_poll_t, + * especially on Windows. + * + * It is possible that uv_poll occasionally signals that a file descriptor is + * readable or writable even when it isn't. The user should therefore always + * be prepared to handle EAGAIN or equivalent when it attempts to read from or + * write to the fd. + * + * It is not okay to have multiple active uv_poll watchers for the same socket. + * This can cause libuv to busyloop or otherwise malfunction. + * + * The user should not close a file descriptor while it is being polled by an + * active uv_poll watcher. This can cause the poll watcher to report an error, + * but it might also start polling another socket. However the fd can be safely + * closed immediately after a call to uv_poll_stop() or uv_close(). + * + * On windows only sockets can be polled with uv_poll. On unix any file + * descriptor that would be accepted by poll(2) can be used with uv_poll. + */ +struct uv_poll_s { + UV_HANDLE_FIELDS + uv_poll_cb poll_cb; + UV_POLL_PRIVATE_FIELDS +}; + +enum uv_poll_event { + UV_READABLE = 1, + UV_WRITABLE = 2 +}; + +/* Initialize the poll watcher using a file descriptor. */ +UV_EXTERN int uv_poll_init(uv_loop_t* loop, uv_poll_t* handle, int fd); + +/* Initialize the poll watcher using a socket descriptor. On unix this is */ +/* identical to uv_poll_init. On windows it takes a SOCKET handle. */ +UV_EXTERN int uv_poll_init_socket(uv_loop_t* loop, uv_poll_t* handle, + uv_os_sock_t socket); + +/* + * Starts polling the file descriptor. `events` is a bitmask consisting made up + * of UV_READABLE and UV_WRITABLE. As soon as an event is detected the callback + * will be called with `status` set to 0, and the detected events set en the + * `events` field. + * + * If an error happens while polling status may be set to -1 and the error + * code can be retrieved with uv_last_error. The user should not close the + * socket while uv_poll is active. If the user does that anyway, the callback + * *may* be called reporting an error status, but this is not guaranteed. + * + * Calling uv_poll_start on an uv_poll watcher that is already active is fine. + * Doing so will update the events mask that is being watched for. + */ +UV_EXTERN int uv_poll_start(uv_poll_t* handle, int events, uv_poll_cb cb); + +/* Stops polling the file descriptor. */ +UV_EXTERN int uv_poll_stop(uv_poll_t* handle); + + +/* + * uv_prepare_t is a subclass of uv_handle_t. + * + * libev wrapper. Every active prepare handle gets its callback called + * exactly once per loop iteration, just before the system blocks to wait + * for completed i/o. + */ +struct uv_prepare_s { + UV_HANDLE_FIELDS + UV_PREPARE_PRIVATE_FIELDS +}; + +UV_EXTERN int uv_prepare_init(uv_loop_t*, uv_prepare_t* prepare); + +UV_EXTERN int uv_prepare_start(uv_prepare_t* prepare, uv_prepare_cb cb); + +UV_EXTERN int uv_prepare_stop(uv_prepare_t* prepare); + + +/* + * uv_check_t is a subclass of uv_handle_t. + * + * libev wrapper. Every active check handle gets its callback called exactly + * once per loop iteration, just after the system returns from blocking. + */ +struct uv_check_s { + UV_HANDLE_FIELDS + UV_CHECK_PRIVATE_FIELDS +}; + +UV_EXTERN int uv_check_init(uv_loop_t*, uv_check_t* check); + +UV_EXTERN int uv_check_start(uv_check_t* check, uv_check_cb cb); + +UV_EXTERN int uv_check_stop(uv_check_t* check); + + +/* + * uv_idle_t is a subclass of uv_handle_t. + * + * libev wrapper. Every active idle handle gets its callback called + * repeatedly until it is stopped. This happens after all other types of + * callbacks are processed. When there are multiple "idle" handles active, + * their callbacks are called in turn. + */ +struct uv_idle_s { + UV_HANDLE_FIELDS + UV_IDLE_PRIVATE_FIELDS +}; + +UV_EXTERN int uv_idle_init(uv_loop_t*, uv_idle_t* idle); + +UV_EXTERN int uv_idle_start(uv_idle_t* idle, uv_idle_cb cb); + +UV_EXTERN int uv_idle_stop(uv_idle_t* idle); + + +/* + * uv_async_t is a subclass of uv_handle_t. + * + * libev wrapper. uv_async_send wakes up the event + * loop and calls the async handle's callback There is no guarantee that + * every uv_async_send call leads to exactly one invocation of the callback; + * The only guarantee is that the callback function is called at least once + * after the call to async_send. Unlike all other libuv functions, + * uv_async_send can be called from another thread. + */ +struct uv_async_s { + UV_HANDLE_FIELDS + UV_ASYNC_PRIVATE_FIELDS +}; + +UV_EXTERN int uv_async_init(uv_loop_t*, uv_async_t* async, + uv_async_cb async_cb); + +/* + * This can be called from other threads to wake up a libuv thread. + * + * libuv is single threaded at the moment. + */ +UV_EXTERN int uv_async_send(uv_async_t* async); + + +/* + * uv_timer_t is a subclass of uv_handle_t. + * + * Used to get woken up at a specified time in the future. + */ +struct uv_timer_s { + UV_HANDLE_FIELDS + UV_TIMER_PRIVATE_FIELDS +}; + +UV_EXTERN int uv_timer_init(uv_loop_t*, uv_timer_t* timer); + +/* + * Start the timer. `timeout` and `repeat` are in milliseconds. + * + * If timeout is zero, the callback fires on the next tick of the event loop. + * + * If repeat is non-zero, the callback fires first after timeout milliseconds + * and then repeatedly after repeat milliseconds. + * + * timeout and repeat are signed integers but that will change in a future + * version of libuv. Don't pass in negative values, you'll get a nasty surprise + * when that change becomes effective. + */ +UV_EXTERN int uv_timer_start(uv_timer_t* timer, + uv_timer_cb cb, + int64_t timeout, + int64_t repeat); + +UV_EXTERN int uv_timer_stop(uv_timer_t* timer); + +/* + * Stop the timer, and if it is repeating restart it using the repeat value + * as the timeout. If the timer has never been started before it returns -1 and + * sets the error to UV_EINVAL. + */ +UV_EXTERN int uv_timer_again(uv_timer_t* timer); + +/* + * Set the repeat value in milliseconds. Note that if the repeat value is set + * from a timer callback it does not immediately take effect. If the timer was + * non-repeating before, it will have been stopped. If it was repeating, then + * the old repeat value will have been used to schedule the next timeout. + */ +UV_EXTERN void uv_timer_set_repeat(uv_timer_t* timer, int64_t repeat); + +UV_EXTERN int64_t uv_timer_get_repeat(uv_timer_t* timer); + + +/* c-ares integration initialize and terminate */ +UV_EXTERN int uv_ares_init_options(uv_loop_t*, + ares_channel *channelptr, struct ares_options *options, int optmask); + +/* TODO remove the loop argument from this function? */ +UV_EXTERN void uv_ares_destroy(uv_loop_t*, ares_channel channel); + + +/* + * uv_getaddrinfo_t is a subclass of uv_req_t + * + * Request object for uv_getaddrinfo. + */ +struct uv_getaddrinfo_s { + UV_REQ_FIELDS + /* read-only */ + uv_loop_t* loop; + UV_GETADDRINFO_PRIVATE_FIELDS +}; + + +/* + * Asynchronous getaddrinfo(3). + * + * Return code 0 means that request is accepted and callback will be called + * with result. Other return codes mean that there will not be a callback. + * Input arguments may be released after return from this call. + * + * uv_freeaddrinfo() must be called after completion to free the addrinfo + * structure. + * + * On error NXDOMAIN the status code will be non-zero and UV_ENOENT returned. + */ +UV_EXTERN int uv_getaddrinfo(uv_loop_t*, uv_getaddrinfo_t* handle, + uv_getaddrinfo_cb getaddrinfo_cb, const char* node, const char* service, + const struct addrinfo* hints); + +UV_EXTERN void uv_freeaddrinfo(struct addrinfo* ai); + +/* uv_spawn() options */ +typedef enum { + UV_IGNORE = 0x00, + UV_CREATE_PIPE = 0x01, + UV_INHERIT_FD = 0x02, + UV_INHERIT_STREAM = 0x04, + + /* When UV_CREATE_PIPE is specified, UV_READABLE_PIPE and UV_WRITABLE_PIPE + * determine the direction of flow, from the child process' perspective. Both + * flags may be specified to create a duplex data stream. + */ + UV_READABLE_PIPE = 0x10, + UV_WRITABLE_PIPE = 0x20 +} uv_stdio_flags; + +typedef struct uv_stdio_container_s { + uv_stdio_flags flags; + + union { + uv_stream_t* stream; + int fd; + } data; +} uv_stdio_container_t; + +typedef struct uv_process_options_s { + uv_exit_cb exit_cb; /* Called after the process exits. */ + const char* file; /* Path to program to execute. */ + /* + * Command line arguments. args[0] should be the path to the program. On + * Windows this uses CreateProcess which concatenates the arguments into a + * string this can cause some strange errors. See the note at + * windows_verbatim_arguments. + */ + char** args; + /* + * This will be set as the environ variable in the subprocess. If this is + * NULL then the parents environ will be used. + */ + char** env; + /* + * If non-null this represents a directory the subprocess should execute + * in. Stands for current working directory. + */ + char* cwd; + /* + * Various flags that control how uv_spawn() behaves. See the definition of + * `enum uv_process_flags` below. + */ + unsigned int flags; + /* + * Libuv can change the child process' user/group id. This happens only when + * the appropriate bits are set in the flags fields. This is not supported on + * windows; uv_spawn() will fail and set the error to UV_ENOTSUP. + */ + uv_uid_t uid; + uv_gid_t gid; + + /* + * The `stdio` field points to an array of uv_stdio_container_t structs that + * describe the file descriptors that will be made available to the child + * process. The convention is that stdio[0] points to stdin, fd 1 is used for + * stdout, and fd 2 is stderr. + * + * Note that on windows file descriptors greater than 2 are available to the + * child process only if the child processes uses the MSVCRT runtime. + */ + int stdio_count; + uv_stdio_container_t* stdio; +} uv_process_options_t; + +/* + * These are the flags that can be used for the uv_process_options.flags field. + */ +enum uv_process_flags { + /* + * Set the child process' user id. The user id is supplied in the `uid` field + * of the options struct. This does not work on windows; setting this flag + * will cause uv_spawn() to fail. + */ + UV_PROCESS_SETUID = (1 << 0), + /* + * Set the child process' group id. The user id is supplied in the `gid` + * field of the options struct. This does not work on windows; setting this + * flag will cause uv_spawn() to fail. + */ + UV_PROCESS_SETGID = (1 << 1), + /* + * Do not wrap any arguments in quotes, or perform any other escaping, when + * converting the argument list into a command line string. This option is + * only meaningful on Windows systems. On unix it is silently ignored. + */ + UV_PROCESS_WINDOWS_VERBATIM_ARGUMENTS = (1 << 2), + /* + * Spawn the child process in a detached state - this will make it a process + * group leader, and will effectively enable the child to keep running after + * the parent exits. Note that the child process will still keep the + * parent's event loop alive unless the parent process calls uv_unref() on + * the child's process handle. + */ + UV_PROCESS_DETACHED = (1 << 3) +}; + +/* + * uv_process_t is a subclass of uv_handle_t + */ +struct uv_process_s { + UV_HANDLE_FIELDS + uv_exit_cb exit_cb; + int pid; + UV_PROCESS_PRIVATE_FIELDS +}; + +/* Initializes uv_process_t and starts the process. */ +UV_EXTERN int uv_spawn(uv_loop_t*, uv_process_t*, + uv_process_options_t options); + + +/* + * Kills the process with the specified signal. The user must still + * call uv_close on the process. + */ +UV_EXTERN int uv_process_kill(uv_process_t*, int signum); + + +/* Kills the process with the specified signal. */ +UV_EXTERN uv_err_t uv_kill(int pid, int signum); + + +/* + * uv_work_t is a subclass of uv_req_t + */ +struct uv_work_s { + UV_REQ_FIELDS + uv_loop_t* loop; + uv_work_cb work_cb; + uv_after_work_cb after_work_cb; + UV_WORK_PRIVATE_FIELDS +}; + +/* Queues a work request to execute asynchronously on the thread pool. */ +UV_EXTERN int uv_queue_work(uv_loop_t* loop, uv_work_t* req, + uv_work_cb work_cb, uv_after_work_cb after_work_cb); + + +struct uv_cpu_info_s { + char* model; + int speed; + struct uv_cpu_times_s { + uint64_t user; + uint64_t nice; + uint64_t sys; + uint64_t idle; + uint64_t irq; + } cpu_times; +}; + +struct uv_interface_address_s { + char* name; + int is_internal; + union { + struct sockaddr_in address4; + struct sockaddr_in6 address6; + } address; +}; + +UV_EXTERN char** uv_setup_args(int argc, char** argv); +UV_EXTERN uv_err_t uv_get_process_title(char* buffer, size_t size); +UV_EXTERN uv_err_t uv_set_process_title(const char* title); +UV_EXTERN uv_err_t uv_resident_set_memory(size_t* rss); +UV_EXTERN uv_err_t uv_uptime(double* uptime); + +/* + * This allocates cpu_infos array, and sets count. The array + * is freed using uv_free_cpu_info(). + */ +UV_EXTERN uv_err_t uv_cpu_info(uv_cpu_info_t** cpu_infos, int* count); +UV_EXTERN void uv_free_cpu_info(uv_cpu_info_t* cpu_infos, int count); + +/* + * This allocates addresses array, and sets count. The array + * is freed using uv_free_interface_addresses(). + */ +UV_EXTERN uv_err_t uv_interface_addresses(uv_interface_address_t** addresses, + int* count); +UV_EXTERN void uv_free_interface_addresses(uv_interface_address_t* addresses, + int count); + +/* + * File System Methods. + * + * The uv_fs_* functions execute a blocking system call asynchronously (in a + * thread pool) and call the specified callback in the specified loop after + * completion. If the user gives NULL as the callback the blocking system + * call will be called synchronously. req should be a pointer to an + * uninitialized uv_fs_t object. + * + * uv_fs_req_cleanup() must be called after completion of the uv_fs_ + * function to free any internal memory allocations associated with the + * request. + */ + +typedef enum { + UV_FS_UNKNOWN = -1, + UV_FS_CUSTOM, + UV_FS_OPEN, + UV_FS_CLOSE, + UV_FS_READ, + UV_FS_WRITE, + UV_FS_SENDFILE, + UV_FS_STAT, + UV_FS_LSTAT, + UV_FS_FSTAT, + UV_FS_FTRUNCATE, + UV_FS_UTIME, + UV_FS_FUTIME, + UV_FS_CHMOD, + UV_FS_FCHMOD, + UV_FS_FSYNC, + UV_FS_FDATASYNC, + UV_FS_UNLINK, + UV_FS_RMDIR, + UV_FS_MKDIR, + UV_FS_RENAME, + UV_FS_READDIR, + UV_FS_LINK, + UV_FS_SYMLINK, + UV_FS_READLINK, + UV_FS_CHOWN, + UV_FS_FCHOWN +} uv_fs_type; + +/* uv_fs_t is a subclass of uv_req_t */ +struct uv_fs_s { + UV_REQ_FIELDS + uv_fs_type fs_type; + uv_loop_t* loop; + uv_fs_cb cb; + ssize_t result; + void* ptr; + const char* path; + uv_err_code errorno; + UV_FS_PRIVATE_FIELDS +}; + +UV_EXTERN void uv_fs_req_cleanup(uv_fs_t* req); + +UV_EXTERN int uv_fs_close(uv_loop_t* loop, uv_fs_t* req, uv_file file, + uv_fs_cb cb); + +UV_EXTERN int uv_fs_open(uv_loop_t* loop, uv_fs_t* req, const char* path, + int flags, int mode, uv_fs_cb cb); + +UV_EXTERN int uv_fs_read(uv_loop_t* loop, uv_fs_t* req, uv_file file, + void* buf, size_t length, int64_t offset, uv_fs_cb cb); + +UV_EXTERN int uv_fs_unlink(uv_loop_t* loop, uv_fs_t* req, const char* path, + uv_fs_cb cb); + +UV_EXTERN int uv_fs_write(uv_loop_t* loop, uv_fs_t* req, uv_file file, + void* buf, size_t length, int64_t offset, uv_fs_cb cb); + +UV_EXTERN int uv_fs_mkdir(uv_loop_t* loop, uv_fs_t* req, const char* path, + int mode, uv_fs_cb cb); + +UV_EXTERN int uv_fs_rmdir(uv_loop_t* loop, uv_fs_t* req, const char* path, + uv_fs_cb cb); + +UV_EXTERN int uv_fs_readdir(uv_loop_t* loop, uv_fs_t* req, + const char* path, int flags, uv_fs_cb cb); + +UV_EXTERN int uv_fs_stat(uv_loop_t* loop, uv_fs_t* req, const char* path, + uv_fs_cb cb); + +UV_EXTERN int uv_fs_fstat(uv_loop_t* loop, uv_fs_t* req, uv_file file, + uv_fs_cb cb); + +UV_EXTERN int uv_fs_rename(uv_loop_t* loop, uv_fs_t* req, const char* path, + const char* new_path, uv_fs_cb cb); + +UV_EXTERN int uv_fs_fsync(uv_loop_t* loop, uv_fs_t* req, uv_file file, + uv_fs_cb cb); + +UV_EXTERN int uv_fs_fdatasync(uv_loop_t* loop, uv_fs_t* req, uv_file file, + uv_fs_cb cb); + +UV_EXTERN int uv_fs_ftruncate(uv_loop_t* loop, uv_fs_t* req, uv_file file, + int64_t offset, uv_fs_cb cb); + +UV_EXTERN int uv_fs_sendfile(uv_loop_t* loop, uv_fs_t* req, uv_file out_fd, + uv_file in_fd, int64_t in_offset, size_t length, uv_fs_cb cb); + +UV_EXTERN int uv_fs_chmod(uv_loop_t* loop, uv_fs_t* req, const char* path, + int mode, uv_fs_cb cb); + +UV_EXTERN int uv_fs_utime(uv_loop_t* loop, uv_fs_t* req, const char* path, + double atime, double mtime, uv_fs_cb cb); + +UV_EXTERN int uv_fs_futime(uv_loop_t* loop, uv_fs_t* req, uv_file file, + double atime, double mtime, uv_fs_cb cb); + +UV_EXTERN int uv_fs_lstat(uv_loop_t* loop, uv_fs_t* req, const char* path, + uv_fs_cb cb); + +UV_EXTERN int uv_fs_link(uv_loop_t* loop, uv_fs_t* req, const char* path, + const char* new_path, uv_fs_cb cb); + +/* + * This flag can be used with uv_fs_symlink on Windows + * to specify whether path argument points to a directory. + */ +#define UV_FS_SYMLINK_DIR 0x0001 + +/* + * This flag can be used with uv_fs_symlink on Windows + * to specify whether the symlink is to be created using junction points. + */ +#define UV_FS_SYMLINK_JUNCTION 0x0002 + +UV_EXTERN int uv_fs_symlink(uv_loop_t* loop, uv_fs_t* req, const char* path, + const char* new_path, int flags, uv_fs_cb cb); + +UV_EXTERN int uv_fs_readlink(uv_loop_t* loop, uv_fs_t* req, const char* path, + uv_fs_cb cb); + +UV_EXTERN int uv_fs_fchmod(uv_loop_t* loop, uv_fs_t* req, uv_file file, + int mode, uv_fs_cb cb); + +UV_EXTERN int uv_fs_chown(uv_loop_t* loop, uv_fs_t* req, const char* path, + int uid, int gid, uv_fs_cb cb); + +UV_EXTERN int uv_fs_fchown(uv_loop_t* loop, uv_fs_t* req, uv_file file, + int uid, int gid, uv_fs_cb cb); + + +enum uv_fs_event { + UV_RENAME = 1, + UV_CHANGE = 2 +}; + + +struct uv_fs_event_s { + UV_HANDLE_FIELDS + char* filename; + UV_FS_EVENT_PRIVATE_FIELDS +}; + + +/* + * uv_fs_stat() based polling file watcher. + */ +struct uv_fs_poll_s { + UV_HANDLE_FIELDS + /* Private, don't touch. */ + void* poll_ctx; + /* v0.8 ABI compatibility */ + char padding[sizeof(int) + + sizeof(unsigned int) + + sizeof(uint64_t) + + sizeof(char*) + + sizeof(uv_fs_poll_cb) + + sizeof(uv_timer_t) + + sizeof(uv_fs_t*) + + sizeof(uv_statbuf_t) + - sizeof(void*)]; +}; + +UV_EXTERN int uv_fs_poll_init(uv_loop_t* loop, uv_fs_poll_t* handle); + +/* + * Check the file at `path` for changes every `interval` milliseconds. + * + * Your callback i invoked with `status == -1` if `path` does not exist + * or is inaccessible. The watcher is *not* stopped but your callback is + * not called again until something changes (e.g. when the file is created + * or the error reason changes). + * + * When `status == 0`, your callback receives pointers to the old and new + * `uv_statbuf_t` structs. They are valid for the duration of the callback + * only! + * + * For maximum portability, use multi-second intervals. Sub-second intervals + * will not detect all changes on many file systems. + */ +UV_EXTERN int uv_fs_poll_start(uv_fs_poll_t* handle, + uv_fs_poll_cb poll_cb, + const char* path, + unsigned int interval); + +UV_EXTERN int uv_fs_poll_stop(uv_fs_poll_t* handle); + +/* + * Gets load avg + * See: http://en.wikipedia.org/wiki/Load_(computing) + * (Returns [0,0,0] for windows and cygwin) + */ +UV_EXTERN void uv_loadavg(double avg[3]); + + +/* + * Flags to be passed to uv_fs_event_init. + */ +enum uv_fs_event_flags { + /* + * By default, if the fs event watcher is given a directory name, we will + * watch for all events in that directory. This flags overrides this behavior + * and makes fs_event report only changes to the directory entry itself. This + * flag does not affect individual files watched. + * This flag is currently not implemented yet on any backend. + */ + UV_FS_EVENT_WATCH_ENTRY = 1, + + /* + * By default uv_fs_event will try to use a kernel interface such as inotify + * or kqueue to detect events. This may not work on remote filesystems such + * as NFS mounts. This flag makes fs_event fall back to calling stat() on a + * regular interval. + * This flag is currently not implemented yet on any backend. + */ + UV_FS_EVENT_STAT = 2 +}; + + +UV_EXTERN int uv_fs_event_init(uv_loop_t* loop, uv_fs_event_t* handle, + const char* filename, uv_fs_event_cb cb, int flags); + +/* Utility */ + +/* Convert string ip addresses to binary structures */ +UV_EXTERN struct sockaddr_in uv_ip4_addr(const char* ip, int port); +UV_EXTERN struct sockaddr_in6 uv_ip6_addr(const char* ip, int port); + +/* Convert binary addresses to strings */ +UV_EXTERN int uv_ip4_name(struct sockaddr_in* src, char* dst, size_t size); +UV_EXTERN int uv_ip6_name(struct sockaddr_in6* src, char* dst, size_t size); + +/* Gets the executable path */ +UV_EXTERN int uv_exepath(char* buffer, size_t* size); + +/* Gets the current working directory */ +UV_EXTERN uv_err_t uv_cwd(char* buffer, size_t size); + +/* Changes the current working directory */ +UV_EXTERN uv_err_t uv_chdir(const char* dir); + +/* Gets memory info in bytes */ +UV_EXTERN uint64_t uv_get_free_memory(void); +UV_EXTERN uint64_t uv_get_total_memory(void); + +/* + * Returns the current high-resolution real time. This is expressed in + * nanoseconds. It is relative to an arbitrary time in the past. It is not + * related to the time of day and therefore not subject to clock drift. The + * primary use is for measuring performance between intervals. + * + * Note not every platform can support nanosecond resolution; however, this + * value will always be in nanoseconds. + */ +UV_EXTERN extern uint64_t uv_hrtime(void); + + +/* + * Disables inheritance for file descriptors / handles that this process + * inherited from its parent. The effect is that child processes spawned by + * this proces don't accidently inherit these handles. + * + * It is recommended to call this function as early in your program as possible, + * before the inherited file descriptors can be closed or duplicated. + * + * Note that this function works on a best-effort basis: there is no guarantee + * that libuv can discover all file descriptors that were inherited. In general + * it does a better job on Windows than it does on unix. + * + * TODO(bb): insert snarky remark to annoy bnoordhuis and the folks at joyent. + */ +UV_EXTERN void uv_disable_stdio_inheritance(void); + +/* + * Opens a shared library. The filename is in utf-8. Returns 0 on success and + * -1 on error. Call `uv_dlerror(uv_lib_t*)` to get the error message. + */ +UV_EXTERN int uv_dlopen(const char* filename, uv_lib_t* lib); + +/* + * Close the shared libary. + */ +UV_EXTERN void uv_dlclose(uv_lib_t* lib); + +/* + * Retrieves a data pointer from a dynamic library. It is legal for a symbol to + * map to NULL. Returns 0 on success and -1 if the symbol was not found. + */ +UV_EXTERN int uv_dlsym(uv_lib_t* lib, const char* name, void** ptr); + +/* + * Returns the last uv_dlopen() or uv_dlsym() error message. + */ +UV_EXTERN const char* uv_dlerror(uv_lib_t* lib); + +/* + * The mutex functions return 0 on success, -1 on error + * (unless the return type is void, of course). + */ +UV_EXTERN int uv_mutex_init(uv_mutex_t* handle); +UV_EXTERN void uv_mutex_destroy(uv_mutex_t* handle); +UV_EXTERN void uv_mutex_lock(uv_mutex_t* handle); +UV_EXTERN int uv_mutex_trylock(uv_mutex_t* handle); +UV_EXTERN void uv_mutex_unlock(uv_mutex_t* handle); + +/* + * Same goes for the read/write lock functions. + */ +UV_EXTERN int uv_rwlock_init(uv_rwlock_t* rwlock); +UV_EXTERN void uv_rwlock_destroy(uv_rwlock_t* rwlock); +UV_EXTERN void uv_rwlock_rdlock(uv_rwlock_t* rwlock); +UV_EXTERN int uv_rwlock_tryrdlock(uv_rwlock_t* rwlock); +UV_EXTERN void uv_rwlock_rdunlock(uv_rwlock_t* rwlock); +UV_EXTERN void uv_rwlock_wrlock(uv_rwlock_t* rwlock); +UV_EXTERN int uv_rwlock_trywrlock(uv_rwlock_t* rwlock); +UV_EXTERN void uv_rwlock_wrunlock(uv_rwlock_t* rwlock); + +/* + * Same goes for the semaphore functions. + */ +UV_EXTERN int uv_sem_init(uv_sem_t* sem, unsigned int value); +UV_EXTERN void uv_sem_destroy(uv_sem_t* sem); +UV_EXTERN void uv_sem_post(uv_sem_t* sem); +UV_EXTERN void uv_sem_wait(uv_sem_t* sem); +UV_EXTERN int uv_sem_trywait(uv_sem_t* sem); + +/* Runs a function once and only once. Concurrent calls to uv_once() with the + * same guard will block all callers except one (it's unspecified which one). + * The guard should be initialized statically with the UV_ONCE_INIT macro. + */ +UV_EXTERN void uv_once(uv_once_t* guard, void (*callback)(void)); + +UV_EXTERN int uv_thread_create(uv_thread_t *tid, + void (*entry)(void *arg), void *arg); +UV_EXTERN int uv_thread_join(uv_thread_t *tid); + +/* the presence of these unions force similar struct layout */ +union uv_any_handle { + uv_tcp_t tcp; + uv_pipe_t pipe; + uv_prepare_t prepare; + uv_check_t check; + uv_idle_t idle; + uv_async_t async; + uv_timer_t timer; + uv_getaddrinfo_t getaddrinfo; + uv_fs_event_t fs_event; +}; + +union uv_any_req { + uv_req_t req; + uv_write_t write; + uv_connect_t connect; + uv_shutdown_t shutdown; + uv_fs_t fs_req; + uv_work_t work_req; +}; + + +struct uv_counters_s { + uint64_t async_init; + uint64_t check_init; + uint64_t eio_init; + uint64_t fs_event_init; + uint64_t fs_poll_init; + uint64_t handle_init; + uint64_t idle_init; + uint64_t pipe_init; + uint64_t poll_init; + uint64_t prepare_init; + uint64_t process_init; + uint64_t req_init; + uint64_t stream_init; + uint64_t tcp_init; + uint64_t timer_init; + uint64_t tty_init; + uint64_t udp_init; +}; + + +struct uv_loop_s { + UV_LOOP_PRIVATE_FIELDS + ares_channel channel; + /* While the channel is active this timer is called once per second to be */ + /* sure that we're always calling ares_process. See the warning above the */ + /* definition of ares_timeout(). */ + uv_timer_t ares_timer; \ + /* RB_HEAD(uv__ares_tasks, uv_ares_task_t) */ + struct uv__ares_tasks { uv_ares_task_t* rbh_root; } ares_handles; + /* Diagnostic counters */ + uv_counters_t counters; + /* The last error */ + uv_err_t last_err; + /* Loop reference counting */ + unsigned int active_handles; + ngx_queue_t handle_queue; + ngx_queue_t active_reqs; + /* User data - use this for whatever. */ + void* data; +}; + + +/* Don't export the private CPP symbols. */ +#undef UV_HANDLE_TYPE_PRIVATE +#undef UV_REQ_TYPE_PRIVATE +#undef UV_REQ_PRIVATE_FIELDS +#undef UV_STREAM_PRIVATE_FIELDS +#undef UV_TCP_PRIVATE_FIELDS +#undef UV_PREPARE_PRIVATE_FIELDS +#undef UV_CHECK_PRIVATE_FIELDS +#undef UV_IDLE_PRIVATE_FIELDS +#undef UV_ASYNC_PRIVATE_FIELDS +#undef UV_TIMER_PRIVATE_FIELDS +#undef UV_GETADDRINFO_PRIVATE_FIELDS +#undef UV_FS_REQ_PRIVATE_FIELDS +#undef UV_WORK_PRIVATE_FIELDS +#undef UV_FS_EVENT_PRIVATE_FIELDS +#undef UV_LOOP_PRIVATE_FIELDS +#undef UV_LOOP_PRIVATE_PLATFORM_FIELDS + +#ifdef __cplusplus +} +#endif +#endif /* UV_H */ diff --git a/node-v0.8.14/deps/uv/test/benchmark-ares.c b/node-v0.8.14/deps/uv/test/benchmark-ares.c new file mode 100644 index 0000000..27084fa --- /dev/null +++ b/node-v0.8.14/deps/uv/test/benchmark-ares.c @@ -0,0 +1,117 @@ +/* Copyright Joyent, Inc. and other Node contributors. All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ + +#include "uv.h" +#include "task.h" + +#include +#include +#include /* strlen */ + +static uv_loop_t* loop; + +static ares_channel channel; +static struct ares_options options; +static int optmask; + +static int ares_callbacks; +static int ares_errors; +static int argument; + +#define NUM_CALLS_TO_START 1000 + +static int64_t start_time; +static int64_t end_time; + + +/* callback method. */ +static void aresbynamecallback(void *arg, + int status, + int timeouts, + struct hostent *hostent) { + ares_callbacks++; + if (status != 0) { + ares_errors++; + } +} + + +static void prep_tcploopback() +{ + /* for test, use echo server - TCP port TEST_PORT on loopback */ + struct sockaddr_in test_server = uv_ip4_addr("127.0.0.1", 0); + int rc = 0; + optmask = 0; + + optmask = ARES_OPT_SERVERS | ARES_OPT_TCP_PORT | ARES_OPT_FLAGS; + options.servers = &test_server.sin_addr; + options.nservers = 1; + options.tcp_port = htons(TEST_PORT_2); + options.flags = ARES_FLAG_USEVC; + + rc = uv_ares_init_options(loop, &channel, &options, optmask); + + ASSERT(rc == ARES_SUCCESS); +} + + +BENCHMARK_IMPL(gethostbyname) { + + int rc = 0; + int ares_start;; + + rc = ares_library_init(ARES_LIB_INIT_ALL); + if (rc != 0) { + printf("ares library init fails %d\n", rc); + return 1; + } + + loop = uv_default_loop(); + + ares_callbacks = 0; + ares_errors = 0; + + start_time = uv_hrtime(); + + prep_tcploopback(); + + for (ares_start = 0; ares_start < NUM_CALLS_TO_START; ares_start++) { + ares_gethostbyname(channel, + "echos.srv", + AF_INET, + &aresbynamecallback, + &argument); + } + + uv_run(loop); + + uv_ares_destroy(loop, channel); + + end_time = uv_hrtime(); + + if (ares_errors > 0) { + printf("There were %d failures\n", ares_errors); + } + LOGF("ares_gethostbyname: %.0f req/s\n", + 1e9 * ares_callbacks / (double)(end_time - start_time)); + + return 0; +} diff --git a/node-v0.8.14/deps/uv/test/benchmark-fs-stat.c b/node-v0.8.14/deps/uv/test/benchmark-fs-stat.c new file mode 100644 index 0000000..53aa60b --- /dev/null +++ b/node-v0.8.14/deps/uv/test/benchmark-fs-stat.c @@ -0,0 +1,164 @@ +/* Copyright Joyent, Inc. and other Node contributors. All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ + +#include "task.h" +#include "uv.h" + +#include +#include + +#define NUM_SYNC_REQS (10 * 1e5) +#define NUM_ASYNC_REQS (1 * 1e5) +#define MAX_CONCURRENT_REQS 32 + +#define sync_stat(req, path) \ + do { \ + uv_fs_stat(uv_default_loop(), (req), (path), NULL); \ + uv_fs_req_cleanup((req)); \ + } \ + while (0) + +struct async_req { + const char* path; + uv_fs_t fs_req; + int* count; +}; + + +static const char* fmt(double d) { + uint64_t v; + char* p; + + p = (char *) calloc(1, 32) + 31; /* leaks memory */ + v = d; + +#if 0 /* works but we don't care about fractional precision */ + if (d - v >= 0.01) { + *--p = '0' + (uint64_t) (d * 100) % 10; + *--p = '0' + (uint64_t) (d * 10) % 10; + *--p = '.'; + } +#endif + + if (v == 0) + *--p = '0'; + + while (v) { + if (v) *--p = '0' + (v % 10), v /= 10; + if (v) *--p = '0' + (v % 10), v /= 10; + if (v) *--p = '0' + (v % 10), v /= 10; + if (v) *--p = ','; + } + + return p; +} + + +static void warmup(const char* path) { + uv_fs_t reqs[MAX_CONCURRENT_REQS]; + int i; + + /* warm up the thread pool */ + for (i = 0; i < ARRAY_SIZE(reqs); i++) + uv_fs_stat(uv_default_loop(), reqs + i, path, uv_fs_req_cleanup); + + uv_run(uv_default_loop()); + + /* warm up the OS dirent cache */ + for (i = 0; i < 16; i++) + sync_stat(reqs + 0, path); +} + + +static void sync_bench(const char* path) { + uint64_t before; + uint64_t after; + uv_fs_t req; + int i; + + /* do the sync benchmark */ + before = uv_hrtime(); + + for (i = 0; i < NUM_SYNC_REQS; i++) + sync_stat(&req, path); + + after = uv_hrtime(); + + printf("%s stats (sync): %.2fs (%s/s)\n", + fmt(1.0 * NUM_SYNC_REQS), + (after - before) / 1e9, + fmt((1.0 * NUM_SYNC_REQS) / ((after - before) / 1e9))); + fflush(stdout); +} + + +static void stat_cb(uv_fs_t* fs_req) { + struct async_req* req = container_of(fs_req, struct async_req, fs_req); + uv_fs_req_cleanup(&req->fs_req); + if (*req->count == 0) return; + uv_fs_stat(uv_default_loop(), &req->fs_req, req->path, stat_cb); + (*req->count)--; +} + + +static void async_bench(const char* path) { + struct async_req reqs[MAX_CONCURRENT_REQS]; + struct async_req* req; + uint64_t before; + uint64_t after; + int count; + int i; + + for (i = 1; i <= MAX_CONCURRENT_REQS; i++) { + count = NUM_ASYNC_REQS; + + for (req = reqs; req < reqs + i; req++) { + req->path = path; + req->count = &count; + uv_fs_stat(uv_default_loop(), &req->fs_req, req->path, stat_cb); + } + + before = uv_hrtime(); + uv_run(uv_default_loop()); + after = uv_hrtime(); + + printf("%s stats (%d concurrent): %.2fs (%s/s)\n", + fmt(1.0 * NUM_ASYNC_REQS), + i, + (after - before) / 1e9, + fmt((1.0 * NUM_ASYNC_REQS) / ((after - before) / 1e9))); + fflush(stdout); + } +} + + +/* This benchmark aims to measure the overhead of doing I/O syscalls from + * the thread pool. The stat() syscall was chosen because its results are + * easy for the operating system to cache, taking the actual I/O overhead + * out of the equation. + */ +BENCHMARK_IMPL(fs_stat) { + const char path[] = "."; + warmup(path); + sync_bench(path); + async_bench(path); + return 0; +} diff --git a/node-v0.8.14/deps/uv/test/benchmark-getaddrinfo.c b/node-v0.8.14/deps/uv/test/benchmark-getaddrinfo.c new file mode 100644 index 0000000..892c14d --- /dev/null +++ b/node-v0.8.14/deps/uv/test/benchmark-getaddrinfo.c @@ -0,0 +1,94 @@ +/* Copyright Joyent, Inc. and other Node contributors. All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ + +#include "uv.h" +#include "task.h" + +#include +#include +#include /* strlen */ + + +#define CONCURRENT_CALLS 10 +#define TOTAL_CALLS 10000 + +const char* name = "localhost"; + +static uv_loop_t* loop; + +static uv_getaddrinfo_t handles[CONCURRENT_CALLS]; + +static int calls_initiated = 0; +static int calls_completed = 0; +static int64_t start_time; +static int64_t end_time; + + +static void getaddrinfo_initiate(uv_getaddrinfo_t* handle); + + +static void getaddrinfo_cb(uv_getaddrinfo_t* handle, int status, + struct addrinfo* res) { + ASSERT(status == 0); + calls_completed++; + if (calls_initiated < TOTAL_CALLS) { + getaddrinfo_initiate(handle); + } + + uv_freeaddrinfo(res); +} + + +static void getaddrinfo_initiate(uv_getaddrinfo_t* handle) { + int r; + + calls_initiated++; + + r = uv_getaddrinfo(loop, handle, &getaddrinfo_cb, name, NULL, NULL); + ASSERT(r == 0); +} + + +BENCHMARK_IMPL(getaddrinfo) { + int i; + + loop = uv_default_loop(); + + uv_update_time(loop); + start_time = uv_now(loop); + + for (i = 0; i < CONCURRENT_CALLS; i++) { + getaddrinfo_initiate(&handles[i]); + } + + uv_run(loop); + + uv_update_time(loop); + end_time = uv_now(loop); + + ASSERT(calls_initiated == TOTAL_CALLS); + ASSERT(calls_completed == TOTAL_CALLS); + + LOGF("getaddrinfo: %.0f req/s\n", + (double) calls_completed / (double) (end_time - start_time) * 1000.0); + + return 0; +} diff --git a/node-v0.8.14/deps/uv/test/benchmark-list.h b/node-v0.8.14/deps/uv/test/benchmark-list.h new file mode 100644 index 0000000..2e24682 --- /dev/null +++ b/node-v0.8.14/deps/uv/test/benchmark-list.h @@ -0,0 +1,114 @@ +/* Copyright Joyent, Inc. and other Node contributors. All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ + +BENCHMARK_DECLARE (sizes) +BENCHMARK_DECLARE (loop_count) +BENCHMARK_DECLARE (loop_count_timed) +BENCHMARK_DECLARE (ping_pongs) +BENCHMARK_DECLARE (tcp_write_batch) +BENCHMARK_DECLARE (tcp4_pound_100) +BENCHMARK_DECLARE (tcp4_pound_1000) +BENCHMARK_DECLARE (pipe_pound_100) +BENCHMARK_DECLARE (pipe_pound_1000) +BENCHMARK_DECLARE (tcp_pump100_client) +BENCHMARK_DECLARE (tcp_pump1_client) +BENCHMARK_DECLARE (pipe_pump100_client) +BENCHMARK_DECLARE (pipe_pump1_client) +BENCHMARK_DECLARE (udp_packet_storm_1v1) +BENCHMARK_DECLARE (udp_packet_storm_1v10) +BENCHMARK_DECLARE (udp_packet_storm_1v100) +BENCHMARK_DECLARE (udp_packet_storm_1v1000) +BENCHMARK_DECLARE (udp_packet_storm_10v10) +BENCHMARK_DECLARE (udp_packet_storm_10v100) +BENCHMARK_DECLARE (udp_packet_storm_10v1000) +BENCHMARK_DECLARE (udp_packet_storm_100v100) +BENCHMARK_DECLARE (udp_packet_storm_100v1000) +BENCHMARK_DECLARE (udp_packet_storm_1000v1000) +BENCHMARK_DECLARE (gethostbyname) +BENCHMARK_DECLARE (getaddrinfo) +BENCHMARK_DECLARE (fs_stat) +BENCHMARK_DECLARE (spawn) +BENCHMARK_DECLARE (thread_create) +BENCHMARK_DECLARE (million_timers) +HELPER_DECLARE (tcp4_blackhole_server) +HELPER_DECLARE (tcp_pump_server) +HELPER_DECLARE (pipe_pump_server) +HELPER_DECLARE (tcp4_echo_server) +HELPER_DECLARE (pipe_echo_server) +HELPER_DECLARE (dns_server) + +TASK_LIST_START + BENCHMARK_ENTRY (sizes) + BENCHMARK_ENTRY (loop_count) + BENCHMARK_ENTRY (loop_count_timed) + + BENCHMARK_ENTRY (ping_pongs) + BENCHMARK_HELPER (ping_pongs, tcp4_echo_server) + + BENCHMARK_ENTRY (tcp_write_batch) + BENCHMARK_HELPER (tcp_write_batch, tcp4_blackhole_server) + + BENCHMARK_ENTRY (tcp_pump100_client) + BENCHMARK_HELPER (tcp_pump100_client, tcp_pump_server) + + BENCHMARK_ENTRY (tcp_pump1_client) + BENCHMARK_HELPER (tcp_pump1_client, tcp_pump_server) + + BENCHMARK_ENTRY (tcp4_pound_100) + BENCHMARK_HELPER (tcp4_pound_100, tcp4_echo_server) + + BENCHMARK_ENTRY (tcp4_pound_1000) + BENCHMARK_HELPER (tcp4_pound_1000, tcp4_echo_server) + + BENCHMARK_ENTRY (pipe_pump100_client) + BENCHMARK_HELPER (pipe_pump100_client, pipe_pump_server) + + BENCHMARK_ENTRY (pipe_pump1_client) + BENCHMARK_HELPER (pipe_pump1_client, pipe_pump_server) + + BENCHMARK_ENTRY (pipe_pound_100) + BENCHMARK_HELPER (pipe_pound_100, pipe_echo_server) + + BENCHMARK_ENTRY (pipe_pound_1000) + BENCHMARK_HELPER (pipe_pound_1000, pipe_echo_server) + + BENCHMARK_ENTRY (udp_packet_storm_1v1) + BENCHMARK_ENTRY (udp_packet_storm_1v10) + BENCHMARK_ENTRY (udp_packet_storm_1v100) + BENCHMARK_ENTRY (udp_packet_storm_1v1000) + BENCHMARK_ENTRY (udp_packet_storm_10v10) + BENCHMARK_ENTRY (udp_packet_storm_10v100) + BENCHMARK_ENTRY (udp_packet_storm_10v1000) + BENCHMARK_ENTRY (udp_packet_storm_100v100) + BENCHMARK_ENTRY (udp_packet_storm_100v1000) + BENCHMARK_ENTRY (udp_packet_storm_1000v1000) + + BENCHMARK_ENTRY (gethostbyname) + BENCHMARK_HELPER (gethostbyname, dns_server) + + BENCHMARK_ENTRY (getaddrinfo) + + BENCHMARK_ENTRY (fs_stat) + + BENCHMARK_ENTRY (spawn) + BENCHMARK_ENTRY (thread_create) + BENCHMARK_ENTRY (million_timers) +TASK_LIST_END diff --git a/node-v0.8.14/deps/uv/test/benchmark-loop-count.c b/node-v0.8.14/deps/uv/test/benchmark-loop-count.c new file mode 100644 index 0000000..a58181a --- /dev/null +++ b/node-v0.8.14/deps/uv/test/benchmark-loop-count.c @@ -0,0 +1,88 @@ +/* Copyright Joyent, Inc. and other Node contributors. All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ + +#include "task.h" +#include "uv.h" + +#include +#include + +#define NUM_TICKS (2 * 1000 * 1000) + +static unsigned long ticks; +static uv_idle_t idle_handle; +static uv_timer_t timer_handle; + + +static void idle_cb(uv_idle_t* handle, int status) { + if (++ticks == NUM_TICKS) + uv_idle_stop(handle); +} + + +static void idle2_cb(uv_idle_t* handle, int status) { + ticks++; +} + + +static void timer_cb(uv_timer_t* handle, int status) { + uv_idle_stop(&idle_handle); + uv_timer_stop(&timer_handle); +} + + +BENCHMARK_IMPL(loop_count) { + uv_loop_t* loop = uv_default_loop(); + uint64_t ns; + + uv_idle_init(loop, &idle_handle); + uv_idle_start(&idle_handle, idle_cb); + + ns = uv_hrtime(); + uv_run(loop); + ns = uv_hrtime() - ns; + + ASSERT(ticks == NUM_TICKS); + + LOGF("loop_count: %d ticks in %.2fs (%.0f/s)\n", + NUM_TICKS, + ns / 1e9, + NUM_TICKS / (ns / 1e9)); + + return 0; +} + + +BENCHMARK_IMPL(loop_count_timed) { + uv_loop_t* loop = uv_default_loop(); + + uv_idle_init(loop, &idle_handle); + uv_idle_start(&idle_handle, idle2_cb); + + uv_timer_init(loop, &timer_handle); + uv_timer_start(&timer_handle, timer_cb, 5000, 0); + + uv_run(loop); + + LOGF("loop_count: %lu ticks (%.0f ticks/s)\n", ticks, ticks / 5.0); + + return 0; +} diff --git a/node-v0.8.14/deps/uv/test/benchmark-million-timers.c b/node-v0.8.14/deps/uv/test/benchmark-million-timers.c new file mode 100644 index 0000000..ae56b2b --- /dev/null +++ b/node-v0.8.14/deps/uv/test/benchmark-million-timers.c @@ -0,0 +1,65 @@ +/* Copyright Joyent, Inc. and other Node contributors. All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ + +#include "task.h" +#include "uv.h" + +#define NUM_TIMERS (1000 * 1000) + +static int timer_cb_called; + + +static void timer_cb(uv_timer_t* handle, int status) { + timer_cb_called++; +} + + +BENCHMARK_IMPL(million_timers) { + uv_timer_t* timers; + uv_loop_t* loop; + uint64_t before; + uint64_t after; + int timeout; + int i; + + timers = malloc(NUM_TIMERS * sizeof(timers[0])); + ASSERT(timers != NULL); + + loop = uv_default_loop(); + timeout = 0; + + for (i = 0; i < NUM_TIMERS; i++) { + if (i % 1000 == 0) timeout++; + ASSERT(0 == uv_timer_init(loop, timers + i)); + ASSERT(0 == uv_timer_start(timers + i, timer_cb, timeout, 0)); + } + + before = uv_hrtime(); + ASSERT(0 == uv_run(loop)); + after = uv_hrtime(); + + ASSERT(timer_cb_called == NUM_TIMERS); + free(timers); + + LOGF("%.2f seconds\n", (after - before) / 1e9); + + return 0; +} diff --git a/node-v0.8.14/deps/uv/test/benchmark-ping-pongs.c b/node-v0.8.14/deps/uv/test/benchmark-ping-pongs.c new file mode 100644 index 0000000..d42e706 --- /dev/null +++ b/node-v0.8.14/deps/uv/test/benchmark-ping-pongs.c @@ -0,0 +1,213 @@ +/* Copyright Joyent, Inc. and other Node contributors. All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ + +#include "uv.h" +#include "task.h" + +#include +#include +#include /* strlen */ + +/* Run the benchmark for this many ms */ +#define TIME 5000 + + +typedef struct { + int pongs; + int state; + uv_tcp_t tcp; + uv_connect_t connect_req; + uv_shutdown_t shutdown_req; +} pinger_t; + +typedef struct buf_s { + uv_buf_t uv_buf_t; + struct buf_s* next; +} buf_t; + + +static char PING[] = "PING\n"; + +static uv_loop_t* loop; + +static buf_t* buf_freelist = NULL; +static int pinger_shutdown_cb_called; +static int completed_pingers = 0; +static int64_t start_time; + + +static uv_buf_t buf_alloc(uv_handle_t* tcp, size_t size) { + buf_t* ab; + + ab = buf_freelist; + + if (ab != NULL) { + buf_freelist = ab->next; + return ab->uv_buf_t; + } + + ab = (buf_t*) malloc(size + sizeof *ab); + ab->uv_buf_t.len = size; + ab->uv_buf_t.base = ((char*) ab) + sizeof *ab; + + return ab->uv_buf_t; +} + + +static void buf_free(uv_buf_t uv_buf_t) { + buf_t* ab = (buf_t*) (uv_buf_t.base - sizeof *ab); + + ab->next = buf_freelist; + buf_freelist = ab; +} + + +static void pinger_close_cb(uv_handle_t* handle) { + pinger_t* pinger; + + pinger = (pinger_t*)handle->data; + LOGF("ping_pongs: %d roundtrips/s\n", (1000 * pinger->pongs) / TIME); + + free(pinger); + + completed_pingers++; +} + + +static void pinger_write_cb(uv_write_t* req, int status) { + ASSERT(status == 0); + + free(req); +} + + +static void pinger_write_ping(pinger_t* pinger) { + uv_write_t* req; + uv_buf_t buf; + + buf.base = (char*)&PING; + buf.len = strlen(PING); + + req = malloc(sizeof *req); + if (uv_write(req, (uv_stream_t*) &pinger->tcp, &buf, 1, pinger_write_cb)) { + FATAL("uv_write failed"); + } +} + + +static void pinger_shutdown_cb(uv_shutdown_t* req, int status) { + ASSERT(status == 0); + pinger_shutdown_cb_called++; + + /* + * The close callback has not been triggered yet. We must wait for EOF + * until we close the connection. + */ + ASSERT(completed_pingers == 0); +} + + +static void pinger_read_cb(uv_stream_t* tcp, ssize_t nread, uv_buf_t buf) { + ssize_t i; + pinger_t* pinger; + + pinger = (pinger_t*)tcp->data; + + if (nread < 0) { + ASSERT(uv_last_error(loop).code == UV_EOF); + + if (buf.base) { + buf_free(buf); + } + + ASSERT(pinger_shutdown_cb_called == 1); + uv_close((uv_handle_t*)tcp, pinger_close_cb); + + return; + } + + /* Now we count the pings */ + for (i = 0; i < nread; i++) { + ASSERT(buf.base[i] == PING[pinger->state]); + pinger->state = (pinger->state + 1) % (sizeof(PING) - 1); + if (pinger->state == 0) { + pinger->pongs++; + if (uv_now(loop) - start_time > TIME) { + uv_shutdown(&pinger->shutdown_req, (uv_stream_t*) tcp, pinger_shutdown_cb); + break; + } else { + pinger_write_ping(pinger); + } + } + } + + buf_free(buf); +} + + +static void pinger_connect_cb(uv_connect_t* req, int status) { + pinger_t *pinger = (pinger_t*)req->handle->data; + + ASSERT(status == 0); + + pinger_write_ping(pinger); + + if (uv_read_start(req->handle, buf_alloc, pinger_read_cb)) { + FATAL("uv_read_start failed"); + } +} + + +static void pinger_new() { + int r; + struct sockaddr_in client_addr = uv_ip4_addr("0.0.0.0", 0); + struct sockaddr_in server_addr = uv_ip4_addr("127.0.0.1", TEST_PORT); + pinger_t *pinger; + + pinger = (pinger_t*)malloc(sizeof(*pinger)); + pinger->state = 0; + pinger->pongs = 0; + + /* Try to connect to the server and do NUM_PINGS ping-pongs. */ + r = uv_tcp_init(loop, &pinger->tcp); + ASSERT(!r); + + pinger->tcp.data = pinger; + + uv_tcp_bind(&pinger->tcp, client_addr); + + r = uv_tcp_connect(&pinger->connect_req, &pinger->tcp, server_addr, pinger_connect_cb); + ASSERT(!r); +} + + +BENCHMARK_IMPL(ping_pongs) { + loop = uv_default_loop(); + + start_time = uv_now(loop); + + pinger_new(); + uv_run(loop); + + ASSERT(completed_pingers == 1); + + return 0; +} diff --git a/node-v0.8.14/deps/uv/test/benchmark-pound.c b/node-v0.8.14/deps/uv/test/benchmark-pound.c new file mode 100644 index 0000000..5c29a05 --- /dev/null +++ b/node-v0.8.14/deps/uv/test/benchmark-pound.c @@ -0,0 +1,324 @@ +/* Copyright Joyent, Inc. and other Node contributors. All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ + +#include "task.h" +#include "uv.h" + +/* Update this is you're going to run > 1000 concurrent requests. */ +#define MAX_CONNS 1000 + +#undef NANOSEC +#define NANOSEC ((uint64_t) 1e9) + +#undef DEBUG +#define DEBUG 0 + +struct conn_rec_s; + +typedef void (*setup_fn)(int num, void* arg); +typedef void (*make_connect_fn)(struct conn_rec_s* conn); +typedef int (*connect_fn)(int num, make_connect_fn make_connect, void* arg); + +/* Base class for tcp_conn_rec and pipe_conn_rec. + * The ordering of fields matters! + */ +typedef struct conn_rec_s { + int i; + uv_connect_t conn_req; + uv_write_t write_req; + make_connect_fn make_connect; + uv_stream_t stream; +} conn_rec; + +typedef struct { + int i; + uv_connect_t conn_req; + uv_write_t write_req; + make_connect_fn make_connect; + uv_tcp_t stream; +} tcp_conn_rec; + +typedef struct { + int i; + uv_connect_t conn_req; + uv_write_t write_req; + make_connect_fn make_connect; + uv_pipe_t stream; +} pipe_conn_rec; + +static char buffer[] = "QS"; + +static uv_loop_t* loop; + +static tcp_conn_rec tcp_conns[MAX_CONNS]; +static pipe_conn_rec pipe_conns[MAX_CONNS]; + +static uint64_t start; /* in ms */ +static int closed_streams; +static int conns_failed; + +static uv_buf_t alloc_cb(uv_handle_t* handle, size_t suggested_size); +static void connect_cb(uv_connect_t* conn_req, int status); +static void read_cb(uv_stream_t* stream, ssize_t nread, uv_buf_t buf); +static void close_cb(uv_handle_t* handle); + + +static uv_buf_t alloc_cb(uv_handle_t* handle, size_t suggested_size) { + static char slab[65536]; + uv_buf_t buf; + buf.base = slab; + buf.len = sizeof(slab); + return buf; +} + + +static void after_write(uv_write_t* req, int status) { + if (status != 0) { + fprintf(stderr, "write error %s\n", uv_err_name(uv_last_error(loop))); + uv_close((uv_handle_t*)req->handle, close_cb); + conns_failed++; + return; + } +} + + +static void connect_cb(uv_connect_t* req, int status) { + conn_rec* conn; + uv_buf_t buf; + int r; + + if (status != 0) { +#if DEBUG + fprintf(stderr, + "connect error %s\n", + uv_err_name(uv_last_error(uv_default_loop()))); +#endif + uv_close((uv_handle_t*)req->handle, close_cb); + conns_failed++; + return; + } + + ASSERT(req != NULL); + ASSERT(status == 0); + + conn = (conn_rec*)req->data; + ASSERT(conn != NULL); + +#if DEBUG + printf("connect_cb %d\n", conn->i); +#endif + + r = uv_read_start(&conn->stream, alloc_cb, read_cb); + ASSERT(r == 0); + + buf.base = buffer; + buf.len = sizeof(buffer) - 1; + + r = uv_write(&conn->write_req, &conn->stream, &buf, 1, after_write); + ASSERT(r == 0); +} + + +static void read_cb(uv_stream_t* stream, ssize_t nread, uv_buf_t buf) { + uv_err_t err = uv_last_error(loop); + + ASSERT(stream != NULL); + +#if DEBUG + printf("read_cb %d\n", p->i); +#endif + + uv_close((uv_handle_t*)stream, close_cb); + + if (nread == -1) { + if (err.code == UV_EOF) { + ; + } else if (err.code == UV_ECONNRESET) { + conns_failed++; + } else { + fprintf(stderr, "read error %s\n", uv_err_name(uv_last_error(loop))); + ASSERT(0); + } + } +} + + +static void close_cb(uv_handle_t* handle) { + conn_rec* p = (conn_rec*)handle->data; + + ASSERT(handle != NULL); + closed_streams++; + +#if DEBUG + printf("close_cb %d\n", p->i); +#endif + + if (uv_now(loop) - start < 10000) { + p->make_connect(p); + } +} + + +static void tcp_do_setup(int num, void* arg) { + int i; + + for (i = 0; i < num; i++) { + tcp_conns[i].i = i; + } +} + + +static void pipe_do_setup(int num, void* arg) { + int i; + + for (i = 0; i < num; i++) { + pipe_conns[i].i = i; + } +} + + +static void tcp_make_connect(conn_rec* p) { + struct sockaddr_in addr; + int r; + + r = uv_tcp_init(loop, (uv_tcp_t*)&p->stream); + ASSERT(r == 0); + + addr = uv_ip4_addr("127.0.0.1", TEST_PORT); + + r = uv_tcp_connect(&((tcp_conn_rec*)p)->conn_req, (uv_tcp_t*)&p->stream, addr, connect_cb); + if (r) { + fprintf(stderr, "uv_tcp_connect error %s\n", + uv_err_name(uv_last_error(loop))); + ASSERT(0); + } + +#if DEBUG + printf("make connect %d\n", p->i); +#endif + + p->conn_req.data = p; + p->write_req.data = p; + p->stream.data = p; +} + + +static void pipe_make_connect(conn_rec* p) { + int r; + + r = uv_pipe_init(loop, (uv_pipe_t*)&p->stream, 0); + ASSERT(r == 0); + + uv_pipe_connect(&((pipe_conn_rec*)p)->conn_req, (uv_pipe_t*)&p->stream, TEST_PIPENAME, connect_cb); + +#if DEBUG + printf("make connect %d\n", p->i); +#endif + + p->conn_req.data = p; + p->write_req.data = p; + p->stream.data = p; +} + + +static int tcp_do_connect(int num, make_connect_fn make_connect, void* arg) { + int i; + + for (i = 0; i < num; i++) { + tcp_make_connect((conn_rec*)&tcp_conns[i]); + tcp_conns[i].make_connect = make_connect; + } + + return 0; +} + + +static int pipe_do_connect(int num, make_connect_fn make_connect, void* arg) { + int i; + + for (i = 0; i < num; i++) { + pipe_make_connect((conn_rec*)&pipe_conns[i]); + pipe_conns[i].make_connect = make_connect; + } + + return 0; +} + + +static int pound_it(int concurrency, + const char* type, + setup_fn do_setup, + connect_fn do_connect, + make_connect_fn make_connect, + void* arg) { + double secs; + int r; + uint64_t start_time; /* in ns */ + uint64_t end_time; + + loop = uv_default_loop(); + + uv_update_time(loop); + start = uv_now(loop); + + /* Run benchmark for at least five seconds. */ + start_time = uv_hrtime(); + + do_setup(concurrency, arg); + + r = do_connect(concurrency, make_connect, arg); + ASSERT(!r); + + uv_run(loop); + + end_time = uv_hrtime(); + + /* Number of fractional seconds it took to run the benchmark. */ + secs = (double)(end_time - start_time) / NANOSEC; + + LOGF("%s-conn-pound-%d: %.0f accepts/s (%d failed)\n", + type, + concurrency, + closed_streams / secs, + conns_failed); + + return 0; +} + + +BENCHMARK_IMPL(tcp4_pound_100) { + return pound_it(100, "tcp", tcp_do_setup, tcp_do_connect, tcp_make_connect, NULL); +} + + +BENCHMARK_IMPL(tcp4_pound_1000) { + return pound_it(1000, "tcp", tcp_do_setup, tcp_do_connect, tcp_make_connect, NULL); +} + + +BENCHMARK_IMPL(pipe_pound_100) { + return pound_it(100, "pipe", pipe_do_setup, pipe_do_connect, pipe_make_connect, NULL); +} + + +BENCHMARK_IMPL(pipe_pound_1000) { + return pound_it(1000, "pipe", pipe_do_setup, pipe_do_connect, pipe_make_connect, NULL); +} diff --git a/node-v0.8.14/deps/uv/test/benchmark-pump.c b/node-v0.8.14/deps/uv/test/benchmark-pump.c new file mode 100644 index 0000000..52f2957 --- /dev/null +++ b/node-v0.8.14/deps/uv/test/benchmark-pump.c @@ -0,0 +1,462 @@ +/* Copyright Joyent, Inc. and other Node contributors. All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ + +#include "task.h" +#include "uv.h" + +#include +#include + + +static int TARGET_CONNECTIONS; +#define WRITE_BUFFER_SIZE 8192 +#define MAX_SIMULTANEOUS_CONNECTS 100 + +#define PRINT_STATS 0 +#define STATS_INTERVAL 1000 /* msec */ +#define STATS_COUNT 5 + + +static void do_write(uv_stream_t*); +static void maybe_connect_some(); + +static uv_req_t* req_alloc(); +static void req_free(uv_req_t* uv_req); + +static uv_buf_t buf_alloc(uv_handle_t*, size_t size); +static void buf_free(uv_buf_t uv_buf_t); + +static uv_loop_t* loop; + +static uv_tcp_t tcpServer; +static uv_pipe_t pipeServer; +static uv_stream_t* server; +static struct sockaddr_in listen_addr; +static struct sockaddr_in connect_addr; + +static int64_t start_time; + +static int max_connect_socket = 0; +static int max_read_sockets = 0; +static int read_sockets = 0; +static int write_sockets = 0; + +static int64_t nrecv = 0; +static int64_t nrecv_total = 0; +static int64_t nsent = 0; +static int64_t nsent_total = 0; + +static int stats_left = 0; + +static char write_buffer[WRITE_BUFFER_SIZE]; + +/* Make this as large as you need. */ +#define MAX_WRITE_HANDLES 1000 + +static stream_type type; + +static uv_tcp_t tcp_write_handles[MAX_WRITE_HANDLES]; +static uv_pipe_t pipe_write_handles[MAX_WRITE_HANDLES]; + +static uv_timer_t timer_handle; + + +static double gbit(int64_t bytes, int64_t passed_ms) { + double gbits = ((double)bytes / (1024 * 1024 * 1024)) * 8; + return gbits / ((double)passed_ms / 1000); +} + + +static void show_stats(uv_timer_t* handle, int status) { + int64_t diff; + int i; + +#if PRINT_STATS + LOGF("connections: %d, write: %.1f gbit/s\n", + write_sockets, + gbit(nsent, STATS_INTERVAL)); +#endif + + /* Exit if the show is over */ + if (!--stats_left) { + + uv_update_time(loop); + diff = uv_now(loop) - start_time; + + LOGF("%s_pump%d_client: %.1f gbit/s\n", type == TCP ? "tcp" : "pipe", write_sockets, + gbit(nsent_total, diff)); + + for (i = 0; i < write_sockets; i++) { + uv_close(type == TCP ? (uv_handle_t*)&tcp_write_handles[i] : (uv_handle_t*)&pipe_write_handles[i], NULL); + } + + exit(0); + } + + /* Reset read and write counters */ + nrecv = 0; + nsent = 0; +} + + +static void read_show_stats() { + int64_t diff; + + uv_update_time(loop); + diff = uv_now(loop) - start_time; + + LOGF("%s_pump%d_server: %.1f gbit/s\n", type == TCP ? "tcp" : "pipe", max_read_sockets, + gbit(nrecv_total, diff)); +} + + + +void write_sockets_close_cb(uv_handle_t* handle) { + /* If any client closes, the process is done. */ + exit(0); +} + + +void read_sockets_close_cb(uv_handle_t* handle) { + free(handle); + read_sockets--; + + /* If it's past the first second and everyone has closed their connection + * Then print stats. + */ + if (uv_now(loop) - start_time > 1000 && read_sockets == 0) { + read_show_stats(); + uv_close((uv_handle_t*)server, NULL); + } +} + + +static void start_stats_collection() { + int r; + + /* Show-stats timer */ + stats_left = STATS_COUNT; + r = uv_timer_init(loop, &timer_handle); + ASSERT(r == 0); + r = uv_timer_start(&timer_handle, show_stats, STATS_INTERVAL, STATS_INTERVAL); + ASSERT(r == 0); + + uv_update_time(loop); + start_time = uv_now(loop); +} + + +static void read_cb(uv_stream_t* stream, ssize_t bytes, uv_buf_t buf) { + if (nrecv_total == 0) { + ASSERT(start_time == 0); + uv_update_time(loop); + start_time = uv_now(loop); + } + + if (bytes < 0) { + uv_close((uv_handle_t*)stream, read_sockets_close_cb); + return; + } + + buf_free(buf); + + nrecv += bytes; + nrecv_total += bytes; +} + + +static void write_cb(uv_write_t* req, int status) { + ASSERT(status == 0); + + req_free((uv_req_t*) req); + + nsent += sizeof write_buffer; + nsent_total += sizeof write_buffer; + + do_write((uv_stream_t*) req->handle); +} + + +static void do_write(uv_stream_t* stream) { + uv_write_t* req; + uv_buf_t buf; + int r; + + buf.base = (char*) &write_buffer; + buf.len = sizeof write_buffer; + + while (stream->write_queue_size == 0) { + req = (uv_write_t*) req_alloc(); + r = uv_write(req, stream, &buf, 1, write_cb); + ASSERT(r == 0); + } +} + + +static void connect_cb(uv_connect_t* req, int status) { + int i; + + if (status) LOG(uv_strerror(uv_last_error(loop))); + ASSERT(status == 0); + + write_sockets++; + req_free((uv_req_t*) req); + + maybe_connect_some(); + + if (write_sockets == TARGET_CONNECTIONS) { + start_stats_collection(); + + /* Yay! start writing */ + for (i = 0; i < write_sockets; i++) { + do_write(type == TCP ? (uv_stream_t*)&tcp_write_handles[i] : (uv_stream_t*)&pipe_write_handles[i]); + } + } +} + + +static void maybe_connect_some() { + uv_connect_t* req; + uv_tcp_t* tcp; + uv_pipe_t* pipe; + int r; + + while (max_connect_socket < TARGET_CONNECTIONS && + max_connect_socket < write_sockets + MAX_SIMULTANEOUS_CONNECTS) { + if (type == TCP) { + tcp = &tcp_write_handles[max_connect_socket++]; + + r = uv_tcp_init(loop, tcp); + ASSERT(r == 0); + + req = (uv_connect_t*) req_alloc(); + r = uv_tcp_connect(req, tcp, connect_addr, connect_cb); + ASSERT(r == 0); + } else { + pipe = &pipe_write_handles[max_connect_socket++]; + + r = uv_pipe_init(loop, pipe, 0); + ASSERT(r == 0); + + req = (uv_connect_t*) req_alloc(); + uv_pipe_connect(req, pipe, TEST_PIPENAME, connect_cb); + } + } +} + + +static void connection_cb(uv_stream_t* s, int status) { + uv_stream_t* stream; + int r; + + ASSERT(server == s); + ASSERT(status == 0); + + if (type == TCP) { + stream = (uv_stream_t*)malloc(sizeof(uv_tcp_t)); + r = uv_tcp_init(loop, (uv_tcp_t*)stream); + ASSERT(r == 0); + } else { + stream = (uv_stream_t*)malloc(sizeof(uv_pipe_t)); + r = uv_pipe_init(loop, (uv_pipe_t*)stream, 0); + ASSERT(r == 0); + } + + r = uv_accept(s, stream); + ASSERT(r == 0); + + r = uv_read_start(stream, buf_alloc, read_cb); + ASSERT(r == 0); + + read_sockets++; + max_read_sockets++; +} + + +/* + * Request allocator + */ + +typedef struct req_list_s { + union uv_any_req uv_req; + struct req_list_s* next; +} req_list_t; + + +static req_list_t* req_freelist = NULL; + + +static uv_req_t* req_alloc() { + req_list_t* req; + + req = req_freelist; + if (req != NULL) { + req_freelist = req->next; + return (uv_req_t*) req; + } + + req = (req_list_t*) malloc(sizeof *req); + return (uv_req_t*) req; +} + + +static void req_free(uv_req_t* uv_req) { + req_list_t* req = (req_list_t*) uv_req; + + req->next = req_freelist; + req_freelist = req; +} + + +/* + * Buffer allocator + */ + +typedef struct buf_list_s { + uv_buf_t uv_buf_t; + struct buf_list_s* next; +} buf_list_t; + + +static buf_list_t* buf_freelist = NULL; + + +static uv_buf_t buf_alloc(uv_handle_t* handle, size_t size) { + buf_list_t* buf; + + buf = buf_freelist; + if (buf != NULL) { + buf_freelist = buf->next; + return buf->uv_buf_t; + } + + buf = (buf_list_t*) malloc(size + sizeof *buf); + buf->uv_buf_t.len = (unsigned int)size; + buf->uv_buf_t.base = ((char*) buf) + sizeof *buf; + + return buf->uv_buf_t; +} + + +static void buf_free(uv_buf_t uv_buf_t) { + buf_list_t* buf = (buf_list_t*) (uv_buf_t.base - sizeof *buf); + + buf->next = buf_freelist; + buf_freelist = buf; +} + + +HELPER_IMPL(tcp_pump_server) { + int r; + + type = TCP; + loop = uv_default_loop(); + + listen_addr = uv_ip4_addr("0.0.0.0", TEST_PORT); + + /* Server */ + server = (uv_stream_t*)&tcpServer; + r = uv_tcp_init(loop, &tcpServer); + ASSERT(r == 0); + r = uv_tcp_bind(&tcpServer, listen_addr); + ASSERT(r == 0); + r = uv_listen((uv_stream_t*)&tcpServer, MAX_WRITE_HANDLES, connection_cb); + ASSERT(r == 0); + + uv_run(loop); + + return 0; +} + + +HELPER_IMPL(pipe_pump_server) { + int r; + type = PIPE; + + loop = uv_default_loop(); + + /* Server */ + server = (uv_stream_t*)&pipeServer; + r = uv_pipe_init(loop, &pipeServer, 0); + ASSERT(r == 0); + r = uv_pipe_bind(&pipeServer, TEST_PIPENAME); + ASSERT(r == 0); + r = uv_listen((uv_stream_t*)&pipeServer, MAX_WRITE_HANDLES, connection_cb); + ASSERT(r == 0); + + uv_run(loop); + + return 0; +} + + +void tcp_pump(int n) { + ASSERT(n <= MAX_WRITE_HANDLES); + TARGET_CONNECTIONS = n; + type = TCP; + + loop = uv_default_loop(); + + connect_addr = uv_ip4_addr("127.0.0.1", TEST_PORT); + + /* Start making connections */ + maybe_connect_some(); + + uv_run(loop); +} + + +void pipe_pump(int n) { + ASSERT(n <= MAX_WRITE_HANDLES); + TARGET_CONNECTIONS = n; + type = PIPE; + + loop = uv_default_loop(); + + /* Start making connections */ + maybe_connect_some(); + + uv_run(loop); +} + + +BENCHMARK_IMPL(tcp_pump100_client) { + tcp_pump(100); + return 0; +} + + +BENCHMARK_IMPL(tcp_pump1_client) { + tcp_pump(1); + return 0; +} + + +BENCHMARK_IMPL(pipe_pump100_client) { + pipe_pump(100); + return 0; +} + + +BENCHMARK_IMPL(pipe_pump1_client) { + pipe_pump(1); + return 0; +} diff --git a/node-v0.8.14/deps/uv/test/benchmark-sizes.c b/node-v0.8.14/deps/uv/test/benchmark-sizes.c new file mode 100644 index 0000000..8ccf10e --- /dev/null +++ b/node-v0.8.14/deps/uv/test/benchmark-sizes.c @@ -0,0 +1,45 @@ +/* Copyright Joyent, Inc. and other Node contributors. All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ + +#include "task.h" +#include "uv.h" + + +BENCHMARK_IMPL(sizes) { + LOGF("uv_shutdown_t: %u bytes\n", (unsigned int) sizeof(uv_shutdown_t)); + LOGF("uv_write_t: %u bytes\n", (unsigned int) sizeof(uv_write_t)); + LOGF("uv_connect_t: %u bytes\n", (unsigned int) sizeof(uv_connect_t)); + LOGF("uv_udp_send_t: %u bytes\n", (unsigned int) sizeof(uv_udp_send_t)); + LOGF("uv_tcp_t: %u bytes\n", (unsigned int) sizeof(uv_tcp_t)); + LOGF("uv_pipe_t: %u bytes\n", (unsigned int) sizeof(uv_pipe_t)); + LOGF("uv_tty_t: %u bytes\n", (unsigned int) sizeof(uv_tty_t)); + LOGF("uv_prepare_t: %u bytes\n", (unsigned int) sizeof(uv_prepare_t)); + LOGF("uv_check_t: %u bytes\n", (unsigned int) sizeof(uv_check_t)); + LOGF("uv_idle_t: %u bytes\n", (unsigned int) sizeof(uv_idle_t)); + LOGF("uv_async_t: %u bytes\n", (unsigned int) sizeof(uv_async_t)); + LOGF("uv_timer_t: %u bytes\n", (unsigned int) sizeof(uv_timer_t)); + LOGF("uv_fs_poll_t: %u bytes\n", (unsigned int) sizeof(uv_fs_poll_t)); + LOGF("uv_fs_event_t: %u bytes\n", (unsigned int) sizeof(uv_fs_event_t)); + LOGF("uv_process_t: %u bytes\n", (unsigned int) sizeof(uv_process_t)); + LOGF("uv_poll_t: %u bytes\n", (unsigned int) sizeof(uv_poll_t)); + LOGF("uv_loop_t: %u bytes\n", (unsigned int) sizeof(uv_loop_t)); + return 0; +} diff --git a/node-v0.8.14/deps/uv/test/benchmark-spawn.c b/node-v0.8.14/deps/uv/test/benchmark-spawn.c new file mode 100644 index 0000000..74cc3d2 --- /dev/null +++ b/node-v0.8.14/deps/uv/test/benchmark-spawn.c @@ -0,0 +1,162 @@ +/* Copyright Joyent, Inc. and other Node contributors. All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ + +/* This benchmark spawns itself 1000 times. */ + +#include "task.h" +#include "uv.h" + +static uv_loop_t* loop; + +static int N = 1000; +static int done; + +static uv_process_t process; +static uv_process_options_t options = { 0 }; +static char exepath[1024]; +static size_t exepath_size = 1024; +static char* args[3]; +static uv_pipe_t out; + +#define OUTPUT_SIZE 1024 +static char output[OUTPUT_SIZE]; +static int output_used; + +static int process_open; +static int pipe_open; + + +static void spawn(); + + +void maybe_spawn() { + if (process_open == 0 && pipe_open == 0) { + done++; + if (done < N) { + spawn(); + } + } +} + + +static void process_close_cb(uv_handle_t* handle) { + ASSERT(process_open == 1); + process_open = 0; + maybe_spawn(); +} + + +static void exit_cb(uv_process_t* process, int exit_status, int term_signal) { + ASSERT(exit_status == 42); + ASSERT(term_signal == 0); + uv_close((uv_handle_t*)process, process_close_cb); +} + + +uv_buf_t on_alloc(uv_handle_t* handle, size_t suggested_size) { + uv_buf_t buf; + buf.base = output + output_used; + buf.len = OUTPUT_SIZE - output_used; + return buf; +} + + +void pipe_close_cb(uv_handle_t* pipe) { + ASSERT(pipe_open == 1); + pipe_open = 0; + maybe_spawn(); +} + + +void on_read(uv_stream_t* pipe, ssize_t nread, uv_buf_t buf) { + uv_err_t err = uv_last_error(loop); + + if (nread > 0) { + ASSERT(pipe_open == 1); + output_used += nread; + } else if (nread < 0) { + if (err.code == UV_EOF) { + uv_close((uv_handle_t*)pipe, pipe_close_cb); + } + } +} + + +static void spawn() { + uv_stdio_container_t stdio[2]; + int r; + + ASSERT(process_open == 0); + ASSERT(pipe_open == 0); + + args[0] = exepath; + args[1] = "spawn_helper"; + args[2] = NULL; + options.file = exepath; + options.args = args; + options.exit_cb = exit_cb; + + uv_pipe_init(loop, &out, 0); + + options.stdio = stdio; + options.stdio_count = 2; + options.stdio[0].flags = UV_IGNORE; + options.stdio[1].flags = UV_CREATE_PIPE | UV_WRITABLE_PIPE; + options.stdio[1].data.stream = (uv_stream_t*)&out; + + r = uv_spawn(loop, &process, options); + ASSERT(r == 0); + + process_open = 1; + pipe_open = 1; + output_used = 0; + + r = uv_read_start((uv_stream_t*) &out, on_alloc, on_read); + ASSERT(r == 0); +} + + +BENCHMARK_IMPL(spawn) { + int r; + static int64_t start_time, end_time; + + loop = uv_default_loop(); + + r = uv_exepath(exepath, &exepath_size); + ASSERT(r == 0); + exepath[exepath_size] = '\0'; + + uv_update_time(loop); + start_time = uv_now(loop); + + spawn(); + + r = uv_run(loop); + ASSERT(r == 0); + + uv_update_time(loop); + end_time = uv_now(loop); + + LOGF("spawn: %.0f spawns/s\n", + (double) N / (double) (end_time - start_time) * 1000.0); + + return 0; +} diff --git a/node-v0.8.14/deps/uv/test/benchmark-tcp-write-batch.c b/node-v0.8.14/deps/uv/test/benchmark-tcp-write-batch.c new file mode 100644 index 0000000..0b15f44 --- /dev/null +++ b/node-v0.8.14/deps/uv/test/benchmark-tcp-write-batch.c @@ -0,0 +1,140 @@ +/* Copyright Joyent, Inc. and other Node contributors. All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ + +#include "uv.h" +#include "task.h" + +#include +#include + +#define WRITE_REQ_DATA "Hello, world." +#define NUM_WRITE_REQS (1000 * 1000) + +typedef struct { + uv_write_t req; + uv_buf_t buf; +} write_req; + + +static write_req* write_reqs; +static uv_tcp_t tcp_client; +static uv_connect_t connect_req; +static uv_shutdown_t shutdown_req; + +static int shutdown_cb_called = 0; +static int connect_cb_called = 0; +static int write_cb_called = 0; +static int close_cb_called = 0; + +static void connect_cb(uv_connect_t* req, int status); +static void write_cb(uv_write_t* req, int status); +static void shutdown_cb(uv_shutdown_t* req, int status); +static void close_cb(uv_handle_t* handle); + + +static void connect_cb(uv_connect_t* req, int status) { + write_req* w; + int i; + int r; + + ASSERT(req->handle == (uv_stream_t*)&tcp_client); + + for (i = 0; i < NUM_WRITE_REQS; i++) { + w = &write_reqs[i]; + r = uv_write(&w->req, req->handle, &w->buf, 1, write_cb); + ASSERT(r == 0); + } + + r = uv_shutdown(&shutdown_req, req->handle, shutdown_cb); + ASSERT(r == 0); + + connect_cb_called++; +} + + +static void write_cb(uv_write_t* req, int status) { + ASSERT(req != NULL); + ASSERT(status == 0); + write_cb_called++; +} + + +static void shutdown_cb(uv_shutdown_t* req, int status) { + ASSERT(req->handle == (uv_stream_t*)&tcp_client); + ASSERT(req->handle->write_queue_size == 0); + + uv_close((uv_handle_t*)req->handle, close_cb); + free(write_reqs); + + shutdown_cb_called++; +} + + +static void close_cb(uv_handle_t* handle) { + ASSERT(handle == (uv_handle_t*)&tcp_client); + close_cb_called++; +} + + +BENCHMARK_IMPL(tcp_write_batch) { + struct sockaddr_in addr; + uv_loop_t* loop; + uint64_t start; + uint64_t stop; + int i; + int r; + + write_reqs = malloc(sizeof(*write_reqs) * NUM_WRITE_REQS); + ASSERT(write_reqs != NULL); + + /* Prepare the data to write out. */ + for (i = 0; i < NUM_WRITE_REQS; i++) { + write_reqs[i].buf = uv_buf_init(WRITE_REQ_DATA, + sizeof(WRITE_REQ_DATA) - 1); + } + + loop = uv_default_loop(); + addr = uv_ip4_addr("127.0.0.1", TEST_PORT); + + r = uv_tcp_init(loop, &tcp_client); + ASSERT(r == 0); + + r = uv_tcp_connect(&connect_req, &tcp_client, addr, connect_cb); + ASSERT(r == 0); + + start = uv_hrtime(); + + r = uv_run(loop); + ASSERT(r == 0); + + stop = uv_hrtime(); + + ASSERT(connect_cb_called == 1); + ASSERT(write_cb_called == NUM_WRITE_REQS); + ASSERT(shutdown_cb_called == 1); + ASSERT(close_cb_called == 1); + + printf("%ld write requests in %.2fs.\n", + (long)NUM_WRITE_REQS, + (stop - start) / 10e8); + + return 0; +} diff --git a/node-v0.8.14/deps/uv/test/benchmark-thread.c b/node-v0.8.14/deps/uv/test/benchmark-thread.c new file mode 100644 index 0000000..b37a7fd --- /dev/null +++ b/node-v0.8.14/deps/uv/test/benchmark-thread.c @@ -0,0 +1,64 @@ +/* Copyright Joyent, Inc. and other Node contributors. All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ + +#include "uv.h" +#include "task.h" + +#include +#include + +#define NUM_THREADS (20 * 1000) + +static volatile int num_threads; + + +static void thread_entry(void* arg) { + ASSERT(arg == (void *) 42); + num_threads++; + /* FIXME write barrier? */ +} + + +BENCHMARK_IMPL(thread_create) { + uint64_t start_time; + double duration; + uv_thread_t tid; + int i, r; + + start_time = uv_hrtime(); + + for (i = 0; i < NUM_THREADS; i++) { + r = uv_thread_create(&tid, thread_entry, (void *) 42); + ASSERT(r == 0); + + r = uv_thread_join(&tid); + ASSERT(r == 0); + } + + duration = (uv_hrtime() - start_time) / 1e9; + + ASSERT(num_threads == NUM_THREADS); + + printf("%d threads created in %.2f seconds (%.0f/s)\n", + NUM_THREADS, duration, NUM_THREADS / duration); + + return 0; +} diff --git a/node-v0.8.14/deps/uv/test/benchmark-udp-packet-storm.c b/node-v0.8.14/deps/uv/test/benchmark-udp-packet-storm.c new file mode 100644 index 0000000..5941287 --- /dev/null +++ b/node-v0.8.14/deps/uv/test/benchmark-udp-packet-storm.c @@ -0,0 +1,247 @@ +/* Copyright Joyent, Inc. and other Node contributors. All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ + +#include "task.h" +#include "uv.h" + +#include +#include +#include + +#define EXPECTED "RANG TANG DING DONG I AM THE JAPANESE SANDMAN" /* "Take eight!" */ + +#define TEST_DURATION 5000 /* ms */ + +#define MAX_SENDERS 1000 +#define MAX_RECEIVERS 1000 + +#define BASE_PORT 12345 + +static uv_loop_t* loop; + +static int n_senders_; +static int n_receivers_; +static uv_udp_t senders[MAX_SENDERS]; +static uv_udp_t receivers[MAX_RECEIVERS]; +static uv_buf_t bufs[5]; + +static int send_cb_called; +static int recv_cb_called; +static int close_cb_called; +static int stopping = 0; + +typedef struct { + struct sockaddr_in addr; +} sender_state_t; + + +static uv_buf_t alloc_cb(uv_handle_t* handle, size_t suggested_size) { + static char slab[65536]; + ASSERT(suggested_size <= sizeof slab); + return uv_buf_init(slab, sizeof slab); +} + + +static void send_cb(uv_udp_send_t* req, int status) { + sender_state_t* ss; + int r; + + if (stopping) { + return; + } + + ASSERT(req != NULL); + ASSERT(status == 0); + + ss = req->data; + + r = uv_udp_send(req, req->handle, bufs, ARRAY_SIZE(bufs), ss->addr, send_cb); + ASSERT(r == 0); + + req->data = ss; + + send_cb_called++; +} + + +static void recv_cb(uv_udp_t* handle, + ssize_t nread, + uv_buf_t buf, + struct sockaddr* addr, + unsigned flags) { + if (nread == 0) + return; + + if (nread == -1) { + ASSERT(uv_last_error(loop).code == UV_EINTR); /* FIXME change error code */ + return; + } + + ASSERT(addr->sa_family == AF_INET); + ASSERT(!memcmp(buf.base, EXPECTED, nread)); + + recv_cb_called++; +} + + +static void close_cb(uv_handle_t* handle) { + ASSERT(handle != NULL); + close_cb_called++; +} + + +static void timeout_cb(uv_timer_t* timer, int status) { + int i; + + stopping = 1; + + for (i = 0; i < n_senders_; i++) + uv_close((uv_handle_t*)&senders[i], close_cb); + + for (i = 0; i < n_receivers_; i++) + uv_close((uv_handle_t*)&receivers[i], close_cb); +} + + +static int do_packet_storm(int n_senders, int n_receivers) { + uv_timer_t timeout; + sender_state_t *ss; + uv_udp_send_t* req; + uv_udp_t* handle; + int i; + int r; + + ASSERT(n_senders <= MAX_SENDERS); + ASSERT(n_receivers <= MAX_RECEIVERS); + + loop = uv_default_loop(); + + n_senders_ = n_senders; + n_receivers_ = n_receivers; + + r = uv_timer_init(loop, &timeout); + ASSERT(r == 0); + + r = uv_timer_start(&timeout, timeout_cb, TEST_DURATION, 0); + ASSERT(r == 0); + + /* Timer should not keep loop alive. */ + uv_unref((uv_handle_t*)&timeout); + + for (i = 0; i < n_receivers; i++) { + struct sockaddr_in addr; + handle = &receivers[i]; + + r = uv_udp_init(loop, handle); + ASSERT(r == 0); + + addr = uv_ip4_addr("0.0.0.0", BASE_PORT + i); + + r = uv_udp_bind(handle, addr, 0); + ASSERT(r == 0); + + r = uv_udp_recv_start(handle, alloc_cb, recv_cb); + ASSERT(r == 0); + } + + bufs[0] = uv_buf_init(EXPECTED + 0, 10); + bufs[1] = uv_buf_init(EXPECTED + 10, 10); + bufs[2] = uv_buf_init(EXPECTED + 20, 10); + bufs[3] = uv_buf_init(EXPECTED + 30, 10); + bufs[4] = uv_buf_init(EXPECTED + 40, 5); + + for (i = 0; i < n_senders; i++) { + handle = &senders[i]; + + r = uv_udp_init(loop, handle); + ASSERT(r == 0); + + req = malloc(sizeof(*req) + sizeof(*ss)); + + ss = (void*)(req + 1); + ss->addr = uv_ip4_addr("127.0.0.1", BASE_PORT + (i % n_receivers)); + + r = uv_udp_send(req, handle, bufs, ARRAY_SIZE(bufs), ss->addr, send_cb); + ASSERT(r == 0); + + req->data = ss; + } + + uv_run(loop); + + printf("udp_packet_storm_%dv%d: %.0f/s received, %.0f/s sent\n", + n_receivers, + n_senders, + recv_cb_called / (TEST_DURATION / 1000.0), + send_cb_called / (TEST_DURATION / 1000.0)); + + return 0; +} + + +BENCHMARK_IMPL(udp_packet_storm_1v1) { + return do_packet_storm(1, 1); +} + + +BENCHMARK_IMPL(udp_packet_storm_1v10) { + return do_packet_storm(1, 10); +} + + +BENCHMARK_IMPL(udp_packet_storm_1v100) { + return do_packet_storm(1, 100); +} + + +BENCHMARK_IMPL(udp_packet_storm_1v1000) { + return do_packet_storm(1, 1000); +} + + +BENCHMARK_IMPL(udp_packet_storm_10v10) { + return do_packet_storm(10, 10); +} + + +BENCHMARK_IMPL(udp_packet_storm_10v100) { + return do_packet_storm(10, 100); +} + + +BENCHMARK_IMPL(udp_packet_storm_10v1000) { + return do_packet_storm(10, 1000); +} + + +BENCHMARK_IMPL(udp_packet_storm_100v100) { + return do_packet_storm(100, 100); +} + + +BENCHMARK_IMPL(udp_packet_storm_100v1000) { + return do_packet_storm(100, 1000); +} + + +BENCHMARK_IMPL(udp_packet_storm_1000v1000) { + return do_packet_storm(1000, 1000); +} diff --git a/node-v0.8.14/deps/uv/test/blackhole-server.c b/node-v0.8.14/deps/uv/test/blackhole-server.c new file mode 100644 index 0000000..765bb32 --- /dev/null +++ b/node-v0.8.14/deps/uv/test/blackhole-server.c @@ -0,0 +1,118 @@ +/* Copyright Joyent, Inc. and other Node contributors. All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ + +#include "uv.h" +#include "task.h" + +#include +#include + +typedef struct { + uv_tcp_t handle; + uv_shutdown_t shutdown_req; +} conn_rec; + +static uv_tcp_t tcp_server; + +static void connection_cb(uv_stream_t* stream, int status); +static uv_buf_t alloc_cb(uv_handle_t* handle, size_t suggested_size); +static void read_cb(uv_stream_t* stream, ssize_t nread, uv_buf_t buf); +static void shutdown_cb(uv_shutdown_t* req, int status); +static void close_cb(uv_handle_t* handle); + + +static void connection_cb(uv_stream_t* stream, int status) { + conn_rec* conn; + int r; + + ASSERT(status == 0); + ASSERT(stream == (uv_stream_t*)&tcp_server); + + conn = malloc(sizeof *conn); + ASSERT(conn != NULL); + + r = uv_tcp_init(stream->loop, &conn->handle); + ASSERT(r == 0); + + r = uv_accept(stream, (uv_stream_t*)&conn->handle); + ASSERT(r == 0); + + r = uv_read_start((uv_stream_t*)&conn->handle, alloc_cb, read_cb); + ASSERT(r == 0); +} + + +static uv_buf_t alloc_cb(uv_handle_t* handle, size_t suggested_size) { + static char buf[65536]; + return uv_buf_init(buf, sizeof buf); +} + + +static void read_cb(uv_stream_t* stream, ssize_t nread, uv_buf_t buf) { + conn_rec* conn; + int r; + + if (nread >= 0) + return; + + ASSERT(uv_last_error(stream->loop).code == UV_EOF); + + conn = container_of(stream, conn_rec, handle); + + r = uv_shutdown(&conn->shutdown_req, stream, shutdown_cb); + ASSERT(r == 0); +} + + +static void shutdown_cb(uv_shutdown_t* req, int status) { + conn_rec* conn = container_of(req, conn_rec, shutdown_req); + uv_close((uv_handle_t*)&conn->handle, close_cb); +} + + +static void close_cb(uv_handle_t* handle) { + conn_rec* conn = container_of(handle, conn_rec, handle); + free(conn); +} + + +HELPER_IMPL(tcp4_blackhole_server) { + struct sockaddr_in addr; + uv_loop_t* loop; + int r; + + loop = uv_default_loop(); + addr = uv_ip4_addr("127.0.0.1", TEST_PORT); + + r = uv_tcp_init(loop, &tcp_server); + ASSERT(r == 0); + + r = uv_tcp_bind(&tcp_server, addr); + ASSERT(r == 0); + + r = uv_listen((uv_stream_t*)&tcp_server, 128, connection_cb); + ASSERT(r == 0); + + r = uv_run(loop); + ASSERT(0 && "Blackhole server dropped out of event loop."); + + return 0; +} diff --git a/node-v0.8.14/deps/uv/test/dns-server.c b/node-v0.8.14/deps/uv/test/dns-server.c new file mode 100644 index 0000000..d885f4c --- /dev/null +++ b/node-v0.8.14/deps/uv/test/dns-server.c @@ -0,0 +1,321 @@ +/* Copyright Joyent, Inc. and other Node contributors. All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ + +#include "uv.h" +#include "task.h" +#include +#include +#include + + +typedef struct { + uv_write_t req; + uv_buf_t buf; +} write_req_t; + + +/* used to track multiple DNS requests received */ +typedef struct { + char* prevbuf_ptr; + int prevbuf_pos; + int prevbuf_rem; +} dnsstate; + + +/* modify handle to append dnsstate */ +typedef struct { + uv_tcp_t handle; + dnsstate state; +} dnshandle; + + +static uv_loop_t* loop; + + +static uv_tcp_t server; + + +static void after_write(uv_write_t* req, int status); +static void after_read(uv_stream_t*, ssize_t nread, uv_buf_t buf); +static void on_close(uv_handle_t* peer); +static void on_connection(uv_stream_t*, int status); + +#define WRITE_BUF_LEN (64*1024) +#define DNSREC_LEN (4) + +#define LEN_OFFSET 0 +#define QUERYID_OFFSET 2 +unsigned char DNSRsp[] = {0, 43, 0, 0, 0x81, 0x80, 0, 1, 0, 1, 0, 0, 0, 0 }; +unsigned char qrecord[] = {5, 'e', 'c', 'h', 'o', 's', 3, 's', 'r', 'v', 0, 0, 1, 0, 1}; +unsigned char arecord[] = {0xc0, 0x0c, 0, 1, 0, 1, 0, 0, 5, 0xbd, 0, 4, 10, 0, 1, 1 }; + + +static void after_write(uv_write_t* req, int status) { + write_req_t* wr; + + if (status) { + uv_err_t err = uv_last_error(loop); + fprintf(stderr, "uv_write error: %s\n", uv_strerror(err)); + ASSERT(0); + } + + wr = (write_req_t*) req; + + /* Free the read/write buffer and the request */ + free(wr->buf.base); + free(wr); +} + + +static void after_shutdown(uv_shutdown_t* req, int status) { + uv_close((uv_handle_t*) req->handle, on_close); + free(req); +} + + +static void addrsp(write_req_t* wr, char* hdr) { + char * dnsrsp; + short int rsplen; + short int* reclen; + + rsplen = sizeof(DNSRsp) + sizeof(qrecord) + sizeof(arecord); + + ASSERT (rsplen + wr->buf.len < WRITE_BUF_LEN); + + dnsrsp = wr->buf.base + wr->buf.len; + + /* copy stock response */ + memcpy(dnsrsp, DNSRsp, sizeof(DNSRsp)); + memcpy(dnsrsp + sizeof(DNSRsp), qrecord, sizeof(qrecord)); + memcpy(dnsrsp + sizeof(DNSRsp) + sizeof(qrecord), arecord, sizeof(arecord)); + + /* overwrite with network order length and id from request header */ + reclen = (short int*)dnsrsp; + *reclen = htons(rsplen-2); + dnsrsp[QUERYID_OFFSET] = hdr[QUERYID_OFFSET]; + dnsrsp[QUERYID_OFFSET+1] = hdr[QUERYID_OFFSET+1]; + + wr->buf.len += rsplen; +} + +static void process_req(uv_stream_t* handle, ssize_t nread, uv_buf_t buf) { + write_req_t* wr; + dnshandle* dns = (dnshandle*)handle; + char hdrbuf[DNSREC_LEN]; + int hdrbuf_remaining = DNSREC_LEN; + int rec_remaining = 0; + int readbuf_remaining; + char* dnsreq; + char* hdrstart; + int usingprev = 0; + + wr = (write_req_t*) malloc(sizeof *wr); + wr->buf.base = (char*)malloc(WRITE_BUF_LEN); + wr->buf.len = 0; + + if (dns->state.prevbuf_ptr != NULL) { + dnsreq = dns->state.prevbuf_ptr + dns->state.prevbuf_pos; + readbuf_remaining = dns->state.prevbuf_rem; + usingprev = 1; + } else { + dnsreq = buf.base; + readbuf_remaining = nread; + } + hdrstart = dnsreq; + + while (dnsreq != NULL) { + /* something to process */ + while (readbuf_remaining > 0) { + /* something to process in current buffer */ + if (hdrbuf_remaining > 0) { + /* process len and id */ + if (readbuf_remaining < hdrbuf_remaining) { + /* too little to get request header. save for next buffer */ + memcpy(&hdrbuf[DNSREC_LEN - hdrbuf_remaining], dnsreq, readbuf_remaining); + hdrbuf_remaining = DNSREC_LEN - readbuf_remaining; + break; + } else { + short int reclen_n; + /* save header */ + memcpy(&hdrbuf[DNSREC_LEN - hdrbuf_remaining], dnsreq, hdrbuf_remaining); + dnsreq += hdrbuf_remaining; + readbuf_remaining -= hdrbuf_remaining; + hdrbuf_remaining = 0; + + /* get record length */ + reclen_n = *((short int*)hdrbuf); + rec_remaining = ntohs(reclen_n) - (DNSREC_LEN - 2); + } + } + + if (rec_remaining <= readbuf_remaining) { + /* prepare reply */ + addrsp(wr, hdrbuf); + + /* move to next record */ + dnsreq += rec_remaining; + hdrstart = dnsreq; + readbuf_remaining -= rec_remaining; + rec_remaining = 0; + hdrbuf_remaining = DNSREC_LEN; + } else { + /* otherwise this buffer is done. */ + rec_remaining -= readbuf_remaining; + break; + } + } + + /* if we had to use bytes from prev buffer, start processing the current one */ + if (usingprev == 1) { + /* free previous buffer */ + free(dns->state.prevbuf_ptr); + dnsreq = buf.base; + readbuf_remaining = nread; + usingprev = 0; + } else { + dnsreq = NULL; + } + } + + /* send write buffer */ + if (wr->buf.len > 0) { + if (uv_write((uv_write_t*) &wr->req, handle, &wr->buf, 1, after_write)) { + FATAL("uv_write failed"); + } + } + + if (readbuf_remaining > 0) { + /* save start of record position, so we can continue on next read */ + dns->state.prevbuf_ptr = buf.base; + dns->state.prevbuf_pos = hdrstart - buf.base; + dns->state.prevbuf_rem = nread - dns->state.prevbuf_pos; + } else { + /* nothing left in this buffer */ + dns->state.prevbuf_ptr = NULL; + dns->state.prevbuf_pos = 0; + dns->state.prevbuf_rem = 0; + free(buf.base); + } +} + +static void after_read(uv_stream_t* handle, ssize_t nread, uv_buf_t buf) { + uv_shutdown_t* req; + + if (nread < 0) { + /* Error or EOF */ + ASSERT (uv_last_error(loop).code == UV_EOF); + + if (buf.base) { + free(buf.base); + } + + req = malloc(sizeof *req); + uv_shutdown(req, handle, after_shutdown); + + return; + } + + if (nread == 0) { + /* Everything OK, but nothing read. */ + free(buf.base); + return; + } + /* process requests and send responses */ + process_req(handle, nread, buf); +} + + +static void on_close(uv_handle_t* peer) { + free(peer); +} + + +static uv_buf_t buf_alloc(uv_handle_t* handle, size_t suggested_size) { + uv_buf_t buf; + buf.base = (char*) malloc(suggested_size); + buf.len = suggested_size; + return buf; +} + + +static void on_connection(uv_stream_t* server, int status) { + dnshandle* handle; + int r; + + ASSERT(status == 0); + + handle = (dnshandle*) malloc(sizeof *handle); + ASSERT(handle != NULL); + + /* initialize read buffer state */ + handle->state.prevbuf_ptr = 0; + handle->state.prevbuf_pos = 0; + handle->state.prevbuf_rem = 0; + + r = uv_tcp_init(loop, (uv_tcp_t*)handle); + ASSERT(r == 0); + + r = uv_accept(server, (uv_stream_t*)handle); + ASSERT(r == 0); + + r = uv_read_start((uv_stream_t*)handle, buf_alloc, after_read); + ASSERT(r == 0); +} + + +static int dns_start(int port) { + struct sockaddr_in addr = uv_ip4_addr("0.0.0.0", port); + int r; + + r = uv_tcp_init(loop, &server); + if (r) { + /* TODO: Error codes */ + fprintf(stderr, "Socket creation error\n"); + return 1; + } + + r = uv_tcp_bind(&server, addr); + if (r) { + /* TODO: Error codes */ + fprintf(stderr, "Bind error\n"); + return 1; + } + + r = uv_listen((uv_stream_t*)&server, 128, on_connection); + if (r) { + /* TODO: Error codes */ + fprintf(stderr, "Listen error\n"); + return 1; + } + + return 0; +} + + +HELPER_IMPL(dns_server) { + loop = uv_default_loop(); + + if (dns_start(TEST_PORT_2)) + return 1; + + uv_run(loop); + return 0; +} diff --git a/node-v0.8.14/deps/uv/test/echo-server.c b/node-v0.8.14/deps/uv/test/echo-server.c new file mode 100644 index 0000000..d663d60 --- /dev/null +++ b/node-v0.8.14/deps/uv/test/echo-server.c @@ -0,0 +1,378 @@ +/* Copyright Joyent, Inc. and other Node contributors. All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ + +#include "uv.h" +#include "task.h" +#include +#include + +typedef struct { + uv_write_t req; + uv_buf_t buf; +} write_req_t; + +static uv_loop_t* loop; + +static int server_closed; +static stream_type serverType; +static uv_tcp_t tcpServer; +static uv_udp_t udpServer; +static uv_pipe_t pipeServer; +static uv_handle_t* server; + +static void after_write(uv_write_t* req, int status); +static void after_read(uv_stream_t*, ssize_t nread, uv_buf_t buf); +static void on_close(uv_handle_t* peer); +static void on_server_close(uv_handle_t* handle); +static void on_connection(uv_stream_t*, int status); + + +static void after_write(uv_write_t* req, int status) { + write_req_t* wr; + + if (status) { + uv_err_t err = uv_last_error(loop); + fprintf(stderr, "uv_write error: %s\n", uv_strerror(err)); + ASSERT(0); + } + + wr = (write_req_t*) req; + + /* Free the read/write buffer and the request */ + free(wr->buf.base); + free(wr); +} + + +static void after_shutdown(uv_shutdown_t* req, int status) { + uv_close((uv_handle_t*)req->handle, on_close); + free(req); +} + + +static void after_read(uv_stream_t* handle, ssize_t nread, uv_buf_t buf) { + int i; + write_req_t *wr; + uv_shutdown_t* req; + + if (nread < 0) { + /* Error or EOF */ + ASSERT (uv_last_error(loop).code == UV_EOF); + + if (buf.base) { + free(buf.base); + } + + req = (uv_shutdown_t*) malloc(sizeof *req); + uv_shutdown(req, handle, after_shutdown); + + return; + } + + if (nread == 0) { + /* Everything OK, but nothing read. */ + free(buf.base); + return; + } + + /* + * Scan for the letter Q which signals that we should quit the server. + * If we get QS it means close the stream. + */ + if (!server_closed) { + for (i = 0; i < nread; i++) { + if (buf.base[i] == 'Q') { + if (i + 1 < nread && buf.base[i + 1] == 'S') { + free(buf.base); + uv_close((uv_handle_t*)handle, on_close); + return; + } else { + uv_close(server, on_server_close); + server_closed = 1; + } + } + } + } + + wr = (write_req_t*) malloc(sizeof *wr); + + wr->buf = uv_buf_init(buf.base, nread); + if (uv_write(&wr->req, handle, &wr->buf, 1, after_write)) { + FATAL("uv_write failed"); + } +} + + +static void on_close(uv_handle_t* peer) { + free(peer); +} + + +static uv_buf_t echo_alloc(uv_handle_t* handle, size_t suggested_size) { + return uv_buf_init(malloc(suggested_size), suggested_size); +} + + +static void on_connection(uv_stream_t* server, int status) { + uv_stream_t* stream; + int r; + + if (status != 0) { + fprintf(stderr, "Connect error %d\n", + uv_last_error(loop).code); + } + ASSERT(status == 0); + + switch (serverType) { + case TCP: + stream = malloc(sizeof(uv_tcp_t)); + ASSERT(stream != NULL); + r = uv_tcp_init(loop, (uv_tcp_t*)stream); + ASSERT(r == 0); + break; + + case PIPE: + stream = malloc(sizeof(uv_pipe_t)); + ASSERT(stream != NULL); + r = uv_pipe_init(loop, (uv_pipe_t*)stream, 0); + ASSERT(r == 0); + break; + + default: + ASSERT(0 && "Bad serverType"); + abort(); + } + + /* associate server with stream */ + stream->data = server; + + r = uv_accept(server, stream); + ASSERT(r == 0); + + r = uv_read_start(stream, echo_alloc, after_read); + ASSERT(r == 0); +} + + +static void on_server_close(uv_handle_t* handle) { + ASSERT(handle == server); +} + + +static void on_send(uv_udp_send_t* req, int status); + + +static void on_recv(uv_udp_t* handle, + ssize_t nread, + uv_buf_t buf, + struct sockaddr* addr, + unsigned flags) { + uv_udp_send_t* req; + int r; + + ASSERT(nread > 0); + ASSERT(addr->sa_family == AF_INET); + + req = malloc(sizeof(*req)); + ASSERT(req != NULL); + + r = uv_udp_send(req, handle, &buf, 1, *(struct sockaddr_in*)addr, on_send); + ASSERT(r == 0); +} + + +static void on_send(uv_udp_send_t* req, int status) { + ASSERT(status == 0); + free(req); +} + + +static int tcp4_echo_start(int port) { + struct sockaddr_in addr = uv_ip4_addr("0.0.0.0", port); + int r; + + server = (uv_handle_t*)&tcpServer; + serverType = TCP; + + r = uv_tcp_init(loop, &tcpServer); + if (r) { + /* TODO: Error codes */ + fprintf(stderr, "Socket creation error\n"); + return 1; + } + + r = uv_tcp_bind(&tcpServer, addr); + if (r) { + /* TODO: Error codes */ + fprintf(stderr, "Bind error\n"); + return 1; + } + + r = uv_listen((uv_stream_t*)&tcpServer, SOMAXCONN, on_connection); + if (r) { + /* TODO: Error codes */ + fprintf(stderr, "Listen error %s\n", + uv_err_name(uv_last_error(loop))); + return 1; + } + + return 0; +} + + +static int tcp6_echo_start(int port) { + struct sockaddr_in6 addr6 = uv_ip6_addr("::1", port); + int r; + + server = (uv_handle_t*)&tcpServer; + serverType = TCP; + + r = uv_tcp_init(loop, &tcpServer); + if (r) { + /* TODO: Error codes */ + fprintf(stderr, "Socket creation error\n"); + return 1; + } + + /* IPv6 is optional as not all platforms support it */ + r = uv_tcp_bind6(&tcpServer, addr6); + if (r) { + /* show message but return OK */ + fprintf(stderr, "IPv6 not supported\n"); + return 0; + } + + r = uv_listen((uv_stream_t*)&tcpServer, SOMAXCONN, on_connection); + if (r) { + /* TODO: Error codes */ + fprintf(stderr, "Listen error\n"); + return 1; + } + + return 0; +} + + +static int udp4_echo_start(int port) { + int r; + + server = (uv_handle_t*)&udpServer; + serverType = UDP; + + r = uv_udp_init(loop, &udpServer); + if (r) { + fprintf(stderr, "uv_udp_init: %s\n", + uv_strerror(uv_last_error(loop))); + return 1; + } + + r = uv_udp_recv_start(&udpServer, echo_alloc, on_recv); + if (r) { + fprintf(stderr, "uv_udp_recv_start: %s\n", + uv_strerror(uv_last_error(loop))); + return 1; + } + + return 0; +} + + +static int pipe_echo_start(char* pipeName) { + int r; + +#ifndef _WIN32 + { + uv_fs_t req; + uv_fs_unlink(uv_default_loop(), &req, pipeName, NULL); + uv_fs_req_cleanup(&req); + } +#endif + + server = (uv_handle_t*)&pipeServer; + serverType = PIPE; + + r = uv_pipe_init(loop, &pipeServer, 0); + if (r) { + fprintf(stderr, "uv_pipe_init: %s\n", + uv_strerror(uv_last_error(loop))); + return 1; + } + + r = uv_pipe_bind(&pipeServer, pipeName); + if (r) { + fprintf(stderr, "uv_pipe_bind: %s\n", + uv_strerror(uv_last_error(loop))); + return 1; + } + + r = uv_listen((uv_stream_t*)&pipeServer, SOMAXCONN, on_connection); + if (r) { + fprintf(stderr, "uv_pipe_listen: %s\n", + uv_strerror(uv_last_error(loop))); + return 1; + } + + return 0; +} + + +HELPER_IMPL(tcp4_echo_server) { + loop = uv_default_loop(); + + if (tcp4_echo_start(TEST_PORT)) + return 1; + + uv_run(loop); + return 0; +} + + +HELPER_IMPL(tcp6_echo_server) { + loop = uv_default_loop(); + + if (tcp6_echo_start(TEST_PORT)) + return 1; + + uv_run(loop); + return 0; +} + + +HELPER_IMPL(pipe_echo_server) { + loop = uv_default_loop(); + + if (pipe_echo_start(TEST_PIPENAME)) + return 1; + + uv_run(loop); + return 0; +} + + +HELPER_IMPL(udp4_echo_server) { + loop = uv_default_loop(); + + if (udp4_echo_start(TEST_PORT)) + return 1; + + uv_run(loop); + return 0; +} diff --git a/node-v0.8.14/deps/uv/test/fixtures/empty_file b/node-v0.8.14/deps/uv/test/fixtures/empty_file new file mode 100644 index 0000000..e69de29 diff --git a/node-v0.8.14/deps/uv/test/fixtures/load_error.node b/node-v0.8.14/deps/uv/test/fixtures/load_error.node new file mode 100644 index 0000000..323fae0 --- /dev/null +++ b/node-v0.8.14/deps/uv/test/fixtures/load_error.node @@ -0,0 +1 @@ +foobar diff --git a/node-v0.8.14/deps/uv/test/run-benchmarks.c b/node-v0.8.14/deps/uv/test/run-benchmarks.c new file mode 100644 index 0000000..af11beb --- /dev/null +++ b/node-v0.8.14/deps/uv/test/run-benchmarks.c @@ -0,0 +1,64 @@ +/* Copyright Joyent, Inc. and other Node contributors. All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ + +#include +#include + +#include "runner.h" +#include "task.h" + +/* Actual benchmarks and helpers are defined in benchmark-list.h */ +#include "benchmark-list.h" + + +/* The time in milliseconds after which a single benchmark times out. */ +#define BENCHMARK_TIMEOUT 60000 + +static int maybe_run_test(int argc, char **argv); + + +int main(int argc, char **argv) { + platform_init(argc, argv); + + switch (argc) { + case 1: return run_tests(BENCHMARK_TIMEOUT, 1); + case 2: return maybe_run_test(argc, argv); + case 3: return run_test_part(argv[1], argv[2]); + default: + LOGF("Too many arguments.\n"); + return 1; + } +} + + +static int maybe_run_test(int argc, char **argv) { + if (strcmp(argv[1], "--list") == 0) { + print_tests(stdout); + return 0; + } + + if (strcmp(argv[1], "spawn_helper") == 0) { + printf("hello world\n"); + return 42; + } + + return run_test(argv[1], BENCHMARK_TIMEOUT, 1); +} diff --git a/node-v0.8.14/deps/uv/test/run-tests.c b/node-v0.8.14/deps/uv/test/run-tests.c new file mode 100644 index 0000000..fb16303 --- /dev/null +++ b/node-v0.8.14/deps/uv/test/run-tests.c @@ -0,0 +1,138 @@ +/* Copyright Joyent, Inc. and other Node contributors. All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ + +#include +#include + +#ifdef _WIN32 +# include +#else +# include +#endif + +#include "uv.h" +#include "runner.h" +#include "task.h" + +/* Actual tests and helpers are defined in test-list.h */ +#include "test-list.h" + +/* The time in milliseconds after which a single test times out. */ +#define TEST_TIMEOUT 5000 + +int ipc_helper(int listen_after_write); +int ipc_helper_tcp_connection(void); +int ipc_send_recv_helper(void); +int stdio_over_pipes_helper(void); + +static int maybe_run_test(int argc, char **argv); + + +int main(int argc, char **argv) { + platform_init(argc, argv); + + argv = uv_setup_args(argc, argv); + + switch (argc) { + case 1: return run_tests(TEST_TIMEOUT, 0); + case 2: return maybe_run_test(argc, argv); + case 3: return run_test_part(argv[1], argv[2]); + default: + LOGF("Too many arguments.\n"); + return 1; + } +} + + +static int maybe_run_test(int argc, char **argv) { + if (strcmp(argv[1], "--list") == 0) { + print_tests(stdout); + return 0; + } + + if (strcmp(argv[1], "ipc_helper_listen_before_write") == 0) { + return ipc_helper(0); + } + + if (strcmp(argv[1], "ipc_helper_listen_after_write") == 0) { + return ipc_helper(1); + } + + if (strcmp(argv[1], "ipc_send_recv_helper") == 0) { + return ipc_send_recv_helper(); + } + + if (strcmp(argv[1], "ipc_helper_tcp_connection") == 0) { + return ipc_helper_tcp_connection(); + } + + if (strcmp(argv[1], "stdio_over_pipes_helper") == 0) { + return stdio_over_pipes_helper(); + } + + if (strcmp(argv[1], "spawn_helper1") == 0) { + return 1; + } + + if (strcmp(argv[1], "spawn_helper2") == 0) { + printf("hello world\n"); + return 1; + } + + if (strcmp(argv[1], "spawn_helper3") == 0) { + char buffer[256]; + fgets(buffer, sizeof(buffer) - 1, stdin); + buffer[sizeof(buffer) - 1] = '\0'; + fputs(buffer, stdout); + return 1; + } + + if (strcmp(argv[1], "spawn_helper4") == 0) { + /* Never surrender, never return! */ + while (1) uv_sleep(10000); + } + + if (strcmp(argv[1], "spawn_helper5") == 0) { + const char* out = "fourth stdio!\n\0"; +#ifdef _WIN32 + DWORD bytes; + WriteFile((HANDLE) _get_osfhandle(3), out, strlen(out), &bytes, NULL); +#else + write(3, out, strlen(out)); + fsync(3); +#endif + return 1; + } + + if (strcmp(argv[1], "spawn_helper6") == 0) { + int r; + + r = fprintf(stdout, "hello world\n"); + ASSERT(r > 0); + + r = fprintf(stderr, "hello errworld\n"); + ASSERT(r > 0); + + return 1; + } + + return run_test(argv[1], TEST_TIMEOUT, 0); +} diff --git a/node-v0.8.14/deps/uv/test/runner-unix.c b/node-v0.8.14/deps/uv/test/runner-unix.c new file mode 100644 index 0000000..d0ebfbf --- /dev/null +++ b/node-v0.8.14/deps/uv/test/runner-unix.c @@ -0,0 +1,290 @@ +/* Copyright Joyent, Inc. and other Node contributors. All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ + +#include "runner-unix.h" +#include "runner.h" + +#include /* uintptr_t */ + +#include /* usleep */ +#include /* strdup */ +#include +#include +#include +#include +#include +#include +#include + +#include +#include + + +/* Do platform-specific initialization. */ +void platform_init(int argc, char **argv) { + /* Disable stdio output buffering. */ + setvbuf(stdout, NULL, _IONBF, 0); + setvbuf(stderr, NULL, _IONBF, 0); + strcpy(executable_path, argv[0]); + signal(SIGPIPE, SIG_IGN); +} + + +/* Invoke "argv[0] test-name [test-part]". Store process info in *p. */ +/* Make sure that all stdio output of the processes is buffered up. */ +int process_start(char* name, char* part, process_info_t* p) { + FILE* stdout_file = tmpfile(); + if (!stdout_file) { + perror("tmpfile"); + return -1; + } + + p->terminated = 0; + p->status = 0; + + pid_t pid = fork(); + + if (pid < 0) { + perror("vfork"); + return -1; + } + + if (pid == 0) { + /* child */ + dup2(fileno(stdout_file), STDOUT_FILENO); + dup2(fileno(stdout_file), STDERR_FILENO); + + char* args[] = { executable_path, name, part, NULL }; + execvp(executable_path, args); + perror("execvp()"); + _exit(127); + } + + /* parent */ + p->pid = pid; + p->name = strdup(name); + p->stdout_file = stdout_file; + + return 0; +} + + +typedef struct { + int pipe[2]; + process_info_t* vec; + int n; +} dowait_args; + + +/* This function is run inside a pthread. We do this so that we can possibly + * timeout. + */ +static void* dowait(void* data) { + dowait_args* args = data; + + int i, r; + process_info_t* p; + + for (i = 0; i < args->n; i++) { + p = (process_info_t*)(args->vec + i * sizeof(process_info_t)); + if (p->terminated) continue; + r = waitpid(p->pid, &p->status, 0); + if (r < 0) { + perror("waitpid"); + return NULL; + } + p->terminated = 1; + } + + if (args->pipe[1] >= 0) { + /* Write a character to the main thread to notify it about this. */ + char c = 0; + write(args->pipe[1], &c, 1); + } + + return NULL; +} + + +/* Wait for all `n` processes in `vec` to terminate. */ +/* Time out after `timeout` msec, or never if timeout == -1 */ +/* Return 0 if all processes are terminated, -1 on error, -2 on timeout. */ +int process_wait(process_info_t* vec, int n, int timeout) { + int i; + process_info_t* p; + dowait_args args; + args.vec = vec; + args.n = n; + args.pipe[0] = -1; + args.pipe[1] = -1; + + /* The simple case is where there is no timeout */ + if (timeout == -1) { + dowait(&args); + return 0; + } + + /* Hard case. Do the wait with a timeout. + * + * Assumption: we are the only ones making this call right now. Otherwise + * we'd need to lock vec. + */ + + pthread_t tid; + int retval; + + int r = pipe((int*)&(args.pipe)); + if (r) { + perror("pipe()"); + return -1; + } + + r = pthread_create(&tid, NULL, dowait, &args); + if (r) { + perror("pthread_create()"); + retval = -1; + goto terminate; + } + + struct timeval tv; + tv.tv_sec = timeout / 1000; + tv.tv_usec = 0; + + fd_set fds; + FD_ZERO(&fds); + FD_SET(args.pipe[0], &fds); + + r = select(args.pipe[0] + 1, &fds, NULL, NULL, &tv); + + if (r == -1) { + perror("select()"); + retval = -1; + + } else if (r) { + /* The thread completed successfully. */ + retval = 0; + + } else { + /* Timeout. Kill all the children. */ + for (i = 0; i < n; i++) { + p = (process_info_t*)(vec + i * sizeof(process_info_t)); + kill(p->pid, SIGTERM); + } + retval = -2; + + /* Wait for thread to finish. */ + r = pthread_join(tid, NULL); + if (r) { + perror("pthread_join"); + retval = -1; + } + } + +terminate: + close(args.pipe[0]); + close(args.pipe[1]); + return retval; +} + + +/* Returns the number of bytes in the stdio output buffer for process `p`. */ +long int process_output_size(process_info_t *p) { + /* Size of the p->stdout_file */ + struct stat buf; + + int r = fstat(fileno(p->stdout_file), &buf); + if (r < 0) { + return -1; + } + + return (long)buf.st_size; +} + + +/* Copy the contents of the stdio output buffer to `fd`. */ +int process_copy_output(process_info_t *p, int fd) { + int r = fseek(p->stdout_file, 0, SEEK_SET); + if (r < 0) { + perror("fseek"); + return -1; + } + + ssize_t nread, nwritten; + char buf[1024]; + + while ((nread = read(fileno(p->stdout_file), buf, 1024)) > 0) { + nwritten = write(fd, buf, nread); + /* TODO: what if write doesn't write the whole buffer... */ + if (nwritten < 0) { + perror("write"); + return -1; + } + } + + if (nread < 0) { + perror("read"); + return -1; + } + + return 0; +} + + +/* Return the name that was specified when `p` was started by process_start */ +char* process_get_name(process_info_t *p) { + return p->name; +} + + +/* Terminate process `p`. */ +int process_terminate(process_info_t *p) { + return kill(p->pid, SIGTERM); +} + + +/* Return the exit code of process p. */ +/* On error, return -1. */ +int process_reap(process_info_t *p) { + if (WIFEXITED(p->status)) { + return WEXITSTATUS(p->status); + } else { + return p->status; /* ? */ + } +} + + +/* Clean up after terminating process `p` (e.g. free the output buffer etc.). */ +void process_cleanup(process_info_t *p) { + fclose(p->stdout_file); + free(p->name); +} + + +/* Move the console cursor one line up and back to the first column. */ +void rewind_cursor() { + fprintf(stderr, "\033[2K\r"); +} + + +/* Pause the calling thread for a number of milliseconds. */ +void uv_sleep(int msec) { + usleep(msec * 1000); +} diff --git a/node-v0.8.14/deps/uv/test/runner-unix.h b/node-v0.8.14/deps/uv/test/runner-unix.h new file mode 100644 index 0000000..e21847f --- /dev/null +++ b/node-v0.8.14/deps/uv/test/runner-unix.h @@ -0,0 +1,36 @@ +/* Copyright Joyent, Inc. and other Node contributors. All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ + +#ifndef TEST_RUNNER_UNIX_H +#define TEST_RUNNER_UNIX_H + +#include +#include /* FILE */ + +typedef struct { + FILE* stdout_file; + pid_t pid; + char* name; + int status; + int terminated; +} process_info_t; + +#endif /* TEST_RUNNER_UNIX_H */ diff --git a/node-v0.8.14/deps/uv/test/runner-win.c b/node-v0.8.14/deps/uv/test/runner-win.c new file mode 100644 index 0000000..0a9690e --- /dev/null +++ b/node-v0.8.14/deps/uv/test/runner-win.c @@ -0,0 +1,293 @@ +/* Copyright Joyent, Inc. and other Node contributors. All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ + +#include +#include +#include +#include +#include +#include +#if !defined(__MINGW32__) +#include +#endif + + +#include "task.h" +#include "runner.h" + + +/* + * Define the stuff that MinGW doesn't have + */ +#ifndef GetFileSizeEx + WINBASEAPI BOOL WINAPI GetFileSizeEx(HANDLE hFile, + PLARGE_INTEGER lpFileSize); +#endif + + +/* Do platform-specific initialization. */ +void platform_init(int argc, char **argv) { + /* Disable the "application crashed" popup. */ + SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOGPFAULTERRORBOX | + SEM_NOOPENFILEERRORBOX); +#if !defined(__MINGW32__) + _CrtSetReportMode(_CRT_ASSERT, _CRTDBG_MODE_DEBUG); + _CrtSetReportMode(_CRT_ERROR, _CRTDBG_MODE_DEBUG); +#endif + + _setmode(0, _O_BINARY); + _setmode(1, _O_BINARY); + _setmode(2, _O_BINARY); + + /* Disable stdio output buffering. */ + setvbuf(stdout, NULL, _IONBF, 0); + setvbuf(stderr, NULL, _IONBF, 0); + + strcpy(executable_path, argv[0]); +} + + +int process_start(char *name, char *part, process_info_t *p) { + HANDLE file = INVALID_HANDLE_VALUE; + HANDLE nul = INVALID_HANDLE_VALUE; + WCHAR path[MAX_PATH], filename[MAX_PATH]; + WCHAR image[MAX_PATH + 1]; + WCHAR args[MAX_PATH * 2]; + STARTUPINFOW si; + PROCESS_INFORMATION pi; + DWORD result; + + if (GetTempPathW(sizeof(path) / sizeof(WCHAR), (WCHAR*)&path) == 0) + goto error; + if (GetTempFileNameW((WCHAR*)&path, L"uv", 0, (WCHAR*)&filename) == 0) + goto error; + + file = CreateFileW((WCHAR*)filename, + GENERIC_READ | GENERIC_WRITE, + 0, + NULL, + CREATE_ALWAYS, + FILE_ATTRIBUTE_TEMPORARY | FILE_FLAG_DELETE_ON_CLOSE, + NULL); + if (file == INVALID_HANDLE_VALUE) + goto error; + + if (!SetHandleInformation(file, HANDLE_FLAG_INHERIT, HANDLE_FLAG_INHERIT)) + goto error; + + nul = CreateFileA("nul", + GENERIC_READ, + FILE_SHARE_READ | FILE_SHARE_WRITE, + NULL, + OPEN_EXISTING, + FILE_ATTRIBUTE_NORMAL, + NULL); + if (nul == INVALID_HANDLE_VALUE) + goto error; + + if (!SetHandleInformation(nul, HANDLE_FLAG_INHERIT, HANDLE_FLAG_INHERIT)) + goto error; + + result = GetModuleFileNameW(NULL, (WCHAR*)&image, sizeof(image) / sizeof(WCHAR)); + if (result == 0 || result == sizeof(image)) + goto error; + + if (part) { + if (_snwprintf((wchar_t*)args, + sizeof(args) / sizeof(wchar_t), + L"\"%s\" %S %S", + image, + name, + part) < 0) { + goto error; + } + } else { + if (_snwprintf((wchar_t*)args, + sizeof(args) / sizeof(wchar_t), + L"\"%s\" %S", + image, + name) < 0) { + goto error; + } + } + + memset((void*)&si, 0, sizeof(si)); + si.cb = sizeof(si); + si.dwFlags = STARTF_USESTDHANDLES; + si.hStdInput = nul; + si.hStdOutput = file; + si.hStdError = file; + + if (!CreateProcessW(image, args, NULL, NULL, TRUE, + 0, NULL, NULL, &si, &pi)) + goto error; + + CloseHandle(pi.hThread); + + SetHandleInformation(nul, HANDLE_FLAG_INHERIT, 0); + SetHandleInformation(file, HANDLE_FLAG_INHERIT, 0); + + p->stdio_in = nul; + p->stdio_out = file; + p->process = pi.hProcess; + p->name = part; + + return 0; + +error: + if (file != INVALID_HANDLE_VALUE) + CloseHandle(file); + if (nul != INVALID_HANDLE_VALUE) + CloseHandle(nul); + + return -1; +} + + +/* Timeout is is msecs. Set timeout < 0 to never time out. */ +/* Returns 0 when all processes are terminated, -2 on timeout. */ +int process_wait(process_info_t *vec, int n, int timeout) { + int i; + HANDLE handles[MAXIMUM_WAIT_OBJECTS]; + DWORD timeout_api, result; + + /* If there's nothing to wait for, return immediately. */ + if (n == 0) + return 0; + + ASSERT(n <= MAXIMUM_WAIT_OBJECTS); + + for (i = 0; i < n; i++) + handles[i] = vec[i].process; + + if (timeout >= 0) { + timeout_api = (DWORD)timeout; + } else { + timeout_api = INFINITE; + } + + result = WaitForMultipleObjects(n, handles, TRUE, timeout_api); + + if (result >= WAIT_OBJECT_0 && result < WAIT_OBJECT_0 + n) { + /* All processes are terminated. */ + return 0; + } + if (result == WAIT_TIMEOUT) { + return -2; + } + return -1; +} + + +long int process_output_size(process_info_t *p) { + LARGE_INTEGER size; + if (!GetFileSizeEx(p->stdio_out, &size)) + return -1; + return (long int)size.QuadPart; +} + + +int process_copy_output(process_info_t *p, int fd) { + DWORD read; + char buf[1024]; + + if (SetFilePointer(p->stdio_out, 0, 0, FILE_BEGIN) == INVALID_SET_FILE_POINTER) + return -1; + + while (ReadFile(p->stdio_out, (void*)&buf, sizeof(buf), &read, NULL) && + read > 0) + write(fd, buf, read); + + if (GetLastError() != ERROR_HANDLE_EOF) + return -1; + + return 0; +} + + +char* process_get_name(process_info_t *p) { + return p->name; +} + + +int process_terminate(process_info_t *p) { + if (!TerminateProcess(p->process, 1)) + return -1; + return 0; +} + + +int process_reap(process_info_t *p) { + DWORD exitCode; + if (!GetExitCodeProcess(p->process, &exitCode)) + return -1; + return (int)exitCode; +} + + +void process_cleanup(process_info_t *p) { + CloseHandle(p->process); + CloseHandle(p->stdio_in); + CloseHandle(p->stdio_out); +} + + +static int clear_line() { + HANDLE handle; + CONSOLE_SCREEN_BUFFER_INFO info; + COORD coord; + DWORD written; + + handle = (HANDLE)_get_osfhandle(fileno(stderr)); + if (handle == INVALID_HANDLE_VALUE) + return -1; + + if (!GetConsoleScreenBufferInfo(handle, &info)) + return -1; + + coord = info.dwCursorPosition; + if (coord.Y <= 0) + return -1; + + coord.X = 0; + + if (!SetConsoleCursorPosition(handle, coord)) + return -1; + + if (!FillConsoleOutputCharacterW(handle, 0x20, info.dwSize.X, coord, &written)) + return -1; + + return 0; +} + + +void rewind_cursor() { + if (clear_line() == -1) { + /* If clear_line fails (stdout is not a console), print a newline. */ + fprintf(stderr, "\n"); + } +} + + +/* Pause the calling thread for a number of milliseconds. */ +void uv_sleep(int msec) { + Sleep(msec); +} diff --git a/node-v0.8.14/deps/uv/test/runner-win.h b/node-v0.8.14/deps/uv/test/runner-win.h new file mode 100644 index 0000000..f69976e --- /dev/null +++ b/node-v0.8.14/deps/uv/test/runner-win.h @@ -0,0 +1,42 @@ +/* Copyright Joyent, Inc. and other Node contributors. All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ + +/* Don't complain about _snprintf being insecure. */ +#define _CRT_SECURE_NO_WARNINGS + +/* Don't complain about write(), fileno() etc. being deprecated. */ +#pragma warning(disable : 4996) + + +#include +#include + + +/* Windows has no snprintf, only _snprintf. */ +#define snprintf _snprintf + + +typedef struct { + HANDLE process; + HANDLE stdio_in; + HANDLE stdio_out; + char *name; +} process_info_t; diff --git a/node-v0.8.14/deps/uv/test/runner.c b/node-v0.8.14/deps/uv/test/runner.c new file mode 100644 index 0000000..214c9a0 --- /dev/null +++ b/node-v0.8.14/deps/uv/test/runner.c @@ -0,0 +1,326 @@ +/* Copyright Joyent, Inc. and other Node contributors. All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ + +#include +#include + +#include "runner.h" +#include "task.h" + +char executable_path[PATHMAX] = { '\0' }; + + +static void log_progress(int total, int passed, int failed, const char* name) { + if (total == 0) + total = 1; + + LOGF("[%% %3d|+ %3d|- %3d]: %s", (int) ((passed + failed) / ((double) total) * 100.0), + passed, failed, name); +} + + +int run_tests(int timeout, int benchmark_output) { + int total, passed, failed; + task_entry_t* task; + + /* Count the number of tests. */ + total = 0; + for (task = TASKS; task->main; task++) { + if (!task->is_helper) { + total++; + } + } + + /* Run all tests. */ + passed = 0; + failed = 0; + for (task = TASKS; task->main; task++) { + if (task->is_helper) { + continue; + } + + rewind_cursor(); + if (!benchmark_output) { + log_progress(total, passed, failed, task->task_name); + } + + if (run_test(task->task_name, timeout, benchmark_output) == 0) { + passed++; + } else { + failed++; + } + } + + rewind_cursor(); + + if (!benchmark_output) { + log_progress(total, passed, failed, "Done.\n"); + } + + return failed; +} + + +int run_test(const char* test, int timeout, int benchmark_output) { + char errmsg[1024] = "no error"; + process_info_t processes[1024]; + process_info_t *main_proc; + task_entry_t* task; + int process_count; + int result; + int status; + int i; + + status = 255; + main_proc = NULL; + process_count = 0; + +#ifndef _WIN32 + /* Clean up stale socket from previous run. */ + remove(TEST_PIPENAME); +#endif + + /* If it's a helper the user asks for, start it directly. */ + for (task = TASKS; task->main; task++) { + if (task->is_helper && strcmp(test, task->process_name) == 0) { + return task->main(); + } + } + + /* Start the helpers first. */ + for (task = TASKS; task->main; task++) { + if (strcmp(test, task->task_name) != 0) { + continue; + } + + /* Skip the test itself. */ + if (!task->is_helper) { + continue; + } + + if (process_start(task->task_name, + task->process_name, + &processes[process_count]) == -1) { + snprintf(errmsg, + sizeof errmsg, + "Process `%s` failed to start.", + task->process_name); + goto out; + } + + process_count++; + } + + /* Give the helpers time to settle. Race-y, fix this. */ + uv_sleep(250); + + /* Now start the test itself. */ + for (task = TASKS; task->main; task++) { + if (strcmp(test, task->task_name) != 0) { + continue; + } + + if (task->is_helper) { + continue; + } + + if (process_start(task->task_name, + task->process_name, + &processes[process_count]) == -1) { + snprintf(errmsg, + sizeof errmsg, + "Process `%s` failed to start.", + task->process_name); + goto out; + } + + main_proc = &processes[process_count]; + process_count++; + break; + } + + if (main_proc == NULL) { + snprintf(errmsg, + sizeof errmsg, + "No test with that name: %s", + test); + goto out; + } + + result = process_wait(main_proc, 1, timeout); + if (result == -1) { + FATAL("process_wait failed"); + } else if (result == -2) { + /* Don't have to clean up the process, process_wait() has killed it. */ + snprintf(errmsg, + sizeof errmsg, + "timeout"); + goto out; + } + + status = process_reap(main_proc); + if (status != 0) { + snprintf(errmsg, + sizeof errmsg, + "exit code %d", + status); + goto out; + } + + if (benchmark_output) { + /* Give the helpers time to clean up their act. */ + uv_sleep(1000); + } + +out: + /* Reap running processes except the main process, it's already dead. */ + for (i = 0; i < process_count - 1; i++) { + process_terminate(&processes[i]); + } + + if (process_count > 0 && + process_wait(processes, process_count - 1, -1) < 0) { + FATAL("process_wait failed"); + } + + /* Show error and output from processes if the test failed. */ + if (status != 0 || task->show_output) { + if (status != 0) { + LOGF("\n`%s` failed: %s\n", test, errmsg); + } else { + LOGF("\n"); + } + + for (i = 0; i < process_count; i++) { + switch (process_output_size(&processes[i])) { + case -1: + LOGF("Output from process `%s`: (unavailable)\n", + process_get_name(&processes[i])); + break; + + case 0: + LOGF("Output from process `%s`: (no output)\n", + process_get_name(&processes[i])); + break; + + default: + LOGF("Output from process `%s`:\n", process_get_name(&processes[i])); + process_copy_output(&processes[i], fileno(stderr)); + break; + } + } + LOG("=============================================================\n"); + + /* In benchmark mode show concise output from the main process. */ + } else if (benchmark_output) { + switch (process_output_size(main_proc)) { + case -1: + LOGF("%s: (unavailable)\n", test); + break; + + case 0: + LOGF("%s: (no output)\n", test); + break; + + default: + for (i = 0; i < process_count; i++) { + process_copy_output(&processes[i], fileno(stderr)); + } + break; + } + } + + /* Clean up all process handles. */ + for (i = 0; i < process_count; i++) { + process_cleanup(&processes[i]); + } + + return status; +} + + +/* Returns the status code of the task part + * or 255 if no matching task was not found. + */ +int run_test_part(const char* test, const char* part) { + task_entry_t* task; + + for (task = TASKS; task->main; task++) { + if (strcmp(test, task->task_name) == 0 + && strcmp(part, task->process_name) == 0) { + return task->main(); + } + } + + LOGF("No test part with that name: %s:%s\n", test, part); + return 255; +} + + +static int compare_task(const void* va, const void* vb) { + const task_entry_t* a = va; + const task_entry_t* b = vb; + return strcmp(a->task_name, b->task_name); +} + + +static int find_helpers(const task_entry_t* task, const task_entry_t** helpers) { + const task_entry_t* helper; + int n_helpers; + + for (n_helpers = 0, helper = TASKS; helper->main; helper++) { + if (helper->is_helper && strcmp(helper->task_name, task->task_name) == 0) { + *helpers++ = helper; + n_helpers++; + } + } + + return n_helpers; +} + + +void print_tests(FILE* stream) { + const task_entry_t* helpers[1024]; + const task_entry_t* task; + int n_helpers; + int n_tasks; + int i; + + for (n_tasks = 0, task = TASKS; task->main; n_tasks++, task++); + qsort(TASKS, n_tasks, sizeof(TASKS[0]), compare_task); + + for (task = TASKS; task->main; task++) { + if (task->is_helper) { + continue; + } + + n_helpers = find_helpers(task, helpers); + if (n_helpers) { + printf("%-25s (helpers:", task->task_name); + for (i = 0; i < n_helpers; i++) { + printf(" %s", helpers[i]->process_name); + } + printf(")\n"); + } else { + printf("%s\n", task->task_name); + } + } +} diff --git a/node-v0.8.14/deps/uv/test/runner.h b/node-v0.8.14/deps/uv/test/runner.h new file mode 100644 index 0000000..5cee695 --- /dev/null +++ b/node-v0.8.14/deps/uv/test/runner.h @@ -0,0 +1,159 @@ +/* Copyright Joyent, Inc. and other Node contributors. All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ + +#ifndef RUNNER_H_ +#define RUNNER_H_ + +#include /* FILE */ + + +/* + * The maximum number of processes (main + helpers) that a test / benchmark + * can have. + */ +#define MAX_PROCESSES 8 + + +/* + * Struct to store both tests and to define helper processes for tasks. + */ +typedef struct { + char *task_name; + char *process_name; + int (*main)(); + int is_helper; + int show_output; +} task_entry_t, bench_entry_t; + + +/* + * Macros used by test-list.h and benchmark-list.h. + */ +#define TASK_LIST_START \ + task_entry_t TASKS[] = { + +#define TASK_LIST_END \ + { 0, 0, 0, 0 } \ + }; + +#define TEST_DECLARE(name) \ + int run_test_##name(); + +#define TEST_ENTRY(name) \ + { #name, #name, &run_test_##name, 0, 0 }, + +#define TEST_OUTPUT_ENTRY(name) \ + { #name, #name, &run_test_##name, 0, 1 }, + +#define BENCHMARK_DECLARE(name) \ + int run_benchmark_##name(); + +#define BENCHMARK_ENTRY(name) \ + { #name, #name, &run_benchmark_##name, 0, 0 }, + +#define HELPER_DECLARE(name) \ + int run_helper_##name(); + +#define HELPER_ENTRY(task_name, name) \ + { #task_name, #name, &run_helper_##name, 1, 0 }, + +#define TEST_HELPER HELPER_ENTRY +#define BENCHMARK_HELPER HELPER_ENTRY + +#define PATHMAX 1024 +extern char executable_path[PATHMAX]; + +/* + * Include platform-dependent definitions + */ +#ifdef _WIN32 +# include "runner-win.h" +#else +# include "runner-unix.h" +#endif + + +/* The array that is filled by test-list.h or benchmark-list.h */ +extern task_entry_t TASKS[]; + +/* + * Run all tests. + */ +int run_tests(int timeout, int benchmark_output); + +/* + * Run a single test. Starts up any helpers. + */ +int run_test(const char* test, int timeout, int benchmark_output); + +/* + * Run a test part, i.e. the test or one of its helpers. + */ +int run_test_part(const char* test, const char* part); + + +/* + * Print tests in sorted order to `stream`. Used by `./run-tests --list`. + */ +void print_tests(FILE* stream); + + +/* + * Stuff that should be implemented by test-runner-.h + * All functions return 0 on success, -1 on failure, unless specified + * otherwise. + */ + +/* Do platform-specific initialization. */ +void platform_init(); + +/* Invoke "argv[0] test-name [test-part]". Store process info in *p. */ +/* Make sure that all stdio output of the processes is buffered up. */ +int process_start(char *name, char* part, process_info_t *p); + +/* Wait for all `n` processes in `vec` to terminate. */ +/* Time out after `timeout` msec, or never if timeout == -1 */ +/* Return 0 if all processes are terminated, -1 on error, -2 on timeout. */ +int process_wait(process_info_t *vec, int n, int timeout); + +/* Returns the number of bytes in the stdio output buffer for process `p`. */ +long int process_output_size(process_info_t *p); + +/* Copy the contents of the stdio output buffer to `fd`. */ +int process_copy_output(process_info_t *p, int fd); + +/* Return the name that was specified when `p` was started by process_start */ +char* process_get_name(process_info_t *p); + +/* Terminate process `p`. */ +int process_terminate(process_info_t *p); + +/* Return the exit code of process p. */ +/* On error, return -1. */ +int process_reap(process_info_t *p); + +/* Clean up after terminating process `p` (e.g. free the output buffer etc.). */ +void process_cleanup(process_info_t *p); + +/* Move the console cursor one line up and back to the first column. */ +void rewind_cursor(); + +#endif /* RUNNER_H_ */ diff --git a/node-v0.8.14/deps/uv/test/task.h b/node-v0.8.14/deps/uv/test/task.h new file mode 100644 index 0000000..0449734 --- /dev/null +++ b/node-v0.8.14/deps/uv/test/task.h @@ -0,0 +1,109 @@ +/* Copyright Joyent, Inc. and other Node contributors. All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ + +#ifndef TASK_H_ +#define TASK_H_ + +#include +#include +#include +#include + +#define TEST_PORT 9123 +#define TEST_PORT_2 9124 + +#ifdef _WIN32 +# define TEST_PIPENAME "\\\\.\\pipe\\uv-test" +# define TEST_PIPENAME_2 "\\\\.\\pipe\\uv-test2" +#else +# define TEST_PIPENAME "/tmp/uv-test-sock" +# define TEST_PIPENAME_2 "/tmp/uv-test-sock2" +#endif + +#define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0])) + +#define container_of(ptr, type, member) \ + ((type *) ((char *) (ptr) - offsetof(type, member))) + +typedef enum { + TCP = 0, + UDP, + PIPE +} stream_type; + +/* Log to stderr. */ +#define LOG(...) \ + do { \ + fprintf(stderr, "%s", __VA_ARGS__); \ + fflush(stderr); \ + } while (0) + +#define LOGF(...) \ + do { \ + fprintf(stderr, __VA_ARGS__); \ + fflush(stderr); \ + } while (0) + +/* Die with fatal error. */ +#define FATAL(msg) \ + do { \ + fprintf(stderr, \ + "Fatal error in %s on line %d: %s\n", \ + __FILE__, \ + __LINE__, \ + msg); \ + fflush(stderr); \ + abort(); \ + } while (0) + + + +/* Have our own assert, so we are sure it does not get optimized away in + * a release build. + */ +#define ASSERT(expr) \ + do { \ + if (!(expr)) { \ + fprintf(stderr, \ + "Assertion failed in %s on line %d: %s\n", \ + __FILE__, \ + __LINE__, \ + #expr); \ + abort(); \ + } \ + } while (0) + + +/* Just sugar for wrapping the main() for a task or helper. */ +#define TEST_IMPL(name) \ + int run_test_##name() + +#define BENCHMARK_IMPL(name) \ + int run_benchmark_##name() + +#define HELPER_IMPL(name) \ + int run_helper_##name() + + +/* Pause the calling thread for a number of milliseconds. */ +void uv_sleep(int msec); + +#endif /* TASK_H_ */ diff --git a/node-v0.8.14/deps/uv/test/test-async.c b/node-v0.8.14/deps/uv/test/test-async.c new file mode 100644 index 0000000..7cdad09 --- /dev/null +++ b/node-v0.8.14/deps/uv/test/test-async.c @@ -0,0 +1,118 @@ +/* Copyright Joyent, Inc. and other Node contributors. All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ + +#include "uv.h" +#include "task.h" +#include +#include + +static uv_thread_t thread; +static uv_mutex_t mutex; + +static uv_prepare_t prepare; +static uv_async_t async; + +static volatile int async_cb_called; +static int prepare_cb_called; +static int close_cb_called; + + +void thread_cb(void *arg) { + int n; + int r; + + for (;;) { + uv_mutex_lock(&mutex); + n = async_cb_called; + uv_mutex_unlock(&mutex); + + if (n == 3) { + break; + } + + r = uv_async_send(&async); + ASSERT(r == 0); + } +} + + +static void close_cb(uv_handle_t* handle) { + ASSERT(handle != NULL); + close_cb_called++; +} + + +static void async_cb(uv_async_t* handle, int status) { + int n; + + ASSERT(handle == &async); + ASSERT(status == 0); + + uv_mutex_lock(&mutex); + n = ++async_cb_called; + uv_mutex_unlock(&mutex); + + if (n == 3) { + uv_close((uv_handle_t*)&async, close_cb); + uv_close((uv_handle_t*)&prepare, close_cb); + } +} + + +static void prepare_cb(uv_prepare_t* handle, int status) { + int r; + + ASSERT(handle == &prepare); + ASSERT(status == 0); + + if (prepare_cb_called++) + return; + + r = uv_thread_create(&thread, thread_cb, NULL); + ASSERT(r == 0); + uv_mutex_unlock(&mutex); +} + + +TEST_IMPL(async) { + int r; + + r = uv_mutex_init(&mutex); + ASSERT(r == 0); + uv_mutex_lock(&mutex); + + r = uv_prepare_init(uv_default_loop(), &prepare); + ASSERT(r == 0); + r = uv_prepare_start(&prepare, prepare_cb); + ASSERT(r == 0); + + r = uv_async_init(uv_default_loop(), &async, async_cb); + ASSERT(r == 0); + + r = uv_run(uv_default_loop()); + ASSERT(r == 0); + + ASSERT(prepare_cb_called > 0); + ASSERT(async_cb_called == 3); + ASSERT(close_cb_called == 2); + + return 0; +} diff --git a/node-v0.8.14/deps/uv/test/test-callback-order.c b/node-v0.8.14/deps/uv/test/test-callback-order.c new file mode 100644 index 0000000..a6c40cb --- /dev/null +++ b/node-v0.8.14/deps/uv/test/test-callback-order.c @@ -0,0 +1,76 @@ +/* Copyright Joyent, Inc. and other Node contributors. All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ + +#include "uv.h" +#include "task.h" + +static int idle_cb_called; +static int timer_cb_called; + +static uv_idle_t idle_handle; +static uv_timer_t timer_handle; + + +/* idle_cb should run before timer_cb */ +static void idle_cb(uv_idle_t* handle, int status) { + ASSERT(idle_cb_called == 0); + ASSERT(timer_cb_called == 0); + uv_idle_stop(handle); + idle_cb_called++; +} + + +static void timer_cb(uv_timer_t* handle, int status) { + ASSERT(idle_cb_called == 1); + ASSERT(timer_cb_called == 0); + uv_timer_stop(handle); + timer_cb_called++; +} + + +static void next_tick(uv_idle_t* handle, int status) { + uv_loop_t* loop = handle->loop; + uv_idle_stop(handle); + uv_idle_init(loop, &idle_handle); + uv_idle_start(&idle_handle, idle_cb); + uv_timer_init(loop, &timer_handle); + uv_timer_start(&timer_handle, timer_cb, 0, 0); +} + + +TEST_IMPL(callback_order) { + uv_loop_t* loop; + uv_idle_t idle; + + loop = uv_default_loop(); + uv_idle_init(loop, &idle); + uv_idle_start(&idle, next_tick); + + ASSERT(idle_cb_called == 0); + ASSERT(timer_cb_called == 0); + + uv_run(loop); + + ASSERT(idle_cb_called == 1); + ASSERT(timer_cb_called == 1); + + return 0; +} diff --git a/node-v0.8.14/deps/uv/test/test-callback-stack.c b/node-v0.8.14/deps/uv/test/test-callback-stack.c new file mode 100644 index 0000000..4983b65 --- /dev/null +++ b/node-v0.8.14/deps/uv/test/test-callback-stack.c @@ -0,0 +1,203 @@ +/* Copyright Joyent, Inc. and other Node contributors. All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ + +/* + * TODO: Add explanation of why we want on_close to be called from fresh + * stack. + */ + +#include "uv.h" +#include "task.h" + + +static const char MESSAGE[] = "Failure is for the weak. Everyone dies alone."; + +static uv_tcp_t client; +static uv_timer_t timer; +static uv_connect_t connect_req; +static uv_write_t write_req; +static uv_shutdown_t shutdown_req; + +static int nested = 0; +static int close_cb_called = 0; +static int connect_cb_called = 0; +static int write_cb_called = 0; +static int timer_cb_called = 0; +static int bytes_received = 0; +static int shutdown_cb_called = 0; + + +static uv_buf_t alloc_cb(uv_handle_t* handle, size_t size) { + uv_buf_t buf; + buf.len = size; + buf.base = (char*) malloc(size); + ASSERT(buf.base); + return buf; +} + + +static void close_cb(uv_handle_t* handle) { + ASSERT(nested == 0 && "close_cb must be called from a fresh stack"); + + close_cb_called++; +} + + +static void shutdown_cb(uv_shutdown_t* req, int status) { + ASSERT(status == 0); + ASSERT(nested == 0 && "shutdown_cb must be called from a fresh stack"); + + shutdown_cb_called++; +} + + +static void read_cb(uv_stream_t* tcp, ssize_t nread, uv_buf_t buf) { + ASSERT(nested == 0 && "read_cb must be called from a fresh stack"); + + printf("Read. nread == %d\n", (int)nread); + free(buf.base); + + if (nread == 0) { + ASSERT(uv_last_error(uv_default_loop()).code == UV_EAGAIN); + return; + + } else if (nread == -1) { + ASSERT(uv_last_error(uv_default_loop()).code == UV_EOF); + + nested++; + uv_close((uv_handle_t*)tcp, close_cb); + nested--; + + return; + } + + bytes_received += nread; + + /* We call shutdown here because when bytes_received == sizeof MESSAGE */ + /* there will be no more data sent nor received, so here it would be */ + /* possible for a backend to to call shutdown_cb immediately and *not* */ + /* from a fresh stack. */ + if (bytes_received == sizeof MESSAGE) { + nested++; + + puts("Shutdown"); + + if (uv_shutdown(&shutdown_req, (uv_stream_t*)tcp, shutdown_cb)) { + FATAL("uv_shutdown failed"); + } + nested--; + } +} + + +static void timer_cb(uv_timer_t* handle, int status) { + ASSERT(handle == &timer); + ASSERT(status == 0); + ASSERT(nested == 0 && "timer_cb must be called from a fresh stack"); + + puts("Timeout complete. Now read data..."); + + nested++; + if (uv_read_start((uv_stream_t*)&client, alloc_cb, read_cb)) { + FATAL("uv_read_start failed"); + } + nested--; + + timer_cb_called++; + + uv_close((uv_handle_t*)handle, close_cb); +} + + +static void write_cb(uv_write_t* req, int status) { + int r; + + ASSERT(status == 0); + ASSERT(nested == 0 && "write_cb must be called from a fresh stack"); + + puts("Data written. 500ms timeout..."); + + /* After the data has been sent, we're going to wait for a while, then */ + /* start reading. This makes us certain that the message has been echoed */ + /* back to our receive buffer when we start reading. This maximizes the */ + /* temptation for the backend to use dirty stack for calling read_cb. */ + nested++; + r = uv_timer_init(uv_default_loop(), &timer); + ASSERT(r == 0); + r = uv_timer_start(&timer, timer_cb, 500, 0); + ASSERT(r == 0); + nested--; + + write_cb_called++; +} + + +static void connect_cb(uv_connect_t* req, int status) { + uv_buf_t buf; + + puts("Connected. Write some data to echo server..."); + + ASSERT(status == 0); + ASSERT(nested == 0 && "connect_cb must be called from a fresh stack"); + + nested++; + + buf.base = (char*) &MESSAGE; + buf.len = sizeof MESSAGE; + + if (uv_write(&write_req, (uv_stream_t*)req->handle, &buf, 1, write_cb)) { + FATAL("uv_write failed"); + } + + nested--; + + connect_cb_called++; +} + + +TEST_IMPL(callback_stack) { + struct sockaddr_in addr = uv_ip4_addr("127.0.0.1", TEST_PORT); + + if (uv_tcp_init(uv_default_loop(), &client)) { + FATAL("uv_tcp_init failed"); + } + + puts("Connecting..."); + + nested++; + + if (uv_tcp_connect(&connect_req, &client, addr, connect_cb)) { + FATAL("uv_tcp_connect failed"); + } + nested--; + + uv_run(uv_default_loop()); + + ASSERT(nested == 0); + ASSERT(connect_cb_called == 1 && "connect_cb must be called exactly once"); + ASSERT(write_cb_called == 1 && "write_cb must be called exactly once"); + ASSERT(timer_cb_called == 1 && "timer_cb must be called exactly once"); + ASSERT(bytes_received == sizeof MESSAGE); + ASSERT(shutdown_cb_called == 1 && "shutdown_cb must be called exactly once"); + ASSERT(close_cb_called == 2 && "close_cb must be called exactly twice"); + + return 0; +} diff --git a/node-v0.8.14/deps/uv/test/test-connection-fail.c b/node-v0.8.14/deps/uv/test/test-connection-fail.c new file mode 100644 index 0000000..1c5a31d --- /dev/null +++ b/node-v0.8.14/deps/uv/test/test-connection-fail.c @@ -0,0 +1,148 @@ +/* Copyright Joyent, Inc. and other Node contributors. All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ + +#include "uv.h" +#include "task.h" + +#include +#include + + +static uv_tcp_t tcp; +static uv_connect_t req; +static int connect_cb_calls; +static int close_cb_calls; + +static uv_timer_t timer; +static int timer_close_cb_calls; +static int timer_cb_calls; + + +static void on_close(uv_handle_t* handle) { + close_cb_calls++; +} + + +static void timer_close_cb(uv_handle_t* handle) { + timer_close_cb_calls++; +} + + +static void timer_cb(uv_timer_t* handle, int status) { + ASSERT(status == 0); + timer_cb_calls++; + + /* + * These are the important asserts. The connection callback has been made, + * but libuv hasn't automatically closed the socket. The user must + * uv_close the handle manually. + */ + ASSERT(close_cb_calls == 0); + ASSERT(connect_cb_calls == 1); + + /* Close the tcp handle. */ + uv_close((uv_handle_t*)&tcp, on_close); + + /* Close the timer. */ + uv_close((uv_handle_t*)handle, timer_close_cb); +} + + +static void on_connect_with_close(uv_connect_t *req, int status) { + ASSERT((uv_stream_t*) &tcp == req->handle); + ASSERT(status == -1); + ASSERT(uv_last_error(uv_default_loop()).code == UV_ECONNREFUSED); + connect_cb_calls++; + + ASSERT(close_cb_calls == 0); + uv_close((uv_handle_t*)req->handle, on_close); +} + + +static void on_connect_without_close(uv_connect_t *req, int status) { + ASSERT(status == -1); + ASSERT(uv_last_error(uv_default_loop()).code == UV_ECONNREFUSED); + connect_cb_calls++; + + uv_timer_start(&timer, timer_cb, 100, 0); + + ASSERT(close_cb_calls == 0); +} + + +void connection_fail(uv_connect_cb connect_cb) { + struct sockaddr_in client_addr, server_addr; + int r; + + client_addr = uv_ip4_addr("0.0.0.0", 0); + + /* There should be no servers listening on this port. */ + server_addr = uv_ip4_addr("127.0.0.1", TEST_PORT); + + /* Try to connect to the server and do NUM_PINGS ping-pongs. */ + r = uv_tcp_init(uv_default_loop(), &tcp); + ASSERT(!r); + + /* We are never doing multiple reads/connects at a time anyway. */ + /* so these handles can be pre-initialized. */ + uv_tcp_bind(&tcp, client_addr); + r = uv_tcp_connect(&req, &tcp, server_addr, connect_cb); + ASSERT(!r); + + uv_run(uv_default_loop()); + + ASSERT(connect_cb_calls == 1); + ASSERT(close_cb_calls == 1); +} + + +/* + * This test attempts to connect to a port where no server is running. We + * expect an error. + */ +TEST_IMPL(connection_fail) { + connection_fail(on_connect_with_close); + + ASSERT(timer_close_cb_calls == 0); + ASSERT(timer_cb_calls == 0); + + return 0; +} + + +/* + * This test is the same as the first except it check that the close + * callback of the tcp handle hasn't been made after the failed connection + * attempt. + */ +TEST_IMPL(connection_fail_doesnt_auto_close) { + int r; + + r = uv_timer_init(uv_default_loop(), &timer); + ASSERT(r == 0); + + connection_fail(on_connect_without_close); + + ASSERT(timer_close_cb_calls == 1); + ASSERT(timer_cb_calls == 1); + + return 0; +} diff --git a/node-v0.8.14/deps/uv/test/test-counters-init.c b/node-v0.8.14/deps/uv/test/test-counters-init.c new file mode 100644 index 0000000..6318684 --- /dev/null +++ b/node-v0.8.14/deps/uv/test/test-counters-init.c @@ -0,0 +1,215 @@ +/* Copyright Joyent, Inc. and other Node contributors. All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +#define UNIX (defined(__unix__) || defined(__POSIX__) || defined(__APPLE__)) +#include "task.h" +#include "uv.h" +#include + +#if UNIX +#include /* unlink, rmdir, etc. */ +#else +# include +# include +# define unlink _unlink +# define rmdir _rmdir +# define stat _stati64 +# define open _open +# define write _write +# define lseek _lseek +# define close _close +#endif + +static char exepath[1024]; +static size_t exepath_size = 1024; +static char* args[3]; +static uv_fs_t open_req; +static uv_tcp_t tcp; +static uv_udp_t udp; +static uv_pipe_t uvpipe; +static uv_tty_t tty; +static uv_prepare_t prepare; +static uv_check_t check; +static uv_idle_t idle; +static uv_async_t async; +static uv_timer_t timer; +static uv_fs_event_t fs_event; +static uv_process_t process; +static uv_process_options_t options; +static uv_fs_t fs_req; + +static void exit_cb(uv_process_t* process, int exit_status, int term_signal) { + ASSERT(exit_status == 1); + ASSERT(term_signal == 0); + uv_close((uv_handle_t*)process, NULL); +} + +static void init_process_options(char* test, uv_exit_cb exit_cb) { + int r = uv_exepath(exepath, &exepath_size); + ASSERT(r == 0); + exepath[exepath_size] = '\0'; + args[0] = exepath; + args[1] = test; + args[2] = NULL; + options.file = exepath; + options.args = args; + options.exit_cb = exit_cb; +} + +static void create_dir(uv_loop_t* loop, const char* name) { + int r; + uv_fs_t req; + r = uv_fs_rmdir(loop, &req, name, NULL); + r = uv_fs_mkdir(loop, &req, name, 0755, NULL); + ASSERT(r == 0 || uv_last_error(loop).code == UV_EEXIST); + uv_fs_req_cleanup(&req); +} + +static void create_cb(uv_fs_t* req) { + ASSERT(req == &open_req); + ASSERT(req->fs_type == UV_FS_OPEN); + ASSERT(req->result != -1); + uv_fs_req_cleanup(req); + unlink("test_file"); +} + +TEST_IMPL(counters_init) { + int r; + uint64_t eio_init_prev; + uint64_t req_init_prev; + uint64_t handle_init_prev; + uint64_t stream_init_prev; + uint64_t tcp_init_prev; + uint64_t udp_init_prev; + uint64_t pipe_init_prev; + uint64_t tty_init_prev; + uint64_t prepare_init_prev; + uint64_t check_init_prev; + uint64_t idle_init_prev; + uint64_t async_init_prev; + uint64_t timer_init_prev; + uint64_t process_init_prev; + uint64_t fs_event_init_prev; + + /* req_init and eio_init test by uv_fs_open() */ + unlink("test_file"); + req_init_prev = uv_default_loop()->counters.req_init; + eio_init_prev = uv_default_loop()->counters.eio_init; + r = uv_fs_open(uv_default_loop(), &open_req, "test_file", O_WRONLY | O_CREAT, + S_IREAD | S_IWRITE, create_cb); + ASSERT(r == 0); + ASSERT(open_req.result == 0); + ASSERT(uv_default_loop()->counters.req_init == ++req_init_prev); +#ifndef _WIN32 + ASSERT(uv_default_loop()->counters.eio_init == ++eio_init_prev); +#endif + + /* tcp_init, stream_init and handle_init test by uv_tcp_init() */ + tcp_init_prev = uv_default_loop()->counters.tcp_init; + stream_init_prev = uv_default_loop()->counters.stream_init; + handle_init_prev = uv_default_loop()->counters.handle_init; + r = uv_tcp_init(uv_default_loop(), &tcp); + ASSERT(r == 0); + ASSERT(uv_default_loop()->counters.tcp_init == ++tcp_init_prev); + ASSERT(uv_default_loop()->counters.stream_init == ++stream_init_prev); + ASSERT(uv_default_loop()->counters.handle_init == ++handle_init_prev); + uv_close((uv_handle_t*)&tcp, NULL); + + /* udp_init test by uv_udp_init() */ + udp_init_prev = uv_default_loop()->counters.udp_init; + r = uv_udp_init(uv_default_loop(), &udp); + ASSERT(r == 0); + ASSERT(uv_default_loop()->counters.udp_init == ++udp_init_prev); + uv_close((uv_handle_t*)&udp, NULL); + + /* pipe_init uv_pipe_init() */ + pipe_init_prev = uv_default_loop()->counters.pipe_init; + uv_pipe_init(uv_default_loop(), &uvpipe, 0); + ASSERT(r == 0); + ASSERT(uv_default_loop()->counters.pipe_init == ++pipe_init_prev); + uv_close((uv_handle_t*)&uvpipe, NULL); + + /* tty_init test by uv_tty_init()*/ + tty_init_prev = uv_default_loop()->counters.tty_init; + r = uv_tty_init(uv_default_loop(), &tty, 1, 0); + /* uv_tty_init() always returns -1 in run_test in Windows + so that we avoid to check return value. + */ +#ifndef _WIN32 + ASSERT(r == 0); + uv_close((uv_handle_t*)&tty, NULL); +#endif + ASSERT(uv_default_loop()->counters.tty_init == ++tty_init_prev); + + /* prepare_init test by uv_prepare_init() */ + prepare_init_prev = uv_default_loop()->counters.prepare_init; + r = uv_prepare_init(uv_default_loop(), &prepare); + ASSERT(r == 0); + ASSERT(uv_default_loop()->counters.prepare_init == ++prepare_init_prev); + uv_close((uv_handle_t*)&prepare, NULL); + + /* check_init test by uv_check_init() */ + check_init_prev = uv_default_loop()->counters.check_init; + r = uv_check_init(uv_default_loop(), &check); + ASSERT(r == 0); + ASSERT(uv_default_loop()->counters.check_init == ++check_init_prev); + uv_close((uv_handle_t*)&check, NULL); + + /* idle_init test by uv_idle_init() */ + idle_init_prev = uv_default_loop()->counters.idle_init; + r = uv_idle_init(uv_default_loop(), &idle); + ASSERT(r == 0); + ASSERT(uv_default_loop()->counters.idle_init == ++idle_init_prev); + uv_close((uv_handle_t*)&idle, NULL); + + /* async_init test by uv_async_init() */ + async_init_prev = uv_default_loop()->counters.async_init; + r = uv_async_init(uv_default_loop(), &async, NULL); + ASSERT(r == 0); + ASSERT(uv_default_loop()->counters.async_init == ++async_init_prev); + uv_close((uv_handle_t*)&async, NULL); + + /* timer_init test by uv_timer_init() */ + timer_init_prev = uv_default_loop()->counters.timer_init; + r = uv_timer_init(uv_default_loop(), &timer); + ASSERT(r == 0); + ASSERT(uv_default_loop()->counters.timer_init == ++timer_init_prev); + uv_close((uv_handle_t*)&timer, NULL); + + /* process_init test by uv_spawn() */ + process_init_prev = uv_default_loop()->counters.process_init; + init_process_options("spawn_helper1", exit_cb); + r = uv_spawn(uv_default_loop(), &process, options); + ASSERT(r == 0); + ASSERT(uv_default_loop()->counters.process_init == ++process_init_prev); + r = uv_run(uv_default_loop()); + ASSERT(r == 0); + + /* fs_event_init test by uv_fs_event_init() */ + create_dir(uv_default_loop(), "watch_dir"); + fs_event_init_prev = uv_default_loop()->counters.fs_event_init; + r = uv_fs_event_init(uv_default_loop(), &fs_event, "watch_dir", NULL, 0); + ASSERT(r == 0); + ASSERT(uv_default_loop()->counters.fs_event_init == ++fs_event_init_prev); + uv_fs_rmdir(uv_default_loop(), &fs_req, "watch_dir", NULL); + uv_fs_req_cleanup(&fs_req); + + return 0; +} diff --git a/node-v0.8.14/deps/uv/test/test-cwd-and-chdir.c b/node-v0.8.14/deps/uv/test/test-cwd-and-chdir.c new file mode 100644 index 0000000..d72c26a --- /dev/null +++ b/node-v0.8.14/deps/uv/test/test-cwd-and-chdir.c @@ -0,0 +1,64 @@ +/* Copyright Joyent, Inc. and other Node contributors. All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ + +#include "uv.h" +#include "task.h" +#include + +#define PATHMAX 1024 +extern char executable_path[]; + +TEST_IMPL(cwd_and_chdir) { + char buffer_orig[PATHMAX]; + char buffer_new[PATHMAX]; + size_t size; + char* last_slash; + uv_err_t err; + + size = sizeof(buffer_orig) / sizeof(buffer_orig[0]); + err = uv_cwd(buffer_orig, size); + ASSERT(err.code == UV_OK); + + /* Remove trailing slash unless at a root directory. */ +#ifdef _WIN32 + last_slash = strrchr(buffer_orig, '\\'); + ASSERT(last_slash); + if (last_slash > buffer_orig && *(last_slash - 1) != ':') { + *last_slash = '\0'; + } +#else /* Unix */ + last_slash = strrchr(buffer_orig, '/'); + ASSERT(last_slash); + if (last_slash != buffer_orig) { + *last_slash = '\0'; + } +#endif + + err = uv_chdir(buffer_orig); + ASSERT(err.code == UV_OK); + + err = uv_cwd(buffer_new, size); + ASSERT(err.code == UV_OK); + + ASSERT(strcmp(buffer_orig, buffer_new) == 0); + + return 0; +} diff --git a/node-v0.8.14/deps/uv/test/test-delayed-accept.c b/node-v0.8.14/deps/uv/test/test-delayed-accept.c new file mode 100644 index 0000000..990444e --- /dev/null +++ b/node-v0.8.14/deps/uv/test/test-delayed-accept.c @@ -0,0 +1,197 @@ +/* Copyright Joyent, Inc. and other Node contributors. All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ + +#include "uv.h" +#include "task.h" +#include +#include + +static int connection_cb_called = 0; +static int do_accept_called = 0; +static int close_cb_called = 0; +static int connect_cb_called = 0; + + +static uv_buf_t alloc_cb(uv_handle_t* handle, size_t size) { + uv_buf_t buf; + buf.base = (char*)malloc(size); + buf.len = size; + return buf; +} + + +static void close_cb(uv_handle_t* handle) { + ASSERT(handle != NULL); + + free(handle); + + close_cb_called++; +} + + +static void do_accept(uv_timer_t* timer_handle, int status) { + uv_tcp_t* server; + uv_tcp_t* accepted_handle = (uv_tcp_t*)malloc(sizeof *accepted_handle); + uint64_t tcpcnt; + int r; + + ASSERT(timer_handle != NULL); + ASSERT(status == 0); + ASSERT(accepted_handle != NULL); + + r = uv_tcp_init(uv_default_loop(), accepted_handle); + ASSERT(r == 0); + + /* Test to that uv_default_loop()->counters.tcp_init does not increase across the uv_accept. */ + tcpcnt = uv_default_loop()->counters.tcp_init; + + server = (uv_tcp_t*)timer_handle->data; + r = uv_accept((uv_stream_t*)server, (uv_stream_t*)accepted_handle); + ASSERT(r == 0); + + ASSERT(uv_default_loop()->counters.tcp_init == tcpcnt); + + do_accept_called++; + + /* Immediately close the accepted handle. */ + uv_close((uv_handle_t*)accepted_handle, close_cb); + + /* After accepting the two clients close the server handle */ + if (do_accept_called == 2) { + uv_close((uv_handle_t*)server, close_cb); + } + + /* Dispose the timer. */ + uv_close((uv_handle_t*)timer_handle, close_cb); +} + + +static void connection_cb(uv_stream_t* tcp, int status) { + int r; + uv_timer_t* timer_handle; + + ASSERT(status == 0); + + timer_handle = (uv_timer_t*)malloc(sizeof *timer_handle); + ASSERT(timer_handle != NULL); + + /* Accept the client after 1 second */ + r = uv_timer_init(uv_default_loop(), timer_handle); + ASSERT(r == 0); + + timer_handle->data = tcp; + + r = uv_timer_start(timer_handle, do_accept, 1000, 0); + ASSERT(r == 0); + + connection_cb_called++; +} + + +static void start_server() { + struct sockaddr_in addr = uv_ip4_addr("0.0.0.0", TEST_PORT); + uv_tcp_t* server = (uv_tcp_t*)malloc(sizeof *server); + int r; + + ASSERT(server != NULL); + + r = uv_tcp_init(uv_default_loop(), server); + ASSERT(r == 0); + ASSERT(uv_default_loop()->counters.tcp_init == 1); + ASSERT(uv_default_loop()->counters.handle_init == 1); + + r = uv_tcp_bind(server, addr); + ASSERT(r == 0); + + r = uv_listen((uv_stream_t*)server, 128, connection_cb); + ASSERT(r == 0); +} + + +static void read_cb(uv_stream_t* tcp, ssize_t nread, uv_buf_t buf) { + /* The server will not send anything, it should close gracefully. */ + + if (buf.base) { + free(buf.base); + } + + if (nread != -1) { + ASSERT(nread == 0); + ASSERT(uv_last_error(uv_default_loop()).code == UV_EAGAIN); + } else { + ASSERT(tcp != NULL); + ASSERT(nread == -1); + ASSERT(uv_last_error(uv_default_loop()).code == UV_EOF); + uv_close((uv_handle_t*)tcp, close_cb); + } +} + + +static void connect_cb(uv_connect_t* req, int status) { + int r; + + ASSERT(req != NULL); + ASSERT(status == 0); + + /* Not that the server will send anything, but otherwise we'll never know */ + /* when the server closes the connection. */ + r = uv_read_start((uv_stream_t*)(req->handle), alloc_cb, read_cb); + ASSERT(r == 0); + + connect_cb_called++; + + free(req); +} + + +static void client_connect() { + struct sockaddr_in addr = uv_ip4_addr("127.0.0.1", TEST_PORT); + uv_tcp_t* client = (uv_tcp_t*)malloc(sizeof *client); + uv_connect_t* connect_req = malloc(sizeof *connect_req); + int r; + + ASSERT(client != NULL); + ASSERT(connect_req != NULL); + + r = uv_tcp_init(uv_default_loop(), client); + ASSERT(r == 0); + + r = uv_tcp_connect(connect_req, client, addr, connect_cb); + ASSERT(r == 0); +} + + + +TEST_IMPL(delayed_accept) { + start_server(); + + client_connect(); + client_connect(); + + uv_run(uv_default_loop()); + + ASSERT(connection_cb_called == 2); + ASSERT(do_accept_called == 2); + ASSERT(connect_cb_called == 2); + ASSERT(close_cb_called == 7); + + return 0; +} diff --git a/node-v0.8.14/deps/uv/test/test-dlerror.c b/node-v0.8.14/deps/uv/test/test-dlerror.c new file mode 100644 index 0000000..877ebf3 --- /dev/null +++ b/node-v0.8.14/deps/uv/test/test-dlerror.c @@ -0,0 +1,58 @@ +/* Copyright Joyent, Inc. and other Node contributors. All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ + +#include "uv.h" +#include "task.h" +#include + + +TEST_IMPL(dlerror) { + const char* path = "test/fixtures/load_error.node"; + const char* msg; + uv_lib_t lib; + int r; + +#ifdef __linux__ + const char* dlerror_desc = "file too short"; +#elif defined (__sun__) + const char* dlerror_desc = "unknown file type"; +#elif defined (_WIN32) + const char* dlerror_desc = "%1 is not a valid Win32 application"; +#else + const char* dlerror_desc = ""; +#endif + + r = uv_dlopen(path, &lib); + ASSERT(r == -1); + + msg = uv_dlerror(&lib); + ASSERT(msg != NULL); + ASSERT(strstr(msg, dlerror_desc) != NULL); + + /* Should return the same error twice in a row. */ + msg = uv_dlerror(&lib); + ASSERT(msg != NULL); + ASSERT(strstr(msg, dlerror_desc) != NULL); + + uv_dlclose(&lib); + + return 0; +} diff --git a/node-v0.8.14/deps/uv/test/test-error.c b/node-v0.8.14/deps/uv/test/test-error.c new file mode 100644 index 0000000..8d6f235 --- /dev/null +++ b/node-v0.8.14/deps/uv/test/test-error.c @@ -0,0 +1,59 @@ +/* Copyright Joyent, Inc. and other Node contributors. All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ + +#include "uv.h" +#include "task.h" + +#include +#include +#include + + +/* + * Synthetic errors (errors that originate from within libuv, not the system) + * should produce sensible error messages when run through uv_strerror(). + * + * See https://github.com/joyent/libuv/issues/210 + */ +TEST_IMPL(error_message) { + uv_err_t e; + + /* Cop out. Can't do proper checks on systems with + * i18n-ized error messages... + */ + e.code = 0, e.sys_errno_ = 0; + + if (strcmp(uv_strerror(e), "Success") != 0) { + printf("i18n error messages detected, skipping test.\n"); + return 0; + } + + e.code = UV_EINVAL, e.sys_errno_ = 0; + ASSERT(strstr(uv_strerror(e), "Success") == NULL); + + e.code = UV_UNKNOWN, e.sys_errno_ = 0; + ASSERT(strcmp(uv_strerror(e), "Unknown error") == 0); + + e.code = 1337, e.sys_errno_ = 0; + ASSERT(strcmp(uv_strerror(e), "Unknown error") == 0); + + return 0; +} diff --git a/node-v0.8.14/deps/uv/test/test-fail-always.c b/node-v0.8.14/deps/uv/test/test-fail-always.c new file mode 100644 index 0000000..0008459 --- /dev/null +++ b/node-v0.8.14/deps/uv/test/test-fail-always.c @@ -0,0 +1,29 @@ +/* Copyright Joyent, Inc. and other Node contributors. All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ + +#include "task.h" + + +TEST_IMPL(fail_always) { + /* This test always fails. It is used to test the test runner. */ + FATAL("Yes, it always fails"); + return 2; +} diff --git a/node-v0.8.14/deps/uv/test/test-fs-event.c b/node-v0.8.14/deps/uv/test/test-fs-event.c new file mode 100644 index 0000000..4d4cfbc --- /dev/null +++ b/node-v0.8.14/deps/uv/test/test-fs-event.c @@ -0,0 +1,474 @@ +/* Copyright Joyent, Inc. and other Node contributors. All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ + +#include "uv.h" +#include "task.h" + +#include +#include + +#ifndef HAVE_KQUEUE +# if __APPLE__ || __FreeBSD__ || __OpenBSD__ || __NetBSD__ +# define HAVE_KQUEUE 1 +# endif +#endif + +static uv_fs_event_t fs_event; +static uv_timer_t timer; +static int timer_cb_called = 0; +static int close_cb_called = 0; +static int fs_event_cb_called = 0; +static int timer_cb_touch_called = 0; + +static void create_dir(uv_loop_t* loop, const char* name) { + int r; + uv_fs_t req; + r = uv_fs_mkdir(loop, &req, name, 0755, NULL); + ASSERT(r == 0 || uv_last_error(loop).code == UV_EEXIST); + uv_fs_req_cleanup(&req); +} + +static void create_file(uv_loop_t* loop, const char* name) { + int r; + uv_file file; + uv_fs_t req; + + r = uv_fs_open(loop, &req, name, O_WRONLY | O_CREAT, + S_IWRITE | S_IREAD, NULL); + ASSERT(r != -1); + file = r; + uv_fs_req_cleanup(&req); + r = uv_fs_close(loop, &req, file, NULL); + ASSERT(r == 0); + uv_fs_req_cleanup(&req); +} + +static void touch_file(uv_loop_t* loop, const char* name) { + int r; + uv_file file; + uv_fs_t req; + + r = uv_fs_open(loop, &req, name, O_RDWR, 0, NULL); + ASSERT(r != -1); + file = r; + uv_fs_req_cleanup(&req); + + r = uv_fs_write(loop, &req, file, "foo", 4, -1, NULL); + ASSERT(r != -1); + uv_fs_req_cleanup(&req); + + r = uv_fs_close(loop, &req, file, NULL); + ASSERT(r != -1); + uv_fs_req_cleanup(&req); +} + +static void close_cb(uv_handle_t* handle) { + ASSERT(handle != NULL); + close_cb_called++; +} + +static void fail_cb(uv_fs_event_t* handle, + const char* path, + int events, + int status) { + ASSERT(0 && "fail_cb called"); +} + +static void fs_event_cb_dir(uv_fs_event_t* handle, const char* filename, + int events, int status) { + ++fs_event_cb_called; + ASSERT(handle == &fs_event); + ASSERT(status == 0); + ASSERT(events == UV_RENAME); + ASSERT(filename == NULL || strcmp(filename, "file1") == 0); + uv_close((uv_handle_t*)handle, close_cb); +} + +static void fs_event_cb_file(uv_fs_event_t* handle, const char* filename, + int events, int status) { + ++fs_event_cb_called; + ASSERT(handle == &fs_event); + ASSERT(status == 0); + ASSERT(events == UV_CHANGE); + ASSERT(filename == NULL || strcmp(filename, "file2") == 0); + uv_close((uv_handle_t*)handle, close_cb); +} + +static void timber_cb_close_handle(uv_timer_t* timer, int status) { + uv_handle_t* handle; + + ASSERT(timer != NULL); + ASSERT(status == 0); + handle = timer->data; + + uv_close((uv_handle_t*)timer, NULL); + uv_close((uv_handle_t*)handle, close_cb); +} + +static void fs_event_cb_file_current_dir(uv_fs_event_t* handle, + const char* filename, int events, int status) { + ASSERT(fs_event_cb_called == 0); + ++fs_event_cb_called; + + ASSERT(handle == &fs_event); + ASSERT(status == 0); + ASSERT(events == UV_CHANGE); + ASSERT(filename == NULL || strcmp(filename, "watch_file") == 0); + + /* Regression test for SunOS: touch should generate just one event. */ + { + static uv_timer_t timer; + uv_timer_init(handle->loop, &timer); + timer.data = handle; + uv_timer_start(&timer, timber_cb_close_handle, 250, 0); + } +} + +static void timer_cb_dir(uv_timer_t* handle, int status) { + ++timer_cb_called; + create_file(handle->loop, "watch_dir/file1"); + uv_close((uv_handle_t*)handle, close_cb); +} + +static void timer_cb_file(uv_timer_t* handle, int status) { + ++timer_cb_called; + + if (timer_cb_called == 1) { + touch_file(handle->loop, "watch_dir/file1"); + } else { + touch_file(handle->loop, "watch_dir/file2"); + uv_close((uv_handle_t*)handle, close_cb); + } +} + +static void timer_cb_touch(uv_timer_t* timer, int status) { + ASSERT(status == 0); + uv_close((uv_handle_t*)timer, NULL); + touch_file(timer->loop, "watch_file"); + timer_cb_touch_called++; +} + +static void timer_cb_watch_twice(uv_timer_t* handle, int status) { + uv_fs_event_t* handles = handle->data; + uv_close((uv_handle_t*) (handles + 0), NULL); + uv_close((uv_handle_t*) (handles + 1), NULL); + uv_close((uv_handle_t*) handle, NULL); +} + +TEST_IMPL(fs_event_watch_dir) { + uv_fs_t fs_req; + uv_loop_t* loop = uv_default_loop(); + int r; + + /* Setup */ + uv_fs_unlink(loop, &fs_req, "watch_dir/file1", NULL); + uv_fs_unlink(loop, &fs_req, "watch_dir/file2", NULL); + uv_fs_rmdir(loop, &fs_req, "watch_dir", NULL); + create_dir(loop, "watch_dir"); + + r = uv_fs_event_init(loop, &fs_event, "watch_dir", fs_event_cb_dir, 0); + ASSERT(r != -1); + r = uv_timer_init(loop, &timer); + ASSERT(r != -1); + r = uv_timer_start(&timer, timer_cb_dir, 100, 0); + ASSERT(r != -1); + + uv_run(loop); + + ASSERT(fs_event_cb_called == 1); + ASSERT(timer_cb_called == 1); + ASSERT(close_cb_called == 2); + + /* Cleanup */ + r = uv_fs_unlink(loop, &fs_req, "watch_dir/file1", NULL); + r = uv_fs_unlink(loop, &fs_req, "watch_dir/file2", NULL); + r = uv_fs_rmdir(loop, &fs_req, "watch_dir", NULL); + + return 0; +} + +TEST_IMPL(fs_event_watch_file) { + uv_fs_t fs_req; + uv_loop_t* loop = uv_default_loop(); + int r; + + /* Setup */ + uv_fs_unlink(loop, &fs_req, "watch_dir/file1", NULL); + uv_fs_unlink(loop, &fs_req, "watch_dir/file2", NULL); + uv_fs_rmdir(loop, &fs_req, "watch_dir", NULL); + create_dir(loop, "watch_dir"); + create_file(loop, "watch_dir/file1"); + create_file(loop, "watch_dir/file2"); + + r = uv_fs_event_init(loop, &fs_event, "watch_dir/file2", fs_event_cb_file, 0); + ASSERT(r != -1); + r = uv_timer_init(loop, &timer); + ASSERT(r != -1); + r = uv_timer_start(&timer, timer_cb_file, 100, 100); + ASSERT(r != -1); + + uv_run(loop); + + ASSERT(fs_event_cb_called == 1); + ASSERT(timer_cb_called == 2); + ASSERT(close_cb_called == 2); + + /* Cleanup */ + r = uv_fs_unlink(loop, &fs_req, "watch_dir/file1", NULL); + r = uv_fs_unlink(loop, &fs_req, "watch_dir/file2", NULL); + r = uv_fs_rmdir(loop, &fs_req, "watch_dir", NULL); + + return 0; +} + +TEST_IMPL(fs_event_watch_file_twice) { + const char path[] = "test/fixtures/empty_file"; + uv_fs_event_t watchers[2]; + uv_timer_t timer; + uv_loop_t* loop; + + loop = uv_default_loop(); + timer.data = watchers; + + ASSERT(0 == uv_fs_event_init(loop, watchers + 0, path, fail_cb, 0)); + ASSERT(0 == uv_fs_event_init(loop, watchers + 1, path, fail_cb, 0)); + ASSERT(0 == uv_timer_init(loop, &timer)); + ASSERT(0 == uv_timer_start(&timer, timer_cb_watch_twice, 10, 0)); + ASSERT(0 == uv_run(loop)); + + return 0; +} + +TEST_IMPL(fs_event_watch_file_current_dir) { + uv_timer_t timer; + uv_loop_t* loop; + uv_fs_t fs_req; + int r; + + loop = uv_default_loop(); + + /* Setup */ + uv_fs_unlink(loop, &fs_req, "watch_file", NULL); + create_file(loop, "watch_file"); + + r = uv_fs_event_init(loop, &fs_event, "watch_file", + fs_event_cb_file_current_dir, 0); + ASSERT(r != -1); + + r = uv_timer_init(loop, &timer); + ASSERT(r == 0); + + r = uv_timer_start(&timer, timer_cb_touch, 1, 0); + ASSERT(r == 0); + + ASSERT(timer_cb_touch_called == 0); + ASSERT(fs_event_cb_called == 0); + ASSERT(close_cb_called == 0); + + uv_run(loop); + + ASSERT(timer_cb_touch_called == 1); + ASSERT(fs_event_cb_called == 1); + ASSERT(close_cb_called == 1); + + /* Cleanup */ + r = uv_fs_unlink(loop, &fs_req, "watch_file", NULL); + return 0; +} + + +TEST_IMPL(fs_event_no_callback_on_close) { + uv_fs_t fs_req; + uv_loop_t* loop = uv_default_loop(); + int r; + + /* Setup */ + uv_fs_unlink(loop, &fs_req, "watch_dir/file1", NULL); + uv_fs_rmdir(loop, &fs_req, "watch_dir", NULL); + create_dir(loop, "watch_dir"); + create_file(loop, "watch_dir/file1"); + + r = uv_fs_event_init(loop, + &fs_event, + "watch_dir/file1", + fs_event_cb_file, + 0); + ASSERT(r != -1); + + uv_close((uv_handle_t*)&fs_event, close_cb); + + uv_run(loop); + + ASSERT(fs_event_cb_called == 0); + ASSERT(close_cb_called == 1); + + /* Cleanup */ + r = uv_fs_unlink(loop, &fs_req, "watch_dir/file1", NULL); + r = uv_fs_rmdir(loop, &fs_req, "watch_dir", NULL); + + return 0; +} + + +static void fs_event_fail(uv_fs_event_t* handle, const char* filename, + int events, int status) { + ASSERT(0 && "should never be called"); +} + + +static void timer_cb(uv_timer_t* handle, int status) { + int r; + + ASSERT(status == 0); + + r = uv_fs_event_init(handle->loop, &fs_event, ".", fs_event_fail, 0); + ASSERT(r == 0); + + uv_close((uv_handle_t*)&fs_event, close_cb); + uv_close((uv_handle_t*)handle, close_cb); +} + + +TEST_IMPL(fs_event_immediate_close) { + uv_timer_t timer; + uv_loop_t* loop; + int r; + + loop = uv_default_loop(); + + r = uv_timer_init(loop, &timer); + ASSERT(r == 0); + + r = uv_timer_start(&timer, timer_cb, 1, 0); + ASSERT(r == 0); + + uv_run(loop); + + ASSERT(close_cb_called == 2); + + return 0; +} + + +TEST_IMPL(fs_event_close_with_pending_event) { + uv_loop_t* loop; + uv_fs_t fs_req; + int r; + + loop = uv_default_loop(); + + create_dir(loop, "watch_dir"); + create_file(loop, "watch_dir/file"); + + r = uv_fs_event_init(loop, &fs_event, "watch_dir", fs_event_fail, 0); + ASSERT(r == 0); + + /* Generate an fs event. */ + touch_file(loop, "watch_dir/file"); + + uv_close((uv_handle_t*)&fs_event, close_cb); + + uv_run(loop); + + ASSERT(close_cb_called == 1); + + /* Clean up */ + r = uv_fs_unlink(loop, &fs_req, "watch_dir/file", NULL); + ASSERT(r == 0); + r = uv_fs_rmdir(loop, &fs_req, "watch_dir", NULL); + ASSERT(r == 0); + + return 0; +} + +#if HAVE_KQUEUE + +/* kqueue doesn't register fs events if you don't have an active watcher. + * The file descriptor needs to be part of the kqueue set of interest and + * that's not the case until we actually enter the event loop. + */ +TEST_IMPL(fs_event_close_in_callback) { + fprintf(stderr, "Skipping test, doesn't work with kqueue.\n"); + return 0; +} + +#else /* !HAVE_KQUEUE */ + +static void fs_event_cb_close(uv_fs_event_t* handle, const char* filename, + int events, int status) { + ASSERT(status == 0); + + ASSERT(fs_event_cb_called < 3); + ++fs_event_cb_called; + + if (fs_event_cb_called == 3) { + uv_close((uv_handle_t*) handle, close_cb); + } +} + + +TEST_IMPL(fs_event_close_in_callback) { + uv_loop_t* loop; + uv_fs_t fs_req; + int r; + + loop = uv_default_loop(); + + create_dir(loop, "watch_dir"); + create_file(loop, "watch_dir/file1"); + create_file(loop, "watch_dir/file2"); + create_file(loop, "watch_dir/file3"); + create_file(loop, "watch_dir/file4"); + create_file(loop, "watch_dir/file5"); + + r = uv_fs_event_init(loop, &fs_event, "watch_dir", fs_event_cb_close, 0); + ASSERT(r == 0); + + /* Generate a couple of fs events. */ + touch_file(loop, "watch_dir/file1"); + touch_file(loop, "watch_dir/file2"); + touch_file(loop, "watch_dir/file3"); + touch_file(loop, "watch_dir/file4"); + touch_file(loop, "watch_dir/file5"); + + uv_run(loop); + + ASSERT(close_cb_called == 1); + ASSERT(fs_event_cb_called == 3); + + /* Clean up */ + r = uv_fs_unlink(loop, &fs_req, "watch_dir/file1", NULL); + ASSERT(r == 0); + r = uv_fs_unlink(loop, &fs_req, "watch_dir/file2", NULL); + ASSERT(r == 0); + r = uv_fs_unlink(loop, &fs_req, "watch_dir/file3", NULL); + ASSERT(r == 0); + r = uv_fs_unlink(loop, &fs_req, "watch_dir/file4", NULL); + ASSERT(r == 0); + r = uv_fs_unlink(loop, &fs_req, "watch_dir/file5", NULL); + ASSERT(r == 0); + r = uv_fs_rmdir(loop, &fs_req, "watch_dir", NULL); + ASSERT(r == 0); + + return 0; +} + +#endif /* HAVE_KQUEUE */ diff --git a/node-v0.8.14/deps/uv/test/test-fs-poll.c b/node-v0.8.14/deps/uv/test/test-fs-poll.c new file mode 100644 index 0000000..00a73b6 --- /dev/null +++ b/node-v0.8.14/deps/uv/test/test-fs-poll.c @@ -0,0 +1,146 @@ +/* Copyright Joyent, Inc. and other Node contributors. All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ + +#include "uv.h" +#include "task.h" + +#include + +#define FIXTURE "testfile" + +static void timer_cb(uv_timer_t* handle, int status); +static void close_cb(uv_handle_t* handle); +static void poll_cb(uv_fs_poll_t* handle, + int status, + const uv_statbuf_t* prev, + const uv_statbuf_t* curr); + +static uv_fs_poll_t poll_handle; +static uv_timer_t timer_handle; +static uv_loop_t* loop; + +static int poll_cb_called; +static int timer_cb_called; +static int close_cb_called; + + +static void touch_file(const char* path) { + static int count; + FILE* fp; + int i; + + ASSERT((fp = fopen(FIXTURE, "w+"))); + + /* Need to change the file size because the poller may not pick up + * sub-second mtime changes. + */ + i = ++count; + + while (i--) + fputc('*', fp); + + fclose(fp); +} + + +static void close_cb(uv_handle_t* handle) { + close_cb_called++; +} + + +static void timer_cb(uv_timer_t* handle, int status) { + touch_file(FIXTURE); + timer_cb_called++; +} + + +static void poll_cb(uv_fs_poll_t* handle, + int status, + const uv_statbuf_t* prev, + const uv_statbuf_t* curr) { + const static uv_statbuf_t zero_statbuf; + + ASSERT(handle == &poll_handle); + ASSERT(uv_is_active((uv_handle_t*)handle)); + ASSERT(prev != NULL); + ASSERT(curr != NULL); + + switch (poll_cb_called++) { + case 0: + ASSERT(status == -1); + ASSERT(uv_last_error(loop).code == UV_ENOENT); + ASSERT(0 == memcmp(prev, &zero_statbuf, sizeof(zero_statbuf))); + ASSERT(0 == memcmp(curr, &zero_statbuf, sizeof(zero_statbuf))); + touch_file(FIXTURE); + break; + + case 1: + ASSERT(status == 0); + ASSERT(0 == memcmp(prev, &zero_statbuf, sizeof(zero_statbuf))); + ASSERT(0 != memcmp(curr, &zero_statbuf, sizeof(zero_statbuf))); + ASSERT(0 == uv_timer_start(&timer_handle, timer_cb, 20, 0)); + break; + + case 2: + ASSERT(status == 0); + ASSERT(0 != memcmp(prev, &zero_statbuf, sizeof(zero_statbuf))); + ASSERT(0 != memcmp(curr, &zero_statbuf, sizeof(zero_statbuf))); + ASSERT(0 == uv_timer_start(&timer_handle, timer_cb, 200, 0)); + break; + + case 3: + ASSERT(status == 0); + ASSERT(0 != memcmp(prev, &zero_statbuf, sizeof(zero_statbuf))); + ASSERT(0 != memcmp(curr, &zero_statbuf, sizeof(zero_statbuf))); + remove(FIXTURE); + break; + + case 4: + ASSERT(status == -1); + ASSERT(0 != memcmp(prev, &zero_statbuf, sizeof(zero_statbuf))); + ASSERT(0 == memcmp(curr, &zero_statbuf, sizeof(zero_statbuf))); + ASSERT(uv_last_error(loop).code == UV_ENOENT); + uv_close((uv_handle_t*)handle, close_cb); + break; + + default: + ASSERT(0); + } +} + + +TEST_IMPL(fs_poll) { + loop = uv_default_loop(); + + remove(FIXTURE); + + ASSERT(0 == uv_timer_init(loop, &timer_handle)); + ASSERT(0 == uv_fs_poll_init(loop, &poll_handle)); + ASSERT(0 == uv_fs_poll_start(&poll_handle, poll_cb, FIXTURE, 100)); + ASSERT(0 == uv_run(loop)); + + ASSERT(poll_cb_called == 5); + ASSERT(timer_cb_called == 2); + ASSERT(close_cb_called == 1); + uv_loop_delete(loop); + + return 0; +} diff --git a/node-v0.8.14/deps/uv/test/test-fs.c b/node-v0.8.14/deps/uv/test/test-fs.c new file mode 100644 index 0000000..4b6d847 --- /dev/null +++ b/node-v0.8.14/deps/uv/test/test-fs.c @@ -0,0 +1,1843 @@ +/* Copyright Joyent, Inc. and other Node contributors. All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ + +/* FIXME we shouldn't need to branch in this file */ +#define UNIX (defined(__unix__) || defined(__POSIX__) || defined(__APPLE__)) + +#include "uv.h" +#include "task.h" + +#include +#include /* memset */ +#include +#include + + +#if UNIX +#include /* unlink, rmdir, etc. */ +#else +# include +# include +# define unlink _unlink +# define rmdir _rmdir +# define stat _stati64 +# define open _open +# define write _write +# define lseek _lseek +# define close _close +#endif + +#define TOO_LONG_NAME_LENGTH 65536 +#define PATHMAX 1024 + +typedef struct { + const char* path; + double atime; + double mtime; +} utime_check_t; + + +static int close_cb_count; +static int create_cb_count; +static int open_cb_count; +static int read_cb_count; +static int write_cb_count; +static int unlink_cb_count; +static int mkdir_cb_count; +static int rmdir_cb_count; +static int readdir_cb_count; +static int stat_cb_count; +static int rename_cb_count; +static int fsync_cb_count; +static int fdatasync_cb_count; +static int ftruncate_cb_count; +static int sendfile_cb_count; +static int fstat_cb_count; +static int chmod_cb_count; +static int fchmod_cb_count; +static int chown_cb_count; +static int fchown_cb_count; +static int link_cb_count; +static int symlink_cb_count; +static int readlink_cb_count; +static int utime_cb_count; +static int futime_cb_count; + +static uv_loop_t* loop; + +static uv_fs_t open_req1; +static uv_fs_t open_req2; +static uv_fs_t read_req; +static uv_fs_t write_req; +static uv_fs_t unlink_req; +static uv_fs_t close_req; +static uv_fs_t mkdir_req; +static uv_fs_t rmdir_req; +static uv_fs_t readdir_req; +static uv_fs_t stat_req; +static uv_fs_t rename_req; +static uv_fs_t fsync_req; +static uv_fs_t fdatasync_req; +static uv_fs_t ftruncate_req; +static uv_fs_t sendfile_req; +static uv_fs_t utime_req; +static uv_fs_t futime_req; + +static char buf[32]; +static char test_buf[] = "test-buffer\n"; + + +void check_permission(const char* filename, int mode) { + int r; + uv_fs_t req; + struct stat* s; + + r = uv_fs_stat(uv_default_loop(), &req, filename, NULL); + ASSERT(r == 0); + ASSERT(req.result == 0); + + s = req.ptr; +#ifdef _WIN32 + /* + * On Windows, chmod can only modify S_IWUSR (_S_IWRITE) bit, + * so only testing for the specified flags. + */ + ASSERT((s->st_mode & 0777) & mode); +#else + ASSERT((s->st_mode & 0777) == mode); +#endif + + uv_fs_req_cleanup(&req); +} + + +static void link_cb(uv_fs_t* req) { + ASSERT(req->fs_type == UV_FS_LINK); + ASSERT(req->result == 0); + link_cb_count++; + uv_fs_req_cleanup(req); +} + + +static void symlink_cb(uv_fs_t* req) { + ASSERT(req->fs_type == UV_FS_SYMLINK); + ASSERT(req->result == 0); + symlink_cb_count++; + uv_fs_req_cleanup(req); +} + +static void readlink_cb(uv_fs_t* req) { + ASSERT(req->fs_type == UV_FS_READLINK); + ASSERT(req->result == 0); + ASSERT(strcmp(req->ptr, "test_file_symlink2") == 0); + readlink_cb_count++; + uv_fs_req_cleanup(req); +} + +static void fchmod_cb(uv_fs_t* req) { + ASSERT(req->fs_type == UV_FS_FCHMOD); + ASSERT(req->result == 0); + fchmod_cb_count++; + uv_fs_req_cleanup(req); + check_permission("test_file", *(int*)req->data); +} + + +static void chmod_cb(uv_fs_t* req) { + ASSERT(req->fs_type == UV_FS_CHMOD); + ASSERT(req->result == 0); + chmod_cb_count++; + uv_fs_req_cleanup(req); + check_permission("test_file", *(int*)req->data); +} + + +static void fchown_cb(uv_fs_t* req) { + ASSERT(req->fs_type == UV_FS_FCHOWN); + ASSERT(req->result == 0); + fchown_cb_count++; + uv_fs_req_cleanup(req); +} + + +static void chown_cb(uv_fs_t* req) { + ASSERT(req->fs_type == UV_FS_CHOWN); + ASSERT(req->result == 0); + chown_cb_count++; + uv_fs_req_cleanup(req); +} + +static void chown_root_cb(uv_fs_t* req) { + ASSERT(req->fs_type == UV_FS_CHOWN); +#ifdef _WIN32 + /* On windows, chown is a no-op and always succeeds. */ + ASSERT(req->result == 0); +#else + /* On unix, chown'ing the root directory is not allowed. */ + ASSERT(req->result == -1); + ASSERT(req->errorno == UV_EPERM); +#endif + chown_cb_count++; + uv_fs_req_cleanup(req); +} + +static void unlink_cb(uv_fs_t* req) { + ASSERT(req == &unlink_req); + ASSERT(req->fs_type == UV_FS_UNLINK); + ASSERT(req->result != -1); + unlink_cb_count++; + uv_fs_req_cleanup(req); +} + +static void fstat_cb(uv_fs_t* req) { + struct stat* s = req->ptr; + ASSERT(req->fs_type == UV_FS_FSTAT); + ASSERT(req->result == 0); + ASSERT(s->st_size == sizeof(test_buf)); + uv_fs_req_cleanup(req); + fstat_cb_count++; +} + + +static void close_cb(uv_fs_t* req) { + int r; + ASSERT(req == &close_req); + ASSERT(req->fs_type == UV_FS_CLOSE); + ASSERT(req->result != -1); + close_cb_count++; + uv_fs_req_cleanup(req); + if (close_cb_count == 3) { + r = uv_fs_unlink(loop, &unlink_req, "test_file2", unlink_cb); + ASSERT(r == 0); + } +} + + +static void ftruncate_cb(uv_fs_t* req) { + int r; + ASSERT(req == &ftruncate_req); + ASSERT(req->fs_type == UV_FS_FTRUNCATE); + ASSERT(req->result != -1); + ftruncate_cb_count++; + uv_fs_req_cleanup(req); + r = uv_fs_close(loop, &close_req, open_req1.result, close_cb); + ASSERT(r == 0); +} + + +static void read_cb(uv_fs_t* req) { + int r; + ASSERT(req == &read_req); + ASSERT(req->fs_type == UV_FS_READ); + ASSERT(req->result != -1); + read_cb_count++; + uv_fs_req_cleanup(req); + if (read_cb_count == 1) { + ASSERT(strcmp(buf, test_buf) == 0); + r = uv_fs_ftruncate(loop, &ftruncate_req, open_req1.result, 7, + ftruncate_cb); + } else { + ASSERT(strcmp(buf, "test-bu") == 0); + r = uv_fs_close(loop, &close_req, open_req1.result, close_cb); + } + ASSERT(r == 0); +} + + +static void open_cb(uv_fs_t* req) { + int r; + ASSERT(req == &open_req1); + ASSERT(req->fs_type == UV_FS_OPEN); + if (req->result < 0) { + /* TODO get error with uv_last_error() */ + fprintf(stderr, "async open error: %d\n", req->errorno); + ASSERT(0); + } + open_cb_count++; + ASSERT(req->path); + ASSERT(memcmp(req->path, "test_file2\0", 11) == 0); + uv_fs_req_cleanup(req); + memset(buf, 0, sizeof(buf)); + r = uv_fs_read(loop, &read_req, open_req1.result, buf, sizeof(buf), -1, + read_cb); + ASSERT(r == 0); +} + + +static void open_cb_simple(uv_fs_t* req) { + ASSERT(req->fs_type == UV_FS_OPEN); + if (req->result < 0) { + /* TODO get error with uv_last_error() */ + fprintf(stderr, "async open error: %d\n", req->errorno); + ASSERT(0); + } + open_cb_count++; + ASSERT(req->path); + uv_fs_req_cleanup(req); +} + + +static void fsync_cb(uv_fs_t* req) { + int r; + ASSERT(req == &fsync_req); + ASSERT(req->fs_type == UV_FS_FSYNC); + ASSERT(req->result != -1); + fsync_cb_count++; + uv_fs_req_cleanup(req); + r = uv_fs_close(loop, &close_req, open_req1.result, close_cb); + ASSERT(r == 0); +} + + +static void fdatasync_cb(uv_fs_t* req) { + int r; + ASSERT(req == &fdatasync_req); + ASSERT(req->fs_type == UV_FS_FDATASYNC); + ASSERT(req->result != -1); + fdatasync_cb_count++; + uv_fs_req_cleanup(req); + r = uv_fs_fsync(loop, &fsync_req, open_req1.result, fsync_cb); + ASSERT(r == 0); +} + + +static void write_cb(uv_fs_t* req) { + int r; + ASSERT(req == &write_req); + ASSERT(req->fs_type == UV_FS_WRITE); + ASSERT(req->result != -1); + write_cb_count++; + uv_fs_req_cleanup(req); + r = uv_fs_fdatasync(loop, &fdatasync_req, open_req1.result, fdatasync_cb); + ASSERT(r == 0); +} + + +static void create_cb(uv_fs_t* req) { + int r; + ASSERT(req == &open_req1); + ASSERT(req->fs_type == UV_FS_OPEN); + ASSERT(req->result != -1); + create_cb_count++; + uv_fs_req_cleanup(req); + r = uv_fs_write(loop, &write_req, req->result, test_buf, sizeof(test_buf), + -1, write_cb); + ASSERT(r == 0); +} + + +static void rename_cb(uv_fs_t* req) { + ASSERT(req == &rename_req); + ASSERT(req->fs_type == UV_FS_RENAME); + ASSERT(req->result != -1); + rename_cb_count++; + uv_fs_req_cleanup(req); +} + + +static void mkdir_cb(uv_fs_t* req) { + ASSERT(req == &mkdir_req); + ASSERT(req->fs_type == UV_FS_MKDIR); + ASSERT(req->result != -1); + mkdir_cb_count++; + ASSERT(req->path); + ASSERT(memcmp(req->path, "test_dir\0", 9) == 0); + uv_fs_req_cleanup(req); +} + + +static void rmdir_cb(uv_fs_t* req) { + ASSERT(req == &rmdir_req); + ASSERT(req->fs_type == UV_FS_RMDIR); + ASSERT(req->result != -1); + rmdir_cb_count++; + ASSERT(req->path); + ASSERT(memcmp(req->path, "test_dir\0", 9) == 0); + uv_fs_req_cleanup(req); +} + + +static void readdir_cb(uv_fs_t* req) { + ASSERT(req == &readdir_req); + ASSERT(req->fs_type == UV_FS_READDIR); + ASSERT(req->result == 2); + ASSERT(req->ptr); + ASSERT(memcmp(req->ptr, "file1\0file2\0", 12) == 0 + || memcmp(req->ptr, "file2\0file1\0", 12) == 0); + readdir_cb_count++; + ASSERT(req->path); + ASSERT(memcmp(req->path, "test_dir\0", 9) == 0); + uv_fs_req_cleanup(req); + ASSERT(!req->ptr); +} + + +static void empty_readdir_cb(uv_fs_t* req) { + ASSERT(req == &readdir_req); + ASSERT(req->fs_type == UV_FS_READDIR); + ASSERT(req->result == 0); + ASSERT(req->ptr == NULL); + uv_fs_req_cleanup(req); + readdir_cb_count++; +} + + +static void file_readdir_cb(uv_fs_t* req) { + ASSERT(req == &readdir_req); + ASSERT(req->fs_type == UV_FS_READDIR); + ASSERT(req->result == -1); + ASSERT(req->ptr == NULL); + ASSERT(uv_last_error(req->loop).code == UV_ENOTDIR); + uv_fs_req_cleanup(req); + readdir_cb_count++; +} + + +static void stat_cb(uv_fs_t* req) { + ASSERT(req == &stat_req); + ASSERT(req->fs_type == UV_FS_STAT || req->fs_type == UV_FS_LSTAT); + ASSERT(req->result != -1); + ASSERT(req->ptr); + stat_cb_count++; + uv_fs_req_cleanup(req); + ASSERT(!req->ptr); +} + + +static void sendfile_cb(uv_fs_t* req) { + ASSERT(req == &sendfile_req); + ASSERT(req->fs_type == UV_FS_SENDFILE); + ASSERT(req->result == 65546); + sendfile_cb_count++; + uv_fs_req_cleanup(req); +} + + +static void open_noent_cb(uv_fs_t* req) { + ASSERT(req->fs_type == UV_FS_OPEN); + ASSERT(req->errorno == UV_ENOENT); + ASSERT(req->result == -1); + open_cb_count++; + uv_fs_req_cleanup(req); +} + +static void open_nametoolong_cb(uv_fs_t* req) { + ASSERT(req->fs_type == UV_FS_OPEN); + ASSERT(req->errorno == UV_ENAMETOOLONG); + ASSERT(req->result == -1); + open_cb_count++; + uv_fs_req_cleanup(req); +} + +static void open_loop_cb(uv_fs_t* req) { + ASSERT(req->fs_type == UV_FS_OPEN); + ASSERT(req->errorno == UV_ELOOP); + ASSERT(req->result == -1); + open_cb_count++; + uv_fs_req_cleanup(req); +} + + +TEST_IMPL(fs_file_noent) { + uv_fs_t req; + int r; + + loop = uv_default_loop(); + + r = uv_fs_open(loop, &req, "does_not_exist", O_RDONLY, 0, NULL); + ASSERT(r == -1); + ASSERT(req.result == -1); + ASSERT(uv_last_error(loop).code == UV_ENOENT); + uv_fs_req_cleanup(&req); + + r = uv_fs_open(loop, &req, "does_not_exist", O_RDONLY, 0, open_noent_cb); + ASSERT(r == 0); + + ASSERT(open_cb_count == 0); + uv_run(loop); + ASSERT(open_cb_count == 1); + + /* TODO add EACCES test */ + + return 0; +} + +TEST_IMPL(fs_file_nametoolong) { + uv_fs_t req; + int r; + char name[TOO_LONG_NAME_LENGTH + 1]; + + loop = uv_default_loop(); + + memset(name, 'a', TOO_LONG_NAME_LENGTH); + name[TOO_LONG_NAME_LENGTH] = 0; + + r = uv_fs_open(loop, &req, name, O_RDONLY, 0, NULL); + ASSERT(r == -1); + ASSERT(req.result == -1); + ASSERT(uv_last_error(loop).code == UV_ENAMETOOLONG); + uv_fs_req_cleanup(&req); + + r = uv_fs_open(loop, &req, name, O_RDONLY, 0, open_nametoolong_cb); + ASSERT(r == 0); + + ASSERT(open_cb_count == 0); + uv_run(loop); + ASSERT(open_cb_count == 1); + + return 0; +} + +TEST_IMPL(fs_file_loop) { + uv_fs_t req; + int r; + + loop = uv_default_loop(); + + unlink("test_symlink"); + uv_fs_symlink(loop, &req, "test_symlink", "test_symlink", 0, NULL); + uv_fs_req_cleanup(&req); + + r = uv_fs_open(loop, &req, "test_symlink", O_RDONLY, 0, NULL); + ASSERT(r == -1); + ASSERT(req.result == -1); + ASSERT(uv_last_error(loop).code == UV_ELOOP); + uv_fs_req_cleanup(&req); + + r = uv_fs_open(loop, &req, "test_symlink", O_RDONLY, 0, open_loop_cb); + ASSERT(r == 0); + + ASSERT(open_cb_count == 0); + uv_run(loop); + ASSERT(open_cb_count == 1); + + unlink("test_symlink"); + + return 0; +} + +static void check_utime(const char* path, double atime, double mtime) { + struct stat* s; + uv_fs_t req; + int r; + + r = uv_fs_stat(loop, &req, path, NULL); + ASSERT(r == 0); + + ASSERT(req.result == 0); + s = req.ptr; + +#if _WIN32 + ASSERT(s->st_atime == atime); + ASSERT(s->st_mtime == mtime); +#elif !defined(_POSIX_C_SOURCE) || defined(_DARWIN_C_SOURCE) + ASSERT(s->st_atimespec.tv_sec == atime); + ASSERT(s->st_mtimespec.tv_sec == mtime); +#else + ASSERT(s->st_atim.tv_sec == atime); + ASSERT(s->st_mtim.tv_sec == mtime); +#endif + + uv_fs_req_cleanup(&req); +} + + +static void utime_cb(uv_fs_t* req) { + utime_check_t* c; + + ASSERT(req == &utime_req); + ASSERT(req->result == 0); + ASSERT(req->fs_type == UV_FS_UTIME); + + c = req->data; + check_utime(c->path, c->atime, c->mtime); + + uv_fs_req_cleanup(req); + utime_cb_count++; +} + + +static void futime_cb(uv_fs_t* req) { + utime_check_t* c; + + ASSERT(req == &futime_req); + ASSERT(req->result == 0); + ASSERT(req->fs_type == UV_FS_FUTIME); + + c = req->data; + check_utime(c->path, c->atime, c->mtime); + + uv_fs_req_cleanup(req); + futime_cb_count++; +} + + +TEST_IMPL(fs_file_async) { + int r; + + /* Setup. */ + unlink("test_file"); + unlink("test_file2"); + + loop = uv_default_loop(); + + r = uv_fs_open(loop, &open_req1, "test_file", O_WRONLY | O_CREAT, + S_IREAD | S_IWRITE, create_cb); + ASSERT(r == 0); + uv_run(loop); + + ASSERT(create_cb_count == 1); + ASSERT(write_cb_count == 1); + ASSERT(fsync_cb_count == 1); + ASSERT(fdatasync_cb_count == 1); + ASSERT(close_cb_count == 1); + + r = uv_fs_rename(loop, &rename_req, "test_file", "test_file2", rename_cb); + ASSERT(r == 0); + + uv_run(loop); + ASSERT(create_cb_count == 1); + ASSERT(write_cb_count == 1); + ASSERT(close_cb_count == 1); + ASSERT(rename_cb_count == 1); + + r = uv_fs_open(loop, &open_req1, "test_file2", O_RDWR, 0, open_cb); + ASSERT(r == 0); + + uv_run(loop); + ASSERT(open_cb_count == 1); + ASSERT(read_cb_count == 1); + ASSERT(close_cb_count == 2); + ASSERT(rename_cb_count == 1); + ASSERT(create_cb_count == 1); + ASSERT(write_cb_count == 1); + ASSERT(ftruncate_cb_count == 1); + + r = uv_fs_open(loop, &open_req1, "test_file2", O_RDONLY, 0, open_cb); + ASSERT(r == 0); + + uv_run(loop); + ASSERT(open_cb_count == 2); + ASSERT(read_cb_count == 2); + ASSERT(close_cb_count == 3); + ASSERT(rename_cb_count == 1); + ASSERT(unlink_cb_count == 1); + ASSERT(create_cb_count == 1); + ASSERT(write_cb_count == 1); + ASSERT(ftruncate_cb_count == 1); + + /* Cleanup. */ + unlink("test_file"); + unlink("test_file2"); + + return 0; +} + + +TEST_IMPL(fs_file_sync) { + int r; + + /* Setup. */ + unlink("test_file"); + unlink("test_file2"); + + loop = uv_default_loop(); + + r = uv_fs_open(loop, &open_req1, "test_file", O_WRONLY | O_CREAT, + S_IWRITE | S_IREAD, NULL); + ASSERT(r != -1); + ASSERT(open_req1.result != -1); + uv_fs_req_cleanup(&open_req1); + + r = uv_fs_write(loop, &write_req, open_req1.result, test_buf, + sizeof(test_buf), -1, NULL); + ASSERT(r != -1); + ASSERT(write_req.result != -1); + uv_fs_req_cleanup(&write_req); + + r = uv_fs_close(loop, &close_req, open_req1.result, NULL); + ASSERT(r != -1); + ASSERT(close_req.result != -1); + uv_fs_req_cleanup(&close_req); + + r = uv_fs_open(loop, &open_req1, "test_file", O_RDWR, 0, NULL); + ASSERT(r != -1); + ASSERT(open_req1.result != -1); + uv_fs_req_cleanup(&open_req1); + + r = uv_fs_read(loop, &read_req, open_req1.result, buf, sizeof(buf), -1, + NULL); + ASSERT(r != -1); + ASSERT(read_req.result != -1); + ASSERT(strcmp(buf, test_buf) == 0); + uv_fs_req_cleanup(&read_req); + + r = uv_fs_ftruncate(loop, &ftruncate_req, open_req1.result, 7, NULL); + ASSERT(r != -1); + ASSERT(ftruncate_req.result != -1); + uv_fs_req_cleanup(&ftruncate_req); + + r = uv_fs_close(loop, &close_req, open_req1.result, NULL); + ASSERT(r != -1); + ASSERT(close_req.result != -1); + uv_fs_req_cleanup(&close_req); + + r = uv_fs_rename(loop, &rename_req, "test_file", "test_file2", NULL); + ASSERT(r != -1); + ASSERT(rename_req.result != -1); + uv_fs_req_cleanup(&rename_req); + + r = uv_fs_open(loop, &open_req1, "test_file2", O_RDONLY, 0, NULL); + ASSERT(r != -1); + ASSERT(open_req1.result != -1); + uv_fs_req_cleanup(&open_req1); + + memset(buf, 0, sizeof(buf)); + r = uv_fs_read(loop, &read_req, open_req1.result, buf, sizeof(buf), -1, + NULL); + ASSERT(r != -1); + ASSERT(read_req.result != -1); + ASSERT(strcmp(buf, "test-bu") == 0); + uv_fs_req_cleanup(&read_req); + + r = uv_fs_close(loop, &close_req, open_req1.result, NULL); + ASSERT(r != -1); + ASSERT(close_req.result != -1); + uv_fs_req_cleanup(&close_req); + + r = uv_fs_unlink(loop, &unlink_req, "test_file2", NULL); + ASSERT(r != -1); + ASSERT(unlink_req.result != -1); + uv_fs_req_cleanup(&unlink_req); + + /* Cleanup */ + unlink("test_file"); + unlink("test_file2"); + + return 0; +} + + +TEST_IMPL(fs_async_dir) { + int r; + + /* Setup */ + unlink("test_dir/file1"); + unlink("test_dir/file2"); + rmdir("test_dir"); + + loop = uv_default_loop(); + + r = uv_fs_mkdir(loop, &mkdir_req, "test_dir", 0755, mkdir_cb); + ASSERT(r == 0); + + uv_run(loop); + ASSERT(mkdir_cb_count == 1); + + /* Create 2 files synchronously. */ + r = uv_fs_open(loop, &open_req1, "test_dir/file1", O_WRONLY | O_CREAT, + S_IWRITE | S_IREAD, NULL); + ASSERT(r != -1); + uv_fs_req_cleanup(&open_req1); + r = uv_fs_close(loop, &close_req, open_req1.result, NULL); + ASSERT(r == 0); + uv_fs_req_cleanup(&close_req); + + r = uv_fs_open(loop, &open_req1, "test_dir/file2", O_WRONLY | O_CREAT, + S_IWRITE | S_IREAD, NULL); + ASSERT(r != -1); + uv_fs_req_cleanup(&open_req1); + r = uv_fs_close(loop, &close_req, open_req1.result, NULL); + ASSERT(r == 0); + uv_fs_req_cleanup(&close_req); + + r = uv_fs_readdir(loop, &readdir_req, "test_dir", 0, readdir_cb); + ASSERT(r == 0); + + uv_run(loop); + ASSERT(readdir_cb_count == 1); + + /* sync uv_fs_readdir */ + r = uv_fs_readdir(loop, &readdir_req, "test_dir", 0, NULL); + ASSERT(r == 2); + ASSERT(readdir_req.result == 2); + ASSERT(readdir_req.ptr); + ASSERT(memcmp(readdir_req.ptr, "file1\0file2\0", 12) == 0 + || memcmp(readdir_req.ptr, "file2\0file1\0", 12) == 0); + uv_fs_req_cleanup(&readdir_req); + ASSERT(!readdir_req.ptr); + + r = uv_fs_stat(loop, &stat_req, "test_dir", stat_cb); + ASSERT(r == 0); + uv_run(loop); + + r = uv_fs_stat(loop, &stat_req, "test_dir\\", stat_cb); + ASSERT(r == 0); + uv_run(loop); + + r = uv_fs_lstat(loop, &stat_req, "test_dir", stat_cb); + ASSERT(r == 0); + uv_run(loop); + + r = uv_fs_lstat(loop, &stat_req, "test_dir\\", stat_cb); + ASSERT(r == 0); + uv_run(loop); + + ASSERT(stat_cb_count == 4); + + r = uv_fs_unlink(loop, &unlink_req, "test_dir/file1", unlink_cb); + ASSERT(r == 0); + uv_run(loop); + ASSERT(unlink_cb_count == 1); + + r = uv_fs_unlink(loop, &unlink_req, "test_dir/file2", unlink_cb); + ASSERT(r == 0); + uv_run(loop); + ASSERT(unlink_cb_count == 2); + + r = uv_fs_rmdir(loop, &rmdir_req, "test_dir", rmdir_cb); + ASSERT(r == 0); + uv_run(loop); + ASSERT(rmdir_cb_count == 1); + + /* Cleanup */ + unlink("test_dir/file1"); + unlink("test_dir/file2"); + rmdir("test_dir"); + + return 0; +} + + +TEST_IMPL(fs_async_sendfile) { + int f, r; + struct stat s1, s2; + + loop = uv_default_loop(); + + /* Setup. */ + unlink("test_file"); + unlink("test_file2"); + + f = open("test_file", O_WRONLY | O_CREAT, S_IWRITE | S_IREAD); + ASSERT(f != -1); + + r = write(f, "begin\n", 6); + ASSERT(r == 6); + + r = lseek(f, 65536, SEEK_CUR); + ASSERT(r == 65542); + + r = write(f, "end\n", 4); + ASSERT(r != -1); + + r = close(f); + ASSERT(r == 0); + + /* Test starts here. */ + r = uv_fs_open(loop, &open_req1, "test_file", O_RDWR, 0, NULL); + ASSERT(r != -1); + ASSERT(open_req1.result != -1); + uv_fs_req_cleanup(&open_req1); + + r = uv_fs_open(loop, &open_req2, "test_file2", O_WRONLY | O_CREAT, + S_IWRITE | S_IREAD, NULL); + ASSERT(r != -1); + ASSERT(open_req2.result != -1); + uv_fs_req_cleanup(&open_req2); + + r = uv_fs_sendfile(loop, &sendfile_req, open_req2.result, open_req1.result, + 0, 131072, sendfile_cb); + ASSERT(r == 0); + uv_run(loop); + + ASSERT(sendfile_cb_count == 1); + + r = uv_fs_close(loop, &close_req, open_req1.result, NULL); + ASSERT(r == 0); + uv_fs_req_cleanup(&close_req); + r = uv_fs_close(loop, &close_req, open_req2.result, NULL); + ASSERT(r == 0); + uv_fs_req_cleanup(&close_req); + + stat("test_file", &s1); + stat("test_file2", &s2); + ASSERT(65546 == s2.st_size && s1.st_size == s2.st_size); + + /* Cleanup. */ + unlink("test_file"); + unlink("test_file2"); + + return 0; +} + + +TEST_IMPL(fs_fstat) { + int r; + uv_fs_t req; + uv_file file; + struct stat* s; + + /* Setup. */ + unlink("test_file"); + + loop = uv_default_loop(); + + r = uv_fs_open(loop, &req, "test_file", O_RDWR | O_CREAT, + S_IWRITE | S_IREAD, NULL); + ASSERT(r != -1); + ASSERT(req.result != -1); + file = req.result; + uv_fs_req_cleanup(&req); + + r = uv_fs_write(loop, &req, file, test_buf, sizeof(test_buf), -1, NULL); + ASSERT(r == sizeof(test_buf)); + ASSERT(req.result == sizeof(test_buf)); + uv_fs_req_cleanup(&req); + + r = uv_fs_fstat(loop, &req, file, NULL); + ASSERT(r == 0); + ASSERT(req.result == 0); + s = req.ptr; + ASSERT(s->st_size == sizeof(test_buf)); + uv_fs_req_cleanup(&req); + + /* Now do the uv_fs_fstat call asynchronously */ + r = uv_fs_fstat(loop, &req, file, fstat_cb); + ASSERT(r == 0); + uv_run(loop); + ASSERT(fstat_cb_count == 1); + + + r = uv_fs_close(loop, &req, file, NULL); + ASSERT(r == 0); + ASSERT(req.result == 0); + uv_fs_req_cleanup(&req); + + /* + * Run the loop just to check we don't have make any extraneous uv_ref() + * calls. This should drop out immediately. + */ + uv_run(loop); + + /* Cleanup. */ + unlink("test_file"); + + return 0; +} + + +TEST_IMPL(fs_chmod) { + int r; + uv_fs_t req; + uv_file file; + + /* Setup. */ + unlink("test_file"); + + loop = uv_default_loop(); + + r = uv_fs_open(loop, &req, "test_file", O_RDWR | O_CREAT, + S_IWRITE | S_IREAD, NULL); + ASSERT(r != -1); + ASSERT(req.result != -1); + file = req.result; + uv_fs_req_cleanup(&req); + + r = uv_fs_write(loop, &req, file, test_buf, sizeof(test_buf), -1, NULL); + ASSERT(r == sizeof(test_buf)); + ASSERT(req.result == sizeof(test_buf)); + uv_fs_req_cleanup(&req); + +#ifndef _WIN32 + /* Make the file write-only */ + r = uv_fs_chmod(loop, &req, "test_file", 0200, NULL); + ASSERT(r == 0); + ASSERT(req.result == 0); + uv_fs_req_cleanup(&req); + + check_permission("test_file", 0200); +#endif + + /* Make the file read-only */ + r = uv_fs_chmod(loop, &req, "test_file", 0400, NULL); + ASSERT(r == 0); + ASSERT(req.result == 0); + uv_fs_req_cleanup(&req); + + check_permission("test_file", 0400); + + /* Make the file read+write with sync uv_fs_fchmod */ + r = uv_fs_fchmod(loop, &req, file, 0600, NULL); + ASSERT(r == 0); + ASSERT(req.result == 0); + uv_fs_req_cleanup(&req); + + check_permission("test_file", 0600); + +#ifndef _WIN32 + /* async chmod */ + { + static int mode = 0200; + req.data = &mode; + } + r = uv_fs_chmod(loop, &req, "test_file", 0200, chmod_cb); + ASSERT(r == 0); + uv_run(loop); + ASSERT(chmod_cb_count == 1); + chmod_cb_count = 0; /* reset for the next test */ +#endif + + /* async chmod */ + { + static int mode = 0400; + req.data = &mode; + } + r = uv_fs_chmod(loop, &req, "test_file", 0400, chmod_cb); + ASSERT(r == 0); + uv_run(loop); + ASSERT(chmod_cb_count == 1); + + /* async fchmod */ + { + static int mode = 0600; + req.data = &mode; + } + r = uv_fs_fchmod(loop, &req, file, 0600, fchmod_cb); + ASSERT(r == 0); + uv_run(loop); + ASSERT(fchmod_cb_count == 1); + + close(file); + + /* + * Run the loop just to check we don't have make any extraneous uv_ref() + * calls. This should drop out immediately. + */ + uv_run(loop); + + /* Cleanup. */ + unlink("test_file"); + + return 0; +} + + +TEST_IMPL(fs_chown) { + int r; + uv_fs_t req; + uv_file file; + + /* Setup. */ + unlink("test_file"); + + loop = uv_default_loop(); + + r = uv_fs_open(loop, &req, "test_file", O_RDWR | O_CREAT, + S_IWRITE | S_IREAD, NULL); + ASSERT(r != -1); + ASSERT(req.result != -1); + file = req.result; + uv_fs_req_cleanup(&req); + + /* sync chown */ + r = uv_fs_chown(loop, &req, "test_file", -1, -1, NULL); + ASSERT(r == 0); + ASSERT(req.result == 0); + uv_fs_req_cleanup(&req); + + /* sync fchown */ + r = uv_fs_fchown(loop, &req, file, -1, -1, NULL); + ASSERT(r == 0); + ASSERT(req.result == 0); + uv_fs_req_cleanup(&req); + + /* async chown */ + r = uv_fs_chown(loop, &req, "test_file", -1, -1, chown_cb); + ASSERT(r == 0); + uv_run(loop); + ASSERT(chown_cb_count == 1); + + /* chown to root (fail) */ + chown_cb_count = 0; + r = uv_fs_chown(loop, &req, "test_file", 0, 0, chown_root_cb); + uv_run(loop); + ASSERT(chown_cb_count == 1); + + /* async fchown */ + r = uv_fs_fchown(loop, &req, file, -1, -1, fchown_cb); + ASSERT(r == 0); + uv_run(loop); + ASSERT(fchown_cb_count == 1); + + close(file); + + /* + * Run the loop just to check we don't have make any extraneous uv_ref() + * calls. This should drop out immediately. + */ + uv_run(loop); + + /* Cleanup. */ + unlink("test_file"); + + return 0; +} + + +TEST_IMPL(fs_link) { + int r; + uv_fs_t req; + uv_file file; + uv_file link; + + /* Setup. */ + unlink("test_file"); + unlink("test_file_link"); + unlink("test_file_link2"); + + loop = uv_default_loop(); + + r = uv_fs_open(loop, &req, "test_file", O_RDWR | O_CREAT, + S_IWRITE | S_IREAD, NULL); + ASSERT(r != -1); + ASSERT(req.result != -1); + file = req.result; + uv_fs_req_cleanup(&req); + + r = uv_fs_write(loop, &req, file, test_buf, sizeof(test_buf), -1, NULL); + ASSERT(r == sizeof(test_buf)); + ASSERT(req.result == sizeof(test_buf)); + uv_fs_req_cleanup(&req); + + close(file); + + /* sync link */ + r = uv_fs_link(loop, &req, "test_file", "test_file_link", NULL); + ASSERT(r == 0); + ASSERT(req.result == 0); + uv_fs_req_cleanup(&req); + + r = uv_fs_open(loop, &req, "test_file_link", O_RDWR, 0, NULL); + ASSERT(r != -1); + ASSERT(req.result != -1); + link = req.result; + uv_fs_req_cleanup(&req); + + memset(buf, 0, sizeof(buf)); + r = uv_fs_read(loop, &req, link, buf, sizeof(buf), 0, NULL); + ASSERT(r != -1); + ASSERT(req.result != -1); + ASSERT(strcmp(buf, test_buf) == 0); + + close(link); + + /* async link */ + r = uv_fs_link(loop, &req, "test_file", "test_file_link2", link_cb); + ASSERT(r == 0); + uv_run(loop); + ASSERT(link_cb_count == 1); + + r = uv_fs_open(loop, &req, "test_file_link2", O_RDWR, 0, NULL); + ASSERT(r != -1); + ASSERT(req.result != -1); + link = req.result; + uv_fs_req_cleanup(&req); + + memset(buf, 0, sizeof(buf)); + r = uv_fs_read(loop, &req, link, buf, sizeof(buf), 0, NULL); + ASSERT(r != -1); + ASSERT(req.result != -1); + ASSERT(strcmp(buf, test_buf) == 0); + + close(link); + + /* + * Run the loop just to check we don't have make any extraneous uv_ref() + * calls. This should drop out immediately. + */ + uv_run(loop); + + /* Cleanup. */ + unlink("test_file"); + unlink("test_file_link"); + unlink("test_file_link2"); + + return 0; +} + + +TEST_IMPL(fs_symlink) { + int r; + uv_fs_t req; + uv_file file; + uv_file link; + + /* Setup. */ + unlink("test_file"); + unlink("test_file_symlink"); + unlink("test_file_symlink2"); + unlink("test_file_symlink_symlink"); + unlink("test_file_symlink2_symlink"); + + loop = uv_default_loop(); + + r = uv_fs_open(loop, &req, "test_file", O_RDWR | O_CREAT, + S_IWRITE | S_IREAD, NULL); + ASSERT(r != -1); + ASSERT(req.result != -1); + file = req.result; + uv_fs_req_cleanup(&req); + + r = uv_fs_write(loop, &req, file, test_buf, sizeof(test_buf), -1, NULL); + ASSERT(r == sizeof(test_buf)); + ASSERT(req.result == sizeof(test_buf)); + uv_fs_req_cleanup(&req); + + close(file); + + /* sync symlink */ + r = uv_fs_symlink(loop, &req, "test_file", "test_file_symlink", 0, NULL); +#ifdef _WIN32 + if (r == -1) { + if (uv_last_error(loop).code == UV_ENOTSUP) { + /* + * Windows doesn't support symlinks on older versions. + * We just pass the test and bail out early if we get ENOTSUP. + */ + return 0; + } else if (uv_last_error(loop).code == UV_EPERM) { + /* + * Creating a symlink is only allowed when running elevated. + * We pass the test and bail out early if we get UV_EPERM. + */ + return 0; + } + } +#endif + ASSERT(r == 0); + ASSERT(req.result == 0); + uv_fs_req_cleanup(&req); + + r = uv_fs_open(loop, &req, "test_file_symlink", O_RDWR, 0, NULL); + ASSERT(r != -1); + ASSERT(req.result != -1); + link = req.result; + uv_fs_req_cleanup(&req); + + memset(buf, 0, sizeof(buf)); + r = uv_fs_read(loop, &req, link, buf, sizeof(buf), 0, NULL); + ASSERT(r != -1); + ASSERT(req.result != -1); + ASSERT(strcmp(buf, test_buf) == 0); + + close(link); + + r = uv_fs_symlink(loop, &req, "test_file_symlink", "test_file_symlink_symlink", 0, NULL); + ASSERT(r != -1); + r = uv_fs_readlink(loop, &req, "test_file_symlink_symlink", NULL); + ASSERT(r != -1); + ASSERT(strcmp(req.ptr, "test_file_symlink") == 0); + uv_fs_req_cleanup(&req); + + /* async link */ + r = uv_fs_symlink(loop, &req, "test_file", "test_file_symlink2", 0, symlink_cb); + ASSERT(r == 0); + uv_run(loop); + ASSERT(symlink_cb_count == 1); + + r = uv_fs_open(loop, &req, "test_file_symlink2", O_RDWR, 0, NULL); + ASSERT(r != -1); + ASSERT(req.result != -1); + link = req.result; + uv_fs_req_cleanup(&req); + + memset(buf, 0, sizeof(buf)); + r = uv_fs_read(loop, &req, link, buf, sizeof(buf), 0, NULL); + ASSERT(r != -1); + ASSERT(req.result != -1); + ASSERT(strcmp(buf, test_buf) == 0); + + close(link); + + r = uv_fs_symlink(loop, &req, "test_file_symlink2", "test_file_symlink2_symlink", 0, NULL); + ASSERT(r != -1); + r = uv_fs_readlink(loop, &req, "test_file_symlink2_symlink", readlink_cb); + ASSERT(r != -1); + uv_run(loop); + ASSERT(readlink_cb_count == 1); + + /* + * Run the loop just to check we don't have make any extraneous uv_ref() + * calls. This should drop out immediately. + */ + uv_run(loop); + + /* Cleanup. */ + unlink("test_file"); + unlink("test_file_symlink"); + unlink("test_file_symlink_symlink"); + unlink("test_file_symlink2"); + unlink("test_file_symlink2_symlink"); + + return 0; +} + + +TEST_IMPL(fs_symlink_dir) { + uv_fs_t req; + int r; + char* test_dir; + + /* set-up */ + unlink("test_dir/file1"); + unlink("test_dir/file2"); + rmdir("test_dir"); + rmdir("test_dir_symlink"); + + loop = uv_default_loop(); + + uv_fs_mkdir(loop, &req, "test_dir", 0777, NULL); + uv_fs_req_cleanup(&req); + +#ifdef _WIN32 + { + static char src_path_buf[PATHMAX]; + strcpy(src_path_buf, "\\\\?\\"); + uv_cwd(src_path_buf + 4, sizeof(src_path_buf)); + strcat(src_path_buf, "\\test_dir\\"); + test_dir = src_path_buf; + } +#else + test_dir = "test_dir"; +#endif + + r = uv_fs_symlink(loop, &req, test_dir, "test_dir_symlink", + UV_FS_SYMLINK_JUNCTION, NULL); + ASSERT(r == 0); + ASSERT(req.result == 0); + uv_fs_req_cleanup(&req); + + r = uv_fs_stat(loop, &req, "test_dir_symlink", NULL); + ASSERT(r == 0); + ASSERT(((struct stat*)req.ptr)->st_mode & S_IFDIR); + uv_fs_req_cleanup(&req); + + r = uv_fs_lstat(loop, &req, "test_dir_symlink", NULL); + ASSERT(r == 0); + ASSERT(((struct stat*)req.ptr)->st_mode & S_IFLNK); +#ifdef _WIN32 + ASSERT(((struct stat*)req.ptr)->st_size == strlen(test_dir + 4)); +#else + ASSERT(((struct stat*)req.ptr)->st_size == strlen(test_dir)); +#endif + uv_fs_req_cleanup(&req); + + r = uv_fs_readlink(loop, &req, "test_dir_symlink", NULL); + ASSERT(r == 0); +#ifdef _WIN32 + ASSERT(strcmp(req.ptr, test_dir + 4) == 0); +#else + ASSERT(strcmp(req.ptr, test_dir) == 0); +#endif + uv_fs_req_cleanup(&req); + + r = uv_fs_open(loop, &open_req1, "test_dir/file1", O_WRONLY | O_CREAT, + S_IWRITE | S_IREAD, NULL); + ASSERT(r != -1); + uv_fs_req_cleanup(&open_req1); + r = uv_fs_close(loop, &close_req, open_req1.result, NULL); + ASSERT(r == 0); + uv_fs_req_cleanup(&close_req); + + r = uv_fs_open(loop, &open_req1, "test_dir/file2", O_WRONLY | O_CREAT, + S_IWRITE | S_IREAD, NULL); + ASSERT(r != -1); + uv_fs_req_cleanup(&open_req1); + r = uv_fs_close(loop, &close_req, open_req1.result, NULL); + ASSERT(r == 0); + uv_fs_req_cleanup(&close_req); + + r = uv_fs_readdir(loop, &readdir_req, "test_dir_symlink", 0, NULL); + ASSERT(r == 2); + ASSERT(readdir_req.result == 2); + ASSERT(readdir_req.ptr); + ASSERT(memcmp(readdir_req.ptr, "file1\0file2\0", 12) == 0 + || memcmp(readdir_req.ptr, "file2\0file1\0", 12) == 0); + uv_fs_req_cleanup(&readdir_req); + ASSERT(!readdir_req.ptr); + + /* unlink will remove the directory symlink */ + r = uv_fs_unlink(loop, &req, "test_dir_symlink", NULL); + ASSERT(r == 0); + uv_fs_req_cleanup(&req); + + r = uv_fs_readdir(loop, &readdir_req, "test_dir_symlink", 0, NULL); + ASSERT(r == -1); + uv_fs_req_cleanup(&readdir_req); + + r = uv_fs_readdir(loop, &readdir_req, "test_dir", 0, NULL); + ASSERT(r == 2); + ASSERT(readdir_req.result == 2); + ASSERT(readdir_req.ptr); + ASSERT(memcmp(readdir_req.ptr, "file1\0file2\0", 12) == 0 + || memcmp(readdir_req.ptr, "file2\0file1\0", 12) == 0); + uv_fs_req_cleanup(&readdir_req); + ASSERT(!readdir_req.ptr); + + /* clean-up */ + unlink("test_dir/file1"); + unlink("test_dir/file2"); + rmdir("test_dir"); + rmdir("test_dir_symlink"); + + return 0; +} + + +TEST_IMPL(fs_utime) { + utime_check_t checkme; + const char* path = "test_file"; + double atime; + double mtime; + uv_fs_t req; + int r; + + /* Setup. */ + loop = uv_default_loop(); + unlink(path); + r = uv_fs_open(loop, &req, path, O_RDWR | O_CREAT, + S_IWRITE | S_IREAD, NULL); + ASSERT(r != -1); + ASSERT(req.result != -1); + uv_fs_req_cleanup(&req); + close(r); + + atime = mtime = 400497753; /* 1982-09-10 11:22:33 */ + + r = uv_fs_utime(loop, &req, path, atime, mtime, NULL); + ASSERT(r == 0); + ASSERT(req.result == 0); + uv_fs_req_cleanup(&req); + + r = uv_fs_stat(loop, &req, path, NULL); + ASSERT(r == 0); + ASSERT(req.result == 0); + check_utime(path, atime, mtime); + uv_fs_req_cleanup(&req); + + atime = mtime = 1291404900; /* 2010-12-03 20:35:00 - mees <3 */ + checkme.path = path; + checkme.atime = atime; + checkme.mtime = mtime; + + /* async utime */ + utime_req.data = &checkme; + r = uv_fs_utime(loop, &utime_req, path, atime, mtime, utime_cb); + ASSERT(r == 0); + uv_run(loop); + ASSERT(utime_cb_count == 1); + + /* Cleanup. */ + unlink(path); + + return 0; +} + + +#ifdef _WIN32 +TEST_IMPL(fs_stat_root) { + int r; + uv_loop_t* loop = uv_default_loop(); + + r = uv_fs_stat(loop, &stat_req, "\\", NULL); + ASSERT(r == 0); + + r = uv_fs_stat(loop, &stat_req, "..\\..\\..\\..\\..\\..\\..", NULL); + ASSERT(r == 0); + + r = uv_fs_stat(loop, &stat_req, "..", NULL); + ASSERT(r == 0); + + r = uv_fs_stat(loop, &stat_req, "..\\", NULL); + ASSERT(r == 0); + + /* stats the current directory on c: */ + r = uv_fs_stat(loop, &stat_req, "c:", NULL); + ASSERT(r == 0); + + r = uv_fs_stat(loop, &stat_req, "c:\\", NULL); + ASSERT(r == 0); + + r = uv_fs_stat(loop, &stat_req, "\\\\?\\C:\\", NULL); + ASSERT(r == 0); + + return 0; +} +#endif + + +TEST_IMPL(fs_futime) { + utime_check_t checkme; + const char* path = "test_file"; + double atime; + double mtime; + uv_file file; + uv_fs_t req; + int r; + + /* Setup. */ + loop = uv_default_loop(); + unlink(path); + r = uv_fs_open(loop, &req, path, O_RDWR | O_CREAT, + S_IWRITE | S_IREAD, NULL); + ASSERT(r != -1); + ASSERT(req.result != -1); + uv_fs_req_cleanup(&req); + close(r); + + atime = mtime = 400497753; /* 1982-09-10 11:22:33 */ + + r = uv_fs_open(loop, &req, path, O_RDWR, 0, NULL); + ASSERT(r != -1); + ASSERT(req.result != -1); + file = req.result; /* FIXME probably not how it's supposed to be used */ + uv_fs_req_cleanup(&req); + + r = uv_fs_futime(loop, &req, file, atime, mtime, NULL); + ASSERT(r == 0); + ASSERT(req.result == 0); + uv_fs_req_cleanup(&req); + + r = uv_fs_stat(loop, &req, path, NULL); + ASSERT(r == 0); + ASSERT(req.result == 0); + check_utime(path, atime, mtime); + uv_fs_req_cleanup(&req); + + atime = mtime = 1291404900; /* 2010-12-03 20:35:00 - mees <3 */ + + checkme.atime = atime; + checkme.mtime = mtime; + checkme.path = path; + + /* async futime */ + futime_req.data = &checkme; + r = uv_fs_futime(loop, &futime_req, file, atime, mtime, futime_cb); + ASSERT(r == 0); + uv_run(loop); + ASSERT(futime_cb_count == 1); + + /* Cleanup. */ + unlink(path); + + return 0; +} + + +TEST_IMPL(fs_stat_missing_path) { + uv_fs_t req; + int r; + + loop = uv_default_loop(); + + r = uv_fs_stat(loop, &req, "non_existent_file", NULL); + ASSERT(r == -1); + ASSERT(req.result == -1); + ASSERT(uv_last_error(loop).code == UV_ENOENT); + uv_fs_req_cleanup(&req); + + return 0; +} + + +TEST_IMPL(fs_readdir_empty_dir) { + const char* path; + uv_fs_t req; + int r; + + path = "./empty_dir/"; + loop = uv_default_loop(); + + uv_fs_mkdir(loop, &req, path, 0777, NULL); + uv_fs_req_cleanup(&req); + + r = uv_fs_readdir(loop, &req, path, 0, NULL); + ASSERT(r == 0); + ASSERT(req.result == 0); + ASSERT(req.ptr == NULL); + uv_fs_req_cleanup(&req); + + r = uv_fs_readdir(loop, &readdir_req, path, 0, empty_readdir_cb); + ASSERT(r == 0); + + ASSERT(readdir_cb_count == 0); + uv_run(loop); + ASSERT(readdir_cb_count == 1); + + uv_fs_rmdir(loop, &req, path, NULL); + uv_fs_req_cleanup(&req); + + return 0; +} + + +TEST_IMPL(fs_readdir_file) { + const char* path; + int r; + + path = "test/fixtures/empty_file"; + loop = uv_default_loop(); + + r = uv_fs_readdir(loop, &readdir_req, path, 0, NULL); + ASSERT(r == -1); + ASSERT(uv_last_error(loop).code == UV_ENOTDIR); + + r = uv_fs_readdir(loop, &readdir_req, path, 0, file_readdir_cb); + ASSERT(r == 0); + + ASSERT(readdir_cb_count == 0); + uv_run(loop); + ASSERT(readdir_cb_count == 1); + + return 0; +} + + +TEST_IMPL(fs_open_dir) { + const char* path; + uv_fs_t req; + int r, file; + + path = "."; + loop = uv_default_loop(); + + r = uv_fs_open(loop, &req, path, O_RDONLY, 0, NULL); + ASSERT(r != -1); + ASSERT(req.result != -1); + ASSERT(req.ptr == NULL); + file = r; + uv_fs_req_cleanup(&req); + + r = uv_fs_close(loop, &req, file, NULL); + ASSERT(r == 0); + + r = uv_fs_open(loop, &req, path, O_RDONLY, 0, open_cb_simple); + ASSERT(r == 0); + + ASSERT(open_cb_count == 0); + uv_run(loop); + ASSERT(open_cb_count == 1); + + return 0; +} + + +TEST_IMPL(fs_file_open_append) { + int r; + + /* Setup. */ + unlink("test_file"); + + loop = uv_default_loop(); + + r = uv_fs_open(loop, &open_req1, "test_file", O_WRONLY | O_CREAT, + S_IWRITE | S_IREAD, NULL); + ASSERT(r != -1); + ASSERT(open_req1.result != -1); + uv_fs_req_cleanup(&open_req1); + + r = uv_fs_write(loop, &write_req, open_req1.result, test_buf, + sizeof(test_buf), -1, NULL); + ASSERT(r != -1); + ASSERT(write_req.result != -1); + uv_fs_req_cleanup(&write_req); + + r = uv_fs_close(loop, &close_req, open_req1.result, NULL); + ASSERT(r != -1); + ASSERT(close_req.result != -1); + uv_fs_req_cleanup(&close_req); + + r = uv_fs_open(loop, &open_req1, "test_file", O_RDWR | O_APPEND, 0, NULL); + ASSERT(r != -1); + ASSERT(open_req1.result != -1); + uv_fs_req_cleanup(&open_req1); + + r = uv_fs_write(loop, &write_req, open_req1.result, test_buf, + sizeof(test_buf), -1, NULL); + ASSERT(r != -1); + ASSERT(write_req.result != -1); + uv_fs_req_cleanup(&write_req); + + r = uv_fs_close(loop, &close_req, open_req1.result, NULL); + ASSERT(r != -1); + ASSERT(close_req.result != -1); + uv_fs_req_cleanup(&close_req); + + r = uv_fs_open(loop, &open_req1, "test_file", O_RDONLY, S_IREAD, NULL); + ASSERT(r != -1); + ASSERT(open_req1.result != -1); + uv_fs_req_cleanup(&open_req1); + + r = uv_fs_read(loop, &read_req, open_req1.result, buf, sizeof(buf), -1, + NULL); + printf("read = %d\n", r); + ASSERT(r == 26); + ASSERT(read_req.result == 26); + ASSERT(memcmp(buf, + "test-buffer\n\0test-buffer\n\0", + sizeof("test-buffer\n\0test-buffer\n\0") - 1) == 0); + uv_fs_req_cleanup(&read_req); + + r = uv_fs_close(loop, &close_req, open_req1.result, NULL); + ASSERT(r != -1); + ASSERT(close_req.result != -1); + uv_fs_req_cleanup(&close_req); + + /* Cleanup */ + unlink("test_file"); + + return 0; +} + + +TEST_IMPL(fs_rename_to_existing_file) { + int r; + + /* Setup. */ + unlink("test_file"); + unlink("test_file2"); + + loop = uv_default_loop(); + + r = uv_fs_open(loop, &open_req1, "test_file", O_WRONLY | O_CREAT, + S_IWRITE | S_IREAD, NULL); + ASSERT(r != -1); + ASSERT(open_req1.result != -1); + uv_fs_req_cleanup(&open_req1); + + r = uv_fs_write(loop, &write_req, open_req1.result, test_buf, + sizeof(test_buf), -1, NULL); + ASSERT(r != -1); + ASSERT(write_req.result != -1); + uv_fs_req_cleanup(&write_req); + + r = uv_fs_close(loop, &close_req, open_req1.result, NULL); + ASSERT(r != -1); + ASSERT(close_req.result != -1); + uv_fs_req_cleanup(&close_req); + + r = uv_fs_open(loop, &open_req1, "test_file2", O_WRONLY | O_CREAT, + S_IWRITE | S_IREAD, NULL); + ASSERT(r != -1); + ASSERT(open_req1.result != -1); + uv_fs_req_cleanup(&open_req1); + + r = uv_fs_close(loop, &close_req, open_req1.result, NULL); + ASSERT(r != -1); + ASSERT(close_req.result != -1); + uv_fs_req_cleanup(&close_req); + + r = uv_fs_rename(loop, &rename_req, "test_file", "test_file2", NULL); + ASSERT(r != -1); + ASSERT(rename_req.result != -1); + uv_fs_req_cleanup(&rename_req); + + r = uv_fs_open(loop, &open_req1, "test_file2", O_RDONLY, 0, NULL); + ASSERT(r != -1); + ASSERT(open_req1.result != -1); + uv_fs_req_cleanup(&open_req1); + + memset(buf, 0, sizeof(buf)); + r = uv_fs_read(loop, &read_req, open_req1.result, buf, sizeof(buf), -1, + NULL); + ASSERT(r != -1); + ASSERT(read_req.result != -1); + ASSERT(strcmp(buf, test_buf) == 0); + uv_fs_req_cleanup(&read_req); + + r = uv_fs_close(loop, &close_req, open_req1.result, NULL); + ASSERT(r != -1); + ASSERT(close_req.result != -1); + uv_fs_req_cleanup(&close_req); + + /* Cleanup */ + unlink("test_file"); + unlink("test_file2"); + + return 0; +} + + +TEST_IMPL(fs_read_file_eof) { + int r; + + /* Setup. */ + unlink("test_file"); + + loop = uv_default_loop(); + + r = uv_fs_open(loop, &open_req1, "test_file", O_WRONLY | O_CREAT, + S_IWRITE | S_IREAD, NULL); + ASSERT(r != -1); + ASSERT(open_req1.result != -1); + uv_fs_req_cleanup(&open_req1); + + r = uv_fs_write(loop, &write_req, open_req1.result, test_buf, + sizeof(test_buf), -1, NULL); + ASSERT(r != -1); + ASSERT(write_req.result != -1); + uv_fs_req_cleanup(&write_req); + + r = uv_fs_close(loop, &close_req, open_req1.result, NULL); + ASSERT(r != -1); + ASSERT(close_req.result != -1); + uv_fs_req_cleanup(&close_req); + + r = uv_fs_open(loop, &open_req1, "test_file", O_RDONLY, 0, NULL); + ASSERT(r != -1); + ASSERT(open_req1.result != -1); + uv_fs_req_cleanup(&open_req1); + + memset(buf, 0, sizeof(buf)); + r = uv_fs_read(loop, &read_req, open_req1.result, buf, sizeof(buf), -1, + NULL); + ASSERT(r != -1); + ASSERT(read_req.result != -1); + ASSERT(strcmp(buf, test_buf) == 0); + uv_fs_req_cleanup(&read_req); + + r = uv_fs_read(loop, &read_req, open_req1.result, buf, sizeof(buf), + read_req.result, NULL); + ASSERT(r == 0); + ASSERT(read_req.result == 0); + uv_fs_req_cleanup(&read_req); + + r = uv_fs_close(loop, &close_req, open_req1.result, NULL); + ASSERT(r != -1); + ASSERT(close_req.result != -1); + uv_fs_req_cleanup(&close_req); + + /* Cleanup */ + unlink("test_file"); + + return 0; +} diff --git a/node-v0.8.14/deps/uv/test/test-get-currentexe.c b/node-v0.8.14/deps/uv/test/test-get-currentexe.c new file mode 100644 index 0000000..9dd2676 --- /dev/null +++ b/node-v0.8.14/deps/uv/test/test-get-currentexe.c @@ -0,0 +1,63 @@ +/* Copyright Joyent, Inc. and other Node contributors. All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ + +#include "uv.h" +#include "task.h" +#include + +#define PATHMAX 1024 +extern char executable_path[]; + +TEST_IMPL(get_currentexe) { + char buffer[PATHMAX]; + size_t size; + char* match; + char* path; + int r; + + size = sizeof(buffer) / sizeof(buffer[0]); + r = uv_exepath(buffer, &size); + ASSERT(!r); + + /* uv_exepath can return an absolute path on darwin, so if the test runner + * was run with a relative prefix of "./", we need to strip that prefix off + * executable_path or we'll fail. */ + if (executable_path[0] == '.' && executable_path[1] == '/') { + path = executable_path + 2; + } else { + path = executable_path; + } + + match = strstr(buffer, path); + /* Verify that the path returned from uv_exepath is a subdirectory of executable_path */ + ASSERT(match && !strcmp(match, path)); + ASSERT(size == strlen(buffer)); + + /* Negative tests */ + size = sizeof(buffer) / sizeof(buffer[0]); + r = uv_exepath(NULL, &size); + ASSERT(r == -1); + + r = uv_exepath(buffer, NULL); + ASSERT(r == -1); + + return 0; +} diff --git a/node-v0.8.14/deps/uv/test/test-get-loadavg.c b/node-v0.8.14/deps/uv/test/test-get-loadavg.c new file mode 100644 index 0000000..7465e18 --- /dev/null +++ b/node-v0.8.14/deps/uv/test/test-get-loadavg.c @@ -0,0 +1,36 @@ +/* Copyright Joyent, Inc. and other Node contributors. All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ + +#include "uv.h" +#include "task.h" + +TEST_IMPL(get_loadavg) { + + double avg[3]; + uv_loadavg(avg); + + ASSERT(avg != NULL); + ASSERT(avg[0] >= 0); + ASSERT(avg[1] >= 0); + ASSERT(avg[2] >= 0); + + return 0; +} diff --git a/node-v0.8.14/deps/uv/test/test-get-memory.c b/node-v0.8.14/deps/uv/test/test-get-memory.c new file mode 100644 index 0000000..2396939 --- /dev/null +++ b/node-v0.8.14/deps/uv/test/test-get-memory.c @@ -0,0 +1,38 @@ +/* Copyright Joyent, Inc. and other Node contributors. All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ + +#include "uv.h" +#include "task.h" + +TEST_IMPL(get_memory) { + uint64_t free_mem = uv_get_free_memory(); + uint64_t total_mem = uv_get_total_memory(); + + printf("free_mem=%llu, total_mem=%llu\n", + (unsigned long long) free_mem, + (unsigned long long) total_mem); + + ASSERT(free_mem > 0); + ASSERT(total_mem > 0); + ASSERT(total_mem > free_mem); + + return 0; +} diff --git a/node-v0.8.14/deps/uv/test/test-getaddrinfo.c b/node-v0.8.14/deps/uv/test/test-getaddrinfo.c new file mode 100644 index 0000000..2a8c94e --- /dev/null +++ b/node-v0.8.14/deps/uv/test/test-getaddrinfo.c @@ -0,0 +1,122 @@ +/* Copyright Joyent, Inc. and other Node contributors. All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ + +#include "uv.h" +#include "task.h" + +#include +#include +#include /* strlen */ + + +#define CONCURRENT_COUNT 10 + +static const char* name = "localhost"; + +static int getaddrinfo_cbs = 0; + +/* data used for running multiple calls concurrently */ +static uv_getaddrinfo_t* getaddrinfo_handle; +static uv_getaddrinfo_t getaddrinfo_handles[CONCURRENT_COUNT]; +static int callback_counts[CONCURRENT_COUNT]; + + +static void getaddrinfo_basic_cb(uv_getaddrinfo_t* handle, + int status, + struct addrinfo* res) { + ASSERT(handle == getaddrinfo_handle); + getaddrinfo_cbs++; + free(handle); + uv_freeaddrinfo(res); +} + + +static void getaddrinfo_cuncurrent_cb(uv_getaddrinfo_t* handle, + int status, + struct addrinfo* res) { + int i; + int* data = (int*)handle->data; + + for (i = 0; i < CONCURRENT_COUNT; i++) { + if (&getaddrinfo_handles[i] == handle) { + ASSERT(i == *data); + + callback_counts[i]++; + break; + } + } + ASSERT (i < CONCURRENT_COUNT); + + free(data); + uv_freeaddrinfo(res); + + getaddrinfo_cbs++; +} + + +TEST_IMPL(getaddrinfo_basic) { + int r; + getaddrinfo_handle = (uv_getaddrinfo_t*)malloc(sizeof(uv_getaddrinfo_t)); + + r = uv_getaddrinfo(uv_default_loop(), + getaddrinfo_handle, + &getaddrinfo_basic_cb, + name, + NULL, + NULL); + ASSERT(r == 0); + + uv_run(uv_default_loop()); + + ASSERT(getaddrinfo_cbs == 1); + + return 0; +} + + +TEST_IMPL(getaddrinfo_concurrent) { + int i, r; + int* data; + + for (i = 0; i < CONCURRENT_COUNT; i++) { + callback_counts[i] = 0; + + data = (int*)malloc(sizeof(int)); + *data = i; + getaddrinfo_handles[i].data = data; + + r = uv_getaddrinfo(uv_default_loop(), + &getaddrinfo_handles[i], + &getaddrinfo_cuncurrent_cb, + name, + NULL, + NULL); + ASSERT(r == 0); + } + + uv_run(uv_default_loop()); + + for (i = 0; i < CONCURRENT_COUNT; i++) { + ASSERT(callback_counts[i] == 1); + } + + return 0; +} diff --git a/node-v0.8.14/deps/uv/test/test-gethostbyname.c b/node-v0.8.14/deps/uv/test/test-gethostbyname.c new file mode 100644 index 0000000..1df2aaa --- /dev/null +++ b/node-v0.8.14/deps/uv/test/test-gethostbyname.c @@ -0,0 +1,180 @@ +/* Copyright Joyent, Inc. and other Node contributors. All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ + +#include "uv.h" +#include "task.h" + +#include +#include +#include /* strlen */ + +static ares_channel channel; + +static int ares_bynamecallbacks; +static int bynamecallbacksig; +static int ares_byaddrcallbacks; +static int byaddrcallbacksig; + +static void aresbynamecallback( void *arg, + int status, + int timeouts, + struct hostent *hostent) { + int * iargs; + ASSERT(arg != NULL); + iargs = (int*)arg; + ASSERT(*iargs == bynamecallbacksig); + ASSERT(timeouts == 0); + + printf("aresbynamecallback %d\n", ares_bynamecallbacks++); +} + + +static void aresbyaddrcallback( void *arg, + int status, + int timeouts, + struct hostent *hostent) { + int * iargs; + ASSERT(arg != NULL); + iargs = (int*)arg; + ASSERT(*iargs == byaddrcallbacksig); + ASSERT(timeouts == 0); + + printf("aresbyaddrcallback %d\n", ares_byaddrcallbacks++); +} + + +static void setup_cares() { + int r; + struct ares_options options; + memset(&options, 0, sizeof options); + r = uv_ares_init_options(uv_default_loop(), &channel, &options, 0); + ASSERT(r == ARES_SUCCESS); +} + + +TEST_IMPL(gethostbyname) { + + int rc = 0; + char addr[4]; + + rc = ares_library_init(ARES_LIB_INIT_ALL); + if (rc != 0) { + printf("ares library init fails %d\n", rc); + return 1; + } + + printf("Start basic gethostbyname test\n"); + setup_cares(); + + ares_bynamecallbacks = 0; + bynamecallbacksig = 7; + + ares_gethostbyname(channel, + "microsoft.com", + AF_INET, + &aresbynamecallback, + &bynamecallbacksig); + uv_run(uv_default_loop()); + + ASSERT(ares_bynamecallbacks == 1); + + uv_ares_destroy(uv_default_loop(), channel); + printf("Done basic gethostbyname test\n"); + + + /* two sequential call on new channel */ + + printf("Start gethostbyname and gethostbyaddr sequential test\n"); + setup_cares(); + + ares_bynamecallbacks = 0; + bynamecallbacksig = 7; + + ares_gethostbyname(channel, + "microsoft.com", + AF_INET, + &aresbynamecallback, + &bynamecallbacksig); + uv_run(uv_default_loop()); + + ASSERT(ares_bynamecallbacks == 1); + + ares_byaddrcallbacks = 0; + byaddrcallbacksig = 8; + addr[0] = 10; + addr[1] = 0; + addr[2] = 1; + addr[3] = 99; + + ares_gethostbyaddr(channel, + addr, + 4, + AF_INET, + &aresbyaddrcallback, + &byaddrcallbacksig); + + uv_run(uv_default_loop()); + + ASSERT(ares_byaddrcallbacks == 1); + + uv_ares_destroy(uv_default_loop(), channel); + printf("Done gethostbyname and gethostbyaddr sequential test\n"); + + + /* two simultaneous calls on new channel */ + + printf("Start gethostbyname and gethostbyaddr concurrent test\n"); + setup_cares(); + + ares_bynamecallbacks = 0; + bynamecallbacksig = 7; + + ares_gethostbyname(channel, + "microsoft.com", + AF_INET, + &aresbynamecallback, + &bynamecallbacksig); + + ares_byaddrcallbacks = 0; + byaddrcallbacksig = 8; + addr[0] = 10; + addr[1] = 0; + addr[2] = 1; + addr[3] = 99; + + ares_gethostbyaddr(channel, + addr, + 4, + AF_INET, + &aresbyaddrcallback, + &byaddrcallbacksig); + + uv_run(uv_default_loop()); + + ASSERT(ares_bynamecallbacks == 1); + ASSERT(ares_byaddrcallbacks == 1); + + + uv_ares_destroy(uv_default_loop(), channel); + printf("Done gethostbyname and gethostbyaddr concurrent test\n"); + + return 0; +} diff --git a/node-v0.8.14/deps/uv/test/test-getsockname.c b/node-v0.8.14/deps/uv/test/test-getsockname.c new file mode 100644 index 0000000..ff28beb --- /dev/null +++ b/node-v0.8.14/deps/uv/test/test-getsockname.c @@ -0,0 +1,342 @@ +/* Copyright Joyent, Inc. and other Node contributors. All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ + +#include "uv.h" +#include "task.h" + +#include +#include +#include + +static const int server_port = TEST_PORT; +/* Will be updated right after making the uv_connect_call */ +static int connect_port = -1; + +static int getsocknamecount = 0; +static int getpeernamecount = 0; + +static uv_loop_t* loop; +static uv_tcp_t tcp; +static uv_udp_t udp; +static uv_connect_t connect_req; +static uv_tcp_t tcpServer; +static uv_udp_t udpServer; +static uv_udp_send_t send_req; + + +static uv_buf_t alloc(uv_handle_t* handle, size_t suggested_size) { + uv_buf_t buf; + buf.base = (char*) malloc(suggested_size); + buf.len = suggested_size; + return buf; +} + + +static void on_close(uv_handle_t* peer) { + free(peer); + uv_close((uv_handle_t*)&tcpServer, NULL); +} + + +static void after_shutdown(uv_shutdown_t* req, int status) { + uv_close((uv_handle_t*) req->handle, on_close); + free(req); +} + + +static void after_read(uv_stream_t* handle, ssize_t nread, uv_buf_t buf) { + uv_shutdown_t* req; + int r; + + if (buf.base) { + free(buf.base); + } + + req = (uv_shutdown_t*) malloc(sizeof *req); + r = uv_shutdown(req, handle, after_shutdown); + ASSERT(r == 0); +} + + +static void check_sockname(struct sockaddr* addr, const char* compare_ip, + int compare_port, const char* context) { + struct sockaddr_in check_addr = *(struct sockaddr_in*) addr; + struct sockaddr_in compare_addr = uv_ip4_addr(compare_ip, compare_port); + char check_ip[17]; + int r; + + /* Both addresses should be ipv4 */ + ASSERT(check_addr.sin_family == AF_INET); + ASSERT(compare_addr.sin_family == AF_INET); + + /* Check if the ip matches */ + ASSERT(memcmp(&check_addr.sin_addr, + &compare_addr.sin_addr, + sizeof compare_addr.sin_addr) == 0); + + /* Check if the port matches. If port == 0 anything goes. */ + ASSERT(compare_port == 0 || check_addr.sin_port == compare_addr.sin_port); + + r = uv_ip4_name(&check_addr, (char*) check_ip, sizeof check_ip); + ASSERT(r == 0); + + printf("%s: %s:%d\n", context, check_ip, ntohs(check_addr.sin_port)); +} + + +static void on_connection(uv_stream_t* server, int status) { + struct sockaddr sockname, peername; + int namelen; + uv_handle_t* handle; + int r; + + if (status != 0) { + fprintf(stderr, "Connect error %d\n", + uv_last_error(loop).code); + } + ASSERT(status == 0); + + handle = (uv_handle_t*) malloc(sizeof(uv_tcp_t)); + ASSERT(handle != NULL); + + r = uv_tcp_init(loop, (uv_tcp_t*)handle); + ASSERT(r == 0); + + /* associate server with stream */ + handle->data = server; + + r = uv_accept(server, (uv_stream_t*)handle); + ASSERT(r == 0); + + namelen = sizeof sockname; + r = uv_tcp_getsockname((uv_tcp_t*) handle, &sockname, &namelen); + ASSERT(r == 0); + check_sockname(&sockname, "127.0.0.1", server_port, "accepted socket"); + getsocknamecount++; + + namelen = sizeof peername; + r = uv_tcp_getpeername((uv_tcp_t*) handle, &peername, &namelen); + ASSERT(r == 0); + check_sockname(&peername, "127.0.0.1", connect_port, "accepted socket peer"); + getpeernamecount++; + + r = uv_read_start((uv_stream_t*)handle, alloc, after_read); + ASSERT(r == 0); +} + + +static void on_connect(uv_connect_t* req, int status) { + struct sockaddr sockname, peername; + int r, namelen; + + ASSERT(status == 0); + + namelen = sizeof sockname; + r = uv_tcp_getsockname((uv_tcp_t*) req->handle, &sockname, &namelen); + ASSERT(r == 0); + check_sockname(&sockname, "127.0.0.1", 0, "connected socket"); + getsocknamecount++; + + namelen = sizeof peername; + r = uv_tcp_getpeername((uv_tcp_t*) req->handle, &peername, &namelen); + ASSERT(r == 0); + check_sockname(&peername, "127.0.0.1", server_port, "connected socket peer"); + getpeernamecount++; + + uv_close((uv_handle_t*)&tcp, NULL); +} + + +static int tcp_listener() { + struct sockaddr_in addr = uv_ip4_addr("0.0.0.0", server_port); + struct sockaddr sockname, peername; + int namelen; + int r; + + r = uv_tcp_init(loop, &tcpServer); + if (r) { + fprintf(stderr, "Socket creation error\n"); + return 1; + } + + r = uv_tcp_bind(&tcpServer, addr); + if (r) { + fprintf(stderr, "Bind error\n"); + return 1; + } + + r = uv_listen((uv_stream_t*)&tcpServer, 128, on_connection); + if (r) { + fprintf(stderr, "Listen error\n"); + return 1; + } + + memset(&sockname, -1, sizeof sockname); + namelen = sizeof sockname; + r = uv_tcp_getsockname(&tcpServer, &sockname, &namelen); + ASSERT(r == 0); + check_sockname(&sockname, "0.0.0.0", server_port, "server socket"); + getsocknamecount++; + + namelen = sizeof sockname; + r = uv_tcp_getpeername(&tcpServer, &peername, &namelen); + ASSERT(r == -1); + ASSERT(uv_last_error(loop).code == UV_ENOTCONN); + getpeernamecount++; + + return 0; +} + + +static void tcp_connector() { + struct sockaddr_in server_addr = uv_ip4_addr("127.0.0.1", server_port); + struct sockaddr sockname; + int r, namelen; + + r = uv_tcp_init(loop, &tcp); + tcp.data = &connect_req; + ASSERT(!r); + + r = uv_tcp_connect(&connect_req, &tcp, server_addr, on_connect); + ASSERT(!r); + + /* Fetch the actual port used by the connecting socket. */ + namelen = sizeof sockname; + r = uv_tcp_getsockname(&tcp, &sockname, &namelen); + ASSERT(!r); + ASSERT(sockname.sa_family == AF_INET); + connect_port = ntohs(((struct sockaddr_in*) &sockname)->sin_port); + ASSERT(connect_port > 0); +} + + +static void udp_recv(uv_udp_t* handle, + ssize_t nread, + uv_buf_t buf, + struct sockaddr* addr, + unsigned flags) { + struct sockaddr sockname; + int namelen; + int r; + + ASSERT(nread >= 0); + + if (nread == 0) { + free(buf.base); + return; + } + + memset(&sockname, -1, sizeof sockname); + namelen = sizeof(sockname); + r = uv_udp_getsockname(&udp, &sockname, &namelen); + ASSERT(r == 0); + check_sockname(&sockname, "0.0.0.0", 0, "udp receiving socket"); + getsocknamecount++; + + uv_close((uv_handle_t*) &udp, NULL); + uv_close((uv_handle_t*) handle, NULL); +} + + +static void udp_send(uv_udp_send_t* req, int status) { + +} + + +static int udp_listener() { + struct sockaddr_in addr = uv_ip4_addr("0.0.0.0", server_port); + struct sockaddr sockname; + int namelen; + int r; + + r = uv_udp_init(loop, &udpServer); + if (r) { + fprintf(stderr, "Socket creation error\n"); + return 1; + } + + r = uv_udp_bind(&udpServer, addr, 0); + if (r) { + fprintf(stderr, "Bind error\n"); + return 1; + } + + memset(&sockname, -1, sizeof sockname); + namelen = sizeof sockname; + r = uv_udp_getsockname(&udpServer, &sockname, &namelen); + ASSERT(r == 0); + check_sockname(&sockname, "0.0.0.0", server_port, "udp listener socket"); + getsocknamecount++; + + r = uv_udp_recv_start(&udpServer, alloc, udp_recv); + ASSERT(r == 0); + + return 0; +} + + +static void udp_sender(void) { + struct sockaddr_in server_addr; + uv_buf_t buf; + int r; + + r = uv_udp_init(loop, &udp); + ASSERT(!r); + + buf = uv_buf_init("PING", 4); + server_addr = uv_ip4_addr("127.0.0.1", server_port); + + r = uv_udp_send(&send_req, &udp, &buf, 1, server_addr, udp_send); + ASSERT(!r); +} + + +TEST_IMPL(getsockname_tcp) { + loop = uv_default_loop(); + + if (tcp_listener()) + return 1; + + tcp_connector(); + + uv_run(loop); + + ASSERT(getsocknamecount == 3); + ASSERT(getpeernamecount == 3); + + return 0; +} + + +TEST_IMPL(getsockname_udp) { + loop = uv_default_loop(); + + if (udp_listener()) + return 1; + + udp_sender(); + + uv_run(loop); + + ASSERT(getsocknamecount == 2); + + return 0; +} diff --git a/node-v0.8.14/deps/uv/test/test-hrtime.c b/node-v0.8.14/deps/uv/test/test-hrtime.c new file mode 100644 index 0000000..72a4d4b --- /dev/null +++ b/node-v0.8.14/deps/uv/test/test-hrtime.c @@ -0,0 +1,54 @@ +/* Copyright Joyent, Inc. and other Node contributors. All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ + +#include "uv.h" +#include "task.h" + +#ifndef MILLISEC +# define MILLISEC 1000 +#endif + +#ifndef NANOSEC +# define NANOSEC ((uint64_t) 1e9) +#endif + + +TEST_IMPL(hrtime) { + uint64_t a, b, diff; + int i = 75; + while (i > 0) { + a = uv_hrtime(); + uv_sleep(45); + b = uv_hrtime(); + + diff = b - a; + + /* printf("i= %d diff = %llu\n", i, (unsigned long long int) diff); */ + + /* The windows Sleep() function has only a resolution of 10-20 ms. */ + /* Check that the difference between the two hrtime values is somewhat in */ + /* the range we expect it to be. */ + ASSERT(diff > (uint64_t) 25 * NANOSEC / MILLISEC); + ASSERT(diff < (uint64_t) 80 * NANOSEC / MILLISEC); + --i; + } + return 0; +} diff --git a/node-v0.8.14/deps/uv/test/test-idle.c b/node-v0.8.14/deps/uv/test/test-idle.c new file mode 100644 index 0000000..95ef3a9 --- /dev/null +++ b/node-v0.8.14/deps/uv/test/test-idle.c @@ -0,0 +1,81 @@ +/* Copyright Joyent, Inc. and other Node contributors. All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ + +#include "uv.h" +#include "task.h" + + +static uv_timer_t timer_handle; +static uv_idle_t idle_handle; + +static int idle_cb_called = 0; +static int timer_cb_called = 0; +static int close_cb_called = 0; + + +static void close_cb(uv_handle_t* handle) { + close_cb_called++; +} + + +static void timer_cb(uv_timer_t* handle, int status) { + ASSERT(handle == &timer_handle); + ASSERT(status == 0); + + uv_close((uv_handle_t*) &idle_handle, close_cb); + uv_close((uv_handle_t*) &timer_handle, close_cb); + + timer_cb_called++; + LOGF("timer_cb %d\n", timer_cb_called); +} + + +static void idle_cb(uv_idle_t* handle, int status) { + ASSERT(handle == &idle_handle); + ASSERT(status == 0); + + idle_cb_called++; + LOGF("idle_cb %d\n", idle_cb_called); +} + + +TEST_IMPL(idle_starvation) { + int r; + + r = uv_idle_init(uv_default_loop(), &idle_handle); + ASSERT(r == 0); + r = uv_idle_start(&idle_handle, idle_cb); + ASSERT(r == 0); + + r = uv_timer_init(uv_default_loop(), &timer_handle); + ASSERT(r == 0); + r = uv_timer_start(&timer_handle, timer_cb, 50, 0); + ASSERT(r == 0); + + r = uv_run(uv_default_loop()); + ASSERT(r == 0); + + ASSERT(idle_cb_called > 0); + ASSERT(timer_cb_called == 1); + ASSERT(close_cb_called == 2); + + return 0; +} diff --git a/node-v0.8.14/deps/uv/test/test-ipc-send-recv.c b/node-v0.8.14/deps/uv/test/test-ipc-send-recv.c new file mode 100644 index 0000000..970bf1e --- /dev/null +++ b/node-v0.8.14/deps/uv/test/test-ipc-send-recv.c @@ -0,0 +1,209 @@ +/* Copyright Joyent, Inc. and other Node contributors. All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ + +#include "uv.h" +#include "task.h" + +#include +#include + +/* See test-ipc.ctx */ +void spawn_helper(uv_pipe_t* channel, + uv_process_t* process, + const char* helper); + +union handles { + uv_handle_t handle; + uv_stream_t stream; + uv_pipe_t pipe; + uv_tcp_t tcp; + uv_tty_t tty; +}; + +struct echo_ctx { + uv_pipe_t channel; + uv_write_t write_req; + uv_handle_type expected_type; + union handles send; + union handles recv; +}; + +static struct echo_ctx ctx; +static int num_recv_handles; + + +static uv_buf_t alloc_cb(uv_handle_t* handle, size_t suggested_size) { + /* we're not actually reading anything so a small buffer is okay */ + static char buf[8]; + return uv_buf_init(buf, sizeof(buf)); +} + + +static void recv_cb(uv_pipe_t* handle, + ssize_t nread, + uv_buf_t buf, + uv_handle_type pending) { + int r; + + ASSERT(pending == ctx.expected_type); + ASSERT(handle == &ctx.channel); + ASSERT(nread >= 0); + + if (pending == UV_NAMED_PIPE) + r = uv_pipe_init(ctx.channel.loop, &ctx.recv.pipe, 0); + else if (pending == UV_TCP) + r = uv_tcp_init(ctx.channel.loop, &ctx.recv.tcp); + else + abort(); + ASSERT(r == 0); + + r = uv_accept((uv_stream_t*)&ctx.channel, &ctx.recv.stream); + ASSERT(r == 0); + + uv_close((uv_handle_t*)&ctx.channel, NULL); + uv_close(&ctx.send.handle, NULL); + uv_close(&ctx.recv.handle, NULL); + num_recv_handles++; +} + + +static int run_test(void) { + uv_process_t process; + uv_buf_t buf; + int r; + + spawn_helper(&ctx.channel, &process, "ipc_send_recv_helper"); + + buf = uv_buf_init(".", 1); + r = uv_write2(&ctx.write_req, + (uv_stream_t*)&ctx.channel, + &buf, 1, + &ctx.send.stream, + NULL); + ASSERT(r == 0); + + r = uv_read2_start((uv_stream_t*)&ctx.channel, alloc_cb, recv_cb); + ASSERT(r == 0); + + r = uv_run(uv_default_loop()); + ASSERT(r == 0); + + ASSERT(num_recv_handles == 1); + + return 0; +} + + +TEST_IMPL(ipc_send_recv_pipe) { + int r; + + ctx.expected_type = UV_NAMED_PIPE; + + r = uv_pipe_init(uv_default_loop(), &ctx.send.pipe, 1); + ASSERT(r == 0); + + r = uv_pipe_bind(&ctx.send.pipe, TEST_PIPENAME); + ASSERT(r == 0); + + return run_test(); +} + + +TEST_IMPL(ipc_send_recv_tcp) { + int r; + + ctx.expected_type = UV_TCP; + + r = uv_tcp_init(uv_default_loop(), &ctx.send.tcp); + ASSERT(r == 0); + + r = uv_tcp_bind(&ctx.send.tcp, uv_ip4_addr("127.0.0.1", TEST_PORT)); + ASSERT(r == 0); + + return run_test(); +} + + +/* Everything here runs in a child process. */ + +static void write2_cb(uv_write_t* req, int status) { + ASSERT(status == 0); + uv_close(&ctx.recv.handle, NULL); + uv_close((uv_handle_t*)&ctx.channel, NULL); +} + + +static void read2_cb(uv_pipe_t* handle, + ssize_t nread, + uv_buf_t buf, + uv_handle_type pending) { + int r; + + ASSERT(pending == UV_NAMED_PIPE || pending == UV_TCP); + ASSERT(handle == &ctx.channel); + ASSERT(nread >= 0); + + buf = uv_buf_init(".", 1); + + if (pending == UV_NAMED_PIPE) + r = uv_pipe_init(ctx.channel.loop, &ctx.recv.pipe, 0); + else if (pending == UV_TCP) + r = uv_tcp_init(ctx.channel.loop, &ctx.recv.tcp); + else + abort(); + ASSERT(r == 0); + + r = uv_accept((uv_stream_t*)handle, &ctx.recv.stream); + ASSERT(r == 0); + + r = uv_write2(&ctx.write_req, + (uv_stream_t*)&ctx.channel, + &buf, 1, + &ctx.recv.stream, + write2_cb); + ASSERT(r == 0); +} + + +/* stdin is a duplex channel over which a handle is sent. + * We receive it and send it back where it came from. + */ +int ipc_send_recv_helper(void) { + int r; + + memset(&ctx, 0, sizeof(ctx)); + + r = uv_pipe_init(uv_default_loop(), &ctx.channel, 1); + ASSERT(r == 0); + + uv_pipe_open(&ctx.channel, 0); + ASSERT(uv_is_readable((uv_stream_t*)&ctx.channel)); + ASSERT(uv_is_writable((uv_stream_t*)&ctx.channel)); + ASSERT(!uv_is_closing((uv_handle_t*)&ctx.channel)); + + r = uv_read2_start((uv_stream_t*)&ctx.channel, alloc_cb, read2_cb); + ASSERT(r == 0); + + r = uv_run(uv_default_loop()); + ASSERT(r == 0); + + return 0; +} diff --git a/node-v0.8.14/deps/uv/test/test-ipc.c b/node-v0.8.14/deps/uv/test/test-ipc.c new file mode 100644 index 0000000..61add0b --- /dev/null +++ b/node-v0.8.14/deps/uv/test/test-ipc.c @@ -0,0 +1,620 @@ +/* Copyright Joyent, Inc. and other Node contributors. All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ + +#include "uv.h" +#include "task.h" + +#include +#include + +static uv_pipe_t channel; +static uv_tcp_t tcp_server; +static uv_tcp_t tcp_connection; + +static int exit_cb_called; +static int read2_cb_called; +static int tcp_write_cb_called; +static int tcp_read_cb_called; +static int on_pipe_read_called; +static int local_conn_accepted; +static int remote_conn_accepted; +static int tcp_server_listening; +static uv_write_t write_req; +static uv_pipe_t channel; +static uv_tcp_t tcp_server; +static uv_write_t conn_notify_req; +static int close_cb_called; +static int connection_accepted; +static int tcp_conn_read_cb_called; +static int tcp_conn_write_cb_called; + +typedef struct { + uv_connect_t conn_req; + uv_write_t tcp_write_req; + uv_tcp_t conn; +} tcp_conn; + +#define CONN_COUNT 100 + + +static void close_server_conn_cb(uv_handle_t* handle) { + free(handle); +} + + +static void on_connection(uv_stream_t* server, int status) { + uv_tcp_t* conn; + int r; + + if (!local_conn_accepted) { + /* Accept the connection and close it. Also and close the server. */ + ASSERT(status == 0); + ASSERT((uv_stream_t*)&tcp_server == server); + + conn = malloc(sizeof(*conn)); + ASSERT(conn); + r = uv_tcp_init(server->loop, conn); + ASSERT(r == 0); + + r = uv_accept(server, (uv_stream_t*)conn); + ASSERT(r == 0); + + uv_close((uv_handle_t*)conn, close_server_conn_cb); + uv_close((uv_handle_t*)server, NULL); + local_conn_accepted = 1; + } +} + + +static void exit_cb(uv_process_t* process, int exit_status, int term_signal) { + printf("exit_cb\n"); + exit_cb_called++; + ASSERT(exit_status == 0); + uv_close((uv_handle_t*)process, NULL); +} + + +static uv_buf_t on_alloc(uv_handle_t* handle, size_t suggested_size) { + return uv_buf_init(malloc(suggested_size), suggested_size); +} + + +static void close_client_conn_cb(uv_handle_t* handle) { + tcp_conn* p = (tcp_conn*)handle->data; + free(p); +} + + +static void connect_cb(uv_connect_t* req, int status) { + uv_close((uv_handle_t*)req->handle, close_client_conn_cb); +} + + +static void make_many_connections() { + tcp_conn* conn; + struct sockaddr_in addr; + int r, i; + + for (i = 0; i < CONN_COUNT; i++) { + conn = malloc(sizeof(*conn)); + ASSERT(conn); + + r = uv_tcp_init(uv_default_loop(), &conn->conn); + ASSERT(r == 0); + + addr = uv_ip4_addr("127.0.0.1", TEST_PORT); + + r = uv_tcp_connect(&conn->conn_req, (uv_tcp_t*)&conn->conn, addr, connect_cb); + ASSERT(r == 0); + + conn->conn.data = conn; + } +} + + +static void on_read(uv_pipe_t* pipe, ssize_t nread, uv_buf_t buf, + uv_handle_type pending) { + int r; + uv_buf_t outbuf; + uv_err_t err; + + if (nread == 0) { + /* Everything OK, but nothing read. */ + free(buf.base); + return; + } + + if (nread < 0) { + err = uv_last_error(pipe->loop); + if (err.code == UV_EOF) { + free(buf.base); + return; + } + + printf("error recving on channel: %s\n", uv_strerror(err)); + abort(); + } + + fprintf(stderr, "got %d bytes\n", (int)nread); + + if (!tcp_server_listening) { + ASSERT(nread > 0 && buf.base && pending != UV_UNKNOWN_HANDLE); + read2_cb_called++; + + /* Accept the pending TCP server, and start listening on it. */ + ASSERT(pending == UV_TCP); + r = uv_tcp_init(uv_default_loop(), &tcp_server); + ASSERT(r == 0); + + r = uv_accept((uv_stream_t*)pipe, (uv_stream_t*)&tcp_server); + ASSERT(r == 0); + + r = uv_listen((uv_stream_t*)&tcp_server, 12, on_connection); + ASSERT(r == 0); + + tcp_server_listening = 1; + + /* Make sure that the expected data is correctly multiplexed. */ + ASSERT(memcmp("hello\n", buf.base, nread) == 0); + + outbuf = uv_buf_init("world\n", 6); + r = uv_write(&write_req, (uv_stream_t*)pipe, &outbuf, 1, NULL); + ASSERT(r == 0); + + /* Create a bunch of connections to get both servers to accept. */ + make_many_connections(); + } else if (memcmp("accepted_connection\n", buf.base, nread) == 0) { + /* Remote server has accepted a connection. Close the channel. */ + ASSERT(pending == UV_UNKNOWN_HANDLE); + remote_conn_accepted = 1; + uv_close((uv_handle_t*)&channel, NULL); + } + + free(buf.base); +} + + +void spawn_helper(uv_pipe_t* channel, + uv_process_t* process, + const char* helper) { + uv_process_options_t options; + size_t exepath_size; + char exepath[1024]; + char* args[3]; + int r; + uv_stdio_container_t stdio[1]; + + r = uv_pipe_init(uv_default_loop(), channel, 1); + ASSERT(r == 0); + ASSERT(channel->ipc); + + exepath_size = sizeof(exepath); + r = uv_exepath(exepath, &exepath_size); + ASSERT(r == 0); + + exepath[exepath_size] = '\0'; + args[0] = exepath; + args[1] = (char*)helper; + args[2] = NULL; + + memset(&options, 0, sizeof(options)); + options.file = exepath; + options.args = args; + options.exit_cb = exit_cb; + + options.stdio = stdio; + options.stdio[0].flags = UV_CREATE_PIPE | + UV_READABLE_PIPE | UV_WRITABLE_PIPE; + options.stdio[0].data.stream = (uv_stream_t*)channel; + options.stdio_count = 1; + + r = uv_spawn(uv_default_loop(), process, options); + ASSERT(r == 0); +} + + +static void on_tcp_write(uv_write_t* req, int status) { + ASSERT(status == 0); + ASSERT(req->handle == (uv_stream_t*)&tcp_connection); + tcp_write_cb_called++; +} + + +static uv_buf_t on_read_alloc(uv_handle_t* handle, size_t suggested_size) { + uv_buf_t buf; + buf.base = (char*)malloc(suggested_size); + buf.len = suggested_size; + return buf; +} + + +static void on_tcp_read(uv_stream_t* tcp, ssize_t nread, uv_buf_t buf) { + ASSERT(nread > 0); + ASSERT(memcmp("hello again\n", buf.base, nread) == 0); + ASSERT(tcp == (uv_stream_t*)&tcp_connection); + free(buf.base); + + tcp_read_cb_called++; + + uv_close((uv_handle_t*)tcp, NULL); + uv_close((uv_handle_t*)&channel, NULL); +} + + +static void on_read_connection(uv_pipe_t* pipe, ssize_t nread, uv_buf_t buf, + uv_handle_type pending) { + int r; + uv_buf_t outbuf; + uv_err_t err; + + if (nread == 0) { + /* Everything OK, but nothing read. */ + free(buf.base); + return; + } + + if (nread < 0) { + err = uv_last_error(pipe->loop); + if (err.code == UV_EOF) { + free(buf.base); + return; + } + + printf("error recving on channel: %s\n", uv_strerror(err)); + abort(); + } + + fprintf(stderr, "got %d bytes\n", (int)nread); + + ASSERT(nread > 0 && buf.base && pending != UV_UNKNOWN_HANDLE); + read2_cb_called++; + + /* Accept the pending TCP connection */ + ASSERT(pending == UV_TCP); + r = uv_tcp_init(uv_default_loop(), &tcp_connection); + ASSERT(r == 0); + + r = uv_accept((uv_stream_t*)pipe, (uv_stream_t*)&tcp_connection); + ASSERT(r == 0); + + /* Make sure that the expected data is correctly multiplexed. */ + ASSERT(memcmp("hello\n", buf.base, nread) == 0); + + /* Write/read to/from the connection */ + outbuf = uv_buf_init("world\n", 6); + r = uv_write(&write_req, (uv_stream_t*)&tcp_connection, &outbuf, 1, + on_tcp_write); + ASSERT(r == 0); + + r = uv_read_start((uv_stream_t*)&tcp_connection, on_read_alloc, on_tcp_read); + ASSERT(r == 0); + + free(buf.base); +} + + +static int run_ipc_test(const char* helper, uv_read2_cb read_cb) { + uv_process_t process; + int r; + + spawn_helper(&channel, &process, helper); + uv_read2_start((uv_stream_t*)&channel, on_alloc, read_cb); + + r = uv_run(uv_default_loop()); + ASSERT(r == 0); + + return 0; +} + + +TEST_IMPL(ipc_listen_before_write) { + int r = run_ipc_test("ipc_helper_listen_before_write", on_read); + ASSERT(local_conn_accepted == 1); + ASSERT(remote_conn_accepted == 1); + ASSERT(read2_cb_called == 1); + ASSERT(exit_cb_called == 1); + return r; +} + + +TEST_IMPL(ipc_listen_after_write) { + int r = run_ipc_test("ipc_helper_listen_after_write", on_read); + ASSERT(local_conn_accepted == 1); + ASSERT(remote_conn_accepted == 1); + ASSERT(read2_cb_called == 1); + ASSERT(exit_cb_called == 1); + return r; +} + + +TEST_IMPL(ipc_tcp_connection) { + int r = run_ipc_test("ipc_helper_tcp_connection", on_read_connection); + ASSERT(read2_cb_called == 1); + ASSERT(tcp_write_cb_called == 1); + ASSERT(tcp_read_cb_called == 1); + ASSERT(exit_cb_called == 1); + return r; +} + + +#ifdef _WIN32 +TEST_IMPL(listen_with_simultaneous_accepts) { + uv_tcp_t server; + int r; + struct sockaddr_in addr = uv_ip4_addr("0.0.0.0", TEST_PORT); + + r = uv_tcp_init(uv_default_loop(), &server); + ASSERT(r == 0); + + r = uv_tcp_bind(&server, addr); + ASSERT(r == 0); + + r = uv_tcp_simultaneous_accepts(&server, 1); + ASSERT(r == 0); + + r = uv_listen((uv_stream_t*)&server, SOMAXCONN, NULL); + ASSERT(r == 0); + ASSERT(server.reqs_pending == 32); + + return 0; +} + + +TEST_IMPL(listen_no_simultaneous_accepts) { + uv_tcp_t server; + int r; + struct sockaddr_in addr = uv_ip4_addr("0.0.0.0", TEST_PORT); + + r = uv_tcp_init(uv_default_loop(), &server); + ASSERT(r == 0); + + r = uv_tcp_bind(&server, addr); + ASSERT(r == 0); + + r = uv_tcp_simultaneous_accepts(&server, 0); + ASSERT(r == 0); + + r = uv_listen((uv_stream_t*)&server, SOMAXCONN, NULL); + ASSERT(r == 0); + ASSERT(server.reqs_pending == 1); + + return 0; +} +#endif + + +/* Everything here runs in a child process. */ + +tcp_conn conn; + + +static void close_cb(uv_handle_t* handle) { + close_cb_called++; +} + + +static void conn_notify_write_cb(uv_write_t* req, int status) { + uv_close((uv_handle_t*)&tcp_server, close_cb); + uv_close((uv_handle_t*)&channel, close_cb); +} + + +static void tcp_connection_write_cb(uv_write_t* req, int status) { + ASSERT((uv_handle_t*)&conn.conn == (uv_handle_t*)req->handle); + uv_close((uv_handle_t*)req->handle, close_cb); + uv_close((uv_handle_t*)&channel, close_cb); + uv_close((uv_handle_t*)&tcp_server, close_cb); + tcp_conn_write_cb_called++; +} + + +static void on_tcp_child_process_read(uv_stream_t* tcp, ssize_t nread, uv_buf_t buf) { + uv_buf_t outbuf; + int r; + + if (nread < 0) { + if (uv_last_error(tcp->loop).code == UV_EOF) { + free(buf.base); + return; + } + + printf("error recving on tcp connection: %s\n", + uv_strerror(uv_last_error(tcp->loop))); + abort(); + } + + ASSERT(nread > 0); + ASSERT(memcmp("world\n", buf.base, nread) == 0); + on_pipe_read_called++; + free(buf.base); + + /* Write to the socket */ + outbuf = uv_buf_init("hello again\n", 12); + r = uv_write(&conn.tcp_write_req, tcp, &outbuf, 1, tcp_connection_write_cb); + ASSERT(r == 0); + + tcp_conn_read_cb_called++; +} + + +static void connect_child_process_cb(uv_connect_t* req, int status) { + int r; + + ASSERT(status == 0); + r = uv_read_start(req->handle, on_read_alloc, on_tcp_child_process_read); + ASSERT(r == 0); +} + + +static void ipc_on_connection(uv_stream_t* server, int status) { + int r; + uv_buf_t buf; + + if (!connection_accepted) { + /* + * Accept the connection and close it. Also let the other + * side know. + */ + ASSERT(status == 0); + ASSERT((uv_stream_t*)&tcp_server == server); + + r = uv_tcp_init(server->loop, &conn.conn); + ASSERT(r == 0); + + r = uv_accept(server, (uv_stream_t*)&conn.conn); + ASSERT(r == 0); + + uv_close((uv_handle_t*)&conn.conn, close_cb); + + buf = uv_buf_init("accepted_connection\n", 20); + r = uv_write2(&conn_notify_req, (uv_stream_t*)&channel, &buf, 1, + NULL, conn_notify_write_cb); + ASSERT(r == 0); + + connection_accepted = 1; + } +} + + +static void ipc_on_connection_tcp_conn(uv_stream_t* server, int status) { + int r; + uv_buf_t buf; + uv_tcp_t* conn; + + ASSERT(status == 0); + ASSERT((uv_stream_t*)&tcp_server == server); + + conn = malloc(sizeof(*conn)); + ASSERT(conn); + + r = uv_tcp_init(server->loop, conn); + ASSERT(r == 0); + + r = uv_accept(server, (uv_stream_t*)conn); + ASSERT(r == 0); + + /* Send the accepted connection to the other process */ + buf = uv_buf_init("hello\n", 6); + r = uv_write2(&conn_notify_req, (uv_stream_t*)&channel, &buf, 1, + (uv_stream_t*)conn, NULL); + ASSERT(r == 0); + + r = uv_read_start((uv_stream_t*)conn, on_read_alloc, on_tcp_child_process_read); + ASSERT(r == 0); + + uv_close((uv_handle_t*)conn, close_cb); +} + + +int ipc_helper(int listen_after_write) { + /* + * This is launched from test-ipc.c. stdin is a duplex channel that we + * over which a handle will be transmitted. + */ + + uv_write_t write_req; + int r; + uv_buf_t buf; + + r = uv_pipe_init(uv_default_loop(), &channel, 1); + ASSERT(r == 0); + + uv_pipe_open(&channel, 0); + + ASSERT(uv_is_readable((uv_stream_t*) &channel)); + ASSERT(uv_is_writable((uv_stream_t*) &channel)); + ASSERT(!uv_is_closing((uv_handle_t*) &channel)); + + r = uv_tcp_init(uv_default_loop(), &tcp_server); + ASSERT(r == 0); + + r = uv_tcp_bind(&tcp_server, uv_ip4_addr("0.0.0.0", TEST_PORT)); + ASSERT(r == 0); + + if (!listen_after_write) { + r = uv_listen((uv_stream_t*)&tcp_server, 12, ipc_on_connection); + ASSERT(r == 0); + } + + buf = uv_buf_init("hello\n", 6); + r = uv_write2(&write_req, (uv_stream_t*)&channel, &buf, 1, + (uv_stream_t*)&tcp_server, NULL); + ASSERT(r == 0); + + if (listen_after_write) { + r = uv_listen((uv_stream_t*)&tcp_server, 12, ipc_on_connection); + ASSERT(r == 0); + } + + r = uv_run(uv_default_loop()); + ASSERT(r == 0); + + ASSERT(connection_accepted == 1); + ASSERT(close_cb_called == 3); + + return 0; +} + + +int ipc_helper_tcp_connection() { + /* + * This is launched from test-ipc.c. stdin is a duplex channel that we + * over which a handle will be transmitted. + */ + + int r; + struct sockaddr_in addr; + + r = uv_pipe_init(uv_default_loop(), &channel, 1); + ASSERT(r == 0); + + uv_pipe_open(&channel, 0); + + ASSERT(uv_is_readable((uv_stream_t*)&channel)); + ASSERT(uv_is_writable((uv_stream_t*)&channel)); + ASSERT(!uv_is_closing((uv_handle_t*)&channel)); + + r = uv_tcp_init(uv_default_loop(), &tcp_server); + ASSERT(r == 0); + + r = uv_tcp_bind(&tcp_server, uv_ip4_addr("0.0.0.0", TEST_PORT)); + ASSERT(r == 0); + + r = uv_listen((uv_stream_t*)&tcp_server, 12, ipc_on_connection_tcp_conn); + ASSERT(r == 0); + + /* Make a connection to the server */ + r = uv_tcp_init(uv_default_loop(), &conn.conn); + ASSERT(r == 0); + + addr = uv_ip4_addr("127.0.0.1", TEST_PORT); + r = uv_tcp_connect(&conn.conn_req, (uv_tcp_t*)&conn.conn, addr, connect_child_process_cb); + ASSERT(r == 0); + + r = uv_run(uv_default_loop()); + ASSERT(r == 0); + + ASSERT(tcp_conn_read_cb_called == 1); + ASSERT(tcp_conn_write_cb_called == 1); + ASSERT(close_cb_called == 4); + + return 0; +} diff --git a/node-v0.8.14/deps/uv/test/test-list.h b/node-v0.8.14/deps/uv/test/test-list.h new file mode 100644 index 0000000..19670e5 --- /dev/null +++ b/node-v0.8.14/deps/uv/test/test-list.h @@ -0,0 +1,424 @@ +/* Copyright Joyent, Inc. and other Node contributors. All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ + +TEST_DECLARE (platform_output) +TEST_DECLARE (callback_order) +TEST_DECLARE (run_once) +TEST_DECLARE (semaphore_1) +TEST_DECLARE (semaphore_2) +TEST_DECLARE (semaphore_3) +TEST_DECLARE (tty) +TEST_DECLARE (stdio_over_pipes) +TEST_DECLARE (ipc_listen_before_write) +TEST_DECLARE (ipc_listen_after_write) +#ifndef _WIN32 +TEST_DECLARE (ipc_send_recv_pipe) +#endif +TEST_DECLARE (ipc_send_recv_tcp) +TEST_DECLARE (ipc_tcp_connection) +TEST_DECLARE (tcp_ping_pong) +TEST_DECLARE (tcp_ping_pong_v6) +TEST_DECLARE (pipe_ping_pong) +TEST_DECLARE (delayed_accept) +TEST_DECLARE (multiple_listen) +TEST_DECLARE (tcp_writealot) +TEST_DECLARE (tcp_connect_error_after_write) +TEST_DECLARE (tcp_shutdown_after_write) +TEST_DECLARE (tcp_bind_error_addrinuse) +TEST_DECLARE (tcp_bind_error_addrnotavail_1) +TEST_DECLARE (tcp_bind_error_addrnotavail_2) +TEST_DECLARE (tcp_bind_error_fault) +TEST_DECLARE (tcp_bind_error_inval) +TEST_DECLARE (tcp_bind_localhost_ok) +TEST_DECLARE (tcp_listen_without_bind) +TEST_DECLARE (tcp_connect_error_fault) +TEST_DECLARE (tcp_connect_timeout) +TEST_DECLARE (tcp_close_while_connecting) +TEST_DECLARE (tcp_close) +TEST_DECLARE (tcp_flags) +TEST_DECLARE (tcp_write_error) +TEST_DECLARE (tcp_write_to_half_open_connection) +TEST_DECLARE (tcp_unexpected_read) +TEST_DECLARE (tcp_bind6_error_addrinuse) +TEST_DECLARE (tcp_bind6_error_addrnotavail) +TEST_DECLARE (tcp_bind6_error_fault) +TEST_DECLARE (tcp_bind6_error_inval) +TEST_DECLARE (tcp_bind6_localhost_ok) +TEST_DECLARE (udp_send_and_recv) +TEST_DECLARE (udp_multicast_join) +TEST_DECLARE (udp_multicast_ttl) +TEST_DECLARE (udp_dgram_too_big) +TEST_DECLARE (udp_dual_stack) +TEST_DECLARE (udp_ipv6_only) +TEST_DECLARE (udp_options) +TEST_DECLARE (pipe_bind_error_addrinuse) +TEST_DECLARE (pipe_bind_error_addrnotavail) +TEST_DECLARE (pipe_bind_error_inval) +TEST_DECLARE (pipe_listen_without_bind) +TEST_DECLARE (pipe_connect_bad_name) +TEST_DECLARE (pipe_connect_to_file) +TEST_DECLARE (connection_fail) +TEST_DECLARE (connection_fail_doesnt_auto_close) +TEST_DECLARE (shutdown_close_tcp) +TEST_DECLARE (shutdown_close_pipe) +TEST_DECLARE (shutdown_eof) +TEST_DECLARE (callback_stack) +TEST_DECLARE (error_message) +TEST_DECLARE (timer) +TEST_DECLARE (timer_again) +TEST_DECLARE (timer_start_twice) +TEST_DECLARE (idle_starvation) +TEST_DECLARE (loop_handles) +TEST_DECLARE (get_loadavg) +TEST_DECLARE (walk_handles) +TEST_DECLARE (ref) +TEST_DECLARE (idle_ref) +TEST_DECLARE (async_ref) +TEST_DECLARE (prepare_ref) +TEST_DECLARE (check_ref) +TEST_DECLARE (unref_in_prepare_cb) +TEST_DECLARE (timer_ref) +TEST_DECLARE (timer_ref2) +TEST_DECLARE (fs_event_ref) +TEST_DECLARE (fs_poll_ref) +TEST_DECLARE (tcp_ref) +TEST_DECLARE (tcp_ref2) +TEST_DECLARE (tcp_ref3) +TEST_DECLARE (tcp_ref4) +TEST_DECLARE (udp_ref) +TEST_DECLARE (udp_ref2) +TEST_DECLARE (udp_ref3) +TEST_DECLARE (pipe_ref) +TEST_DECLARE (pipe_ref2) +TEST_DECLARE (pipe_ref3) +TEST_DECLARE (pipe_ref4) +TEST_DECLARE (process_ref) +TEST_DECLARE (async) +TEST_DECLARE (get_currentexe) +TEST_DECLARE (process_title) +TEST_DECLARE (cwd_and_chdir) +TEST_DECLARE (get_memory) +TEST_DECLARE (hrtime) +TEST_DECLARE (getaddrinfo_basic) +TEST_DECLARE (getaddrinfo_concurrent) +TEST_DECLARE (gethostbyname) +TEST_DECLARE (getsockname_tcp) +TEST_DECLARE (getsockname_udp) +TEST_DECLARE (fail_always) +TEST_DECLARE (pass_always) +TEST_DECLARE (spawn_exit_code) +TEST_DECLARE (spawn_stdout) +TEST_DECLARE (spawn_stdin) +TEST_DECLARE (spawn_stdio_greater_than_3) +TEST_DECLARE (spawn_ignored_stdio) +TEST_DECLARE (spawn_and_kill) +TEST_DECLARE (spawn_detached) +TEST_DECLARE (spawn_and_kill_with_std) +TEST_DECLARE (spawn_and_ping) +TEST_DECLARE (spawn_setuid_fails) +TEST_DECLARE (spawn_setgid_fails) +TEST_DECLARE (spawn_stdout_to_file) +TEST_DECLARE (fs_poll) +TEST_DECLARE (kill) +TEST_DECLARE (fs_file_noent) +TEST_DECLARE (fs_file_nametoolong) +TEST_DECLARE (fs_file_loop) +TEST_DECLARE (fs_file_async) +TEST_DECLARE (fs_file_sync) +TEST_DECLARE (fs_async_dir) +TEST_DECLARE (fs_async_sendfile) +TEST_DECLARE (fs_fstat) +TEST_DECLARE (fs_chmod) +TEST_DECLARE (fs_chown) +TEST_DECLARE (fs_link) +TEST_DECLARE (fs_symlink) +TEST_DECLARE (fs_symlink_dir) +TEST_DECLARE (fs_utime) +TEST_DECLARE (fs_futime) +TEST_DECLARE (fs_file_open_append) +TEST_DECLARE (fs_stat_missing_path) +TEST_DECLARE (fs_read_file_eof) +TEST_DECLARE (fs_event_watch_dir) +TEST_DECLARE (fs_event_watch_file) +TEST_DECLARE (fs_event_watch_file_twice) +TEST_DECLARE (fs_event_watch_file_current_dir) +TEST_DECLARE (fs_event_no_callback_on_close) +TEST_DECLARE (fs_event_immediate_close) +TEST_DECLARE (fs_event_close_with_pending_event) +TEST_DECLARE (fs_event_close_in_callback) +TEST_DECLARE (fs_readdir_empty_dir) +TEST_DECLARE (fs_readdir_file) +TEST_DECLARE (fs_open_dir) +TEST_DECLARE (fs_rename_to_existing_file) +TEST_DECLARE (threadpool_queue_work_simple) +TEST_DECLARE (threadpool_multiple_event_loops) +TEST_DECLARE (thread_mutex) +TEST_DECLARE (thread_rwlock) +TEST_DECLARE (thread_create) +TEST_DECLARE (strlcpy) +TEST_DECLARE (strlcat) +TEST_DECLARE (counters_init) +TEST_DECLARE (dlerror) +TEST_DECLARE (poll_duplex) +TEST_DECLARE (poll_unidirectional) +TEST_DECLARE (poll_close) +#ifdef _WIN32 +TEST_DECLARE (spawn_detect_pipe_name_collisions_on_windows) +TEST_DECLARE (argument_escaping) +TEST_DECLARE (environment_creation) +TEST_DECLARE (listen_with_simultaneous_accepts) +TEST_DECLARE (listen_no_simultaneous_accepts) +TEST_DECLARE (fs_stat_root) +#else +TEST_DECLARE (spawn_setuid_setgid) +#endif +HELPER_DECLARE (tcp4_echo_server) +HELPER_DECLARE (tcp6_echo_server) +HELPER_DECLARE (udp4_echo_server) +HELPER_DECLARE (pipe_echo_server) + + +TASK_LIST_START + TEST_OUTPUT_ENTRY (platform_output) + +#if 0 + TEST_ENTRY (callback_order) +#endif + TEST_ENTRY (run_once) + TEST_ENTRY (semaphore_1) + TEST_ENTRY (semaphore_2) + TEST_ENTRY (semaphore_3) + + TEST_ENTRY (pipe_connect_bad_name) + TEST_ENTRY (pipe_connect_to_file) + + TEST_ENTRY (tty) + TEST_ENTRY (stdio_over_pipes) + TEST_ENTRY (ipc_listen_before_write) + TEST_ENTRY (ipc_listen_after_write) +#ifndef _WIN32 + TEST_ENTRY (ipc_send_recv_pipe) +#endif + TEST_ENTRY (ipc_send_recv_tcp) + TEST_ENTRY (ipc_tcp_connection) + + TEST_ENTRY (tcp_ping_pong) + TEST_HELPER (tcp_ping_pong, tcp4_echo_server) + + TEST_ENTRY (tcp_ping_pong_v6) + TEST_HELPER (tcp_ping_pong_v6, tcp6_echo_server) + + TEST_ENTRY (pipe_ping_pong) + TEST_HELPER (pipe_ping_pong, pipe_echo_server) + + TEST_ENTRY (delayed_accept) + TEST_ENTRY (multiple_listen) + + TEST_ENTRY (tcp_writealot) + TEST_HELPER (tcp_writealot, tcp4_echo_server) + + TEST_ENTRY (tcp_shutdown_after_write) + TEST_HELPER (tcp_shutdown_after_write, tcp4_echo_server) + + TEST_ENTRY (tcp_connect_error_after_write) + TEST_ENTRY (tcp_bind_error_addrinuse) + TEST_ENTRY (tcp_bind_error_addrnotavail_1) + TEST_ENTRY (tcp_bind_error_addrnotavail_2) + TEST_ENTRY (tcp_bind_error_fault) + TEST_ENTRY (tcp_bind_error_inval) + TEST_ENTRY (tcp_bind_localhost_ok) + TEST_ENTRY (tcp_listen_without_bind) + TEST_ENTRY (tcp_connect_error_fault) + TEST_ENTRY (tcp_connect_timeout) + TEST_ENTRY (tcp_close_while_connecting) + TEST_ENTRY (tcp_close) + TEST_ENTRY (tcp_flags) + TEST_ENTRY (tcp_write_error) + TEST_ENTRY (tcp_write_to_half_open_connection) + TEST_ENTRY (tcp_unexpected_read) + + TEST_ENTRY (tcp_bind6_error_addrinuse) + TEST_ENTRY (tcp_bind6_error_addrnotavail) + TEST_ENTRY (tcp_bind6_error_fault) + TEST_ENTRY (tcp_bind6_error_inval) + TEST_ENTRY (tcp_bind6_localhost_ok) + + TEST_ENTRY (udp_send_and_recv) + TEST_ENTRY (udp_dgram_too_big) + TEST_ENTRY (udp_dual_stack) + TEST_ENTRY (udp_ipv6_only) + TEST_ENTRY (udp_options) + TEST_ENTRY (udp_multicast_join) + TEST_ENTRY (udp_multicast_ttl) + + TEST_ENTRY (pipe_bind_error_addrinuse) + TEST_ENTRY (pipe_bind_error_addrnotavail) + TEST_ENTRY (pipe_bind_error_inval) + TEST_ENTRY (pipe_listen_without_bind) + + TEST_ENTRY (connection_fail) + TEST_ENTRY (connection_fail_doesnt_auto_close) + + TEST_ENTRY (shutdown_close_tcp) + TEST_HELPER (shutdown_close_tcp, tcp4_echo_server) + TEST_ENTRY (shutdown_close_pipe) + TEST_HELPER (shutdown_close_pipe, pipe_echo_server) + + TEST_ENTRY (shutdown_eof) + TEST_HELPER (shutdown_eof, tcp4_echo_server) + + TEST_ENTRY (callback_stack) + TEST_HELPER (callback_stack, tcp4_echo_server) + + TEST_ENTRY (error_message) + + TEST_ENTRY (timer) + TEST_ENTRY (timer_again) + TEST_ENTRY (timer_start_twice) + + TEST_ENTRY (idle_starvation) + + TEST_ENTRY (ref) + TEST_ENTRY (idle_ref) + TEST_ENTRY (fs_poll_ref) + TEST_ENTRY (async_ref) + TEST_ENTRY (prepare_ref) + TEST_ENTRY (check_ref) + TEST_ENTRY (unref_in_prepare_cb) + TEST_ENTRY (timer_ref) + TEST_ENTRY (timer_ref2) + TEST_ENTRY (fs_event_ref) + TEST_ENTRY (tcp_ref) + TEST_ENTRY (tcp_ref2) + TEST_ENTRY (tcp_ref3) + TEST_HELPER (tcp_ref3, tcp4_echo_server) + TEST_ENTRY (tcp_ref4) + TEST_HELPER (tcp_ref4, tcp4_echo_server) + TEST_ENTRY (udp_ref) + TEST_ENTRY (udp_ref2) + TEST_ENTRY (udp_ref3) + TEST_HELPER (udp_ref3, udp4_echo_server) + TEST_ENTRY (pipe_ref) + TEST_ENTRY (pipe_ref2) + TEST_ENTRY (pipe_ref3) + TEST_HELPER (pipe_ref3, pipe_echo_server) + TEST_ENTRY (pipe_ref4) + TEST_HELPER (pipe_ref4, pipe_echo_server) + TEST_ENTRY (process_ref) + + TEST_ENTRY (loop_handles) + TEST_ENTRY (walk_handles) + + TEST_ENTRY (async) + + TEST_ENTRY (get_currentexe) + + TEST_ENTRY (process_title) + + TEST_ENTRY (cwd_and_chdir) + + TEST_ENTRY (get_memory) + + TEST_ENTRY (get_loadavg) + + TEST_ENTRY (hrtime) + + TEST_ENTRY (getaddrinfo_basic) + TEST_ENTRY (getaddrinfo_concurrent) + + TEST_ENTRY (gethostbyname) + + TEST_ENTRY (getsockname_tcp) + TEST_ENTRY (getsockname_udp) + + TEST_ENTRY (poll_duplex) + TEST_ENTRY (poll_unidirectional) + TEST_ENTRY (poll_close) + + TEST_ENTRY (spawn_exit_code) + TEST_ENTRY (spawn_stdout) + TEST_ENTRY (spawn_stdin) + TEST_ENTRY (spawn_stdio_greater_than_3) + TEST_ENTRY (spawn_ignored_stdio) + TEST_ENTRY (spawn_and_kill) + TEST_ENTRY (spawn_detached) + TEST_ENTRY (spawn_and_kill_with_std) + TEST_ENTRY (spawn_and_ping) + TEST_ENTRY (spawn_setuid_fails) + TEST_ENTRY (spawn_setgid_fails) + TEST_ENTRY (spawn_stdout_to_file) + TEST_ENTRY (fs_poll) + TEST_ENTRY (kill) +#ifdef _WIN32 + TEST_ENTRY (spawn_detect_pipe_name_collisions_on_windows) + TEST_ENTRY (argument_escaping) + TEST_ENTRY (environment_creation) + TEST_ENTRY (listen_with_simultaneous_accepts) + TEST_ENTRY (listen_no_simultaneous_accepts) + TEST_ENTRY (fs_stat_root) +#else + TEST_ENTRY (spawn_setuid_setgid) +#endif + + TEST_ENTRY (fs_file_noent) + TEST_ENTRY (fs_file_nametoolong) + TEST_ENTRY (fs_file_loop) + TEST_ENTRY (fs_file_async) + TEST_ENTRY (fs_file_sync) + TEST_ENTRY (fs_async_dir) + TEST_ENTRY (fs_async_sendfile) + TEST_ENTRY (fs_fstat) + TEST_ENTRY (fs_chmod) + TEST_ENTRY (fs_chown) + TEST_ENTRY (fs_utime) + TEST_ENTRY (fs_futime) + TEST_ENTRY (fs_symlink) + TEST_ENTRY (fs_symlink_dir) + TEST_ENTRY (fs_stat_missing_path) + TEST_ENTRY (fs_read_file_eof) + TEST_ENTRY (fs_file_open_append) + TEST_ENTRY (fs_event_watch_dir) + TEST_ENTRY (fs_event_watch_file) + TEST_ENTRY (fs_event_watch_file_twice) + TEST_ENTRY (fs_event_watch_file_current_dir) + TEST_ENTRY (fs_event_no_callback_on_close) + TEST_ENTRY (fs_event_immediate_close) + TEST_ENTRY (fs_event_close_with_pending_event) + TEST_ENTRY (fs_event_close_in_callback) + TEST_ENTRY (fs_readdir_empty_dir) + TEST_ENTRY (fs_readdir_file) + TEST_ENTRY (fs_open_dir) + TEST_ENTRY (fs_rename_to_existing_file) + TEST_ENTRY (threadpool_queue_work_simple) + TEST_ENTRY (threadpool_multiple_event_loops) + TEST_ENTRY (thread_mutex) + TEST_ENTRY (thread_rwlock) + TEST_ENTRY (thread_create) + TEST_ENTRY (strlcpy) + TEST_ENTRY (strlcat) + TEST_ENTRY (counters_init) + TEST_ENTRY (dlerror) +#if 0 + /* These are for testing the test runner. */ + TEST_ENTRY (fail_always) + TEST_ENTRY (pass_always) +#endif +TASK_LIST_END diff --git a/node-v0.8.14/deps/uv/test/test-loop-handles.c b/node-v0.8.14/deps/uv/test/test-loop-handles.c new file mode 100644 index 0000000..9972dfa --- /dev/null +++ b/node-v0.8.14/deps/uv/test/test-loop-handles.c @@ -0,0 +1,336 @@ +/* Copyright Joyent, Inc. and other Node contributors. All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ + +/* Tests commented out with XXX are ones that are failing on Linux */ + +/* + * Purpose of this test is to check semantics of starting and stopping + * prepare, check and idle watchers. + * + * - A watcher must be able to safely stop or close itself; + * - Once a watcher is stopped or closed its callback should never be called. + * - If a watcher is closed, it is implicitly stopped and its close_cb should + * be called exactly once. + * - A watcher can safely start and stop other watchers of the same type. + * - Prepare and check watchers are called once per event loop iterations. + * - All active idle watchers are queued when the event loop has no more work + * to do. This is done repeatedly until all idle watchers are inactive. + * - If a watcher starts another watcher of the same type its callback is not + * immediately queued. For check and prepare watchers, that means that if + * a watcher makes another of the same type active, it'll not be called until + * the next event loop iteration. For idle. watchers this means that the + * newly activated idle watcher might not be queued immediately. + * - Prepare, check, idle watchers keep the event loop alive even when they're + * not active. + * + * This is what the test globally does: + * + * - prepare_1 is always active and counts event loop iterations. It also + * creates and starts prepare_2 every other iteration. Finally it verifies + * that no idle watchers are active before polling. + * - prepare_2 is started by prepare_1 every other iteration. It immediately + * stops itself. It verifies that a watcher is not queued immediately + * if created by another watcher of the same type. + * - There's a check watcher that stops the event loop after a certain number + * of iterations. It starts a varying number of idle_1 watchers. + * - Idle_1 watchers stop themselves after being called a few times. All idle_1 + * watchers try to start the idle_2 watcher if it is not already started or + * awaiting its close callback. + * - The idle_2 watcher always exists but immediately closes itself after + * being started by a check_1 watcher. It verifies that a watcher is + * implicitly stopped when closed, and that a watcher can close itself + * safely. + * - There is a repeating timer. It does not keep the event loop alive + * (ev_unref) but makes sure that the loop keeps polling the system for + * events. + */ + + +#include "uv.h" +#include "task.h" + +#include + + +#define IDLE_COUNT 7 +#define ITERATIONS 21 +#define TIMEOUT 100 + + +static uv_prepare_t prepare_1_handle; +static uv_prepare_t prepare_2_handle; + +static uv_check_t check_handle; + +static uv_idle_t idle_1_handles[IDLE_COUNT]; +static uv_idle_t idle_2_handle; + +static uv_timer_t timer_handle; + + +static int loop_iteration = 0; + +static int prepare_1_cb_called = 0; +static int prepare_1_close_cb_called = 0; + +static int prepare_2_cb_called = 0; +static int prepare_2_close_cb_called = 0; + +static int check_cb_called = 0; +static int check_close_cb_called = 0; + +static int idle_1_cb_called = 0; +static int idle_1_close_cb_called = 0; +static int idles_1_active = 0; + +static int idle_2_cb_called = 0; +static int idle_2_close_cb_called = 0; +static int idle_2_cb_started = 0; +static int idle_2_is_active = 0; + + +static void timer_cb(uv_timer_t* handle, int status) { + ASSERT(handle == &timer_handle); + ASSERT(status == 0); +} + + +static void idle_2_close_cb(uv_handle_t* handle) { + LOG("IDLE_2_CLOSE_CB\n"); + + ASSERT(handle == (uv_handle_t*)&idle_2_handle); + + ASSERT(idle_2_is_active); + + idle_2_close_cb_called++; + idle_2_is_active = 0; +} + + +static void idle_2_cb(uv_idle_t* handle, int status) { + LOG("IDLE_2_CB\n"); + + ASSERT(handle == &idle_2_handle); + ASSERT(status == 0); + + idle_2_cb_called++; + + uv_close((uv_handle_t*)handle, idle_2_close_cb); +} + + +static void idle_1_cb(uv_idle_t* handle, int status) { + int r; + + LOG("IDLE_1_CB\n"); + + ASSERT(handle != NULL); + ASSERT(status == 0); + + ASSERT(idles_1_active > 0); + + /* Init idle_2 and make it active */ + if (!idle_2_is_active && !uv_is_closing((uv_handle_t*)&idle_2_handle)) { + r = uv_idle_init(uv_default_loop(), &idle_2_handle); + ASSERT(r == 0); + r = uv_idle_start(&idle_2_handle, idle_2_cb); + ASSERT(r == 0); + idle_2_is_active = 1; + idle_2_cb_started++; + } + + idle_1_cb_called++; + + if (idle_1_cb_called % 5 == 0) { + r = uv_idle_stop((uv_idle_t*)handle); + ASSERT(r == 0); + idles_1_active--; + } +} + + +static void idle_1_close_cb(uv_handle_t* handle) { + LOG("IDLE_1_CLOSE_CB\n"); + + ASSERT(handle != NULL); + + idle_1_close_cb_called++; +} + + +static void prepare_1_close_cb(uv_handle_t* handle) { + LOG("PREPARE_1_CLOSE_CB"); + ASSERT(handle == (uv_handle_t*)&prepare_1_handle); + + prepare_1_close_cb_called++; +} + + +static void check_close_cb(uv_handle_t* handle) { + LOG("CHECK_CLOSE_CB\n"); + ASSERT(handle == (uv_handle_t*)&check_handle); + + check_close_cb_called++; +} + + +static void prepare_2_close_cb(uv_handle_t* handle) { + LOG("PREPARE_2_CLOSE_CB\n"); + ASSERT(handle == (uv_handle_t*)&prepare_2_handle); + + prepare_2_close_cb_called++; +} + + +static void check_cb(uv_check_t* handle, int status) { + int i, r; + + LOG("CHECK_CB\n"); + + ASSERT(handle == &check_handle); + ASSERT(status == 0); + + if (loop_iteration < ITERATIONS) { + /* Make some idle watchers active */ + for (i = 0; i < 1 + (loop_iteration % IDLE_COUNT); i++) { + r = uv_idle_start(&idle_1_handles[i], idle_1_cb); + ASSERT(r == 0); + idles_1_active++; + } + + } else { + /* End of the test - close all handles */ + uv_close((uv_handle_t*)&prepare_1_handle, prepare_1_close_cb); + uv_close((uv_handle_t*)&check_handle, check_close_cb); + uv_close((uv_handle_t*)&prepare_2_handle, prepare_2_close_cb); + + for (i = 0; i < IDLE_COUNT; i++) { + uv_close((uv_handle_t*)&idle_1_handles[i], idle_1_close_cb); + } + + /* This handle is closed/recreated every time, close it only if it is */ + /* active.*/ + if (idle_2_is_active) { + uv_close((uv_handle_t*)&idle_2_handle, idle_2_close_cb); + } + } + + check_cb_called++; +} + + +static void prepare_2_cb(uv_prepare_t* handle, int status) { + int r; + + LOG("PREPARE_2_CB\n"); + + ASSERT(handle == &prepare_2_handle); + ASSERT(status == 0); + + /* prepare_2 gets started by prepare_1 when (loop_iteration % 2 == 0), */ + /* and it stops itself immediately. A started watcher is not queued */ + /* until the next round, so when this callback is made */ + /* (loop_iteration % 2 == 0) cannot be true. */ + ASSERT(loop_iteration % 2 != 0); + + r = uv_prepare_stop((uv_prepare_t*)handle); + ASSERT(r == 0); + + prepare_2_cb_called++; +} + + +static void prepare_1_cb(uv_prepare_t* handle, int status) { + int r; + + LOG("PREPARE_1_CB\n"); + + ASSERT(handle == &prepare_1_handle); + ASSERT(status == 0); + + if (loop_iteration % 2 == 0) { + r = uv_prepare_start(&prepare_2_handle, prepare_2_cb); + ASSERT(r == 0); + } + + prepare_1_cb_called++; + loop_iteration++; + + printf("Loop iteration %d of %d.\n", loop_iteration, ITERATIONS); +} + + +TEST_IMPL(loop_handles) { + int i; + int r; + + r = uv_prepare_init(uv_default_loop(), &prepare_1_handle); + ASSERT(r == 0); + r = uv_prepare_start(&prepare_1_handle, prepare_1_cb); + ASSERT(r == 0); + + r = uv_check_init(uv_default_loop(), &check_handle); + ASSERT(r == 0); + r = uv_check_start(&check_handle, check_cb); + ASSERT(r == 0); + + /* initialize only, prepare_2 is started by prepare_1_cb */ + r = uv_prepare_init(uv_default_loop(), &prepare_2_handle); + ASSERT(r == 0); + + for (i = 0; i < IDLE_COUNT; i++) { + /* initialize only, idle_1 handles are started by check_cb */ + r = uv_idle_init(uv_default_loop(), &idle_1_handles[i]); + ASSERT(r == 0); + } + + /* don't init or start idle_2, both is done by idle_1_cb */ + + /* the timer callback is there to keep the event loop polling */ + /* unref it as it is not supposed to keep the loop alive */ + r = uv_timer_init(uv_default_loop(), &timer_handle); + ASSERT(r == 0); + r = uv_timer_start(&timer_handle, timer_cb, TIMEOUT, TIMEOUT); + ASSERT(r == 0); + uv_unref((uv_handle_t*)&timer_handle); + + r = uv_run(uv_default_loop()); + ASSERT(r == 0); + + ASSERT(loop_iteration == ITERATIONS); + + ASSERT(prepare_1_cb_called == ITERATIONS); + ASSERT(prepare_1_close_cb_called == 1); + + ASSERT(prepare_2_cb_called == floor(ITERATIONS / 2.0)); + ASSERT(prepare_2_close_cb_called == 1); + + ASSERT(check_cb_called == ITERATIONS); + ASSERT(check_close_cb_called == 1); + + /* idle_1_cb should be called a lot */ + ASSERT(idle_1_close_cb_called == IDLE_COUNT); + + ASSERT(idle_2_close_cb_called == idle_2_cb_started); + ASSERT(idle_2_is_active == 0); + + return 0; +} diff --git a/node-v0.8.14/deps/uv/test/test-multiple-listen.c b/node-v0.8.14/deps/uv/test/test-multiple-listen.c new file mode 100644 index 0000000..0b5c887 --- /dev/null +++ b/node-v0.8.14/deps/uv/test/test-multiple-listen.c @@ -0,0 +1,102 @@ +/* Copyright Joyent, Inc. and other Node contributors. All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ + +#include "uv.h" +#include "task.h" +#include +#include + +static int connection_cb_called = 0; +static int close_cb_called = 0; +static int connect_cb_called = 0; +static uv_tcp_t server; +static uv_tcp_t client; + + +static void close_cb(uv_handle_t* handle) { + ASSERT(handle != NULL); + close_cb_called++; +} + + +static void connection_cb(uv_stream_t* tcp, int status) { + ASSERT(status == 0); + uv_close((uv_handle_t*)&server, close_cb); + connection_cb_called++; +} + + +static void start_server() { + struct sockaddr_in addr = uv_ip4_addr("0.0.0.0", TEST_PORT); + int r; + + r = uv_tcp_init(uv_default_loop(), &server); + ASSERT(r == 0); + + r = uv_tcp_bind(&server, addr); + ASSERT(r == 0); + + r = uv_listen((uv_stream_t*)&server, 128, connection_cb); + ASSERT(r == 0); + + r = uv_listen((uv_stream_t*)&server, 128, connection_cb); + ASSERT(r == 0); +} + + +static void connect_cb(uv_connect_t* req, int status) { + ASSERT(req != NULL); + ASSERT(status == 0); + free(req); + uv_close((uv_handle_t*)&client, close_cb); + connect_cb_called++; +} + + +static void client_connect() { + struct sockaddr_in addr = uv_ip4_addr("127.0.0.1", TEST_PORT); + uv_connect_t* connect_req = malloc(sizeof *connect_req); + int r; + + ASSERT(connect_req != NULL); + + r = uv_tcp_init(uv_default_loop(), &client); + ASSERT(r == 0); + + r = uv_tcp_connect(connect_req, &client, addr, connect_cb); + ASSERT(r == 0); +} + + + +TEST_IMPL(multiple_listen) { + start_server(); + + client_connect(); + + uv_run(uv_default_loop()); + + ASSERT(connection_cb_called == 1); + ASSERT(connect_cb_called == 1); + ASSERT(close_cb_called == 2); + + return 0; +} diff --git a/node-v0.8.14/deps/uv/test/test-mutexes.c b/node-v0.8.14/deps/uv/test/test-mutexes.c new file mode 100644 index 0000000..896f46b --- /dev/null +++ b/node-v0.8.14/deps/uv/test/test-mutexes.c @@ -0,0 +1,63 @@ +/* Copyright Joyent, Inc. and other Node contributors. All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ + +#include "uv.h" +#include "task.h" + +#include +#include + + +/* The mutex and rwlock tests are really poor. + * They're very basic sanity checks and nothing more. + * Apologies if that rhymes. + */ + +TEST_IMPL(thread_mutex) { + uv_mutex_t mutex; + int r; + + r = uv_mutex_init(&mutex); + ASSERT(r == 0); + + uv_mutex_lock(&mutex); + uv_mutex_unlock(&mutex); + uv_mutex_destroy(&mutex); + + return 0; +} + + +TEST_IMPL(thread_rwlock) { + uv_rwlock_t rwlock; + int r; + + r = uv_rwlock_init(&rwlock); + ASSERT(r == 0); + + uv_rwlock_rdlock(&rwlock); + uv_rwlock_rdunlock(&rwlock); + uv_rwlock_wrlock(&rwlock); + uv_rwlock_wrunlock(&rwlock); + uv_rwlock_destroy(&rwlock); + + return 0; +} diff --git a/node-v0.8.14/deps/uv/test/test-pass-always.c b/node-v0.8.14/deps/uv/test/test-pass-always.c new file mode 100644 index 0000000..4fb58ff --- /dev/null +++ b/node-v0.8.14/deps/uv/test/test-pass-always.c @@ -0,0 +1,28 @@ +/* Copyright Joyent, Inc. and other Node contributors. All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ + +#include "task.h" + + +TEST_IMPL(pass_always) { + /* This test always passes. It is used to test the test runner. */ + return 0; +} diff --git a/node-v0.8.14/deps/uv/test/test-ping-pong.c b/node-v0.8.14/deps/uv/test/test-ping-pong.c new file mode 100644 index 0000000..1bdcc3b --- /dev/null +++ b/node-v0.8.14/deps/uv/test/test-ping-pong.c @@ -0,0 +1,253 @@ +/* Copyright Joyent, Inc. and other Node contributors. All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ + +#include "uv.h" +#include "task.h" + +#include +#include +#include /* strlen */ + +static int completed_pingers = 0; + +#define NUM_PINGS 1000 + +/* 64 bytes is enough for a pinger */ +#define BUFSIZE 10240 + +static char PING[] = "PING\n"; +static int pinger_on_connect_count; + + +typedef struct { + int pongs; + int state; + union { + uv_tcp_t tcp; + uv_pipe_t pipe; + } stream; + uv_connect_t connect_req; + char read_buffer[BUFSIZE]; +} pinger_t; + +void pinger_try_read(pinger_t* pinger); + + +static uv_buf_t alloc_cb(uv_handle_t* handle, size_t size) { + uv_buf_t buf; + buf.base = (char*)malloc(size); + buf.len = size; + return buf; +} + + +static void pinger_on_close(uv_handle_t* handle) { + pinger_t* pinger = (pinger_t*)handle->data; + + ASSERT(NUM_PINGS == pinger->pongs); + + free(pinger); + + completed_pingers++; +} + + +static void pinger_after_write(uv_write_t *req, int status) { + ASSERT(status == 0); + free(req); +} + + +static void pinger_write_ping(pinger_t* pinger) { + uv_write_t *req; + uv_buf_t buf; + + buf.base = (char*)&PING; + buf.len = strlen(PING); + + req = malloc(sizeof(uv_write_t)); + + if (uv_write(req, (uv_stream_t*)&pinger->stream.tcp, &buf, 1, pinger_after_write)) { + FATAL("uv_write failed"); + } + + puts("PING"); +} + + +static void pinger_read_cb(uv_stream_t* stream, ssize_t nread, uv_buf_t buf) { + ssize_t i; + pinger_t* pinger; + + pinger = (pinger_t*)stream->data; + + if (nread < 0) { + ASSERT(uv_last_error(uv_default_loop()).code == UV_EOF); + + puts("got EOF"); + + if (buf.base) { + free(buf.base); + } + + uv_close((uv_handle_t*)(&pinger->stream.tcp), pinger_on_close); + + return; + } + + /* Now we count the pings */ + for (i = 0; i < nread; i++) { + ASSERT(buf.base[i] == PING[pinger->state]); + pinger->state = (pinger->state + 1) % (sizeof(PING) - 1); + if (pinger->state == 0) { + printf("PONG %d\n", pinger->pongs); + pinger->pongs++; + if (pinger->pongs < NUM_PINGS) { + pinger_write_ping(pinger); + } else { + uv_close((uv_handle_t*)(&pinger->stream.tcp), pinger_on_close); + return; + } + } + } +} + + +static void pinger_on_connect(uv_connect_t *req, int status) { + pinger_t *pinger = (pinger_t*)req->handle->data; + + pinger_on_connect_count++; + + ASSERT(status == 0); + + ASSERT(uv_is_readable(req->handle)); + ASSERT(uv_is_writable(req->handle)); + ASSERT(!uv_is_closing((uv_handle_t *)req->handle)); + + pinger_write_ping(pinger); + + uv_read_start((uv_stream_t*)(req->handle), alloc_cb, pinger_read_cb); +} + + +/* same ping-pong test, but using IPv6 connection */ +static void tcp_pinger_v6_new() { + int r; + struct sockaddr_in6 server_addr = uv_ip6_addr("::1", TEST_PORT); + pinger_t *pinger; + + pinger = (pinger_t*)malloc(sizeof(*pinger)); + pinger->state = 0; + pinger->pongs = 0; + + /* Try to connect to the server and do NUM_PINGS ping-pongs. */ + r = uv_tcp_init(uv_default_loop(), &pinger->stream.tcp); + pinger->stream.tcp.data = pinger; + ASSERT(!r); + + /* We are never doing multiple reads/connects at a time anyway. */ + /* so these handles can be pre-initialized. */ + r = uv_tcp_connect6(&pinger->connect_req, &pinger->stream.tcp, server_addr, + pinger_on_connect); + ASSERT(!r); + + /* Synchronous connect callbacks are not allowed. */ + ASSERT(pinger_on_connect_count == 0); +} + + +static void tcp_pinger_new() { + int r; + struct sockaddr_in server_addr = uv_ip4_addr("127.0.0.1", TEST_PORT); + pinger_t *pinger; + + pinger = (pinger_t*)malloc(sizeof(*pinger)); + pinger->state = 0; + pinger->pongs = 0; + + /* Try to connect to the server and do NUM_PINGS ping-pongs. */ + r = uv_tcp_init(uv_default_loop(), &pinger->stream.tcp); + pinger->stream.tcp.data = pinger; + ASSERT(!r); + + /* We are never doing multiple reads/connects at a time anyway. */ + /* so these handles can be pre-initialized. */ + r = uv_tcp_connect(&pinger->connect_req, &pinger->stream.tcp, server_addr, + pinger_on_connect); + ASSERT(!r); + + /* Synchronous connect callbacks are not allowed. */ + ASSERT(pinger_on_connect_count == 0); +} + + +static void pipe_pinger_new() { + int r; + pinger_t *pinger; + + pinger = (pinger_t*)malloc(sizeof(*pinger)); + pinger->state = 0; + pinger->pongs = 0; + + /* Try to connect to the server and do NUM_PINGS ping-pongs. */ + r = uv_pipe_init(uv_default_loop(), &pinger->stream.pipe, 0); + pinger->stream.pipe.data = pinger; + ASSERT(!r); + + /* We are never doing multiple reads/connects at a time anyway. */ + /* so these handles can be pre-initialized. */ + + uv_pipe_connect(&pinger->connect_req, &pinger->stream.pipe, TEST_PIPENAME, + pinger_on_connect); + + /* Synchronous connect callbacks are not allowed. */ + ASSERT(pinger_on_connect_count == 0); +} + + +TEST_IMPL(tcp_ping_pong) { + tcp_pinger_new(); + uv_run(uv_default_loop()); + + ASSERT(completed_pingers == 1); + + return 0; +} + + +TEST_IMPL(tcp_ping_pong_v6) { + tcp_pinger_v6_new(); + uv_run(uv_default_loop()); + + ASSERT(completed_pingers == 1); + + return 0; +} + + +TEST_IMPL(pipe_ping_pong) { + pipe_pinger_new(); + uv_run(uv_default_loop()); + + ASSERT(completed_pingers == 1); + + return 0; +} diff --git a/node-v0.8.14/deps/uv/test/test-pipe-bind-error.c b/node-v0.8.14/deps/uv/test/test-pipe-bind-error.c new file mode 100644 index 0000000..b84d20f --- /dev/null +++ b/node-v0.8.14/deps/uv/test/test-pipe-bind-error.c @@ -0,0 +1,140 @@ +/* Copyright Joyent, Inc. and other Node contributors. All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ + +#include "uv.h" +#include "task.h" +#include +#include + + +#ifdef _WIN32 +# define BAD_PIPENAME "bad-pipe" +#else +# define BAD_PIPENAME "/path/to/unix/socket/that/really/should/not/be/there" +#endif + + +static int close_cb_called = 0; + + +static void close_cb(uv_handle_t* handle) { + ASSERT(handle != NULL); + close_cb_called++; +} + + +TEST_IMPL(pipe_bind_error_addrinuse) { + uv_pipe_t server1, server2; + int r; + + r = uv_pipe_init(uv_default_loop(), &server1, 0); + ASSERT(r == 0); + r = uv_pipe_bind(&server1, TEST_PIPENAME); + ASSERT(r == 0); + + r = uv_pipe_init(uv_default_loop(), &server2, 0); + ASSERT(r == 0); + r = uv_pipe_bind(&server2, TEST_PIPENAME); + ASSERT(r == -1); + + ASSERT(uv_last_error(uv_default_loop()).code == UV_EADDRINUSE); + + r = uv_listen((uv_stream_t*)&server1, SOMAXCONN, NULL); + ASSERT(r == 0); + r = uv_listen((uv_stream_t*)&server2, SOMAXCONN, NULL); + ASSERT(r == -1); + + ASSERT(uv_last_error(uv_default_loop()).code == UV_EINVAL); + + uv_close((uv_handle_t*)&server1, close_cb); + uv_close((uv_handle_t*)&server2, close_cb); + + uv_run(uv_default_loop()); + + ASSERT(close_cb_called == 2); + + return 0; +} + + +TEST_IMPL(pipe_bind_error_addrnotavail) { + uv_pipe_t server; + int r; + + r = uv_pipe_init(uv_default_loop(), &server, 0); + ASSERT(r == 0); + r = uv_pipe_bind(&server, BAD_PIPENAME); + + ASSERT(r == -1); + ASSERT(uv_last_error(uv_default_loop()).code == UV_EACCES); + + uv_close((uv_handle_t*)&server, close_cb); + + uv_run(uv_default_loop()); + + ASSERT(close_cb_called == 1); + + return 0; +} + + +TEST_IMPL(pipe_bind_error_inval) { + uv_pipe_t server; + int r; + + r = uv_pipe_init(uv_default_loop(), &server, 0); + ASSERT(r == 0); + r = uv_pipe_bind(&server, TEST_PIPENAME); + ASSERT(r == 0); + r = uv_pipe_bind(&server, TEST_PIPENAME_2); + ASSERT(r == -1); + + ASSERT(uv_last_error(uv_default_loop()).code == UV_EINVAL); + + uv_close((uv_handle_t*)&server, close_cb); + + uv_run(uv_default_loop()); + + ASSERT(close_cb_called == 1); + + return 0; +} + + +TEST_IMPL(pipe_listen_without_bind) { + uv_pipe_t server; + int r; + + r = uv_pipe_init(uv_default_loop(), &server, 0); + ASSERT(r == 0); + r = uv_listen((uv_stream_t*)&server, SOMAXCONN, NULL); + ASSERT(r == -1); + + ASSERT(uv_last_error(uv_default_loop()).code == UV_EINVAL); + + uv_close((uv_handle_t*)&server, close_cb); + + uv_run(uv_default_loop()); + + ASSERT(close_cb_called == 1); + + return 0; +} diff --git a/node-v0.8.14/deps/uv/test/test-pipe-connect-error.c b/node-v0.8.14/deps/uv/test/test-pipe-connect-error.c new file mode 100644 index 0000000..cc06d42 --- /dev/null +++ b/node-v0.8.14/deps/uv/test/test-pipe-connect-error.c @@ -0,0 +1,96 @@ +/* Copyright Joyent, Inc. and other Node contributors. All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ + +#include "uv.h" +#include "task.h" +#include +#include + + +#ifdef _WIN32 +# define BAD_PIPENAME "bad-pipe" +#else +# define BAD_PIPENAME "/path/to/unix/socket/that/really/should/not/be/there" +#endif + + +static int close_cb_called = 0; +static int connect_cb_called = 0; + + +static void close_cb(uv_handle_t* handle) { + ASSERT(handle != NULL); + close_cb_called++; +} + + +static void connect_cb(uv_connect_t* connect_req, int status) { + ASSERT(status == -1); + ASSERT(uv_last_error(uv_default_loop()).code == UV_ENOENT); + uv_close((uv_handle_t*)connect_req->handle, close_cb); + connect_cb_called++; +} + + +static void connect_cb_file(uv_connect_t* connect_req, int status) { + ASSERT(status == -1); + ASSERT(uv_last_error(uv_default_loop()).code == UV_ENOTSOCK || + uv_last_error(uv_default_loop()).code == UV_ECONNREFUSED); + uv_close((uv_handle_t*)connect_req->handle, close_cb); + connect_cb_called++; +} + + +TEST_IMPL(pipe_connect_bad_name) { + uv_pipe_t client; + uv_connect_t req; + int r; + + r = uv_pipe_init(uv_default_loop(), &client, 0); + ASSERT(r == 0); + uv_pipe_connect(&req, &client, BAD_PIPENAME, connect_cb); + + uv_run(uv_default_loop()); + + ASSERT(close_cb_called == 1); + ASSERT(connect_cb_called == 1); + + return 0; +} + + +TEST_IMPL(pipe_connect_to_file) { + const char* path = "test/fixtures/empty_file"; + uv_pipe_t client; + uv_connect_t req; + int r; + + r = uv_pipe_init(uv_default_loop(), &client, 0); + ASSERT(r == 0); + uv_pipe_connect(&req, &client, path, connect_cb_file); + + uv_run(uv_default_loop()); + + ASSERT(close_cb_called == 1); + ASSERT(connect_cb_called == 1); + + return 0; +} diff --git a/node-v0.8.14/deps/uv/test/test-platform-output.c b/node-v0.8.14/deps/uv/test/test-platform-output.c new file mode 100644 index 0000000..008d14f --- /dev/null +++ b/node-v0.8.14/deps/uv/test/test-platform-output.c @@ -0,0 +1,87 @@ +/* Copyright Joyent, Inc. and other Node contributors. All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ + +#include "uv.h" +#include "task.h" +#include + + +TEST_IMPL(platform_output) { + char buffer[512]; + size_t rss; + double uptime; + uv_cpu_info_t* cpus; + uv_interface_address_t* interfaces; + int count; + int i; + uv_err_t err; + + err = uv_get_process_title(buffer, sizeof(buffer)); + ASSERT(UV_OK == err.code); + printf("uv_get_process_title: %s\n", buffer); + + err = uv_resident_set_memory(&rss); + ASSERT(UV_OK == err.code); + printf("uv_resident_set_memory: %llu\n", (unsigned long long) rss); + + err = uv_uptime(&uptime); + ASSERT(UV_OK == err.code); + ASSERT(uptime > 0); + printf("uv_uptime: %f\n", uptime); + + err = uv_cpu_info(&cpus, &count); + ASSERT(UV_OK == err.code); + + printf("uv_cpu_info:\n"); + for (i = 0; i < count; i++) { + printf(" model: %s\n", cpus[i].model); + printf(" speed: %d\n", cpus[i].speed); + printf(" times.sys: %llu\n", (unsigned long long) cpus[i].cpu_times.sys); + printf(" times.user: %llu\n", + (unsigned long long) cpus[i].cpu_times.user); + printf(" times.idle: %llu\n", + (unsigned long long) cpus[i].cpu_times.idle); + printf(" times.irq: %llu\n", (unsigned long long) cpus[i].cpu_times.irq); + printf(" times.nice: %llu\n", + (unsigned long long) cpus[i].cpu_times.nice); + } + uv_free_cpu_info(cpus, count); + + err = uv_interface_addresses(&interfaces, &count); + ASSERT(UV_OK == err.code); + + printf("uv_interface_addresses:\n"); + for (i = 0; i < count; i++) { + printf(" name: %s\n", interfaces[i].name); + printf(" internal: %d\n", interfaces[i].is_internal); + + if (interfaces[i].address.address4.sin_family == AF_INET) { + uv_ip4_name(&interfaces[i].address.address4, buffer, sizeof(buffer)); + } else if (interfaces[i].address.address4.sin_family == AF_INET6) { + uv_ip6_name(&interfaces[i].address.address6, buffer, sizeof(buffer)); + } + + printf(" address: %s\n", buffer); + } + uv_free_interface_addresses(interfaces, count); + + return 0; +} diff --git a/node-v0.8.14/deps/uv/test/test-poll-close.c b/node-v0.8.14/deps/uv/test/test-poll-close.c new file mode 100644 index 0000000..4c3701b --- /dev/null +++ b/node-v0.8.14/deps/uv/test/test-poll-close.c @@ -0,0 +1,77 @@ +/* Copyright Joyent, Inc. and other Node contributors. All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ + +#include + +#ifndef _WIN32 +# include +# include +# include +#endif + +#include "uv.h" +#include "task.h" + +#define NUM_SOCKETS 64 + + +static int close_cb_called = 0; + + +static void poll_cb_fail(uv_poll_t* handle, int status, int events) { + ASSERT(0 && "poll_fail_cb should never be called"); +} + + +static void close_cb(uv_handle_t* handle) { + close_cb_called++; +} + + +TEST_IMPL(poll_close) { + uv_os_sock_t sockets[NUM_SOCKETS]; + uv_poll_t poll_handles[NUM_SOCKETS]; + int i; + +#ifdef _WIN32 + { + struct WSAData wsa_data; + int r = WSAStartup(MAKEWORD(2, 2), &wsa_data); + ASSERT(r == 0); + } +#endif + + for (i = 0; i < NUM_SOCKETS; i++) { + sockets[i] = socket(AF_INET, SOCK_STREAM, 0); + uv_poll_init_socket(uv_default_loop(), &poll_handles[i], sockets[i]); + uv_poll_start(&poll_handles[i], UV_READABLE | UV_WRITABLE, NULL); + } + + for (i = 0; i < NUM_SOCKETS; i++) { + uv_close((uv_handle_t*) &poll_handles[i], close_cb); + } + + uv_run(uv_default_loop()); + + ASSERT(close_cb_called == NUM_SOCKETS); + + return 0; +} diff --git a/node-v0.8.14/deps/uv/test/test-poll.c b/node-v0.8.14/deps/uv/test/test-poll.c new file mode 100644 index 0000000..5a20b9d --- /dev/null +++ b/node-v0.8.14/deps/uv/test/test-poll.c @@ -0,0 +1,573 @@ +/* Copyright Joyent, Inc. and other Node contributors. All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ + +#include + +#ifndef _WIN32 +# include +# include +# include +#endif + +#include "uv.h" +#include "task.h" + + +#define NUM_CLIENTS 5 +#define TRANSFER_BYTES (1 << 16) + +#undef MIN +#define MIN(a, b) (((a) < (b)) ? (a) : (b)); + + +typedef enum { + UNIDIRECTIONAL, + DUPLEX +} test_mode_t; + +typedef struct connection_context_s { + uv_poll_t poll_handle; + uv_timer_t timer_handle; + uv_os_sock_t sock; + size_t read, sent; + int is_server_connection; + int open_handles; + int got_fin, sent_fin; + unsigned int events, delayed_events; +} connection_context_t; + +typedef struct server_context_s { + uv_poll_t poll_handle; + uv_os_sock_t sock; + int connections; +} server_context_t; + + +static void delay_timer_cb(uv_timer_t* timer, int status); + + +static test_mode_t test_mode = DUPLEX; + +static int closed_connections = 0; + +static int valid_writable_wakeups = 0; +static int spurious_writable_wakeups = 0; + + +static int got_eagain() { +#ifdef _WIN32 + return WSAGetLastError() == WSAEWOULDBLOCK; +#else + return errno == EAGAIN + || errno == EINPROGRESS +#ifdef EWOULDBLOCK + || errno == EWOULDBLOCK; +#endif + ; +#endif +} + + +static void set_nonblocking(uv_os_sock_t sock) { + int r; +#ifdef _WIN32 + unsigned long on = 1; + r = ioctlsocket(sock, FIONBIO, &on); + ASSERT(r == 0); +#else + int flags = fcntl(sock, F_GETFL, 0); + ASSERT(flags >= 0); + r = fcntl(sock, F_SETFL, flags | O_NONBLOCK); + ASSERT(r >= 0); +#endif +} + + +static uv_os_sock_t create_nonblocking_bound_socket( + struct sockaddr_in bind_addr) { + uv_os_sock_t sock; + int r; + + sock = socket(AF_INET, SOCK_STREAM, IPPROTO_IP); +#ifdef _WIN32 + ASSERT(sock != INVALID_SOCKET); +#else + ASSERT(sock >= 0); +#endif + + set_nonblocking(sock); + +#ifndef _WIN32 + { + /* Allow reuse of the port. */ + int yes = 1; + r = setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof yes); + ASSERT(r == 0); + } +#endif + + r = bind(sock, (const struct sockaddr*) &bind_addr, sizeof bind_addr); + ASSERT(r == 0); + + return sock; +} + + +static void close_socket(uv_os_sock_t sock) { + int r; +#ifdef _WIN32 + r = closesocket(sock); +#else + r = close(sock); +#endif + ASSERT(r == 0); +} + + +static connection_context_t* create_connection_context( + uv_os_sock_t sock, int is_server_connection) { + int r; + connection_context_t* context; + + context = (connection_context_t*) malloc(sizeof *context); + ASSERT(context != NULL); + + context->sock = sock; + context->is_server_connection = is_server_connection; + context->read = 0; + context->sent = 0; + context->open_handles = 0; + context->events = 0; + context->delayed_events = 0; + context->got_fin = 0; + context->sent_fin = 0; + + r = uv_poll_init_socket(uv_default_loop(), &context->poll_handle, sock); + context->open_handles++; + context->poll_handle.data = context; + ASSERT(r == 0); + + r = uv_timer_init(uv_default_loop(), &context->timer_handle); + context->open_handles++; + context->timer_handle.data = context; + ASSERT(r == 0); + + return context; +} + + +static void connection_close_cb(uv_handle_t* handle) { + connection_context_t* context = (connection_context_t*) handle->data; + + if (--context->open_handles == 0) { + if (test_mode == DUPLEX || context->is_server_connection) { + ASSERT(context->read == TRANSFER_BYTES); + } else { + ASSERT(context->read == 0); + } + + if (test_mode == DUPLEX || !context->is_server_connection) { + ASSERT(context->sent == TRANSFER_BYTES); + } else { + ASSERT(context->sent == 0); + } + + closed_connections++; + + free(context); + } +} + + +static void destroy_connection_context(connection_context_t* context) { + uv_close((uv_handle_t*) &context->poll_handle, connection_close_cb); + uv_close((uv_handle_t*) &context->timer_handle, connection_close_cb); +} + + +static void connection_poll_cb(uv_poll_t* handle, int status, int events) { + connection_context_t* context = (connection_context_t*) handle->data; + int new_events; + int r; + + ASSERT(status == 0); + ASSERT(events & context->events); + ASSERT(!(events & ~context->events)); + + new_events = context->events; + + if (events & UV_READABLE) { + int action = rand() % 7; + + switch (action) { + case 0: + case 1: { + /* Read a couple of bytes. */ + static char buffer[74]; + r = recv(context->sock, buffer, sizeof buffer, 0); + ASSERT(r >= 0); + + if (r > 0) { + context->read += r; + } else { + /* Got FIN. */ + context->got_fin = 1; + new_events &= ~UV_READABLE; + } + + break; + } + + case 2: + case 3: { + /* Read until EAGAIN. */ + static char buffer[931]; + r = recv(context->sock, buffer, sizeof buffer, 0); + ASSERT(r >= 0); + + while (r > 0) { + context->read += r; + r = recv(context->sock, buffer, sizeof buffer, 0); + } + + if (r == 0) { + /* Got FIN. */ + context->got_fin = 1; + new_events &= ~UV_READABLE; + } else { + ASSERT(got_eagain()); + } + + break; + } + + case 4: + /* Ignore. */ + break; + + case 5: + /* Stop reading for a while. Restart in timer callback. */ + new_events &= ~UV_READABLE; + if (!uv_is_active((uv_handle_t*) &context->timer_handle)) { + context->delayed_events = UV_READABLE; + uv_timer_start(&context->timer_handle, delay_timer_cb, 10, 0); + } else { + context->delayed_events |= UV_READABLE; + } + break; + + case 6: + /* Fudge with the event mask. */ + uv_poll_start(&context->poll_handle, UV_WRITABLE, connection_poll_cb); + uv_poll_start(&context->poll_handle, UV_READABLE, connection_poll_cb); + context->events = UV_READABLE; + break; + + default: + ASSERT(0); + } + } + + if (events & UV_WRITABLE) { + if (context->sent < TRANSFER_BYTES && + !(test_mode == UNIDIRECTIONAL && context->is_server_connection)) { + /* We have to send more bytes. */ + int action = rand() % 7; + + switch (action) { + case 0: + case 1: { + /* Send a couple of bytes. */ + static char buffer[103]; + + int send_bytes = MIN(TRANSFER_BYTES - context->sent, sizeof buffer); + ASSERT(send_bytes > 0); + + r = send(context->sock, buffer, send_bytes, 0); + + if (r < 0) { + ASSERT(got_eagain()); + spurious_writable_wakeups++; + break; + } + + ASSERT(r > 0); + context->sent += r; + valid_writable_wakeups++; + break; + } + + case 2: + case 3: { + /* Send until EAGAIN. */ + static char buffer[1234]; + + int send_bytes = MIN(TRANSFER_BYTES - context->sent, sizeof buffer); + ASSERT(send_bytes > 0); + + r = send(context->sock, buffer, send_bytes, 0); + + if (r < 0) { + ASSERT(got_eagain()); + spurious_writable_wakeups++; + break; + } + + ASSERT(r > 0); + valid_writable_wakeups++; + context->sent += r; + + while (context->sent < TRANSFER_BYTES) { + send_bytes = MIN(TRANSFER_BYTES - context->sent, sizeof buffer); + ASSERT(send_bytes > 0); + + r = send(context->sock, buffer, send_bytes, 0); + + if (r <= 0) break; + context->sent += r; + } + ASSERT(r > 0 || got_eagain()); + break; + } + + case 4: + /* Ignore. */ + break; + + case 5: + /* Stop sending for a while. Restart in timer callback. */ + new_events &= ~UV_WRITABLE; + if (!uv_is_active((uv_handle_t*) &context->timer_handle)) { + context->delayed_events = UV_WRITABLE; + uv_timer_start(&context->timer_handle, delay_timer_cb, 100, 0); + } else { + context->delayed_events |= UV_WRITABLE; + } + break; + + case 6: + /* Fudge with the event mask. */ + uv_poll_start(&context->poll_handle, + UV_READABLE, + connection_poll_cb); + uv_poll_start(&context->poll_handle, + UV_WRITABLE, + connection_poll_cb); + context->events = UV_WRITABLE; + break; + + default: + ASSERT(0); + } + + } else { + /* Nothing more to write. Send FIN. */ + int r; +#ifdef _WIN32 + r = shutdown(context->sock, SD_SEND); +#else + r = shutdown(context->sock, SHUT_WR); +#endif + ASSERT(r == 0); + context->sent_fin = 1; + new_events &= ~UV_WRITABLE; + } + } + + if (context->got_fin && context->sent_fin) { + /* Sent and received FIN. Close and destroy context. */ + close_socket(context->sock); + destroy_connection_context(context); + context->events = 0; + + } else if (new_events != context->events) { + /* Poll mask changed. Call uv_poll_start again. */ + context->events = new_events; + uv_poll_start(handle, new_events, connection_poll_cb); + } + + /* Assert that uv_is_active works correctly for poll handles. */ + if (context->events != 0) { + ASSERT(uv_is_active((uv_handle_t*) handle)); + } else { + ASSERT(!uv_is_active((uv_handle_t*) handle)); + } +} + + +static void delay_timer_cb(uv_timer_t* timer, int status) { + connection_context_t* context = (connection_context_t*) timer->data; + int r; + + /* Timer should auto stop. */ + ASSERT(!uv_is_active((uv_handle_t*) timer)); + + /* Add the requested events to the poll mask. */ + ASSERT(context->delayed_events != 0); + context->events |= context->delayed_events; + context->delayed_events = 0; + + r = uv_poll_start(&context->poll_handle, + context->events, + connection_poll_cb); + ASSERT(r == 0); +} + + +static server_context_t* create_server_context( + uv_os_sock_t sock) { + int r; + server_context_t* context; + + context = (server_context_t*) malloc(sizeof *context); + ASSERT(context != NULL); + + context->sock = sock; + context->connections = 0; + + r = uv_poll_init_socket(uv_default_loop(), &context->poll_handle, sock); + context->poll_handle.data = context; + ASSERT(r == 0); + + return context; +} + + +static void server_close_cb(uv_handle_t* handle) { + server_context_t* context = (server_context_t*) handle->data; + free(context); +} + + +static void destroy_server_context(server_context_t* context) { + uv_close((uv_handle_t*) &context->poll_handle, server_close_cb); +} + + +static void server_poll_cb(uv_poll_t* handle, int status, int events) { + server_context_t* server_context = (server_context_t*) + handle->data; + connection_context_t* connection_context; + struct sockaddr_in addr; + socklen_t addr_len; + uv_os_sock_t sock; + int r; + + addr_len = sizeof addr; + sock = accept(server_context->sock, (struct sockaddr*) &addr, &addr_len); +#ifdef _WIN32 + ASSERT(sock != INVALID_SOCKET); +#else + ASSERT(sock >= 0); +#endif + + set_nonblocking(sock); + + connection_context = create_connection_context(sock, 1); + connection_context->events = UV_READABLE | UV_WRITABLE; + r = uv_poll_start(&connection_context->poll_handle, + UV_READABLE | UV_WRITABLE, + connection_poll_cb); + ASSERT(r == 0); + + if (++server_context->connections == NUM_CLIENTS) { + close_socket(server_context->sock); + destroy_server_context(server_context); + } +} + + +static void start_server() { + uv_os_sock_t sock; + server_context_t* context; + int r; + + sock = create_nonblocking_bound_socket(uv_ip4_addr("127.0.0.1", TEST_PORT)); + context = create_server_context(sock); + + r = listen(sock, 100); + ASSERT(r == 0); + + r = uv_poll_start(&context->poll_handle, UV_READABLE, server_poll_cb); + ASSERT(r == 0); +} + + +static void start_client() { + uv_os_sock_t sock; + connection_context_t* context; + struct sockaddr_in server_addr = uv_ip4_addr("127.0.0.1", TEST_PORT); + int r; + + sock = create_nonblocking_bound_socket(uv_ip4_addr("0.0.0.0", 0)); + context = create_connection_context(sock, 0); + + context->events = UV_READABLE | UV_WRITABLE; + r = uv_poll_start(&context->poll_handle, + UV_READABLE | UV_WRITABLE, + connection_poll_cb); + ASSERT(r == 0); + + r = connect(sock, (struct sockaddr*) &server_addr, sizeof server_addr); + ASSERT(r == 0 || got_eagain()); +} + + +static void start_poll_test() { + int i, r; + +#ifdef _WIN32 + { + struct WSAData wsa_data; + int r = WSAStartup(MAKEWORD(2, 2), &wsa_data); + ASSERT(r == 0); + } +#endif + + start_server(); + + for (i = 0; i < NUM_CLIENTS; i++) + start_client(); + + r = uv_run(uv_default_loop()); + ASSERT(r == 0); + + /* Assert that at most five percent of the writable wakeups was spurious. */ + ASSERT(spurious_writable_wakeups == 0 || + (valid_writable_wakeups + spurious_writable_wakeups) / + spurious_writable_wakeups > 20); + + ASSERT(closed_connections == NUM_CLIENTS * 2); +} + + +TEST_IMPL(poll_duplex) { + test_mode = DUPLEX; + start_poll_test(); + return 0; +} + + +TEST_IMPL(poll_unidirectional) { + test_mode = UNIDIRECTIONAL; + start_poll_test(); + return 0; +} diff --git a/node-v0.8.14/deps/uv/test/test-process-title.c b/node-v0.8.14/deps/uv/test/test-process-title.c new file mode 100644 index 0000000..13d9ddd --- /dev/null +++ b/node-v0.8.14/deps/uv/test/test-process-title.c @@ -0,0 +1,49 @@ +/* Copyright Joyent, Inc. and other Node contributors. All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ + +#include "uv.h" +#include "task.h" +#include + + +static void set_title(const char* title) { + char buffer[512]; + uv_err_t err; + + err = uv_get_process_title(buffer, sizeof(buffer)); + ASSERT(UV_OK == err.code); + + err = uv_set_process_title(title); + ASSERT(UV_OK == err.code); + + err = uv_get_process_title(buffer, sizeof(buffer)); + ASSERT(UV_OK == err.code); + + ASSERT(strcmp(buffer, title) == 0); +} + + +TEST_IMPL(process_title) { + /* Check for format string vulnerabilities. */ + set_title("%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s"); + set_title("new title"); + return 0; +} diff --git a/node-v0.8.14/deps/uv/test/test-ref.c b/node-v0.8.14/deps/uv/test/test-ref.c new file mode 100644 index 0000000..e0c3885 --- /dev/null +++ b/node-v0.8.14/deps/uv/test/test-ref.c @@ -0,0 +1,338 @@ +/* Copyright Joyent, Inc. and other Node contributors. All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ + +#include "uv.h" +#include "task.h" + +#include +#include + + +static uv_write_t write_req; +static uv_shutdown_t shutdown_req; +static uv_connect_t connect_req; + +static char buffer[32767]; + +static int req_cb_called; +static int connect_cb_called; +static int write_cb_called; +static int shutdown_cb_called; + + +static void fail_cb(void) { + FATAL("fail_cb should not have been called"); +} + + +static void req_cb(uv_handle_t* req, int status) { + req_cb_called++; +} + + +static void shutdown_cb(uv_shutdown_t* req, int status) { + ASSERT(req == &shutdown_req); + shutdown_cb_called++; +} + + +static void write_cb(uv_write_t* req, int status) { + ASSERT(req == &write_req); + uv_shutdown(&shutdown_req, req->handle, shutdown_cb); + write_cb_called++; +} + + +static void connect_and_write(uv_connect_t* req, int status) { + uv_buf_t buf = uv_buf_init(buffer, sizeof buffer); + ASSERT(req == &connect_req); + ASSERT(status == 0); + uv_write(&write_req, req->handle, &buf, 1, write_cb); + connect_cb_called++; +} + + + +static void connect_and_shutdown(uv_connect_t* req, int status) { + ASSERT(req == &connect_req); + ASSERT(status == 0); + uv_shutdown(&shutdown_req, req->handle, shutdown_cb); + connect_cb_called++; +} + + +TEST_IMPL(ref) { + uv_run(uv_default_loop()); + return 0; +} + + +TEST_IMPL(idle_ref) { + uv_idle_t h; + uv_idle_init(uv_default_loop(), &h); + uv_idle_start(&h, NULL); + uv_unref((uv_handle_t*)&h); + uv_run(uv_default_loop()); + return 0; +} + + +TEST_IMPL(async_ref) { + uv_async_t h; + uv_async_init(uv_default_loop(), &h, NULL); + uv_unref((uv_handle_t*)&h); + uv_run(uv_default_loop()); + return 0; +} + + +TEST_IMPL(prepare_ref) { + uv_prepare_t h; + uv_prepare_init(uv_default_loop(), &h); + uv_prepare_start(&h, NULL); + uv_unref((uv_handle_t*)&h); + uv_run(uv_default_loop()); + return 0; +} + + +TEST_IMPL(check_ref) { + uv_check_t h; + uv_check_init(uv_default_loop(), &h); + uv_check_start(&h, NULL); + uv_unref((uv_handle_t*)&h); + uv_run(uv_default_loop()); + return 0; +} + + +static void prepare_cb(uv_prepare_t* h, int status) { + ASSERT(h != NULL); + ASSERT(status == 0); + uv_unref((uv_handle_t*)h); +} + + +TEST_IMPL(unref_in_prepare_cb) { + uv_prepare_t h; + uv_prepare_init(uv_default_loop(), &h); + uv_prepare_start(&h, prepare_cb); + uv_run(uv_default_loop()); + return 0; +} + + +TEST_IMPL(timer_ref) { + uv_timer_t h; + uv_timer_init(uv_default_loop(), &h); + uv_unref((uv_handle_t*)&h); + uv_run(uv_default_loop()); + return 0; +} + + +TEST_IMPL(timer_ref2) { + uv_timer_t h; + uv_timer_init(uv_default_loop(), &h); + uv_timer_start(&h, (uv_timer_cb)fail_cb, 42, 42); + uv_unref((uv_handle_t*)&h); + uv_run(uv_default_loop()); + return 0; +} + + +TEST_IMPL(fs_event_ref) { + uv_fs_event_t h; + uv_fs_event_init(uv_default_loop(), &h, ".", (uv_fs_event_cb)fail_cb, 0); + uv_unref((uv_handle_t*)&h); + uv_run(uv_default_loop()); + return 0; +} + + +TEST_IMPL(fs_poll_ref) { + uv_fs_poll_t h; + uv_fs_poll_init(uv_default_loop(), &h); + uv_fs_poll_start(&h, NULL, ".", 999); + uv_unref((uv_handle_t*)&h); + uv_run(uv_default_loop()); + return 0; +} + + +TEST_IMPL(tcp_ref) { + uv_tcp_t h; + uv_tcp_init(uv_default_loop(), &h); + uv_unref((uv_handle_t*)&h); + uv_run(uv_default_loop()); + return 0; +} + + +TEST_IMPL(tcp_ref2) { + uv_tcp_t h; + uv_tcp_init(uv_default_loop(), &h); + uv_listen((uv_stream_t*)&h, 128, (uv_connection_cb)fail_cb); + uv_unref((uv_handle_t*)&h); + uv_run(uv_default_loop()); + return 0; +} + + +TEST_IMPL(tcp_ref3) { + struct sockaddr_in addr = uv_ip4_addr("127.0.0.1", TEST_PORT); + uv_tcp_t h; + uv_tcp_init(uv_default_loop(), &h); + uv_tcp_connect(&connect_req, &h, addr, connect_and_shutdown); + uv_unref((uv_handle_t*)&h); + uv_run(uv_default_loop()); + ASSERT(connect_cb_called == 1); + ASSERT(shutdown_cb_called == 1); + return 0; +} + + +TEST_IMPL(tcp_ref4) { + struct sockaddr_in addr = uv_ip4_addr("127.0.0.1", TEST_PORT); + uv_tcp_t h; + uv_tcp_init(uv_default_loop(), &h); + uv_tcp_connect(&connect_req, &h, addr, connect_and_write); + uv_unref((uv_handle_t*)&h); + uv_run(uv_default_loop()); + ASSERT(connect_cb_called == 1); + ASSERT(write_cb_called == 1); + ASSERT(shutdown_cb_called == 1); + return 0; +} + + +TEST_IMPL(udp_ref) { + uv_udp_t h; + uv_udp_init(uv_default_loop(), &h); + uv_unref((uv_handle_t*)&h); + uv_run(uv_default_loop()); + return 0; +} + + +TEST_IMPL(udp_ref2) { + struct sockaddr_in addr = uv_ip4_addr("127.0.0.1", TEST_PORT); + uv_udp_t h; + uv_udp_init(uv_default_loop(), &h); + uv_udp_bind(&h, addr, 0); + uv_udp_recv_start(&h, (uv_alloc_cb)fail_cb, (uv_udp_recv_cb)fail_cb); + uv_unref((uv_handle_t*)&h); + uv_run(uv_default_loop()); + return 0; +} + + +TEST_IMPL(udp_ref3) { + struct sockaddr_in addr = uv_ip4_addr("127.0.0.1", TEST_PORT); + uv_buf_t buf = uv_buf_init("PING", 4); + uv_udp_send_t req; + uv_udp_t h; + + uv_udp_init(uv_default_loop(), &h); + uv_udp_send(&req, &h, &buf, 1, addr, (uv_udp_send_cb)req_cb); + uv_unref((uv_handle_t*)&h); + uv_run(uv_default_loop()); + ASSERT(req_cb_called == 1); + + return 0; +} + + +TEST_IMPL(pipe_ref) { + uv_pipe_t h; + uv_pipe_init(uv_default_loop(), &h, 0); + uv_unref((uv_handle_t*)&h); + uv_run(uv_default_loop()); + return 0; +} + + +TEST_IMPL(pipe_ref2) { + uv_pipe_t h; + uv_pipe_init(uv_default_loop(), &h, 0); + uv_listen((uv_stream_t*)&h, 128, (uv_connection_cb)fail_cb); + uv_unref((uv_handle_t*)&h); + uv_run(uv_default_loop()); + return 0; +} + + +TEST_IMPL(pipe_ref3) { + uv_pipe_t h; + uv_pipe_init(uv_default_loop(), &h, 0); + uv_pipe_connect(&connect_req, &h, TEST_PIPENAME, connect_and_shutdown); + uv_unref((uv_handle_t*)&h); + uv_run(uv_default_loop()); + ASSERT(connect_cb_called == 1); + ASSERT(shutdown_cb_called == 1); + return 0; +} + + +TEST_IMPL(pipe_ref4) { + uv_pipe_t h; + uv_pipe_init(uv_default_loop(), &h, 0); + uv_pipe_connect(&connect_req, &h, TEST_PIPENAME, connect_and_write); + uv_unref((uv_handle_t*)&h); + uv_run(uv_default_loop()); + ASSERT(connect_cb_called == 1); + ASSERT(write_cb_called == 1); + ASSERT(shutdown_cb_called == 1); + return 0; +} + + +TEST_IMPL(process_ref) { + /* spawn_helper4 blocks indefinitely. */ + char *argv[] = { NULL, "spawn_helper4", NULL }; + uv_process_options_t options; + size_t exepath_size; + char exepath[256]; + uv_process_t h; + int r; + + memset(&options, 0, sizeof(options)); + exepath_size = sizeof(exepath); + + r = uv_exepath(exepath, &exepath_size); + ASSERT(r == 0); + + argv[0] = exepath; + options.file = exepath; + options.args = argv; + options.exit_cb = NULL; + + r = uv_spawn(uv_default_loop(), &h, options); + ASSERT(r == 0); + + uv_unref((uv_handle_t*)&h); + uv_run(uv_default_loop()); + + r = uv_process_kill(&h, /* SIGTERM */ 15); + ASSERT(r == 0); + + return 0; +} diff --git a/node-v0.8.14/deps/uv/test/test-run-once.c b/node-v0.8.14/deps/uv/test/test-run-once.c new file mode 100644 index 0000000..f74e9f3 --- /dev/null +++ b/node-v0.8.14/deps/uv/test/test-run-once.c @@ -0,0 +1,48 @@ +/* Copyright Joyent, Inc. and other Node contributors. All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ + +#include "uv.h" +#include "task.h" + +#define NUM_TICKS 64 + +static uv_idle_t idle_handle; +static int idle_counter; + + +static void idle_cb(uv_idle_t* handle, int status) { + ASSERT(handle == &idle_handle); + ASSERT(status == 0); + + if (++idle_counter == NUM_TICKS) + uv_idle_stop(handle); +} + + +TEST_IMPL(run_once) { + uv_idle_init(uv_default_loop(), &idle_handle); + uv_idle_start(&idle_handle, idle_cb); + + while (uv_run_once(uv_default_loop())); + ASSERT(idle_counter == NUM_TICKS); + + return 0; +} diff --git a/node-v0.8.14/deps/uv/test/test-semaphore.c b/node-v0.8.14/deps/uv/test/test-semaphore.c new file mode 100644 index 0000000..ee89d4f --- /dev/null +++ b/node-v0.8.14/deps/uv/test/test-semaphore.c @@ -0,0 +1,111 @@ +/* Copyright Joyent, Inc. and other Node contributors. All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ + +#include "uv.h" +#include "task.h" + +#include +#include + +typedef struct { + uv_mutex_t mutex; + uv_sem_t sem; + int delay; + volatile int posted; +} worker_config; + + +static void worker(void* arg) { + worker_config* c = arg; + + if (c->delay) + uv_sleep(c->delay); + + uv_mutex_lock(&c->mutex); + ASSERT(c->posted == 0); + uv_sem_post(&c->sem); + c->posted = 1; + uv_mutex_unlock(&c->mutex); +} + + +TEST_IMPL(semaphore_1) { + uv_thread_t thread; + worker_config wc; + + memset(&wc, 0, sizeof(wc)); + + ASSERT(0 == uv_sem_init(&wc.sem, 0)); + ASSERT(0 == uv_mutex_init(&wc.mutex)); + ASSERT(0 == uv_thread_create(&thread, worker, &wc)); + + uv_sleep(100); + uv_mutex_lock(&wc.mutex); + ASSERT(wc.posted == 1); + uv_sem_wait(&wc.sem); /* should not block */ + uv_mutex_unlock(&wc.mutex); /* ergo, it should be ok to unlock after wait */ + + ASSERT(0 == uv_thread_join(&thread)); + uv_mutex_destroy(&wc.mutex); + uv_sem_destroy(&wc.sem); + + return 0; +} + + +TEST_IMPL(semaphore_2) { + uv_thread_t thread; + worker_config wc; + + memset(&wc, 0, sizeof(wc)); + wc.delay = 100; + + ASSERT(0 == uv_sem_init(&wc.sem, 0)); + ASSERT(0 == uv_mutex_init(&wc.mutex)); + ASSERT(0 == uv_thread_create(&thread, worker, &wc)); + + uv_sem_wait(&wc.sem); + + ASSERT(0 == uv_thread_join(&thread)); + uv_mutex_destroy(&wc.mutex); + uv_sem_destroy(&wc.sem); + + return 0; +} + + +TEST_IMPL(semaphore_3) { + uv_sem_t sem; + + ASSERT(0 == uv_sem_init(&sem, 3)); + uv_sem_wait(&sem); /* should not block */ + uv_sem_wait(&sem); /* should not block */ + ASSERT(0 == uv_sem_trywait(&sem)); + ASSERT(-1 == uv_sem_trywait(&sem)); + + uv_sem_post(&sem); + ASSERT(0 == uv_sem_trywait(&sem)); + ASSERT(-1 == uv_sem_trywait(&sem)); + + uv_sem_destroy(&sem); + + return 0; +} diff --git a/node-v0.8.14/deps/uv/test/test-shutdown-close.c b/node-v0.8.14/deps/uv/test/test-shutdown-close.c new file mode 100644 index 0000000..eabbefc --- /dev/null +++ b/node-v0.8.14/deps/uv/test/test-shutdown-close.c @@ -0,0 +1,103 @@ +/* Copyright Joyent, Inc. and other Node contributors. All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ + +/* + * These tests verify that the uv_shutdown callback is always made, even when + * it is immediately followed by an uv_close call. + */ + +#include "uv.h" +#include "task.h" + + +static uv_shutdown_t shutdown_req; +static uv_connect_t connect_req; + +static int connect_cb_called = 0; +static int shutdown_cb_called = 0; +static int close_cb_called = 0; + + +static void shutdown_cb(uv_shutdown_t* req, int status) { + ASSERT(req == &shutdown_req); + ASSERT(status == 0 || + (status == -1 && uv_last_error(uv_default_loop()).code == UV_EINTR)); + shutdown_cb_called++; +} + + +static void close_cb(uv_handle_t* handle) { + close_cb_called++; +} + + +static void connect_cb(uv_connect_t* req, int status) { + int r; + + ASSERT(req == &connect_req); + ASSERT(status == 0); + + r = uv_shutdown(&shutdown_req, req->handle, shutdown_cb); + ASSERT(r == 0); + ASSERT(!uv_is_closing((uv_handle_t*) req->handle)); + uv_close((uv_handle_t*) req->handle, close_cb); + ASSERT(uv_is_closing((uv_handle_t*) req->handle)); + + connect_cb_called++; +} + + +TEST_IMPL(shutdown_close_tcp) { + struct sockaddr_in addr = uv_ip4_addr("127.0.0.1", TEST_PORT); + uv_tcp_t h; + int r; + + r = uv_tcp_init(uv_default_loop(), &h); + ASSERT(r == 0); + r = uv_tcp_connect(&connect_req, &h, addr, connect_cb); + ASSERT(r == 0); + r = uv_run(uv_default_loop()); + ASSERT(r == 0); + + ASSERT(connect_cb_called == 1); + ASSERT(shutdown_cb_called == 1); + ASSERT(close_cb_called == 1); + + return 0; +} + + +TEST_IMPL(shutdown_close_pipe) { + uv_pipe_t h; + int r; + + r = uv_pipe_init(uv_default_loop(), &h, 0); + ASSERT(r == 0); + uv_pipe_connect(&connect_req, &h, TEST_PIPENAME, connect_cb); + r = uv_run(uv_default_loop()); + ASSERT(r == 0); + + ASSERT(connect_cb_called == 1); + ASSERT(shutdown_cb_called == 1); + ASSERT(close_cb_called == 1); + + return 0; +} diff --git a/node-v0.8.14/deps/uv/test/test-shutdown-eof.c b/node-v0.8.14/deps/uv/test/test-shutdown-eof.c new file mode 100644 index 0000000..9d4f2cc --- /dev/null +++ b/node-v0.8.14/deps/uv/test/test-shutdown-eof.c @@ -0,0 +1,183 @@ +/* Copyright Joyent, Inc. and other Node contributors. All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ + +#include "uv.h" +#include "task.h" +#include +#include + +static uv_timer_t timer; +static uv_tcp_t tcp; +static uv_connect_t connect_req; +static uv_write_t write_req; +static uv_shutdown_t shutdown_req; +static uv_buf_t qbuf; +static int got_q; +static int got_eof; +static int called_connect_cb; +static int called_shutdown_cb; +static int called_tcp_close_cb; +static int called_timer_close_cb; +static int called_timer_cb; + + +static uv_buf_t alloc_cb(uv_handle_t* handle, size_t size) { + uv_buf_t buf; + buf.base = (char*)malloc(size); + buf.len = size; + return buf; +} + + +static void read_cb(uv_stream_t* t, ssize_t nread, uv_buf_t buf) { + uv_err_t err = uv_last_error(uv_default_loop()); + + ASSERT((uv_tcp_t*)t == &tcp); + + if (nread == 0) { + ASSERT(err.code == UV_EAGAIN); + free(buf.base); + return; + } + + if (!got_q) { + ASSERT(nread == 1); + ASSERT(!got_eof); + ASSERT(buf.base[0] == 'Q'); + free(buf.base); + got_q = 1; + puts("got Q"); + } else { + ASSERT(err.code == UV_EOF); + if (buf.base) { + free(buf.base); + } + got_eof = 1; + puts("got EOF"); + } +} + + +static void shutdown_cb(uv_shutdown_t *req, int status) { + ASSERT(req == &shutdown_req); + + ASSERT(called_connect_cb == 1); + ASSERT(!got_eof); + ASSERT(called_tcp_close_cb == 0); + ASSERT(called_timer_close_cb == 0); + ASSERT(called_timer_cb == 0); + + called_shutdown_cb++; +} + + +static void connect_cb(uv_connect_t *req, int status) { + ASSERT(status == 0); + ASSERT(req == &connect_req); + + /* Start reading from our connection so we can receive the EOF. */ + uv_read_start((uv_stream_t*)&tcp, alloc_cb, read_cb); + + /* + * Write the letter 'Q' to gracefully kill the echo-server. This will not + * effect our connection. + */ + uv_write(&write_req, (uv_stream_t*) &tcp, &qbuf, 1, NULL); + + /* Shutdown our end of the connection. */ + uv_shutdown(&shutdown_req, (uv_stream_t*) &tcp, shutdown_cb); + + called_connect_cb++; + ASSERT(called_shutdown_cb == 0); +} + + +void tcp_close_cb(uv_handle_t* handle) { + ASSERT(handle == (uv_handle_t*) &tcp); + + ASSERT(called_connect_cb == 1); + ASSERT(got_q); + ASSERT(got_eof); + ASSERT(called_timer_cb == 1); + + called_tcp_close_cb++; +} + + +void timer_close_cb(uv_handle_t* handle) { + ASSERT(handle == (uv_handle_t*) &timer); + called_timer_close_cb++; +} + + +void timer_cb(uv_timer_t* handle, int status) { + ASSERT(handle == &timer); + uv_close((uv_handle_t*) handle, timer_close_cb); + + /* + * The most important assert of the test: we have not received + * tcp_close_cb yet. + */ + ASSERT(called_tcp_close_cb == 0); + uv_close((uv_handle_t*) &tcp, tcp_close_cb); + + called_timer_cb++; +} + + +/* + * This test has a client which connects to the echo_server and immediately + * issues a shutdown. The echo-server, in response, will also shutdown their + * connection. We check, with a timer, that libuv is not automatically + * calling uv_close when the client receives the EOF from echo-server. + */ +TEST_IMPL(shutdown_eof) { + struct sockaddr_in server_addr; + int r; + + qbuf.base = "Q"; + qbuf.len = 1; + + r = uv_timer_init(uv_default_loop(), &timer); + ASSERT(r == 0); + + uv_timer_start(&timer, timer_cb, 100, 0); + + server_addr = uv_ip4_addr("127.0.0.1", TEST_PORT); + r = uv_tcp_init(uv_default_loop(), &tcp); + ASSERT(!r); + + r = uv_tcp_connect(&connect_req, &tcp, server_addr, connect_cb); + ASSERT(!r); + + uv_run(uv_default_loop()); + + ASSERT(called_connect_cb == 1); + ASSERT(called_shutdown_cb == 1); + ASSERT(got_eof); + ASSERT(got_q); + ASSERT(called_tcp_close_cb == 1); + ASSERT(called_timer_close_cb == 1); + ASSERT(called_timer_cb == 1); + + return 0; +} + diff --git a/node-v0.8.14/deps/uv/test/test-spawn.c b/node-v0.8.14/deps/uv/test/test-spawn.c new file mode 100644 index 0000000..51ed2e5 --- /dev/null +++ b/node-v0.8.14/deps/uv/test/test-spawn.c @@ -0,0 +1,847 @@ +/* Copyright Joyent, Inc. and other Node contributors. All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ + +#include "uv.h" +#include "task.h" +#include +#include +#include +#include + +#ifndef _WIN32 +#include +#endif + + +static int close_cb_called; +static int exit_cb_called; +static uv_process_t process; +static uv_timer_t timer; +static uv_process_options_t options; +static char exepath[1024]; +static size_t exepath_size = 1024; +static char* args[3]; +static int no_term_signal; + +#define OUTPUT_SIZE 1024 +static char output[OUTPUT_SIZE]; +static int output_used; + + +static void close_cb(uv_handle_t* handle) { + printf("close_cb\n"); + close_cb_called++; +} + + +static void exit_cb(uv_process_t* process, int exit_status, int term_signal) { + printf("exit_cb\n"); + exit_cb_called++; + ASSERT(exit_status == 1); + ASSERT(term_signal == 0); + uv_close((uv_handle_t*)process, close_cb); +} + + +static void exit_cb_failure_expected(uv_process_t* process, int exit_status, + int term_signal) { + printf("exit_cb\n"); + exit_cb_called++; + ASSERT(exit_status == 127); + ASSERT(term_signal == 0); + uv_close((uv_handle_t*)process, close_cb); +} + + +static void exit_cb_unexpected(uv_process_t* process, int exit_status, + int term_signal) { + ASSERT(0 && "should not have been called"); +} + + +static void kill_cb(uv_process_t* process, int exit_status, int term_signal) { + uv_err_t err; + + printf("exit_cb\n"); + exit_cb_called++; +#ifdef _WIN32 + ASSERT(exit_status == 1); +#else + ASSERT(exit_status == 0); +#endif + ASSERT(no_term_signal || term_signal == 15); + uv_close((uv_handle_t*)process, close_cb); + + /* + * Sending signum == 0 should check if the + * child process is still alive, not kill it. + * This process should be dead. + */ + err = uv_kill(process->pid, 0); + ASSERT(err.code == UV_ESRCH); +} + +static void detach_failure_cb(uv_process_t* process, int exit_status, int term_signal) { + printf("detach_cb\n"); + exit_cb_called++; +} + +static uv_buf_t on_alloc(uv_handle_t* handle, size_t suggested_size) { + uv_buf_t buf; + buf.base = output + output_used; + buf.len = OUTPUT_SIZE - output_used; + return buf; +} + + +void on_read(uv_stream_t* tcp, ssize_t nread, uv_buf_t buf) { + uv_err_t err = uv_last_error(uv_default_loop()); + + if (nread > 0) { + output_used += nread; + } else if (nread < 0) { + ASSERT(err.code == UV_EOF); + uv_close((uv_handle_t*)tcp, close_cb); + } +} + + +void write_cb(uv_write_t* req, int status) { + ASSERT(status == 0); + uv_close((uv_handle_t*)req->handle, close_cb); +} + + +static void init_process_options(char* test, uv_exit_cb exit_cb) { + /* Note spawn_helper1 defined in test/run-tests.c */ + int r = uv_exepath(exepath, &exepath_size); + ASSERT(r == 0); + exepath[exepath_size] = '\0'; + args[0] = exepath; + args[1] = test; + args[2] = NULL; + options.file = exepath; + options.args = args; + options.exit_cb = exit_cb; + options.flags = 0; +} + + +static void timer_cb(uv_timer_t* handle, int status) { + uv_process_kill(&process, /* SIGTERM */ 15); + uv_close((uv_handle_t*)handle, close_cb); +} + + +TEST_IMPL(spawn_exit_code) { + int r; + + init_process_options("spawn_helper1", exit_cb); + + r = uv_spawn(uv_default_loop(), &process, options); + ASSERT(r == 0); + + r = uv_run(uv_default_loop()); + ASSERT(r == 0); + + ASSERT(exit_cb_called == 1); + ASSERT(close_cb_called == 1); + + return 0; +} + + +TEST_IMPL(spawn_stdout) { + int r; + uv_pipe_t out; + uv_stdio_container_t stdio[2]; + + init_process_options("spawn_helper2", exit_cb); + + uv_pipe_init(uv_default_loop(), &out, 0); + options.stdio = stdio; + options.stdio[0].flags = UV_IGNORE; + options.stdio[1].flags = UV_CREATE_PIPE | UV_WRITABLE_PIPE; + options.stdio[1].data.stream = (uv_stream_t*)&out; + options.stdio_count = 2; + + r = uv_spawn(uv_default_loop(), &process, options); + ASSERT(r == 0); + + r = uv_read_start((uv_stream_t*) &out, on_alloc, on_read); + ASSERT(r == 0); + + r = uv_run(uv_default_loop()); + ASSERT(r == 0); + + ASSERT(exit_cb_called == 1); + ASSERT(close_cb_called == 2); /* Once for process once for the pipe. */ + printf("output is: %s", output); + ASSERT(strcmp("hello world\n", output) == 0); + + return 0; +} + + +TEST_IMPL(spawn_stdout_to_file) { + int r; + uv_file file; + uv_fs_t fs_req; + uv_stdio_container_t stdio[2]; + + /* Setup. */ + unlink("stdout_file"); + + init_process_options("spawn_helper2", exit_cb); + + r = uv_fs_open(uv_default_loop(), &fs_req, "stdout_file", O_CREAT | O_RDWR, + S_IREAD | S_IWRITE, NULL); + ASSERT(r != -1); + uv_fs_req_cleanup(&fs_req); + + file = r; + + options.stdio = stdio; + options.stdio[0].flags = UV_IGNORE; + options.stdio[1].flags = UV_INHERIT_FD; + options.stdio[1].data.fd = file; + options.stdio_count = 2; + + r = uv_spawn(uv_default_loop(), &process, options); + ASSERT(r == 0); + + r = uv_run(uv_default_loop()); + ASSERT(r == 0); + + ASSERT(exit_cb_called == 1); + ASSERT(close_cb_called == 1); + + r = uv_fs_read(uv_default_loop(), &fs_req, file, output, sizeof(output), + 0, NULL); + ASSERT(r == 12); + uv_fs_req_cleanup(&fs_req); + + r = uv_fs_close(uv_default_loop(), &fs_req, file, NULL); + ASSERT(r == 0); + uv_fs_req_cleanup(&fs_req); + + printf("output is: %s", output); + ASSERT(strcmp("hello world\n", output) == 0); + + /* Cleanup. */ + unlink("stdout_file"); + + return 0; +} + + +TEST_IMPL(spawn_stdin) { + int r; + uv_pipe_t out; + uv_pipe_t in; + uv_write_t write_req; + uv_buf_t buf; + uv_stdio_container_t stdio[2]; + char buffer[] = "hello-from-spawn_stdin"; + + init_process_options("spawn_helper3", exit_cb); + + uv_pipe_init(uv_default_loop(), &out, 0); + uv_pipe_init(uv_default_loop(), &in, 0); + options.stdio = stdio; + options.stdio[0].flags = UV_CREATE_PIPE | UV_READABLE_PIPE; + options.stdio[0].data.stream = (uv_stream_t*)∈ + options.stdio[1].flags = UV_CREATE_PIPE | UV_WRITABLE_PIPE; + options.stdio[1].data.stream = (uv_stream_t*)&out; + options.stdio_count = 2; + + r = uv_spawn(uv_default_loop(), &process, options); + ASSERT(r == 0); + + buf.base = buffer; + buf.len = sizeof(buffer); + r = uv_write(&write_req, (uv_stream_t*)&in, &buf, 1, write_cb); + ASSERT(r == 0); + + r = uv_read_start((uv_stream_t*) &out, on_alloc, on_read); + ASSERT(r == 0); + + r = uv_run(uv_default_loop()); + ASSERT(r == 0); + + ASSERT(exit_cb_called == 1); + ASSERT(close_cb_called == 3); /* Once for process twice for the pipe. */ + ASSERT(strcmp(buffer, output) == 0); + + return 0; +} + + +TEST_IMPL(spawn_stdio_greater_than_3) { + int r; + uv_pipe_t pipe; + uv_stdio_container_t stdio[4]; + + init_process_options("spawn_helper5", exit_cb); + + uv_pipe_init(uv_default_loop(), &pipe, 0); + options.stdio = stdio; + options.stdio[0].flags = UV_IGNORE; + options.stdio[1].flags = UV_IGNORE; + options.stdio[2].flags = UV_IGNORE; + options.stdio[3].flags = UV_CREATE_PIPE | UV_WRITABLE_PIPE; + options.stdio[3].data.stream = (uv_stream_t*)&pipe; + options.stdio_count = 4; + + r = uv_spawn(uv_default_loop(), &process, options); + ASSERT(r == 0); + + r = uv_read_start((uv_stream_t*) &pipe, on_alloc, on_read); + ASSERT(r == 0); + + r = uv_run(uv_default_loop()); + ASSERT(r == 0); + + ASSERT(exit_cb_called == 1); + ASSERT(close_cb_called == 2); /* Once for process once for the pipe. */ + printf("output from stdio[3] is: %s", output); + ASSERT(strcmp("fourth stdio!\n", output) == 0); + + return 0; +} + + +TEST_IMPL(spawn_ignored_stdio) { + int r; + + init_process_options("spawn_helper6", exit_cb); + + options.stdio = NULL; + options.stdio_count = 0; + + r = uv_spawn(uv_default_loop(), &process, options); + ASSERT(r == 0); + + r = uv_run(uv_default_loop()); + ASSERT(r == 0); + + ASSERT(exit_cb_called == 1); + ASSERT(close_cb_called == 1); + + return 0; +} + + +TEST_IMPL(spawn_and_kill) { + int r; + + init_process_options("spawn_helper4", kill_cb); + + r = uv_spawn(uv_default_loop(), &process, options); + ASSERT(r == 0); + + r = uv_timer_init(uv_default_loop(), &timer); + ASSERT(r == 0); + + r = uv_timer_start(&timer, timer_cb, 500, 0); + ASSERT(r == 0); + + r = uv_run(uv_default_loop()); + ASSERT(r == 0); + + ASSERT(exit_cb_called == 1); + ASSERT(close_cb_called == 2); /* Once for process and once for timer. */ + + return 0; +} + +TEST_IMPL(spawn_detached) { + int r; + uv_err_t err; + + init_process_options("spawn_helper4", detach_failure_cb); + + options.flags |= UV_PROCESS_DETACHED; + + r = uv_spawn(uv_default_loop(), &process, options); + ASSERT(r == 0); + + uv_unref((uv_handle_t*)&process); + + r = uv_run(uv_default_loop()); + ASSERT(r == 0); + + ASSERT(exit_cb_called == 0); + + err = uv_kill(process.pid, 0); + ASSERT(err.code == 0); + + err = uv_kill(process.pid, 15); + ASSERT(err.code == 0); + + return 0; +} + +TEST_IMPL(spawn_and_kill_with_std) { + int r; + uv_pipe_t in, out, err; + uv_write_t write; + char message[] = "Nancy's joining me because the message this evening is " + "not my message but ours."; + uv_buf_t buf; + uv_stdio_container_t stdio[3]; + + init_process_options("spawn_helper4", kill_cb); + + r = uv_pipe_init(uv_default_loop(), &in, 0); + ASSERT(r == 0); + + r = uv_pipe_init(uv_default_loop(), &out, 0); + ASSERT(r == 0); + + r = uv_pipe_init(uv_default_loop(), &err, 0); + ASSERT(r == 0); + + options.stdio = stdio; + options.stdio[0].flags = UV_CREATE_PIPE | UV_READABLE_PIPE; + options.stdio[0].data.stream = (uv_stream_t*)∈ + options.stdio[1].flags = UV_CREATE_PIPE | UV_WRITABLE_PIPE; + options.stdio[1].data.stream = (uv_stream_t*)&out; + options.stdio[2].flags = UV_CREATE_PIPE | UV_WRITABLE_PIPE; + options.stdio[2].data.stream = (uv_stream_t*)&err; + options.stdio_count = 3; + + r = uv_spawn(uv_default_loop(), &process, options); + ASSERT(r == 0); + + buf = uv_buf_init(message, sizeof message); + r = uv_write(&write, (uv_stream_t*) &in, &buf, 1, write_cb); + ASSERT(r == 0); + + r = uv_read_start((uv_stream_t*) &out, on_alloc, on_read); + ASSERT(r == 0); + + r = uv_read_start((uv_stream_t*) &err, on_alloc, on_read); + ASSERT(r == 0); + + r = uv_timer_init(uv_default_loop(), &timer); + ASSERT(r == 0); + + r = uv_timer_start(&timer, timer_cb, 500, 0); + ASSERT(r == 0); + + r = uv_run(uv_default_loop()); + ASSERT(r == 0); + + ASSERT(exit_cb_called == 1); + ASSERT(close_cb_called == 5); /* process x 1, timer x 1, stdio x 3. */ + + return 0; +} + + +TEST_IMPL(spawn_and_ping) { + uv_write_t write_req; + uv_pipe_t in, out; + uv_buf_t buf; + uv_stdio_container_t stdio[2]; + int r; + + init_process_options("spawn_helper3", exit_cb); + buf = uv_buf_init("TEST", 4); + + uv_pipe_init(uv_default_loop(), &out, 0); + uv_pipe_init(uv_default_loop(), &in, 0); + options.stdio = stdio; + options.stdio[0].flags = UV_CREATE_PIPE | UV_READABLE_PIPE; + options.stdio[0].data.stream = (uv_stream_t*)∈ + options.stdio[1].flags = UV_CREATE_PIPE | UV_WRITABLE_PIPE; + options.stdio[1].data.stream = (uv_stream_t*)&out; + options.stdio_count = 2; + + r = uv_spawn(uv_default_loop(), &process, options); + ASSERT(r == 0); + + /* Sending signum == 0 should check if the + * child process is still alive, not kill it. + */ + r = uv_process_kill(&process, 0); + ASSERT(r == 0); + + r = uv_write(&write_req, (uv_stream_t*)&in, &buf, 1, write_cb); + ASSERT(r == 0); + + r = uv_read_start((uv_stream_t*)&out, on_alloc, on_read); + ASSERT(r == 0); + + ASSERT(exit_cb_called == 0); + + r = uv_run(uv_default_loop()); + ASSERT(r == 0); + + ASSERT(exit_cb_called == 1); + ASSERT(strcmp(output, "TEST") == 0); + + return 0; +} + + +TEST_IMPL(kill) { + int r; + uv_err_t err; + +#ifdef _WIN32 + no_term_signal = 1; +#endif + + init_process_options("spawn_helper4", kill_cb); + + r = uv_spawn(uv_default_loop(), &process, options); + ASSERT(r == 0); + + /* Sending signum == 0 should check if the + * child process is still alive, not kill it. + */ + err = uv_kill(process.pid, 0); + ASSERT(err.code == UV_OK); + + /* Kill the process. */ + err = uv_kill(process.pid, /* SIGTERM */ 15); + ASSERT(err.code == UV_OK); + + r = uv_run(uv_default_loop()); + ASSERT(r == 0); + + ASSERT(exit_cb_called == 1); + ASSERT(close_cb_called == 1); + + return 0; +} + + +#ifdef _WIN32 +TEST_IMPL(spawn_detect_pipe_name_collisions_on_windows) { + int r; + uv_pipe_t out; + char name[64]; + HANDLE pipe_handle; + uv_stdio_container_t stdio[2]; + + init_process_options("spawn_helper2", exit_cb); + + uv_pipe_init(uv_default_loop(), &out, 0); + options.stdio = stdio; + options.stdio[0].flags = UV_IGNORE; + options.stdio[1].flags = UV_CREATE_PIPE | UV_WRITABLE_PIPE; + options.stdio[1].data.stream = (uv_stream_t*)&out; + options.stdio_count = 2; + + /* Create a pipe that'll cause a collision. */ + _snprintf(name, sizeof(name), "\\\\.\\pipe\\uv\\%p-%d", &out, GetCurrentProcessId()); + pipe_handle = CreateNamedPipeA(name, + PIPE_ACCESS_INBOUND | FILE_FLAG_OVERLAPPED, + PIPE_TYPE_BYTE | PIPE_READMODE_BYTE | PIPE_WAIT, + 10, + 65536, + 65536, + 0, + NULL); + ASSERT(pipe_handle != INVALID_HANDLE_VALUE); + + r = uv_spawn(uv_default_loop(), &process, options); + ASSERT(r == 0); + + r = uv_read_start((uv_stream_t*) &out, on_alloc, on_read); + ASSERT(r == 0); + + r = uv_run(uv_default_loop()); + ASSERT(r == 0); + + ASSERT(exit_cb_called == 1); + ASSERT(close_cb_called == 2); /* Once for process once for the pipe. */ + printf("output is: %s", output); + ASSERT(strcmp("hello world\n", output) == 0); + + return 0; +} + + +wchar_t* make_program_args(char** args, int verbatim_arguments); +wchar_t* quote_cmd_arg(const wchar_t *source, wchar_t *target); + +TEST_IMPL(argument_escaping) { + const wchar_t* test_str[] = { + L"HelloWorld", + L"Hello World", + L"Hello\"World", + L"Hello World\\", + L"Hello\\\"World", + L"Hello\\World", + L"Hello\\\\World", + L"Hello World\\", + L"c:\\path\\to\\node.exe --eval \"require('c:\\\\path\\\\to\\\\test.js')\"" + }; + const int count = sizeof(test_str) / sizeof(*test_str); + wchar_t** test_output; + wchar_t* command_line; + wchar_t** cracked; + size_t total_size = 0; + int i; + int num_args; + + char* verbatim[] = { + "cmd.exe", + "/c", + "c:\\path\\to\\node.exe --eval \"require('c:\\\\path\\\\to\\\\test.js')\"", + NULL + }; + wchar_t* verbatim_output; + wchar_t* non_verbatim_output; + + test_output = calloc(count, sizeof(wchar_t*)); + for (i = 0; i < count; ++i) { + test_output[i] = calloc(2 * (wcslen(test_str[i]) + 2), sizeof(wchar_t)); + quote_cmd_arg(test_str[i], test_output[i]); + wprintf(L"input : %s\n", test_str[i]); + wprintf(L"output: %s\n", test_output[i]); + total_size += wcslen(test_output[i]) + 1; + } + command_line = calloc(total_size + 1, sizeof(wchar_t)); + for (i = 0; i < count; ++i) { + wcscat(command_line, test_output[i]); + wcscat(command_line, L" "); + } + command_line[total_size - 1] = L'\0'; + + wprintf(L"command_line: %s\n", command_line); + + cracked = CommandLineToArgvW(command_line, &num_args); + for (i = 0; i < num_args; ++i) { + wprintf(L"%d: %s\t%s\n", i, test_str[i], cracked[i]); + ASSERT(wcscmp(test_str[i], cracked[i]) == 0); + } + + LocalFree(cracked); + for (i = 0; i < count; ++i) { + free(test_output[i]); + } + + verbatim_output = make_program_args(verbatim, 1); + non_verbatim_output = make_program_args(verbatim, 0); + + wprintf(L" verbatim_output: %s\n", verbatim_output); + wprintf(L"non_verbatim_output: %s\n", non_verbatim_output); + + ASSERT(wcscmp(verbatim_output, L"cmd.exe /c c:\\path\\to\\node.exe --eval \"require('c:\\\\path\\\\to\\\\test.js')\"") == 0); + ASSERT(wcscmp(non_verbatim_output, L"cmd.exe /c \"c:\\path\\to\\node.exe --eval \\\"require('c:\\\\path\\\\to\\\\test.js')\\\"\"") == 0); + + free(verbatim_output); + free(non_verbatim_output); + + return 0; +} + +wchar_t* make_program_env(char** env_block); + +TEST_IMPL(environment_creation) { + int i; + char* environment[] = { + "FOO=BAR", + "SYSTEM=ROOT", /* substring of a supplied var name */ + "SYSTEMROOTED=OMG", /* supplied var name is a substring */ + "TEMP=C:\\Temp", + "BAZ=QUX", + NULL + }; + + wchar_t expected[512]; + wchar_t* ptr = expected; + wchar_t* result; + wchar_t* str; + + for (i = 0; i < sizeof(environment) / sizeof(environment[0]) - 1; i++) { + ptr += uv_utf8_to_utf16(environment[i], ptr, expected + sizeof(expected) - ptr); + } + + memcpy(ptr, L"SYSTEMROOT=", sizeof(L"SYSTEMROOT=")); + ptr += sizeof(L"SYSTEMROOT=")/sizeof(wchar_t) - 1; + ptr += GetEnvironmentVariableW(L"SYSTEMROOT", ptr, expected + sizeof(expected) - ptr); + ++ptr; + + memcpy(ptr, L"SYSTEMDRIVE=", sizeof(L"SYSTEMDRIVE=")); + ptr += sizeof(L"SYSTEMDRIVE=")/sizeof(wchar_t) - 1; + ptr += GetEnvironmentVariableW(L"SYSTEMDRIVE", ptr, expected + sizeof(expected) - ptr); + ++ptr; + *ptr = '\0'; + + result = make_program_env(environment); + + for (str = result; *str; str += wcslen(str) + 1) { + wprintf(L"%s\n", str); + } + + ASSERT(wcscmp(expected, result) == 0); + + return 0; +} +#endif + +#ifndef _WIN32 +TEST_IMPL(spawn_setuid_setgid) { + int r; + + /* if not root, then this will fail. */ + uv_uid_t uid = getuid(); + if (uid != 0) { + fprintf(stderr, "spawn_setuid_setgid skipped: not root\n"); + return 0; + } + + init_process_options("spawn_helper1", exit_cb); + + /* become the "nobody" user. */ + struct passwd* pw; + pw = getpwnam("nobody"); + ASSERT(pw != NULL); + options.uid = pw->pw_uid; + options.gid = pw->pw_gid; + options.flags = UV_PROCESS_SETUID | UV_PROCESS_SETGID; + + r = uv_spawn(uv_default_loop(), &process, options); + ASSERT(r == 0); + + r = uv_run(uv_default_loop()); + ASSERT(r == 0); + + ASSERT(exit_cb_called == 1); + ASSERT(close_cb_called == 1); + + return 0; +} +#endif + + +#ifndef _WIN32 +TEST_IMPL(spawn_setuid_fails) { + int r; + + /* if root, become nobody. */ + uv_uid_t uid = getuid(); + if (uid == 0) { + struct passwd* pw; + pw = getpwnam("nobody"); + ASSERT(pw != NULL); + r = setuid(pw->pw_uid); + ASSERT(r == 0); + } + + init_process_options("spawn_helper1", exit_cb_failure_expected); + + options.flags |= UV_PROCESS_SETUID; + options.uid = (uv_uid_t) -42424242; + + r = uv_spawn(uv_default_loop(), &process, options); + ASSERT(r == 0); + + r = uv_run(uv_default_loop()); + ASSERT(r == 0); + + ASSERT(exit_cb_called == 1); + ASSERT(close_cb_called == 1); + + return 0; +} + + +TEST_IMPL(spawn_setgid_fails) { + int r; + + /* if root, become nobody. */ + uv_uid_t uid = getuid(); + if (uid == 0) { + struct passwd* pw; + pw = getpwnam("nobody"); + ASSERT(pw != NULL); + r = setuid(pw->pw_uid); + ASSERT(r == 0); + } + + init_process_options("spawn_helper1", exit_cb_failure_expected); + + options.flags |= UV_PROCESS_SETGID; + options.gid = (uv_gid_t) -42424242; + + r = uv_spawn(uv_default_loop(), &process, options); + ASSERT(r == 0); + + r = uv_run(uv_default_loop()); + ASSERT(r == 0); + + ASSERT(exit_cb_called == 1); + ASSERT(close_cb_called == 1); + + return 0; +} +#endif + + +#ifdef _WIN32 +TEST_IMPL(spawn_setuid_fails) { + int r; + + init_process_options("spawn_helper1", exit_cb_unexpected); + + options.flags |= UV_PROCESS_SETUID; + options.uid = (uv_uid_t) -42424242; + + r = uv_spawn(uv_default_loop(), &process, options); + ASSERT(r == -1); + ASSERT(uv_last_error(uv_default_loop()).code == UV_ENOTSUP); + + r = uv_run(uv_default_loop()); + ASSERT(r == 0); + + ASSERT(close_cb_called == 0); + + return 0; +} + + +TEST_IMPL(spawn_setgid_fails) { + int r; + + init_process_options("spawn_helper1", exit_cb_unexpected); + + options.flags |= UV_PROCESS_SETGID; + options.gid = (uv_gid_t) -42424242; + + r = uv_spawn(uv_default_loop(), &process, options); + ASSERT(r == -1); + ASSERT(uv_last_error(uv_default_loop()).code == UV_ENOTSUP); + + r = uv_run(uv_default_loop()); + ASSERT(r == 0); + + ASSERT(close_cb_called == 0); + + return 0; +} +#endif diff --git a/node-v0.8.14/deps/uv/test/test-stdio-over-pipes.c b/node-v0.8.14/deps/uv/test/test-stdio-over-pipes.c new file mode 100644 index 0000000..7603027 --- /dev/null +++ b/node-v0.8.14/deps/uv/test/test-stdio-over-pipes.c @@ -0,0 +1,246 @@ +/* Copyright Joyent, Inc. and other Node contributors. All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ + +#include "uv.h" +#include "task.h" + +#include +#include + + +static char exepath[1024]; +static size_t exepath_size = 1024; +static char* args[3]; +static uv_process_options_t options; +static int close_cb_called; +static int exit_cb_called; +static int on_read_cb_called; +static int after_write_cb_called; +uv_pipe_t out, in; +static uv_loop_t* loop; +#define OUTPUT_SIZE 1024 +static char output[OUTPUT_SIZE]; +static int output_used; + + +static void close_cb(uv_handle_t* handle) { + printf("close_cb\n"); + close_cb_called++; +} + + +static void exit_cb(uv_process_t* process, int exit_status, int term_signal) { + printf("exit_cb\n"); + exit_cb_called++; + ASSERT(exit_status == 0); + ASSERT(term_signal == 0); + uv_close((uv_handle_t*)process, close_cb); + uv_close((uv_handle_t*)&in, close_cb); + uv_close((uv_handle_t*)&out, close_cb); +} + + +static void init_process_options(char* test, uv_exit_cb exit_cb) { + int r = uv_exepath(exepath, &exepath_size); + ASSERT(r == 0); + exepath[exepath_size] = '\0'; + args[0] = exepath; + args[1] = test; + args[2] = NULL; + options.file = exepath; + options.args = args; + options.exit_cb = exit_cb; +} + + +static uv_buf_t on_alloc(uv_handle_t* handle, size_t suggested_size) { + return uv_buf_init(output + output_used, OUTPUT_SIZE - output_used); +} + + +static void after_write(uv_write_t* req, int status) { + if (status) { + uv_err_t err = uv_last_error(loop); + fprintf(stderr, "uv_write error: %s\n", uv_strerror(err)); + ASSERT(0); + } + + /* Free the read/write buffer and the request */ + free(req); + + after_write_cb_called++; +} + + +static void on_read(uv_stream_t* tcp, ssize_t nread, uv_buf_t rdbuf) { + uv_write_t* req; + uv_buf_t wrbuf; + int r; + + ASSERT(nread > 0 || uv_last_error(uv_default_loop()).code == UV_EOF); + + if (nread > 0) { + output_used += nread; + if (output_used == 12) { + ASSERT(memcmp("hello world\n", output, 12) == 0); + wrbuf = uv_buf_init(output, output_used); + req = malloc(sizeof(*req)); + r = uv_write(req, (uv_stream_t*)&in, &wrbuf, 1, after_write); + ASSERT(r == 0); + } + } + + on_read_cb_called++; +} + + +TEST_IMPL(stdio_over_pipes) { + int r; + uv_process_t process; + uv_stdio_container_t stdio[2]; + + loop = uv_default_loop(); + + init_process_options("stdio_over_pipes_helper", exit_cb); + + uv_pipe_init(loop, &out, 0); + uv_pipe_init(loop, &in, 0); + + options.stdio = stdio; + options.stdio[0].flags = UV_CREATE_PIPE | UV_READABLE_PIPE; + options.stdio[0].data.stream = (uv_stream_t*)∈ + options.stdio[1].flags = UV_CREATE_PIPE | UV_WRITABLE_PIPE; + options.stdio[1].data.stream = (uv_stream_t*)&out; + options.stdio_count = 2; + + r = uv_spawn(loop, &process, options); + ASSERT(r == 0); + + r = uv_read_start((uv_stream_t*) &out, on_alloc, on_read); + ASSERT(r == 0); + + r = uv_run(uv_default_loop()); + ASSERT(r == 0); + + ASSERT(on_read_cb_called > 1); + ASSERT(after_write_cb_called == 1); + ASSERT(exit_cb_called == 1); + ASSERT(close_cb_called == 3); + ASSERT(memcmp("hello world\n", output, 12) == 0); + ASSERT(output_used == 12); + + return 0; +} + + +/* Everything here runs in a child process. */ + +static int on_pipe_read_called; +static int after_write_called; +static uv_pipe_t stdin_pipe; +static uv_pipe_t stdout_pipe; + +static void on_pipe_read(uv_stream_t* tcp, ssize_t nread, uv_buf_t buf) { + ASSERT(nread > 0); + ASSERT(memcmp("hello world\n", buf.base, nread) == 0); + on_pipe_read_called++; + + free(buf.base); + + uv_close((uv_handle_t*)&stdin_pipe, close_cb); + uv_close((uv_handle_t*)&stdout_pipe, close_cb); +} + + +static void after_pipe_write(uv_write_t* req, int status) { + ASSERT(status == 0); + after_write_called++; +} + + +static uv_buf_t on_read_alloc(uv_handle_t* handle, size_t suggested_size) { + return uv_buf_init(malloc(suggested_size), suggested_size); +} + + +int stdio_over_pipes_helper() { + /* Write several buffers to test that the write order is preserved. */ + char* buffers[] = { + "he", + "ll", + "o ", + "wo", + "rl", + "d", + "\n" + }; + + uv_write_t write_req[ARRAY_SIZE(buffers)]; + uv_buf_t buf[ARRAY_SIZE(buffers)]; + int r, i; + uv_loop_t* loop = uv_default_loop(); + + ASSERT(UV_NAMED_PIPE == uv_guess_handle(0)); + ASSERT(UV_NAMED_PIPE == uv_guess_handle(1)); + + r = uv_pipe_init(loop, &stdin_pipe, 0); + ASSERT(r == 0); + r = uv_pipe_init(loop, &stdout_pipe, 0); + ASSERT(r == 0); + + uv_pipe_open(&stdin_pipe, 0); + uv_pipe_open(&stdout_pipe, 1); + + /* Unref both stdio handles to make sure that all writes complete. */ + uv_unref((uv_handle_t*)&stdin_pipe); + uv_unref((uv_handle_t*)&stdout_pipe); + + for (i = 0; i < ARRAY_SIZE(buffers); i++) { + buf[i] = uv_buf_init((char*)buffers[i], strlen(buffers[i])); + } + + for (i = 0; i < ARRAY_SIZE(buffers); i++) { + r = uv_write(&write_req[i], (uv_stream_t*)&stdout_pipe, &buf[i], 1, + after_pipe_write); + ASSERT(r == 0); + } + + uv_run(loop); + + ASSERT(after_write_called == 7); + ASSERT(on_pipe_read_called == 0); + ASSERT(close_cb_called == 0); + + uv_ref((uv_handle_t*)&stdout_pipe); + uv_ref((uv_handle_t*)&stdin_pipe); + + r = uv_read_start((uv_stream_t*)&stdin_pipe, on_read_alloc, + on_pipe_read); + ASSERT(r == 0); + + uv_run(loop); + + ASSERT(after_write_called == 7); + ASSERT(on_pipe_read_called == 1); + ASSERT(close_cb_called == 2); + + return 0; +} diff --git a/node-v0.8.14/deps/uv/test/test-tcp-bind-error.c b/node-v0.8.14/deps/uv/test/test-tcp-bind-error.c new file mode 100644 index 0000000..9512519 --- /dev/null +++ b/node-v0.8.14/deps/uv/test/test-tcp-bind-error.c @@ -0,0 +1,191 @@ +/* Copyright Joyent, Inc. and other Node contributors. All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ + +#include "uv.h" +#include "task.h" +#include +#include + + +static int close_cb_called = 0; + + +static void close_cb(uv_handle_t* handle) { + ASSERT(handle != NULL); + close_cb_called++; +} + + +TEST_IMPL(tcp_bind_error_addrinuse) { + struct sockaddr_in addr = uv_ip4_addr("0.0.0.0", TEST_PORT); + uv_tcp_t server1, server2; + int r; + + r = uv_tcp_init(uv_default_loop(), &server1); + ASSERT(r == 0); + r = uv_tcp_bind(&server1, addr); + ASSERT(r == 0); + + r = uv_tcp_init(uv_default_loop(), &server2); + ASSERT(r == 0); + r = uv_tcp_bind(&server2, addr); + ASSERT(r == 0); + + r = uv_listen((uv_stream_t*)&server1, 128, NULL); + ASSERT(r == 0); + r = uv_listen((uv_stream_t*)&server2, 128, NULL); + ASSERT(r == -1); + + ASSERT(uv_last_error(uv_default_loop()).code == UV_EADDRINUSE); + + uv_close((uv_handle_t*)&server1, close_cb); + uv_close((uv_handle_t*)&server2, close_cb); + + uv_run(uv_default_loop()); + + ASSERT(close_cb_called == 2); + + return 0; +} + + +TEST_IMPL(tcp_bind_error_addrnotavail_1) { + struct sockaddr_in addr = uv_ip4_addr("127.255.255.255", TEST_PORT); + uv_tcp_t server; + int r; + + r = uv_tcp_init(uv_default_loop(), &server); + ASSERT(r == 0); + r = uv_tcp_bind(&server, addr); + + /* It seems that Linux is broken here - bind succeeds. */ + if (r == -1) { + ASSERT(uv_last_error(uv_default_loop()).code == UV_EADDRNOTAVAIL); + } + + uv_close((uv_handle_t*)&server, close_cb); + + uv_run(uv_default_loop()); + + ASSERT(close_cb_called == 1); + + return 0; +} + + +TEST_IMPL(tcp_bind_error_addrnotavail_2) { + struct sockaddr_in addr = uv_ip4_addr("4.4.4.4", TEST_PORT); + uv_tcp_t server; + int r; + + r = uv_tcp_init(uv_default_loop(), &server); + ASSERT(r == 0); + r = uv_tcp_bind(&server, addr); + ASSERT(r == -1); + ASSERT(uv_last_error(uv_default_loop()).code == UV_EADDRNOTAVAIL); + + uv_close((uv_handle_t*)&server, close_cb); + + uv_run(uv_default_loop()); + + ASSERT(close_cb_called == 1); + + return 0; +} + + +TEST_IMPL(tcp_bind_error_fault) { + char garbage[] = "blah blah blah blah blah blah blah blah blah blah blah blah"; + struct sockaddr_in* garbage_addr; + uv_tcp_t server; + int r; + + garbage_addr = (struct sockaddr_in*) &garbage; + + r = uv_tcp_init(uv_default_loop(), &server); + ASSERT(r == 0); + r = uv_tcp_bind(&server, *garbage_addr); + ASSERT(r == -1); + + ASSERT(uv_last_error(uv_default_loop()).code == UV_EFAULT); + + uv_close((uv_handle_t*)&server, close_cb); + + uv_run(uv_default_loop()); + + ASSERT(close_cb_called == 1); + + return 0; +} + +/* Notes: On Linux uv_bind(server, NULL) will segfault the program. */ + +TEST_IMPL(tcp_bind_error_inval) { + struct sockaddr_in addr1 = uv_ip4_addr("0.0.0.0", TEST_PORT); + struct sockaddr_in addr2 = uv_ip4_addr("0.0.0.0", TEST_PORT_2); + uv_tcp_t server; + int r; + + r = uv_tcp_init(uv_default_loop(), &server); + ASSERT(r == 0); + r = uv_tcp_bind(&server, addr1); + ASSERT(r == 0); + r = uv_tcp_bind(&server, addr2); + ASSERT(r == -1); + + ASSERT(uv_last_error(uv_default_loop()).code == UV_EINVAL); + + uv_close((uv_handle_t*)&server, close_cb); + + uv_run(uv_default_loop()); + + ASSERT(close_cb_called == 1); + + return 0; +} + + +TEST_IMPL(tcp_bind_localhost_ok) { + struct sockaddr_in addr = uv_ip4_addr("127.0.0.1", TEST_PORT); + + uv_tcp_t server; + int r; + + r = uv_tcp_init(uv_default_loop(), &server); + ASSERT(r == 0); + r = uv_tcp_bind(&server, addr); + ASSERT(r == 0); + + return 0; +} + + +TEST_IMPL(tcp_listen_without_bind) { + int r; + uv_tcp_t server; + + r = uv_tcp_init(uv_default_loop(), &server); + ASSERT(r == 0); + r = uv_listen((uv_stream_t*)&server, 128, NULL); + ASSERT(r == 0); + + return 0; +} diff --git a/node-v0.8.14/deps/uv/test/test-tcp-bind6-error.c b/node-v0.8.14/deps/uv/test/test-tcp-bind6-error.c new file mode 100644 index 0000000..5a8b763 --- /dev/null +++ b/node-v0.8.14/deps/uv/test/test-tcp-bind6-error.c @@ -0,0 +1,154 @@ +/* Copyright Joyent, Inc. and other Node contributors. All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ + +#include "uv.h" +#include "task.h" +#include +#include + + +static int close_cb_called = 0; + + +static void close_cb(uv_handle_t* handle) { + ASSERT(handle != NULL); + close_cb_called++; +} + + +TEST_IMPL(tcp_bind6_error_addrinuse) { + struct sockaddr_in6 addr = uv_ip6_addr("::", TEST_PORT); + uv_tcp_t server1, server2; + int r; + + r = uv_tcp_init(uv_default_loop(), &server1); + ASSERT(r == 0); + r = uv_tcp_bind6(&server1, addr); + ASSERT(r == 0); + + r = uv_tcp_init(uv_default_loop(), &server2); + ASSERT(r == 0); + r = uv_tcp_bind6(&server2, addr); + ASSERT(r == 0); + + r = uv_listen((uv_stream_t*)&server1, 128, NULL); + ASSERT(r == 0); + r = uv_listen((uv_stream_t*)&server2, 128, NULL); + ASSERT(r == -1); + + ASSERT(uv_last_error(uv_default_loop()).code == UV_EADDRINUSE); + + uv_close((uv_handle_t*)&server1, close_cb); + uv_close((uv_handle_t*)&server2, close_cb); + + uv_run(uv_default_loop()); + + ASSERT(close_cb_called == 2); + + return 0; +} + + +TEST_IMPL(tcp_bind6_error_addrnotavail) { + struct sockaddr_in6 addr = uv_ip6_addr("4:4:4:4:4:4:4:4", TEST_PORT); + uv_tcp_t server; + int r; + + r = uv_tcp_init(uv_default_loop(), &server); + ASSERT(r == 0); + r = uv_tcp_bind6(&server, addr); + ASSERT(r == -1); + ASSERT(uv_last_error(uv_default_loop()).code == UV_EADDRNOTAVAIL); + + uv_close((uv_handle_t*)&server, close_cb); + + uv_run(uv_default_loop()); + + ASSERT(close_cb_called == 1); + + return 0; +} + + +TEST_IMPL(tcp_bind6_error_fault) { + char garbage[] = "blah blah blah blah blah blah blah blah blah blah blah blah"; + struct sockaddr_in6* garbage_addr; + uv_tcp_t server; + int r; + + garbage_addr = (struct sockaddr_in6*) &garbage; + + r = uv_tcp_init(uv_default_loop(), &server); + ASSERT(r == 0); + r = uv_tcp_bind6(&server, *garbage_addr); + ASSERT(r == -1); + + ASSERT(uv_last_error(uv_default_loop()).code == UV_EFAULT); + + uv_close((uv_handle_t*)&server, close_cb); + + uv_run(uv_default_loop()); + + ASSERT(close_cb_called == 1); + + return 0; +} + +/* Notes: On Linux uv_bind6(server, NULL) will segfault the program. */ + +TEST_IMPL(tcp_bind6_error_inval) { + struct sockaddr_in6 addr1 = uv_ip6_addr("::", TEST_PORT); + struct sockaddr_in6 addr2 = uv_ip6_addr("::", TEST_PORT_2); + uv_tcp_t server; + int r; + + r = uv_tcp_init(uv_default_loop(), &server); + ASSERT(r == 0); + r = uv_tcp_bind6(&server, addr1); + ASSERT(r == 0); + r = uv_tcp_bind6(&server, addr2); + ASSERT(r == -1); + + ASSERT(uv_last_error(uv_default_loop()).code == UV_EINVAL); + + uv_close((uv_handle_t*)&server, close_cb); + + uv_run(uv_default_loop()); + + ASSERT(close_cb_called == 1); + + return 0; +} + + +TEST_IMPL(tcp_bind6_localhost_ok) { + struct sockaddr_in6 addr = uv_ip6_addr("::1", TEST_PORT); + + uv_tcp_t server; + int r; + + r = uv_tcp_init(uv_default_loop(), &server); + ASSERT(r == 0); + r = uv_tcp_bind6(&server, addr); + ASSERT(r == 0); + + return 0; +} diff --git a/node-v0.8.14/deps/uv/test/test-tcp-close-while-connecting.c b/node-v0.8.14/deps/uv/test/test-tcp-close-while-connecting.c new file mode 100644 index 0000000..93e331d --- /dev/null +++ b/node-v0.8.14/deps/uv/test/test-tcp-close-while-connecting.c @@ -0,0 +1,80 @@ +/* Copyright Joyent, Inc. and other Node contributors. All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ + +#include "uv.h" +#include "task.h" + +static uv_timer_t timer1_handle; +static uv_timer_t timer2_handle; +static uv_tcp_t tcp_handle; + +static int connect_cb_called; +static int timer1_cb_called; +static int close_cb_called; + + +static void close_cb(uv_handle_t* handle) { + close_cb_called++; +} + + +static void connect_cb(uv_connect_t* req, int status) { + ASSERT(status == -1); + ASSERT(uv_last_error(req->handle->loop).code == UV_EINTR); + uv_timer_stop(&timer2_handle); + connect_cb_called++; +} + + +static void timer1_cb(uv_timer_t* handle, int status) { + uv_close((uv_handle_t*)handle, close_cb); + uv_close((uv_handle_t*)&tcp_handle, close_cb); + timer1_cb_called++; +} + + +static void timer2_cb(uv_timer_t* handle, int status) { + ASSERT(0 && "should not be called"); +} + + +TEST_IMPL(tcp_close_while_connecting) { + uv_connect_t connect_req; + struct sockaddr_in addr; + uv_loop_t* loop; + + addr = uv_ip4_addr("1.2.3.4", TEST_PORT); + loop = uv_default_loop(); + + ASSERT(0 == uv_tcp_init(loop, &tcp_handle)); + ASSERT(0 == uv_tcp_connect(&connect_req, &tcp_handle, addr, connect_cb)); + ASSERT(0 == uv_timer_init(loop, &timer1_handle)); + ASSERT(0 == uv_timer_start(&timer1_handle, timer1_cb, 50, 0)); + ASSERT(0 == uv_timer_init(loop, &timer2_handle)); + ASSERT(0 == uv_timer_start(&timer2_handle, timer2_cb, 86400 * 1000, 0)); + ASSERT(0 == uv_run(loop)); + + ASSERT(connect_cb_called == 1); + ASSERT(timer1_cb_called == 1); + ASSERT(close_cb_called == 2); + + return 0; +} diff --git a/node-v0.8.14/deps/uv/test/test-tcp-close.c b/node-v0.8.14/deps/uv/test/test-tcp-close.c new file mode 100644 index 0000000..33f7997 --- /dev/null +++ b/node-v0.8.14/deps/uv/test/test-tcp-close.c @@ -0,0 +1,129 @@ +/* Copyright Joyent, Inc. and other Node contributors. All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ + +#include "uv.h" +#include "task.h" + +#include +#include /* memset */ + +#define NUM_WRITE_REQS 32 + +static uv_tcp_t tcp_handle; +static uv_connect_t connect_req; + +static int write_cb_called; +static int close_cb_called; + +static void connect_cb(uv_connect_t* req, int status); +static void write_cb(uv_write_t* req, int status); +static void close_cb(uv_handle_t* handle); + + +static void connect_cb(uv_connect_t* conn_req, int status) { + uv_write_t* req; + uv_buf_t buf; + int i, r; + + buf = uv_buf_init("PING", 4); + for (i = 0; i < NUM_WRITE_REQS; i++) { + req = malloc(sizeof *req); + ASSERT(req != NULL); + + r = uv_write(req, (uv_stream_t*)&tcp_handle, &buf, 1, write_cb); + ASSERT(r == 0); + } + + uv_close((uv_handle_t*)&tcp_handle, close_cb); +} + + +static void write_cb(uv_write_t* req, int status) { + /* write callbacks should run before the close callback */ + ASSERT(close_cb_called == 0); + ASSERT(req->handle == (uv_stream_t*)&tcp_handle); + write_cb_called++; + free(req); +} + + +static void close_cb(uv_handle_t* handle) { + ASSERT(handle == (uv_handle_t*)&tcp_handle); + close_cb_called++; +} + + +static void connection_cb(uv_stream_t* server, int status) { + ASSERT(status == 0); +} + + +static void start_server(uv_loop_t* loop, uv_tcp_t* handle) { + int r; + + r = uv_tcp_init(loop, handle); + ASSERT(r == 0); + + r = uv_tcp_bind(handle, uv_ip4_addr("127.0.0.1", TEST_PORT)); + ASSERT(r == 0); + + r = uv_listen((uv_stream_t*)handle, 128, connection_cb); + ASSERT(r == 0); + + uv_unref((uv_handle_t*)handle); +} + + +/* Check that pending write requests have their callbacks + * invoked when the handle is closed. + */ +TEST_IMPL(tcp_close) { + uv_loop_t* loop; + uv_tcp_t tcp_server; + int r; + + loop = uv_default_loop(); + + /* We can't use the echo server, it doesn't handle ECONNRESET. */ + start_server(loop, &tcp_server); + + r = uv_tcp_init(loop, &tcp_handle); + ASSERT(r == 0); + + r = uv_tcp_connect(&connect_req, + &tcp_handle, + uv_ip4_addr("127.0.0.1", TEST_PORT), + connect_cb); + ASSERT(r == 0); + + ASSERT(write_cb_called == 0); + ASSERT(close_cb_called == 0); + + r = uv_run(loop); + ASSERT(r == 0); + + printf("%d of %d write reqs seen\n", write_cb_called, NUM_WRITE_REQS); + + ASSERT(write_cb_called == NUM_WRITE_REQS); + ASSERT(close_cb_called == 1); + + return 0; +} diff --git a/node-v0.8.14/deps/uv/test/test-tcp-connect-error-after-write.c b/node-v0.8.14/deps/uv/test/test-tcp-connect-error-after-write.c new file mode 100644 index 0000000..a9c0203 --- /dev/null +++ b/node-v0.8.14/deps/uv/test/test-tcp-connect-error-after-write.c @@ -0,0 +1,95 @@ +/* Copyright Joyent, Inc. and other Node contributors. All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ + +#include "uv.h" +#include "task.h" + +#include +#include +#include + +static int connect_cb_called; +static int write_cb_called; +static int close_cb_called; + + +static void close_cb(uv_handle_t* handle) { + close_cb_called++; +} + + +static void connect_cb(uv_connect_t* req, int status) { + ASSERT(status == -1); + connect_cb_called++; + uv_close((uv_handle_t*)req->handle, close_cb); +} + + +static void write_cb(uv_write_t* req, int status) { + ASSERT(status == -1); + write_cb_called++; +} + + +/* + * Try to connect to an address on which nothing listens, get ECONNREFUSED + * (uv errno 12) and get connect_cb() called once with status != 0. + * Related issue: https://github.com/joyent/libuv/issues/443 + */ +TEST_IMPL(tcp_connect_error_after_write) { + uv_connect_t connect_req; + struct sockaddr_in addr; + uv_write_t write_req; + uv_tcp_t conn; + uv_buf_t buf; + int r; + +#ifdef _WIN32 + fprintf(stderr, "This test is disabled on Windows for now.\n"); + fprintf(stderr, "See https://github.com/joyent/libuv/issues/444\n"); + return 0; /* windows slackers... */ +#endif + + addr = uv_ip4_addr("127.0.0.1", TEST_PORT); + buf = uv_buf_init("TEST", 4); + + r = uv_tcp_init(uv_default_loop(), &conn); + ASSERT(r == 0); + + r = uv_write(&write_req, (uv_stream_t*)&conn, &buf, 1, write_cb); + ASSERT(r == -1); + ASSERT(uv_last_error(uv_default_loop()).code == UV_EBADF); + + r = uv_tcp_connect(&connect_req, &conn, addr, connect_cb); + ASSERT(r == 0); + + r = uv_write(&write_req, (uv_stream_t*)&conn, &buf, 1, write_cb); + ASSERT(r == 0); + + r = uv_run(uv_default_loop()); + ASSERT(r == 0); + + ASSERT(connect_cb_called == 1); + ASSERT(write_cb_called == 1); + ASSERT(close_cb_called == 1); + + return 0; +} diff --git a/node-v0.8.14/deps/uv/test/test-tcp-connect-error.c b/node-v0.8.14/deps/uv/test/test-tcp-connect-error.c new file mode 100644 index 0000000..5cdacab --- /dev/null +++ b/node-v0.8.14/deps/uv/test/test-tcp-connect-error.c @@ -0,0 +1,70 @@ +/* Copyright Joyent, Inc. and other Node contributors. All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ + +#include "uv.h" +#include "task.h" +#include +#include + + +static int connect_cb_called = 0; +static int close_cb_called = 0; + + + +static void connect_cb(uv_connect_t* handle, int status) { + ASSERT(handle != NULL); + connect_cb_called++; +} + + + +static void close_cb(uv_handle_t* handle) { + ASSERT(handle != NULL); + close_cb_called++; +} + + +TEST_IMPL(tcp_connect_error_fault) { + char garbage[] = "blah blah blah blah blah blah blah blah blah blah blah blah"; + struct sockaddr_in* garbage_addr; + uv_tcp_t server; + int r; + uv_connect_t req; + + garbage_addr = (struct sockaddr_in*) &garbage; + + r = uv_tcp_init(uv_default_loop(), &server); + ASSERT(r == 0); + r = uv_tcp_connect(&req, &server, *garbage_addr, connect_cb); + ASSERT(r == -1); + + ASSERT(uv_last_error(uv_default_loop()).code == UV_EINVAL); + + uv_close((uv_handle_t*)&server, close_cb); + + uv_run(uv_default_loop()); + + ASSERT(connect_cb_called == 0); + ASSERT(close_cb_called == 1); + + return 0; +} diff --git a/node-v0.8.14/deps/uv/test/test-tcp-connect-timeout.c b/node-v0.8.14/deps/uv/test/test-tcp-connect-timeout.c new file mode 100644 index 0000000..32b0dff --- /dev/null +++ b/node-v0.8.14/deps/uv/test/test-tcp-connect-timeout.c @@ -0,0 +1,85 @@ +/* Copyright Joyent, Inc. and other Node contributors. All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ + +#include "uv.h" +#include "task.h" +#include +#include + + +static int connect_cb_called; +static int close_cb_called; + +static uv_connect_t connect_req; +static uv_timer_t timer; +static uv_tcp_t conn; + +static void connect_cb(uv_connect_t* req, int status); +static void timer_cb(uv_timer_t* handle, int status); +static void close_cb(uv_handle_t* handle); + + +static void connect_cb(uv_connect_t* req, int status) { + ASSERT(req == &connect_req); + ASSERT(status == -1); + connect_cb_called++; +} + + +static void timer_cb(uv_timer_t* handle, int status) { + ASSERT(handle == &timer); + uv_close((uv_handle_t*)&conn, close_cb); + uv_close((uv_handle_t*)&timer, close_cb); +} + + +static void close_cb(uv_handle_t* handle) { + ASSERT(handle == (uv_handle_t*)&conn || handle == (uv_handle_t*)&timer); + close_cb_called++; +} + + +/* Verify that connecting to an unreachable address or port doesn't hang + * the event loop. + */ +TEST_IMPL(tcp_connect_timeout) { + struct sockaddr_in addr; + int r; + + addr = uv_ip4_addr("8.8.8.8", 9999); + + r = uv_timer_init(uv_default_loop(), &timer); + ASSERT(r == 0); + + r = uv_timer_start(&timer, timer_cb, 50, 0); + ASSERT(r == 0); + + r = uv_tcp_init(uv_default_loop(), &conn); + ASSERT(r == 0); + + r = uv_tcp_connect(&connect_req, &conn, addr, connect_cb); + ASSERT(r == 0); + + r = uv_run(uv_default_loop()); + ASSERT(r == 0); + + return 0; +} diff --git a/node-v0.8.14/deps/uv/test/test-tcp-connect6-error.c b/node-v0.8.14/deps/uv/test/test-tcp-connect6-error.c new file mode 100644 index 0000000..5c158ff --- /dev/null +++ b/node-v0.8.14/deps/uv/test/test-tcp-connect6-error.c @@ -0,0 +1,68 @@ +/* Copyright Joyent, Inc. and other Node contributors. All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ + +#include "uv.h" +#include "task.h" +#include +#include + + +static int connect_cb_called = 0; +static int close_cb_called = 0; + + +static void connect_cb(uv_connect_t* handle, int status) { + ASSERT(handle != NULL); + connect_cb_called++; +} + + +static void close_cb(uv_handle_t* handle) { + ASSERT(handle != NULL); + close_cb_called++; +} + + +TEST_IMPL(tcp_connect6_error_fault) { + char garbage[] = "blah blah blah blah blah blah blah blah blah blah blah blah"; + struct sockaddr_in6* garbage_addr; + uv_tcp_t server; + int r; + uv_connect_t req; + + garbage_addr = (struct sockaddr_in6*) &garbage; + + r = uv_tcp_init(uv_default_loop(), &server); + ASSERT(r == 0); + r = uv_tcp_connect6(&req, &server, *garbage_addr, connect_cb); + ASSERT(r == -1); + + ASSERT(uv_last_error(uv_default_loop()).code == UV_EINVAL); + + uv_close((uv_handle_t*)&server, close_cb); + + uv_run(uv_default_loop()); + + ASSERT(connect_cb_called == 0); + ASSERT(close_cb_called == 1); + + return 0; +} diff --git a/node-v0.8.14/deps/uv/test/test-tcp-flags.c b/node-v0.8.14/deps/uv/test/test-tcp-flags.c new file mode 100644 index 0000000..c441b56 --- /dev/null +++ b/node-v0.8.14/deps/uv/test/test-tcp-flags.c @@ -0,0 +1,51 @@ +/* Copyright Joyent, Inc. and other Node contributors. All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ + +#include "uv.h" +#include "task.h" + +#include +#include + + +TEST_IMPL(tcp_flags) { + uv_loop_t* loop; + uv_tcp_t handle; + int r; + + loop = uv_default_loop(); + + r = uv_tcp_init(loop, &handle); + ASSERT(r == 0); + + r = uv_tcp_nodelay(&handle, 1); + ASSERT(r == 0); + + r = uv_tcp_keepalive(&handle, 1, 60); + ASSERT(r == 0); + + uv_close((uv_handle_t*)&handle, NULL); + + r = uv_run(loop); + ASSERT(r == 0); + + return 0; +} diff --git a/node-v0.8.14/deps/uv/test/test-tcp-shutdown-after-write.c b/node-v0.8.14/deps/uv/test/test-tcp-shutdown-after-write.c new file mode 100644 index 0000000..219a3b4 --- /dev/null +++ b/node-v0.8.14/deps/uv/test/test-tcp-shutdown-after-write.c @@ -0,0 +1,131 @@ +/* Copyright Joyent, Inc. and other Node contributors. All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ + +#include "uv.h" +#include "task.h" + +static void write_cb(uv_write_t* req, int status); +static void shutdown_cb(uv_shutdown_t* req, int status); + +static uv_tcp_t conn; +static uv_timer_t timer; +static uv_connect_t connect_req; +static uv_write_t write_req; +static uv_shutdown_t shutdown_req; + +static int connect_cb_called; +static int write_cb_called; +static int shutdown_cb_called; + +static int conn_close_cb_called; +static int timer_close_cb_called; + + +static void close_cb(uv_handle_t* handle) { + if (handle == (uv_handle_t*)&conn) + conn_close_cb_called++; + else if (handle == (uv_handle_t*)&timer) + timer_close_cb_called++; + else + ASSERT(0 && "bad handle in close_cb"); +} + + +static uv_buf_t alloc_cb(uv_handle_t* handle, size_t suggested_size) { + static char slab[64]; + return uv_buf_init(slab, sizeof(slab)); +} + + +static void timer_cb(uv_timer_t* handle, int status) { + uv_buf_t buf; + int r; + + uv_close((uv_handle_t*)handle, close_cb); + + buf = uv_buf_init("TEST", 4); + r = uv_write(&write_req, (uv_stream_t*)&conn, &buf, 1, write_cb); + ASSERT(r == 0); + + r = uv_shutdown(&shutdown_req, (uv_stream_t*)&conn, shutdown_cb); + ASSERT(r == 0); +} + + +static void read_cb(uv_stream_t* handle, ssize_t nread, uv_buf_t buf) { +} + + +static void connect_cb(uv_connect_t* req, int status) { + int r; + + ASSERT(status == 0); + connect_cb_called++; + + r = uv_read_start((uv_stream_t*)&conn, alloc_cb, read_cb); + ASSERT(r == 0); +} + + +static void write_cb(uv_write_t* req, int status) { + ASSERT(status == 0); + write_cb_called++; +} + + +static void shutdown_cb(uv_shutdown_t* req, int status) { + ASSERT(status == 0); + shutdown_cb_called++; + uv_close((uv_handle_t*)&conn, close_cb); +} + + +TEST_IMPL(tcp_shutdown_after_write) { + struct sockaddr_in addr; + uv_loop_t* loop; + int r; + + addr = uv_ip4_addr("127.0.0.1", TEST_PORT); + loop = uv_default_loop(); + + r = uv_timer_init(loop, &timer); + ASSERT(r == 0); + + r = uv_timer_start(&timer, timer_cb, 125, 0); + ASSERT(r == 0); + + r = uv_tcp_init(loop, &conn); + ASSERT(r == 0); + + r = uv_tcp_connect(&connect_req, &conn, addr, connect_cb); + ASSERT(r == 0); + + r = uv_run(loop); + ASSERT(r == 0); + + ASSERT(connect_cb_called == 1); + ASSERT(write_cb_called == 1); + ASSERT(shutdown_cb_called == 1); + ASSERT(conn_close_cb_called == 1); + ASSERT(timer_close_cb_called == 1); + + return 0; +} diff --git a/node-v0.8.14/deps/uv/test/test-tcp-unexpected-read.c b/node-v0.8.14/deps/uv/test/test-tcp-unexpected-read.c new file mode 100644 index 0000000..45559c0 --- /dev/null +++ b/node-v0.8.14/deps/uv/test/test-tcp-unexpected-read.c @@ -0,0 +1,113 @@ +/* Copyright Joyent, Inc. and other Node contributors. All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ + +#include "uv.h" +#include "task.h" + +static uv_check_t check_handle; +static uv_timer_t timer_handle; +static uv_tcp_t server_handle; +static uv_tcp_t client_handle; +static uv_tcp_t peer_handle; +static uv_write_t write_req; +static uv_connect_t connect_req; + +static unsigned long ticks; /* event loop ticks */ + + +static void check_cb(uv_check_t* handle, int status) { + ticks++; +} + + +static void timer_cb(uv_timer_t* handle, int status) { + uv_close((uv_handle_t*) &check_handle, NULL); + uv_close((uv_handle_t*) &timer_handle, NULL); + uv_close((uv_handle_t*) &server_handle, NULL); + uv_close((uv_handle_t*) &client_handle, NULL); + uv_close((uv_handle_t*) &peer_handle, NULL); +} + + +static uv_buf_t alloc_cb(uv_handle_t* handle, size_t suggested_size) { + ASSERT(0 && "alloc_cb should not have been called"); + /* Satisfy the compiler. */ + return uv_buf_init(NULL, 0); +} + + +static void read_cb(uv_stream_t* handle, ssize_t nread, uv_buf_t buf) { + ASSERT(0 && "read_cb should not have been called"); +} + + +static void connect_cb(uv_connect_t* req, int status) { + ASSERT(req->handle == (uv_stream_t*) &client_handle); + ASSERT(0 == status); +} + + +static void write_cb(uv_write_t* req, int status) { + ASSERT(req->handle == (uv_stream_t*) &peer_handle); + ASSERT(0 == status); +} + + +static void connection_cb(uv_stream_t* handle, int status) { + uv_buf_t buf; + + buf = uv_buf_init("PING", 4); + + ASSERT(0 == status); + ASSERT(0 == uv_tcp_init(uv_default_loop(), &peer_handle)); + ASSERT(0 == uv_accept(handle, (uv_stream_t*) &peer_handle)); + ASSERT(0 == uv_read_start((uv_stream_t*) &peer_handle, alloc_cb, read_cb)); + ASSERT(0 == uv_write(&write_req, (uv_stream_t*) &peer_handle, + &buf, 1, write_cb)); +} + + +TEST_IMPL(tcp_unexpected_read) { + struct sockaddr_in addr; + uv_loop_t* loop; + + addr = uv_ip4_addr("127.0.0.1", TEST_PORT); + loop = uv_default_loop(); + + ASSERT(0 == uv_timer_init(loop, &timer_handle)); + ASSERT(0 == uv_timer_start(&timer_handle, timer_cb, 1000, 0)); + ASSERT(0 == uv_check_init(loop, &check_handle)); + ASSERT(0 == uv_check_start(&check_handle, check_cb)); + ASSERT(0 == uv_tcp_init(loop, &server_handle)); + ASSERT(0 == uv_tcp_init(loop, &client_handle)); + ASSERT(0 == uv_tcp_bind(&server_handle, addr)); + ASSERT(0 == uv_listen((uv_stream_t*) &server_handle, 1, connection_cb)); + ASSERT(0 == uv_tcp_connect(&connect_req, &client_handle, addr, connect_cb)); + ASSERT(0 == uv_run(loop)); + + /* This is somewhat inexact but the idea is that the event loop should not + * start busy looping when the server sends a message and the client isn't + * reading. + */ + ASSERT(ticks <= 10); + + return 0; +} diff --git a/node-v0.8.14/deps/uv/test/test-tcp-write-error.c b/node-v0.8.14/deps/uv/test/test-tcp-write-error.c new file mode 100644 index 0000000..32207dd --- /dev/null +++ b/node-v0.8.14/deps/uv/test/test-tcp-write-error.c @@ -0,0 +1,168 @@ +/* Copyright Joyent, Inc. and other Node contributors. All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ + +#include "uv.h" +#include "task.h" + +#include +#include +#include + +static void connection_cb(uv_stream_t* server, int status); +static void connect_cb(uv_connect_t* req, int status); +static void write_cb(uv_write_t* req, int status); +static void read_cb(uv_stream_t* stream, ssize_t nread, uv_buf_t buf); +static uv_buf_t alloc_cb(uv_handle_t* handle, size_t suggested_size); + +static uv_tcp_t tcp_server; +static uv_tcp_t tcp_client; +static uv_tcp_t tcp_peer; /* client socket as accept()-ed by server */ +static uv_connect_t connect_req; + +static int write_cb_called; +static int write_cb_error_called; + +typedef struct { + uv_write_t req; + uv_buf_t buf; +} write_req_t; + + +static void connection_cb(uv_stream_t* server, int status) { + int r; + + ASSERT(server == (uv_stream_t*)&tcp_server); + ASSERT(status == 0); + + r = uv_tcp_init(server->loop, &tcp_peer); + ASSERT(r == 0); + + r = uv_accept(server, (uv_stream_t*)&tcp_peer); + ASSERT(r == 0); + + r = uv_read_start((uv_stream_t*)&tcp_peer, alloc_cb, read_cb); + ASSERT(r == 0); +} + + +static uv_buf_t alloc_cb(uv_handle_t* handle, size_t suggested_size) { + static char slab[1024]; + return uv_buf_init(slab, sizeof slab); +} + + +static void read_cb(uv_stream_t* stream, ssize_t nread, uv_buf_t buf) { + uv_close((uv_handle_t*)&tcp_server, NULL); + uv_close((uv_handle_t*)&tcp_peer, NULL); +} + + +static void connect_cb(uv_connect_t* req, int status) { + uv_buf_t buf; + size_t size; + char* data; + int r; + write_req_t* wr; + + ASSERT(req == &connect_req); + ASSERT(status == 0); + + while (1) { + size = 10 * 1024 * 1024; + data = malloc(size); + ASSERT(data != NULL); + + memset(data, '$', size); + buf = uv_buf_init(data, size); + + wr = (write_req_t*) malloc(sizeof *wr); + wr->buf = buf; + wr->req.data = data; + + r = uv_write(&(wr->req), req->handle, &wr->buf, 1, write_cb); + ASSERT(r == 0); + + if (req->handle->write_queue_size >= size * 2) { + break; + } + } +} + + +static void write_cb(uv_write_t* req, int status) { + write_req_t* wr; + wr = (write_req_t*) req; + + if (status == -1) { + write_cb_error_called++; + } + + if (req->handle->write_queue_size == 0) { + uv_close((uv_handle_t*)&tcp_client, NULL); + } + + free(wr->buf.base); + free(wr); + + write_cb_called++; +} + + +/* + * Assert that a failing write does not leave + * the stream's write_queue_size in an inconsistent state. + */ +TEST_IMPL(tcp_write_error) { + uv_loop_t* loop; + int r; + + loop = uv_default_loop(); + ASSERT(loop != NULL); + + r = uv_tcp_init(loop, &tcp_server); + ASSERT(r == 0); + + r = uv_tcp_bind(&tcp_server, uv_ip4_addr("127.0.0.1", TEST_PORT)); + ASSERT(r == 0); + + r = uv_listen((uv_stream_t*)&tcp_server, 1, connection_cb); + ASSERT(r == 0); + + r = uv_tcp_init(loop, &tcp_client); + ASSERT(r == 0); + + r = uv_tcp_connect(&connect_req, + &tcp_client, + uv_ip4_addr("127.0.0.1", TEST_PORT), + connect_cb); + ASSERT(r == 0); + + ASSERT(write_cb_called == 0); + + r = uv_run(loop); + ASSERT(r == 0); + + ASSERT(write_cb_called > 0); + ASSERT(write_cb_error_called >= 1); + ASSERT(tcp_client.write_queue_size == 0); + + return 0; +} diff --git a/node-v0.8.14/deps/uv/test/test-tcp-write-to-half-open-connection.c b/node-v0.8.14/deps/uv/test/test-tcp-write-to-half-open-connection.c new file mode 100644 index 0000000..26f914b --- /dev/null +++ b/node-v0.8.14/deps/uv/test/test-tcp-write-to-half-open-connection.c @@ -0,0 +1,135 @@ +/* Copyright Joyent, Inc. and other Node contributors. All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ + +#include "uv.h" +#include "task.h" + +#include +#include +#include + +static void connection_cb(uv_stream_t* server, int status); +static void connect_cb(uv_connect_t* req, int status); +static void write_cb(uv_write_t* req, int status); +static void read_cb(uv_stream_t* stream, ssize_t nread, uv_buf_t buf); +static uv_buf_t alloc_cb(uv_handle_t* handle, size_t suggested_size); + +static uv_tcp_t tcp_server; +static uv_tcp_t tcp_client; +static uv_tcp_t tcp_peer; /* client socket as accept()-ed by server */ +static uv_connect_t connect_req; +static uv_write_t write_req; + +static int write_cb_called; +static int read_cb_called; + +static void connection_cb(uv_stream_t* server, int status) { + int r; + uv_buf_t buf; + + ASSERT(server == (uv_stream_t*)&tcp_server); + ASSERT(status == 0); + + r = uv_tcp_init(server->loop, &tcp_peer); + ASSERT(r == 0); + + r = uv_accept(server, (uv_stream_t*)&tcp_peer); + ASSERT(r == 0); + + r = uv_read_start((uv_stream_t*)&tcp_peer, alloc_cb, read_cb); + ASSERT(r == 0); + + buf.base = "hello\n"; + buf.len = 6; + + r = uv_write(&write_req, (uv_stream_t*)&tcp_peer, &buf, 1, write_cb); + ASSERT(r == 0); +} + + +static uv_buf_t alloc_cb(uv_handle_t* handle, size_t suggested_size) { + static char slab[1024]; + return uv_buf_init(slab, sizeof slab); +} + + +static void read_cb(uv_stream_t* stream, ssize_t nread, uv_buf_t buf) { + if (nread == -1) { + fprintf(stderr, "read_cb error: %s\n", uv_err_name(uv_last_error(stream->loop))); + ASSERT(uv_last_error(stream->loop).code == UV_ECONNRESET || + uv_last_error(stream->loop).code == UV_EOF); + + uv_close((uv_handle_t*)&tcp_server, NULL); + uv_close((uv_handle_t*)&tcp_peer, NULL); + } + + read_cb_called++; +} + + +static void connect_cb(uv_connect_t* req, int status) { + ASSERT(req == &connect_req); + ASSERT(status == 0); + + /* Close the client. */ + uv_close((uv_handle_t*)&tcp_client, NULL); +} + + +static void write_cb(uv_write_t* req, int status) { + ASSERT(status == 0); + write_cb_called++; +} + + +TEST_IMPL(tcp_write_to_half_open_connection) { + uv_loop_t* loop; + int r; + + loop = uv_default_loop(); + ASSERT(loop != NULL); + + r = uv_tcp_init(loop, &tcp_server); + ASSERT(r == 0); + + r = uv_tcp_bind(&tcp_server, uv_ip4_addr("127.0.0.1", TEST_PORT)); + ASSERT(r == 0); + + r = uv_listen((uv_stream_t*)&tcp_server, 1, connection_cb); + ASSERT(r == 0); + + r = uv_tcp_init(loop, &tcp_client); + ASSERT(r == 0); + + r = uv_tcp_connect(&connect_req, + &tcp_client, + uv_ip4_addr("127.0.0.1", TEST_PORT), + connect_cb); + ASSERT(r == 0); + + r = uv_run(loop); + ASSERT(r == 0); + + ASSERT(write_cb_called > 0); + ASSERT(read_cb_called > 0); + + return 0; +} diff --git a/node-v0.8.14/deps/uv/test/test-tcp-writealot.c b/node-v0.8.14/deps/uv/test/test-tcp-writealot.c new file mode 100644 index 0000000..841df3c --- /dev/null +++ b/node-v0.8.14/deps/uv/test/test-tcp-writealot.c @@ -0,0 +1,170 @@ +/* Copyright Joyent, Inc. and other Node contributors. All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ + +#include "uv.h" +#include "task.h" +#include +#include + + +#define WRITES 3 +#define CHUNKS_PER_WRITE 3 +#define CHUNK_SIZE 10485760 /* 10 MB */ + +#define TOTAL_BYTES (WRITES * CHUNKS_PER_WRITE * CHUNK_SIZE) + +static char* send_buffer; + +static int shutdown_cb_called = 0; +static int connect_cb_called = 0; +static int write_cb_called = 0; +static int close_cb_called = 0; +static size_t bytes_sent = 0; +static size_t bytes_sent_done = 0; +static size_t bytes_received_done = 0; + +static uv_connect_t connect_req; +static uv_shutdown_t shutdown_req; +static uv_write_t write_reqs[WRITES]; + + +static uv_buf_t alloc_cb(uv_handle_t* handle, size_t size) { + return uv_buf_init(malloc(size), size); +} + + +static void close_cb(uv_handle_t* handle) { + ASSERT(handle != NULL); + close_cb_called++; +} + + +static void shutdown_cb(uv_shutdown_t* req, int status) { + uv_tcp_t* tcp; + + ASSERT(req == &shutdown_req); + ASSERT(status == 0); + + tcp = (uv_tcp_t*)(req->handle); + + /* The write buffer should be empty by now. */ + ASSERT(tcp->write_queue_size == 0); + + /* Now we wait for the EOF */ + shutdown_cb_called++; + + /* We should have had all the writes called already. */ + ASSERT(write_cb_called == WRITES); +} + + +static void read_cb(uv_stream_t* tcp, ssize_t nread, uv_buf_t buf) { + ASSERT(tcp != NULL); + + if (nread >= 0) { + bytes_received_done += nread; + } + else { + ASSERT(uv_last_error(uv_default_loop()).code == UV_EOF); + printf("GOT EOF\n"); + uv_close((uv_handle_t*)tcp, close_cb); + } + + free(buf.base); +} + + +static void write_cb(uv_write_t* req, int status) { + ASSERT(req != NULL); + + if (status) { + uv_err_t err = uv_last_error(uv_default_loop()); + fprintf(stderr, "uv_write error: %s\n", uv_strerror(err)); + ASSERT(0); + } + + bytes_sent_done += CHUNKS_PER_WRITE * CHUNK_SIZE; + write_cb_called++; +} + + +static void connect_cb(uv_connect_t* req, int status) { + uv_buf_t send_bufs[CHUNKS_PER_WRITE]; + uv_stream_t* stream; + int i, j, r; + + ASSERT(req == &connect_req); + ASSERT(status == 0); + + stream = req->handle; + connect_cb_called++; + + /* Write a lot of data */ + for (i = 0; i < WRITES; i++) { + uv_write_t* write_req = write_reqs + i; + + for (j = 0; j < CHUNKS_PER_WRITE; j++) { + send_bufs[j] = uv_buf_init(send_buffer + bytes_sent, CHUNK_SIZE); + bytes_sent += CHUNK_SIZE; + } + + r = uv_write(write_req, stream, send_bufs, CHUNKS_PER_WRITE, write_cb); + ASSERT(r == 0); + } + + /* Shutdown on drain. */ + r = uv_shutdown(&shutdown_req, stream, shutdown_cb); + ASSERT(r == 0); + + /* Start reading */ + r = uv_read_start(stream, alloc_cb, read_cb); + ASSERT(r == 0); +} + + +TEST_IMPL(tcp_writealot) { + struct sockaddr_in addr = uv_ip4_addr("127.0.0.1", TEST_PORT); + uv_tcp_t client; + int r; + + send_buffer = malloc(TOTAL_BYTES); + ASSERT(send_buffer != NULL); + + r = uv_tcp_init(uv_default_loop(), &client); + ASSERT(r == 0); + + r = uv_tcp_connect(&connect_req, &client, addr, connect_cb); + ASSERT(r == 0); + + uv_run(uv_default_loop()); + + ASSERT(shutdown_cb_called == 1); + ASSERT(connect_cb_called == 1); + ASSERT(write_cb_called == WRITES); + ASSERT(close_cb_called == 1); + ASSERT(bytes_sent == TOTAL_BYTES); + ASSERT(bytes_sent_done == TOTAL_BYTES); + ASSERT(bytes_received_done == TOTAL_BYTES); + + free(send_buffer); + + return 0; +} diff --git a/node-v0.8.14/deps/uv/test/test-thread.c b/node-v0.8.14/deps/uv/test/test-thread.c new file mode 100644 index 0000000..1766637 --- /dev/null +++ b/node-v0.8.14/deps/uv/test/test-thread.c @@ -0,0 +1,183 @@ +/* Copyright Joyent, Inc. and other Node contributors. All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ + +#include "uv.h" +#include "task.h" + +#include +#include +#include /* memset */ + +struct getaddrinfo_req { + uv_thread_t thread_id; + unsigned int counter; + uv_loop_t* loop; + uv_getaddrinfo_t handle; +}; + + +struct fs_req { + uv_thread_t thread_id; + unsigned int counter; + uv_loop_t* loop; + uv_fs_t handle; +}; + + +struct thread { + uv_thread_t thread_id; + volatile int thread_called; +}; + +static void getaddrinfo_do(struct getaddrinfo_req* req); +static void getaddrinfo_cb(uv_getaddrinfo_t* handle, + int status, + struct addrinfo* res); +static void fs_do(struct fs_req* req); +static void fs_cb(uv_fs_t* handle); + +static volatile int thread_called; + + +static void getaddrinfo_do(struct getaddrinfo_req* req) { + int r; + + r = uv_getaddrinfo(req->loop, + &req->handle, + getaddrinfo_cb, + "localhost", + NULL, + NULL); + ASSERT(r == 0); +} + + +static void getaddrinfo_cb(uv_getaddrinfo_t* handle, + int status, + struct addrinfo* res) { + struct getaddrinfo_req* req; + + ASSERT(status == 0); + + req = container_of(handle, struct getaddrinfo_req, handle); + uv_freeaddrinfo(res); + + if (--req->counter) + getaddrinfo_do(req); +} + + +static void fs_do(struct fs_req* req) { + int r; + + r = uv_fs_stat(req->loop, &req->handle, ".", fs_cb); + ASSERT(r == 0); +} + + +static void fs_cb(uv_fs_t* handle) { + struct fs_req* req = container_of(handle, struct fs_req, handle); + + uv_fs_req_cleanup(handle); + + if (--req->counter) + fs_do(req); +} + + +static void do_work(void* arg) { + struct getaddrinfo_req getaddrinfo_reqs[16]; + struct fs_req fs_reqs[16]; + uv_loop_t* loop; + size_t i; + int r; + struct thread* thread = arg; + + loop = uv_loop_new(); + ASSERT(loop != NULL); + + for (i = 0; i < ARRAY_SIZE(getaddrinfo_reqs); i++) { + struct getaddrinfo_req* req = getaddrinfo_reqs + i; + req->counter = 16; + req->loop = loop; + getaddrinfo_do(req); + } + + for (i = 0; i < ARRAY_SIZE(fs_reqs); i++) { + struct fs_req* req = fs_reqs + i; + req->counter = 16; + req->loop = loop; + fs_do(req); + } + + r = uv_run(loop); + ASSERT(r == 0); + + uv_loop_delete(loop); + thread->thread_called = 1; +} + + +static void thread_entry(void* arg) { + ASSERT(arg == (void *) 42); + thread_called++; +} + + +TEST_IMPL(thread_create) { + uv_thread_t tid; + int r; + + r = uv_thread_create(&tid, thread_entry, (void *) 42); + ASSERT(r == 0); + + r = uv_thread_join(&tid); + ASSERT(r == 0); + + ASSERT(thread_called == 1); + + return 0; +} + + +/* Hilariously bad test name. Run a lot of tasks in the thread pool and verify + * that each "finished" callback is run in its originating thread. + */ +TEST_IMPL(threadpool_multiple_event_loops) { + struct thread threads[8]; + size_t i; + int r; + + memset(threads, 0, sizeof(threads)); + + for (i = 0; i < ARRAY_SIZE(threads); i++) { + r = uv_thread_create(&threads[i].thread_id, do_work, &threads[i]); + ASSERT(r == 0); + } + + for (i = 0; i < ARRAY_SIZE(threads); i++) { + r = uv_thread_join(&threads[i].thread_id); + ASSERT(r == 0); + ASSERT(threads[i].thread_called); + } + + return 0; +} diff --git a/node-v0.8.14/deps/uv/test/test-threadpool.c b/node-v0.8.14/deps/uv/test/test-threadpool.c new file mode 100644 index 0000000..92130b5 --- /dev/null +++ b/node-v0.8.14/deps/uv/test/test-threadpool.c @@ -0,0 +1,57 @@ +/* Copyright Joyent, Inc. and other Node contributors. All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ + +#include "uv.h" +#include "task.h" + +static int work_cb_count; +static int after_work_cb_count; +static uv_work_t work_req; +static char data; + + +static void work_cb(uv_work_t* req) { + ASSERT(req == &work_req); + ASSERT(req->data == &data); + work_cb_count++; +} + + +static void after_work_cb(uv_work_t* req) { + ASSERT(req == &work_req); + ASSERT(req->data == &data); + after_work_cb_count++; +} + + +TEST_IMPL(threadpool_queue_work_simple) { + int r; + + work_req.data = &data; + r = uv_queue_work(uv_default_loop(), &work_req, work_cb, after_work_cb); + ASSERT(r == 0); + uv_run(uv_default_loop()); + + ASSERT(work_cb_count == 1); + ASSERT(after_work_cb_count == 1); + + return 0; +} diff --git a/node-v0.8.14/deps/uv/test/test-timer-again.c b/node-v0.8.14/deps/uv/test/test-timer-again.c new file mode 100644 index 0000000..e492c36 --- /dev/null +++ b/node-v0.8.14/deps/uv/test/test-timer-again.c @@ -0,0 +1,141 @@ +/* Copyright Joyent, Inc. and other Node contributors. All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ + +#include "uv.h" +#include "task.h" + + +static int close_cb_called = 0; +static int repeat_1_cb_called = 0; +static int repeat_2_cb_called = 0; + +static int repeat_2_cb_allowed = 0; + +static uv_timer_t dummy, repeat_1, repeat_2; + +static int64_t start_time; + + +static void close_cb(uv_handle_t* handle) { + ASSERT(handle != NULL); + + close_cb_called++; +} + + +static void repeat_1_cb(uv_timer_t* handle, int status) { + int r; + + ASSERT(handle == &repeat_1); + ASSERT(status == 0); + + ASSERT(uv_timer_get_repeat((uv_timer_t*)handle) == 50); + + LOGF("repeat_1_cb called after %ld ms\n", + (long int)(uv_now(uv_default_loop()) - start_time)); + + repeat_1_cb_called++; + + r = uv_timer_again(&repeat_2); + ASSERT(r == 0); + + if (uv_now(uv_default_loop()) >= start_time + 500) { + uv_close((uv_handle_t*)handle, close_cb); + /* We're not calling uv_timer_again on repeat_2 any more, so after this */ + /* timer_2_cb is expected. */ + repeat_2_cb_allowed = 1; + return; + } +} + + +static void repeat_2_cb(uv_timer_t* handle, int status) { + ASSERT(handle == &repeat_2); + ASSERT(status == 0); + ASSERT(repeat_2_cb_allowed); + + LOGF("repeat_2_cb called after %ld ms\n", + (long int)(uv_now(uv_default_loop()) - start_time)); + + repeat_2_cb_called++; + + if (uv_timer_get_repeat(&repeat_2) == 0) { + ASSERT(!uv_is_active((uv_handle_t*)handle)); + uv_close((uv_handle_t*)handle, close_cb); + return; + } + + LOGF("uv_timer_get_repeat %ld ms\n", + (long int)uv_timer_get_repeat(&repeat_2)); + ASSERT(uv_timer_get_repeat(&repeat_2) == 100); + + /* This shouldn't take effect immediately. */ + uv_timer_set_repeat(&repeat_2, 0); +} + + +TEST_IMPL(timer_again) { + int r; + + start_time = uv_now(uv_default_loop()); + ASSERT(0 < start_time); + + /* Verify that it is not possible to uv_timer_again a never-started timer. */ + r = uv_timer_init(uv_default_loop(), &dummy); + ASSERT(r == 0); + r = uv_timer_again(&dummy); + ASSERT(r == -1); + ASSERT(uv_last_error(uv_default_loop()).code == UV_EINVAL); + uv_unref((uv_handle_t*)&dummy); + + /* Start timer repeat_1. */ + r = uv_timer_init(uv_default_loop(), &repeat_1); + ASSERT(r == 0); + r = uv_timer_start(&repeat_1, repeat_1_cb, 50, 0); + ASSERT(r == 0); + ASSERT(uv_timer_get_repeat(&repeat_1) == 0); + + /* Actually make repeat_1 repeating. */ + uv_timer_set_repeat(&repeat_1, 50); + ASSERT(uv_timer_get_repeat(&repeat_1) == 50); + + /* + * Start another repeating timer. It'll be again()ed by the repeat_1 so + * it should not time out until repeat_1 stops. + */ + r = uv_timer_init(uv_default_loop(), &repeat_2); + ASSERT(r == 0); + r = uv_timer_start(&repeat_2, repeat_2_cb, 100, 100); + ASSERT(r == 0); + ASSERT(uv_timer_get_repeat(&repeat_2) == 100); + + uv_run(uv_default_loop()); + + ASSERT(repeat_1_cb_called == 10); + ASSERT(repeat_2_cb_called == 2); + ASSERT(close_cb_called == 2); + + LOGF("Test took %ld ms (expected ~700 ms)\n", + (long int)(uv_now(uv_default_loop()) - start_time)); + ASSERT(700 <= uv_now(uv_default_loop()) - start_time); + + return 0; +} diff --git a/node-v0.8.14/deps/uv/test/test-timer.c b/node-v0.8.14/deps/uv/test/test-timer.c new file mode 100644 index 0000000..c1b629b --- /dev/null +++ b/node-v0.8.14/deps/uv/test/test-timer.c @@ -0,0 +1,152 @@ +/* Copyright Joyent, Inc. and other Node contributors. All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ + +#include "uv.h" +#include "task.h" + + +static int once_cb_called = 0; +static int once_close_cb_called = 0; +static int repeat_cb_called = 0; +static int repeat_close_cb_called = 0; + +static int64_t start_time; + + +static void once_close_cb(uv_handle_t* handle) { + printf("ONCE_CLOSE_CB\n"); + + ASSERT(handle != NULL); + ASSERT(!uv_is_active(handle)); + + once_close_cb_called++; +} + + +static void once_cb(uv_timer_t* handle, int status) { + printf("ONCE_CB %d\n", once_cb_called); + + ASSERT(handle != NULL); + ASSERT(status == 0); + ASSERT(!uv_is_active((uv_handle_t*)handle)); + + once_cb_called++; + + uv_close((uv_handle_t*)handle, once_close_cb); + + /* Just call this randomly for the code coverage. */ + uv_update_time(uv_default_loop()); +} + + +static void repeat_close_cb(uv_handle_t* handle) { + printf("REPEAT_CLOSE_CB\n"); + + ASSERT(handle != NULL); + + repeat_close_cb_called++; +} + + +static void repeat_cb(uv_timer_t* handle, int status) { + printf("REPEAT_CB\n"); + + ASSERT(handle != NULL); + ASSERT(status == 0); + ASSERT(uv_is_active((uv_handle_t*)handle)); + + repeat_cb_called++; + + if (repeat_cb_called == 5) { + uv_close((uv_handle_t*)handle, repeat_close_cb); + } +} + + +static void never_cb(uv_timer_t* handle, int status) { + FATAL("never_cb should never be called"); +} + + +TEST_IMPL(timer) { + uv_timer_t once_timers[10]; + uv_timer_t *once; + uv_timer_t repeat, never; + int i, r; + + start_time = uv_now(uv_default_loop()); + ASSERT(0 < start_time); + + /* Let 10 timers time out in 500 ms total. */ + for (i = 0; i < ARRAY_SIZE(once_timers); i++) { + once = once_timers + i; + r = uv_timer_init(uv_default_loop(), once); + ASSERT(r == 0); + r = uv_timer_start(once, once_cb, i * 50, 0); + ASSERT(r == 0); + } + + /* The 11th timer is a repeating timer that runs 4 times */ + r = uv_timer_init(uv_default_loop(), &repeat); + ASSERT(r == 0); + r = uv_timer_start(&repeat, repeat_cb, 100, 100); + ASSERT(r == 0); + + /* The 12th timer should not do anything. */ + r = uv_timer_init(uv_default_loop(), &never); + ASSERT(r == 0); + r = uv_timer_start(&never, never_cb, 100, 100); + ASSERT(r == 0); + r = uv_timer_stop(&never); + ASSERT(r == 0); + uv_unref((uv_handle_t*)&never); + + uv_run(uv_default_loop()); + + ASSERT(once_cb_called == 10); + ASSERT(once_close_cb_called == 10); + printf("repeat_cb_called %d\n", repeat_cb_called); + ASSERT(repeat_cb_called == 5); + ASSERT(repeat_close_cb_called == 1); + + ASSERT(500 <= uv_now(uv_default_loop()) - start_time); + + return 0; +} + + +TEST_IMPL(timer_start_twice) { + uv_timer_t once; + int r; + + r = uv_timer_init(uv_default_loop(), &once); + ASSERT(r == 0); + r = uv_timer_start(&once, never_cb, 86400 * 1000, 0); + ASSERT(r == 0); + r = uv_timer_start(&once, once_cb, 10, 0); + ASSERT(r == 0); + r = uv_run(uv_default_loop()); + ASSERT(r == 0); + + ASSERT(once_cb_called == 1); + + return 0; +} diff --git a/node-v0.8.14/deps/uv/test/test-tty.c b/node-v0.8.14/deps/uv/test/test-tty.c new file mode 100644 index 0000000..ded59c9 --- /dev/null +++ b/node-v0.8.14/deps/uv/test/test-tty.c @@ -0,0 +1,110 @@ +/* Copyright Joyent, Inc. and other Node contributors. All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ + +#include "uv.h" +#include "task.h" + +#ifdef _WIN32 +# include +# include +#else /* Unix */ +# include +# include +#endif + + +TEST_IMPL(tty) { + int r, width, height; + int ttyin_fd, ttyout_fd; + uv_tty_t tty_in, tty_out; + uv_loop_t* loop = uv_default_loop(); + + /* Make sure we have an FD that refers to a tty */ +#ifdef _WIN32 + HANDLE handle; + handle = CreateFileA("conin$", + GENERIC_READ | GENERIC_WRITE, + FILE_SHARE_READ | FILE_SHARE_WRITE, + NULL, + OPEN_EXISTING, + FILE_ATTRIBUTE_NORMAL, + NULL); + ASSERT(handle != INVALID_HANDLE_VALUE); + ttyin_fd = _open_osfhandle((intptr_t) handle, 0); + + handle = CreateFileA("conout$", + GENERIC_READ | GENERIC_WRITE, + FILE_SHARE_READ | FILE_SHARE_WRITE, + NULL, + OPEN_EXISTING, + FILE_ATTRIBUTE_NORMAL, + NULL); + ASSERT(handle != INVALID_HANDLE_VALUE); + ttyout_fd = _open_osfhandle((intptr_t) handle, 0); + +#else /* unix */ + ttyin_fd = open("/dev/tty", O_RDONLY, 0); + ttyout_fd = open("/dev/tty", O_WRONLY, 0); +#endif + + ASSERT(ttyin_fd >= 0); + ASSERT(ttyout_fd >= 0); + + ASSERT(UV_UNKNOWN_HANDLE == uv_guess_handle(-1)); + + ASSERT(UV_TTY == uv_guess_handle(ttyin_fd)); + ASSERT(UV_TTY == uv_guess_handle(ttyout_fd)); + + r = uv_tty_init(uv_default_loop(), &tty_in, ttyin_fd, 1); + ASSERT(r == 0); + + r = uv_tty_init(uv_default_loop(), &tty_out, ttyout_fd, 2); + ASSERT(r == 0); + + r = uv_tty_get_winsize(&tty_out, &width, &height); + ASSERT(r == 0); + + printf("width=%d height=%d\n", width, height); + + /* + * Is it a safe assumption that most people have terminals larger than + * 10x10? + */ + ASSERT(width > 10); + ASSERT(height > 10); + + /* Turn on raw mode. */ + r = uv_tty_set_mode(&tty_in, 1); + ASSERT(r == 0); + + /* Turn off raw mode. */ + r = uv_tty_set_mode(&tty_in, 0); + ASSERT(r == 0); + + /* TODO check the actual mode! */ + + uv_close((uv_handle_t*) &tty_in, NULL); + uv_close((uv_handle_t*) &tty_out, NULL); + + uv_run(loop); + + return 0; +} diff --git a/node-v0.8.14/deps/uv/test/test-udp-dgram-too-big.c b/node-v0.8.14/deps/uv/test/test-udp-dgram-too-big.c new file mode 100644 index 0000000..2d172c0 --- /dev/null +++ b/node-v0.8.14/deps/uv/test/test-udp-dgram-too-big.c @@ -0,0 +1,86 @@ +/* Copyright Joyent, Inc. and other Node contributors. All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ + +#include "uv.h" +#include "task.h" + +#include +#include +#include + +#define CHECK_HANDLE(handle) \ + ASSERT((uv_udp_t*)(handle) == &handle_) + +#define CHECK_REQ(req) \ + ASSERT((req) == &req_); + +static uv_udp_t handle_; +static uv_udp_send_t req_; + +static int send_cb_called; +static int close_cb_called; + + +static void close_cb(uv_handle_t* handle) { + CHECK_HANDLE(handle); + close_cb_called++; +} + + +static void send_cb(uv_udp_send_t* req, int status) { + CHECK_REQ(req); + CHECK_HANDLE(req->handle); + + ASSERT(status == -1); + ASSERT(uv_last_error(uv_default_loop()).code == UV_EMSGSIZE); + + uv_close((uv_handle_t*)req->handle, close_cb); + send_cb_called++; +} + + +TEST_IMPL(udp_dgram_too_big) { + char dgram[65536]; /* 64K MTU is unlikely, even on localhost */ + struct sockaddr_in addr; + uv_buf_t buf; + int r; + + memset(dgram, 42, sizeof dgram); /* silence valgrind */ + + r = uv_udp_init(uv_default_loop(), &handle_); + ASSERT(r == 0); + + buf = uv_buf_init(dgram, sizeof dgram); + addr = uv_ip4_addr("127.0.0.1", TEST_PORT); + + r = uv_udp_send(&req_, &handle_, &buf, 1, addr, send_cb); + ASSERT(r == 0); + + ASSERT(close_cb_called == 0); + ASSERT(send_cb_called == 0); + + uv_run(uv_default_loop()); + + ASSERT(send_cb_called == 1); + ASSERT(close_cb_called == 1); + + return 0; +} diff --git a/node-v0.8.14/deps/uv/test/test-udp-ipv6.c b/node-v0.8.14/deps/uv/test/test-udp-ipv6.c new file mode 100644 index 0000000..6ff36b3 --- /dev/null +++ b/node-v0.8.14/deps/uv/test/test-udp-ipv6.c @@ -0,0 +1,156 @@ +/* Copyright Joyent, Inc. and other Node contributors. All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ + +#include "uv.h" +#include "task.h" + +#include +#include +#include + +#define CHECK_HANDLE(handle) \ + ASSERT((uv_udp_t*)(handle) == &server \ + || (uv_udp_t*)(handle) == &client \ + || (uv_timer_t*)(handle) == &timeout) + +#define CHECK_REQ(req) \ + ASSERT((req) == &req_); + +static uv_udp_t client; +static uv_udp_t server; +static uv_udp_send_t req_; +static uv_timer_t timeout; + +static int send_cb_called; +static int recv_cb_called; +static int close_cb_called; + + +static uv_buf_t alloc_cb(uv_handle_t* handle, size_t suggested_size) { + static char slab[65536]; + CHECK_HANDLE(handle); + return uv_buf_init(slab, sizeof slab); +} + + +static void close_cb(uv_handle_t* handle) { + CHECK_HANDLE(handle); + close_cb_called++; +} + + +static void send_cb(uv_udp_send_t* req, int status) { + CHECK_REQ(req); + CHECK_HANDLE(req->handle); + ASSERT(status == 0); + send_cb_called++; +} + + +static void ipv6_recv_fail(uv_udp_t* handle, + ssize_t nread, + uv_buf_t buf, + struct sockaddr* addr, + unsigned flags) { + ASSERT(0 && "this function should not have been called"); +} + + +static void ipv6_recv_ok(uv_udp_t* handle, + ssize_t nread, + uv_buf_t buf, + struct sockaddr* addr, + unsigned flags) { + CHECK_HANDLE(handle); + ASSERT(nread >= 0); + + if (nread) + recv_cb_called++; +} + + +static void timeout_cb(uv_timer_t* timer, int status) { + uv_close((uv_handle_t*)&server, close_cb); + uv_close((uv_handle_t*)&client, close_cb); + uv_close((uv_handle_t*)&timeout, close_cb); +} + + +static void do_test(uv_udp_recv_cb recv_cb, int bind_flags) { + struct sockaddr_in6 addr6; + struct sockaddr_in addr; + uv_buf_t buf; + int r; + + addr6 = uv_ip6_addr("::0", TEST_PORT); + + r = uv_udp_init(uv_default_loop(), &server); + ASSERT(r == 0); + + r = uv_udp_bind6(&server, addr6, bind_flags); + ASSERT(r == 0); + + r = uv_udp_recv_start(&server, alloc_cb, recv_cb); + ASSERT(r == 0); + + r = uv_udp_init(uv_default_loop(), &client); + ASSERT(r == 0); + + buf = uv_buf_init("PING", 4); + addr = uv_ip4_addr("127.0.0.1", TEST_PORT); + + r = uv_udp_send(&req_, &client, &buf, 1, addr, send_cb); + ASSERT(r == 0); + + r = uv_timer_init(uv_default_loop(), &timeout); + ASSERT(r == 0); + + r = uv_timer_start(&timeout, timeout_cb, 500, 0); + ASSERT(r == 0); + + ASSERT(close_cb_called == 0); + ASSERT(send_cb_called == 0); + ASSERT(recv_cb_called == 0); + + uv_run(uv_default_loop()); + + ASSERT(close_cb_called == 3); +} + + +TEST_IMPL(udp_dual_stack) { + do_test(ipv6_recv_ok, 0); + + ASSERT(recv_cb_called == 1); + ASSERT(send_cb_called == 1); + + return 0; +} + + +TEST_IMPL(udp_ipv6_only) { + do_test(ipv6_recv_fail, UV_UDP_IPV6ONLY); + + ASSERT(recv_cb_called == 0); + ASSERT(send_cb_called == 1); + + return 0; +} diff --git a/node-v0.8.14/deps/uv/test/test-udp-multicast-join.c b/node-v0.8.14/deps/uv/test/test-udp-multicast-join.c new file mode 100644 index 0000000..b32ef07 --- /dev/null +++ b/node-v0.8.14/deps/uv/test/test-udp-multicast-join.c @@ -0,0 +1,139 @@ +/* Copyright Joyent, Inc. and other Node contributors. All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ + +#include "uv.h" +#include "task.h" + +#include +#include +#include + +#define CHECK_HANDLE(handle) \ + ASSERT((uv_udp_t*)(handle) == &server || (uv_udp_t*)(handle) == &client) + +static uv_udp_t server; +static uv_udp_t client; + +static int cl_recv_cb_called; + +static int sv_send_cb_called; + +static int close_cb_called; + +static uv_buf_t alloc_cb(uv_handle_t* handle, size_t suggested_size) { + static char slab[65536]; + + CHECK_HANDLE(handle); + ASSERT(suggested_size <= sizeof slab); + + return uv_buf_init(slab, sizeof slab); +} + + +static void close_cb(uv_handle_t* handle) { + CHECK_HANDLE(handle); + close_cb_called++; +} + + +static void sv_send_cb(uv_udp_send_t* req, int status) { + ASSERT(req != NULL); + ASSERT(status == 0); + CHECK_HANDLE(req->handle); + + sv_send_cb_called++; + + uv_close((uv_handle_t*) req->handle, close_cb); +} + + +static void cl_recv_cb(uv_udp_t* handle, + ssize_t nread, + uv_buf_t buf, + struct sockaddr* addr, + unsigned flags) { + CHECK_HANDLE(handle); + ASSERT(flags == 0); + + cl_recv_cb_called++; + + if (nread < 0) { + ASSERT(0 && "unexpected error"); + } + + if (nread == 0) { + /* Returning unused buffer */ + /* Don't count towards cl_recv_cb_called */ + ASSERT(addr == NULL); + return; + } + + ASSERT(addr != NULL); + ASSERT(nread == 4); + ASSERT(!memcmp("PING", buf.base, nread)); + + /* we are done with the client handle, we can close it */ + uv_close((uv_handle_t*) &client, close_cb); +} + + +TEST_IMPL(udp_multicast_join) { + int r; + uv_udp_send_t req; + uv_buf_t buf; + struct sockaddr_in addr = uv_ip4_addr("127.0.0.1", TEST_PORT); + + r = uv_udp_init(uv_default_loop(), &server); + ASSERT(r == 0); + + r = uv_udp_init(uv_default_loop(), &client); + ASSERT(r == 0); + + /* bind to the desired port */ + r = uv_udp_bind(&client, addr, 0); + ASSERT(r == 0); + + /* join the multicast channel */ + r = uv_udp_set_membership(&client, "239.255.0.1", NULL, UV_JOIN_GROUP); + ASSERT(r == 0); + + r = uv_udp_recv_start(&client, alloc_cb, cl_recv_cb); + ASSERT(r == 0); + + buf = uv_buf_init("PING", 4); + + /* server sends "PING" */ + r = uv_udp_send(&req, &server, &buf, 1, addr, sv_send_cb); + ASSERT(r == 0); + + ASSERT(close_cb_called == 0); + ASSERT(cl_recv_cb_called == 0); + ASSERT(sv_send_cb_called == 0); + + /* run the loop till all events are processed */ + uv_run(uv_default_loop()); + + ASSERT(cl_recv_cb_called == 1); + ASSERT(sv_send_cb_called == 1); + ASSERT(close_cb_called == 2); + + return 0; +} diff --git a/node-v0.8.14/deps/uv/test/test-udp-multicast-ttl.c b/node-v0.8.14/deps/uv/test/test-udp-multicast-ttl.c new file mode 100644 index 0000000..b2f1125 --- /dev/null +++ b/node-v0.8.14/deps/uv/test/test-udp-multicast-ttl.c @@ -0,0 +1,86 @@ +/* Copyright Joyent, Inc. and other Node contributors. All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ + +#include "uv.h" +#include "task.h" + +#include +#include +#include + +#define CHECK_HANDLE(handle) \ + ASSERT((uv_udp_t*)(handle) == &server || (uv_udp_t*)(handle) == &client) + +static uv_udp_t server; +static uv_udp_t client; + +static int sv_send_cb_called; +static int close_cb_called; + + +static void close_cb(uv_handle_t* handle) { + CHECK_HANDLE(handle); + close_cb_called++; +} + + +static void sv_send_cb(uv_udp_send_t* req, int status) { + ASSERT(req != NULL); + ASSERT(status == 0); + CHECK_HANDLE(req->handle); + + sv_send_cb_called++; + + uv_close((uv_handle_t*) req->handle, close_cb); +} + + +TEST_IMPL(udp_multicast_ttl) { + int r; + uv_udp_send_t req; + uv_buf_t buf; + struct sockaddr_in addr = uv_ip4_addr("239.255.0.1", TEST_PORT); + + r = uv_udp_init(uv_default_loop(), &server); + ASSERT(r == 0); + + r = uv_udp_bind(&server, uv_ip4_addr("0.0.0.0", 0), 0); + ASSERT(r == 0); + + r = uv_udp_set_multicast_ttl(&server, 32); + ASSERT(r == 0); + + /* server sends "PING" */ + buf = uv_buf_init("PING", 4); + r = uv_udp_send(&req, &server, &buf, 1, addr, sv_send_cb); + ASSERT(r == 0); + + ASSERT(close_cb_called == 0); + ASSERT(sv_send_cb_called == 0); + + /* run the loop till all events are processed */ + uv_run(uv_default_loop()); + + ASSERT(sv_send_cb_called == 1); + ASSERT(close_cb_called == 1); + + return 0; +} diff --git a/node-v0.8.14/deps/uv/test/test-udp-options.c b/node-v0.8.14/deps/uv/test/test-udp-options.c new file mode 100644 index 0000000..4ff650d --- /dev/null +++ b/node-v0.8.14/deps/uv/test/test-udp-options.c @@ -0,0 +1,86 @@ +/* Copyright Joyent, Inc. and other Node contributors. All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ + +#include "uv.h" +#include "task.h" + +#include +#include +#include + + +TEST_IMPL(udp_options) { + static int invalid_ttls[] = { -1, 0, 256 }; + uv_loop_t* loop; + uv_udp_t h; + int i, r; + + loop = uv_default_loop(); + + r = uv_udp_init(loop, &h); + ASSERT(r == 0); + + uv_unref((uv_handle_t*)&h); /* don't keep the loop alive */ + + r = uv_udp_bind(&h, uv_ip4_addr("0.0.0.0", TEST_PORT), 0); + ASSERT(r == 0); + + r = uv_udp_set_broadcast(&h, 1); + r |= uv_udp_set_broadcast(&h, 1); + r |= uv_udp_set_broadcast(&h, 0); + r |= uv_udp_set_broadcast(&h, 0); + ASSERT(r == 0); + + /* values 1-255 should work */ + for (i = 1; i <= 255; i++) { + r = uv_udp_set_ttl(&h, i); + ASSERT(r == 0); + } + + for (i = 0; i < (int) ARRAY_SIZE(invalid_ttls); i++) { + r = uv_udp_set_ttl(&h, invalid_ttls[i]); + ASSERT(r == -1); + ASSERT(uv_last_error(loop).code == UV_EINVAL); + } + + r = uv_udp_set_multicast_loop(&h, 1); + r |= uv_udp_set_multicast_loop(&h, 1); + r |= uv_udp_set_multicast_loop(&h, 0); + r |= uv_udp_set_multicast_loop(&h, 0); + ASSERT(r == 0); + + /* values 0-255 should work */ + for (i = 0; i <= 255; i++) { + r = uv_udp_set_multicast_ttl(&h, i); + ASSERT(r == 0); + } + + /* anything >255 should fail */ + r = uv_udp_set_multicast_ttl(&h, 256); + ASSERT(r == -1); + ASSERT(uv_last_error(loop).code == UV_EINVAL); + /* don't test ttl=-1, it's a valid value on some platforms */ + + r = uv_run(loop); + ASSERT(r == 0); + + return 0; +} diff --git a/node-v0.8.14/deps/uv/test/test-udp-send-and-recv.c b/node-v0.8.14/deps/uv/test/test-udp-send-and-recv.c new file mode 100644 index 0000000..ab47e91 --- /dev/null +++ b/node-v0.8.14/deps/uv/test/test-udp-send-and-recv.c @@ -0,0 +1,208 @@ +/* Copyright Joyent, Inc. and other Node contributors. All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ + +#include "uv.h" +#include "task.h" + +#include +#include +#include + +#define CHECK_HANDLE(handle) \ + ASSERT((uv_udp_t*)(handle) == &server || (uv_udp_t*)(handle) == &client) + +static uv_udp_t server; +static uv_udp_t client; + +static int cl_send_cb_called; +static int cl_recv_cb_called; + +static int sv_send_cb_called; +static int sv_recv_cb_called; + +static int close_cb_called; + + +static uv_buf_t alloc_cb(uv_handle_t* handle, size_t suggested_size) { + static char slab[65536]; + + CHECK_HANDLE(handle); + ASSERT(suggested_size <= sizeof slab); + + return uv_buf_init(slab, sizeof slab); +} + + +static void close_cb(uv_handle_t* handle) { + CHECK_HANDLE(handle); + close_cb_called++; +} + + +static void cl_recv_cb(uv_udp_t* handle, + ssize_t nread, + uv_buf_t buf, + struct sockaddr* addr, + unsigned flags) { + CHECK_HANDLE(handle); + ASSERT(flags == 0); + + if (nread < 0) { + ASSERT(0 && "unexpected error"); + } + + if (nread == 0) { + /* Returning unused buffer */ + /* Don't count towards cl_recv_cb_called */ + ASSERT(addr == NULL); + return; + } + + ASSERT(addr != NULL); + ASSERT(nread == 4); + ASSERT(!memcmp("PONG", buf.base, nread)); + + cl_recv_cb_called++; + + uv_close((uv_handle_t*) handle, close_cb); +} + + +static void cl_send_cb(uv_udp_send_t* req, int status) { + int r; + + ASSERT(req != NULL); + ASSERT(status == 0); + CHECK_HANDLE(req->handle); + + r = uv_udp_recv_start(req->handle, alloc_cb, cl_recv_cb); + ASSERT(r == 0); + + cl_send_cb_called++; +} + + +static void sv_send_cb(uv_udp_send_t* req, int status) { + ASSERT(req != NULL); + ASSERT(status == 0); + CHECK_HANDLE(req->handle); + + uv_close((uv_handle_t*) req->handle, close_cb); + free(req); + + sv_send_cb_called++; +} + + +static void sv_recv_cb(uv_udp_t* handle, + ssize_t nread, + uv_buf_t buf, + struct sockaddr* addr, + unsigned flags) { + uv_udp_send_t* req; + int r; + + if (nread < 0) { + ASSERT(0 && "unexpected error"); + } + + if (nread == 0) { + /* Returning unused buffer */ + /* Don't count towards sv_recv_cb_called */ + ASSERT(addr == NULL); + return; + } + + CHECK_HANDLE(handle); + ASSERT(flags == 0); + + ASSERT(addr != NULL); + ASSERT(nread == 4); + ASSERT(!memcmp("PING", buf.base, nread)); + + /* FIXME? `uv_udp_recv_stop` does what it says: recv_cb is not called + * anymore. That's problematic because the read buffer won't be returned + * either... Not sure I like that but it's consistent with `uv_read_stop`. + */ + r = uv_udp_recv_stop(handle); + ASSERT(r == 0); + + req = malloc(sizeof *req); + ASSERT(req != NULL); + + buf = uv_buf_init("PONG", 4); + + r = uv_udp_send(req, + handle, + &buf, + 1, + *(struct sockaddr_in*)addr, + sv_send_cb); + ASSERT(r == 0); + + sv_recv_cb_called++; +} + + +TEST_IMPL(udp_send_and_recv) { + struct sockaddr_in addr; + uv_udp_send_t req; + uv_buf_t buf; + int r; + + addr = uv_ip4_addr("0.0.0.0", TEST_PORT); + + r = uv_udp_init(uv_default_loop(), &server); + ASSERT(r == 0); + + r = uv_udp_bind(&server, addr, 0); + ASSERT(r == 0); + + r = uv_udp_recv_start(&server, alloc_cb, sv_recv_cb); + ASSERT(r == 0); + + addr = uv_ip4_addr("127.0.0.1", TEST_PORT); + + r = uv_udp_init(uv_default_loop(), &client); + ASSERT(r == 0); + + /* client sends "PING", expects "PONG" */ + buf = uv_buf_init("PING", 4); + + r = uv_udp_send(&req, &client, &buf, 1, addr, cl_send_cb); + ASSERT(r == 0); + + ASSERT(close_cb_called == 0); + ASSERT(cl_send_cb_called == 0); + ASSERT(cl_recv_cb_called == 0); + ASSERT(sv_send_cb_called == 0); + ASSERT(sv_recv_cb_called == 0); + + uv_run(uv_default_loop()); + + ASSERT(cl_send_cb_called == 1); + ASSERT(cl_recv_cb_called == 1); + ASSERT(sv_send_cb_called == 1); + ASSERT(sv_recv_cb_called == 1); + ASSERT(close_cb_called == 2); + + return 0; +} diff --git a/node-v0.8.14/deps/uv/test/test-util.c b/node-v0.8.14/deps/uv/test/test-util.c new file mode 100644 index 0000000..d61d3b1 --- /dev/null +++ b/node-v0.8.14/deps/uv/test/test-util.c @@ -0,0 +1,97 @@ +/* Copyright Joyent, Inc. and other Node contributors. All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ + +#include "uv.h" +#include "task.h" + +#include + +#define memeq(a, b, c) (memcmp((a), (b), (c)) == 0) + + +TEST_IMPL(strlcpy) { + size_t r; + + { + char dst[2] = "A"; + r = uv_strlcpy(dst, "", 0); + ASSERT(r == 0); + ASSERT(memeq(dst, "A", 1)); + } + + { + char dst[2] = "A"; + r = uv_strlcpy(dst, "B", 1); + ASSERT(r == 0); + ASSERT(memeq(dst, "", 1)); + } + + { + char dst[2] = "A"; + r = uv_strlcpy(dst, "B", 2); + ASSERT(r == 1); + ASSERT(memeq(dst, "B", 2)); + } + + { + char dst[3] = "AB"; + r = uv_strlcpy(dst, "CD", 3); + ASSERT(r == 2); + ASSERT(memeq(dst, "CD", 3)); + } + + return 0; +} + + +TEST_IMPL(strlcat) { + size_t r; + + { + char dst[2] = "A"; + r = uv_strlcat(dst, "B", 1); + ASSERT(r == 1); + ASSERT(memeq(dst, "A", 2)); + } + + { + char dst[2] = "A"; + r = uv_strlcat(dst, "B", 2); + ASSERT(r == 1); + ASSERT(memeq(dst, "A", 2)); + } + + { + char dst[3] = "A"; + r = uv_strlcat(dst, "B", 3); + ASSERT(r == 2); + ASSERT(memeq(dst, "AB", 3)); + } + + { + char dst[5] = "AB"; + r = uv_strlcat(dst, "CD", 5); + ASSERT(r == 4); + ASSERT(memeq(dst, "ABCD", 5)); + } + + return 0; +} diff --git a/node-v0.8.14/deps/uv/test/test-walk-handles.c b/node-v0.8.14/deps/uv/test/test-walk-handles.c new file mode 100644 index 0000000..a72c095 --- /dev/null +++ b/node-v0.8.14/deps/uv/test/test-walk-handles.c @@ -0,0 +1,77 @@ +/* Copyright Joyent, Inc. and other Node contributors. All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ + +#include "uv.h" +#include "task.h" + +#include +#include + +static char magic_cookie[] = "magic cookie"; +static int seen_timer_handle; +static uv_timer_t timer; + + +static void walk_cb(uv_handle_t* handle, void* arg) { + ASSERT(arg == (void*)magic_cookie); + + if (handle == (uv_handle_t*)&timer) { + seen_timer_handle++; + } else { + ASSERT(0 && "unexpected handle"); + } +} + + +static void timer_cb(uv_timer_t* handle, int status) { + ASSERT(handle == &timer); + ASSERT(status == 0); + + uv_walk(handle->loop, walk_cb, magic_cookie); + uv_close((uv_handle_t*)handle, NULL); +} + + +TEST_IMPL(walk_handles) { + uv_loop_t* loop; + int r; + + loop = uv_default_loop(); + + r = uv_timer_init(loop, &timer); + ASSERT(r == 0); + + r = uv_timer_start(&timer, timer_cb, 1, 0); + ASSERT(r == 0); + + /* Start event loop, expect to see the timer handle in walk_cb. */ + ASSERT(seen_timer_handle == 0); + r = uv_run(loop); + ASSERT(r == 0); + ASSERT(seen_timer_handle == 1); + + /* Loop is finished, walk_cb should not see our timer handle. */ + seen_timer_handle = 0; + uv_walk(loop, walk_cb, magic_cookie); + ASSERT(seen_timer_handle == 0); + + return 0; +} diff --git a/node-v0.8.14/deps/uv/uv.gyp b/node-v0.8.14/deps/uv/uv.gyp new file mode 100644 index 0000000..96c6b72 --- /dev/null +++ b/node-v0.8.14/deps/uv/uv.gyp @@ -0,0 +1,453 @@ +{ + 'target_defaults': { + 'conditions': [ + ['OS != "win"', { + 'defines': [ + '_LARGEFILE_SOURCE', + '_FILE_OFFSET_BITS=64', + '_GNU_SOURCE', + 'EIO_STACKSIZE=262144' + ], + 'conditions': [ + ['OS=="solaris"', { + 'cflags': ['-pthreads'], + 'ldlags': ['-pthreads'], + }, { + 'cflags': ['-pthread'], + 'ldlags': ['-pthread'], + }], + ], + }], + ], + }, + + 'targets': [ + { + 'target_name': 'uv', + 'type': '<(library)', + 'include_dirs': [ + 'include', + 'include/uv-private', + 'src/', + ], + 'direct_dependent_settings': { + 'include_dirs': [ 'include' ], + 'conditions': [ + ['OS=="linux"', { + 'libraries': [ '-ldl' ], + }], + ], + }, + + 'defines': [ + 'HAVE_CONFIG_H' + ], + 'sources': [ + 'common.gypi', + 'include/ares.h', + 'include/ares_version.h', + 'include/uv.h', + 'include/uv-private/ngx-queue.h', + 'include/uv-private/tree.h', + 'src/cares.c', + 'src/fs-poll.c', + 'src/uv-common.c', + 'src/uv-common.h', + 'src/ares/ares_cancel.c', + 'src/ares/ares__close_sockets.c', + 'src/ares/ares_data.c', + 'src/ares/ares_data.h', + 'src/ares/ares_destroy.c', + 'src/ares/ares_dns.h', + 'src/ares/ares_expand_name.c', + 'src/ares/ares_expand_string.c', + 'src/ares/ares_fds.c', + 'src/ares/ares_free_hostent.c', + 'src/ares/ares_free_string.c', + 'src/ares/ares_getenv.h', + 'src/ares/ares_gethostbyaddr.c', + 'src/ares/ares_gethostbyname.c', + 'src/ares/ares__get_hostent.c', + 'src/ares/ares_getnameinfo.c', + 'src/ares/ares_getopt.c', + 'src/ares/ares_getopt.h', + 'src/ares/ares_getsock.c', + 'src/ares/ares_init.c', + 'src/ares/ares_ipv6.h', + 'src/ares/ares_library_init.c', + 'src/ares/ares_library_init.h', + 'src/ares/ares_llist.c', + 'src/ares/ares_llist.h', + 'src/ares/ares_mkquery.c', + 'src/ares/ares_nowarn.c', + 'src/ares/ares_nowarn.h', + 'src/ares/ares_options.c', + 'src/ares/ares_parse_aaaa_reply.c', + 'src/ares/ares_parse_a_reply.c', + 'src/ares/ares_parse_mx_reply.c', + 'src/ares/ares_parse_ns_reply.c', + 'src/ares/ares_parse_ptr_reply.c', + 'src/ares/ares_parse_srv_reply.c', + 'src/ares/ares_parse_txt_reply.c', + 'src/ares/ares_platform.h', + 'src/ares/ares_private.h', + 'src/ares/ares_process.c', + 'src/ares/ares_query.c', + 'src/ares/ares__read_line.c', + 'src/ares/ares_rules.h', + 'src/ares/ares_search.c', + 'src/ares/ares_send.c', + 'src/ares/ares_setup.h', + 'src/ares/ares_strcasecmp.c', + 'src/ares/ares_strcasecmp.h', + 'src/ares/ares_strdup.c', + 'src/ares/ares_strdup.h', + 'src/ares/ares_strerror.c', + 'src/ares/ares_timeout.c', + 'src/ares/ares__timeval.c', + 'src/ares/ares_version.c', + 'src/ares/ares_writev.c', + 'src/ares/ares_writev.h', + 'src/ares/bitncmp.c', + 'src/ares/bitncmp.h', + 'src/ares/inet_net_pton.c', + 'src/ares/inet_net_pton.h', + 'src/ares/inet_ntop.c', + 'src/ares/inet_ntop.h', + 'src/ares/nameser.h', + 'src/ares/setup_once.h', + 'src/ares/windows_port.c', + ], + 'conditions': [ + [ 'OS=="win"', { + 'include_dirs': [ + 'src/ares/config_win32' + ], + 'defines': [ + '_WIN32_WINNT=0x0600', + 'EIO_STACKSIZE=262144', + '_GNU_SOURCE', + ], + 'sources': [ + 'include/uv-private/uv-win.h', + 'src/ares/config_win32/ares_config.h', + 'src/ares/windows_port.c', + 'src/ares/ares_getenv.c', + 'src/ares/ares_iphlpapi.h', + 'src/ares/ares_platform.c', + 'src/win/async.c', + 'src/win/core.c', + 'src/win/dl.c', + 'src/win/error.c', + 'src/win/fs.c', + 'src/win/fs-event.c', + 'src/win/getaddrinfo.c', + 'src/win/handle.c', + 'src/win/handle-inl.h', + 'src/win/internal.h', + 'src/win/loop-watcher.c', + 'src/win/pipe.c', + 'src/win/thread.c', + 'src/win/poll.c', + 'src/win/process.c', + 'src/win/process-stdio.c', + 'src/win/req.c', + 'src/win/req-inl.h', + 'src/win/stream.c', + 'src/win/stream-inl.h', + 'src/win/tcp.c', + 'src/win/tty.c', + 'src/win/threadpool.c', + 'src/win/timer.c', + 'src/win/udp.c', + 'src/win/util.c', + 'src/win/winapi.c', + 'src/win/winapi.h', + 'src/win/winsock.c', + 'src/win/winsock.h', + ], + 'link_settings': { + 'libraries': [ + '-lws2_32.lib', + '-lpsapi.lib', + '-liphlpapi.lib' + ], + }, + }, { # Not Windows i.e. POSIX + 'cflags': [ + '-g', + '--std=gnu89', + '-pedantic', + '-Wall', + '-Wextra', + '-Wno-unused-parameter' + ], + 'sources': [ + 'include/uv-private/eio.h', + 'include/uv-private/ev.h', + 'include/uv-private/uv-unix.h', + 'src/unix/async.c', + 'src/unix/core.c', + 'src/unix/dl.c', + 'src/unix/eio/ecb.h', + 'src/unix/eio/eio.c', + 'src/unix/eio/xthread.h', + 'src/unix/error.c', + 'src/unix/ev/ev.c', + 'src/unix/ev/ev_vars.h', + 'src/unix/ev/ev_wrap.h', + 'src/unix/ev/event.h', + 'src/unix/fs.c', + 'src/unix/internal.h', + 'src/unix/loop.c', + 'src/unix/loop-watcher.c', + 'src/unix/pipe.c', + 'src/unix/poll.c', + 'src/unix/process.c', + 'src/unix/stream.c', + 'src/unix/tcp.c', + 'src/unix/thread.c', + 'src/unix/timer.c', + 'src/unix/tty.c', + 'src/unix/udp.c', + 'src/unix/uv-eio.c', + 'src/unix/uv-eio.h', + ], + 'include_dirs': [ 'src/unix/ev', ], + 'libraries': [ '-lm' ] + }], + [ 'OS=="mac"', { + 'include_dirs': [ 'src/ares/config_darwin' ], + 'sources': [ 'src/unix/darwin.c' ], + 'direct_dependent_settings': { + 'libraries': [ + '$(SDKROOT)/System/Library/Frameworks/CoreServices.framework', + ], + }, + 'defines': [ + '_DARWIN_USE_64_BIT_INODE=1', + 'EV_CONFIG_H="config_darwin.h"', + 'EIO_CONFIG_H="config_darwin.h"', + ] + }], + [ 'OS=="linux"', { + 'include_dirs': [ 'src/ares/config_linux' ], + 'sources': [ + 'src/unix/linux/linux-core.c', + 'src/unix/linux/inotify.c', + 'src/unix/linux/syscalls.c', + 'src/unix/linux/syscalls.h', + ], + 'defines': [ + 'EV_CONFIG_H="config_linux.h"', + 'EIO_CONFIG_H="config_linux.h"', + ], + 'direct_dependent_settings': { + 'libraries': [ '-lrt' ], + }, + }], + [ 'OS=="solaris"', { + 'include_dirs': [ 'src/ares/config_sunos' ], + 'sources': [ 'src/unix/sunos.c' ], + 'defines': [ + '__EXTENSIONS__', + '_XOPEN_SOURCE=500', + 'EV_CONFIG_H="config_sunos.h"', + 'EIO_CONFIG_H="config_sunos.h"', + ], + 'direct_dependent_settings': { + 'libraries': [ + '-lkstat', + '-lsocket', + '-lnsl', + ], + }, + }], + [ 'OS=="freebsd"', { + 'include_dirs': [ 'src/ares/config_freebsd' ], + 'sources': [ 'src/unix/freebsd.c' ], + 'defines': [ + 'EV_CONFIG_H="config_freebsd.h"', + 'EIO_CONFIG_H="config_freebsd.h"', + ], + 'direct_dependent_settings': { + 'libraries': [ + '-lkvm', + ], + }, + }], + [ 'OS=="openbsd"', { + 'include_dirs': [ 'src/ares/config_openbsd' ], + 'sources': [ 'src/unix/openbsd.c' ], + 'defines': [ + 'EV_CONFIG_H="config_openbsd.h"', + 'EIO_CONFIG_H="config_openbsd.h"', + ], + }], + [ 'OS=="mac" or OS=="freebsd" or OS=="openbsd" or OS=="netbsd"', { + 'sources': [ 'src/unix/kqueue.c' ], + }], + ] + }, + + { + 'target_name': 'run-tests', + 'type': 'executable', + 'dependencies': [ 'uv' ], + 'sources': [ + 'test/blackhole-server.c', + 'test/echo-server.c', + 'test/run-tests.c', + 'test/runner.c', + 'test/runner.h', + 'test/test-get-loadavg.c', + 'test/task.h', + 'test/test-util.c', + 'test/test-async.c', + 'test/test-error.c', + 'test/test-callback-stack.c', + 'test/test-callback-order.c', + 'test/test-connection-fail.c', + 'test/test-cwd-and-chdir.c', + 'test/test-delayed-accept.c', + 'test/test-fail-always.c', + 'test/test-fs.c', + 'test/test-fs-event.c', + 'test/test-get-currentexe.c', + 'test/test-get-memory.c', + 'test/test-getaddrinfo.c', + 'test/test-gethostbyname.c', + 'test/test-getsockname.c', + 'test/test-hrtime.c', + 'test/test-idle.c', + 'test/test-ipc.c', + 'test/test-ipc-send-recv.c', + 'test/test-list.h', + 'test/test-loop-handles.c', + 'test/test-walk-handles.c', + 'test/test-multiple-listen.c', + 'test/test-pass-always.c', + 'test/test-ping-pong.c', + 'test/test-pipe-bind-error.c', + 'test/test-pipe-connect-error.c', + 'test/test-platform-output.c', + 'test/test-poll.c', + 'test/test-poll-close.c', + 'test/test-process-title.c', + 'test/test-ref.c', + 'test/test-run-once.c', + 'test/test-semaphore.c', + 'test/test-shutdown-close.c', + 'test/test-shutdown-eof.c', + 'test/test-spawn.c', + 'test/test-fs-poll.c', + 'test/test-stdio-over-pipes.c', + 'test/test-tcp-bind-error.c', + 'test/test-tcp-bind6-error.c', + 'test/test-tcp-close.c', + 'test/test-tcp-close-while-connecting.c', + 'test/test-tcp-connect-error-after-write.c', + 'test/test-tcp-shutdown-after-write.c', + 'test/test-tcp-flags.c', + 'test/test-tcp-connect-error.c', + 'test/test-tcp-connect-timeout.c', + 'test/test-tcp-connect6-error.c', + 'test/test-tcp-write-error.c', + 'test/test-tcp-write-to-half-open-connection.c', + 'test/test-tcp-writealot.c', + 'test/test-tcp-unexpected-read.c', + 'test/test-threadpool.c', + 'test/test-mutexes.c', + 'test/test-thread.c', + 'test/test-timer-again.c', + 'test/test-timer.c', + 'test/test-tty.c', + 'test/test-udp-dgram-too-big.c', + 'test/test-udp-ipv6.c', + 'test/test-udp-options.c', + 'test/test-udp-send-and-recv.c', + 'test/test-udp-multicast-join.c', + 'test/test-counters-init.c', + 'test/test-dlerror.c', + 'test/test-udp-multicast-ttl.c', + ], + 'conditions': [ + [ 'OS=="win"', { + 'sources': [ + 'test/runner-win.c', + 'test/runner-win.h' + ], + 'libraries': [ 'ws2_32.lib' ] + }, { # POSIX + 'defines': [ '_GNU_SOURCE' ], + 'sources': [ + 'test/runner-unix.c', + 'test/runner-unix.h', + ], + }], + [ 'OS=="solaris"', { # make test-fs.c compile, needs _POSIX_C_SOURCE + 'defines': [ + '__EXTENSIONS__', + '_XOPEN_SOURCE=500', + ], + }], + ], + 'msvs-settings': { + 'VCLinkerTool': { + 'SubSystem': 1, # /subsystem:console + }, + }, + }, + + { + 'target_name': 'run-benchmarks', + 'type': 'executable', + 'dependencies': [ 'uv' ], + 'sources': [ + 'test/benchmark-ares.c', + 'test/benchmark-fs-stat.c', + 'test/benchmark-getaddrinfo.c', + 'test/benchmark-list.h', + 'test/benchmark-loop-count.c', + 'test/benchmark-million-timers.c', + 'test/benchmark-ping-pongs.c', + 'test/benchmark-pound.c', + 'test/benchmark-pump.c', + 'test/benchmark-sizes.c', + 'test/benchmark-spawn.c', + 'test/benchmark-thread.c', + 'test/benchmark-tcp-write-batch.c', + 'test/benchmark-udp-packet-storm.c', + 'test/dns-server.c', + 'test/echo-server.c', + 'test/blackhole-server.c', + 'test/run-benchmarks.c', + 'test/runner.c', + 'test/runner.h', + 'test/task.h', + ], + 'conditions': [ + [ 'OS=="win"', { + 'sources': [ + 'test/runner-win.c', + 'test/runner-win.h', + ], + 'libraries': [ 'ws2_32.lib' ] + }, { # POSIX + 'defines': [ '_GNU_SOURCE' ], + 'sources': [ + 'test/runner-unix.c', + 'test/runner-unix.h', + ] + }] + ], + 'msvs-settings': { + 'VCLinkerTool': { + 'SubSystem': 1, # /subsystem:console + }, + }, + } + ] +} + + diff --git a/node-v0.8.14/deps/uv/vcbuild.bat b/node-v0.8.14/deps/uv/vcbuild.bat new file mode 100644 index 0000000..644f574 --- /dev/null +++ b/node-v0.8.14/deps/uv/vcbuild.bat @@ -0,0 +1,105 @@ +@echo off + +cd %~dp0 + +if /i "%1"=="help" goto help +if /i "%1"=="--help" goto help +if /i "%1"=="-help" goto help +if /i "%1"=="/help" goto help +if /i "%1"=="?" goto help +if /i "%1"=="-?" goto help +if /i "%1"=="--?" goto help +if /i "%1"=="/?" goto help + +@rem Process arguments. +set config= +set target=Build +set noprojgen= +set nobuild= +set run= + +:next-arg +if "%1"=="" goto args-done +if /i "%1"=="debug" set config=Debug&goto arg-ok +if /i "%1"=="release" set config=Release&goto arg-ok +if /i "%1"=="test" set run=run-tests.exe&goto arg-ok +if /i "%1"=="bench" set run=run-benchmarks.exe&goto arg-ok +if /i "%1"=="clean" set target=Clean&goto arg-ok +if /i "%1"=="noprojgen" set noprojgen=1&goto arg-ok +if /i "%1"=="nobuild" set nobuild=1&goto arg-ok +:arg-ok +shift +goto next-arg +:args-done + +if not "%config%"=="" goto project-gen +if "%run%"=="run-tests.exe" set config=Debug& goto project-gen +if "%run%"=="run-benchmarks.exe" set config=Release& goto project-gen +set config=Debug + +:project-gen +@rem Skip project generation if requested. +if defined noprojgen goto msbuild + +@rem Generate the VS project. + +if exist build\gyp goto have_gyp +echo svn co http://gyp.googlecode.com/svn/trunk@983 build/gyp +svn co http://gyp.googlecode.com/svn/trunk@983 build/gyp +if errorlevel 1 goto gyp_install_failed +goto have_gyp + +:gyp_install_failed +echo Failed to download gyp. Make sure you have subversion installed, or +echo manually install gyp into %~dp0build\gyp. +goto exit + +:have_gyp +python gyp_uv +if errorlevel 1 goto create-msvs-files-failed +if not exist uv.sln goto create-msvs-files-failed +echo Project files generated. + +:msbuild +@rem Skip project generation if requested. +if defined nobuild goto run + +@rem If not running in the VS build env, try to start it. If that fails, bail +@rem out. +if defined VCINSTALLDIR goto msbuild-found +if not defined VS100COMNTOOLS goto msbuild-not-found +if not exist "%VS100COMNTOOLS%\..\..\vc\vcvarsall.bat" goto msbuild-not-found +call "%VS100COMNTOOLS%\..\..\vc\vcvarsall.bat" +if not defined VCINSTALLDIR goto msbuild-not-found +goto msbuild-found + +:msbuild-not-found +echo Build skipped. To build, this file needs to run from VS cmd prompt. +goto run + +@rem Build the sln with msbuild. +:msbuild-found +msbuild uv.sln /t:%target% /p:Configuration=%config% /clp:NoSummary;NoItemAndPropertyList;Verbosity=minimal /nologo +if errorlevel 1 goto exit + +:run +@rem Run tests if requested. +if "%run%"=="" goto exit +if not exist %config%\%run% goto exit +echo running '%config%\%run%' +%config%\%run% +goto exit + +:create-msvs-files-failed +echo Failed to create vc project files. +goto exit + +:help +echo vcbuild.bat [debug/release] [test/bench] [clean] [noprojgen] [nobuild] +echo Examples: +echo vcbuild.bat : builds debug build +echo vcbuild.bat test : builds debug build and runs tests +echo vcbuild.bat release bench: builds release build and runs benchmarks +goto exit + +:exit diff --git a/node-v0.8.14/deps/v8/.gitignore b/node-v0.8.14/deps/v8/.gitignore new file mode 100644 index 0000000..088daea --- /dev/null +++ b/node-v0.8.14/deps/v8/.gitignore @@ -0,0 +1,36 @@ +*.a +*.exe +*.idb +*.lib +*.log +*.map +*.mk +*.ncb +*.pdb +*.pyc +*.scons* +*.so +*.suo +*.user +*.xcodeproj +#*# +*~ +.cpplint-cache +d8 +d8_g +shell +shell_g +/build/gyp +/obj/ +/out/ +/test/es5conform/data +/test/mozilla/data +/test/sputnik/sputniktests +/test/test262/data +/tools/oom_dump/oom_dump +/tools/oom_dump/oom_dump.o +/tools/visual_studio/Debug +/tools/visual_studio/Release +/xcodebuild/ +TAGS +*.Makefile diff --git a/node-v0.8.14/deps/v8/AUTHORS b/node-v0.8.14/deps/v8/AUTHORS new file mode 100644 index 0000000..6e46b3d --- /dev/null +++ b/node-v0.8.14/deps/v8/AUTHORS @@ -0,0 +1,55 @@ +# Below is a list of people and organizations that have contributed +# to the V8 project. Names should be added to the list like so: +# +# Name/Organization + +Google Inc. +Sigma Designs Inc. +ARM Ltd. +Hewlett-Packard Development Company, LP +Igalia, S.L. +Joyent, Inc. + +Akinori MUSHA +Alexander Botero-Lowry +Alexander Karpinsky +Alexandre Vassalotti +Andreas Anyuru +Bert Belder +Burcu Dogan +Craig Schlenter +Daniel Andersson +Daniel James +Dineel D Sule +Erich Ocean +Fedor Indutny +Filipe David Manana +Ioseb Dzmanashvili +Jan de Mooij +Jay Freeman +Joel Stanley +John Jozwiak +Jonathan Liu +Kun Zhang +Martyn Capewell +Mathias Bynens +Matt Hanselman +Maxim Mossienko +Michael Lutz +Michael Smith +Mike Gilbert +Paolo Giarrusso +Patrick Gansterer +Peter Varga +Rafal Krypa +Rene Rebe +Robert Mustacchi +Rodolph Perfetta +Ryan Dahl +Sanjoy Das +Subrato K De +Tobias Burnus +Vlad Burlik +Yuqiang Xian +Zaheer Ahmad +Zhongping Wang diff --git a/node-v0.8.14/deps/v8/ChangeLog b/node-v0.8.14/deps/v8/ChangeLog new file mode 100644 index 0000000..fae15e5 --- /dev/null +++ b/node-v0.8.14/deps/v8/ChangeLog @@ -0,0 +1,4248 @@ +2012-06-13: Version 3.11.10 + + Implemented heap profiler memory usage reporting. + + Preserved error message during finally block in try..finally. + (Chromium issue 129171) + + Fixed EnsureCanContainElements to properly handle double values. + (issue 2170) + + Improved heuristics to keep objects in fast mode with inherited + constructors. + + Performance and stability improvements on all platforms. + + +2012-06-06: Version 3.11.9 + + Implemented ES5-conformant semantics for inherited setters and read-only + properties. Currently behind --es5_readonly flag, because it breaks + WebKit bindings. + + Exposed last seen heap object id via v8 public api. + + Performance and stability improvements on all platforms. + + +2012-05-31: Version 3.11.8 + + Avoid overdeep recursion in regexp where a guarded expression with a + minimum repetition count is inside another quantifier. + (Chromium issue 129926) + + Fixed missing write barrier in store field stub. + (issues 2143, 1465, Chromium issue 129355) + + Proxies: Fixed receiver for setters inherited from proxies. + Proxies: Fixed ToStringArray function so that it does not reject some + keys. + (issue 1543) + + Performance and stability improvements on all platforms. + + +2012-05-29: Version 3.11.7 + + Get better function names in stack traces. + + Performance and stability improvements on all platforms. + + +2012-05-24: Version 3.11.6 + + Fixed RegExp.prototype.toString for incompatible receivers + (issue 1981). + + Performance and stability improvements on all platforms. + + +2012-05-23: Version 3.11.5 + + Performance and stability improvements on all platforms. + + +2012-05-22: Version 3.11.4 + + Some cleanup to common.gypi. This fixes some host/target combinations + that weren't working in the Make build on Mac. + + Handle EINTR in socket functions and continue incomplete sends. + (issue 2098) + + Fixed python deprecations. (issue 1391) + + Made socket send and receive more robust and return 0 on failure. + (Chromium issue 15719) + + Fixed GCC 4.7 (C++11) compilation. (issue 2136) + + Set '-m32' option for host and target platforms + + Performance and stability improvements on all platforms. + + +2012-05-18: Version 3.11.3 + + Disable optimization for functions that have scopes that cannot be + reconstructed from the context chain. (issue 2071) + + Define V8_EXPORT to nothing for clients of v8. (Chromium issue 90078) + + Correctly check for native error objects. (Chromium issue 2138) + + Performance and stability improvements on all platforms. + + +2012-05-16: Version 3.11.2 + + Revert r11496. (Chromium issue 128146) + + Implement map collection for incremental marking. (issue 1465) + + Add toString method to CallSite (which describes a frame of the + stack trace). + + +2012-05-15: Version 3.11.1 + + Added a readbuffer function to d8 that reads a file into an ArrayBuffer. + + Fix freebsd build. (V8 issue 2126) + + Performance and stability improvements on all platforms. + + +2012-05-11: Version 3.11.0 + + Fixed compose-discard crasher from r11524 (issue 2123). + + Activated new global semantics by default. Global variables can + now shadow properties of the global object (ES5.1 erratum). + + Properly set ElementsKind of empty FAST_DOUBLE_ELEMENTS arrays when + transitioning (Chromium issue 117409). + + Made Error.prototype.name writable again, as required by the spec and + the web (Chromium issue 69187). + + Implemented map collection with incremental marking (issue 1465). + + Regexp: Fixed overflow in min-match-length calculation + (Chromium issue 126412). + + MIPS: Fixed illegal instruction use on Loongson in code for + Math.random() (issue 2115). + + Fixed crash bug in VisitChoice (Chromium issue 126272). + + Fixed unsigned-Smi check in MappedArgumentsLookup + (Chromium issue 126414). + + Fixed LiveEdit for function with no locals (issue 825). + + Fixed register clobbering in LoadIC for interceptors + (Chromium issue 125988). + + Implemented clearing of CompareICs (issue 2102). + + Performance and stability improvements on all platforms. + + +2012-05-03: Version 3.10.8 + + Enabled MIPS cross-compilation. + + Ensured reload of elements pointer in StoreFastDoubleElement stub. + (Chromium issue 125515) + + Fixed corner cases in truncation behavior when storing to + TypedArrays. (issue 2110) + + Fixed failure to properly recognize and report out-of-memory + conditions when allocating code space pages. (Chromium issue + 118625) + + Fixed idle notifications to perform a round of incremental GCs + after context disposal. (issue 2107) + + Fixed preparser for try statement. (issue 2109) + + Performance and stability improvements on all platforms. + + +2012-04-30: Version 3.10.7 + + Performance and stability improvements on all platforms. + + +2012-04-26: Version 3.10.6 + + Fixed some bugs in accessing details of the last regexp match. + + Fixed source property of empty RegExp objects. (issue 1982) + + Enabled inlining some V8 API functions. + + Performance and stability improvements on all platforms. + + +2012-04-23: Version 3.10.5 + + Put new global var semantics behind a flag until WebKit tests are + cleaned up. + + Enabled stepping into callback passed to builtins. + (Chromium issue 109564) + + Performance and stability improvements on all platforms. + + +2012-04-19: Version 3.10.4 + + Fixed issues when stressing compaction with WeakMaps. + + Fixed missing GVN flag for new-space promotion. (Chromium issue 123919) + + Simplify invocation sequence at monomorphic function invocation sites. + (issue 2079) + + Performance and stability improvements on all platforms. + + +2012-04-17: Version 3.10.3 + + Fixed several bugs in heap profiles (including issue 2078). + + Throw syntax errors on illegal escape sequences. + + Implemented rudimentary module linking (behind --harmony flag) + + Implemented ES5 erratum: Global declarations should shadow + inherited properties. + + Made handling of const more consistent when combined with 'eval' + and 'with'. + + Fixed V8 on MinGW-x64 (issue 2026). + + Performance and stability improvements on all platforms. + + +2012-04-13: Version 3.10.2 + + Fixed native ARM build (issues 1744, 539) + + Return LOOKUP variable instead of CONTEXT for non-context allocated + outer scope parameters (Chromium issue 119609). + + Fixed regular and ElementsKind transitions interfering with each other + (Chromium issue 122271). + + Improved performance of keyed loads/stores which have a HeapNumber + index (issues 1388, 1295). + + Fixed WeakMap processing for evacuation candidates (issue 2060). + + Bailout on possible direct eval calls (Chromium issue 122681). + + Do not assume that names of function expressions are context-allocated + (issue 2051). + + Performance and stability improvements on all platforms. + + +2012-04-10: Version 3.10.1 + + Fixed bug with arguments object in inlined functions (issue 2045). + + Fixed performance bug with lazy initialization (Chromium issue + 118686). + + Added suppport for Mac OS X 64bit builds with GYP. + (Patch contributed by Filipe David Manana ) + + Fixed bug with hidden properties (issue 2034). + + Fixed a performance bug when reloading pages (Chromium issue 117767, + V8 issue 1902). + + Fixed bug when optimizing throw in top-level code (issue 2054). + + Fixed two bugs with array literals (issue 2055, Chromium issue 121407). + + Fixed bug with Math.min/Math.max with NaN inputs (issue 2056). + + Fixed a bug with the new runtime profiler (Chromium issue 121147). + + Fixed compilation of V8 using uClibc. + + Optimized boot-up memory use. + + Optimized regular expressions. + + +2012-03-30: Version 3.10.0 + + Fixed store IC writability check in strict mode + (Chromium issue 120099). + + Resynchronize timers if the Windows system time was changed. + (Chromium issue 119815) + + Removed "-mfloat-abi=hard" from host compiler cflags when building for + hardfp ARM + (https://code.google.com/p/chrome-os-partner/issues/detail?id=8539) + + Fixed edge case for case independent regexp character classes + (issue 2032). + + Reset function info counters after context disposal. + (Chromium issue 117767, V8 issue 1902) + + Fixed missing write barrier in CopyObjectToObjectElements. + (Chromium issue 119926) + + Fixed missing bounds check in HasElementImpl. + (Chromium issue 119925) + + Performance and stability improvements on all platforms. + + +2012-03-23: Version 3.9.24 + + Activated count-based profiler for ARM. + + Fixed use of proxies as f.prototype properties. (issue 2021) + + Enabled snapshots on MIPS. + + Performance and stability improvements on all platforms. + + +2012-03-21: Version 3.9.23 + + Use correct arguments adaptation environment when inlining function + containing arguments. (Issue 2014) + + Performance and stability improvements on all platforms. + + +2012-03-20: Version 3.9.22 + + Enabled count-based profiler by default. + + Implemented a hash based look-up to speed up address checks + in large object space (issue 853). + + Performance and stability improvements on all platforms. + + +2012-03-19: Version 3.9.21 + + Fixed push-to-trunk script (and re-push). + + Added API call that identifies strings that are guaranteed only to + contain ASCII characters. + + +2012-03-19: Version 3.9.20 + + Fixed declarations escaping global strict eval. (Issue 1624) + + Fixed wrapping of receiver for non-strict callbacks. (Issue 1973) + + Fixed function declarations overwriting read-only global properties. + (Chromium issue 115452) + + Fixed --use-strict flag in combination with --harmony[-scoping]. + + Debugger: naive implementation of "step into Function.prototype.bind". + + Debugger: added ability to set script source from within OnBeforeCompile + + Added flag to always call DebugBreak on abort. + + Re-enabled constructor inlining and inline === comparison with boolean + constants. (Issue 2009) + + Don't use an explicit s0 in ClampDoubleToUint8. (Issue 2004) + + Performance and stability improvements on all platforms. + + +2012-03-14: Version 3.9.19 + + Ensure there is a smi check of the receiver for global load and call + ICs (Chromium issue 117794). + + Performance and stability improvements on all platforms. + + +2012-03-13: Version 3.9.18 + + Ensure consistency of Math.sqrt on Intel platforms. + + Remove static initializers in v8. (issue 1859) + + Add explicit dependency on v8_base in the GYP-based build. + + Performance and stability improvements on all platforms. + + +2012-03-12: Version 3.9.17 + + Fixed VFP detection through compiler defines. (issue 1996) + + Add Code-related fields to postmortem metadata. + + Performance and stability improvements on all platforms. + + +2012-03-09: Version 3.9.16 + + Added basic interface inference for modules (behind the --harmony flag). + + Added Object.is, Number.isFinite, Number.isNaN. + + Updated the Unicode tables to Unicode version 6.1.0. + + Performance and stability improvements on all platforms. + + +2012-03-06: Version 3.9.15 + + Fix the heap profiler crash caused by memory layout changes between + passes. + + Fix Error.prototype.toString to throw TypeError. (issue 1980) + + Fix double-rounding in strtod for MinGW. (issue 1062) + + Fix corrupted snapshot serializaton on ia32. (Chromium issue v8/1985) + + Performance and stability improvements on all platforms. + + +2012-03-01: Version 3.9.14 + + Performance and stability improvements on all platforms. + + +2012-02-29: Version 3.9.13 + + Added code kind check before preparing for OSR. (issue 1900, 115073) + + Fixed issue 1802: Pass zone explicitly to zone-allocation on x64 and + ARM. + + Ported string construct stub to x64. (issue 849) + + Performance and stability improvements on all platforms. + + +2012-02-28: Version 3.9.12 + + Fixed the negative lookup stub to handle deleted entries in a + dictionary. (issue 1964) + + Added a new API where the host can supply a callback function. The + callback function can resolve the location of a return address on stack + to the location where a return-address rewriting profiler stashed the + original return address. + + Fixed Chromium issue http://crbug.com/115646: When compiling for-in + pass correct context value to the increment instruction. + + Fixed issue 1853: Update breakpoints set with partial file name after + compile. + + +2012-02-27: Version 3.9.11 + + Made 'module' a context-sensitive keyword (V8 issue 1957). + + +2012-02-24: Version 3.9.10 + + Fixed V8 issues 1322, 1772 and 1969. + + Conformance improvements. + + Performance and stability improvements on all platforms. + + +2012-02-23: Version 3.9.9 + + Supported fast case for-in in Crankshaft. + + Sped up heap snapshot serialization and dominators construction. + + Randomized allocation addresses on windows. (Chromium issue 115151) + + Fixed compilation with MinGW-w64. (issue 1943) + + Fixed incorrect value of assignments to non-extensible properties. + + Fixed a crash bug in generated code on ia32. + + Performance and stability improvements on all platforms. + + +2012-02-21: Version 3.9.8 + + Fixed memory leak and missing #include in StartupDataDecompressor + (issue 1960). + + Renamed static methods to avoid shadowing virtual methods and fix Clang + C++11 compile error. + + Fixed sequence of element access in array builtins (issue 1790). + + Performance and stability improvements on all platforms. + + +2012-02-16: Version 3.9.7 + + Fixed V8 issues 1322, 1878, 1942, 1945 and Chromium issue 113924. + + Fixed GCC-4.7 warnings. + + Added Navier-Stokes benchmark. + + Performance and stability improvements on all platforms. + + +2012-02-14: Version 3.9.6 + + Fixed template-related linker error. (issue 1936) + + Allowed inlining of functions containing object literals. (issue 1322) + + Added --call-graph-size option to tickprocessor. (issue 1937) + + Heap Snapshot maximum size limit is too low for really big apps. At the + moment the limit is 256MB. (Chromium issue 113015) + + Performance and stability improvements on all platforms. + + +2012-02-09: Version 3.9.5 + + Removed unused command line flags. + + Performance and stability improvements on all platforms. + + +2012-02-08: Version 3.9.4 + + Properly initialize element-transitioning array literals on ARM. + (issue 1930) + + Bug fixes on all platforms. + + +2012-02-07: Version 3.9.3 + + When rethrowing an exception, print the stack trace of its original + site instead of rethrow site (Chromium issue 60240). + + Increased size of small stacks from 32k to 64k to avoid hitting limits + in Chromium (Chromium issue 112843). + + +2012-02-06: Version 3.9.2 + + Added timestamp to --trace-gc output. (issue 1932) + + Heap profiler reports implicit references. + + Optionally export metadata with libv8 to enable debuggers to inspect V8 + state. + + +2012-02-02: Version 3.9.1 + + Fixed memory leak in NativeObjectsExplorer::FindOrAddGroupInfo + (Chromium issue 112315). + + Fixed a crash in dev tools (Chromium issue 107996). + + Added 'dependencies_traverse': 1 to v8 GYP target. + + Performance and stability improvements on all platforms. + + +2012-02-01: Version 3.9.0 + + Reduced memory use immediately after starting V8. + + Stability fixes and performance improvements on all platforms. + + +2012-01-26: Version 3.8.9 + + Flush number string cache on GC (issue 1605). + + Provide access to function inferred name with + v8::Function::GetInferredName in V8 public API. + + Fix building with Clang (issue 1912). + + Reduce the space used by the stack for the profiling thread. + + Fix misleading documentation of v8::Locker (issue 542). + + Introduce readbinary function in d8 to read binary files. + + Performance and stability improvements on all platforms. + + +2012-01-23: Version 3.8.8 + + Limited number of loop iterations in Heap::ReserveSpace + (Chromium issue 99027). + + Fixed solaris build (VirtualMemory) (issue 1761). + + Fixed strict vs. non-strict handling of function proxies in + higher-order array and string methods. + + Enabled asynchronous remote debugging with d8 (issue 1691). + + Stability and performance improvements on all platforms. + + +2012-01-19: Version 3.8.7 + + Ensure that LRandom restores rsi after call to the C function on x64. + (Chromium issue http://crbug.com/110509) + + Fixing include issues on *bsd when building with scons. + (issue 1897) + + Provide a switch to specify -fno-strict-aliasing + (issue 1887) + + Move WIN32 define from standalone.gypi to common.gypi + (issue 1760) + + Fix corner-case in heap size estimation. + (issue 1893) + + Fix and enable NEW_NON_STRICT_FAST ArgumentsAccess stub on x64. + (issue 1903) + + Performance improvements and bug fixes. + + +2012-01-16: Version 3.8.6 + + Add primitive WebGL array support to d8. + + Improve heap size estimation (issue 1893). + + Hash collision DOS workaround extended from string keys + to numeric keys. + + Provide an API for iterating through all external strings referenced + from the JS heap. + + Adjust position recorded for call expressions. http://crbug.com/109195 + + Fix GC crash related to instanceof. http://crbug.com/109448 + + Performance improvements and bug fixes. + + +2012-01-05: Version 3.8.5 + + Fix broken test that assumes that no GC can clear the regexp cache (GC + can happen at any time due to Crankshaft). + + Fix handling of bogus receivers for Harmony collections. (issue 1884) + + Add netbsd support to gyp build. + + Determine page size at runtime on posix platforms. + + Ensure that store buffer filtering hash sets are cleared after + StoreBuffer::Filter. + + Randomize the seed used for string hashing. This helps guard against + CPU-eating DOS attacks against node.js servers. Based on code from + Bert Belder. This version only solves the issue for those that compile + V8 themselves or those that do not use snapshots. A snapshot-based + precompiled V8 will still have predictable string hash codes. + + Implement callback when script finishes running in V8 API. + + Improve performance of Math.min and Math.max for the case of two + arguments. (issue 1325) + + +2012-01-02: Version 3.8.4 + + Performance improvements for large Smi-only arrays. + + Fixed InternalArrays construction. (issue 1878) + + +2011-12-27: Version 3.8.3 + + Avoid embedding new space objects into code objects in the lithium gap + resolver. (chromium:108296) + + Bug fixes and performance optimizations on all platforms. + + +2011-12-21: Version 3.8.2 + + Add max optimization flag to v8 gyp build to ensure V8 is always built + fully optimized in Chrome. + + MIPS: Bring MIPS to parity with other platforms. + + Optimizations and stability improvements on all platforms. + + +2011-12-19: Version 3.8.1 + + Fixed GCC 4.7 warnings. Patch from Tobias Burnus. + + Stability improvements on all platforms. + + +2011-12-13: Version 3.8.0 + + Fixed handling of arrays in DefineOwnProperty. (issue 1756) + + Sync parser and preparser on do-while and return statements. + (issue 1856) + + Fixed another corner case for DefineOwnProperty on arrays (issue 1756). + + Stability and performance improvements on all platforms. + + +2011-12-01: Version 3.7.12 + + Increase tick interval for the android platform. + + Fix a bug in the register allocator. (chromium:105112) + + Fix handling of recompiling code. (chromium:105375, v8:1782) + + Start incremental marking on idle notification. (v8:1458) + + Build fixes for various platforms. + + Various performance improvements. + + +2011-11-29: Version 3.7.11 + + Fixed bug when generating padding to ensure space for lazy + deoptimization. + (issue 1846) + + Further reduced pause times due to GC. + + Stability and performance improvements on all platforms. + + +2011-11-23: Version 3.7.10 + + Set maximum length of FixedArray in terms of elements instead an + absolute number of bytes. + (Chromium issue 103103) + + Stability and performance improvements on all platforms. + + +2011-11-21: Version 3.7.9 + + Removed exit-time destructors. + + Stability and performance improvements on all platforms. + + +2011-11-17: Version 3.7.8 + + Removed hidden prototype from builtins, i.e., deleting an overridden + function on builtins will not make the original function reappear. + + Added NetBSD support for scons build. + + Performance improvements on all platforms. + + +2011-11-14: Version 3.7.7 + + Fix missing fast property accessors in heap snapshots. + (issue 1818) + + +2011-11-11: Version 3.7.6 + + Fixed filtering of store buffer for large object pages. + (issue 1817) + + Fixed generated hash function on all platforms. + (issue 1808) + + Fixed Heap::Shrink to ensure that it does not free pages that are + still in use. + (Chromium issue 100414) + + Stability and performance improvements on all platforms. + + +2011-11-10: Version 3.7.5 + + Added initial gyp infrastructure for MIPS. + + Implemented performance improvements to the incremental garbage + collector. + + Added optimizations and stability improvements on all platforms. + + +2011-11-07: Version 3.7.4 + + Proper "libv8.so.3.7.4" SONAME for Linux shared library (issue 1786). + + Fix Harmony sets and maps to allow null and undefined as keys + (still hidden behind --harmony flag) (issue 1622). + + Implement VirtualMemory on FreeBSD to fix build (issue 1807). + + Enable VFP instructions for Android. + + Fix error handling in Date.prototype.toISOString (issue 1792). + + Bug fixes and performance improvements for all platforms. + + Not officially supported but noteworthy: Crankshaft for MIPS :-) + + +2011-10-28: Version 3.7.3 + + Slight deoptimization as a workaround for issue with jslint: Issue + 1789. + + +2011-10-27: Version 3.7.2 + + Fix bug in deoptimization. Known issue with jslint: Issue 1789. + + +2011-10-26: Version 3.7.1 + + Achieved 33% speedup in debug-mode tests. + + Removed special casing of calls to RegExp test and exec methods with no + argument. Now matches new JSC behaviour. crbug.com/75740. + + Return the empty string on cyclic references in toString (ES5 + conformance). + + Fixed bug triggered by JSBeautifier. crbug.com/100409. + + Made Math.random state per-context instead of per-process (issue 864). + + Fixed stack traces to skip native functions. + + Make snapshots (new contexts) smaller and faster. + + Fixed handling of Function.apply for non-array arguments. + + Fixed evaluation order in defineProperties to match FireFox. + + Fixed handling of non-object receivers for array builtins, + crbug.com/100702. + + Multiple fixes to improve compliance with test262. + + Fixed compatibility with older Android releases. + + Fixed compilation with gcc-4.5.3. + + Improved performance of WriteUtf8, issue 1665. + + Made native syntax an early error in the preparser. + + Fixed issues 793 and 893 relating to Function.prototype.bind. + + Improved let, const, Set and Map support and other Harmony features + (behind the --harmony flag). + + Changed evaluation order for > and <= to match ES5 instead of ES3. + + Bug fixes and performance improvements on all platforms. + + +2011-10-13: Version 3.7.0 + + Fixed array handling for Object.defineOwnProperty (ES5 conformance). + + Fixed issue 1757 (string slices of external strings). + + Fixed issue 1759 (ARM). + + Added flag --noclever-optimizations to disable some things that + caused trouble in the past. + + Added flag --stress-compaction for testing. + + Added flag --harmony to activate all experimental Harmony features. + + +2011-10-10: Version 3.6.6 + + Added a GC pause visualization tool. + + Added presubmit=no and werror=no flags to Makefile. + + ES5/Test262 conformance improvements. + + Fixed compilation issues with GCC 4.5.x (issue 1743). + + Bug fixes and performance improvements on all platforms. + + +2011-10-05: Version 3.6.5 + + New incremental garbage collector. + + Removed the hard heap size limit (soft heap size limit is still + 700/1400Mbytes by default). + + Implemented ES5 generic Array.prototype.toString (Issue 1361). + + V8 now allows surrogate pair codes in decodeURIComponent (Issue 1415). + + Fixed x64 RegExp start-of-string bug (Issues 1746, 1748). + + Fixed propertyIsEnumerable for numeric properties (Issue 1692). + + Fixed the MinGW and Windows 2000 builds. + + Fixed "Prototype chain is not searched if named property handler does + not set a property" (Issue 1636). + + Made the RegExp.prototype object be a RegExp object (Issue 1217). + + Disallowed future reserved words as labels in strict mode. + + Fixed string split to correctly coerce the separator to a string + (Issue 1711). + + API: Added an optional source length field to the Extension + constructor. + + API: Added Debug::DisableAgent to match existing Debug::EnableAgent + (Issue 1573). + + Added "native" target to Makefile for the benefit of Linux distros. + + Fixed: debugger stops stepping outside evaluate (Issue 1639). + + More work on ES-Harmony proxies. Still hidden behind a flag. + + Bug fixes and performance improvements on all platforms. + + +2011-09-15: Version 3.6.4 + + Fixed d8's broken readline history. + + Removed the need for code delete events in CPU profiler (Issue 1466). + + Fixed debugger stepping next with trycatch recursion (Issue 1639). + + Fixing parallel execution in d8 (with -p) and some memory leaks. + + Support for precise stepping in functions compiled before debugging was + started (step 1). + + +2011-09-13: Version 3.6.3 + + Implemented better support of typed arrays in the d8 shell. + + Bug fixes and performance improvements on all platforms. + + +2011-09-08: Version 3.6.2 + + Added "dependencies" target to top-level Makefile. + + Added ability to turn profiler on/off in d8. + + Added "soname_version" parameter to common.gypi, v8.gyp, and Makefile. + + Fixed several crash bugs. + + +2011-09-07: Version 3.6.1 + + Fixed a bug in abrupt exit from with or catch inside finally. + + Fixed possible crash in FixedDoubleArray::Initialize() (Chromium + issue 95113). + + Fixed a bug in Page::GetRegionMaskForSpan (Chromium issue 94425). + + Fixed a few clang warnings (which -Werror treated as errors). + + Performance improvements on all platforms. + + +2011-09-05: Version 3.6.0 + + Fixed a bug when optimizing named function expression (issue 1647). + + Fixed a bug when optimizing f.call.apply (issue 1650). + + Made arguments and caller always be null on native functions + (issues 1548 and 1643). + + Fixed issue 1648 (cross-compiling x64 targeting ia32). + + Fixed issue 371 (d8 printing of strings containing \0). + + Fixed order of evaluation in arguments to parseInt (issue 1649). + + Fixed a problem with large heap snapshots in Chrome DevTools + (issue 1658, chromium issue 89268). + + Upped default maximum heap size from 512M to 700M. + + +2011-08-31: Version 3.5.10 + + Added dependency of v8_base on WinSocket2 Windows library in + the GYP-build. + + Various bugfixes. + + +2011-08-29: Version 3.5.9 + + Made FromPropertyDescriptor not trigger inherited setters. + + Fixed .gyp files to work on the ARM simulator. + + Fixed shared library build warnings for MSVS. + + +2011-08-24: Version 3.5.8 + + Added V8EXPORT attributes for v8::Array::CheckCast and + v8::Number::CheckCast. + + Made a slight API change enabling opting out from null termination + in String::Write*(). + + Fixed arm build for gcc-4.6. + + +2011-08-22: Version 3.5.7 + + Make scanner handle invalid unicode escapes in identifiers correctly. + + Make regexp flag parsing stricter. + + Fix several memory leaks. + + +2011-08-17: Version 3.5.6 + + Fixed issue that could cause crashes when running with --heap-stats. + + Fixed compilation on Linux 2.6.9 and older. + + Fixed live-object-list to work with isolates. + + Fixed memory leaks in zones and isolates. + + Fixed a performance regression for TypedArrays on x64. + + Stability improvements on all platforms. + + +2011-08-15: Version 3.5.5 + + Fixed bugs involving negative zero and the optimizing compiler. + + Fixed optimized version of Function.apply(x, arguments). (issue 1592) + + Eliminated uses of deprecated ARM instructions. + + Sped up Math.floor by using SSE 4.1 roundsd instruction on ia32. + + Removed restriction on the size of disassembled code that is printed. + + +2011-08-10: Version 3.5.4 + + Added a preliminary implementation of ES Harmony weak maps. Weak + maps can be enabled by the flag --harmony-weakmaps. + + Introduced a toplevel Makefile to support GYP-based building. GYP + can be obtained from http://gyp.googlecode.com. + + Fixed a bug in the length property of functions created by + Function.prototype.bind. + + Reduced malloc heap allocation on process startup. + + Several important code generation bug fixes. + + Performance improvements on all platforms. + + +2011-08-03: Version 3.5.3 + + MIPS: Port of fix to ClassOf check from ARM. + Patch from Paul Lind . + + Stopped using mprotect on Cygwin. + Avoided uninitialized member warning on gcc 4.3.4 + Both patches by Bert Belder. + + Bug fixes and performance improvements on all platforms. + + +2011-08-01: Version 3.5.2 + + Performance improvements on all platforms. + + +2011-07-28: Version 3.5.1 + + Fixed setting the readonly flag on the prototype property using the + API call FunctionTemplate::SetPrototypeAttributes (issue 1539). + + Changed the tools/test.py script to use d8 instead of shell for + testing. + + Fixed crash in ToBooleanStub when GC happens during invocation. + + Enabled automatic unboxing of double arrays. + + Performance improvements on all platforms. + + +2011-07-25: Version 3.5.0 + + Implemented Object.prototype.{hasOwnProperty, propertyIsEnumerable} for + proxies. + + Removed logging to memory support. + + Bugfixes and performance work. + + +2011-07-20: Version 3.4.14 + + Fix the debugger for strict-mode functions. (Chromium issue 89236) + + Add GetPropertyAttribute method for Object in the API. (Patch by + Peter Varga) + + Fix -Wunused-but-set-variable for gcc-4.6 on x64. (Issue 1291) + + +2011-07-18: Version 3.4.13 + + Improved debugger support to allow inspection of optimized frames (issue + 1140). + + Fixed a bug in prototype transitions cache clearing introduced by r8165. + + Fixed shortcutting bug in HInferRepresentation. Patch by Andy Wingo. + + Fixed a memory leak in sample/shell.cc (dispose semaphores). + + Simplified HClampToUint8. Patch by Andy Wingo. + + Exposed APIs for detecting boxed primitives, native errors. Patch by + Luke Zarko. + + Added map check for COW elements to crankshaft array handling code + (issue 1560). + + Sample shell and (a light version of) D8 links against a shared library + now. + + Fixed bug in array filter and reduce functions (issue 1559). + + Avoid TLS load in AstNode constructor. + + Introduced a random entropy source which can optionally be provided at + initialization. (Chromium issue 89462). + + +2011-07-13: Version 3.4.12 + + Added --prof profiling option to d8 shell. + + Fixed a bug where reading a directory in d8 shell hangs (issue 1533). + + Fixed a potential assertion failure in const declarations. + + Fixed an assertion failure in descriptor arrays (issue 1526). + + Enabled fast thread-local storage by default on supported platforms. + + Improved reporting of source position for global variable loads + (issue 1527). + + +2011-07-11: Version 3.4.11 + + Fixed MinGW32 build. + + Fixed a GC bug with RegExp code flushing. + + Implemented Object.defineProperty for proxies. + + Fixed a bug in for/in iteration of arguments objects (issue 1531). + + Added debugger support for inspecting optimized frames (issue 1140). + + Allowed JSObject::PreventExtensions to work for arguments objects. + + Bugfixes and performance work. + + +2011-07-06: Version 3.4.10 + + Fixed debugger not breaking on certain "if" statements (issue 1523). + + Fixed assertion failure in runtime profiler when running on IA32 + without snapshot (issue 1522). + + Fixed ABI for API calls on IA32 (for clang compatibility). + + Introduced code flushing of RegExp code to free memory used by + RegExps sooner. + + Fixed linux-tick-processor built wrong version of v8 (issue 1532). + + Fixed assertion failure in v8::TryCache::StackTrace (issue 1529). + + Performance improvements on all platforms. + + +2011-07-04: Version 3.4.9 + + Added support for debugger inspection of locals in optimized frames + (issue 1140). + + Fixed SConstruct to pass correct defines to samples/preparser when + building with library=shared. + + Made date parser handle ES5 Date Time Strings correctly (issue 1498). + + Fixed a bug in Object.defineProperty on the arguments object. + + Performance improvements on all platforms. + + +2011-06-29: Version 3.4.8 + + Ensure 16-byte stack alignment on Solaris (issue 1505). + + Fix "illegal access" when calling parseInt with a radix + that is not a smi. (issue 1246). + + +2011-06-27: Version 3.4.7 + + Fixed 64-bit build on FreeBSD. + + Added API to set the property attributes for the prototype + property on functions created from FunctionTemplates. + + Bugfixes and performance work. + + +2011-06-22: Version 3.4.6 + + Lowered limit on code space for systems with low memory supply. + + Allowed compiling v8_shell with the 'host' toolset (issue 82437). + + Extended setBreakpoint API to accept partial script name (issue 1418). + + Made multi-line comments not count when deciding whether the '-->' + comment starter is first on a line. This matches Safari. + + Made handling of non-array recievers in Array length setter correct + (issue 1491). + + Added ability to heap profiler to iterate over snapshot's node + (issue 1481). + + +2011-06-20: Version 3.4.5 + + Fixed issues 794, 1097, 1215(partial), 1417, 1435, 1472, 1473, + 1476, and 1477. + + Improved code generation for !0 and !1. + + Reduced memory usage for regular expressions with nested qualifiers. + (issue 1472) + + Fixed V8 to count line terminators in multi-line comments. + (Chromium issue 86431) + + Fixed disassembler=on option for release-mode builds. (issue 1473) + + Performance improvements on all platforms. + + +2011-06-15: Version 3.4.4 + + Added snapshot compression support and --stress-opt flag to d8. + + Improved performance of try/catch. + + Several GYP-related changes: Added support for building Xcode project + files. Make the ARM simulator build with GYP again. Generate Makefiles + for all architectures on Linux. + + Fixed Array.prototype.{reduce,reduceRight} to pass undefined as the + receiver for strict mode callbacks. (issue 1436) + + Fixed a bug where an array load was incorrectly hoisted by GVN. + + Handle 'undefined' correctly when === has been specialized for doubles. + (issue 1434) + + Corrected the limit of local variables in an optimized function from 64 + to 63. + + Correctly set ReadOnly flag on indexed properties when using the API Set + method. (issue 1470) + + Give the correct error message when Object.isExtensible is called on a + non-object. (issue 1452) + + Added GetOwnPropertyNames method for Object in the API. Patch by Peter + Varga. + + Do not redefine properties unneccesarily in seal and freeze. (issue + 1447) + + IsExecutionTerminating has an Isolate parameter now. + + Distinguish keyed loads with a symbol key from fast elements loads, + avoiding some useless deoptimizations. (issue 1471) + + +2011-06-08: Version 3.4.3 + + Clear the global thread table when an isolate is disposed + (issue 1433). + + Converted time zone name to UTF8 on Windows (issue 1290). + + Limited the number of arguments in a function call to 32766 + (issue 1413). + + Compress sources of JS libraries in addition to the snapshot. + + Fixed a bug in Lithium environment iteration. + + Performance improvements on all platforms. + + +2011-06-06: Version 3.4.2 + + More work on ES-Harmony proxies. Still hidden behind a flag. + + Fixed some crash bugs and improved performance. + + Fixed building with gdb debugging support. + + Do not install SIGPROF handler until it is needed. + + Added DateTimeFormat to i18n API. + + Fixed compilation on OpenBSD. + + Take the ulimit into account when sizing the heap. OpenBSD users + may still have to increase the default ulimit to run heavy pages in + the browser. + + +2011-06-01: Version 3.4.1 + + Fixed JSON stringify issue with arrays. + + Changed calls to JS builtins to be passed undefined when called with + implicit receiver. + + Implemented the set trap for Harmony proxies. Proxies still need to + be enabled with the --harmony-proxies flag. + + +2011-05-30: Version 3.4.0 + + Changed calls to undefined property setters to not throw (issue 1355). + + Made RegExp objects not callable. + + Fixed issues on special case large JSON strings in new json parser + (issues http://crbug.com/83877 and http://crbug.com/84186). + + Performance improvements on all platforms. + + +2011-05-25: Version 3.3.10 + + Fixed calls of strict mode function with an implicit receiver. + + Fixed fast handling of arrays to properly deal with changes to the + Object prototype (issue 1403). + + Changed strict mode poison pill to be the same type error function + (issue 1387). + + Fixed a debug crash in arguments object handling (issue 1227). + + Fixed a bug in deoptimization on x64 (issue 1404). + + Performance improvements and bug fixes on all platforms. + + +2011-05-23: Version 3.3.9 + + Added DateTimeFormat class to experimental i18n API. + + Extended preparser to give early errors for some strict mode + restrictions. + + Removed legacy execScript function from V8. + + Extended isolate API with the ability to add embedder-specific + data to an isolate. + + Added basic support for polymorphic loads from JS and external + arrays. + + Fixed bug in handling of switch statements in the optimizing + compiler. + + +2011-05-18: Version 3.3.8 + + Added MarkIndependent to the persistent handle API. Independent + handles are independent of all other persistent handles and can be + garbage collected more frequently. + + Implemented the get trap for Harmony proxies. Proxies are enabled + with the --harmony-proxies flag. + + Performance improvements and bug fixes on all platforms. + + +2011-05-16: Version 3.3.7 + + Updated MIPS infrastructure files. + + Performance improvements and bug fixes on all platforms. + + +2011-05-11: Version 3.3.6 + + Updated MIPS infrastructure files. + + Added method IsCallable for Object to the API. + Patch by Peter Varga. + + +2011-05-09: Version 3.3.5 + + Fixed build on FreeBSD. Patch by Akinori MUSHA. + + Added check that receiver is JSObject on API calls. + + Implemented CallAsConstructor method for Object in the API (Issue 1348). + Patch by Peter Varga. + + Added CallAsFunction method to the Object class in the API (Issue 1336). + Patch by Peter Varga. + + Added per-isolate locking and unlocking. + + Fixed bug in x64 >>> operator (Issue 1359). + + +2011-05-04: Version 3.3.4 + + Implemented API to disallow code generation from strings for a context + (issue 1258). + + Fixed bug with whitespaces in parseInt (issue 955). + + Fixed bug with == comparison of Date objects (issue 1356). + + Added GYP variables for ARM code generation: + v8_can_use_vfp_instructions, v8_can_use_unaligned_accesses + and v8_use_arm_eabi_hardfloat. + + +2011-05-02: Version 3.3.3 + + Added support for generating Visual Studio solution and project files + using GYP. + + Implemented support for ARM EABI calling convention variation where + floating-point arguments are passed in registers (hardfloat). + + Added Object::HasOwnProperty() to the API. + + Added support for compressing startup data to reduce binary size. This + includes build time support and an API for the embedder to decompress + the startup data before initializing V8. + + Reduced the profiling hooks overhead from >400% to 25% when using + ll_prof. + + Performance improvements and bug fixes on all platforms. + + +2011-04-27: Version 3.3.2 + + Fixed crash bug on ARM with no VFP3 hardware. + + Fixed compilation of V8 without debugger support. + + Improved performance on JSLint. + + Added support Float64 WebGL arrays. + + Fixed crash bug in regexp replace. + + +2011-04-20: Version 3.3.1 + + Reduced V8 binary size by removing virtual functions from hydrogen. + + Fixed crash bug on x64. + + Performance improvements on ARM and IA32. + + +2011-04-18: Version 3.3.0 + + Fixed bug in floating point rounding in Crankshaft on ARM + (issue 958) + + Fixed a number of issues with running without VFPv3 support on ARM + (issue 1315) + + Introduced v8Locale.Collator, a partial implementation of Collator + per last ECMAScript meeting + mailing list. + + Minor performance improvements and bug fixes. + + +2011-04-13: Version 3.2.10 + + Fixed bug in external float arrays on ARM (issue 1323). + + Minor performance improvements and bug fixes. + + +2011-04-11: Version 3.2.9 + + Removed support for ABI prior to EABI on ARM. + + Fixed multiple crash bugs. + + Added GCMole to the repository, a simple static analysis tool that + searches for GC-unsafe evaluation order dependent callsites. + + Made preparser API be exported in shared libraries. + + Fixed multiple issues in EcmaScript 5 strict mode implementation. + + Fixed mutable __proto__ property if object is not extensible + (Issue 1309). + + Fixed auto suspension of the sampler thread. + + +2011-04-06: Version 3.2.8 + + Exposed WebGL typed array constructors in the shell sample. + + Performance improvements on all platforms. + + +2011-04-04: Version 3.2.7 + + Disabled the original 'classic' V8 code generator. Crankshaft is + now the default on all platforms. + + Changed the heap profiler to use more descriptive names. + + Performance and stability improvements to isolates on all platforms. + + +2011-03-30: Version 3.2.6 + + Fixed xcode build warning in shell.cc (out of order initialization). + + Fixed null-pointer dereference in the compiler when running without + SSE3 support (Chromium issue 77654). + + Fixed x64 compilation error due to some dead code. (Issue 1286) + + Introduced scons target to build the preparser stand-alone example. + + Made FreeBSD build and pass all tests. + + +2011-03-28: Version 3.2.5 + + Fixed build with Irregexp interpreter (issue 1266). + + Added Crankshaft support for external arrays. + + Fixed two potential crash bugs. + + +2011-03-23: Version 3.2.4 + + Added isolates which allows several V8 instances in the same process. + This is controlled through the new Isolate class in the API. + + Implemented more of EcmaScript 5 strict mode. + + Reduced the time it takes to make detailed heap snapshot. + + Added a number of commands to the ARM simulator and enhanced the ARM + disassembler. + + +2011-03-17: Version 3.2.3 + + Fixed a number of crash bugs. + + Fixed Array::New(length) to return an array with a length (issue 1256). + + Fixed FreeBSD build. + + Changed __defineGetter__ to not throw (matching the behavior of Safari). + + Implemented more of EcmaScript 5 strict mode. + + Improved Crankshaft performance on all platforms. + + +2011-03-14: Version 3.2.2 + + Fixed a number of crash and correctness bugs. + + Improved Crankshaft performance on all platforms. + + Fixed Crankshaft on Solaris/Illumos. + + +2011-03-10: Version 3.2.1 + + Fixed a number of crash bugs. + + Improved Crankshaft for x64 and ARM. + + Implemented more of EcmaScript 5 strict mode. + + +2011-03-07: Version 3.2.0 + + Fixed a number of crash bugs. + + Turned on Crankshaft by default on x64 and ARM. + + Improved Crankshaft for x64 and ARM. + + Implemented more of EcmaScript 5 strict mode. + + +2011-03-02: Version 3.1.8 + + Fixed a number of crash bugs. + + Improved Crankshaft for x64 and ARM. + + Implemented more of EcmaScript 5 strict mode. + + Fixed issue with unaligned reads and writes on ARM. + + Improved heap profiler support. + + +2011-02-28: Version 3.1.7 + + Fixed a number of crash bugs. + + Improved Crankshaft for x64 and ARM. + + Fixed implementation of indexOf/lastIndexOf for sparse + arrays (http://crbug.com/73940). + + Fixed bug in map space compaction (http://crbug.com/59688). + + Added support for direct getter accessors calls on ARM. + + +2011-02-24: Version 3.1.6 + + Fixed a number of crash bugs. + + Added support for Cygwin (issue 64). + + Improved Crankshaft for x64 and ARM. + + Added Crankshaft support for stores to pixel arrays. + + Fixed issue in CPU profiler with Crankshaft. + + +2011-02-16: Version 3.1.5 + + Change RegExp parsing to disallow /(*)/. + + Added GDB JIT support for ARM. + + Fixed several crash bugs. + + Performance improvements on the IA32 platform. + + +2011-02-14: Version 3.1.4 + + Fixed incorrect compare of prototypes of the global object (issue + 1082). + + Fixed a bug in optimizing calls to global functions (issue 1106). + + Made optimized Function.prototype.apply safe for non-JSObject first + arguments (issue 1128). + + Fixed an error related to element accessors on Object.prototype and + parser errors (issue 1130). + + Fixed a bug in sorting an array with large array indices (issue 1131). + + Properly treat exceptions thrown while compiling (issue 1132). + + Fixed bug in register requirements for function.apply (issue 1133). + + Fixed a representation change bug in the Hydrogen graph construction + (issue 1134). + + Fixed the semantics of delete on parameters (issue 1136). + + Fixed a optimizer bug related to moving instructions with side effects + (issue 1138). + + Added support for the global object in Object.keys (issue 1150). + + Fixed incorrect value for Math.LOG10E + (issue http://code.google.com/p/chromium/issues/detail?id=72555) + + Performance improvements on the IA32 platform. + + Implement assignment to undefined reference in ES5 Strict Mode. + + +2011-02-09: Version 3.1.3 + + Fixed a bug triggered by functions with huge numbers of declared + arguments. + + Fixed zap value aliasing a real object - debug mode only (issue 866). + + Fixed issue where Array.prototype.__proto__ had been set to null + (issue 1121). + + Fixed stability bugs in Crankshaft for x86. + + +2011-02-07: Version 3.1.2 + + Added better security checks when accessing properties via + Object.getOwnPropertyDescriptor. + + Fixed bug in Object.defineProperty and related access bugs (issues + 992, 1083 and 1092). + + Added LICENSE.v8, LICENSE.strongtalk and LICENSE.valgrind to ease + copyright notice generation for embedders. + + +2011-02-02: Version 3.1.1 + + Perform security checks before fetching the value in + Object.getOwnPropertyDescriptor. + + Fixed a bug in Array.prototype.splice triggered by passing no + arguments. + + Fixed bugs in -0 in arithmetic and in Math.pow. + + Fixed bugs in the register allocator and in switching from optimized + to unoptimized code. + + +2011-01-31: Version 3.1.0 + + Performance improvements on all platforms. + + +2011-01-28: Version 3.0.12 + + Added support for strict mode parameter and object property + validation. + + Fixed a couple of crash bugs. + + +2011-01-25: Version 3.0.11 + + Fixed a bug in deletion of lookup slots that could cause global + variables to be accidentally deleted (http://crbug.com/70066). + + Added support for strict mode octal literal verification. + + Fixed a couple of crash bugs (issues 1070 and 1071). + + +2011-01-24: Version 3.0.10 + + Fixed External::Wrap for 64-bit addresses (issue 1037). + + Fixed incorrect .arguments variable proxy handling in the full + code generator (issue 1060). + + Introduced partial strict mode support. + + Changed formatting of recursive error messages to match Firefox and + Safari (issue http://crbug.com/70334). + + Fixed incorrect rounding for float-to-integer conversions for external + array types, which implement the Typed Array spec + (issue http://crbug.com/50972). + + Performance improvements on the IA32 platform. + + +2011-01-19: Version 3.0.9 + + Added basic GDB JIT Interface integration. + + Make invalid break/continue statements a syntax error instead of a + runtime error. + + +2011-01-17: Version 3.0.8 + + Exposed heap size limit to the heap statistics gathered by + the GetHeapStatistics API. + + Wrapped external pointers more carefully (issue 1037). + + Hardened the implementation of error objects to avoid setters + intercepting the properties set then throwing an error. + + Avoided trashing the FPSCR when calculating Math.floor on ARM. + + Performance improvements on the IA32 platform. + + +2011-01-10: Version 3.0.7 + + Stopped calling inherited setters when creating object literals + (issue 1015). + + Changed interpretation of malformed \c? escapes in RegExp to match + JSC. + + Enhanced the command-line debugger interface and fixed some minor + bugs in the debugger. + + Performance improvements on the IA32 platform. + + +2011-01-05: Version 3.0.6 + + Allowed getters and setters on JSArray elements (issue 900). + + Stopped JSON objects from hitting inherited setters (part of + issue 1015). + + Allowed numbers and strings as names of getters/setters in object + initializer (issue 820). + + Added use_system_v8 option to gyp (off by default), to make it easier + for Linux distributions to ship with system-provided V8 library. + + Exported external array data accessors (issue 1016). + + Added labelled thread names to help with debugging (on Linux). + + +2011-01-03: Version 3.0.5 + + Fixed a couple of cast errors for gcc-3.4.3. + + Performance improvements in GC and IA32 code generator. + + +2010-12-21: Version 3.0.4 + + Added Date::ResetCache() to the API so that the cached values in the + Date object can be reset to allow live DST / timezone changes. + + Extended existing support for printing (while debugging) the contents + of objects. Added support for printing objects from release builds. + + Fixed V8 issues 989, 1006, and 1007. + + +2010-12-17: Version 3.0.3 + + Reapplied all changes for version 3.0.1. + + Improved debugger protocol for remote debugging. + + Added experimental support for using gyp to generate build files + for V8. + + Fixed implementation of String::Write in the API (issue 975). + + +2010-12-15: Version 3.0.2 + + Revert version 3.0.1 and patch 3.0.1.1. + + +2010-12-13: Version 3.0.1 + + Added support for an experimental internationalization API as an + extension. This extension is disabled by default but can be enabled + when building V8. The ECMAScript internationalization strawman is + at http://wiki.ecmascript.org/doku.php?id=strawman:i18n_api. + + Made RegExp character class parsing stricter. This mirrors a change + to RegExp parsing in WebKit. + + Fixed a bug in Object.defineProperty when used to change attributes + of an existing property. It incorrectly set the property value to + undefined (issue 965). + + Fixed several different compilation failures on various platforms + caused by the 3.0.0 release. + + Optimized Math.pow so it can work on unboxed doubles. + + Sped up quoting of JSON strings by removing one traversal of the + string. + + +2010-12-07: Version 3.0.0 + + Improved performance by (partially) addressing issue 957 on + IA-32. Still needs more work for the other architectures. + + +2010-11-29: Version 2.5.9 + + Fixed crashes during GC caused by partially initialize heap + objects. + + Fixed bug in process sample that caused memory leaks. + + Improved performance on ARM by implementing missing stubs and + inlining. + + Improved heap profiler support. + + Added separate seeding on Windows of the random number generator + used internally by the compiler (issue 936). + + Exposed API for getting the name of the function used to construct + an object. + + Fixed date parser to handle one and two digit millisecond + values (issue 944). + + Fixed number parsing to disallow space between sign and + digits (issue 946). + + +2010-11-23: Version 2.5.8 + + Removed dependency on Gay's dtoa. + + Improved heap profiler precision and speed. + + Reduced overhead of callback invocations on ARM. + + +2010-11-18: Version 2.5.7 + + Fixed obscure evaluation order bug (issue 931). + + Split the random number state between JavaScript and the private API. + + Fixed performance bug causing GCs when generating stack traces on + code from very large scripts. + + Fixed bug in parser that allowed (foo):42 as a labelled statement + (issue 918). + + Provide more accurate results about used heap size via + GetHeapStatistics. + + Allow build-time customization of the max semispace size. + + Made String.prototype.split honor limit when separator is empty + (issue 929). + + Added missing failure check after expecting an identifier in + preparser (Chromium issue 62639). + + +2010-11-10: Version 2.5.6 + + Added support for VFP rounding modes to the ARM simulator. + + Fixed multiplication overflow bug (issue 927). + + Added a limit for the amount of executable memory (issue 925). + + +2010-11-08: Version 2.5.5 + + Added more aggressive GC of external objects in near out-of-memory + situations. + + Fixed a bug that gave the incorrect result for String.split called + on the empty string (issue 924). + + +2010-11-03: Version 2.5.4 + + Improved V8 VFPv3 runtime detection to address issue 914. + + +2010-11-01: Version 2.5.3 + + Fixed a bug that prevents constants from overwriting function values + in object literals (issue 907). + + Fixed a bug with reporting of impossible nested calls of DOM functions + (issue http://crbug.com/60753). + + +2010-10-27: Version 2.5.2 + + Improved sampler resolution on Linux. + + Allowed forcing the use of a simulator from the build script + independently of the host architecture. + + Fixed FreeBSD port (issue 912). + + Made windows-tick-processor respect D8_PATH. + + Implemented --noinline-new flag fully on IA32, X64 and ARM platforms. + + +2010-10-20: Version 2.5.1 + + Fixed bug causing spurious out of memory exceptions + (issue http://crbug.com/54580). + + Fixed compilation error on Solaris platform (issue 901). + + Fixed error in strtod (string to floating point number conversion) + due to glibc's use of 80-bit floats in the FPU on 32-bit linux. + + Adjusted randomized allocations of executable memory to have 64k + granularity (issue http://crbug.com/56036). + + Supported profiling using kernel perf_events on linux. Added ll_prof + script to tools and --ll-prof flag to V8. + + +2010-10-18: Version 2.5.0 + + Fixed bug in cache handling of lastIndex on global regexps + (issue http://crbug.com/58740). + + Added USE_SIMULATOR macro that explicitly indicates that we wish to use + the simulator as the execution engine (by Mark Lam + from Hewlett-Packard Development Company, LP). + + Fixed compilation error on ARM with gcc 4.4 (issue 894). + + +2010-10-13: Version 2.4.9 + + Fixed a bug in the handling of conditional expressions in test + contexts in compiler for top-level code. + + Added "//@ sourceURL" information to the StackTrace API. + + Exposed RegExp construction through the API. + + +2010-10-04: Version 2.4.8 + + Fixed a bug in ResumeProfilerEx causing it to not always write out the + whole snapshot (issue 868). + + Performance improvements on all platforms. + + +2010-09-30: Version 2.4.7 + + Changed the command-line flag --max-new-space-size to be in kB and the + flag --max-old-space-size to be in MB (previously they were in bytes). + + Added Debug::CancelDebugBreak to the debugger API. + + Fixed a bug in getters for negative numeric property names + (https://bugs.webkit.org/show_bug.cgi?id=46689). + + Performance improvements on all platforms. + + +2010-09-27: Version 2.4.6 + + Fixed assertion failure related to copy-on-write arrays (issue 876). + + Fixed build failure of 64-bit V8 on Windows. + + Fixed a bug in RegExp (issue http://crbug.com/52801). + + Improved the profiler's coverage to cover more functions (issue 858). + + Fixed error in shift operators on 64-bit V8 + (issue http://crbug.com/54521). + + +2010-09-22: Version 2.4.5 + + Changed the RegExp benchmark to exercise the regexp engine on different + inputs by scrambling the input strings. + + Fixed a bug in keyed loads on strings. + + Fixed a bug with loading global function prototypes. + + Fixed a bug with profiling RegExp calls (issue http://crbug.com/55999). + + Performance improvements on all platforms. + + +2010-09-15: Version 2.4.4 + + Fixed bug with hangs on very large sparse arrays. + + Now tries harder to free up memory when running out of space. + + Added heap snapshots to JSON format to API. + + Recalibrated benchmarks. + + +2010-09-13: Version 2.4.3 + + Made Date.parse properly handle TZ offsets (issue 857). + + Performance improvements on all platforms. + + +2010-09-08: Version 2.4.2 + + Fixed GC crash bug. + + Fixed stack corruption bug. + + Fixed compilation for newer C++ compilers that found Operand(0) + ambiguous. + + +2010-09-06: Version 2.4.1 + + Added the ability for an embedding application to receive a callback + when V8 allocates (V8::AddMemoryAllocationCallback) or deallocates + (V8::RemoveMemoryAllocationCallback) from the OS. + + Fixed several JSON bugs (including issue 855). + + Fixed memory overrun crash bug triggered during V8's tick-based + profiling. + + Performance improvements on all platforms. + + +2010-09-01: Version 2.4.0 + + Fixed bug in Object.freeze and Object.seal when Array.prototype or + Object.prototype are changed (issue 842). + + Updated Array.splice to follow Safari and Firefox when called + with zero arguments. + + Fixed a missing live register when breaking at keyed loads on ARM. + + Performance improvements on all platforms. + + +2010-08-25: Version 2.3.11 + + Fixed bug in RegExp related to copy-on-write arrays. + + Refactored tools/test.py script, including the introduction of + VARIANT_FLAGS that allows specification of sets of flags with which + all tests should be run. + + Fixed a bug in the handling of debug breaks in CallIC. + + Performance improvements on all platforms. + + +2010-08-23: Version 2.3.10 + + Fixed bug in bitops on ARM. + + Build fixes for unusual compilers. + + Track high water mark for RWX memory. + + Performance improvements on all platforms. + + +2010-08-18: Version 2.3.9 + + Fixed compilation for ARMv4 on OpenBSD/FreeBSD. + + Removed specialized handling of GCC 4.4 (issue 830). + + Fixed DST cache to take into account the suspension of DST in + Egypt during the 2010 Ramadan (issue http://crbug.com/51855). + + Performance improvements on all platforms. + + +2010-08-16: Version 2.3.8 + + Fixed build with strict aliasing on GCC 4.4 (issue 463). + + Fixed issue with incorrect handling of custom valueOf methods on + string wrappers (issue 760). + + Fixed compilation for ARMv4 (issue 590). + + Improved performance. + + +2010-08-11: Version 2.3.7 + + Reduced size of heap snapshots produced by heap profiler (issue 783). + + Introduced v8::Value::IsRegExp method. + + Fixed CPU profiler crash in start / stop sequence when non-existent + name is passed (issue http://crbug.com/51594). + + Introduced new indexed property query callbacks API (issue 816). This + API is guarded by USE_NEW_QUERY_CALLBACK define and is disabled + by default. + + Removed support for object literal get/set with number/string + property name. + + Fixed handling of JSObject::elements in CalculateNetworkSize + (issue 822). + + Allowed compiling with strict aliasing enabled on GCC 4.4 (issue 463). + + +2010-08-09: Version 2.3.6 + + RegExp literals create a new object every time they are evaluated + (issue 704). + + Object.seal and Object.freeze return the modified object (issue 809). + + Fixed building using GCC 4.4.4. + + +2010-08-04: Version 2.3.5 + + Added support for ES5 property names. Object initialisers and + dot-notation property access now allows keywords. Also allowed + non-identifiers after "get" or "set" in an object initialiser. + + Randomized the addresses of allocated executable memory on Windows. + + +2010-08-02: Version 2.3.4 + + Fixed problems in implementation of ES5 function.prototype.bind. + + Fixed error when using apply with arguments object on ARM (issue 784). + + Added setting of global flags to debugger protocol. + + Fixed an error affecting cached results of sin and cos (issue 792). + + Removed memory leak from a boundary case where V8 is not initialized. + + Fixed issue where debugger could set breakpoints outside the body + of a function. + + Fixed issue in debugger when using both live edit and step in features. + + Added Number-letter (Nl) category to Unicode tables. These characters + can now be used in identifiers. + + Fixed an assert failure on X64 (issue 806). + + Performance improvements on all platforms. + + +2010-07-26: Version 2.3.3 + + Fixed error when building the d8 shell in a fresh checkout. + + Implemented Function.prototype.bind (ES5 15.3.4.5). + + Fixed an error in inlined stores on ia32. + + Fixed an error when setting a breakpoint at the end of a function + that does not end with a newline character. + + Performance improvements on all platforms. + + +2010-07-21: Version 2.3.2 + + Fixed compiler warnings when building with LLVM. + + Fixed a bug with for-in applied to strings (issue 785). + + Performance improvements on all platforms. + + +2010-07-19: Version 2.3.1 + + Fixed compilation and linking with V8_INTERPRETED_REGEXP flag. + + Fixed bug related to code flushing while compiling a lazy + compilable function (issue http://crbug.com/49099). + + Performance improvements on all platforms. + + +2010-07-15: Version 2.3.0 + + Added ES5 Object.seal and Object.isSealed. + + Added debugger API for scheduling debugger commands from a + separate thread. + + +2010-07-14: Version 2.2.24 + + Added API for capturing stack traces for uncaught exceptions. + + Fixed crash bug when preparsing from a non-external V8 string + (issue 775). + + Fixed JSON.parse bug causing input not to be converted to string + (issue 764). + + Added ES5 Object.freeze and Object.isFrozen. + + Performance improvements on all platforms. + + +2010-07-07: Version 2.2.23 + + API change: Convert Unicode code points outside the basic multilingual + plane to the replacement character. Previous behavior was to silently + truncate the value to 16 bits. + + Fixed crash: handle all flat string types in regexp replace. + + Prevent invalid pre-parsing data passed in through the API from + crashing V8. + + Performance improvements on all platforms. + + +2010-07-05: Version 2.2.22 + + Added ES5 Object.isExtensible and Object.preventExtensions. + + Enabled building V8 as a DLL. + + Fixed a bug in date code where -0 was not interpreted as 0 + (issue 736). + + Performance improvements on all platforms. + + +2010-06-30: Version 2.2.21 + + Fixed bug in externalizing some ASCII strings (Chromium issue 47824). + + Updated JSON.stringify to floor the space parameter (issue 753). + + Updated the Mozilla test expectations to the newest version. + + Updated the ES5 Conformance Test expectations to the latest version. + + Updated the V8 benchmark suite. + + Provide actual breakpoints locations in response to setBreakpoint + and listBreakpoints requests. + + +2010-06-28: Version 2.2.20 + + Fixed bug with for-in on x64 platform (issue 748). + + Fixed crash bug on x64 platform (issue 756). + + Fixed bug in Object.getOwnPropertyNames. (chromium issue 41243). + + Fixed a bug on ARM that caused the result of 1 << x to be + miscalculated for some inputs. + + Performance improvements on all platforms. + + +2010-06-23: Version 2.2.19 + + Fixed bug that causes the build to break when profillingsupport=off + (issue 738). + + Added expose-externalize-string flag for testing extensions. + + Resolve linker issues with using V8 as a DLL causing a number of + problems with unresolved symbols. + + Fixed build failure for cctests when ENABLE_DEBUGGER_SUPPORT is not + defined. + + Performance improvements on all platforms. + + +2010-06-16: Version 2.2.18 + + Added API functions to retrieve information on indexed properties + managed by the embedding layer. Fixes bug 737. + + Made ES5 Object.defineProperty support array elements. Fixes bug 619. + + Added heap profiling to the API. + + Removed old named property query from the API. + + Incremental performance improvements. + + +2010-06-14: Version 2.2.17 + + Improved debugger support for stepping out of functions. + + Incremental performance improvements. + + +2010-06-09: Version 2.2.16 + + Removed the SetExternalStringDiposeCallback API. Changed the + disposal of external string resources to call a virtual Dispose + method on the resource. + + Added support for more precise break points when debugging and + stepping. + + Memory usage improvements on all platforms. + + +2010-06-07: Version 2.2.15 + + Added an API to control the disposal of external string resources. + + Added missing initialization of a couple of variables which makes + some compilers complaint when compiling with -Werror. + + Improved performance on all platforms. + + +2010-06-02: Version 2.2.14 + + Fixed a crash in code generated for String.charCodeAt. + + Fixed a compilation issue with some GCC versions (issue 727). + + Performance optimizations on x64 and ARM platforms. + + +2010-05-31: Version 2.2.13 + + Implemented Object.getOwnPropertyDescriptor for element indices and + strings (issue 599). + + Fixed bug for windows 64 bit C calls from generated code. + + Added new scons flag unalignedaccesses for arm builds. + + Performance improvements on all platforms. + + +2010-05-26: Version 2.2.12 + + Allowed accessors to be defined on objects rather than just object + templates. + + Changed the ScriptData API. + + +2010-05-21: Version 2.2.11 + + Fixed crash bug in liveedit on 64 bit. + + Use 'full compiler' when debugging is active. This should increase + the density of possible break points, making single step more fine + grained. This will only take effect for functions compiled after + debugging has been started, so recompilation of all functions is + required to get the full effect. IA32 and x64 only for now. + + Misc. fixes to the Solaris build. + + Added new flags --print-cumulative-gc-stat and --trace-gc-nvp. + + Added filtering of CPU profiles by security context. + + Fixed crash bug on ARM when running without VFP2 or VFP3. + + Incremental performance improvements in all backends. + + +2010-05-17: Version 2.2.10 + + Performance improvements in the x64 and ARM backends. + + +2010-05-10: Version 2.2.9 + + Allowed Object.create to be called with a function (issue 697). + + Fixed bug with Date.parse returning a non-NaN value when called on a + non date string (issue 696). + + Allowed unaligned memory accesses on ARM targets that support it (by + Subrato K De of CodeAurora ). + + C++ API for retrieving JavaScript stack trace information. + + +2010-05-05: Version 2.2.8 + + Performance improvements in the x64 and ARM backends. + + +2010-05-03: Version 2.2.7 + + Added support for ES5 date time string format to Date.parse. + + Performance improvements in the x64 backend. + + +2010-04-28: Version 2.2.6 + + Added "amd64" as recognized architecture in scons build script + (by Ryan Dahl ). + + Fixed bug in String search and replace with very simple RegExps. + + Fixed bug in RegExp containing "\b^". + + Performance improvements on all platforms. + + +2010-04-26: Version 2.2.5 + + Various performance improvements (especially for ARM and x64) + + Fixed bug in CPU profiling (http://crbug.com/42137) + + Fixed a bug with the natives cache. + + Fixed two bugs in the ARM code generator that can cause + wrong calculations. + + Fixed a bug that may cause a wrong result for shift operations. + + +2010-04-21: Version 2.2.4 + + Fixed warnings on arm on newer GCC versions. + + Fixed a number of minor bugs. + + Performance improvements on all platforms. + + +2010-04-14: Version 2.2.3 + + Added stack command and mem command to ARM simulator debugger. + + Fixed scons snapshot and ARM build, and Windows X64 build issues. + + Performance improvements on all platforms. + + +2010-04-12: Version 2.2.2 + + Introduced new profiler API. + + Fixed random number generator to produce full 32 random bits. + + +2010-04-06: Version 2.2.1 + + Debugger improvements. + + Fixed minor bugs. + + +2010-03-29: Version 2.2.0 + + Fixed a few minor bugs. + + Performance improvements for string operations. + + +2010-03-26: Version 2.1.10 + + Fixed scons build issues. + + Fixed a couple of minor bugs. + + +2010-03-25: Version 2.1.9 + + Added API support for reattaching a global object to a context. + + Extended debugger API with access to the internal debugger context. + + Fixed Chromium crashes (issues http://crbug.com/39128 and + http://crbug.com/39160) + + +2010-03-24: Version 2.1.8 + + Added fine-grained garbage collection callbacks to the API. + + Performance improvements on all platforms. + + +2010-03-22: Version 2.1.7 + + Fixed issue 650. + + Fixed a bug where __proto__ was sometimes enumerated (issue 646). + + Performance improvements for arithmetic operations. + + Performance improvements for string operations. + + Print script name and line number information in stack trace. + + +2010-03-17: Version 2.1.6 + + Performance improvements for arithmetic operations. + + Performance improvements for string operations. + + +2010-03-10: Version 2.1.4 + + Fixed code cache lookup for keyed IC's (issue http://crbug.com/37853). + + Performance improvements on all platforms. + + +2010-03-10: Version 2.1.3 + + Added API method for context-disposal notifications. + + Added API method for accessing elements by integer index. + + Added missing implementation of Uint32::Value and Value::IsUint32 + API methods. + + Added IsExecutionTerminating API method. + + Disabled strict aliasing for GCC 4.4. + + Fixed string-concatenation bug (issue 636). + + Performance improvements on all platforms. + + +2010-02-23: Version 2.1.2 + + Fixed a crash bug caused by wrong assert. + + Fixed a bug with register names on 64-bit V8 (issue 615). + + Performance improvements on all platforms. + + +2010-02-19: Version 2.1.1 + + [ES5] Implemented Object.defineProperty. + + Improved profiler support. + + Added SetPrototype method in the public V8 API. + + Added GetScriptOrigin and GetScriptLineNumber methods to Function + objects in the API. + + Performance improvements on all platforms. + + +2010-02-03: Version 2.1.0 + + Values are now always wrapped in objects when used as a receiver. + (issue 223). + + [ES5] Implemented Object.getOwnPropertyNames. + + [ES5] Restrict JSON.parse to only accept strings that conforms to the + JSON grammar. + + Improvement of debugger agent (issue 549 and 554). + + Fixed problem with skipped stack frame in profiles (issue 553). + + Solaris support by Erich Ocean and Ryan Dahl + . + + Fixed a bug that Math.round() returns incorrect results for huge + integers. + + Fixed enumeration order for objects created from some constructor + functions (isue http://crbug.com/3867). + + Fixed arithmetic on some integer constants (issue 580). + + Numerous performance improvements including porting of previous IA-32 + optimizations to x64 and ARM architectures. + + +2010-01-14: Version 2.0.6 + + Added ES5 Object.getPrototypeOf, GetOwnPropertyDescriptor, + GetOwnProperty, FromPropertyDescriptor. + + Fixed Mac x64 build errors. + + Improved performance of some math and string operations. + + Improved performance of some regexp operations. + + Improved performance of context creation. + + Improved performance of hash tables. + + +2009-12-18: Version 2.0.5 + + Extended to upper limit of map space to allow for 7 times as many map + to be allocated (issue 524). + + Improved performance of code using closures. + + Improved performance of some binary operations involving doubles. + + +2009-12-16: Version 2.0.4 + + Added ECMAScript 5 Object.create. + + Improved performance of Math.max and Math.min. + + Optimized adding of strings on 64-bit platforms. + + Improved handling of external strings by using a separate table + instead of weak handles. This improves garbage collection + performance and uses less memory. + + Changed code generation for object and array literals in toplevel + code to be more compact by doing more work in the runtime. + + Fixed a crash bug triggered when garbage collection happened during + generation of a callback load inline cache stub. + + Fixed crash bug sometimes triggered when local variables shadowed + parameters in functions that used the arguments object. + + +2009-12-03: Version 2.0.3 + + Optimized handling and adding of strings, for-in and Array.join. + + Heap serialization is now non-destructive. + + Improved profiler support with information on time spend in C++ + callbacks registered through the API. + + Added commands to the debugger protocol for starting/stopping + profiling. + + Enabled the non-optimizing compiler for top-level code. + + Changed the API to only allow strings to be set as data objects on + Contexts and scripts to avoid potentially keeping global objects + around for too long (issue 528). + + OpenBSD support patch by Peter Valchev . + + Fixed bugs. + + +2009-11-24: Version 2.0.2 + + Improved profiler support. + + Fixed bug that broke compilation of d8 with readline support. + + +2009-11-20: Version 2.0.1 + + Fixed crash bug in String.prototype.replace. + + Reverted a change which caused Chromium interactive ui test + failures. + + +2009-11-18: Version 2.0.0 + + Added support for VFP on ARM. + + Added TryCatch::ReThrow method to the API. + + Reduced the size of snapshots and improved the snapshot load time. + + Improved heap profiler support. + + 64-bit version now supported on Windows. + + Fixed a number of debugger issues. + + Fixed bugs. + + +2009-10-29: Version 1.3.18 + + Reverted a change which caused crashes in RegExp replace. + + Reverted a change which caused Chromium ui_tests failure. + + +2009-10-28: Version 1.3.17 + + Added API method to get simple heap statistics. + + Improved heap profiler support. + + Fixed the implementation of the resource constraint API so it + works when using snapshots. + + Fixed a number of issues in the Windows 64-bit version. + + Optimized calls to API getters. + + Added valgrind notification on code modification to the 64-bit version. + + Fixed issue where we logged shared library addresses on Windows at + startup and never used them. + + +2009-10-16: Version 1.3.16 + + X64: Convert smis to holding 32 bits of payload. + + Introduced v8::Integer::NewFromUnsigned method. + + Added missing null check in Context::GetCurrent. + + Added trim, trimLeft and trimRight methods to String + Patch by Jan de Mooij + + Implement ES5 Array.isArray + Patch by Jan de Mooij + + Skip access checks for hidden properties. + + Added String::Concat(Handle left, Handle right) to the + V8 API. + + Fixed GYP-based builds of V8. + + +2009-10-07: Version 1.3.15 + + Expanded the maximum size of the code space to 512MB for 64-bit mode. + + Fixed a crash bug happening when starting profiling (issue + http://crbug.com/23768). + + +2009-10-07: Version 1.3.14 + + Added GetRealNamedProperty to the API to lookup real properties + located on the object or in the prototype chain skipping any + interceptors. + + Fixed the stack limits setting API to work correctly with threads. The + stack limit now needs to be set to each thread thich is used with V8. + + Removed the high-priority flag from IdleNotification() + + Ensure V8 is initialized before locking and unlocking threads. + + Implemented a new JavaScript minifier for compressing the source of + the built-in JavaScript. This removes non-Open Source code from Douglas + Crockford from the project. + + Added a missing optimization in StringCharAt. + + Fixed some flaky socket tests. + + Change by Alexander Botero-Lowry to fix profiler sampling on FreeBSD + in 64-bit mode. + + Fixed memory leaks in the thread management code. + + Fixed the result of assignment to a pixel array. The assigned value + is now the result. + + Error reporting for invalid left-hand sides in for-in statements, pre- + and postfix count expressions, and assignments now matches the JSC + behavior in Safari 4. + + Follow the spec in disallowing function declarations without a name. + + Always allocate code objects within a 2 GB range. On x64 architecture + this is used to use near calls (32-bit displacement) in Code objects. + + Optimized array construction ported to x64 and ARM architectures. + + [ES5] Changed Object.keys to return strings for element indices. + + +2009-09-23: Version 1.3.13 + + Fixed uninitialized memory problem. + + Improved heap profiler support. + + +2009-09-22: Version 1.3.12 + + Changed behavior of |function|.toString() on built-in functions to + be compatible with other implementations. Patch by Jan de Mooij. + + Added Object::IsDirty in the API. + + Optimized array construction; it is now handled purely in native + code. + + [ES5] Made properties of the arguments array enumerable. + + [ES5] Added test suite adapter for the es5conform test suite. + + [ES5] Added Object.keys function. + + +2009-09-15: Version 1.3.11 + + Fixed crash in error reporting during bootstrapping. + + Optimized generated IA32 math code by using SSE2 instructions when + available. + + Implemented missing pieces of debugger infrastructure on ARM. The + debugger is now fully functional on ARM. + + Made 'hidden' the default visibility for gcc. + + +2009-09-09: Version 1.3.10 + + Fixed profiler on Mac in 64-bit mode. + + Optimized creation of objects from simple constructor functions on + ARM. + + Fixed a number of debugger issues. + + Reduced the amount of memory consumed by V8. + + +2009-09-02: Version 1.3.9 + + Optimized stack guard checks on ARM. + + Optimized API operations by inlining more in the API. + + Optimized creation of objects from simple constructor functions. + + Enabled a number of missing optimizations in the 64-bit port. + + Implemented native-code support for regular expressions on ARM. + + Stopped using the 'sahf' instruction on 64-bit machines that do + not support it. + + Fixed a bug in the support for forceful termination of JavaScript + execution. + + +2009-08-26: Version 1.3.8 + + Changed the handling of idle notifications to allow idle + notifications when V8 has not yet been initialized. + + Fixed ARM simulator compilation problem on Windows. + + +2009-08-25: Version 1.3.7 + + Reduced the size of generated code on ARM platforms by reducing + the size of constant pools. + + Changed build files to not include the 'ENV' user environment + variable in the build environment. + + Changed the handling of idle notifications. + + +2009-08-21: Version 1.3.6 + + Added support for forceful termination of JavaScript execution. + + Added low memory notification to the API. The embedding host can signal + a low memory situation to V8. + + Changed the handling of global handles (persistent handles in the API + sense) to avoid issues regarding allocation of new global handles + during weak handle callbacks. + + Changed the growth policy of the young space. + + Fixed a GC issue introduced in version 1.3.5. + + +2009-08-19: Version 1.3.5 + + Optimized initialization of some arrays in the builtins. + + Fixed mac-nm script to support filenames with spaces. + + Support for using the V8 profiler when V8 is embedded in a Windows DLL. + + Changed typeof RegExp from 'object' to 'function' for compatibility. + Fixed bug where regexps were not callable across contexts. + + Added context independent script compilation to the API. + + Added API call to get the stack trace for an exception. + + Added API for getting object mirrors. + + Made sure that SSE3 instructions are used whenever possible even when + running off a snapshot generated without using SSE3 instructions. + + Tweaked the handling of the initial size and growth policy of the heap. + + Added native code generation for RegExp to 64-bit version. + + Added JavaScript debugger support to 64-bit version. + + +2009-08-13: Version 1.3.4 + + Added a readline() command to the d8 shell. + + Fixed bug in json parsing. + + Added idle notification to the API and reduced memory on idle + notifications. + + +2009-08-12: Version 1.3.3 + + Fixed issue 417: incorrect %t placeholder expansion. + + Added .gitignore file similar to Chromium's one. + + Fixed SConstruct file to build with new logging code for Android. + + API: added function to find instance of template in prototype + chain. Inlined Object::IsInstanceOf. + + Land change to notify valgrind when we modify code on x86. + + Added api call to determine whether a string can be externalized. + + Added a write() command to d8. + + +2009-08-05: Version 1.3.2 + + Started new compiler infrastructure for two-pass compilation using a + control flow graph constructed from the AST. + + Profiler stack sampling for X64. + + Safe handling of NaN to Posix platform-dependent time functions. + + Added a new profiler control API to unify controlling various aspects + of profiling. + + Fixed issue 392. + + +2009-07-30: Version 1.3.1 + + Speed improvements to accessors and interceptors. + + Added support for capturing stack information on custom errors. + + Added support for morphing an object into a pixel array where its + indexed properties are stored in an external byte array. Values written + are always clamped to the 0..255 interval. + + Profiler on x64 now handles C/C++ functions from shared libraries. + + Changed the debugger to avoid stepping into function.call/apply if the + function is a built-in. + + Initial implementation of constructor heap profile for JS objects. + + More fine grained control of profiling aspects through the API. + + Optimized the called as constructor check for API calls. + + +2009-07-27: Version 1.3.0 + + Allowed RegExp objects to be called as functions (issue 132). + + Fixed issue where global property cells would escape after + detaching the global object; see http://crbug.com/16276. + + Added support for stepping into setters and getters in the + debugger. + + Changed the debugger to avoid stopping in its own JavaScript code + and in the code of built-in functions. + + Fixed issue 345 by avoiding duplicate escaping labels. + + Fixed ARM code generator crash in short-circuited boolean + expressions and added regression tests. + + Added an external allocation limit to avoid issues where small V8 + objects would hold on to large amounts of external memory without + causing garbage collections. + + Finished more of the inline caching stubs for x64 targets. + + +2009-07-13: Version 1.2.14 + + Added separate paged heap space for global property cells and + avoid updating the write barrier when storing into them. + + Improved peep-hole optimization on ARM platforms by not emitting + unnecessary debug information. + + Re-enabled ICs for loads and calls that skip a global object + during lookup through the prototype chain. + + Allowed access through global proxies to use ICs. + + Fixed issue 401. + + +2009-07-09: Version 1.2.13 + + Fixed issue 397, issue 398, and issue 399. + + Added support for breakpoint groups. + + Fixed bugs introduced with the new global object representation. + + Fixed a few bugs in the ARM code generator. + + +2009-07-06: Version 1.2.12 + + Added stack traces collection to Error objects accessible through + the e.stack property. + + Changed RegExp parser to use a recursive data structure instead of + stack-based recursion. + + Optimized Date object construction and string concatenation. + + Improved performance of div, mod, and mul on ARM platforms. + + +2009-07-02: Version 1.2.11 + + Improved performance on IA-32 and ARM. + + Fixed profiler sampler implementation on Mac OS X. + + Changed the representation of global objects to improve + performance of adding a lot of new properties. + + +2009-06-29: Version 1.2.10 + + Improved debugger support. + + Fixed bug in exception message reporting (issue 390). + + Improved overall performance. + + +2009-06-23: Version 1.2.9 + + Improved math performance on ARM. + + Fixed profiler name-inference bug. + + Fixed handling of shared libraries in the profiler tick processor + scripts. + + Fixed handling of tests that time out in the test scripts. + + Fixed compilation on MacOS X version 10.4. + + Fixed two bugs in the regular expression engine. + + Fixed a bug in the string type inference. + + Fixed a bug in the handling of 'constant function' properties. + + Improved overall performance. + + +2009-06-16: Version 1.2.8 + + Optimized math on ARM platforms. + + Fixed two crash bugs in the handling of getters and setters. + + Improved the debugger support by adding scope chain information. + + Improved the profiler support by compressing log data transmitted + to clients. + + Improved overall performance. + + +2009-06-08: Version 1.2.7 + + Improved debugger and profiler support. + + Reduced compilation time by improving the handling of deferred + code. + + Optimized interceptor accesses where the property is on the object + on which the interceptors is attached. + + Fixed compilation problem on GCC 4.4 by changing the stack + alignment to 16 bytes. + + Fixed handle creation to follow stric aliasing rules. + + Fixed compilation on FreeBSD. + + Introduced API for forcing the deletion of a property ignoring + interceptors and attributes. + + +2009-05-29: Version 1.2.6 + + Added a histogram recording hit rates at different levels of the + compilation cache. + + Added stack overflow check for the RegExp analysis phase. Previously a + very long regexp graph could overflow the stack with recursive calls. + + Use a dynamic buffer when collecting log events in memory. + + Added start/stop events to the profiler log. + + Fixed infinite loop which could happen when setting a debug break while + executing a RegExp compiled to native code. + + Fixed handling of lastIndexOf called with negative index (issue 351). + + Fixed irregular crash in profiler test (issue 358). + + Fixed compilation issues with some versions of gcc. + + +2009-05-26: Version 1.2.5 + + Fixed bug in initial boundary check for Boyer-Moore text + search (issue 349). + + Fixed compilation issues with MinGW and gcc 4.3+ and added support + for armv7 and cortex-a8 architectures. Patches by Lei Zhang and + Craig Schlenter. + + Added a script cache to the debugger. + + Optimized compilation performance by improving internal data + structures and avoiding expensive property load optimizations for + code that's infrequently executed. + + Exposed the calling JavaScript context through the static API + function Context::GetCalling(). + + +2009-05-18: Version 1.2.4 + + Improved performance of floating point number allocation for ARM + platforms. + + Fixed crash when using the instanceof operator on functions with + number values in their prototype chain (issue 341). + + Optimized virtual frame operations in the code generator to speed + up compilation time and allocated the frames in the zone. + + Made the representation of virtual frames and jump targets in the + code generator much more compact. + + Avoided linear search for non-locals in scope code when resolving + variables inside with and eval scopes. + + Optimized lexical scanner by dealing with whitespace as part of + the token scanning instead of as a separate step before it. + + Changed the scavenging collector so that promoted objects do not + reside in the old generation while their remembered set is being + swept for pointers into the young generation. + + Fixed numeric overflow handling when compiling count operations. + + +2009-05-11: Version 1.2.3 + + Fixed bug in reporting of out-of-memory situations. + + Introduced hidden prototypes on certain builtin prototype objects + such as String.prototype to emulate JSC's behavior of restoring + the original function when deleting functions from those prototype + objects. + + Fixed crash bug in the register allocator. + + +2009-05-04: Version 1.2.2 + + Fixed bug in array sorting for sparse arrays (issue 326). + + Added support for adding a soname when building a shared library + on Linux (issue 151). + + Fixed bug caused by morphing internal ASCII strings to external + two-byte strings. Slices over ASCII strings have to forward ASCII + checks to the underlying buffer string. + + Allowed API call-as-function handlers to be called as + constructors. + + Fixed a crash bug where an external string was disposed but a + slice of the external string survived as a symbol. + + +2009-04-27: Version 1.2.1 + + Added EcmaScript 5 JSON object. + + Fixed bug in preemption support on ARM. + + +2009-04-23: Version 1.2.0 + + Optimized floating-point operations on ARM. + + Added a number of extensions to the debugger API. + + Changed the enumeration order for unsigned integer keys to always + be numerical order. + + Added a "read" extension to the shell sample. + + Added support for Array.prototype.reduce and + Array.prototype.reduceRight. + + Added an option to the SCons build to control Microsoft Visual C++ + link-time code generation. + + Fixed a number of bugs (in particular issue 315, issue 316, + issue 317 and issue 318). + + +2009-04-15: Version 1.1.10 + + Fixed crash bug that occurred when loading a const variable in the + presence of eval. + + Allowed using with and eval in registered extensions in debug mode + by fixing bogus assert. + + Fixed the source position for function returns to enable the + debugger to break there. + + +2009-04-14: Version 1.1.9 + + Made the stack traversal code in the profiler robust by avoiding + to look into the heap. + + Added name inferencing for anonymous functions to facilitate + debugging and profiling. + + Re-enabled stats timers in the developer shell (d8). + + Fixed issue 303 by avoiding to shortcut cons-symbols. + + +2009-04-11: Version 1.1.8 + + Changed test-debug/ThreadedDebugging to be non-flaky (issue 96). + + Fixed step-in handling for Function.prototype.apply and call in + the debugger (issue 269). + + Fixed v8::Object::DeleteHiddenValue to not bail out when there + are no hidden properties. + + Added workaround for crash bug, where external symbol table + entries with deleted resources would lead to NPEs when looking + up in the symbol table. + + +2009-04-07: Version 1.1.7 + + Added support for easily importing additional environment + variables into the SCons build. + + Optimized strict equality checks. + + Fixed crash in indexed setters on objects without a corresponding + getter (issue 298). + + Re-enabled script compilation cache. + + +2009-04-01: Version 1.1.6 + + Reverted an unsafe code generator change. + + +2009-04-01: Version 1.1.5 + + Fixed bug that caused function literals to not be optimized as + much as other functions. + + Improved profiler support. + + Fixed a crash bug in connection with debugger unloading. + + Fixed a crash bug in the code generator caused by losing the + information that a frame element was copied. + + Fixed an exception propagation bug that could cause non-null + return values when exceptions were thrown. + + +2009-03-30: Version 1.1.4 + + Optimized String.prototype.match. + + Improved the stack information in profiles. + + Fixed bug in ARM port making it possible to compile the runtime + system for thumb mode again. + + Implemented a number of optimizations in the code generator. + + Fixed a number of memory leaks in tests. + + Fixed crash bug in connection with script source code and external + strings. + + +2009-03-24: Version 1.1.3 + + Fixed assertion failures in compilation of loop conditions. + + Removed STL dependency from developer shell (d8). + + Added infrastructure for protecting the V8 heap from corruption + caused by memory modifications from the outside. + + +2009-03-24: Version 1.1.2 + + Improved frame merge code generated by the code generator. + + Optimized String.prototype.replace. + + Implemented __defineGetter__ and __defineSetter__ for properties + with integer keys on non-array objects. + + Improved debugger and profiler support. + + Fixed a number of portability issues to allow compilation for + smaller ARM devices. + + Exposed object cloning through the API. + + Implemented hidden properties. This is used to expose an identity + hash for objects through the API. + + Implemented restarting of regular expressions if their input + string changes representation during preemption. + + Fixed a code generator bug that could cause assignments in loops + to be ignored if using continue to break out of the loop (issue + 284). + + +2009-03-12: Version 1.1.1 + + Fixed an assertion in the new compiler to take stack overflow + exceptions into account. + + Removed exception propagation code that could cause crashes. + + Fixed minor bug in debugger line number computations. + + 8-byte align the C stack on Linux and Windows to speed up floating + point computations. + + +2009-03-12: Version 1.1.0 + + Improved code generation infrastructure by doing simple register + allocation and constant folding and propagation. + + Optimized regular expression matching by avoiding to create + intermediate string arrays and by flattening nested array + representations of RegExp data. + + Traverse a few stack frames when recording profiler samples to + include partial call graphs in the profiling output. + + Added support for using OProfile to profile generated code. + + Added remote debugging support to the D8 developer shell. + + Optimized creation of nested literals like JSON objects. + + Fixed a bug in garbage collecting unused maps and turned it on by + default (--collect-maps). + + Added support for running tests under Valgrind. + + +2009-02-27: Version 1.0.3 + + Optimized double-to-integer conversions in bit operations by using + SSE3 instructions if available. + + Optimized initialization sequences that store to multiple + properties of the same object. + + Changed the D8 debugger frontend to use JSON messages. + + Force garbage collections when disposing contexts. + + Align code objects at 32-byte boundaries. + + +2009-02-25: Version 1.0.2 + + Improved profiling support by performing simple call stack + sampling for ticks and by fixing a bug in the logging of code + addresses. + + Fixed a number of debugger issues. + + Optimized code that uses eval. + + Fixed a couple of bugs in the regular expression engine. + + Reduced the size of generated code for certain regular expressions. + + Removed JSCRE completely. + + Fixed issue where test could not be run if there was a dot in the + checkout path. + + +2009-02-13: Version 1.0.1 + + Fixed two crash-bugs in irregexp (issue 231 and 233). + + Fixed a number of minor bugs (issue 87, 227 and 228). + + Added support for morphing strings to external strings on demand + to avoid having to create copies in the embedding code. + + Removed experimental support for external symbol callbacks. + + +2009-02-09: Version 1.0.0 + + Fixed crash-bug in the code generation for case independent 16 bit + backreferences. + + Made shells more robust in the presence of string conversion + failures (issue 224). + + Fixed a potential infinite loop when attempting to resolve + eval (issue 221). + + Miscellaneous fixes to the new regular expression engine. + + Reduced binary by stripping unneeded text from JavaScript library and + minifying some JavaScript files. + + +2009-01-27: Version 0.4.9 + + Enabled new regular expression engine. + + Made a number of changes to the debugger protocol. + + Fixed a number of bugs in the preemption support. + + Added -p option to the developer shell to run files in parallel + using preemption. + + Fixed a number of minor bugs (including issues 176, 187, 189, 192, + 193, 198 and 201). + + Fixed a number of bugs in the serialization/deserialization + support for the ARM platform. + + +2009-01-19: Version 0.4.8.1 + + Minor patch to debugger support. + + +2009-01-16: Version 0.4.8 + + Fixed string length bug on ARM (issue 171). + + Made most methods in the API const. + + Optimized object literals by improving data locality. + + Fixed bug that caused incomplete functions to be cached in case of + stack overflow exceptions. + + Fixed bugs that caused catch variables and variables introduced by + eval to behave incorrectly when using accessors (issues 186, 190 + and 191). + + +2009-01-06: Version 0.4.7 + + Minor bugfixes and optimizations. + + Added command line debugger to D8 shell. + + Fixed subtle bug that caused the wrong 'this' to be used when + calling a caught function in a catch clause. + + Inline array loads within loops directly in the code instead of + always calling a stub. + + +2008-12-11: Version 0.4.6 + + Fixed exception reporting bug where certain exceptions were + incorrectly reported as uncaught. + + Improved the memory allocation strategy used during compilation to + make running out of memory when compiling huge scripts less + likely. + + Optimized String.replace by avoiding the construction of certain + sub strings. + + Fixed bug in code generation for large switch statements on ARM. + + Fixed bug that caused V8 to change the global object template + passed in by the user. + + Changed the API for creating object groups used during garbage + collection. Entire object groups are now passed to V8 instead of + individual members of the groups. + + +2008-12-03: Version 0.4.5 + + Added experimental API support for allocating V8 symbols as + external strings. + + Fixed bugs in debugging support on ARM. + + Changed eval implementation to correctly detect whether or not a + call to eval is aliased. + + Fixed bug caused by a combination of the compilation cache and + dictionary probing in native code. The bug caused us to sometimes + call functions that had not yet been compiled. + + Added platform support for FreeBSD. + + Added support for building V8 on Windows with either the shared or + static version of MSVCRT + + Added the v8::jscre namespace around the jscre functions to avoid + link errors (duplicate symbols) when building Google Chrome. + + Added support for calling a JavaScript function with the current + debugger execution context as its argument to the debugger + interface. + + Changed the type of names of counters from wchar_t to char. + + Changed the Windows system call used to compute daylight savings + time. The system call that we used to use became four times + slower on WinXP SP3. + + Added support in the d8 developer shell for memory-mapped counters + and added a stats-viewer tool. + + Fixed bug in upper/lower case mappings (issue 149). + + +2008-11-17: Version 0.4.4 + + Reduced code size by using shorter instruction encoding when + possible. + + Added a --help option to the shell sample and to the d8 shell. + + Added visual studio project files for building the ARM simulator. + + Fixed a number of ARM simulator issues. + + Fixed bug in out-of-memory handling on ARM. + + Implemented shell support for passing arguments to a script from + the command line. + + Fixed bug in date code that made certain date functions return -0 + instead of 0 for dates before the epoch. + + Restricted applications of eval so it can only be used in the + context of the associated global object. + + Treat byte-order marks as whitespace characters. + + +2008-11-04: Version 0.4.3 + + Added support for API accessors that prohibit overwriting by + accessors defined in JavaScript code by using __defineGetter__ and + __defineSetter__. + + Improved handling of conditionals in test status files. + + Introduced access control in propertyIsEnumerable. + + Improved performance of some string operations by caching + information about the type of the string between operations. + + Fixed bug in fast-case code for switch statements that only have + integer labels. + + +2008-10-30: Version 0.4.2 + + Improved performance of Array.prototype.concat by moving the + implementation to C++ (issue 123). + + Fixed heap growth policy to avoid growing old space to its maximum + capacity before doing a garbage collection and fixed issue that + would lead to artificial out of memory situations (issue 129). + + Fixed Date.prototype.toLocaleDateString to return the date in the + same format as WebKit. + + Added missing initialization checks to debugger API. + + Added removing of unused maps during GC. + + +2008-10-28: Version 0.4.1 + + Added caching of RegExp data in compilation cache. + + Added Visual Studio project file for d8 shell. + + Fixed function call performance regression introduced in version + 0.4.0 when splitting the global object in two parts (issue 120). + + Fixed issue 131 by checking for empty handles before throwing and + reporting exceptions. + + +2008-10-23: Version 0.4.0 + + Split the global object into two parts: The state holding global + object and the global object proxy. + + Fixed bug that affected the value of an assignment to an element + in certain cases (issue 116). + + Added GetPropertyNames functionality (issue 33) and extra Date + functions (issue 77) to the API. + + Changed WeakReferenceCallback to take a Persistent instead + of a Persistent (issue 101). + + Fixed issues with message reporting for exceptions in try-finally + blocks (issues 73 and 75). + + Optimized flattening of strings and string equality checking. + + Improved Boyer-Moore implementation for faster indexOf operations. + + Added development shell (d8) which includes counters and + completion support. + + Fixed problem with the receiver passed to functions called from + eval (issue 124). + + +2008-10-16: Version 0.3.5 + + Improved string hash-code distribution by excluding bit-field bits + from the hash-code. + + Changed string search algorithm used in indexOf from KMP to + Boyer-Moore. + + Improved the generated code for the instanceof operator. + + Improved performance of slow-case string equality checks by + specializing the code based on the string representation. + + Improve the handling of out-of-memory situations (issue 70). + + Improved performance of strict equality checks. + + Improved profiler output to make it easier to see anonymous + functions. + + Improved performance of slow-case keyed loads. + + Improved property access performance by allocating a number of + properties in the front object. + + Changed the toString behavior on the built-in object constructors + to print [native code] instead of the actual source. Some web + applications do not like constructors with complex toString + results. + + +2008-10-06: Version 0.3.4 + + Changed Array.prototype.sort to use quick sort. + + Fixed code generation issue where leaving a finally block with + break or continue would accumulate elements on the expression + stack (issue 86). + + Made sure that the name accessor on functions returns the expected + names for builtin JavaScript functions and C++ callback functions. + + Added fast case code for extending the property storage array of + JavaScript objects. + + Ported switch statement optimizations introduced in version 0.3.3 + to the ARM code generator. + + Allowed GCC to use strict-aliasing rules when compiling. + + Improved performance of arguments object allocation by taking care + of arguments adaptor frames in the generated code. + + Updated the V8 benchmark suite to version 2. + + +2008-09-25: Version 0.3.3 + + Improved handling of relocation information to enable more + peep-hole optimizations. + + Optimized switch statements where all labels are constant small + integers. + + Optimized String.prototype.indexOf for common cases. + + Fixed more build issues (issue 80). + + Fixed a couple of profiler issues. + + Fixed bug where the body of a function created using the Function + constructor was not allowed to end with a single-line comment + (issue 85). + + Improved handling of object literals by canonicalizing object + literal maps. This will allow JSON objects with the same set of + properties to share the same map making inline caching work better + for JSON objects. + + +2008-09-17: Version 0.3.2 + + Generalized the EvalCache into a CompilationCache and enabled it + for scripts too. The current strategy is to retire all entries + whenever a mark-sweep collection is started. + + Fixed bug where switch statements containing only a default case + would lead to an unbalanced stack (issue 69). + + Fixed bug that made access to the function in a named function + expression impossible in certain situations (issue 24). + + Fixed even more build issues. + + Optimized calling conventions on ARM. The conventions on ARM and + IA-32 now match. + + Removed static initializers for flags and counters. + + Improved inline caching behavior for uncommon cases where lazily + loading Date and RegExp code could force certain code paths go + megamorphic. + + Removed arguments adaption for builtins written in C++. This + makes Array.prototype.push and Array.prototype.pop slightly + faster. + + +2008-09-11: Version 0.3.1 + + Fixed a number of build issues. + + Fixed problem with missing I-cache flusing on ARM. + + Changed space layout in memory management by splitting up + code space into old data space and code space. + + Added utf-8 conversion support to the API (issue 57). + + Optimized repeated calls to eval with the same strings. These + repeated calls are common in web applications. + + Added Xcode project file. + + Optimized a couple of Array operation. + + Fixed parser bug by checking for end-of-string when parsing break + and continue (issue 35). + + Fixed problem where asian characters were not categorized as + letters. + + Fixed bug that disallowed calling functions fetched from an array + using a string as an array index (issue 32). + + Fixed bug where the internal field count on object templates were + sometimes ignored (issue 54). + + Added -f option to the shell sample for compatibility with other + engines (issue 18). + + Added source info to TryCatches in the API. + + Fixed problem where the seed for the random number generator was + clipped in a double to unsigned int conversion. + + Fixed bug where cons string symbols were sometimes converted to + non-symbol flat strings during GC. + + Fixed bug in error reporting when attempting to convert null to an + object. + + +2008-09-04: Version 0.3.0 + + Added support for running tests on the ARM simulator. + + Fixed bug in the 'in' operator where negative indices were not + treated correctly. + + Fixed build issues on gcc-4.3.1. + + Changed Date.prototype.toLocaleTimeString to not print the + timezone part of the time. + + Renamed debug.h to v8-debug.h to reduce the risk of name conflicts + with user code. + + +2008-09-02: Version 0.2.5 + + Renamed the top level directory 'public' to 'include'. + + Added 'env' option to the SCons build scripts to support + overriding the ENV part of the build environment. This is mostly + to support Windows builds in cases where SCons cannot find the + correct paths to the Windows SDK, as these paths cannot be passed + through shell environment variables. + + Enabled "Buffer Security Check" on for the Windows SCons build and + added the linker option /OPT:ICF as an optimization. + + Added the V8 benchmark suite to the repository. + + +2008-09-01: Version 0.2.4 + + Included mjsunit JavaScript test suite and C++ unit tests. + + Changed the shell sample to not print the result of executing a + script provided on the command line. + + Fixed issue when building samples on Windows using a shared V8 + library. Added visibility option on Linux build which makes the + generated library 18% smaller. + + Changed build system to accept multiple build modes in one build + and generate separate objects, libraries and executables for each + mode. + + Removed deferred negation optimization (a * -b => -(a * b)) since + this visibly changes operand conversion order. + + Improved parsing performance by introducing stack guard in + preparsing. Without a stack guard preparsing always bails out + with stack overflow. + + Changed shell sample to take flags directly from the command-line. + Added API call that implements this. + + Added load, quit and version functions to the shell sample so it's + easier to run benchmarks and tests. + + Fixed issue with building samples and cctests on 64-bit machines. + + Fixed bug in the runtime system where the prototype chain was not + always searched for a setter when setting a property that does not + exist locally. + + +2008-08-14: Version 0.2.3 + + Improved performance of garbage collection by moving the + function that updates pointers during compacting collection + into the updating visitor. This gives the compiler a better + chance to inline and avoid a function call per (potential) + pointer. + + Extended the shell sample with a --runtime-flags option. + + Added Visual Studio project files for the shell.cc and + process.cc samples. + + +2008-08-13: Version 0.2.2 + + Improved performance of garbage collection by changing the way + we use the marking stack in the event of stack overflow during + full garbage collection and by changing the way we mark roots. + + Cleaned up ARM version by removing top of stack caching and by + introducing push/pop elimination. + + Cleaned up the way runtime functions are called to allow + runtime calls with no arguments. + + Changed Windows build options to make sure that exceptions are + disabled and that optimization flags are enabled. + + Added first version of Visual Studio project files. + + +2008-08-06: Version 0.2.1 + + Improved performance of unary addition by avoiding runtime calls. + + Fixed the handling of '>' and '<=' to use right-to-left conversion + and left-to-right evaluation as specified by ECMA-262. + + Fixed a branch elimination bug on the ARM platform where incorrect + code was generated because of overly aggressive branch + elimination. + + Improved performance of code that repeatedly assigns the same + function to the same property of different objects with the same + map. + + Untangled DEBUG and ENABLE_DISASSEMBLER defines. The disassembler + no longer expects DEBUG to be defined. + + Added platform-nullos.cc to serve as the basis for new platform + implementations. + + +2008-07-30: Version 0.2.0 + + Changed all text files to have native svn:eol-style. + + Added a few samples and support for building them. The samples + include a simple shell that can be used to benchmark and test V8. + + Changed V8::GetVersion to return the version as a string. + + Added source for lazily loaded scripts to snapshots and made + serialization non-destructive. + + Improved ARM support by fixing the write barrier code to use + aligned loads and stores and by removing premature locals + optimization that relied on broken support for callee-saved + registers (removed). + + Refactored the code for marking live objects during garbage + collection and the code for allocating objects in paged + spaces. Introduced an abstraction for the map word of a heap- + allocated object and changed the memory allocator to allocate + executable memory only for spaces that may contain code objects. + + Moved StringBuilder to utils.h and ScopedLock to platform.h, where + they can be used by debugging and logging modules. Added + thread-safe message queues for dealing with debugger events. + + Fixed the source code reported by toString for certain builtin + empty functions and made sure that the prototype property of a + function is enumerable. + + Improved performance of converting values to condition flags in + generated code. + + Merged disassembler-{arch} files. + + +2008-07-28: Version 0.1.4 + + Added support for storing JavaScript stack traces in a stack + allocated buffer to make it visible in shallow core dumps. + Controlled by the --preallocate-message-memory flag which is + disabled by default. + + +2008-07-25: Version 0.1.3 + + Fixed bug in JSObject::GetPropertyAttributePostInterceptor where + map transitions would count as properties. + + Allowed aliased eval invocations by treating them as evals in the + global context. This may change in the future. + + Added support for accessing the last entered context through the + API and renamed Context::Current to Context::GetCurrent and + Context::GetSecurityContext to Context::GetCurrentSecurityContext. + + Fixed bug in the debugger that would cause the debugger scripts to + be recursively loaded and changed all disabling of interrupts to + be block-structured. + + Made snapshot data read-only to allow it to be more easily shared + across multiple users of V8 when linked as a shared library. + + +2008-07-16: Version 0.1.2 + + Fixed building on Mac OS X by recognizing i386 and friends as + IA-32 platforms. + + Added propagation of stack overflow exceptions that occur while + compiling nested functions. + + Improved debugger with support for recursive break points and + handling of exceptions that occur in the debugger JavaScript code. + + Renamed GetInternal to GetInternalField and SetInternal to + SetInternalField in the API and moved InternalFieldCount and + SetInternalFieldCount from FunctionTemplate to ObjectTemplate. + + +2008-07-09: Version 0.1.1 + + Fixed bug in stack overflow check code for IA-32 targets where a + non-tagged value in register eax was pushed to the stack. + + Fixed potential quadratic behavior when converting strings to + numbers. + + Fixed bug where the return value from Object::SetProperty could + end up being the property holder instead of the written value. + + Improved debugger support by allowing nested break points and by + dealing with stack-overflows when compiling functions before + setting break points in them. + + +2008-07-03: Version 0.1.0 + + Initial export. + +# Local Variables: +# mode:text +# End: diff --git a/node-v0.8.14/deps/v8/DEPS b/node-v0.8.14/deps/v8/DEPS new file mode 100644 index 0000000..e50d1d2 --- /dev/null +++ b/node-v0.8.14/deps/v8/DEPS @@ -0,0 +1,27 @@ +# Note: The buildbots evaluate this file with CWD set to the parent +# directory and assume that the root of the checkout is in ./v8/, so +# all paths in here must match this assumption. + +deps = { + # Remember to keep the revision in sync with the Makefile. + "v8/build/gyp": + "http://gyp.googlecode.com/svn/trunk@1282", +} + +deps_os = { + "win": { + "v8/third_party/cygwin": + "http://src.chromium.org/svn/trunk/deps/third_party/cygwin@66844", + + "v8/third_party/python_26": + "http://src.chromium.org/svn/trunk/tools/third_party/python_26@89111", + } +} + +hooks = [ + { + # A change to a .gyp, .gypi, or to GYP itself should run the generator. + "pattern": ".", + "action": ["python", "v8/build/gyp_v8"], + }, +] diff --git a/node-v0.8.14/deps/v8/LICENSE b/node-v0.8.14/deps/v8/LICENSE new file mode 100644 index 0000000..2e516ba --- /dev/null +++ b/node-v0.8.14/deps/v8/LICENSE @@ -0,0 +1,54 @@ +This license applies to all parts of V8 that are not externally +maintained libraries. The externally maintained libraries used by V8 +are: + + - PCRE test suite, located in + test/mjsunit/third_party/regexp-pcre.js. This is based on the + test suite from PCRE-7.3, which is copyrighted by the University + of Cambridge and Google, Inc. The copyright notice and license + are embedded in regexp-pcre.js. + + - Layout tests, located in test/mjsunit/third_party. These are + based on layout tests from webkit.org which are copyrighted by + Apple Computer, Inc. and released under a 3-clause BSD license. + + - Strongtalk assembler, the basis of the files assembler-arm-inl.h, + assembler-arm.cc, assembler-arm.h, assembler-ia32-inl.h, + assembler-ia32.cc, assembler-ia32.h, assembler-x64-inl.h, + assembler-x64.cc, assembler-x64.h, assembler-mips-inl.h, + assembler-mips.cc, assembler-mips.h, assembler.cc and assembler.h. + This code is copyrighted by Sun Microsystems Inc. and released + under a 3-clause BSD license. + + - Valgrind client API header, located at third_party/valgrind/valgrind.h + This is release under the BSD license. + +These libraries have their own licenses; we recommend you read them, +as their terms may differ from the terms below. + +Copyright 2006-2012, the V8 project authors. All rights reserved. +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above + copyright notice, this list of conditions and the following + disclaimer in the documentation and/or other materials provided + with the distribution. + * Neither the name of Google Inc. nor the names of its + contributors may be used to endorse or promote products derived + from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/node-v0.8.14/deps/v8/LICENSE.strongtalk b/node-v0.8.14/deps/v8/LICENSE.strongtalk new file mode 100644 index 0000000..9bd62e4 --- /dev/null +++ b/node-v0.8.14/deps/v8/LICENSE.strongtalk @@ -0,0 +1,29 @@ +Copyright (c) 1994-2006 Sun Microsystems Inc. +All Rights Reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + +- Redistributions of source code must retain the above copyright notice, +this list of conditions and the following disclaimer. + +- Redistribution in binary form must reproduce the above copyright +notice, this list of conditions and the following disclaimer in the +documentation and/or other materials provided with the distribution. + +- Neither the name of Sun Microsystems or the names of contributors may +be used to endorse or promote products derived from this software without +specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS +IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF +LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/node-v0.8.14/deps/v8/LICENSE.v8 b/node-v0.8.14/deps/v8/LICENSE.v8 new file mode 100644 index 0000000..933718a --- /dev/null +++ b/node-v0.8.14/deps/v8/LICENSE.v8 @@ -0,0 +1,26 @@ +Copyright 2006-2011, the V8 project authors. All rights reserved. +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above + copyright notice, this list of conditions and the following + disclaimer in the documentation and/or other materials provided + with the distribution. + * Neither the name of Google Inc. nor the names of its + contributors may be used to endorse or promote products derived + from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/node-v0.8.14/deps/v8/LICENSE.valgrind b/node-v0.8.14/deps/v8/LICENSE.valgrind new file mode 100644 index 0000000..fd8ebaf --- /dev/null +++ b/node-v0.8.14/deps/v8/LICENSE.valgrind @@ -0,0 +1,45 @@ +---------------------------------------------------------------- + +Notice that the following BSD-style license applies to this one +file (valgrind.h) only. The rest of Valgrind is licensed under the +terms of the GNU General Public License, version 2, unless +otherwise indicated. See the COPYING file in the source +distribution for details. + +---------------------------------------------------------------- + +This file is part of Valgrind, a dynamic binary instrumentation +framework. + +Copyright (C) 2000-2007 Julian Seward. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: + +1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + +2. The origin of this software must not be misrepresented; you must + not claim that you wrote the original software. If you use this + software in a product, an acknowledgment in the product + documentation would be appreciated but is not required. + +3. Altered source versions must be plainly marked as such, and must + not be misrepresented as being the original software. + +4. The name of the author may not be used to endorse or promote + products derived from this software without specific prior written + permission. + +THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS +OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE +GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, +WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/node-v0.8.14/deps/v8/Makefile b/node-v0.8.14/deps/v8/Makefile new file mode 100644 index 0000000..0d825c0 --- /dev/null +++ b/node-v0.8.14/deps/v8/Makefile @@ -0,0 +1,256 @@ +# Copyright 2012 the V8 project authors. All rights reserved. +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above +# copyright notice, this list of conditions and the following +# disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of Google Inc. nor the names of its +# contributors may be used to endorse or promote products derived +# from this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + +# Variable default definitions. Override them by exporting them in your shell. +CXX ?= g++ +LINK ?= g++ +OUTDIR ?= out +TESTJOBS ?= -j16 +GYPFLAGS ?= +TESTFLAGS ?= +ANDROID_NDK_ROOT ?= +ANDROID_TOOL_PREFIX = $(ANDROID_NDK_ROOT)/toolchain/bin/arm-linux-androideabi + +# Special build flags. Use them like this: "make library=shared" + +# library=shared || component=shared_library +ifeq ($(library), shared) + GYPFLAGS += -Dcomponent=shared_library +endif +ifdef component + GYPFLAGS += -Dcomponent=$(component) +endif +# console=readline +ifdef console + GYPFLAGS += -Dconsole=$(console) +endif +# disassembler=on +ifeq ($(disassembler), on) + GYPFLAGS += -Dv8_enable_disassembler=1 +endif +# objectprint=on +ifeq ($(objectprint), on) + GYPFLAGS += -Dv8_object_print=1 +endif +# snapshot=off +ifeq ($(snapshot), off) + GYPFLAGS += -Dv8_use_snapshot='false' +endif +# gdbjit=on +ifeq ($(gdbjit), on) + GYPFLAGS += -Dv8_enable_gdbjit=1 +endif +# liveobjectlist=on +ifeq ($(liveobjectlist), on) + GYPFLAGS += -Dv8_use_liveobjectlist=true +endif +# vfp3=off +ifeq ($(vfp3), off) + GYPFLAGS += -Dv8_can_use_vfp_instructions=false +else + GYPFLAGS += -Dv8_can_use_vfp_instructions=true +endif +# debuggersupport=off +ifeq ($(debuggersupport), off) + GYPFLAGS += -Dv8_enable_debugger_support=0 +endif +# soname_version=1.2.3 +ifdef soname_version + GYPFLAGS += -Dsoname_version=$(soname_version) +endif +# werror=no +ifeq ($(werror), no) + GYPFLAGS += -Dwerror='' +endif +# presubmit=no +ifeq ($(presubmit), no) + TESTFLAGS += --no-presubmit +endif +# strictaliasing=off (workaround for GCC-4.5) +ifeq ($(strictaliasing), off) + GYPFLAGS += -Dv8_no_strict_aliasing=1 +endif + +# ----------------- available targets: -------------------- +# - "dependencies": pulls in external dependencies (currently: GYP) +# - any arch listed in ARCHES (see below) +# - any mode listed in MODES +# - every combination ., e.g. "ia32.release" +# - "native": current host's architecture, release mode +# - any of the above with .check appended, e.g. "ia32.release.check" +# - "android": cross-compile for Android/ARM (release mode) +# - default (no target specified): build all DEFAULT_ARCHES and MODES +# - "check": build all targets and run all tests +# - ".clean" for any in ARCHES +# - "clean": clean all ARCHES + +# ----------------- internal stuff ------------------------ + +# Architectures and modes to be compiled. Consider these to be internal +# variables, don't override them (use the targets instead). +ARCHES = ia32 x64 arm mips +DEFAULT_ARCHES = ia32 x64 arm +MODES = release debug + +# List of files that trigger Makefile regeneration: +GYPFILES = build/all.gyp build/common.gypi build/standalone.gypi \ + preparser/preparser.gyp samples/samples.gyp src/d8.gyp \ + test/cctest/cctest.gyp tools/gyp/v8.gyp + +# Generates all combinations of ARCHES and MODES, e.g. "ia32.release". +BUILDS = $(foreach mode,$(MODES),$(addsuffix .$(mode),$(ARCHES))) +# Generates corresponding test targets, e.g. "ia32.release.check". +CHECKS = $(addsuffix .check,$(BUILDS)) +# File where previously used GYPFLAGS are stored. +ENVFILE = $(OUTDIR)/environment + +.PHONY: all check clean dependencies $(ENVFILE).new native \ + $(ARCHES) $(MODES) $(BUILDS) $(CHECKS) $(addsuffix .clean,$(ARCHES)) \ + $(addsuffix .check,$(MODES)) $(addsuffix .check,$(ARCHES)) \ + must-set-ANDROID_NDK_ROOT + +# Target definitions. "all" is the default. +all: $(MODES) + +# Special target for the buildbots to use. Depends on $(OUTDIR)/Makefile +# having been created before. +buildbot: + $(MAKE) -C "$(OUTDIR)" BUILDTYPE=$(BUILDTYPE) \ + builddir="$(abspath $(OUTDIR))/$(BUILDTYPE)" + +# Compile targets. MODES and ARCHES are convenience targets. +.SECONDEXPANSION: +$(MODES): $(addsuffix .$$@,$(DEFAULT_ARCHES)) + +$(ARCHES): $(addprefix $$@.,$(MODES)) + +# Defines how to build a particular target (e.g. ia32.release). +$(BUILDS): $(OUTDIR)/Makefile.$$(basename $$@) + @$(MAKE) -C "$(OUTDIR)" -f Makefile.$(basename $@) \ + CXX="$(CXX)" LINK="$(LINK)" \ + BUILDTYPE=$(shell echo $(subst .,,$(suffix $@)) | \ + python -c "print raw_input().capitalize()") \ + builddir="$(shell pwd)/$(OUTDIR)/$@" + +native: $(OUTDIR)/Makefile.native + @$(MAKE) -C "$(OUTDIR)" -f Makefile.native \ + CXX="$(CXX)" LINK="$(LINK)" BUILDTYPE=Release \ + builddir="$(shell pwd)/$(OUTDIR)/$@" + +# TODO(jkummerow): add "android.debug" when we need it. +android android.release: $(OUTDIR)/Makefile.android + @$(MAKE) -C "$(OUTDIR)" -f Makefile.android \ + CXX="$(ANDROID_TOOL_PREFIX)-g++" \ + AR="$(ANDROID_TOOL_PREFIX)-ar" \ + RANLIB="$(ANDROID_TOOL_PREFIX)-ranlib" \ + CC="$(ANDROID_TOOL_PREFIX)-gcc" \ + LD="$(ANDROID_TOOL_PREFIX)-ld" \ + LINK="$(ANDROID_TOOL_PREFIX)-g++" \ + BUILDTYPE=Release \ + builddir="$(shell pwd)/$(OUTDIR)/android.release" + +# Test targets. +check: all + @tools/test-wrapper-gypbuild.py $(TESTJOBS) --outdir=$(OUTDIR) \ + --arch=$(shell echo $(DEFAULT_ARCHES) | sed -e 's/ /,/g') \ + $(TESTFLAGS) + +$(addsuffix .check,$(MODES)): $$(basename $$@) + @tools/test-wrapper-gypbuild.py $(TESTJOBS) --outdir=$(OUTDIR) \ + --mode=$(basename $@) $(TESTFLAGS) + +$(addsuffix .check,$(ARCHES)): $$(basename $$@) + @tools/test-wrapper-gypbuild.py $(TESTJOBS) --outdir=$(OUTDIR) \ + --arch=$(basename $@) $(TESTFLAGS) + +$(CHECKS): $$(basename $$@) + @tools/test-wrapper-gypbuild.py $(TESTJOBS) --outdir=$(OUTDIR) \ + --arch-and-mode=$(basename $@) $(TESTFLAGS) + +native.check: native + @tools/test-wrapper-gypbuild.py $(TESTJOBS) --outdir=$(OUTDIR)/native \ + --arch-and-mode=. $(TESTFLAGS) + +# Clean targets. You can clean each architecture individually, or everything. +$(addsuffix .clean,$(ARCHES)) android.clean: + rm -f $(OUTDIR)/Makefile.$(basename $@) + rm -rf $(OUTDIR)/$(basename $@).release + rm -rf $(OUTDIR)/$(basename $@).debug + find $(OUTDIR) -regex '.*\(host\|target\).$(basename $@)\.mk' -delete + +native.clean: + rm -f $(OUTDIR)/Makefile.native + rm -rf $(OUTDIR)/native + find $(OUTDIR) -regex '.*\(host\|target\).native\.mk' -delete + +clean: $(addsuffix .clean,$(ARCHES)) native.clean android.clean + +# GYP file generation targets. +MAKEFILES = $(addprefix $(OUTDIR)/Makefile.,$(ARCHES)) +$(MAKEFILES): $(GYPFILES) $(ENVFILE) + GYP_GENERATORS=make \ + build/gyp/gyp --generator-output="$(OUTDIR)" build/all.gyp \ + -Ibuild/standalone.gypi --depth=. \ + -Dv8_target_arch=$(subst .,,$(suffix $@)) \ + -S.$(subst .,,$(suffix $@)) $(GYPFLAGS) + +$(OUTDIR)/Makefile.native: $(GYPFILES) $(ENVFILE) + GYP_GENERATORS=make \ + build/gyp/gyp --generator-output="$(OUTDIR)" build/all.gyp \ + -Ibuild/standalone.gypi --depth=. -S.native $(GYPFLAGS) + +$(OUTDIR)/Makefile.android: $(GYPFILES) $(ENVFILE) build/android.gypi \ + must-set-ANDROID_NDK_ROOT + GYP_GENERATORS=make \ + CC="${ANDROID_TOOL_PREFIX}-gcc" \ + CXX="${ANDROID_TOOL_PREFIX}-g++" \ + build/gyp/gyp --generator-output="$(OUTDIR)" build/all.gyp \ + -Ibuild/standalone.gypi --depth=. -Ibuild/android.gypi \ + -S.android $(GYPFLAGS) + +must-set-ANDROID_NDK_ROOT: +ifndef ANDROID_NDK_ROOT + $(error ANDROID_NDK_ROOT is not set) +endif + +# Replaces the old with the new environment file if they're different, which +# will trigger GYP to regenerate Makefiles. +$(ENVFILE): $(ENVFILE).new + @if test -r $(ENVFILE) && cmp $(ENVFILE).new $(ENVFILE) >/dev/null; \ + then rm $(ENVFILE).new; \ + else mv $(ENVFILE).new $(ENVFILE); fi + +# Stores current GYPFLAGS in a file. +$(ENVFILE).new: + @mkdir -p $(OUTDIR); echo "GYPFLAGS=$(GYPFLAGS)" > $(ENVFILE).new; \ + echo "CXX=$(CXX)" >> $(ENVFILE).new + +# Dependencies. +dependencies: + svn checkout --force http://gyp.googlecode.com/svn/trunk build/gyp \ + --revision 1282 diff --git a/node-v0.8.14/deps/v8/SConstruct b/node-v0.8.14/deps/v8/SConstruct new file mode 100644 index 0000000..ebce7ff --- /dev/null +++ b/node-v0.8.14/deps/v8/SConstruct @@ -0,0 +1,1617 @@ +# Copyright 2012 the V8 project authors. All rights reserved. +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above +# copyright notice, this list of conditions and the following +# disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of Google Inc. nor the names of its +# contributors may be used to endorse or promote products derived +# from this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +import platform +import re +import subprocess +import sys +import os +from os.path import join, dirname, abspath +from types import DictType, StringTypes +root_dir = dirname(File('SConstruct').rfile().abspath) +src_dir = join(root_dir, 'src') +sys.path.insert(0, join(root_dir, 'tools')) +import js2c, utils + +# ARM_TARGET_LIB is the path to the dynamic library to use on the target +# machine if cross-compiling to an arm machine. You will also need to set +# the additional cross-compiling environment variables to the cross compiler. +ARM_TARGET_LIB = os.environ.get('ARM_TARGET_LIB') +if ARM_TARGET_LIB: + ARM_LINK_FLAGS = ['-Wl,-rpath=' + ARM_TARGET_LIB + '/lib:' + + ARM_TARGET_LIB + '/usr/lib', + '-Wl,--dynamic-linker=' + ARM_TARGET_LIB + + '/lib/ld-linux.so.3'] +else: + ARM_LINK_FLAGS = [] + +GCC_EXTRA_CCFLAGS = [] +GCC_DTOA_EXTRA_CCFLAGS = [] + +LIBRARY_FLAGS = { + 'all': { + 'CPPPATH': [src_dir], + 'regexp:interpreted': { + 'CPPDEFINES': ['V8_INTERPRETED_REGEXP'] + }, + 'mode:debug': { + 'CPPDEFINES': ['V8_ENABLE_CHECKS', 'OBJECT_PRINT'] + }, + 'objectprint:on': { + 'CPPDEFINES': ['OBJECT_PRINT'], + }, + 'debuggersupport:on': { + 'CPPDEFINES': ['ENABLE_DEBUGGER_SUPPORT'], + }, + 'inspector:on': { + 'CPPDEFINES': ['INSPECTOR'], + }, + 'fasttls:off': { + 'CPPDEFINES': ['V8_NO_FAST_TLS'], + }, + 'liveobjectlist:on': { + 'CPPDEFINES': ['ENABLE_DEBUGGER_SUPPORT', 'INSPECTOR', + 'LIVE_OBJECT_LIST', 'OBJECT_PRINT'], + } + }, + 'gcc': { + 'all': { + 'CCFLAGS': ['$DIALECTFLAGS', '$WARNINGFLAGS'], + 'CXXFLAGS': ['-fno-rtti', '-fno-exceptions'], + }, + 'visibility:hidden': { + # Use visibility=default to disable this. + 'CXXFLAGS': ['-fvisibility=hidden'] + }, + 'strictaliasing:off': { + 'CCFLAGS': ['-fno-strict-aliasing'] + }, + 'mode:debug': { + 'CCFLAGS': ['-g', '-O0'], + 'CPPDEFINES': ['ENABLE_DISASSEMBLER', 'DEBUG'], + }, + 'mode:release': { + 'CCFLAGS': ['-O3', '-fomit-frame-pointer', '-fdata-sections', + '-ffunction-sections'], + }, + 'os:linux': { + 'CCFLAGS': ['-ansi'] + GCC_EXTRA_CCFLAGS, + 'library:shared': { + 'CPPDEFINES': ['V8_SHARED', 'BUILDING_V8_SHARED'], + 'LIBS': ['pthread'] + } + }, + 'os:macos': { + 'CCFLAGS': ['-ansi', '-mmacosx-version-min=10.4'], + 'library:shared': { + 'CPPDEFINES': ['V8_SHARED', 'BUILDING_V8_SHARED'], + } + }, + 'os:freebsd': { + 'CPPPATH' : [src_dir, '/usr/local/include'], + 'LIBPATH' : ['/usr/local/lib'], + 'CCFLAGS': ['-ansi'], + 'LIBS': ['execinfo'] + }, + 'os:openbsd': { + 'CPPPATH' : [src_dir, '/usr/local/include'], + 'LIBPATH' : ['/usr/local/lib'], + 'CCFLAGS': ['-ansi'], + }, + 'os:solaris': { + # On Solaris, to get isinf, INFINITY, fpclassify and other macros one + # needs to define __C99FEATURES__. + 'CPPDEFINES': ['__C99FEATURES__'], + 'CPPPATH' : [src_dir, '/usr/local/include'], + 'LIBPATH' : ['/usr/local/lib'], + 'CCFLAGS': ['-ansi'], + }, + 'os:netbsd': { + 'CPPPATH' : [src_dir, '/usr/pkg/include'], + 'LIBPATH' : ['/usr/pkg/lib'], + }, + 'os:win32': { + 'CCFLAGS': ['-DWIN32'], + 'CXXFLAGS': ['-DWIN32'], + }, + 'arch:ia32': { + 'CPPDEFINES': ['V8_TARGET_ARCH_IA32'], + 'CCFLAGS': ['-m32'], + 'LINKFLAGS': ['-m32'] + }, + 'arch:arm': { + 'CPPDEFINES': ['V8_TARGET_ARCH_ARM'], + 'unalignedaccesses:on' : { + 'CPPDEFINES' : ['CAN_USE_UNALIGNED_ACCESSES=1'] + }, + 'unalignedaccesses:off' : { + 'CPPDEFINES' : ['CAN_USE_UNALIGNED_ACCESSES=0'] + }, + 'armeabi:soft' : { + 'CPPDEFINES' : ['USE_EABI_HARDFLOAT=0'], + 'simulator:none': { + 'CCFLAGS': ['-mfloat-abi=soft'], + } + }, + 'armeabi:softfp' : { + 'CPPDEFINES' : ['USE_EABI_HARDFLOAT=0'], + 'vfp3:on': { + 'CPPDEFINES' : ['CAN_USE_VFP_INSTRUCTIONS'] + }, + 'simulator:none': { + 'CCFLAGS': ['-mfloat-abi=softfp'], + } + }, + 'armeabi:hard' : { + 'CPPDEFINES' : ['USE_EABI_HARDFLOAT=1'], + 'vfp3:on': { + 'CPPDEFINES' : ['CAN_USE_VFP_INSTRUCTIONS'] + }, + 'simulator:none': { + 'CCFLAGS': ['-mfloat-abi=hard'], + } + } + }, + 'simulator:arm': { + 'CCFLAGS': ['-m32'], + 'LINKFLAGS': ['-m32'], + }, + 'arch:mips': { + 'CPPDEFINES': ['V8_TARGET_ARCH_MIPS'], + 'mips_arch_variant:mips32r2': { + 'CPPDEFINES': ['_MIPS_ARCH_MIPS32R2'] + }, + 'mips_arch_variant:loongson': { + 'CPPDEFINES': ['_MIPS_ARCH_LOONGSON'] + }, + 'simulator:none': { + 'CCFLAGS': ['-EL'], + 'LINKFLAGS': ['-EL'], + 'mips_arch_variant:mips32r2': { + 'CCFLAGS': ['-mips32r2', '-Wa,-mips32r2'] + }, + 'mips_arch_variant:mips32r1': { + 'CCFLAGS': ['-mips32', '-Wa,-mips32'] + }, + 'mips_arch_variant:loongson': { + 'CCFLAGS': ['-march=mips3', '-Wa,-march=mips3'] + }, + 'library:static': { + 'LINKFLAGS': ['-static', '-static-libgcc'] + }, + 'mipsabi:softfloat': { + 'CCFLAGS': ['-msoft-float'], + 'LINKFLAGS': ['-msoft-float'] + }, + 'mipsabi:hardfloat': { + 'CCFLAGS': ['-mhard-float'], + 'LINKFLAGS': ['-mhard-float'] + } + } + }, + 'simulator:mips': { + 'CCFLAGS': ['-m32'], + 'LINKFLAGS': ['-m32'], + 'mipsabi:softfloat': { + 'CPPDEFINES': ['__mips_soft_float=1'], + 'fpu:on': { + 'CPPDEFINES' : ['CAN_USE_FPU_INSTRUCTIONS'] + } + }, + 'mipsabi:hardfloat': { + 'CPPDEFINES': ['__mips_hard_float=1', 'CAN_USE_FPU_INSTRUCTIONS'], + } + }, + 'arch:x64': { + 'CPPDEFINES': ['V8_TARGET_ARCH_X64'], + 'CCFLAGS': ['-m64'], + 'LINKFLAGS': ['-m64'], + }, + 'gdbjit:on': { + 'CPPDEFINES': ['ENABLE_GDB_JIT_INTERFACE'] + }, + 'compress_startup_data:bz2': { + 'CPPDEFINES': ['COMPRESS_STARTUP_DATA_BZ2'] + } + }, + 'msvc': { + 'all': { + 'CCFLAGS': ['$DIALECTFLAGS', '$WARNINGFLAGS'], + 'CXXFLAGS': ['/GR-', '/Gy'], + 'CPPDEFINES': ['WIN32'], + 'LINKFLAGS': ['/INCREMENTAL:NO', '/NXCOMPAT', '/IGNORE:4221'], + 'CCPDBFLAGS': ['/Zi'] + }, + 'verbose:off': { + 'DIALECTFLAGS': ['/nologo'], + 'ARFLAGS': ['/NOLOGO'] + }, + 'arch:ia32': { + 'CPPDEFINES': ['V8_TARGET_ARCH_IA32', '_USE_32BIT_TIME_T'], + 'LINKFLAGS': ['/MACHINE:X86'], + 'ARFLAGS': ['/MACHINE:X86'] + }, + 'arch:x64': { + 'CPPDEFINES': ['V8_TARGET_ARCH_X64'], + 'LINKFLAGS': ['/MACHINE:X64'], + 'ARFLAGS': ['/MACHINE:X64'] + }, + 'mode:debug': { + 'CCFLAGS': ['/Od', '/Gm'], + 'CPPDEFINES': ['_DEBUG', 'ENABLE_DISASSEMBLER', 'DEBUG'], + 'LINKFLAGS': ['/DEBUG'], + 'msvcrt:static': { + 'CCFLAGS': ['/MTd'] + }, + 'msvcrt:shared': { + 'CCFLAGS': ['/MDd'] + } + }, + 'mode:release': { + 'CCFLAGS': ['/O2'], + 'LINKFLAGS': ['/OPT:REF', '/OPT:ICF'], + 'msvcrt:static': { + 'CCFLAGS': ['/MT'] + }, + 'msvcrt:shared': { + 'CCFLAGS': ['/MD'] + }, + 'msvcltcg:on': { + 'CCFLAGS': ['/GL'], + 'ARFLAGS': ['/LTCG'], + 'pgo:off': { + 'LINKFLAGS': ['/LTCG'], + }, + 'pgo:instrument': { + 'LINKFLAGS': ['/LTCG:PGI'] + }, + 'pgo:optimize': { + 'LINKFLAGS': ['/LTCG:PGO'] + } + } + } + } +} + + +V8_EXTRA_FLAGS = { + 'gcc': { + 'all': { + 'WARNINGFLAGS': ['-Wall', + '-Werror', + '-W', + '-Wno-unused-parameter', + '-Woverloaded-virtual', + '-Wnon-virtual-dtor'] + }, + 'os:win32': { + 'WARNINGFLAGS': ['-pedantic', + '-Wno-long-long', + '-Wno-pedantic-ms-format'], + 'library:shared': { + 'LIBS': ['winmm', 'ws2_32'] + } + }, + 'os:linux': { + 'WARNINGFLAGS': ['-pedantic'], + 'library:shared': { + 'soname:on': { + 'LINKFLAGS': ['-Wl,-soname,${SONAME}'] + } + } + }, + 'os:macos': { + 'WARNINGFLAGS': ['-pedantic'] + }, + 'arch:arm': { + # This is to silence warnings about ABI changes that some versions of the + # CodeSourcery G++ tool chain produce for each occurrence of varargs. + 'WARNINGFLAGS': ['-Wno-abi'] + }, + 'disassembler:on': { + 'CPPDEFINES': ['ENABLE_DISASSEMBLER'] + } + }, + 'msvc': { + 'all': { + 'WARNINGFLAGS': ['/W3', '/WX', '/wd4351', '/wd4355', '/wd4800'] + }, + 'library:shared': { + 'CPPDEFINES': ['BUILDING_V8_SHARED'], + 'LIBS': ['winmm', 'ws2_32'] + }, + 'arch:arm': { + 'CPPDEFINES': ['V8_TARGET_ARCH_ARM'], + # /wd4996 is to silence the warning about sscanf + # used by the arm simulator. + 'WARNINGFLAGS': ['/wd4996'] + }, + 'arch:mips': { + 'CPPDEFINES': ['V8_TARGET_ARCH_MIPS'], + 'mips_arch_variant:mips32r2': { + 'CPPDEFINES': ['_MIPS_ARCH_MIPS32R2'] + }, + }, + 'disassembler:on': { + 'CPPDEFINES': ['ENABLE_DISASSEMBLER'] + } + } +} + + +MKSNAPSHOT_EXTRA_FLAGS = { + 'gcc': { + 'os:linux': { + 'LIBS': ['pthread'], + }, + 'os:macos': { + 'LIBS': ['pthread'], + }, + 'os:freebsd': { + 'LIBS': ['execinfo', 'pthread'] + }, + 'os:solaris': { + 'LIBS': ['m', 'pthread', 'socket', 'nsl', 'rt'], + 'LINKFLAGS': ['-mt'] + }, + 'os:openbsd': { + 'LIBS': ['execinfo', 'pthread'] + }, + 'os:win32': { + 'LIBS': ['winmm', 'ws2_32'], + }, + 'os:netbsd': { + 'LIBS': ['execinfo', 'pthread'] + }, + 'compress_startup_data:bz2': { + 'os:linux': { + 'LIBS': ['bz2'] + } + }, + }, + 'msvc': { + 'all': { + 'CPPDEFINES': ['_HAS_EXCEPTIONS=0'], + 'LIBS': ['winmm', 'ws2_32'] + } + } +} + + +DTOA_EXTRA_FLAGS = { + 'gcc': { + 'all': { + 'WARNINGFLAGS': ['-Werror', '-Wno-uninitialized'], + 'CCFLAGS': GCC_DTOA_EXTRA_CCFLAGS + } + }, + 'msvc': { + 'all': { + 'WARNINGFLAGS': ['/WX', '/wd4018', '/wd4244'] + } + } +} + + +CCTEST_EXTRA_FLAGS = { + 'all': { + 'CPPPATH': [src_dir], + 'library:shared': { + 'CPPDEFINES': ['USING_V8_SHARED'] + }, + }, + 'gcc': { + 'all': { + 'LIBPATH': [abspath('.')], + 'CCFLAGS': ['$DIALECTFLAGS', '$WARNINGFLAGS'], + 'CXXFLAGS': ['-fno-rtti', '-fno-exceptions'], + 'LINKFLAGS': ['$CCFLAGS'], + }, + 'os:linux': { + 'LIBS': ['pthread'], + 'CCFLAGS': ['-Wno-unused-but-set-variable'], + }, + 'os:macos': { + 'LIBS': ['pthread'], + }, + 'os:freebsd': { + 'LIBS': ['execinfo', 'pthread'] + }, + 'os:solaris': { + 'LIBS': ['m', 'pthread', 'socket', 'nsl', 'rt'], + 'LINKFLAGS': ['-mt'] + }, + 'os:openbsd': { + 'LIBS': ['execinfo', 'pthread'] + }, + 'os:win32': { + 'LIBS': ['winmm', 'ws2_32'] + }, + 'os:netbsd': { + 'LIBS': ['execinfo', 'pthread'] + }, + 'arch:arm': { + 'LINKFLAGS': ARM_LINK_FLAGS + }, + }, + 'msvc': { + 'all': { + 'CPPDEFINES': ['_HAS_EXCEPTIONS=0'], + 'LIBS': ['winmm', 'ws2_32'] + }, + 'arch:ia32': { + 'CPPDEFINES': ['V8_TARGET_ARCH_IA32'] + }, + 'arch:x64': { + 'CPPDEFINES': ['V8_TARGET_ARCH_X64'], + 'LINKFLAGS': ['/STACK:2097152'] + }, + } +} + + +SAMPLE_FLAGS = { + 'all': { + 'CPPPATH': [join(root_dir, 'include')], + 'library:shared': { + 'CPPDEFINES': ['USING_V8_SHARED'] + }, + }, + 'gcc': { + 'all': { + 'LIBPATH': ['.'], + 'CCFLAGS': ['$DIALECTFLAGS', '$WARNINGFLAGS'], + 'CXXFLAGS': ['-fno-rtti', '-fno-exceptions'], + 'LINKFLAGS': ['$CCFLAGS'], + }, + 'os:linux': { + 'LIBS': ['pthread'], + }, + 'os:macos': { + 'LIBS': ['pthread'], + }, + 'os:freebsd': { + 'LIBPATH' : ['/usr/local/lib'], + 'LIBS': ['execinfo', 'pthread'] + }, + 'os:solaris': { + # On Solaris, to get isinf, INFINITY, fpclassify and other macros one + # needs to define __C99FEATURES__. + 'CPPDEFINES': ['__C99FEATURES__'], + 'LIBPATH' : ['/usr/local/lib'], + 'LIBS': ['m', 'pthread', 'socket', 'nsl', 'rt'], + 'LINKFLAGS': ['-mt'] + }, + 'os:openbsd': { + 'LIBPATH' : ['/usr/local/lib'], + 'LIBS': ['execinfo', 'pthread'] + }, + 'os:win32': { + 'LIBS': ['winmm', 'ws2_32'] + }, + 'os:netbsd': { + 'LIBPATH' : ['/usr/pkg/lib'], + 'LIBS': ['execinfo', 'pthread'] + }, + 'arch:arm': { + 'LINKFLAGS': ARM_LINK_FLAGS, + 'armeabi:soft' : { + 'CPPDEFINES' : ['USE_EABI_HARDFLOAT=0'], + 'simulator:none': { + 'CCFLAGS': ['-mfloat-abi=soft'], + } + }, + 'armeabi:softfp' : { + 'CPPDEFINES' : ['USE_EABI_HARDFLOAT=0'], + 'simulator:none': { + 'CCFLAGS': ['-mfloat-abi=softfp'], + } + }, + 'armeabi:hard' : { + 'CPPDEFINES' : ['USE_EABI_HARDFLOAT=1'], + 'vfp3:on': { + 'CPPDEFINES' : ['CAN_USE_VFP_INSTRUCTIONS'] + }, + 'simulator:none': { + 'CCFLAGS': ['-mfloat-abi=hard'], + } + } + }, + 'arch:ia32': { + 'CCFLAGS': ['-m32'], + 'LINKFLAGS': ['-m32'] + }, + 'arch:x64': { + 'CCFLAGS': ['-m64'], + 'LINKFLAGS': ['-m64'] + }, + 'arch:mips': { + 'CPPDEFINES': ['V8_TARGET_ARCH_MIPS'], + 'mips_arch_variant:mips32r2': { + 'CPPDEFINES': ['_MIPS_ARCH_MIPS32R2'] + }, + 'mips_arch_variant:loongson': { + 'CPPDEFINES': ['_MIPS_ARCH_LOONGSON'] + }, + 'simulator:none': { + 'CCFLAGS': ['-EL'], + 'LINKFLAGS': ['-EL'], + 'mips_arch_variant:mips32r2': { + 'CCFLAGS': ['-mips32r2', '-Wa,-mips32r2'] + }, + 'mips_arch_variant:mips32r1': { + 'CCFLAGS': ['-mips32', '-Wa,-mips32'] + }, + 'mips_arch_variant:loongson': { + 'CCFLAGS': ['-march=mips3', '-Wa,-march=mips3'] + }, + 'library:static': { + 'LINKFLAGS': ['-static', '-static-libgcc'] + }, + 'mipsabi:softfloat': { + 'CCFLAGS': ['-msoft-float'], + 'LINKFLAGS': ['-msoft-float'] + }, + 'mipsabi:hardfloat': { + 'CCFLAGS': ['-mhard-float'], + 'LINKFLAGS': ['-mhard-float'], + 'fpu:on': { + 'CPPDEFINES' : ['CAN_USE_FPU_INSTRUCTIONS'] + } + } + } + }, + 'simulator:arm': { + 'CCFLAGS': ['-m32'], + 'LINKFLAGS': ['-m32'] + }, + 'simulator:mips': { + 'CCFLAGS': ['-m32'], + 'LINKFLAGS': ['-m32'] + }, + 'mode:release': { + 'CCFLAGS': ['-O2'] + }, + 'mode:debug': { + 'CCFLAGS': ['-g', '-O0'], + 'CPPDEFINES': ['DEBUG'] + }, + 'compress_startup_data:bz2': { + 'CPPDEFINES': ['COMPRESS_STARTUP_DATA_BZ2'], + 'os:linux': { + 'LIBS': ['bz2'] + } + }, + }, + 'msvc': { + 'all': { + 'LIBS': ['winmm', 'ws2_32'] + }, + 'verbose:off': { + 'CCFLAGS': ['/nologo'], + 'LINKFLAGS': ['/NOLOGO'] + }, + 'verbose:on': { + 'LINKFLAGS': ['/VERBOSE'] + }, + 'prof:on': { + 'LINKFLAGS': ['/MAP'] + }, + 'mode:release': { + 'CCFLAGS': ['/O2'], + 'LINKFLAGS': ['/OPT:REF', '/OPT:ICF'], + 'msvcrt:static': { + 'CCFLAGS': ['/MT'] + }, + 'msvcrt:shared': { + 'CCFLAGS': ['/MD'] + }, + 'msvcltcg:on': { + 'CCFLAGS': ['/GL'], + 'pgo:off': { + 'LINKFLAGS': ['/LTCG'], + }, + }, + 'pgo:instrument': { + 'LINKFLAGS': ['/LTCG:PGI'] + }, + 'pgo:optimize': { + 'LINKFLAGS': ['/LTCG:PGO'] + } + }, + 'arch:ia32': { + 'CPPDEFINES': ['V8_TARGET_ARCH_IA32', 'WIN32'], + 'LINKFLAGS': ['/MACHINE:X86'] + }, + 'arch:x64': { + 'CPPDEFINES': ['V8_TARGET_ARCH_X64', 'WIN32'], + 'LINKFLAGS': ['/MACHINE:X64', '/STACK:2097152'] + }, + 'mode:debug': { + 'CCFLAGS': ['/Od'], + 'LINKFLAGS': ['/DEBUG'], + 'CPPDEFINES': ['DEBUG'], + 'msvcrt:static': { + 'CCFLAGS': ['/MTd'] + }, + 'msvcrt:shared': { + 'CCFLAGS': ['/MDd'] + } + } + } +} + + +PREPARSER_FLAGS = { + 'all': { + 'CPPPATH': [join(root_dir, 'include'), src_dir], + 'library:shared': { + 'CPPDEFINES': ['USING_V8_SHARED'] + }, + }, + 'gcc': { + 'all': { + 'LIBPATH': ['.'], + 'CCFLAGS': ['$DIALECTFLAGS', '$WARNINGFLAGS'], + 'CXXFLAGS': ['-fno-rtti', '-fno-exceptions'], + 'LINKFLAGS': ['$CCFLAGS'], + }, + 'os:win32': { + 'LIBS': ['winmm', 'ws2_32'] + }, + 'arch:arm': { + 'LINKFLAGS': ARM_LINK_FLAGS, + 'armeabi:soft' : { + 'CPPDEFINES' : ['USE_EABI_HARDFLOAT=0'], + 'simulator:none': { + 'CCFLAGS': ['-mfloat-abi=soft'], + } + }, + 'armeabi:softfp' : { + 'simulator:none': { + 'CCFLAGS': ['-mfloat-abi=softfp'], + } + }, + 'armeabi:hard' : { + 'simulator:none': { + 'CCFLAGS': ['-mfloat-abi=hard'], + } + } + }, + 'arch:ia32': { + 'CCFLAGS': ['-m32'], + 'LINKFLAGS': ['-m32'] + }, + 'arch:x64': { + 'CCFLAGS': ['-m64'], + 'LINKFLAGS': ['-m64'] + }, + 'arch:mips': { + 'CPPDEFINES': ['V8_TARGET_ARCH_MIPS'], + 'mips_arch_variant:mips32r2': { + 'CPPDEFINES': ['_MIPS_ARCH_MIPS32R2'] + }, + 'mips_arch_variant:loongson': { + 'CPPDEFINES': ['_MIPS_ARCH_LOONGSON'] + }, + 'simulator:none': { + 'CCFLAGS': ['-EL'], + 'LINKFLAGS': ['-EL'], + 'mips_arch_variant:mips32r2': { + 'CCFLAGS': ['-mips32r2', '-Wa,-mips32r2'] + }, + 'mips_arch_variant:mips32r1': { + 'CCFLAGS': ['-mips32', '-Wa,-mips32'] + }, + 'mips_arch_variant:loongson': { + 'CCFLAGS': ['-march=mips3', '-Wa,-march=mips3'] + }, + 'library:static': { + 'LINKFLAGS': ['-static', '-static-libgcc'] + }, + 'mipsabi:softfloat': { + 'CCFLAGS': ['-msoft-float'], + 'LINKFLAGS': ['-msoft-float'] + }, + 'mipsabi:hardfloat': { + 'CCFLAGS': ['-mhard-float'], + 'LINKFLAGS': ['-mhard-float'] + } + } + }, + 'simulator:arm': { + 'CCFLAGS': ['-m32'], + 'LINKFLAGS': ['-m32'] + }, + 'simulator:mips': { + 'CCFLAGS': ['-m32'], + 'LINKFLAGS': ['-m32'], + 'mipsabi:softfloat': { + 'CPPDEFINES': ['__mips_soft_float=1'], + }, + 'mipsabi:hardfloat': { + 'CPPDEFINES': ['__mips_hard_float=1'], + } + }, + 'mode:release': { + 'CCFLAGS': ['-O2'] + }, + 'mode:debug': { + 'CCFLAGS': ['-g', '-O0'], + 'CPPDEFINES': ['DEBUG'] + }, + 'os:freebsd': { + 'LIBPATH' : ['/usr/local/lib'], + }, + }, + 'msvc': { + 'all': { + 'LIBS': ['winmm', 'ws2_32'] + }, + 'verbose:off': { + 'CCFLAGS': ['/nologo'], + 'LINKFLAGS': ['/NOLOGO'] + }, + 'verbose:on': { + 'LINKFLAGS': ['/VERBOSE'] + }, + 'prof:on': { + 'LINKFLAGS': ['/MAP'] + }, + 'mode:release': { + 'CCFLAGS': ['/O2'], + 'LINKFLAGS': ['/OPT:REF', '/OPT:ICF'], + 'msvcrt:static': { + 'CCFLAGS': ['/MT'] + }, + 'msvcrt:shared': { + 'CCFLAGS': ['/MD'] + }, + 'msvcltcg:on': { + 'CCFLAGS': ['/GL'], + 'pgo:off': { + 'LINKFLAGS': ['/LTCG'], + }, + }, + 'pgo:instrument': { + 'LINKFLAGS': ['/LTCG:PGI'] + }, + 'pgo:optimize': { + 'LINKFLAGS': ['/LTCG:PGO'] + } + }, + 'arch:ia32': { + 'CPPDEFINES': ['V8_TARGET_ARCH_IA32', 'WIN32'], + 'LINKFLAGS': ['/MACHINE:X86'] + }, + 'arch:x64': { + 'CPPDEFINES': ['V8_TARGET_ARCH_X64', 'WIN32'], + 'LINKFLAGS': ['/MACHINE:X64', '/STACK:2097152'] + }, + 'mode:debug': { + 'CCFLAGS': ['/Od'], + 'LINKFLAGS': ['/DEBUG'], + 'CPPDEFINES': ['DEBUG'], + 'msvcrt:static': { + 'CCFLAGS': ['/MTd'] + }, + 'msvcrt:shared': { + 'CCFLAGS': ['/MDd'] + } + } + } +} + + +D8_FLAGS = { + 'all': { + 'library:shared': { + 'CPPDEFINES': ['V8_SHARED'], + 'LIBS': ['v8'], + 'LIBPATH': ['.'] + }, + }, + 'gcc': { + 'all': { + 'CCFLAGS': ['$DIALECTFLAGS', '$WARNINGFLAGS'], + 'CXXFLAGS': ['-fno-rtti', '-fno-exceptions'], + 'LINKFLAGS': ['$CCFLAGS'], + }, + 'console:readline': { + 'LIBS': ['readline'] + }, + 'os:linux': { + 'LIBS': ['pthread'], + }, + 'os:macos': { + 'LIBS': ['pthread'], + }, + 'os:freebsd': { + 'LIBS': ['pthread'], + }, + 'os:solaris': { + 'LIBS': ['m', 'pthread', 'socket', 'nsl', 'rt'], + 'LINKFLAGS': ['-mt'] + }, + 'os:openbsd': { + 'LIBS': ['pthread'], + }, + 'os:win32': { + 'LIBS': ['winmm', 'ws2_32'], + }, + 'os:netbsd': { + 'LIBS': ['pthread'], + }, + 'arch:arm': { + 'LINKFLAGS': ARM_LINK_FLAGS + }, + 'compress_startup_data:bz2': { + 'CPPDEFINES': ['COMPRESS_STARTUP_DATA_BZ2'], + 'os:linux': { + 'LIBS': ['bz2'] + } + } + }, + 'msvc': { + 'all': { + 'LIBS': ['winmm', 'ws2_32'] + }, + 'verbose:off': { + 'CCFLAGS': ['/nologo'], + 'LINKFLAGS': ['/NOLOGO'] + }, + 'verbose:on': { + 'LINKFLAGS': ['/VERBOSE'] + }, + 'prof:on': { + 'LINKFLAGS': ['/MAP'] + }, + 'mode:release': { + 'CCFLAGS': ['/O2'], + 'LINKFLAGS': ['/OPT:REF', '/OPT:ICF'], + 'msvcrt:static': { + 'CCFLAGS': ['/MT'] + }, + 'msvcrt:shared': { + 'CCFLAGS': ['/MD'] + }, + 'msvcltcg:on': { + 'CCFLAGS': ['/GL'], + 'pgo:off': { + 'LINKFLAGS': ['/LTCG'], + }, + }, + 'pgo:instrument': { + 'LINKFLAGS': ['/LTCG:PGI'] + }, + 'pgo:optimize': { + 'LINKFLAGS': ['/LTCG:PGO'] + } + }, + 'arch:ia32': { + 'CPPDEFINES': ['V8_TARGET_ARCH_IA32', 'WIN32'], + 'LINKFLAGS': ['/MACHINE:X86'] + }, + 'arch:x64': { + 'CPPDEFINES': ['V8_TARGET_ARCH_X64', 'WIN32'], + 'LINKFLAGS': ['/MACHINE:X64', '/STACK:2097152'] + }, + 'mode:debug': { + 'CCFLAGS': ['/Od'], + 'LINKFLAGS': ['/DEBUG'], + 'CPPDEFINES': ['DEBUG'], + 'msvcrt:static': { + 'CCFLAGS': ['/MTd'] + }, + 'msvcrt:shared': { + 'CCFLAGS': ['/MDd'] + } + } + } +} + + +SUFFIXES = { + 'release': '', + 'debug': '_g' +} + + +def Abort(message): + print message + sys.exit(1) + + +def GuessOS(env): + return utils.GuessOS() + + +def GuessArch(env): + return utils.GuessArchitecture() + + +def GuessToolchain(env): + tools = env['TOOLS'] + if 'gcc' in tools: + return 'gcc' + elif 'msvc' in tools: + return 'msvc' + else: + return None + + +def GuessVisibility(env): + os = env['os'] + toolchain = env['toolchain']; + if (os == 'win32' or os == 'cygwin') and toolchain == 'gcc': + # MinGW / Cygwin can't do it. + return 'default' + elif os == 'solaris': + return 'default' + else: + return 'hidden' + + +def GuessStrictAliasing(env): + # There seems to be a problem with gcc 4.5.x. + # See http://code.google.com/p/v8/issues/detail?id=884 + # It can be worked around by disabling strict aliasing. + toolchain = env['toolchain']; + if toolchain == 'gcc': + env = Environment(tools=['gcc']) + # The gcc version should be available in env['CCVERSION'], + # but when scons detects msvc this value is not set. + version = subprocess.Popen([env['CC'], '-dumpversion'], + stdout=subprocess.PIPE).communicate()[0] + if version.find('4.5') == 0: + return 'off' + return 'default' + + +PLATFORM_OPTIONS = { + 'arch': { + 'values': ['arm', 'ia32', 'x64', 'mips'], + 'guess': GuessArch, + 'help': 'the architecture to build for' + }, + 'os': { + 'values': ['freebsd', 'linux', 'macos', 'win32', 'openbsd', 'solaris', 'cygwin', 'netbsd'], + 'guess': GuessOS, + 'help': 'the os to build for' + }, + 'toolchain': { + 'values': ['gcc', 'msvc'], + 'guess': GuessToolchain, + 'help': 'the toolchain to use' + } +} + +SIMPLE_OPTIONS = { + 'regexp': { + 'values': ['native', 'interpreted'], + 'default': 'native', + 'help': 'Whether to use native or interpreted regexp implementation' + }, + 'snapshot': { + 'values': ['on', 'off', 'nobuild'], + 'default': 'off', + 'help': 'build using snapshots for faster start-up' + }, + 'prof': { + 'values': ['on', 'off'], + 'default': 'off', + 'help': 'enable profiling of build target' + }, + 'gdbjit': { + 'values': ['on', 'off'], + 'default': 'off', + 'help': 'enable GDB JIT interface' + }, + 'library': { + 'values': ['static', 'shared'], + 'default': 'static', + 'help': 'the type of library to produce' + }, + 'objectprint': { + 'values': ['on', 'off'], + 'default': 'off', + 'help': 'enable object printing' + }, + 'profilingsupport': { + 'values': ['on', 'off'], + 'default': 'on', + 'help': 'enable profiling of JavaScript code' + }, + 'debuggersupport': { + 'values': ['on', 'off'], + 'default': 'on', + 'help': 'enable debugging of JavaScript code' + }, + 'inspector': { + 'values': ['on', 'off'], + 'default': 'off', + 'help': 'enable inspector features' + }, + 'liveobjectlist': { + 'values': ['on', 'off'], + 'default': 'off', + 'help': 'enable live object list features in the debugger' + }, + 'soname': { + 'values': ['on', 'off'], + 'default': 'off', + 'help': 'turn on setting soname for Linux shared library' + }, + 'msvcrt': { + 'values': ['static', 'shared'], + 'default': 'static', + 'help': 'the type of Microsoft Visual C++ runtime library to use' + }, + 'msvcltcg': { + 'values': ['on', 'off'], + 'default': 'on', + 'help': 'use Microsoft Visual C++ link-time code generation' + }, + 'simulator': { + 'values': ['arm', 'mips', 'none'], + 'default': 'none', + 'help': 'build with simulator' + }, + 'unalignedaccesses': { + 'values': ['default', 'on', 'off'], + 'default': 'default', + 'help': 'set whether the ARM target supports unaligned accesses' + }, + 'disassembler': { + 'values': ['on', 'off'], + 'default': 'off', + 'help': 'enable the disassembler to inspect generated code' + }, + 'fasttls': { + 'values': ['on', 'off'], + 'default': 'on', + 'help': 'enable fast thread local storage support ' + '(if available on the current architecture/platform)' + }, + 'sourcesignatures': { + 'values': ['MD5', 'timestamp'], + 'default': 'MD5', + 'help': 'set how the build system detects file changes' + }, + 'console': { + 'values': ['dumb', 'readline'], + 'default': 'dumb', + 'help': 'the console to use for the d8 shell' + }, + 'verbose': { + 'values': ['on', 'off'], + 'default': 'off', + 'help': 'more output from compiler and linker' + }, + 'visibility': { + 'values': ['default', 'hidden'], + 'guess': GuessVisibility, + 'help': 'shared library symbol visibility' + }, + 'strictaliasing': { + 'values': ['default', 'off'], + 'guess': GuessStrictAliasing, + 'help': 'assume strict aliasing while optimizing' + }, + 'pgo': { + 'values': ['off', 'instrument', 'optimize'], + 'default': 'off', + 'help': 'select profile guided optimization variant', + }, + 'armeabi': { + 'values': ['hard', 'softfp', 'soft'], + 'default': 'softfp', + 'help': 'generate calling conventiont according to selected ARM EABI variant' + }, + 'mipsabi': { + 'values': ['hardfloat', 'softfloat', 'none'], + 'default': 'hardfloat', + 'help': 'generate calling conventiont according to selected mips ABI' + }, + 'mips_arch_variant': { + 'values': ['mips32r2', 'mips32r1', 'loongson'], + 'default': 'mips32r2', + 'help': 'mips variant' + }, + 'compress_startup_data': { + 'values': ['off', 'bz2'], + 'default': 'off', + 'help': 'compress startup data (snapshot) [Linux only]' + }, + 'vfp3': { + 'values': ['on', 'off'], + 'default': 'on', + 'help': 'use vfp3 instructions when building the snapshot [Arm only]' + }, + 'fpu': { + 'values': ['on', 'off'], + 'default': 'on', + 'help': 'use fpu instructions when building the snapshot [MIPS only]' + }, + +} + +ALL_OPTIONS = dict(PLATFORM_OPTIONS, **SIMPLE_OPTIONS) + + +def AddOptions(options, result): + guess_env = Environment(options=result) + for (name, option) in options.iteritems(): + if 'guess' in option: + # Option has a guess function + guess = option.get('guess') + default = guess(guess_env) + else: + # Option has a fixed default + default = option.get('default') + help = '%s (%s)' % (option.get('help'), ", ".join(option['values'])) + result.Add(name, help, default) + + +def GetOptions(): + result = Options() + result.Add('mode', 'compilation mode (debug, release)', 'release') + result.Add('sample', 'build sample (shell, process, lineprocessor)', '') + result.Add('cache', 'directory to use for scons build cache', '') + result.Add('env', 'override environment settings (NAME0:value0,NAME1:value1,...)', '') + result.Add('importenv', 'import environment settings (NAME0,NAME1,...)', '') + AddOptions(PLATFORM_OPTIONS, result) + AddOptions(SIMPLE_OPTIONS, result) + return result + + +def GetTools(opts): + env = Environment(options=opts) + os = env['os'] + toolchain = env['toolchain'] + if os == 'win32' and toolchain == 'gcc': + return ['mingw'] + elif os == 'win32' and toolchain == 'msvc': + return ['msvc', 'mslink', 'mslib', 'msvs'] + else: + return ['default'] + + +def GetVersionComponents(): + MAJOR_VERSION_PATTERN = re.compile(r"#define\s+MAJOR_VERSION\s+(.*)") + MINOR_VERSION_PATTERN = re.compile(r"#define\s+MINOR_VERSION\s+(.*)") + BUILD_NUMBER_PATTERN = re.compile(r"#define\s+BUILD_NUMBER\s+(.*)") + PATCH_LEVEL_PATTERN = re.compile(r"#define\s+PATCH_LEVEL\s+(.*)") + + patterns = [MAJOR_VERSION_PATTERN, + MINOR_VERSION_PATTERN, + BUILD_NUMBER_PATTERN, + PATCH_LEVEL_PATTERN] + + source = open(join(root_dir, 'src', 'version.cc')).read() + version_components = [] + for pattern in patterns: + match = pattern.search(source) + if match: + version_components.append(match.group(1).strip()) + else: + version_components.append('0') + + return version_components + + +def GetVersion(): + version_components = GetVersionComponents() + + if version_components[len(version_components) - 1] == '0': + version_components.pop() + return '.'.join(version_components) + + +def GetSpecificSONAME(): + SONAME_PATTERN = re.compile(r"#define\s+SONAME\s+\"(.*)\"") + + source = open(join(root_dir, 'src', 'version.cc')).read() + match = SONAME_PATTERN.search(source) + + if match: + return match.group(1).strip() + else: + return '' + + +def SplitList(str): + return [ s for s in str.split(",") if len(s) > 0 ] + + +def IsLegal(env, option, values): + str = env[option] + for s in SplitList(str): + if not s in values: + Abort("Illegal value for option %s '%s'." % (option, s)) + return False + return True + + +def VerifyOptions(env): + if not IsLegal(env, 'mode', ['debug', 'release']): + return False + if not IsLegal(env, 'sample', ["shell", "process", "lineprocessor"]): + return False + if not IsLegal(env, 'regexp', ["native", "interpreted"]): + return False + if env['os'] == 'win32' and env['library'] == 'shared' and env['prof'] == 'on': + Abort("Profiling on windows only supported for static library.") + if env['gdbjit'] == 'on' and ((env['os'] != 'linux' and env['os'] != 'macos') or (env['arch'] != 'ia32' and env['arch'] != 'x64' and env['arch'] != 'arm')): + Abort("GDBJIT interface is supported only for Intel-compatible (ia32 or x64) Linux/OSX target.") + if env['os'] == 'win32' and env['soname'] == 'on': + Abort("Shared Object soname not applicable for Windows.") + if env['soname'] == 'on' and env['library'] == 'static': + Abort("Shared Object soname not applicable for static library.") + if env['os'] != 'win32' and env['pgo'] != 'off': + Abort("Profile guided optimization only supported on Windows.") + if env['cache'] and not os.path.isdir(env['cache']): + Abort("The specified cache directory does not exist.") + if not (env['arch'] == 'arm' or env['simulator'] == 'arm') and ('unalignedaccesses' in ARGUMENTS): + print env['arch'] + print env['simulator'] + Abort("Option unalignedaccesses only supported for the ARM architecture.") + if env['os'] != 'linux' and env['compress_startup_data'] != 'off': + Abort("Startup data compression is only available on Linux") + for (name, option) in ALL_OPTIONS.iteritems(): + if (not name in env): + message = ("A value for option %s must be specified (%s)." % + (name, ", ".join(option['values']))) + Abort(message) + if not env[name] in option['values']: + message = ("Unknown %s value '%s'. Possible values are (%s)." % + (name, env[name], ", ".join(option['values']))) + Abort(message) + + +class BuildContext(object): + + def __init__(self, options, env_overrides, samples): + self.library_targets = [] + self.mksnapshot_targets = [] + self.cctest_targets = [] + self.sample_targets = [] + self.d8_targets = [] + self.options = options + self.env_overrides = env_overrides + self.samples = samples + self.preparser_targets = [] + self.use_snapshot = (options['snapshot'] != 'off') + self.build_snapshot = (options['snapshot'] == 'on') + self.flags = None + + def AddRelevantFlags(self, initial, flags): + result = initial.copy() + toolchain = self.options['toolchain'] + if toolchain in flags: + self.AppendFlags(result, flags[toolchain].get('all')) + for option in sorted(self.options.keys()): + value = self.options[option] + self.AppendFlags(result, flags[toolchain].get(option + ':' + value)) + self.AppendFlags(result, flags.get('all')) + return result + + def AddRelevantSubFlags(self, options, flags): + self.AppendFlags(options, flags.get('all')) + for option in sorted(self.options.keys()): + value = self.options[option] + self.AppendFlags(options, flags.get(option + ':' + value)) + + def GetRelevantSources(self, source): + result = [] + result += source.get('all', []) + for (name, value) in self.options.iteritems(): + source_value = source.get(name + ':' + value, []) + if type(source_value) == dict: + result += self.GetRelevantSources(source_value) + else: + result += source_value + return sorted(result) + + def AppendFlags(self, options, added): + if not added: + return + for (key, value) in added.iteritems(): + if key.find(':') != -1: + self.AddRelevantSubFlags(options, { key: value }) + else: + if not key in options: + options[key] = value + else: + prefix = options[key] + if isinstance(prefix, StringTypes): prefix = prefix.split() + options[key] = prefix + value + + def ConfigureObject(self, env, input, **kw): + if (kw.has_key('CPPPATH') and env.has_key('CPPPATH')): + kw['CPPPATH'] += env['CPPPATH'] + if self.options['library'] == 'static': + return env.StaticObject(input, **kw) + else: + return env.SharedObject(input, **kw) + + def ApplyEnvOverrides(self, env): + if not self.env_overrides: + return + if type(env['ENV']) == DictType: + env['ENV'].update(**self.env_overrides) + else: + env['ENV'] = self.env_overrides + + +def PostprocessOptions(options, os): + # Adjust architecture if the simulator option has been set + if (options['simulator'] != 'none') and (options['arch'] != options['simulator']): + if 'arch' in ARGUMENTS: + # Print a warning if arch has explicitly been set + print "Warning: forcing architecture to match simulator (%s)" % options['simulator'] + options['arch'] = options['simulator'] + if (options['prof'] != 'off') and (options['profilingsupport'] == 'off'): + # Print a warning if profiling is enabled without profiling support + print "Warning: forcing profilingsupport on when prof is on" + options['profilingsupport'] = 'on' + if os == 'win32' and options['pgo'] != 'off' and options['msvcltcg'] == 'off': + if 'msvcltcg' in ARGUMENTS: + print "Warning: forcing msvcltcg on as it is required for pgo (%s)" % options['pgo'] + options['msvcltcg'] = 'on' + if (options['mipsabi'] != 'none') and (options['arch'] != 'mips') and (options['simulator'] != 'mips'): + options['mipsabi'] = 'none' + if options['liveobjectlist'] == 'on': + if (options['debuggersupport'] != 'on') or (options['mode'] == 'release'): + # Print a warning that liveobjectlist will implicitly enable the debugger + print "Warning: forcing debuggersupport on for liveobjectlist" + options['debuggersupport'] = 'on' + options['inspector'] = 'on' + options['objectprint'] = 'on' + + +def ParseEnvOverrides(arg, imports): + # The environment overrides are in the format NAME0:value0,NAME1:value1,... + # The environment imports are in the format NAME0,NAME1,... + overrides = {} + for var in imports.split(','): + if var in os.environ: + overrides[var] = os.environ[var] + for override in arg.split(','): + pos = override.find(':') + if pos == -1: + continue + overrides[override[:pos].strip()] = override[pos+1:].strip() + return overrides + + +def BuildSpecific(env, mode, env_overrides, tools): + options = {'mode': mode} + for option in ALL_OPTIONS: + options[option] = env[option] + PostprocessOptions(options, env['os']) + + context = BuildContext(options, env_overrides, samples=SplitList(env['sample'])) + + # Remove variables which can't be imported from the user's external + # environment into a construction environment. + user_environ = os.environ.copy() + try: + del user_environ['ENV'] + except KeyError: + pass + + library_flags = context.AddRelevantFlags(user_environ, LIBRARY_FLAGS) + v8_flags = context.AddRelevantFlags(library_flags, V8_EXTRA_FLAGS) + mksnapshot_flags = context.AddRelevantFlags(library_flags, MKSNAPSHOT_EXTRA_FLAGS) + dtoa_flags = context.AddRelevantFlags(library_flags, DTOA_EXTRA_FLAGS) + cctest_flags = context.AddRelevantFlags(v8_flags, CCTEST_EXTRA_FLAGS) + sample_flags = context.AddRelevantFlags(user_environ, SAMPLE_FLAGS) + preparser_flags = context.AddRelevantFlags(user_environ, PREPARSER_FLAGS) + d8_flags = context.AddRelevantFlags(library_flags, D8_FLAGS) + + context.flags = { + 'v8': v8_flags, + 'mksnapshot': mksnapshot_flags, + 'dtoa': dtoa_flags, + 'cctest': cctest_flags, + 'sample': sample_flags, + 'd8': d8_flags, + 'preparser': preparser_flags + } + + # Generate library base name. + target_id = mode + suffix = SUFFIXES[target_id] + library_name = 'v8' + suffix + preparser_library_name = 'v8preparser' + suffix + version = GetVersion() + if context.options['soname'] == 'on': + # When building shared object with SONAME version the library name. + library_name += '-' + version + + # Generate library SONAME if required by the build. + if context.options['soname'] == 'on': + soname = GetSpecificSONAME() + if soname == '': + soname = 'lib' + library_name + '.so' + env['SONAME'] = soname + + # Build the object files by invoking SCons recursively. + d8_env = Environment(tools=tools) + d8_env.Replace(**context.flags['d8']) + (object_files, shell_files, mksnapshot, preparser_files) = env.SConscript( + join('src', 'SConscript'), + build_dir=join('obj', target_id), + exports='context tools d8_env', + duplicate=False + ) + + context.mksnapshot_targets.append(mksnapshot) + + # Link the object files into a library. + env.Replace(**context.flags['v8']) + + context.ApplyEnvOverrides(env) + if context.options['library'] == 'static': + library = env.StaticLibrary(library_name, object_files) + preparser_library = env.StaticLibrary(preparser_library_name, + preparser_files) + else: + # There seems to be a glitch in the way scons decides where to put + # PDB files when compiling using MSVC so we specify it manually. + # This should not affect any other platforms. + pdb_name = library_name + '.dll.pdb' + library = env.SharedLibrary(library_name, object_files, PDB=pdb_name) + preparser_pdb_name = preparser_library_name + '.dll.pdb'; + preparser_soname = 'lib' + preparser_library_name + '.so'; + preparser_library = env.SharedLibrary(preparser_library_name, + preparser_files, + PDB=preparser_pdb_name, + SONAME=preparser_soname) + context.library_targets.append(library) + context.library_targets.append(preparser_library) + + context.ApplyEnvOverrides(d8_env) + if context.options['library'] == 'static': + shell = d8_env.Program('d8' + suffix, object_files + shell_files) + else: + shell = d8_env.Program('d8' + suffix, shell_files) + d8_env.Depends(shell, library) + context.d8_targets.append(shell) + + for sample in context.samples: + sample_env = Environment(tools=tools) + sample_env.Replace(**context.flags['sample']) + sample_env.Prepend(LIBS=[library_name]) + context.ApplyEnvOverrides(sample_env) + sample_object = sample_env.SConscript( + join('samples', 'SConscript'), + build_dir=join('obj', 'sample', sample, target_id), + exports='sample context tools', + duplicate=False + ) + sample_name = sample + suffix + sample_program = sample_env.Program(sample_name, sample_object) + sample_env.Depends(sample_program, library) + context.sample_targets.append(sample_program) + + cctest_env = env.Copy() + cctest_env.Prepend(LIBS=[library_name]) + cctest_program = cctest_env.SConscript( + join('test', 'cctest', 'SConscript'), + build_dir=join('obj', 'test', target_id), + exports='context object_files tools', + duplicate=False + ) + context.cctest_targets.append(cctest_program) + + preparser_env = env.Copy() + preparser_env.Replace(**context.flags['preparser']) + preparser_env.Prepend(LIBS=[preparser_library_name]) + context.ApplyEnvOverrides(preparser_env) + preparser_object = preparser_env.SConscript( + join('preparser', 'SConscript'), + build_dir=join('obj', 'preparser', target_id), + exports='context tools', + duplicate=False + ) + preparser_name = join('obj', 'preparser', target_id, 'preparser') + preparser_program = preparser_env.Program(preparser_name, preparser_object); + preparser_env.Depends(preparser_program, preparser_library) + context.preparser_targets.append(preparser_program) + + return context + + +def Build(): + opts = GetOptions() + tools = GetTools(opts) + env = Environment(options=opts, tools=tools) + + Help(opts.GenerateHelpText(env)) + VerifyOptions(env) + env_overrides = ParseEnvOverrides(env['env'], env['importenv']) + + SourceSignatures(env['sourcesignatures']) + + libraries = [] + mksnapshots = [] + cctests = [] + samples = [] + preparsers = [] + d8s = [] + modes = SplitList(env['mode']) + for mode in modes: + context = BuildSpecific(env.Copy(), mode, env_overrides, tools) + libraries += context.library_targets + mksnapshots += context.mksnapshot_targets + cctests += context.cctest_targets + samples += context.sample_targets + preparsers += context.preparser_targets + d8s += context.d8_targets + + env.Alias('library', libraries) + env.Alias('mksnapshot', mksnapshots) + env.Alias('cctests', cctests) + env.Alias('sample', samples) + env.Alias('d8', d8s) + env.Alias('preparser', preparsers) + + if env['sample']: + env.Default('sample') + else: + env.Default('library') + + if env['cache']: + CacheDir(env['cache']) + +# We disable deprecation warnings because we need to be able to use +# env.Copy without getting warnings for compatibility with older +# version of scons. Also, there's a bug in some revisions that +# doesn't allow this flag to be set, so we swallow any exceptions. +# Lovely. +try: + SetOption('warn', 'no-deprecated') +except: + pass + + +def WarnAboutDeprecation(): + print """ +####################################################### +# WARNING: Building V8 with SCons is deprecated and # +# will not work much longer. Please switch to using # +# the GYP-based build now. Instructions are at # +# http://code.google.com/p/v8/wiki/BuildingWithGYP. # +####################################################### + """ + +WarnAboutDeprecation() +import atexit +atexit.register(WarnAboutDeprecation) +Build() diff --git a/node-v0.8.14/deps/v8/benchmarks/README.txt b/node-v0.8.14/deps/v8/benchmarks/README.txt new file mode 100644 index 0000000..59f76ff --- /dev/null +++ b/node-v0.8.14/deps/v8/benchmarks/README.txt @@ -0,0 +1,86 @@ +V8 Benchmark Suite +================== + +This is the V8 benchmark suite: A collection of pure JavaScript +benchmarks that we have used to tune V8. The licenses for the +individual benchmarks are included in the JavaScript files. + +In addition to the benchmarks, the suite consists of the benchmark +framework (base.js), which must be loaded before any of the individual +benchmark files, and two benchmark runners: An HTML version (run.html) +and a standalone JavaScript version (run.js). + + +Changes From Version 1 To Version 2 +=================================== + +For version 2 the crypto benchmark was fixed. Previously, the +decryption stage was given plaintext as input, which resulted in an +error. Now, the decryption stage is given the output of the +encryption stage as input. The result is checked against the original +plaintext. For this to give the correct results the crypto objects +are reset for each iteration of the benchmark. In addition, the size +of the plain text has been increased a little and the use of +Math.random() and new Date() to build an RNG pool has been removed. + +Other benchmarks were fixed to do elementary verification of the +results of their calculations. This is to avoid accidentally +obtaining scores that are the result of an incorrect JavaScript engine +optimization. + + +Changes From Version 2 To Version 3 +=================================== + +Version 3 adds a new benchmark, RegExp. The RegExp benchmark is +generated by loading 50 of the most popular pages on the web and +logging all regexp operations performed. Each operation is given a +weight that is calculated from an estimate of the popularity of the +pages where it occurs and the number of times it is executed while +loading each page. Finally the literal letters in the data are +encoded using ROT13 in a way that does not affect how the regexps +match their input. + + +Changes from Version 3 to Version 4 +=================================== + +The Splay benchmark is a newcomer in version 4. It manipulates a +splay tree by adding and removing data nodes, thus exercising the +memory management subsystem of the JavaScript engine. + +Furthermore, all the unused parts of the Prototype library were +removed from the RayTrace benchmark. This does not affect the running +of the benchmark. + + +Changes from Version 4 to Version 5 +=================================== + +Removed duplicate line in random seed code, and changed the name of +the Object.prototype.inherits function in the DeltaBlue benchmark to +inheritsFrom to avoid name clashes when running in Chromium with +extensions enabled. + + +Changes from Version 5 to Version 6 +=================================== + +Removed dead code from the RayTrace benchmark and fixed a couple of +typos in the DeltaBlue implementation. Changed the Splay benchmark to +avoid converting the same numeric key to a string over and over again +and to avoid inserting and removing the same element repeatedly thus +increasing pressure on the memory subsystem. Changed the RegExp +benchmark to exercise the regular expression engine on different +input strings. + +Furthermore, the benchmark runner was changed to run the benchmarks +for at least a few times to stabilize the reported numbers on slower +machines. + + +Changes from Version 6 to Version 7 +=================================== + +Added the Navier-Stokes benchmark, a 2D differential equation solver +that stresses arithmetic computations on double arrays. diff --git a/node-v0.8.14/deps/v8/benchmarks/base.js b/node-v0.8.14/deps/v8/benchmarks/base.js new file mode 100644 index 0000000..62c37e1 --- /dev/null +++ b/node-v0.8.14/deps/v8/benchmarks/base.js @@ -0,0 +1,284 @@ +// Copyright 2012 the V8 project authors. All rights reserved. +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following +// disclaimer in the documentation and/or other materials provided +// with the distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + +// Simple framework for running the benchmark suites and +// computing a score based on the timing measurements. + + +// A benchmark has a name (string) and a function that will be run to +// do the performance measurement. The optional setup and tearDown +// arguments are functions that will be invoked before and after +// running the benchmark, but the running time of these functions will +// not be accounted for in the benchmark score. +function Benchmark(name, run, setup, tearDown) { + this.name = name; + this.run = run; + this.Setup = setup ? setup : function() { }; + this.TearDown = tearDown ? tearDown : function() { }; +} + + +// Benchmark results hold the benchmark and the measured time used to +// run the benchmark. The benchmark score is computed later once a +// full benchmark suite has run to completion. +function BenchmarkResult(benchmark, time) { + this.benchmark = benchmark; + this.time = time; +} + + +// Automatically convert results to numbers. Used by the geometric +// mean computation. +BenchmarkResult.prototype.valueOf = function() { + return this.time; +} + + +// Suites of benchmarks consist of a name and the set of benchmarks in +// addition to the reference timing that the final score will be based +// on. This way, all scores are relative to a reference run and higher +// scores implies better performance. +function BenchmarkSuite(name, reference, benchmarks) { + this.name = name; + this.reference = reference; + this.benchmarks = benchmarks; + BenchmarkSuite.suites.push(this); +} + + +// Keep track of all declared benchmark suites. +BenchmarkSuite.suites = []; + + +// Scores are not comparable across versions. Bump the version if +// you're making changes that will affect that scores, e.g. if you add +// a new benchmark or change an existing one. +BenchmarkSuite.version = '7'; + + +// To make the benchmark results predictable, we replace Math.random +// with a 100% deterministic alternative. +Math.random = (function() { + var seed = 49734321; + return function() { + // Robert Jenkins' 32 bit integer hash function. + seed = ((seed + 0x7ed55d16) + (seed << 12)) & 0xffffffff; + seed = ((seed ^ 0xc761c23c) ^ (seed >>> 19)) & 0xffffffff; + seed = ((seed + 0x165667b1) + (seed << 5)) & 0xffffffff; + seed = ((seed + 0xd3a2646c) ^ (seed << 9)) & 0xffffffff; + seed = ((seed + 0xfd7046c5) + (seed << 3)) & 0xffffffff; + seed = ((seed ^ 0xb55a4f09) ^ (seed >>> 16)) & 0xffffffff; + return (seed & 0xfffffff) / 0x10000000; + }; +})(); + + +// Runs all registered benchmark suites and optionally yields between +// each individual benchmark to avoid running for too long in the +// context of browsers. Once done, the final score is reported to the +// runner. +BenchmarkSuite.RunSuites = function(runner) { + var continuation = null; + var suites = BenchmarkSuite.suites; + var length = suites.length; + BenchmarkSuite.scores = []; + var index = 0; + function RunStep() { + while (continuation || index < length) { + if (continuation) { + continuation = continuation(); + } else { + var suite = suites[index++]; + if (runner.NotifyStart) runner.NotifyStart(suite.name); + continuation = suite.RunStep(runner); + } + if (continuation && typeof window != 'undefined' && window.setTimeout) { + window.setTimeout(RunStep, 25); + return; + } + } + if (runner.NotifyScore) { + var score = BenchmarkSuite.GeometricMean(BenchmarkSuite.scores); + var formatted = BenchmarkSuite.FormatScore(100 * score); + runner.NotifyScore(formatted); + } + } + RunStep(); +} + + +// Counts the total number of registered benchmarks. Useful for +// showing progress as a percentage. +BenchmarkSuite.CountBenchmarks = function() { + var result = 0; + var suites = BenchmarkSuite.suites; + for (var i = 0; i < suites.length; i++) { + result += suites[i].benchmarks.length; + } + return result; +} + + +// Computes the geometric mean of a set of numbers. +BenchmarkSuite.GeometricMean = function(numbers) { + var log = 0; + for (var i = 0; i < numbers.length; i++) { + log += Math.log(numbers[i]); + } + return Math.pow(Math.E, log / numbers.length); +} + + +// Converts a score value to a string with at least three significant +// digits. +BenchmarkSuite.FormatScore = function(value) { + if (value > 100) { + return value.toFixed(0); + } else { + return value.toPrecision(3); + } +} + +// Notifies the runner that we're done running a single benchmark in +// the benchmark suite. This can be useful to report progress. +BenchmarkSuite.prototype.NotifyStep = function(result) { + this.results.push(result); + if (this.runner.NotifyStep) this.runner.NotifyStep(result.benchmark.name); +} + + +// Notifies the runner that we're done with running a suite and that +// we have a result which can be reported to the user if needed. +BenchmarkSuite.prototype.NotifyResult = function() { + var mean = BenchmarkSuite.GeometricMean(this.results); + var score = this.reference / mean; + BenchmarkSuite.scores.push(score); + if (this.runner.NotifyResult) { + var formatted = BenchmarkSuite.FormatScore(100 * score); + this.runner.NotifyResult(this.name, formatted); + } +} + + +// Notifies the runner that running a benchmark resulted in an error. +BenchmarkSuite.prototype.NotifyError = function(error) { + if (this.runner.NotifyError) { + this.runner.NotifyError(this.name, error); + } + if (this.runner.NotifyStep) { + this.runner.NotifyStep(this.name); + } +} + + +// Runs a single benchmark for at least a second and computes the +// average time it takes to run a single iteration. +BenchmarkSuite.prototype.RunSingleBenchmark = function(benchmark, data) { + function Measure(data) { + var elapsed = 0; + var start = new Date(); + for (var n = 0; elapsed < 1000; n++) { + benchmark.run(); + elapsed = new Date() - start; + } + if (data != null) { + data.runs += n; + data.elapsed += elapsed; + } + } + + if (data == null) { + // Measure the benchmark once for warm up and throw the result + // away. Return a fresh data object. + Measure(null); + return { runs: 0, elapsed: 0 }; + } else { + Measure(data); + // If we've run too few iterations, we continue for another second. + if (data.runs < 32) return data; + var usec = (data.elapsed * 1000) / data.runs; + this.NotifyStep(new BenchmarkResult(benchmark, usec)); + return null; + } +} + + +// This function starts running a suite, but stops between each +// individual benchmark in the suite and returns a continuation +// function which can be invoked to run the next benchmark. Once the +// last benchmark has been executed, null is returned. +BenchmarkSuite.prototype.RunStep = function(runner) { + this.results = []; + this.runner = runner; + var length = this.benchmarks.length; + var index = 0; + var suite = this; + var data; + + // Run the setup, the actual benchmark, and the tear down in three + // separate steps to allow the framework to yield between any of the + // steps. + + function RunNextSetup() { + if (index < length) { + try { + suite.benchmarks[index].Setup(); + } catch (e) { + suite.NotifyError(e); + return null; + } + return RunNextBenchmark; + } + suite.NotifyResult(); + return null; + } + + function RunNextBenchmark() { + try { + data = suite.RunSingleBenchmark(suite.benchmarks[index], data); + } catch (e) { + suite.NotifyError(e); + return null; + } + // If data is null, we're done with this benchmark. + return (data == null) ? RunNextTearDown : RunNextBenchmark(); + } + + function RunNextTearDown() { + try { + suite.benchmarks[index++].TearDown(); + } catch (e) { + suite.NotifyError(e); + return null; + } + return RunNextSetup; + } + + // Start out running the setup. + return RunNextSetup(); +} diff --git a/node-v0.8.14/deps/v8/benchmarks/crypto.js b/node-v0.8.14/deps/v8/benchmarks/crypto.js new file mode 100644 index 0000000..531ad45 --- /dev/null +++ b/node-v0.8.14/deps/v8/benchmarks/crypto.js @@ -0,0 +1,1698 @@ +/* + * Copyright (c) 2003-2005 Tom Wu + * All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND, + * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY + * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. + * + * IN NO EVENT SHALL TOM WU BE LIABLE FOR ANY SPECIAL, INCIDENTAL, + * INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND, OR ANY DAMAGES WHATSOEVER + * RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER OR NOT ADVISED OF + * THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF LIABILITY, ARISING OUT + * OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + * + * In addition, the following condition applies: + * + * All redistributions must retain an intact copy of this copyright notice + * and disclaimer. + */ + + +// The code has been adapted for use as a benchmark by Google. +var Crypto = new BenchmarkSuite('Crypto', 266181, [ + new Benchmark("Encrypt", encrypt), + new Benchmark("Decrypt", decrypt) +]); + + +// Basic JavaScript BN library - subset useful for RSA encryption. + +// Bits per digit +var dbits; +var BI_DB; +var BI_DM; +var BI_DV; + +var BI_FP; +var BI_FV; +var BI_F1; +var BI_F2; + +// JavaScript engine analysis +var canary = 0xdeadbeefcafe; +var j_lm = ((canary&0xffffff)==0xefcafe); + +// (public) Constructor +function BigInteger(a,b,c) { + this.array = new Array(); + if(a != null) + if("number" == typeof a) this.fromNumber(a,b,c); + else if(b == null && "string" != typeof a) this.fromString(a,256); + else this.fromString(a,b); +} + +// return new, unset BigInteger +function nbi() { return new BigInteger(null); } + +// am: Compute w_j += (x*this_i), propagate carries, +// c is initial carry, returns final carry. +// c < 3*dvalue, x < 2*dvalue, this_i < dvalue +// We need to select the fastest one that works in this environment. + +// am1: use a single mult and divide to get the high bits, +// max digit bits should be 26 because +// max internal value = 2*dvalue^2-2*dvalue (< 2^53) +function am1(i,x,w,j,c,n) { + var this_array = this.array; + var w_array = w.array; + while(--n >= 0) { + var v = x*this_array[i++]+w_array[j]+c; + c = Math.floor(v/0x4000000); + w_array[j++] = v&0x3ffffff; + } + return c; +} + +// am2 avoids a big mult-and-extract completely. +// Max digit bits should be <= 30 because we do bitwise ops +// on values up to 2*hdvalue^2-hdvalue-1 (< 2^31) +function am2(i,x,w,j,c,n) { + var this_array = this.array; + var w_array = w.array; + var xl = x&0x7fff, xh = x>>15; + while(--n >= 0) { + var l = this_array[i]&0x7fff; + var h = this_array[i++]>>15; + var m = xh*l+h*xl; + l = xl*l+((m&0x7fff)<<15)+w_array[j]+(c&0x3fffffff); + c = (l>>>30)+(m>>>15)+xh*h+(c>>>30); + w_array[j++] = l&0x3fffffff; + } + return c; +} + +// Alternately, set max digit bits to 28 since some +// browsers slow down when dealing with 32-bit numbers. +function am3(i,x,w,j,c,n) { + var this_array = this.array; + var w_array = w.array; + + var xl = x&0x3fff, xh = x>>14; + while(--n >= 0) { + var l = this_array[i]&0x3fff; + var h = this_array[i++]>>14; + var m = xh*l+h*xl; + l = xl*l+((m&0x3fff)<<14)+w_array[j]+c; + c = (l>>28)+(m>>14)+xh*h; + w_array[j++] = l&0xfffffff; + } + return c; +} + +// This is tailored to VMs with 2-bit tagging. It makes sure +// that all the computations stay within the 29 bits available. +function am4(i,x,w,j,c,n) { + var this_array = this.array; + var w_array = w.array; + + var xl = x&0x1fff, xh = x>>13; + while(--n >= 0) { + var l = this_array[i]&0x1fff; + var h = this_array[i++]>>13; + var m = xh*l+h*xl; + l = xl*l+((m&0x1fff)<<13)+w_array[j]+c; + c = (l>>26)+(m>>13)+xh*h; + w_array[j++] = l&0x3ffffff; + } + return c; +} + +// am3/28 is best for SM, Rhino, but am4/26 is best for v8. +// Kestrel (Opera 9.5) gets its best result with am4/26. +// IE7 does 9% better with am3/28 than with am4/26. +// Firefox (SM) gets 10% faster with am3/28 than with am4/26. + +setupEngine = function(fn, bits) { + BigInteger.prototype.am = fn; + dbits = bits; + + BI_DB = dbits; + BI_DM = ((1<= 0; --i) r_array[i] = this_array[i]; + r.t = this.t; + r.s = this.s; +} + +// (protected) set from integer value x, -DV <= x < DV +function bnpFromInt(x) { + var this_array = this.array; + this.t = 1; + this.s = (x<0)?-1:0; + if(x > 0) this_array[0] = x; + else if(x < -1) this_array[0] = x+DV; + else this.t = 0; +} + +// return bigint initialized to value +function nbv(i) { var r = nbi(); r.fromInt(i); return r; } + +// (protected) set from string and radix +function bnpFromString(s,b) { + var this_array = this.array; + var k; + if(b == 16) k = 4; + else if(b == 8) k = 3; + else if(b == 256) k = 8; // byte array + else if(b == 2) k = 1; + else if(b == 32) k = 5; + else if(b == 4) k = 2; + else { this.fromRadix(s,b); return; } + this.t = 0; + this.s = 0; + var i = s.length, mi = false, sh = 0; + while(--i >= 0) { + var x = (k==8)?s[i]&0xff:intAt(s,i); + if(x < 0) { + if(s.charAt(i) == "-") mi = true; + continue; + } + mi = false; + if(sh == 0) + this_array[this.t++] = x; + else if(sh+k > BI_DB) { + this_array[this.t-1] |= (x&((1<<(BI_DB-sh))-1))<>(BI_DB-sh)); + } + else + this_array[this.t-1] |= x<= BI_DB) sh -= BI_DB; + } + if(k == 8 && (s[0]&0x80) != 0) { + this.s = -1; + if(sh > 0) this_array[this.t-1] |= ((1<<(BI_DB-sh))-1)< 0 && this_array[this.t-1] == c) --this.t; +} + +// (public) return string representation in given radix +function bnToString(b) { + var this_array = this.array; + if(this.s < 0) return "-"+this.negate().toString(b); + var k; + if(b == 16) k = 4; + else if(b == 8) k = 3; + else if(b == 2) k = 1; + else if(b == 32) k = 5; + else if(b == 4) k = 2; + else return this.toRadix(b); + var km = (1< 0) { + if(p < BI_DB && (d = this_array[i]>>p) > 0) { m = true; r = int2char(d); } + while(i >= 0) { + if(p < k) { + d = (this_array[i]&((1<>(p+=BI_DB-k); + } + else { + d = (this_array[i]>>(p-=k))&km; + if(p <= 0) { p += BI_DB; --i; } + } + if(d > 0) m = true; + if(m) r += int2char(d); + } + } + return m?r:"0"; +} + +// (public) -this +function bnNegate() { var r = nbi(); BigInteger.ZERO.subTo(this,r); return r; } + +// (public) |this| +function bnAbs() { return (this.s<0)?this.negate():this; } + +// (public) return + if this > a, - if this < a, 0 if equal +function bnCompareTo(a) { + var this_array = this.array; + var a_array = a.array; + + var r = this.s-a.s; + if(r != 0) return r; + var i = this.t; + r = i-a.t; + if(r != 0) return r; + while(--i >= 0) if((r=this_array[i]-a_array[i]) != 0) return r; + return 0; +} + +// returns bit length of the integer x +function nbits(x) { + var r = 1, t; + if((t=x>>>16) != 0) { x = t; r += 16; } + if((t=x>>8) != 0) { x = t; r += 8; } + if((t=x>>4) != 0) { x = t; r += 4; } + if((t=x>>2) != 0) { x = t; r += 2; } + if((t=x>>1) != 0) { x = t; r += 1; } + return r; +} + +// (public) return the number of bits in "this" +function bnBitLength() { + var this_array = this.array; + if(this.t <= 0) return 0; + return BI_DB*(this.t-1)+nbits(this_array[this.t-1]^(this.s&BI_DM)); +} + +// (protected) r = this << n*DB +function bnpDLShiftTo(n,r) { + var this_array = this.array; + var r_array = r.array; + var i; + for(i = this.t-1; i >= 0; --i) r_array[i+n] = this_array[i]; + for(i = n-1; i >= 0; --i) r_array[i] = 0; + r.t = this.t+n; + r.s = this.s; +} + +// (protected) r = this >> n*DB +function bnpDRShiftTo(n,r) { + var this_array = this.array; + var r_array = r.array; + for(var i = n; i < this.t; ++i) r_array[i-n] = this_array[i]; + r.t = Math.max(this.t-n,0); + r.s = this.s; +} + +// (protected) r = this << n +function bnpLShiftTo(n,r) { + var this_array = this.array; + var r_array = r.array; + var bs = n%BI_DB; + var cbs = BI_DB-bs; + var bm = (1<= 0; --i) { + r_array[i+ds+1] = (this_array[i]>>cbs)|c; + c = (this_array[i]&bm)<= 0; --i) r_array[i] = 0; + r_array[ds] = c; + r.t = this.t+ds+1; + r.s = this.s; + r.clamp(); +} + +// (protected) r = this >> n +function bnpRShiftTo(n,r) { + var this_array = this.array; + var r_array = r.array; + r.s = this.s; + var ds = Math.floor(n/BI_DB); + if(ds >= this.t) { r.t = 0; return; } + var bs = n%BI_DB; + var cbs = BI_DB-bs; + var bm = (1<>bs; + for(var i = ds+1; i < this.t; ++i) { + r_array[i-ds-1] |= (this_array[i]&bm)<>bs; + } + if(bs > 0) r_array[this.t-ds-1] |= (this.s&bm)<>= BI_DB; + } + if(a.t < this.t) { + c -= a.s; + while(i < this.t) { + c += this_array[i]; + r_array[i++] = c&BI_DM; + c >>= BI_DB; + } + c += this.s; + } + else { + c += this.s; + while(i < a.t) { + c -= a_array[i]; + r_array[i++] = c&BI_DM; + c >>= BI_DB; + } + c -= a.s; + } + r.s = (c<0)?-1:0; + if(c < -1) r_array[i++] = BI_DV+c; + else if(c > 0) r_array[i++] = c; + r.t = i; + r.clamp(); +} + +// (protected) r = this * a, r != this,a (HAC 14.12) +// "this" should be the larger one if appropriate. +function bnpMultiplyTo(a,r) { + var this_array = this.array; + var r_array = r.array; + var x = this.abs(), y = a.abs(); + var y_array = y.array; + + var i = x.t; + r.t = i+y.t; + while(--i >= 0) r_array[i] = 0; + for(i = 0; i < y.t; ++i) r_array[i+x.t] = x.am(0,y_array[i],r,i,0,x.t); + r.s = 0; + r.clamp(); + if(this.s != a.s) BigInteger.ZERO.subTo(r,r); +} + +// (protected) r = this^2, r != this (HAC 14.16) +function bnpSquareTo(r) { + var x = this.abs(); + var x_array = x.array; + var r_array = r.array; + + var i = r.t = 2*x.t; + while(--i >= 0) r_array[i] = 0; + for(i = 0; i < x.t-1; ++i) { + var c = x.am(i,x_array[i],r,2*i,0,1); + if((r_array[i+x.t]+=x.am(i+1,2*x_array[i],r,2*i+1,c,x.t-i-1)) >= BI_DV) { + r_array[i+x.t] -= BI_DV; + r_array[i+x.t+1] = 1; + } + } + if(r.t > 0) r_array[r.t-1] += x.am(i,x_array[i],r,2*i,0,1); + r.s = 0; + r.clamp(); +} + +// (protected) divide this by m, quotient and remainder to q, r (HAC 14.20) +// r != q, this != m. q or r may be null. +function bnpDivRemTo(m,q,r) { + var pm = m.abs(); + if(pm.t <= 0) return; + var pt = this.abs(); + if(pt.t < pm.t) { + if(q != null) q.fromInt(0); + if(r != null) this.copyTo(r); + return; + } + if(r == null) r = nbi(); + var y = nbi(), ts = this.s, ms = m.s; + var pm_array = pm.array; + var nsh = BI_DB-nbits(pm_array[pm.t-1]); // normalize modulus + if(nsh > 0) { pm.lShiftTo(nsh,y); pt.lShiftTo(nsh,r); } + else { pm.copyTo(y); pt.copyTo(r); } + var ys = y.t; + + var y_array = y.array; + var y0 = y_array[ys-1]; + if(y0 == 0) return; + var yt = y0*(1<1)?y_array[ys-2]>>BI_F2:0); + var d1 = BI_FV/yt, d2 = (1<= 0) { + r_array[r.t++] = 1; + r.subTo(t,r); + } + BigInteger.ONE.dlShiftTo(ys,t); + t.subTo(y,y); // "negative" y so we can replace sub with am later + while(y.t < ys) y_array[y.t++] = 0; + while(--j >= 0) { + // Estimate quotient digit + var qd = (r_array[--i]==y0)?BI_DM:Math.floor(r_array[i]*d1+(r_array[i-1]+e)*d2); + if((r_array[i]+=y.am(0,qd,r,j,0,ys)) < qd) { // Try it out + y.dlShiftTo(j,t); + r.subTo(t,r); + while(r_array[i] < --qd) r.subTo(t,r); + } + } + if(q != null) { + r.drShiftTo(ys,q); + if(ts != ms) BigInteger.ZERO.subTo(q,q); + } + r.t = ys; + r.clamp(); + if(nsh > 0) r.rShiftTo(nsh,r); // Denormalize remainder + if(ts < 0) BigInteger.ZERO.subTo(r,r); +} + +// (public) this mod a +function bnMod(a) { + var r = nbi(); + this.abs().divRemTo(a,null,r); + if(this.s < 0 && r.compareTo(BigInteger.ZERO) > 0) a.subTo(r,r); + return r; +} + +// Modular reduction using "classic" algorithm +function Classic(m) { this.m = m; } +function cConvert(x) { + if(x.s < 0 || x.compareTo(this.m) >= 0) return x.mod(this.m); + else return x; +} +function cRevert(x) { return x; } +function cReduce(x) { x.divRemTo(this.m,null,x); } +function cMulTo(x,y,r) { x.multiplyTo(y,r); this.reduce(r); } +function cSqrTo(x,r) { x.squareTo(r); this.reduce(r); } + +Classic.prototype.convert = cConvert; +Classic.prototype.revert = cRevert; +Classic.prototype.reduce = cReduce; +Classic.prototype.mulTo = cMulTo; +Classic.prototype.sqrTo = cSqrTo; + +// (protected) return "-1/this % 2^DB"; useful for Mont. reduction +// justification: +// xy == 1 (mod m) +// xy = 1+km +// xy(2-xy) = (1+km)(1-km) +// x[y(2-xy)] = 1-k^2m^2 +// x[y(2-xy)] == 1 (mod m^2) +// if y is 1/x mod m, then y(2-xy) is 1/x mod m^2 +// should reduce x and y(2-xy) by m^2 at each step to keep size bounded. +// JS multiply "overflows" differently from C/C++, so care is needed here. +function bnpInvDigit() { + var this_array = this.array; + if(this.t < 1) return 0; + var x = this_array[0]; + if((x&1) == 0) return 0; + var y = x&3; // y == 1/x mod 2^2 + y = (y*(2-(x&0xf)*y))&0xf; // y == 1/x mod 2^4 + y = (y*(2-(x&0xff)*y))&0xff; // y == 1/x mod 2^8 + y = (y*(2-(((x&0xffff)*y)&0xffff)))&0xffff; // y == 1/x mod 2^16 + // last step - calculate inverse mod DV directly; + // assumes 16 < DB <= 32 and assumes ability to handle 48-bit ints + y = (y*(2-x*y%BI_DV))%BI_DV; // y == 1/x mod 2^dbits + // we really want the negative inverse, and -DV < y < DV + return (y>0)?BI_DV-y:-y; +} + +// Montgomery reduction +function Montgomery(m) { + this.m = m; + this.mp = m.invDigit(); + this.mpl = this.mp&0x7fff; + this.mph = this.mp>>15; + this.um = (1<<(BI_DB-15))-1; + this.mt2 = 2*m.t; +} + +// xR mod m +function montConvert(x) { + var r = nbi(); + x.abs().dlShiftTo(this.m.t,r); + r.divRemTo(this.m,null,r); + if(x.s < 0 && r.compareTo(BigInteger.ZERO) > 0) this.m.subTo(r,r); + return r; +} + +// x/R mod m +function montRevert(x) { + var r = nbi(); + x.copyTo(r); + this.reduce(r); + return r; +} + +// x = x/R mod m (HAC 14.32) +function montReduce(x) { + var x_array = x.array; + while(x.t <= this.mt2) // pad x so am has enough room later + x_array[x.t++] = 0; + for(var i = 0; i < this.m.t; ++i) { + // faster way of calculating u0 = x[i]*mp mod DV + var j = x_array[i]&0x7fff; + var u0 = (j*this.mpl+(((j*this.mph+(x_array[i]>>15)*this.mpl)&this.um)<<15))&BI_DM; + // use am to combine the multiply-shift-add into one call + j = i+this.m.t; + x_array[j] += this.m.am(0,u0,x,i,0,this.m.t); + // propagate carry + while(x_array[j] >= BI_DV) { x_array[j] -= BI_DV; x_array[++j]++; } + } + x.clamp(); + x.drShiftTo(this.m.t,x); + if(x.compareTo(this.m) >= 0) x.subTo(this.m,x); +} + +// r = "x^2/R mod m"; x != r +function montSqrTo(x,r) { x.squareTo(r); this.reduce(r); } + +// r = "xy/R mod m"; x,y != r +function montMulTo(x,y,r) { x.multiplyTo(y,r); this.reduce(r); } + +Montgomery.prototype.convert = montConvert; +Montgomery.prototype.revert = montRevert; +Montgomery.prototype.reduce = montReduce; +Montgomery.prototype.mulTo = montMulTo; +Montgomery.prototype.sqrTo = montSqrTo; + +// (protected) true iff this is even +function bnpIsEven() { + var this_array = this.array; + return ((this.t>0)?(this_array[0]&1):this.s) == 0; +} + +// (protected) this^e, e < 2^32, doing sqr and mul with "r" (HAC 14.79) +function bnpExp(e,z) { + if(e > 0xffffffff || e < 1) return BigInteger.ONE; + var r = nbi(), r2 = nbi(), g = z.convert(this), i = nbits(e)-1; + g.copyTo(r); + while(--i >= 0) { + z.sqrTo(r,r2); + if((e&(1< 0) z.mulTo(r2,g,r); + else { var t = r; r = r2; r2 = t; } + } + return z.revert(r); +} + +// (public) this^e % m, 0 <= e < 2^32 +function bnModPowInt(e,m) { + var z; + if(e < 256 || m.isEven()) z = new Classic(m); else z = new Montgomery(m); + return this.exp(e,z); +} + +// protected +BigInteger.prototype.copyTo = bnpCopyTo; +BigInteger.prototype.fromInt = bnpFromInt; +BigInteger.prototype.fromString = bnpFromString; +BigInteger.prototype.clamp = bnpClamp; +BigInteger.prototype.dlShiftTo = bnpDLShiftTo; +BigInteger.prototype.drShiftTo = bnpDRShiftTo; +BigInteger.prototype.lShiftTo = bnpLShiftTo; +BigInteger.prototype.rShiftTo = bnpRShiftTo; +BigInteger.prototype.subTo = bnpSubTo; +BigInteger.prototype.multiplyTo = bnpMultiplyTo; +BigInteger.prototype.squareTo = bnpSquareTo; +BigInteger.prototype.divRemTo = bnpDivRemTo; +BigInteger.prototype.invDigit = bnpInvDigit; +BigInteger.prototype.isEven = bnpIsEven; +BigInteger.prototype.exp = bnpExp; + +// public +BigInteger.prototype.toString = bnToString; +BigInteger.prototype.negate = bnNegate; +BigInteger.prototype.abs = bnAbs; +BigInteger.prototype.compareTo = bnCompareTo; +BigInteger.prototype.bitLength = bnBitLength; +BigInteger.prototype.mod = bnMod; +BigInteger.prototype.modPowInt = bnModPowInt; + +// "constants" +BigInteger.ZERO = nbv(0); +BigInteger.ONE = nbv(1); +// Copyright (c) 2005 Tom Wu +// All Rights Reserved. +// See "LICENSE" for details. + +// Extended JavaScript BN functions, required for RSA private ops. + +// (public) +function bnClone() { var r = nbi(); this.copyTo(r); return r; } + +// (public) return value as integer +function bnIntValue() { + var this_array = this.array; + if(this.s < 0) { + if(this.t == 1) return this_array[0]-BI_DV; + else if(this.t == 0) return -1; + } + else if(this.t == 1) return this_array[0]; + else if(this.t == 0) return 0; + // assumes 16 < DB < 32 + return ((this_array[1]&((1<<(32-BI_DB))-1))<>24; +} + +// (public) return value as short (assumes DB>=16) +function bnShortValue() { + var this_array = this.array; + return (this.t==0)?this.s:(this_array[0]<<16)>>16; +} + +// (protected) return x s.t. r^x < DV +function bnpChunkSize(r) { return Math.floor(Math.LN2*BI_DB/Math.log(r)); } + +// (public) 0 if this == 0, 1 if this > 0 +function bnSigNum() { + var this_array = this.array; + if(this.s < 0) return -1; + else if(this.t <= 0 || (this.t == 1 && this_array[0] <= 0)) return 0; + else return 1; +} + +// (protected) convert to radix string +function bnpToRadix(b) { + if(b == null) b = 10; + if(this.signum() == 0 || b < 2 || b > 36) return "0"; + var cs = this.chunkSize(b); + var a = Math.pow(b,cs); + var d = nbv(a), y = nbi(), z = nbi(), r = ""; + this.divRemTo(d,y,z); + while(y.signum() > 0) { + r = (a+z.intValue()).toString(b).substr(1) + r; + y.divRemTo(d,y,z); + } + return z.intValue().toString(b) + r; +} + +// (protected) convert from radix string +function bnpFromRadix(s,b) { + this.fromInt(0); + if(b == null) b = 10; + var cs = this.chunkSize(b); + var d = Math.pow(b,cs), mi = false, j = 0, w = 0; + for(var i = 0; i < s.length; ++i) { + var x = intAt(s,i); + if(x < 0) { + if(s.charAt(i) == "-" && this.signum() == 0) mi = true; + continue; + } + w = b*w+x; + if(++j >= cs) { + this.dMultiply(d); + this.dAddOffset(w,0); + j = 0; + w = 0; + } + } + if(j > 0) { + this.dMultiply(Math.pow(b,j)); + this.dAddOffset(w,0); + } + if(mi) BigInteger.ZERO.subTo(this,this); +} + +// (protected) alternate constructor +function bnpFromNumber(a,b,c) { + if("number" == typeof b) { + // new BigInteger(int,int,RNG) + if(a < 2) this.fromInt(1); + else { + this.fromNumber(a,c); + if(!this.testBit(a-1)) // force MSB set + this.bitwiseTo(BigInteger.ONE.shiftLeft(a-1),op_or,this); + if(this.isEven()) this.dAddOffset(1,0); // force odd + while(!this.isProbablePrime(b)) { + this.dAddOffset(2,0); + if(this.bitLength() > a) this.subTo(BigInteger.ONE.shiftLeft(a-1),this); + } + } + } + else { + // new BigInteger(int,RNG) + var x = new Array(), t = a&7; + x.length = (a>>3)+1; + b.nextBytes(x); + if(t > 0) x[0] &= ((1< 0) { + if(p < BI_DB && (d = this_array[i]>>p) != (this.s&BI_DM)>>p) + r[k++] = d|(this.s<<(BI_DB-p)); + while(i >= 0) { + if(p < 8) { + d = (this_array[i]&((1<>(p+=BI_DB-8); + } + else { + d = (this_array[i]>>(p-=8))&0xff; + if(p <= 0) { p += BI_DB; --i; } + } + if((d&0x80) != 0) d |= -256; + if(k == 0 && (this.s&0x80) != (d&0x80)) ++k; + if(k > 0 || d != this.s) r[k++] = d; + } + } + return r; +} + +function bnEquals(a) { return(this.compareTo(a)==0); } +function bnMin(a) { return(this.compareTo(a)<0)?this:a; } +function bnMax(a) { return(this.compareTo(a)>0)?this:a; } + +// (protected) r = this op a (bitwise) +function bnpBitwiseTo(a,op,r) { + var this_array = this.array; + var a_array = a.array; + var r_array = r.array; + var i, f, m = Math.min(a.t,this.t); + for(i = 0; i < m; ++i) r_array[i] = op(this_array[i],a_array[i]); + if(a.t < this.t) { + f = a.s&BI_DM; + for(i = m; i < this.t; ++i) r_array[i] = op(this_array[i],f); + r.t = this.t; + } + else { + f = this.s&BI_DM; + for(i = m; i < a.t; ++i) r_array[i] = op(f,a_array[i]); + r.t = a.t; + } + r.s = op(this.s,a.s); + r.clamp(); +} + +// (public) this & a +function op_and(x,y) { return x&y; } +function bnAnd(a) { var r = nbi(); this.bitwiseTo(a,op_and,r); return r; } + +// (public) this | a +function op_or(x,y) { return x|y; } +function bnOr(a) { var r = nbi(); this.bitwiseTo(a,op_or,r); return r; } + +// (public) this ^ a +function op_xor(x,y) { return x^y; } +function bnXor(a) { var r = nbi(); this.bitwiseTo(a,op_xor,r); return r; } + +// (public) this & ~a +function op_andnot(x,y) { return x&~y; } +function bnAndNot(a) { var r = nbi(); this.bitwiseTo(a,op_andnot,r); return r; } + +// (public) ~this +function bnNot() { + var this_array = this.array; + var r = nbi(); + var r_array = r.array; + + for(var i = 0; i < this.t; ++i) r_array[i] = BI_DM&~this_array[i]; + r.t = this.t; + r.s = ~this.s; + return r; +} + +// (public) this << n +function bnShiftLeft(n) { + var r = nbi(); + if(n < 0) this.rShiftTo(-n,r); else this.lShiftTo(n,r); + return r; +} + +// (public) this >> n +function bnShiftRight(n) { + var r = nbi(); + if(n < 0) this.lShiftTo(-n,r); else this.rShiftTo(n,r); + return r; +} + +// return index of lowest 1-bit in x, x < 2^31 +function lbit(x) { + if(x == 0) return -1; + var r = 0; + if((x&0xffff) == 0) { x >>= 16; r += 16; } + if((x&0xff) == 0) { x >>= 8; r += 8; } + if((x&0xf) == 0) { x >>= 4; r += 4; } + if((x&3) == 0) { x >>= 2; r += 2; } + if((x&1) == 0) ++r; + return r; +} + +// (public) returns index of lowest 1-bit (or -1 if none) +function bnGetLowestSetBit() { + var this_array = this.array; + for(var i = 0; i < this.t; ++i) + if(this_array[i] != 0) return i*BI_DB+lbit(this_array[i]); + if(this.s < 0) return this.t*BI_DB; + return -1; +} + +// return number of 1 bits in x +function cbit(x) { + var r = 0; + while(x != 0) { x &= x-1; ++r; } + return r; +} + +// (public) return number of set bits +function bnBitCount() { + var r = 0, x = this.s&BI_DM; + for(var i = 0; i < this.t; ++i) r += cbit(this_array[i]^x); + return r; +} + +// (public) true iff nth bit is set +function bnTestBit(n) { + var this_array = this.array; + var j = Math.floor(n/BI_DB); + if(j >= this.t) return(this.s!=0); + return((this_array[j]&(1<<(n%BI_DB)))!=0); +} + +// (protected) this op (1<>= BI_DB; + } + if(a.t < this.t) { + c += a.s; + while(i < this.t) { + c += this_array[i]; + r_array[i++] = c&BI_DM; + c >>= BI_DB; + } + c += this.s; + } + else { + c += this.s; + while(i < a.t) { + c += a_array[i]; + r_array[i++] = c&BI_DM; + c >>= BI_DB; + } + c += a.s; + } + r.s = (c<0)?-1:0; + if(c > 0) r_array[i++] = c; + else if(c < -1) r_array[i++] = BI_DV+c; + r.t = i; + r.clamp(); +} + +// (public) this + a +function bnAdd(a) { var r = nbi(); this.addTo(a,r); return r; } + +// (public) this - a +function bnSubtract(a) { var r = nbi(); this.subTo(a,r); return r; } + +// (public) this * a +function bnMultiply(a) { var r = nbi(); this.multiplyTo(a,r); return r; } + +// (public) this / a +function bnDivide(a) { var r = nbi(); this.divRemTo(a,r,null); return r; } + +// (public) this % a +function bnRemainder(a) { var r = nbi(); this.divRemTo(a,null,r); return r; } + +// (public) [this/a,this%a] +function bnDivideAndRemainder(a) { + var q = nbi(), r = nbi(); + this.divRemTo(a,q,r); + return new Array(q,r); +} + +// (protected) this *= n, this >= 0, 1 < n < DV +function bnpDMultiply(n) { + var this_array = this.array; + this_array[this.t] = this.am(0,n-1,this,0,0,this.t); + ++this.t; + this.clamp(); +} + +// (protected) this += n << w words, this >= 0 +function bnpDAddOffset(n,w) { + var this_array = this.array; + while(this.t <= w) this_array[this.t++] = 0; + this_array[w] += n; + while(this_array[w] >= BI_DV) { + this_array[w] -= BI_DV; + if(++w >= this.t) this_array[this.t++] = 0; + ++this_array[w]; + } +} + +// A "null" reducer +function NullExp() {} +function nNop(x) { return x; } +function nMulTo(x,y,r) { x.multiplyTo(y,r); } +function nSqrTo(x,r) { x.squareTo(r); } + +NullExp.prototype.convert = nNop; +NullExp.prototype.revert = nNop; +NullExp.prototype.mulTo = nMulTo; +NullExp.prototype.sqrTo = nSqrTo; + +// (public) this^e +function bnPow(e) { return this.exp(e,new NullExp()); } + +// (protected) r = lower n words of "this * a", a.t <= n +// "this" should be the larger one if appropriate. +function bnpMultiplyLowerTo(a,n,r) { + var r_array = r.array; + var a_array = a.array; + var i = Math.min(this.t+a.t,n); + r.s = 0; // assumes a,this >= 0 + r.t = i; + while(i > 0) r_array[--i] = 0; + var j; + for(j = r.t-this.t; i < j; ++i) r_array[i+this.t] = this.am(0,a_array[i],r,i,0,this.t); + for(j = Math.min(a.t,n); i < j; ++i) this.am(0,a_array[i],r,i,0,n-i); + r.clamp(); +} + +// (protected) r = "this * a" without lower n words, n > 0 +// "this" should be the larger one if appropriate. +function bnpMultiplyUpperTo(a,n,r) { + var r_array = r.array; + var a_array = a.array; + --n; + var i = r.t = this.t+a.t-n; + r.s = 0; // assumes a,this >= 0 + while(--i >= 0) r_array[i] = 0; + for(i = Math.max(n-this.t,0); i < a.t; ++i) + r_array[this.t+i-n] = this.am(n-i,a_array[i],r,0,0,this.t+i-n); + r.clamp(); + r.drShiftTo(1,r); +} + +// Barrett modular reduction +function Barrett(m) { + // setup Barrett + this.r2 = nbi(); + this.q3 = nbi(); + BigInteger.ONE.dlShiftTo(2*m.t,this.r2); + this.mu = this.r2.divide(m); + this.m = m; +} + +function barrettConvert(x) { + if(x.s < 0 || x.t > 2*this.m.t) return x.mod(this.m); + else if(x.compareTo(this.m) < 0) return x; + else { var r = nbi(); x.copyTo(r); this.reduce(r); return r; } +} + +function barrettRevert(x) { return x; } + +// x = x mod m (HAC 14.42) +function barrettReduce(x) { + x.drShiftTo(this.m.t-1,this.r2); + if(x.t > this.m.t+1) { x.t = this.m.t+1; x.clamp(); } + this.mu.multiplyUpperTo(this.r2,this.m.t+1,this.q3); + this.m.multiplyLowerTo(this.q3,this.m.t+1,this.r2); + while(x.compareTo(this.r2) < 0) x.dAddOffset(1,this.m.t+1); + x.subTo(this.r2,x); + while(x.compareTo(this.m) >= 0) x.subTo(this.m,x); +} + +// r = x^2 mod m; x != r +function barrettSqrTo(x,r) { x.squareTo(r); this.reduce(r); } + +// r = x*y mod m; x,y != r +function barrettMulTo(x,y,r) { x.multiplyTo(y,r); this.reduce(r); } + +Barrett.prototype.convert = barrettConvert; +Barrett.prototype.revert = barrettRevert; +Barrett.prototype.reduce = barrettReduce; +Barrett.prototype.mulTo = barrettMulTo; +Barrett.prototype.sqrTo = barrettSqrTo; + +// (public) this^e % m (HAC 14.85) +function bnModPow(e,m) { + var e_array = e.array; + var i = e.bitLength(), k, r = nbv(1), z; + if(i <= 0) return r; + else if(i < 18) k = 1; + else if(i < 48) k = 3; + else if(i < 144) k = 4; + else if(i < 768) k = 5; + else k = 6; + if(i < 8) + z = new Classic(m); + else if(m.isEven()) + z = new Barrett(m); + else + z = new Montgomery(m); + + // precomputation + var g = new Array(), n = 3, k1 = k-1, km = (1< 1) { + var g2 = nbi(); + z.sqrTo(g[1],g2); + while(n <= km) { + g[n] = nbi(); + z.mulTo(g2,g[n-2],g[n]); + n += 2; + } + } + + var j = e.t-1, w, is1 = true, r2 = nbi(), t; + i = nbits(e_array[j])-1; + while(j >= 0) { + if(i >= k1) w = (e_array[j]>>(i-k1))&km; + else { + w = (e_array[j]&((1<<(i+1))-1))<<(k1-i); + if(j > 0) w |= e_array[j-1]>>(BI_DB+i-k1); + } + + n = k; + while((w&1) == 0) { w >>= 1; --n; } + if((i -= n) < 0) { i += BI_DB; --j; } + if(is1) { // ret == 1, don't bother squaring or multiplying it + g[w].copyTo(r); + is1 = false; + } + else { + while(n > 1) { z.sqrTo(r,r2); z.sqrTo(r2,r); n -= 2; } + if(n > 0) z.sqrTo(r,r2); else { t = r; r = r2; r2 = t; } + z.mulTo(r2,g[w],r); + } + + while(j >= 0 && (e_array[j]&(1< 0) { + x.rShiftTo(g,x); + y.rShiftTo(g,y); + } + while(x.signum() > 0) { + if((i = x.getLowestSetBit()) > 0) x.rShiftTo(i,x); + if((i = y.getLowestSetBit()) > 0) y.rShiftTo(i,y); + if(x.compareTo(y) >= 0) { + x.subTo(y,x); + x.rShiftTo(1,x); + } + else { + y.subTo(x,y); + y.rShiftTo(1,y); + } + } + if(g > 0) y.lShiftTo(g,y); + return y; +} + +// (protected) this % n, n < 2^26 +function bnpModInt(n) { + var this_array = this.array; + if(n <= 0) return 0; + var d = BI_DV%n, r = (this.s<0)?n-1:0; + if(this.t > 0) + if(d == 0) r = this_array[0]%n; + else for(var i = this.t-1; i >= 0; --i) r = (d*r+this_array[i])%n; + return r; +} + +// (public) 1/this % m (HAC 14.61) +function bnModInverse(m) { + var ac = m.isEven(); + if((this.isEven() && ac) || m.signum() == 0) return BigInteger.ZERO; + var u = m.clone(), v = this.clone(); + var a = nbv(1), b = nbv(0), c = nbv(0), d = nbv(1); + while(u.signum() != 0) { + while(u.isEven()) { + u.rShiftTo(1,u); + if(ac) { + if(!a.isEven() || !b.isEven()) { a.addTo(this,a); b.subTo(m,b); } + a.rShiftTo(1,a); + } + else if(!b.isEven()) b.subTo(m,b); + b.rShiftTo(1,b); + } + while(v.isEven()) { + v.rShiftTo(1,v); + if(ac) { + if(!c.isEven() || !d.isEven()) { c.addTo(this,c); d.subTo(m,d); } + c.rShiftTo(1,c); + } + else if(!d.isEven()) d.subTo(m,d); + d.rShiftTo(1,d); + } + if(u.compareTo(v) >= 0) { + u.subTo(v,u); + if(ac) a.subTo(c,a); + b.subTo(d,b); + } + else { + v.subTo(u,v); + if(ac) c.subTo(a,c); + d.subTo(b,d); + } + } + if(v.compareTo(BigInteger.ONE) != 0) return BigInteger.ZERO; + if(d.compareTo(m) >= 0) return d.subtract(m); + if(d.signum() < 0) d.addTo(m,d); else return d; + if(d.signum() < 0) return d.add(m); else return d; +} + +var lowprimes = [2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101,103,107,109,113,127,131,137,139,149,151,157,163,167,173,179,181,191,193,197,199,211,223,227,229,233,239,241,251,257,263,269,271,277,281,283,293,307,311,313,317,331,337,347,349,353,359,367,373,379,383,389,397,401,409,419,421,431,433,439,443,449,457,461,463,467,479,487,491,499,503,509]; +var lplim = (1<<26)/lowprimes[lowprimes.length-1]; + +// (public) test primality with certainty >= 1-.5^t +function bnIsProbablePrime(t) { + var i, x = this.abs(); + var x_array = x.array; + if(x.t == 1 && x_array[0] <= lowprimes[lowprimes.length-1]) { + for(i = 0; i < lowprimes.length; ++i) + if(x_array[0] == lowprimes[i]) return true; + return false; + } + if(x.isEven()) return false; + i = 1; + while(i < lowprimes.length) { + var m = lowprimes[i], j = i+1; + while(j < lowprimes.length && m < lplim) m *= lowprimes[j++]; + m = x.modInt(m); + while(i < j) if(m%lowprimes[i++] == 0) return false; + } + return x.millerRabin(t); +} + +// (protected) true if probably prime (HAC 4.24, Miller-Rabin) +function bnpMillerRabin(t) { + var n1 = this.subtract(BigInteger.ONE); + var k = n1.getLowestSetBit(); + if(k <= 0) return false; + var r = n1.shiftRight(k); + t = (t+1)>>1; + if(t > lowprimes.length) t = lowprimes.length; + var a = nbi(); + for(var i = 0; i < t; ++i) { + a.fromInt(lowprimes[i]); + var y = a.modPow(r,this); + if(y.compareTo(BigInteger.ONE) != 0 && y.compareTo(n1) != 0) { + var j = 1; + while(j++ < k && y.compareTo(n1) != 0) { + y = y.modPowInt(2,this); + if(y.compareTo(BigInteger.ONE) == 0) return false; + } + if(y.compareTo(n1) != 0) return false; + } + } + return true; +} + +// protected +BigInteger.prototype.chunkSize = bnpChunkSize; +BigInteger.prototype.toRadix = bnpToRadix; +BigInteger.prototype.fromRadix = bnpFromRadix; +BigInteger.prototype.fromNumber = bnpFromNumber; +BigInteger.prototype.bitwiseTo = bnpBitwiseTo; +BigInteger.prototype.changeBit = bnpChangeBit; +BigInteger.prototype.addTo = bnpAddTo; +BigInteger.prototype.dMultiply = bnpDMultiply; +BigInteger.prototype.dAddOffset = bnpDAddOffset; +BigInteger.prototype.multiplyLowerTo = bnpMultiplyLowerTo; +BigInteger.prototype.multiplyUpperTo = bnpMultiplyUpperTo; +BigInteger.prototype.modInt = bnpModInt; +BigInteger.prototype.millerRabin = bnpMillerRabin; + +// public +BigInteger.prototype.clone = bnClone; +BigInteger.prototype.intValue = bnIntValue; +BigInteger.prototype.byteValue = bnByteValue; +BigInteger.prototype.shortValue = bnShortValue; +BigInteger.prototype.signum = bnSigNum; +BigInteger.prototype.toByteArray = bnToByteArray; +BigInteger.prototype.equals = bnEquals; +BigInteger.prototype.min = bnMin; +BigInteger.prototype.max = bnMax; +BigInteger.prototype.and = bnAnd; +BigInteger.prototype.or = bnOr; +BigInteger.prototype.xor = bnXor; +BigInteger.prototype.andNot = bnAndNot; +BigInteger.prototype.not = bnNot; +BigInteger.prototype.shiftLeft = bnShiftLeft; +BigInteger.prototype.shiftRight = bnShiftRight; +BigInteger.prototype.getLowestSetBit = bnGetLowestSetBit; +BigInteger.prototype.bitCount = bnBitCount; +BigInteger.prototype.testBit = bnTestBit; +BigInteger.prototype.setBit = bnSetBit; +BigInteger.prototype.clearBit = bnClearBit; +BigInteger.prototype.flipBit = bnFlipBit; +BigInteger.prototype.add = bnAdd; +BigInteger.prototype.subtract = bnSubtract; +BigInteger.prototype.multiply = bnMultiply; +BigInteger.prototype.divide = bnDivide; +BigInteger.prototype.remainder = bnRemainder; +BigInteger.prototype.divideAndRemainder = bnDivideAndRemainder; +BigInteger.prototype.modPow = bnModPow; +BigInteger.prototype.modInverse = bnModInverse; +BigInteger.prototype.pow = bnPow; +BigInteger.prototype.gcd = bnGCD; +BigInteger.prototype.isProbablePrime = bnIsProbablePrime; + +// BigInteger interfaces not implemented in jsbn: + +// BigInteger(int signum, byte[] magnitude) +// double doubleValue() +// float floatValue() +// int hashCode() +// long longValue() +// static BigInteger valueOf(long val) +// prng4.js - uses Arcfour as a PRNG + +function Arcfour() { + this.i = 0; + this.j = 0; + this.S = new Array(); +} + +// Initialize arcfour context from key, an array of ints, each from [0..255] +function ARC4init(key) { + var i, j, t; + for(i = 0; i < 256; ++i) + this.S[i] = i; + j = 0; + for(i = 0; i < 256; ++i) { + j = (j + this.S[i] + key[i % key.length]) & 255; + t = this.S[i]; + this.S[i] = this.S[j]; + this.S[j] = t; + } + this.i = 0; + this.j = 0; +} + +function ARC4next() { + var t; + this.i = (this.i + 1) & 255; + this.j = (this.j + this.S[this.i]) & 255; + t = this.S[this.i]; + this.S[this.i] = this.S[this.j]; + this.S[this.j] = t; + return this.S[(t + this.S[this.i]) & 255]; +} + +Arcfour.prototype.init = ARC4init; +Arcfour.prototype.next = ARC4next; + +// Plug in your RNG constructor here +function prng_newstate() { + return new Arcfour(); +} + +// Pool size must be a multiple of 4 and greater than 32. +// An array of bytes the size of the pool will be passed to init() +var rng_psize = 256; +// Random number generator - requires a PRNG backend, e.g. prng4.js + +// For best results, put code like +// +// in your main HTML document. + +var rng_state; +var rng_pool; +var rng_pptr; + +// Mix in a 32-bit integer into the pool +function rng_seed_int(x) { + rng_pool[rng_pptr++] ^= x & 255; + rng_pool[rng_pptr++] ^= (x >> 8) & 255; + rng_pool[rng_pptr++] ^= (x >> 16) & 255; + rng_pool[rng_pptr++] ^= (x >> 24) & 255; + if(rng_pptr >= rng_psize) rng_pptr -= rng_psize; +} + +// Mix in the current time (w/milliseconds) into the pool +function rng_seed_time() { + // Use pre-computed date to avoid making the benchmark + // results dependent on the current date. + rng_seed_int(1122926989487); +} + +// Initialize the pool with junk if needed. +if(rng_pool == null) { + rng_pool = new Array(); + rng_pptr = 0; + var t; + while(rng_pptr < rng_psize) { // extract some randomness from Math.random() + t = Math.floor(65536 * Math.random()); + rng_pool[rng_pptr++] = t >>> 8; + rng_pool[rng_pptr++] = t & 255; + } + rng_pptr = 0; + rng_seed_time(); + //rng_seed_int(window.screenX); + //rng_seed_int(window.screenY); +} + +function rng_get_byte() { + if(rng_state == null) { + rng_seed_time(); + rng_state = prng_newstate(); + rng_state.init(rng_pool); + for(rng_pptr = 0; rng_pptr < rng_pool.length; ++rng_pptr) + rng_pool[rng_pptr] = 0; + rng_pptr = 0; + //rng_pool = null; + } + // TODO: allow reseeding after first request + return rng_state.next(); +} + +function rng_get_bytes(ba) { + var i; + for(i = 0; i < ba.length; ++i) ba[i] = rng_get_byte(); +} + +function SecureRandom() {} + +SecureRandom.prototype.nextBytes = rng_get_bytes; +// Depends on jsbn.js and rng.js + +// convert a (hex) string to a bignum object +function parseBigInt(str,r) { + return new BigInteger(str,r); +} + +function linebrk(s,n) { + var ret = ""; + var i = 0; + while(i + n < s.length) { + ret += s.substring(i,i+n) + "\n"; + i += n; + } + return ret + s.substring(i,s.length); +} + +function byte2Hex(b) { + if(b < 0x10) + return "0" + b.toString(16); + else + return b.toString(16); +} + +// PKCS#1 (type 2, random) pad input string s to n bytes, and return a bigint +function pkcs1pad2(s,n) { + if(n < s.length + 11) { + alert("Message too long for RSA"); + return null; + } + var ba = new Array(); + var i = s.length - 1; + while(i >= 0 && n > 0) ba[--n] = s.charCodeAt(i--); + ba[--n] = 0; + var rng = new SecureRandom(); + var x = new Array(); + while(n > 2) { // random non-zero pad + x[0] = 0; + while(x[0] == 0) rng.nextBytes(x); + ba[--n] = x[0]; + } + ba[--n] = 2; + ba[--n] = 0; + return new BigInteger(ba); +} + +// "empty" RSA key constructor +function RSAKey() { + this.n = null; + this.e = 0; + this.d = null; + this.p = null; + this.q = null; + this.dmp1 = null; + this.dmq1 = null; + this.coeff = null; +} + +// Set the public key fields N and e from hex strings +function RSASetPublic(N,E) { + if(N != null && E != null && N.length > 0 && E.length > 0) { + this.n = parseBigInt(N,16); + this.e = parseInt(E,16); + } + else + alert("Invalid RSA public key"); +} + +// Perform raw public operation on "x": return x^e (mod n) +function RSADoPublic(x) { + return x.modPowInt(this.e, this.n); +} + +// Return the PKCS#1 RSA encryption of "text" as an even-length hex string +function RSAEncrypt(text) { + var m = pkcs1pad2(text,(this.n.bitLength()+7)>>3); + if(m == null) return null; + var c = this.doPublic(m); + if(c == null) return null; + var h = c.toString(16); + if((h.length & 1) == 0) return h; else return "0" + h; +} + +// Return the PKCS#1 RSA encryption of "text" as a Base64-encoded string +//function RSAEncryptB64(text) { +// var h = this.encrypt(text); +// if(h) return hex2b64(h); else return null; +//} + +// protected +RSAKey.prototype.doPublic = RSADoPublic; + +// public +RSAKey.prototype.setPublic = RSASetPublic; +RSAKey.prototype.encrypt = RSAEncrypt; +//RSAKey.prototype.encrypt_b64 = RSAEncryptB64; +// Depends on rsa.js and jsbn2.js + +// Undo PKCS#1 (type 2, random) padding and, if valid, return the plaintext +function pkcs1unpad2(d,n) { + var b = d.toByteArray(); + var i = 0; + while(i < b.length && b[i] == 0) ++i; + if(b.length-i != n-1 || b[i] != 2) + return null; + ++i; + while(b[i] != 0) + if(++i >= b.length) return null; + var ret = ""; + while(++i < b.length) + ret += String.fromCharCode(b[i]); + return ret; +} + +// Set the private key fields N, e, and d from hex strings +function RSASetPrivate(N,E,D) { + if(N != null && E != null && N.length > 0 && E.length > 0) { + this.n = parseBigInt(N,16); + this.e = parseInt(E,16); + this.d = parseBigInt(D,16); + } + else + alert("Invalid RSA private key"); +} + +// Set the private key fields N, e, d and CRT params from hex strings +function RSASetPrivateEx(N,E,D,P,Q,DP,DQ,C) { + if(N != null && E != null && N.length > 0 && E.length > 0) { + this.n = parseBigInt(N,16); + this.e = parseInt(E,16); + this.d = parseBigInt(D,16); + this.p = parseBigInt(P,16); + this.q = parseBigInt(Q,16); + this.dmp1 = parseBigInt(DP,16); + this.dmq1 = parseBigInt(DQ,16); + this.coeff = parseBigInt(C,16); + } + else + alert("Invalid RSA private key"); +} + +// Generate a new random private key B bits long, using public expt E +function RSAGenerate(B,E) { + var rng = new SecureRandom(); + var qs = B>>1; + this.e = parseInt(E,16); + var ee = new BigInteger(E,16); + for(;;) { + for(;;) { + this.p = new BigInteger(B-qs,1,rng); + if(this.p.subtract(BigInteger.ONE).gcd(ee).compareTo(BigInteger.ONE) == 0 && this.p.isProbablePrime(10)) break; + } + for(;;) { + this.q = new BigInteger(qs,1,rng); + if(this.q.subtract(BigInteger.ONE).gcd(ee).compareTo(BigInteger.ONE) == 0 && this.q.isProbablePrime(10)) break; + } + if(this.p.compareTo(this.q) <= 0) { + var t = this.p; + this.p = this.q; + this.q = t; + } + var p1 = this.p.subtract(BigInteger.ONE); + var q1 = this.q.subtract(BigInteger.ONE); + var phi = p1.multiply(q1); + if(phi.gcd(ee).compareTo(BigInteger.ONE) == 0) { + this.n = this.p.multiply(this.q); + this.d = ee.modInverse(phi); + this.dmp1 = this.d.mod(p1); + this.dmq1 = this.d.mod(q1); + this.coeff = this.q.modInverse(this.p); + break; + } + } +} + +// Perform raw private operation on "x": return x^d (mod n) +function RSADoPrivate(x) { + if(this.p == null || this.q == null) + return x.modPow(this.d, this.n); + + // TODO: re-calculate any missing CRT params + var xp = x.mod(this.p).modPow(this.dmp1, this.p); + var xq = x.mod(this.q).modPow(this.dmq1, this.q); + + while(xp.compareTo(xq) < 0) + xp = xp.add(this.p); + return xp.subtract(xq).multiply(this.coeff).mod(this.p).multiply(this.q).add(xq); +} + +// Return the PKCS#1 RSA decryption of "ctext". +// "ctext" is an even-length hex string and the output is a plain string. +function RSADecrypt(ctext) { + var c = parseBigInt(ctext, 16); + var m = this.doPrivate(c); + if(m == null) return null; + return pkcs1unpad2(m, (this.n.bitLength()+7)>>3); +} + +// Return the PKCS#1 RSA decryption of "ctext". +// "ctext" is a Base64-encoded string and the output is a plain string. +//function RSAB64Decrypt(ctext) { +// var h = b64tohex(ctext); +// if(h) return this.decrypt(h); else return null; +//} + +// protected +RSAKey.prototype.doPrivate = RSADoPrivate; + +// public +RSAKey.prototype.setPrivate = RSASetPrivate; +RSAKey.prototype.setPrivateEx = RSASetPrivateEx; +RSAKey.prototype.generate = RSAGenerate; +RSAKey.prototype.decrypt = RSADecrypt; +//RSAKey.prototype.b64_decrypt = RSAB64Decrypt; + + +nValue="a5261939975948bb7a58dffe5ff54e65f0498f9175f5a09288810b8975871e99af3b5dd94057b0fc07535f5f97444504fa35169d461d0d30cf0192e307727c065168c788771c561a9400fb49175e9e6aa4e23fe11af69e9412dd23b0cb6684c4c2429bce139e848ab26d0829073351f4acd36074eafd036a5eb83359d2a698d3"; +eValue="10001"; +dValue="8e9912f6d3645894e8d38cb58c0db81ff516cf4c7e5a14c7f1eddb1459d2cded4d8d293fc97aee6aefb861859c8b6a3d1dfe710463e1f9ddc72048c09751971c4a580aa51eb523357a3cc48d31cfad1d4a165066ed92d4748fb6571211da5cb14bc11b6e2df7c1a559e6d5ac1cd5c94703a22891464fba23d0d965086277a161"; +pValue="d090ce58a92c75233a6486cb0a9209bf3583b64f540c76f5294bb97d285eed33aec220bde14b2417951178ac152ceab6da7090905b478195498b352048f15e7d"; +qValue="cab575dc652bb66df15a0359609d51d1db184750c00c6698b90ef3465c99655103edbf0d54c56aec0ce3c4d22592338092a126a0cc49f65a4a30d222b411e58f"; +dmp1Value="1a24bca8e273df2f0e47c199bbf678604e7df7215480c77c8db39f49b000ce2cf7500038acfff5433b7d582a01f1826e6f4d42e1c57f5e1fef7b12aabc59fd25"; +dmq1Value="3d06982efbbe47339e1f6d36b1216b8a741d410b0c662f54f7118b27b9a4ec9d914337eb39841d8666f3034408cf94f5b62f11c402fc994fe15a05493150d9fd"; +coeffValue="3a3e731acd8960b7ff9eb81a7ff93bd1cfa74cbd56987db58b4594fb09c09084db1734c8143f98b602b981aaa9243ca28deb69b5b280ee8dcee0fd2625e53250"; + +setupEngine(am3, 28); + +var TEXT = "The quick brown fox jumped over the extremely lazy frog! " + + "Now is the time for all good men to come to the party."; +var encrypted; + +function encrypt() { + var RSA = new RSAKey(); + RSA.setPublic(nValue, eValue); + RSA.setPrivateEx(nValue, eValue, dValue, pValue, qValue, dmp1Value, dmq1Value, coeffValue); + encrypted = RSA.encrypt(TEXT); +} + +function decrypt() { + var RSA = new RSAKey(); + RSA.setPublic(nValue, eValue); + RSA.setPrivateEx(nValue, eValue, dValue, pValue, qValue, dmp1Value, dmq1Value, coeffValue); + var decrypted = RSA.decrypt(encrypted); + if (decrypted != TEXT) { + throw new Error("Crypto operation failed"); + } +} diff --git a/node-v0.8.14/deps/v8/benchmarks/deltablue.js b/node-v0.8.14/deps/v8/benchmarks/deltablue.js new file mode 100644 index 0000000..548fd96 --- /dev/null +++ b/node-v0.8.14/deps/v8/benchmarks/deltablue.js @@ -0,0 +1,880 @@ +// Copyright 2008 the V8 project authors. All rights reserved. +// Copyright 1996 John Maloney and Mario Wolczko. + +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation; either version 2 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License +// along with this program; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + +// This implementation of the DeltaBlue benchmark is derived +// from the Smalltalk implementation by John Maloney and Mario +// Wolczko. Some parts have been translated directly, whereas +// others have been modified more aggresively to make it feel +// more like a JavaScript program. + + +var DeltaBlue = new BenchmarkSuite('DeltaBlue', 66118, [ + new Benchmark('DeltaBlue', deltaBlue) +]); + + +/** + * A JavaScript implementation of the DeltaBlue constraint-solving + * algorithm, as described in: + * + * "The DeltaBlue Algorithm: An Incremental Constraint Hierarchy Solver" + * Bjorn N. Freeman-Benson and John Maloney + * January 1990 Communications of the ACM, + * also available as University of Washington TR 89-08-06. + * + * Beware: this benchmark is written in a grotesque style where + * the constraint model is built by side-effects from constructors. + * I've kept it this way to avoid deviating too much from the original + * implementation. + */ + + +/* --- O b j e c t M o d e l --- */ + +Object.prototype.inheritsFrom = function (shuper) { + function Inheriter() { } + Inheriter.prototype = shuper.prototype; + this.prototype = new Inheriter(); + this.superConstructor = shuper; +} + +function OrderedCollection() { + this.elms = new Array(); +} + +OrderedCollection.prototype.add = function (elm) { + this.elms.push(elm); +} + +OrderedCollection.prototype.at = function (index) { + return this.elms[index]; +} + +OrderedCollection.prototype.size = function () { + return this.elms.length; +} + +OrderedCollection.prototype.removeFirst = function () { + return this.elms.pop(); +} + +OrderedCollection.prototype.remove = function (elm) { + var index = 0, skipped = 0; + for (var i = 0; i < this.elms.length; i++) { + var value = this.elms[i]; + if (value != elm) { + this.elms[index] = value; + index++; + } else { + skipped++; + } + } + for (var i = 0; i < skipped; i++) + this.elms.pop(); +} + +/* --- * + * S t r e n g t h + * --- */ + +/** + * Strengths are used to measure the relative importance of constraints. + * New strengths may be inserted in the strength hierarchy without + * disrupting current constraints. Strengths cannot be created outside + * this class, so pointer comparison can be used for value comparison. + */ +function Strength(strengthValue, name) { + this.strengthValue = strengthValue; + this.name = name; +} + +Strength.stronger = function (s1, s2) { + return s1.strengthValue < s2.strengthValue; +} + +Strength.weaker = function (s1, s2) { + return s1.strengthValue > s2.strengthValue; +} + +Strength.weakestOf = function (s1, s2) { + return this.weaker(s1, s2) ? s1 : s2; +} + +Strength.strongest = function (s1, s2) { + return this.stronger(s1, s2) ? s1 : s2; +} + +Strength.prototype.nextWeaker = function () { + switch (this.strengthValue) { + case 0: return Strength.WEAKEST; + case 1: return Strength.WEAK_DEFAULT; + case 2: return Strength.NORMAL; + case 3: return Strength.STRONG_DEFAULT; + case 4: return Strength.PREFERRED; + case 5: return Strength.REQUIRED; + } +} + +// Strength constants. +Strength.REQUIRED = new Strength(0, "required"); +Strength.STONG_PREFERRED = new Strength(1, "strongPreferred"); +Strength.PREFERRED = new Strength(2, "preferred"); +Strength.STRONG_DEFAULT = new Strength(3, "strongDefault"); +Strength.NORMAL = new Strength(4, "normal"); +Strength.WEAK_DEFAULT = new Strength(5, "weakDefault"); +Strength.WEAKEST = new Strength(6, "weakest"); + +/* --- * + * C o n s t r a i n t + * --- */ + +/** + * An abstract class representing a system-maintainable relationship + * (or "constraint") between a set of variables. A constraint supplies + * a strength instance variable; concrete subclasses provide a means + * of storing the constrained variables and other information required + * to represent a constraint. + */ +function Constraint(strength) { + this.strength = strength; +} + +/** + * Activate this constraint and attempt to satisfy it. + */ +Constraint.prototype.addConstraint = function () { + this.addToGraph(); + planner.incrementalAdd(this); +} + +/** + * Attempt to find a way to enforce this constraint. If successful, + * record the solution, perhaps modifying the current dataflow + * graph. Answer the constraint that this constraint overrides, if + * there is one, or nil, if there isn't. + * Assume: I am not already satisfied. + */ +Constraint.prototype.satisfy = function (mark) { + this.chooseMethod(mark); + if (!this.isSatisfied()) { + if (this.strength == Strength.REQUIRED) + alert("Could not satisfy a required constraint!"); + return null; + } + this.markInputs(mark); + var out = this.output(); + var overridden = out.determinedBy; + if (overridden != null) overridden.markUnsatisfied(); + out.determinedBy = this; + if (!planner.addPropagate(this, mark)) + alert("Cycle encountered"); + out.mark = mark; + return overridden; +} + +Constraint.prototype.destroyConstraint = function () { + if (this.isSatisfied()) planner.incrementalRemove(this); + else this.removeFromGraph(); +} + +/** + * Normal constraints are not input constraints. An input constraint + * is one that depends on external state, such as the mouse, the + * keybord, a clock, or some arbitraty piece of imperative code. + */ +Constraint.prototype.isInput = function () { + return false; +} + +/* --- * + * U n a r y C o n s t r a i n t + * --- */ + +/** + * Abstract superclass for constraints having a single possible output + * variable. + */ +function UnaryConstraint(v, strength) { + UnaryConstraint.superConstructor.call(this, strength); + this.myOutput = v; + this.satisfied = false; + this.addConstraint(); +} + +UnaryConstraint.inheritsFrom(Constraint); + +/** + * Adds this constraint to the constraint graph + */ +UnaryConstraint.prototype.addToGraph = function () { + this.myOutput.addConstraint(this); + this.satisfied = false; +} + +/** + * Decides if this constraint can be satisfied and records that + * decision. + */ +UnaryConstraint.prototype.chooseMethod = function (mark) { + this.satisfied = (this.myOutput.mark != mark) + && Strength.stronger(this.strength, this.myOutput.walkStrength); +} + +/** + * Returns true if this constraint is satisfied in the current solution. + */ +UnaryConstraint.prototype.isSatisfied = function () { + return this.satisfied; +} + +UnaryConstraint.prototype.markInputs = function (mark) { + // has no inputs +} + +/** + * Returns the current output variable. + */ +UnaryConstraint.prototype.output = function () { + return this.myOutput; +} + +/** + * Calculate the walkabout strength, the stay flag, and, if it is + * 'stay', the value for the current output of this constraint. Assume + * this constraint is satisfied. + */ +UnaryConstraint.prototype.recalculate = function () { + this.myOutput.walkStrength = this.strength; + this.myOutput.stay = !this.isInput(); + if (this.myOutput.stay) this.execute(); // Stay optimization +} + +/** + * Records that this constraint is unsatisfied + */ +UnaryConstraint.prototype.markUnsatisfied = function () { + this.satisfied = false; +} + +UnaryConstraint.prototype.inputsKnown = function () { + return true; +} + +UnaryConstraint.prototype.removeFromGraph = function () { + if (this.myOutput != null) this.myOutput.removeConstraint(this); + this.satisfied = false; +} + +/* --- * + * S t a y C o n s t r a i n t + * --- */ + +/** + * Variables that should, with some level of preference, stay the same. + * Planners may exploit the fact that instances, if satisfied, will not + * change their output during plan execution. This is called "stay + * optimization". + */ +function StayConstraint(v, str) { + StayConstraint.superConstructor.call(this, v, str); +} + +StayConstraint.inheritsFrom(UnaryConstraint); + +StayConstraint.prototype.execute = function () { + // Stay constraints do nothing +} + +/* --- * + * E d i t C o n s t r a i n t + * --- */ + +/** + * A unary input constraint used to mark a variable that the client + * wishes to change. + */ +function EditConstraint(v, str) { + EditConstraint.superConstructor.call(this, v, str); +} + +EditConstraint.inheritsFrom(UnaryConstraint); + +/** + * Edits indicate that a variable is to be changed by imperative code. + */ +EditConstraint.prototype.isInput = function () { + return true; +} + +EditConstraint.prototype.execute = function () { + // Edit constraints do nothing +} + +/* --- * + * B i n a r y C o n s t r a i n t + * --- */ + +var Direction = new Object(); +Direction.NONE = 0; +Direction.FORWARD = 1; +Direction.BACKWARD = -1; + +/** + * Abstract superclass for constraints having two possible output + * variables. + */ +function BinaryConstraint(var1, var2, strength) { + BinaryConstraint.superConstructor.call(this, strength); + this.v1 = var1; + this.v2 = var2; + this.direction = Direction.NONE; + this.addConstraint(); +} + +BinaryConstraint.inheritsFrom(Constraint); + +/** + * Decides if this constraint can be satisfied and which way it + * should flow based on the relative strength of the variables related, + * and record that decision. + */ +BinaryConstraint.prototype.chooseMethod = function (mark) { + if (this.v1.mark == mark) { + this.direction = (this.v2.mark != mark && Strength.stronger(this.strength, this.v2.walkStrength)) + ? Direction.FORWARD + : Direction.NONE; + } + if (this.v2.mark == mark) { + this.direction = (this.v1.mark != mark && Strength.stronger(this.strength, this.v1.walkStrength)) + ? Direction.BACKWARD + : Direction.NONE; + } + if (Strength.weaker(this.v1.walkStrength, this.v2.walkStrength)) { + this.direction = Strength.stronger(this.strength, this.v1.walkStrength) + ? Direction.BACKWARD + : Direction.NONE; + } else { + this.direction = Strength.stronger(this.strength, this.v2.walkStrength) + ? Direction.FORWARD + : Direction.BACKWARD + } +} + +/** + * Add this constraint to the constraint graph + */ +BinaryConstraint.prototype.addToGraph = function () { + this.v1.addConstraint(this); + this.v2.addConstraint(this); + this.direction = Direction.NONE; +} + +/** + * Answer true if this constraint is satisfied in the current solution. + */ +BinaryConstraint.prototype.isSatisfied = function () { + return this.direction != Direction.NONE; +} + +/** + * Mark the input variable with the given mark. + */ +BinaryConstraint.prototype.markInputs = function (mark) { + this.input().mark = mark; +} + +/** + * Returns the current input variable + */ +BinaryConstraint.prototype.input = function () { + return (this.direction == Direction.FORWARD) ? this.v1 : this.v2; +} + +/** + * Returns the current output variable + */ +BinaryConstraint.prototype.output = function () { + return (this.direction == Direction.FORWARD) ? this.v2 : this.v1; +} + +/** + * Calculate the walkabout strength, the stay flag, and, if it is + * 'stay', the value for the current output of this + * constraint. Assume this constraint is satisfied. + */ +BinaryConstraint.prototype.recalculate = function () { + var ihn = this.input(), out = this.output(); + out.walkStrength = Strength.weakestOf(this.strength, ihn.walkStrength); + out.stay = ihn.stay; + if (out.stay) this.execute(); +} + +/** + * Record the fact that this constraint is unsatisfied. + */ +BinaryConstraint.prototype.markUnsatisfied = function () { + this.direction = Direction.NONE; +} + +BinaryConstraint.prototype.inputsKnown = function (mark) { + var i = this.input(); + return i.mark == mark || i.stay || i.determinedBy == null; +} + +BinaryConstraint.prototype.removeFromGraph = function () { + if (this.v1 != null) this.v1.removeConstraint(this); + if (this.v2 != null) this.v2.removeConstraint(this); + this.direction = Direction.NONE; +} + +/* --- * + * S c a l e C o n s t r a i n t + * --- */ + +/** + * Relates two variables by the linear scaling relationship: "v2 = + * (v1 * scale) + offset". Either v1 or v2 may be changed to maintain + * this relationship but the scale factor and offset are considered + * read-only. + */ +function ScaleConstraint(src, scale, offset, dest, strength) { + this.direction = Direction.NONE; + this.scale = scale; + this.offset = offset; + ScaleConstraint.superConstructor.call(this, src, dest, strength); +} + +ScaleConstraint.inheritsFrom(BinaryConstraint); + +/** + * Adds this constraint to the constraint graph. + */ +ScaleConstraint.prototype.addToGraph = function () { + ScaleConstraint.superConstructor.prototype.addToGraph.call(this); + this.scale.addConstraint(this); + this.offset.addConstraint(this); +} + +ScaleConstraint.prototype.removeFromGraph = function () { + ScaleConstraint.superConstructor.prototype.removeFromGraph.call(this); + if (this.scale != null) this.scale.removeConstraint(this); + if (this.offset != null) this.offset.removeConstraint(this); +} + +ScaleConstraint.prototype.markInputs = function (mark) { + ScaleConstraint.superConstructor.prototype.markInputs.call(this, mark); + this.scale.mark = this.offset.mark = mark; +} + +/** + * Enforce this constraint. Assume that it is satisfied. + */ +ScaleConstraint.prototype.execute = function () { + if (this.direction == Direction.FORWARD) { + this.v2.value = this.v1.value * this.scale.value + this.offset.value; + } else { + this.v1.value = (this.v2.value - this.offset.value) / this.scale.value; + } +} + +/** + * Calculate the walkabout strength, the stay flag, and, if it is + * 'stay', the value for the current output of this constraint. Assume + * this constraint is satisfied. + */ +ScaleConstraint.prototype.recalculate = function () { + var ihn = this.input(), out = this.output(); + out.walkStrength = Strength.weakestOf(this.strength, ihn.walkStrength); + out.stay = ihn.stay && this.scale.stay && this.offset.stay; + if (out.stay) this.execute(); +} + +/* --- * + * E q u a l i t y C o n s t r a i n t + * --- */ + +/** + * Constrains two variables to have the same value. + */ +function EqualityConstraint(var1, var2, strength) { + EqualityConstraint.superConstructor.call(this, var1, var2, strength); +} + +EqualityConstraint.inheritsFrom(BinaryConstraint); + +/** + * Enforce this constraint. Assume that it is satisfied. + */ +EqualityConstraint.prototype.execute = function () { + this.output().value = this.input().value; +} + +/* --- * + * V a r i a b l e + * --- */ + +/** + * A constrained variable. In addition to its value, it maintain the + * structure of the constraint graph, the current dataflow graph, and + * various parameters of interest to the DeltaBlue incremental + * constraint solver. + **/ +function Variable(name, initialValue) { + this.value = initialValue || 0; + this.constraints = new OrderedCollection(); + this.determinedBy = null; + this.mark = 0; + this.walkStrength = Strength.WEAKEST; + this.stay = true; + this.name = name; +} + +/** + * Add the given constraint to the set of all constraints that refer + * this variable. + */ +Variable.prototype.addConstraint = function (c) { + this.constraints.add(c); +} + +/** + * Removes all traces of c from this variable. + */ +Variable.prototype.removeConstraint = function (c) { + this.constraints.remove(c); + if (this.determinedBy == c) this.determinedBy = null; +} + +/* --- * + * P l a n n e r + * --- */ + +/** + * The DeltaBlue planner + */ +function Planner() { + this.currentMark = 0; +} + +/** + * Attempt to satisfy the given constraint and, if successful, + * incrementally update the dataflow graph. Details: If satifying + * the constraint is successful, it may override a weaker constraint + * on its output. The algorithm attempts to resatisfy that + * constraint using some other method. This process is repeated + * until either a) it reaches a variable that was not previously + * determined by any constraint or b) it reaches a constraint that + * is too weak to be satisfied using any of its methods. The + * variables of constraints that have been processed are marked with + * a unique mark value so that we know where we've been. This allows + * the algorithm to avoid getting into an infinite loop even if the + * constraint graph has an inadvertent cycle. + */ +Planner.prototype.incrementalAdd = function (c) { + var mark = this.newMark(); + var overridden = c.satisfy(mark); + while (overridden != null) + overridden = overridden.satisfy(mark); +} + +/** + * Entry point for retracting a constraint. Remove the given + * constraint and incrementally update the dataflow graph. + * Details: Retracting the given constraint may allow some currently + * unsatisfiable downstream constraint to be satisfied. We therefore collect + * a list of unsatisfied downstream constraints and attempt to + * satisfy each one in turn. This list is traversed by constraint + * strength, strongest first, as a heuristic for avoiding + * unnecessarily adding and then overriding weak constraints. + * Assume: c is satisfied. + */ +Planner.prototype.incrementalRemove = function (c) { + var out = c.output(); + c.markUnsatisfied(); + c.removeFromGraph(); + var unsatisfied = this.removePropagateFrom(out); + var strength = Strength.REQUIRED; + do { + for (var i = 0; i < unsatisfied.size(); i++) { + var u = unsatisfied.at(i); + if (u.strength == strength) + this.incrementalAdd(u); + } + strength = strength.nextWeaker(); + } while (strength != Strength.WEAKEST); +} + +/** + * Select a previously unused mark value. + */ +Planner.prototype.newMark = function () { + return ++this.currentMark; +} + +/** + * Extract a plan for resatisfaction starting from the given source + * constraints, usually a set of input constraints. This method + * assumes that stay optimization is desired; the plan will contain + * only constraints whose output variables are not stay. Constraints + * that do no computation, such as stay and edit constraints, are + * not included in the plan. + * Details: The outputs of a constraint are marked when it is added + * to the plan under construction. A constraint may be appended to + * the plan when all its input variables are known. A variable is + * known if either a) the variable is marked (indicating that has + * been computed by a constraint appearing earlier in the plan), b) + * the variable is 'stay' (i.e. it is a constant at plan execution + * time), or c) the variable is not determined by any + * constraint. The last provision is for past states of history + * variables, which are not stay but which are also not computed by + * any constraint. + * Assume: sources are all satisfied. + */ +Planner.prototype.makePlan = function (sources) { + var mark = this.newMark(); + var plan = new Plan(); + var todo = sources; + while (todo.size() > 0) { + var c = todo.removeFirst(); + if (c.output().mark != mark && c.inputsKnown(mark)) { + plan.addConstraint(c); + c.output().mark = mark; + this.addConstraintsConsumingTo(c.output(), todo); + } + } + return plan; +} + +/** + * Extract a plan for resatisfying starting from the output of the + * given constraints, usually a set of input constraints. + */ +Planner.prototype.extractPlanFromConstraints = function (constraints) { + var sources = new OrderedCollection(); + for (var i = 0; i < constraints.size(); i++) { + var c = constraints.at(i); + if (c.isInput() && c.isSatisfied()) + // not in plan already and eligible for inclusion + sources.add(c); + } + return this.makePlan(sources); +} + +/** + * Recompute the walkabout strengths and stay flags of all variables + * downstream of the given constraint and recompute the actual + * values of all variables whose stay flag is true. If a cycle is + * detected, remove the given constraint and answer + * false. Otherwise, answer true. + * Details: Cycles are detected when a marked variable is + * encountered downstream of the given constraint. The sender is + * assumed to have marked the inputs of the given constraint with + * the given mark. Thus, encountering a marked node downstream of + * the output constraint means that there is a path from the + * constraint's output to one of its inputs. + */ +Planner.prototype.addPropagate = function (c, mark) { + var todo = new OrderedCollection(); + todo.add(c); + while (todo.size() > 0) { + var d = todo.removeFirst(); + if (d.output().mark == mark) { + this.incrementalRemove(c); + return false; + } + d.recalculate(); + this.addConstraintsConsumingTo(d.output(), todo); + } + return true; +} + + +/** + * Update the walkabout strengths and stay flags of all variables + * downstream of the given constraint. Answer a collection of + * unsatisfied constraints sorted in order of decreasing strength. + */ +Planner.prototype.removePropagateFrom = function (out) { + out.determinedBy = null; + out.walkStrength = Strength.WEAKEST; + out.stay = true; + var unsatisfied = new OrderedCollection(); + var todo = new OrderedCollection(); + todo.add(out); + while (todo.size() > 0) { + var v = todo.removeFirst(); + for (var i = 0; i < v.constraints.size(); i++) { + var c = v.constraints.at(i); + if (!c.isSatisfied()) + unsatisfied.add(c); + } + var determining = v.determinedBy; + for (var i = 0; i < v.constraints.size(); i++) { + var next = v.constraints.at(i); + if (next != determining && next.isSatisfied()) { + next.recalculate(); + todo.add(next.output()); + } + } + } + return unsatisfied; +} + +Planner.prototype.addConstraintsConsumingTo = function (v, coll) { + var determining = v.determinedBy; + var cc = v.constraints; + for (var i = 0; i < cc.size(); i++) { + var c = cc.at(i); + if (c != determining && c.isSatisfied()) + coll.add(c); + } +} + +/* --- * + * P l a n + * --- */ + +/** + * A Plan is an ordered list of constraints to be executed in sequence + * to resatisfy all currently satisfiable constraints in the face of + * one or more changing inputs. + */ +function Plan() { + this.v = new OrderedCollection(); +} + +Plan.prototype.addConstraint = function (c) { + this.v.add(c); +} + +Plan.prototype.size = function () { + return this.v.size(); +} + +Plan.prototype.constraintAt = function (index) { + return this.v.at(index); +} + +Plan.prototype.execute = function () { + for (var i = 0; i < this.size(); i++) { + var c = this.constraintAt(i); + c.execute(); + } +} + +/* --- * + * M a i n + * --- */ + +/** + * This is the standard DeltaBlue benchmark. A long chain of equality + * constraints is constructed with a stay constraint on one end. An + * edit constraint is then added to the opposite end and the time is + * measured for adding and removing this constraint, and extracting + * and executing a constraint satisfaction plan. There are two cases. + * In case 1, the added constraint is stronger than the stay + * constraint and values must propagate down the entire length of the + * chain. In case 2, the added constraint is weaker than the stay + * constraint so it cannot be accomodated. The cost in this case is, + * of course, very low. Typical situations lie somewhere between these + * two extremes. + */ +function chainTest(n) { + planner = new Planner(); + var prev = null, first = null, last = null; + + // Build chain of n equality constraints + for (var i = 0; i <= n; i++) { + var name = "v" + i; + var v = new Variable(name); + if (prev != null) + new EqualityConstraint(prev, v, Strength.REQUIRED); + if (i == 0) first = v; + if (i == n) last = v; + prev = v; + } + + new StayConstraint(last, Strength.STRONG_DEFAULT); + var edit = new EditConstraint(first, Strength.PREFERRED); + var edits = new OrderedCollection(); + edits.add(edit); + var plan = planner.extractPlanFromConstraints(edits); + for (var i = 0; i < 100; i++) { + first.value = i; + plan.execute(); + if (last.value != i) + alert("Chain test failed."); + } +} + +/** + * This test constructs a two sets of variables related to each + * other by a simple linear transformation (scale and offset). The + * time is measured to change a variable on either side of the + * mapping and to change the scale and offset factors. + */ +function projectionTest(n) { + planner = new Planner(); + var scale = new Variable("scale", 10); + var offset = new Variable("offset", 1000); + var src = null, dst = null; + + var dests = new OrderedCollection(); + for (var i = 0; i < n; i++) { + src = new Variable("src" + i, i); + dst = new Variable("dst" + i, i); + dests.add(dst); + new StayConstraint(src, Strength.NORMAL); + new ScaleConstraint(src, scale, offset, dst, Strength.REQUIRED); + } + + change(src, 17); + if (dst.value != 1170) alert("Projection 1 failed"); + change(dst, 1050); + if (src.value != 5) alert("Projection 2 failed"); + change(scale, 5); + for (var i = 0; i < n - 1; i++) { + if (dests.at(i).value != i * 5 + 1000) + alert("Projection 3 failed"); + } + change(offset, 2000); + for (var i = 0; i < n - 1; i++) { + if (dests.at(i).value != i * 5 + 2000) + alert("Projection 4 failed"); + } +} + +function change(v, newValue) { + var edit = new EditConstraint(v, Strength.PREFERRED); + var edits = new OrderedCollection(); + edits.add(edit); + var plan = planner.extractPlanFromConstraints(edits); + for (var i = 0; i < 10; i++) { + v.value = newValue; + plan.execute(); + } + edit.destroyConstraint(); +} + +// Global variable holding the current planner. +var planner = null; + +function deltaBlue() { + chainTest(100); + projectionTest(100); +} diff --git a/node-v0.8.14/deps/v8/benchmarks/earley-boyer.js b/node-v0.8.14/deps/v8/benchmarks/earley-boyer.js new file mode 100644 index 0000000..b2328d6 --- /dev/null +++ b/node-v0.8.14/deps/v8/benchmarks/earley-boyer.js @@ -0,0 +1,4684 @@ +// This file is automatically generated by scheme2js, except for the +// benchmark harness code at the beginning and end of the file. + +var EarleyBoyer = new BenchmarkSuite('EarleyBoyer', 666463, [ + new Benchmark("Earley", function () { BgL_earleyzd2benchmarkzd2(); }), + new Benchmark("Boyer", function () { BgL_nboyerzd2benchmarkzd2(); }) +]); + + +/************* GENERATED FILE - DO NOT EDIT *************/ +/************* GENERATED FILE - DO NOT EDIT *************/ +/************* GENERATED FILE - DO NOT EDIT *************/ +/************* GENERATED FILE - DO NOT EDIT *************/ +/************* GENERATED FILE - DO NOT EDIT *************/ +/************* GENERATED FILE - DO NOT EDIT *************/ +/************* GENERATED FILE - DO NOT EDIT *************/ +/************* GENERATED FILE - DO NOT EDIT *************/ +/* + * To use write/prints/... the default-output port has to be set first. + * Simply setting SC_DEFAULT_OUT and SC_ERROR_OUT to the desired values + * should do the trick. + * In the following example the std-out and error-port are redirected to + * a DIV. +function initRuntime() { + function escapeHTML(s) { + var tmp = s; + tmp = tmp.replace(/&/g, "&"); + tmp = tmp.replace(//g, ">"); + tmp = tmp.replace(/ /g, " "); + tmp = tmp.replace(/\n/g, "
"); + tmp = tmp.replace(/\t/g, "    "); + return tmp; + + } + + document.write("
"); + SC_DEFAULT_OUT = new sc_GenericOutputPort( + function(s) { + var stdout = document.getElementById('stdout'); + stdout.innerHTML = stdout.innerHTML + escapeHTML(s); + }); + SC_ERROR_OUT = SC_DEFAULT_OUT; +} +*/ + + +function sc_print_debug() { + sc_print.apply(null, arguments); +} +/*** META ((export *js*)) */ +var sc_JS_GLOBALS = this; + +var __sc_LINE=-1; +var __sc_FILE=""; + +/*** META ((export #t)) */ +function sc_alert() { + var len = arguments.length; + var s = ""; + var i; + + for( i = 0; i < len; i++ ) { + s += sc_toDisplayString(arguments[ i ]); + } + + return alert( s ); +} + +/*** META ((export #t)) */ +function sc_typeof( x ) { + return typeof x; +} + +/*** META ((export #t)) */ +function sc_error() { + var a = [sc_jsstring2symbol("*error*")]; + for (var i = 0; i < arguments.length; i++) { + a[i+1] = arguments[i]; + } + throw a; +} + +/*** META ((export #t) + (peephole (prefix "throw "))) +*/ +function sc_raise(obj) { + throw obj; +} + +/*** META ((export with-handler-lambda)) */ +function sc_withHandlerLambda(handler, body) { + try { + return body(); + } catch(e) { + if (!e._internalException) + return handler(e); + else + throw e; + } +} + +var sc_properties = new Object(); + +/*** META ((export #t)) */ +function sc_putpropBang(sym, key, val) { + var ht = sc_properties[sym]; + if (!ht) { + ht = new Object(); + sc_properties[sym] = ht; + } + ht[key] = val; +} + +/*** META ((export #t)) */ +function sc_getprop(sym, key) { + var ht = sc_properties[sym]; + if (ht) { + if (key in ht) + return ht[key]; + else + return false; + } else + return false; +} + +/*** META ((export #t)) */ +function sc_rempropBang(sym, key) { + var ht = sc_properties[sym]; + if (ht) + delete ht[key]; +} + +/*** META ((export #t)) */ +function sc_any2String(o) { + return jsstring2string(sc_toDisplayString(o)); +} + +/*** META ((export #t) + (peephole (infix 2 2 "===")) + (type bool)) +*/ +function sc_isEqv(o1, o2) { + return (o1 === o2); +} + +/*** META ((export #t) + (peephole (infix 2 2 "===")) + (type bool)) +*/ +function sc_isEq(o1, o2) { + return (o1 === o2); +} + +/*** META ((export #t) + (type bool)) +*/ +function sc_isNumber(n) { + return (typeof n === "number"); +} + +/*** META ((export #t) + (type bool)) +*/ +function sc_isComplex(n) { + return sc_isNumber(n); +} + +/*** META ((export #t) + (type bool)) +*/ +function sc_isReal(n) { + return sc_isNumber(n); +} + +/*** META ((export #t) + (type bool)) +*/ +function sc_isRational(n) { + return sc_isReal(n); +} + +/*** META ((export #t) + (type bool)) +*/ +function sc_isInteger(n) { + return (parseInt(n) === n); +} + +/*** META ((export #t) + (type bool) + (peephole (postfix ", false"))) +*/ +// we don't have exact numbers... +function sc_isExact(n) { + return false; +} + +/*** META ((export #t) + (peephole (postfix ", true")) + (type bool)) +*/ +function sc_isInexact(n) { + return true; +} + +/*** META ((export = =fx =fl) + (type bool) + (peephole (infix 2 2 "==="))) +*/ +function sc_equal(x) { + for (var i = 1; i < arguments.length; i++) + if (x !== arguments[i]) + return false; + return true; +} + +/*** META ((export < = arguments[i]) + return false; + x = arguments[i]; + } + return true; +} + +/*** META ((export > >fx >fl) + (type bool) + (peephole (infix 2 2 ">"))) +*/ +function sc_greater(x, y) { + for (var i = 1; i < arguments.length; i++) { + if (x <= arguments[i]) + return false; + x = arguments[i]; + } + return true; +} + +/*** META ((export <= <=fx <=fl) + (type bool) + (peephole (infix 2 2 "<="))) +*/ +function sc_lessEqual(x, y) { + for (var i = 1; i < arguments.length; i++) { + if (x > arguments[i]) + return false; + x = arguments[i]; + } + return true; +} + +/*** META ((export >= >=fl >=fx) + (type bool) + (peephole (infix 2 2 ">="))) +*/ +function sc_greaterEqual(x, y) { + for (var i = 1; i < arguments.length; i++) { + if (x < arguments[i]) + return false; + x = arguments[i]; + } + return true; +} + +/*** META ((export #t) + (type bool) + (peephole (postfix "=== 0"))) +*/ +function sc_isZero(x) { + return (x === 0); +} + +/*** META ((export #t) + (type bool) + (peephole (postfix "> 0"))) +*/ +function sc_isPositive(x) { + return (x > 0); +} + +/*** META ((export #t) + (type bool) + (peephole (postfix "< 0"))) +*/ +function sc_isNegative(x) { + return (x < 0); +} + +/*** META ((export #t) + (type bool) + (peephole (postfix "%2===1"))) +*/ +function sc_isOdd(x) { + return (x % 2 === 1); +} + +/*** META ((export #t) + (type bool) + (peephole (postfix "%2===0"))) +*/ +function sc_isEven(x) { + return (x % 2 === 0); +} + +/*** META ((export #t)) */ +var sc_max = Math.max; +/*** META ((export #t)) */ +var sc_min = Math.min; + +/*** META ((export + +fx +fl) + (peephole (infix 0 #f "+" "0"))) +*/ +function sc_plus() { + var sum = 0; + for (var i = 0; i < arguments.length; i++) + sum += arguments[i]; + return sum; +} + +/*** META ((export * *fx *fl) + (peephole (infix 0 #f "*" "1"))) +*/ +function sc_multi() { + var product = 1; + for (var i = 0; i < arguments.length; i++) + product *= arguments[i]; + return product; +} + +/*** META ((export - -fx -fl) + (peephole (minus))) +*/ +function sc_minus(x) { + if (arguments.length === 1) + return -x; + else { + var res = x; + for (var i = 1; i < arguments.length; i++) + res -= arguments[i]; + return res; + } +} + +/*** META ((export / /fl) + (peephole (div))) +*/ +function sc_div(x) { + if (arguments.length === 1) + return 1/x; + else { + var res = x; + for (var i = 1; i < arguments.length; i++) + res /= arguments[i]; + return res; + } +} + +/*** META ((export #t)) */ +var sc_abs = Math.abs; + +/*** META ((export quotient /fx) + (peephole (hole 2 "parseInt(" x "/" y ")"))) +*/ +function sc_quotient(x, y) { + return parseInt(x / y); +} + +/*** META ((export #t) + (peephole (infix 2 2 "%"))) +*/ +function sc_remainder(x, y) { + return x % y; +} + +/*** META ((export #t) + (peephole (modulo))) +*/ +function sc_modulo(x, y) { + var remainder = x % y; + // if they don't have the same sign + if ((remainder * y) < 0) + return remainder + y; + else + return remainder; +} + +function sc_euclid_gcd(a, b) { + var temp; + if (a === 0) return b; + if (b === 0) return a; + if (a < 0) {a = -a;}; + if (b < 0) {b = -b;}; + if (b > a) {temp = a; a = b; b = temp;}; + while (true) { + a %= b; + if(a === 0) {return b;}; + b %= a; + if(b === 0) {return a;}; + }; + return b; +} + +/*** META ((export #t)) */ +function sc_gcd() { + var gcd = 0; + for (var i = 0; i < arguments.length; i++) + gcd = sc_euclid_gcd(gcd, arguments[i]); + return gcd; +} + +/*** META ((export #t)) */ +function sc_lcm() { + var lcm = 1; + for (var i = 0; i < arguments.length; i++) { + var f = Math.round(arguments[i] / sc_euclid_gcd(arguments[i], lcm)); + lcm *= Math.abs(f); + } + return lcm; +} + +// LIMITATION: numerator and denominator don't make sense in floating point world. +//var SC_MAX_DECIMALS = 1000000 +// +// function sc_numerator(x) { +// var rounded = Math.round(x * SC_MAX_DECIMALS); +// return Math.round(rounded / sc_euclid_gcd(rounded, SC_MAX_DECIMALS)); +// } + +// function sc_denominator(x) { +// var rounded = Math.round(x * SC_MAX_DECIMALS); +// return Math.round(SC_MAX_DECIMALS / sc_euclid_gcd(rounded, SC_MAX_DECIMALS)); +// } + +/*** META ((export #t)) */ +var sc_floor = Math.floor; +/*** META ((export #t)) */ +var sc_ceiling = Math.ceil; +/*** META ((export #t)) */ +var sc_truncate = parseInt; +/*** META ((export #t)) */ +var sc_round = Math.round; + +// LIMITATION: sc_rationalize doesn't make sense in a floating point world. + +/*** META ((export #t)) */ +var sc_exp = Math.exp; +/*** META ((export #t)) */ +var sc_log = Math.log; +/*** META ((export #t)) */ +var sc_sin = Math.sin; +/*** META ((export #t)) */ +var sc_cos = Math.cos; +/*** META ((export #t)) */ +var sc_tan = Math.tan; +/*** META ((export #t)) */ +var sc_asin = Math.asin; +/*** META ((export #t)) */ +var sc_acos = Math.acos; +/*** META ((export #t)) */ +var sc_atan = Math.atan; + +/*** META ((export #t)) */ +var sc_sqrt = Math.sqrt; +/*** META ((export #t)) */ +var sc_expt = Math.pow; + +// LIMITATION: we don't have complex numbers. +// LIMITATION: the following functions are hence not implemented. +// LIMITATION: make-rectangular, make-polar, real-part, imag-part, magnitude, angle +// LIMITATION: 2 argument atan + +/*** META ((export #t) + (peephole (id))) +*/ +function sc_exact2inexact(x) { + return x; +} + +/*** META ((export #t) + (peephole (id))) +*/ +function sc_inexact2exact(x) { + return x; +} + +function sc_number2jsstring(x, radix) { + if (radix) + return x.toString(radix); + else + return x.toString(); +} + +function sc_jsstring2number(s, radix) { + if (s === "") return false; + + if (radix) { + var t = parseInt(s, radix); + if (!t && t !== 0) return false; + // verify that each char is in range. (parseInt ignores leading + // white and trailing chars) + var allowedChars = "01234567890abcdefghijklmnopqrstuvwxyz".substring(0, radix+1); + if ((new RegExp("^["+allowedChars+"]*$", "i")).test(s)) + return t; + else return false; + } else { + var t = +s; // does not ignore trailing chars. + if (!t && t !== 0) return false; + // simply verify that first char is not whitespace. + var c = s.charAt(0); + // if +c is 0, but the char is not "0", then we have a whitespace. + if (+c === 0 && c !== "0") return false; + return t; + } +} + +/*** META ((export #t) + (type bool) + (peephole (not))) +*/ +function sc_not(b) { + return b === false; +} + +/*** META ((export #t) + (type bool)) +*/ +function sc_isBoolean(b) { + return (b === true) || (b === false); +} + +function sc_Pair(car, cdr) { + this.car = car; + this.cdr = cdr; +} + +sc_Pair.prototype.toString = function() { + return sc_toDisplayString(this); +}; +sc_Pair.prototype.sc_toWriteOrDisplayString = function(writeOrDisplay) { + var current = this; + + var res = "("; + + while(true) { + res += writeOrDisplay(current.car); + if (sc_isPair(current.cdr)) { + res += " "; + current = current.cdr; + } else if (current.cdr !== null) { + res += " . " + writeOrDisplay(current.cdr); + break; + } else // current.cdr == null + break; + } + + res += ")"; + + return res; +}; +sc_Pair.prototype.sc_toDisplayString = function() { + return this.sc_toWriteOrDisplayString(sc_toDisplayString); +}; +sc_Pair.prototype.sc_toWriteString = function() { + return this.sc_toWriteOrDisplayString(sc_toWriteString); +}; +// sc_Pair.prototype.sc_toWriteCircleString in IO.js + +/*** META ((export #t) + (type bool) + (peephole (postfix " instanceof sc_Pair"))) +*/ +function sc_isPair(p) { + return (p instanceof sc_Pair); +} + +function sc_isPairEqual(p1, p2, comp) { + return (comp(p1.car, p2.car) && comp(p1.cdr, p2.cdr)); +} + +/*** META ((export #t) + (peephole (hole 2 "new sc_Pair(" car ", " cdr ")"))) +*/ +function sc_cons(car, cdr) { + return new sc_Pair(car, cdr); +} + +/*** META ((export cons*)) */ +function sc_consStar() { + var res = arguments[arguments.length - 1]; + for (var i = arguments.length-2; i >= 0; i--) + res = new sc_Pair(arguments[i], res); + return res; +} + +/*** META ((export #t) + (peephole (postfix ".car"))) +*/ +function sc_car(p) { + return p.car; +} + +/*** META ((export #t) + (peephole (postfix ".cdr"))) +*/ +function sc_cdr(p) { + return p.cdr; +} + +/*** META ((export #t) + (peephole (hole 2 p ".car = " val))) +*/ +function sc_setCarBang(p, val) { + p.car = val; +} + +/*** META ((export #t) + (peephole (hole 2 p ".cdr = " val))) +*/ +function sc_setCdrBang(p, val) { + p.cdr = val; +} + +/*** META ((export #t) + (peephole (postfix ".car.car"))) +*/ +function sc_caar(p) { return p.car.car; } +/*** META ((export #t) + (peephole (postfix ".cdr.car"))) +*/ +function sc_cadr(p) { return p.cdr.car; } +/*** META ((export #t) + (peephole (postfix ".car.cdr"))) +*/ +function sc_cdar(p) { return p.car.cdr; } +/*** META ((export #t) + (peephole (postfix ".cdr.cdr"))) +*/ +function sc_cddr(p) { return p.cdr.cdr; } +/*** META ((export #t) + (peephole (postfix ".car.car.car"))) +*/ +function sc_caaar(p) { return p.car.car.car; } +/*** META ((export #t) + (peephole (postfix ".car.cdr.car"))) +*/ +function sc_cadar(p) { return p.car.cdr.car; } +/*** META ((export #t) + (peephole (postfix ".cdr.car.car"))) +*/ +function sc_caadr(p) { return p.cdr.car.car; } +/*** META ((export #t) + (peephole (postfix ".cdr.cdr.car"))) +*/ +function sc_caddr(p) { return p.cdr.cdr.car; } +/*** META ((export #t) + (peephole (postfix ".car.car.cdr"))) +*/ +function sc_cdaar(p) { return p.car.car.cdr; } +/*** META ((export #t) + (peephole (postfix ".cdr.car.cdr"))) +*/ +function sc_cdadr(p) { return p.cdr.car.cdr; } +/*** META ((export #t) + (peephole (postfix ".car.cdr.cdr"))) +*/ +function sc_cddar(p) { return p.car.cdr.cdr; } +/*** META ((export #t) + (peephole (postfix ".cdr.cdr.cdr"))) +*/ +function sc_cdddr(p) { return p.cdr.cdr.cdr; } +/*** META ((export #t) + (peephole (postfix ".car.car.car.car"))) +*/ +function sc_caaaar(p) { return p.car.car.car.car; } +/*** META ((export #t) + (peephole (postfix ".car.cdr.car.car"))) +*/ +function sc_caadar(p) { return p.car.cdr.car.car; } +/*** META ((export #t) + (peephole (postfix ".cdr.car.car.car"))) +*/ +function sc_caaadr(p) { return p.cdr.car.car.car; } +/*** META ((export #t) + (peephole (postfix ".cdr.cdr.car.car"))) +*/ +function sc_caaddr(p) { return p.cdr.cdr.car.car; } +/*** META ((export #t) + (peephole (postfix ".car.car.car.cdr"))) +*/ +function sc_cdaaar(p) { return p.car.car.car.cdr; } +/*** META ((export #t) + (peephole (postfix ".car.cdr.car.cdr"))) +*/ +function sc_cdadar(p) { return p.car.cdr.car.cdr; } +/*** META ((export #t) + (peephole (postfix ".cdr.car.car.cdr"))) +*/ +function sc_cdaadr(p) { return p.cdr.car.car.cdr; } +/*** META ((export #t) + (peephole (postfix ".cdr.cdr.car.cdr"))) +*/ +function sc_cdaddr(p) { return p.cdr.cdr.car.cdr; } +/*** META ((export #t) + (peephole (postfix ".car.car.cdr.car"))) +*/ +function sc_cadaar(p) { return p.car.car.cdr.car; } +/*** META ((export #t) + (peephole (postfix ".car.cdr.cdr.car"))) +*/ +function sc_caddar(p) { return p.car.cdr.cdr.car; } +/*** META ((export #t) + (peephole (postfix ".cdr.car.cdr.car"))) +*/ +function sc_cadadr(p) { return p.cdr.car.cdr.car; } +/*** META ((export #t) + (peephole (postfix ".cdr.cdr.cdr.car"))) +*/ +function sc_cadddr(p) { return p.cdr.cdr.cdr.car; } +/*** META ((export #t) + (peephole (postfix ".car.car.cdr.cdr"))) +*/ +function sc_cddaar(p) { return p.car.car.cdr.cdr; } +/*** META ((export #t) + (peephole (postfix ".car.cdr.cdr.cdr"))) +*/ +function sc_cdddar(p) { return p.car.cdr.cdr.cdr; } +/*** META ((export #t) + (peephole (postfix ".cdr.car.cdr.cdr"))) +*/ +function sc_cddadr(p) { return p.cdr.car.cdr.cdr; } +/*** META ((export #t) + (peephole (postfix ".cdr.cdr.cdr.cdr"))) +*/ +function sc_cddddr(p) { return p.cdr.cdr.cdr.cdr; } + +/*** META ((export #t)) */ +function sc_lastPair(l) { + if (!sc_isPair(l)) sc_error("sc_lastPair: pair expected"); + var res = l; + var cdr = l.cdr; + while (sc_isPair(cdr)) { + res = cdr; + cdr = res.cdr; + } + return res; +} + +/*** META ((export #t) + (type bool) + (peephole (postfix " === null"))) +*/ +function sc_isNull(o) { + return (o === null); +} + +/*** META ((export #t) + (type bool)) +*/ +function sc_isList(o) { + var rabbit; + var turtle; + + var rabbit = o; + var turtle = o; + while (true) { + if (rabbit === null || + (rabbit instanceof sc_Pair && rabbit.cdr === null)) + return true; // end of list + else if ((rabbit instanceof sc_Pair) && + (rabbit.cdr instanceof sc_Pair)) { + rabbit = rabbit.cdr.cdr; + turtle = turtle.cdr; + if (rabbit === turtle) return false; // cycle + } else + return false; // not pair + } +} + +/*** META ((export #t)) */ +function sc_list() { + var res = null; + var a = arguments; + for (var i = a.length-1; i >= 0; i--) + res = new sc_Pair(a[i], res); + return res; +} + +/*** META ((export #t)) */ +function sc_iota(num, init) { + var res = null; + if (!init) init = 0; + for (var i = num - 1; i >= 0; i--) + res = new sc_Pair(i + init, res); + return res; +} + +/*** META ((export #t)) */ +function sc_makeList(nbEls, fill) { + var res = null; + for (var i = 0; i < nbEls; i++) + res = new sc_Pair(fill, res); + return res; +} + +/*** META ((export #t)) */ +function sc_length(l) { + var res = 0; + while (l !== null) { + res++; + l = l.cdr; + } + return res; +} + +/*** META ((export #t)) */ +function sc_remq(o, l) { + var dummy = { cdr : null }; + var tail = dummy; + while (l !== null) { + if (l.car !== o) { + tail.cdr = sc_cons(l.car, null); + tail = tail.cdr; + } + l = l.cdr; + } + return dummy.cdr; +} + +/*** META ((export #t)) */ +function sc_remqBang(o, l) { + var dummy = { cdr : null }; + var tail = dummy; + var needsAssig = true; + while (l !== null) { + if (l.car === o) { + needsAssig = true; + } else { + if (needsAssig) { + tail.cdr = l; + needsAssig = false; + } + tail = l; + } + l = l.cdr; + } + tail.cdr = null; + return dummy.cdr; +} + +/*** META ((export #t)) */ +function sc_delete(o, l) { + var dummy = { cdr : null }; + var tail = dummy; + while (l !== null) { + if (!sc_isEqual(l.car, o)) { + tail.cdr = sc_cons(l.car, null); + tail = tail.cdr; + } + l = l.cdr; + } + return dummy.cdr; +} + +/*** META ((export #t)) */ +function sc_deleteBang(o, l) { + var dummy = { cdr : null }; + var tail = dummy; + var needsAssig = true; + while (l !== null) { + if (sc_isEqual(l.car, o)) { + needsAssig = true; + } else { + if (needsAssig) { + tail.cdr = l; + needsAssig = false; + } + tail = l; + } + l = l.cdr; + } + tail.cdr = null; + return dummy.cdr; +} + +function sc_reverseAppendBang(l1, l2) { + var res = l2; + while (l1 !== null) { + var tmp = res; + res = l1; + l1 = l1.cdr; + res.cdr = tmp; + } + return res; +} + +function sc_dualAppend(l1, l2) { + if (l1 === null) return l2; + if (l2 === null) return l1; + var rev = sc_reverse(l1); + return sc_reverseAppendBang(rev, l2); +} + +/*** META ((export #t)) */ +function sc_append() { + if (arguments.length === 0) + return null; + var res = arguments[arguments.length - 1]; + for (var i = arguments.length - 2; i >= 0; i--) + res = sc_dualAppend(arguments[i], res); + return res; +} + +function sc_dualAppendBang(l1, l2) { + if (l1 === null) return l2; + if (l2 === null) return l1; + var tmp = l1; + while (tmp.cdr !== null) tmp=tmp.cdr; + tmp.cdr = l2; + return l1; +} + +/*** META ((export #t)) */ +function sc_appendBang() { + var res = null; + for (var i = 0; i < arguments.length; i++) + res = sc_dualAppendBang(res, arguments[i]); + return res; +} + +/*** META ((export #t)) */ +function sc_reverse(l1) { + var res = null; + while (l1 !== null) { + res = sc_cons(l1.car, res); + l1 = l1.cdr; + } + return res; +} + +/*** META ((export #t)) */ +function sc_reverseBang(l) { + return sc_reverseAppendBang(l, null); +} + +/*** META ((export #t)) */ +function sc_listTail(l, k) { + var res = l; + for (var i = 0; i < k; i++) { + res = res.cdr; + } + return res; +} + +/*** META ((export #t)) */ +function sc_listRef(l, k) { + return sc_listTail(l, k).car; +} + +/* // unoptimized generic versions +function sc_memX(o, l, comp) { + while (l != null) { + if (comp(l.car, o)) + return l; + l = l.cdr; + } + return false; +} +function sc_memq(o, l) { return sc_memX(o, l, sc_isEq); } +function sc_memv(o, l) { return sc_memX(o, l, sc_isEqv); } +function sc_member(o, l) { return sc_memX(o, l, sc_isEqual); } +*/ + +/* optimized versions */ +/*** META ((export #t)) */ +function sc_memq(o, l) { + while (l !== null) { + if (l.car === o) + return l; + l = l.cdr; + } + return false; +} +/*** META ((export #t)) */ +function sc_memv(o, l) { + while (l !== null) { + if (l.car === o) + return l; + l = l.cdr; + } + return false; +} +/*** META ((export #t)) */ +function sc_member(o, l) { + while (l !== null) { + if (sc_isEqual(l.car,o)) + return l; + l = l.cdr; + } + return false; +} + +/* // generic unoptimized versions +function sc_assX(o, al, comp) { + while (al != null) { + if (comp(al.car.car, o)) + return al.car; + al = al.cdr; + } + return false; +} +function sc_assq(o, al) { return sc_assX(o, al, sc_isEq); } +function sc_assv(o, al) { return sc_assX(o, al, sc_isEqv); } +function sc_assoc(o, al) { return sc_assX(o, al, sc_isEqual); } +*/ +// optimized versions +/*** META ((export #t)) */ +function sc_assq(o, al) { + while (al !== null) { + if (al.car.car === o) + return al.car; + al = al.cdr; + } + return false; +} +/*** META ((export #t)) */ +function sc_assv(o, al) { + while (al !== null) { + if (al.car.car === o) + return al.car; + al = al.cdr; + } + return false; +} +/*** META ((export #t)) */ +function sc_assoc(o, al) { + while (al !== null) { + if (sc_isEqual(al.car.car, o)) + return al.car; + al = al.cdr; + } + return false; +} + +/* can be used for mutable strings and characters */ +function sc_isCharStringEqual(cs1, cs2) { return cs1.val === cs2.val; } +function sc_isCharStringLess(cs1, cs2) { return cs1.val < cs2.val; } +function sc_isCharStringGreater(cs1, cs2) { return cs1.val > cs2.val; } +function sc_isCharStringLessEqual(cs1, cs2) { return cs1.val <= cs2.val; } +function sc_isCharStringGreaterEqual(cs1, cs2) { return cs1.val >= cs2.val; } +function sc_isCharStringCIEqual(cs1, cs2) + { return cs1.val.toLowerCase() === cs2.val.toLowerCase(); } +function sc_isCharStringCILess(cs1, cs2) + { return cs1.val.toLowerCase() < cs2.val.toLowerCase(); } +function sc_isCharStringCIGreater(cs1, cs2) + { return cs1.val.toLowerCase() > cs2.val.toLowerCase(); } +function sc_isCharStringCILessEqual(cs1, cs2) + { return cs1.val.toLowerCase() <= cs2.val.toLowerCase(); } +function sc_isCharStringCIGreaterEqual(cs1, cs2) + { return cs1.val.toLowerCase() >= cs2.val.toLowerCase(); } + + + + +function sc_Char(c) { + var cached = sc_Char.lazy[c]; + if (cached) + return cached; + this.val = c; + sc_Char.lazy[c] = this; + // add return, so FF does not complain. + return undefined; +} +sc_Char.lazy = new Object(); +// thanks to Eric +sc_Char.char2readable = { + "\000": "#\\null", + "\007": "#\\bell", + "\010": "#\\backspace", + "\011": "#\\tab", + "\012": "#\\newline", + "\014": "#\\page", + "\015": "#\\return", + "\033": "#\\escape", + "\040": "#\\space", + "\177": "#\\delete", + + /* poeticless names */ + "\001": "#\\soh", + "\002": "#\\stx", + "\003": "#\\etx", + "\004": "#\\eot", + "\005": "#\\enq", + "\006": "#\\ack", + + "\013": "#\\vt", + "\016": "#\\so", + "\017": "#\\si", + + "\020": "#\\dle", + "\021": "#\\dc1", + "\022": "#\\dc2", + "\023": "#\\dc3", + "\024": "#\\dc4", + "\025": "#\\nak", + "\026": "#\\syn", + "\027": "#\\etb", + + "\030": "#\\can", + "\031": "#\\em", + "\032": "#\\sub", + "\033": "#\\esc", + "\034": "#\\fs", + "\035": "#\\gs", + "\036": "#\\rs", + "\037": "#\\us"}; + +sc_Char.readable2char = { + "null": "\000", + "bell": "\007", + "backspace": "\010", + "tab": "\011", + "newline": "\012", + "page": "\014", + "return": "\015", + "escape": "\033", + "space": "\040", + "delete": "\000", + "soh": "\001", + "stx": "\002", + "etx": "\003", + "eot": "\004", + "enq": "\005", + "ack": "\006", + "bel": "\007", + "bs": "\010", + "ht": "\011", + "nl": "\012", + "vt": "\013", + "np": "\014", + "cr": "\015", + "so": "\016", + "si": "\017", + "dle": "\020", + "dc1": "\021", + "dc2": "\022", + "dc3": "\023", + "dc4": "\024", + "nak": "\025", + "syn": "\026", + "etb": "\027", + "can": "\030", + "em": "\031", + "sub": "\032", + "esc": "\033", + "fs": "\034", + "gs": "\035", + "rs": "\036", + "us": "\037", + "sp": "\040", + "del": "\177"}; + +sc_Char.prototype.toString = function() { + return this.val; +}; +// sc_toDisplayString == toString +sc_Char.prototype.sc_toWriteString = function() { + var entry = sc_Char.char2readable[this.val]; + if (entry) + return entry; + else + return "#\\" + this.val; +}; + +/*** META ((export #t) + (type bool) + (peephole (postfix "instanceof sc_Char"))) +*/ +function sc_isChar(c) { + return (c instanceof sc_Char); +} + +/*** META ((export char=?) + (type bool) + (peephole (hole 2 c1 ".val === " c2 ".val"))) +*/ +var sc_isCharEqual = sc_isCharStringEqual; +/*** META ((export char?) + (type bool) + (peephole (hole 2 c1 ".val > " c2 ".val"))) +*/ +var sc_isCharGreater = sc_isCharStringGreater; +/*** META ((export char<=?) + (type bool) + (peephole (hole 2 c1 ".val <= " c2 ".val"))) +*/ +var sc_isCharLessEqual = sc_isCharStringLessEqual; +/*** META ((export char>=?) + (type bool) + (peephole (hole 2 c1 ".val >= " c2 ".val"))) +*/ +var sc_isCharGreaterEqual = sc_isCharStringGreaterEqual; +/*** META ((export char-ci=?) + (type bool) + (peephole (hole 2 c1 ".val.toLowerCase() === " c2 ".val.toLowerCase()"))) +*/ +var sc_isCharCIEqual = sc_isCharStringCIEqual; +/*** META ((export char-ci?) + (type bool) + (peephole (hole 2 c1 ".val.toLowerCase() > " c2 ".val.toLowerCase()"))) +*/ +var sc_isCharCIGreater = sc_isCharStringCIGreater; +/*** META ((export char-ci<=?) + (type bool) + (peephole (hole 2 c1 ".val.toLowerCase() <= " c2 ".val.toLowerCase()"))) +*/ +var sc_isCharCILessEqual = sc_isCharStringCILessEqual; +/*** META ((export char-ci>=?) + (type bool) + (peephole (hole 2 c1 ".val.toLowerCase() >= " c2 ".val.toLowerCase()"))) +*/ +var sc_isCharCIGreaterEqual = sc_isCharStringCIGreaterEqual; + +var SC_NUMBER_CLASS = "0123456789"; +var SC_WHITESPACE_CLASS = ' \r\n\t\f'; +var SC_LOWER_CLASS = 'abcdefghijklmnopqrstuvwxyz'; +var SC_UPPER_CLASS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'; + +function sc_isCharOfClass(c, cl) { return (cl.indexOf(c) != -1); } +/*** META ((export #t) + (type bool)) +*/ +function sc_isCharAlphabetic(c) + { return sc_isCharOfClass(c.val, SC_LOWER_CLASS) || + sc_isCharOfClass(c.val, SC_UPPER_CLASS); } +/*** META ((export #t) + (type bool) + (peephole (hole 1 "SC_NUMBER_CLASS.indexOf(" c ".val) != -1"))) +*/ +function sc_isCharNumeric(c) + { return sc_isCharOfClass(c.val, SC_NUMBER_CLASS); } +/*** META ((export #t) + (type bool)) +*/ +function sc_isCharWhitespace(c) { + var tmp = c.val; + return tmp === " " || tmp === "\r" || tmp === "\n" || tmp === "\t" || tmp === "\f"; +} +/*** META ((export #t) + (type bool) + (peephole (hole 1 "SC_UPPER_CLASS.indexOf(" c ".val) != -1"))) +*/ +function sc_isCharUpperCase(c) + { return sc_isCharOfClass(c.val, SC_UPPER_CLASS); } +/*** META ((export #t) + (type bool) + (peephole (hole 1 "SC_LOWER_CLASS.indexOf(" c ".val) != -1"))) +*/ +function sc_isCharLowerCase(c) + { return sc_isCharOfClass(c.val, SC_LOWER_CLASS); } + +/*** META ((export #t) + (peephole (postfix ".val.charCodeAt(0)"))) +*/ +function sc_char2integer(c) + { return c.val.charCodeAt(0); } +/*** META ((export #t) + (peephole (hole 1 "new sc_Char(String.fromCharCode(" n "))"))) +*/ +function sc_integer2char(n) + { return new sc_Char(String.fromCharCode(n)); } + +/*** META ((export #t) + (peephole (hole 1 "new sc_Char(" c ".val.toUpperCase())"))) +*/ +function sc_charUpcase(c) + { return new sc_Char(c.val.toUpperCase()); } +/*** META ((export #t) + (peephole (hole 1 "new sc_Char(" c ".val.toLowerCase())"))) +*/ +function sc_charDowncase(c) + { return new sc_Char(c.val.toLowerCase()); } + +function sc_makeJSStringOfLength(k, c) { + var fill; + if (c === undefined) + fill = " "; + else + fill = c; + var res = ""; + var len = 1; + // every round doubles the size of fill. + while (k >= len) { + if (k & len) + res = res.concat(fill); + fill = fill.concat(fill); + len *= 2; + } + return res; +} + +function sc_makejsString(k, c) { + var fill; + if (c) + fill = c.val; + else + fill = " "; + return sc_makeJSStringOfLength(k, fill); +} + +function sc_jsstring2list(s) { + var res = null; + for (var i = s.length - 1; i >= 0; i--) + res = sc_cons(new sc_Char(s.charAt(i)), res); + return res; +} + +function sc_list2jsstring(l) { + var a = new Array(); + while(l !== null) { + a.push(l.car.val); + l = l.cdr; + } + return "".concat.apply("", a); +} + +var sc_Vector = Array; + +sc_Vector.prototype.sc_toWriteOrDisplayString = function(writeOrDisplay) { + if (this.length === 0) return "#()"; + + var res = "#(" + writeOrDisplay(this[0]); + for (var i = 1; i < this.length; i++) + res += " " + writeOrDisplay(this[i]); + res += ")"; + return res; +}; +sc_Vector.prototype.sc_toDisplayString = function() { + return this.sc_toWriteOrDisplayString(sc_toDisplayString); +}; +sc_Vector.prototype.sc_toWriteString = function() { + return this.sc_toWriteOrDisplayString(sc_toWriteString); +}; + +/*** META ((export vector? array?) + (type bool) + (peephole (postfix " instanceof sc_Vector"))) +*/ +function sc_isVector(v) { + return (v instanceof sc_Vector); +} + +// only applies to vectors +function sc_isVectorEqual(v1, v2, comp) { + if (v1.length !== v2.length) return false; + for (var i = 0; i < v1.length; i++) + if (!comp(v1[i], v2[i])) return false; + return true; +} + +/*** META ((export make-vector make-array)) */ +function sc_makeVector(size, fill) { + var a = new sc_Vector(size); + if (fill !== undefined) + sc_vectorFillBang(a, fill); + return a; +} + +/*** META ((export vector array) + (peephole (vector))) +*/ +function sc_vector() { + var a = new sc_Vector(); + for (var i = 0; i < arguments.length; i++) + a.push(arguments[i]); + return a; +} + +/*** META ((export vector-length array-length) + (peephole (postfix ".length"))) +*/ +function sc_vectorLength(v) { + return v.length; +} + +/*** META ((export vector-ref array-ref) + (peephole (hole 2 v "[" pos "]"))) +*/ +function sc_vectorRef(v, pos) { + return v[pos]; +} + +/*** META ((export vector-set! array-set!) + (peephole (hole 3 v "[" pos "] = " val))) +*/ +function sc_vectorSetBang(v, pos, val) { + v[pos] = val; +} + +/*** META ((export vector->list array->list)) */ +function sc_vector2list(a) { + var res = null; + for (var i = a.length-1; i >= 0; i--) + res = sc_cons(a[i], res); + return res; +} + +/*** META ((export list->vector list->array)) */ +function sc_list2vector(l) { + var a = new sc_Vector(); + while(l !== null) { + a.push(l.car); + l = l.cdr; + } + return a; +} + +/*** META ((export vector-fill! array-fill!)) */ +function sc_vectorFillBang(a, fill) { + for (var i = 0; i < a.length; i++) + a[i] = fill; +} + + +/*** META ((export #t)) */ +function sc_copyVector(a, len) { + if (len <= a.length) + return a.slice(0, len); + else { + var tmp = a.concat(); + tmp.length = len; + return tmp; + } +} + +/*** META ((export #t) + (peephole (hole 3 a ".slice(" start "," end ")"))) +*/ +function sc_vectorCopy(a, start, end) { + return a.slice(start, end); +} + +/*** META ((export #t)) */ +function sc_vectorCopyBang(target, tstart, source, sstart, send) { + if (!sstart) sstart = 0; + if (!send) send = source.length; + + // if target == source we don't want to overwrite not yet copied elements. + if (tstart <= sstart) { + for (var i = tstart, j = sstart; j < send; i++, j++) { + target[i] = source[j]; + } + } else { + var diff = send - sstart; + for (var i = tstart + diff - 1, j = send - 1; + j >= sstart; + i--, j--) { + target[i] = source[j]; + } + } + return target; +} + +/*** META ((export #t) + (type bool) + (peephole (hole 1 "typeof " o " === 'function'"))) +*/ +function sc_isProcedure(o) { + return (typeof o === "function"); +} + +/*** META ((export #t)) */ +function sc_apply(proc) { + var args = new Array(); + // first part of arguments are not in list-form. + for (var i = 1; i < arguments.length - 1; i++) + args.push(arguments[i]); + var l = arguments[arguments.length - 1]; + while (l !== null) { + args.push(l.car); + l = l.cdr; + } + return proc.apply(null, args); +} + +/*** META ((export #t)) */ +function sc_map(proc, l1) { + if (l1 === undefined) + return null; + // else + var nbApplyArgs = arguments.length - 1; + var applyArgs = new Array(nbApplyArgs); + var revres = null; + while (l1 !== null) { + for (var i = 0; i < nbApplyArgs; i++) { + applyArgs[i] = arguments[i + 1].car; + arguments[i + 1] = arguments[i + 1].cdr; + } + revres = sc_cons(proc.apply(null, applyArgs), revres); + } + return sc_reverseAppendBang(revres, null); +} + +/*** META ((export #t)) */ +function sc_mapBang(proc, l1) { + if (l1 === undefined) + return null; + // else + var l1_orig = l1; + var nbApplyArgs = arguments.length - 1; + var applyArgs = new Array(nbApplyArgs); + while (l1 !== null) { + var tmp = l1; + for (var i = 0; i < nbApplyArgs; i++) { + applyArgs[i] = arguments[i + 1].car; + arguments[i + 1] = arguments[i + 1].cdr; + } + tmp.car = proc.apply(null, applyArgs); + } + return l1_orig; +} + +/*** META ((export #t)) */ +function sc_forEach(proc, l1) { + if (l1 === undefined) + return undefined; + // else + var nbApplyArgs = arguments.length - 1; + var applyArgs = new Array(nbApplyArgs); + while (l1 !== null) { + for (var i = 0; i < nbApplyArgs; i++) { + applyArgs[i] = arguments[i + 1].car; + arguments[i + 1] = arguments[i + 1].cdr; + } + proc.apply(null, applyArgs); + } + // add return so FF does not complain. + return undefined; +} + +/*** META ((export #t)) */ +function sc_filter(proc, l1) { + var dummy = { cdr : null }; + var tail = dummy; + while (l1 !== null) { + if (proc(l1.car) !== false) { + tail.cdr = sc_cons(l1.car, null); + tail = tail.cdr; + } + l1 = l1.cdr; + } + return dummy.cdr; +} + +/*** META ((export #t)) */ +function sc_filterBang(proc, l1) { + var head = sc_cons("dummy", l1); + var it = head; + var next = l1; + while (next !== null) { + if (proc(next.car) !== false) { + it.cdr = next + it = next; + } + next = next.cdr; + } + it.cdr = null; + return head.cdr; +} + +function sc_filterMap1(proc, l1) { + var revres = null; + while (l1 !== null) { + var tmp = proc(l1.car) + if (tmp !== false) revres = sc_cons(tmp, revres); + l1 = l1.cdr; + } + return sc_reverseAppendBang(revres, null); +} +function sc_filterMap2(proc, l1, l2) { + var revres = null; + while (l1 !== null) { + var tmp = proc(l1.car, l2.car); + if(tmp !== false) revres = sc_cons(tmp, revres); + l1 = l1.cdr; + l2 = l2.cdr + } + return sc_reverseAppendBang(revres, null); +} + +/*** META ((export #t)) */ +function sc_filterMap(proc, l1, l2, l3) { + if (l2 === undefined) + return sc_filterMap1(proc, l1); + else if (l3 === undefined) + return sc_filterMap2(proc, l1, l2); + // else + var nbApplyArgs = arguments.length - 1; + var applyArgs = new Array(nbApplyArgs); + var revres = null; + while (l1 !== null) { + for (var i = 0; i < nbApplyArgs; i++) { + applyArgs[i] = arguments[i + 1].car; + arguments[i + 1] = arguments[i + 1].cdr; + } + var tmp = proc.apply(null, applyArgs); + if(tmp !== false) revres = sc_cons(tmp, revres); + } + return sc_reverseAppendBang(revres, null); +} + +/*** META ((export #t)) */ +function sc_any(proc, l) { + var revres = null; + while (l !== null) { + var tmp = proc(l.car); + if(tmp !== false) return tmp; + l = l.cdr; + } + return false; +} + +/*** META ((export any?) + (peephole (hole 2 "sc_any(" proc "," l ") !== false"))) +*/ +function sc_anyPred(proc, l) { + return sc_any(proc, l)!== false; +} + +/*** META ((export #t)) */ +function sc_every(proc, l) { + var revres = null; + var tmp = true; + while (l !== null) { + tmp = proc(l.car); + if (tmp === false) return false; + l = l.cdr; + } + return tmp; +} + +/*** META ((export every?) + (peephole (hole 2 "sc_every(" proc "," l ") !== false"))) +*/ +function sc_everyPred(proc, l) { + var tmp = sc_every(proc, l); + if (tmp !== false) return true; + return false; +} + +/*** META ((export #t) + (peephole (postfix "()"))) +*/ +function sc_force(o) { + return o(); +} + +/*** META ((export #t)) */ +function sc_makePromise(proc) { + var isResultReady = false; + var result = undefined; + return function() { + if (!isResultReady) { + var tmp = proc(); + if (!isResultReady) { + isResultReady = true; + result = tmp; + } + } + return result; + }; +} + +function sc_Values(values) { + this.values = values; +} + +/*** META ((export #t) + (peephole (values))) +*/ +function sc_values() { + if (arguments.length === 1) + return arguments[0]; + else + return new sc_Values(arguments); +} + +/*** META ((export #t)) */ +function sc_callWithValues(producer, consumer) { + var produced = producer(); + if (produced instanceof sc_Values) + return consumer.apply(null, produced.values); + else + return consumer(produced); +} + +/*** META ((export #t)) */ +function sc_dynamicWind(before, thunk, after) { + before(); + try { + var res = thunk(); + return res; + } finally { + after(); + } +} + + +// TODO: eval/scheme-report-environment/null-environment/interaction-environment + +// LIMITATION: 'load' doesn't exist without files. +// LIMITATION: transcript-on/transcript-off doesn't exist without files. + + +function sc_Struct(name) { + this.name = name; +} +sc_Struct.prototype.sc_toDisplayString = function() { + return "#"; +}; +sc_Struct.prototype.sc_toWriteString = sc_Struct.prototype.sc_toDisplayString; + +/*** META ((export #t) + (peephole (hole 1 "new sc_Struct(" name ")"))) +*/ +function sc_makeStruct(name) { + return new sc_Struct(name); +} + +/*** META ((export #t) + (type bool) + (peephole (postfix " instanceof sc_Struct"))) +*/ +function sc_isStruct(o) { + return (o instanceof sc_Struct); +} + +/*** META ((export #t) + (type bool) + (peephole (hole 2 "(" 1 " instanceof sc_Struct) && ( " 1 ".name === " 0 ")"))) +*/ +function sc_isStructNamed(name, s) { + return ((s instanceof sc_Struct) && (s.name === name)); +} + +/*** META ((export struct-field) + (peephole (hole 3 0 "[" 2 "]"))) +*/ +function sc_getStructField(s, name, field) { + return s[field]; +} + +/*** META ((export struct-field-set!) + (peephole (hole 4 0 "[" 2 "] = " 3))) +*/ +function sc_setStructFieldBang(s, name, field, val) { + s[field] = val; +} + +/*** META ((export #t) + (peephole (prefix "~"))) +*/ +function sc_bitNot(x) { + return ~x; +} + +/*** META ((export #t) + (peephole (infix 2 2 "&"))) +*/ +function sc_bitAnd(x, y) { + return x & y; +} + +/*** META ((export #t) + (peephole (infix 2 2 "|"))) +*/ +function sc_bitOr(x, y) { + return x | y; +} + +/*** META ((export #t) + (peephole (infix 2 2 "^"))) +*/ +function sc_bitXor(x, y) { + return x ^ y; +} + +/*** META ((export #t) + (peephole (infix 2 2 "<<"))) +*/ +function sc_bitLsh(x, y) { + return x << y; +} + +/*** META ((export #t) + (peephole (infix 2 2 ">>"))) +*/ +function sc_bitRsh(x, y) { + return x >> y; +} + +/*** META ((export #t) + (peephole (infix 2 2 ">>>"))) +*/ +function sc_bitUrsh(x, y) { + return x >>> y; +} + +/*** META ((export js-field js-property) + (peephole (hole 2 o "[" field "]"))) +*/ +function sc_jsField(o, field) { + return o[field]; +} + +/*** META ((export js-field-set! js-property-set!) + (peephole (hole 3 o "[" field "] = " val))) +*/ +function sc_setJsFieldBang(o, field, val) { + return o[field] = val; +} + +/*** META ((export js-field-delete! js-property-delete!) + (peephole (hole 2 "delete" o "[" field "]"))) +*/ +function sc_deleteJsFieldBang(o, field) { + delete o[field]; +} + +/*** META ((export #t) + (peephole (jsCall))) +*/ +function sc_jsCall(o, fun) { + var args = new Array(); + for (var i = 2; i < arguments.length; i++) + args[i-2] = arguments[i]; + return fun.apply(o, args); +} + +/*** META ((export #t) + (peephole (jsMethodCall))) +*/ +function sc_jsMethodCall(o, field) { + var args = new Array(); + for (var i = 2; i < arguments.length; i++) + args[i-2] = arguments[i]; + return o[field].apply(o, args); +} + +/*** META ((export new js-new) + (peephole (jsNew))) +*/ +function sc_jsNew(c) { + var evalStr = "new c("; + evalStr +=arguments.length > 1? "arguments[1]": ""; + for (var i = 2; i < arguments.length; i++) + evalStr += ", arguments[" + i + "]"; + evalStr +=")"; + return eval(evalStr); +} + +// ======================== RegExp ==================== +/*** META ((export #t)) */ +function sc_pregexp(re) { + return new RegExp(sc_string2jsstring(re)); +} + +/*** META ((export #t)) */ +function sc_pregexpMatch(re, s) { + var reg = (re instanceof RegExp) ? re : sc_pregexp(re); + var tmp = reg.exec(sc_string2jsstring(s)); + + if (tmp == null) return false; + + var res = null; + for (var i = tmp.length-1; i >= 0; i--) { + if (tmp[i] !== null) { + res = sc_cons(sc_jsstring2string(tmp[i]), res); + } else { + res = sc_cons(false, res); + } + } + return res; +} + +/*** META ((export #t)) */ +function sc_pregexpReplace(re, s1, s2) { + var reg; + var jss1 = sc_string2jsstring(s1); + var jss2 = sc_string2jsstring(s2); + + if (re instanceof RegExp) { + if (re.global) + reg = re; + else + reg = new RegExp(re.source); + } else { + reg = new RegExp(sc_string2jsstring(re)); + } + + return jss1.replace(reg, jss2); +} + +/*** META ((export pregexp-replace*)) */ +function sc_pregexpReplaceAll(re, s1, s2) { + var reg; + var jss1 = sc_string2jsstring(s1); + var jss2 = sc_string2jsstring(s2); + + if (re instanceof RegExp) { + if (re.global) + reg = re; + else + reg = new RegExp(re.source, "g"); + } else { + reg = new RegExp(sc_string2jsstring(re), "g"); + } + + return jss1.replace(reg, jss2); +} + +/*** META ((export #t)) */ +function sc_pregexpSplit(re, s) { + var reg = ((re instanceof RegExp) ? + re : + new RegExp(sc_string2jsstring(re))); + var jss = sc_string2jsstring(s); + var tmp = jss.split(reg); + + if (tmp == null) return false; + + return sc_vector2list(tmp); +} + + +/* =========================================================================== */ +/* Other library stuff */ +/* =========================================================================== */ + +/*** META ((export #t) + (peephole (hole 1 "Math.floor(Math.random()*" 'n ")"))) +*/ +function sc_random(n) { + return Math.floor(Math.random()*n); +} + +/*** META ((export current-date) + (peephole (hole 0 "new Date()"))) +*/ +function sc_currentDate() { + return new Date(); +} + +function sc_Hashtable() { +} +sc_Hashtable.prototype.toString = function() { + return "#{%hashtable}"; +}; +// sc_toWriteString == sc_toDisplayString == toString + +function sc_HashtableElement(key, val) { + this.key = key; + this.val = val; +} + +/*** META ((export #t) + (peephole (hole 0 "new sc_Hashtable()"))) +*/ +function sc_makeHashtable() { + return new sc_Hashtable(); +} + +/*** META ((export #t)) */ +function sc_hashtablePutBang(ht, key, val) { + var hash = sc_hash(key); + ht[hash] = new sc_HashtableElement(key, val); +} + +/*** META ((export #t)) */ +function sc_hashtableGet(ht, key) { + var hash = sc_hash(key); + if (hash in ht) + return ht[hash].val; + else + return false; +} + +/*** META ((export #t)) */ +function sc_hashtableForEach(ht, f) { + for (var v in ht) { + if (ht[v] instanceof sc_HashtableElement) + f(ht[v].key, ht[v].val); + } +} + +/*** META ((export hashtable-contains?) + (peephole (hole 2 "sc_hash(" 1 ") in " 0))) +*/ +function sc_hashtableContains(ht, key) { + var hash = sc_hash(key); + if (hash in ht) + return true; + else + return false; +} + +var SC_HASH_COUNTER = 0; + +function sc_hash(o) { + if (o === null) + return "null"; + else if (o === undefined) + return "undefined"; + else if (o === true) + return "true"; + else if (o === false) + return "false"; + else if (typeof o === "number") + return "num-" + o; + else if (typeof o === "string") + return "jsstr-" + o; + else if (o.sc_getHash) + return o.sc_getHash(); + else + return sc_counterHash.call(o); +} +function sc_counterHash() { + if (!this.sc_hash) { + this.sc_hash = "hash-" + SC_HASH_COUNTER; + SC_HASH_COUNTER++; + } + return this.sc_hash; +} + +function sc_Trampoline(args, maxTailCalls) { + this['__trampoline return__'] = true; + this.args = args; + this.MAX_TAIL_CALLs = maxTailCalls; +} +// TODO: call/cc stuff +sc_Trampoline.prototype.restart = function() { + var o = this; + while (true) { + // set both globals. + SC_TAIL_OBJECT.calls = o.MAX_TAIL_CALLs-1; + var fun = o.args.callee; + var res = fun.apply(SC_TAIL_OBJECT, o.args); + if (res instanceof sc_Trampoline) + o = res; + else + return res; + } +} + +/*** META ((export bind-exit-lambda)) */ +function sc_bindExitLambda(proc) { + var escape_obj = new sc_BindExitException(); + var escape = function(res) { + escape_obj.res = res; + throw escape_obj; + }; + try { + return proc(escape); + } catch(e) { + if (e === escape_obj) { + return e.res; + } + throw e; + } +} +function sc_BindExitException() { + this._internalException = true; +} + +var SC_SCM2JS_GLOBALS = new Object(); + +// default tail-call depth. +// normally the program should set it again. but just in case... +var SC_TAIL_OBJECT = new Object(); +SC_SCM2JS_GLOBALS.TAIL_OBJECT = SC_TAIL_OBJECT; +// ======================== I/O ======================= + +/*------------------------------------------------------------------*/ + +function sc_EOF() { +} +var SC_EOF_OBJECT = new sc_EOF(); + +function sc_Port() { +} + +/* --------------- Input ports -------------------------------------*/ + +function sc_InputPort() { +} +sc_InputPort.prototype = new sc_Port(); + +sc_InputPort.prototype.peekChar = function() { + if (!("peeked" in this)) + this.peeked = this.getNextChar(); + return this.peeked; +} +sc_InputPort.prototype.readChar = function() { + var tmp = this.peekChar(); + delete this.peeked; + return tmp; +} +sc_InputPort.prototype.isCharReady = function() { + return true; +} +sc_InputPort.prototype.close = function() { + // do nothing +} + +/* .............. String port ..........................*/ +function sc_ErrorInputPort() { +}; +sc_ErrorInputPort.prototype = new sc_InputPort(); +sc_ErrorInputPort.prototype.getNextChar = function() { + throw "can't read from error-port."; +}; +sc_ErrorInputPort.prototype.isCharReady = function() { + return false; +}; + + +/* .............. String port ..........................*/ + +function sc_StringInputPort(jsStr) { + // we are going to do some charAts on the str. + // instead of recreating all the time a String-object, we + // create one in the beginning. (not sure, if this is really an optim) + this.str = new String(jsStr); + this.pos = 0; +} +sc_StringInputPort.prototype = new sc_InputPort(); +sc_StringInputPort.prototype.getNextChar = function() { + if (this.pos >= this.str.length) + return SC_EOF_OBJECT; + return this.str.charAt(this.pos++); +}; + +/* ------------- Read and other lib-funs -------------------------------*/ +function sc_Token(type, val, pos) { + this.type = type; + this.val = val; + this.pos = pos; +} +sc_Token.EOF = 0/*EOF*/; +sc_Token.OPEN_PAR = 1/*OPEN_PAR*/; +sc_Token.CLOSE_PAR = 2/*CLOSE_PAR*/; +sc_Token.OPEN_BRACE = 3/*OPEN_BRACE*/; +sc_Token.CLOSE_BRACE = 4/*CLOSE_BRACE*/; +sc_Token.OPEN_BRACKET = 5/*OPEN_BRACKET*/; +sc_Token.CLOSE_BRACKET = 6/*CLOSE_BRACKET*/; +sc_Token.WHITESPACE = 7/*WHITESPACE*/; +sc_Token.QUOTE = 8/*QUOTE*/; +sc_Token.ID = 9/*ID*/; +sc_Token.DOT = 10/*DOT*/; +sc_Token.STRING = 11/*STRING*/; +sc_Token.NUMBER = 12/*NUMBER*/; +sc_Token.ERROR = 13/*ERROR*/; +sc_Token.VECTOR_BEGIN = 14/*VECTOR_BEGIN*/; +sc_Token.TRUE = 15/*TRUE*/; +sc_Token.FALSE = 16/*FALSE*/; +sc_Token.UNSPECIFIED = 17/*UNSPECIFIED*/; +sc_Token.REFERENCE = 18/*REFERENCE*/; +sc_Token.STORE = 19/*STORE*/; +sc_Token.CHAR = 20/*CHAR*/; + +var SC_ID_CLASS = SC_LOWER_CLASS + SC_UPPER_CLASS + "!$%*+-./:<=>?@^_~"; +function sc_Tokenizer(port) { + this.port = port; +} +sc_Tokenizer.prototype.peekToken = function() { + if (this.peeked) + return this.peeked; + var newToken = this.nextToken(); + this.peeked = newToken; + return newToken; +}; +sc_Tokenizer.prototype.readToken = function() { + var tmp = this.peekToken(); + delete this.peeked; + return tmp; +}; +sc_Tokenizer.prototype.nextToken = function() { + var port = this.port; + + function isNumberChar(c) { + return (c >= "0" && c <= "9"); + }; + function isIdOrNumberChar(c) { + return SC_ID_CLASS.indexOf(c) != -1 || // ID-char + (c >= "0" && c <= "9"); + } + function isWhitespace(c) { + return c === " " || c === "\r" || c === "\n" || c === "\t" || c === "\f"; + }; + function isWhitespaceOrEOF(c) { + return isWhitespace(c) || c === SC_EOF_OBJECT; + }; + + function readString() { + res = ""; + while (true) { + var c = port.readChar(); + switch (c) { + case '"': + return new sc_Token(11/*STRING*/, res); + case "\\": + var tmp = port.readChar(); + switch (tmp) { + case '0': res += "\0"; break; + case 'a': res += "\a"; break; + case 'b': res += "\b"; break; + case 'f': res += "\f"; break; + case 'n': res += "\n"; break; + case 'r': res += "\r"; break; + case 't': res += "\t"; break; + case 'v': res += "\v"; break; + case '"': res += '"'; break; + case '\\': res += '\\'; break; + case 'x': + /* hexa-number */ + var nb = 0; + while (true) { + var hexC = port.peekChar(); + if (hexC >= '0' && hexC <= '9') { + port.readChar(); + nb = nb * 16 + hexC.charCodeAt(0) - '0'.charCodeAt(0); + } else if (hexC >= 'a' && hexC <= 'f') { + port.readChar(); + nb = nb * 16 + hexC.charCodeAt(0) - 'a'.charCodeAt(0); + } else if (hexC >= 'A' && hexC <= 'F') { + port.readChar(); + nb = nb * 16 + hexC.charCodeAt(0) - 'A'.charCodeAt(0); + } else { + // next char isn't part of hex. + res += String.fromCharCode(nb); + break; + } + } + break; + default: + if (tmp === SC_EOF_OBJECT) { + return new sc_Token(13/*ERROR*/, "unclosed string-literal" + res); + } + res += tmp; + } + break; + default: + if (c === SC_EOF_OBJECT) { + return new sc_Token(13/*ERROR*/, "unclosed string-literal" + res); + } + res += c; + } + } + }; + function readIdOrNumber(firstChar) { + var res = firstChar; + while (isIdOrNumberChar(port.peekChar())) + res += port.readChar(); + if (isNaN(res)) + return new sc_Token(9/*ID*/, res); + else + return new sc_Token(12/*NUMBER*/, res - 0); + }; + + function skipWhitespaceAndComments() { + var done = false; + while (!done) { + done = true; + while (isWhitespace(port.peekChar())) + port.readChar(); + if (port.peekChar() === ';') { + port.readChar(); + done = false; + while (true) { + curChar = port.readChar(); + if (curChar === SC_EOF_OBJECT || + curChar === '\n') + break; + } + } + } + }; + + function readDot() { + if (isWhitespace(port.peekChar())) + return new sc_Token(10/*DOT*/); + else + return readIdOrNumber("."); + }; + + function readSharp() { + var c = port.readChar(); + if (isWhitespace(c)) + return new sc_Token(13/*ERROR*/, "bad #-pattern0."); + + // reference + if (isNumberChar(c)) { + var nb = c - 0; + while (isNumberChar(port.peekChar())) + nb = nb*10 + (port.readChar() - 0); + switch (port.readChar()) { + case '#': + return new sc_Token(18/*REFERENCE*/, nb); + case '=': + return new sc_Token(19/*STORE*/, nb); + default: + return new sc_Token(13/*ERROR*/, "bad #-pattern1." + nb); + } + } + + if (c === "(") + return new sc_Token(14/*VECTOR_BEGIN*/); + + if (c === "\\") { // character + var tmp = "" + while (!isWhitespaceOrEOF(port.peekChar())) + tmp += port.readChar(); + switch (tmp.length) { + case 0: // it's escaping a whitespace char: + if (sc_isEOFObject(port.peekChar)) + return new sc_Token(13/*ERROR*/, "bad #-pattern2."); + else + return new sc_Token(20/*CHAR*/, port.readChar()); + case 1: + return new sc_Token(20/*CHAR*/, tmp); + default: + var entry = sc_Char.readable2char[tmp.toLowerCase()]; + if (entry) + return new sc_Token(20/*CHAR*/, entry); + else + return new sc_Token(13/*ERROR*/, "unknown character description: #\\" + tmp); + } + } + + // some constants (#t, #f, #unspecified) + var res; + var needing; + switch (c) { + case 't': res = new sc_Token(15/*TRUE*/, true); needing = ""; break; + case 'f': res = new sc_Token(16/*FALSE*/, false); needing = ""; break; + case 'u': res = new sc_Token(17/*UNSPECIFIED*/, undefined); needing = "nspecified"; break; + default: + return new sc_Token(13/*ERROR*/, "bad #-pattern3: " + c); + } + while(true) { + c = port.peekChar(); + if ((isWhitespaceOrEOF(c) || c === ')') && + needing == "") + return res; + else if (isWhitespace(c) || needing == "") + return new sc_Token(13/*ERROR*/, "bad #-pattern4 " + c + " " + needing); + else if (needing.charAt(0) == c) { + port.readChar(); // consume + needing = needing.slice(1); + } else + return new sc_Token(13/*ERROR*/, "bad #-pattern5"); + } + + }; + + skipWhitespaceAndComments(); + var curChar = port.readChar(); + if (curChar === SC_EOF_OBJECT) + return new sc_Token(0/*EOF*/, curChar); + switch (curChar) + { + case " ": + case "\n": + case "\t": + return readWhitespace(); + case "(": + return new sc_Token(1/*OPEN_PAR*/); + case ")": + return new sc_Token(2/*CLOSE_PAR*/); + case "{": + return new sc_Token(3/*OPEN_BRACE*/); + case "}": + return new sc_Token(4/*CLOSE_BRACE*/); + case "[": + return new sc_Token(5/*OPEN_BRACKET*/); + case "]": + return new sc_Token(6/*CLOSE_BRACKET*/); + case "'": + return new sc_Token(8/*QUOTE*/); + case "#": + return readSharp(); + case ".": + return readDot(); + case '"': + return readString(); + default: + if (isIdOrNumberChar(curChar)) + return readIdOrNumber(curChar); + throw "unexpected character: " + curChar; + } +}; + +function sc_Reader(tokenizer) { + this.tokenizer = tokenizer; + this.backref = new Array(); +} +sc_Reader.prototype.read = function() { + function readList(listBeginType) { + function matchesPeer(open, close) { + return open === 1/*OPEN_PAR*/ && close === 2/*CLOSE_PAR*/ + || open === 3/*OPEN_BRACE*/ && close === 4/*CLOSE_BRACE*/ + || open === 5/*OPEN_BRACKET*/ && close === 6/*CLOSE_BRACKET*/; + }; + var res = null; + + while (true) { + var token = tokenizer.peekToken(); + + switch (token.type) { + case 2/*CLOSE_PAR*/: + case 4/*CLOSE_BRACE*/: + case 6/*CLOSE_BRACKET*/: + if (matchesPeer(listBeginType, token.type)) { + tokenizer.readToken(); // consume token + return sc_reverseBang(res); + } else + throw "closing par doesn't match: " + listBeginType + + " " + listEndType; + + case 0/*EOF*/: + throw "unexpected end of file"; + + case 10/*DOT*/: + tokenizer.readToken(); // consume token + var cdr = this.read(); + var par = tokenizer.readToken(); + if (!matchesPeer(listBeginType, par.type)) + throw "closing par doesn't match: " + listBeginType + + " " + par.type; + else + return sc_reverseAppendBang(res, cdr); + + + default: + res = sc_cons(this.read(), res); + } + } + }; + function readQuote() { + return sc_cons("quote", sc_cons(this.read(), null)); + }; + function readVector() { + // opening-parenthesis is already consumed + var a = new Array(); + while (true) { + var token = tokenizer.peekToken(); + switch (token.type) { + case 2/*CLOSE_PAR*/: + tokenizer.readToken(); + return a; + + default: + a.push(this.read()); + } + } + }; + + function storeRefence(nb) { + var tmp = this.read(); + this.backref[nb] = tmp; + return tmp; + }; + + function readReference(nb) { + if (nb in this.backref) + return this.backref[nb]; + else + throw "bad reference: " + nb; + }; + + var tokenizer = this.tokenizer; + + var token = tokenizer.readToken(); + + // handle error + if (token.type === 13/*ERROR*/) + throw token.val; + + switch (token.type) { + case 1/*OPEN_PAR*/: + case 3/*OPEN_BRACE*/: + case 5/*OPEN_BRACKET*/: + return readList.call(this, token.type); + case 8/*QUOTE*/: + return readQuote.call(this); + case 11/*STRING*/: + return sc_jsstring2string(token.val); + case 20/*CHAR*/: + return new sc_Char(token.val); + case 14/*VECTOR_BEGIN*/: + return readVector.call(this); + case 18/*REFERENCE*/: + return readReference.call(this, token.val); + case 19/*STORE*/: + return storeRefence.call(this, token.val); + case 9/*ID*/: + return sc_jsstring2symbol(token.val); + case 0/*EOF*/: + case 12/*NUMBER*/: + case 15/*TRUE*/: + case 16/*FALSE*/: + case 17/*UNSPECIFIED*/: + return token.val; + default: + throw "unexpected token " + token.type + " " + token.val; + } +}; + +/*** META ((export #t)) */ +function sc_read(port) { + if (port === undefined) // we assume the port hasn't been given. + port = SC_DEFAULT_IN; // THREAD: shared var... + var reader = new sc_Reader(new sc_Tokenizer(port)); + return reader.read(); +} +/*** META ((export #t)) */ +function sc_readChar(port) { + if (port === undefined) // we assume the port hasn't been given. + port = SC_DEFAULT_IN; // THREAD: shared var... + var t = port.readChar(); + return t === SC_EOF_OBJECT? t: new sc_Char(t); +} +/*** META ((export #t)) */ +function sc_peekChar(port) { + if (port === undefined) // we assume the port hasn't been given. + port = SC_DEFAULT_IN; // THREAD: shared var... + var t = port.peekChar(); + return t === SC_EOF_OBJECT? t: new sc_Char(t); +} +/*** META ((export #t) + (type bool)) +*/ +function sc_isCharReady(port) { + if (port === undefined) // we assume the port hasn't been given. + port = SC_DEFAULT_IN; // THREAD: shared var... + return port.isCharReady(); +} +/*** META ((export #t) + (peephole (postfix ".close()"))) +*/ +function sc_closeInputPort(p) { + return p.close(); +} + +/*** META ((export #t) + (type bool) + (peephole (postfix " instanceof sc_InputPort"))) +*/ +function sc_isInputPort(o) { + return (o instanceof sc_InputPort); +} + +/*** META ((export eof-object?) + (type bool) + (peephole (postfix " === SC_EOF_OBJECT"))) +*/ +function sc_isEOFObject(o) { + return o === SC_EOF_OBJECT; +} + +/*** META ((export #t) + (peephole (hole 0 "SC_DEFAULT_IN"))) +*/ +function sc_currentInputPort() { + return SC_DEFAULT_IN; +} + +/* ------------ file operations are not supported -----------*/ +/*** META ((export #t)) */ +function sc_callWithInputFile(s, proc) { + throw "can't open " + s; +} + +/*** META ((export #t)) */ +function sc_callWithOutputFile(s, proc) { + throw "can't open " + s; +} + +/*** META ((export #t)) */ +function sc_withInputFromFile(s, thunk) { + throw "can't open " + s; +} + +/*** META ((export #t)) */ +function sc_withOutputToFile(s, thunk) { + throw "can't open " + s; +} + +/*** META ((export #t)) */ +function sc_openInputFile(s) { + throw "can't open " + s; +} + +/*** META ((export #t)) */ +function sc_openOutputFile(s) { + throw "can't open " + s; +} + +/* ----------------------------------------------------------------------------*/ +/*** META ((export #t)) */ +function sc_basename(p) { + var i = p.lastIndexOf('/'); + + if(i >= 0) + return p.substring(i + 1, p.length); + else + return ''; +} + +/*** META ((export #t)) */ +function sc_dirname(p) { + var i = p.lastIndexOf('/'); + + if(i >= 0) + return p.substring(0, i); + else + return ''; +} + +/* ----------------------------------------------------------------------------*/ + +/*** META ((export #t)) */ +function sc_withInputFromPort(p, thunk) { + try { + var tmp = SC_DEFAULT_IN; // THREAD: shared var. + SC_DEFAULT_IN = p; + return thunk(); + } finally { + SC_DEFAULT_IN = tmp; + } +} + +/*** META ((export #t)) */ +function sc_withInputFromString(s, thunk) { + return sc_withInputFromPort(new sc_StringInputPort(sc_string2jsstring(s)), thunk); +} + +/*** META ((export #t)) */ +function sc_withOutputToPort(p, thunk) { + try { + var tmp = SC_DEFAULT_OUT; // THREAD: shared var. + SC_DEFAULT_OUT = p; + return thunk(); + } finally { + SC_DEFAULT_OUT = tmp; + } +} + +/*** META ((export #t)) */ +function sc_withOutputToString(thunk) { + var p = new sc_StringOutputPort(); + sc_withOutputToPort(p, thunk); + return p.close(); +} + +/*** META ((export #t)) */ +function sc_withOutputToProcedure(proc, thunk) { + var t = function(s) { proc(sc_jsstring2string(s)); }; + return sc_withOutputToPort(new sc_GenericOutputPort(t), thunk); +} + +/*** META ((export #t) + (peephole (hole 0 "new sc_StringOutputPort()"))) +*/ +function sc_openOutputString() { + return new sc_StringOutputPort(); +} + +/*** META ((export #t)) */ +function sc_openInputString(str) { + return new sc_StringInputPort(sc_string2jsstring(str)); +} + +/* ----------------------------------------------------------------------------*/ + +function sc_OutputPort() { +} +sc_OutputPort.prototype = new sc_Port(); +sc_OutputPort.prototype.appendJSString = function(obj) { + /* do nothing */ +} +sc_OutputPort.prototype.close = function() { + /* do nothing */ +} + +function sc_StringOutputPort() { + this.res = ""; +} +sc_StringOutputPort.prototype = new sc_OutputPort(); +sc_StringOutputPort.prototype.appendJSString = function(s) { + this.res += s; +} +sc_StringOutputPort.prototype.close = function() { + return sc_jsstring2string(this.res); +} + +/*** META ((export #t)) */ +function sc_getOutputString(sp) { + return sc_jsstring2string(sp.res); +} + + +function sc_ErrorOutputPort() { +} +sc_ErrorOutputPort.prototype = new sc_OutputPort(); +sc_ErrorOutputPort.prototype.appendJSString = function(s) { + throw "don't write on ErrorPort!"; +} +sc_ErrorOutputPort.prototype.close = function() { + /* do nothing */ +} + +function sc_GenericOutputPort(appendJSString, close) { + this.appendJSString = appendJSString; + if (close) + this.close = close; +} +sc_GenericOutputPort.prototype = new sc_OutputPort(); + +/*** META ((export #t) + (type bool) + (peephole (postfix " instanceof sc_OutputPort"))) +*/ +function sc_isOutputPort(o) { + return (o instanceof sc_OutputPort); +} + +/*** META ((export #t) + (peephole (postfix ".close()"))) +*/ +function sc_closeOutputPort(p) { + return p.close(); +} + +/* ------------------ write ---------------------------------------------------*/ + +/*** META ((export #t)) */ +function sc_write(o, p) { + if (p === undefined) // we assume not given + p = SC_DEFAULT_OUT; + p.appendJSString(sc_toWriteString(o)); +} + +function sc_toWriteString(o) { + if (o === null) + return "()"; + else if (o === true) + return "#t"; + else if (o === false) + return "#f"; + else if (o === undefined) + return "#unspecified"; + else if (typeof o === 'function') + return "#"; + else if (o.sc_toWriteString) + return o.sc_toWriteString(); + else + return o.toString(); +} + +function sc_escapeWriteString(s) { + var res = ""; + var j = 0; + for (i = 0; i < s.length; i++) { + switch (s.charAt(i)) { + case "\0": res += s.substring(j, i) + "\\0"; j = i + 1; break; + case "\b": res += s.substring(j, i) + "\\b"; j = i + 1; break; + case "\f": res += s.substring(j, i) + "\\f"; j = i + 1; break; + case "\n": res += s.substring(j, i) + "\\n"; j = i + 1; break; + case "\r": res += s.substring(j, i) + "\\r"; j = i + 1; break; + case "\t": res += s.substring(j, i) + "\\t"; j = i + 1; break; + case "\v": res += s.substring(j, i) + "\\v"; j = i + 1; break; + case '"': res += s.substring(j, i) + '\\"'; j = i + 1; break; + case "\\": res += s.substring(j, i) + "\\\\"; j = i + 1; break; + default: + var c = s.charAt(i); + if ("\a" !== "a" && c == "\a") { + res += s.substring(j, i) + "\\a"; j = i + 1; continue; + } + if ("\v" !== "v" && c == "\v") { + res += s.substring(j, i) + "\\v"; j = i + 1; continue; + } + //if (s.charAt(i) < ' ' || s.charCodeAt(i) > 127) { + // CARE: Manuel is this OK with HOP? + if (s.charAt(i) < ' ') { + /* non printable character and special chars */ + res += s.substring(j, i) + "\\x" + s.charCodeAt(i).toString(16); + j = i + 1; + } + // else just let i increase... + } + } + res += s.substring(j, i); + return res; +} + +/* ------------------ display ---------------------------------------------------*/ + +/*** META ((export #t)) */ +function sc_display(o, p) { + if (p === undefined) // we assume not given + p = SC_DEFAULT_OUT; + p.appendJSString(sc_toDisplayString(o)); +} + +function sc_toDisplayString(o) { + if (o === null) + return "()"; + else if (o === true) + return "#t"; + else if (o === false) + return "#f"; + else if (o === undefined) + return "#unspecified"; + else if (typeof o === 'function') + return "#"; + else if (o.sc_toDisplayString) + return o.sc_toDisplayString(); + else + return o.toString(); +} + +/* ------------------ newline ---------------------------------------------------*/ + +/*** META ((export #t)) */ +function sc_newline(p) { + if (p === undefined) // we assume not given + p = SC_DEFAULT_OUT; + p.appendJSString("\n"); +} + +/* ------------------ write-char ---------------------------------------------------*/ + +/*** META ((export #t)) */ +function sc_writeChar(c, p) { + if (p === undefined) // we assume not given + p = SC_DEFAULT_OUT; + p.appendJSString(c.val); +} + +/* ------------------ write-circle ---------------------------------------------------*/ + +/*** META ((export #t)) */ +function sc_writeCircle(o, p) { + if (p === undefined) // we assume not given + p = SC_DEFAULT_OUT; + p.appendJSString(sc_toWriteCircleString(o)); +} + +function sc_toWriteCircleString(o) { + var symb = sc_gensym("writeCircle"); + var nbPointer = new Object(); + nbPointer.nb = 0; + sc_prepWriteCircle(o, symb, nbPointer); + return sc_genToWriteCircleString(o, symb); +} + +function sc_prepWriteCircle(o, symb, nbPointer) { + // TODO sc_Struct + if (o instanceof sc_Pair || + o instanceof sc_Vector) { + if (o[symb] !== undefined) { + // not the first visit. + o[symb]++; + // unless there is already a number, assign one. + if (!o[symb + "nb"]) o[symb + "nb"] = nbPointer.nb++; + return; + } + o[symb] = 0; + if (o instanceof sc_Pair) { + sc_prepWriteCircle(o.car, symb, nbPointer); + sc_prepWriteCircle(o.cdr, symb, nbPointer); + } else { + for (var i = 0; i < o.length; i++) + sc_prepWriteCircle(o[i], symb, nbPointer); + } + } +} + +function sc_genToWriteCircleString(o, symb) { + if (!(o instanceof sc_Pair || + o instanceof sc_Vector)) + return sc_toWriteString(o); + return o.sc_toWriteCircleString(symb); +} +sc_Pair.prototype.sc_toWriteCircleString = function(symb, inList) { + if (this[symb + "use"]) { // use-flag is set. Just use it. + var nb = this[symb + "nb"]; + if (this[symb]-- === 0) { // if we are the last use. remove all fields. + delete this[symb]; + delete this[symb + "nb"]; + delete this[symb + "use"]; + } + if (inList) + return '. #' + nb + '#'; + else + return '#' + nb + '#'; + } + if (this[symb]-- === 0) { // if we are the last use. remove all fields. + delete this[symb]; + delete this[symb + "nb"]; + delete this[symb + "use"]; + } + + var res = ""; + + if (this[symb] !== undefined) { // implies > 0 + this[symb + "use"] = true; + if (inList) + res += '. #' + this[symb + "nb"] + '='; + else + res += '#' + this[symb + "nb"] + '='; + inList = false; + } + + if (!inList) + res += "("; + + // print car + res += sc_genToWriteCircleString(this.car, symb); + + if (sc_isPair(this.cdr)) { + res += " " + this.cdr.sc_toWriteCircleString(symb, true); + } else if (this.cdr !== null) { + res += " . " + sc_genToWriteCircleString(this.cdr, symb); + } + if (!inList) + res += ")"; + return res; +}; +sc_Vector.prototype.sc_toWriteCircleString = function(symb) { + if (this[symb + "use"]) { // use-flag is set. Just use it. + var nb = this[symb + "nb"]; + if (this[symb]-- === 0) { // if we are the last use. remove all fields. + delete this[symb]; + delete this[symb + "nb"]; + delete this[symb + "use"]; + } + return '#' + nb + '#'; + } + if (this[symb]-- === 0) { // if we are the last use. remove all fields. + delete this[symb]; + delete this[symb + "nb"]; + delete this[symb + "use"]; + } + + var res = ""; + if (this[symb] !== undefined) { // implies > 0 + this[symb + "use"] = true; + res += '#' + this[symb + "nb"] + '='; + } + res += "#("; + for (var i = 0; i < this.length; i++) { + res += sc_genToWriteCircleString(this[i], symb); + if (i < this.length - 1) res += " "; + } + res += ")"; + return res; +}; + + +/* ------------------ print ---------------------------------------------------*/ + +/*** META ((export #t)) */ +function sc_print(s) { + if (arguments.length === 1) { + sc_display(s); + sc_newline(); + } + else { + for (var i = 0; i < arguments.length; i++) + sc_display(arguments[i]); + sc_newline(); + } +} + +/* ------------------ format ---------------------------------------------------*/ +/*** META ((export #t)) */ +function sc_format(s, args) { + var len = s.length; + var p = new sc_StringOutputPort(); + var i = 0, j = 1; + + while( i < len ) { + var i2 = s.indexOf("~", i); + + if (i2 == -1) { + p.appendJSString( s.substring( i, len ) ); + return p.close(); + } else { + if (i2 > i) { + if (i2 == (len - 1)) { + p.appendJSString(s.substring(i, len)); + return p.close(); + } else { + p.appendJSString(s.substring(i, i2)); + i = i2; + } + } + + switch(s.charCodeAt(i2 + 1)) { + case 65: + case 97: + // a + sc_display(arguments[j], p); + i += 2; j++; + break; + + case 83: + case 115: + // s + sc_write(arguments[j], p); + i += 2; j++; + break; + + case 86: + case 118: + // v + sc_display(arguments[j], p); + p.appendJSString("\n"); + i += 2; j++; + break; + + case 67: + case 99: + // c + p.appendJSString(String.fromCharCode(arguments[j])); + i += 2; j++; + break; + + case 88: + case 120: + // x + p.appendJSString(arguments[j].toString(6)); + i += 2; j++; + break; + + case 79: + case 111: + // o + p.appendJSString(arguments[j].toString(8)); + i += 2; j++; + break; + + case 66: + case 98: + // b + p.appendJSString(arguments[j].toString(2)); + i += 2; j++; + break; + + case 37: + case 110: + // %, n + p.appendJSString("\n"); + i += 2; break; + + case 114: + // r + p.appendJSString("\r"); + i += 2; break; + + case 126: + // ~ + p.appendJSString("~"); + i += 2; break; + + default: + sc_error( "format: illegal ~" + + String.fromCharCode(s.charCodeAt(i2 + 1)) + + " sequence" ); + return ""; + } + } + } + + return p.close(); +} + +/* ------------------ global ports ---------------------------------------------------*/ + +var SC_DEFAULT_IN = new sc_ErrorInputPort(); +var SC_DEFAULT_OUT = new sc_ErrorOutputPort(); +var SC_ERROR_OUT = new sc_ErrorOutputPort(); + +var sc_SYMBOL_PREFIX = "\u1E9C"; +var sc_KEYWORD_PREFIX = "\u1E9D"; + +/*** META ((export #t) + (peephole (id))) */ +function sc_jsstring2string(s) { + return s; +} + +/*** META ((export #t) + (peephole (prefix "'\\u1E9C' +"))) +*/ +function sc_jsstring2symbol(s) { + return sc_SYMBOL_PREFIX + s; +} + +/*** META ((export #t) + (peephole (id))) +*/ +function sc_string2jsstring(s) { + return s; +} + +/*** META ((export #t) + (peephole (symbol2jsstring_immutable))) +*/ +function sc_symbol2jsstring(s) { + return s.slice(1); +} + +/*** META ((export #t) + (peephole (postfix ".slice(1)"))) +*/ +function sc_keyword2jsstring(k) { + return k.slice(1); +} + +/*** META ((export #t) + (peephole (prefix "'\\u1E9D' +"))) +*/ +function sc_jsstring2keyword(s) { + return sc_KEYWORD_PREFIX + s; +} + +/*** META ((export #t) + (type bool)) +*/ +function sc_isKeyword(s) { + return (typeof s === "string") && + (s.charAt(0) === sc_KEYWORD_PREFIX); +} + + +/*** META ((export #t)) */ +var sc_gensym = function() { + var counter = 1000; + return function(sym) { + counter++; + if (!sym) sym = sc_SYMBOL_PREFIX; + return sym + "s" + counter + "~" + "^sC-GeNsYm "; + }; +}(); + + +/*** META ((export #t) + (type bool)) +*/ +function sc_isEqual(o1, o2) { + return ((o1 === o2) || + (sc_isPair(o1) && sc_isPair(o2) + && sc_isPairEqual(o1, o2, sc_isEqual)) || + (sc_isVector(o1) && sc_isVector(o2) + && sc_isVectorEqual(o1, o2, sc_isEqual))); +} + +/*** META ((export number->symbol integer->symbol)) */ +function sc_number2symbol(x, radix) { + return sc_SYMBOL_PREFIX + sc_number2jsstring(x, radix); +} + +/*** META ((export number->string integer->string)) */ +var sc_number2string = sc_number2jsstring; + +/*** META ((export #t)) */ +function sc_symbol2number(s, radix) { + return sc_jsstring2number(s.slice(1), radix); +} + +/*** META ((export #t)) */ +var sc_string2number = sc_jsstring2number; + +/*** META ((export #t) + (peephole (prefix "+" s))) + ;; peephole will only apply if no radix is given. +*/ +function sc_string2integer(s, radix) { + if (!radix) return +s; + return parseInt(s, radix); +} + +/*** META ((export #t) + (peephole (prefix "+"))) +*/ +function sc_string2real(s) { + return +s; +} + + +/*** META ((export #t) + (type bool)) +*/ +function sc_isSymbol(s) { + return (typeof s === "string") && + (s.charAt(0) === sc_SYMBOL_PREFIX); +} + +/*** META ((export #t) + (peephole (symbol2string_immutable))) +*/ +function sc_symbol2string(s) { + return s.slice(1); +} + +/*** META ((export #t) + (peephole (prefix "'\\u1E9C' +"))) +*/ +function sc_string2symbol(s) { + return sc_SYMBOL_PREFIX + s; +} + +/*** META ((export symbol-append) + (peephole (symbolAppend_immutable))) +*/ +function sc_symbolAppend() { + var res = sc_SYMBOL_PREFIX; + for (var i = 0; i < arguments.length; i++) + res += arguments[i].slice(1); + return res; +} + +/*** META ((export #t) + (peephole (postfix ".val"))) +*/ +function sc_char2string(c) { return c.val; } + +/*** META ((export #t) + (peephole (hole 1 "'\\u1E9C' + " c ".val"))) +*/ +function sc_char2symbol(c) { return sc_SYMBOL_PREFIX + c.val; } + +/*** META ((export #t) + (type bool)) +*/ +function sc_isString(s) { + return (typeof s === "string") && + (s.charAt(0) !== sc_SYMBOL_PREFIX); +} + +/*** META ((export #t)) */ +var sc_makeString = sc_makejsString; + + +/*** META ((export #t)) */ +function sc_string() { + for (var i = 0; i < arguments.length; i++) + arguments[i] = arguments[i].val; + return "".concat.apply("", arguments); +} + +/*** META ((export #t) + (peephole (postfix ".length"))) +*/ +function sc_stringLength(s) { return s.length; } + +/*** META ((export #t)) */ +function sc_stringRef(s, k) { + return new sc_Char(s.charAt(k)); +} + +/* there's no stringSet in the immutable version +function sc_stringSet(s, k, c) +*/ + + +/*** META ((export string=?) + (type bool) + (peephole (hole 2 str1 " === " str2))) +*/ +function sc_isStringEqual(s1, s2) { + return s1 === s2; +} +/*** META ((export string?) + (type bool) + (peephole (hole 2 str1 " > " str2))) +*/ +function sc_isStringGreater(s1, s2) { + return s1 > s2; +} +/*** META ((export string<=?) + (type bool) + (peephole (hole 2 str1 " <= " str2))) +*/ +function sc_isStringLessEqual(s1, s2) { + return s1 <= s2; +} +/*** META ((export string>=?) + (type bool) + (peephole (hole 2 str1 " >= " str2))) +*/ +function sc_isStringGreaterEqual(s1, s2) { + return s1 >= s2; +} +/*** META ((export string-ci=?) + (type bool) + (peephole (hole 2 str1 ".toLowerCase() === " str2 ".toLowerCase()"))) +*/ +function sc_isStringCIEqual(s1, s2) { + return s1.toLowerCase() === s2.toLowerCase(); +} +/*** META ((export string-ci?) + (type bool) + (peephole (hole 2 str1 ".toLowerCase() > " str2 ".toLowerCase()"))) +*/ +function sc_isStringCIGreater(s1, s2) { + return s1.toLowerCase() > s2.toLowerCase(); +} +/*** META ((export string-ci<=?) + (type bool) + (peephole (hole 2 str1 ".toLowerCase() <= " str2 ".toLowerCase()"))) +*/ +function sc_isStringCILessEqual(s1, s2) { + return s1.toLowerCase() <= s2.toLowerCase(); +} +/*** META ((export string-ci>=?) + (type bool) + (peephole (hole 2 str1 ".toLowerCase() >= " str2 ".toLowerCase()"))) +*/ +function sc_isStringCIGreaterEqual(s1, s2) { + return s1.toLowerCase() >= s2.toLowerCase(); +} + +/*** META ((export #t) + (peephole (hole 3 s ".substring(" start ", " end ")"))) +*/ +function sc_substring(s, start, end) { + return s.substring(start, end); +} + +/*** META ((export #t)) +*/ +function sc_isSubstring_at(s1, s2, i) { + return s2 == s1.substring(i, i+ s2.length); +} + +/*** META ((export #t) + (peephole (infix 0 #f "+" "''"))) +*/ +function sc_stringAppend() { + return "".concat.apply("", arguments); +} + +/*** META ((export #t)) */ +var sc_string2list = sc_jsstring2list; + +/*** META ((export #t)) */ +var sc_list2string = sc_list2jsstring; + +/*** META ((export #t) + (peephole (id))) +*/ +function sc_stringCopy(s) { + return s; +} + +/* there's no string-fill in the immutable version +function sc_stringFill(s, c) +*/ + +/*** META ((export #t) + (peephole (postfix ".slice(1)"))) +*/ +function sc_keyword2string(o) { + return o.slice(1); +} + +/*** META ((export #t) + (peephole (prefix "'\\u1E9D' +"))) +*/ +function sc_string2keyword(o) { + return sc_KEYWORD_PREFIX + o; +} + +String.prototype.sc_toDisplayString = function() { + if (this.charAt(0) === sc_SYMBOL_PREFIX) + // TODO: care for symbols with spaces (escape-chars symbols). + return this.slice(1); + else if (this.charAt(0) === sc_KEYWORD_PREFIX) + return ":" + this.slice(1); + else + return this.toString(); +}; + +String.prototype.sc_toWriteString = function() { + if (this.charAt(0) === sc_SYMBOL_PREFIX) + // TODO: care for symbols with spaces (escape-chars symbols). + return this.slice(1); + else if (this.charAt(0) === sc_KEYWORD_PREFIX) + return ":" + this.slice(1); + else + return '"' + sc_escapeWriteString(this) + '"'; +}; +/* Exported Variables */ +var BgL_testzd2boyerzd2; +var BgL_nboyerzd2benchmarkzd2; +var BgL_setupzd2boyerzd2; +/* End Exports */ + +var translate_term_nboyer; +var translate_args_nboyer; +var untranslate_term_nboyer; +var BgL_sc_symbolzd2ze3symbolzd2record_1ze3_nboyer; +var BgL_sc_za2symbolzd2recordszd2alistza2_2z00_nboyer; +var translate_alist_nboyer; +var apply_subst_nboyer; +var apply_subst_lst_nboyer; +var tautologyp_nboyer; +var if_constructor_nboyer; +var rewrite_count_nboyer; +var rewrite_nboyer; +var rewrite_args_nboyer; +var unify_subst_nboyer; +var one_way_unify1_nboyer; +var false_term_nboyer; +var true_term_nboyer; +var trans_of_implies1_nboyer; +var is_term_equal_nboyer; +var is_term_member_nboyer; +var const_nboyer; +var sc_const_3_nboyer; +var sc_const_4_nboyer; +{ + (sc_const_4_nboyer = (new sc_Pair("\u1E9Cimplies",(new sc_Pair((new sc_Pair("\u1E9Cand",(new sc_Pair((new sc_Pair("\u1E9Cimplies",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Cy",null)))))),(new sc_Pair((new sc_Pair("\u1E9Cand",(new sc_Pair((new sc_Pair("\u1E9Cimplies",(new sc_Pair("\u1E9Cy",(new sc_Pair("\u1E9Cz",null)))))),(new sc_Pair((new sc_Pair("\u1E9Cand",(new sc_Pair((new sc_Pair("\u1E9Cimplies",(new sc_Pair("\u1E9Cz",(new sc_Pair("\u1E9Cu",null)))))),(new sc_Pair((new sc_Pair("\u1E9Cimplies",(new sc_Pair("\u1E9Cu",(new sc_Pair("\u1E9Cw",null)))))),null)))))),null)))))),null)))))),(new sc_Pair((new sc_Pair("\u1E9Cimplies",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Cw",null)))))),null))))))); + (sc_const_3_nboyer = sc_list((new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Ccompile",(new sc_Pair("\u1E9Cform",null)))),(new sc_Pair((new sc_Pair("\u1E9Creverse",(new sc_Pair((new sc_Pair("\u1E9Ccodegen",(new sc_Pair((new sc_Pair("\u1E9Coptimize",(new sc_Pair("\u1E9Cform",null)))),(new sc_Pair((new sc_Pair("\u1E9Cnil",null)),null)))))),null)))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Ceqp",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Cy",null)))))),(new sc_Pair((new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cfix",(new sc_Pair("\u1E9Cx",null)))),(new sc_Pair((new sc_Pair("\u1E9Cfix",(new sc_Pair("\u1E9Cy",null)))),null)))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cgreaterp",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Cy",null)))))),(new sc_Pair((new sc_Pair("\u1E9Clessp",(new sc_Pair("\u1E9Cy",(new sc_Pair("\u1E9Cx",null)))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Clesseqp",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Cy",null)))))),(new sc_Pair((new sc_Pair("\u1E9Cnot",(new sc_Pair((new sc_Pair("\u1E9Clessp",(new sc_Pair("\u1E9Cy",(new sc_Pair("\u1E9Cx",null)))))),null)))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cgreatereqp",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Cy",null)))))),(new sc_Pair((new sc_Pair("\u1E9Cnot",(new sc_Pair((new sc_Pair("\u1E9Clessp",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Cy",null)))))),null)))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cboolean",(new sc_Pair("\u1E9Cx",null)))),(new sc_Pair((new sc_Pair("\u1E9Cor",(new sc_Pair((new sc_Pair("\u1E9Cequal",(new sc_Pair("\u1E9Cx",(new sc_Pair((new sc_Pair("\u1E9Ct",null)),null)))))),(new sc_Pair((new sc_Pair("\u1E9Cequal",(new sc_Pair("\u1E9Cx",(new sc_Pair((new sc_Pair("\u1E9Cf",null)),null)))))),null)))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Ciff",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Cy",null)))))),(new sc_Pair((new sc_Pair("\u1E9Cand",(new sc_Pair((new sc_Pair("\u1E9Cimplies",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Cy",null)))))),(new sc_Pair((new sc_Pair("\u1E9Cimplies",(new sc_Pair("\u1E9Cy",(new sc_Pair("\u1E9Cx",null)))))),null)))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Ceven1",(new sc_Pair("\u1E9Cx",null)))),(new sc_Pair((new sc_Pair("\u1E9Cif",(new sc_Pair((new sc_Pair("\u1E9Czerop",(new sc_Pair("\u1E9Cx",null)))),(new sc_Pair((new sc_Pair("\u1E9Ct",null)),(new sc_Pair((new sc_Pair("\u1E9Codd",(new sc_Pair((new sc_Pair("\u1E9Csub1",(new sc_Pair("\u1E9Cx",null)))),null)))),null)))))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Ccountps-",(new sc_Pair("\u1E9Cl",(new sc_Pair("\u1E9Cpred",null)))))),(new sc_Pair((new sc_Pair("\u1E9Ccountps-loop",(new sc_Pair("\u1E9Cl",(new sc_Pair("\u1E9Cpred",(new sc_Pair((new sc_Pair("\u1E9Czero",null)),null)))))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cfact-",(new sc_Pair("\u1E9Ci",null)))),(new sc_Pair((new sc_Pair("\u1E9Cfact-loop",(new sc_Pair("\u1E9Ci",(new sc_Pair((1),null)))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Creverse-",(new sc_Pair("\u1E9Cx",null)))),(new sc_Pair((new sc_Pair("\u1E9Creverse-loop",(new sc_Pair("\u1E9Cx",(new sc_Pair((new sc_Pair("\u1E9Cnil",null)),null)))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cdivides",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Cy",null)))))),(new sc_Pair((new sc_Pair("\u1E9Czerop",(new sc_Pair((new sc_Pair("\u1E9Cremainder",(new sc_Pair("\u1E9Cy",(new sc_Pair("\u1E9Cx",null)))))),null)))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cassume-true",(new sc_Pair("\u1E9Cvar",(new sc_Pair("\u1E9Calist",null)))))),(new sc_Pair((new sc_Pair("\u1E9Ccons",(new sc_Pair((new sc_Pair("\u1E9Ccons",(new sc_Pair("\u1E9Cvar",(new sc_Pair((new sc_Pair("\u1E9Ct",null)),null)))))),(new sc_Pair("\u1E9Calist",null)))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cassume-false",(new sc_Pair("\u1E9Cvar",(new sc_Pair("\u1E9Calist",null)))))),(new sc_Pair((new sc_Pair("\u1E9Ccons",(new sc_Pair((new sc_Pair("\u1E9Ccons",(new sc_Pair("\u1E9Cvar",(new sc_Pair((new sc_Pair("\u1E9Cf",null)),null)))))),(new sc_Pair("\u1E9Calist",null)))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Ctautology-checker",(new sc_Pair("\u1E9Cx",null)))),(new sc_Pair((new sc_Pair("\u1E9Ctautologyp",(new sc_Pair((new sc_Pair("\u1E9Cnormalize",(new sc_Pair("\u1E9Cx",null)))),(new sc_Pair((new sc_Pair("\u1E9Cnil",null)),null)))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cfalsify",(new sc_Pair("\u1E9Cx",null)))),(new sc_Pair((new sc_Pair("\u1E9Cfalsify1",(new sc_Pair((new sc_Pair("\u1E9Cnormalize",(new sc_Pair("\u1E9Cx",null)))),(new sc_Pair((new sc_Pair("\u1E9Cnil",null)),null)))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cprime",(new sc_Pair("\u1E9Cx",null)))),(new sc_Pair((new sc_Pair("\u1E9Cand",(new sc_Pair((new sc_Pair("\u1E9Cnot",(new sc_Pair((new sc_Pair("\u1E9Czerop",(new sc_Pair("\u1E9Cx",null)))),null)))),(new sc_Pair((new sc_Pair("\u1E9Cnot",(new sc_Pair((new sc_Pair("\u1E9Cequal",(new sc_Pair("\u1E9Cx",(new sc_Pair((new sc_Pair("\u1E9Cadd1",(new sc_Pair((new sc_Pair("\u1E9Czero",null)),null)))),null)))))),null)))),(new sc_Pair((new sc_Pair("\u1E9Cprime1",(new sc_Pair("\u1E9Cx",(new sc_Pair((new sc_Pair("\u1E9Csub1",(new sc_Pair("\u1E9Cx",null)))),null)))))),null)))))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cand",(new sc_Pair("\u1E9Cp",(new sc_Pair("\u1E9Cq",null)))))),(new sc_Pair((new sc_Pair("\u1E9Cif",(new sc_Pair("\u1E9Cp",(new sc_Pair((new sc_Pair("\u1E9Cif",(new sc_Pair("\u1E9Cq",(new sc_Pair((new sc_Pair("\u1E9Ct",null)),(new sc_Pair((new sc_Pair("\u1E9Cf",null)),null)))))))),(new sc_Pair((new sc_Pair("\u1E9Cf",null)),null)))))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cor",(new sc_Pair("\u1E9Cp",(new sc_Pair("\u1E9Cq",null)))))),(new sc_Pair((new sc_Pair("\u1E9Cif",(new sc_Pair("\u1E9Cp",(new sc_Pair((new sc_Pair("\u1E9Ct",null)),(new sc_Pair((new sc_Pair("\u1E9Cif",(new sc_Pair("\u1E9Cq",(new sc_Pair((new sc_Pair("\u1E9Ct",null)),(new sc_Pair((new sc_Pair("\u1E9Cf",null)),null)))))))),null)))))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cnot",(new sc_Pair("\u1E9Cp",null)))),(new sc_Pair((new sc_Pair("\u1E9Cif",(new sc_Pair("\u1E9Cp",(new sc_Pair((new sc_Pair("\u1E9Cf",null)),(new sc_Pair((new sc_Pair("\u1E9Ct",null)),null)))))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cimplies",(new sc_Pair("\u1E9Cp",(new sc_Pair("\u1E9Cq",null)))))),(new sc_Pair((new sc_Pair("\u1E9Cif",(new sc_Pair("\u1E9Cp",(new sc_Pair((new sc_Pair("\u1E9Cif",(new sc_Pair("\u1E9Cq",(new sc_Pair((new sc_Pair("\u1E9Ct",null)),(new sc_Pair((new sc_Pair("\u1E9Cf",null)),null)))))))),(new sc_Pair((new sc_Pair("\u1E9Ct",null)),null)))))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cfix",(new sc_Pair("\u1E9Cx",null)))),(new sc_Pair((new sc_Pair("\u1E9Cif",(new sc_Pair((new sc_Pair("\u1E9Cnumberp",(new sc_Pair("\u1E9Cx",null)))),(new sc_Pair("\u1E9Cx",(new sc_Pair((new sc_Pair("\u1E9Czero",null)),null)))))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cif",(new sc_Pair((new sc_Pair("\u1E9Cif",(new sc_Pair("\u1E9Ca",(new sc_Pair("\u1E9Cb",(new sc_Pair("\u1E9Cc",null)))))))),(new sc_Pair("\u1E9Cd",(new sc_Pair("\u1E9Ce",null)))))))),(new sc_Pair((new sc_Pair("\u1E9Cif",(new sc_Pair("\u1E9Ca",(new sc_Pair((new sc_Pair("\u1E9Cif",(new sc_Pair("\u1E9Cb",(new sc_Pair("\u1E9Cd",(new sc_Pair("\u1E9Ce",null)))))))),(new sc_Pair((new sc_Pair("\u1E9Cif",(new sc_Pair("\u1E9Cc",(new sc_Pair("\u1E9Cd",(new sc_Pair("\u1E9Ce",null)))))))),null)))))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Czerop",(new sc_Pair("\u1E9Cx",null)))),(new sc_Pair((new sc_Pair("\u1E9Cor",(new sc_Pair((new sc_Pair("\u1E9Cequal",(new sc_Pair("\u1E9Cx",(new sc_Pair((new sc_Pair("\u1E9Czero",null)),null)))))),(new sc_Pair((new sc_Pair("\u1E9Cnot",(new sc_Pair((new sc_Pair("\u1E9Cnumberp",(new sc_Pair("\u1E9Cx",null)))),null)))),null)))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cplus",(new sc_Pair((new sc_Pair("\u1E9Cplus",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Cy",null)))))),(new sc_Pair("\u1E9Cz",null)))))),(new sc_Pair((new sc_Pair("\u1E9Cplus",(new sc_Pair("\u1E9Cx",(new sc_Pair((new sc_Pair("\u1E9Cplus",(new sc_Pair("\u1E9Cy",(new sc_Pair("\u1E9Cz",null)))))),null)))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cplus",(new sc_Pair("\u1E9Ca",(new sc_Pair("\u1E9Cb",null)))))),(new sc_Pair((new sc_Pair("\u1E9Czero",null)),null)))))),(new sc_Pair((new sc_Pair("\u1E9Cand",(new sc_Pair((new sc_Pair("\u1E9Czerop",(new sc_Pair("\u1E9Ca",null)))),(new sc_Pair((new sc_Pair("\u1E9Czerop",(new sc_Pair("\u1E9Cb",null)))),null)))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cdifference",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Cx",null)))))),(new sc_Pair((new sc_Pair("\u1E9Czero",null)),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cplus",(new sc_Pair("\u1E9Ca",(new sc_Pair("\u1E9Cb",null)))))),(new sc_Pair((new sc_Pair("\u1E9Cplus",(new sc_Pair("\u1E9Ca",(new sc_Pair("\u1E9Cc",null)))))),null)))))),(new sc_Pair((new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cfix",(new sc_Pair("\u1E9Cb",null)))),(new sc_Pair((new sc_Pair("\u1E9Cfix",(new sc_Pair("\u1E9Cc",null)))),null)))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Czero",null)),(new sc_Pair((new sc_Pair("\u1E9Cdifference",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Cy",null)))))),null)))))),(new sc_Pair((new sc_Pair("\u1E9Cnot",(new sc_Pair((new sc_Pair("\u1E9Clessp",(new sc_Pair("\u1E9Cy",(new sc_Pair("\u1E9Cx",null)))))),null)))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cequal",(new sc_Pair("\u1E9Cx",(new sc_Pair((new sc_Pair("\u1E9Cdifference",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Cy",null)))))),null)))))),(new sc_Pair((new sc_Pair("\u1E9Cand",(new sc_Pair((new sc_Pair("\u1E9Cnumberp",(new sc_Pair("\u1E9Cx",null)))),(new sc_Pair((new sc_Pair("\u1E9Cor",(new sc_Pair((new sc_Pair("\u1E9Cequal",(new sc_Pair("\u1E9Cx",(new sc_Pair((new sc_Pair("\u1E9Czero",null)),null)))))),(new sc_Pair((new sc_Pair("\u1E9Czerop",(new sc_Pair("\u1E9Cy",null)))),null)))))),null)))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cmeaning",(new sc_Pair((new sc_Pair("\u1E9Cplus-tree",(new sc_Pair((new sc_Pair("\u1E9Cappend",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Cy",null)))))),null)))),(new sc_Pair("\u1E9Ca",null)))))),(new sc_Pair((new sc_Pair("\u1E9Cplus",(new sc_Pair((new sc_Pair("\u1E9Cmeaning",(new sc_Pair((new sc_Pair("\u1E9Cplus-tree",(new sc_Pair("\u1E9Cx",null)))),(new sc_Pair("\u1E9Ca",null)))))),(new sc_Pair((new sc_Pair("\u1E9Cmeaning",(new sc_Pair((new sc_Pair("\u1E9Cplus-tree",(new sc_Pair("\u1E9Cy",null)))),(new sc_Pair("\u1E9Ca",null)))))),null)))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cmeaning",(new sc_Pair((new sc_Pair("\u1E9Cplus-tree",(new sc_Pair((new sc_Pair("\u1E9Cplus-fringe",(new sc_Pair("\u1E9Cx",null)))),null)))),(new sc_Pair("\u1E9Ca",null)))))),(new sc_Pair((new sc_Pair("\u1E9Cfix",(new sc_Pair((new sc_Pair("\u1E9Cmeaning",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Ca",null)))))),null)))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cappend",(new sc_Pair((new sc_Pair("\u1E9Cappend",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Cy",null)))))),(new sc_Pair("\u1E9Cz",null)))))),(new sc_Pair((new sc_Pair("\u1E9Cappend",(new sc_Pair("\u1E9Cx",(new sc_Pair((new sc_Pair("\u1E9Cappend",(new sc_Pair("\u1E9Cy",(new sc_Pair("\u1E9Cz",null)))))),null)))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Creverse",(new sc_Pair((new sc_Pair("\u1E9Cappend",(new sc_Pair("\u1E9Ca",(new sc_Pair("\u1E9Cb",null)))))),null)))),(new sc_Pair((new sc_Pair("\u1E9Cappend",(new sc_Pair((new sc_Pair("\u1E9Creverse",(new sc_Pair("\u1E9Cb",null)))),(new sc_Pair((new sc_Pair("\u1E9Creverse",(new sc_Pair("\u1E9Ca",null)))),null)))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Ctimes",(new sc_Pair("\u1E9Cx",(new sc_Pair((new sc_Pair("\u1E9Cplus",(new sc_Pair("\u1E9Cy",(new sc_Pair("\u1E9Cz",null)))))),null)))))),(new sc_Pair((new sc_Pair("\u1E9Cplus",(new sc_Pair((new sc_Pair("\u1E9Ctimes",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Cy",null)))))),(new sc_Pair((new sc_Pair("\u1E9Ctimes",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Cz",null)))))),null)))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Ctimes",(new sc_Pair((new sc_Pair("\u1E9Ctimes",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Cy",null)))))),(new sc_Pair("\u1E9Cz",null)))))),(new sc_Pair((new sc_Pair("\u1E9Ctimes",(new sc_Pair("\u1E9Cx",(new sc_Pair((new sc_Pair("\u1E9Ctimes",(new sc_Pair("\u1E9Cy",(new sc_Pair("\u1E9Cz",null)))))),null)))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Ctimes",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Cy",null)))))),(new sc_Pair((new sc_Pair("\u1E9Czero",null)),null)))))),(new sc_Pair((new sc_Pair("\u1E9Cor",(new sc_Pair((new sc_Pair("\u1E9Czerop",(new sc_Pair("\u1E9Cx",null)))),(new sc_Pair((new sc_Pair("\u1E9Czerop",(new sc_Pair("\u1E9Cy",null)))),null)))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cexec",(new sc_Pair((new sc_Pair("\u1E9Cappend",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Cy",null)))))),(new sc_Pair("\u1E9Cpds",(new sc_Pair("\u1E9Cenvrn",null)))))))),(new sc_Pair((new sc_Pair("\u1E9Cexec",(new sc_Pair("\u1E9Cy",(new sc_Pair((new sc_Pair("\u1E9Cexec",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Cpds",(new sc_Pair("\u1E9Cenvrn",null)))))))),(new sc_Pair("\u1E9Cenvrn",null)))))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cmc-flatten",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Cy",null)))))),(new sc_Pair((new sc_Pair("\u1E9Cappend",(new sc_Pair((new sc_Pair("\u1E9Cflatten",(new sc_Pair("\u1E9Cx",null)))),(new sc_Pair("\u1E9Cy",null)))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cmember",(new sc_Pair("\u1E9Cx",(new sc_Pair((new sc_Pair("\u1E9Cappend",(new sc_Pair("\u1E9Ca",(new sc_Pair("\u1E9Cb",null)))))),null)))))),(new sc_Pair((new sc_Pair("\u1E9Cor",(new sc_Pair((new sc_Pair("\u1E9Cmember",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Ca",null)))))),(new sc_Pair((new sc_Pair("\u1E9Cmember",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Cb",null)))))),null)))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cmember",(new sc_Pair("\u1E9Cx",(new sc_Pair((new sc_Pair("\u1E9Creverse",(new sc_Pair("\u1E9Cy",null)))),null)))))),(new sc_Pair((new sc_Pair("\u1E9Cmember",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Cy",null)))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Clength",(new sc_Pair((new sc_Pair("\u1E9Creverse",(new sc_Pair("\u1E9Cx",null)))),null)))),(new sc_Pair((new sc_Pair("\u1E9Clength",(new sc_Pair("\u1E9Cx",null)))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cmember",(new sc_Pair("\u1E9Ca",(new sc_Pair((new sc_Pair("\u1E9Cintersect",(new sc_Pair("\u1E9Cb",(new sc_Pair("\u1E9Cc",null)))))),null)))))),(new sc_Pair((new sc_Pair("\u1E9Cand",(new sc_Pair((new sc_Pair("\u1E9Cmember",(new sc_Pair("\u1E9Ca",(new sc_Pair("\u1E9Cb",null)))))),(new sc_Pair((new sc_Pair("\u1E9Cmember",(new sc_Pair("\u1E9Ca",(new sc_Pair("\u1E9Cc",null)))))),null)))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cnth",(new sc_Pair((new sc_Pair("\u1E9Czero",null)),(new sc_Pair("\u1E9Ci",null)))))),(new sc_Pair((new sc_Pair("\u1E9Czero",null)),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cexp",(new sc_Pair("\u1E9Ci",(new sc_Pair((new sc_Pair("\u1E9Cplus",(new sc_Pair("\u1E9Cj",(new sc_Pair("\u1E9Ck",null)))))),null)))))),(new sc_Pair((new sc_Pair("\u1E9Ctimes",(new sc_Pair((new sc_Pair("\u1E9Cexp",(new sc_Pair("\u1E9Ci",(new sc_Pair("\u1E9Cj",null)))))),(new sc_Pair((new sc_Pair("\u1E9Cexp",(new sc_Pair("\u1E9Ci",(new sc_Pair("\u1E9Ck",null)))))),null)))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cexp",(new sc_Pair("\u1E9Ci",(new sc_Pair((new sc_Pair("\u1E9Ctimes",(new sc_Pair("\u1E9Cj",(new sc_Pair("\u1E9Ck",null)))))),null)))))),(new sc_Pair((new sc_Pair("\u1E9Cexp",(new sc_Pair((new sc_Pair("\u1E9Cexp",(new sc_Pair("\u1E9Ci",(new sc_Pair("\u1E9Cj",null)))))),(new sc_Pair("\u1E9Ck",null)))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Creverse-loop",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Cy",null)))))),(new sc_Pair((new sc_Pair("\u1E9Cappend",(new sc_Pair((new sc_Pair("\u1E9Creverse",(new sc_Pair("\u1E9Cx",null)))),(new sc_Pair("\u1E9Cy",null)))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Creverse-loop",(new sc_Pair("\u1E9Cx",(new sc_Pair((new sc_Pair("\u1E9Cnil",null)),null)))))),(new sc_Pair((new sc_Pair("\u1E9Creverse",(new sc_Pair("\u1E9Cx",null)))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Ccount-list",(new sc_Pair("\u1E9Cz",(new sc_Pair((new sc_Pair("\u1E9Csort-lp",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Cy",null)))))),null)))))),(new sc_Pair((new sc_Pair("\u1E9Cplus",(new sc_Pair((new sc_Pair("\u1E9Ccount-list",(new sc_Pair("\u1E9Cz",(new sc_Pair("\u1E9Cx",null)))))),(new sc_Pair((new sc_Pair("\u1E9Ccount-list",(new sc_Pair("\u1E9Cz",(new sc_Pair("\u1E9Cy",null)))))),null)))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cappend",(new sc_Pair("\u1E9Ca",(new sc_Pair("\u1E9Cb",null)))))),(new sc_Pair((new sc_Pair("\u1E9Cappend",(new sc_Pair("\u1E9Ca",(new sc_Pair("\u1E9Cc",null)))))),null)))))),(new sc_Pair((new sc_Pair("\u1E9Cequal",(new sc_Pair("\u1E9Cb",(new sc_Pair("\u1E9Cc",null)))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cplus",(new sc_Pair((new sc_Pair("\u1E9Cremainder",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Cy",null)))))),(new sc_Pair((new sc_Pair("\u1E9Ctimes",(new sc_Pair("\u1E9Cy",(new sc_Pair((new sc_Pair("\u1E9Cquotient",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Cy",null)))))),null)))))),null)))))),(new sc_Pair((new sc_Pair("\u1E9Cfix",(new sc_Pair("\u1E9Cx",null)))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cpower-eval",(new sc_Pair((new sc_Pair("\u1E9Cbig-plus1",(new sc_Pair("\u1E9Cl",(new sc_Pair("\u1E9Ci",(new sc_Pair("\u1E9Cbase",null)))))))),(new sc_Pair("\u1E9Cbase",null)))))),(new sc_Pair((new sc_Pair("\u1E9Cplus",(new sc_Pair((new sc_Pair("\u1E9Cpower-eval",(new sc_Pair("\u1E9Cl",(new sc_Pair("\u1E9Cbase",null)))))),(new sc_Pair("\u1E9Ci",null)))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cpower-eval",(new sc_Pair((new sc_Pair("\u1E9Cbig-plus",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Cy",(new sc_Pair("\u1E9Ci",(new sc_Pair("\u1E9Cbase",null)))))))))),(new sc_Pair("\u1E9Cbase",null)))))),(new sc_Pair((new sc_Pair("\u1E9Cplus",(new sc_Pair("\u1E9Ci",(new sc_Pair((new sc_Pair("\u1E9Cplus",(new sc_Pair((new sc_Pair("\u1E9Cpower-eval",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Cbase",null)))))),(new sc_Pair((new sc_Pair("\u1E9Cpower-eval",(new sc_Pair("\u1E9Cy",(new sc_Pair("\u1E9Cbase",null)))))),null)))))),null)))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cremainder",(new sc_Pair("\u1E9Cy",(new sc_Pair((1),null)))))),(new sc_Pair((new sc_Pair("\u1E9Czero",null)),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Clessp",(new sc_Pair((new sc_Pair("\u1E9Cremainder",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Cy",null)))))),(new sc_Pair("\u1E9Cy",null)))))),(new sc_Pair((new sc_Pair("\u1E9Cnot",(new sc_Pair((new sc_Pair("\u1E9Czerop",(new sc_Pair("\u1E9Cy",null)))),null)))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cremainder",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Cx",null)))))),(new sc_Pair((new sc_Pair("\u1E9Czero",null)),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Clessp",(new sc_Pair((new sc_Pair("\u1E9Cquotient",(new sc_Pair("\u1E9Ci",(new sc_Pair("\u1E9Cj",null)))))),(new sc_Pair("\u1E9Ci",null)))))),(new sc_Pair((new sc_Pair("\u1E9Cand",(new sc_Pair((new sc_Pair("\u1E9Cnot",(new sc_Pair((new sc_Pair("\u1E9Czerop",(new sc_Pair("\u1E9Ci",null)))),null)))),(new sc_Pair((new sc_Pair("\u1E9Cor",(new sc_Pair((new sc_Pair("\u1E9Czerop",(new sc_Pair("\u1E9Cj",null)))),(new sc_Pair((new sc_Pair("\u1E9Cnot",(new sc_Pair((new sc_Pair("\u1E9Cequal",(new sc_Pair("\u1E9Cj",(new sc_Pair((1),null)))))),null)))),null)))))),null)))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Clessp",(new sc_Pair((new sc_Pair("\u1E9Cremainder",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Cy",null)))))),(new sc_Pair("\u1E9Cx",null)))))),(new sc_Pair((new sc_Pair("\u1E9Cand",(new sc_Pair((new sc_Pair("\u1E9Cnot",(new sc_Pair((new sc_Pair("\u1E9Czerop",(new sc_Pair("\u1E9Cy",null)))),null)))),(new sc_Pair((new sc_Pair("\u1E9Cnot",(new sc_Pair((new sc_Pair("\u1E9Czerop",(new sc_Pair("\u1E9Cx",null)))),null)))),(new sc_Pair((new sc_Pair("\u1E9Cnot",(new sc_Pair((new sc_Pair("\u1E9Clessp",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Cy",null)))))),null)))),null)))))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cpower-eval",(new sc_Pair((new sc_Pair("\u1E9Cpower-rep",(new sc_Pair("\u1E9Ci",(new sc_Pair("\u1E9Cbase",null)))))),(new sc_Pair("\u1E9Cbase",null)))))),(new sc_Pair((new sc_Pair("\u1E9Cfix",(new sc_Pair("\u1E9Ci",null)))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cpower-eval",(new sc_Pair((new sc_Pair("\u1E9Cbig-plus",(new sc_Pair((new sc_Pair("\u1E9Cpower-rep",(new sc_Pair("\u1E9Ci",(new sc_Pair("\u1E9Cbase",null)))))),(new sc_Pair((new sc_Pair("\u1E9Cpower-rep",(new sc_Pair("\u1E9Cj",(new sc_Pair("\u1E9Cbase",null)))))),(new sc_Pair((new sc_Pair("\u1E9Czero",null)),(new sc_Pair("\u1E9Cbase",null)))))))))),(new sc_Pair("\u1E9Cbase",null)))))),(new sc_Pair((new sc_Pair("\u1E9Cplus",(new sc_Pair("\u1E9Ci",(new sc_Pair("\u1E9Cj",null)))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cgcd",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Cy",null)))))),(new sc_Pair((new sc_Pair("\u1E9Cgcd",(new sc_Pair("\u1E9Cy",(new sc_Pair("\u1E9Cx",null)))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cnth",(new sc_Pair((new sc_Pair("\u1E9Cappend",(new sc_Pair("\u1E9Ca",(new sc_Pair("\u1E9Cb",null)))))),(new sc_Pair("\u1E9Ci",null)))))),(new sc_Pair((new sc_Pair("\u1E9Cappend",(new sc_Pair((new sc_Pair("\u1E9Cnth",(new sc_Pair("\u1E9Ca",(new sc_Pair("\u1E9Ci",null)))))),(new sc_Pair((new sc_Pair("\u1E9Cnth",(new sc_Pair("\u1E9Cb",(new sc_Pair((new sc_Pair("\u1E9Cdifference",(new sc_Pair("\u1E9Ci",(new sc_Pair((new sc_Pair("\u1E9Clength",(new sc_Pair("\u1E9Ca",null)))),null)))))),null)))))),null)))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cdifference",(new sc_Pair((new sc_Pair("\u1E9Cplus",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Cy",null)))))),(new sc_Pair("\u1E9Cx",null)))))),(new sc_Pair((new sc_Pair("\u1E9Cfix",(new sc_Pair("\u1E9Cy",null)))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cdifference",(new sc_Pair((new sc_Pair("\u1E9Cplus",(new sc_Pair("\u1E9Cy",(new sc_Pair("\u1E9Cx",null)))))),(new sc_Pair("\u1E9Cx",null)))))),(new sc_Pair((new sc_Pair("\u1E9Cfix",(new sc_Pair("\u1E9Cy",null)))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cdifference",(new sc_Pair((new sc_Pair("\u1E9Cplus",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Cy",null)))))),(new sc_Pair((new sc_Pair("\u1E9Cplus",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Cz",null)))))),null)))))),(new sc_Pair((new sc_Pair("\u1E9Cdifference",(new sc_Pair("\u1E9Cy",(new sc_Pair("\u1E9Cz",null)))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Ctimes",(new sc_Pair("\u1E9Cx",(new sc_Pair((new sc_Pair("\u1E9Cdifference",(new sc_Pair("\u1E9Cc",(new sc_Pair("\u1E9Cw",null)))))),null)))))),(new sc_Pair((new sc_Pair("\u1E9Cdifference",(new sc_Pair((new sc_Pair("\u1E9Ctimes",(new sc_Pair("\u1E9Cc",(new sc_Pair("\u1E9Cx",null)))))),(new sc_Pair((new sc_Pair("\u1E9Ctimes",(new sc_Pair("\u1E9Cw",(new sc_Pair("\u1E9Cx",null)))))),null)))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cremainder",(new sc_Pair((new sc_Pair("\u1E9Ctimes",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Cz",null)))))),(new sc_Pair("\u1E9Cz",null)))))),(new sc_Pair((new sc_Pair("\u1E9Czero",null)),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cdifference",(new sc_Pair((new sc_Pair("\u1E9Cplus",(new sc_Pair("\u1E9Cb",(new sc_Pair((new sc_Pair("\u1E9Cplus",(new sc_Pair("\u1E9Ca",(new sc_Pair("\u1E9Cc",null)))))),null)))))),(new sc_Pair("\u1E9Ca",null)))))),(new sc_Pair((new sc_Pair("\u1E9Cplus",(new sc_Pair("\u1E9Cb",(new sc_Pair("\u1E9Cc",null)))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cdifference",(new sc_Pair((new sc_Pair("\u1E9Cadd1",(new sc_Pair((new sc_Pair("\u1E9Cplus",(new sc_Pair("\u1E9Cy",(new sc_Pair("\u1E9Cz",null)))))),null)))),(new sc_Pair("\u1E9Cz",null)))))),(new sc_Pair((new sc_Pair("\u1E9Cadd1",(new sc_Pair("\u1E9Cy",null)))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Clessp",(new sc_Pair((new sc_Pair("\u1E9Cplus",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Cy",null)))))),(new sc_Pair((new sc_Pair("\u1E9Cplus",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Cz",null)))))),null)))))),(new sc_Pair((new sc_Pair("\u1E9Clessp",(new sc_Pair("\u1E9Cy",(new sc_Pair("\u1E9Cz",null)))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Clessp",(new sc_Pair((new sc_Pair("\u1E9Ctimes",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Cz",null)))))),(new sc_Pair((new sc_Pair("\u1E9Ctimes",(new sc_Pair("\u1E9Cy",(new sc_Pair("\u1E9Cz",null)))))),null)))))),(new sc_Pair((new sc_Pair("\u1E9Cand",(new sc_Pair((new sc_Pair("\u1E9Cnot",(new sc_Pair((new sc_Pair("\u1E9Czerop",(new sc_Pair("\u1E9Cz",null)))),null)))),(new sc_Pair((new sc_Pair("\u1E9Clessp",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Cy",null)))))),null)))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Clessp",(new sc_Pair("\u1E9Cy",(new sc_Pair((new sc_Pair("\u1E9Cplus",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Cy",null)))))),null)))))),(new sc_Pair((new sc_Pair("\u1E9Cnot",(new sc_Pair((new sc_Pair("\u1E9Czerop",(new sc_Pair("\u1E9Cx",null)))),null)))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cgcd",(new sc_Pair((new sc_Pair("\u1E9Ctimes",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Cz",null)))))),(new sc_Pair((new sc_Pair("\u1E9Ctimes",(new sc_Pair("\u1E9Cy",(new sc_Pair("\u1E9Cz",null)))))),null)))))),(new sc_Pair((new sc_Pair("\u1E9Ctimes",(new sc_Pair("\u1E9Cz",(new sc_Pair((new sc_Pair("\u1E9Cgcd",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Cy",null)))))),null)))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cvalue",(new sc_Pair((new sc_Pair("\u1E9Cnormalize",(new sc_Pair("\u1E9Cx",null)))),(new sc_Pair("\u1E9Ca",null)))))),(new sc_Pair((new sc_Pair("\u1E9Cvalue",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Ca",null)))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cflatten",(new sc_Pair("\u1E9Cx",null)))),(new sc_Pair((new sc_Pair("\u1E9Ccons",(new sc_Pair("\u1E9Cy",(new sc_Pair((new sc_Pair("\u1E9Cnil",null)),null)))))),null)))))),(new sc_Pair((new sc_Pair("\u1E9Cand",(new sc_Pair((new sc_Pair("\u1E9Cnlistp",(new sc_Pair("\u1E9Cx",null)))),(new sc_Pair((new sc_Pair("\u1E9Cequal",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Cy",null)))))),null)))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Clistp",(new sc_Pair((new sc_Pair("\u1E9Cgopher",(new sc_Pair("\u1E9Cx",null)))),null)))),(new sc_Pair((new sc_Pair("\u1E9Clistp",(new sc_Pair("\u1E9Cx",null)))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Csamefringe",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Cy",null)))))),(new sc_Pair((new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cflatten",(new sc_Pair("\u1E9Cx",null)))),(new sc_Pair((new sc_Pair("\u1E9Cflatten",(new sc_Pair("\u1E9Cy",null)))),null)))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cgreatest-factor",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Cy",null)))))),(new sc_Pair((new sc_Pair("\u1E9Czero",null)),null)))))),(new sc_Pair((new sc_Pair("\u1E9Cand",(new sc_Pair((new sc_Pair("\u1E9Cor",(new sc_Pair((new sc_Pair("\u1E9Czerop",(new sc_Pair("\u1E9Cy",null)))),(new sc_Pair((new sc_Pair("\u1E9Cequal",(new sc_Pair("\u1E9Cy",(new sc_Pair((1),null)))))),null)))))),(new sc_Pair((new sc_Pair("\u1E9Cequal",(new sc_Pair("\u1E9Cx",(new sc_Pair((new sc_Pair("\u1E9Czero",null)),null)))))),null)))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cgreatest-factor",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Cy",null)))))),(new sc_Pair((1),null)))))),(new sc_Pair((new sc_Pair("\u1E9Cequal",(new sc_Pair("\u1E9Cx",(new sc_Pair((1),null)))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cnumberp",(new sc_Pair((new sc_Pair("\u1E9Cgreatest-factor",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Cy",null)))))),null)))),(new sc_Pair((new sc_Pair("\u1E9Cnot",(new sc_Pair((new sc_Pair("\u1E9Cand",(new sc_Pair((new sc_Pair("\u1E9Cor",(new sc_Pair((new sc_Pair("\u1E9Czerop",(new sc_Pair("\u1E9Cy",null)))),(new sc_Pair((new sc_Pair("\u1E9Cequal",(new sc_Pair("\u1E9Cy",(new sc_Pair((1),null)))))),null)))))),(new sc_Pair((new sc_Pair("\u1E9Cnot",(new sc_Pair((new sc_Pair("\u1E9Cnumberp",(new sc_Pair("\u1E9Cx",null)))),null)))),null)))))),null)))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Ctimes-list",(new sc_Pair((new sc_Pair("\u1E9Cappend",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Cy",null)))))),null)))),(new sc_Pair((new sc_Pair("\u1E9Ctimes",(new sc_Pair((new sc_Pair("\u1E9Ctimes-list",(new sc_Pair("\u1E9Cx",null)))),(new sc_Pair((new sc_Pair("\u1E9Ctimes-list",(new sc_Pair("\u1E9Cy",null)))),null)))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cprime-list",(new sc_Pair((new sc_Pair("\u1E9Cappend",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Cy",null)))))),null)))),(new sc_Pair((new sc_Pair("\u1E9Cand",(new sc_Pair((new sc_Pair("\u1E9Cprime-list",(new sc_Pair("\u1E9Cx",null)))),(new sc_Pair((new sc_Pair("\u1E9Cprime-list",(new sc_Pair("\u1E9Cy",null)))),null)))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cequal",(new sc_Pair("\u1E9Cz",(new sc_Pair((new sc_Pair("\u1E9Ctimes",(new sc_Pair("\u1E9Cw",(new sc_Pair("\u1E9Cz",null)))))),null)))))),(new sc_Pair((new sc_Pair("\u1E9Cand",(new sc_Pair((new sc_Pair("\u1E9Cnumberp",(new sc_Pair("\u1E9Cz",null)))),(new sc_Pair((new sc_Pair("\u1E9Cor",(new sc_Pair((new sc_Pair("\u1E9Cequal",(new sc_Pair("\u1E9Cz",(new sc_Pair((new sc_Pair("\u1E9Czero",null)),null)))))),(new sc_Pair((new sc_Pair("\u1E9Cequal",(new sc_Pair("\u1E9Cw",(new sc_Pair((1),null)))))),null)))))),null)))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cgreatereqp",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Cy",null)))))),(new sc_Pair((new sc_Pair("\u1E9Cnot",(new sc_Pair((new sc_Pair("\u1E9Clessp",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Cy",null)))))),null)))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cequal",(new sc_Pair("\u1E9Cx",(new sc_Pair((new sc_Pair("\u1E9Ctimes",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Cy",null)))))),null)))))),(new sc_Pair((new sc_Pair("\u1E9Cor",(new sc_Pair((new sc_Pair("\u1E9Cequal",(new sc_Pair("\u1E9Cx",(new sc_Pair((new sc_Pair("\u1E9Czero",null)),null)))))),(new sc_Pair((new sc_Pair("\u1E9Cand",(new sc_Pair((new sc_Pair("\u1E9Cnumberp",(new sc_Pair("\u1E9Cx",null)))),(new sc_Pair((new sc_Pair("\u1E9Cequal",(new sc_Pair("\u1E9Cy",(new sc_Pair((1),null)))))),null)))))),null)))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cremainder",(new sc_Pair((new sc_Pair("\u1E9Ctimes",(new sc_Pair("\u1E9Cy",(new sc_Pair("\u1E9Cx",null)))))),(new sc_Pair("\u1E9Cy",null)))))),(new sc_Pair((new sc_Pair("\u1E9Czero",null)),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Ctimes",(new sc_Pair("\u1E9Ca",(new sc_Pair("\u1E9Cb",null)))))),(new sc_Pair((1),null)))))),(new sc_Pair(sc_list("\u1E9Cand", (new sc_Pair("\u1E9Cnot",(new sc_Pair((new sc_Pair("\u1E9Cequal",(new sc_Pair("\u1E9Ca",(new sc_Pair((new sc_Pair("\u1E9Czero",null)),null)))))),null)))), (new sc_Pair("\u1E9Cnot",(new sc_Pair((new sc_Pair("\u1E9Cequal",(new sc_Pair("\u1E9Cb",(new sc_Pair((new sc_Pair("\u1E9Czero",null)),null)))))),null)))), (new sc_Pair("\u1E9Cnumberp",(new sc_Pair("\u1E9Ca",null)))), (new sc_Pair("\u1E9Cnumberp",(new sc_Pair("\u1E9Cb",null)))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Csub1",(new sc_Pair("\u1E9Ca",null)))),(new sc_Pair((new sc_Pair("\u1E9Czero",null)),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Csub1",(new sc_Pair("\u1E9Cb",null)))),(new sc_Pair((new sc_Pair("\u1E9Czero",null)),null))))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Clessp",(new sc_Pair((new sc_Pair("\u1E9Clength",(new sc_Pair((new sc_Pair("\u1E9Cdelete",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Cl",null)))))),null)))),(new sc_Pair((new sc_Pair("\u1E9Clength",(new sc_Pair("\u1E9Cl",null)))),null)))))),(new sc_Pair((new sc_Pair("\u1E9Cmember",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Cl",null)))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Csort2",(new sc_Pair((new sc_Pair("\u1E9Cdelete",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Cl",null)))))),null)))),(new sc_Pair((new sc_Pair("\u1E9Cdelete",(new sc_Pair("\u1E9Cx",(new sc_Pair((new sc_Pair("\u1E9Csort2",(new sc_Pair("\u1E9Cl",null)))),null)))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cdsort",(new sc_Pair("\u1E9Cx",null)))),(new sc_Pair((new sc_Pair("\u1E9Csort2",(new sc_Pair("\u1E9Cx",null)))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Clength",(new sc_Pair((new sc_Pair("\u1E9Ccons",(new sc_Pair("\u1E9Cx1",(new sc_Pair((new sc_Pair("\u1E9Ccons",(new sc_Pair("\u1E9Cx2",(new sc_Pair((new sc_Pair("\u1E9Ccons",(new sc_Pair("\u1E9Cx3",(new sc_Pair((new sc_Pair("\u1E9Ccons",(new sc_Pair("\u1E9Cx4",(new sc_Pair((new sc_Pair("\u1E9Ccons",(new sc_Pair("\u1E9Cx5",(new sc_Pair((new sc_Pair("\u1E9Ccons",(new sc_Pair("\u1E9Cx6",(new sc_Pair("\u1E9Cx7",null)))))),null)))))),null)))))),null)))))),null)))))),null)))))),null)))),(new sc_Pair((new sc_Pair("\u1E9Cplus",(new sc_Pair((6),(new sc_Pair((new sc_Pair("\u1E9Clength",(new sc_Pair("\u1E9Cx7",null)))),null)))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cdifference",(new sc_Pair((new sc_Pair("\u1E9Cadd1",(new sc_Pair((new sc_Pair("\u1E9Cadd1",(new sc_Pair("\u1E9Cx",null)))),null)))),(new sc_Pair((2),null)))))),(new sc_Pair((new sc_Pair("\u1E9Cfix",(new sc_Pair("\u1E9Cx",null)))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cquotient",(new sc_Pair((new sc_Pair("\u1E9Cplus",(new sc_Pair("\u1E9Cx",(new sc_Pair((new sc_Pair("\u1E9Cplus",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Cy",null)))))),null)))))),(new sc_Pair((2),null)))))),(new sc_Pair((new sc_Pair("\u1E9Cplus",(new sc_Pair("\u1E9Cx",(new sc_Pair((new sc_Pair("\u1E9Cquotient",(new sc_Pair("\u1E9Cy",(new sc_Pair((2),null)))))),null)))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Csigma",(new sc_Pair((new sc_Pair("\u1E9Czero",null)),(new sc_Pair("\u1E9Ci",null)))))),(new sc_Pair((new sc_Pair("\u1E9Cquotient",(new sc_Pair((new sc_Pair("\u1E9Ctimes",(new sc_Pair("\u1E9Ci",(new sc_Pair((new sc_Pair("\u1E9Cadd1",(new sc_Pair("\u1E9Ci",null)))),null)))))),(new sc_Pair((2),null)))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cplus",(new sc_Pair("\u1E9Cx",(new sc_Pair((new sc_Pair("\u1E9Cadd1",(new sc_Pair("\u1E9Cy",null)))),null)))))),(new sc_Pair((new sc_Pair("\u1E9Cif",(new sc_Pair((new sc_Pair("\u1E9Cnumberp",(new sc_Pair("\u1E9Cy",null)))),(new sc_Pair((new sc_Pair("\u1E9Cadd1",(new sc_Pair((new sc_Pair("\u1E9Cplus",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Cy",null)))))),null)))),(new sc_Pair((new sc_Pair("\u1E9Cadd1",(new sc_Pair("\u1E9Cx",null)))),null)))))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cdifference",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Cy",null)))))),(new sc_Pair((new sc_Pair("\u1E9Cdifference",(new sc_Pair("\u1E9Cz",(new sc_Pair("\u1E9Cy",null)))))),null)))))),(new sc_Pair((new sc_Pair("\u1E9Cif",(new sc_Pair((new sc_Pair("\u1E9Clessp",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Cy",null)))))),(new sc_Pair((new sc_Pair("\u1E9Cnot",(new sc_Pair((new sc_Pair("\u1E9Clessp",(new sc_Pair("\u1E9Cy",(new sc_Pair("\u1E9Cz",null)))))),null)))),(new sc_Pair((new sc_Pair("\u1E9Cif",(new sc_Pair((new sc_Pair("\u1E9Clessp",(new sc_Pair("\u1E9Cz",(new sc_Pair("\u1E9Cy",null)))))),(new sc_Pair((new sc_Pair("\u1E9Cnot",(new sc_Pair((new sc_Pair("\u1E9Clessp",(new sc_Pair("\u1E9Cy",(new sc_Pair("\u1E9Cx",null)))))),null)))),(new sc_Pair((new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cfix",(new sc_Pair("\u1E9Cx",null)))),(new sc_Pair((new sc_Pair("\u1E9Cfix",(new sc_Pair("\u1E9Cz",null)))),null)))))),null)))))))),null)))))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cmeaning",(new sc_Pair((new sc_Pair("\u1E9Cplus-tree",(new sc_Pair((new sc_Pair("\u1E9Cdelete",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Cy",null)))))),null)))),(new sc_Pair("\u1E9Ca",null)))))),(new sc_Pair((new sc_Pair("\u1E9Cif",(new sc_Pair((new sc_Pair("\u1E9Cmember",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Cy",null)))))),(new sc_Pair((new sc_Pair("\u1E9Cdifference",(new sc_Pair((new sc_Pair("\u1E9Cmeaning",(new sc_Pair((new sc_Pair("\u1E9Cplus-tree",(new sc_Pair("\u1E9Cy",null)))),(new sc_Pair("\u1E9Ca",null)))))),(new sc_Pair((new sc_Pair("\u1E9Cmeaning",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Ca",null)))))),null)))))),(new sc_Pair((new sc_Pair("\u1E9Cmeaning",(new sc_Pair((new sc_Pair("\u1E9Cplus-tree",(new sc_Pair("\u1E9Cy",null)))),(new sc_Pair("\u1E9Ca",null)))))),null)))))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Ctimes",(new sc_Pair("\u1E9Cx",(new sc_Pair((new sc_Pair("\u1E9Cadd1",(new sc_Pair("\u1E9Cy",null)))),null)))))),(new sc_Pair((new sc_Pair("\u1E9Cif",(new sc_Pair((new sc_Pair("\u1E9Cnumberp",(new sc_Pair("\u1E9Cy",null)))),(new sc_Pair((new sc_Pair("\u1E9Cplus",(new sc_Pair("\u1E9Cx",(new sc_Pair((new sc_Pair("\u1E9Ctimes",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Cy",null)))))),null)))))),(new sc_Pair((new sc_Pair("\u1E9Cfix",(new sc_Pair("\u1E9Cx",null)))),null)))))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cnth",(new sc_Pair((new sc_Pair("\u1E9Cnil",null)),(new sc_Pair("\u1E9Ci",null)))))),(new sc_Pair((new sc_Pair("\u1E9Cif",(new sc_Pair((new sc_Pair("\u1E9Czerop",(new sc_Pair("\u1E9Ci",null)))),(new sc_Pair((new sc_Pair("\u1E9Cnil",null)),(new sc_Pair((new sc_Pair("\u1E9Czero",null)),null)))))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Clast",(new sc_Pair((new sc_Pair("\u1E9Cappend",(new sc_Pair("\u1E9Ca",(new sc_Pair("\u1E9Cb",null)))))),null)))),(new sc_Pair((new sc_Pair("\u1E9Cif",(new sc_Pair((new sc_Pair("\u1E9Clistp",(new sc_Pair("\u1E9Cb",null)))),(new sc_Pair((new sc_Pair("\u1E9Clast",(new sc_Pair("\u1E9Cb",null)))),(new sc_Pair((new sc_Pair("\u1E9Cif",(new sc_Pair((new sc_Pair("\u1E9Clistp",(new sc_Pair("\u1E9Ca",null)))),(new sc_Pair((new sc_Pair("\u1E9Ccons",(new sc_Pair((new sc_Pair("\u1E9Ccar",(new sc_Pair((new sc_Pair("\u1E9Clast",(new sc_Pair("\u1E9Ca",null)))),null)))),(new sc_Pair("\u1E9Cb",null)))))),(new sc_Pair("\u1E9Cb",null)))))))),null)))))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Clessp",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Cy",null)))))),(new sc_Pair("\u1E9Cz",null)))))),(new sc_Pair((new sc_Pair("\u1E9Cif",(new sc_Pair((new sc_Pair("\u1E9Clessp",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Cy",null)))))),(new sc_Pair((new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Ct",null)),(new sc_Pair("\u1E9Cz",null)))))),(new sc_Pair((new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cf",null)),(new sc_Pair("\u1E9Cz",null)))))),null)))))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cassignment",(new sc_Pair("\u1E9Cx",(new sc_Pair((new sc_Pair("\u1E9Cappend",(new sc_Pair("\u1E9Ca",(new sc_Pair("\u1E9Cb",null)))))),null)))))),(new sc_Pair((new sc_Pair("\u1E9Cif",(new sc_Pair((new sc_Pair("\u1E9Cassignedp",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Ca",null)))))),(new sc_Pair((new sc_Pair("\u1E9Cassignment",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Ca",null)))))),(new sc_Pair((new sc_Pair("\u1E9Cassignment",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Cb",null)))))),null)))))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Ccar",(new sc_Pair((new sc_Pair("\u1E9Cgopher",(new sc_Pair("\u1E9Cx",null)))),null)))),(new sc_Pair((new sc_Pair("\u1E9Cif",(new sc_Pair((new sc_Pair("\u1E9Clistp",(new sc_Pair("\u1E9Cx",null)))),(new sc_Pair((new sc_Pair("\u1E9Ccar",(new sc_Pair((new sc_Pair("\u1E9Cflatten",(new sc_Pair("\u1E9Cx",null)))),null)))),(new sc_Pair((new sc_Pair("\u1E9Czero",null)),null)))))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cflatten",(new sc_Pair((new sc_Pair("\u1E9Ccdr",(new sc_Pair((new sc_Pair("\u1E9Cgopher",(new sc_Pair("\u1E9Cx",null)))),null)))),null)))),(new sc_Pair((new sc_Pair("\u1E9Cif",(new sc_Pair((new sc_Pair("\u1E9Clistp",(new sc_Pair("\u1E9Cx",null)))),(new sc_Pair((new sc_Pair("\u1E9Ccdr",(new sc_Pair((new sc_Pair("\u1E9Cflatten",(new sc_Pair("\u1E9Cx",null)))),null)))),(new sc_Pair((new sc_Pair("\u1E9Ccons",(new sc_Pair((new sc_Pair("\u1E9Czero",null)),(new sc_Pair((new sc_Pair("\u1E9Cnil",null)),null)))))),null)))))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cquotient",(new sc_Pair((new sc_Pair("\u1E9Ctimes",(new sc_Pair("\u1E9Cy",(new sc_Pair("\u1E9Cx",null)))))),(new sc_Pair("\u1E9Cy",null)))))),(new sc_Pair((new sc_Pair("\u1E9Cif",(new sc_Pair((new sc_Pair("\u1E9Czerop",(new sc_Pair("\u1E9Cy",null)))),(new sc_Pair((new sc_Pair("\u1E9Czero",null)),(new sc_Pair((new sc_Pair("\u1E9Cfix",(new sc_Pair("\u1E9Cx",null)))),null)))))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cget",(new sc_Pair("\u1E9Cj",(new sc_Pair((new sc_Pair("\u1E9Cset",(new sc_Pair("\u1E9Ci",(new sc_Pair("\u1E9Cval",(new sc_Pair("\u1E9Cmem",null)))))))),null)))))),(new sc_Pair((new sc_Pair("\u1E9Cif",(new sc_Pair((new sc_Pair("\u1E9Ceqp",(new sc_Pair("\u1E9Cj",(new sc_Pair("\u1E9Ci",null)))))),(new sc_Pair("\u1E9Cval",(new sc_Pair((new sc_Pair("\u1E9Cget",(new sc_Pair("\u1E9Cj",(new sc_Pair("\u1E9Cmem",null)))))),null)))))))),null)))))))); + (const_nboyer = (new sc_Pair((new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Cf",(new sc_Pair((new sc_Pair("\u1E9Cplus",(new sc_Pair((new sc_Pair("\u1E9Cplus",(new sc_Pair("\u1E9Ca",(new sc_Pair("\u1E9Cb",null)))))),(new sc_Pair((new sc_Pair("\u1E9Cplus",(new sc_Pair("\u1E9Cc",(new sc_Pair((new sc_Pair("\u1E9Czero",null)),null)))))),null)))))),null)))))),(new sc_Pair((new sc_Pair("\u1E9Cy",(new sc_Pair("\u1E9Cf",(new sc_Pair((new sc_Pair("\u1E9Ctimes",(new sc_Pair((new sc_Pair("\u1E9Ctimes",(new sc_Pair("\u1E9Ca",(new sc_Pair("\u1E9Cb",null)))))),(new sc_Pair((new sc_Pair("\u1E9Cplus",(new sc_Pair("\u1E9Cc",(new sc_Pair("\u1E9Cd",null)))))),null)))))),null)))))),(new sc_Pair((new sc_Pair("\u1E9Cz",(new sc_Pair("\u1E9Cf",(new sc_Pair((new sc_Pair("\u1E9Creverse",(new sc_Pair((new sc_Pair("\u1E9Cappend",(new sc_Pair((new sc_Pair("\u1E9Cappend",(new sc_Pair("\u1E9Ca",(new sc_Pair("\u1E9Cb",null)))))),(new sc_Pair((new sc_Pair("\u1E9Cnil",null)),null)))))),null)))),null)))))),(new sc_Pair((new sc_Pair("\u1E9Cu",(new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cplus",(new sc_Pair("\u1E9Ca",(new sc_Pair("\u1E9Cb",null)))))),(new sc_Pair((new sc_Pair("\u1E9Cdifference",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Cy",null)))))),null)))))))),(new sc_Pair((new sc_Pair("\u1E9Cw",(new sc_Pair("\u1E9Clessp",(new sc_Pair((new sc_Pair("\u1E9Cremainder",(new sc_Pair("\u1E9Ca",(new sc_Pair("\u1E9Cb",null)))))),(new sc_Pair((new sc_Pair("\u1E9Cmember",(new sc_Pair("\u1E9Ca",(new sc_Pair((new sc_Pair("\u1E9Clength",(new sc_Pair("\u1E9Cb",null)))),null)))))),null)))))))),null))))))))))); + BgL_nboyerzd2benchmarkzd2 = function() { + var args = null; + for (var sc_tmp = arguments.length - 1; sc_tmp >= 0; sc_tmp--) { + args = sc_cons(arguments[sc_tmp], args); + } + var n; + return ((n = ((args === null)?(0):(args.car))), (BgL_setupzd2boyerzd2()), (BgL_runzd2benchmarkzd2(("nboyer"+(sc_number2string(n))), (1), function() { + return (BgL_testzd2boyerzd2(n)); + }, function(rewrites) { + if ((sc_isNumber(rewrites))) + switch (n) { + case (0): + return (rewrites===(95024)); + break; + case (1): + return (rewrites===(591777)); + break; + case (2): + return (rewrites===(1813975)); + break; + case (3): + return (rewrites===(5375678)); + break; + case (4): + return (rewrites===(16445406)); + break; + case (5): + return (rewrites===(51507739)); + break; + default: + return true; + break; + } + else + return false; + }))); + }; + BgL_setupzd2boyerzd2 = function() { + return true; + }; + BgL_testzd2boyerzd2 = function() { + return true; + }; + translate_term_nboyer = function(term) { + var lst; + return (!(term instanceof sc_Pair)?term:(new sc_Pair((BgL_sc_symbolzd2ze3symbolzd2record_1ze3_nboyer((term.car))), ((lst = (term.cdr)), ((lst === null)?null:(new sc_Pair((translate_term_nboyer((lst.car))), (translate_args_nboyer((lst.cdr)))))))))); + }; + translate_args_nboyer = function(lst) { + var sc_lst_5; + var term; + return ((lst === null)?null:(new sc_Pair(((term = (lst.car)), (!(term instanceof sc_Pair)?term:(new sc_Pair((BgL_sc_symbolzd2ze3symbolzd2record_1ze3_nboyer((term.car))), (translate_args_nboyer((term.cdr))))))), ((sc_lst_5 = (lst.cdr)), ((sc_lst_5 === null)?null:(new sc_Pair((translate_term_nboyer((sc_lst_5.car))), (translate_args_nboyer((sc_lst_5.cdr)))))))))); + }; + untranslate_term_nboyer = function(term) { + var optrOpnd; + var tail1131; + var L1127; + var falseHead1130; + var symbol_record; + if (!(term instanceof sc_Pair)) + return term; + else + { + (falseHead1130 = (new sc_Pair(null, null))); + (L1127 = (term.cdr)); + (tail1131 = falseHead1130); + while (!(L1127 === null)) { + { + (tail1131.cdr = (new sc_Pair((untranslate_term_nboyer((L1127.car))), null))); + (tail1131 = (tail1131.cdr)); + (L1127 = (L1127.cdr)); + } + } + (optrOpnd = (falseHead1130.cdr)); + return (new sc_Pair(((symbol_record = (term.car)), (symbol_record[(0)])), optrOpnd)); + } + }; + BgL_sc_symbolzd2ze3symbolzd2record_1ze3_nboyer = function(sym) { + var r; + var x; + return ((x = (sc_assq(sym, BgL_sc_za2symbolzd2recordszd2alistza2_2z00_nboyer))), ((x!== false)?(x.cdr):((r = [sym, null]), (BgL_sc_za2symbolzd2recordszd2alistza2_2z00_nboyer = (new sc_Pair((new sc_Pair(sym, r)), BgL_sc_za2symbolzd2recordszd2alistza2_2z00_nboyer))), r))); + }; + (BgL_sc_za2symbolzd2recordszd2alistza2_2z00_nboyer = null); + translate_alist_nboyer = function(alist) { + var sc_alist_6; + var term; + return ((alist === null)?null:(new sc_Pair((new sc_Pair((alist.car.car), ((term = (alist.car.cdr)), (!(term instanceof sc_Pair)?term:(new sc_Pair((BgL_sc_symbolzd2ze3symbolzd2record_1ze3_nboyer((term.car))), (translate_args_nboyer((term.cdr))))))))), ((sc_alist_6 = (alist.cdr)), ((sc_alist_6 === null)?null:(new sc_Pair((new sc_Pair((sc_alist_6.car.car), (translate_term_nboyer((sc_alist_6.car.cdr))))), (translate_alist_nboyer((sc_alist_6.cdr)))))))))); + }; + apply_subst_nboyer = function(alist, term) { + var lst; + var temp_temp; + return (!(term instanceof sc_Pair)?((temp_temp = (sc_assq(term, alist))), ((temp_temp!== false)?(temp_temp.cdr):term)):(new sc_Pair((term.car), ((lst = (term.cdr)), ((lst === null)?null:(new sc_Pair((apply_subst_nboyer(alist, (lst.car))), (apply_subst_lst_nboyer(alist, (lst.cdr)))))))))); + }; + apply_subst_lst_nboyer = function(alist, lst) { + var sc_lst_7; + return ((lst === null)?null:(new sc_Pair((apply_subst_nboyer(alist, (lst.car))), ((sc_lst_7 = (lst.cdr)), ((sc_lst_7 === null)?null:(new sc_Pair((apply_subst_nboyer(alist, (sc_lst_7.car))), (apply_subst_lst_nboyer(alist, (sc_lst_7.cdr)))))))))); + }; + tautologyp_nboyer = function(sc_x_11, true_lst, false_lst) { + var tmp1125; + var x; + var tmp1126; + var sc_x_8; + var sc_tmp1125_9; + var sc_tmp1126_10; + var sc_x_11; + var true_lst; + var false_lst; + while (true) { + if ((((sc_tmp1126_10 = (is_term_equal_nboyer(sc_x_11, true_term_nboyer))), ((sc_tmp1126_10!== false)?sc_tmp1126_10:(is_term_member_nboyer(sc_x_11, true_lst))))!== false)) + return true; + else + if ((((sc_tmp1125_9 = (is_term_equal_nboyer(sc_x_11, false_term_nboyer))), ((sc_tmp1125_9!== false)?sc_tmp1125_9:(is_term_member_nboyer(sc_x_11, false_lst))))!== false)) + return false; + else + if (!(sc_x_11 instanceof sc_Pair)) + return false; + else + if (((sc_x_11.car)===if_constructor_nboyer)) + if ((((sc_x_8 = (sc_x_11.cdr.car)), (tmp1126 = (is_term_equal_nboyer(sc_x_8, true_term_nboyer))), ((tmp1126!== false)?tmp1126:(is_term_member_nboyer(sc_x_8, true_lst))))!== false)) + (sc_x_11 = (sc_x_11.cdr.cdr.car)); + else + if ((((x = (sc_x_11.cdr.car)), (tmp1125 = (is_term_equal_nboyer(x, false_term_nboyer))), ((tmp1125!== false)?tmp1125:(is_term_member_nboyer(x, false_lst))))!== false)) + (sc_x_11 = (sc_x_11.cdr.cdr.cdr.car)); + else + if (((tautologyp_nboyer((sc_x_11.cdr.cdr.car), (new sc_Pair((sc_x_11.cdr.car), true_lst)), false_lst))!== false)) + { + (false_lst = (new sc_Pair((sc_x_11.cdr.car), false_lst))); + (sc_x_11 = (sc_x_11.cdr.cdr.cdr.car)); + } + else + return false; + else + return false; + } + }; + (if_constructor_nboyer = "\u1E9C*"); + (rewrite_count_nboyer = (0)); + rewrite_nboyer = function(term) { + var term2; + var sc_term_12; + var lst; + var symbol_record; + var sc_lst_13; + { + (++rewrite_count_nboyer); + if (!(term instanceof sc_Pair)) + return term; + else + { + (sc_term_12 = (new sc_Pair((term.car), ((sc_lst_13 = (term.cdr)), ((sc_lst_13 === null)?null:(new sc_Pair((rewrite_nboyer((sc_lst_13.car))), (rewrite_args_nboyer((sc_lst_13.cdr)))))))))); + (lst = ((symbol_record = (term.car)), (symbol_record[(1)]))); + while (true) { + if ((lst === null)) + return sc_term_12; + else + if ((((term2 = ((lst.car).cdr.car)), (unify_subst_nboyer = null), (one_way_unify1_nboyer(sc_term_12, term2)))!== false)) + return (rewrite_nboyer((apply_subst_nboyer(unify_subst_nboyer, ((lst.car).cdr.cdr.car))))); + else + (lst = (lst.cdr)); + } + } + } + }; + rewrite_args_nboyer = function(lst) { + var sc_lst_14; + return ((lst === null)?null:(new sc_Pair((rewrite_nboyer((lst.car))), ((sc_lst_14 = (lst.cdr)), ((sc_lst_14 === null)?null:(new sc_Pair((rewrite_nboyer((sc_lst_14.car))), (rewrite_args_nboyer((sc_lst_14.cdr)))))))))); + }; + (unify_subst_nboyer = "\u1E9C*"); + one_way_unify1_nboyer = function(term1, term2) { + var lst1; + var lst2; + var temp_temp; + if (!(term2 instanceof sc_Pair)) + { + (temp_temp = (sc_assq(term2, unify_subst_nboyer))); + if ((temp_temp!== false)) + return (is_term_equal_nboyer(term1, (temp_temp.cdr))); + else + if ((sc_isNumber(term2))) + return (sc_isEqual(term1, term2)); + else + { + (unify_subst_nboyer = (new sc_Pair((new sc_Pair(term2, term1)), unify_subst_nboyer))); + return true; + } + } + else + if (!(term1 instanceof sc_Pair)) + return false; + else + if (((term1.car)===(term2.car))) + { + (lst1 = (term1.cdr)); + (lst2 = (term2.cdr)); + while (true) { + if ((lst1 === null)) + return (lst2 === null); + else + if ((lst2 === null)) + return false; + else + if (((one_way_unify1_nboyer((lst1.car), (lst2.car)))!== false)) + { + (lst1 = (lst1.cdr)); + (lst2 = (lst2.cdr)); + } + else + return false; + } + } + else + return false; + }; + (false_term_nboyer = "\u1E9C*"); + (true_term_nboyer = "\u1E9C*"); + trans_of_implies1_nboyer = function(n) { + var sc_n_15; + return ((sc_isEqual(n, (1)))?(sc_list("\u1E9Cimplies", (0), (1))):(sc_list("\u1E9Cand", (sc_list("\u1E9Cimplies", (n-(1)), n)), ((sc_n_15 = (n-(1))), ((sc_isEqual(sc_n_15, (1)))?(sc_list("\u1E9Cimplies", (0), (1))):(sc_list("\u1E9Cand", (sc_list("\u1E9Cimplies", (sc_n_15-(1)), sc_n_15)), (trans_of_implies1_nboyer((sc_n_15-(1))))))))))); + }; + is_term_equal_nboyer = function(x, y) { + var lst1; + var lst2; + var r2; + var r1; + if ((x instanceof sc_Pair)) + if ((y instanceof sc_Pair)) + if ((((r1 = (x.car)), (r2 = (y.car)), (r1===r2))!== false)) + { + (lst1 = (x.cdr)); + (lst2 = (y.cdr)); + while (true) { + if ((lst1 === null)) + return (lst2 === null); + else + if ((lst2 === null)) + return false; + else + if (((is_term_equal_nboyer((lst1.car), (lst2.car)))!== false)) + { + (lst1 = (lst1.cdr)); + (lst2 = (lst2.cdr)); + } + else + return false; + } + } + else + return false; + else + return false; + else + return (sc_isEqual(x, y)); + }; + is_term_member_nboyer = function(x, lst) { + var x; + var lst; + while (true) { + if ((lst === null)) + return false; + else + if (((is_term_equal_nboyer(x, (lst.car)))!== false)) + return true; + else + (lst = (lst.cdr)); + } + }; + BgL_setupzd2boyerzd2 = function() { + var symbol_record; + var value; + var BgL_sc_symbolzd2record_16zd2; + var sym; + var sc_sym_17; + var term; + var lst; + var sc_term_18; + var sc_term_19; + { + (BgL_sc_za2symbolzd2recordszd2alistza2_2z00_nboyer = null); + (if_constructor_nboyer = (BgL_sc_symbolzd2ze3symbolzd2record_1ze3_nboyer("\u1E9Cif"))); + (false_term_nboyer = ((sc_term_19 = (new sc_Pair("\u1E9Cf",null))), (!(sc_term_19 instanceof sc_Pair)?sc_term_19:(new sc_Pair((BgL_sc_symbolzd2ze3symbolzd2record_1ze3_nboyer((sc_term_19.car))), (translate_args_nboyer((sc_term_19.cdr)))))))); + (true_term_nboyer = ((sc_term_18 = (new sc_Pair("\u1E9Ct",null))), (!(sc_term_18 instanceof sc_Pair)?sc_term_18:(new sc_Pair((BgL_sc_symbolzd2ze3symbolzd2record_1ze3_nboyer((sc_term_18.car))), (translate_args_nboyer((sc_term_18.cdr)))))))); + (lst = sc_const_3_nboyer); + while (!(lst === null)) { + { + (term = (lst.car)); + if (((term instanceof sc_Pair)&&(((term.car)==="\u1E9Cequal")&&((term.cdr.car) instanceof sc_Pair)))) + { + (sc_sym_17 = ((term.cdr.car).car)); + (value = (new sc_Pair((!(term instanceof sc_Pair)?term:(new sc_Pair((BgL_sc_symbolzd2ze3symbolzd2record_1ze3_nboyer((term.car))), (translate_args_nboyer((term.cdr)))))), ((sym = ((term.cdr.car).car)), (BgL_sc_symbolzd2record_16zd2 = (BgL_sc_symbolzd2ze3symbolzd2record_1ze3_nboyer(sym))), (BgL_sc_symbolzd2record_16zd2[(1)]))))); + (symbol_record = (BgL_sc_symbolzd2ze3symbolzd2record_1ze3_nboyer(sc_sym_17))); + (symbol_record[(1)] = value); + } + else + (sc_error("ADD-LEMMA did not like term: ", term)); + (lst = (lst.cdr)); + } + } + return true; + } + }; + BgL_testzd2boyerzd2 = function(n) { + var optrOpnd; + var term; + var sc_n_20; + var answer; + var sc_term_21; + var sc_term_22; + { + (rewrite_count_nboyer = (0)); + (term = sc_const_4_nboyer); + (sc_n_20 = n); + while (!(sc_n_20=== 0)) { + { + (term = (sc_list("\u1E9Cor", term, (new sc_Pair("\u1E9Cf",null))))); + (--sc_n_20); + } + } + (sc_term_22 = term); + if (!(sc_term_22 instanceof sc_Pair)) + (optrOpnd = sc_term_22); + else + (optrOpnd = (new sc_Pair((BgL_sc_symbolzd2ze3symbolzd2record_1ze3_nboyer((sc_term_22.car))), (translate_args_nboyer((sc_term_22.cdr)))))); + (sc_term_21 = (apply_subst_nboyer(((const_nboyer === null)?null:(new sc_Pair((new sc_Pair((const_nboyer.car.car), (translate_term_nboyer((const_nboyer.car.cdr))))), (translate_alist_nboyer((const_nboyer.cdr)))))), optrOpnd))); + (answer = (tautologyp_nboyer((rewrite_nboyer(sc_term_21)), null, null))); + (sc_write(rewrite_count_nboyer)); + (sc_display(" rewrites")); + (sc_newline()); + if ((answer!== false)) + return rewrite_count_nboyer; + else + return false; + } + }; +} +/* Exported Variables */ +var BgL_parsezd2ze3nbzd2treesze3; +var BgL_earleyzd2benchmarkzd2; +var BgL_parsezd2ze3parsedzf3zc2; +var test; +var BgL_parsezd2ze3treesz31; +var BgL_makezd2parserzd2; +/* End Exports */ + +var const_earley; +{ + (const_earley = (new sc_Pair((new sc_Pair("\u1E9Cs",(new sc_Pair((new sc_Pair("\u1E9Ca",null)),(new sc_Pair((new sc_Pair("\u1E9Cs",(new sc_Pair("\u1E9Cs",null)))),null)))))),null))); + BgL_makezd2parserzd2 = function(grammar, lexer) { + var i; + var parser_descr; + var def_loop; + var nb_nts; + var names; + var steps; + var predictors; + var enders; + var starters; + var nts; + var sc_names_1; + var sc_steps_2; + var sc_predictors_3; + var sc_enders_4; + var sc_starters_5; + var nb_confs; + var BgL_sc_defzd2loop_6zd2; + var BgL_sc_nbzd2nts_7zd2; + var sc_nts_8; + var BgL_sc_defzd2loop_9zd2; + var ind; + { + ind = function(nt, sc_nts_10) { + var i; + { + (i = ((sc_nts_10.length)-(1))); + while (true) { + if ((i>=(0))) + if ((sc_isEqual((sc_nts_10[i]), nt))) + return i; + else + (--i); + else + return false; + } + } + }; + (sc_nts_8 = ((BgL_sc_defzd2loop_9zd2 = function(defs, sc_nts_11) { + var rule_loop; + var head; + var def; + return ((defs instanceof sc_Pair)?((def = (defs.car)), (head = (def.car)), (rule_loop = function(rules, sc_nts_12) { + var nt; + var l; + var sc_nts_13; + var rule; + if ((rules instanceof sc_Pair)) + { + (rule = (rules.car)); + (l = rule); + (sc_nts_13 = sc_nts_12); + while ((l instanceof sc_Pair)) { + { + (nt = (l.car)); + (l = (l.cdr)); + (sc_nts_13 = (((sc_member(nt, sc_nts_13))!== false)?sc_nts_13:(new sc_Pair(nt, sc_nts_13)))); + } + } + return (rule_loop((rules.cdr), sc_nts_13)); + } + else + return (BgL_sc_defzd2loop_9zd2((defs.cdr), sc_nts_12)); + }), (rule_loop((def.cdr), (((sc_member(head, sc_nts_11))!== false)?sc_nts_11:(new sc_Pair(head, sc_nts_11)))))):(sc_list2vector((sc_reverse(sc_nts_11))))); + }), (BgL_sc_defzd2loop_9zd2(grammar, null)))); + (BgL_sc_nbzd2nts_7zd2 = (sc_nts_8.length)); + (nb_confs = (((BgL_sc_defzd2loop_6zd2 = function(defs, BgL_sc_nbzd2confs_14zd2) { + var rule_loop; + var def; + return ((defs instanceof sc_Pair)?((def = (defs.car)), (rule_loop = function(rules, BgL_sc_nbzd2confs_15zd2) { + var l; + var BgL_sc_nbzd2confs_16zd2; + var rule; + if ((rules instanceof sc_Pair)) + { + (rule = (rules.car)); + (l = rule); + (BgL_sc_nbzd2confs_16zd2 = BgL_sc_nbzd2confs_15zd2); + while ((l instanceof sc_Pair)) { + { + (l = (l.cdr)); + (++BgL_sc_nbzd2confs_16zd2); + } + } + return (rule_loop((rules.cdr), (BgL_sc_nbzd2confs_16zd2+(1)))); + } + else + return (BgL_sc_defzd2loop_6zd2((defs.cdr), BgL_sc_nbzd2confs_15zd2)); + }), (rule_loop((def.cdr), BgL_sc_nbzd2confs_14zd2))):BgL_sc_nbzd2confs_14zd2); + }), (BgL_sc_defzd2loop_6zd2(grammar, (0))))+BgL_sc_nbzd2nts_7zd2)); + (sc_starters_5 = (sc_makeVector(BgL_sc_nbzd2nts_7zd2, null))); + (sc_enders_4 = (sc_makeVector(BgL_sc_nbzd2nts_7zd2, null))); + (sc_predictors_3 = (sc_makeVector(BgL_sc_nbzd2nts_7zd2, null))); + (sc_steps_2 = (sc_makeVector(nb_confs, false))); + (sc_names_1 = (sc_makeVector(nb_confs, false))); + (nts = sc_nts_8); + (starters = sc_starters_5); + (enders = sc_enders_4); + (predictors = sc_predictors_3); + (steps = sc_steps_2); + (names = sc_names_1); + (nb_nts = (sc_nts_8.length)); + (i = (nb_nts-(1))); + while ((i>=(0))) { + { + (sc_steps_2[i] = (i-nb_nts)); + (sc_names_1[i] = (sc_list((sc_nts_8[i]), (0)))); + (sc_enders_4[i] = (sc_list(i))); + (--i); + } + } + def_loop = function(defs, conf) { + var rule_loop; + var head; + var def; + return ((defs instanceof sc_Pair)?((def = (defs.car)), (head = (def.car)), (rule_loop = function(rules, conf, rule_num) { + var i; + var sc_i_17; + var nt; + var l; + var sc_conf_18; + var sc_i_19; + var rule; + if ((rules instanceof sc_Pair)) + { + (rule = (rules.car)); + (names[conf] = (sc_list(head, rule_num))); + (sc_i_19 = (ind(head, nts))); + (starters[sc_i_19] = (new sc_Pair(conf, (starters[sc_i_19])))); + (l = rule); + (sc_conf_18 = conf); + while ((l instanceof sc_Pair)) { + { + (nt = (l.car)); + (steps[sc_conf_18] = (ind(nt, nts))); + (sc_i_17 = (ind(nt, nts))); + (predictors[sc_i_17] = (new sc_Pair(sc_conf_18, (predictors[sc_i_17])))); + (l = (l.cdr)); + (++sc_conf_18); + } + } + (steps[sc_conf_18] = ((ind(head, nts))-nb_nts)); + (i = (ind(head, nts))); + (enders[i] = (new sc_Pair(sc_conf_18, (enders[i])))); + return (rule_loop((rules.cdr), (sc_conf_18+(1)), (rule_num+(1)))); + } + else + return (def_loop((defs.cdr), conf)); + }), (rule_loop((def.cdr), conf, (1)))):undefined); + }; + (def_loop(grammar, (sc_nts_8.length))); + (parser_descr = [lexer, sc_nts_8, sc_starters_5, sc_enders_4, sc_predictors_3, sc_steps_2, sc_names_1]); + return function(input) { + var optrOpnd; + var sc_optrOpnd_20; + var sc_optrOpnd_21; + var sc_optrOpnd_22; + var loop1; + var BgL_sc_stateza2_23za2; + var toks; + var BgL_sc_nbzd2nts_24zd2; + var sc_steps_25; + var sc_enders_26; + var state_num; + var BgL_sc_statesza2_27za2; + var states; + var i; + var conf; + var l; + var tok_nts; + var sc_i_28; + var sc_i_29; + var l1; + var l2; + var tok; + var tail1129; + var L1125; + var goal_enders; + var BgL_sc_statesza2_30za2; + var BgL_sc_nbzd2nts_31zd2; + var BgL_sc_nbzd2confs_32zd2; + var nb_toks; + var goal_starters; + var sc_states_33; + var BgL_sc_nbzd2confs_34zd2; + var BgL_sc_nbzd2toks_35zd2; + var sc_toks_36; + var falseHead1128; + var sc_names_37; + var sc_steps_38; + var sc_predictors_39; + var sc_enders_40; + var sc_starters_41; + var sc_nts_42; + var lexer; + var sc_ind_43; + var make_states; + var BgL_sc_confzd2setzd2getza2_44za2; + var conf_set_merge_new_bang; + var conf_set_adjoin; + var BgL_sc_confzd2setzd2adjoinza2_45za2; + var BgL_sc_confzd2setzd2adjoinza2za2_46z00; + var conf_set_union; + var forw; + var is_parsed; + var deriv_trees; + var BgL_sc_derivzd2treesza2_47z70; + var nb_deriv_trees; + var BgL_sc_nbzd2derivzd2treesza2_48za2; + { + sc_ind_43 = function(nt, sc_nts_49) { + var i; + { + (i = ((sc_nts_49.length)-(1))); + while (true) { + if ((i>=(0))) + if ((sc_isEqual((sc_nts_49[i]), nt))) + return i; + else + (--i); + else + return false; + } + } + }; + make_states = function(BgL_sc_nbzd2toks_50zd2, BgL_sc_nbzd2confs_51zd2) { + var v; + var i; + var sc_states_52; + { + (sc_states_52 = (sc_makeVector((BgL_sc_nbzd2toks_50zd2+(1)), false))); + (i = BgL_sc_nbzd2toks_50zd2); + while ((i>=(0))) { + { + (v = (sc_makeVector((BgL_sc_nbzd2confs_51zd2+(1)), false))); + (v[(0)] = (-1)); + (sc_states_52[i] = v); + (--i); + } + } + return sc_states_52; + } + }; + BgL_sc_confzd2setzd2getza2_44za2 = function(state, BgL_sc_statezd2num_53zd2, sc_conf_54) { + var conf_set; + var BgL_sc_confzd2set_55zd2; + return ((BgL_sc_confzd2set_55zd2 = (state[(sc_conf_54+(1))])), ((BgL_sc_confzd2set_55zd2!== false)?BgL_sc_confzd2set_55zd2:((conf_set = (sc_makeVector((BgL_sc_statezd2num_53zd2+(6)), false))), (conf_set[(1)] = (-3)), (conf_set[(2)] = (-1)), (conf_set[(3)] = (-1)), (conf_set[(4)] = (-1)), (state[(sc_conf_54+(1))] = conf_set), conf_set))); + }; + conf_set_merge_new_bang = function(conf_set) { + return ((conf_set[((conf_set[(1)])+(5))] = (conf_set[(4)])), (conf_set[(1)] = (conf_set[(3)])), (conf_set[(3)] = (-1)), (conf_set[(4)] = (-1))); + }; + conf_set_adjoin = function(state, conf_set, sc_conf_56, i) { + var tail; + return ((tail = (conf_set[(3)])), (conf_set[(i+(5))] = (-1)), (conf_set[(tail+(5))] = i), (conf_set[(3)] = i), ((tail<(0))?((conf_set[(0)] = (state[(0)])), (state[(0)] = sc_conf_56)):undefined)); + }; + BgL_sc_confzd2setzd2adjoinza2_45za2 = function(sc_states_57, BgL_sc_statezd2num_58zd2, l, i) { + var conf_set; + var sc_conf_59; + var l1; + var state; + { + (state = (sc_states_57[BgL_sc_statezd2num_58zd2])); + (l1 = l); + while ((l1 instanceof sc_Pair)) { + { + (sc_conf_59 = (l1.car)); + (conf_set = (BgL_sc_confzd2setzd2getza2_44za2(state, BgL_sc_statezd2num_58zd2, sc_conf_59))); + if (((conf_set[(i+(5))])=== false)) + { + (conf_set_adjoin(state, conf_set, sc_conf_59, i)); + (l1 = (l1.cdr)); + } + else + (l1 = (l1.cdr)); + } + } + return undefined; + } + }; + BgL_sc_confzd2setzd2adjoinza2za2_46z00 = function(sc_states_60, BgL_sc_statesza2_61za2, BgL_sc_statezd2num_62zd2, sc_conf_63, i) { + var BgL_sc_confzd2setza2_64z70; + var BgL_sc_stateza2_65za2; + var conf_set; + var state; + return ((state = (sc_states_60[BgL_sc_statezd2num_62zd2])), ((((conf_set = (state[(sc_conf_63+(1))])), ((conf_set!== false)?(conf_set[(i+(5))]):false))!== false)?((BgL_sc_stateza2_65za2 = (BgL_sc_statesza2_61za2[BgL_sc_statezd2num_62zd2])), (BgL_sc_confzd2setza2_64z70 = (BgL_sc_confzd2setzd2getza2_44za2(BgL_sc_stateza2_65za2, BgL_sc_statezd2num_62zd2, sc_conf_63))), (((BgL_sc_confzd2setza2_64z70[(i+(5))])=== false)?(conf_set_adjoin(BgL_sc_stateza2_65za2, BgL_sc_confzd2setza2_64z70, sc_conf_63, i)):undefined), true):false)); + }; + conf_set_union = function(state, conf_set, sc_conf_66, other_set) { + var i; + { + (i = (other_set[(2)])); + while ((i>=(0))) { + if (((conf_set[(i+(5))])=== false)) + { + (conf_set_adjoin(state, conf_set, sc_conf_66, i)); + (i = (other_set[(i+(5))])); + } + else + (i = (other_set[(i+(5))])); + } + return undefined; + } + }; + forw = function(sc_states_67, BgL_sc_statezd2num_68zd2, sc_starters_69, sc_enders_70, sc_predictors_71, sc_steps_72, sc_nts_73) { + var next_set; + var next; + var conf_set; + var ender; + var l; + var starter_set; + var starter; + var sc_l_74; + var sc_loop1_75; + var head; + var BgL_sc_confzd2set_76zd2; + var BgL_sc_statezd2num_77zd2; + var state; + var sc_states_78; + var preds; + var BgL_sc_confzd2set_79zd2; + var step; + var sc_conf_80; + var BgL_sc_nbzd2nts_81zd2; + var sc_state_82; + { + (sc_state_82 = (sc_states_67[BgL_sc_statezd2num_68zd2])); + (BgL_sc_nbzd2nts_81zd2 = (sc_nts_73.length)); + while (true) { + { + (sc_conf_80 = (sc_state_82[(0)])); + if ((sc_conf_80>=(0))) + { + (step = (sc_steps_72[sc_conf_80])); + (BgL_sc_confzd2set_79zd2 = (sc_state_82[(sc_conf_80+(1))])); + (head = (BgL_sc_confzd2set_79zd2[(4)])); + (sc_state_82[(0)] = (BgL_sc_confzd2set_79zd2[(0)])); + (conf_set_merge_new_bang(BgL_sc_confzd2set_79zd2)); + if ((step>=(0))) + { + (sc_l_74 = (sc_starters_69[step])); + while ((sc_l_74 instanceof sc_Pair)) { + { + (starter = (sc_l_74.car)); + (starter_set = (BgL_sc_confzd2setzd2getza2_44za2(sc_state_82, BgL_sc_statezd2num_68zd2, starter))); + if (((starter_set[(BgL_sc_statezd2num_68zd2+(5))])=== false)) + { + (conf_set_adjoin(sc_state_82, starter_set, starter, BgL_sc_statezd2num_68zd2)); + (sc_l_74 = (sc_l_74.cdr)); + } + else + (sc_l_74 = (sc_l_74.cdr)); + } + } + (l = (sc_enders_70[step])); + while ((l instanceof sc_Pair)) { + { + (ender = (l.car)); + if ((((conf_set = (sc_state_82[(ender+(1))])), ((conf_set!== false)?(conf_set[(BgL_sc_statezd2num_68zd2+(5))]):false))!== false)) + { + (next = (sc_conf_80+(1))); + (next_set = (BgL_sc_confzd2setzd2getza2_44za2(sc_state_82, BgL_sc_statezd2num_68zd2, next))); + (conf_set_union(sc_state_82, next_set, next, BgL_sc_confzd2set_79zd2)); + (l = (l.cdr)); + } + else + (l = (l.cdr)); + } + } + } + else + { + (preds = (sc_predictors_71[(step+BgL_sc_nbzd2nts_81zd2)])); + (sc_states_78 = sc_states_67); + (state = sc_state_82); + (BgL_sc_statezd2num_77zd2 = BgL_sc_statezd2num_68zd2); + (BgL_sc_confzd2set_76zd2 = BgL_sc_confzd2set_79zd2); + sc_loop1_75 = function(l) { + var sc_state_83; + var BgL_sc_nextzd2set_84zd2; + var sc_next_85; + var pred_set; + var i; + var pred; + if ((l instanceof sc_Pair)) + { + (pred = (l.car)); + (i = head); + while ((i>=(0))) { + { + (pred_set = ((sc_state_83 = (sc_states_78[i])), (sc_state_83[(pred+(1))]))); + if ((pred_set!== false)) + { + (sc_next_85 = (pred+(1))); + (BgL_sc_nextzd2set_84zd2 = (BgL_sc_confzd2setzd2getza2_44za2(state, BgL_sc_statezd2num_77zd2, sc_next_85))); + (conf_set_union(state, BgL_sc_nextzd2set_84zd2, sc_next_85, pred_set)); + } + (i = (BgL_sc_confzd2set_76zd2[(i+(5))])); + } + } + return (sc_loop1_75((l.cdr))); + } + else + return undefined; + }; + (sc_loop1_75(preds)); + } + } + else + return undefined; + } + } + } + }; + is_parsed = function(nt, i, j, sc_nts_86, sc_enders_87, sc_states_88) { + var conf_set; + var state; + var sc_conf_89; + var l; + var BgL_sc_ntza2_90za2; + { + (BgL_sc_ntza2_90za2 = (sc_ind_43(nt, sc_nts_86))); + if ((BgL_sc_ntza2_90za2!== false)) + { + (sc_nts_86.length); + (l = (sc_enders_87[BgL_sc_ntza2_90za2])); + while (true) { + if ((l instanceof sc_Pair)) + { + (sc_conf_89 = (l.car)); + if ((((state = (sc_states_88[j])), (conf_set = (state[(sc_conf_89+(1))])), ((conf_set!== false)?(conf_set[(i+(5))]):false))!== false)) + return true; + else + (l = (l.cdr)); + } + else + return false; + } + } + else + return false; + } + }; + deriv_trees = function(sc_conf_91, i, j, sc_enders_92, sc_steps_93, sc_names_94, sc_toks_95, sc_states_96, BgL_sc_nbzd2nts_97zd2) { + var sc_loop1_98; + var prev; + var name; + return ((name = (sc_names_94[sc_conf_91])), ((name!== false)?((sc_conf_91=(0))) + if (((k>=i)&&(((sc_state_99 = (sc_states_96[k])), (conf_set = (sc_state_99[(prev+(1))])), ((conf_set!== false)?(conf_set[(i+(5))]):false))!== false))) + { + (prev_trees = (deriv_trees(prev, i, k, sc_enders_92, sc_steps_93, sc_names_94, sc_toks_95, sc_states_96, BgL_sc_nbzd2nts_97zd2))); + (ender_trees = (deriv_trees(ender, k, j, sc_enders_92, sc_steps_93, sc_names_94, sc_toks_95, sc_states_96, BgL_sc_nbzd2nts_97zd2))); + loop3 = function(l3, l2) { + var l4; + var sc_l2_100; + var ender_tree; + if ((l3 instanceof sc_Pair)) + { + (ender_tree = (sc_list((l3.car)))); + (l4 = prev_trees); + (sc_l2_100 = l2); + while ((l4 instanceof sc_Pair)) { + { + (sc_l2_100 = (new sc_Pair((sc_append((l4.car), ender_tree)), sc_l2_100))); + (l4 = (l4.cdr)); + } + } + return (loop3((l3.cdr), sc_l2_100)); + } + else + return (loop2((ender_set[(k+(5))]), l2)); + }; + return (loop3(ender_trees, l2)); + } + else + (k = (ender_set[(k+(5))])); + else + return (sc_loop1_98((l1.cdr), l2)); + } + }; + return (loop2((ender_set[(2)]), l2)); + } + else + (l1 = (l1.cdr)); + } + else + return l2; + } + }), (sc_loop1_98((sc_enders_92[(sc_steps_93[prev])]), null))))); + }; + BgL_sc_derivzd2treesza2_47z70 = function(nt, i, j, sc_nts_101, sc_enders_102, sc_steps_103, sc_names_104, sc_toks_105, sc_states_106) { + var conf_set; + var state; + var sc_conf_107; + var l; + var trees; + var BgL_sc_nbzd2nts_108zd2; + var BgL_sc_ntza2_109za2; + { + (BgL_sc_ntza2_109za2 = (sc_ind_43(nt, sc_nts_101))); + if ((BgL_sc_ntza2_109za2!== false)) + { + (BgL_sc_nbzd2nts_108zd2 = (sc_nts_101.length)); + (l = (sc_enders_102[BgL_sc_ntza2_109za2])); + (trees = null); + while ((l instanceof sc_Pair)) { + { + (sc_conf_107 = (l.car)); + if ((((state = (sc_states_106[j])), (conf_set = (state[(sc_conf_107+(1))])), ((conf_set!== false)?(conf_set[(i+(5))]):false))!== false)) + { + (l = (l.cdr)); + (trees = (sc_append((deriv_trees(sc_conf_107, i, j, sc_enders_102, sc_steps_103, sc_names_104, sc_toks_105, sc_states_106, BgL_sc_nbzd2nts_108zd2)), trees))); + } + else + (l = (l.cdr)); + } + } + return trees; + } + else + return false; + } + }; + nb_deriv_trees = function(sc_conf_110, i, j, sc_enders_111, sc_steps_112, sc_toks_113, sc_states_114, BgL_sc_nbzd2nts_115zd2) { + var sc_loop1_116; + var tmp1124; + var prev; + return ((prev = (sc_conf_110-(1))), ((((tmp1124 = (sc_conf_110=(0))) { + if (((k>=i)&&(((state = (sc_states_114[k])), (conf_set = (state[(prev+(1))])), ((conf_set!== false)?(conf_set[(i+(5))]):false))!== false))) + { + (nb_prev_trees = (nb_deriv_trees(prev, i, k, sc_enders_111, sc_steps_112, sc_toks_113, sc_states_114, BgL_sc_nbzd2nts_115zd2))); + (nb_ender_trees = (nb_deriv_trees(ender, k, j, sc_enders_111, sc_steps_112, sc_toks_113, sc_states_114, BgL_sc_nbzd2nts_115zd2))); + (k = (ender_set[(k+(5))])); + (n +=(nb_prev_trees*nb_ender_trees)); + } + else + (k = (ender_set[(k+(5))])); + } + return (sc_loop1_116((l.cdr), n)); + } + else + (l = (l.cdr)); + } + else + return sc_n_118; + } + }), (sc_loop1_116((sc_enders_111[(sc_steps_112[prev])]), (0)))))); + }; + BgL_sc_nbzd2derivzd2treesza2_48za2 = function(nt, i, j, sc_nts_119, sc_enders_120, sc_steps_121, sc_toks_122, sc_states_123) { + var conf_set; + var state; + var sc_conf_124; + var l; + var nb_trees; + var BgL_sc_nbzd2nts_125zd2; + var BgL_sc_ntza2_126za2; + { + (BgL_sc_ntza2_126za2 = (sc_ind_43(nt, sc_nts_119))); + if ((BgL_sc_ntza2_126za2!== false)) + { + (BgL_sc_nbzd2nts_125zd2 = (sc_nts_119.length)); + (l = (sc_enders_120[BgL_sc_ntza2_126za2])); + (nb_trees = (0)); + while ((l instanceof sc_Pair)) { + { + (sc_conf_124 = (l.car)); + if ((((state = (sc_states_123[j])), (conf_set = (state[(sc_conf_124+(1))])), ((conf_set!== false)?(conf_set[(i+(5))]):false))!== false)) + { + (l = (l.cdr)); + (nb_trees = ((nb_deriv_trees(sc_conf_124, i, j, sc_enders_120, sc_steps_121, sc_toks_122, sc_states_123, BgL_sc_nbzd2nts_125zd2))+nb_trees)); + } + else + (l = (l.cdr)); + } + } + return nb_trees; + } + else + return false; + } + }; + (lexer = (parser_descr[(0)])); + (sc_nts_42 = (parser_descr[(1)])); + (sc_starters_41 = (parser_descr[(2)])); + (sc_enders_40 = (parser_descr[(3)])); + (sc_predictors_39 = (parser_descr[(4)])); + (sc_steps_38 = (parser_descr[(5)])); + (sc_names_37 = (parser_descr[(6)])); + (falseHead1128 = (new sc_Pair(null, null))); + (L1125 = (lexer(input))); + (tail1129 = falseHead1128); + while (!(L1125 === null)) { + { + (tok = (L1125.car)); + (l1 = (tok.cdr)); + (l2 = null); + while ((l1 instanceof sc_Pair)) { + { + (sc_i_29 = (sc_ind_43((l1.car), sc_nts_42))); + if ((sc_i_29!== false)) + { + (l1 = (l1.cdr)); + (l2 = (new sc_Pair(sc_i_29, l2))); + } + else + (l1 = (l1.cdr)); + } + } + (sc_optrOpnd_22 = (new sc_Pair((tok.car), (sc_reverse(l2))))); + (sc_optrOpnd_21 = (new sc_Pair(sc_optrOpnd_22, null))); + (tail1129.cdr = sc_optrOpnd_21); + (tail1129 = (tail1129.cdr)); + (L1125 = (L1125.cdr)); + } + } + (sc_optrOpnd_20 = (falseHead1128.cdr)); + (sc_toks_36 = (sc_list2vector(sc_optrOpnd_20))); + (BgL_sc_nbzd2toks_35zd2 = (sc_toks_36.length)); + (BgL_sc_nbzd2confs_34zd2 = (sc_steps_38.length)); + (sc_states_33 = (make_states(BgL_sc_nbzd2toks_35zd2, BgL_sc_nbzd2confs_34zd2))); + (goal_starters = (sc_starters_41[(0)])); + (BgL_sc_confzd2setzd2adjoinza2_45za2(sc_states_33, (0), goal_starters, (0))); + (forw(sc_states_33, (0), sc_starters_41, sc_enders_40, sc_predictors_39, sc_steps_38, sc_nts_42)); + (sc_i_28 = (0)); + while ((sc_i_28=(0))) { + { + (states = sc_states_33); + (BgL_sc_statesza2_27za2 = BgL_sc_statesza2_30za2); + (state_num = i); + (sc_enders_26 = sc_enders_40); + (sc_steps_25 = sc_steps_38); + (BgL_sc_nbzd2nts_24zd2 = BgL_sc_nbzd2nts_31zd2); + (toks = sc_toks_36); + (BgL_sc_stateza2_23za2 = (BgL_sc_statesza2_30za2[i])); + loop1 = function() { + var sc_loop1_127; + var prev; + var BgL_sc_statesza2_128za2; + var sc_states_129; + var j; + var i; + var sc_i_130; + var head; + var conf_set; + var sc_conf_131; + { + (sc_conf_131 = (BgL_sc_stateza2_23za2[(0)])); + if ((sc_conf_131>=(0))) + { + (conf_set = (BgL_sc_stateza2_23za2[(sc_conf_131+(1))])); + (head = (conf_set[(4)])); + (BgL_sc_stateza2_23za2[(0)] = (conf_set[(0)])); + (conf_set_merge_new_bang(conf_set)); + (sc_i_130 = head); + while ((sc_i_130>=(0))) { + { + (i = sc_i_130); + (j = state_num); + (sc_states_129 = states); + (BgL_sc_statesza2_128za2 = BgL_sc_statesza2_27za2); + (prev = (sc_conf_131-(1))); + if (((sc_conf_131>=BgL_sc_nbzd2nts_24zd2)&&((sc_steps_25[prev])>=(0)))) + { + sc_loop1_127 = function(l) { + var k; + var ender_set; + var state; + var ender; + var l; + while (true) { + if ((l instanceof sc_Pair)) + { + (ender = (l.car)); + (ender_set = ((state = (sc_states_129[j])), (state[(ender+(1))]))); + if ((ender_set!== false)) + { + (k = (ender_set[(2)])); + while ((k>=(0))) { + { + if ((k>=i)) + if (((BgL_sc_confzd2setzd2adjoinza2za2_46z00(sc_states_129, BgL_sc_statesza2_128za2, k, prev, i))!== false)) + (BgL_sc_confzd2setzd2adjoinza2za2_46z00(sc_states_129, BgL_sc_statesza2_128za2, j, ender, k)); + (k = (ender_set[(k+(5))])); + } + } + return (sc_loop1_127((l.cdr))); + } + else + (l = (l.cdr)); + } + else + return undefined; + } + }; + (sc_loop1_127((sc_enders_26[(sc_steps_25[prev])]))); + } + (sc_i_130 = (conf_set[(sc_i_130+(5))])); + } + } + return (loop1()); + } + else + return undefined; + } + }; + (loop1()); + (--i); + } + } + (optrOpnd = BgL_sc_statesza2_30za2); + return [sc_nts_42, sc_starters_41, sc_enders_40, sc_predictors_39, sc_steps_38, sc_names_37, sc_toks_36, optrOpnd, is_parsed, BgL_sc_derivzd2treesza2_47z70, BgL_sc_nbzd2derivzd2treesza2_48za2]; + } + }; + } + }; + BgL_parsezd2ze3parsedzf3zc2 = function(parse, nt, i, j) { + var is_parsed; + var states; + var enders; + var nts; + return ((nts = (parse[(0)])), (enders = (parse[(2)])), (states = (parse[(7)])), (is_parsed = (parse[(8)])), (is_parsed(nt, i, j, nts, enders, states))); + }; + BgL_parsezd2ze3treesz31 = function(parse, nt, i, j) { + var BgL_sc_derivzd2treesza2_132z70; + var states; + var toks; + var names; + var steps; + var enders; + var nts; + return ((nts = (parse[(0)])), (enders = (parse[(2)])), (steps = (parse[(4)])), (names = (parse[(5)])), (toks = (parse[(6)])), (states = (parse[(7)])), (BgL_sc_derivzd2treesza2_132z70 = (parse[(9)])), (BgL_sc_derivzd2treesza2_132z70(nt, i, j, nts, enders, steps, names, toks, states))); + }; + BgL_parsezd2ze3nbzd2treesze3 = function(parse, nt, i, j) { + var BgL_sc_nbzd2derivzd2treesza2_133za2; + var states; + var toks; + var steps; + var enders; + var nts; + return ((nts = (parse[(0)])), (enders = (parse[(2)])), (steps = (parse[(4)])), (toks = (parse[(6)])), (states = (parse[(7)])), (BgL_sc_nbzd2derivzd2treesza2_133za2 = (parse[(10)])), (BgL_sc_nbzd2derivzd2treesza2_133za2(nt, i, j, nts, enders, steps, toks, states))); + }; + test = function(k) { + var x; + var p; + return ((p = (BgL_makezd2parserzd2(const_earley, function(l) { + var sc_x_134; + var tail1134; + var L1130; + var falseHead1133; + { + (falseHead1133 = (new sc_Pair(null, null))); + (tail1134 = falseHead1133); + (L1130 = l); + while (!(L1130 === null)) { + { + (tail1134.cdr = (new sc_Pair(((sc_x_134 = (L1130.car)), (sc_list(sc_x_134, sc_x_134))), null))); + (tail1134 = (tail1134.cdr)); + (L1130 = (L1130.cdr)); + } + } + return (falseHead1133.cdr); + } + }))), (x = (p((sc_vector2list((sc_makeVector(k, "\u1E9Ca"))))))), (sc_length((BgL_parsezd2ze3treesz31(x, "\u1E9Cs", (0), k))))); + }; + BgL_earleyzd2benchmarkzd2 = function() { + var args = null; + for (var sc_tmp = arguments.length - 1; sc_tmp >= 0; sc_tmp--) { + args = sc_cons(arguments[sc_tmp], args); + } + var k; + return ((k = ((args === null)?(7):(args.car))), (BgL_runzd2benchmarkzd2("earley", (1), function() { + return (test(k)); + }, function(result) { + return ((sc_display(result)), (sc_newline()), result == 132); + }))); + }; +} + + +/************* END OF GENERATED CODE *************/ +// Invoke this function to run a benchmark. +// The first argument is a string identifying the benchmark. +// The second argument is the number of times to run the benchmark. +// The third argument is a function that runs the benchmark. +// The fourth argument is a unary function that warns if the result +// returned by the benchmark is incorrect. +// +// Example: +// RunBenchmark("new Array()", +// 1, +// function () { new Array(1000000); } +// function (v) { +// return (v instanceof Array) && (v.length == 1000000); +// }); + +SC_DEFAULT_OUT = new sc_GenericOutputPort(function(s) {}); +SC_ERROR_OUT = SC_DEFAULT_OUT; + +function RunBenchmark(name, count, run, warn) { + for (var n = 0; n < count; ++n) { + result = run(); + if (!warn(result)) { + throw new Error("Earley or Boyer did incorrect number of rewrites"); + } + } +} + +var BgL_runzd2benchmarkzd2 = RunBenchmark; diff --git a/node-v0.8.14/deps/v8/benchmarks/navier-stokes.js b/node-v0.8.14/deps/v8/benchmarks/navier-stokes.js new file mode 100644 index 0000000..b0dc3c8 --- /dev/null +++ b/node-v0.8.14/deps/v8/benchmarks/navier-stokes.js @@ -0,0 +1,387 @@ +/** + * Copyright 2012 the V8 project authors. All rights reserved. + * Copyright 2009 Oliver Hunt + * + * Permission is hereby granted, free of charge, to any person + * obtaining a copy of this software and associated documentation + * files (the "Software"), to deal in the Software without + * restriction, including without limitation the rights to use, + * copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following + * conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES + * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + * OTHER DEALINGS IN THE SOFTWARE. + */ + +var NavierStokes = new BenchmarkSuite('NavierStokes', 1484000, + [new Benchmark('NavierStokes', + runNavierStokes, + setupNavierStokes, + tearDownNavierStokes)]); + +var solver = null; + +function runNavierStokes() +{ + solver.update(); +} + +function setupNavierStokes() +{ + solver = new FluidField(null); + solver.setResolution(128, 128); + solver.setIterations(20); + solver.setDisplayFunction(function(){}); + solver.setUICallback(prepareFrame); + solver.reset(); +} + +function tearDownNavierStokes() +{ + solver = null; +} + +function addPoints(field) { + var n = 64; + for (var i = 1; i <= n; i++) { + field.setVelocity(i, i, n, n); + field.setDensity(i, i, 5); + field.setVelocity(i, n - i, -n, -n); + field.setDensity(i, n - i, 20); + field.setVelocity(128 - i, n + i, -n, -n); + field.setDensity(128 - i, n + i, 30); + } +} + +var framesTillAddingPoints = 0; +var framesBetweenAddingPoints = 5; + +function prepareFrame(field) +{ + if (framesTillAddingPoints == 0) { + addPoints(field); + framesTillAddingPoints = framesBetweenAddingPoints; + framesBetweenAddingPoints++; + } else { + framesTillAddingPoints--; + } +} + +// Code from Oliver Hunt (http://nerget.com/fluidSim/pressure.js) starts here. +function FluidField(canvas) { + function addFields(x, s, dt) + { + for (var i=0; i Wp5) + x = Wp5; + var i0 = x | 0; + var i1 = i0 + 1; + if (y < 0.5) + y = 0.5; + else if (y > Hp5) + y = Hp5; + var j0 = y | 0; + var j1 = j0 + 1; + var s1 = x - i0; + var s0 = 1 - s1; + var t1 = y - j0; + var t0 = 1 - t1; + var row1 = j0 * rowSize; + var row2 = j1 * rowSize; + d[pos] = s0 * (t0 * d0[i0 + row1] + t1 * d0[i0 + row2]) + s1 * (t0 * d0[i1 + row1] + t1 * d0[i1 + row2]); + } + } + set_bnd(b, d); + } + + function project(u, v, p, div) + { + var h = -0.5 / Math.sqrt(width * height); + for (var j = 1 ; j <= height; j++ ) { + var row = j * rowSize; + var previousRow = (j - 1) * rowSize; + var prevValue = row - 1; + var currentRow = row; + var nextValue = row + 1; + var nextRow = (j + 1) * rowSize; + for (var i = 1; i <= width; i++ ) { + div[++currentRow] = h * (u[++nextValue] - u[++prevValue] + v[++nextRow] - v[++previousRow]); + p[currentRow] = 0; + } + } + set_bnd(0, div); + set_bnd(0, p); + + lin_solve(0, p, div, 1, 4 ); + var wScale = 0.5 * width; + var hScale = 0.5 * height; + for (var j = 1; j<= height; j++ ) { + var prevPos = j * rowSize - 1; + var currentPos = j * rowSize; + var nextPos = j * rowSize + 1; + var prevRow = (j - 1) * rowSize; + var currentRow = j * rowSize; + var nextRow = (j + 1) * rowSize; + + for (var i = 1; i<= width; i++) { + u[++currentPos] -= wScale * (p[++nextPos] - p[++prevPos]); + v[currentPos] -= hScale * (p[++nextRow] - p[++prevRow]); + } + } + set_bnd(1, u); + set_bnd(2, v); + } + + function dens_step(x, x0, u, v, dt) + { + addFields(x, x0, dt); + diffuse(0, x0, x, dt ); + advect(0, x, x0, u, v, dt ); + } + + function vel_step(u, v, u0, v0, dt) + { + addFields(u, u0, dt ); + addFields(v, v0, dt ); + var temp = u0; u0 = u; u = temp; + var temp = v0; v0 = v; v = temp; + diffuse2(u,u0,v,v0, dt); + project(u, v, u0, v0); + var temp = u0; u0 = u; u = temp; + var temp = v0; v0 = v; v = temp; + advect(1, u, u0, u0, v0, dt); + advect(2, v, v0, u0, v0, dt); + project(u, v, u0, v0 ); + } + var uiCallback = function(d,u,v) {}; + + function Field(dens, u, v) { + // Just exposing the fields here rather than using accessors is a measurable win during display (maybe 5%) + // but makes the code ugly. + this.setDensity = function(x, y, d) { + dens[(x + 1) + (y + 1) * rowSize] = d; + } + this.getDensity = function(x, y) { + return dens[(x + 1) + (y + 1) * rowSize]; + } + this.setVelocity = function(x, y, xv, yv) { + u[(x + 1) + (y + 1) * rowSize] = xv; + v[(x + 1) + (y + 1) * rowSize] = yv; + } + this.getXVelocity = function(x, y) { + return u[(x + 1) + (y + 1) * rowSize]; + } + this.getYVelocity = function(x, y) { + return v[(x + 1) + (y + 1) * rowSize]; + } + this.width = function() { return width; } + this.height = function() { return height; } + } + function queryUI(d, u, v) + { + for (var i = 0; i < size; i++) + u[i] = v[i] = d[i] = 0.0; + uiCallback(new Field(d, u, v)); + } + + this.update = function () { + queryUI(dens_prev, u_prev, v_prev); + vel_step(u, v, u_prev, v_prev, dt); + dens_step(dens, dens_prev, u, v, dt); + displayFunc(new Field(dens, u, v)); + } + this.setDisplayFunction = function(func) { + displayFunc = func; + } + + this.iterations = function() { return iterations; } + this.setIterations = function(iters) { + if (iters > 0 && iters <= 100) + iterations = iters; + } + this.setUICallback = function(callback) { + uiCallback = callback; + } + var iterations = 10; + var visc = 0.5; + var dt = 0.1; + var dens; + var dens_prev; + var u; + var u_prev; + var v; + var v_prev; + var width; + var height; + var rowSize; + var size; + var displayFunc; + function reset() + { + rowSize = width + 2; + size = (width+2)*(height+2); + dens = new Array(size); + dens_prev = new Array(size); + u = new Array(size); + u_prev = new Array(size); + v = new Array(size); + v_prev = new Array(size); + for (var i = 0; i < size; i++) + dens_prev[i] = u_prev[i] = v_prev[i] = dens[i] = u[i] = v[i] = 0; + } + this.reset = reset; + this.setResolution = function (hRes, wRes) + { + var res = wRes * hRes; + if (res > 0 && res < 1000000 && (wRes != width || hRes != height)) { + width = wRes; + height = hRes; + reset(); + return true; + } + return false; + } + this.setResolution(64, 64); +} diff --git a/node-v0.8.14/deps/v8/benchmarks/raytrace.js b/node-v0.8.14/deps/v8/benchmarks/raytrace.js new file mode 100644 index 0000000..971ef72 --- /dev/null +++ b/node-v0.8.14/deps/v8/benchmarks/raytrace.js @@ -0,0 +1,904 @@ +// The ray tracer code in this file is written by Adam Burmister. It +// is available in its original form from: +// +// http://labs.flog.nz.co/raytracer/ +// +// It has been modified slightly by Google to work as a standalone +// benchmark, but the all the computational code remains +// untouched. This file also contains a copy of parts of the Prototype +// JavaScript framework which is used by the ray tracer. + +var RayTrace = new BenchmarkSuite('RayTrace', 739989, [ + new Benchmark('RayTrace', renderScene) +]); + + +// Variable used to hold a number that can be used to verify that +// the scene was ray traced correctly. +var checkNumber; + + +// ------------------------------------------------------------------------ +// ------------------------------------------------------------------------ + +// The following is a copy of parts of the Prototype JavaScript library: + +// Prototype JavaScript framework, version 1.5.0 +// (c) 2005-2007 Sam Stephenson +// +// Prototype is freely distributable under the terms of an MIT-style license. +// For details, see the Prototype web site: http://prototype.conio.net/ + + +var Class = { + create: function() { + return function() { + this.initialize.apply(this, arguments); + } + } +}; + + +Object.extend = function(destination, source) { + for (var property in source) { + destination[property] = source[property]; + } + return destination; +}; + + +// ------------------------------------------------------------------------ +// ------------------------------------------------------------------------ + +// The rest of this file is the actual ray tracer written by Adam +// Burmister. It's a concatenation of the following files: +// +// flog/color.js +// flog/light.js +// flog/vector.js +// flog/ray.js +// flog/scene.js +// flog/material/basematerial.js +// flog/material/solid.js +// flog/material/chessboard.js +// flog/shape/baseshape.js +// flog/shape/sphere.js +// flog/shape/plane.js +// flog/intersectioninfo.js +// flog/camera.js +// flog/background.js +// flog/engine.js + + +/* Fake a Flog.* namespace */ +if(typeof(Flog) == 'undefined') var Flog = {}; +if(typeof(Flog.RayTracer) == 'undefined') Flog.RayTracer = {}; + +Flog.RayTracer.Color = Class.create(); + +Flog.RayTracer.Color.prototype = { + red : 0.0, + green : 0.0, + blue : 0.0, + + initialize : function(r, g, b) { + if(!r) r = 0.0; + if(!g) g = 0.0; + if(!b) b = 0.0; + + this.red = r; + this.green = g; + this.blue = b; + }, + + add : function(c1, c2){ + var result = new Flog.RayTracer.Color(0,0,0); + + result.red = c1.red + c2.red; + result.green = c1.green + c2.green; + result.blue = c1.blue + c2.blue; + + return result; + }, + + addScalar: function(c1, s){ + var result = new Flog.RayTracer.Color(0,0,0); + + result.red = c1.red + s; + result.green = c1.green + s; + result.blue = c1.blue + s; + + result.limit(); + + return result; + }, + + subtract: function(c1, c2){ + var result = new Flog.RayTracer.Color(0,0,0); + + result.red = c1.red - c2.red; + result.green = c1.green - c2.green; + result.blue = c1.blue - c2.blue; + + return result; + }, + + multiply : function(c1, c2) { + var result = new Flog.RayTracer.Color(0,0,0); + + result.red = c1.red * c2.red; + result.green = c1.green * c2.green; + result.blue = c1.blue * c2.blue; + + return result; + }, + + multiplyScalar : function(c1, f) { + var result = new Flog.RayTracer.Color(0,0,0); + + result.red = c1.red * f; + result.green = c1.green * f; + result.blue = c1.blue * f; + + return result; + }, + + divideFactor : function(c1, f) { + var result = new Flog.RayTracer.Color(0,0,0); + + result.red = c1.red / f; + result.green = c1.green / f; + result.blue = c1.blue / f; + + return result; + }, + + limit: function(){ + this.red = (this.red > 0.0) ? ( (this.red > 1.0) ? 1.0 : this.red ) : 0.0; + this.green = (this.green > 0.0) ? ( (this.green > 1.0) ? 1.0 : this.green ) : 0.0; + this.blue = (this.blue > 0.0) ? ( (this.blue > 1.0) ? 1.0 : this.blue ) : 0.0; + }, + + distance : function(color) { + var d = Math.abs(this.red - color.red) + Math.abs(this.green - color.green) + Math.abs(this.blue - color.blue); + return d; + }, + + blend: function(c1, c2, w){ + var result = new Flog.RayTracer.Color(0,0,0); + result = Flog.RayTracer.Color.prototype.add( + Flog.RayTracer.Color.prototype.multiplyScalar(c1, 1 - w), + Flog.RayTracer.Color.prototype.multiplyScalar(c2, w) + ); + return result; + }, + + brightness : function() { + var r = Math.floor(this.red*255); + var g = Math.floor(this.green*255); + var b = Math.floor(this.blue*255); + return (r * 77 + g * 150 + b * 29) >> 8; + }, + + toString : function () { + var r = Math.floor(this.red*255); + var g = Math.floor(this.green*255); + var b = Math.floor(this.blue*255); + + return "rgb("+ r +","+ g +","+ b +")"; + } +} +/* Fake a Flog.* namespace */ +if(typeof(Flog) == 'undefined') var Flog = {}; +if(typeof(Flog.RayTracer) == 'undefined') Flog.RayTracer = {}; + +Flog.RayTracer.Light = Class.create(); + +Flog.RayTracer.Light.prototype = { + position: null, + color: null, + intensity: 10.0, + + initialize : function(pos, color, intensity) { + this.position = pos; + this.color = color; + this.intensity = (intensity ? intensity : 10.0); + }, + + toString : function () { + return 'Light [' + this.position.x + ',' + this.position.y + ',' + this.position.z + ']'; + } +} +/* Fake a Flog.* namespace */ +if(typeof(Flog) == 'undefined') var Flog = {}; +if(typeof(Flog.RayTracer) == 'undefined') Flog.RayTracer = {}; + +Flog.RayTracer.Vector = Class.create(); + +Flog.RayTracer.Vector.prototype = { + x : 0.0, + y : 0.0, + z : 0.0, + + initialize : function(x, y, z) { + this.x = (x ? x : 0); + this.y = (y ? y : 0); + this.z = (z ? z : 0); + }, + + copy: function(vector){ + this.x = vector.x; + this.y = vector.y; + this.z = vector.z; + }, + + normalize : function() { + var m = this.magnitude(); + return new Flog.RayTracer.Vector(this.x / m, this.y / m, this.z / m); + }, + + magnitude : function() { + return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z)); + }, + + cross : function(w) { + return new Flog.RayTracer.Vector( + -this.z * w.y + this.y * w.z, + this.z * w.x - this.x * w.z, + -this.y * w.x + this.x * w.y); + }, + + dot : function(w) { + return this.x * w.x + this.y * w.y + this.z * w.z; + }, + + add : function(v, w) { + return new Flog.RayTracer.Vector(w.x + v.x, w.y + v.y, w.z + v.z); + }, + + subtract : function(v, w) { + if(!w || !v) throw 'Vectors must be defined [' + v + ',' + w + ']'; + return new Flog.RayTracer.Vector(v.x - w.x, v.y - w.y, v.z - w.z); + }, + + multiplyVector : function(v, w) { + return new Flog.RayTracer.Vector(v.x * w.x, v.y * w.y, v.z * w.z); + }, + + multiplyScalar : function(v, w) { + return new Flog.RayTracer.Vector(v.x * w, v.y * w, v.z * w); + }, + + toString : function () { + return 'Vector [' + this.x + ',' + this.y + ',' + this.z + ']'; + } +} +/* Fake a Flog.* namespace */ +if(typeof(Flog) == 'undefined') var Flog = {}; +if(typeof(Flog.RayTracer) == 'undefined') Flog.RayTracer = {}; + +Flog.RayTracer.Ray = Class.create(); + +Flog.RayTracer.Ray.prototype = { + position : null, + direction : null, + initialize : function(pos, dir) { + this.position = pos; + this.direction = dir; + }, + + toString : function () { + return 'Ray [' + this.position + ',' + this.direction + ']'; + } +} +/* Fake a Flog.* namespace */ +if(typeof(Flog) == 'undefined') var Flog = {}; +if(typeof(Flog.RayTracer) == 'undefined') Flog.RayTracer = {}; + +Flog.RayTracer.Scene = Class.create(); + +Flog.RayTracer.Scene.prototype = { + camera : null, + shapes : [], + lights : [], + background : null, + + initialize : function() { + this.camera = new Flog.RayTracer.Camera( + new Flog.RayTracer.Vector(0,0,-5), + new Flog.RayTracer.Vector(0,0,1), + new Flog.RayTracer.Vector(0,1,0) + ); + this.shapes = new Array(); + this.lights = new Array(); + this.background = new Flog.RayTracer.Background(new Flog.RayTracer.Color(0,0,0.5), 0.2); + } +} +/* Fake a Flog.* namespace */ +if(typeof(Flog) == 'undefined') var Flog = {}; +if(typeof(Flog.RayTracer) == 'undefined') Flog.RayTracer = {}; +if(typeof(Flog.RayTracer.Material) == 'undefined') Flog.RayTracer.Material = {}; + +Flog.RayTracer.Material.BaseMaterial = Class.create(); + +Flog.RayTracer.Material.BaseMaterial.prototype = { + + gloss: 2.0, // [0...infinity] 0 = matt + transparency: 0.0, // 0=opaque + reflection: 0.0, // [0...infinity] 0 = no reflection + refraction: 0.50, + hasTexture: false, + + initialize : function() { + + }, + + getColor: function(u, v){ + + }, + + wrapUp: function(t){ + t = t % 2.0; + if(t < -1) t += 2.0; + if(t >= 1) t -= 2.0; + return t; + }, + + toString : function () { + return 'Material [gloss=' + this.gloss + ', transparency=' + this.transparency + ', hasTexture=' + this.hasTexture +']'; + } +} +/* Fake a Flog.* namespace */ +if(typeof(Flog) == 'undefined') var Flog = {}; +if(typeof(Flog.RayTracer) == 'undefined') Flog.RayTracer = {}; + +Flog.RayTracer.Material.Solid = Class.create(); + +Flog.RayTracer.Material.Solid.prototype = Object.extend( + new Flog.RayTracer.Material.BaseMaterial(), { + initialize : function(color, reflection, refraction, transparency, gloss) { + this.color = color; + this.reflection = reflection; + this.transparency = transparency; + this.gloss = gloss; + this.hasTexture = false; + }, + + getColor: function(u, v){ + return this.color; + }, + + toString : function () { + return 'SolidMaterial [gloss=' + this.gloss + ', transparency=' + this.transparency + ', hasTexture=' + this.hasTexture +']'; + } + } +); +/* Fake a Flog.* namespace */ +if(typeof(Flog) == 'undefined') var Flog = {}; +if(typeof(Flog.RayTracer) == 'undefined') Flog.RayTracer = {}; + +Flog.RayTracer.Material.Chessboard = Class.create(); + +Flog.RayTracer.Material.Chessboard.prototype = Object.extend( + new Flog.RayTracer.Material.BaseMaterial(), { + colorEven: null, + colorOdd: null, + density: 0.5, + + initialize : function(colorEven, colorOdd, reflection, transparency, gloss, density) { + this.colorEven = colorEven; + this.colorOdd = colorOdd; + this.reflection = reflection; + this.transparency = transparency; + this.gloss = gloss; + this.density = density; + this.hasTexture = true; + }, + + getColor: function(u, v){ + var t = this.wrapUp(u * this.density) * this.wrapUp(v * this.density); + + if(t < 0.0) + return this.colorEven; + else + return this.colorOdd; + }, + + toString : function () { + return 'ChessMaterial [gloss=' + this.gloss + ', transparency=' + this.transparency + ', hasTexture=' + this.hasTexture +']'; + } + } +); +/* Fake a Flog.* namespace */ +if(typeof(Flog) == 'undefined') var Flog = {}; +if(typeof(Flog.RayTracer) == 'undefined') Flog.RayTracer = {}; +if(typeof(Flog.RayTracer.Shape) == 'undefined') Flog.RayTracer.Shape = {}; + +Flog.RayTracer.Shape.Sphere = Class.create(); + +Flog.RayTracer.Shape.Sphere.prototype = { + initialize : function(pos, radius, material) { + this.radius = radius; + this.position = pos; + this.material = material; + }, + + intersect: function(ray){ + var info = new Flog.RayTracer.IntersectionInfo(); + info.shape = this; + + var dst = Flog.RayTracer.Vector.prototype.subtract(ray.position, this.position); + + var B = dst.dot(ray.direction); + var C = dst.dot(dst) - (this.radius * this.radius); + var D = (B * B) - C; + + if(D > 0){ // intersection! + info.isHit = true; + info.distance = (-B) - Math.sqrt(D); + info.position = Flog.RayTracer.Vector.prototype.add( + ray.position, + Flog.RayTracer.Vector.prototype.multiplyScalar( + ray.direction, + info.distance + ) + ); + info.normal = Flog.RayTracer.Vector.prototype.subtract( + info.position, + this.position + ).normalize(); + + info.color = this.material.getColor(0,0); + } else { + info.isHit = false; + } + return info; + }, + + toString : function () { + return 'Sphere [position=' + this.position + ', radius=' + this.radius + ']'; + } +} +/* Fake a Flog.* namespace */ +if(typeof(Flog) == 'undefined') var Flog = {}; +if(typeof(Flog.RayTracer) == 'undefined') Flog.RayTracer = {}; +if(typeof(Flog.RayTracer.Shape) == 'undefined') Flog.RayTracer.Shape = {}; + +Flog.RayTracer.Shape.Plane = Class.create(); + +Flog.RayTracer.Shape.Plane.prototype = { + d: 0.0, + + initialize : function(pos, d, material) { + this.position = pos; + this.d = d; + this.material = material; + }, + + intersect: function(ray){ + var info = new Flog.RayTracer.IntersectionInfo(); + + var Vd = this.position.dot(ray.direction); + if(Vd == 0) return info; // no intersection + + var t = -(this.position.dot(ray.position) + this.d) / Vd; + if(t <= 0) return info; + + info.shape = this; + info.isHit = true; + info.position = Flog.RayTracer.Vector.prototype.add( + ray.position, + Flog.RayTracer.Vector.prototype.multiplyScalar( + ray.direction, + t + ) + ); + info.normal = this.position; + info.distance = t; + + if(this.material.hasTexture){ + var vU = new Flog.RayTracer.Vector(this.position.y, this.position.z, -this.position.x); + var vV = vU.cross(this.position); + var u = info.position.dot(vU); + var v = info.position.dot(vV); + info.color = this.material.getColor(u,v); + } else { + info.color = this.material.getColor(0,0); + } + + return info; + }, + + toString : function () { + return 'Plane [' + this.position + ', d=' + this.d + ']'; + } +} +/* Fake a Flog.* namespace */ +if(typeof(Flog) == 'undefined') var Flog = {}; +if(typeof(Flog.RayTracer) == 'undefined') Flog.RayTracer = {}; + +Flog.RayTracer.IntersectionInfo = Class.create(); + +Flog.RayTracer.IntersectionInfo.prototype = { + isHit: false, + hitCount: 0, + shape: null, + position: null, + normal: null, + color: null, + distance: null, + + initialize : function() { + this.color = new Flog.RayTracer.Color(0,0,0); + }, + + toString : function () { + return 'Intersection [' + this.position + ']'; + } +} +/* Fake a Flog.* namespace */ +if(typeof(Flog) == 'undefined') var Flog = {}; +if(typeof(Flog.RayTracer) == 'undefined') Flog.RayTracer = {}; + +Flog.RayTracer.Camera = Class.create(); + +Flog.RayTracer.Camera.prototype = { + position: null, + lookAt: null, + equator: null, + up: null, + screen: null, + + initialize : function(pos, lookAt, up) { + this.position = pos; + this.lookAt = lookAt; + this.up = up; + this.equator = lookAt.normalize().cross(this.up); + this.screen = Flog.RayTracer.Vector.prototype.add(this.position, this.lookAt); + }, + + getRay: function(vx, vy){ + var pos = Flog.RayTracer.Vector.prototype.subtract( + this.screen, + Flog.RayTracer.Vector.prototype.subtract( + Flog.RayTracer.Vector.prototype.multiplyScalar(this.equator, vx), + Flog.RayTracer.Vector.prototype.multiplyScalar(this.up, vy) + ) + ); + pos.y = pos.y * -1; + var dir = Flog.RayTracer.Vector.prototype.subtract( + pos, + this.position + ); + + var ray = new Flog.RayTracer.Ray(pos, dir.normalize()); + + return ray; + }, + + toString : function () { + return 'Ray []'; + } +} +/* Fake a Flog.* namespace */ +if(typeof(Flog) == 'undefined') var Flog = {}; +if(typeof(Flog.RayTracer) == 'undefined') Flog.RayTracer = {}; + +Flog.RayTracer.Background = Class.create(); + +Flog.RayTracer.Background.prototype = { + color : null, + ambience : 0.0, + + initialize : function(color, ambience) { + this.color = color; + this.ambience = ambience; + } +} +/* Fake a Flog.* namespace */ +if(typeof(Flog) == 'undefined') var Flog = {}; +if(typeof(Flog.RayTracer) == 'undefined') Flog.RayTracer = {}; + +Flog.RayTracer.Engine = Class.create(); + +Flog.RayTracer.Engine.prototype = { + canvas: null, /* 2d context we can render to */ + + initialize: function(options){ + this.options = Object.extend({ + canvasHeight: 100, + canvasWidth: 100, + pixelWidth: 2, + pixelHeight: 2, + renderDiffuse: false, + renderShadows: false, + renderHighlights: false, + renderReflections: false, + rayDepth: 2 + }, options || {}); + + this.options.canvasHeight /= this.options.pixelHeight; + this.options.canvasWidth /= this.options.pixelWidth; + + /* TODO: dynamically include other scripts */ + }, + + setPixel: function(x, y, color){ + var pxW, pxH; + pxW = this.options.pixelWidth; + pxH = this.options.pixelHeight; + + if (this.canvas) { + this.canvas.fillStyle = color.toString(); + this.canvas.fillRect (x * pxW, y * pxH, pxW, pxH); + } else { + if (x === y) { + checkNumber += color.brightness(); + } + // print(x * pxW, y * pxH, pxW, pxH); + } + }, + + renderScene: function(scene, canvas){ + checkNumber = 0; + /* Get canvas */ + if (canvas) { + this.canvas = canvas.getContext("2d"); + } else { + this.canvas = null; + } + + var canvasHeight = this.options.canvasHeight; + var canvasWidth = this.options.canvasWidth; + + for(var y=0; y < canvasHeight; y++){ + for(var x=0; x < canvasWidth; x++){ + var yp = y * 1.0 / canvasHeight * 2 - 1; + var xp = x * 1.0 / canvasWidth * 2 - 1; + + var ray = scene.camera.getRay(xp, yp); + + var color = this.getPixelColor(ray, scene); + + this.setPixel(x, y, color); + } + } + if (checkNumber !== 2321) { + throw new Error("Scene rendered incorrectly"); + } + }, + + getPixelColor: function(ray, scene){ + var info = this.testIntersection(ray, scene, null); + if(info.isHit){ + var color = this.rayTrace(info, ray, scene, 0); + return color; + } + return scene.background.color; + }, + + testIntersection: function(ray, scene, exclude){ + var hits = 0; + var best = new Flog.RayTracer.IntersectionInfo(); + best.distance = 2000; + + for(var i=0; i= 0 && info.distance < best.distance){ + best = info; + hits++; + } + } + } + best.hitCount = hits; + return best; + }, + + getReflectionRay: function(P,N,V){ + var c1 = -N.dot(V); + var R1 = Flog.RayTracer.Vector.prototype.add( + Flog.RayTracer.Vector.prototype.multiplyScalar(N, 2*c1), + V + ); + return new Flog.RayTracer.Ray(P, R1); + }, + + rayTrace: function(info, ray, scene, depth){ + // Calc ambient + var color = Flog.RayTracer.Color.prototype.multiplyScalar(info.color, scene.background.ambience); + var oldColor = color; + var shininess = Math.pow(10, info.shape.material.gloss + 1); + + for(var i=0; i 0.0){ + color = Flog.RayTracer.Color.prototype.add( + color, + Flog.RayTracer.Color.prototype.multiply( + info.color, + Flog.RayTracer.Color.prototype.multiplyScalar( + light.color, + L + ) + ) + ); + } + } + + // The greater the depth the more accurate the colours, but + // this is exponentially (!) expensive + if(depth <= this.options.rayDepth){ + // calculate reflection ray + if(this.options.renderReflections && info.shape.material.reflection > 0) + { + var reflectionRay = this.getReflectionRay(info.position, info.normal, ray.direction); + var refl = this.testIntersection(reflectionRay, scene, info.shape); + + if (refl.isHit && refl.distance > 0){ + refl.color = this.rayTrace(refl, reflectionRay, scene, depth + 1); + } else { + refl.color = scene.background.color; + } + + color = Flog.RayTracer.Color.prototype.blend( + color, + refl.color, + info.shape.material.reflection + ); + } + + // Refraction + /* TODO */ + } + + /* Render shadows and highlights */ + + var shadowInfo = new Flog.RayTracer.IntersectionInfo(); + + if(this.options.renderShadows){ + var shadowRay = new Flog.RayTracer.Ray(info.position, v); + + shadowInfo = this.testIntersection(shadowRay, scene, info.shape); + if(shadowInfo.isHit && shadowInfo.shape != info.shape /*&& shadowInfo.shape.type != 'PLANE'*/){ + var vA = Flog.RayTracer.Color.prototype.multiplyScalar(color, 0.5); + var dB = (0.5 * Math.pow(shadowInfo.shape.material.transparency, 0.5)); + color = Flog.RayTracer.Color.prototype.addScalar(vA,dB); + } + } + + // Phong specular highlights + if(this.options.renderHighlights && !shadowInfo.isHit && info.shape.material.gloss > 0){ + var Lv = Flog.RayTracer.Vector.prototype.subtract( + info.shape.position, + light.position + ).normalize(); + + var E = Flog.RayTracer.Vector.prototype.subtract( + scene.camera.position, + info.shape.position + ).normalize(); + + var H = Flog.RayTracer.Vector.prototype.subtract( + E, + Lv + ).normalize(); + + var glossWeight = Math.pow(Math.max(info.normal.dot(H), 0), shininess); + color = Flog.RayTracer.Color.prototype.add( + Flog.RayTracer.Color.prototype.multiplyScalar(light.color, glossWeight), + color + ); + } + } + color.limit(); + return color; + } +}; + + +function renderScene(){ + var scene = new Flog.RayTracer.Scene(); + + scene.camera = new Flog.RayTracer.Camera( + new Flog.RayTracer.Vector(0, 0, -15), + new Flog.RayTracer.Vector(-0.2, 0, 5), + new Flog.RayTracer.Vector(0, 1, 0) + ); + + scene.background = new Flog.RayTracer.Background( + new Flog.RayTracer.Color(0.5, 0.5, 0.5), + 0.4 + ); + + var sphere = new Flog.RayTracer.Shape.Sphere( + new Flog.RayTracer.Vector(-1.5, 1.5, 2), + 1.5, + new Flog.RayTracer.Material.Solid( + new Flog.RayTracer.Color(0,0.5,0.5), + 0.3, + 0.0, + 0.0, + 2.0 + ) + ); + + var sphere1 = new Flog.RayTracer.Shape.Sphere( + new Flog.RayTracer.Vector(1, 0.25, 1), + 0.5, + new Flog.RayTracer.Material.Solid( + new Flog.RayTracer.Color(0.9,0.9,0.9), + 0.1, + 0.0, + 0.0, + 1.5 + ) + ); + + var plane = new Flog.RayTracer.Shape.Plane( + new Flog.RayTracer.Vector(0.1, 0.9, -0.5).normalize(), + 1.2, + new Flog.RayTracer.Material.Chessboard( + new Flog.RayTracer.Color(1,1,1), + new Flog.RayTracer.Color(0,0,0), + 0.2, + 0.0, + 1.0, + 0.7 + ) + ); + + scene.shapes.push(plane); + scene.shapes.push(sphere); + scene.shapes.push(sphere1); + + var light = new Flog.RayTracer.Light( + new Flog.RayTracer.Vector(5, 10, -1), + new Flog.RayTracer.Color(0.8, 0.8, 0.8) + ); + + var light1 = new Flog.RayTracer.Light( + new Flog.RayTracer.Vector(-3, 5, -15), + new Flog.RayTracer.Color(0.8, 0.8, 0.8), + 100 + ); + + scene.lights.push(light); + scene.lights.push(light1); + + var imageWidth = 100; // $F('imageWidth'); + var imageHeight = 100; // $F('imageHeight'); + var pixelSize = "5,5".split(','); // $F('pixelSize').split(','); + var renderDiffuse = true; // $F('renderDiffuse'); + var renderShadows = true; // $F('renderShadows'); + var renderHighlights = true; // $F('renderHighlights'); + var renderReflections = true; // $F('renderReflections'); + var rayDepth = 2;//$F('rayDepth'); + + var raytracer = new Flog.RayTracer.Engine( + { + canvasWidth: imageWidth, + canvasHeight: imageHeight, + pixelWidth: pixelSize[0], + pixelHeight: pixelSize[1], + "renderDiffuse": renderDiffuse, + "renderHighlights": renderHighlights, + "renderShadows": renderShadows, + "renderReflections": renderReflections, + "rayDepth": rayDepth + } + ); + + raytracer.renderScene(scene, null, 0); +} diff --git a/node-v0.8.14/deps/v8/benchmarks/regexp.js b/node-v0.8.14/deps/v8/benchmarks/regexp.js new file mode 100644 index 0000000..9c83142 --- /dev/null +++ b/node-v0.8.14/deps/v8/benchmarks/regexp.js @@ -0,0 +1,1764 @@ +// Copyright 2010 the V8 project authors. All rights reserved. +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following +// disclaimer in the documentation and/or other materials provided +// with the distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +// Automatically generated on 2009-01-30. Manually updated on 2010-09-17. + +// This benchmark is generated by loading 50 of the most popular pages +// on the web and logging all regexp operations performed. Each +// operation is given a weight that is calculated from an estimate of +// the popularity of the pages where it occurs and the number of times +// it is executed while loading each page. Furthermore the literal +// letters in the data are encoded using ROT13 in a way that does not +// affect how the regexps match their input. Finally the strings are +// scrambled to exercise the regexp engine on different input strings. + + +var RegExp = new BenchmarkSuite('RegExp', 910985, [ + new Benchmark("RegExp", RegExpRun, RegExpSetup, RegExpTearDown) +]); + +var regExpBenchmark = null; + +function RegExpSetup() { + regExpBenchmark = new RegExpBenchmark(); + RegExpRun(); // run once to get system initialized +} + +function RegExpRun() { + regExpBenchmark.run(); +} + +function RegExpTearDown() { + regExpBenchmark = null; +} + +// Returns an array of n different variants of the input string str. +// The variants are computed by randomly rotating one random +// character. +function computeInputVariants(str, n) { + var variants = [ str ]; + for (var i = 1; i < n; i++) { + var pos = Math.floor(Math.random() * str.length); + var chr = String.fromCharCode((str.charCodeAt(pos) + Math.floor(Math.random() * 128)) % 128); + variants[i] = str.substring(0, pos) + chr + str.substring(pos + 1, str.length); + } + return variants; +} + +function RegExpBenchmark() { + var re0 = /^ba/; + var re1 = /(((\w+):\/\/)([^\/:]*)(:(\d+))?)?([^#?]*)(\?([^#]*))?(#(.*))?/; + var re2 = /^\s*|\s*$/g; + var re3 = /\bQBZPbageby_cynprubyqre\b/; + var re4 = /,/; + var re5 = /\bQBZPbageby_cynprubyqre\b/g; + var re6 = /^[\s\xa0]+|[\s\xa0]+$/g; + var re7 = /(\d*)(\D*)/g; + var re8 = /=/; + var re9 = /(^|\s)lhv\-h(\s|$)/; + var str0 = 'Zbmvyyn/5.0 (Jvaqbjf; H; Jvaqbjf AG 5.1; ra-HF) NccyrJroXvg/528.9 (XUGZY, yvxr Trpxb) Puebzr/2.0.157.0 Fnsnev/528.9'; + var re10 = /\#/g; + var re11 = /\./g; + var re12 = /'/g; + var re13 = /\?[\w\W]*(sevraqvq|punaaryvq|tebhcvq)=([^\&\?#]*)/i; + var str1 = 'Fubpxjnir Synfu 9.0 e115'; + var re14 = /\s+/g; + var re15 = /^\s*(\S*(\s+\S+)*)\s*$/; + var re16 = /(-[a-z])/i; + + var s0 = computeInputVariants('pyvpx', 6511); + var s1 = computeInputVariants('uggc://jjj.snprobbx.pbz/ybtva.cuc', 1844); + var s2 = computeInputVariants('QBZPbageby_cynprubyqre', 739); + var s3 = computeInputVariants('uggc://jjj.snprobbx.pbz/', 598); + var s4 = computeInputVariants('uggc://jjj.snprobbx.pbz/fepu.cuc', 454); + var s5 = computeInputVariants('qqqq, ZZZ q, llll', 352); + var s6 = computeInputVariants('vachggrkg QBZPbageby_cynprubyqre', 312); + var s7 = computeInputVariants('/ZlFcnprUbzrcntr/Vaqrk-FvgrUbzr,10000000', 282); + var s8 = computeInputVariants('vachggrkg', 177); + var s9 = computeInputVariants('528.9', 170); + var s10 = computeInputVariants('528', 170); + var s11 = computeInputVariants('VCPhygher=ra-HF', 156); + var s12 = computeInputVariants('CersreerqPhygher=ra-HF', 156); + var s13 = computeInputVariants('xrlcerff', 144); + var s14 = computeInputVariants('521', 139); + var s15 = computeInputVariants(str0, 139); + var s16 = computeInputVariants('qvi .so_zrah', 137); + var s17 = computeInputVariants('qvi.so_zrah', 137); + var s18 = computeInputVariants('uvqqra_ryrz', 117); + var s19 = computeInputVariants('sevraqfgre_naba=nvq%3Qn6ss9p85n868ro9s059pn854735956o3%26ers%3Q%26df%3Q%26vpgl%3QHF', 95); + var s20 = computeInputVariants('uggc://ubzr.zlfcnpr.pbz/vaqrk.psz', 93); + var s21 = computeInputVariants(str1, 92); + var s22 = computeInputVariants('svefg', 85); + var s23 = computeInputVariants('uggc://cebsvyr.zlfcnpr.pbz/vaqrk.psz', 85); + var s24 = computeInputVariants('ynfg', 85); + var s25 = computeInputVariants('qvfcynl', 85); + + function runBlock0() { + for (var i = 0; i < 6511; i++) { + re0.exec(s0[i]); + } + for (var i = 0; i < 1844; i++) { + re1.exec(s1[i]); + } + for (var i = 0; i < 739; i++) { + s2[i].replace(re2, ''); + } + for (var i = 0; i < 598; i++) { + re1.exec(s3[i]); + } + for (var i = 0; i < 454; i++) { + re1.exec(s4[i]); + } + for (var i = 0; i < 352; i++) { + /qqqq|qqq|qq|q|ZZZZ|ZZZ|ZZ|Z|llll|ll|l|uu|u|UU|U|zz|z|ff|f|gg|g|sss|ss|s|mmm|mm|m/g.exec(s5[i]); + } + for (var i = 0; i < 312; i++) { + re3.exec(s6[i]); + } + for (var i = 0; i < 282; i++) { + re4.exec(s7[i]); + } + for (var i = 0; i < 177; i++) { + s8[i].replace(re5, ''); + } + for (var i = 0; i < 170; i++) { + s9[i].replace(re6, ''); + re7.exec(s10[i]); + } + for (var i = 0; i < 156; i++) { + re8.exec(s11[i]); + re8.exec(s12[i]); + } + for (var i = 0; i < 144; i++) { + re0.exec(s13[i]); + } + for (var i = 0; i < 139; i++) { + s14[i].replace(re6, ''); + re7.exec(s14[i]); + re9.exec(''); + /JroXvg\/(\S+)/.exec(s15[i]); + } + for (var i = 0; i < 137; i++) { + s16[i].replace(re10, ''); + s16[i].replace(/\[/g, ''); + s17[i].replace(re11, ''); + } + for (var i = 0; i < 117; i++) { + s18[i].replace(re2, ''); + } + for (var i = 0; i < 95; i++) { + /(?:^|;)\s*sevraqfgre_ynat=([^;]*)/.exec(s19[i]); + } + for (var i = 0; i < 93; i++) { + s20[i].replace(re12, ''); + re13.exec(s20[i]); + } + for (var i = 0; i < 92; i++) { + s21[i].replace(/([a-zA-Z]|\s)+/, ''); + } + for (var i = 0; i < 85; i++) { + s22[i].replace(re14, ''); + s22[i].replace(re15, ''); + s23[i].replace(re12, ''); + s24[i].replace(re14, ''); + s24[i].replace(re15, ''); + re16.exec(s25[i]); + re13.exec(s23[i]); + } + } + var re17 = /(^|[^\\])\"\\\/Qngr\((-?[0-9]+)\)\\\/\"/g; + var str2 = '{"anzr":"","ahzoreSbezng":{"PheeraplQrpvznyQvtvgf":2,"PheeraplQrpvznyFrcnengbe":".","VfErnqBayl":gehr,"PheeraplTebhcFvmrf":[3],"AhzoreTebhcFvmrf":[3],"CrepragTebhcFvmrf":[3],"PheeraplTebhcFrcnengbe":",","PheeraplFlzoby":"\xa4","AnAFlzoby":"AnA","PheeraplArtngvirCnggrea":0,"AhzoreArtngvirCnggrea":1,"CrepragCbfvgvirCnggrea":0,"CrepragArtngvirCnggrea":0,"ArtngvirVasvavglFlzoby":"-Vasvavgl","ArtngvirFvta":"-","AhzoreQrpvznyQvtvgf":2,"AhzoreQrpvznyFrcnengbe":".","AhzoreTebhcFrcnengbe":",","PheeraplCbfvgvirCnggrea":0,"CbfvgvirVasvavglFlzoby":"Vasvavgl","CbfvgvirFvta":"+","CrepragQrpvznyQvtvgf":2,"CrepragQrpvznyFrcnengbe":".","CrepragTebhcFrcnengbe":",","CrepragFlzoby":"%","CreZvyyrFlzoby":"\u2030","AngvirQvtvgf":["0","1","2","3","4","5","6","7","8","9"],"QvtvgFhofgvghgvba":1},"qngrGvzrSbezng":{"NZQrfvtangbe":"NZ","Pnyraqne":{"ZvaFhccbegrqQngrGvzr":"@-62135568000000@","ZnkFhccbegrqQngrGvzr":"@253402300799999@","NytbevguzGlcr":1,"PnyraqneGlcr":1,"Renf":[1],"GjbQvtvgLrneZnk":2029,"VfErnqBayl":gehr},"QngrFrcnengbe":"/","SvefgQnlBsJrrx":0,"PnyraqneJrrxEhyr":0,"ShyyQngrGvzrCnggrea":"qqqq, qq ZZZZ llll UU:zz:ff","YbatQngrCnggrea":"qqqq, qq ZZZZ llll","YbatGvzrCnggrea":"UU:zz:ff","ZbaguQnlCnggrea":"ZZZZ qq","CZQrfvtangbe":"CZ","ESP1123Cnggrea":"qqq, qq ZZZ llll UU\':\'zz\':\'ff \'TZG\'","FubegQngrCnggrea":"ZZ/qq/llll","FubegGvzrCnggrea":"UU:zz","FbegnoyrQngrGvzrCnggrea":"llll\'-\'ZZ\'-\'qq\'G\'UU\':\'zz\':\'ff","GvzrFrcnengbe":":","HavirefnyFbegnoyrQngrGvzrCnggrea":"llll\'-\'ZZ\'-\'qq UU\':\'zz\':\'ff\'M\'","LrneZbaguCnggrea":"llll ZZZZ","NooerivngrqQnlAnzrf":["Fha","Zba","Ghr","Jrq","Guh","Sev","Fng"],"FubegrfgQnlAnzrf":["Fh","Zb","Gh","Jr","Gu","Se","Fn"],"QnlAnzrf":["Fhaqnl","Zbaqnl","Ghrfqnl","Jrqarfqnl","Guhefqnl","Sevqnl","Fngheqnl"],"NooerivngrqZbaguAnzrf":["Wna","Sro","Zne","Nce","Znl","Wha","Why","Nht","Frc","Bpg","Abi","Qrp",""],"ZbaguAnzrf":["Wnahnel","Sroehnel","Znepu","Ncevy","Znl","Whar","Whyl","Nhthfg","Frcgrzore","Bpgbore","Abirzore","Qrprzore",""],"VfErnqBayl":gehr,"AngvirPnyraqneAnzr":"Tertbevna Pnyraqne","NooerivngrqZbaguTravgvirAnzrf":["Wna","Sro","Zne","Nce","Znl","Wha","Why","Nht","Frc","Bpg","Abi","Qrp",""],"ZbaguTravgvirAnzrf":["Wnahnel","Sroehnel","Znepu","Ncevy","Znl","Whar","Whyl","Nhthfg","Frcgrzore","Bpgbore","Abirzore","Qrprzore",""]}}'; + var str3 = '{"anzr":"ra-HF","ahzoreSbezng":{"PheeraplQrpvznyQvtvgf":2,"PheeraplQrpvznyFrcnengbe":".","VfErnqBayl":snyfr,"PheeraplTebhcFvmrf":[3],"AhzoreTebhcFvmrf":[3],"CrepragTebhcFvmrf":[3],"PheeraplTebhcFrcnengbe":",","PheeraplFlzoby":"$","AnAFlzoby":"AnA","PheeraplArtngvirCnggrea":0,"AhzoreArtngvirCnggrea":1,"CrepragCbfvgvirCnggrea":0,"CrepragArtngvirCnggrea":0,"ArtngvirVasvavglFlzoby":"-Vasvavgl","ArtngvirFvta":"-","AhzoreQrpvznyQvtvgf":2,"AhzoreQrpvznyFrcnengbe":".","AhzoreTebhcFrcnengbe":",","PheeraplCbfvgvirCnggrea":0,"CbfvgvirVasvavglFlzoby":"Vasvavgl","CbfvgvirFvta":"+","CrepragQrpvznyQvtvgf":2,"CrepragQrpvznyFrcnengbe":".","CrepragTebhcFrcnengbe":",","CrepragFlzoby":"%","CreZvyyrFlzoby":"\u2030","AngvirQvtvgf":["0","1","2","3","4","5","6","7","8","9"],"QvtvgFhofgvghgvba":1},"qngrGvzrSbezng":{"NZQrfvtangbe":"NZ","Pnyraqne":{"ZvaFhccbegrqQngrGvzr":"@-62135568000000@","ZnkFhccbegrqQngrGvzr":"@253402300799999@","NytbevguzGlcr":1,"PnyraqneGlcr":1,"Renf":[1],"GjbQvtvgLrneZnk":2029,"VfErnqBayl":snyfr},"QngrFrcnengbe":"/","SvefgQnlBsJrrx":0,"PnyraqneJrrxEhyr":0,"ShyyQngrGvzrCnggrea":"qqqq, ZZZZ qq, llll u:zz:ff gg","YbatQngrCnggrea":"qqqq, ZZZZ qq, llll","YbatGvzrCnggrea":"u:zz:ff gg","ZbaguQnlCnggrea":"ZZZZ qq","CZQrfvtangbe":"CZ","ESP1123Cnggrea":"qqq, qq ZZZ llll UU\':\'zz\':\'ff \'TZG\'","FubegQngrCnggrea":"Z/q/llll","FubegGvzrCnggrea":"u:zz gg","FbegnoyrQngrGvzrCnggrea":"llll\'-\'ZZ\'-\'qq\'G\'UU\':\'zz\':\'ff","GvzrFrcnengbe":":","HavirefnyFbegnoyrQngrGvzrCnggrea":"llll\'-\'ZZ\'-\'qq UU\':\'zz\':\'ff\'M\'","LrneZbaguCnggrea":"ZZZZ, llll","NooerivngrqQnlAnzrf":["Fha","Zba","Ghr","Jrq","Guh","Sev","Fng"],"FubegrfgQnlAnzrf":["Fh","Zb","Gh","Jr","Gu","Se","Fn"],"QnlAnzrf":["Fhaqnl","Zbaqnl","Ghrfqnl","Jrqarfqnl","Guhefqnl","Sevqnl","Fngheqnl"],"NooerivngrqZbaguAnzrf":["Wna","Sro","Zne","Nce","Znl","Wha","Why","Nht","Frc","Bpg","Abi","Qrp",""],"ZbaguAnzrf":["Wnahnel","Sroehnel","Znepu","Ncevy","Znl","Whar","Whyl","Nhthfg","Frcgrzore","Bpgbore","Abirzore","Qrprzore",""],"VfErnqBayl":snyfr,"AngvirPnyraqneAnzr":"Tertbevna Pnyraqne","NooerivngrqZbaguTravgvirAnzrf":["Wna","Sro","Zne","Nce","Znl","Wha","Why","Nht","Frc","Bpg","Abi","Qrp",""],"ZbaguTravgvirAnzrf":["Wnahnel","Sroehnel","Znepu","Ncevy","Znl","Whar","Whyl","Nhthfg","Frcgrzore","Bpgbore","Abirzore","Qrprzore",""]}}'; + var str4 = 'HFEYBP=DKWyLHAiMTH9AwHjWxAcqUx9GJ91oaEunJ4tIzyyqlMQo3IhqUW5D29xMG1IHlMQo3IhqUW5GzSgMG1Iozy0MJDtH3EuqTImWxEgLHAiMTH9BQN3WxkuqTy0qJEyCGZ3YwDkBGVzGT9hM2y0qJEyCF0kZwVhZQH3APMDo3A0LJkQo2EyCGx0ZQDmWyWyM2yiox5uoJH9D0R%3Q'; + var str5 = 'HFEYBP=DKWyLHAiMTH9AwHjWxAcqUx9GJ91oaEunJ4tIzyyqlMQo3IhqUW5D29xMG1IHlMQo3IhqUW5GzSgMG1Iozy0MJDtH3EuqTImWxEgLHAiMTH9BQN3WxkuqTy0qJEyCGZ3YwDkBGVzGT9hM2y0qJEyCF0kZwVhZQH3APMDo3A0LJkQo2EyCGx0ZQDmWyWyM2yiox5uoJH9D0R='; + var re18 = /^\s+|\s+$/g; + var str6 = 'uggc://jjj.snprobbx.pbz/vaqrk.cuc'; + var re19 = /(?:^|\s+)ba(?:\s+|$)/; + var re20 = /[+, ]/; + var re21 = /ybnqrq|pbzcyrgr/; + var str7 = ';;jvaqbj.IjPurpxZbhfrCbfvgvbaNQ_VQ=shapgvba(r){vs(!r)ine r=jvaqbj.rirag;ine c=-1;vs(d1)c=d1.EbyybssCnary;ine bo=IjTrgBow("IjCnayNQ_VQ_"+c);vs(bo&&bo.fglyr.ivfvovyvgl=="ivfvoyr"){ine fns=IjFns?8:0;ine pheK=r.pyvragK+IjBOFpe("U")+fns,pheL=r.pyvragL+IjBOFpe("I")+fns;ine y=IjBOEC(NQ_VQ,bo,"Y"),g=IjBOEC(NQ_VQ,bo,"G");ine e=y+d1.Cnaryf[c].Jvqgu,o=g+d1.Cnaryf[c].Urvtug;vs((pheKe)||(pheLo)){vs(jvaqbj.IjBaEbyybssNQ_VQ)IjBaEbyybssNQ_VQ(c);ryfr IjPybfrNq(NQ_VQ,c,gehr,"");}ryfr erghea;}IjPnapryZbhfrYvfgrareNQ_VQ();};;jvaqbj.IjFrgEbyybssCnaryNQ_VQ=shapgvba(c){ine z="zbhfrzbir",q=qbphzrag,s=IjPurpxZbhfrCbfvgvbaNQ_VQ;c=IjTc(NQ_VQ,c);vs(d1&&d1.EbyybssCnary>-1)IjPnapryZbhfrYvfgrareNQ_VQ();vs(d1)d1.EbyybssCnary=c;gel{vs(q.nqqRiragYvfgrare)q.nqqRiragYvfgrare(z,s,snyfr);ryfr vs(q.nggnpuRirag)q.nggnpuRirag("ba"+z,s);}pngpu(r){}};;jvaqbj.IjPnapryZbhfrYvfgrareNQ_VQ=shapgvba(){ine z="zbhfrzbir",q=qbphzrag,s=IjPurpxZbhfrCbfvgvbaNQ_VQ;vs(d1)d1.EbyybssCnary=-1;gel{vs(q.erzbirRiragYvfgrare)q.erzbirRiragYvfgrare(z,s,snyfr);ryfr vs(q.qrgnpuRirag)q.qrgnpuRirag("ba"+z,s);}pngpu(r){}};;d1.IjTc=d2(n,c){ine nq=d1;vs(vfAnA(c)){sbe(ine v=0;v0){vs(nq.FzV.yratgu>0)nq.FzV+="/";nq.FzV+=vh[v];nq.FtZ[nq.FtZ.yratgu]=snyfr;}}};;d1.IjYvzvg0=d2(n,f){ine nq=d1,vh=f.fcyvg("/");sbe(ine v=0;v0){vs(nq.OvC.yratgu>0)nq.OvC+="/";nq.OvC+=vh[v];}}};;d1.IjRVST=d2(n,c){jvaqbj["IjCnayNQ_VQ_"+c+"_Bow"]=IjTrgBow("IjCnayNQ_VQ_"+c+"_Bow");vs(jvaqbj["IjCnayNQ_VQ_"+c+"_Bow"]==ahyy)frgGvzrbhg("IjRVST(NQ_VQ,"+c+")",d1.rvsg);};;d1.IjNavzSHC=d2(n,c){ine nq=d1;vs(c>nq.Cnaryf.yratgu)erghea;ine cna=nq.Cnaryf[c],nn=gehr,on=gehr,yn=gehr,en=gehr,cn=nq.Cnaryf[0],sf=nq.ShF,j=cn.Jvqgu,u=cn.Urvtug;vs(j=="100%"){j=sf;en=snyfr;yn=snyfr;}vs(u=="100%"){u=sf;nn=snyfr;on=snyfr;}vs(cn.YnY=="Y")yn=snyfr;vs(cn.YnY=="E")en=snyfr;vs(cn.GnY=="G")nn=snyfr;vs(cn.GnY=="O")on=snyfr;ine k=0,l=0;fjvgpu(nq.NshP%8){pnfr 0:oernx;pnfr 1:vs(nn)l=-sf;oernx;pnfr 2:k=j-sf;oernx;pnfr 3:vs(en)k=j;oernx;pnfr 4:k=j-sf;l=u-sf;oernx;pnfr 5:k=j-sf;vs(on)l=u;oernx;pnfr 6:l=u-sf;oernx;pnfr 7:vs(yn)k=-sf;l=u-sf;oernx;}vs(nq.NshP++ 0)||(nethzragf.yratgu==3&&bG>0))){pyrneGvzrbhg(cay.UgU);cay.UgU=frgGvzrbhg(cay.UvqrNpgvba,(nethzragf.yratgu==3?bG:cay.UvqrGvzrbhgInyhr));}};;d1.IjErfrgGvzrbhg=d2(n,c,bG){c=IjTc(n,c);IjPnapryGvzrbhg(n,c);riny("IjFgnegGvzrbhg(NQ_VQ,c"+(nethzragf.yratgu==3?",bG":"")+")");};;d1.IjErfrgNyyGvzrbhgf=d2(n){sbe(ine c=0;c]/g; + var str15 = 'FrffvbaQQS2=s6r4579npn4rn2135s904r0s75pp1o5334p6s6pospo12696; ZFPhygher=VC=74.125.75.1&VCPhygher=ra-HF&CersreerqPhygher=ra-HF&CersreerqPhygherCraqvat=&Pbhagel=IIZ=&SbeprqRkcvengvba=633669316860113296&gvzrMbar=0&HFEYBP=DKWyLHAiMTH9AwHjWxAcqUx9GJ91oaEunJ4tIzyyqlMQo3IhqUW5D29xMG1IHlMQo3IhqUW5GzSgMG1Iozy0MJDtH3EuqTImWxEgLHAiMTH9BQN3WxkuqTy0qJEyCGZ3YwDkBGVzGT9hM2y0qJEyCF0kZwVhZQH3APMDo3A0LJkQo2EyCGx0ZQDmWyWyM2yiox5uoJH9D0R=; AFP_zp_dfctwzs-aowb_80=44132r503660'; + var str16 = 'FrffvbaQQS2=s6r4579npn4rn2135s904r0s75pp1o5334p6s6pospo12696; AFP_zp_dfctwzs-aowb_80=44132r503660; __hgzm=144631658.1231363638.1.1.hgzpfe=(qverpg)|hgzppa=(qverpg)|hgzpzq=(abar); __hgzn=144631658.965867047679498800.1231363638.1231363638.1231363638.1; __hgzo=144631658.0.10.1231363638; __hgzp=144631658; ZFPhygher=VC=74.125.75.1&VCPhygher=ra-HF&CersreerqPhygher=ra-HF&Pbhagel=IIZ%3Q&SbeprqRkcvengvba=633669316860113296&gvzrMbar=-8&HFEYBP=DKWyLHAiMTH9AwHjWxAcqUx9GJ91oaEunJ4tIzyyqlMQo3IhqUW5D29xMG1IHlMQo3IhqUW5GzSgMG1Iozy0MJDtH3EuqTImWxEgLHAiMTH9BQN3WxkuqTy0qJEyCGZ3YwDkBGVzGT9hM2y0qJEyCF0kZwVhZQH3APMDo3A0LJkQo2EyCGx0ZQDmWyWyM2yiox5uoJH9D0R%3Q'; + var str17 = 'uggc://tbbtyrnqf.t.qbhoyrpyvpx.arg/cntrnq/nqf?pyvrag=pn-svz_zlfcnpr_zlfcnpr-ubzrcntr_wf&qg=1231363621014&uy=ra&nqfnsr=uvtu&br=hgs8&ahz_nqf=4&bhgchg=wf&nqgrfg=bss&pbeeryngbe=1231363621014&punaary=svz_zlfcnpr_ubzrcntr_abgybttrqva%2Psvz_zlfcnpr_aba_HTP%2Psvz_zlfcnpr_havgrq-fgngrf&hey=uggc%3N%2S%2Scebsvyr.zlfcnpr.pbz%2Svaqrk.psz&nq_glcr=grkg&rvq=6083027&rn=0&sez=0&tn_ivq=348699119.1231363624&tn_fvq=1231363624&tn_uvq=895511034&synfu=9.0.115&h_u=768&h_j=1024&h_nu=738&h_nj=1024&h_pq=24&h_gm=-480&h_uvf=2&h_wnin=gehr&h_acyht=7&h_azvzr=22'; + var str18 = 'uggc://jjj.yrobapbva.se/yv'; + var str19 = 'ZFPhygher=VC=74.125.75.1&VCPhygher=ra-HF&CersreerqPhygher=ra-HF&Pbhagel=IIZ%3Q&SbeprqRkcvengvba=633669316860113296&gvzrMbar=-8&HFEYBP=DKWyLHAiMTH9AwHjWxAcqUx9GJ91oaEunJ4tIzyyqlMQo3IhqUW5D29xMG1IHlMQo3IhqUW5GzSgMG1Iozy0MJDtH3EuqTImWxEgLHAiMTH9BQN3WxkuqTy0qJEyCGZ3YwDkBGVzGT9hM2y0qJEyCF0kZwVhZQH3APMDo3A0LJkQo2EyCGx0ZQDmWyWyM2yiox5uoJH9D0R%3Q'; + var str20 = 'ZFPhygher=VC=74.125.75.1&VCPhygher=ra-HF&CersreerqPhygher=ra-HF&CersreerqPhygherCraqvat=&Pbhagel=IIZ=&SbeprqRkcvengvba=633669316860113296&gvzrMbar=0&HFEYBP=DKWyLHAiMTH9AwHjWxAcqUx9GJ91oaEunJ4tIzyyqlMQo3IhqUW5D29xMG1IHlMQo3IhqUW5GzSgMG1Iozy0MJDtH3EuqTImWxEgLHAiMTH9BQN3WxkuqTy0qJEyCGZ3YwDkBGVzGT9hM2y0qJEyCF0kZwVhZQH3APMDo3A0LJkQo2EyCGx0ZQDmWyWyM2yiox5uoJH9D0R='; + + var s67 = computeInputVariants('e115', 27); + var s68 = computeInputVariants('qvfcynl', 27); + var s69 = computeInputVariants('cbfvgvba', 27); + var s70 = computeInputVariants('uggc://jjj.zlfcnpr.pbz/', 27); + var s71 = computeInputVariants('cntrivrj', 27); + var s72 = computeInputVariants('VC=74.125.75.3', 27); + var s73 = computeInputVariants('ra', 27); + var s74 = computeInputVariants(str10, 27); + var s75 = computeInputVariants(str11, 27); + var s76 = computeInputVariants(str12, 27); + var s77 = computeInputVariants(str17, 27); + var s78 = computeInputVariants(str18, 27); + + function runBlock3() { + for (var i = 0; i < 27; i++) { + s67[i].replace(/[A-Za-z]/g, ''); + } + for (var i = 0; i < 23; i++) { + s68[i].replace(re27, ''); + s69[i].replace(re27, ''); + } + for (var i = 0; i < 22; i++) { + 'unaqyr'.replace(re14, ''); + 'unaqyr'.replace(re15, ''); + 'yvar'.replace(re14, ''); + 'yvar'.replace(re15, ''); + 'cnerag puebzr6 fvatyr1 gno'.replace(re14, ''); + 'cnerag puebzr6 fvatyr1 gno'.replace(re15, ''); + 'fyvqre'.replace(re14, ''); + 'fyvqre'.replace(re15, ''); + re28.exec(''); + } + for (var i = 0; i < 21; i++) { + s70[i].replace(re12, ''); + re13.exec(s70[i]); + } + for (var i = 0; i < 20; i++) { + s71[i].replace(re29, ''); + s71[i].replace(re30, ''); + re19.exec('ynfg'); + re19.exec('ba svefg'); + re8.exec(s72[i]); + } + for (var i = 0; i < 19; i++) { + re31.exec(s73[i]); + } + for (var i = 0; i < 18; i++) { + s74[i].split(re32); + s75[i].split(re32); + s76[i].replace(re33, ''); + re8.exec('144631658.0.10.1231363570'); + re8.exec('144631658.1231363570.1.1.hgzpfe=(qverpg)|hgzppa=(qverpg)|hgzpzq=(abar)'); + re8.exec('144631658.3426875219718084000.1231363570.1231363570.1231363570.1'); + re8.exec(str13); + re8.exec(str14); + re8.exec('__hgzn=144631658.3426875219718084000.1231363570.1231363570.1231363570.1'); + re8.exec('__hgzo=144631658.0.10.1231363570'); + re8.exec('__hgzm=144631658.1231363570.1.1.hgzpfe=(qverpg)|hgzppa=(qverpg)|hgzpzq=(abar)'); + re34.exec(s74[i]); + re34.exec(s75[i]); + } + for (var i = 0; i < 17; i++) { + s15[i].match(/zfvr/gi); + s15[i].match(/bcren/gi); + str15.split(re32); + str16.split(re32); + 'ohggba'.replace(re14, ''); + 'ohggba'.replace(re15, ''); + 'puvyq p1 svefg sylbhg pybfrq'.replace(re14, ''); + 'puvyq p1 svefg sylbhg pybfrq'.replace(re15, ''); + 'pvgvrf'.replace(re14, ''); + 'pvgvrf'.replace(re15, ''); + 'pybfrq'.replace(re14, ''); + 'pybfrq'.replace(re15, ''); + 'qry'.replace(re14, ''); + 'qry'.replace(re15, ''); + 'uqy_zba'.replace(re14, ''); + 'uqy_zba'.replace(re15, ''); + s77[i].replace(re33, ''); + s78[i].replace(/%3P/g, ''); + s78[i].replace(/%3R/g, ''); + s78[i].replace(/%3q/g, ''); + s78[i].replace(re35, ''); + 'yvaxyvfg16'.replace(re14, ''); + 'yvaxyvfg16'.replace(re15, ''); + 'zvahf'.replace(re14, ''); + 'zvahf'.replace(re15, ''); + 'bcra'.replace(re14, ''); + 'bcra'.replace(re15, ''); + 'cnerag puebzr5 fvatyr1 ps NU'.replace(re14, ''); + 'cnerag puebzr5 fvatyr1 ps NU'.replace(re15, ''); + 'cynlre'.replace(re14, ''); + 'cynlre'.replace(re15, ''); + 'cyhf'.replace(re14, ''); + 'cyhf'.replace(re15, ''); + 'cb_uqy'.replace(re14, ''); + 'cb_uqy'.replace(re15, ''); + 'hyJVzt'.replace(re14, ''); + 'hyJVzt'.replace(re15, ''); + re8.exec('144631658.0.10.1231363638'); + re8.exec('144631658.1231363638.1.1.hgzpfe=(qverpg)|hgzppa=(qverpg)|hgzpzq=(abar)'); + re8.exec('144631658.965867047679498800.1231363638.1231363638.1231363638.1'); + re8.exec('4413268q3660'); + re8.exec('4ss747o77904333q374or84qrr1s9r0nprp8r5q81534o94n'); + re8.exec('SbeprqRkcvengvba=633669321699093060'); + re8.exec('VC=74.125.75.20'); + re8.exec(str19); + re8.exec(str20); + re8.exec('AFP_zp_tfwsbrg-aowb_80=4413268q3660'); + re8.exec('FrffvbaQQS2=4ss747o77904333q374or84qrr1s9r0nprp8r5q81534o94n'); + re8.exec('__hgzn=144631658.965867047679498800.1231363638.1231363638.1231363638.1'); + re8.exec('__hgzo=144631658.0.10.1231363638'); + re8.exec('__hgzm=144631658.1231363638.1.1.hgzpfe=(qverpg)|hgzppa=(qverpg)|hgzpzq=(abar)'); + re34.exec(str15); + re34.exec(str16); + } + } + var re36 = /uers|fep|fryrpgrq/; + var re37 = /\s*([+>~\s])\s*([a-zA-Z#.*:\[])/g; + var re38 = /^(\w+|\*)$/; + var str21 = 'FrffvbaQQS2=s15q53p9n372sn76npr13o271n4s3p5r29p235746p908p58; ZFPhygher=VC=66.249.85.130&VCPhygher=ra-HF&CersreerqPhygher=ra-HF&CersreerqPhygherCraqvat=&Pbhagel=IIZ=&SbeprqRkcvengvba=633669358527244818&gvzrMbar=0&HFEYBP=DKWyLHAiMTH9AwHjWxAcqUx9GJ91oaEunJ4tIzyyqlMQo3IhqUW5D29xMG1IHlMQo3IhqUW5GzSgMG1Iozy0MJDtH3EuqTImWxEgLHAiMTH9BQN3WxkuqTy0qJEyCGZ3YwDkBGVzGT9hM2y0qJEyCF0kZwVhZQH3APMDo3A0LJkQo2EyCGx0ZQDmWyWyM2yiox5uoJH9D0R='; + var str22 = 'FrffvbaQQS2=s15q53p9n372sn76npr13o271n4s3p5r29p235746p908p58; __hgzm=144631658.1231367822.1.1.hgzpfe=(qverpg)|hgzppa=(qverpg)|hgzpzq=(abar); __hgzn=144631658.4127520630321984500.1231367822.1231367822.1231367822.1; __hgzo=144631658.0.10.1231367822; __hgzp=144631658; ZFPhygher=VC=66.249.85.130&VCPhygher=ra-HF&CersreerqPhygher=ra-HF&Pbhagel=IIZ%3Q&SbeprqRkcvengvba=633669358527244818&gvzrMbar=-8&HFEYBP=DKWyLHAiMTH9AwHjWxAcqUx9GJ91oaEunJ4tIzyyqlMQo3IhqUW5D29xMG1IHlMQo3IhqUW5GzSgMG1Iozy0MJDtH3EuqTImWxEgLHAiMTH9BQN3WxkuqTy0qJEyCGZ3YwDkBGVzGT9hM2y0qJEyCF0kZwVhZQH3APMDo3A0LJkQo2EyCGx0ZQDmWyWyM2yiox5uoJH9D0R%3Q'; + var str23 = 'uggc://tbbtyrnqf.t.qbhoyrpyvpx.arg/cntrnq/nqf?pyvrag=pn-svz_zlfcnpr_zlfcnpr-ubzrcntr_wf&qg=1231367803797&uy=ra&nqfnsr=uvtu&br=hgs8&ahz_nqf=4&bhgchg=wf&nqgrfg=bss&pbeeryngbe=1231367803797&punaary=svz_zlfcnpr_ubzrcntr_abgybttrqva%2Psvz_zlfcnpr_aba_HTP%2Psvz_zlfcnpr_havgrq-fgngrf&hey=uggc%3N%2S%2Szrffntvat.zlfcnpr.pbz%2Svaqrk.psz&nq_glcr=grkg&rvq=6083027&rn=0&sez=0&tn_ivq=1192552091.1231367807&tn_fvq=1231367807&tn_uvq=1155446857&synfu=9.0.115&h_u=768&h_j=1024&h_nu=738&h_nj=1024&h_pq=24&h_gm=-480&h_uvf=2&h_wnin=gehr&h_acyht=7&h_azvzr=22'; + var str24 = 'ZFPhygher=VC=66.249.85.130&VCPhygher=ra-HF&CersreerqPhygher=ra-HF&Pbhagel=IIZ%3Q&SbeprqRkcvengvba=633669358527244818&gvzrMbar=-8&HFEYBP=DKWyLHAiMTH9AwHjWxAcqUx9GJ91oaEunJ4tIzyyqlMQo3IhqUW5D29xMG1IHlMQo3IhqUW5GzSgMG1Iozy0MJDtH3EuqTImWxEgLHAiMTH9BQN3WxkuqTy0qJEyCGZ3YwDkBGVzGT9hM2y0qJEyCF0kZwVhZQH3APMDo3A0LJkQo2EyCGx0ZQDmWyWyM2yiox5uoJH9D0R%3Q'; + var str25 = 'ZFPhygher=VC=66.249.85.130&VCPhygher=ra-HF&CersreerqPhygher=ra-HF&CersreerqPhygherCraqvat=&Pbhagel=IIZ=&SbeprqRkcvengvba=633669358527244818&gvzrMbar=0&HFEYBP=DKWyLHAiMTH9AwHjWxAcqUx9GJ91oaEunJ4tIzyyqlMQo3IhqUW5D29xMG1IHlMQo3IhqUW5GzSgMG1Iozy0MJDtH3EuqTImWxEgLHAiMTH9BQN3WxkuqTy0qJEyCGZ3YwDkBGVzGT9hM2y0qJEyCF0kZwVhZQH3APMDo3A0LJkQo2EyCGx0ZQDmWyWyM2yiox5uoJH9D0R='; + var str26 = 'hy.ynat-fryrpgbe'; + var re39 = /\\/g; + var re40 = / /g; + var re41 = /\/\xc4\/t/; + var re42 = /\/\xd6\/t/; + var re43 = /\/\xdc\/t/; + var re44 = /\/\xdf\/t/; + var re45 = /\/\xe4\/t/; + var re46 = /\/\xf6\/t/; + var re47 = /\/\xfc\/t/; + var re48 = /\W/g; + var re49 = /uers|fep|fglyr/; + var s79 = computeInputVariants(str21, 16); + var s80 = computeInputVariants(str22, 16); + var s81 = computeInputVariants(str23, 16); + var s82 = computeInputVariants(str26, 16); + + function runBlock4() { + for (var i = 0; i < 16; i++) { + ''.replace(/\*/g, ''); + /\bnpgvir\b/.exec('npgvir'); + /sversbk/i.exec(s15[i]); + re36.exec('glcr'); + /zfvr/i.exec(s15[i]); + /bcren/i.exec(s15[i]); + } + for (var i = 0; i < 15; i++) { + s79[i].split(re32); + s80[i].split(re32); + 'uggc://ohyyrgvaf.zlfcnpr.pbz/vaqrk.psz'.replace(re12, ''); + s81[i].replace(re33, ''); + 'yv'.replace(re37, ''); + 'yv'.replace(re18, ''); + re8.exec('144631658.0.10.1231367822'); + re8.exec('144631658.1231367822.1.1.hgzpfe=(qverpg)|hgzppa=(qverpg)|hgzpzq=(abar)'); + re8.exec('144631658.4127520630321984500.1231367822.1231367822.1231367822.1'); + re8.exec(str24); + re8.exec(str25); + re8.exec('__hgzn=144631658.4127520630321984500.1231367822.1231367822.1231367822.1'); + re8.exec('__hgzo=144631658.0.10.1231367822'); + re8.exec('__hgzm=144631658.1231367822.1.1.hgzpfe=(qverpg)|hgzppa=(qverpg)|hgzpzq=(abar)'); + re34.exec(s79[i]); + re34.exec(s80[i]); + /\.([\w-]+)|\[(\w+)(?:([!*^$~|]?=)["']?(.*?)["']?)?\]|:([\w-]+)(?:\(["']?(.*?)?["']?\)|$)/g.exec(s82[i]); + re13.exec('uggc://ohyyrgvaf.zlfcnpr.pbz/vaqrk.psz'); + re38.exec('yv'); + } + for (var i = 0; i < 14; i++) { + ''.replace(re18, ''); + '9.0 e115'.replace(/(\s+e|\s+o[0-9]+)/, ''); + 'Funer guvf tnqtrg'.replace(//g, ''); + 'Funer guvf tnqtrg'.replace(re39, ''); + 'uggc://cebsvyrrqvg.zlfcnpr.pbz/vaqrk.psz'.replace(re12, ''); + 'grnfre'.replace(re40, ''); + 'grnfre'.replace(re41, ''); + 'grnfre'.replace(re42, ''); + 'grnfre'.replace(re43, ''); + 'grnfre'.replace(re44, ''); + 'grnfre'.replace(re45, ''); + 'grnfre'.replace(re46, ''); + 'grnfre'.replace(re47, ''); + 'grnfre'.replace(re48, ''); + re16.exec('znetva-gbc'); + re16.exec('cbfvgvba'); + re19.exec('gno1'); + re9.exec('qz'); + re9.exec('qg'); + re9.exec('zbqobk'); + re9.exec('zbqobkva'); + re9.exec('zbqgvgyr'); + re13.exec('uggc://cebsvyrrqvg.zlfcnpr.pbz/vaqrk.psz'); + re26.exec('/vt/znvytnqtrg'); + re49.exec('glcr'); + } + } + var re50 = /(?:^|\s+)fryrpgrq(?:\s+|$)/; + var re51 = /\&/g; + var re52 = /\+/g; + var re53 = /\?/g; + var re54 = /\t/g; + var re55 = /(\$\{nqiHey\})|(\$nqiHey\b)/g; + var re56 = /(\$\{cngu\})|(\$cngu\b)/g; + function runBlock5() { + for (var i = 0; i < 13; i++) { + 'purpx'.replace(re14, ''); + 'purpx'.replace(re15, ''); + 'pvgl'.replace(re14, ''); + 'pvgl'.replace(re15, ''); + 'qrpe fyvqrgrkg'.replace(re14, ''); + 'qrpe fyvqrgrkg'.replace(re15, ''); + 'svefg fryrpgrq'.replace(re14, ''); + 'svefg fryrpgrq'.replace(re15, ''); + 'uqy_rag'.replace(re14, ''); + 'uqy_rag'.replace(re15, ''); + 'vape fyvqrgrkg'.replace(re14, ''); + 'vape fyvqrgrkg'.replace(re15, ''); + 'vachggrkg QBZPbageby_cynprubyqre'.replace(re5, ''); + 'cnerag puebzr6 fvatyr1 gno fryrpgrq'.replace(re14, ''); + 'cnerag puebzr6 fvatyr1 gno fryrpgrq'.replace(re15, ''); + 'cb_guz'.replace(re14, ''); + 'cb_guz'.replace(re15, ''); + 'fhozvg'.replace(re14, ''); + 'fhozvg'.replace(re15, ''); + re50.exec(''); + /NccyrJroXvg\/([^\s]*)/.exec(s15[i]); + /XUGZY/.exec(s15[i]); + } + for (var i = 0; i < 12; i++) { + '${cebg}://${ubfg}${cngu}/${dz}'.replace(/(\$\{cebg\})|(\$cebg\b)/g, ''); + '1'.replace(re40, ''); + '1'.replace(re10, ''); + '1'.replace(re51, ''); + '1'.replace(re52, ''); + '1'.replace(re53, ''); + '1'.replace(re39, ''); + '1'.replace(re54, ''); + '9.0 e115'.replace(/^(.*)\..*$/, ''); + '9.0 e115'.replace(/^.*e(.*)$/, ''); + ''.replace(re55, ''); + ''.replace(re55, ''); + s21[i].replace(/^.*\s+(\S+\s+\S+$)/, ''); + 'tzk%2Subzrcntr%2Sfgneg%2Sqr%2S'.replace(re30, ''); + 'tzk'.replace(re30, ''); + 'uggc://${ubfg}${cngu}/${dz}'.replace(/(\$\{ubfg\})|(\$ubfg\b)/g, ''); + 'uggc://nqpyvrag.hvzfrei.arg${cngu}/${dz}'.replace(re56, ''); + 'uggc://nqpyvrag.hvzfrei.arg/wf.at/${dz}'.replace(/(\$\{dz\})|(\$dz\b)/g, ''); + 'frpgvba'.replace(re29, ''); + 'frpgvba'.replace(re30, ''); + 'fvgr'.replace(re29, ''); + 'fvgr'.replace(re30, ''); + 'fcrpvny'.replace(re29, ''); + 'fcrpvny'.replace(re30, ''); + re36.exec('anzr'); + /e/.exec('9.0 e115'); + } + } + var re57 = /##yv4##/gi; + var re58 = /##yv16##/gi; + var re59 = /##yv19##/gi; + var str27 = '##yv4##Cbjreshy Zvpebfbsg grpuabybtl urycf svtug fcnz naq vzcebir frphevgl.##yv19##Trg zber qbar gunaxf gb terngre rnfr naq fcrrq.##yv16##Ybgf bs fgbentr (5 TO) - zber pbby fghss ba gur jnl.##OE## ##OE## ##N##Yrnea zber##/N##'; + var str28 = 'Cbjreshy Zvpebfbsg grpuabybtl urycf svtug fcnz naq vzcebir frphevgl.##yv19##Trg zber qbar gunaxf gb terngre rnfr naq fcrrq.##yv16##Ybgf bs fgbentr (5 TO) - zber pbby fghss ba gur jnl.##OE## ##OE## ##N##Yrnea zber##/N##'; + var str29 = 'Cbjreshy Zvpebfbsg grpuabybtl urycf svtug fcnz naq vzcebir frphevgl.##yv19##Trg zber qbar gunaxf gb terngre rnfr naq fcrrq.Ybgf bs fgbentr (5 TO) - zber pbby fghss ba gur jnl.##OE## ##OE## ##N##Yrnea zber##/N##'; + var str30 = 'Cbjreshy Zvpebfbsg grpuabybtl urycf svtug fcnz naq vzcebir frphevgl.Trg zber qbar gunaxf gb terngre rnfr naq fcrrq.Ybgf bs fgbentr (5 TO) - zber pbby fghss ba gur jnl.##OE## ##OE## ##N##Yrnea zber##/N##'; + var str31 = 'Cbjreshy Zvpebfbsg grpuabybtl urycf svtug fcnz naq vzcebir frphevgl.Trg zber qbar gunaxf gb terngre rnfr naq fcrrq.Ybgf bs fgbentr (5 TO) - zber pbby fghss ba gur jnl. ##N##Yrnea zber##/N##'; + var str32 = 'Cbjreshy Zvpebfbsg grpuabybtl urycf svtug fcnz naq vzcebir frphevgl.Trg zber qbar gunaxf gb terngre rnfr naq fcrrq.Ybgf bs fgbentr (5 TO) - zber pbby fghss ba gur jnl. Yrnea zber##/N##'; + var str33 = 'Bar Jvaqbjf Yvir VQ trgf lbh vagb Ubgznvy, Zrffratre, Kobk YVIR \u2014 naq bgure cynprf lbh frr #~#argjbexybtb#~#'; + var re60 = /(?:^|\s+)bss(?:\s+|$)/; + var re61 = /^(([^:\/?#]+):)?(\/\/([^\/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?$/; + var re62 = /^[^<]*(<(.|\s)+>)[^>]*$|^#(\w+)$/; + var str34 = '${1}://${2}${3}${4}${5}'; + var str35 = ' O=6gnyg0g4znrrn&o=3&f=gc; Q=_lyu=K3bQZGSxnT4lZzD3OS9GNmV3ZGLkAQxRpTyxNmRlZmRmAmNkAQLRqTImqNZjOUEgpTjQnJ5xMKtgoN--; SCF=qy'; + var s83 = computeInputVariants(str27, 11); + var s84 = computeInputVariants(str28, 11); + var s85 = computeInputVariants(str29, 11); + var s86 = computeInputVariants(str30, 11); + var s87 = computeInputVariants(str31, 11); + var s88 = computeInputVariants(str32, 11); + var s89 = computeInputVariants(str33, 11); + var s90 = computeInputVariants(str34, 11); + + function runBlock6() { + for (var i = 0; i < 11; i++) { + s83[i].replace(/##yv0##/gi, ''); + s83[i].replace(re57, ''); + s84[i].replace(re58, ''); + s85[i].replace(re59, ''); + s86[i].replace(/##\/o##/gi, ''); + s86[i].replace(/##\/v##/gi, ''); + s86[i].replace(/##\/h##/gi, ''); + s86[i].replace(/##o##/gi, ''); + s86[i].replace(/##oe##/gi, ''); + s86[i].replace(/##v##/gi, ''); + s86[i].replace(/##h##/gi, ''); + s87[i].replace(/##n##/gi, ''); + s88[i].replace(/##\/n##/gi, ''); + s89[i].replace(/#~#argjbexybtb#~#/g, ''); + / Zbovyr\//.exec(s15[i]); + /##yv1##/gi.exec(s83[i]); + /##yv10##/gi.exec(s84[i]); + /##yv11##/gi.exec(s84[i]); + /##yv12##/gi.exec(s84[i]); + /##yv13##/gi.exec(s84[i]); + /##yv14##/gi.exec(s84[i]); + /##yv15##/gi.exec(s84[i]); + re58.exec(s84[i]); + /##yv17##/gi.exec(s85[i]); + /##yv18##/gi.exec(s85[i]); + re59.exec(s85[i]); + /##yv2##/gi.exec(s83[i]); + /##yv20##/gi.exec(s86[i]); + /##yv21##/gi.exec(s86[i]); + /##yv22##/gi.exec(s86[i]); + /##yv23##/gi.exec(s86[i]); + /##yv3##/gi.exec(s83[i]); + re57.exec(s83[i]); + /##yv5##/gi.exec(s84[i]); + /##yv6##/gi.exec(s84[i]); + /##yv7##/gi.exec(s84[i]); + /##yv8##/gi.exec(s84[i]); + /##yv9##/gi.exec(s84[i]); + re8.exec('473qq1rs0n2r70q9qo1pq48n021s9468ron90nps048p4p29'); + re8.exec('SbeprqRkcvengvba=633669325184628362'); + re8.exec('FrffvbaQQS2=473qq1rs0n2r70q9qo1pq48n021s9468ron90nps048p4p29'); + /AbxvnA[^\/]*/.exec(s15[i]); + } + for (var i = 0; i < 10; i++) { + ' bss'.replace(/(?:^|\s+)bss(?:\s+|$)/g, ''); + s90[i].replace(/(\$\{0\})|(\$0\b)/g, ''); + s90[i].replace(/(\$\{1\})|(\$1\b)/g, ''); + s90[i].replace(/(\$\{pbzcyrgr\})|(\$pbzcyrgr\b)/g, ''); + s90[i].replace(/(\$\{sentzrag\})|(\$sentzrag\b)/g, ''); + s90[i].replace(/(\$\{ubfgcbeg\})|(\$ubfgcbeg\b)/g, ''); + s90[i].replace(re56, ''); + s90[i].replace(/(\$\{cebgbpby\})|(\$cebgbpby\b)/g, ''); + s90[i].replace(/(\$\{dhrel\})|(\$dhrel\b)/g, ''); + 'nqfvmr'.replace(re29, ''); + 'nqfvmr'.replace(re30, ''); + 'uggc://${2}${3}${4}${5}'.replace(/(\$\{2\})|(\$2\b)/g, ''); + 'uggc://wf.hv-cbegny.qr${3}${4}${5}'.replace(/(\$\{3\})|(\$3\b)/g, ''); + 'arjf'.replace(re40, ''); + 'arjf'.replace(re41, ''); + 'arjf'.replace(re42, ''); + 'arjf'.replace(re43, ''); + 'arjf'.replace(re44, ''); + 'arjf'.replace(re45, ''); + 'arjf'.replace(re46, ''); + 'arjf'.replace(re47, ''); + 'arjf'.replace(re48, ''); + / PC=i=(\d+)&oe=(.)/.exec(str35); + re60.exec(' '); + re60.exec(' bss'); + re60.exec(''); + re19.exec(' '); + re19.exec('svefg ba'); + re19.exec('ynfg vtaber'); + re19.exec('ba'); + re9.exec('scnq so '); + re9.exec('zrqvgobk'); + re9.exec('hsgy'); + re9.exec('lhv-h'); + /Fnsnev|Xbadhrebe|XUGZY/gi.exec(s15[i]); + re61.exec('uggc://wf.hv-cbegny.qr/tzk/ubzr/wf/20080602/onfr.wf'); + re62.exec('#Ybtva_rznvy'); + } + } + var re63 = /\{0\}/g; + var str36 = 'FrffvbaQQS2=4ss747o77904333q374or84qrr1s9r0nprp8r5q81534o94n; ZFPhygher=VC=74.125.75.20&VCPhygher=ra-HF&CersreerqPhygher=ra-HF&CersreerqPhygherCraqvat=&Pbhagel=IIZ=&SbeprqRkcvengvba=633669321699093060&gvzrMbar=0&HFEYBP=DKWyLHAiMTH9AwHjWxAcqUx9GJ91oaEunJ4tIzyyqlMQo3IhqUW5D29xMG1IHlMQo3IhqUW5GzSgMG1Iozy0MJDtH3EuqTImWxEgLHAiMTH9BQN3WxkuqTy0qJEyCGZ3YwDkBGVzGT9hM2y0qJEyCF0kZwVhZQH3APMDo3A0LJkQo2EyCGx0ZQDmWyWyM2yiox5uoJH9D0R=; AFP_zp_tfwsbrg-aowb_80=4413268q3660'; + var str37 = 'FrffvbaQQS2=4ss747o77904333q374or84qrr1s9r0nprp8r5q81534o94n; AFP_zp_tfwsbrg-aowb_80=4413268q3660; __hgzm=144631658.1231364074.1.1.hgzpfe=(qverpg)|hgzppa=(qverpg)|hgzpzq=(abar); __hgzn=144631658.2294274870215848400.1231364074.1231364074.1231364074.1; __hgzo=144631658.0.10.1231364074; __hgzp=144631658; ZFPhygher=VC=74.125.75.20&VCPhygher=ra-HF&CersreerqPhygher=ra-HF&Pbhagel=IIZ%3Q&SbeprqRkcvengvba=633669321699093060&gvzrMbar=-8&HFEYBP=DKWyLHAiMTH9AwHjWxAcqUx9GJ91oaEunJ4tIzyyqlMQo3IhqUW5D29xMG1IHlMQo3IhqUW5GzSgMG1Iozy0MJDtH3EuqTImWxEgLHAiMTH9BQN3WxkuqTy0qJEyCGZ3YwDkBGVzGT9hM2y0qJEyCF0kZwVhZQH3APMDo3A0LJkQo2EyCGx0ZQDmWyWyM2yiox5uoJH9D0R%3Q'; + var str38 = 'uggc://tbbtyrnqf.t.qbhoyrpyvpx.arg/cntrnq/nqf?pyvrag=pn-svz_zlfcnpr_zlfcnpr-ubzrcntr_wf&qg=1231364057761&uy=ra&nqfnsr=uvtu&br=hgs8&ahz_nqf=4&bhgchg=wf&nqgrfg=bss&pbeeryngbe=1231364057761&punaary=svz_zlfcnpr_ubzrcntr_abgybttrqva%2Psvz_zlfcnpr_aba_HTP%2Psvz_zlfcnpr_havgrq-fgngrf&hey=uggc%3N%2S%2Ssevraqf.zlfcnpr.pbz%2Svaqrk.psz&nq_glcr=grkg&rvq=6083027&rn=0&sez=0&tn_ivq=1667363813.1231364061&tn_fvq=1231364061&tn_uvq=1917563877&synfu=9.0.115&h_u=768&h_j=1024&h_nu=738&h_nj=1024&h_pq=24&h_gm=-480&h_uvf=2&h_wnin=gehr&h_acyht=7&h_azvzr=22'; + var str39 = 'ZFPhygher=VC=74.125.75.20&VCPhygher=ra-HF&CersreerqPhygher=ra-HF&Pbhagel=IIZ%3Q&SbeprqRkcvengvba=633669321699093060&gvzrMbar=-8&HFEYBP=DKWyLHAiMTH9AwHjWxAcqUx9GJ91oaEunJ4tIzyyqlMQo3IhqUW5D29xMG1IHlMQo3IhqUW5GzSgMG1Iozy0MJDtH3EuqTImWxEgLHAiMTH9BQN3WxkuqTy0qJEyCGZ3YwDkBGVzGT9hM2y0qJEyCF0kZwVhZQH3APMDo3A0LJkQo2EyCGx0ZQDmWyWyM2yiox5uoJH9D0R%3Q'; + var str40 = 'ZFPhygher=VC=74.125.75.20&VCPhygher=ra-HF&CersreerqPhygher=ra-HF&CersreerqPhygherCraqvat=&Pbhagel=IIZ=&SbeprqRkcvengvba=633669321699093060&gvzrMbar=0&HFEYBP=DKWyLHAiMTH9AwHjWxAcqUx9GJ91oaEunJ4tIzyyqlMQo3IhqUW5D29xMG1IHlMQo3IhqUW5GzSgMG1Iozy0MJDtH3EuqTImWxEgLHAiMTH9BQN3WxkuqTy0qJEyCGZ3YwDkBGVzGT9hM2y0qJEyCF0kZwVhZQH3APMDo3A0LJkQo2EyCGx0ZQDmWyWyM2yiox5uoJH9D0R='; + var s91 = computeInputVariants(str36, 9); + var s92 = computeInputVariants(str37, 9); + var s93 = computeInputVariants(str38, 9); + function runBlock7() { + for (var i = 0; i < 9; i++) { + '0'.replace(re40, ''); + '0'.replace(re10, ''); + '0'.replace(re51, ''); + '0'.replace(re52, ''); + '0'.replace(re53, ''); + '0'.replace(re39, ''); + '0'.replace(re54, ''); + 'Lrf'.replace(re40, ''); + 'Lrf'.replace(re10, ''); + 'Lrf'.replace(re51, ''); + 'Lrf'.replace(re52, ''); + 'Lrf'.replace(re53, ''); + 'Lrf'.replace(re39, ''); + 'Lrf'.replace(re54, ''); + } + for (var i = 0; i < 8; i++) { + 'Pybfr {0}'.replace(re63, ''); + 'Bcra {0}'.replace(re63, ''); + s91[i].split(re32); + s92[i].split(re32); + 'puvyq p1 svefg gnournqref'.replace(re14, ''); + 'puvyq p1 svefg gnournqref'.replace(re15, ''); + 'uqy_fcb'.replace(re14, ''); + 'uqy_fcb'.replace(re15, ''); + 'uvag'.replace(re14, ''); + 'uvag'.replace(re15, ''); + s93[i].replace(re33, ''); + 'yvfg'.replace(re14, ''); + 'yvfg'.replace(re15, ''); + 'at_bhgre'.replace(re30, ''); + 'cnerag puebzr5 qbhoyr2 NU'.replace(re14, ''); + 'cnerag puebzr5 qbhoyr2 NU'.replace(re15, ''); + 'cnerag puebzr5 dhnq5 ps NU osyvax zbarl'.replace(re14, ''); + 'cnerag puebzr5 dhnq5 ps NU osyvax zbarl'.replace(re15, ''); + 'cnerag puebzr6 fvatyr1'.replace(re14, ''); + 'cnerag puebzr6 fvatyr1'.replace(re15, ''); + 'cb_qrs'.replace(re14, ''); + 'cb_qrs'.replace(re15, ''); + 'gnopbagrag'.replace(re14, ''); + 'gnopbagrag'.replace(re15, ''); + 'iv_svefg_gvzr'.replace(re30, ''); + /(^|.)(ronl|qri-ehf3.wbg)(|fgberf|zbgbef|yvirnhpgvbaf|jvxv|rkcerff|punggre).(pbz(|.nh|.pa|.ux|.zl|.ft|.oe|.zk)|pb(.hx|.xe|.am)|pn|qr|se|vg|ay|or|ng|pu|vr|va|rf|cy|cu|fr)$/i.exec('cntrf.ronl.pbz'); + re8.exec('144631658.0.10.1231364074'); + re8.exec('144631658.1231364074.1.1.hgzpfe=(qverpg)|hgzppa=(qverpg)|hgzpzq=(abar)'); + re8.exec('144631658.2294274870215848400.1231364074.1231364074.1231364074.1'); + re8.exec('4413241q3660'); + re8.exec('SbeprqRkcvengvba=633669357391353591'); + re8.exec(str39); + re8.exec(str40); + re8.exec('AFP_zp_kkk-gdzogv_80=4413241q3660'); + re8.exec('FrffvbaQQS2=p98s8o9q42nr21or1r61pqorn1n002nsss569635984s6qp7'); + re8.exec('__hgzn=144631658.2294274870215848400.1231364074.1231364074.1231364074.1'); + re8.exec('__hgzo=144631658.0.10.1231364074'); + re8.exec('__hgzm=144631658.1231364074.1.1.hgzpfe=(qverpg)|hgzppa=(qverpg)|hgzpzq=(abar)'); + re8.exec('p98s8o9q42nr21or1r61pqorn1n002nsss569635984s6qp7'); + re34.exec(s91[i]); + re34.exec(s92[i]); + } + } + var re64 = /\b[a-z]/g; + var re65 = /^uggc:\/\//; + var re66 = /(?:^|\s+)qvfnoyrq(?:\s+|$)/; + var str41 = 'uggc://cebsvyr.zlfcnpr.pbz/Zbqhyrf/Nccyvpngvbaf/Cntrf/Pnainf.nfck'; + function runBlock8() { + for (var i = 0; i < 7; i++) { + s21[i].match(/\d+/g); + 'nsgre'.replace(re64, ''); + 'orsber'.replace(re64, ''); + 'obggbz'.replace(re64, ''); + 'ohvygva_jrngure.kzy'.replace(re65, ''); + 'ohggba'.replace(re37, ''); + 'ohggba'.replace(re18, ''); + 'qngrgvzr.kzy'.replace(re65, ''); + 'uggc://eff.paa.pbz/eff/paa_gbcfgbevrf.eff'.replace(re65, ''); + 'vachg'.replace(re37, ''); + 'vachg'.replace(re18, ''); + 'vafvqr'.replace(re64, ''); + 'cbvagre'.replace(re27, ''); + 'cbfvgvba'.replace(/[A-Z]/g, ''); + 'gbc'.replace(re27, ''); + 'gbc'.replace(re64, ''); + 'hy'.replace(re37, ''); + 'hy'.replace(re18, ''); + str26.replace(re37, ''); + str26.replace(re18, ''); + 'lbhghor_vtbbtyr/i2/lbhghor.kzy'.replace(re65, ''); + 'm-vaqrk'.replace(re27, ''); + /#([\w-]+)/.exec(str26); + re16.exec('urvtug'); + re16.exec('znetvaGbc'); + re16.exec('jvqgu'); + re19.exec('gno0 svefg ba'); + re19.exec('gno0 ba'); + re19.exec('gno4 ynfg'); + re19.exec('gno4'); + re19.exec('gno5'); + re19.exec('gno6'); + re19.exec('gno7'); + re19.exec('gno8'); + /NqborNVE\/([^\s]*)/.exec(s15[i]); + /NccyrJroXvg\/([^ ]*)/.exec(s15[i]); + /XUGZY/gi.exec(s15[i]); + /^(?:obql|ugzy)$/i.exec('YV'); + re38.exec('ohggba'); + re38.exec('vachg'); + re38.exec('hy'); + re38.exec(str26); + /^(\w+|\*)/.exec(str26); + /znp|jva|yvahk/i.exec('Jva32'); + /eton?\([\d\s,]+\)/.exec('fgngvp'); + } + for (var i = 0; i < 6; i++) { + ''.replace(/\r/g, ''); + '/'.replace(re40, ''); + '/'.replace(re10, ''); + '/'.replace(re51, ''); + '/'.replace(re52, ''); + '/'.replace(re53, ''); + '/'.replace(re39, ''); + '/'.replace(re54, ''); + 'uggc://zfacbegny.112.2b7.arg/o/ff/zfacbegnyubzr/1/U.7-cqi-2/{0}?[NDO]&{1}&{2}&[NDR]'.replace(re63, ''); + str41.replace(re12, ''); + 'uggc://jjj.snprobbx.pbz/fepu.cuc'.replace(re23, ''); + 'freivpr'.replace(re40, ''); + 'freivpr'.replace(re41, ''); + 'freivpr'.replace(re42, ''); + 'freivpr'.replace(re43, ''); + 'freivpr'.replace(re44, ''); + 'freivpr'.replace(re45, ''); + 'freivpr'.replace(re46, ''); + 'freivpr'.replace(re47, ''); + 'freivpr'.replace(re48, ''); + /((ZFVR\s+([6-9]|\d\d)\.))/.exec(s15[i]); + re66.exec(''); + re50.exec('fryrpgrq'); + re8.exec('8sqq78r9n442851q565599o401385sp3s04r92rnn7o19ssn'); + re8.exec('SbeprqRkcvengvba=633669340386893867'); + re8.exec('VC=74.125.75.17'); + re8.exec('FrffvbaQQS2=8sqq78r9n442851q565599o401385sp3s04r92rnn7o19ssn'); + /Xbadhrebe|Fnsnev|XUGZY/.exec(s15[i]); + re13.exec(str41); + re49.exec('unfsbphf'); + } + } + var re67 = /zrah_byq/g; + var str42 = 'FrffvbaQQS2=473qq1rs0n2r70q9qo1pq48n021s9468ron90nps048p4p29; ZFPhygher=VC=74.125.75.3&VCPhygher=ra-HF&CersreerqPhygher=ra-HF&CersreerqPhygherCraqvat=&Pbhagel=IIZ=&SbeprqRkcvengvba=633669325184628362&gvzrMbar=0&HFEYBP=DKWyLHAiMTH9AwHjWxAcqUx9GJ91oaEunJ4tIzyyqlMQo3IhqUW5D29xMG1IHlMQo3IhqUW5GzSgMG1Iozy0MJDtH3EuqTImWxEgLHAiMTH9BQN3WxkuqTy0qJEyCGZ3YwDkBGVzGT9hM2y0qJEyCF0kZwVhZQH3APMDo3A0LJkQo2EyCGx0ZQDmWyWyM2yiox5uoJH9D0R='; + var str43 = 'FrffvbaQQS2=473qq1rs0n2r70q9qo1pq48n021s9468ron90nps048p4p29; __hgzm=144631658.1231364380.1.1.hgzpfe=(qverpg)|hgzppa=(qverpg)|hgzpzq=(abar); __hgzn=144631658.3931862196947939300.1231364380.1231364380.1231364380.1; __hgzo=144631658.0.10.1231364380; __hgzp=144631658; ZFPhygher=VC=74.125.75.3&VCPhygher=ra-HF&CersreerqPhygher=ra-HF&Pbhagel=IIZ%3Q&SbeprqRkcvengvba=633669325184628362&gvzrMbar=-8&HFEYBP=DKWyLHAiMTH9AwHjWxAcqUx9GJ91oaEunJ4tIzyyqlMQo3IhqUW5D29xMG1IHlMQo3IhqUW5GzSgMG1Iozy0MJDtH3EuqTImWxEgLHAiMTH9BQN3WxkuqTy0qJEyCGZ3YwDkBGVzGT9hM2y0qJEyCF0kZwVhZQH3APMDo3A0LJkQo2EyCGx0ZQDmWyWyM2yiox5uoJH9D0R%3Q'; + var str44 = 'uggc://tbbtyrnqf.t.qbhoyrpyvpx.arg/cntrnq/nqf?pyvrag=pn-svz_zlfcnpr_vzntrf_wf&qg=1231364373088&uy=ra&nqfnsr=uvtu&br=hgs8&ahz_nqf=4&bhgchg=wf&nqgrfg=bss&pbeeryngbe=1231364373088&punaary=svz_zlfcnpr_hfre-ivrj-pbzzragf%2Psvz_zlfcnpr_havgrq-fgngrf&hey=uggc%3N%2S%2Spbzzrag.zlfcnpr.pbz%2Svaqrk.psz&nq_glcr=grkg&rvq=6083027&rn=0&sez=0&tn_ivq=1158737789.1231364375&tn_fvq=1231364375&tn_uvq=415520832&synfu=9.0.115&h_u=768&h_j=1024&h_nu=738&h_nj=1024&h_pq=24&h_gm=-480&h_uvf=2&h_wnin=gehr&h_acyht=7&h_azvzr=22'; + var str45 = 'ZFPhygher=VC=74.125.75.3&VCPhygher=ra-HF&CersreerqPhygher=ra-HF&Pbhagel=IIZ%3Q&SbeprqRkcvengvba=633669325184628362&gvzrMbar=-8&HFEYBP=DKWyLHAiMTH9AwHjWxAcqUx9GJ91oaEunJ4tIzyyqlMQo3IhqUW5D29xMG1IHlMQo3IhqUW5GzSgMG1Iozy0MJDtH3EuqTImWxEgLHAiMTH9BQN3WxkuqTy0qJEyCGZ3YwDkBGVzGT9hM2y0qJEyCF0kZwVhZQH3APMDo3A0LJkQo2EyCGx0ZQDmWyWyM2yiox5uoJH9D0R%3Q'; + var str46 = 'ZFPhygher=VC=74.125.75.3&VCPhygher=ra-HF&CersreerqPhygher=ra-HF&CersreerqPhygherCraqvat=&Pbhagel=IIZ=&SbeprqRkcvengvba=633669325184628362&gvzrMbar=0&HFEYBP=DKWyLHAiMTH9AwHjWxAcqUx9GJ91oaEunJ4tIzyyqlMQo3IhqUW5D29xMG1IHlMQo3IhqUW5GzSgMG1Iozy0MJDtH3EuqTImWxEgLHAiMTH9BQN3WxkuqTy0qJEyCGZ3YwDkBGVzGT9hM2y0qJEyCF0kZwVhZQH3APMDo3A0LJkQo2EyCGx0ZQDmWyWyM2yiox5uoJH9D0R='; + var re68 = /^([#.]?)((?:[\w\u0128-\uffff*_-]|\\.)*)/; + var re69 = /\{1\}/g; + var re70 = /\s+/; + var re71 = /(\$\{4\})|(\$4\b)/g; + var re72 = /(\$\{5\})|(\$5\b)/g; + var re73 = /\{2\}/g; + var re74 = /[^+>] [^+>]/; + var re75 = /\bucpyv\s*=\s*([^;]*)/i; + var re76 = /\bucuvqr\s*=\s*([^;]*)/i; + var re77 = /\bucfie\s*=\s*([^;]*)/i; + var re78 = /\bhfucjrn\s*=\s*([^;]*)/i; + var re79 = /\bmvc\s*=\s*([^;]*)/i; + var re80 = /^((?:[\w\u0128-\uffff*_-]|\\.)+)(#)((?:[\w\u0128-\uffff*_-]|\\.)+)/; + var re81 = /^([>+~])\s*(\w*)/i; + var re82 = /^>\s*((?:[\w\u0128-\uffff*_-]|\\.)+)/; + var re83 = /^[\s[]?shapgvba/; + var re84 = /v\/g.tvs#(.*)/i; + var str47 = '#Zbq-Vasb-Vasb-WninFpevcgUvag'; + var str48 = ',n.svryqOgaPnapry'; + var str49 = 'FrffvbaQQS2=p98s8o9q42nr21or1r61pqorn1n002nsss569635984s6qp7; ZFPhygher=VC=74.125.75.3&VCPhygher=ra-HF&CersreerqPhygher=ra-HF&CersreerqPhygherCraqvat=&Pbhagel=IIZ=&SbeprqRkcvengvba=633669357391353591&gvzrMbar=0&HFEYBP=DKWyLHAiMTH9AwHjWxAcqUx9GJ91oaEunJ4tIzyyqlMQo3IhqUW5D29xMG1IHlMQo3IhqUW5GzSgMG1Iozy0MJDtH3EuqTImWxEgLHAiMTH9BQN3WxkuqTy0qJEyCGZ3YwDkBGVzGT9hM2y0qJEyCF0kZwVhZQH3APMDo3A0LJkQo2EyCGx0ZQDmWyWyM2yiox5uoJH9D0R=; AFP_zp_kkk-gdzogv_80=4413241q3660'; + var str50 = 'FrffvbaQQS2=p98s8o9q42nr21or1r61pqorn1n002nsss569635984s6qp7; AFP_zp_kkk-gdzogv_80=4413241q3660; AFP_zp_kkk-aowb_80=4413235p3660; __hgzm=144631658.1231367708.1.1.hgzpfe=(qverpg)|hgzppa=(qverpg)|hgzpzq=(abar); __hgzn=144631658.2770915348920628700.1231367708.1231367708.1231367708.1; __hgzo=144631658.0.10.1231367708; __hgzp=144631658; ZFPhygher=VC=74.125.75.3&VCPhygher=ra-HF&CersreerqPhygher=ra-HF&Pbhagel=IIZ%3Q&SbeprqRkcvengvba=633669357391353591&gvzrMbar=-8&HFEYBP=DKWyLHAiMTH9AwHjWxAcqUx9GJ91oaEunJ4tIzyyqlMQo3IhqUW5D29xMG1IHlMQo3IhqUW5GzSgMG1Iozy0MJDtH3EuqTImWxEgLHAiMTH9BQN3WxkuqTy0qJEyCGZ3YwDkBGVzGT9hM2y0qJEyCF0kZwVhZQH3APMDo3A0LJkQo2EyCGx0ZQDmWyWyM2yiox5uoJH9D0R%3Q'; + var str51 = 'uggc://tbbtyrnqf.t.qbhoyrpyvpx.arg/cntrnq/nqf?pyvrag=pn-svz_zlfcnpr_zlfcnpr-ubzrcntr_wf&qg=1231367691141&uy=ra&nqfnsr=uvtu&br=hgs8&ahz_nqf=4&bhgchg=wf&nqgrfg=bss&pbeeryngbe=1231367691141&punaary=svz_zlfcnpr_ubzrcntr_abgybttrqva%2Psvz_zlfcnpr_aba_HTP%2Psvz_zlfcnpr_havgrq-fgngrf&hey=uggc%3N%2S%2Sjjj.zlfcnpr.pbz%2S&nq_glcr=grkg&rvq=6083027&rn=0&sez=0&tn_ivq=320757904.1231367694&tn_fvq=1231367694&tn_uvq=1758792003&synfu=9.0.115&h_u=768&h_j=1024&h_nu=738&h_nj=1024&h_pq=24&h_gm=-480&h_uvf=2&h_wnin=gehr&h_acyht=7&h_azvzr=22'; + var str52 = 'uggc://zfacbegny.112.2b7.arg/o/ff/zfacbegnyubzr/1/U.7-cqi-2/f55332979829981?[NDO]&aqu=1&g=7%2S0%2S2009%2014%3N38%3N42%203%20480&af=zfacbegny&cntrAnzr=HF%20UCZFSGJ&t=uggc%3N%2S%2Sjjj.zfa.pbz%2S&f=1024k768&p=24&x=L&oj=994&ou=634&uc=A&{2}&[NDR]'; + var str53 = 'cnerag puebzr6 fvatyr1 gno fryrpgrq ovaq qbhoyr2 ps'; + var str54 = 'ZFPhygher=VC=74.125.75.3&VCPhygher=ra-HF&CersreerqPhygher=ra-HF&Pbhagel=IIZ%3Q&SbeprqRkcvengvba=633669357391353591&gvzrMbar=-8&HFEYBP=DKWyLHAiMTH9AwHjWxAcqUx9GJ91oaEunJ4tIzyyqlMQo3IhqUW5D29xMG1IHlMQo3IhqUW5GzSgMG1Iozy0MJDtH3EuqTImWxEgLHAiMTH9BQN3WxkuqTy0qJEyCGZ3YwDkBGVzGT9hM2y0qJEyCF0kZwVhZQH3APMDo3A0LJkQo2EyCGx0ZQDmWyWyM2yiox5uoJH9D0R%3Q'; + var str55 = 'ZFPhygher=VC=74.125.75.3&VCPhygher=ra-HF&CersreerqPhygher=ra-HF&CersreerqPhygherCraqvat=&Pbhagel=IIZ=&SbeprqRkcvengvba=633669357391353591&gvzrMbar=0&HFEYBP=DKWyLHAiMTH9AwHjWxAcqUx9GJ91oaEunJ4tIzyyqlMQo3IhqUW5D29xMG1IHlMQo3IhqUW5GzSgMG1Iozy0MJDtH3EuqTImWxEgLHAiMTH9BQN3WxkuqTy0qJEyCGZ3YwDkBGVzGT9hM2y0qJEyCF0kZwVhZQH3APMDo3A0LJkQo2EyCGx0ZQDmWyWyM2yiox5uoJH9D0R='; + var str56 = 'ne;ng;nh;or;oe;pn;pu;py;pa;qr;qx;rf;sv;se;to;ux;vq;vr;va;vg;wc;xe;zk;zl;ay;ab;am;cu;cy;cg;eh;fr;ft;gu;ge;gj;mn;'; + var str57 = 'ZP1=I=3&THVQ=6nnpr9q661804s33nnop45nosqp17q85; zu=ZFSG; PHYGHER=RA-HF; SyvtugTebhcVq=97; SyvtugVq=OnfrCntr; ucfie=Z:5|S:5|G:5|R:5|Q:oyh|J:S; ucpyv=J.U|Y.|F.|E.|H.Y|P.|U.; hfucjrn=jp:HFPN0746; ZHVQ=Q783SN9O14054831N4869R51P0SO8886&GHVQ=1'; + var str58 = 'ZP1=I=3&THVQ=6nnpr9q661804s33nnop45nosqp17q85; zu=ZFSG; PHYGHER=RA-HF; SyvtugTebhcVq=97; SyvtugVq=OnfrCntr; ucfie=Z:5|S:5|G:5|R:5|Q:oyh|J:S; ucpyv=J.U|Y.|F.|E.|H.Y|P.|U.; hfucjrn=jp:HFPN0746; ZHVQ=Q783SN9O14054831N4869R51P0SO8886'; + var str59 = 'ZP1=I=3&THVQ=6nnpr9q661804s33nnop45nosqp17q85; zu=ZFSG; PHYGHER=RA-HF; SyvtugTebhcVq=97; SyvtugVq=OnfrCntr; ucfie=Z:5|S:5|G:5|R:5|Q:oyh|J:S; ucpyv=J.U|Y.|F.|E.|H.Y|P.|U.; hfucjrn=jp:HFPN0746; ZHVQ=Q783SN9O14054831N4869R51P0SO8886; mvc=m:94043|yn:37.4154|yb:-122.0585|p:HF|ue:1'; + var str60 = 'ZP1=I=3&THVQ=6nnpr9q661804s33nnop45nosqp17q85; zu=ZFSG; PHYGHER=RA-HF; SyvtugTebhcVq=97; SyvtugVq=OnfrCntr; ucfie=Z:5|S:5|G:5|R:5|Q:oyh|J:S; ucpyv=J.U|Y.|F.|E.|H.Y|P.|U.; hfucjrn=jp:HFPN0746; ZHVQ=Q783SN9O14054831N4869R51P0SO8886; mvc=m:94043|yn:37.4154|yb:-122.0585|p:HF'; + var str61 = 'uggc://gx2.fgp.f-zfa.pbz/oe/uc/11/ra-hf/pff/v/g.tvs#uggc://gx2.fgo.f-zfa.pbz/v/29/4RQP4969777N048NPS4RRR3PO2S7S.wct'; + var str62 = 'uggc://gx2.fgp.f-zfa.pbz/oe/uc/11/ra-hf/pff/v/g.tvs#uggc://gx2.fgo.f-zfa.pbz/v/OQ/63NP9O94NS5OQP1249Q9S1ROP7NS3.wct'; + var str63 = 'zbmvyyn/5.0 (jvaqbjf; h; jvaqbjf ag 5.1; ra-hf) nccyrjroxvg/528.9 (xugzy, yvxr trpxb) puebzr/2.0.157.0 fnsnev/528.9'; + var s94 = computeInputVariants(str42, 5); + var s95 = computeInputVariants(str43, 5); + var s96 = computeInputVariants(str44, 5); + var s97 = computeInputVariants(str47, 5); + var s98 = computeInputVariants(str48, 5); + var s99 = computeInputVariants(str49, 5); + var s100 = computeInputVariants(str50, 5); + var s101 = computeInputVariants(str51, 5); + var s102 = computeInputVariants(str52, 5); + var s103 = computeInputVariants(str53, 5); + + function runBlock9() { + for (var i = 0; i < 5; i++) { + s94[i].split(re32); + s95[i].split(re32); + 'svz_zlfcnpr_hfre-ivrj-pbzzragf,svz_zlfcnpr_havgrq-fgngrf'.split(re20); + s96[i].replace(re33, ''); + 'zrah_arj zrah_arj_gbttyr zrah_gbttyr'.replace(re67, ''); + 'zrah_byq zrah_byq_gbttyr zrah_gbttyr'.replace(re67, ''); + re8.exec('102n9o0o9pq60132qn0337rr867p75953502q2s27s2s5r98'); + re8.exec('144631658.0.10.1231364380'); + re8.exec('144631658.1231364380.1.1.hgzpfe=(qverpg)|hgzppa=(qverpg)|hgzpzq=(abar)'); + re8.exec('144631658.3931862196947939300.1231364380.1231364380.1231364380.1'); + re8.exec('441326q33660'); + re8.exec('SbeprqRkcvengvba=633669341278771470'); + re8.exec(str45); + re8.exec(str46); + re8.exec('AFP_zp_dfctwzssrwh-aowb_80=441326q33660'); + re8.exec('FrffvbaQQS2=102n9o0o9pq60132qn0337rr867p75953502q2s27s2s5r98'); + re8.exec('__hgzn=144631658.3931862196947939300.1231364380.1231364380.1231364380.1'); + re8.exec('__hgzo=144631658.0.10.1231364380'); + re8.exec('__hgzm=144631658.1231364380.1.1.hgzpfe=(qverpg)|hgzppa=(qverpg)|hgzpzq=(abar)'); + } + for (var i = 0; i < 4; i++) { + ' yvfg1'.replace(re14, ''); + ' yvfg1'.replace(re15, ''); + ' yvfg2'.replace(re14, ''); + ' yvfg2'.replace(re15, ''); + ' frneputebhc1'.replace(re14, ''); + ' frneputebhc1'.replace(re15, ''); + s97[i].replace(re68, ''); + s97[i].replace(re18, ''); + ''.replace(/&/g, ''); + ''.replace(re35, ''); + '(..-{0})(\|(\d+)|)'.replace(re63, ''); + s98[i].replace(re18, ''); + '//vzt.jro.qr/vij/FC/${cngu}/${anzr}/${inyhr}?gf=${abj}'.replace(re56, ''); + '//vzt.jro.qr/vij/FC/tzk_uc/${anzr}/${inyhr}?gf=${abj}'.replace(/(\$\{anzr\})|(\$anzr\b)/g, ''); + 'Jvaqbjf Yvir Ubgznvy{1}'.replace(re69, ''); + '{0}{1}'.replace(re63, ''); + '{1}'.replace(re69, ''); + '{1}'.replace(re63, ''); + 'Vzntrf'.replace(re15, ''); + 'ZFA'.replace(re15, ''); + 'Zncf'.replace(re15, ''); + 'Zbq-Vasb-Vasb-WninFpevcgUvag'.replace(re39, ''); + 'Arjf'.replace(re15, ''); + s99[i].split(re32); + s100[i].split(re32); + 'Ivqrb'.replace(re15, ''); + 'Jro'.replace(re15, ''); + 'n'.replace(re39, ''); + 'nwnkFgneg'.split(re70); + 'nwnkFgbc'.split(re70); + 'ovaq'.replace(re14, ''); + 'ovaq'.replace(re15, ''); + 'oevatf lbh zber. Zber fcnpr (5TO), zber frphevgl, fgvyy serr.'.replace(re63, ''); + 'puvyq p1 svefg qrpx'.replace(re14, ''); + 'puvyq p1 svefg qrpx'.replace(re15, ''); + 'puvyq p1 svefg qbhoyr2'.replace(re14, ''); + 'puvyq p1 svefg qbhoyr2'.replace(re15, ''); + 'puvyq p2 ynfg'.replace(re14, ''); + 'puvyq p2 ynfg'.replace(re15, ''); + 'puvyq p2'.replace(re14, ''); + 'puvyq p2'.replace(re15, ''); + 'puvyq p3'.replace(re14, ''); + 'puvyq p3'.replace(re15, ''); + 'puvyq p4 ynfg'.replace(re14, ''); + 'puvyq p4 ynfg'.replace(re15, ''); + 'pbclevtug'.replace(re14, ''); + 'pbclevtug'.replace(re15, ''); + 'qZFAZR_1'.replace(re14, ''); + 'qZFAZR_1'.replace(re15, ''); + 'qbhoyr2 ps'.replace(re14, ''); + 'qbhoyr2 ps'.replace(re15, ''); + 'qbhoyr2'.replace(re14, ''); + 'qbhoyr2'.replace(re15, ''); + 'uqy_arj'.replace(re14, ''); + 'uqy_arj'.replace(re15, ''); + 'uc_fubccvatobk'.replace(re30, ''); + 'ugzy%2Rvq'.replace(re29, ''); + 'ugzy%2Rvq'.replace(re30, ''); + s101[i].replace(re33, ''); + 'uggc://wf.hv-cbegny.qr/tzk/ubzr/wf/20080602/cebgbglcr.wf${4}${5}'.replace(re71, ''); + 'uggc://wf.hv-cbegny.qr/tzk/ubzr/wf/20080602/cebgbglcr.wf${5}'.replace(re72, ''); + s102[i].replace(re73, ''); + 'uggc://zfacbegny.112.2b7.arg/o/ff/zfacbegnyubzr/1/U.7-cqi-2/f55332979829981?[NDO]&{1}&{2}&[NDR]'.replace(re69, ''); + 'vztZFSG'.replace(re14, ''); + 'vztZFSG'.replace(re15, ''); + 'zfasbbg1 ps'.replace(re14, ''); + 'zfasbbg1 ps'.replace(re15, ''); + s103[i].replace(re14, ''); + s103[i].replace(re15, ''); + 'cnerag puebzr6 fvatyr1 gno fryrpgrq ovaq'.replace(re14, ''); + 'cnerag puebzr6 fvatyr1 gno fryrpgrq ovaq'.replace(re15, ''); + 'cevznel'.replace(re14, ''); + 'cevznel'.replace(re15, ''); + 'erpgnatyr'.replace(re30, ''); + 'frpbaqnel'.replace(re14, ''); + 'frpbaqnel'.replace(re15, ''); + 'haybnq'.split(re70); + '{0}{1}1'.replace(re63, ''); + '|{1}1'.replace(re69, ''); + /(..-HF)(\|(\d+)|)/i.exec('xb-xe,ra-va,gu-gu'); + re4.exec('/ZlFcnprNccf/NccPnainf,45000012'); + re8.exec('144631658.0.10.1231367708'); + re8.exec('144631658.1231367708.1.1.hgzpfe=(qverpg)|hgzppa=(qverpg)|hgzpzq=(abar)'); + re8.exec('144631658.2770915348920628700.1231367708.1231367708.1231367708.1'); + re8.exec('4413235p3660'); + re8.exec('441327q73660'); + re8.exec('9995p6rp12rrnr893334ro7nq70o7p64p69rqn844prs1473'); + re8.exec('SbeprqRkcvengvba=633669350559478880'); + re8.exec(str54); + re8.exec(str55); + re8.exec('AFP_zp_dfctwzs-aowb_80=441327q73660'); + re8.exec('AFP_zp_kkk-aowb_80=4413235p3660'); + re8.exec('FrffvbaQQS2=9995p6rp12rrnr893334ro7nq70o7p64p69rqn844prs1473'); + re8.exec('__hgzn=144631658.2770915348920628700.1231367708.1231367708.1231367708.1'); + re8.exec('__hgzo=144631658.0.10.1231367708'); + re8.exec('__hgzm=144631658.1231367708.1.1.hgzpfe=(qverpg)|hgzppa=(qverpg)|hgzpzq=(abar)'); + re34.exec(s99[i]); + re34.exec(s100[i]); + /ZFVR\s+5[.]01/.exec(s15[i]); + /HF(?=;)/i.exec(str56); + re74.exec(s97[i]); + re28.exec('svefg npgvir svefgNpgvir'); + re28.exec('ynfg'); + /\bp:(..)/i.exec('m:94043|yn:37.4154|yb:-122.0585|p:HF'); + re75.exec(str57); + re75.exec(str58); + re76.exec(str57); + re76.exec(str58); + re77.exec(str57); + re77.exec(str58); + /\bhfucce\s*=\s*([^;]*)/i.exec(str59); + re78.exec(str57); + re78.exec(str58); + /\bjci\s*=\s*([^;]*)/i.exec(str59); + re79.exec(str58); + re79.exec(str60); + re79.exec(str59); + /\|p:([a-z]{2})/i.exec('m:94043|yn:37.4154|yb:-122.0585|p:HF|ue:1'); + re80.exec(s97[i]); + re61.exec('cebgbglcr.wf'); + re68.exec(s97[i]); + re81.exec(s97[i]); + re82.exec(s97[i]); + /^Fubpxjnir Synfu (\d)/.exec(s21[i]); + /^Fubpxjnir Synfu (\d+)/.exec(s21[i]); + re83.exec('[bowrpg tybony]'); + re62.exec(s97[i]); + re84.exec(str61); + re84.exec(str62); + /jroxvg/.exec(str63); + } + } + var re85 = /eaq_zbqobkva/; + var str64 = '1231365729213'; + var str65 = '74.125.75.3-1057165600.29978900'; + var str66 = '74.125.75.3-1057165600.29978900.1231365730214'; + var str67 = 'Frnepu%20Zvpebfbsg.pbz'; + var str68 = 'FrffvbaQQS2=8sqq78r9n442851q565599o401385sp3s04r92rnn7o19ssn; ZFPhygher=VC=74.125.75.17&VCPhygher=ra-HF&CersreerqPhygher=ra-HF&CersreerqPhygherCraqvat=&Pbhagel=IIZ=&SbeprqRkcvengvba=633669340386893867&gvzrMbar=0&HFEYBP=DKWyLHAiMTH9AwHjWxAcqUx9GJ91oaEunJ4tIzyyqlMQo3IhqUW5D29xMG1IHlMQo3IhqUW5GzSgMG1Iozy0MJDtH3EuqTImWxEgLHAiMTH9BQN3WxkuqTy0qJEyCGZ3YwDkBGVzGT9hM2y0qJEyCF0kZwVhZQH3APMDo3A0LJkQo2EyCGx0ZQDmWyWyM2yiox5uoJH9D0R='; + var str69 = 'FrffvbaQQS2=8sqq78r9n442851q565599o401385sp3s04r92rnn7o19ssn; __hgzm=144631658.1231365779.1.1.hgzpfe=(qverpg)|hgzppa=(qverpg)|hgzpzq=(abar); __hgzn=144631658.1877536177953918500.1231365779.1231365779.1231365779.1; __hgzo=144631658.0.10.1231365779; __hgzp=144631658; ZFPhygher=VC=74.125.75.17&VCPhygher=ra-HF&CersreerqPhygher=ra-HF&Pbhagel=IIZ%3Q&SbeprqRkcvengvba=633669340386893867&gvzrMbar=-8&HFEYBP=DKWyLHAiMTH9AwHjWxAcqUx9GJ91oaEunJ4tIzyyqlMQo3IhqUW5D29xMG1IHlMQo3IhqUW5GzSgMG1Iozy0MJDtH3EuqTImWxEgLHAiMTH9BQN3WxkuqTy0qJEyCGZ3YwDkBGVzGT9hM2y0qJEyCF0kZwVhZQH3APMDo3A0LJkQo2EyCGx0ZQDmWyWyM2yiox5uoJH9D0R%3Q'; + var str70 = 'I=3%26THVQ=757q3ss871q44o7o805n8113n5p72q52'; + var str71 = 'I=3&THVQ=757q3ss871q44o7o805n8113n5p72q52'; + var str72 = 'uggc://tbbtyrnqf.t.qbhoyrpyvpx.arg/cntrnq/nqf?pyvrag=pn-svz_zlfcnpr_zlfcnpr-ubzrcntr_wf&qg=1231365765292&uy=ra&nqfnsr=uvtu&br=hgs8&ahz_nqf=4&bhgchg=wf&nqgrfg=bss&pbeeryngbe=1231365765292&punaary=svz_zlfcnpr_ubzrcntr_abgybttrqva%2Psvz_zlfcnpr_aba_HTP%2Psvz_zlfcnpr_havgrq-fgngrf&hey=uggc%3N%2S%2Sohyyrgvaf.zlfcnpr.pbz%2Svaqrk.psz&nq_glcr=grkg&rvq=6083027&rn=0&sez=0&tn_ivq=1579793869.1231365768&tn_fvq=1231365768&tn_uvq=2056210897&synfu=9.0.115&h_u=768&h_j=1024&h_nu=738&h_nj=1024&h_pq=24&h_gm=-480&h_uvf=2&h_wnin=gehr&h_acyht=7&h_azvzr=22'; + var str73 = 'frnepu.zvpebfbsg.pbz'; + var str74 = 'frnepu.zvpebfbsg.pbz/'; + var str75 = 'ZFPhygher=VC=74.125.75.17&VCPhygher=ra-HF&CersreerqPhygher=ra-HF&Pbhagel=IIZ%3Q&SbeprqRkcvengvba=633669340386893867&gvzrMbar=-8&HFEYBP=DKWyLHAiMTH9AwHjWxAcqUx9GJ91oaEunJ4tIzyyqlMQo3IhqUW5D29xMG1IHlMQo3IhqUW5GzSgMG1Iozy0MJDtH3EuqTImWxEgLHAiMTH9BQN3WxkuqTy0qJEyCGZ3YwDkBGVzGT9hM2y0qJEyCF0kZwVhZQH3APMDo3A0LJkQo2EyCGx0ZQDmWyWyM2yiox5uoJH9D0R%3Q'; + var str76 = 'ZFPhygher=VC=74.125.75.17&VCPhygher=ra-HF&CersreerqPhygher=ra-HF&CersreerqPhygherCraqvat=&Pbhagel=IIZ=&SbeprqRkcvengvba=633669340386893867&gvzrMbar=0&HFEYBP=DKWyLHAiMTH9AwHjWxAcqUx9GJ91oaEunJ4tIzyyqlMQo3IhqUW5D29xMG1IHlMQo3IhqUW5GzSgMG1Iozy0MJDtH3EuqTImWxEgLHAiMTH9BQN3WxkuqTy0qJEyCGZ3YwDkBGVzGT9hM2y0qJEyCF0kZwVhZQH3APMDo3A0LJkQo2EyCGx0ZQDmWyWyM2yiox5uoJH9D0R='; + function runBlock10() { + for (var i = 0; i < 3; i++) { + '%3Szxg=ra-HF'.replace(re39, ''); + '-8'.replace(re40, ''); + '-8'.replace(re10, ''); + '-8'.replace(re51, ''); + '-8'.replace(re52, ''); + '-8'.replace(re53, ''); + '-8'.replace(re39, ''); + '-8'.replace(re54, ''); + '1.5'.replace(re40, ''); + '1.5'.replace(re10, ''); + '1.5'.replace(re51, ''); + '1.5'.replace(re52, ''); + '1.5'.replace(re53, ''); + '1.5'.replace(re39, ''); + '1.5'.replace(re54, ''); + '1024k768'.replace(re40, ''); + '1024k768'.replace(re10, ''); + '1024k768'.replace(re51, ''); + '1024k768'.replace(re52, ''); + '1024k768'.replace(re53, ''); + '1024k768'.replace(re39, ''); + '1024k768'.replace(re54, ''); + str64.replace(re40, ''); + str64.replace(re10, ''); + str64.replace(re51, ''); + str64.replace(re52, ''); + str64.replace(re53, ''); + str64.replace(re39, ''); + str64.replace(re54, ''); + '14'.replace(re40, ''); + '14'.replace(re10, ''); + '14'.replace(re51, ''); + '14'.replace(re52, ''); + '14'.replace(re53, ''); + '14'.replace(re39, ''); + '14'.replace(re54, ''); + '24'.replace(re40, ''); + '24'.replace(re10, ''); + '24'.replace(re51, ''); + '24'.replace(re52, ''); + '24'.replace(re53, ''); + '24'.replace(re39, ''); + '24'.replace(re54, ''); + str65.replace(re40, ''); + str65.replace(re10, ''); + str65.replace(re51, ''); + str65.replace(re52, ''); + str65.replace(re53, ''); + str65.replace(re39, ''); + str65.replace(re54, ''); + str66.replace(re40, ''); + str66.replace(re10, ''); + str66.replace(re51, ''); + str66.replace(re52, ''); + str66.replace(re53, ''); + str66.replace(re39, ''); + str66.replace(re54, ''); + '9.0'.replace(re40, ''); + '9.0'.replace(re10, ''); + '9.0'.replace(re51, ''); + '9.0'.replace(re52, ''); + '9.0'.replace(re53, ''); + '9.0'.replace(re39, ''); + '9.0'.replace(re54, ''); + '994k634'.replace(re40, ''); + '994k634'.replace(re10, ''); + '994k634'.replace(re51, ''); + '994k634'.replace(re52, ''); + '994k634'.replace(re53, ''); + '994k634'.replace(re39, ''); + '994k634'.replace(re54, ''); + '?zxg=ra-HF'.replace(re40, ''); + '?zxg=ra-HF'.replace(re10, ''); + '?zxg=ra-HF'.replace(re51, ''); + '?zxg=ra-HF'.replace(re52, ''); + '?zxg=ra-HF'.replace(re53, ''); + '?zxg=ra-HF'.replace(re54, ''); + 'PAA.pbz'.replace(re25, ''); + 'PAA.pbz'.replace(re12, ''); + 'PAA.pbz'.replace(re39, ''); + 'Qngr & Gvzr'.replace(re25, ''); + 'Qngr & Gvzr'.replace(re12, ''); + 'Qngr & Gvzr'.replace(re39, ''); + 'Frnepu Zvpebfbsg.pbz'.replace(re40, ''); + 'Frnepu Zvpebfbsg.pbz'.replace(re54, ''); + str67.replace(re10, ''); + str67.replace(re51, ''); + str67.replace(re52, ''); + str67.replace(re53, ''); + str67.replace(re39, ''); + str68.split(re32); + str69.split(re32); + str70.replace(re52, ''); + str70.replace(re53, ''); + str70.replace(re39, ''); + str71.replace(re40, ''); + str71.replace(re10, ''); + str71.replace(re51, ''); + str71.replace(re54, ''); + 'Jrngure'.replace(re25, ''); + 'Jrngure'.replace(re12, ''); + 'Jrngure'.replace(re39, ''); + 'LbhGhor'.replace(re25, ''); + 'LbhGhor'.replace(re12, ''); + 'LbhGhor'.replace(re39, ''); + str72.replace(re33, ''); + 'erzbgr_vsenzr_1'.replace(/^erzbgr_vsenzr_/, ''); + str73.replace(re40, ''); + str73.replace(re10, ''); + str73.replace(re51, ''); + str73.replace(re52, ''); + str73.replace(re53, ''); + str73.replace(re39, ''); + str73.replace(re54, ''); + str74.replace(re40, ''); + str74.replace(re10, ''); + str74.replace(re51, ''); + str74.replace(re52, ''); + str74.replace(re53, ''); + str74.replace(re39, ''); + str74.replace(re54, ''); + 'lhv-h'.replace(/\-/g, ''); + re9.exec('p'); + re9.exec('qz p'); + re9.exec('zbqynory'); + re9.exec('lhv-h svefg'); + re8.exec('144631658.0.10.1231365779'); + re8.exec('144631658.1231365779.1.1.hgzpfe=(qverpg)|hgzppa=(qverpg)|hgzpzq=(abar)'); + re8.exec('144631658.1877536177953918500.1231365779.1231365779.1231365779.1'); + re8.exec(str75); + re8.exec(str76); + re8.exec('__hgzn=144631658.1877536177953918500.1231365779.1231365779.1231365779.1'); + re8.exec('__hgzo=144631658.0.10.1231365779'); + re8.exec('__hgzm=144631658.1231365779.1.1.hgzpfe=(qverpg)|hgzppa=(qverpg)|hgzpzq=(abar)'); + re34.exec(str68); + re34.exec(str69); + /^$/.exec(''); + re31.exec('qr'); + /^znk\d+$/.exec(''); + /^zva\d+$/.exec(''); + /^erfgber$/.exec(''); + re85.exec('zbqobkva zbqobk_abcnqqvat '); + re85.exec('zbqgvgyr'); + re85.exec('eaq_zbqobkva '); + re85.exec('eaq_zbqgvgyr '); + /frpgvba\d+_pbagragf/.exec('obggbz_ani'); + } + } + var re86 = /;\s*/; + var re87 = /(\$\{inyhr\})|(\$inyhr\b)/g; + var re88 = /(\$\{abj\})|(\$abj\b)/g; + var re89 = /\s+$/; + var re90 = /^\s+/; + var re91 = /(\\\"|\x00-|\x1f|\x7f-|\x9f|\u00ad|\u0600-|\u0604|\u070f|\u17b4|\u17b5|\u200c-|\u200f|\u2028-|\u202f|\u2060-|\u206f|\ufeff|\ufff0-|\uffff)/g; + var re92 = /^(:)([\w-]+)\("?'?(.*?(\(.*?\))?[^(]*?)"?'?\)/; + var re93 = /^([:.#]*)((?:[\w\u0128-\uffff*_-]|\\.)+)/; + var re94 = /^(\[) *@?([\w-]+) *([!*$^~=]*) *('?"?)(.*?)\4 *\]/; + var str77 = '#fubhgobk .pybfr'; + var str78 = 'FrffvbaQQS2=102n9o0o9pq60132qn0337rr867p75953502q2s27s2s5r98; ZFPhygher=VC=74.125.75.1&VCPhygher=ra-HF&CersreerqPhygher=ra-HF&CersreerqPhygherCraqvat=&Pbhagel=IIZ=&SbeprqRkcvengvba=633669341278771470&gvzrMbar=0&HFEYBP=DKWyLHAiMTH9AwHjWxAcqUx9GJ91oaEunJ4tIzyyqlMQo3IhqUW5D29xMG1IHlMQo3IhqUW5GzSgMG1Iozy0MJDtH3EuqTImWxEgLHAiMTH9BQN3WxkuqTy0qJEyCGZ3YwDkBGVzGT9hM2y0qJEyCF0kZwVhZQH3APMDo3A0LJkQo2EyCGx0ZQDmWyWyM2yiox5uoJH9D0R=; AFP_zp_dfctwzssrwh-aowb_80=441326q33660'; + var str79 = 'FrffvbaQQS2=102n9o0o9pq60132qn0337rr867p75953502q2s27s2s5r98; AFP_zp_dfctwzssrwh-aowb_80=441326q33660; __hgzm=144631658.1231365869.1.1.hgzpfe=(qverpg)|hgzppa=(qverpg)|hgzpzq=(abar); __hgzn=144631658.1670816052019209000.1231365869.1231365869.1231365869.1; __hgzo=144631658.0.10.1231365869; __hgzp=144631658; ZFPhygher=VC=74.125.75.1&VCPhygher=ra-HF&CersreerqPhygher=ra-HF&Pbhagel=IIZ%3Q&SbeprqRkcvengvba=633669341278771470&gvzrMbar=-8&HFEYBP=DKWyLHAiMTH9AwHjWxAcqUx9GJ91oaEunJ4tIzyyqlMQo3IhqUW5D29xMG1IHlMQo3IhqUW5GzSgMG1Iozy0MJDtH3EuqTImWxEgLHAiMTH9BQN3WxkuqTy0qJEyCGZ3YwDkBGVzGT9hM2y0qJEyCF0kZwVhZQH3APMDo3A0LJkQo2EyCGx0ZQDmWyWyM2yiox5uoJH9D0R%3Q'; + var str80 = 'FrffvbaQQS2=9995p6rp12rrnr893334ro7nq70o7p64p69rqn844prs1473; ZFPhygher=VC=74.125.75.1&VCPhygher=ra-HF&CersreerqPhygher=ra-HF&CersreerqPhygherCraqvat=&Pbhagel=IIZ=&SbeprqRkcvengvba=633669350559478880&gvzrMbar=0&HFEYBP=DKWyLHAiMTH9AwHjWxAcqUx9GJ91oaEunJ4tIzyyqlMQo3IhqUW5D29xMG1IHlMQo3IhqUW5GzSgMG1Iozy0MJDtH3EuqTImWxEgLHAiMTH9BQN3WxkuqTy0qJEyCGZ3YwDkBGVzGT9hM2y0qJEyCF0kZwVhZQH3APMDo3A0LJkQo2EyCGx0ZQDmWyWyM2yiox5uoJH9D0R=; AFP_zp_dfctwzs-aowb_80=441327q73660'; + var str81 = 'FrffvbaQQS2=9995p6rp12rrnr893334ro7nq70o7p64p69rqn844prs1473; AFP_zp_dfctwzs-aowb_80=441327q73660; __hgzm=144631658.1231367054.1.1.hgzpfe=(qverpg)|hgzppa=(qverpg)|hgzpzq=(abar); __hgzn=144631658.1796080716621419500.1231367054.1231367054.1231367054.1; __hgzo=144631658.0.10.1231367054; __hgzp=144631658; ZFPhygher=VC=74.125.75.1&VCPhygher=ra-HF&CersreerqPhygher=ra-HF&Pbhagel=IIZ%3Q&SbeprqRkcvengvba=633669350559478880&gvzrMbar=-8&HFEYBP=DKWyLHAiMTH9AwHjWxAcqUx9GJ91oaEunJ4tIzyyqlMQo3IhqUW5D29xMG1IHlMQo3IhqUW5GzSgMG1Iozy0MJDtH3EuqTImWxEgLHAiMTH9BQN3WxkuqTy0qJEyCGZ3YwDkBGVzGT9hM2y0qJEyCF0kZwVhZQH3APMDo3A0LJkQo2EyCGx0ZQDmWyWyM2yiox5uoJH9D0R%3Q'; + var str82 = '[glcr=fhozvg]'; + var str83 = 'n.svryqOga,n.svryqOgaPnapry'; + var str84 = 'n.svryqOgaPnapry'; + var str85 = 'oyvpxchaxg'; + var str86 = 'qvi.bow-nppbeqvba qg'; + var str87 = 'uggc://tbbtyrnqf.t.qbhoyrpyvpx.arg/cntrnq/nqf?pyvrag=pn-svz_zlfcnpr_nccf_wf&qg=1231367052227&uy=ra&nqfnsr=uvtu&br=hgs8&ahz_nqf=4&bhgchg=wf&nqgrfg=bss&pbeeryngbe=1231367052227&punaary=svz_zlfcnpr_nccf-pnainf%2Psvz_zlfcnpr_havgrq-fgngrf&hey=uggc%3N%2S%2Scebsvyr.zlfcnpr.pbz%2SZbqhyrf%2SNccyvpngvbaf%2SCntrf%2SPnainf.nfck&nq_glcr=grkg&rvq=6083027&rn=0&sez=1&tn_ivq=716357910.1231367056&tn_fvq=1231367056&tn_uvq=1387206491&synfu=9.0.115&h_u=768&h_j=1024&h_nu=738&h_nj=1024&h_pq=24&h_gm=-480&h_uvf=2&h_wnin=gehr&h_acyht=7&h_azvzr=22'; + var str88 = 'uggc://tbbtyrnqf.t.qbhoyrpyvpx.arg/cntrnq/nqf?pyvrag=pn-svz_zlfcnpr_zlfcnpr-ubzrcntr_wf&qg=1231365851658&uy=ra&nqfnsr=uvtu&br=hgs8&ahz_nqf=4&bhgchg=wf&nqgrfg=bss&pbeeryngbe=1231365851658&punaary=svz_zlfcnpr_ubzrcntr_abgybttrqva%2Psvz_zlfcnpr_aba_HTP%2Psvz_zlfcnpr_havgrq-fgngrf&hey=uggc%3N%2S%2Scebsvyrrqvg.zlfcnpr.pbz%2Svaqrk.psz&nq_glcr=grkg&rvq=6083027&rn=0&sez=0&tn_ivq=1979828129.1231365855&tn_fvq=1231365855&tn_uvq=2085229649&synfu=9.0.115&h_u=768&h_j=1024&h_nu=738&h_nj=1024&h_pq=24&h_gm=-480&h_uvf=2&h_wnin=gehr&h_acyht=7&h_azvzr=22'; + var str89 = 'uggc://zfacbegny.112.2b7.arg/o/ff/zfacbegnyubzr/1/U.7-cqi-2/f55023338617756?[NDO]&aqu=1&g=7%2S0%2S2009%2014%3N12%3N47%203%20480&af=zfacbegny&cntrAnzr=HF%20UCZFSGJ&t=uggc%3N%2S%2Sjjj.zfa.pbz%2S&f=0k0&p=43835816&x=A&oj=994&ou=634&uc=A&{2}&[NDR]'; + var str90 = 'zrgn[anzr=nwnkHey]'; + var str91 = 'anpuevpugra'; + var str92 = 'b oS={\'oT\':1.1};x $8n(B){z(B!=o9)};x $S(B){O(!$8n(B))z A;O(B.4L)z\'T\';b S=7t B;O(S==\'2P\'&&B.p4){23(B.7f){12 1:z\'T\';12 3:z/\S/.2g(B.8M)?\'ox\':\'oh\'}}O(S==\'2P\'||S==\'x\'){23(B.nE){12 2V:z\'1O\';12 7I:z\'5a\';12 18:z\'4B\'}O(7t B.I==\'4F\'){O(B.3u)z\'pG\';O(B.8e)z\'1p\'}}z S};x $2p(){b 4E={};Z(b v=0;v<1p.I;v++){Z(b X 1o 1p[v]){b nc=1p[v][X];b 6E=4E[X];O(6E&&$S(nc)==\'2P\'&&$S(6E)==\'2P\')4E[X]=$2p(6E,nc);17 4E[X]=nc}}z 4E};b $E=7p.E=x(){b 1d=1p;O(!1d[1])1d=[p,1d[0]];Z(b X 1o 1d[1])1d[0][X]=1d[1][X];z 1d[0]};b $4D=7p.pJ=x(){Z(b v=0,y=1p.I;v-1:p.3F(2R)>-1},nX:x(){z p.3y(/([.*+?^${}()|[\]\/\\])/t,\'\\$1\')}});2V.E({5V:x(1O){O(p.I<3)z A;O(p.I==4&&p[3]==0&&!1O)z\'p5\';b 3P=[];Z(b v=0;v<3;v++){b 52=(p[v]-0).4h(16);3P.1x((52.I==1)?\'0\'+52:52)}z 1O?3P:\'#\'+3P.2u(\'\')},5U:x(1O){O(p.I!=3)z A;b 1i=[];Z(b v=0;v<3;v++){1i.1x(5K((p[v].I==1)?p[v]+p[v]:p[v],16))}z 1O?1i:\'1i(\'+1i.2u(\',\')+\')\'}});7F.E({3n:x(P){b J=p;P=$2p({\'L\':J,\'V\':A,\'1p\':1S,\'2x\':A,\'4s\':A,\'6W\':A},P);O($2O(P.1p)&&$S(P.1p)!=\'1O\')P.1p=[P.1p];z x(V){b 1d;O(P.V){V=V||H.V;1d=[(P.V===1r)?V:Y P.V(V)];O(P.1p)1d.E(P.1p)}17 1d=P.1p||1p;b 3C=x(){z J.3H($5S(P'; + var str93 = 'hagreunyghat'; + var str94 = 'ZFPhygher=VC=74.125.75.1&VCPhygher=ra-HF&CersreerqPhygher=ra-HF&Pbhagel=IIZ%3Q&SbeprqRkcvengvba=633669341278771470&gvzrMbar=-8&HFEYBP=DKWyLHAiMTH9AwHjWxAcqUx9GJ91oaEunJ4tIzyyqlMQo3IhqUW5D29xMG1IHlMQo3IhqUW5GzSgMG1Iozy0MJDtH3EuqTImWxEgLHAiMTH9BQN3WxkuqTy0qJEyCGZ3YwDkBGVzGT9hM2y0qJEyCF0kZwVhZQH3APMDo3A0LJkQo2EyCGx0ZQDmWyWyM2yiox5uoJH9D0R%3Q'; + var str95 = 'ZFPhygher=VC=74.125.75.1&VCPhygher=ra-HF&CersreerqPhygher=ra-HF&Pbhagel=IIZ%3Q&SbeprqRkcvengvba=633669350559478880&gvzrMbar=-8&HFEYBP=DKWyLHAiMTH9AwHjWxAcqUx9GJ91oaEunJ4tIzyyqlMQo3IhqUW5D29xMG1IHlMQo3IhqUW5GzSgMG1Iozy0MJDtH3EuqTImWxEgLHAiMTH9BQN3WxkuqTy0qJEyCGZ3YwDkBGVzGT9hM2y0qJEyCF0kZwVhZQH3APMDo3A0LJkQo2EyCGx0ZQDmWyWyM2yiox5uoJH9D0R%3Q'; + var str96 = 'ZFPhygher=VC=74.125.75.1&VCPhygher=ra-HF&CersreerqPhygher=ra-HF&CersreerqPhygherCraqvat=&Pbhagel=IIZ=&SbeprqRkcvengvba=633669341278771470&gvzrMbar=0&HFEYBP=DKWyLHAiMTH9AwHjWxAcqUx9GJ91oaEunJ4tIzyyqlMQo3IhqUW5D29xMG1IHlMQo3IhqUW5GzSgMG1Iozy0MJDtH3EuqTImWxEgLHAiMTH9BQN3WxkuqTy0qJEyCGZ3YwDkBGVzGT9hM2y0qJEyCF0kZwVhZQH3APMDo3A0LJkQo2EyCGx0ZQDmWyWyM2yiox5uoJH9D0R='; + var str97 = 'ZFPhygher=VC=74.125.75.1&VCPhygher=ra-HF&CersreerqPhygher=ra-HF&CersreerqPhygherCraqvat=&Pbhagel=IIZ=&SbeprqRkcvengvba=633669350559478880&gvzrMbar=0&HFEYBP=DKWyLHAiMTH9AwHjWxAcqUx9GJ91oaEunJ4tIzyyqlMQo3IhqUW5D29xMG1IHlMQo3IhqUW5GzSgMG1Iozy0MJDtH3EuqTImWxEgLHAiMTH9BQN3WxkuqTy0qJEyCGZ3YwDkBGVzGT9hM2y0qJEyCF0kZwVhZQH3APMDo3A0LJkQo2EyCGx0ZQDmWyWyM2yiox5uoJH9D0R='; + var str98 = 'shapgvba (){Cuk.Nccyvpngvba.Frghc.Pber();Cuk.Nccyvpngvba.Frghc.Nwnk();Cuk.Nccyvpngvba.Frghc.Synfu();Cuk.Nccyvpngvba.Frghc.Zbqhyrf()}'; + function runBlock11() { + for (var i = 0; i < 2; i++) { + ' .pybfr'.replace(re18, ''); + ' n.svryqOgaPnapry'.replace(re18, ''); + ' qg'.replace(re18, ''); + str77.replace(re68, ''); + str77.replace(re18, ''); + ''.replace(re39, ''); + ''.replace(/^/, ''); + ''.split(re86); + '*'.replace(re39, ''); + '*'.replace(re68, ''); + '*'.replace(re18, ''); + '.pybfr'.replace(re68, ''); + '.pybfr'.replace(re18, ''); + '//vzt.jro.qr/vij/FC/tzk_uc/fperra/${inyhr}?gf=${abj}'.replace(re87, ''); + '//vzt.jro.qr/vij/FC/tzk_uc/fperra/1024?gf=${abj}'.replace(re88, ''); + '//vzt.jro.qr/vij/FC/tzk_uc/jvafvmr/${inyhr}?gf=${abj}'.replace(re87, ''); + '//vzt.jro.qr/vij/FC/tzk_uc/jvafvmr/992/608?gf=${abj}'.replace(re88, ''); + '300k120'.replace(re30, ''); + '300k250'.replace(re30, ''); + '310k120'.replace(re30, ''); + '310k170'.replace(re30, ''); + '310k250'.replace(re30, ''); + '9.0 e115'.replace(/^.*\.(.*)\s.*$/, ''); + 'Nppbeqvba'.replace(re2, ''); + 'Nxghryy\x0a'.replace(re89, ''); + 'Nxghryy\x0a'.replace(re90, ''); + 'Nccyvpngvba'.replace(re2, ''); + 'Oyvpxchaxg\x0a'.replace(re89, ''); + 'Oyvpxchaxg\x0a'.replace(re90, ''); + 'Svanamra\x0a'.replace(re89, ''); + 'Svanamra\x0a'.replace(re90, ''); + 'Tnzrf\x0a'.replace(re89, ''); + 'Tnzrf\x0a'.replace(re90, ''); + 'Ubebfxbc\x0a'.replace(re89, ''); + 'Ubebfxbc\x0a'.replace(re90, ''); + 'Xvab\x0a'.replace(re89, ''); + 'Xvab\x0a'.replace(re90, ''); + 'Zbqhyrf'.replace(re2, ''); + 'Zhfvx\x0a'.replace(re89, ''); + 'Zhfvx\x0a'.replace(re90, ''); + 'Anpuevpugra\x0a'.replace(re89, ''); + 'Anpuevpugra\x0a'.replace(re90, ''); + 'Cuk'.replace(re2, ''); + 'ErdhrfgSvavfu'.split(re70); + 'ErdhrfgSvavfu.NWNK.Cuk'.split(re70); + 'Ebhgr\x0a'.replace(re89, ''); + 'Ebhgr\x0a'.replace(re90, ''); + str78.split(re32); + str79.split(re32); + str80.split(re32); + str81.split(re32); + 'Fcbeg\x0a'.replace(re89, ''); + 'Fcbeg\x0a'.replace(re90, ''); + 'GI-Fcbg\x0a'.replace(re89, ''); + 'GI-Fcbg\x0a'.replace(re90, ''); + 'Gbhe\x0a'.replace(re89, ''); + 'Gbhe\x0a'.replace(re90, ''); + 'Hagreunyghat\x0a'.replace(re89, ''); + 'Hagreunyghat\x0a'.replace(re90, ''); + 'Ivqrb\x0a'.replace(re89, ''); + 'Ivqrb\x0a'.replace(re90, ''); + 'Jrggre\x0a'.replace(re89, ''); + 'Jrggre\x0a'.replace(re90, ''); + str82.replace(re68, ''); + str82.replace(re18, ''); + str83.replace(re68, ''); + str83.replace(re18, ''); + str84.replace(re68, ''); + str84.replace(re18, ''); + 'nqiFreivprObk'.replace(re30, ''); + 'nqiFubccvatObk'.replace(re30, ''); + 'nwnk'.replace(re39, ''); + 'nxghryy'.replace(re40, ''); + 'nxghryy'.replace(re41, ''); + 'nxghryy'.replace(re42, ''); + 'nxghryy'.replace(re43, ''); + 'nxghryy'.replace(re44, ''); + 'nxghryy'.replace(re45, ''); + 'nxghryy'.replace(re46, ''); + 'nxghryy'.replace(re47, ''); + 'nxghryy'.replace(re48, ''); + str85.replace(re40, ''); + str85.replace(re41, ''); + str85.replace(re42, ''); + str85.replace(re43, ''); + str85.replace(re44, ''); + str85.replace(re45, ''); + str85.replace(re46, ''); + str85.replace(re47, ''); + str85.replace(re48, ''); + 'pngrtbel'.replace(re29, ''); + 'pngrtbel'.replace(re30, ''); + 'pybfr'.replace(re39, ''); + 'qvi'.replace(re39, ''); + str86.replace(re68, ''); + str86.replace(re18, ''); + 'qg'.replace(re39, ''); + 'qg'.replace(re68, ''); + 'qg'.replace(re18, ''); + 'rzorq'.replace(re39, ''); + 'rzorq'.replace(re68, ''); + 'rzorq'.replace(re18, ''); + 'svryqOga'.replace(re39, ''); + 'svryqOgaPnapry'.replace(re39, ''); + 'svz_zlfcnpr_nccf-pnainf,svz_zlfcnpr_havgrq-fgngrf'.split(re20); + 'svanamra'.replace(re40, ''); + 'svanamra'.replace(re41, ''); + 'svanamra'.replace(re42, ''); + 'svanamra'.replace(re43, ''); + 'svanamra'.replace(re44, ''); + 'svanamra'.replace(re45, ''); + 'svanamra'.replace(re46, ''); + 'svanamra'.replace(re47, ''); + 'svanamra'.replace(re48, ''); + 'sbphf'.split(re70); + 'sbphf.gno sbphfva.gno'.split(re70); + 'sbphfva'.split(re70); + 'sbez'.replace(re39, ''); + 'sbez.nwnk'.replace(re68, ''); + 'sbez.nwnk'.replace(re18, ''); + 'tnzrf'.replace(re40, ''); + 'tnzrf'.replace(re41, ''); + 'tnzrf'.replace(re42, ''); + 'tnzrf'.replace(re43, ''); + 'tnzrf'.replace(re44, ''); + 'tnzrf'.replace(re45, ''); + 'tnzrf'.replace(re46, ''); + 'tnzrf'.replace(re47, ''); + 'tnzrf'.replace(re48, ''); + 'ubzrcntr'.replace(re30, ''); + 'ubebfxbc'.replace(re40, ''); + 'ubebfxbc'.replace(re41, ''); + 'ubebfxbc'.replace(re42, ''); + 'ubebfxbc'.replace(re43, ''); + 'ubebfxbc'.replace(re44, ''); + 'ubebfxbc'.replace(re45, ''); + 'ubebfxbc'.replace(re46, ''); + 'ubebfxbc'.replace(re47, ''); + 'ubebfxbc'.replace(re48, ''); + 'uc_cebzbobk_ugzy%2Puc_cebzbobk_vzt'.replace(re30, ''); + 'uc_erpgnatyr'.replace(re30, ''); + str87.replace(re33, ''); + str88.replace(re33, ''); + 'uggc://wf.hv-cbegny.qr/tzk/ubzr/wf/20080602/onfr.wf${4}${5}'.replace(re71, ''); + 'uggc://wf.hv-cbegny.qr/tzk/ubzr/wf/20080602/onfr.wf${5}'.replace(re72, ''); + 'uggc://wf.hv-cbegny.qr/tzk/ubzr/wf/20080602/qlaYvo.wf${4}${5}'.replace(re71, ''); + 'uggc://wf.hv-cbegny.qr/tzk/ubzr/wf/20080602/qlaYvo.wf${5}'.replace(re72, ''); + 'uggc://wf.hv-cbegny.qr/tzk/ubzr/wf/20080602/rssrpgYvo.wf${4}${5}'.replace(re71, ''); + 'uggc://wf.hv-cbegny.qr/tzk/ubzr/wf/20080602/rssrpgYvo.wf${5}'.replace(re72, ''); + str89.replace(re73, ''); + 'uggc://zfacbegny.112.2b7.arg/o/ff/zfacbegnyubzr/1/U.7-cqi-2/f55023338617756?[NDO]&{1}&{2}&[NDR]'.replace(re69, ''); + str6.replace(re23, ''); + 'xvab'.replace(re40, ''); + 'xvab'.replace(re41, ''); + 'xvab'.replace(re42, ''); + 'xvab'.replace(re43, ''); + 'xvab'.replace(re44, ''); + 'xvab'.replace(re45, ''); + 'xvab'.replace(re46, ''); + 'xvab'.replace(re47, ''); + 'xvab'.replace(re48, ''); + 'ybnq'.split(re70); + 'zrqvnzbqgno lhv-anifrg lhv-anifrg-gbc'.replace(re18, ''); + 'zrgn'.replace(re39, ''); + str90.replace(re68, ''); + str90.replace(re18, ''); + 'zbhfrzbir'.split(re70); + 'zbhfrzbir.gno'.split(re70); + str63.replace(/^.*jroxvg\/(\d+(\.\d+)?).*$/, ''); + 'zhfvx'.replace(re40, ''); + 'zhfvx'.replace(re41, ''); + 'zhfvx'.replace(re42, ''); + 'zhfvx'.replace(re43, ''); + 'zhfvx'.replace(re44, ''); + 'zhfvx'.replace(re45, ''); + 'zhfvx'.replace(re46, ''); + 'zhfvx'.replace(re47, ''); + 'zhfvx'.replace(re48, ''); + 'zlfcnpr_nccf_pnainf'.replace(re52, ''); + str91.replace(re40, ''); + str91.replace(re41, ''); + str91.replace(re42, ''); + str91.replace(re43, ''); + str91.replace(re44, ''); + str91.replace(re45, ''); + str91.replace(re46, ''); + str91.replace(re47, ''); + str91.replace(re48, ''); + 'anzr'.replace(re39, ''); + str92.replace(/\b\w+\b/g, ''); + 'bow-nppbeqvba'.replace(re39, ''); + 'bowrpg'.replace(re39, ''); + 'bowrpg'.replace(re68, ''); + 'bowrpg'.replace(re18, ''); + 'cnenzf%2Rfglyrf'.replace(re29, ''); + 'cnenzf%2Rfglyrf'.replace(re30, ''); + 'cbchc'.replace(re30, ''); + 'ebhgr'.replace(re40, ''); + 'ebhgr'.replace(re41, ''); + 'ebhgr'.replace(re42, ''); + 'ebhgr'.replace(re43, ''); + 'ebhgr'.replace(re44, ''); + 'ebhgr'.replace(re45, ''); + 'ebhgr'.replace(re46, ''); + 'ebhgr'.replace(re47, ''); + 'ebhgr'.replace(re48, ''); + 'freivprobk_uc'.replace(re30, ''); + 'fubccvatobk_uc'.replace(re30, ''); + 'fubhgobk'.replace(re39, ''); + 'fcbeg'.replace(re40, ''); + 'fcbeg'.replace(re41, ''); + 'fcbeg'.replace(re42, ''); + 'fcbeg'.replace(re43, ''); + 'fcbeg'.replace(re44, ''); + 'fcbeg'.replace(re45, ''); + 'fcbeg'.replace(re46, ''); + 'fcbeg'.replace(re47, ''); + 'fcbeg'.replace(re48, ''); + 'gbhe'.replace(re40, ''); + 'gbhe'.replace(re41, ''); + 'gbhe'.replace(re42, ''); + 'gbhe'.replace(re43, ''); + 'gbhe'.replace(re44, ''); + 'gbhe'.replace(re45, ''); + 'gbhe'.replace(re46, ''); + 'gbhe'.replace(re47, ''); + 'gbhe'.replace(re48, ''); + 'gi-fcbg'.replace(re40, ''); + 'gi-fcbg'.replace(re41, ''); + 'gi-fcbg'.replace(re42, ''); + 'gi-fcbg'.replace(re43, ''); + 'gi-fcbg'.replace(re44, ''); + 'gi-fcbg'.replace(re45, ''); + 'gi-fcbg'.replace(re46, ''); + 'gi-fcbg'.replace(re47, ''); + 'gi-fcbg'.replace(re48, ''); + 'glcr'.replace(re39, ''); + 'haqrsvarq'.replace(/\//g, ''); + str93.replace(re40, ''); + str93.replace(re41, ''); + str93.replace(re42, ''); + str93.replace(re43, ''); + str93.replace(re44, ''); + str93.replace(re45, ''); + str93.replace(re46, ''); + str93.replace(re47, ''); + str93.replace(re48, ''); + 'ivqrb'.replace(re40, ''); + 'ivqrb'.replace(re41, ''); + 'ivqrb'.replace(re42, ''); + 'ivqrb'.replace(re43, ''); + 'ivqrb'.replace(re44, ''); + 'ivqrb'.replace(re45, ''); + 'ivqrb'.replace(re46, ''); + 'ivqrb'.replace(re47, ''); + 'ivqrb'.replace(re48, ''); + 'ivfvgf=1'.split(re86); + 'jrggre'.replace(re40, ''); + 'jrggre'.replace(re41, ''); + 'jrggre'.replace(re42, ''); + 'jrggre'.replace(re43, ''); + 'jrggre'.replace(re44, ''); + 'jrggre'.replace(re45, ''); + 'jrggre'.replace(re46, ''); + 'jrggre'.replace(re47, ''); + 'jrggre'.replace(re48, ''); + /#[a-z0-9]+$/i.exec('uggc://jjj.fpuhryreim.arg/Qrsnhyg'); + re66.exec('fryrpgrq'); + /(?:^|\s+)lhv-ani(?:\s+|$)/.exec('sff lhv-ani'); + /(?:^|\s+)lhv-anifrg(?:\s+|$)/.exec('zrqvnzbqgno lhv-anifrg'); + /(?:^|\s+)lhv-anifrg-gbc(?:\s+|$)/.exec('zrqvnzbqgno lhv-anifrg'); + re91.exec('GnoThvq'); + re91.exec('thvq'); + /(pbzcngvoyr|jroxvg)/.exec(str63); + /.+(?:ei|vg|en|vr)[\/: ]([\d.]+)/.exec(str63); + re8.exec('144631658.0.10.1231365869'); + re8.exec('144631658.0.10.1231367054'); + re8.exec('144631658.1231365869.1.1.hgzpfe=(qverpg)|hgzppa=(qverpg)|hgzpzq=(abar)'); + re8.exec('144631658.1231367054.1.1.hgzpfe=(qverpg)|hgzppa=(qverpg)|hgzpzq=(abar)'); + re8.exec('144631658.1670816052019209000.1231365869.1231365869.1231365869.1'); + re8.exec('144631658.1796080716621419500.1231367054.1231367054.1231367054.1'); + re8.exec(str94); + re8.exec(str95); + re8.exec(str96); + re8.exec(str97); + re8.exec('__hgzn=144631658.1670816052019209000.1231365869.1231365869.1231365869.1'); + re8.exec('__hgzn=144631658.1796080716621419500.1231367054.1231367054.1231367054.1'); + re8.exec('__hgzo=144631658.0.10.1231365869'); + re8.exec('__hgzo=144631658.0.10.1231367054'); + re8.exec('__hgzm=144631658.1231365869.1.1.hgzpfe=(qverpg)|hgzppa=(qverpg)|hgzpzq=(abar)'); + re8.exec('__hgzm=144631658.1231367054.1.1.hgzpfe=(qverpg)|hgzppa=(qverpg)|hgzpzq=(abar)'); + re34.exec(str78); + re34.exec(str79); + re34.exec(str81); + re74.exec(str77); + re74.exec('*'); + re74.exec(str82); + re74.exec(str83); + re74.exec(str86); + re74.exec('rzorq'); + re74.exec('sbez.nwnk'); + re74.exec(str90); + re74.exec('bowrpg'); + /\/onfr.wf(\?.+)?$/.exec('/uggc://wf.hv-cbegny.qr/tzk/ubzr/wf/20080602/onfr.wf'); + re28.exec('uvag ynfgUvag ynfg'); + re75.exec(''); + re76.exec(''); + re77.exec(''); + re78.exec(''); + re80.exec(str77); + re80.exec('*'); + re80.exec('.pybfr'); + re80.exec(str82); + re80.exec(str83); + re80.exec(str84); + re80.exec(str86); + re80.exec('qg'); + re80.exec('rzorq'); + re80.exec('sbez.nwnk'); + re80.exec(str90); + re80.exec('bowrpg'); + re61.exec('qlaYvo.wf'); + re61.exec('rssrpgYvo.wf'); + re61.exec('uggc://jjj.tzk.arg/qr/?fgnghf=uvajrvf'); + re92.exec(' .pybfr'); + re92.exec(' n.svryqOgaPnapry'); + re92.exec(' qg'); + re92.exec(str48); + re92.exec('.nwnk'); + re92.exec('.svryqOga,n.svryqOgaPnapry'); + re92.exec('.svryqOgaPnapry'); + re92.exec('.bow-nppbeqvba qg'); + re68.exec(str77); + re68.exec('*'); + re68.exec('.pybfr'); + re68.exec(str82); + re68.exec(str83); + re68.exec(str84); + re68.exec(str86); + re68.exec('qg'); + re68.exec('rzorq'); + re68.exec('sbez.nwnk'); + re68.exec(str90); + re68.exec('bowrpg'); + re93.exec(' .pybfr'); + re93.exec(' n.svryqOgaPnapry'); + re93.exec(' qg'); + re93.exec(str48); + re93.exec('.nwnk'); + re93.exec('.svryqOga,n.svryqOgaPnapry'); + re93.exec('.svryqOgaPnapry'); + re93.exec('.bow-nppbeqvba qg'); + re81.exec(str77); + re81.exec('*'); + re81.exec(str48); + re81.exec('.pybfr'); + re81.exec(str82); + re81.exec(str83); + re81.exec(str84); + re81.exec(str86); + re81.exec('qg'); + re81.exec('rzorq'); + re81.exec('sbez.nwnk'); + re81.exec(str90); + re81.exec('bowrpg'); + re94.exec(' .pybfr'); + re94.exec(' n.svryqOgaPnapry'); + re94.exec(' qg'); + re94.exec(str48); + re94.exec('.nwnk'); + re94.exec('.svryqOga,n.svryqOgaPnapry'); + re94.exec('.svryqOgaPnapry'); + re94.exec('.bow-nppbeqvba qg'); + re94.exec('[anzr=nwnkHey]'); + re94.exec(str82); + re31.exec('rf'); + re31.exec('wn'); + re82.exec(str77); + re82.exec('*'); + re82.exec(str48); + re82.exec('.pybfr'); + re82.exec(str82); + re82.exec(str83); + re82.exec(str84); + re82.exec(str86); + re82.exec('qg'); + re82.exec('rzorq'); + re82.exec('sbez.nwnk'); + re82.exec(str90); + re82.exec('bowrpg'); + re83.exec(str98); + re83.exec('shapgvba sbphf() { [angvir pbqr] }'); + re62.exec('#Ybtva'); + re62.exec('#Ybtva_cnffjbeq'); + re62.exec(str77); + re62.exec('#fubhgobkWf'); + re62.exec('#fubhgobkWfReebe'); + re62.exec('#fubhgobkWfFhpprff'); + re62.exec('*'); + re62.exec(str82); + re62.exec(str83); + re62.exec(str86); + re62.exec('rzorq'); + re62.exec('sbez.nwnk'); + re62.exec(str90); + re62.exec('bowrpg'); + re49.exec('pbagrag'); + re24.exec(str6); + /xbadhrebe/.exec(str63); + /znp/.exec('jva32'); + /zbmvyyn/.exec(str63); + /zfvr/.exec(str63); + /ag\s5\.1/.exec(str63); + /bcren/.exec(str63); + /fnsnev/.exec(str63); + /jva/.exec('jva32'); + /jvaqbjf/.exec(str63); + } + } + + function run() { + for (var i = 0; i < 5; i++) { + runBlock0(); + runBlock1(); + runBlock2(); + runBlock3(); + runBlock4(); + runBlock5(); + runBlock6(); + runBlock7(); + runBlock8(); + runBlock9(); + runBlock10(); + runBlock11(); + } + } + + this.run = run; +} diff --git a/node-v0.8.14/deps/v8/benchmarks/revisions.html b/node-v0.8.14/deps/v8/benchmarks/revisions.html new file mode 100644 index 0000000..3ce9889 --- /dev/null +++ b/node-v0.8.14/deps/v8/benchmarks/revisions.html @@ -0,0 +1,104 @@ + + +V8 Benchmark Suite Revisions + + + +
+

V8 Benchmark Suite Revisions

+ + +
+ +

+ +The V8 benchmark suite is changed from time to time as we fix bugs or +expand the scope of the benchmarks. Here is a list of revisions, with +a description of the changes made. Note that benchmark results are +not comparable unless both results are run with the same revision of +the benchmark suite. + +

+

Version 7 (link)

+ +

This version includes the new Navier-Stokes benchmark, a 2D differential + equation solver that stresses arithmetic computations on double arrays.

+ +

Version 6 (link)

+ +

Removed dead code from the RayTrace benchmark and fixed a couple of +typos in the DeltaBlue implementation. Changed the Splay benchmark to +avoid converting the same numeric key to a string over and over again +and to avoid inserting and removing the same element repeatedly thus +increasing pressure on the memory subsystem. Changed the RegExp +benchmark to exercise the regular expression engine on different input +strings.

+ +

Furthermore, the benchmark runner was changed to run the benchmarks +for at least a few times to stabilize the reported numbers on slower +machines.

+ +

Version 5 (link)

+ +

Removed duplicate line in random seed code, and changed the name of +the Object.prototype.inherits function in the DeltaBlue benchmark to +inheritsFrom to avoid name clashes when running in Chromium with +extensions enabled. +

+ +

Version 4 (link)

+ +

The Splay benchmark is a newcomer in version 4. It +manipulates a splay tree by adding and removing data nodes, thus +exercising the memory management subsystem of the JavaScript engine. +

+ +

+Furthermore, all the unused parts of the Prototype library were +removed from the RayTrace benchmark. This does not affect the running +of the benchmark. +

+ + +

Version 3 (link)

+ +

Version 3 adds a new benchmark, RegExp. The RegExp +benchmark is generated by loading 50 of the most popular pages on the +web and logging all regexp operations performed. Each operation is +given a weight that is calculated from an estimate of the popularity +of the pages where it occurs and the number of times it is executed +while loading each page. Finally the literal letters in the data are +encoded using ROT13 in a way that does not affect how the regexps +match their input. +

+ + +

Version 2 (link)

+ +

For version 2 the Crypto benchmark was fixed. Previously, the +decryption stage was given plaintext as input, which resulted in an +error. Now, the decryption stage is given the output of the +encryption stage as input. The result is checked against the original +plaintext. For this to give the correct results the crypto objects +are reset for each iteration of the benchmark. In addition, the size +of the plain text has been increased a little and the use of +Math.random() and new Date() to build an RNG pool has been +removed.

+ +

Other benchmarks were fixed to do elementary verification of the +results of their calculations. This is to avoid accidentally +obtaining scores that are the result of an incorrect JavaScript engine +optimization.

+ + +

Version 1 (link)

+ +

Initial release.

+ +
+
+ +
+ + + diff --git a/node-v0.8.14/deps/v8/benchmarks/richards.js b/node-v0.8.14/deps/v8/benchmarks/richards.js new file mode 100644 index 0000000..054928d --- /dev/null +++ b/node-v0.8.14/deps/v8/benchmarks/richards.js @@ -0,0 +1,539 @@ +// Copyright 2006-2008 the V8 project authors. All rights reserved. +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following +// disclaimer in the documentation and/or other materials provided +// with the distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + +// This is a JavaScript implementation of the Richards +// benchmark from: +// +// http://www.cl.cam.ac.uk/~mr10/Bench.html +// +// The benchmark was originally implemented in BCPL by +// Martin Richards. + + +var Richards = new BenchmarkSuite('Richards', 35302, [ + new Benchmark("Richards", runRichards) +]); + + +/** + * The Richards benchmark simulates the task dispatcher of an + * operating system. + **/ +function runRichards() { + var scheduler = new Scheduler(); + scheduler.addIdleTask(ID_IDLE, 0, null, COUNT); + + var queue = new Packet(null, ID_WORKER, KIND_WORK); + queue = new Packet(queue, ID_WORKER, KIND_WORK); + scheduler.addWorkerTask(ID_WORKER, 1000, queue); + + queue = new Packet(null, ID_DEVICE_A, KIND_DEVICE); + queue = new Packet(queue, ID_DEVICE_A, KIND_DEVICE); + queue = new Packet(queue, ID_DEVICE_A, KIND_DEVICE); + scheduler.addHandlerTask(ID_HANDLER_A, 2000, queue); + + queue = new Packet(null, ID_DEVICE_B, KIND_DEVICE); + queue = new Packet(queue, ID_DEVICE_B, KIND_DEVICE); + queue = new Packet(queue, ID_DEVICE_B, KIND_DEVICE); + scheduler.addHandlerTask(ID_HANDLER_B, 3000, queue); + + scheduler.addDeviceTask(ID_DEVICE_A, 4000, null); + + scheduler.addDeviceTask(ID_DEVICE_B, 5000, null); + + scheduler.schedule(); + + if (scheduler.queueCount != EXPECTED_QUEUE_COUNT || + scheduler.holdCount != EXPECTED_HOLD_COUNT) { + var msg = + "Error during execution: queueCount = " + scheduler.queueCount + + ", holdCount = " + scheduler.holdCount + "."; + throw new Error(msg); + } +} + +var COUNT = 1000; + +/** + * These two constants specify how many times a packet is queued and + * how many times a task is put on hold in a correct run of richards. + * They don't have any meaning a such but are characteristic of a + * correct run so if the actual queue or hold count is different from + * the expected there must be a bug in the implementation. + **/ +var EXPECTED_QUEUE_COUNT = 2322; +var EXPECTED_HOLD_COUNT = 928; + + +/** + * A scheduler can be used to schedule a set of tasks based on their relative + * priorities. Scheduling is done by maintaining a list of task control blocks + * which holds tasks and the data queue they are processing. + * @constructor + */ +function Scheduler() { + this.queueCount = 0; + this.holdCount = 0; + this.blocks = new Array(NUMBER_OF_IDS); + this.list = null; + this.currentTcb = null; + this.currentId = null; +} + +var ID_IDLE = 0; +var ID_WORKER = 1; +var ID_HANDLER_A = 2; +var ID_HANDLER_B = 3; +var ID_DEVICE_A = 4; +var ID_DEVICE_B = 5; +var NUMBER_OF_IDS = 6; + +var KIND_DEVICE = 0; +var KIND_WORK = 1; + +/** + * Add an idle task to this scheduler. + * @param {int} id the identity of the task + * @param {int} priority the task's priority + * @param {Packet} queue the queue of work to be processed by the task + * @param {int} count the number of times to schedule the task + */ +Scheduler.prototype.addIdleTask = function (id, priority, queue, count) { + this.addRunningTask(id, priority, queue, new IdleTask(this, 1, count)); +}; + +/** + * Add a work task to this scheduler. + * @param {int} id the identity of the task + * @param {int} priority the task's priority + * @param {Packet} queue the queue of work to be processed by the task + */ +Scheduler.prototype.addWorkerTask = function (id, priority, queue) { + this.addTask(id, priority, queue, new WorkerTask(this, ID_HANDLER_A, 0)); +}; + +/** + * Add a handler task to this scheduler. + * @param {int} id the identity of the task + * @param {int} priority the task's priority + * @param {Packet} queue the queue of work to be processed by the task + */ +Scheduler.prototype.addHandlerTask = function (id, priority, queue) { + this.addTask(id, priority, queue, new HandlerTask(this)); +}; + +/** + * Add a handler task to this scheduler. + * @param {int} id the identity of the task + * @param {int} priority the task's priority + * @param {Packet} queue the queue of work to be processed by the task + */ +Scheduler.prototype.addDeviceTask = function (id, priority, queue) { + this.addTask(id, priority, queue, new DeviceTask(this)) +}; + +/** + * Add the specified task and mark it as running. + * @param {int} id the identity of the task + * @param {int} priority the task's priority + * @param {Packet} queue the queue of work to be processed by the task + * @param {Task} task the task to add + */ +Scheduler.prototype.addRunningTask = function (id, priority, queue, task) { + this.addTask(id, priority, queue, task); + this.currentTcb.setRunning(); +}; + +/** + * Add the specified task to this scheduler. + * @param {int} id the identity of the task + * @param {int} priority the task's priority + * @param {Packet} queue the queue of work to be processed by the task + * @param {Task} task the task to add + */ +Scheduler.prototype.addTask = function (id, priority, queue, task) { + this.currentTcb = new TaskControlBlock(this.list, id, priority, queue, task); + this.list = this.currentTcb; + this.blocks[id] = this.currentTcb; +}; + +/** + * Execute the tasks managed by this scheduler. + */ +Scheduler.prototype.schedule = function () { + this.currentTcb = this.list; + while (this.currentTcb != null) { + if (this.currentTcb.isHeldOrSuspended()) { + this.currentTcb = this.currentTcb.link; + } else { + this.currentId = this.currentTcb.id; + this.currentTcb = this.currentTcb.run(); + } + } +}; + +/** + * Release a task that is currently blocked and return the next block to run. + * @param {int} id the id of the task to suspend + */ +Scheduler.prototype.release = function (id) { + var tcb = this.blocks[id]; + if (tcb == null) return tcb; + tcb.markAsNotHeld(); + if (tcb.priority > this.currentTcb.priority) { + return tcb; + } else { + return this.currentTcb; + } +}; + +/** + * Block the currently executing task and return the next task control block + * to run. The blocked task will not be made runnable until it is explicitly + * released, even if new work is added to it. + */ +Scheduler.prototype.holdCurrent = function () { + this.holdCount++; + this.currentTcb.markAsHeld(); + return this.currentTcb.link; +}; + +/** + * Suspend the currently executing task and return the next task control block + * to run. If new work is added to the suspended task it will be made runnable. + */ +Scheduler.prototype.suspendCurrent = function () { + this.currentTcb.markAsSuspended(); + return this.currentTcb; +}; + +/** + * Add the specified packet to the end of the worklist used by the task + * associated with the packet and make the task runnable if it is currently + * suspended. + * @param {Packet} packet the packet to add + */ +Scheduler.prototype.queue = function (packet) { + var t = this.blocks[packet.id]; + if (t == null) return t; + this.queueCount++; + packet.link = null; + packet.id = this.currentId; + return t.checkPriorityAdd(this.currentTcb, packet); +}; + +/** + * A task control block manages a task and the queue of work packages associated + * with it. + * @param {TaskControlBlock} link the preceding block in the linked block list + * @param {int} id the id of this block + * @param {int} priority the priority of this block + * @param {Packet} queue the queue of packages to be processed by the task + * @param {Task} task the task + * @constructor + */ +function TaskControlBlock(link, id, priority, queue, task) { + this.link = link; + this.id = id; + this.priority = priority; + this.queue = queue; + this.task = task; + if (queue == null) { + this.state = STATE_SUSPENDED; + } else { + this.state = STATE_SUSPENDED_RUNNABLE; + } +} + +/** + * The task is running and is currently scheduled. + */ +var STATE_RUNNING = 0; + +/** + * The task has packets left to process. + */ +var STATE_RUNNABLE = 1; + +/** + * The task is not currently running. The task is not blocked as such and may +* be started by the scheduler. + */ +var STATE_SUSPENDED = 2; + +/** + * The task is blocked and cannot be run until it is explicitly released. + */ +var STATE_HELD = 4; + +var STATE_SUSPENDED_RUNNABLE = STATE_SUSPENDED | STATE_RUNNABLE; +var STATE_NOT_HELD = ~STATE_HELD; + +TaskControlBlock.prototype.setRunning = function () { + this.state = STATE_RUNNING; +}; + +TaskControlBlock.prototype.markAsNotHeld = function () { + this.state = this.state & STATE_NOT_HELD; +}; + +TaskControlBlock.prototype.markAsHeld = function () { + this.state = this.state | STATE_HELD; +}; + +TaskControlBlock.prototype.isHeldOrSuspended = function () { + return (this.state & STATE_HELD) != 0 || (this.state == STATE_SUSPENDED); +}; + +TaskControlBlock.prototype.markAsSuspended = function () { + this.state = this.state | STATE_SUSPENDED; +}; + +TaskControlBlock.prototype.markAsRunnable = function () { + this.state = this.state | STATE_RUNNABLE; +}; + +/** + * Runs this task, if it is ready to be run, and returns the next task to run. + */ +TaskControlBlock.prototype.run = function () { + var packet; + if (this.state == STATE_SUSPENDED_RUNNABLE) { + packet = this.queue; + this.queue = packet.link; + if (this.queue == null) { + this.state = STATE_RUNNING; + } else { + this.state = STATE_RUNNABLE; + } + } else { + packet = null; + } + return this.task.run(packet); +}; + +/** + * Adds a packet to the worklist of this block's task, marks this as runnable if + * necessary, and returns the next runnable object to run (the one + * with the highest priority). + */ +TaskControlBlock.prototype.checkPriorityAdd = function (task, packet) { + if (this.queue == null) { + this.queue = packet; + this.markAsRunnable(); + if (this.priority > task.priority) return this; + } else { + this.queue = packet.addTo(this.queue); + } + return task; +}; + +TaskControlBlock.prototype.toString = function () { + return "tcb { " + this.task + "@" + this.state + " }"; +}; + +/** + * An idle task doesn't do any work itself but cycles control between the two + * device tasks. + * @param {Scheduler} scheduler the scheduler that manages this task + * @param {int} v1 a seed value that controls how the device tasks are scheduled + * @param {int} count the number of times this task should be scheduled + * @constructor + */ +function IdleTask(scheduler, v1, count) { + this.scheduler = scheduler; + this.v1 = v1; + this.count = count; +} + +IdleTask.prototype.run = function (packet) { + this.count--; + if (this.count == 0) return this.scheduler.holdCurrent(); + if ((this.v1 & 1) == 0) { + this.v1 = this.v1 >> 1; + return this.scheduler.release(ID_DEVICE_A); + } else { + this.v1 = (this.v1 >> 1) ^ 0xD008; + return this.scheduler.release(ID_DEVICE_B); + } +}; + +IdleTask.prototype.toString = function () { + return "IdleTask" +}; + +/** + * A task that suspends itself after each time it has been run to simulate + * waiting for data from an external device. + * @param {Scheduler} scheduler the scheduler that manages this task + * @constructor + */ +function DeviceTask(scheduler) { + this.scheduler = scheduler; + this.v1 = null; +} + +DeviceTask.prototype.run = function (packet) { + if (packet == null) { + if (this.v1 == null) return this.scheduler.suspendCurrent(); + var v = this.v1; + this.v1 = null; + return this.scheduler.queue(v); + } else { + this.v1 = packet; + return this.scheduler.holdCurrent(); + } +}; + +DeviceTask.prototype.toString = function () { + return "DeviceTask"; +}; + +/** + * A task that manipulates work packets. + * @param {Scheduler} scheduler the scheduler that manages this task + * @param {int} v1 a seed used to specify how work packets are manipulated + * @param {int} v2 another seed used to specify how work packets are manipulated + * @constructor + */ +function WorkerTask(scheduler, v1, v2) { + this.scheduler = scheduler; + this.v1 = v1; + this.v2 = v2; +} + +WorkerTask.prototype.run = function (packet) { + if (packet == null) { + return this.scheduler.suspendCurrent(); + } else { + if (this.v1 == ID_HANDLER_A) { + this.v1 = ID_HANDLER_B; + } else { + this.v1 = ID_HANDLER_A; + } + packet.id = this.v1; + packet.a1 = 0; + for (var i = 0; i < DATA_SIZE; i++) { + this.v2++; + if (this.v2 > 26) this.v2 = 1; + packet.a2[i] = this.v2; + } + return this.scheduler.queue(packet); + } +}; + +WorkerTask.prototype.toString = function () { + return "WorkerTask"; +}; + +/** + * A task that manipulates work packets and then suspends itself. + * @param {Scheduler} scheduler the scheduler that manages this task + * @constructor + */ +function HandlerTask(scheduler) { + this.scheduler = scheduler; + this.v1 = null; + this.v2 = null; +} + +HandlerTask.prototype.run = function (packet) { + if (packet != null) { + if (packet.kind == KIND_WORK) { + this.v1 = packet.addTo(this.v1); + } else { + this.v2 = packet.addTo(this.v2); + } + } + if (this.v1 != null) { + var count = this.v1.a1; + var v; + if (count < DATA_SIZE) { + if (this.v2 != null) { + v = this.v2; + this.v2 = this.v2.link; + v.a1 = this.v1.a2[count]; + this.v1.a1 = count + 1; + return this.scheduler.queue(v); + } + } else { + v = this.v1; + this.v1 = this.v1.link; + return this.scheduler.queue(v); + } + } + return this.scheduler.suspendCurrent(); +}; + +HandlerTask.prototype.toString = function () { + return "HandlerTask"; +}; + +/* --- * + * P a c k e t + * --- */ + +var DATA_SIZE = 4; + +/** + * A simple package of data that is manipulated by the tasks. The exact layout + * of the payload data carried by a packet is not importaint, and neither is the + * nature of the work performed on packets by the tasks. + * + * Besides carrying data, packets form linked lists and are hence used both as + * data and worklists. + * @param {Packet} link the tail of the linked list of packets + * @param {int} id an ID for this packet + * @param {int} kind the type of this packet + * @constructor + */ +function Packet(link, id, kind) { + this.link = link; + this.id = id; + this.kind = kind; + this.a1 = 0; + this.a2 = new Array(DATA_SIZE); +} + +/** + * Add this packet to the end of a worklist, and return the worklist. + * @param {Packet} queue the worklist to add this packet to + */ +Packet.prototype.addTo = function (queue) { + this.link = null; + if (queue == null) return this; + var peek, next = queue; + while ((peek = next.link) != null) + next = peek; + next.link = this; + return queue; +}; + +Packet.prototype.toString = function () { + return "Packet"; +}; diff --git a/node-v0.8.14/deps/v8/benchmarks/run.html b/node-v0.8.14/deps/v8/benchmarks/run.html new file mode 100644 index 0000000..f1d14c1 --- /dev/null +++ b/node-v0.8.14/deps/v8/benchmarks/run.html @@ -0,0 +1,143 @@ + + + + + + +V8 Benchmark Suite + + + + + + + + + + + + + +
+

V8 Benchmark Suite - version ?

+
+Warning! This is not the latest version of the V8 benchmark +suite. Consider running the + +latest version. +
+ + +
+This page contains a suite of pure JavaScript benchmarks that we have +used to tune V8. The final score is computed as the geometric mean of +the individual results to make it independent of the running times of +the individual benchmarks and of a reference system (score +100). Scores are not comparable across benchmark suite versions and +higher scores means better performance: Bigger is better! + +
    +
  • Richards
    OS kernel simulation benchmark, originally written in BCPL by Martin Richards (539 lines).
  • +
  • DeltaBlue
    One-way constraint solver, originally written in Smalltalk by John Maloney and Mario Wolczko (880 lines).
  • +
  • Crypto
    Encryption and decryption benchmark based on code by Tom Wu (1698 lines).
  • +
  • RayTrace
    Ray tracer benchmark based on code by Adam Burmister (904 lines).
  • +
  • EarleyBoyer
    Classic Scheme benchmarks, translated to JavaScript by Florian Loitsch's Scheme2Js compiler (4684 lines).
  • +
  • RegExp
    Regular expression benchmark generated by extracting regular expression operations from 50 of the most popular web pages +(1761 lines). +
  • +
  • Splay
    Data manipulation benchmark that deals with splay trees and exercises the automatic memory management subsystem (394 lines).
  • +
  • NavierStokes
    Solves NavierStokes equations in 2D, heavily manipulating double precision arrays. Based on Oliver Hunt's code (387 lines).
  • +
+ +

+Note that benchmark results are not comparable unless both results are +run with the same revision of the benchmark suite. We will be making +revisions from time to time in order to fix bugs or expand the scope +of the benchmark suite. For previous revisions and the change log see +the revisions page. +

+ +
+
+
Starting...
+
+
+
+
+ +
+ + + diff --git a/node-v0.8.14/deps/v8/benchmarks/run.js b/node-v0.8.14/deps/v8/benchmarks/run.js new file mode 100644 index 0000000..58f6265 --- /dev/null +++ b/node-v0.8.14/deps/v8/benchmarks/run.js @@ -0,0 +1,62 @@ +// Copyright 2008 the V8 project authors. All rights reserved. +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following +// disclaimer in the documentation and/or other materials provided +// with the distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + +load('base.js'); +load('richards.js'); +load('deltablue.js'); +load('crypto.js'); +load('raytrace.js'); +load('earley-boyer.js'); +load('regexp.js'); +load('splay.js'); +load('navier-stokes.js'); + +var success = true; + +function PrintResult(name, result) { + print(name + ': ' + result); +} + + +function PrintError(name, error) { + PrintResult(name, error); + success = false; +} + + +function PrintScore(score) { + if (success) { + print('----'); + print('Score (version ' + BenchmarkSuite.version + '): ' + score); + } +} + + +BenchmarkSuite.RunSuites({ NotifyResult: PrintResult, + NotifyError: PrintError, + NotifyScore: PrintScore }); diff --git a/node-v0.8.14/deps/v8/benchmarks/spinning-balls/index.html b/node-v0.8.14/deps/v8/benchmarks/spinning-balls/index.html new file mode 100644 index 0000000..d01f31f --- /dev/null +++ b/node-v0.8.14/deps/v8/benchmarks/spinning-balls/index.html @@ -0,0 +1,11 @@ + + + + + + + + + diff --git a/node-v0.8.14/deps/v8/benchmarks/spinning-balls/splay-tree.js b/node-v0.8.14/deps/v8/benchmarks/spinning-balls/splay-tree.js new file mode 100644 index 0000000..a88e4cb --- /dev/null +++ b/node-v0.8.14/deps/v8/benchmarks/spinning-balls/splay-tree.js @@ -0,0 +1,326 @@ +// Copyright 2011 the V8 project authors. All rights reserved. +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following +// disclaimer in the documentation and/or other materials provided +// with the distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +/** + * Constructs a Splay tree. A splay tree is a self-balancing binary + * search tree with the additional property that recently accessed + * elements are quick to access again. It performs basic operations + * such as insertion, look-up and removal in O(log(n)) amortized time. + * + * @constructor + */ +function SplayTree() { +}; + + +/** + * Pointer to the root node of the tree. + * + * @type {SplayTree.Node} + * @private + */ +SplayTree.prototype.root_ = null; + + +/** + * @return {boolean} Whether the tree is empty. + */ +SplayTree.prototype.isEmpty = function() { + return !this.root_; +}; + + +/** + * Inserts a node into the tree with the specified key and value if + * the tree does not already contain a node with the specified key. If + * the value is inserted, it becomes the root of the tree. + * + * @param {number} key Key to insert into the tree. + * @param {*} value Value to insert into the tree. + */ +SplayTree.prototype.insert = function(key, value) { + if (this.isEmpty()) { + this.root_ = new SplayTree.Node(key, value); + return; + } + // Splay on the key to move the last node on the search path for + // the key to the root of the tree. + this.splay_(key); + if (this.root_.key == key) { + return; + } + var node = new SplayTree.Node(key, value); + if (key > this.root_.key) { + node.left = this.root_; + node.right = this.root_.right; + this.root_.right = null; + } else { + node.right = this.root_; + node.left = this.root_.left; + this.root_.left = null; + } + this.root_ = node; +}; + + +/** + * Removes a node with the specified key from the tree if the tree + * contains a node with this key. The removed node is returned. If the + * key is not found, an exception is thrown. + * + * @param {number} key Key to find and remove from the tree. + * @return {SplayTree.Node} The removed node. + */ +SplayTree.prototype.remove = function(key) { + if (this.isEmpty()) { + throw Error('Key not found: ' + key); + } + this.splay_(key); + if (this.root_.key != key) { + throw Error('Key not found: ' + key); + } + var removed = this.root_; + if (!this.root_.left) { + this.root_ = this.root_.right; + } else { + var right = this.root_.right; + this.root_ = this.root_.left; + // Splay to make sure that the new root has an empty right child. + this.splay_(key); + // Insert the original right child as the right child of the new + // root. + this.root_.right = right; + } + return removed; +}; + + +/** + * Returns the node having the specified key or null if the tree doesn't contain + * a node with the specified key. + * + * @param {number} key Key to find in the tree. + * @return {SplayTree.Node} Node having the specified key. + */ +SplayTree.prototype.find = function(key) { + if (this.isEmpty()) { + return null; + } + this.splay_(key); + return this.root_.key == key ? this.root_ : null; +}; + + +/** + * @return {SplayTree.Node} Node having the maximum key value. + */ +SplayTree.prototype.findMax = function(opt_startNode) { + if (this.isEmpty()) { + return null; + } + var current = opt_startNode || this.root_; + while (current.right) { + current = current.right; + } + return current; +}; + + +/** + * @return {SplayTree.Node} Node having the maximum key value that + * is less than the specified key value. + */ +SplayTree.prototype.findGreatestLessThan = function(key) { + if (this.isEmpty()) { + return null; + } + // Splay on the key to move the node with the given key or the last + // node on the search path to the top of the tree. + this.splay_(key); + // Now the result is either the root node or the greatest node in + // the left subtree. + if (this.root_.key < key) { + return this.root_; + } else if (this.root_.left) { + return this.findMax(this.root_.left); + } else { + return null; + } +}; + + +/** + * @return {Array<*>} An array containing all the keys of tree's nodes. + */ +SplayTree.prototype.exportKeys = function() { + var result = []; + if (!this.isEmpty()) { + this.root_.traverse_(function(node) { result.push(node.key); }); + } + return result; +}; + + +/** + * Perform the splay operation for the given key. Moves the node with + * the given key to the top of the tree. If no node has the given + * key, the last node on the search path is moved to the top of the + * tree. This is the simplified top-down splaying algorithm from: + * "Self-adjusting Binary Search Trees" by Sleator and Tarjan + * + * @param {number} key Key to splay the tree on. + * @private + */ +SplayTree.prototype.splay_ = function(key) { + if (this.isEmpty()) { + return; + } + // Create a dummy node. The use of the dummy node is a bit + // counter-intuitive: The right child of the dummy node will hold + // the L tree of the algorithm. The left child of the dummy node + // will hold the R tree of the algorithm. Using a dummy node, left + // and right will always be nodes and we avoid special cases. + var dummy, left, right; + dummy = left = right = new SplayTree.Node(null, null); + var current = this.root_; + while (true) { + if (key < current.key) { + if (!current.left) { + break; + } + if (key < current.left.key) { + // Rotate right. + var tmp = current.left; + current.left = tmp.right; + tmp.right = current; + current = tmp; + if (!current.left) { + break; + } + } + // Link right. + right.left = current; + right = current; + current = current.left; + } else if (key > current.key) { + if (!current.right) { + break; + } + if (key > current.right.key) { + // Rotate left. + var tmp = current.right; + current.right = tmp.left; + tmp.left = current; + current = tmp; + if (!current.right) { + break; + } + } + // Link left. + left.right = current; + left = current; + current = current.right; + } else { + break; + } + } + // Assemble. + left.right = current.left; + right.left = current.right; + current.left = dummy.right; + current.right = dummy.left; + this.root_ = current; +}; + + +/** + * Constructs a Splay tree node. + * + * @param {number} key Key. + * @param {*} value Value. + */ +SplayTree.Node = function(key, value) { + this.key = key; + this.value = value; +}; + + +/** + * @type {SplayTree.Node} + */ +SplayTree.Node.prototype.left = null; + + +/** + * @type {SplayTree.Node} + */ +SplayTree.Node.prototype.right = null; + + +/** + * Performs an ordered traversal of the subtree starting at + * this SplayTree.Node. + * + * @param {function(SplayTree.Node)} f Visitor function. + * @private + */ +SplayTree.Node.prototype.traverse_ = function(f) { + var current = this; + while (current) { + var left = current.left; + if (left) left.traverse_(f); + f(current); + current = current.right; + } +}; + +SplayTree.prototype.traverseBreadthFirst = function (f) { + if (f(this.root_.value)) return; + + var stack = [this.root_]; + var length = 1; + + while (length > 0) { + var new_stack = new Array(stack.length * 2); + var new_length = 0; + for (var i = 0; i < length; i++) { + var n = stack[i]; + var l = n.left; + var r = n.right; + if (l) { + if (f(l.value)) return; + new_stack[new_length++] = l; + } + if (r) { + if (f(r.value)) return; + new_stack[new_length++] = r; + } + } + stack = new_stack; + length = new_length; + } +}; diff --git a/node-v0.8.14/deps/v8/benchmarks/spinning-balls/v.js b/node-v0.8.14/deps/v8/benchmarks/spinning-balls/v.js new file mode 100644 index 0000000..5ae1194 --- /dev/null +++ b/node-v0.8.14/deps/v8/benchmarks/spinning-balls/v.js @@ -0,0 +1,498 @@ +// Copyright 2011 the V8 project authors. All rights reserved. +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following +// disclaimer in the documentation and/or other materials provided +// with the distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + +/** + * This function provides requestAnimationFrame in a cross browser way. + * http://paulirish.com/2011/requestanimationframe-for-smart-animating/ + */ +if ( !window.requestAnimationFrame ) { + window.requestAnimationFrame = ( function() { + return window.webkitRequestAnimationFrame || + window.mozRequestAnimationFrame || + window.oRequestAnimationFrame || + window.msRequestAnimationFrame || + function(callback, element) { + window.setTimeout( callback, 1000 / 60 ); + }; + } )(); +} + +var kNPoints = 8000; +var kNModifications = 20; +var kNVisiblePoints = 200; +var kDecaySpeed = 20; + +var kPointRadius = 4; +var kInitialLifeForce = 100; + +var livePoints = void 0; +var dyingPoints = void 0; +var scene = void 0; +var renderingStartTime = void 0; +var scene = void 0; +var pausePlot = void 0; +var splayTree = void 0; +var numberOfFrames = 0; +var sumOfSquaredPauses = 0; +var benchmarkStartTime = void 0; +var benchmarkTimeLimit = void 0; +var autoScale = void 0; +var pauseDistribution = []; + + +function Point(x, y, z, payload) { + this.x = x; + this.y = y; + this.z = z; + + this.next = null; + this.prev = null; + this.payload = payload; + this.lifeForce = kInitialLifeForce; +} + + +Point.prototype.color = function () { + return "rgba(0, 0, 0, " + (this.lifeForce / kInitialLifeForce) + ")"; +}; + + +Point.prototype.decay = function () { + this.lifeForce -= kDecaySpeed; + return this.lifeForce <= 0; +}; + + +function PointsList() { + this.head = null; + this.count = 0; +} + + +PointsList.prototype.add = function (point) { + if (this.head !== null) this.head.prev = point; + point.next = this.head; + this.head = point; + this.count++; +} + + +PointsList.prototype.remove = function (point) { + if (point.next !== null) { + point.next.prev = point.prev; + } + if (point.prev !== null) { + point.prev.next = point.next; + } else { + this.head = point.next; + } + this.count--; +} + + +function GeneratePayloadTree(depth, tag) { + if (depth == 0) { + return { + array : [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ], + string : 'String for key ' + tag + ' in leaf node' + }; + } else { + return { + left: GeneratePayloadTree(depth - 1, tag), + right: GeneratePayloadTree(depth - 1, tag) + }; + } +} + + +// To make the benchmark results predictable, we replace Math.random +// with a 100% deterministic alternative. +Math.random = (function() { + var seed = 49734321; + return function() { + // Robert Jenkins' 32 bit integer hash function. + seed = ((seed + 0x7ed55d16) + (seed << 12)) & 0xffffffff; + seed = ((seed ^ 0xc761c23c) ^ (seed >>> 19)) & 0xffffffff; + seed = ((seed + 0x165667b1) + (seed << 5)) & 0xffffffff; + seed = ((seed + 0xd3a2646c) ^ (seed << 9)) & 0xffffffff; + seed = ((seed + 0xfd7046c5) + (seed << 3)) & 0xffffffff; + seed = ((seed ^ 0xb55a4f09) ^ (seed >>> 16)) & 0xffffffff; + return (seed & 0xfffffff) / 0x10000000; + }; +})(); + + +function GenerateKey() { + // The benchmark framework guarantees that Math.random is + // deterministic; see base.js. + return Math.random(); +} + +function CreateNewPoint() { + // Insert new node with a unique key. + var key; + do { key = GenerateKey(); } while (splayTree.find(key) != null); + + var point = new Point(Math.random() * 40 - 20, + Math.random() * 40 - 20, + Math.random() * 40 - 20, + GeneratePayloadTree(5, "" + key)); + + livePoints.add(point); + + splayTree.insert(key, point); + return key; +} + +function ModifyPointsSet() { + if (livePoints.count < kNPoints) { + for (var i = 0; i < kNModifications; i++) { + CreateNewPoint(); + } + } else if (kNModifications === 20) { + kNModifications = 80; + kDecay = 30; + } + + for (var i = 0; i < kNModifications; i++) { + var key = CreateNewPoint(); + var greatest = splayTree.findGreatestLessThan(key); + if (greatest == null) { + var point = splayTree.remove(key).value; + } else { + var point = splayTree.remove(greatest.key).value; + } + livePoints.remove(point); + point.payload = null; + dyingPoints.add(point); + } +} + + +function PausePlot(width, height, size, scale) { + var canvas = document.createElement("canvas"); + canvas.width = this.width = width; + canvas.height = this.height = height; + document.body.appendChild(canvas); + + this.ctx = canvas.getContext('2d'); + + if (typeof scale !== "number") { + this.autoScale = true; + this.maxPause = 0; + } else { + this.autoScale = false; + this.maxPause = scale; + } + + this.size = size; + + // Initialize cyclic buffer for pauses. + this.pauses = new Array(this.size); + this.start = this.size; + this.idx = 0; +} + + +PausePlot.prototype.addPause = function (p) { + if (this.idx === this.size) { + this.idx = 0; + } + + if (this.idx === this.start) { + this.start++; + } + + if (this.start === this.size) { + this.start = 0; + } + + this.pauses[this.idx++] = p; +}; + + +PausePlot.prototype.iteratePauses = function (f) { + if (this.start < this.idx) { + for (var i = this.start; i < this.idx; i++) { + f.call(this, i - this.start, this.pauses[i]); + } + } else { + for (var i = this.start; i < this.size; i++) { + f.call(this, i - this.start, this.pauses[i]); + } + + var offs = this.size - this.start; + for (var i = 0; i < this.idx; i++) { + f.call(this, i + offs, this.pauses[i]); + } + } +}; + + +PausePlot.prototype.draw = function () { + var first = null; + + if (this.autoScale) { + this.iteratePauses(function (i, v) { + if (first === null) { + first = v; + } + this.maxPause = Math.max(v, this.maxPause); + }); + } + + var dx = this.width / this.size; + var dy = this.height / this.maxPause; + + this.ctx.save(); + this.ctx.clearRect(0, 0, this.width, this.height); + this.ctx.beginPath(); + this.ctx.moveTo(1, dy * this.pauses[this.start]); + var p = first; + this.iteratePauses(function (i, v) { + var delta = v - p; + var x = 1 + dx * i; + var y = dy * v; + this.ctx.lineTo(x, y); + if (delta > 2 * (p / 3)) { + this.ctx.font = "bold 12px sans-serif"; + this.ctx.textBaseline = "bottom"; + this.ctx.fillText(v + "ms", x + 2, y); + } + p = v; + }); + this.ctx.strokeStyle = "black"; + this.ctx.stroke(); + this.ctx.restore(); +} + + +function Scene(width, height) { + var canvas = document.createElement("canvas"); + canvas.width = width; + canvas.height = height; + document.body.appendChild(canvas); + + this.ctx = canvas.getContext('2d'); + this.width = canvas.width; + this.height = canvas.height; + + // Projection configuration. + this.x0 = canvas.width / 2; + this.y0 = canvas.height / 2; + this.z0 = 100; + this.f = 1000; // Focal length. + + // Camera is rotating around y-axis. + this.angle = 0; +} + + +Scene.prototype.drawPoint = function (x, y, z, color) { + // Rotate the camera around y-axis. + var rx = x * Math.cos(this.angle) - z * Math.sin(this.angle); + var ry = y; + var rz = x * Math.sin(this.angle) + z * Math.cos(this.angle); + + // Perform perspective projection. + var px = (this.f * rx) / (rz - this.z0) + this.x0; + var py = (this.f * ry) / (rz - this.z0) + this.y0; + + this.ctx.save(); + this.ctx.fillStyle = color + this.ctx.beginPath(); + this.ctx.arc(px, py, kPointRadius, 0, 2 * Math.PI, true); + this.ctx.fill(); + this.ctx.restore(); +}; + + +Scene.prototype.drawDyingPoints = function () { + var point_next = null; + for (var point = dyingPoints.head; point !== null; point = point_next) { + // Rotate the scene around y-axis. + scene.drawPoint(point.x, point.y, point.z, point.color()); + + point_next = point.next; + + // Decay the current point and remove it from the list + // if it's life-force ran out. + if (point.decay()) { + dyingPoints.remove(point); + } + } +}; + + +Scene.prototype.draw = function () { + this.ctx.save(); + this.ctx.clearRect(0, 0, this.width, this.height); + this.drawDyingPoints(); + this.ctx.restore(); + + this.angle += Math.PI / 90.0; +}; + + +function updateStats(pause) { + numberOfFrames++; + if (pause > 20) { + sumOfSquaredPauses += (pause - 20) * (pause - 20); + } + pauseDistribution[Math.floor(pause / 10)] |= 0; + pauseDistribution[Math.floor(pause / 10)]++; +} + + +function renderStats() { + var msg = document.createElement("p"); + msg.innerHTML = "Score " + + Math.round(numberOfFrames * 1000 / sumOfSquaredPauses); + var table = document.createElement("table"); + table.align = "center"; + for (var i = 0; i < pauseDistribution.length; i++) { + if (pauseDistribution[i] > 0) { + var row = document.createElement("tr"); + var time = document.createElement("td"); + var count = document.createElement("td"); + time.innerHTML = i*10 + "-" + (i+1)*10 + "ms"; + count.innerHTML = " => " + pauseDistribution[i]; + row.appendChild(time); + row.appendChild(count); + table.appendChild(row); + } + } + div.appendChild(msg); + div.appendChild(table); +} + + +function render() { + if (typeof renderingStartTime === 'undefined') { + renderingStartTime = Date.now(); + benchmarkStartTime = renderingStartTime; + } + + ModifyPointsSet(); + + scene.draw(); + + var renderingEndTime = Date.now(); + var pause = renderingEndTime - renderingStartTime; + pausePlot.addPause(pause); + renderingStartTime = renderingEndTime; + + pausePlot.draw(); + + updateStats(pause); + + div.innerHTML = + livePoints.count + "/" + dyingPoints.count + " " + + pause + "(max = " + pausePlot.maxPause + ") ms " + + numberOfFrames + " frames"; + + if (renderingEndTime < benchmarkStartTime + benchmarkTimeLimit) { + // Schedule next frame. + requestAnimationFrame(render); + } else { + renderStats(); + } +} + + +function Form() { + function create(tag) { return document.createElement(tag); } + function text(value) { return document.createTextNode(value); } + + this.form = create("form"); + this.form.setAttribute("action", "javascript:start()"); + + var table = create("table"); + table.setAttribute("style", "margin-left: auto; margin-right: auto;"); + + function col(a) { + var td = create("td"); + td.appendChild(a); + return td; + } + + function row(a, b) { + var tr = create("tr"); + tr.appendChild(col(a)); + tr.appendChild(col(b)); + return tr; + } + + this.timelimit = create("input"); + this.timelimit.setAttribute("value", "60"); + + table.appendChild(row(text("Time limit in seconds"), this.timelimit)); + + this.autoscale = create("input"); + this.autoscale.setAttribute("type", "checkbox"); + this.autoscale.setAttribute("checked", "true"); + table.appendChild(row(text("Autoscale pauses plot"), this.autoscale)); + + var button = create("input"); + button.setAttribute("type", "submit"); + button.setAttribute("value", "Start"); + this.form.appendChild(table); + this.form.appendChild(button); + + document.body.appendChild(this.form); +} + + +Form.prototype.remove = function () { + document.body.removeChild(this.form); +}; + + +function init() { + livePoints = new PointsList; + dyingPoints = new PointsList; + + splayTree = new SplayTree(); + + scene = new Scene(640, 480); + + div = document.createElement("div"); + document.body.appendChild(div); + + pausePlot = new PausePlot(480, autoScale ? 240 : 500, 160, autoScale ? void 0 : 500); +} + +function start() { + benchmarkTimeLimit = form.timelimit.value * 1000; + autoScale = form.autoscale.checked; + form.remove(); + init(); + render(); +} + +var form = new Form(); diff --git a/node-v0.8.14/deps/v8/benchmarks/splay.js b/node-v0.8.14/deps/v8/benchmarks/splay.js new file mode 100644 index 0000000..6b4f56d --- /dev/null +++ b/node-v0.8.14/deps/v8/benchmarks/splay.js @@ -0,0 +1,394 @@ +// Copyright 2009 the V8 project authors. All rights reserved. +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following +// disclaimer in the documentation and/or other materials provided +// with the distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +// This benchmark is based on a JavaScript log processing module used +// by the V8 profiler to generate execution time profiles for runs of +// JavaScript applications, and it effectively measures how fast the +// JavaScript engine is at allocating nodes and reclaiming the memory +// used for old nodes. Because of the way splay trees work, the engine +// also has to deal with a lot of changes to the large tree object +// graph. + +var Splay = new BenchmarkSuite('Splay', 81491, [ + new Benchmark("Splay", SplayRun, SplaySetup, SplayTearDown) +]); + + +// Configuration. +var kSplayTreeSize = 8000; +var kSplayTreeModifications = 80; +var kSplayTreePayloadDepth = 5; + +var splayTree = null; + + +function GeneratePayloadTree(depth, tag) { + if (depth == 0) { + return { + array : [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ], + string : 'String for key ' + tag + ' in leaf node' + }; + } else { + return { + left: GeneratePayloadTree(depth - 1, tag), + right: GeneratePayloadTree(depth - 1, tag) + }; + } +} + + +function GenerateKey() { + // The benchmark framework guarantees that Math.random is + // deterministic; see base.js. + return Math.random(); +} + + +function InsertNewNode() { + // Insert new node with a unique key. + var key; + do { + key = GenerateKey(); + } while (splayTree.find(key) != null); + var payload = GeneratePayloadTree(kSplayTreePayloadDepth, String(key)); + splayTree.insert(key, payload); + return key; +} + + + +function SplaySetup() { + splayTree = new SplayTree(); + for (var i = 0; i < kSplayTreeSize; i++) InsertNewNode(); +} + + +function SplayTearDown() { + // Allow the garbage collector to reclaim the memory + // used by the splay tree no matter how we exit the + // tear down function. + var keys = splayTree.exportKeys(); + splayTree = null; + + // Verify that the splay tree has the right size. + var length = keys.length; + if (length != kSplayTreeSize) { + throw new Error("Splay tree has wrong size"); + } + + // Verify that the splay tree has sorted, unique keys. + for (var i = 0; i < length - 1; i++) { + if (keys[i] >= keys[i + 1]) { + throw new Error("Splay tree not sorted"); + } + } +} + + +function SplayRun() { + // Replace a few nodes in the splay tree. + for (var i = 0; i < kSplayTreeModifications; i++) { + var key = InsertNewNode(); + var greatest = splayTree.findGreatestLessThan(key); + if (greatest == null) splayTree.remove(key); + else splayTree.remove(greatest.key); + } +} + + +/** + * Constructs a Splay tree. A splay tree is a self-balancing binary + * search tree with the additional property that recently accessed + * elements are quick to access again. It performs basic operations + * such as insertion, look-up and removal in O(log(n)) amortized time. + * + * @constructor + */ +function SplayTree() { +}; + + +/** + * Pointer to the root node of the tree. + * + * @type {SplayTree.Node} + * @private + */ +SplayTree.prototype.root_ = null; + + +/** + * @return {boolean} Whether the tree is empty. + */ +SplayTree.prototype.isEmpty = function() { + return !this.root_; +}; + + +/** + * Inserts a node into the tree with the specified key and value if + * the tree does not already contain a node with the specified key. If + * the value is inserted, it becomes the root of the tree. + * + * @param {number} key Key to insert into the tree. + * @param {*} value Value to insert into the tree. + */ +SplayTree.prototype.insert = function(key, value) { + if (this.isEmpty()) { + this.root_ = new SplayTree.Node(key, value); + return; + } + // Splay on the key to move the last node on the search path for + // the key to the root of the tree. + this.splay_(key); + if (this.root_.key == key) { + return; + } + var node = new SplayTree.Node(key, value); + if (key > this.root_.key) { + node.left = this.root_; + node.right = this.root_.right; + this.root_.right = null; + } else { + node.right = this.root_; + node.left = this.root_.left; + this.root_.left = null; + } + this.root_ = node; +}; + + +/** + * Removes a node with the specified key from the tree if the tree + * contains a node with this key. The removed node is returned. If the + * key is not found, an exception is thrown. + * + * @param {number} key Key to find and remove from the tree. + * @return {SplayTree.Node} The removed node. + */ +SplayTree.prototype.remove = function(key) { + if (this.isEmpty()) { + throw Error('Key not found: ' + key); + } + this.splay_(key); + if (this.root_.key != key) { + throw Error('Key not found: ' + key); + } + var removed = this.root_; + if (!this.root_.left) { + this.root_ = this.root_.right; + } else { + var right = this.root_.right; + this.root_ = this.root_.left; + // Splay to make sure that the new root has an empty right child. + this.splay_(key); + // Insert the original right child as the right child of the new + // root. + this.root_.right = right; + } + return removed; +}; + + +/** + * Returns the node having the specified key or null if the tree doesn't contain + * a node with the specified key. + * + * @param {number} key Key to find in the tree. + * @return {SplayTree.Node} Node having the specified key. + */ +SplayTree.prototype.find = function(key) { + if (this.isEmpty()) { + return null; + } + this.splay_(key); + return this.root_.key == key ? this.root_ : null; +}; + + +/** + * @return {SplayTree.Node} Node having the maximum key value. + */ +SplayTree.prototype.findMax = function(opt_startNode) { + if (this.isEmpty()) { + return null; + } + var current = opt_startNode || this.root_; + while (current.right) { + current = current.right; + } + return current; +}; + + +/** + * @return {SplayTree.Node} Node having the maximum key value that + * is less than the specified key value. + */ +SplayTree.prototype.findGreatestLessThan = function(key) { + if (this.isEmpty()) { + return null; + } + // Splay on the key to move the node with the given key or the last + // node on the search path to the top of the tree. + this.splay_(key); + // Now the result is either the root node or the greatest node in + // the left subtree. + if (this.root_.key < key) { + return this.root_; + } else if (this.root_.left) { + return this.findMax(this.root_.left); + } else { + return null; + } +}; + + +/** + * @return {Array<*>} An array containing all the keys of tree's nodes. + */ +SplayTree.prototype.exportKeys = function() { + var result = []; + if (!this.isEmpty()) { + this.root_.traverse_(function(node) { result.push(node.key); }); + } + return result; +}; + + +/** + * Perform the splay operation for the given key. Moves the node with + * the given key to the top of the tree. If no node has the given + * key, the last node on the search path is moved to the top of the + * tree. This is the simplified top-down splaying algorithm from: + * "Self-adjusting Binary Search Trees" by Sleator and Tarjan + * + * @param {number} key Key to splay the tree on. + * @private + */ +SplayTree.prototype.splay_ = function(key) { + if (this.isEmpty()) { + return; + } + // Create a dummy node. The use of the dummy node is a bit + // counter-intuitive: The right child of the dummy node will hold + // the L tree of the algorithm. The left child of the dummy node + // will hold the R tree of the algorithm. Using a dummy node, left + // and right will always be nodes and we avoid special cases. + var dummy, left, right; + dummy = left = right = new SplayTree.Node(null, null); + var current = this.root_; + while (true) { + if (key < current.key) { + if (!current.left) { + break; + } + if (key < current.left.key) { + // Rotate right. + var tmp = current.left; + current.left = tmp.right; + tmp.right = current; + current = tmp; + if (!current.left) { + break; + } + } + // Link right. + right.left = current; + right = current; + current = current.left; + } else if (key > current.key) { + if (!current.right) { + break; + } + if (key > current.right.key) { + // Rotate left. + var tmp = current.right; + current.right = tmp.left; + tmp.left = current; + current = tmp; + if (!current.right) { + break; + } + } + // Link left. + left.right = current; + left = current; + current = current.right; + } else { + break; + } + } + // Assemble. + left.right = current.left; + right.left = current.right; + current.left = dummy.right; + current.right = dummy.left; + this.root_ = current; +}; + + +/** + * Constructs a Splay tree node. + * + * @param {number} key Key. + * @param {*} value Value. + */ +SplayTree.Node = function(key, value) { + this.key = key; + this.value = value; +}; + + +/** + * @type {SplayTree.Node} + */ +SplayTree.Node.prototype.left = null; + + +/** + * @type {SplayTree.Node} + */ +SplayTree.Node.prototype.right = null; + + +/** + * Performs an ordered traversal of the subtree starting at + * this SplayTree.Node. + * + * @param {function(SplayTree.Node)} f Visitor function. + * @private + */ +SplayTree.Node.prototype.traverse_ = function(f) { + var current = this; + while (current) { + var left = current.left; + if (left) left.traverse_(f); + f(current); + current = current.right; + } +}; diff --git a/node-v0.8.14/deps/v8/benchmarks/style.css b/node-v0.8.14/deps/v8/benchmarks/style.css new file mode 100644 index 0000000..d9f4dbf --- /dev/null +++ b/node-v0.8.14/deps/v8/benchmarks/style.css @@ -0,0 +1,77 @@ +hr { + border: 1px solid; + border-color: #36C; + margin: 1em 0; +} + +h1, h2, h3, h4 { + margin: 0; + margin-bottom: 0; +} + +h1 { + font-size: 154%; + height: 1.2em; +} + + +li { + margin: .3em 0 1em 0; +} + +body { + font-family: Helvetica,Arial,sans-serif; + color: #000; + background-color: #fff; +} + +div.title { + background-color: rgb(229, 236, 249); + border-top: 1px solid rgb(51, 102, 204); + text-align: center; + padding-top: 0.2em; + padding-bottom: 0.2em; + margin-bottom: 20px; +} + +div.subtitle { + border-bottom: 1px solid rgb(51, 102, 204); + margin-top: 2em; +} + +td.contents { + text-align: left; +} + +div.run { + margin: 20px; + width: 300px; + height: 300px; + float: right; + background-color: rgb(229, 236, 249); + background-image: url(v8-logo.png); + background-position: center center; + background-repeat: no-repeat; + border: 1px solid rgb(51, 102, 204); +} + +div.warning { + background: #ffffd9; + border: 1px solid #d2d26a; + display: none; + margin: 1em 0 2em; + padding: 8px; + text-align: center; +} + +#status { + text-align: center; + margin-top: 50px; + font-size: 120%; + font-weight: bold; +} + +#results { + text-align: left; + margin: 30px 0 0 90px; +} diff --git a/node-v0.8.14/deps/v8/benchmarks/v8-logo.png b/node-v0.8.14/deps/v8/benchmarks/v8-logo.png new file mode 100644 index 0000000000000000000000000000000000000000..91867657f7aa419c355ce4b25667f788905947a4 GIT binary patch literal 24293 zcmV+2Kq9}1P)D)3~444>0B!qZn_~G%G`X z8uin-pVtpD zCR#tQr*S{82fT95lv1LmX(+}>OU^`1L$oXuQzT~{wOvQnT1qL&&o9eD)>?`&5)o0` zw&dLNQ9q6Qc|AnkjA)(szY(2{F+@#6y&K5SGf@b%EDHtiS5Z7S4bAgZQuowTGmd1f zecs@waX+tnN9de05fOzDXibssoEXMD> zr>^Uy4%eys7NY*Vp2q#WzHp_K$a_!Dxe~EMpb!H&TOLbZGUZrmY||8@?Anf8+fs~? zT-%bhmb~|5j9D3I*L4E2`QXV1PxCyHwU$g{sO$TZ%5&O}*TnBR=bi@t!>{H^V!5v| z0}x9oQHqfoV<-e)qAoQ8mMyf9b1g0W^OlXx7;|=djnsagCOS+9{3SK)2=MPq&Sb2m z#16w4L#=B|eb3p0bMA@0KO^_^(&;u*>%@qGet+6?^LvlG z9T{tBVgoOAc%sG_BB1aokuip12t-6QPZL=-=w(@`Ydh-t{vzk{yq?DWPhKGeN^CGW zXG$?j>TJl+LW>xA>soSb$T}rPbk)ZC*{kn+LC|9eN2e2myid-Vh->|(X-e(Szdz3t zlvb*FivuI)-%z8sCGbuAfdCGABjt<&mj7`8lY=g3-1 zEvMc@L?gcsz5^n6&Y67hQj<$Ik`m>rzJFd%&UX9>Dm}QZT-JXKifx+plO;nX|=T2sPx1IsrRl#Y{m+L_tY3eDVIO@oTfjor*Z#N z={6Aw5Y;pd8RsZW2O*9)=g3({DJMz0VSKGh!8LtUQ%5f~>T?YH+&Ue`KaL}{ZA*Th zX_}`}TFCnZ>bmZEAfCqkvr}%O5`jYq6uhTl94W>~frm6EKZ|j7+<$h86$Zmalt&7T z*VW+HXASyR5fmtS+jVp}>?x`~eBcz`Jk#{2asPx%8)A%c6{VY|A!9A=_pkEvK6o)| z*S4#A7RIb;q(>L5?6X51i1c-&zK3CJd|}C%TGvwKd*qxWYwVM^{xt5# zyu9~htrer>le}VW#T3Qpt+iy0rC}V!&`>w)G<8{)RTTe>)6qr^V}_%+M+QSw`rYDC ztfj8+$AGJIsx8Yx(=-XScb;dN&@;w}lm9Ab;c47w9@@w~XANfMoT+Ww)nPsy z_7b6-b+p^Ph~eVF!k}T)EdysT$V(3jKA$$|d$Pm4_r=kn-)#(aT_=tW(cBs<6KVgF zp+f8e=b~*}IX61<0rwx8Ta21exVvN+bEyWPXI!7tSazCu4%o&wuAk{i2>_0rWX*$S#?Anep(~UbO z6KThBtLvZSmgC{Ua6cFANKBjdEBoH(NLvMgkc zEs+^)L+0Qww8%Y4F|HhA@V+qntXl<_oU<7E%{m?bno&pgusU__x=tQe!)Y}hsx?O< zi55Qq!mazyFuc#Ut#l0y$MD(S_E(}a9G{*8$AJfyprcC8ndWJtn4%1|bY1t5ky~d( z`Z>YLgL+%ObNTMpShCK&aaP`Y3f@!7%--Yg@6^u$a}a(&->(hKIl(Bbv6Pogt?P(V zB0tY$jG=M2dm8sg9yu#sG!Y2})X(!O>c$kQp)y93P8$QoNFqWI<`lHs5j^>62*%9=h}AG|v9-{YF+ z`S=+*V*oB7#2jO(9|ozZk@*NZuE3y0l`~D#ke_EtIZ@a3!qn4rT3x!-9C>}O>U*Lc zqcKLnPo%QinL|!WpM^zf%;lVE_A@!_sP6|h%x=XK*vd{~jDj&BZH71ooWUg}S<^Js z4?_t+DN)La=4mQvIj8WyHgaq98R=Duky1|7P(ur`XKhRw*5D|GRzwWp_%l?zwtg^3 zF)xWenxKL|Bh|$L(CPQR9G*sY6Swh*sAMYq`K&Ft0zQ|XGp}21+Hf%Jg2-=;r5H;D zN6HGra@MU7_83CRkQ9KaQ&&yUk#STQtC~O0s#I!>p=mluookI1QqgYrQeG!FGAyGV zO?{R^EbK$vlbADgT`$h>tIrVcKgDBP_4V~HbzLt`?AqDf!vksnKmdfns8J_@3TdsC zVGN|!nmW3$NP&)^x`sZ-u^@_QqpqV|4U*mK9-+sI`+>tBV-V#P9IC$WCGyqZp)M_) zbM*T6uK-J3*RNV)+HpG9u2O%?hZX5;Jsh*BS#tRt6^Pd~jm*Kz_-szX+pqDJzUu|i z25lDEh*5Y8epmlKScY|kzUDPelSpM{CI#U=uWj7!5u-E?o98qdA_6!ReLs{wEVm(A zWmt$p%d*IU)+zQm9$0ID2R>N(^|e0uy#X=(8Ju&)`FURsEoU|;Y)ot@ zlESO{mWasDvwTOxkpzyQYdbPkdWw625=7%1=ZZO?6hM?ln^4n$LyBY?BZg^>rE%Q7 z+mh66Oo&d#bOc>n*S={*X}siC*_UOOUx+1WkRfW8h5|Dsulb(enwIO{F|@uKV^*m) z`i?CRCTykB8YR^S?i^>Lff=2O!dcvl?s=-Mx2mC8(2$756V*W_q7|sssQMOdE*KsR z+wnMOUNSXwG%}=#xR;t-vxQWD)uA^{Lo>I9#Gsi>VvUvWVU(8JsYnOsfV$oLc||xf zjUmfQGVj&W$P#Y#Z1=CPV&F~FP~R1B?V2sdZ;RYu1_3>U;-@i&EY~_fv9(GGoPlmJ zi5?k0tooto+7hY0etjIOT0ZDI2pTY0L|XtzLUH8CRY(&@(Fcue2i7uQP+r*5U&Uer zr0*%ELPk;DfvxYpRSVWA_$63_UY@Wjc@zK$GEoeH96Rb$*?=C@ndfPxjDxHL0+Uvy z_%Qk!)z{*Y=Nj52KZ}mevMfZlOcu_5rfylNulnRa%D9(hp?RLgs0F=budMs57$el_ zw)Xb;->JG+(?#nsNkr)Ho@mmOWJrxQIxJ{6|G8~D;eGeRP~?#2S<-N{`;4`;G!1!Q zB6HXE6hjd42)xHvSY}&Ob9Kb4+gt$s0J<4gc0tb_ZOV?xL|cbl|L$}+2xU03Q)`T& zzUu`WfpgG6o}3GI3bj*5ws0y#fI~qm&d)QoU3d0*0lMq%q5 z)jkVa2t(H16Ng4WOn?yY9mslXhmJn?Y)ze0^I$ zzO<)!iVX%MGvrFI?N*BjYB37U0|1cJx_0v!)_iuInaPec)^^jf%%r&P!!U|`bItkJ ztw}xV8@v}fZQTacJal|s8Lp|&e(T%{L_Fu3=b5JIAXv&c?r8V&a+R9@E@5k$CgIuQ z26t_@>FIPd(EU~YbEm#^eXw+U>Jg@w^k)j-l_t~q$SDUO=BCz6i$LJ9q{iu>%uxE^wCp{!jePE4$Prp zgkHBVPdTx={6H|!gFEP!q!?xB1D~N$4#=o1=+dj_*F+XE&l4@nLc=(IIjg*>aigVi zIPA-yf7emlc4Dks2A4Nh>6~jgI!Zi>h`x3>!FxH-pf*}#rRNH5@EWlPPJmHNv{72u zQcO_{dKku4nyv5MJ?@33fPzSbZ7H_3(#3e=;5f?S?}Y=7dFY(v^TU`^O7!yQzoV|Y zQi9Qd>pAB~kLl{HPqXu4isXZr8FsA!PzRsS7brrSSTSqE$>=yFQ`+tN7B-UMANZP9N&~3OD+$xbuG1HC!QZEw@%G-N;LcVh%q!qh7tPR@U6}a z1|T4raF8>U4h`cSjUn{rxq%DNWPR zFpd;rD8nSnLVljbi9DQf#~4LW5A|Nl4>yFciGW{H59{B16oEcnqk(i|7%Y+2lp?`^ z?`$-H#!f-X6K?6m6gd@dS4Q$(eRqv`BUR3deWp?TI;z#B(>zTyF>6aAw2I^<@*g$V zZ}nY-W6wQtI1_-6ecwyp|JshUkbcGjdd5hHye~EQ7beDTV%*;Q6-dx_9Sy@MsVT-P zw?^|WG3-ZJG!IWN0H8|mr2WECHFN6;hZukl4$Pu@_4u9zt0*(n<8Jq@*nyU9)_r); zOyP)%m}2+F0MM@T^GpjZ)KDWWIw8*}B2L?PH=A+SfEqd!I?W!(-KrJ`CbP>K31Xh+GTyJZt=2-&Nx$0GYrd)W~x`467)uaS$vt2;ms{eDFdcHpZ+# zz+33WX>bidWM(V~_dKOU-7u_h3-ANroa2?!=B;zx_dQM1feaB%(?I~yZ#Qn;>O$KJ zHIjfE+>g8$$aC#O0Uk9`=}BwQrT}^C!Go)8dFri3dv86QqLE^m#DazxgGgvK8Dog5XNu2xI2>duOcRu} zNJW_oCmHOi_0F$t)EF2sYLYE@|0c`$2u-)v(mYKoHB*3qTPvErV%)oz7jZxZl%8bx z=dQ*rlScC_9=dBgnfKjd7-6YAP0go1^gW`MJ_t?I(1H8N)>>L37<9cD9*h;vKsJmp zSR)+(?(b^j(4rHdCEjY}aO=BDipr%$ZRo&AYS|*(C-1$8Wh`_=&4+$iml~B*xFtJK zD7XsykN`7|7aJqwkc6wRgfH;CuZrIHeIe`QOdi4;?6qJoC2M1EA8lbARwkl-usi3Jv~=_E2^Y` zfPNNL7cK46P(#$L)8n>nrFKS78V6X*{UBPwsnrCDI%U13lS4W=O@|dXALN;)X~?p} z+WH*$zFCoPFjZE*UwNir9YUr^mlT&6wrHU#2Yc%I5fv6BMR)SbU2g;%Tl?Bc$zB>ZETP^YPFGDWg~i8 z3XyXhcPk3z76C|$1P1SA!-%n#3>}|ut7ZaF$DRVGF8Rz^l`~roUaPpmp$_A?0`)$c zKd2FX{4S=&^jv~oTmk3h=UGard75Nw^;%<_7kNVkeo zN)-05WvWT(eL+h3)Zof33_HdsQC8%5trLkP=N!>HY_Ym4kaD777+1t2+)ps$u0ia8 zVZ|7W2A(Q=@ZP#~!oAHY$@4kYDn&U_3o_`Itmb9tXSF3h0gdwz0*&KH%{WSF_L=hI zq=7m|eb>`8m(0Y^^VwL;r;J;xQvz_pO?GFF5JK`*sFr+laiGvcg+T+o{m78@mtHA) zFq2B7`8k*LvgmO4s~S`v5F8vt3k*aobWGn`*ODbp1KEJ?HGx*IAtEA`HukIN{85Re z)kB4l!tEZ7DQHoMuR1C1P-HNK9ld^Clm^g7!!tQGwyG(xnB?LcwsN{~OpxVzGp)8^ zsL0%apzAEmdoLra*FevQaio}{WKbcTw;SDkCMxKMj2hKiE2Nc6hSv3m%xZc`8ze|yqaCV7H!!%M~U$l z!wN!{w~nBkyv7A-<-lEubEEe~^W0ioPsZ_>Mz~N}XM0Un5l9p|BDXxdtW`AeKp_}d z4t!W0AQ|Q3v>AF_ko<)~pez6ZLsEKnVl86|RtehQ8||+rm{33KgZ~k*gWfx4>#<|| z*59Qb%azW8N@X>PC+9383^kyn2TU|ZfUbm5#F$%i1+b4!7B)aMLWy*K)e*kF{uP|) zzyJ9^AA)NaM{c1bLav8v)mwl=TN^V`li?8Kzf(%Gp%Y_}N05&toEk;*q(*3tx>YlS zY{F`yh!$WD^-NT`Ck0j$Y4qfnOv9vX9KK z08VJ0X~0XEa7siI#F%ASs8Pb1_gs05=Y-%lO_PwDzH%WjMM#9j_-1v{my8=AjSSZF z?js^v0WR0NM5me~wLCyIcoMuPuXL&Pgpa6tn00!D;SCss@ZnRGaZ0p%hCidc@4a^{ zYXC6BAR-PL#XXmUji@$HlYBSq$GXQbiYDsltfStBQg2JutvPfi^l}5eM)*62iNILX z_zv{br)i@83VY1ku9L0@+Q{!YWq0WVf*0L$ZyP$|*A#ZsAd%kWp{06}HU}2nH^xYc z*|oVHl4_tMs~|jjosCHPlGj?kcZ0$4@et)+i&F;jgF z1Fth&$Vp|T$og3)i9kw3tKp?#95-Lro%_Plvf|}xKvUZzdqqFP~jfZx*=6>~KS+-P0-w-S4(sE04TzsO4bJPR$jb*;2} zw8PY`ziXr5S&d2V_pdA51EQGqG?{h)+JNgU>Jc>Y-m8xzv)F>V&xiefb5-!Uou!4P zk9Fsu1|vUZ++d?=eJ2>%wQ5V;7yv7J;h*lULqn|VO8>P^oi*qLVLMr4OT;^pTN=jk zp(22QNI6S60jjGkY^XH5G^ZKT#wjOhjTvi;jMF=}Q&1 z64~P5{c%-}PI-9+(0eI8$`7b+e)iCzoWS#g69wb17B)c1K&mV-Qu#w)=QUU31Rso-DRc_Co>V zG>2JxC6Frsh9MFV5!v7brPRGliP+syr4pl*kD`kDZu-U1Z&0l|Ow(ZmQ)Hrzp@r2! zA!+R1835UOzgFp9Gt9!qC zE6F2*FsDGM8Ud~i4#Ox(c=z3h`>#GqBNM0f=d{+KY7%24&kOD$l87-^d=}mQ!YC|2 z!k-+S&#k`^*yO&lQKnC{A?x#;mP8Fdi~6~rot9%|DpK1eXKKzoNO+*=)#?o+(5QwG zJB$;wQJv0VZoEvLmDU@E26TE~@6*2ZIOQ#o*Z2M%0{mamqgzFAu5&+n9e{O+*rqWe z1B`)+R_%Mkpa;LvMQe9{`UQMM%TD3%{XCO7u`=mH1E<2W)OrH->wI{JQM>9$l9x=* zxU*!E=6ROZm9=&?XN$I$RiK#Oi7f&GoX#K>ZCxugzna9LYgDa}@>8xlyZESma?Qy1 zp02o7AJNMdP&Vm9i)Xt6^^}^+Z@Z8giPA0R&N*WxqKgb1b_86?G-h+&-JNsTWZH<; zRj{n>Bk5J3w_tva<4)2EOzG&F3=n@(61sYKG_pJ5PrLk@sXc zE4lS|0Xe2#=OoBCgLPWt4J<`*Kx&gr;?%pI9{bIgjHEK>9CI3)LVGsoieai4DbRW! z{n^HiUS%WcRC^X92*@c`!3@LOLHd>Ps`?Q(LNA2FXVD1odo}(~JxsMu83-Qt_&zXV zI9XjY;xIv^png^`WX(}{UT?3qZD~3jXjb;6@7pEOJLfC|Ou_p%z~#rrjp-|v90Isz zKB!}-X_Cn-5GXXLP&){)miP}V5N(%^uxDsy}u)R<9jBe)nwYW4I9!xx^0Q93Wl!v z`+3Q$g@ey@`*YD79DCF5abuETh(S;zk}IU3@9v$U8Yy7 zq8^76h%r#hLmzrGCQ|!zxw-o1YF1C}_1^P}kC5VHaly<4lWV2BdU?Fm&zyq$d8YsU z-~aEeuz@ku|ANfvUfCJ$qi%mfMjjNOja+mW3J>4fHk& zd?7dsaJ})`nf0Q;jdr&1*pb?UgRBJxw%Bi4$`{#&kU^^HBOG)+c(2t=HCX^PPrbFY z7MHjNxVGQF76q7;Xx#0tX5hM(M-)#n$`~)6kG1y8GX&3zPGUrLx96N4VX`~|&#c$B)W!{jm8eiD$K6gmSB&vkXY=pFyJ2DoM2<$$ zVzqO?pLL&H3o~d{8PqO%kO2mkQXZ*0G>uf_m{KB2@ zD8@3f*~aTk;pz28dLLF<0o4jG+&cG=izEKUT3ip#e3Y8&Kyu32e;B!`X-ZAd6hzd| zGj$sS2;d5%pKXm5FbD@5fDJUu7Fx(GMi@=P$7LoOes>&qD|)FWZD{H#j23lG{TVg# zs|^n~N;@48|Lf66jU;1S5wqe^X=kB-2{aRfANql4wo%RW)2*q}(=V?FRP-yOgUCvx zL%}VTRa?G#iW3 z^>6{ch(uRqKtfSmV5Hp}&;B!QpTw_UnT2?btjEj3V~sJ8$BAOJ~3K~&DkCf(Xb+$ry_ z2_`8ekuIvE=&S_(;q5^&)w`W*)E&m9Sxmx+qP1-8M?7S0NLsE(lR(f;D!aapsW4b~ zva6XRSsnGaMDF!_eg$mWGWvhX0F?mIUF;Lh*I&M0oaBv|SAPz`z-1YWNtxK%|GhIV(IiIhlZPr*yP2$vgPk;XW_ipC` zT>uR%o|}&WC@&W zX`$oLhBlV1Ivd<{q<+FR=Q-h7Snzvl$NT+2&7whFs`drdNDE!R+N#WQ_I?b{f$&RXlB;GCnxHW_2297B=c zI^(&zQ|SP}7QLwh%BP6#_%}=j)oH4p-xcA%oK||_0-`A`YU}J><#n{tZ>7j}O|B=- zwEUBnJJL!oQZF%JrjdI6nl&C!4|AYYan_N~p39<15Pi+TmzwMf23bF=r;%Upl95=f za>DaxUWFFV0NLwYti^p)140NvYkyYYXyq04O>qUrJPpkjhNq_nXH2J5mL90 z#8cKcQ%Cu&^|bZp*1%ZZbFU4#?nu;9xk$-?b6|I~*7mM3lWSb)_g{Mt^>2;V*!n6F z8T-W9z+Hu>e1w^tZQQ6!z4xNH5>q6bo$$bO&MVedqv}$<@)YfrX*v`HojJ4^OgJ14 z6j<;ODlGU6|5Ai_Z@FBJP@jV|o3K?(*)d(ENEOQskD<>g5Ge9i=)SGN^; z=dldmELrf4tq6W?1AkuU17;xvnx;v#5s?|Ov zZ+PFe1|6Q)$A-Of!YXCPaE{E)^9bv+UcUWvAtH&?ktZU%zNcXvR|FuvBOXBWsi^(g zmga}C9%GqWL(9^7+)Nv7X_d4>gn?Jmi};X&WKz4nzhOo0PrSD7587ktaLkxAU3AHr zqH0k-%bx3|-J1D`C6k6Rs%~S&a9%Pk`8e2gYMbm=o$<%Ut@aUZ8LB=gAivPE&^%A& z4eVMM%6l(ECar5_tPm0Cd42LhG6oW(A{VLdg{hV{Jjp; zXI_J3r=oVf{q(BFEt@vedgueju2Vqty_=>XAH0Y(H0==`4QHAaNd!7fV_H)VR^%^;}+z~DKM@bydBYb+_PH>Vy;CMO8) zXUZTDXO?A=;f3E2t-be00S<*V!H~PIqvo9%du;eb_Xt_-d(Qyn)n_x>vuf_uKIbJ1 z4^|?98qEZ0ecLSKsDyl1$+=n z%sjdD8*1u#n#$@P9(Zb+hC1iYc8;2EN<^|N&7PnL!};oZ{p!XIFb%>95G%CSl2O|= z!Hb5jnDkohaWph3k$Y>bq$Q2D&szHi^>^^Th&%XMmIM-&HVl9s;3S_JtBs7n|BD8$ z_4Occg%RY>tT@)SdSa)DR`PqJwqL!sA6ix0w&eXx3oSC*2|M3$x4En>lS7b>4#6LtsVUi1thyYRM2NO+%ed)0UwuI3yDnrh*msUL z6}HiSm0RC54NdbTJMd1GG0my zN?*I{x=%B2p4WNN8?spQJgqe4vQlbA)^#c6x9vJQ9QNeB|FoXlqZl;=JF$Er<+4f| zM*WrcAvWg3c-&_Dkwd)JN~W_cOZVW~YMJ`sa46GZt`#ZVei-QW^{;FT0h|vIO*SQb zf-n2LE=!x0L@xUDH;KI^Z`3(ADiRo zuMhB}UYesFV-$zfG!6B`?e@}~!V38f$#18EN2sY?z*-Uv5sVYDbculdA7d3@xoZ*;jpJAEP~8J&ntLOncHVb<=<;_A?o9R-t*aFiABmu*pt>+ za;}wGh3_=%X_}5B&&>JXa)8i-zr}3DS=@5HdiT9?LA|=BX&UOc=rhy6w6$7{Mtv+C}fRxpb*@kJMc6fD63D!dXWl22uNYl;E*c%Q(hyck(`B zfa==d-r08oNb0FnO(WvYISR`{nS~LBSDVw*xE~-rAI6bljC45c%h)3G`_U?r_86zT zXq|2C5u2t1+2*$M0noMw&l~3nEV7=4hib=p?`fJ2N4>!l+ba)j zg%xTW$D>`yDvr6;HcCWta8~o-yqQyzE$%@!_^FqSCn^Iy z$G{;Yec)c~VZRs92lqcP0Yf{1u2QkZT){`++c{Ahd$W*!o5sje$XlSvx41-lscEQT zzWOi>n@(WKnd}X_4DM2|)HIC@ec*s-y)J+WBInw+G))INP$@@sfHwDRF-2*IQ$$ABN*b*&q0vV~jL0c}CLmjSLE_h3LkC z%AI?lBCqUi@-dCp2L`nm^v#>)=*b(kfimYzhKQ_dC7pw)A_(?+3=sl~3oYbw`)iFG zN;ja6V$0{q5f=9hpctl~kS3x8+UloTYiSrp8Gl4{)|*L@bzvn=&te0avj#mM{+>~T z%Z}HE2naH>AN_n-N(>13FpQfR0RrGHrqC`nZVlF8_+txf;~y?#bZUn%R;S3%aIbva z?T+>LT&9d>UJcy3R#qmUSDsR$VHh`Sn14O}MwSE73*a9!Bi-8RNk2GeB5TVg5+|+X@ay@e!HvvqL}r_*nz!mCt@&m8Va00vfQF;seeUDwHwI^>v$cs(xT)a5?xfJEiIWM zsRd?Lr#R^KVV&n$K+sd;zz}D|Xed6ny+B;>r$lXHQ3fsf{L%Tm_4z%!&y6*)c#xJw z_zcS}Azc&C#I-a80i1J`c>6_B;Or!w)Q1NG4glfcIP|i5FsuGW<3=i7jC(H*5oxtC z1wlsi)-&|;JX2;o1H0LR_wsw-j^qBeZMPEqLkbB@MPn&Q=}}s(&ccR+NowOLQQ@Im zWBy4A>zp&qe9wTAckO8)5bCGRBh=hdQyW7IM{i>cEwrptJKpzYxt*m^^_;WNQDX=c zt&e737?0p@qhA zx9I@>r3(l-0AHZ|TVtgfEWXFR`1IgN41pXk4A&1`8?)y_MMTuK#baY1vG+5zN+hvP z?Qr0*;je)d_({k$^H4JR&{a&?* z1O9*JsH=Y;KQHTryq7HvTb>MP;_K^Q5t`GhPC<5Pe<;#AO%orGNm@OfK@A^#u z5j7nI7%=9DL#IJ2ok?|VM?QE#!9(zG#P3@++MJSLCvd3vj6kRC{J|j z)~eRz7AS4h9 z6Lnor3oWurNWaE={p(>Eq<0I2jd~RI-t)wlURV(mL!i850lMmv$F(hWZTBIfEGf5j zg47yoMQeNO=Z!IRIP420vLB>%Gf$IDhSk|YSOSk$XPuslx@`q&-dnQh5iidhU9@qZ za_sj4(N@m+Y%ky(wXXE1wIR2Tm;9*+4kUdg@W6)&`@JFaGyC}>8lGlNIqsJut(>`r zeKfFazke<0HxF8@aD}d;-OC^P^XET$`Sa)O1E5)BD1pHHf6qY=<9O7NS2)Sm{gV_^ z8MWxH{c^(w2Bd*TW3A}Z)y9o`_RwiLYV1bolWQ<&QREh=O=E!|+ zy@qWK;PC1wg>9jaqQn_ODEqW{SGjgf(mOUrmh@fvneqEr_6{9!Ep_$Y@9MUqsp!G@ zZvb&y-HhLUL62NEuCUrl{T#JT+?!c>Sz6Bj)2TR6-K3(2=l(0a7050yMro0WxZS+! zx1N(h_~6AOrj&%1nTWnEJx`1-=al5Z*Y^)(l)mdl>h{wQ&pA3A_S815+U)Yauwm0Q zBB_*OdV_F7=R4(sk$~j#G;DeU7;A=R+qNfp+;BrKj%z_L7%{c2OTxhzfQSq z1Z|YTxwb8O&Pr7kaz7s#CE98&Evu&tMG9#_q zJbl+wUQ`cU_4$YjnWbr(GV;fc;k_HMLL0F?qgkl$2WqHHl@)Y168Zb=A;b5b=jq7I z!bV8`&d6+DUj9hta!o_&`<^mqE|!k#fZppsh{yu(2tzB=no={$E_HU)r?}(4(cqy- zv*cWM*K?PmZM&18XQ5l)e>mn#xhte_> z%uANOt~eiJWWM4x-{Jv#@5#?|(fekkTKE853%j-e{y&!TX~@ zhTySCk2kp%_d@0?q|xDeQ)OlrRP5|0QXzy^(SXV!FX+m@`c6e%7hd{}(`qkdp! zrvi`Zmhv@XibW5MJ?lBU%{C(%*H&0p1F9@iZ}gUFS*RZdiPYcKU$>QG1hM55>rX(T zN^zx8W23kiTM_9uqvtZEXbd$h=6H%*@ZEe1^O-M)bPwsVP!rkH>urYG0i;-f8USqr z&u!!9blQH7gTX-?hOsE8s$qtY*jiiP3!5$Gc@{MjsBAPF%C6QqdU^RH-1qOgP~&Sy z3gGNbbY`uut$G~KRgc?lIfmcd7F(4)&dCa6eNXh-qwl;|=Cg+hkwU9=xVDx0x0ZCB z=jqrAQ$1;j5FqUdF?@)0qqfC*qNM6;sDQW&(jh^=y{8a7&GRHExUR2(4~)B)LKl7c z^QqMT7J!uI5J=58&ouE|woVrz+XQ3Q(b%djBQ;QTss_JyWPJ3vbris@3zl<@|b^Qv=!i@;rJJk;_A#GPZVJ#r=UW9F^7i zqh2>&3#=?3{2T7Kq~T3NyWNW@pS-AC0T>`?mvfnEdz_)vjh zA}yAbC^K!(T1yEBhY$a$3sSu}kfM*CN{P^MyG{3=Pu5N;v0T%!*9+8L8+q6F)OG#Y zKp9>;crSHq%85+FLiI~|?dfokZ64mwlu|FmlC2TUkFps!Mu<3I-WZa*K-I~Tw9SNP z4%A$Mg*DoKi%pbuy8oytKb-V59b^Wcs3;88!!`?ptl#}zKIL8-S{t}*U2Izhq1G)T zoi>Y#i!wZ83}xuEogtkhlV)UAGE8`F*;4tQgJ6S#@B_RsA|QVOLBh{9Y{(5G^(9qd zfOun#E%Lxirp$Y#4V7gNA$W55M)DT6~AVXl~Qrr|$(oCALg2>iT0pUE?E2z7-A_w*` z=~h~O_<+>wo1YXFd_01q`gB^ZQxFZFVQLG*AdNCU$Rc5DW6qhHWudO`X}^D! z`UQ3H)&Z+gNJuAZiRHR}2MSMASXr8~N_5;p+IC&}Y}US8uLG=Vsu|tGeouMHk~!8Yq=;OoxpjnHO>Zqlx4CEU zhmlZCf!qRDu&QWT7ILOcoIx_#skvhq0=8cwbqCc_x6&+}(UPfcyR-IQiH4ifpPuJg zK3iIjJ!GWT5EGmZ2a%qtg$<#qVxy&*Utj+Y@kG}tW6<}o>pEIEg4CNoAzZ1QWUka< zPHoG$b{+dugdb2U^}`_i2LuJ;sQqZT!Ixc3ZNNBSkmWsfAX1Dp^RhbqfN|i_i(S<- zoc3S|yW=)mUP|^5)vjr&%dHg|CZxOgU(xs;$f&ydqy0^b6069H$tCG;bL{Vr<4)$G zq3hjt9WRb=S4b>+8_6bUS;;*ao(i+fL)hw% zU+drkocbyJbXm8{_fZyQVB;xc8kYBmH$S=NuDvY|Cg!oVVQPYl96%~HZsMM_L{V#{ z2VU3R-uq*;Tk>ke60$-2{p(7vZQ%uiu|nTLw1Ix~C8GHP5;CHV)jO-`naT##vc7nd zY$1d|#O)~ON~Qs)gEYEPV}xDTi@Ix8ZM1owH=U4H!+G!XizKn;M>{9Nm0S1X)L!<_ z7|Ns7rXK>NaLoMut#d@duN*vR){k_3Dss1NE94WsB(RR;0H-8k%@iyj zq{(P+Axh<(X_^izLq@Ht*S(s?NUENAEHC(D@4D?e8u~%NB^=^Q+ZI^J7gLm|x{w;e zprhKU?2odRB0H?UAJ&q=tazI8ar6~>XKmL>gfH~mN%p0kay%a`Yp9htwGwQ;@F z;wPl!rcwyf?972hNt|&H2Mn6edbBz{*TfTuF>HzOHHvsbN_;_2A!+F)KhLsRM5p;P z_o(q17S!pLQfJ$BW$kZ22qWw(Xr|ttf{5I(+G|WDRUgM44Z~3CYbAiFH-nrh%(; zeC1S5MCLbT)-~?m4;UHsoN8~0SgyF_DN)mQ5BYsQecHReFA6IPG2T2B8)TCuXG-X0 zbA4w`(IHRF@Ih)TDG-w@oO4ollTQ1MA**DDTGvWT4&}nNE)kqSpPDn1uI;2Y0~-7h z`u=8(5Yts9iYv)t9rYk?VS`;63kDYAiMlqcKD(w-;(h`L&<*tV?@Mc$~UvN3dhFVWYkDX)Zf8rPXo?UV*dC8qd> zrmC0G6OlZaYkJgLW(OQ`{ryFUj9Xgg9%8*CJ2UYFe>aSyOr}K>S8`O-JRQ?^^*P^j zX0>W81RSwKxKRf+rSz`4=V!2*db8-GfoQ-pPGx$9rFI-BdQ?YcuIlYn-?Szu)RCNs zs2>KonNZ&(h1y~jEDl&hjR0?wR&repB8zp7y1u^|8XH+$P+xkUHAGpmU1b}y7-q}~k_ zj9+aI#fl=Um~prA>iRpI#t`uSzBB*;9$HC6K~$My@O^)DMBv+hr4;Cd`8J8jg&6E| zti2ol962SLQ=)OV6D|3zdFAQej+#}Z7XX9>H0SF%V;dtHFN*@|g5bxofqj9$*V+;*L>HoU6 zmGt}8hK&d7xW|t%PSmRUUNm|LW3=5UMO7%-kZLQUJg9f1Zy6WFG*%fFmk&!7 zrR((lT9Nw{z4%cgcVx$S>I`J{`N2s1r_yrgoKPguibBLiJ*9ix`tT#tfG&zi1!4=* zPHewiICah zwpB~FXrw@}w@~bK#rjxp-*`mh2F9}mq-o<9jXpjL|76Xr$q0+m8MD?(UD_xXltyV$ zf6u&EEU7vg?IayJ4u`z}F{pL!jk>zFm5A(|6WZvKv(#bN{yc5l(zx5vIPQd^+Pe1G z1yGI@2M$PmZ9rSRbAC8PJZw@QcC_-Yhc|L!|3uAQ zr`&H0zd24m>BtSbrRI+Z2o_koqVZ`(PZ-gnjO&)QwH|=MXX*Q%LI^ZX2Z_!CMCqwC z-lKM{3x?eH!-|B09{3h55=N=({-`#wXwVZ`NbQ*Fw%9ch^DRu^yQB7d*-l{XIpG~J zkek%@+J6dABPyg3v}O*6y?8xsl=`7IR74EH=E4@xWGyXzSuZl+v=9y=#BkM!EmFWK zt;RS3iY+|j4b~P?Ugz4fiieJK-NF0S!nbQbY@vx#A-7=H8k9eloGHghb2G~x^;+am z%P8eaEobYnOBdjZ90AKatmkQ>%o1CVaN+seDjS`qsf={Su+E0K-)$d2EA1wc`wcKs ztr)_9yI%DhQ(RF~fqG-=$Ta0=FhZ%h<%n9>Fr1_iVt8fE?m}6Sr!2&j;5~JH;idmo zGCOF675GLR@5V~BYAE$2)PXFWM3A_n|S)z%WKZk4h(O|u$|!2OYDa%D$_ za$=q)X?H$Ejf$1i9IRmQSUNCq=K{25*R~Ja2KzEvu7?b?n16kc>Xc0Oi80g6+0rX? z)(INzlvme1W$$OH(?1K!033^{=we|KOUNmFu(d>!Rt(jP4kgNAB@%C1xkb9E=ZdYh zBGptI2PW3^cUqQ3xa#`vPmwV29dBWHC~*uAxqLUcrU#S2qC;SUU}cD5wU2JMdwFQX z{yLzh$1T+W`$uUoXrovV*!4YGV`ZqsaDCZuJ?K>QC=+GV3Kjkga8jacD>PCpQV@a+ ztCwQAAxJ7QgtE5Sx>dTX_eb3<&2nzV1F+5szg!QrKnxM02)J+H|JMq(tCU?uS6bfA z!e28Dw%iH%ZbA$6>Y?jrt(8R+)8Rm`uYaZd!7$KIkcRq_ahJ)ab_LMr1EpN`k&~M< z^<7`m@nxZfj=Ef!Q||lzO$!Yz2hmt#(SrAsNltocZegG;Cz*)iqiX_=SBj(%qo`9` zy+(J-Sgv*TeJ`bi{vHyA)i`Xum32iqRsXGrT}}Z_w{TS2Vc$D?3qL;u3c-_eE%n1d z12Ud-hW;JG8E7qP;b-7i9!o78Ed-v5lFltCX_x&I# z_B_vJn=3d4s^t}_NIyS%I)0VNt@XsDjlezAMI9zQxQ^$UG0Tia^(iH(zcttf6u4g1 z0waXf?Ca}a5q~&0dIK17ZA&97p2Qf00Y^NcRlhHc7(90UceR4dXSxp;83>m!E2(Ey z|4+Qa30W4}Ud;!TNf0&e(T|RIZi&tFQL7%a2^|Yl?q6T&_3!^uh-K(!+`Z6l_aZdu zmzO_3#<0H}xdG<9QPX73GsZL<{x=}wAXyY3tvl}aipALAG%O>)#u&=wX$WIVyi;SS zF$Kv!XD7BU9~N39dONlGL!8yzS$TuY~a&0 z9XG$^^;Sv^#MLdKd(^=l6G8A?Z_#=akwa!S>b-2!G|}O(U&&lU*yE>fGyO6$AO}H3 zlVw@RwvJp*$7wIjeX}89Nj=hU9N3f+8AhhNu9JOQ^E|B_K+`nj$Vpw;GV+a7FU3g1 zIKGL7nyR_bvKq|5um+~swpIWmWlbqj>sr~Ul9x=jIm$162ArIkyN*oaqt}5UOou~p zSdF2$#AA7ccIC3rvT+YialC~{bSFd@JJmrZx|Z+(hLb?%(UXI~EPN=yq;-zQarcm- z3*Tzo&N=c}uOt25^=1zcL%OzmBVB{2B51QBY@k02$zuEr5OhtXF`P?TJSfcQHO!*~%uw6&J#+%(-;H_~iKBCpt0 z6=Duj&K5#`FH{(#ve$~(vWStDOHo(j+#C)E8Kos6(XanW_4LgFHA$DL*-SGbmxNUO z)S?1JOFUpbNYbdoskd`98>>^Z+L48bbre}#M`4-bqUMdVC2G{J?PT;6@2A^0z#6my zth1#TeolW_M;7hmPGt>SSK#+@>T_zq4bMVz_H`LG4C5Q4!n3<)TB_A|zCum{5)M82 zuJ36aN7+F0`uA_y?8?!4_wtAS`|p1qYMH>p7`G;}AT8H5a*YHp8xuxok4a6-=;b`m z)DHvoEFX*LuUjW*rNCgP!$AlxJu8r6ln*QJNwaZ39dC?R7NeETfN{S z15;ZOt@ry^p&5%R?hgmeZfe|!5F-7fYB`DE%W@>HoY){KGua#+d*<`%2-x?-Y77*0 zI9hD7|C$ddmIGq>0XA?#uT8hbwz3JK8@B6V7-Sbn`2~qKrhqeyHotdBH7#_-0pObN zT=GZ@0S5*caWA&En`*;3#Z1G`e+N+ma|D;ndwcK6`!dH4N2LL=5CR?cdz$A--lLRZ z-9K&ES26BW1O#W@YC)ig(Vy|)q7r?8>PSgpgG_3PC;}8qINA#*S{+X33TIu5KGcV* z{`{IdU%s*V;3IoksO(k>ZPSRBW`ST6t6VvGG~H zYiU5+7Nk0a@F7=VQPfyXh#7`KIvt1oo(_loYT%=xMk4mVeqE*JhR4^bo~}oYEz9QN zSx-eJh#Knl6p&x6FA@Vnf0)Gw9cZmJ{XvKrUEvpqOIQhLdNu7?Tver z)PPUVAT1*Ke*aq1a0bl0+HyM1IjPHEUjD4K-C)Rq;v+NJ*aWh5->kK= z4-8!a&33yOJ+5}A0|U{E80#*@n-pF-*YCJc-n^%fns}%OA{j915CTOO(}+A4YdLEJ zyX-q1*N?2ZYi5|N3*rN>xy;oXHpJ&OyPUH_fz_hv-BHX791)8Rl}*U>oc z-srH`#u#Iy>2Ub4b_A6bpR4P-PZ<}|{G}2=)T%bi#%{2!dHe64uU>KGA#)UhtV4!6 z4ki$T_cZ&N4!l+>i}rX&<8JpW4f|@wtr1ELCrH~xt*kN4c{_~Jv(=GM&xwn?FJJSt z9+1#0c^2A^o;tdreyha;^e$=B7y+w>aa;|J&U z#6}HnKZG>KaYz6C_dh~P`R&(LpQ2v>qroxMrW*17FwJLvwQh@H1+SlHS;7~1OjEbM zthMs9M8t<7tPT(|3>by8PS*2)(N_tLx}~04y>G_!C3Ra+f076ao1~TqiR>_TJYRR z25$`m*K2;kSQDC|s;e*+hPpfP01MvNvml}t$j_DB4^|u@CEr3>(H_&BZL0dn#AKUu z>7>_4Yik8oy#jf)0Y;S)I-=kEI_l$j=@d-UVI?H7(zsiA0S4nCWgq(ZV-!+;q;Z4R zX&3-YF;WO#BJ0eOHRpO(7^y~`O=F}_iPRE(;yV4-NV`73ZQBYT9`(5oUJepAh@_m} z1!ase^ykli!ef_}xZ21$${Y^+n`?yuV5*5Knpcizp+yp6jDjxT+o&}cT-0sZnGWM9 zD~z$e$p_W5Opy&49p>fP!J17#2u)@^F4lvSg$&8W( z530^K#!%uKT-W590}nNwdy_jt2uJc0XE}{AWcaxs_IueYM?@=O$gb^vEeifE#!XaK z?m#iL%y}MBEaq-XA>dTN^l1a18V4GR-k?|N0G%ppBm| z-e`gza|j(Z3TJ>moSxG@Ob43%Oyjt_8lsD=K!avzJ8Hdca0vA5yj~7?Ym^)gNH7#N zbb~AMiYb75)*WZ@+qQeA-``bp%ZoN^kOtd0t#dT7=J=(x{3;FZdm)@yQzAK9XGzUR z}3?EWt49C~@<-dKiYO!4! zv580|m34-MZUTNz6Ku3r+Z%P%8%1m2En5Aha0t9OznJ2&v|y#YcJEcV9I7+`$N3Qy{t#gvX7u63nd89IoyivDb;@sM;0Zl%kl@+_L3g(l2<|vdfprck}BcHTSP={)OjgcmQ#Zs zkmG_xHNKa1j{2@I+ydUm^^DdJVBBb3B|nQqtoL3fazO4k-dhB%Q<_cL=d$C$Y3x)HTrekU>(c9R9i0hRQ`hx^*gp;X!HgRcNuGJYNPEHgmWY(n zr_x^?!D=>^PS*oROGIU~ry5R~Q9kIjR93ihihqq74~FA;tEo(~g+Pm2MDQ^$S%@_u zhQgp@urQ@WjVd=#qn0fxvHY2iBp*a?A`*=`425X=Cg!29abYF0tRZqvUK_2iX*$Sv z^ud!4{&=sQqd$NCyUUi7r*U5aT~v~1gs zrs*Juyz4p<{KF=Znj)&_%=>;2liSDl$?*(qQGA{YHd;eAcn)zfsXk`YFEqB9Uo?7^_d-OI|kKCcHi?zU~q zQZ*jzkknXBiG5`OTrHFUBl3P;ZQ(S=P@_ZyBdsUX8nuB`=$Ii$q`a1+)8E_kpYu}G zPZO>8VK+Rsm{KZwVEmaN`GhDBd1h-Y8EcN@50-1T#)`3n%_pe2;+=mbQbRC9*7FR* zQ8S!qrQ#Y>q$Mu0``TDbeb=v8h0p5;7&i_M(nRb%hKG(Z%I>hwrvF{vul7t?Yw6FQ z|7gE|mHBc+>xC6YP!iN4hCr~#air9?lKNgdl4xbuuIr^vMpRBQl2f?AqSQc}rlH0b z38{q^8L<`B*ldWJ<6gE#IV()bi6%NIofl>(n8wl@MN=;FS+aaWYoych^MGjve57@4 z(SCbgKh(I5kq9H{vnx?)_Vbrga~Ue&77`*PYPUL#N6P4fCsU1QqLw}IYM%CnQbTxM zEO;+->p^N$O+*nkUSouA+jT_@FoZxIJGFV5j!O!8dj_zH+R=f^d1-x%om=3klhTgI z>j*l}WrRpbr=!G^wU(T9qIvhcexPy37>gi4&g6p^?+ycdPYLzx^q)Z`@4ZCCk5or> zUt9lwOi{L*xH}C|K!47ABm1;HbMURH*7MS`2`-}ccGl5CYaR5I(#m-X155#l=NPrt zDT8nZvJJdXR%pHVbLj?PpoWJ+u*Ky!2^Id6#trpS?ZNT)TiZxJ8v)Pl)1pUAl~E(T z)H|y{=e)-lBq*|(7yH2&fojjwv|6PUyr+PAnUUt4Gf~de_k;ZY7DEj^Zv8%67t(8F z5?GE1!_QGSghi3*bBi1ua6GNEmreBuWvMN9X+(B8P?vQ-#bs!myG+|njL!Q#O*R=^)hh; zU32iDTh~%lK;U;=+FxyfmdM_2%iZn36Xsv>y4I2R24B(H! zv2ondxZ6Fg>QNm3J>I16d+BGcsFAEg4Tjb=W}DB6+NPRPBei=BpikSj!jA`a((^vA z?-uR<(mkl^@YV7HzBgJBLGLufx}M;@bUVY); z9bC`r7aO-GWcYa&(uv*;b~x;%CclMqacx_~>^Cw585&XOGmvVepD^-!sh36o>qRHJ0{44}1H6~$X&-K%=f4y-Fd4=bjoo{9B>NxIX6x93q>W2nB+d>vu zR>rIeEzJfZj?d?PSwIImC&0p=M8tq_0yd4vh7>J(tXAO$)_2c2(_)Hq9*1$Y@Zov= z@|qjQ)Azls;fZRBsH`Izj{CJY7V=%=U=tnpm8}*D5Rr4O&_U~~<>dxi$|%KH7SsKJ zD4tTH!+tL;F%g`!NAW>yc!ANz5TsK8 z{RAHR;jovei>Qsh?|U`0F{V&w=Y}R0gK*YSO7Y>fv$1Uy3leiml(}Ap1eVZmW0aX} zh+1IPlGZ(YUQgpb4Xm}DFu}0o4F-gMlLb}%RCJEGe zSb;n4cAq|6i6wLK-m4we#!$lp8s``&wtGTRq+!7UeD+5&02%hkW%e7>VH(T8DxtFb z`f!xUV!5MR^A4WZKW5wjsfKZ+{r;7FD4_K4g*W+a?TGE;bM$30&0vAg_jzn#LuB;jdo>!0(*E~PvbuCjd`Ck5Zn+0 zEw8UM?skeqF_j)`4AjPW(SZ}z6&p4ptds_>U6D~P>91RBMVk!SN9&yQ(Z8!Mg{)CZ zNfcPxwtF*}16gEbM%WVuQ1Mw;KaKm#SIg1F8&lTY#z2;rwB2Ckwe0F1rhT&U#zbPf5`5I?elvxm2rbE%N zTQDNZ?XPDF{xt5J716CGSJtCWUh6NI(5L&&Pg#+ zUNW`zbK{5|tF`R+uOh@)RA+Wlhu<5|aL!SRjtp}JYALD1VNZUZ$yiGRQ%0YW`f1!Z zJ(O6r>w}lS_pENZOeNy%_pc)96Jnqk%eF_fa3IQ$d1G3ZB00nWo+xluhxsdVKW*F6 z%gZ0BU5SoTL%F-}npwTFM{B1;bYYqf6uhT#+(~Qec|DE$F45ZBAX!r8xsW$pcuIB&#zxkm?oS;IANQ^WZNH_S;&^lWbHyU6WQDIX- zqg!*>Zw+W2_WJ_haReQPQMmHANPm}Qp^1@u%wl7nx>hNDs-ZlM`ynpOR-=|RI=ZsR zy=jcF-4N}&wxq#Mtr)uJfdu-}({IB&Jo+Ggh%?5VNRT2*D5CWt zEidH%O^1Vw&~|MnT5DL*i^Yq#${L>6Gjd<$^4_na7osu@{tZX zOQWe)Bn{q+9=vG`?OtA1d(&3qoKM4k8uw4Qe$rZ3En##x>{p8kF_2*y)vkAC)rN^J z9x+DQ{%IN`qqIQ2wS>~ssGn*1&+;A!vg=P zt!qPm8us&g8uvYKw2IzE5V9A&G6*v+F{~oGfP=^ccmQO{S=eV!Lw;WWOwIi-UbVQt z$T)Q!O@~9-=;>P7WV#Y~d|uD%Y2452dHt^INmqJa&+BR2&+B svn co http://src.chromium.org/svn/trunk/deps/third_party/cygwin@66844 third_party/cygwin + +To run GYP Python is required and it is recommended to use the same version as +is used by the Chromium project. This can also be checked out from the Chromium +repository. From the root of the V8 project do the following: + +> svn co http://src.chromium.org/svn/trunk/tools/third_party/python_26@89111 third_party/python_26 + +Now generate Visual Studio solution and project files for the ia32 architecture: + +> third_party\python_26\python build/gyp_v8 + +Now open build\All.sln in Visual Studio. diff --git a/node-v0.8.14/deps/v8/build/all.gyp b/node-v0.8.14/deps/v8/build/all.gyp new file mode 100644 index 0000000..4b2fe52 --- /dev/null +++ b/node-v0.8.14/deps/v8/build/all.gyp @@ -0,0 +1,19 @@ +# Copyright 2011 the V8 project authors. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +{ + 'targets': [ + { + 'target_name': 'All', + 'type': 'none', + 'dependencies': [ + '../preparser/preparser.gyp:*', + '../samples/samples.gyp:*', + '../src/d8.gyp:d8', + '../test/cctest/cctest.gyp:*', + ], + } + ] +} + diff --git a/node-v0.8.14/deps/v8/build/android.gypi b/node-v0.8.14/deps/v8/build/android.gypi new file mode 100644 index 0000000..ffd0648 --- /dev/null +++ b/node-v0.8.14/deps/v8/build/android.gypi @@ -0,0 +1,225 @@ +# Copyright 2012 the V8 project authors. All rights reserved. +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above +# copyright notice, this list of conditions and the following +# disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of Google Inc. nor the names of its +# contributors may be used to endorse or promote products derived +# from this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +# Definitions for building standalone V8 binaries to run on Android. +# This is mostly excerpted from: +# http://src.chromium.org/viewvc/chrome/trunk/src/build/common.gypi + +{ + 'variables': { + # Location of Android NDK. + 'variables': { + 'variables': { + 'android_ndk_root%': '&1 | grep -q "^Target: mips-" && echo "yes" || echo "no")', + }, + 'conditions': [ + ['mipscompiler=="yes"', { + 'target_conditions': [ + ['_toolset=="target"', { + 'cflags': ['-EL'], + 'ldflags': ['-EL'], + 'conditions': [ + [ 'v8_use_mips_abi_hardfloat=="true"', { + 'cflags': ['-mhard-float'], + 'ldflags': ['-mhard-float'], + }, { + 'cflags': ['-msoft-float'], + 'ldflags': ['-msoft-float'], + }], + ['mips_arch_variant=="mips32r2"', { + 'cflags': ['-mips32r2', '-Wa,-mips32r2'], + }], + ['mips_arch_variant=="loongson"', { + 'cflags': ['-mips3', '-Wa,-mips3'], + }, { + 'cflags': ['-mips32', '-Wa,-mips32'], + }], + ], + }], + ], + }], + [ 'v8_can_use_fpu_instructions=="true"', { + 'defines': [ + 'CAN_USE_FPU_INSTRUCTIONS', + ], + }], + [ 'v8_use_mips_abi_hardfloat=="true"', { + 'defines': [ + '__mips_hard_float=1', + 'CAN_USE_FPU_INSTRUCTIONS', + ], + }, { + 'defines': [ + '__mips_soft_float=1' + ], + }], + ['mips_arch_variant=="mips32r2"', { + 'defines': ['_MIPS_ARCH_MIPS32R2',], + }], + ['mips_arch_variant=="loongson"', { + 'defines': ['_MIPS_ARCH_LOONGSON',], + }], + ], + }], # v8_target_arch=="mips" + ['v8_target_arch=="x64"', { + 'defines': [ + 'V8_TARGET_ARCH_X64', + ], + 'xcode_settings': { + 'ARCHS': [ 'x86_64' ], + }, + 'msvs_settings': { + 'VCLinkerTool': { + 'StackReserveSize': '2097152', + }, + }, + }], # v8_target_arch=="x64" + ['v8_use_liveobjectlist=="true"', { + 'defines': [ + 'ENABLE_DEBUGGER_SUPPORT', + 'INSPECTOR', + 'OBJECT_PRINT', + 'LIVEOBJECTLIST', + ], + }], + ['v8_compress_startup_data=="bz2"', { + 'defines': [ + 'COMPRESS_STARTUP_DATA_BZ2', + ], + }], + ['OS=="win"', { + 'defines': [ + 'WIN32', + ], + 'msvs_configuration_attributes': { + 'OutputDirectory': '<(DEPTH)\\build\\$(ConfigurationName)', + 'IntermediateDirectory': '$(OutDir)\\obj\\$(ProjectName)', + 'CharacterSet': '1', + }, + }], + ['OS=="win" and v8_enable_prof==1', { + 'msvs_settings': { + 'VCLinkerTool': { + 'GenerateMapFile': 'true', + }, + }, + }], + ['OS=="linux" or OS=="freebsd" or OS=="openbsd" or OS=="solaris" \ + or OS=="netbsd"', { + 'conditions': [ + [ 'v8_no_strict_aliasing==1', { + 'cflags': [ '-fno-strict-aliasing' ], + }], + ], # conditions + }], + ['OS=="solaris"', { + 'defines': [ '__C99FEATURES__=1' ], # isinf() etc. + }], + ['(OS=="linux" or OS=="freebsd" or OS=="openbsd" or OS=="solaris" \ + or OS=="netbsd" or OS=="mac" or OS=="android") and \ + (v8_target_arch=="arm" or v8_target_arch=="ia32" or \ + v8_target_arch=="mips")', { + # Check whether the host compiler and target compiler support the + # '-m32' option and set it if so. + 'target_conditions': [ + ['_toolset=="host"', { + 'variables': { + 'm32flag': ' /dev/null 2>&1) && echo "-m32" || true)', + }, + 'cflags': [ '<(m32flag)' ], + 'ldflags': [ '<(m32flag)' ], + 'xcode_settings': { + 'ARCHS': [ 'i386' ], + }, + }], + ['_toolset=="target"', { + 'variables': { + 'm32flag': ' /dev/null 2>&1) && echo "-m32" || true)', + }, + 'cflags': [ '<(m32flag)' ], + 'ldflags': [ '<(m32flag)' ], + 'xcode_settings': { + 'ARCHS': [ 'i386' ], + }, + }], + ], + }], + ['OS=="freebsd" or OS=="openbsd"', { + 'cflags': [ '-I/usr/local/include' ], + }], + ['OS=="netbsd"', { + 'cflags': [ '-I/usr/pkg/include' ], + }], + ], # conditions + 'configurations': { + 'Debug': { + 'defines': [ + 'DEBUG', + 'ENABLE_DISASSEMBLER', + 'V8_ENABLE_CHECKS', + 'OBJECT_PRINT', + ], + 'msvs_settings': { + 'VCCLCompilerTool': { + 'Optimization': '0', + + 'conditions': [ + ['OS=="win" and component=="shared_library"', { + 'RuntimeLibrary': '3', # /MDd + }, { + 'RuntimeLibrary': '1', # /MTd + }], + ], + }, + 'VCLinkerTool': { + 'LinkIncremental': '2', + }, + }, + 'conditions': [ + ['OS=="linux" or OS=="freebsd" or OS=="openbsd" or OS=="netbsd"', { + 'cflags': [ '-Wall', '<(werror)', '-W', '-Wno-unused-parameter', + '-Wnon-virtual-dtor', '-Woverloaded-virtual' ], + }], + ], + }, # Debug + 'Release': { + 'conditions': [ + ['OS=="linux" or OS=="freebsd" or OS=="openbsd" or OS=="netbsd" \ + or OS=="android"', { + 'conditions': [ + [ 'gcc_version==44 and clang==0', { + 'cflags': [ + # Avoid crashes with gcc 4.4 in the v8 test suite. + '-fno-tree-vrp', + ], + }], + ], + }], + ['OS=="mac"', { + 'xcode_settings': { + 'GCC_OPTIMIZATION_LEVEL': '3', # -O3 + + # -fstrict-aliasing. Mainline gcc + # enables this at -O2 and above, + # but Apple gcc does not unless it + # is specified explicitly. + 'GCC_STRICT_ALIASING': 'YES', + }, + }], # OS=="mac" + ['OS=="win"', { + 'msvs_settings': { + 'VCCLCompilerTool': { + 'Optimization': '2', + 'InlineFunctionExpansion': '2', + 'EnableIntrinsicFunctions': 'true', + 'FavorSizeOrSpeed': '0', + 'OmitFramePointers': 'true', + 'StringPooling': 'true', + + 'conditions': [ + ['OS=="win" and component=="shared_library"', { + 'RuntimeLibrary': '2', #/MD + }, { + 'RuntimeLibrary': '0', #/MT + }], + ], + }, + 'VCLinkerTool': { + 'LinkIncremental': '1', + 'OptimizeReferences': '2', + 'EnableCOMDATFolding': '2', + }, + }, + }], # OS=="win" + ], # conditions + }, # Release + }, # configurations + }, # target_defaults +} diff --git a/node-v0.8.14/deps/v8/build/gyp_v8 b/node-v0.8.14/deps/v8/build/gyp_v8 new file mode 100755 index 0000000..345f777 --- /dev/null +++ b/node-v0.8.14/deps/v8/build/gyp_v8 @@ -0,0 +1,169 @@ +#!/usr/bin/python +# +# Copyright 2012 the V8 project authors. All rights reserved. +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above +# copyright notice, this list of conditions and the following +# disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of Google Inc. nor the names of its +# contributors may be used to endorse or promote products derived +# from this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +# This script is wrapper for V8 that adds some support for how GYP +# is invoked by V8 beyond what can be done in the gclient hooks. + +import glob +import os +import shlex +import sys + +script_dir = os.path.dirname(__file__) +v8_root = os.path.normpath(os.path.join(script_dir, os.pardir)) + +if __name__ == '__main__': + os.chdir(v8_root) + script_dir = os.path.dirname(__file__) + v8_root = '.' + +sys.path.insert(0, os.path.join(v8_root, 'tools')) +import utils + +sys.path.insert(0, os.path.join(v8_root, 'build', 'gyp', 'pylib')) +import gyp + + +def apply_gyp_environment(file_path=None): + """ + Reads in a *.gyp_env file and applies the valid keys to os.environ. + """ + if not file_path or not os.path.exists(file_path): + return + file_contents = open(file_path).read() + try: + file_data = eval(file_contents, {'__builtins__': None}, None) + except SyntaxError, e: + e.filename = os.path.abspath(file_path) + raise + supported_vars = ( 'V8_GYP_FILE', + 'V8_GYP_SYNTAX_CHECK', + 'GYP_DEFINES', + 'GYP_GENERATOR_FLAGS', + 'GYP_GENERATOR_OUTPUT', ) + for var in supported_vars: + val = file_data.get(var) + if val: + if var in os.environ: + print 'INFO: Environment value for "%s" overrides value in %s.' % ( + var, os.path.abspath(file_path) + ) + else: + os.environ[var] = val + + +def additional_include_files(args=[]): + """ + Returns a list of additional (.gypi) files to include, without + duplicating ones that are already specified on the command line. + """ + # Determine the include files specified on the command line. + # This doesn't cover all the different option formats you can use, + # but it's mainly intended to avoid duplicating flags on the automatic + # makefile regeneration which only uses this format. + specified_includes = set() + for arg in args: + if arg.startswith('-I') and len(arg) > 2: + specified_includes.add(os.path.realpath(arg[2:])) + + result = [] + def AddInclude(path): + if os.path.realpath(path) not in specified_includes: + result.append(path) + + # Always include standalone.gypi + AddInclude(os.path.join(v8_root, 'build', 'standalone.gypi')) + + # Optionally add supplemental .gypi files if present. + supplements = glob.glob(os.path.join(v8_root, '*', 'supplement.gypi')) + for supplement in supplements: + AddInclude(supplement) + + return result + + +def run_gyp(args): + rc = gyp.main(args) + if rc != 0: + print 'Error running GYP' + sys.exit(rc) + + +if __name__ == '__main__': + args = sys.argv[1:] + + if 'SKIP_V8_GYP_ENV' not in os.environ: + # Update the environment based on v8.gyp_env + gyp_env_path = os.path.join(os.path.dirname(v8_root), 'v8.gyp_env') + apply_gyp_environment(gyp_env_path) + + # This could give false positives since it doesn't actually do real option + # parsing. Oh well. + gyp_file_specified = False + for arg in args: + if arg.endswith('.gyp'): + gyp_file_specified = True + break + + # If we didn't get a file, check an env var, and then fall back to + # assuming 'all.gyp' from the same directory as the script. + if not gyp_file_specified: + gyp_file = os.environ.get('V8_GYP_FILE') + if gyp_file: + # Note that V8_GYP_FILE values can't have backslashes as + # path separators even on Windows due to the use of shlex.split(). + args.extend(shlex.split(gyp_file)) + else: + # Note that this must not start with "./" or things break. + # So we rely on having done os.chdir(v8_root) above and use the + # relative path. + args.append(os.path.join('build', 'all.gyp')) + + args.extend(['-I' + i for i in additional_include_files(args)]) + + # There shouldn't be a circular dependency relationship between .gyp files + args.append('--no-circular-check') + + # Set the GYP DEPTH variable to the root of the V8 project. + args.append('--depth=' + v8_root) + + # If V8_GYP_SYNTAX_CHECK is set to 1, it will invoke gyp with --check + # to enfore syntax checking. + syntax_check = os.environ.get('V8_GYP_SYNTAX_CHECK') + if syntax_check and int(syntax_check): + args.append('--check') + + print 'Updating projects from gyp files...' + sys.stdout.flush() + + # Generate for the architectures supported on the given platform. + gyp_args = list(args) + if utils.GuessOS() == 'linux': + gyp_args.append('--generator-output=out') + run_gyp(gyp_args) diff --git a/node-v0.8.14/deps/v8/build/standalone.gypi b/node-v0.8.14/deps/v8/build/standalone.gypi new file mode 100644 index 0000000..ebdf557 --- /dev/null +++ b/node-v0.8.14/deps/v8/build/standalone.gypi @@ -0,0 +1,217 @@ +# Copyright 2012 the V8 project authors. All rights reserved. +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above +# copyright notice, this list of conditions and the following +# disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of Google Inc. nor the names of its +# contributors may be used to endorse or promote products derived +# from this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +# Definitions to be used when building stand-alone V8 binaries. + +{ + 'variables': { + 'library%': 'static_library', + 'component%': 'static_library', + 'visibility%': 'hidden', + 'msvs_multi_core_compile%': '1', + 'variables': { + 'variables': { + 'variables': { + 'conditions': [ + ['OS=="linux" or OS=="freebsd" or OS=="openbsd" or \ + OS=="netbsd" or OS=="mac"', { + # This handles the Unix platforms we generally deal with. + # Anything else gets passed through, which probably won't work + # very well; such hosts should pass an explicit target_arch + # to gyp. + 'host_arch%': + '= 4) && defined(V8_SHARED) +#define EXPORT __attribute__ ((visibility("default"))) +#else // defined(__GNUC__) && (__GNUC__ >= 4) +#define EXPORT +#endif // defined(__GNUC__) && (__GNUC__ >= 4) + +#endif // _WIN32 + + +/** + * Debugger support for the V8 JavaScript engine. + */ +namespace v8 { + +// Debug events which can occur in the V8 JavaScript engine. +enum DebugEvent { + Break = 1, + Exception = 2, + NewFunction = 3, + BeforeCompile = 4, + AfterCompile = 5, + ScriptCollected = 6, + BreakForCommand = 7 +}; + + +class EXPORT Debug { + public: + /** + * A client object passed to the v8 debugger whose ownership will be taken by + * it. v8 is always responsible for deleting the object. + */ + class ClientData { + public: + virtual ~ClientData() {} + }; + + + /** + * A message object passed to the debug message handler. + */ + class Message { + public: + /** + * Check type of message. + */ + virtual bool IsEvent() const = 0; + virtual bool IsResponse() const = 0; + virtual DebugEvent GetEvent() const = 0; + + /** + * Indicate whether this is a response to a continue command which will + * start the VM running after this is processed. + */ + virtual bool WillStartRunning() const = 0; + + /** + * Access to execution state and event data. Don't store these cross + * callbacks as their content becomes invalid. These objects are from the + * debugger event that started the debug message loop. + */ + virtual Handle GetExecutionState() const = 0; + virtual Handle GetEventData() const = 0; + + /** + * Get the debugger protocol JSON. + */ + virtual Handle GetJSON() const = 0; + + /** + * Get the context active when the debug event happened. Note this is not + * the current active context as the JavaScript part of the debugger is + * running in its own context which is entered at this point. + */ + virtual Handle GetEventContext() const = 0; + + /** + * Client data passed with the corresponding request if any. This is the + * client_data data value passed into Debug::SendCommand along with the + * request that led to the message or NULL if the message is an event. The + * debugger takes ownership of the data and will delete it even if there is + * no message handler. + */ + virtual ClientData* GetClientData() const = 0; + + virtual ~Message() {} + }; + + + /** + * An event details object passed to the debug event listener. + */ + class EventDetails { + public: + /** + * Event type. + */ + virtual DebugEvent GetEvent() const = 0; + + /** + * Access to execution state and event data of the debug event. Don't store + * these cross callbacks as their content becomes invalid. + */ + virtual Handle GetExecutionState() const = 0; + virtual Handle GetEventData() const = 0; + + /** + * Get the context active when the debug event happened. Note this is not + * the current active context as the JavaScript part of the debugger is + * running in its own context which is entered at this point. + */ + virtual Handle GetEventContext() const = 0; + + /** + * Client data passed with the corresponding callback when it was + * registered. + */ + virtual Handle GetCallbackData() const = 0; + + /** + * Client data passed to DebugBreakForCommand function. The + * debugger takes ownership of the data and will delete it even if + * there is no message handler. + */ + virtual ClientData* GetClientData() const = 0; + + virtual ~EventDetails() {} + }; + + + /** + * Debug event callback function. + * + * \param event the type of the debug event that triggered the callback + * (enum DebugEvent) + * \param exec_state execution state (JavaScript object) + * \param event_data event specific data (JavaScript object) + * \param data value passed by the user to SetDebugEventListener + */ + typedef void (*EventCallback)(DebugEvent event, + Handle exec_state, + Handle event_data, + Handle data); + + /** + * Debug event callback function. + * + * \param event_details object providing information about the debug event + * + * A EventCallback2 does not take possession of the event data, + * and must not rely on the data persisting after the handler returns. + */ + typedef void (*EventCallback2)(const EventDetails& event_details); + + /** + * Debug message callback function. + * + * \param message the debug message handler message object + * \param length length of the message + * \param client_data the data value passed when registering the message handler + + * A MessageHandler does not take possession of the message string, + * and must not rely on the data persisting after the handler returns. + * + * This message handler is deprecated. Use MessageHandler2 instead. + */ + typedef void (*MessageHandler)(const uint16_t* message, int length, + ClientData* client_data); + + /** + * Debug message callback function. + * + * \param message the debug message handler message object + * + * A MessageHandler does not take possession of the message data, + * and must not rely on the data persisting after the handler returns. + */ + typedef void (*MessageHandler2)(const Message& message); + + /** + * Debug host dispatch callback function. + */ + typedef void (*HostDispatchHandler)(); + + /** + * Callback function for the host to ensure debug messages are processed. + */ + typedef void (*DebugMessageDispatchHandler)(); + + // Set a C debug event listener. + static bool SetDebugEventListener(EventCallback that, + Handle data = Handle()); + static bool SetDebugEventListener2(EventCallback2 that, + Handle data = Handle()); + + // Set a JavaScript debug event listener. + static bool SetDebugEventListener(v8::Handle that, + Handle data = Handle()); + + // Schedule a debugger break to happen when JavaScript code is run + // in the given isolate. If no isolate is provided the default + // isolate is used. + static void DebugBreak(Isolate* isolate = NULL); + + // Remove scheduled debugger break in given isolate if it has not + // happened yet. If no isolate is provided the default isolate is + // used. + static void CancelDebugBreak(Isolate* isolate = NULL); + + // Break execution of JavaScript in the given isolate (this method + // can be invoked from a non-VM thread) for further client command + // execution on a VM thread. Client data is then passed in + // EventDetails to EventCallback at the moment when the VM actually + // stops. If no isolate is provided the default isolate is used. + static void DebugBreakForCommand(ClientData* data = NULL, + Isolate* isolate = NULL); + + // Message based interface. The message protocol is JSON. NOTE the message + // handler thread is not supported any more parameter must be false. + static void SetMessageHandler(MessageHandler handler, + bool message_handler_thread = false); + static void SetMessageHandler2(MessageHandler2 handler); + + // If no isolate is provided the default isolate is + // used. + static void SendCommand(const uint16_t* command, int length, + ClientData* client_data = NULL, + Isolate* isolate = NULL); + + // Dispatch interface. + static void SetHostDispatchHandler(HostDispatchHandler handler, + int period = 100); + + /** + * Register a callback function to be called when a debug message has been + * received and is ready to be processed. For the debug messages to be + * processed V8 needs to be entered, and in certain embedding scenarios this + * callback can be used to make sure V8 is entered for the debug message to + * be processed. Note that debug messages will only be processed if there is + * a V8 break. This can happen automatically by using the option + * --debugger-auto-break. + * \param provide_locker requires that V8 acquires v8::Locker for you before + * calling handler + */ + static void SetDebugMessageDispatchHandler( + DebugMessageDispatchHandler handler, bool provide_locker = false); + + /** + * Run a JavaScript function in the debugger. + * \param fun the function to call + * \param data passed as second argument to the function + * With this call the debugger is entered and the function specified is called + * with the execution state as the first argument. This makes it possible to + * get access to information otherwise not available during normal JavaScript + * execution e.g. details on stack frames. Receiver of the function call will + * be the debugger context global object, however this is a subject to change. + * The following example shows a JavaScript function which when passed to + * v8::Debug::Call will return the current line of JavaScript execution. + * + * \code + * function frame_source_line(exec_state) { + * return exec_state.frame(0).sourceLine(); + * } + * \endcode + */ + static Local Call(v8::Handle fun, + Handle data = Handle()); + + /** + * Returns a mirror object for the given object. + */ + static Local GetMirror(v8::Handle obj); + + /** + * Enable the V8 builtin debug agent. The debugger agent will listen on the + * supplied TCP/IP port for remote debugger connection. + * \param name the name of the embedding application + * \param port the TCP/IP port to listen on + * \param wait_for_connection whether V8 should pause on a first statement + * allowing remote debugger to connect before anything interesting happened + */ + static bool EnableAgent(const char* name, int port, + bool wait_for_connection = false); + + /** + * Disable the V8 builtin debug agent. The TCP/IP connection will be closed. + */ + static void DisableAgent(); + + /** + * Makes V8 process all pending debug messages. + * + * From V8 point of view all debug messages come asynchronously (e.g. from + * remote debugger) but they all must be handled synchronously: V8 cannot + * do 2 things at one time so normal script execution must be interrupted + * for a while. + * + * Generally when message arrives V8 may be in one of 3 states: + * 1. V8 is running script; V8 will automatically interrupt and process all + * pending messages (however auto_break flag should be enabled); + * 2. V8 is suspended on debug breakpoint; in this state V8 is dedicated + * to reading and processing debug messages; + * 3. V8 is not running at all or has called some long-working C++ function; + * by default it means that processing of all debug messages will be deferred + * until V8 gets control again; however, embedding application may improve + * this by manually calling this method. + * + * It makes sense to call this method whenever a new debug message arrived and + * V8 is not already running. Method v8::Debug::SetDebugMessageDispatchHandler + * should help with the former condition. + * + * Technically this method in many senses is equivalent to executing empty + * script: + * 1. It does nothing except for processing all pending debug messages. + * 2. It should be invoked with the same precautions and from the same context + * as V8 script would be invoked from, because: + * a. with "evaluate" command it can do whatever normal script can do, + * including all native calls; + * b. no other thread should call V8 while this method is running + * (v8::Locker may be used here). + * + * "Evaluate" debug command behavior currently is not specified in scope + * of this method. + */ + static void ProcessDebugMessages(); + + /** + * Debugger is running in its own context which is entered while debugger + * messages are being dispatched. This is an explicit getter for this + * debugger context. Note that the content of the debugger context is subject + * to change. + */ + static Local GetDebugContext(); +}; + + +} // namespace v8 + + +#undef EXPORT + + +#endif // V8_V8_DEBUG_H_ diff --git a/node-v0.8.14/deps/v8/include/v8-preparser.h b/node-v0.8.14/deps/v8/include/v8-preparser.h new file mode 100644 index 0000000..f11d05e --- /dev/null +++ b/node-v0.8.14/deps/v8/include/v8-preparser.h @@ -0,0 +1,117 @@ +// Copyright 2011 the V8 project authors. All rights reserved. +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following +// disclaimer in the documentation and/or other materials provided +// with the distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +#ifndef PREPARSER_H +#define PREPARSER_H + +#include "v8stdint.h" + +#ifdef _WIN32 + +// Setup for Windows DLL export/import. When building the V8 DLL the +// BUILDING_V8_SHARED needs to be defined. When building a program which uses +// the V8 DLL USING_V8_SHARED needs to be defined. When either building the V8 +// static library or building a program which uses the V8 static library neither +// BUILDING_V8_SHARED nor USING_V8_SHARED should be defined. +#if defined(BUILDING_V8_SHARED) && defined(USING_V8_SHARED) +#error both BUILDING_V8_SHARED and USING_V8_SHARED are set - please check the\ + build configuration to ensure that at most one of these is set +#endif + +#ifdef BUILDING_V8_SHARED +#define V8EXPORT __declspec(dllexport) +#elif USING_V8_SHARED +#define V8EXPORT __declspec(dllimport) +#else +#define V8EXPORT +#endif // BUILDING_V8_SHARED + +#else // _WIN32 + +// Setup for Linux shared library export. There is no need to distinguish +// between building or using the V8 shared library, but we should not +// export symbols when we are building a static library. +#if defined(__GNUC__) && (__GNUC__ >= 4) && defined(V8_SHARED) +#define V8EXPORT __attribute__ ((visibility("default"))) +#else // defined(__GNUC__) && (__GNUC__ >= 4) +#define V8EXPORT +#endif // defined(__GNUC__) && (__GNUC__ >= 4) + +#endif // _WIN32 + + +namespace v8 { + +// The result of preparsing is either a stack overflow error, or an opaque +// blob of data that can be passed back into the parser. +class V8EXPORT PreParserData { + public: + PreParserData(size_t size, const uint8_t* data) + : data_(data), size_(size) { } + + // Create a PreParserData value where stack_overflow reports true. + static PreParserData StackOverflow() { return PreParserData(0, NULL); } + + // Whether the pre-parser stopped due to a stack overflow. + // If this is the case, size() and data() should not be used. + bool stack_overflow() { return size_ == 0u; } + + // The size of the data in bytes. + size_t size() const { return size_; } + + // Pointer to the data. + const uint8_t* data() const { return data_; } + + private: + const uint8_t* const data_; + const size_t size_; +}; + + +// Interface for a stream of Unicode characters. +class V8EXPORT UnicodeInputStream { // NOLINT - Thinks V8EXPORT is class name. + public: + virtual ~UnicodeInputStream(); + + // Returns the next Unicode code-point in the input, or a negative value when + // there is no more input in the stream. + virtual int32_t Next() = 0; +}; + + +// Preparse a JavaScript program. The source code is provided as a +// UnicodeInputStream. The max_stack_size limits the amount of stack +// space that the preparser is allowed to use. If the preparser uses +// more stack space than the limit provided, the result's stack_overflow() +// method will return true. Otherwise the result contains preparser +// data that can be used by the V8 parser to speed up parsing. +PreParserData V8EXPORT Preparse(UnicodeInputStream* input, + size_t max_stack_size); + +} // namespace v8. + +#endif // PREPARSER_H diff --git a/node-v0.8.14/deps/v8/include/v8-profiler.h b/node-v0.8.14/deps/v8/include/v8-profiler.h new file mode 100644 index 0000000..cda2463 --- /dev/null +++ b/node-v0.8.14/deps/v8/include/v8-profiler.h @@ -0,0 +1,584 @@ +// Copyright 2010 the V8 project authors. All rights reserved. +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following +// disclaimer in the documentation and/or other materials provided +// with the distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +#ifndef V8_V8_PROFILER_H_ +#define V8_V8_PROFILER_H_ + +#include "v8.h" + +#ifdef _WIN32 +// Setup for Windows DLL export/import. See v8.h in this directory for +// information on how to build/use V8 as a DLL. +#if defined(BUILDING_V8_SHARED) && defined(USING_V8_SHARED) +#error both BUILDING_V8_SHARED and USING_V8_SHARED are set - please check the\ + build configuration to ensure that at most one of these is set +#endif + +#ifdef BUILDING_V8_SHARED +#define V8EXPORT __declspec(dllexport) +#elif USING_V8_SHARED +#define V8EXPORT __declspec(dllimport) +#else +#define V8EXPORT +#endif + +#else // _WIN32 + +// Setup for Linux shared library export. See v8.h in this directory for +// information on how to build/use V8 as shared library. +#if defined(__GNUC__) && (__GNUC__ >= 4) && defined(V8_SHARED) +#define V8EXPORT __attribute__ ((visibility("default"))) +#else // defined(__GNUC__) && (__GNUC__ >= 4) +#define V8EXPORT +#endif // defined(__GNUC__) && (__GNUC__ >= 4) + +#endif // _WIN32 + + +/** + * Profiler support for the V8 JavaScript engine. + */ +namespace v8 { + +typedef uint32_t SnapshotObjectId; + +/** + * CpuProfileNode represents a node in a call graph. + */ +class V8EXPORT CpuProfileNode { + public: + /** Returns function name (empty string for anonymous functions.) */ + Handle GetFunctionName() const; + + /** Returns resource name for script from where the function originates. */ + Handle GetScriptResourceName() const; + + /** + * Returns the number, 1-based, of the line where the function originates. + * kNoLineNumberInfo if no line number information is available. + */ + int GetLineNumber() const; + + /** + * Returns total (self + children) execution time of the function, + * in milliseconds, estimated by samples count. + */ + double GetTotalTime() const; + + /** + * Returns self execution time of the function, in milliseconds, + * estimated by samples count. + */ + double GetSelfTime() const; + + /** Returns the count of samples where function exists. */ + double GetTotalSamplesCount() const; + + /** Returns the count of samples where function was currently executing. */ + double GetSelfSamplesCount() const; + + /** Returns function entry UID. */ + unsigned GetCallUid() const; + + /** Returns child nodes count of the node. */ + int GetChildrenCount() const; + + /** Retrieves a child node by index. */ + const CpuProfileNode* GetChild(int index) const; + + static const int kNoLineNumberInfo = Message::kNoLineNumberInfo; +}; + + +/** + * CpuProfile contains a CPU profile in a form of two call trees: + * - top-down (from main() down to functions that do all the work); + * - bottom-up call graph (in backward direction). + */ +class V8EXPORT CpuProfile { + public: + /** Returns CPU profile UID (assigned by the profiler.) */ + unsigned GetUid() const; + + /** Returns CPU profile title. */ + Handle GetTitle() const; + + /** Returns the root node of the bottom up call tree. */ + const CpuProfileNode* GetBottomUpRoot() const; + + /** Returns the root node of the top down call tree. */ + const CpuProfileNode* GetTopDownRoot() const; + + /** + * Deletes the profile and removes it from CpuProfiler's list. + * All pointers to nodes previously returned become invalid. + * Profiles with the same uid but obtained using different + * security token are not deleted, but become inaccessible + * using FindProfile method. It is embedder's responsibility + * to call Delete on these profiles. + */ + void Delete(); +}; + + +/** + * Interface for controlling CPU profiling. + */ +class V8EXPORT CpuProfiler { + public: + /** + * A note on security tokens usage. As scripts from different + * origins can run inside a single V8 instance, it is possible to + * have functions from different security contexts intermixed in a + * single CPU profile. To avoid exposing function names belonging to + * other contexts, filtering by security token is performed while + * obtaining profiling results. + */ + + /** + * Returns the number of profiles collected (doesn't include + * profiles that are being collected at the moment of call.) + */ + static int GetProfilesCount(); + + /** Returns a profile by index. */ + static const CpuProfile* GetProfile( + int index, + Handle security_token = Handle()); + + /** Returns a profile by uid. */ + static const CpuProfile* FindProfile( + unsigned uid, + Handle security_token = Handle()); + + /** + * Starts collecting CPU profile. Title may be an empty string. It + * is allowed to have several profiles being collected at + * once. Attempts to start collecting several profiles with the same + * title are silently ignored. While collecting a profile, functions + * from all security contexts are included in it. The token-based + * filtering is only performed when querying for a profile. + */ + static void StartProfiling(Handle title); + + /** + * Stops collecting CPU profile with a given title and returns it. + * If the title given is empty, finishes the last profile started. + */ + static const CpuProfile* StopProfiling( + Handle title, + Handle security_token = Handle()); + + /** + * Deletes all existing profiles, also cancelling all profiling + * activity. All previously returned pointers to profiles and their + * contents become invalid after this call. + */ + static void DeleteAllProfiles(); +}; + + +class HeapGraphNode; + + +/** + * HeapSnapshotEdge represents a directed connection between heap + * graph nodes: from retainers to retained nodes. + */ +class V8EXPORT HeapGraphEdge { + public: + enum Type { + kContextVariable = 0, // A variable from a function context. + kElement = 1, // An element of an array. + kProperty = 2, // A named object property. + kInternal = 3, // A link that can't be accessed from JS, + // thus, its name isn't a real property name + // (e.g. parts of a ConsString). + kHidden = 4, // A link that is needed for proper sizes + // calculation, but may be hidden from user. + kShortcut = 5, // A link that must not be followed during + // sizes calculation. + kWeak = 6 // A weak reference (ignored by the GC). + }; + + /** Returns edge type (see HeapGraphEdge::Type). */ + Type GetType() const; + + /** + * Returns edge name. This can be a variable name, an element index, or + * a property name. + */ + Handle GetName() const; + + /** Returns origin node. */ + const HeapGraphNode* GetFromNode() const; + + /** Returns destination node. */ + const HeapGraphNode* GetToNode() const; +}; + + +/** + * HeapGraphNode represents a node in a heap graph. + */ +class V8EXPORT HeapGraphNode { + public: + enum Type { + kHidden = 0, // Hidden node, may be filtered when shown to user. + kArray = 1, // An array of elements. + kString = 2, // A string. + kObject = 3, // A JS object (except for arrays and strings). + kCode = 4, // Compiled code. + kClosure = 5, // Function closure. + kRegExp = 6, // RegExp. + kHeapNumber = 7, // Number stored in the heap. + kNative = 8, // Native object (not from V8 heap). + kSynthetic = 9 // Synthetic object, usualy used for grouping + // snapshot items together. + }; + + /** Returns node type (see HeapGraphNode::Type). */ + Type GetType() const; + + /** + * Returns node name. Depending on node's type this can be the name + * of the constructor (for objects), the name of the function (for + * closures), string value, or an empty string (for compiled code). + */ + Handle GetName() const; + + /** + * Returns node id. For the same heap object, the id remains the same + * across all snapshots. + */ + SnapshotObjectId GetId() const; + + /** Returns node's own size, in bytes. */ + int GetSelfSize() const; + + /** + * Returns node's retained size, in bytes. That is, self + sizes of + * the objects that are reachable only from this object. In other + * words, the size of memory that will be reclaimed having this node + * collected. + */ + int GetRetainedSize() const; + + /** Returns child nodes count of the node. */ + int GetChildrenCount() const; + + /** Retrieves a child by index. */ + const HeapGraphEdge* GetChild(int index) const; + + /** Returns retainer nodes count of the node. */ + int GetRetainersCount() const; + + /** Returns a retainer by index. */ + const HeapGraphEdge* GetRetainer(int index) const; + + /** + * Returns a dominator node. This is the node that participates in every + * path from the snapshot root to the current node. + */ + const HeapGraphNode* GetDominatorNode() const; + + /** + * Finds and returns a value from the heap corresponding to this node, + * if the value is still reachable. + */ + Handle GetHeapValue() const; +}; + + +/** + * HeapSnapshots record the state of the JS heap at some moment. + */ +class V8EXPORT HeapSnapshot { + public: + enum Type { + kFull = 0 // Heap snapshot with all instances and references. + }; + enum SerializationFormat { + kJSON = 0 // See format description near 'Serialize' method. + }; + + /** Returns heap snapshot type. */ + Type GetType() const; + + /** Returns heap snapshot UID (assigned by the profiler.) */ + unsigned GetUid() const; + + /** Returns heap snapshot title. */ + Handle GetTitle() const; + + /** Returns the root node of the heap graph. */ + const HeapGraphNode* GetRoot() const; + + /** Returns a node by its id. */ + const HeapGraphNode* GetNodeById(SnapshotObjectId id) const; + + /** Returns total nodes count in the snapshot. */ + int GetNodesCount() const; + + /** Returns a node by index. */ + const HeapGraphNode* GetNode(int index) const; + + /** Returns a max seen JS object Id. */ + SnapshotObjectId GetMaxSnapshotJSObjectId() const; + + /** + * Deletes the snapshot and removes it from HeapProfiler's list. + * All pointers to nodes, edges and paths previously returned become + * invalid. + */ + void Delete(); + + /** + * Prepare a serialized representation of the snapshot. The result + * is written into the stream provided in chunks of specified size. + * The total length of the serialized snapshot is unknown in + * advance, it can be roughly equal to JS heap size (that means, + * it can be really big - tens of megabytes). + * + * For the JSON format, heap contents are represented as an object + * with the following structure: + * + * { + * snapshot: { + * title: "...", + * uid: nnn, + * meta: { meta-info }, + * node_count: nnn, + * edge_count: nnn + * }, + * nodes: [nodes array], + * edges: [edges array], + * strings: [strings array] + * } + * + * Nodes reference strings, other nodes, and edges by their indexes + * in corresponding arrays. + */ + void Serialize(OutputStream* stream, SerializationFormat format) const; +}; + + +class RetainedObjectInfo; + +/** + * Interface for controlling heap profiling. + */ +class V8EXPORT HeapProfiler { + public: + /** + * Callback function invoked for obtaining RetainedObjectInfo for + * the given JavaScript wrapper object. It is prohibited to enter V8 + * while the callback is running: only getters on the handle and + * GetPointerFromInternalField on the objects are allowed. + */ + typedef RetainedObjectInfo* (*WrapperInfoCallback) + (uint16_t class_id, Handle wrapper); + + /** Returns the number of snapshots taken. */ + static int GetSnapshotsCount(); + + /** Returns a snapshot by index. */ + static const HeapSnapshot* GetSnapshot(int index); + + /** Returns a profile by uid. */ + static const HeapSnapshot* FindSnapshot(unsigned uid); + + /** + * Returns SnapshotObjectId for a heap object referenced by |value| if + * it has been seen by the heap profiler, kUnknownObjectId otherwise. + */ + static SnapshotObjectId GetSnapshotObjectId(Handle value); + + /** + * A constant for invalid SnapshotObjectId. GetSnapshotObjectId will return + * it in case heap profiler cannot find id for the object passed as + * parameter. HeapSnapshot::GetNodeById will always return NULL for such id. + */ + static const SnapshotObjectId kUnknownObjectId = 0; + + /** + * Takes a heap snapshot and returns it. Title may be an empty string. + * See HeapSnapshot::Type for types description. + */ + static const HeapSnapshot* TakeSnapshot( + Handle title, + HeapSnapshot::Type type = HeapSnapshot::kFull, + ActivityControl* control = NULL); + + /** + * Starts tracking of heap objects population statistics. After calling + * this method, all heap objects relocations done by the garbage collector + * are being registered. + */ + static void StartHeapObjectsTracking(); + + /** + * Adds a new time interval entry to the aggregated statistics array. The + * time interval entry contains information on the current heap objects + * population size. The method also updates aggregated statistics and + * reports updates for all previous time intervals via the OutputStream + * object. Updates on each time interval are provided as a stream of the + * HeapStatsUpdate structure instances. + * The return value of the function is the last seen heap object Id. + * + * StartHeapObjectsTracking must be called before the first call to this + * method. + */ + static SnapshotObjectId PushHeapObjectsStats(OutputStream* stream); + + /** + * Stops tracking of heap objects population statistics, cleans up all + * collected data. StartHeapObjectsTracking must be called again prior to + * calling PushHeapObjectsStats next time. + */ + static void StopHeapObjectsTracking(); + + /** + * Deletes all snapshots taken. All previously returned pointers to + * snapshots and their contents become invalid after this call. + */ + static void DeleteAllSnapshots(); + + /** Binds a callback to embedder's class ID. */ + static void DefineWrapperClass( + uint16_t class_id, + WrapperInfoCallback callback); + + /** + * Default value of persistent handle class ID. Must not be used to + * define a class. Can be used to reset a class of a persistent + * handle. + */ + static const uint16_t kPersistentHandleNoClassId = 0; + + /** Returns the number of currently existing persistent handles. */ + static int GetPersistentHandleCount(); + + /** Returns memory used for profiler internal data and snapshots. */ + static size_t GetMemorySizeUsedByProfiler(); +}; + + +/** + * Interface for providing information about embedder's objects + * held by global handles. This information is reported in two ways: + * + * 1. When calling AddObjectGroup, an embedder may pass + * RetainedObjectInfo instance describing the group. To collect + * this information while taking a heap snapshot, V8 calls GC + * prologue and epilogue callbacks. + * + * 2. When a heap snapshot is collected, V8 additionally + * requests RetainedObjectInfos for persistent handles that + * were not previously reported via AddObjectGroup. + * + * Thus, if an embedder wants to provide information about native + * objects for heap snapshots, he can do it in a GC prologue + * handler, and / or by assigning wrapper class ids in the following way: + * + * 1. Bind a callback to class id by calling DefineWrapperClass. + * 2. Call SetWrapperClassId on certain persistent handles. + * + * V8 takes ownership of RetainedObjectInfo instances passed to it and + * keeps them alive only during snapshot collection. Afterwards, they + * are freed by calling the Dispose class function. + */ +class V8EXPORT RetainedObjectInfo { // NOLINT + public: + /** Called by V8 when it no longer needs an instance. */ + virtual void Dispose() = 0; + + /** Returns whether two instances are equivalent. */ + virtual bool IsEquivalent(RetainedObjectInfo* other) = 0; + + /** + * Returns hash value for the instance. Equivalent instances + * must have the same hash value. + */ + virtual intptr_t GetHash() = 0; + + /** + * Returns human-readable label. It must be a null-terminated UTF-8 + * encoded string. V8 copies its contents during a call to GetLabel. + */ + virtual const char* GetLabel() = 0; + + /** + * Returns human-readable group label. It must be a null-terminated UTF-8 + * encoded string. V8 copies its contents during a call to GetGroupLabel. + * Heap snapshot generator will collect all the group names, create + * top level entries with these names and attach the objects to the + * corresponding top level group objects. There is a default + * implementation which is required because embedders don't have their + * own implementation yet. + */ + virtual const char* GetGroupLabel() { return GetLabel(); } + + /** + * Returns element count in case if a global handle retains + * a subgraph by holding one of its nodes. + */ + virtual intptr_t GetElementCount() { return -1; } + + /** Returns embedder's object size in bytes. */ + virtual intptr_t GetSizeInBytes() { return -1; } + + protected: + RetainedObjectInfo() {} + virtual ~RetainedObjectInfo() {} + + private: + RetainedObjectInfo(const RetainedObjectInfo&); + RetainedObjectInfo& operator=(const RetainedObjectInfo&); +}; + + +/** + * A struct for exporting HeapStats data from V8, using "push" model. + * See HeapProfiler::PushHeapObjectsStats. + */ +struct HeapStatsUpdate { + HeapStatsUpdate(uint32_t index, uint32_t count, uint32_t size) + : index(index), count(count), size(size) { } + uint32_t index; // Index of the time interval that was changed. + uint32_t count; // New value of count field for the interval with this index. + uint32_t size; // New value of size field for the interval with this index. +}; + + +} // namespace v8 + + +#undef V8EXPORT + + +#endif // V8_V8_PROFILER_H_ diff --git a/node-v0.8.14/deps/v8/include/v8-testing.h b/node-v0.8.14/deps/v8/include/v8-testing.h new file mode 100644 index 0000000..245f74d --- /dev/null +++ b/node-v0.8.14/deps/v8/include/v8-testing.h @@ -0,0 +1,104 @@ +// Copyright 2010 the V8 project authors. All rights reserved. +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following +// disclaimer in the documentation and/or other materials provided +// with the distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +#ifndef V8_V8_TEST_H_ +#define V8_V8_TEST_H_ + +#include "v8.h" + +#ifdef _WIN32 +// Setup for Windows DLL export/import. See v8.h in this directory for +// information on how to build/use V8 as a DLL. +#if defined(BUILDING_V8_SHARED) && defined(USING_V8_SHARED) +#error both BUILDING_V8_SHARED and USING_V8_SHARED are set - please check the\ + build configuration to ensure that at most one of these is set +#endif + +#ifdef BUILDING_V8_SHARED +#define V8EXPORT __declspec(dllexport) +#elif USING_V8_SHARED +#define V8EXPORT __declspec(dllimport) +#else +#define V8EXPORT +#endif + +#else // _WIN32 + +// Setup for Linux shared library export. See v8.h in this directory for +// information on how to build/use V8 as shared library. +#if defined(__GNUC__) && (__GNUC__ >= 4) && defined(V8_SHARED) +#define V8EXPORT __attribute__ ((visibility("default"))) +#else // defined(__GNUC__) && (__GNUC__ >= 4) +#define V8EXPORT +#endif // defined(__GNUC__) && (__GNUC__ >= 4) + +#endif // _WIN32 + + +/** + * Testing support for the V8 JavaScript engine. + */ +namespace v8 { + +class V8EXPORT Testing { + public: + enum StressType { + kStressTypeOpt, + kStressTypeDeopt + }; + + /** + * Set the type of stressing to do. The default if not set is kStressTypeOpt. + */ + static void SetStressRunType(StressType type); + + /** + * Get the number of runs of a given test that is required to get the full + * stress coverage. + */ + static int GetStressRuns(); + + /** + * Indicate the number of the run which is about to start. The value of run + * should be between 0 and one less than the result from GetStressRuns() + */ + static void PrepareStressRun(int run); + + /** + * Force deoptimization of all functions. + */ + static void DeoptimizeAll(); +}; + + +} // namespace v8 + + +#undef V8EXPORT + + +#endif // V8_V8_TEST_H_ diff --git a/node-v0.8.14/deps/v8/include/v8.h b/node-v0.8.14/deps/v8/include/v8.h new file mode 100644 index 0000000..77ffb38 --- /dev/null +++ b/node-v0.8.14/deps/v8/include/v8.h @@ -0,0 +1,4505 @@ +// Copyright 2012 the V8 project authors. All rights reserved. +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following +// disclaimer in the documentation and/or other materials provided +// with the distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +/** \mainpage V8 API Reference Guide + * + * V8 is Google's open source JavaScript engine. + * + * This set of documents provides reference material generated from the + * V8 header file, include/v8.h. + * + * For other documentation see http://code.google.com/apis/v8/ + */ + +#ifndef V8_H_ +#define V8_H_ + +#include "v8stdint.h" + +#ifdef _WIN32 + +// Setup for Windows DLL export/import. When building the V8 DLL the +// BUILDING_V8_SHARED needs to be defined. When building a program which uses +// the V8 DLL USING_V8_SHARED needs to be defined. When either building the V8 +// static library or building a program which uses the V8 static library neither +// BUILDING_V8_SHARED nor USING_V8_SHARED should be defined. +#if defined(BUILDING_V8_SHARED) && defined(USING_V8_SHARED) +#error both BUILDING_V8_SHARED and USING_V8_SHARED are set - please check the\ + build configuration to ensure that at most one of these is set +#endif + +#ifdef BUILDING_V8_SHARED +#define V8EXPORT __declspec(dllexport) +#elif USING_V8_SHARED +#define V8EXPORT __declspec(dllimport) +#else +#define V8EXPORT +#endif // BUILDING_V8_SHARED + +#else // _WIN32 + +// Setup for Linux shared library export. +#if defined(__GNUC__) && (__GNUC__ >= 4) && defined(V8_SHARED) +#ifdef BUILDING_V8_SHARED +#define V8EXPORT __attribute__ ((visibility("default"))) +#else +#define V8EXPORT +#endif +#else // defined(__GNUC__) && (__GNUC__ >= 4) +#define V8EXPORT +#endif // defined(__GNUC__) && (__GNUC__ >= 4) + +#endif // _WIN32 + +/** + * The v8 JavaScript engine. + */ +namespace v8 { + +class Context; +class String; +class StringObject; +class Value; +class Utils; +class Number; +class NumberObject; +class Object; +class Array; +class Int32; +class Uint32; +class External; +class Primitive; +class Boolean; +class BooleanObject; +class Integer; +class Function; +class Date; +class ImplementationUtilities; +class Signature; +class AccessorSignature; +template class Handle; +template class Local; +template class Persistent; +class FunctionTemplate; +class ObjectTemplate; +class Data; +class AccessorInfo; +class StackTrace; +class StackFrame; +class Isolate; + +namespace internal { + +class Arguments; +class Object; +class Heap; +class HeapObject; +class Isolate; +} + + +// --- Weak Handles --- + + +/** + * A weak reference callback function. + * + * This callback should either explicitly invoke Dispose on |object| if + * V8 wrapper is not needed anymore, or 'revive' it by invocation of MakeWeak. + * + * \param object the weak global object to be reclaimed by the garbage collector + * \param parameter the value passed in when making the weak global object + */ +typedef void (*WeakReferenceCallback)(Persistent object, + void* parameter); + + +// --- Handles --- + +#define TYPE_CHECK(T, S) \ + while (false) { \ + *(static_cast(0)) = static_cast(0); \ + } + +/** + * An object reference managed by the v8 garbage collector. + * + * All objects returned from v8 have to be tracked by the garbage + * collector so that it knows that the objects are still alive. Also, + * because the garbage collector may move objects, it is unsafe to + * point directly to an object. Instead, all objects are stored in + * handles which are known by the garbage collector and updated + * whenever an object moves. Handles should always be passed by value + * (except in cases like out-parameters) and they should never be + * allocated on the heap. + * + * There are two types of handles: local and persistent handles. + * Local handles are light-weight and transient and typically used in + * local operations. They are managed by HandleScopes. Persistent + * handles can be used when storing objects across several independent + * operations and have to be explicitly deallocated when they're no + * longer used. + * + * It is safe to extract the object stored in the handle by + * dereferencing the handle (for instance, to extract the Object* from + * a Handle); the value will still be governed by a handle + * behind the scenes and the same rules apply to these values as to + * their handles. + */ +template class Handle { + public: + /** + * Creates an empty handle. + */ + inline Handle() : val_(0) {} + + /** + * Creates a new handle for the specified value. + */ + inline explicit Handle(T* val) : val_(val) {} + + /** + * Creates a handle for the contents of the specified handle. This + * constructor allows you to pass handles as arguments by value and + * to assign between handles. However, if you try to assign between + * incompatible handles, for instance from a Handle to a + * Handle it will cause a compile-time error. Assigning + * between compatible handles, for instance assigning a + * Handle to a variable declared as Handle, is legal + * because String is a subclass of Value. + */ + template inline Handle(Handle that) + : val_(reinterpret_cast(*that)) { + /** + * This check fails when trying to convert between incompatible + * handles. For example, converting from a Handle to a + * Handle. + */ + TYPE_CHECK(T, S); + } + + /** + * Returns true if the handle is empty. + */ + inline bool IsEmpty() const { return val_ == 0; } + + /** + * Sets the handle to be empty. IsEmpty() will then return true. + */ + inline void Clear() { val_ = 0; } + + inline T* operator->() const { return val_; } + + inline T* operator*() const { return val_; } + + /** + * Checks whether two handles are the same. + * Returns true if both are empty, or if the objects + * to which they refer are identical. + * The handles' references are not checked. + */ + template inline bool operator==(Handle that) const { + internal::Object** a = reinterpret_cast(**this); + internal::Object** b = reinterpret_cast(*that); + if (a == 0) return b == 0; + if (b == 0) return false; + return *a == *b; + } + + /** + * Checks whether two handles are different. + * Returns true if only one of the handles is empty, or if + * the objects to which they refer are different. + * The handles' references are not checked. + */ + template inline bool operator!=(Handle that) const { + return !operator==(that); + } + + template static inline Handle Cast(Handle that) { +#ifdef V8_ENABLE_CHECKS + // If we're going to perform the type check then we have to check + // that the handle isn't empty before doing the checked cast. + if (that.IsEmpty()) return Handle(); +#endif + return Handle(T::Cast(*that)); + } + + template inline Handle As() { + return Handle::Cast(*this); + } + + private: + T* val_; +}; + + +/** + * A light-weight stack-allocated object handle. All operations + * that return objects from within v8 return them in local handles. They + * are created within HandleScopes, and all local handles allocated within a + * handle scope are destroyed when the handle scope is destroyed. Hence it + * is not necessary to explicitly deallocate local handles. + */ +template class Local : public Handle { + public: + inline Local(); + template inline Local(Local that) + : Handle(reinterpret_cast(*that)) { + /** + * This check fails when trying to convert between incompatible + * handles. For example, converting from a Handle to a + * Handle. + */ + TYPE_CHECK(T, S); + } + template inline Local(S* that) : Handle(that) { } + template static inline Local Cast(Local that) { +#ifdef V8_ENABLE_CHECKS + // If we're going to perform the type check then we have to check + // that the handle isn't empty before doing the checked cast. + if (that.IsEmpty()) return Local(); +#endif + return Local(T::Cast(*that)); + } + + template inline Local As() { + return Local::Cast(*this); + } + + /** Create a local handle for the content of another handle. + * The referee is kept alive by the local handle even when + * the original handle is destroyed/disposed. + */ + inline static Local New(Handle that); +}; + + +/** + * An object reference that is independent of any handle scope. Where + * a Local handle only lives as long as the HandleScope in which it was + * allocated, a Persistent handle remains valid until it is explicitly + * disposed. + * + * A persistent handle contains a reference to a storage cell within + * the v8 engine which holds an object value and which is updated by + * the garbage collector whenever the object is moved. A new storage + * cell can be created using Persistent::New and existing handles can + * be disposed using Persistent::Dispose. Since persistent handles + * are passed by value you may have many persistent handle objects + * that point to the same storage cell. For instance, if you pass a + * persistent handle as an argument to a function you will not get two + * different storage cells but rather two references to the same + * storage cell. + */ +template class Persistent : public Handle { + public: + /** + * Creates an empty persistent handle that doesn't point to any + * storage cell. + */ + inline Persistent(); + + /** + * Creates a persistent handle for the same storage cell as the + * specified handle. This constructor allows you to pass persistent + * handles as arguments by value and to assign between persistent + * handles. However, attempting to assign between incompatible + * persistent handles, for instance from a Persistent to a + * Persistent will cause a compile-time error. Assigning + * between compatible persistent handles, for instance assigning a + * Persistent to a variable declared as Persistent, + * is allowed as String is a subclass of Value. + */ + template inline Persistent(Persistent that) + : Handle(reinterpret_cast(*that)) { + /** + * This check fails when trying to convert between incompatible + * handles. For example, converting from a Handle to a + * Handle. + */ + TYPE_CHECK(T, S); + } + + template inline Persistent(S* that) : Handle(that) { } + + /** + * "Casts" a plain handle which is known to be a persistent handle + * to a persistent handle. + */ + template explicit inline Persistent(Handle that) + : Handle(*that) { } + + template static inline Persistent Cast(Persistent that) { +#ifdef V8_ENABLE_CHECKS + // If we're going to perform the type check then we have to check + // that the handle isn't empty before doing the checked cast. + if (that.IsEmpty()) return Persistent(); +#endif + return Persistent(T::Cast(*that)); + } + + template inline Persistent As() { + return Persistent::Cast(*this); + } + + /** + * Creates a new persistent handle for an existing local or + * persistent handle. + */ + inline static Persistent New(Handle that); + + /** + * Releases the storage cell referenced by this persistent handle. + * Does not remove the reference to the cell from any handles. + * This handle's reference, and any other references to the storage + * cell remain and IsEmpty will still return false. + */ + inline void Dispose(); + + /** + * Make the reference to this object weak. When only weak handles + * refer to the object, the garbage collector will perform a + * callback to the given V8::WeakReferenceCallback function, passing + * it the object reference and the given parameters. + */ + inline void MakeWeak(void* parameters, WeakReferenceCallback callback); + + /** Clears the weak reference to this object.*/ + inline void ClearWeak(); + + /** + * Marks the reference to this object independent. Garbage collector + * is free to ignore any object groups containing this object. + * Weak callback for an independent handle should not + * assume that it will be preceded by a global GC prologue callback + * or followed by a global GC epilogue callback. + */ + inline void MarkIndependent(); + + /** + *Checks if the handle holds the only reference to an object. + */ + inline bool IsNearDeath() const; + + /** + * Returns true if the handle's reference is weak. + */ + inline bool IsWeak() const; + + /** + * Assigns a wrapper class ID to the handle. See RetainedObjectInfo + * interface description in v8-profiler.h for details. + */ + inline void SetWrapperClassId(uint16_t class_id); + + private: + friend class ImplementationUtilities; + friend class ObjectTemplate; +}; + + + /** + * A stack-allocated class that governs a number of local handles. + * After a handle scope has been created, all local handles will be + * allocated within that handle scope until either the handle scope is + * deleted or another handle scope is created. If there is already a + * handle scope and a new one is created, all allocations will take + * place in the new handle scope until it is deleted. After that, + * new handles will again be allocated in the original handle scope. + * + * After the handle scope of a local handle has been deleted the + * garbage collector will no longer track the object stored in the + * handle and may deallocate it. The behavior of accessing a handle + * for which the handle scope has been deleted is undefined. + */ +class V8EXPORT HandleScope { + public: + HandleScope(); + + ~HandleScope(); + + /** + * Closes the handle scope and returns the value as a handle in the + * previous scope, which is the new current scope after the call. + */ + template Local Close(Handle value); + + /** + * Counts the number of allocated handles. + */ + static int NumberOfHandles(); + + /** + * Creates a new handle with the given value. + */ + static internal::Object** CreateHandle(internal::Object* value); + // Faster version, uses HeapObject to obtain the current Isolate. + static internal::Object** CreateHandle(internal::HeapObject* value); + + private: + // Make it impossible to create heap-allocated or illegal handle + // scopes by disallowing certain operations. + HandleScope(const HandleScope&); + void operator=(const HandleScope&); + void* operator new(size_t size); + void operator delete(void*, size_t); + + // This Data class is accessible internally as HandleScopeData through a + // typedef in the ImplementationUtilities class. + class V8EXPORT Data { + public: + internal::Object** next; + internal::Object** limit; + int level; + inline void Initialize() { + next = limit = NULL; + level = 0; + } + }; + + void Leave(); + + internal::Isolate* isolate_; + internal::Object** prev_next_; + internal::Object** prev_limit_; + + // Allow for the active closing of HandleScopes which allows to pass a handle + // from the HandleScope being closed to the next top most HandleScope. + bool is_closed_; + internal::Object** RawClose(internal::Object** value); + + friend class ImplementationUtilities; +}; + + +// --- Special objects --- + + +/** + * The superclass of values and API object templates. + */ +class V8EXPORT Data { + private: + Data(); +}; + + +/** + * Pre-compilation data that can be associated with a script. This + * data can be calculated for a script in advance of actually + * compiling it, and can be stored between compilations. When script + * data is given to the compile method compilation will be faster. + */ +class V8EXPORT ScriptData { // NOLINT + public: + virtual ~ScriptData() { } + + /** + * Pre-compiles the specified script (context-independent). + * + * \param input Pointer to UTF-8 script source code. + * \param length Length of UTF-8 script source code. + */ + static ScriptData* PreCompile(const char* input, int length); + + /** + * Pre-compiles the specified script (context-independent). + * + * NOTE: Pre-compilation using this method cannot happen on another thread + * without using Lockers. + * + * \param source Script source code. + */ + static ScriptData* PreCompile(Handle source); + + /** + * Load previous pre-compilation data. + * + * \param data Pointer to data returned by a call to Data() of a previous + * ScriptData. Ownership is not transferred. + * \param length Length of data. + */ + static ScriptData* New(const char* data, int length); + + /** + * Returns the length of Data(). + */ + virtual int Length() = 0; + + /** + * Returns a serialized representation of this ScriptData that can later be + * passed to New(). NOTE: Serialized data is platform-dependent. + */ + virtual const char* Data() = 0; + + /** + * Returns true if the source code could not be parsed. + */ + virtual bool HasError() = 0; +}; + + +/** + * The origin, within a file, of a script. + */ +class ScriptOrigin { + public: + inline ScriptOrigin( + Handle resource_name, + Handle resource_line_offset = Handle(), + Handle resource_column_offset = Handle()) + : resource_name_(resource_name), + resource_line_offset_(resource_line_offset), + resource_column_offset_(resource_column_offset) { } + inline Handle ResourceName() const; + inline Handle ResourceLineOffset() const; + inline Handle ResourceColumnOffset() const; + private: + Handle resource_name_; + Handle resource_line_offset_; + Handle resource_column_offset_; +}; + + +/** + * A compiled JavaScript script. + */ +class V8EXPORT Script { + public: + /** + * Compiles the specified script (context-independent). + * + * \param source Script source code. + * \param origin Script origin, owned by caller, no references are kept + * when New() returns + * \param pre_data Pre-parsing data, as obtained by ScriptData::PreCompile() + * using pre_data speeds compilation if it's done multiple times. + * Owned by caller, no references are kept when New() returns. + * \param script_data Arbitrary data associated with script. Using + * this has same effect as calling SetData(), but allows data to be + * available to compile event handlers. + * \return Compiled script object (context independent; when run it + * will use the currently entered context). + */ + static Local + + + + + + + diff --git a/node-v0.8.14/doc/api/_toc.html b/node-v0.8.14/doc/api/_toc.html new file mode 100644 index 0000000..2dbadb5 --- /dev/null +++ b/node-v0.8.14/doc/api/_toc.html @@ -0,0 +1,124 @@ + + + + + Node.js v0.8.14 Manual & Documentation + + + + + +
+ + + +
+ + + + + + + + + + diff --git a/node-v0.8.14/doc/api/_toc.json b/node-v0.8.14/doc/api/_toc.json new file mode 100644 index 0000000..80c461e --- /dev/null +++ b/node-v0.8.14/doc/api/_toc.json @@ -0,0 +1,372 @@ +{ + "source": "doc/api/_toc.markdown", + "desc": [ + { + "type": "list_start", + "ordered": false + }, + { + "type": "list_item_start" + }, + { + "type": "text", + "text": "[About these Docs](documentation.html)" + }, + { + "type": "list_item_end" + }, + { + "type": "list_item_start" + }, + { + "type": "text", + "text": "[Synopsis](synopsis.html)" + }, + { + "type": "list_item_end" + }, + { + "type": "list_item_start" + }, + { + "type": "text", + "text": "[Assertion Testing](assert.html)" + }, + { + "type": "list_item_end" + }, + { + "type": "list_item_start" + }, + { + "type": "text", + "text": "[Buffer](buffer.html)" + }, + { + "type": "list_item_end" + }, + { + "type": "list_item_start" + }, + { + "type": "text", + "text": "[C/C++ Addons](addons.html)" + }, + { + "type": "list_item_end" + }, + { + "type": "list_item_start" + }, + { + "type": "text", + "text": "[Child Processes](child_process.html)" + }, + { + "type": "list_item_end" + }, + { + "type": "list_item_start" + }, + { + "type": "text", + "text": "[Cluster](cluster.html)" + }, + { + "type": "list_item_end" + }, + { + "type": "list_item_start" + }, + { + "type": "text", + "text": "[Crypto](crypto.html)" + }, + { + "type": "list_item_end" + }, + { + "type": "list_item_start" + }, + { + "type": "text", + "text": "[Debugger](debugger.html)" + }, + { + "type": "list_item_end" + }, + { + "type": "list_item_start" + }, + { + "type": "text", + "text": "[DNS](dns.html)" + }, + { + "type": "list_item_end" + }, + { + "type": "list_item_start" + }, + { + "type": "text", + "text": "[Domain](domain.html)" + }, + { + "type": "list_item_end" + }, + { + "type": "list_item_start" + }, + { + "type": "text", + "text": "[Events](events.html)" + }, + { + "type": "list_item_end" + }, + { + "type": "list_item_start" + }, + { + "type": "text", + "text": "[File System](fs.html)" + }, + { + "type": "list_item_end" + }, + { + "type": "list_item_start" + }, + { + "type": "text", + "text": "[Globals](globals.html)" + }, + { + "type": "list_item_end" + }, + { + "type": "list_item_start" + }, + { + "type": "text", + "text": "[HTTP](http.html)" + }, + { + "type": "list_item_end" + }, + { + "type": "list_item_start" + }, + { + "type": "text", + "text": "[HTTPS](https.html)" + }, + { + "type": "list_item_end" + }, + { + "type": "list_item_start" + }, + { + "type": "text", + "text": "[Modules](modules.html)" + }, + { + "type": "list_item_end" + }, + { + "type": "list_item_start" + }, + { + "type": "text", + "text": "[Net](net.html)" + }, + { + "type": "list_item_end" + }, + { + "type": "list_item_start" + }, + { + "type": "text", + "text": "[OS](os.html)" + }, + { + "type": "list_item_end" + }, + { + "type": "list_item_start" + }, + { + "type": "text", + "text": "[Path](path.html)" + }, + { + "type": "list_item_end" + }, + { + "type": "list_item_start" + }, + { + "type": "text", + "text": "[Process](process.html)" + }, + { + "type": "list_item_end" + }, + { + "type": "list_item_start" + }, + { + "type": "text", + "text": "[Punycode](punycode.html)" + }, + { + "type": "list_item_end" + }, + { + "type": "list_item_start" + }, + { + "type": "text", + "text": "[Query Strings](querystring.html)" + }, + { + "type": "list_item_end" + }, + { + "type": "list_item_start" + }, + { + "type": "text", + "text": "[Readline](readline.html)" + }, + { + "type": "list_item_end" + }, + { + "type": "list_item_start" + }, + { + "type": "text", + "text": "[REPL](repl.html)" + }, + { + "type": "list_item_end" + }, + { + "type": "list_item_start" + }, + { + "type": "text", + "text": "[STDIO](stdio.html)" + }, + { + "type": "list_item_end" + }, + { + "type": "list_item_start" + }, + { + "type": "text", + "text": "[Stream](stream.html)" + }, + { + "type": "list_item_end" + }, + { + "type": "list_item_start" + }, + { + "type": "text", + "text": "[String Decoder](string_decoder.html)" + }, + { + "type": "list_item_end" + }, + { + "type": "list_item_start" + }, + { + "type": "text", + "text": "[Timers](timers.html)" + }, + { + "type": "list_item_end" + }, + { + "type": "list_item_start" + }, + { + "type": "text", + "text": "[TLS/SSL](tls.html)" + }, + { + "type": "list_item_end" + }, + { + "type": "list_item_start" + }, + { + "type": "text", + "text": "[TTY](tty.html)" + }, + { + "type": "list_item_end" + }, + { + "type": "list_item_start" + }, + { + "type": "text", + "text": "[UDP/Datagram](dgram.html)" + }, + { + "type": "list_item_end" + }, + { + "type": "list_item_start" + }, + { + "type": "text", + "text": "[URL](url.html)" + }, + { + "type": "list_item_end" + }, + { + "type": "list_item_start" + }, + { + "type": "text", + "text": "[Utilities](util.html)" + }, + { + "type": "list_item_end" + }, + { + "type": "list_item_start" + }, + { + "type": "text", + "text": "[VM](vm.html)" + }, + { + "type": "list_item_end" + }, + { + "type": "list_item_start" + }, + { + "type": "text", + "text": "[ZLIB](zlib.html)" + }, + { + "type": "list_item_end" + }, + { + "type": "list_end" + } + ] +} diff --git a/node-v0.8.14/doc/api/_toc.markdown b/node-v0.8.14/doc/api/_toc.markdown new file mode 100644 index 0000000..9f65868 --- /dev/null +++ b/node-v0.8.14/doc/api/_toc.markdown @@ -0,0 +1,36 @@ +* [About these Docs](documentation.html) +* [Synopsis](synopsis.html) +* [Assertion Testing](assert.html) +* [Buffer](buffer.html) +* [C/C++ Addons](addons.html) +* [Child Processes](child_process.html) +* [Cluster](cluster.html) +* [Crypto](crypto.html) +* [Debugger](debugger.html) +* [DNS](dns.html) +* [Domain](domain.html) +* [Events](events.html) +* [File System](fs.html) +* [Globals](globals.html) +* [HTTP](http.html) +* [HTTPS](https.html) +* [Modules](modules.html) +* [Net](net.html) +* [OS](os.html) +* [Path](path.html) +* [Process](process.html) +* [Punycode](punycode.html) +* [Query Strings](querystring.html) +* [Readline](readline.html) +* [REPL](repl.html) +* [STDIO](stdio.html) +* [Stream](stream.html) +* [String Decoder](string_decoder.html) +* [Timers](timers.html) +* [TLS/SSL](tls.html) +* [TTY](tty.html) +* [UDP/Datagram](dgram.html) +* [URL](url.html) +* [Utilities](util.html) +* [VM](vm.html) +* [ZLIB](zlib.html) diff --git a/node-v0.8.14/doc/api/addons.html b/node-v0.8.14/doc/api/addons.html new file mode 100644 index 0000000..c3a7a66 --- /dev/null +++ b/node-v0.8.14/doc/api/addons.html @@ -0,0 +1,721 @@ + + + + + Addons Node.js v0.8.14 Manual & Documentation + + + + + +
+ + + +
+
+ + +
+
+

Node.js v0.8.14 Manual & Documentation

+ +
+
+ + + +
+

Addons#

+

Addons are dynamically linked shared objects. They can provide glue to C and +C++ libraries. The API (at the moment) is rather complex, involving +knowledge of several libraries: + +

+
    +
  • V8 JavaScript, a C++ library. Used for interfacing with JavaScript: +creating objects, calling functions, etc. Documented mostly in the +v8.h header file (deps/v8/include/v8.h in the Node source tree), +which is also available online.

    +
  • +
  • libuv, C event loop library. Anytime one +needs to wait for a file descriptor to become readable, wait for a timer, or +wait for a signal to received one will need to interface with libuv. That is, +if you perform any I/O, libuv will need to be used.

    +
  • +
  • Internal Node libraries. Most importantly is the node::ObjectWrap +class which you will likely want to derive from.

    +
  • +
  • Others. Look in deps/ for what else is available.

    +
  • +
+

Node statically compiles all its dependencies into the executable. When +compiling your module, you don't need to worry about linking to any of these +libraries. + + +

+

Hello world#

+

To get started let's make a small Addon which is the C++ equivalent of +the following JavaScript code: + +

+
exports.hello = function() { return 'world'; };
+

First we create a file hello.cc: + +

+
#include <node.h>
+#include <v8.h>
+
+using namespace v8;
+
+Handle<Value> Method(const Arguments& args) {
+  HandleScope scope;
+  return scope.Close(String::New("world"));
+}
+
+void init(Handle<Object> target) {
+  target->Set(String::NewSymbol("hello"),
+      FunctionTemplate::New(Method)->GetFunction());
+}
+NODE_MODULE(hello, init)
+

Note that all Node addons must export an initialization function: + +

+
void Initialize (Handle<Object> target);
+NODE_MODULE(module_name, Initialize)
+

There is no semi-colon after NODE_MODULE as it's not a function (see node.h). + +

+

The module_name needs to match the filename of the final binary (minus the +.node suffix). + +

+

The source code needs to be built into hello.node, the binary Addon. To +do this we create a file called binding.gyp which describes the configuration +to build your module in a JSON-like format. This file gets compiled by +node-gyp. + +

+
{
+  "targets": [
+    {
+      "target_name": "hello",
+      "sources": [ "hello.cc" ]
+    }
+  ]
+}
+

The next step is to generate the appropriate project build files for the +current platform. Use node-gyp configure for that. + +

+

Now you will have either a Makefile (on Unix platforms) or a vcxproj file +(on Windows) in the build/ directory. Next invoke the node-gyp build +command. + +

+

Now you have your compiled .node bindings file! The compiled bindings end up +in build/Release/. + +

+

You can now use the binary addon in a Node project hello.js by pointing require to +the recently built hello.node module: + +

+
var addon = require('./build/Release/hello');
+
+console.log(addon.hello()); // 'world'
+

Please see patterns below for further information or +

+

https://github.com/arturadib/node-qt for an example in production. + + +

+

Addon patterns#

+

Below are some addon patterns to help you get started. Consult the online +v8 reference for help with the various v8 +calls, and v8's Embedder's Guide +for an explanation of several concepts used such as handles, scopes, +function templates, etc. + +

+

In order to use these examples you need to compile them using node-gyp. +Create the following binding.gyp file: + +

+
{
+  "targets": [
+    {
+      "target_name": "addon",
+      "sources": [ "addon.cc" ]
+    }
+  ]
+}
+

In cases where there is more than one .cc file, simply add the file name to the +sources array, e.g.: + +

+
"sources": ["addon.cc", "myexample.cc"]
+

Now that you have your binding.gyp ready, you can configure and build the +addon: + +

+
$ node-gyp configure build
+

Function arguments#

+

The following pattern illustrates how to read arguments from JavaScript +function calls and return a result. This is the main and only needed source +addon.cc: + +

+
#define BUILDING_NODE_EXTENSION
+#include <node.h>
+
+using namespace v8;
+
+Handle<Value> Add(const Arguments& args) {
+  HandleScope scope;
+
+  if (args.Length() < 2) {
+    ThrowException(Exception::TypeError(String::New("Wrong number of arguments")));
+    return scope.Close(Undefined());
+  }
+
+  if (!args[0]->IsNumber() || !args[1]->IsNumber()) {
+    ThrowException(Exception::TypeError(String::New("Wrong arguments")));
+    return scope.Close(Undefined());
+  }
+
+  Local<Number> num = Number::New(args[0]->NumberValue() +
+      args[1]->NumberValue());
+  return scope.Close(num);
+}
+
+void Init(Handle<Object> target) {
+  target->Set(String::NewSymbol("add"),
+      FunctionTemplate::New(Add)->GetFunction());
+}
+
+NODE_MODULE(addon, Init)
+

You can test it with the following JavaScript snippet: + +

+
var addon = require('./build/Release/addon');
+
+console.log( 'This should be eight:', addon.add(3,5) );
+

Callbacks#

+

You can pass JavaScript functions to a C++ function and execute them from +there. Here's addon.cc: + +

+
#define BUILDING_NODE_EXTENSION
+#include <node.h>
+
+using namespace v8;
+
+Handle<Value> RunCallback(const Arguments& args) {
+  HandleScope scope;
+
+  Local<Function> cb = Local<Function>::Cast(args[0]);
+  const unsigned argc = 1;
+  Local<Value> argv[argc] = { Local<Value>::New(String::New("hello world")) };
+  cb->Call(Context::GetCurrent()->Global(), argc, argv);
+
+  return scope.Close(Undefined());
+}
+
+void Init(Handle<Object> target) {
+  target->Set(String::NewSymbol("runCallback"),
+      FunctionTemplate::New(RunCallback)->GetFunction());
+}
+
+NODE_MODULE(addon, Init)
+

To test it run the following JavaScript snippet: + +

+
var addon = require('./build/Release/addon');
+
+addon.runCallback(function(msg){
+  console.log(msg); // 'hello world'
+});
+

Object factory#

+

You can create and return new objects from within a C++ function with this +addon.cc pattern, which returns an object with property msg that echoes +the string passed to createObject(): + +

+
#define BUILDING_NODE_EXTENSION
+#include <node.h>
+
+using namespace v8;
+
+Handle<Value> CreateObject(const Arguments& args) {
+  HandleScope scope;
+
+  Local<Object> obj = Object::New();
+  obj->Set(String::NewSymbol("msg"), args[0]->ToString());
+
+  return scope.Close(obj);
+}
+
+void Init(Handle<Object> target) {
+  target->Set(String::NewSymbol("createObject"),
+      FunctionTemplate::New(CreateObject)->GetFunction());
+}
+
+NODE_MODULE(addon, Init)
+

To test it in JavaScript: + +

+
var addon = require('./build/Release/addon');
+
+var obj1 = addon.createObject('hello');
+var obj2 = addon.createObject('world');
+console.log(obj1.msg+' '+obj2.msg); // 'hello world'
+

Function factory#

+

This pattern illustrates how to create and return a JavaScript function that +wraps a C++ function: + +

+
#define BUILDING_NODE_EXTENSION
+#include <node.h>
+
+using namespace v8;
+
+Handle<Value> MyFunction(const Arguments& args) {
+  HandleScope scope;
+  return scope.Close(String::New("hello world"));
+}
+
+Handle<Value> CreateFunction(const Arguments& args) {
+  HandleScope scope;
+
+  Local<FunctionTemplate> tpl = FunctionTemplate::New(MyFunction);
+  Local<Function> fn = tpl->GetFunction();
+  fn->SetName(String::NewSymbol("theFunction")); // omit this to make it anonymous
+
+  return scope.Close(fn);
+}
+
+void Init(Handle<Object> target) {
+  target->Set(String::NewSymbol("createFunction"),
+      FunctionTemplate::New(CreateFunction)->GetFunction());
+}
+
+NODE_MODULE(addon, Init)
+

To test: + +

+
var addon = require('./build/Release/addon');
+
+var fn = addon.createFunction();
+console.log(fn()); // 'hello world'
+

Wrapping C++ objects#

+

Here we will create a wrapper for a C++ object/class MyObject that can be +instantiated in JavaScript through the new operator. First prepare the main +module addon.cc: + +

+
#define BUILDING_NODE_EXTENSION
+#include <node.h>
+#include "myobject.h"
+
+using namespace v8;
+
+void InitAll(Handle<Object> target) {
+  MyObject::Init(target);
+}
+
+NODE_MODULE(addon, InitAll)
+

Then in myobject.h make your wrapper inherit from node::ObjectWrap: + +

+
#ifndef MYOBJECT_H
+#define MYOBJECT_H
+
+#include <node.h>
+
+class MyObject : public node::ObjectWrap {
+ public:
+  static void Init(v8::Handle<v8::Object> target);
+
+ private:
+  MyObject();
+  ~MyObject();
+
+  static v8::Handle<v8::Value> New(const v8::Arguments& args);
+  static v8::Handle<v8::Value> PlusOne(const v8::Arguments& args);
+  double counter_;
+};
+
+#endif
+

And in myobject.cc implement the various methods that you want to expose. +Here we expose the method plusOne by adding it to the constructor's +prototype: + +

+
#define BUILDING_NODE_EXTENSION
+#include <node.h>
+#include "myobject.h"
+
+using namespace v8;
+
+MyObject::MyObject() {};
+MyObject::~MyObject() {};
+
+void MyObject::Init(Handle<Object> target) {
+  // Prepare constructor template
+  Local<FunctionTemplate> tpl = FunctionTemplate::New(New);
+  tpl->SetClassName(String::NewSymbol("MyObject"));
+  tpl->InstanceTemplate()->SetInternalFieldCount(1);
+  // Prototype
+  tpl->PrototypeTemplate()->Set(String::NewSymbol("plusOne"),
+      FunctionTemplate::New(PlusOne)->GetFunction());
+
+  Persistent<Function> constructor = Persistent<Function>::New(tpl->GetFunction());
+  target->Set(String::NewSymbol("MyObject"), constructor);
+}
+
+Handle<Value> MyObject::New(const Arguments& args) {
+  HandleScope scope;
+
+  MyObject* obj = new MyObject();
+  obj->counter_ = args[0]->IsUndefined() ? 0 : args[0]->NumberValue();
+  obj->Wrap(args.This());
+
+  return args.This();
+}
+
+Handle<Value> MyObject::PlusOne(const Arguments& args) {
+  HandleScope scope;
+
+  MyObject* obj = ObjectWrap::Unwrap<MyObject>(args.This());
+  obj->counter_ += 1;
+
+  return scope.Close(Number::New(obj->counter_));
+}
+

Test it with: + +

+
var addon = require('./build/Release/addon');
+
+var obj = new addon.MyObject(10);
+console.log( obj.plusOne() ); // 11
+console.log( obj.plusOne() ); // 12
+console.log( obj.plusOne() ); // 13
+

Factory of wrapped objects#

+

This is useful when you want to be able to create native objects without +explicitly instantiating them with the new operator in JavaScript, e.g. + +

+
var obj = addon.createObject();
+// instead of:
+// var obj = new addon.Object();
+

Let's register our createObject method in addon.cc: + +

+
#define BUILDING_NODE_EXTENSION
+#include <node.h>
+#include "myobject.h"
+
+using namespace v8;
+
+Handle<Value> CreateObject(const Arguments& args) {
+  HandleScope scope;
+  return scope.Close(MyObject::NewInstance(args));
+}
+
+void InitAll(Handle<Object> target) {
+  MyObject::Init();
+
+  target->Set(String::NewSymbol("createObject"),
+      FunctionTemplate::New(CreateObject)->GetFunction());
+}
+
+NODE_MODULE(addon, InitAll)
+

In myobject.h we now introduce the static method NewInstance that takes +care of instantiating the object (i.e. it does the job of new in JavaScript): + +

+
#define BUILDING_NODE_EXTENSION
+#ifndef MYOBJECT_H
+#define MYOBJECT_H
+
+#include <node.h>
+
+class MyObject : public node::ObjectWrap {
+ public:
+  static void Init();
+  static v8::Handle<v8::Value> NewInstance(const v8::Arguments& args);
+
+ private:
+  MyObject();
+  ~MyObject();
+
+  static v8::Persistent<v8::Function> constructor;
+  static v8::Handle<v8::Value> New(const v8::Arguments& args);
+  static v8::Handle<v8::Value> PlusOne(const v8::Arguments& args);
+  double counter_;
+};
+
+#endif
+

The implementation is similar to the above in myobject.cc: + +

+
#define BUILDING_NODE_EXTENSION
+#include <node.h>
+#include "myobject.h"
+
+using namespace v8;
+
+MyObject::MyObject() {};
+MyObject::~MyObject() {};
+
+Persistent<Function> MyObject::constructor;
+
+void MyObject::Init() {
+  // Prepare constructor template
+  Local<FunctionTemplate> tpl = FunctionTemplate::New(New);
+  tpl->SetClassName(String::NewSymbol("MyObject"));
+  tpl->InstanceTemplate()->SetInternalFieldCount(1);
+  // Prototype
+  tpl->PrototypeTemplate()->Set(String::NewSymbol("plusOne"),
+      FunctionTemplate::New(PlusOne)->GetFunction());
+
+  constructor = Persistent<Function>::New(tpl->GetFunction());
+}
+
+Handle<Value> MyObject::New(const Arguments& args) {
+  HandleScope scope;
+
+  MyObject* obj = new MyObject();
+  obj->counter_ = args[0]->IsUndefined() ? 0 : args[0]->NumberValue();
+  obj->Wrap(args.This());
+
+  return args.This();
+}
+
+Handle<Value> MyObject::NewInstance(const Arguments& args) {
+  HandleScope scope;
+
+  const unsigned argc = 1;
+  Handle<Value> argv[argc] = { args[0] };
+  Local<Object> instance = constructor->NewInstance(argc, argv);
+
+  return scope.Close(instance);
+}
+
+Handle<Value> MyObject::PlusOne(const Arguments& args) {
+  HandleScope scope;
+
+  MyObject* obj = ObjectWrap::Unwrap<MyObject>(args.This());
+  obj->counter_ += 1;
+
+  return scope.Close(Number::New(obj->counter_));
+}
+

Test it with: + +

+
var addon = require('./build/Release/addon');
+
+var obj = addon.createObject(10);
+console.log( obj.plusOne() ); // 11
+console.log( obj.plusOne() ); // 12
+console.log( obj.plusOne() ); // 13
+
+var obj2 = addon.createObject(20);
+console.log( obj2.plusOne() ); // 21
+console.log( obj2.plusOne() ); // 22
+console.log( obj2.plusOne() ); // 23
+

Passing wrapped objects around#

+

In addition to wrapping and returning C++ objects, you can pass them around +by unwrapping them with Node's node::ObjectWrap::Unwrap helper function. +In the following addon.cc we introduce a function add() that can take on two +MyObject objects: + +

+
#define BUILDING_NODE_EXTENSION
+#include <node.h>
+#include "myobject.h"
+
+using namespace v8;
+
+Handle<Value> CreateObject(const Arguments& args) {
+  HandleScope scope;
+  return scope.Close(MyObject::NewInstance(args));
+}
+
+Handle<Value> Add(const Arguments& args) {
+  HandleScope scope;
+
+  MyObject* obj1 = node::ObjectWrap::Unwrap<MyObject>(
+      args[0]->ToObject());
+  MyObject* obj2 = node::ObjectWrap::Unwrap<MyObject>(
+      args[1]->ToObject());
+
+  double sum = obj1->Val() + obj2->Val();
+  return scope.Close(Number::New(sum));
+}
+
+void InitAll(Handle<Object> target) {
+  MyObject::Init();
+
+  target->Set(String::NewSymbol("createObject"),
+      FunctionTemplate::New(CreateObject)->GetFunction());
+
+  target->Set(String::NewSymbol("add"),
+      FunctionTemplate::New(Add)->GetFunction());
+}
+
+NODE_MODULE(addon, InitAll)
+

To make things interesting we introduce a public method in myobject.h so we +can probe private values after unwrapping the object: + +

+
#define BUILDING_NODE_EXTENSION
+#ifndef MYOBJECT_H
+#define MYOBJECT_H
+
+#include <node.h>
+
+class MyObject : public node::ObjectWrap {
+ public:
+  static void Init();
+  static v8::Handle<v8::Value> NewInstance(const v8::Arguments& args);
+  double Val() const { return val_; }
+
+ private:
+  MyObject();
+  ~MyObject();
+
+  static v8::Persistent<v8::Function> constructor;
+  static v8::Handle<v8::Value> New(const v8::Arguments& args);
+  double val_;
+};
+
+#endif
+

The implementation of myobject.cc is similar as before: + +

+
#define BUILDING_NODE_EXTENSION
+#include <node.h>
+#include "myobject.h"
+
+using namespace v8;
+
+MyObject::MyObject() {};
+MyObject::~MyObject() {};
+
+Persistent<Function> MyObject::constructor;
+
+void MyObject::Init() {
+  // Prepare constructor template
+  Local<FunctionTemplate> tpl = FunctionTemplate::New(New);
+  tpl->SetClassName(String::NewSymbol("MyObject"));
+  tpl->InstanceTemplate()->SetInternalFieldCount(1);
+
+  constructor = Persistent<Function>::New(tpl->GetFunction());
+}
+
+Handle<Value> MyObject::New(const Arguments& args) {
+  HandleScope scope;
+
+  MyObject* obj = new MyObject();
+  obj->val_ = args[0]->IsUndefined() ? 0 : args[0]->NumberValue();
+  obj->Wrap(args.This());
+
+  return args.This();
+}
+
+Handle<Value> MyObject::NewInstance(const Arguments& args) {
+  HandleScope scope;
+
+  const unsigned argc = 1;
+  Handle<Value> argv[argc] = { args[0] };
+  Local<Object> instance = constructor->NewInstance(argc, argv);
+
+  return scope.Close(instance);
+}
+

Test it with: + +

+
var addon = require('./build/Release/addon');
+
+var obj1 = addon.createObject(10);
+var obj2 = addon.createObject(20);
+var result = addon.add(obj1, obj2);
+
+console.log(result); // 30
+ +
+
+
+ + + + + + + + + diff --git a/node-v0.8.14/doc/api/addons.json b/node-v0.8.14/doc/api/addons.json new file mode 100644 index 0000000..19efb02 --- /dev/null +++ b/node-v0.8.14/doc/api/addons.json @@ -0,0 +1,79 @@ +{ + "source": "doc/api/addons.markdown", + "modules": [ + { + "textRaw": "Addons", + "name": "addons", + "desc": "

Addons are dynamically linked shared objects. They can provide glue to C and\nC++ libraries. The API (at the moment) is rather complex, involving\nknowledge of several libraries:\n\n

\n
    \n
  • V8 JavaScript, a C++ library. Used for interfacing with JavaScript:\ncreating objects, calling functions, etc. Documented mostly in the\nv8.h header file (deps/v8/include/v8.h in the Node source tree),\nwhich is also available online.

    \n
  • \n
  • libuv, C event loop library. Anytime one\nneeds to wait for a file descriptor to become readable, wait for a timer, or\nwait for a signal to received one will need to interface with libuv. That is,\nif you perform any I/O, libuv will need to be used.

    \n
  • \n
  • Internal Node libraries. Most importantly is the node::ObjectWrap\nclass which you will likely want to derive from.

    \n
  • \n
  • Others. Look in deps/ for what else is available.

    \n
  • \n
\n

Node statically compiles all its dependencies into the executable. When\ncompiling your module, you don't need to worry about linking to any of these\nlibraries.\n\n\n

\n", + "modules": [ + { + "textRaw": "Hello world", + "name": "hello_world", + "desc": "

To get started let's make a small Addon which is the C++ equivalent of\nthe following JavaScript code:\n\n

\n
exports.hello = function() { return 'world'; };
\n

First we create a file hello.cc:\n\n

\n
#include <node.h>\n#include <v8.h>\n\nusing namespace v8;\n\nHandle<Value> Method(const Arguments& args) {\n  HandleScope scope;\n  return scope.Close(String::New("world"));\n}\n\nvoid init(Handle<Object> target) {\n  target->Set(String::NewSymbol("hello"),\n      FunctionTemplate::New(Method)->GetFunction());\n}\nNODE_MODULE(hello, init)
\n

Note that all Node addons must export an initialization function:\n\n

\n
void Initialize (Handle<Object> target);\nNODE_MODULE(module_name, Initialize)
\n

There is no semi-colon after NODE_MODULE as it's not a function (see node.h).\n\n

\n

The module_name needs to match the filename of the final binary (minus the\n.node suffix).\n\n

\n

The source code needs to be built into hello.node, the binary Addon. To\ndo this we create a file called binding.gyp which describes the configuration\nto build your module in a JSON-like format. This file gets compiled by\nnode-gyp.\n\n

\n
{\n  "targets": [\n    {\n      "target_name": "hello",\n      "sources": [ "hello.cc" ]\n    }\n  ]\n}
\n

The next step is to generate the appropriate project build files for the\ncurrent platform. Use node-gyp configure for that.\n\n

\n

Now you will have either a Makefile (on Unix platforms) or a vcxproj file\n(on Windows) in the build/ directory. Next invoke the node-gyp build\ncommand.\n\n

\n

Now you have your compiled .node bindings file! The compiled bindings end up\nin build/Release/.\n\n

\n

You can now use the binary addon in a Node project hello.js by pointing require to\nthe recently built hello.node module:\n\n

\n
var addon = require('./build/Release/hello');\n\nconsole.log(addon.hello()); // 'world'
\n

Please see patterns below for further information or\n

\n

https://github.com/arturadib/node-qt for an example in production.\n\n\n

\n", + "type": "module", + "displayName": "Hello world" + }, + { + "textRaw": "Addon patterns", + "name": "addon_patterns", + "desc": "

Below are some addon patterns to help you get started. Consult the online\nv8 reference for help with the various v8\ncalls, and v8's Embedder's Guide\nfor an explanation of several concepts used such as handles, scopes,\nfunction templates, etc.\n\n

\n

In order to use these examples you need to compile them using node-gyp.\nCreate the following binding.gyp file:\n\n

\n
{\n  "targets": [\n    {\n      "target_name": "addon",\n      "sources": [ "addon.cc" ]\n    }\n  ]\n}
\n

In cases where there is more than one .cc file, simply add the file name to the\nsources array, e.g.:\n\n

\n
"sources": ["addon.cc", "myexample.cc"]
\n

Now that you have your binding.gyp ready, you can configure and build the\naddon:\n\n

\n
$ node-gyp configure build
\n", + "modules": [ + { + "textRaw": "Function arguments", + "name": "function_arguments", + "desc": "

The following pattern illustrates how to read arguments from JavaScript\nfunction calls and return a result. This is the main and only needed source\naddon.cc:\n\n

\n
#define BUILDING_NODE_EXTENSION\n#include <node.h>\n\nusing namespace v8;\n\nHandle<Value> Add(const Arguments& args) {\n  HandleScope scope;\n\n  if (args.Length() < 2) {\n    ThrowException(Exception::TypeError(String::New("Wrong number of arguments")));\n    return scope.Close(Undefined());\n  }\n\n  if (!args[0]->IsNumber() || !args[1]->IsNumber()) {\n    ThrowException(Exception::TypeError(String::New("Wrong arguments")));\n    return scope.Close(Undefined());\n  }\n\n  Local<Number> num = Number::New(args[0]->NumberValue() +\n      args[1]->NumberValue());\n  return scope.Close(num);\n}\n\nvoid Init(Handle<Object> target) {\n  target->Set(String::NewSymbol("add"),\n      FunctionTemplate::New(Add)->GetFunction());\n}\n\nNODE_MODULE(addon, Init)
\n

You can test it with the following JavaScript snippet:\n\n

\n
var addon = require('./build/Release/addon');\n\nconsole.log( 'This should be eight:', addon.add(3,5) );
\n", + "type": "module", + "displayName": "Function arguments" + }, + { + "textRaw": "Callbacks", + "name": "callbacks", + "desc": "

You can pass JavaScript functions to a C++ function and execute them from\nthere. Here's addon.cc:\n\n

\n
#define BUILDING_NODE_EXTENSION\n#include <node.h>\n\nusing namespace v8;\n\nHandle<Value> RunCallback(const Arguments& args) {\n  HandleScope scope;\n\n  Local<Function> cb = Local<Function>::Cast(args[0]);\n  const unsigned argc = 1;\n  Local<Value> argv[argc] = { Local<Value>::New(String::New("hello world")) };\n  cb->Call(Context::GetCurrent()->Global(), argc, argv);\n\n  return scope.Close(Undefined());\n}\n\nvoid Init(Handle<Object> target) {\n  target->Set(String::NewSymbol("runCallback"),\n      FunctionTemplate::New(RunCallback)->GetFunction());\n}\n\nNODE_MODULE(addon, Init)
\n

To test it run the following JavaScript snippet:\n\n

\n
var addon = require('./build/Release/addon');\n\naddon.runCallback(function(msg){\n  console.log(msg); // 'hello world'\n});
\n", + "type": "module", + "displayName": "Callbacks" + }, + { + "textRaw": "Object factory", + "name": "object_factory", + "desc": "

You can create and return new objects from within a C++ function with this\naddon.cc pattern, which returns an object with property msg that echoes\nthe string passed to createObject():\n\n

\n
#define BUILDING_NODE_EXTENSION\n#include <node.h>\n\nusing namespace v8;\n\nHandle<Value> CreateObject(const Arguments& args) {\n  HandleScope scope;\n\n  Local<Object> obj = Object::New();\n  obj->Set(String::NewSymbol("msg"), args[0]->ToString());\n\n  return scope.Close(obj);\n}\n\nvoid Init(Handle<Object> target) {\n  target->Set(String::NewSymbol("createObject"),\n      FunctionTemplate::New(CreateObject)->GetFunction());\n}\n\nNODE_MODULE(addon, Init)
\n

To test it in JavaScript:\n\n

\n
var addon = require('./build/Release/addon');\n\nvar obj1 = addon.createObject('hello');\nvar obj2 = addon.createObject('world');\nconsole.log(obj1.msg+' '+obj2.msg); // 'hello world'
\n", + "type": "module", + "displayName": "Object factory" + }, + { + "textRaw": "Function factory", + "name": "function_factory", + "desc": "

This pattern illustrates how to create and return a JavaScript function that\nwraps a C++ function:\n\n

\n
#define BUILDING_NODE_EXTENSION\n#include <node.h>\n\nusing namespace v8;\n\nHandle<Value> MyFunction(const Arguments& args) {\n  HandleScope scope;\n  return scope.Close(String::New("hello world"));\n}\n\nHandle<Value> CreateFunction(const Arguments& args) {\n  HandleScope scope;\n\n  Local<FunctionTemplate> tpl = FunctionTemplate::New(MyFunction);\n  Local<Function> fn = tpl->GetFunction();\n  fn->SetName(String::NewSymbol("theFunction")); // omit this to make it anonymous\n\n  return scope.Close(fn);\n}\n\nvoid Init(Handle<Object> target) {\n  target->Set(String::NewSymbol("createFunction"),\n      FunctionTemplate::New(CreateFunction)->GetFunction());\n}\n\nNODE_MODULE(addon, Init)
\n

To test:\n\n

\n
var addon = require('./build/Release/addon');\n\nvar fn = addon.createFunction();\nconsole.log(fn()); // 'hello world'
\n", + "type": "module", + "displayName": "Function factory" + }, + { + "textRaw": "Wrapping C++ objects", + "name": "wrapping_c++_objects", + "desc": "

Here we will create a wrapper for a C++ object/class MyObject that can be\ninstantiated in JavaScript through the new operator. First prepare the main\nmodule addon.cc:\n\n

\n
#define BUILDING_NODE_EXTENSION\n#include <node.h>\n#include "myobject.h"\n\nusing namespace v8;\n\nvoid InitAll(Handle<Object> target) {\n  MyObject::Init(target);\n}\n\nNODE_MODULE(addon, InitAll)
\n

Then in myobject.h make your wrapper inherit from node::ObjectWrap:\n\n

\n
#ifndef MYOBJECT_H\n#define MYOBJECT_H\n\n#include <node.h>\n\nclass MyObject : public node::ObjectWrap {\n public:\n  static void Init(v8::Handle<v8::Object> target);\n\n private:\n  MyObject();\n  ~MyObject();\n\n  static v8::Handle<v8::Value> New(const v8::Arguments& args);\n  static v8::Handle<v8::Value> PlusOne(const v8::Arguments& args);\n  double counter_;\n};\n\n#endif
\n

And in myobject.cc implement the various methods that you want to expose.\nHere we expose the method plusOne by adding it to the constructor's\nprototype:\n\n

\n
#define BUILDING_NODE_EXTENSION\n#include <node.h>\n#include "myobject.h"\n\nusing namespace v8;\n\nMyObject::MyObject() {};\nMyObject::~MyObject() {};\n\nvoid MyObject::Init(Handle<Object> target) {\n  // Prepare constructor template\n  Local<FunctionTemplate> tpl = FunctionTemplate::New(New);\n  tpl->SetClassName(String::NewSymbol("MyObject"));\n  tpl->InstanceTemplate()->SetInternalFieldCount(1);\n  // Prototype\n  tpl->PrototypeTemplate()->Set(String::NewSymbol("plusOne"),\n      FunctionTemplate::New(PlusOne)->GetFunction());\n\n  Persistent<Function> constructor = Persistent<Function>::New(tpl->GetFunction());\n  target->Set(String::NewSymbol("MyObject"), constructor);\n}\n\nHandle<Value> MyObject::New(const Arguments& args) {\n  HandleScope scope;\n\n  MyObject* obj = new MyObject();\n  obj->counter_ = args[0]->IsUndefined() ? 0 : args[0]->NumberValue();\n  obj->Wrap(args.This());\n\n  return args.This();\n}\n\nHandle<Value> MyObject::PlusOne(const Arguments& args) {\n  HandleScope scope;\n\n  MyObject* obj = ObjectWrap::Unwrap<MyObject>(args.This());\n  obj->counter_ += 1;\n\n  return scope.Close(Number::New(obj->counter_));\n}
\n

Test it with:\n\n

\n
var addon = require('./build/Release/addon');\n\nvar obj = new addon.MyObject(10);\nconsole.log( obj.plusOne() ); // 11\nconsole.log( obj.plusOne() ); // 12\nconsole.log( obj.plusOne() ); // 13
\n", + "type": "module", + "displayName": "Wrapping C++ objects" + }, + { + "textRaw": "Factory of wrapped objects", + "name": "factory_of_wrapped_objects", + "desc": "

This is useful when you want to be able to create native objects without\nexplicitly instantiating them with the new operator in JavaScript, e.g.\n\n

\n
var obj = addon.createObject();\n// instead of:\n// var obj = new addon.Object();
\n

Let's register our createObject method in addon.cc:\n\n

\n
#define BUILDING_NODE_EXTENSION\n#include <node.h>\n#include "myobject.h"\n\nusing namespace v8;\n\nHandle<Value> CreateObject(const Arguments& args) {\n  HandleScope scope;\n  return scope.Close(MyObject::NewInstance(args));\n}\n\nvoid InitAll(Handle<Object> target) {\n  MyObject::Init();\n\n  target->Set(String::NewSymbol("createObject"),\n      FunctionTemplate::New(CreateObject)->GetFunction());\n}\n\nNODE_MODULE(addon, InitAll)
\n

In myobject.h we now introduce the static method NewInstance that takes\ncare of instantiating the object (i.e. it does the job of new in JavaScript):\n\n

\n
#define BUILDING_NODE_EXTENSION\n#ifndef MYOBJECT_H\n#define MYOBJECT_H\n\n#include <node.h>\n\nclass MyObject : public node::ObjectWrap {\n public:\n  static void Init();\n  static v8::Handle<v8::Value> NewInstance(const v8::Arguments& args);\n\n private:\n  MyObject();\n  ~MyObject();\n\n  static v8::Persistent<v8::Function> constructor;\n  static v8::Handle<v8::Value> New(const v8::Arguments& args);\n  static v8::Handle<v8::Value> PlusOne(const v8::Arguments& args);\n  double counter_;\n};\n\n#endif
\n

The implementation is similar to the above in myobject.cc:\n\n

\n
#define BUILDING_NODE_EXTENSION\n#include <node.h>\n#include "myobject.h"\n\nusing namespace v8;\n\nMyObject::MyObject() {};\nMyObject::~MyObject() {};\n\nPersistent<Function> MyObject::constructor;\n\nvoid MyObject::Init() {\n  // Prepare constructor template\n  Local<FunctionTemplate> tpl = FunctionTemplate::New(New);\n  tpl->SetClassName(String::NewSymbol("MyObject"));\n  tpl->InstanceTemplate()->SetInternalFieldCount(1);\n  // Prototype\n  tpl->PrototypeTemplate()->Set(String::NewSymbol("plusOne"),\n      FunctionTemplate::New(PlusOne)->GetFunction());\n\n  constructor = Persistent<Function>::New(tpl->GetFunction());\n}\n\nHandle<Value> MyObject::New(const Arguments& args) {\n  HandleScope scope;\n\n  MyObject* obj = new MyObject();\n  obj->counter_ = args[0]->IsUndefined() ? 0 : args[0]->NumberValue();\n  obj->Wrap(args.This());\n\n  return args.This();\n}\n\nHandle<Value> MyObject::NewInstance(const Arguments& args) {\n  HandleScope scope;\n\n  const unsigned argc = 1;\n  Handle<Value> argv[argc] = { args[0] };\n  Local<Object> instance = constructor->NewInstance(argc, argv);\n\n  return scope.Close(instance);\n}\n\nHandle<Value> MyObject::PlusOne(const Arguments& args) {\n  HandleScope scope;\n\n  MyObject* obj = ObjectWrap::Unwrap<MyObject>(args.This());\n  obj->counter_ += 1;\n\n  return scope.Close(Number::New(obj->counter_));\n}
\n

Test it with:\n\n

\n
var addon = require('./build/Release/addon');\n\nvar obj = addon.createObject(10);\nconsole.log( obj.plusOne() ); // 11\nconsole.log( obj.plusOne() ); // 12\nconsole.log( obj.plusOne() ); // 13\n\nvar obj2 = addon.createObject(20);\nconsole.log( obj2.plusOne() ); // 21\nconsole.log( obj2.plusOne() ); // 22\nconsole.log( obj2.plusOne() ); // 23
\n", + "type": "module", + "displayName": "Factory of wrapped objects" + }, + { + "textRaw": "Passing wrapped objects around", + "name": "passing_wrapped_objects_around", + "desc": "

In addition to wrapping and returning C++ objects, you can pass them around\nby unwrapping them with Node's node::ObjectWrap::Unwrap helper function.\nIn the following addon.cc we introduce a function add() that can take on two\nMyObject objects:\n\n

\n
#define BUILDING_NODE_EXTENSION\n#include <node.h>\n#include "myobject.h"\n\nusing namespace v8;\n\nHandle<Value> CreateObject(const Arguments& args) {\n  HandleScope scope;\n  return scope.Close(MyObject::NewInstance(args));\n}\n\nHandle<Value> Add(const Arguments& args) {\n  HandleScope scope;\n\n  MyObject* obj1 = node::ObjectWrap::Unwrap<MyObject>(\n      args[0]->ToObject());\n  MyObject* obj2 = node::ObjectWrap::Unwrap<MyObject>(\n      args[1]->ToObject());\n\n  double sum = obj1->Val() + obj2->Val();\n  return scope.Close(Number::New(sum));\n}\n\nvoid InitAll(Handle<Object> target) {\n  MyObject::Init();\n\n  target->Set(String::NewSymbol("createObject"),\n      FunctionTemplate::New(CreateObject)->GetFunction());\n\n  target->Set(String::NewSymbol("add"),\n      FunctionTemplate::New(Add)->GetFunction());\n}\n\nNODE_MODULE(addon, InitAll)
\n

To make things interesting we introduce a public method in myobject.h so we\ncan probe private values after unwrapping the object:\n\n

\n
#define BUILDING_NODE_EXTENSION\n#ifndef MYOBJECT_H\n#define MYOBJECT_H\n\n#include <node.h>\n\nclass MyObject : public node::ObjectWrap {\n public:\n  static void Init();\n  static v8::Handle<v8::Value> NewInstance(const v8::Arguments& args);\n  double Val() const { return val_; }\n\n private:\n  MyObject();\n  ~MyObject();\n\n  static v8::Persistent<v8::Function> constructor;\n  static v8::Handle<v8::Value> New(const v8::Arguments& args);\n  double val_;\n};\n\n#endif
\n

The implementation of myobject.cc is similar as before:\n\n

\n
#define BUILDING_NODE_EXTENSION\n#include <node.h>\n#include "myobject.h"\n\nusing namespace v8;\n\nMyObject::MyObject() {};\nMyObject::~MyObject() {};\n\nPersistent<Function> MyObject::constructor;\n\nvoid MyObject::Init() {\n  // Prepare constructor template\n  Local<FunctionTemplate> tpl = FunctionTemplate::New(New);\n  tpl->SetClassName(String::NewSymbol("MyObject"));\n  tpl->InstanceTemplate()->SetInternalFieldCount(1);\n\n  constructor = Persistent<Function>::New(tpl->GetFunction());\n}\n\nHandle<Value> MyObject::New(const Arguments& args) {\n  HandleScope scope;\n\n  MyObject* obj = new MyObject();\n  obj->val_ = args[0]->IsUndefined() ? 0 : args[0]->NumberValue();\n  obj->Wrap(args.This());\n\n  return args.This();\n}\n\nHandle<Value> MyObject::NewInstance(const Arguments& args) {\n  HandleScope scope;\n\n  const unsigned argc = 1;\n  Handle<Value> argv[argc] = { args[0] };\n  Local<Object> instance = constructor->NewInstance(argc, argv);\n\n  return scope.Close(instance);\n}
\n

Test it with:\n\n

\n
var addon = require('./build/Release/addon');\n\nvar obj1 = addon.createObject(10);\nvar obj2 = addon.createObject(20);\nvar result = addon.add(obj1, obj2);\n\nconsole.log(result); // 30
\n", + "type": "module", + "displayName": "Passing wrapped objects around" + } + ], + "type": "module", + "displayName": "Addon patterns" + } + ], + "type": "module", + "displayName": "Addons" + } + ] +} diff --git a/node-v0.8.14/doc/api/addons.markdown b/node-v0.8.14/doc/api/addons.markdown new file mode 100644 index 0000000..b414943 --- /dev/null +++ b/node-v0.8.14/doc/api/addons.markdown @@ -0,0 +1,624 @@ +# Addons + +Addons are dynamically linked shared objects. They can provide glue to C and +C++ libraries. The API (at the moment) is rather complex, involving +knowledge of several libraries: + + - V8 JavaScript, a C++ library. Used for interfacing with JavaScript: + creating objects, calling functions, etc. Documented mostly in the + `v8.h` header file (`deps/v8/include/v8.h` in the Node source tree), + which is also available [online](http://izs.me/v8-docs/main.html). + + - [libuv](https://github.com/joyent/libuv), C event loop library. Anytime one + needs to wait for a file descriptor to become readable, wait for a timer, or + wait for a signal to received one will need to interface with libuv. That is, + if you perform any I/O, libuv will need to be used. + + - Internal Node libraries. Most importantly is the `node::ObjectWrap` + class which you will likely want to derive from. + + - Others. Look in `deps/` for what else is available. + +Node statically compiles all its dependencies into the executable. When +compiling your module, you don't need to worry about linking to any of these +libraries. + + +## Hello world + +To get started let's make a small Addon which is the C++ equivalent of +the following JavaScript code: + + exports.hello = function() { return 'world'; }; + +First we create a file `hello.cc`: + + #include + #include + + using namespace v8; + + Handle Method(const Arguments& args) { + HandleScope scope; + return scope.Close(String::New("world")); + } + + void init(Handle target) { + target->Set(String::NewSymbol("hello"), + FunctionTemplate::New(Method)->GetFunction()); + } + NODE_MODULE(hello, init) + +Note that all Node addons must export an initialization function: + + void Initialize (Handle target); + NODE_MODULE(module_name, Initialize) + +There is no semi-colon after `NODE_MODULE` as it's not a function (see `node.h`). + +The `module_name` needs to match the filename of the final binary (minus the +.node suffix). + +The source code needs to be built into `hello.node`, the binary Addon. To +do this we create a file called `binding.gyp` which describes the configuration +to build your module in a JSON-like format. This file gets compiled by +[node-gyp](https://github.com/TooTallNate/node-gyp). + + { + "targets": [ + { + "target_name": "hello", + "sources": [ "hello.cc" ] + } + ] + } + +The next step is to generate the appropriate project build files for the +current platform. Use `node-gyp configure` for that. + +Now you will have either a `Makefile` (on Unix platforms) or a `vcxproj` file +(on Windows) in the `build/` directory. Next invoke the `node-gyp build` +command. + +Now you have your compiled `.node` bindings file! The compiled bindings end up +in `build/Release/`. + +You can now use the binary addon in a Node project `hello.js` by pointing `require` to +the recently built `hello.node` module: + + var addon = require('./build/Release/hello'); + + console.log(addon.hello()); // 'world' + +Please see patterns below for further information or + for an example in production. + + +## Addon patterns + +Below are some addon patterns to help you get started. Consult the online +[v8 reference](http://izs.me/v8-docs/main.html) for help with the various v8 +calls, and v8's [Embedder's Guide](http://code.google.com/apis/v8/embed.html) +for an explanation of several concepts used such as handles, scopes, +function templates, etc. + +In order to use these examples you need to compile them using `node-gyp`. +Create the following `binding.gyp` file: + + { + "targets": [ + { + "target_name": "addon", + "sources": [ "addon.cc" ] + } + ] + } + +In cases where there is more than one `.cc` file, simply add the file name to the +`sources` array, e.g.: + + "sources": ["addon.cc", "myexample.cc"] + +Now that you have your `binding.gyp` ready, you can configure and build the +addon: + + $ node-gyp configure build + + +### Function arguments + +The following pattern illustrates how to read arguments from JavaScript +function calls and return a result. This is the main and only needed source +`addon.cc`: + + #define BUILDING_NODE_EXTENSION + #include + + using namespace v8; + + Handle Add(const Arguments& args) { + HandleScope scope; + + if (args.Length() < 2) { + ThrowException(Exception::TypeError(String::New("Wrong number of arguments"))); + return scope.Close(Undefined()); + } + + if (!args[0]->IsNumber() || !args[1]->IsNumber()) { + ThrowException(Exception::TypeError(String::New("Wrong arguments"))); + return scope.Close(Undefined()); + } + + Local num = Number::New(args[0]->NumberValue() + + args[1]->NumberValue()); + return scope.Close(num); + } + + void Init(Handle target) { + target->Set(String::NewSymbol("add"), + FunctionTemplate::New(Add)->GetFunction()); + } + + NODE_MODULE(addon, Init) + +You can test it with the following JavaScript snippet: + + var addon = require('./build/Release/addon'); + + console.log( 'This should be eight:', addon.add(3,5) ); + + +### Callbacks + +You can pass JavaScript functions to a C++ function and execute them from +there. Here's `addon.cc`: + + #define BUILDING_NODE_EXTENSION + #include + + using namespace v8; + + Handle RunCallback(const Arguments& args) { + HandleScope scope; + + Local cb = Local::Cast(args[0]); + const unsigned argc = 1; + Local argv[argc] = { Local::New(String::New("hello world")) }; + cb->Call(Context::GetCurrent()->Global(), argc, argv); + + return scope.Close(Undefined()); + } + + void Init(Handle target) { + target->Set(String::NewSymbol("runCallback"), + FunctionTemplate::New(RunCallback)->GetFunction()); + } + + NODE_MODULE(addon, Init) + +To test it run the following JavaScript snippet: + + var addon = require('./build/Release/addon'); + + addon.runCallback(function(msg){ + console.log(msg); // 'hello world' + }); + + +### Object factory + +You can create and return new objects from within a C++ function with this +`addon.cc` pattern, which returns an object with property `msg` that echoes +the string passed to `createObject()`: + + #define BUILDING_NODE_EXTENSION + #include + + using namespace v8; + + Handle CreateObject(const Arguments& args) { + HandleScope scope; + + Local obj = Object::New(); + obj->Set(String::NewSymbol("msg"), args[0]->ToString()); + + return scope.Close(obj); + } + + void Init(Handle target) { + target->Set(String::NewSymbol("createObject"), + FunctionTemplate::New(CreateObject)->GetFunction()); + } + + NODE_MODULE(addon, Init) + +To test it in JavaScript: + + var addon = require('./build/Release/addon'); + + var obj1 = addon.createObject('hello'); + var obj2 = addon.createObject('world'); + console.log(obj1.msg+' '+obj2.msg); // 'hello world' + + +### Function factory + +This pattern illustrates how to create and return a JavaScript function that +wraps a C++ function: + + #define BUILDING_NODE_EXTENSION + #include + + using namespace v8; + + Handle MyFunction(const Arguments& args) { + HandleScope scope; + return scope.Close(String::New("hello world")); + } + + Handle CreateFunction(const Arguments& args) { + HandleScope scope; + + Local tpl = FunctionTemplate::New(MyFunction); + Local fn = tpl->GetFunction(); + fn->SetName(String::NewSymbol("theFunction")); // omit this to make it anonymous + + return scope.Close(fn); + } + + void Init(Handle target) { + target->Set(String::NewSymbol("createFunction"), + FunctionTemplate::New(CreateFunction)->GetFunction()); + } + + NODE_MODULE(addon, Init) + + +To test: + + var addon = require('./build/Release/addon'); + + var fn = addon.createFunction(); + console.log(fn()); // 'hello world' + + +### Wrapping C++ objects + +Here we will create a wrapper for a C++ object/class `MyObject` that can be +instantiated in JavaScript through the `new` operator. First prepare the main +module `addon.cc`: + + #define BUILDING_NODE_EXTENSION + #include + #include "myobject.h" + + using namespace v8; + + void InitAll(Handle target) { + MyObject::Init(target); + } + + NODE_MODULE(addon, InitAll) + +Then in `myobject.h` make your wrapper inherit from `node::ObjectWrap`: + + #ifndef MYOBJECT_H + #define MYOBJECT_H + + #include + + class MyObject : public node::ObjectWrap { + public: + static void Init(v8::Handle target); + + private: + MyObject(); + ~MyObject(); + + static v8::Handle New(const v8::Arguments& args); + static v8::Handle PlusOne(const v8::Arguments& args); + double counter_; + }; + + #endif + +And in `myobject.cc` implement the various methods that you want to expose. +Here we expose the method `plusOne` by adding it to the constructor's +prototype: + + #define BUILDING_NODE_EXTENSION + #include + #include "myobject.h" + + using namespace v8; + + MyObject::MyObject() {}; + MyObject::~MyObject() {}; + + void MyObject::Init(Handle target) { + // Prepare constructor template + Local tpl = FunctionTemplate::New(New); + tpl->SetClassName(String::NewSymbol("MyObject")); + tpl->InstanceTemplate()->SetInternalFieldCount(1); + // Prototype + tpl->PrototypeTemplate()->Set(String::NewSymbol("plusOne"), + FunctionTemplate::New(PlusOne)->GetFunction()); + + Persistent constructor = Persistent::New(tpl->GetFunction()); + target->Set(String::NewSymbol("MyObject"), constructor); + } + + Handle MyObject::New(const Arguments& args) { + HandleScope scope; + + MyObject* obj = new MyObject(); + obj->counter_ = args[0]->IsUndefined() ? 0 : args[0]->NumberValue(); + obj->Wrap(args.This()); + + return args.This(); + } + + Handle MyObject::PlusOne(const Arguments& args) { + HandleScope scope; + + MyObject* obj = ObjectWrap::Unwrap(args.This()); + obj->counter_ += 1; + + return scope.Close(Number::New(obj->counter_)); + } + +Test it with: + + var addon = require('./build/Release/addon'); + + var obj = new addon.MyObject(10); + console.log( obj.plusOne() ); // 11 + console.log( obj.plusOne() ); // 12 + console.log( obj.plusOne() ); // 13 + + +### Factory of wrapped objects + +This is useful when you want to be able to create native objects without +explicitly instantiating them with the `new` operator in JavaScript, e.g. + + var obj = addon.createObject(); + // instead of: + // var obj = new addon.Object(); + +Let's register our `createObject` method in `addon.cc`: + + #define BUILDING_NODE_EXTENSION + #include + #include "myobject.h" + + using namespace v8; + + Handle CreateObject(const Arguments& args) { + HandleScope scope; + return scope.Close(MyObject::NewInstance(args)); + } + + void InitAll(Handle target) { + MyObject::Init(); + + target->Set(String::NewSymbol("createObject"), + FunctionTemplate::New(CreateObject)->GetFunction()); + } + + NODE_MODULE(addon, InitAll) + +In `myobject.h` we now introduce the static method `NewInstance` that takes +care of instantiating the object (i.e. it does the job of `new` in JavaScript): + + #define BUILDING_NODE_EXTENSION + #ifndef MYOBJECT_H + #define MYOBJECT_H + + #include + + class MyObject : public node::ObjectWrap { + public: + static void Init(); + static v8::Handle NewInstance(const v8::Arguments& args); + + private: + MyObject(); + ~MyObject(); + + static v8::Persistent constructor; + static v8::Handle New(const v8::Arguments& args); + static v8::Handle PlusOne(const v8::Arguments& args); + double counter_; + }; + + #endif + +The implementation is similar to the above in `myobject.cc`: + + #define BUILDING_NODE_EXTENSION + #include + #include "myobject.h" + + using namespace v8; + + MyObject::MyObject() {}; + MyObject::~MyObject() {}; + + Persistent MyObject::constructor; + + void MyObject::Init() { + // Prepare constructor template + Local tpl = FunctionTemplate::New(New); + tpl->SetClassName(String::NewSymbol("MyObject")); + tpl->InstanceTemplate()->SetInternalFieldCount(1); + // Prototype + tpl->PrototypeTemplate()->Set(String::NewSymbol("plusOne"), + FunctionTemplate::New(PlusOne)->GetFunction()); + + constructor = Persistent::New(tpl->GetFunction()); + } + + Handle MyObject::New(const Arguments& args) { + HandleScope scope; + + MyObject* obj = new MyObject(); + obj->counter_ = args[0]->IsUndefined() ? 0 : args[0]->NumberValue(); + obj->Wrap(args.This()); + + return args.This(); + } + + Handle MyObject::NewInstance(const Arguments& args) { + HandleScope scope; + + const unsigned argc = 1; + Handle argv[argc] = { args[0] }; + Local instance = constructor->NewInstance(argc, argv); + + return scope.Close(instance); + } + + Handle MyObject::PlusOne(const Arguments& args) { + HandleScope scope; + + MyObject* obj = ObjectWrap::Unwrap(args.This()); + obj->counter_ += 1; + + return scope.Close(Number::New(obj->counter_)); + } + +Test it with: + + var addon = require('./build/Release/addon'); + + var obj = addon.createObject(10); + console.log( obj.plusOne() ); // 11 + console.log( obj.plusOne() ); // 12 + console.log( obj.plusOne() ); // 13 + + var obj2 = addon.createObject(20); + console.log( obj2.plusOne() ); // 21 + console.log( obj2.plusOne() ); // 22 + console.log( obj2.plusOne() ); // 23 + + +### Passing wrapped objects around + +In addition to wrapping and returning C++ objects, you can pass them around +by unwrapping them with Node's `node::ObjectWrap::Unwrap` helper function. +In the following `addon.cc` we introduce a function `add()` that can take on two +`MyObject` objects: + + #define BUILDING_NODE_EXTENSION + #include + #include "myobject.h" + + using namespace v8; + + Handle CreateObject(const Arguments& args) { + HandleScope scope; + return scope.Close(MyObject::NewInstance(args)); + } + + Handle Add(const Arguments& args) { + HandleScope scope; + + MyObject* obj1 = node::ObjectWrap::Unwrap( + args[0]->ToObject()); + MyObject* obj2 = node::ObjectWrap::Unwrap( + args[1]->ToObject()); + + double sum = obj1->Val() + obj2->Val(); + return scope.Close(Number::New(sum)); + } + + void InitAll(Handle target) { + MyObject::Init(); + + target->Set(String::NewSymbol("createObject"), + FunctionTemplate::New(CreateObject)->GetFunction()); + + target->Set(String::NewSymbol("add"), + FunctionTemplate::New(Add)->GetFunction()); + } + + NODE_MODULE(addon, InitAll) + +To make things interesting we introduce a public method in `myobject.h` so we +can probe private values after unwrapping the object: + + #define BUILDING_NODE_EXTENSION + #ifndef MYOBJECT_H + #define MYOBJECT_H + + #include + + class MyObject : public node::ObjectWrap { + public: + static void Init(); + static v8::Handle NewInstance(const v8::Arguments& args); + double Val() const { return val_; } + + private: + MyObject(); + ~MyObject(); + + static v8::Persistent constructor; + static v8::Handle New(const v8::Arguments& args); + double val_; + }; + + #endif + +The implementation of `myobject.cc` is similar as before: + + #define BUILDING_NODE_EXTENSION + #include + #include "myobject.h" + + using namespace v8; + + MyObject::MyObject() {}; + MyObject::~MyObject() {}; + + Persistent MyObject::constructor; + + void MyObject::Init() { + // Prepare constructor template + Local tpl = FunctionTemplate::New(New); + tpl->SetClassName(String::NewSymbol("MyObject")); + tpl->InstanceTemplate()->SetInternalFieldCount(1); + + constructor = Persistent::New(tpl->GetFunction()); + } + + Handle MyObject::New(const Arguments& args) { + HandleScope scope; + + MyObject* obj = new MyObject(); + obj->val_ = args[0]->IsUndefined() ? 0 : args[0]->NumberValue(); + obj->Wrap(args.This()); + + return args.This(); + } + + Handle MyObject::NewInstance(const Arguments& args) { + HandleScope scope; + + const unsigned argc = 1; + Handle argv[argc] = { args[0] }; + Local instance = constructor->NewInstance(argc, argv); + + return scope.Close(instance); + } + +Test it with: + + var addon = require('./build/Release/addon'); + + var obj1 = addon.createObject(10); + var obj2 = addon.createObject(20); + var result = addon.add(obj1, obj2); + + console.log(result); // 30 diff --git a/node-v0.8.14/doc/api/all.html b/node-v0.8.14/doc/api/all.html new file mode 100644 index 0000000..49747d9 --- /dev/null +++ b/node-v0.8.14/doc/api/all.html @@ -0,0 +1,11221 @@ + + + + + About this Documentation Node.js v0.8.14 Manual & Documentation + + + + + +
+ + + +
+
+ + +
+
+

Node.js v0.8.14 Manual & Documentation

+ +
+
+ +
+

Table of Contents

+ + +
+ +
+

About this Documentation#

+ + +

The goal of this documentation is to comprehensively explain the Node.js +API, both from a reference as well as a conceptual point of view. Each +section describes a built-in module or high-level concept. + +

+

Where appropriate, property types, method arguments, and the arguments +provided to event handlers are detailed in a list underneath the topic +heading. + +

+

Every .html document has a corresponding .json document presenting +the same information in a structured manner. This feature is +experimental, and added for the benefit of IDEs and other utilities that +wish to do programmatic things with the documentation. + +

+

Every .html and .json file is generated based on the corresponding +.markdown file in the doc/api/ folder in node's source tree. The +documentation is generated using the tools/doc/generate.js program. +The HTML template is located at doc/template.html. + +

+

Stability Index#

+ + +

Throughout the documentation, you will see indications of a section's +stability. The Node.js API is still somewhat changing, and as it +matures, certain parts are more reliable than others. Some are so +proven, and so relied upon, that they are unlikely to ever change at +all. Others are brand new and experimental, or known to be hazardous +and in the process of being redesigned. + +

+

The notices look like this: + +

+
Stability: 1 Experimental
+

The stability indices are as follows: + +

+
    +
  • 0 - Deprecated This feature is known to be problematic, and changes are +planned. Do not rely on it. Use of the feature may cause warnings. Backwards +compatibility should not be expected.
  • +
+
    +
  • 1 - Experimental This feature was introduced recently, and may change +or be removed in future versions. Please try it out and provide feedback. +If it addresses a use-case that is important to you, tell the node core team.
  • +
+
    +
  • 2 - Unstable The API is in the process of settling, but has not yet had +sufficient real-world testing to be considered stable. Backwards-compatibility +will be maintained if reasonable.
  • +
+
    +
  • 3 - Stable The API has proven satisfactory, but cleanup in the underlying +code may cause minor changes. Backwards-compatibility is guaranteed.
  • +
+
    +
  • 4 - API Frozen This API has been tested extensively in production and is +unlikely to ever have to change.
  • +
+
    +
  • 5 - Locked Unless serious bugs are found, this code will not ever +change. Please do not suggest changes in this area; they will be refused.
  • +
+

JSON Output#

+
Stability: 1 - Experimental
+

Every HTML file in the markdown has a corresponding JSON file with the +same data. + +

+

This feature is new as of node v0.6.12. It is experimental. + +

+

Synopsis#

+ + +

An example of a web server written with Node which responds with 'Hello +World': + +

+
var http = require('http');
+
+http.createServer(function (request, response) {
+  response.writeHead(200, {'Content-Type': 'text/plain'});
+  response.end('Hello World\n');
+}).listen(8124);
+
+console.log('Server running at http://127.0.0.1:8124/');
+

To run the server, put the code into a file called example.js and execute +it with the node program + +

+
> node example.js
+Server running at http://127.0.0.1:8124/
+

All of the examples in the documentation can be run similarly. + +

+

Global Objects#

+ + +

These objects are available in all modules. Some of these objects aren't +actually in the global scope but in the module scope - this will be noted. + +

+

global#

+ + +
    +
  • {Object} The global namespace object.
  • +
+

In browsers, the top-level scope is the global scope. That means that in +browsers if you're in the global scope var something will define a global +variable. In Node this is different. The top-level scope is not the global +scope; var something inside a Node module will be local to that module. + +

+

process#

+ + +
    +
  • {Object}
  • +
+

The process object. See the process object section. + +

+

console#

+ + +
    +
  • {Object}
  • +
+

Used to print to stdout and stderr. See the stdio section. + +

+

Class: Buffer#

+ + +
    +
  • {Function}
  • +
+

Used to handle binary data. See the buffer section + +

+

require()#

+ + +
    +
  • {Function}
  • +
+

To require modules. See the Modules section. require isn't actually a +global but rather local to each module. + +

+

require.resolve()#

+

Use the internal require() machinery to look up the location of a module, +but rather than loading the module, just return the resolved filename. + +

+

require.cache#

+
    +
  • Object
  • +
+

Modules are cached in this object when they are required. By deleting a key +value from this object, the next require will reload the module. + +

+

require.extensions#

+
    +
  • Array
  • +
+

Instruct require on how to handle certain file extensions. + +

+

Process files with the extension .sjs as .js: + +

+
require.extensions['.sjs'] = require.extensions['.js'];
+

Write your own extension handler: + +

+
require.extensions['.sjs'] = function(module, filename) {
+  var content = fs.readFileSync(filename, 'utf8');
+  // Parse the file content and give to module.exports
+  module.exports = content;
+};
+

__filename#

+ + +
    +
  • {String}
  • +
+

The filename of the code being executed. This is the resolved absolute path +of this code file. For a main program this is not necessarily the same +filename used in the command line. The value inside a module is the path +to that module file. + +

+

Example: running node example.js from /Users/mjr + +

+
console.log(__filename);
+// /Users/mjr/example.js
+

__filename isn't actually a global but rather local to each module. + +

+

__dirname#

+ + +
    +
  • {String}
  • +
+

The name of the directory that the currently executing script resides in. + +

+

Example: running node example.js from /Users/mjr + +

+
console.log(__dirname);
+// /Users/mjr
+

__dirname isn't actually a global but rather local to each module. + + +

+

module#

+ + +
    +
  • {Object}
  • +
+

A reference to the current module. In particular +module.exports is the same as the exports object. +module isn't actually a global but rather local to each module. + +

+

See the module system documentation for more information. + +

+

exports#

+ + +

An object which is shared between all instances of the current module and +made accessible through require(). +exports is the same as the module.exports object. +exports isn't actually a global but rather local to each module. + +

+

See the module system documentation for more information. + +

+

See the module section for more information. + +

+

setTimeout(cb, ms)#

+

Run callback cb after at least ms milliseconds. The actual delay depends +on external factors like OS timer granularity and system load. + +

+

The timeout must be in the range of 1-2,147,483,647 inclusive. If the value is +outside that range, it's changed to 1 millisecond. Broadly speaking, a timer +cannot span more than 24.8 days. + +

+

Returns an opaque value that represents the timer. + +

+

clearTimeout(t)#

+

Stop a timer that was previously created with setTimeout(). The callback will +not execute. + +

+

setInterval(cb, ms)#

+

Run callback cb repeatedly every ms milliseconds. Note that the actual +interval may vary, depending on external factors like OS timer granularity and +system load. It's never less than ms but it may be longer. + +

+

The interval must be in the range of 1-2,147,483,647 inclusive. If the value is +outside that range, it's changed to 1 millisecond. Broadly speaking, a timer +cannot span more than 24.8 days. + +

+

Returns an opaque value that represents the timer. + +

+

clearInterval(t)#

+

Stop a timer that was previously created with setInterval(). The callback +will not execute. + +

+ + +

The timer functions are global variables. See the timers section. + +

+

console#

+
Stability: 4 - API Frozen
+
    +
  • {Object}
  • +
+ + +

For printing to stdout and stderr. Similar to the console object functions +provided by most web browsers, here the output is sent to stdout or stderr. + +

+

console.log([data], [...])#

+

Prints to stdout with newline. This function can take multiple arguments in a +printf()-like way. Example: + +

+
console.log('count: %d', count);
+

If formatting elements are not found in the first string then util.inspect +is used on each argument. See util.format() for more information. + +

+

console.info([data], [...])#

+

Same as console.log. + +

+

console.error([data], [...])#

+

Same as console.log but prints to stderr. + +

+

console.warn([data], [...])#

+

Same as console.error. + +

+

console.dir(obj)#

+

Uses util.inspect on obj and prints resulting string to stdout. + +

+

console.time(label)#

+

Mark a time. + +

+

console.timeEnd(label)#

+

Finish timer, record output. Example: + +

+
console.time('100-elements');
+for (var i = 0; i < 100; i++) {
+  ;
+}
+console.timeEnd('100-elements');
+

console.trace(label)#

+

Print a stack trace to stderr of the current position. + +

+

console.assert(expression, [message])#

+

Same as assert.ok() where if the expression evaluates as false throw an +AssertionError with message. + +

+

Timers#

+
Stability: 5 - Locked
+

All of the timer functions are globals. You do not need to require() +this module in order to use them. + +

+

setTimeout(callback, delay, [arg], [...])#

+

To schedule execution of a one-time callback after delay milliseconds. Returns a +timeoutId for possible use with clearTimeout(). Optionally you can +also pass arguments to the callback. + +

+

It is important to note that your callback will probably not be called in exactly +delay milliseconds - Node.js makes no guarantees about the exact timing of when +the callback will fire, nor of the ordering things will fire in. The callback will +be called as close as possible to the time specified. + +

+

clearTimeout(timeoutId)#

+

Prevents a timeout from triggering. + +

+

setInterval(callback, delay, [arg], [...])#

+

To schedule the repeated execution of callback every delay milliseconds. +Returns a intervalId for possible use with clearInterval(). Optionally +you can also pass arguments to the callback. + +

+

clearInterval(intervalId)#

+

Stops a interval from triggering. + +

+

Modules#

+
Stability: 5 - Locked
+ + +

Node has a simple module loading system. In Node, files and modules are in +one-to-one correspondence. As an example, foo.js loads the module +circle.js in the same directory. + +

+

The contents of foo.js: + +

+
var circle = require('./circle.js');
+console.log( 'The area of a circle of radius 4 is '
+           + circle.area(4));
+

The contents of circle.js: + +

+
var PI = Math.PI;
+
+exports.area = function (r) {
+  return PI * r * r;
+};
+
+exports.circumference = function (r) {
+  return 2 * PI * r;
+};
+

The module circle.js has exported the functions area() and +circumference(). To export an object, add to the special exports +object. + +

+

Variables +local to the module will be private. In this example the variable PI is +private to circle.js. + +

+

The module system is implemented in the require("module") module. + +

+

Cycles#

+ + +

When there are circular require() calls, a module might not be +done being executed when it is returned. + +

+

Consider this situation: + +

+

a.js: + +

+
console.log('a starting');
+exports.done = false;
+var b = require('./b.js');
+console.log('in a, b.done = %j', b.done);
+exports.done = true;
+console.log('a done');
+

b.js: + +

+
console.log('b starting');
+exports.done = false;
+var a = require('./a.js');
+console.log('in b, a.done = %j', a.done);
+exports.done = true;
+console.log('b done');
+

main.js: + +

+
console.log('main starting');
+var a = require('./a.js');
+var b = require('./b.js');
+console.log('in main, a.done=%j, b.done=%j', a.done, b.done);
+

When main.js loads a.js, then a.js in turn loads b.js. At that +point, b.js tries to load a.js. In order to prevent an infinite +loop an unfinished copy of the a.js exports object is returned to the +b.js module. b.js then finishes loading, and its exports object is +provided to the a.js module. + +

+

By the time main.js has loaded both modules, they're both finished. +The output of this program would thus be: + +

+
$ node main.js
+main starting
+a starting
+b starting
+in b, a.done = false
+b done
+in a, b.done = true
+a done
+in main, a.done=true, b.done=true
+

If you have cyclic module dependencies in your program, make sure to +plan accordingly. + +

+

Core Modules#

+ + +

Node has several modules compiled into the binary. These modules are +described in greater detail elsewhere in this documentation. + +

+

The core modules are defined in node's source in the lib/ folder. + +

+

Core modules are always preferentially loaded if their identifier is +passed to require(). For instance, require('http') will always +return the built in HTTP module, even if there is a file by that name. + +

+

File Modules#

+ + +

If the exact filename is not found, then node will attempt to load the +required filename with the added extension of .js, .json, and then .node. + +

+

.js files are interpreted as JavaScript text files, and .json files are +parsed as JSON text files. .node files are interpreted as compiled addon +modules loaded with dlopen. + +

+

A module prefixed with '/' is an absolute path to the file. For +example, require('/home/marco/foo.js') will load the file at +/home/marco/foo.js. + +

+

A module prefixed with './' is relative to the file calling require(). +That is, circle.js must be in the same directory as foo.js for +require('./circle') to find it. + +

+

Without a leading '/' or './' to indicate a file, the module is either a +"core module" or is loaded from a node_modules folder. + +

+

If the given path does not exist, require() will throw an Error with its +code property set to 'MODULE_NOT_FOUND'. + +

+

Loading from node_modules Folders#

+ + +

If the module identifier passed to require() is not a native module, +and does not begin with '/', '../', or './', then node starts at the +parent directory of the current module, and adds /node_modules, and +attempts to load the module from that location. + +

+

If it is not found there, then it moves to the parent directory, and so +on, until the root of the tree is reached. + +

+

For example, if the file at '/home/ry/projects/foo.js' called +require('bar.js'), then node would look in the following locations, in +this order: + +

+
    +
  • /home/ry/projects/node_modules/bar.js
  • +
  • /home/ry/node_modules/bar.js
  • +
  • /home/node_modules/bar.js
  • +
  • /node_modules/bar.js
  • +
+

This allows programs to localize their dependencies, so that they do not +clash. + +

+

Folders as Modules#

+ + +

It is convenient to organize programs and libraries into self-contained +directories, and then provide a single entry point to that library. +There are three ways in which a folder may be passed to require() as +an argument. + +

+

The first is to create a package.json file in the root of the folder, +which specifies a main module. An example package.json file might +look like this: + +

+
{ "name" : "some-library",
+  "main" : "./lib/some-library.js" }
+

If this was in a folder at ./some-library, then +require('./some-library') would attempt to load +./some-library/lib/some-library.js. + +

+

This is the extent of Node's awareness of package.json files. + +

+

If there is no package.json file present in the directory, then node +will attempt to load an index.js or index.node file out of that +directory. For example, if there was no package.json file in the above +example, then require('./some-library') would attempt to load: + +

+
    +
  • ./some-library/index.js
  • +
  • ./some-library/index.node
  • +
+

Caching#

+ + +

Modules are cached after the first time they are loaded. This means +(among other things) that every call to require('foo') will get +exactly the same object returned, if it would resolve to the same file. + +

+

Multiple calls to require('foo') may not cause the module code to be +executed multiple times. This is an important feature. With it, +"partially done" objects can be returned, thus allowing transitive +dependencies to be loaded even when they would cause cycles. + +

+

If you want to have a module execute code multiple times, then export a +function, and call that function. + +

+

Module Caching Caveats#

+ + +

Modules are cached based on their resolved filename. Since modules may +resolve to a different filename based on the location of the calling +module (loading from node_modules folders), it is not a guarantee +that require('foo') will always return the exact same object, if it +would resolve to different files. + +

+

The module Object#

+ + + +
    +
  • {Object}
  • +
+

In each module, the module free variable is a reference to the object +representing the current module. In particular +module.exports is the same as the exports object. +module isn't actually a global but rather local to each module. + +

+

module.exports#

+
    +
  • Object
  • +
+

The exports object is created by the Module system. Sometimes this is not +acceptable, many want their module to be an instance of some class. To do this +assign the desired export object to module.exports. For example suppose we +were making a module called a.js + +

+
var EventEmitter = require('events').EventEmitter;
+
+module.exports = new EventEmitter();
+
+// Do some work, and after some time emit
+// the 'ready' event from the module itself.
+setTimeout(function() {
+  module.exports.emit('ready');
+}, 1000);
+

Then in another file we could do + +

+
var a = require('./a');
+a.on('ready', function() {
+  console.log('module a is ready');
+});
+

Note that assignment to module.exports must be done immediately. It cannot be +done in any callbacks. This does not work: + +

+

x.js: + +

+
setTimeout(function() {
+  module.exports = { a: "hello" };
+}, 0);
+

y.js: + +

+
var x = require('./x');
+console.log(x.a);
+

module.require(id)#

+
    +
  • id String
  • +
  • Return: Object exports from the resolved module
  • +
+

The module.require method provides a way to load a module as if +require() was called from the original module. + +

+

Note that in order to do this, you must get a reference to the module +object. Since require() returns the exports, and the module is +typically only available within a specific module's code, it must be +explicitly exported in order to be used. + + +

+

module.id#

+
    +
  • String
  • +
+

The identifier for the module. Typically this is the fully resolved +filename. + + +

+

module.filename#

+
    +
  • String
  • +
+

The fully resolved filename to the module. + + +

+

module.loaded#

+
    +
  • Boolean
  • +
+

Whether or not the module is done loading, or is in the process of +loading. + + +

+

module.parent#

+
    +
  • Module Object
  • +
+

The module that required this one. + + +

+

module.children#

+
    +
  • Array
  • +
+

The module objects required by this one. + + + +

+

All Together...#

+ + +

To get the exact filename that will be loaded when require() is called, use +the require.resolve() function. + +

+

Putting together all of the above, here is the high-level algorithm +in pseudocode of what require.resolve does: + +

+
require(X) from module at path Y
+1. If X is a core module,
+   a. return the core module
+   b. STOP
+2. If X begins with './' or '/' or '../'
+   a. LOAD_AS_FILE(Y + X)
+   b. LOAD_AS_DIRECTORY(Y + X)
+3. LOAD_NODE_MODULES(X, dirname(Y))
+4. THROW "not found"
+
+LOAD_AS_FILE(X)
+1. If X is a file, load X as JavaScript text.  STOP
+2. If X.js is a file, load X.js as JavaScript text.  STOP
+3. If X.node is a file, load X.node as binary addon.  STOP
+
+LOAD_AS_DIRECTORY(X)
+1. If X/package.json is a file,
+   a. Parse X/package.json, and look for "main" field.
+   b. let M = X + (json main field)
+   c. LOAD_AS_FILE(M)
+2. If X/index.js is a file, load X/index.js as JavaScript text.  STOP
+3. If X/index.node is a file, load X/index.node as binary addon.  STOP
+
+LOAD_NODE_MODULES(X, START)
+1. let DIRS=NODE_MODULES_PATHS(START)
+2. for each DIR in DIRS:
+   a. LOAD_AS_FILE(DIR/X)
+   b. LOAD_AS_DIRECTORY(DIR/X)
+
+NODE_MODULES_PATHS(START)
+1. let PARTS = path split(START)
+2. let ROOT = index of first instance of "node_modules" in PARTS, or 0
+3. let I = count of PARTS - 1
+4. let DIRS = []
+5. while I > ROOT,
+   a. if PARTS[I] = "node_modules" CONTINUE
+   c. DIR = path join(PARTS[0 .. I] + "node_modules")
+   b. DIRS = DIRS + DIR
+   c. let I = I - 1
+6. return DIRS
+

Loading from the global folders#

+ + +

If the NODE_PATH environment variable is set to a colon-delimited list +of absolute paths, then node will search those paths for modules if they +are not found elsewhere. (Note: On Windows, NODE_PATH is delimited by +semicolons instead of colons.) + +

+

Additionally, node will search in the following locations: + +

+
    +
  • 1: $HOME/.node_modules
  • +
  • 2: $HOME/.node_libraries
  • +
  • 3: $PREFIX/lib/node
  • +
+

Where $HOME is the user's home directory, and $PREFIX is node's +configured node_prefix. + +

+

These are mostly for historic reasons. You are highly encouraged to +place your dependencies locally in node_modules folders. They will be +loaded faster, and more reliably. + +

+

Accessing the main module#

+ + +

When a file is run directly from Node, require.main is set to its +module. That means that you can determine whether a file has been run +directly by testing + +

+
require.main === module
+

For a file foo.js, this will be true if run via node foo.js, but +false if run by require('./foo'). + +

+

Because module provides a filename property (normally equivalent to +__filename), the entry point of the current application can be obtained +by checking require.main.filename. + +

+

Addenda: Package Manager Tips#

+ + +

The semantics of Node's require() function were designed to be general +enough to support a number of sane directory structures. Package manager +programs such as dpkg, rpm, and npm will hopefully find it possible to +build native packages from Node modules without modification. + +

+

Below we give a suggested directory structure that could work: + +

+

Let's say that we wanted to have the folder at +/usr/lib/node/<some-package>/<some-version> hold the contents of a +specific version of a package. + +

+

Packages can depend on one another. In order to install package foo, you +may have to install a specific version of package bar. The bar package +may itself have dependencies, and in some cases, these dependencies may even +collide or form cycles. + +

+

Since Node looks up the realpath of any modules it loads (that is, +resolves symlinks), and then looks for their dependencies in the +node_modules folders as described above, this situation is very simple to +resolve with the following architecture: + +

+
    +
  • /usr/lib/node/foo/1.2.3/ - Contents of the foo package, version 1.2.3.
  • +
  • /usr/lib/node/bar/4.3.2/ - Contents of the bar package that foo +depends on.
  • +
  • /usr/lib/node/foo/1.2.3/node_modules/bar - Symbolic link to +/usr/lib/node/bar/4.3.2/.
  • +
  • /usr/lib/node/bar/4.3.2/node_modules/* - Symbolic links to the packages +that bar depends on.
  • +
+

Thus, even if a cycle is encountered, or if there are dependency +conflicts, every module will be able to get a version of its dependency +that it can use. + +

+

When the code in the foo package does require('bar'), it will get the +version that is symlinked into /usr/lib/node/foo/1.2.3/node_modules/bar. +Then, when the code in the bar package calls require('quux'), it'll get +the version that is symlinked into +/usr/lib/node/bar/4.3.2/node_modules/quux. + +

+

Furthermore, to make the module lookup process even more optimal, rather +than putting packages directly in /usr/lib/node, we could put them in +/usr/lib/node_modules/<name>/<version>. Then node will not bother +looking for missing dependencies in /usr/node_modules or /node_modules. + +

+

In order to make modules available to the node REPL, it might be useful to +also add the /usr/lib/node_modules folder to the $NODE_PATH environment +variable. Since the module lookups using node_modules folders are all +relative, and based on the real path of the files making the calls to +require(), the packages themselves can be anywhere. + +

+

Addons#

+

Addons are dynamically linked shared objects. They can provide glue to C and +C++ libraries. The API (at the moment) is rather complex, involving +knowledge of several libraries: + +

+
    +
  • V8 JavaScript, a C++ library. Used for interfacing with JavaScript: +creating objects, calling functions, etc. Documented mostly in the +v8.h header file (deps/v8/include/v8.h in the Node source tree), +which is also available online.

    +
  • +
  • libuv, C event loop library. Anytime one +needs to wait for a file descriptor to become readable, wait for a timer, or +wait for a signal to received one will need to interface with libuv. That is, +if you perform any I/O, libuv will need to be used.

    +
  • +
  • Internal Node libraries. Most importantly is the node::ObjectWrap +class which you will likely want to derive from.

    +
  • +
  • Others. Look in deps/ for what else is available.

    +
  • +
+

Node statically compiles all its dependencies into the executable. When +compiling your module, you don't need to worry about linking to any of these +libraries. + + +

+

Hello world#

+

To get started let's make a small Addon which is the C++ equivalent of +the following JavaScript code: + +

+
exports.hello = function() { return 'world'; };
+

First we create a file hello.cc: + +

+
#include <node.h>
+#include <v8.h>
+
+using namespace v8;
+
+Handle<Value> Method(const Arguments& args) {
+  HandleScope scope;
+  return scope.Close(String::New("world"));
+}
+
+void init(Handle<Object> target) {
+  target->Set(String::NewSymbol("hello"),
+      FunctionTemplate::New(Method)->GetFunction());
+}
+NODE_MODULE(hello, init)
+

Note that all Node addons must export an initialization function: + +

+
void Initialize (Handle<Object> target);
+NODE_MODULE(module_name, Initialize)
+

There is no semi-colon after NODE_MODULE as it's not a function (see node.h). + +

+

The module_name needs to match the filename of the final binary (minus the +.node suffix). + +

+

The source code needs to be built into hello.node, the binary Addon. To +do this we create a file called binding.gyp which describes the configuration +to build your module in a JSON-like format. This file gets compiled by +node-gyp. + +

+
{
+  "targets": [
+    {
+      "target_name": "hello",
+      "sources": [ "hello.cc" ]
+    }
+  ]
+}
+

The next step is to generate the appropriate project build files for the +current platform. Use node-gyp configure for that. + +

+

Now you will have either a Makefile (on Unix platforms) or a vcxproj file +(on Windows) in the build/ directory. Next invoke the node-gyp build +command. + +

+

Now you have your compiled .node bindings file! The compiled bindings end up +in build/Release/. + +

+

You can now use the binary addon in a Node project hello.js by pointing require to +the recently built hello.node module: + +

+
var addon = require('./build/Release/hello');
+
+console.log(addon.hello()); // 'world'
+

Please see patterns below for further information or +

+

https://github.com/arturadib/node-qt for an example in production. + + +

+

Addon patterns#

+

Below are some addon patterns to help you get started. Consult the online +v8 reference for help with the various v8 +calls, and v8's Embedder's Guide +for an explanation of several concepts used such as handles, scopes, +function templates, etc. + +

+

In order to use these examples you need to compile them using node-gyp. +Create the following binding.gyp file: + +

+
{
+  "targets": [
+    {
+      "target_name": "addon",
+      "sources": [ "addon.cc" ]
+    }
+  ]
+}
+

In cases where there is more than one .cc file, simply add the file name to the +sources array, e.g.: + +

+
"sources": ["addon.cc", "myexample.cc"]
+

Now that you have your binding.gyp ready, you can configure and build the +addon: + +

+
$ node-gyp configure build
+

Function arguments#

+

The following pattern illustrates how to read arguments from JavaScript +function calls and return a result. This is the main and only needed source +addon.cc: + +

+
#define BUILDING_NODE_EXTENSION
+#include <node.h>
+
+using namespace v8;
+
+Handle<Value> Add(const Arguments& args) {
+  HandleScope scope;
+
+  if (args.Length() < 2) {
+    ThrowException(Exception::TypeError(String::New("Wrong number of arguments")));
+    return scope.Close(Undefined());
+  }
+
+  if (!args[0]->IsNumber() || !args[1]->IsNumber()) {
+    ThrowException(Exception::TypeError(String::New("Wrong arguments")));
+    return scope.Close(Undefined());
+  }
+
+  Local<Number> num = Number::New(args[0]->NumberValue() +
+      args[1]->NumberValue());
+  return scope.Close(num);
+}
+
+void Init(Handle<Object> target) {
+  target->Set(String::NewSymbol("add"),
+      FunctionTemplate::New(Add)->GetFunction());
+}
+
+NODE_MODULE(addon, Init)
+

You can test it with the following JavaScript snippet: + +

+
var addon = require('./build/Release/addon');
+
+console.log( 'This should be eight:', addon.add(3,5) );
+

Callbacks#

+

You can pass JavaScript functions to a C++ function and execute them from +there. Here's addon.cc: + +

+
#define BUILDING_NODE_EXTENSION
+#include <node.h>
+
+using namespace v8;
+
+Handle<Value> RunCallback(const Arguments& args) {
+  HandleScope scope;
+
+  Local<Function> cb = Local<Function>::Cast(args[0]);
+  const unsigned argc = 1;
+  Local<Value> argv[argc] = { Local<Value>::New(String::New("hello world")) };
+  cb->Call(Context::GetCurrent()->Global(), argc, argv);
+
+  return scope.Close(Undefined());
+}
+
+void Init(Handle<Object> target) {
+  target->Set(String::NewSymbol("runCallback"),
+      FunctionTemplate::New(RunCallback)->GetFunction());
+}
+
+NODE_MODULE(addon, Init)
+

To test it run the following JavaScript snippet: + +

+
var addon = require('./build/Release/addon');
+
+addon.runCallback(function(msg){
+  console.log(msg); // 'hello world'
+});
+

Object factory#

+

You can create and return new objects from within a C++ function with this +addon.cc pattern, which returns an object with property msg that echoes +the string passed to createObject(): + +

+
#define BUILDING_NODE_EXTENSION
+#include <node.h>
+
+using namespace v8;
+
+Handle<Value> CreateObject(const Arguments& args) {
+  HandleScope scope;
+
+  Local<Object> obj = Object::New();
+  obj->Set(String::NewSymbol("msg"), args[0]->ToString());
+
+  return scope.Close(obj);
+}
+
+void Init(Handle<Object> target) {
+  target->Set(String::NewSymbol("createObject"),
+      FunctionTemplate::New(CreateObject)->GetFunction());
+}
+
+NODE_MODULE(addon, Init)
+

To test it in JavaScript: + +

+
var addon = require('./build/Release/addon');
+
+var obj1 = addon.createObject('hello');
+var obj2 = addon.createObject('world');
+console.log(obj1.msg+' '+obj2.msg); // 'hello world'
+

Function factory#

+

This pattern illustrates how to create and return a JavaScript function that +wraps a C++ function: + +

+
#define BUILDING_NODE_EXTENSION
+#include <node.h>
+
+using namespace v8;
+
+Handle<Value> MyFunction(const Arguments& args) {
+  HandleScope scope;
+  return scope.Close(String::New("hello world"));
+}
+
+Handle<Value> CreateFunction(const Arguments& args) {
+  HandleScope scope;
+
+  Local<FunctionTemplate> tpl = FunctionTemplate::New(MyFunction);
+  Local<Function> fn = tpl->GetFunction();
+  fn->SetName(String::NewSymbol("theFunction")); // omit this to make it anonymous
+
+  return scope.Close(fn);
+}
+
+void Init(Handle<Object> target) {
+  target->Set(String::NewSymbol("createFunction"),
+      FunctionTemplate::New(CreateFunction)->GetFunction());
+}
+
+NODE_MODULE(addon, Init)
+

To test: + +

+
var addon = require('./build/Release/addon');
+
+var fn = addon.createFunction();
+console.log(fn()); // 'hello world'
+

Wrapping C++ objects#

+

Here we will create a wrapper for a C++ object/class MyObject that can be +instantiated in JavaScript through the new operator. First prepare the main +module addon.cc: + +

+
#define BUILDING_NODE_EXTENSION
+#include <node.h>
+#include "myobject.h"
+
+using namespace v8;
+
+void InitAll(Handle<Object> target) {
+  MyObject::Init(target);
+}
+
+NODE_MODULE(addon, InitAll)
+

Then in myobject.h make your wrapper inherit from node::ObjectWrap: + +

+
#ifndef MYOBJECT_H
+#define MYOBJECT_H
+
+#include <node.h>
+
+class MyObject : public node::ObjectWrap {
+ public:
+  static void Init(v8::Handle<v8::Object> target);
+
+ private:
+  MyObject();
+  ~MyObject();
+
+  static v8::Handle<v8::Value> New(const v8::Arguments& args);
+  static v8::Handle<v8::Value> PlusOne(const v8::Arguments& args);
+  double counter_;
+};
+
+#endif
+

And in myobject.cc implement the various methods that you want to expose. +Here we expose the method plusOne by adding it to the constructor's +prototype: + +

+
#define BUILDING_NODE_EXTENSION
+#include <node.h>
+#include "myobject.h"
+
+using namespace v8;
+
+MyObject::MyObject() {};
+MyObject::~MyObject() {};
+
+void MyObject::Init(Handle<Object> target) {
+  // Prepare constructor template
+  Local<FunctionTemplate> tpl = FunctionTemplate::New(New);
+  tpl->SetClassName(String::NewSymbol("MyObject"));
+  tpl->InstanceTemplate()->SetInternalFieldCount(1);
+  // Prototype
+  tpl->PrototypeTemplate()->Set(String::NewSymbol("plusOne"),
+      FunctionTemplate::New(PlusOne)->GetFunction());
+
+  Persistent<Function> constructor = Persistent<Function>::New(tpl->GetFunction());
+  target->Set(String::NewSymbol("MyObject"), constructor);
+}
+
+Handle<Value> MyObject::New(const Arguments& args) {
+  HandleScope scope;
+
+  MyObject* obj = new MyObject();
+  obj->counter_ = args[0]->IsUndefined() ? 0 : args[0]->NumberValue();
+  obj->Wrap(args.This());
+
+  return args.This();
+}
+
+Handle<Value> MyObject::PlusOne(const Arguments& args) {
+  HandleScope scope;
+
+  MyObject* obj = ObjectWrap::Unwrap<MyObject>(args.This());
+  obj->counter_ += 1;
+
+  return scope.Close(Number::New(obj->counter_));
+}
+

Test it with: + +

+
var addon = require('./build/Release/addon');
+
+var obj = new addon.MyObject(10);
+console.log( obj.plusOne() ); // 11
+console.log( obj.plusOne() ); // 12
+console.log( obj.plusOne() ); // 13
+

Factory of wrapped objects#

+

This is useful when you want to be able to create native objects without +explicitly instantiating them with the new operator in JavaScript, e.g. + +

+
var obj = addon.createObject();
+// instead of:
+// var obj = new addon.Object();
+

Let's register our createObject method in addon.cc: + +

+
#define BUILDING_NODE_EXTENSION
+#include <node.h>
+#include "myobject.h"
+
+using namespace v8;
+
+Handle<Value> CreateObject(const Arguments& args) {
+  HandleScope scope;
+  return scope.Close(MyObject::NewInstance(args));
+}
+
+void InitAll(Handle<Object> target) {
+  MyObject::Init();
+
+  target->Set(String::NewSymbol("createObject"),
+      FunctionTemplate::New(CreateObject)->GetFunction());
+}
+
+NODE_MODULE(addon, InitAll)
+

In myobject.h we now introduce the static method NewInstance that takes +care of instantiating the object (i.e. it does the job of new in JavaScript): + +

+
#define BUILDING_NODE_EXTENSION
+#ifndef MYOBJECT_H
+#define MYOBJECT_H
+
+#include <node.h>
+
+class MyObject : public node::ObjectWrap {
+ public:
+  static void Init();
+  static v8::Handle<v8::Value> NewInstance(const v8::Arguments& args);
+
+ private:
+  MyObject();
+  ~MyObject();
+
+  static v8::Persistent<v8::Function> constructor;
+  static v8::Handle<v8::Value> New(const v8::Arguments& args);
+  static v8::Handle<v8::Value> PlusOne(const v8::Arguments& args);
+  double counter_;
+};
+
+#endif
+

The implementation is similar to the above in myobject.cc: + +

+
#define BUILDING_NODE_EXTENSION
+#include <node.h>
+#include "myobject.h"
+
+using namespace v8;
+
+MyObject::MyObject() {};
+MyObject::~MyObject() {};
+
+Persistent<Function> MyObject::constructor;
+
+void MyObject::Init() {
+  // Prepare constructor template
+  Local<FunctionTemplate> tpl = FunctionTemplate::New(New);
+  tpl->SetClassName(String::NewSymbol("MyObject"));
+  tpl->InstanceTemplate()->SetInternalFieldCount(1);
+  // Prototype
+  tpl->PrototypeTemplate()->Set(String::NewSymbol("plusOne"),
+      FunctionTemplate::New(PlusOne)->GetFunction());
+
+  constructor = Persistent<Function>::New(tpl->GetFunction());
+}
+
+Handle<Value> MyObject::New(const Arguments& args) {
+  HandleScope scope;
+
+  MyObject* obj = new MyObject();
+  obj->counter_ = args[0]->IsUndefined() ? 0 : args[0]->NumberValue();
+  obj->Wrap(args.This());
+
+  return args.This();
+}
+
+Handle<Value> MyObject::NewInstance(const Arguments& args) {
+  HandleScope scope;
+
+  const unsigned argc = 1;
+  Handle<Value> argv[argc] = { args[0] };
+  Local<Object> instance = constructor->NewInstance(argc, argv);
+
+  return scope.Close(instance);
+}
+
+Handle<Value> MyObject::PlusOne(const Arguments& args) {
+  HandleScope scope;
+
+  MyObject* obj = ObjectWrap::Unwrap<MyObject>(args.This());
+  obj->counter_ += 1;
+
+  return scope.Close(Number::New(obj->counter_));
+}
+

Test it with: + +

+
var addon = require('./build/Release/addon');
+
+var obj = addon.createObject(10);
+console.log( obj.plusOne() ); // 11
+console.log( obj.plusOne() ); // 12
+console.log( obj.plusOne() ); // 13
+
+var obj2 = addon.createObject(20);
+console.log( obj2.plusOne() ); // 21
+console.log( obj2.plusOne() ); // 22
+console.log( obj2.plusOne() ); // 23
+

Passing wrapped objects around#

+

In addition to wrapping and returning C++ objects, you can pass them around +by unwrapping them with Node's node::ObjectWrap::Unwrap helper function. +In the following addon.cc we introduce a function add() that can take on two +MyObject objects: + +

+
#define BUILDING_NODE_EXTENSION
+#include <node.h>
+#include "myobject.h"
+
+using namespace v8;
+
+Handle<Value> CreateObject(const Arguments& args) {
+  HandleScope scope;
+  return scope.Close(MyObject::NewInstance(args));
+}
+
+Handle<Value> Add(const Arguments& args) {
+  HandleScope scope;
+
+  MyObject* obj1 = node::ObjectWrap::Unwrap<MyObject>(
+      args[0]->ToObject());
+  MyObject* obj2 = node::ObjectWrap::Unwrap<MyObject>(
+      args[1]->ToObject());
+
+  double sum = obj1->Val() + obj2->Val();
+  return scope.Close(Number::New(sum));
+}
+
+void InitAll(Handle<Object> target) {
+  MyObject::Init();
+
+  target->Set(String::NewSymbol("createObject"),
+      FunctionTemplate::New(CreateObject)->GetFunction());
+
+  target->Set(String::NewSymbol("add"),
+      FunctionTemplate::New(Add)->GetFunction());
+}
+
+NODE_MODULE(addon, InitAll)
+

To make things interesting we introduce a public method in myobject.h so we +can probe private values after unwrapping the object: + +

+
#define BUILDING_NODE_EXTENSION
+#ifndef MYOBJECT_H
+#define MYOBJECT_H
+
+#include <node.h>
+
+class MyObject : public node::ObjectWrap {
+ public:
+  static void Init();
+  static v8::Handle<v8::Value> NewInstance(const v8::Arguments& args);
+  double Val() const { return val_; }
+
+ private:
+  MyObject();
+  ~MyObject();
+
+  static v8::Persistent<v8::Function> constructor;
+  static v8::Handle<v8::Value> New(const v8::Arguments& args);
+  double val_;
+};
+
+#endif
+

The implementation of myobject.cc is similar as before: + +

+
#define BUILDING_NODE_EXTENSION
+#include <node.h>
+#include "myobject.h"
+
+using namespace v8;
+
+MyObject::MyObject() {};
+MyObject::~MyObject() {};
+
+Persistent<Function> MyObject::constructor;
+
+void MyObject::Init() {
+  // Prepare constructor template
+  Local<FunctionTemplate> tpl = FunctionTemplate::New(New);
+  tpl->SetClassName(String::NewSymbol("MyObject"));
+  tpl->InstanceTemplate()->SetInternalFieldCount(1);
+
+  constructor = Persistent<Function>::New(tpl->GetFunction());
+}
+
+Handle<Value> MyObject::New(const Arguments& args) {
+  HandleScope scope;
+
+  MyObject* obj = new MyObject();
+  obj->val_ = args[0]->IsUndefined() ? 0 : args[0]->NumberValue();
+  obj->Wrap(args.This());
+
+  return args.This();
+}
+
+Handle<Value> MyObject::NewInstance(const Arguments& args) {
+  HandleScope scope;
+
+  const unsigned argc = 1;
+  Handle<Value> argv[argc] = { args[0] };
+  Local<Object> instance = constructor->NewInstance(argc, argv);
+
+  return scope.Close(instance);
+}
+

Test it with: + +

+
var addon = require('./build/Release/addon');
+
+var obj1 = addon.createObject(10);
+var obj2 = addon.createObject(20);
+var result = addon.add(obj1, obj2);
+
+console.log(result); // 30
+

process#

+ + +

The process object is a global object and can be accessed from anywhere. +It is an instance of EventEmitter. + + +

+

Event: 'exit'#

+

Emitted when the process is about to exit. This is a good hook to perform +constant time checks of the module's state (like for unit tests). The main +event loop will no longer be run after the 'exit' callback finishes, so +timers may not be scheduled. + +

+

Example of listening for exit: + +

+
process.on('exit', function () {
+  process.nextTick(function () {
+   console.log('This will not run');
+  });
+  console.log('About to exit.');
+});
+

Event: 'uncaughtException'#

+

Emitted when an exception bubbles all the way back to the event loop. If a +listener is added for this exception, the default action (which is to print +a stack trace and exit) will not occur. + +

+

Example of listening for uncaughtException: + +

+
process.on('uncaughtException', function (err) {
+  console.log('Caught exception: ' + err);
+});
+
+setTimeout(function () {
+  console.log('This will still run.');
+}, 500);
+
+// Intentionally cause an exception, but don't catch it.
+nonexistentFunc();
+console.log('This will not run.');
+

Note that uncaughtException is a very crude mechanism for exception +handling and may be removed in the future. + +

+

Don't use it, use domains instead. If you do use it, restart +your application after every unhandled exception! + +

+

Do not use it as the node.js equivalent of On Error Resume Next. An +unhandled exception means your application - and by extension node.js itself - +is in an undefined state. Blindly resuming means anything could happen. + +

+

Think of resuming as pulling the power cord when you are upgrading your system. +Nine out of ten times nothing happens - but the 10th time, your system is bust. + +

+

You have been warned. + +

+

Signal Events#

+ + + +

Emitted when the processes receives a signal. See sigaction(2) for a list of +standard POSIX signal names such as SIGINT, SIGUSR1, etc. + +

+

Example of listening for SIGINT: + +

+
// Start reading from stdin so we don't exit.
+process.stdin.resume();
+
+process.on('SIGINT', function () {
+  console.log('Got SIGINT.  Press Control-D to exit.');
+});
+

An easy way to send the SIGINT signal is with Control-C in most terminal +programs. + + +

+

process.stdout#

+

A Writable Stream to stdout. + +

+

Example: the definition of console.log + +

+
console.log = function (d) {
+  process.stdout.write(d + '\n');
+};
+

process.stderr and process.stdout are unlike other streams in Node in +that writes to them are usually blocking. They are blocking in the case +that they refer to regular files or TTY file descriptors. In the case they +refer to pipes, they are non-blocking like other streams. + + +

+

process.stderr#

+

A writable stream to stderr. + +

+

process.stderr and process.stdout are unlike other streams in Node in +that writes to them are usually blocking. They are blocking in the case +that they refer to regular files or TTY file descriptors. In the case they +refer to pipes, they are non-blocking like other streams. + + +

+

process.stdin#

+

A Readable Stream for stdin. The stdin stream is paused by default, so one +must call process.stdin.resume() to read from it. + +

+

Example of opening standard input and listening for both events: + +

+
process.stdin.resume();
+process.stdin.setEncoding('utf8');
+
+process.stdin.on('data', function (chunk) {
+  process.stdout.write('data: ' + chunk);
+});
+
+process.stdin.on('end', function () {
+  process.stdout.write('end');
+});
+

process.argv#

+

An array containing the command line arguments. The first element will be +'node', the second element will be the name of the JavaScript file. The +next elements will be any additional command line arguments. + +

+
// print process.argv
+process.argv.forEach(function (val, index, array) {
+  console.log(index + ': ' + val);
+});
+

This will generate: + +

+
$ node process-2.js one two=three four
+0: node
+1: /Users/mjr/work/node/process-2.js
+2: one
+3: two=three
+4: four
+

process.execPath#

+

This is the absolute pathname of the executable that started the process. + +

+

Example: + +

+
/usr/local/bin/node
+

process.abort()#

+

This causes node to emit an abort. This will cause node to exit and +generate a core file. + +

+

process.chdir(directory)#

+

Changes the current working directory of the process or throws an exception if that fails. + +

+
console.log('Starting directory: ' + process.cwd());
+try {
+  process.chdir('/tmp');
+  console.log('New directory: ' + process.cwd());
+}
+catch (err) {
+  console.log('chdir: ' + err);
+}
+

process.cwd()#

+

Returns the current working directory of the process. + +

+
console.log('Current directory: ' + process.cwd());
+

process.env#

+

An object containing the user environment. See environ(7). + + +

+

process.exit([code])#

+

Ends the process with the specified code. If omitted, exit uses the +'success' code 0. + +

+

To exit with a 'failure' code: + +

+
process.exit(1);
+

The shell that executed node should see the exit code as 1. + + +

+

process.getgid()#

+

Note: this function is only available on POSIX platforms (i.e. not Windows) + +

+

Gets the group identity of the process. (See getgid(2).) +This is the numerical group id, not the group name. + +

+
if (process.getgid) {
+  console.log('Current gid: ' + process.getgid());
+}
+

process.setgid(id)#

+

Note: this function is only available on POSIX platforms (i.e. not Windows) + +

+

Sets the group identity of the process. (See setgid(2).) This accepts either +a numerical ID or a groupname string. If a groupname is specified, this method +blocks while resolving it to a numerical ID. + +

+
if (process.getgid && process.setgid) {
+  console.log('Current gid: ' + process.getgid());
+  try {
+    process.setgid(501);
+    console.log('New gid: ' + process.getgid());
+  }
+  catch (err) {
+    console.log('Failed to set gid: ' + err);
+  }
+}
+

process.getuid()#

+

Note: this function is only available on POSIX platforms (i.e. not Windows) + +

+

Gets the user identity of the process. (See getuid(2).) +This is the numerical userid, not the username. + +

+
if (process.getuid) {
+  console.log('Current uid: ' + process.getuid());
+}
+

process.setuid(id)#

+

Note: this function is only available on POSIX platforms (i.e. not Windows) + +

+

Sets the user identity of the process. (See setuid(2).) This accepts either +a numerical ID or a username string. If a username is specified, this method +blocks while resolving it to a numerical ID. + +

+
if (process.getuid && process.setuid) {
+  console.log('Current uid: ' + process.getuid());
+  try {
+    process.setuid(501);
+    console.log('New uid: ' + process.getuid());
+  }
+  catch (err) {
+    console.log('Failed to set uid: ' + err);
+  }
+}
+

process.version#

+

A compiled-in property that exposes NODE_VERSION. + +

+
console.log('Version: ' + process.version);
+

process.versions#

+

A property exposing version strings of node and its dependencies. + +

+
console.log(process.versions);
+

Will output: + +

+
{ node: '0.4.12',
+  v8: '3.1.8.26',
+  ares: '1.7.4',
+  ev: '4.4',
+  openssl: '1.0.0e-fips' }
+

process.config#

+

An Object containing the JavaScript representation of the configure options +that were used to compile the current node executable. This is the same as +the "config.gypi" file that was produced when running the ./configure script. + +

+

An example of the possible output looks like: + +

+
{ target_defaults:
+   { cflags: [],
+     default_configuration: 'Release',
+     defines: [],
+     include_dirs: [],
+     libraries: [] },
+  variables:
+   { host_arch: 'x64',
+     node_install_npm: 'true',
+     node_install_waf: 'true',
+     node_prefix: '',
+     node_shared_v8: 'false',
+     node_shared_zlib: 'false',
+     node_use_dtrace: 'false',
+     node_use_openssl: 'true',
+     node_shared_openssl: 'false',
+     strict_aliasing: 'true',
+     target_arch: 'x64',
+     v8_use_snapshot: 'true' } }
+

process.kill(pid, [signal])#

+

Send a signal to a process. pid is the process id and signal is the +string describing the signal to send. Signal names are strings like +'SIGINT' or 'SIGUSR1'. If omitted, the signal will be 'SIGTERM'. +See kill(2) for more information. + +

+

Note that just because the name of this function is process.kill, it is +really just a signal sender, like the kill system call. The signal sent +may do something other than kill the target process. + +

+

Example of sending a signal to yourself: + +

+
process.on('SIGHUP', function () {
+  console.log('Got SIGHUP signal.');
+});
+
+setTimeout(function () {
+  console.log('Exiting.');
+  process.exit(0);
+}, 100);
+
+process.kill(process.pid, 'SIGHUP');
+

process.pid#

+

The PID of the process. + +

+
console.log('This process is pid ' + process.pid);
+

process.title#

+

Getter/setter to set what is displayed in 'ps'. + + +

+

process.arch#

+

What processor architecture you're running on: 'arm', 'ia32', or 'x64'. + +

+
console.log('This processor architecture is ' + process.arch);
+

process.platform#

+

What platform you're running on: +'darwin', 'freebsd', 'linux', 'sunos' or 'win32' + +

+
console.log('This platform is ' + process.platform);
+

process.memoryUsage()#

+

Returns an object describing the memory usage of the Node process +measured in bytes. + +

+
var util = require('util');
+
+console.log(util.inspect(process.memoryUsage()));
+

This will generate: + +

+
{ rss: 4935680,
+  heapTotal: 1826816,
+  heapUsed: 650472 }
+

heapTotal and heapUsed refer to V8's memory usage. + + +

+

process.nextTick(callback)#

+

On the next loop around the event loop call this callback. +This is not a simple alias to setTimeout(fn, 0), it's much more +efficient. + +

+
process.nextTick(function () {
+  console.log('nextTick callback');
+});
+

process.umask([mask])#

+

Sets or reads the process's file mode creation mask. Child processes inherit +the mask from the parent process. Returns the old mask if mask argument is +given, otherwise returns the current mask. + +

+
var oldmask, newmask = 0644;
+
+oldmask = process.umask(newmask);
+console.log('Changed umask from: ' + oldmask.toString(8) +
+            ' to ' + newmask.toString(8));
+

process.uptime()#

+

Number of seconds Node has been running. + + +

+

process.hrtime()#

+

Returns the current high-resolution real time in a [seconds, nanoseconds] +tuple Array. It is relative to an arbitrary time in the past. It is not +related to the time of day and therefore not subject to clock drift. The +primary use is for measuring performance between intervals. + +

+

You may pass in the result of a previous call to process.hrtime() to get +a diff reading, useful for benchmarks and measuring intervals: + +

+
var time = process.hrtime();
+// [ 1800216, 927643717 ]
+
+setTimeout(function () {
+  var diff = process.hrtime(time);
+  // [ 1, 6962306 ]
+
+  console.log('benchmark took %d seconds and %d nanoseconds',
+              diff[0], diff[1]);
+  // benchmark took 1 seconds and 6962306 nanoseconds
+}, 1000);
+

util#

+
Stability: 5 - Locked
+

These functions are in the module 'util'. Use require('util') to access +them. + + +

+

util.format(format, [...])#

+

Returns a formatted string using the first argument as a printf-like format. + +

+

The first argument is a string that contains zero or more placeholders. +Each placeholder is replaced with the converted value from its corresponding +argument. Supported placeholders are: + +

+
    +
  • %s - String.
  • +
  • %d - Number (both integer and float).
  • +
  • %j - JSON.
  • +
  • % - single percent sign ('%'). This does not consume an argument.
  • +
+

If the placeholder does not have a corresponding argument, the placeholder is +not replaced. + +

+
util.format('%s:%s', 'foo'); // 'foo:%s'
+

If there are more arguments than placeholders, the extra arguments are +converted to strings with util.inspect() and these strings are concatenated, +delimited by a space. + +

+
util.format('%s:%s', 'foo', 'bar', 'baz'); // 'foo:bar baz'
+

If the first argument is not a format string then util.format() returns +a string that is the concatenation of all its arguments separated by spaces. +Each argument is converted to a string with util.inspect(). + +

+
util.format(1, 2, 3); // '1 2 3'
+

util.debug(string)#

+

A synchronous output function. Will block the process and +output string immediately to stderr. + +

+
require('util').debug('message on stderr');
+

util.error([...])#

+

Same as util.debug() except this will output all arguments immediately to +stderr. + +

+

util.puts([...])#

+

A synchronous output function. Will block the process and output all arguments +to stdout with newlines after each argument. + +

+

util.print([...])#

+

A synchronous output function. Will block the process, cast each argument to a +string then output to stdout. Does not place newlines after each argument. + +

+

util.log(string)#

+

Output with timestamp on stdout. + +

+
require('util').log('Timestamped message.');
+

util.inspect(object, [showHidden], [depth], [colors])#

+

Return a string representation of object, which is useful for debugging. + +

+

If showHidden is true, then the object's non-enumerable properties will be +shown too. Defaults to false. + +

+

If depth is provided, it tells inspect how many times to recurse while +formatting the object. This is useful for inspecting large complicated objects. + +

+

The default is to only recurse twice. To make it recurse indefinitely, pass +in null for depth. + +

+

If colors is true, the output will be styled with ANSI color codes. +Defaults to false. + +

+

Example of inspecting all properties of the util object: + +

+
var util = require('util');
+
+console.log(util.inspect(util, true, null));
+

Objects also may define their own inspect(depth) function which util.inspect() +will invoke and use the result of when inspecting the object: + +

+
var util = require('util');
+
+var obj = { name: 'nate' };
+obj.inspect = function(depth) {
+  return '{' + this.name + '}';
+};
+
+util.inspect(obj);
+  // "{nate}"
+

util.isArray(object)#

+

Returns true if the given "object" is an Array. false otherwise. + +

+
var util = require('util');
+
+util.isArray([])
+  // true
+util.isArray(new Array)
+  // true
+util.isArray({})
+  // false
+

util.isRegExp(object)#

+

Returns true if the given "object" is a RegExp. false otherwise. + +

+
var util = require('util');
+
+util.isRegExp(/some regexp/)
+  // true
+util.isRegExp(new RegExp('another regexp'))
+  // true
+util.isRegExp({})
+  // false
+

util.isDate(object)#

+

Returns true if the given "object" is a Date. false otherwise. + +

+
var util = require('util');
+
+util.isDate(new Date())
+  // true
+util.isDate(Date())
+  // false (without 'new' returns a String)
+util.isDate({})
+  // false
+

util.isError(object)#

+

Returns true if the given "object" is an Error. false otherwise. + +

+
var util = require('util');
+
+util.isError(new Error())
+  // true
+util.isError(new TypeError())
+  // true
+util.isError({ name: 'Error', message: 'an error occurred' })
+  // false
+

util.pump(readableStream, writableStream, [callback])#

+
Stability: 0 - Deprecated: Use readableStream.pipe(writableStream)
+

Read the data from readableStream and send it to the writableStream. +When writableStream.write(data) returns false readableStream will be +paused until the drain event occurs on the writableStream. callback gets +an error as its only argument and is called when writableStream is closed or +when an error occurs. + + +

+

util.inherits(constructor, superConstructor)#

+

Inherit the prototype methods from one +constructor +into another. The prototype of constructor will be set to a new +object created from superConstructor. + +

+

As an additional convenience, superConstructor will be accessible +through the constructor.super_ property. + +

+
var util = require("util");
+var events = require("events");
+
+function MyStream() {
+    events.EventEmitter.call(this);
+}
+
+util.inherits(MyStream, events.EventEmitter);
+
+MyStream.prototype.write = function(data) {
+    this.emit("data", data);
+}
+
+var stream = new MyStream();
+
+console.log(stream instanceof events.EventEmitter); // true
+console.log(MyStream.super_ === events.EventEmitter); // true
+
+stream.on("data", function(data) {
+    console.log('Received data: "' + data + '"');
+})
+stream.write("It works!"); // Received data: "It works!"
+

Events#

+
Stability: 4 - API Frozen
+ + +

Many objects in Node emit events: a net.Server emits an event each time +a peer connects to it, a fs.readStream emits an event when the file is +opened. All objects which emit events are instances of events.EventEmitter. +You can access this module by doing: require("events"); + +

+

Typically, event names are represented by a camel-cased string, however, +there aren't any strict restrictions on that, as any string will be accepted. + +

+

Functions can then be attached to objects, to be executed when an event +is emitted. These functions are called listeners. + + +

+

Class: events.EventEmitter#

+

To access the EventEmitter class, require('events').EventEmitter. + +

+

When an EventEmitter instance experiences an error, the typical action is +to emit an 'error' event. Error events are treated as a special case in node. +If there is no listener for it, then the default action is to print a stack +trace and exit the program. + +

+

All EventEmitters emit the event 'newListener' when new listeners are +added. + +

+

emitter.addListener(event, listener)#

+

emitter.on(event, listener)#

+

Adds a listener to the end of the listeners array for the specified event. + +

+
server.on('connection', function (stream) {
+  console.log('someone connected!');
+});
+

emitter.once(event, listener)#

+

Adds a one time listener for the event. This listener is +invoked only the next time the event is fired, after which +it is removed. + +

+
server.once('connection', function (stream) {
+  console.log('Ah, we have our first user!');
+});
+

emitter.removeListener(event, listener)#

+

Remove a listener from the listener array for the specified event. +Caution: changes array indices in the listener array behind the listener. + +

+
var callback = function(stream) {
+  console.log('someone connected!');
+};
+server.on('connection', callback);
+// ...
+server.removeListener('connection', callback);
+

emitter.removeAllListeners([event])#

+

Removes all listeners, or those of the specified event. + +

+

Note that this will invalidate any arrays that have previously been +returned by emitter.listeners(event). + + +

+

emitter.setMaxListeners(n)#

+

By default EventEmitters will print a warning if more than 10 listeners are +added for a particular event. This is a useful default which helps finding memory leaks. +Obviously not all Emitters should be limited to 10. This function allows +that to be increased. Set to zero for unlimited. + + +

+

emitter.listeners(event)#

+

Returns an array of listeners for the specified event. + +

+
server.on('connection', function (stream) {
+  console.log('someone connected!');
+});
+console.log(util.inspect(server.listeners('connection'))); // [ [Function] ]
+

This array may be a mutable reference to the same underlying list of +listeners that is used by the event subsystem. However, certain +actions (specifically, removeAllListeners) will invalidate this +reference. + +

+

If you would like to get a copy of the listeners at a specific point in +time that is guaranteed not to change, make a copy, for example by doing +emitter.listeners(event).slice(0). + +

+

In a future release of node, this behavior may change to always +return a copy, for consistency. In your programs, please do not rely on +being able to modify the EventEmitter listeners using array methods. +Always use the 'on' method to add new listeners. + +

+

emitter.emit(event, [arg1], [arg2], [...])#

+

Execute each of the listeners in order with the supplied arguments. + +

+

Event: 'newListener'#

+
    +
  • event String The event name
  • +
  • listener Function The event handler function
  • +
+

This event is emitted any time someone adds a new listener. + +

+

Domain#

+
Stability: 1 - Experimental
+

Domains provide a way to handle multiple different IO operations as a +single group. If any of the event emitters or callbacks registered to a +domain emit an error event, or throw an error, then the domain object +will be notified, rather than losing the context of the error in the +process.on('uncaughtException') handler, or causing the program to +exit with an error code. + +

+

This feature is new in Node version 0.8. It is a first pass, and is +expected to change significantly in future versions. Please use it and +provide feedback. + +

+

Due to their experimental nature, the Domains features are disabled unless +the domain module is loaded at least once. No domains are created or +registered by default. This is by design, to prevent adverse effects on +current programs. It is expected to be enabled by default in future +Node.js versions. + +

+

Additions to Error objects#

+ + +

Any time an Error object is routed through a domain, a few extra fields +are added to it. + +

+
    +
  • error.domain The domain that first handled the error.
  • +
  • error.domain_emitter The event emitter that emitted an 'error' event +with the error object.
  • +
  • error.domain_bound The callback function which was bound to the +domain, and passed an error as its first argument.
  • +
  • error.domain_thrown A boolean indicating whether the error was +thrown, emitted, or passed to a bound callback function.
  • +
+

Implicit Binding#

+ + +

If domains are in use, then all new EventEmitter objects (including +Stream objects, requests, responses, etc.) will be implicitly bound to +the active domain at the time of their creation. + +

+

Additionally, callbacks passed to lowlevel event loop requests (such as +to fs.open, or other callback-taking methods) will automatically be +bound to the active domain. If they throw, then the domain will catch +the error. + +

+

In order to prevent excessive memory usage, Domain objects themselves +are not implicitly added as children of the active domain. If they +were, then it would be too easy to prevent request and response objects +from being properly garbage collected. + +

+

If you want to nest Domain objects as children of a parent Domain, +then you must explicitly add them, and then dispose of them later. + +

+

Implicit binding routes thrown errors and 'error' events to the +Domain's error event, but does not register the EventEmitter on the +Domain, so domain.dispose() will not shut down the EventEmitter. +Implicit binding only takes care of thrown errors and 'error' events. + +

+

Explicit Binding#

+ + +

Sometimes, the domain in use is not the one that ought to be used for a +specific event emitter. Or, the event emitter could have been created +in the context of one domain, but ought to instead be bound to some +other domain. + +

+

For example, there could be one domain in use for an HTTP server, but +perhaps we would like to have a separate domain to use for each request. + +

+

That is possible via explicit binding. + +

+

For example: + +

+
// create a top-level domain for the server
+var serverDomain = domain.create();
+
+serverDomain.run(function() {
+  // server is created in the scope of serverDomain
+  http.createServer(function(req, res) {
+    // req and res are also created in the scope of serverDomain
+    // however, we'd prefer to have a separate domain for each request.
+    // create it first thing, and add req and res to it.
+    var reqd = domain.create();
+    reqd.add(req);
+    reqd.add(res);
+    reqd.on('error', function(er) {
+      console.error('Error', er, req.url);
+      try {
+        res.writeHead(500);
+        res.end('Error occurred, sorry.');
+        res.on('close', function() {
+          // forcibly shut down any other things added to this domain
+          reqd.dispose();
+        });
+      } catch (er) {
+        console.error('Error sending 500', er, req.url);
+        // tried our best.  clean up anything remaining.
+        reqd.dispose();
+      }
+    });
+  }).listen(1337);
+});
+

domain.create()#

+
    +
  • return: Domain
  • +
+

Returns a new Domain object. + +

+

Class: Domain#

+

The Domain class encapsulates the functionality of routing errors and +uncaught exceptions to the active Domain object. + +

+

Domain is a child class of EventEmitter. To handle the errors that it +catches, listen to its error event. + +

+

domain.run(fn)#

+
    +
  • fn Function
  • +
+

Run the supplied function in the context of the domain, implicitly +binding all event emitters, timers, and lowlevel requests that are +created in that context. + +

+

This is the most basic way to use a domain. + +

+

Example: + +

+
var d = domain.create();
+d.on('error', function(er) {
+  console.error('Caught error!', er);
+});
+d.run(function() {
+  process.nextTick(function() {
+    setTimeout(function() { // simulating some various async stuff
+      fs.open('non-existent file', 'r', function(er, fd) {
+        if (er) throw er;
+        // proceed...
+      });
+    }, 100);
+  });
+});
+

In this example, the d.on('error') handler will be triggered, rather +than crashing the program. + +

+

domain.members#

+
    +
  • Array
  • +
+

An array of timers and event emitters that have been explicitly added +to the domain. + +

+

domain.add(emitter)#

+
    +
  • emitter EventEmitter | Timer emitter or timer to be added to the domain
  • +
+

Explicitly adds an emitter to the domain. If any event handlers called by +the emitter throw an error, or if the emitter emits an error event, it +will be routed to the domain's error event, just like with implicit +binding. + +

+

This also works with timers that are returned from setInterval and +setTimeout. If their callback function throws, it will be caught by +the domain 'error' handler. + +

+

If the Timer or EventEmitter was already bound to a domain, it is removed +from that one, and bound to this one instead. + +

+

domain.remove(emitter)#

+
    +
  • emitter EventEmitter | Timer emitter or timer to be removed from the domain
  • +
+

The opposite of domain.add(emitter). Removes domain handling from the +specified emitter. + +

+

domain.bind(callback)#

+
    +
  • callback Function The callback function
  • +
  • return: Function The bound function
  • +
+

The returned function will be a wrapper around the supplied callback +function. When the returned function is called, any errors that are +thrown will be routed to the domain's error event. + +

+

Example#

+
var d = domain.create();
+
+function readSomeFile(filename, cb) {
+  fs.readFile(filename, 'utf8', d.bind(function(er, data) {
+    // if this throws, it will also be passed to the domain
+    return cb(er, data ? JSON.parse(data) : null);
+  }));
+}
+
+d.on('error', function(er) {
+  // an error occurred somewhere.
+  // if we throw it now, it will crash the program
+  // with the normal line number and stack message.
+});
+

domain.intercept(callback)#

+
    +
  • callback Function The callback function
  • +
  • return: Function The intercepted function
  • +
+

This method is almost identical to domain.bind(callback). However, in +addition to catching thrown errors, it will also intercept Error +objects sent as the first argument to the function. + +

+

In this way, the common if (er) return callback(er); pattern can be replaced +with a single error handler in a single place. + +

+

Example#

+
var d = domain.create();
+
+function readSomeFile(filename, cb) {
+  fs.readFile(filename, 'utf8', d.intercept(function(data) {
+    // note, the first argument is never passed to the
+    // callback since it is assumed to be the 'Error' argument
+    // and thus intercepted by the domain.
+
+    // if this throws, it will also be passed to the domain
+    // so the error-handling logic can be moved to the 'error'
+    // event on the domain instead of being repeated throughout
+    // the program.
+    return cb(null, JSON.parse(data));
+  }));
+}
+
+d.on('error', function(er) {
+  // an error occurred somewhere.
+  // if we throw it now, it will crash the program
+  // with the normal line number and stack message.
+});
+

domain.dispose()#

+

The dispose method destroys a domain, and makes a best effort attempt to +clean up any and all IO that is associated with the domain. Streams are +aborted, ended, closed, and/or destroyed. Timers are cleared. +Explicitly bound callbacks are no longer called. Any error events that +are raised as a result of this are ignored. + +

+

The intention of calling dispose is generally to prevent cascading +errors when a critical part of the Domain context is found to be in an +error state. + +

+

Once the domain is disposed the dispose event will emit. + +

+

Note that IO might still be performed. However, to the highest degree +possible, once a domain is disposed, further errors from the emitters in +that set will be ignored. So, even if some remaining actions are still +in flight, Node.js will not communicate further about them. + +

+

Buffer#

+
Stability: 3 - Stable
+

Pure JavaScript is Unicode friendly but not nice to binary data. When +dealing with TCP streams or the file system, it's necessary to handle octet +streams. Node has several strategies for manipulating, creating, and +consuming octet streams. + +

+

Raw data is stored in instances of the Buffer class. A Buffer is similar +to an array of integers but corresponds to a raw memory allocation outside +the V8 heap. A Buffer cannot be resized. + +

+

The Buffer class is a global, making it very rare that one would need +to ever require('buffer'). + +

+

Converting between Buffers and JavaScript string objects requires an explicit +encoding method. Here are the different string encodings. + +

+
    +
  • 'ascii' - for 7 bit ASCII data only. This encoding method is very fast, and +will strip the high bit if set. +Note that this encoding converts a null character ('\0' or '\u0000') into +0x20 (character code of a space). If you want to convert a null character +into 0x00, you should use 'utf8'.

    +
  • +
  • 'utf8' - Multibyte encoded Unicode characters. Many web pages and other +document formats use UTF-8.

    +
  • +
  • 'utf16le' - 2 or 4 bytes, little endian encoded Unicode characters. +Surrogate pairs (U+10000 to U+10FFFF) are supported.

    +
  • +
  • 'ucs2' - Alias of 'utf16le'.

    +
  • +
  • 'base64' - Base64 string encoding.

    +
  • +
  • 'binary' - A way of encoding raw binary data into strings by using only +the first 8 bits of each character. This encoding method is deprecated and +should be avoided in favor of Buffer objects where possible. This encoding +will be removed in future versions of Node.

    +
  • +
  • 'hex' - Encode each byte as two hexadecimal characters.

    +
  • +
+

Class: Buffer#

+

The Buffer class is a global type for dealing with binary data directly. +It can be constructed in a variety of ways. + +

+

new Buffer(size)#

+
    +
  • size Number
  • +
+

Allocates a new buffer of size octets. + +

+

new Buffer(array)#

+
    +
  • array Array
  • +
+

Allocates a new buffer using an array of octets. + +

+

new Buffer(str, [encoding])#

+
    +
  • str String - string to encode.
  • +
  • encoding String - encoding to use, Optional.
  • +
+

Allocates a new buffer containing the given str. +encoding defaults to 'utf8'. + +

+

buf.write(string, [offset], [length], [encoding])#

+
    +
  • string String - data to be written to buffer
  • +
  • offset Number, Optional, Default: 0
  • +
  • length Number, Optional, Default: buffer.length - offset
  • +
  • encoding String, Optional, Default: 'utf8'
  • +
+

Writes string to the buffer at offset using the given encoding. +offset defaults to 0, encoding defaults to 'utf8'. length is +the number of bytes to write. Returns number of octets written. If buffer did +not contain enough space to fit the entire string, it will write a partial +amount of the string. length defaults to buffer.length - offset. +The method will not write partial characters. + +

+
buf = new Buffer(256);
+len = buf.write('\u00bd + \u00bc = \u00be', 0);
+console.log(len + " bytes: " + buf.toString('utf8', 0, len));
+

The number of characters written (which may be different than the number of +bytes written) is set in Buffer._charsWritten and will be overwritten the +next time buf.write() is called. + + +

+

buf.toString([encoding], [start], [end])#

+
    +
  • encoding String, Optional, Default: 'utf8'
  • +
  • start Number, Optional, Default: 0
  • +
  • end Number, Optional, Default: buffer.length
  • +
+

Decodes and returns a string from buffer data encoded with encoding +(defaults to 'utf8') beginning at start (defaults to 0) and ending at +end (defaults to buffer.length). + +

+

See buffer.write() example, above. + + +

+

buf[index]#

+ + + +

Get and set the octet at index. The values refer to individual bytes, +so the legal range is between 0x00 and 0xFF hex or 0 and 255. + +

+

Example: copy an ASCII string into a buffer, one byte at a time: + +

+
str = "node.js";
+buf = new Buffer(str.length);
+
+for (var i = 0; i < str.length ; i++) {
+  buf[i] = str.charCodeAt(i);
+}
+
+console.log(buf);
+
+// node.js
+

Class Method: Buffer.isBuffer(obj)#

+
    +
  • obj Object
  • +
  • Return: Boolean
  • +
+

Tests if obj is a Buffer. + +

+

Class Method: Buffer.byteLength(string, [encoding])#

+
    +
  • string String
  • +
  • encoding String, Optional, Default: 'utf8'
  • +
  • Return: Number
  • +
+

Gives the actual byte length of a string. encoding defaults to 'utf8'. +This is not the same as String.prototype.length since that returns the +number of characters in a string. + +

+

Example: + +

+
str = '\u00bd + \u00bc = \u00be';
+
+console.log(str + ": " + str.length + " characters, " +
+  Buffer.byteLength(str, 'utf8') + " bytes");
+
+// ½ + ¼ = ¾: 9 characters, 12 bytes
+

Class Method: Buffer.concat(list, [totalLength])#

+
    +
  • list Array List of Buffer objects to concat
  • +
  • totalLength Number Total length of the buffers when concatenated
  • +
+

Returns a buffer which is the result of concatenating all the buffers in +the list together. + +

+

If the list has no items, or if the totalLength is 0, then it returns a +zero-length buffer. + +

+

If the list has exactly one item, then the first item of the list is +returned. + +

+

If the list has more than one item, then a new Buffer is created. + +

+

If totalLength is not provided, it is read from the buffers in the list. +However, this adds an additional loop to the function, so it is faster +to provide the length explicitly. + +

+

buf.length#

+
    +
  • Number
  • +
+

The size of the buffer in bytes. Note that this is not necessarily the size +of the contents. length refers to the amount of memory allocated for the +buffer object. It does not change when the contents of the buffer are changed. + +

+
buf = new Buffer(1234);
+
+console.log(buf.length);
+buf.write("some string", 0, "ascii");
+console.log(buf.length);
+
+// 1234
+// 1234
+

buf.copy(targetBuffer, [targetStart], [sourceStart], [sourceEnd])#

+
    +
  • targetBuffer Buffer object - Buffer to copy into
  • +
  • targetStart Number, Optional, Default: 0
  • +
  • sourceStart Number, Optional, Default: 0
  • +
  • sourceEnd Number, Optional, Default: buffer.length
  • +
+

Does copy between buffers. The source and target regions can be overlapped. +targetStart and sourceStart default to 0. +sourceEnd defaults to buffer.length. + +

+

Example: build two Buffers, then copy buf1 from byte 16 through byte 19 +into buf2, starting at the 8th byte in buf2. + +

+
buf1 = new Buffer(26);
+buf2 = new Buffer(26);
+
+for (var i = 0 ; i < 26 ; i++) {
+  buf1[i] = i + 97; // 97 is ASCII a
+  buf2[i] = 33; // ASCII !
+}
+
+buf1.copy(buf2, 8, 16, 20);
+console.log(buf2.toString('ascii', 0, 25));
+
+// !!!!!!!!qrst!!!!!!!!!!!!!
+

buf.slice([start], [end])#

+
    +
  • start Number, Optional, Default: 0
  • +
  • end Number, Optional, Default: buffer.length
  • +
+

Returns a new buffer which references the same memory as the old, but offset +and cropped by the start (defaults to 0) and end (defaults to +buffer.length) indexes. + +

+

Modifying the new buffer slice will modify memory in the original buffer! + +

+

Example: build a Buffer with the ASCII alphabet, take a slice, then modify one +byte from the original Buffer. + +

+
var buf1 = new Buffer(26);
+
+for (var i = 0 ; i < 26 ; i++) {
+  buf1[i] = i + 97; // 97 is ASCII a
+}
+
+var buf2 = buf1.slice(0, 3);
+console.log(buf2.toString('ascii', 0, buf2.length));
+buf1[0] = 33;
+console.log(buf2.toString('ascii', 0, buf2.length));
+
+// abc
+// !bc
+

buf.readUInt8(offset, [noAssert])#

+
    +
  • offset Number
  • +
  • noAssert Boolean, Optional, Default: false
  • +
  • Return: Number
  • +
+

Reads an unsigned 8 bit integer from the buffer at the specified offset. + +

+

Set noAssert to true to skip validation of offset. This means that offset +may be beyond the end of the buffer. Defaults to false. + +

+

Example: + +

+
var buf = new Buffer(4);
+
+buf[0] = 0x3;
+buf[1] = 0x4;
+buf[2] = 0x23;
+buf[3] = 0x42;
+
+for (ii = 0; ii < buf.length; ii++) {
+  console.log(buf.readUInt8(ii));
+}
+
+// 0x3
+// 0x4
+// 0x23
+// 0x42
+

buf.readUInt16LE(offset, [noAssert])#

+

buf.readUInt16BE(offset, [noAssert])#

+
    +
  • offset Number
  • +
  • noAssert Boolean, Optional, Default: false
  • +
  • Return: Number
  • +
+

Reads an unsigned 16 bit integer from the buffer at the specified offset with +specified endian format. + +

+

Set noAssert to true to skip validation of offset. This means that offset +may be beyond the end of the buffer. Defaults to false. + +

+

Example: + +

+
var buf = new Buffer(4);
+
+buf[0] = 0x3;
+buf[1] = 0x4;
+buf[2] = 0x23;
+buf[3] = 0x42;
+
+console.log(buf.readUInt16BE(0));
+console.log(buf.readUInt16LE(0));
+console.log(buf.readUInt16BE(1));
+console.log(buf.readUInt16LE(1));
+console.log(buf.readUInt16BE(2));
+console.log(buf.readUInt16LE(2));
+
+// 0x0304
+// 0x0403
+// 0x0423
+// 0x2304
+// 0x2342
+// 0x4223
+

buf.readUInt32LE(offset, [noAssert])#

+

buf.readUInt32BE(offset, [noAssert])#

+
    +
  • offset Number
  • +
  • noAssert Boolean, Optional, Default: false
  • +
  • Return: Number
  • +
+

Reads an unsigned 32 bit integer from the buffer at the specified offset with +specified endian format. + +

+

Set noAssert to true to skip validation of offset. This means that offset +may be beyond the end of the buffer. Defaults to false. + +

+

Example: + +

+
var buf = new Buffer(4);
+
+buf[0] = 0x3;
+buf[1] = 0x4;
+buf[2] = 0x23;
+buf[3] = 0x42;
+
+console.log(buf.readUInt32BE(0));
+console.log(buf.readUInt32LE(0));
+
+// 0x03042342
+// 0x42230403
+

buf.readInt8(offset, [noAssert])#

+
    +
  • offset Number
  • +
  • noAssert Boolean, Optional, Default: false
  • +
  • Return: Number
  • +
+

Reads a signed 8 bit integer from the buffer at the specified offset. + +

+

Set noAssert to true to skip validation of offset. This means that offset +may be beyond the end of the buffer. Defaults to false. + +

+

Works as buffer.readUInt8, except buffer contents are treated as two's +complement signed values. + +

+

buf.readInt16LE(offset, [noAssert])#

+

buf.readInt16BE(offset, [noAssert])#

+
    +
  • offset Number
  • +
  • noAssert Boolean, Optional, Default: false
  • +
  • Return: Number
  • +
+

Reads a signed 16 bit integer from the buffer at the specified offset with +specified endian format. + +

+

Set noAssert to true to skip validation of offset. This means that offset +may be beyond the end of the buffer. Defaults to false. + +

+

Works as buffer.readUInt16*, except buffer contents are treated as two's +complement signed values. + +

+

buf.readInt32LE(offset, [noAssert])#

+

buf.readInt32BE(offset, [noAssert])#

+
    +
  • offset Number
  • +
  • noAssert Boolean, Optional, Default: false
  • +
  • Return: Number
  • +
+

Reads a signed 32 bit integer from the buffer at the specified offset with +specified endian format. + +

+

Set noAssert to true to skip validation of offset. This means that offset +may be beyond the end of the buffer. Defaults to false. + +

+

Works as buffer.readUInt32*, except buffer contents are treated as two's +complement signed values. + +

+

buf.readFloatLE(offset, [noAssert])#

+

buf.readFloatBE(offset, [noAssert])#

+
    +
  • offset Number
  • +
  • noAssert Boolean, Optional, Default: false
  • +
  • Return: Number
  • +
+

Reads a 32 bit float from the buffer at the specified offset with specified +endian format. + +

+

Set noAssert to true to skip validation of offset. This means that offset +may be beyond the end of the buffer. Defaults to false. + +

+

Example: + +

+
var buf = new Buffer(4);
+
+buf[0] = 0x00;
+buf[1] = 0x00;
+buf[2] = 0x80;
+buf[3] = 0x3f;
+
+console.log(buf.readFloatLE(0));
+
+// 0x01
+

buf.readDoubleLE(offset, [noAssert])#

+

buf.readDoubleBE(offset, [noAssert])#

+
    +
  • offset Number
  • +
  • noAssert Boolean, Optional, Default: false
  • +
  • Return: Number
  • +
+

Reads a 64 bit double from the buffer at the specified offset with specified +endian format. + +

+

Set noAssert to true to skip validation of offset. This means that offset +may be beyond the end of the buffer. Defaults to false. + +

+

Example: + +

+
var buf = new Buffer(8);
+
+buf[0] = 0x55;
+buf[1] = 0x55;
+buf[2] = 0x55;
+buf[3] = 0x55;
+buf[4] = 0x55;
+buf[5] = 0x55;
+buf[6] = 0xd5;
+buf[7] = 0x3f;
+
+console.log(buf.readDoubleLE(0));
+
+// 0.3333333333333333
+

buf.writeUInt8(value, offset, [noAssert])#

+
    +
  • value Number
  • +
  • offset Number
  • +
  • noAssert Boolean, Optional, Default: false
  • +
+

Writes value to the buffer at the specified offset. Note, value must be a +valid unsigned 8 bit integer. + +

+

Set noAssert to true to skip validation of value and offset. This means +that value may be too large for the specific function and offset may be +beyond the end of the buffer leading to the values being silently dropped. This +should not be used unless you are certain of correctness. Defaults to false. + +

+

Example: + +

+
var buf = new Buffer(4);
+buf.writeUInt8(0x3, 0);
+buf.writeUInt8(0x4, 1);
+buf.writeUInt8(0x23, 2);
+buf.writeUInt8(0x42, 3);
+
+console.log(buf);
+
+// <Buffer 03 04 23 42>
+

buf.writeUInt16LE(value, offset, [noAssert])#

+

buf.writeUInt16BE(value, offset, [noAssert])#

+
    +
  • value Number
  • +
  • offset Number
  • +
  • noAssert Boolean, Optional, Default: false
  • +
+

Writes value to the buffer at the specified offset with specified endian +format. Note, value must be a valid unsigned 16 bit integer. + +

+

Set noAssert to true to skip validation of value and offset. This means +that value may be too large for the specific function and offset may be +beyond the end of the buffer leading to the values being silently dropped. This +should not be used unless you are certain of correctness. Defaults to false. + +

+

Example: + +

+
var buf = new Buffer(4);
+buf.writeUInt16BE(0xdead, 0);
+buf.writeUInt16BE(0xbeef, 2);
+
+console.log(buf);
+
+buf.writeUInt16LE(0xdead, 0);
+buf.writeUInt16LE(0xbeef, 2);
+
+console.log(buf);
+
+// <Buffer de ad be ef>
+// <Buffer ad de ef be>
+

buf.writeUInt32LE(value, offset, [noAssert])#

+

buf.writeUInt32BE(value, offset, [noAssert])#

+
    +
  • value Number
  • +
  • offset Number
  • +
  • noAssert Boolean, Optional, Default: false
  • +
+

Writes value to the buffer at the specified offset with specified endian +format. Note, value must be a valid unsigned 32 bit integer. + +

+

Set noAssert to true to skip validation of value and offset. This means +that value may be too large for the specific function and offset may be +beyond the end of the buffer leading to the values being silently dropped. This +should not be used unless you are certain of correctness. Defaults to false. + +

+

Example: + +

+
var buf = new Buffer(4);
+buf.writeUInt32BE(0xfeedface, 0);
+
+console.log(buf);
+
+buf.writeUInt32LE(0xfeedface, 0);
+
+console.log(buf);
+
+// <Buffer fe ed fa ce>
+// <Buffer ce fa ed fe>
+

buf.writeInt8(value, offset, [noAssert])#

+
    +
  • value Number
  • +
  • offset Number
  • +
  • noAssert Boolean, Optional, Default: false
  • +
+

Writes value to the buffer at the specified offset. Note, value must be a +valid signed 8 bit integer. + +

+

Set noAssert to true to skip validation of value and offset. This means +that value may be too large for the specific function and offset may be +beyond the end of the buffer leading to the values being silently dropped. This +should not be used unless you are certain of correctness. Defaults to false. + +

+

Works as buffer.writeUInt8, except value is written out as a two's complement +signed integer into buffer. + +

+

buf.writeInt16LE(value, offset, [noAssert])#

+

buf.writeInt16BE(value, offset, [noAssert])#

+
    +
  • value Number
  • +
  • offset Number
  • +
  • noAssert Boolean, Optional, Default: false
  • +
+

Writes value to the buffer at the specified offset with specified endian +format. Note, value must be a valid signed 16 bit integer. + +

+

Set noAssert to true to skip validation of value and offset. This means +that value may be too large for the specific function and offset may be +beyond the end of the buffer leading to the values being silently dropped. This +should not be used unless you are certain of correctness. Defaults to false. + +

+

Works as buffer.writeUInt16*, except value is written out as a two's +complement signed integer into buffer. + +

+

buf.writeInt32LE(value, offset, [noAssert])#

+

buf.writeInt32BE(value, offset, [noAssert])#

+
    +
  • value Number
  • +
  • offset Number
  • +
  • noAssert Boolean, Optional, Default: false
  • +
+

Writes value to the buffer at the specified offset with specified endian +format. Note, value must be a valid signed 32 bit integer. + +

+

Set noAssert to true to skip validation of value and offset. This means +that value may be too large for the specific function and offset may be +beyond the end of the buffer leading to the values being silently dropped. This +should not be used unless you are certain of correctness. Defaults to false. + +

+

Works as buffer.writeUInt32*, except value is written out as a two's +complement signed integer into buffer. + +

+

buf.writeFloatLE(value, offset, [noAssert])#

+

buf.writeFloatBE(value, offset, [noAssert])#

+
    +
  • value Number
  • +
  • offset Number
  • +
  • noAssert Boolean, Optional, Default: false
  • +
+

Writes value to the buffer at the specified offset with specified endian +format. Note, value must be a valid 32 bit float. + +

+

Set noAssert to true to skip validation of value and offset. This means +that value may be too large for the specific function and offset may be +beyond the end of the buffer leading to the values being silently dropped. This +should not be used unless you are certain of correctness. Defaults to false. + +

+

Example: + +

+
var buf = new Buffer(4);
+buf.writeFloatBE(0xcafebabe, 0);
+
+console.log(buf);
+
+buf.writeFloatLE(0xcafebabe, 0);
+
+console.log(buf);
+
+// <Buffer 4f 4a fe bb>
+// <Buffer bb fe 4a 4f>
+

buf.writeDoubleLE(value, offset, [noAssert])#

+

buf.writeDoubleBE(value, offset, [noAssert])#

+
    +
  • value Number
  • +
  • offset Number
  • +
  • noAssert Boolean, Optional, Default: false
  • +
+

Writes value to the buffer at the specified offset with specified endian +format. Note, value must be a valid 64 bit double. + +

+

Set noAssert to true to skip validation of value and offset. This means +that value may be too large for the specific function and offset may be +beyond the end of the buffer leading to the values being silently dropped. This +should not be used unless you are certain of correctness. Defaults to false. + +

+

Example: + +

+
var buf = new Buffer(8);
+buf.writeDoubleBE(0xdeadbeefcafebabe, 0);
+
+console.log(buf);
+
+buf.writeDoubleLE(0xdeadbeefcafebabe, 0);
+
+console.log(buf);
+
+// <Buffer 43 eb d5 b7 dd f9 5f d7>
+// <Buffer d7 5f f9 dd b7 d5 eb 43>
+

buf.fill(value, [offset], [end])#

+
    +
  • value
  • +
  • offset Number, Optional
  • +
  • end Number, Optional
  • +
+

Fills the buffer with the specified value. If the offset (defaults to 0) +and end (defaults to buffer.length) are not given it will fill the entire +buffer. + +

+
var b = new Buffer(50);
+b.fill("h");
+

buffer.INSPECT_MAX_BYTES#

+
    +
  • Number, Default: 50
  • +
+

How many bytes will be returned when buffer.inspect() is called. This can +be overridden by user modules. + +

+

Note that this is a property on the buffer module returned by +require('buffer'), not on the Buffer global, or a buffer instance. + +

+

Class: SlowBuffer#

+

This class is primarily for internal use. JavaScript programs should +use Buffer instead of using SlowBuffer. + +

+

In order to avoid the overhead of allocating many C++ Buffer objects for +small blocks of memory in the lifetime of a server, Node allocates memory +in 8Kb (8192 byte) chunks. If a buffer is smaller than this size, then it +will be backed by a parent SlowBuffer object. If it is larger than this, +then Node will allocate a SlowBuffer slab for it directly. + +

+

Stream#

+
Stability: 2 - Unstable
+

A stream is an abstract interface implemented by various objects in +Node. For example a request to an HTTP server is a stream, as is +stdout. Streams are readable, writable, or both. All streams are +instances of EventEmitter + +

+

You can load up the Stream base class by doing require('stream'). + +

+

Readable Stream#

+ + +

A Readable Stream has the following methods, members, and events. + +

+

Event: 'data'#

+

function (data) { } + +

+

The 'data' event emits either a Buffer (by default) or a string if +setEncoding() was used. + +

+

Note that the data will be lost if there is no listener when a +Readable Stream emits a 'data' event. + +

+

Event: 'end'#

+

function () { } + +

+

Emitted when the stream has received an EOF (FIN in TCP terminology). +Indicates that no more 'data' events will happen. If the stream is +also writable, it may be possible to continue writing. + +

+

Event: 'error'#

+

function (exception) { } + +

+

Emitted if there was an error receiving data. + +

+

Event: 'close'#

+

function () { } + +

+

Emitted when the underlying resource (for example, the backing file +descriptor) has been closed. Not all streams will emit this. + +

+

stream.readable#

+

A boolean that is true by default, but turns false after an +'error' occurred, the stream came to an 'end', or destroy() was +called. + +

+

stream.setEncoding([encoding])#

+

Makes the 'data' event emit a string instead of a Buffer. encoding +can be 'utf8', 'utf16le' ('ucs2'), 'ascii', or 'hex'. Defaults +to 'utf8'. + +

+

stream.pause()#

+

Issues an advisory signal to the underlying communication layer, +requesting that no further data be sent until resume() is called. + +

+

Note that, due to the advisory nature, certain streams will not be +paused immediately, and so 'data' events may be emitted for some +indeterminate period of time even after pause() is called. You may +wish to buffer such 'data' events. + +

+

stream.resume()#

+

Resumes the incoming 'data' events after a pause(). + +

+

stream.destroy()#

+

Closes the underlying file descriptor. Stream is no longer writable +nor readable. The stream will not emit any more 'data', or 'end' +events. Any queued write data will not be sent. The stream should emit +'close' event once its resources have been disposed of. + + +

+

stream.pipe(destination, [options])#

+

This is a Stream.prototype method available on all Streams. + +

+

Connects this read stream to destination WriteStream. Incoming data on +this stream gets written to destination. The destination and source +streams are kept in sync by pausing and resuming as necessary. + +

+

This function returns the destination stream. + +

+

Emulating the Unix cat command: + +

+
process.stdin.resume(); process.stdin.pipe(process.stdout);
+

By default end() is called on the destination when the source stream +emits end, so that destination is no longer writable. Pass { end: +false } as options to keep the destination stream open. + +

+

This keeps process.stdout open so that "Goodbye" can be written at the +end. + +

+
process.stdin.resume();
+
+process.stdin.pipe(process.stdout, { end: false });
+
+process.stdin.on("end", function() {
+process.stdout.write("Goodbye\n"); });
+

Writable Stream#

+ + +

A Writable Stream has the following methods, members, and events. + +

+

Event: 'drain'#

+

function () { } + +

+

Emitted when the stream's write queue empties and it's safe to write without +buffering again. Listen for it when stream.write() returns false. + +

+

The 'drain' event can happen at any time, regardless of whether or not +stream.write() has previously returned false. To avoid receiving unwanted +'drain' events, listen using stream.once(). + +

+

Event: 'error'#

+

function (exception) { } + +

+

Emitted on error with the exception exception. + +

+

Event: 'close'#

+

function () { } + +

+

Emitted when the underlying file descriptor has been closed. + +

+

Event: 'pipe'#

+

function (src) { } + +

+

Emitted when the stream is passed to a readable stream's pipe method. + +

+

stream.writable#

+

A boolean that is true by default, but turns false after an +'error' occurred or end() / destroy() was called. + +

+

stream.write(string, [encoding])#

+

Writes string with the given encoding to the stream. Returns true +if the string has been flushed to the kernel buffer. Returns false to +indicate that the kernel buffer is full, and the data will be sent out +in the future. The 'drain' event will indicate when the kernel buffer +is empty again. The encoding defaults to 'utf8'. + +

+

stream.write(buffer)#

+

Same as the above except with a raw buffer. + +

+

stream.end()#

+

Terminates the stream with EOF or FIN. This call will allow queued +write data to be sent before closing the stream. + +

+

stream.end(string, encoding)#

+

Sends string with the given encoding and terminates the stream with +EOF or FIN. This is useful to reduce the number of packets sent. + +

+

stream.end(buffer)#

+

Same as above but with a buffer. + +

+

stream.destroy()#

+

Closes the underlying file descriptor. Stream is no longer writable +nor readable. The stream will not emit any more 'data', or 'end' +events. Any queued write data will not be sent. The stream should emit +'close' event once its resources have been disposed of. + +

+

stream.destroySoon()#

+

After the write queue is drained, close the file descriptor. +destroySoon() can still destroy straight away, as long as there is no +data left in the queue for writes. + +

+

Crypto#

+
Stability: 2 - Unstable; API changes are being discussed for
+future versions.  Breaking changes will be minimized.  See below.
+

Use require('crypto') to access this module. + +

+

The crypto module requires OpenSSL to be available on the underlying platform. +It offers a way of encapsulating secure credentials to be used as part +of a secure HTTPS net or http connection. + +

+

It also offers a set of wrappers for OpenSSL's hash, hmac, cipher, decipher, sign and verify methods. + +

+

crypto.createCredentials(details)#

+

Creates a credentials object, with the optional details being a dictionary with keys: + +

+
    +
  • pfx : A string or buffer holding the PFX or PKCS12 encoded private key, certificate and CA certificates
  • +
  • key : A string holding the PEM encoded private key
  • +
  • passphrase : A string of passphrase for the private key or pfx
  • +
  • cert : A string holding the PEM encoded certificate
  • +
  • ca : Either a string or list of strings of PEM encoded CA certificates to trust.
  • +
  • crl : Either a string or list of strings of PEM encoded CRLs (Certificate Revocation List)
  • +
  • ciphers: A string describing the ciphers to use or exclude. Consult +http://www.openssl.org/docs/apps/ciphers.html#CIPHER_LIST_FORMAT for details +on the format.
  • +
+

If no 'ca' details are given, then node.js will use the default publicly trusted list of CAs as given in +

+

http://mxr.mozilla.org/mozilla/source/security/nss/lib/ckfw/builtins/certdata.txt. + + +

+

crypto.createHash(algorithm)#

+

Creates and returns a hash object, a cryptographic hash with the given algorithm +which can be used to generate hash digests. + +

+

algorithm is dependent on the available algorithms supported by the version +of OpenSSL on the platform. Examples are 'sha1', 'md5', 'sha256', 'sha512', etc. +On recent releases, openssl list-message-digest-algorithms will display the available digest algorithms. + +

+

Example: this program that takes the sha1 sum of a file + +

+
var filename = process.argv[2];
+var crypto = require('crypto');
+var fs = require('fs');
+
+var shasum = crypto.createHash('sha1');
+
+var s = fs.ReadStream(filename);
+s.on('data', function(d) {
+  shasum.update(d);
+});
+
+s.on('end', function() {
+  var d = shasum.digest('hex');
+  console.log(d + '  ' + filename);
+});
+

Class: Hash#

+

The class for creating hash digests of data. + +

+

Returned by crypto.createHash. + +

+

hash.update(data, [input_encoding])#

+

Updates the hash content with the given data, the encoding of which is given +in input_encoding and can be 'utf8', 'ascii' or 'binary'. +Defaults to 'binary'. +This can be called many times with new data as it is streamed. + +

+

hash.digest([encoding])#

+

Calculates the digest of all of the passed data to be hashed. +The encoding can be 'hex', 'binary' or 'base64'. +Defaults to 'binary'. + +

+

Note: hash object can not be used after digest() method been called. + + +

+

crypto.createHmac(algorithm, key)#

+

Creates and returns a hmac object, a cryptographic hmac with the given algorithm and key. + +

+

algorithm is dependent on the available algorithms supported by OpenSSL - see createHash above. +key is the hmac key to be used. + +

+

Class: Hmac#

+

Class for creating cryptographic hmac content. + +

+

Returned by crypto.createHmac. + +

+

hmac.update(data)#

+

Update the hmac content with the given data. +This can be called many times with new data as it is streamed. + +

+

hmac.digest([encoding])#

+

Calculates the digest of all of the passed data to the hmac. +The encoding can be 'hex', 'binary' or 'base64'. +Defaults to 'binary'. + +

+

Note: hmac object can not be used after digest() method been called. + + +

+

crypto.createCipher(algorithm, password)#

+

Creates and returns a cipher object, with the given algorithm and password. + +

+

algorithm is dependent on OpenSSL, examples are 'aes192', etc. +On recent releases, openssl list-cipher-algorithms will display the +available cipher algorithms. +password is used to derive key and IV, which must be a 'binary' encoded +string or a buffer. + +

+

crypto.createCipheriv(algorithm, key, iv)#

+

Creates and returns a cipher object, with the given algorithm, key and iv. + +

+

algorithm is the same as the argument to createCipher(). +key is the raw key used by the algorithm. +iv is an initialization +vector. + +

+

key and iv must be 'binary' encoded strings or buffers. + +

+

Class: Cipher#

+

Class for encrypting data. + +

+

Returned by crypto.createCipher and crypto.createCipheriv. + +

+

cipher.update(data, [input_encoding], [output_encoding])#

+

Updates the cipher with data, the encoding of which is given in +input_encoding and can be 'utf8', 'ascii' or 'binary'. +Defaults to 'binary'. + +

+

The output_encoding specifies the output format of the enciphered data, +and can be 'binary', 'base64' or 'hex'. Defaults to 'binary'. + +

+

Returns the enciphered contents, and can be called many times with new data as it is streamed. + +

+

cipher.final([output_encoding])#

+

Returns any remaining enciphered contents, with output_encoding being one of: +'binary', 'base64' or 'hex'. Defaults to 'binary'. + +

+

Note: cipher object can not be used after final() method been called. + +

+

cipher.setAutoPadding(auto_padding=true)#

+

You can disable automatic padding of the input data to block size. If auto_padding is false, +the length of the entire input data must be a multiple of the cipher's block size or final will fail. +Useful for non-standard padding, e.g. using 0x0 instead of PKCS padding. You must call this before cipher.final. + + +

+

crypto.createDecipher(algorithm, password)#

+

Creates and returns a decipher object, with the given algorithm and key. +This is the mirror of the createCipher() above. + +

+

crypto.createDecipheriv(algorithm, key, iv)#

+

Creates and returns a decipher object, with the given algorithm, key and iv. +This is the mirror of the createCipheriv() above. + +

+

Class: Decipher#

+

Class for decrypting data. + +

+

Returned by crypto.createDecipher and crypto.createDecipheriv. + +

+

decipher.update(data, [input_encoding], [output_encoding])#

+

Updates the decipher with data, which is encoded in 'binary', 'base64' +or 'hex'. Defaults to 'binary'. + +

+

The output_decoding specifies in what format to return the deciphered +plaintext: 'binary', 'ascii' or 'utf8'. Defaults to 'binary'. + +

+

decipher.final([output_encoding])#

+

Returns any remaining plaintext which is deciphered, +with output_encoding being one of: 'binary', 'ascii' or 'utf8'. +Defaults to 'binary'. + +

+

Note: decipher object can not be used after final() method been called. + +

+

decipher.setAutoPadding(auto_padding=true)#

+

You can disable auto padding if the data has been encrypted without standard block padding to prevent +decipher.final from checking and removing it. Can only work if the input data's length is a multiple of the +ciphers block size. You must call this before streaming data to decipher.update. + +

+

crypto.createSign(algorithm)#

+

Creates and returns a signing object, with the given algorithm. +On recent OpenSSL releases, openssl list-public-key-algorithms will display +the available signing algorithms. Examples are 'RSA-SHA256'. + +

+

Class: Signer#

+

Class for generating signatures. + +

+

Returned by crypto.createSign. + +

+

signer.update(data)#

+

Updates the signer object with data. +This can be called many times with new data as it is streamed. + +

+

signer.sign(private_key, [output_format])#

+

Calculates the signature on all the updated data passed through the signer. +private_key is a string containing the PEM encoded private key for signing. + +

+

Returns the signature in output_format which can be 'binary', 'hex' or +'base64'. Defaults to 'binary'. + +

+

Note: signer object can not be used after sign() method been called. + +

+

crypto.createVerify(algorithm)#

+

Creates and returns a verification object, with the given algorithm. +This is the mirror of the signing object above. + +

+

Class: Verify#

+

Class for verifying signatures. + +

+

Returned by crypto.createVerify. + +

+

verifier.update(data)#

+

Updates the verifier object with data. +This can be called many times with new data as it is streamed. + +

+

verifier.verify(object, signature, [signature_format])#

+

Verifies the signed data by using the object and signature. object is a +string containing a PEM encoded object, which can be one of RSA public key, +DSA public key, or X.509 certificate. signature is the previously calculated +signature for the data, in the signature_format which can be 'binary', +'hex' or 'base64'. Defaults to 'binary'. + +

+

Returns true or false depending on the validity of the signature for the data and public key. + +

+

Note: verifier object can not be used after verify() method been called. + +

+

crypto.createDiffieHellman(prime_length)#

+

Creates a Diffie-Hellman key exchange object and generates a prime of the +given bit length. The generator used is 2. + +

+

crypto.createDiffieHellman(prime, [encoding])#

+

Creates a Diffie-Hellman key exchange object using the supplied prime. The +generator used is 2. Encoding can be 'binary', 'hex', or 'base64'. +Defaults to 'binary'. + +

+

Class: DiffieHellman#

+

The class for creating Diffie-Hellman key exchanges. + +

+

Returned by crypto.createDiffieHellman. + +

+

diffieHellman.generateKeys([encoding])#

+

Generates private and public Diffie-Hellman key values, and returns the +public key in the specified encoding. This key should be transferred to the +other party. Encoding can be 'binary', 'hex', or 'base64'. +Defaults to 'binary'. + +

+

diffieHellman.computeSecret(other_public_key, [input_encoding], [output_encoding])#

+

Computes the shared secret using other_public_key as the other party's +public key and returns the computed shared secret. Supplied key is +interpreted using specified input_encoding, and secret is encoded using +specified output_encoding. Encodings can be 'binary', 'hex', or +'base64'. The input encoding defaults to 'binary'. +If no output encoding is given, the input encoding is used as output encoding. + +

+

diffieHellman.getPrime([encoding])#

+

Returns the Diffie-Hellman prime in the specified encoding, which can be +'binary', 'hex', or 'base64'. Defaults to 'binary'. + +

+

diffieHellman.getGenerator([encoding])#

+

Returns the Diffie-Hellman prime in the specified encoding, which can be +'binary', 'hex', or 'base64'. Defaults to 'binary'. + +

+

diffieHellman.getPublicKey([encoding])#

+

Returns the Diffie-Hellman public key in the specified encoding, which can +be 'binary', 'hex', or 'base64'. Defaults to 'binary'. + +

+

diffieHellman.getPrivateKey([encoding])#

+

Returns the Diffie-Hellman private key in the specified encoding, which can +be 'binary', 'hex', or 'base64'. Defaults to 'binary'. + +

+

diffieHellman.setPublicKey(public_key, [encoding])#

+

Sets the Diffie-Hellman public key. Key encoding can be 'binary', 'hex', +or 'base64'. Defaults to 'binary'. + +

+

diffieHellman.setPrivateKey(public_key, [encoding])#

+

Sets the Diffie-Hellman private key. Key encoding can be 'binary', 'hex', +or 'base64'. Defaults to 'binary'. + +

+

crypto.getDiffieHellman(group_name)#

+

Creates a predefined Diffie-Hellman key exchange object. +The supported groups are: 'modp1', 'modp2', 'modp5' +(defined in RFC 2412) +and 'modp14', 'modp15', 'modp16', 'modp17', 'modp18' +(defined in RFC 3526). +The returned object mimics the interface of objects created by +crypto.createDiffieHellman() above, but +will not allow to change the keys (with +diffieHellman.setPublicKey() for example). +The advantage of using this routine is that the parties don't have to +generate nor exchange group modulus beforehand, saving both processor and +communication time. + +

+

Example (obtaining a shared secret): + +

+
var crypto = require('crypto');
+var alice = crypto.getDiffieHellman('modp5');
+var bob = crypto.getDiffieHellman('modp5');
+
+alice.generateKeys();
+bob.generateKeys();
+
+var alice_secret = alice.computeSecret(bob.getPublicKey(), 'binary', 'hex');
+var bob_secret = bob.computeSecret(alice.getPublicKey(), 'binary', 'hex');
+
+/* alice_secret and bob_secret should be the same */
+console.log(alice_secret == bob_secret);
+

crypto.pbkdf2(password, salt, iterations, keylen, callback)#

+

Asynchronous PBKDF2 applies pseudorandom function HMAC-SHA1 to derive +a key of given length from the given password, salt and iterations. +The callback gets two arguments (err, derivedKey). + +

+

crypto.randomBytes(size, [callback])#

+

Generates cryptographically strong pseudo-random data. Usage: + +

+
// async
+crypto.randomBytes(256, function(ex, buf) {
+  if (ex) throw ex;
+  console.log('Have %d bytes of random data: %s', buf.length, buf);
+});
+
+// sync
+try {
+  var buf = crypto.randomBytes(256);
+  console.log('Have %d bytes of random data: %s', buf.length, buf);
+} catch (ex) {
+  // handle error
+}
+

Proposed API Changes in Future Versions of Node#

+

The Crypto module was added to Node before there was the concept of a +unified Stream API, and before there were Buffer objects for handling +binary data. + +

+

As such, the streaming classes don't have the typical methods found on +other Node classes, and many methods accept and return Binary-encoded +strings by default rather than Buffers. + +

+

A future version of node will make Buffers the default data type. +This will be a breaking change for some use cases, but not all. + +

+

For example, if you currently use the default arguments to the Sign +class, and then pass the results to the Verify class, without ever +inspecting the data, then it will continue to work as before. Where +you now get a binary string and then present the binary string to the +Verify object, you'll get a Buffer, and present the Buffer to the +Verify object. + +

+

However, if you are doing things with the string data that will not +work properly on Buffers (such as, concatenating them, storing in +databases, etc.), or you are passing binary strings to the crypto +functions without an encoding argument, then you will need to start +providing encoding arguments to specify which encoding you'd like to +use. + +

+

Also, a Streaming API will be provided, but this will be done in such +a way as to preserve the legacy API surface. + + +

+

TLS (SSL)#

+
Stability: 3 - Stable
+

Use require('tls') to access this module. + +

+

The tls module uses OpenSSL to provide Transport Layer Security and/or +Secure Socket Layer: encrypted stream communication. + +

+

TLS/SSL is a public/private key infrastructure. Each client and each +server must have a private key. A private key is created like this + +

+
openssl genrsa -out ryans-key.pem 1024
+

All severs and some clients need to have a certificate. Certificates are public +keys signed by a Certificate Authority or self-signed. The first step to +getting a certificate is to create a "Certificate Signing Request" (CSR) +file. This is done with: + +

+
openssl req -new -key ryans-key.pem -out ryans-csr.pem
+

To create a self-signed certificate with the CSR, do this: + +

+
openssl x509 -req -in ryans-csr.pem -signkey ryans-key.pem -out ryans-cert.pem
+

Alternatively you can send the CSR to a Certificate Authority for signing. + +

+

(TODO: docs on creating a CA, for now interested users should just look at +test/fixtures/keys/Makefile in the Node source code) + +

+

To create .pfx or .p12, do this: + +

+
openssl pkcs12 -export -in agent5-cert.pem -inkey agent5-key.pem \
+    -certfile ca-cert.pem -out agent5.pfx
+
    +
  • in: certificate
  • +
  • inkey: private key
  • +
  • certfile: all CA certs concatenated in one file like +cat ca1-cert.pem ca2-cert.pem > ca-cert.pem
  • +
+

Client-initiated renegotiation attack mitigation#

+ + +

The TLS protocol lets the client renegotiate certain aspects of the TLS session. +Unfortunately, session renegotiation requires a disproportional amount of +server-side resources, which makes it a potential vector for denial-of-service +attacks. + +

+

To mitigate this, renegotiations are limited to three times every 10 minutes. An +error is emitted on the CleartextStream instance when the threshold is +exceeded. The limits are configurable: + +

+
    +
  • tls.CLIENT_RENEG_LIMIT: renegotiation limit, default is 3.

    +
  • +
  • tls.CLIENT_RENEG_WINDOW: renegotiation window in seconds, default is

    +
                           10 minutes.
    +
  • +
+

Don't change the defaults unless you know what you are doing. + +

+

To test your server, connect to it with openssl s_client -connect address:port +and tap R<CR> (that's the letter R followed by a carriage return) a few +times. + + +

+

NPN and SNI#

+ + +

NPN (Next Protocol Negotiation) and SNI (Server Name Indication) are TLS +handshake extensions allowing you: + +

+
    +
  • NPN - to use one TLS server for multiple protocols (HTTP, SPDY)
  • +
  • SNI - to use one TLS server for multiple hostnames with different SSL +certificates.
  • +
+

tls.createServer(options, [secureConnectionListener])#

+

Creates a new tls.Server. The connectionListener argument is +automatically set as a listener for the secureConnection event. The +options object has these possibilities: + +

+
    +
  • pfx: A string or Buffer containing the private key, certificate and +CA certs of the server in PFX or PKCS12 format. (Mutually exclusive with +the key, cert and ca options.)

    +
  • +
  • key: A string or Buffer containing the private key of the server in +PEM format. (Required)

    +
  • +
  • passphrase: A string of passphrase for the private key or pfx.

    +
  • +
  • cert: A string or Buffer containing the certificate key of the server in +PEM format. (Required)

    +
  • +
  • ca: An array of strings or Buffers of trusted certificates. If this is +omitted several well known "root" CAs will be used, like VeriSign. +These are used to authorize connections.

    +
  • +
  • crl : Either a string or list of strings of PEM encoded CRLs (Certificate +Revocation List)

    +
  • +
  • ciphers: A string describing the ciphers to use or exclude.

    +

    To mitigate BEAST attacks it is recommended that you use this option in +conjunction with the honorCipherOrder option described below to +prioritize the non-CBC cipher.

    +

    Defaults to +ECDHE-RSA-AES128-SHA256:AES128-GCM-SHA256:RC4:HIGH:!MD5:!aNULL:!EDH. +Consult the OpenSSL cipher list format documentation for details on the +format.

    +

    ECDHE-RSA-AES128-SHA256 and AES128-GCM-SHA256 are used when node.js is +linked against OpenSSL 1.0.1 or newer and the client speaks TLS 1.2, RC4 is +used as a secure fallback.

    +

    NOTE: Previous revisions of this section suggested AES256-SHA as an +acceptable cipher. Unfortunately, AES256-SHA is a CBC cipher and therefore +susceptible to BEAST attacks. Do not use it.

    +
  • +
  • honorCipherOrder : When choosing a cipher, use the server's preferences +instead of the client preferences.

    +

    Note that if SSLv2 is used, the server will send its list of preferences +to the client, and the client chooses the cipher.

    +

    Although, this option is disabled by default, it is recommended that you +use this option in conjunction with the ciphers option to mitigate +BEAST attacks.

    +
  • +
  • requestCert: If true the server will request a certificate from +clients that connect and attempt to verify that certificate. Default: +false.

    +
  • +
  • rejectUnauthorized: If true the server will reject any connection +which is not authorized with the list of supplied CAs. This option only +has an effect if requestCert is true. Default: false.

    +
  • +
  • NPNProtocols: An array or Buffer of possible NPN protocols. (Protocols +should be ordered by their priority).

    +
  • +
  • SNICallback: A function that will be called if client supports SNI TLS +extension. Only one argument will be passed to it: servername. And +SNICallback should return SecureContext instance. +(You can use crypto.createCredentials(...).context to get proper +SecureContext). If SNICallback wasn't provided - default callback with +high-level API will be used (see below).

    +
  • +
  • sessionIdContext: A string containing a opaque identifier for session +resumption. If requestCert is true, the default is MD5 hash value +generated from command-line. Otherwise, the default is not provided.

    +
  • +
+

Here is a simple example echo server: + +

+
var tls = require('tls');
+var fs = require('fs');
+
+var options = {
+  key: fs.readFileSync('server-key.pem'),
+  cert: fs.readFileSync('server-cert.pem'),
+
+  // This is necessary only if using the client certificate authentication.
+  requestCert: true,
+
+  // This is necessary only if the client uses the self-signed certificate.
+  ca: [ fs.readFileSync('client-cert.pem') ]
+};
+
+var server = tls.createServer(options, function(cleartextStream) {
+  console.log('server connected',
+              cleartextStream.authorized ? 'authorized' : 'unauthorized');
+  cleartextStream.write("welcome!\n");
+  cleartextStream.setEncoding('utf8');
+  cleartextStream.pipe(cleartextStream);
+});
+server.listen(8000, function() {
+  console.log('server bound');
+});
+

Or + +

+
var tls = require('tls');
+var fs = require('fs');
+
+var options = {
+  pfx: fs.readFileSync('server.pfx'),
+
+  // This is necessary only if using the client certificate authentication.
+  requestCert: true,
+
+};
+
+var server = tls.createServer(options, function(cleartextStream) {
+  console.log('server connected',
+              cleartextStream.authorized ? 'authorized' : 'unauthorized');
+  cleartextStream.write("welcome!\n");
+  cleartextStream.setEncoding('utf8');
+  cleartextStream.pipe(cleartextStream);
+});
+server.listen(8000, function() {
+  console.log('server bound');
+});
+

You can test this server by connecting to it with openssl s_client: + + +

+
openssl s_client -connect 127.0.0.1:8000
+

tls.connect(options, [callback])#

+

tls.connect(port, [host], [options], [callback])#

+

Creates a new client connection to the given port and host (old API) or +options.port and options.host. (If host is omitted, it defaults to +localhost.) options should be an object which specifies: + +

+
    +
  • host: Host the client should connect to

    +
  • +
  • port: Port the client should connect to

    +
  • +
  • socket: Establish secure connection on a given socket rather than +creating a new socket. If this option is specified, host and port +are ignored.

    +
  • +
  • pfx: A string or Buffer containing the private key, certificate and +CA certs of the server in PFX or PKCS12 format.

    +
  • +
  • key: A string or Buffer containing the private key of the client in +PEM format.

    +
  • +
  • passphrase: A string of passphrase for the private key or pfx.

    +
  • +
  • cert: A string or Buffer containing the certificate key of the client in +PEM format.

    +
  • +
  • ca: An array of strings or Buffers of trusted certificates. If this is +omitted several well known "root" CAs will be used, like VeriSign. +These are used to authorize connections.

    +
  • +
  • rejectUnauthorized: If true, the server certificate is verified against +the list of supplied CAs. An 'error' event is emitted if verification +fails. Default: false.

    +
  • +
  • NPNProtocols: An array of string or Buffer containing supported NPN +protocols. Buffer should have following format: 0x05hello0x05world, +where first byte is next protocol name's length. (Passing array should +usually be much simpler: ['hello', 'world'].)

    +
  • +
  • servername: Servername for SNI (Server Name Indication) TLS extension.

    +
  • +
+

The callback parameter will be added as a listener for the +'secureConnect' event. + +

+

tls.connect() returns a CleartextStream object. + +

+

Here is an example of a client of echo server as described previously: + +

+
var tls = require('tls');
+var fs = require('fs');
+
+var options = {
+  // These are necessary only if using the client certificate authentication
+  key: fs.readFileSync('client-key.pem'),
+  cert: fs.readFileSync('client-cert.pem'),
+
+  // This is necessary only if the server uses the self-signed certificate
+  ca: [ fs.readFileSync('server-cert.pem') ]
+};
+
+var cleartextStream = tls.connect(8000, options, function() {
+  console.log('client connected',
+              cleartextStream.authorized ? 'authorized' : 'unauthorized');
+  process.stdin.pipe(cleartextStream);
+  process.stdin.resume();
+});
+cleartextStream.setEncoding('utf8');
+cleartextStream.on('data', function(data) {
+  console.log(data);
+});
+cleartextStream.on('end', function() {
+  server.close();
+});
+

Or + +

+
var tls = require('tls');
+var fs = require('fs');
+
+var options = {
+  pfx: fs.readFileSync('client.pfx')
+};
+
+var cleartextStream = tls.connect(8000, options, function() {
+  console.log('client connected',
+              cleartextStream.authorized ? 'authorized' : 'unauthorized');
+  process.stdin.pipe(cleartextStream);
+  process.stdin.resume();
+});
+cleartextStream.setEncoding('utf8');
+cleartextStream.on('data', function(data) {
+  console.log(data);
+});
+cleartextStream.on('end', function() {
+  server.close();
+});
+

tls.createSecurePair([credentials], [isServer], [requestCert], [rejectUnauthorized])#

+

Creates a new secure pair object with two streams, one of which reads/writes +encrypted data, and one reads/writes cleartext data. +Generally the encrypted one is piped to/from an incoming encrypted data stream, +and the cleartext one is used as a replacement for the initial encrypted stream. + +

+
    +
  • credentials: A credentials object from crypto.createCredentials( ... )

    +
  • +
  • isServer: A boolean indicating whether this tls connection should be +opened as a server or a client.

    +
  • +
  • requestCert: A boolean indicating whether a server should request a +certificate from a connecting client. Only applies to server connections.

    +
  • +
  • rejectUnauthorized: A boolean indicating whether a server should +automatically reject clients with invalid certificates. Only applies to +servers with requestCert enabled.

    +
  • +
+

tls.createSecurePair() returns a SecurePair object with [cleartext][] and +encrypted stream properties. + +

+

Class: SecurePair#

+

Returned by tls.createSecurePair. + +

+

Event: 'secure'#

+

The event is emitted from the SecurePair once the pair has successfully +established a secure connection. + +

+

Similarly to the checking for the server 'secureConnection' event, +pair.cleartext.authorized should be checked to confirm whether the certificate +used properly authorized. + +

+

Class: tls.Server#

+

This class is a subclass of net.Server and has the same methods on it. +Instead of accepting just raw TCP connections, this accepts encrypted +connections using TLS or SSL. + +

+

Event: 'secureConnection'#

+

function (cleartextStream) {} + +

+

This event is emitted after a new connection has been successfully +handshaked. The argument is a instance of CleartextStream. It has all the +common stream methods and events. + +

+

cleartextStream.authorized is a boolean value which indicates if the +client has verified by one of the supplied certificate authorities for the +server. If cleartextStream.authorized is false, then +cleartextStream.authorizationError is set to describe how authorization +failed. Implied but worth mentioning: depending on the settings of the TLS +server, you unauthorized connections may be accepted. +cleartextStream.npnProtocol is a string containing selected NPN protocol. +cleartextStream.servername is a string containing servername requested with +SNI. + + +

+

Event: 'clientError'#

+

function (exception) { } + +

+

When a client connection emits an 'error' event before secure connection is +established - it will be forwarded here. + + +

+

server.listen(port, [host], [callback])#

+

Begin accepting connections on the specified port and host. If the +host is omitted, the server will accept connections directed to any +IPv4 address (INADDR_ANY). + +

+

This function is asynchronous. The last parameter callback will be called +when the server has been bound. + +

+

See net.Server for more information. + + +

+

server.close()#

+

Stops the server from accepting new connections. This function is +asynchronous, the server is finally closed when the server emits a 'close' +event. + +

+

server.address()#

+

Returns the bound address, the address family name and port of the +server as reported by the operating system. See net.Server.address() for +more information. + +

+

server.addContext(hostname, credentials)#

+

Add secure context that will be used if client request's SNI hostname is +matching passed hostname (wildcards can be used). credentials can contain +key, cert and ca. + +

+

server.maxConnections#

+

Set this property to reject connections when the server's connection count +gets high. + +

+

server.connections#

+

The number of concurrent connections on the server. + + +

+

Class: tls.CleartextStream#

+

This is a stream on top of the Encrypted stream that makes it possible to +read/write an encrypted data as a cleartext data. + +

+

This instance implements a duplex Stream interfaces. It has all the +common stream methods and events. + +

+

A ClearTextStream is the clear member of a SecurePair object. + +

+

Event: 'secureConnect'#

+

This event is emitted after a new connection has been successfully handshaked. +The listener will be called no matter if the server's certificate was +authorized or not. It is up to the user to test cleartextStream.authorized +to see if the server certificate was signed by one of the specified CAs. +If cleartextStream.authorized === false then the error can be found in +cleartextStream.authorizationError. Also if NPN was used - you can check +cleartextStream.npnProtocol for negotiated protocol. + +

+

cleartextStream.authorized#

+

A boolean that is true if the peer certificate was signed by one of the +specified CAs, otherwise false + +

+

cleartextStream.authorizationError#

+

The reason why the peer's certificate has not been verified. This property +becomes available only when cleartextStream.authorized === false. + +

+

cleartextStream.getPeerCertificate()#

+

Returns an object representing the peer's certificate. The returned object has +some properties corresponding to the field of the certificate. + +

+

Example: + +

+
{ subject: 
+   { C: 'UK',
+     ST: 'Acknack Ltd',
+     L: 'Rhys Jones',
+     O: 'node.js',
+     OU: 'Test TLS Certificate',
+     CN: 'localhost' },
+  issuer: 
+   { C: 'UK',
+     ST: 'Acknack Ltd',
+     L: 'Rhys Jones',
+     O: 'node.js',
+     OU: 'Test TLS Certificate',
+     CN: 'localhost' },
+  valid_from: 'Nov 11 09:52:22 2009 GMT',
+  valid_to: 'Nov  6 09:52:22 2029 GMT',
+  fingerprint: '2A:7A:C2:DD:E5:F9:CC:53:72:35:99:7A:02:5A:71:38:52:EC:8A:DF' }
+

If the peer does not provide a certificate, it returns null or an empty +object. + +

+

cleartextStream.getCipher()#

+

Returns an object representing the cipher name and the SSL/TLS +protocol version of the current connection. + +

+

Example: +{ name: 'AES256-SHA', version: 'TLSv1/SSLv3' } + +

+

See SSL_CIPHER_get_name() and SSL_CIPHER_get_version() in +http://www.openssl.org/docs/ssl/ssl.html#DEALING_WITH_CIPHERS for more +information. + +

+

cleartextStream.address()#

+

Returns the bound address, the address family name and port of the +underlying socket as reported by the operating system. Returns an +object with three properties, e.g. +{ port: 12346, family: 'IPv4', address: '127.0.0.1' } + +

+

cleartextStream.remoteAddress#

+

The string representation of the remote IP address. For example, +'74.125.127.100' or '2001:4860:a005::68'. + +

+

cleartextStream.remotePort#

+

The numeric representation of the remote port. For example, 443. + +

+

StringDecoder#

+
Stability: 3 - Stable
+

To use this module, do require('string_decoder'). StringDecoder decodes a +buffer to a string. It is a simple interface to buffer.toString() but provides +additional support for utf8. + +

+
var StringDecoder = require('string_decoder').StringDecoder;
+var decoder = new StringDecoder('utf8');
+
+var cent = new Buffer([0xC2, 0xA2]);
+console.log(decoder.write(cent));
+
+var euro = new Buffer([0xE2, 0x82, 0xAC]);
+console.log(decoder.write(euro));
+

Class: StringDecoder#

+

Accepts a single argument, encoding which defaults to utf8. + +

+

StringDecoder.write(buffer)#

+

Returns a decoded string. +

+

File System#

+
Stability: 3 - Stable
+ + +

File I/O is provided by simple wrappers around standard POSIX functions. To +use this module do require('fs'). All the methods have asynchronous and +synchronous forms. + +

+

The asynchronous form always take a completion callback as its last argument. +The arguments passed to the completion callback depend on the method, but the +first argument is always reserved for an exception. If the operation was +completed successfully, then the first argument will be null or undefined. + +

+

When using the synchronous form any exceptions are immediately thrown. +You can use try/catch to handle exceptions or allow them to bubble up. + +

+

Here is an example of the asynchronous version: + +

+
var fs = require('fs');
+
+fs.unlink('/tmp/hello', function (err) {
+  if (err) throw err;
+  console.log('successfully deleted /tmp/hello');
+});
+

Here is the synchronous version: + +

+
var fs = require('fs');
+
+fs.unlinkSync('/tmp/hello')
+console.log('successfully deleted /tmp/hello');
+

With the asynchronous methods there is no guaranteed ordering. So the +following is prone to error: + +

+
fs.rename('/tmp/hello', '/tmp/world', function (err) {
+  if (err) throw err;
+  console.log('renamed complete');
+});
+fs.stat('/tmp/world', function (err, stats) {
+  if (err) throw err;
+  console.log('stats: ' + JSON.stringify(stats));
+});
+

It could be that fs.stat is executed before fs.rename. +The correct way to do this is to chain the callbacks. + +

+
fs.rename('/tmp/hello', '/tmp/world', function (err) {
+  if (err) throw err;
+  fs.stat('/tmp/world', function (err, stats) {
+    if (err) throw err;
+    console.log('stats: ' + JSON.stringify(stats));
+  });
+});
+

In busy processes, the programmer is strongly encouraged to use the +asynchronous versions of these calls. The synchronous versions will block +the entire process until they complete--halting all connections. + +

+

Relative path to filename can be used, remember however that this path will be relative +to process.cwd(). + +

+

fs.rename(oldPath, newPath, [callback])#

+

Asynchronous rename(2). No arguments other than a possible exception are given +to the completion callback. + +

+

fs.renameSync(oldPath, newPath)#

+

Synchronous rename(2). + +

+

fs.truncate(fd, len, [callback])#

+

Asynchronous ftruncate(2). No arguments other than a possible exception are +given to the completion callback. + +

+

fs.truncateSync(fd, len)#

+

Synchronous ftruncate(2). + +

+

fs.chown(path, uid, gid, [callback])#

+

Asynchronous chown(2). No arguments other than a possible exception are given +to the completion callback. + +

+

fs.chownSync(path, uid, gid)#

+

Synchronous chown(2). + +

+

fs.fchown(fd, uid, gid, [callback])#

+

Asynchronous fchown(2). No arguments other than a possible exception are given +to the completion callback. + +

+

fs.fchownSync(fd, uid, gid)#

+

Synchronous fchown(2). + +

+

fs.lchown(path, uid, gid, [callback])#

+

Asynchronous lchown(2). No arguments other than a possible exception are given +to the completion callback. + +

+

fs.lchownSync(path, uid, gid)#

+

Synchronous lchown(2). + +

+

fs.chmod(path, mode, [callback])#

+

Asynchronous chmod(2). No arguments other than a possible exception are given +to the completion callback. + +

+

fs.chmodSync(path, mode)#

+

Synchronous chmod(2). + +

+

fs.fchmod(fd, mode, [callback])#

+

Asynchronous fchmod(2). No arguments other than a possible exception +are given to the completion callback. + +

+

fs.fchmodSync(fd, mode)#

+

Synchronous fchmod(2). + +

+

fs.lchmod(path, mode, [callback])#

+

Asynchronous lchmod(2). No arguments other than a possible exception +are given to the completion callback. + +

+

Only available on Mac OS X. + +

+

fs.lchmodSync(path, mode)#

+

Synchronous lchmod(2). + +

+

fs.stat(path, [callback])#

+

Asynchronous stat(2). The callback gets two arguments (err, stats) where +stats is a fs.Stats object. See the fs.Stats +section below for more information. + +

+

fs.lstat(path, [callback])#

+

Asynchronous lstat(2). The callback gets two arguments (err, stats) where +stats is a fs.Stats object. lstat() is identical to stat(), except that if +path is a symbolic link, then the link itself is stat-ed, not the file that it +refers to. + +

+

fs.fstat(fd, [callback])#

+

Asynchronous fstat(2). The callback gets two arguments (err, stats) where +stats is a fs.Stats object. fstat() is identical to stat(), except that +the file to be stat-ed is specified by the file descriptor fd. + +

+

fs.statSync(path)#

+

Synchronous stat(2). Returns an instance of fs.Stats. + +

+

fs.lstatSync(path)#

+

Synchronous lstat(2). Returns an instance of fs.Stats. + +

+

fs.fstatSync(fd)#

+

Synchronous fstat(2). Returns an instance of fs.Stats. + +

+

fs.link(srcpath, dstpath, [callback])#

+

Asynchronous link(2). No arguments other than a possible exception are given to +the completion callback. + +

+

fs.linkSync(srcpath, dstpath)#

+

Synchronous link(2). + +

+

fs.symlink(srcpath, dstpath, [type], [callback])#

+

Asynchronous symlink(2). No arguments other than a possible exception are given +to the completion callback. +type argument can be either 'dir', 'file', or 'junction' (default is 'file'). It is only +used on Windows (ignored on other platforms). +Note that Windows junction points require the destination path to be absolute. When using +'junction', the destination argument will automatically be normalized to absolute path. + +

+

fs.symlinkSync(srcpath, dstpath, [type])#

+

Synchronous symlink(2). + +

+

fs.readlink(path, [callback])#

+

Asynchronous readlink(2). The callback gets two arguments (err, +linkString). + +

+

fs.readlinkSync(path)#

+

Synchronous readlink(2). Returns the symbolic link's string value. + +

+

fs.realpath(path, [cache], callback)#

+

Asynchronous realpath(2). The callback gets two arguments (err, +resolvedPath). May use process.cwd to resolve relative paths. cache is an +object literal of mapped paths that can be used to force a specific path +resolution or avoid additional fs.stat calls for known real paths. + +

+

Example: + +

+
var cache = {'/etc':'/private/etc'};
+fs.realpath('/etc/passwd', cache, function (err, resolvedPath) {
+  if (err) throw err;
+  console.log(resolvedPath);
+});
+

fs.realpathSync(path, [cache])#

+

Synchronous realpath(2). Returns the resolved path. + +

+

fs.unlink(path, [callback])#

+

Asynchronous unlink(2). No arguments other than a possible exception are given +to the completion callback. + +

+

fs.unlinkSync(path)#

+

Synchronous unlink(2). + +

+

fs.rmdir(path, [callback])#

+

Asynchronous rmdir(2). No arguments other than a possible exception are given +to the completion callback. + +

+

fs.rmdirSync(path)#

+

Synchronous rmdir(2). + +

+

fs.mkdir(path, [mode], [callback])#

+

Asynchronous mkdir(2). No arguments other than a possible exception are given +to the completion callback. mode defaults to 0777. + +

+

fs.mkdirSync(path, [mode])#

+

Synchronous mkdir(2). + +

+

fs.readdir(path, [callback])#

+

Asynchronous readdir(3). Reads the contents of a directory. +The callback gets two arguments (err, files) where files is an array of +the names of the files in the directory excluding '.' and '..'. + +

+

fs.readdirSync(path)#

+

Synchronous readdir(3). Returns an array of filenames excluding '.' and +'..'. + +

+

fs.close(fd, [callback])#

+

Asynchronous close(2). No arguments other than a possible exception are given +to the completion callback. + +

+

fs.closeSync(fd)#

+

Synchronous close(2). + +

+

fs.open(path, flags, [mode], [callback])#

+

Asynchronous file open. See open(2). flags can be: + +

+
    +
  • 'r' - Open file for reading. +An exception occurs if the file does not exist.

    +
  • +
  • 'r+' - Open file for reading and writing. +An exception occurs if the file does not exist.

    +
  • +
  • 'rs' - Open file for reading in synchronous mode. Instructs the operating +system to bypass the local file system cache.

    +

    This is primarily useful for opening files on NFS mounts as it allows you to +skip the potentially stale local cache. It has a very real impact on I/O +performance so don't use this mode unless you need it.

    +

    Note that this doesn't turn fs.open() into a synchronous blocking call. +If that's what you want then you should be using fs.openSync()

    +
  • +
  • 'rs+' - Open file for reading and writing, telling the OS to open it +synchronously. See notes for 'rs' about using this with caution.

    +
  • +
  • 'w' - Open file for writing. +The file is created (if it does not exist) or truncated (if it exists).

    +
  • +
  • 'wx' - Like 'w' but opens the file in exclusive mode.

    +
  • +
  • 'w+' - Open file for reading and writing. +The file is created (if it does not exist) or truncated (if it exists).

    +
  • +
  • 'wx+' - Like 'w+' but opens the file in exclusive mode.

    +
  • +
  • 'a' - Open file for appending. +The file is created if it does not exist.

    +
  • +
  • 'ax' - Like 'a' but opens the file in exclusive mode.

    +
  • +
  • 'a+' - Open file for reading and appending. +The file is created if it does not exist.

    +
  • +
  • 'ax+' - Like 'a+' but opens the file in exclusive mode.

    +
  • +
+

mode defaults to 0666. The callback gets two arguments (err, fd). + +

+

Exclusive mode (O_EXCL) ensures that path is newly created. fs.open() +fails if a file by that name already exists. On POSIX systems, symlinks are +not followed. Exclusive mode may or may not work with network file systems. + +

+

fs.openSync(path, flags, [mode])#

+

Synchronous open(2). + +

+

fs.utimes(path, atime, mtime, [callback])#

+

fs.utimesSync(path, atime, mtime)#

+

Change file timestamps of the file referenced by the supplied path. + +

+

fs.futimes(fd, atime, mtime, [callback])#

+

fs.futimesSync(fd, atime, mtime)#

+

Change the file timestamps of a file referenced by the supplied file +descriptor. + +

+

fs.fsync(fd, [callback])#

+

Asynchronous fsync(2). No arguments other than a possible exception are given +to the completion callback. + +

+

fs.fsyncSync(fd)#

+

Synchronous fsync(2). + +

+

fs.write(fd, buffer, offset, length, position, [callback])#

+

Write buffer to the file specified by fd. + +

+

offset and length determine the part of the buffer to be written. + +

+

position refers to the offset from the beginning of the file where this data +should be written. If position is null, the data will be written at the +current position. +See pwrite(2). + +

+

The callback will be given three arguments (err, written, buffer) where written +specifies how many bytes were written from buffer. + +

+

Note that it is unsafe to use fs.write multiple times on the same file +without waiting for the callback. For this scenario, +fs.createWriteStream is strongly recommended. + +

+

fs.writeSync(fd, buffer, offset, length, position)#

+

Synchronous version of fs.write(). Returns the number of bytes written. + +

+

fs.read(fd, buffer, offset, length, position, [callback])#

+

Read data from the file specified by fd. + +

+

buffer is the buffer that the data will be written to. + +

+

offset is offset within the buffer where reading will start. + +

+

length is an integer specifying the number of bytes to read. + +

+

position is an integer specifying where to begin reading from in the file. +If position is null, data will be read from the current file position. + +

+

The callback is given the three arguments, (err, bytesRead, buffer). + +

+

fs.readSync(fd, buffer, offset, length, position)#

+

Synchronous version of fs.read. Returns the number of bytesRead. + +

+

fs.readFile(filename, [encoding], [callback])#

+

Asynchronously reads the entire contents of a file. Example: + +

+
fs.readFile('/etc/passwd', function (err, data) {
+  if (err) throw err;
+  console.log(data);
+});
+

The callback is passed two arguments (err, data), where data is the +contents of the file. + +

+

If no encoding is specified, then the raw buffer is returned. + + +

+

fs.readFileSync(filename, [encoding])#

+

Synchronous version of fs.readFile. Returns the contents of the filename. + +

+

If encoding is specified then this function returns a string. Otherwise it +returns a buffer. + + +

+

fs.writeFile(filename, data, [encoding], [callback])#

+

Asynchronously writes data to a file, replacing the file if it already exists. +data can be a string or a buffer. The encoding argument is ignored if +data is a buffer. It defaults to 'utf8'. + +

+

Example: + +

+
fs.writeFile('message.txt', 'Hello Node', function (err) {
+  if (err) throw err;
+  console.log('It\'s saved!');
+});
+

fs.writeFileSync(filename, data, [encoding])#

+

The synchronous version of fs.writeFile. + +

+

fs.appendFile(filename, data, encoding='utf8', [callback])#

+

Asynchronously append data to a file, creating the file if it not yet exists. +data can be a string or a buffer. The encoding argument is ignored if +data is a buffer. + +

+

Example: + +

+
fs.appendFile('message.txt', 'data to append', function (err) {
+  if (err) throw err;
+  console.log('The "data to append" was appended to file!');
+});
+

fs.appendFileSync(filename, data, encoding='utf8')#

+

The synchronous version of fs.appendFile. + +

+

fs.watchFile(filename, [options], listener)#

+
Stability: 2 - Unstable.  Use fs.watch instead, if possible.
+

Watch for changes on filename. The callback listener will be called each +time the file is accessed. + +

+

The second argument is optional. The options if provided should be an object +containing two members a boolean, persistent, and interval. persistent +indicates whether the process should continue to run as long as files are +being watched. interval indicates how often the target should be polled, +in milliseconds. The default is { persistent: true, interval: 5007 }. + +

+

The listener gets two arguments the current stat object and the previous +stat object: + +

+
fs.watchFile('message.text', function (curr, prev) {
+  console.log('the current mtime is: ' + curr.mtime);
+  console.log('the previous mtime was: ' + prev.mtime);
+});
+

These stat objects are instances of fs.Stat. + +

+

If you want to be notified when the file was modified, not just accessed +you need to compare curr.mtime and prev.mtime. + +

+

fs.unwatchFile(filename, [listener])#

+
Stability: 2 - Unstable.  Use fs.watch instead, if available.
+

Stop watching for changes on filename. If listener is specified, only that +particular listener is removed. Otherwise, all listeners are removed and you +have effectively stopped watching filename. + +

+

Calling fs.unwatchFile() with a filename that is not being watched is a +no-op, not an error. + +

+

fs.watch(filename, [options], [listener])#

+
Stability: 2 - Unstable.
+

Watch for changes on filename, where filename is either a file or a +directory. The returned object is a fs.FSWatcher. + +

+

The second argument is optional. The options if provided should be an object +containing a boolean member persistent, which indicates whether the process +should continue to run as long as files are being watched. The default is +{ persistent: true }. + +

+

The listener callback gets two arguments (event, filename). event is either +'rename' or 'change', and filename is the name of the file which triggered +the event. + +

+

Caveats#

+ + +

The fs.watch API is not 100% consistent across platforms, and is +unavailable in some situations. + +

+

Availability#

+ + +

This feature depends on the underlying operating system providing a way +to be notified of filesystem changes. + +

+
    +
  • On Linux systems, this uses inotify.
  • +
  • On BSD systems (including OS X), this uses kqueue.
  • +
  • On SunOS systems (including Solaris and SmartOS), this uses event ports.
  • +
  • On Windows systems, this feature depends on ReadDirectoryChangesW.
  • +
+

If the underlying functionality is not available for some reason, then +fs.watch will not be able to function. For example, watching files or +directories on network file systems (NFS, SMB, etc.) often doesn't work +reliably or at all. + +

+

You can still use fs.watchFile, which uses stat polling, but it is slower and +less reliable. + +

+

Filename Argument#

+ + +

Providing filename argument in the callback is not supported +on every platform (currently it's only supported on Linux and Windows). Even +on supported platforms filename is not always guaranteed to be provided. +Therefore, don't assume that filename argument is always provided in the +callback, and have some fallback logic if it is null. + +

+
fs.watch('somedir', function (event, filename) {
+  console.log('event is: ' + event);
+  if (filename) {
+    console.log('filename provided: ' + filename);
+  } else {
+    console.log('filename not provided');
+  }
+});
+

fs.exists(path, [callback])#

+

Test whether or not the given path exists by checking with the file system. +Then call the callback argument with either true or false. Example: + +

+
fs.exists('/etc/passwd', function (exists) {
+  util.debug(exists ? "it's there" : "no passwd!");
+});
+

fs.existsSync(path)#

+

Synchronous version of fs.exists. + +

+

Class: fs.Stats#

+

Objects returned from fs.stat(), fs.lstat() and fs.fstat() and their +synchronous counterparts are of this type. + +

+
    +
  • stats.isFile()
  • +
  • stats.isDirectory()
  • +
  • stats.isBlockDevice()
  • +
  • stats.isCharacterDevice()
  • +
  • stats.isSymbolicLink() (only valid with fs.lstat())
  • +
  • stats.isFIFO()
  • +
  • stats.isSocket()
  • +
+

For a regular file util.inspect(stats) would return a string very +similar to this: + +

+
{ dev: 2114,
+  ino: 48064969,
+  mode: 33188,
+  nlink: 1,
+  uid: 85,
+  gid: 100,
+  rdev: 0,
+  size: 527,
+  blksize: 4096,
+  blocks: 8,
+  atime: Mon, 10 Oct 2011 23:24:11 GMT,
+  mtime: Mon, 10 Oct 2011 23:24:11 GMT,
+  ctime: Mon, 10 Oct 2011 23:24:11 GMT }
+

Please note that atime, mtime and ctime are instances +of Date object and to compare the values of +these objects you should use appropriate methods. For most +general uses getTime() will return +the number of milliseconds elapsed since 1 January 1970 +00:00:00 UTC and this integer should be sufficient for +any comparison, however there additional methods which can +be used for displaying fuzzy information. More details can +be found in the MDN JavaScript Reference page. + +

+

fs.createReadStream(path, [options])#

+

Returns a new ReadStream object (See Readable Stream). + +

+

options is an object with the following defaults: + +

+
{ flags: 'r',
+  encoding: null,
+  fd: null,
+  mode: 0666,
+  bufferSize: 64 * 1024
+}
+

options can include start and end values to read a range of bytes from +the file instead of the entire file. Both start and end are inclusive and +start at 0. The encoding can be 'utf8', 'ascii', or 'base64'. + +

+

An example to read the last 10 bytes of a file which is 100 bytes long: + +

+
fs.createReadStream('sample.txt', {start: 90, end: 99});
+

Class: fs.ReadStream#

+

ReadStream is a Readable Stream. + +

+

Event: 'open'#

+
    +
  • fd Integer file descriptor used by the ReadStream.
  • +
+

Emitted when the ReadStream's file is opened. + + +

+

fs.createWriteStream(path, [options])#

+

Returns a new WriteStream object (See Writable Stream). + +

+

options is an object with the following defaults: + +

+
{ flags: 'w',
+  encoding: null,
+  mode: 0666 }
+

options may also include a start option to allow writing data at +some position past the beginning of the file. Modifying a file rather +than replacing it may require a flags mode of r+ rather than the +default mode w. + +

+

fs.WriteStream#

+

WriteStream is a Writable Stream. + +

+

Event: 'open'#

+
    +
  • fd Integer file descriptor used by the WriteStream.
  • +
+

Emitted when the WriteStream's file is opened. + +

+

file.bytesWritten#

+

The number of bytes written so far. Does not include data that is still queued +for writing. + +

+

Class: fs.FSWatcher#

+

Objects returned from fs.watch() are of this type. + +

+

watcher.close()#

+

Stop watching for changes on the given fs.FSWatcher. + +

+

Event: 'change'#

+
    +
  • event String The type of fs change
  • +
  • filename String The filename that changed (if relevant/available)
  • +
+

Emitted when something changes in a watched directory or file. +See more details in fs.watch. + +

+

Event: 'error'#

+
    +
  • error Error object
  • +
+

Emitted when an error occurs. + +

+

Path#

+
Stability: 3 - Stable
+

This module contains utilities for handling and transforming file +paths. Almost all these methods perform only string transformations. +The file system is not consulted to check whether paths are valid. + +

+

Use require('path') to use this module. The following methods are provided: + +

+

path.normalize(p)#

+

Normalize a string path, taking care of '..' and '.' parts. + +

+

When multiple slashes are found, they're replaced by a single one; +when the path contains a trailing slash, it is preserved. +On windows backslashes are used. + +

+

Example: + +

+
path.normalize('/foo/bar//baz/asdf/quux/..')
+// returns
+'/foo/bar/baz/asdf'
+

path.join([path1], [path2], [...])#

+

Join all arguments together and normalize the resulting path. +Non-string arguments are ignored. + +

+

Example: + +

+
path.join('/foo', 'bar', 'baz/asdf', 'quux', '..')
+// returns
+'/foo/bar/baz/asdf'
+
+path.join('foo', {}, 'bar')
+// returns
+'foo/bar'
+

path.resolve([from ...], to)#

+

Resolves to to an absolute path. + +

+

If to isn't already absolute from arguments are prepended in right to left +order, until an absolute path is found. If after using all from paths still +no absolute path is found, the current working directory is used as well. The +resulting path is normalized, and trailing slashes are removed unless the path +gets resolved to the root directory. Non-string arguments are ignored. + +

+

Another way to think of it is as a sequence of cd commands in a shell. + +

+
path.resolve('foo/bar', '/tmp/file/', '..', 'a/../subfile')
+

Is similar to: + +

+
cd foo/bar
+cd /tmp/file/
+cd ..
+cd a/../subfile
+pwd
+

The difference is that the different paths don't need to exist and may also be +files. + +

+

Examples: + +

+
path.resolve('/foo/bar', './baz')
+// returns
+'/foo/bar/baz'
+
+path.resolve('/foo/bar', '/tmp/file/')
+// returns
+'/tmp/file'
+
+path.resolve('wwwroot', 'static_files/png/', '../gif/image.gif')
+// if currently in /home/myself/node, it returns
+'/home/myself/node/wwwroot/static_files/gif/image.gif'
+

path.relative(from, to)#

+

Solve the relative path from from to to. + +

+

At times we have two absolute paths, and we need to derive the relative +path from one to the other. This is actually the reverse transform of +path.resolve, which means we see that: + +

+
path.resolve(from, path.relative(from, to)) == path.resolve(to)
+

Examples: + +

+
path.relative('C:\\orandea\\test\\aaa', 'C:\\orandea\\impl\\bbb')
+// returns
+'..\\..\\impl\\bbb'
+
+path.relative('/data/orandea/test/aaa', '/data/orandea/impl/bbb')
+// returns
+'../../impl/bbb'
+

path.dirname(p)#

+

Return the directory name of a path. Similar to the Unix dirname command. + +

+

Example: + +

+
path.dirname('/foo/bar/baz/asdf/quux')
+// returns
+'/foo/bar/baz/asdf'
+

path.basename(p, [ext])#

+

Return the last portion of a path. Similar to the Unix basename command. + +

+

Example: + +

+
path.basename('/foo/bar/baz/asdf/quux.html')
+// returns
+'quux.html'
+
+path.basename('/foo/bar/baz/asdf/quux.html', '.html')
+// returns
+'quux'
+

path.extname(p)#

+

Return the extension of the path, from the last '.' to end of string +in the last portion of the path. If there is no '.' in the last portion +of the path or the first character of it is '.', then it returns +an empty string. Examples: + +

+
path.extname('index.html')
+// returns
+'.html'
+
+path.extname('index.')
+// returns
+'.'
+
+path.extname('index')
+// returns
+''
+

path.sep#

+

The platform-specific file separator. '\\' or '/'. + +

+

An example on linux: + +

+
'foo/bar/baz'.split(path.sep)
+// returns
+['foo', 'bar', 'baz']
+

An example on windows: + +

+
'foo\\bar\\baz'.split(path.sep)
+// returns
+['foo', 'bar', 'baz']
+

net#

+
Stability: 3 - Stable
+

The net module provides you with an asynchronous network wrapper. It contains +methods for creating both servers and clients (called streams). You can include +this module with require('net'); + +

+

net.createServer([options], [connectionListener])#

+

Creates a new TCP server. The connectionListener argument is +automatically set as a listener for the 'connection' event. + +

+

options is an object with the following defaults: + +

+
{ allowHalfOpen: false
+}
+

If allowHalfOpen is true, then the socket won't automatically send a FIN +packet when the other end of the socket sends a FIN packet. The socket becomes +non-readable, but still writable. You should call the end() method explicitly. +See 'end' event for more information. + +

+

Here is an example of an echo server which listens for connections +on port 8124: + +

+
var net = require('net');
+var server = net.createServer(function(c) { //'connection' listener
+  console.log('server connected');
+  c.on('end', function() {
+    console.log('server disconnected');
+  });
+  c.write('hello\r\n');
+  c.pipe(c);
+});
+server.listen(8124, function() { //'listening' listener
+  console.log('server bound');
+});
+

Test this by using telnet: + +

+
telnet localhost 8124
+

To listen on the socket /tmp/echo.sock the third line from the last would +just be changed to + +

+
server.listen('/tmp/echo.sock', function() { //'listening' listener
+

Use nc to connect to a UNIX domain socket server: + +

+
nc -U /tmp/echo.sock
+

net.connect(options, [connectionListener])#

+

net.createConnection(options, [connectionListener])#

+

Constructs a new socket object and opens the socket to the given location. +When the socket is established, the 'connect' event will be emitted. + +

+

For TCP sockets, options argument should be an object which specifies: + +

+
    +
  • port: Port the client should connect to (Required).

    +
  • +
  • host: Host the client should connect to. Defaults to 'localhost'.

    +
  • +
  • localAddress: Local interface to bind to for network connections.

    +
  • +
+

For UNIX domain sockets, options argument should be an object which specifies: + +

+
    +
  • path: Path the client should connect to (Required).
  • +
+

Common options are: + +

+
    +
  • allowHalfOpen: if true, the socket won't automatically send +a FIN packet when the other end of the socket sends a FIN packet. +Defaults to false. See 'end' event for more information.
  • +
+

The connectListener parameter will be added as an listener for the +'connect' event. + +

+

Here is an example of a client of echo server as described previously: + +

+
var net = require('net');
+var client = net.connect({port: 8124},
+    function() { //'connect' listener
+  console.log('client connected');
+  client.write('world!\r\n');
+});
+client.on('data', function(data) {
+  console.log(data.toString());
+  client.end();
+});
+client.on('end', function() {
+  console.log('client disconnected');
+});
+

To connect on the socket /tmp/echo.sock the second line would just be +changed to + +

+
var client = net.connect({path: '/tmp/echo.sock'},
+

net.connect(port, [host], [connectListener])#

+

net.createConnection(port, [host], [connectListener])#

+

Creates a TCP connection to port on host. If host is omitted, +'localhost' will be assumed. +The connectListener parameter will be added as an listener for the +'connect' event. + +

+

net.connect(path, [connectListener])#

+

net.createConnection(path, [connectListener])#

+

Creates unix socket connection to path. +The connectListener parameter will be added as an listener for the +'connect' event. + +

+

Class: net.Server#

+

This class is used to create a TCP or UNIX server. +A server is a net.Socket that can listen for new incoming connections. + +

+

server.listen(port, [host], [backlog], [callback])#

+

Begin accepting connections on the specified port and host. If the +host is omitted, the server will accept connections directed to any +IPv4 address (INADDR_ANY). A port value of zero will assign a random port. + +

+

Backlog is the maximum length of the queue of pending connections. +The actual length will be determined by your OS through sysctl settings such as +tcp_max_syn_backlog and somaxconn on linux. The default value of this +parameter is 511 (not 512). + +

+

This function is asynchronous. When the server has been bound, +'listening' event will be emitted. The last parameter callback +will be added as an listener for the 'listening' event. + +

+

One issue some users run into is getting EADDRINUSE errors. This means that +another server is already running on the requested port. One way of handling this +would be to wait a second and then try again. This can be done with + +

+
server.on('error', function (e) {
+  if (e.code == 'EADDRINUSE') {
+    console.log('Address in use, retrying...');
+    setTimeout(function () {
+      server.close();
+      server.listen(PORT, HOST);
+    }, 1000);
+  }
+});
+

(Note: All sockets in Node set SO_REUSEADDR already) + + +

+

server.listen(path, [callback])#

+

Start a UNIX socket server listening for connections on the given path. + +

+

This function is asynchronous. When the server has been bound, +'listening' event will be emitted. The last parameter callback +will be added as an listener for the 'listening' event. + +

+

server.listen(handle, [callback])#

+
    +
  • handle Object
  • +
  • callback Function
  • +
+

The handle object can be set to either a server or socket (anything +with an underlying _handle member), or a {fd: <n>} object. + +

+

This will cause the server to accept connections on the specified +handle, but it is presumed that the file descriptor or handle has +already been bound to a port or domain socket. + +

+

Listening on a file descriptor is not supported on Windows. + +

+

This function is asynchronous. When the server has been bound, +'listening' event will be emitted. +the last parameter callback will be added as an listener for the +'listening' event. + +

+

server.close([callback])#

+

Stops the server from accepting new connections and keeps existing +connections. This function is asynchronous, the server is finally +closed when all connections are ended and the server emits a 'close' +event. Optionally, you can pass a callback to listen for the 'close' +event. + +

+

server.address()#

+

Returns the bound address, the address family name and port of the server +as reported by the operating system. +Useful to find which port was assigned when giving getting an OS-assigned address. +Returns an object with three properties, e.g. +{ port: 12346, family: 'IPv4', address: '127.0.0.1' } + +

+

Example: + +

+
var server = net.createServer(function (socket) {
+  socket.end("goodbye\n");
+});
+
+// grab a random port.
+server.listen(function() {
+  address = server.address();
+  console.log("opened server on %j", address);
+});
+

Don't call server.address() until the 'listening' event has been emitted. + +

+

server.maxConnections#

+

Set this property to reject connections when the server's connection count gets +high. + +

+

It is not recommended to use this option once a socket has been sent to a child +with child_process.fork(). + +

+

server.connections#

+

The number of concurrent connections on the server. + +

+

This becomes null when sending a socket to a child with child_process.fork(). + +

+

net.Server is an EventEmitter with the following events: + +

+

Event: 'listening'#

+

Emitted when the server has been bound after calling server.listen. + +

+

Event: 'connection'#

+
    +
  • Socket object The connection object
  • +
+

Emitted when a new connection is made. socket is an instance of +net.Socket. + +

+

Event: 'close'#

+

Emitted when the server closes. Note that if connections exist, this +event is not emitted until all connections are ended. + +

+

Event: 'error'#

+
    +
  • Error Object
  • +
+

Emitted when an error occurs. The 'close' event will be called directly +following this event. See example in discussion of server.listen. + +

+

Class: net.Socket#

+

This object is an abstraction of a TCP or UNIX socket. net.Socket +instances implement a duplex Stream interface. They can be created by the +user and used as a client (with connect()) or they can be created by Node +and passed to the user through the 'connection' event of a server. + +

+

new net.Socket([options])#

+

Construct a new socket object. + +

+

options is an object with the following defaults: + +

+
{ fd: null
+  type: null
+  allowHalfOpen: false
+}
+

fd allows you to specify the existing file descriptor of socket. type +specified underlying protocol. It can be 'tcp4', 'tcp6', or 'unix'. +About allowHalfOpen, refer to createServer() and 'end' event. + +

+

socket.connect(port, [host], [connectListener])#

+

socket.connect(path, [connectListener])#

+

Opens the connection for a given socket. If port and host are given, +then the socket will be opened as a TCP socket, if host is omitted, +localhost will be assumed. If a path is given, the socket will be +opened as a unix socket to that path. + +

+

Normally this method is not needed, as net.createConnection opens the +socket. Use this only if you are implementing a custom Socket or if a +Socket is closed and you want to reuse it to connect to another server. + +

+

This function is asynchronous. When the 'connect' event is emitted the +socket is established. If there is a problem connecting, the 'connect' event +will not be emitted, the 'error' event will be emitted with the exception. + +

+

The connectListener parameter will be added as an listener for the +'connect' event. + + +

+

socket.bufferSize#

+

net.Socket has the property that socket.write() always works. This is to +help users get up and running quickly. The computer cannot always keep up +with the amount of data that is written to a socket - the network connection +simply might be too slow. Node will internally queue up the data written to a +socket and send it out over the wire when it is possible. (Internally it is +polling on the socket's file descriptor for being writable). + +

+

The consequence of this internal buffering is that memory may grow. This +property shows the number of characters currently buffered to be written. +(Number of characters is approximately equal to the number of bytes to be +written, but the buffer may contain strings, and the strings are lazily +encoded, so the exact number of bytes is not known.) + +

+

Users who experience large or growing bufferSize should attempt to +"throttle" the data flows in their program with pause() and resume(). + + +

+

socket.setEncoding([encoding])#

+

Set the encoding for the socket as a Readable Stream. See +stream.setEncoding() for more information. + +

+

socket.write(data, [encoding], [callback])#

+

Sends data on the socket. The second parameter specifies the encoding in the +case of a string--it defaults to UTF8 encoding. + +

+

Returns true if the entire data was flushed successfully to the kernel +buffer. Returns false if all or part of the data was queued in user memory. +'drain' will be emitted when the buffer is again free. + +

+

The optional callback parameter will be executed when the data is finally +written out - this may not be immediately. + +

+

socket.end([data], [encoding])#

+

Half-closes the socket. i.e., it sends a FIN packet. It is possible the +server will still send some data. + +

+

If data is specified, it is equivalent to calling +socket.write(data, encoding) followed by socket.end(). + +

+

socket.destroy()#

+

Ensures that no more I/O activity happens on this socket. Only necessary in +case of errors (parse error or so). + +

+

socket.pause()#

+

Pauses the reading of data. That is, 'data' events will not be emitted. +Useful to throttle back an upload. + +

+

socket.resume()#

+

Resumes reading after a call to pause(). + +

+

socket.setTimeout(timeout, [callback])#

+

Sets the socket to timeout after timeout milliseconds of inactivity on +the socket. By default net.Socket do not have a timeout. + +

+

When an idle timeout is triggered the socket will receive a 'timeout' +event but the connection will not be severed. The user must manually end() +or destroy() the socket. + +

+

If timeout is 0, then the existing idle timeout is disabled. + +

+

The optional callback parameter will be added as a one time listener for the +'timeout' event. + +

+

socket.setNoDelay([noDelay])#

+

Disables the Nagle algorithm. By default TCP connections use the Nagle +algorithm, they buffer data before sending it off. Setting true for +noDelay will immediately fire off data each time socket.write() is called. +noDelay defaults to true. + +

+

socket.setKeepAlive([enable], [initialDelay])#

+

Enable/disable keep-alive functionality, and optionally set the initial +delay before the first keepalive probe is sent on an idle socket. +enable defaults to false. + +

+

Set initialDelay (in milliseconds) to set the delay between the last +data packet received and the first keepalive probe. Setting 0 for +initialDelay will leave the value unchanged from the default +(or previous) setting. Defaults to 0. + +

+

socket.address()#

+

Returns the bound address, the address family name and port of the +socket as reported by the operating system. Returns an object with +three properties, e.g. +{ port: 12346, family: 'IPv4', address: '127.0.0.1' } + +

+

socket.remoteAddress#

+

The string representation of the remote IP address. For example, +'74.125.127.100' or '2001:4860:a005::68'. + +

+

socket.remotePort#

+

The numeric representation of the remote port. For example, +80 or 21. + +

+

socket.bytesRead#

+

The amount of received bytes. + +

+

socket.bytesWritten#

+

The amount of bytes sent. + + +

+

net.Socket instances are EventEmitter with the following events: + +

+

Event: 'connect'#

+

Emitted when a socket connection is successfully established. +See connect(). + +

+

Event: 'data'#

+
    +
  • Buffer object
  • +
+

Emitted when data is received. The argument data will be a Buffer or +String. Encoding of data is set by socket.setEncoding(). +(See the Readable Stream section for more information.) + +

+

Note that the data will be lost if there is no listener when a Socket +emits a 'data' event. + +

+

Event: 'end'#

+

Emitted when the other end of the socket sends a FIN packet. + +

+

By default (allowHalfOpen == false) the socket will destroy its file +descriptor once it has written out its pending write queue. However, by +setting allowHalfOpen == true the socket will not automatically end() +its side allowing the user to write arbitrary amounts of data, with the +caveat that the user is required to end() their side now. + + +

+

Event: 'timeout'#

+

Emitted if the socket times out from inactivity. This is only to notify that +the socket has been idle. The user must manually close the connection. + +

+

See also: socket.setTimeout() + + +

+

Event: 'drain'#

+

Emitted when the write buffer becomes empty. Can be used to throttle uploads. + +

+

See also: the return values of socket.write() + +

+

Event: 'error'#

+
    +
  • Error object
  • +
+

Emitted when an error occurs. The 'close' event will be called directly +following this event. + +

+

Event: 'close'#

+
    +
  • had_error Boolean true if the socket had a transmission error
  • +
+

Emitted once the socket is fully closed. The argument had_error is a boolean +which says if the socket was closed due to a transmission error. + +

+

net.isIP(input)#

+

Tests if input is an IP address. Returns 0 for invalid strings, +returns 4 for IP version 4 addresses, and returns 6 for IP version 6 addresses. + + +

+

net.isIPv4(input)#

+

Returns true if input is a version 4 IP address, otherwise returns false. + + +

+

net.isIPv6(input)#

+

Returns true if input is a version 6 IP address, otherwise returns false. + +

+

UDP / Datagram Sockets#

+
Stability: 3 - Stable
+ + +

Datagram sockets are available through require('dgram'). + +

+

dgram.createSocket(type, [callback])#

+
    +
  • type String. Either 'udp4' or 'udp6'
  • +
  • callback Function. Attached as a listener to message events. +Optional
  • +
  • Returns: Socket object
  • +
+

Creates a datagram Socket of the specified types. Valid types are udp4 +and udp6. + +

+

Takes an optional callback which is added as a listener for message events. + +

+

Call socket.bind if you want to receive datagrams. socket.bind() will bind +to the "all interfaces" address on a random port (it does the right thing for +both udp4 and udp6 sockets). You can then retrieve the address and port +with socket.address().address and socket.address().port. + +

+

Class: Socket#

+

The dgram Socket class encapsulates the datagram functionality. It +should be created via dgram.createSocket(type, [callback]). + +

+

Event: 'message'#

+
    +
  • msg Buffer object. The message
  • +
  • rinfo Object. Remote address information
  • +
+

Emitted when a new datagram is available on a socket. msg is a Buffer and rinfo is +an object with the sender's address information and the number of bytes in the datagram. + +

+

Event: 'listening'#

+

Emitted when a socket starts listening for datagrams. This happens as soon as UDP sockets +are created. + +

+

Event: 'close'#

+

Emitted when a socket is closed with close(). No new message events will be emitted +on this socket. + +

+

Event: 'error'#

+
    +
  • exception Error object
  • +
+

Emitted when an error occurs. + +

+

dgram.send(buf, offset, length, port, address, [callback])#

+
    +
  • buf Buffer object. Message to be sent
  • +
  • offset Integer. Offset in the buffer where the message starts.
  • +
  • length Integer. Number of bytes in the message.
  • +
  • port Integer. destination port
  • +
  • address String. destination IP
  • +
  • callback Function. Callback when message is done being delivered. +Optional.
  • +
+

For UDP sockets, the destination port and IP address must be specified. A string +may be supplied for the address parameter, and it will be resolved with DNS. An +optional callback may be specified to detect any DNS errors and when buf may be +re-used. Note that DNS lookups will delay the time that a send takes place, at +least until the next tick. The only way to know for sure that a send has taken place +is to use the callback. + +

+

If the socket has not been previously bound with a call to bind, it's +assigned a random port number and bound to the "all interfaces" address +(0.0.0.0 for udp4 sockets, ::0 for udp6 sockets). + +

+

Example of sending a UDP packet to a random port on localhost; + +

+
var dgram = require('dgram');
+var message = new Buffer("Some bytes");
+var client = dgram.createSocket("udp4");
+client.send(message, 0, message.length, 41234, "localhost", function(err, bytes) {
+  client.close();
+});
+

A Note about UDP datagram size + +

+

The maximum size of an IPv4/v6 datagram depends on the MTU (Maximum Transmission Unit) +and on the Payload Length field size. + +

+
    +
  • The Payload Length field is 16 bits wide, which means that a normal payload +cannot be larger than 64K octets including internet header and data +(65,507 bytes = 65,535 − 8 bytes UDP header − 20 bytes IP header); +this is generally true for loopback interfaces, but such long datagrams +are impractical for most hosts and networks.

    +
  • +
  • The MTU is the largest size a given link layer technology can support for datagrams. +For any link, IPv4 mandates a minimum MTU of 68 octets, while the recommended MTU +for IPv4 is 576 (typically recommended as the MTU for dial-up type applications), +whether they arrive whole or in fragments.

    +

    For IPv6, the minimum MTU is 1280 octets, however, the mandatory minimum +fragment reassembly buffer size is 1500 octets. +The value of 68 octets is very small, since most current link layer technologies have +a minimum MTU of 1500 (like Ethernet).

    +
  • +
+

Note that it's impossible to know in advance the MTU of each link through which +a packet might travel, and that generally sending a datagram greater than +the (receiver) MTU won't work (the packet gets silently dropped, without +informing the source that the data did not reach its intended recipient). + +

+

dgram.bind(port, [address])#

+
    +
  • port Integer
  • +
  • address String, Optional
  • +
+

For UDP sockets, listen for datagrams on a named port and optional address. If +address is not specified, the OS will try to listen on all addresses. + +

+

Example of a UDP server listening on port 41234: + +

+
var dgram = require("dgram");
+
+var server = dgram.createSocket("udp4");
+
+server.on("message", function (msg, rinfo) {
+  console.log("server got: " + msg + " from " +
+    rinfo.address + ":" + rinfo.port);
+});
+
+server.on("listening", function () {
+  var address = server.address();
+  console.log("server listening " +
+      address.address + ":" + address.port);
+});
+
+server.bind(41234);
+// server listening 0.0.0.0:41234
+

dgram.close()#

+

Close the underlying socket and stop listening for data on it. + +

+

dgram.address()#

+

Returns an object containing the address information for a socket. For UDP sockets, +this object will contain address , family and port. + +

+

dgram.setBroadcast(flag)#

+
    +
  • flag Boolean
  • +
+

Sets or clears the SO_BROADCAST socket option. When this option is set, UDP packets +may be sent to a local interface's broadcast address. + +

+

dgram.setTTL(ttl)#

+
    +
  • ttl Integer
  • +
+

Sets the IP_TTL socket option. TTL stands for "Time to Live," but in this context it +specifies the number of IP hops that a packet is allowed to go through. Each router or +gateway that forwards a packet decrements the TTL. If the TTL is decremented to 0 by a +router, it will not be forwarded. Changing TTL values is typically done for network +probes or when multicasting. + +

+

The argument to setTTL() is a number of hops between 1 and 255. The default on most +systems is 64. + +

+

dgram.setMulticastTTL(ttl)#

+
    +
  • ttl Integer
  • +
+

Sets the IP_MULTICAST_TTL socket option. TTL stands for "Time to Live," but in this +context it specifies the number of IP hops that a packet is allowed to go through, +specifically for multicast traffic. Each router or gateway that forwards a packet +decrements the TTL. If the TTL is decremented to 0 by a router, it will not be forwarded. + +

+

The argument to setMulticastTTL() is a number of hops between 0 and 255. The default on most +systems is 1. + +

+

dgram.setMulticastLoopback(flag)#

+
    +
  • flag Boolean
  • +
+

Sets or clears the IP_MULTICAST_LOOP socket option. When this option is set, multicast +packets will also be received on the local interface. + +

+

dgram.addMembership(multicastAddress, [multicastInterface])#

+
    +
  • multicastAddress String
  • +
  • multicastInterface String, Optional
  • +
+

Tells the kernel to join a multicast group with IP_ADD_MEMBERSHIP socket option. + +

+

If multicastInterface is not specified, the OS will try to add membership to all valid +interfaces. + +

+

dgram.dropMembership(multicastAddress, [multicastInterface])#

+
    +
  • multicastAddress String
  • +
  • multicastInterface String, Optional
  • +
+

Opposite of addMembership - tells the kernel to leave a multicast group with +IP_DROP_MEMBERSHIP socket option. This is automatically called by the kernel +when the socket is closed or process terminates, so most apps will never need to call +this. + +

+

If multicastInterface is not specified, the OS will try to drop membership to all valid +interfaces. + +

+

DNS#

+
Stability: 3 - Stable
+

Use require('dns') to access this module. All methods in the dns module +use C-Ares except for dns.lookup which uses getaddrinfo(3) in a thread +pool. C-Ares is much faster than getaddrinfo but the system resolver is +more constant with how other programs operate. When a user does +net.connect(80, 'google.com') or http.get({ host: 'google.com' }) the +dns.lookup method is used. Users who need to do a large number of look ups +quickly should use the methods that go through C-Ares. + +

+

Here is an example which resolves 'www.google.com' then reverse +resolves the IP addresses which are returned. + +

+
var dns = require('dns');
+
+dns.resolve4('www.google.com', function (err, addresses) {
+  if (err) throw err;
+
+  console.log('addresses: ' + JSON.stringify(addresses));
+
+  addresses.forEach(function (a) {
+    dns.reverse(a, function (err, domains) {
+      if (err) {
+        throw err;
+      }
+
+      console.log('reverse for ' + a + ': ' + JSON.stringify(domains));
+    });
+  });
+});
+

dns.lookup(domain, [family], callback)#

+

Resolves a domain (e.g. 'google.com') into the first found A (IPv4) or +AAAA (IPv6) record. +The family can be the integer 4 or 6. Defaults to null that indicates +both Ip v4 and v6 address family. + +

+

The callback has arguments (err, address, family). The address argument +is a string representation of a IP v4 or v6 address. The family argument +is either the integer 4 or 6 and denotes the family of address (not +necessarily the value initially passed to lookup). + +

+

On error, err is an Error object, where err.code is the error code. +Keep in mind that err.code will be set to 'ENOENT' not only when +the domain does not exist but also when the lookup fails in other ways +such as no available file descriptors. + + +

+

dns.resolve(domain, [rrtype], callback)#

+

Resolves a domain (e.g. 'google.com') into an array of the record types +specified by rrtype. Valid rrtypes are 'A' (IPV4 addresses, default), +'AAAA' (IPV6 addresses), 'MX' (mail exchange records), 'TXT' (text +records), 'SRV' (SRV records), 'PTR' (used for reverse IP lookups), +'NS' (name server records) and 'CNAME' (canonical name records). + +

+

The callback has arguments (err, addresses). The type of each item +in addresses is determined by the record type, and described in the +documentation for the corresponding lookup methods below. + +

+

On error, err is an Error object, where err.code is +one of the error codes listed below. + + +

+

dns.resolve4(domain, callback)#

+

The same as dns.resolve(), but only for IPv4 queries (A records). +addresses is an array of IPv4 addresses (e.g. +['74.125.79.104', '74.125.79.105', '74.125.79.106']). + +

+

dns.resolve6(domain, callback)#

+

The same as dns.resolve4() except for IPv6 queries (an AAAA query). + + +

+

dns.resolveMx(domain, callback)#

+

The same as dns.resolve(), but only for mail exchange queries (MX records). + +

+

addresses is an array of MX records, each with a priority and an exchange +attribute (e.g. [{'priority': 10, 'exchange': 'mx.example.com'},...]). + +

+

dns.resolveTxt(domain, callback)#

+

The same as dns.resolve(), but only for text queries (TXT records). +addresses is an array of the text records available for domain (e.g., +['v=spf1 ip4:0.0.0.0 ~all']). + +

+

dns.resolveSrv(domain, callback)#

+

The same as dns.resolve(), but only for service records (SRV records). +addresses is an array of the SRV records available for domain. Properties +of SRV records are priority, weight, port, and name (e.g., +[{'priority': 10, {'weight': 5, 'port': 21223, 'name': 'service.example.com'}, ...]). + +

+

dns.resolveNs(domain, callback)#

+

The same as dns.resolve(), but only for name server records (NS records). +addresses is an array of the name server records available for domain +(e.g., ['ns1.example.com', 'ns2.example.com']). + +

+

dns.resolveCname(domain, callback)#

+

The same as dns.resolve(), but only for canonical name records (CNAME +records). addresses is an array of the canonical name records available for +domain (e.g., ['bar.example.com']). + +

+

dns.reverse(ip, callback)#

+

Reverse resolves an ip address to an array of domain names. + +

+

The callback has arguments (err, domains). + +

+

On error, err is an Error object, where err.code is +one of the error codes listed below. + +

+

Error codes#

+

Each DNS query can return one of the following error codes: + +

+
    +
  • dns.NODATA: DNS server returned answer with no data.
  • +
  • dns.FORMERR: DNS server claims query was misformatted.
  • +
  • dns.SERVFAIL: DNS server returned general failure.
  • +
  • dns.NOTFOUND: Domain name not found.
  • +
  • dns.NOTIMP: DNS server does not implement requested operation.
  • +
  • dns.REFUSED: DNS server refused query.
  • +
  • dns.BADQUERY: Misformatted DNS query.
  • +
  • dns.BADNAME: Misformatted domain name.
  • +
  • dns.BADFAMILY: Unsupported address family.
  • +
  • dns.BADRESP: Misformatted DNS reply.
  • +
  • dns.CONNREFUSED: Could not contact DNS servers.
  • +
  • dns.TIMEOUT: Timeout while contacting DNS servers.
  • +
  • dns.EOF: End of file.
  • +
  • dns.FILE: Error reading file.
  • +
  • dns.NOMEM: Out of memory.
  • +
  • dns.DESTRUCTION: Channel is being destroyed.
  • +
  • dns.BADSTR: Misformatted string.
  • +
  • dns.BADFLAGS: Illegal flags specified.
  • +
  • dns.NONAME: Given hostname is not numeric.
  • +
  • dns.BADHINTS: Illegal hints flags specified.
  • +
  • dns.NOTINITIALIZED: c-ares library initialization not yet performed.
  • +
  • dns.LOADIPHLPAPI: Error loading iphlpapi.dll.
  • +
  • dns.ADDRGETNETWORKPARAMS: Could not find GetNetworkParams function.
  • +
  • dns.CANCELLED: DNS query cancelled.
  • +
+

HTTP#

+
Stability: 3 - Stable
+

To use the HTTP server and client one must require('http'). + +

+

The HTTP interfaces in Node are designed to support many features +of the protocol which have been traditionally difficult to use. +In particular, large, possibly chunk-encoded, messages. The interface is +careful to never buffer entire requests or responses--the +user is able to stream data. + +

+

HTTP message headers are represented by an object like this: + +

+
{ 'content-length': '123',
+  'content-type': 'text/plain',
+  'connection': 'keep-alive',
+  'accept': '*/*' }
+

Keys are lowercased. Values are not modified. + +

+

In order to support the full spectrum of possible HTTP applications, Node's +HTTP API is very low-level. It deals with stream handling and message +parsing only. It parses a message into headers and body but it does not +parse the actual headers or the body. + + +

+

http.STATUS_CODES#

+
    +
  • Object
  • +
+

A collection of all the standard HTTP response status codes, and the +short description of each. For example, http.STATUS_CODES[404] === 'Not +Found'. + +

+

http.createServer([requestListener])#

+

Returns a new web server object. + +

+

The requestListener is a function which is automatically +added to the 'request' event. + +

+

http.createClient([port], [host])#

+

This function is deprecated; please use http.request() instead. +Constructs a new HTTP client. port and host refer to the server to be +connected to. + +

+

Class: http.Server#

+

This is an EventEmitter with the following events: + +

+

Event: 'request'#

+

function (request, response) { } + +

+

Emitted each time there is a request. Note that there may be multiple requests +per connection (in the case of keep-alive connections). + request is an instance of http.ServerRequest and response is + an instance of http.ServerResponse + +

+

Event: 'connection'#

+

function (socket) { } + +

+

When a new TCP stream is established. socket is an object of type + net.Socket. Usually users will not want to access this event. The + socket can also be accessed at request.connection. + +

+

Event: 'close'#

+

function () { } + +

+

Emitted when the server closes. + +

+

Event: 'checkContinue'#

+

function (request, response) { } + +

+

Emitted each time a request with an http Expect: 100-continue is received. +If this event isn't listened for, the server will automatically respond +with a 100 Continue as appropriate. + +

+

Handling this event involves calling response.writeContinue if the client +should continue to send the request body, or generating an appropriate HTTP +response (e.g., 400 Bad Request) if the client should not continue to send the +request body. + +

+

Note that when this event is emitted and handled, the request event will +not be emitted. + +

+

Event: 'connect'#

+

function (request, socket, head) { } + +

+

Emitted each time a client requests a http CONNECT method. If this event isn't +listened for, then clients requesting a CONNECT method will have their +connections closed. + +

+
    +
  • request is the arguments for the http request, as it is in the request +event.
  • +
  • socket is the network socket between the server and client.
  • +
  • head is an instance of Buffer, the first packet of the tunneling stream, +this may be empty.
  • +
+

After this event is emitted, the request's socket will not have a data +event listener, meaning you will need to bind to it in order to handle data +sent to the server on that socket. + +

+

Event: 'upgrade'#

+

function (request, socket, head) { } + +

+

Emitted each time a client requests a http upgrade. If this event isn't +listened for, then clients requesting an upgrade will have their connections +closed. + +

+
    +
  • request is the arguments for the http request, as it is in the request +event.
  • +
  • socket is the network socket between the server and client.
  • +
  • head is an instance of Buffer, the first packet of the upgraded stream, +this may be empty.
  • +
+

After this event is emitted, the request's socket will not have a data +event listener, meaning you will need to bind to it in order to handle data +sent to the server on that socket. + +

+

Event: 'clientError'#

+

function (exception) { } + +

+

If a client connection emits an 'error' event - it will forwarded here. + +

+

server.listen(port, [hostname], [backlog], [callback])#

+

Begin accepting connections on the specified port and hostname. If the +hostname is omitted, the server will accept connections directed to any +IPv4 address (INADDR_ANY). + +

+

To listen to a unix socket, supply a filename instead of port and hostname. + +

+

Backlog is the maximum length of the queue of pending connections. +The actual length will be determined by your OS through sysctl settings such as +tcp_max_syn_backlog and somaxconn on linux. The default value of this +parameter is 511 (not 512). + +

+

This function is asynchronous. The last parameter callback will be added as +a listener for the 'listening' event. See also net.Server.listen(port). + + +

+

server.listen(path, [callback])#

+

Start a UNIX socket server listening for connections on the given path. + +

+

This function is asynchronous. The last parameter callback will be added as +a listener for the 'listening' event. See also net.Server.listen(path). + + +

+

server.listen(handle, [callback])#

+
    +
  • handle Object
  • +
  • callback Function
  • +
+

The handle object can be set to either a server or socket (anything +with an underlying _handle member), or a {fd: <n>} object. + +

+

This will cause the server to accept connections on the specified +handle, but it is presumed that the file descriptor or handle has +already been bound to a port or domain socket. + +

+

Listening on a file descriptor is not supported on Windows. + +

+

This function is asynchronous. The last parameter callback will be added as +a listener for the 'listening' event. +See also net.Server.listen(). + +

+

server.close([callback])#

+

Stops the server from accepting new connections. See net.Server.close(). + + +

+

server.maxHeadersCount#

+

Limits maximum incoming headers count, equal to 1000 by default. If set to 0 - +no limit will be applied. + + +

+

Class: http.ServerRequest#

+

This object is created internally by a HTTP server -- not by +the user -- and passed as the first argument to a 'request' listener. + +

+

The request implements the Readable Stream interface. This is an +EventEmitter with the following events: + +

+

Event: 'data'#

+

function (chunk) { } + +

+

Emitted when a piece of the message body is received. The chunk is a string if +an encoding has been set with request.setEncoding(), otherwise it's a +Buffer. + +

+

Note that the data will be lost if there is no listener when a +ServerRequest emits a 'data' event. + +

+

Event: 'end'#

+

function () { } + +

+

Emitted exactly once for each request. After that, no more 'data' events +will be emitted on the request. + +

+

Event: 'close'#

+

function () { } + +

+

Indicates that the underlaying connection was terminated before +response.end() was called or able to flush. + +

+

Just like 'end', this event occurs only once per request, and no more 'data' +events will fire afterwards. + +

+

Note: 'close' can fire after 'end', but not vice versa. + +

+

request.method#

+

The request method as a string. Read only. Example: +'GET', 'DELETE'. + + +

+

request.url#

+

Request URL string. This contains only the URL that is +present in the actual HTTP request. If the request is: + +

+
GET /status?name=ryan HTTP/1.1\r\n
+Accept: text/plain\r\n
+\r\n
+

Then request.url will be: + +

+
'/status?name=ryan'
+

If you would like to parse the URL into its parts, you can use +require('url').parse(request.url). Example: + +

+
node> require('url').parse('/status?name=ryan')
+{ href: '/status?name=ryan',
+  search: '?name=ryan',
+  query: 'name=ryan',
+  pathname: '/status' }
+

If you would like to extract the params from the query string, +you can use the require('querystring').parse function, or pass +true as the second argument to require('url').parse. Example: + +

+
node> require('url').parse('/status?name=ryan', true)
+{ href: '/status?name=ryan',
+  search: '?name=ryan',
+  query: { name: 'ryan' },
+  pathname: '/status' }
+

request.headers#

+

Read only map of header names and values. Header names are lower-cased. +Example: + +

+
// Prints something like:
+//
+// { 'user-agent': 'curl/7.22.0',
+//   host: '127.0.0.1:8000',
+//   accept: '*/*' }
+console.log(request.headers);
+

request.trailers#

+

Read only; HTTP trailers (if present). Only populated after the 'end' event. + +

+

request.httpVersion#

+

The HTTP protocol version as a string. Read only. Examples: +'1.1', '1.0'. +Also request.httpVersionMajor is the first integer and +request.httpVersionMinor is the second. + + +

+

request.setEncoding([encoding])#

+

Set the encoding for the request body. See stream.setEncoding() for more +information. + +

+

request.pause()#

+

Pauses request from emitting events. Useful to throttle back an upload. + + +

+

request.resume()#

+

Resumes a paused request. + +

+

request.connection#

+

The net.Socket object associated with the connection. + + +

+

With HTTPS support, use request.connection.verifyPeer() and +request.connection.getPeerCertificate() to obtain the client's +authentication details. + + + +

+

Class: http.ServerResponse#

+

This object is created internally by a HTTP server--not by the user. It is +passed as the second parameter to the 'request' event. + +

+

The response implements the Writable Stream interface. This is an +EventEmitter with the following events: + +

+

Event: 'close'#

+

function () { } + +

+

Indicates that the underlaying connection was terminated before +response.end() was called or able to flush. + +

+

response.writeContinue()#

+

Sends a HTTP/1.1 100 Continue message to the client, indicating that +the request body should be sent. See the 'checkContinue' event on Server. + +

+

response.writeHead(statusCode, [reasonPhrase], [headers])#

+

Sends a response header to the request. The status code is a 3-digit HTTP +status code, like 404. The last argument, headers, are the response headers. +Optionally one can give a human-readable reasonPhrase as the second +argument. + +

+

Example: + +

+
var body = 'hello world';
+response.writeHead(200, {
+  'Content-Length': body.length,
+  'Content-Type': 'text/plain' });
+

This method must only be called once on a message and it must +be called before response.end() is called. + +

+

If you call response.write() or response.end() before calling this, the +implicit/mutable headers will be calculated and call this function for you. + +

+

Note: that Content-Length is given in bytes not characters. The above example +works because the string 'hello world' contains only single byte characters. +If the body contains higher coded characters then Buffer.byteLength() +should be used to determine the number of bytes in a given encoding. +And Node does not check whether Content-Length and the length of the body +which has been transmitted are equal or not. + +

+

response.statusCode#

+

When using implicit headers (not calling response.writeHead() explicitly), this property +controls the status code that will be sent to the client when the headers get +flushed. + +

+

Example: + +

+
response.statusCode = 404;
+

After response header was sent to the client, this property indicates the +status code which was sent out. + +

+

response.setHeader(name, value)#

+

Sets a single header value for implicit headers. If this header already exists +in the to-be-sent headers, its value will be replaced. Use an array of strings +here if you need to send multiple headers with the same name. + +

+

Example: + +

+
response.setHeader("Content-Type", "text/html");
+

or + +

+
response.setHeader("Set-Cookie", ["type=ninja", "language=javascript"]);
+

response.sendDate#

+

When true, the Date header will be automatically generated and sent in +the response if it is not already present in the headers. Defaults to true. + +

+

This should only be disabled for testing; HTTP requires the Date header +in responses. + +

+

response.getHeader(name)#

+

Reads out a header that's already been queued but not sent to the client. Note +that the name is case insensitive. This can only be called before headers get +implicitly flushed. + +

+

Example: + +

+
var contentType = response.getHeader('content-type');
+

response.removeHeader(name)#

+

Removes a header that's queued for implicit sending. + +

+

Example: + +

+
response.removeHeader("Content-Encoding");
+

response.write(chunk, [encoding])#

+

If this method is called and response.writeHead() has not been called, it will +switch to implicit header mode and flush the implicit headers. + +

+

This sends a chunk of the response body. This method may +be called multiple times to provide successive parts of the body. + +

+

chunk can be a string or a buffer. If chunk is a string, +the second parameter specifies how to encode it into a byte stream. +By default the encoding is 'utf8'. + +

+

Note: This is the raw HTTP body and has nothing to do with +higher-level multi-part body encodings that may be used. + +

+

The first time response.write() is called, it will send the buffered +header information and the first body to the client. The second time +response.write() is called, Node assumes you're going to be streaming +data, and sends that separately. That is, the response is buffered up to the +first chunk of body. + +

+

Returns true if the entire data was flushed successfully to the kernel +buffer. Returns false if all or part of the data was queued in user memory. +'drain' will be emitted when the buffer is again free. + +

+

response.addTrailers(headers)#

+

This method adds HTTP trailing headers (a header but at the end of the +message) to the response. + +

+

Trailers will only be emitted if chunked encoding is used for the +response; if it is not (e.g., if the request was HTTP/1.0), they will +be silently discarded. + +

+

Note that HTTP requires the Trailer header to be sent if you intend to +emit trailers, with a list of the header fields in its value. E.g., + +

+
response.writeHead(200, { 'Content-Type': 'text/plain',
+                          'Trailer': 'Content-MD5' });
+response.write(fileData);
+response.addTrailers({'Content-MD5': "7895bf4b8828b55ceaf47747b4bca667"});
+response.end();
+

response.end([data], [encoding])#

+

This method signals to the server that all of the response headers and body +have been sent; that server should consider this message complete. +The method, response.end(), MUST be called on each +response. + +

+

If data is specified, it is equivalent to calling response.write(data, encoding) +followed by response.end(). + + +

+

http.request(options, callback)#

+

Node maintains several connections per server to make HTTP requests. +This function allows one to transparently issue requests. + +

+

options can be an object or a string. If options is a string, it is +automatically parsed with url.parse(). + +

+

Options: + +

+
    +
  • host: A domain name or IP address of the server to issue the request to. +Defaults to 'localhost'.
  • +
  • hostname: To support url.parse() hostname is preferred over host
  • +
  • port: Port of remote server. Defaults to 80.
  • +
  • localAddress: Local interface to bind for network connections.
  • +
  • socketPath: Unix Domain Socket (use one of host:port or socketPath)
  • +
  • method: A string specifying the HTTP request method. Defaults to 'GET'.
  • +
  • path: Request path. Defaults to '/'. Should include query string if any. +E.G. '/index.html?page=12'
  • +
  • headers: An object containing request headers.
  • +
  • auth: Basic authentication i.e. 'user:password' to compute an +Authorization header.
  • +
  • agent: Controls Agent behavior. When an Agent is used request will +default to Connection: keep-alive. Possible values:
      +
    • undefined (default): use global Agent for this host and port.
    • +
    • Agent object: explicitly use the passed in Agent.
    • +
    • false: opts out of connection pooling with an Agent, defaults request to +Connection: close.
    • +
    +
  • +
+

http.request() returns an instance of the http.ClientRequest +class. The ClientRequest instance is a writable stream. If one needs to +upload a file with a POST request, then write to the ClientRequest object. + +

+

Example: + +

+
var options = {
+  host: 'www.google.com',
+  port: 80,
+  path: '/upload',
+  method: 'POST'
+};
+
+var req = http.request(options, function(res) {
+  console.log('STATUS: ' + res.statusCode);
+  console.log('HEADERS: ' + JSON.stringify(res.headers));
+  res.setEncoding('utf8');
+  res.on('data', function (chunk) {
+    console.log('BODY: ' + chunk);
+  });
+});
+
+req.on('error', function(e) {
+  console.log('problem with request: ' + e.message);
+});
+
+// write data to request body
+req.write('data\n');
+req.write('data\n');
+req.end();
+

Note that in the example req.end() was called. With http.request() one +must always call req.end() to signify that you're done with the request - +even if there is no data being written to the request body. + +

+

If any error is encountered during the request (be that with DNS resolution, +TCP level errors, or actual HTTP parse errors) an 'error' event is emitted +on the returned request object. + +

+

There are a few special headers that should be noted. + +

+
    +
  • Sending a 'Connection: keep-alive' will notify Node that the connection to +the server should be persisted until the next request.

    +
  • +
  • Sending a 'Content-length' header will disable the default chunked encoding.

    +
  • +
  • Sending an 'Expect' header will immediately send the request headers. +Usually, when sending 'Expect: 100-continue', you should both set a timeout +and listen for the continue event. See RFC2616 Section 8.2.3 for more +information.

    +
  • +
  • Sending an Authorization header will override using the auth option +to compute basic authentication.

    +
  • +
+

http.get(options, callback)#

+

Since most requests are GET requests without bodies, Node provides this +convenience method. The only difference between this method and http.request() +is that it sets the method to GET and calls req.end() automatically. + +

+

Example: + +

+
http.get("http://www.google.com/index.html", function(res) {
+  console.log("Got response: " + res.statusCode);
+}).on('error', function(e) {
+  console.log("Got error: " + e.message);
+});
+

Class: http.Agent#

+

In node 0.5.3+ there is a new implementation of the HTTP Agent which is used +for pooling sockets used in HTTP client requests. + +

+

Previously, a single agent instance helped pool for a single host+port. The +current implementation now holds sockets for any number of hosts. + +

+

The current HTTP Agent also defaults client requests to using +Connection:keep-alive. If no pending HTTP requests are waiting on a socket +to become free the socket is closed. This means that node's pool has the +benefit of keep-alive when under load but still does not require developers +to manually close the HTTP clients using keep-alive. + +

+

Sockets are removed from the agent's pool when the socket emits either a +"close" event or a special "agentRemove" event. This means that if you intend +to keep one HTTP request open for a long time and don't want it to stay in the +pool you can do something along the lines of: + +

+
http.get(options, function(res) {
+  // Do stuff
+}).on("socket", function (socket) {
+  socket.emit("agentRemove");
+});
+

Alternatively, you could just opt out of pooling entirely using agent:false: + +

+
http.get({host:'localhost', port:80, path:'/', agent:false}, function (res) {
+  // Do stuff
+})
+

agent.maxSockets#

+

By default set to 5. Determines how many concurrent sockets the agent can have +open per host. + +

+

agent.sockets#

+

An object which contains arrays of sockets currently in use by the Agent. Do not +modify. + +

+

agent.requests#

+

An object which contains queues of requests that have not yet been assigned to +sockets. Do not modify. + +

+

http.globalAgent#

+

Global instance of Agent which is used as the default for all http client +requests. + + +

+

Class: http.ClientRequest#

+

This object is created internally and returned from http.request(). It +represents an in-progress request whose header has already been queued. The +header is still mutable using the setHeader(name, value), getHeader(name), +removeHeader(name) API. The actual header will be sent along with the first +data chunk or when closing the connection. + +

+

To get the response, add a listener for 'response' to the request object. +'response' will be emitted from the request object when the response +headers have been received. The 'response' event is executed with one +argument which is an instance of http.ClientResponse. + +

+

During the 'response' event, one can add listeners to the +response object; particularly to listen for the 'data' event. Note that +the 'response' event is called before any part of the response body is received, +so there is no need to worry about racing to catch the first part of the +body. As long as a listener for 'data' is added during the 'response' +event, the entire body will be caught. + + +

+
// Good
+request.on('response', function (response) {
+  response.on('data', function (chunk) {
+    console.log('BODY: ' + chunk);
+  });
+});
+
+// Bad - misses all or part of the body
+request.on('response', function (response) {
+  setTimeout(function () {
+    response.on('data', function (chunk) {
+      console.log('BODY: ' + chunk);
+    });
+  }, 10);
+});
+

Note: Node does not check whether Content-Length and the length of the body +which has been transmitted are equal or not. + +

+

The request implements the Writable Stream interface. This is an +EventEmitter with the following events: + +

+

Event 'response'#

+

function (response) { } + +

+

Emitted when a response is received to this request. This event is emitted only +once. The response argument will be an instance of http.ClientResponse. + +

+

Options: + +

+
    +
  • host: A domain name or IP address of the server to issue the request to.
  • +
  • port: Port of remote server.
  • +
  • socketPath: Unix Domain Socket (use one of host:port or socketPath)
  • +
+

Event: 'socket'#

+

function (socket) { } + +

+

Emitted after a socket is assigned to this request. + +

+

Event: 'connect'#

+

function (response, socket, head) { } + +

+

Emitted each time a server responds to a request with a CONNECT method. If this +event isn't being listened for, clients receiving a CONNECT method will have +their connections closed. + +

+

A client server pair that show you how to listen for the connect event. + +

+
var http = require('http');
+var net = require('net');
+var url = require('url');
+
+// Create an HTTP tunneling proxy
+var proxy = http.createServer(function (req, res) {
+  res.writeHead(200, {'Content-Type': 'text/plain'});
+  res.end('okay');
+});
+proxy.on('connect', function(req, cltSocket, head) {
+  // connect to an origin server
+  var srvUrl = url.parse('http://' + req.url);
+  var srvSocket = net.connect(srvUrl.port, srvUrl.hostname, function() {
+    cltSocket.write('HTTP/1.1 200 Connection Established\r\n' +
+                    'Proxy-agent: Node-Proxy\r\n' +
+                    '\r\n');
+    srvSocket.write(head);
+    srvSocket.pipe(cltSocket);
+    cltSocket.pipe(srvSocket);
+  });
+});
+
+// now that proxy is running
+proxy.listen(1337, '127.0.0.1', function() {
+
+  // make a request to a tunneling proxy
+  var options = {
+    port: 1337,
+    host: '127.0.0.1',
+    method: 'CONNECT',
+    path: 'www.google.com:80'
+  };
+
+  var req = http.request(options);
+  req.end();
+
+  req.on('connect', function(res, socket, head) {
+    console.log('got connected!');
+
+    // make a request over an HTTP tunnel
+    socket.write('GET / HTTP/1.1\r\n' +
+                 'Host: www.google.com:80\r\n' +
+                 'Connection: close\r\n' +
+                 '\r\n');
+    socket.on('data', function(chunk) {
+      console.log(chunk.toString());
+    });
+    socket.on('end', function() {
+      proxy.close();
+    });
+  });
+});
+

Event: 'upgrade'#

+

function (response, socket, head) { } + +

+

Emitted each time a server responds to a request with an upgrade. If this +event isn't being listened for, clients receiving an upgrade header will have +their connections closed. + +

+

A client server pair that show you how to listen for the upgrade event. + +

+
var http = require('http');
+
+// Create an HTTP server
+var srv = http.createServer(function (req, res) {
+  res.writeHead(200, {'Content-Type': 'text/plain'});
+  res.end('okay');
+});
+srv.on('upgrade', function(req, socket, head) {
+  socket.write('HTTP/1.1 101 Web Socket Protocol Handshake\r\n' +
+               'Upgrade: WebSocket\r\n' +
+               'Connection: Upgrade\r\n' +
+               '\r\n');
+
+  socket.pipe(socket); // echo back
+});
+
+// now that server is running
+srv.listen(1337, '127.0.0.1', function() {
+
+  // make a request
+  var options = {
+    port: 1337,
+    host: '127.0.0.1',
+    headers: {
+      'Connection': 'Upgrade',
+      'Upgrade': 'websocket'
+    }
+  };
+
+  var req = http.request(options);
+  req.end();
+
+  req.on('upgrade', function(res, socket, upgradeHead) {
+    console.log('got upgraded!');
+    socket.end();
+    process.exit(0);
+  });
+});
+

Event: 'continue'#

+

function () { } + +

+

Emitted when the server sends a '100 Continue' HTTP response, usually because +the request contained 'Expect: 100-continue'. This is an instruction that +the client should send the request body. + +

+

request.write(chunk, [encoding])#

+

Sends a chunk of the body. By calling this method +many times, the user can stream a request body to a +server--in that case it is suggested to use the +['Transfer-Encoding', 'chunked'] header line when +creating the request. + +

+

The chunk argument should be a Buffer or a string. + +

+

The encoding argument is optional and only applies when chunk is a string. +Defaults to 'utf8'. + + +

+

request.end([data], [encoding])#

+

Finishes sending the request. If any parts of the body are +unsent, it will flush them to the stream. If the request is +chunked, this will send the terminating '0\r\n\r\n'. + +

+

If data is specified, it is equivalent to calling +request.write(data, encoding) followed by request.end(). + +

+

request.abort()#

+

Aborts a request. (New since v0.3.8.) + +

+

request.setTimeout(timeout, [callback])#

+

Once a socket is assigned to this request and is connected +socket.setTimeout() will be called. + +

+

request.setNoDelay([noDelay])#

+

Once a socket is assigned to this request and is connected +socket.setNoDelay() will be called. + +

+

request.setSocketKeepAlive([enable], [initialDelay])#

+

Once a socket is assigned to this request and is connected +socket.setKeepAlive() will be called. + +

+

http.ClientResponse#

+

This object is created when making a request with http.request(). It is +passed to the 'response' event of the request object. + +

+

The response implements the Readable Stream interface. This is an +EventEmitter with the following events: + + +

+

Event: 'data'#

+

function (chunk) { } + +

+

Emitted when a piece of the message body is received. + +

+

Note that the data will be lost if there is no listener when a +ClientResponse emits a 'data' event. + + +

+

Event: 'end'#

+

function () { } + +

+

Emitted exactly once for each response. After that, no more 'data' events +will be emitted on the response. + + +

+

Event: 'close'#

+

function () { } + +

+

Indicates that the underlaying connection was terminated before +response.end() was called or able to flush. + +

+

Just like 'end', this event occurs only once per response, and no more +'data' events will fire afterwards. See [http.ServerResponse][]'s 'close' +event for more information. + +

+

Note: 'close' can fire after 'end', but not vice versa. + + +

+

response.statusCode#

+

The 3-digit HTTP response status code. E.G. 404. + +

+

response.httpVersion#

+

The HTTP version of the connected-to server. Probably either +'1.1' or '1.0'. +Also response.httpVersionMajor is the first integer and +response.httpVersionMinor is the second. + +

+

response.headers#

+

The response headers object. + +

+

response.trailers#

+

The response trailers object. Only populated after the 'end' event. + +

+

response.setEncoding([encoding])#

+

Set the encoding for the response body. See stream.setEncoding() for more +information. + +

+

response.pause()#

+

Pauses response from emitting events. Useful to throttle back a download. + +

+

response.resume()#

+

Resumes a paused response. + +

+

HTTPS#

+
Stability: 3 - Stable
+

HTTPS is the HTTP protocol over TLS/SSL. In Node this is implemented as a +separate module. + +

+

Class: https.Server#

+

This class is a subclass of tls.Server and emits events same as +http.Server. See http.Server for more information. + +

+

https.createServer(options, [requestListener])#

+

Returns a new HTTPS web server object. The options is similar to +tls.createServer(). The requestListener is a function which is +automatically added to the 'request' event. + +

+

Example: + +

+
// curl -k https://localhost:8000/
+var https = require('https');
+var fs = require('fs');
+
+var options = {
+  key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'),
+  cert: fs.readFileSync('test/fixtures/keys/agent2-cert.pem')
+};
+
+https.createServer(options, function (req, res) {
+  res.writeHead(200);
+  res.end("hello world\n");
+}).listen(8000);
+

Or + +

+
var https = require('https');
+var fs = require('fs');
+
+var options = {
+  pfx: fs.readFileSync('server.pfx')
+};
+
+https.createServer(options, function (req, res) {
+  res.writeHead(200);
+  res.end("hello world\n");
+}).listen(8000);
+

server.listen(port, [host], [backlog], [callback])#

+

server.listen(path, [callback])#

+

server.listen(handle, [callback])#

+

See http.listen() for details. + +

+

server.close([callback])#

+

See http.close() for details. + +

+

https.request(options, callback)#

+

Makes a request to a secure web server. + +

+

options can be an object or a string. If options is a string, it is +automatically parsed with url.parse(). + +

+

All options from http.request() are valid. + +

+

Example: + +

+
var https = require('https');
+
+var options = {
+  host: 'encrypted.google.com',
+  port: 443,
+  path: '/',
+  method: 'GET'
+};
+
+var req = https.request(options, function(res) {
+  console.log("statusCode: ", res.statusCode);
+  console.log("headers: ", res.headers);
+
+  res.on('data', function(d) {
+    process.stdout.write(d);
+  });
+});
+req.end();
+
+req.on('error', function(e) {
+  console.error(e);
+});
+

The options argument has the following options + +

+
    +
  • host: IP or domain of host to make request to. Defaults to 'localhost'.
  • +
  • port: port of host to request to. Defaults to 443.
  • +
  • path: Path to request. Default '/'.
  • +
  • method: HTTP request method. Default 'GET'.

    +
  • +
  • host: A domain name or IP address of the server to issue the request to. +Defaults to 'localhost'.

    +
  • +
  • hostname: To support url.parse() hostname is preferred over host
  • +
  • port: Port of remote server. Defaults to 443.
  • +
  • method: A string specifying the HTTP request method. Defaults to 'GET'.
  • +
  • path: Request path. Defaults to '/'. Should include query string if any. +E.G. '/index.html?page=12'
  • +
  • headers: An object containing request headers.
  • +
  • auth: Basic authentication i.e. 'user:password' to compute an +Authorization header.
  • +
  • agent: Controls Agent behavior. When an Agent is used request will +default to Connection: keep-alive. Possible values:
      +
    • undefined (default): use globalAgent for this host and port.
    • +
    • Agent object: explicitly use the passed in Agent.
    • +
    • false: opts out of connection pooling with an Agent, defaults request to +Connection: close.
    • +
    +
  • +
+

The following options from tls.connect() can also be specified. However, a +globalAgent silently ignores these. + +

+
    +
  • pfx: Certificate, Private key and CA certificates to use for SSL. Default null.
  • +
  • key: Private key to use for SSL. Default null.
  • +
  • passphrase: A string of passphrase for the private key or pfx. Default null.
  • +
  • cert: Public x509 certificate to use. Default null.
  • +
  • ca: An authority certificate or array of authority certificates to check +the remote host against.
  • +
  • ciphers: A string describing the ciphers to use or exclude. Consult +http://www.openssl.org/docs/apps/ciphers.html#CIPHER_LIST_FORMAT for +details on the format.
  • +
  • rejectUnauthorized: If true, the server certificate is verified against +the list of supplied CAs. An 'error' event is emitted if verification +fails. Verification happens at the connection level, before the HTTP +request is sent. Default false.
  • +
+

In order to specify these options, use a custom Agent. + +

+

Example: + +

+
var options = {
+  host: 'encrypted.google.com',
+  port: 443,
+  path: '/',
+  method: 'GET',
+  key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'),
+  cert: fs.readFileSync('test/fixtures/keys/agent2-cert.pem')
+};
+options.agent = new https.Agent(options);
+
+var req = https.request(options, function(res) {
+  ...
+}
+

Or does not use an Agent. + +

+

Example: + +

+
var options = {
+  host: 'encrypted.google.com',
+  port: 443,
+  path: '/',
+  method: 'GET',
+  key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'),
+  cert: fs.readFileSync('test/fixtures/keys/agent2-cert.pem'),
+  agent: false
+};
+
+var req = https.request(options, function(res) {
+  ...
+}
+

https.get(options, callback)#

+

Like http.get() but for HTTPS. + +

+

options can be an object or a string. If options is a string, it is +automatically parsed with url.parse(). + +

+

Example: + +

+
var https = require('https');
+
+https.get('https://encrypted.google.com/', function(res) {
+  console.log("statusCode: ", res.statusCode);
+  console.log("headers: ", res.headers);
+
+  res.on('data', function(d) {
+    process.stdout.write(d);
+  });
+
+}).on('error', function(e) {
+  console.error(e);
+});
+

Class: https.Agent#

+

An Agent object for HTTPS similar to http.Agent. See [https.request()][] +for more information. + + +

+

https.globalAgent#

+

Global instance of https.Agent for all HTTPS client requests. + +

+

URL#

+
Stability: 3 - Stable
+

This module has utilities for URL resolution and parsing. +Call require('url') to use it. + +

+

Parsed URL objects have some or all of the following fields, depending on +whether or not they exist in the URL string. Any parts that are not in the URL +string will not be in the parsed object. Examples are shown for the URL + +

+

'http://user:pass@host.com:8080/p/a/t/h?query=string#hash' + +

+
    +
  • href: The full URL that was originally parsed. Both the protocol and host are lowercased.

    +

    Example: 'http://user:pass@host.com:8080/p/a/t/h?query=string#hash'

    +
  • +
  • protocol: The request protocol, lowercased.

    +

    Example: 'http:'

    +
  • +
  • host: The full lowercased host portion of the URL, including port +information.

    +

    Example: 'host.com:8080'

    +
  • +
  • auth: The authentication information portion of a URL.

    +

    Example: 'user:pass'

    +
  • +
  • hostname: Just the lowercased hostname portion of the host.

    +

    Example: 'host.com'

    +
  • +
  • port: The port number portion of the host.

    +

    Example: '8080'

    +
  • +
  • pathname: The path section of the URL, that comes after the host and +before the query, including the initial slash if present.

    +

    Example: '/p/a/t/h'

    +
  • +
  • search: The 'query string' portion of the URL, including the leading +question mark.

    +

    Example: '?query=string'

    +
  • +
  • path: Concatenation of pathname and search.

    +

    Example: '/p/a/t/h?query=string'

    +
  • +
  • query: Either the 'params' portion of the query string, or a +querystring-parsed object.

    +

    Example: 'query=string' or {'query':'string'}

    +
  • +
  • hash: The 'fragment' portion of the URL including the pound-sign.

    +

    Example: '#hash'

    +
  • +
+

The following methods are provided by the URL module: + +

+

url.parse(urlStr, [parseQueryString], [slashesDenoteHost])#

+

Take a URL string, and return an object. + +

+

Pass true as the second argument to also parse +the query string using the querystring module. +Defaults to false. + +

+

Pass true as the third argument to treat //foo/bar as +{ host: 'foo', pathname: '/bar' } rather than +{ pathname: '//foo/bar' }. Defaults to false. + +

+

url.format(urlObj)#

+

Take a parsed URL object, and return a formatted URL string. + +

+
    +
  • href will be ignored.
  • +
  • protocolis treated the same with or without the trailing : (colon).
      +
    • The protocols http, https, ftp, gopher, file will be +postfixed with :// (colon-slash-slash).
    • +
    • All other protocols mailto, xmpp, aim, sftp, foo, etc will +be postfixed with : (colon)
    • +
    +
  • +
  • auth will be used if present.
  • +
  • hostname will only be used if host is absent.
  • +
  • port will only be used if host is absent.
  • +
  • host will be used in place of hostname and port
  • +
  • pathname is treated the same with or without the leading / (slash)
  • +
  • search will be used in place of query
  • +
  • query (object; see querystring) will only be used if search is absent.
  • +
  • search is treated the same with or without the leading ? (question mark)
  • +
  • hash is treated the same with or without the leading # (pound sign, anchor)
  • +
+

url.resolve(from, to)#

+

Take a base URL, and a href URL, and resolve them as a browser would for +an anchor tag. + +

+

Query String#

+
Stability: 3 - Stable
+ + +

This module provides utilities for dealing with query strings. +It provides the following methods: + +

+

querystring.stringify(obj, [sep], [eq])#

+

Serialize an object to a query string. +Optionally override the default separator ('&') and assignment ('=') +characters. + +

+

Example: + +

+
querystring.stringify({ foo: 'bar', baz: ['qux', 'quux'], corge: '' })
+// returns
+'foo=bar&baz=qux&baz=quux&corge='
+
+querystring.stringify({foo: 'bar', baz: 'qux'}, ';', ':')
+// returns
+'foo:bar;baz:qux'
+

querystring.parse(str, [sep], [eq], [options])#

+

Deserialize a query string to an object. +Optionally override the default separator ('&') and assignment ('=') +characters. + +

+

Options object may contain maxKeys property (equal to 1000 by default), it'll +be used to limit processed keys. Set it to 0 to remove key count limitation. + +

+

Example: + +

+
querystring.parse('foo=bar&baz=qux&baz=quux&corge')
+// returns
+{ foo: 'bar', baz: ['qux', 'quux'], corge: '' }
+

querystring.escape#

+

The escape function used by querystring.stringify, +provided so that it could be overridden if necessary. + +

+

querystring.unescape#

+

The unescape function used by querystring.parse, +provided so that it could be overridden if necessary. + +

+

punycode#

+
Stability: 2 - Unstable
+

Punycode.js is bundled with Node.js v0.6.2+. Use +require('punycode') to access it. (To use it with other Node.js versions, +use npm to install the punycode module first.) + +

+

punycode.decode(string)#

+

Converts a Punycode string of ASCII code points to a string of Unicode code +points. + +

+
// decode domain name parts
+punycode.decode('maana-pta'); // 'mañana'
+punycode.decode('--dqo34k'); // '☃-⌘'
+

punycode.encode(string)#

+

Converts a string of Unicode code points to a Punycode string of ASCII code +points. + +

+
// encode domain name parts
+punycode.encode('mañana'); // 'maana-pta'
+punycode.encode('☃-⌘'); // '--dqo34k'
+

punycode.toUnicode(domain)#

+

Converts a Punycode string representing a domain name to Unicode. Only the +Punycoded parts of the domain name will be converted, i.e. it doesn't matter if +you call it on a string that has already been converted to Unicode. + +

+
// decode domain names
+punycode.toUnicode('xn--maana-pta.com'); // 'mañana.com'
+punycode.toUnicode('xn----dqo34k.com'); // '☃-⌘.com'
+

punycode.toASCII(domain)#

+

Converts a Unicode string representing a domain name to Punycode. Only the +non-ASCII parts of the domain name will be converted, i.e. it doesn't matter if +you call it with a domain that's already in ASCII. + +

+
// encode domain names
+punycode.toASCII('mañana.com'); // 'xn--maana-pta.com'
+punycode.toASCII('☃-⌘.com'); // 'xn----dqo34k.com'
+

punycode.ucs2#

+

punycode.ucs2.decode(string)#

+

Creates an array containing the decimal code points of each Unicode character +in the string. While JavaScript uses UCS-2 +internally, this function +will convert a pair of surrogate halves (each of which UCS-2 exposes as +separate characters) into a single code point, matching UTF-16. + +

+
punycode.ucs2.decode('abc'); // [97, 98, 99]
+// surrogate pair for U+1D306 tetragram for centre:
+punycode.ucs2.decode('\uD834\uDF06'); // [0x1D306]
+

punycode.ucs2.encode(codePoints)#

+

Creates a string based on an array of decimal code points. + +

+
punycode.ucs2.encode([97, 98, 99]); // 'abc'
+punycode.ucs2.encode([0x1D306]); // '\uD834\uDF06'
+

punycode.version#

+

A string representing the current Punycode.js version number. + +

+

Readline#

+
Stability: 2 - Unstable
+

To use this module, do require('readline'). Readline allows reading of a +stream (such as process.stdin) on a line-by-line basis. + +

+

Note that once you've invoked this module, your node program will not +terminate until you've closed the interface. Here's how to allow your +program to gracefully exit: + +

+
var readline = require('readline');
+
+var rl = readline.createInterface({
+  input: process.stdin,
+  output: process.stdout
+});
+
+rl.question("What do you think of node.js? ", function(answer) {
+  // TODO: Log the answer in a database
+  console.log("Thank you for your valuable feedback:", answer);
+
+  rl.close();
+});
+

readline.createInterface(options)#

+

Creates a readline Interface instance. Accepts an "options" Object that takes +the following values: + +

+
    +
  • input - the readable stream to listen to (Required).

    +
  • +
  • output - the writable stream to write readline data to (Required).

    +
  • +
  • completer - an optional function that is used for Tab autocompletion. See +below for an example of using this.

    +
  • +
  • terminal - pass true if the input and output streams should be +treated like a TTY, and have ANSI/VT100 escape codes written to it. +Defaults to checking isTTY on the output stream upon instantiation.

    +
  • +
+

The completer function is given a the current line entered by the user, and +is supposed to return an Array with 2 entries: + +

+
    +
  1. An Array with matching entries for the completion.

    +
  2. +
  3. The substring that was used for the matching.

    +
  4. +
+

Which ends up looking something like: +[[substr1, substr2, ...], originalsubstring]. + +

+

Example: + +

+
function completer(line) {
+  var completions = '.help .error .exit .quit .q'.split(' ')
+  var hits = completions.filter(function(c) { return c.indexOf(line) == 0 })
+  // show all completions if none found
+  return [hits.length ? hits : completions, line]
+}
+

Also completer can be run in async mode if it accepts two arguments: + +

+
function completer(linePartial, callback) {
+  callback(null, [['123'], linePartial]);
+}
+

createInterface is commonly used with process.stdin and +process.stdout in order to accept user input: + +

+
var readline = require('readline');
+var rl = readline.createInterface({
+  input: process.stdin,
+  output: process.stdout
+});
+

Once you have a readline instance, you most commonly listen for the +"line" event. + +

+

If terminal is true for this instance then the output stream will get +the best compatibility if it defines an output.columns property, and fires +a "resize" event on the output if/when the columns ever change +(process.stdout does this automatically when it is a TTY). + +

+

Class: Interface#

+

The class that represents a readline interface with an input and output +stream. + +

+

rl.setPrompt(prompt, length)#

+

Sets the prompt, for example when you run node on the command line, you see +> , which is node's prompt. + +

+

rl.prompt([preserveCursor])#

+

Readies readline for input from the user, putting the current setPrompt +options on a new line, giving the user a new spot to write. Set preserveCursor +to true to prevent the cursor placement being reset to 0. + +

+

This will also resume the input stream used with createInterface if it has +been paused. + +

+

rl.question(query, callback)#

+

Prepends the prompt with query and invokes callback with the user's +response. Displays the query to the user, and then invokes callback +with the user's response after it has been typed. + +

+

This will also resume the input stream used with createInterface if +it has been paused. + +

+

Example usage: + +

+
interface.question('What is your favorite food?', function(answer) {
+  console.log('Oh, so your favorite food is ' + answer);
+});
+

rl.pause()#

+

Pauses the readline input stream, allowing it to be resumed later if needed. + +

+

rl.resume()#

+

Resumes the readline input stream. + +

+

rl.close()#

+

Closes the Interface instance, relinquishing control on the input and +output streams. The "close" event will also be emitted. + +

+

rl.write(data, [key])#

+

Writes data to output stream. key is an object literal to represent a key +sequence; available if the terminal is a TTY. + +

+

This will also resume the input stream if it has been paused. + +

+

Example: + +

+
rl.write('Delete me!');
+// Simulate ctrl+u to delete the line written previously
+rl.write(null, {ctrl: true, name: 'u'});
+

Events#

+

Event: 'line'#

+

function (line) {} + +

+

Emitted whenever the input stream receives a \n, usually received when the +user hits enter, or return. This is a good hook to listen for user input. + +

+

Example of listening for line: + +

+
rl.on('line', function (cmd) {
+  console.log('You just typed: '+cmd);
+});
+

Event: 'pause'#

+

function () {} + +

+

Emitted whenever the input stream is paused. + +

+

Also emitted whenever the input stream is not paused and receives the +SIGCONT event. (See events SIGTSTP and SIGCONT) + +

+

Example of listening for pause: + +

+
rl.on('pause', function() {
+  console.log('Readline paused.');
+});
+

Event: 'resume'#

+

function () {} + +

+

Emitted whenever the input stream is resumed. + +

+

Example of listening for resume: + +

+
rl.on('resume', function() {
+  console.log('Readline resumed.');
+});
+

Event: 'close'#

+

function () {} + +

+

Emitted when close() is called. + +

+

Also emitted when the input stream receives its "end" event. The Interface +instance should be considered "finished" once this is emitted. For example, when +the input stream receives ^D, respectively known as EOT. + +

+

This event is also called if there is no SIGINT event listener present when +the input stream receives a ^C, respectively known as SIGINT. + +

+

Event: 'SIGINT'#

+

function () {} + +

+

Emitted whenever the input stream receives a ^C, respectively known as +SIGINT. If there is no SIGINT event listener present when the input +stream receives a SIGINT, pause will be triggered. + +

+

Example of listening for SIGINT: + +

+
rl.on('SIGINT', function() {
+  rl.question('Are you sure you want to exit?', function(answer) {
+    if (answer.match(/^y(es)?$/i)) rl.pause();
+  });
+});
+

Event: 'SIGTSTP'#

+

function () {} + +

+

This does not work on Windows. + +

+

Emitted whenever the input stream receives a ^Z, respectively known as +SIGTSTP. If there is no SIGTSTP event listener present when the input +stream receives a SIGTSTP, the program will be sent to the background. + +

+

When the program is resumed with fg, the pause and SIGCONT events will be +emitted. You can use either to resume the stream. + +

+

The pause and SIGCONT events will not be triggered if the stream was paused +before the program was sent to the background. + +

+

Example of listening for SIGTSTP: + +

+
rl.on('SIGTSTP', function() {
+  // This will override SIGTSTP and prevent the program from going to the
+  // background.
+  console.log('Caught SIGTSTP.');
+});
+

Event: 'SIGCONT'#

+

function () {} + +

+

This does not work on Windows. + +

+

Emitted whenever the input stream is sent to the background with ^Z, +respectively known as SIGTSTP, and then continued with fg(1). This event +only emits if the stream was not paused before sending the program to the +background. + +

+

Example of listening for SIGCONT: + +

+
rl.on('SIGCONT', function() {
+  // `prompt` will automatically resume the stream
+  rl.prompt();
+});
+

Example: Tiny CLI#

+

Here's an example of how to use all these together to craft a tiny command +line interface: + +

+
var readline = require('readline'),
+    rl = readline.createInterface(process.stdin, process.stdout);
+
+rl.setPrompt('OHAI> ');
+rl.prompt();
+
+rl.on('line', function(line) {
+  switch(line.trim()) {
+    case 'hello':
+      console.log('world!');
+      break;
+    default:
+      console.log('Say what? I might have heard `' + line.trim() + '`');
+      break;
+  }
+  rl.prompt();
+}).on('close', function() {
+  console.log('Have a great day!');
+  process.exit(0);
+});
+

REPL#

+

A Read-Eval-Print-Loop (REPL) is available both as a standalone program and +easily includable in other programs. The REPL provides a way to interactively +run JavaScript and see the results. It can be used for debugging, testing, or +just trying things out. + +

+

By executing node without any arguments from the command-line you will be +dropped into the REPL. It has simplistic emacs line-editing. + +

+
mjr:~$ node
+Type '.help' for options.
+> a = [ 1, 2, 3];
+[ 1, 2, 3 ]
+> a.forEach(function (v) {
+...   console.log(v);
+...   });
+1
+2
+3
+

For advanced line-editors, start node with the environmental variable +NODE_NO_READLINE=1. This will start the main and debugger REPL in canonical +terminal settings which will allow you to use with rlwrap. + +

+

For example, you could add this to your bashrc file: + +

+
alias node="env NODE_NO_READLINE=1 rlwrap node"
+

repl.start(options)#

+

Returns and starts a REPLServer instance. Accepts an "options" Object that +takes the following values: + +

+
    +
  • prompt - the prompt and stream for all I/O. Defaults to > .

    +
  • +
  • input - the readable stream to listen to. Defaults to process.stdin.

    +
  • +
  • output - the writable stream to write readline data to. Defaults to +process.stdout.

    +
  • +
  • terminal - pass true if the stream should be treated like a TTY, and +have ANSI/VT100 escape codes written to it. Defaults to checking isTTY +on the output stream upon instantiation.

    +
  • +
  • eval - function that will be used to eval each given line. Defaults to +an async wrapper for eval(). See below for an example of a custom eval.

    +
  • +
  • useColors - a boolean which specifies whether or not the writer function +should output colors. If a different writer function is set then this does +nothing. Defaults to the repl's terminal value.

    +
  • +
  • useGlobal - if set to true, then the repl will use the global object, +instead of running scripts in a separate context. Defaults to false.

    +
  • +
  • ignoreUndefined - if set to true, then the repl will not output the +return value of command if it's undefined. Defaults to false.

    +
  • +
  • writer - the function to invoke for each command that gets evaluated which +returns the formatting (including coloring) to display. Defaults to +util.inspect.

    +
  • +
+

You can use your own eval function if it has following signature: + +

+
function eval(cmd, context, filename, callback) {
+  callback(null, result);
+}
+

Multiple REPLs may be started against the same running instance of node. Each +will share the same global object but will have unique I/O. + +

+

Here is an example that starts a REPL on stdin, a Unix socket, and a TCP socket: + +

+
var net = require("net"),
+    repl = require("repl");
+
+connections = 0;
+
+repl.start({
+  prompt: "node via stdin> ",
+  input: process.stdin,
+  output: process.stdout
+});
+
+net.createServer(function (socket) {
+  connections += 1;
+  repl.start({
+    prompt: "node via Unix socket> ",
+    input: socket,
+    output: socket
+  }).on('exit', function() {
+    socket.end();
+  })
+}).listen("/tmp/node-repl-sock");
+
+net.createServer(function (socket) {
+  connections += 1;
+  repl.start({
+    prompt: "node via TCP socket> ",
+    input: socket,
+    output: socket
+  }).on('exit', function() {
+    socket.end();
+  });
+}).listen(5001);
+

Running this program from the command line will start a REPL on stdin. Other +REPL clients may connect through the Unix socket or TCP socket. telnet is useful +for connecting to TCP sockets, and socat can be used to connect to both Unix and +TCP sockets. + +

+

By starting a REPL from a Unix socket-based server instead of stdin, you can +connect to a long-running node process without restarting it. + +

+

For an example of running a "full-featured" (terminal) REPL over +a net.Server and net.Socket instance, see: https://gist.github.com/2209310 + +

+

For an example of running a REPL instance over curl(1), +see: https://gist.github.com/2053342 + +

+

Event: 'exit'#

+

function () {} + +

+

Emitted when the user exits the REPL in any of the defined ways. Namely, typing +.exit at the repl, pressing Ctrl+C twice to signal SIGINT, or pressing Ctrl+D +to signal "end" on the input stream. + +

+

Example of listening for exit: + +

+
r.on('exit', function () {
+  console.log('Got "exit" event from repl!');
+  process.exit();
+});
+

REPL Features#

+ + +

Inside the REPL, Control+D will exit. Multi-line expressions can be input. +Tab completion is supported for both global and local variables. + +

+

The special variable _ (underscore) contains the result of the last expression. + +

+
> [ "a", "b", "c" ]
+[ 'a', 'b', 'c' ]
+> _.length
+3
+> _ += 1
+4
+

The REPL provides access to any variables in the global scope. You can expose +a variable to the REPL explicitly by assigning it to the context object +associated with each REPLServer. For example: + +

+
// repl_test.js
+var repl = require("repl"),
+    msg = "message";
+
+repl.start().context.m = msg;
+

Things in the context object appear as local within the REPL: + +

+
mjr:~$ node repl_test.js
+> m
+'message'
+

There are a few special REPL commands: + +

+
    +
  • .break - While inputting a multi-line expression, sometimes you get lost +or just don't care about completing it. .break will start over.
  • +
  • .clear - Resets the context object to an empty object and clears any +multi-line expression.
  • +
  • .exit - Close the I/O stream, which will cause the REPL to exit.
  • +
  • .help - Show this list of special commands.
  • +
  • .save - Save the current REPL session to a file
    +

    .save ./file/to/save.js

    +
    +
  • +
  • .load - Load a file into the current REPL session.
    +

    .load ./file/to/load.js

    +
    +
  • +
+

The following key combinations in the REPL have these special effects: + +

+
    +
  • <ctrl>C - Similar to the .break keyword. Terminates the current +command. Press twice on a blank line to forcibly exit.
  • +
  • <ctrl>D - Similar to the .exit keyword.
  • +
+

Executing JavaScript#

+
Stability: 2 - Unstable. See Caveats, below.
+ + +

You can access this module with: + +

+
var vm = require('vm');
+

JavaScript code can be compiled and run immediately or compiled, saved, and run later. + +

+

Caveats#

+

The vm module has many known issues and edge cases. If you run into +issues or unexpected behavior, please consult +the open issues on GitHub. +Some of the biggest problems are described below. + +

+

Sandboxes#

+

The sandbox argument to vm.runInNewContext and vm.createContext, +along with the initSandbox argument to vm.createContext, do not +behave as one might normally expect and their behavior varies +between different versions of Node. + +

+

The key issue to be aware of is that V8 provides no way to directly +control the global object used within a context. As a result, while +properties of your sandbox object will be available in the context, +any properties from the prototypes of the sandbox may not be +available. Furthermore, the this expression within the global scope +of the context evaluates to the empty object ({}) instead of to +your sandbox. + +

+

Your sandbox's properties are also not shared directly with the script. +Instead, the properties of the sandbox are copied into the context at +the beginning of execution, and then after execution, the properties +are copied back out in an attempt to propagate any changes. + +

+

Globals#

+

Properties of the global object, like Array and String, have +different values inside of a context. This means that common +expressions like [] instanceof Array or +Object.getPrototypeOf([]) === Array.prototype may not produce +expected results when used inside of scripts evaluated via the vm module. + +

+

Some of these problems have known workarounds listed in the issues for +vm on GitHub. for example, Array.isArray works around +the example problem with Array. + +

+

vm.runInThisContext(code, [filename])#

+

vm.runInThisContext() compiles code, runs it and returns the result. Running +code does not have access to local scope. filename is optional, it's used only +in stack traces. + +

+

Example of using vm.runInThisContext and eval to run the same code: + +

+
var localVar = 123,
+    usingscript, evaled,
+    vm = require('vm');
+
+usingscript = vm.runInThisContext('localVar = 1;',
+  'myfile.vm');
+console.log('localVar: ' + localVar + ', usingscript: ' +
+  usingscript);
+evaled = eval('localVar = 1;');
+console.log('localVar: ' + localVar + ', evaled: ' +
+  evaled);
+
+// localVar: 123, usingscript: 1
+// localVar: 1, evaled: 1
+

vm.runInThisContext does not have access to the local scope, so localVar is unchanged. +eval does have access to the local scope, so localVar is changed. + +

+

In case of syntax error in code, vm.runInThisContext emits the syntax error to stderr +and throws an exception. + + +

+

vm.runInNewContext(code, [sandbox], [filename])#

+

vm.runInNewContext compiles code, then runs it in sandbox and returns the +result. Running code does not have access to local scope. The object sandbox +will be used as the global object for code. +sandbox and filename are optional, filename is only used in stack traces. + +

+

Example: compile and execute code that increments a global variable and sets a new one. +These globals are contained in the sandbox. + +

+
var util = require('util'),
+    vm = require('vm'),
+    sandbox = {
+      animal: 'cat',
+      count: 2
+    };
+
+vm.runInNewContext('count += 1; name = "kitty"', sandbox, 'myfile.vm');
+console.log(util.inspect(sandbox));
+
+// { animal: 'cat', count: 3, name: 'kitty' }
+

Note that running untrusted code is a tricky business requiring great care. To prevent accidental +global variable leakage, vm.runInNewContext is quite useful, but safely running untrusted code +requires a separate process. + +

+

In case of syntax error in code, vm.runInNewContext emits the syntax error to stderr +and throws an exception. + +

+

vm.runInContext(code, context, [filename])#

+

vm.runInContext compiles code, then runs it in context and returns the +result. A (V8) context comprises a global object, together with a set of +built-in objects and functions. Running code does not have access to local scope +and the global object held within context will be used as the global object +for code. +filename is optional, it's used only in stack traces. + +

+

Example: compile and execute code in a existing context. + +

+
var util = require('util'),
+    vm = require('vm'),
+    initSandbox = {
+      animal: 'cat',
+      count: 2
+    },
+    context = vm.createContext(initSandbox);
+
+vm.runInContext('count += 1; name = "CATT"', context, 'myfile.vm');
+console.log(util.inspect(context));
+
+// { animal: 'cat', count: 3, name: 'CATT' }
+

Note that createContext will perform a shallow clone of the supplied sandbox object in order to +initialize the global object of the freshly constructed context. + +

+

Note that running untrusted code is a tricky business requiring great care. To prevent accidental +global variable leakage, vm.runInContext is quite useful, but safely running untrusted code +requires a separate process. + +

+

In case of syntax error in code, vm.runInContext emits the syntax error to stderr +and throws an exception. + +

+

vm.createContext([initSandbox])#

+

vm.createContext creates a new context which is suitable for use as the 2nd argument of a subsequent +call to vm.runInContext. A (V8) context comprises a global object together with a set of +build-in objects and functions. The optional argument initSandbox will be shallow-copied +to seed the initial contents of the global object used by the context. + +

+

vm.createScript(code, [filename])#

+

createScript compiles code but does not run it. Instead, it returns a +vm.Script object representing this compiled code. This script can be run +later many times using methods below. The returned script is not bound to any +global object. It is bound before each run, just for that run. filename is +optional, it's only used in stack traces. + +

+

In case of syntax error in code, createScript prints the syntax error to stderr +and throws an exception. + + +

+

Class: Script#

+

A class for running scripts. Returned by vm.createScript. + +

+

script.runInThisContext()#

+

Similar to vm.runInThisContext but a method of a precompiled Script object. +script.runInThisContext runs the code of script and returns the result. +Running code does not have access to local scope, but does have access to the global object +(v8: in actual context). + +

+

Example of using script.runInThisContext to compile code once and run it multiple times: + +

+
var vm = require('vm');
+
+globalVar = 0;
+
+var script = vm.createScript('globalVar += 1', 'myfile.vm');
+
+for (var i = 0; i < 1000 ; i += 1) {
+  script.runInThisContext();
+}
+
+console.log(globalVar);
+
+// 1000
+

script.runInNewContext([sandbox])#

+

Similar to vm.runInNewContext a method of a precompiled Script object. +script.runInNewContext runs the code of script with sandbox as the global object and returns the result. +Running code does not have access to local scope. sandbox is optional. + +

+

Example: compile code that increments a global variable and sets one, then execute this code multiple times. +These globals are contained in the sandbox. + +

+
var util = require('util'),
+    vm = require('vm'),
+    sandbox = {
+      animal: 'cat',
+      count: 2
+    };
+
+var script = vm.createScript('count += 1; name = "kitty"', 'myfile.vm');
+
+for (var i = 0; i < 10 ; i += 1) {
+  script.runInNewContext(sandbox);
+}
+
+console.log(util.inspect(sandbox));
+
+// { animal: 'cat', count: 12, name: 'kitty' }
+

Note that running untrusted code is a tricky business requiring great care. To prevent accidental +global variable leakage, script.runInNewContext is quite useful, but safely running untrusted code +requires a separate process. + +

+

Child Process#

+
Stability: 3 - Stable
+

Node provides a tri-directional popen(3) facility through the +child_process module. + +

+

It is possible to stream data through a child's stdin, stdout, and +stderr in a fully non-blocking way. + +

+

To create a child process use require('child_process').spawn() or +require('child_process').fork(). The semantics of each are slightly +different, and explained below. + +

+

Class: ChildProcess#

+

ChildProcess is an EventEmitter. + +

+

Child processes always have three streams associated with them. child.stdin, +child.stdout, and child.stderr. These may be shared with the stdio +streams of the parent process, or they may be separate stream objects +which can be piped to and from. + +

+

The ChildProcess class is not intended to be used directly. Use the +spawn() or fork() methods to create a Child Process instance. + +

+

Event: 'exit'#

+
    +
  • code Number the exit code, if it exited normally.
  • +
  • signal String the signal passed to kill the child process, if it +was killed by the parent.
  • +
+

This event is emitted after the child process ends. If the process terminated +normally, code is the final exit code of the process, otherwise null. If +the process terminated due to receipt of a signal, signal is the string name +of the signal, otherwise null. + +

+

Note that the child process stdio streams might still be open. + +

+

See waitpid(2). + +

+

Event: 'close'#

+

This event is emitted when the stdio streams of a child process have all +terminated. This is distinct from 'exit', since multiple processes +might share the same stdio streams. + +

+

Event: 'disconnect'#

+

This event is emitted after using the .disconnect() method in the parent or +in the child. After disconnecting it is no longer possible to send messages. +An alternative way to check if you can send messages is to see if the +child.connected property is true. + +

+

Event: 'message'#

+
    +
  • message Object a parsed JSON object or primitive value
  • +
  • sendHandle Handle object a Socket or Server object
  • +
+

Messages send by .send(message, [sendHandle]) are obtained using the +message event. + +

+

child.stdin#

+
    +
  • Stream object
  • +
+

A Writable Stream that represents the child process's stdin. +Closing this stream via end() often causes the child process to terminate. + +

+

If the child stdio streams are shared with the parent, then this will +not be set. + +

+

child.stdout#

+
    +
  • Stream object
  • +
+

A Readable Stream that represents the child process's stdout. + +

+

If the child stdio streams are shared with the parent, then this will +not be set. + +

+

child.stderr#

+
    +
  • Stream object
  • +
+

A Readable Stream that represents the child process's stderr. + +

+

If the child stdio streams are shared with the parent, then this will +not be set. + +

+

child.pid#

+
    +
  • Integer
  • +
+

The PID of the child process. + +

+

Example: + +

+
var spawn = require('child_process').spawn,
+    grep  = spawn('grep', ['ssh']);
+
+console.log('Spawned child pid: ' + grep.pid);
+grep.stdin.end();
+

child.kill([signal])#

+
    +
  • signal String
  • +
+

Send a signal to the child process. If no argument is given, the process will +be sent 'SIGTERM'. See signal(7) for a list of available signals. + +

+
var spawn = require('child_process').spawn,
+    grep  = spawn('grep', ['ssh']);
+
+grep.on('exit', function (code, signal) {
+  console.log('child process terminated due to receipt of signal '+signal);
+});
+
+// send SIGHUP to process
+grep.kill('SIGHUP');
+

Note that while the function is called kill, the signal delivered to the child +process may not actually kill it. kill really just sends a signal to a process. + +

+

See kill(2) + +

+

child.send(message, [sendHandle])#

+
    +
  • message Object
  • +
  • sendHandle Handle object
  • +
+

When using child_process.fork() you can write to the child using +child.send(message, [sendHandle]) and messages are received by +a 'message' event on the child. + +

+

For example: + +

+
var cp = require('child_process');
+
+var n = cp.fork(__dirname + '/sub.js');
+
+n.on('message', function(m) {
+  console.log('PARENT got message:', m);
+});
+
+n.send({ hello: 'world' });
+

And then the child script, 'sub.js' might look like this: + +

+
process.on('message', function(m) {
+  console.log('CHILD got message:', m);
+});
+
+process.send({ foo: 'bar' });
+

In the child the process object will have a send() method, and process +will emit objects each time it receives a message on its channel. + +

+

There is a special case when sending a {cmd: 'NODE_foo'} message. All messages +containing a NODE_ prefix in its cmd property will not be emitted in +the message event, since they are internal messages used by node core. +Messages containing the prefix are emitted in the internalMessage event, you +should by all means avoid using this feature, it is subject to change without notice. + +

+

The sendHandle option to child.send() is for sending a TCP server or +socket object to another process. The child will receive the object as its +second argument to the message event. + +

+

send server object + +

+

Here is an example of sending a server: + +

+
var child = require('child_process').fork('child.js');
+
+// Open up the server object and send the handle.
+var server = require('net').createServer();
+server.on('connection', function (socket) {
+  socket.end('handled by parent');
+});
+server.listen(1337, function() {
+  child.send('server', server);
+});
+

And the child would the receive the server object as: + +

+
process.on('message', function(m, server) {
+  if (m === 'server') {
+    server.on('connection', function (socket) {
+      socket.end('handled by child');
+    });
+  }
+});
+

Note that the server is now shared between the parent and child, this means +that some connections will be handled by the parent and some by the child. + +

+

send socket object + +

+

Here is an example of sending a socket. It will spawn two children and handle +connections with the remote address 74.125.127.100 as VIP by sending the +socket to a "special" child process. Other sockets will go to a "normal" process. + +

+
var normal = require('child_process').fork('child.js', ['normal']);
+var special = require('child_process').fork('child.js', ['special']);
+
+// Open up the server and send sockets to child
+var server = require('net').createServer();
+server.on('connection', function (socket) {
+
+  // if this is a VIP
+  if (socket.remoteAddress === '74.125.127.100') {
+    special.send('socket', socket);
+    return;
+  }
+  // just the usual dudes
+  normal.send('socket', socket);
+});
+server.listen(1337);
+

The child.js could look like this: + +

+
process.on('message', function(m, socket) {
+  if (m === 'socket') {
+    socket.end('You were handled as a ' + process.argv[2] + ' person');
+  }
+});
+

Note that once a single socket has been sent to a child the parent can no +longer keep track of when the socket is destroyed. To indicate this condition +the .connections property becomes null. +It is also recommended not to use .maxConnections in this condition. + +

+

child.disconnect()#

+

To close the IPC connection between parent and child use the +child.disconnect() method. This allows the child to exit gracefully since +there is no IPC channel keeping it alive. When calling this method the +disconnect event will be emitted in both parent and child, and the +connected flag will be set to false. Please note that you can also call +process.disconnect() in the child process. + +

+

child_process.spawn(command, [args], [options])#

+
    +
  • command String The command to run
  • +
  • args Array List of string arguments
  • +
  • options Object
      +
    • cwd String Current working directory of the child process
    • +
    • stdio Array|String Child's stdio configuration. (See below)
    • +
    • customFds Array Deprecated File descriptors for the child to use +for stdio. (See below)
    • +
    • env Object Environment key-value pairs
    • +
    • detached Boolean The child will be a process group leader. (See below)
    • +
    • uid Number Sets the user identity of the process. (See setuid(2).)
    • +
    • gid Number Sets the group identity of the process. (See setgid(2).)
    • +
    +
  • +
  • return: ChildProcess object
  • +
+

Launches a new process with the given command, with command line arguments in args. +If omitted, args defaults to an empty Array. + +

+

The third argument is used to specify additional options, which defaults to: + +

+
{ cwd: undefined,
+  env: process.env
+}
+

cwd allows you to specify the working directory from which the process is spawned. +Use env to specify environment variables that will be visible to the new process. + +

+

Example of running ls -lh /usr, capturing stdout, stderr, and the exit code: + +

+
var spawn = require('child_process').spawn,
+    ls    = spawn('ls', ['-lh', '/usr']);
+
+ls.stdout.on('data', function (data) {
+  console.log('stdout: ' + data);
+});
+
+ls.stderr.on('data', function (data) {
+  console.log('stderr: ' + data);
+});
+
+ls.on('exit', function (code) {
+  console.log('child process exited with code ' + code);
+});
+

Example: A very elaborate way to run 'ps ax | grep ssh' + +

+
var spawn = require('child_process').spawn,
+    ps    = spawn('ps', ['ax']),
+    grep  = spawn('grep', ['ssh']);
+
+ps.stdout.on('data', function (data) {
+  grep.stdin.write(data);
+});
+
+ps.stderr.on('data', function (data) {
+  console.log('ps stderr: ' + data);
+});
+
+ps.on('exit', function (code) {
+  if (code !== 0) {
+    console.log('ps process exited with code ' + code);
+  }
+  grep.stdin.end();
+});
+
+grep.stdout.on('data', function (data) {
+  console.log('' + data);
+});
+
+grep.stderr.on('data', function (data) {
+  console.log('grep stderr: ' + data);
+});
+
+grep.on('exit', function (code) {
+  if (code !== 0) {
+    console.log('grep process exited with code ' + code);
+  }
+});
+

Example of checking for failed exec: + +

+
var spawn = require('child_process').spawn,
+    child = spawn('bad_command');
+
+child.stderr.setEncoding('utf8');
+child.stderr.on('data', function (data) {
+  if (/^execvp\(\)/.test(data)) {
+    console.log('Failed to start child process.');
+  }
+});
+

Note that if spawn receives an empty options object, it will result in +spawning the process with an empty environment rather than using +process.env. This due to backwards compatibility issues with a deprecated +API. + +

+

The 'stdio' option to child_process.spawn() is an array where each +index corresponds to a fd in the child. The value is one of the following: + +

+
    +
  1. 'pipe' - Create a pipe between the child process and the parent process. +The parent end of the pipe is exposed to the parent as a property on the +child_process object as ChildProcess.stdio[fd]. Pipes created for +fds 0 - 2 are also available as ChildProcess.stdin, ChildProcess.stdout +and ChildProcess.stderr, respectively.
  2. +
  3. 'ipc' - Create an IPC channel for passing messages/file descriptors +between parent and child. A ChildProcess may have at most one IPC stdio +file descriptor. Setting this option enables the ChildProcess.send() method. +If the child writes JSON messages to this file descriptor, then this will +trigger ChildProcess.on('message'). If the child is a Node.js program, then +the presence of an IPC channel will enable process.send() and +process.on('message').
  4. +
  5. 'ignore' - Do not set this file descriptor in the child. Note that Node +will always open fd 0 - 2 for the processes it spawns. When any of these is +ignored node will open /dev/null and attach it to the child's fd.
  6. +
  7. Stream object - Share a readable or writable stream that refers to a tty, +file, socket, or a pipe with the child process. The stream's underlying +file descriptor is duplicated in the child process to the fd that +corresponds to the index in the stdio array.
  8. +
  9. Positive integer - The integer value is interpreted as a file descriptor +that is is currently open in the parent process. It is shared with the child +process, similar to how Stream objects can be shared.
  10. +
  11. null, undefined - Use default value. For stdio fds 0, 1 and 2 (in other +words, stdin, stdout, and stderr) a pipe is created. For fd 3 and up, the +default is 'ignore'.
  12. +
+

As a shorthand, the stdio argument may also be one of the following +strings, rather than an array: + +

+
    +
  • ignore - ['ignore', 'ignore', 'ignore']
  • +
  • pipe - ['pipe', 'pipe', 'pipe']
  • +
  • inherit - [process.stdin, process.stdout, process.stderr] or [0,1,2]
  • +
+

Example: + +

+
var spawn = require('child_process').spawn;
+
+// Child will use parent's stdios
+spawn('prg', [], { stdio: 'inherit' });
+
+// Spawn child sharing only stderr
+spawn('prg', [], { stdio: ['pipe', 'pipe', process.stderr] });
+
+// Open an extra fd=4, to interact with programs present a
+// startd-style interface.
+spawn('prg', [], { stdio: ['pipe', null, null, null, 'pipe'] });
+

If the detached option is set, the child process will be made the leader of a +new process group. This makes it possible for the child to continue running +after the parent exits. + +

+

By default, the parent will wait for the detached child to exit. To prevent +the parent from waiting for a given child, use the child.unref() method, +and the parent's event loop will not include the child in its reference count. + +

+

Example of detaching a long-running process and redirecting its output to a +file: + +

+
 var fs = require('fs'),
+     spawn = require('child_process').spawn,
+     out = fs.openSync('./out.log', 'a'),
+     err = fs.openSync('./out.log', 'a');
+
+ var child = spawn('prg', [], {
+   detached: true,
+   stdio: [ 'ignore', out, err ]
+ });
+
+ child.unref();
+

When using the detached option to start a long-running process, the process +will not stay running in the background unless it is provided with a stdio +configuration that is not connected to the parent. If the parent's stdio is +inherited, the child will remain attached to the controlling terminal. + +

+

There is a deprecated option called customFds which allows one to specify +specific file descriptors for the stdio of the child process. This API was +not portable to all platforms and therefore removed. +With customFds it was possible to hook up the new process' [stdin, stdout, +stderr] to existing streams; -1 meant that a new stream should be created. +Use at your own risk. + +

+

There are several internal options. In particular stdinStream, +stdoutStream, stderrStream. They are for INTERNAL USE ONLY. As with all +undocumented APIs in Node, they should not be used. + +

+

See also: child_process.exec() and child_process.fork() + +

+

child_process.exec(command, [options], callback)#

+
    +
  • command String The command to run, with space-separated arguments
  • +
  • options Object
      +
    • cwd String Current working directory of the child process
    • +
    • stdio Array|String Child's stdio configuration. (See above)
    • +
    • customFds Array Deprecated File descriptors for the child to use +for stdio. (See above)
    • +
    • env Object Environment key-value pairs
    • +
    • encoding String (Default: 'utf8')
    • +
    • timeout Number (Default: 0)
    • +
    • maxBuffer Number (Default: 200*1024)
    • +
    • killSignal String (Default: 'SIGTERM')
    • +
    +
  • +
  • callback Function called with the output when process terminates
      +
    • error Error
    • +
    • stdout Buffer
    • +
    • stderr Buffer
    • +
    +
  • +
  • Return: ChildProcess object
  • +
+

Runs a command in a shell and buffers the output. + +

+
var exec = require('child_process').exec,
+    child;
+
+child = exec('cat *.js bad_file | wc -l',
+  function (error, stdout, stderr) {
+    console.log('stdout: ' + stdout);
+    console.log('stderr: ' + stderr);
+    if (error !== null) {
+      console.log('exec error: ' + error);
+    }
+});
+

The callback gets the arguments (error, stdout, stderr). On success, error +will be null. On error, error will be an instance of Error and err.code +will be the exit code of the child process, and err.signal will be set to the +signal that terminated the process. + +

+

There is a second optional argument to specify several options. The +default options are + +

+
{ encoding: 'utf8',
+  timeout: 0,
+  maxBuffer: 200*1024,
+  killSignal: 'SIGTERM',
+  cwd: null,
+  env: null }
+

If timeout is greater than 0, then it will kill the child process +if it runs longer than timeout milliseconds. The child process is killed with +killSignal (default: 'SIGTERM'). maxBuffer specifies the largest +amount of data allowed on stdout or stderr - if this value is exceeded then +the child process is killed. + + +

+

child_process.execFile(file, args, options, callback)#

+
    +
  • file String The filename of the program to run
  • +
  • args Array List of string arguments
  • +
  • options Object
      +
    • cwd String Current working directory of the child process
    • +
    • stdio Array|String Child's stdio configuration. (See above)
    • +
    • customFds Array Deprecated File descriptors for the child to use +for stdio. (See above)
    • +
    • env Object Environment key-value pairs
    • +
    • encoding String (Default: 'utf8')
    • +
    • timeout Number (Default: 0)
    • +
    • maxBuffer Number (Default: 200*1024)
    • +
    • killSignal String (Default: 'SIGTERM')
    • +
    +
  • +
  • callback Function called with the output when process terminates
      +
    • error Error
    • +
    • stdout Buffer
    • +
    • stderr Buffer
    • +
    +
  • +
  • Return: ChildProcess object
  • +
+

This is similar to child_process.exec() except it does not execute a +subshell but rather the specified file directly. This makes it slightly +leaner than child_process.exec. It has the same options. + + +

+

child_process.fork(modulePath, [args], [options])#

+
    +
  • modulePath String The module to run in the child
  • +
  • args Array List of string arguments
  • +
  • options Object
      +
    • cwd String Current working directory of the child process
    • +
    • env Object Environment key-value pairs
    • +
    • encoding String (Default: 'utf8')
    • +
    +
  • +
  • Return: ChildProcess object
  • +
+

This is a special case of the spawn() functionality for spawning Node +processes. In addition to having all the methods in a normal ChildProcess +instance, the returned object has a communication channel built-in. See +child.send(message, [sendHandle]) for details. + +

+

By default the spawned Node process will have the stdout, stderr associated +with the parent's. To change this behavior set the silent property in the +options object to true. + +

+

The child process does not automatically exit once it's done, you need to call +process.exit() explicitly. This limitation may be lifted in the future. + +

+

These child Nodes are still whole new instances of V8. Assume at least 30ms +startup and 10mb memory for each new Node. That is, you cannot create many +thousands of them. + +

+

Assert#

+
Stability: 5 - Locked
+

This module is used for writing unit tests for your applications, you can +access it with require('assert'). + +

+

assert.fail(actual, expected, message, operator)#

+

Throws an exception that displays the values for actual and expected separated by the provided operator. + +

+

assert(value, message), assert.ok(value, [message])#

+

Tests if value is truthy, it is equivalent to assert.equal(true, !!value, message); + +

+

assert.equal(actual, expected, [message])#

+

Tests shallow, coercive equality with the equal comparison operator ( == ). + +

+

assert.notEqual(actual, expected, [message])#

+

Tests shallow, coercive non-equality with the not equal comparison operator ( != ). + +

+

assert.deepEqual(actual, expected, [message])#

+

Tests for deep equality. + +

+

assert.notDeepEqual(actual, expected, [message])#

+

Tests for any deep inequality. + +

+

assert.strictEqual(actual, expected, [message])#

+

Tests strict equality, as determined by the strict equality operator ( === ) + +

+

assert.notStrictEqual(actual, expected, [message])#

+

Tests strict non-equality, as determined by the strict not equal operator ( !== ) + +

+

assert.throws(block, [error], [message])#

+

Expects block to throw an error. error can be constructor, regexp or +validation function. + +

+

Validate instanceof using constructor: + +

+
assert.throws(
+  function() {
+    throw new Error("Wrong value");
+  },
+  Error
+);
+

Validate error message using RegExp: + +

+
assert.throws(
+  function() {
+    throw new Error("Wrong value");
+  },
+  /value/
+);
+

Custom error validation: + +

+
assert.throws(
+  function() {
+    throw new Error("Wrong value");
+  },
+  function(err) {
+    if ( (err instanceof Error) && /value/.test(err) ) {
+      return true;
+    }
+  },
+  "unexpected error"
+);
+

assert.doesNotThrow(block, [error], [message])#

+

Expects block not to throw an error, see assert.throws for details. + +

+

assert.ifError(value)#

+

Tests if value is not a false value, throws if it is a true value. Useful when +testing the first argument, error in callbacks. + +

+

TTY#

+
Stability: 2 - Unstable
+

The tty module houses the tty.ReadStream and tty.WriteStream classes. In +most cases, you will not need to use this module directly. + +

+

When node detects that it is being run inside a TTY context, then process.stdin +will be a tty.ReadStream instance and process.stdout will be +a tty.WriteStream instance. The preferred way to check if node is being run in +a TTY context is to check process.stdout.isTTY: + +

+
$ node -p -e "Boolean(process.stdout.isTTY)"
+true
+$ node -p -e "Boolean(process.stdout.isTTY)" | cat
+false
+

tty.isatty(fd)#

+

Returns true or false depending on if the fd is associated with a +terminal. + + +

+

tty.setRawMode(mode)#

+

Deprecated. Use tty.ReadStream#setRawMode() +(i.e. process.stdin.setRawMode()) instead. + + +

+

Class: ReadStream#

+

A net.Socket subclass that represents the readable portion of a tty. In normal +circumstances, process.stdin will be the only tty.ReadStream instance in any +node program (only when isatty(0) is true). + +

+

rs.isRaw#

+

A Boolean that is initialized to false. It represents the current "raw" state +of the tty.ReadStream instance. + +

+

rs.setRawMode(mode)#

+

mode should be true or false. This sets the properties of the +tty.ReadStream to act either as a raw device or default. isRaw will be set +to the resulting mode. + + +

+

Class WriteStream#

+

A net.Socket subclass that represents the writable portion of a tty. In normal +circumstances, process.stdout will be the only tty.WriteStream instance +ever created (and only when isatty(1) is true). + +

+

ws.columns#

+

A Number that gives the number of columns the TTY currently has. This property +gets updated on "resize" events. + +

+

ws.rows#

+

A Number that gives the number of rows the TTY currently has. This property +gets updated on "resize" events. + +

+

Event: 'resize'#

+

function () {} + +

+

Emitted by refreshSize() when either of the columns or rows properties +has changed. + +

+
process.stdout.on('resize', function() {
+  console.log('screen size has changed!');
+  console.log(process.stdout.columns + 'x' + process.stdout.rows);
+});
+

Zlib#

+
Stability: 3 - Stable
+

You can access this module with: + +

+
var zlib = require('zlib');
+

This provides bindings to Gzip/Gunzip, Deflate/Inflate, and +DeflateRaw/InflateRaw classes. Each class takes the same options, and +is a readable/writable Stream. + +

+

Examples#

+

Compressing or decompressing a file can be done by piping an +fs.ReadStream into a zlib stream, then into an fs.WriteStream. + +

+
var gzip = zlib.createGzip();
+var fs = require('fs');
+var inp = fs.createReadStream('input.txt');
+var out = fs.createWriteStream('input.txt.gz');
+
+inp.pipe(gzip).pipe(out);
+

Compressing or decompressing data in one step can be done by using +the convenience methods. + +

+
var input = '.................................';
+zlib.deflate(input, function(err, buffer) {
+  if (!err) {
+    console.log(buffer.toString('base64'));
+  }
+});
+
+var buffer = new Buffer('eJzT0yMAAGTvBe8=', 'base64');
+zlib.unzip(buffer, function(err, buffer) {
+  if (!err) {
+    console.log(buffer.toString());
+  }
+});
+

To use this module in an HTTP client or server, use the +accept-encoding +on requests, and the +content-encoding +header on responses. + +

+

Note: these examples are drastically simplified to show +the basic concept. Zlib encoding can be expensive, and the results +ought to be cached. See Memory Usage Tuning +below for more information on the speed/memory/compression +tradeoffs involved in zlib usage. + +

+
// client request example
+var zlib = require('zlib');
+var http = require('http');
+var fs = require('fs');
+var request = http.get({ host: 'izs.me',
+                         path: '/',
+                         port: 80,
+                         headers: { 'accept-encoding': 'gzip,deflate' } });
+request.on('response', function(response) {
+  var output = fs.createWriteStream('izs.me_index.html');
+
+  switch (response.headers['content-encoding']) {
+    // or, just use zlib.createUnzip() to handle both cases
+    case 'gzip':
+      response.pipe(zlib.createGunzip()).pipe(output);
+      break;
+    case 'deflate':
+      response.pipe(zlib.createInflate()).pipe(output);
+      break;
+    default:
+      response.pipe(output);
+      break;
+  }
+});
+
+// server example
+// Running a gzip operation on every request is quite expensive.
+// It would be much more efficient to cache the compressed buffer.
+var zlib = require('zlib');
+var http = require('http');
+var fs = require('fs');
+http.createServer(function(request, response) {
+  var raw = fs.createReadStream('index.html');
+  var acceptEncoding = request.headers['accept-encoding'];
+  if (!acceptEncoding) {
+    acceptEncoding = '';
+  }
+
+  // Note: this is not a conformant accept-encoding parser.
+  // See http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.3
+  if (acceptEncoding.match(/\bdeflate\b/)) {
+    response.writeHead(200, { 'content-encoding': 'deflate' });
+    raw.pipe(zlib.createDeflate()).pipe(response);
+  } else if (acceptEncoding.match(/\bgzip\b/)) {
+    response.writeHead(200, { 'content-encoding': 'gzip' });
+    raw.pipe(zlib.createGzip()).pipe(response);
+  } else {
+    response.writeHead(200, {});
+    raw.pipe(response);
+  }
+}).listen(1337);
+

zlib.createGzip([options])#

+

Returns a new Gzip object with an +options. + +

+

zlib.createGunzip([options])#

+

Returns a new Gunzip object with an +options. + +

+

zlib.createDeflate([options])#

+

Returns a new Deflate object with an +options. + +

+

zlib.createInflate([options])#

+

Returns a new Inflate object with an +options. + +

+

zlib.createDeflateRaw([options])#

+

Returns a new DeflateRaw object with an +options. + +

+

zlib.createInflateRaw([options])#

+

Returns a new InflateRaw object with an +options. + +

+

zlib.createUnzip([options])#

+

Returns a new Unzip object with an +options. + + +

+

Class: zlib.Gzip#

+

Compress data using gzip. + +

+

Class: zlib.Gunzip#

+

Decompress a gzip stream. + +

+

Class: zlib.Deflate#

+

Compress data using deflate. + +

+

Class: zlib.Inflate#

+

Decompress a deflate stream. + +

+

Class: zlib.DeflateRaw#

+

Compress data using deflate, and do not append a zlib header. + +

+

Class: zlib.InflateRaw#

+

Decompress a raw deflate stream. + +

+

Class: zlib.Unzip#

+

Decompress either a Gzip- or Deflate-compressed stream by auto-detecting +the header. + +

+

Convenience Methods#

+ + +

All of these take a string or buffer as the first argument, and call the +supplied callback with callback(error, result). The +compression/decompression engine is created using the default settings +in all convenience methods. To supply different options, use the +zlib classes directly. + +

+

zlib.deflate(buf, callback)#

+

Compress a string with Deflate. + +

+

zlib.deflateRaw(buf, callback)#

+

Compress a string with DeflateRaw. + +

+

zlib.gzip(buf, callback)#

+

Compress a string with Gzip. + +

+

zlib.gunzip(buf, callback)#

+

Decompress a raw Buffer with Gunzip. + +

+

zlib.inflate(buf, callback)#

+

Decompress a raw Buffer with Inflate. + +

+

zlib.inflateRaw(buf, callback)#

+

Decompress a raw Buffer with InflateRaw. + +

+

zlib.unzip(buf, callback)#

+

Decompress a raw Buffer with Unzip. + +

+

Options#

+ + +

Each class takes an options object. All options are optional. (The +convenience methods use the default settings for all options.) + +

+

Note that some options are only +relevant when compressing, and are ignored by the decompression classes. + +

+
    +
  • chunkSize (default: 16*1024)
  • +
  • windowBits
  • +
  • level (compression only)
  • +
  • memLevel (compression only)
  • +
  • strategy (compression only)
  • +
  • dictionary (deflate/inflate only, empty dictionary by default)
  • +
+

See the description of deflateInit2 and inflateInit2 +at http://zlib.net/manual.html#Advanced for more information on these. + +

+

Memory Usage Tuning#

+ + +

From zlib/zconf.h, modified to node's usage: + +

+

The memory requirements for deflate are (in bytes): + +

+
(1 << (windowBits+2)) +  (1 << (memLevel+9))
+

that is: 128K for windowBits=15 + 128K for memLevel = 8 +(default values) plus a few kilobytes for small objects. + +

+

For example, if you want to reduce +the default memory requirements from 256K to 128K, set the options to: + +

+
{ windowBits: 14, memLevel: 7 }
+

Of course this will generally degrade compression (there's no free lunch). + +

+

The memory requirements for inflate are (in bytes) + +

+
1 << windowBits
+

that is, 32K for windowBits=15 (default value) plus a few kilobytes +for small objects. + +

+

This is in addition to a single internal output slab buffer of size +chunkSize, which defaults to 16K. + +

+

The speed of zlib compression is affected most dramatically by the +level setting. A higher level will result in better compression, but +will take longer to complete. A lower level will result in less +compression, but will be much faster. + +

+

In general, greater memory usage options will mean that node has to make +fewer calls to zlib, since it'll be able to process more data in a +single write operation. So, this is another factor that affects the +speed, at the cost of memory usage. + +

+

Constants#

+ + +

All of the constants defined in zlib.h are also defined on +require('zlib'). +In the normal course of operations, you will not need to ever set any of +these. They are documented here so that their presence is not +surprising. This section is taken almost directly from the zlib +documentation. See +

+

http://zlib.net/manual.html#Constants for more details. + +

+

Allowed flush values. + +

+
    +
  • zlib.Z_NO_FLUSH
  • +
  • zlib.Z_PARTIAL_FLUSH
  • +
  • zlib.Z_SYNC_FLUSH
  • +
  • zlib.Z_FULL_FLUSH
  • +
  • zlib.Z_FINISH
  • +
  • zlib.Z_BLOCK
  • +
  • zlib.Z_TREES
  • +
+

Return codes for the compression/decompression functions. Negative +values are errors, positive values are used for special but normal +events. + +

+
    +
  • zlib.Z_OK
  • +
  • zlib.Z_STREAM_END
  • +
  • zlib.Z_NEED_DICT
  • +
  • zlib.Z_ERRNO
  • +
  • zlib.Z_STREAM_ERROR
  • +
  • zlib.Z_DATA_ERROR
  • +
  • zlib.Z_MEM_ERROR
  • +
  • zlib.Z_BUF_ERROR
  • +
  • zlib.Z_VERSION_ERROR
  • +
+

Compression levels. + +

+
    +
  • zlib.Z_NO_COMPRESSION
  • +
  • zlib.Z_BEST_SPEED
  • +
  • zlib.Z_BEST_COMPRESSION
  • +
  • zlib.Z_DEFAULT_COMPRESSION
  • +
+

Compression strategy. + +

+
    +
  • zlib.Z_FILTERED
  • +
  • zlib.Z_HUFFMAN_ONLY
  • +
  • zlib.Z_RLE
  • +
  • zlib.Z_FIXED
  • +
  • zlib.Z_DEFAULT_STRATEGY
  • +
+

Possible values of the data_type field. + +

+
    +
  • zlib.Z_BINARY
  • +
  • zlib.Z_TEXT
  • +
  • zlib.Z_ASCII
  • +
  • zlib.Z_UNKNOWN
  • +
+

The deflate compression method (the only one supported in this version). + +

+
    +
  • zlib.Z_DEFLATED
  • +
+

For initializing zalloc, zfree, opaque. + +

+
    +
  • zlib.Z_NULL
  • +
+

os#

+
Stability: 4 - API Frozen
+

Provides a few basic operating-system related utility functions. + +

+

Use require('os') to access this module. + +

+

os.tmpDir()#

+

Returns the operating system's default directory for temp files. + +

+

os.hostname()#

+

Returns the hostname of the operating system. + +

+

os.type()#

+

Returns the operating system name. + +

+

os.platform()#

+

Returns the operating system platform. + +

+

os.arch()#

+

Returns the operating system CPU architecture. + +

+

os.release()#

+

Returns the operating system release. + +

+

os.uptime()#

+

Returns the system uptime in seconds. + +

+

os.loadavg()#

+

Returns an array containing the 1, 5, and 15 minute load averages. + +

+

os.totalmem()#

+

Returns the total amount of system memory in bytes. + +

+

os.freemem()#

+

Returns the amount of free system memory in bytes. + +

+

os.cpus()#

+

Returns an array of objects containing information about each CPU/core installed: model, speed (in MHz), and times (an object containing the number of CPU ticks spent in: user, nice, sys, idle, and irq). + +

+

Example inspection of os.cpus: + +

+
[ { model: 'Intel(R) Core(TM) i7 CPU         860  @ 2.80GHz',
+    speed: 2926,
+    times:
+     { user: 252020,
+       nice: 0,
+       sys: 30340,
+       idle: 1070356870,
+       irq: 0 } },
+  { model: 'Intel(R) Core(TM) i7 CPU         860  @ 2.80GHz',
+    speed: 2926,
+    times:
+     { user: 306960,
+       nice: 0,
+       sys: 26980,
+       idle: 1071569080,
+       irq: 0 } },
+  { model: 'Intel(R) Core(TM) i7 CPU         860  @ 2.80GHz',
+    speed: 2926,
+    times:
+     { user: 248450,
+       nice: 0,
+       sys: 21750,
+       idle: 1070919370,
+       irq: 0 } },
+  { model: 'Intel(R) Core(TM) i7 CPU         860  @ 2.80GHz',
+    speed: 2926,
+    times:
+     { user: 256880,
+       nice: 0,
+       sys: 19430,
+       idle: 1070905480,
+       irq: 20 } },
+  { model: 'Intel(R) Core(TM) i7 CPU         860  @ 2.80GHz',
+    speed: 2926,
+    times:
+     { user: 511580,
+       nice: 20,
+       sys: 40900,
+       idle: 1070842510,
+       irq: 0 } },
+  { model: 'Intel(R) Core(TM) i7 CPU         860  @ 2.80GHz',
+    speed: 2926,
+    times:
+     { user: 291660,
+       nice: 0,
+       sys: 34360,
+       idle: 1070888000,
+       irq: 10 } },
+  { model: 'Intel(R) Core(TM) i7 CPU         860  @ 2.80GHz',
+    speed: 2926,
+    times:
+     { user: 308260,
+       nice: 0,
+       sys: 55410,
+       idle: 1071129970,
+       irq: 880 } },
+  { model: 'Intel(R) Core(TM) i7 CPU         860  @ 2.80GHz',
+    speed: 2926,
+    times:
+     { user: 266450,
+       nice: 1480,
+       sys: 34920,
+       idle: 1072572010,
+       irq: 30 } } ]
+

os.networkInterfaces()#

+

Get a list of network interfaces: + +

+
{ lo0: 
+   [ { address: '::1', family: 'IPv6', internal: true },
+     { address: 'fe80::1', family: 'IPv6', internal: true },
+     { address: '127.0.0.1', family: 'IPv4', internal: true } ],
+  en1: 
+   [ { address: 'fe80::cabc:c8ff:feef:f996', family: 'IPv6',
+       internal: false },
+     { address: '10.0.1.123', family: 'IPv4', internal: false } ],
+  vmnet1: [ { address: '10.99.99.254', family: 'IPv4', internal: false } ],
+  vmnet8: [ { address: '10.88.88.1', family: 'IPv4', internal: false } ],
+  ppp0: [ { address: '10.2.0.231', family: 'IPv4', internal: false } ] }
+

os.EOL#

+

A constant defining the appropriate End-of-line marker for the operating system. + +

+

Debugger#

+
Stability: 3 - Stable
+ + +

V8 comes with an extensive debugger which is accessible out-of-process via a +simple TCP protocol. +Node has a built-in client for this debugger. To use this, start Node with the +debug argument; a prompt will appear: + +

+
% node debug myscript.js
+< debugger listening on port 5858
+connecting... ok
+break in /home/indutny/Code/git/indutny/myscript.js:1
+  1 x = 5;
+  2 setTimeout(function () {
+  3   debugger;
+debug>
+

Node's debugger client doesn't support the full range of commands, but +simple step and inspection is possible. By putting the statement debugger; +into the source code of your script, you will enable a breakpoint. + +

+

For example, suppose myscript.js looked like this: + +

+
// myscript.js
+x = 5;
+setTimeout(function () {
+  debugger;
+  console.log("world");
+}, 1000);
+console.log("hello");
+

Then once the debugger is run, it will break on line 4. + +

+
% node debug myscript.js
+< debugger listening on port 5858
+connecting... ok
+break in /home/indutny/Code/git/indutny/myscript.js:1
+  1 x = 5;
+  2 setTimeout(function () {
+  3   debugger;
+debug> cont
+< hello
+break in /home/indutny/Code/git/indutny/myscript.js:3
+  1 x = 5;
+  2 setTimeout(function () {
+  3   debugger;
+  4   console.log("world");
+  5 }, 1000);
+debug> next
+break in /home/indutny/Code/git/indutny/myscript.js:4
+  2 setTimeout(function () {
+  3   debugger;
+  4   console.log("world");
+  5 }, 1000);
+  6 console.log("hello");
+debug> repl
+Press Ctrl + C to leave debug repl
+> x
+5
+> 2+2
+4
+debug> next
+< world
+break in /home/indutny/Code/git/indutny/myscript.js:5
+  3   debugger;
+  4   console.log("world");
+  5 }, 1000);
+  6 console.log("hello");
+  7
+debug> quit
+%
+

The repl command allows you to evaluate code remotely. The next command +steps over to the next line. There are a few other commands available and more +to come. Type help to see others. + +

+

Watchers#

+

You can watch expression and variable values while debugging your code. +On every breakpoint each expression from the watchers list will be evaluated +in the current context and displayed just before the breakpoint's source code +listing. + +

+

To start watching an expression, type watch("my_expression"). watchers +prints the active watchers. To remove a watcher, type +unwatch("my_expression"). + +

+

Commands reference#

+

Stepping#

+
    +
  • cont, c - Continue execution
  • +
  • next, n - Step next
  • +
  • step, s - Step in
  • +
  • out, o - Step out
  • +
  • pause - Pause running code (like pause button in Developer TOols)
  • +
+

Breakpoints#

+
    +
  • setBreakpoint(), sb() - Set breakpoint on current line
  • +
  • setBreakpoint(line), sb(line) - Set breakpoint on specific line
  • +
  • setBreakpoint('fn()'), sb(...) - Set breakpoint on a first statement in +functions body
  • +
  • setBreakpoint('script.js', 1), sb(...) - Set breakpoint on first line of +script.js
  • +
  • clearBreakpoint, cb(...) - Clear breakpoint
  • +
+

Info#

+
    +
  • backtrace, bt - Print backtrace of current execution frame
  • +
  • list(5) - List scripts source code with 5 line context (5 lines before and +after)
  • +
  • watch(expr) - Add expression to watch list
  • +
  • unwatch(expr) - Remove expression from watch list
  • +
  • watchers - List all watchers and their values (automatically listed on each +breakpoint)
  • +
  • repl - Open debugger's repl for evaluation in debugging script's context
  • +
+

Execution control#

+
    +
  • run - Run script (automatically runs on debugger's start)
  • +
  • restart - Restart script
  • +
  • kill - Kill script
  • +
+

Various#

+
    +
  • scripts - List all loaded scripts
  • +
  • version - Display v8's version
  • +
+

Advanced Usage#

+

The V8 debugger can be enabled and accessed either by starting Node with +the --debug command-line flag or by signaling an existing Node process +with SIGUSR1. + +

+

Cluster#

+
Stability: 1 - Experimental
+

A single instance of Node runs in a single thread. To take advantage of +multi-core systems the user will sometimes want to launch a cluster of Node +processes to handle the load. + +

+

The cluster module allows you to easily create a network of processes that +all share server ports. + +

+
var cluster = require('cluster');
+var http = require('http');
+var numCPUs = require('os').cpus().length;
+
+if (cluster.isMaster) {
+  // Fork workers.
+  for (var i = 0; i < numCPUs; i++) {
+    cluster.fork();
+  }
+
+  cluster.on('exit', function(worker, code, signal) {
+    console.log('worker ' + worker.process.pid + ' died');
+  });
+} else {
+  // Workers can share any TCP connection
+  // In this case its a HTTP server
+  http.createServer(function(req, res) {
+    res.writeHead(200);
+    res.end("hello world\n");
+  }).listen(8000);
+}
+

Running node will now share port 8000 between the workers: + +

+
% node server.js
+Worker 2438 online
+Worker 2437 online
+

This feature was introduced recently, and may change in future versions. +Please try it out and provide feedback. + +

+

Also note that, on Windows, it is not yet possible to set up a named pipe +server in a worker. + +

+

How It Works#

+ + +

The worker processes are spawned using the child_process.fork method, +so that they can communicate with the parent via IPC and pass server +handles back and forth. + +

+

When you call server.listen(...) in a worker, it serializes the +arguments and passes the request to the master process. If the master +process already has a listening server matching the worker's +requirements, then it passes the handle to the worker. If it does not +already have a listening server matching that requirement, then it will +create one, and pass the handle to the child. + +

+

This causes potentially surprising behavior in three edge cases: + +

+
    +
  1. server.listen({fd: 7}) Because the message is passed to the master, +file descriptor 7 in the parent will be listened on, and the +handle passed to the worker, rather than listening to the worker's +idea of what the number 7 file descriptor references.
  2. +
  3. server.listen(handle) Listening on handles explicitly will cause +the worker to use the supplied handle, rather than talk to the master +process. If the worker already has the handle, then it's presumed +that you know what you are doing.
  4. +
  5. server.listen(0) Normally, this will cause servers to listen on a +random port. However, in a cluster, each worker will receive the +same "random" port each time they do listen(0). In essence, the +port is random the first time, but predictable thereafter. If you +want to listen on a unique port, generate a port number based on the +cluster worker ID.
  6. +
+

When multiple processes are all accept()ing on the same underlying +resource, the operating system load-balances across them very +efficiently. There is no routing logic in Node.js, or in your program, +and no shared state between the workers. Therefore, it is important to +design your program such that it does not rely too heavily on in-memory +data objects for things like sessions and login. + +

+

Because workers are all separate processes, they can be killed or +re-spawned depending on your program's needs, without affecting other +workers. As long as there are some workers still alive, the server will +continue to accept connections. Node does not automatically manage the +number of workers for you, however. It is your responsibility to manage +the worker pool for your application's needs. + +

+

cluster.settings#

+
    +
  • Object
      +
    • exec String file path to worker file. (Default=__filename)
    • +
    • args Array string arguments passed to worker. +(Default=process.argv.slice(2))
    • +
    • silent Boolean whether or not to send output to parent's stdio. +(Default=false)
    • +
    +
  • +
+

All settings set by the .setupMaster is stored in this settings object. +This object is not supposed to be change or set manually, by you. + +

+

cluster.isMaster#

+
    +
  • Boolean
  • +
+

True if the process is a master. This is determined +by the process.env.NODE_UNIQUE_ID. If process.env.NODE_UNIQUE_ID is +undefined, then isMaster is true. + +

+

cluster.isWorker#

+
    +
  • Boolean
  • +
+

This boolean flag is true if the process is a worker forked from a master. +If the process.env.NODE_UNIQUE_ID is set to a value, then +isWorker is true. + +

+

Event: 'fork'#

+
    +
  • worker Worker object
  • +
+

When a new worker is forked the cluster module will emit a 'fork' event. +This can be used to log worker activity, and create you own timeout. + +

+
var timeouts = [];
+function errorMsg() {
+  console.error("Something must be wrong with the connection ...");
+}
+
+cluster.on('fork', function(worker) {
+  timeouts[worker.id] = setTimeout(errorMsg, 2000);
+});
+cluster.on('listening', function(worker, address) {
+  clearTimeout(timeouts[worker.id]);
+});
+cluster.on('exit', function(worker, code, signal) {
+  clearTimeout(timeouts[worker.id]);
+  errorMsg();
+});
+

Event: 'online'#

+
    +
  • worker Worker object
  • +
+

After forking a new worker, the worker should respond with a online message. +When the master receives a online message it will emit such event. +The difference between 'fork' and 'online' is that fork is emitted when the +master tries to fork a worker, and 'online' is emitted when the worker is +being executed. + +

+
cluster.on('online', function(worker) {
+  console.log("Yay, the worker responded after it was forked");
+});
+

Event: 'listening'#

+
    +
  • worker Worker object
  • +
  • address Object
  • +
+

When calling listen() from a worker, a 'listening' event is automatically assigned +to the server instance. When the server is listening a message is send to the master +where the 'listening' event is emitted. + +

+

The event handler is executed with two arguments, the worker contains the worker +object and the address object contains the following connection properties: +address, port and addressType. This is very useful if the worker is listening +on more than one address. + +

+
cluster.on('listening', function(worker, address) {
+  console.log("A worker is now connected to " + address.address + ":" + address.port);
+});
+

Event: 'disconnect'#

+
    +
  • worker Worker object
  • +
+

When a workers IPC channel has disconnected this event is emitted. This will happen +when the worker dies, usually after calling .destroy(). + +

+

When calling .disconnect(), there may be a delay between the +disconnect and exit events. This event can be used to detect if +the process is stuck in a cleanup or if there are long-living +connections. + +

+
cluster.on('disconnect', function(worker) {
+  console.log('The worker #' + worker.id + ' has disconnected');
+});
+

Event: 'exit'#

+
    +
  • worker Worker object
  • +
  • code Number the exit code, if it exited normally.
  • +
  • signal String the name of the signal (eg. 'SIGHUP') that caused +the process to be killed.
  • +
+

When any of the workers die the cluster module will emit the 'exit' event. +This can be used to restart the worker by calling fork() again. + +

+
cluster.on('exit', function(worker, code, signal) {
+  var exitCode = worker.process.exitCode;
+  console.log('worker ' + worker.process.pid + ' died ('+exitCode+'). restarting...');
+  cluster.fork();
+});
+

Event: 'setup'#

+
    +
  • worker Worker object
  • +
+

When the .setupMaster() function has been executed this event emits. +If .setupMaster() was not executed before fork() this function will +call .setupMaster() with no arguments. + +

+

cluster.setupMaster([settings])#

+
    +
  • settings Object
      +
    • exec String file path to worker file. (Default=__filename)
    • +
    • args Array string arguments passed to worker. +(Default=process.argv.slice(2))
    • +
    • silent Boolean whether or not to send output to parent's stdio. +(Default=false)
    • +
    +
  • +
+

setupMaster is used to change the default 'fork' behavior. The new settings +are effective immediately and permanently, they cannot be changed later on. + +

+

Example: + +

+
var cluster = require("cluster");
+cluster.setupMaster({
+  exec : "worker.js",
+  args : ["--use", "https"],
+  silent : true
+});
+cluster.fork();
+

cluster.fork([env])#

+
    +
  • env Object Key/value pairs to add to child process environment.
  • +
  • return Worker object
  • +
+

Spawn a new worker process. This can only be called from the master process. + +

+

cluster.disconnect([callback])#

+
    +
  • callback Function called when all workers are disconnected and handlers are closed
  • +
+

When calling this method, all workers will commit a graceful suicide. When they are +disconnected all internal handlers will be closed, allowing the master process to +die graceful if no other event is waiting. + +

+

The method takes an optional callback argument which will be called when finished. + +

+

cluster.worker#

+
    +
  • Object
  • +
+

A reference to the current worker object. Not available in the master process. + +

+
var cluster = require('cluster');
+
+if (cluster.isMaster) {
+  console.log('I am master');
+  cluster.fork();
+  cluster.fork();
+} else if (cluster.isWorker) {
+  console.log('I am worker #' + cluster.worker.id);
+}
+

cluster.workers#

+
    +
  • Object
  • +
+

A hash that stores the active worker objects, keyed by id field. Makes it +easy to loop through all the workers. It is only available in the master +process. + +

+
// Go through all workers
+function eachWorker(callback) {
+  for (var id in cluster.workers) {
+    callback(cluster.workers[id]);
+  }
+}
+eachWorker(function(worker) {
+  worker.send('big announcement to all workers');
+});
+

Should you wish to reference a worker over a communication channel, using +the worker's unique id is the easiest way to find the worker. + +

+
socket.on('data', function(id) {
+  var worker = cluster.workers[id];
+});
+

Class: Worker#

+

A Worker object contains all public information and method about a worker. +In the master it can be obtained using cluster.workers. In a worker +it can be obtained using cluster.worker. + +

+

worker.id#

+
    +
  • String
  • +
+

Each new worker is given its own unique id, this id is stored in the +id. + +

+

While a worker is alive, this is the key that indexes it in +cluster.workers + +

+

worker.process#

+
    +
  • ChildProcess object
  • +
+

All workers are created using child_process.fork(), the returned object +from this function is stored in process. + +

+

See: Child Process module + +

+

worker.suicide#

+
    +
  • Boolean
  • +
+

This property is a boolean. It is set when a worker dies after calling .destroy() +or immediately after calling the .disconnect() method. Until then it is undefined. + +

+

worker.send(message, [sendHandle])#

+
    +
  • message Object
  • +
  • sendHandle Handle object
  • +
+

This function is equal to the send methods provided by +child_process.fork(). In the master you should use this function to +send a message to a specific worker. However in a worker you can also use +process.send(message), since this is the same function. + +

+

This example will echo back all messages from the master: + +

+
if (cluster.isMaster) {
+  var worker = cluster.fork();
+  worker.send('hi there');
+
+} else if (cluster.isWorker) {
+  process.on('message', function(msg) {
+    process.send(msg);
+  });
+}
+

worker.destroy()#

+

This function will kill the worker, and inform the master to not spawn a +new worker. The boolean suicide lets you distinguish between voluntary +and accidental exit. + +

+
cluster.on('exit', function(worker, code, signal) {
+  if (worker.suicide === true) {
+    console.log('Oh, it was just suicide\' – no need to worry').
+  }
+});
+
+// destroy worker
+worker.destroy();
+

worker.disconnect()#

+

When calling this function the worker will no longer accept new connections, but +they will be handled by any other listening worker. Existing connection will be +allowed to exit as usual. When no more connections exist, the IPC channel to the worker +will close allowing it to die graceful. When the IPC channel is closed the disconnect +event will emit, this is then followed by the exit event, there is emitted when +the worker finally die. + +

+

Because there might be long living connections, it is useful to implement a timeout. +This example ask the worker to disconnect and after 2 seconds it will destroy the +server. An alternative would be to execute worker.destroy() after 2 seconds, but +that would normally not allow the worker to do any cleanup if needed. + +

+
if (cluster.isMaster) {
+  var worker = cluster.fork();
+  var timeout;
+
+  worker.on('listening', function(address) {
+    worker.disconnect();
+    timeout = setTimeout(function() {
+      worker.send('force kill');
+    }, 2000);
+  });
+
+  worker.on('disconnect', function() {
+    clearTimeout(timeout);
+  });
+
+} else if (cluster.isWorker) {
+  var net = require('net');
+  var server = net.createServer(function(socket) {
+    // connection never end
+  });
+
+  server.listen(8000);
+
+  server.on('close', function() {
+    // cleanup
+  });
+
+  process.on('message', function(msg) {
+    if (msg === 'force kill') {
+      server.destroy();
+    }
+  });
+}
+

Event: 'message'#

+
    +
  • message Object
  • +
+

This event is the same as the one provided by child_process.fork(). +In the master you should use this event, however in a worker you can also use +process.on('message') + +

+

As an example, here is a cluster that keeps count of the number of requests +in the master process using the message system: + +

+
var cluster = require('cluster');
+var http = require('http');
+
+if (cluster.isMaster) {
+
+  // Keep track of http requests
+  var numReqs = 0;
+  setInterval(function() {
+    console.log("numReqs =", numReqs);
+  }, 1000);
+
+  // Count requestes
+  function messageHandler(msg) {
+    if (msg.cmd && msg.cmd == 'notifyRequest') {
+      numReqs += 1;
+    }
+  }
+
+  // Start workers and listen for messages containing notifyRequest
+  var numCPUs = require('os').cpus().length;
+  for (var i = 0; i < numCPUs; i++) {
+    cluster.fork();
+  }
+
+  Object.keys(cluster.workers).forEach(function(id) {
+    cluster.workers[id].on('message', messageHandler);
+  });
+
+} else {
+
+  // Worker processes have a http server.
+  http.Server(function(req, res) {
+    res.writeHead(200);
+    res.end("hello world\n");
+
+    // notify master about the request
+    process.send({ cmd: 'notifyRequest' });
+  }).listen(8000);
+}
+

Event: 'online'#

+

Same as the cluster.on('online') event, but emits only when the state change +on the specified worker. + +

+
cluster.fork().on('online', function() {
+  // Worker is online
+};
+

Event: 'listening'#

+
    +
  • address Object
  • +
+

Same as the cluster.on('listening') event, but emits only when the state change +on the specified worker. + +

+
cluster.fork().on('listening', function(address) {
+  // Worker is listening
+};
+

Event: 'disconnect'#

+

Same as the cluster.on('disconnect') event, but emits only when the state change +on the specified worker. + +

+
cluster.fork().on('disconnect', function() {
+  // Worker has disconnected
+};
+

Event: 'exit'#

+
    +
  • code Number the exit code, if it exited normally.
  • +
  • signal String the name of the signal (eg. 'SIGHUP') that caused +the process to be killed.
  • +
+

Emitted by the individual worker instance, when the underlying child process +is terminated. See child_process event: 'exit'. + +

+
var worker = cluster.fork();
+worker.on('exit', function(code, signal) {
+  if( signal ) {
+    console.log("worker was killed by signal: "+signal);
+  } else if( code !== 0 ) {
+    console.log("worker exited with error code: "+code);
+  } else {
+    console.log("worker success!");
+  }
+};
+ +
+
+
+ + + + + + + + + diff --git a/node-v0.8.14/doc/api/all.json b/node-v0.8.14/doc/api/all.json new file mode 100644 index 0000000..300de4d --- /dev/null +++ b/node-v0.8.14/doc/api/all.json @@ -0,0 +1,11543 @@ +{ + "source": "doc/api/all.markdown", + "miscs": [ + { + "textRaw": "About this Documentation", + "name": "About this Documentation", + "type": "misc", + "desc": "

The goal of this documentation is to comprehensively explain the Node.js\nAPI, both from a reference as well as a conceptual point of view. Each\nsection describes a built-in module or high-level concept.\n\n

\n

Where appropriate, property types, method arguments, and the arguments\nprovided to event handlers are detailed in a list underneath the topic\nheading.\n\n

\n

Every .html document has a corresponding .json document presenting\nthe same information in a structured manner. This feature is\nexperimental, and added for the benefit of IDEs and other utilities that\nwish to do programmatic things with the documentation.\n\n

\n

Every .html and .json file is generated based on the corresponding\n.markdown file in the doc/api/ folder in node's source tree. The\ndocumentation is generated using the tools/doc/generate.js program.\nThe HTML template is located at doc/template.html.\n\n

\n", + "miscs": [ + { + "textRaw": "Stability Index", + "name": "Stability Index", + "type": "misc", + "desc": "

Throughout the documentation, you will see indications of a section's\nstability. The Node.js API is still somewhat changing, and as it\nmatures, certain parts are more reliable than others. Some are so\nproven, and so relied upon, that they are unlikely to ever change at\nall. Others are brand new and experimental, or known to be hazardous\nand in the process of being redesigned.\n\n

\n

The notices look like this:\n\n

\n
Stability: 1 Experimental
\n

The stability indices are as follows:\n\n

\n
    \n
  • 0 - Deprecated This feature is known to be problematic, and changes are\nplanned. Do not rely on it. Use of the feature may cause warnings. Backwards\ncompatibility should not be expected.
  • \n
\n
    \n
  • 1 - Experimental This feature was introduced recently, and may change\nor be removed in future versions. Please try it out and provide feedback.\nIf it addresses a use-case that is important to you, tell the node core team.
  • \n
\n
    \n
  • 2 - Unstable The API is in the process of settling, but has not yet had\nsufficient real-world testing to be considered stable. Backwards-compatibility\nwill be maintained if reasonable.
  • \n
\n
    \n
  • 3 - Stable The API has proven satisfactory, but cleanup in the underlying\ncode may cause minor changes. Backwards-compatibility is guaranteed.
  • \n
\n
    \n
  • 4 - API Frozen This API has been tested extensively in production and is\nunlikely to ever have to change.
  • \n
\n
    \n
  • 5 - Locked Unless serious bugs are found, this code will not ever\nchange. Please do not suggest changes in this area; they will be refused.
  • \n
\n" + }, + { + "textRaw": "JSON Output", + "name": "json_output", + "stability": 1, + "stabilityText": "Experimental", + "desc": "

Every HTML file in the markdown has a corresponding JSON file with the\nsame data.\n\n

\n

This feature is new as of node v0.6.12. It is experimental.\n\n

\n", + "type": "misc", + "displayName": "JSON Output" + } + ] + }, + { + "textRaw": "Synopsis", + "name": "Synopsis", + "type": "misc", + "desc": "

An example of a web server written with Node which responds with 'Hello\nWorld':\n\n

\n
var http = require('http');\n\nhttp.createServer(function (request, response) {\n  response.writeHead(200, {'Content-Type': 'text/plain'});\n  response.end('Hello World\\n');\n}).listen(8124);\n\nconsole.log('Server running at http://127.0.0.1:8124/');
\n

To run the server, put the code into a file called example.js and execute\nit with the node program\n\n

\n
> node example.js\nServer running at http://127.0.0.1:8124/
\n

All of the examples in the documentation can be run similarly.\n\n

\n" + }, + { + "textRaw": "Global Objects", + "name": "Global Objects", + "type": "misc", + "desc": "

These objects are available in all modules. Some of these objects aren't\nactually in the global scope but in the module scope - this will be noted.\n\n

\n", + "globals": [ + { + "textRaw": "global", + "name": "global", + "type": "global", + "desc": "

In browsers, the top-level scope is the global scope. That means that in\nbrowsers if you're in the global scope var something will define a global\nvariable. In Node this is different. The top-level scope is not the global\nscope; var something inside a Node module will be local to that module.\n\n

\n" + }, + { + "textRaw": "process", + "name": "process", + "type": "global", + "desc": "

The process object. See the [process object][] section.\n\n

\n" + }, + { + "textRaw": "console", + "name": "console", + "type": "global", + "desc": "

Used to print to stdout and stderr. See the [stdio][] section.\n\n

\n" + }, + { + "textRaw": "Class: Buffer", + "type": "global", + "name": "Buffer", + "desc": "

Used to handle binary data. See the [buffer section][]\n\n

\n" + }, + { + "textRaw": "clearInterval(t)", + "type": "global", + "name": "clearInterval", + "desc": "

Stop a timer that was previously created with setInterval(). The callback\nwill not execute.\n\n

\n

The timer functions are global variables. See the [timers][] section.\n\n

\n" + }, + { + "textRaw": "console", + "name": "console", + "stability": 4, + "stabilityText": "API Frozen", + "type": "global", + "desc": "

For printing to stdout and stderr. Similar to the console object functions\nprovided by most web browsers, here the output is sent to stdout or stderr.\n\n

\n", + "methods": [ + { + "textRaw": "console.log([data], [...])", + "type": "method", + "name": "log", + "desc": "

Prints to stdout with newline. This function can take multiple arguments in a\nprintf()-like way. Example:\n\n

\n
console.log('count: %d', count);
\n

If formatting elements are not found in the first string then util.inspect\nis used on each argument. See [util.format()][] for more information.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "data", + "optional": true + }, + { + "name": "...", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "console.info([data], [...])", + "type": "method", + "name": "info", + "desc": "

Same as console.log.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "data", + "optional": true + }, + { + "name": "...", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "console.error([data], [...])", + "type": "method", + "name": "error", + "desc": "

Same as console.log but prints to stderr.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "data", + "optional": true + }, + { + "name": "...", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "console.warn([data], [...])", + "type": "method", + "name": "warn", + "desc": "

Same as console.error.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "data", + "optional": true + }, + { + "name": "...", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "console.dir(obj)", + "type": "method", + "name": "dir", + "desc": "

Uses util.inspect on obj and prints resulting string to stdout.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "obj" + } + ] + } + ] + }, + { + "textRaw": "console.time(label)", + "type": "method", + "name": "time", + "desc": "

Mark a time.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "label" + } + ] + } + ] + }, + { + "textRaw": "console.timeEnd(label)", + "type": "method", + "name": "timeEnd", + "desc": "

Finish timer, record output. Example:\n\n

\n
console.time('100-elements');\nfor (var i = 0; i < 100; i++) {\n  ;\n}\nconsole.timeEnd('100-elements');
\n", + "signatures": [ + { + "params": [ + { + "name": "label" + } + ] + } + ] + }, + { + "textRaw": "console.trace(label)", + "type": "method", + "name": "trace", + "desc": "

Print a stack trace to stderr of the current position.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "label" + } + ] + } + ] + }, + { + "textRaw": "console.assert(expression, [message])", + "type": "method", + "name": "assert", + "desc": "

Same as [assert.ok()][] where if the expression evaluates as false throw an\nAssertionError with message.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "expression" + }, + { + "name": "message", + "optional": true + } + ] + } + ] + } + ] + }, + { + "textRaw": "process", + "name": "process", + "type": "global", + "desc": "

The process object is a global object and can be accessed from anywhere.\nIt is an instance of [EventEmitter][].\n\n\n

\n", + "events": [ + { + "textRaw": "Event: 'exit'", + "type": "event", + "name": "exit", + "desc": "

Emitted when the process is about to exit. This is a good hook to perform\nconstant time checks of the module's state (like for unit tests). The main\nevent loop will no longer be run after the 'exit' callback finishes, so\ntimers may not be scheduled.\n\n

\n

Example of listening for exit:\n\n

\n
process.on('exit', function () {\n  process.nextTick(function () {\n   console.log('This will not run');\n  });\n  console.log('About to exit.');\n});
\n", + "params": [] + }, + { + "textRaw": "Event: 'uncaughtException'", + "type": "event", + "name": "uncaughtException", + "desc": "

Emitted when an exception bubbles all the way back to the event loop. If a\nlistener is added for this exception, the default action (which is to print\na stack trace and exit) will not occur.\n\n

\n

Example of listening for uncaughtException:\n\n

\n
process.on('uncaughtException', function (err) {\n  console.log('Caught exception: ' + err);\n});\n\nsetTimeout(function () {\n  console.log('This will still run.');\n}, 500);\n\n// Intentionally cause an exception, but don't catch it.\nnonexistentFunc();\nconsole.log('This will not run.');
\n

Note that uncaughtException is a very crude mechanism for exception\nhandling and may be removed in the future.\n\n

\n

Don't use it, use domains instead. If you do use it, restart\nyour application after every unhandled exception!\n\n

\n

Do not use it as the node.js equivalent of On Error Resume Next. An\nunhandled exception means your application - and by extension node.js itself -\nis in an undefined state. Blindly resuming means anything could happen.\n\n

\n

Think of resuming as pulling the power cord when you are upgrading your system.\nNine out of ten times nothing happens - but the 10th time, your system is bust.\n\n

\n

You have been warned.\n\n

\n", + "params": [] + }, + { + "textRaw": "Signal Events", + "name": "SIGINT, SIGUSR1, etc.", + "type": "event", + "desc": "

Emitted when the processes receives a signal. See sigaction(2) for a list of\nstandard POSIX signal names such as SIGINT, SIGUSR1, etc.\n\n

\n

Example of listening for SIGINT:\n\n

\n
// Start reading from stdin so we don't exit.\nprocess.stdin.resume();\n\nprocess.on('SIGINT', function () {\n  console.log('Got SIGINT.  Press Control-D to exit.');\n});
\n

An easy way to send the SIGINT signal is with Control-C in most terminal\nprograms.\n\n\n

\n", + "params": [] + } + ], + "properties": [ + { + "textRaw": "process.stdout", + "name": "stdout", + "desc": "

A Writable Stream to stdout.\n\n

\n

Example: the definition of console.log\n\n

\n
console.log = function (d) {\n  process.stdout.write(d + '\\n');\n};
\n

process.stderr and process.stdout are unlike other streams in Node in\nthat writes to them are usually blocking. They are blocking in the case\nthat they refer to regular files or TTY file descriptors. In the case they\nrefer to pipes, they are non-blocking like other streams.\n\n\n

\n" + }, + { + "textRaw": "process.stderr", + "name": "stderr", + "desc": "

A writable stream to stderr.\n\n

\n

process.stderr and process.stdout are unlike other streams in Node in\nthat writes to them are usually blocking. They are blocking in the case\nthat they refer to regular files or TTY file descriptors. In the case they\nrefer to pipes, they are non-blocking like other streams.\n\n\n

\n" + }, + { + "textRaw": "process.stdin", + "name": "stdin", + "desc": "

A Readable Stream for stdin. The stdin stream is paused by default, so one\nmust call process.stdin.resume() to read from it.\n\n

\n

Example of opening standard input and listening for both events:\n\n

\n
process.stdin.resume();\nprocess.stdin.setEncoding('utf8');\n\nprocess.stdin.on('data', function (chunk) {\n  process.stdout.write('data: ' + chunk);\n});\n\nprocess.stdin.on('end', function () {\n  process.stdout.write('end');\n});
\n" + }, + { + "textRaw": "process.argv", + "name": "argv", + "desc": "

An array containing the command line arguments. The first element will be\n'node', the second element will be the name of the JavaScript file. The\nnext elements will be any additional command line arguments.\n\n

\n
// print process.argv\nprocess.argv.forEach(function (val, index, array) {\n  console.log(index + ': ' + val);\n});
\n

This will generate:\n\n

\n
$ node process-2.js one two=three four\n0: node\n1: /Users/mjr/work/node/process-2.js\n2: one\n3: two=three\n4: four
\n" + }, + { + "textRaw": "process.execPath", + "name": "execPath", + "desc": "

This is the absolute pathname of the executable that started the process.\n\n

\n

Example:\n\n

\n
/usr/local/bin/node
\n" + }, + { + "textRaw": "process.env", + "name": "env", + "desc": "

An object containing the user environment. See environ(7).\n\n\n

\n" + }, + { + "textRaw": "process.version", + "name": "version", + "desc": "

A compiled-in property that exposes NODE_VERSION.\n\n

\n
console.log('Version: ' + process.version);
\n" + }, + { + "textRaw": "process.versions", + "name": "versions", + "desc": "

A property exposing version strings of node and its dependencies.\n\n

\n
console.log(process.versions);
\n

Will output:\n\n

\n
{ node: '0.4.12',\n  v8: '3.1.8.26',\n  ares: '1.7.4',\n  ev: '4.4',\n  openssl: '1.0.0e-fips' }
\n" + }, + { + "textRaw": "process.config", + "name": "config", + "desc": "

An Object containing the JavaScript representation of the configure options\nthat were used to compile the current node executable. This is the same as\nthe "config.gypi" file that was produced when running the ./configure script.\n\n

\n

An example of the possible output looks like:\n\n

\n
{ target_defaults:\n   { cflags: [],\n     default_configuration: 'Release',\n     defines: [],\n     include_dirs: [],\n     libraries: [] },\n  variables:\n   { host_arch: 'x64',\n     node_install_npm: 'true',\n     node_install_waf: 'true',\n     node_prefix: '',\n     node_shared_v8: 'false',\n     node_shared_zlib: 'false',\n     node_use_dtrace: 'false',\n     node_use_openssl: 'true',\n     node_shared_openssl: 'false',\n     strict_aliasing: 'true',\n     target_arch: 'x64',\n     v8_use_snapshot: 'true' } }
\n" + }, + { + "textRaw": "process.pid", + "name": "pid", + "desc": "

The PID of the process.\n\n

\n
console.log('This process is pid ' + process.pid);
\n" + }, + { + "textRaw": "process.title", + "name": "title", + "desc": "

Getter/setter to set what is displayed in 'ps'.\n\n\n

\n" + }, + { + "textRaw": "process.arch", + "name": "arch", + "desc": "

What processor architecture you're running on: 'arm', 'ia32', or 'x64'.\n\n

\n
console.log('This processor architecture is ' + process.arch);
\n" + }, + { + "textRaw": "process.platform", + "name": "platform", + "desc": "

What platform you're running on:\n'darwin', 'freebsd', 'linux', 'sunos' or 'win32'\n\n

\n
console.log('This platform is ' + process.platform);
\n" + } + ], + "methods": [ + { + "textRaw": "process.abort()", + "type": "method", + "name": "abort", + "desc": "

This causes node to emit an abort. This will cause node to exit and\ngenerate a core file.\n\n

\n", + "signatures": [ + { + "params": [] + } + ] + }, + { + "textRaw": "process.chdir(directory)", + "type": "method", + "name": "chdir", + "desc": "

Changes the current working directory of the process or throws an exception if that fails.\n\n

\n
console.log('Starting directory: ' + process.cwd());\ntry {\n  process.chdir('/tmp');\n  console.log('New directory: ' + process.cwd());\n}\ncatch (err) {\n  console.log('chdir: ' + err);\n}
\n", + "signatures": [ + { + "params": [ + { + "name": "directory" + } + ] + } + ] + }, + { + "textRaw": "process.cwd()", + "type": "method", + "name": "cwd", + "desc": "

Returns the current working directory of the process.\n\n

\n
console.log('Current directory: ' + process.cwd());
\n", + "signatures": [ + { + "params": [] + } + ] + }, + { + "textRaw": "process.exit([code])", + "type": "method", + "name": "exit", + "desc": "

Ends the process with the specified code. If omitted, exit uses the\n'success' code 0.\n\n

\n

To exit with a 'failure' code:\n\n

\n
process.exit(1);
\n

The shell that executed node should see the exit code as 1.\n\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "code", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "process.getgid()", + "type": "method", + "name": "getgid", + "desc": "

Note: this function is only available on POSIX platforms (i.e. not Windows)\n\n

\n

Gets the group identity of the process. (See getgid(2).)\nThis is the numerical group id, not the group name.\n\n

\n
if (process.getgid) {\n  console.log('Current gid: ' + process.getgid());\n}
\n", + "signatures": [ + { + "params": [] + } + ] + }, + { + "textRaw": "process.setgid(id)", + "type": "method", + "name": "setgid", + "desc": "

Note: this function is only available on POSIX platforms (i.e. not Windows)\n\n

\n

Sets the group identity of the process. (See setgid(2).) This accepts either\na numerical ID or a groupname string. If a groupname is specified, this method\nblocks while resolving it to a numerical ID.\n\n

\n
if (process.getgid && process.setgid) {\n  console.log('Current gid: ' + process.getgid());\n  try {\n    process.setgid(501);\n    console.log('New gid: ' + process.getgid());\n  }\n  catch (err) {\n    console.log('Failed to set gid: ' + err);\n  }\n}
\n", + "signatures": [ + { + "params": [ + { + "name": "id" + } + ] + } + ] + }, + { + "textRaw": "process.getuid()", + "type": "method", + "name": "getuid", + "desc": "

Note: this function is only available on POSIX platforms (i.e. not Windows)\n\n

\n

Gets the user identity of the process. (See getuid(2).)\nThis is the numerical userid, not the username.\n\n

\n
if (process.getuid) {\n  console.log('Current uid: ' + process.getuid());\n}
\n", + "signatures": [ + { + "params": [] + } + ] + }, + { + "textRaw": "process.setuid(id)", + "type": "method", + "name": "setuid", + "desc": "

Note: this function is only available on POSIX platforms (i.e. not Windows)\n\n

\n

Sets the user identity of the process. (See setuid(2).) This accepts either\na numerical ID or a username string. If a username is specified, this method\nblocks while resolving it to a numerical ID.\n\n

\n
if (process.getuid && process.setuid) {\n  console.log('Current uid: ' + process.getuid());\n  try {\n    process.setuid(501);\n    console.log('New uid: ' + process.getuid());\n  }\n  catch (err) {\n    console.log('Failed to set uid: ' + err);\n  }\n}
\n", + "signatures": [ + { + "params": [ + { + "name": "id" + } + ] + } + ] + }, + { + "textRaw": "process.kill(pid, [signal])", + "type": "method", + "name": "kill", + "desc": "

Send a signal to a process. pid is the process id and signal is the\nstring describing the signal to send. Signal names are strings like\n'SIGINT' or 'SIGUSR1'. If omitted, the signal will be 'SIGTERM'.\nSee kill(2) for more information.\n\n

\n

Note that just because the name of this function is process.kill, it is\nreally just a signal sender, like the kill system call. The signal sent\nmay do something other than kill the target process.\n\n

\n

Example of sending a signal to yourself:\n\n

\n
process.on('SIGHUP', function () {\n  console.log('Got SIGHUP signal.');\n});\n\nsetTimeout(function () {\n  console.log('Exiting.');\n  process.exit(0);\n}, 100);\n\nprocess.kill(process.pid, 'SIGHUP');
\n", + "signatures": [ + { + "params": [ + { + "name": "pid" + }, + { + "name": "signal", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "process.memoryUsage()", + "type": "method", + "name": "memoryUsage", + "desc": "

Returns an object describing the memory usage of the Node process\nmeasured in bytes.\n\n

\n
var util = require('util');\n\nconsole.log(util.inspect(process.memoryUsage()));
\n

This will generate:\n\n

\n
{ rss: 4935680,\n  heapTotal: 1826816,\n  heapUsed: 650472 }
\n

heapTotal and heapUsed refer to V8's memory usage.\n\n\n

\n", + "signatures": [ + { + "params": [] + } + ] + }, + { + "textRaw": "process.nextTick(callback)", + "type": "method", + "name": "nextTick", + "desc": "

On the next loop around the event loop call this callback.\nThis is not a simple alias to setTimeout(fn, 0), it's much more\nefficient.\n\n

\n
process.nextTick(function () {\n  console.log('nextTick callback');\n});
\n", + "signatures": [ + { + "params": [ + { + "name": "callback" + } + ] + } + ] + }, + { + "textRaw": "process.umask([mask])", + "type": "method", + "name": "umask", + "desc": "

Sets or reads the process's file mode creation mask. Child processes inherit\nthe mask from the parent process. Returns the old mask if mask argument is\ngiven, otherwise returns the current mask.\n\n

\n
var oldmask, newmask = 0644;\n\noldmask = process.umask(newmask);\nconsole.log('Changed umask from: ' + oldmask.toString(8) +\n            ' to ' + newmask.toString(8));
\n", + "signatures": [ + { + "params": [ + { + "name": "mask", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "process.uptime()", + "type": "method", + "name": "uptime", + "desc": "

Number of seconds Node has been running.\n\n\n

\n", + "signatures": [ + { + "params": [] + } + ] + }, + { + "textRaw": "process.hrtime()", + "type": "method", + "name": "hrtime", + "desc": "

Returns the current high-resolution real time in a [seconds, nanoseconds]\ntuple Array. It is relative to an arbitrary time in the past. It is not\nrelated to the time of day and therefore not subject to clock drift. The\nprimary use is for measuring performance between intervals.\n\n

\n

You may pass in the result of a previous call to process.hrtime() to get\na diff reading, useful for benchmarks and measuring intervals:\n\n

\n
var time = process.hrtime();\n// [ 1800216, 927643717 ]\n\nsetTimeout(function () {\n  var diff = process.hrtime(time);\n  // [ 1, 6962306 ]\n\n  console.log('benchmark took %d seconds and %d nanoseconds',\n              diff[0], diff[1]);\n  // benchmark took 1 seconds and 6962306 nanoseconds\n}, 1000);
\n", + "signatures": [ + { + "params": [] + } + ] + } + ] + } + ], + "vars": [ + { + "textRaw": "require()", + "type": "var", + "name": "require", + "desc": "

To require modules. See the [Modules][] section. require isn't actually a\nglobal but rather local to each module.\n\n

\n", + "methods": [ + { + "textRaw": "require.resolve()", + "type": "method", + "name": "resolve", + "desc": "

Use the internal require() machinery to look up the location of a module,\nbut rather than loading the module, just return the resolved filename.\n\n

\n", + "signatures": [ + { + "params": [] + } + ] + } + ], + "properties": [ + { + "textRaw": "`cache` {Object} ", + "name": "cache", + "desc": "

Modules are cached in this object when they are required. By deleting a key\nvalue from this object, the next require will reload the module.\n\n

\n" + }, + { + "textRaw": "`extensions` {Array} ", + "name": "extensions", + "desc": "

Instruct require on how to handle certain file extensions.\n\n

\n

Process files with the extension .sjs as .js:\n\n

\n
require.extensions['.sjs'] = require.extensions['.js'];
\n

Write your own extension handler:\n\n

\n
require.extensions['.sjs'] = function(module, filename) {\n  var content = fs.readFileSync(filename, 'utf8');\n  // Parse the file content and give to module.exports\n  module.exports = content;\n};
\n" + } + ] + }, + { + "textRaw": "__filename", + "name": "__filename", + "type": "var", + "desc": "

The filename of the code being executed. This is the resolved absolute path\nof this code file. For a main program this is not necessarily the same\nfilename used in the command line. The value inside a module is the path\nto that module file.\n\n

\n

Example: running node example.js from /Users/mjr\n\n

\n
console.log(__filename);\n// /Users/mjr/example.js
\n

__filename isn't actually a global but rather local to each module.\n\n

\n" + }, + { + "textRaw": "__dirname", + "name": "__dirname", + "type": "var", + "desc": "

The name of the directory that the currently executing script resides in.\n\n

\n

Example: running node example.js from /Users/mjr\n\n

\n
console.log(__dirname);\n// /Users/mjr
\n

__dirname isn't actually a global but rather local to each module.\n\n\n

\n" + }, + { + "textRaw": "module", + "name": "module", + "type": "var", + "desc": "

A reference to the current module. In particular\nmodule.exports is the same as the exports object.\nmodule isn't actually a global but rather local to each module.\n\n

\n

See the [module system documentation][] for more information.\n\n

\n" + }, + { + "textRaw": "exports", + "name": "exports", + "type": "var", + "desc": "

An object which is shared between all instances of the current module and\nmade accessible through require().\nexports is the same as the module.exports object.\nexports isn't actually a global but rather local to each module.\n\n

\n

See the [module system documentation][] for more information.\n\n

\n

See the [module section][] for more information.\n\n

\n" + } + ], + "methods": [ + { + "textRaw": "setTimeout(cb, ms)", + "type": "method", + "name": "setTimeout", + "desc": "

Run callback cb after at least ms milliseconds. The actual delay depends\non external factors like OS timer granularity and system load.\n\n

\n

The timeout must be in the range of 1-2,147,483,647 inclusive. If the value is\noutside that range, it's changed to 1 millisecond. Broadly speaking, a timer\ncannot span more than 24.8 days.\n\n

\n

Returns an opaque value that represents the timer.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "cb" + }, + { + "name": "ms" + } + ] + } + ] + }, + { + "textRaw": "clearTimeout(t)", + "type": "method", + "name": "clearTimeout", + "desc": "

Stop a timer that was previously created with setTimeout(). The callback will\nnot execute.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "t" + } + ] + } + ] + }, + { + "textRaw": "setInterval(cb, ms)", + "type": "method", + "name": "setInterval", + "desc": "

Run callback cb repeatedly every ms milliseconds. Note that the actual\ninterval may vary, depending on external factors like OS timer granularity and\nsystem load. It's never less than ms but it may be longer.\n\n

\n

The interval must be in the range of 1-2,147,483,647 inclusive. If the value is\noutside that range, it's changed to 1 millisecond. Broadly speaking, a timer\ncannot span more than 24.8 days.\n\n

\n

Returns an opaque value that represents the timer.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "cb" + }, + { + "name": "ms" + } + ] + } + ] + } + ] + }, + { + "textRaw": "Debugger", + "name": "Debugger", + "stability": 3, + "stabilityText": "Stable", + "type": "misc", + "desc": "

V8 comes with an extensive debugger which is accessible out-of-process via a\nsimple TCP protocol.\nNode has a built-in client for this debugger. To use this, start Node with the\ndebug argument; a prompt will appear:\n\n

\n
% node debug myscript.js\n< debugger listening on port 5858\nconnecting... ok\nbreak in /home/indutny/Code/git/indutny/myscript.js:1\n  1 x = 5;\n  2 setTimeout(function () {\n  3   debugger;\ndebug>
\n

Node's debugger client doesn't support the full range of commands, but\nsimple step and inspection is possible. By putting the statement debugger;\ninto the source code of your script, you will enable a breakpoint.\n\n

\n

For example, suppose myscript.js looked like this:\n\n

\n
// myscript.js\nx = 5;\nsetTimeout(function () {\n  debugger;\n  console.log("world");\n}, 1000);\nconsole.log("hello");
\n

Then once the debugger is run, it will break on line 4.\n\n

\n
% node debug myscript.js\n< debugger listening on port 5858\nconnecting... ok\nbreak in /home/indutny/Code/git/indutny/myscript.js:1\n  1 x = 5;\n  2 setTimeout(function () {\n  3   debugger;\ndebug> cont\n< hello\nbreak in /home/indutny/Code/git/indutny/myscript.js:3\n  1 x = 5;\n  2 setTimeout(function () {\n  3   debugger;\n  4   console.log("world");\n  5 }, 1000);\ndebug> next\nbreak in /home/indutny/Code/git/indutny/myscript.js:4\n  2 setTimeout(function () {\n  3   debugger;\n  4   console.log("world");\n  5 }, 1000);\n  6 console.log("hello");\ndebug> repl\nPress Ctrl + C to leave debug repl\n> x\n5\n> 2+2\n4\ndebug> next\n< world\nbreak in /home/indutny/Code/git/indutny/myscript.js:5\n  3   debugger;\n  4   console.log("world");\n  5 }, 1000);\n  6 console.log("hello");\n  7\ndebug> quit\n%
\n

The repl command allows you to evaluate code remotely. The next command\nsteps over to the next line. There are a few other commands available and more\nto come. Type help to see others.\n\n

\n", + "miscs": [ + { + "textRaw": "Watchers", + "name": "watchers", + "desc": "

You can watch expression and variable values while debugging your code.\nOn every breakpoint each expression from the watchers list will be evaluated\nin the current context and displayed just before the breakpoint's source code\nlisting.\n\n

\n

To start watching an expression, type watch("my_expression"). watchers\nprints the active watchers. To remove a watcher, type\nunwatch("my_expression").\n\n

\n", + "type": "misc", + "displayName": "Watchers" + }, + { + "textRaw": "Commands reference", + "name": "commands_reference", + "modules": [ + { + "textRaw": "Execution control", + "name": "Execution control", + "type": "module", + "displayName": "Various" + }, + { + "textRaw": "Various", + "name": "various", + "type": "module", + "displayName": "Various" + } + ], + "type": "misc", + "displayName": "Commands reference" + }, + { + "textRaw": "Advanced Usage", + "name": "advanced_usage", + "desc": "

The V8 debugger can be enabled and accessed either by starting Node with\nthe --debug command-line flag or by signaling an existing Node process\nwith SIGUSR1.\n\n

\n", + "type": "misc", + "displayName": "Advanced Usage" + } + ] + } + ], + "globals": [ + { + "textRaw": "global", + "name": "global", + "type": "global", + "desc": "

In browsers, the top-level scope is the global scope. That means that in\nbrowsers if you're in the global scope var something will define a global\nvariable. In Node this is different. The top-level scope is not the global\nscope; var something inside a Node module will be local to that module.\n\n

\n" + }, + { + "textRaw": "process", + "name": "process", + "type": "global", + "desc": "

The process object. See the [process object][] section.\n\n

\n" + }, + { + "textRaw": "console", + "name": "console", + "type": "global", + "desc": "

Used to print to stdout and stderr. See the [stdio][] section.\n\n

\n" + }, + { + "textRaw": "Class: Buffer", + "type": "global", + "name": "Buffer", + "desc": "

Used to handle binary data. See the [buffer section][]\n\n

\n" + }, + { + "textRaw": "clearInterval(t)", + "type": "global", + "name": "clearInterval", + "desc": "

Stop a timer that was previously created with setInterval(). The callback\nwill not execute.\n\n

\n

The timer functions are global variables. See the [timers][] section.\n\n

\n" + }, + { + "textRaw": "console", + "name": "console", + "stability": 4, + "stabilityText": "API Frozen", + "type": "global", + "desc": "

For printing to stdout and stderr. Similar to the console object functions\nprovided by most web browsers, here the output is sent to stdout or stderr.\n\n

\n", + "methods": [ + { + "textRaw": "console.log([data], [...])", + "type": "method", + "name": "log", + "desc": "

Prints to stdout with newline. This function can take multiple arguments in a\nprintf()-like way. Example:\n\n

\n
console.log('count: %d', count);
\n

If formatting elements are not found in the first string then util.inspect\nis used on each argument. See [util.format()][] for more information.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "data", + "optional": true + }, + { + "name": "...", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "console.info([data], [...])", + "type": "method", + "name": "info", + "desc": "

Same as console.log.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "data", + "optional": true + }, + { + "name": "...", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "console.error([data], [...])", + "type": "method", + "name": "error", + "desc": "

Same as console.log but prints to stderr.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "data", + "optional": true + }, + { + "name": "...", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "console.warn([data], [...])", + "type": "method", + "name": "warn", + "desc": "

Same as console.error.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "data", + "optional": true + }, + { + "name": "...", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "console.dir(obj)", + "type": "method", + "name": "dir", + "desc": "

Uses util.inspect on obj and prints resulting string to stdout.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "obj" + } + ] + } + ] + }, + { + "textRaw": "console.time(label)", + "type": "method", + "name": "time", + "desc": "

Mark a time.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "label" + } + ] + } + ] + }, + { + "textRaw": "console.timeEnd(label)", + "type": "method", + "name": "timeEnd", + "desc": "

Finish timer, record output. Example:\n\n

\n
console.time('100-elements');\nfor (var i = 0; i < 100; i++) {\n  ;\n}\nconsole.timeEnd('100-elements');
\n", + "signatures": [ + { + "params": [ + { + "name": "label" + } + ] + } + ] + }, + { + "textRaw": "console.trace(label)", + "type": "method", + "name": "trace", + "desc": "

Print a stack trace to stderr of the current position.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "label" + } + ] + } + ] + }, + { + "textRaw": "console.assert(expression, [message])", + "type": "method", + "name": "assert", + "desc": "

Same as [assert.ok()][] where if the expression evaluates as false throw an\nAssertionError with message.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "expression" + }, + { + "name": "message", + "optional": true + } + ] + } + ] + } + ] + }, + { + "textRaw": "process", + "name": "process", + "type": "global", + "desc": "

The process object is a global object and can be accessed from anywhere.\nIt is an instance of [EventEmitter][].\n\n\n

\n", + "events": [ + { + "textRaw": "Event: 'exit'", + "type": "event", + "name": "exit", + "desc": "

Emitted when the process is about to exit. This is a good hook to perform\nconstant time checks of the module's state (like for unit tests). The main\nevent loop will no longer be run after the 'exit' callback finishes, so\ntimers may not be scheduled.\n\n

\n

Example of listening for exit:\n\n

\n
process.on('exit', function () {\n  process.nextTick(function () {\n   console.log('This will not run');\n  });\n  console.log('About to exit.');\n});
\n", + "params": [] + }, + { + "textRaw": "Event: 'uncaughtException'", + "type": "event", + "name": "uncaughtException", + "desc": "

Emitted when an exception bubbles all the way back to the event loop. If a\nlistener is added for this exception, the default action (which is to print\na stack trace and exit) will not occur.\n\n

\n

Example of listening for uncaughtException:\n\n

\n
process.on('uncaughtException', function (err) {\n  console.log('Caught exception: ' + err);\n});\n\nsetTimeout(function () {\n  console.log('This will still run.');\n}, 500);\n\n// Intentionally cause an exception, but don't catch it.\nnonexistentFunc();\nconsole.log('This will not run.');
\n

Note that uncaughtException is a very crude mechanism for exception\nhandling and may be removed in the future.\n\n

\n

Don't use it, use domains instead. If you do use it, restart\nyour application after every unhandled exception!\n\n

\n

Do not use it as the node.js equivalent of On Error Resume Next. An\nunhandled exception means your application - and by extension node.js itself -\nis in an undefined state. Blindly resuming means anything could happen.\n\n

\n

Think of resuming as pulling the power cord when you are upgrading your system.\nNine out of ten times nothing happens - but the 10th time, your system is bust.\n\n

\n

You have been warned.\n\n

\n", + "params": [] + }, + { + "textRaw": "Signal Events", + "name": "SIGINT, SIGUSR1, etc.", + "type": "event", + "desc": "

Emitted when the processes receives a signal. See sigaction(2) for a list of\nstandard POSIX signal names such as SIGINT, SIGUSR1, etc.\n\n

\n

Example of listening for SIGINT:\n\n

\n
// Start reading from stdin so we don't exit.\nprocess.stdin.resume();\n\nprocess.on('SIGINT', function () {\n  console.log('Got SIGINT.  Press Control-D to exit.');\n});
\n

An easy way to send the SIGINT signal is with Control-C in most terminal\nprograms.\n\n\n

\n", + "params": [] + } + ], + "properties": [ + { + "textRaw": "process.stdout", + "name": "stdout", + "desc": "

A Writable Stream to stdout.\n\n

\n

Example: the definition of console.log\n\n

\n
console.log = function (d) {\n  process.stdout.write(d + '\\n');\n};
\n

process.stderr and process.stdout are unlike other streams in Node in\nthat writes to them are usually blocking. They are blocking in the case\nthat they refer to regular files or TTY file descriptors. In the case they\nrefer to pipes, they are non-blocking like other streams.\n\n\n

\n" + }, + { + "textRaw": "process.stderr", + "name": "stderr", + "desc": "

A writable stream to stderr.\n\n

\n

process.stderr and process.stdout are unlike other streams in Node in\nthat writes to them are usually blocking. They are blocking in the case\nthat they refer to regular files or TTY file descriptors. In the case they\nrefer to pipes, they are non-blocking like other streams.\n\n\n

\n" + }, + { + "textRaw": "process.stdin", + "name": "stdin", + "desc": "

A Readable Stream for stdin. The stdin stream is paused by default, so one\nmust call process.stdin.resume() to read from it.\n\n

\n

Example of opening standard input and listening for both events:\n\n

\n
process.stdin.resume();\nprocess.stdin.setEncoding('utf8');\n\nprocess.stdin.on('data', function (chunk) {\n  process.stdout.write('data: ' + chunk);\n});\n\nprocess.stdin.on('end', function () {\n  process.stdout.write('end');\n});
\n" + }, + { + "textRaw": "process.argv", + "name": "argv", + "desc": "

An array containing the command line arguments. The first element will be\n'node', the second element will be the name of the JavaScript file. The\nnext elements will be any additional command line arguments.\n\n

\n
// print process.argv\nprocess.argv.forEach(function (val, index, array) {\n  console.log(index + ': ' + val);\n});
\n

This will generate:\n\n

\n
$ node process-2.js one two=three four\n0: node\n1: /Users/mjr/work/node/process-2.js\n2: one\n3: two=three\n4: four
\n" + }, + { + "textRaw": "process.execPath", + "name": "execPath", + "desc": "

This is the absolute pathname of the executable that started the process.\n\n

\n

Example:\n\n

\n
/usr/local/bin/node
\n" + }, + { + "textRaw": "process.env", + "name": "env", + "desc": "

An object containing the user environment. See environ(7).\n\n\n

\n" + }, + { + "textRaw": "process.version", + "name": "version", + "desc": "

A compiled-in property that exposes NODE_VERSION.\n\n

\n
console.log('Version: ' + process.version);
\n" + }, + { + "textRaw": "process.versions", + "name": "versions", + "desc": "

A property exposing version strings of node and its dependencies.\n\n

\n
console.log(process.versions);
\n

Will output:\n\n

\n
{ node: '0.4.12',\n  v8: '3.1.8.26',\n  ares: '1.7.4',\n  ev: '4.4',\n  openssl: '1.0.0e-fips' }
\n" + }, + { + "textRaw": "process.config", + "name": "config", + "desc": "

An Object containing the JavaScript representation of the configure options\nthat were used to compile the current node executable. This is the same as\nthe "config.gypi" file that was produced when running the ./configure script.\n\n

\n

An example of the possible output looks like:\n\n

\n
{ target_defaults:\n   { cflags: [],\n     default_configuration: 'Release',\n     defines: [],\n     include_dirs: [],\n     libraries: [] },\n  variables:\n   { host_arch: 'x64',\n     node_install_npm: 'true',\n     node_install_waf: 'true',\n     node_prefix: '',\n     node_shared_v8: 'false',\n     node_shared_zlib: 'false',\n     node_use_dtrace: 'false',\n     node_use_openssl: 'true',\n     node_shared_openssl: 'false',\n     strict_aliasing: 'true',\n     target_arch: 'x64',\n     v8_use_snapshot: 'true' } }
\n" + }, + { + "textRaw": "process.pid", + "name": "pid", + "desc": "

The PID of the process.\n\n

\n
console.log('This process is pid ' + process.pid);
\n" + }, + { + "textRaw": "process.title", + "name": "title", + "desc": "

Getter/setter to set what is displayed in 'ps'.\n\n\n

\n" + }, + { + "textRaw": "process.arch", + "name": "arch", + "desc": "

What processor architecture you're running on: 'arm', 'ia32', or 'x64'.\n\n

\n
console.log('This processor architecture is ' + process.arch);
\n" + }, + { + "textRaw": "process.platform", + "name": "platform", + "desc": "

What platform you're running on:\n'darwin', 'freebsd', 'linux', 'sunos' or 'win32'\n\n

\n
console.log('This platform is ' + process.platform);
\n" + } + ], + "methods": [ + { + "textRaw": "process.abort()", + "type": "method", + "name": "abort", + "desc": "

This causes node to emit an abort. This will cause node to exit and\ngenerate a core file.\n\n

\n", + "signatures": [ + { + "params": [] + } + ] + }, + { + "textRaw": "process.chdir(directory)", + "type": "method", + "name": "chdir", + "desc": "

Changes the current working directory of the process or throws an exception if that fails.\n\n

\n
console.log('Starting directory: ' + process.cwd());\ntry {\n  process.chdir('/tmp');\n  console.log('New directory: ' + process.cwd());\n}\ncatch (err) {\n  console.log('chdir: ' + err);\n}
\n", + "signatures": [ + { + "params": [ + { + "name": "directory" + } + ] + } + ] + }, + { + "textRaw": "process.cwd()", + "type": "method", + "name": "cwd", + "desc": "

Returns the current working directory of the process.\n\n

\n
console.log('Current directory: ' + process.cwd());
\n", + "signatures": [ + { + "params": [] + } + ] + }, + { + "textRaw": "process.exit([code])", + "type": "method", + "name": "exit", + "desc": "

Ends the process with the specified code. If omitted, exit uses the\n'success' code 0.\n\n

\n

To exit with a 'failure' code:\n\n

\n
process.exit(1);
\n

The shell that executed node should see the exit code as 1.\n\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "code", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "process.getgid()", + "type": "method", + "name": "getgid", + "desc": "

Note: this function is only available on POSIX platforms (i.e. not Windows)\n\n

\n

Gets the group identity of the process. (See getgid(2).)\nThis is the numerical group id, not the group name.\n\n

\n
if (process.getgid) {\n  console.log('Current gid: ' + process.getgid());\n}
\n", + "signatures": [ + { + "params": [] + } + ] + }, + { + "textRaw": "process.setgid(id)", + "type": "method", + "name": "setgid", + "desc": "

Note: this function is only available on POSIX platforms (i.e. not Windows)\n\n

\n

Sets the group identity of the process. (See setgid(2).) This accepts either\na numerical ID or a groupname string. If a groupname is specified, this method\nblocks while resolving it to a numerical ID.\n\n

\n
if (process.getgid && process.setgid) {\n  console.log('Current gid: ' + process.getgid());\n  try {\n    process.setgid(501);\n    console.log('New gid: ' + process.getgid());\n  }\n  catch (err) {\n    console.log('Failed to set gid: ' + err);\n  }\n}
\n", + "signatures": [ + { + "params": [ + { + "name": "id" + } + ] + } + ] + }, + { + "textRaw": "process.getuid()", + "type": "method", + "name": "getuid", + "desc": "

Note: this function is only available on POSIX platforms (i.e. not Windows)\n\n

\n

Gets the user identity of the process. (See getuid(2).)\nThis is the numerical userid, not the username.\n\n

\n
if (process.getuid) {\n  console.log('Current uid: ' + process.getuid());\n}
\n", + "signatures": [ + { + "params": [] + } + ] + }, + { + "textRaw": "process.setuid(id)", + "type": "method", + "name": "setuid", + "desc": "

Note: this function is only available on POSIX platforms (i.e. not Windows)\n\n

\n

Sets the user identity of the process. (See setuid(2).) This accepts either\na numerical ID or a username string. If a username is specified, this method\nblocks while resolving it to a numerical ID.\n\n

\n
if (process.getuid && process.setuid) {\n  console.log('Current uid: ' + process.getuid());\n  try {\n    process.setuid(501);\n    console.log('New uid: ' + process.getuid());\n  }\n  catch (err) {\n    console.log('Failed to set uid: ' + err);\n  }\n}
\n", + "signatures": [ + { + "params": [ + { + "name": "id" + } + ] + } + ] + }, + { + "textRaw": "process.kill(pid, [signal])", + "type": "method", + "name": "kill", + "desc": "

Send a signal to a process. pid is the process id and signal is the\nstring describing the signal to send. Signal names are strings like\n'SIGINT' or 'SIGUSR1'. If omitted, the signal will be 'SIGTERM'.\nSee kill(2) for more information.\n\n

\n

Note that just because the name of this function is process.kill, it is\nreally just a signal sender, like the kill system call. The signal sent\nmay do something other than kill the target process.\n\n

\n

Example of sending a signal to yourself:\n\n

\n
process.on('SIGHUP', function () {\n  console.log('Got SIGHUP signal.');\n});\n\nsetTimeout(function () {\n  console.log('Exiting.');\n  process.exit(0);\n}, 100);\n\nprocess.kill(process.pid, 'SIGHUP');
\n", + "signatures": [ + { + "params": [ + { + "name": "pid" + }, + { + "name": "signal", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "process.memoryUsage()", + "type": "method", + "name": "memoryUsage", + "desc": "

Returns an object describing the memory usage of the Node process\nmeasured in bytes.\n\n

\n
var util = require('util');\n\nconsole.log(util.inspect(process.memoryUsage()));
\n

This will generate:\n\n

\n
{ rss: 4935680,\n  heapTotal: 1826816,\n  heapUsed: 650472 }
\n

heapTotal and heapUsed refer to V8's memory usage.\n\n\n

\n", + "signatures": [ + { + "params": [] + } + ] + }, + { + "textRaw": "process.nextTick(callback)", + "type": "method", + "name": "nextTick", + "desc": "

On the next loop around the event loop call this callback.\nThis is not a simple alias to setTimeout(fn, 0), it's much more\nefficient.\n\n

\n
process.nextTick(function () {\n  console.log('nextTick callback');\n});
\n", + "signatures": [ + { + "params": [ + { + "name": "callback" + } + ] + } + ] + }, + { + "textRaw": "process.umask([mask])", + "type": "method", + "name": "umask", + "desc": "

Sets or reads the process's file mode creation mask. Child processes inherit\nthe mask from the parent process. Returns the old mask if mask argument is\ngiven, otherwise returns the current mask.\n\n

\n
var oldmask, newmask = 0644;\n\noldmask = process.umask(newmask);\nconsole.log('Changed umask from: ' + oldmask.toString(8) +\n            ' to ' + newmask.toString(8));
\n", + "signatures": [ + { + "params": [ + { + "name": "mask", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "process.uptime()", + "type": "method", + "name": "uptime", + "desc": "

Number of seconds Node has been running.\n\n\n

\n", + "signatures": [ + { + "params": [] + } + ] + }, + { + "textRaw": "process.hrtime()", + "type": "method", + "name": "hrtime", + "desc": "

Returns the current high-resolution real time in a [seconds, nanoseconds]\ntuple Array. It is relative to an arbitrary time in the past. It is not\nrelated to the time of day and therefore not subject to clock drift. The\nprimary use is for measuring performance between intervals.\n\n

\n

You may pass in the result of a previous call to process.hrtime() to get\na diff reading, useful for benchmarks and measuring intervals:\n\n

\n
var time = process.hrtime();\n// [ 1800216, 927643717 ]\n\nsetTimeout(function () {\n  var diff = process.hrtime(time);\n  // [ 1, 6962306 ]\n\n  console.log('benchmark took %d seconds and %d nanoseconds',\n              diff[0], diff[1]);\n  // benchmark took 1 seconds and 6962306 nanoseconds\n}, 1000);
\n", + "signatures": [ + { + "params": [] + } + ] + } + ] + } + ], + "vars": [ + { + "textRaw": "require()", + "type": "var", + "name": "require", + "desc": "

To require modules. See the [Modules][] section. require isn't actually a\nglobal but rather local to each module.\n\n

\n", + "methods": [ + { + "textRaw": "require.resolve()", + "type": "method", + "name": "resolve", + "desc": "

Use the internal require() machinery to look up the location of a module,\nbut rather than loading the module, just return the resolved filename.\n\n

\n", + "signatures": [ + { + "params": [] + } + ] + } + ], + "properties": [ + { + "textRaw": "`cache` {Object} ", + "name": "cache", + "desc": "

Modules are cached in this object when they are required. By deleting a key\nvalue from this object, the next require will reload the module.\n\n

\n" + }, + { + "textRaw": "`extensions` {Array} ", + "name": "extensions", + "desc": "

Instruct require on how to handle certain file extensions.\n\n

\n

Process files with the extension .sjs as .js:\n\n

\n
require.extensions['.sjs'] = require.extensions['.js'];
\n

Write your own extension handler:\n\n

\n
require.extensions['.sjs'] = function(module, filename) {\n  var content = fs.readFileSync(filename, 'utf8');\n  // Parse the file content and give to module.exports\n  module.exports = content;\n};
\n" + } + ] + }, + { + "textRaw": "__filename", + "name": "__filename", + "type": "var", + "desc": "

The filename of the code being executed. This is the resolved absolute path\nof this code file. For a main program this is not necessarily the same\nfilename used in the command line. The value inside a module is the path\nto that module file.\n\n

\n

Example: running node example.js from /Users/mjr\n\n

\n
console.log(__filename);\n// /Users/mjr/example.js
\n

__filename isn't actually a global but rather local to each module.\n\n

\n" + }, + { + "textRaw": "__dirname", + "name": "__dirname", + "type": "var", + "desc": "

The name of the directory that the currently executing script resides in.\n\n

\n

Example: running node example.js from /Users/mjr\n\n

\n
console.log(__dirname);\n// /Users/mjr
\n

__dirname isn't actually a global but rather local to each module.\n\n\n

\n" + }, + { + "textRaw": "module", + "name": "module", + "type": "var", + "desc": "

A reference to the current module. In particular\nmodule.exports is the same as the exports object.\nmodule isn't actually a global but rather local to each module.\n\n

\n

See the [module system documentation][] for more information.\n\n

\n" + }, + { + "textRaw": "exports", + "name": "exports", + "type": "var", + "desc": "

An object which is shared between all instances of the current module and\nmade accessible through require().\nexports is the same as the module.exports object.\nexports isn't actually a global but rather local to each module.\n\n

\n

See the [module system documentation][] for more information.\n\n

\n

See the [module section][] for more information.\n\n

\n" + } + ], + "methods": [ + { + "textRaw": "setTimeout(cb, ms)", + "type": "method", + "name": "setTimeout", + "desc": "

Run callback cb after at least ms milliseconds. The actual delay depends\non external factors like OS timer granularity and system load.\n\n

\n

The timeout must be in the range of 1-2,147,483,647 inclusive. If the value is\noutside that range, it's changed to 1 millisecond. Broadly speaking, a timer\ncannot span more than 24.8 days.\n\n

\n

Returns an opaque value that represents the timer.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "cb" + }, + { + "name": "ms" + } + ] + } + ] + }, + { + "textRaw": "clearTimeout(t)", + "type": "method", + "name": "clearTimeout", + "desc": "

Stop a timer that was previously created with setTimeout(). The callback will\nnot execute.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "t" + } + ] + } + ] + }, + { + "textRaw": "setInterval(cb, ms)", + "type": "method", + "name": "setInterval", + "desc": "

Run callback cb repeatedly every ms milliseconds. Note that the actual\ninterval may vary, depending on external factors like OS timer granularity and\nsystem load. It's never less than ms but it may be longer.\n\n

\n

The interval must be in the range of 1-2,147,483,647 inclusive. If the value is\noutside that range, it's changed to 1 millisecond. Broadly speaking, a timer\ncannot span more than 24.8 days.\n\n

\n

Returns an opaque value that represents the timer.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "cb" + }, + { + "name": "ms" + } + ] + } + ] + } + ], + "modules": [ + { + "textRaw": "Timers", + "name": "timers", + "stability": 5, + "stabilityText": "Locked", + "desc": "

All of the timer functions are globals. You do not need to require()\nthis module in order to use them.\n\n

\n", + "methods": [ + { + "textRaw": "setTimeout(callback, delay, [arg], [...])", + "type": "method", + "name": "setTimeout", + "desc": "

To schedule execution of a one-time callback after delay milliseconds. Returns a\ntimeoutId for possible use with clearTimeout(). Optionally you can\nalso pass arguments to the callback.\n\n

\n

It is important to note that your callback will probably not be called in exactly\ndelay milliseconds - Node.js makes no guarantees about the exact timing of when\nthe callback will fire, nor of the ordering things will fire in. The callback will\nbe called as close as possible to the time specified.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "callback" + }, + { + "name": "delay" + }, + { + "name": "arg", + "optional": true + }, + { + "name": "...", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "clearTimeout(timeoutId)", + "type": "method", + "name": "clearTimeout", + "desc": "

Prevents a timeout from triggering.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "timeoutId" + } + ] + } + ] + }, + { + "textRaw": "setInterval(callback, delay, [arg], [...])", + "type": "method", + "name": "setInterval", + "desc": "

To schedule the repeated execution of callback every delay milliseconds.\nReturns a intervalId for possible use with clearInterval(). Optionally\nyou can also pass arguments to the callback.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "callback" + }, + { + "name": "delay" + }, + { + "name": "arg", + "optional": true + }, + { + "name": "...", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "clearInterval(intervalId)", + "type": "method", + "name": "clearInterval", + "desc": "

Stops a interval from triggering.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "intervalId" + } + ] + } + ] + } + ], + "type": "module", + "displayName": "Timers" + }, + { + "textRaw": "Modules", + "name": "module", + "stability": 5, + "stabilityText": "Locked", + "desc": "

Node has a simple module loading system. In Node, files and modules are in\none-to-one correspondence. As an example, foo.js loads the module\ncircle.js in the same directory.\n\n

\n

The contents of foo.js:\n\n

\n
var circle = require('./circle.js');\nconsole.log( 'The area of a circle of radius 4 is '\n           + circle.area(4));
\n

The contents of circle.js:\n\n

\n
var PI = Math.PI;\n\nexports.area = function (r) {\n  return PI * r * r;\n};\n\nexports.circumference = function (r) {\n  return 2 * PI * r;\n};
\n

The module circle.js has exported the functions area() and\ncircumference(). To export an object, add to the special exports\nobject.\n\n

\n

Variables\nlocal to the module will be private. In this example the variable PI is\nprivate to circle.js.\n\n

\n

The module system is implemented in the require("module") module.\n\n

\n", + "miscs": [ + { + "textRaw": "Cycles", + "name": "Cycles", + "type": "misc", + "desc": "

When there are circular require() calls, a module might not be\ndone being executed when it is returned.\n\n

\n

Consider this situation:\n\n

\n

a.js:\n\n

\n
console.log('a starting');\nexports.done = false;\nvar b = require('./b.js');\nconsole.log('in a, b.done = %j', b.done);\nexports.done = true;\nconsole.log('a done');
\n

b.js:\n\n

\n
console.log('b starting');\nexports.done = false;\nvar a = require('./a.js');\nconsole.log('in b, a.done = %j', a.done);\nexports.done = true;\nconsole.log('b done');
\n

main.js:\n\n

\n
console.log('main starting');\nvar a = require('./a.js');\nvar b = require('./b.js');\nconsole.log('in main, a.done=%j, b.done=%j', a.done, b.done);
\n

When main.js loads a.js, then a.js in turn loads b.js. At that\npoint, b.js tries to load a.js. In order to prevent an infinite\nloop an unfinished copy of the a.js exports object is returned to the\nb.js module. b.js then finishes loading, and its exports object is\nprovided to the a.js module.\n\n

\n

By the time main.js has loaded both modules, they're both finished.\nThe output of this program would thus be:\n\n

\n
$ node main.js\nmain starting\na starting\nb starting\nin b, a.done = false\nb done\nin a, b.done = true\na done\nin main, a.done=true, b.done=true
\n

If you have cyclic module dependencies in your program, make sure to\nplan accordingly.\n\n

\n" + }, + { + "textRaw": "Core Modules", + "name": "Core Modules", + "type": "misc", + "desc": "

Node has several modules compiled into the binary. These modules are\ndescribed in greater detail elsewhere in this documentation.\n\n

\n

The core modules are defined in node's source in the lib/ folder.\n\n

\n

Core modules are always preferentially loaded if their identifier is\npassed to require(). For instance, require('http') will always\nreturn the built in HTTP module, even if there is a file by that name.\n\n

\n" + }, + { + "textRaw": "File Modules", + "name": "File Modules", + "type": "misc", + "desc": "

If the exact filename is not found, then node will attempt to load the\nrequired filename with the added extension of .js, .json, and then .node.\n\n

\n

.js files are interpreted as JavaScript text files, and .json files are\nparsed as JSON text files. .node files are interpreted as compiled addon\nmodules loaded with dlopen.\n\n

\n

A module prefixed with '/' is an absolute path to the file. For\nexample, require('/home/marco/foo.js') will load the file at\n/home/marco/foo.js.\n\n

\n

A module prefixed with './' is relative to the file calling require().\nThat is, circle.js must be in the same directory as foo.js for\nrequire('./circle') to find it.\n\n

\n

Without a leading '/' or './' to indicate a file, the module is either a\n"core module" or is loaded from a node_modules folder.\n\n

\n

If the given path does not exist, require() will throw an Error with its\ncode property set to 'MODULE_NOT_FOUND'.\n\n

\n" + }, + { + "textRaw": "Loading from `node_modules` Folders", + "name": "Loading from `node_modules` Folders", + "type": "misc", + "desc": "

If the module identifier passed to require() is not a native module,\nand does not begin with '/', '../', or './', then node starts at the\nparent directory of the current module, and adds /node_modules, and\nattempts to load the module from that location.\n\n

\n

If it is not found there, then it moves to the parent directory, and so\non, until the root of the tree is reached.\n\n

\n

For example, if the file at '/home/ry/projects/foo.js' called\nrequire('bar.js'), then node would look in the following locations, in\nthis order:\n\n

\n
    \n
  • /home/ry/projects/node_modules/bar.js
  • \n
  • /home/ry/node_modules/bar.js
  • \n
  • /home/node_modules/bar.js
  • \n
  • /node_modules/bar.js
  • \n
\n

This allows programs to localize their dependencies, so that they do not\nclash.\n\n

\n" + }, + { + "textRaw": "Folders as Modules", + "name": "Folders as Modules", + "type": "misc", + "desc": "

It is convenient to organize programs and libraries into self-contained\ndirectories, and then provide a single entry point to that library.\nThere are three ways in which a folder may be passed to require() as\nan argument.\n\n

\n

The first is to create a package.json file in the root of the folder,\nwhich specifies a main module. An example package.json file might\nlook like this:\n\n

\n
{ "name" : "some-library",\n  "main" : "./lib/some-library.js" }
\n

If this was in a folder at ./some-library, then\nrequire('./some-library') would attempt to load\n./some-library/lib/some-library.js.\n\n

\n

This is the extent of Node's awareness of package.json files.\n\n

\n

If there is no package.json file present in the directory, then node\nwill attempt to load an index.js or index.node file out of that\ndirectory. For example, if there was no package.json file in the above\nexample, then require('./some-library') would attempt to load:\n\n

\n
    \n
  • ./some-library/index.js
  • \n
  • ./some-library/index.node
  • \n
\n" + }, + { + "textRaw": "Caching", + "name": "Caching", + "type": "misc", + "desc": "

Modules are cached after the first time they are loaded. This means\n(among other things) that every call to require('foo') will get\nexactly the same object returned, if it would resolve to the same file.\n\n

\n

Multiple calls to require('foo') may not cause the module code to be\nexecuted multiple times. This is an important feature. With it,\n"partially done" objects can be returned, thus allowing transitive\ndependencies to be loaded even when they would cause cycles.\n\n

\n

If you want to have a module execute code multiple times, then export a\nfunction, and call that function.\n\n

\n", + "miscs": [ + { + "textRaw": "Module Caching Caveats", + "name": "Module Caching Caveats", + "type": "misc", + "desc": "

Modules are cached based on their resolved filename. Since modules may\nresolve to a different filename based on the location of the calling\nmodule (loading from node_modules folders), it is not a guarantee\nthat require('foo') will always return the exact same object, if it\nwould resolve to different files.\n\n

\n" + } + ] + }, + { + "textRaw": "All Together...", + "name": "All Together...", + "type": "misc", + "desc": "

To get the exact filename that will be loaded when require() is called, use\nthe require.resolve() function.\n\n

\n

Putting together all of the above, here is the high-level algorithm\nin pseudocode of what require.resolve does:\n\n

\n
require(X) from module at path Y\n1. If X is a core module,\n   a. return the core module\n   b. STOP\n2. If X begins with './' or '/' or '../'\n   a. LOAD_AS_FILE(Y + X)\n   b. LOAD_AS_DIRECTORY(Y + X)\n3. LOAD_NODE_MODULES(X, dirname(Y))\n4. THROW "not found"\n\nLOAD_AS_FILE(X)\n1. If X is a file, load X as JavaScript text.  STOP\n2. If X.js is a file, load X.js as JavaScript text.  STOP\n3. If X.node is a file, load X.node as binary addon.  STOP\n\nLOAD_AS_DIRECTORY(X)\n1. If X/package.json is a file,\n   a. Parse X/package.json, and look for "main" field.\n   b. let M = X + (json main field)\n   c. LOAD_AS_FILE(M)\n2. If X/index.js is a file, load X/index.js as JavaScript text.  STOP\n3. If X/index.node is a file, load X/index.node as binary addon.  STOP\n\nLOAD_NODE_MODULES(X, START)\n1. let DIRS=NODE_MODULES_PATHS(START)\n2. for each DIR in DIRS:\n   a. LOAD_AS_FILE(DIR/X)\n   b. LOAD_AS_DIRECTORY(DIR/X)\n\nNODE_MODULES_PATHS(START)\n1. let PARTS = path split(START)\n2. let ROOT = index of first instance of "node_modules" in PARTS, or 0\n3. let I = count of PARTS - 1\n4. let DIRS = []\n5. while I > ROOT,\n   a. if PARTS[I] = "node_modules" CONTINUE\n   c. DIR = path join(PARTS[0 .. I] + "node_modules")\n   b. DIRS = DIRS + DIR\n   c. let I = I - 1\n6. return DIRS
\n" + }, + { + "textRaw": "Loading from the global folders", + "name": "Loading from the global folders", + "type": "misc", + "desc": "

If the NODE_PATH environment variable is set to a colon-delimited list\nof absolute paths, then node will search those paths for modules if they\nare not found elsewhere. (Note: On Windows, NODE_PATH is delimited by\nsemicolons instead of colons.)\n\n

\n

Additionally, node will search in the following locations:\n\n

\n
    \n
  • 1: $HOME/.node_modules
  • \n
  • 2: $HOME/.node_libraries
  • \n
  • 3: $PREFIX/lib/node
  • \n
\n

Where $HOME is the user's home directory, and $PREFIX is node's\nconfigured node_prefix.\n\n

\n

These are mostly for historic reasons. You are highly encouraged to\nplace your dependencies locally in node_modules folders. They will be\nloaded faster, and more reliably.\n\n

\n" + }, + { + "textRaw": "Accessing the main module", + "name": "Accessing the main module", + "type": "misc", + "desc": "

When a file is run directly from Node, require.main is set to its\nmodule. That means that you can determine whether a file has been run\ndirectly by testing\n\n

\n
require.main === module
\n

For a file foo.js, this will be true if run via node foo.js, but\nfalse if run by require('./foo').\n\n

\n

Because module provides a filename property (normally equivalent to\n__filename), the entry point of the current application can be obtained\nby checking require.main.filename.\n\n

\n" + }, + { + "textRaw": "Addenda: Package Manager Tips", + "name": "Addenda: Package Manager Tips", + "type": "misc", + "desc": "

The semantics of Node's require() function were designed to be general\nenough to support a number of sane directory structures. Package manager\nprograms such as dpkg, rpm, and npm will hopefully find it possible to\nbuild native packages from Node modules without modification.\n\n

\n

Below we give a suggested directory structure that could work:\n\n

\n

Let's say that we wanted to have the folder at\n/usr/lib/node/<some-package>/<some-version> hold the contents of a\nspecific version of a package.\n\n

\n

Packages can depend on one another. In order to install package foo, you\nmay have to install a specific version of package bar. The bar package\nmay itself have dependencies, and in some cases, these dependencies may even\ncollide or form cycles.\n\n

\n

Since Node looks up the realpath of any modules it loads (that is,\nresolves symlinks), and then looks for their dependencies in the\nnode_modules folders as described above, this situation is very simple to\nresolve with the following architecture:\n\n

\n
    \n
  • /usr/lib/node/foo/1.2.3/ - Contents of the foo package, version 1.2.3.
  • \n
  • /usr/lib/node/bar/4.3.2/ - Contents of the bar package that foo\ndepends on.
  • \n
  • /usr/lib/node/foo/1.2.3/node_modules/bar - Symbolic link to\n/usr/lib/node/bar/4.3.2/.
  • \n
  • /usr/lib/node/bar/4.3.2/node_modules/* - Symbolic links to the packages\nthat bar depends on.
  • \n
\n

Thus, even if a cycle is encountered, or if there are dependency\nconflicts, every module will be able to get a version of its dependency\nthat it can use.\n\n

\n

When the code in the foo package does require('bar'), it will get the\nversion that is symlinked into /usr/lib/node/foo/1.2.3/node_modules/bar.\nThen, when the code in the bar package calls require('quux'), it'll get\nthe version that is symlinked into\n/usr/lib/node/bar/4.3.2/node_modules/quux.\n\n

\n

Furthermore, to make the module lookup process even more optimal, rather\nthan putting packages directly in /usr/lib/node, we could put them in\n/usr/lib/node_modules/<name>/<version>. Then node will not bother\nlooking for missing dependencies in /usr/node_modules or /node_modules.\n\n

\n

In order to make modules available to the node REPL, it might be useful to\nalso add the /usr/lib/node_modules folder to the $NODE_PATH environment\nvariable. Since the module lookups using node_modules folders are all\nrelative, and based on the real path of the files making the calls to\nrequire(), the packages themselves can be anywhere.\n\n

\n" + } + ], + "vars": [ + { + "textRaw": "The `module` Object", + "name": "module", + "type": "var", + "desc": "

In each module, the module free variable is a reference to the object\nrepresenting the current module. In particular\nmodule.exports is the same as the exports object.\nmodule isn't actually a global but rather local to each module.\n\n

\n", + "properties": [ + { + "textRaw": "`exports` {Object} ", + "name": "exports", + "desc": "

The exports object is created by the Module system. Sometimes this is not\nacceptable, many want their module to be an instance of some class. To do this\nassign the desired export object to module.exports. For example suppose we\nwere making a module called a.js\n\n

\n
var EventEmitter = require('events').EventEmitter;\n\nmodule.exports = new EventEmitter();\n\n// Do some work, and after some time emit\n// the 'ready' event from the module itself.\nsetTimeout(function() {\n  module.exports.emit('ready');\n}, 1000);
\n

Then in another file we could do\n\n

\n
var a = require('./a');\na.on('ready', function() {\n  console.log('module a is ready');\n});
\n

Note that assignment to module.exports must be done immediately. It cannot be\ndone in any callbacks. This does not work:\n\n

\n

x.js:\n\n

\n
setTimeout(function() {\n  module.exports = { a: "hello" };\n}, 0);
\n

y.js:\n\n

\n
var x = require('./x');\nconsole.log(x.a);
\n" + }, + { + "textRaw": "`id` {String} ", + "name": "id", + "desc": "

The identifier for the module. Typically this is the fully resolved\nfilename.\n\n\n

\n" + }, + { + "textRaw": "`filename` {String} ", + "name": "filename", + "desc": "

The fully resolved filename to the module.\n\n\n

\n" + }, + { + "textRaw": "`loaded` {Boolean} ", + "name": "loaded", + "desc": "

Whether or not the module is done loading, or is in the process of\nloading.\n\n\n

\n" + }, + { + "textRaw": "`parent` {Module Object} ", + "name": "parent", + "desc": "

The module that required this one.\n\n\n

\n" + }, + { + "textRaw": "`children` {Array} ", + "name": "children", + "desc": "

The module objects required by this one.\n\n\n\n

\n" + } + ], + "methods": [ + { + "textRaw": "module.require(id)", + "type": "method", + "name": "require", + "signatures": [ + { + "return": { + "textRaw": "Return: {Object} `exports` from the resolved module ", + "name": "return", + "type": "Object", + "desc": "`exports` from the resolved module" + }, + "params": [ + { + "textRaw": "`id` {String} ", + "name": "id", + "type": "String" + } + ] + }, + { + "params": [ + { + "name": "id" + } + ] + } + ], + "desc": "

The module.require method provides a way to load a module as if\nrequire() was called from the original module.\n\n

\n

Note that in order to do this, you must get a reference to the module\nobject. Since require() returns the exports, and the module is\ntypically only available within a specific module's code, it must be\nexplicitly exported in order to be used.\n\n\n

\n" + } + ] + } + ], + "type": "module", + "displayName": "module" + }, + { + "textRaw": "Addons", + "name": "addons", + "desc": "

Addons are dynamically linked shared objects. They can provide glue to C and\nC++ libraries. The API (at the moment) is rather complex, involving\nknowledge of several libraries:\n\n

\n
    \n
  • V8 JavaScript, a C++ library. Used for interfacing with JavaScript:\ncreating objects, calling functions, etc. Documented mostly in the\nv8.h header file (deps/v8/include/v8.h in the Node source tree),\nwhich is also available online.

    \n
  • \n
  • libuv, C event loop library. Anytime one\nneeds to wait for a file descriptor to become readable, wait for a timer, or\nwait for a signal to received one will need to interface with libuv. That is,\nif you perform any I/O, libuv will need to be used.

    \n
  • \n
  • Internal Node libraries. Most importantly is the node::ObjectWrap\nclass which you will likely want to derive from.

    \n
  • \n
  • Others. Look in deps/ for what else is available.

    \n
  • \n
\n

Node statically compiles all its dependencies into the executable. When\ncompiling your module, you don't need to worry about linking to any of these\nlibraries.\n\n\n

\n", + "modules": [ + { + "textRaw": "Hello world", + "name": "hello_world", + "desc": "

To get started let's make a small Addon which is the C++ equivalent of\nthe following JavaScript code:\n\n

\n
exports.hello = function() { return 'world'; };
\n

First we create a file hello.cc:\n\n

\n
#include <node.h>\n#include <v8.h>\n\nusing namespace v8;\n\nHandle<Value> Method(const Arguments& args) {\n  HandleScope scope;\n  return scope.Close(String::New("world"));\n}\n\nvoid init(Handle<Object> target) {\n  target->Set(String::NewSymbol("hello"),\n      FunctionTemplate::New(Method)->GetFunction());\n}\nNODE_MODULE(hello, init)
\n

Note that all Node addons must export an initialization function:\n\n

\n
void Initialize (Handle<Object> target);\nNODE_MODULE(module_name, Initialize)
\n

There is no semi-colon after NODE_MODULE as it's not a function (see node.h).\n\n

\n

The module_name needs to match the filename of the final binary (minus the\n.node suffix).\n\n

\n

The source code needs to be built into hello.node, the binary Addon. To\ndo this we create a file called binding.gyp which describes the configuration\nto build your module in a JSON-like format. This file gets compiled by\nnode-gyp.\n\n

\n
{\n  "targets": [\n    {\n      "target_name": "hello",\n      "sources": [ "hello.cc" ]\n    }\n  ]\n}
\n

The next step is to generate the appropriate project build files for the\ncurrent platform. Use node-gyp configure for that.\n\n

\n

Now you will have either a Makefile (on Unix platforms) or a vcxproj file\n(on Windows) in the build/ directory. Next invoke the node-gyp build\ncommand.\n\n

\n

Now you have your compiled .node bindings file! The compiled bindings end up\nin build/Release/.\n\n

\n

You can now use the binary addon in a Node project hello.js by pointing require to\nthe recently built hello.node module:\n\n

\n
var addon = require('./build/Release/hello');\n\nconsole.log(addon.hello()); // 'world'
\n

Please see patterns below for further information or\n

\n

https://github.com/arturadib/node-qt for an example in production.\n\n\n

\n", + "type": "module", + "displayName": "Hello world" + }, + { + "textRaw": "Addon patterns", + "name": "addon_patterns", + "desc": "

Below are some addon patterns to help you get started. Consult the online\nv8 reference for help with the various v8\ncalls, and v8's Embedder's Guide\nfor an explanation of several concepts used such as handles, scopes,\nfunction templates, etc.\n\n

\n

In order to use these examples you need to compile them using node-gyp.\nCreate the following binding.gyp file:\n\n

\n
{\n  "targets": [\n    {\n      "target_name": "addon",\n      "sources": [ "addon.cc" ]\n    }\n  ]\n}
\n

In cases where there is more than one .cc file, simply add the file name to the\nsources array, e.g.:\n\n

\n
"sources": ["addon.cc", "myexample.cc"]
\n

Now that you have your binding.gyp ready, you can configure and build the\naddon:\n\n

\n
$ node-gyp configure build
\n", + "modules": [ + { + "textRaw": "Function arguments", + "name": "function_arguments", + "desc": "

The following pattern illustrates how to read arguments from JavaScript\nfunction calls and return a result. This is the main and only needed source\naddon.cc:\n\n

\n
#define BUILDING_NODE_EXTENSION\n#include <node.h>\n\nusing namespace v8;\n\nHandle<Value> Add(const Arguments& args) {\n  HandleScope scope;\n\n  if (args.Length() < 2) {\n    ThrowException(Exception::TypeError(String::New("Wrong number of arguments")));\n    return scope.Close(Undefined());\n  }\n\n  if (!args[0]->IsNumber() || !args[1]->IsNumber()) {\n    ThrowException(Exception::TypeError(String::New("Wrong arguments")));\n    return scope.Close(Undefined());\n  }\n\n  Local<Number> num = Number::New(args[0]->NumberValue() +\n      args[1]->NumberValue());\n  return scope.Close(num);\n}\n\nvoid Init(Handle<Object> target) {\n  target->Set(String::NewSymbol("add"),\n      FunctionTemplate::New(Add)->GetFunction());\n}\n\nNODE_MODULE(addon, Init)
\n

You can test it with the following JavaScript snippet:\n\n

\n
var addon = require('./build/Release/addon');\n\nconsole.log( 'This should be eight:', addon.add(3,5) );
\n", + "type": "module", + "displayName": "Function arguments" + }, + { + "textRaw": "Callbacks", + "name": "callbacks", + "desc": "

You can pass JavaScript functions to a C++ function and execute them from\nthere. Here's addon.cc:\n\n

\n
#define BUILDING_NODE_EXTENSION\n#include <node.h>\n\nusing namespace v8;\n\nHandle<Value> RunCallback(const Arguments& args) {\n  HandleScope scope;\n\n  Local<Function> cb = Local<Function>::Cast(args[0]);\n  const unsigned argc = 1;\n  Local<Value> argv[argc] = { Local<Value>::New(String::New("hello world")) };\n  cb->Call(Context::GetCurrent()->Global(), argc, argv);\n\n  return scope.Close(Undefined());\n}\n\nvoid Init(Handle<Object> target) {\n  target->Set(String::NewSymbol("runCallback"),\n      FunctionTemplate::New(RunCallback)->GetFunction());\n}\n\nNODE_MODULE(addon, Init)
\n

To test it run the following JavaScript snippet:\n\n

\n
var addon = require('./build/Release/addon');\n\naddon.runCallback(function(msg){\n  console.log(msg); // 'hello world'\n});
\n", + "type": "module", + "displayName": "Callbacks" + }, + { + "textRaw": "Object factory", + "name": "object_factory", + "desc": "

You can create and return new objects from within a C++ function with this\naddon.cc pattern, which returns an object with property msg that echoes\nthe string passed to createObject():\n\n

\n
#define BUILDING_NODE_EXTENSION\n#include <node.h>\n\nusing namespace v8;\n\nHandle<Value> CreateObject(const Arguments& args) {\n  HandleScope scope;\n\n  Local<Object> obj = Object::New();\n  obj->Set(String::NewSymbol("msg"), args[0]->ToString());\n\n  return scope.Close(obj);\n}\n\nvoid Init(Handle<Object> target) {\n  target->Set(String::NewSymbol("createObject"),\n      FunctionTemplate::New(CreateObject)->GetFunction());\n}\n\nNODE_MODULE(addon, Init)
\n

To test it in JavaScript:\n\n

\n
var addon = require('./build/Release/addon');\n\nvar obj1 = addon.createObject('hello');\nvar obj2 = addon.createObject('world');\nconsole.log(obj1.msg+' '+obj2.msg); // 'hello world'
\n", + "type": "module", + "displayName": "Object factory" + }, + { + "textRaw": "Function factory", + "name": "function_factory", + "desc": "

This pattern illustrates how to create and return a JavaScript function that\nwraps a C++ function:\n\n

\n
#define BUILDING_NODE_EXTENSION\n#include <node.h>\n\nusing namespace v8;\n\nHandle<Value> MyFunction(const Arguments& args) {\n  HandleScope scope;\n  return scope.Close(String::New("hello world"));\n}\n\nHandle<Value> CreateFunction(const Arguments& args) {\n  HandleScope scope;\n\n  Local<FunctionTemplate> tpl = FunctionTemplate::New(MyFunction);\n  Local<Function> fn = tpl->GetFunction();\n  fn->SetName(String::NewSymbol("theFunction")); // omit this to make it anonymous\n\n  return scope.Close(fn);\n}\n\nvoid Init(Handle<Object> target) {\n  target->Set(String::NewSymbol("createFunction"),\n      FunctionTemplate::New(CreateFunction)->GetFunction());\n}\n\nNODE_MODULE(addon, Init)
\n

To test:\n\n

\n
var addon = require('./build/Release/addon');\n\nvar fn = addon.createFunction();\nconsole.log(fn()); // 'hello world'
\n", + "type": "module", + "displayName": "Function factory" + }, + { + "textRaw": "Wrapping C++ objects", + "name": "wrapping_c++_objects", + "desc": "

Here we will create a wrapper for a C++ object/class MyObject that can be\ninstantiated in JavaScript through the new operator. First prepare the main\nmodule addon.cc:\n\n

\n
#define BUILDING_NODE_EXTENSION\n#include <node.h>\n#include "myobject.h"\n\nusing namespace v8;\n\nvoid InitAll(Handle<Object> target) {\n  MyObject::Init(target);\n}\n\nNODE_MODULE(addon, InitAll)
\n

Then in myobject.h make your wrapper inherit from node::ObjectWrap:\n\n

\n
#ifndef MYOBJECT_H\n#define MYOBJECT_H\n\n#include <node.h>\n\nclass MyObject : public node::ObjectWrap {\n public:\n  static void Init(v8::Handle<v8::Object> target);\n\n private:\n  MyObject();\n  ~MyObject();\n\n  static v8::Handle<v8::Value> New(const v8::Arguments& args);\n  static v8::Handle<v8::Value> PlusOne(const v8::Arguments& args);\n  double counter_;\n};\n\n#endif
\n

And in myobject.cc implement the various methods that you want to expose.\nHere we expose the method plusOne by adding it to the constructor's\nprototype:\n\n

\n
#define BUILDING_NODE_EXTENSION\n#include <node.h>\n#include "myobject.h"\n\nusing namespace v8;\n\nMyObject::MyObject() {};\nMyObject::~MyObject() {};\n\nvoid MyObject::Init(Handle<Object> target) {\n  // Prepare constructor template\n  Local<FunctionTemplate> tpl = FunctionTemplate::New(New);\n  tpl->SetClassName(String::NewSymbol("MyObject"));\n  tpl->InstanceTemplate()->SetInternalFieldCount(1);\n  // Prototype\n  tpl->PrototypeTemplate()->Set(String::NewSymbol("plusOne"),\n      FunctionTemplate::New(PlusOne)->GetFunction());\n\n  Persistent<Function> constructor = Persistent<Function>::New(tpl->GetFunction());\n  target->Set(String::NewSymbol("MyObject"), constructor);\n}\n\nHandle<Value> MyObject::New(const Arguments& args) {\n  HandleScope scope;\n\n  MyObject* obj = new MyObject();\n  obj->counter_ = args[0]->IsUndefined() ? 0 : args[0]->NumberValue();\n  obj->Wrap(args.This());\n\n  return args.This();\n}\n\nHandle<Value> MyObject::PlusOne(const Arguments& args) {\n  HandleScope scope;\n\n  MyObject* obj = ObjectWrap::Unwrap<MyObject>(args.This());\n  obj->counter_ += 1;\n\n  return scope.Close(Number::New(obj->counter_));\n}
\n

Test it with:\n\n

\n
var addon = require('./build/Release/addon');\n\nvar obj = new addon.MyObject(10);\nconsole.log( obj.plusOne() ); // 11\nconsole.log( obj.plusOne() ); // 12\nconsole.log( obj.plusOne() ); // 13
\n", + "type": "module", + "displayName": "Wrapping C++ objects" + }, + { + "textRaw": "Factory of wrapped objects", + "name": "factory_of_wrapped_objects", + "desc": "

This is useful when you want to be able to create native objects without\nexplicitly instantiating them with the new operator in JavaScript, e.g.\n\n

\n
var obj = addon.createObject();\n// instead of:\n// var obj = new addon.Object();
\n

Let's register our createObject method in addon.cc:\n\n

\n
#define BUILDING_NODE_EXTENSION\n#include <node.h>\n#include "myobject.h"\n\nusing namespace v8;\n\nHandle<Value> CreateObject(const Arguments& args) {\n  HandleScope scope;\n  return scope.Close(MyObject::NewInstance(args));\n}\n\nvoid InitAll(Handle<Object> target) {\n  MyObject::Init();\n\n  target->Set(String::NewSymbol("createObject"),\n      FunctionTemplate::New(CreateObject)->GetFunction());\n}\n\nNODE_MODULE(addon, InitAll)
\n

In myobject.h we now introduce the static method NewInstance that takes\ncare of instantiating the object (i.e. it does the job of new in JavaScript):\n\n

\n
#define BUILDING_NODE_EXTENSION\n#ifndef MYOBJECT_H\n#define MYOBJECT_H\n\n#include <node.h>\n\nclass MyObject : public node::ObjectWrap {\n public:\n  static void Init();\n  static v8::Handle<v8::Value> NewInstance(const v8::Arguments& args);\n\n private:\n  MyObject();\n  ~MyObject();\n\n  static v8::Persistent<v8::Function> constructor;\n  static v8::Handle<v8::Value> New(const v8::Arguments& args);\n  static v8::Handle<v8::Value> PlusOne(const v8::Arguments& args);\n  double counter_;\n};\n\n#endif
\n

The implementation is similar to the above in myobject.cc:\n\n

\n
#define BUILDING_NODE_EXTENSION\n#include <node.h>\n#include "myobject.h"\n\nusing namespace v8;\n\nMyObject::MyObject() {};\nMyObject::~MyObject() {};\n\nPersistent<Function> MyObject::constructor;\n\nvoid MyObject::Init() {\n  // Prepare constructor template\n  Local<FunctionTemplate> tpl = FunctionTemplate::New(New);\n  tpl->SetClassName(String::NewSymbol("MyObject"));\n  tpl->InstanceTemplate()->SetInternalFieldCount(1);\n  // Prototype\n  tpl->PrototypeTemplate()->Set(String::NewSymbol("plusOne"),\n      FunctionTemplate::New(PlusOne)->GetFunction());\n\n  constructor = Persistent<Function>::New(tpl->GetFunction());\n}\n\nHandle<Value> MyObject::New(const Arguments& args) {\n  HandleScope scope;\n\n  MyObject* obj = new MyObject();\n  obj->counter_ = args[0]->IsUndefined() ? 0 : args[0]->NumberValue();\n  obj->Wrap(args.This());\n\n  return args.This();\n}\n\nHandle<Value> MyObject::NewInstance(const Arguments& args) {\n  HandleScope scope;\n\n  const unsigned argc = 1;\n  Handle<Value> argv[argc] = { args[0] };\n  Local<Object> instance = constructor->NewInstance(argc, argv);\n\n  return scope.Close(instance);\n}\n\nHandle<Value> MyObject::PlusOne(const Arguments& args) {\n  HandleScope scope;\n\n  MyObject* obj = ObjectWrap::Unwrap<MyObject>(args.This());\n  obj->counter_ += 1;\n\n  return scope.Close(Number::New(obj->counter_));\n}
\n

Test it with:\n\n

\n
var addon = require('./build/Release/addon');\n\nvar obj = addon.createObject(10);\nconsole.log( obj.plusOne() ); // 11\nconsole.log( obj.plusOne() ); // 12\nconsole.log( obj.plusOne() ); // 13\n\nvar obj2 = addon.createObject(20);\nconsole.log( obj2.plusOne() ); // 21\nconsole.log( obj2.plusOne() ); // 22\nconsole.log( obj2.plusOne() ); // 23
\n", + "type": "module", + "displayName": "Factory of wrapped objects" + }, + { + "textRaw": "Passing wrapped objects around", + "name": "passing_wrapped_objects_around", + "desc": "

In addition to wrapping and returning C++ objects, you can pass them around\nby unwrapping them with Node's node::ObjectWrap::Unwrap helper function.\nIn the following addon.cc we introduce a function add() that can take on two\nMyObject objects:\n\n

\n
#define BUILDING_NODE_EXTENSION\n#include <node.h>\n#include "myobject.h"\n\nusing namespace v8;\n\nHandle<Value> CreateObject(const Arguments& args) {\n  HandleScope scope;\n  return scope.Close(MyObject::NewInstance(args));\n}\n\nHandle<Value> Add(const Arguments& args) {\n  HandleScope scope;\n\n  MyObject* obj1 = node::ObjectWrap::Unwrap<MyObject>(\n      args[0]->ToObject());\n  MyObject* obj2 = node::ObjectWrap::Unwrap<MyObject>(\n      args[1]->ToObject());\n\n  double sum = obj1->Val() + obj2->Val();\n  return scope.Close(Number::New(sum));\n}\n\nvoid InitAll(Handle<Object> target) {\n  MyObject::Init();\n\n  target->Set(String::NewSymbol("createObject"),\n      FunctionTemplate::New(CreateObject)->GetFunction());\n\n  target->Set(String::NewSymbol("add"),\n      FunctionTemplate::New(Add)->GetFunction());\n}\n\nNODE_MODULE(addon, InitAll)
\n

To make things interesting we introduce a public method in myobject.h so we\ncan probe private values after unwrapping the object:\n\n

\n
#define BUILDING_NODE_EXTENSION\n#ifndef MYOBJECT_H\n#define MYOBJECT_H\n\n#include <node.h>\n\nclass MyObject : public node::ObjectWrap {\n public:\n  static void Init();\n  static v8::Handle<v8::Value> NewInstance(const v8::Arguments& args);\n  double Val() const { return val_; }\n\n private:\n  MyObject();\n  ~MyObject();\n\n  static v8::Persistent<v8::Function> constructor;\n  static v8::Handle<v8::Value> New(const v8::Arguments& args);\n  double val_;\n};\n\n#endif
\n

The implementation of myobject.cc is similar as before:\n\n

\n
#define BUILDING_NODE_EXTENSION\n#include <node.h>\n#include "myobject.h"\n\nusing namespace v8;\n\nMyObject::MyObject() {};\nMyObject::~MyObject() {};\n\nPersistent<Function> MyObject::constructor;\n\nvoid MyObject::Init() {\n  // Prepare constructor template\n  Local<FunctionTemplate> tpl = FunctionTemplate::New(New);\n  tpl->SetClassName(String::NewSymbol("MyObject"));\n  tpl->InstanceTemplate()->SetInternalFieldCount(1);\n\n  constructor = Persistent<Function>::New(tpl->GetFunction());\n}\n\nHandle<Value> MyObject::New(const Arguments& args) {\n  HandleScope scope;\n\n  MyObject* obj = new MyObject();\n  obj->val_ = args[0]->IsUndefined() ? 0 : args[0]->NumberValue();\n  obj->Wrap(args.This());\n\n  return args.This();\n}\n\nHandle<Value> MyObject::NewInstance(const Arguments& args) {\n  HandleScope scope;\n\n  const unsigned argc = 1;\n  Handle<Value> argv[argc] = { args[0] };\n  Local<Object> instance = constructor->NewInstance(argc, argv);\n\n  return scope.Close(instance);\n}
\n

Test it with:\n\n

\n
var addon = require('./build/Release/addon');\n\nvar obj1 = addon.createObject(10);\nvar obj2 = addon.createObject(20);\nvar result = addon.add(obj1, obj2);\n\nconsole.log(result); // 30
\n", + "type": "module", + "displayName": "Passing wrapped objects around" + } + ], + "type": "module", + "displayName": "Addon patterns" + } + ], + "type": "module", + "displayName": "Addons" + }, + { + "textRaw": "util", + "name": "util", + "stability": 5, + "stabilityText": "Locked", + "desc": "

These functions are in the module 'util'. Use require('util') to access\nthem.\n\n\n

\n", + "methods": [ + { + "textRaw": "util.format(format, [...])", + "type": "method", + "name": "format", + "desc": "

Returns a formatted string using the first argument as a printf-like format.\n\n

\n

The first argument is a string that contains zero or more placeholders.\nEach placeholder is replaced with the converted value from its corresponding\nargument. Supported placeholders are:\n\n

\n
    \n
  • %s - String.
  • \n
  • %d - Number (both integer and float).
  • \n
  • %j - JSON.
  • \n
  • % - single percent sign ('%'). This does not consume an argument.
  • \n
\n

If the placeholder does not have a corresponding argument, the placeholder is\nnot replaced.\n\n

\n
util.format('%s:%s', 'foo'); // 'foo:%s'
\n

If there are more arguments than placeholders, the extra arguments are\nconverted to strings with util.inspect() and these strings are concatenated,\ndelimited by a space.\n\n

\n
util.format('%s:%s', 'foo', 'bar', 'baz'); // 'foo:bar baz'
\n

If the first argument is not a format string then util.format() returns\na string that is the concatenation of all its arguments separated by spaces.\nEach argument is converted to a string with util.inspect().\n\n

\n
util.format(1, 2, 3); // '1 2 3'
\n", + "signatures": [ + { + "params": [ + { + "name": "format" + }, + { + "name": "...", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "util.debug(string)", + "type": "method", + "name": "debug", + "desc": "

A synchronous output function. Will block the process and\noutput string immediately to stderr.\n\n

\n
require('util').debug('message on stderr');
\n", + "signatures": [ + { + "params": [ + { + "name": "string" + } + ] + } + ] + }, + { + "textRaw": "util.error([...])", + "type": "method", + "name": "error", + "desc": "

Same as util.debug() except this will output all arguments immediately to\nstderr.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "...", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "util.puts([...])", + "type": "method", + "name": "puts", + "desc": "

A synchronous output function. Will block the process and output all arguments\nto stdout with newlines after each argument.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "...", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "util.print([...])", + "type": "method", + "name": "print", + "desc": "

A synchronous output function. Will block the process, cast each argument to a\nstring then output to stdout. Does not place newlines after each argument.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "...", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "util.log(string)", + "type": "method", + "name": "log", + "desc": "

Output with timestamp on stdout.\n\n

\n
require('util').log('Timestamped message.');
\n", + "signatures": [ + { + "params": [ + { + "name": "string" + } + ] + } + ] + }, + { + "textRaw": "util.inspect(object, [showHidden], [depth], [colors])", + "type": "method", + "name": "inspect", + "desc": "

Return a string representation of object, which is useful for debugging.\n\n

\n

If showHidden is true, then the object's non-enumerable properties will be\nshown too. Defaults to false.\n\n

\n

If depth is provided, it tells inspect how many times to recurse while\nformatting the object. This is useful for inspecting large complicated objects.\n\n

\n

The default is to only recurse twice. To make it recurse indefinitely, pass\nin null for depth.\n\n

\n

If colors is true, the output will be styled with ANSI color codes.\nDefaults to false.\n\n

\n

Example of inspecting all properties of the util object:\n\n

\n
var util = require('util');\n\nconsole.log(util.inspect(util, true, null));
\n

Objects also may define their own inspect(depth) function which util.inspect()\nwill invoke and use the result of when inspecting the object:\n\n

\n
var util = require('util');\n\nvar obj = { name: 'nate' };\nobj.inspect = function(depth) {\n  return '{' + this.name + '}';\n};\n\nutil.inspect(obj);\n  // "{nate}"
\n", + "signatures": [ + { + "params": [ + { + "name": "object" + }, + { + "name": "showHidden", + "optional": true + }, + { + "name": "depth", + "optional": true + }, + { + "name": "colors", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "util.isArray(object)", + "type": "method", + "name": "isArray", + "desc": "

Returns true if the given "object" is an Array. false otherwise.\n\n

\n
var util = require('util');\n\nutil.isArray([])\n  // true\nutil.isArray(new Array)\n  // true\nutil.isArray({})\n  // false
\n", + "signatures": [ + { + "params": [ + { + "name": "object" + } + ] + } + ] + }, + { + "textRaw": "util.isRegExp(object)", + "type": "method", + "name": "isRegExp", + "desc": "

Returns true if the given "object" is a RegExp. false otherwise.\n\n

\n
var util = require('util');\n\nutil.isRegExp(/some regexp/)\n  // true\nutil.isRegExp(new RegExp('another regexp'))\n  // true\nutil.isRegExp({})\n  // false
\n", + "signatures": [ + { + "params": [ + { + "name": "object" + } + ] + } + ] + }, + { + "textRaw": "util.isDate(object)", + "type": "method", + "name": "isDate", + "desc": "

Returns true if the given "object" is a Date. false otherwise.\n\n

\n
var util = require('util');\n\nutil.isDate(new Date())\n  // true\nutil.isDate(Date())\n  // false (without 'new' returns a String)\nutil.isDate({})\n  // false
\n", + "signatures": [ + { + "params": [ + { + "name": "object" + } + ] + } + ] + }, + { + "textRaw": "util.isError(object)", + "type": "method", + "name": "isError", + "desc": "

Returns true if the given "object" is an Error. false otherwise.\n\n

\n
var util = require('util');\n\nutil.isError(new Error())\n  // true\nutil.isError(new TypeError())\n  // true\nutil.isError({ name: 'Error', message: 'an error occurred' })\n  // false
\n", + "signatures": [ + { + "params": [ + { + "name": "object" + } + ] + } + ] + }, + { + "textRaw": "util.pump(readableStream, writableStream, [callback])", + "type": "method", + "name": "pump", + "stability": 0, + "stabilityText": "Deprecated: Use readableStream.pipe(writableStream)", + "desc": "

Read the data from readableStream and send it to the writableStream.\nWhen writableStream.write(data) returns false readableStream will be\npaused until the drain event occurs on the writableStream. callback gets\nan error as its only argument and is called when writableStream is closed or\nwhen an error occurs.\n\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "readableStream" + }, + { + "name": "writableStream" + }, + { + "name": "callback", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "util.inherits(constructor, superConstructor)", + "type": "method", + "name": "inherits", + "desc": "

Inherit the prototype methods from one\nconstructor\ninto another. The prototype of constructor will be set to a new\nobject created from superConstructor.\n\n

\n

As an additional convenience, superConstructor will be accessible\nthrough the constructor.super_ property.\n\n

\n
var util = require("util");\nvar events = require("events");\n\nfunction MyStream() {\n    events.EventEmitter.call(this);\n}\n\nutil.inherits(MyStream, events.EventEmitter);\n\nMyStream.prototype.write = function(data) {\n    this.emit("data", data);\n}\n\nvar stream = new MyStream();\n\nconsole.log(stream instanceof events.EventEmitter); // true\nconsole.log(MyStream.super_ === events.EventEmitter); // true\n\nstream.on("data", function(data) {\n    console.log('Received data: "' + data + '"');\n})\nstream.write("It works!"); // Received data: "It works!"
\n", + "signatures": [ + { + "params": [ + { + "name": "constructor" + }, + { + "name": "superConstructor" + } + ] + } + ] + } + ], + "type": "module", + "displayName": "util" + }, + { + "textRaw": "Events", + "name": "Events", + "stability": 4, + "stabilityText": "API Frozen", + "type": "module", + "desc": "

Many objects in Node emit events: a net.Server emits an event each time\na peer connects to it, a fs.readStream emits an event when the file is\nopened. All objects which emit events are instances of events.EventEmitter.\nYou can access this module by doing: require("events");\n\n

\n

Typically, event names are represented by a camel-cased string, however,\nthere aren't any strict restrictions on that, as any string will be accepted.\n\n

\n

Functions can then be attached to objects, to be executed when an event\nis emitted. These functions are called listeners.\n\n\n

\n", + "classes": [ + { + "textRaw": "Class: events.EventEmitter", + "type": "class", + "name": "events.EventEmitter", + "desc": "

To access the EventEmitter class, require('events').EventEmitter.\n\n

\n

When an EventEmitter instance experiences an error, the typical action is\nto emit an 'error' event. Error events are treated as a special case in node.\nIf there is no listener for it, then the default action is to print a stack\ntrace and exit the program.\n\n

\n

All EventEmitters emit the event 'newListener' when new listeners are\nadded.\n\n

\n", + "methods": [ + { + "textRaw": "emitter.addListener(event, listener)", + "type": "method", + "name": "addListener", + "desc": "

Adds a listener to the end of the listeners array for the specified event.\n\n

\n
server.on('connection', function (stream) {\n  console.log('someone connected!');\n});
\n", + "signatures": [ + { + "params": [ + { + "name": "event" + }, + { + "name": "listener" + } + ] + }, + { + "params": [ + { + "name": "event" + }, + { + "name": "listener" + } + ] + } + ] + }, + { + "textRaw": "emitter.on(event, listener)", + "type": "method", + "name": "on", + "desc": "

Adds a listener to the end of the listeners array for the specified event.\n\n

\n
server.on('connection', function (stream) {\n  console.log('someone connected!');\n});
\n", + "signatures": [ + { + "params": [ + { + "name": "event" + }, + { + "name": "listener" + } + ] + } + ] + }, + { + "textRaw": "emitter.once(event, listener)", + "type": "method", + "name": "once", + "desc": "

Adds a one time listener for the event. This listener is\ninvoked only the next time the event is fired, after which\nit is removed.\n\n

\n
server.once('connection', function (stream) {\n  console.log('Ah, we have our first user!');\n});
\n", + "signatures": [ + { + "params": [ + { + "name": "event" + }, + { + "name": "listener" + } + ] + } + ] + }, + { + "textRaw": "emitter.removeListener(event, listener)", + "type": "method", + "name": "removeListener", + "desc": "

Remove a listener from the listener array for the specified event.\nCaution: changes array indices in the listener array behind the listener.\n\n

\n
var callback = function(stream) {\n  console.log('someone connected!');\n};\nserver.on('connection', callback);\n// ...\nserver.removeListener('connection', callback);
\n", + "signatures": [ + { + "params": [ + { + "name": "event" + }, + { + "name": "listener" + } + ] + } + ] + }, + { + "textRaw": "emitter.removeAllListeners([event])", + "type": "method", + "name": "removeAllListeners", + "desc": "

Removes all listeners, or those of the specified event.\n\n

\n

Note that this will invalidate any arrays that have previously been\nreturned by emitter.listeners(event).\n\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "event", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "emitter.setMaxListeners(n)", + "type": "method", + "name": "setMaxListeners", + "desc": "

By default EventEmitters will print a warning if more than 10 listeners are\nadded for a particular event. This is a useful default which helps finding memory leaks.\nObviously not all Emitters should be limited to 10. This function allows\nthat to be increased. Set to zero for unlimited.\n\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "n" + } + ] + } + ] + }, + { + "textRaw": "emitter.listeners(event)", + "type": "method", + "name": "listeners", + "desc": "

Returns an array of listeners for the specified event.\n\n

\n
server.on('connection', function (stream) {\n  console.log('someone connected!');\n});\nconsole.log(util.inspect(server.listeners('connection'))); // [ [Function] ]
\n

This array may be a mutable reference to the same underlying list of\nlisteners that is used by the event subsystem. However, certain\nactions (specifically, removeAllListeners) will invalidate this\nreference.\n\n

\n

If you would like to get a copy of the listeners at a specific point in\ntime that is guaranteed not to change, make a copy, for example by doing\nemitter.listeners(event).slice(0).\n\n

\n

In a future release of node, this behavior may change to always\nreturn a copy, for consistency. In your programs, please do not rely on\nbeing able to modify the EventEmitter listeners using array methods.\nAlways use the 'on' method to add new listeners.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "event" + } + ] + } + ] + }, + { + "textRaw": "emitter.emit(event, [arg1], [arg2], [...])", + "type": "method", + "name": "emit", + "desc": "

Execute each of the listeners in order with the supplied arguments.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "event" + }, + { + "name": "arg1", + "optional": true + }, + { + "name": "arg2", + "optional": true + }, + { + "name": "...", + "optional": true + } + ] + } + ] + } + ], + "events": [ + { + "textRaw": "Event: 'newListener'", + "type": "event", + "name": "newListener", + "params": [], + "desc": "

This event is emitted any time someone adds a new listener.\n\n

\n" + } + ] + } + ] + }, + { + "textRaw": "Domain", + "name": "domain", + "stability": 1, + "stabilityText": "Experimental", + "desc": "

Domains provide a way to handle multiple different IO operations as a\nsingle group. If any of the event emitters or callbacks registered to a\ndomain emit an error event, or throw an error, then the domain object\nwill be notified, rather than losing the context of the error in the\nprocess.on('uncaughtException') handler, or causing the program to\nexit with an error code.\n\n

\n

This feature is new in Node version 0.8. It is a first pass, and is\nexpected to change significantly in future versions. Please use it and\nprovide feedback.\n\n

\n

Due to their experimental nature, the Domains features are disabled unless\nthe domain module is loaded at least once. No domains are created or\nregistered by default. This is by design, to prevent adverse effects on\ncurrent programs. It is expected to be enabled by default in future\nNode.js versions.\n\n

\n", + "miscs": [ + { + "textRaw": "Additions to Error objects", + "name": "Additions to Error objects", + "type": "misc", + "desc": "

Any time an Error object is routed through a domain, a few extra fields\nare added to it.\n\n

\n
    \n
  • error.domain The domain that first handled the error.
  • \n
  • error.domain_emitter The event emitter that emitted an 'error' event\nwith the error object.
  • \n
  • error.domain_bound The callback function which was bound to the\ndomain, and passed an error as its first argument.
  • \n
  • error.domain_thrown A boolean indicating whether the error was\nthrown, emitted, or passed to a bound callback function.
  • \n
\n" + }, + { + "textRaw": "Implicit Binding", + "name": "Implicit Binding", + "type": "misc", + "desc": "

If domains are in use, then all new EventEmitter objects (including\nStream objects, requests, responses, etc.) will be implicitly bound to\nthe active domain at the time of their creation.\n\n

\n

Additionally, callbacks passed to lowlevel event loop requests (such as\nto fs.open, or other callback-taking methods) will automatically be\nbound to the active domain. If they throw, then the domain will catch\nthe error.\n\n

\n

In order to prevent excessive memory usage, Domain objects themselves\nare not implicitly added as children of the active domain. If they\nwere, then it would be too easy to prevent request and response objects\nfrom being properly garbage collected.\n\n

\n

If you want to nest Domain objects as children of a parent Domain,\nthen you must explicitly add them, and then dispose of them later.\n\n

\n

Implicit binding routes thrown errors and 'error' events to the\nDomain's error event, but does not register the EventEmitter on the\nDomain, so domain.dispose() will not shut down the EventEmitter.\nImplicit binding only takes care of thrown errors and 'error' events.\n\n

\n" + }, + { + "textRaw": "Explicit Binding", + "name": "Explicit Binding", + "type": "misc", + "desc": "

Sometimes, the domain in use is not the one that ought to be used for a\nspecific event emitter. Or, the event emitter could have been created\nin the context of one domain, but ought to instead be bound to some\nother domain.\n\n

\n

For example, there could be one domain in use for an HTTP server, but\nperhaps we would like to have a separate domain to use for each request.\n\n

\n

That is possible via explicit binding.\n\n

\n

For example:\n\n

\n
// create a top-level domain for the server\nvar serverDomain = domain.create();\n\nserverDomain.run(function() {\n  // server is created in the scope of serverDomain\n  http.createServer(function(req, res) {\n    // req and res are also created in the scope of serverDomain\n    // however, we'd prefer to have a separate domain for each request.\n    // create it first thing, and add req and res to it.\n    var reqd = domain.create();\n    reqd.add(req);\n    reqd.add(res);\n    reqd.on('error', function(er) {\n      console.error('Error', er, req.url);\n      try {\n        res.writeHead(500);\n        res.end('Error occurred, sorry.');\n        res.on('close', function() {\n          // forcibly shut down any other things added to this domain\n          reqd.dispose();\n        });\n      } catch (er) {\n        console.error('Error sending 500', er, req.url);\n        // tried our best.  clean up anything remaining.\n        reqd.dispose();\n      }\n    });\n  }).listen(1337);\n});
\n" + } + ], + "methods": [ + { + "textRaw": "domain.create()", + "type": "method", + "name": "create", + "signatures": [ + { + "return": { + "textRaw": "return: {Domain} ", + "name": "return", + "type": "Domain" + }, + "params": [] + }, + { + "params": [] + } + ], + "desc": "

Returns a new Domain object.\n\n

\n" + } + ], + "classes": [ + { + "textRaw": "Class: Domain", + "type": "class", + "name": "Domain", + "desc": "

The Domain class encapsulates the functionality of routing errors and\nuncaught exceptions to the active Domain object.\n\n

\n

Domain is a child class of [EventEmitter][]. To handle the errors that it\ncatches, listen to its error event.\n\n

\n", + "methods": [ + { + "textRaw": "domain.run(fn)", + "type": "method", + "name": "run", + "signatures": [ + { + "params": [ + { + "textRaw": "`fn` {Function} ", + "name": "fn", + "type": "Function" + } + ] + }, + { + "params": [ + { + "name": "fn" + } + ] + } + ], + "desc": "

Run the supplied function in the context of the domain, implicitly\nbinding all event emitters, timers, and lowlevel requests that are\ncreated in that context.\n\n

\n

This is the most basic way to use a domain.\n\n

\n

Example:\n\n

\n
var d = domain.create();\nd.on('error', function(er) {\n  console.error('Caught error!', er);\n});\nd.run(function() {\n  process.nextTick(function() {\n    setTimeout(function() { // simulating some various async stuff\n      fs.open('non-existent file', 'r', function(er, fd) {\n        if (er) throw er;\n        // proceed...\n      });\n    }, 100);\n  });\n});
\n

In this example, the d.on('error') handler will be triggered, rather\nthan crashing the program.\n\n

\n" + }, + { + "textRaw": "domain.add(emitter)", + "type": "method", + "name": "add", + "signatures": [ + { + "params": [ + { + "textRaw": "`emitter` {EventEmitter | Timer} emitter or timer to be added to the domain ", + "name": "emitter", + "type": "EventEmitter | Timer", + "desc": "emitter or timer to be added to the domain" + } + ] + }, + { + "params": [ + { + "name": "emitter" + } + ] + } + ], + "desc": "

Explicitly adds an emitter to the domain. If any event handlers called by\nthe emitter throw an error, or if the emitter emits an error event, it\nwill be routed to the domain's error event, just like with implicit\nbinding.\n\n

\n

This also works with timers that are returned from setInterval and\nsetTimeout. If their callback function throws, it will be caught by\nthe domain 'error' handler.\n\n

\n

If the Timer or EventEmitter was already bound to a domain, it is removed\nfrom that one, and bound to this one instead.\n\n

\n" + }, + { + "textRaw": "domain.remove(emitter)", + "type": "method", + "name": "remove", + "signatures": [ + { + "params": [ + { + "textRaw": "`emitter` {EventEmitter | Timer} emitter or timer to be removed from the domain ", + "name": "emitter", + "type": "EventEmitter | Timer", + "desc": "emitter or timer to be removed from the domain" + } + ] + }, + { + "params": [ + { + "name": "emitter" + } + ] + } + ], + "desc": "

The opposite of domain.add(emitter). Removes domain handling from the\nspecified emitter.\n\n

\n" + }, + { + "textRaw": "domain.bind(callback)", + "type": "method", + "name": "bind", + "signatures": [ + { + "return": { + "textRaw": "return: {Function} The bound function ", + "name": "return", + "type": "Function", + "desc": "The bound function" + }, + "params": [ + { + "textRaw": "`callback` {Function} The callback function ", + "name": "callback", + "type": "Function", + "desc": "The callback function" + } + ] + }, + { + "params": [ + { + "name": "callback" + } + ] + } + ], + "desc": "

The returned function will be a wrapper around the supplied callback\nfunction. When the returned function is called, any errors that are\nthrown will be routed to the domain's error event.\n\n

\n

Example

\n
var d = domain.create();\n\nfunction readSomeFile(filename, cb) {\n  fs.readFile(filename, 'utf8', d.bind(function(er, data) {\n    // if this throws, it will also be passed to the domain\n    return cb(er, data ? JSON.parse(data) : null);\n  }));\n}\n\nd.on('error', function(er) {\n  // an error occurred somewhere.\n  // if we throw it now, it will crash the program\n  // with the normal line number and stack message.\n});
\n" + }, + { + "textRaw": "domain.intercept(callback)", + "type": "method", + "name": "intercept", + "signatures": [ + { + "return": { + "textRaw": "return: {Function} The intercepted function ", + "name": "return", + "type": "Function", + "desc": "The intercepted function" + }, + "params": [ + { + "textRaw": "`callback` {Function} The callback function ", + "name": "callback", + "type": "Function", + "desc": "The callback function" + } + ] + }, + { + "params": [ + { + "name": "callback" + } + ] + } + ], + "desc": "

This method is almost identical to domain.bind(callback). However, in\naddition to catching thrown errors, it will also intercept Error\nobjects sent as the first argument to the function.\n\n

\n

In this way, the common if (er) return callback(er); pattern can be replaced\nwith a single error handler in a single place.\n\n

\n

Example

\n
var d = domain.create();\n\nfunction readSomeFile(filename, cb) {\n  fs.readFile(filename, 'utf8', d.intercept(function(data) {\n    // note, the first argument is never passed to the\n    // callback since it is assumed to be the 'Error' argument\n    // and thus intercepted by the domain.\n\n    // if this throws, it will also be passed to the domain\n    // so the error-handling logic can be moved to the 'error'\n    // event on the domain instead of being repeated throughout\n    // the program.\n    return cb(null, JSON.parse(data));\n  }));\n}\n\nd.on('error', function(er) {\n  // an error occurred somewhere.\n  // if we throw it now, it will crash the program\n  // with the normal line number and stack message.\n});
\n" + }, + { + "textRaw": "domain.dispose()", + "type": "method", + "name": "dispose", + "desc": "

The dispose method destroys a domain, and makes a best effort attempt to\nclean up any and all IO that is associated with the domain. Streams are\naborted, ended, closed, and/or destroyed. Timers are cleared.\nExplicitly bound callbacks are no longer called. Any error events that\nare raised as a result of this are ignored.\n\n

\n

The intention of calling dispose is generally to prevent cascading\nerrors when a critical part of the Domain context is found to be in an\nerror state.\n\n

\n

Once the domain is disposed the dispose event will emit.\n\n

\n

Note that IO might still be performed. However, to the highest degree\npossible, once a domain is disposed, further errors from the emitters in\nthat set will be ignored. So, even if some remaining actions are still\nin flight, Node.js will not communicate further about them.\n\n

\n", + "signatures": [ + { + "params": [] + } + ] + } + ], + "properties": [ + { + "textRaw": "`members` {Array} ", + "name": "members", + "desc": "

An array of timers and event emitters that have been explicitly added\nto the domain.\n\n

\n" + } + ] + } + ], + "type": "module", + "displayName": "Domain" + }, + { + "textRaw": "Buffer", + "name": "buffer", + "stability": 3, + "stabilityText": "Stable", + "desc": "

Pure JavaScript is Unicode friendly but not nice to binary data. When\ndealing with TCP streams or the file system, it's necessary to handle octet\nstreams. Node has several strategies for manipulating, creating, and\nconsuming octet streams.\n\n

\n

Raw data is stored in instances of the Buffer class. A Buffer is similar\nto an array of integers but corresponds to a raw memory allocation outside\nthe V8 heap. A Buffer cannot be resized.\n\n

\n

The Buffer class is a global, making it very rare that one would need\nto ever require('buffer').\n\n

\n

Converting between Buffers and JavaScript string objects requires an explicit\nencoding method. Here are the different string encodings.\n\n

\n
    \n
  • 'ascii' - for 7 bit ASCII data only. This encoding method is very fast, and\nwill strip the high bit if set.\nNote that this encoding converts a null character ('\\0' or '\\u0000') into\n0x20 (character code of a space). If you want to convert a null character\ninto 0x00, you should use 'utf8'.

    \n
  • \n
  • 'utf8' - Multibyte encoded Unicode characters. Many web pages and other\ndocument formats use UTF-8.

    \n
  • \n
  • 'utf16le' - 2 or 4 bytes, little endian encoded Unicode characters.\nSurrogate pairs (U+10000 to U+10FFFF) are supported.

    \n
  • \n
  • 'ucs2' - Alias of 'utf16le'.

    \n
  • \n
  • 'base64' - Base64 string encoding.

    \n
  • \n
  • 'binary' - A way of encoding raw binary data into strings by using only\nthe first 8 bits of each character. This encoding method is deprecated and\nshould be avoided in favor of Buffer objects where possible. This encoding\nwill be removed in future versions of Node.

    \n
  • \n
  • 'hex' - Encode each byte as two hexadecimal characters.

    \n
  • \n
\n", + "classes": [ + { + "textRaw": "Class: Buffer", + "type": "class", + "name": "Buffer", + "desc": "

The Buffer class is a global type for dealing with binary data directly.\nIt can be constructed in a variety of ways.\n\n

\n", + "methods": [ + { + "textRaw": "buf.write(string, [offset], [length], [encoding])", + "type": "method", + "name": "write", + "signatures": [ + { + "params": [ + { + "textRaw": "`string` String - data to be written to buffer ", + "name": "string", + "desc": "String - data to be written to buffer" + }, + { + "textRaw": "`offset` Number, Optional, Default: 0 ", + "name": "offset", + "desc": "Number, Optional, Default: 0", + "optional": true + }, + { + "textRaw": "`length` Number, Optional, Default: `buffer.length - offset` ", + "name": "length", + "desc": "Number, Optional, Default: `buffer.length - offset`", + "optional": true + }, + { + "textRaw": "`encoding` String, Optional, Default: 'utf8' ", + "name": "encoding", + "desc": "String, Optional, Default: 'utf8'", + "optional": true + } + ] + }, + { + "params": [ + { + "name": "string" + }, + { + "name": "offset", + "optional": true + }, + { + "name": "length", + "optional": true + }, + { + "name": "encoding", + "optional": true + } + ] + } + ], + "desc": "

Writes string to the buffer at offset using the given encoding.\noffset defaults to 0, encoding defaults to 'utf8'. length is\nthe number of bytes to write. Returns number of octets written. If buffer did\nnot contain enough space to fit the entire string, it will write a partial\namount of the string. length defaults to buffer.length - offset.\nThe method will not write partial characters.\n\n

\n
buf = new Buffer(256);\nlen = buf.write('\\u00bd + \\u00bc = \\u00be', 0);\nconsole.log(len + " bytes: " + buf.toString('utf8', 0, len));
\n

The number of characters written (which may be different than the number of\nbytes written) is set in Buffer._charsWritten and will be overwritten the\nnext time buf.write() is called.\n\n\n

\n" + }, + { + "textRaw": "buf.toString([encoding], [start], [end])", + "type": "method", + "name": "toString", + "signatures": [ + { + "params": [ + { + "textRaw": "`encoding` String, Optional, Default: 'utf8' ", + "name": "encoding", + "desc": "String, Optional, Default: 'utf8'", + "optional": true + }, + { + "textRaw": "`start` Number, Optional, Default: 0 ", + "name": "start", + "desc": "Number, Optional, Default: 0", + "optional": true + }, + { + "textRaw": "`end` Number, Optional, Default: `buffer.length` ", + "name": "end", + "desc": "Number, Optional, Default: `buffer.length`", + "optional": true + } + ] + }, + { + "params": [ + { + "name": "encoding", + "optional": true + }, + { + "name": "start", + "optional": true + }, + { + "name": "end", + "optional": true + } + ] + } + ], + "desc": "

Decodes and returns a string from buffer data encoded with encoding\n(defaults to 'utf8') beginning at start (defaults to 0) and ending at\nend (defaults to buffer.length).\n\n

\n

See buffer.write() example, above.\n\n\n

\n" + }, + { + "textRaw": "buf.copy(targetBuffer, [targetStart], [sourceStart], [sourceEnd])", + "type": "method", + "name": "copy", + "signatures": [ + { + "params": [ + { + "textRaw": "`targetBuffer` Buffer object - Buffer to copy into ", + "name": "targetBuffer", + "desc": "Buffer object - Buffer to copy into" + }, + { + "textRaw": "`targetStart` Number, Optional, Default: 0 ", + "name": "targetStart", + "desc": "Number, Optional, Default: 0", + "optional": true + }, + { + "textRaw": "`sourceStart` Number, Optional, Default: 0 ", + "name": "sourceStart", + "desc": "Number, Optional, Default: 0", + "optional": true + }, + { + "textRaw": "`sourceEnd` Number, Optional, Default: `buffer.length` ", + "name": "sourceEnd", + "desc": "Number, Optional, Default: `buffer.length`", + "optional": true + } + ] + }, + { + "params": [ + { + "name": "targetBuffer" + }, + { + "name": "targetStart", + "optional": true + }, + { + "name": "sourceStart", + "optional": true + }, + { + "name": "sourceEnd", + "optional": true + } + ] + } + ], + "desc": "

Does copy between buffers. The source and target regions can be overlapped.\ntargetStart and sourceStart default to 0.\nsourceEnd defaults to buffer.length.\n\n

\n

Example: build two Buffers, then copy buf1 from byte 16 through byte 19\ninto buf2, starting at the 8th byte in buf2.\n\n

\n
buf1 = new Buffer(26);\nbuf2 = new Buffer(26);\n\nfor (var i = 0 ; i < 26 ; i++) {\n  buf1[i] = i + 97; // 97 is ASCII a\n  buf2[i] = 33; // ASCII !\n}\n\nbuf1.copy(buf2, 8, 16, 20);\nconsole.log(buf2.toString('ascii', 0, 25));\n\n// !!!!!!!!qrst!!!!!!!!!!!!!
\n" + }, + { + "textRaw": "buf.slice([start], [end])", + "type": "method", + "name": "slice", + "signatures": [ + { + "params": [ + { + "textRaw": "`start` Number, Optional, Default: 0 ", + "name": "start", + "desc": "Number, Optional, Default: 0", + "optional": true + }, + { + "textRaw": "`end` Number, Optional, Default: `buffer.length` ", + "name": "end", + "desc": "Number, Optional, Default: `buffer.length`", + "optional": true + } + ] + }, + { + "params": [ + { + "name": "start", + "optional": true + }, + { + "name": "end", + "optional": true + } + ] + } + ], + "desc": "

Returns a new buffer which references the same memory as the old, but offset\nand cropped by the start (defaults to 0) and end (defaults to\nbuffer.length) indexes.\n\n

\n

Modifying the new buffer slice will modify memory in the original buffer!\n\n

\n

Example: build a Buffer with the ASCII alphabet, take a slice, then modify one\nbyte from the original Buffer.\n\n

\n
var buf1 = new Buffer(26);\n\nfor (var i = 0 ; i < 26 ; i++) {\n  buf1[i] = i + 97; // 97 is ASCII a\n}\n\nvar buf2 = buf1.slice(0, 3);\nconsole.log(buf2.toString('ascii', 0, buf2.length));\nbuf1[0] = 33;\nconsole.log(buf2.toString('ascii', 0, buf2.length));\n\n// abc\n// !bc
\n" + }, + { + "textRaw": "buf.readUInt8(offset, [noAssert])", + "type": "method", + "name": "readUInt8", + "signatures": [ + { + "return": { + "textRaw": "Return: Number ", + "name": "return", + "desc": "Number" + }, + "params": [ + { + "textRaw": "`offset` Number ", + "name": "offset", + "desc": "Number" + }, + { + "textRaw": "`noAssert` Boolean, Optional, Default: false ", + "name": "noAssert", + "desc": "Boolean, Optional, Default: false", + "optional": true + } + ] + }, + { + "params": [ + { + "name": "offset" + }, + { + "name": "noAssert", + "optional": true + } + ] + } + ], + "desc": "

Reads an unsigned 8 bit integer from the buffer at the specified offset.\n\n

\n

Set noAssert to true to skip validation of offset. This means that offset\nmay be beyond the end of the buffer. Defaults to false.\n\n

\n

Example:\n\n

\n
var buf = new Buffer(4);\n\nbuf[0] = 0x3;\nbuf[1] = 0x4;\nbuf[2] = 0x23;\nbuf[3] = 0x42;\n\nfor (ii = 0; ii < buf.length; ii++) {\n  console.log(buf.readUInt8(ii));\n}\n\n// 0x3\n// 0x4\n// 0x23\n// 0x42
\n" + }, + { + "textRaw": "buf.readUInt16LE(offset, [noAssert])", + "type": "method", + "name": "readUInt16LE", + "signatures": [ + { + "return": { + "textRaw": "Return: Number ", + "name": "return", + "desc": "Number" + }, + "params": [ + { + "textRaw": "`offset` Number ", + "name": "offset", + "desc": "Number" + }, + { + "textRaw": "`noAssert` Boolean, Optional, Default: false ", + "name": "noAssert", + "desc": "Boolean, Optional, Default: false", + "optional": true + } + ] + }, + { + "params": [ + { + "name": "offset" + }, + { + "name": "noAssert", + "optional": true + } + ] + }, + { + "params": [ + { + "name": "offset" + }, + { + "name": "noAssert", + "optional": true + } + ] + } + ], + "desc": "

Reads an unsigned 16 bit integer from the buffer at the specified offset with\nspecified endian format.\n\n

\n

Set noAssert to true to skip validation of offset. This means that offset\nmay be beyond the end of the buffer. Defaults to false.\n\n

\n

Example:\n\n

\n
var buf = new Buffer(4);\n\nbuf[0] = 0x3;\nbuf[1] = 0x4;\nbuf[2] = 0x23;\nbuf[3] = 0x42;\n\nconsole.log(buf.readUInt16BE(0));\nconsole.log(buf.readUInt16LE(0));\nconsole.log(buf.readUInt16BE(1));\nconsole.log(buf.readUInt16LE(1));\nconsole.log(buf.readUInt16BE(2));\nconsole.log(buf.readUInt16LE(2));\n\n// 0x0304\n// 0x0403\n// 0x0423\n// 0x2304\n// 0x2342\n// 0x4223
\n" + }, + { + "textRaw": "buf.readUInt16BE(offset, [noAssert])", + "type": "method", + "name": "readUInt16BE", + "signatures": [ + { + "return": { + "textRaw": "Return: Number ", + "name": "return", + "desc": "Number" + }, + "params": [ + { + "textRaw": "`offset` Number ", + "name": "offset", + "desc": "Number" + }, + { + "textRaw": "`noAssert` Boolean, Optional, Default: false ", + "name": "noAssert", + "desc": "Boolean, Optional, Default: false", + "optional": true + } + ] + }, + { + "params": [ + { + "name": "offset" + }, + { + "name": "noAssert", + "optional": true + } + ] + } + ], + "desc": "

Reads an unsigned 16 bit integer from the buffer at the specified offset with\nspecified endian format.\n\n

\n

Set noAssert to true to skip validation of offset. This means that offset\nmay be beyond the end of the buffer. Defaults to false.\n\n

\n

Example:\n\n

\n
var buf = new Buffer(4);\n\nbuf[0] = 0x3;\nbuf[1] = 0x4;\nbuf[2] = 0x23;\nbuf[3] = 0x42;\n\nconsole.log(buf.readUInt16BE(0));\nconsole.log(buf.readUInt16LE(0));\nconsole.log(buf.readUInt16BE(1));\nconsole.log(buf.readUInt16LE(1));\nconsole.log(buf.readUInt16BE(2));\nconsole.log(buf.readUInt16LE(2));\n\n// 0x0304\n// 0x0403\n// 0x0423\n// 0x2304\n// 0x2342\n// 0x4223
\n" + }, + { + "textRaw": "buf.readUInt32LE(offset, [noAssert])", + "type": "method", + "name": "readUInt32LE", + "signatures": [ + { + "return": { + "textRaw": "Return: Number ", + "name": "return", + "desc": "Number" + }, + "params": [ + { + "textRaw": "`offset` Number ", + "name": "offset", + "desc": "Number" + }, + { + "textRaw": "`noAssert` Boolean, Optional, Default: false ", + "name": "noAssert", + "desc": "Boolean, Optional, Default: false", + "optional": true + } + ] + }, + { + "params": [ + { + "name": "offset" + }, + { + "name": "noAssert", + "optional": true + } + ] + }, + { + "params": [ + { + "name": "offset" + }, + { + "name": "noAssert", + "optional": true + } + ] + } + ], + "desc": "

Reads an unsigned 32 bit integer from the buffer at the specified offset with\nspecified endian format.\n\n

\n

Set noAssert to true to skip validation of offset. This means that offset\nmay be beyond the end of the buffer. Defaults to false.\n\n

\n

Example:\n\n

\n
var buf = new Buffer(4);\n\nbuf[0] = 0x3;\nbuf[1] = 0x4;\nbuf[2] = 0x23;\nbuf[3] = 0x42;\n\nconsole.log(buf.readUInt32BE(0));\nconsole.log(buf.readUInt32LE(0));\n\n// 0x03042342\n// 0x42230403
\n" + }, + { + "textRaw": "buf.readUInt32BE(offset, [noAssert])", + "type": "method", + "name": "readUInt32BE", + "signatures": [ + { + "return": { + "textRaw": "Return: Number ", + "name": "return", + "desc": "Number" + }, + "params": [ + { + "textRaw": "`offset` Number ", + "name": "offset", + "desc": "Number" + }, + { + "textRaw": "`noAssert` Boolean, Optional, Default: false ", + "name": "noAssert", + "desc": "Boolean, Optional, Default: false", + "optional": true + } + ] + }, + { + "params": [ + { + "name": "offset" + }, + { + "name": "noAssert", + "optional": true + } + ] + } + ], + "desc": "

Reads an unsigned 32 bit integer from the buffer at the specified offset with\nspecified endian format.\n\n

\n

Set noAssert to true to skip validation of offset. This means that offset\nmay be beyond the end of the buffer. Defaults to false.\n\n

\n

Example:\n\n

\n
var buf = new Buffer(4);\n\nbuf[0] = 0x3;\nbuf[1] = 0x4;\nbuf[2] = 0x23;\nbuf[3] = 0x42;\n\nconsole.log(buf.readUInt32BE(0));\nconsole.log(buf.readUInt32LE(0));\n\n// 0x03042342\n// 0x42230403
\n" + }, + { + "textRaw": "buf.readInt8(offset, [noAssert])", + "type": "method", + "name": "readInt8", + "signatures": [ + { + "return": { + "textRaw": "Return: Number ", + "name": "return", + "desc": "Number" + }, + "params": [ + { + "textRaw": "`offset` Number ", + "name": "offset", + "desc": "Number" + }, + { + "textRaw": "`noAssert` Boolean, Optional, Default: false ", + "name": "noAssert", + "desc": "Boolean, Optional, Default: false", + "optional": true + } + ] + }, + { + "params": [ + { + "name": "offset" + }, + { + "name": "noAssert", + "optional": true + } + ] + } + ], + "desc": "

Reads a signed 8 bit integer from the buffer at the specified offset.\n\n

\n

Set noAssert to true to skip validation of offset. This means that offset\nmay be beyond the end of the buffer. Defaults to false.\n\n

\n

Works as buffer.readUInt8, except buffer contents are treated as two's\ncomplement signed values.\n\n

\n" + }, + { + "textRaw": "buf.readInt16LE(offset, [noAssert])", + "type": "method", + "name": "readInt16LE", + "signatures": [ + { + "return": { + "textRaw": "Return: Number ", + "name": "return", + "desc": "Number" + }, + "params": [ + { + "textRaw": "`offset` Number ", + "name": "offset", + "desc": "Number" + }, + { + "textRaw": "`noAssert` Boolean, Optional, Default: false ", + "name": "noAssert", + "desc": "Boolean, Optional, Default: false", + "optional": true + } + ] + }, + { + "params": [ + { + "name": "offset" + }, + { + "name": "noAssert", + "optional": true + } + ] + }, + { + "params": [ + { + "name": "offset" + }, + { + "name": "noAssert", + "optional": true + } + ] + } + ], + "desc": "

Reads a signed 16 bit integer from the buffer at the specified offset with\nspecified endian format.\n\n

\n

Set noAssert to true to skip validation of offset. This means that offset\nmay be beyond the end of the buffer. Defaults to false.\n\n

\n

Works as buffer.readUInt16*, except buffer contents are treated as two's\ncomplement signed values.\n\n

\n" + }, + { + "textRaw": "buf.readInt16BE(offset, [noAssert])", + "type": "method", + "name": "readInt16BE", + "signatures": [ + { + "return": { + "textRaw": "Return: Number ", + "name": "return", + "desc": "Number" + }, + "params": [ + { + "textRaw": "`offset` Number ", + "name": "offset", + "desc": "Number" + }, + { + "textRaw": "`noAssert` Boolean, Optional, Default: false ", + "name": "noAssert", + "desc": "Boolean, Optional, Default: false", + "optional": true + } + ] + }, + { + "params": [ + { + "name": "offset" + }, + { + "name": "noAssert", + "optional": true + } + ] + } + ], + "desc": "

Reads a signed 16 bit integer from the buffer at the specified offset with\nspecified endian format.\n\n

\n

Set noAssert to true to skip validation of offset. This means that offset\nmay be beyond the end of the buffer. Defaults to false.\n\n

\n

Works as buffer.readUInt16*, except buffer contents are treated as two's\ncomplement signed values.\n\n

\n" + }, + { + "textRaw": "buf.readInt32LE(offset, [noAssert])", + "type": "method", + "name": "readInt32LE", + "signatures": [ + { + "return": { + "textRaw": "Return: Number ", + "name": "return", + "desc": "Number" + }, + "params": [ + { + "textRaw": "`offset` Number ", + "name": "offset", + "desc": "Number" + }, + { + "textRaw": "`noAssert` Boolean, Optional, Default: false ", + "name": "noAssert", + "desc": "Boolean, Optional, Default: false", + "optional": true + } + ] + }, + { + "params": [ + { + "name": "offset" + }, + { + "name": "noAssert", + "optional": true + } + ] + }, + { + "params": [ + { + "name": "offset" + }, + { + "name": "noAssert", + "optional": true + } + ] + } + ], + "desc": "

Reads a signed 32 bit integer from the buffer at the specified offset with\nspecified endian format.\n\n

\n

Set noAssert to true to skip validation of offset. This means that offset\nmay be beyond the end of the buffer. Defaults to false.\n\n

\n

Works as buffer.readUInt32*, except buffer contents are treated as two's\ncomplement signed values.\n\n

\n" + }, + { + "textRaw": "buf.readInt32BE(offset, [noAssert])", + "type": "method", + "name": "readInt32BE", + "signatures": [ + { + "return": { + "textRaw": "Return: Number ", + "name": "return", + "desc": "Number" + }, + "params": [ + { + "textRaw": "`offset` Number ", + "name": "offset", + "desc": "Number" + }, + { + "textRaw": "`noAssert` Boolean, Optional, Default: false ", + "name": "noAssert", + "desc": "Boolean, Optional, Default: false", + "optional": true + } + ] + }, + { + "params": [ + { + "name": "offset" + }, + { + "name": "noAssert", + "optional": true + } + ] + } + ], + "desc": "

Reads a signed 32 bit integer from the buffer at the specified offset with\nspecified endian format.\n\n

\n

Set noAssert to true to skip validation of offset. This means that offset\nmay be beyond the end of the buffer. Defaults to false.\n\n

\n

Works as buffer.readUInt32*, except buffer contents are treated as two's\ncomplement signed values.\n\n

\n" + }, + { + "textRaw": "buf.readFloatLE(offset, [noAssert])", + "type": "method", + "name": "readFloatLE", + "signatures": [ + { + "return": { + "textRaw": "Return: Number ", + "name": "return", + "desc": "Number" + }, + "params": [ + { + "textRaw": "`offset` Number ", + "name": "offset", + "desc": "Number" + }, + { + "textRaw": "`noAssert` Boolean, Optional, Default: false ", + "name": "noAssert", + "desc": "Boolean, Optional, Default: false", + "optional": true + } + ] + }, + { + "params": [ + { + "name": "offset" + }, + { + "name": "noAssert", + "optional": true + } + ] + }, + { + "params": [ + { + "name": "offset" + }, + { + "name": "noAssert", + "optional": true + } + ] + } + ], + "desc": "

Reads a 32 bit float from the buffer at the specified offset with specified\nendian format.\n\n

\n

Set noAssert to true to skip validation of offset. This means that offset\nmay be beyond the end of the buffer. Defaults to false.\n\n

\n

Example:\n\n

\n
var buf = new Buffer(4);\n\nbuf[0] = 0x00;\nbuf[1] = 0x00;\nbuf[2] = 0x80;\nbuf[3] = 0x3f;\n\nconsole.log(buf.readFloatLE(0));\n\n// 0x01
\n" + }, + { + "textRaw": "buf.readFloatBE(offset, [noAssert])", + "type": "method", + "name": "readFloatBE", + "signatures": [ + { + "return": { + "textRaw": "Return: Number ", + "name": "return", + "desc": "Number" + }, + "params": [ + { + "textRaw": "`offset` Number ", + "name": "offset", + "desc": "Number" + }, + { + "textRaw": "`noAssert` Boolean, Optional, Default: false ", + "name": "noAssert", + "desc": "Boolean, Optional, Default: false", + "optional": true + } + ] + }, + { + "params": [ + { + "name": "offset" + }, + { + "name": "noAssert", + "optional": true + } + ] + } + ], + "desc": "

Reads a 32 bit float from the buffer at the specified offset with specified\nendian format.\n\n

\n

Set noAssert to true to skip validation of offset. This means that offset\nmay be beyond the end of the buffer. Defaults to false.\n\n

\n

Example:\n\n

\n
var buf = new Buffer(4);\n\nbuf[0] = 0x00;\nbuf[1] = 0x00;\nbuf[2] = 0x80;\nbuf[3] = 0x3f;\n\nconsole.log(buf.readFloatLE(0));\n\n// 0x01
\n" + }, + { + "textRaw": "buf.readDoubleLE(offset, [noAssert])", + "type": "method", + "name": "readDoubleLE", + "signatures": [ + { + "return": { + "textRaw": "Return: Number ", + "name": "return", + "desc": "Number" + }, + "params": [ + { + "textRaw": "`offset` Number ", + "name": "offset", + "desc": "Number" + }, + { + "textRaw": "`noAssert` Boolean, Optional, Default: false ", + "name": "noAssert", + "desc": "Boolean, Optional, Default: false", + "optional": true + } + ] + }, + { + "params": [ + { + "name": "offset" + }, + { + "name": "noAssert", + "optional": true + } + ] + }, + { + "params": [ + { + "name": "offset" + }, + { + "name": "noAssert", + "optional": true + } + ] + } + ], + "desc": "

Reads a 64 bit double from the buffer at the specified offset with specified\nendian format.\n\n

\n

Set noAssert to true to skip validation of offset. This means that offset\nmay be beyond the end of the buffer. Defaults to false.\n\n

\n

Example:\n\n

\n
var buf = new Buffer(8);\n\nbuf[0] = 0x55;\nbuf[1] = 0x55;\nbuf[2] = 0x55;\nbuf[3] = 0x55;\nbuf[4] = 0x55;\nbuf[5] = 0x55;\nbuf[6] = 0xd5;\nbuf[7] = 0x3f;\n\nconsole.log(buf.readDoubleLE(0));\n\n// 0.3333333333333333
\n" + }, + { + "textRaw": "buf.readDoubleBE(offset, [noAssert])", + "type": "method", + "name": "readDoubleBE", + "signatures": [ + { + "return": { + "textRaw": "Return: Number ", + "name": "return", + "desc": "Number" + }, + "params": [ + { + "textRaw": "`offset` Number ", + "name": "offset", + "desc": "Number" + }, + { + "textRaw": "`noAssert` Boolean, Optional, Default: false ", + "name": "noAssert", + "desc": "Boolean, Optional, Default: false", + "optional": true + } + ] + }, + { + "params": [ + { + "name": "offset" + }, + { + "name": "noAssert", + "optional": true + } + ] + } + ], + "desc": "

Reads a 64 bit double from the buffer at the specified offset with specified\nendian format.\n\n

\n

Set noAssert to true to skip validation of offset. This means that offset\nmay be beyond the end of the buffer. Defaults to false.\n\n

\n

Example:\n\n

\n
var buf = new Buffer(8);\n\nbuf[0] = 0x55;\nbuf[1] = 0x55;\nbuf[2] = 0x55;\nbuf[3] = 0x55;\nbuf[4] = 0x55;\nbuf[5] = 0x55;\nbuf[6] = 0xd5;\nbuf[7] = 0x3f;\n\nconsole.log(buf.readDoubleLE(0));\n\n// 0.3333333333333333
\n" + }, + { + "textRaw": "buf.writeUInt8(value, offset, [noAssert])", + "type": "method", + "name": "writeUInt8", + "signatures": [ + { + "params": [ + { + "textRaw": "`value` Number ", + "name": "value", + "desc": "Number" + }, + { + "textRaw": "`offset` Number ", + "name": "offset", + "desc": "Number" + }, + { + "textRaw": "`noAssert` Boolean, Optional, Default: false ", + "name": "noAssert", + "desc": "Boolean, Optional, Default: false", + "optional": true + } + ] + }, + { + "params": [ + { + "name": "value" + }, + { + "name": "offset" + }, + { + "name": "noAssert", + "optional": true + } + ] + } + ], + "desc": "

Writes value to the buffer at the specified offset. Note, value must be a\nvalid unsigned 8 bit integer.\n\n

\n

Set noAssert to true to skip validation of value and offset. This means\nthat value may be too large for the specific function and offset may be\nbeyond the end of the buffer leading to the values being silently dropped. This\nshould not be used unless you are certain of correctness. Defaults to false.\n\n

\n

Example:\n\n

\n
var buf = new Buffer(4);\nbuf.writeUInt8(0x3, 0);\nbuf.writeUInt8(0x4, 1);\nbuf.writeUInt8(0x23, 2);\nbuf.writeUInt8(0x42, 3);\n\nconsole.log(buf);\n\n// <Buffer 03 04 23 42>
\n" + }, + { + "textRaw": "buf.writeUInt16LE(value, offset, [noAssert])", + "type": "method", + "name": "writeUInt16LE", + "signatures": [ + { + "params": [ + { + "textRaw": "`value` Number ", + "name": "value", + "desc": "Number" + }, + { + "textRaw": "`offset` Number ", + "name": "offset", + "desc": "Number" + }, + { + "textRaw": "`noAssert` Boolean, Optional, Default: false ", + "name": "noAssert", + "desc": "Boolean, Optional, Default: false", + "optional": true + } + ] + }, + { + "params": [ + { + "name": "value" + }, + { + "name": "offset" + }, + { + "name": "noAssert", + "optional": true + } + ] + }, + { + "params": [ + { + "name": "value" + }, + { + "name": "offset" + }, + { + "name": "noAssert", + "optional": true + } + ] + } + ], + "desc": "

Writes value to the buffer at the specified offset with specified endian\nformat. Note, value must be a valid unsigned 16 bit integer.\n\n

\n

Set noAssert to true to skip validation of value and offset. This means\nthat value may be too large for the specific function and offset may be\nbeyond the end of the buffer leading to the values being silently dropped. This\nshould not be used unless you are certain of correctness. Defaults to false.\n\n

\n

Example:\n\n

\n
var buf = new Buffer(4);\nbuf.writeUInt16BE(0xdead, 0);\nbuf.writeUInt16BE(0xbeef, 2);\n\nconsole.log(buf);\n\nbuf.writeUInt16LE(0xdead, 0);\nbuf.writeUInt16LE(0xbeef, 2);\n\nconsole.log(buf);\n\n// <Buffer de ad be ef>\n// <Buffer ad de ef be>
\n" + }, + { + "textRaw": "buf.writeUInt16BE(value, offset, [noAssert])", + "type": "method", + "name": "writeUInt16BE", + "signatures": [ + { + "params": [ + { + "textRaw": "`value` Number ", + "name": "value", + "desc": "Number" + }, + { + "textRaw": "`offset` Number ", + "name": "offset", + "desc": "Number" + }, + { + "textRaw": "`noAssert` Boolean, Optional, Default: false ", + "name": "noAssert", + "desc": "Boolean, Optional, Default: false", + "optional": true + } + ] + }, + { + "params": [ + { + "name": "value" + }, + { + "name": "offset" + }, + { + "name": "noAssert", + "optional": true + } + ] + } + ], + "desc": "

Writes value to the buffer at the specified offset with specified endian\nformat. Note, value must be a valid unsigned 16 bit integer.\n\n

\n

Set noAssert to true to skip validation of value and offset. This means\nthat value may be too large for the specific function and offset may be\nbeyond the end of the buffer leading to the values being silently dropped. This\nshould not be used unless you are certain of correctness. Defaults to false.\n\n

\n

Example:\n\n

\n
var buf = new Buffer(4);\nbuf.writeUInt16BE(0xdead, 0);\nbuf.writeUInt16BE(0xbeef, 2);\n\nconsole.log(buf);\n\nbuf.writeUInt16LE(0xdead, 0);\nbuf.writeUInt16LE(0xbeef, 2);\n\nconsole.log(buf);\n\n// <Buffer de ad be ef>\n// <Buffer ad de ef be>
\n" + }, + { + "textRaw": "buf.writeUInt32LE(value, offset, [noAssert])", + "type": "method", + "name": "writeUInt32LE", + "signatures": [ + { + "params": [ + { + "textRaw": "`value` Number ", + "name": "value", + "desc": "Number" + }, + { + "textRaw": "`offset` Number ", + "name": "offset", + "desc": "Number" + }, + { + "textRaw": "`noAssert` Boolean, Optional, Default: false ", + "name": "noAssert", + "desc": "Boolean, Optional, Default: false", + "optional": true + } + ] + }, + { + "params": [ + { + "name": "value" + }, + { + "name": "offset" + }, + { + "name": "noAssert", + "optional": true + } + ] + }, + { + "params": [ + { + "name": "value" + }, + { + "name": "offset" + }, + { + "name": "noAssert", + "optional": true + } + ] + } + ], + "desc": "

Writes value to the buffer at the specified offset with specified endian\nformat. Note, value must be a valid unsigned 32 bit integer.\n\n

\n

Set noAssert to true to skip validation of value and offset. This means\nthat value may be too large for the specific function and offset may be\nbeyond the end of the buffer leading to the values being silently dropped. This\nshould not be used unless you are certain of correctness. Defaults to false.\n\n

\n

Example:\n\n

\n
var buf = new Buffer(4);\nbuf.writeUInt32BE(0xfeedface, 0);\n\nconsole.log(buf);\n\nbuf.writeUInt32LE(0xfeedface, 0);\n\nconsole.log(buf);\n\n// <Buffer fe ed fa ce>\n// <Buffer ce fa ed fe>
\n" + }, + { + "textRaw": "buf.writeUInt32BE(value, offset, [noAssert])", + "type": "method", + "name": "writeUInt32BE", + "signatures": [ + { + "params": [ + { + "textRaw": "`value` Number ", + "name": "value", + "desc": "Number" + }, + { + "textRaw": "`offset` Number ", + "name": "offset", + "desc": "Number" + }, + { + "textRaw": "`noAssert` Boolean, Optional, Default: false ", + "name": "noAssert", + "desc": "Boolean, Optional, Default: false", + "optional": true + } + ] + }, + { + "params": [ + { + "name": "value" + }, + { + "name": "offset" + }, + { + "name": "noAssert", + "optional": true + } + ] + } + ], + "desc": "

Writes value to the buffer at the specified offset with specified endian\nformat. Note, value must be a valid unsigned 32 bit integer.\n\n

\n

Set noAssert to true to skip validation of value and offset. This means\nthat value may be too large for the specific function and offset may be\nbeyond the end of the buffer leading to the values being silently dropped. This\nshould not be used unless you are certain of correctness. Defaults to false.\n\n

\n

Example:\n\n

\n
var buf = new Buffer(4);\nbuf.writeUInt32BE(0xfeedface, 0);\n\nconsole.log(buf);\n\nbuf.writeUInt32LE(0xfeedface, 0);\n\nconsole.log(buf);\n\n// <Buffer fe ed fa ce>\n// <Buffer ce fa ed fe>
\n" + }, + { + "textRaw": "buf.writeInt8(value, offset, [noAssert])", + "type": "method", + "name": "writeInt8", + "signatures": [ + { + "params": [ + { + "textRaw": "`value` Number ", + "name": "value", + "desc": "Number" + }, + { + "textRaw": "`offset` Number ", + "name": "offset", + "desc": "Number" + }, + { + "textRaw": "`noAssert` Boolean, Optional, Default: false ", + "name": "noAssert", + "desc": "Boolean, Optional, Default: false", + "optional": true + } + ] + }, + { + "params": [ + { + "name": "value" + }, + { + "name": "offset" + }, + { + "name": "noAssert", + "optional": true + } + ] + } + ], + "desc": "

Writes value to the buffer at the specified offset. Note, value must be a\nvalid signed 8 bit integer.\n\n

\n

Set noAssert to true to skip validation of value and offset. This means\nthat value may be too large for the specific function and offset may be\nbeyond the end of the buffer leading to the values being silently dropped. This\nshould not be used unless you are certain of correctness. Defaults to false.\n\n

\n

Works as buffer.writeUInt8, except value is written out as a two's complement\nsigned integer into buffer.\n\n

\n" + }, + { + "textRaw": "buf.writeInt16LE(value, offset, [noAssert])", + "type": "method", + "name": "writeInt16LE", + "signatures": [ + { + "params": [ + { + "textRaw": "`value` Number ", + "name": "value", + "desc": "Number" + }, + { + "textRaw": "`offset` Number ", + "name": "offset", + "desc": "Number" + }, + { + "textRaw": "`noAssert` Boolean, Optional, Default: false ", + "name": "noAssert", + "desc": "Boolean, Optional, Default: false", + "optional": true + } + ] + }, + { + "params": [ + { + "name": "value" + }, + { + "name": "offset" + }, + { + "name": "noAssert", + "optional": true + } + ] + }, + { + "params": [ + { + "name": "value" + }, + { + "name": "offset" + }, + { + "name": "noAssert", + "optional": true + } + ] + } + ], + "desc": "

Writes value to the buffer at the specified offset with specified endian\nformat. Note, value must be a valid signed 16 bit integer.\n\n

\n

Set noAssert to true to skip validation of value and offset. This means\nthat value may be too large for the specific function and offset may be\nbeyond the end of the buffer leading to the values being silently dropped. This\nshould not be used unless you are certain of correctness. Defaults to false.\n\n

\n

Works as buffer.writeUInt16*, except value is written out as a two's\ncomplement signed integer into buffer.\n\n

\n" + }, + { + "textRaw": "buf.writeInt16BE(value, offset, [noAssert])", + "type": "method", + "name": "writeInt16BE", + "signatures": [ + { + "params": [ + { + "textRaw": "`value` Number ", + "name": "value", + "desc": "Number" + }, + { + "textRaw": "`offset` Number ", + "name": "offset", + "desc": "Number" + }, + { + "textRaw": "`noAssert` Boolean, Optional, Default: false ", + "name": "noAssert", + "desc": "Boolean, Optional, Default: false", + "optional": true + } + ] + }, + { + "params": [ + { + "name": "value" + }, + { + "name": "offset" + }, + { + "name": "noAssert", + "optional": true + } + ] + } + ], + "desc": "

Writes value to the buffer at the specified offset with specified endian\nformat. Note, value must be a valid signed 16 bit integer.\n\n

\n

Set noAssert to true to skip validation of value and offset. This means\nthat value may be too large for the specific function and offset may be\nbeyond the end of the buffer leading to the values being silently dropped. This\nshould not be used unless you are certain of correctness. Defaults to false.\n\n

\n

Works as buffer.writeUInt16*, except value is written out as a two's\ncomplement signed integer into buffer.\n\n

\n" + }, + { + "textRaw": "buf.writeInt32LE(value, offset, [noAssert])", + "type": "method", + "name": "writeInt32LE", + "signatures": [ + { + "params": [ + { + "textRaw": "`value` Number ", + "name": "value", + "desc": "Number" + }, + { + "textRaw": "`offset` Number ", + "name": "offset", + "desc": "Number" + }, + { + "textRaw": "`noAssert` Boolean, Optional, Default: false ", + "name": "noAssert", + "desc": "Boolean, Optional, Default: false", + "optional": true + } + ] + }, + { + "params": [ + { + "name": "value" + }, + { + "name": "offset" + }, + { + "name": "noAssert", + "optional": true + } + ] + }, + { + "params": [ + { + "name": "value" + }, + { + "name": "offset" + }, + { + "name": "noAssert", + "optional": true + } + ] + } + ], + "desc": "

Writes value to the buffer at the specified offset with specified endian\nformat. Note, value must be a valid signed 32 bit integer.\n\n

\n

Set noAssert to true to skip validation of value and offset. This means\nthat value may be too large for the specific function and offset may be\nbeyond the end of the buffer leading to the values being silently dropped. This\nshould not be used unless you are certain of correctness. Defaults to false.\n\n

\n

Works as buffer.writeUInt32*, except value is written out as a two's\ncomplement signed integer into buffer.\n\n

\n" + }, + { + "textRaw": "buf.writeInt32BE(value, offset, [noAssert])", + "type": "method", + "name": "writeInt32BE", + "signatures": [ + { + "params": [ + { + "textRaw": "`value` Number ", + "name": "value", + "desc": "Number" + }, + { + "textRaw": "`offset` Number ", + "name": "offset", + "desc": "Number" + }, + { + "textRaw": "`noAssert` Boolean, Optional, Default: false ", + "name": "noAssert", + "desc": "Boolean, Optional, Default: false", + "optional": true + } + ] + }, + { + "params": [ + { + "name": "value" + }, + { + "name": "offset" + }, + { + "name": "noAssert", + "optional": true + } + ] + } + ], + "desc": "

Writes value to the buffer at the specified offset with specified endian\nformat. Note, value must be a valid signed 32 bit integer.\n\n

\n

Set noAssert to true to skip validation of value and offset. This means\nthat value may be too large for the specific function and offset may be\nbeyond the end of the buffer leading to the values being silently dropped. This\nshould not be used unless you are certain of correctness. Defaults to false.\n\n

\n

Works as buffer.writeUInt32*, except value is written out as a two's\ncomplement signed integer into buffer.\n\n

\n" + }, + { + "textRaw": "buf.writeFloatLE(value, offset, [noAssert])", + "type": "method", + "name": "writeFloatLE", + "signatures": [ + { + "params": [ + { + "textRaw": "`value` Number ", + "name": "value", + "desc": "Number" + }, + { + "textRaw": "`offset` Number ", + "name": "offset", + "desc": "Number" + }, + { + "textRaw": "`noAssert` Boolean, Optional, Default: false ", + "name": "noAssert", + "desc": "Boolean, Optional, Default: false", + "optional": true + } + ] + }, + { + "params": [ + { + "name": "value" + }, + { + "name": "offset" + }, + { + "name": "noAssert", + "optional": true + } + ] + }, + { + "params": [ + { + "name": "value" + }, + { + "name": "offset" + }, + { + "name": "noAssert", + "optional": true + } + ] + } + ], + "desc": "

Writes value to the buffer at the specified offset with specified endian\nformat. Note, value must be a valid 32 bit float.\n\n

\n

Set noAssert to true to skip validation of value and offset. This means\nthat value may be too large for the specific function and offset may be\nbeyond the end of the buffer leading to the values being silently dropped. This\nshould not be used unless you are certain of correctness. Defaults to false.\n\n

\n

Example:\n\n

\n
var buf = new Buffer(4);\nbuf.writeFloatBE(0xcafebabe, 0);\n\nconsole.log(buf);\n\nbuf.writeFloatLE(0xcafebabe, 0);\n\nconsole.log(buf);\n\n// <Buffer 4f 4a fe bb>\n// <Buffer bb fe 4a 4f>
\n" + }, + { + "textRaw": "buf.writeFloatBE(value, offset, [noAssert])", + "type": "method", + "name": "writeFloatBE", + "signatures": [ + { + "params": [ + { + "textRaw": "`value` Number ", + "name": "value", + "desc": "Number" + }, + { + "textRaw": "`offset` Number ", + "name": "offset", + "desc": "Number" + }, + { + "textRaw": "`noAssert` Boolean, Optional, Default: false ", + "name": "noAssert", + "desc": "Boolean, Optional, Default: false", + "optional": true + } + ] + }, + { + "params": [ + { + "name": "value" + }, + { + "name": "offset" + }, + { + "name": "noAssert", + "optional": true + } + ] + } + ], + "desc": "

Writes value to the buffer at the specified offset with specified endian\nformat. Note, value must be a valid 32 bit float.\n\n

\n

Set noAssert to true to skip validation of value and offset. This means\nthat value may be too large for the specific function and offset may be\nbeyond the end of the buffer leading to the values being silently dropped. This\nshould not be used unless you are certain of correctness. Defaults to false.\n\n

\n

Example:\n\n

\n
var buf = new Buffer(4);\nbuf.writeFloatBE(0xcafebabe, 0);\n\nconsole.log(buf);\n\nbuf.writeFloatLE(0xcafebabe, 0);\n\nconsole.log(buf);\n\n// <Buffer 4f 4a fe bb>\n// <Buffer bb fe 4a 4f>
\n" + }, + { + "textRaw": "buf.writeDoubleLE(value, offset, [noAssert])", + "type": "method", + "name": "writeDoubleLE", + "signatures": [ + { + "params": [ + { + "textRaw": "`value` Number ", + "name": "value", + "desc": "Number" + }, + { + "textRaw": "`offset` Number ", + "name": "offset", + "desc": "Number" + }, + { + "textRaw": "`noAssert` Boolean, Optional, Default: false ", + "name": "noAssert", + "desc": "Boolean, Optional, Default: false", + "optional": true + } + ] + }, + { + "params": [ + { + "name": "value" + }, + { + "name": "offset" + }, + { + "name": "noAssert", + "optional": true + } + ] + }, + { + "params": [ + { + "name": "value" + }, + { + "name": "offset" + }, + { + "name": "noAssert", + "optional": true + } + ] + } + ], + "desc": "

Writes value to the buffer at the specified offset with specified endian\nformat. Note, value must be a valid 64 bit double.\n\n

\n

Set noAssert to true to skip validation of value and offset. This means\nthat value may be too large for the specific function and offset may be\nbeyond the end of the buffer leading to the values being silently dropped. This\nshould not be used unless you are certain of correctness. Defaults to false.\n\n

\n

Example:\n\n

\n
var buf = new Buffer(8);\nbuf.writeDoubleBE(0xdeadbeefcafebabe, 0);\n\nconsole.log(buf);\n\nbuf.writeDoubleLE(0xdeadbeefcafebabe, 0);\n\nconsole.log(buf);\n\n// <Buffer 43 eb d5 b7 dd f9 5f d7>\n// <Buffer d7 5f f9 dd b7 d5 eb 43>
\n" + }, + { + "textRaw": "buf.writeDoubleBE(value, offset, [noAssert])", + "type": "method", + "name": "writeDoubleBE", + "signatures": [ + { + "params": [ + { + "textRaw": "`value` Number ", + "name": "value", + "desc": "Number" + }, + { + "textRaw": "`offset` Number ", + "name": "offset", + "desc": "Number" + }, + { + "textRaw": "`noAssert` Boolean, Optional, Default: false ", + "name": "noAssert", + "desc": "Boolean, Optional, Default: false", + "optional": true + } + ] + }, + { + "params": [ + { + "name": "value" + }, + { + "name": "offset" + }, + { + "name": "noAssert", + "optional": true + } + ] + } + ], + "desc": "

Writes value to the buffer at the specified offset with specified endian\nformat. Note, value must be a valid 64 bit double.\n\n

\n

Set noAssert to true to skip validation of value and offset. This means\nthat value may be too large for the specific function and offset may be\nbeyond the end of the buffer leading to the values being silently dropped. This\nshould not be used unless you are certain of correctness. Defaults to false.\n\n

\n

Example:\n\n

\n
var buf = new Buffer(8);\nbuf.writeDoubleBE(0xdeadbeefcafebabe, 0);\n\nconsole.log(buf);\n\nbuf.writeDoubleLE(0xdeadbeefcafebabe, 0);\n\nconsole.log(buf);\n\n// <Buffer 43 eb d5 b7 dd f9 5f d7>\n// <Buffer d7 5f f9 dd b7 d5 eb 43>
\n" + }, + { + "textRaw": "buf.fill(value, [offset], [end])", + "type": "method", + "name": "fill", + "signatures": [ + { + "params": [ + { + "textRaw": "`value` ", + "name": "value" + }, + { + "textRaw": "`offset` Number, Optional ", + "name": "offset", + "optional": true, + "desc": "Number" + }, + { + "textRaw": "`end` Number, Optional ", + "name": "end", + "optional": true, + "desc": "Number" + } + ] + }, + { + "params": [ + { + "name": "value" + }, + { + "name": "offset", + "optional": true + }, + { + "name": "end", + "optional": true + } + ] + } + ], + "desc": "

Fills the buffer with the specified value. If the offset (defaults to 0)\nand end (defaults to buffer.length) are not given it will fill the entire\nbuffer.\n\n

\n
var b = new Buffer(50);\nb.fill("h");
\n" + } + ], + "properties": [ + { + "textRaw": "buf[index]", + "name": "[index]", + "desc": "

Get and set the octet at index. The values refer to individual bytes,\nso the legal range is between 0x00 and 0xFF hex or 0 and 255.\n\n

\n

Example: copy an ASCII string into a buffer, one byte at a time:\n\n

\n
str = "node.js";\nbuf = new Buffer(str.length);\n\nfor (var i = 0; i < str.length ; i++) {\n  buf[i] = str.charCodeAt(i);\n}\n\nconsole.log(buf);\n\n// node.js
\n" + }, + { + "textRaw": "`length` Number ", + "name": "length", + "desc": "

The size of the buffer in bytes. Note that this is not necessarily the size\nof the contents. length refers to the amount of memory allocated for the\nbuffer object. It does not change when the contents of the buffer are changed.\n\n

\n
buf = new Buffer(1234);\n\nconsole.log(buf.length);\nbuf.write("some string", 0, "ascii");\nconsole.log(buf.length);\n\n// 1234\n// 1234
\n", + "shortDesc": "Number" + } + ], + "classMethods": [ + { + "textRaw": "Class Method: Buffer.isBuffer(obj)", + "type": "classMethod", + "name": "isBuffer", + "signatures": [ + { + "return": { + "textRaw": "Return: Boolean ", + "name": "return", + "desc": "Boolean" + }, + "params": [ + { + "textRaw": "`obj` Object ", + "name": "obj", + "desc": "Object" + } + ] + }, + { + "params": [ + { + "name": "obj" + } + ] + } + ], + "desc": "

Tests if obj is a Buffer.\n\n

\n" + }, + { + "textRaw": "Class Method: Buffer.byteLength(string, [encoding])", + "type": "classMethod", + "name": "byteLength", + "signatures": [ + { + "return": { + "textRaw": "Return: Number ", + "name": "return", + "desc": "Number" + }, + "params": [ + { + "textRaw": "`string` String ", + "name": "string", + "desc": "String" + }, + { + "textRaw": "`encoding` String, Optional, Default: 'utf8' ", + "name": "encoding", + "desc": "String, Optional, Default: 'utf8'", + "optional": true + } + ] + }, + { + "params": [ + { + "name": "string" + }, + { + "name": "encoding", + "optional": true + } + ] + } + ], + "desc": "

Gives the actual byte length of a string. encoding defaults to 'utf8'.\nThis is not the same as String.prototype.length since that returns the\nnumber of characters in a string.\n\n

\n

Example:\n\n

\n
str = '\\u00bd + \\u00bc = \\u00be';\n\nconsole.log(str + ": " + str.length + " characters, " +\n  Buffer.byteLength(str, 'utf8') + " bytes");\n\n// ½ + ¼ = ¾: 9 characters, 12 bytes
\n" + }, + { + "textRaw": "Class Method: Buffer.concat(list, [totalLength])", + "type": "classMethod", + "name": "concat", + "signatures": [ + { + "params": [ + { + "textRaw": "`list` {Array} List of Buffer objects to concat ", + "name": "list", + "type": "Array", + "desc": "List of Buffer objects to concat" + }, + { + "textRaw": "`totalLength` {Number} Total length of the buffers when concatenated ", + "name": "totalLength", + "type": "Number", + "desc": "Total length of the buffers when concatenated", + "optional": true + } + ] + }, + { + "params": [ + { + "name": "list" + }, + { + "name": "totalLength", + "optional": true + } + ] + } + ], + "desc": "

Returns a buffer which is the result of concatenating all the buffers in\nthe list together.\n\n

\n

If the list has no items, or if the totalLength is 0, then it returns a\nzero-length buffer.\n\n

\n

If the list has exactly one item, then the first item of the list is\nreturned.\n\n

\n

If the list has more than one item, then a new Buffer is created.\n\n

\n

If totalLength is not provided, it is read from the buffers in the list.\nHowever, this adds an additional loop to the function, so it is faster\nto provide the length explicitly.\n\n

\n" + } + ], + "signatures": [ + { + "params": [ + { + "textRaw": "`size` Number ", + "name": "size", + "desc": "Number" + } + ], + "desc": "

Allocates a new buffer of size octets.\n\n

\n" + }, + { + "params": [ + { + "name": "size" + } + ], + "desc": "

Allocates a new buffer of size octets.\n\n

\n" + }, + { + "params": [ + { + "textRaw": "`array` Array ", + "name": "array", + "desc": "Array" + } + ], + "desc": "

Allocates a new buffer using an array of octets.\n\n

\n" + }, + { + "params": [ + { + "name": "array" + } + ], + "desc": "

Allocates a new buffer using an array of octets.\n\n

\n" + }, + { + "params": [ + { + "textRaw": "`str` String - string to encode. ", + "name": "str", + "desc": "String - string to encode." + }, + { + "textRaw": "`encoding` String - encoding to use, Optional. ", + "name": "encoding", + "desc": "String - encoding to use, Optional.", + "optional": true + } + ], + "desc": "

Allocates a new buffer containing the given str.\nencoding defaults to 'utf8'.\n\n

\n" + }, + { + "params": [ + { + "name": "str" + }, + { + "name": "encoding", + "optional": true + } + ], + "desc": "

Allocates a new buffer containing the given str.\nencoding defaults to 'utf8'.\n\n

\n" + } + ] + }, + { + "textRaw": "Class: SlowBuffer", + "type": "class", + "name": "SlowBuffer", + "desc": "

This class is primarily for internal use. JavaScript programs should\nuse Buffer instead of using SlowBuffer.\n\n

\n

In order to avoid the overhead of allocating many C++ Buffer objects for\nsmall blocks of memory in the lifetime of a server, Node allocates memory\nin 8Kb (8192 byte) chunks. If a buffer is smaller than this size, then it\nwill be backed by a parent SlowBuffer object. If it is larger than this,\nthen Node will allocate a SlowBuffer slab for it directly.\n\n

\n" + } + ], + "properties": [ + { + "textRaw": "`INSPECT_MAX_BYTES` Number, Default: 50 ", + "name": "INSPECT_MAX_BYTES", + "desc": "

How many bytes will be returned when buffer.inspect() is called. This can\nbe overridden by user modules.\n\n

\n

Note that this is a property on the buffer module returned by\nrequire('buffer'), not on the Buffer global, or a buffer instance.\n\n

\n", + "shortDesc": "Number, Default: 50" + } + ], + "type": "module", + "displayName": "Buffer" + }, + { + "textRaw": "Stream", + "name": "stream", + "stability": 2, + "stabilityText": "Unstable", + "desc": "

A stream is an abstract interface implemented by various objects in\nNode. For example a request to an HTTP server is a stream, as is\nstdout. Streams are readable, writable, or both. All streams are\ninstances of [EventEmitter][]\n\n

\n

You can load up the Stream base class by doing require('stream').\n\n

\n", + "classes": [ + { + "textRaw": "Readable Stream", + "name": "Readable Stream", + "type": "class", + "desc": "

A Readable Stream has the following methods, members, and events.\n\n

\n", + "events": [ + { + "textRaw": "Event: 'data'", + "type": "event", + "name": "data", + "desc": "

function (data) { }\n\n

\n

The 'data' event emits either a Buffer (by default) or a string if\nsetEncoding() was used.\n\n

\n

Note that the data will be lost if there is no listener when a\nReadable Stream emits a 'data' event.\n\n

\n", + "params": [] + }, + { + "textRaw": "Event: 'end'", + "type": "event", + "name": "end", + "desc": "

function () { }\n\n

\n

Emitted when the stream has received an EOF (FIN in TCP terminology).\nIndicates that no more 'data' events will happen. If the stream is\nalso writable, it may be possible to continue writing.\n\n

\n", + "params": [] + }, + { + "textRaw": "Event: 'error'", + "type": "event", + "name": "error", + "desc": "

function (exception) { }\n\n

\n

Emitted if there was an error receiving data.\n\n

\n", + "params": [] + }, + { + "textRaw": "Event: 'close'", + "type": "event", + "name": "close", + "desc": "

function () { }\n\n

\n

Emitted when the underlying resource (for example, the backing file\ndescriptor) has been closed. Not all streams will emit this.\n\n

\n", + "params": [] + } + ], + "properties": [ + { + "textRaw": "stream.readable", + "name": "readable", + "desc": "

A boolean that is true by default, but turns false after an\n'error' occurred, the stream came to an 'end', or destroy() was\ncalled.\n\n

\n" + } + ], + "methods": [ + { + "textRaw": "stream.setEncoding([encoding])", + "type": "method", + "name": "setEncoding", + "desc": "

Makes the 'data' event emit a string instead of a Buffer. encoding\ncan be 'utf8', 'utf16le' ('ucs2'), 'ascii', or 'hex'. Defaults\nto 'utf8'.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "encoding", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "stream.pause()", + "type": "method", + "name": "pause", + "desc": "

Issues an advisory signal to the underlying communication layer,\nrequesting that no further data be sent until resume() is called.\n\n

\n

Note that, due to the advisory nature, certain streams will not be\npaused immediately, and so 'data' events may be emitted for some\nindeterminate period of time even after pause() is called. You may\nwish to buffer such 'data' events.\n\n

\n", + "signatures": [ + { + "params": [] + } + ] + }, + { + "textRaw": "stream.resume()", + "type": "method", + "name": "resume", + "desc": "

Resumes the incoming 'data' events after a pause().\n\n

\n", + "signatures": [ + { + "params": [] + } + ] + }, + { + "textRaw": "stream.destroy()", + "type": "method", + "name": "destroy", + "desc": "

Closes the underlying file descriptor. Stream is no longer writable\nnor readable. The stream will not emit any more 'data', or 'end'\nevents. Any queued write data will not be sent. The stream should emit\n'close' event once its resources have been disposed of.\n\n\n

\n", + "signatures": [ + { + "params": [] + } + ] + }, + { + "textRaw": "stream.pipe(destination, [options])", + "type": "method", + "name": "pipe", + "desc": "

This is a Stream.prototype method available on all Streams.\n\n

\n

Connects this read stream to destination WriteStream. Incoming data on\nthis stream gets written to destination. The destination and source\nstreams are kept in sync by pausing and resuming as necessary.\n\n

\n

This function returns the destination stream.\n\n

\n

Emulating the Unix cat command:\n\n

\n
process.stdin.resume(); process.stdin.pipe(process.stdout);
\n

By default end() is called on the destination when the source stream\nemits end, so that destination is no longer writable. Pass { end:\nfalse } as options to keep the destination stream open.\n\n

\n

This keeps process.stdout open so that "Goodbye" can be written at the\nend.\n\n

\n
process.stdin.resume();\n\nprocess.stdin.pipe(process.stdout, { end: false });\n\nprocess.stdin.on("end", function() {\nprocess.stdout.write("Goodbye\\n"); });
\n", + "signatures": [ + { + "params": [ + { + "name": "destination" + }, + { + "name": "options", + "optional": true + } + ] + } + ] + } + ] + }, + { + "textRaw": "Writable Stream", + "name": "Writable Stream", + "type": "class", + "desc": "

A Writable Stream has the following methods, members, and events.\n\n

\n", + "events": [ + { + "textRaw": "Event: 'drain'", + "type": "event", + "name": "drain", + "desc": "

function () { }\n\n

\n

Emitted when the stream's write queue empties and it's safe to write without\nbuffering again. Listen for it when stream.write() returns false.\n\n

\n

The 'drain' event can happen at any time, regardless of whether or not\nstream.write() has previously returned false. To avoid receiving unwanted\n'drain' events, listen using stream.once().\n\n

\n", + "params": [] + }, + { + "textRaw": "Event: 'error'", + "type": "event", + "name": "error", + "desc": "

function (exception) { }\n\n

\n

Emitted on error with the exception exception.\n\n

\n", + "params": [] + }, + { + "textRaw": "Event: 'close'", + "type": "event", + "name": "close", + "desc": "

function () { }\n\n

\n

Emitted when the underlying file descriptor has been closed.\n\n

\n", + "params": [] + }, + { + "textRaw": "Event: 'pipe'", + "type": "event", + "name": "pipe", + "desc": "

function (src) { }\n\n

\n

Emitted when the stream is passed to a readable stream's pipe method.\n\n

\n", + "params": [] + } + ], + "properties": [ + { + "textRaw": "stream.writable", + "name": "writable", + "desc": "

A boolean that is true by default, but turns false after an\n'error' occurred or end() / destroy() was called.\n\n

\n" + } + ], + "methods": [ + { + "textRaw": "stream.write(string, [encoding])", + "type": "method", + "name": "write", + "desc": "

Writes string with the given encoding to the stream. Returns true\nif the string has been flushed to the kernel buffer. Returns false to\nindicate that the kernel buffer is full, and the data will be sent out\nin the future. The 'drain' event will indicate when the kernel buffer\nis empty again. The encoding defaults to 'utf8'.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "string" + }, + { + "name": "encoding", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "stream.write(buffer)", + "type": "method", + "name": "write", + "desc": "

Same as the above except with a raw buffer.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "buffer" + } + ] + } + ] + }, + { + "textRaw": "stream.end()", + "type": "method", + "name": "end", + "desc": "

Terminates the stream with EOF or FIN. This call will allow queued\nwrite data to be sent before closing the stream.\n\n

\n", + "signatures": [ + { + "params": [] + } + ] + }, + { + "textRaw": "stream.end(string, encoding)", + "type": "method", + "name": "end", + "desc": "

Sends string with the given encoding and terminates the stream with\nEOF or FIN. This is useful to reduce the number of packets sent.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "string" + }, + { + "name": "encoding" + } + ] + } + ] + }, + { + "textRaw": "stream.end(buffer)", + "type": "method", + "name": "end", + "desc": "

Same as above but with a buffer.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "buffer" + } + ] + } + ] + }, + { + "textRaw": "stream.destroy()", + "type": "method", + "name": "destroy", + "desc": "

Closes the underlying file descriptor. Stream is no longer writable\nnor readable. The stream will not emit any more 'data', or 'end'\nevents. Any queued write data will not be sent. The stream should emit\n'close' event once its resources have been disposed of.\n\n

\n", + "signatures": [ + { + "params": [] + } + ] + }, + { + "textRaw": "stream.destroySoon()", + "type": "method", + "name": "destroySoon", + "desc": "

After the write queue is drained, close the file descriptor.\ndestroySoon() can still destroy straight away, as long as there is no\ndata left in the queue for writes.\n\n

\n", + "signatures": [ + { + "params": [] + } + ] + } + ] + } + ], + "type": "module", + "displayName": "Stream" + }, + { + "textRaw": "Crypto", + "name": "crypto", + "desc": "
Stability: 2 - Unstable; API changes are being discussed for\nfuture versions.  Breaking changes will be minimized.  See below.
\n

Use require('crypto') to access this module.\n\n

\n

The crypto module requires OpenSSL to be available on the underlying platform.\nIt offers a way of encapsulating secure credentials to be used as part\nof a secure HTTPS net or http connection.\n\n

\n

It also offers a set of wrappers for OpenSSL's hash, hmac, cipher, decipher, sign and verify methods.\n\n

\n", + "methods": [ + { + "textRaw": "crypto.createCredentials(details)", + "type": "method", + "name": "createCredentials", + "desc": "

Creates a credentials object, with the optional details being a dictionary with keys:\n\n

\n
    \n
  • pfx : A string or buffer holding the PFX or PKCS12 encoded private key, certificate and CA certificates
  • \n
  • key : A string holding the PEM encoded private key
  • \n
  • passphrase : A string of passphrase for the private key or pfx
  • \n
  • cert : A string holding the PEM encoded certificate
  • \n
  • ca : Either a string or list of strings of PEM encoded CA certificates to trust.
  • \n
  • crl : Either a string or list of strings of PEM encoded CRLs (Certificate Revocation List)
  • \n
  • ciphers: A string describing the ciphers to use or exclude. Consult\nhttp://www.openssl.org/docs/apps/ciphers.html#CIPHER_LIST_FORMAT for details\non the format.
  • \n
\n

If no 'ca' details are given, then node.js will use the default publicly trusted list of CAs as given in\n

\n

http://mxr.mozilla.org/mozilla/source/security/nss/lib/ckfw/builtins/certdata.txt.\n\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "details" + } + ] + } + ] + }, + { + "textRaw": "crypto.createHash(algorithm)", + "type": "method", + "name": "createHash", + "desc": "

Creates and returns a hash object, a cryptographic hash with the given algorithm\nwhich can be used to generate hash digests.\n\n

\n

algorithm is dependent on the available algorithms supported by the version\nof OpenSSL on the platform. Examples are 'sha1', 'md5', 'sha256', 'sha512', etc.\nOn recent releases, openssl list-message-digest-algorithms will display the available digest algorithms.\n\n

\n

Example: this program that takes the sha1 sum of a file\n\n

\n
var filename = process.argv[2];\nvar crypto = require('crypto');\nvar fs = require('fs');\n\nvar shasum = crypto.createHash('sha1');\n\nvar s = fs.ReadStream(filename);\ns.on('data', function(d) {\n  shasum.update(d);\n});\n\ns.on('end', function() {\n  var d = shasum.digest('hex');\n  console.log(d + '  ' + filename);\n});
\n", + "signatures": [ + { + "params": [ + { + "name": "algorithm" + } + ] + } + ] + }, + { + "textRaw": "crypto.createHmac(algorithm, key)", + "type": "method", + "name": "createHmac", + "desc": "

Creates and returns a hmac object, a cryptographic hmac with the given algorithm and key.\n\n

\n

algorithm is dependent on the available algorithms supported by OpenSSL - see createHash above.\nkey is the hmac key to be used.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "algorithm" + }, + { + "name": "key" + } + ] + } + ] + }, + { + "textRaw": "crypto.createCipher(algorithm, password)", + "type": "method", + "name": "createCipher", + "desc": "

Creates and returns a cipher object, with the given algorithm and password.\n\n

\n

algorithm is dependent on OpenSSL, examples are 'aes192', etc.\nOn recent releases, openssl list-cipher-algorithms will display the\navailable cipher algorithms.\npassword is used to derive key and IV, which must be a 'binary' encoded\nstring or a buffer.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "algorithm" + }, + { + "name": "password" + } + ] + } + ] + }, + { + "textRaw": "crypto.createCipheriv(algorithm, key, iv)", + "type": "method", + "name": "createCipheriv", + "desc": "

Creates and returns a cipher object, with the given algorithm, key and iv.\n\n

\n

algorithm is the same as the argument to createCipher().\nkey is the raw key used by the algorithm.\niv is an initialization\nvector.\n\n

\n

key and iv must be 'binary' encoded strings or buffers.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "algorithm" + }, + { + "name": "key" + }, + { + "name": "iv" + } + ] + } + ] + }, + { + "textRaw": "crypto.createDecipher(algorithm, password)", + "type": "method", + "name": "createDecipher", + "desc": "

Creates and returns a decipher object, with the given algorithm and key.\nThis is the mirror of the [createCipher()][] above.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "algorithm" + }, + { + "name": "password" + } + ] + } + ] + }, + { + "textRaw": "crypto.createDecipheriv(algorithm, key, iv)", + "type": "method", + "name": "createDecipheriv", + "desc": "

Creates and returns a decipher object, with the given algorithm, key and iv.\nThis is the mirror of the [createCipheriv()][] above.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "algorithm" + }, + { + "name": "key" + }, + { + "name": "iv" + } + ] + } + ] + }, + { + "textRaw": "crypto.createSign(algorithm)", + "type": "method", + "name": "createSign", + "desc": "

Creates and returns a signing object, with the given algorithm.\nOn recent OpenSSL releases, openssl list-public-key-algorithms will display\nthe available signing algorithms. Examples are 'RSA-SHA256'.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "algorithm" + } + ] + } + ] + }, + { + "textRaw": "crypto.createVerify(algorithm)", + "type": "method", + "name": "createVerify", + "desc": "

Creates and returns a verification object, with the given algorithm.\nThis is the mirror of the signing object above.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "algorithm" + } + ] + } + ] + }, + { + "textRaw": "crypto.createDiffieHellman(prime_length)", + "type": "method", + "name": "createDiffieHellman", + "desc": "

Creates a Diffie-Hellman key exchange object and generates a prime of the\ngiven bit length. The generator used is 2.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "prime_length" + } + ] + } + ] + }, + { + "textRaw": "crypto.createDiffieHellman(prime, [encoding])", + "type": "method", + "name": "createDiffieHellman", + "desc": "

Creates a Diffie-Hellman key exchange object using the supplied prime. The\ngenerator used is 2. Encoding can be 'binary', 'hex', or 'base64'.\nDefaults to 'binary'.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "prime" + }, + { + "name": "encoding", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "crypto.getDiffieHellman(group_name)", + "type": "method", + "name": "getDiffieHellman", + "desc": "

Creates a predefined Diffie-Hellman key exchange object.\nThe supported groups are: 'modp1', 'modp2', 'modp5'\n(defined in [RFC 2412][])\nand 'modp14', 'modp15', 'modp16', 'modp17', 'modp18'\n(defined in [RFC 3526][]).\nThe returned object mimics the interface of objects created by\n[crypto.createDiffieHellman()][] above, but\nwill not allow to change the keys (with\n[diffieHellman.setPublicKey()][] for example).\nThe advantage of using this routine is that the parties don't have to\ngenerate nor exchange group modulus beforehand, saving both processor and\ncommunication time.\n\n

\n

Example (obtaining a shared secret):\n\n

\n
var crypto = require('crypto');\nvar alice = crypto.getDiffieHellman('modp5');\nvar bob = crypto.getDiffieHellman('modp5');\n\nalice.generateKeys();\nbob.generateKeys();\n\nvar alice_secret = alice.computeSecret(bob.getPublicKey(), 'binary', 'hex');\nvar bob_secret = bob.computeSecret(alice.getPublicKey(), 'binary', 'hex');\n\n/* alice_secret and bob_secret should be the same */\nconsole.log(alice_secret == bob_secret);
\n", + "signatures": [ + { + "params": [ + { + "name": "group_name" + } + ] + } + ] + }, + { + "textRaw": "crypto.pbkdf2(password, salt, iterations, keylen, callback)", + "type": "method", + "name": "pbkdf2", + "desc": "

Asynchronous PBKDF2 applies pseudorandom function HMAC-SHA1 to derive\na key of given length from the given password, salt and iterations.\nThe callback gets two arguments (err, derivedKey).\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "password" + }, + { + "name": "salt" + }, + { + "name": "iterations" + }, + { + "name": "keylen" + }, + { + "name": "callback" + } + ] + } + ] + }, + { + "textRaw": "crypto.randomBytes(size, [callback])", + "type": "method", + "name": "randomBytes", + "desc": "

Generates cryptographically strong pseudo-random data. Usage:\n\n

\n
// async\ncrypto.randomBytes(256, function(ex, buf) {\n  if (ex) throw ex;\n  console.log('Have %d bytes of random data: %s', buf.length, buf);\n});\n\n// sync\ntry {\n  var buf = crypto.randomBytes(256);\n  console.log('Have %d bytes of random data: %s', buf.length, buf);\n} catch (ex) {\n  // handle error\n}
\n", + "signatures": [ + { + "params": [ + { + "name": "size" + }, + { + "name": "callback", + "optional": true + } + ] + } + ] + } + ], + "classes": [ + { + "textRaw": "Class: Hash", + "type": "class", + "name": "Hash", + "desc": "

The class for creating hash digests of data.\n\n

\n

Returned by crypto.createHash.\n\n

\n", + "methods": [ + { + "textRaw": "hash.update(data, [input_encoding])", + "type": "method", + "name": "update", + "desc": "

Updates the hash content with the given data, the encoding of which is given\nin input_encoding and can be 'utf8', 'ascii' or 'binary'.\nDefaults to 'binary'.\nThis can be called many times with new data as it is streamed.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "data" + }, + { + "name": "input_encoding", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "hash.digest([encoding])", + "type": "method", + "name": "digest", + "desc": "

Calculates the digest of all of the passed data to be hashed.\nThe encoding can be 'hex', 'binary' or 'base64'.\nDefaults to 'binary'.\n\n

\n

Note: hash object can not be used after digest() method been called.\n\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "encoding", + "optional": true + } + ] + } + ] + } + ] + }, + { + "textRaw": "Class: Hmac", + "type": "class", + "name": "Hmac", + "desc": "

Class for creating cryptographic hmac content.\n\n

\n

Returned by crypto.createHmac.\n\n

\n", + "methods": [ + { + "textRaw": "hmac.update(data)", + "type": "method", + "name": "update", + "desc": "

Update the hmac content with the given data.\nThis can be called many times with new data as it is streamed.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "data" + } + ] + } + ] + }, + { + "textRaw": "hmac.digest([encoding])", + "type": "method", + "name": "digest", + "desc": "

Calculates the digest of all of the passed data to the hmac.\nThe encoding can be 'hex', 'binary' or 'base64'.\nDefaults to 'binary'.\n\n

\n

Note: hmac object can not be used after digest() method been called.\n\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "encoding", + "optional": true + } + ] + } + ] + } + ] + }, + { + "textRaw": "Class: Cipher", + "type": "class", + "name": "Cipher", + "desc": "

Class for encrypting data.\n\n

\n

Returned by crypto.createCipher and crypto.createCipheriv.\n\n

\n", + "methods": [ + { + "textRaw": "cipher.update(data, [input_encoding], [output_encoding])", + "type": "method", + "name": "update", + "desc": "

Updates the cipher with data, the encoding of which is given in\ninput_encoding and can be 'utf8', 'ascii' or 'binary'.\nDefaults to 'binary'.\n\n

\n

The output_encoding specifies the output format of the enciphered data,\nand can be 'binary', 'base64' or 'hex'. Defaults to 'binary'.\n\n

\n

Returns the enciphered contents, and can be called many times with new data as it is streamed.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "data" + }, + { + "name": "input_encoding", + "optional": true + }, + { + "name": "output_encoding", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "cipher.final([output_encoding])", + "type": "method", + "name": "final", + "desc": "

Returns any remaining enciphered contents, with output_encoding being one of:\n'binary', 'base64' or 'hex'. Defaults to 'binary'.\n\n

\n

Note: cipher object can not be used after final() method been called.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "output_encoding", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "cipher.setAutoPadding(auto_padding=true)", + "type": "method", + "name": "setAutoPadding", + "desc": "

You can disable automatic padding of the input data to block size. If auto_padding is false,\nthe length of the entire input data must be a multiple of the cipher's block size or final will fail.\nUseful for non-standard padding, e.g. using 0x0 instead of PKCS padding. You must call this before cipher.final.\n\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "auto_padding", + "default": "true" + } + ] + } + ] + } + ] + }, + { + "textRaw": "Class: Decipher", + "type": "class", + "name": "Decipher", + "desc": "

Class for decrypting data.\n\n

\n

Returned by crypto.createDecipher and crypto.createDecipheriv.\n\n

\n", + "methods": [ + { + "textRaw": "decipher.update(data, [input_encoding], [output_encoding])", + "type": "method", + "name": "update", + "desc": "

Updates the decipher with data, which is encoded in 'binary', 'base64'\nor 'hex'. Defaults to 'binary'.\n\n

\n

The output_decoding specifies in what format to return the deciphered\nplaintext: 'binary', 'ascii' or 'utf8'. Defaults to 'binary'.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "data" + }, + { + "name": "input_encoding", + "optional": true + }, + { + "name": "output_encoding", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "decipher.final([output_encoding])", + "type": "method", + "name": "final", + "desc": "

Returns any remaining plaintext which is deciphered,\nwith output_encoding being one of: 'binary', 'ascii' or 'utf8'.\nDefaults to 'binary'.\n\n

\n

Note: decipher object can not be used after final() method been called.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "output_encoding", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "decipher.setAutoPadding(auto_padding=true)", + "type": "method", + "name": "setAutoPadding", + "desc": "

You can disable auto padding if the data has been encrypted without standard block padding to prevent\ndecipher.final from checking and removing it. Can only work if the input data's length is a multiple of the\nciphers block size. You must call this before streaming data to decipher.update.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "auto_padding", + "default": "true" + } + ] + } + ] + } + ] + }, + { + "textRaw": "Class: Signer", + "type": "class", + "name": "Signer", + "desc": "

Class for generating signatures.\n\n

\n

Returned by crypto.createSign.\n\n

\n", + "methods": [ + { + "textRaw": "signer.update(data)", + "type": "method", + "name": "update", + "desc": "

Updates the signer object with data.\nThis can be called many times with new data as it is streamed.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "data" + } + ] + } + ] + }, + { + "textRaw": "signer.sign(private_key, [output_format])", + "type": "method", + "name": "sign", + "desc": "

Calculates the signature on all the updated data passed through the signer.\nprivate_key is a string containing the PEM encoded private key for signing.\n\n

\n

Returns the signature in output_format which can be 'binary', 'hex' or\n'base64'. Defaults to 'binary'.\n\n

\n

Note: signer object can not be used after sign() method been called.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "private_key" + }, + { + "name": "output_format", + "optional": true + } + ] + } + ] + } + ] + }, + { + "textRaw": "Class: Verify", + "type": "class", + "name": "Verify", + "desc": "

Class for verifying signatures.\n\n

\n

Returned by crypto.createVerify.\n\n

\n", + "methods": [ + { + "textRaw": "verifier.update(data)", + "type": "method", + "name": "update", + "desc": "

Updates the verifier object with data.\nThis can be called many times with new data as it is streamed.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "data" + } + ] + } + ] + }, + { + "textRaw": "verifier.verify(object, signature, [signature_format])", + "type": "method", + "name": "verify", + "desc": "

Verifies the signed data by using the object and signature. object is a\nstring containing a PEM encoded object, which can be one of RSA public key,\nDSA public key, or X.509 certificate. signature is the previously calculated\nsignature for the data, in the signature_format which can be 'binary',\n'hex' or 'base64'. Defaults to 'binary'.\n\n

\n

Returns true or false depending on the validity of the signature for the data and public key.\n\n

\n

Note: verifier object can not be used after verify() method been called.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "object" + }, + { + "name": "signature" + }, + { + "name": "signature_format", + "optional": true + } + ] + } + ] + } + ] + }, + { + "textRaw": "Class: DiffieHellman", + "type": "class", + "name": "DiffieHellman", + "desc": "

The class for creating Diffie-Hellman key exchanges.\n\n

\n

Returned by crypto.createDiffieHellman.\n\n

\n", + "methods": [ + { + "textRaw": "diffieHellman.generateKeys([encoding])", + "type": "method", + "name": "generateKeys", + "desc": "

Generates private and public Diffie-Hellman key values, and returns the\npublic key in the specified encoding. This key should be transferred to the\nother party. Encoding can be 'binary', 'hex', or 'base64'.\nDefaults to 'binary'.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "encoding", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "diffieHellman.computeSecret(other_public_key, [input_encoding], [output_encoding])", + "type": "method", + "name": "computeSecret", + "desc": "

Computes the shared secret using other_public_key as the other party's\npublic key and returns the computed shared secret. Supplied key is\ninterpreted using specified input_encoding, and secret is encoded using\nspecified output_encoding. Encodings can be 'binary', 'hex', or\n'base64'. The input encoding defaults to 'binary'.\nIf no output encoding is given, the input encoding is used as output encoding.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "other_public_key" + }, + { + "name": "input_encoding", + "optional": true + }, + { + "name": "output_encoding", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "diffieHellman.getPrime([encoding])", + "type": "method", + "name": "getPrime", + "desc": "

Returns the Diffie-Hellman prime in the specified encoding, which can be\n'binary', 'hex', or 'base64'. Defaults to 'binary'.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "encoding", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "diffieHellman.getGenerator([encoding])", + "type": "method", + "name": "getGenerator", + "desc": "

Returns the Diffie-Hellman prime in the specified encoding, which can be\n'binary', 'hex', or 'base64'. Defaults to 'binary'.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "encoding", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "diffieHellman.getPublicKey([encoding])", + "type": "method", + "name": "getPublicKey", + "desc": "

Returns the Diffie-Hellman public key in the specified encoding, which can\nbe 'binary', 'hex', or 'base64'. Defaults to 'binary'.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "encoding", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "diffieHellman.getPrivateKey([encoding])", + "type": "method", + "name": "getPrivateKey", + "desc": "

Returns the Diffie-Hellman private key in the specified encoding, which can\nbe 'binary', 'hex', or 'base64'. Defaults to 'binary'.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "encoding", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "diffieHellman.setPublicKey(public_key, [encoding])", + "type": "method", + "name": "setPublicKey", + "desc": "

Sets the Diffie-Hellman public key. Key encoding can be 'binary', 'hex',\nor 'base64'. Defaults to 'binary'.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "public_key" + }, + { + "name": "encoding", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "diffieHellman.setPrivateKey(public_key, [encoding])", + "type": "method", + "name": "setPrivateKey", + "desc": "

Sets the Diffie-Hellman private key. Key encoding can be 'binary', 'hex',\nor 'base64'. Defaults to 'binary'.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "public_key" + }, + { + "name": "encoding", + "optional": true + } + ] + } + ] + } + ] + } + ], + "modules": [ + { + "textRaw": "Proposed API Changes in Future Versions of Node", + "name": "proposed_api_changes_in_future_versions_of_node", + "desc": "

The Crypto module was added to Node before there was the concept of a\nunified Stream API, and before there were Buffer objects for handling\nbinary data.\n\n

\n

As such, the streaming classes don't have the typical methods found on\nother Node classes, and many methods accept and return Binary-encoded\nstrings by default rather than Buffers.\n\n

\n

A future version of node will make Buffers the default data type.\nThis will be a breaking change for some use cases, but not all.\n\n

\n

For example, if you currently use the default arguments to the Sign\nclass, and then pass the results to the Verify class, without ever\ninspecting the data, then it will continue to work as before. Where\nyou now get a binary string and then present the binary string to the\nVerify object, you'll get a Buffer, and present the Buffer to the\nVerify object.\n\n

\n

However, if you are doing things with the string data that will not\nwork properly on Buffers (such as, concatenating them, storing in\ndatabases, etc.), or you are passing binary strings to the crypto\nfunctions without an encoding argument, then you will need to start\nproviding encoding arguments to specify which encoding you'd like to\nuse.\n\n

\n

Also, a Streaming API will be provided, but this will be done in such\na way as to preserve the legacy API surface.\n\n\n

\n", + "type": "module", + "displayName": "Proposed API Changes in Future Versions of Node" + } + ], + "type": "module", + "displayName": "Crypto" + }, + { + "textRaw": "TLS (SSL)", + "name": "tls_(ssl)", + "stability": 3, + "stabilityText": "Stable", + "desc": "

Use require('tls') to access this module.\n\n

\n

The tls module uses OpenSSL to provide Transport Layer Security and/or\nSecure Socket Layer: encrypted stream communication.\n\n

\n

TLS/SSL is a public/private key infrastructure. Each client and each\nserver must have a private key. A private key is created like this\n\n

\n
openssl genrsa -out ryans-key.pem 1024
\n

All severs and some clients need to have a certificate. Certificates are public\nkeys signed by a Certificate Authority or self-signed. The first step to\ngetting a certificate is to create a "Certificate Signing Request" (CSR)\nfile. This is done with:\n\n

\n
openssl req -new -key ryans-key.pem -out ryans-csr.pem
\n

To create a self-signed certificate with the CSR, do this:\n\n

\n
openssl x509 -req -in ryans-csr.pem -signkey ryans-key.pem -out ryans-cert.pem
\n

Alternatively you can send the CSR to a Certificate Authority for signing.\n\n

\n

(TODO: docs on creating a CA, for now interested users should just look at\ntest/fixtures/keys/Makefile in the Node source code)\n\n

\n

To create .pfx or .p12, do this:\n\n

\n
openssl pkcs12 -export -in agent5-cert.pem -inkey agent5-key.pem \\\n    -certfile ca-cert.pem -out agent5.pfx
\n
    \n
  • in: certificate
  • \n
  • inkey: private key
  • \n
  • certfile: all CA certs concatenated in one file like\ncat ca1-cert.pem ca2-cert.pem > ca-cert.pem
  • \n
\n", + "miscs": [ + { + "textRaw": "Client-initiated renegotiation attack mitigation", + "name": "Client-initiated renegotiation attack mitigation", + "type": "misc", + "desc": "

The TLS protocol lets the client renegotiate certain aspects of the TLS session.\nUnfortunately, session renegotiation requires a disproportional amount of\nserver-side resources, which makes it a potential vector for denial-of-service\nattacks.\n\n

\n

To mitigate this, renegotiations are limited to three times every 10 minutes. An\nerror is emitted on the [CleartextStream][] instance when the threshold is\nexceeded. The limits are configurable:\n\n

\n
    \n
  • tls.CLIENT_RENEG_LIMIT: renegotiation limit, default is 3.

    \n
  • \n
  • tls.CLIENT_RENEG_WINDOW: renegotiation window in seconds, default is

    \n
                           10 minutes.
    \n
  • \n
\n

Don't change the defaults unless you know what you are doing.\n\n

\n

To test your server, connect to it with openssl s_client -connect address:port\nand tap R<CR> (that's the letter R followed by a carriage return) a few\ntimes.\n\n\n

\n" + }, + { + "textRaw": "NPN and SNI", + "name": "NPN and SNI", + "type": "misc", + "desc": "

NPN (Next Protocol Negotiation) and SNI (Server Name Indication) are TLS\nhandshake extensions allowing you:\n\n

\n
    \n
  • NPN - to use one TLS server for multiple protocols (HTTP, SPDY)
  • \n
  • SNI - to use one TLS server for multiple hostnames with different SSL\ncertificates.
  • \n
\n" + } + ], + "methods": [ + { + "textRaw": "tls.createServer(options, [secureConnectionListener])", + "type": "method", + "name": "createServer", + "desc": "

Creates a new [tls.Server][]. The connectionListener argument is\nautomatically set as a listener for the [secureConnection][] event. The\noptions object has these possibilities:\n\n

\n
    \n
  • pfx: A string or Buffer containing the private key, certificate and\nCA certs of the server in PFX or PKCS12 format. (Mutually exclusive with\nthe key, cert and ca options.)

    \n
  • \n
  • key: A string or Buffer containing the private key of the server in\nPEM format. (Required)

    \n
  • \n
  • passphrase: A string of passphrase for the private key or pfx.

    \n
  • \n
  • cert: A string or Buffer containing the certificate key of the server in\nPEM format. (Required)

    \n
  • \n
  • ca: An array of strings or Buffers of trusted certificates. If this is\nomitted several well known "root" CAs will be used, like VeriSign.\nThese are used to authorize connections.

    \n
  • \n
  • crl : Either a string or list of strings of PEM encoded CRLs (Certificate\nRevocation List)

    \n
  • \n
  • ciphers: A string describing the ciphers to use or exclude.

    \n

    To mitigate [BEAST attacks] it is recommended that you use this option in\nconjunction with the honorCipherOrder option described below to\nprioritize the non-CBC cipher.

    \n

    Defaults to\nECDHE-RSA-AES128-SHA256:AES128-GCM-SHA256:RC4:HIGH:!MD5:!aNULL:!EDH.\nConsult the [OpenSSL cipher list format documentation] for details on the\nformat.

    \n

    ECDHE-RSA-AES128-SHA256 and AES128-GCM-SHA256 are used when node.js is\nlinked against OpenSSL 1.0.1 or newer and the client speaks TLS 1.2, RC4 is\nused as a secure fallback.

    \n

    NOTE: Previous revisions of this section suggested AES256-SHA as an\nacceptable cipher. Unfortunately, AES256-SHA is a CBC cipher and therefore\nsusceptible to BEAST attacks. Do not use it.

    \n
  • \n
  • honorCipherOrder : When choosing a cipher, use the server's preferences\ninstead of the client preferences.

    \n

    Note that if SSLv2 is used, the server will send its list of preferences\nto the client, and the client chooses the cipher.

    \n

    Although, this option is disabled by default, it is recommended that you\nuse this option in conjunction with the ciphers option to mitigate\nBEAST attacks.

    \n
  • \n
  • requestCert: If true the server will request a certificate from\nclients that connect and attempt to verify that certificate. Default:\nfalse.

    \n
  • \n
  • rejectUnauthorized: If true the server will reject any connection\nwhich is not authorized with the list of supplied CAs. This option only\nhas an effect if requestCert is true. Default: false.

    \n
  • \n
  • NPNProtocols: An array or Buffer of possible NPN protocols. (Protocols\nshould be ordered by their priority).

    \n
  • \n
  • SNICallback: A function that will be called if client supports SNI TLS\nextension. Only one argument will be passed to it: servername. And\nSNICallback should return SecureContext instance.\n(You can use crypto.createCredentials(...).context to get proper\nSecureContext). If SNICallback wasn't provided - default callback with\nhigh-level API will be used (see below).

    \n
  • \n
  • sessionIdContext: A string containing a opaque identifier for session\nresumption. If requestCert is true, the default is MD5 hash value\ngenerated from command-line. Otherwise, the default is not provided.

    \n
  • \n
\n

Here is a simple example echo server:\n\n

\n
var tls = require('tls');\nvar fs = require('fs');\n\nvar options = {\n  key: fs.readFileSync('server-key.pem'),\n  cert: fs.readFileSync('server-cert.pem'),\n\n  // This is necessary only if using the client certificate authentication.\n  requestCert: true,\n\n  // This is necessary only if the client uses the self-signed certificate.\n  ca: [ fs.readFileSync('client-cert.pem') ]\n};\n\nvar server = tls.createServer(options, function(cleartextStream) {\n  console.log('server connected',\n              cleartextStream.authorized ? 'authorized' : 'unauthorized');\n  cleartextStream.write("welcome!\\n");\n  cleartextStream.setEncoding('utf8');\n  cleartextStream.pipe(cleartextStream);\n});\nserver.listen(8000, function() {\n  console.log('server bound');\n});
\n

Or\n\n

\n
var tls = require('tls');\nvar fs = require('fs');\n\nvar options = {\n  pfx: fs.readFileSync('server.pfx'),\n\n  // This is necessary only if using the client certificate authentication.\n  requestCert: true,\n\n};\n\nvar server = tls.createServer(options, function(cleartextStream) {\n  console.log('server connected',\n              cleartextStream.authorized ? 'authorized' : 'unauthorized');\n  cleartextStream.write("welcome!\\n");\n  cleartextStream.setEncoding('utf8');\n  cleartextStream.pipe(cleartextStream);\n});\nserver.listen(8000, function() {\n  console.log('server bound');\n});
\n

You can test this server by connecting to it with openssl s_client:\n\n\n

\n
openssl s_client -connect 127.0.0.1:8000
\n", + "signatures": [ + { + "params": [ + { + "name": "options" + }, + { + "name": "secureConnectionListener", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "tls.connect(options, [callback])", + "type": "method", + "name": "connect", + "desc": "

Creates a new client connection to the given port and host (old API) or\noptions.port and options.host. (If host is omitted, it defaults to\nlocalhost.) options should be an object which specifies:\n\n

\n
    \n
  • host: Host the client should connect to

    \n
  • \n
  • port: Port the client should connect to

    \n
  • \n
  • socket: Establish secure connection on a given socket rather than\ncreating a new socket. If this option is specified, host and port\nare ignored.

    \n
  • \n
  • pfx: A string or Buffer containing the private key, certificate and\nCA certs of the server in PFX or PKCS12 format.

    \n
  • \n
  • key: A string or Buffer containing the private key of the client in\nPEM format.

    \n
  • \n
  • passphrase: A string of passphrase for the private key or pfx.

    \n
  • \n
  • cert: A string or Buffer containing the certificate key of the client in\nPEM format.

    \n
  • \n
  • ca: An array of strings or Buffers of trusted certificates. If this is\nomitted several well known "root" CAs will be used, like VeriSign.\nThese are used to authorize connections.

    \n
  • \n
  • rejectUnauthorized: If true, the server certificate is verified against\nthe list of supplied CAs. An 'error' event is emitted if verification\nfails. Default: false.

    \n
  • \n
  • NPNProtocols: An array of string or Buffer containing supported NPN\nprotocols. Buffer should have following format: 0x05hello0x05world,\nwhere first byte is next protocol name's length. (Passing array should\nusually be much simpler: ['hello', 'world'].)

    \n
  • \n
  • servername: Servername for SNI (Server Name Indication) TLS extension.

    \n
  • \n
\n

The callback parameter will be added as a listener for the\n['secureConnect'][] event.\n\n

\n

tls.connect() returns a [CleartextStream][] object.\n\n

\n

Here is an example of a client of echo server as described previously:\n\n

\n
var tls = require('tls');\nvar fs = require('fs');\n\nvar options = {\n  // These are necessary only if using the client certificate authentication\n  key: fs.readFileSync('client-key.pem'),\n  cert: fs.readFileSync('client-cert.pem'),\n\n  // This is necessary only if the server uses the self-signed certificate\n  ca: [ fs.readFileSync('server-cert.pem') ]\n};\n\nvar cleartextStream = tls.connect(8000, options, function() {\n  console.log('client connected',\n              cleartextStream.authorized ? 'authorized' : 'unauthorized');\n  process.stdin.pipe(cleartextStream);\n  process.stdin.resume();\n});\ncleartextStream.setEncoding('utf8');\ncleartextStream.on('data', function(data) {\n  console.log(data);\n});\ncleartextStream.on('end', function() {\n  server.close();\n});
\n

Or\n\n

\n
var tls = require('tls');\nvar fs = require('fs');\n\nvar options = {\n  pfx: fs.readFileSync('client.pfx')\n};\n\nvar cleartextStream = tls.connect(8000, options, function() {\n  console.log('client connected',\n              cleartextStream.authorized ? 'authorized' : 'unauthorized');\n  process.stdin.pipe(cleartextStream);\n  process.stdin.resume();\n});\ncleartextStream.setEncoding('utf8');\ncleartextStream.on('data', function(data) {\n  console.log(data);\n});\ncleartextStream.on('end', function() {\n  server.close();\n});
\n", + "signatures": [ + { + "params": [ + { + "name": "port" + }, + { + "name": "host", + "optional": true + }, + { + "name": "options", + "optional": true + }, + { + "name": "callback", + "optional": true + } + ] + }, + { + "params": [ + { + "name": "options" + }, + { + "name": "callback", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "tls.connect(port, [host], [options], [callback])", + "type": "method", + "name": "connect", + "desc": "

Creates a new client connection to the given port and host (old API) or\noptions.port and options.host. (If host is omitted, it defaults to\nlocalhost.) options should be an object which specifies:\n\n

\n
    \n
  • host: Host the client should connect to

    \n
  • \n
  • port: Port the client should connect to

    \n
  • \n
  • socket: Establish secure connection on a given socket rather than\ncreating a new socket. If this option is specified, host and port\nare ignored.

    \n
  • \n
  • pfx: A string or Buffer containing the private key, certificate and\nCA certs of the server in PFX or PKCS12 format.

    \n
  • \n
  • key: A string or Buffer containing the private key of the client in\nPEM format.

    \n
  • \n
  • passphrase: A string of passphrase for the private key or pfx.

    \n
  • \n
  • cert: A string or Buffer containing the certificate key of the client in\nPEM format.

    \n
  • \n
  • ca: An array of strings or Buffers of trusted certificates. If this is\nomitted several well known "root" CAs will be used, like VeriSign.\nThese are used to authorize connections.

    \n
  • \n
  • rejectUnauthorized: If true, the server certificate is verified against\nthe list of supplied CAs. An 'error' event is emitted if verification\nfails. Default: false.

    \n
  • \n
  • NPNProtocols: An array of string or Buffer containing supported NPN\nprotocols. Buffer should have following format: 0x05hello0x05world,\nwhere first byte is next protocol name's length. (Passing array should\nusually be much simpler: ['hello', 'world'].)

    \n
  • \n
  • servername: Servername for SNI (Server Name Indication) TLS extension.

    \n
  • \n
\n

The callback parameter will be added as a listener for the\n['secureConnect'][] event.\n\n

\n

tls.connect() returns a [CleartextStream][] object.\n\n

\n

Here is an example of a client of echo server as described previously:\n\n

\n
var tls = require('tls');\nvar fs = require('fs');\n\nvar options = {\n  // These are necessary only if using the client certificate authentication\n  key: fs.readFileSync('client-key.pem'),\n  cert: fs.readFileSync('client-cert.pem'),\n\n  // This is necessary only if the server uses the self-signed certificate\n  ca: [ fs.readFileSync('server-cert.pem') ]\n};\n\nvar cleartextStream = tls.connect(8000, options, function() {\n  console.log('client connected',\n              cleartextStream.authorized ? 'authorized' : 'unauthorized');\n  process.stdin.pipe(cleartextStream);\n  process.stdin.resume();\n});\ncleartextStream.setEncoding('utf8');\ncleartextStream.on('data', function(data) {\n  console.log(data);\n});\ncleartextStream.on('end', function() {\n  server.close();\n});
\n

Or\n\n

\n
var tls = require('tls');\nvar fs = require('fs');\n\nvar options = {\n  pfx: fs.readFileSync('client.pfx')\n};\n\nvar cleartextStream = tls.connect(8000, options, function() {\n  console.log('client connected',\n              cleartextStream.authorized ? 'authorized' : 'unauthorized');\n  process.stdin.pipe(cleartextStream);\n  process.stdin.resume();\n});\ncleartextStream.setEncoding('utf8');\ncleartextStream.on('data', function(data) {\n  console.log(data);\n});\ncleartextStream.on('end', function() {\n  server.close();\n});
\n", + "signatures": [ + { + "params": [ + { + "name": "port" + }, + { + "name": "host", + "optional": true + }, + { + "name": "options", + "optional": true + }, + { + "name": "callback", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "tls.createSecurePair([credentials], [isServer], [requestCert], [rejectUnauthorized])", + "type": "method", + "name": "createSecurePair", + "desc": "

Creates a new secure pair object with two streams, one of which reads/writes\nencrypted data, and one reads/writes cleartext data.\nGenerally the encrypted one is piped to/from an incoming encrypted data stream,\nand the cleartext one is used as a replacement for the initial encrypted stream.\n\n

\n
    \n
  • credentials: A credentials object from crypto.createCredentials( ... )

    \n
  • \n
  • isServer: A boolean indicating whether this tls connection should be\nopened as a server or a client.

    \n
  • \n
  • requestCert: A boolean indicating whether a server should request a\ncertificate from a connecting client. Only applies to server connections.

    \n
  • \n
  • rejectUnauthorized: A boolean indicating whether a server should\nautomatically reject clients with invalid certificates. Only applies to\nservers with requestCert enabled.

    \n
  • \n
\n

tls.createSecurePair() returns a SecurePair object with [cleartext][] and\nencrypted stream properties.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "credentials", + "optional": true + }, + { + "name": "isServer", + "optional": true + }, + { + "name": "requestCert", + "optional": true + }, + { + "name": "rejectUnauthorized", + "optional": true + } + ] + } + ] + } + ], + "classes": [ + { + "textRaw": "Class: SecurePair", + "type": "class", + "name": "SecurePair", + "desc": "

Returned by tls.createSecurePair.\n\n

\n", + "events": [ + { + "textRaw": "Event: 'secure'", + "type": "event", + "name": "secure", + "desc": "

The event is emitted from the SecurePair once the pair has successfully\nestablished a secure connection.\n\n

\n

Similarly to the checking for the server 'secureConnection' event,\npair.cleartext.authorized should be checked to confirm whether the certificate\nused properly authorized.\n\n

\n", + "params": [] + } + ] + }, + { + "textRaw": "Class: tls.Server", + "type": "class", + "name": "tls.Server", + "desc": "

This class is a subclass of net.Server and has the same methods on it.\nInstead of accepting just raw TCP connections, this accepts encrypted\nconnections using TLS or SSL.\n\n

\n", + "events": [ + { + "textRaw": "Event: 'secureConnection'", + "type": "event", + "name": "secureConnection", + "desc": "

function (cleartextStream) {}\n\n

\n

This event is emitted after a new connection has been successfully\nhandshaked. The argument is a instance of [CleartextStream][]. It has all the\ncommon stream methods and events.\n\n

\n

cleartextStream.authorized is a boolean value which indicates if the\nclient has verified by one of the supplied certificate authorities for the\nserver. If cleartextStream.authorized is false, then\ncleartextStream.authorizationError is set to describe how authorization\nfailed. Implied but worth mentioning: depending on the settings of the TLS\nserver, you unauthorized connections may be accepted.\ncleartextStream.npnProtocol is a string containing selected NPN protocol.\ncleartextStream.servername is a string containing servername requested with\nSNI.\n\n\n

\n", + "params": [] + }, + { + "textRaw": "Event: 'clientError'", + "type": "event", + "name": "clientError", + "desc": "

function (exception) { }\n\n

\n

When a client connection emits an 'error' event before secure connection is\nestablished - it will be forwarded here.\n\n\n

\n", + "params": [] + } + ], + "methods": [ + { + "textRaw": "server.listen(port, [host], [callback])", + "type": "method", + "name": "listen", + "desc": "

Begin accepting connections on the specified port and host. If the\nhost is omitted, the server will accept connections directed to any\nIPv4 address (INADDR_ANY).\n\n

\n

This function is asynchronous. The last parameter callback will be called\nwhen the server has been bound.\n\n

\n

See net.Server for more information.\n\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "port" + }, + { + "name": "host", + "optional": true + }, + { + "name": "callback", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "server.close()", + "type": "method", + "name": "close", + "desc": "

Stops the server from accepting new connections. This function is\nasynchronous, the server is finally closed when the server emits a 'close'\nevent.\n\n

\n", + "signatures": [ + { + "params": [] + } + ] + }, + { + "textRaw": "server.address()", + "type": "method", + "name": "address", + "desc": "

Returns the bound address, the address family name and port of the\nserver as reported by the operating system. See [net.Server.address()][] for\nmore information.\n\n

\n", + "signatures": [ + { + "params": [] + } + ] + }, + { + "textRaw": "server.addContext(hostname, credentials)", + "type": "method", + "name": "addContext", + "desc": "

Add secure context that will be used if client request's SNI hostname is\nmatching passed hostname (wildcards can be used). credentials can contain\nkey, cert and ca.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "hostname" + }, + { + "name": "credentials" + } + ] + } + ] + } + ], + "properties": [ + { + "textRaw": "server.maxConnections", + "name": "maxConnections", + "desc": "

Set this property to reject connections when the server's connection count\ngets high.\n\n

\n" + }, + { + "textRaw": "server.connections", + "name": "connections", + "desc": "

The number of concurrent connections on the server.\n\n\n

\n" + } + ] + }, + { + "textRaw": "Class: tls.CleartextStream", + "type": "class", + "name": "tls.CleartextStream", + "desc": "

This is a stream on top of the Encrypted stream that makes it possible to\nread/write an encrypted data as a cleartext data.\n\n

\n

This instance implements a duplex [Stream][] interfaces. It has all the\ncommon stream methods and events.\n\n

\n

A ClearTextStream is the clear member of a SecurePair object.\n\n

\n", + "events": [ + { + "textRaw": "Event: 'secureConnect'", + "type": "event", + "name": "secureConnect", + "desc": "

This event is emitted after a new connection has been successfully handshaked. \nThe listener will be called no matter if the server's certificate was\nauthorized or not. It is up to the user to test cleartextStream.authorized\nto see if the server certificate was signed by one of the specified CAs.\nIf cleartextStream.authorized === false then the error can be found in\ncleartextStream.authorizationError. Also if NPN was used - you can check\ncleartextStream.npnProtocol for negotiated protocol.\n\n

\n", + "params": [] + } + ], + "properties": [ + { + "textRaw": "cleartextStream.authorized", + "name": "authorized", + "desc": "

A boolean that is true if the peer certificate was signed by one of the\nspecified CAs, otherwise false\n\n

\n" + }, + { + "textRaw": "cleartextStream.authorizationError", + "name": "authorizationError", + "desc": "

The reason why the peer's certificate has not been verified. This property\nbecomes available only when cleartextStream.authorized === false.\n\n

\n" + }, + { + "textRaw": "cleartextStream.remoteAddress", + "name": "remoteAddress", + "desc": "

The string representation of the remote IP address. For example,\n'74.125.127.100' or '2001:4860:a005::68'.\n\n

\n" + }, + { + "textRaw": "cleartextStream.remotePort", + "name": "remotePort", + "desc": "

The numeric representation of the remote port. For example, 443.\n\n

\n" + } + ], + "methods": [ + { + "textRaw": "cleartextStream.getPeerCertificate()", + "type": "method", + "name": "getPeerCertificate", + "desc": "

Returns an object representing the peer's certificate. The returned object has\nsome properties corresponding to the field of the certificate.\n\n

\n

Example:\n\n

\n
{ subject: \n   { C: 'UK',\n     ST: 'Acknack Ltd',\n     L: 'Rhys Jones',\n     O: 'node.js',\n     OU: 'Test TLS Certificate',\n     CN: 'localhost' },\n  issuer: \n   { C: 'UK',\n     ST: 'Acknack Ltd',\n     L: 'Rhys Jones',\n     O: 'node.js',\n     OU: 'Test TLS Certificate',\n     CN: 'localhost' },\n  valid_from: 'Nov 11 09:52:22 2009 GMT',\n  valid_to: 'Nov  6 09:52:22 2029 GMT',\n  fingerprint: '2A:7A:C2:DD:E5:F9:CC:53:72:35:99:7A:02:5A:71:38:52:EC:8A:DF' }
\n

If the peer does not provide a certificate, it returns null or an empty\nobject.\n\n

\n", + "signatures": [ + { + "params": [] + } + ] + }, + { + "textRaw": "cleartextStream.getCipher()", + "type": "method", + "name": "getCipher", + "desc": "

Returns an object representing the cipher name and the SSL/TLS\nprotocol version of the current connection.\n\n

\n

Example:\n{ name: 'AES256-SHA', version: 'TLSv1/SSLv3' }\n\n

\n

See SSL_CIPHER_get_name() and SSL_CIPHER_get_version() in\nhttp://www.openssl.org/docs/ssl/ssl.html#DEALING_WITH_CIPHERS for more\ninformation.\n\n

\n", + "signatures": [ + { + "params": [] + } + ] + }, + { + "textRaw": "cleartextStream.address()", + "type": "method", + "name": "address", + "desc": "

Returns the bound address, the address family name and port of the\nunderlying socket as reported by the operating system. Returns an\nobject with three properties, e.g.\n{ port: 12346, family: 'IPv4', address: '127.0.0.1' }\n\n

\n", + "signatures": [ + { + "params": [] + } + ] + } + ] + } + ], + "type": "module", + "displayName": "TLS (SSL)" + }, + { + "textRaw": "StringDecoder", + "name": "stringdecoder", + "stability": 3, + "stabilityText": "Stable", + "desc": "

To use this module, do require('string_decoder'). StringDecoder decodes a\nbuffer to a string. It is a simple interface to buffer.toString() but provides\nadditional support for utf8.\n\n

\n
var StringDecoder = require('string_decoder').StringDecoder;\nvar decoder = new StringDecoder('utf8');\n\nvar cent = new Buffer([0xC2, 0xA2]);\nconsole.log(decoder.write(cent));\n\nvar euro = new Buffer([0xE2, 0x82, 0xAC]);\nconsole.log(decoder.write(euro));
\n", + "classes": [ + { + "textRaw": "Class: StringDecoder", + "type": "class", + "name": "StringDecoder", + "desc": "

Accepts a single argument, encoding which defaults to utf8.\n\n

\n", + "methods": [ + { + "textRaw": "StringDecoder.write(buffer)", + "type": "method", + "name": "write", + "desc": "

Returns a decoded string.\n

\n", + "signatures": [ + { + "params": [ + { + "name": "buffer" + } + ] + } + ] + } + ] + } + ], + "type": "module", + "displayName": "StringDecoder" + }, + { + "textRaw": "File System", + "name": "fs", + "stability": 3, + "stabilityText": "Stable", + "desc": "

File I/O is provided by simple wrappers around standard POSIX functions. To\nuse this module do require('fs'). All the methods have asynchronous and\nsynchronous forms.\n\n

\n

The asynchronous form always take a completion callback as its last argument.\nThe arguments passed to the completion callback depend on the method, but the\nfirst argument is always reserved for an exception. If the operation was\ncompleted successfully, then the first argument will be null or undefined.\n\n

\n

When using the synchronous form any exceptions are immediately thrown.\nYou can use try/catch to handle exceptions or allow them to bubble up.\n\n

\n

Here is an example of the asynchronous version:\n\n

\n
var fs = require('fs');\n\nfs.unlink('/tmp/hello', function (err) {\n  if (err) throw err;\n  console.log('successfully deleted /tmp/hello');\n});
\n

Here is the synchronous version:\n\n

\n
var fs = require('fs');\n\nfs.unlinkSync('/tmp/hello')\nconsole.log('successfully deleted /tmp/hello');
\n

With the asynchronous methods there is no guaranteed ordering. So the\nfollowing is prone to error:\n\n

\n
fs.rename('/tmp/hello', '/tmp/world', function (err) {\n  if (err) throw err;\n  console.log('renamed complete');\n});\nfs.stat('/tmp/world', function (err, stats) {\n  if (err) throw err;\n  console.log('stats: ' + JSON.stringify(stats));\n});
\n

It could be that fs.stat is executed before fs.rename.\nThe correct way to do this is to chain the callbacks.\n\n

\n
fs.rename('/tmp/hello', '/tmp/world', function (err) {\n  if (err) throw err;\n  fs.stat('/tmp/world', function (err, stats) {\n    if (err) throw err;\n    console.log('stats: ' + JSON.stringify(stats));\n  });\n});
\n

In busy processes, the programmer is strongly encouraged to use the\nasynchronous versions of these calls. The synchronous versions will block\nthe entire process until they complete--halting all connections.\n\n

\n

Relative path to filename can be used, remember however that this path will be relative\nto process.cwd().\n\n

\n", + "methods": [ + { + "textRaw": "fs.rename(oldPath, newPath, [callback])", + "type": "method", + "name": "rename", + "desc": "

Asynchronous rename(2). No arguments other than a possible exception are given\nto the completion callback.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "oldPath" + }, + { + "name": "newPath" + }, + { + "name": "callback", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "fs.renameSync(oldPath, newPath)", + "type": "method", + "name": "renameSync", + "desc": "

Synchronous rename(2).\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "oldPath" + }, + { + "name": "newPath" + } + ] + } + ] + }, + { + "textRaw": "fs.truncate(fd, len, [callback])", + "type": "method", + "name": "truncate", + "desc": "

Asynchronous ftruncate(2). No arguments other than a possible exception are\ngiven to the completion callback.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "fd" + }, + { + "name": "len" + }, + { + "name": "callback", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "fs.truncateSync(fd, len)", + "type": "method", + "name": "truncateSync", + "desc": "

Synchronous ftruncate(2).\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "fd" + }, + { + "name": "len" + } + ] + } + ] + }, + { + "textRaw": "fs.chown(path, uid, gid, [callback])", + "type": "method", + "name": "chown", + "desc": "

Asynchronous chown(2). No arguments other than a possible exception are given\nto the completion callback.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "path" + }, + { + "name": "uid" + }, + { + "name": "gid" + }, + { + "name": "callback", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "fs.chownSync(path, uid, gid)", + "type": "method", + "name": "chownSync", + "desc": "

Synchronous chown(2).\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "path" + }, + { + "name": "uid" + }, + { + "name": "gid" + } + ] + } + ] + }, + { + "textRaw": "fs.fchown(fd, uid, gid, [callback])", + "type": "method", + "name": "fchown", + "desc": "

Asynchronous fchown(2). No arguments other than a possible exception are given\nto the completion callback.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "fd" + }, + { + "name": "uid" + }, + { + "name": "gid" + }, + { + "name": "callback", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "fs.fchownSync(fd, uid, gid)", + "type": "method", + "name": "fchownSync", + "desc": "

Synchronous fchown(2).\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "fd" + }, + { + "name": "uid" + }, + { + "name": "gid" + } + ] + } + ] + }, + { + "textRaw": "fs.lchown(path, uid, gid, [callback])", + "type": "method", + "name": "lchown", + "desc": "

Asynchronous lchown(2). No arguments other than a possible exception are given\nto the completion callback.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "path" + }, + { + "name": "uid" + }, + { + "name": "gid" + }, + { + "name": "callback", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "fs.lchownSync(path, uid, gid)", + "type": "method", + "name": "lchownSync", + "desc": "

Synchronous lchown(2).\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "path" + }, + { + "name": "uid" + }, + { + "name": "gid" + } + ] + } + ] + }, + { + "textRaw": "fs.chmod(path, mode, [callback])", + "type": "method", + "name": "chmod", + "desc": "

Asynchronous chmod(2). No arguments other than a possible exception are given\nto the completion callback.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "path" + }, + { + "name": "mode" + }, + { + "name": "callback", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "fs.chmodSync(path, mode)", + "type": "method", + "name": "chmodSync", + "desc": "

Synchronous chmod(2).\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "path" + }, + { + "name": "mode" + } + ] + } + ] + }, + { + "textRaw": "fs.fchmod(fd, mode, [callback])", + "type": "method", + "name": "fchmod", + "desc": "

Asynchronous fchmod(2). No arguments other than a possible exception\nare given to the completion callback.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "fd" + }, + { + "name": "mode" + }, + { + "name": "callback", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "fs.fchmodSync(fd, mode)", + "type": "method", + "name": "fchmodSync", + "desc": "

Synchronous fchmod(2).\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "fd" + }, + { + "name": "mode" + } + ] + } + ] + }, + { + "textRaw": "fs.lchmod(path, mode, [callback])", + "type": "method", + "name": "lchmod", + "desc": "

Asynchronous lchmod(2). No arguments other than a possible exception\nare given to the completion callback.\n\n

\n

Only available on Mac OS X.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "path" + }, + { + "name": "mode" + }, + { + "name": "callback", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "fs.lchmodSync(path, mode)", + "type": "method", + "name": "lchmodSync", + "desc": "

Synchronous lchmod(2).\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "path" + }, + { + "name": "mode" + } + ] + } + ] + }, + { + "textRaw": "fs.stat(path, [callback])", + "type": "method", + "name": "stat", + "desc": "

Asynchronous stat(2). The callback gets two arguments (err, stats) where\nstats is a fs.Stats object. See the fs.Stats\nsection below for more information.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "path" + }, + { + "name": "callback", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "fs.lstat(path, [callback])", + "type": "method", + "name": "lstat", + "desc": "

Asynchronous lstat(2). The callback gets two arguments (err, stats) where\nstats is a fs.Stats object. lstat() is identical to stat(), except that if\npath is a symbolic link, then the link itself is stat-ed, not the file that it\nrefers to.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "path" + }, + { + "name": "callback", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "fs.fstat(fd, [callback])", + "type": "method", + "name": "fstat", + "desc": "

Asynchronous fstat(2). The callback gets two arguments (err, stats) where\nstats is a fs.Stats object. fstat() is identical to stat(), except that\nthe file to be stat-ed is specified by the file descriptor fd.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "fd" + }, + { + "name": "callback", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "fs.statSync(path)", + "type": "method", + "name": "statSync", + "desc": "

Synchronous stat(2). Returns an instance of fs.Stats.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "path" + } + ] + } + ] + }, + { + "textRaw": "fs.lstatSync(path)", + "type": "method", + "name": "lstatSync", + "desc": "

Synchronous lstat(2). Returns an instance of fs.Stats.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "path" + } + ] + } + ] + }, + { + "textRaw": "fs.fstatSync(fd)", + "type": "method", + "name": "fstatSync", + "desc": "

Synchronous fstat(2). Returns an instance of fs.Stats.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "fd" + } + ] + } + ] + }, + { + "textRaw": "fs.link(srcpath, dstpath, [callback])", + "type": "method", + "name": "link", + "desc": "

Asynchronous link(2). No arguments other than a possible exception are given to\nthe completion callback.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "srcpath" + }, + { + "name": "dstpath" + }, + { + "name": "callback", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "fs.linkSync(srcpath, dstpath)", + "type": "method", + "name": "linkSync", + "desc": "

Synchronous link(2).\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "srcpath" + }, + { + "name": "dstpath" + } + ] + } + ] + }, + { + "textRaw": "fs.symlink(srcpath, dstpath, [type], [callback])", + "type": "method", + "name": "symlink", + "desc": "

Asynchronous symlink(2). No arguments other than a possible exception are given\nto the completion callback.\ntype argument can be either 'dir', 'file', or 'junction' (default is 'file'). It is only \nused on Windows (ignored on other platforms).\nNote that Windows junction points require the destination path to be absolute. When using\n'junction', the destination argument will automatically be normalized to absolute path.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "srcpath" + }, + { + "name": "dstpath" + }, + { + "name": "type", + "optional": true + }, + { + "name": "callback", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "fs.symlinkSync(srcpath, dstpath, [type])", + "type": "method", + "name": "symlinkSync", + "desc": "

Synchronous symlink(2).\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "srcpath" + }, + { + "name": "dstpath" + }, + { + "name": "type", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "fs.readlink(path, [callback])", + "type": "method", + "name": "readlink", + "desc": "

Asynchronous readlink(2). The callback gets two arguments (err,\nlinkString).\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "path" + }, + { + "name": "callback", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "fs.readlinkSync(path)", + "type": "method", + "name": "readlinkSync", + "desc": "

Synchronous readlink(2). Returns the symbolic link's string value.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "path" + } + ] + } + ] + }, + { + "textRaw": "fs.realpath(path, [cache], callback)", + "type": "method", + "name": "realpath", + "desc": "

Asynchronous realpath(2). The callback gets two arguments (err,\nresolvedPath). May use process.cwd to resolve relative paths. cache is an\nobject literal of mapped paths that can be used to force a specific path\nresolution or avoid additional fs.stat calls for known real paths.\n\n

\n

Example:\n\n

\n
var cache = {'/etc':'/private/etc'};\nfs.realpath('/etc/passwd', cache, function (err, resolvedPath) {\n  if (err) throw err;\n  console.log(resolvedPath);\n});
\n", + "signatures": [ + { + "params": [ + { + "name": "path" + }, + { + "name": "cache", + "optional": true + }, + { + "name": "callback" + } + ] + } + ] + }, + { + "textRaw": "fs.realpathSync(path, [cache])", + "type": "method", + "name": "realpathSync", + "desc": "

Synchronous realpath(2). Returns the resolved path.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "path" + }, + { + "name": "cache", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "fs.unlink(path, [callback])", + "type": "method", + "name": "unlink", + "desc": "

Asynchronous unlink(2). No arguments other than a possible exception are given\nto the completion callback.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "path" + }, + { + "name": "callback", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "fs.unlinkSync(path)", + "type": "method", + "name": "unlinkSync", + "desc": "

Synchronous unlink(2).\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "path" + } + ] + } + ] + }, + { + "textRaw": "fs.rmdir(path, [callback])", + "type": "method", + "name": "rmdir", + "desc": "

Asynchronous rmdir(2). No arguments other than a possible exception are given\nto the completion callback.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "path" + }, + { + "name": "callback", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "fs.rmdirSync(path)", + "type": "method", + "name": "rmdirSync", + "desc": "

Synchronous rmdir(2).\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "path" + } + ] + } + ] + }, + { + "textRaw": "fs.mkdir(path, [mode], [callback])", + "type": "method", + "name": "mkdir", + "desc": "

Asynchronous mkdir(2). No arguments other than a possible exception are given\nto the completion callback. mode defaults to 0777.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "path" + }, + { + "name": "mode", + "optional": true + }, + { + "name": "callback", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "fs.mkdirSync(path, [mode])", + "type": "method", + "name": "mkdirSync", + "desc": "

Synchronous mkdir(2).\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "path" + }, + { + "name": "mode", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "fs.readdir(path, [callback])", + "type": "method", + "name": "readdir", + "desc": "

Asynchronous readdir(3). Reads the contents of a directory.\nThe callback gets two arguments (err, files) where files is an array of\nthe names of the files in the directory excluding '.' and '..'.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "path" + }, + { + "name": "callback", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "fs.readdirSync(path)", + "type": "method", + "name": "readdirSync", + "desc": "

Synchronous readdir(3). Returns an array of filenames excluding '.' and\n'..'.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "path" + } + ] + } + ] + }, + { + "textRaw": "fs.close(fd, [callback])", + "type": "method", + "name": "close", + "desc": "

Asynchronous close(2). No arguments other than a possible exception are given\nto the completion callback.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "fd" + }, + { + "name": "callback", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "fs.closeSync(fd)", + "type": "method", + "name": "closeSync", + "desc": "

Synchronous close(2).\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "fd" + } + ] + } + ] + }, + { + "textRaw": "fs.open(path, flags, [mode], [callback])", + "type": "method", + "name": "open", + "desc": "

Asynchronous file open. See open(2). flags can be:\n\n

\n
    \n
  • 'r' - Open file for reading.\nAn exception occurs if the file does not exist.

    \n
  • \n
  • 'r+' - Open file for reading and writing.\nAn exception occurs if the file does not exist.

    \n
  • \n
  • 'rs' - Open file for reading in synchronous mode. Instructs the operating\nsystem to bypass the local file system cache.

    \n

    This is primarily useful for opening files on NFS mounts as it allows you to\nskip the potentially stale local cache. It has a very real impact on I/O\nperformance so don't use this mode unless you need it.

    \n

    Note that this doesn't turn fs.open() into a synchronous blocking call.\nIf that's what you want then you should be using fs.openSync()

    \n
  • \n
  • 'rs+' - Open file for reading and writing, telling the OS to open it\nsynchronously. See notes for 'rs' about using this with caution.

    \n
  • \n
  • 'w' - Open file for writing.\nThe file is created (if it does not exist) or truncated (if it exists).

    \n
  • \n
  • 'wx' - Like 'w' but opens the file in exclusive mode.

    \n
  • \n
  • 'w+' - Open file for reading and writing.\nThe file is created (if it does not exist) or truncated (if it exists).

    \n
  • \n
  • 'wx+' - Like 'w+' but opens the file in exclusive mode.

    \n
  • \n
  • 'a' - Open file for appending.\nThe file is created if it does not exist.

    \n
  • \n
  • 'ax' - Like 'a' but opens the file in exclusive mode.

    \n
  • \n
  • 'a+' - Open file for reading and appending.\nThe file is created if it does not exist.

    \n
  • \n
  • 'ax+' - Like 'a+' but opens the file in exclusive mode.

    \n
  • \n
\n

mode defaults to 0666. The callback gets two arguments (err, fd).\n\n

\n

Exclusive mode (O_EXCL) ensures that path is newly created. fs.open()\nfails if a file by that name already exists. On POSIX systems, symlinks are\nnot followed. Exclusive mode may or may not work with network file systems.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "path" + }, + { + "name": "flags" + }, + { + "name": "mode", + "optional": true + }, + { + "name": "callback", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "fs.openSync(path, flags, [mode])", + "type": "method", + "name": "openSync", + "desc": "

Synchronous open(2).\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "path" + }, + { + "name": "flags" + }, + { + "name": "mode", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "fs.utimes(path, atime, mtime, [callback])", + "type": "method", + "name": "utimes", + "desc": "

Change file timestamps of the file referenced by the supplied path.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "path" + }, + { + "name": "atime" + }, + { + "name": "mtime" + } + ] + }, + { + "params": [ + { + "name": "path" + }, + { + "name": "atime" + }, + { + "name": "mtime" + }, + { + "name": "callback", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "fs.utimesSync(path, atime, mtime)", + "type": "method", + "name": "utimesSync", + "desc": "

Change file timestamps of the file referenced by the supplied path.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "path" + }, + { + "name": "atime" + }, + { + "name": "mtime" + } + ] + } + ] + }, + { + "textRaw": "fs.futimes(fd, atime, mtime, [callback])", + "type": "method", + "name": "futimes", + "desc": "

Change the file timestamps of a file referenced by the supplied file\ndescriptor.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "fd" + }, + { + "name": "atime" + }, + { + "name": "mtime" + } + ] + }, + { + "params": [ + { + "name": "fd" + }, + { + "name": "atime" + }, + { + "name": "mtime" + }, + { + "name": "callback", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "fs.futimesSync(fd, atime, mtime)", + "type": "method", + "name": "futimesSync", + "desc": "

Change the file timestamps of a file referenced by the supplied file\ndescriptor.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "fd" + }, + { + "name": "atime" + }, + { + "name": "mtime" + } + ] + } + ] + }, + { + "textRaw": "fs.fsync(fd, [callback])", + "type": "method", + "name": "fsync", + "desc": "

Asynchronous fsync(2). No arguments other than a possible exception are given\nto the completion callback.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "fd" + }, + { + "name": "callback", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "fs.fsyncSync(fd)", + "type": "method", + "name": "fsyncSync", + "desc": "

Synchronous fsync(2).\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "fd" + } + ] + } + ] + }, + { + "textRaw": "fs.write(fd, buffer, offset, length, position, [callback])", + "type": "method", + "name": "write", + "desc": "

Write buffer to the file specified by fd.\n\n

\n

offset and length determine the part of the buffer to be written.\n\n

\n

position refers to the offset from the beginning of the file where this data\nshould be written. If position is null, the data will be written at the\ncurrent position.\nSee pwrite(2).\n\n

\n

The callback will be given three arguments (err, written, buffer) where written\nspecifies how many bytes were written from buffer.\n\n

\n

Note that it is unsafe to use fs.write multiple times on the same file\nwithout waiting for the callback. For this scenario,\nfs.createWriteStream is strongly recommended.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "fd" + }, + { + "name": "buffer" + }, + { + "name": "offset" + }, + { + "name": "length" + }, + { + "name": "position" + }, + { + "name": "callback", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "fs.writeSync(fd, buffer, offset, length, position)", + "type": "method", + "name": "writeSync", + "desc": "

Synchronous version of fs.write(). Returns the number of bytes written.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "fd" + }, + { + "name": "buffer" + }, + { + "name": "offset" + }, + { + "name": "length" + }, + { + "name": "position" + } + ] + } + ] + }, + { + "textRaw": "fs.read(fd, buffer, offset, length, position, [callback])", + "type": "method", + "name": "read", + "desc": "

Read data from the file specified by fd.\n\n

\n

buffer is the buffer that the data will be written to.\n\n

\n

offset is offset within the buffer where reading will start.\n\n

\n

length is an integer specifying the number of bytes to read.\n\n

\n

position is an integer specifying where to begin reading from in the file.\nIf position is null, data will be read from the current file position.\n\n

\n

The callback is given the three arguments, (err, bytesRead, buffer).\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "fd" + }, + { + "name": "buffer" + }, + { + "name": "offset" + }, + { + "name": "length" + }, + { + "name": "position" + }, + { + "name": "callback", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "fs.readSync(fd, buffer, offset, length, position)", + "type": "method", + "name": "readSync", + "desc": "

Synchronous version of fs.read. Returns the number of bytesRead.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "fd" + }, + { + "name": "buffer" + }, + { + "name": "offset" + }, + { + "name": "length" + }, + { + "name": "position" + } + ] + } + ] + }, + { + "textRaw": "fs.readFile(filename, [encoding], [callback])", + "type": "method", + "name": "readFile", + "desc": "

Asynchronously reads the entire contents of a file. Example:\n\n

\n
fs.readFile('/etc/passwd', function (err, data) {\n  if (err) throw err;\n  console.log(data);\n});
\n

The callback is passed two arguments (err, data), where data is the\ncontents of the file.\n\n

\n

If no encoding is specified, then the raw buffer is returned.\n\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "filename" + }, + { + "name": "encoding", + "optional": true + }, + { + "name": "callback", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "fs.readFileSync(filename, [encoding])", + "type": "method", + "name": "readFileSync", + "desc": "

Synchronous version of fs.readFile. Returns the contents of the filename.\n\n

\n

If encoding is specified then this function returns a string. Otherwise it\nreturns a buffer.\n\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "filename" + }, + { + "name": "encoding", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "fs.writeFile(filename, data, [encoding], [callback])", + "type": "method", + "name": "writeFile", + "desc": "

Asynchronously writes data to a file, replacing the file if it already exists.\ndata can be a string or a buffer. The encoding argument is ignored if\ndata is a buffer. It defaults to 'utf8'.\n\n

\n

Example:\n\n

\n
fs.writeFile('message.txt', 'Hello Node', function (err) {\n  if (err) throw err;\n  console.log('It\\'s saved!');\n});
\n", + "signatures": [ + { + "params": [ + { + "name": "filename" + }, + { + "name": "data" + }, + { + "name": "encoding", + "optional": true + }, + { + "name": "callback", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "fs.writeFileSync(filename, data, [encoding])", + "type": "method", + "name": "writeFileSync", + "desc": "

The synchronous version of fs.writeFile.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "filename" + }, + { + "name": "data" + }, + { + "name": "encoding", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "fs.appendFile(filename, data, encoding='utf8', [callback])", + "type": "method", + "name": "appendFile", + "desc": "

Asynchronously append data to a file, creating the file if it not yet exists.\ndata can be a string or a buffer. The encoding argument is ignored if\ndata is a buffer.\n\n

\n

Example:\n\n

\n
fs.appendFile('message.txt', 'data to append', function (err) {\n  if (err) throw err;\n  console.log('The "data to append" was appended to file!');\n});
\n", + "signatures": [ + { + "params": [ + { + "name": "filename" + }, + { + "name": "data" + }, + { + "name": "encoding", + "default": "'utf8'" + }, + { + "name": "callback", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "fs.appendFileSync(filename, data, encoding='utf8')", + "type": "method", + "name": "appendFileSync", + "desc": "

The synchronous version of fs.appendFile.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "filename" + }, + { + "name": "data" + }, + { + "name": "encoding", + "default": "'utf8'" + } + ] + } + ] + }, + { + "textRaw": "fs.watchFile(filename, [options], listener)", + "type": "method", + "name": "watchFile", + "stability": 2, + "stabilityText": "Unstable. Use fs.watch instead, if possible.", + "desc": "

Watch for changes on filename. The callback listener will be called each\ntime the file is accessed.\n\n

\n

The second argument is optional. The options if provided should be an object\ncontaining two members a boolean, persistent, and interval. persistent\nindicates whether the process should continue to run as long as files are\nbeing watched. interval indicates how often the target should be polled,\nin milliseconds. The default is { persistent: true, interval: 5007 }.\n\n

\n

The listener gets two arguments the current stat object and the previous\nstat object:\n\n

\n
fs.watchFile('message.text', function (curr, prev) {\n  console.log('the current mtime is: ' + curr.mtime);\n  console.log('the previous mtime was: ' + prev.mtime);\n});
\n

These stat objects are instances of fs.Stat.\n\n

\n

If you want to be notified when the file was modified, not just accessed\nyou need to compare curr.mtime and prev.mtime.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "filename" + }, + { + "name": "options", + "optional": true + }, + { + "name": "listener" + } + ] + } + ] + }, + { + "textRaw": "fs.unwatchFile(filename, [listener])", + "type": "method", + "name": "unwatchFile", + "stability": 2, + "stabilityText": "Unstable. Use fs.watch instead, if available.", + "desc": "

Stop watching for changes on filename. If listener is specified, only that\nparticular listener is removed. Otherwise, all listeners are removed and you\nhave effectively stopped watching filename.\n\n

\n

Calling fs.unwatchFile() with a filename that is not being watched is a\nno-op, not an error.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "filename" + }, + { + "name": "listener", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "fs.watch(filename, [options], [listener])", + "type": "method", + "name": "watch", + "stability": 2, + "stabilityText": "Unstable.", + "desc": "

Watch for changes on filename, where filename is either a file or a\ndirectory. The returned object is a fs.FSWatcher.\n\n

\n

The second argument is optional. The options if provided should be an object\ncontaining a boolean member persistent, which indicates whether the process\nshould continue to run as long as files are being watched. The default is\n{ persistent: true }.\n\n

\n

The listener callback gets two arguments (event, filename). event is either\n'rename' or 'change', and filename is the name of the file which triggered\nthe event.\n\n

\n", + "miscs": [ + { + "textRaw": "Caveats", + "name": "Caveats", + "type": "misc", + "desc": "

The fs.watch API is not 100% consistent across platforms, and is\nunavailable in some situations.\n\n

\n", + "miscs": [ + { + "textRaw": "Availability", + "name": "Availability", + "type": "misc", + "desc": "

This feature depends on the underlying operating system providing a way\nto be notified of filesystem changes.\n\n

\n
    \n
  • On Linux systems, this uses inotify.
  • \n
  • On BSD systems (including OS X), this uses kqueue.
  • \n
  • On SunOS systems (including Solaris and SmartOS), this uses event ports.
  • \n
  • On Windows systems, this feature depends on ReadDirectoryChangesW.
  • \n
\n

If the underlying functionality is not available for some reason, then\nfs.watch will not be able to function. For example, watching files or\ndirectories on network file systems (NFS, SMB, etc.) often doesn't work\nreliably or at all.\n\n

\n

You can still use fs.watchFile, which uses stat polling, but it is slower and\nless reliable.\n\n

\n" + }, + { + "textRaw": "Filename Argument", + "name": "Filename Argument", + "type": "misc", + "desc": "

Providing filename argument in the callback is not supported\non every platform (currently it's only supported on Linux and Windows). Even\non supported platforms filename is not always guaranteed to be provided.\nTherefore, don't assume that filename argument is always provided in the\ncallback, and have some fallback logic if it is null.\n\n

\n
fs.watch('somedir', function (event, filename) {\n  console.log('event is: ' + event);\n  if (filename) {\n    console.log('filename provided: ' + filename);\n  } else {\n    console.log('filename not provided');\n  }\n});
\n" + } + ] + } + ], + "signatures": [ + { + "params": [ + { + "name": "filename" + }, + { + "name": "options", + "optional": true + }, + { + "name": "listener", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "fs.exists(path, [callback])", + "type": "method", + "name": "exists", + "desc": "

Test whether or not the given path exists by checking with the file system.\nThen call the callback argument with either true or false. Example:\n\n

\n
fs.exists('/etc/passwd', function (exists) {\n  util.debug(exists ? "it's there" : "no passwd!");\n});
\n", + "signatures": [ + { + "params": [ + { + "name": "path" + }, + { + "name": "callback", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "fs.existsSync(path)", + "type": "method", + "name": "existsSync", + "desc": "

Synchronous version of fs.exists.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "path" + } + ] + } + ] + }, + { + "textRaw": "fs.createReadStream(path, [options])", + "type": "method", + "name": "createReadStream", + "desc": "

Returns a new ReadStream object (See Readable Stream).\n\n

\n

options is an object with the following defaults:\n\n

\n
{ flags: 'r',\n  encoding: null,\n  fd: null,\n  mode: 0666,\n  bufferSize: 64 * 1024\n}
\n

options can include start and end values to read a range of bytes from\nthe file instead of the entire file. Both start and end are inclusive and\nstart at 0. The encoding can be 'utf8', 'ascii', or 'base64'.\n\n

\n

An example to read the last 10 bytes of a file which is 100 bytes long:\n\n

\n
fs.createReadStream('sample.txt', {start: 90, end: 99});
\n", + "signatures": [ + { + "params": [ + { + "name": "path" + }, + { + "name": "options", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "fs.createWriteStream(path, [options])", + "type": "method", + "name": "createWriteStream", + "desc": "

Returns a new WriteStream object (See Writable Stream).\n\n

\n

options is an object with the following defaults:\n\n

\n
{ flags: 'w',\n  encoding: null,\n  mode: 0666 }
\n

options may also include a start option to allow writing data at\nsome position past the beginning of the file. Modifying a file rather\nthan replacing it may require a flags mode of r+ rather than the\ndefault mode w.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "path" + }, + { + "name": "options", + "optional": true + } + ] + } + ] + } + ], + "classes": [ + { + "textRaw": "Class: fs.Stats", + "type": "class", + "name": "fs.Stats", + "desc": "

Objects returned from fs.stat(), fs.lstat() and fs.fstat() and their\nsynchronous counterparts are of this type.\n\n

\n
    \n
  • stats.isFile()
  • \n
  • stats.isDirectory()
  • \n
  • stats.isBlockDevice()
  • \n
  • stats.isCharacterDevice()
  • \n
  • stats.isSymbolicLink() (only valid with fs.lstat())
  • \n
  • stats.isFIFO()
  • \n
  • stats.isSocket()
  • \n
\n

For a regular file util.inspect(stats) would return a string very\nsimilar to this:\n\n

\n
{ dev: 2114,\n  ino: 48064969,\n  mode: 33188,\n  nlink: 1,\n  uid: 85,\n  gid: 100,\n  rdev: 0,\n  size: 527,\n  blksize: 4096,\n  blocks: 8,\n  atime: Mon, 10 Oct 2011 23:24:11 GMT,\n  mtime: Mon, 10 Oct 2011 23:24:11 GMT,\n  ctime: Mon, 10 Oct 2011 23:24:11 GMT }
\n

Please note that atime, mtime and ctime are instances\nof [Date][MDN-Date] object and to compare the values of\nthese objects you should use appropriate methods. For most\ngeneral uses [getTime()][MDN-Date-getTime] will return\nthe number of milliseconds elapsed since 1 January 1970\n00:00:00 UTC and this integer should be sufficient for\nany comparison, however there additional methods which can\nbe used for displaying fuzzy information. More details can\nbe found in the [MDN JavaScript Reference][MDN-Date] page.\n\n

\n" + }, + { + "textRaw": "Class: fs.ReadStream", + "type": "class", + "name": "fs.ReadStream", + "desc": "

ReadStream is a Readable Stream.\n\n

\n", + "events": [ + { + "textRaw": "Event: 'open'", + "type": "event", + "name": "open", + "params": [], + "desc": "

Emitted when the ReadStream's file is opened.\n\n\n

\n" + } + ] + }, + { + "textRaw": "Class: fs.FSWatcher", + "type": "class", + "name": "fs.FSWatcher", + "desc": "

Objects returned from fs.watch() are of this type.\n\n

\n", + "methods": [ + { + "textRaw": "watcher.close()", + "type": "method", + "name": "close", + "desc": "

Stop watching for changes on the given fs.FSWatcher.\n\n

\n", + "signatures": [ + { + "params": [] + } + ] + } + ], + "events": [ + { + "textRaw": "Event: 'change'", + "type": "event", + "name": "change", + "params": [], + "desc": "

Emitted when something changes in a watched directory or file.\nSee more details in fs.watch.\n\n

\n" + }, + { + "textRaw": "Event: 'error'", + "type": "event", + "name": "error", + "params": [], + "desc": "

Emitted when an error occurs.\n\n

\n" + } + ] + } + ], + "properties": [ + { + "textRaw": "fs.WriteStream", + "name": "WriteStream", + "desc": "

WriteStream is a Writable Stream.\n\n

\n", + "events": [ + { + "textRaw": "Event: 'open'", + "type": "event", + "name": "open", + "params": [], + "desc": "

Emitted when the WriteStream's file is opened.\n\n

\n" + } + ], + "properties": [ + { + "textRaw": "file.bytesWritten", + "name": "bytesWritten", + "desc": "

The number of bytes written so far. Does not include data that is still queued\nfor writing.\n\n

\n" + } + ] + } + ], + "type": "module", + "displayName": "fs" + }, + { + "textRaw": "Path", + "name": "path", + "stability": 3, + "stabilityText": "Stable", + "desc": "

This module contains utilities for handling and transforming file\npaths. Almost all these methods perform only string transformations.\nThe file system is not consulted to check whether paths are valid.\n\n

\n

Use require('path') to use this module. The following methods are provided:\n\n

\n", + "methods": [ + { + "textRaw": "path.normalize(p)", + "type": "method", + "name": "normalize", + "desc": "

Normalize a string path, taking care of '..' and '.' parts.\n\n

\n

When multiple slashes are found, they're replaced by a single one;\nwhen the path contains a trailing slash, it is preserved.\nOn windows backslashes are used. \n\n

\n

Example:\n\n

\n
path.normalize('/foo/bar//baz/asdf/quux/..')\n// returns\n'/foo/bar/baz/asdf'
\n", + "signatures": [ + { + "params": [ + { + "name": "p" + } + ] + } + ] + }, + { + "textRaw": "path.join([path1], [path2], [...])", + "type": "method", + "name": "join", + "desc": "

Join all arguments together and normalize the resulting path.\nNon-string arguments are ignored.\n\n

\n

Example:\n\n

\n
path.join('/foo', 'bar', 'baz/asdf', 'quux', '..')\n// returns\n'/foo/bar/baz/asdf'\n\npath.join('foo', {}, 'bar')\n// returns\n'foo/bar'
\n", + "signatures": [ + { + "params": [ + { + "name": "path1", + "optional": true + }, + { + "name": "path2", + "optional": true + }, + { + "name": "...", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "path.resolve([from ...], to)", + "type": "method", + "name": "resolve", + "desc": "

Resolves to to an absolute path.\n\n

\n

If to isn't already absolute from arguments are prepended in right to left\norder, until an absolute path is found. If after using all from paths still\nno absolute path is found, the current working directory is used as well. The\nresulting path is normalized, and trailing slashes are removed unless the path \ngets resolved to the root directory. Non-string arguments are ignored.\n\n

\n

Another way to think of it is as a sequence of cd commands in a shell.\n\n

\n
path.resolve('foo/bar', '/tmp/file/', '..', 'a/../subfile')
\n

Is similar to:\n\n

\n
cd foo/bar\ncd /tmp/file/\ncd ..\ncd a/../subfile\npwd
\n

The difference is that the different paths don't need to exist and may also be\nfiles.\n\n

\n

Examples:\n\n

\n
path.resolve('/foo/bar', './baz')\n// returns\n'/foo/bar/baz'\n\npath.resolve('/foo/bar', '/tmp/file/')\n// returns\n'/tmp/file'\n\npath.resolve('wwwroot', 'static_files/png/', '../gif/image.gif')\n// if currently in /home/myself/node, it returns\n'/home/myself/node/wwwroot/static_files/gif/image.gif'
\n", + "signatures": [ + { + "params": [ + { + "name": "from ...", + "optional": true + }, + { + "name": "to" + } + ] + } + ] + }, + { + "textRaw": "path.relative(from, to)", + "type": "method", + "name": "relative", + "desc": "

Solve the relative path from from to to.\n\n

\n

At times we have two absolute paths, and we need to derive the relative\npath from one to the other. This is actually the reverse transform of\npath.resolve, which means we see that:\n\n

\n
path.resolve(from, path.relative(from, to)) == path.resolve(to)
\n

Examples:\n\n

\n
path.relative('C:\\\\orandea\\\\test\\\\aaa', 'C:\\\\orandea\\\\impl\\\\bbb')\n// returns\n'..\\\\..\\\\impl\\\\bbb'\n\npath.relative('/data/orandea/test/aaa', '/data/orandea/impl/bbb')\n// returns\n'../../impl/bbb'
\n", + "signatures": [ + { + "params": [ + { + "name": "from" + }, + { + "name": "to" + } + ] + } + ] + }, + { + "textRaw": "path.dirname(p)", + "type": "method", + "name": "dirname", + "desc": "

Return the directory name of a path. Similar to the Unix dirname command.\n\n

\n

Example:\n\n

\n
path.dirname('/foo/bar/baz/asdf/quux')\n// returns\n'/foo/bar/baz/asdf'
\n", + "signatures": [ + { + "params": [ + { + "name": "p" + } + ] + } + ] + }, + { + "textRaw": "path.basename(p, [ext])", + "type": "method", + "name": "basename", + "desc": "

Return the last portion of a path. Similar to the Unix basename command.\n\n

\n

Example:\n\n

\n
path.basename('/foo/bar/baz/asdf/quux.html')\n// returns\n'quux.html'\n\npath.basename('/foo/bar/baz/asdf/quux.html', '.html')\n// returns\n'quux'
\n", + "signatures": [ + { + "params": [ + { + "name": "p" + }, + { + "name": "ext", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "path.extname(p)", + "type": "method", + "name": "extname", + "desc": "

Return the extension of the path, from the last '.' to end of string\nin the last portion of the path. If there is no '.' in the last portion\nof the path or the first character of it is '.', then it returns\nan empty string. Examples:\n\n

\n
path.extname('index.html')\n// returns\n'.html'\n\npath.extname('index.')\n// returns\n'.'\n\npath.extname('index')\n// returns\n''
\n", + "signatures": [ + { + "params": [ + { + "name": "p" + } + ] + } + ] + } + ], + "properties": [ + { + "textRaw": "path.sep", + "name": "sep", + "desc": "

The platform-specific file separator. '\\\\' or '/'.\n\n

\n

An example on linux:\n\n

\n
'foo/bar/baz'.split(path.sep)\n// returns\n['foo', 'bar', 'baz']
\n

An example on windows:\n\n

\n
'foo\\\\bar\\\\baz'.split(path.sep)\n// returns\n['foo', 'bar', 'baz']
\n" + } + ], + "type": "module", + "displayName": "Path" + }, + { + "textRaw": "net", + "name": "net", + "stability": 3, + "stabilityText": "Stable", + "desc": "

The net module provides you with an asynchronous network wrapper. It contains\nmethods for creating both servers and clients (called streams). You can include\nthis module with require('net');\n\n

\n", + "methods": [ + { + "textRaw": "net.createServer([options], [connectionListener])", + "type": "method", + "name": "createServer", + "desc": "

Creates a new TCP server. The connectionListener argument is\nautomatically set as a listener for the ['connection'][] event.\n\n

\n

options is an object with the following defaults:\n\n

\n
{ allowHalfOpen: false\n}
\n

If allowHalfOpen is true, then the socket won't automatically send a FIN\npacket when the other end of the socket sends a FIN packet. The socket becomes\nnon-readable, but still writable. You should call the end() method explicitly.\nSee ['end'][] event for more information.\n\n

\n

Here is an example of an echo server which listens for connections\non port 8124:\n\n

\n
var net = require('net');\nvar server = net.createServer(function(c) { //'connection' listener\n  console.log('server connected');\n  c.on('end', function() {\n    console.log('server disconnected');\n  });\n  c.write('hello\\r\\n');\n  c.pipe(c);\n});\nserver.listen(8124, function() { //'listening' listener\n  console.log('server bound');\n});
\n

Test this by using telnet:\n\n

\n
telnet localhost 8124
\n

To listen on the socket /tmp/echo.sock the third line from the last would\njust be changed to\n\n

\n
server.listen('/tmp/echo.sock', function() { //'listening' listener
\n

Use nc to connect to a UNIX domain socket server:\n\n

\n
nc -U /tmp/echo.sock
\n", + "signatures": [ + { + "params": [ + { + "name": "options", + "optional": true + }, + { + "name": "connectionListener", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "net.connect(options, [connectionListener])", + "type": "method", + "name": "connect", + "desc": "

Constructs a new socket object and opens the socket to the given location.\nWhen the socket is established, the ['connect'][] event will be emitted.\n\n

\n

For TCP sockets, options argument should be an object which specifies:\n\n

\n
    \n
  • port: Port the client should connect to (Required).

    \n
  • \n
  • host: Host the client should connect to. Defaults to 'localhost'.

    \n
  • \n
  • localAddress: Local interface to bind to for network connections.

    \n
  • \n
\n

For UNIX domain sockets, options argument should be an object which specifies:\n\n

\n
    \n
  • path: Path the client should connect to (Required).
  • \n
\n

Common options are:\n\n

\n
    \n
  • allowHalfOpen: if true, the socket won't automatically send\na FIN packet when the other end of the socket sends a FIN packet.\nDefaults to false. See ['end'][] event for more information.
  • \n
\n

The connectListener parameter will be added as an listener for the\n['connect'][] event.\n\n

\n

Here is an example of a client of echo server as described previously:\n\n

\n
var net = require('net');\nvar client = net.connect({port: 8124},\n    function() { //'connect' listener\n  console.log('client connected');\n  client.write('world!\\r\\n');\n});\nclient.on('data', function(data) {\n  console.log(data.toString());\n  client.end();\n});\nclient.on('end', function() {\n  console.log('client disconnected');\n});
\n

To connect on the socket /tmp/echo.sock the second line would just be\nchanged to\n\n

\n
var client = net.connect({path: '/tmp/echo.sock'},
\n", + "signatures": [ + { + "params": [ + { + "name": "options" + }, + { + "name": "connectionListener", + "optional": true + } + ] + }, + { + "params": [ + { + "name": "options" + }, + { + "name": "connectionListener", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "net.createConnection(options, [connectionListener])", + "type": "method", + "name": "createConnection", + "desc": "

Constructs a new socket object and opens the socket to the given location.\nWhen the socket is established, the ['connect'][] event will be emitted.\n\n

\n

For TCP sockets, options argument should be an object which specifies:\n\n

\n
    \n
  • port: Port the client should connect to (Required).

    \n
  • \n
  • host: Host the client should connect to. Defaults to 'localhost'.

    \n
  • \n
  • localAddress: Local interface to bind to for network connections.

    \n
  • \n
\n

For UNIX domain sockets, options argument should be an object which specifies:\n\n

\n
    \n
  • path: Path the client should connect to (Required).
  • \n
\n

Common options are:\n\n

\n
    \n
  • allowHalfOpen: if true, the socket won't automatically send\na FIN packet when the other end of the socket sends a FIN packet.\nDefaults to false. See ['end'][] event for more information.
  • \n
\n

The connectListener parameter will be added as an listener for the\n['connect'][] event.\n\n

\n

Here is an example of a client of echo server as described previously:\n\n

\n
var net = require('net');\nvar client = net.connect({port: 8124},\n    function() { //'connect' listener\n  console.log('client connected');\n  client.write('world!\\r\\n');\n});\nclient.on('data', function(data) {\n  console.log(data.toString());\n  client.end();\n});\nclient.on('end', function() {\n  console.log('client disconnected');\n});
\n

To connect on the socket /tmp/echo.sock the second line would just be\nchanged to\n\n

\n
var client = net.connect({path: '/tmp/echo.sock'},
\n", + "signatures": [ + { + "params": [ + { + "name": "options" + }, + { + "name": "connectionListener", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "net.connect(port, [host], [connectListener])", + "type": "method", + "name": "connect", + "desc": "

Creates a TCP connection to port on host. If host is omitted,\n'localhost' will be assumed.\nThe connectListener parameter will be added as an listener for the\n['connect'][] event.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "port" + }, + { + "name": "host", + "optional": true + }, + { + "name": "connectListener", + "optional": true + } + ] + }, + { + "params": [ + { + "name": "port" + }, + { + "name": "host", + "optional": true + }, + { + "name": "connectListener", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "net.createConnection(port, [host], [connectListener])", + "type": "method", + "name": "createConnection", + "desc": "

Creates a TCP connection to port on host. If host is omitted,\n'localhost' will be assumed.\nThe connectListener parameter will be added as an listener for the\n['connect'][] event.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "port" + }, + { + "name": "host", + "optional": true + }, + { + "name": "connectListener", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "net.connect(path, [connectListener])", + "type": "method", + "name": "connect", + "desc": "

Creates unix socket connection to path.\nThe connectListener parameter will be added as an listener for the\n['connect'][] event.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "path" + }, + { + "name": "connectListener", + "optional": true + } + ] + }, + { + "params": [ + { + "name": "path" + }, + { + "name": "connectListener", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "net.createConnection(path, [connectListener])", + "type": "method", + "name": "createConnection", + "desc": "

Creates unix socket connection to path.\nThe connectListener parameter will be added as an listener for the\n['connect'][] event.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "path" + }, + { + "name": "connectListener", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "net.isIP(input)", + "type": "method", + "name": "isIP", + "desc": "

Tests if input is an IP address. Returns 0 for invalid strings,\nreturns 4 for IP version 4 addresses, and returns 6 for IP version 6 addresses.\n\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "input" + } + ] + } + ] + }, + { + "textRaw": "net.isIPv4(input)", + "type": "method", + "name": "isIPv4", + "desc": "

Returns true if input is a version 4 IP address, otherwise returns false.\n\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "input" + } + ] + } + ] + }, + { + "textRaw": "net.isIPv6(input)", + "type": "method", + "name": "isIPv6", + "desc": "

Returns true if input is a version 6 IP address, otherwise returns false.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "input" + } + ] + } + ] + } + ], + "classes": [ + { + "textRaw": "Class: net.Server", + "type": "class", + "name": "net.Server", + "desc": "

This class is used to create a TCP or UNIX server.\nA server is a net.Socket that can listen for new incoming connections.\n\n

\n", + "methods": [ + { + "textRaw": "server.listen(port, [host], [backlog], [callback])", + "type": "method", + "name": "listen", + "desc": "

Begin accepting connections on the specified port and host. If the\nhost is omitted, the server will accept connections directed to any\nIPv4 address (INADDR_ANY). A port value of zero will assign a random port.\n\n

\n

Backlog is the maximum length of the queue of pending connections.\nThe actual length will be determined by your OS through sysctl settings such as\ntcp_max_syn_backlog and somaxconn on linux. The default value of this\nparameter is 511 (not 512).\n\n

\n

This function is asynchronous. When the server has been bound,\n['listening'][] event will be emitted. The last parameter callback\nwill be added as an listener for the ['listening'][] event.\n\n

\n

One issue some users run into is getting EADDRINUSE errors. This means that\nanother server is already running on the requested port. One way of handling this\nwould be to wait a second and then try again. This can be done with\n\n

\n
server.on('error', function (e) {\n  if (e.code == 'EADDRINUSE') {\n    console.log('Address in use, retrying...');\n    setTimeout(function () {\n      server.close();\n      server.listen(PORT, HOST);\n    }, 1000);\n  }\n});
\n

(Note: All sockets in Node set SO_REUSEADDR already)\n\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "port" + }, + { + "name": "host", + "optional": true + }, + { + "name": "backlog", + "optional": true + }, + { + "name": "callback", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "server.listen(path, [callback])", + "type": "method", + "name": "listen", + "desc": "

Start a UNIX socket server listening for connections on the given path.\n\n

\n

This function is asynchronous. When the server has been bound,\n['listening'][] event will be emitted. The last parameter callback\nwill be added as an listener for the ['listening'][] event.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "path" + }, + { + "name": "callback", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "server.listen(handle, [callback])", + "type": "method", + "name": "listen", + "signatures": [ + { + "params": [ + { + "textRaw": "`handle` {Object} ", + "name": "handle", + "type": "Object" + }, + { + "textRaw": "`callback` {Function} ", + "name": "callback", + "type": "Function", + "optional": true + } + ] + }, + { + "params": [ + { + "name": "handle" + }, + { + "name": "callback", + "optional": true + } + ] + } + ], + "desc": "

The handle object can be set to either a server or socket (anything\nwith an underlying _handle member), or a {fd: <n>} object.\n\n

\n

This will cause the server to accept connections on the specified\nhandle, but it is presumed that the file descriptor or handle has\nalready been bound to a port or domain socket.\n\n

\n

Listening on a file descriptor is not supported on Windows.\n\n

\n

This function is asynchronous. When the server has been bound,\n'listening' event will be emitted.\nthe last parameter callback will be added as an listener for the\n'listening' event.\n\n

\n" + }, + { + "textRaw": "server.close([callback])", + "type": "method", + "name": "close", + "desc": "

Stops the server from accepting new connections and keeps existing\nconnections. This function is asynchronous, the server is finally\nclosed when all connections are ended and the server emits a 'close'\nevent. Optionally, you can pass a callback to listen for the 'close'\nevent.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "callback", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "server.address()", + "type": "method", + "name": "address", + "desc": "

Returns the bound address, the address family name and port of the server\nas reported by the operating system.\nUseful to find which port was assigned when giving getting an OS-assigned address.\nReturns an object with three properties, e.g.\n{ port: 12346, family: 'IPv4', address: '127.0.0.1' }\n\n

\n

Example:\n\n

\n
var server = net.createServer(function (socket) {\n  socket.end("goodbye\\n");\n});\n\n// grab a random port.\nserver.listen(function() {\n  address = server.address();\n  console.log("opened server on %j", address);\n});
\n

Don't call server.address() until the 'listening' event has been emitted.\n\n

\n", + "signatures": [ + { + "params": [] + } + ] + } + ], + "properties": [ + { + "textRaw": "server.maxConnections", + "name": "maxConnections", + "desc": "

Set this property to reject connections when the server's connection count gets\nhigh.\n\n

\n

It is not recommended to use this option once a socket has been sent to a child\nwith child_process.fork().\n\n

\n" + }, + { + "textRaw": "server.connections", + "name": "connections", + "desc": "

The number of concurrent connections on the server.\n\n

\n

This becomes null when sending a socket to a child with child_process.fork().\n\n

\n

net.Server is an [EventEmitter][] with the following events:\n\n

\n" + } + ], + "events": [ + { + "textRaw": "Event: 'listening'", + "type": "event", + "name": "listening", + "desc": "

Emitted when the server has been bound after calling server.listen.\n\n

\n", + "params": [] + }, + { + "textRaw": "Event: 'connection'", + "type": "event", + "name": "connection", + "params": [], + "desc": "

Emitted when a new connection is made. socket is an instance of\nnet.Socket.\n\n

\n" + }, + { + "textRaw": "Event: 'close'", + "type": "event", + "name": "close", + "desc": "

Emitted when the server closes. Note that if connections exist, this\nevent is not emitted until all connections are ended.\n\n

\n", + "params": [] + }, + { + "textRaw": "Event: 'error'", + "type": "event", + "name": "error", + "params": [], + "desc": "

Emitted when an error occurs. The 'close' event will be called directly\nfollowing this event. See example in discussion of server.listen.\n\n

\n" + } + ] + }, + { + "textRaw": "Class: net.Socket", + "type": "class", + "name": "net.Socket", + "desc": "

This object is an abstraction of a TCP or UNIX socket. net.Socket\ninstances implement a duplex Stream interface. They can be created by the\nuser and used as a client (with connect()) or they can be created by Node\nand passed to the user through the 'connection' event of a server.\n\n

\n", + "methods": [ + { + "textRaw": "new net.Socket([options])", + "type": "method", + "name": "Socket", + "desc": "

Construct a new socket object.\n\n

\n

options is an object with the following defaults:\n\n

\n
{ fd: null\n  type: null\n  allowHalfOpen: false\n}
\n

fd allows you to specify the existing file descriptor of socket. type\nspecified underlying protocol. It can be 'tcp4', 'tcp6', or 'unix'.\nAbout allowHalfOpen, refer to createServer() and 'end' event.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "options", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "socket.connect(port, [host], [connectListener])", + "type": "method", + "name": "connect", + "desc": "

Opens the connection for a given socket. If port and host are given,\nthen the socket will be opened as a TCP socket, if host is omitted,\nlocalhost will be assumed. If a path is given, the socket will be\nopened as a unix socket to that path.\n\n

\n

Normally this method is not needed, as net.createConnection opens the\nsocket. Use this only if you are implementing a custom Socket or if a\nSocket is closed and you want to reuse it to connect to another server.\n\n

\n

This function is asynchronous. When the ['connect'][] event is emitted the\nsocket is established. If there is a problem connecting, the 'connect' event\nwill not be emitted, the 'error' event will be emitted with the exception.\n\n

\n

The connectListener parameter will be added as an listener for the\n['connect'][] event.\n\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "path" + }, + { + "name": "connectListener", + "optional": true + } + ] + }, + { + "params": [ + { + "name": "port" + }, + { + "name": "host", + "optional": true + }, + { + "name": "connectListener", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "socket.connect(path, [connectListener])", + "type": "method", + "name": "connect", + "desc": "

Opens the connection for a given socket. If port and host are given,\nthen the socket will be opened as a TCP socket, if host is omitted,\nlocalhost will be assumed. If a path is given, the socket will be\nopened as a unix socket to that path.\n\n

\n

Normally this method is not needed, as net.createConnection opens the\nsocket. Use this only if you are implementing a custom Socket or if a\nSocket is closed and you want to reuse it to connect to another server.\n\n

\n

This function is asynchronous. When the ['connect'][] event is emitted the\nsocket is established. If there is a problem connecting, the 'connect' event\nwill not be emitted, the 'error' event will be emitted with the exception.\n\n

\n

The connectListener parameter will be added as an listener for the\n['connect'][] event.\n\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "path" + }, + { + "name": "connectListener", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "socket.setEncoding([encoding])", + "type": "method", + "name": "setEncoding", + "desc": "

Set the encoding for the socket as a Readable Stream. See\n[stream.setEncoding()][] for more information.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "encoding", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "socket.write(data, [encoding], [callback])", + "type": "method", + "name": "write", + "desc": "

Sends data on the socket. The second parameter specifies the encoding in the\ncase of a string--it defaults to UTF8 encoding.\n\n

\n

Returns true if the entire data was flushed successfully to the kernel\nbuffer. Returns false if all or part of the data was queued in user memory.\n'drain' will be emitted when the buffer is again free.\n\n

\n

The optional callback parameter will be executed when the data is finally\nwritten out - this may not be immediately.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "data" + }, + { + "name": "encoding", + "optional": true + }, + { + "name": "callback", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "socket.end([data], [encoding])", + "type": "method", + "name": "end", + "desc": "

Half-closes the socket. i.e., it sends a FIN packet. It is possible the\nserver will still send some data.\n\n

\n

If data is specified, it is equivalent to calling\nsocket.write(data, encoding) followed by socket.end().\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "data", + "optional": true + }, + { + "name": "encoding", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "socket.destroy()", + "type": "method", + "name": "destroy", + "desc": "

Ensures that no more I/O activity happens on this socket. Only necessary in\ncase of errors (parse error or so).\n\n

\n", + "signatures": [ + { + "params": [] + } + ] + }, + { + "textRaw": "socket.pause()", + "type": "method", + "name": "pause", + "desc": "

Pauses the reading of data. That is, 'data' events will not be emitted.\nUseful to throttle back an upload.\n\n

\n", + "signatures": [ + { + "params": [] + } + ] + }, + { + "textRaw": "socket.resume()", + "type": "method", + "name": "resume", + "desc": "

Resumes reading after a call to pause().\n\n

\n", + "signatures": [ + { + "params": [] + } + ] + }, + { + "textRaw": "socket.setTimeout(timeout, [callback])", + "type": "method", + "name": "setTimeout", + "desc": "

Sets the socket to timeout after timeout milliseconds of inactivity on\nthe socket. By default net.Socket do not have a timeout.\n\n

\n

When an idle timeout is triggered the socket will receive a 'timeout'\nevent but the connection will not be severed. The user must manually end()\nor destroy() the socket.\n\n

\n

If timeout is 0, then the existing idle timeout is disabled.\n\n

\n

The optional callback parameter will be added as a one time listener for the\n'timeout' event.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "timeout" + }, + { + "name": "callback", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "socket.setNoDelay([noDelay])", + "type": "method", + "name": "setNoDelay", + "desc": "

Disables the Nagle algorithm. By default TCP connections use the Nagle\nalgorithm, they buffer data before sending it off. Setting true for\nnoDelay will immediately fire off data each time socket.write() is called.\nnoDelay defaults to true.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "noDelay", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "socket.setKeepAlive([enable], [initialDelay])", + "type": "method", + "name": "setKeepAlive", + "desc": "

Enable/disable keep-alive functionality, and optionally set the initial\ndelay before the first keepalive probe is sent on an idle socket.\nenable defaults to false.\n\n

\n

Set initialDelay (in milliseconds) to set the delay between the last\ndata packet received and the first keepalive probe. Setting 0 for\ninitialDelay will leave the value unchanged from the default\n(or previous) setting. Defaults to 0.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "enable", + "optional": true + }, + { + "name": "initialDelay", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "socket.address()", + "type": "method", + "name": "address", + "desc": "

Returns the bound address, the address family name and port of the\nsocket as reported by the operating system. Returns an object with\nthree properties, e.g.\n{ port: 12346, family: 'IPv4', address: '127.0.0.1' }\n\n

\n", + "signatures": [ + { + "params": [] + } + ] + } + ], + "properties": [ + { + "textRaw": "socket.bufferSize", + "name": "bufferSize", + "desc": "

net.Socket has the property that socket.write() always works. This is to\nhelp users get up and running quickly. The computer cannot always keep up\nwith the amount of data that is written to a socket - the network connection\nsimply might be too slow. Node will internally queue up the data written to a\nsocket and send it out over the wire when it is possible. (Internally it is\npolling on the socket's file descriptor for being writable).\n\n

\n

The consequence of this internal buffering is that memory may grow. This\nproperty shows the number of characters currently buffered to be written.\n(Number of characters is approximately equal to the number of bytes to be\nwritten, but the buffer may contain strings, and the strings are lazily\nencoded, so the exact number of bytes is not known.)\n\n

\n

Users who experience large or growing bufferSize should attempt to\n"throttle" the data flows in their program with pause() and resume().\n\n\n

\n" + }, + { + "textRaw": "socket.remoteAddress", + "name": "remoteAddress", + "desc": "

The string representation of the remote IP address. For example,\n'74.125.127.100' or '2001:4860:a005::68'.\n\n

\n" + }, + { + "textRaw": "socket.remotePort", + "name": "remotePort", + "desc": "

The numeric representation of the remote port. For example,\n80 or 21.\n\n

\n" + }, + { + "textRaw": "socket.bytesRead", + "name": "bytesRead", + "desc": "

The amount of received bytes.\n\n

\n" + }, + { + "textRaw": "socket.bytesWritten", + "name": "bytesWritten", + "desc": "

The amount of bytes sent.\n\n\n

\n

net.Socket instances are [EventEmitter][] with the following events:\n\n

\n" + } + ], + "events": [ + { + "textRaw": "Event: 'connect'", + "type": "event", + "name": "connect", + "desc": "

Emitted when a socket connection is successfully established.\nSee connect().\n\n

\n", + "params": [] + }, + { + "textRaw": "Event: 'data'", + "type": "event", + "name": "data", + "params": [], + "desc": "

Emitted when data is received. The argument data will be a Buffer or\nString. Encoding of data is set by socket.setEncoding().\n(See the [Readable Stream][] section for more information.)\n\n

\n

Note that the data will be lost if there is no listener when a Socket\nemits a 'data' event.\n\n

\n" + }, + { + "textRaw": "Event: 'end'", + "type": "event", + "name": "end", + "desc": "

Emitted when the other end of the socket sends a FIN packet.\n\n

\n

By default (allowHalfOpen == false) the socket will destroy its file\ndescriptor once it has written out its pending write queue. However, by\nsetting allowHalfOpen == true the socket will not automatically end()\nits side allowing the user to write arbitrary amounts of data, with the\ncaveat that the user is required to end() their side now.\n\n\n

\n", + "params": [] + }, + { + "textRaw": "Event: 'timeout'", + "type": "event", + "name": "timeout", + "desc": "

Emitted if the socket times out from inactivity. This is only to notify that\nthe socket has been idle. The user must manually close the connection.\n\n

\n

See also: socket.setTimeout()\n\n\n

\n", + "params": [] + }, + { + "textRaw": "Event: 'drain'", + "type": "event", + "name": "drain", + "desc": "

Emitted when the write buffer becomes empty. Can be used to throttle uploads.\n\n

\n

See also: the return values of socket.write()\n\n

\n", + "params": [] + }, + { + "textRaw": "Event: 'error'", + "type": "event", + "name": "error", + "params": [], + "desc": "

Emitted when an error occurs. The 'close' event will be called directly\nfollowing this event.\n\n

\n" + }, + { + "textRaw": "Event: 'close'", + "type": "event", + "name": "close", + "params": [], + "desc": "

Emitted once the socket is fully closed. The argument had_error is a boolean\nwhich says if the socket was closed due to a transmission error.\n\n

\n" + } + ] + } + ], + "type": "module", + "displayName": "net" + }, + { + "textRaw": "UDP / Datagram Sockets", + "name": "dgram", + "stability": 3, + "stabilityText": "Stable", + "desc": "

Datagram sockets are available through require('dgram').\n\n

\n", + "methods": [ + { + "textRaw": "dgram.createSocket(type, [callback])", + "type": "method", + "name": "createSocket", + "signatures": [ + { + "return": { + "textRaw": "Returns: Socket object ", + "name": "return", + "desc": "Socket object" + }, + "params": [ + { + "textRaw": "`type` String. Either 'udp4' or 'udp6' ", + "name": "type", + "desc": "String. Either 'udp4' or 'udp6'" + }, + { + "textRaw": "`callback` Function. Attached as a listener to `message` events. Optional ", + "name": "callback", + "optional": true, + "desc": "Function. Attached as a listener to `message` events." + } + ] + }, + { + "params": [ + { + "name": "type" + }, + { + "name": "callback", + "optional": true + } + ] + } + ], + "desc": "

Creates a datagram Socket of the specified types. Valid types are udp4\nand udp6.\n\n

\n

Takes an optional callback which is added as a listener for message events.\n\n

\n

Call socket.bind if you want to receive datagrams. socket.bind() will bind\nto the "all interfaces" address on a random port (it does the right thing for\nboth udp4 and udp6 sockets). You can then retrieve the address and port\nwith socket.address().address and socket.address().port.\n\n

\n" + } + ], + "classes": [ + { + "textRaw": "Class: Socket", + "type": "class", + "name": "Socket", + "desc": "

The dgram Socket class encapsulates the datagram functionality. It\nshould be created via dgram.createSocket(type, [callback]).\n\n

\n", + "events": [ + { + "textRaw": "Event: 'message'", + "type": "event", + "name": "message", + "params": [], + "desc": "

Emitted when a new datagram is available on a socket. msg is a Buffer and rinfo is\nan object with the sender's address information and the number of bytes in the datagram.\n\n

\n" + }, + { + "textRaw": "Event: 'listening'", + "type": "event", + "name": "listening", + "desc": "

Emitted when a socket starts listening for datagrams. This happens as soon as UDP sockets\nare created.\n\n

\n", + "params": [] + }, + { + "textRaw": "Event: 'close'", + "type": "event", + "name": "close", + "desc": "

Emitted when a socket is closed with close(). No new message events will be emitted\non this socket.\n\n

\n", + "params": [] + }, + { + "textRaw": "Event: 'error'", + "type": "event", + "name": "error", + "params": [], + "desc": "

Emitted when an error occurs.\n\n

\n" + } + ], + "methods": [ + { + "textRaw": "dgram.send(buf, offset, length, port, address, [callback])", + "type": "method", + "name": "send", + "signatures": [ + { + "params": [ + { + "textRaw": "`buf` Buffer object. Message to be sent ", + "name": "buf", + "desc": "Buffer object. Message to be sent" + }, + { + "textRaw": "`offset` Integer. Offset in the buffer where the message starts. ", + "name": "offset", + "desc": "Integer. Offset in the buffer where the message starts." + }, + { + "textRaw": "`length` Integer. Number of bytes in the message. ", + "name": "length", + "desc": "Integer. Number of bytes in the message." + }, + { + "textRaw": "`port` Integer. destination port ", + "name": "port", + "desc": "Integer. destination port" + }, + { + "textRaw": "`address` String. destination IP ", + "name": "address", + "desc": "String. destination IP" + }, + { + "textRaw": "`callback` Function. Callback when message is done being delivered. Optional. ", + "name": "callback", + "desc": "Function. Callback when message is done being delivered. Optional.", + "optional": true + } + ] + }, + { + "params": [ + { + "name": "buf" + }, + { + "name": "offset" + }, + { + "name": "length" + }, + { + "name": "port" + }, + { + "name": "address" + }, + { + "name": "callback", + "optional": true + } + ] + } + ], + "desc": "

For UDP sockets, the destination port and IP address must be specified. A string\nmay be supplied for the address parameter, and it will be resolved with DNS. An\noptional callback may be specified to detect any DNS errors and when buf may be\nre-used. Note that DNS lookups will delay the time that a send takes place, at\nleast until the next tick. The only way to know for sure that a send has taken place\nis to use the callback.\n\n

\n

If the socket has not been previously bound with a call to bind, it's\nassigned a random port number and bound to the "all interfaces" address\n(0.0.0.0 for udp4 sockets, ::0 for udp6 sockets).\n\n

\n

Example of sending a UDP packet to a random port on localhost;\n\n

\n
var dgram = require('dgram');\nvar message = new Buffer("Some bytes");\nvar client = dgram.createSocket("udp4");\nclient.send(message, 0, message.length, 41234, "localhost", function(err, bytes) {\n  client.close();\n});
\n

A Note about UDP datagram size\n\n

\n

The maximum size of an IPv4/v6 datagram depends on the MTU (Maximum Transmission Unit)\nand on the Payload Length field size.\n\n

\n
    \n
  • The Payload Length field is 16 bits wide, which means that a normal payload\ncannot be larger than 64K octets including internet header and data\n(65,507 bytes = 65,535 − 8 bytes UDP header − 20 bytes IP header);\nthis is generally true for loopback interfaces, but such long datagrams\nare impractical for most hosts and networks.

    \n
  • \n
  • The MTU is the largest size a given link layer technology can support for datagrams.\nFor any link, IPv4 mandates a minimum MTU of 68 octets, while the recommended MTU\nfor IPv4 is 576 (typically recommended as the MTU for dial-up type applications),\nwhether they arrive whole or in fragments.

    \n

    For IPv6, the minimum MTU is 1280 octets, however, the mandatory minimum\nfragment reassembly buffer size is 1500 octets.\nThe value of 68 octets is very small, since most current link layer technologies have\na minimum MTU of 1500 (like Ethernet).

    \n
  • \n
\n

Note that it's impossible to know in advance the MTU of each link through which\na packet might travel, and that generally sending a datagram greater than\nthe (receiver) MTU won't work (the packet gets silently dropped, without\ninforming the source that the data did not reach its intended recipient).\n\n

\n" + }, + { + "textRaw": "dgram.bind(port, [address])", + "type": "method", + "name": "bind", + "signatures": [ + { + "params": [ + { + "textRaw": "`port` Integer ", + "name": "port", + "desc": "Integer" + }, + { + "textRaw": "`address` String, Optional ", + "name": "address", + "optional": true, + "desc": "String" + } + ] + }, + { + "params": [ + { + "name": "port" + }, + { + "name": "address", + "optional": true + } + ] + } + ], + "desc": "

For UDP sockets, listen for datagrams on a named port and optional address. If\naddress is not specified, the OS will try to listen on all addresses.\n\n

\n

Example of a UDP server listening on port 41234:\n\n

\n
var dgram = require("dgram");\n\nvar server = dgram.createSocket("udp4");\n\nserver.on("message", function (msg, rinfo) {\n  console.log("server got: " + msg + " from " +\n    rinfo.address + ":" + rinfo.port);\n});\n\nserver.on("listening", function () {\n  var address = server.address();\n  console.log("server listening " +\n      address.address + ":" + address.port);\n});\n\nserver.bind(41234);\n// server listening 0.0.0.0:41234
\n" + }, + { + "textRaw": "dgram.close()", + "type": "method", + "name": "close", + "desc": "

Close the underlying socket and stop listening for data on it.\n\n

\n", + "signatures": [ + { + "params": [] + } + ] + }, + { + "textRaw": "dgram.address()", + "type": "method", + "name": "address", + "desc": "

Returns an object containing the address information for a socket. For UDP sockets,\nthis object will contain address , family and port.\n\n

\n", + "signatures": [ + { + "params": [] + } + ] + }, + { + "textRaw": "dgram.setBroadcast(flag)", + "type": "method", + "name": "setBroadcast", + "signatures": [ + { + "params": [ + { + "textRaw": "`flag` Boolean ", + "name": "flag", + "desc": "Boolean" + } + ] + }, + { + "params": [ + { + "name": "flag" + } + ] + } + ], + "desc": "

Sets or clears the SO_BROADCAST socket option. When this option is set, UDP packets\nmay be sent to a local interface's broadcast address.\n\n

\n" + }, + { + "textRaw": "dgram.setTTL(ttl)", + "type": "method", + "name": "setTTL", + "signatures": [ + { + "params": [ + { + "textRaw": "`ttl` Integer ", + "name": "ttl", + "desc": "Integer" + } + ] + }, + { + "params": [ + { + "name": "ttl" + } + ] + } + ], + "desc": "

Sets the IP_TTL socket option. TTL stands for "Time to Live," but in this context it\nspecifies the number of IP hops that a packet is allowed to go through. Each router or\ngateway that forwards a packet decrements the TTL. If the TTL is decremented to 0 by a\nrouter, it will not be forwarded. Changing TTL values is typically done for network\nprobes or when multicasting.\n\n

\n

The argument to setTTL() is a number of hops between 1 and 255. The default on most\nsystems is 64.\n\n

\n" + }, + { + "textRaw": "dgram.setMulticastTTL(ttl)", + "type": "method", + "name": "setMulticastTTL", + "signatures": [ + { + "params": [ + { + "textRaw": "`ttl` Integer ", + "name": "ttl", + "desc": "Integer" + } + ] + }, + { + "params": [ + { + "name": "ttl" + } + ] + } + ], + "desc": "

Sets the IP_MULTICAST_TTL socket option. TTL stands for "Time to Live," but in this\ncontext it specifies the number of IP hops that a packet is allowed to go through,\nspecifically for multicast traffic. Each router or gateway that forwards a packet\ndecrements the TTL. If the TTL is decremented to 0 by a router, it will not be forwarded.\n\n

\n

The argument to setMulticastTTL() is a number of hops between 0 and 255. The default on most\nsystems is 1.\n\n

\n" + }, + { + "textRaw": "dgram.setMulticastLoopback(flag)", + "type": "method", + "name": "setMulticastLoopback", + "signatures": [ + { + "params": [ + { + "textRaw": "`flag` Boolean ", + "name": "flag", + "desc": "Boolean" + } + ] + }, + { + "params": [ + { + "name": "flag" + } + ] + } + ], + "desc": "

Sets or clears the IP_MULTICAST_LOOP socket option. When this option is set, multicast\npackets will also be received on the local interface.\n\n

\n" + }, + { + "textRaw": "dgram.addMembership(multicastAddress, [multicastInterface])", + "type": "method", + "name": "addMembership", + "signatures": [ + { + "params": [ + { + "textRaw": "`multicastAddress` String ", + "name": "multicastAddress", + "desc": "String" + }, + { + "textRaw": "`multicastInterface` String, Optional ", + "name": "multicastInterface", + "optional": true, + "desc": "String" + } + ] + }, + { + "params": [ + { + "name": "multicastAddress" + }, + { + "name": "multicastInterface", + "optional": true + } + ] + } + ], + "desc": "

Tells the kernel to join a multicast group with IP_ADD_MEMBERSHIP socket option.\n\n

\n

If multicastInterface is not specified, the OS will try to add membership to all valid\ninterfaces.\n\n

\n" + }, + { + "textRaw": "dgram.dropMembership(multicastAddress, [multicastInterface])", + "type": "method", + "name": "dropMembership", + "signatures": [ + { + "params": [ + { + "textRaw": "`multicastAddress` String ", + "name": "multicastAddress", + "desc": "String" + }, + { + "textRaw": "`multicastInterface` String, Optional ", + "name": "multicastInterface", + "optional": true, + "desc": "String" + } + ] + }, + { + "params": [ + { + "name": "multicastAddress" + }, + { + "name": "multicastInterface", + "optional": true + } + ] + } + ], + "desc": "

Opposite of addMembership - tells the kernel to leave a multicast group with\nIP_DROP_MEMBERSHIP socket option. This is automatically called by the kernel\nwhen the socket is closed or process terminates, so most apps will never need to call\nthis.\n\n

\n

If multicastInterface is not specified, the OS will try to drop membership to all valid\ninterfaces.\n\n

\n" + } + ] + } + ], + "type": "module", + "displayName": "dgram" + }, + { + "textRaw": "DNS", + "name": "dns", + "stability": 3, + "stabilityText": "Stable", + "desc": "

Use require('dns') to access this module. All methods in the dns module\nuse C-Ares except for dns.lookup which uses getaddrinfo(3) in a thread\npool. C-Ares is much faster than getaddrinfo but the system resolver is\nmore constant with how other programs operate. When a user does\nnet.connect(80, 'google.com') or http.get({ host: 'google.com' }) the\ndns.lookup method is used. Users who need to do a large number of look ups\nquickly should use the methods that go through C-Ares.\n\n

\n

Here is an example which resolves 'www.google.com' then reverse\nresolves the IP addresses which are returned.\n\n

\n
var dns = require('dns');\n\ndns.resolve4('www.google.com', function (err, addresses) {\n  if (err) throw err;\n\n  console.log('addresses: ' + JSON.stringify(addresses));\n\n  addresses.forEach(function (a) {\n    dns.reverse(a, function (err, domains) {\n      if (err) {\n        throw err;\n      }\n\n      console.log('reverse for ' + a + ': ' + JSON.stringify(domains));\n    });\n  });\n});
\n", + "methods": [ + { + "textRaw": "dns.lookup(domain, [family], callback)", + "type": "method", + "name": "lookup", + "desc": "

Resolves a domain (e.g. 'google.com') into the first found A (IPv4) or\nAAAA (IPv6) record.\nThe family can be the integer 4 or 6. Defaults to null that indicates\nboth Ip v4 and v6 address family.\n\n

\n

The callback has arguments (err, address, family). The address argument\nis a string representation of a IP v4 or v6 address. The family argument\nis either the integer 4 or 6 and denotes the family of address (not\nnecessarily the value initially passed to lookup).\n\n

\n

On error, err is an Error object, where err.code is the error code.\nKeep in mind that err.code will be set to 'ENOENT' not only when\nthe domain does not exist but also when the lookup fails in other ways\nsuch as no available file descriptors.\n\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "domain" + }, + { + "name": "family", + "optional": true + }, + { + "name": "callback" + } + ] + } + ] + }, + { + "textRaw": "dns.resolve(domain, [rrtype], callback)", + "type": "method", + "name": "resolve", + "desc": "

Resolves a domain (e.g. 'google.com') into an array of the record types\nspecified by rrtype. Valid rrtypes are 'A' (IPV4 addresses, default),\n'AAAA' (IPV6 addresses), 'MX' (mail exchange records), 'TXT' (text\nrecords), 'SRV' (SRV records), 'PTR' (used for reverse IP lookups),\n'NS' (name server records) and 'CNAME' (canonical name records).\n\n

\n

The callback has arguments (err, addresses). The type of each item\nin addresses is determined by the record type, and described in the\ndocumentation for the corresponding lookup methods below.\n\n

\n

On error, err is an Error object, where err.code is\none of the error codes listed below.\n\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "domain" + }, + { + "name": "rrtype", + "optional": true + }, + { + "name": "callback" + } + ] + } + ] + }, + { + "textRaw": "dns.resolve4(domain, callback)", + "type": "method", + "name": "resolve4", + "desc": "

The same as dns.resolve(), but only for IPv4 queries (A records).\naddresses is an array of IPv4 addresses (e.g.\n['74.125.79.104', '74.125.79.105', '74.125.79.106']).\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "domain" + }, + { + "name": "callback" + } + ] + } + ] + }, + { + "textRaw": "dns.resolve6(domain, callback)", + "type": "method", + "name": "resolve6", + "desc": "

The same as dns.resolve4() except for IPv6 queries (an AAAA query).\n\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "domain" + }, + { + "name": "callback" + } + ] + } + ] + }, + { + "textRaw": "dns.resolveMx(domain, callback)", + "type": "method", + "name": "resolveMx", + "desc": "

The same as dns.resolve(), but only for mail exchange queries (MX records).\n\n

\n

addresses is an array of MX records, each with a priority and an exchange\nattribute (e.g. [{'priority': 10, 'exchange': 'mx.example.com'},...]).\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "domain" + }, + { + "name": "callback" + } + ] + } + ] + }, + { + "textRaw": "dns.resolveTxt(domain, callback)", + "type": "method", + "name": "resolveTxt", + "desc": "

The same as dns.resolve(), but only for text queries (TXT records).\naddresses is an array of the text records available for domain (e.g.,\n['v=spf1 ip4:0.0.0.0 ~all']).\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "domain" + }, + { + "name": "callback" + } + ] + } + ] + }, + { + "textRaw": "dns.resolveSrv(domain, callback)", + "type": "method", + "name": "resolveSrv", + "desc": "

The same as dns.resolve(), but only for service records (SRV records).\naddresses is an array of the SRV records available for domain. Properties\nof SRV records are priority, weight, port, and name (e.g.,\n[{'priority': 10, {'weight': 5, 'port': 21223, 'name': 'service.example.com'}, ...]).\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "domain" + }, + { + "name": "callback" + } + ] + } + ] + }, + { + "textRaw": "dns.resolveNs(domain, callback)", + "type": "method", + "name": "resolveNs", + "desc": "

The same as dns.resolve(), but only for name server records (NS records).\naddresses is an array of the name server records available for domain\n(e.g., ['ns1.example.com', 'ns2.example.com']).\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "domain" + }, + { + "name": "callback" + } + ] + } + ] + }, + { + "textRaw": "dns.resolveCname(domain, callback)", + "type": "method", + "name": "resolveCname", + "desc": "

The same as dns.resolve(), but only for canonical name records (CNAME\nrecords). addresses is an array of the canonical name records available for\ndomain (e.g., ['bar.example.com']).\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "domain" + }, + { + "name": "callback" + } + ] + } + ] + }, + { + "textRaw": "dns.reverse(ip, callback)", + "type": "method", + "name": "reverse", + "desc": "

Reverse resolves an ip address to an array of domain names.\n\n

\n

The callback has arguments (err, domains).\n\n

\n

On error, err is an Error object, where err.code is\none of the error codes listed below.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "ip" + }, + { + "name": "callback" + } + ] + } + ] + } + ], + "modules": [ + { + "textRaw": "Error codes", + "name": "error_codes", + "desc": "

Each DNS query can return one of the following error codes:\n\n

\n
    \n
  • dns.NODATA: DNS server returned answer with no data.
  • \n
  • dns.FORMERR: DNS server claims query was misformatted.
  • \n
  • dns.SERVFAIL: DNS server returned general failure.
  • \n
  • dns.NOTFOUND: Domain name not found.
  • \n
  • dns.NOTIMP: DNS server does not implement requested operation.
  • \n
  • dns.REFUSED: DNS server refused query.
  • \n
  • dns.BADQUERY: Misformatted DNS query.
  • \n
  • dns.BADNAME: Misformatted domain name.
  • \n
  • dns.BADFAMILY: Unsupported address family.
  • \n
  • dns.BADRESP: Misformatted DNS reply.
  • \n
  • dns.CONNREFUSED: Could not contact DNS servers.
  • \n
  • dns.TIMEOUT: Timeout while contacting DNS servers.
  • \n
  • dns.EOF: End of file.
  • \n
  • dns.FILE: Error reading file.
  • \n
  • dns.NOMEM: Out of memory.
  • \n
  • dns.DESTRUCTION: Channel is being destroyed.
  • \n
  • dns.BADSTR: Misformatted string.
  • \n
  • dns.BADFLAGS: Illegal flags specified.
  • \n
  • dns.NONAME: Given hostname is not numeric.
  • \n
  • dns.BADHINTS: Illegal hints flags specified.
  • \n
  • dns.NOTINITIALIZED: c-ares library initialization not yet performed.
  • \n
  • dns.LOADIPHLPAPI: Error loading iphlpapi.dll.
  • \n
  • dns.ADDRGETNETWORKPARAMS: Could not find GetNetworkParams function.
  • \n
  • dns.CANCELLED: DNS query cancelled.
  • \n
\n", + "type": "module", + "displayName": "Error codes" + } + ], + "type": "module", + "displayName": "DNS" + }, + { + "textRaw": "HTTP", + "name": "http", + "stability": 3, + "stabilityText": "Stable", + "desc": "

To use the HTTP server and client one must require('http').\n\n

\n

The HTTP interfaces in Node are designed to support many features\nof the protocol which have been traditionally difficult to use.\nIn particular, large, possibly chunk-encoded, messages. The interface is\ncareful to never buffer entire requests or responses--the\nuser is able to stream data.\n\n

\n

HTTP message headers are represented by an object like this:\n\n

\n
{ 'content-length': '123',\n  'content-type': 'text/plain',\n  'connection': 'keep-alive',\n  'accept': '*/*' }
\n

Keys are lowercased. Values are not modified.\n\n

\n

In order to support the full spectrum of possible HTTP applications, Node's\nHTTP API is very low-level. It deals with stream handling and message\nparsing only. It parses a message into headers and body but it does not\nparse the actual headers or the body.\n\n\n

\n", + "properties": [ + { + "textRaw": "`STATUS_CODES` {Object} ", + "name": "STATUS_CODES", + "desc": "

A collection of all the standard HTTP response status codes, and the\nshort description of each. For example, http.STATUS_CODES[404] === 'Not\nFound'.\n\n

\n" + }, + { + "textRaw": "http.globalAgent", + "name": "globalAgent", + "desc": "

Global instance of Agent which is used as the default for all http client\nrequests.\n\n\n

\n" + }, + { + "textRaw": "http.ClientResponse", + "name": "ClientResponse", + "desc": "

This object is created when making a request with http.request(). It is\npassed to the 'response' event of the request object.\n\n

\n

The response implements the [Readable Stream][] interface. This is an\n[EventEmitter][] with the following events:\n\n\n

\n", + "events": [ + { + "textRaw": "Event: 'data'", + "type": "event", + "name": "data", + "desc": "

function (chunk) { }\n\n

\n

Emitted when a piece of the message body is received.\n\n

\n

Note that the data will be lost if there is no listener when a\nClientResponse emits a 'data' event.\n\n\n

\n", + "params": [] + }, + { + "textRaw": "Event: 'end'", + "type": "event", + "name": "end", + "desc": "

function () { }\n\n

\n

Emitted exactly once for each response. After that, no more 'data' events\nwill be emitted on the response.\n\n\n

\n", + "params": [] + }, + { + "textRaw": "Event: 'close'", + "type": "event", + "name": "close", + "desc": "

function () { }\n\n

\n

Indicates that the underlaying connection was terminated before\nresponse.end() was called or able to flush.\n\n

\n

Just like 'end', this event occurs only once per response, and no more\n'data' events will fire afterwards. See [http.ServerResponse][]'s 'close'\nevent for more information.\n\n

\n

Note: 'close' can fire after 'end', but not vice versa.\n\n\n

\n", + "params": [] + } + ], + "properties": [ + { + "textRaw": "response.statusCode", + "name": "statusCode", + "desc": "

The 3-digit HTTP response status code. E.G. 404.\n\n

\n" + }, + { + "textRaw": "response.httpVersion", + "name": "httpVersion", + "desc": "

The HTTP version of the connected-to server. Probably either\n'1.1' or '1.0'.\nAlso response.httpVersionMajor is the first integer and\nresponse.httpVersionMinor is the second.\n\n

\n" + }, + { + "textRaw": "response.headers", + "name": "headers", + "desc": "

The response headers object.\n\n

\n" + }, + { + "textRaw": "response.trailers", + "name": "trailers", + "desc": "

The response trailers object. Only populated after the 'end' event.\n\n

\n" + } + ], + "methods": [ + { + "textRaw": "response.setEncoding([encoding])", + "type": "method", + "name": "setEncoding", + "desc": "

Set the encoding for the response body. See [stream.setEncoding()][] for more\ninformation.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "encoding", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "response.pause()", + "type": "method", + "name": "pause", + "desc": "

Pauses response from emitting events. Useful to throttle back a download.\n\n

\n", + "signatures": [ + { + "params": [] + } + ] + }, + { + "textRaw": "response.resume()", + "type": "method", + "name": "resume", + "desc": "

Resumes a paused response.\n\n

\n", + "signatures": [ + { + "params": [] + } + ] + } + ] + } + ], + "methods": [ + { + "textRaw": "http.createServer([requestListener])", + "type": "method", + "name": "createServer", + "desc": "

Returns a new web server object.\n\n

\n

The requestListener is a function which is automatically\nadded to the 'request' event.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "requestListener", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "http.createClient([port], [host])", + "type": "method", + "name": "createClient", + "desc": "

This function is deprecated; please use [http.request()][] instead.\nConstructs a new HTTP client. port and host refer to the server to be\nconnected to.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "port", + "optional": true + }, + { + "name": "host", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "http.request(options, callback)", + "type": "method", + "name": "request", + "desc": "

Node maintains several connections per server to make HTTP requests.\nThis function allows one to transparently issue requests.\n\n

\n

options can be an object or a string. If options is a string, it is\nautomatically parsed with [url.parse()][].\n\n

\n

Options:\n\n

\n
    \n
  • host: A domain name or IP address of the server to issue the request to.\nDefaults to 'localhost'.
  • \n
  • hostname: To support url.parse() hostname is preferred over host
  • \n
  • port: Port of remote server. Defaults to 80.
  • \n
  • localAddress: Local interface to bind for network connections.
  • \n
  • socketPath: Unix Domain Socket (use one of host:port or socketPath)
  • \n
  • method: A string specifying the HTTP request method. Defaults to 'GET'.
  • \n
  • path: Request path. Defaults to '/'. Should include query string if any.\nE.G. '/index.html?page=12'
  • \n
  • headers: An object containing request headers.
  • \n
  • auth: Basic authentication i.e. 'user:password' to compute an\nAuthorization header.
  • \n
  • agent: Controls [Agent][] behavior. When an Agent is used request will\ndefault to Connection: keep-alive. Possible values:
      \n
    • undefined (default): use [global Agent][] for this host and port.
    • \n
    • Agent object: explicitly use the passed in Agent.
    • \n
    • false: opts out of connection pooling with an Agent, defaults request to\nConnection: close.
    • \n
    \n
  • \n
\n

http.request() returns an instance of the http.ClientRequest\nclass. The ClientRequest instance is a writable stream. If one needs to\nupload a file with a POST request, then write to the ClientRequest object.\n\n

\n

Example:\n\n

\n
var options = {\n  host: 'www.google.com',\n  port: 80,\n  path: '/upload',\n  method: 'POST'\n};\n\nvar req = http.request(options, function(res) {\n  console.log('STATUS: ' + res.statusCode);\n  console.log('HEADERS: ' + JSON.stringify(res.headers));\n  res.setEncoding('utf8');\n  res.on('data', function (chunk) {\n    console.log('BODY: ' + chunk);\n  });\n});\n\nreq.on('error', function(e) {\n  console.log('problem with request: ' + e.message);\n});\n\n// write data to request body\nreq.write('data\\n');\nreq.write('data\\n');\nreq.end();
\n

Note that in the example req.end() was called. With http.request() one\nmust always call req.end() to signify that you're done with the request -\neven if there is no data being written to the request body.\n\n

\n

If any error is encountered during the request (be that with DNS resolution,\nTCP level errors, or actual HTTP parse errors) an 'error' event is emitted\non the returned request object.\n\n

\n

There are a few special headers that should be noted.\n\n

\n
    \n
  • Sending a 'Connection: keep-alive' will notify Node that the connection to\nthe server should be persisted until the next request.

    \n
  • \n
  • Sending a 'Content-length' header will disable the default chunked encoding.

    \n
  • \n
  • Sending an 'Expect' header will immediately send the request headers.\nUsually, when sending 'Expect: 100-continue', you should both set a timeout\nand listen for the continue event. See RFC2616 Section 8.2.3 for more\ninformation.

    \n
  • \n
  • Sending an Authorization header will override using the auth option\nto compute basic authentication.

    \n
  • \n
\n", + "signatures": [ + { + "params": [ + { + "name": "options" + }, + { + "name": "callback" + } + ] + } + ] + }, + { + "textRaw": "http.get(options, callback)", + "type": "method", + "name": "get", + "desc": "

Since most requests are GET requests without bodies, Node provides this\nconvenience method. The only difference between this method and http.request()\nis that it sets the method to GET and calls req.end() automatically.\n\n

\n

Example:\n\n

\n
http.get("http://www.google.com/index.html", function(res) {\n  console.log("Got response: " + res.statusCode);\n}).on('error', function(e) {\n  console.log("Got error: " + e.message);\n});
\n", + "signatures": [ + { + "params": [ + { + "name": "options" + }, + { + "name": "callback" + } + ] + } + ] + } + ], + "classes": [ + { + "textRaw": "Class: http.Server", + "type": "class", + "name": "http.Server", + "desc": "

This is an [EventEmitter][] with the following events:\n\n

\n", + "events": [ + { + "textRaw": "Event: 'request'", + "type": "event", + "name": "request", + "desc": "

function (request, response) { }\n\n

\n

Emitted each time there is a request. Note that there may be multiple requests\nper connection (in the case of keep-alive connections).\n request is an instance of http.ServerRequest and response is\n an instance of http.ServerResponse\n\n

\n", + "params": [] + }, + { + "textRaw": "Event: 'connection'", + "type": "event", + "name": "connection", + "desc": "

function (socket) { }\n\n

\n

When a new TCP stream is established. socket is an object of type\n net.Socket. Usually users will not want to access this event. The\n socket can also be accessed at request.connection.\n\n

\n", + "params": [] + }, + { + "textRaw": "Event: 'close'", + "type": "event", + "name": "close", + "desc": "

function () { }\n\n

\n

Emitted when the server closes.\n\n

\n", + "params": [] + }, + { + "textRaw": "Event: 'checkContinue'", + "type": "event", + "name": "checkContinue", + "desc": "

function (request, response) { }\n\n

\n

Emitted each time a request with an http Expect: 100-continue is received.\nIf this event isn't listened for, the server will automatically respond\nwith a 100 Continue as appropriate.\n\n

\n

Handling this event involves calling response.writeContinue if the client\nshould continue to send the request body, or generating an appropriate HTTP\nresponse (e.g., 400 Bad Request) if the client should not continue to send the\nrequest body.\n\n

\n

Note that when this event is emitted and handled, the request event will\nnot be emitted.\n\n

\n", + "params": [] + }, + { + "textRaw": "Event: 'connect'", + "type": "event", + "name": "connect", + "desc": "

function (request, socket, head) { }\n\n

\n

Emitted each time a client requests a http CONNECT method. If this event isn't\nlistened for, then clients requesting a CONNECT method will have their\nconnections closed.\n\n

\n
    \n
  • request is the arguments for the http request, as it is in the request\nevent.
  • \n
  • socket is the network socket between the server and client.
  • \n
  • head is an instance of Buffer, the first packet of the tunneling stream,\nthis may be empty.
  • \n
\n

After this event is emitted, the request's socket will not have a data\nevent listener, meaning you will need to bind to it in order to handle data\nsent to the server on that socket.\n\n

\n", + "params": [] + }, + { + "textRaw": "Event: 'upgrade'", + "type": "event", + "name": "upgrade", + "desc": "

function (request, socket, head) { }\n\n

\n

Emitted each time a client requests a http upgrade. If this event isn't\nlistened for, then clients requesting an upgrade will have their connections\nclosed.\n\n

\n
    \n
  • request is the arguments for the http request, as it is in the request\nevent.
  • \n
  • socket is the network socket between the server and client.
  • \n
  • head is an instance of Buffer, the first packet of the upgraded stream,\nthis may be empty.
  • \n
\n

After this event is emitted, the request's socket will not have a data\nevent listener, meaning you will need to bind to it in order to handle data\nsent to the server on that socket.\n\n

\n", + "params": [] + }, + { + "textRaw": "Event: 'clientError'", + "type": "event", + "name": "clientError", + "desc": "

function (exception) { }\n\n

\n

If a client connection emits an 'error' event - it will forwarded here.\n\n

\n", + "params": [] + } + ], + "methods": [ + { + "textRaw": "server.listen(port, [hostname], [backlog], [callback])", + "type": "method", + "name": "listen", + "desc": "

Begin accepting connections on the specified port and hostname. If the\nhostname is omitted, the server will accept connections directed to any\nIPv4 address (INADDR_ANY).\n\n

\n

To listen to a unix socket, supply a filename instead of port and hostname.\n\n

\n

Backlog is the maximum length of the queue of pending connections.\nThe actual length will be determined by your OS through sysctl settings such as\ntcp_max_syn_backlog and somaxconn on linux. The default value of this\nparameter is 511 (not 512).\n\n

\n

This function is asynchronous. The last parameter callback will be added as\na listener for the ['listening'][] event. See also [net.Server.listen(port)][].\n\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "port" + }, + { + "name": "hostname", + "optional": true + }, + { + "name": "backlog", + "optional": true + }, + { + "name": "callback", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "server.listen(path, [callback])", + "type": "method", + "name": "listen", + "desc": "

Start a UNIX socket server listening for connections on the given path.\n\n

\n

This function is asynchronous. The last parameter callback will be added as\na listener for the ['listening'][] event. See also [net.Server.listen(path)][].\n\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "path" + }, + { + "name": "callback", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "server.listen(handle, [callback])", + "type": "method", + "name": "listen", + "signatures": [ + { + "params": [ + { + "textRaw": "`handle` {Object} ", + "name": "handle", + "type": "Object" + }, + { + "textRaw": "`callback` {Function} ", + "name": "callback", + "type": "Function", + "optional": true + } + ] + }, + { + "params": [ + { + "name": "handle" + }, + { + "name": "callback", + "optional": true + } + ] + } + ], + "desc": "

The handle object can be set to either a server or socket (anything\nwith an underlying _handle member), or a {fd: <n>} object.\n\n

\n

This will cause the server to accept connections on the specified\nhandle, but it is presumed that the file descriptor or handle has\nalready been bound to a port or domain socket.\n\n

\n

Listening on a file descriptor is not supported on Windows.\n\n

\n

This function is asynchronous. The last parameter callback will be added as\na listener for the 'listening' event.\nSee also net.Server.listen().\n\n

\n" + }, + { + "textRaw": "server.close([callback])", + "type": "method", + "name": "close", + "desc": "

Stops the server from accepting new connections. See [net.Server.close()][].\n\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "callback", + "optional": true + } + ] + } + ] + } + ], + "properties": [ + { + "textRaw": "server.maxHeadersCount", + "name": "maxHeadersCount", + "desc": "

Limits maximum incoming headers count, equal to 1000 by default. If set to 0 -\nno limit will be applied.\n\n\n

\n" + } + ] + }, + { + "textRaw": "Class: http.ServerRequest", + "type": "class", + "name": "http.ServerRequest", + "desc": "

This object is created internally by a HTTP server -- not by\nthe user -- and passed as the first argument to a 'request' listener.\n\n

\n

The request implements the [Readable Stream][] interface. This is an\n[EventEmitter][] with the following events:\n\n

\n", + "events": [ + { + "textRaw": "Event: 'data'", + "type": "event", + "name": "data", + "desc": "

function (chunk) { }\n\n

\n

Emitted when a piece of the message body is received. The chunk is a string if\nan encoding has been set with request.setEncoding(), otherwise it's a\n[Buffer][].\n\n

\n

Note that the data will be lost if there is no listener when a\nServerRequest emits a 'data' event.\n\n

\n", + "params": [] + }, + { + "textRaw": "Event: 'end'", + "type": "event", + "name": "end", + "desc": "

function () { }\n\n

\n

Emitted exactly once for each request. After that, no more 'data' events\nwill be emitted on the request.\n\n

\n", + "params": [] + }, + { + "textRaw": "Event: 'close'", + "type": "event", + "name": "close", + "desc": "

function () { }\n\n

\n

Indicates that the underlaying connection was terminated before\nresponse.end() was called or able to flush.\n\n

\n

Just like 'end', this event occurs only once per request, and no more 'data'\nevents will fire afterwards.\n\n

\n

Note: 'close' can fire after 'end', but not vice versa.\n\n

\n", + "params": [] + } + ], + "properties": [ + { + "textRaw": "request.method", + "name": "method", + "desc": "

The request method as a string. Read only. Example:\n'GET', 'DELETE'.\n\n\n

\n" + }, + { + "textRaw": "request.url", + "name": "url", + "desc": "

Request URL string. This contains only the URL that is\npresent in the actual HTTP request. If the request is:\n\n

\n
GET /status?name=ryan HTTP/1.1\\r\\n\nAccept: text/plain\\r\\n\n\\r\\n
\n

Then request.url will be:\n\n

\n
'/status?name=ryan'
\n

If you would like to parse the URL into its parts, you can use\nrequire('url').parse(request.url). Example:\n\n

\n
node> require('url').parse('/status?name=ryan')\n{ href: '/status?name=ryan',\n  search: '?name=ryan',\n  query: 'name=ryan',\n  pathname: '/status' }
\n

If you would like to extract the params from the query string,\nyou can use the require('querystring').parse function, or pass\ntrue as the second argument to require('url').parse. Example:\n\n

\n
node> require('url').parse('/status?name=ryan', true)\n{ href: '/status?name=ryan',\n  search: '?name=ryan',\n  query: { name: 'ryan' },\n  pathname: '/status' }
\n" + }, + { + "textRaw": "request.headers", + "name": "headers", + "desc": "

Read only map of header names and values. Header names are lower-cased.\nExample:\n\n

\n
// Prints something like:\n//\n// { 'user-agent': 'curl/7.22.0',\n//   host: '127.0.0.1:8000',\n//   accept: '*/*' }\nconsole.log(request.headers);
\n" + }, + { + "textRaw": "request.trailers", + "name": "trailers", + "desc": "

Read only; HTTP trailers (if present). Only populated after the 'end' event.\n\n

\n" + }, + { + "textRaw": "request.httpVersion", + "name": "httpVersion", + "desc": "

The HTTP protocol version as a string. Read only. Examples:\n'1.1', '1.0'.\nAlso request.httpVersionMajor is the first integer and\nrequest.httpVersionMinor is the second.\n\n\n

\n" + }, + { + "textRaw": "request.connection", + "name": "connection", + "desc": "

The net.Socket object associated with the connection.\n\n\n

\n

With HTTPS support, use request.connection.verifyPeer() and\nrequest.connection.getPeerCertificate() to obtain the client's\nauthentication details.\n\n\n\n

\n" + } + ], + "methods": [ + { + "textRaw": "request.setEncoding([encoding])", + "type": "method", + "name": "setEncoding", + "desc": "

Set the encoding for the request body. See [stream.setEncoding()][] for more\ninformation.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "encoding", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "request.pause()", + "type": "method", + "name": "pause", + "desc": "

Pauses request from emitting events. Useful to throttle back an upload.\n\n\n

\n", + "signatures": [ + { + "params": [] + } + ] + }, + { + "textRaw": "request.resume()", + "type": "method", + "name": "resume", + "desc": "

Resumes a paused request.\n\n

\n", + "signatures": [ + { + "params": [] + } + ] + } + ] + }, + { + "textRaw": "Class: http.ServerResponse", + "type": "class", + "name": "http.ServerResponse", + "desc": "

This object is created internally by a HTTP server--not by the user. It is\npassed as the second parameter to the 'request' event.\n\n

\n

The response implements the [Writable Stream][] interface. This is an\n[EventEmitter][] with the following events:\n\n

\n", + "events": [ + { + "textRaw": "Event: 'close'", + "type": "event", + "name": "close", + "desc": "

function () { }\n\n

\n

Indicates that the underlaying connection was terminated before\nresponse.end() was called or able to flush.\n\n

\n", + "params": [] + } + ], + "methods": [ + { + "textRaw": "response.writeContinue()", + "type": "method", + "name": "writeContinue", + "desc": "

Sends a HTTP/1.1 100 Continue message to the client, indicating that\nthe request body should be sent. See the ['checkContinue'][] event on Server.\n\n

\n", + "signatures": [ + { + "params": [] + } + ] + }, + { + "textRaw": "response.writeHead(statusCode, [reasonPhrase], [headers])", + "type": "method", + "name": "writeHead", + "desc": "

Sends a response header to the request. The status code is a 3-digit HTTP\nstatus code, like 404. The last argument, headers, are the response headers.\nOptionally one can give a human-readable reasonPhrase as the second\nargument.\n\n

\n

Example:\n\n

\n
var body = 'hello world';\nresponse.writeHead(200, {\n  'Content-Length': body.length,\n  'Content-Type': 'text/plain' });
\n

This method must only be called once on a message and it must\nbe called before response.end() is called.\n\n

\n

If you call response.write() or response.end() before calling this, the\nimplicit/mutable headers will be calculated and call this function for you.\n\n

\n

Note: that Content-Length is given in bytes not characters. The above example\nworks because the string 'hello world' contains only single byte characters.\nIf the body contains higher coded characters then Buffer.byteLength()\nshould be used to determine the number of bytes in a given encoding.\nAnd Node does not check whether Content-Length and the length of the body\nwhich has been transmitted are equal or not.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "statusCode" + }, + { + "name": "reasonPhrase", + "optional": true + }, + { + "name": "headers", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "response.setHeader(name, value)", + "type": "method", + "name": "setHeader", + "desc": "

Sets a single header value for implicit headers. If this header already exists\nin the to-be-sent headers, its value will be replaced. Use an array of strings\nhere if you need to send multiple headers with the same name.\n\n

\n

Example:\n\n

\n
response.setHeader("Content-Type", "text/html");
\n

or\n\n

\n
response.setHeader("Set-Cookie", ["type=ninja", "language=javascript"]);
\n", + "signatures": [ + { + "params": [ + { + "name": "name" + }, + { + "name": "value" + } + ] + } + ] + }, + { + "textRaw": "response.getHeader(name)", + "type": "method", + "name": "getHeader", + "desc": "

Reads out a header that's already been queued but not sent to the client. Note\nthat the name is case insensitive. This can only be called before headers get\nimplicitly flushed.\n\n

\n

Example:\n\n

\n
var contentType = response.getHeader('content-type');
\n", + "signatures": [ + { + "params": [ + { + "name": "name" + } + ] + } + ] + }, + { + "textRaw": "response.removeHeader(name)", + "type": "method", + "name": "removeHeader", + "desc": "

Removes a header that's queued for implicit sending.\n\n

\n

Example:\n\n

\n
response.removeHeader("Content-Encoding");
\n", + "signatures": [ + { + "params": [ + { + "name": "name" + } + ] + } + ] + }, + { + "textRaw": "response.write(chunk, [encoding])", + "type": "method", + "name": "write", + "desc": "

If this method is called and response.writeHead() has not been called, it will\nswitch to implicit header mode and flush the implicit headers.\n\n

\n

This sends a chunk of the response body. This method may\nbe called multiple times to provide successive parts of the body.\n\n

\n

chunk can be a string or a buffer. If chunk is a string,\nthe second parameter specifies how to encode it into a byte stream.\nBy default the encoding is 'utf8'.\n\n

\n

Note: This is the raw HTTP body and has nothing to do with\nhigher-level multi-part body encodings that may be used.\n\n

\n

The first time response.write() is called, it will send the buffered\nheader information and the first body to the client. The second time\nresponse.write() is called, Node assumes you're going to be streaming\ndata, and sends that separately. That is, the response is buffered up to the\nfirst chunk of body.\n\n

\n

Returns true if the entire data was flushed successfully to the kernel\nbuffer. Returns false if all or part of the data was queued in user memory.\n'drain' will be emitted when the buffer is again free.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "chunk" + }, + { + "name": "encoding", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "response.addTrailers(headers)", + "type": "method", + "name": "addTrailers", + "desc": "

This method adds HTTP trailing headers (a header but at the end of the\nmessage) to the response.\n\n

\n

Trailers will only be emitted if chunked encoding is used for the\nresponse; if it is not (e.g., if the request was HTTP/1.0), they will\nbe silently discarded.\n\n

\n

Note that HTTP requires the Trailer header to be sent if you intend to\nemit trailers, with a list of the header fields in its value. E.g.,\n\n

\n
response.writeHead(200, { 'Content-Type': 'text/plain',\n                          'Trailer': 'Content-MD5' });\nresponse.write(fileData);\nresponse.addTrailers({'Content-MD5': "7895bf4b8828b55ceaf47747b4bca667"});\nresponse.end();
\n", + "signatures": [ + { + "params": [ + { + "name": "headers" + } + ] + } + ] + }, + { + "textRaw": "response.end([data], [encoding])", + "type": "method", + "name": "end", + "desc": "

This method signals to the server that all of the response headers and body\nhave been sent; that server should consider this message complete.\nThe method, response.end(), MUST be called on each\nresponse.\n\n

\n

If data is specified, it is equivalent to calling response.write(data, encoding)\nfollowed by response.end().\n\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "data", + "optional": true + }, + { + "name": "encoding", + "optional": true + } + ] + } + ] + } + ], + "properties": [ + { + "textRaw": "response.statusCode", + "name": "statusCode", + "desc": "

When using implicit headers (not calling response.writeHead() explicitly), this property\ncontrols the status code that will be sent to the client when the headers get\nflushed.\n\n

\n

Example:\n\n

\n
response.statusCode = 404;
\n

After response header was sent to the client, this property indicates the\nstatus code which was sent out.\n\n

\n" + }, + { + "textRaw": "response.sendDate", + "name": "sendDate", + "desc": "

When true, the Date header will be automatically generated and sent in \nthe response if it is not already present in the headers. Defaults to true.\n\n

\n

This should only be disabled for testing; HTTP requires the Date header\nin responses.\n\n

\n" + } + ] + }, + { + "textRaw": "Class: http.Agent", + "type": "class", + "name": "http.Agent", + "desc": "

In node 0.5.3+ there is a new implementation of the HTTP Agent which is used\nfor pooling sockets used in HTTP client requests.\n\n

\n

Previously, a single agent instance helped pool for a single host+port. The\ncurrent implementation now holds sockets for any number of hosts.\n\n

\n

The current HTTP Agent also defaults client requests to using\nConnection:keep-alive. If no pending HTTP requests are waiting on a socket\nto become free the socket is closed. This means that node's pool has the\nbenefit of keep-alive when under load but still does not require developers\nto manually close the HTTP clients using keep-alive.\n\n

\n

Sockets are removed from the agent's pool when the socket emits either a\n"close" event or a special "agentRemove" event. This means that if you intend\nto keep one HTTP request open for a long time and don't want it to stay in the\npool you can do something along the lines of:\n\n

\n
http.get(options, function(res) {\n  // Do stuff\n}).on("socket", function (socket) {\n  socket.emit("agentRemove");\n});
\n

Alternatively, you could just opt out of pooling entirely using agent:false:\n\n

\n
http.get({host:'localhost', port:80, path:'/', agent:false}, function (res) {\n  // Do stuff\n})
\n", + "properties": [ + { + "textRaw": "agent.maxSockets", + "name": "maxSockets", + "desc": "

By default set to 5. Determines how many concurrent sockets the agent can have \nopen per host.\n\n

\n" + }, + { + "textRaw": "agent.sockets", + "name": "sockets", + "desc": "

An object which contains arrays of sockets currently in use by the Agent. Do not \nmodify.\n\n

\n" + }, + { + "textRaw": "agent.requests", + "name": "requests", + "desc": "

An object which contains queues of requests that have not yet been assigned to \nsockets. Do not modify.\n\n

\n" + } + ] + }, + { + "textRaw": "Class: http.ClientRequest", + "type": "class", + "name": "http.ClientRequest", + "desc": "

This object is created internally and returned from http.request(). It\nrepresents an in-progress request whose header has already been queued. The\nheader is still mutable using the setHeader(name, value), getHeader(name),\nremoveHeader(name) API. The actual header will be sent along with the first\ndata chunk or when closing the connection.\n\n

\n

To get the response, add a listener for 'response' to the request object.\n'response' will be emitted from the request object when the response\nheaders have been received. The 'response' event is executed with one\nargument which is an instance of http.ClientResponse.\n\n

\n

During the 'response' event, one can add listeners to the\nresponse object; particularly to listen for the 'data' event. Note that\nthe 'response' event is called before any part of the response body is received,\nso there is no need to worry about racing to catch the first part of the\nbody. As long as a listener for 'data' is added during the 'response'\nevent, the entire body will be caught.\n\n\n

\n
// Good\nrequest.on('response', function (response) {\n  response.on('data', function (chunk) {\n    console.log('BODY: ' + chunk);\n  });\n});\n\n// Bad - misses all or part of the body\nrequest.on('response', function (response) {\n  setTimeout(function () {\n    response.on('data', function (chunk) {\n      console.log('BODY: ' + chunk);\n    });\n  }, 10);\n});
\n

Note: Node does not check whether Content-Length and the length of the body\nwhich has been transmitted are equal or not.\n\n

\n

The request implements the [Writable Stream][] interface. This is an\n[EventEmitter][] with the following events:\n\n

\n", + "events": [ + { + "textRaw": "Event 'response'", + "type": "event", + "name": "response", + "desc": "

function (response) { }\n\n

\n

Emitted when a response is received to this request. This event is emitted only\nonce. The response argument will be an instance of http.ClientResponse.\n\n

\n

Options:\n\n

\n
    \n
  • host: A domain name or IP address of the server to issue the request to.
  • \n
  • port: Port of remote server.
  • \n
  • socketPath: Unix Domain Socket (use one of host:port or socketPath)
  • \n
\n", + "params": [] + }, + { + "textRaw": "Event: 'socket'", + "type": "event", + "name": "socket", + "desc": "

function (socket) { }\n\n

\n

Emitted after a socket is assigned to this request.\n\n

\n", + "params": [] + }, + { + "textRaw": "Event: 'connect'", + "type": "event", + "name": "connect", + "desc": "

function (response, socket, head) { }\n\n

\n

Emitted each time a server responds to a request with a CONNECT method. If this\nevent isn't being listened for, clients receiving a CONNECT method will have\ntheir connections closed.\n\n

\n

A client server pair that show you how to listen for the connect event.\n\n

\n
var http = require('http');\nvar net = require('net');\nvar url = require('url');\n\n// Create an HTTP tunneling proxy\nvar proxy = http.createServer(function (req, res) {\n  res.writeHead(200, {'Content-Type': 'text/plain'});\n  res.end('okay');\n});\nproxy.on('connect', function(req, cltSocket, head) {\n  // connect to an origin server\n  var srvUrl = url.parse('http://' + req.url);\n  var srvSocket = net.connect(srvUrl.port, srvUrl.hostname, function() {\n    cltSocket.write('HTTP/1.1 200 Connection Established\\r\\n' +\n                    'Proxy-agent: Node-Proxy\\r\\n' +\n                    '\\r\\n');\n    srvSocket.write(head);\n    srvSocket.pipe(cltSocket);\n    cltSocket.pipe(srvSocket);\n  });\n});\n\n// now that proxy is running\nproxy.listen(1337, '127.0.0.1', function() {\n\n  // make a request to a tunneling proxy\n  var options = {\n    port: 1337,\n    host: '127.0.0.1',\n    method: 'CONNECT',\n    path: 'www.google.com:80'\n  };\n\n  var req = http.request(options);\n  req.end();\n\n  req.on('connect', function(res, socket, head) {\n    console.log('got connected!');\n\n    // make a request over an HTTP tunnel\n    socket.write('GET / HTTP/1.1\\r\\n' +\n                 'Host: www.google.com:80\\r\\n' +\n                 'Connection: close\\r\\n' +\n                 '\\r\\n');\n    socket.on('data', function(chunk) {\n      console.log(chunk.toString());\n    });\n    socket.on('end', function() {\n      proxy.close();\n    });\n  });\n});
\n", + "params": [] + }, + { + "textRaw": "Event: 'upgrade'", + "type": "event", + "name": "upgrade", + "desc": "

function (response, socket, head) { }\n\n

\n

Emitted each time a server responds to a request with an upgrade. If this\nevent isn't being listened for, clients receiving an upgrade header will have\ntheir connections closed.\n\n

\n

A client server pair that show you how to listen for the upgrade event.\n\n

\n
var http = require('http');\n\n// Create an HTTP server\nvar srv = http.createServer(function (req, res) {\n  res.writeHead(200, {'Content-Type': 'text/plain'});\n  res.end('okay');\n});\nsrv.on('upgrade', function(req, socket, head) {\n  socket.write('HTTP/1.1 101 Web Socket Protocol Handshake\\r\\n' +\n               'Upgrade: WebSocket\\r\\n' +\n               'Connection: Upgrade\\r\\n' +\n               '\\r\\n');\n\n  socket.pipe(socket); // echo back\n});\n\n// now that server is running\nsrv.listen(1337, '127.0.0.1', function() {\n\n  // make a request\n  var options = {\n    port: 1337,\n    host: '127.0.0.1',\n    headers: {\n      'Connection': 'Upgrade',\n      'Upgrade': 'websocket'\n    }\n  };\n\n  var req = http.request(options);\n  req.end();\n\n  req.on('upgrade', function(res, socket, upgradeHead) {\n    console.log('got upgraded!');\n    socket.end();\n    process.exit(0);\n  });\n});
\n", + "params": [] + }, + { + "textRaw": "Event: 'continue'", + "type": "event", + "name": "continue", + "desc": "

function () { }\n\n

\n

Emitted when the server sends a '100 Continue' HTTP response, usually because\nthe request contained 'Expect: 100-continue'. This is an instruction that\nthe client should send the request body.\n\n

\n", + "params": [] + } + ], + "methods": [ + { + "textRaw": "request.write(chunk, [encoding])", + "type": "method", + "name": "write", + "desc": "

Sends a chunk of the body. By calling this method\nmany times, the user can stream a request body to a\nserver--in that case it is suggested to use the\n['Transfer-Encoding', 'chunked'] header line when\ncreating the request.\n\n

\n

The chunk argument should be a [Buffer][] or a string.\n\n

\n

The encoding argument is optional and only applies when chunk is a string.\nDefaults to 'utf8'.\n\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "chunk" + }, + { + "name": "encoding", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "request.end([data], [encoding])", + "type": "method", + "name": "end", + "desc": "

Finishes sending the request. If any parts of the body are\nunsent, it will flush them to the stream. If the request is\nchunked, this will send the terminating '0\\r\\n\\r\\n'.\n\n

\n

If data is specified, it is equivalent to calling\nrequest.write(data, encoding) followed by request.end().\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "data", + "optional": true + }, + { + "name": "encoding", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "request.abort()", + "type": "method", + "name": "abort", + "desc": "

Aborts a request. (New since v0.3.8.)\n\n

\n", + "signatures": [ + { + "params": [] + } + ] + }, + { + "textRaw": "request.setTimeout(timeout, [callback])", + "type": "method", + "name": "setTimeout", + "desc": "

Once a socket is assigned to this request and is connected\n[socket.setTimeout()][] will be called.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "timeout" + }, + { + "name": "callback", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "request.setNoDelay([noDelay])", + "type": "method", + "name": "setNoDelay", + "desc": "

Once a socket is assigned to this request and is connected\n[socket.setNoDelay()][] will be called.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "noDelay", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "request.setSocketKeepAlive([enable], [initialDelay])", + "type": "method", + "name": "setSocketKeepAlive", + "desc": "

Once a socket is assigned to this request and is connected\n[socket.setKeepAlive()][] will be called.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "enable", + "optional": true + }, + { + "name": "initialDelay", + "optional": true + } + ] + } + ] + } + ] + } + ], + "type": "module", + "displayName": "HTTP" + }, + { + "textRaw": "HTTPS", + "name": "https", + "stability": 3, + "stabilityText": "Stable", + "desc": "

HTTPS is the HTTP protocol over TLS/SSL. In Node this is implemented as a\nseparate module.\n\n

\n", + "classes": [ + { + "textRaw": "Class: https.Server", + "type": "class", + "name": "https.Server", + "desc": "

This class is a subclass of tls.Server and emits events same as\nhttp.Server. See http.Server for more information.\n\n

\n" + }, + { + "textRaw": "Class: https.Agent", + "type": "class", + "name": "https.Agent", + "desc": "

An Agent object for HTTPS similar to [http.Agent][]. See [https.request()][]\nfor more information.\n\n\n

\n" + } + ], + "methods": [ + { + "textRaw": "https.createServer(options, [requestListener])", + "type": "method", + "name": "createServer", + "desc": "

Returns a new HTTPS web server object. The options is similar to\n[tls.createServer()][]. The requestListener is a function which is\nautomatically added to the 'request' event.\n\n

\n

Example:\n\n

\n
// curl -k https://localhost:8000/\nvar https = require('https');\nvar fs = require('fs');\n\nvar options = {\n  key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'),\n  cert: fs.readFileSync('test/fixtures/keys/agent2-cert.pem')\n};\n\nhttps.createServer(options, function (req, res) {\n  res.writeHead(200);\n  res.end("hello world\\n");\n}).listen(8000);
\n

Or\n\n

\n
var https = require('https');\nvar fs = require('fs');\n\nvar options = {\n  pfx: fs.readFileSync('server.pfx')\n};\n\nhttps.createServer(options, function (req, res) {\n  res.writeHead(200);\n  res.end("hello world\\n");\n}).listen(8000);
\n", + "methods": [ + { + "textRaw": "server.listen(path, [callback])", + "type": "method", + "name": "listen", + "desc": "

See [http.listen()][] for details.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "handle" + }, + { + "name": "callback", + "optional": true + } + ] + }, + { + "params": [ + { + "name": "path" + }, + { + "name": "callback", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "server.listen(handle, [callback])", + "type": "method", + "name": "listen", + "desc": "

See [http.listen()][] for details.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "handle" + }, + { + "name": "callback", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "server.close([callback])", + "type": "method", + "name": "close", + "desc": "

See [http.close()][] for details.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "callback", + "optional": true + } + ] + } + ] + } + ], + "signatures": [ + { + "params": [ + { + "name": "options" + }, + { + "name": "requestListener", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "https.request(options, callback)", + "type": "method", + "name": "request", + "desc": "

Makes a request to a secure web server.\n\n

\n

options can be an object or a string. If options is a string, it is\nautomatically parsed with url.parse().\n\n

\n

All options from [http.request()][] are valid.\n\n

\n

Example:\n\n

\n
var https = require('https');\n\nvar options = {\n  host: 'encrypted.google.com',\n  port: 443,\n  path: '/',\n  method: 'GET'\n};\n\nvar req = https.request(options, function(res) {\n  console.log("statusCode: ", res.statusCode);\n  console.log("headers: ", res.headers);\n\n  res.on('data', function(d) {\n    process.stdout.write(d);\n  });\n});\nreq.end();\n\nreq.on('error', function(e) {\n  console.error(e);\n});
\n

The options argument has the following options\n\n

\n
    \n
  • host: IP or domain of host to make request to. Defaults to 'localhost'.
  • \n
  • port: port of host to request to. Defaults to 443.
  • \n
  • path: Path to request. Default '/'.
  • \n
  • method: HTTP request method. Default 'GET'.

    \n
  • \n
  • host: A domain name or IP address of the server to issue the request to.\nDefaults to 'localhost'.

    \n
  • \n
  • hostname: To support url.parse() hostname is preferred over host
  • \n
  • port: Port of remote server. Defaults to 443.
  • \n
  • method: A string specifying the HTTP request method. Defaults to 'GET'.
  • \n
  • path: Request path. Defaults to '/'. Should include query string if any.\nE.G. '/index.html?page=12'
  • \n
  • headers: An object containing request headers.
  • \n
  • auth: Basic authentication i.e. 'user:password' to compute an\nAuthorization header.
  • \n
  • agent: Controls [Agent][] behavior. When an Agent is used request will\ndefault to Connection: keep-alive. Possible values:
      \n
    • undefined (default): use [globalAgent][] for this host and port.
    • \n
    • Agent object: explicitly use the passed in Agent.
    • \n
    • false: opts out of connection pooling with an Agent, defaults request to\nConnection: close.
    • \n
    \n
  • \n
\n

The following options from [tls.connect()][] can also be specified. However, a\n[globalAgent][] silently ignores these.\n\n

\n
    \n
  • pfx: Certificate, Private key and CA certificates to use for SSL. Default null.
  • \n
  • key: Private key to use for SSL. Default null.
  • \n
  • passphrase: A string of passphrase for the private key or pfx. Default null.
  • \n
  • cert: Public x509 certificate to use. Default null.
  • \n
  • ca: An authority certificate or array of authority certificates to check\nthe remote host against.
  • \n
  • ciphers: A string describing the ciphers to use or exclude. Consult\nhttp://www.openssl.org/docs/apps/ciphers.html#CIPHER_LIST_FORMAT for\ndetails on the format.
  • \n
  • rejectUnauthorized: If true, the server certificate is verified against\nthe list of supplied CAs. An 'error' event is emitted if verification\nfails. Verification happens at the connection level, before the HTTP\nrequest is sent. Default false.
  • \n
\n

In order to specify these options, use a custom Agent.\n\n

\n

Example:\n\n

\n
var options = {\n  host: 'encrypted.google.com',\n  port: 443,\n  path: '/',\n  method: 'GET',\n  key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'),\n  cert: fs.readFileSync('test/fixtures/keys/agent2-cert.pem')\n};\noptions.agent = new https.Agent(options);\n\nvar req = https.request(options, function(res) {\n  ...\n}
\n

Or does not use an Agent.\n\n

\n

Example:\n\n

\n
var options = {\n  host: 'encrypted.google.com',\n  port: 443,\n  path: '/',\n  method: 'GET',\n  key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'),\n  cert: fs.readFileSync('test/fixtures/keys/agent2-cert.pem'),\n  agent: false\n};\n\nvar req = https.request(options, function(res) {\n  ...\n}
\n", + "signatures": [ + { + "params": [ + { + "name": "options" + }, + { + "name": "callback" + } + ] + } + ] + }, + { + "textRaw": "https.get(options, callback)", + "type": "method", + "name": "get", + "desc": "

Like http.get() but for HTTPS.\n\n

\n

options can be an object or a string. If options is a string, it is\nautomatically parsed with url.parse().\n\n

\n

Example:\n\n

\n
var https = require('https');\n\nhttps.get('https://encrypted.google.com/', function(res) {\n  console.log("statusCode: ", res.statusCode);\n  console.log("headers: ", res.headers);\n\n  res.on('data', function(d) {\n    process.stdout.write(d);\n  });\n\n}).on('error', function(e) {\n  console.error(e);\n});
\n", + "signatures": [ + { + "params": [ + { + "name": "options" + }, + { + "name": "callback" + } + ] + } + ] + } + ], + "properties": [ + { + "textRaw": "https.globalAgent", + "name": "globalAgent", + "desc": "

Global instance of [https.Agent][] for all HTTPS client requests.\n\n

\n" + } + ], + "type": "module", + "displayName": "HTTPS" + }, + { + "textRaw": "URL", + "name": "url", + "stability": 3, + "stabilityText": "Stable", + "desc": "

This module has utilities for URL resolution and parsing.\nCall require('url') to use it.\n\n

\n

Parsed URL objects have some or all of the following fields, depending on\nwhether or not they exist in the URL string. Any parts that are not in the URL\nstring will not be in the parsed object. Examples are shown for the URL\n\n

\n

'http://user:pass@host.com:8080/p/a/t/h?query=string#hash'\n\n

\n
    \n
  • href: The full URL that was originally parsed. Both the protocol and host are lowercased.

    \n

    Example: 'http://user:pass@host.com:8080/p/a/t/h?query=string#hash'

    \n
  • \n
  • protocol: The request protocol, lowercased.

    \n

    Example: 'http:'

    \n
  • \n
  • host: The full lowercased host portion of the URL, including port\ninformation.

    \n

    Example: 'host.com:8080'

    \n
  • \n
  • auth: The authentication information portion of a URL.

    \n

    Example: 'user:pass'

    \n
  • \n
  • hostname: Just the lowercased hostname portion of the host.

    \n

    Example: 'host.com'

    \n
  • \n
  • port: The port number portion of the host.

    \n

    Example: '8080'

    \n
  • \n
  • pathname: The path section of the URL, that comes after the host and\nbefore the query, including the initial slash if present.

    \n

    Example: '/p/a/t/h'

    \n
  • \n
  • search: The 'query string' portion of the URL, including the leading\nquestion mark.

    \n

    Example: '?query=string'

    \n
  • \n
  • path: Concatenation of pathname and search.

    \n

    Example: '/p/a/t/h?query=string'

    \n
  • \n
  • query: Either the 'params' portion of the query string, or a\nquerystring-parsed object.

    \n

    Example: 'query=string' or {'query':'string'}

    \n
  • \n
  • hash: The 'fragment' portion of the URL including the pound-sign.

    \n

    Example: '#hash'

    \n
  • \n
\n

The following methods are provided by the URL module:\n\n

\n", + "methods": [ + { + "textRaw": "url.parse(urlStr, [parseQueryString], [slashesDenoteHost])", + "type": "method", + "name": "parse", + "desc": "

Take a URL string, and return an object.\n\n

\n

Pass true as the second argument to also parse\nthe query string using the querystring module.\nDefaults to false.\n\n

\n

Pass true as the third argument to treat //foo/bar as\n{ host: 'foo', pathname: '/bar' } rather than\n{ pathname: '//foo/bar' }. Defaults to false.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "urlStr" + }, + { + "name": "parseQueryString", + "optional": true + }, + { + "name": "slashesDenoteHost", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "url.format(urlObj)", + "type": "method", + "name": "format", + "desc": "

Take a parsed URL object, and return a formatted URL string.\n\n

\n
    \n
  • href will be ignored.
  • \n
  • protocolis treated the same with or without the trailing : (colon).
      \n
    • The protocols http, https, ftp, gopher, file will be\npostfixed with :// (colon-slash-slash).
    • \n
    • All other protocols mailto, xmpp, aim, sftp, foo, etc will\nbe postfixed with : (colon)
    • \n
    \n
  • \n
  • auth will be used if present.
  • \n
  • hostname will only be used if host is absent.
  • \n
  • port will only be used if host is absent.
  • \n
  • host will be used in place of hostname and port
  • \n
  • pathname is treated the same with or without the leading / (slash)
  • \n
  • search will be used in place of query
  • \n
  • query (object; see querystring) will only be used if search is absent.
  • \n
  • search is treated the same with or without the leading ? (question mark)
  • \n
  • hash is treated the same with or without the leading # (pound sign, anchor)
  • \n
\n", + "signatures": [ + { + "params": [ + { + "name": "urlObj" + } + ] + } + ] + }, + { + "textRaw": "url.resolve(from, to)", + "type": "method", + "name": "resolve", + "desc": "

Take a base URL, and a href URL, and resolve them as a browser would for\nan anchor tag.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "from" + }, + { + "name": "to" + } + ] + } + ] + } + ], + "type": "module", + "displayName": "URL" + }, + { + "textRaw": "Query String", + "name": "querystring", + "stability": 3, + "stabilityText": "Stable", + "desc": "

This module provides utilities for dealing with query strings.\nIt provides the following methods:\n\n

\n", + "methods": [ + { + "textRaw": "querystring.stringify(obj, [sep], [eq])", + "type": "method", + "name": "stringify", + "desc": "

Serialize an object to a query string.\nOptionally override the default separator ('&') and assignment ('=')\ncharacters.\n\n

\n

Example:\n\n

\n
querystring.stringify({ foo: 'bar', baz: ['qux', 'quux'], corge: '' })\n// returns\n'foo=bar&baz=qux&baz=quux&corge='\n\nquerystring.stringify({foo: 'bar', baz: 'qux'}, ';', ':')\n// returns\n'foo:bar;baz:qux'
\n", + "signatures": [ + { + "params": [ + { + "name": "obj" + }, + { + "name": "sep", + "optional": true + }, + { + "name": "eq", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "querystring.parse(str, [sep], [eq], [options])", + "type": "method", + "name": "parse", + "desc": "

Deserialize a query string to an object.\nOptionally override the default separator ('&') and assignment ('=')\ncharacters.\n\n

\n

Options object may contain maxKeys property (equal to 1000 by default), it'll\nbe used to limit processed keys. Set it to 0 to remove key count limitation.\n\n

\n

Example:\n\n

\n
querystring.parse('foo=bar&baz=qux&baz=quux&corge')\n// returns\n{ foo: 'bar', baz: ['qux', 'quux'], corge: '' }
\n", + "signatures": [ + { + "params": [ + { + "name": "str" + }, + { + "name": "sep", + "optional": true + }, + { + "name": "eq", + "optional": true + }, + { + "name": "options", + "optional": true + } + ] + } + ] + } + ], + "properties": [ + { + "textRaw": "querystring.escape", + "name": "escape", + "desc": "

The escape function used by querystring.stringify,\nprovided so that it could be overridden if necessary.\n\n

\n" + }, + { + "textRaw": "querystring.unescape", + "name": "unescape", + "desc": "

The unescape function used by querystring.parse,\nprovided so that it could be overridden if necessary.\n\n

\n" + } + ], + "type": "module", + "displayName": "querystring" + }, + { + "textRaw": "punycode", + "name": "punycode", + "stability": 2, + "stabilityText": "Unstable", + "desc": "

Punycode.js is bundled with Node.js v0.6.2+. Use\nrequire('punycode') to access it. (To use it with other Node.js versions,\nuse npm to install the punycode module first.)\n\n

\n", + "methods": [ + { + "textRaw": "punycode.decode(string)", + "type": "method", + "name": "decode", + "desc": "

Converts a Punycode string of ASCII code points to a string of Unicode code\npoints.\n\n

\n
// decode domain name parts\npunycode.decode('maana-pta'); // 'mañana'\npunycode.decode('--dqo34k'); // '☃-⌘'
\n", + "signatures": [ + { + "params": [ + { + "name": "string" + } + ] + } + ] + }, + { + "textRaw": "punycode.encode(string)", + "type": "method", + "name": "encode", + "desc": "

Converts a string of Unicode code points to a Punycode string of ASCII code\npoints.\n\n

\n
// encode domain name parts\npunycode.encode('mañana'); // 'maana-pta'\npunycode.encode('☃-⌘'); // '--dqo34k'
\n", + "signatures": [ + { + "params": [ + { + "name": "string" + } + ] + } + ] + }, + { + "textRaw": "punycode.toUnicode(domain)", + "type": "method", + "name": "toUnicode", + "desc": "

Converts a Punycode string representing a domain name to Unicode. Only the\nPunycoded parts of the domain name will be converted, i.e. it doesn't matter if\nyou call it on a string that has already been converted to Unicode.\n\n

\n
// decode domain names\npunycode.toUnicode('xn--maana-pta.com'); // 'mañana.com'\npunycode.toUnicode('xn----dqo34k.com'); // '☃-⌘.com'
\n", + "signatures": [ + { + "params": [ + { + "name": "domain" + } + ] + } + ] + }, + { + "textRaw": "punycode.toASCII(domain)", + "type": "method", + "name": "toASCII", + "desc": "

Converts a Unicode string representing a domain name to Punycode. Only the\nnon-ASCII parts of the domain name will be converted, i.e. it doesn't matter if\nyou call it with a domain that's already in ASCII.\n\n

\n
// encode domain names\npunycode.toASCII('mañana.com'); // 'xn--maana-pta.com'\npunycode.toASCII('☃-⌘.com'); // 'xn----dqo34k.com'
\n", + "signatures": [ + { + "params": [ + { + "name": "domain" + } + ] + } + ] + } + ], + "properties": [ + { + "textRaw": "punycode.ucs2", + "name": "ucs2", + "modules": [ + { + "textRaw": "punycode.ucs2.decode(string)", + "name": "punycode.ucs2.decode(string)", + "desc": "

Creates an array containing the decimal code points of each Unicode character\nin the string. While JavaScript uses UCS-2\ninternally, this function\nwill convert a pair of surrogate halves (each of which UCS-2 exposes as\nseparate characters) into a single code point, matching UTF-16.\n\n

\n
punycode.ucs2.decode('abc'); // [97, 98, 99]\n// surrogate pair for U+1D306 tetragram for centre:\npunycode.ucs2.decode('\\uD834\\uDF06'); // [0x1D306]
\n", + "type": "module", + "displayName": "punycode.ucs2.decode(string)" + }, + { + "textRaw": "punycode.ucs2.encode(codePoints)", + "name": "punycode.ucs2.encode(codepoints)", + "desc": "

Creates a string based on an array of decimal code points.\n\n

\n
punycode.ucs2.encode([97, 98, 99]); // 'abc'\npunycode.ucs2.encode([0x1D306]); // '\\uD834\\uDF06'
\n", + "type": "module", + "displayName": "punycode.ucs2.encode(codePoints)" + } + ] + }, + { + "textRaw": "punycode.version", + "name": "version", + "desc": "

A string representing the current Punycode.js version number.\n\n

\n" + } + ], + "type": "module", + "displayName": "punycode" + }, + { + "textRaw": "Readline", + "name": "readline", + "stability": 2, + "stabilityText": "Unstable", + "desc": "

To use this module, do require('readline'). Readline allows reading of a\nstream (such as process.stdin) on a line-by-line basis.\n\n

\n

Note that once you've invoked this module, your node program will not\nterminate until you've closed the interface. Here's how to allow your\nprogram to gracefully exit:\n\n

\n
var readline = require('readline');\n\nvar rl = readline.createInterface({\n  input: process.stdin,\n  output: process.stdout\n});\n\nrl.question("What do you think of node.js? ", function(answer) {\n  // TODO: Log the answer in a database\n  console.log("Thank you for your valuable feedback:", answer);\n\n  rl.close();\n});
\n", + "methods": [ + { + "textRaw": "readline.createInterface(options)", + "type": "method", + "name": "createInterface", + "desc": "

Creates a readline Interface instance. Accepts an "options" Object that takes\nthe following values:\n\n

\n
    \n
  • input - the readable stream to listen to (Required).

    \n
  • \n
  • output - the writable stream to write readline data to (Required).

    \n
  • \n
  • completer - an optional function that is used for Tab autocompletion. See\nbelow for an example of using this.

    \n
  • \n
  • terminal - pass true if the input and output streams should be\ntreated like a TTY, and have ANSI/VT100 escape codes written to it.\nDefaults to checking isTTY on the output stream upon instantiation.

    \n
  • \n
\n

The completer function is given a the current line entered by the user, and\nis supposed to return an Array with 2 entries:\n\n

\n
    \n
  1. An Array with matching entries for the completion.

    \n
  2. \n
  3. The substring that was used for the matching.

    \n
  4. \n
\n

Which ends up looking something like:\n[[substr1, substr2, ...], originalsubstring].\n\n

\n

Example:\n\n

\n
function completer(line) {\n  var completions = '.help .error .exit .quit .q'.split(' ')\n  var hits = completions.filter(function(c) { return c.indexOf(line) == 0 })\n  // show all completions if none found\n  return [hits.length ? hits : completions, line]\n}
\n

Also completer can be run in async mode if it accepts two arguments:\n\n

\n
function completer(linePartial, callback) {\n  callback(null, [['123'], linePartial]);\n}
\n

createInterface is commonly used with process.stdin and\nprocess.stdout in order to accept user input:\n\n

\n
var readline = require('readline');\nvar rl = readline.createInterface({\n  input: process.stdin,\n  output: process.stdout\n});
\n

Once you have a readline instance, you most commonly listen for the\n"line" event.\n\n

\n

If terminal is true for this instance then the output stream will get\nthe best compatibility if it defines an output.columns property, and fires\na "resize" event on the output if/when the columns ever change\n(process.stdout does this automatically when it is a TTY).\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "options" + } + ] + } + ] + } + ], + "classes": [ + { + "textRaw": "Class: Interface", + "type": "class", + "name": "Interface", + "desc": "

The class that represents a readline interface with an input and output\nstream.\n\n

\n", + "methods": [ + { + "textRaw": "rl.setPrompt(prompt, length)", + "type": "method", + "name": "setPrompt", + "desc": "

Sets the prompt, for example when you run node on the command line, you see\n> , which is node's prompt.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "prompt" + }, + { + "name": "length" + } + ] + } + ] + }, + { + "textRaw": "rl.prompt([preserveCursor])", + "type": "method", + "name": "prompt", + "desc": "

Readies readline for input from the user, putting the current setPrompt\noptions on a new line, giving the user a new spot to write. Set preserveCursor\nto true to prevent the cursor placement being reset to 0.\n\n

\n

This will also resume the input stream used with createInterface if it has\nbeen paused.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "preserveCursor", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "rl.question(query, callback)", + "type": "method", + "name": "question", + "desc": "

Prepends the prompt with query and invokes callback with the user's\nresponse. Displays the query to the user, and then invokes callback\nwith the user's response after it has been typed.\n\n

\n

This will also resume the input stream used with createInterface if\nit has been paused.\n\n

\n

Example usage:\n\n

\n
interface.question('What is your favorite food?', function(answer) {\n  console.log('Oh, so your favorite food is ' + answer);\n});
\n", + "signatures": [ + { + "params": [ + { + "name": "query" + }, + { + "name": "callback" + } + ] + } + ] + }, + { + "textRaw": "rl.pause()", + "type": "method", + "name": "pause", + "desc": "

Pauses the readline input stream, allowing it to be resumed later if needed.\n\n

\n", + "signatures": [ + { + "params": [] + } + ] + }, + { + "textRaw": "rl.resume()", + "type": "method", + "name": "resume", + "desc": "

Resumes the readline input stream.\n\n

\n", + "signatures": [ + { + "params": [] + } + ] + }, + { + "textRaw": "rl.close()", + "type": "method", + "name": "close", + "desc": "

Closes the Interface instance, relinquishing control on the input and\noutput streams. The "close" event will also be emitted.\n\n

\n", + "signatures": [ + { + "params": [] + } + ] + }, + { + "textRaw": "rl.write(data, [key])", + "type": "method", + "name": "write", + "desc": "

Writes data to output stream. key is an object literal to represent a key\nsequence; available if the terminal is a TTY.\n\n

\n

This will also resume the input stream if it has been paused.\n\n

\n

Example:\n\n

\n
rl.write('Delete me!');\n// Simulate ctrl+u to delete the line written previously\nrl.write(null, {ctrl: true, name: 'u'});
\n", + "signatures": [ + { + "params": [ + { + "name": "data" + }, + { + "name": "key", + "optional": true + } + ] + } + ] + } + ] + } + ], + "modules": [ + { + "textRaw": "Events", + "name": "events", + "events": [ + { + "textRaw": "Event: 'line'", + "type": "event", + "name": "line", + "desc": "

function (line) {}\n\n

\n

Emitted whenever the input stream receives a \\n, usually received when the\nuser hits enter, or return. This is a good hook to listen for user input.\n\n

\n

Example of listening for line:\n\n

\n
rl.on('line', function (cmd) {\n  console.log('You just typed: '+cmd);\n});
\n", + "params": [] + }, + { + "textRaw": "Event: 'pause'", + "type": "event", + "name": "pause", + "desc": "

function () {}\n\n

\n

Emitted whenever the input stream is paused.\n\n

\n

Also emitted whenever the input stream is not paused and receives the\nSIGCONT event. (See events SIGTSTP and SIGCONT)\n\n

\n

Example of listening for pause:\n\n

\n
rl.on('pause', function() {\n  console.log('Readline paused.');\n});
\n", + "params": [] + }, + { + "textRaw": "Event: 'resume'", + "type": "event", + "name": "resume", + "desc": "

function () {}\n\n

\n

Emitted whenever the input stream is resumed.\n\n

\n

Example of listening for resume:\n\n

\n
rl.on('resume', function() {\n  console.log('Readline resumed.');\n});
\n", + "params": [] + }, + { + "textRaw": "Event: 'close'", + "type": "event", + "name": "close", + "desc": "

function () {}\n\n

\n

Emitted when close() is called.\n\n

\n

Also emitted when the input stream receives its "end" event. The Interface\ninstance should be considered "finished" once this is emitted. For example, when\nthe input stream receives ^D, respectively known as EOT.\n\n

\n

This event is also called if there is no SIGINT event listener present when\nthe input stream receives a ^C, respectively known as SIGINT.\n\n

\n", + "params": [] + }, + { + "textRaw": "Event: 'SIGINT'", + "type": "event", + "name": "SIGINT", + "desc": "

function () {}\n\n

\n

Emitted whenever the input stream receives a ^C, respectively known as\nSIGINT. If there is no SIGINT event listener present when the input\nstream receives a SIGINT, pause will be triggered.\n\n

\n

Example of listening for SIGINT:\n\n

\n
rl.on('SIGINT', function() {\n  rl.question('Are you sure you want to exit?', function(answer) {\n    if (answer.match(/^y(es)?$/i)) rl.pause();\n  });\n});
\n", + "params": [] + }, + { + "textRaw": "Event: 'SIGTSTP'", + "type": "event", + "name": "SIGTSTP", + "desc": "

function () {}\n\n

\n

This does not work on Windows.\n\n

\n

Emitted whenever the input stream receives a ^Z, respectively known as\nSIGTSTP. If there is no SIGTSTP event listener present when the input\nstream receives a SIGTSTP, the program will be sent to the background.\n\n

\n

When the program is resumed with fg, the pause and SIGCONT events will be\nemitted. You can use either to resume the stream.\n\n

\n

The pause and SIGCONT events will not be triggered if the stream was paused\nbefore the program was sent to the background.\n\n

\n

Example of listening for SIGTSTP:\n\n

\n
rl.on('SIGTSTP', function() {\n  // This will override SIGTSTP and prevent the program from going to the\n  // background.\n  console.log('Caught SIGTSTP.');\n});
\n", + "params": [] + }, + { + "textRaw": "Event: 'SIGCONT'", + "type": "event", + "name": "SIGCONT", + "desc": "

function () {}\n\n

\n

This does not work on Windows.\n\n

\n

Emitted whenever the input stream is sent to the background with ^Z,\nrespectively known as SIGTSTP, and then continued with fg(1). This event\nonly emits if the stream was not paused before sending the program to the\nbackground.\n\n

\n

Example of listening for SIGCONT:\n\n

\n
rl.on('SIGCONT', function() {\n  // `prompt` will automatically resume the stream\n  rl.prompt();\n});
\n

Example: Tiny CLI

\n

Here's an example of how to use all these together to craft a tiny command\nline interface:\n\n

\n
var readline = require('readline'),\n    rl = readline.createInterface(process.stdin, process.stdout);\n\nrl.setPrompt('OHAI> ');\nrl.prompt();\n\nrl.on('line', function(line) {\n  switch(line.trim()) {\n    case 'hello':\n      console.log('world!');\n      break;\n    default:\n      console.log('Say what? I might have heard `' + line.trim() + '`');\n      break;\n  }\n  rl.prompt();\n}).on('close', function() {\n  console.log('Have a great day!');\n  process.exit(0);\n});
\n", + "params": [] + } + ], + "type": "module", + "displayName": "Events" + } + ], + "type": "module", + "displayName": "Readline" + }, + { + "textRaw": "REPL", + "name": "repl", + "desc": "

A Read-Eval-Print-Loop (REPL) is available both as a standalone program and\neasily includable in other programs. The REPL provides a way to interactively\nrun JavaScript and see the results. It can be used for debugging, testing, or\njust trying things out.\n\n

\n

By executing node without any arguments from the command-line you will be\ndropped into the REPL. It has simplistic emacs line-editing.\n\n

\n
mjr:~$ node\nType '.help' for options.\n> a = [ 1, 2, 3];\n[ 1, 2, 3 ]\n> a.forEach(function (v) {\n...   console.log(v);\n...   });\n1\n2\n3
\n

For advanced line-editors, start node with the environmental variable\nNODE_NO_READLINE=1. This will start the main and debugger REPL in canonical\nterminal settings which will allow you to use with rlwrap.\n\n

\n

For example, you could add this to your bashrc file:\n\n

\n
alias node="env NODE_NO_READLINE=1 rlwrap node"
\n", + "methods": [ + { + "textRaw": "repl.start(options)", + "type": "method", + "name": "start", + "desc": "

Returns and starts a REPLServer instance. Accepts an "options" Object that\ntakes the following values:\n\n

\n
    \n
  • prompt - the prompt and stream for all I/O. Defaults to > .

    \n
  • \n
  • input - the readable stream to listen to. Defaults to process.stdin.

    \n
  • \n
  • output - the writable stream to write readline data to. Defaults to\nprocess.stdout.

    \n
  • \n
  • terminal - pass true if the stream should be treated like a TTY, and\nhave ANSI/VT100 escape codes written to it. Defaults to checking isTTY\non the output stream upon instantiation.

    \n
  • \n
  • eval - function that will be used to eval each given line. Defaults to\nan async wrapper for eval(). See below for an example of a custom eval.

    \n
  • \n
  • useColors - a boolean which specifies whether or not the writer function\nshould output colors. If a different writer function is set then this does\nnothing. Defaults to the repl's terminal value.

    \n
  • \n
  • useGlobal - if set to true, then the repl will use the global object,\ninstead of running scripts in a separate context. Defaults to false.

    \n
  • \n
  • ignoreUndefined - if set to true, then the repl will not output the\nreturn value of command if it's undefined. Defaults to false.

    \n
  • \n
  • writer - the function to invoke for each command that gets evaluated which\nreturns the formatting (including coloring) to display. Defaults to\nutil.inspect.

    \n
  • \n
\n

You can use your own eval function if it has following signature:\n\n

\n
function eval(cmd, context, filename, callback) {\n  callback(null, result);\n}
\n

Multiple REPLs may be started against the same running instance of node. Each\nwill share the same global object but will have unique I/O.\n\n

\n

Here is an example that starts a REPL on stdin, a Unix socket, and a TCP socket:\n\n

\n
var net = require("net"),\n    repl = require("repl");\n\nconnections = 0;\n\nrepl.start({\n  prompt: "node via stdin> ",\n  input: process.stdin,\n  output: process.stdout\n});\n\nnet.createServer(function (socket) {\n  connections += 1;\n  repl.start({\n    prompt: "node via Unix socket> ",\n    input: socket,\n    output: socket\n  }).on('exit', function() {\n    socket.end();\n  })\n}).listen("/tmp/node-repl-sock");\n\nnet.createServer(function (socket) {\n  connections += 1;\n  repl.start({\n    prompt: "node via TCP socket> ",\n    input: socket,\n    output: socket\n  }).on('exit', function() {\n    socket.end();\n  });\n}).listen(5001);
\n

Running this program from the command line will start a REPL on stdin. Other\nREPL clients may connect through the Unix socket or TCP socket. telnet is useful\nfor connecting to TCP sockets, and socat can be used to connect to both Unix and\nTCP sockets.\n\n

\n

By starting a REPL from a Unix socket-based server instead of stdin, you can\nconnect to a long-running node process without restarting it.\n\n

\n

For an example of running a "full-featured" (terminal) REPL over\na net.Server and net.Socket instance, see: https://gist.github.com/2209310\n\n

\n

For an example of running a REPL instance over curl(1),\nsee: https://gist.github.com/2053342\n\n

\n", + "events": [ + { + "textRaw": "Event: 'exit'", + "type": "event", + "name": "exit", + "desc": "

function () {}\n\n

\n

Emitted when the user exits the REPL in any of the defined ways. Namely, typing\n.exit at the repl, pressing Ctrl+C twice to signal SIGINT, or pressing Ctrl+D\nto signal "end" on the input stream.\n\n

\n

Example of listening for exit:\n\n

\n
r.on('exit', function () {\n  console.log('Got "exit" event from repl!');\n  process.exit();\n});
\n", + "params": [] + } + ], + "signatures": [ + { + "params": [ + { + "name": "options" + } + ] + } + ] + } + ], + "miscs": [ + { + "textRaw": "REPL Features", + "name": "REPL Features", + "type": "misc", + "desc": "

Inside the REPL, Control+D will exit. Multi-line expressions can be input.\nTab completion is supported for both global and local variables.\n\n

\n

The special variable _ (underscore) contains the result of the last expression.\n\n

\n
> [ "a", "b", "c" ]\n[ 'a', 'b', 'c' ]\n> _.length\n3\n> _ += 1\n4
\n

The REPL provides access to any variables in the global scope. You can expose\na variable to the REPL explicitly by assigning it to the context object\nassociated with each REPLServer. For example:\n\n

\n
// repl_test.js\nvar repl = require("repl"),\n    msg = "message";\n\nrepl.start().context.m = msg;
\n

Things in the context object appear as local within the REPL:\n\n

\n
mjr:~$ node repl_test.js\n> m\n'message'
\n

There are a few special REPL commands:\n\n

\n
    \n
  • .break - While inputting a multi-line expression, sometimes you get lost\nor just don't care about completing it. .break will start over.
  • \n
  • .clear - Resets the context object to an empty object and clears any\nmulti-line expression.
  • \n
  • .exit - Close the I/O stream, which will cause the REPL to exit.
  • \n
  • .help - Show this list of special commands.
  • \n
  • .save - Save the current REPL session to a file
    \n

    .save ./file/to/save.js

    \n
    \n
  • \n
  • .load - Load a file into the current REPL session.
    \n

    .load ./file/to/load.js

    \n
    \n
  • \n
\n

The following key combinations in the REPL have these special effects:\n\n

\n
    \n
  • <ctrl>C - Similar to the .break keyword. Terminates the current\ncommand. Press twice on a blank line to forcibly exit.
  • \n
  • <ctrl>D - Similar to the .exit keyword.
  • \n
\n" + } + ], + "type": "module", + "displayName": "REPL" + }, + { + "textRaw": "Executing JavaScript", + "name": "vm", + "stability": 2, + "stabilityText": "Unstable. See Caveats, below.", + "desc": "

You can access this module with:\n\n

\n
var vm = require('vm');
\n

JavaScript code can be compiled and run immediately or compiled, saved, and run later.\n\n

\n", + "modules": [ + { + "textRaw": "Caveats", + "name": "caveats", + "desc": "

The vm module has many known issues and edge cases. If you run into\nissues or unexpected behavior, please consult\nthe open issues on GitHub.\nSome of the biggest problems are described below.\n\n

\n", + "modules": [ + { + "textRaw": "Sandboxes", + "name": "sandboxes", + "desc": "

The sandbox argument to vm.runInNewContext and vm.createContext,\nalong with the initSandbox argument to vm.createContext, do not\nbehave as one might normally expect and their behavior varies\nbetween different versions of Node.\n\n

\n

The key issue to be aware of is that V8 provides no way to directly\ncontrol the global object used within a context. As a result, while\nproperties of your sandbox object will be available in the context,\nany properties from the prototypes of the sandbox may not be\navailable. Furthermore, the this expression within the global scope\nof the context evaluates to the empty object ({}) instead of to\nyour sandbox.\n\n

\n

Your sandbox's properties are also not shared directly with the script.\nInstead, the properties of the sandbox are copied into the context at\nthe beginning of execution, and then after execution, the properties\nare copied back out in an attempt to propagate any changes.\n\n

\n", + "type": "module", + "displayName": "Sandboxes" + }, + { + "textRaw": "Globals", + "name": "globals", + "desc": "

Properties of the global object, like Array and String, have\ndifferent values inside of a context. This means that common\nexpressions like [] instanceof Array or\nObject.getPrototypeOf([]) === Array.prototype may not produce\nexpected results when used inside of scripts evaluated via the vm module.\n\n

\n

Some of these problems have known workarounds listed in the issues for\nvm on GitHub. for example, Array.isArray works around\nthe example problem with Array.\n\n

\n", + "type": "module", + "displayName": "Globals" + } + ], + "type": "module", + "displayName": "Caveats" + } + ], + "methods": [ + { + "textRaw": "vm.runInThisContext(code, [filename])", + "type": "method", + "name": "runInThisContext", + "desc": "

vm.runInThisContext() compiles code, runs it and returns the result. Running\ncode does not have access to local scope. filename is optional, it's used only\nin stack traces.\n\n

\n

Example of using vm.runInThisContext and eval to run the same code:\n\n

\n
var localVar = 123,\n    usingscript, evaled,\n    vm = require('vm');\n\nusingscript = vm.runInThisContext('localVar = 1;',\n  'myfile.vm');\nconsole.log('localVar: ' + localVar + ', usingscript: ' +\n  usingscript);\nevaled = eval('localVar = 1;');\nconsole.log('localVar: ' + localVar + ', evaled: ' +\n  evaled);\n\n// localVar: 123, usingscript: 1\n// localVar: 1, evaled: 1
\n

vm.runInThisContext does not have access to the local scope, so localVar is unchanged.\neval does have access to the local scope, so localVar is changed.\n\n

\n

In case of syntax error in code, vm.runInThisContext emits the syntax error to stderr\nand throws an exception.\n\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "code" + }, + { + "name": "filename", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "vm.runInNewContext(code, [sandbox], [filename])", + "type": "method", + "name": "runInNewContext", + "desc": "

vm.runInNewContext compiles code, then runs it in sandbox and returns the\nresult. Running code does not have access to local scope. The object sandbox\nwill be used as the global object for code.\nsandbox and filename are optional, filename is only used in stack traces.\n\n

\n

Example: compile and execute code that increments a global variable and sets a new one.\nThese globals are contained in the sandbox.\n\n

\n
var util = require('util'),\n    vm = require('vm'),\n    sandbox = {\n      animal: 'cat',\n      count: 2\n    };\n\nvm.runInNewContext('count += 1; name = "kitty"', sandbox, 'myfile.vm');\nconsole.log(util.inspect(sandbox));\n\n// { animal: 'cat', count: 3, name: 'kitty' }
\n

Note that running untrusted code is a tricky business requiring great care. To prevent accidental\nglobal variable leakage, vm.runInNewContext is quite useful, but safely running untrusted code\nrequires a separate process.\n\n

\n

In case of syntax error in code, vm.runInNewContext emits the syntax error to stderr\nand throws an exception.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "code" + }, + { + "name": "sandbox", + "optional": true + }, + { + "name": "filename", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "vm.runInContext(code, context, [filename])", + "type": "method", + "name": "runInContext", + "desc": "

vm.runInContext compiles code, then runs it in context and returns the\nresult. A (V8) context comprises a global object, together with a set of\nbuilt-in objects and functions. Running code does not have access to local scope\nand the global object held within context will be used as the global object\nfor code.\nfilename is optional, it's used only in stack traces.\n\n

\n

Example: compile and execute code in a existing context.\n\n

\n
var util = require('util'),\n    vm = require('vm'),\n    initSandbox = {\n      animal: 'cat',\n      count: 2\n    },\n    context = vm.createContext(initSandbox);\n\nvm.runInContext('count += 1; name = "CATT"', context, 'myfile.vm');\nconsole.log(util.inspect(context));\n\n// { animal: 'cat', count: 3, name: 'CATT' }
\n

Note that createContext will perform a shallow clone of the supplied sandbox object in order to\ninitialize the global object of the freshly constructed context.\n\n

\n

Note that running untrusted code is a tricky business requiring great care. To prevent accidental\nglobal variable leakage, vm.runInContext is quite useful, but safely running untrusted code\nrequires a separate process.\n\n

\n

In case of syntax error in code, vm.runInContext emits the syntax error to stderr\nand throws an exception.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "code" + }, + { + "name": "context" + }, + { + "name": "filename", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "vm.createContext([initSandbox])", + "type": "method", + "name": "createContext", + "desc": "

vm.createContext creates a new context which is suitable for use as the 2nd argument of a subsequent\ncall to vm.runInContext. A (V8) context comprises a global object together with a set of\nbuild-in objects and functions. The optional argument initSandbox will be shallow-copied\nto seed the initial contents of the global object used by the context.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "initSandbox", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "vm.createScript(code, [filename])", + "type": "method", + "name": "createScript", + "desc": "

createScript compiles code but does not run it. Instead, it returns a\nvm.Script object representing this compiled code. This script can be run\nlater many times using methods below. The returned script is not bound to any\nglobal object. It is bound before each run, just for that run. filename is\noptional, it's only used in stack traces.\n\n

\n

In case of syntax error in code, createScript prints the syntax error to stderr\nand throws an exception.\n\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "code" + }, + { + "name": "filename", + "optional": true + } + ] + } + ] + } + ], + "classes": [ + { + "textRaw": "Class: Script", + "type": "class", + "name": "Script", + "desc": "

A class for running scripts. Returned by vm.createScript.\n\n

\n", + "methods": [ + { + "textRaw": "script.runInThisContext()", + "type": "method", + "name": "runInThisContext", + "desc": "

Similar to vm.runInThisContext but a method of a precompiled Script object.\nscript.runInThisContext runs the code of script and returns the result.\nRunning code does not have access to local scope, but does have access to the global object\n(v8: in actual context).\n\n

\n

Example of using script.runInThisContext to compile code once and run it multiple times:\n\n

\n
var vm = require('vm');\n\nglobalVar = 0;\n\nvar script = vm.createScript('globalVar += 1', 'myfile.vm');\n\nfor (var i = 0; i < 1000 ; i += 1) {\n  script.runInThisContext();\n}\n\nconsole.log(globalVar);\n\n// 1000
\n", + "signatures": [ + { + "params": [] + } + ] + }, + { + "textRaw": "script.runInNewContext([sandbox])", + "type": "method", + "name": "runInNewContext", + "desc": "

Similar to vm.runInNewContext a method of a precompiled Script object.\nscript.runInNewContext runs the code of script with sandbox as the global object and returns the result.\nRunning code does not have access to local scope. sandbox is optional.\n\n

\n

Example: compile code that increments a global variable and sets one, then execute this code multiple times.\nThese globals are contained in the sandbox.\n\n

\n
var util = require('util'),\n    vm = require('vm'),\n    sandbox = {\n      animal: 'cat',\n      count: 2\n    };\n\nvar script = vm.createScript('count += 1; name = "kitty"', 'myfile.vm');\n\nfor (var i = 0; i < 10 ; i += 1) {\n  script.runInNewContext(sandbox);\n}\n\nconsole.log(util.inspect(sandbox));\n\n// { animal: 'cat', count: 12, name: 'kitty' }
\n

Note that running untrusted code is a tricky business requiring great care. To prevent accidental\nglobal variable leakage, script.runInNewContext is quite useful, but safely running untrusted code\nrequires a separate process.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "sandbox", + "optional": true + } + ] + } + ] + } + ] + } + ], + "type": "module", + "displayName": "vm" + }, + { + "textRaw": "Child Process", + "name": "child_process", + "stability": 3, + "stabilityText": "Stable", + "desc": "

Node provides a tri-directional popen(3) facility through the\nchild_process module.\n\n

\n

It is possible to stream data through a child's stdin, stdout, and\nstderr in a fully non-blocking way.\n\n

\n

To create a child process use require('child_process').spawn() or\nrequire('child_process').fork(). The semantics of each are slightly\ndifferent, and explained below.\n\n

\n", + "classes": [ + { + "textRaw": "Class: ChildProcess", + "type": "class", + "name": "ChildProcess", + "desc": "

ChildProcess is an [EventEmitter][].\n\n

\n

Child processes always have three streams associated with them. child.stdin,\nchild.stdout, and child.stderr. These may be shared with the stdio\nstreams of the parent process, or they may be separate stream objects\nwhich can be piped to and from.\n\n

\n

The ChildProcess class is not intended to be used directly. Use the\nspawn() or fork() methods to create a Child Process instance.\n\n

\n", + "events": [ + { + "textRaw": "Event: 'exit'", + "type": "event", + "name": "exit", + "params": [], + "desc": "

This event is emitted after the child process ends. If the process terminated\nnormally, code is the final exit code of the process, otherwise null. If\nthe process terminated due to receipt of a signal, signal is the string name\nof the signal, otherwise null.\n\n

\n

Note that the child process stdio streams might still be open.\n\n

\n

See waitpid(2).\n\n

\n" + }, + { + "textRaw": "Event: 'close'", + "type": "event", + "name": "close", + "desc": "

This event is emitted when the stdio streams of a child process have all\nterminated. This is distinct from 'exit', since multiple processes\nmight share the same stdio streams.\n\n

\n", + "params": [] + }, + { + "textRaw": "Event: 'disconnect'", + "type": "event", + "name": "disconnect", + "desc": "

This event is emitted after using the .disconnect() method in the parent or\nin the child. After disconnecting it is no longer possible to send messages.\nAn alternative way to check if you can send messages is to see if the\nchild.connected property is true.\n\n

\n", + "params": [] + }, + { + "textRaw": "Event: 'message'", + "type": "event", + "name": "message", + "params": [], + "desc": "

Messages send by .send(message, [sendHandle]) are obtained using the\nmessage event.\n\n

\n" + } + ], + "properties": [ + { + "textRaw": "`stdin` {Stream object} ", + "name": "stdin", + "desc": "

A Writable Stream that represents the child process's stdin.\nClosing this stream via end() often causes the child process to terminate.\n\n

\n

If the child stdio streams are shared with the parent, then this will\nnot be set.\n\n

\n" + }, + { + "textRaw": "`stdout` {Stream object} ", + "name": "stdout", + "desc": "

A Readable Stream that represents the child process's stdout.\n\n

\n

If the child stdio streams are shared with the parent, then this will\nnot be set.\n\n

\n" + }, + { + "textRaw": "`stderr` {Stream object} ", + "name": "stderr", + "desc": "

A Readable Stream that represents the child process's stderr.\n\n

\n

If the child stdio streams are shared with the parent, then this will\nnot be set.\n\n

\n" + }, + { + "textRaw": "`pid` {Integer} ", + "name": "pid", + "desc": "

The PID of the child process.\n\n

\n

Example:\n\n

\n
var spawn = require('child_process').spawn,\n    grep  = spawn('grep', ['ssh']);\n\nconsole.log('Spawned child pid: ' + grep.pid);\ngrep.stdin.end();
\n" + } + ], + "methods": [ + { + "textRaw": "child.kill([signal])", + "type": "method", + "name": "kill", + "signatures": [ + { + "params": [ + { + "textRaw": "`signal` {String} ", + "name": "signal", + "type": "String", + "optional": true + } + ] + }, + { + "params": [ + { + "name": "signal", + "optional": true + } + ] + } + ], + "desc": "

Send a signal to the child process. If no argument is given, the process will\nbe sent 'SIGTERM'. See signal(7) for a list of available signals.\n\n

\n
var spawn = require('child_process').spawn,\n    grep  = spawn('grep', ['ssh']);\n\ngrep.on('exit', function (code, signal) {\n  console.log('child process terminated due to receipt of signal '+signal);\n});\n\n// send SIGHUP to process\ngrep.kill('SIGHUP');
\n

Note that while the function is called kill, the signal delivered to the child\nprocess may not actually kill it. kill really just sends a signal to a process.\n\n

\n

See kill(2)\n\n

\n" + }, + { + "textRaw": "child.send(message, [sendHandle])", + "type": "method", + "name": "send", + "signatures": [ + { + "params": [ + { + "textRaw": "`message` {Object} ", + "name": "message", + "type": "Object" + }, + { + "textRaw": "`sendHandle` {Handle object} ", + "name": "sendHandle", + "type": "Handle object", + "optional": true + } + ] + }, + { + "params": [ + { + "name": "message" + }, + { + "name": "sendHandle", + "optional": true + } + ] + } + ], + "desc": "

When using child_process.fork() you can write to the child using\nchild.send(message, [sendHandle]) and messages are received by\na 'message' event on the child.\n\n

\n

For example:\n\n

\n
var cp = require('child_process');\n\nvar n = cp.fork(__dirname + '/sub.js');\n\nn.on('message', function(m) {\n  console.log('PARENT got message:', m);\n});\n\nn.send({ hello: 'world' });
\n

And then the child script, 'sub.js' might look like this:\n\n

\n
process.on('message', function(m) {\n  console.log('CHILD got message:', m);\n});\n\nprocess.send({ foo: 'bar' });
\n

In the child the process object will have a send() method, and process\nwill emit objects each time it receives a message on its channel.\n\n

\n

There is a special case when sending a {cmd: 'NODE_foo'} message. All messages\ncontaining a NODE_ prefix in its cmd property will not be emitted in\nthe message event, since they are internal messages used by node core.\nMessages containing the prefix are emitted in the internalMessage event, you\nshould by all means avoid using this feature, it is subject to change without notice.\n\n

\n

The sendHandle option to child.send() is for sending a TCP server or\nsocket object to another process. The child will receive the object as its\nsecond argument to the message event.\n\n

\n

send server object\n\n

\n

Here is an example of sending a server:\n\n

\n
var child = require('child_process').fork('child.js');\n\n// Open up the server object and send the handle.\nvar server = require('net').createServer();\nserver.on('connection', function (socket) {\n  socket.end('handled by parent');\n});\nserver.listen(1337, function() {\n  child.send('server', server);\n});
\n

And the child would the receive the server object as:\n\n

\n
process.on('message', function(m, server) {\n  if (m === 'server') {\n    server.on('connection', function (socket) {\n      socket.end('handled by child');\n    });\n  }\n});
\n

Note that the server is now shared between the parent and child, this means\nthat some connections will be handled by the parent and some by the child.\n\n

\n

send socket object\n\n

\n

Here is an example of sending a socket. It will spawn two children and handle\nconnections with the remote address 74.125.127.100 as VIP by sending the\nsocket to a "special" child process. Other sockets will go to a "normal" process.\n\n

\n
var normal = require('child_process').fork('child.js', ['normal']);\nvar special = require('child_process').fork('child.js', ['special']);\n\n// Open up the server and send sockets to child\nvar server = require('net').createServer();\nserver.on('connection', function (socket) {\n\n  // if this is a VIP\n  if (socket.remoteAddress === '74.125.127.100') {\n    special.send('socket', socket);\n    return;\n  }\n  // just the usual dudes\n  normal.send('socket', socket);\n});\nserver.listen(1337);
\n

The child.js could look like this:\n\n

\n
process.on('message', function(m, socket) {\n  if (m === 'socket') {\n    socket.end('You were handled as a ' + process.argv[2] + ' person');\n  }\n});
\n

Note that once a single socket has been sent to a child the parent can no\nlonger keep track of when the socket is destroyed. To indicate this condition\nthe .connections property becomes null.\nIt is also recommended not to use .maxConnections in this condition.\n\n

\n" + }, + { + "textRaw": "child.disconnect()", + "type": "method", + "name": "disconnect", + "desc": "

To close the IPC connection between parent and child use the\nchild.disconnect() method. This allows the child to exit gracefully since\nthere is no IPC channel keeping it alive. When calling this method the\ndisconnect event will be emitted in both parent and child, and the\nconnected flag will be set to false. Please note that you can also call\nprocess.disconnect() in the child process.\n\n

\n", + "signatures": [ + { + "params": [] + } + ] + } + ] + } + ], + "methods": [ + { + "textRaw": "child_process.spawn(command, [args], [options])", + "type": "method", + "name": "spawn", + "signatures": [ + { + "return": { + "textRaw": "return: {ChildProcess object} ", + "name": "return", + "type": "ChildProcess object" + }, + "params": [ + { + "textRaw": "`command` {String} The command to run ", + "name": "command", + "type": "String", + "desc": "The command to run" + }, + { + "textRaw": "`args` {Array} List of string arguments ", + "name": "args", + "type": "Array", + "desc": "List of string arguments", + "optional": true + }, + { + "textRaw": "`options` {Object} ", + "options": [ + { + "textRaw": "`cwd` {String} Current working directory of the child process ", + "name": "cwd", + "type": "String", + "desc": "Current working directory of the child process" + }, + { + "textRaw": "`stdio` {Array|String} Child's stdio configuration. (See below) ", + "name": "stdio", + "type": "Array|String", + "desc": "Child's stdio configuration. (See below)" + }, + { + "textRaw": "`customFds` {Array} **Deprecated** File descriptors for the child to use for stdio. (See below) ", + "name": "customFds", + "type": "Array", + "desc": "**Deprecated** File descriptors for the child to use for stdio. (See below)" + }, + { + "textRaw": "`env` {Object} Environment key-value pairs ", + "name": "env", + "type": "Object", + "desc": "Environment key-value pairs" + }, + { + "textRaw": "`detached` {Boolean} The child will be a process group leader. (See below) ", + "name": "detached", + "type": "Boolean", + "desc": "The child will be a process group leader. (See below)" + }, + { + "textRaw": "`uid` {Number} Sets the user identity of the process. (See setuid(2).) ", + "name": "uid", + "type": "Number", + "desc": "Sets the user identity of the process. (See setuid(2).)" + }, + { + "textRaw": "`gid` {Number} Sets the group identity of the process. (See setgid(2).) ", + "name": "gid", + "type": "Number", + "desc": "Sets the group identity of the process. (See setgid(2).)" + } + ], + "name": "options", + "type": "Object", + "optional": true + } + ] + }, + { + "params": [ + { + "name": "command" + }, + { + "name": "args", + "optional": true + }, + { + "name": "options", + "optional": true + } + ] + } + ], + "desc": "

Launches a new process with the given command, with command line arguments in args.\nIf omitted, args defaults to an empty Array.\n\n

\n

The third argument is used to specify additional options, which defaults to:\n\n

\n
{ cwd: undefined,\n  env: process.env\n}
\n

cwd allows you to specify the working directory from which the process is spawned.\nUse env to specify environment variables that will be visible to the new process.\n\n

\n

Example of running ls -lh /usr, capturing stdout, stderr, and the exit code:\n\n

\n
var spawn = require('child_process').spawn,\n    ls    = spawn('ls', ['-lh', '/usr']);\n\nls.stdout.on('data', function (data) {\n  console.log('stdout: ' + data);\n});\n\nls.stderr.on('data', function (data) {\n  console.log('stderr: ' + data);\n});\n\nls.on('exit', function (code) {\n  console.log('child process exited with code ' + code);\n});
\n

Example: A very elaborate way to run 'ps ax | grep ssh'\n\n

\n
var spawn = require('child_process').spawn,\n    ps    = spawn('ps', ['ax']),\n    grep  = spawn('grep', ['ssh']);\n\nps.stdout.on('data', function (data) {\n  grep.stdin.write(data);\n});\n\nps.stderr.on('data', function (data) {\n  console.log('ps stderr: ' + data);\n});\n\nps.on('exit', function (code) {\n  if (code !== 0) {\n    console.log('ps process exited with code ' + code);\n  }\n  grep.stdin.end();\n});\n\ngrep.stdout.on('data', function (data) {\n  console.log('' + data);\n});\n\ngrep.stderr.on('data', function (data) {\n  console.log('grep stderr: ' + data);\n});\n\ngrep.on('exit', function (code) {\n  if (code !== 0) {\n    console.log('grep process exited with code ' + code);\n  }\n});
\n

Example of checking for failed exec:\n\n

\n
var spawn = require('child_process').spawn,\n    child = spawn('bad_command');\n\nchild.stderr.setEncoding('utf8');\nchild.stderr.on('data', function (data) {\n  if (/^execvp\\(\\)/.test(data)) {\n    console.log('Failed to start child process.');\n  }\n});
\n

Note that if spawn receives an empty options object, it will result in\nspawning the process with an empty environment rather than using\nprocess.env. This due to backwards compatibility issues with a deprecated\nAPI.\n\n

\n

The 'stdio' option to child_process.spawn() is an array where each\nindex corresponds to a fd in the child. The value is one of the following:\n\n

\n
    \n
  1. 'pipe' - Create a pipe between the child process and the parent process.\nThe parent end of the pipe is exposed to the parent as a property on the\nchild_process object as ChildProcess.stdio[fd]. Pipes created for\nfds 0 - 2 are also available as ChildProcess.stdin, ChildProcess.stdout\nand ChildProcess.stderr, respectively.
  2. \n
  3. 'ipc' - Create an IPC channel for passing messages/file descriptors\nbetween parent and child. A ChildProcess may have at most one IPC stdio\nfile descriptor. Setting this option enables the ChildProcess.send() method.\nIf the child writes JSON messages to this file descriptor, then this will\ntrigger ChildProcess.on('message'). If the child is a Node.js program, then\nthe presence of an IPC channel will enable process.send() and\nprocess.on('message').
  4. \n
  5. 'ignore' - Do not set this file descriptor in the child. Note that Node\nwill always open fd 0 - 2 for the processes it spawns. When any of these is\nignored node will open /dev/null and attach it to the child's fd.
  6. \n
  7. Stream object - Share a readable or writable stream that refers to a tty,\nfile, socket, or a pipe with the child process. The stream's underlying\nfile descriptor is duplicated in the child process to the fd that \ncorresponds to the index in the stdio array.
  8. \n
  9. Positive integer - The integer value is interpreted as a file descriptor \nthat is is currently open in the parent process. It is shared with the child\nprocess, similar to how Stream objects can be shared.
  10. \n
  11. null, undefined - Use default value. For stdio fds 0, 1 and 2 (in other\nwords, stdin, stdout, and stderr) a pipe is created. For fd 3 and up, the\ndefault is 'ignore'.
  12. \n
\n

As a shorthand, the stdio argument may also be one of the following\nstrings, rather than an array:\n\n

\n
    \n
  • ignore - ['ignore', 'ignore', 'ignore']
  • \n
  • pipe - ['pipe', 'pipe', 'pipe']
  • \n
  • inherit - [process.stdin, process.stdout, process.stderr] or [0,1,2]
  • \n
\n

Example:\n\n

\n
var spawn = require('child_process').spawn;\n\n// Child will use parent's stdios\nspawn('prg', [], { stdio: 'inherit' });\n\n// Spawn child sharing only stderr\nspawn('prg', [], { stdio: ['pipe', 'pipe', process.stderr] });\n\n// Open an extra fd=4, to interact with programs present a\n// startd-style interface.\nspawn('prg', [], { stdio: ['pipe', null, null, null, 'pipe'] });
\n

If the detached option is set, the child process will be made the leader of a\nnew process group. This makes it possible for the child to continue running \nafter the parent exits.\n\n

\n

By default, the parent will wait for the detached child to exit. To prevent\nthe parent from waiting for a given child, use the child.unref() method,\nand the parent's event loop will not include the child in its reference count.\n\n

\n

Example of detaching a long-running process and redirecting its output to a\nfile:\n\n

\n
 var fs = require('fs'),\n     spawn = require('child_process').spawn,\n     out = fs.openSync('./out.log', 'a'),\n     err = fs.openSync('./out.log', 'a');\n\n var child = spawn('prg', [], {\n   detached: true,\n   stdio: [ 'ignore', out, err ]\n });\n\n child.unref();
\n

When using the detached option to start a long-running process, the process\nwill not stay running in the background unless it is provided with a stdio\nconfiguration that is not connected to the parent. If the parent's stdio is\ninherited, the child will remain attached to the controlling terminal.\n\n

\n

There is a deprecated option called customFds which allows one to specify\nspecific file descriptors for the stdio of the child process. This API was\nnot portable to all platforms and therefore removed.\nWith customFds it was possible to hook up the new process' [stdin, stdout,\nstderr] to existing streams; -1 meant that a new stream should be created.\nUse at your own risk.\n\n

\n

There are several internal options. In particular stdinStream,\nstdoutStream, stderrStream. They are for INTERNAL USE ONLY. As with all\nundocumented APIs in Node, they should not be used.\n\n

\n

See also: child_process.exec() and child_process.fork()\n\n

\n" + }, + { + "textRaw": "child_process.exec(command, [options], callback)", + "type": "method", + "name": "exec", + "signatures": [ + { + "return": { + "textRaw": "Return: ChildProcess object ", + "name": "return", + "desc": "ChildProcess object" + }, + "params": [ + { + "textRaw": "`command` {String} The command to run, with space-separated arguments ", + "name": "command", + "type": "String", + "desc": "The command to run, with space-separated arguments" + }, + { + "textRaw": "`options` {Object} ", + "options": [ + { + "textRaw": "`cwd` {String} Current working directory of the child process ", + "name": "cwd", + "type": "String", + "desc": "Current working directory of the child process" + }, + { + "textRaw": "`stdio` {Array|String} Child's stdio configuration. (See above) ", + "name": "stdio", + "type": "Array|String", + "desc": "Child's stdio configuration. (See above)" + }, + { + "textRaw": "`customFds` {Array} **Deprecated** File descriptors for the child to use for stdio. (See above) ", + "name": "customFds", + "type": "Array", + "desc": "**Deprecated** File descriptors for the child to use for stdio. (See above)" + }, + { + "textRaw": "`env` {Object} Environment key-value pairs ", + "name": "env", + "type": "Object", + "desc": "Environment key-value pairs" + }, + { + "textRaw": "`encoding` {String} (Default: 'utf8') ", + "name": "encoding", + "default": "utf8", + "type": "String" + }, + { + "textRaw": "`timeout` {Number} (Default: 0) ", + "name": "timeout", + "default": "0", + "type": "Number" + }, + { + "textRaw": "`maxBuffer` {Number} (Default: 200*1024) ", + "name": "maxBuffer", + "default": "200*1024", + "type": "Number" + }, + { + "textRaw": "`killSignal` {String} (Default: 'SIGTERM') ", + "name": "killSignal", + "default": "SIGTERM", + "type": "String" + } + ], + "name": "options", + "type": "Object", + "optional": true + }, + { + "textRaw": "`callback` {Function} called with the output when process terminates ", + "options": [ + { + "textRaw": "`error` {Error} ", + "name": "error", + "type": "Error" + }, + { + "textRaw": "`stdout` {Buffer} ", + "name": "stdout", + "type": "Buffer" + }, + { + "textRaw": "`stderr` {Buffer} ", + "name": "stderr", + "type": "Buffer" + } + ], + "name": "callback", + "type": "Function", + "desc": "called with the output when process terminates" + } + ] + }, + { + "params": [ + { + "name": "command" + }, + { + "name": "options", + "optional": true + }, + { + "name": "callback" + } + ] + } + ], + "desc": "

Runs a command in a shell and buffers the output.\n\n

\n
var exec = require('child_process').exec,\n    child;\n\nchild = exec('cat *.js bad_file | wc -l',\n  function (error, stdout, stderr) {\n    console.log('stdout: ' + stdout);\n    console.log('stderr: ' + stderr);\n    if (error !== null) {\n      console.log('exec error: ' + error);\n    }\n});
\n

The callback gets the arguments (error, stdout, stderr). On success, error\nwill be null. On error, error will be an instance of Error and err.code\nwill be the exit code of the child process, and err.signal will be set to the\nsignal that terminated the process.\n\n

\n

There is a second optional argument to specify several options. The\ndefault options are\n\n

\n
{ encoding: 'utf8',\n  timeout: 0,\n  maxBuffer: 200*1024,\n  killSignal: 'SIGTERM',\n  cwd: null,\n  env: null }
\n

If timeout is greater than 0, then it will kill the child process\nif it runs longer than timeout milliseconds. The child process is killed with\nkillSignal (default: 'SIGTERM'). maxBuffer specifies the largest\namount of data allowed on stdout or stderr - if this value is exceeded then\nthe child process is killed.\n\n\n

\n" + }, + { + "textRaw": "child_process.execFile(file, args, options, callback)", + "type": "method", + "name": "execFile", + "signatures": [ + { + "return": { + "textRaw": "Return: ChildProcess object ", + "name": "return", + "desc": "ChildProcess object" + }, + "params": [ + { + "textRaw": "`file` {String} The filename of the program to run ", + "name": "file", + "type": "String", + "desc": "The filename of the program to run" + }, + { + "textRaw": "`args` {Array} List of string arguments ", + "name": "args", + "type": "Array", + "desc": "List of string arguments" + }, + { + "textRaw": "`options` {Object} ", + "options": [ + { + "textRaw": "`cwd` {String} Current working directory of the child process ", + "name": "cwd", + "type": "String", + "desc": "Current working directory of the child process" + }, + { + "textRaw": "`stdio` {Array|String} Child's stdio configuration. (See above) ", + "name": "stdio", + "type": "Array|String", + "desc": "Child's stdio configuration. (See above)" + }, + { + "textRaw": "`customFds` {Array} **Deprecated** File descriptors for the child to use for stdio. (See above) ", + "name": "customFds", + "type": "Array", + "desc": "**Deprecated** File descriptors for the child to use for stdio. (See above)" + }, + { + "textRaw": "`env` {Object} Environment key-value pairs ", + "name": "env", + "type": "Object", + "desc": "Environment key-value pairs" + }, + { + "textRaw": "`encoding` {String} (Default: 'utf8') ", + "name": "encoding", + "default": "utf8", + "type": "String" + }, + { + "textRaw": "`timeout` {Number} (Default: 0) ", + "name": "timeout", + "default": "0", + "type": "Number" + }, + { + "textRaw": "`maxBuffer` {Number} (Default: 200\\*1024) ", + "name": "maxBuffer", + "default": "200\\*1024", + "type": "Number" + }, + { + "textRaw": "`killSignal` {String} (Default: 'SIGTERM') ", + "name": "killSignal", + "default": "SIGTERM", + "type": "String" + } + ], + "name": "options", + "type": "Object" + }, + { + "textRaw": "`callback` {Function} called with the output when process terminates ", + "options": [ + { + "textRaw": "`error` {Error} ", + "name": "error", + "type": "Error" + }, + { + "textRaw": "`stdout` {Buffer} ", + "name": "stdout", + "type": "Buffer" + }, + { + "textRaw": "`stderr` {Buffer} ", + "name": "stderr", + "type": "Buffer" + } + ], + "name": "callback", + "type": "Function", + "desc": "called with the output when process terminates" + } + ] + }, + { + "params": [ + { + "name": "file" + }, + { + "name": "args" + }, + { + "name": "options" + }, + { + "name": "callback" + } + ] + } + ], + "desc": "

This is similar to child_process.exec() except it does not execute a\nsubshell but rather the specified file directly. This makes it slightly\nleaner than child_process.exec. It has the same options.\n\n\n

\n" + }, + { + "textRaw": "child\\_process.fork(modulePath, [args], [options])", + "type": "method", + "name": "fork", + "signatures": [ + { + "return": { + "textRaw": "Return: ChildProcess object ", + "name": "return", + "desc": "ChildProcess object" + }, + "params": [ + { + "textRaw": "`modulePath` {String} The module to run in the child ", + "name": "modulePath", + "type": "String", + "desc": "The module to run in the child" + }, + { + "textRaw": "`args` {Array} List of string arguments ", + "name": "args", + "type": "Array", + "desc": "List of string arguments", + "optional": true + }, + { + "textRaw": "`options` {Object} ", + "options": [ + { + "textRaw": "`cwd` {String} Current working directory of the child process ", + "name": "cwd", + "type": "String", + "desc": "Current working directory of the child process" + }, + { + "textRaw": "`env` {Object} Environment key-value pairs ", + "name": "env", + "type": "Object", + "desc": "Environment key-value pairs" + }, + { + "textRaw": "`encoding` {String} (Default: 'utf8') ", + "name": "encoding", + "default": "utf8", + "type": "String" + } + ], + "name": "options", + "type": "Object", + "optional": true + } + ] + }, + { + "params": [ + { + "name": "modulePath" + }, + { + "name": "args", + "optional": true + }, + { + "name": "options", + "optional": true + } + ] + } + ], + "desc": "

This is a special case of the spawn() functionality for spawning Node\nprocesses. In addition to having all the methods in a normal ChildProcess\ninstance, the returned object has a communication channel built-in. See\nchild.send(message, [sendHandle]) for details.\n\n

\n

By default the spawned Node process will have the stdout, stderr associated\nwith the parent's. To change this behavior set the silent property in the\noptions object to true.\n\n

\n

The child process does not automatically exit once it's done, you need to call\nprocess.exit() explicitly. This limitation may be lifted in the future.\n\n

\n

These child Nodes are still whole new instances of V8. Assume at least 30ms\nstartup and 10mb memory for each new Node. That is, you cannot create many\nthousands of them.\n\n

\n" + } + ], + "type": "module", + "displayName": "Child Process" + }, + { + "textRaw": "Assert", + "name": "assert", + "stability": 5, + "stabilityText": "Locked", + "desc": "

This module is used for writing unit tests for your applications, you can\naccess it with require('assert').\n\n

\n", + "methods": [ + { + "textRaw": "assert.fail(actual, expected, message, operator)", + "type": "method", + "name": "fail", + "desc": "

Throws an exception that displays the values for actual and expected separated by the provided operator.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "actual" + }, + { + "name": "expected" + }, + { + "name": "message" + }, + { + "name": "operator" + } + ] + } + ] + }, + { + "textRaw": "assert(value, message), assert.ok(value, [message])", + "type": "method", + "name": "ok", + "desc": "

Tests if value is truthy, it is equivalent to assert.equal(true, !!value, message);\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "value" + }, + { + "name": "message)" + }, + { + "name": "assert.ok(value" + }, + { + "name": "message", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "assert.equal(actual, expected, [message])", + "type": "method", + "name": "equal", + "desc": "

Tests shallow, coercive equality with the equal comparison operator ( == ).\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "actual" + }, + { + "name": "expected" + }, + { + "name": "message", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "assert.notEqual(actual, expected, [message])", + "type": "method", + "name": "notEqual", + "desc": "

Tests shallow, coercive non-equality with the not equal comparison operator ( != ).\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "actual" + }, + { + "name": "expected" + }, + { + "name": "message", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "assert.deepEqual(actual, expected, [message])", + "type": "method", + "name": "deepEqual", + "desc": "

Tests for deep equality.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "actual" + }, + { + "name": "expected" + }, + { + "name": "message", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "assert.notDeepEqual(actual, expected, [message])", + "type": "method", + "name": "notDeepEqual", + "desc": "

Tests for any deep inequality.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "actual" + }, + { + "name": "expected" + }, + { + "name": "message", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "assert.strictEqual(actual, expected, [message])", + "type": "method", + "name": "strictEqual", + "desc": "

Tests strict equality, as determined by the strict equality operator ( === )\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "actual" + }, + { + "name": "expected" + }, + { + "name": "message", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "assert.notStrictEqual(actual, expected, [message])", + "type": "method", + "name": "notStrictEqual", + "desc": "

Tests strict non-equality, as determined by the strict not equal operator ( !== )\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "actual" + }, + { + "name": "expected" + }, + { + "name": "message", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "assert.throws(block, [error], [message])", + "type": "method", + "name": "throws", + "desc": "

Expects block to throw an error. error can be constructor, regexp or \nvalidation function.\n\n

\n

Validate instanceof using constructor:\n\n

\n
assert.throws(\n  function() {\n    throw new Error("Wrong value");\n  },\n  Error\n);
\n

Validate error message using RegExp:\n\n

\n
assert.throws(\n  function() {\n    throw new Error("Wrong value");\n  },\n  /value/\n);
\n

Custom error validation:\n\n

\n
assert.throws(\n  function() {\n    throw new Error("Wrong value");\n  },\n  function(err) {\n    if ( (err instanceof Error) && /value/.test(err) ) {\n      return true;\n    }\n  },\n  "unexpected error"\n);
\n", + "signatures": [ + { + "params": [ + { + "name": "block" + }, + { + "name": "error", + "optional": true + }, + { + "name": "message", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "assert.doesNotThrow(block, [error], [message])", + "type": "method", + "name": "doesNotThrow", + "desc": "

Expects block not to throw an error, see assert.throws for details.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "block" + }, + { + "name": "error", + "optional": true + }, + { + "name": "message", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "assert.ifError(value)", + "type": "method", + "name": "ifError", + "desc": "

Tests if value is not a false value, throws if it is a true value. Useful when\ntesting the first argument, error in callbacks.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "value" + } + ] + } + ] + } + ], + "type": "module", + "displayName": "Assert" + }, + { + "textRaw": "TTY", + "name": "tty", + "stability": 2, + "stabilityText": "Unstable", + "desc": "

The tty module houses the tty.ReadStream and tty.WriteStream classes. In\nmost cases, you will not need to use this module directly.\n\n

\n

When node detects that it is being run inside a TTY context, then process.stdin\nwill be a tty.ReadStream instance and process.stdout will be\na tty.WriteStream instance. The preferred way to check if node is being run in\na TTY context is to check process.stdout.isTTY:\n\n

\n
$ node -p -e "Boolean(process.stdout.isTTY)"\ntrue\n$ node -p -e "Boolean(process.stdout.isTTY)" | cat\nfalse
\n", + "methods": [ + { + "textRaw": "tty.isatty(fd)", + "type": "method", + "name": "isatty", + "desc": "

Returns true or false depending on if the fd is associated with a\nterminal.\n\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "fd" + } + ] + } + ] + }, + { + "textRaw": "tty.setRawMode(mode)", + "type": "method", + "name": "setRawMode", + "desc": "

Deprecated. Use tty.ReadStream#setRawMode()\n(i.e. process.stdin.setRawMode()) instead.\n\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "mode" + } + ] + } + ] + } + ], + "classes": [ + { + "textRaw": "Class: ReadStream", + "type": "class", + "name": "ReadStream", + "desc": "

A net.Socket subclass that represents the readable portion of a tty. In normal\ncircumstances, process.stdin will be the only tty.ReadStream instance in any\nnode program (only when isatty(0) is true).\n\n

\n", + "properties": [ + { + "textRaw": "rs.isRaw", + "name": "isRaw", + "desc": "

A Boolean that is initialized to false. It represents the current "raw" state\nof the tty.ReadStream instance.\n\n

\n" + } + ], + "methods": [ + { + "textRaw": "rs.setRawMode(mode)", + "type": "method", + "name": "setRawMode", + "desc": "

mode should be true or false. This sets the properties of the\ntty.ReadStream to act either as a raw device or default. isRaw will be set\nto the resulting mode.\n\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "mode" + } + ] + } + ] + } + ] + } + ], + "modules": [ + { + "textRaw": "Class WriteStream", + "name": "class_writestream", + "desc": "

A net.Socket subclass that represents the writable portion of a tty. In normal\ncircumstances, process.stdout will be the only tty.WriteStream instance\never created (and only when isatty(1) is true).\n\n

\n", + "properties": [ + { + "textRaw": "ws.columns", + "name": "columns", + "desc": "

A Number that gives the number of columns the TTY currently has. This property\ngets updated on "resize" events.\n\n

\n" + }, + { + "textRaw": "ws.rows", + "name": "rows", + "desc": "

A Number that gives the number of rows the TTY currently has. This property\ngets updated on "resize" events.\n\n

\n" + } + ], + "events": [ + { + "textRaw": "Event: 'resize'", + "type": "event", + "name": "resize", + "desc": "

function () {}\n\n

\n

Emitted by refreshSize() when either of the columns or rows properties\nhas changed.\n\n

\n
process.stdout.on('resize', function() {\n  console.log('screen size has changed!');\n  console.log(process.stdout.columns + 'x' + process.stdout.rows);\n});
\n", + "params": [] + } + ], + "type": "module", + "displayName": "Class WriteStream" + } + ], + "type": "module", + "displayName": "TTY" + }, + { + "textRaw": "Zlib", + "name": "zlib", + "stability": 3, + "stabilityText": "Stable", + "desc": "

You can access this module with:\n\n

\n
var zlib = require('zlib');
\n

This provides bindings to Gzip/Gunzip, Deflate/Inflate, and\nDeflateRaw/InflateRaw classes. Each class takes the same options, and\nis a readable/writable Stream.\n\n

\n

Examples

\n

Compressing or decompressing a file can be done by piping an\nfs.ReadStream into a zlib stream, then into an fs.WriteStream.\n\n

\n
var gzip = zlib.createGzip();\nvar fs = require('fs');\nvar inp = fs.createReadStream('input.txt');\nvar out = fs.createWriteStream('input.txt.gz');\n\ninp.pipe(gzip).pipe(out);
\n

Compressing or decompressing data in one step can be done by using\nthe convenience methods.\n\n

\n
var input = '.................................';\nzlib.deflate(input, function(err, buffer) {\n  if (!err) {\n    console.log(buffer.toString('base64'));\n  }\n});\n\nvar buffer = new Buffer('eJzT0yMAAGTvBe8=', 'base64');\nzlib.unzip(buffer, function(err, buffer) {\n  if (!err) {\n    console.log(buffer.toString());\n  }\n});
\n

To use this module in an HTTP client or server, use the\naccept-encoding\non requests, and the\ncontent-encoding\nheader on responses.\n\n

\n

Note: these examples are drastically simplified to show\nthe basic concept. Zlib encoding can be expensive, and the results\nought to be cached. See Memory Usage Tuning\nbelow for more information on the speed/memory/compression\ntradeoffs involved in zlib usage.\n\n

\n
// client request example\nvar zlib = require('zlib');\nvar http = require('http');\nvar fs = require('fs');\nvar request = http.get({ host: 'izs.me',\n                         path: '/',\n                         port: 80,\n                         headers: { 'accept-encoding': 'gzip,deflate' } });\nrequest.on('response', function(response) {\n  var output = fs.createWriteStream('izs.me_index.html');\n\n  switch (response.headers['content-encoding']) {\n    // or, just use zlib.createUnzip() to handle both cases\n    case 'gzip':\n      response.pipe(zlib.createGunzip()).pipe(output);\n      break;\n    case 'deflate':\n      response.pipe(zlib.createInflate()).pipe(output);\n      break;\n    default:\n      response.pipe(output);\n      break;\n  }\n});\n\n// server example\n// Running a gzip operation on every request is quite expensive.\n// It would be much more efficient to cache the compressed buffer.\nvar zlib = require('zlib');\nvar http = require('http');\nvar fs = require('fs');\nhttp.createServer(function(request, response) {\n  var raw = fs.createReadStream('index.html');\n  var acceptEncoding = request.headers['accept-encoding'];\n  if (!acceptEncoding) {\n    acceptEncoding = '';\n  }\n\n  // Note: this is not a conformant accept-encoding parser.\n  // See http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.3\n  if (acceptEncoding.match(/\\bdeflate\\b/)) {\n    response.writeHead(200, { 'content-encoding': 'deflate' });\n    raw.pipe(zlib.createDeflate()).pipe(response);\n  } else if (acceptEncoding.match(/\\bgzip\\b/)) {\n    response.writeHead(200, { 'content-encoding': 'gzip' });\n    raw.pipe(zlib.createGzip()).pipe(response);\n  } else {\n    response.writeHead(200, {});\n    raw.pipe(response);\n  }\n}).listen(1337);
\n", + "methods": [ + { + "textRaw": "zlib.createGzip([options])", + "type": "method", + "name": "createGzip", + "desc": "

Returns a new Gzip object with an\noptions.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "options", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "zlib.createGunzip([options])", + "type": "method", + "name": "createGunzip", + "desc": "

Returns a new Gunzip object with an\noptions.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "options", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "zlib.createDeflate([options])", + "type": "method", + "name": "createDeflate", + "desc": "

Returns a new Deflate object with an\noptions.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "options", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "zlib.createInflate([options])", + "type": "method", + "name": "createInflate", + "desc": "

Returns a new Inflate object with an\noptions.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "options", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "zlib.createDeflateRaw([options])", + "type": "method", + "name": "createDeflateRaw", + "desc": "

Returns a new DeflateRaw object with an\noptions.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "options", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "zlib.createInflateRaw([options])", + "type": "method", + "name": "createInflateRaw", + "desc": "

Returns a new InflateRaw object with an\noptions.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "options", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "zlib.createUnzip([options])", + "type": "method", + "name": "createUnzip", + "desc": "

Returns a new Unzip object with an\noptions.\n\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "options", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "zlib.deflate(buf, callback)", + "type": "method", + "name": "deflate", + "desc": "

Compress a string with Deflate.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "buf" + }, + { + "name": "callback" + } + ] + } + ] + }, + { + "textRaw": "zlib.deflateRaw(buf, callback)", + "type": "method", + "name": "deflateRaw", + "desc": "

Compress a string with DeflateRaw.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "buf" + }, + { + "name": "callback" + } + ] + } + ] + }, + { + "textRaw": "zlib.gzip(buf, callback)", + "type": "method", + "name": "gzip", + "desc": "

Compress a string with Gzip.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "buf" + }, + { + "name": "callback" + } + ] + } + ] + }, + { + "textRaw": "zlib.gunzip(buf, callback)", + "type": "method", + "name": "gunzip", + "desc": "

Decompress a raw Buffer with Gunzip.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "buf" + }, + { + "name": "callback" + } + ] + } + ] + }, + { + "textRaw": "zlib.inflate(buf, callback)", + "type": "method", + "name": "inflate", + "desc": "

Decompress a raw Buffer with Inflate.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "buf" + }, + { + "name": "callback" + } + ] + } + ] + }, + { + "textRaw": "zlib.inflateRaw(buf, callback)", + "type": "method", + "name": "inflateRaw", + "desc": "

Decompress a raw Buffer with InflateRaw.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "buf" + }, + { + "name": "callback" + } + ] + } + ] + }, + { + "textRaw": "zlib.unzip(buf, callback)", + "type": "method", + "name": "unzip", + "desc": "

Decompress a raw Buffer with Unzip.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "buf" + }, + { + "name": "callback" + } + ] + } + ] + } + ], + "classes": [ + { + "textRaw": "Class: zlib.Gzip", + "type": "class", + "name": "zlib.Gzip", + "desc": "

Compress data using gzip.\n\n

\n" + }, + { + "textRaw": "Class: zlib.Gunzip", + "type": "class", + "name": "zlib.Gunzip", + "desc": "

Decompress a gzip stream.\n\n

\n" + }, + { + "textRaw": "Class: zlib.Deflate", + "type": "class", + "name": "zlib.Deflate", + "desc": "

Compress data using deflate.\n\n

\n" + }, + { + "textRaw": "Class: zlib.Inflate", + "type": "class", + "name": "zlib.Inflate", + "desc": "

Decompress a deflate stream.\n\n

\n" + }, + { + "textRaw": "Class: zlib.DeflateRaw", + "type": "class", + "name": "zlib.DeflateRaw", + "desc": "

Compress data using deflate, and do not append a zlib header.\n\n

\n" + }, + { + "textRaw": "Class: zlib.InflateRaw", + "type": "class", + "name": "zlib.InflateRaw", + "desc": "

Decompress a raw deflate stream.\n\n

\n" + }, + { + "textRaw": "Class: zlib.Unzip", + "type": "class", + "name": "zlib.Unzip", + "desc": "

Decompress either a Gzip- or Deflate-compressed stream by auto-detecting\nthe header.\n\n

\n" + } + ], + "miscs": [ + { + "textRaw": "Convenience Methods", + "name": "Convenience Methods", + "type": "misc", + "desc": "

All of these take a string or buffer as the first argument, and call the\nsupplied callback with callback(error, result). The\ncompression/decompression engine is created using the default settings\nin all convenience methods. To supply different options, use the\nzlib classes directly.\n\n

\n" + }, + { + "textRaw": "Options", + "name": "Options", + "type": "misc", + "desc": "

Each class takes an options object. All options are optional. (The\nconvenience methods use the default settings for all options.)\n\n

\n

Note that some options are only\nrelevant when compressing, and are ignored by the decompression classes.\n\n

\n
    \n
  • chunkSize (default: 16*1024)
  • \n
  • windowBits
  • \n
  • level (compression only)
  • \n
  • memLevel (compression only)
  • \n
  • strategy (compression only)
  • \n
  • dictionary (deflate/inflate only, empty dictionary by default)
  • \n
\n

See the description of deflateInit2 and inflateInit2\nat http://zlib.net/manual.html#Advanced for more information on these.\n\n

\n" + }, + { + "textRaw": "Memory Usage Tuning", + "name": "Memory Usage Tuning", + "type": "misc", + "desc": "

From zlib/zconf.h, modified to node's usage:\n\n

\n

The memory requirements for deflate are (in bytes):\n\n

\n
(1 << (windowBits+2)) +  (1 << (memLevel+9))
\n

that is: 128K for windowBits=15 + 128K for memLevel = 8\n(default values) plus a few kilobytes for small objects.\n\n

\n

For example, if you want to reduce\nthe default memory requirements from 256K to 128K, set the options to:\n\n

\n
{ windowBits: 14, memLevel: 7 }
\n

Of course this will generally degrade compression (there's no free lunch).\n\n

\n

The memory requirements for inflate are (in bytes)\n\n

\n
1 << windowBits
\n

that is, 32K for windowBits=15 (default value) plus a few kilobytes\nfor small objects.\n\n

\n

This is in addition to a single internal output slab buffer of size\nchunkSize, which defaults to 16K.\n\n

\n

The speed of zlib compression is affected most dramatically by the\nlevel setting. A higher level will result in better compression, but\nwill take longer to complete. A lower level will result in less\ncompression, but will be much faster.\n\n

\n

In general, greater memory usage options will mean that node has to make\nfewer calls to zlib, since it'll be able to process more data in a\nsingle write operation. So, this is another factor that affects the\nspeed, at the cost of memory usage.\n\n

\n" + }, + { + "textRaw": "Constants", + "name": "Constants", + "type": "misc", + "desc": "

All of the constants defined in zlib.h are also defined on\nrequire('zlib').\nIn the normal course of operations, you will not need to ever set any of\nthese. They are documented here so that their presence is not\nsurprising. This section is taken almost directly from the zlib\ndocumentation. See\n

\n

http://zlib.net/manual.html#Constants for more details.\n\n

\n

Allowed flush values.\n\n

\n
    \n
  • zlib.Z_NO_FLUSH
  • \n
  • zlib.Z_PARTIAL_FLUSH
  • \n
  • zlib.Z_SYNC_FLUSH
  • \n
  • zlib.Z_FULL_FLUSH
  • \n
  • zlib.Z_FINISH
  • \n
  • zlib.Z_BLOCK
  • \n
  • zlib.Z_TREES
  • \n
\n

Return codes for the compression/decompression functions. Negative\nvalues are errors, positive values are used for special but normal\nevents.\n\n

\n
    \n
  • zlib.Z_OK
  • \n
  • zlib.Z_STREAM_END
  • \n
  • zlib.Z_NEED_DICT
  • \n
  • zlib.Z_ERRNO
  • \n
  • zlib.Z_STREAM_ERROR
  • \n
  • zlib.Z_DATA_ERROR
  • \n
  • zlib.Z_MEM_ERROR
  • \n
  • zlib.Z_BUF_ERROR
  • \n
  • zlib.Z_VERSION_ERROR
  • \n
\n

Compression levels.\n\n

\n
    \n
  • zlib.Z_NO_COMPRESSION
  • \n
  • zlib.Z_BEST_SPEED
  • \n
  • zlib.Z_BEST_COMPRESSION
  • \n
  • zlib.Z_DEFAULT_COMPRESSION
  • \n
\n

Compression strategy.\n\n

\n
    \n
  • zlib.Z_FILTERED
  • \n
  • zlib.Z_HUFFMAN_ONLY
  • \n
  • zlib.Z_RLE
  • \n
  • zlib.Z_FIXED
  • \n
  • zlib.Z_DEFAULT_STRATEGY
  • \n
\n

Possible values of the data_type field.\n\n

\n
    \n
  • zlib.Z_BINARY
  • \n
  • zlib.Z_TEXT
  • \n
  • zlib.Z_ASCII
  • \n
  • zlib.Z_UNKNOWN
  • \n
\n

The deflate compression method (the only one supported in this version).\n\n

\n
    \n
  • zlib.Z_DEFLATED
  • \n
\n

For initializing zalloc, zfree, opaque.\n\n

\n
    \n
  • zlib.Z_NULL
  • \n
\n" + } + ], + "type": "module", + "displayName": "Zlib" + }, + { + "textRaw": "os", + "name": "os", + "stability": 4, + "stabilityText": "API Frozen", + "desc": "

Provides a few basic operating-system related utility functions.\n\n

\n

Use require('os') to access this module.\n\n

\n", + "methods": [ + { + "textRaw": "os.tmpDir()", + "type": "method", + "name": "tmpDir", + "desc": "

Returns the operating system's default directory for temp files.\n\n

\n", + "signatures": [ + { + "params": [] + } + ] + }, + { + "textRaw": "os.hostname()", + "type": "method", + "name": "hostname", + "desc": "

Returns the hostname of the operating system.\n\n

\n", + "signatures": [ + { + "params": [] + } + ] + }, + { + "textRaw": "os.type()", + "type": "method", + "name": "type", + "desc": "

Returns the operating system name.\n\n

\n", + "signatures": [ + { + "params": [] + } + ] + }, + { + "textRaw": "os.platform()", + "type": "method", + "name": "platform", + "desc": "

Returns the operating system platform.\n\n

\n", + "signatures": [ + { + "params": [] + } + ] + }, + { + "textRaw": "os.arch()", + "type": "method", + "name": "arch", + "desc": "

Returns the operating system CPU architecture.\n\n

\n", + "signatures": [ + { + "params": [] + } + ] + }, + { + "textRaw": "os.release()", + "type": "method", + "name": "release", + "desc": "

Returns the operating system release.\n\n

\n", + "signatures": [ + { + "params": [] + } + ] + }, + { + "textRaw": "os.uptime()", + "type": "method", + "name": "uptime", + "desc": "

Returns the system uptime in seconds.\n\n

\n", + "signatures": [ + { + "params": [] + } + ] + }, + { + "textRaw": "os.loadavg()", + "type": "method", + "name": "loadavg", + "desc": "

Returns an array containing the 1, 5, and 15 minute load averages.\n\n

\n", + "signatures": [ + { + "params": [] + } + ] + }, + { + "textRaw": "os.totalmem()", + "type": "method", + "name": "totalmem", + "desc": "

Returns the total amount of system memory in bytes.\n\n

\n", + "signatures": [ + { + "params": [] + } + ] + }, + { + "textRaw": "os.freemem()", + "type": "method", + "name": "freemem", + "desc": "

Returns the amount of free system memory in bytes.\n\n

\n", + "signatures": [ + { + "params": [] + } + ] + }, + { + "textRaw": "os.cpus()", + "type": "method", + "name": "cpus", + "desc": "

Returns an array of objects containing information about each CPU/core installed: model, speed (in MHz), and times (an object containing the number of CPU ticks spent in: user, nice, sys, idle, and irq).\n\n

\n

Example inspection of os.cpus:\n\n

\n
[ { model: 'Intel(R) Core(TM) i7 CPU         860  @ 2.80GHz',\n    speed: 2926,\n    times:\n     { user: 252020,\n       nice: 0,\n       sys: 30340,\n       idle: 1070356870,\n       irq: 0 } },\n  { model: 'Intel(R) Core(TM) i7 CPU         860  @ 2.80GHz',\n    speed: 2926,\n    times:\n     { user: 306960,\n       nice: 0,\n       sys: 26980,\n       idle: 1071569080,\n       irq: 0 } },\n  { model: 'Intel(R) Core(TM) i7 CPU         860  @ 2.80GHz',\n    speed: 2926,\n    times:\n     { user: 248450,\n       nice: 0,\n       sys: 21750,\n       idle: 1070919370,\n       irq: 0 } },\n  { model: 'Intel(R) Core(TM) i7 CPU         860  @ 2.80GHz',\n    speed: 2926,\n    times:\n     { user: 256880,\n       nice: 0,\n       sys: 19430,\n       idle: 1070905480,\n       irq: 20 } },\n  { model: 'Intel(R) Core(TM) i7 CPU         860  @ 2.80GHz',\n    speed: 2926,\n    times:\n     { user: 511580,\n       nice: 20,\n       sys: 40900,\n       idle: 1070842510,\n       irq: 0 } },\n  { model: 'Intel(R) Core(TM) i7 CPU         860  @ 2.80GHz',\n    speed: 2926,\n    times:\n     { user: 291660,\n       nice: 0,\n       sys: 34360,\n       idle: 1070888000,\n       irq: 10 } },\n  { model: 'Intel(R) Core(TM) i7 CPU         860  @ 2.80GHz',\n    speed: 2926,\n    times:\n     { user: 308260,\n       nice: 0,\n       sys: 55410,\n       idle: 1071129970,\n       irq: 880 } },\n  { model: 'Intel(R) Core(TM) i7 CPU         860  @ 2.80GHz',\n    speed: 2926,\n    times:\n     { user: 266450,\n       nice: 1480,\n       sys: 34920,\n       idle: 1072572010,\n       irq: 30 } } ]
\n", + "signatures": [ + { + "params": [] + } + ] + }, + { + "textRaw": "os.networkInterfaces()", + "type": "method", + "name": "networkInterfaces", + "desc": "

Get a list of network interfaces:\n\n

\n
{ lo0: \n   [ { address: '::1', family: 'IPv6', internal: true },\n     { address: 'fe80::1', family: 'IPv6', internal: true },\n     { address: '127.0.0.1', family: 'IPv4', internal: true } ],\n  en1: \n   [ { address: 'fe80::cabc:c8ff:feef:f996', family: 'IPv6',\n       internal: false },\n     { address: '10.0.1.123', family: 'IPv4', internal: false } ],\n  vmnet1: [ { address: '10.99.99.254', family: 'IPv4', internal: false } ],\n  vmnet8: [ { address: '10.88.88.1', family: 'IPv4', internal: false } ],\n  ppp0: [ { address: '10.2.0.231', family: 'IPv4', internal: false } ] }
\n", + "signatures": [ + { + "params": [] + } + ] + } + ], + "properties": [ + { + "textRaw": "os.EOL", + "name": "EOL", + "desc": "

A constant defining the appropriate End-of-line marker for the operating system.\n\n

\n" + } + ], + "type": "module", + "displayName": "os" + }, + { + "textRaw": "Cluster", + "name": "cluster", + "stability": 1, + "stabilityText": "Experimental", + "desc": "

A single instance of Node runs in a single thread. To take advantage of\nmulti-core systems the user will sometimes want to launch a cluster of Node\nprocesses to handle the load.\n\n

\n

The cluster module allows you to easily create a network of processes that\nall share server ports.\n\n

\n
var cluster = require('cluster');\nvar http = require('http');\nvar numCPUs = require('os').cpus().length;\n\nif (cluster.isMaster) {\n  // Fork workers.\n  for (var i = 0; i < numCPUs; i++) {\n    cluster.fork();\n  }\n\n  cluster.on('exit', function(worker, code, signal) {\n    console.log('worker ' + worker.process.pid + ' died');\n  });\n} else {\n  // Workers can share any TCP connection\n  // In this case its a HTTP server\n  http.createServer(function(req, res) {\n    res.writeHead(200);\n    res.end("hello world\\n");\n  }).listen(8000);\n}
\n

Running node will now share port 8000 between the workers:\n\n

\n
% node server.js\nWorker 2438 online\nWorker 2437 online
\n

This feature was introduced recently, and may change in future versions.\nPlease try it out and provide feedback.\n\n

\n

Also note that, on Windows, it is not yet possible to set up a named pipe\nserver in a worker.\n\n

\n", + "miscs": [ + { + "textRaw": "How It Works", + "name": "How It Works", + "type": "misc", + "desc": "

The worker processes are spawned using the child_process.fork method,\nso that they can communicate with the parent via IPC and pass server\nhandles back and forth.\n\n

\n

When you call server.listen(...) in a worker, it serializes the\narguments and passes the request to the master process. If the master\nprocess already has a listening server matching the worker's\nrequirements, then it passes the handle to the worker. If it does not\nalready have a listening server matching that requirement, then it will\ncreate one, and pass the handle to the child.\n\n

\n

This causes potentially surprising behavior in three edge cases:\n\n

\n
    \n
  1. server.listen({fd: 7}) Because the message is passed to the master,\nfile descriptor 7 in the parent will be listened on, and the\nhandle passed to the worker, rather than listening to the worker's\nidea of what the number 7 file descriptor references.
  2. \n
  3. server.listen(handle) Listening on handles explicitly will cause\nthe worker to use the supplied handle, rather than talk to the master\nprocess. If the worker already has the handle, then it's presumed\nthat you know what you are doing.
  4. \n
  5. server.listen(0) Normally, this will cause servers to listen on a\nrandom port. However, in a cluster, each worker will receive the\nsame "random" port each time they do listen(0). In essence, the\nport is random the first time, but predictable thereafter. If you\nwant to listen on a unique port, generate a port number based on the\ncluster worker ID.
  6. \n
\n

When multiple processes are all accept()ing on the same underlying\nresource, the operating system load-balances across them very\nefficiently. There is no routing logic in Node.js, or in your program,\nand no shared state between the workers. Therefore, it is important to\ndesign your program such that it does not rely too heavily on in-memory\ndata objects for things like sessions and login.\n\n

\n

Because workers are all separate processes, they can be killed or\nre-spawned depending on your program's needs, without affecting other\nworkers. As long as there are some workers still alive, the server will\ncontinue to accept connections. Node does not automatically manage the\nnumber of workers for you, however. It is your responsibility to manage\nthe worker pool for your application's needs.\n\n

\n" + } + ], + "properties": [ + { + "textRaw": "`settings` {Object} ", + "name": "settings", + "options": [ + { + "textRaw": "`exec` {String} file path to worker file. (Default=`__filename`) ", + "name": "exec", + "default": "__filename", + "type": "String", + "desc": "file path to worker file." + }, + { + "textRaw": "`args` {Array} string arguments passed to worker. (Default=`process.argv.slice(2)`) ", + "name": "args", + "default": "process.argv.slice(2)", + "type": "Array", + "desc": "string arguments passed to worker." + }, + { + "textRaw": "`silent` {Boolean} whether or not to send output to parent's stdio. (Default=`false`) ", + "name": "silent", + "default": "false", + "type": "Boolean", + "desc": "whether or not to send output to parent's stdio." + } + ], + "desc": "

All settings set by the .setupMaster is stored in this settings object.\nThis object is not supposed to be change or set manually, by you.\n\n

\n" + }, + { + "textRaw": "`isMaster` {Boolean} ", + "name": "isMaster", + "desc": "

True if the process is a master. This is determined\nby the process.env.NODE_UNIQUE_ID. If process.env.NODE_UNIQUE_ID is\nundefined, then isMaster is true.\n\n

\n" + }, + { + "textRaw": "`isWorker` {Boolean} ", + "name": "isWorker", + "desc": "

This boolean flag is true if the process is a worker forked from a master.\nIf the process.env.NODE_UNIQUE_ID is set to a value, then\nisWorker is true.\n\n

\n" + }, + { + "textRaw": "`worker` {Object} ", + "name": "worker", + "desc": "

A reference to the current worker object. Not available in the master process.\n\n

\n
var cluster = require('cluster');\n\nif (cluster.isMaster) {\n  console.log('I am master');\n  cluster.fork();\n  cluster.fork();\n} else if (cluster.isWorker) {\n  console.log('I am worker #' + cluster.worker.id);\n}
\n" + }, + { + "textRaw": "`workers` {Object} ", + "name": "workers", + "desc": "

A hash that stores the active worker objects, keyed by id field. Makes it\neasy to loop through all the workers. It is only available in the master\nprocess.\n\n

\n
// Go through all workers\nfunction eachWorker(callback) {\n  for (var id in cluster.workers) {\n    callback(cluster.workers[id]);\n  }\n}\neachWorker(function(worker) {\n  worker.send('big announcement to all workers');\n});
\n

Should you wish to reference a worker over a communication channel, using\nthe worker's unique id is the easiest way to find the worker.\n\n

\n
socket.on('data', function(id) {\n  var worker = cluster.workers[id];\n});
\n" + } + ], + "events": [ + { + "textRaw": "Event: 'fork'", + "type": "event", + "name": "fork", + "params": [], + "desc": "

When a new worker is forked the cluster module will emit a 'fork' event.\nThis can be used to log worker activity, and create you own timeout.\n\n

\n
var timeouts = [];\nfunction errorMsg() {\n  console.error("Something must be wrong with the connection ...");\n}\n\ncluster.on('fork', function(worker) {\n  timeouts[worker.id] = setTimeout(errorMsg, 2000);\n});\ncluster.on('listening', function(worker, address) {\n  clearTimeout(timeouts[worker.id]);\n});\ncluster.on('exit', function(worker, code, signal) {\n  clearTimeout(timeouts[worker.id]);\n  errorMsg();\n});
\n" + }, + { + "textRaw": "Event: 'online'", + "type": "event", + "name": "online", + "params": [], + "desc": "

After forking a new worker, the worker should respond with a online message.\nWhen the master receives a online message it will emit such event.\nThe difference between 'fork' and 'online' is that fork is emitted when the\nmaster tries to fork a worker, and 'online' is emitted when the worker is\nbeing executed.\n\n

\n
cluster.on('online', function(worker) {\n  console.log("Yay, the worker responded after it was forked");\n});
\n" + }, + { + "textRaw": "Event: 'listening'", + "type": "event", + "name": "listening", + "params": [], + "desc": "

When calling listen() from a worker, a 'listening' event is automatically assigned\nto the server instance. When the server is listening a message is send to the master\nwhere the 'listening' event is emitted.\n\n

\n

The event handler is executed with two arguments, the worker contains the worker\nobject and the address object contains the following connection properties:\naddress, port and addressType. This is very useful if the worker is listening\non more than one address.\n\n

\n
cluster.on('listening', function(worker, address) {\n  console.log("A worker is now connected to " + address.address + ":" + address.port);\n});
\n" + }, + { + "textRaw": "Event: 'disconnect'", + "type": "event", + "name": "disconnect", + "params": [], + "desc": "

When a workers IPC channel has disconnected this event is emitted. This will happen\nwhen the worker dies, usually after calling .destroy().\n\n

\n

When calling .disconnect(), there may be a delay between the\ndisconnect and exit events. This event can be used to detect if\nthe process is stuck in a cleanup or if there are long-living\nconnections.\n\n

\n
cluster.on('disconnect', function(worker) {\n  console.log('The worker #' + worker.id + ' has disconnected');\n});
\n" + }, + { + "textRaw": "Event: 'exit'", + "type": "event", + "name": "exit", + "params": [], + "desc": "

When any of the workers die the cluster module will emit the 'exit' event.\nThis can be used to restart the worker by calling fork() again.\n\n

\n
cluster.on('exit', function(worker, code, signal) {\n  var exitCode = worker.process.exitCode;\n  console.log('worker ' + worker.process.pid + ' died ('+exitCode+'). restarting...');\n  cluster.fork();\n});
\n" + }, + { + "textRaw": "Event: 'setup'", + "type": "event", + "name": "setup", + "params": [], + "desc": "

When the .setupMaster() function has been executed this event emits.\nIf .setupMaster() was not executed before fork() this function will\ncall .setupMaster() with no arguments.\n\n

\n" + } + ], + "methods": [ + { + "textRaw": "cluster.setupMaster([settings])", + "type": "method", + "name": "setupMaster", + "signatures": [ + { + "params": [ + { + "textRaw": "`settings` {Object} ", + "options": [ + { + "textRaw": "`exec` {String} file path to worker file. (Default=`__filename`) ", + "name": "exec", + "default": "__filename", + "type": "String", + "desc": "file path to worker file." + }, + { + "textRaw": "`args` {Array} string arguments passed to worker. (Default=`process.argv.slice(2)`) ", + "name": "args", + "default": "process.argv.slice(2)", + "type": "Array", + "desc": "string arguments passed to worker." + }, + { + "textRaw": "`silent` {Boolean} whether or not to send output to parent's stdio. (Default=`false`) ", + "name": "silent", + "default": "false", + "type": "Boolean", + "desc": "whether or not to send output to parent's stdio." + } + ], + "name": "settings", + "type": "Object", + "optional": true + } + ] + }, + { + "params": [ + { + "name": "settings", + "optional": true + } + ] + } + ], + "desc": "

setupMaster is used to change the default 'fork' behavior. The new settings\nare effective immediately and permanently, they cannot be changed later on.\n\n

\n

Example:\n\n

\n
var cluster = require("cluster");\ncluster.setupMaster({\n  exec : "worker.js",\n  args : ["--use", "https"],\n  silent : true\n});\ncluster.fork();
\n" + }, + { + "textRaw": "cluster.fork([env])", + "type": "method", + "name": "fork", + "signatures": [ + { + "return": { + "textRaw": "return {Worker object} ", + "name": "return", + "type": "Worker object" + }, + "params": [ + { + "textRaw": "`env` {Object} Key/value pairs to add to child process environment. ", + "name": "env", + "type": "Object", + "desc": "Key/value pairs to add to child process environment.", + "optional": true + } + ] + }, + { + "params": [ + { + "name": "env", + "optional": true + } + ] + } + ], + "desc": "

Spawn a new worker process. This can only be called from the master process.\n\n

\n" + }, + { + "textRaw": "cluster.disconnect([callback])", + "type": "method", + "name": "disconnect", + "signatures": [ + { + "params": [ + { + "textRaw": "`callback` {Function} called when all workers are disconnected and handlers are closed ", + "name": "callback", + "type": "Function", + "desc": "called when all workers are disconnected and handlers are closed", + "optional": true + } + ] + }, + { + "params": [ + { + "name": "callback", + "optional": true + } + ] + } + ], + "desc": "

When calling this method, all workers will commit a graceful suicide. When they are\ndisconnected all internal handlers will be closed, allowing the master process to\ndie graceful if no other event is waiting.\n\n

\n

The method takes an optional callback argument which will be called when finished.\n\n

\n" + } + ], + "classes": [ + { + "textRaw": "Class: Worker", + "type": "class", + "name": "Worker", + "desc": "

A Worker object contains all public information and method about a worker.\nIn the master it can be obtained using cluster.workers. In a worker\nit can be obtained using cluster.worker.\n\n

\n", + "properties": [ + { + "textRaw": "`id` {String} ", + "name": "id", + "desc": "

Each new worker is given its own unique id, this id is stored in the\nid.\n\n

\n

While a worker is alive, this is the key that indexes it in\ncluster.workers\n\n

\n" + }, + { + "textRaw": "`process` {ChildProcess object} ", + "name": "process", + "desc": "

All workers are created using child_process.fork(), the returned object\nfrom this function is stored in process.\n\n

\n

See: Child Process module\n\n

\n" + }, + { + "textRaw": "`suicide` {Boolean} ", + "name": "suicide", + "desc": "

This property is a boolean. It is set when a worker dies after calling .destroy()\nor immediately after calling the .disconnect() method. Until then it is undefined.\n\n

\n" + } + ], + "methods": [ + { + "textRaw": "worker.send(message, [sendHandle])", + "type": "method", + "name": "send", + "signatures": [ + { + "params": [ + { + "textRaw": "`message` {Object} ", + "name": "message", + "type": "Object" + }, + { + "textRaw": "`sendHandle` {Handle object} ", + "name": "sendHandle", + "type": "Handle object", + "optional": true + } + ] + }, + { + "params": [ + { + "name": "message" + }, + { + "name": "sendHandle", + "optional": true + } + ] + } + ], + "desc": "

This function is equal to the send methods provided by\nchild_process.fork(). In the master you should use this function to\nsend a message to a specific worker. However in a worker you can also use\nprocess.send(message), since this is the same function.\n\n

\n

This example will echo back all messages from the master:\n\n

\n
if (cluster.isMaster) {\n  var worker = cluster.fork();\n  worker.send('hi there');\n\n} else if (cluster.isWorker) {\n  process.on('message', function(msg) {\n    process.send(msg);\n  });\n}
\n" + }, + { + "textRaw": "worker.destroy()", + "type": "method", + "name": "destroy", + "desc": "

This function will kill the worker, and inform the master to not spawn a\nnew worker. The boolean suicide lets you distinguish between voluntary\nand accidental exit.\n\n

\n
cluster.on('exit', function(worker, code, signal) {\n  if (worker.suicide === true) {\n    console.log('Oh, it was just suicide\\' – no need to worry').\n  }\n});\n\n// destroy worker\nworker.destroy();
\n", + "signatures": [ + { + "params": [] + } + ] + }, + { + "textRaw": "worker.disconnect()", + "type": "method", + "name": "disconnect", + "desc": "

When calling this function the worker will no longer accept new connections, but\nthey will be handled by any other listening worker. Existing connection will be\nallowed to exit as usual. When no more connections exist, the IPC channel to the worker\nwill close allowing it to die graceful. When the IPC channel is closed the disconnect\nevent will emit, this is then followed by the exit event, there is emitted when\nthe worker finally die.\n\n

\n

Because there might be long living connections, it is useful to implement a timeout.\nThis example ask the worker to disconnect and after 2 seconds it will destroy the\nserver. An alternative would be to execute worker.destroy() after 2 seconds, but\nthat would normally not allow the worker to do any cleanup if needed.\n\n

\n
if (cluster.isMaster) {\n  var worker = cluster.fork();\n  var timeout;\n\n  worker.on('listening', function(address) {\n    worker.disconnect();\n    timeout = setTimeout(function() {\n      worker.send('force kill');\n    }, 2000);\n  });\n\n  worker.on('disconnect', function() {\n    clearTimeout(timeout);\n  });\n\n} else if (cluster.isWorker) {\n  var net = require('net');\n  var server = net.createServer(function(socket) {\n    // connection never end\n  });\n\n  server.listen(8000);\n\n  server.on('close', function() {\n    // cleanup\n  });\n\n  process.on('message', function(msg) {\n    if (msg === 'force kill') {\n      server.destroy();\n    }\n  });\n}
\n", + "signatures": [ + { + "params": [] + } + ] + } + ], + "events": [ + { + "textRaw": "Event: 'message'", + "type": "event", + "name": "message", + "params": [], + "desc": "

This event is the same as the one provided by child_process.fork().\nIn the master you should use this event, however in a worker you can also use\nprocess.on('message')\n\n

\n

As an example, here is a cluster that keeps count of the number of requests\nin the master process using the message system:\n\n

\n
var cluster = require('cluster');\nvar http = require('http');\n\nif (cluster.isMaster) {\n\n  // Keep track of http requests\n  var numReqs = 0;\n  setInterval(function() {\n    console.log("numReqs =", numReqs);\n  }, 1000);\n\n  // Count requestes\n  function messageHandler(msg) {\n    if (msg.cmd && msg.cmd == 'notifyRequest') {\n      numReqs += 1;\n    }\n  }\n\n  // Start workers and listen for messages containing notifyRequest\n  var numCPUs = require('os').cpus().length;\n  for (var i = 0; i < numCPUs; i++) {\n    cluster.fork();\n  }\n\n  Object.keys(cluster.workers).forEach(function(id) {\n    cluster.workers[id].on('message', messageHandler);\n  });\n\n} else {\n\n  // Worker processes have a http server.\n  http.Server(function(req, res) {\n    res.writeHead(200);\n    res.end("hello world\\n");\n\n    // notify master about the request\n    process.send({ cmd: 'notifyRequest' });\n  }).listen(8000);\n}
\n" + }, + { + "textRaw": "Event: 'online'", + "type": "event", + "name": "online", + "desc": "

Same as the cluster.on('online') event, but emits only when the state change\non the specified worker.\n\n

\n
cluster.fork().on('online', function() {\n  // Worker is online\n};
\n", + "params": [] + }, + { + "textRaw": "Event: 'listening'", + "type": "event", + "name": "listening", + "params": [], + "desc": "

Same as the cluster.on('listening') event, but emits only when the state change\non the specified worker.\n\n

\n
cluster.fork().on('listening', function(address) {\n  // Worker is listening\n};
\n" + }, + { + "textRaw": "Event: 'disconnect'", + "type": "event", + "name": "disconnect", + "desc": "

Same as the cluster.on('disconnect') event, but emits only when the state change\non the specified worker.\n\n

\n
cluster.fork().on('disconnect', function() {\n  // Worker has disconnected\n};
\n", + "params": [] + }, + { + "textRaw": "Event: 'exit'", + "type": "event", + "name": "exit", + "params": [], + "desc": "

Emitted by the individual worker instance, when the underlying child process\nis terminated. See child_process event: 'exit'.\n\n

\n
var worker = cluster.fork();\nworker.on('exit', function(code, signal) {\n  if( signal ) {\n    console.log("worker was killed by signal: "+signal);\n  } else if( code !== 0 ) {\n    console.log("worker exited with error code: "+code);\n  } else {\n    console.log("worker success!");\n  }\n};
\n" + } + ] + } + ], + "type": "module", + "displayName": "Cluster" + } + ], + "stability": 3, + "stabilityText": "Stable" +} diff --git a/node-v0.8.14/doc/api/all.markdown b/node-v0.8.14/doc/api/all.markdown new file mode 100644 index 0000000..4e0dd81 --- /dev/null +++ b/node-v0.8.14/doc/api/all.markdown @@ -0,0 +1,36 @@ +@include documentation +@include synopsis +@include globals +@include stdio +@include timers +@include modules +@include addons +@include process +@include util +@include events +@include domain +@include buffer +@include stream +@include crypto +@include tls +@include string_decoder +@include fs +@include path +@include net +@include dgram +@include dns +@include http +@include https +@include url +@include querystring +@include punycode +@include readline +@include repl +@include vm +@include child_process +@include assert +@include tty +@include zlib +@include os +@include debugger +@include cluster diff --git a/node-v0.8.14/doc/api/assert.html b/node-v0.8.14/doc/api/assert.html new file mode 100644 index 0000000..4187134 --- /dev/null +++ b/node-v0.8.14/doc/api/assert.html @@ -0,0 +1,185 @@ + + + + + Assert Node.js v0.8.14 Manual & Documentation + + + + + +
+ + + +
+
+ + +
+
+

Node.js v0.8.14 Manual & Documentation

+ +
+
+ + + +
+

Assert#

+
Stability: 5 - Locked
+

This module is used for writing unit tests for your applications, you can +access it with require('assert'). + +

+

assert.fail(actual, expected, message, operator)#

+

Throws an exception that displays the values for actual and expected separated by the provided operator. + +

+

assert(value, message), assert.ok(value, [message])#

+

Tests if value is truthy, it is equivalent to assert.equal(true, !!value, message); + +

+

assert.equal(actual, expected, [message])#

+

Tests shallow, coercive equality with the equal comparison operator ( == ). + +

+

assert.notEqual(actual, expected, [message])#

+

Tests shallow, coercive non-equality with the not equal comparison operator ( != ). + +

+

assert.deepEqual(actual, expected, [message])#

+

Tests for deep equality. + +

+

assert.notDeepEqual(actual, expected, [message])#

+

Tests for any deep inequality. + +

+

assert.strictEqual(actual, expected, [message])#

+

Tests strict equality, as determined by the strict equality operator ( === ) + +

+

assert.notStrictEqual(actual, expected, [message])#

+

Tests strict non-equality, as determined by the strict not equal operator ( !== ) + +

+

assert.throws(block, [error], [message])#

+

Expects block to throw an error. error can be constructor, regexp or +validation function. + +

+

Validate instanceof using constructor: + +

+
assert.throws(
+  function() {
+    throw new Error("Wrong value");
+  },
+  Error
+);
+

Validate error message using RegExp: + +

+
assert.throws(
+  function() {
+    throw new Error("Wrong value");
+  },
+  /value/
+);
+

Custom error validation: + +

+
assert.throws(
+  function() {
+    throw new Error("Wrong value");
+  },
+  function(err) {
+    if ( (err instanceof Error) && /value/.test(err) ) {
+      return true;
+    }
+  },
+  "unexpected error"
+);
+

assert.doesNotThrow(block, [error], [message])#

+

Expects block not to throw an error, see assert.throws for details. + +

+

assert.ifError(value)#

+

Tests if value is not a false value, throws if it is a true value. Useful when +testing the first argument, error in callbacks. +

+ +
+
+
+ + + + + + + + + diff --git a/node-v0.8.14/doc/api/assert.json b/node-v0.8.14/doc/api/assert.json new file mode 100644 index 0000000..63c24ef --- /dev/null +++ b/node-v0.8.14/doc/api/assert.json @@ -0,0 +1,258 @@ +{ + "source": "doc/api/assert.markdown", + "modules": [ + { + "textRaw": "Assert", + "name": "assert", + "stability": 5, + "stabilityText": "Locked", + "desc": "

This module is used for writing unit tests for your applications, you can\naccess it with require('assert').\n\n

\n", + "methods": [ + { + "textRaw": "assert.fail(actual, expected, message, operator)", + "type": "method", + "name": "fail", + "desc": "

Throws an exception that displays the values for actual and expected separated by the provided operator.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "actual" + }, + { + "name": "expected" + }, + { + "name": "message" + }, + { + "name": "operator" + } + ] + } + ] + }, + { + "textRaw": "assert(value, message), assert.ok(value, [message])", + "type": "method", + "name": "ok", + "desc": "

Tests if value is truthy, it is equivalent to assert.equal(true, !!value, message);\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "value" + }, + { + "name": "message)" + }, + { + "name": "assert.ok(value" + }, + { + "name": "message", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "assert.equal(actual, expected, [message])", + "type": "method", + "name": "equal", + "desc": "

Tests shallow, coercive equality with the equal comparison operator ( == ).\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "actual" + }, + { + "name": "expected" + }, + { + "name": "message", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "assert.notEqual(actual, expected, [message])", + "type": "method", + "name": "notEqual", + "desc": "

Tests shallow, coercive non-equality with the not equal comparison operator ( != ).\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "actual" + }, + { + "name": "expected" + }, + { + "name": "message", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "assert.deepEqual(actual, expected, [message])", + "type": "method", + "name": "deepEqual", + "desc": "

Tests for deep equality.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "actual" + }, + { + "name": "expected" + }, + { + "name": "message", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "assert.notDeepEqual(actual, expected, [message])", + "type": "method", + "name": "notDeepEqual", + "desc": "

Tests for any deep inequality.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "actual" + }, + { + "name": "expected" + }, + { + "name": "message", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "assert.strictEqual(actual, expected, [message])", + "type": "method", + "name": "strictEqual", + "desc": "

Tests strict equality, as determined by the strict equality operator ( === )\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "actual" + }, + { + "name": "expected" + }, + { + "name": "message", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "assert.notStrictEqual(actual, expected, [message])", + "type": "method", + "name": "notStrictEqual", + "desc": "

Tests strict non-equality, as determined by the strict not equal operator ( !== )\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "actual" + }, + { + "name": "expected" + }, + { + "name": "message", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "assert.throws(block, [error], [message])", + "type": "method", + "name": "throws", + "desc": "

Expects block to throw an error. error can be constructor, regexp or \nvalidation function.\n\n

\n

Validate instanceof using constructor:\n\n

\n
assert.throws(\n  function() {\n    throw new Error("Wrong value");\n  },\n  Error\n);
\n

Validate error message using RegExp:\n\n

\n
assert.throws(\n  function() {\n    throw new Error("Wrong value");\n  },\n  /value/\n);
\n

Custom error validation:\n\n

\n
assert.throws(\n  function() {\n    throw new Error("Wrong value");\n  },\n  function(err) {\n    if ( (err instanceof Error) && /value/.test(err) ) {\n      return true;\n    }\n  },\n  "unexpected error"\n);
\n", + "signatures": [ + { + "params": [ + { + "name": "block" + }, + { + "name": "error", + "optional": true + }, + { + "name": "message", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "assert.doesNotThrow(block, [error], [message])", + "type": "method", + "name": "doesNotThrow", + "desc": "

Expects block not to throw an error, see assert.throws for details.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "block" + }, + { + "name": "error", + "optional": true + }, + { + "name": "message", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "assert.ifError(value)", + "type": "method", + "name": "ifError", + "desc": "

Tests if value is not a false value, throws if it is a true value. Useful when\ntesting the first argument, error in callbacks.\n

\n", + "signatures": [ + { + "params": [ + { + "name": "value" + } + ] + } + ] + } + ], + "type": "module", + "displayName": "Assert" + } + ] +} diff --git a/node-v0.8.14/doc/api/assert.markdown b/node-v0.8.14/doc/api/assert.markdown new file mode 100644 index 0000000..c93c1e7 --- /dev/null +++ b/node-v0.8.14/doc/api/assert.markdown @@ -0,0 +1,84 @@ +# Assert + + Stability: 5 - Locked + +This module is used for writing unit tests for your applications, you can +access it with `require('assert')`. + +## assert.fail(actual, expected, message, operator) + +Throws an exception that displays the values for `actual` and `expected` separated by the provided operator. + +## assert(value, message), assert.ok(value, [message]) + +Tests if value is truthy, it is equivalent to `assert.equal(true, !!value, message);` + +## assert.equal(actual, expected, [message]) + +Tests shallow, coercive equality with the equal comparison operator ( `==` ). + +## assert.notEqual(actual, expected, [message]) + +Tests shallow, coercive non-equality with the not equal comparison operator ( `!=` ). + +## assert.deepEqual(actual, expected, [message]) + +Tests for deep equality. + +## assert.notDeepEqual(actual, expected, [message]) + +Tests for any deep inequality. + +## assert.strictEqual(actual, expected, [message]) + +Tests strict equality, as determined by the strict equality operator ( `===` ) + +## assert.notStrictEqual(actual, expected, [message]) + +Tests strict non-equality, as determined by the strict not equal operator ( `!==` ) + +## assert.throws(block, [error], [message]) + +Expects `block` to throw an error. `error` can be constructor, regexp or +validation function. + +Validate instanceof using constructor: + + assert.throws( + function() { + throw new Error("Wrong value"); + }, + Error + ); + +Validate error message using RegExp: + + assert.throws( + function() { + throw new Error("Wrong value"); + }, + /value/ + ); + +Custom error validation: + + assert.throws( + function() { + throw new Error("Wrong value"); + }, + function(err) { + if ( (err instanceof Error) && /value/.test(err) ) { + return true; + } + }, + "unexpected error" + ); + +## assert.doesNotThrow(block, [error], [message]) + +Expects `block` not to throw an error, see assert.throws for details. + +## assert.ifError(value) + +Tests if value is not a false value, throws if it is a true value. Useful when +testing the first argument, `error` in callbacks. diff --git a/node-v0.8.14/doc/api/assets/sh.css b/node-v0.8.14/doc/api/assets/sh.css new file mode 100644 index 0000000..7022e19 --- /dev/null +++ b/node-v0.8.14/doc/api/assets/sh.css @@ -0,0 +1,24 @@ +.sh_sourceCode { + font-weight: normal; + font-style: normal; +} + +.sh_sourceCode .sh_symbol, +.sh_sourceCode .sh_cbracket { + color: #333; +} + +.sh_sourceCode .sh_keyword { + color: #c96; +} + +.sh_sourceCode .sh_string, +.sh_sourceCode .sh_regexp, +.sh_sourceCode .sh_number, +.sh_sourceCode .sh_specialchar { + color: #690; +} + +.sh_sourceCode .sh_comment { + color: #666; +} diff --git a/node-v0.8.14/doc/api/assets/style.css b/node-v0.8.14/doc/api/assets/style.css new file mode 100644 index 0000000..5523984 --- /dev/null +++ b/node-v0.8.14/doc/api/assets/style.css @@ -0,0 +1,518 @@ +/*--------------------- Layout and Typography ----------------------------*/ +html { + -webkit-font-smoothing: antialiased; +} + +body { + font-family: "Lucida Grande", "Lucida Sans Unicode", "Lucida Sans", Verdana, Tahoma, sans-serif; + font-size: 14px; + line-height: 180%; + color: black; + background-color: white; + margin: 0; padding: 49px 0 0 0; + border-top: 6px #8CC84B solid; +} + +a { + color: #480; + text-decoration: underline; +} + +a:visited { + color: #46483e; + text-decoration: underline; +} + +a:hover, +a:focus { + text-decoration: none; +} + +code a:hover { + background: none; + color: #b950b7; +} + +#changelog #gtoc { + display: none; +} + +#gtoc p { + margin: 0; + font-size: 18px; + line-height: 30px; +} + +#gtoc a { + font-family: Georgia, FreeSerif, Times, serif; + text-decoration: none; + color: #46483e; +} + +#gtoc a:hover { + color: #669900; + text-decoration: underline; +} + +.notice { + display: block; + padding: 1em; + margin: 1.4667em 0 2.9334em; + background: #FFF6BF; + color: #514721; + border: 1px solid #FFD324; +} + +.notice p { + margin: 0; +} + +ul.plain { + list-style: none; +} + +abbr { + border-bottom: 1px dotted #454545; +} + +p { + margin: 0 0 1.4667em 0; + position: relative; + text-rendering: optimizeLegibility; +} + +.apidoc #apicontent p, +.apidoc #apicontent li { + font-size: 15px; + line-height: 22px; + color: #000; + font-family: Georgia, FreeSerif, Times, serif; +} + +ol, ul, dl { + margin: 0 0 1em 0; + padding: 0; +} + +ol ul, ol ol, ol dl, +ul ul, ul ol, ul dl, +dl ul, dl ol, dl dl { + margin-bottom: 0; +} + +ol p:first-child, +ul p:first-child, +dl p:first-child { + margin-bottom: 0; +} + +ul, ol { + margin-left: 2em; +} + +dl dt { + position: relative; + margin: 1.5em 0 0; +} + +dl dd { + position: relative; + margin: 0 1em 0; +} + +dd + dt.pre { + margin-top: 1.6em; +} + +h1, h2, h3, h4, h5, h6 { + font-family: Helvetica, Arial, sans-serif; + color: #000; + text-rendering: optimizeLegibility; + position: relative; +} + +header h1 { + font-family: Georgia, FreeSerif, Times, serif; + font-size: 30px; + font-weight: normal; + line-height: 36px; + color: #480; + margin: 15px 0 11px; +} + +h1 { + font-size: 29px; + line-height: 33px; + margin: 2em 0 15px; +} + +#toc + h1 { + margin-top: 1em; + padding-top: 0; +} + +h2 { + font-size: 1.4em; + line-height: 1.0909em; + margin: 1.5em 0 0.5em; +} + +h2 + h2 { + margin: 0 0 0.5em; +} + +h3 { + font-size: 1.3em; + line-height: 1.1282em; + margin: 2.2em 0 0.5em; +} + +h3 + h3 { + margin: 0 0 0.5em; +} + +h2, h3, h4 { + position: relative; + padding-right: 40px; +} + +h1 span, h2 span, h3 span, h4 span { + font-size: 25px; + position: absolute; + display: block; + top: 0; + right: 0; + opacity: 0.3; +} + +h1 span:hover, h2 span:hover, h3 span:hover, h4 span:hover { + opacity: 1; +} + +h1 span a, h2 span a, h3 span a, h4 span a { + font-size: 0.8em; + color: #000; + text-decoration: none; + font-family: Helvetica, Arial, sans-serif; + font-weight: bold; +} + +h1 span a.top, h2 span a.top, h3 span a.top, h4 span a.top { + /* XXX Get an image and clean up these two links + * so that they look nice next to one another. + * http://www.chrisglass.com/work/nodejs/website/v05/docs.html + * -isaacs + */ + display: none; +} + +h5 { + font-size: 1.125em; + line-height: 1.4em; +} + +h6 { + font-size: 1em; + line-height: 1.4667em; +} + +pre, tt, code { + font-size: 14px; + line-height: 1.5438em; + font-family: Monaco, Consolas, "Lucida Console", monospace; + margin: 0; padding: 0; +} + +.pre { + font-family: Monaco, Consolas, "Lucida Console", monospace; + line-height: 1.5438em; + font-size: 0.95em; +} + +pre { + padding: 1em 1.6em 1em 1.2em; + vertical-align: top; + background: #f8f8f8; + border: 1px solid #e8e8e8; + border-width: 1px 1px 1px 6px; + margin: -0.5em 0 1.1em; + overflow-x: auto; +} + +pre + h3 { + margin-top: 2.225em; +} + +code.pre { + white-space: pre; +} + +#intro { + width: 775px; + margin: 0 auto; + text-align: center; + color: #d2d8ba; + /* preload platform-icons.png */ + background-image: url(http://nodejs.org/images/platform-icons.png); + background-repeat: no-repeat; + background-position: -999em -999em; +} + +#intro.interior #logo { + margin-left: -298px; + border: 0; +} + +hr { + background: none; + border: medium none; + border-bottom: 1px solid #ccc; + margin: 1em 0; +} + +#toc { + font-size: 15px; + line-height: 1.5em; + line-height: 22px; + padding-top: 4px; +} + +#toc h2 { + font-size: 15px; + line-height: 21px; + margin: 0 0 0.5em; +} + +#toc h2 a { + float: right; +} + +#toc hr { + margin: 1em 0 2em; +} + +#toc ul, +#api-section-index #apicontent ul li, +#api-section-index #apicontent ul { + font-family: Georgia, FreeSerif, Times, serif; + color: #666 !important; +} + +#toc ul a { + text-decoration: none; + border-bottom: 1px dotted #480; +} + +#toc ul a:hover, +#toc ul a:focus { + border-bottom: 1px dotted #fff; + color: #000; +} + +p tt, +p code { + background: #f8f8ff; + border: 1px solid #dedede; + padding: 0 0.2em; +} + +#content { + width: 953px; + margin: 0 auto; + overflow: visible; + clear: both; + display: block; +} + +#column1.interior { + width: 749px; + float: right; + padding-top: 7px; + padding-top: 11px; + font-size: 18px; +} + +#column2.interior { + width: 140px; + float: left; + margin-top: -55px; + overflow: visible; +} + +#column2.interior ul { + margin-left: 0; +} + +#column2.interior li { + list-style-type: none; +} + +#column2.interior li a { + display: block; + padding: 0 0 0 35px; + color: #878b78; + text-transform: uppercase; + text-decoration: none; + font-size: 11px; + line-height: 23px; +} + +#column2.interior li a.home { background: url(http://nodejs.org/images/icons-interior.png) no-repeat -156px 3px; } +#column2.interior li a.download { background: url(http://nodejs.org/images/icons-interior.png) no-repeat -156px -21px; } +#column2.interior li a.about { background: url(http://nodejs.org/images/icons-interior.png) no-repeat -156px -45px; } +#column2.interior li a.npm { background: url(http://nodejs.org/images/icons-interior.png) no-repeat -156px -69px; } +#column2.interior li a.docs { background: url(http://nodejs.org/images/icons-interior.png) no-repeat -156px -93px; } +#column2.interior li a.blog { background: url(http://nodejs.org/images/icons-interior.png) no-repeat -156px -117px; } +#column2.interior li a.community { background: url(http://nodejs.org/images/icons-interior.png) no-repeat -156px -141px; } +#column2.interior li a.logos { background: url(http://nodejs.org/images/icons-interior.png) no-repeat -156px -165px; } +#column2.interior li a.jobs { background: url(http://nodejs.org/images/icons-interior.png) no-repeat -156px -189px; } + +#column2.interior li a.home.current { background-position: 2px 3px; } +#column2.interior li a.download.current { background-position: 2px -21px; } +#column2.interior li a.about.current { background-position: 2px -45px; } +#column2.interior li a.npm.current { background-position: 2px -69px; } +#column2.interior li a.docs.current { background-position: 2px -93px; } +#column2.interior li a.blog.current { background-position: 2px -117px; } +#column2.interior li a.community.current { background-position: 2px -141px; } +#column2.interior li a.logos.current { background-position: 2px -165px; } +#column2.interior li a.jobs.current { background-position: 2px -189px; } + +#column2.interior li a.home:hover { background-position: -331px 3px; } +#column2.interior li a.download:hover { background-position: -331px -21px; } +#column2.interior li a.about:hover { background-position: -331px -45px; } +#column2.interior li a.npm:hover { background-position: -331px -69px; } +#column2.interior li a.docs:hover { background-position: -331px -93px; } +#column2.interior li a.blog:hover { background-position: -331px -117px; } +#column2.interior li a.community:hover { background-position: -331px -141px; } +#column2.interior li a.logos:hover { background-position: -331px -165px; } +#column2.interior li a.jobs:hover { background-position: -331px -189px; } + +#column2.interior li a.current { + color: #8cc84b; + font-weight: bold; +} + +#column2.interior li a:hover { + color: #000000; + text-decoration: none; +} + +#column2.interior li + li { + border-top: 1px solid #c1c7ac; +} + +#column2.interior p.twitter { + padding-top: 20px; +} + +#column2.interior p.twitter a { + background: url(http://nodejs.org/images/twitter-bird.png) no-repeat 0 4px; + padding-left: 37px; + text-decoration: none; +} + +#column2.interior p.twitter a:hover { + text-decoration: underline; +} + +a.totop { + font-family: "Lucida Grande", "Lucida Sans Unicode", "Lucida Sans", Verdana, Tahoma, sans-serif; + font-weight: bold; + text-indent: -9999999px; + background: url(http://nodejs.org/images/anchor.png) no-repeat top left; + margin-right: 7px; + display: block; + width: 13px; + border-bottom: 1px solid #cccccc; +} + +a.anchor { + font-family: "Lucida Grande", "Lucida Sans Unicode", "Lucida Sans", Verdana, Tahoma, sans-serif; + font-weight: bold; + text-indent: -9999999px; + background: url(http://nodejs.org/images/anchor.png) no-repeat top right; + display: block; + width: 13px; + border-bottom: 1px solid #cccccc; +} + +#footer { + width: 942px; + margin: 150px auto 55px auto; + padding: 0; +} + +#footer p { + font-size: 11px; + line-height: 1em; + padding: 0 0 0 195px; + color: #666; +} + +#footer p, +#footer li { + font-family: "Lucida Grande", "Lucida Sans Unicode", "Lucida Sans", Verdana, Tahoma, sans-serif; +} + +#footer a { + text-decoration: none; + border: none; + color: #480; +} + +#footer a:hover { + color: #000; +} + +#footer p a { + border-bottom: 1px dotted #480; + color: #878b78; +} + +#footer ul { + background: url(http://nodejs.org/images/footer-logo-alt.png) left 17px no-repeat; + padding: 23px 0 0 195px; + height: 26px; + margin-left: -1px; + border-top: 1px solid #626557; +} + +#footer ul li { + list-style-type: none; + float: left; + font-size: 12px; + margin: 0 !important; + padding: 0; + height: 12px; +} + +#footer ul li a { + margin: 0; + padding: 0 6px 0 0; + display: block; + height: 12px; + line-height: 12px; +} + +#footer ul li + li { + margin-left: 3px; +} + +#footer ul li + li a { + padding: 0 6px 0 6px; + border-left: 1px solid #878b78; +} + +#footer ul li a.twitter { + background: url(http://nodejs.org/images/twitter-bird.png) no-repeat 5px 0px; + padding-left: 25px; +} + +/* simpler clearfix */ +.clearfix:after { + content: "."; + display: block; + height: 0; + clear: both; + visibility: hidden; +} diff --git a/node-v0.8.14/doc/api/buffer.html b/node-v0.8.14/doc/api/buffer.html new file mode 100644 index 0000000..26fde29 --- /dev/null +++ b/node-v0.8.14/doc/api/buffer.html @@ -0,0 +1,865 @@ + + + + + Buffer Node.js v0.8.14 Manual & Documentation + + + + + +
+ + + +
+
+ + +
+
+

Node.js v0.8.14 Manual & Documentation

+ +
+
+ +
+

Table of Contents

+ + +
+ +
+

Buffer#

+
Stability: 3 - Stable
+

Pure JavaScript is Unicode friendly but not nice to binary data. When +dealing with TCP streams or the file system, it's necessary to handle octet +streams. Node has several strategies for manipulating, creating, and +consuming octet streams. + +

+

Raw data is stored in instances of the Buffer class. A Buffer is similar +to an array of integers but corresponds to a raw memory allocation outside +the V8 heap. A Buffer cannot be resized. + +

+

The Buffer class is a global, making it very rare that one would need +to ever require('buffer'). + +

+

Converting between Buffers and JavaScript string objects requires an explicit +encoding method. Here are the different string encodings. + +

+
    +
  • 'ascii' - for 7 bit ASCII data only. This encoding method is very fast, and +will strip the high bit if set. +Note that this encoding converts a null character ('\0' or '\u0000') into +0x20 (character code of a space). If you want to convert a null character +into 0x00, you should use 'utf8'.

    +
  • +
  • 'utf8' - Multibyte encoded Unicode characters. Many web pages and other +document formats use UTF-8.

    +
  • +
  • 'utf16le' - 2 or 4 bytes, little endian encoded Unicode characters. +Surrogate pairs (U+10000 to U+10FFFF) are supported.

    +
  • +
  • 'ucs2' - Alias of 'utf16le'.

    +
  • +
  • 'base64' - Base64 string encoding.

    +
  • +
  • 'binary' - A way of encoding raw binary data into strings by using only +the first 8 bits of each character. This encoding method is deprecated and +should be avoided in favor of Buffer objects where possible. This encoding +will be removed in future versions of Node.

    +
  • +
  • 'hex' - Encode each byte as two hexadecimal characters.

    +
  • +
+

Class: Buffer#

+

The Buffer class is a global type for dealing with binary data directly. +It can be constructed in a variety of ways. + +

+

new Buffer(size)#

+
    +
  • size Number
  • +
+

Allocates a new buffer of size octets. + +

+

new Buffer(array)#

+
    +
  • array Array
  • +
+

Allocates a new buffer using an array of octets. + +

+

new Buffer(str, [encoding])#

+
    +
  • str String - string to encode.
  • +
  • encoding String - encoding to use, Optional.
  • +
+

Allocates a new buffer containing the given str. +encoding defaults to 'utf8'. + +

+

buf.write(string, [offset], [length], [encoding])#

+
    +
  • string String - data to be written to buffer
  • +
  • offset Number, Optional, Default: 0
  • +
  • length Number, Optional, Default: buffer.length - offset
  • +
  • encoding String, Optional, Default: 'utf8'
  • +
+

Writes string to the buffer at offset using the given encoding. +offset defaults to 0, encoding defaults to 'utf8'. length is +the number of bytes to write. Returns number of octets written. If buffer did +not contain enough space to fit the entire string, it will write a partial +amount of the string. length defaults to buffer.length - offset. +The method will not write partial characters. + +

+
buf = new Buffer(256);
+len = buf.write('\u00bd + \u00bc = \u00be', 0);
+console.log(len + " bytes: " + buf.toString('utf8', 0, len));
+

The number of characters written (which may be different than the number of +bytes written) is set in Buffer._charsWritten and will be overwritten the +next time buf.write() is called. + + +

+

buf.toString([encoding], [start], [end])#

+
    +
  • encoding String, Optional, Default: 'utf8'
  • +
  • start Number, Optional, Default: 0
  • +
  • end Number, Optional, Default: buffer.length
  • +
+

Decodes and returns a string from buffer data encoded with encoding +(defaults to 'utf8') beginning at start (defaults to 0) and ending at +end (defaults to buffer.length). + +

+

See buffer.write() example, above. + + +

+

buf[index]#

+ + + +

Get and set the octet at index. The values refer to individual bytes, +so the legal range is between 0x00 and 0xFF hex or 0 and 255. + +

+

Example: copy an ASCII string into a buffer, one byte at a time: + +

+
str = "node.js";
+buf = new Buffer(str.length);
+
+for (var i = 0; i < str.length ; i++) {
+  buf[i] = str.charCodeAt(i);
+}
+
+console.log(buf);
+
+// node.js
+

Class Method: Buffer.isBuffer(obj)#

+
    +
  • obj Object
  • +
  • Return: Boolean
  • +
+

Tests if obj is a Buffer. + +

+

Class Method: Buffer.byteLength(string, [encoding])#

+
    +
  • string String
  • +
  • encoding String, Optional, Default: 'utf8'
  • +
  • Return: Number
  • +
+

Gives the actual byte length of a string. encoding defaults to 'utf8'. +This is not the same as String.prototype.length since that returns the +number of characters in a string. + +

+

Example: + +

+
str = '\u00bd + \u00bc = \u00be';
+
+console.log(str + ": " + str.length + " characters, " +
+  Buffer.byteLength(str, 'utf8') + " bytes");
+
+// ½ + ¼ = ¾: 9 characters, 12 bytes
+

Class Method: Buffer.concat(list, [totalLength])#

+
    +
  • list Array List of Buffer objects to concat
  • +
  • totalLength Number Total length of the buffers when concatenated
  • +
+

Returns a buffer which is the result of concatenating all the buffers in +the list together. + +

+

If the list has no items, or if the totalLength is 0, then it returns a +zero-length buffer. + +

+

If the list has exactly one item, then the first item of the list is +returned. + +

+

If the list has more than one item, then a new Buffer is created. + +

+

If totalLength is not provided, it is read from the buffers in the list. +However, this adds an additional loop to the function, so it is faster +to provide the length explicitly. + +

+

buf.length#

+
    +
  • Number
  • +
+

The size of the buffer in bytes. Note that this is not necessarily the size +of the contents. length refers to the amount of memory allocated for the +buffer object. It does not change when the contents of the buffer are changed. + +

+
buf = new Buffer(1234);
+
+console.log(buf.length);
+buf.write("some string", 0, "ascii");
+console.log(buf.length);
+
+// 1234
+// 1234
+

buf.copy(targetBuffer, [targetStart], [sourceStart], [sourceEnd])#

+
    +
  • targetBuffer Buffer object - Buffer to copy into
  • +
  • targetStart Number, Optional, Default: 0
  • +
  • sourceStart Number, Optional, Default: 0
  • +
  • sourceEnd Number, Optional, Default: buffer.length
  • +
+

Does copy between buffers. The source and target regions can be overlapped. +targetStart and sourceStart default to 0. +sourceEnd defaults to buffer.length. + +

+

Example: build two Buffers, then copy buf1 from byte 16 through byte 19 +into buf2, starting at the 8th byte in buf2. + +

+
buf1 = new Buffer(26);
+buf2 = new Buffer(26);
+
+for (var i = 0 ; i < 26 ; i++) {
+  buf1[i] = i + 97; // 97 is ASCII a
+  buf2[i] = 33; // ASCII !
+}
+
+buf1.copy(buf2, 8, 16, 20);
+console.log(buf2.toString('ascii', 0, 25));
+
+// !!!!!!!!qrst!!!!!!!!!!!!!
+

buf.slice([start], [end])#

+
    +
  • start Number, Optional, Default: 0
  • +
  • end Number, Optional, Default: buffer.length
  • +
+

Returns a new buffer which references the same memory as the old, but offset +and cropped by the start (defaults to 0) and end (defaults to +buffer.length) indexes. + +

+

Modifying the new buffer slice will modify memory in the original buffer! + +

+

Example: build a Buffer with the ASCII alphabet, take a slice, then modify one +byte from the original Buffer. + +

+
var buf1 = new Buffer(26);
+
+for (var i = 0 ; i < 26 ; i++) {
+  buf1[i] = i + 97; // 97 is ASCII a
+}
+
+var buf2 = buf1.slice(0, 3);
+console.log(buf2.toString('ascii', 0, buf2.length));
+buf1[0] = 33;
+console.log(buf2.toString('ascii', 0, buf2.length));
+
+// abc
+// !bc
+

buf.readUInt8(offset, [noAssert])#

+
    +
  • offset Number
  • +
  • noAssert Boolean, Optional, Default: false
  • +
  • Return: Number
  • +
+

Reads an unsigned 8 bit integer from the buffer at the specified offset. + +

+

Set noAssert to true to skip validation of offset. This means that offset +may be beyond the end of the buffer. Defaults to false. + +

+

Example: + +

+
var buf = new Buffer(4);
+
+buf[0] = 0x3;
+buf[1] = 0x4;
+buf[2] = 0x23;
+buf[3] = 0x42;
+
+for (ii = 0; ii < buf.length; ii++) {
+  console.log(buf.readUInt8(ii));
+}
+
+// 0x3
+// 0x4
+// 0x23
+// 0x42
+

buf.readUInt16LE(offset, [noAssert])#

+

buf.readUInt16BE(offset, [noAssert])#

+
    +
  • offset Number
  • +
  • noAssert Boolean, Optional, Default: false
  • +
  • Return: Number
  • +
+

Reads an unsigned 16 bit integer from the buffer at the specified offset with +specified endian format. + +

+

Set noAssert to true to skip validation of offset. This means that offset +may be beyond the end of the buffer. Defaults to false. + +

+

Example: + +

+
var buf = new Buffer(4);
+
+buf[0] = 0x3;
+buf[1] = 0x4;
+buf[2] = 0x23;
+buf[3] = 0x42;
+
+console.log(buf.readUInt16BE(0));
+console.log(buf.readUInt16LE(0));
+console.log(buf.readUInt16BE(1));
+console.log(buf.readUInt16LE(1));
+console.log(buf.readUInt16BE(2));
+console.log(buf.readUInt16LE(2));
+
+// 0x0304
+// 0x0403
+// 0x0423
+// 0x2304
+// 0x2342
+// 0x4223
+

buf.readUInt32LE(offset, [noAssert])#

+

buf.readUInt32BE(offset, [noAssert])#

+
    +
  • offset Number
  • +
  • noAssert Boolean, Optional, Default: false
  • +
  • Return: Number
  • +
+

Reads an unsigned 32 bit integer from the buffer at the specified offset with +specified endian format. + +

+

Set noAssert to true to skip validation of offset. This means that offset +may be beyond the end of the buffer. Defaults to false. + +

+

Example: + +

+
var buf = new Buffer(4);
+
+buf[0] = 0x3;
+buf[1] = 0x4;
+buf[2] = 0x23;
+buf[3] = 0x42;
+
+console.log(buf.readUInt32BE(0));
+console.log(buf.readUInt32LE(0));
+
+// 0x03042342
+// 0x42230403
+

buf.readInt8(offset, [noAssert])#

+
    +
  • offset Number
  • +
  • noAssert Boolean, Optional, Default: false
  • +
  • Return: Number
  • +
+

Reads a signed 8 bit integer from the buffer at the specified offset. + +

+

Set noAssert to true to skip validation of offset. This means that offset +may be beyond the end of the buffer. Defaults to false. + +

+

Works as buffer.readUInt8, except buffer contents are treated as two's +complement signed values. + +

+

buf.readInt16LE(offset, [noAssert])#

+

buf.readInt16BE(offset, [noAssert])#

+
    +
  • offset Number
  • +
  • noAssert Boolean, Optional, Default: false
  • +
  • Return: Number
  • +
+

Reads a signed 16 bit integer from the buffer at the specified offset with +specified endian format. + +

+

Set noAssert to true to skip validation of offset. This means that offset +may be beyond the end of the buffer. Defaults to false. + +

+

Works as buffer.readUInt16*, except buffer contents are treated as two's +complement signed values. + +

+

buf.readInt32LE(offset, [noAssert])#

+

buf.readInt32BE(offset, [noAssert])#

+
    +
  • offset Number
  • +
  • noAssert Boolean, Optional, Default: false
  • +
  • Return: Number
  • +
+

Reads a signed 32 bit integer from the buffer at the specified offset with +specified endian format. + +

+

Set noAssert to true to skip validation of offset. This means that offset +may be beyond the end of the buffer. Defaults to false. + +

+

Works as buffer.readUInt32*, except buffer contents are treated as two's +complement signed values. + +

+

buf.readFloatLE(offset, [noAssert])#

+

buf.readFloatBE(offset, [noAssert])#

+
    +
  • offset Number
  • +
  • noAssert Boolean, Optional, Default: false
  • +
  • Return: Number
  • +
+

Reads a 32 bit float from the buffer at the specified offset with specified +endian format. + +

+

Set noAssert to true to skip validation of offset. This means that offset +may be beyond the end of the buffer. Defaults to false. + +

+

Example: + +

+
var buf = new Buffer(4);
+
+buf[0] = 0x00;
+buf[1] = 0x00;
+buf[2] = 0x80;
+buf[3] = 0x3f;
+
+console.log(buf.readFloatLE(0));
+
+// 0x01
+

buf.readDoubleLE(offset, [noAssert])#

+

buf.readDoubleBE(offset, [noAssert])#

+
    +
  • offset Number
  • +
  • noAssert Boolean, Optional, Default: false
  • +
  • Return: Number
  • +
+

Reads a 64 bit double from the buffer at the specified offset with specified +endian format. + +

+

Set noAssert to true to skip validation of offset. This means that offset +may be beyond the end of the buffer. Defaults to false. + +

+

Example: + +

+
var buf = new Buffer(8);
+
+buf[0] = 0x55;
+buf[1] = 0x55;
+buf[2] = 0x55;
+buf[3] = 0x55;
+buf[4] = 0x55;
+buf[5] = 0x55;
+buf[6] = 0xd5;
+buf[7] = 0x3f;
+
+console.log(buf.readDoubleLE(0));
+
+// 0.3333333333333333
+

buf.writeUInt8(value, offset, [noAssert])#

+
    +
  • value Number
  • +
  • offset Number
  • +
  • noAssert Boolean, Optional, Default: false
  • +
+

Writes value to the buffer at the specified offset. Note, value must be a +valid unsigned 8 bit integer. + +

+

Set noAssert to true to skip validation of value and offset. This means +that value may be too large for the specific function and offset may be +beyond the end of the buffer leading to the values being silently dropped. This +should not be used unless you are certain of correctness. Defaults to false. + +

+

Example: + +

+
var buf = new Buffer(4);
+buf.writeUInt8(0x3, 0);
+buf.writeUInt8(0x4, 1);
+buf.writeUInt8(0x23, 2);
+buf.writeUInt8(0x42, 3);
+
+console.log(buf);
+
+// <Buffer 03 04 23 42>
+

buf.writeUInt16LE(value, offset, [noAssert])#

+

buf.writeUInt16BE(value, offset, [noAssert])#

+
    +
  • value Number
  • +
  • offset Number
  • +
  • noAssert Boolean, Optional, Default: false
  • +
+

Writes value to the buffer at the specified offset with specified endian +format. Note, value must be a valid unsigned 16 bit integer. + +

+

Set noAssert to true to skip validation of value and offset. This means +that value may be too large for the specific function and offset may be +beyond the end of the buffer leading to the values being silently dropped. This +should not be used unless you are certain of correctness. Defaults to false. + +

+

Example: + +

+
var buf = new Buffer(4);
+buf.writeUInt16BE(0xdead, 0);
+buf.writeUInt16BE(0xbeef, 2);
+
+console.log(buf);
+
+buf.writeUInt16LE(0xdead, 0);
+buf.writeUInt16LE(0xbeef, 2);
+
+console.log(buf);
+
+// <Buffer de ad be ef>
+// <Buffer ad de ef be>
+

buf.writeUInt32LE(value, offset, [noAssert])#

+

buf.writeUInt32BE(value, offset, [noAssert])#

+
    +
  • value Number
  • +
  • offset Number
  • +
  • noAssert Boolean, Optional, Default: false
  • +
+

Writes value to the buffer at the specified offset with specified endian +format. Note, value must be a valid unsigned 32 bit integer. + +

+

Set noAssert to true to skip validation of value and offset. This means +that value may be too large for the specific function and offset may be +beyond the end of the buffer leading to the values being silently dropped. This +should not be used unless you are certain of correctness. Defaults to false. + +

+

Example: + +

+
var buf = new Buffer(4);
+buf.writeUInt32BE(0xfeedface, 0);
+
+console.log(buf);
+
+buf.writeUInt32LE(0xfeedface, 0);
+
+console.log(buf);
+
+// <Buffer fe ed fa ce>
+// <Buffer ce fa ed fe>
+

buf.writeInt8(value, offset, [noAssert])#

+
    +
  • value Number
  • +
  • offset Number
  • +
  • noAssert Boolean, Optional, Default: false
  • +
+

Writes value to the buffer at the specified offset. Note, value must be a +valid signed 8 bit integer. + +

+

Set noAssert to true to skip validation of value and offset. This means +that value may be too large for the specific function and offset may be +beyond the end of the buffer leading to the values being silently dropped. This +should not be used unless you are certain of correctness. Defaults to false. + +

+

Works as buffer.writeUInt8, except value is written out as a two's complement +signed integer into buffer. + +

+

buf.writeInt16LE(value, offset, [noAssert])#

+

buf.writeInt16BE(value, offset, [noAssert])#

+
    +
  • value Number
  • +
  • offset Number
  • +
  • noAssert Boolean, Optional, Default: false
  • +
+

Writes value to the buffer at the specified offset with specified endian +format. Note, value must be a valid signed 16 bit integer. + +

+

Set noAssert to true to skip validation of value and offset. This means +that value may be too large for the specific function and offset may be +beyond the end of the buffer leading to the values being silently dropped. This +should not be used unless you are certain of correctness. Defaults to false. + +

+

Works as buffer.writeUInt16*, except value is written out as a two's +complement signed integer into buffer. + +

+

buf.writeInt32LE(value, offset, [noAssert])#

+

buf.writeInt32BE(value, offset, [noAssert])#

+
    +
  • value Number
  • +
  • offset Number
  • +
  • noAssert Boolean, Optional, Default: false
  • +
+

Writes value to the buffer at the specified offset with specified endian +format. Note, value must be a valid signed 32 bit integer. + +

+

Set noAssert to true to skip validation of value and offset. This means +that value may be too large for the specific function and offset may be +beyond the end of the buffer leading to the values being silently dropped. This +should not be used unless you are certain of correctness. Defaults to false. + +

+

Works as buffer.writeUInt32*, except value is written out as a two's +complement signed integer into buffer. + +

+

buf.writeFloatLE(value, offset, [noAssert])#

+

buf.writeFloatBE(value, offset, [noAssert])#

+
    +
  • value Number
  • +
  • offset Number
  • +
  • noAssert Boolean, Optional, Default: false
  • +
+

Writes value to the buffer at the specified offset with specified endian +format. Note, value must be a valid 32 bit float. + +

+

Set noAssert to true to skip validation of value and offset. This means +that value may be too large for the specific function and offset may be +beyond the end of the buffer leading to the values being silently dropped. This +should not be used unless you are certain of correctness. Defaults to false. + +

+

Example: + +

+
var buf = new Buffer(4);
+buf.writeFloatBE(0xcafebabe, 0);
+
+console.log(buf);
+
+buf.writeFloatLE(0xcafebabe, 0);
+
+console.log(buf);
+
+// <Buffer 4f 4a fe bb>
+// <Buffer bb fe 4a 4f>
+

buf.writeDoubleLE(value, offset, [noAssert])#

+

buf.writeDoubleBE(value, offset, [noAssert])#

+
    +
  • value Number
  • +
  • offset Number
  • +
  • noAssert Boolean, Optional, Default: false
  • +
+

Writes value to the buffer at the specified offset with specified endian +format. Note, value must be a valid 64 bit double. + +

+

Set noAssert to true to skip validation of value and offset. This means +that value may be too large for the specific function and offset may be +beyond the end of the buffer leading to the values being silently dropped. This +should not be used unless you are certain of correctness. Defaults to false. + +

+

Example: + +

+
var buf = new Buffer(8);
+buf.writeDoubleBE(0xdeadbeefcafebabe, 0);
+
+console.log(buf);
+
+buf.writeDoubleLE(0xdeadbeefcafebabe, 0);
+
+console.log(buf);
+
+// <Buffer 43 eb d5 b7 dd f9 5f d7>
+// <Buffer d7 5f f9 dd b7 d5 eb 43>
+

buf.fill(value, [offset], [end])#

+
    +
  • value
  • +
  • offset Number, Optional
  • +
  • end Number, Optional
  • +
+

Fills the buffer with the specified value. If the offset (defaults to 0) +and end (defaults to buffer.length) are not given it will fill the entire +buffer. + +

+
var b = new Buffer(50);
+b.fill("h");
+

buffer.INSPECT_MAX_BYTES#

+
    +
  • Number, Default: 50
  • +
+

How many bytes will be returned when buffer.inspect() is called. This can +be overridden by user modules. + +

+

Note that this is a property on the buffer module returned by +require('buffer'), not on the Buffer global, or a buffer instance. + +

+

Class: SlowBuffer#

+

This class is primarily for internal use. JavaScript programs should +use Buffer instead of using SlowBuffer. + +

+

In order to avoid the overhead of allocating many C++ Buffer objects for +small blocks of memory in the lifetime of a server, Node allocates memory +in 8Kb (8192 byte) chunks. If a buffer is smaller than this size, then it +will be backed by a parent SlowBuffer object. If it is larger than this, +then Node will allocate a SlowBuffer slab for it directly. +

+ +
+
+
+ + + + + + + + + diff --git a/node-v0.8.14/doc/api/buffer.json b/node-v0.8.14/doc/api/buffer.json new file mode 100644 index 0000000..36f6e9a --- /dev/null +++ b/node-v0.8.14/doc/api/buffer.json @@ -0,0 +1,1740 @@ +{ + "source": "doc/api/buffer.markdown", + "modules": [ + { + "textRaw": "Buffer", + "name": "buffer", + "stability": 3, + "stabilityText": "Stable", + "desc": "

Pure JavaScript is Unicode friendly but not nice to binary data. When\ndealing with TCP streams or the file system, it's necessary to handle octet\nstreams. Node has several strategies for manipulating, creating, and\nconsuming octet streams.\n\n

\n

Raw data is stored in instances of the Buffer class. A Buffer is similar\nto an array of integers but corresponds to a raw memory allocation outside\nthe V8 heap. A Buffer cannot be resized.\n\n

\n

The Buffer class is a global, making it very rare that one would need\nto ever require('buffer').\n\n

\n

Converting between Buffers and JavaScript string objects requires an explicit\nencoding method. Here are the different string encodings.\n\n

\n
    \n
  • 'ascii' - for 7 bit ASCII data only. This encoding method is very fast, and\nwill strip the high bit if set.\nNote that this encoding converts a null character ('\\0' or '\\u0000') into\n0x20 (character code of a space). If you want to convert a null character\ninto 0x00, you should use 'utf8'.

    \n
  • \n
  • 'utf8' - Multibyte encoded Unicode characters. Many web pages and other\ndocument formats use UTF-8.

    \n
  • \n
  • 'utf16le' - 2 or 4 bytes, little endian encoded Unicode characters.\nSurrogate pairs (U+10000 to U+10FFFF) are supported.

    \n
  • \n
  • 'ucs2' - Alias of 'utf16le'.

    \n
  • \n
  • 'base64' - Base64 string encoding.

    \n
  • \n
  • 'binary' - A way of encoding raw binary data into strings by using only\nthe first 8 bits of each character. This encoding method is deprecated and\nshould be avoided in favor of Buffer objects where possible. This encoding\nwill be removed in future versions of Node.

    \n
  • \n
  • 'hex' - Encode each byte as two hexadecimal characters.

    \n
  • \n
\n", + "classes": [ + { + "textRaw": "Class: Buffer", + "type": "class", + "name": "Buffer", + "desc": "

The Buffer class is a global type for dealing with binary data directly.\nIt can be constructed in a variety of ways.\n\n

\n", + "methods": [ + { + "textRaw": "buf.write(string, [offset], [length], [encoding])", + "type": "method", + "name": "write", + "signatures": [ + { + "params": [ + { + "textRaw": "`string` String - data to be written to buffer ", + "name": "string", + "desc": "String - data to be written to buffer" + }, + { + "textRaw": "`offset` Number, Optional, Default: 0 ", + "name": "offset", + "desc": "Number, Optional, Default: 0", + "optional": true + }, + { + "textRaw": "`length` Number, Optional, Default: `buffer.length - offset` ", + "name": "length", + "desc": "Number, Optional, Default: `buffer.length - offset`", + "optional": true + }, + { + "textRaw": "`encoding` String, Optional, Default: 'utf8' ", + "name": "encoding", + "desc": "String, Optional, Default: 'utf8'", + "optional": true + } + ] + }, + { + "params": [ + { + "name": "string" + }, + { + "name": "offset", + "optional": true + }, + { + "name": "length", + "optional": true + }, + { + "name": "encoding", + "optional": true + } + ] + } + ], + "desc": "

Writes string to the buffer at offset using the given encoding.\noffset defaults to 0, encoding defaults to 'utf8'. length is\nthe number of bytes to write. Returns number of octets written. If buffer did\nnot contain enough space to fit the entire string, it will write a partial\namount of the string. length defaults to buffer.length - offset.\nThe method will not write partial characters.\n\n

\n
buf = new Buffer(256);\nlen = buf.write('\\u00bd + \\u00bc = \\u00be', 0);\nconsole.log(len + " bytes: " + buf.toString('utf8', 0, len));
\n

The number of characters written (which may be different than the number of\nbytes written) is set in Buffer._charsWritten and will be overwritten the\nnext time buf.write() is called.\n\n\n

\n" + }, + { + "textRaw": "buf.toString([encoding], [start], [end])", + "type": "method", + "name": "toString", + "signatures": [ + { + "params": [ + { + "textRaw": "`encoding` String, Optional, Default: 'utf8' ", + "name": "encoding", + "desc": "String, Optional, Default: 'utf8'", + "optional": true + }, + { + "textRaw": "`start` Number, Optional, Default: 0 ", + "name": "start", + "desc": "Number, Optional, Default: 0", + "optional": true + }, + { + "textRaw": "`end` Number, Optional, Default: `buffer.length` ", + "name": "end", + "desc": "Number, Optional, Default: `buffer.length`", + "optional": true + } + ] + }, + { + "params": [ + { + "name": "encoding", + "optional": true + }, + { + "name": "start", + "optional": true + }, + { + "name": "end", + "optional": true + } + ] + } + ], + "desc": "

Decodes and returns a string from buffer data encoded with encoding\n(defaults to 'utf8') beginning at start (defaults to 0) and ending at\nend (defaults to buffer.length).\n\n

\n

See buffer.write() example, above.\n\n\n

\n" + }, + { + "textRaw": "buf.copy(targetBuffer, [targetStart], [sourceStart], [sourceEnd])", + "type": "method", + "name": "copy", + "signatures": [ + { + "params": [ + { + "textRaw": "`targetBuffer` Buffer object - Buffer to copy into ", + "name": "targetBuffer", + "desc": "Buffer object - Buffer to copy into" + }, + { + "textRaw": "`targetStart` Number, Optional, Default: 0 ", + "name": "targetStart", + "desc": "Number, Optional, Default: 0", + "optional": true + }, + { + "textRaw": "`sourceStart` Number, Optional, Default: 0 ", + "name": "sourceStart", + "desc": "Number, Optional, Default: 0", + "optional": true + }, + { + "textRaw": "`sourceEnd` Number, Optional, Default: `buffer.length` ", + "name": "sourceEnd", + "desc": "Number, Optional, Default: `buffer.length`", + "optional": true + } + ] + }, + { + "params": [ + { + "name": "targetBuffer" + }, + { + "name": "targetStart", + "optional": true + }, + { + "name": "sourceStart", + "optional": true + }, + { + "name": "sourceEnd", + "optional": true + } + ] + } + ], + "desc": "

Does copy between buffers. The source and target regions can be overlapped.\ntargetStart and sourceStart default to 0.\nsourceEnd defaults to buffer.length.\n\n

\n

Example: build two Buffers, then copy buf1 from byte 16 through byte 19\ninto buf2, starting at the 8th byte in buf2.\n\n

\n
buf1 = new Buffer(26);\nbuf2 = new Buffer(26);\n\nfor (var i = 0 ; i < 26 ; i++) {\n  buf1[i] = i + 97; // 97 is ASCII a\n  buf2[i] = 33; // ASCII !\n}\n\nbuf1.copy(buf2, 8, 16, 20);\nconsole.log(buf2.toString('ascii', 0, 25));\n\n// !!!!!!!!qrst!!!!!!!!!!!!!
\n" + }, + { + "textRaw": "buf.slice([start], [end])", + "type": "method", + "name": "slice", + "signatures": [ + { + "params": [ + { + "textRaw": "`start` Number, Optional, Default: 0 ", + "name": "start", + "desc": "Number, Optional, Default: 0", + "optional": true + }, + { + "textRaw": "`end` Number, Optional, Default: `buffer.length` ", + "name": "end", + "desc": "Number, Optional, Default: `buffer.length`", + "optional": true + } + ] + }, + { + "params": [ + { + "name": "start", + "optional": true + }, + { + "name": "end", + "optional": true + } + ] + } + ], + "desc": "

Returns a new buffer which references the same memory as the old, but offset\nand cropped by the start (defaults to 0) and end (defaults to\nbuffer.length) indexes.\n\n

\n

Modifying the new buffer slice will modify memory in the original buffer!\n\n

\n

Example: build a Buffer with the ASCII alphabet, take a slice, then modify one\nbyte from the original Buffer.\n\n

\n
var buf1 = new Buffer(26);\n\nfor (var i = 0 ; i < 26 ; i++) {\n  buf1[i] = i + 97; // 97 is ASCII a\n}\n\nvar buf2 = buf1.slice(0, 3);\nconsole.log(buf2.toString('ascii', 0, buf2.length));\nbuf1[0] = 33;\nconsole.log(buf2.toString('ascii', 0, buf2.length));\n\n// abc\n// !bc
\n" + }, + { + "textRaw": "buf.readUInt8(offset, [noAssert])", + "type": "method", + "name": "readUInt8", + "signatures": [ + { + "return": { + "textRaw": "Return: Number ", + "name": "return", + "desc": "Number" + }, + "params": [ + { + "textRaw": "`offset` Number ", + "name": "offset", + "desc": "Number" + }, + { + "textRaw": "`noAssert` Boolean, Optional, Default: false ", + "name": "noAssert", + "desc": "Boolean, Optional, Default: false", + "optional": true + } + ] + }, + { + "params": [ + { + "name": "offset" + }, + { + "name": "noAssert", + "optional": true + } + ] + } + ], + "desc": "

Reads an unsigned 8 bit integer from the buffer at the specified offset.\n\n

\n

Set noAssert to true to skip validation of offset. This means that offset\nmay be beyond the end of the buffer. Defaults to false.\n\n

\n

Example:\n\n

\n
var buf = new Buffer(4);\n\nbuf[0] = 0x3;\nbuf[1] = 0x4;\nbuf[2] = 0x23;\nbuf[3] = 0x42;\n\nfor (ii = 0; ii < buf.length; ii++) {\n  console.log(buf.readUInt8(ii));\n}\n\n// 0x3\n// 0x4\n// 0x23\n// 0x42
\n" + }, + { + "textRaw": "buf.readUInt16LE(offset, [noAssert])", + "type": "method", + "name": "readUInt16LE", + "signatures": [ + { + "return": { + "textRaw": "Return: Number ", + "name": "return", + "desc": "Number" + }, + "params": [ + { + "textRaw": "`offset` Number ", + "name": "offset", + "desc": "Number" + }, + { + "textRaw": "`noAssert` Boolean, Optional, Default: false ", + "name": "noAssert", + "desc": "Boolean, Optional, Default: false", + "optional": true + } + ] + }, + { + "params": [ + { + "name": "offset" + }, + { + "name": "noAssert", + "optional": true + } + ] + }, + { + "params": [ + { + "name": "offset" + }, + { + "name": "noAssert", + "optional": true + } + ] + } + ], + "desc": "

Reads an unsigned 16 bit integer from the buffer at the specified offset with\nspecified endian format.\n\n

\n

Set noAssert to true to skip validation of offset. This means that offset\nmay be beyond the end of the buffer. Defaults to false.\n\n

\n

Example:\n\n

\n
var buf = new Buffer(4);\n\nbuf[0] = 0x3;\nbuf[1] = 0x4;\nbuf[2] = 0x23;\nbuf[3] = 0x42;\n\nconsole.log(buf.readUInt16BE(0));\nconsole.log(buf.readUInt16LE(0));\nconsole.log(buf.readUInt16BE(1));\nconsole.log(buf.readUInt16LE(1));\nconsole.log(buf.readUInt16BE(2));\nconsole.log(buf.readUInt16LE(2));\n\n// 0x0304\n// 0x0403\n// 0x0423\n// 0x2304\n// 0x2342\n// 0x4223
\n" + }, + { + "textRaw": "buf.readUInt16BE(offset, [noAssert])", + "type": "method", + "name": "readUInt16BE", + "signatures": [ + { + "return": { + "textRaw": "Return: Number ", + "name": "return", + "desc": "Number" + }, + "params": [ + { + "textRaw": "`offset` Number ", + "name": "offset", + "desc": "Number" + }, + { + "textRaw": "`noAssert` Boolean, Optional, Default: false ", + "name": "noAssert", + "desc": "Boolean, Optional, Default: false", + "optional": true + } + ] + }, + { + "params": [ + { + "name": "offset" + }, + { + "name": "noAssert", + "optional": true + } + ] + } + ], + "desc": "

Reads an unsigned 16 bit integer from the buffer at the specified offset with\nspecified endian format.\n\n

\n

Set noAssert to true to skip validation of offset. This means that offset\nmay be beyond the end of the buffer. Defaults to false.\n\n

\n

Example:\n\n

\n
var buf = new Buffer(4);\n\nbuf[0] = 0x3;\nbuf[1] = 0x4;\nbuf[2] = 0x23;\nbuf[3] = 0x42;\n\nconsole.log(buf.readUInt16BE(0));\nconsole.log(buf.readUInt16LE(0));\nconsole.log(buf.readUInt16BE(1));\nconsole.log(buf.readUInt16LE(1));\nconsole.log(buf.readUInt16BE(2));\nconsole.log(buf.readUInt16LE(2));\n\n// 0x0304\n// 0x0403\n// 0x0423\n// 0x2304\n// 0x2342\n// 0x4223
\n" + }, + { + "textRaw": "buf.readUInt32LE(offset, [noAssert])", + "type": "method", + "name": "readUInt32LE", + "signatures": [ + { + "return": { + "textRaw": "Return: Number ", + "name": "return", + "desc": "Number" + }, + "params": [ + { + "textRaw": "`offset` Number ", + "name": "offset", + "desc": "Number" + }, + { + "textRaw": "`noAssert` Boolean, Optional, Default: false ", + "name": "noAssert", + "desc": "Boolean, Optional, Default: false", + "optional": true + } + ] + }, + { + "params": [ + { + "name": "offset" + }, + { + "name": "noAssert", + "optional": true + } + ] + }, + { + "params": [ + { + "name": "offset" + }, + { + "name": "noAssert", + "optional": true + } + ] + } + ], + "desc": "

Reads an unsigned 32 bit integer from the buffer at the specified offset with\nspecified endian format.\n\n

\n

Set noAssert to true to skip validation of offset. This means that offset\nmay be beyond the end of the buffer. Defaults to false.\n\n

\n

Example:\n\n

\n
var buf = new Buffer(4);\n\nbuf[0] = 0x3;\nbuf[1] = 0x4;\nbuf[2] = 0x23;\nbuf[3] = 0x42;\n\nconsole.log(buf.readUInt32BE(0));\nconsole.log(buf.readUInt32LE(0));\n\n// 0x03042342\n// 0x42230403
\n" + }, + { + "textRaw": "buf.readUInt32BE(offset, [noAssert])", + "type": "method", + "name": "readUInt32BE", + "signatures": [ + { + "return": { + "textRaw": "Return: Number ", + "name": "return", + "desc": "Number" + }, + "params": [ + { + "textRaw": "`offset` Number ", + "name": "offset", + "desc": "Number" + }, + { + "textRaw": "`noAssert` Boolean, Optional, Default: false ", + "name": "noAssert", + "desc": "Boolean, Optional, Default: false", + "optional": true + } + ] + }, + { + "params": [ + { + "name": "offset" + }, + { + "name": "noAssert", + "optional": true + } + ] + } + ], + "desc": "

Reads an unsigned 32 bit integer from the buffer at the specified offset with\nspecified endian format.\n\n

\n

Set noAssert to true to skip validation of offset. This means that offset\nmay be beyond the end of the buffer. Defaults to false.\n\n

\n

Example:\n\n

\n
var buf = new Buffer(4);\n\nbuf[0] = 0x3;\nbuf[1] = 0x4;\nbuf[2] = 0x23;\nbuf[3] = 0x42;\n\nconsole.log(buf.readUInt32BE(0));\nconsole.log(buf.readUInt32LE(0));\n\n// 0x03042342\n// 0x42230403
\n" + }, + { + "textRaw": "buf.readInt8(offset, [noAssert])", + "type": "method", + "name": "readInt8", + "signatures": [ + { + "return": { + "textRaw": "Return: Number ", + "name": "return", + "desc": "Number" + }, + "params": [ + { + "textRaw": "`offset` Number ", + "name": "offset", + "desc": "Number" + }, + { + "textRaw": "`noAssert` Boolean, Optional, Default: false ", + "name": "noAssert", + "desc": "Boolean, Optional, Default: false", + "optional": true + } + ] + }, + { + "params": [ + { + "name": "offset" + }, + { + "name": "noAssert", + "optional": true + } + ] + } + ], + "desc": "

Reads a signed 8 bit integer from the buffer at the specified offset.\n\n

\n

Set noAssert to true to skip validation of offset. This means that offset\nmay be beyond the end of the buffer. Defaults to false.\n\n

\n

Works as buffer.readUInt8, except buffer contents are treated as two's\ncomplement signed values.\n\n

\n" + }, + { + "textRaw": "buf.readInt16LE(offset, [noAssert])", + "type": "method", + "name": "readInt16LE", + "signatures": [ + { + "return": { + "textRaw": "Return: Number ", + "name": "return", + "desc": "Number" + }, + "params": [ + { + "textRaw": "`offset` Number ", + "name": "offset", + "desc": "Number" + }, + { + "textRaw": "`noAssert` Boolean, Optional, Default: false ", + "name": "noAssert", + "desc": "Boolean, Optional, Default: false", + "optional": true + } + ] + }, + { + "params": [ + { + "name": "offset" + }, + { + "name": "noAssert", + "optional": true + } + ] + }, + { + "params": [ + { + "name": "offset" + }, + { + "name": "noAssert", + "optional": true + } + ] + } + ], + "desc": "

Reads a signed 16 bit integer from the buffer at the specified offset with\nspecified endian format.\n\n

\n

Set noAssert to true to skip validation of offset. This means that offset\nmay be beyond the end of the buffer. Defaults to false.\n\n

\n

Works as buffer.readUInt16*, except buffer contents are treated as two's\ncomplement signed values.\n\n

\n" + }, + { + "textRaw": "buf.readInt16BE(offset, [noAssert])", + "type": "method", + "name": "readInt16BE", + "signatures": [ + { + "return": { + "textRaw": "Return: Number ", + "name": "return", + "desc": "Number" + }, + "params": [ + { + "textRaw": "`offset` Number ", + "name": "offset", + "desc": "Number" + }, + { + "textRaw": "`noAssert` Boolean, Optional, Default: false ", + "name": "noAssert", + "desc": "Boolean, Optional, Default: false", + "optional": true + } + ] + }, + { + "params": [ + { + "name": "offset" + }, + { + "name": "noAssert", + "optional": true + } + ] + } + ], + "desc": "

Reads a signed 16 bit integer from the buffer at the specified offset with\nspecified endian format.\n\n

\n

Set noAssert to true to skip validation of offset. This means that offset\nmay be beyond the end of the buffer. Defaults to false.\n\n

\n

Works as buffer.readUInt16*, except buffer contents are treated as two's\ncomplement signed values.\n\n

\n" + }, + { + "textRaw": "buf.readInt32LE(offset, [noAssert])", + "type": "method", + "name": "readInt32LE", + "signatures": [ + { + "return": { + "textRaw": "Return: Number ", + "name": "return", + "desc": "Number" + }, + "params": [ + { + "textRaw": "`offset` Number ", + "name": "offset", + "desc": "Number" + }, + { + "textRaw": "`noAssert` Boolean, Optional, Default: false ", + "name": "noAssert", + "desc": "Boolean, Optional, Default: false", + "optional": true + } + ] + }, + { + "params": [ + { + "name": "offset" + }, + { + "name": "noAssert", + "optional": true + } + ] + }, + { + "params": [ + { + "name": "offset" + }, + { + "name": "noAssert", + "optional": true + } + ] + } + ], + "desc": "

Reads a signed 32 bit integer from the buffer at the specified offset with\nspecified endian format.\n\n

\n

Set noAssert to true to skip validation of offset. This means that offset\nmay be beyond the end of the buffer. Defaults to false.\n\n

\n

Works as buffer.readUInt32*, except buffer contents are treated as two's\ncomplement signed values.\n\n

\n" + }, + { + "textRaw": "buf.readInt32BE(offset, [noAssert])", + "type": "method", + "name": "readInt32BE", + "signatures": [ + { + "return": { + "textRaw": "Return: Number ", + "name": "return", + "desc": "Number" + }, + "params": [ + { + "textRaw": "`offset` Number ", + "name": "offset", + "desc": "Number" + }, + { + "textRaw": "`noAssert` Boolean, Optional, Default: false ", + "name": "noAssert", + "desc": "Boolean, Optional, Default: false", + "optional": true + } + ] + }, + { + "params": [ + { + "name": "offset" + }, + { + "name": "noAssert", + "optional": true + } + ] + } + ], + "desc": "

Reads a signed 32 bit integer from the buffer at the specified offset with\nspecified endian format.\n\n

\n

Set noAssert to true to skip validation of offset. This means that offset\nmay be beyond the end of the buffer. Defaults to false.\n\n

\n

Works as buffer.readUInt32*, except buffer contents are treated as two's\ncomplement signed values.\n\n

\n" + }, + { + "textRaw": "buf.readFloatLE(offset, [noAssert])", + "type": "method", + "name": "readFloatLE", + "signatures": [ + { + "return": { + "textRaw": "Return: Number ", + "name": "return", + "desc": "Number" + }, + "params": [ + { + "textRaw": "`offset` Number ", + "name": "offset", + "desc": "Number" + }, + { + "textRaw": "`noAssert` Boolean, Optional, Default: false ", + "name": "noAssert", + "desc": "Boolean, Optional, Default: false", + "optional": true + } + ] + }, + { + "params": [ + { + "name": "offset" + }, + { + "name": "noAssert", + "optional": true + } + ] + }, + { + "params": [ + { + "name": "offset" + }, + { + "name": "noAssert", + "optional": true + } + ] + } + ], + "desc": "

Reads a 32 bit float from the buffer at the specified offset with specified\nendian format.\n\n

\n

Set noAssert to true to skip validation of offset. This means that offset\nmay be beyond the end of the buffer. Defaults to false.\n\n

\n

Example:\n\n

\n
var buf = new Buffer(4);\n\nbuf[0] = 0x00;\nbuf[1] = 0x00;\nbuf[2] = 0x80;\nbuf[3] = 0x3f;\n\nconsole.log(buf.readFloatLE(0));\n\n// 0x01
\n" + }, + { + "textRaw": "buf.readFloatBE(offset, [noAssert])", + "type": "method", + "name": "readFloatBE", + "signatures": [ + { + "return": { + "textRaw": "Return: Number ", + "name": "return", + "desc": "Number" + }, + "params": [ + { + "textRaw": "`offset` Number ", + "name": "offset", + "desc": "Number" + }, + { + "textRaw": "`noAssert` Boolean, Optional, Default: false ", + "name": "noAssert", + "desc": "Boolean, Optional, Default: false", + "optional": true + } + ] + }, + { + "params": [ + { + "name": "offset" + }, + { + "name": "noAssert", + "optional": true + } + ] + } + ], + "desc": "

Reads a 32 bit float from the buffer at the specified offset with specified\nendian format.\n\n

\n

Set noAssert to true to skip validation of offset. This means that offset\nmay be beyond the end of the buffer. Defaults to false.\n\n

\n

Example:\n\n

\n
var buf = new Buffer(4);\n\nbuf[0] = 0x00;\nbuf[1] = 0x00;\nbuf[2] = 0x80;\nbuf[3] = 0x3f;\n\nconsole.log(buf.readFloatLE(0));\n\n// 0x01
\n" + }, + { + "textRaw": "buf.readDoubleLE(offset, [noAssert])", + "type": "method", + "name": "readDoubleLE", + "signatures": [ + { + "return": { + "textRaw": "Return: Number ", + "name": "return", + "desc": "Number" + }, + "params": [ + { + "textRaw": "`offset` Number ", + "name": "offset", + "desc": "Number" + }, + { + "textRaw": "`noAssert` Boolean, Optional, Default: false ", + "name": "noAssert", + "desc": "Boolean, Optional, Default: false", + "optional": true + } + ] + }, + { + "params": [ + { + "name": "offset" + }, + { + "name": "noAssert", + "optional": true + } + ] + }, + { + "params": [ + { + "name": "offset" + }, + { + "name": "noAssert", + "optional": true + } + ] + } + ], + "desc": "

Reads a 64 bit double from the buffer at the specified offset with specified\nendian format.\n\n

\n

Set noAssert to true to skip validation of offset. This means that offset\nmay be beyond the end of the buffer. Defaults to false.\n\n

\n

Example:\n\n

\n
var buf = new Buffer(8);\n\nbuf[0] = 0x55;\nbuf[1] = 0x55;\nbuf[2] = 0x55;\nbuf[3] = 0x55;\nbuf[4] = 0x55;\nbuf[5] = 0x55;\nbuf[6] = 0xd5;\nbuf[7] = 0x3f;\n\nconsole.log(buf.readDoubleLE(0));\n\n// 0.3333333333333333
\n" + }, + { + "textRaw": "buf.readDoubleBE(offset, [noAssert])", + "type": "method", + "name": "readDoubleBE", + "signatures": [ + { + "return": { + "textRaw": "Return: Number ", + "name": "return", + "desc": "Number" + }, + "params": [ + { + "textRaw": "`offset` Number ", + "name": "offset", + "desc": "Number" + }, + { + "textRaw": "`noAssert` Boolean, Optional, Default: false ", + "name": "noAssert", + "desc": "Boolean, Optional, Default: false", + "optional": true + } + ] + }, + { + "params": [ + { + "name": "offset" + }, + { + "name": "noAssert", + "optional": true + } + ] + } + ], + "desc": "

Reads a 64 bit double from the buffer at the specified offset with specified\nendian format.\n\n

\n

Set noAssert to true to skip validation of offset. This means that offset\nmay be beyond the end of the buffer. Defaults to false.\n\n

\n

Example:\n\n

\n
var buf = new Buffer(8);\n\nbuf[0] = 0x55;\nbuf[1] = 0x55;\nbuf[2] = 0x55;\nbuf[3] = 0x55;\nbuf[4] = 0x55;\nbuf[5] = 0x55;\nbuf[6] = 0xd5;\nbuf[7] = 0x3f;\n\nconsole.log(buf.readDoubleLE(0));\n\n// 0.3333333333333333
\n" + }, + { + "textRaw": "buf.writeUInt8(value, offset, [noAssert])", + "type": "method", + "name": "writeUInt8", + "signatures": [ + { + "params": [ + { + "textRaw": "`value` Number ", + "name": "value", + "desc": "Number" + }, + { + "textRaw": "`offset` Number ", + "name": "offset", + "desc": "Number" + }, + { + "textRaw": "`noAssert` Boolean, Optional, Default: false ", + "name": "noAssert", + "desc": "Boolean, Optional, Default: false", + "optional": true + } + ] + }, + { + "params": [ + { + "name": "value" + }, + { + "name": "offset" + }, + { + "name": "noAssert", + "optional": true + } + ] + } + ], + "desc": "

Writes value to the buffer at the specified offset. Note, value must be a\nvalid unsigned 8 bit integer.\n\n

\n

Set noAssert to true to skip validation of value and offset. This means\nthat value may be too large for the specific function and offset may be\nbeyond the end of the buffer leading to the values being silently dropped. This\nshould not be used unless you are certain of correctness. Defaults to false.\n\n

\n

Example:\n\n

\n
var buf = new Buffer(4);\nbuf.writeUInt8(0x3, 0);\nbuf.writeUInt8(0x4, 1);\nbuf.writeUInt8(0x23, 2);\nbuf.writeUInt8(0x42, 3);\n\nconsole.log(buf);\n\n// <Buffer 03 04 23 42>
\n" + }, + { + "textRaw": "buf.writeUInt16LE(value, offset, [noAssert])", + "type": "method", + "name": "writeUInt16LE", + "signatures": [ + { + "params": [ + { + "textRaw": "`value` Number ", + "name": "value", + "desc": "Number" + }, + { + "textRaw": "`offset` Number ", + "name": "offset", + "desc": "Number" + }, + { + "textRaw": "`noAssert` Boolean, Optional, Default: false ", + "name": "noAssert", + "desc": "Boolean, Optional, Default: false", + "optional": true + } + ] + }, + { + "params": [ + { + "name": "value" + }, + { + "name": "offset" + }, + { + "name": "noAssert", + "optional": true + } + ] + }, + { + "params": [ + { + "name": "value" + }, + { + "name": "offset" + }, + { + "name": "noAssert", + "optional": true + } + ] + } + ], + "desc": "

Writes value to the buffer at the specified offset with specified endian\nformat. Note, value must be a valid unsigned 16 bit integer.\n\n

\n

Set noAssert to true to skip validation of value and offset. This means\nthat value may be too large for the specific function and offset may be\nbeyond the end of the buffer leading to the values being silently dropped. This\nshould not be used unless you are certain of correctness. Defaults to false.\n\n

\n

Example:\n\n

\n
var buf = new Buffer(4);\nbuf.writeUInt16BE(0xdead, 0);\nbuf.writeUInt16BE(0xbeef, 2);\n\nconsole.log(buf);\n\nbuf.writeUInt16LE(0xdead, 0);\nbuf.writeUInt16LE(0xbeef, 2);\n\nconsole.log(buf);\n\n// <Buffer de ad be ef>\n// <Buffer ad de ef be>
\n" + }, + { + "textRaw": "buf.writeUInt16BE(value, offset, [noAssert])", + "type": "method", + "name": "writeUInt16BE", + "signatures": [ + { + "params": [ + { + "textRaw": "`value` Number ", + "name": "value", + "desc": "Number" + }, + { + "textRaw": "`offset` Number ", + "name": "offset", + "desc": "Number" + }, + { + "textRaw": "`noAssert` Boolean, Optional, Default: false ", + "name": "noAssert", + "desc": "Boolean, Optional, Default: false", + "optional": true + } + ] + }, + { + "params": [ + { + "name": "value" + }, + { + "name": "offset" + }, + { + "name": "noAssert", + "optional": true + } + ] + } + ], + "desc": "

Writes value to the buffer at the specified offset with specified endian\nformat. Note, value must be a valid unsigned 16 bit integer.\n\n

\n

Set noAssert to true to skip validation of value and offset. This means\nthat value may be too large for the specific function and offset may be\nbeyond the end of the buffer leading to the values being silently dropped. This\nshould not be used unless you are certain of correctness. Defaults to false.\n\n

\n

Example:\n\n

\n
var buf = new Buffer(4);\nbuf.writeUInt16BE(0xdead, 0);\nbuf.writeUInt16BE(0xbeef, 2);\n\nconsole.log(buf);\n\nbuf.writeUInt16LE(0xdead, 0);\nbuf.writeUInt16LE(0xbeef, 2);\n\nconsole.log(buf);\n\n// <Buffer de ad be ef>\n// <Buffer ad de ef be>
\n" + }, + { + "textRaw": "buf.writeUInt32LE(value, offset, [noAssert])", + "type": "method", + "name": "writeUInt32LE", + "signatures": [ + { + "params": [ + { + "textRaw": "`value` Number ", + "name": "value", + "desc": "Number" + }, + { + "textRaw": "`offset` Number ", + "name": "offset", + "desc": "Number" + }, + { + "textRaw": "`noAssert` Boolean, Optional, Default: false ", + "name": "noAssert", + "desc": "Boolean, Optional, Default: false", + "optional": true + } + ] + }, + { + "params": [ + { + "name": "value" + }, + { + "name": "offset" + }, + { + "name": "noAssert", + "optional": true + } + ] + }, + { + "params": [ + { + "name": "value" + }, + { + "name": "offset" + }, + { + "name": "noAssert", + "optional": true + } + ] + } + ], + "desc": "

Writes value to the buffer at the specified offset with specified endian\nformat. Note, value must be a valid unsigned 32 bit integer.\n\n

\n

Set noAssert to true to skip validation of value and offset. This means\nthat value may be too large for the specific function and offset may be\nbeyond the end of the buffer leading to the values being silently dropped. This\nshould not be used unless you are certain of correctness. Defaults to false.\n\n

\n

Example:\n\n

\n
var buf = new Buffer(4);\nbuf.writeUInt32BE(0xfeedface, 0);\n\nconsole.log(buf);\n\nbuf.writeUInt32LE(0xfeedface, 0);\n\nconsole.log(buf);\n\n// <Buffer fe ed fa ce>\n// <Buffer ce fa ed fe>
\n" + }, + { + "textRaw": "buf.writeUInt32BE(value, offset, [noAssert])", + "type": "method", + "name": "writeUInt32BE", + "signatures": [ + { + "params": [ + { + "textRaw": "`value` Number ", + "name": "value", + "desc": "Number" + }, + { + "textRaw": "`offset` Number ", + "name": "offset", + "desc": "Number" + }, + { + "textRaw": "`noAssert` Boolean, Optional, Default: false ", + "name": "noAssert", + "desc": "Boolean, Optional, Default: false", + "optional": true + } + ] + }, + { + "params": [ + { + "name": "value" + }, + { + "name": "offset" + }, + { + "name": "noAssert", + "optional": true + } + ] + } + ], + "desc": "

Writes value to the buffer at the specified offset with specified endian\nformat. Note, value must be a valid unsigned 32 bit integer.\n\n

\n

Set noAssert to true to skip validation of value and offset. This means\nthat value may be too large for the specific function and offset may be\nbeyond the end of the buffer leading to the values being silently dropped. This\nshould not be used unless you are certain of correctness. Defaults to false.\n\n

\n

Example:\n\n

\n
var buf = new Buffer(4);\nbuf.writeUInt32BE(0xfeedface, 0);\n\nconsole.log(buf);\n\nbuf.writeUInt32LE(0xfeedface, 0);\n\nconsole.log(buf);\n\n// <Buffer fe ed fa ce>\n// <Buffer ce fa ed fe>
\n" + }, + { + "textRaw": "buf.writeInt8(value, offset, [noAssert])", + "type": "method", + "name": "writeInt8", + "signatures": [ + { + "params": [ + { + "textRaw": "`value` Number ", + "name": "value", + "desc": "Number" + }, + { + "textRaw": "`offset` Number ", + "name": "offset", + "desc": "Number" + }, + { + "textRaw": "`noAssert` Boolean, Optional, Default: false ", + "name": "noAssert", + "desc": "Boolean, Optional, Default: false", + "optional": true + } + ] + }, + { + "params": [ + { + "name": "value" + }, + { + "name": "offset" + }, + { + "name": "noAssert", + "optional": true + } + ] + } + ], + "desc": "

Writes value to the buffer at the specified offset. Note, value must be a\nvalid signed 8 bit integer.\n\n

\n

Set noAssert to true to skip validation of value and offset. This means\nthat value may be too large for the specific function and offset may be\nbeyond the end of the buffer leading to the values being silently dropped. This\nshould not be used unless you are certain of correctness. Defaults to false.\n\n

\n

Works as buffer.writeUInt8, except value is written out as a two's complement\nsigned integer into buffer.\n\n

\n" + }, + { + "textRaw": "buf.writeInt16LE(value, offset, [noAssert])", + "type": "method", + "name": "writeInt16LE", + "signatures": [ + { + "params": [ + { + "textRaw": "`value` Number ", + "name": "value", + "desc": "Number" + }, + { + "textRaw": "`offset` Number ", + "name": "offset", + "desc": "Number" + }, + { + "textRaw": "`noAssert` Boolean, Optional, Default: false ", + "name": "noAssert", + "desc": "Boolean, Optional, Default: false", + "optional": true + } + ] + }, + { + "params": [ + { + "name": "value" + }, + { + "name": "offset" + }, + { + "name": "noAssert", + "optional": true + } + ] + }, + { + "params": [ + { + "name": "value" + }, + { + "name": "offset" + }, + { + "name": "noAssert", + "optional": true + } + ] + } + ], + "desc": "

Writes value to the buffer at the specified offset with specified endian\nformat. Note, value must be a valid signed 16 bit integer.\n\n

\n

Set noAssert to true to skip validation of value and offset. This means\nthat value may be too large for the specific function and offset may be\nbeyond the end of the buffer leading to the values being silently dropped. This\nshould not be used unless you are certain of correctness. Defaults to false.\n\n

\n

Works as buffer.writeUInt16*, except value is written out as a two's\ncomplement signed integer into buffer.\n\n

\n" + }, + { + "textRaw": "buf.writeInt16BE(value, offset, [noAssert])", + "type": "method", + "name": "writeInt16BE", + "signatures": [ + { + "params": [ + { + "textRaw": "`value` Number ", + "name": "value", + "desc": "Number" + }, + { + "textRaw": "`offset` Number ", + "name": "offset", + "desc": "Number" + }, + { + "textRaw": "`noAssert` Boolean, Optional, Default: false ", + "name": "noAssert", + "desc": "Boolean, Optional, Default: false", + "optional": true + } + ] + }, + { + "params": [ + { + "name": "value" + }, + { + "name": "offset" + }, + { + "name": "noAssert", + "optional": true + } + ] + } + ], + "desc": "

Writes value to the buffer at the specified offset with specified endian\nformat. Note, value must be a valid signed 16 bit integer.\n\n

\n

Set noAssert to true to skip validation of value and offset. This means\nthat value may be too large for the specific function and offset may be\nbeyond the end of the buffer leading to the values being silently dropped. This\nshould not be used unless you are certain of correctness. Defaults to false.\n\n

\n

Works as buffer.writeUInt16*, except value is written out as a two's\ncomplement signed integer into buffer.\n\n

\n" + }, + { + "textRaw": "buf.writeInt32LE(value, offset, [noAssert])", + "type": "method", + "name": "writeInt32LE", + "signatures": [ + { + "params": [ + { + "textRaw": "`value` Number ", + "name": "value", + "desc": "Number" + }, + { + "textRaw": "`offset` Number ", + "name": "offset", + "desc": "Number" + }, + { + "textRaw": "`noAssert` Boolean, Optional, Default: false ", + "name": "noAssert", + "desc": "Boolean, Optional, Default: false", + "optional": true + } + ] + }, + { + "params": [ + { + "name": "value" + }, + { + "name": "offset" + }, + { + "name": "noAssert", + "optional": true + } + ] + }, + { + "params": [ + { + "name": "value" + }, + { + "name": "offset" + }, + { + "name": "noAssert", + "optional": true + } + ] + } + ], + "desc": "

Writes value to the buffer at the specified offset with specified endian\nformat. Note, value must be a valid signed 32 bit integer.\n\n

\n

Set noAssert to true to skip validation of value and offset. This means\nthat value may be too large for the specific function and offset may be\nbeyond the end of the buffer leading to the values being silently dropped. This\nshould not be used unless you are certain of correctness. Defaults to false.\n\n

\n

Works as buffer.writeUInt32*, except value is written out as a two's\ncomplement signed integer into buffer.\n\n

\n" + }, + { + "textRaw": "buf.writeInt32BE(value, offset, [noAssert])", + "type": "method", + "name": "writeInt32BE", + "signatures": [ + { + "params": [ + { + "textRaw": "`value` Number ", + "name": "value", + "desc": "Number" + }, + { + "textRaw": "`offset` Number ", + "name": "offset", + "desc": "Number" + }, + { + "textRaw": "`noAssert` Boolean, Optional, Default: false ", + "name": "noAssert", + "desc": "Boolean, Optional, Default: false", + "optional": true + } + ] + }, + { + "params": [ + { + "name": "value" + }, + { + "name": "offset" + }, + { + "name": "noAssert", + "optional": true + } + ] + } + ], + "desc": "

Writes value to the buffer at the specified offset with specified endian\nformat. Note, value must be a valid signed 32 bit integer.\n\n

\n

Set noAssert to true to skip validation of value and offset. This means\nthat value may be too large for the specific function and offset may be\nbeyond the end of the buffer leading to the values being silently dropped. This\nshould not be used unless you are certain of correctness. Defaults to false.\n\n

\n

Works as buffer.writeUInt32*, except value is written out as a two's\ncomplement signed integer into buffer.\n\n

\n" + }, + { + "textRaw": "buf.writeFloatLE(value, offset, [noAssert])", + "type": "method", + "name": "writeFloatLE", + "signatures": [ + { + "params": [ + { + "textRaw": "`value` Number ", + "name": "value", + "desc": "Number" + }, + { + "textRaw": "`offset` Number ", + "name": "offset", + "desc": "Number" + }, + { + "textRaw": "`noAssert` Boolean, Optional, Default: false ", + "name": "noAssert", + "desc": "Boolean, Optional, Default: false", + "optional": true + } + ] + }, + { + "params": [ + { + "name": "value" + }, + { + "name": "offset" + }, + { + "name": "noAssert", + "optional": true + } + ] + }, + { + "params": [ + { + "name": "value" + }, + { + "name": "offset" + }, + { + "name": "noAssert", + "optional": true + } + ] + } + ], + "desc": "

Writes value to the buffer at the specified offset with specified endian\nformat. Note, value must be a valid 32 bit float.\n\n

\n

Set noAssert to true to skip validation of value and offset. This means\nthat value may be too large for the specific function and offset may be\nbeyond the end of the buffer leading to the values being silently dropped. This\nshould not be used unless you are certain of correctness. Defaults to false.\n\n

\n

Example:\n\n

\n
var buf = new Buffer(4);\nbuf.writeFloatBE(0xcafebabe, 0);\n\nconsole.log(buf);\n\nbuf.writeFloatLE(0xcafebabe, 0);\n\nconsole.log(buf);\n\n// <Buffer 4f 4a fe bb>\n// <Buffer bb fe 4a 4f>
\n" + }, + { + "textRaw": "buf.writeFloatBE(value, offset, [noAssert])", + "type": "method", + "name": "writeFloatBE", + "signatures": [ + { + "params": [ + { + "textRaw": "`value` Number ", + "name": "value", + "desc": "Number" + }, + { + "textRaw": "`offset` Number ", + "name": "offset", + "desc": "Number" + }, + { + "textRaw": "`noAssert` Boolean, Optional, Default: false ", + "name": "noAssert", + "desc": "Boolean, Optional, Default: false", + "optional": true + } + ] + }, + { + "params": [ + { + "name": "value" + }, + { + "name": "offset" + }, + { + "name": "noAssert", + "optional": true + } + ] + } + ], + "desc": "

Writes value to the buffer at the specified offset with specified endian\nformat. Note, value must be a valid 32 bit float.\n\n

\n

Set noAssert to true to skip validation of value and offset. This means\nthat value may be too large for the specific function and offset may be\nbeyond the end of the buffer leading to the values being silently dropped. This\nshould not be used unless you are certain of correctness. Defaults to false.\n\n

\n

Example:\n\n

\n
var buf = new Buffer(4);\nbuf.writeFloatBE(0xcafebabe, 0);\n\nconsole.log(buf);\n\nbuf.writeFloatLE(0xcafebabe, 0);\n\nconsole.log(buf);\n\n// <Buffer 4f 4a fe bb>\n// <Buffer bb fe 4a 4f>
\n" + }, + { + "textRaw": "buf.writeDoubleLE(value, offset, [noAssert])", + "type": "method", + "name": "writeDoubleLE", + "signatures": [ + { + "params": [ + { + "textRaw": "`value` Number ", + "name": "value", + "desc": "Number" + }, + { + "textRaw": "`offset` Number ", + "name": "offset", + "desc": "Number" + }, + { + "textRaw": "`noAssert` Boolean, Optional, Default: false ", + "name": "noAssert", + "desc": "Boolean, Optional, Default: false", + "optional": true + } + ] + }, + { + "params": [ + { + "name": "value" + }, + { + "name": "offset" + }, + { + "name": "noAssert", + "optional": true + } + ] + }, + { + "params": [ + { + "name": "value" + }, + { + "name": "offset" + }, + { + "name": "noAssert", + "optional": true + } + ] + } + ], + "desc": "

Writes value to the buffer at the specified offset with specified endian\nformat. Note, value must be a valid 64 bit double.\n\n

\n

Set noAssert to true to skip validation of value and offset. This means\nthat value may be too large for the specific function and offset may be\nbeyond the end of the buffer leading to the values being silently dropped. This\nshould not be used unless you are certain of correctness. Defaults to false.\n\n

\n

Example:\n\n

\n
var buf = new Buffer(8);\nbuf.writeDoubleBE(0xdeadbeefcafebabe, 0);\n\nconsole.log(buf);\n\nbuf.writeDoubleLE(0xdeadbeefcafebabe, 0);\n\nconsole.log(buf);\n\n// <Buffer 43 eb d5 b7 dd f9 5f d7>\n// <Buffer d7 5f f9 dd b7 d5 eb 43>
\n" + }, + { + "textRaw": "buf.writeDoubleBE(value, offset, [noAssert])", + "type": "method", + "name": "writeDoubleBE", + "signatures": [ + { + "params": [ + { + "textRaw": "`value` Number ", + "name": "value", + "desc": "Number" + }, + { + "textRaw": "`offset` Number ", + "name": "offset", + "desc": "Number" + }, + { + "textRaw": "`noAssert` Boolean, Optional, Default: false ", + "name": "noAssert", + "desc": "Boolean, Optional, Default: false", + "optional": true + } + ] + }, + { + "params": [ + { + "name": "value" + }, + { + "name": "offset" + }, + { + "name": "noAssert", + "optional": true + } + ] + } + ], + "desc": "

Writes value to the buffer at the specified offset with specified endian\nformat. Note, value must be a valid 64 bit double.\n\n

\n

Set noAssert to true to skip validation of value and offset. This means\nthat value may be too large for the specific function and offset may be\nbeyond the end of the buffer leading to the values being silently dropped. This\nshould not be used unless you are certain of correctness. Defaults to false.\n\n

\n

Example:\n\n

\n
var buf = new Buffer(8);\nbuf.writeDoubleBE(0xdeadbeefcafebabe, 0);\n\nconsole.log(buf);\n\nbuf.writeDoubleLE(0xdeadbeefcafebabe, 0);\n\nconsole.log(buf);\n\n// <Buffer 43 eb d5 b7 dd f9 5f d7>\n// <Buffer d7 5f f9 dd b7 d5 eb 43>
\n" + }, + { + "textRaw": "buf.fill(value, [offset], [end])", + "type": "method", + "name": "fill", + "signatures": [ + { + "params": [ + { + "textRaw": "`value` ", + "name": "value" + }, + { + "textRaw": "`offset` Number, Optional ", + "name": "offset", + "optional": true, + "desc": "Number" + }, + { + "textRaw": "`end` Number, Optional ", + "name": "end", + "optional": true, + "desc": "Number" + } + ] + }, + { + "params": [ + { + "name": "value" + }, + { + "name": "offset", + "optional": true + }, + { + "name": "end", + "optional": true + } + ] + } + ], + "desc": "

Fills the buffer with the specified value. If the offset (defaults to 0)\nand end (defaults to buffer.length) are not given it will fill the entire\nbuffer.\n\n

\n
var b = new Buffer(50);\nb.fill("h");
\n" + } + ], + "properties": [ + { + "textRaw": "buf[index]", + "name": "[index]", + "desc": "

Get and set the octet at index. The values refer to individual bytes,\nso the legal range is between 0x00 and 0xFF hex or 0 and 255.\n\n

\n

Example: copy an ASCII string into a buffer, one byte at a time:\n\n

\n
str = "node.js";\nbuf = new Buffer(str.length);\n\nfor (var i = 0; i < str.length ; i++) {\n  buf[i] = str.charCodeAt(i);\n}\n\nconsole.log(buf);\n\n// node.js
\n" + }, + { + "textRaw": "`length` Number ", + "name": "length", + "desc": "

The size of the buffer in bytes. Note that this is not necessarily the size\nof the contents. length refers to the amount of memory allocated for the\nbuffer object. It does not change when the contents of the buffer are changed.\n\n

\n
buf = new Buffer(1234);\n\nconsole.log(buf.length);\nbuf.write("some string", 0, "ascii");\nconsole.log(buf.length);\n\n// 1234\n// 1234
\n", + "shortDesc": "Number" + } + ], + "classMethods": [ + { + "textRaw": "Class Method: Buffer.isBuffer(obj)", + "type": "classMethod", + "name": "isBuffer", + "signatures": [ + { + "return": { + "textRaw": "Return: Boolean ", + "name": "return", + "desc": "Boolean" + }, + "params": [ + { + "textRaw": "`obj` Object ", + "name": "obj", + "desc": "Object" + } + ] + }, + { + "params": [ + { + "name": "obj" + } + ] + } + ], + "desc": "

Tests if obj is a Buffer.\n\n

\n" + }, + { + "textRaw": "Class Method: Buffer.byteLength(string, [encoding])", + "type": "classMethod", + "name": "byteLength", + "signatures": [ + { + "return": { + "textRaw": "Return: Number ", + "name": "return", + "desc": "Number" + }, + "params": [ + { + "textRaw": "`string` String ", + "name": "string", + "desc": "String" + }, + { + "textRaw": "`encoding` String, Optional, Default: 'utf8' ", + "name": "encoding", + "desc": "String, Optional, Default: 'utf8'", + "optional": true + } + ] + }, + { + "params": [ + { + "name": "string" + }, + { + "name": "encoding", + "optional": true + } + ] + } + ], + "desc": "

Gives the actual byte length of a string. encoding defaults to 'utf8'.\nThis is not the same as String.prototype.length since that returns the\nnumber of characters in a string.\n\n

\n

Example:\n\n

\n
str = '\\u00bd + \\u00bc = \\u00be';\n\nconsole.log(str + ": " + str.length + " characters, " +\n  Buffer.byteLength(str, 'utf8') + " bytes");\n\n// ½ + ¼ = ¾: 9 characters, 12 bytes
\n" + }, + { + "textRaw": "Class Method: Buffer.concat(list, [totalLength])", + "type": "classMethod", + "name": "concat", + "signatures": [ + { + "params": [ + { + "textRaw": "`list` {Array} List of Buffer objects to concat ", + "name": "list", + "type": "Array", + "desc": "List of Buffer objects to concat" + }, + { + "textRaw": "`totalLength` {Number} Total length of the buffers when concatenated ", + "name": "totalLength", + "type": "Number", + "desc": "Total length of the buffers when concatenated", + "optional": true + } + ] + }, + { + "params": [ + { + "name": "list" + }, + { + "name": "totalLength", + "optional": true + } + ] + } + ], + "desc": "

Returns a buffer which is the result of concatenating all the buffers in\nthe list together.\n\n

\n

If the list has no items, or if the totalLength is 0, then it returns a\nzero-length buffer.\n\n

\n

If the list has exactly one item, then the first item of the list is\nreturned.\n\n

\n

If the list has more than one item, then a new Buffer is created.\n\n

\n

If totalLength is not provided, it is read from the buffers in the list.\nHowever, this adds an additional loop to the function, so it is faster\nto provide the length explicitly.\n\n

\n" + } + ], + "signatures": [ + { + "params": [ + { + "textRaw": "`size` Number ", + "name": "size", + "desc": "Number" + } + ], + "desc": "

Allocates a new buffer of size octets.\n\n

\n" + }, + { + "params": [ + { + "name": "size" + } + ], + "desc": "

Allocates a new buffer of size octets.\n\n

\n" + }, + { + "params": [ + { + "textRaw": "`array` Array ", + "name": "array", + "desc": "Array" + } + ], + "desc": "

Allocates a new buffer using an array of octets.\n\n

\n" + }, + { + "params": [ + { + "name": "array" + } + ], + "desc": "

Allocates a new buffer using an array of octets.\n\n

\n" + }, + { + "params": [ + { + "textRaw": "`str` String - string to encode. ", + "name": "str", + "desc": "String - string to encode." + }, + { + "textRaw": "`encoding` String - encoding to use, Optional. ", + "name": "encoding", + "desc": "String - encoding to use, Optional.", + "optional": true + } + ], + "desc": "

Allocates a new buffer containing the given str.\nencoding defaults to 'utf8'.\n\n

\n" + }, + { + "params": [ + { + "name": "str" + }, + { + "name": "encoding", + "optional": true + } + ], + "desc": "

Allocates a new buffer containing the given str.\nencoding defaults to 'utf8'.\n\n

\n" + } + ] + }, + { + "textRaw": "Class: SlowBuffer", + "type": "class", + "name": "SlowBuffer", + "desc": "

This class is primarily for internal use. JavaScript programs should\nuse Buffer instead of using SlowBuffer.\n\n

\n

In order to avoid the overhead of allocating many C++ Buffer objects for\nsmall blocks of memory in the lifetime of a server, Node allocates memory\nin 8Kb (8192 byte) chunks. If a buffer is smaller than this size, then it\nwill be backed by a parent SlowBuffer object. If it is larger than this,\nthen Node will allocate a SlowBuffer slab for it directly.\n

\n" + } + ], + "properties": [ + { + "textRaw": "`INSPECT_MAX_BYTES` Number, Default: 50 ", + "name": "INSPECT_MAX_BYTES", + "desc": "

How many bytes will be returned when buffer.inspect() is called. This can\nbe overridden by user modules.\n\n

\n

Note that this is a property on the buffer module returned by\nrequire('buffer'), not on the Buffer global, or a buffer instance.\n\n

\n", + "shortDesc": "Number, Default: 50" + } + ], + "type": "module", + "displayName": "Buffer" + } + ] +} diff --git a/node-v0.8.14/doc/api/buffer.markdown b/node-v0.8.14/doc/api/buffer.markdown new file mode 100644 index 0000000..ff95304 --- /dev/null +++ b/node-v0.8.14/doc/api/buffer.markdown @@ -0,0 +1,668 @@ +# Buffer + + Stability: 3 - Stable + +Pure JavaScript is Unicode friendly but not nice to binary data. When +dealing with TCP streams or the file system, it's necessary to handle octet +streams. Node has several strategies for manipulating, creating, and +consuming octet streams. + +Raw data is stored in instances of the `Buffer` class. A `Buffer` is similar +to an array of integers but corresponds to a raw memory allocation outside +the V8 heap. A `Buffer` cannot be resized. + +The `Buffer` class is a global, making it very rare that one would need +to ever `require('buffer')`. + +Converting between Buffers and JavaScript string objects requires an explicit +encoding method. Here are the different string encodings. + +* `'ascii'` - for 7 bit ASCII data only. This encoding method is very fast, and + will strip the high bit if set. + Note that this encoding converts a null character (`'\0'` or `'\u0000'`) into + `0x20` (character code of a space). If you want to convert a null character + into `0x00`, you should use `'utf8'`. + +* `'utf8'` - Multibyte encoded Unicode characters. Many web pages and other + document formats use UTF-8. + +* `'utf16le'` - 2 or 4 bytes, little endian encoded Unicode characters. + Surrogate pairs (U+10000 to U+10FFFF) are supported. + +* `'ucs2'` - Alias of `'utf16le'`. + +* `'base64'` - Base64 string encoding. + +* `'binary'` - A way of encoding raw binary data into strings by using only + the first 8 bits of each character. This encoding method is deprecated and + should be avoided in favor of `Buffer` objects where possible. This encoding + will be removed in future versions of Node. + +* `'hex'` - Encode each byte as two hexadecimal characters. + +## Class: Buffer + +The Buffer class is a global type for dealing with binary data directly. +It can be constructed in a variety of ways. + +### new Buffer(size) + +* `size` Number + +Allocates a new buffer of `size` octets. + +### new Buffer(array) + +* `array` Array + +Allocates a new buffer using an `array` of octets. + +### new Buffer(str, [encoding]) + +* `str` String - string to encode. +* `encoding` String - encoding to use, Optional. + +Allocates a new buffer containing the given `str`. +`encoding` defaults to `'utf8'`. + +### buf.write(string, [offset], [length], [encoding]) + +* `string` String - data to be written to buffer +* `offset` Number, Optional, Default: 0 +* `length` Number, Optional, Default: `buffer.length - offset` +* `encoding` String, Optional, Default: 'utf8' + +Writes `string` to the buffer at `offset` using the given encoding. +`offset` defaults to `0`, `encoding` defaults to `'utf8'`. `length` is +the number of bytes to write. Returns number of octets written. If `buffer` did +not contain enough space to fit the entire string, it will write a partial +amount of the string. `length` defaults to `buffer.length - offset`. +The method will not write partial characters. + + buf = new Buffer(256); + len = buf.write('\u00bd + \u00bc = \u00be', 0); + console.log(len + " bytes: " + buf.toString('utf8', 0, len)); + +The number of characters written (which may be different than the number of +bytes written) is set in `Buffer._charsWritten` and will be overwritten the +next time `buf.write()` is called. + + +### buf.toString([encoding], [start], [end]) + +* `encoding` String, Optional, Default: 'utf8' +* `start` Number, Optional, Default: 0 +* `end` Number, Optional, Default: `buffer.length` + +Decodes and returns a string from buffer data encoded with `encoding` +(defaults to `'utf8'`) beginning at `start` (defaults to `0`) and ending at +`end` (defaults to `buffer.length`). + +See `buffer.write()` example, above. + + +### buf[index] + + + + +Get and set the octet at `index`. The values refer to individual bytes, +so the legal range is between `0x00` and `0xFF` hex or `0` and `255`. + +Example: copy an ASCII string into a buffer, one byte at a time: + + str = "node.js"; + buf = new Buffer(str.length); + + for (var i = 0; i < str.length ; i++) { + buf[i] = str.charCodeAt(i); + } + + console.log(buf); + + // node.js + +### Class Method: Buffer.isBuffer(obj) + +* `obj` Object +* Return: Boolean + +Tests if `obj` is a `Buffer`. + +### Class Method: Buffer.byteLength(string, [encoding]) + +* `string` String +* `encoding` String, Optional, Default: 'utf8' +* Return: Number + +Gives the actual byte length of a string. `encoding` defaults to `'utf8'`. +This is not the same as `String.prototype.length` since that returns the +number of *characters* in a string. + +Example: + + str = '\u00bd + \u00bc = \u00be'; + + console.log(str + ": " + str.length + " characters, " + + Buffer.byteLength(str, 'utf8') + " bytes"); + + // ½ + ¼ = ¾: 9 characters, 12 bytes + +### Class Method: Buffer.concat(list, [totalLength]) + +* `list` {Array} List of Buffer objects to concat +* `totalLength` {Number} Total length of the buffers when concatenated + +Returns a buffer which is the result of concatenating all the buffers in +the list together. + +If the list has no items, or if the totalLength is 0, then it returns a +zero-length buffer. + +If the list has exactly one item, then the first item of the list is +returned. + +If the list has more than one item, then a new Buffer is created. + +If totalLength is not provided, it is read from the buffers in the list. +However, this adds an additional loop to the function, so it is faster +to provide the length explicitly. + +### buf.length + +* Number + +The size of the buffer in bytes. Note that this is not necessarily the size +of the contents. `length` refers to the amount of memory allocated for the +buffer object. It does not change when the contents of the buffer are changed. + + buf = new Buffer(1234); + + console.log(buf.length); + buf.write("some string", 0, "ascii"); + console.log(buf.length); + + // 1234 + // 1234 + +### buf.copy(targetBuffer, [targetStart], [sourceStart], [sourceEnd]) + +* `targetBuffer` Buffer object - Buffer to copy into +* `targetStart` Number, Optional, Default: 0 +* `sourceStart` Number, Optional, Default: 0 +* `sourceEnd` Number, Optional, Default: `buffer.length` + +Does copy between buffers. The source and target regions can be overlapped. +`targetStart` and `sourceStart` default to `0`. +`sourceEnd` defaults to `buffer.length`. + +Example: build two Buffers, then copy `buf1` from byte 16 through byte 19 +into `buf2`, starting at the 8th byte in `buf2`. + + buf1 = new Buffer(26); + buf2 = new Buffer(26); + + for (var i = 0 ; i < 26 ; i++) { + buf1[i] = i + 97; // 97 is ASCII a + buf2[i] = 33; // ASCII ! + } + + buf1.copy(buf2, 8, 16, 20); + console.log(buf2.toString('ascii', 0, 25)); + + // !!!!!!!!qrst!!!!!!!!!!!!! + + +### buf.slice([start], [end]) + +* `start` Number, Optional, Default: 0 +* `end` Number, Optional, Default: `buffer.length` + +Returns a new buffer which references the same memory as the old, but offset +and cropped by the `start` (defaults to `0`) and `end` (defaults to +`buffer.length`) indexes. + +**Modifying the new buffer slice will modify memory in the original buffer!** + +Example: build a Buffer with the ASCII alphabet, take a slice, then modify one +byte from the original Buffer. + + var buf1 = new Buffer(26); + + for (var i = 0 ; i < 26 ; i++) { + buf1[i] = i + 97; // 97 is ASCII a + } + + var buf2 = buf1.slice(0, 3); + console.log(buf2.toString('ascii', 0, buf2.length)); + buf1[0] = 33; + console.log(buf2.toString('ascii', 0, buf2.length)); + + // abc + // !bc + +### buf.readUInt8(offset, [noAssert]) + +* `offset` Number +* `noAssert` Boolean, Optional, Default: false +* Return: Number + +Reads an unsigned 8 bit integer from the buffer at the specified offset. + +Set `noAssert` to true to skip validation of `offset`. This means that `offset` +may be beyond the end of the buffer. Defaults to `false`. + +Example: + + var buf = new Buffer(4); + + buf[0] = 0x3; + buf[1] = 0x4; + buf[2] = 0x23; + buf[3] = 0x42; + + for (ii = 0; ii < buf.length; ii++) { + console.log(buf.readUInt8(ii)); + } + + // 0x3 + // 0x4 + // 0x23 + // 0x42 + +### buf.readUInt16LE(offset, [noAssert]) +### buf.readUInt16BE(offset, [noAssert]) + +* `offset` Number +* `noAssert` Boolean, Optional, Default: false +* Return: Number + +Reads an unsigned 16 bit integer from the buffer at the specified offset with +specified endian format. + +Set `noAssert` to true to skip validation of `offset`. This means that `offset` +may be beyond the end of the buffer. Defaults to `false`. + +Example: + + var buf = new Buffer(4); + + buf[0] = 0x3; + buf[1] = 0x4; + buf[2] = 0x23; + buf[3] = 0x42; + + console.log(buf.readUInt16BE(0)); + console.log(buf.readUInt16LE(0)); + console.log(buf.readUInt16BE(1)); + console.log(buf.readUInt16LE(1)); + console.log(buf.readUInt16BE(2)); + console.log(buf.readUInt16LE(2)); + + // 0x0304 + // 0x0403 + // 0x0423 + // 0x2304 + // 0x2342 + // 0x4223 + +### buf.readUInt32LE(offset, [noAssert]) +### buf.readUInt32BE(offset, [noAssert]) + +* `offset` Number +* `noAssert` Boolean, Optional, Default: false +* Return: Number + +Reads an unsigned 32 bit integer from the buffer at the specified offset with +specified endian format. + +Set `noAssert` to true to skip validation of `offset`. This means that `offset` +may be beyond the end of the buffer. Defaults to `false`. + +Example: + + var buf = new Buffer(4); + + buf[0] = 0x3; + buf[1] = 0x4; + buf[2] = 0x23; + buf[3] = 0x42; + + console.log(buf.readUInt32BE(0)); + console.log(buf.readUInt32LE(0)); + + // 0x03042342 + // 0x42230403 + +### buf.readInt8(offset, [noAssert]) + +* `offset` Number +* `noAssert` Boolean, Optional, Default: false +* Return: Number + +Reads a signed 8 bit integer from the buffer at the specified offset. + +Set `noAssert` to true to skip validation of `offset`. This means that `offset` +may be beyond the end of the buffer. Defaults to `false`. + +Works as `buffer.readUInt8`, except buffer contents are treated as two's +complement signed values. + +### buf.readInt16LE(offset, [noAssert]) +### buf.readInt16BE(offset, [noAssert]) + +* `offset` Number +* `noAssert` Boolean, Optional, Default: false +* Return: Number + +Reads a signed 16 bit integer from the buffer at the specified offset with +specified endian format. + +Set `noAssert` to true to skip validation of `offset`. This means that `offset` +may be beyond the end of the buffer. Defaults to `false`. + +Works as `buffer.readUInt16*`, except buffer contents are treated as two's +complement signed values. + +### buf.readInt32LE(offset, [noAssert]) +### buf.readInt32BE(offset, [noAssert]) + +* `offset` Number +* `noAssert` Boolean, Optional, Default: false +* Return: Number + +Reads a signed 32 bit integer from the buffer at the specified offset with +specified endian format. + +Set `noAssert` to true to skip validation of `offset`. This means that `offset` +may be beyond the end of the buffer. Defaults to `false`. + +Works as `buffer.readUInt32*`, except buffer contents are treated as two's +complement signed values. + +### buf.readFloatLE(offset, [noAssert]) +### buf.readFloatBE(offset, [noAssert]) + +* `offset` Number +* `noAssert` Boolean, Optional, Default: false +* Return: Number + +Reads a 32 bit float from the buffer at the specified offset with specified +endian format. + +Set `noAssert` to true to skip validation of `offset`. This means that `offset` +may be beyond the end of the buffer. Defaults to `false`. + +Example: + + var buf = new Buffer(4); + + buf[0] = 0x00; + buf[1] = 0x00; + buf[2] = 0x80; + buf[3] = 0x3f; + + console.log(buf.readFloatLE(0)); + + // 0x01 + +### buf.readDoubleLE(offset, [noAssert]) +### buf.readDoubleBE(offset, [noAssert]) + +* `offset` Number +* `noAssert` Boolean, Optional, Default: false +* Return: Number + +Reads a 64 bit double from the buffer at the specified offset with specified +endian format. + +Set `noAssert` to true to skip validation of `offset`. This means that `offset` +may be beyond the end of the buffer. Defaults to `false`. + +Example: + + var buf = new Buffer(8); + + buf[0] = 0x55; + buf[1] = 0x55; + buf[2] = 0x55; + buf[3] = 0x55; + buf[4] = 0x55; + buf[5] = 0x55; + buf[6] = 0xd5; + buf[7] = 0x3f; + + console.log(buf.readDoubleLE(0)); + + // 0.3333333333333333 + +### buf.writeUInt8(value, offset, [noAssert]) + +* `value` Number +* `offset` Number +* `noAssert` Boolean, Optional, Default: false + +Writes `value` to the buffer at the specified offset. Note, `value` must be a +valid unsigned 8 bit integer. + +Set `noAssert` to true to skip validation of `value` and `offset`. This means +that `value` may be too large for the specific function and `offset` may be +beyond the end of the buffer leading to the values being silently dropped. This +should not be used unless you are certain of correctness. Defaults to `false`. + +Example: + + var buf = new Buffer(4); + buf.writeUInt8(0x3, 0); + buf.writeUInt8(0x4, 1); + buf.writeUInt8(0x23, 2); + buf.writeUInt8(0x42, 3); + + console.log(buf); + + // + +### buf.writeUInt16LE(value, offset, [noAssert]) +### buf.writeUInt16BE(value, offset, [noAssert]) + +* `value` Number +* `offset` Number +* `noAssert` Boolean, Optional, Default: false + +Writes `value` to the buffer at the specified offset with specified endian +format. Note, `value` must be a valid unsigned 16 bit integer. + +Set `noAssert` to true to skip validation of `value` and `offset`. This means +that `value` may be too large for the specific function and `offset` may be +beyond the end of the buffer leading to the values being silently dropped. This +should not be used unless you are certain of correctness. Defaults to `false`. + +Example: + + var buf = new Buffer(4); + buf.writeUInt16BE(0xdead, 0); + buf.writeUInt16BE(0xbeef, 2); + + console.log(buf); + + buf.writeUInt16LE(0xdead, 0); + buf.writeUInt16LE(0xbeef, 2); + + console.log(buf); + + // + // + +### buf.writeUInt32LE(value, offset, [noAssert]) +### buf.writeUInt32BE(value, offset, [noAssert]) + +* `value` Number +* `offset` Number +* `noAssert` Boolean, Optional, Default: false + +Writes `value` to the buffer at the specified offset with specified endian +format. Note, `value` must be a valid unsigned 32 bit integer. + +Set `noAssert` to true to skip validation of `value` and `offset`. This means +that `value` may be too large for the specific function and `offset` may be +beyond the end of the buffer leading to the values being silently dropped. This +should not be used unless you are certain of correctness. Defaults to `false`. + +Example: + + var buf = new Buffer(4); + buf.writeUInt32BE(0xfeedface, 0); + + console.log(buf); + + buf.writeUInt32LE(0xfeedface, 0); + + console.log(buf); + + // + // + +### buf.writeInt8(value, offset, [noAssert]) + +* `value` Number +* `offset` Number +* `noAssert` Boolean, Optional, Default: false + +Writes `value` to the buffer at the specified offset. Note, `value` must be a +valid signed 8 bit integer. + +Set `noAssert` to true to skip validation of `value` and `offset`. This means +that `value` may be too large for the specific function and `offset` may be +beyond the end of the buffer leading to the values being silently dropped. This +should not be used unless you are certain of correctness. Defaults to `false`. + +Works as `buffer.writeUInt8`, except value is written out as a two's complement +signed integer into `buffer`. + +### buf.writeInt16LE(value, offset, [noAssert]) +### buf.writeInt16BE(value, offset, [noAssert]) + +* `value` Number +* `offset` Number +* `noAssert` Boolean, Optional, Default: false + +Writes `value` to the buffer at the specified offset with specified endian +format. Note, `value` must be a valid signed 16 bit integer. + +Set `noAssert` to true to skip validation of `value` and `offset`. This means +that `value` may be too large for the specific function and `offset` may be +beyond the end of the buffer leading to the values being silently dropped. This +should not be used unless you are certain of correctness. Defaults to `false`. + +Works as `buffer.writeUInt16*`, except value is written out as a two's +complement signed integer into `buffer`. + +### buf.writeInt32LE(value, offset, [noAssert]) +### buf.writeInt32BE(value, offset, [noAssert]) + +* `value` Number +* `offset` Number +* `noAssert` Boolean, Optional, Default: false + +Writes `value` to the buffer at the specified offset with specified endian +format. Note, `value` must be a valid signed 32 bit integer. + +Set `noAssert` to true to skip validation of `value` and `offset`. This means +that `value` may be too large for the specific function and `offset` may be +beyond the end of the buffer leading to the values being silently dropped. This +should not be used unless you are certain of correctness. Defaults to `false`. + +Works as `buffer.writeUInt32*`, except value is written out as a two's +complement signed integer into `buffer`. + +### buf.writeFloatLE(value, offset, [noAssert]) +### buf.writeFloatBE(value, offset, [noAssert]) + +* `value` Number +* `offset` Number +* `noAssert` Boolean, Optional, Default: false + +Writes `value` to the buffer at the specified offset with specified endian +format. Note, `value` must be a valid 32 bit float. + +Set `noAssert` to true to skip validation of `value` and `offset`. This means +that `value` may be too large for the specific function and `offset` may be +beyond the end of the buffer leading to the values being silently dropped. This +should not be used unless you are certain of correctness. Defaults to `false`. + +Example: + + var buf = new Buffer(4); + buf.writeFloatBE(0xcafebabe, 0); + + console.log(buf); + + buf.writeFloatLE(0xcafebabe, 0); + + console.log(buf); + + // + // + +### buf.writeDoubleLE(value, offset, [noAssert]) +### buf.writeDoubleBE(value, offset, [noAssert]) + +* `value` Number +* `offset` Number +* `noAssert` Boolean, Optional, Default: false + +Writes `value` to the buffer at the specified offset with specified endian +format. Note, `value` must be a valid 64 bit double. + +Set `noAssert` to true to skip validation of `value` and `offset`. This means +that `value` may be too large for the specific function and `offset` may be +beyond the end of the buffer leading to the values being silently dropped. This +should not be used unless you are certain of correctness. Defaults to `false`. + +Example: + + var buf = new Buffer(8); + buf.writeDoubleBE(0xdeadbeefcafebabe, 0); + + console.log(buf); + + buf.writeDoubleLE(0xdeadbeefcafebabe, 0); + + console.log(buf); + + // + // + +### buf.fill(value, [offset], [end]) + +* `value` +* `offset` Number, Optional +* `end` Number, Optional + +Fills the buffer with the specified value. If the `offset` (defaults to `0`) +and `end` (defaults to `buffer.length`) are not given it will fill the entire +buffer. + + var b = new Buffer(50); + b.fill("h"); + +## buffer.INSPECT_MAX_BYTES + +* Number, Default: 50 + +How many bytes will be returned when `buffer.inspect()` is called. This can +be overridden by user modules. + +Note that this is a property on the buffer module returned by +`require('buffer')`, not on the Buffer global, or a buffer instance. + +## Class: SlowBuffer + +This class is primarily for internal use. JavaScript programs should +use Buffer instead of using SlowBuffer. + +In order to avoid the overhead of allocating many C++ Buffer objects for +small blocks of memory in the lifetime of a server, Node allocates memory +in 8Kb (8192 byte) chunks. If a buffer is smaller than this size, then it +will be backed by a parent SlowBuffer object. If it is larger than this, +then Node will allocate a SlowBuffer slab for it directly. diff --git a/node-v0.8.14/doc/api/child_process.html b/node-v0.8.14/doc/api/child_process.html new file mode 100644 index 0000000..b6a13a3 --- /dev/null +++ b/node-v0.8.14/doc/api/child_process.html @@ -0,0 +1,699 @@ + + + + + Child Process Node.js v0.8.14 Manual & Documentation + + + + + +
+ + + +
+
+ + +
+
+

Node.js v0.8.14 Manual & Documentation

+ +
+
+ + + +
+

Child Process#

+
Stability: 3 - Stable
+

Node provides a tri-directional popen(3) facility through the +child_process module. + +

+

It is possible to stream data through a child's stdin, stdout, and +stderr in a fully non-blocking way. + +

+

To create a child process use require('child_process').spawn() or +require('child_process').fork(). The semantics of each are slightly +different, and explained below. + +

+

Class: ChildProcess#

+

ChildProcess is an EventEmitter. + +

+

Child processes always have three streams associated with them. child.stdin, +child.stdout, and child.stderr. These may be shared with the stdio +streams of the parent process, or they may be separate stream objects +which can be piped to and from. + +

+

The ChildProcess class is not intended to be used directly. Use the +spawn() or fork() methods to create a Child Process instance. + +

+

Event: 'exit'#

+
    +
  • code Number the exit code, if it exited normally.
  • +
  • signal String the signal passed to kill the child process, if it +was killed by the parent.
  • +
+

This event is emitted after the child process ends. If the process terminated +normally, code is the final exit code of the process, otherwise null. If +the process terminated due to receipt of a signal, signal is the string name +of the signal, otherwise null. + +

+

Note that the child process stdio streams might still be open. + +

+

See waitpid(2). + +

+

Event: 'close'#

+

This event is emitted when the stdio streams of a child process have all +terminated. This is distinct from 'exit', since multiple processes +might share the same stdio streams. + +

+

Event: 'disconnect'#

+

This event is emitted after using the .disconnect() method in the parent or +in the child. After disconnecting it is no longer possible to send messages. +An alternative way to check if you can send messages is to see if the +child.connected property is true. + +

+

Event: 'message'#

+
    +
  • message Object a parsed JSON object or primitive value
  • +
  • sendHandle Handle object a Socket or Server object
  • +
+

Messages send by .send(message, [sendHandle]) are obtained using the +message event. + +

+

child.stdin#

+
    +
  • Stream object
  • +
+

A Writable Stream that represents the child process's stdin. +Closing this stream via end() often causes the child process to terminate. + +

+

If the child stdio streams are shared with the parent, then this will +not be set. + +

+

child.stdout#

+
    +
  • Stream object
  • +
+

A Readable Stream that represents the child process's stdout. + +

+

If the child stdio streams are shared with the parent, then this will +not be set. + +

+

child.stderr#

+
    +
  • Stream object
  • +
+

A Readable Stream that represents the child process's stderr. + +

+

If the child stdio streams are shared with the parent, then this will +not be set. + +

+

child.pid#

+
    +
  • Integer
  • +
+

The PID of the child process. + +

+

Example: + +

+
var spawn = require('child_process').spawn,
+    grep  = spawn('grep', ['ssh']);
+
+console.log('Spawned child pid: ' + grep.pid);
+grep.stdin.end();
+

child.kill([signal])#

+
    +
  • signal String
  • +
+

Send a signal to the child process. If no argument is given, the process will +be sent 'SIGTERM'. See signal(7) for a list of available signals. + +

+
var spawn = require('child_process').spawn,
+    grep  = spawn('grep', ['ssh']);
+
+grep.on('exit', function (code, signal) {
+  console.log('child process terminated due to receipt of signal '+signal);
+});
+
+// send SIGHUP to process
+grep.kill('SIGHUP');
+

Note that while the function is called kill, the signal delivered to the child +process may not actually kill it. kill really just sends a signal to a process. + +

+

See kill(2) + +

+

child.send(message, [sendHandle])#

+
    +
  • message Object
  • +
  • sendHandle Handle object
  • +
+

When using child_process.fork() you can write to the child using +child.send(message, [sendHandle]) and messages are received by +a 'message' event on the child. + +

+

For example: + +

+
var cp = require('child_process');
+
+var n = cp.fork(__dirname + '/sub.js');
+
+n.on('message', function(m) {
+  console.log('PARENT got message:', m);
+});
+
+n.send({ hello: 'world' });
+

And then the child script, 'sub.js' might look like this: + +

+
process.on('message', function(m) {
+  console.log('CHILD got message:', m);
+});
+
+process.send({ foo: 'bar' });
+

In the child the process object will have a send() method, and process +will emit objects each time it receives a message on its channel. + +

+

There is a special case when sending a {cmd: 'NODE_foo'} message. All messages +containing a NODE_ prefix in its cmd property will not be emitted in +the message event, since they are internal messages used by node core. +Messages containing the prefix are emitted in the internalMessage event, you +should by all means avoid using this feature, it is subject to change without notice. + +

+

The sendHandle option to child.send() is for sending a TCP server or +socket object to another process. The child will receive the object as its +second argument to the message event. + +

+

send server object + +

+

Here is an example of sending a server: + +

+
var child = require('child_process').fork('child.js');
+
+// Open up the server object and send the handle.
+var server = require('net').createServer();
+server.on('connection', function (socket) {
+  socket.end('handled by parent');
+});
+server.listen(1337, function() {
+  child.send('server', server);
+});
+

And the child would the receive the server object as: + +

+
process.on('message', function(m, server) {
+  if (m === 'server') {
+    server.on('connection', function (socket) {
+      socket.end('handled by child');
+    });
+  }
+});
+

Note that the server is now shared between the parent and child, this means +that some connections will be handled by the parent and some by the child. + +

+

send socket object + +

+

Here is an example of sending a socket. It will spawn two children and handle +connections with the remote address 74.125.127.100 as VIP by sending the +socket to a "special" child process. Other sockets will go to a "normal" process. + +

+
var normal = require('child_process').fork('child.js', ['normal']);
+var special = require('child_process').fork('child.js', ['special']);
+
+// Open up the server and send sockets to child
+var server = require('net').createServer();
+server.on('connection', function (socket) {
+
+  // if this is a VIP
+  if (socket.remoteAddress === '74.125.127.100') {
+    special.send('socket', socket);
+    return;
+  }
+  // just the usual dudes
+  normal.send('socket', socket);
+});
+server.listen(1337);
+

The child.js could look like this: + +

+
process.on('message', function(m, socket) {
+  if (m === 'socket') {
+    socket.end('You were handled as a ' + process.argv[2] + ' person');
+  }
+});
+

Note that once a single socket has been sent to a child the parent can no +longer keep track of when the socket is destroyed. To indicate this condition +the .connections property becomes null. +It is also recommended not to use .maxConnections in this condition. + +

+

child.disconnect()#

+

To close the IPC connection between parent and child use the +child.disconnect() method. This allows the child to exit gracefully since +there is no IPC channel keeping it alive. When calling this method the +disconnect event will be emitted in both parent and child, and the +connected flag will be set to false. Please note that you can also call +process.disconnect() in the child process. + +

+

child_process.spawn(command, [args], [options])#

+
    +
  • command String The command to run
  • +
  • args Array List of string arguments
  • +
  • options Object
      +
    • cwd String Current working directory of the child process
    • +
    • stdio Array|String Child's stdio configuration. (See below)
    • +
    • customFds Array Deprecated File descriptors for the child to use +for stdio. (See below)
    • +
    • env Object Environment key-value pairs
    • +
    • detached Boolean The child will be a process group leader. (See below)
    • +
    • uid Number Sets the user identity of the process. (See setuid(2).)
    • +
    • gid Number Sets the group identity of the process. (See setgid(2).)
    • +
    +
  • +
  • return: ChildProcess object
  • +
+

Launches a new process with the given command, with command line arguments in args. +If omitted, args defaults to an empty Array. + +

+

The third argument is used to specify additional options, which defaults to: + +

+
{ cwd: undefined,
+  env: process.env
+}
+

cwd allows you to specify the working directory from which the process is spawned. +Use env to specify environment variables that will be visible to the new process. + +

+

Example of running ls -lh /usr, capturing stdout, stderr, and the exit code: + +

+
var spawn = require('child_process').spawn,
+    ls    = spawn('ls', ['-lh', '/usr']);
+
+ls.stdout.on('data', function (data) {
+  console.log('stdout: ' + data);
+});
+
+ls.stderr.on('data', function (data) {
+  console.log('stderr: ' + data);
+});
+
+ls.on('exit', function (code) {
+  console.log('child process exited with code ' + code);
+});
+

Example: A very elaborate way to run 'ps ax | grep ssh' + +

+
var spawn = require('child_process').spawn,
+    ps    = spawn('ps', ['ax']),
+    grep  = spawn('grep', ['ssh']);
+
+ps.stdout.on('data', function (data) {
+  grep.stdin.write(data);
+});
+
+ps.stderr.on('data', function (data) {
+  console.log('ps stderr: ' + data);
+});
+
+ps.on('exit', function (code) {
+  if (code !== 0) {
+    console.log('ps process exited with code ' + code);
+  }
+  grep.stdin.end();
+});
+
+grep.stdout.on('data', function (data) {
+  console.log('' + data);
+});
+
+grep.stderr.on('data', function (data) {
+  console.log('grep stderr: ' + data);
+});
+
+grep.on('exit', function (code) {
+  if (code !== 0) {
+    console.log('grep process exited with code ' + code);
+  }
+});
+

Example of checking for failed exec: + +

+
var spawn = require('child_process').spawn,
+    child = spawn('bad_command');
+
+child.stderr.setEncoding('utf8');
+child.stderr.on('data', function (data) {
+  if (/^execvp\(\)/.test(data)) {
+    console.log('Failed to start child process.');
+  }
+});
+

Note that if spawn receives an empty options object, it will result in +spawning the process with an empty environment rather than using +process.env. This due to backwards compatibility issues with a deprecated +API. + +

+

The 'stdio' option to child_process.spawn() is an array where each +index corresponds to a fd in the child. The value is one of the following: + +

+
    +
  1. 'pipe' - Create a pipe between the child process and the parent process. +The parent end of the pipe is exposed to the parent as a property on the +child_process object as ChildProcess.stdio[fd]. Pipes created for +fds 0 - 2 are also available as ChildProcess.stdin, ChildProcess.stdout +and ChildProcess.stderr, respectively.
  2. +
  3. 'ipc' - Create an IPC channel for passing messages/file descriptors +between parent and child. A ChildProcess may have at most one IPC stdio +file descriptor. Setting this option enables the ChildProcess.send() method. +If the child writes JSON messages to this file descriptor, then this will +trigger ChildProcess.on('message'). If the child is a Node.js program, then +the presence of an IPC channel will enable process.send() and +process.on('message').
  4. +
  5. 'ignore' - Do not set this file descriptor in the child. Note that Node +will always open fd 0 - 2 for the processes it spawns. When any of these is +ignored node will open /dev/null and attach it to the child's fd.
  6. +
  7. Stream object - Share a readable or writable stream that refers to a tty, +file, socket, or a pipe with the child process. The stream's underlying +file descriptor is duplicated in the child process to the fd that +corresponds to the index in the stdio array.
  8. +
  9. Positive integer - The integer value is interpreted as a file descriptor +that is is currently open in the parent process. It is shared with the child +process, similar to how Stream objects can be shared.
  10. +
  11. null, undefined - Use default value. For stdio fds 0, 1 and 2 (in other +words, stdin, stdout, and stderr) a pipe is created. For fd 3 and up, the +default is 'ignore'.
  12. +
+

As a shorthand, the stdio argument may also be one of the following +strings, rather than an array: + +

+
    +
  • ignore - ['ignore', 'ignore', 'ignore']
  • +
  • pipe - ['pipe', 'pipe', 'pipe']
  • +
  • inherit - [process.stdin, process.stdout, process.stderr] or [0,1,2]
  • +
+

Example: + +

+
var spawn = require('child_process').spawn;
+
+// Child will use parent's stdios
+spawn('prg', [], { stdio: 'inherit' });
+
+// Spawn child sharing only stderr
+spawn('prg', [], { stdio: ['pipe', 'pipe', process.stderr] });
+
+// Open an extra fd=4, to interact with programs present a
+// startd-style interface.
+spawn('prg', [], { stdio: ['pipe', null, null, null, 'pipe'] });
+

If the detached option is set, the child process will be made the leader of a +new process group. This makes it possible for the child to continue running +after the parent exits. + +

+

By default, the parent will wait for the detached child to exit. To prevent +the parent from waiting for a given child, use the child.unref() method, +and the parent's event loop will not include the child in its reference count. + +

+

Example of detaching a long-running process and redirecting its output to a +file: + +

+
 var fs = require('fs'),
+     spawn = require('child_process').spawn,
+     out = fs.openSync('./out.log', 'a'),
+     err = fs.openSync('./out.log', 'a');
+
+ var child = spawn('prg', [], {
+   detached: true,
+   stdio: [ 'ignore', out, err ]
+ });
+
+ child.unref();
+

When using the detached option to start a long-running process, the process +will not stay running in the background unless it is provided with a stdio +configuration that is not connected to the parent. If the parent's stdio is +inherited, the child will remain attached to the controlling terminal. + +

+

There is a deprecated option called customFds which allows one to specify +specific file descriptors for the stdio of the child process. This API was +not portable to all platforms and therefore removed. +With customFds it was possible to hook up the new process' [stdin, stdout, +stderr] to existing streams; -1 meant that a new stream should be created. +Use at your own risk. + +

+

There are several internal options. In particular stdinStream, +stdoutStream, stderrStream. They are for INTERNAL USE ONLY. As with all +undocumented APIs in Node, they should not be used. + +

+

See also: child_process.exec() and child_process.fork() + +

+

child_process.exec(command, [options], callback)#

+
    +
  • command String The command to run, with space-separated arguments
  • +
  • options Object
      +
    • cwd String Current working directory of the child process
    • +
    • stdio Array|String Child's stdio configuration. (See above)
    • +
    • customFds Array Deprecated File descriptors for the child to use +for stdio. (See above)
    • +
    • env Object Environment key-value pairs
    • +
    • encoding String (Default: 'utf8')
    • +
    • timeout Number (Default: 0)
    • +
    • maxBuffer Number (Default: 200*1024)
    • +
    • killSignal String (Default: 'SIGTERM')
    • +
    +
  • +
  • callback Function called with the output when process terminates
      +
    • error Error
    • +
    • stdout Buffer
    • +
    • stderr Buffer
    • +
    +
  • +
  • Return: ChildProcess object
  • +
+

Runs a command in a shell and buffers the output. + +

+
var exec = require('child_process').exec,
+    child;
+
+child = exec('cat *.js bad_file | wc -l',
+  function (error, stdout, stderr) {
+    console.log('stdout: ' + stdout);
+    console.log('stderr: ' + stderr);
+    if (error !== null) {
+      console.log('exec error: ' + error);
+    }
+});
+

The callback gets the arguments (error, stdout, stderr). On success, error +will be null. On error, error will be an instance of Error and err.code +will be the exit code of the child process, and err.signal will be set to the +signal that terminated the process. + +

+

There is a second optional argument to specify several options. The +default options are + +

+
{ encoding: 'utf8',
+  timeout: 0,
+  maxBuffer: 200*1024,
+  killSignal: 'SIGTERM',
+  cwd: null,
+  env: null }
+

If timeout is greater than 0, then it will kill the child process +if it runs longer than timeout milliseconds. The child process is killed with +killSignal (default: 'SIGTERM'). maxBuffer specifies the largest +amount of data allowed on stdout or stderr - if this value is exceeded then +the child process is killed. + + +

+

child_process.execFile(file, args, options, callback)#

+
    +
  • file String The filename of the program to run
  • +
  • args Array List of string arguments
  • +
  • options Object
      +
    • cwd String Current working directory of the child process
    • +
    • stdio Array|String Child's stdio configuration. (See above)
    • +
    • customFds Array Deprecated File descriptors for the child to use +for stdio. (See above)
    • +
    • env Object Environment key-value pairs
    • +
    • encoding String (Default: 'utf8')
    • +
    • timeout Number (Default: 0)
    • +
    • maxBuffer Number (Default: 200*1024)
    • +
    • killSignal String (Default: 'SIGTERM')
    • +
    +
  • +
  • callback Function called with the output when process terminates
      +
    • error Error
    • +
    • stdout Buffer
    • +
    • stderr Buffer
    • +
    +
  • +
  • Return: ChildProcess object
  • +
+

This is similar to child_process.exec() except it does not execute a +subshell but rather the specified file directly. This makes it slightly +leaner than child_process.exec. It has the same options. + + +

+

child_process.fork(modulePath, [args], [options])#

+
    +
  • modulePath String The module to run in the child
  • +
  • args Array List of string arguments
  • +
  • options Object
      +
    • cwd String Current working directory of the child process
    • +
    • env Object Environment key-value pairs
    • +
    • encoding String (Default: 'utf8')
    • +
    +
  • +
  • Return: ChildProcess object
  • +
+

This is a special case of the spawn() functionality for spawning Node +processes. In addition to having all the methods in a normal ChildProcess +instance, the returned object has a communication channel built-in. See +child.send(message, [sendHandle]) for details. + +

+

By default the spawned Node process will have the stdout, stderr associated +with the parent's. To change this behavior set the silent property in the +options object to true. + +

+

The child process does not automatically exit once it's done, you need to call +process.exit() explicitly. This limitation may be lifted in the future. + +

+

These child Nodes are still whole new instances of V8. Assume at least 30ms +startup and 10mb memory for each new Node. That is, you cannot create many +thousands of them. + +

+ +
+
+
+ + + + + + + + + diff --git a/node-v0.8.14/doc/api/child_process.json b/node-v0.8.14/doc/api/child_process.json new file mode 100644 index 0000000..7d0218a --- /dev/null +++ b/node-v0.8.14/doc/api/child_process.json @@ -0,0 +1,554 @@ +{ + "source": "doc/api/child_process.markdown", + "modules": [ + { + "textRaw": "Child Process", + "name": "child_process", + "stability": 3, + "stabilityText": "Stable", + "desc": "

Node provides a tri-directional popen(3) facility through the\nchild_process module.\n\n

\n

It is possible to stream data through a child's stdin, stdout, and\nstderr in a fully non-blocking way.\n\n

\n

To create a child process use require('child_process').spawn() or\nrequire('child_process').fork(). The semantics of each are slightly\ndifferent, and explained below.\n\n

\n", + "classes": [ + { + "textRaw": "Class: ChildProcess", + "type": "class", + "name": "ChildProcess", + "desc": "

ChildProcess is an [EventEmitter][].\n\n

\n

Child processes always have three streams associated with them. child.stdin,\nchild.stdout, and child.stderr. These may be shared with the stdio\nstreams of the parent process, or they may be separate stream objects\nwhich can be piped to and from.\n\n

\n

The ChildProcess class is not intended to be used directly. Use the\nspawn() or fork() methods to create a Child Process instance.\n\n

\n", + "events": [ + { + "textRaw": "Event: 'exit'", + "type": "event", + "name": "exit", + "params": [], + "desc": "

This event is emitted after the child process ends. If the process terminated\nnormally, code is the final exit code of the process, otherwise null. If\nthe process terminated due to receipt of a signal, signal is the string name\nof the signal, otherwise null.\n\n

\n

Note that the child process stdio streams might still be open.\n\n

\n

See waitpid(2).\n\n

\n" + }, + { + "textRaw": "Event: 'close'", + "type": "event", + "name": "close", + "desc": "

This event is emitted when the stdio streams of a child process have all\nterminated. This is distinct from 'exit', since multiple processes\nmight share the same stdio streams.\n\n

\n", + "params": [] + }, + { + "textRaw": "Event: 'disconnect'", + "type": "event", + "name": "disconnect", + "desc": "

This event is emitted after using the .disconnect() method in the parent or\nin the child. After disconnecting it is no longer possible to send messages.\nAn alternative way to check if you can send messages is to see if the\nchild.connected property is true.\n\n

\n", + "params": [] + }, + { + "textRaw": "Event: 'message'", + "type": "event", + "name": "message", + "params": [], + "desc": "

Messages send by .send(message, [sendHandle]) are obtained using the\nmessage event.\n\n

\n" + } + ], + "properties": [ + { + "textRaw": "`stdin` {Stream object} ", + "name": "stdin", + "desc": "

A Writable Stream that represents the child process's stdin.\nClosing this stream via end() often causes the child process to terminate.\n\n

\n

If the child stdio streams are shared with the parent, then this will\nnot be set.\n\n

\n" + }, + { + "textRaw": "`stdout` {Stream object} ", + "name": "stdout", + "desc": "

A Readable Stream that represents the child process's stdout.\n\n

\n

If the child stdio streams are shared with the parent, then this will\nnot be set.\n\n

\n" + }, + { + "textRaw": "`stderr` {Stream object} ", + "name": "stderr", + "desc": "

A Readable Stream that represents the child process's stderr.\n\n

\n

If the child stdio streams are shared with the parent, then this will\nnot be set.\n\n

\n" + }, + { + "textRaw": "`pid` {Integer} ", + "name": "pid", + "desc": "

The PID of the child process.\n\n

\n

Example:\n\n

\n
var spawn = require('child_process').spawn,\n    grep  = spawn('grep', ['ssh']);\n\nconsole.log('Spawned child pid: ' + grep.pid);\ngrep.stdin.end();
\n" + } + ], + "methods": [ + { + "textRaw": "child.kill([signal])", + "type": "method", + "name": "kill", + "signatures": [ + { + "params": [ + { + "textRaw": "`signal` {String} ", + "name": "signal", + "type": "String", + "optional": true + } + ] + }, + { + "params": [ + { + "name": "signal", + "optional": true + } + ] + } + ], + "desc": "

Send a signal to the child process. If no argument is given, the process will\nbe sent 'SIGTERM'. See signal(7) for a list of available signals.\n\n

\n
var spawn = require('child_process').spawn,\n    grep  = spawn('grep', ['ssh']);\n\ngrep.on('exit', function (code, signal) {\n  console.log('child process terminated due to receipt of signal '+signal);\n});\n\n// send SIGHUP to process\ngrep.kill('SIGHUP');
\n

Note that while the function is called kill, the signal delivered to the child\nprocess may not actually kill it. kill really just sends a signal to a process.\n\n

\n

See kill(2)\n\n

\n" + }, + { + "textRaw": "child.send(message, [sendHandle])", + "type": "method", + "name": "send", + "signatures": [ + { + "params": [ + { + "textRaw": "`message` {Object} ", + "name": "message", + "type": "Object" + }, + { + "textRaw": "`sendHandle` {Handle object} ", + "name": "sendHandle", + "type": "Handle object", + "optional": true + } + ] + }, + { + "params": [ + { + "name": "message" + }, + { + "name": "sendHandle", + "optional": true + } + ] + } + ], + "desc": "

When using child_process.fork() you can write to the child using\nchild.send(message, [sendHandle]) and messages are received by\na 'message' event on the child.\n\n

\n

For example:\n\n

\n
var cp = require('child_process');\n\nvar n = cp.fork(__dirname + '/sub.js');\n\nn.on('message', function(m) {\n  console.log('PARENT got message:', m);\n});\n\nn.send({ hello: 'world' });
\n

And then the child script, 'sub.js' might look like this:\n\n

\n
process.on('message', function(m) {\n  console.log('CHILD got message:', m);\n});\n\nprocess.send({ foo: 'bar' });
\n

In the child the process object will have a send() method, and process\nwill emit objects each time it receives a message on its channel.\n\n

\n

There is a special case when sending a {cmd: 'NODE_foo'} message. All messages\ncontaining a NODE_ prefix in its cmd property will not be emitted in\nthe message event, since they are internal messages used by node core.\nMessages containing the prefix are emitted in the internalMessage event, you\nshould by all means avoid using this feature, it is subject to change without notice.\n\n

\n

The sendHandle option to child.send() is for sending a TCP server or\nsocket object to another process. The child will receive the object as its\nsecond argument to the message event.\n\n

\n

send server object\n\n

\n

Here is an example of sending a server:\n\n

\n
var child = require('child_process').fork('child.js');\n\n// Open up the server object and send the handle.\nvar server = require('net').createServer();\nserver.on('connection', function (socket) {\n  socket.end('handled by parent');\n});\nserver.listen(1337, function() {\n  child.send('server', server);\n});
\n

And the child would the receive the server object as:\n\n

\n
process.on('message', function(m, server) {\n  if (m === 'server') {\n    server.on('connection', function (socket) {\n      socket.end('handled by child');\n    });\n  }\n});
\n

Note that the server is now shared between the parent and child, this means\nthat some connections will be handled by the parent and some by the child.\n\n

\n

send socket object\n\n

\n

Here is an example of sending a socket. It will spawn two children and handle\nconnections with the remote address 74.125.127.100 as VIP by sending the\nsocket to a "special" child process. Other sockets will go to a "normal" process.\n\n

\n
var normal = require('child_process').fork('child.js', ['normal']);\nvar special = require('child_process').fork('child.js', ['special']);\n\n// Open up the server and send sockets to child\nvar server = require('net').createServer();\nserver.on('connection', function (socket) {\n\n  // if this is a VIP\n  if (socket.remoteAddress === '74.125.127.100') {\n    special.send('socket', socket);\n    return;\n  }\n  // just the usual dudes\n  normal.send('socket', socket);\n});\nserver.listen(1337);
\n

The child.js could look like this:\n\n

\n
process.on('message', function(m, socket) {\n  if (m === 'socket') {\n    socket.end('You were handled as a ' + process.argv[2] + ' person');\n  }\n});
\n

Note that once a single socket has been sent to a child the parent can no\nlonger keep track of when the socket is destroyed. To indicate this condition\nthe .connections property becomes null.\nIt is also recommended not to use .maxConnections in this condition.\n\n

\n" + }, + { + "textRaw": "child.disconnect()", + "type": "method", + "name": "disconnect", + "desc": "

To close the IPC connection between parent and child use the\nchild.disconnect() method. This allows the child to exit gracefully since\nthere is no IPC channel keeping it alive. When calling this method the\ndisconnect event will be emitted in both parent and child, and the\nconnected flag will be set to false. Please note that you can also call\nprocess.disconnect() in the child process.\n\n

\n", + "signatures": [ + { + "params": [] + } + ] + } + ] + } + ], + "methods": [ + { + "textRaw": "child_process.spawn(command, [args], [options])", + "type": "method", + "name": "spawn", + "signatures": [ + { + "return": { + "textRaw": "return: {ChildProcess object} ", + "name": "return", + "type": "ChildProcess object" + }, + "params": [ + { + "textRaw": "`command` {String} The command to run ", + "name": "command", + "type": "String", + "desc": "The command to run" + }, + { + "textRaw": "`args` {Array} List of string arguments ", + "name": "args", + "type": "Array", + "desc": "List of string arguments", + "optional": true + }, + { + "textRaw": "`options` {Object} ", + "options": [ + { + "textRaw": "`cwd` {String} Current working directory of the child process ", + "name": "cwd", + "type": "String", + "desc": "Current working directory of the child process" + }, + { + "textRaw": "`stdio` {Array|String} Child's stdio configuration. (See below) ", + "name": "stdio", + "type": "Array|String", + "desc": "Child's stdio configuration. (See below)" + }, + { + "textRaw": "`customFds` {Array} **Deprecated** File descriptors for the child to use for stdio. (See below) ", + "name": "customFds", + "type": "Array", + "desc": "**Deprecated** File descriptors for the child to use for stdio. (See below)" + }, + { + "textRaw": "`env` {Object} Environment key-value pairs ", + "name": "env", + "type": "Object", + "desc": "Environment key-value pairs" + }, + { + "textRaw": "`detached` {Boolean} The child will be a process group leader. (See below) ", + "name": "detached", + "type": "Boolean", + "desc": "The child will be a process group leader. (See below)" + }, + { + "textRaw": "`uid` {Number} Sets the user identity of the process. (See setuid(2).) ", + "name": "uid", + "type": "Number", + "desc": "Sets the user identity of the process. (See setuid(2).)" + }, + { + "textRaw": "`gid` {Number} Sets the group identity of the process. (See setgid(2).) ", + "name": "gid", + "type": "Number", + "desc": "Sets the group identity of the process. (See setgid(2).)" + } + ], + "name": "options", + "type": "Object", + "optional": true + } + ] + }, + { + "params": [ + { + "name": "command" + }, + { + "name": "args", + "optional": true + }, + { + "name": "options", + "optional": true + } + ] + } + ], + "desc": "

Launches a new process with the given command, with command line arguments in args.\nIf omitted, args defaults to an empty Array.\n\n

\n

The third argument is used to specify additional options, which defaults to:\n\n

\n
{ cwd: undefined,\n  env: process.env\n}
\n

cwd allows you to specify the working directory from which the process is spawned.\nUse env to specify environment variables that will be visible to the new process.\n\n

\n

Example of running ls -lh /usr, capturing stdout, stderr, and the exit code:\n\n

\n
var spawn = require('child_process').spawn,\n    ls    = spawn('ls', ['-lh', '/usr']);\n\nls.stdout.on('data', function (data) {\n  console.log('stdout: ' + data);\n});\n\nls.stderr.on('data', function (data) {\n  console.log('stderr: ' + data);\n});\n\nls.on('exit', function (code) {\n  console.log('child process exited with code ' + code);\n});
\n

Example: A very elaborate way to run 'ps ax | grep ssh'\n\n

\n
var spawn = require('child_process').spawn,\n    ps    = spawn('ps', ['ax']),\n    grep  = spawn('grep', ['ssh']);\n\nps.stdout.on('data', function (data) {\n  grep.stdin.write(data);\n});\n\nps.stderr.on('data', function (data) {\n  console.log('ps stderr: ' + data);\n});\n\nps.on('exit', function (code) {\n  if (code !== 0) {\n    console.log('ps process exited with code ' + code);\n  }\n  grep.stdin.end();\n});\n\ngrep.stdout.on('data', function (data) {\n  console.log('' + data);\n});\n\ngrep.stderr.on('data', function (data) {\n  console.log('grep stderr: ' + data);\n});\n\ngrep.on('exit', function (code) {\n  if (code !== 0) {\n    console.log('grep process exited with code ' + code);\n  }\n});
\n

Example of checking for failed exec:\n\n

\n
var spawn = require('child_process').spawn,\n    child = spawn('bad_command');\n\nchild.stderr.setEncoding('utf8');\nchild.stderr.on('data', function (data) {\n  if (/^execvp\\(\\)/.test(data)) {\n    console.log('Failed to start child process.');\n  }\n});
\n

Note that if spawn receives an empty options object, it will result in\nspawning the process with an empty environment rather than using\nprocess.env. This due to backwards compatibility issues with a deprecated\nAPI.\n\n

\n

The 'stdio' option to child_process.spawn() is an array where each\nindex corresponds to a fd in the child. The value is one of the following:\n\n

\n
    \n
  1. 'pipe' - Create a pipe between the child process and the parent process.\nThe parent end of the pipe is exposed to the parent as a property on the\nchild_process object as ChildProcess.stdio[fd]. Pipes created for\nfds 0 - 2 are also available as ChildProcess.stdin, ChildProcess.stdout\nand ChildProcess.stderr, respectively.
  2. \n
  3. 'ipc' - Create an IPC channel for passing messages/file descriptors\nbetween parent and child. A ChildProcess may have at most one IPC stdio\nfile descriptor. Setting this option enables the ChildProcess.send() method.\nIf the child writes JSON messages to this file descriptor, then this will\ntrigger ChildProcess.on('message'). If the child is a Node.js program, then\nthe presence of an IPC channel will enable process.send() and\nprocess.on('message').
  4. \n
  5. 'ignore' - Do not set this file descriptor in the child. Note that Node\nwill always open fd 0 - 2 for the processes it spawns. When any of these is\nignored node will open /dev/null and attach it to the child's fd.
  6. \n
  7. Stream object - Share a readable or writable stream that refers to a tty,\nfile, socket, or a pipe with the child process. The stream's underlying\nfile descriptor is duplicated in the child process to the fd that \ncorresponds to the index in the stdio array.
  8. \n
  9. Positive integer - The integer value is interpreted as a file descriptor \nthat is is currently open in the parent process. It is shared with the child\nprocess, similar to how Stream objects can be shared.
  10. \n
  11. null, undefined - Use default value. For stdio fds 0, 1 and 2 (in other\nwords, stdin, stdout, and stderr) a pipe is created. For fd 3 and up, the\ndefault is 'ignore'.
  12. \n
\n

As a shorthand, the stdio argument may also be one of the following\nstrings, rather than an array:\n\n

\n
    \n
  • ignore - ['ignore', 'ignore', 'ignore']
  • \n
  • pipe - ['pipe', 'pipe', 'pipe']
  • \n
  • inherit - [process.stdin, process.stdout, process.stderr] or [0,1,2]
  • \n
\n

Example:\n\n

\n
var spawn = require('child_process').spawn;\n\n// Child will use parent's stdios\nspawn('prg', [], { stdio: 'inherit' });\n\n// Spawn child sharing only stderr\nspawn('prg', [], { stdio: ['pipe', 'pipe', process.stderr] });\n\n// Open an extra fd=4, to interact with programs present a\n// startd-style interface.\nspawn('prg', [], { stdio: ['pipe', null, null, null, 'pipe'] });
\n

If the detached option is set, the child process will be made the leader of a\nnew process group. This makes it possible for the child to continue running \nafter the parent exits.\n\n

\n

By default, the parent will wait for the detached child to exit. To prevent\nthe parent from waiting for a given child, use the child.unref() method,\nand the parent's event loop will not include the child in its reference count.\n\n

\n

Example of detaching a long-running process and redirecting its output to a\nfile:\n\n

\n
 var fs = require('fs'),\n     spawn = require('child_process').spawn,\n     out = fs.openSync('./out.log', 'a'),\n     err = fs.openSync('./out.log', 'a');\n\n var child = spawn('prg', [], {\n   detached: true,\n   stdio: [ 'ignore', out, err ]\n });\n\n child.unref();
\n

When using the detached option to start a long-running process, the process\nwill not stay running in the background unless it is provided with a stdio\nconfiguration that is not connected to the parent. If the parent's stdio is\ninherited, the child will remain attached to the controlling terminal.\n\n

\n

There is a deprecated option called customFds which allows one to specify\nspecific file descriptors for the stdio of the child process. This API was\nnot portable to all platforms and therefore removed.\nWith customFds it was possible to hook up the new process' [stdin, stdout,\nstderr] to existing streams; -1 meant that a new stream should be created.\nUse at your own risk.\n\n

\n

There are several internal options. In particular stdinStream,\nstdoutStream, stderrStream. They are for INTERNAL USE ONLY. As with all\nundocumented APIs in Node, they should not be used.\n\n

\n

See also: child_process.exec() and child_process.fork()\n\n

\n" + }, + { + "textRaw": "child_process.exec(command, [options], callback)", + "type": "method", + "name": "exec", + "signatures": [ + { + "return": { + "textRaw": "Return: ChildProcess object ", + "name": "return", + "desc": "ChildProcess object" + }, + "params": [ + { + "textRaw": "`command` {String} The command to run, with space-separated arguments ", + "name": "command", + "type": "String", + "desc": "The command to run, with space-separated arguments" + }, + { + "textRaw": "`options` {Object} ", + "options": [ + { + "textRaw": "`cwd` {String} Current working directory of the child process ", + "name": "cwd", + "type": "String", + "desc": "Current working directory of the child process" + }, + { + "textRaw": "`stdio` {Array|String} Child's stdio configuration. (See above) ", + "name": "stdio", + "type": "Array|String", + "desc": "Child's stdio configuration. (See above)" + }, + { + "textRaw": "`customFds` {Array} **Deprecated** File descriptors for the child to use for stdio. (See above) ", + "name": "customFds", + "type": "Array", + "desc": "**Deprecated** File descriptors for the child to use for stdio. (See above)" + }, + { + "textRaw": "`env` {Object} Environment key-value pairs ", + "name": "env", + "type": "Object", + "desc": "Environment key-value pairs" + }, + { + "textRaw": "`encoding` {String} (Default: 'utf8') ", + "name": "encoding", + "default": "utf8", + "type": "String" + }, + { + "textRaw": "`timeout` {Number} (Default: 0) ", + "name": "timeout", + "default": "0", + "type": "Number" + }, + { + "textRaw": "`maxBuffer` {Number} (Default: 200*1024) ", + "name": "maxBuffer", + "default": "200*1024", + "type": "Number" + }, + { + "textRaw": "`killSignal` {String} (Default: 'SIGTERM') ", + "name": "killSignal", + "default": "SIGTERM", + "type": "String" + } + ], + "name": "options", + "type": "Object", + "optional": true + }, + { + "textRaw": "`callback` {Function} called with the output when process terminates ", + "options": [ + { + "textRaw": "`error` {Error} ", + "name": "error", + "type": "Error" + }, + { + "textRaw": "`stdout` {Buffer} ", + "name": "stdout", + "type": "Buffer" + }, + { + "textRaw": "`stderr` {Buffer} ", + "name": "stderr", + "type": "Buffer" + } + ], + "name": "callback", + "type": "Function", + "desc": "called with the output when process terminates" + } + ] + }, + { + "params": [ + { + "name": "command" + }, + { + "name": "options", + "optional": true + }, + { + "name": "callback" + } + ] + } + ], + "desc": "

Runs a command in a shell and buffers the output.\n\n

\n
var exec = require('child_process').exec,\n    child;\n\nchild = exec('cat *.js bad_file | wc -l',\n  function (error, stdout, stderr) {\n    console.log('stdout: ' + stdout);\n    console.log('stderr: ' + stderr);\n    if (error !== null) {\n      console.log('exec error: ' + error);\n    }\n});
\n

The callback gets the arguments (error, stdout, stderr). On success, error\nwill be null. On error, error will be an instance of Error and err.code\nwill be the exit code of the child process, and err.signal will be set to the\nsignal that terminated the process.\n\n

\n

There is a second optional argument to specify several options. The\ndefault options are\n\n

\n
{ encoding: 'utf8',\n  timeout: 0,\n  maxBuffer: 200*1024,\n  killSignal: 'SIGTERM',\n  cwd: null,\n  env: null }
\n

If timeout is greater than 0, then it will kill the child process\nif it runs longer than timeout milliseconds. The child process is killed with\nkillSignal (default: 'SIGTERM'). maxBuffer specifies the largest\namount of data allowed on stdout or stderr - if this value is exceeded then\nthe child process is killed.\n\n\n

\n" + }, + { + "textRaw": "child_process.execFile(file, args, options, callback)", + "type": "method", + "name": "execFile", + "signatures": [ + { + "return": { + "textRaw": "Return: ChildProcess object ", + "name": "return", + "desc": "ChildProcess object" + }, + "params": [ + { + "textRaw": "`file` {String} The filename of the program to run ", + "name": "file", + "type": "String", + "desc": "The filename of the program to run" + }, + { + "textRaw": "`args` {Array} List of string arguments ", + "name": "args", + "type": "Array", + "desc": "List of string arguments" + }, + { + "textRaw": "`options` {Object} ", + "options": [ + { + "textRaw": "`cwd` {String} Current working directory of the child process ", + "name": "cwd", + "type": "String", + "desc": "Current working directory of the child process" + }, + { + "textRaw": "`stdio` {Array|String} Child's stdio configuration. (See above) ", + "name": "stdio", + "type": "Array|String", + "desc": "Child's stdio configuration. (See above)" + }, + { + "textRaw": "`customFds` {Array} **Deprecated** File descriptors for the child to use for stdio. (See above) ", + "name": "customFds", + "type": "Array", + "desc": "**Deprecated** File descriptors for the child to use for stdio. (See above)" + }, + { + "textRaw": "`env` {Object} Environment key-value pairs ", + "name": "env", + "type": "Object", + "desc": "Environment key-value pairs" + }, + { + "textRaw": "`encoding` {String} (Default: 'utf8') ", + "name": "encoding", + "default": "utf8", + "type": "String" + }, + { + "textRaw": "`timeout` {Number} (Default: 0) ", + "name": "timeout", + "default": "0", + "type": "Number" + }, + { + "textRaw": "`maxBuffer` {Number} (Default: 200\\*1024) ", + "name": "maxBuffer", + "default": "200\\*1024", + "type": "Number" + }, + { + "textRaw": "`killSignal` {String} (Default: 'SIGTERM') ", + "name": "killSignal", + "default": "SIGTERM", + "type": "String" + } + ], + "name": "options", + "type": "Object" + }, + { + "textRaw": "`callback` {Function} called with the output when process terminates ", + "options": [ + { + "textRaw": "`error` {Error} ", + "name": "error", + "type": "Error" + }, + { + "textRaw": "`stdout` {Buffer} ", + "name": "stdout", + "type": "Buffer" + }, + { + "textRaw": "`stderr` {Buffer} ", + "name": "stderr", + "type": "Buffer" + } + ], + "name": "callback", + "type": "Function", + "desc": "called with the output when process terminates" + } + ] + }, + { + "params": [ + { + "name": "file" + }, + { + "name": "args" + }, + { + "name": "options" + }, + { + "name": "callback" + } + ] + } + ], + "desc": "

This is similar to child_process.exec() except it does not execute a\nsubshell but rather the specified file directly. This makes it slightly\nleaner than child_process.exec. It has the same options.\n\n\n

\n" + }, + { + "textRaw": "child\\_process.fork(modulePath, [args], [options])", + "type": "method", + "name": "fork", + "signatures": [ + { + "return": { + "textRaw": "Return: ChildProcess object ", + "name": "return", + "desc": "ChildProcess object" + }, + "params": [ + { + "textRaw": "`modulePath` {String} The module to run in the child ", + "name": "modulePath", + "type": "String", + "desc": "The module to run in the child" + }, + { + "textRaw": "`args` {Array} List of string arguments ", + "name": "args", + "type": "Array", + "desc": "List of string arguments", + "optional": true + }, + { + "textRaw": "`options` {Object} ", + "options": [ + { + "textRaw": "`cwd` {String} Current working directory of the child process ", + "name": "cwd", + "type": "String", + "desc": "Current working directory of the child process" + }, + { + "textRaw": "`env` {Object} Environment key-value pairs ", + "name": "env", + "type": "Object", + "desc": "Environment key-value pairs" + }, + { + "textRaw": "`encoding` {String} (Default: 'utf8') ", + "name": "encoding", + "default": "utf8", + "type": "String" + } + ], + "name": "options", + "type": "Object", + "optional": true + } + ] + }, + { + "params": [ + { + "name": "modulePath" + }, + { + "name": "args", + "optional": true + }, + { + "name": "options", + "optional": true + } + ] + } + ], + "desc": "

This is a special case of the spawn() functionality for spawning Node\nprocesses. In addition to having all the methods in a normal ChildProcess\ninstance, the returned object has a communication channel built-in. See\nchild.send(message, [sendHandle]) for details.\n\n

\n

By default the spawned Node process will have the stdout, stderr associated\nwith the parent's. To change this behavior set the silent property in the\noptions object to true.\n\n

\n

The child process does not automatically exit once it's done, you need to call\nprocess.exit() explicitly. This limitation may be lifted in the future.\n\n

\n

These child Nodes are still whole new instances of V8. Assume at least 30ms\nstartup and 10mb memory for each new Node. That is, you cannot create many\nthousands of them.\n\n

\n" + } + ], + "type": "module", + "displayName": "Child Process" + } + ] +} diff --git a/node-v0.8.14/doc/api/child_process.markdown b/node-v0.8.14/doc/api/child_process.markdown new file mode 100644 index 0000000..4417ed7 --- /dev/null +++ b/node-v0.8.14/doc/api/child_process.markdown @@ -0,0 +1,537 @@ +# Child Process + + Stability: 3 - Stable + +Node provides a tri-directional `popen(3)` facility through the +`child_process` module. + +It is possible to stream data through a child's `stdin`, `stdout`, and +`stderr` in a fully non-blocking way. + +To create a child process use `require('child_process').spawn()` or +`require('child_process').fork()`. The semantics of each are slightly +different, and explained below. + +## Class: ChildProcess + +`ChildProcess` is an [EventEmitter][]. + +Child processes always have three streams associated with them. `child.stdin`, +`child.stdout`, and `child.stderr`. These may be shared with the stdio +streams of the parent process, or they may be separate stream objects +which can be piped to and from. + +The ChildProcess class is not intended to be used directly. Use the +`spawn()` or `fork()` methods to create a Child Process instance. + +### Event: 'exit' + +* `code` {Number} the exit code, if it exited normally. +* `signal` {String} the signal passed to kill the child process, if it + was killed by the parent. + +This event is emitted after the child process ends. If the process terminated +normally, `code` is the final exit code of the process, otherwise `null`. If +the process terminated due to receipt of a signal, `signal` is the string name +of the signal, otherwise `null`. + +Note that the child process stdio streams might still be open. + +See `waitpid(2)`. + +### Event: 'close' + +This event is emitted when the stdio streams of a child process have all +terminated. This is distinct from 'exit', since multiple processes +might share the same stdio streams. + +### Event: 'disconnect' + +This event is emitted after using the `.disconnect()` method in the parent or +in the child. After disconnecting it is no longer possible to send messages. +An alternative way to check if you can send messages is to see if the +`child.connected` property is `true`. + +### Event: 'message' + +* `message` {Object} a parsed JSON object or primitive value +* `sendHandle` {Handle object} a Socket or Server object + +Messages send by `.send(message, [sendHandle])` are obtained using the +`message` event. + +### child.stdin + +* {Stream object} + +A `Writable Stream` that represents the child process's `stdin`. +Closing this stream via `end()` often causes the child process to terminate. + +If the child stdio streams are shared with the parent, then this will +not be set. + +### child.stdout + +* {Stream object} + +A `Readable Stream` that represents the child process's `stdout`. + +If the child stdio streams are shared with the parent, then this will +not be set. + +### child.stderr + +* {Stream object} + +A `Readable Stream` that represents the child process's `stderr`. + +If the child stdio streams are shared with the parent, then this will +not be set. + +### child.pid + +* {Integer} + +The PID of the child process. + +Example: + + var spawn = require('child_process').spawn, + grep = spawn('grep', ['ssh']); + + console.log('Spawned child pid: ' + grep.pid); + grep.stdin.end(); + +### child.kill([signal]) + +* `signal` {String} + +Send a signal to the child process. If no argument is given, the process will +be sent `'SIGTERM'`. See `signal(7)` for a list of available signals. + + var spawn = require('child_process').spawn, + grep = spawn('grep', ['ssh']); + + grep.on('exit', function (code, signal) { + console.log('child process terminated due to receipt of signal '+signal); + }); + + // send SIGHUP to process + grep.kill('SIGHUP'); + +Note that while the function is called `kill`, the signal delivered to the child +process may not actually kill it. `kill` really just sends a signal to a process. + +See `kill(2)` + +### child.send(message, [sendHandle]) + +* `message` {Object} +* `sendHandle` {Handle object} + +When using `child_process.fork()` you can write to the child using +`child.send(message, [sendHandle])` and messages are received by +a `'message'` event on the child. + +For example: + + var cp = require('child_process'); + + var n = cp.fork(__dirname + '/sub.js'); + + n.on('message', function(m) { + console.log('PARENT got message:', m); + }); + + n.send({ hello: 'world' }); + +And then the child script, `'sub.js'` might look like this: + + process.on('message', function(m) { + console.log('CHILD got message:', m); + }); + + process.send({ foo: 'bar' }); + +In the child the `process` object will have a `send()` method, and `process` +will emit objects each time it receives a message on its channel. + +There is a special case when sending a `{cmd: 'NODE_foo'}` message. All messages +containing a `NODE_` prefix in its `cmd` property will not be emitted in +the `message` event, since they are internal messages used by node core. +Messages containing the prefix are emitted in the `internalMessage` event, you +should by all means avoid using this feature, it is subject to change without notice. + +The `sendHandle` option to `child.send()` is for sending a TCP server or +socket object to another process. The child will receive the object as its +second argument to the `message` event. + +**send server object** + +Here is an example of sending a server: + + var child = require('child_process').fork('child.js'); + + // Open up the server object and send the handle. + var server = require('net').createServer(); + server.on('connection', function (socket) { + socket.end('handled by parent'); + }); + server.listen(1337, function() { + child.send('server', server); + }); + +And the child would the receive the server object as: + + process.on('message', function(m, server) { + if (m === 'server') { + server.on('connection', function (socket) { + socket.end('handled by child'); + }); + } + }); + +Note that the server is now shared between the parent and child, this means +that some connections will be handled by the parent and some by the child. + +**send socket object** + +Here is an example of sending a socket. It will spawn two children and handle +connections with the remote address `74.125.127.100` as VIP by sending the +socket to a "special" child process. Other sockets will go to a "normal" process. + + var normal = require('child_process').fork('child.js', ['normal']); + var special = require('child_process').fork('child.js', ['special']); + + // Open up the server and send sockets to child + var server = require('net').createServer(); + server.on('connection', function (socket) { + + // if this is a VIP + if (socket.remoteAddress === '74.125.127.100') { + special.send('socket', socket); + return; + } + // just the usual dudes + normal.send('socket', socket); + }); + server.listen(1337); + +The `child.js` could look like this: + + process.on('message', function(m, socket) { + if (m === 'socket') { + socket.end('You were handled as a ' + process.argv[2] + ' person'); + } + }); + +Note that once a single socket has been sent to a child the parent can no +longer keep track of when the socket is destroyed. To indicate this condition +the `.connections` property becomes `null`. +It is also recommended not to use `.maxConnections` in this condition. + +### child.disconnect() + +To close the IPC connection between parent and child use the +`child.disconnect()` method. This allows the child to exit gracefully since +there is no IPC channel keeping it alive. When calling this method the +`disconnect` event will be emitted in both parent and child, and the +`connected` flag will be set to `false`. Please note that you can also call +`process.disconnect()` in the child process. + +## child_process.spawn(command, [args], [options]) + +* `command` {String} The command to run +* `args` {Array} List of string arguments +* `options` {Object} + * `cwd` {String} Current working directory of the child process + * `stdio` {Array|String} Child's stdio configuration. (See below) + * `customFds` {Array} **Deprecated** File descriptors for the child to use + for stdio. (See below) + * `env` {Object} Environment key-value pairs + * `detached` {Boolean} The child will be a process group leader. (See below) + * `uid` {Number} Sets the user identity of the process. (See setuid(2).) + * `gid` {Number} Sets the group identity of the process. (See setgid(2).) +* return: {ChildProcess object} + +Launches a new process with the given `command`, with command line arguments in `args`. +If omitted, `args` defaults to an empty Array. + +The third argument is used to specify additional options, which defaults to: + + { cwd: undefined, + env: process.env + } + +`cwd` allows you to specify the working directory from which the process is spawned. +Use `env` to specify environment variables that will be visible to the new process. + +Example of running `ls -lh /usr`, capturing `stdout`, `stderr`, and the exit code: + + var spawn = require('child_process').spawn, + ls = spawn('ls', ['-lh', '/usr']); + + ls.stdout.on('data', function (data) { + console.log('stdout: ' + data); + }); + + ls.stderr.on('data', function (data) { + console.log('stderr: ' + data); + }); + + ls.on('exit', function (code) { + console.log('child process exited with code ' + code); + }); + + +Example: A very elaborate way to run 'ps ax | grep ssh' + + var spawn = require('child_process').spawn, + ps = spawn('ps', ['ax']), + grep = spawn('grep', ['ssh']); + + ps.stdout.on('data', function (data) { + grep.stdin.write(data); + }); + + ps.stderr.on('data', function (data) { + console.log('ps stderr: ' + data); + }); + + ps.on('exit', function (code) { + if (code !== 0) { + console.log('ps process exited with code ' + code); + } + grep.stdin.end(); + }); + + grep.stdout.on('data', function (data) { + console.log('' + data); + }); + + grep.stderr.on('data', function (data) { + console.log('grep stderr: ' + data); + }); + + grep.on('exit', function (code) { + if (code !== 0) { + console.log('grep process exited with code ' + code); + } + }); + + +Example of checking for failed exec: + + var spawn = require('child_process').spawn, + child = spawn('bad_command'); + + child.stderr.setEncoding('utf8'); + child.stderr.on('data', function (data) { + if (/^execvp\(\)/.test(data)) { + console.log('Failed to start child process.'); + } + }); + +Note that if spawn receives an empty options object, it will result in +spawning the process with an empty environment rather than using +`process.env`. This due to backwards compatibility issues with a deprecated +API. + +The 'stdio' option to `child_process.spawn()` is an array where each +index corresponds to a fd in the child. The value is one of the following: + +1. `'pipe'` - Create a pipe between the child process and the parent process. + The parent end of the pipe is exposed to the parent as a property on the + `child_process` object as `ChildProcess.stdio[fd]`. Pipes created for + fds 0 - 2 are also available as ChildProcess.stdin, ChildProcess.stdout + and ChildProcess.stderr, respectively. +2. `'ipc'` - Create an IPC channel for passing messages/file descriptors + between parent and child. A ChildProcess may have at most *one* IPC stdio + file descriptor. Setting this option enables the ChildProcess.send() method. + If the child writes JSON messages to this file descriptor, then this will + trigger ChildProcess.on('message'). If the child is a Node.js program, then + the presence of an IPC channel will enable process.send() and + process.on('message'). +3. `'ignore'` - Do not set this file descriptor in the child. Note that Node + will always open fd 0 - 2 for the processes it spawns. When any of these is + ignored node will open `/dev/null` and attach it to the child's fd. +4. `Stream` object - Share a readable or writable stream that refers to a tty, + file, socket, or a pipe with the child process. The stream's underlying + file descriptor is duplicated in the child process to the fd that + corresponds to the index in the `stdio` array. +5. Positive integer - The integer value is interpreted as a file descriptor + that is is currently open in the parent process. It is shared with the child + process, similar to how `Stream` objects can be shared. +6. `null`, `undefined` - Use default value. For stdio fds 0, 1 and 2 (in other + words, stdin, stdout, and stderr) a pipe is created. For fd 3 and up, the + default is `'ignore'`. + +As a shorthand, the `stdio` argument may also be one of the following +strings, rather than an array: + +* `ignore` - `['ignore', 'ignore', 'ignore']` +* `pipe` - `['pipe', 'pipe', 'pipe']` +* `inherit` - `[process.stdin, process.stdout, process.stderr]` or `[0,1,2]` + +Example: + + var spawn = require('child_process').spawn; + + // Child will use parent's stdios + spawn('prg', [], { stdio: 'inherit' }); + + // Spawn child sharing only stderr + spawn('prg', [], { stdio: ['pipe', 'pipe', process.stderr] }); + + // Open an extra fd=4, to interact with programs present a + // startd-style interface. + spawn('prg', [], { stdio: ['pipe', null, null, null, 'pipe'] }); + +If the `detached` option is set, the child process will be made the leader of a +new process group. This makes it possible for the child to continue running +after the parent exits. + +By default, the parent will wait for the detached child to exit. To prevent +the parent from waiting for a given `child`, use the `child.unref()` method, +and the parent's event loop will not include the child in its reference count. + +Example of detaching a long-running process and redirecting its output to a +file: + + var fs = require('fs'), + spawn = require('child_process').spawn, + out = fs.openSync('./out.log', 'a'), + err = fs.openSync('./out.log', 'a'); + + var child = spawn('prg', [], { + detached: true, + stdio: [ 'ignore', out, err ] + }); + + child.unref(); + +When using the `detached` option to start a long-running process, the process +will not stay running in the background unless it is provided with a `stdio` +configuration that is not connected to the parent. If the parent's `stdio` is +inherited, the child will remain attached to the controlling terminal. + +There is a deprecated option called `customFds` which allows one to specify +specific file descriptors for the stdio of the child process. This API was +not portable to all platforms and therefore removed. +With `customFds` it was possible to hook up the new process' `[stdin, stdout, +stderr]` to existing streams; `-1` meant that a new stream should be created. +Use at your own risk. + +There are several internal options. In particular `stdinStream`, +`stdoutStream`, `stderrStream`. They are for INTERNAL USE ONLY. As with all +undocumented APIs in Node, they should not be used. + +See also: `child_process.exec()` and `child_process.fork()` + +## child_process.exec(command, [options], callback) + +* `command` {String} The command to run, with space-separated arguments +* `options` {Object} + * `cwd` {String} Current working directory of the child process + * `stdio` {Array|String} Child's stdio configuration. (See above) + * `customFds` {Array} **Deprecated** File descriptors for the child to use + for stdio. (See above) + * `env` {Object} Environment key-value pairs + * `encoding` {String} (Default: 'utf8') + * `timeout` {Number} (Default: 0) + * `maxBuffer` {Number} (Default: 200*1024) + * `killSignal` {String} (Default: 'SIGTERM') +* `callback` {Function} called with the output when process terminates + * `error` {Error} + * `stdout` {Buffer} + * `stderr` {Buffer} +* Return: ChildProcess object + +Runs a command in a shell and buffers the output. + + var exec = require('child_process').exec, + child; + + child = exec('cat *.js bad_file | wc -l', + function (error, stdout, stderr) { + console.log('stdout: ' + stdout); + console.log('stderr: ' + stderr); + if (error !== null) { + console.log('exec error: ' + error); + } + }); + +The callback gets the arguments `(error, stdout, stderr)`. On success, `error` +will be `null`. On error, `error` will be an instance of `Error` and `err.code` +will be the exit code of the child process, and `err.signal` will be set to the +signal that terminated the process. + +There is a second optional argument to specify several options. The +default options are + + { encoding: 'utf8', + timeout: 0, + maxBuffer: 200*1024, + killSignal: 'SIGTERM', + cwd: null, + env: null } + +If `timeout` is greater than 0, then it will kill the child process +if it runs longer than `timeout` milliseconds. The child process is killed with +`killSignal` (default: `'SIGTERM'`). `maxBuffer` specifies the largest +amount of data allowed on stdout or stderr - if this value is exceeded then +the child process is killed. + + +## child_process.execFile(file, args, options, callback) + +* `file` {String} The filename of the program to run +* `args` {Array} List of string arguments +* `options` {Object} + * `cwd` {String} Current working directory of the child process + * `stdio` {Array|String} Child's stdio configuration. (See above) + * `customFds` {Array} **Deprecated** File descriptors for the child to use + for stdio. (See above) + * `env` {Object} Environment key-value pairs + * `encoding` {String} (Default: 'utf8') + * `timeout` {Number} (Default: 0) + * `maxBuffer` {Number} (Default: 200\*1024) + * `killSignal` {String} (Default: 'SIGTERM') +* `callback` {Function} called with the output when process terminates + * `error` {Error} + * `stdout` {Buffer} + * `stderr` {Buffer} +* Return: ChildProcess object + +This is similar to `child_process.exec()` except it does not execute a +subshell but rather the specified file directly. This makes it slightly +leaner than `child_process.exec`. It has the same options. + + +## child\_process.fork(modulePath, [args], [options]) + +* `modulePath` {String} The module to run in the child +* `args` {Array} List of string arguments +* `options` {Object} + * `cwd` {String} Current working directory of the child process + * `env` {Object} Environment key-value pairs + * `encoding` {String} (Default: 'utf8') +* Return: ChildProcess object + +This is a special case of the `spawn()` functionality for spawning Node +processes. In addition to having all the methods in a normal ChildProcess +instance, the returned object has a communication channel built-in. See +`child.send(message, [sendHandle])` for details. + +By default the spawned Node process will have the stdout, stderr associated +with the parent's. To change this behavior set the `silent` property in the +`options` object to `true`. + +The child process does not automatically exit once it's done, you need to call +`process.exit()` explicitly. This limitation may be lifted in the future. + +These child Nodes are still whole new instances of V8. Assume at least 30ms +startup and 10mb memory for each new Node. That is, you cannot create many +thousands of them. + +[EventEmitter]: events.html#events_class_events_eventemitter diff --git a/node-v0.8.14/doc/api/cluster.html b/node-v0.8.14/doc/api/cluster.html new file mode 100644 index 0000000..941bd2d --- /dev/null +++ b/node-v0.8.14/doc/api/cluster.html @@ -0,0 +1,655 @@ + + + + + Cluster Node.js v0.8.14 Manual & Documentation + + + + + +
+ + + +
+
+ + +
+
+

Node.js v0.8.14 Manual & Documentation

+ +
+
+ + + +
+

Cluster#

+
Stability: 1 - Experimental
+

A single instance of Node runs in a single thread. To take advantage of +multi-core systems the user will sometimes want to launch a cluster of Node +processes to handle the load. + +

+

The cluster module allows you to easily create a network of processes that +all share server ports. + +

+
var cluster = require('cluster');
+var http = require('http');
+var numCPUs = require('os').cpus().length;
+
+if (cluster.isMaster) {
+  // Fork workers.
+  for (var i = 0; i < numCPUs; i++) {
+    cluster.fork();
+  }
+
+  cluster.on('exit', function(worker, code, signal) {
+    console.log('worker ' + worker.process.pid + ' died');
+  });
+} else {
+  // Workers can share any TCP connection
+  // In this case its a HTTP server
+  http.createServer(function(req, res) {
+    res.writeHead(200);
+    res.end("hello world\n");
+  }).listen(8000);
+}
+

Running node will now share port 8000 between the workers: + +

+
% node server.js
+Worker 2438 online
+Worker 2437 online
+

This feature was introduced recently, and may change in future versions. +Please try it out and provide feedback. + +

+

Also note that, on Windows, it is not yet possible to set up a named pipe +server in a worker. + +

+

How It Works#

+ + +

The worker processes are spawned using the child_process.fork method, +so that they can communicate with the parent via IPC and pass server +handles back and forth. + +

+

When you call server.listen(...) in a worker, it serializes the +arguments and passes the request to the master process. If the master +process already has a listening server matching the worker's +requirements, then it passes the handle to the worker. If it does not +already have a listening server matching that requirement, then it will +create one, and pass the handle to the child. + +

+

This causes potentially surprising behavior in three edge cases: + +

+
    +
  1. server.listen({fd: 7}) Because the message is passed to the master, +file descriptor 7 in the parent will be listened on, and the +handle passed to the worker, rather than listening to the worker's +idea of what the number 7 file descriptor references.
  2. +
  3. server.listen(handle) Listening on handles explicitly will cause +the worker to use the supplied handle, rather than talk to the master +process. If the worker already has the handle, then it's presumed +that you know what you are doing.
  4. +
  5. server.listen(0) Normally, this will cause servers to listen on a +random port. However, in a cluster, each worker will receive the +same "random" port each time they do listen(0). In essence, the +port is random the first time, but predictable thereafter. If you +want to listen on a unique port, generate a port number based on the +cluster worker ID.
  6. +
+

When multiple processes are all accept()ing on the same underlying +resource, the operating system load-balances across them very +efficiently. There is no routing logic in Node.js, or in your program, +and no shared state between the workers. Therefore, it is important to +design your program such that it does not rely too heavily on in-memory +data objects for things like sessions and login. + +

+

Because workers are all separate processes, they can be killed or +re-spawned depending on your program's needs, without affecting other +workers. As long as there are some workers still alive, the server will +continue to accept connections. Node does not automatically manage the +number of workers for you, however. It is your responsibility to manage +the worker pool for your application's needs. + +

+

cluster.settings#

+
    +
  • Object
      +
    • exec String file path to worker file. (Default=__filename)
    • +
    • args Array string arguments passed to worker. +(Default=process.argv.slice(2))
    • +
    • silent Boolean whether or not to send output to parent's stdio. +(Default=false)
    • +
    +
  • +
+

All settings set by the .setupMaster is stored in this settings object. +This object is not supposed to be change or set manually, by you. + +

+

cluster.isMaster#

+
    +
  • Boolean
  • +
+

True if the process is a master. This is determined +by the process.env.NODE_UNIQUE_ID. If process.env.NODE_UNIQUE_ID is +undefined, then isMaster is true. + +

+

cluster.isWorker#

+
    +
  • Boolean
  • +
+

This boolean flag is true if the process is a worker forked from a master. +If the process.env.NODE_UNIQUE_ID is set to a value, then +isWorker is true. + +

+

Event: 'fork'#

+
    +
  • worker Worker object
  • +
+

When a new worker is forked the cluster module will emit a 'fork' event. +This can be used to log worker activity, and create you own timeout. + +

+
var timeouts = [];
+function errorMsg() {
+  console.error("Something must be wrong with the connection ...");
+}
+
+cluster.on('fork', function(worker) {
+  timeouts[worker.id] = setTimeout(errorMsg, 2000);
+});
+cluster.on('listening', function(worker, address) {
+  clearTimeout(timeouts[worker.id]);
+});
+cluster.on('exit', function(worker, code, signal) {
+  clearTimeout(timeouts[worker.id]);
+  errorMsg();
+});
+

Event: 'online'#

+
    +
  • worker Worker object
  • +
+

After forking a new worker, the worker should respond with a online message. +When the master receives a online message it will emit such event. +The difference between 'fork' and 'online' is that fork is emitted when the +master tries to fork a worker, and 'online' is emitted when the worker is +being executed. + +

+
cluster.on('online', function(worker) {
+  console.log("Yay, the worker responded after it was forked");
+});
+

Event: 'listening'#

+
    +
  • worker Worker object
  • +
  • address Object
  • +
+

When calling listen() from a worker, a 'listening' event is automatically assigned +to the server instance. When the server is listening a message is send to the master +where the 'listening' event is emitted. + +

+

The event handler is executed with two arguments, the worker contains the worker +object and the address object contains the following connection properties: +address, port and addressType. This is very useful if the worker is listening +on more than one address. + +

+
cluster.on('listening', function(worker, address) {
+  console.log("A worker is now connected to " + address.address + ":" + address.port);
+});
+

Event: 'disconnect'#

+
    +
  • worker Worker object
  • +
+

When a workers IPC channel has disconnected this event is emitted. This will happen +when the worker dies, usually after calling .destroy(). + +

+

When calling .disconnect(), there may be a delay between the +disconnect and exit events. This event can be used to detect if +the process is stuck in a cleanup or if there are long-living +connections. + +

+
cluster.on('disconnect', function(worker) {
+  console.log('The worker #' + worker.id + ' has disconnected');
+});
+

Event: 'exit'#

+
    +
  • worker Worker object
  • +
  • code Number the exit code, if it exited normally.
  • +
  • signal String the name of the signal (eg. 'SIGHUP') that caused +the process to be killed.
  • +
+

When any of the workers die the cluster module will emit the 'exit' event. +This can be used to restart the worker by calling fork() again. + +

+
cluster.on('exit', function(worker, code, signal) {
+  var exitCode = worker.process.exitCode;
+  console.log('worker ' + worker.process.pid + ' died ('+exitCode+'). restarting...');
+  cluster.fork();
+});
+

Event: 'setup'#

+
    +
  • worker Worker object
  • +
+

When the .setupMaster() function has been executed this event emits. +If .setupMaster() was not executed before fork() this function will +call .setupMaster() with no arguments. + +

+

cluster.setupMaster([settings])#

+
    +
  • settings Object
      +
    • exec String file path to worker file. (Default=__filename)
    • +
    • args Array string arguments passed to worker. +(Default=process.argv.slice(2))
    • +
    • silent Boolean whether or not to send output to parent's stdio. +(Default=false)
    • +
    +
  • +
+

setupMaster is used to change the default 'fork' behavior. The new settings +are effective immediately and permanently, they cannot be changed later on. + +

+

Example: + +

+
var cluster = require("cluster");
+cluster.setupMaster({
+  exec : "worker.js",
+  args : ["--use", "https"],
+  silent : true
+});
+cluster.fork();
+

cluster.fork([env])#

+
    +
  • env Object Key/value pairs to add to child process environment.
  • +
  • return Worker object
  • +
+

Spawn a new worker process. This can only be called from the master process. + +

+

cluster.disconnect([callback])#

+
    +
  • callback Function called when all workers are disconnected and handlers are closed
  • +
+

When calling this method, all workers will commit a graceful suicide. When they are +disconnected all internal handlers will be closed, allowing the master process to +die graceful if no other event is waiting. + +

+

The method takes an optional callback argument which will be called when finished. + +

+

cluster.worker#

+
    +
  • Object
  • +
+

A reference to the current worker object. Not available in the master process. + +

+
var cluster = require('cluster');
+
+if (cluster.isMaster) {
+  console.log('I am master');
+  cluster.fork();
+  cluster.fork();
+} else if (cluster.isWorker) {
+  console.log('I am worker #' + cluster.worker.id);
+}
+

cluster.workers#

+
    +
  • Object
  • +
+

A hash that stores the active worker objects, keyed by id field. Makes it +easy to loop through all the workers. It is only available in the master +process. + +

+
// Go through all workers
+function eachWorker(callback) {
+  for (var id in cluster.workers) {
+    callback(cluster.workers[id]);
+  }
+}
+eachWorker(function(worker) {
+  worker.send('big announcement to all workers');
+});
+

Should you wish to reference a worker over a communication channel, using +the worker's unique id is the easiest way to find the worker. + +

+
socket.on('data', function(id) {
+  var worker = cluster.workers[id];
+});
+

Class: Worker#

+

A Worker object contains all public information and method about a worker. +In the master it can be obtained using cluster.workers. In a worker +it can be obtained using cluster.worker. + +

+

worker.id#

+
    +
  • String
  • +
+

Each new worker is given its own unique id, this id is stored in the +id. + +

+

While a worker is alive, this is the key that indexes it in +cluster.workers + +

+

worker.process#

+
    +
  • ChildProcess object
  • +
+

All workers are created using child_process.fork(), the returned object +from this function is stored in process. + +

+

See: Child Process module + +

+

worker.suicide#

+
    +
  • Boolean
  • +
+

This property is a boolean. It is set when a worker dies after calling .destroy() +or immediately after calling the .disconnect() method. Until then it is undefined. + +

+

worker.send(message, [sendHandle])#

+
    +
  • message Object
  • +
  • sendHandle Handle object
  • +
+

This function is equal to the send methods provided by +child_process.fork(). In the master you should use this function to +send a message to a specific worker. However in a worker you can also use +process.send(message), since this is the same function. + +

+

This example will echo back all messages from the master: + +

+
if (cluster.isMaster) {
+  var worker = cluster.fork();
+  worker.send('hi there');
+
+} else if (cluster.isWorker) {
+  process.on('message', function(msg) {
+    process.send(msg);
+  });
+}
+

worker.destroy()#

+

This function will kill the worker, and inform the master to not spawn a +new worker. The boolean suicide lets you distinguish between voluntary +and accidental exit. + +

+
cluster.on('exit', function(worker, code, signal) {
+  if (worker.suicide === true) {
+    console.log('Oh, it was just suicide\' – no need to worry').
+  }
+});
+
+// destroy worker
+worker.destroy();
+

worker.disconnect()#

+

When calling this function the worker will no longer accept new connections, but +they will be handled by any other listening worker. Existing connection will be +allowed to exit as usual. When no more connections exist, the IPC channel to the worker +will close allowing it to die graceful. When the IPC channel is closed the disconnect +event will emit, this is then followed by the exit event, there is emitted when +the worker finally die. + +

+

Because there might be long living connections, it is useful to implement a timeout. +This example ask the worker to disconnect and after 2 seconds it will destroy the +server. An alternative would be to execute worker.destroy() after 2 seconds, but +that would normally not allow the worker to do any cleanup if needed. + +

+
if (cluster.isMaster) {
+  var worker = cluster.fork();
+  var timeout;
+
+  worker.on('listening', function(address) {
+    worker.disconnect();
+    timeout = setTimeout(function() {
+      worker.send('force kill');
+    }, 2000);
+  });
+
+  worker.on('disconnect', function() {
+    clearTimeout(timeout);
+  });
+
+} else if (cluster.isWorker) {
+  var net = require('net');
+  var server = net.createServer(function(socket) {
+    // connection never end
+  });
+
+  server.listen(8000);
+
+  server.on('close', function() {
+    // cleanup
+  });
+
+  process.on('message', function(msg) {
+    if (msg === 'force kill') {
+      server.destroy();
+    }
+  });
+}
+

Event: 'message'#

+
    +
  • message Object
  • +
+

This event is the same as the one provided by child_process.fork(). +In the master you should use this event, however in a worker you can also use +process.on('message') + +

+

As an example, here is a cluster that keeps count of the number of requests +in the master process using the message system: + +

+
var cluster = require('cluster');
+var http = require('http');
+
+if (cluster.isMaster) {
+
+  // Keep track of http requests
+  var numReqs = 0;
+  setInterval(function() {
+    console.log("numReqs =", numReqs);
+  }, 1000);
+
+  // Count requestes
+  function messageHandler(msg) {
+    if (msg.cmd && msg.cmd == 'notifyRequest') {
+      numReqs += 1;
+    }
+  }
+
+  // Start workers and listen for messages containing notifyRequest
+  var numCPUs = require('os').cpus().length;
+  for (var i = 0; i < numCPUs; i++) {
+    cluster.fork();
+  }
+
+  Object.keys(cluster.workers).forEach(function(id) {
+    cluster.workers[id].on('message', messageHandler);
+  });
+
+} else {
+
+  // Worker processes have a http server.
+  http.Server(function(req, res) {
+    res.writeHead(200);
+    res.end("hello world\n");
+
+    // notify master about the request
+    process.send({ cmd: 'notifyRequest' });
+  }).listen(8000);
+}
+

Event: 'online'#

+

Same as the cluster.on('online') event, but emits only when the state change +on the specified worker. + +

+
cluster.fork().on('online', function() {
+  // Worker is online
+};
+

Event: 'listening'#

+
    +
  • address Object
  • +
+

Same as the cluster.on('listening') event, but emits only when the state change +on the specified worker. + +

+
cluster.fork().on('listening', function(address) {
+  // Worker is listening
+};
+

Event: 'disconnect'#

+

Same as the cluster.on('disconnect') event, but emits only when the state change +on the specified worker. + +

+
cluster.fork().on('disconnect', function() {
+  // Worker has disconnected
+};
+

Event: 'exit'#

+
    +
  • code Number the exit code, if it exited normally.
  • +
  • signal String the name of the signal (eg. 'SIGHUP') that caused +the process to be killed.
  • +
+

Emitted by the individual worker instance, when the underlying child process +is terminated. See child_process event: 'exit'. + +

+
var worker = cluster.fork();
+worker.on('exit', function(code, signal) {
+  if( signal ) {
+    console.log("worker was killed by signal: "+signal);
+  } else if( code !== 0 ) {
+    console.log("worker exited with error code: "+code);
+  } else {
+    console.log("worker success!");
+  }
+};
+ +
+
+
+ + + + + + + + + diff --git a/node-v0.8.14/doc/api/cluster.json b/node-v0.8.14/doc/api/cluster.json new file mode 100644 index 0000000..51aa7ec --- /dev/null +++ b/node-v0.8.14/doc/api/cluster.json @@ -0,0 +1,346 @@ +{ + "source": "doc/api/cluster.markdown", + "modules": [ + { + "textRaw": "Cluster", + "name": "cluster", + "stability": 1, + "stabilityText": "Experimental", + "desc": "

A single instance of Node runs in a single thread. To take advantage of\nmulti-core systems the user will sometimes want to launch a cluster of Node\nprocesses to handle the load.\n\n

\n

The cluster module allows you to easily create a network of processes that\nall share server ports.\n\n

\n
var cluster = require('cluster');\nvar http = require('http');\nvar numCPUs = require('os').cpus().length;\n\nif (cluster.isMaster) {\n  // Fork workers.\n  for (var i = 0; i < numCPUs; i++) {\n    cluster.fork();\n  }\n\n  cluster.on('exit', function(worker, code, signal) {\n    console.log('worker ' + worker.process.pid + ' died');\n  });\n} else {\n  // Workers can share any TCP connection\n  // In this case its a HTTP server\n  http.createServer(function(req, res) {\n    res.writeHead(200);\n    res.end("hello world\\n");\n  }).listen(8000);\n}
\n

Running node will now share port 8000 between the workers:\n\n

\n
% node server.js\nWorker 2438 online\nWorker 2437 online
\n

This feature was introduced recently, and may change in future versions.\nPlease try it out and provide feedback.\n\n

\n

Also note that, on Windows, it is not yet possible to set up a named pipe\nserver in a worker.\n\n

\n", + "miscs": [ + { + "textRaw": "How It Works", + "name": "How It Works", + "type": "misc", + "desc": "

The worker processes are spawned using the child_process.fork method,\nso that they can communicate with the parent via IPC and pass server\nhandles back and forth.\n\n

\n

When you call server.listen(...) in a worker, it serializes the\narguments and passes the request to the master process. If the master\nprocess already has a listening server matching the worker's\nrequirements, then it passes the handle to the worker. If it does not\nalready have a listening server matching that requirement, then it will\ncreate one, and pass the handle to the child.\n\n

\n

This causes potentially surprising behavior in three edge cases:\n\n

\n
    \n
  1. server.listen({fd: 7}) Because the message is passed to the master,\nfile descriptor 7 in the parent will be listened on, and the\nhandle passed to the worker, rather than listening to the worker's\nidea of what the number 7 file descriptor references.
  2. \n
  3. server.listen(handle) Listening on handles explicitly will cause\nthe worker to use the supplied handle, rather than talk to the master\nprocess. If the worker already has the handle, then it's presumed\nthat you know what you are doing.
  4. \n
  5. server.listen(0) Normally, this will cause servers to listen on a\nrandom port. However, in a cluster, each worker will receive the\nsame "random" port each time they do listen(0). In essence, the\nport is random the first time, but predictable thereafter. If you\nwant to listen on a unique port, generate a port number based on the\ncluster worker ID.
  6. \n
\n

When multiple processes are all accept()ing on the same underlying\nresource, the operating system load-balances across them very\nefficiently. There is no routing logic in Node.js, or in your program,\nand no shared state between the workers. Therefore, it is important to\ndesign your program such that it does not rely too heavily on in-memory\ndata objects for things like sessions and login.\n\n

\n

Because workers are all separate processes, they can be killed or\nre-spawned depending on your program's needs, without affecting other\nworkers. As long as there are some workers still alive, the server will\ncontinue to accept connections. Node does not automatically manage the\nnumber of workers for you, however. It is your responsibility to manage\nthe worker pool for your application's needs.\n\n

\n" + } + ], + "properties": [ + { + "textRaw": "`settings` {Object} ", + "name": "settings", + "options": [ + { + "textRaw": "`exec` {String} file path to worker file. (Default=`__filename`) ", + "name": "exec", + "default": "__filename", + "type": "String", + "desc": "file path to worker file." + }, + { + "textRaw": "`args` {Array} string arguments passed to worker. (Default=`process.argv.slice(2)`) ", + "name": "args", + "default": "process.argv.slice(2)", + "type": "Array", + "desc": "string arguments passed to worker." + }, + { + "textRaw": "`silent` {Boolean} whether or not to send output to parent's stdio. (Default=`false`) ", + "name": "silent", + "default": "false", + "type": "Boolean", + "desc": "whether or not to send output to parent's stdio." + } + ], + "desc": "

All settings set by the .setupMaster is stored in this settings object.\nThis object is not supposed to be change or set manually, by you.\n\n

\n" + }, + { + "textRaw": "`isMaster` {Boolean} ", + "name": "isMaster", + "desc": "

True if the process is a master. This is determined\nby the process.env.NODE_UNIQUE_ID. If process.env.NODE_UNIQUE_ID is\nundefined, then isMaster is true.\n\n

\n" + }, + { + "textRaw": "`isWorker` {Boolean} ", + "name": "isWorker", + "desc": "

This boolean flag is true if the process is a worker forked from a master.\nIf the process.env.NODE_UNIQUE_ID is set to a value, then\nisWorker is true.\n\n

\n" + }, + { + "textRaw": "`worker` {Object} ", + "name": "worker", + "desc": "

A reference to the current worker object. Not available in the master process.\n\n

\n
var cluster = require('cluster');\n\nif (cluster.isMaster) {\n  console.log('I am master');\n  cluster.fork();\n  cluster.fork();\n} else if (cluster.isWorker) {\n  console.log('I am worker #' + cluster.worker.id);\n}
\n" + }, + { + "textRaw": "`workers` {Object} ", + "name": "workers", + "desc": "

A hash that stores the active worker objects, keyed by id field. Makes it\neasy to loop through all the workers. It is only available in the master\nprocess.\n\n

\n
// Go through all workers\nfunction eachWorker(callback) {\n  for (var id in cluster.workers) {\n    callback(cluster.workers[id]);\n  }\n}\neachWorker(function(worker) {\n  worker.send('big announcement to all workers');\n});
\n

Should you wish to reference a worker over a communication channel, using\nthe worker's unique id is the easiest way to find the worker.\n\n

\n
socket.on('data', function(id) {\n  var worker = cluster.workers[id];\n});
\n" + } + ], + "events": [ + { + "textRaw": "Event: 'fork'", + "type": "event", + "name": "fork", + "params": [], + "desc": "

When a new worker is forked the cluster module will emit a 'fork' event.\nThis can be used to log worker activity, and create you own timeout.\n\n

\n
var timeouts = [];\nfunction errorMsg() {\n  console.error("Something must be wrong with the connection ...");\n}\n\ncluster.on('fork', function(worker) {\n  timeouts[worker.id] = setTimeout(errorMsg, 2000);\n});\ncluster.on('listening', function(worker, address) {\n  clearTimeout(timeouts[worker.id]);\n});\ncluster.on('exit', function(worker, code, signal) {\n  clearTimeout(timeouts[worker.id]);\n  errorMsg();\n});
\n" + }, + { + "textRaw": "Event: 'online'", + "type": "event", + "name": "online", + "params": [], + "desc": "

After forking a new worker, the worker should respond with a online message.\nWhen the master receives a online message it will emit such event.\nThe difference between 'fork' and 'online' is that fork is emitted when the\nmaster tries to fork a worker, and 'online' is emitted when the worker is\nbeing executed.\n\n

\n
cluster.on('online', function(worker) {\n  console.log("Yay, the worker responded after it was forked");\n});
\n" + }, + { + "textRaw": "Event: 'listening'", + "type": "event", + "name": "listening", + "params": [], + "desc": "

When calling listen() from a worker, a 'listening' event is automatically assigned\nto the server instance. When the server is listening a message is send to the master\nwhere the 'listening' event is emitted.\n\n

\n

The event handler is executed with two arguments, the worker contains the worker\nobject and the address object contains the following connection properties:\naddress, port and addressType. This is very useful if the worker is listening\non more than one address.\n\n

\n
cluster.on('listening', function(worker, address) {\n  console.log("A worker is now connected to " + address.address + ":" + address.port);\n});
\n" + }, + { + "textRaw": "Event: 'disconnect'", + "type": "event", + "name": "disconnect", + "params": [], + "desc": "

When a workers IPC channel has disconnected this event is emitted. This will happen\nwhen the worker dies, usually after calling .destroy().\n\n

\n

When calling .disconnect(), there may be a delay between the\ndisconnect and exit events. This event can be used to detect if\nthe process is stuck in a cleanup or if there are long-living\nconnections.\n\n

\n
cluster.on('disconnect', function(worker) {\n  console.log('The worker #' + worker.id + ' has disconnected');\n});
\n" + }, + { + "textRaw": "Event: 'exit'", + "type": "event", + "name": "exit", + "params": [], + "desc": "

When any of the workers die the cluster module will emit the 'exit' event.\nThis can be used to restart the worker by calling fork() again.\n\n

\n
cluster.on('exit', function(worker, code, signal) {\n  var exitCode = worker.process.exitCode;\n  console.log('worker ' + worker.process.pid + ' died ('+exitCode+'). restarting...');\n  cluster.fork();\n});
\n" + }, + { + "textRaw": "Event: 'setup'", + "type": "event", + "name": "setup", + "params": [], + "desc": "

When the .setupMaster() function has been executed this event emits.\nIf .setupMaster() was not executed before fork() this function will\ncall .setupMaster() with no arguments.\n\n

\n" + } + ], + "methods": [ + { + "textRaw": "cluster.setupMaster([settings])", + "type": "method", + "name": "setupMaster", + "signatures": [ + { + "params": [ + { + "textRaw": "`settings` {Object} ", + "options": [ + { + "textRaw": "`exec` {String} file path to worker file. (Default=`__filename`) ", + "name": "exec", + "default": "__filename", + "type": "String", + "desc": "file path to worker file." + }, + { + "textRaw": "`args` {Array} string arguments passed to worker. (Default=`process.argv.slice(2)`) ", + "name": "args", + "default": "process.argv.slice(2)", + "type": "Array", + "desc": "string arguments passed to worker." + }, + { + "textRaw": "`silent` {Boolean} whether or not to send output to parent's stdio. (Default=`false`) ", + "name": "silent", + "default": "false", + "type": "Boolean", + "desc": "whether or not to send output to parent's stdio." + } + ], + "name": "settings", + "type": "Object", + "optional": true + } + ] + }, + { + "params": [ + { + "name": "settings", + "optional": true + } + ] + } + ], + "desc": "

setupMaster is used to change the default 'fork' behavior. The new settings\nare effective immediately and permanently, they cannot be changed later on.\n\n

\n

Example:\n\n

\n
var cluster = require("cluster");\ncluster.setupMaster({\n  exec : "worker.js",\n  args : ["--use", "https"],\n  silent : true\n});\ncluster.fork();
\n" + }, + { + "textRaw": "cluster.fork([env])", + "type": "method", + "name": "fork", + "signatures": [ + { + "return": { + "textRaw": "return {Worker object} ", + "name": "return", + "type": "Worker object" + }, + "params": [ + { + "textRaw": "`env` {Object} Key/value pairs to add to child process environment. ", + "name": "env", + "type": "Object", + "desc": "Key/value pairs to add to child process environment.", + "optional": true + } + ] + }, + { + "params": [ + { + "name": "env", + "optional": true + } + ] + } + ], + "desc": "

Spawn a new worker process. This can only be called from the master process.\n\n

\n" + }, + { + "textRaw": "cluster.disconnect([callback])", + "type": "method", + "name": "disconnect", + "signatures": [ + { + "params": [ + { + "textRaw": "`callback` {Function} called when all workers are disconnected and handlers are closed ", + "name": "callback", + "type": "Function", + "desc": "called when all workers are disconnected and handlers are closed", + "optional": true + } + ] + }, + { + "params": [ + { + "name": "callback", + "optional": true + } + ] + } + ], + "desc": "

When calling this method, all workers will commit a graceful suicide. When they are\ndisconnected all internal handlers will be closed, allowing the master process to\ndie graceful if no other event is waiting.\n\n

\n

The method takes an optional callback argument which will be called when finished.\n\n

\n" + } + ], + "classes": [ + { + "textRaw": "Class: Worker", + "type": "class", + "name": "Worker", + "desc": "

A Worker object contains all public information and method about a worker.\nIn the master it can be obtained using cluster.workers. In a worker\nit can be obtained using cluster.worker.\n\n

\n", + "properties": [ + { + "textRaw": "`id` {String} ", + "name": "id", + "desc": "

Each new worker is given its own unique id, this id is stored in the\nid.\n\n

\n

While a worker is alive, this is the key that indexes it in\ncluster.workers\n\n

\n" + }, + { + "textRaw": "`process` {ChildProcess object} ", + "name": "process", + "desc": "

All workers are created using child_process.fork(), the returned object\nfrom this function is stored in process.\n\n

\n

See: Child Process module\n\n

\n" + }, + { + "textRaw": "`suicide` {Boolean} ", + "name": "suicide", + "desc": "

This property is a boolean. It is set when a worker dies after calling .destroy()\nor immediately after calling the .disconnect() method. Until then it is undefined.\n\n

\n" + } + ], + "methods": [ + { + "textRaw": "worker.send(message, [sendHandle])", + "type": "method", + "name": "send", + "signatures": [ + { + "params": [ + { + "textRaw": "`message` {Object} ", + "name": "message", + "type": "Object" + }, + { + "textRaw": "`sendHandle` {Handle object} ", + "name": "sendHandle", + "type": "Handle object", + "optional": true + } + ] + }, + { + "params": [ + { + "name": "message" + }, + { + "name": "sendHandle", + "optional": true + } + ] + } + ], + "desc": "

This function is equal to the send methods provided by\nchild_process.fork(). In the master you should use this function to\nsend a message to a specific worker. However in a worker you can also use\nprocess.send(message), since this is the same function.\n\n

\n

This example will echo back all messages from the master:\n\n

\n
if (cluster.isMaster) {\n  var worker = cluster.fork();\n  worker.send('hi there');\n\n} else if (cluster.isWorker) {\n  process.on('message', function(msg) {\n    process.send(msg);\n  });\n}
\n" + }, + { + "textRaw": "worker.destroy()", + "type": "method", + "name": "destroy", + "desc": "

This function will kill the worker, and inform the master to not spawn a\nnew worker. The boolean suicide lets you distinguish between voluntary\nand accidental exit.\n\n

\n
cluster.on('exit', function(worker, code, signal) {\n  if (worker.suicide === true) {\n    console.log('Oh, it was just suicide\\' – no need to worry').\n  }\n});\n\n// destroy worker\nworker.destroy();
\n", + "signatures": [ + { + "params": [] + } + ] + }, + { + "textRaw": "worker.disconnect()", + "type": "method", + "name": "disconnect", + "desc": "

When calling this function the worker will no longer accept new connections, but\nthey will be handled by any other listening worker. Existing connection will be\nallowed to exit as usual. When no more connections exist, the IPC channel to the worker\nwill close allowing it to die graceful. When the IPC channel is closed the disconnect\nevent will emit, this is then followed by the exit event, there is emitted when\nthe worker finally die.\n\n

\n

Because there might be long living connections, it is useful to implement a timeout.\nThis example ask the worker to disconnect and after 2 seconds it will destroy the\nserver. An alternative would be to execute worker.destroy() after 2 seconds, but\nthat would normally not allow the worker to do any cleanup if needed.\n\n

\n
if (cluster.isMaster) {\n  var worker = cluster.fork();\n  var timeout;\n\n  worker.on('listening', function(address) {\n    worker.disconnect();\n    timeout = setTimeout(function() {\n      worker.send('force kill');\n    }, 2000);\n  });\n\n  worker.on('disconnect', function() {\n    clearTimeout(timeout);\n  });\n\n} else if (cluster.isWorker) {\n  var net = require('net');\n  var server = net.createServer(function(socket) {\n    // connection never end\n  });\n\n  server.listen(8000);\n\n  server.on('close', function() {\n    // cleanup\n  });\n\n  process.on('message', function(msg) {\n    if (msg === 'force kill') {\n      server.destroy();\n    }\n  });\n}
\n", + "signatures": [ + { + "params": [] + } + ] + } + ], + "events": [ + { + "textRaw": "Event: 'message'", + "type": "event", + "name": "message", + "params": [], + "desc": "

This event is the same as the one provided by child_process.fork().\nIn the master you should use this event, however in a worker you can also use\nprocess.on('message')\n\n

\n

As an example, here is a cluster that keeps count of the number of requests\nin the master process using the message system:\n\n

\n
var cluster = require('cluster');\nvar http = require('http');\n\nif (cluster.isMaster) {\n\n  // Keep track of http requests\n  var numReqs = 0;\n  setInterval(function() {\n    console.log("numReqs =", numReqs);\n  }, 1000);\n\n  // Count requestes\n  function messageHandler(msg) {\n    if (msg.cmd && msg.cmd == 'notifyRequest') {\n      numReqs += 1;\n    }\n  }\n\n  // Start workers and listen for messages containing notifyRequest\n  var numCPUs = require('os').cpus().length;\n  for (var i = 0; i < numCPUs; i++) {\n    cluster.fork();\n  }\n\n  Object.keys(cluster.workers).forEach(function(id) {\n    cluster.workers[id].on('message', messageHandler);\n  });\n\n} else {\n\n  // Worker processes have a http server.\n  http.Server(function(req, res) {\n    res.writeHead(200);\n    res.end("hello world\\n");\n\n    // notify master about the request\n    process.send({ cmd: 'notifyRequest' });\n  }).listen(8000);\n}
\n" + }, + { + "textRaw": "Event: 'online'", + "type": "event", + "name": "online", + "desc": "

Same as the cluster.on('online') event, but emits only when the state change\non the specified worker.\n\n

\n
cluster.fork().on('online', function() {\n  // Worker is online\n};
\n", + "params": [] + }, + { + "textRaw": "Event: 'listening'", + "type": "event", + "name": "listening", + "params": [], + "desc": "

Same as the cluster.on('listening') event, but emits only when the state change\non the specified worker.\n\n

\n
cluster.fork().on('listening', function(address) {\n  // Worker is listening\n};
\n" + }, + { + "textRaw": "Event: 'disconnect'", + "type": "event", + "name": "disconnect", + "desc": "

Same as the cluster.on('disconnect') event, but emits only when the state change\non the specified worker.\n\n

\n
cluster.fork().on('disconnect', function() {\n  // Worker has disconnected\n};
\n", + "params": [] + }, + { + "textRaw": "Event: 'exit'", + "type": "event", + "name": "exit", + "params": [], + "desc": "

Emitted by the individual worker instance, when the underlying child process\nis terminated. See child_process event: 'exit'.\n\n

\n
var worker = cluster.fork();\nworker.on('exit', function(code, signal) {\n  if( signal ) {\n    console.log("worker was killed by signal: "+signal);\n  } else if( code !== 0 ) {\n    console.log("worker exited with error code: "+code);\n  } else {\n    console.log("worker success!");\n  }\n};
\n" + } + ] + } + ], + "type": "module", + "displayName": "Cluster" + } + ] +} diff --git a/node-v0.8.14/doc/api/cluster.markdown b/node-v0.8.14/doc/api/cluster.markdown new file mode 100644 index 0000000..79aa790 --- /dev/null +++ b/node-v0.8.14/doc/api/cluster.markdown @@ -0,0 +1,512 @@ +# Cluster + + Stability: 1 - Experimental + +A single instance of Node runs in a single thread. To take advantage of +multi-core systems the user will sometimes want to launch a cluster of Node +processes to handle the load. + +The cluster module allows you to easily create a network of processes that +all share server ports. + + var cluster = require('cluster'); + var http = require('http'); + var numCPUs = require('os').cpus().length; + + if (cluster.isMaster) { + // Fork workers. + for (var i = 0; i < numCPUs; i++) { + cluster.fork(); + } + + cluster.on('exit', function(worker, code, signal) { + console.log('worker ' + worker.process.pid + ' died'); + }); + } else { + // Workers can share any TCP connection + // In this case its a HTTP server + http.createServer(function(req, res) { + res.writeHead(200); + res.end("hello world\n"); + }).listen(8000); + } + +Running node will now share port 8000 between the workers: + + % node server.js + Worker 2438 online + Worker 2437 online + + +This feature was introduced recently, and may change in future versions. +Please try it out and provide feedback. + +Also note that, on Windows, it is not yet possible to set up a named pipe +server in a worker. + +## How It Works + + + +The worker processes are spawned using the `child_process.fork` method, +so that they can communicate with the parent via IPC and pass server +handles back and forth. + +When you call `server.listen(...)` in a worker, it serializes the +arguments and passes the request to the master process. If the master +process already has a listening server matching the worker's +requirements, then it passes the handle to the worker. If it does not +already have a listening server matching that requirement, then it will +create one, and pass the handle to the child. + +This causes potentially surprising behavior in three edge cases: + +1. `server.listen({fd: 7})` Because the message is passed to the master, + file descriptor 7 **in the parent** will be listened on, and the + handle passed to the worker, rather than listening to the worker's + idea of what the number 7 file descriptor references. +2. `server.listen(handle)` Listening on handles explicitly will cause + the worker to use the supplied handle, rather than talk to the master + process. If the worker already has the handle, then it's presumed + that you know what you are doing. +3. `server.listen(0)` Normally, this will cause servers to listen on a + random port. However, in a cluster, each worker will receive the + same "random" port each time they do `listen(0)`. In essence, the + port is random the first time, but predictable thereafter. If you + want to listen on a unique port, generate a port number based on the + cluster worker ID. + +When multiple processes are all `accept()`ing on the same underlying +resource, the operating system load-balances across them very +efficiently. There is no routing logic in Node.js, or in your program, +and no shared state between the workers. Therefore, it is important to +design your program such that it does not rely too heavily on in-memory +data objects for things like sessions and login. + +Because workers are all separate processes, they can be killed or +re-spawned depending on your program's needs, without affecting other +workers. As long as there are some workers still alive, the server will +continue to accept connections. Node does not automatically manage the +number of workers for you, however. It is your responsibility to manage +the worker pool for your application's needs. + +## cluster.settings + +* {Object} + * `exec` {String} file path to worker file. (Default=`__filename`) + * `args` {Array} string arguments passed to worker. + (Default=`process.argv.slice(2)`) + * `silent` {Boolean} whether or not to send output to parent's stdio. + (Default=`false`) + +All settings set by the `.setupMaster` is stored in this settings object. +This object is not supposed to be change or set manually, by you. + +## cluster.isMaster + +* {Boolean} + +True if the process is a master. This is determined +by the `process.env.NODE_UNIQUE_ID`. If `process.env.NODE_UNIQUE_ID` is +undefined, then `isMaster` is `true`. + +## cluster.isWorker + +* {Boolean} + +This boolean flag is true if the process is a worker forked from a master. +If the `process.env.NODE_UNIQUE_ID` is set to a value, then +`isWorker` is `true`. + +## Event: 'fork' + +* `worker` {Worker object} + +When a new worker is forked the cluster module will emit a 'fork' event. +This can be used to log worker activity, and create you own timeout. + + var timeouts = []; + function errorMsg() { + console.error("Something must be wrong with the connection ..."); + } + + cluster.on('fork', function(worker) { + timeouts[worker.id] = setTimeout(errorMsg, 2000); + }); + cluster.on('listening', function(worker, address) { + clearTimeout(timeouts[worker.id]); + }); + cluster.on('exit', function(worker, code, signal) { + clearTimeout(timeouts[worker.id]); + errorMsg(); + }); + +## Event: 'online' + +* `worker` {Worker object} + +After forking a new worker, the worker should respond with a online message. +When the master receives a online message it will emit such event. +The difference between 'fork' and 'online' is that fork is emitted when the +master tries to fork a worker, and 'online' is emitted when the worker is +being executed. + + cluster.on('online', function(worker) { + console.log("Yay, the worker responded after it was forked"); + }); + +## Event: 'listening' + +* `worker` {Worker object} +* `address` {Object} + +When calling `listen()` from a worker, a 'listening' event is automatically assigned +to the server instance. When the server is listening a message is send to the master +where the 'listening' event is emitted. + +The event handler is executed with two arguments, the `worker` contains the worker +object and the `address` object contains the following connection properties: +`address`, `port` and `addressType`. This is very useful if the worker is listening +on more than one address. + + cluster.on('listening', function(worker, address) { + console.log("A worker is now connected to " + address.address + ":" + address.port); + }); + +## Event: 'disconnect' + +* `worker` {Worker object} + +When a workers IPC channel has disconnected this event is emitted. This will happen +when the worker dies, usually after calling `.destroy()`. + +When calling `.disconnect()`, there may be a delay between the +`disconnect` and `exit` events. This event can be used to detect if +the process is stuck in a cleanup or if there are long-living +connections. + + cluster.on('disconnect', function(worker) { + console.log('The worker #' + worker.id + ' has disconnected'); + }); + +## Event: 'exit' + +* `worker` {Worker object} +* `code` {Number} the exit code, if it exited normally. +* `signal` {String} the name of the signal (eg. `'SIGHUP'`) that caused + the process to be killed. + +When any of the workers die the cluster module will emit the 'exit' event. +This can be used to restart the worker by calling `fork()` again. + + cluster.on('exit', function(worker, code, signal) { + var exitCode = worker.process.exitCode; + console.log('worker ' + worker.process.pid + ' died ('+exitCode+'). restarting...'); + cluster.fork(); + }); + +## Event: 'setup' + +* `worker` {Worker object} + +When the `.setupMaster()` function has been executed this event emits. +If `.setupMaster()` was not executed before `fork()` this function will +call `.setupMaster()` with no arguments. + +## cluster.setupMaster([settings]) + +* `settings` {Object} + * `exec` {String} file path to worker file. (Default=`__filename`) + * `args` {Array} string arguments passed to worker. + (Default=`process.argv.slice(2)`) + * `silent` {Boolean} whether or not to send output to parent's stdio. + (Default=`false`) + +`setupMaster` is used to change the default 'fork' behavior. The new settings +are effective immediately and permanently, they cannot be changed later on. + +Example: + + var cluster = require("cluster"); + cluster.setupMaster({ + exec : "worker.js", + args : ["--use", "https"], + silent : true + }); + cluster.fork(); + +## cluster.fork([env]) + +* `env` {Object} Key/value pairs to add to child process environment. +* return {Worker object} + +Spawn a new worker process. This can only be called from the master process. + +## cluster.disconnect([callback]) + +* `callback` {Function} called when all workers are disconnected and handlers are closed + +When calling this method, all workers will commit a graceful suicide. When they are +disconnected all internal handlers will be closed, allowing the master process to +die graceful if no other event is waiting. + +The method takes an optional callback argument which will be called when finished. + +## cluster.worker + +* {Object} + +A reference to the current worker object. Not available in the master process. + + var cluster = require('cluster'); + + if (cluster.isMaster) { + console.log('I am master'); + cluster.fork(); + cluster.fork(); + } else if (cluster.isWorker) { + console.log('I am worker #' + cluster.worker.id); + } + +## cluster.workers + +* {Object} + +A hash that stores the active worker objects, keyed by `id` field. Makes it +easy to loop through all the workers. It is only available in the master +process. + + // Go through all workers + function eachWorker(callback) { + for (var id in cluster.workers) { + callback(cluster.workers[id]); + } + } + eachWorker(function(worker) { + worker.send('big announcement to all workers'); + }); + +Should you wish to reference a worker over a communication channel, using +the worker's unique id is the easiest way to find the worker. + + socket.on('data', function(id) { + var worker = cluster.workers[id]; + }); + +## Class: Worker + +A Worker object contains all public information and method about a worker. +In the master it can be obtained using `cluster.workers`. In a worker +it can be obtained using `cluster.worker`. + +### worker.id + +* {String} + +Each new worker is given its own unique id, this id is stored in the +`id`. + +While a worker is alive, this is the key that indexes it in +cluster.workers + +### worker.process + +* {ChildProcess object} + +All workers are created using `child_process.fork()`, the returned object +from this function is stored in process. + +See: [Child Process module](child_process.html) + +### worker.suicide + +* {Boolean} + +This property is a boolean. It is set when a worker dies after calling `.destroy()` +or immediately after calling the `.disconnect()` method. Until then it is `undefined`. + +### worker.send(message, [sendHandle]) + +* `message` {Object} +* `sendHandle` {Handle object} + +This function is equal to the send methods provided by +`child_process.fork()`. In the master you should use this function to +send a message to a specific worker. However in a worker you can also use +`process.send(message)`, since this is the same function. + +This example will echo back all messages from the master: + + if (cluster.isMaster) { + var worker = cluster.fork(); + worker.send('hi there'); + + } else if (cluster.isWorker) { + process.on('message', function(msg) { + process.send(msg); + }); + } + +### worker.destroy() + +This function will kill the worker, and inform the master to not spawn a +new worker. The boolean `suicide` lets you distinguish between voluntary +and accidental exit. + + cluster.on('exit', function(worker, code, signal) { + if (worker.suicide === true) { + console.log('Oh, it was just suicide\' – no need to worry'). + } + }); + + // destroy worker + worker.destroy(); + + +### worker.disconnect() + +When calling this function the worker will no longer accept new connections, but +they will be handled by any other listening worker. Existing connection will be +allowed to exit as usual. When no more connections exist, the IPC channel to the worker +will close allowing it to die graceful. When the IPC channel is closed the `disconnect` +event will emit, this is then followed by the `exit` event, there is emitted when +the worker finally die. + +Because there might be long living connections, it is useful to implement a timeout. +This example ask the worker to disconnect and after 2 seconds it will destroy the +server. An alternative would be to execute `worker.destroy()` after 2 seconds, but +that would normally not allow the worker to do any cleanup if needed. + + if (cluster.isMaster) { + var worker = cluster.fork(); + var timeout; + + worker.on('listening', function(address) { + worker.disconnect(); + timeout = setTimeout(function() { + worker.send('force kill'); + }, 2000); + }); + + worker.on('disconnect', function() { + clearTimeout(timeout); + }); + + } else if (cluster.isWorker) { + var net = require('net'); + var server = net.createServer(function(socket) { + // connection never end + }); + + server.listen(8000); + + server.on('close', function() { + // cleanup + }); + + process.on('message', function(msg) { + if (msg === 'force kill') { + server.destroy(); + } + }); + } + +### Event: 'message' + +* `message` {Object} + +This event is the same as the one provided by `child_process.fork()`. +In the master you should use this event, however in a worker you can also use +`process.on('message')` + +As an example, here is a cluster that keeps count of the number of requests +in the master process using the message system: + + var cluster = require('cluster'); + var http = require('http'); + + if (cluster.isMaster) { + + // Keep track of http requests + var numReqs = 0; + setInterval(function() { + console.log("numReqs =", numReqs); + }, 1000); + + // Count requestes + function messageHandler(msg) { + if (msg.cmd && msg.cmd == 'notifyRequest') { + numReqs += 1; + } + } + + // Start workers and listen for messages containing notifyRequest + var numCPUs = require('os').cpus().length; + for (var i = 0; i < numCPUs; i++) { + cluster.fork(); + } + + Object.keys(cluster.workers).forEach(function(id) { + cluster.workers[id].on('message', messageHandler); + }); + + } else { + + // Worker processes have a http server. + http.Server(function(req, res) { + res.writeHead(200); + res.end("hello world\n"); + + // notify master about the request + process.send({ cmd: 'notifyRequest' }); + }).listen(8000); + } + +### Event: 'online' + +Same as the `cluster.on('online')` event, but emits only when the state change +on the specified worker. + + cluster.fork().on('online', function() { + // Worker is online + }; + +### Event: 'listening' + +* `address` {Object} + +Same as the `cluster.on('listening')` event, but emits only when the state change +on the specified worker. + + cluster.fork().on('listening', function(address) { + // Worker is listening + }; + +### Event: 'disconnect' + +Same as the `cluster.on('disconnect')` event, but emits only when the state change +on the specified worker. + + cluster.fork().on('disconnect', function() { + // Worker has disconnected + }; + +### Event: 'exit' + +* `code` {Number} the exit code, if it exited normally. +* `signal` {String} the name of the signal (eg. `'SIGHUP'`) that caused + the process to be killed. + +Emitted by the individual worker instance, when the underlying child process +is terminated. See [child_process event: 'exit'](child_process.html#child_process_event_exit). + + var worker = cluster.fork(); + worker.on('exit', function(code, signal) { + if( signal ) { + console.log("worker was killed by signal: "+signal); + } else if( code !== 0 ) { + console.log("worker exited with error code: "+code); + } else { + console.log("worker success!"); + } + }; diff --git a/node-v0.8.14/doc/api/crypto.html b/node-v0.8.14/doc/api/crypto.html new file mode 100644 index 0000000..a9bf540 --- /dev/null +++ b/node-v0.8.14/doc/api/crypto.html @@ -0,0 +1,580 @@ + + + + + Crypto Node.js v0.8.14 Manual & Documentation + + + + + +
+ + + +
+
+ + +
+
+

Node.js v0.8.14 Manual & Documentation

+ +
+
+ +
+

Table of Contents

+ + +
+ +
+

Crypto#

+
Stability: 2 - Unstable; API changes are being discussed for
+future versions.  Breaking changes will be minimized.  See below.
+

Use require('crypto') to access this module. + +

+

The crypto module requires OpenSSL to be available on the underlying platform. +It offers a way of encapsulating secure credentials to be used as part +of a secure HTTPS net or http connection. + +

+

It also offers a set of wrappers for OpenSSL's hash, hmac, cipher, decipher, sign and verify methods. + +

+

crypto.createCredentials(details)#

+

Creates a credentials object, with the optional details being a dictionary with keys: + +

+
    +
  • pfx : A string or buffer holding the PFX or PKCS12 encoded private key, certificate and CA certificates
  • +
  • key : A string holding the PEM encoded private key
  • +
  • passphrase : A string of passphrase for the private key or pfx
  • +
  • cert : A string holding the PEM encoded certificate
  • +
  • ca : Either a string or list of strings of PEM encoded CA certificates to trust.
  • +
  • crl : Either a string or list of strings of PEM encoded CRLs (Certificate Revocation List)
  • +
  • ciphers: A string describing the ciphers to use or exclude. Consult +http://www.openssl.org/docs/apps/ciphers.html#CIPHER_LIST_FORMAT for details +on the format.
  • +
+

If no 'ca' details are given, then node.js will use the default publicly trusted list of CAs as given in +

+

http://mxr.mozilla.org/mozilla/source/security/nss/lib/ckfw/builtins/certdata.txt. + + +

+

crypto.createHash(algorithm)#

+

Creates and returns a hash object, a cryptographic hash with the given algorithm +which can be used to generate hash digests. + +

+

algorithm is dependent on the available algorithms supported by the version +of OpenSSL on the platform. Examples are 'sha1', 'md5', 'sha256', 'sha512', etc. +On recent releases, openssl list-message-digest-algorithms will display the available digest algorithms. + +

+

Example: this program that takes the sha1 sum of a file + +

+
var filename = process.argv[2];
+var crypto = require('crypto');
+var fs = require('fs');
+
+var shasum = crypto.createHash('sha1');
+
+var s = fs.ReadStream(filename);
+s.on('data', function(d) {
+  shasum.update(d);
+});
+
+s.on('end', function() {
+  var d = shasum.digest('hex');
+  console.log(d + '  ' + filename);
+});
+

Class: Hash#

+

The class for creating hash digests of data. + +

+

Returned by crypto.createHash. + +

+

hash.update(data, [input_encoding])#

+

Updates the hash content with the given data, the encoding of which is given +in input_encoding and can be 'utf8', 'ascii' or 'binary'. +Defaults to 'binary'. +This can be called many times with new data as it is streamed. + +

+

hash.digest([encoding])#

+

Calculates the digest of all of the passed data to be hashed. +The encoding can be 'hex', 'binary' or 'base64'. +Defaults to 'binary'. + +

+

Note: hash object can not be used after digest() method been called. + + +

+

crypto.createHmac(algorithm, key)#

+

Creates and returns a hmac object, a cryptographic hmac with the given algorithm and key. + +

+

algorithm is dependent on the available algorithms supported by OpenSSL - see createHash above. +key is the hmac key to be used. + +

+

Class: Hmac#

+

Class for creating cryptographic hmac content. + +

+

Returned by crypto.createHmac. + +

+

hmac.update(data)#

+

Update the hmac content with the given data. +This can be called many times with new data as it is streamed. + +

+

hmac.digest([encoding])#

+

Calculates the digest of all of the passed data to the hmac. +The encoding can be 'hex', 'binary' or 'base64'. +Defaults to 'binary'. + +

+

Note: hmac object can not be used after digest() method been called. + + +

+

crypto.createCipher(algorithm, password)#

+

Creates and returns a cipher object, with the given algorithm and password. + +

+

algorithm is dependent on OpenSSL, examples are 'aes192', etc. +On recent releases, openssl list-cipher-algorithms will display the +available cipher algorithms. +password is used to derive key and IV, which must be a 'binary' encoded +string or a buffer. + +

+

crypto.createCipheriv(algorithm, key, iv)#

+

Creates and returns a cipher object, with the given algorithm, key and iv. + +

+

algorithm is the same as the argument to createCipher(). +key is the raw key used by the algorithm. +iv is an initialization +vector. + +

+

key and iv must be 'binary' encoded strings or buffers. + +

+

Class: Cipher#

+

Class for encrypting data. + +

+

Returned by crypto.createCipher and crypto.createCipheriv. + +

+

cipher.update(data, [input_encoding], [output_encoding])#

+

Updates the cipher with data, the encoding of which is given in +input_encoding and can be 'utf8', 'ascii' or 'binary'. +Defaults to 'binary'. + +

+

The output_encoding specifies the output format of the enciphered data, +and can be 'binary', 'base64' or 'hex'. Defaults to 'binary'. + +

+

Returns the enciphered contents, and can be called many times with new data as it is streamed. + +

+

cipher.final([output_encoding])#

+

Returns any remaining enciphered contents, with output_encoding being one of: +'binary', 'base64' or 'hex'. Defaults to 'binary'. + +

+

Note: cipher object can not be used after final() method been called. + +

+

cipher.setAutoPadding(auto_padding=true)#

+

You can disable automatic padding of the input data to block size. If auto_padding is false, +the length of the entire input data must be a multiple of the cipher's block size or final will fail. +Useful for non-standard padding, e.g. using 0x0 instead of PKCS padding. You must call this before cipher.final. + + +

+

crypto.createDecipher(algorithm, password)#

+

Creates and returns a decipher object, with the given algorithm and key. +This is the mirror of the createCipher() above. + +

+

crypto.createDecipheriv(algorithm, key, iv)#

+

Creates and returns a decipher object, with the given algorithm, key and iv. +This is the mirror of the createCipheriv() above. + +

+

Class: Decipher#

+

Class for decrypting data. + +

+

Returned by crypto.createDecipher and crypto.createDecipheriv. + +

+

decipher.update(data, [input_encoding], [output_encoding])#

+

Updates the decipher with data, which is encoded in 'binary', 'base64' +or 'hex'. Defaults to 'binary'. + +

+

The output_decoding specifies in what format to return the deciphered +plaintext: 'binary', 'ascii' or 'utf8'. Defaults to 'binary'. + +

+

decipher.final([output_encoding])#

+

Returns any remaining plaintext which is deciphered, +with output_encoding being one of: 'binary', 'ascii' or 'utf8'. +Defaults to 'binary'. + +

+

Note: decipher object can not be used after final() method been called. + +

+

decipher.setAutoPadding(auto_padding=true)#

+

You can disable auto padding if the data has been encrypted without standard block padding to prevent +decipher.final from checking and removing it. Can only work if the input data's length is a multiple of the +ciphers block size. You must call this before streaming data to decipher.update. + +

+

crypto.createSign(algorithm)#

+

Creates and returns a signing object, with the given algorithm. +On recent OpenSSL releases, openssl list-public-key-algorithms will display +the available signing algorithms. Examples are 'RSA-SHA256'. + +

+

Class: Signer#

+

Class for generating signatures. + +

+

Returned by crypto.createSign. + +

+

signer.update(data)#

+

Updates the signer object with data. +This can be called many times with new data as it is streamed. + +

+

signer.sign(private_key, [output_format])#

+

Calculates the signature on all the updated data passed through the signer. +private_key is a string containing the PEM encoded private key for signing. + +

+

Returns the signature in output_format which can be 'binary', 'hex' or +'base64'. Defaults to 'binary'. + +

+

Note: signer object can not be used after sign() method been called. + +

+

crypto.createVerify(algorithm)#

+

Creates and returns a verification object, with the given algorithm. +This is the mirror of the signing object above. + +

+

Class: Verify#

+

Class for verifying signatures. + +

+

Returned by crypto.createVerify. + +

+

verifier.update(data)#

+

Updates the verifier object with data. +This can be called many times with new data as it is streamed. + +

+

verifier.verify(object, signature, [signature_format])#

+

Verifies the signed data by using the object and signature. object is a +string containing a PEM encoded object, which can be one of RSA public key, +DSA public key, or X.509 certificate. signature is the previously calculated +signature for the data, in the signature_format which can be 'binary', +'hex' or 'base64'. Defaults to 'binary'. + +

+

Returns true or false depending on the validity of the signature for the data and public key. + +

+

Note: verifier object can not be used after verify() method been called. + +

+

crypto.createDiffieHellman(prime_length)#

+

Creates a Diffie-Hellman key exchange object and generates a prime of the +given bit length. The generator used is 2. + +

+

crypto.createDiffieHellman(prime, [encoding])#

+

Creates a Diffie-Hellman key exchange object using the supplied prime. The +generator used is 2. Encoding can be 'binary', 'hex', or 'base64'. +Defaults to 'binary'. + +

+

Class: DiffieHellman#

+

The class for creating Diffie-Hellman key exchanges. + +

+

Returned by crypto.createDiffieHellman. + +

+

diffieHellman.generateKeys([encoding])#

+

Generates private and public Diffie-Hellman key values, and returns the +public key in the specified encoding. This key should be transferred to the +other party. Encoding can be 'binary', 'hex', or 'base64'. +Defaults to 'binary'. + +

+

diffieHellman.computeSecret(other_public_key, [input_encoding], [output_encoding])#

+

Computes the shared secret using other_public_key as the other party's +public key and returns the computed shared secret. Supplied key is +interpreted using specified input_encoding, and secret is encoded using +specified output_encoding. Encodings can be 'binary', 'hex', or +'base64'. The input encoding defaults to 'binary'. +If no output encoding is given, the input encoding is used as output encoding. + +

+

diffieHellman.getPrime([encoding])#

+

Returns the Diffie-Hellman prime in the specified encoding, which can be +'binary', 'hex', or 'base64'. Defaults to 'binary'. + +

+

diffieHellman.getGenerator([encoding])#

+

Returns the Diffie-Hellman prime in the specified encoding, which can be +'binary', 'hex', or 'base64'. Defaults to 'binary'. + +

+

diffieHellman.getPublicKey([encoding])#

+

Returns the Diffie-Hellman public key in the specified encoding, which can +be 'binary', 'hex', or 'base64'. Defaults to 'binary'. + +

+

diffieHellman.getPrivateKey([encoding])#

+

Returns the Diffie-Hellman private key in the specified encoding, which can +be 'binary', 'hex', or 'base64'. Defaults to 'binary'. + +

+

diffieHellman.setPublicKey(public_key, [encoding])#

+

Sets the Diffie-Hellman public key. Key encoding can be 'binary', 'hex', +or 'base64'. Defaults to 'binary'. + +

+

diffieHellman.setPrivateKey(public_key, [encoding])#

+

Sets the Diffie-Hellman private key. Key encoding can be 'binary', 'hex', +or 'base64'. Defaults to 'binary'. + +

+

crypto.getDiffieHellman(group_name)#

+

Creates a predefined Diffie-Hellman key exchange object. +The supported groups are: 'modp1', 'modp2', 'modp5' +(defined in RFC 2412) +and 'modp14', 'modp15', 'modp16', 'modp17', 'modp18' +(defined in RFC 3526). +The returned object mimics the interface of objects created by +crypto.createDiffieHellman() above, but +will not allow to change the keys (with +diffieHellman.setPublicKey() for example). +The advantage of using this routine is that the parties don't have to +generate nor exchange group modulus beforehand, saving both processor and +communication time. + +

+

Example (obtaining a shared secret): + +

+
var crypto = require('crypto');
+var alice = crypto.getDiffieHellman('modp5');
+var bob = crypto.getDiffieHellman('modp5');
+
+alice.generateKeys();
+bob.generateKeys();
+
+var alice_secret = alice.computeSecret(bob.getPublicKey(), 'binary', 'hex');
+var bob_secret = bob.computeSecret(alice.getPublicKey(), 'binary', 'hex');
+
+/* alice_secret and bob_secret should be the same */
+console.log(alice_secret == bob_secret);
+

crypto.pbkdf2(password, salt, iterations, keylen, callback)#

+

Asynchronous PBKDF2 applies pseudorandom function HMAC-SHA1 to derive +a key of given length from the given password, salt and iterations. +The callback gets two arguments (err, derivedKey). + +

+

crypto.randomBytes(size, [callback])#

+

Generates cryptographically strong pseudo-random data. Usage: + +

+
// async
+crypto.randomBytes(256, function(ex, buf) {
+  if (ex) throw ex;
+  console.log('Have %d bytes of random data: %s', buf.length, buf);
+});
+
+// sync
+try {
+  var buf = crypto.randomBytes(256);
+  console.log('Have %d bytes of random data: %s', buf.length, buf);
+} catch (ex) {
+  // handle error
+}
+

Proposed API Changes in Future Versions of Node#

+

The Crypto module was added to Node before there was the concept of a +unified Stream API, and before there were Buffer objects for handling +binary data. + +

+

As such, the streaming classes don't have the typical methods found on +other Node classes, and many methods accept and return Binary-encoded +strings by default rather than Buffers. + +

+

A future version of node will make Buffers the default data type. +This will be a breaking change for some use cases, but not all. + +

+

For example, if you currently use the default arguments to the Sign +class, and then pass the results to the Verify class, without ever +inspecting the data, then it will continue to work as before. Where +you now get a binary string and then present the binary string to the +Verify object, you'll get a Buffer, and present the Buffer to the +Verify object. + +

+

However, if you are doing things with the string data that will not +work properly on Buffers (such as, concatenating them, storing in +databases, etc.), or you are passing binary strings to the crypto +functions without an encoding argument, then you will need to start +providing encoding arguments to specify which encoding you'd like to +use. + +

+

Also, a Streaming API will be provided, but this will be done in such +a way as to preserve the legacy API surface. + + +

+ +
+
+
+ + + + + + + + + diff --git a/node-v0.8.14/doc/api/crypto.json b/node-v0.8.14/doc/api/crypto.json new file mode 100644 index 0000000..135f25f --- /dev/null +++ b/node-v0.8.14/doc/api/crypto.json @@ -0,0 +1,720 @@ +{ + "source": "doc/api/crypto.markdown", + "modules": [ + { + "textRaw": "Crypto", + "name": "crypto", + "desc": "
Stability: 2 - Unstable; API changes are being discussed for\nfuture versions.  Breaking changes will be minimized.  See below.
\n

Use require('crypto') to access this module.\n\n

\n

The crypto module requires OpenSSL to be available on the underlying platform.\nIt offers a way of encapsulating secure credentials to be used as part\nof a secure HTTPS net or http connection.\n\n

\n

It also offers a set of wrappers for OpenSSL's hash, hmac, cipher, decipher, sign and verify methods.\n\n

\n", + "methods": [ + { + "textRaw": "crypto.createCredentials(details)", + "type": "method", + "name": "createCredentials", + "desc": "

Creates a credentials object, with the optional details being a dictionary with keys:\n\n

\n
    \n
  • pfx : A string or buffer holding the PFX or PKCS12 encoded private key, certificate and CA certificates
  • \n
  • key : A string holding the PEM encoded private key
  • \n
  • passphrase : A string of passphrase for the private key or pfx
  • \n
  • cert : A string holding the PEM encoded certificate
  • \n
  • ca : Either a string or list of strings of PEM encoded CA certificates to trust.
  • \n
  • crl : Either a string or list of strings of PEM encoded CRLs (Certificate Revocation List)
  • \n
  • ciphers: A string describing the ciphers to use or exclude. Consult\nhttp://www.openssl.org/docs/apps/ciphers.html#CIPHER_LIST_FORMAT for details\non the format.
  • \n
\n

If no 'ca' details are given, then node.js will use the default publicly trusted list of CAs as given in\n

\n

http://mxr.mozilla.org/mozilla/source/security/nss/lib/ckfw/builtins/certdata.txt.\n\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "details" + } + ] + } + ] + }, + { + "textRaw": "crypto.createHash(algorithm)", + "type": "method", + "name": "createHash", + "desc": "

Creates and returns a hash object, a cryptographic hash with the given algorithm\nwhich can be used to generate hash digests.\n\n

\n

algorithm is dependent on the available algorithms supported by the version\nof OpenSSL on the platform. Examples are 'sha1', 'md5', 'sha256', 'sha512', etc.\nOn recent releases, openssl list-message-digest-algorithms will display the available digest algorithms.\n\n

\n

Example: this program that takes the sha1 sum of a file\n\n

\n
var filename = process.argv[2];\nvar crypto = require('crypto');\nvar fs = require('fs');\n\nvar shasum = crypto.createHash('sha1');\n\nvar s = fs.ReadStream(filename);\ns.on('data', function(d) {\n  shasum.update(d);\n});\n\ns.on('end', function() {\n  var d = shasum.digest('hex');\n  console.log(d + '  ' + filename);\n});
\n", + "signatures": [ + { + "params": [ + { + "name": "algorithm" + } + ] + } + ] + }, + { + "textRaw": "crypto.createHmac(algorithm, key)", + "type": "method", + "name": "createHmac", + "desc": "

Creates and returns a hmac object, a cryptographic hmac with the given algorithm and key.\n\n

\n

algorithm is dependent on the available algorithms supported by OpenSSL - see createHash above.\nkey is the hmac key to be used.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "algorithm" + }, + { + "name": "key" + } + ] + } + ] + }, + { + "textRaw": "crypto.createCipher(algorithm, password)", + "type": "method", + "name": "createCipher", + "desc": "

Creates and returns a cipher object, with the given algorithm and password.\n\n

\n

algorithm is dependent on OpenSSL, examples are 'aes192', etc.\nOn recent releases, openssl list-cipher-algorithms will display the\navailable cipher algorithms.\npassword is used to derive key and IV, which must be a 'binary' encoded\nstring or a buffer.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "algorithm" + }, + { + "name": "password" + } + ] + } + ] + }, + { + "textRaw": "crypto.createCipheriv(algorithm, key, iv)", + "type": "method", + "name": "createCipheriv", + "desc": "

Creates and returns a cipher object, with the given algorithm, key and iv.\n\n

\n

algorithm is the same as the argument to createCipher().\nkey is the raw key used by the algorithm.\niv is an initialization\nvector.\n\n

\n

key and iv must be 'binary' encoded strings or buffers.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "algorithm" + }, + { + "name": "key" + }, + { + "name": "iv" + } + ] + } + ] + }, + { + "textRaw": "crypto.createDecipher(algorithm, password)", + "type": "method", + "name": "createDecipher", + "desc": "

Creates and returns a decipher object, with the given algorithm and key.\nThis is the mirror of the [createCipher()][] above.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "algorithm" + }, + { + "name": "password" + } + ] + } + ] + }, + { + "textRaw": "crypto.createDecipheriv(algorithm, key, iv)", + "type": "method", + "name": "createDecipheriv", + "desc": "

Creates and returns a decipher object, with the given algorithm, key and iv.\nThis is the mirror of the [createCipheriv()][] above.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "algorithm" + }, + { + "name": "key" + }, + { + "name": "iv" + } + ] + } + ] + }, + { + "textRaw": "crypto.createSign(algorithm)", + "type": "method", + "name": "createSign", + "desc": "

Creates and returns a signing object, with the given algorithm.\nOn recent OpenSSL releases, openssl list-public-key-algorithms will display\nthe available signing algorithms. Examples are 'RSA-SHA256'.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "algorithm" + } + ] + } + ] + }, + { + "textRaw": "crypto.createVerify(algorithm)", + "type": "method", + "name": "createVerify", + "desc": "

Creates and returns a verification object, with the given algorithm.\nThis is the mirror of the signing object above.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "algorithm" + } + ] + } + ] + }, + { + "textRaw": "crypto.createDiffieHellman(prime_length)", + "type": "method", + "name": "createDiffieHellman", + "desc": "

Creates a Diffie-Hellman key exchange object and generates a prime of the\ngiven bit length. The generator used is 2.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "prime_length" + } + ] + } + ] + }, + { + "textRaw": "crypto.createDiffieHellman(prime, [encoding])", + "type": "method", + "name": "createDiffieHellman", + "desc": "

Creates a Diffie-Hellman key exchange object using the supplied prime. The\ngenerator used is 2. Encoding can be 'binary', 'hex', or 'base64'.\nDefaults to 'binary'.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "prime" + }, + { + "name": "encoding", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "crypto.getDiffieHellman(group_name)", + "type": "method", + "name": "getDiffieHellman", + "desc": "

Creates a predefined Diffie-Hellman key exchange object.\nThe supported groups are: 'modp1', 'modp2', 'modp5'\n(defined in [RFC 2412][])\nand 'modp14', 'modp15', 'modp16', 'modp17', 'modp18'\n(defined in [RFC 3526][]).\nThe returned object mimics the interface of objects created by\n[crypto.createDiffieHellman()][] above, but\nwill not allow to change the keys (with\n[diffieHellman.setPublicKey()][] for example).\nThe advantage of using this routine is that the parties don't have to\ngenerate nor exchange group modulus beforehand, saving both processor and\ncommunication time.\n\n

\n

Example (obtaining a shared secret):\n\n

\n
var crypto = require('crypto');\nvar alice = crypto.getDiffieHellman('modp5');\nvar bob = crypto.getDiffieHellman('modp5');\n\nalice.generateKeys();\nbob.generateKeys();\n\nvar alice_secret = alice.computeSecret(bob.getPublicKey(), 'binary', 'hex');\nvar bob_secret = bob.computeSecret(alice.getPublicKey(), 'binary', 'hex');\n\n/* alice_secret and bob_secret should be the same */\nconsole.log(alice_secret == bob_secret);
\n", + "signatures": [ + { + "params": [ + { + "name": "group_name" + } + ] + } + ] + }, + { + "textRaw": "crypto.pbkdf2(password, salt, iterations, keylen, callback)", + "type": "method", + "name": "pbkdf2", + "desc": "

Asynchronous PBKDF2 applies pseudorandom function HMAC-SHA1 to derive\na key of given length from the given password, salt and iterations.\nThe callback gets two arguments (err, derivedKey).\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "password" + }, + { + "name": "salt" + }, + { + "name": "iterations" + }, + { + "name": "keylen" + }, + { + "name": "callback" + } + ] + } + ] + }, + { + "textRaw": "crypto.randomBytes(size, [callback])", + "type": "method", + "name": "randomBytes", + "desc": "

Generates cryptographically strong pseudo-random data. Usage:\n\n

\n
// async\ncrypto.randomBytes(256, function(ex, buf) {\n  if (ex) throw ex;\n  console.log('Have %d bytes of random data: %s', buf.length, buf);\n});\n\n// sync\ntry {\n  var buf = crypto.randomBytes(256);\n  console.log('Have %d bytes of random data: %s', buf.length, buf);\n} catch (ex) {\n  // handle error\n}
\n", + "signatures": [ + { + "params": [ + { + "name": "size" + }, + { + "name": "callback", + "optional": true + } + ] + } + ] + } + ], + "classes": [ + { + "textRaw": "Class: Hash", + "type": "class", + "name": "Hash", + "desc": "

The class for creating hash digests of data.\n\n

\n

Returned by crypto.createHash.\n\n

\n", + "methods": [ + { + "textRaw": "hash.update(data, [input_encoding])", + "type": "method", + "name": "update", + "desc": "

Updates the hash content with the given data, the encoding of which is given\nin input_encoding and can be 'utf8', 'ascii' or 'binary'.\nDefaults to 'binary'.\nThis can be called many times with new data as it is streamed.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "data" + }, + { + "name": "input_encoding", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "hash.digest([encoding])", + "type": "method", + "name": "digest", + "desc": "

Calculates the digest of all of the passed data to be hashed.\nThe encoding can be 'hex', 'binary' or 'base64'.\nDefaults to 'binary'.\n\n

\n

Note: hash object can not be used after digest() method been called.\n\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "encoding", + "optional": true + } + ] + } + ] + } + ] + }, + { + "textRaw": "Class: Hmac", + "type": "class", + "name": "Hmac", + "desc": "

Class for creating cryptographic hmac content.\n\n

\n

Returned by crypto.createHmac.\n\n

\n", + "methods": [ + { + "textRaw": "hmac.update(data)", + "type": "method", + "name": "update", + "desc": "

Update the hmac content with the given data.\nThis can be called many times with new data as it is streamed.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "data" + } + ] + } + ] + }, + { + "textRaw": "hmac.digest([encoding])", + "type": "method", + "name": "digest", + "desc": "

Calculates the digest of all of the passed data to the hmac.\nThe encoding can be 'hex', 'binary' or 'base64'.\nDefaults to 'binary'.\n\n

\n

Note: hmac object can not be used after digest() method been called.\n\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "encoding", + "optional": true + } + ] + } + ] + } + ] + }, + { + "textRaw": "Class: Cipher", + "type": "class", + "name": "Cipher", + "desc": "

Class for encrypting data.\n\n

\n

Returned by crypto.createCipher and crypto.createCipheriv.\n\n

\n", + "methods": [ + { + "textRaw": "cipher.update(data, [input_encoding], [output_encoding])", + "type": "method", + "name": "update", + "desc": "

Updates the cipher with data, the encoding of which is given in\ninput_encoding and can be 'utf8', 'ascii' or 'binary'.\nDefaults to 'binary'.\n\n

\n

The output_encoding specifies the output format of the enciphered data,\nand can be 'binary', 'base64' or 'hex'. Defaults to 'binary'.\n\n

\n

Returns the enciphered contents, and can be called many times with new data as it is streamed.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "data" + }, + { + "name": "input_encoding", + "optional": true + }, + { + "name": "output_encoding", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "cipher.final([output_encoding])", + "type": "method", + "name": "final", + "desc": "

Returns any remaining enciphered contents, with output_encoding being one of:\n'binary', 'base64' or 'hex'. Defaults to 'binary'.\n\n

\n

Note: cipher object can not be used after final() method been called.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "output_encoding", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "cipher.setAutoPadding(auto_padding=true)", + "type": "method", + "name": "setAutoPadding", + "desc": "

You can disable automatic padding of the input data to block size. If auto_padding is false,\nthe length of the entire input data must be a multiple of the cipher's block size or final will fail.\nUseful for non-standard padding, e.g. using 0x0 instead of PKCS padding. You must call this before cipher.final.\n\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "auto_padding", + "default": "true" + } + ] + } + ] + } + ] + }, + { + "textRaw": "Class: Decipher", + "type": "class", + "name": "Decipher", + "desc": "

Class for decrypting data.\n\n

\n

Returned by crypto.createDecipher and crypto.createDecipheriv.\n\n

\n", + "methods": [ + { + "textRaw": "decipher.update(data, [input_encoding], [output_encoding])", + "type": "method", + "name": "update", + "desc": "

Updates the decipher with data, which is encoded in 'binary', 'base64'\nor 'hex'. Defaults to 'binary'.\n\n

\n

The output_decoding specifies in what format to return the deciphered\nplaintext: 'binary', 'ascii' or 'utf8'. Defaults to 'binary'.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "data" + }, + { + "name": "input_encoding", + "optional": true + }, + { + "name": "output_encoding", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "decipher.final([output_encoding])", + "type": "method", + "name": "final", + "desc": "

Returns any remaining plaintext which is deciphered,\nwith output_encoding being one of: 'binary', 'ascii' or 'utf8'.\nDefaults to 'binary'.\n\n

\n

Note: decipher object can not be used after final() method been called.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "output_encoding", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "decipher.setAutoPadding(auto_padding=true)", + "type": "method", + "name": "setAutoPadding", + "desc": "

You can disable auto padding if the data has been encrypted without standard block padding to prevent\ndecipher.final from checking and removing it. Can only work if the input data's length is a multiple of the\nciphers block size. You must call this before streaming data to decipher.update.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "auto_padding", + "default": "true" + } + ] + } + ] + } + ] + }, + { + "textRaw": "Class: Signer", + "type": "class", + "name": "Signer", + "desc": "

Class for generating signatures.\n\n

\n

Returned by crypto.createSign.\n\n

\n", + "methods": [ + { + "textRaw": "signer.update(data)", + "type": "method", + "name": "update", + "desc": "

Updates the signer object with data.\nThis can be called many times with new data as it is streamed.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "data" + } + ] + } + ] + }, + { + "textRaw": "signer.sign(private_key, [output_format])", + "type": "method", + "name": "sign", + "desc": "

Calculates the signature on all the updated data passed through the signer.\nprivate_key is a string containing the PEM encoded private key for signing.\n\n

\n

Returns the signature in output_format which can be 'binary', 'hex' or\n'base64'. Defaults to 'binary'.\n\n

\n

Note: signer object can not be used after sign() method been called.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "private_key" + }, + { + "name": "output_format", + "optional": true + } + ] + } + ] + } + ] + }, + { + "textRaw": "Class: Verify", + "type": "class", + "name": "Verify", + "desc": "

Class for verifying signatures.\n\n

\n

Returned by crypto.createVerify.\n\n

\n", + "methods": [ + { + "textRaw": "verifier.update(data)", + "type": "method", + "name": "update", + "desc": "

Updates the verifier object with data.\nThis can be called many times with new data as it is streamed.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "data" + } + ] + } + ] + }, + { + "textRaw": "verifier.verify(object, signature, [signature_format])", + "type": "method", + "name": "verify", + "desc": "

Verifies the signed data by using the object and signature. object is a\nstring containing a PEM encoded object, which can be one of RSA public key,\nDSA public key, or X.509 certificate. signature is the previously calculated\nsignature for the data, in the signature_format which can be 'binary',\n'hex' or 'base64'. Defaults to 'binary'.\n\n

\n

Returns true or false depending on the validity of the signature for the data and public key.\n\n

\n

Note: verifier object can not be used after verify() method been called.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "object" + }, + { + "name": "signature" + }, + { + "name": "signature_format", + "optional": true + } + ] + } + ] + } + ] + }, + { + "textRaw": "Class: DiffieHellman", + "type": "class", + "name": "DiffieHellman", + "desc": "

The class for creating Diffie-Hellman key exchanges.\n\n

\n

Returned by crypto.createDiffieHellman.\n\n

\n", + "methods": [ + { + "textRaw": "diffieHellman.generateKeys([encoding])", + "type": "method", + "name": "generateKeys", + "desc": "

Generates private and public Diffie-Hellman key values, and returns the\npublic key in the specified encoding. This key should be transferred to the\nother party. Encoding can be 'binary', 'hex', or 'base64'.\nDefaults to 'binary'.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "encoding", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "diffieHellman.computeSecret(other_public_key, [input_encoding], [output_encoding])", + "type": "method", + "name": "computeSecret", + "desc": "

Computes the shared secret using other_public_key as the other party's\npublic key and returns the computed shared secret. Supplied key is\ninterpreted using specified input_encoding, and secret is encoded using\nspecified output_encoding. Encodings can be 'binary', 'hex', or\n'base64'. The input encoding defaults to 'binary'.\nIf no output encoding is given, the input encoding is used as output encoding.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "other_public_key" + }, + { + "name": "input_encoding", + "optional": true + }, + { + "name": "output_encoding", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "diffieHellman.getPrime([encoding])", + "type": "method", + "name": "getPrime", + "desc": "

Returns the Diffie-Hellman prime in the specified encoding, which can be\n'binary', 'hex', or 'base64'. Defaults to 'binary'.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "encoding", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "diffieHellman.getGenerator([encoding])", + "type": "method", + "name": "getGenerator", + "desc": "

Returns the Diffie-Hellman prime in the specified encoding, which can be\n'binary', 'hex', or 'base64'. Defaults to 'binary'.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "encoding", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "diffieHellman.getPublicKey([encoding])", + "type": "method", + "name": "getPublicKey", + "desc": "

Returns the Diffie-Hellman public key in the specified encoding, which can\nbe 'binary', 'hex', or 'base64'. Defaults to 'binary'.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "encoding", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "diffieHellman.getPrivateKey([encoding])", + "type": "method", + "name": "getPrivateKey", + "desc": "

Returns the Diffie-Hellman private key in the specified encoding, which can\nbe 'binary', 'hex', or 'base64'. Defaults to 'binary'.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "encoding", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "diffieHellman.setPublicKey(public_key, [encoding])", + "type": "method", + "name": "setPublicKey", + "desc": "

Sets the Diffie-Hellman public key. Key encoding can be 'binary', 'hex',\nor 'base64'. Defaults to 'binary'.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "public_key" + }, + { + "name": "encoding", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "diffieHellman.setPrivateKey(public_key, [encoding])", + "type": "method", + "name": "setPrivateKey", + "desc": "

Sets the Diffie-Hellman private key. Key encoding can be 'binary', 'hex',\nor 'base64'. Defaults to 'binary'.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "public_key" + }, + { + "name": "encoding", + "optional": true + } + ] + } + ] + } + ] + } + ], + "modules": [ + { + "textRaw": "Proposed API Changes in Future Versions of Node", + "name": "proposed_api_changes_in_future_versions_of_node", + "desc": "

The Crypto module was added to Node before there was the concept of a\nunified Stream API, and before there were Buffer objects for handling\nbinary data.\n\n

\n

As such, the streaming classes don't have the typical methods found on\nother Node classes, and many methods accept and return Binary-encoded\nstrings by default rather than Buffers.\n\n

\n

A future version of node will make Buffers the default data type.\nThis will be a breaking change for some use cases, but not all.\n\n

\n

For example, if you currently use the default arguments to the Sign\nclass, and then pass the results to the Verify class, without ever\ninspecting the data, then it will continue to work as before. Where\nyou now get a binary string and then present the binary string to the\nVerify object, you'll get a Buffer, and present the Buffer to the\nVerify object.\n\n

\n

However, if you are doing things with the string data that will not\nwork properly on Buffers (such as, concatenating them, storing in\ndatabases, etc.), or you are passing binary strings to the crypto\nfunctions without an encoding argument, then you will need to start\nproviding encoding arguments to specify which encoding you'd like to\nuse.\n\n

\n

Also, a Streaming API will be provided, but this will be done in such\na way as to preserve the legacy API surface.\n\n\n

\n", + "type": "module", + "displayName": "Proposed API Changes in Future Versions of Node" + } + ], + "type": "module", + "displayName": "Crypto" + } + ] +} diff --git a/node-v0.8.14/doc/api/crypto.markdown b/node-v0.8.14/doc/api/crypto.markdown new file mode 100644 index 0000000..00ed394 --- /dev/null +++ b/node-v0.8.14/doc/api/crypto.markdown @@ -0,0 +1,406 @@ +# Crypto + + Stability: 2 - Unstable; API changes are being discussed for + future versions. Breaking changes will be minimized. See below. + +Use `require('crypto')` to access this module. + +The crypto module requires OpenSSL to be available on the underlying platform. +It offers a way of encapsulating secure credentials to be used as part +of a secure HTTPS net or http connection. + +It also offers a set of wrappers for OpenSSL's hash, hmac, cipher, decipher, sign and verify methods. + +## crypto.createCredentials(details) + +Creates a credentials object, with the optional details being a dictionary with keys: + +* `pfx` : A string or buffer holding the PFX or PKCS12 encoded private key, certificate and CA certificates +* `key` : A string holding the PEM encoded private key +* `passphrase` : A string of passphrase for the private key or pfx +* `cert` : A string holding the PEM encoded certificate +* `ca` : Either a string or list of strings of PEM encoded CA certificates to trust. +* `crl` : Either a string or list of strings of PEM encoded CRLs (Certificate Revocation List) +* `ciphers`: A string describing the ciphers to use or exclude. Consult + for details + on the format. + +If no 'ca' details are given, then node.js will use the default publicly trusted list of CAs as given in +. + + +## crypto.createHash(algorithm) + +Creates and returns a hash object, a cryptographic hash with the given algorithm +which can be used to generate hash digests. + +`algorithm` is dependent on the available algorithms supported by the version +of OpenSSL on the platform. Examples are `'sha1'`, `'md5'`, `'sha256'`, `'sha512'`, etc. +On recent releases, `openssl list-message-digest-algorithms` will display the available digest algorithms. + +Example: this program that takes the sha1 sum of a file + + var filename = process.argv[2]; + var crypto = require('crypto'); + var fs = require('fs'); + + var shasum = crypto.createHash('sha1'); + + var s = fs.ReadStream(filename); + s.on('data', function(d) { + shasum.update(d); + }); + + s.on('end', function() { + var d = shasum.digest('hex'); + console.log(d + ' ' + filename); + }); + +## Class: Hash + +The class for creating hash digests of data. + +Returned by `crypto.createHash`. + +### hash.update(data, [input_encoding]) + +Updates the hash content with the given `data`, the encoding of which is given +in `input_encoding` and can be `'utf8'`, `'ascii'` or `'binary'`. +Defaults to `'binary'`. +This can be called many times with new data as it is streamed. + +### hash.digest([encoding]) + +Calculates the digest of all of the passed data to be hashed. +The `encoding` can be `'hex'`, `'binary'` or `'base64'`. +Defaults to `'binary'`. + +Note: `hash` object can not be used after `digest()` method been called. + + +## crypto.createHmac(algorithm, key) + +Creates and returns a hmac object, a cryptographic hmac with the given algorithm and key. + +`algorithm` is dependent on the available algorithms supported by OpenSSL - see createHash above. +`key` is the hmac key to be used. + +## Class: Hmac + +Class for creating cryptographic hmac content. + +Returned by `crypto.createHmac`. + +### hmac.update(data) + +Update the hmac content with the given `data`. +This can be called many times with new data as it is streamed. + +### hmac.digest([encoding]) + +Calculates the digest of all of the passed data to the hmac. +The `encoding` can be `'hex'`, `'binary'` or `'base64'`. +Defaults to `'binary'`. + +Note: `hmac` object can not be used after `digest()` method been called. + + +## crypto.createCipher(algorithm, password) + +Creates and returns a cipher object, with the given algorithm and password. + +`algorithm` is dependent on OpenSSL, examples are `'aes192'`, etc. +On recent releases, `openssl list-cipher-algorithms` will display the +available cipher algorithms. +`password` is used to derive key and IV, which must be a `'binary'` encoded +string or a [buffer](buffer.html). + +## crypto.createCipheriv(algorithm, key, iv) + +Creates and returns a cipher object, with the given algorithm, key and iv. + +`algorithm` is the same as the argument to `createCipher()`. +`key` is the raw key used by the algorithm. +`iv` is an [initialization +vector](http://en.wikipedia.org/wiki/Initialization_vector). + +`key` and `iv` must be `'binary'` encoded strings or [buffers](buffer.html). + +## Class: Cipher + +Class for encrypting data. + +Returned by `crypto.createCipher` and `crypto.createCipheriv`. + +### cipher.update(data, [input_encoding], [output_encoding]) + +Updates the cipher with `data`, the encoding of which is given in +`input_encoding` and can be `'utf8'`, `'ascii'` or `'binary'`. +Defaults to `'binary'`. + +The `output_encoding` specifies the output format of the enciphered data, +and can be `'binary'`, `'base64'` or `'hex'`. Defaults to `'binary'`. + +Returns the enciphered contents, and can be called many times with new data as it is streamed. + +### cipher.final([output_encoding]) + +Returns any remaining enciphered contents, with `output_encoding` being one of: +`'binary'`, `'base64'` or `'hex'`. Defaults to `'binary'`. + +Note: `cipher` object can not be used after `final()` method been called. + +### cipher.setAutoPadding(auto_padding=true) + +You can disable automatic padding of the input data to block size. If `auto_padding` is false, +the length of the entire input data must be a multiple of the cipher's block size or `final` will fail. +Useful for non-standard padding, e.g. using `0x0` instead of PKCS padding. You must call this before `cipher.final`. + + +## crypto.createDecipher(algorithm, password) + +Creates and returns a decipher object, with the given algorithm and key. +This is the mirror of the [createCipher()][] above. + +## crypto.createDecipheriv(algorithm, key, iv) + +Creates and returns a decipher object, with the given algorithm, key and iv. +This is the mirror of the [createCipheriv()][] above. + +## Class: Decipher + +Class for decrypting data. + +Returned by `crypto.createDecipher` and `crypto.createDecipheriv`. + +### decipher.update(data, [input_encoding], [output_encoding]) + +Updates the decipher with `data`, which is encoded in `'binary'`, `'base64'` +or `'hex'`. Defaults to `'binary'`. + +The `output_decoding` specifies in what format to return the deciphered +plaintext: `'binary'`, `'ascii'` or `'utf8'`. Defaults to `'binary'`. + +### decipher.final([output_encoding]) + +Returns any remaining plaintext which is deciphered, +with `output_encoding` being one of: `'binary'`, `'ascii'` or `'utf8'`. +Defaults to `'binary'`. + +Note: `decipher` object can not be used after `final()` method been called. + +### decipher.setAutoPadding(auto_padding=true) + +You can disable auto padding if the data has been encrypted without standard block padding to prevent +`decipher.final` from checking and removing it. Can only work if the input data's length is a multiple of the +ciphers block size. You must call this before streaming data to `decipher.update`. + +## crypto.createSign(algorithm) + +Creates and returns a signing object, with the given algorithm. +On recent OpenSSL releases, `openssl list-public-key-algorithms` will display +the available signing algorithms. Examples are `'RSA-SHA256'`. + +## Class: Signer + +Class for generating signatures. + +Returned by `crypto.createSign`. + +### signer.update(data) + +Updates the signer object with data. +This can be called many times with new data as it is streamed. + +### signer.sign(private_key, [output_format]) + +Calculates the signature on all the updated data passed through the signer. +`private_key` is a string containing the PEM encoded private key for signing. + +Returns the signature in `output_format` which can be `'binary'`, `'hex'` or +`'base64'`. Defaults to `'binary'`. + +Note: `signer` object can not be used after `sign()` method been called. + +## crypto.createVerify(algorithm) + +Creates and returns a verification object, with the given algorithm. +This is the mirror of the signing object above. + +## Class: Verify + +Class for verifying signatures. + +Returned by `crypto.createVerify`. + +### verifier.update(data) + +Updates the verifier object with data. +This can be called many times with new data as it is streamed. + +### verifier.verify(object, signature, [signature_format]) + +Verifies the signed data by using the `object` and `signature`. `object` is a +string containing a PEM encoded object, which can be one of RSA public key, +DSA public key, or X.509 certificate. `signature` is the previously calculated +signature for the data, in the `signature_format` which can be `'binary'`, +`'hex'` or `'base64'`. Defaults to `'binary'`. + +Returns true or false depending on the validity of the signature for the data and public key. + +Note: `verifier` object can not be used after `verify()` method been called. + +## crypto.createDiffieHellman(prime_length) + +Creates a Diffie-Hellman key exchange object and generates a prime of the +given bit length. The generator used is `2`. + +## crypto.createDiffieHellman(prime, [encoding]) + +Creates a Diffie-Hellman key exchange object using the supplied prime. The +generator used is `2`. Encoding can be `'binary'`, `'hex'`, or `'base64'`. +Defaults to `'binary'`. + +## Class: DiffieHellman + +The class for creating Diffie-Hellman key exchanges. + +Returned by `crypto.createDiffieHellman`. + +### diffieHellman.generateKeys([encoding]) + +Generates private and public Diffie-Hellman key values, and returns the +public key in the specified encoding. This key should be transferred to the +other party. Encoding can be `'binary'`, `'hex'`, or `'base64'`. +Defaults to `'binary'`. + +### diffieHellman.computeSecret(other_public_key, [input_encoding], [output_encoding]) + +Computes the shared secret using `other_public_key` as the other party's +public key and returns the computed shared secret. Supplied key is +interpreted using specified `input_encoding`, and secret is encoded using +specified `output_encoding`. Encodings can be `'binary'`, `'hex'`, or +`'base64'`. The input encoding defaults to `'binary'`. +If no output encoding is given, the input encoding is used as output encoding. + +### diffieHellman.getPrime([encoding]) + +Returns the Diffie-Hellman prime in the specified encoding, which can be +`'binary'`, `'hex'`, or `'base64'`. Defaults to `'binary'`. + +### diffieHellman.getGenerator([encoding]) + +Returns the Diffie-Hellman prime in the specified encoding, which can be +`'binary'`, `'hex'`, or `'base64'`. Defaults to `'binary'`. + +### diffieHellman.getPublicKey([encoding]) + +Returns the Diffie-Hellman public key in the specified encoding, which can +be `'binary'`, `'hex'`, or `'base64'`. Defaults to `'binary'`. + +### diffieHellman.getPrivateKey([encoding]) + +Returns the Diffie-Hellman private key in the specified encoding, which can +be `'binary'`, `'hex'`, or `'base64'`. Defaults to `'binary'`. + +### diffieHellman.setPublicKey(public_key, [encoding]) + +Sets the Diffie-Hellman public key. Key encoding can be `'binary'`, `'hex'`, +or `'base64'`. Defaults to `'binary'`. + +### diffieHellman.setPrivateKey(public_key, [encoding]) + +Sets the Diffie-Hellman private key. Key encoding can be `'binary'`, `'hex'`, +or `'base64'`. Defaults to `'binary'`. + +## crypto.getDiffieHellman(group_name) + +Creates a predefined Diffie-Hellman key exchange object. +The supported groups are: `'modp1'`, `'modp2'`, `'modp5'` +(defined in [RFC 2412][]) +and `'modp14'`, `'modp15'`, `'modp16'`, `'modp17'`, `'modp18'` +(defined in [RFC 3526][]). +The returned object mimics the interface of objects created by +[crypto.createDiffieHellman()][] above, but +will not allow to change the keys (with +[diffieHellman.setPublicKey()][] for example). +The advantage of using this routine is that the parties don't have to +generate nor exchange group modulus beforehand, saving both processor and +communication time. + +Example (obtaining a shared secret): + + var crypto = require('crypto'); + var alice = crypto.getDiffieHellman('modp5'); + var bob = crypto.getDiffieHellman('modp5'); + + alice.generateKeys(); + bob.generateKeys(); + + var alice_secret = alice.computeSecret(bob.getPublicKey(), 'binary', 'hex'); + var bob_secret = bob.computeSecret(alice.getPublicKey(), 'binary', 'hex'); + + /* alice_secret and bob_secret should be the same */ + console.log(alice_secret == bob_secret); + +## crypto.pbkdf2(password, salt, iterations, keylen, callback) + +Asynchronous PBKDF2 applies pseudorandom function HMAC-SHA1 to derive +a key of given length from the given password, salt and iterations. +The callback gets two arguments `(err, derivedKey)`. + +## crypto.randomBytes(size, [callback]) + +Generates cryptographically strong pseudo-random data. Usage: + + // async + crypto.randomBytes(256, function(ex, buf) { + if (ex) throw ex; + console.log('Have %d bytes of random data: %s', buf.length, buf); + }); + + // sync + try { + var buf = crypto.randomBytes(256); + console.log('Have %d bytes of random data: %s', buf.length, buf); + } catch (ex) { + // handle error + } + +## Proposed API Changes in Future Versions of Node + +The Crypto module was added to Node before there was the concept of a +unified Stream API, and before there were Buffer objects for handling +binary data. + +As such, the streaming classes don't have the typical methods found on +other Node classes, and many methods accept and return Binary-encoded +strings by default rather than Buffers. + +A future version of node will make Buffers the default data type. +This will be a breaking change for some use cases, but not all. + +For example, if you currently use the default arguments to the Sign +class, and then pass the results to the Verify class, without ever +inspecting the data, then it will continue to work as before. Where +you now get a binary string and then present the binary string to the +Verify object, you'll get a Buffer, and present the Buffer to the +Verify object. + +However, if you are doing things with the string data that will not +work properly on Buffers (such as, concatenating them, storing in +databases, etc.), or you are passing binary strings to the crypto +functions without an encoding argument, then you will need to start +providing encoding arguments to specify which encoding you'd like to +use. + +Also, a Streaming API will be provided, but this will be done in such +a way as to preserve the legacy API surface. + + +[createCipher()]: #crypto_crypto_createcipher_algorithm_password +[createCipheriv()]: #crypto_crypto_createcipheriv_algorithm_key_iv +[crypto.createDiffieHellman()]: #crypto_crypto_creatediffiehellman_prime_encoding +[diffieHellman.setPublicKey()]: #crypto_diffiehellman_setpublickey_public_key_encoding +[RFC 2412]: http://www.rfc-editor.org/rfc/rfc2412.txt +[RFC 3526]: http://www.rfc-editor.org/rfc/rfc3526.txt diff --git a/node-v0.8.14/doc/api/debugger.html b/node-v0.8.14/doc/api/debugger.html new file mode 100644 index 0000000..1d23325 --- /dev/null +++ b/node-v0.8.14/doc/api/debugger.html @@ -0,0 +1,238 @@ + + + + + Debugger Node.js v0.8.14 Manual & Documentation + + + + + +
+ + + +
+
+ + +
+
+

Node.js v0.8.14 Manual & Documentation

+ +
+
+ + + +
+

Debugger#

+
Stability: 3 - Stable
+ + +

V8 comes with an extensive debugger which is accessible out-of-process via a +simple TCP protocol. +Node has a built-in client for this debugger. To use this, start Node with the +debug argument; a prompt will appear: + +

+
% node debug myscript.js
+< debugger listening on port 5858
+connecting... ok
+break in /home/indutny/Code/git/indutny/myscript.js:1
+  1 x = 5;
+  2 setTimeout(function () {
+  3   debugger;
+debug>
+

Node's debugger client doesn't support the full range of commands, but +simple step and inspection is possible. By putting the statement debugger; +into the source code of your script, you will enable a breakpoint. + +

+

For example, suppose myscript.js looked like this: + +

+
// myscript.js
+x = 5;
+setTimeout(function () {
+  debugger;
+  console.log("world");
+}, 1000);
+console.log("hello");
+

Then once the debugger is run, it will break on line 4. + +

+
% node debug myscript.js
+< debugger listening on port 5858
+connecting... ok
+break in /home/indutny/Code/git/indutny/myscript.js:1
+  1 x = 5;
+  2 setTimeout(function () {
+  3   debugger;
+debug> cont
+< hello
+break in /home/indutny/Code/git/indutny/myscript.js:3
+  1 x = 5;
+  2 setTimeout(function () {
+  3   debugger;
+  4   console.log("world");
+  5 }, 1000);
+debug> next
+break in /home/indutny/Code/git/indutny/myscript.js:4
+  2 setTimeout(function () {
+  3   debugger;
+  4   console.log("world");
+  5 }, 1000);
+  6 console.log("hello");
+debug> repl
+Press Ctrl + C to leave debug repl
+> x
+5
+> 2+2
+4
+debug> next
+< world
+break in /home/indutny/Code/git/indutny/myscript.js:5
+  3   debugger;
+  4   console.log("world");
+  5 }, 1000);
+  6 console.log("hello");
+  7
+debug> quit
+%
+

The repl command allows you to evaluate code remotely. The next command +steps over to the next line. There are a few other commands available and more +to come. Type help to see others. + +

+

Watchers#

+

You can watch expression and variable values while debugging your code. +On every breakpoint each expression from the watchers list will be evaluated +in the current context and displayed just before the breakpoint's source code +listing. + +

+

To start watching an expression, type watch("my_expression"). watchers +prints the active watchers. To remove a watcher, type +unwatch("my_expression"). + +

+

Commands reference#

+

Stepping#

+
    +
  • cont, c - Continue execution
  • +
  • next, n - Step next
  • +
  • step, s - Step in
  • +
  • out, o - Step out
  • +
  • pause - Pause running code (like pause button in Developer TOols)
  • +
+

Breakpoints#

+
    +
  • setBreakpoint(), sb() - Set breakpoint on current line
  • +
  • setBreakpoint(line), sb(line) - Set breakpoint on specific line
  • +
  • setBreakpoint('fn()'), sb(...) - Set breakpoint on a first statement in +functions body
  • +
  • setBreakpoint('script.js', 1), sb(...) - Set breakpoint on first line of +script.js
  • +
  • clearBreakpoint, cb(...) - Clear breakpoint
  • +
+

Info#

+
    +
  • backtrace, bt - Print backtrace of current execution frame
  • +
  • list(5) - List scripts source code with 5 line context (5 lines before and +after)
  • +
  • watch(expr) - Add expression to watch list
  • +
  • unwatch(expr) - Remove expression from watch list
  • +
  • watchers - List all watchers and their values (automatically listed on each +breakpoint)
  • +
  • repl - Open debugger's repl for evaluation in debugging script's context
  • +
+

Execution control#

+
    +
  • run - Run script (automatically runs on debugger's start)
  • +
  • restart - Restart script
  • +
  • kill - Kill script
  • +
+

Various#

+
    +
  • scripts - List all loaded scripts
  • +
  • version - Display v8's version
  • +
+

Advanced Usage#

+

The V8 debugger can be enabled and accessed either by starting Node with +the --debug command-line flag or by signaling an existing Node process +with SIGUSR1. +

+ +
+
+
+ + + + + + + + + diff --git a/node-v0.8.14/doc/api/debugger.json b/node-v0.8.14/doc/api/debugger.json new file mode 100644 index 0000000..9a582d4 --- /dev/null +++ b/node-v0.8.14/doc/api/debugger.json @@ -0,0 +1,51 @@ +{ + "source": "doc/api/debugger.markdown", + "stability": 3, + "stabilityText": "Stable", + "miscs": [ + { + "textRaw": "Debugger", + "name": "Debugger", + "stability": 3, + "stabilityText": "Stable", + "type": "misc", + "desc": "

V8 comes with an extensive debugger which is accessible out-of-process via a\nsimple TCP protocol.\nNode has a built-in client for this debugger. To use this, start Node with the\ndebug argument; a prompt will appear:\n\n

\n
% node debug myscript.js\n< debugger listening on port 5858\nconnecting... ok\nbreak in /home/indutny/Code/git/indutny/myscript.js:1\n  1 x = 5;\n  2 setTimeout(function () {\n  3   debugger;\ndebug>
\n

Node's debugger client doesn't support the full range of commands, but\nsimple step and inspection is possible. By putting the statement debugger;\ninto the source code of your script, you will enable a breakpoint.\n\n

\n

For example, suppose myscript.js looked like this:\n\n

\n
// myscript.js\nx = 5;\nsetTimeout(function () {\n  debugger;\n  console.log("world");\n}, 1000);\nconsole.log("hello");
\n

Then once the debugger is run, it will break on line 4.\n\n

\n
% node debug myscript.js\n< debugger listening on port 5858\nconnecting... ok\nbreak in /home/indutny/Code/git/indutny/myscript.js:1\n  1 x = 5;\n  2 setTimeout(function () {\n  3   debugger;\ndebug> cont\n< hello\nbreak in /home/indutny/Code/git/indutny/myscript.js:3\n  1 x = 5;\n  2 setTimeout(function () {\n  3   debugger;\n  4   console.log("world");\n  5 }, 1000);\ndebug> next\nbreak in /home/indutny/Code/git/indutny/myscript.js:4\n  2 setTimeout(function () {\n  3   debugger;\n  4   console.log("world");\n  5 }, 1000);\n  6 console.log("hello");\ndebug> repl\nPress Ctrl + C to leave debug repl\n> x\n5\n> 2+2\n4\ndebug> next\n< world\nbreak in /home/indutny/Code/git/indutny/myscript.js:5\n  3   debugger;\n  4   console.log("world");\n  5 }, 1000);\n  6 console.log("hello");\n  7\ndebug> quit\n%
\n

The repl command allows you to evaluate code remotely. The next command\nsteps over to the next line. There are a few other commands available and more\nto come. Type help to see others.\n\n

\n", + "miscs": [ + { + "textRaw": "Watchers", + "name": "watchers", + "desc": "

You can watch expression and variable values while debugging your code.\nOn every breakpoint each expression from the watchers list will be evaluated\nin the current context and displayed just before the breakpoint's source code\nlisting.\n\n

\n

To start watching an expression, type watch("my_expression"). watchers\nprints the active watchers. To remove a watcher, type\nunwatch("my_expression").\n\n

\n", + "type": "misc", + "displayName": "Watchers" + }, + { + "textRaw": "Commands reference", + "name": "commands_reference", + "modules": [ + { + "textRaw": "Execution control", + "name": "Execution control", + "type": "module", + "displayName": "Various" + }, + { + "textRaw": "Various", + "name": "various", + "type": "module", + "displayName": "Various" + } + ], + "type": "misc", + "displayName": "Commands reference" + }, + { + "textRaw": "Advanced Usage", + "name": "advanced_usage", + "desc": "

The V8 debugger can be enabled and accessed either by starting Node with\nthe --debug command-line flag or by signaling an existing Node process\nwith SIGUSR1.\n

\n", + "type": "misc", + "displayName": "Advanced Usage" + } + ] + } + ] +} diff --git a/node-v0.8.14/doc/api/debugger.markdown b/node-v0.8.14/doc/api/debugger.markdown new file mode 100644 index 0000000..ed37f0c --- /dev/null +++ b/node-v0.8.14/doc/api/debugger.markdown @@ -0,0 +1,138 @@ +# Debugger + + Stability: 3 - Stable + + + +V8 comes with an extensive debugger which is accessible out-of-process via a +simple [TCP protocol](http://code.google.com/p/v8/wiki/DebuggerProtocol). +Node has a built-in client for this debugger. To use this, start Node with the +`debug` argument; a prompt will appear: + + % node debug myscript.js + < debugger listening on port 5858 + connecting... ok + break in /home/indutny/Code/git/indutny/myscript.js:1 + 1 x = 5; + 2 setTimeout(function () { + 3 debugger; + debug> + +Node's debugger client doesn't support the full range of commands, but +simple step and inspection is possible. By putting the statement `debugger;` +into the source code of your script, you will enable a breakpoint. + +For example, suppose `myscript.js` looked like this: + + // myscript.js + x = 5; + setTimeout(function () { + debugger; + console.log("world"); + }, 1000); + console.log("hello"); + +Then once the debugger is run, it will break on line 4. + + % node debug myscript.js + < debugger listening on port 5858 + connecting... ok + break in /home/indutny/Code/git/indutny/myscript.js:1 + 1 x = 5; + 2 setTimeout(function () { + 3 debugger; + debug> cont + < hello + break in /home/indutny/Code/git/indutny/myscript.js:3 + 1 x = 5; + 2 setTimeout(function () { + 3 debugger; + 4 console.log("world"); + 5 }, 1000); + debug> next + break in /home/indutny/Code/git/indutny/myscript.js:4 + 2 setTimeout(function () { + 3 debugger; + 4 console.log("world"); + 5 }, 1000); + 6 console.log("hello"); + debug> repl + Press Ctrl + C to leave debug repl + > x + 5 + > 2+2 + 4 + debug> next + < world + break in /home/indutny/Code/git/indutny/myscript.js:5 + 3 debugger; + 4 console.log("world"); + 5 }, 1000); + 6 console.log("hello"); + 7 + debug> quit + % + + +The `repl` command allows you to evaluate code remotely. The `next` command +steps over to the next line. There are a few other commands available and more +to come. Type `help` to see others. + +## Watchers + +You can watch expression and variable values while debugging your code. +On every breakpoint each expression from the watchers list will be evaluated +in the current context and displayed just before the breakpoint's source code +listing. + +To start watching an expression, type `watch("my_expression")`. `watchers` +prints the active watchers. To remove a watcher, type +`unwatch("my_expression")`. + +## Commands reference + +### Stepping + +* `cont`, `c` - Continue execution +* `next`, `n` - Step next +* `step`, `s` - Step in +* `out`, `o` - Step out +* `pause` - Pause running code (like pause button in Developer TOols) + +### Breakpoints + +* `setBreakpoint()`, `sb()` - Set breakpoint on current line +* `setBreakpoint(line)`, `sb(line)` - Set breakpoint on specific line +* `setBreakpoint('fn()')`, `sb(...)` - Set breakpoint on a first statement in +functions body +* `setBreakpoint('script.js', 1)`, `sb(...)` - Set breakpoint on first line of +script.js +* `clearBreakpoint`, `cb(...)` - Clear breakpoint + +### Info + +* `backtrace`, `bt` - Print backtrace of current execution frame +* `list(5)` - List scripts source code with 5 line context (5 lines before and +after) +* `watch(expr)` - Add expression to watch list +* `unwatch(expr)` - Remove expression from watch list +* `watchers` - List all watchers and their values (automatically listed on each +breakpoint) +* `repl` - Open debugger's repl for evaluation in debugging script's context + +### Execution control + +* `run` - Run script (automatically runs on debugger's start) +* `restart` - Restart script +* `kill` - Kill script + +### Various + +* `scripts` - List all loaded scripts +* `version` - Display v8's version + +## Advanced Usage + +The V8 debugger can be enabled and accessed either by starting Node with +the `--debug` command-line flag or by signaling an existing Node process +with `SIGUSR1`. diff --git a/node-v0.8.14/doc/api/dgram.html b/node-v0.8.14/doc/api/dgram.html new file mode 100644 index 0000000..620297a --- /dev/null +++ b/node-v0.8.14/doc/api/dgram.html @@ -0,0 +1,338 @@ + + + + + UDP / Datagram Sockets Node.js v0.8.14 Manual & Documentation + + + + + +
+ + + +
+
+ + +
+
+

Node.js v0.8.14 Manual & Documentation

+ +
+
+ + + +
+

UDP / Datagram Sockets#

+
Stability: 3 - Stable
+ + +

Datagram sockets are available through require('dgram'). + +

+

dgram.createSocket(type, [callback])#

+
    +
  • type String. Either 'udp4' or 'udp6'
  • +
  • callback Function. Attached as a listener to message events. +Optional
  • +
  • Returns: Socket object
  • +
+

Creates a datagram Socket of the specified types. Valid types are udp4 +and udp6. + +

+

Takes an optional callback which is added as a listener for message events. + +

+

Call socket.bind if you want to receive datagrams. socket.bind() will bind +to the "all interfaces" address on a random port (it does the right thing for +both udp4 and udp6 sockets). You can then retrieve the address and port +with socket.address().address and socket.address().port. + +

+

Class: Socket#

+

The dgram Socket class encapsulates the datagram functionality. It +should be created via dgram.createSocket(type, [callback]). + +

+

Event: 'message'#

+
    +
  • msg Buffer object. The message
  • +
  • rinfo Object. Remote address information
  • +
+

Emitted when a new datagram is available on a socket. msg is a Buffer and rinfo is +an object with the sender's address information and the number of bytes in the datagram. + +

+

Event: 'listening'#

+

Emitted when a socket starts listening for datagrams. This happens as soon as UDP sockets +are created. + +

+

Event: 'close'#

+

Emitted when a socket is closed with close(). No new message events will be emitted +on this socket. + +

+

Event: 'error'#

+
    +
  • exception Error object
  • +
+

Emitted when an error occurs. + +

+

dgram.send(buf, offset, length, port, address, [callback])#

+
    +
  • buf Buffer object. Message to be sent
  • +
  • offset Integer. Offset in the buffer where the message starts.
  • +
  • length Integer. Number of bytes in the message.
  • +
  • port Integer. destination port
  • +
  • address String. destination IP
  • +
  • callback Function. Callback when message is done being delivered. +Optional.
  • +
+

For UDP sockets, the destination port and IP address must be specified. A string +may be supplied for the address parameter, and it will be resolved with DNS. An +optional callback may be specified to detect any DNS errors and when buf may be +re-used. Note that DNS lookups will delay the time that a send takes place, at +least until the next tick. The only way to know for sure that a send has taken place +is to use the callback. + +

+

If the socket has not been previously bound with a call to bind, it's +assigned a random port number and bound to the "all interfaces" address +(0.0.0.0 for udp4 sockets, ::0 for udp6 sockets). + +

+

Example of sending a UDP packet to a random port on localhost; + +

+
var dgram = require('dgram');
+var message = new Buffer("Some bytes");
+var client = dgram.createSocket("udp4");
+client.send(message, 0, message.length, 41234, "localhost", function(err, bytes) {
+  client.close();
+});
+

A Note about UDP datagram size + +

+

The maximum size of an IPv4/v6 datagram depends on the MTU (Maximum Transmission Unit) +and on the Payload Length field size. + +

+
    +
  • The Payload Length field is 16 bits wide, which means that a normal payload +cannot be larger than 64K octets including internet header and data +(65,507 bytes = 65,535 − 8 bytes UDP header − 20 bytes IP header); +this is generally true for loopback interfaces, but such long datagrams +are impractical for most hosts and networks.

    +
  • +
  • The MTU is the largest size a given link layer technology can support for datagrams. +For any link, IPv4 mandates a minimum MTU of 68 octets, while the recommended MTU +for IPv4 is 576 (typically recommended as the MTU for dial-up type applications), +whether they arrive whole or in fragments.

    +

    For IPv6, the minimum MTU is 1280 octets, however, the mandatory minimum +fragment reassembly buffer size is 1500 octets. +The value of 68 octets is very small, since most current link layer technologies have +a minimum MTU of 1500 (like Ethernet).

    +
  • +
+

Note that it's impossible to know in advance the MTU of each link through which +a packet might travel, and that generally sending a datagram greater than +the (receiver) MTU won't work (the packet gets silently dropped, without +informing the source that the data did not reach its intended recipient). + +

+

dgram.bind(port, [address])#

+
    +
  • port Integer
  • +
  • address String, Optional
  • +
+

For UDP sockets, listen for datagrams on a named port and optional address. If +address is not specified, the OS will try to listen on all addresses. + +

+

Example of a UDP server listening on port 41234: + +

+
var dgram = require("dgram");
+
+var server = dgram.createSocket("udp4");
+
+server.on("message", function (msg, rinfo) {
+  console.log("server got: " + msg + " from " +
+    rinfo.address + ":" + rinfo.port);
+});
+
+server.on("listening", function () {
+  var address = server.address();
+  console.log("server listening " +
+      address.address + ":" + address.port);
+});
+
+server.bind(41234);
+// server listening 0.0.0.0:41234
+

dgram.close()#

+

Close the underlying socket and stop listening for data on it. + +

+

dgram.address()#

+

Returns an object containing the address information for a socket. For UDP sockets, +this object will contain address , family and port. + +

+

dgram.setBroadcast(flag)#

+
    +
  • flag Boolean
  • +
+

Sets or clears the SO_BROADCAST socket option. When this option is set, UDP packets +may be sent to a local interface's broadcast address. + +

+

dgram.setTTL(ttl)#

+
    +
  • ttl Integer
  • +
+

Sets the IP_TTL socket option. TTL stands for "Time to Live," but in this context it +specifies the number of IP hops that a packet is allowed to go through. Each router or +gateway that forwards a packet decrements the TTL. If the TTL is decremented to 0 by a +router, it will not be forwarded. Changing TTL values is typically done for network +probes or when multicasting. + +

+

The argument to setTTL() is a number of hops between 1 and 255. The default on most +systems is 64. + +

+

dgram.setMulticastTTL(ttl)#

+
    +
  • ttl Integer
  • +
+

Sets the IP_MULTICAST_TTL socket option. TTL stands for "Time to Live," but in this +context it specifies the number of IP hops that a packet is allowed to go through, +specifically for multicast traffic. Each router or gateway that forwards a packet +decrements the TTL. If the TTL is decremented to 0 by a router, it will not be forwarded. + +

+

The argument to setMulticastTTL() is a number of hops between 0 and 255. The default on most +systems is 1. + +

+

dgram.setMulticastLoopback(flag)#

+
    +
  • flag Boolean
  • +
+

Sets or clears the IP_MULTICAST_LOOP socket option. When this option is set, multicast +packets will also be received on the local interface. + +

+

dgram.addMembership(multicastAddress, [multicastInterface])#

+
    +
  • multicastAddress String
  • +
  • multicastInterface String, Optional
  • +
+

Tells the kernel to join a multicast group with IP_ADD_MEMBERSHIP socket option. + +

+

If multicastInterface is not specified, the OS will try to add membership to all valid +interfaces. + +

+

dgram.dropMembership(multicastAddress, [multicastInterface])#

+
    +
  • multicastAddress String
  • +
  • multicastInterface String, Optional
  • +
+

Opposite of addMembership - tells the kernel to leave a multicast group with +IP_DROP_MEMBERSHIP socket option. This is automatically called by the kernel +when the socket is closed or process terminates, so most apps will never need to call +this. + +

+

If multicastInterface is not specified, the OS will try to drop membership to all valid +interfaces. +

+ +
+
+
+ + + + + + + + + diff --git a/node-v0.8.14/doc/api/dgram.json b/node-v0.8.14/doc/api/dgram.json new file mode 100644 index 0000000..ab70c05 --- /dev/null +++ b/node-v0.8.14/doc/api/dgram.json @@ -0,0 +1,381 @@ +{ + "source": "doc/api/dgram.markdown", + "modules": [ + { + "textRaw": "UDP / Datagram Sockets", + "name": "dgram", + "stability": 3, + "stabilityText": "Stable", + "desc": "

Datagram sockets are available through require('dgram').\n\n

\n", + "methods": [ + { + "textRaw": "dgram.createSocket(type, [callback])", + "type": "method", + "name": "createSocket", + "signatures": [ + { + "return": { + "textRaw": "Returns: Socket object ", + "name": "return", + "desc": "Socket object" + }, + "params": [ + { + "textRaw": "`type` String. Either 'udp4' or 'udp6' ", + "name": "type", + "desc": "String. Either 'udp4' or 'udp6'" + }, + { + "textRaw": "`callback` Function. Attached as a listener to `message` events. Optional ", + "name": "callback", + "optional": true, + "desc": "Function. Attached as a listener to `message` events." + } + ] + }, + { + "params": [ + { + "name": "type" + }, + { + "name": "callback", + "optional": true + } + ] + } + ], + "desc": "

Creates a datagram Socket of the specified types. Valid types are udp4\nand udp6.\n\n

\n

Takes an optional callback which is added as a listener for message events.\n\n

\n

Call socket.bind if you want to receive datagrams. socket.bind() will bind\nto the "all interfaces" address on a random port (it does the right thing for\nboth udp4 and udp6 sockets). You can then retrieve the address and port\nwith socket.address().address and socket.address().port.\n\n

\n" + } + ], + "classes": [ + { + "textRaw": "Class: Socket", + "type": "class", + "name": "Socket", + "desc": "

The dgram Socket class encapsulates the datagram functionality. It\nshould be created via dgram.createSocket(type, [callback]).\n\n

\n", + "events": [ + { + "textRaw": "Event: 'message'", + "type": "event", + "name": "message", + "params": [], + "desc": "

Emitted when a new datagram is available on a socket. msg is a Buffer and rinfo is\nan object with the sender's address information and the number of bytes in the datagram.\n\n

\n" + }, + { + "textRaw": "Event: 'listening'", + "type": "event", + "name": "listening", + "desc": "

Emitted when a socket starts listening for datagrams. This happens as soon as UDP sockets\nare created.\n\n

\n", + "params": [] + }, + { + "textRaw": "Event: 'close'", + "type": "event", + "name": "close", + "desc": "

Emitted when a socket is closed with close(). No new message events will be emitted\non this socket.\n\n

\n", + "params": [] + }, + { + "textRaw": "Event: 'error'", + "type": "event", + "name": "error", + "params": [], + "desc": "

Emitted when an error occurs.\n\n

\n" + } + ], + "methods": [ + { + "textRaw": "dgram.send(buf, offset, length, port, address, [callback])", + "type": "method", + "name": "send", + "signatures": [ + { + "params": [ + { + "textRaw": "`buf` Buffer object. Message to be sent ", + "name": "buf", + "desc": "Buffer object. Message to be sent" + }, + { + "textRaw": "`offset` Integer. Offset in the buffer where the message starts. ", + "name": "offset", + "desc": "Integer. Offset in the buffer where the message starts." + }, + { + "textRaw": "`length` Integer. Number of bytes in the message. ", + "name": "length", + "desc": "Integer. Number of bytes in the message." + }, + { + "textRaw": "`port` Integer. destination port ", + "name": "port", + "desc": "Integer. destination port" + }, + { + "textRaw": "`address` String. destination IP ", + "name": "address", + "desc": "String. destination IP" + }, + { + "textRaw": "`callback` Function. Callback when message is done being delivered. Optional. ", + "name": "callback", + "desc": "Function. Callback when message is done being delivered. Optional.", + "optional": true + } + ] + }, + { + "params": [ + { + "name": "buf" + }, + { + "name": "offset" + }, + { + "name": "length" + }, + { + "name": "port" + }, + { + "name": "address" + }, + { + "name": "callback", + "optional": true + } + ] + } + ], + "desc": "

For UDP sockets, the destination port and IP address must be specified. A string\nmay be supplied for the address parameter, and it will be resolved with DNS. An\noptional callback may be specified to detect any DNS errors and when buf may be\nre-used. Note that DNS lookups will delay the time that a send takes place, at\nleast until the next tick. The only way to know for sure that a send has taken place\nis to use the callback.\n\n

\n

If the socket has not been previously bound with a call to bind, it's\nassigned a random port number and bound to the "all interfaces" address\n(0.0.0.0 for udp4 sockets, ::0 for udp6 sockets).\n\n

\n

Example of sending a UDP packet to a random port on localhost;\n\n

\n
var dgram = require('dgram');\nvar message = new Buffer("Some bytes");\nvar client = dgram.createSocket("udp4");\nclient.send(message, 0, message.length, 41234, "localhost", function(err, bytes) {\n  client.close();\n});
\n

A Note about UDP datagram size\n\n

\n

The maximum size of an IPv4/v6 datagram depends on the MTU (Maximum Transmission Unit)\nand on the Payload Length field size.\n\n

\n
    \n
  • The Payload Length field is 16 bits wide, which means that a normal payload\ncannot be larger than 64K octets including internet header and data\n(65,507 bytes = 65,535 − 8 bytes UDP header − 20 bytes IP header);\nthis is generally true for loopback interfaces, but such long datagrams\nare impractical for most hosts and networks.

    \n
  • \n
  • The MTU is the largest size a given link layer technology can support for datagrams.\nFor any link, IPv4 mandates a minimum MTU of 68 octets, while the recommended MTU\nfor IPv4 is 576 (typically recommended as the MTU for dial-up type applications),\nwhether they arrive whole or in fragments.

    \n

    For IPv6, the minimum MTU is 1280 octets, however, the mandatory minimum\nfragment reassembly buffer size is 1500 octets.\nThe value of 68 octets is very small, since most current link layer technologies have\na minimum MTU of 1500 (like Ethernet).

    \n
  • \n
\n

Note that it's impossible to know in advance the MTU of each link through which\na packet might travel, and that generally sending a datagram greater than\nthe (receiver) MTU won't work (the packet gets silently dropped, without\ninforming the source that the data did not reach its intended recipient).\n\n

\n" + }, + { + "textRaw": "dgram.bind(port, [address])", + "type": "method", + "name": "bind", + "signatures": [ + { + "params": [ + { + "textRaw": "`port` Integer ", + "name": "port", + "desc": "Integer" + }, + { + "textRaw": "`address` String, Optional ", + "name": "address", + "optional": true, + "desc": "String" + } + ] + }, + { + "params": [ + { + "name": "port" + }, + { + "name": "address", + "optional": true + } + ] + } + ], + "desc": "

For UDP sockets, listen for datagrams on a named port and optional address. If\naddress is not specified, the OS will try to listen on all addresses.\n\n

\n

Example of a UDP server listening on port 41234:\n\n

\n
var dgram = require("dgram");\n\nvar server = dgram.createSocket("udp4");\n\nserver.on("message", function (msg, rinfo) {\n  console.log("server got: " + msg + " from " +\n    rinfo.address + ":" + rinfo.port);\n});\n\nserver.on("listening", function () {\n  var address = server.address();\n  console.log("server listening " +\n      address.address + ":" + address.port);\n});\n\nserver.bind(41234);\n// server listening 0.0.0.0:41234
\n" + }, + { + "textRaw": "dgram.close()", + "type": "method", + "name": "close", + "desc": "

Close the underlying socket and stop listening for data on it.\n\n

\n", + "signatures": [ + { + "params": [] + } + ] + }, + { + "textRaw": "dgram.address()", + "type": "method", + "name": "address", + "desc": "

Returns an object containing the address information for a socket. For UDP sockets,\nthis object will contain address , family and port.\n\n

\n", + "signatures": [ + { + "params": [] + } + ] + }, + { + "textRaw": "dgram.setBroadcast(flag)", + "type": "method", + "name": "setBroadcast", + "signatures": [ + { + "params": [ + { + "textRaw": "`flag` Boolean ", + "name": "flag", + "desc": "Boolean" + } + ] + }, + { + "params": [ + { + "name": "flag" + } + ] + } + ], + "desc": "

Sets or clears the SO_BROADCAST socket option. When this option is set, UDP packets\nmay be sent to a local interface's broadcast address.\n\n

\n" + }, + { + "textRaw": "dgram.setTTL(ttl)", + "type": "method", + "name": "setTTL", + "signatures": [ + { + "params": [ + { + "textRaw": "`ttl` Integer ", + "name": "ttl", + "desc": "Integer" + } + ] + }, + { + "params": [ + { + "name": "ttl" + } + ] + } + ], + "desc": "

Sets the IP_TTL socket option. TTL stands for "Time to Live," but in this context it\nspecifies the number of IP hops that a packet is allowed to go through. Each router or\ngateway that forwards a packet decrements the TTL. If the TTL is decremented to 0 by a\nrouter, it will not be forwarded. Changing TTL values is typically done for network\nprobes or when multicasting.\n\n

\n

The argument to setTTL() is a number of hops between 1 and 255. The default on most\nsystems is 64.\n\n

\n" + }, + { + "textRaw": "dgram.setMulticastTTL(ttl)", + "type": "method", + "name": "setMulticastTTL", + "signatures": [ + { + "params": [ + { + "textRaw": "`ttl` Integer ", + "name": "ttl", + "desc": "Integer" + } + ] + }, + { + "params": [ + { + "name": "ttl" + } + ] + } + ], + "desc": "

Sets the IP_MULTICAST_TTL socket option. TTL stands for "Time to Live," but in this\ncontext it specifies the number of IP hops that a packet is allowed to go through,\nspecifically for multicast traffic. Each router or gateway that forwards a packet\ndecrements the TTL. If the TTL is decremented to 0 by a router, it will not be forwarded.\n\n

\n

The argument to setMulticastTTL() is a number of hops between 0 and 255. The default on most\nsystems is 1.\n\n

\n" + }, + { + "textRaw": "dgram.setMulticastLoopback(flag)", + "type": "method", + "name": "setMulticastLoopback", + "signatures": [ + { + "params": [ + { + "textRaw": "`flag` Boolean ", + "name": "flag", + "desc": "Boolean" + } + ] + }, + { + "params": [ + { + "name": "flag" + } + ] + } + ], + "desc": "

Sets or clears the IP_MULTICAST_LOOP socket option. When this option is set, multicast\npackets will also be received on the local interface.\n\n

\n" + }, + { + "textRaw": "dgram.addMembership(multicastAddress, [multicastInterface])", + "type": "method", + "name": "addMembership", + "signatures": [ + { + "params": [ + { + "textRaw": "`multicastAddress` String ", + "name": "multicastAddress", + "desc": "String" + }, + { + "textRaw": "`multicastInterface` String, Optional ", + "name": "multicastInterface", + "optional": true, + "desc": "String" + } + ] + }, + { + "params": [ + { + "name": "multicastAddress" + }, + { + "name": "multicastInterface", + "optional": true + } + ] + } + ], + "desc": "

Tells the kernel to join a multicast group with IP_ADD_MEMBERSHIP socket option.\n\n

\n

If multicastInterface is not specified, the OS will try to add membership to all valid\ninterfaces.\n\n

\n" + }, + { + "textRaw": "dgram.dropMembership(multicastAddress, [multicastInterface])", + "type": "method", + "name": "dropMembership", + "signatures": [ + { + "params": [ + { + "textRaw": "`multicastAddress` String ", + "name": "multicastAddress", + "desc": "String" + }, + { + "textRaw": "`multicastInterface` String, Optional ", + "name": "multicastInterface", + "optional": true, + "desc": "String" + } + ] + }, + { + "params": [ + { + "name": "multicastAddress" + }, + { + "name": "multicastInterface", + "optional": true + } + ] + } + ], + "desc": "

Opposite of addMembership - tells the kernel to leave a multicast group with\nIP_DROP_MEMBERSHIP socket option. This is automatically called by the kernel\nwhen the socket is closed or process terminates, so most apps will never need to call\nthis.\n\n

\n

If multicastInterface is not specified, the OS will try to drop membership to all valid\ninterfaces.\n

\n" + } + ] + } + ], + "type": "module", + "displayName": "dgram" + } + ] +} diff --git a/node-v0.8.14/doc/api/dgram.markdown b/node-v0.8.14/doc/api/dgram.markdown new file mode 100644 index 0000000..a14a42b --- /dev/null +++ b/node-v0.8.14/doc/api/dgram.markdown @@ -0,0 +1,209 @@ +# UDP / Datagram Sockets + + Stability: 3 - Stable + + + +Datagram sockets are available through `require('dgram')`. + +## dgram.createSocket(type, [callback]) + +* `type` String. Either 'udp4' or 'udp6' +* `callback` Function. Attached as a listener to `message` events. + Optional +* Returns: Socket object + +Creates a datagram Socket of the specified types. Valid types are `udp4` +and `udp6`. + +Takes an optional callback which is added as a listener for `message` events. + +Call `socket.bind` if you want to receive datagrams. `socket.bind()` will bind +to the "all interfaces" address on a random port (it does the right thing for +both `udp4` and `udp6` sockets). You can then retrieve the address and port +with `socket.address().address` and `socket.address().port`. + +## Class: Socket + +The dgram Socket class encapsulates the datagram functionality. It +should be created via `dgram.createSocket(type, [callback])`. + +### Event: 'message' + +* `msg` Buffer object. The message +* `rinfo` Object. Remote address information + +Emitted when a new datagram is available on a socket. `msg` is a `Buffer` and `rinfo` is +an object with the sender's address information and the number of bytes in the datagram. + +### Event: 'listening' + +Emitted when a socket starts listening for datagrams. This happens as soon as UDP sockets +are created. + +### Event: 'close' + +Emitted when a socket is closed with `close()`. No new `message` events will be emitted +on this socket. + +### Event: 'error' + +* `exception` Error object + +Emitted when an error occurs. + +### dgram.send(buf, offset, length, port, address, [callback]) + +* `buf` Buffer object. Message to be sent +* `offset` Integer. Offset in the buffer where the message starts. +* `length` Integer. Number of bytes in the message. +* `port` Integer. destination port +* `address` String. destination IP +* `callback` Function. Callback when message is done being delivered. + Optional. + +For UDP sockets, the destination port and IP address must be specified. A string +may be supplied for the `address` parameter, and it will be resolved with DNS. An +optional callback may be specified to detect any DNS errors and when `buf` may be +re-used. Note that DNS lookups will delay the time that a send takes place, at +least until the next tick. The only way to know for sure that a send has taken place +is to use the callback. + +If the socket has not been previously bound with a call to `bind`, it's +assigned a random port number and bound to the "all interfaces" address +(0.0.0.0 for `udp4` sockets, ::0 for `udp6` sockets). + +Example of sending a UDP packet to a random port on `localhost`; + + var dgram = require('dgram'); + var message = new Buffer("Some bytes"); + var client = dgram.createSocket("udp4"); + client.send(message, 0, message.length, 41234, "localhost", function(err, bytes) { + client.close(); + }); + +**A Note about UDP datagram size** + +The maximum size of an `IPv4/v6` datagram depends on the `MTU` (_Maximum Transmission Unit_) +and on the `Payload Length` field size. + +- The `Payload Length` field is `16 bits` wide, which means that a normal payload + cannot be larger than 64K octets including internet header and data + (65,507 bytes = 65,535 − 8 bytes UDP header − 20 bytes IP header); + this is generally true for loopback interfaces, but such long datagrams + are impractical for most hosts and networks. + +- The `MTU` is the largest size a given link layer technology can support for datagrams. + For any link, `IPv4` mandates a minimum `MTU` of `68` octets, while the recommended `MTU` + for IPv4 is `576` (typically recommended as the `MTU` for dial-up type applications), + whether they arrive whole or in fragments. + + For `IPv6`, the minimum `MTU` is `1280` octets, however, the mandatory minimum + fragment reassembly buffer size is `1500` octets. + The value of `68` octets is very small, since most current link layer technologies have + a minimum `MTU` of `1500` (like Ethernet). + +Note that it's impossible to know in advance the MTU of each link through which +a packet might travel, and that generally sending a datagram greater than +the (receiver) `MTU` won't work (the packet gets silently dropped, without +informing the source that the data did not reach its intended recipient). + +### dgram.bind(port, [address]) + +* `port` Integer +* `address` String, Optional + +For UDP sockets, listen for datagrams on a named `port` and optional `address`. If +`address` is not specified, the OS will try to listen on all addresses. + +Example of a UDP server listening on port 41234: + + var dgram = require("dgram"); + + var server = dgram.createSocket("udp4"); + + server.on("message", function (msg, rinfo) { + console.log("server got: " + msg + " from " + + rinfo.address + ":" + rinfo.port); + }); + + server.on("listening", function () { + var address = server.address(); + console.log("server listening " + + address.address + ":" + address.port); + }); + + server.bind(41234); + // server listening 0.0.0.0:41234 + + +### dgram.close() + +Close the underlying socket and stop listening for data on it. + +### dgram.address() + +Returns an object containing the address information for a socket. For UDP sockets, +this object will contain `address` , `family` and `port`. + +### dgram.setBroadcast(flag) + +* `flag` Boolean + +Sets or clears the `SO_BROADCAST` socket option. When this option is set, UDP packets +may be sent to a local interface's broadcast address. + +### dgram.setTTL(ttl) + +* `ttl` Integer + +Sets the `IP_TTL` socket option. TTL stands for "Time to Live," but in this context it +specifies the number of IP hops that a packet is allowed to go through. Each router or +gateway that forwards a packet decrements the TTL. If the TTL is decremented to 0 by a +router, it will not be forwarded. Changing TTL values is typically done for network +probes or when multicasting. + +The argument to `setTTL()` is a number of hops between 1 and 255. The default on most +systems is 64. + +### dgram.setMulticastTTL(ttl) + +* `ttl` Integer + +Sets the `IP_MULTICAST_TTL` socket option. TTL stands for "Time to Live," but in this +context it specifies the number of IP hops that a packet is allowed to go through, +specifically for multicast traffic. Each router or gateway that forwards a packet +decrements the TTL. If the TTL is decremented to 0 by a router, it will not be forwarded. + +The argument to `setMulticastTTL()` is a number of hops between 0 and 255. The default on most +systems is 1. + +### dgram.setMulticastLoopback(flag) + +* `flag` Boolean + +Sets or clears the `IP_MULTICAST_LOOP` socket option. When this option is set, multicast +packets will also be received on the local interface. + +### dgram.addMembership(multicastAddress, [multicastInterface]) + +* `multicastAddress` String +* `multicastInterface` String, Optional + +Tells the kernel to join a multicast group with `IP_ADD_MEMBERSHIP` socket option. + +If `multicastInterface` is not specified, the OS will try to add membership to all valid +interfaces. + +### dgram.dropMembership(multicastAddress, [multicastInterface]) + +* `multicastAddress` String +* `multicastInterface` String, Optional + +Opposite of `addMembership` - tells the kernel to leave a multicast group with +`IP_DROP_MEMBERSHIP` socket option. This is automatically called by the kernel +when the socket is closed or process terminates, so most apps will never need to call +this. + +If `multicastInterface` is not specified, the OS will try to drop membership to all valid +interfaces. diff --git a/node-v0.8.14/doc/api/dns.html b/node-v0.8.14/doc/api/dns.html new file mode 100644 index 0000000..10de169 --- /dev/null +++ b/node-v0.8.14/doc/api/dns.html @@ -0,0 +1,257 @@ + + + + + DNS Node.js v0.8.14 Manual & Documentation + + + + + +
+ + + +
+
+ + +
+
+

Node.js v0.8.14 Manual & Documentation

+ +
+
+ + + +
+

DNS#

+
Stability: 3 - Stable
+

Use require('dns') to access this module. All methods in the dns module +use C-Ares except for dns.lookup which uses getaddrinfo(3) in a thread +pool. C-Ares is much faster than getaddrinfo but the system resolver is +more constant with how other programs operate. When a user does +net.connect(80, 'google.com') or http.get({ host: 'google.com' }) the +dns.lookup method is used. Users who need to do a large number of look ups +quickly should use the methods that go through C-Ares. + +

+

Here is an example which resolves 'www.google.com' then reverse +resolves the IP addresses which are returned. + +

+
var dns = require('dns');
+
+dns.resolve4('www.google.com', function (err, addresses) {
+  if (err) throw err;
+
+  console.log('addresses: ' + JSON.stringify(addresses));
+
+  addresses.forEach(function (a) {
+    dns.reverse(a, function (err, domains) {
+      if (err) {
+        throw err;
+      }
+
+      console.log('reverse for ' + a + ': ' + JSON.stringify(domains));
+    });
+  });
+});
+

dns.lookup(domain, [family], callback)#

+

Resolves a domain (e.g. 'google.com') into the first found A (IPv4) or +AAAA (IPv6) record. +The family can be the integer 4 or 6. Defaults to null that indicates +both Ip v4 and v6 address family. + +

+

The callback has arguments (err, address, family). The address argument +is a string representation of a IP v4 or v6 address. The family argument +is either the integer 4 or 6 and denotes the family of address (not +necessarily the value initially passed to lookup). + +

+

On error, err is an Error object, where err.code is the error code. +Keep in mind that err.code will be set to 'ENOENT' not only when +the domain does not exist but also when the lookup fails in other ways +such as no available file descriptors. + + +

+

dns.resolve(domain, [rrtype], callback)#

+

Resolves a domain (e.g. 'google.com') into an array of the record types +specified by rrtype. Valid rrtypes are 'A' (IPV4 addresses, default), +'AAAA' (IPV6 addresses), 'MX' (mail exchange records), 'TXT' (text +records), 'SRV' (SRV records), 'PTR' (used for reverse IP lookups), +'NS' (name server records) and 'CNAME' (canonical name records). + +

+

The callback has arguments (err, addresses). The type of each item +in addresses is determined by the record type, and described in the +documentation for the corresponding lookup methods below. + +

+

On error, err is an Error object, where err.code is +one of the error codes listed below. + + +

+

dns.resolve4(domain, callback)#

+

The same as dns.resolve(), but only for IPv4 queries (A records). +addresses is an array of IPv4 addresses (e.g. +['74.125.79.104', '74.125.79.105', '74.125.79.106']). + +

+

dns.resolve6(domain, callback)#

+

The same as dns.resolve4() except for IPv6 queries (an AAAA query). + + +

+

dns.resolveMx(domain, callback)#

+

The same as dns.resolve(), but only for mail exchange queries (MX records). + +

+

addresses is an array of MX records, each with a priority and an exchange +attribute (e.g. [{'priority': 10, 'exchange': 'mx.example.com'},...]). + +

+

dns.resolveTxt(domain, callback)#

+

The same as dns.resolve(), but only for text queries (TXT records). +addresses is an array of the text records available for domain (e.g., +['v=spf1 ip4:0.0.0.0 ~all']). + +

+

dns.resolveSrv(domain, callback)#

+

The same as dns.resolve(), but only for service records (SRV records). +addresses is an array of the SRV records available for domain. Properties +of SRV records are priority, weight, port, and name (e.g., +[{'priority': 10, {'weight': 5, 'port': 21223, 'name': 'service.example.com'}, ...]). + +

+

dns.resolveNs(domain, callback)#

+

The same as dns.resolve(), but only for name server records (NS records). +addresses is an array of the name server records available for domain +(e.g., ['ns1.example.com', 'ns2.example.com']). + +

+

dns.resolveCname(domain, callback)#

+

The same as dns.resolve(), but only for canonical name records (CNAME +records). addresses is an array of the canonical name records available for +domain (e.g., ['bar.example.com']). + +

+

dns.reverse(ip, callback)#

+

Reverse resolves an ip address to an array of domain names. + +

+

The callback has arguments (err, domains). + +

+

On error, err is an Error object, where err.code is +one of the error codes listed below. + +

+

Error codes#

+

Each DNS query can return one of the following error codes: + +

+
    +
  • dns.NODATA: DNS server returned answer with no data.
  • +
  • dns.FORMERR: DNS server claims query was misformatted.
  • +
  • dns.SERVFAIL: DNS server returned general failure.
  • +
  • dns.NOTFOUND: Domain name not found.
  • +
  • dns.NOTIMP: DNS server does not implement requested operation.
  • +
  • dns.REFUSED: DNS server refused query.
  • +
  • dns.BADQUERY: Misformatted DNS query.
  • +
  • dns.BADNAME: Misformatted domain name.
  • +
  • dns.BADFAMILY: Unsupported address family.
  • +
  • dns.BADRESP: Misformatted DNS reply.
  • +
  • dns.CONNREFUSED: Could not contact DNS servers.
  • +
  • dns.TIMEOUT: Timeout while contacting DNS servers.
  • +
  • dns.EOF: End of file.
  • +
  • dns.FILE: Error reading file.
  • +
  • dns.NOMEM: Out of memory.
  • +
  • dns.DESTRUCTION: Channel is being destroyed.
  • +
  • dns.BADSTR: Misformatted string.
  • +
  • dns.BADFLAGS: Illegal flags specified.
  • +
  • dns.NONAME: Given hostname is not numeric.
  • +
  • dns.BADHINTS: Illegal hints flags specified.
  • +
  • dns.NOTINITIALIZED: c-ares library initialization not yet performed.
  • +
  • dns.LOADIPHLPAPI: Error loading iphlpapi.dll.
  • +
  • dns.ADDRGETNETWORKPARAMS: Could not find GetNetworkParams function.
  • +
  • dns.CANCELLED: DNS query cancelled.
  • +
+ +
+
+
+ + + + + + + + + diff --git a/node-v0.8.14/doc/api/dns.json b/node-v0.8.14/doc/api/dns.json new file mode 100644 index 0000000..9f5d787 --- /dev/null +++ b/node-v0.8.14/doc/api/dns.json @@ -0,0 +1,213 @@ +{ + "source": "doc/api/dns.markdown", + "modules": [ + { + "textRaw": "DNS", + "name": "dns", + "stability": 3, + "stabilityText": "Stable", + "desc": "

Use require('dns') to access this module. All methods in the dns module\nuse C-Ares except for dns.lookup which uses getaddrinfo(3) in a thread\npool. C-Ares is much faster than getaddrinfo but the system resolver is\nmore constant with how other programs operate. When a user does\nnet.connect(80, 'google.com') or http.get({ host: 'google.com' }) the\ndns.lookup method is used. Users who need to do a large number of look ups\nquickly should use the methods that go through C-Ares.\n\n

\n

Here is an example which resolves 'www.google.com' then reverse\nresolves the IP addresses which are returned.\n\n

\n
var dns = require('dns');\n\ndns.resolve4('www.google.com', function (err, addresses) {\n  if (err) throw err;\n\n  console.log('addresses: ' + JSON.stringify(addresses));\n\n  addresses.forEach(function (a) {\n    dns.reverse(a, function (err, domains) {\n      if (err) {\n        throw err;\n      }\n\n      console.log('reverse for ' + a + ': ' + JSON.stringify(domains));\n    });\n  });\n});
\n", + "methods": [ + { + "textRaw": "dns.lookup(domain, [family], callback)", + "type": "method", + "name": "lookup", + "desc": "

Resolves a domain (e.g. 'google.com') into the first found A (IPv4) or\nAAAA (IPv6) record.\nThe family can be the integer 4 or 6. Defaults to null that indicates\nboth Ip v4 and v6 address family.\n\n

\n

The callback has arguments (err, address, family). The address argument\nis a string representation of a IP v4 or v6 address. The family argument\nis either the integer 4 or 6 and denotes the family of address (not\nnecessarily the value initially passed to lookup).\n\n

\n

On error, err is an Error object, where err.code is the error code.\nKeep in mind that err.code will be set to 'ENOENT' not only when\nthe domain does not exist but also when the lookup fails in other ways\nsuch as no available file descriptors.\n\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "domain" + }, + { + "name": "family", + "optional": true + }, + { + "name": "callback" + } + ] + } + ] + }, + { + "textRaw": "dns.resolve(domain, [rrtype], callback)", + "type": "method", + "name": "resolve", + "desc": "

Resolves a domain (e.g. 'google.com') into an array of the record types\nspecified by rrtype. Valid rrtypes are 'A' (IPV4 addresses, default),\n'AAAA' (IPV6 addresses), 'MX' (mail exchange records), 'TXT' (text\nrecords), 'SRV' (SRV records), 'PTR' (used for reverse IP lookups),\n'NS' (name server records) and 'CNAME' (canonical name records).\n\n

\n

The callback has arguments (err, addresses). The type of each item\nin addresses is determined by the record type, and described in the\ndocumentation for the corresponding lookup methods below.\n\n

\n

On error, err is an Error object, where err.code is\none of the error codes listed below.\n\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "domain" + }, + { + "name": "rrtype", + "optional": true + }, + { + "name": "callback" + } + ] + } + ] + }, + { + "textRaw": "dns.resolve4(domain, callback)", + "type": "method", + "name": "resolve4", + "desc": "

The same as dns.resolve(), but only for IPv4 queries (A records).\naddresses is an array of IPv4 addresses (e.g.\n['74.125.79.104', '74.125.79.105', '74.125.79.106']).\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "domain" + }, + { + "name": "callback" + } + ] + } + ] + }, + { + "textRaw": "dns.resolve6(domain, callback)", + "type": "method", + "name": "resolve6", + "desc": "

The same as dns.resolve4() except for IPv6 queries (an AAAA query).\n\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "domain" + }, + { + "name": "callback" + } + ] + } + ] + }, + { + "textRaw": "dns.resolveMx(domain, callback)", + "type": "method", + "name": "resolveMx", + "desc": "

The same as dns.resolve(), but only for mail exchange queries (MX records).\n\n

\n

addresses is an array of MX records, each with a priority and an exchange\nattribute (e.g. [{'priority': 10, 'exchange': 'mx.example.com'},...]).\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "domain" + }, + { + "name": "callback" + } + ] + } + ] + }, + { + "textRaw": "dns.resolveTxt(domain, callback)", + "type": "method", + "name": "resolveTxt", + "desc": "

The same as dns.resolve(), but only for text queries (TXT records).\naddresses is an array of the text records available for domain (e.g.,\n['v=spf1 ip4:0.0.0.0 ~all']).\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "domain" + }, + { + "name": "callback" + } + ] + } + ] + }, + { + "textRaw": "dns.resolveSrv(domain, callback)", + "type": "method", + "name": "resolveSrv", + "desc": "

The same as dns.resolve(), but only for service records (SRV records).\naddresses is an array of the SRV records available for domain. Properties\nof SRV records are priority, weight, port, and name (e.g.,\n[{'priority': 10, {'weight': 5, 'port': 21223, 'name': 'service.example.com'}, ...]).\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "domain" + }, + { + "name": "callback" + } + ] + } + ] + }, + { + "textRaw": "dns.resolveNs(domain, callback)", + "type": "method", + "name": "resolveNs", + "desc": "

The same as dns.resolve(), but only for name server records (NS records).\naddresses is an array of the name server records available for domain\n(e.g., ['ns1.example.com', 'ns2.example.com']).\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "domain" + }, + { + "name": "callback" + } + ] + } + ] + }, + { + "textRaw": "dns.resolveCname(domain, callback)", + "type": "method", + "name": "resolveCname", + "desc": "

The same as dns.resolve(), but only for canonical name records (CNAME\nrecords). addresses is an array of the canonical name records available for\ndomain (e.g., ['bar.example.com']).\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "domain" + }, + { + "name": "callback" + } + ] + } + ] + }, + { + "textRaw": "dns.reverse(ip, callback)", + "type": "method", + "name": "reverse", + "desc": "

Reverse resolves an ip address to an array of domain names.\n\n

\n

The callback has arguments (err, domains).\n\n

\n

On error, err is an Error object, where err.code is\none of the error codes listed below.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "ip" + }, + { + "name": "callback" + } + ] + } + ] + } + ], + "modules": [ + { + "textRaw": "Error codes", + "name": "error_codes", + "desc": "

Each DNS query can return one of the following error codes:\n\n

\n
    \n
  • dns.NODATA: DNS server returned answer with no data.
  • \n
  • dns.FORMERR: DNS server claims query was misformatted.
  • \n
  • dns.SERVFAIL: DNS server returned general failure.
  • \n
  • dns.NOTFOUND: Domain name not found.
  • \n
  • dns.NOTIMP: DNS server does not implement requested operation.
  • \n
  • dns.REFUSED: DNS server refused query.
  • \n
  • dns.BADQUERY: Misformatted DNS query.
  • \n
  • dns.BADNAME: Misformatted domain name.
  • \n
  • dns.BADFAMILY: Unsupported address family.
  • \n
  • dns.BADRESP: Misformatted DNS reply.
  • \n
  • dns.CONNREFUSED: Could not contact DNS servers.
  • \n
  • dns.TIMEOUT: Timeout while contacting DNS servers.
  • \n
  • dns.EOF: End of file.
  • \n
  • dns.FILE: Error reading file.
  • \n
  • dns.NOMEM: Out of memory.
  • \n
  • dns.DESTRUCTION: Channel is being destroyed.
  • \n
  • dns.BADSTR: Misformatted string.
  • \n
  • dns.BADFLAGS: Illegal flags specified.
  • \n
  • dns.NONAME: Given hostname is not numeric.
  • \n
  • dns.BADHINTS: Illegal hints flags specified.
  • \n
  • dns.NOTINITIALIZED: c-ares library initialization not yet performed.
  • \n
  • dns.LOADIPHLPAPI: Error loading iphlpapi.dll.
  • \n
  • dns.ADDRGETNETWORKPARAMS: Could not find GetNetworkParams function.
  • \n
  • dns.CANCELLED: DNS query cancelled.
  • \n
\n", + "type": "module", + "displayName": "Error codes" + } + ], + "type": "module", + "displayName": "DNS" + } + ] +} diff --git a/node-v0.8.14/doc/api/dns.markdown b/node-v0.8.14/doc/api/dns.markdown new file mode 100644 index 0000000..f6cec4c --- /dev/null +++ b/node-v0.8.14/doc/api/dns.markdown @@ -0,0 +1,148 @@ +# DNS + + Stability: 3 - Stable + +Use `require('dns')` to access this module. All methods in the dns module +use C-Ares except for `dns.lookup` which uses `getaddrinfo(3)` in a thread +pool. C-Ares is much faster than `getaddrinfo` but the system resolver is +more constant with how other programs operate. When a user does +`net.connect(80, 'google.com')` or `http.get({ host: 'google.com' })` the +`dns.lookup` method is used. Users who need to do a large number of look ups +quickly should use the methods that go through C-Ares. + +Here is an example which resolves `'www.google.com'` then reverse +resolves the IP addresses which are returned. + + var dns = require('dns'); + + dns.resolve4('www.google.com', function (err, addresses) { + if (err) throw err; + + console.log('addresses: ' + JSON.stringify(addresses)); + + addresses.forEach(function (a) { + dns.reverse(a, function (err, domains) { + if (err) { + throw err; + } + + console.log('reverse for ' + a + ': ' + JSON.stringify(domains)); + }); + }); + }); + +## dns.lookup(domain, [family], callback) + +Resolves a domain (e.g. `'google.com'`) into the first found A (IPv4) or +AAAA (IPv6) record. +The `family` can be the integer `4` or `6`. Defaults to `null` that indicates +both Ip v4 and v6 address family. + +The callback has arguments `(err, address, family)`. The `address` argument +is a string representation of a IP v4 or v6 address. The `family` argument +is either the integer 4 or 6 and denotes the family of `address` (not +necessarily the value initially passed to `lookup`). + +On error, `err` is an `Error` object, where `err.code` is the error code. +Keep in mind that `err.code` will be set to `'ENOENT'` not only when +the domain does not exist but also when the lookup fails in other ways +such as no available file descriptors. + + +## dns.resolve(domain, [rrtype], callback) + +Resolves a domain (e.g. `'google.com'`) into an array of the record types +specified by rrtype. Valid rrtypes are `'A'` (IPV4 addresses, default), +`'AAAA'` (IPV6 addresses), `'MX'` (mail exchange records), `'TXT'` (text +records), `'SRV'` (SRV records), `'PTR'` (used for reverse IP lookups), +`'NS'` (name server records) and `'CNAME'` (canonical name records). + +The callback has arguments `(err, addresses)`. The type of each item +in `addresses` is determined by the record type, and described in the +documentation for the corresponding lookup methods below. + +On error, `err` is an `Error` object, where `err.code` is +one of the error codes listed below. + + +## dns.resolve4(domain, callback) + +The same as `dns.resolve()`, but only for IPv4 queries (`A` records). +`addresses` is an array of IPv4 addresses (e.g. +`['74.125.79.104', '74.125.79.105', '74.125.79.106']`). + +## dns.resolve6(domain, callback) + +The same as `dns.resolve4()` except for IPv6 queries (an `AAAA` query). + + +## dns.resolveMx(domain, callback) + +The same as `dns.resolve()`, but only for mail exchange queries (`MX` records). + +`addresses` is an array of MX records, each with a priority and an exchange +attribute (e.g. `[{'priority': 10, 'exchange': 'mx.example.com'},...]`). + +## dns.resolveTxt(domain, callback) + +The same as `dns.resolve()`, but only for text queries (`TXT` records). +`addresses` is an array of the text records available for `domain` (e.g., +`['v=spf1 ip4:0.0.0.0 ~all']`). + +## dns.resolveSrv(domain, callback) + +The same as `dns.resolve()`, but only for service records (`SRV` records). +`addresses` is an array of the SRV records available for `domain`. Properties +of SRV records are priority, weight, port, and name (e.g., +`[{'priority': 10, {'weight': 5, 'port': 21223, 'name': 'service.example.com'}, ...]`). + +## dns.resolveNs(domain, callback) + +The same as `dns.resolve()`, but only for name server records (`NS` records). +`addresses` is an array of the name server records available for `domain` +(e.g., `['ns1.example.com', 'ns2.example.com']`). + +## dns.resolveCname(domain, callback) + +The same as `dns.resolve()`, but only for canonical name records (`CNAME` +records). `addresses` is an array of the canonical name records available for +`domain` (e.g., `['bar.example.com']`). + +## dns.reverse(ip, callback) + +Reverse resolves an ip address to an array of domain names. + +The callback has arguments `(err, domains)`. + +On error, `err` is an `Error` object, where `err.code` is +one of the error codes listed below. + +## Error codes + +Each DNS query can return one of the following error codes: + +- `dns.NODATA`: DNS server returned answer with no data. +- `dns.FORMERR`: DNS server claims query was misformatted. +- `dns.SERVFAIL`: DNS server returned general failure. +- `dns.NOTFOUND`: Domain name not found. +- `dns.NOTIMP`: DNS server does not implement requested operation. +- `dns.REFUSED`: DNS server refused query. +- `dns.BADQUERY`: Misformatted DNS query. +- `dns.BADNAME`: Misformatted domain name. +- `dns.BADFAMILY`: Unsupported address family. +- `dns.BADRESP`: Misformatted DNS reply. +- `dns.CONNREFUSED`: Could not contact DNS servers. +- `dns.TIMEOUT`: Timeout while contacting DNS servers. +- `dns.EOF`: End of file. +- `dns.FILE`: Error reading file. +- `dns.NOMEM`: Out of memory. +- `dns.DESTRUCTION`: Channel is being destroyed. +- `dns.BADSTR`: Misformatted string. +- `dns.BADFLAGS`: Illegal flags specified. +- `dns.NONAME`: Given hostname is not numeric. +- `dns.BADHINTS`: Illegal hints flags specified. +- `dns.NOTINITIALIZED`: c-ares library initialization not yet performed. +- `dns.LOADIPHLPAPI`: Error loading iphlpapi.dll. +- `dns.ADDRGETNETWORKPARAMS`: Could not find GetNetworkParams function. +- `dns.CANCELLED`: DNS query cancelled. + diff --git a/node-v0.8.14/doc/api/documentation.html b/node-v0.8.14/doc/api/documentation.html new file mode 100644 index 0000000..802557d --- /dev/null +++ b/node-v0.8.14/doc/api/documentation.html @@ -0,0 +1,171 @@ + + + + + About this Documentation Node.js v0.8.14 Manual & Documentation + + + + + +
+ + + +
+
+ + +
+
+

Node.js v0.8.14 Manual & Documentation

+ +
+
+ +
+

Table of Contents

+ + +
+ +
+

About this Documentation#

+ + +

The goal of this documentation is to comprehensively explain the Node.js +API, both from a reference as well as a conceptual point of view. Each +section describes a built-in module or high-level concept. + +

+

Where appropriate, property types, method arguments, and the arguments +provided to event handlers are detailed in a list underneath the topic +heading. + +

+

Every .html document has a corresponding .json document presenting +the same information in a structured manner. This feature is +experimental, and added for the benefit of IDEs and other utilities that +wish to do programmatic things with the documentation. + +

+

Every .html and .json file is generated based on the corresponding +.markdown file in the doc/api/ folder in node's source tree. The +documentation is generated using the tools/doc/generate.js program. +The HTML template is located at doc/template.html. + +

+

Stability Index#

+ + +

Throughout the documentation, you will see indications of a section's +stability. The Node.js API is still somewhat changing, and as it +matures, certain parts are more reliable than others. Some are so +proven, and so relied upon, that they are unlikely to ever change at +all. Others are brand new and experimental, or known to be hazardous +and in the process of being redesigned. + +

+

The notices look like this: + +

+
Stability: 1 Experimental
+

The stability indices are as follows: + +

+
    +
  • 0 - Deprecated This feature is known to be problematic, and changes are +planned. Do not rely on it. Use of the feature may cause warnings. Backwards +compatibility should not be expected.
  • +
+
    +
  • 1 - Experimental This feature was introduced recently, and may change +or be removed in future versions. Please try it out and provide feedback. +If it addresses a use-case that is important to you, tell the node core team.
  • +
+
    +
  • 2 - Unstable The API is in the process of settling, but has not yet had +sufficient real-world testing to be considered stable. Backwards-compatibility +will be maintained if reasonable.
  • +
+
    +
  • 3 - Stable The API has proven satisfactory, but cleanup in the underlying +code may cause minor changes. Backwards-compatibility is guaranteed.
  • +
+
    +
  • 4 - API Frozen This API has been tested extensively in production and is +unlikely to ever have to change.
  • +
+
    +
  • 5 - Locked Unless serious bugs are found, this code will not ever +change. Please do not suggest changes in this area; they will be refused.
  • +
+

JSON Output#

+
Stability: 1 - Experimental
+

Every HTML file in the markdown has a corresponding JSON file with the +same data. + +

+

This feature is new as of node v0.6.12. It is experimental. +

+ +
+
+
+ + + + + + + + + diff --git a/node-v0.8.14/doc/api/documentation.json b/node-v0.8.14/doc/api/documentation.json new file mode 100644 index 0000000..14fb1c5 --- /dev/null +++ b/node-v0.8.14/doc/api/documentation.json @@ -0,0 +1,28 @@ +{ + "source": "doc/api/documentation.markdown", + "miscs": [ + { + "textRaw": "About this Documentation", + "name": "About this Documentation", + "type": "misc", + "desc": "

The goal of this documentation is to comprehensively explain the Node.js\nAPI, both from a reference as well as a conceptual point of view. Each\nsection describes a built-in module or high-level concept.\n\n

\n

Where appropriate, property types, method arguments, and the arguments\nprovided to event handlers are detailed in a list underneath the topic\nheading.\n\n

\n

Every .html document has a corresponding .json document presenting\nthe same information in a structured manner. This feature is\nexperimental, and added for the benefit of IDEs and other utilities that\nwish to do programmatic things with the documentation.\n\n

\n

Every .html and .json file is generated based on the corresponding\n.markdown file in the doc/api/ folder in node's source tree. The\ndocumentation is generated using the tools/doc/generate.js program.\nThe HTML template is located at doc/template.html.\n\n

\n", + "miscs": [ + { + "textRaw": "Stability Index", + "name": "Stability Index", + "type": "misc", + "desc": "

Throughout the documentation, you will see indications of a section's\nstability. The Node.js API is still somewhat changing, and as it\nmatures, certain parts are more reliable than others. Some are so\nproven, and so relied upon, that they are unlikely to ever change at\nall. Others are brand new and experimental, or known to be hazardous\nand in the process of being redesigned.\n\n

\n

The notices look like this:\n\n

\n
Stability: 1 Experimental
\n

The stability indices are as follows:\n\n

\n
    \n
  • 0 - Deprecated This feature is known to be problematic, and changes are\nplanned. Do not rely on it. Use of the feature may cause warnings. Backwards\ncompatibility should not be expected.
  • \n
\n
    \n
  • 1 - Experimental This feature was introduced recently, and may change\nor be removed in future versions. Please try it out and provide feedback.\nIf it addresses a use-case that is important to you, tell the node core team.
  • \n
\n
    \n
  • 2 - Unstable The API is in the process of settling, but has not yet had\nsufficient real-world testing to be considered stable. Backwards-compatibility\nwill be maintained if reasonable.
  • \n
\n
    \n
  • 3 - Stable The API has proven satisfactory, but cleanup in the underlying\ncode may cause minor changes. Backwards-compatibility is guaranteed.
  • \n
\n
    \n
  • 4 - API Frozen This API has been tested extensively in production and is\nunlikely to ever have to change.
  • \n
\n
    \n
  • 5 - Locked Unless serious bugs are found, this code will not ever\nchange. Please do not suggest changes in this area; they will be refused.
  • \n
\n" + }, + { + "textRaw": "JSON Output", + "name": "json_output", + "stability": 1, + "stabilityText": "Experimental", + "desc": "

Every HTML file in the markdown has a corresponding JSON file with the\nsame data.\n\n

\n

This feature is new as of node v0.6.12. It is experimental.\n

\n", + "type": "misc", + "displayName": "JSON Output" + } + ] + } + ] +} diff --git a/node-v0.8.14/doc/api/documentation.markdown b/node-v0.8.14/doc/api/documentation.markdown new file mode 100644 index 0000000..70a76c2 --- /dev/null +++ b/node-v0.8.14/doc/api/documentation.markdown @@ -0,0 +1,68 @@ +# About this Documentation + + + +The goal of this documentation is to comprehensively explain the Node.js +API, both from a reference as well as a conceptual point of view. Each +section describes a built-in module or high-level concept. + +Where appropriate, property types, method arguments, and the arguments +provided to event handlers are detailed in a list underneath the topic +heading. + +Every `.html` document has a corresponding `.json` document presenting +the same information in a structured manner. This feature is +experimental, and added for the benefit of IDEs and other utilities that +wish to do programmatic things with the documentation. + +Every `.html` and `.json` file is generated based on the corresponding +`.markdown` file in the `doc/api/` folder in node's source tree. The +documentation is generated using the `tools/doc/generate.js` program. +The HTML template is located at `doc/template.html`. + +## Stability Index + + + +Throughout the documentation, you will see indications of a section's +stability. The Node.js API is still somewhat changing, and as it +matures, certain parts are more reliable than others. Some are so +proven, and so relied upon, that they are unlikely to ever change at +all. Others are brand new and experimental, or known to be hazardous +and in the process of being redesigned. + +The notices look like this: + + Stability: 1 Experimental + +The stability indices are as follows: + +* **0 - Deprecated** This feature is known to be problematic, and changes are +planned. Do not rely on it. Use of the feature may cause warnings. Backwards +compatibility should not be expected. + +* **1 - Experimental** This feature was introduced recently, and may change +or be removed in future versions. Please try it out and provide feedback. +If it addresses a use-case that is important to you, tell the node core team. + +* **2 - Unstable** The API is in the process of settling, but has not yet had +sufficient real-world testing to be considered stable. Backwards-compatibility +will be maintained if reasonable. + +* **3 - Stable** The API has proven satisfactory, but cleanup in the underlying +code may cause minor changes. Backwards-compatibility is guaranteed. + +* **4 - API Frozen** This API has been tested extensively in production and is +unlikely to ever have to change. + +* **5 - Locked** Unless serious bugs are found, this code will not ever +change. Please do not suggest changes in this area; they will be refused. + +## JSON Output + + Stability: 1 - Experimental + +Every HTML file in the markdown has a corresponding JSON file with the +same data. + +This feature is new as of node v0.6.12. It is experimental. diff --git a/node-v0.8.14/doc/api/domain.html b/node-v0.8.14/doc/api/domain.html new file mode 100644 index 0000000..7c9cb37 --- /dev/null +++ b/node-v0.8.14/doc/api/domain.html @@ -0,0 +1,394 @@ + + + + + Domain Node.js v0.8.14 Manual & Documentation + + + + + +
+ + + +
+
+ + +
+
+

Node.js v0.8.14 Manual & Documentation

+ +
+
+ + + +
+

Domain#

+
Stability: 1 - Experimental
+

Domains provide a way to handle multiple different IO operations as a +single group. If any of the event emitters or callbacks registered to a +domain emit an error event, or throw an error, then the domain object +will be notified, rather than losing the context of the error in the +process.on('uncaughtException') handler, or causing the program to +exit with an error code. + +

+

This feature is new in Node version 0.8. It is a first pass, and is +expected to change significantly in future versions. Please use it and +provide feedback. + +

+

Due to their experimental nature, the Domains features are disabled unless +the domain module is loaded at least once. No domains are created or +registered by default. This is by design, to prevent adverse effects on +current programs. It is expected to be enabled by default in future +Node.js versions. + +

+

Additions to Error objects#

+ + +

Any time an Error object is routed through a domain, a few extra fields +are added to it. + +

+
    +
  • error.domain The domain that first handled the error.
  • +
  • error.domain_emitter The event emitter that emitted an 'error' event +with the error object.
  • +
  • error.domain_bound The callback function which was bound to the +domain, and passed an error as its first argument.
  • +
  • error.domain_thrown A boolean indicating whether the error was +thrown, emitted, or passed to a bound callback function.
  • +
+

Implicit Binding#

+ + +

If domains are in use, then all new EventEmitter objects (including +Stream objects, requests, responses, etc.) will be implicitly bound to +the active domain at the time of their creation. + +

+

Additionally, callbacks passed to lowlevel event loop requests (such as +to fs.open, or other callback-taking methods) will automatically be +bound to the active domain. If they throw, then the domain will catch +the error. + +

+

In order to prevent excessive memory usage, Domain objects themselves +are not implicitly added as children of the active domain. If they +were, then it would be too easy to prevent request and response objects +from being properly garbage collected. + +

+

If you want to nest Domain objects as children of a parent Domain, +then you must explicitly add them, and then dispose of them later. + +

+

Implicit binding routes thrown errors and 'error' events to the +Domain's error event, but does not register the EventEmitter on the +Domain, so domain.dispose() will not shut down the EventEmitter. +Implicit binding only takes care of thrown errors and 'error' events. + +

+

Explicit Binding#

+ + +

Sometimes, the domain in use is not the one that ought to be used for a +specific event emitter. Or, the event emitter could have been created +in the context of one domain, but ought to instead be bound to some +other domain. + +

+

For example, there could be one domain in use for an HTTP server, but +perhaps we would like to have a separate domain to use for each request. + +

+

That is possible via explicit binding. + +

+

For example: + +

+
// create a top-level domain for the server
+var serverDomain = domain.create();
+
+serverDomain.run(function() {
+  // server is created in the scope of serverDomain
+  http.createServer(function(req, res) {
+    // req and res are also created in the scope of serverDomain
+    // however, we'd prefer to have a separate domain for each request.
+    // create it first thing, and add req and res to it.
+    var reqd = domain.create();
+    reqd.add(req);
+    reqd.add(res);
+    reqd.on('error', function(er) {
+      console.error('Error', er, req.url);
+      try {
+        res.writeHead(500);
+        res.end('Error occurred, sorry.');
+        res.on('close', function() {
+          // forcibly shut down any other things added to this domain
+          reqd.dispose();
+        });
+      } catch (er) {
+        console.error('Error sending 500', er, req.url);
+        // tried our best.  clean up anything remaining.
+        reqd.dispose();
+      }
+    });
+  }).listen(1337);
+});
+

domain.create()#

+
    +
  • return: Domain
  • +
+

Returns a new Domain object. + +

+

Class: Domain#

+

The Domain class encapsulates the functionality of routing errors and +uncaught exceptions to the active Domain object. + +

+

Domain is a child class of EventEmitter. To handle the errors that it +catches, listen to its error event. + +

+

domain.run(fn)#

+
    +
  • fn Function
  • +
+

Run the supplied function in the context of the domain, implicitly +binding all event emitters, timers, and lowlevel requests that are +created in that context. + +

+

This is the most basic way to use a domain. + +

+

Example: + +

+
var d = domain.create();
+d.on('error', function(er) {
+  console.error('Caught error!', er);
+});
+d.run(function() {
+  process.nextTick(function() {
+    setTimeout(function() { // simulating some various async stuff
+      fs.open('non-existent file', 'r', function(er, fd) {
+        if (er) throw er;
+        // proceed...
+      });
+    }, 100);
+  });
+});
+

In this example, the d.on('error') handler will be triggered, rather +than crashing the program. + +

+

domain.members#

+
    +
  • Array
  • +
+

An array of timers and event emitters that have been explicitly added +to the domain. + +

+

domain.add(emitter)#

+
    +
  • emitter EventEmitter | Timer emitter or timer to be added to the domain
  • +
+

Explicitly adds an emitter to the domain. If any event handlers called by +the emitter throw an error, or if the emitter emits an error event, it +will be routed to the domain's error event, just like with implicit +binding. + +

+

This also works with timers that are returned from setInterval and +setTimeout. If their callback function throws, it will be caught by +the domain 'error' handler. + +

+

If the Timer or EventEmitter was already bound to a domain, it is removed +from that one, and bound to this one instead. + +

+

domain.remove(emitter)#

+
    +
  • emitter EventEmitter | Timer emitter or timer to be removed from the domain
  • +
+

The opposite of domain.add(emitter). Removes domain handling from the +specified emitter. + +

+

domain.bind(callback)#

+
    +
  • callback Function The callback function
  • +
  • return: Function The bound function
  • +
+

The returned function will be a wrapper around the supplied callback +function. When the returned function is called, any errors that are +thrown will be routed to the domain's error event. + +

+

Example#

+
var d = domain.create();
+
+function readSomeFile(filename, cb) {
+  fs.readFile(filename, 'utf8', d.bind(function(er, data) {
+    // if this throws, it will also be passed to the domain
+    return cb(er, data ? JSON.parse(data) : null);
+  }));
+}
+
+d.on('error', function(er) {
+  // an error occurred somewhere.
+  // if we throw it now, it will crash the program
+  // with the normal line number and stack message.
+});
+

domain.intercept(callback)#

+
    +
  • callback Function The callback function
  • +
  • return: Function The intercepted function
  • +
+

This method is almost identical to domain.bind(callback). However, in +addition to catching thrown errors, it will also intercept Error +objects sent as the first argument to the function. + +

+

In this way, the common if (er) return callback(er); pattern can be replaced +with a single error handler in a single place. + +

+

Example#

+
var d = domain.create();
+
+function readSomeFile(filename, cb) {
+  fs.readFile(filename, 'utf8', d.intercept(function(data) {
+    // note, the first argument is never passed to the
+    // callback since it is assumed to be the 'Error' argument
+    // and thus intercepted by the domain.
+
+    // if this throws, it will also be passed to the domain
+    // so the error-handling logic can be moved to the 'error'
+    // event on the domain instead of being repeated throughout
+    // the program.
+    return cb(null, JSON.parse(data));
+  }));
+}
+
+d.on('error', function(er) {
+  // an error occurred somewhere.
+  // if we throw it now, it will crash the program
+  // with the normal line number and stack message.
+});
+

domain.dispose()#

+

The dispose method destroys a domain, and makes a best effort attempt to +clean up any and all IO that is associated with the domain. Streams are +aborted, ended, closed, and/or destroyed. Timers are cleared. +Explicitly bound callbacks are no longer called. Any error events that +are raised as a result of this are ignored. + +

+

The intention of calling dispose is generally to prevent cascading +errors when a critical part of the Domain context is found to be in an +error state. + +

+

Once the domain is disposed the dispose event will emit. + +

+

Note that IO might still be performed. However, to the highest degree +possible, once a domain is disposed, further errors from the emitters in +that set will be ignored. So, even if some remaining actions are still +in flight, Node.js will not communicate further about them. + +

+ +
+
+
+ + + + + + + + + diff --git a/node-v0.8.14/doc/api/domain.json b/node-v0.8.14/doc/api/domain.json new file mode 100644 index 0000000..ef903d3 --- /dev/null +++ b/node-v0.8.14/doc/api/domain.json @@ -0,0 +1,219 @@ +{ + "source": "doc/api/domain.markdown", + "modules": [ + { + "textRaw": "Domain", + "name": "domain", + "stability": 1, + "stabilityText": "Experimental", + "desc": "

Domains provide a way to handle multiple different IO operations as a\nsingle group. If any of the event emitters or callbacks registered to a\ndomain emit an error event, or throw an error, then the domain object\nwill be notified, rather than losing the context of the error in the\nprocess.on('uncaughtException') handler, or causing the program to\nexit with an error code.\n\n

\n

This feature is new in Node version 0.8. It is a first pass, and is\nexpected to change significantly in future versions. Please use it and\nprovide feedback.\n\n

\n

Due to their experimental nature, the Domains features are disabled unless\nthe domain module is loaded at least once. No domains are created or\nregistered by default. This is by design, to prevent adverse effects on\ncurrent programs. It is expected to be enabled by default in future\nNode.js versions.\n\n

\n", + "miscs": [ + { + "textRaw": "Additions to Error objects", + "name": "Additions to Error objects", + "type": "misc", + "desc": "

Any time an Error object is routed through a domain, a few extra fields\nare added to it.\n\n

\n
    \n
  • error.domain The domain that first handled the error.
  • \n
  • error.domain_emitter The event emitter that emitted an 'error' event\nwith the error object.
  • \n
  • error.domain_bound The callback function which was bound to the\ndomain, and passed an error as its first argument.
  • \n
  • error.domain_thrown A boolean indicating whether the error was\nthrown, emitted, or passed to a bound callback function.
  • \n
\n" + }, + { + "textRaw": "Implicit Binding", + "name": "Implicit Binding", + "type": "misc", + "desc": "

If domains are in use, then all new EventEmitter objects (including\nStream objects, requests, responses, etc.) will be implicitly bound to\nthe active domain at the time of their creation.\n\n

\n

Additionally, callbacks passed to lowlevel event loop requests (such as\nto fs.open, or other callback-taking methods) will automatically be\nbound to the active domain. If they throw, then the domain will catch\nthe error.\n\n

\n

In order to prevent excessive memory usage, Domain objects themselves\nare not implicitly added as children of the active domain. If they\nwere, then it would be too easy to prevent request and response objects\nfrom being properly garbage collected.\n\n

\n

If you want to nest Domain objects as children of a parent Domain,\nthen you must explicitly add them, and then dispose of them later.\n\n

\n

Implicit binding routes thrown errors and 'error' events to the\nDomain's error event, but does not register the EventEmitter on the\nDomain, so domain.dispose() will not shut down the EventEmitter.\nImplicit binding only takes care of thrown errors and 'error' events.\n\n

\n" + }, + { + "textRaw": "Explicit Binding", + "name": "Explicit Binding", + "type": "misc", + "desc": "

Sometimes, the domain in use is not the one that ought to be used for a\nspecific event emitter. Or, the event emitter could have been created\nin the context of one domain, but ought to instead be bound to some\nother domain.\n\n

\n

For example, there could be one domain in use for an HTTP server, but\nperhaps we would like to have a separate domain to use for each request.\n\n

\n

That is possible via explicit binding.\n\n

\n

For example:\n\n

\n
// create a top-level domain for the server\nvar serverDomain = domain.create();\n\nserverDomain.run(function() {\n  // server is created in the scope of serverDomain\n  http.createServer(function(req, res) {\n    // req and res are also created in the scope of serverDomain\n    // however, we'd prefer to have a separate domain for each request.\n    // create it first thing, and add req and res to it.\n    var reqd = domain.create();\n    reqd.add(req);\n    reqd.add(res);\n    reqd.on('error', function(er) {\n      console.error('Error', er, req.url);\n      try {\n        res.writeHead(500);\n        res.end('Error occurred, sorry.');\n        res.on('close', function() {\n          // forcibly shut down any other things added to this domain\n          reqd.dispose();\n        });\n      } catch (er) {\n        console.error('Error sending 500', er, req.url);\n        // tried our best.  clean up anything remaining.\n        reqd.dispose();\n      }\n    });\n  }).listen(1337);\n});
\n" + } + ], + "methods": [ + { + "textRaw": "domain.create()", + "type": "method", + "name": "create", + "signatures": [ + { + "return": { + "textRaw": "return: {Domain} ", + "name": "return", + "type": "Domain" + }, + "params": [] + }, + { + "params": [] + } + ], + "desc": "

Returns a new Domain object.\n\n

\n" + } + ], + "classes": [ + { + "textRaw": "Class: Domain", + "type": "class", + "name": "Domain", + "desc": "

The Domain class encapsulates the functionality of routing errors and\nuncaught exceptions to the active Domain object.\n\n

\n

Domain is a child class of [EventEmitter][]. To handle the errors that it\ncatches, listen to its error event.\n\n

\n", + "methods": [ + { + "textRaw": "domain.run(fn)", + "type": "method", + "name": "run", + "signatures": [ + { + "params": [ + { + "textRaw": "`fn` {Function} ", + "name": "fn", + "type": "Function" + } + ] + }, + { + "params": [ + { + "name": "fn" + } + ] + } + ], + "desc": "

Run the supplied function in the context of the domain, implicitly\nbinding all event emitters, timers, and lowlevel requests that are\ncreated in that context.\n\n

\n

This is the most basic way to use a domain.\n\n

\n

Example:\n\n

\n
var d = domain.create();\nd.on('error', function(er) {\n  console.error('Caught error!', er);\n});\nd.run(function() {\n  process.nextTick(function() {\n    setTimeout(function() { // simulating some various async stuff\n      fs.open('non-existent file', 'r', function(er, fd) {\n        if (er) throw er;\n        // proceed...\n      });\n    }, 100);\n  });\n});
\n

In this example, the d.on('error') handler will be triggered, rather\nthan crashing the program.\n\n

\n" + }, + { + "textRaw": "domain.add(emitter)", + "type": "method", + "name": "add", + "signatures": [ + { + "params": [ + { + "textRaw": "`emitter` {EventEmitter | Timer} emitter or timer to be added to the domain ", + "name": "emitter", + "type": "EventEmitter | Timer", + "desc": "emitter or timer to be added to the domain" + } + ] + }, + { + "params": [ + { + "name": "emitter" + } + ] + } + ], + "desc": "

Explicitly adds an emitter to the domain. If any event handlers called by\nthe emitter throw an error, or if the emitter emits an error event, it\nwill be routed to the domain's error event, just like with implicit\nbinding.\n\n

\n

This also works with timers that are returned from setInterval and\nsetTimeout. If their callback function throws, it will be caught by\nthe domain 'error' handler.\n\n

\n

If the Timer or EventEmitter was already bound to a domain, it is removed\nfrom that one, and bound to this one instead.\n\n

\n" + }, + { + "textRaw": "domain.remove(emitter)", + "type": "method", + "name": "remove", + "signatures": [ + { + "params": [ + { + "textRaw": "`emitter` {EventEmitter | Timer} emitter or timer to be removed from the domain ", + "name": "emitter", + "type": "EventEmitter | Timer", + "desc": "emitter or timer to be removed from the domain" + } + ] + }, + { + "params": [ + { + "name": "emitter" + } + ] + } + ], + "desc": "

The opposite of domain.add(emitter). Removes domain handling from the\nspecified emitter.\n\n

\n" + }, + { + "textRaw": "domain.bind(callback)", + "type": "method", + "name": "bind", + "signatures": [ + { + "return": { + "textRaw": "return: {Function} The bound function ", + "name": "return", + "type": "Function", + "desc": "The bound function" + }, + "params": [ + { + "textRaw": "`callback` {Function} The callback function ", + "name": "callback", + "type": "Function", + "desc": "The callback function" + } + ] + }, + { + "params": [ + { + "name": "callback" + } + ] + } + ], + "desc": "

The returned function will be a wrapper around the supplied callback\nfunction. When the returned function is called, any errors that are\nthrown will be routed to the domain's error event.\n\n

\n

Example

\n
var d = domain.create();\n\nfunction readSomeFile(filename, cb) {\n  fs.readFile(filename, 'utf8', d.bind(function(er, data) {\n    // if this throws, it will also be passed to the domain\n    return cb(er, data ? JSON.parse(data) : null);\n  }));\n}\n\nd.on('error', function(er) {\n  // an error occurred somewhere.\n  // if we throw it now, it will crash the program\n  // with the normal line number and stack message.\n});
\n" + }, + { + "textRaw": "domain.intercept(callback)", + "type": "method", + "name": "intercept", + "signatures": [ + { + "return": { + "textRaw": "return: {Function} The intercepted function ", + "name": "return", + "type": "Function", + "desc": "The intercepted function" + }, + "params": [ + { + "textRaw": "`callback` {Function} The callback function ", + "name": "callback", + "type": "Function", + "desc": "The callback function" + } + ] + }, + { + "params": [ + { + "name": "callback" + } + ] + } + ], + "desc": "

This method is almost identical to domain.bind(callback). However, in\naddition to catching thrown errors, it will also intercept Error\nobjects sent as the first argument to the function.\n\n

\n

In this way, the common if (er) return callback(er); pattern can be replaced\nwith a single error handler in a single place.\n\n

\n

Example

\n
var d = domain.create();\n\nfunction readSomeFile(filename, cb) {\n  fs.readFile(filename, 'utf8', d.intercept(function(data) {\n    // note, the first argument is never passed to the\n    // callback since it is assumed to be the 'Error' argument\n    // and thus intercepted by the domain.\n\n    // if this throws, it will also be passed to the domain\n    // so the error-handling logic can be moved to the 'error'\n    // event on the domain instead of being repeated throughout\n    // the program.\n    return cb(null, JSON.parse(data));\n  }));\n}\n\nd.on('error', function(er) {\n  // an error occurred somewhere.\n  // if we throw it now, it will crash the program\n  // with the normal line number and stack message.\n});
\n" + }, + { + "textRaw": "domain.dispose()", + "type": "method", + "name": "dispose", + "desc": "

The dispose method destroys a domain, and makes a best effort attempt to\nclean up any and all IO that is associated with the domain. Streams are\naborted, ended, closed, and/or destroyed. Timers are cleared.\nExplicitly bound callbacks are no longer called. Any error events that\nare raised as a result of this are ignored.\n\n

\n

The intention of calling dispose is generally to prevent cascading\nerrors when a critical part of the Domain context is found to be in an\nerror state.\n\n

\n

Once the domain is disposed the dispose event will emit.\n\n

\n

Note that IO might still be performed. However, to the highest degree\npossible, once a domain is disposed, further errors from the emitters in\nthat set will be ignored. So, even if some remaining actions are still\nin flight, Node.js will not communicate further about them.\n\n

\n", + "signatures": [ + { + "params": [] + } + ] + } + ], + "properties": [ + { + "textRaw": "`members` {Array} ", + "name": "members", + "desc": "

An array of timers and event emitters that have been explicitly added\nto the domain.\n\n

\n" + } + ] + } + ], + "type": "module", + "displayName": "Domain" + } + ] +} diff --git a/node-v0.8.14/doc/api/domain.markdown b/node-v0.8.14/doc/api/domain.markdown new file mode 100644 index 0000000..24acd29 --- /dev/null +++ b/node-v0.8.14/doc/api/domain.markdown @@ -0,0 +1,268 @@ +# Domain + + Stability: 1 - Experimental + +Domains provide a way to handle multiple different IO operations as a +single group. If any of the event emitters or callbacks registered to a +domain emit an `error` event, or throw an error, then the domain object +will be notified, rather than losing the context of the error in the +`process.on('uncaughtException')` handler, or causing the program to +exit with an error code. + +This feature is new in Node version 0.8. It is a first pass, and is +expected to change significantly in future versions. Please use it and +provide feedback. + +Due to their experimental nature, the Domains features are disabled unless +the `domain` module is loaded at least once. No domains are created or +registered by default. This is by design, to prevent adverse effects on +current programs. It is expected to be enabled by default in future +Node.js versions. + +## Additions to Error objects + + + +Any time an Error object is routed through a domain, a few extra fields +are added to it. + +* `error.domain` The domain that first handled the error. +* `error.domain_emitter` The event emitter that emitted an 'error' event + with the error object. +* `error.domain_bound` The callback function which was bound to the + domain, and passed an error as its first argument. +* `error.domain_thrown` A boolean indicating whether the error was + thrown, emitted, or passed to a bound callback function. + +## Implicit Binding + + + +If domains are in use, then all new EventEmitter objects (including +Stream objects, requests, responses, etc.) will be implicitly bound to +the active domain at the time of their creation. + +Additionally, callbacks passed to lowlevel event loop requests (such as +to fs.open, or other callback-taking methods) will automatically be +bound to the active domain. If they throw, then the domain will catch +the error. + +In order to prevent excessive memory usage, Domain objects themselves +are not implicitly added as children of the active domain. If they +were, then it would be too easy to prevent request and response objects +from being properly garbage collected. + +If you *want* to nest Domain objects as children of a parent Domain, +then you must explicitly add them, and then dispose of them later. + +Implicit binding routes thrown errors and `'error'` events to the +Domain's `error` event, but does not register the EventEmitter on the +Domain, so `domain.dispose()` will not shut down the EventEmitter. +Implicit binding only takes care of thrown errors and `'error'` events. + +## Explicit Binding + + + +Sometimes, the domain in use is not the one that ought to be used for a +specific event emitter. Or, the event emitter could have been created +in the context of one domain, but ought to instead be bound to some +other domain. + +For example, there could be one domain in use for an HTTP server, but +perhaps we would like to have a separate domain to use for each request. + +That is possible via explicit binding. + +For example: + +``` +// create a top-level domain for the server +var serverDomain = domain.create(); + +serverDomain.run(function() { + // server is created in the scope of serverDomain + http.createServer(function(req, res) { + // req and res are also created in the scope of serverDomain + // however, we'd prefer to have a separate domain for each request. + // create it first thing, and add req and res to it. + var reqd = domain.create(); + reqd.add(req); + reqd.add(res); + reqd.on('error', function(er) { + console.error('Error', er, req.url); + try { + res.writeHead(500); + res.end('Error occurred, sorry.'); + res.on('close', function() { + // forcibly shut down any other things added to this domain + reqd.dispose(); + }); + } catch (er) { + console.error('Error sending 500', er, req.url); + // tried our best. clean up anything remaining. + reqd.dispose(); + } + }); + }).listen(1337); +}); +``` + +## domain.create() + +* return: {Domain} + +Returns a new Domain object. + +## Class: Domain + +The Domain class encapsulates the functionality of routing errors and +uncaught exceptions to the active Domain object. + +Domain is a child class of [EventEmitter][]. To handle the errors that it +catches, listen to its `error` event. + +### domain.run(fn) + +* `fn` {Function} + +Run the supplied function in the context of the domain, implicitly +binding all event emitters, timers, and lowlevel requests that are +created in that context. + +This is the most basic way to use a domain. + +Example: + +``` +var d = domain.create(); +d.on('error', function(er) { + console.error('Caught error!', er); +}); +d.run(function() { + process.nextTick(function() { + setTimeout(function() { // simulating some various async stuff + fs.open('non-existent file', 'r', function(er, fd) { + if (er) throw er; + // proceed... + }); + }, 100); + }); +}); +``` + +In this example, the `d.on('error')` handler will be triggered, rather +than crashing the program. + +### domain.members + +* {Array} + +An array of timers and event emitters that have been explicitly added +to the domain. + +### domain.add(emitter) + +* `emitter` {EventEmitter | Timer} emitter or timer to be added to the domain + +Explicitly adds an emitter to the domain. If any event handlers called by +the emitter throw an error, or if the emitter emits an `error` event, it +will be routed to the domain's `error` event, just like with implicit +binding. + +This also works with timers that are returned from `setInterval` and +`setTimeout`. If their callback function throws, it will be caught by +the domain 'error' handler. + +If the Timer or EventEmitter was already bound to a domain, it is removed +from that one, and bound to this one instead. + +### domain.remove(emitter) + +* `emitter` {EventEmitter | Timer} emitter or timer to be removed from the domain + +The opposite of `domain.add(emitter)`. Removes domain handling from the +specified emitter. + +### domain.bind(callback) + +* `callback` {Function} The callback function +* return: {Function} The bound function + +The returned function will be a wrapper around the supplied callback +function. When the returned function is called, any errors that are +thrown will be routed to the domain's `error` event. + +#### Example + + var d = domain.create(); + + function readSomeFile(filename, cb) { + fs.readFile(filename, 'utf8', d.bind(function(er, data) { + // if this throws, it will also be passed to the domain + return cb(er, data ? JSON.parse(data) : null); + })); + } + + d.on('error', function(er) { + // an error occurred somewhere. + // if we throw it now, it will crash the program + // with the normal line number and stack message. + }); + +### domain.intercept(callback) + +* `callback` {Function} The callback function +* return: {Function} The intercepted function + +This method is almost identical to `domain.bind(callback)`. However, in +addition to catching thrown errors, it will also intercept `Error` +objects sent as the first argument to the function. + +In this way, the common `if (er) return callback(er);` pattern can be replaced +with a single error handler in a single place. + +#### Example + + var d = domain.create(); + + function readSomeFile(filename, cb) { + fs.readFile(filename, 'utf8', d.intercept(function(data) { + // note, the first argument is never passed to the + // callback since it is assumed to be the 'Error' argument + // and thus intercepted by the domain. + + // if this throws, it will also be passed to the domain + // so the error-handling logic can be moved to the 'error' + // event on the domain instead of being repeated throughout + // the program. + return cb(null, JSON.parse(data)); + })); + } + + d.on('error', function(er) { + // an error occurred somewhere. + // if we throw it now, it will crash the program + // with the normal line number and stack message. + }); + +### domain.dispose() + +The dispose method destroys a domain, and makes a best effort attempt to +clean up any and all IO that is associated with the domain. Streams are +aborted, ended, closed, and/or destroyed. Timers are cleared. +Explicitly bound callbacks are no longer called. Any error events that +are raised as a result of this are ignored. + +The intention of calling `dispose` is generally to prevent cascading +errors when a critical part of the Domain context is found to be in an +error state. + +Once the domain is disposed the `dispose` event will emit. + +Note that IO might still be performed. However, to the highest degree +possible, once a domain is disposed, further errors from the emitters in +that set will be ignored. So, even if some remaining actions are still +in flight, Node.js will not communicate further about them. + +[EventEmitter]: events.html#events_class_events_eventemitter diff --git a/node-v0.8.14/doc/api/events.html b/node-v0.8.14/doc/api/events.html new file mode 100644 index 0000000..296f4c6 --- /dev/null +++ b/node-v0.8.14/doc/api/events.html @@ -0,0 +1,217 @@ + + + + + Events Node.js v0.8.14 Manual & Documentation + + + + + +
+ + + +
+
+ + +
+
+

Node.js v0.8.14 Manual & Documentation

+ +
+
+ + + +
+

Events#

+
Stability: 4 - API Frozen
+ + +

Many objects in Node emit events: a net.Server emits an event each time +a peer connects to it, a fs.readStream emits an event when the file is +opened. All objects which emit events are instances of events.EventEmitter. +You can access this module by doing: require("events"); + +

+

Typically, event names are represented by a camel-cased string, however, +there aren't any strict restrictions on that, as any string will be accepted. + +

+

Functions can then be attached to objects, to be executed when an event +is emitted. These functions are called listeners. + + +

+

Class: events.EventEmitter#

+

To access the EventEmitter class, require('events').EventEmitter. + +

+

When an EventEmitter instance experiences an error, the typical action is +to emit an 'error' event. Error events are treated as a special case in node. +If there is no listener for it, then the default action is to print a stack +trace and exit the program. + +

+

All EventEmitters emit the event 'newListener' when new listeners are +added. + +

+

emitter.addListener(event, listener)#

+

emitter.on(event, listener)#

+

Adds a listener to the end of the listeners array for the specified event. + +

+
server.on('connection', function (stream) {
+  console.log('someone connected!');
+});
+

emitter.once(event, listener)#

+

Adds a one time listener for the event. This listener is +invoked only the next time the event is fired, after which +it is removed. + +

+
server.once('connection', function (stream) {
+  console.log('Ah, we have our first user!');
+});
+

emitter.removeListener(event, listener)#

+

Remove a listener from the listener array for the specified event. +Caution: changes array indices in the listener array behind the listener. + +

+
var callback = function(stream) {
+  console.log('someone connected!');
+};
+server.on('connection', callback);
+// ...
+server.removeListener('connection', callback);
+

emitter.removeAllListeners([event])#

+

Removes all listeners, or those of the specified event. + +

+

Note that this will invalidate any arrays that have previously been +returned by emitter.listeners(event). + + +

+

emitter.setMaxListeners(n)#

+

By default EventEmitters will print a warning if more than 10 listeners are +added for a particular event. This is a useful default which helps finding memory leaks. +Obviously not all Emitters should be limited to 10. This function allows +that to be increased. Set to zero for unlimited. + + +

+

emitter.listeners(event)#

+

Returns an array of listeners for the specified event. + +

+
server.on('connection', function (stream) {
+  console.log('someone connected!');
+});
+console.log(util.inspect(server.listeners('connection'))); // [ [Function] ]
+

This array may be a mutable reference to the same underlying list of +listeners that is used by the event subsystem. However, certain +actions (specifically, removeAllListeners) will invalidate this +reference. + +

+

If you would like to get a copy of the listeners at a specific point in +time that is guaranteed not to change, make a copy, for example by doing +emitter.listeners(event).slice(0). + +

+

In a future release of node, this behavior may change to always +return a copy, for consistency. In your programs, please do not rely on +being able to modify the EventEmitter listeners using array methods. +Always use the 'on' method to add new listeners. + +

+

emitter.emit(event, [arg1], [arg2], [...])#

+

Execute each of the listeners in order with the supplied arguments. + +

+

Event: 'newListener'#

+
    +
  • event String The event name
  • +
  • listener Function The event handler function
  • +
+

This event is emitted any time someone adds a new listener. +

+ +
+
+
+ + + + + + + + + diff --git a/node-v0.8.14/doc/api/events.json b/node-v0.8.14/doc/api/events.json new file mode 100644 index 0000000..a25ef35 --- /dev/null +++ b/node-v0.8.14/doc/api/events.json @@ -0,0 +1,187 @@ +{ + "source": "doc/api/events.markdown", + "modules": [ + { + "textRaw": "Events", + "name": "Events", + "stability": 4, + "stabilityText": "API Frozen", + "type": "module", + "desc": "

Many objects in Node emit events: a net.Server emits an event each time\na peer connects to it, a fs.readStream emits an event when the file is\nopened. All objects which emit events are instances of events.EventEmitter.\nYou can access this module by doing: require("events");\n\n

\n

Typically, event names are represented by a camel-cased string, however,\nthere aren't any strict restrictions on that, as any string will be accepted.\n\n

\n

Functions can then be attached to objects, to be executed when an event\nis emitted. These functions are called listeners.\n\n\n

\n", + "classes": [ + { + "textRaw": "Class: events.EventEmitter", + "type": "class", + "name": "events.EventEmitter", + "desc": "

To access the EventEmitter class, require('events').EventEmitter.\n\n

\n

When an EventEmitter instance experiences an error, the typical action is\nto emit an 'error' event. Error events are treated as a special case in node.\nIf there is no listener for it, then the default action is to print a stack\ntrace and exit the program.\n\n

\n

All EventEmitters emit the event 'newListener' when new listeners are\nadded.\n\n

\n", + "methods": [ + { + "textRaw": "emitter.addListener(event, listener)", + "type": "method", + "name": "addListener", + "desc": "

Adds a listener to the end of the listeners array for the specified event.\n\n

\n
server.on('connection', function (stream) {\n  console.log('someone connected!');\n});
\n", + "signatures": [ + { + "params": [ + { + "name": "event" + }, + { + "name": "listener" + } + ] + }, + { + "params": [ + { + "name": "event" + }, + { + "name": "listener" + } + ] + } + ] + }, + { + "textRaw": "emitter.on(event, listener)", + "type": "method", + "name": "on", + "desc": "

Adds a listener to the end of the listeners array for the specified event.\n\n

\n
server.on('connection', function (stream) {\n  console.log('someone connected!');\n});
\n", + "signatures": [ + { + "params": [ + { + "name": "event" + }, + { + "name": "listener" + } + ] + } + ] + }, + { + "textRaw": "emitter.once(event, listener)", + "type": "method", + "name": "once", + "desc": "

Adds a one time listener for the event. This listener is\ninvoked only the next time the event is fired, after which\nit is removed.\n\n

\n
server.once('connection', function (stream) {\n  console.log('Ah, we have our first user!');\n});
\n", + "signatures": [ + { + "params": [ + { + "name": "event" + }, + { + "name": "listener" + } + ] + } + ] + }, + { + "textRaw": "emitter.removeListener(event, listener)", + "type": "method", + "name": "removeListener", + "desc": "

Remove a listener from the listener array for the specified event.\nCaution: changes array indices in the listener array behind the listener.\n\n

\n
var callback = function(stream) {\n  console.log('someone connected!');\n};\nserver.on('connection', callback);\n// ...\nserver.removeListener('connection', callback);
\n", + "signatures": [ + { + "params": [ + { + "name": "event" + }, + { + "name": "listener" + } + ] + } + ] + }, + { + "textRaw": "emitter.removeAllListeners([event])", + "type": "method", + "name": "removeAllListeners", + "desc": "

Removes all listeners, or those of the specified event.\n\n

\n

Note that this will invalidate any arrays that have previously been\nreturned by emitter.listeners(event).\n\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "event", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "emitter.setMaxListeners(n)", + "type": "method", + "name": "setMaxListeners", + "desc": "

By default EventEmitters will print a warning if more than 10 listeners are\nadded for a particular event. This is a useful default which helps finding memory leaks.\nObviously not all Emitters should be limited to 10. This function allows\nthat to be increased. Set to zero for unlimited.\n\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "n" + } + ] + } + ] + }, + { + "textRaw": "emitter.listeners(event)", + "type": "method", + "name": "listeners", + "desc": "

Returns an array of listeners for the specified event.\n\n

\n
server.on('connection', function (stream) {\n  console.log('someone connected!');\n});\nconsole.log(util.inspect(server.listeners('connection'))); // [ [Function] ]
\n

This array may be a mutable reference to the same underlying list of\nlisteners that is used by the event subsystem. However, certain\nactions (specifically, removeAllListeners) will invalidate this\nreference.\n\n

\n

If you would like to get a copy of the listeners at a specific point in\ntime that is guaranteed not to change, make a copy, for example by doing\nemitter.listeners(event).slice(0).\n\n

\n

In a future release of node, this behavior may change to always\nreturn a copy, for consistency. In your programs, please do not rely on\nbeing able to modify the EventEmitter listeners using array methods.\nAlways use the 'on' method to add new listeners.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "event" + } + ] + } + ] + }, + { + "textRaw": "emitter.emit(event, [arg1], [arg2], [...])", + "type": "method", + "name": "emit", + "desc": "

Execute each of the listeners in order with the supplied arguments.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "event" + }, + { + "name": "arg1", + "optional": true + }, + { + "name": "arg2", + "optional": true + }, + { + "name": "...", + "optional": true + } + ] + } + ] + } + ], + "events": [ + { + "textRaw": "Event: 'newListener'", + "type": "event", + "name": "newListener", + "params": [], + "desc": "

This event is emitted any time someone adds a new listener.\n

\n" + } + ] + } + ] + } + ] +} diff --git a/node-v0.8.14/doc/api/events.markdown b/node-v0.8.14/doc/api/events.markdown new file mode 100644 index 0000000..b9be5dc --- /dev/null +++ b/node-v0.8.14/doc/api/events.markdown @@ -0,0 +1,111 @@ +# Events + + Stability: 4 - API Frozen + + + +Many objects in Node emit events: a `net.Server` emits an event each time +a peer connects to it, a `fs.readStream` emits an event when the file is +opened. All objects which emit events are instances of `events.EventEmitter`. +You can access this module by doing: `require("events");` + +Typically, event names are represented by a camel-cased string, however, +there aren't any strict restrictions on that, as any string will be accepted. + +Functions can then be attached to objects, to be executed when an event +is emitted. These functions are called _listeners_. + + +## Class: events.EventEmitter + +To access the EventEmitter class, `require('events').EventEmitter`. + +When an `EventEmitter` instance experiences an error, the typical action is +to emit an `'error'` event. Error events are treated as a special case in node. +If there is no listener for it, then the default action is to print a stack +trace and exit the program. + +All EventEmitters emit the event `'newListener'` when new listeners are +added. + +### emitter.addListener(event, listener) +### emitter.on(event, listener) + +Adds a listener to the end of the listeners array for the specified event. + + server.on('connection', function (stream) { + console.log('someone connected!'); + }); + +### emitter.once(event, listener) + +Adds a **one time** listener for the event. This listener is +invoked only the next time the event is fired, after which +it is removed. + + server.once('connection', function (stream) { + console.log('Ah, we have our first user!'); + }); + +### emitter.removeListener(event, listener) + +Remove a listener from the listener array for the specified event. +**Caution**: changes array indices in the listener array behind the listener. + + var callback = function(stream) { + console.log('someone connected!'); + }; + server.on('connection', callback); + // ... + server.removeListener('connection', callback); + + +### emitter.removeAllListeners([event]) + +Removes all listeners, or those of the specified event. + +Note that this will **invalidate** any arrays that have previously been +returned by `emitter.listeners(event)`. + + +### emitter.setMaxListeners(n) + +By default EventEmitters will print a warning if more than 10 listeners are +added for a particular event. This is a useful default which helps finding memory leaks. +Obviously not all Emitters should be limited to 10. This function allows +that to be increased. Set to zero for unlimited. + + +### emitter.listeners(event) + +Returns an array of listeners for the specified event. + + server.on('connection', function (stream) { + console.log('someone connected!'); + }); + console.log(util.inspect(server.listeners('connection'))); // [ [Function] ] + +This array **may** be a mutable reference to the same underlying list of +listeners that is used by the event subsystem. However, certain +actions (specifically, removeAllListeners) will invalidate this +reference. + +If you would like to get a copy of the listeners at a specific point in +time that is guaranteed not to change, make a copy, for example by doing +`emitter.listeners(event).slice(0)`. + +In a future release of node, this behavior **may** change to always +return a copy, for consistency. In your programs, please do not rely on +being able to modify the EventEmitter listeners using array methods. +Always use the 'on' method to add new listeners. + +### emitter.emit(event, [arg1], [arg2], [...]) + +Execute each of the listeners in order with the supplied arguments. + +### Event: 'newListener' + +* `event` {String} The event name +* `listener` {Function} The event handler function + +This event is emitted any time someone adds a new listener. diff --git a/node-v0.8.14/doc/api/fs.html b/node-v0.8.14/doc/api/fs.html new file mode 100644 index 0000000..fef189f --- /dev/null +++ b/node-v0.8.14/doc/api/fs.html @@ -0,0 +1,880 @@ + + + + + File System Node.js v0.8.14 Manual & Documentation + + + + + +
+ + + +
+
+ + +
+
+

Node.js v0.8.14 Manual & Documentation

+ +
+
+ +
+

Table of Contents

+ + +
+ +
+

File System#

+
Stability: 3 - Stable
+ + +

File I/O is provided by simple wrappers around standard POSIX functions. To +use this module do require('fs'). All the methods have asynchronous and +synchronous forms. + +

+

The asynchronous form always take a completion callback as its last argument. +The arguments passed to the completion callback depend on the method, but the +first argument is always reserved for an exception. If the operation was +completed successfully, then the first argument will be null or undefined. + +

+

When using the synchronous form any exceptions are immediately thrown. +You can use try/catch to handle exceptions or allow them to bubble up. + +

+

Here is an example of the asynchronous version: + +

+
var fs = require('fs');
+
+fs.unlink('/tmp/hello', function (err) {
+  if (err) throw err;
+  console.log('successfully deleted /tmp/hello');
+});
+

Here is the synchronous version: + +

+
var fs = require('fs');
+
+fs.unlinkSync('/tmp/hello')
+console.log('successfully deleted /tmp/hello');
+

With the asynchronous methods there is no guaranteed ordering. So the +following is prone to error: + +

+
fs.rename('/tmp/hello', '/tmp/world', function (err) {
+  if (err) throw err;
+  console.log('renamed complete');
+});
+fs.stat('/tmp/world', function (err, stats) {
+  if (err) throw err;
+  console.log('stats: ' + JSON.stringify(stats));
+});
+

It could be that fs.stat is executed before fs.rename. +The correct way to do this is to chain the callbacks. + +

+
fs.rename('/tmp/hello', '/tmp/world', function (err) {
+  if (err) throw err;
+  fs.stat('/tmp/world', function (err, stats) {
+    if (err) throw err;
+    console.log('stats: ' + JSON.stringify(stats));
+  });
+});
+

In busy processes, the programmer is strongly encouraged to use the +asynchronous versions of these calls. The synchronous versions will block +the entire process until they complete--halting all connections. + +

+

Relative path to filename can be used, remember however that this path will be relative +to process.cwd(). + +

+

fs.rename(oldPath, newPath, [callback])#

+

Asynchronous rename(2). No arguments other than a possible exception are given +to the completion callback. + +

+

fs.renameSync(oldPath, newPath)#

+

Synchronous rename(2). + +

+

fs.truncate(fd, len, [callback])#

+

Asynchronous ftruncate(2). No arguments other than a possible exception are +given to the completion callback. + +

+

fs.truncateSync(fd, len)#

+

Synchronous ftruncate(2). + +

+

fs.chown(path, uid, gid, [callback])#

+

Asynchronous chown(2). No arguments other than a possible exception are given +to the completion callback. + +

+

fs.chownSync(path, uid, gid)#

+

Synchronous chown(2). + +

+

fs.fchown(fd, uid, gid, [callback])#

+

Asynchronous fchown(2). No arguments other than a possible exception are given +to the completion callback. + +

+

fs.fchownSync(fd, uid, gid)#

+

Synchronous fchown(2). + +

+

fs.lchown(path, uid, gid, [callback])#

+

Asynchronous lchown(2). No arguments other than a possible exception are given +to the completion callback. + +

+

fs.lchownSync(path, uid, gid)#

+

Synchronous lchown(2). + +

+

fs.chmod(path, mode, [callback])#

+

Asynchronous chmod(2). No arguments other than a possible exception are given +to the completion callback. + +

+

fs.chmodSync(path, mode)#

+

Synchronous chmod(2). + +

+

fs.fchmod(fd, mode, [callback])#

+

Asynchronous fchmod(2). No arguments other than a possible exception +are given to the completion callback. + +

+

fs.fchmodSync(fd, mode)#

+

Synchronous fchmod(2). + +

+

fs.lchmod(path, mode, [callback])#

+

Asynchronous lchmod(2). No arguments other than a possible exception +are given to the completion callback. + +

+

Only available on Mac OS X. + +

+

fs.lchmodSync(path, mode)#

+

Synchronous lchmod(2). + +

+

fs.stat(path, [callback])#

+

Asynchronous stat(2). The callback gets two arguments (err, stats) where +stats is a fs.Stats object. See the fs.Stats +section below for more information. + +

+

fs.lstat(path, [callback])#

+

Asynchronous lstat(2). The callback gets two arguments (err, stats) where +stats is a fs.Stats object. lstat() is identical to stat(), except that if +path is a symbolic link, then the link itself is stat-ed, not the file that it +refers to. + +

+

fs.fstat(fd, [callback])#

+

Asynchronous fstat(2). The callback gets two arguments (err, stats) where +stats is a fs.Stats object. fstat() is identical to stat(), except that +the file to be stat-ed is specified by the file descriptor fd. + +

+

fs.statSync(path)#

+

Synchronous stat(2). Returns an instance of fs.Stats. + +

+

fs.lstatSync(path)#

+

Synchronous lstat(2). Returns an instance of fs.Stats. + +

+

fs.fstatSync(fd)#

+

Synchronous fstat(2). Returns an instance of fs.Stats. + +

+

fs.link(srcpath, dstpath, [callback])#

+

Asynchronous link(2). No arguments other than a possible exception are given to +the completion callback. + +

+

fs.linkSync(srcpath, dstpath)#

+

Synchronous link(2). + +

+

fs.symlink(srcpath, dstpath, [type], [callback])#

+

Asynchronous symlink(2). No arguments other than a possible exception are given +to the completion callback. +type argument can be either 'dir', 'file', or 'junction' (default is 'file'). It is only +used on Windows (ignored on other platforms). +Note that Windows junction points require the destination path to be absolute. When using +'junction', the destination argument will automatically be normalized to absolute path. + +

+

fs.symlinkSync(srcpath, dstpath, [type])#

+

Synchronous symlink(2). + +

+

fs.readlink(path, [callback])#

+

Asynchronous readlink(2). The callback gets two arguments (err, +linkString). + +

+

fs.readlinkSync(path)#

+

Synchronous readlink(2). Returns the symbolic link's string value. + +

+

fs.realpath(path, [cache], callback)#

+

Asynchronous realpath(2). The callback gets two arguments (err, +resolvedPath). May use process.cwd to resolve relative paths. cache is an +object literal of mapped paths that can be used to force a specific path +resolution or avoid additional fs.stat calls for known real paths. + +

+

Example: + +

+
var cache = {'/etc':'/private/etc'};
+fs.realpath('/etc/passwd', cache, function (err, resolvedPath) {
+  if (err) throw err;
+  console.log(resolvedPath);
+});
+

fs.realpathSync(path, [cache])#

+

Synchronous realpath(2). Returns the resolved path. + +

+

fs.unlink(path, [callback])#

+

Asynchronous unlink(2). No arguments other than a possible exception are given +to the completion callback. + +

+

fs.unlinkSync(path)#

+

Synchronous unlink(2). + +

+

fs.rmdir(path, [callback])#

+

Asynchronous rmdir(2). No arguments other than a possible exception are given +to the completion callback. + +

+

fs.rmdirSync(path)#

+

Synchronous rmdir(2). + +

+

fs.mkdir(path, [mode], [callback])#

+

Asynchronous mkdir(2). No arguments other than a possible exception are given +to the completion callback. mode defaults to 0777. + +

+

fs.mkdirSync(path, [mode])#

+

Synchronous mkdir(2). + +

+

fs.readdir(path, [callback])#

+

Asynchronous readdir(3). Reads the contents of a directory. +The callback gets two arguments (err, files) where files is an array of +the names of the files in the directory excluding '.' and '..'. + +

+

fs.readdirSync(path)#

+

Synchronous readdir(3). Returns an array of filenames excluding '.' and +'..'. + +

+

fs.close(fd, [callback])#

+

Asynchronous close(2). No arguments other than a possible exception are given +to the completion callback. + +

+

fs.closeSync(fd)#

+

Synchronous close(2). + +

+

fs.open(path, flags, [mode], [callback])#

+

Asynchronous file open. See open(2). flags can be: + +

+
    +
  • 'r' - Open file for reading. +An exception occurs if the file does not exist.

    +
  • +
  • 'r+' - Open file for reading and writing. +An exception occurs if the file does not exist.

    +
  • +
  • 'rs' - Open file for reading in synchronous mode. Instructs the operating +system to bypass the local file system cache.

    +

    This is primarily useful for opening files on NFS mounts as it allows you to +skip the potentially stale local cache. It has a very real impact on I/O +performance so don't use this mode unless you need it.

    +

    Note that this doesn't turn fs.open() into a synchronous blocking call. +If that's what you want then you should be using fs.openSync()

    +
  • +
  • 'rs+' - Open file for reading and writing, telling the OS to open it +synchronously. See notes for 'rs' about using this with caution.

    +
  • +
  • 'w' - Open file for writing. +The file is created (if it does not exist) or truncated (if it exists).

    +
  • +
  • 'wx' - Like 'w' but opens the file in exclusive mode.

    +
  • +
  • 'w+' - Open file for reading and writing. +The file is created (if it does not exist) or truncated (if it exists).

    +
  • +
  • 'wx+' - Like 'w+' but opens the file in exclusive mode.

    +
  • +
  • 'a' - Open file for appending. +The file is created if it does not exist.

    +
  • +
  • 'ax' - Like 'a' but opens the file in exclusive mode.

    +
  • +
  • 'a+' - Open file for reading and appending. +The file is created if it does not exist.

    +
  • +
  • 'ax+' - Like 'a+' but opens the file in exclusive mode.

    +
  • +
+

mode defaults to 0666. The callback gets two arguments (err, fd). + +

+

Exclusive mode (O_EXCL) ensures that path is newly created. fs.open() +fails if a file by that name already exists. On POSIX systems, symlinks are +not followed. Exclusive mode may or may not work with network file systems. + +

+

fs.openSync(path, flags, [mode])#

+

Synchronous open(2). + +

+

fs.utimes(path, atime, mtime, [callback])#

+

fs.utimesSync(path, atime, mtime)#

+

Change file timestamps of the file referenced by the supplied path. + +

+

fs.futimes(fd, atime, mtime, [callback])#

+

fs.futimesSync(fd, atime, mtime)#

+

Change the file timestamps of a file referenced by the supplied file +descriptor. + +

+

fs.fsync(fd, [callback])#

+

Asynchronous fsync(2). No arguments other than a possible exception are given +to the completion callback. + +

+

fs.fsyncSync(fd)#

+

Synchronous fsync(2). + +

+

fs.write(fd, buffer, offset, length, position, [callback])#

+

Write buffer to the file specified by fd. + +

+

offset and length determine the part of the buffer to be written. + +

+

position refers to the offset from the beginning of the file where this data +should be written. If position is null, the data will be written at the +current position. +See pwrite(2). + +

+

The callback will be given three arguments (err, written, buffer) where written +specifies how many bytes were written from buffer. + +

+

Note that it is unsafe to use fs.write multiple times on the same file +without waiting for the callback. For this scenario, +fs.createWriteStream is strongly recommended. + +

+

fs.writeSync(fd, buffer, offset, length, position)#

+

Synchronous version of fs.write(). Returns the number of bytes written. + +

+

fs.read(fd, buffer, offset, length, position, [callback])#

+

Read data from the file specified by fd. + +

+

buffer is the buffer that the data will be written to. + +

+

offset is offset within the buffer where reading will start. + +

+

length is an integer specifying the number of bytes to read. + +

+

position is an integer specifying where to begin reading from in the file. +If position is null, data will be read from the current file position. + +

+

The callback is given the three arguments, (err, bytesRead, buffer). + +

+

fs.readSync(fd, buffer, offset, length, position)#

+

Synchronous version of fs.read. Returns the number of bytesRead. + +

+

fs.readFile(filename, [encoding], [callback])#

+

Asynchronously reads the entire contents of a file. Example: + +

+
fs.readFile('/etc/passwd', function (err, data) {
+  if (err) throw err;
+  console.log(data);
+});
+

The callback is passed two arguments (err, data), where data is the +contents of the file. + +

+

If no encoding is specified, then the raw buffer is returned. + + +

+

fs.readFileSync(filename, [encoding])#

+

Synchronous version of fs.readFile. Returns the contents of the filename. + +

+

If encoding is specified then this function returns a string. Otherwise it +returns a buffer. + + +

+

fs.writeFile(filename, data, [encoding], [callback])#

+

Asynchronously writes data to a file, replacing the file if it already exists. +data can be a string or a buffer. The encoding argument is ignored if +data is a buffer. It defaults to 'utf8'. + +

+

Example: + +

+
fs.writeFile('message.txt', 'Hello Node', function (err) {
+  if (err) throw err;
+  console.log('It\'s saved!');
+});
+

fs.writeFileSync(filename, data, [encoding])#

+

The synchronous version of fs.writeFile. + +

+

fs.appendFile(filename, data, encoding='utf8', [callback])#

+

Asynchronously append data to a file, creating the file if it not yet exists. +data can be a string or a buffer. The encoding argument is ignored if +data is a buffer. + +

+

Example: + +

+
fs.appendFile('message.txt', 'data to append', function (err) {
+  if (err) throw err;
+  console.log('The "data to append" was appended to file!');
+});
+

fs.appendFileSync(filename, data, encoding='utf8')#

+

The synchronous version of fs.appendFile. + +

+

fs.watchFile(filename, [options], listener)#

+
Stability: 2 - Unstable.  Use fs.watch instead, if possible.
+

Watch for changes on filename. The callback listener will be called each +time the file is accessed. + +

+

The second argument is optional. The options if provided should be an object +containing two members a boolean, persistent, and interval. persistent +indicates whether the process should continue to run as long as files are +being watched. interval indicates how often the target should be polled, +in milliseconds. The default is { persistent: true, interval: 5007 }. + +

+

The listener gets two arguments the current stat object and the previous +stat object: + +

+
fs.watchFile('message.text', function (curr, prev) {
+  console.log('the current mtime is: ' + curr.mtime);
+  console.log('the previous mtime was: ' + prev.mtime);
+});
+

These stat objects are instances of fs.Stat. + +

+

If you want to be notified when the file was modified, not just accessed +you need to compare curr.mtime and prev.mtime. + +

+

fs.unwatchFile(filename, [listener])#

+
Stability: 2 - Unstable.  Use fs.watch instead, if available.
+

Stop watching for changes on filename. If listener is specified, only that +particular listener is removed. Otherwise, all listeners are removed and you +have effectively stopped watching filename. + +

+

Calling fs.unwatchFile() with a filename that is not being watched is a +no-op, not an error. + +

+

fs.watch(filename, [options], [listener])#

+
Stability: 2 - Unstable.
+

Watch for changes on filename, where filename is either a file or a +directory. The returned object is a fs.FSWatcher. + +

+

The second argument is optional. The options if provided should be an object +containing a boolean member persistent, which indicates whether the process +should continue to run as long as files are being watched. The default is +{ persistent: true }. + +

+

The listener callback gets two arguments (event, filename). event is either +'rename' or 'change', and filename is the name of the file which triggered +the event. + +

+

Caveats#

+ + +

The fs.watch API is not 100% consistent across platforms, and is +unavailable in some situations. + +

+

Availability#

+ + +

This feature depends on the underlying operating system providing a way +to be notified of filesystem changes. + +

+
    +
  • On Linux systems, this uses inotify.
  • +
  • On BSD systems (including OS X), this uses kqueue.
  • +
  • On SunOS systems (including Solaris and SmartOS), this uses event ports.
  • +
  • On Windows systems, this feature depends on ReadDirectoryChangesW.
  • +
+

If the underlying functionality is not available for some reason, then +fs.watch will not be able to function. For example, watching files or +directories on network file systems (NFS, SMB, etc.) often doesn't work +reliably or at all. + +

+

You can still use fs.watchFile, which uses stat polling, but it is slower and +less reliable. + +

+

Filename Argument#

+ + +

Providing filename argument in the callback is not supported +on every platform (currently it's only supported on Linux and Windows). Even +on supported platforms filename is not always guaranteed to be provided. +Therefore, don't assume that filename argument is always provided in the +callback, and have some fallback logic if it is null. + +

+
fs.watch('somedir', function (event, filename) {
+  console.log('event is: ' + event);
+  if (filename) {
+    console.log('filename provided: ' + filename);
+  } else {
+    console.log('filename not provided');
+  }
+});
+

fs.exists(path, [callback])#

+

Test whether or not the given path exists by checking with the file system. +Then call the callback argument with either true or false. Example: + +

+
fs.exists('/etc/passwd', function (exists) {
+  util.debug(exists ? "it's there" : "no passwd!");
+});
+

fs.existsSync(path)#

+

Synchronous version of fs.exists. + +

+

Class: fs.Stats#

+

Objects returned from fs.stat(), fs.lstat() and fs.fstat() and their +synchronous counterparts are of this type. + +

+
    +
  • stats.isFile()
  • +
  • stats.isDirectory()
  • +
  • stats.isBlockDevice()
  • +
  • stats.isCharacterDevice()
  • +
  • stats.isSymbolicLink() (only valid with fs.lstat())
  • +
  • stats.isFIFO()
  • +
  • stats.isSocket()
  • +
+

For a regular file util.inspect(stats) would return a string very +similar to this: + +

+
{ dev: 2114,
+  ino: 48064969,
+  mode: 33188,
+  nlink: 1,
+  uid: 85,
+  gid: 100,
+  rdev: 0,
+  size: 527,
+  blksize: 4096,
+  blocks: 8,
+  atime: Mon, 10 Oct 2011 23:24:11 GMT,
+  mtime: Mon, 10 Oct 2011 23:24:11 GMT,
+  ctime: Mon, 10 Oct 2011 23:24:11 GMT }
+

Please note that atime, mtime and ctime are instances +of Date object and to compare the values of +these objects you should use appropriate methods. For most +general uses getTime() will return +the number of milliseconds elapsed since 1 January 1970 +00:00:00 UTC and this integer should be sufficient for +any comparison, however there additional methods which can +be used for displaying fuzzy information. More details can +be found in the MDN JavaScript Reference page. + +

+

fs.createReadStream(path, [options])#

+

Returns a new ReadStream object (See Readable Stream). + +

+

options is an object with the following defaults: + +

+
{ flags: 'r',
+  encoding: null,
+  fd: null,
+  mode: 0666,
+  bufferSize: 64 * 1024
+}
+

options can include start and end values to read a range of bytes from +the file instead of the entire file. Both start and end are inclusive and +start at 0. The encoding can be 'utf8', 'ascii', or 'base64'. + +

+

An example to read the last 10 bytes of a file which is 100 bytes long: + +

+
fs.createReadStream('sample.txt', {start: 90, end: 99});
+

Class: fs.ReadStream#

+

ReadStream is a Readable Stream. + +

+

Event: 'open'#

+
    +
  • fd Integer file descriptor used by the ReadStream.
  • +
+

Emitted when the ReadStream's file is opened. + + +

+

fs.createWriteStream(path, [options])#

+

Returns a new WriteStream object (See Writable Stream). + +

+

options is an object with the following defaults: + +

+
{ flags: 'w',
+  encoding: null,
+  mode: 0666 }
+

options may also include a start option to allow writing data at +some position past the beginning of the file. Modifying a file rather +than replacing it may require a flags mode of r+ rather than the +default mode w. + +

+

fs.WriteStream#

+

WriteStream is a Writable Stream. + +

+

Event: 'open'#

+
    +
  • fd Integer file descriptor used by the WriteStream.
  • +
+

Emitted when the WriteStream's file is opened. + +

+

file.bytesWritten#

+

The number of bytes written so far. Does not include data that is still queued +for writing. + +

+

Class: fs.FSWatcher#

+

Objects returned from fs.watch() are of this type. + +

+

watcher.close()#

+

Stop watching for changes on the given fs.FSWatcher. + +

+

Event: 'change'#

+
    +
  • event String The type of fs change
  • +
  • filename String The filename that changed (if relevant/available)
  • +
+

Emitted when something changes in a watched directory or file. +See more details in fs.watch. + +

+

Event: 'error'#

+
    +
  • error Error object
  • +
+

Emitted when an error occurs. +

+ +
+
+
+ + + + + + + + + diff --git a/node-v0.8.14/doc/api/fs.json b/node-v0.8.14/doc/api/fs.json new file mode 100644 index 0000000..71e36dc --- /dev/null +++ b/node-v0.8.14/doc/api/fs.json @@ -0,0 +1,1496 @@ +{ + "source": "doc/api/fs.markdown", + "modules": [ + { + "textRaw": "File System", + "name": "fs", + "stability": 3, + "stabilityText": "Stable", + "desc": "

File I/O is provided by simple wrappers around standard POSIX functions. To\nuse this module do require('fs'). All the methods have asynchronous and\nsynchronous forms.\n\n

\n

The asynchronous form always take a completion callback as its last argument.\nThe arguments passed to the completion callback depend on the method, but the\nfirst argument is always reserved for an exception. If the operation was\ncompleted successfully, then the first argument will be null or undefined.\n\n

\n

When using the synchronous form any exceptions are immediately thrown.\nYou can use try/catch to handle exceptions or allow them to bubble up.\n\n

\n

Here is an example of the asynchronous version:\n\n

\n
var fs = require('fs');\n\nfs.unlink('/tmp/hello', function (err) {\n  if (err) throw err;\n  console.log('successfully deleted /tmp/hello');\n});
\n

Here is the synchronous version:\n\n

\n
var fs = require('fs');\n\nfs.unlinkSync('/tmp/hello')\nconsole.log('successfully deleted /tmp/hello');
\n

With the asynchronous methods there is no guaranteed ordering. So the\nfollowing is prone to error:\n\n

\n
fs.rename('/tmp/hello', '/tmp/world', function (err) {\n  if (err) throw err;\n  console.log('renamed complete');\n});\nfs.stat('/tmp/world', function (err, stats) {\n  if (err) throw err;\n  console.log('stats: ' + JSON.stringify(stats));\n});
\n

It could be that fs.stat is executed before fs.rename.\nThe correct way to do this is to chain the callbacks.\n\n

\n
fs.rename('/tmp/hello', '/tmp/world', function (err) {\n  if (err) throw err;\n  fs.stat('/tmp/world', function (err, stats) {\n    if (err) throw err;\n    console.log('stats: ' + JSON.stringify(stats));\n  });\n});
\n

In busy processes, the programmer is strongly encouraged to use the\nasynchronous versions of these calls. The synchronous versions will block\nthe entire process until they complete--halting all connections.\n\n

\n

Relative path to filename can be used, remember however that this path will be relative\nto process.cwd().\n\n

\n", + "methods": [ + { + "textRaw": "fs.rename(oldPath, newPath, [callback])", + "type": "method", + "name": "rename", + "desc": "

Asynchronous rename(2). No arguments other than a possible exception are given\nto the completion callback.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "oldPath" + }, + { + "name": "newPath" + }, + { + "name": "callback", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "fs.renameSync(oldPath, newPath)", + "type": "method", + "name": "renameSync", + "desc": "

Synchronous rename(2).\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "oldPath" + }, + { + "name": "newPath" + } + ] + } + ] + }, + { + "textRaw": "fs.truncate(fd, len, [callback])", + "type": "method", + "name": "truncate", + "desc": "

Asynchronous ftruncate(2). No arguments other than a possible exception are\ngiven to the completion callback.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "fd" + }, + { + "name": "len" + }, + { + "name": "callback", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "fs.truncateSync(fd, len)", + "type": "method", + "name": "truncateSync", + "desc": "

Synchronous ftruncate(2).\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "fd" + }, + { + "name": "len" + } + ] + } + ] + }, + { + "textRaw": "fs.chown(path, uid, gid, [callback])", + "type": "method", + "name": "chown", + "desc": "

Asynchronous chown(2). No arguments other than a possible exception are given\nto the completion callback.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "path" + }, + { + "name": "uid" + }, + { + "name": "gid" + }, + { + "name": "callback", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "fs.chownSync(path, uid, gid)", + "type": "method", + "name": "chownSync", + "desc": "

Synchronous chown(2).\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "path" + }, + { + "name": "uid" + }, + { + "name": "gid" + } + ] + } + ] + }, + { + "textRaw": "fs.fchown(fd, uid, gid, [callback])", + "type": "method", + "name": "fchown", + "desc": "

Asynchronous fchown(2). No arguments other than a possible exception are given\nto the completion callback.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "fd" + }, + { + "name": "uid" + }, + { + "name": "gid" + }, + { + "name": "callback", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "fs.fchownSync(fd, uid, gid)", + "type": "method", + "name": "fchownSync", + "desc": "

Synchronous fchown(2).\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "fd" + }, + { + "name": "uid" + }, + { + "name": "gid" + } + ] + } + ] + }, + { + "textRaw": "fs.lchown(path, uid, gid, [callback])", + "type": "method", + "name": "lchown", + "desc": "

Asynchronous lchown(2). No arguments other than a possible exception are given\nto the completion callback.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "path" + }, + { + "name": "uid" + }, + { + "name": "gid" + }, + { + "name": "callback", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "fs.lchownSync(path, uid, gid)", + "type": "method", + "name": "lchownSync", + "desc": "

Synchronous lchown(2).\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "path" + }, + { + "name": "uid" + }, + { + "name": "gid" + } + ] + } + ] + }, + { + "textRaw": "fs.chmod(path, mode, [callback])", + "type": "method", + "name": "chmod", + "desc": "

Asynchronous chmod(2). No arguments other than a possible exception are given\nto the completion callback.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "path" + }, + { + "name": "mode" + }, + { + "name": "callback", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "fs.chmodSync(path, mode)", + "type": "method", + "name": "chmodSync", + "desc": "

Synchronous chmod(2).\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "path" + }, + { + "name": "mode" + } + ] + } + ] + }, + { + "textRaw": "fs.fchmod(fd, mode, [callback])", + "type": "method", + "name": "fchmod", + "desc": "

Asynchronous fchmod(2). No arguments other than a possible exception\nare given to the completion callback.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "fd" + }, + { + "name": "mode" + }, + { + "name": "callback", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "fs.fchmodSync(fd, mode)", + "type": "method", + "name": "fchmodSync", + "desc": "

Synchronous fchmod(2).\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "fd" + }, + { + "name": "mode" + } + ] + } + ] + }, + { + "textRaw": "fs.lchmod(path, mode, [callback])", + "type": "method", + "name": "lchmod", + "desc": "

Asynchronous lchmod(2). No arguments other than a possible exception\nare given to the completion callback.\n\n

\n

Only available on Mac OS X.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "path" + }, + { + "name": "mode" + }, + { + "name": "callback", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "fs.lchmodSync(path, mode)", + "type": "method", + "name": "lchmodSync", + "desc": "

Synchronous lchmod(2).\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "path" + }, + { + "name": "mode" + } + ] + } + ] + }, + { + "textRaw": "fs.stat(path, [callback])", + "type": "method", + "name": "stat", + "desc": "

Asynchronous stat(2). The callback gets two arguments (err, stats) where\nstats is a fs.Stats object. See the fs.Stats\nsection below for more information.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "path" + }, + { + "name": "callback", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "fs.lstat(path, [callback])", + "type": "method", + "name": "lstat", + "desc": "

Asynchronous lstat(2). The callback gets two arguments (err, stats) where\nstats is a fs.Stats object. lstat() is identical to stat(), except that if\npath is a symbolic link, then the link itself is stat-ed, not the file that it\nrefers to.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "path" + }, + { + "name": "callback", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "fs.fstat(fd, [callback])", + "type": "method", + "name": "fstat", + "desc": "

Asynchronous fstat(2). The callback gets two arguments (err, stats) where\nstats is a fs.Stats object. fstat() is identical to stat(), except that\nthe file to be stat-ed is specified by the file descriptor fd.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "fd" + }, + { + "name": "callback", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "fs.statSync(path)", + "type": "method", + "name": "statSync", + "desc": "

Synchronous stat(2). Returns an instance of fs.Stats.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "path" + } + ] + } + ] + }, + { + "textRaw": "fs.lstatSync(path)", + "type": "method", + "name": "lstatSync", + "desc": "

Synchronous lstat(2). Returns an instance of fs.Stats.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "path" + } + ] + } + ] + }, + { + "textRaw": "fs.fstatSync(fd)", + "type": "method", + "name": "fstatSync", + "desc": "

Synchronous fstat(2). Returns an instance of fs.Stats.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "fd" + } + ] + } + ] + }, + { + "textRaw": "fs.link(srcpath, dstpath, [callback])", + "type": "method", + "name": "link", + "desc": "

Asynchronous link(2). No arguments other than a possible exception are given to\nthe completion callback.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "srcpath" + }, + { + "name": "dstpath" + }, + { + "name": "callback", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "fs.linkSync(srcpath, dstpath)", + "type": "method", + "name": "linkSync", + "desc": "

Synchronous link(2).\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "srcpath" + }, + { + "name": "dstpath" + } + ] + } + ] + }, + { + "textRaw": "fs.symlink(srcpath, dstpath, [type], [callback])", + "type": "method", + "name": "symlink", + "desc": "

Asynchronous symlink(2). No arguments other than a possible exception are given\nto the completion callback.\ntype argument can be either 'dir', 'file', or 'junction' (default is 'file'). It is only \nused on Windows (ignored on other platforms).\nNote that Windows junction points require the destination path to be absolute. When using\n'junction', the destination argument will automatically be normalized to absolute path.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "srcpath" + }, + { + "name": "dstpath" + }, + { + "name": "type", + "optional": true + }, + { + "name": "callback", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "fs.symlinkSync(srcpath, dstpath, [type])", + "type": "method", + "name": "symlinkSync", + "desc": "

Synchronous symlink(2).\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "srcpath" + }, + { + "name": "dstpath" + }, + { + "name": "type", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "fs.readlink(path, [callback])", + "type": "method", + "name": "readlink", + "desc": "

Asynchronous readlink(2). The callback gets two arguments (err,\nlinkString).\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "path" + }, + { + "name": "callback", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "fs.readlinkSync(path)", + "type": "method", + "name": "readlinkSync", + "desc": "

Synchronous readlink(2). Returns the symbolic link's string value.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "path" + } + ] + } + ] + }, + { + "textRaw": "fs.realpath(path, [cache], callback)", + "type": "method", + "name": "realpath", + "desc": "

Asynchronous realpath(2). The callback gets two arguments (err,\nresolvedPath). May use process.cwd to resolve relative paths. cache is an\nobject literal of mapped paths that can be used to force a specific path\nresolution or avoid additional fs.stat calls for known real paths.\n\n

\n

Example:\n\n

\n
var cache = {'/etc':'/private/etc'};\nfs.realpath('/etc/passwd', cache, function (err, resolvedPath) {\n  if (err) throw err;\n  console.log(resolvedPath);\n});
\n", + "signatures": [ + { + "params": [ + { + "name": "path" + }, + { + "name": "cache", + "optional": true + }, + { + "name": "callback" + } + ] + } + ] + }, + { + "textRaw": "fs.realpathSync(path, [cache])", + "type": "method", + "name": "realpathSync", + "desc": "

Synchronous realpath(2). Returns the resolved path.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "path" + }, + { + "name": "cache", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "fs.unlink(path, [callback])", + "type": "method", + "name": "unlink", + "desc": "

Asynchronous unlink(2). No arguments other than a possible exception are given\nto the completion callback.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "path" + }, + { + "name": "callback", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "fs.unlinkSync(path)", + "type": "method", + "name": "unlinkSync", + "desc": "

Synchronous unlink(2).\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "path" + } + ] + } + ] + }, + { + "textRaw": "fs.rmdir(path, [callback])", + "type": "method", + "name": "rmdir", + "desc": "

Asynchronous rmdir(2). No arguments other than a possible exception are given\nto the completion callback.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "path" + }, + { + "name": "callback", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "fs.rmdirSync(path)", + "type": "method", + "name": "rmdirSync", + "desc": "

Synchronous rmdir(2).\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "path" + } + ] + } + ] + }, + { + "textRaw": "fs.mkdir(path, [mode], [callback])", + "type": "method", + "name": "mkdir", + "desc": "

Asynchronous mkdir(2). No arguments other than a possible exception are given\nto the completion callback. mode defaults to 0777.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "path" + }, + { + "name": "mode", + "optional": true + }, + { + "name": "callback", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "fs.mkdirSync(path, [mode])", + "type": "method", + "name": "mkdirSync", + "desc": "

Synchronous mkdir(2).\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "path" + }, + { + "name": "mode", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "fs.readdir(path, [callback])", + "type": "method", + "name": "readdir", + "desc": "

Asynchronous readdir(3). Reads the contents of a directory.\nThe callback gets two arguments (err, files) where files is an array of\nthe names of the files in the directory excluding '.' and '..'.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "path" + }, + { + "name": "callback", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "fs.readdirSync(path)", + "type": "method", + "name": "readdirSync", + "desc": "

Synchronous readdir(3). Returns an array of filenames excluding '.' and\n'..'.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "path" + } + ] + } + ] + }, + { + "textRaw": "fs.close(fd, [callback])", + "type": "method", + "name": "close", + "desc": "

Asynchronous close(2). No arguments other than a possible exception are given\nto the completion callback.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "fd" + }, + { + "name": "callback", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "fs.closeSync(fd)", + "type": "method", + "name": "closeSync", + "desc": "

Synchronous close(2).\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "fd" + } + ] + } + ] + }, + { + "textRaw": "fs.open(path, flags, [mode], [callback])", + "type": "method", + "name": "open", + "desc": "

Asynchronous file open. See open(2). flags can be:\n\n

\n
    \n
  • 'r' - Open file for reading.\nAn exception occurs if the file does not exist.

    \n
  • \n
  • 'r+' - Open file for reading and writing.\nAn exception occurs if the file does not exist.

    \n
  • \n
  • 'rs' - Open file for reading in synchronous mode. Instructs the operating\nsystem to bypass the local file system cache.

    \n

    This is primarily useful for opening files on NFS mounts as it allows you to\nskip the potentially stale local cache. It has a very real impact on I/O\nperformance so don't use this mode unless you need it.

    \n

    Note that this doesn't turn fs.open() into a synchronous blocking call.\nIf that's what you want then you should be using fs.openSync()

    \n
  • \n
  • 'rs+' - Open file for reading and writing, telling the OS to open it\nsynchronously. See notes for 'rs' about using this with caution.

    \n
  • \n
  • 'w' - Open file for writing.\nThe file is created (if it does not exist) or truncated (if it exists).

    \n
  • \n
  • 'wx' - Like 'w' but opens the file in exclusive mode.

    \n
  • \n
  • 'w+' - Open file for reading and writing.\nThe file is created (if it does not exist) or truncated (if it exists).

    \n
  • \n
  • 'wx+' - Like 'w+' but opens the file in exclusive mode.

    \n
  • \n
  • 'a' - Open file for appending.\nThe file is created if it does not exist.

    \n
  • \n
  • 'ax' - Like 'a' but opens the file in exclusive mode.

    \n
  • \n
  • 'a+' - Open file for reading and appending.\nThe file is created if it does not exist.

    \n
  • \n
  • 'ax+' - Like 'a+' but opens the file in exclusive mode.

    \n
  • \n
\n

mode defaults to 0666. The callback gets two arguments (err, fd).\n\n

\n

Exclusive mode (O_EXCL) ensures that path is newly created. fs.open()\nfails if a file by that name already exists. On POSIX systems, symlinks are\nnot followed. Exclusive mode may or may not work with network file systems.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "path" + }, + { + "name": "flags" + }, + { + "name": "mode", + "optional": true + }, + { + "name": "callback", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "fs.openSync(path, flags, [mode])", + "type": "method", + "name": "openSync", + "desc": "

Synchronous open(2).\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "path" + }, + { + "name": "flags" + }, + { + "name": "mode", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "fs.utimes(path, atime, mtime, [callback])", + "type": "method", + "name": "utimes", + "desc": "

Change file timestamps of the file referenced by the supplied path.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "path" + }, + { + "name": "atime" + }, + { + "name": "mtime" + } + ] + }, + { + "params": [ + { + "name": "path" + }, + { + "name": "atime" + }, + { + "name": "mtime" + }, + { + "name": "callback", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "fs.utimesSync(path, atime, mtime)", + "type": "method", + "name": "utimesSync", + "desc": "

Change file timestamps of the file referenced by the supplied path.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "path" + }, + { + "name": "atime" + }, + { + "name": "mtime" + } + ] + } + ] + }, + { + "textRaw": "fs.futimes(fd, atime, mtime, [callback])", + "type": "method", + "name": "futimes", + "desc": "

Change the file timestamps of a file referenced by the supplied file\ndescriptor.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "fd" + }, + { + "name": "atime" + }, + { + "name": "mtime" + } + ] + }, + { + "params": [ + { + "name": "fd" + }, + { + "name": "atime" + }, + { + "name": "mtime" + }, + { + "name": "callback", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "fs.futimesSync(fd, atime, mtime)", + "type": "method", + "name": "futimesSync", + "desc": "

Change the file timestamps of a file referenced by the supplied file\ndescriptor.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "fd" + }, + { + "name": "atime" + }, + { + "name": "mtime" + } + ] + } + ] + }, + { + "textRaw": "fs.fsync(fd, [callback])", + "type": "method", + "name": "fsync", + "desc": "

Asynchronous fsync(2). No arguments other than a possible exception are given\nto the completion callback.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "fd" + }, + { + "name": "callback", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "fs.fsyncSync(fd)", + "type": "method", + "name": "fsyncSync", + "desc": "

Synchronous fsync(2).\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "fd" + } + ] + } + ] + }, + { + "textRaw": "fs.write(fd, buffer, offset, length, position, [callback])", + "type": "method", + "name": "write", + "desc": "

Write buffer to the file specified by fd.\n\n

\n

offset and length determine the part of the buffer to be written.\n\n

\n

position refers to the offset from the beginning of the file where this data\nshould be written. If position is null, the data will be written at the\ncurrent position.\nSee pwrite(2).\n\n

\n

The callback will be given three arguments (err, written, buffer) where written\nspecifies how many bytes were written from buffer.\n\n

\n

Note that it is unsafe to use fs.write multiple times on the same file\nwithout waiting for the callback. For this scenario,\nfs.createWriteStream is strongly recommended.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "fd" + }, + { + "name": "buffer" + }, + { + "name": "offset" + }, + { + "name": "length" + }, + { + "name": "position" + }, + { + "name": "callback", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "fs.writeSync(fd, buffer, offset, length, position)", + "type": "method", + "name": "writeSync", + "desc": "

Synchronous version of fs.write(). Returns the number of bytes written.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "fd" + }, + { + "name": "buffer" + }, + { + "name": "offset" + }, + { + "name": "length" + }, + { + "name": "position" + } + ] + } + ] + }, + { + "textRaw": "fs.read(fd, buffer, offset, length, position, [callback])", + "type": "method", + "name": "read", + "desc": "

Read data from the file specified by fd.\n\n

\n

buffer is the buffer that the data will be written to.\n\n

\n

offset is offset within the buffer where reading will start.\n\n

\n

length is an integer specifying the number of bytes to read.\n\n

\n

position is an integer specifying where to begin reading from in the file.\nIf position is null, data will be read from the current file position.\n\n

\n

The callback is given the three arguments, (err, bytesRead, buffer).\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "fd" + }, + { + "name": "buffer" + }, + { + "name": "offset" + }, + { + "name": "length" + }, + { + "name": "position" + }, + { + "name": "callback", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "fs.readSync(fd, buffer, offset, length, position)", + "type": "method", + "name": "readSync", + "desc": "

Synchronous version of fs.read. Returns the number of bytesRead.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "fd" + }, + { + "name": "buffer" + }, + { + "name": "offset" + }, + { + "name": "length" + }, + { + "name": "position" + } + ] + } + ] + }, + { + "textRaw": "fs.readFile(filename, [encoding], [callback])", + "type": "method", + "name": "readFile", + "desc": "

Asynchronously reads the entire contents of a file. Example:\n\n

\n
fs.readFile('/etc/passwd', function (err, data) {\n  if (err) throw err;\n  console.log(data);\n});
\n

The callback is passed two arguments (err, data), where data is the\ncontents of the file.\n\n

\n

If no encoding is specified, then the raw buffer is returned.\n\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "filename" + }, + { + "name": "encoding", + "optional": true + }, + { + "name": "callback", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "fs.readFileSync(filename, [encoding])", + "type": "method", + "name": "readFileSync", + "desc": "

Synchronous version of fs.readFile. Returns the contents of the filename.\n\n

\n

If encoding is specified then this function returns a string. Otherwise it\nreturns a buffer.\n\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "filename" + }, + { + "name": "encoding", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "fs.writeFile(filename, data, [encoding], [callback])", + "type": "method", + "name": "writeFile", + "desc": "

Asynchronously writes data to a file, replacing the file if it already exists.\ndata can be a string or a buffer. The encoding argument is ignored if\ndata is a buffer. It defaults to 'utf8'.\n\n

\n

Example:\n\n

\n
fs.writeFile('message.txt', 'Hello Node', function (err) {\n  if (err) throw err;\n  console.log('It\\'s saved!');\n});
\n", + "signatures": [ + { + "params": [ + { + "name": "filename" + }, + { + "name": "data" + }, + { + "name": "encoding", + "optional": true + }, + { + "name": "callback", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "fs.writeFileSync(filename, data, [encoding])", + "type": "method", + "name": "writeFileSync", + "desc": "

The synchronous version of fs.writeFile.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "filename" + }, + { + "name": "data" + }, + { + "name": "encoding", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "fs.appendFile(filename, data, encoding='utf8', [callback])", + "type": "method", + "name": "appendFile", + "desc": "

Asynchronously append data to a file, creating the file if it not yet exists.\ndata can be a string or a buffer. The encoding argument is ignored if\ndata is a buffer.\n\n

\n

Example:\n\n

\n
fs.appendFile('message.txt', 'data to append', function (err) {\n  if (err) throw err;\n  console.log('The "data to append" was appended to file!');\n});
\n", + "signatures": [ + { + "params": [ + { + "name": "filename" + }, + { + "name": "data" + }, + { + "name": "encoding", + "default": "'utf8'" + }, + { + "name": "callback", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "fs.appendFileSync(filename, data, encoding='utf8')", + "type": "method", + "name": "appendFileSync", + "desc": "

The synchronous version of fs.appendFile.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "filename" + }, + { + "name": "data" + }, + { + "name": "encoding", + "default": "'utf8'" + } + ] + } + ] + }, + { + "textRaw": "fs.watchFile(filename, [options], listener)", + "type": "method", + "name": "watchFile", + "stability": 2, + "stabilityText": "Unstable. Use fs.watch instead, if possible.", + "desc": "

Watch for changes on filename. The callback listener will be called each\ntime the file is accessed.\n\n

\n

The second argument is optional. The options if provided should be an object\ncontaining two members a boolean, persistent, and interval. persistent\nindicates whether the process should continue to run as long as files are\nbeing watched. interval indicates how often the target should be polled,\nin milliseconds. The default is { persistent: true, interval: 5007 }.\n\n

\n

The listener gets two arguments the current stat object and the previous\nstat object:\n\n

\n
fs.watchFile('message.text', function (curr, prev) {\n  console.log('the current mtime is: ' + curr.mtime);\n  console.log('the previous mtime was: ' + prev.mtime);\n});
\n

These stat objects are instances of fs.Stat.\n\n

\n

If you want to be notified when the file was modified, not just accessed\nyou need to compare curr.mtime and prev.mtime.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "filename" + }, + { + "name": "options", + "optional": true + }, + { + "name": "listener" + } + ] + } + ] + }, + { + "textRaw": "fs.unwatchFile(filename, [listener])", + "type": "method", + "name": "unwatchFile", + "stability": 2, + "stabilityText": "Unstable. Use fs.watch instead, if available.", + "desc": "

Stop watching for changes on filename. If listener is specified, only that\nparticular listener is removed. Otherwise, all listeners are removed and you\nhave effectively stopped watching filename.\n\n

\n

Calling fs.unwatchFile() with a filename that is not being watched is a\nno-op, not an error.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "filename" + }, + { + "name": "listener", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "fs.watch(filename, [options], [listener])", + "type": "method", + "name": "watch", + "stability": 2, + "stabilityText": "Unstable.", + "desc": "

Watch for changes on filename, where filename is either a file or a\ndirectory. The returned object is a fs.FSWatcher.\n\n

\n

The second argument is optional. The options if provided should be an object\ncontaining a boolean member persistent, which indicates whether the process\nshould continue to run as long as files are being watched. The default is\n{ persistent: true }.\n\n

\n

The listener callback gets two arguments (event, filename). event is either\n'rename' or 'change', and filename is the name of the file which triggered\nthe event.\n\n

\n", + "miscs": [ + { + "textRaw": "Caveats", + "name": "Caveats", + "type": "misc", + "desc": "

The fs.watch API is not 100% consistent across platforms, and is\nunavailable in some situations.\n\n

\n", + "miscs": [ + { + "textRaw": "Availability", + "name": "Availability", + "type": "misc", + "desc": "

This feature depends on the underlying operating system providing a way\nto be notified of filesystem changes.\n\n

\n
    \n
  • On Linux systems, this uses inotify.
  • \n
  • On BSD systems (including OS X), this uses kqueue.
  • \n
  • On SunOS systems (including Solaris and SmartOS), this uses event ports.
  • \n
  • On Windows systems, this feature depends on ReadDirectoryChangesW.
  • \n
\n

If the underlying functionality is not available for some reason, then\nfs.watch will not be able to function. For example, watching files or\ndirectories on network file systems (NFS, SMB, etc.) often doesn't work\nreliably or at all.\n\n

\n

You can still use fs.watchFile, which uses stat polling, but it is slower and\nless reliable.\n\n

\n" + }, + { + "textRaw": "Filename Argument", + "name": "Filename Argument", + "type": "misc", + "desc": "

Providing filename argument in the callback is not supported\non every platform (currently it's only supported on Linux and Windows). Even\non supported platforms filename is not always guaranteed to be provided.\nTherefore, don't assume that filename argument is always provided in the\ncallback, and have some fallback logic if it is null.\n\n

\n
fs.watch('somedir', function (event, filename) {\n  console.log('event is: ' + event);\n  if (filename) {\n    console.log('filename provided: ' + filename);\n  } else {\n    console.log('filename not provided');\n  }\n});
\n" + } + ] + } + ], + "signatures": [ + { + "params": [ + { + "name": "filename" + }, + { + "name": "options", + "optional": true + }, + { + "name": "listener", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "fs.exists(path, [callback])", + "type": "method", + "name": "exists", + "desc": "

Test whether or not the given path exists by checking with the file system.\nThen call the callback argument with either true or false. Example:\n\n

\n
fs.exists('/etc/passwd', function (exists) {\n  util.debug(exists ? "it's there" : "no passwd!");\n});
\n", + "signatures": [ + { + "params": [ + { + "name": "path" + }, + { + "name": "callback", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "fs.existsSync(path)", + "type": "method", + "name": "existsSync", + "desc": "

Synchronous version of fs.exists.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "path" + } + ] + } + ] + }, + { + "textRaw": "fs.createReadStream(path, [options])", + "type": "method", + "name": "createReadStream", + "desc": "

Returns a new ReadStream object (See Readable Stream).\n\n

\n

options is an object with the following defaults:\n\n

\n
{ flags: 'r',\n  encoding: null,\n  fd: null,\n  mode: 0666,\n  bufferSize: 64 * 1024\n}
\n

options can include start and end values to read a range of bytes from\nthe file instead of the entire file. Both start and end are inclusive and\nstart at 0. The encoding can be 'utf8', 'ascii', or 'base64'.\n\n

\n

An example to read the last 10 bytes of a file which is 100 bytes long:\n\n

\n
fs.createReadStream('sample.txt', {start: 90, end: 99});
\n", + "signatures": [ + { + "params": [ + { + "name": "path" + }, + { + "name": "options", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "fs.createWriteStream(path, [options])", + "type": "method", + "name": "createWriteStream", + "desc": "

Returns a new WriteStream object (See Writable Stream).\n\n

\n

options is an object with the following defaults:\n\n

\n
{ flags: 'w',\n  encoding: null,\n  mode: 0666 }
\n

options may also include a start option to allow writing data at\nsome position past the beginning of the file. Modifying a file rather\nthan replacing it may require a flags mode of r+ rather than the\ndefault mode w.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "path" + }, + { + "name": "options", + "optional": true + } + ] + } + ] + } + ], + "classes": [ + { + "textRaw": "Class: fs.Stats", + "type": "class", + "name": "fs.Stats", + "desc": "

Objects returned from fs.stat(), fs.lstat() and fs.fstat() and their\nsynchronous counterparts are of this type.\n\n

\n
    \n
  • stats.isFile()
  • \n
  • stats.isDirectory()
  • \n
  • stats.isBlockDevice()
  • \n
  • stats.isCharacterDevice()
  • \n
  • stats.isSymbolicLink() (only valid with fs.lstat())
  • \n
  • stats.isFIFO()
  • \n
  • stats.isSocket()
  • \n
\n

For a regular file util.inspect(stats) would return a string very\nsimilar to this:\n\n

\n
{ dev: 2114,\n  ino: 48064969,\n  mode: 33188,\n  nlink: 1,\n  uid: 85,\n  gid: 100,\n  rdev: 0,\n  size: 527,\n  blksize: 4096,\n  blocks: 8,\n  atime: Mon, 10 Oct 2011 23:24:11 GMT,\n  mtime: Mon, 10 Oct 2011 23:24:11 GMT,\n  ctime: Mon, 10 Oct 2011 23:24:11 GMT }
\n

Please note that atime, mtime and ctime are instances\nof [Date][MDN-Date] object and to compare the values of\nthese objects you should use appropriate methods. For most\ngeneral uses [getTime()][MDN-Date-getTime] will return\nthe number of milliseconds elapsed since 1 January 1970\n00:00:00 UTC and this integer should be sufficient for\nany comparison, however there additional methods which can\nbe used for displaying fuzzy information. More details can\nbe found in the [MDN JavaScript Reference][MDN-Date] page.\n\n

\n" + }, + { + "textRaw": "Class: fs.ReadStream", + "type": "class", + "name": "fs.ReadStream", + "desc": "

ReadStream is a Readable Stream.\n\n

\n", + "events": [ + { + "textRaw": "Event: 'open'", + "type": "event", + "name": "open", + "params": [], + "desc": "

Emitted when the ReadStream's file is opened.\n\n\n

\n" + } + ] + }, + { + "textRaw": "Class: fs.FSWatcher", + "type": "class", + "name": "fs.FSWatcher", + "desc": "

Objects returned from fs.watch() are of this type.\n\n

\n", + "methods": [ + { + "textRaw": "watcher.close()", + "type": "method", + "name": "close", + "desc": "

Stop watching for changes on the given fs.FSWatcher.\n\n

\n", + "signatures": [ + { + "params": [] + } + ] + } + ], + "events": [ + { + "textRaw": "Event: 'change'", + "type": "event", + "name": "change", + "params": [], + "desc": "

Emitted when something changes in a watched directory or file.\nSee more details in fs.watch.\n\n

\n" + }, + { + "textRaw": "Event: 'error'", + "type": "event", + "name": "error", + "params": [], + "desc": "

Emitted when an error occurs.\n

\n" + } + ] + } + ], + "properties": [ + { + "textRaw": "fs.WriteStream", + "name": "WriteStream", + "desc": "

WriteStream is a Writable Stream.\n\n

\n", + "events": [ + { + "textRaw": "Event: 'open'", + "type": "event", + "name": "open", + "params": [], + "desc": "

Emitted when the WriteStream's file is opened.\n\n

\n" + } + ], + "properties": [ + { + "textRaw": "file.bytesWritten", + "name": "bytesWritten", + "desc": "

The number of bytes written so far. Does not include data that is still queued\nfor writing.\n\n

\n" + } + ] + } + ], + "type": "module", + "displayName": "fs" + } + ] +} diff --git a/node-v0.8.14/doc/api/fs.markdown b/node-v0.8.14/doc/api/fs.markdown new file mode 100644 index 0000000..a6b31e6 --- /dev/null +++ b/node-v0.8.14/doc/api/fs.markdown @@ -0,0 +1,678 @@ +# File System + + Stability: 3 - Stable + + + +File I/O is provided by simple wrappers around standard POSIX functions. To +use this module do `require('fs')`. All the methods have asynchronous and +synchronous forms. + +The asynchronous form always take a completion callback as its last argument. +The arguments passed to the completion callback depend on the method, but the +first argument is always reserved for an exception. If the operation was +completed successfully, then the first argument will be `null` or `undefined`. + +When using the synchronous form any exceptions are immediately thrown. +You can use try/catch to handle exceptions or allow them to bubble up. + +Here is an example of the asynchronous version: + + var fs = require('fs'); + + fs.unlink('/tmp/hello', function (err) { + if (err) throw err; + console.log('successfully deleted /tmp/hello'); + }); + +Here is the synchronous version: + + var fs = require('fs'); + + fs.unlinkSync('/tmp/hello') + console.log('successfully deleted /tmp/hello'); + +With the asynchronous methods there is no guaranteed ordering. So the +following is prone to error: + + fs.rename('/tmp/hello', '/tmp/world', function (err) { + if (err) throw err; + console.log('renamed complete'); + }); + fs.stat('/tmp/world', function (err, stats) { + if (err) throw err; + console.log('stats: ' + JSON.stringify(stats)); + }); + +It could be that `fs.stat` is executed before `fs.rename`. +The correct way to do this is to chain the callbacks. + + fs.rename('/tmp/hello', '/tmp/world', function (err) { + if (err) throw err; + fs.stat('/tmp/world', function (err, stats) { + if (err) throw err; + console.log('stats: ' + JSON.stringify(stats)); + }); + }); + +In busy processes, the programmer is _strongly encouraged_ to use the +asynchronous versions of these calls. The synchronous versions will block +the entire process until they complete--halting all connections. + +Relative path to filename can be used, remember however that this path will be relative +to `process.cwd()`. + +## fs.rename(oldPath, newPath, [callback]) + +Asynchronous rename(2). No arguments other than a possible exception are given +to the completion callback. + +## fs.renameSync(oldPath, newPath) + +Synchronous rename(2). + +## fs.truncate(fd, len, [callback]) + +Asynchronous ftruncate(2). No arguments other than a possible exception are +given to the completion callback. + +## fs.truncateSync(fd, len) + +Synchronous ftruncate(2). + +## fs.chown(path, uid, gid, [callback]) + +Asynchronous chown(2). No arguments other than a possible exception are given +to the completion callback. + +## fs.chownSync(path, uid, gid) + +Synchronous chown(2). + +## fs.fchown(fd, uid, gid, [callback]) + +Asynchronous fchown(2). No arguments other than a possible exception are given +to the completion callback. + +## fs.fchownSync(fd, uid, gid) + +Synchronous fchown(2). + +## fs.lchown(path, uid, gid, [callback]) + +Asynchronous lchown(2). No arguments other than a possible exception are given +to the completion callback. + +## fs.lchownSync(path, uid, gid) + +Synchronous lchown(2). + +## fs.chmod(path, mode, [callback]) + +Asynchronous chmod(2). No arguments other than a possible exception are given +to the completion callback. + +## fs.chmodSync(path, mode) + +Synchronous chmod(2). + +## fs.fchmod(fd, mode, [callback]) + +Asynchronous fchmod(2). No arguments other than a possible exception +are given to the completion callback. + +## fs.fchmodSync(fd, mode) + +Synchronous fchmod(2). + +## fs.lchmod(path, mode, [callback]) + +Asynchronous lchmod(2). No arguments other than a possible exception +are given to the completion callback. + +Only available on Mac OS X. + +## fs.lchmodSync(path, mode) + +Synchronous lchmod(2). + +## fs.stat(path, [callback]) + +Asynchronous stat(2). The callback gets two arguments `(err, stats)` where +`stats` is a [fs.Stats](#fs_class_fs_stats) object. See the [fs.Stats](#fs_class_fs_stats) +section below for more information. + +## fs.lstat(path, [callback]) + +Asynchronous lstat(2). The callback gets two arguments `(err, stats)` where +`stats` is a `fs.Stats` object. `lstat()` is identical to `stat()`, except that if +`path` is a symbolic link, then the link itself is stat-ed, not the file that it +refers to. + +## fs.fstat(fd, [callback]) + +Asynchronous fstat(2). The callback gets two arguments `(err, stats)` where +`stats` is a `fs.Stats` object. `fstat()` is identical to `stat()`, except that +the file to be stat-ed is specified by the file descriptor `fd`. + +## fs.statSync(path) + +Synchronous stat(2). Returns an instance of `fs.Stats`. + +## fs.lstatSync(path) + +Synchronous lstat(2). Returns an instance of `fs.Stats`. + +## fs.fstatSync(fd) + +Synchronous fstat(2). Returns an instance of `fs.Stats`. + +## fs.link(srcpath, dstpath, [callback]) + +Asynchronous link(2). No arguments other than a possible exception are given to +the completion callback. + +## fs.linkSync(srcpath, dstpath) + +Synchronous link(2). + +## fs.symlink(srcpath, dstpath, [type], [callback]) + +Asynchronous symlink(2). No arguments other than a possible exception are given +to the completion callback. +`type` argument can be either `'dir'`, `'file'`, or `'junction'` (default is `'file'`). It is only +used on Windows (ignored on other platforms). +Note that Windows junction points require the destination path to be absolute. When using +`'junction'`, the `destination` argument will automatically be normalized to absolute path. + +## fs.symlinkSync(srcpath, dstpath, [type]) + +Synchronous symlink(2). + +## fs.readlink(path, [callback]) + +Asynchronous readlink(2). The callback gets two arguments `(err, +linkString)`. + +## fs.readlinkSync(path) + +Synchronous readlink(2). Returns the symbolic link's string value. + +## fs.realpath(path, [cache], callback) + +Asynchronous realpath(2). The `callback` gets two arguments `(err, +resolvedPath)`. May use `process.cwd` to resolve relative paths. `cache` is an +object literal of mapped paths that can be used to force a specific path +resolution or avoid additional `fs.stat` calls for known real paths. + +Example: + + var cache = {'/etc':'/private/etc'}; + fs.realpath('/etc/passwd', cache, function (err, resolvedPath) { + if (err) throw err; + console.log(resolvedPath); + }); + +## fs.realpathSync(path, [cache]) + +Synchronous realpath(2). Returns the resolved path. + +## fs.unlink(path, [callback]) + +Asynchronous unlink(2). No arguments other than a possible exception are given +to the completion callback. + +## fs.unlinkSync(path) + +Synchronous unlink(2). + +## fs.rmdir(path, [callback]) + +Asynchronous rmdir(2). No arguments other than a possible exception are given +to the completion callback. + +## fs.rmdirSync(path) + +Synchronous rmdir(2). + +## fs.mkdir(path, [mode], [callback]) + +Asynchronous mkdir(2). No arguments other than a possible exception are given +to the completion callback. `mode` defaults to `0777`. + +## fs.mkdirSync(path, [mode]) + +Synchronous mkdir(2). + +## fs.readdir(path, [callback]) + +Asynchronous readdir(3). Reads the contents of a directory. +The callback gets two arguments `(err, files)` where `files` is an array of +the names of the files in the directory excluding `'.'` and `'..'`. + +## fs.readdirSync(path) + +Synchronous readdir(3). Returns an array of filenames excluding `'.'` and +`'..'`. + +## fs.close(fd, [callback]) + +Asynchronous close(2). No arguments other than a possible exception are given +to the completion callback. + +## fs.closeSync(fd) + +Synchronous close(2). + +## fs.open(path, flags, [mode], [callback]) + +Asynchronous file open. See open(2). `flags` can be: + +* `'r'` - Open file for reading. +An exception occurs if the file does not exist. + +* `'r+'` - Open file for reading and writing. +An exception occurs if the file does not exist. + +* `'rs'` - Open file for reading in synchronous mode. Instructs the operating + system to bypass the local file system cache. + + This is primarily useful for opening files on NFS mounts as it allows you to + skip the potentially stale local cache. It has a very real impact on I/O + performance so don't use this mode unless you need it. + + Note that this doesn't turn `fs.open()` into a synchronous blocking call. + If that's what you want then you should be using `fs.openSync()` + +* `'rs+'` - Open file for reading and writing, telling the OS to open it + synchronously. See notes for `'rs'` about using this with caution. + +* `'w'` - Open file for writing. +The file is created (if it does not exist) or truncated (if it exists). + +* `'wx'` - Like `'w'` but opens the file in exclusive mode. + +* `'w+'` - Open file for reading and writing. +The file is created (if it does not exist) or truncated (if it exists). + +* `'wx+'` - Like `'w+'` but opens the file in exclusive mode. + +* `'a'` - Open file for appending. +The file is created if it does not exist. + +* `'ax'` - Like `'a'` but opens the file in exclusive mode. + +* `'a+'` - Open file for reading and appending. +The file is created if it does not exist. + +* `'ax+'` - Like `'a+'` but opens the file in exclusive mode. + +`mode` defaults to `0666`. The callback gets two arguments `(err, fd)`. + +Exclusive mode (`O_EXCL`) ensures that `path` is newly created. `fs.open()` +fails if a file by that name already exists. On POSIX systems, symlinks are +not followed. Exclusive mode may or may not work with network file systems. + +## fs.openSync(path, flags, [mode]) + +Synchronous open(2). + +## fs.utimes(path, atime, mtime, [callback]) +## fs.utimesSync(path, atime, mtime) + +Change file timestamps of the file referenced by the supplied path. + +## fs.futimes(fd, atime, mtime, [callback]) +## fs.futimesSync(fd, atime, mtime) + +Change the file timestamps of a file referenced by the supplied file +descriptor. + +## fs.fsync(fd, [callback]) + +Asynchronous fsync(2). No arguments other than a possible exception are given +to the completion callback. + +## fs.fsyncSync(fd) + +Synchronous fsync(2). + +## fs.write(fd, buffer, offset, length, position, [callback]) + +Write `buffer` to the file specified by `fd`. + +`offset` and `length` determine the part of the buffer to be written. + +`position` refers to the offset from the beginning of the file where this data +should be written. If `position` is `null`, the data will be written at the +current position. +See pwrite(2). + +The callback will be given three arguments `(err, written, buffer)` where `written` +specifies how many _bytes_ were written from `buffer`. + +Note that it is unsafe to use `fs.write` multiple times on the same file +without waiting for the callback. For this scenario, +`fs.createWriteStream` is strongly recommended. + +## fs.writeSync(fd, buffer, offset, length, position) + +Synchronous version of `fs.write()`. Returns the number of bytes written. + +## fs.read(fd, buffer, offset, length, position, [callback]) + +Read data from the file specified by `fd`. + +`buffer` is the buffer that the data will be written to. + +`offset` is offset within the buffer where reading will start. + +`length` is an integer specifying the number of bytes to read. + +`position` is an integer specifying where to begin reading from in the file. +If `position` is `null`, data will be read from the current file position. + +The callback is given the three arguments, `(err, bytesRead, buffer)`. + +## fs.readSync(fd, buffer, offset, length, position) + +Synchronous version of `fs.read`. Returns the number of `bytesRead`. + +## fs.readFile(filename, [encoding], [callback]) + +Asynchronously reads the entire contents of a file. Example: + + fs.readFile('/etc/passwd', function (err, data) { + if (err) throw err; + console.log(data); + }); + +The callback is passed two arguments `(err, data)`, where `data` is the +contents of the file. + +If no encoding is specified, then the raw buffer is returned. + + +## fs.readFileSync(filename, [encoding]) + +Synchronous version of `fs.readFile`. Returns the contents of the `filename`. + +If `encoding` is specified then this function returns a string. Otherwise it +returns a buffer. + + +## fs.writeFile(filename, data, [encoding], [callback]) + +Asynchronously writes data to a file, replacing the file if it already exists. +`data` can be a string or a buffer. The `encoding` argument is ignored if +`data` is a buffer. It defaults to `'utf8'`. + +Example: + + fs.writeFile('message.txt', 'Hello Node', function (err) { + if (err) throw err; + console.log('It\'s saved!'); + }); + +## fs.writeFileSync(filename, data, [encoding]) + +The synchronous version of `fs.writeFile`. + +## fs.appendFile(filename, data, encoding='utf8', [callback]) + +Asynchronously append data to a file, creating the file if it not yet exists. +`data` can be a string or a buffer. The `encoding` argument is ignored if +`data` is a buffer. + +Example: + + fs.appendFile('message.txt', 'data to append', function (err) { + if (err) throw err; + console.log('The "data to append" was appended to file!'); + }); + +## fs.appendFileSync(filename, data, encoding='utf8') + +The synchronous version of `fs.appendFile`. + +## fs.watchFile(filename, [options], listener) + + Stability: 2 - Unstable. Use fs.watch instead, if possible. + +Watch for changes on `filename`. The callback `listener` will be called each +time the file is accessed. + +The second argument is optional. The `options` if provided should be an object +containing two members a boolean, `persistent`, and `interval`. `persistent` +indicates whether the process should continue to run as long as files are +being watched. `interval` indicates how often the target should be polled, +in milliseconds. The default is `{ persistent: true, interval: 5007 }`. + +The `listener` gets two arguments the current stat object and the previous +stat object: + + fs.watchFile('message.text', function (curr, prev) { + console.log('the current mtime is: ' + curr.mtime); + console.log('the previous mtime was: ' + prev.mtime); + }); + +These stat objects are instances of `fs.Stat`. + +If you want to be notified when the file was modified, not just accessed +you need to compare `curr.mtime` and `prev.mtime`. + +## fs.unwatchFile(filename, [listener]) + + Stability: 2 - Unstable. Use fs.watch instead, if available. + +Stop watching for changes on `filename`. If `listener` is specified, only that +particular listener is removed. Otherwise, *all* listeners are removed and you +have effectively stopped watching `filename`. + +Calling `fs.unwatchFile()` with a filename that is not being watched is a +no-op, not an error. + +## fs.watch(filename, [options], [listener]) + + Stability: 2 - Unstable. + +Watch for changes on `filename`, where `filename` is either a file or a +directory. The returned object is a [fs.FSWatcher](#fs_class_fs_fswatcher). + +The second argument is optional. The `options` if provided should be an object +containing a boolean member `persistent`, which indicates whether the process +should continue to run as long as files are being watched. The default is +`{ persistent: true }`. + +The listener callback gets two arguments `(event, filename)`. `event` is either +'rename' or 'change', and `filename` is the name of the file which triggered +the event. + +### Caveats + + + +The `fs.watch` API is not 100% consistent across platforms, and is +unavailable in some situations. + +#### Availability + + + +This feature depends on the underlying operating system providing a way +to be notified of filesystem changes. + +* On Linux systems, this uses `inotify`. +* On BSD systems (including OS X), this uses `kqueue`. +* On SunOS systems (including Solaris and SmartOS), this uses `event ports`. +* On Windows systems, this feature depends on `ReadDirectoryChangesW`. + +If the underlying functionality is not available for some reason, then +`fs.watch` will not be able to function. For example, watching files or +directories on network file systems (NFS, SMB, etc.) often doesn't work +reliably or at all. + +You can still use `fs.watchFile`, which uses stat polling, but it is slower and +less reliable. + +#### Filename Argument + + + +Providing `filename` argument in the callback is not supported +on every platform (currently it's only supported on Linux and Windows). Even +on supported platforms `filename` is not always guaranteed to be provided. +Therefore, don't assume that `filename` argument is always provided in the +callback, and have some fallback logic if it is null. + + fs.watch('somedir', function (event, filename) { + console.log('event is: ' + event); + if (filename) { + console.log('filename provided: ' + filename); + } else { + console.log('filename not provided'); + } + }); + +## fs.exists(path, [callback]) + +Test whether or not the given path exists by checking with the file system. +Then call the `callback` argument with either true or false. Example: + + fs.exists('/etc/passwd', function (exists) { + util.debug(exists ? "it's there" : "no passwd!"); + }); + + +## fs.existsSync(path) + +Synchronous version of `fs.exists`. + +## Class: fs.Stats + +Objects returned from `fs.stat()`, `fs.lstat()` and `fs.fstat()` and their +synchronous counterparts are of this type. + + - `stats.isFile()` + - `stats.isDirectory()` + - `stats.isBlockDevice()` + - `stats.isCharacterDevice()` + - `stats.isSymbolicLink()` (only valid with `fs.lstat()`) + - `stats.isFIFO()` + - `stats.isSocket()` + +For a regular file `util.inspect(stats)` would return a string very +similar to this: + + { dev: 2114, + ino: 48064969, + mode: 33188, + nlink: 1, + uid: 85, + gid: 100, + rdev: 0, + size: 527, + blksize: 4096, + blocks: 8, + atime: Mon, 10 Oct 2011 23:24:11 GMT, + mtime: Mon, 10 Oct 2011 23:24:11 GMT, + ctime: Mon, 10 Oct 2011 23:24:11 GMT } + +Please note that `atime`, `mtime` and `ctime` are instances +of [Date][MDN-Date] object and to compare the values of +these objects you should use appropriate methods. For most +general uses [getTime()][MDN-Date-getTime] will return +the number of milliseconds elapsed since _1 January 1970 +00:00:00 UTC_ and this integer should be sufficient for +any comparison, however there additional methods which can +be used for displaying fuzzy information. More details can +be found in the [MDN JavaScript Reference][MDN-Date] page. + +[MDN-Date]: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date +[MDN-Date-getTime]: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date/getTime + + +## fs.createReadStream(path, [options]) + +Returns a new ReadStream object (See `Readable Stream`). + +`options` is an object with the following defaults: + + { flags: 'r', + encoding: null, + fd: null, + mode: 0666, + bufferSize: 64 * 1024 + } + +`options` can include `start` and `end` values to read a range of bytes from +the file instead of the entire file. Both `start` and `end` are inclusive and +start at 0. The `encoding` can be `'utf8'`, `'ascii'`, or `'base64'`. + +An example to read the last 10 bytes of a file which is 100 bytes long: + + fs.createReadStream('sample.txt', {start: 90, end: 99}); + + +## Class: fs.ReadStream + +`ReadStream` is a [Readable Stream](stream.html#stream_readable_stream). + +### Event: 'open' + +* `fd` {Integer} file descriptor used by the ReadStream. + +Emitted when the ReadStream's file is opened. + + +## fs.createWriteStream(path, [options]) + +Returns a new WriteStream object (See `Writable Stream`). + +`options` is an object with the following defaults: + + { flags: 'w', + encoding: null, + mode: 0666 } + +`options` may also include a `start` option to allow writing data at +some position past the beginning of the file. Modifying a file rather +than replacing it may require a `flags` mode of `r+` rather than the +default mode `w`. + +## fs.WriteStream + +`WriteStream` is a [Writable Stream](stream.html#stream_writable_stream). + +### Event: 'open' + +* `fd` {Integer} file descriptor used by the WriteStream. + +Emitted when the WriteStream's file is opened. + +### file.bytesWritten + +The number of bytes written so far. Does not include data that is still queued +for writing. + +## Class: fs.FSWatcher + +Objects returned from `fs.watch()` are of this type. + +### watcher.close() + +Stop watching for changes on the given `fs.FSWatcher`. + +### Event: 'change' + +* `event` {String} The type of fs change +* `filename` {String} The filename that changed (if relevant/available) + +Emitted when something changes in a watched directory or file. +See more details in [fs.watch](#fs_fs_watch_filename_options_listener). + +### Event: 'error' + +* `error` {Error object} + +Emitted when an error occurs. diff --git a/node-v0.8.14/doc/api/globals.html b/node-v0.8.14/doc/api/globals.html new file mode 100644 index 0000000..d1e9fcf --- /dev/null +++ b/node-v0.8.14/doc/api/globals.html @@ -0,0 +1,306 @@ + + + + + Global Objects Node.js v0.8.14 Manual & Documentation + + + + + +
+ + + +
+
+ + +
+
+

Node.js v0.8.14 Manual & Documentation

+ +
+
+ + + +
+

Global Objects#

+ + +

These objects are available in all modules. Some of these objects aren't +actually in the global scope but in the module scope - this will be noted. + +

+

global#

+ + +
    +
  • {Object} The global namespace object.
  • +
+

In browsers, the top-level scope is the global scope. That means that in +browsers if you're in the global scope var something will define a global +variable. In Node this is different. The top-level scope is not the global +scope; var something inside a Node module will be local to that module. + +

+

process#

+ + +
    +
  • {Object}
  • +
+

The process object. See the process object section. + +

+

console#

+ + +
    +
  • {Object}
  • +
+

Used to print to stdout and stderr. See the stdio section. + +

+

Class: Buffer#

+ + +
    +
  • {Function}
  • +
+

Used to handle binary data. See the buffer section + +

+

require()#

+ + +
    +
  • {Function}
  • +
+

To require modules. See the Modules section. require isn't actually a +global but rather local to each module. + +

+

require.resolve()#

+

Use the internal require() machinery to look up the location of a module, +but rather than loading the module, just return the resolved filename. + +

+

require.cache#

+
    +
  • Object
  • +
+

Modules are cached in this object when they are required. By deleting a key +value from this object, the next require will reload the module. + +

+

require.extensions#

+
    +
  • Array
  • +
+

Instruct require on how to handle certain file extensions. + +

+

Process files with the extension .sjs as .js: + +

+
require.extensions['.sjs'] = require.extensions['.js'];
+

Write your own extension handler: + +

+
require.extensions['.sjs'] = function(module, filename) {
+  var content = fs.readFileSync(filename, 'utf8');
+  // Parse the file content and give to module.exports
+  module.exports = content;
+};
+

__filename#

+ + +
    +
  • {String}
  • +
+

The filename of the code being executed. This is the resolved absolute path +of this code file. For a main program this is not necessarily the same +filename used in the command line. The value inside a module is the path +to that module file. + +

+

Example: running node example.js from /Users/mjr + +

+
console.log(__filename);
+// /Users/mjr/example.js
+

__filename isn't actually a global but rather local to each module. + +

+

__dirname#

+ + +
    +
  • {String}
  • +
+

The name of the directory that the currently executing script resides in. + +

+

Example: running node example.js from /Users/mjr + +

+
console.log(__dirname);
+// /Users/mjr
+

__dirname isn't actually a global but rather local to each module. + + +

+

module#

+ + +
    +
  • {Object}
  • +
+

A reference to the current module. In particular +module.exports is the same as the exports object. +module isn't actually a global but rather local to each module. + +

+

See the module system documentation for more information. + +

+

exports#

+ + +

An object which is shared between all instances of the current module and +made accessible through require(). +exports is the same as the module.exports object. +exports isn't actually a global but rather local to each module. + +

+

See the module system documentation for more information. + +

+

See the module section for more information. + +

+

setTimeout(cb, ms)#

+

Run callback cb after at least ms milliseconds. The actual delay depends +on external factors like OS timer granularity and system load. + +

+

The timeout must be in the range of 1-2,147,483,647 inclusive. If the value is +outside that range, it's changed to 1 millisecond. Broadly speaking, a timer +cannot span more than 24.8 days. + +

+

Returns an opaque value that represents the timer. + +

+

clearTimeout(t)#

+

Stop a timer that was previously created with setTimeout(). The callback will +not execute. + +

+

setInterval(cb, ms)#

+

Run callback cb repeatedly every ms milliseconds. Note that the actual +interval may vary, depending on external factors like OS timer granularity and +system load. It's never less than ms but it may be longer. + +

+

The interval must be in the range of 1-2,147,483,647 inclusive. If the value is +outside that range, it's changed to 1 millisecond. Broadly speaking, a timer +cannot span more than 24.8 days. + +

+

Returns an opaque value that represents the timer. + +

+

clearInterval(t)#

+

Stop a timer that was previously created with setInterval(). The callback +will not execute. + +

+ + +

The timer functions are global variables. See the timers section. + +

+ +
+
+
+ + + + + + + + + diff --git a/node-v0.8.14/doc/api/globals.json b/node-v0.8.14/doc/api/globals.json new file mode 100644 index 0000000..56fd7a0 --- /dev/null +++ b/node-v0.8.14/doc/api/globals.json @@ -0,0 +1,295 @@ +{ + "source": "doc/api/globals.markdown", + "globals": [ + { + "textRaw": "global", + "name": "global", + "type": "global", + "desc": "

In browsers, the top-level scope is the global scope. That means that in\nbrowsers if you're in the global scope var something will define a global\nvariable. In Node this is different. The top-level scope is not the global\nscope; var something inside a Node module will be local to that module.\n\n

\n" + }, + { + "textRaw": "process", + "name": "process", + "type": "global", + "desc": "

The process object. See the [process object][] section.\n\n

\n" + }, + { + "textRaw": "console", + "name": "console", + "type": "global", + "desc": "

Used to print to stdout and stderr. See the [stdio][] section.\n\n

\n" + }, + { + "textRaw": "Class: Buffer", + "type": "global", + "name": "Buffer", + "desc": "

Used to handle binary data. See the [buffer section][]\n\n

\n" + }, + { + "textRaw": "clearInterval(t)", + "type": "global", + "name": "clearInterval", + "desc": "

Stop a timer that was previously created with setInterval(). The callback\nwill not execute.\n\n

\n

The timer functions are global variables. See the [timers][] section.\n\n

\n" + } + ], + "vars": [ + { + "textRaw": "require()", + "type": "var", + "name": "require", + "desc": "

To require modules. See the [Modules][] section. require isn't actually a\nglobal but rather local to each module.\n\n

\n", + "methods": [ + { + "textRaw": "require.resolve()", + "type": "method", + "name": "resolve", + "desc": "

Use the internal require() machinery to look up the location of a module,\nbut rather than loading the module, just return the resolved filename.\n\n

\n", + "signatures": [ + { + "params": [] + } + ] + } + ], + "properties": [ + { + "textRaw": "`cache` {Object} ", + "name": "cache", + "desc": "

Modules are cached in this object when they are required. By deleting a key\nvalue from this object, the next require will reload the module.\n\n

\n" + }, + { + "textRaw": "`extensions` {Array} ", + "name": "extensions", + "desc": "

Instruct require on how to handle certain file extensions.\n\n

\n

Process files with the extension .sjs as .js:\n\n

\n
require.extensions['.sjs'] = require.extensions['.js'];
\n

Write your own extension handler:\n\n

\n
require.extensions['.sjs'] = function(module, filename) {\n  var content = fs.readFileSync(filename, 'utf8');\n  // Parse the file content and give to module.exports\n  module.exports = content;\n};
\n" + } + ] + }, + { + "textRaw": "__filename", + "name": "__filename", + "type": "var", + "desc": "

The filename of the code being executed. This is the resolved absolute path\nof this code file. For a main program this is not necessarily the same\nfilename used in the command line. The value inside a module is the path\nto that module file.\n\n

\n

Example: running node example.js from /Users/mjr\n\n

\n
console.log(__filename);\n// /Users/mjr/example.js
\n

__filename isn't actually a global but rather local to each module.\n\n

\n" + }, + { + "textRaw": "__dirname", + "name": "__dirname", + "type": "var", + "desc": "

The name of the directory that the currently executing script resides in.\n\n

\n

Example: running node example.js from /Users/mjr\n\n

\n
console.log(__dirname);\n// /Users/mjr
\n

__dirname isn't actually a global but rather local to each module.\n\n\n

\n" + }, + { + "textRaw": "module", + "name": "module", + "type": "var", + "desc": "

A reference to the current module. In particular\nmodule.exports is the same as the exports object.\nmodule isn't actually a global but rather local to each module.\n\n

\n

See the [module system documentation][] for more information.\n\n

\n" + }, + { + "textRaw": "exports", + "name": "exports", + "type": "var", + "desc": "

An object which is shared between all instances of the current module and\nmade accessible through require().\nexports is the same as the module.exports object.\nexports isn't actually a global but rather local to each module.\n\n

\n

See the [module system documentation][] for more information.\n\n

\n

See the [module section][] for more information.\n\n

\n" + } + ], + "methods": [ + { + "textRaw": "setTimeout(cb, ms)", + "type": "method", + "name": "setTimeout", + "desc": "

Run callback cb after at least ms milliseconds. The actual delay depends\non external factors like OS timer granularity and system load.\n\n

\n

The timeout must be in the range of 1-2,147,483,647 inclusive. If the value is\noutside that range, it's changed to 1 millisecond. Broadly speaking, a timer\ncannot span more than 24.8 days.\n\n

\n

Returns an opaque value that represents the timer.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "cb" + }, + { + "name": "ms" + } + ] + } + ] + }, + { + "textRaw": "clearTimeout(t)", + "type": "method", + "name": "clearTimeout", + "desc": "

Stop a timer that was previously created with setTimeout(). The callback will\nnot execute.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "t" + } + ] + } + ] + }, + { + "textRaw": "setInterval(cb, ms)", + "type": "method", + "name": "setInterval", + "desc": "

Run callback cb repeatedly every ms milliseconds. Note that the actual\ninterval may vary, depending on external factors like OS timer granularity and\nsystem load. It's never less than ms but it may be longer.\n\n

\n

The interval must be in the range of 1-2,147,483,647 inclusive. If the value is\noutside that range, it's changed to 1 millisecond. Broadly speaking, a timer\ncannot span more than 24.8 days.\n\n

\n

Returns an opaque value that represents the timer.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "cb" + }, + { + "name": "ms" + } + ] + } + ] + } + ], + "miscs": [ + { + "textRaw": "Global Objects", + "name": "Global Objects", + "type": "misc", + "desc": "

These objects are available in all modules. Some of these objects aren't\nactually in the global scope but in the module scope - this will be noted.\n\n

\n", + "globals": [ + { + "textRaw": "global", + "name": "global", + "type": "global", + "desc": "

In browsers, the top-level scope is the global scope. That means that in\nbrowsers if you're in the global scope var something will define a global\nvariable. In Node this is different. The top-level scope is not the global\nscope; var something inside a Node module will be local to that module.\n\n

\n" + }, + { + "textRaw": "process", + "name": "process", + "type": "global", + "desc": "

The process object. See the [process object][] section.\n\n

\n" + }, + { + "textRaw": "console", + "name": "console", + "type": "global", + "desc": "

Used to print to stdout and stderr. See the [stdio][] section.\n\n

\n" + }, + { + "textRaw": "Class: Buffer", + "type": "global", + "name": "Buffer", + "desc": "

Used to handle binary data. See the [buffer section][]\n\n

\n" + }, + { + "textRaw": "clearInterval(t)", + "type": "global", + "name": "clearInterval", + "desc": "

Stop a timer that was previously created with setInterval(). The callback\nwill not execute.\n\n

\n

The timer functions are global variables. See the [timers][] section.\n\n

\n" + } + ], + "vars": [ + { + "textRaw": "require()", + "type": "var", + "name": "require", + "desc": "

To require modules. See the [Modules][] section. require isn't actually a\nglobal but rather local to each module.\n\n

\n", + "methods": [ + { + "textRaw": "require.resolve()", + "type": "method", + "name": "resolve", + "desc": "

Use the internal require() machinery to look up the location of a module,\nbut rather than loading the module, just return the resolved filename.\n\n

\n", + "signatures": [ + { + "params": [] + } + ] + } + ], + "properties": [ + { + "textRaw": "`cache` {Object} ", + "name": "cache", + "desc": "

Modules are cached in this object when they are required. By deleting a key\nvalue from this object, the next require will reload the module.\n\n

\n" + }, + { + "textRaw": "`extensions` {Array} ", + "name": "extensions", + "desc": "

Instruct require on how to handle certain file extensions.\n\n

\n

Process files with the extension .sjs as .js:\n\n

\n
require.extensions['.sjs'] = require.extensions['.js'];
\n

Write your own extension handler:\n\n

\n
require.extensions['.sjs'] = function(module, filename) {\n  var content = fs.readFileSync(filename, 'utf8');\n  // Parse the file content and give to module.exports\n  module.exports = content;\n};
\n" + } + ] + }, + { + "textRaw": "__filename", + "name": "__filename", + "type": "var", + "desc": "

The filename of the code being executed. This is the resolved absolute path\nof this code file. For a main program this is not necessarily the same\nfilename used in the command line. The value inside a module is the path\nto that module file.\n\n

\n

Example: running node example.js from /Users/mjr\n\n

\n
console.log(__filename);\n// /Users/mjr/example.js
\n

__filename isn't actually a global but rather local to each module.\n\n

\n" + }, + { + "textRaw": "__dirname", + "name": "__dirname", + "type": "var", + "desc": "

The name of the directory that the currently executing script resides in.\n\n

\n

Example: running node example.js from /Users/mjr\n\n

\n
console.log(__dirname);\n// /Users/mjr
\n

__dirname isn't actually a global but rather local to each module.\n\n\n

\n" + }, + { + "textRaw": "module", + "name": "module", + "type": "var", + "desc": "

A reference to the current module. In particular\nmodule.exports is the same as the exports object.\nmodule isn't actually a global but rather local to each module.\n\n

\n

See the [module system documentation][] for more information.\n\n

\n" + }, + { + "textRaw": "exports", + "name": "exports", + "type": "var", + "desc": "

An object which is shared between all instances of the current module and\nmade accessible through require().\nexports is the same as the module.exports object.\nexports isn't actually a global but rather local to each module.\n\n

\n

See the [module system documentation][] for more information.\n\n

\n

See the [module section][] for more information.\n\n

\n" + } + ], + "methods": [ + { + "textRaw": "setTimeout(cb, ms)", + "type": "method", + "name": "setTimeout", + "desc": "

Run callback cb after at least ms milliseconds. The actual delay depends\non external factors like OS timer granularity and system load.\n\n

\n

The timeout must be in the range of 1-2,147,483,647 inclusive. If the value is\noutside that range, it's changed to 1 millisecond. Broadly speaking, a timer\ncannot span more than 24.8 days.\n\n

\n

Returns an opaque value that represents the timer.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "cb" + }, + { + "name": "ms" + } + ] + } + ] + }, + { + "textRaw": "clearTimeout(t)", + "type": "method", + "name": "clearTimeout", + "desc": "

Stop a timer that was previously created with setTimeout(). The callback will\nnot execute.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "t" + } + ] + } + ] + }, + { + "textRaw": "setInterval(cb, ms)", + "type": "method", + "name": "setInterval", + "desc": "

Run callback cb repeatedly every ms milliseconds. Note that the actual\ninterval may vary, depending on external factors like OS timer granularity and\nsystem load. It's never less than ms but it may be longer.\n\n

\n

The interval must be in the range of 1-2,147,483,647 inclusive. If the value is\noutside that range, it's changed to 1 millisecond. Broadly speaking, a timer\ncannot span more than 24.8 days.\n\n

\n

Returns an opaque value that represents the timer.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "cb" + }, + { + "name": "ms" + } + ] + } + ] + } + ] + } + ] +} diff --git a/node-v0.8.14/doc/api/globals.markdown b/node-v0.8.14/doc/api/globals.markdown new file mode 100644 index 0000000..0ca2b0d --- /dev/null +++ b/node-v0.8.14/doc/api/globals.markdown @@ -0,0 +1,184 @@ +# Global Objects + + + +These objects are available in all modules. Some of these objects aren't +actually in the global scope but in the module scope - this will be noted. + +## global + + + +* {Object} The global namespace object. + +In browsers, the top-level scope is the global scope. That means that in +browsers if you're in the global scope `var something` will define a global +variable. In Node this is different. The top-level scope is not the global +scope; `var something` inside a Node module will be local to that module. + +## process + + + +* {Object} + +The process object. See the [process object][] section. + +## console + + + +* {Object} + +Used to print to stdout and stderr. See the [stdio][] section. + +## Class: Buffer + + + +* {Function} + +Used to handle binary data. See the [buffer section][] + +## require() + + + +* {Function} + +To require modules. See the [Modules][] section. `require` isn't actually a +global but rather local to each module. + +### require.resolve() + +Use the internal `require()` machinery to look up the location of a module, +but rather than loading the module, just return the resolved filename. + +### require.cache + +* {Object} + +Modules are cached in this object when they are required. By deleting a key +value from this object, the next `require` will reload the module. + +### require.extensions + +* {Array} + +Instruct `require` on how to handle certain file extensions. + +Process files with the extension `.sjs` as `.js`: + + require.extensions['.sjs'] = require.extensions['.js']; + +Write your own extension handler: + + require.extensions['.sjs'] = function(module, filename) { + var content = fs.readFileSync(filename, 'utf8'); + // Parse the file content and give to module.exports + module.exports = content; + }; + +## __filename + + + +* {String} + +The filename of the code being executed. This is the resolved absolute path +of this code file. For a main program this is not necessarily the same +filename used in the command line. The value inside a module is the path +to that module file. + +Example: running `node example.js` from `/Users/mjr` + + console.log(__filename); + // /Users/mjr/example.js + +`__filename` isn't actually a global but rather local to each module. + +## __dirname + + + +* {String} + +The name of the directory that the currently executing script resides in. + +Example: running `node example.js` from `/Users/mjr` + + console.log(__dirname); + // /Users/mjr + +`__dirname` isn't actually a global but rather local to each module. + + +## module + + + +* {Object} + +A reference to the current module. In particular +`module.exports` is the same as the `exports` object. +`module` isn't actually a global but rather local to each module. + +See the [module system documentation][] for more information. + +## exports + + + +An object which is shared between all instances of the current module and +made accessible through `require()`. +`exports` is the same as the `module.exports` object. +`exports` isn't actually a global but rather local to each module. + +See the [module system documentation][] for more information. + +See the [module section][] for more information. + +## setTimeout(cb, ms) + +Run callback `cb` after *at least* `ms` milliseconds. The actual delay depends +on external factors like OS timer granularity and system load. + +The timeout must be in the range of 1-2,147,483,647 inclusive. If the value is +outside that range, it's changed to 1 millisecond. Broadly speaking, a timer +cannot span more than 24.8 days. + +Returns an opaque value that represents the timer. + +## clearTimeout(t) + +Stop a timer that was previously created with `setTimeout()`. The callback will +not execute. + +## setInterval(cb, ms) + +Run callback `cb` repeatedly every `ms` milliseconds. Note that the actual +interval may vary, depending on external factors like OS timer granularity and +system load. It's never less than `ms` but it may be longer. + +The interval must be in the range of 1-2,147,483,647 inclusive. If the value is +outside that range, it's changed to 1 millisecond. Broadly speaking, a timer +cannot span more than 24.8 days. + +Returns an opaque value that represents the timer. + +## clearInterval(t) + +Stop a timer that was previously created with `setInterval()`. The callback +will not execute. + + + +The timer functions are global variables. See the [timers][] section. + +[buffer section]: buffer.html +[module section]: modules.html +[module system documentation]: modules.html +[Modules]: modules.html#modules_modules +[process object]: process.html#process_process +[stdio]: stdio.html +[timers]: timers.html diff --git a/node-v0.8.14/doc/api/http.html b/node-v0.8.14/doc/api/http.html new file mode 100644 index 0000000..5a77de1 --- /dev/null +++ b/node-v0.8.14/doc/api/http.html @@ -0,0 +1,1164 @@ + + + + + HTTP Node.js v0.8.14 Manual & Documentation + + + + + +
+ + + +
+
+ + +
+
+

Node.js v0.8.14 Manual & Documentation

+ +
+
+ +
+

Table of Contents

+ + +
+ +
+

HTTP#

+
Stability: 3 - Stable
+

To use the HTTP server and client one must require('http'). + +

+

The HTTP interfaces in Node are designed to support many features +of the protocol which have been traditionally difficult to use. +In particular, large, possibly chunk-encoded, messages. The interface is +careful to never buffer entire requests or responses--the +user is able to stream data. + +

+

HTTP message headers are represented by an object like this: + +

+
{ 'content-length': '123',
+  'content-type': 'text/plain',
+  'connection': 'keep-alive',
+  'accept': '*/*' }
+

Keys are lowercased. Values are not modified. + +

+

In order to support the full spectrum of possible HTTP applications, Node's +HTTP API is very low-level. It deals with stream handling and message +parsing only. It parses a message into headers and body but it does not +parse the actual headers or the body. + + +

+

http.STATUS_CODES#

+
    +
  • Object
  • +
+

A collection of all the standard HTTP response status codes, and the +short description of each. For example, http.STATUS_CODES[404] === 'Not +Found'. + +

+

http.createServer([requestListener])#

+

Returns a new web server object. + +

+

The requestListener is a function which is automatically +added to the 'request' event. + +

+

http.createClient([port], [host])#

+

This function is deprecated; please use http.request() instead. +Constructs a new HTTP client. port and host refer to the server to be +connected to. + +

+

Class: http.Server#

+

This is an EventEmitter with the following events: + +

+

Event: 'request'#

+

function (request, response) { } + +

+

Emitted each time there is a request. Note that there may be multiple requests +per connection (in the case of keep-alive connections). + request is an instance of http.ServerRequest and response is + an instance of http.ServerResponse + +

+

Event: 'connection'#

+

function (socket) { } + +

+

When a new TCP stream is established. socket is an object of type + net.Socket. Usually users will not want to access this event. The + socket can also be accessed at request.connection. + +

+

Event: 'close'#

+

function () { } + +

+

Emitted when the server closes. + +

+

Event: 'checkContinue'#

+

function (request, response) { } + +

+

Emitted each time a request with an http Expect: 100-continue is received. +If this event isn't listened for, the server will automatically respond +with a 100 Continue as appropriate. + +

+

Handling this event involves calling response.writeContinue if the client +should continue to send the request body, or generating an appropriate HTTP +response (e.g., 400 Bad Request) if the client should not continue to send the +request body. + +

+

Note that when this event is emitted and handled, the request event will +not be emitted. + +

+

Event: 'connect'#

+

function (request, socket, head) { } + +

+

Emitted each time a client requests a http CONNECT method. If this event isn't +listened for, then clients requesting a CONNECT method will have their +connections closed. + +

+
    +
  • request is the arguments for the http request, as it is in the request +event.
  • +
  • socket is the network socket between the server and client.
  • +
  • head is an instance of Buffer, the first packet of the tunneling stream, +this may be empty.
  • +
+

After this event is emitted, the request's socket will not have a data +event listener, meaning you will need to bind to it in order to handle data +sent to the server on that socket. + +

+

Event: 'upgrade'#

+

function (request, socket, head) { } + +

+

Emitted each time a client requests a http upgrade. If this event isn't +listened for, then clients requesting an upgrade will have their connections +closed. + +

+
    +
  • request is the arguments for the http request, as it is in the request +event.
  • +
  • socket is the network socket between the server and client.
  • +
  • head is an instance of Buffer, the first packet of the upgraded stream, +this may be empty.
  • +
+

After this event is emitted, the request's socket will not have a data +event listener, meaning you will need to bind to it in order to handle data +sent to the server on that socket. + +

+

Event: 'clientError'#

+

function (exception) { } + +

+

If a client connection emits an 'error' event - it will forwarded here. + +

+

server.listen(port, [hostname], [backlog], [callback])#

+

Begin accepting connections on the specified port and hostname. If the +hostname is omitted, the server will accept connections directed to any +IPv4 address (INADDR_ANY). + +

+

To listen to a unix socket, supply a filename instead of port and hostname. + +

+

Backlog is the maximum length of the queue of pending connections. +The actual length will be determined by your OS through sysctl settings such as +tcp_max_syn_backlog and somaxconn on linux. The default value of this +parameter is 511 (not 512). + +

+

This function is asynchronous. The last parameter callback will be added as +a listener for the 'listening' event. See also net.Server.listen(port). + + +

+

server.listen(path, [callback])#

+

Start a UNIX socket server listening for connections on the given path. + +

+

This function is asynchronous. The last parameter callback will be added as +a listener for the 'listening' event. See also net.Server.listen(path). + + +

+

server.listen(handle, [callback])#

+
    +
  • handle Object
  • +
  • callback Function
  • +
+

The handle object can be set to either a server or socket (anything +with an underlying _handle member), or a {fd: <n>} object. + +

+

This will cause the server to accept connections on the specified +handle, but it is presumed that the file descriptor or handle has +already been bound to a port or domain socket. + +

+

Listening on a file descriptor is not supported on Windows. + +

+

This function is asynchronous. The last parameter callback will be added as +a listener for the 'listening' event. +See also net.Server.listen(). + +

+

server.close([callback])#

+

Stops the server from accepting new connections. See net.Server.close(). + + +

+

server.maxHeadersCount#

+

Limits maximum incoming headers count, equal to 1000 by default. If set to 0 - +no limit will be applied. + + +

+

Class: http.ServerRequest#

+

This object is created internally by a HTTP server -- not by +the user -- and passed as the first argument to a 'request' listener. + +

+

The request implements the Readable Stream interface. This is an +EventEmitter with the following events: + +

+

Event: 'data'#

+

function (chunk) { } + +

+

Emitted when a piece of the message body is received. The chunk is a string if +an encoding has been set with request.setEncoding(), otherwise it's a +Buffer. + +

+

Note that the data will be lost if there is no listener when a +ServerRequest emits a 'data' event. + +

+

Event: 'end'#

+

function () { } + +

+

Emitted exactly once for each request. After that, no more 'data' events +will be emitted on the request. + +

+

Event: 'close'#

+

function () { } + +

+

Indicates that the underlaying connection was terminated before +response.end() was called or able to flush. + +

+

Just like 'end', this event occurs only once per request, and no more 'data' +events will fire afterwards. + +

+

Note: 'close' can fire after 'end', but not vice versa. + +

+

request.method#

+

The request method as a string. Read only. Example: +'GET', 'DELETE'. + + +

+

request.url#

+

Request URL string. This contains only the URL that is +present in the actual HTTP request. If the request is: + +

+
GET /status?name=ryan HTTP/1.1\r\n
+Accept: text/plain\r\n
+\r\n
+

Then request.url will be: + +

+
'/status?name=ryan'
+

If you would like to parse the URL into its parts, you can use +require('url').parse(request.url). Example: + +

+
node> require('url').parse('/status?name=ryan')
+{ href: '/status?name=ryan',
+  search: '?name=ryan',
+  query: 'name=ryan',
+  pathname: '/status' }
+

If you would like to extract the params from the query string, +you can use the require('querystring').parse function, or pass +true as the second argument to require('url').parse. Example: + +

+
node> require('url').parse('/status?name=ryan', true)
+{ href: '/status?name=ryan',
+  search: '?name=ryan',
+  query: { name: 'ryan' },
+  pathname: '/status' }
+

request.headers#

+

Read only map of header names and values. Header names are lower-cased. +Example: + +

+
// Prints something like:
+//
+// { 'user-agent': 'curl/7.22.0',
+//   host: '127.0.0.1:8000',
+//   accept: '*/*' }
+console.log(request.headers);
+

request.trailers#

+

Read only; HTTP trailers (if present). Only populated after the 'end' event. + +

+

request.httpVersion#

+

The HTTP protocol version as a string. Read only. Examples: +'1.1', '1.0'. +Also request.httpVersionMajor is the first integer and +request.httpVersionMinor is the second. + + +

+

request.setEncoding([encoding])#

+

Set the encoding for the request body. See stream.setEncoding() for more +information. + +

+

request.pause()#

+

Pauses request from emitting events. Useful to throttle back an upload. + + +

+

request.resume()#

+

Resumes a paused request. + +

+

request.connection#

+

The net.Socket object associated with the connection. + + +

+

With HTTPS support, use request.connection.verifyPeer() and +request.connection.getPeerCertificate() to obtain the client's +authentication details. + + + +

+

Class: http.ServerResponse#

+

This object is created internally by a HTTP server--not by the user. It is +passed as the second parameter to the 'request' event. + +

+

The response implements the Writable Stream interface. This is an +EventEmitter with the following events: + +

+

Event: 'close'#

+

function () { } + +

+

Indicates that the underlaying connection was terminated before +response.end() was called or able to flush. + +

+

response.writeContinue()#

+

Sends a HTTP/1.1 100 Continue message to the client, indicating that +the request body should be sent. See the 'checkContinue' event on Server. + +

+

response.writeHead(statusCode, [reasonPhrase], [headers])#

+

Sends a response header to the request. The status code is a 3-digit HTTP +status code, like 404. The last argument, headers, are the response headers. +Optionally one can give a human-readable reasonPhrase as the second +argument. + +

+

Example: + +

+
var body = 'hello world';
+response.writeHead(200, {
+  'Content-Length': body.length,
+  'Content-Type': 'text/plain' });
+

This method must only be called once on a message and it must +be called before response.end() is called. + +

+

If you call response.write() or response.end() before calling this, the +implicit/mutable headers will be calculated and call this function for you. + +

+

Note: that Content-Length is given in bytes not characters. The above example +works because the string 'hello world' contains only single byte characters. +If the body contains higher coded characters then Buffer.byteLength() +should be used to determine the number of bytes in a given encoding. +And Node does not check whether Content-Length and the length of the body +which has been transmitted are equal or not. + +

+

response.statusCode#

+

When using implicit headers (not calling response.writeHead() explicitly), this property +controls the status code that will be sent to the client when the headers get +flushed. + +

+

Example: + +

+
response.statusCode = 404;
+

After response header was sent to the client, this property indicates the +status code which was sent out. + +

+

response.setHeader(name, value)#

+

Sets a single header value for implicit headers. If this header already exists +in the to-be-sent headers, its value will be replaced. Use an array of strings +here if you need to send multiple headers with the same name. + +

+

Example: + +

+
response.setHeader("Content-Type", "text/html");
+

or + +

+
response.setHeader("Set-Cookie", ["type=ninja", "language=javascript"]);
+

response.sendDate#

+

When true, the Date header will be automatically generated and sent in +the response if it is not already present in the headers. Defaults to true. + +

+

This should only be disabled for testing; HTTP requires the Date header +in responses. + +

+

response.getHeader(name)#

+

Reads out a header that's already been queued but not sent to the client. Note +that the name is case insensitive. This can only be called before headers get +implicitly flushed. + +

+

Example: + +

+
var contentType = response.getHeader('content-type');
+

response.removeHeader(name)#

+

Removes a header that's queued for implicit sending. + +

+

Example: + +

+
response.removeHeader("Content-Encoding");
+

response.write(chunk, [encoding])#

+

If this method is called and response.writeHead() has not been called, it will +switch to implicit header mode and flush the implicit headers. + +

+

This sends a chunk of the response body. This method may +be called multiple times to provide successive parts of the body. + +

+

chunk can be a string or a buffer. If chunk is a string, +the second parameter specifies how to encode it into a byte stream. +By default the encoding is 'utf8'. + +

+

Note: This is the raw HTTP body and has nothing to do with +higher-level multi-part body encodings that may be used. + +

+

The first time response.write() is called, it will send the buffered +header information and the first body to the client. The second time +response.write() is called, Node assumes you're going to be streaming +data, and sends that separately. That is, the response is buffered up to the +first chunk of body. + +

+

Returns true if the entire data was flushed successfully to the kernel +buffer. Returns false if all or part of the data was queued in user memory. +'drain' will be emitted when the buffer is again free. + +

+

response.addTrailers(headers)#

+

This method adds HTTP trailing headers (a header but at the end of the +message) to the response. + +

+

Trailers will only be emitted if chunked encoding is used for the +response; if it is not (e.g., if the request was HTTP/1.0), they will +be silently discarded. + +

+

Note that HTTP requires the Trailer header to be sent if you intend to +emit trailers, with a list of the header fields in its value. E.g., + +

+
response.writeHead(200, { 'Content-Type': 'text/plain',
+                          'Trailer': 'Content-MD5' });
+response.write(fileData);
+response.addTrailers({'Content-MD5': "7895bf4b8828b55ceaf47747b4bca667"});
+response.end();
+

response.end([data], [encoding])#

+

This method signals to the server that all of the response headers and body +have been sent; that server should consider this message complete. +The method, response.end(), MUST be called on each +response. + +

+

If data is specified, it is equivalent to calling response.write(data, encoding) +followed by response.end(). + + +

+

http.request(options, callback)#

+

Node maintains several connections per server to make HTTP requests. +This function allows one to transparently issue requests. + +

+

options can be an object or a string. If options is a string, it is +automatically parsed with url.parse(). + +

+

Options: + +

+
    +
  • host: A domain name or IP address of the server to issue the request to. +Defaults to 'localhost'.
  • +
  • hostname: To support url.parse() hostname is preferred over host
  • +
  • port: Port of remote server. Defaults to 80.
  • +
  • localAddress: Local interface to bind for network connections.
  • +
  • socketPath: Unix Domain Socket (use one of host:port or socketPath)
  • +
  • method: A string specifying the HTTP request method. Defaults to 'GET'.
  • +
  • path: Request path. Defaults to '/'. Should include query string if any. +E.G. '/index.html?page=12'
  • +
  • headers: An object containing request headers.
  • +
  • auth: Basic authentication i.e. 'user:password' to compute an +Authorization header.
  • +
  • agent: Controls Agent behavior. When an Agent is used request will +default to Connection: keep-alive. Possible values:
      +
    • undefined (default): use global Agent for this host and port.
    • +
    • Agent object: explicitly use the passed in Agent.
    • +
    • false: opts out of connection pooling with an Agent, defaults request to +Connection: close.
    • +
    +
  • +
+

http.request() returns an instance of the http.ClientRequest +class. The ClientRequest instance is a writable stream. If one needs to +upload a file with a POST request, then write to the ClientRequest object. + +

+

Example: + +

+
var options = {
+  host: 'www.google.com',
+  port: 80,
+  path: '/upload',
+  method: 'POST'
+};
+
+var req = http.request(options, function(res) {
+  console.log('STATUS: ' + res.statusCode);
+  console.log('HEADERS: ' + JSON.stringify(res.headers));
+  res.setEncoding('utf8');
+  res.on('data', function (chunk) {
+    console.log('BODY: ' + chunk);
+  });
+});
+
+req.on('error', function(e) {
+  console.log('problem with request: ' + e.message);
+});
+
+// write data to request body
+req.write('data\n');
+req.write('data\n');
+req.end();
+

Note that in the example req.end() was called. With http.request() one +must always call req.end() to signify that you're done with the request - +even if there is no data being written to the request body. + +

+

If any error is encountered during the request (be that with DNS resolution, +TCP level errors, or actual HTTP parse errors) an 'error' event is emitted +on the returned request object. + +

+

There are a few special headers that should be noted. + +

+
    +
  • Sending a 'Connection: keep-alive' will notify Node that the connection to +the server should be persisted until the next request.

    +
  • +
  • Sending a 'Content-length' header will disable the default chunked encoding.

    +
  • +
  • Sending an 'Expect' header will immediately send the request headers. +Usually, when sending 'Expect: 100-continue', you should both set a timeout +and listen for the continue event. See RFC2616 Section 8.2.3 for more +information.

    +
  • +
  • Sending an Authorization header will override using the auth option +to compute basic authentication.

    +
  • +
+

http.get(options, callback)#

+

Since most requests are GET requests without bodies, Node provides this +convenience method. The only difference between this method and http.request() +is that it sets the method to GET and calls req.end() automatically. + +

+

Example: + +

+
http.get("http://www.google.com/index.html", function(res) {
+  console.log("Got response: " + res.statusCode);
+}).on('error', function(e) {
+  console.log("Got error: " + e.message);
+});
+

Class: http.Agent#

+

In node 0.5.3+ there is a new implementation of the HTTP Agent which is used +for pooling sockets used in HTTP client requests. + +

+

Previously, a single agent instance helped pool for a single host+port. The +current implementation now holds sockets for any number of hosts. + +

+

The current HTTP Agent also defaults client requests to using +Connection:keep-alive. If no pending HTTP requests are waiting on a socket +to become free the socket is closed. This means that node's pool has the +benefit of keep-alive when under load but still does not require developers +to manually close the HTTP clients using keep-alive. + +

+

Sockets are removed from the agent's pool when the socket emits either a +"close" event or a special "agentRemove" event. This means that if you intend +to keep one HTTP request open for a long time and don't want it to stay in the +pool you can do something along the lines of: + +

+
http.get(options, function(res) {
+  // Do stuff
+}).on("socket", function (socket) {
+  socket.emit("agentRemove");
+});
+

Alternatively, you could just opt out of pooling entirely using agent:false: + +

+
http.get({host:'localhost', port:80, path:'/', agent:false}, function (res) {
+  // Do stuff
+})
+

agent.maxSockets#

+

By default set to 5. Determines how many concurrent sockets the agent can have +open per host. + +

+

agent.sockets#

+

An object which contains arrays of sockets currently in use by the Agent. Do not +modify. + +

+

agent.requests#

+

An object which contains queues of requests that have not yet been assigned to +sockets. Do not modify. + +

+

http.globalAgent#

+

Global instance of Agent which is used as the default for all http client +requests. + + +

+

Class: http.ClientRequest#

+

This object is created internally and returned from http.request(). It +represents an in-progress request whose header has already been queued. The +header is still mutable using the setHeader(name, value), getHeader(name), +removeHeader(name) API. The actual header will be sent along with the first +data chunk or when closing the connection. + +

+

To get the response, add a listener for 'response' to the request object. +'response' will be emitted from the request object when the response +headers have been received. The 'response' event is executed with one +argument which is an instance of http.ClientResponse. + +

+

During the 'response' event, one can add listeners to the +response object; particularly to listen for the 'data' event. Note that +the 'response' event is called before any part of the response body is received, +so there is no need to worry about racing to catch the first part of the +body. As long as a listener for 'data' is added during the 'response' +event, the entire body will be caught. + + +

+
// Good
+request.on('response', function (response) {
+  response.on('data', function (chunk) {
+    console.log('BODY: ' + chunk);
+  });
+});
+
+// Bad - misses all or part of the body
+request.on('response', function (response) {
+  setTimeout(function () {
+    response.on('data', function (chunk) {
+      console.log('BODY: ' + chunk);
+    });
+  }, 10);
+});
+

Note: Node does not check whether Content-Length and the length of the body +which has been transmitted are equal or not. + +

+

The request implements the Writable Stream interface. This is an +EventEmitter with the following events: + +

+

Event 'response'#

+

function (response) { } + +

+

Emitted when a response is received to this request. This event is emitted only +once. The response argument will be an instance of http.ClientResponse. + +

+

Options: + +

+
    +
  • host: A domain name or IP address of the server to issue the request to.
  • +
  • port: Port of remote server.
  • +
  • socketPath: Unix Domain Socket (use one of host:port or socketPath)
  • +
+

Event: 'socket'#

+

function (socket) { } + +

+

Emitted after a socket is assigned to this request. + +

+

Event: 'connect'#

+

function (response, socket, head) { } + +

+

Emitted each time a server responds to a request with a CONNECT method. If this +event isn't being listened for, clients receiving a CONNECT method will have +their connections closed. + +

+

A client server pair that show you how to listen for the connect event. + +

+
var http = require('http');
+var net = require('net');
+var url = require('url');
+
+// Create an HTTP tunneling proxy
+var proxy = http.createServer(function (req, res) {
+  res.writeHead(200, {'Content-Type': 'text/plain'});
+  res.end('okay');
+});
+proxy.on('connect', function(req, cltSocket, head) {
+  // connect to an origin server
+  var srvUrl = url.parse('http://' + req.url);
+  var srvSocket = net.connect(srvUrl.port, srvUrl.hostname, function() {
+    cltSocket.write('HTTP/1.1 200 Connection Established\r\n' +
+                    'Proxy-agent: Node-Proxy\r\n' +
+                    '\r\n');
+    srvSocket.write(head);
+    srvSocket.pipe(cltSocket);
+    cltSocket.pipe(srvSocket);
+  });
+});
+
+// now that proxy is running
+proxy.listen(1337, '127.0.0.1', function() {
+
+  // make a request to a tunneling proxy
+  var options = {
+    port: 1337,
+    host: '127.0.0.1',
+    method: 'CONNECT',
+    path: 'www.google.com:80'
+  };
+
+  var req = http.request(options);
+  req.end();
+
+  req.on('connect', function(res, socket, head) {
+    console.log('got connected!');
+
+    // make a request over an HTTP tunnel
+    socket.write('GET / HTTP/1.1\r\n' +
+                 'Host: www.google.com:80\r\n' +
+                 'Connection: close\r\n' +
+                 '\r\n');
+    socket.on('data', function(chunk) {
+      console.log(chunk.toString());
+    });
+    socket.on('end', function() {
+      proxy.close();
+    });
+  });
+});
+

Event: 'upgrade'#

+

function (response, socket, head) { } + +

+

Emitted each time a server responds to a request with an upgrade. If this +event isn't being listened for, clients receiving an upgrade header will have +their connections closed. + +

+

A client server pair that show you how to listen for the upgrade event. + +

+
var http = require('http');
+
+// Create an HTTP server
+var srv = http.createServer(function (req, res) {
+  res.writeHead(200, {'Content-Type': 'text/plain'});
+  res.end('okay');
+});
+srv.on('upgrade', function(req, socket, head) {
+  socket.write('HTTP/1.1 101 Web Socket Protocol Handshake\r\n' +
+               'Upgrade: WebSocket\r\n' +
+               'Connection: Upgrade\r\n' +
+               '\r\n');
+
+  socket.pipe(socket); // echo back
+});
+
+// now that server is running
+srv.listen(1337, '127.0.0.1', function() {
+
+  // make a request
+  var options = {
+    port: 1337,
+    host: '127.0.0.1',
+    headers: {
+      'Connection': 'Upgrade',
+      'Upgrade': 'websocket'
+    }
+  };
+
+  var req = http.request(options);
+  req.end();
+
+  req.on('upgrade', function(res, socket, upgradeHead) {
+    console.log('got upgraded!');
+    socket.end();
+    process.exit(0);
+  });
+});
+

Event: 'continue'#

+

function () { } + +

+

Emitted when the server sends a '100 Continue' HTTP response, usually because +the request contained 'Expect: 100-continue'. This is an instruction that +the client should send the request body. + +

+

request.write(chunk, [encoding])#

+

Sends a chunk of the body. By calling this method +many times, the user can stream a request body to a +server--in that case it is suggested to use the +['Transfer-Encoding', 'chunked'] header line when +creating the request. + +

+

The chunk argument should be a Buffer or a string. + +

+

The encoding argument is optional and only applies when chunk is a string. +Defaults to 'utf8'. + + +

+

request.end([data], [encoding])#

+

Finishes sending the request. If any parts of the body are +unsent, it will flush them to the stream. If the request is +chunked, this will send the terminating '0\r\n\r\n'. + +

+

If data is specified, it is equivalent to calling +request.write(data, encoding) followed by request.end(). + +

+

request.abort()#

+

Aborts a request. (New since v0.3.8.) + +

+

request.setTimeout(timeout, [callback])#

+

Once a socket is assigned to this request and is connected +socket.setTimeout() will be called. + +

+

request.setNoDelay([noDelay])#

+

Once a socket is assigned to this request and is connected +socket.setNoDelay() will be called. + +

+

request.setSocketKeepAlive([enable], [initialDelay])#

+

Once a socket is assigned to this request and is connected +socket.setKeepAlive() will be called. + +

+

http.ClientResponse#

+

This object is created when making a request with http.request(). It is +passed to the 'response' event of the request object. + +

+

The response implements the Readable Stream interface. This is an +EventEmitter with the following events: + + +

+

Event: 'data'#

+

function (chunk) { } + +

+

Emitted when a piece of the message body is received. + +

+

Note that the data will be lost if there is no listener when a +ClientResponse emits a 'data' event. + + +

+

Event: 'end'#

+

function () { } + +

+

Emitted exactly once for each response. After that, no more 'data' events +will be emitted on the response. + + +

+

Event: 'close'#

+

function () { } + +

+

Indicates that the underlaying connection was terminated before +response.end() was called or able to flush. + +

+

Just like 'end', this event occurs only once per response, and no more +'data' events will fire afterwards. See [http.ServerResponse][]'s 'close' +event for more information. + +

+

Note: 'close' can fire after 'end', but not vice versa. + + +

+

response.statusCode#

+

The 3-digit HTTP response status code. E.G. 404. + +

+

response.httpVersion#

+

The HTTP version of the connected-to server. Probably either +'1.1' or '1.0'. +Also response.httpVersionMajor is the first integer and +response.httpVersionMinor is the second. + +

+

response.headers#

+

The response headers object. + +

+

response.trailers#

+

The response trailers object. Only populated after the 'end' event. + +

+

response.setEncoding([encoding])#

+

Set the encoding for the response body. See stream.setEncoding() for more +information. + +

+

response.pause()#

+

Pauses response from emitting events. Useful to throttle back a download. + +

+

response.resume()#

+

Resumes a paused response. + +

+ +
+
+
+ + + + + + + + + diff --git a/node-v0.8.14/doc/api/http.json b/node-v0.8.14/doc/api/http.json new file mode 100644 index 0000000..8914435 --- /dev/null +++ b/node-v0.8.14/doc/api/http.json @@ -0,0 +1,793 @@ +{ + "source": "doc/api/http.markdown", + "modules": [ + { + "textRaw": "HTTP", + "name": "http", + "stability": 3, + "stabilityText": "Stable", + "desc": "

To use the HTTP server and client one must require('http').\n\n

\n

The HTTP interfaces in Node are designed to support many features\nof the protocol which have been traditionally difficult to use.\nIn particular, large, possibly chunk-encoded, messages. The interface is\ncareful to never buffer entire requests or responses--the\nuser is able to stream data.\n\n

\n

HTTP message headers are represented by an object like this:\n\n

\n
{ 'content-length': '123',\n  'content-type': 'text/plain',\n  'connection': 'keep-alive',\n  'accept': '*/*' }
\n

Keys are lowercased. Values are not modified.\n\n

\n

In order to support the full spectrum of possible HTTP applications, Node's\nHTTP API is very low-level. It deals with stream handling and message\nparsing only. It parses a message into headers and body but it does not\nparse the actual headers or the body.\n\n\n

\n", + "properties": [ + { + "textRaw": "`STATUS_CODES` {Object} ", + "name": "STATUS_CODES", + "desc": "

A collection of all the standard HTTP response status codes, and the\nshort description of each. For example, http.STATUS_CODES[404] === 'Not\nFound'.\n\n

\n" + }, + { + "textRaw": "http.globalAgent", + "name": "globalAgent", + "desc": "

Global instance of Agent which is used as the default for all http client\nrequests.\n\n\n

\n" + }, + { + "textRaw": "http.ClientResponse", + "name": "ClientResponse", + "desc": "

This object is created when making a request with http.request(). It is\npassed to the 'response' event of the request object.\n\n

\n

The response implements the [Readable Stream][] interface. This is an\n[EventEmitter][] with the following events:\n\n\n

\n", + "events": [ + { + "textRaw": "Event: 'data'", + "type": "event", + "name": "data", + "desc": "

function (chunk) { }\n\n

\n

Emitted when a piece of the message body is received.\n\n

\n

Note that the data will be lost if there is no listener when a\nClientResponse emits a 'data' event.\n\n\n

\n", + "params": [] + }, + { + "textRaw": "Event: 'end'", + "type": "event", + "name": "end", + "desc": "

function () { }\n\n

\n

Emitted exactly once for each response. After that, no more 'data' events\nwill be emitted on the response.\n\n\n

\n", + "params": [] + }, + { + "textRaw": "Event: 'close'", + "type": "event", + "name": "close", + "desc": "

function () { }\n\n

\n

Indicates that the underlaying connection was terminated before\nresponse.end() was called or able to flush.\n\n

\n

Just like 'end', this event occurs only once per response, and no more\n'data' events will fire afterwards. See [http.ServerResponse][]'s 'close'\nevent for more information.\n\n

\n

Note: 'close' can fire after 'end', but not vice versa.\n\n\n

\n", + "params": [] + } + ], + "properties": [ + { + "textRaw": "response.statusCode", + "name": "statusCode", + "desc": "

The 3-digit HTTP response status code. E.G. 404.\n\n

\n" + }, + { + "textRaw": "response.httpVersion", + "name": "httpVersion", + "desc": "

The HTTP version of the connected-to server. Probably either\n'1.1' or '1.0'.\nAlso response.httpVersionMajor is the first integer and\nresponse.httpVersionMinor is the second.\n\n

\n" + }, + { + "textRaw": "response.headers", + "name": "headers", + "desc": "

The response headers object.\n\n

\n" + }, + { + "textRaw": "response.trailers", + "name": "trailers", + "desc": "

The response trailers object. Only populated after the 'end' event.\n\n

\n" + } + ], + "methods": [ + { + "textRaw": "response.setEncoding([encoding])", + "type": "method", + "name": "setEncoding", + "desc": "

Set the encoding for the response body. See [stream.setEncoding()][] for more\ninformation.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "encoding", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "response.pause()", + "type": "method", + "name": "pause", + "desc": "

Pauses response from emitting events. Useful to throttle back a download.\n\n

\n", + "signatures": [ + { + "params": [] + } + ] + }, + { + "textRaw": "response.resume()", + "type": "method", + "name": "resume", + "desc": "

Resumes a paused response.\n\n

\n", + "signatures": [ + { + "params": [] + } + ] + } + ] + } + ], + "methods": [ + { + "textRaw": "http.createServer([requestListener])", + "type": "method", + "name": "createServer", + "desc": "

Returns a new web server object.\n\n

\n

The requestListener is a function which is automatically\nadded to the 'request' event.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "requestListener", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "http.createClient([port], [host])", + "type": "method", + "name": "createClient", + "desc": "

This function is deprecated; please use [http.request()][] instead.\nConstructs a new HTTP client. port and host refer to the server to be\nconnected to.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "port", + "optional": true + }, + { + "name": "host", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "http.request(options, callback)", + "type": "method", + "name": "request", + "desc": "

Node maintains several connections per server to make HTTP requests.\nThis function allows one to transparently issue requests.\n\n

\n

options can be an object or a string. If options is a string, it is\nautomatically parsed with [url.parse()][].\n\n

\n

Options:\n\n

\n
    \n
  • host: A domain name or IP address of the server to issue the request to.\nDefaults to 'localhost'.
  • \n
  • hostname: To support url.parse() hostname is preferred over host
  • \n
  • port: Port of remote server. Defaults to 80.
  • \n
  • localAddress: Local interface to bind for network connections.
  • \n
  • socketPath: Unix Domain Socket (use one of host:port or socketPath)
  • \n
  • method: A string specifying the HTTP request method. Defaults to 'GET'.
  • \n
  • path: Request path. Defaults to '/'. Should include query string if any.\nE.G. '/index.html?page=12'
  • \n
  • headers: An object containing request headers.
  • \n
  • auth: Basic authentication i.e. 'user:password' to compute an\nAuthorization header.
  • \n
  • agent: Controls [Agent][] behavior. When an Agent is used request will\ndefault to Connection: keep-alive. Possible values:
      \n
    • undefined (default): use [global Agent][] for this host and port.
    • \n
    • Agent object: explicitly use the passed in Agent.
    • \n
    • false: opts out of connection pooling with an Agent, defaults request to\nConnection: close.
    • \n
    \n
  • \n
\n

http.request() returns an instance of the http.ClientRequest\nclass. The ClientRequest instance is a writable stream. If one needs to\nupload a file with a POST request, then write to the ClientRequest object.\n\n

\n

Example:\n\n

\n
var options = {\n  host: 'www.google.com',\n  port: 80,\n  path: '/upload',\n  method: 'POST'\n};\n\nvar req = http.request(options, function(res) {\n  console.log('STATUS: ' + res.statusCode);\n  console.log('HEADERS: ' + JSON.stringify(res.headers));\n  res.setEncoding('utf8');\n  res.on('data', function (chunk) {\n    console.log('BODY: ' + chunk);\n  });\n});\n\nreq.on('error', function(e) {\n  console.log('problem with request: ' + e.message);\n});\n\n// write data to request body\nreq.write('data\\n');\nreq.write('data\\n');\nreq.end();
\n

Note that in the example req.end() was called. With http.request() one\nmust always call req.end() to signify that you're done with the request -\neven if there is no data being written to the request body.\n\n

\n

If any error is encountered during the request (be that with DNS resolution,\nTCP level errors, or actual HTTP parse errors) an 'error' event is emitted\non the returned request object.\n\n

\n

There are a few special headers that should be noted.\n\n

\n
    \n
  • Sending a 'Connection: keep-alive' will notify Node that the connection to\nthe server should be persisted until the next request.

    \n
  • \n
  • Sending a 'Content-length' header will disable the default chunked encoding.

    \n
  • \n
  • Sending an 'Expect' header will immediately send the request headers.\nUsually, when sending 'Expect: 100-continue', you should both set a timeout\nand listen for the continue event. See RFC2616 Section 8.2.3 for more\ninformation.

    \n
  • \n
  • Sending an Authorization header will override using the auth option\nto compute basic authentication.

    \n
  • \n
\n", + "signatures": [ + { + "params": [ + { + "name": "options" + }, + { + "name": "callback" + } + ] + } + ] + }, + { + "textRaw": "http.get(options, callback)", + "type": "method", + "name": "get", + "desc": "

Since most requests are GET requests without bodies, Node provides this\nconvenience method. The only difference between this method and http.request()\nis that it sets the method to GET and calls req.end() automatically.\n\n

\n

Example:\n\n

\n
http.get("http://www.google.com/index.html", function(res) {\n  console.log("Got response: " + res.statusCode);\n}).on('error', function(e) {\n  console.log("Got error: " + e.message);\n});
\n", + "signatures": [ + { + "params": [ + { + "name": "options" + }, + { + "name": "callback" + } + ] + } + ] + } + ], + "classes": [ + { + "textRaw": "Class: http.Server", + "type": "class", + "name": "http.Server", + "desc": "

This is an [EventEmitter][] with the following events:\n\n

\n", + "events": [ + { + "textRaw": "Event: 'request'", + "type": "event", + "name": "request", + "desc": "

function (request, response) { }\n\n

\n

Emitted each time there is a request. Note that there may be multiple requests\nper connection (in the case of keep-alive connections).\n request is an instance of http.ServerRequest and response is\n an instance of http.ServerResponse\n\n

\n", + "params": [] + }, + { + "textRaw": "Event: 'connection'", + "type": "event", + "name": "connection", + "desc": "

function (socket) { }\n\n

\n

When a new TCP stream is established. socket is an object of type\n net.Socket. Usually users will not want to access this event. The\n socket can also be accessed at request.connection.\n\n

\n", + "params": [] + }, + { + "textRaw": "Event: 'close'", + "type": "event", + "name": "close", + "desc": "

function () { }\n\n

\n

Emitted when the server closes.\n\n

\n", + "params": [] + }, + { + "textRaw": "Event: 'checkContinue'", + "type": "event", + "name": "checkContinue", + "desc": "

function (request, response) { }\n\n

\n

Emitted each time a request with an http Expect: 100-continue is received.\nIf this event isn't listened for, the server will automatically respond\nwith a 100 Continue as appropriate.\n\n

\n

Handling this event involves calling response.writeContinue if the client\nshould continue to send the request body, or generating an appropriate HTTP\nresponse (e.g., 400 Bad Request) if the client should not continue to send the\nrequest body.\n\n

\n

Note that when this event is emitted and handled, the request event will\nnot be emitted.\n\n

\n", + "params": [] + }, + { + "textRaw": "Event: 'connect'", + "type": "event", + "name": "connect", + "desc": "

function (request, socket, head) { }\n\n

\n

Emitted each time a client requests a http CONNECT method. If this event isn't\nlistened for, then clients requesting a CONNECT method will have their\nconnections closed.\n\n

\n
    \n
  • request is the arguments for the http request, as it is in the request\nevent.
  • \n
  • socket is the network socket between the server and client.
  • \n
  • head is an instance of Buffer, the first packet of the tunneling stream,\nthis may be empty.
  • \n
\n

After this event is emitted, the request's socket will not have a data\nevent listener, meaning you will need to bind to it in order to handle data\nsent to the server on that socket.\n\n

\n", + "params": [] + }, + { + "textRaw": "Event: 'upgrade'", + "type": "event", + "name": "upgrade", + "desc": "

function (request, socket, head) { }\n\n

\n

Emitted each time a client requests a http upgrade. If this event isn't\nlistened for, then clients requesting an upgrade will have their connections\nclosed.\n\n

\n
    \n
  • request is the arguments for the http request, as it is in the request\nevent.
  • \n
  • socket is the network socket between the server and client.
  • \n
  • head is an instance of Buffer, the first packet of the upgraded stream,\nthis may be empty.
  • \n
\n

After this event is emitted, the request's socket will not have a data\nevent listener, meaning you will need to bind to it in order to handle data\nsent to the server on that socket.\n\n

\n", + "params": [] + }, + { + "textRaw": "Event: 'clientError'", + "type": "event", + "name": "clientError", + "desc": "

function (exception) { }\n\n

\n

If a client connection emits an 'error' event - it will forwarded here.\n\n

\n", + "params": [] + } + ], + "methods": [ + { + "textRaw": "server.listen(port, [hostname], [backlog], [callback])", + "type": "method", + "name": "listen", + "desc": "

Begin accepting connections on the specified port and hostname. If the\nhostname is omitted, the server will accept connections directed to any\nIPv4 address (INADDR_ANY).\n\n

\n

To listen to a unix socket, supply a filename instead of port and hostname.\n\n

\n

Backlog is the maximum length of the queue of pending connections.\nThe actual length will be determined by your OS through sysctl settings such as\ntcp_max_syn_backlog and somaxconn on linux. The default value of this\nparameter is 511 (not 512).\n\n

\n

This function is asynchronous. The last parameter callback will be added as\na listener for the ['listening'][] event. See also [net.Server.listen(port)][].\n\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "port" + }, + { + "name": "hostname", + "optional": true + }, + { + "name": "backlog", + "optional": true + }, + { + "name": "callback", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "server.listen(path, [callback])", + "type": "method", + "name": "listen", + "desc": "

Start a UNIX socket server listening for connections on the given path.\n\n

\n

This function is asynchronous. The last parameter callback will be added as\na listener for the ['listening'][] event. See also [net.Server.listen(path)][].\n\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "path" + }, + { + "name": "callback", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "server.listen(handle, [callback])", + "type": "method", + "name": "listen", + "signatures": [ + { + "params": [ + { + "textRaw": "`handle` {Object} ", + "name": "handle", + "type": "Object" + }, + { + "textRaw": "`callback` {Function} ", + "name": "callback", + "type": "Function", + "optional": true + } + ] + }, + { + "params": [ + { + "name": "handle" + }, + { + "name": "callback", + "optional": true + } + ] + } + ], + "desc": "

The handle object can be set to either a server or socket (anything\nwith an underlying _handle member), or a {fd: <n>} object.\n\n

\n

This will cause the server to accept connections on the specified\nhandle, but it is presumed that the file descriptor or handle has\nalready been bound to a port or domain socket.\n\n

\n

Listening on a file descriptor is not supported on Windows.\n\n

\n

This function is asynchronous. The last parameter callback will be added as\na listener for the 'listening' event.\nSee also net.Server.listen().\n\n

\n" + }, + { + "textRaw": "server.close([callback])", + "type": "method", + "name": "close", + "desc": "

Stops the server from accepting new connections. See [net.Server.close()][].\n\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "callback", + "optional": true + } + ] + } + ] + } + ], + "properties": [ + { + "textRaw": "server.maxHeadersCount", + "name": "maxHeadersCount", + "desc": "

Limits maximum incoming headers count, equal to 1000 by default. If set to 0 -\nno limit will be applied.\n\n\n

\n" + } + ] + }, + { + "textRaw": "Class: http.ServerRequest", + "type": "class", + "name": "http.ServerRequest", + "desc": "

This object is created internally by a HTTP server -- not by\nthe user -- and passed as the first argument to a 'request' listener.\n\n

\n

The request implements the [Readable Stream][] interface. This is an\n[EventEmitter][] with the following events:\n\n

\n", + "events": [ + { + "textRaw": "Event: 'data'", + "type": "event", + "name": "data", + "desc": "

function (chunk) { }\n\n

\n

Emitted when a piece of the message body is received. The chunk is a string if\nan encoding has been set with request.setEncoding(), otherwise it's a\n[Buffer][].\n\n

\n

Note that the data will be lost if there is no listener when a\nServerRequest emits a 'data' event.\n\n

\n", + "params": [] + }, + { + "textRaw": "Event: 'end'", + "type": "event", + "name": "end", + "desc": "

function () { }\n\n

\n

Emitted exactly once for each request. After that, no more 'data' events\nwill be emitted on the request.\n\n

\n", + "params": [] + }, + { + "textRaw": "Event: 'close'", + "type": "event", + "name": "close", + "desc": "

function () { }\n\n

\n

Indicates that the underlaying connection was terminated before\nresponse.end() was called or able to flush.\n\n

\n

Just like 'end', this event occurs only once per request, and no more 'data'\nevents will fire afterwards.\n\n

\n

Note: 'close' can fire after 'end', but not vice versa.\n\n

\n", + "params": [] + } + ], + "properties": [ + { + "textRaw": "request.method", + "name": "method", + "desc": "

The request method as a string. Read only. Example:\n'GET', 'DELETE'.\n\n\n

\n" + }, + { + "textRaw": "request.url", + "name": "url", + "desc": "

Request URL string. This contains only the URL that is\npresent in the actual HTTP request. If the request is:\n\n

\n
GET /status?name=ryan HTTP/1.1\\r\\n\nAccept: text/plain\\r\\n\n\\r\\n
\n

Then request.url will be:\n\n

\n
'/status?name=ryan'
\n

If you would like to parse the URL into its parts, you can use\nrequire('url').parse(request.url). Example:\n\n

\n
node> require('url').parse('/status?name=ryan')\n{ href: '/status?name=ryan',\n  search: '?name=ryan',\n  query: 'name=ryan',\n  pathname: '/status' }
\n

If you would like to extract the params from the query string,\nyou can use the require('querystring').parse function, or pass\ntrue as the second argument to require('url').parse. Example:\n\n

\n
node> require('url').parse('/status?name=ryan', true)\n{ href: '/status?name=ryan',\n  search: '?name=ryan',\n  query: { name: 'ryan' },\n  pathname: '/status' }
\n" + }, + { + "textRaw": "request.headers", + "name": "headers", + "desc": "

Read only map of header names and values. Header names are lower-cased.\nExample:\n\n

\n
// Prints something like:\n//\n// { 'user-agent': 'curl/7.22.0',\n//   host: '127.0.0.1:8000',\n//   accept: '*/*' }\nconsole.log(request.headers);
\n" + }, + { + "textRaw": "request.trailers", + "name": "trailers", + "desc": "

Read only; HTTP trailers (if present). Only populated after the 'end' event.\n\n

\n" + }, + { + "textRaw": "request.httpVersion", + "name": "httpVersion", + "desc": "

The HTTP protocol version as a string. Read only. Examples:\n'1.1', '1.0'.\nAlso request.httpVersionMajor is the first integer and\nrequest.httpVersionMinor is the second.\n\n\n

\n" + }, + { + "textRaw": "request.connection", + "name": "connection", + "desc": "

The net.Socket object associated with the connection.\n\n\n

\n

With HTTPS support, use request.connection.verifyPeer() and\nrequest.connection.getPeerCertificate() to obtain the client's\nauthentication details.\n\n\n\n

\n" + } + ], + "methods": [ + { + "textRaw": "request.setEncoding([encoding])", + "type": "method", + "name": "setEncoding", + "desc": "

Set the encoding for the request body. See [stream.setEncoding()][] for more\ninformation.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "encoding", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "request.pause()", + "type": "method", + "name": "pause", + "desc": "

Pauses request from emitting events. Useful to throttle back an upload.\n\n\n

\n", + "signatures": [ + { + "params": [] + } + ] + }, + { + "textRaw": "request.resume()", + "type": "method", + "name": "resume", + "desc": "

Resumes a paused request.\n\n

\n", + "signatures": [ + { + "params": [] + } + ] + } + ] + }, + { + "textRaw": "Class: http.ServerResponse", + "type": "class", + "name": "http.ServerResponse", + "desc": "

This object is created internally by a HTTP server--not by the user. It is\npassed as the second parameter to the 'request' event.\n\n

\n

The response implements the [Writable Stream][] interface. This is an\n[EventEmitter][] with the following events:\n\n

\n", + "events": [ + { + "textRaw": "Event: 'close'", + "type": "event", + "name": "close", + "desc": "

function () { }\n\n

\n

Indicates that the underlaying connection was terminated before\nresponse.end() was called or able to flush.\n\n

\n", + "params": [] + } + ], + "methods": [ + { + "textRaw": "response.writeContinue()", + "type": "method", + "name": "writeContinue", + "desc": "

Sends a HTTP/1.1 100 Continue message to the client, indicating that\nthe request body should be sent. See the ['checkContinue'][] event on Server.\n\n

\n", + "signatures": [ + { + "params": [] + } + ] + }, + { + "textRaw": "response.writeHead(statusCode, [reasonPhrase], [headers])", + "type": "method", + "name": "writeHead", + "desc": "

Sends a response header to the request. The status code is a 3-digit HTTP\nstatus code, like 404. The last argument, headers, are the response headers.\nOptionally one can give a human-readable reasonPhrase as the second\nargument.\n\n

\n

Example:\n\n

\n
var body = 'hello world';\nresponse.writeHead(200, {\n  'Content-Length': body.length,\n  'Content-Type': 'text/plain' });
\n

This method must only be called once on a message and it must\nbe called before response.end() is called.\n\n

\n

If you call response.write() or response.end() before calling this, the\nimplicit/mutable headers will be calculated and call this function for you.\n\n

\n

Note: that Content-Length is given in bytes not characters. The above example\nworks because the string 'hello world' contains only single byte characters.\nIf the body contains higher coded characters then Buffer.byteLength()\nshould be used to determine the number of bytes in a given encoding.\nAnd Node does not check whether Content-Length and the length of the body\nwhich has been transmitted are equal or not.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "statusCode" + }, + { + "name": "reasonPhrase", + "optional": true + }, + { + "name": "headers", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "response.setHeader(name, value)", + "type": "method", + "name": "setHeader", + "desc": "

Sets a single header value for implicit headers. If this header already exists\nin the to-be-sent headers, its value will be replaced. Use an array of strings\nhere if you need to send multiple headers with the same name.\n\n

\n

Example:\n\n

\n
response.setHeader("Content-Type", "text/html");
\n

or\n\n

\n
response.setHeader("Set-Cookie", ["type=ninja", "language=javascript"]);
\n", + "signatures": [ + { + "params": [ + { + "name": "name" + }, + { + "name": "value" + } + ] + } + ] + }, + { + "textRaw": "response.getHeader(name)", + "type": "method", + "name": "getHeader", + "desc": "

Reads out a header that's already been queued but not sent to the client. Note\nthat the name is case insensitive. This can only be called before headers get\nimplicitly flushed.\n\n

\n

Example:\n\n

\n
var contentType = response.getHeader('content-type');
\n", + "signatures": [ + { + "params": [ + { + "name": "name" + } + ] + } + ] + }, + { + "textRaw": "response.removeHeader(name)", + "type": "method", + "name": "removeHeader", + "desc": "

Removes a header that's queued for implicit sending.\n\n

\n

Example:\n\n

\n
response.removeHeader("Content-Encoding");
\n", + "signatures": [ + { + "params": [ + { + "name": "name" + } + ] + } + ] + }, + { + "textRaw": "response.write(chunk, [encoding])", + "type": "method", + "name": "write", + "desc": "

If this method is called and response.writeHead() has not been called, it will\nswitch to implicit header mode and flush the implicit headers.\n\n

\n

This sends a chunk of the response body. This method may\nbe called multiple times to provide successive parts of the body.\n\n

\n

chunk can be a string or a buffer. If chunk is a string,\nthe second parameter specifies how to encode it into a byte stream.\nBy default the encoding is 'utf8'.\n\n

\n

Note: This is the raw HTTP body and has nothing to do with\nhigher-level multi-part body encodings that may be used.\n\n

\n

The first time response.write() is called, it will send the buffered\nheader information and the first body to the client. The second time\nresponse.write() is called, Node assumes you're going to be streaming\ndata, and sends that separately. That is, the response is buffered up to the\nfirst chunk of body.\n\n

\n

Returns true if the entire data was flushed successfully to the kernel\nbuffer. Returns false if all or part of the data was queued in user memory.\n'drain' will be emitted when the buffer is again free.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "chunk" + }, + { + "name": "encoding", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "response.addTrailers(headers)", + "type": "method", + "name": "addTrailers", + "desc": "

This method adds HTTP trailing headers (a header but at the end of the\nmessage) to the response.\n\n

\n

Trailers will only be emitted if chunked encoding is used for the\nresponse; if it is not (e.g., if the request was HTTP/1.0), they will\nbe silently discarded.\n\n

\n

Note that HTTP requires the Trailer header to be sent if you intend to\nemit trailers, with a list of the header fields in its value. E.g.,\n\n

\n
response.writeHead(200, { 'Content-Type': 'text/plain',\n                          'Trailer': 'Content-MD5' });\nresponse.write(fileData);\nresponse.addTrailers({'Content-MD5': "7895bf4b8828b55ceaf47747b4bca667"});\nresponse.end();
\n", + "signatures": [ + { + "params": [ + { + "name": "headers" + } + ] + } + ] + }, + { + "textRaw": "response.end([data], [encoding])", + "type": "method", + "name": "end", + "desc": "

This method signals to the server that all of the response headers and body\nhave been sent; that server should consider this message complete.\nThe method, response.end(), MUST be called on each\nresponse.\n\n

\n

If data is specified, it is equivalent to calling response.write(data, encoding)\nfollowed by response.end().\n\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "data", + "optional": true + }, + { + "name": "encoding", + "optional": true + } + ] + } + ] + } + ], + "properties": [ + { + "textRaw": "response.statusCode", + "name": "statusCode", + "desc": "

When using implicit headers (not calling response.writeHead() explicitly), this property\ncontrols the status code that will be sent to the client when the headers get\nflushed.\n\n

\n

Example:\n\n

\n
response.statusCode = 404;
\n

After response header was sent to the client, this property indicates the\nstatus code which was sent out.\n\n

\n" + }, + { + "textRaw": "response.sendDate", + "name": "sendDate", + "desc": "

When true, the Date header will be automatically generated and sent in \nthe response if it is not already present in the headers. Defaults to true.\n\n

\n

This should only be disabled for testing; HTTP requires the Date header\nin responses.\n\n

\n" + } + ] + }, + { + "textRaw": "Class: http.Agent", + "type": "class", + "name": "http.Agent", + "desc": "

In node 0.5.3+ there is a new implementation of the HTTP Agent which is used\nfor pooling sockets used in HTTP client requests.\n\n

\n

Previously, a single agent instance helped pool for a single host+port. The\ncurrent implementation now holds sockets for any number of hosts.\n\n

\n

The current HTTP Agent also defaults client requests to using\nConnection:keep-alive. If no pending HTTP requests are waiting on a socket\nto become free the socket is closed. This means that node's pool has the\nbenefit of keep-alive when under load but still does not require developers\nto manually close the HTTP clients using keep-alive.\n\n

\n

Sockets are removed from the agent's pool when the socket emits either a\n"close" event or a special "agentRemove" event. This means that if you intend\nto keep one HTTP request open for a long time and don't want it to stay in the\npool you can do something along the lines of:\n\n

\n
http.get(options, function(res) {\n  // Do stuff\n}).on("socket", function (socket) {\n  socket.emit("agentRemove");\n});
\n

Alternatively, you could just opt out of pooling entirely using agent:false:\n\n

\n
http.get({host:'localhost', port:80, path:'/', agent:false}, function (res) {\n  // Do stuff\n})
\n", + "properties": [ + { + "textRaw": "agent.maxSockets", + "name": "maxSockets", + "desc": "

By default set to 5. Determines how many concurrent sockets the agent can have \nopen per host.\n\n

\n" + }, + { + "textRaw": "agent.sockets", + "name": "sockets", + "desc": "

An object which contains arrays of sockets currently in use by the Agent. Do not \nmodify.\n\n

\n" + }, + { + "textRaw": "agent.requests", + "name": "requests", + "desc": "

An object which contains queues of requests that have not yet been assigned to \nsockets. Do not modify.\n\n

\n" + } + ] + }, + { + "textRaw": "Class: http.ClientRequest", + "type": "class", + "name": "http.ClientRequest", + "desc": "

This object is created internally and returned from http.request(). It\nrepresents an in-progress request whose header has already been queued. The\nheader is still mutable using the setHeader(name, value), getHeader(name),\nremoveHeader(name) API. The actual header will be sent along with the first\ndata chunk or when closing the connection.\n\n

\n

To get the response, add a listener for 'response' to the request object.\n'response' will be emitted from the request object when the response\nheaders have been received. The 'response' event is executed with one\nargument which is an instance of http.ClientResponse.\n\n

\n

During the 'response' event, one can add listeners to the\nresponse object; particularly to listen for the 'data' event. Note that\nthe 'response' event is called before any part of the response body is received,\nso there is no need to worry about racing to catch the first part of the\nbody. As long as a listener for 'data' is added during the 'response'\nevent, the entire body will be caught.\n\n\n

\n
// Good\nrequest.on('response', function (response) {\n  response.on('data', function (chunk) {\n    console.log('BODY: ' + chunk);\n  });\n});\n\n// Bad - misses all or part of the body\nrequest.on('response', function (response) {\n  setTimeout(function () {\n    response.on('data', function (chunk) {\n      console.log('BODY: ' + chunk);\n    });\n  }, 10);\n});
\n

Note: Node does not check whether Content-Length and the length of the body\nwhich has been transmitted are equal or not.\n\n

\n

The request implements the [Writable Stream][] interface. This is an\n[EventEmitter][] with the following events:\n\n

\n", + "events": [ + { + "textRaw": "Event 'response'", + "type": "event", + "name": "response", + "desc": "

function (response) { }\n\n

\n

Emitted when a response is received to this request. This event is emitted only\nonce. The response argument will be an instance of http.ClientResponse.\n\n

\n

Options:\n\n

\n
    \n
  • host: A domain name or IP address of the server to issue the request to.
  • \n
  • port: Port of remote server.
  • \n
  • socketPath: Unix Domain Socket (use one of host:port or socketPath)
  • \n
\n", + "params": [] + }, + { + "textRaw": "Event: 'socket'", + "type": "event", + "name": "socket", + "desc": "

function (socket) { }\n\n

\n

Emitted after a socket is assigned to this request.\n\n

\n", + "params": [] + }, + { + "textRaw": "Event: 'connect'", + "type": "event", + "name": "connect", + "desc": "

function (response, socket, head) { }\n\n

\n

Emitted each time a server responds to a request with a CONNECT method. If this\nevent isn't being listened for, clients receiving a CONNECT method will have\ntheir connections closed.\n\n

\n

A client server pair that show you how to listen for the connect event.\n\n

\n
var http = require('http');\nvar net = require('net');\nvar url = require('url');\n\n// Create an HTTP tunneling proxy\nvar proxy = http.createServer(function (req, res) {\n  res.writeHead(200, {'Content-Type': 'text/plain'});\n  res.end('okay');\n});\nproxy.on('connect', function(req, cltSocket, head) {\n  // connect to an origin server\n  var srvUrl = url.parse('http://' + req.url);\n  var srvSocket = net.connect(srvUrl.port, srvUrl.hostname, function() {\n    cltSocket.write('HTTP/1.1 200 Connection Established\\r\\n' +\n                    'Proxy-agent: Node-Proxy\\r\\n' +\n                    '\\r\\n');\n    srvSocket.write(head);\n    srvSocket.pipe(cltSocket);\n    cltSocket.pipe(srvSocket);\n  });\n});\n\n// now that proxy is running\nproxy.listen(1337, '127.0.0.1', function() {\n\n  // make a request to a tunneling proxy\n  var options = {\n    port: 1337,\n    host: '127.0.0.1',\n    method: 'CONNECT',\n    path: 'www.google.com:80'\n  };\n\n  var req = http.request(options);\n  req.end();\n\n  req.on('connect', function(res, socket, head) {\n    console.log('got connected!');\n\n    // make a request over an HTTP tunnel\n    socket.write('GET / HTTP/1.1\\r\\n' +\n                 'Host: www.google.com:80\\r\\n' +\n                 'Connection: close\\r\\n' +\n                 '\\r\\n');\n    socket.on('data', function(chunk) {\n      console.log(chunk.toString());\n    });\n    socket.on('end', function() {\n      proxy.close();\n    });\n  });\n});
\n", + "params": [] + }, + { + "textRaw": "Event: 'upgrade'", + "type": "event", + "name": "upgrade", + "desc": "

function (response, socket, head) { }\n\n

\n

Emitted each time a server responds to a request with an upgrade. If this\nevent isn't being listened for, clients receiving an upgrade header will have\ntheir connections closed.\n\n

\n

A client server pair that show you how to listen for the upgrade event.\n\n

\n
var http = require('http');\n\n// Create an HTTP server\nvar srv = http.createServer(function (req, res) {\n  res.writeHead(200, {'Content-Type': 'text/plain'});\n  res.end('okay');\n});\nsrv.on('upgrade', function(req, socket, head) {\n  socket.write('HTTP/1.1 101 Web Socket Protocol Handshake\\r\\n' +\n               'Upgrade: WebSocket\\r\\n' +\n               'Connection: Upgrade\\r\\n' +\n               '\\r\\n');\n\n  socket.pipe(socket); // echo back\n});\n\n// now that server is running\nsrv.listen(1337, '127.0.0.1', function() {\n\n  // make a request\n  var options = {\n    port: 1337,\n    host: '127.0.0.1',\n    headers: {\n      'Connection': 'Upgrade',\n      'Upgrade': 'websocket'\n    }\n  };\n\n  var req = http.request(options);\n  req.end();\n\n  req.on('upgrade', function(res, socket, upgradeHead) {\n    console.log('got upgraded!');\n    socket.end();\n    process.exit(0);\n  });\n});
\n", + "params": [] + }, + { + "textRaw": "Event: 'continue'", + "type": "event", + "name": "continue", + "desc": "

function () { }\n\n

\n

Emitted when the server sends a '100 Continue' HTTP response, usually because\nthe request contained 'Expect: 100-continue'. This is an instruction that\nthe client should send the request body.\n\n

\n", + "params": [] + } + ], + "methods": [ + { + "textRaw": "request.write(chunk, [encoding])", + "type": "method", + "name": "write", + "desc": "

Sends a chunk of the body. By calling this method\nmany times, the user can stream a request body to a\nserver--in that case it is suggested to use the\n['Transfer-Encoding', 'chunked'] header line when\ncreating the request.\n\n

\n

The chunk argument should be a [Buffer][] or a string.\n\n

\n

The encoding argument is optional and only applies when chunk is a string.\nDefaults to 'utf8'.\n\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "chunk" + }, + { + "name": "encoding", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "request.end([data], [encoding])", + "type": "method", + "name": "end", + "desc": "

Finishes sending the request. If any parts of the body are\nunsent, it will flush them to the stream. If the request is\nchunked, this will send the terminating '0\\r\\n\\r\\n'.\n\n

\n

If data is specified, it is equivalent to calling\nrequest.write(data, encoding) followed by request.end().\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "data", + "optional": true + }, + { + "name": "encoding", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "request.abort()", + "type": "method", + "name": "abort", + "desc": "

Aborts a request. (New since v0.3.8.)\n\n

\n", + "signatures": [ + { + "params": [] + } + ] + }, + { + "textRaw": "request.setTimeout(timeout, [callback])", + "type": "method", + "name": "setTimeout", + "desc": "

Once a socket is assigned to this request and is connected\n[socket.setTimeout()][] will be called.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "timeout" + }, + { + "name": "callback", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "request.setNoDelay([noDelay])", + "type": "method", + "name": "setNoDelay", + "desc": "

Once a socket is assigned to this request and is connected\n[socket.setNoDelay()][] will be called.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "noDelay", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "request.setSocketKeepAlive([enable], [initialDelay])", + "type": "method", + "name": "setSocketKeepAlive", + "desc": "

Once a socket is assigned to this request and is connected\n[socket.setKeepAlive()][] will be called.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "enable", + "optional": true + }, + { + "name": "initialDelay", + "optional": true + } + ] + } + ] + } + ] + } + ], + "type": "module", + "displayName": "HTTP" + } + ] +} diff --git a/node-v0.8.14/doc/api/http.markdown b/node-v0.8.14/doc/api/http.markdown new file mode 100644 index 0000000..e8bf483 --- /dev/null +++ b/node-v0.8.14/doc/api/http.markdown @@ -0,0 +1,936 @@ +# HTTP + + Stability: 3 - Stable + +To use the HTTP server and client one must `require('http')`. + +The HTTP interfaces in Node are designed to support many features +of the protocol which have been traditionally difficult to use. +In particular, large, possibly chunk-encoded, messages. The interface is +careful to never buffer entire requests or responses--the +user is able to stream data. + +HTTP message headers are represented by an object like this: + + { 'content-length': '123', + 'content-type': 'text/plain', + 'connection': 'keep-alive', + 'accept': '*/*' } + +Keys are lowercased. Values are not modified. + +In order to support the full spectrum of possible HTTP applications, Node's +HTTP API is very low-level. It deals with stream handling and message +parsing only. It parses a message into headers and body but it does not +parse the actual headers or the body. + + +## http.STATUS_CODES + +* {Object} + +A collection of all the standard HTTP response status codes, and the +short description of each. For example, `http.STATUS_CODES[404] === 'Not +Found'`. + +## http.createServer([requestListener]) + +Returns a new web server object. + +The `requestListener` is a function which is automatically +added to the `'request'` event. + +## http.createClient([port], [host]) + +This function is **deprecated**; please use [http.request()][] instead. +Constructs a new HTTP client. `port` and `host` refer to the server to be +connected to. + +## Class: http.Server + +This is an [EventEmitter][] with the following events: + +### Event: 'request' + +`function (request, response) { }` + +Emitted each time there is a request. Note that there may be multiple requests +per connection (in the case of keep-alive connections). + `request` is an instance of `http.ServerRequest` and `response` is + an instance of `http.ServerResponse` + +### Event: 'connection' + +`function (socket) { }` + + When a new TCP stream is established. `socket` is an object of type + `net.Socket`. Usually users will not want to access this event. The + `socket` can also be accessed at `request.connection`. + +### Event: 'close' + +`function () { }` + + Emitted when the server closes. + +### Event: 'checkContinue' + +`function (request, response) { }` + +Emitted each time a request with an http Expect: 100-continue is received. +If this event isn't listened for, the server will automatically respond +with a 100 Continue as appropriate. + +Handling this event involves calling `response.writeContinue` if the client +should continue to send the request body, or generating an appropriate HTTP +response (e.g., 400 Bad Request) if the client should not continue to send the +request body. + +Note that when this event is emitted and handled, the `request` event will +not be emitted. + +### Event: 'connect' + +`function (request, socket, head) { }` + +Emitted each time a client requests a http CONNECT method. If this event isn't +listened for, then clients requesting a CONNECT method will have their +connections closed. + +* `request` is the arguments for the http request, as it is in the request + event. +* `socket` is the network socket between the server and client. +* `head` is an instance of Buffer, the first packet of the tunneling stream, + this may be empty. + +After this event is emitted, the request's socket will not have a `data` +event listener, meaning you will need to bind to it in order to handle data +sent to the server on that socket. + +### Event: 'upgrade' + +`function (request, socket, head) { }` + +Emitted each time a client requests a http upgrade. If this event isn't +listened for, then clients requesting an upgrade will have their connections +closed. + +* `request` is the arguments for the http request, as it is in the request + event. +* `socket` is the network socket between the server and client. +* `head` is an instance of Buffer, the first packet of the upgraded stream, + this may be empty. + +After this event is emitted, the request's socket will not have a `data` +event listener, meaning you will need to bind to it in order to handle data +sent to the server on that socket. + +### Event: 'clientError' + +`function (exception) { }` + +If a client connection emits an 'error' event - it will forwarded here. + +### server.listen(port, [hostname], [backlog], [callback]) + +Begin accepting connections on the specified port and hostname. If the +hostname is omitted, the server will accept connections directed to any +IPv4 address (`INADDR_ANY`). + +To listen to a unix socket, supply a filename instead of port and hostname. + +Backlog is the maximum length of the queue of pending connections. +The actual length will be determined by your OS through sysctl settings such as +`tcp_max_syn_backlog` and `somaxconn` on linux. The default value of this +parameter is 511 (not 512). + +This function is asynchronous. The last parameter `callback` will be added as +a listener for the ['listening'][] event. See also [net.Server.listen(port)][]. + + +### server.listen(path, [callback]) + +Start a UNIX socket server listening for connections on the given `path`. + +This function is asynchronous. The last parameter `callback` will be added as +a listener for the ['listening'][] event. See also [net.Server.listen(path)][]. + + +### server.listen(handle, [callback]) + +* `handle` {Object} +* `callback` {Function} + +The `handle` object can be set to either a server or socket (anything +with an underlying `_handle` member), or a `{fd: }` object. + +This will cause the server to accept connections on the specified +handle, but it is presumed that the file descriptor or handle has +already been bound to a port or domain socket. + +Listening on a file descriptor is not supported on Windows. + +This function is asynchronous. The last parameter `callback` will be added as +a listener for the ['listening'](net.html#event_listening_) event. +See also [net.Server.listen()](net.html#net_server_listen_handle_callback). + +### server.close([callback]) + +Stops the server from accepting new connections. See [net.Server.close()][]. + + +### server.maxHeadersCount + +Limits maximum incoming headers count, equal to 1000 by default. If set to 0 - +no limit will be applied. + + +## Class: http.ServerRequest + +This object is created internally by a HTTP server -- not by +the user -- and passed as the first argument to a `'request'` listener. + +The request implements the [Readable Stream][] interface. This is an +[EventEmitter][] with the following events: + +### Event: 'data' + +`function (chunk) { }` + +Emitted when a piece of the message body is received. The chunk is a string if +an encoding has been set with `request.setEncoding()`, otherwise it's a +[Buffer][]. + +Note that the __data will be lost__ if there is no listener when a +`ServerRequest` emits a `'data'` event. + +### Event: 'end' + +`function () { }` + +Emitted exactly once for each request. After that, no more `'data'` events +will be emitted on the request. + +### Event: 'close' + +`function () { }` + +Indicates that the underlaying connection was terminated before +`response.end()` was called or able to flush. + +Just like `'end'`, this event occurs only once per request, and no more `'data'` +events will fire afterwards. + +Note: `'close'` can fire after `'end'`, but not vice versa. + +### request.method + +The request method as a string. Read only. Example: +`'GET'`, `'DELETE'`. + + +### request.url + +Request URL string. This contains only the URL that is +present in the actual HTTP request. If the request is: + + GET /status?name=ryan HTTP/1.1\r\n + Accept: text/plain\r\n + \r\n + +Then `request.url` will be: + + '/status?name=ryan' + +If you would like to parse the URL into its parts, you can use +`require('url').parse(request.url)`. Example: + + node> require('url').parse('/status?name=ryan') + { href: '/status?name=ryan', + search: '?name=ryan', + query: 'name=ryan', + pathname: '/status' } + +If you would like to extract the params from the query string, +you can use the `require('querystring').parse` function, or pass +`true` as the second argument to `require('url').parse`. Example: + + node> require('url').parse('/status?name=ryan', true) + { href: '/status?name=ryan', + search: '?name=ryan', + query: { name: 'ryan' }, + pathname: '/status' } + + + +### request.headers + +Read only map of header names and values. Header names are lower-cased. +Example: + + // Prints something like: + // + // { 'user-agent': 'curl/7.22.0', + // host: '127.0.0.1:8000', + // accept: '*/*' } + console.log(request.headers); + + +### request.trailers + +Read only; HTTP trailers (if present). Only populated after the 'end' event. + +### request.httpVersion + +The HTTP protocol version as a string. Read only. Examples: +`'1.1'`, `'1.0'`. +Also `request.httpVersionMajor` is the first integer and +`request.httpVersionMinor` is the second. + + +### request.setEncoding([encoding]) + +Set the encoding for the request body. See [stream.setEncoding()][] for more +information. + +### request.pause() + +Pauses request from emitting events. Useful to throttle back an upload. + + +### request.resume() + +Resumes a paused request. + +### request.connection + +The `net.Socket` object associated with the connection. + + +With HTTPS support, use request.connection.verifyPeer() and +request.connection.getPeerCertificate() to obtain the client's +authentication details. + + + +## Class: http.ServerResponse + +This object is created internally by a HTTP server--not by the user. It is +passed as the second parameter to the `'request'` event. + +The response implements the [Writable Stream][] interface. This is an +[EventEmitter][] with the following events: + +### Event: 'close' + +`function () { }` + +Indicates that the underlaying connection was terminated before +`response.end()` was called or able to flush. + +### response.writeContinue() + +Sends a HTTP/1.1 100 Continue message to the client, indicating that +the request body should be sent. See the ['checkContinue'][] event on `Server`. + +### response.writeHead(statusCode, [reasonPhrase], [headers]) + +Sends a response header to the request. The status code is a 3-digit HTTP +status code, like `404`. The last argument, `headers`, are the response headers. +Optionally one can give a human-readable `reasonPhrase` as the second +argument. + +Example: + + var body = 'hello world'; + response.writeHead(200, { + 'Content-Length': body.length, + 'Content-Type': 'text/plain' }); + +This method must only be called once on a message and it must +be called before `response.end()` is called. + +If you call `response.write()` or `response.end()` before calling this, the +implicit/mutable headers will be calculated and call this function for you. + +Note: that Content-Length is given in bytes not characters. The above example +works because the string `'hello world'` contains only single byte characters. +If the body contains higher coded characters then `Buffer.byteLength()` +should be used to determine the number of bytes in a given encoding. +And Node does not check whether Content-Length and the length of the body +which has been transmitted are equal or not. + +### response.statusCode + +When using implicit headers (not calling `response.writeHead()` explicitly), this property +controls the status code that will be sent to the client when the headers get +flushed. + +Example: + + response.statusCode = 404; + +After response header was sent to the client, this property indicates the +status code which was sent out. + +### response.setHeader(name, value) + +Sets a single header value for implicit headers. If this header already exists +in the to-be-sent headers, its value will be replaced. Use an array of strings +here if you need to send multiple headers with the same name. + +Example: + + response.setHeader("Content-Type", "text/html"); + +or + + response.setHeader("Set-Cookie", ["type=ninja", "language=javascript"]); + +### response.sendDate + +When true, the Date header will be automatically generated and sent in +the response if it is not already present in the headers. Defaults to true. + +This should only be disabled for testing; HTTP requires the Date header +in responses. + +### response.getHeader(name) + +Reads out a header that's already been queued but not sent to the client. Note +that the name is case insensitive. This can only be called before headers get +implicitly flushed. + +Example: + + var contentType = response.getHeader('content-type'); + +### response.removeHeader(name) + +Removes a header that's queued for implicit sending. + +Example: + + response.removeHeader("Content-Encoding"); + + +### response.write(chunk, [encoding]) + +If this method is called and `response.writeHead()` has not been called, it will +switch to implicit header mode and flush the implicit headers. + +This sends a chunk of the response body. This method may +be called multiple times to provide successive parts of the body. + +`chunk` can be a string or a buffer. If `chunk` is a string, +the second parameter specifies how to encode it into a byte stream. +By default the `encoding` is `'utf8'`. + +**Note**: This is the raw HTTP body and has nothing to do with +higher-level multi-part body encodings that may be used. + +The first time `response.write()` is called, it will send the buffered +header information and the first body to the client. The second time +`response.write()` is called, Node assumes you're going to be streaming +data, and sends that separately. That is, the response is buffered up to the +first chunk of body. + +Returns `true` if the entire data was flushed successfully to the kernel +buffer. Returns `false` if all or part of the data was queued in user memory. +`'drain'` will be emitted when the buffer is again free. + +### response.addTrailers(headers) + +This method adds HTTP trailing headers (a header but at the end of the +message) to the response. + +Trailers will **only** be emitted if chunked encoding is used for the +response; if it is not (e.g., if the request was HTTP/1.0), they will +be silently discarded. + +Note that HTTP requires the `Trailer` header to be sent if you intend to +emit trailers, with a list of the header fields in its value. E.g., + + response.writeHead(200, { 'Content-Type': 'text/plain', + 'Trailer': 'Content-MD5' }); + response.write(fileData); + response.addTrailers({'Content-MD5': "7895bf4b8828b55ceaf47747b4bca667"}); + response.end(); + + +### response.end([data], [encoding]) + +This method signals to the server that all of the response headers and body +have been sent; that server should consider this message complete. +The method, `response.end()`, MUST be called on each +response. + +If `data` is specified, it is equivalent to calling `response.write(data, encoding)` +followed by `response.end()`. + + +## http.request(options, callback) + +Node maintains several connections per server to make HTTP requests. +This function allows one to transparently issue requests. + +`options` can be an object or a string. If `options` is a string, it is +automatically parsed with [url.parse()][]. + +Options: + +- `host`: A domain name or IP address of the server to issue the request to. + Defaults to `'localhost'`. +- `hostname`: To support `url.parse()` `hostname` is preferred over `host` +- `port`: Port of remote server. Defaults to 80. +- `localAddress`: Local interface to bind for network connections. +- `socketPath`: Unix Domain Socket (use one of host:port or socketPath) +- `method`: A string specifying the HTTP request method. Defaults to `'GET'`. +- `path`: Request path. Defaults to `'/'`. Should include query string if any. + E.G. `'/index.html?page=12'` +- `headers`: An object containing request headers. +- `auth`: Basic authentication i.e. `'user:password'` to compute an + Authorization header. +- `agent`: Controls [Agent][] behavior. When an Agent is used request will + default to `Connection: keep-alive`. Possible values: + - `undefined` (default): use [global Agent][] for this host and port. + - `Agent` object: explicitly use the passed in `Agent`. + - `false`: opts out of connection pooling with an Agent, defaults request to + `Connection: close`. + +`http.request()` returns an instance of the `http.ClientRequest` +class. The `ClientRequest` instance is a writable stream. If one needs to +upload a file with a POST request, then write to the `ClientRequest` object. + +Example: + + var options = { + host: 'www.google.com', + port: 80, + path: '/upload', + method: 'POST' + }; + + var req = http.request(options, function(res) { + console.log('STATUS: ' + res.statusCode); + console.log('HEADERS: ' + JSON.stringify(res.headers)); + res.setEncoding('utf8'); + res.on('data', function (chunk) { + console.log('BODY: ' + chunk); + }); + }); + + req.on('error', function(e) { + console.log('problem with request: ' + e.message); + }); + + // write data to request body + req.write('data\n'); + req.write('data\n'); + req.end(); + +Note that in the example `req.end()` was called. With `http.request()` one +must always call `req.end()` to signify that you're done with the request - +even if there is no data being written to the request body. + +If any error is encountered during the request (be that with DNS resolution, +TCP level errors, or actual HTTP parse errors) an `'error'` event is emitted +on the returned request object. + +There are a few special headers that should be noted. + +* Sending a 'Connection: keep-alive' will notify Node that the connection to + the server should be persisted until the next request. + +* Sending a 'Content-length' header will disable the default chunked encoding. + +* Sending an 'Expect' header will immediately send the request headers. + Usually, when sending 'Expect: 100-continue', you should both set a timeout + and listen for the `continue` event. See RFC2616 Section 8.2.3 for more + information. + +* Sending an Authorization header will override using the `auth` option + to compute basic authentication. + +## http.get(options, callback) + +Since most requests are GET requests without bodies, Node provides this +convenience method. The only difference between this method and `http.request()` +is that it sets the method to GET and calls `req.end()` automatically. + +Example: + + http.get("http://www.google.com/index.html", function(res) { + console.log("Got response: " + res.statusCode); + }).on('error', function(e) { + console.log("Got error: " + e.message); + }); + + +## Class: http.Agent + +In node 0.5.3+ there is a new implementation of the HTTP Agent which is used +for pooling sockets used in HTTP client requests. + +Previously, a single agent instance helped pool for a single host+port. The +current implementation now holds sockets for any number of hosts. + +The current HTTP Agent also defaults client requests to using +Connection:keep-alive. If no pending HTTP requests are waiting on a socket +to become free the socket is closed. This means that node's pool has the +benefit of keep-alive when under load but still does not require developers +to manually close the HTTP clients using keep-alive. + +Sockets are removed from the agent's pool when the socket emits either a +"close" event or a special "agentRemove" event. This means that if you intend +to keep one HTTP request open for a long time and don't want it to stay in the +pool you can do something along the lines of: + + http.get(options, function(res) { + // Do stuff + }).on("socket", function (socket) { + socket.emit("agentRemove"); + }); + +Alternatively, you could just opt out of pooling entirely using `agent:false`: + + http.get({host:'localhost', port:80, path:'/', agent:false}, function (res) { + // Do stuff + }) + +### agent.maxSockets + +By default set to 5. Determines how many concurrent sockets the agent can have +open per host. + +### agent.sockets + +An object which contains arrays of sockets currently in use by the Agent. Do not +modify. + +### agent.requests + +An object which contains queues of requests that have not yet been assigned to +sockets. Do not modify. + +## http.globalAgent + +Global instance of Agent which is used as the default for all http client +requests. + + +## Class: http.ClientRequest + +This object is created internally and returned from `http.request()`. It +represents an _in-progress_ request whose header has already been queued. The +header is still mutable using the `setHeader(name, value)`, `getHeader(name)`, +`removeHeader(name)` API. The actual header will be sent along with the first +data chunk or when closing the connection. + +To get the response, add a listener for `'response'` to the request object. +`'response'` will be emitted from the request object when the response +headers have been received. The `'response'` event is executed with one +argument which is an instance of `http.ClientResponse`. + +During the `'response'` event, one can add listeners to the +response object; particularly to listen for the `'data'` event. Note that +the `'response'` event is called before any part of the response body is received, +so there is no need to worry about racing to catch the first part of the +body. As long as a listener for `'data'` is added during the `'response'` +event, the entire body will be caught. + + + // Good + request.on('response', function (response) { + response.on('data', function (chunk) { + console.log('BODY: ' + chunk); + }); + }); + + // Bad - misses all or part of the body + request.on('response', function (response) { + setTimeout(function () { + response.on('data', function (chunk) { + console.log('BODY: ' + chunk); + }); + }, 10); + }); + +Note: Node does not check whether Content-Length and the length of the body +which has been transmitted are equal or not. + +The request implements the [Writable Stream][] interface. This is an +[EventEmitter][] with the following events: + +### Event 'response' + +`function (response) { }` + +Emitted when a response is received to this request. This event is emitted only +once. The `response` argument will be an instance of `http.ClientResponse`. + +Options: + +- `host`: A domain name or IP address of the server to issue the request to. +- `port`: Port of remote server. +- `socketPath`: Unix Domain Socket (use one of host:port or socketPath) + +### Event: 'socket' + +`function (socket) { }` + +Emitted after a socket is assigned to this request. + +### Event: 'connect' + +`function (response, socket, head) { }` + +Emitted each time a server responds to a request with a CONNECT method. If this +event isn't being listened for, clients receiving a CONNECT method will have +their connections closed. + +A client server pair that show you how to listen for the `connect` event. + + var http = require('http'); + var net = require('net'); + var url = require('url'); + + // Create an HTTP tunneling proxy + var proxy = http.createServer(function (req, res) { + res.writeHead(200, {'Content-Type': 'text/plain'}); + res.end('okay'); + }); + proxy.on('connect', function(req, cltSocket, head) { + // connect to an origin server + var srvUrl = url.parse('http://' + req.url); + var srvSocket = net.connect(srvUrl.port, srvUrl.hostname, function() { + cltSocket.write('HTTP/1.1 200 Connection Established\r\n' + + 'Proxy-agent: Node-Proxy\r\n' + + '\r\n'); + srvSocket.write(head); + srvSocket.pipe(cltSocket); + cltSocket.pipe(srvSocket); + }); + }); + + // now that proxy is running + proxy.listen(1337, '127.0.0.1', function() { + + // make a request to a tunneling proxy + var options = { + port: 1337, + host: '127.0.0.1', + method: 'CONNECT', + path: 'www.google.com:80' + }; + + var req = http.request(options); + req.end(); + + req.on('connect', function(res, socket, head) { + console.log('got connected!'); + + // make a request over an HTTP tunnel + socket.write('GET / HTTP/1.1\r\n' + + 'Host: www.google.com:80\r\n' + + 'Connection: close\r\n' + + '\r\n'); + socket.on('data', function(chunk) { + console.log(chunk.toString()); + }); + socket.on('end', function() { + proxy.close(); + }); + }); + }); + +### Event: 'upgrade' + +`function (response, socket, head) { }` + +Emitted each time a server responds to a request with an upgrade. If this +event isn't being listened for, clients receiving an upgrade header will have +their connections closed. + +A client server pair that show you how to listen for the `upgrade` event. + + var http = require('http'); + + // Create an HTTP server + var srv = http.createServer(function (req, res) { + res.writeHead(200, {'Content-Type': 'text/plain'}); + res.end('okay'); + }); + srv.on('upgrade', function(req, socket, head) { + socket.write('HTTP/1.1 101 Web Socket Protocol Handshake\r\n' + + 'Upgrade: WebSocket\r\n' + + 'Connection: Upgrade\r\n' + + '\r\n'); + + socket.pipe(socket); // echo back + }); + + // now that server is running + srv.listen(1337, '127.0.0.1', function() { + + // make a request + var options = { + port: 1337, + host: '127.0.0.1', + headers: { + 'Connection': 'Upgrade', + 'Upgrade': 'websocket' + } + }; + + var req = http.request(options); + req.end(); + + req.on('upgrade', function(res, socket, upgradeHead) { + console.log('got upgraded!'); + socket.end(); + process.exit(0); + }); + }); + +### Event: 'continue' + +`function () { }` + +Emitted when the server sends a '100 Continue' HTTP response, usually because +the request contained 'Expect: 100-continue'. This is an instruction that +the client should send the request body. + +### request.write(chunk, [encoding]) + +Sends a chunk of the body. By calling this method +many times, the user can stream a request body to a +server--in that case it is suggested to use the +`['Transfer-Encoding', 'chunked']` header line when +creating the request. + +The `chunk` argument should be a [Buffer][] or a string. + +The `encoding` argument is optional and only applies when `chunk` is a string. +Defaults to `'utf8'`. + + +### request.end([data], [encoding]) + +Finishes sending the request. If any parts of the body are +unsent, it will flush them to the stream. If the request is +chunked, this will send the terminating `'0\r\n\r\n'`. + +If `data` is specified, it is equivalent to calling +`request.write(data, encoding)` followed by `request.end()`. + +### request.abort() + +Aborts a request. (New since v0.3.8.) + +### request.setTimeout(timeout, [callback]) + +Once a socket is assigned to this request and is connected +[socket.setTimeout()][] will be called. + +### request.setNoDelay([noDelay]) + +Once a socket is assigned to this request and is connected +[socket.setNoDelay()][] will be called. + +### request.setSocketKeepAlive([enable], [initialDelay]) + +Once a socket is assigned to this request and is connected +[socket.setKeepAlive()][] will be called. + +## http.ClientResponse + +This object is created when making a request with `http.request()`. It is +passed to the `'response'` event of the request object. + +The response implements the [Readable Stream][] interface. This is an +[EventEmitter][] with the following events: + + +### Event: 'data' + +`function (chunk) { }` + +Emitted when a piece of the message body is received. + +Note that the __data will be lost__ if there is no listener when a +`ClientResponse` emits a `'data'` event. + + +### Event: 'end' + +`function () { }` + +Emitted exactly once for each response. After that, no more `'data'` events +will be emitted on the response. + + +### Event: 'close' + +`function () { }` + +Indicates that the underlaying connection was terminated before +`response.end()` was called or able to flush. + +Just like `'end'`, this event occurs only once per response, and no more +`'data'` events will fire afterwards. See [http.ServerResponse][]'s `'close'` +event for more information. + +Note: `'close'` can fire after `'end'`, but not vice versa. + + +### response.statusCode + +The 3-digit HTTP response status code. E.G. `404`. + +### response.httpVersion + +The HTTP version of the connected-to server. Probably either +`'1.1'` or `'1.0'`. +Also `response.httpVersionMajor` is the first integer and +`response.httpVersionMinor` is the second. + +### response.headers + +The response headers object. + +### response.trailers + +The response trailers object. Only populated after the 'end' event. + +### response.setEncoding([encoding]) + +Set the encoding for the response body. See [stream.setEncoding()][] for more +information. + +### response.pause() + +Pauses response from emitting events. Useful to throttle back a download. + +### response.resume() + +Resumes a paused response. + +[Agent]: #http_class_http_agent +['checkContinue']: #http_event_checkcontinue +[Buffer]: buffer.html#buffer_buffer +[EventEmitter]: events.html#events_class_events_eventemitter +[global Agent]: #http_http_globalagent +[http.request()]: #http_http_request_options_callback +[http.ServerRequest]: #http_class_http_serverrequest +['listening']: net.html#net_event_listening +[net.Server.close()]: net.html#net_server_close_callback +[net.Server.listen(path)]: net.html#net_server_listen_path_callback +[net.Server.listen(port)]: net.html#net_server_listen_port_host_backlog_callback +[Readable Stream]: stream.html#stream_readable_stream +[socket.setKeepAlive()]: net.html#net_socket_setkeepalive_enable_initialdelay +[socket.setNoDelay()]: net.html#net_socket_setnodelay_nodelay +[socket.setTimeout()]: net.html#net_socket_settimeout_timeout_callback +[stream.setEncoding()]: stream.html#stream_stream_setencoding_encoding +[url.parse()]: url.html#url_url_parse_urlstr_parsequerystring_slashesdenotehost +[Writable Stream]: stream.html#stream_writable_stream diff --git a/node-v0.8.14/doc/api/https.html b/node-v0.8.14/doc/api/https.html new file mode 100644 index 0000000..cb3b29e --- /dev/null +++ b/node-v0.8.14/doc/api/https.html @@ -0,0 +1,316 @@ + + + + + HTTPS Node.js v0.8.14 Manual & Documentation + + + + + +
+ + + +
+
+ + +
+
+

Node.js v0.8.14 Manual & Documentation

+ +
+
+ + + +
+

HTTPS#

+
Stability: 3 - Stable
+

HTTPS is the HTTP protocol over TLS/SSL. In Node this is implemented as a +separate module. + +

+

Class: https.Server#

+

This class is a subclass of tls.Server and emits events same as +http.Server. See http.Server for more information. + +

+

https.createServer(options, [requestListener])#

+

Returns a new HTTPS web server object. The options is similar to +tls.createServer(). The requestListener is a function which is +automatically added to the 'request' event. + +

+

Example: + +

+
// curl -k https://localhost:8000/
+var https = require('https');
+var fs = require('fs');
+
+var options = {
+  key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'),
+  cert: fs.readFileSync('test/fixtures/keys/agent2-cert.pem')
+};
+
+https.createServer(options, function (req, res) {
+  res.writeHead(200);
+  res.end("hello world\n");
+}).listen(8000);
+

Or + +

+
var https = require('https');
+var fs = require('fs');
+
+var options = {
+  pfx: fs.readFileSync('server.pfx')
+};
+
+https.createServer(options, function (req, res) {
+  res.writeHead(200);
+  res.end("hello world\n");
+}).listen(8000);
+

server.listen(port, [host], [backlog], [callback])#

+

server.listen(path, [callback])#

+

server.listen(handle, [callback])#

+

See http.listen() for details. + +

+

server.close([callback])#

+

See http.close() for details. + +

+

https.request(options, callback)#

+

Makes a request to a secure web server. + +

+

options can be an object or a string. If options is a string, it is +automatically parsed with url.parse(). + +

+

All options from http.request() are valid. + +

+

Example: + +

+
var https = require('https');
+
+var options = {
+  host: 'encrypted.google.com',
+  port: 443,
+  path: '/',
+  method: 'GET'
+};
+
+var req = https.request(options, function(res) {
+  console.log("statusCode: ", res.statusCode);
+  console.log("headers: ", res.headers);
+
+  res.on('data', function(d) {
+    process.stdout.write(d);
+  });
+});
+req.end();
+
+req.on('error', function(e) {
+  console.error(e);
+});
+

The options argument has the following options + +

+
    +
  • host: IP or domain of host to make request to. Defaults to 'localhost'.
  • +
  • port: port of host to request to. Defaults to 443.
  • +
  • path: Path to request. Default '/'.
  • +
  • method: HTTP request method. Default 'GET'.

    +
  • +
  • host: A domain name or IP address of the server to issue the request to. +Defaults to 'localhost'.

    +
  • +
  • hostname: To support url.parse() hostname is preferred over host
  • +
  • port: Port of remote server. Defaults to 443.
  • +
  • method: A string specifying the HTTP request method. Defaults to 'GET'.
  • +
  • path: Request path. Defaults to '/'. Should include query string if any. +E.G. '/index.html?page=12'
  • +
  • headers: An object containing request headers.
  • +
  • auth: Basic authentication i.e. 'user:password' to compute an +Authorization header.
  • +
  • agent: Controls Agent behavior. When an Agent is used request will +default to Connection: keep-alive. Possible values:
      +
    • undefined (default): use globalAgent for this host and port.
    • +
    • Agent object: explicitly use the passed in Agent.
    • +
    • false: opts out of connection pooling with an Agent, defaults request to +Connection: close.
    • +
    +
  • +
+

The following options from tls.connect() can also be specified. However, a +globalAgent silently ignores these. + +

+
    +
  • pfx: Certificate, Private key and CA certificates to use for SSL. Default null.
  • +
  • key: Private key to use for SSL. Default null.
  • +
  • passphrase: A string of passphrase for the private key or pfx. Default null.
  • +
  • cert: Public x509 certificate to use. Default null.
  • +
  • ca: An authority certificate or array of authority certificates to check +the remote host against.
  • +
  • ciphers: A string describing the ciphers to use or exclude. Consult +http://www.openssl.org/docs/apps/ciphers.html#CIPHER_LIST_FORMAT for +details on the format.
  • +
  • rejectUnauthorized: If true, the server certificate is verified against +the list of supplied CAs. An 'error' event is emitted if verification +fails. Verification happens at the connection level, before the HTTP +request is sent. Default false.
  • +
+

In order to specify these options, use a custom Agent. + +

+

Example: + +

+
var options = {
+  host: 'encrypted.google.com',
+  port: 443,
+  path: '/',
+  method: 'GET',
+  key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'),
+  cert: fs.readFileSync('test/fixtures/keys/agent2-cert.pem')
+};
+options.agent = new https.Agent(options);
+
+var req = https.request(options, function(res) {
+  ...
+}
+

Or does not use an Agent. + +

+

Example: + +

+
var options = {
+  host: 'encrypted.google.com',
+  port: 443,
+  path: '/',
+  method: 'GET',
+  key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'),
+  cert: fs.readFileSync('test/fixtures/keys/agent2-cert.pem'),
+  agent: false
+};
+
+var req = https.request(options, function(res) {
+  ...
+}
+

https.get(options, callback)#

+

Like http.get() but for HTTPS. + +

+

options can be an object or a string. If options is a string, it is +automatically parsed with url.parse(). + +

+

Example: + +

+
var https = require('https');
+
+https.get('https://encrypted.google.com/', function(res) {
+  console.log("statusCode: ", res.statusCode);
+  console.log("headers: ", res.headers);
+
+  res.on('data', function(d) {
+    process.stdout.write(d);
+  });
+
+}).on('error', function(e) {
+  console.error(e);
+});
+

Class: https.Agent#

+

An Agent object for HTTPS similar to http.Agent. See [https.request()][] +for more information. + + +

+

https.globalAgent#

+

Global instance of https.Agent for all HTTPS client requests. + +

+ +
+
+
+ + + + + + + + + diff --git a/node-v0.8.14/doc/api/https.json b/node-v0.8.14/doc/api/https.json new file mode 100644 index 0000000..836e054 --- /dev/null +++ b/node-v0.8.14/doc/api/https.json @@ -0,0 +1,159 @@ +{ + "source": "doc/api/https.markdown", + "modules": [ + { + "textRaw": "HTTPS", + "name": "https", + "stability": 3, + "stabilityText": "Stable", + "desc": "

HTTPS is the HTTP protocol over TLS/SSL. In Node this is implemented as a\nseparate module.\n\n

\n", + "classes": [ + { + "textRaw": "Class: https.Server", + "type": "class", + "name": "https.Server", + "desc": "

This class is a subclass of tls.Server and emits events same as\nhttp.Server. See http.Server for more information.\n\n

\n" + }, + { + "textRaw": "Class: https.Agent", + "type": "class", + "name": "https.Agent", + "desc": "

An Agent object for HTTPS similar to [http.Agent][]. See [https.request()][]\nfor more information.\n\n\n

\n" + } + ], + "methods": [ + { + "textRaw": "https.createServer(options, [requestListener])", + "type": "method", + "name": "createServer", + "desc": "

Returns a new HTTPS web server object. The options is similar to\n[tls.createServer()][]. The requestListener is a function which is\nautomatically added to the 'request' event.\n\n

\n

Example:\n\n

\n
// curl -k https://localhost:8000/\nvar https = require('https');\nvar fs = require('fs');\n\nvar options = {\n  key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'),\n  cert: fs.readFileSync('test/fixtures/keys/agent2-cert.pem')\n};\n\nhttps.createServer(options, function (req, res) {\n  res.writeHead(200);\n  res.end("hello world\\n");\n}).listen(8000);
\n

Or\n\n

\n
var https = require('https');\nvar fs = require('fs');\n\nvar options = {\n  pfx: fs.readFileSync('server.pfx')\n};\n\nhttps.createServer(options, function (req, res) {\n  res.writeHead(200);\n  res.end("hello world\\n");\n}).listen(8000);
\n", + "methods": [ + { + "textRaw": "server.listen(path, [callback])", + "type": "method", + "name": "listen", + "desc": "

See [http.listen()][] for details.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "handle" + }, + { + "name": "callback", + "optional": true + } + ] + }, + { + "params": [ + { + "name": "path" + }, + { + "name": "callback", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "server.listen(handle, [callback])", + "type": "method", + "name": "listen", + "desc": "

See [http.listen()][] for details.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "handle" + }, + { + "name": "callback", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "server.close([callback])", + "type": "method", + "name": "close", + "desc": "

See [http.close()][] for details.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "callback", + "optional": true + } + ] + } + ] + } + ], + "signatures": [ + { + "params": [ + { + "name": "options" + }, + { + "name": "requestListener", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "https.request(options, callback)", + "type": "method", + "name": "request", + "desc": "

Makes a request to a secure web server.\n\n

\n

options can be an object or a string. If options is a string, it is\nautomatically parsed with url.parse().\n\n

\n

All options from [http.request()][] are valid.\n\n

\n

Example:\n\n

\n
var https = require('https');\n\nvar options = {\n  host: 'encrypted.google.com',\n  port: 443,\n  path: '/',\n  method: 'GET'\n};\n\nvar req = https.request(options, function(res) {\n  console.log("statusCode: ", res.statusCode);\n  console.log("headers: ", res.headers);\n\n  res.on('data', function(d) {\n    process.stdout.write(d);\n  });\n});\nreq.end();\n\nreq.on('error', function(e) {\n  console.error(e);\n});
\n

The options argument has the following options\n\n

\n
    \n
  • host: IP or domain of host to make request to. Defaults to 'localhost'.
  • \n
  • port: port of host to request to. Defaults to 443.
  • \n
  • path: Path to request. Default '/'.
  • \n
  • method: HTTP request method. Default 'GET'.

    \n
  • \n
  • host: A domain name or IP address of the server to issue the request to.\nDefaults to 'localhost'.

    \n
  • \n
  • hostname: To support url.parse() hostname is preferred over host
  • \n
  • port: Port of remote server. Defaults to 443.
  • \n
  • method: A string specifying the HTTP request method. Defaults to 'GET'.
  • \n
  • path: Request path. Defaults to '/'. Should include query string if any.\nE.G. '/index.html?page=12'
  • \n
  • headers: An object containing request headers.
  • \n
  • auth: Basic authentication i.e. 'user:password' to compute an\nAuthorization header.
  • \n
  • agent: Controls [Agent][] behavior. When an Agent is used request will\ndefault to Connection: keep-alive. Possible values:
      \n
    • undefined (default): use [globalAgent][] for this host and port.
    • \n
    • Agent object: explicitly use the passed in Agent.
    • \n
    • false: opts out of connection pooling with an Agent, defaults request to\nConnection: close.
    • \n
    \n
  • \n
\n

The following options from [tls.connect()][] can also be specified. However, a\n[globalAgent][] silently ignores these.\n\n

\n
    \n
  • pfx: Certificate, Private key and CA certificates to use for SSL. Default null.
  • \n
  • key: Private key to use for SSL. Default null.
  • \n
  • passphrase: A string of passphrase for the private key or pfx. Default null.
  • \n
  • cert: Public x509 certificate to use. Default null.
  • \n
  • ca: An authority certificate or array of authority certificates to check\nthe remote host against.
  • \n
  • ciphers: A string describing the ciphers to use or exclude. Consult\nhttp://www.openssl.org/docs/apps/ciphers.html#CIPHER_LIST_FORMAT for\ndetails on the format.
  • \n
  • rejectUnauthorized: If true, the server certificate is verified against\nthe list of supplied CAs. An 'error' event is emitted if verification\nfails. Verification happens at the connection level, before the HTTP\nrequest is sent. Default false.
  • \n
\n

In order to specify these options, use a custom Agent.\n\n

\n

Example:\n\n

\n
var options = {\n  host: 'encrypted.google.com',\n  port: 443,\n  path: '/',\n  method: 'GET',\n  key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'),\n  cert: fs.readFileSync('test/fixtures/keys/agent2-cert.pem')\n};\noptions.agent = new https.Agent(options);\n\nvar req = https.request(options, function(res) {\n  ...\n}
\n

Or does not use an Agent.\n\n

\n

Example:\n\n

\n
var options = {\n  host: 'encrypted.google.com',\n  port: 443,\n  path: '/',\n  method: 'GET',\n  key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'),\n  cert: fs.readFileSync('test/fixtures/keys/agent2-cert.pem'),\n  agent: false\n};\n\nvar req = https.request(options, function(res) {\n  ...\n}
\n", + "signatures": [ + { + "params": [ + { + "name": "options" + }, + { + "name": "callback" + } + ] + } + ] + }, + { + "textRaw": "https.get(options, callback)", + "type": "method", + "name": "get", + "desc": "

Like http.get() but for HTTPS.\n\n

\n

options can be an object or a string. If options is a string, it is\nautomatically parsed with url.parse().\n\n

\n

Example:\n\n

\n
var https = require('https');\n\nhttps.get('https://encrypted.google.com/', function(res) {\n  console.log("statusCode: ", res.statusCode);\n  console.log("headers: ", res.headers);\n\n  res.on('data', function(d) {\n    process.stdout.write(d);\n  });\n\n}).on('error', function(e) {\n  console.error(e);\n});
\n", + "signatures": [ + { + "params": [ + { + "name": "options" + }, + { + "name": "callback" + } + ] + } + ] + } + ], + "properties": [ + { + "textRaw": "https.globalAgent", + "name": "globalAgent", + "desc": "

Global instance of [https.Agent][] for all HTTPS client requests.\n\n

\n" + } + ], + "type": "module", + "displayName": "HTTPS" + } + ] +} diff --git a/node-v0.8.14/doc/api/https.markdown b/node-v0.8.14/doc/api/https.markdown new file mode 100644 index 0000000..f91948e --- /dev/null +++ b/node-v0.8.14/doc/api/https.markdown @@ -0,0 +1,213 @@ +# HTTPS + + Stability: 3 - Stable + +HTTPS is the HTTP protocol over TLS/SSL. In Node this is implemented as a +separate module. + +## Class: https.Server + +This class is a subclass of `tls.Server` and emits events same as +`http.Server`. See `http.Server` for more information. + +## https.createServer(options, [requestListener]) + +Returns a new HTTPS web server object. The `options` is similar to +[tls.createServer()][]. The `requestListener` is a function which is +automatically added to the `'request'` event. + +Example: + + // curl -k https://localhost:8000/ + var https = require('https'); + var fs = require('fs'); + + var options = { + key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'), + cert: fs.readFileSync('test/fixtures/keys/agent2-cert.pem') + }; + + https.createServer(options, function (req, res) { + res.writeHead(200); + res.end("hello world\n"); + }).listen(8000); + +Or + + var https = require('https'); + var fs = require('fs'); + + var options = { + pfx: fs.readFileSync('server.pfx') + }; + + https.createServer(options, function (req, res) { + res.writeHead(200); + res.end("hello world\n"); + }).listen(8000); + + +### server.listen(port, [host], [backlog], [callback]) +### server.listen(path, [callback]) +### server.listen(handle, [callback]) + +See [http.listen()][] for details. + +### server.close([callback]) + +See [http.close()][] for details. + +## https.request(options, callback) + +Makes a request to a secure web server. + +`options` can be an object or a string. If `options` is a string, it is +automatically parsed with [url.parse()](url.html#url.parse). + +All options from [http.request()][] are valid. + +Example: + + var https = require('https'); + + var options = { + host: 'encrypted.google.com', + port: 443, + path: '/', + method: 'GET' + }; + + var req = https.request(options, function(res) { + console.log("statusCode: ", res.statusCode); + console.log("headers: ", res.headers); + + res.on('data', function(d) { + process.stdout.write(d); + }); + }); + req.end(); + + req.on('error', function(e) { + console.error(e); + }); + +The options argument has the following options + +- host: IP or domain of host to make request to. Defaults to `'localhost'`. +- port: port of host to request to. Defaults to 443. +- path: Path to request. Default `'/'`. +- method: HTTP request method. Default `'GET'`. + +- `host`: A domain name or IP address of the server to issue the request to. + Defaults to `'localhost'`. +- `hostname`: To support `url.parse()` `hostname` is preferred over `host` +- `port`: Port of remote server. Defaults to 443. +- `method`: A string specifying the HTTP request method. Defaults to `'GET'`. +- `path`: Request path. Defaults to `'/'`. Should include query string if any. + E.G. `'/index.html?page=12'` +- `headers`: An object containing request headers. +- `auth`: Basic authentication i.e. `'user:password'` to compute an + Authorization header. +- `agent`: Controls [Agent][] behavior. When an Agent is used request will + default to `Connection: keep-alive`. Possible values: + - `undefined` (default): use [globalAgent][] for this host and port. + - `Agent` object: explicitly use the passed in `Agent`. + - `false`: opts out of connection pooling with an Agent, defaults request to + `Connection: close`. + +The following options from [tls.connect()][] can also be specified. However, a +[globalAgent][] silently ignores these. + +- `pfx`: Certificate, Private key and CA certificates to use for SSL. Default `null`. +- `key`: Private key to use for SSL. Default `null`. +- `passphrase`: A string of passphrase for the private key or pfx. Default `null`. +- `cert`: Public x509 certificate to use. Default `null`. +- `ca`: An authority certificate or array of authority certificates to check + the remote host against. +- `ciphers`: A string describing the ciphers to use or exclude. Consult + for + details on the format. +- `rejectUnauthorized`: If `true`, the server certificate is verified against + the list of supplied CAs. An `'error'` event is emitted if verification + fails. Verification happens at the connection level, *before* the HTTP + request is sent. Default `false`. + +In order to specify these options, use a custom `Agent`. + +Example: + + var options = { + host: 'encrypted.google.com', + port: 443, + path: '/', + method: 'GET', + key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'), + cert: fs.readFileSync('test/fixtures/keys/agent2-cert.pem') + }; + options.agent = new https.Agent(options); + + var req = https.request(options, function(res) { + ... + } + +Or does not use an `Agent`. + +Example: + + var options = { + host: 'encrypted.google.com', + port: 443, + path: '/', + method: 'GET', + key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'), + cert: fs.readFileSync('test/fixtures/keys/agent2-cert.pem'), + agent: false + }; + + var req = https.request(options, function(res) { + ... + } + +## https.get(options, callback) + +Like `http.get()` but for HTTPS. + +`options` can be an object or a string. If `options` is a string, it is +automatically parsed with [url.parse()](url.html#url.parse). + +Example: + + var https = require('https'); + + https.get('https://encrypted.google.com/', function(res) { + console.log("statusCode: ", res.statusCode); + console.log("headers: ", res.headers); + + res.on('data', function(d) { + process.stdout.write(d); + }); + + }).on('error', function(e) { + console.error(e); + }); + + +## Class: https.Agent + +An Agent object for HTTPS similar to [http.Agent][]. See [https.request()][] +for more information. + + +## https.globalAgent + +Global instance of [https.Agent][] for all HTTPS client requests. + +[Agent]: #https_class_https_agent +[globalAgent]: #https_https_globalagent +[http.listen()]: http.html#http_server_listen_port_hostname_backlog_callback +[http.close()]: http.html#http_server_close_callback +[http.Agent]: http.html#http_class_http_agent +[http.request()]: http.html#http_http_request_options_callback +[https.Agent]: #https_class_https_agent +[tls.connect()]: tls.html#tls_tls_connect_options_secureconnectlistener +[tls.createServer()]: tls.html#tls_tls_createserver_options_secureconnectionlistener diff --git a/node-v0.8.14/doc/api/index.html b/node-v0.8.14/doc/api/index.html new file mode 100644 index 0000000..33722c9 --- /dev/null +++ b/node-v0.8.14/doc/api/index.html @@ -0,0 +1,124 @@ + + + + + Node.js v0.8.14 Manual & Documentation + + + + + +
+ + + +
+ + + + + + + + + + diff --git a/node-v0.8.14/doc/api/index.json b/node-v0.8.14/doc/api/index.json new file mode 100644 index 0000000..19f6a79 --- /dev/null +++ b/node-v0.8.14/doc/api/index.json @@ -0,0 +1,375 @@ +{ + "source": "doc/api/index.markdown", + "desc": [ + { + "type": "list_start", + "ordered": false + }, + { + "type": "list_item_start" + }, + { + "type": "text", + "text": "[About these Docs](documentation.html)" + }, + { + "type": "list_item_end" + }, + { + "type": "list_item_start" + }, + { + "type": "text", + "text": "[Synopsis](synopsis.html)" + }, + { + "type": "list_item_end" + }, + { + "type": "list_item_start" + }, + { + "type": "text", + "text": "[Assertion Testing](assert.html)" + }, + { + "type": "list_item_end" + }, + { + "type": "list_item_start" + }, + { + "type": "text", + "text": "[Buffer](buffer.html)" + }, + { + "type": "list_item_end" + }, + { + "type": "list_item_start" + }, + { + "type": "text", + "text": "[C/C++ Addons](addons.html)" + }, + { + "type": "list_item_end" + }, + { + "type": "list_item_start" + }, + { + "type": "text", + "text": "[Child Processes](child_process.html)" + }, + { + "type": "list_item_end" + }, + { + "type": "list_item_start" + }, + { + "type": "text", + "text": "[Cluster](cluster.html)" + }, + { + "type": "list_item_end" + }, + { + "type": "list_item_start" + }, + { + "type": "text", + "text": "[Crypto](crypto.html)" + }, + { + "type": "list_item_end" + }, + { + "type": "list_item_start" + }, + { + "type": "text", + "text": "[Debugger](debugger.html)" + }, + { + "type": "list_item_end" + }, + { + "type": "list_item_start" + }, + { + "type": "text", + "text": "[DNS](dns.html)" + }, + { + "type": "list_item_end" + }, + { + "type": "list_item_start" + }, + { + "type": "text", + "text": "[Domain](domain.html)" + }, + { + "type": "list_item_end" + }, + { + "type": "list_item_start" + }, + { + "type": "text", + "text": "[Events](events.html)" + }, + { + "type": "list_item_end" + }, + { + "type": "list_item_start" + }, + { + "type": "text", + "text": "[File System](fs.html)" + }, + { + "type": "list_item_end" + }, + { + "type": "list_item_start" + }, + { + "type": "text", + "text": "[Globals](globals.html)" + }, + { + "type": "list_item_end" + }, + { + "type": "list_item_start" + }, + { + "type": "text", + "text": "[HTTP](http.html)" + }, + { + "type": "list_item_end" + }, + { + "type": "list_item_start" + }, + { + "type": "text", + "text": "[HTTPS](https.html)" + }, + { + "type": "list_item_end" + }, + { + "type": "list_item_start" + }, + { + "type": "text", + "text": "[Modules](modules.html)" + }, + { + "type": "list_item_end" + }, + { + "type": "list_item_start" + }, + { + "type": "text", + "text": "[Net](net.html)" + }, + { + "type": "list_item_end" + }, + { + "type": "list_item_start" + }, + { + "type": "text", + "text": "[OS](os.html)" + }, + { + "type": "list_item_end" + }, + { + "type": "list_item_start" + }, + { + "type": "text", + "text": "[Path](path.html)" + }, + { + "type": "list_item_end" + }, + { + "type": "list_item_start" + }, + { + "type": "text", + "text": "[Process](process.html)" + }, + { + "type": "list_item_end" + }, + { + "type": "list_item_start" + }, + { + "type": "text", + "text": "[Punycode](punycode.html)" + }, + { + "type": "list_item_end" + }, + { + "type": "list_item_start" + }, + { + "type": "text", + "text": "[Query Strings](querystring.html)" + }, + { + "type": "list_item_end" + }, + { + "type": "list_item_start" + }, + { + "type": "text", + "text": "[Readline](readline.html)" + }, + { + "type": "list_item_end" + }, + { + "type": "list_item_start" + }, + { + "type": "text", + "text": "[REPL](repl.html)" + }, + { + "type": "list_item_end" + }, + { + "type": "list_item_start" + }, + { + "type": "text", + "text": "[STDIO](stdio.html)" + }, + { + "type": "list_item_end" + }, + { + "type": "list_item_start" + }, + { + "type": "text", + "text": "[Stream](stream.html)" + }, + { + "type": "list_item_end" + }, + { + "type": "list_item_start" + }, + { + "type": "text", + "text": "[String Decoder](string_decoder.html)" + }, + { + "type": "list_item_end" + }, + { + "type": "list_item_start" + }, + { + "type": "text", + "text": "[Timers](timers.html)" + }, + { + "type": "list_item_end" + }, + { + "type": "list_item_start" + }, + { + "type": "text", + "text": "[TLS/SSL](tls.html)" + }, + { + "type": "list_item_end" + }, + { + "type": "list_item_start" + }, + { + "type": "text", + "text": "[TTY](tty.html)" + }, + { + "type": "list_item_end" + }, + { + "type": "list_item_start" + }, + { + "type": "text", + "text": "[UDP/Datagram](dgram.html)" + }, + { + "type": "list_item_end" + }, + { + "type": "list_item_start" + }, + { + "type": "text", + "text": "[URL](url.html)" + }, + { + "type": "list_item_end" + }, + { + "type": "list_item_start" + }, + { + "type": "text", + "text": "[Utilities](util.html)" + }, + { + "type": "list_item_end" + }, + { + "type": "list_item_start" + }, + { + "type": "text", + "text": "[VM](vm.html)" + }, + { + "type": "list_item_end" + }, + { + "type": "list_item_start" + }, + { + "type": "text", + "text": "[ZLIB](zlib.html)" + }, + { + "type": "space" + }, + { + "type": "list_item_end" + }, + { + "type": "list_end" + } + ] +} diff --git a/node-v0.8.14/doc/api/index.markdown b/node-v0.8.14/doc/api/index.markdown new file mode 100644 index 0000000..1a77450 --- /dev/null +++ b/node-v0.8.14/doc/api/index.markdown @@ -0,0 +1 @@ +@include _toc.markdown diff --git a/node-v0.8.14/doc/api/modules.html b/node-v0.8.14/doc/api/modules.html new file mode 100644 index 0000000..1e679c2 --- /dev/null +++ b/node-v0.8.14/doc/api/modules.html @@ -0,0 +1,618 @@ + + + + + Modules Node.js v0.8.14 Manual & Documentation + + + + + +
+ + + +
+
+ + +
+
+

Node.js v0.8.14 Manual & Documentation

+ +
+
+ + + +
+

Modules#

+
Stability: 5 - Locked
+ + +

Node has a simple module loading system. In Node, files and modules are in +one-to-one correspondence. As an example, foo.js loads the module +circle.js in the same directory. + +

+

The contents of foo.js: + +

+
var circle = require('./circle.js');
+console.log( 'The area of a circle of radius 4 is '
+           + circle.area(4));
+

The contents of circle.js: + +

+
var PI = Math.PI;
+
+exports.area = function (r) {
+  return PI * r * r;
+};
+
+exports.circumference = function (r) {
+  return 2 * PI * r;
+};
+

The module circle.js has exported the functions area() and +circumference(). To export an object, add to the special exports +object. + +

+

Variables +local to the module will be private. In this example the variable PI is +private to circle.js. + +

+

The module system is implemented in the require("module") module. + +

+

Cycles#

+ + +

When there are circular require() calls, a module might not be +done being executed when it is returned. + +

+

Consider this situation: + +

+

a.js: + +

+
console.log('a starting');
+exports.done = false;
+var b = require('./b.js');
+console.log('in a, b.done = %j', b.done);
+exports.done = true;
+console.log('a done');
+

b.js: + +

+
console.log('b starting');
+exports.done = false;
+var a = require('./a.js');
+console.log('in b, a.done = %j', a.done);
+exports.done = true;
+console.log('b done');
+

main.js: + +

+
console.log('main starting');
+var a = require('./a.js');
+var b = require('./b.js');
+console.log('in main, a.done=%j, b.done=%j', a.done, b.done);
+

When main.js loads a.js, then a.js in turn loads b.js. At that +point, b.js tries to load a.js. In order to prevent an infinite +loop an unfinished copy of the a.js exports object is returned to the +b.js module. b.js then finishes loading, and its exports object is +provided to the a.js module. + +

+

By the time main.js has loaded both modules, they're both finished. +The output of this program would thus be: + +

+
$ node main.js
+main starting
+a starting
+b starting
+in b, a.done = false
+b done
+in a, b.done = true
+a done
+in main, a.done=true, b.done=true
+

If you have cyclic module dependencies in your program, make sure to +plan accordingly. + +

+

Core Modules#

+ + +

Node has several modules compiled into the binary. These modules are +described in greater detail elsewhere in this documentation. + +

+

The core modules are defined in node's source in the lib/ folder. + +

+

Core modules are always preferentially loaded if their identifier is +passed to require(). For instance, require('http') will always +return the built in HTTP module, even if there is a file by that name. + +

+

File Modules#

+ + +

If the exact filename is not found, then node will attempt to load the +required filename with the added extension of .js, .json, and then .node. + +

+

.js files are interpreted as JavaScript text files, and .json files are +parsed as JSON text files. .node files are interpreted as compiled addon +modules loaded with dlopen. + +

+

A module prefixed with '/' is an absolute path to the file. For +example, require('/home/marco/foo.js') will load the file at +/home/marco/foo.js. + +

+

A module prefixed with './' is relative to the file calling require(). +That is, circle.js must be in the same directory as foo.js for +require('./circle') to find it. + +

+

Without a leading '/' or './' to indicate a file, the module is either a +"core module" or is loaded from a node_modules folder. + +

+

If the given path does not exist, require() will throw an Error with its +code property set to 'MODULE_NOT_FOUND'. + +

+

Loading from node_modules Folders#

+ + +

If the module identifier passed to require() is not a native module, +and does not begin with '/', '../', or './', then node starts at the +parent directory of the current module, and adds /node_modules, and +attempts to load the module from that location. + +

+

If it is not found there, then it moves to the parent directory, and so +on, until the root of the tree is reached. + +

+

For example, if the file at '/home/ry/projects/foo.js' called +require('bar.js'), then node would look in the following locations, in +this order: + +

+
    +
  • /home/ry/projects/node_modules/bar.js
  • +
  • /home/ry/node_modules/bar.js
  • +
  • /home/node_modules/bar.js
  • +
  • /node_modules/bar.js
  • +
+

This allows programs to localize their dependencies, so that they do not +clash. + +

+

Folders as Modules#

+ + +

It is convenient to organize programs and libraries into self-contained +directories, and then provide a single entry point to that library. +There are three ways in which a folder may be passed to require() as +an argument. + +

+

The first is to create a package.json file in the root of the folder, +which specifies a main module. An example package.json file might +look like this: + +

+
{ "name" : "some-library",
+  "main" : "./lib/some-library.js" }
+

If this was in a folder at ./some-library, then +require('./some-library') would attempt to load +./some-library/lib/some-library.js. + +

+

This is the extent of Node's awareness of package.json files. + +

+

If there is no package.json file present in the directory, then node +will attempt to load an index.js or index.node file out of that +directory. For example, if there was no package.json file in the above +example, then require('./some-library') would attempt to load: + +

+
    +
  • ./some-library/index.js
  • +
  • ./some-library/index.node
  • +
+

Caching#

+ + +

Modules are cached after the first time they are loaded. This means +(among other things) that every call to require('foo') will get +exactly the same object returned, if it would resolve to the same file. + +

+

Multiple calls to require('foo') may not cause the module code to be +executed multiple times. This is an important feature. With it, +"partially done" objects can be returned, thus allowing transitive +dependencies to be loaded even when they would cause cycles. + +

+

If you want to have a module execute code multiple times, then export a +function, and call that function. + +

+

Module Caching Caveats#

+ + +

Modules are cached based on their resolved filename. Since modules may +resolve to a different filename based on the location of the calling +module (loading from node_modules folders), it is not a guarantee +that require('foo') will always return the exact same object, if it +would resolve to different files. + +

+

The module Object#

+ + + +
    +
  • {Object}
  • +
+

In each module, the module free variable is a reference to the object +representing the current module. In particular +module.exports is the same as the exports object. +module isn't actually a global but rather local to each module. + +

+

module.exports#

+
    +
  • Object
  • +
+

The exports object is created by the Module system. Sometimes this is not +acceptable, many want their module to be an instance of some class. To do this +assign the desired export object to module.exports. For example suppose we +were making a module called a.js + +

+
var EventEmitter = require('events').EventEmitter;
+
+module.exports = new EventEmitter();
+
+// Do some work, and after some time emit
+// the 'ready' event from the module itself.
+setTimeout(function() {
+  module.exports.emit('ready');
+}, 1000);
+

Then in another file we could do + +

+
var a = require('./a');
+a.on('ready', function() {
+  console.log('module a is ready');
+});
+

Note that assignment to module.exports must be done immediately. It cannot be +done in any callbacks. This does not work: + +

+

x.js: + +

+
setTimeout(function() {
+  module.exports = { a: "hello" };
+}, 0);
+

y.js: + +

+
var x = require('./x');
+console.log(x.a);
+

module.require(id)#

+
    +
  • id String
  • +
  • Return: Object exports from the resolved module
  • +
+

The module.require method provides a way to load a module as if +require() was called from the original module. + +

+

Note that in order to do this, you must get a reference to the module +object. Since require() returns the exports, and the module is +typically only available within a specific module's code, it must be +explicitly exported in order to be used. + + +

+

module.id#

+
    +
  • String
  • +
+

The identifier for the module. Typically this is the fully resolved +filename. + + +

+

module.filename#

+
    +
  • String
  • +
+

The fully resolved filename to the module. + + +

+

module.loaded#

+
    +
  • Boolean
  • +
+

Whether or not the module is done loading, or is in the process of +loading. + + +

+

module.parent#

+
    +
  • Module Object
  • +
+

The module that required this one. + + +

+

module.children#

+
    +
  • Array
  • +
+

The module objects required by this one. + + + +

+

All Together...#

+ + +

To get the exact filename that will be loaded when require() is called, use +the require.resolve() function. + +

+

Putting together all of the above, here is the high-level algorithm +in pseudocode of what require.resolve does: + +

+
require(X) from module at path Y
+1. If X is a core module,
+   a. return the core module
+   b. STOP
+2. If X begins with './' or '/' or '../'
+   a. LOAD_AS_FILE(Y + X)
+   b. LOAD_AS_DIRECTORY(Y + X)
+3. LOAD_NODE_MODULES(X, dirname(Y))
+4. THROW "not found"
+
+LOAD_AS_FILE(X)
+1. If X is a file, load X as JavaScript text.  STOP
+2. If X.js is a file, load X.js as JavaScript text.  STOP
+3. If X.node is a file, load X.node as binary addon.  STOP
+
+LOAD_AS_DIRECTORY(X)
+1. If X/package.json is a file,
+   a. Parse X/package.json, and look for "main" field.
+   b. let M = X + (json main field)
+   c. LOAD_AS_FILE(M)
+2. If X/index.js is a file, load X/index.js as JavaScript text.  STOP
+3. If X/index.node is a file, load X/index.node as binary addon.  STOP
+
+LOAD_NODE_MODULES(X, START)
+1. let DIRS=NODE_MODULES_PATHS(START)
+2. for each DIR in DIRS:
+   a. LOAD_AS_FILE(DIR/X)
+   b. LOAD_AS_DIRECTORY(DIR/X)
+
+NODE_MODULES_PATHS(START)
+1. let PARTS = path split(START)
+2. let ROOT = index of first instance of "node_modules" in PARTS, or 0
+3. let I = count of PARTS - 1
+4. let DIRS = []
+5. while I > ROOT,
+   a. if PARTS[I] = "node_modules" CONTINUE
+   c. DIR = path join(PARTS[0 .. I] + "node_modules")
+   b. DIRS = DIRS + DIR
+   c. let I = I - 1
+6. return DIRS
+

Loading from the global folders#

+ + +

If the NODE_PATH environment variable is set to a colon-delimited list +of absolute paths, then node will search those paths for modules if they +are not found elsewhere. (Note: On Windows, NODE_PATH is delimited by +semicolons instead of colons.) + +

+

Additionally, node will search in the following locations: + +

+
    +
  • 1: $HOME/.node_modules
  • +
  • 2: $HOME/.node_libraries
  • +
  • 3: $PREFIX/lib/node
  • +
+

Where $HOME is the user's home directory, and $PREFIX is node's +configured node_prefix. + +

+

These are mostly for historic reasons. You are highly encouraged to +place your dependencies locally in node_modules folders. They will be +loaded faster, and more reliably. + +

+

Accessing the main module#

+ + +

When a file is run directly from Node, require.main is set to its +module. That means that you can determine whether a file has been run +directly by testing + +

+
require.main === module
+

For a file foo.js, this will be true if run via node foo.js, but +false if run by require('./foo'). + +

+

Because module provides a filename property (normally equivalent to +__filename), the entry point of the current application can be obtained +by checking require.main.filename. + +

+

Addenda: Package Manager Tips#

+ + +

The semantics of Node's require() function were designed to be general +enough to support a number of sane directory structures. Package manager +programs such as dpkg, rpm, and npm will hopefully find it possible to +build native packages from Node modules without modification. + +

+

Below we give a suggested directory structure that could work: + +

+

Let's say that we wanted to have the folder at +/usr/lib/node/<some-package>/<some-version> hold the contents of a +specific version of a package. + +

+

Packages can depend on one another. In order to install package foo, you +may have to install a specific version of package bar. The bar package +may itself have dependencies, and in some cases, these dependencies may even +collide or form cycles. + +

+

Since Node looks up the realpath of any modules it loads (that is, +resolves symlinks), and then looks for their dependencies in the +node_modules folders as described above, this situation is very simple to +resolve with the following architecture: + +

+
    +
  • /usr/lib/node/foo/1.2.3/ - Contents of the foo package, version 1.2.3.
  • +
  • /usr/lib/node/bar/4.3.2/ - Contents of the bar package that foo +depends on.
  • +
  • /usr/lib/node/foo/1.2.3/node_modules/bar - Symbolic link to +/usr/lib/node/bar/4.3.2/.
  • +
  • /usr/lib/node/bar/4.3.2/node_modules/* - Symbolic links to the packages +that bar depends on.
  • +
+

Thus, even if a cycle is encountered, or if there are dependency +conflicts, every module will be able to get a version of its dependency +that it can use. + +

+

When the code in the foo package does require('bar'), it will get the +version that is symlinked into /usr/lib/node/foo/1.2.3/node_modules/bar. +Then, when the code in the bar package calls require('quux'), it'll get +the version that is symlinked into +/usr/lib/node/bar/4.3.2/node_modules/quux. + +

+

Furthermore, to make the module lookup process even more optimal, rather +than putting packages directly in /usr/lib/node, we could put them in +/usr/lib/node_modules/<name>/<version>. Then node will not bother +looking for missing dependencies in /usr/node_modules or /node_modules. + +

+

In order to make modules available to the node REPL, it might be useful to +also add the /usr/lib/node_modules folder to the $NODE_PATH environment +variable. Since the module lookups using node_modules folders are all +relative, and based on the real path of the files making the calls to +require(), the packages themselves can be anywhere. +

+ +
+
+
+ + + + + + + + + diff --git a/node-v0.8.14/doc/api/modules.json b/node-v0.8.14/doc/api/modules.json new file mode 100644 index 0000000..f279cdd --- /dev/null +++ b/node-v0.8.14/doc/api/modules.json @@ -0,0 +1,156 @@ +{ + "source": "doc/api/modules.markdown", + "modules": [ + { + "textRaw": "Modules", + "name": "module", + "stability": 5, + "stabilityText": "Locked", + "desc": "

Node has a simple module loading system. In Node, files and modules are in\none-to-one correspondence. As an example, foo.js loads the module\ncircle.js in the same directory.\n\n

\n

The contents of foo.js:\n\n

\n
var circle = require('./circle.js');\nconsole.log( 'The area of a circle of radius 4 is '\n           + circle.area(4));
\n

The contents of circle.js:\n\n

\n
var PI = Math.PI;\n\nexports.area = function (r) {\n  return PI * r * r;\n};\n\nexports.circumference = function (r) {\n  return 2 * PI * r;\n};
\n

The module circle.js has exported the functions area() and\ncircumference(). To export an object, add to the special exports\nobject.\n\n

\n

Variables\nlocal to the module will be private. In this example the variable PI is\nprivate to circle.js.\n\n

\n

The module system is implemented in the require("module") module.\n\n

\n", + "miscs": [ + { + "textRaw": "Cycles", + "name": "Cycles", + "type": "misc", + "desc": "

When there are circular require() calls, a module might not be\ndone being executed when it is returned.\n\n

\n

Consider this situation:\n\n

\n

a.js:\n\n

\n
console.log('a starting');\nexports.done = false;\nvar b = require('./b.js');\nconsole.log('in a, b.done = %j', b.done);\nexports.done = true;\nconsole.log('a done');
\n

b.js:\n\n

\n
console.log('b starting');\nexports.done = false;\nvar a = require('./a.js');\nconsole.log('in b, a.done = %j', a.done);\nexports.done = true;\nconsole.log('b done');
\n

main.js:\n\n

\n
console.log('main starting');\nvar a = require('./a.js');\nvar b = require('./b.js');\nconsole.log('in main, a.done=%j, b.done=%j', a.done, b.done);
\n

When main.js loads a.js, then a.js in turn loads b.js. At that\npoint, b.js tries to load a.js. In order to prevent an infinite\nloop an unfinished copy of the a.js exports object is returned to the\nb.js module. b.js then finishes loading, and its exports object is\nprovided to the a.js module.\n\n

\n

By the time main.js has loaded both modules, they're both finished.\nThe output of this program would thus be:\n\n

\n
$ node main.js\nmain starting\na starting\nb starting\nin b, a.done = false\nb done\nin a, b.done = true\na done\nin main, a.done=true, b.done=true
\n

If you have cyclic module dependencies in your program, make sure to\nplan accordingly.\n\n

\n" + }, + { + "textRaw": "Core Modules", + "name": "Core Modules", + "type": "misc", + "desc": "

Node has several modules compiled into the binary. These modules are\ndescribed in greater detail elsewhere in this documentation.\n\n

\n

The core modules are defined in node's source in the lib/ folder.\n\n

\n

Core modules are always preferentially loaded if their identifier is\npassed to require(). For instance, require('http') will always\nreturn the built in HTTP module, even if there is a file by that name.\n\n

\n" + }, + { + "textRaw": "File Modules", + "name": "File Modules", + "type": "misc", + "desc": "

If the exact filename is not found, then node will attempt to load the\nrequired filename with the added extension of .js, .json, and then .node.\n\n

\n

.js files are interpreted as JavaScript text files, and .json files are\nparsed as JSON text files. .node files are interpreted as compiled addon\nmodules loaded with dlopen.\n\n

\n

A module prefixed with '/' is an absolute path to the file. For\nexample, require('/home/marco/foo.js') will load the file at\n/home/marco/foo.js.\n\n

\n

A module prefixed with './' is relative to the file calling require().\nThat is, circle.js must be in the same directory as foo.js for\nrequire('./circle') to find it.\n\n

\n

Without a leading '/' or './' to indicate a file, the module is either a\n"core module" or is loaded from a node_modules folder.\n\n

\n

If the given path does not exist, require() will throw an Error with its\ncode property set to 'MODULE_NOT_FOUND'.\n\n

\n" + }, + { + "textRaw": "Loading from `node_modules` Folders", + "name": "Loading from `node_modules` Folders", + "type": "misc", + "desc": "

If the module identifier passed to require() is not a native module,\nand does not begin with '/', '../', or './', then node starts at the\nparent directory of the current module, and adds /node_modules, and\nattempts to load the module from that location.\n\n

\n

If it is not found there, then it moves to the parent directory, and so\non, until the root of the tree is reached.\n\n

\n

For example, if the file at '/home/ry/projects/foo.js' called\nrequire('bar.js'), then node would look in the following locations, in\nthis order:\n\n

\n
    \n
  • /home/ry/projects/node_modules/bar.js
  • \n
  • /home/ry/node_modules/bar.js
  • \n
  • /home/node_modules/bar.js
  • \n
  • /node_modules/bar.js
  • \n
\n

This allows programs to localize their dependencies, so that they do not\nclash.\n\n

\n" + }, + { + "textRaw": "Folders as Modules", + "name": "Folders as Modules", + "type": "misc", + "desc": "

It is convenient to organize programs and libraries into self-contained\ndirectories, and then provide a single entry point to that library.\nThere are three ways in which a folder may be passed to require() as\nan argument.\n\n

\n

The first is to create a package.json file in the root of the folder,\nwhich specifies a main module. An example package.json file might\nlook like this:\n\n

\n
{ "name" : "some-library",\n  "main" : "./lib/some-library.js" }
\n

If this was in a folder at ./some-library, then\nrequire('./some-library') would attempt to load\n./some-library/lib/some-library.js.\n\n

\n

This is the extent of Node's awareness of package.json files.\n\n

\n

If there is no package.json file present in the directory, then node\nwill attempt to load an index.js or index.node file out of that\ndirectory. For example, if there was no package.json file in the above\nexample, then require('./some-library') would attempt to load:\n\n

\n
    \n
  • ./some-library/index.js
  • \n
  • ./some-library/index.node
  • \n
\n" + }, + { + "textRaw": "Caching", + "name": "Caching", + "type": "misc", + "desc": "

Modules are cached after the first time they are loaded. This means\n(among other things) that every call to require('foo') will get\nexactly the same object returned, if it would resolve to the same file.\n\n

\n

Multiple calls to require('foo') may not cause the module code to be\nexecuted multiple times. This is an important feature. With it,\n"partially done" objects can be returned, thus allowing transitive\ndependencies to be loaded even when they would cause cycles.\n\n

\n

If you want to have a module execute code multiple times, then export a\nfunction, and call that function.\n\n

\n", + "miscs": [ + { + "textRaw": "Module Caching Caveats", + "name": "Module Caching Caveats", + "type": "misc", + "desc": "

Modules are cached based on their resolved filename. Since modules may\nresolve to a different filename based on the location of the calling\nmodule (loading from node_modules folders), it is not a guarantee\nthat require('foo') will always return the exact same object, if it\nwould resolve to different files.\n\n

\n" + } + ] + }, + { + "textRaw": "All Together...", + "name": "All Together...", + "type": "misc", + "desc": "

To get the exact filename that will be loaded when require() is called, use\nthe require.resolve() function.\n\n

\n

Putting together all of the above, here is the high-level algorithm\nin pseudocode of what require.resolve does:\n\n

\n
require(X) from module at path Y\n1. If X is a core module,\n   a. return the core module\n   b. STOP\n2. If X begins with './' or '/' or '../'\n   a. LOAD_AS_FILE(Y + X)\n   b. LOAD_AS_DIRECTORY(Y + X)\n3. LOAD_NODE_MODULES(X, dirname(Y))\n4. THROW "not found"\n\nLOAD_AS_FILE(X)\n1. If X is a file, load X as JavaScript text.  STOP\n2. If X.js is a file, load X.js as JavaScript text.  STOP\n3. If X.node is a file, load X.node as binary addon.  STOP\n\nLOAD_AS_DIRECTORY(X)\n1. If X/package.json is a file,\n   a. Parse X/package.json, and look for "main" field.\n   b. let M = X + (json main field)\n   c. LOAD_AS_FILE(M)\n2. If X/index.js is a file, load X/index.js as JavaScript text.  STOP\n3. If X/index.node is a file, load X/index.node as binary addon.  STOP\n\nLOAD_NODE_MODULES(X, START)\n1. let DIRS=NODE_MODULES_PATHS(START)\n2. for each DIR in DIRS:\n   a. LOAD_AS_FILE(DIR/X)\n   b. LOAD_AS_DIRECTORY(DIR/X)\n\nNODE_MODULES_PATHS(START)\n1. let PARTS = path split(START)\n2. let ROOT = index of first instance of "node_modules" in PARTS, or 0\n3. let I = count of PARTS - 1\n4. let DIRS = []\n5. while I > ROOT,\n   a. if PARTS[I] = "node_modules" CONTINUE\n   c. DIR = path join(PARTS[0 .. I] + "node_modules")\n   b. DIRS = DIRS + DIR\n   c. let I = I - 1\n6. return DIRS
\n" + }, + { + "textRaw": "Loading from the global folders", + "name": "Loading from the global folders", + "type": "misc", + "desc": "

If the NODE_PATH environment variable is set to a colon-delimited list\nof absolute paths, then node will search those paths for modules if they\nare not found elsewhere. (Note: On Windows, NODE_PATH is delimited by\nsemicolons instead of colons.)\n\n

\n

Additionally, node will search in the following locations:\n\n

\n
    \n
  • 1: $HOME/.node_modules
  • \n
  • 2: $HOME/.node_libraries
  • \n
  • 3: $PREFIX/lib/node
  • \n
\n

Where $HOME is the user's home directory, and $PREFIX is node's\nconfigured node_prefix.\n\n

\n

These are mostly for historic reasons. You are highly encouraged to\nplace your dependencies locally in node_modules folders. They will be\nloaded faster, and more reliably.\n\n

\n" + }, + { + "textRaw": "Accessing the main module", + "name": "Accessing the main module", + "type": "misc", + "desc": "

When a file is run directly from Node, require.main is set to its\nmodule. That means that you can determine whether a file has been run\ndirectly by testing\n\n

\n
require.main === module
\n

For a file foo.js, this will be true if run via node foo.js, but\nfalse if run by require('./foo').\n\n

\n

Because module provides a filename property (normally equivalent to\n__filename), the entry point of the current application can be obtained\nby checking require.main.filename.\n\n

\n" + }, + { + "textRaw": "Addenda: Package Manager Tips", + "name": "Addenda: Package Manager Tips", + "type": "misc", + "desc": "

The semantics of Node's require() function were designed to be general\nenough to support a number of sane directory structures. Package manager\nprograms such as dpkg, rpm, and npm will hopefully find it possible to\nbuild native packages from Node modules without modification.\n\n

\n

Below we give a suggested directory structure that could work:\n\n

\n

Let's say that we wanted to have the folder at\n/usr/lib/node/<some-package>/<some-version> hold the contents of a\nspecific version of a package.\n\n

\n

Packages can depend on one another. In order to install package foo, you\nmay have to install a specific version of package bar. The bar package\nmay itself have dependencies, and in some cases, these dependencies may even\ncollide or form cycles.\n\n

\n

Since Node looks up the realpath of any modules it loads (that is,\nresolves symlinks), and then looks for their dependencies in the\nnode_modules folders as described above, this situation is very simple to\nresolve with the following architecture:\n\n

\n
    \n
  • /usr/lib/node/foo/1.2.3/ - Contents of the foo package, version 1.2.3.
  • \n
  • /usr/lib/node/bar/4.3.2/ - Contents of the bar package that foo\ndepends on.
  • \n
  • /usr/lib/node/foo/1.2.3/node_modules/bar - Symbolic link to\n/usr/lib/node/bar/4.3.2/.
  • \n
  • /usr/lib/node/bar/4.3.2/node_modules/* - Symbolic links to the packages\nthat bar depends on.
  • \n
\n

Thus, even if a cycle is encountered, or if there are dependency\nconflicts, every module will be able to get a version of its dependency\nthat it can use.\n\n

\n

When the code in the foo package does require('bar'), it will get the\nversion that is symlinked into /usr/lib/node/foo/1.2.3/node_modules/bar.\nThen, when the code in the bar package calls require('quux'), it'll get\nthe version that is symlinked into\n/usr/lib/node/bar/4.3.2/node_modules/quux.\n\n

\n

Furthermore, to make the module lookup process even more optimal, rather\nthan putting packages directly in /usr/lib/node, we could put them in\n/usr/lib/node_modules/<name>/<version>. Then node will not bother\nlooking for missing dependencies in /usr/node_modules or /node_modules.\n\n

\n

In order to make modules available to the node REPL, it might be useful to\nalso add the /usr/lib/node_modules folder to the $NODE_PATH environment\nvariable. Since the module lookups using node_modules folders are all\nrelative, and based on the real path of the files making the calls to\nrequire(), the packages themselves can be anywhere.\n

\n" + } + ], + "vars": [ + { + "textRaw": "The `module` Object", + "name": "module", + "type": "var", + "desc": "

In each module, the module free variable is a reference to the object\nrepresenting the current module. In particular\nmodule.exports is the same as the exports object.\nmodule isn't actually a global but rather local to each module.\n\n

\n", + "properties": [ + { + "textRaw": "`exports` {Object} ", + "name": "exports", + "desc": "

The exports object is created by the Module system. Sometimes this is not\nacceptable, many want their module to be an instance of some class. To do this\nassign the desired export object to module.exports. For example suppose we\nwere making a module called a.js\n\n

\n
var EventEmitter = require('events').EventEmitter;\n\nmodule.exports = new EventEmitter();\n\n// Do some work, and after some time emit\n// the 'ready' event from the module itself.\nsetTimeout(function() {\n  module.exports.emit('ready');\n}, 1000);
\n

Then in another file we could do\n\n

\n
var a = require('./a');\na.on('ready', function() {\n  console.log('module a is ready');\n});
\n

Note that assignment to module.exports must be done immediately. It cannot be\ndone in any callbacks. This does not work:\n\n

\n

x.js:\n\n

\n
setTimeout(function() {\n  module.exports = { a: "hello" };\n}, 0);
\n

y.js:\n\n

\n
var x = require('./x');\nconsole.log(x.a);
\n" + }, + { + "textRaw": "`id` {String} ", + "name": "id", + "desc": "

The identifier for the module. Typically this is the fully resolved\nfilename.\n\n\n

\n" + }, + { + "textRaw": "`filename` {String} ", + "name": "filename", + "desc": "

The fully resolved filename to the module.\n\n\n

\n" + }, + { + "textRaw": "`loaded` {Boolean} ", + "name": "loaded", + "desc": "

Whether or not the module is done loading, or is in the process of\nloading.\n\n\n

\n" + }, + { + "textRaw": "`parent` {Module Object} ", + "name": "parent", + "desc": "

The module that required this one.\n\n\n

\n" + }, + { + "textRaw": "`children` {Array} ", + "name": "children", + "desc": "

The module objects required by this one.\n\n\n\n

\n" + } + ], + "methods": [ + { + "textRaw": "module.require(id)", + "type": "method", + "name": "require", + "signatures": [ + { + "return": { + "textRaw": "Return: {Object} `exports` from the resolved module ", + "name": "return", + "type": "Object", + "desc": "`exports` from the resolved module" + }, + "params": [ + { + "textRaw": "`id` {String} ", + "name": "id", + "type": "String" + } + ] + }, + { + "params": [ + { + "name": "id" + } + ] + } + ], + "desc": "

The module.require method provides a way to load a module as if\nrequire() was called from the original module.\n\n

\n

Note that in order to do this, you must get a reference to the module\nobject. Since require() returns the exports, and the module is\ntypically only available within a specific module's code, it must be\nexplicitly exported in order to be used.\n\n\n

\n" + } + ] + } + ], + "type": "module", + "displayName": "module" + } + ] +} diff --git a/node-v0.8.14/doc/api/modules.markdown b/node-v0.8.14/doc/api/modules.markdown new file mode 100644 index 0000000..4720aa5 --- /dev/null +++ b/node-v0.8.14/doc/api/modules.markdown @@ -0,0 +1,461 @@ +# Modules + + Stability: 5 - Locked + + + +Node has a simple module loading system. In Node, files and modules are in +one-to-one correspondence. As an example, `foo.js` loads the module +`circle.js` in the same directory. + +The contents of `foo.js`: + + var circle = require('./circle.js'); + console.log( 'The area of a circle of radius 4 is ' + + circle.area(4)); + +The contents of `circle.js`: + + var PI = Math.PI; + + exports.area = function (r) { + return PI * r * r; + }; + + exports.circumference = function (r) { + return 2 * PI * r; + }; + +The module `circle.js` has exported the functions `area()` and +`circumference()`. To export an object, add to the special `exports` +object. + +Variables +local to the module will be private. In this example the variable `PI` is +private to `circle.js`. + +The module system is implemented in the `require("module")` module. + +## Cycles + + + +When there are circular `require()` calls, a module might not be +done being executed when it is returned. + +Consider this situation: + +`a.js`: + + console.log('a starting'); + exports.done = false; + var b = require('./b.js'); + console.log('in a, b.done = %j', b.done); + exports.done = true; + console.log('a done'); + +`b.js`: + + console.log('b starting'); + exports.done = false; + var a = require('./a.js'); + console.log('in b, a.done = %j', a.done); + exports.done = true; + console.log('b done'); + +`main.js`: + + console.log('main starting'); + var a = require('./a.js'); + var b = require('./b.js'); + console.log('in main, a.done=%j, b.done=%j', a.done, b.done); + +When `main.js` loads `a.js`, then `a.js` in turn loads `b.js`. At that +point, `b.js` tries to load `a.js`. In order to prevent an infinite +loop an **unfinished copy** of the `a.js` exports object is returned to the +`b.js` module. `b.js` then finishes loading, and its exports object is +provided to the `a.js` module. + +By the time `main.js` has loaded both modules, they're both finished. +The output of this program would thus be: + + $ node main.js + main starting + a starting + b starting + in b, a.done = false + b done + in a, b.done = true + a done + in main, a.done=true, b.done=true + +If you have cyclic module dependencies in your program, make sure to +plan accordingly. + +## Core Modules + + + +Node has several modules compiled into the binary. These modules are +described in greater detail elsewhere in this documentation. + +The core modules are defined in node's source in the `lib/` folder. + +Core modules are always preferentially loaded if their identifier is +passed to `require()`. For instance, `require('http')` will always +return the built in HTTP module, even if there is a file by that name. + +## File Modules + + + +If the exact filename is not found, then node will attempt to load the +required filename with the added extension of `.js`, `.json`, and then `.node`. + +`.js` files are interpreted as JavaScript text files, and `.json` files are +parsed as JSON text files. `.node` files are interpreted as compiled addon +modules loaded with `dlopen`. + +A module prefixed with `'/'` is an absolute path to the file. For +example, `require('/home/marco/foo.js')` will load the file at +`/home/marco/foo.js`. + +A module prefixed with `'./'` is relative to the file calling `require()`. +That is, `circle.js` must be in the same directory as `foo.js` for +`require('./circle')` to find it. + +Without a leading '/' or './' to indicate a file, the module is either a +"core module" or is loaded from a `node_modules` folder. + +If the given path does not exist, `require()` will throw an Error with its +`code` property set to `'MODULE_NOT_FOUND'`. + +## Loading from `node_modules` Folders + + + +If the module identifier passed to `require()` is not a native module, +and does not begin with `'/'`, `'../'`, or `'./'`, then node starts at the +parent directory of the current module, and adds `/node_modules`, and +attempts to load the module from that location. + +If it is not found there, then it moves to the parent directory, and so +on, until the root of the tree is reached. + +For example, if the file at `'/home/ry/projects/foo.js'` called +`require('bar.js')`, then node would look in the following locations, in +this order: + +* `/home/ry/projects/node_modules/bar.js` +* `/home/ry/node_modules/bar.js` +* `/home/node_modules/bar.js` +* `/node_modules/bar.js` + +This allows programs to localize their dependencies, so that they do not +clash. + +## Folders as Modules + + + +It is convenient to organize programs and libraries into self-contained +directories, and then provide a single entry point to that library. +There are three ways in which a folder may be passed to `require()` as +an argument. + +The first is to create a `package.json` file in the root of the folder, +which specifies a `main` module. An example package.json file might +look like this: + + { "name" : "some-library", + "main" : "./lib/some-library.js" } + +If this was in a folder at `./some-library`, then +`require('./some-library')` would attempt to load +`./some-library/lib/some-library.js`. + +This is the extent of Node's awareness of package.json files. + +If there is no package.json file present in the directory, then node +will attempt to load an `index.js` or `index.node` file out of that +directory. For example, if there was no package.json file in the above +example, then `require('./some-library')` would attempt to load: + +* `./some-library/index.js` +* `./some-library/index.node` + +## Caching + + + +Modules are cached after the first time they are loaded. This means +(among other things) that every call to `require('foo')` will get +exactly the same object returned, if it would resolve to the same file. + +Multiple calls to `require('foo')` may not cause the module code to be +executed multiple times. This is an important feature. With it, +"partially done" objects can be returned, thus allowing transitive +dependencies to be loaded even when they would cause cycles. + +If you want to have a module execute code multiple times, then export a +function, and call that function. + +### Module Caching Caveats + + + +Modules are cached based on their resolved filename. Since modules may +resolve to a different filename based on the location of the calling +module (loading from `node_modules` folders), it is not a *guarantee* +that `require('foo')` will always return the exact same object, if it +would resolve to different files. + +## The `module` Object + + + + +* {Object} + +In each module, the `module` free variable is a reference to the object +representing the current module. In particular +`module.exports` is the same as the `exports` object. +`module` isn't actually a global but rather local to each module. + +### module.exports + +* {Object} + +The `exports` object is created by the Module system. Sometimes this is not +acceptable, many want their module to be an instance of some class. To do this +assign the desired export object to `module.exports`. For example suppose we +were making a module called `a.js` + + var EventEmitter = require('events').EventEmitter; + + module.exports = new EventEmitter(); + + // Do some work, and after some time emit + // the 'ready' event from the module itself. + setTimeout(function() { + module.exports.emit('ready'); + }, 1000); + +Then in another file we could do + + var a = require('./a'); + a.on('ready', function() { + console.log('module a is ready'); + }); + + +Note that assignment to `module.exports` must be done immediately. It cannot be +done in any callbacks. This does not work: + +x.js: + + setTimeout(function() { + module.exports = { a: "hello" }; + }, 0); + +y.js: + + var x = require('./x'); + console.log(x.a); + + +### module.require(id) + +* `id` {String} +* Return: {Object} `exports` from the resolved module + +The `module.require` method provides a way to load a module as if +`require()` was called from the original module. + +Note that in order to do this, you must get a reference to the `module` +object. Since `require()` returns the `exports`, and the `module` is +typically *only* available within a specific module's code, it must be +explicitly exported in order to be used. + + +### module.id + +* {String} + +The identifier for the module. Typically this is the fully resolved +filename. + + +### module.filename + +* {String} + +The fully resolved filename to the module. + + +### module.loaded + +* {Boolean} + +Whether or not the module is done loading, or is in the process of +loading. + + +### module.parent + +* {Module Object} + +The module that required this one. + + +### module.children + +* {Array} + +The module objects required by this one. + + + +## All Together... + + + +To get the exact filename that will be loaded when `require()` is called, use +the `require.resolve()` function. + +Putting together all of the above, here is the high-level algorithm +in pseudocode of what require.resolve does: + + require(X) from module at path Y + 1. If X is a core module, + a. return the core module + b. STOP + 2. If X begins with './' or '/' or '../' + a. LOAD_AS_FILE(Y + X) + b. LOAD_AS_DIRECTORY(Y + X) + 3. LOAD_NODE_MODULES(X, dirname(Y)) + 4. THROW "not found" + + LOAD_AS_FILE(X) + 1. If X is a file, load X as JavaScript text. STOP + 2. If X.js is a file, load X.js as JavaScript text. STOP + 3. If X.node is a file, load X.node as binary addon. STOP + + LOAD_AS_DIRECTORY(X) + 1. If X/package.json is a file, + a. Parse X/package.json, and look for "main" field. + b. let M = X + (json main field) + c. LOAD_AS_FILE(M) + 2. If X/index.js is a file, load X/index.js as JavaScript text. STOP + 3. If X/index.node is a file, load X/index.node as binary addon. STOP + + LOAD_NODE_MODULES(X, START) + 1. let DIRS=NODE_MODULES_PATHS(START) + 2. for each DIR in DIRS: + a. LOAD_AS_FILE(DIR/X) + b. LOAD_AS_DIRECTORY(DIR/X) + + NODE_MODULES_PATHS(START) + 1. let PARTS = path split(START) + 2. let ROOT = index of first instance of "node_modules" in PARTS, or 0 + 3. let I = count of PARTS - 1 + 4. let DIRS = [] + 5. while I > ROOT, + a. if PARTS[I] = "node_modules" CONTINUE + c. DIR = path join(PARTS[0 .. I] + "node_modules") + b. DIRS = DIRS + DIR + c. let I = I - 1 + 6. return DIRS + +## Loading from the global folders + + + +If the `NODE_PATH` environment variable is set to a colon-delimited list +of absolute paths, then node will search those paths for modules if they +are not found elsewhere. (Note: On Windows, `NODE_PATH` is delimited by +semicolons instead of colons.) + +Additionally, node will search in the following locations: + +* 1: `$HOME/.node_modules` +* 2: `$HOME/.node_libraries` +* 3: `$PREFIX/lib/node` + +Where `$HOME` is the user's home directory, and `$PREFIX` is node's +configured `node_prefix`. + +These are mostly for historic reasons. You are highly encouraged to +place your dependencies locally in `node_modules` folders. They will be +loaded faster, and more reliably. + +## Accessing the main module + + + +When a file is run directly from Node, `require.main` is set to its +`module`. That means that you can determine whether a file has been run +directly by testing + + require.main === module + +For a file `foo.js`, this will be `true` if run via `node foo.js`, but +`false` if run by `require('./foo')`. + +Because `module` provides a `filename` property (normally equivalent to +`__filename`), the entry point of the current application can be obtained +by checking `require.main.filename`. + +## Addenda: Package Manager Tips + + + +The semantics of Node's `require()` function were designed to be general +enough to support a number of sane directory structures. Package manager +programs such as `dpkg`, `rpm`, and `npm` will hopefully find it possible to +build native packages from Node modules without modification. + +Below we give a suggested directory structure that could work: + +Let's say that we wanted to have the folder at +`/usr/lib/node//` hold the contents of a +specific version of a package. + +Packages can depend on one another. In order to install package `foo`, you +may have to install a specific version of package `bar`. The `bar` package +may itself have dependencies, and in some cases, these dependencies may even +collide or form cycles. + +Since Node looks up the `realpath` of any modules it loads (that is, +resolves symlinks), and then looks for their dependencies in the +`node_modules` folders as described above, this situation is very simple to +resolve with the following architecture: + +* `/usr/lib/node/foo/1.2.3/` - Contents of the `foo` package, version 1.2.3. +* `/usr/lib/node/bar/4.3.2/` - Contents of the `bar` package that `foo` + depends on. +* `/usr/lib/node/foo/1.2.3/node_modules/bar` - Symbolic link to + `/usr/lib/node/bar/4.3.2/`. +* `/usr/lib/node/bar/4.3.2/node_modules/*` - Symbolic links to the packages + that `bar` depends on. + +Thus, even if a cycle is encountered, or if there are dependency +conflicts, every module will be able to get a version of its dependency +that it can use. + +When the code in the `foo` package does `require('bar')`, it will get the +version that is symlinked into `/usr/lib/node/foo/1.2.3/node_modules/bar`. +Then, when the code in the `bar` package calls `require('quux')`, it'll get +the version that is symlinked into +`/usr/lib/node/bar/4.3.2/node_modules/quux`. + +Furthermore, to make the module lookup process even more optimal, rather +than putting packages directly in `/usr/lib/node`, we could put them in +`/usr/lib/node_modules//`. Then node will not bother +looking for missing dependencies in `/usr/node_modules` or `/node_modules`. + +In order to make modules available to the node REPL, it might be useful to +also add the `/usr/lib/node_modules` folder to the `$NODE_PATH` environment +variable. Since the module lookups using `node_modules` folders are all +relative, and based on the real path of the files making the calls to +`require()`, the packages themselves can be anywhere. diff --git a/node-v0.8.14/doc/api/net.html b/node-v0.8.14/doc/api/net.html new file mode 100644 index 0000000..66e79ed --- /dev/null +++ b/node-v0.8.14/doc/api/net.html @@ -0,0 +1,664 @@ + + + + + net Node.js v0.8.14 Manual & Documentation + + + + + +
+ + + +
+
+ + +
+
+

Node.js v0.8.14 Manual & Documentation

+ +
+
+ + + +
+

net#

+
Stability: 3 - Stable
+

The net module provides you with an asynchronous network wrapper. It contains +methods for creating both servers and clients (called streams). You can include +this module with require('net'); + +

+

net.createServer([options], [connectionListener])#

+

Creates a new TCP server. The connectionListener argument is +automatically set as a listener for the 'connection' event. + +

+

options is an object with the following defaults: + +

+
{ allowHalfOpen: false
+}
+

If allowHalfOpen is true, then the socket won't automatically send a FIN +packet when the other end of the socket sends a FIN packet. The socket becomes +non-readable, but still writable. You should call the end() method explicitly. +See 'end' event for more information. + +

+

Here is an example of an echo server which listens for connections +on port 8124: + +

+
var net = require('net');
+var server = net.createServer(function(c) { //'connection' listener
+  console.log('server connected');
+  c.on('end', function() {
+    console.log('server disconnected');
+  });
+  c.write('hello\r\n');
+  c.pipe(c);
+});
+server.listen(8124, function() { //'listening' listener
+  console.log('server bound');
+});
+

Test this by using telnet: + +

+
telnet localhost 8124
+

To listen on the socket /tmp/echo.sock the third line from the last would +just be changed to + +

+
server.listen('/tmp/echo.sock', function() { //'listening' listener
+

Use nc to connect to a UNIX domain socket server: + +

+
nc -U /tmp/echo.sock
+

net.connect(options, [connectionListener])#

+

net.createConnection(options, [connectionListener])#

+

Constructs a new socket object and opens the socket to the given location. +When the socket is established, the 'connect' event will be emitted. + +

+

For TCP sockets, options argument should be an object which specifies: + +

+
    +
  • port: Port the client should connect to (Required).

    +
  • +
  • host: Host the client should connect to. Defaults to 'localhost'.

    +
  • +
  • localAddress: Local interface to bind to for network connections.

    +
  • +
+

For UNIX domain sockets, options argument should be an object which specifies: + +

+
    +
  • path: Path the client should connect to (Required).
  • +
+

Common options are: + +

+
    +
  • allowHalfOpen: if true, the socket won't automatically send +a FIN packet when the other end of the socket sends a FIN packet. +Defaults to false. See 'end' event for more information.
  • +
+

The connectListener parameter will be added as an listener for the +'connect' event. + +

+

Here is an example of a client of echo server as described previously: + +

+
var net = require('net');
+var client = net.connect({port: 8124},
+    function() { //'connect' listener
+  console.log('client connected');
+  client.write('world!\r\n');
+});
+client.on('data', function(data) {
+  console.log(data.toString());
+  client.end();
+});
+client.on('end', function() {
+  console.log('client disconnected');
+});
+

To connect on the socket /tmp/echo.sock the second line would just be +changed to + +

+
var client = net.connect({path: '/tmp/echo.sock'},
+

net.connect(port, [host], [connectListener])#

+

net.createConnection(port, [host], [connectListener])#

+

Creates a TCP connection to port on host. If host is omitted, +'localhost' will be assumed. +The connectListener parameter will be added as an listener for the +'connect' event. + +

+

net.connect(path, [connectListener])#

+

net.createConnection(path, [connectListener])#

+

Creates unix socket connection to path. +The connectListener parameter will be added as an listener for the +'connect' event. + +

+

Class: net.Server#

+

This class is used to create a TCP or UNIX server. +A server is a net.Socket that can listen for new incoming connections. + +

+

server.listen(port, [host], [backlog], [callback])#

+

Begin accepting connections on the specified port and host. If the +host is omitted, the server will accept connections directed to any +IPv4 address (INADDR_ANY). A port value of zero will assign a random port. + +

+

Backlog is the maximum length of the queue of pending connections. +The actual length will be determined by your OS through sysctl settings such as +tcp_max_syn_backlog and somaxconn on linux. The default value of this +parameter is 511 (not 512). + +

+

This function is asynchronous. When the server has been bound, +'listening' event will be emitted. The last parameter callback +will be added as an listener for the 'listening' event. + +

+

One issue some users run into is getting EADDRINUSE errors. This means that +another server is already running on the requested port. One way of handling this +would be to wait a second and then try again. This can be done with + +

+
server.on('error', function (e) {
+  if (e.code == 'EADDRINUSE') {
+    console.log('Address in use, retrying...');
+    setTimeout(function () {
+      server.close();
+      server.listen(PORT, HOST);
+    }, 1000);
+  }
+});
+

(Note: All sockets in Node set SO_REUSEADDR already) + + +

+

server.listen(path, [callback])#

+

Start a UNIX socket server listening for connections on the given path. + +

+

This function is asynchronous. When the server has been bound, +'listening' event will be emitted. The last parameter callback +will be added as an listener for the 'listening' event. + +

+

server.listen(handle, [callback])#

+
    +
  • handle Object
  • +
  • callback Function
  • +
+

The handle object can be set to either a server or socket (anything +with an underlying _handle member), or a {fd: <n>} object. + +

+

This will cause the server to accept connections on the specified +handle, but it is presumed that the file descriptor or handle has +already been bound to a port or domain socket. + +

+

Listening on a file descriptor is not supported on Windows. + +

+

This function is asynchronous. When the server has been bound, +'listening' event will be emitted. +the last parameter callback will be added as an listener for the +'listening' event. + +

+

server.close([callback])#

+

Stops the server from accepting new connections and keeps existing +connections. This function is asynchronous, the server is finally +closed when all connections are ended and the server emits a 'close' +event. Optionally, you can pass a callback to listen for the 'close' +event. + +

+

server.address()#

+

Returns the bound address, the address family name and port of the server +as reported by the operating system. +Useful to find which port was assigned when giving getting an OS-assigned address. +Returns an object with three properties, e.g. +{ port: 12346, family: 'IPv4', address: '127.0.0.1' } + +

+

Example: + +

+
var server = net.createServer(function (socket) {
+  socket.end("goodbye\n");
+});
+
+// grab a random port.
+server.listen(function() {
+  address = server.address();
+  console.log("opened server on %j", address);
+});
+

Don't call server.address() until the 'listening' event has been emitted. + +

+

server.maxConnections#

+

Set this property to reject connections when the server's connection count gets +high. + +

+

It is not recommended to use this option once a socket has been sent to a child +with child_process.fork(). + +

+

server.connections#

+

The number of concurrent connections on the server. + +

+

This becomes null when sending a socket to a child with child_process.fork(). + +

+

net.Server is an EventEmitter with the following events: + +

+

Event: 'listening'#

+

Emitted when the server has been bound after calling server.listen. + +

+

Event: 'connection'#

+
    +
  • Socket object The connection object
  • +
+

Emitted when a new connection is made. socket is an instance of +net.Socket. + +

+

Event: 'close'#

+

Emitted when the server closes. Note that if connections exist, this +event is not emitted until all connections are ended. + +

+

Event: 'error'#

+
    +
  • Error Object
  • +
+

Emitted when an error occurs. The 'close' event will be called directly +following this event. See example in discussion of server.listen. + +

+

Class: net.Socket#

+

This object is an abstraction of a TCP or UNIX socket. net.Socket +instances implement a duplex Stream interface. They can be created by the +user and used as a client (with connect()) or they can be created by Node +and passed to the user through the 'connection' event of a server. + +

+

new net.Socket([options])#

+

Construct a new socket object. + +

+

options is an object with the following defaults: + +

+
{ fd: null
+  type: null
+  allowHalfOpen: false
+}
+

fd allows you to specify the existing file descriptor of socket. type +specified underlying protocol. It can be 'tcp4', 'tcp6', or 'unix'. +About allowHalfOpen, refer to createServer() and 'end' event. + +

+

socket.connect(port, [host], [connectListener])#

+

socket.connect(path, [connectListener])#

+

Opens the connection for a given socket. If port and host are given, +then the socket will be opened as a TCP socket, if host is omitted, +localhost will be assumed. If a path is given, the socket will be +opened as a unix socket to that path. + +

+

Normally this method is not needed, as net.createConnection opens the +socket. Use this only if you are implementing a custom Socket or if a +Socket is closed and you want to reuse it to connect to another server. + +

+

This function is asynchronous. When the 'connect' event is emitted the +socket is established. If there is a problem connecting, the 'connect' event +will not be emitted, the 'error' event will be emitted with the exception. + +

+

The connectListener parameter will be added as an listener for the +'connect' event. + + +

+

socket.bufferSize#

+

net.Socket has the property that socket.write() always works. This is to +help users get up and running quickly. The computer cannot always keep up +with the amount of data that is written to a socket - the network connection +simply might be too slow. Node will internally queue up the data written to a +socket and send it out over the wire when it is possible. (Internally it is +polling on the socket's file descriptor for being writable). + +

+

The consequence of this internal buffering is that memory may grow. This +property shows the number of characters currently buffered to be written. +(Number of characters is approximately equal to the number of bytes to be +written, but the buffer may contain strings, and the strings are lazily +encoded, so the exact number of bytes is not known.) + +

+

Users who experience large or growing bufferSize should attempt to +"throttle" the data flows in their program with pause() and resume(). + + +

+

socket.setEncoding([encoding])#

+

Set the encoding for the socket as a Readable Stream. See +stream.setEncoding() for more information. + +

+

socket.write(data, [encoding], [callback])#

+

Sends data on the socket. The second parameter specifies the encoding in the +case of a string--it defaults to UTF8 encoding. + +

+

Returns true if the entire data was flushed successfully to the kernel +buffer. Returns false if all or part of the data was queued in user memory. +'drain' will be emitted when the buffer is again free. + +

+

The optional callback parameter will be executed when the data is finally +written out - this may not be immediately. + +

+

socket.end([data], [encoding])#

+

Half-closes the socket. i.e., it sends a FIN packet. It is possible the +server will still send some data. + +

+

If data is specified, it is equivalent to calling +socket.write(data, encoding) followed by socket.end(). + +

+

socket.destroy()#

+

Ensures that no more I/O activity happens on this socket. Only necessary in +case of errors (parse error or so). + +

+

socket.pause()#

+

Pauses the reading of data. That is, 'data' events will not be emitted. +Useful to throttle back an upload. + +

+

socket.resume()#

+

Resumes reading after a call to pause(). + +

+

socket.setTimeout(timeout, [callback])#

+

Sets the socket to timeout after timeout milliseconds of inactivity on +the socket. By default net.Socket do not have a timeout. + +

+

When an idle timeout is triggered the socket will receive a 'timeout' +event but the connection will not be severed. The user must manually end() +or destroy() the socket. + +

+

If timeout is 0, then the existing idle timeout is disabled. + +

+

The optional callback parameter will be added as a one time listener for the +'timeout' event. + +

+

socket.setNoDelay([noDelay])#

+

Disables the Nagle algorithm. By default TCP connections use the Nagle +algorithm, they buffer data before sending it off. Setting true for +noDelay will immediately fire off data each time socket.write() is called. +noDelay defaults to true. + +

+

socket.setKeepAlive([enable], [initialDelay])#

+

Enable/disable keep-alive functionality, and optionally set the initial +delay before the first keepalive probe is sent on an idle socket. +enable defaults to false. + +

+

Set initialDelay (in milliseconds) to set the delay between the last +data packet received and the first keepalive probe. Setting 0 for +initialDelay will leave the value unchanged from the default +(or previous) setting. Defaults to 0. + +

+

socket.address()#

+

Returns the bound address, the address family name and port of the +socket as reported by the operating system. Returns an object with +three properties, e.g. +{ port: 12346, family: 'IPv4', address: '127.0.0.1' } + +

+

socket.remoteAddress#

+

The string representation of the remote IP address. For example, +'74.125.127.100' or '2001:4860:a005::68'. + +

+

socket.remotePort#

+

The numeric representation of the remote port. For example, +80 or 21. + +

+

socket.bytesRead#

+

The amount of received bytes. + +

+

socket.bytesWritten#

+

The amount of bytes sent. + + +

+

net.Socket instances are EventEmitter with the following events: + +

+

Event: 'connect'#

+

Emitted when a socket connection is successfully established. +See connect(). + +

+

Event: 'data'#

+
    +
  • Buffer object
  • +
+

Emitted when data is received. The argument data will be a Buffer or +String. Encoding of data is set by socket.setEncoding(). +(See the Readable Stream section for more information.) + +

+

Note that the data will be lost if there is no listener when a Socket +emits a 'data' event. + +

+

Event: 'end'#

+

Emitted when the other end of the socket sends a FIN packet. + +

+

By default (allowHalfOpen == false) the socket will destroy its file +descriptor once it has written out its pending write queue. However, by +setting allowHalfOpen == true the socket will not automatically end() +its side allowing the user to write arbitrary amounts of data, with the +caveat that the user is required to end() their side now. + + +

+

Event: 'timeout'#

+

Emitted if the socket times out from inactivity. This is only to notify that +the socket has been idle. The user must manually close the connection. + +

+

See also: socket.setTimeout() + + +

+

Event: 'drain'#

+

Emitted when the write buffer becomes empty. Can be used to throttle uploads. + +

+

See also: the return values of socket.write() + +

+

Event: 'error'#

+
    +
  • Error object
  • +
+

Emitted when an error occurs. The 'close' event will be called directly +following this event. + +

+

Event: 'close'#

+
    +
  • had_error Boolean true if the socket had a transmission error
  • +
+

Emitted once the socket is fully closed. The argument had_error is a boolean +which says if the socket was closed due to a transmission error. + +

+

net.isIP(input)#

+

Tests if input is an IP address. Returns 0 for invalid strings, +returns 4 for IP version 4 addresses, and returns 6 for IP version 6 addresses. + + +

+

net.isIPv4(input)#

+

Returns true if input is a version 4 IP address, otherwise returns false. + + +

+

net.isIPv6(input)#

+

Returns true if input is a version 6 IP address, otherwise returns false. + +

+ +
+
+
+ + + + + + + + + diff --git a/node-v0.8.14/doc/api/net.json b/node-v0.8.14/doc/api/net.json new file mode 100644 index 0000000..f011872 --- /dev/null +++ b/node-v0.8.14/doc/api/net.json @@ -0,0 +1,712 @@ +{ + "source": "doc/api/net.markdown", + "modules": [ + { + "textRaw": "net", + "name": "net", + "stability": 3, + "stabilityText": "Stable", + "desc": "

The net module provides you with an asynchronous network wrapper. It contains\nmethods for creating both servers and clients (called streams). You can include\nthis module with require('net');\n\n

\n", + "methods": [ + { + "textRaw": "net.createServer([options], [connectionListener])", + "type": "method", + "name": "createServer", + "desc": "

Creates a new TCP server. The connectionListener argument is\nautomatically set as a listener for the ['connection'][] event.\n\n

\n

options is an object with the following defaults:\n\n

\n
{ allowHalfOpen: false\n}
\n

If allowHalfOpen is true, then the socket won't automatically send a FIN\npacket when the other end of the socket sends a FIN packet. The socket becomes\nnon-readable, but still writable. You should call the end() method explicitly.\nSee ['end'][] event for more information.\n\n

\n

Here is an example of an echo server which listens for connections\non port 8124:\n\n

\n
var net = require('net');\nvar server = net.createServer(function(c) { //'connection' listener\n  console.log('server connected');\n  c.on('end', function() {\n    console.log('server disconnected');\n  });\n  c.write('hello\\r\\n');\n  c.pipe(c);\n});\nserver.listen(8124, function() { //'listening' listener\n  console.log('server bound');\n});
\n

Test this by using telnet:\n\n

\n
telnet localhost 8124
\n

To listen on the socket /tmp/echo.sock the third line from the last would\njust be changed to\n\n

\n
server.listen('/tmp/echo.sock', function() { //'listening' listener
\n

Use nc to connect to a UNIX domain socket server:\n\n

\n
nc -U /tmp/echo.sock
\n", + "signatures": [ + { + "params": [ + { + "name": "options", + "optional": true + }, + { + "name": "connectionListener", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "net.connect(options, [connectionListener])", + "type": "method", + "name": "connect", + "desc": "

Constructs a new socket object and opens the socket to the given location.\nWhen the socket is established, the ['connect'][] event will be emitted.\n\n

\n

For TCP sockets, options argument should be an object which specifies:\n\n

\n
    \n
  • port: Port the client should connect to (Required).

    \n
  • \n
  • host: Host the client should connect to. Defaults to 'localhost'.

    \n
  • \n
  • localAddress: Local interface to bind to for network connections.

    \n
  • \n
\n

For UNIX domain sockets, options argument should be an object which specifies:\n\n

\n
    \n
  • path: Path the client should connect to (Required).
  • \n
\n

Common options are:\n\n

\n
    \n
  • allowHalfOpen: if true, the socket won't automatically send\na FIN packet when the other end of the socket sends a FIN packet.\nDefaults to false. See ['end'][] event for more information.
  • \n
\n

The connectListener parameter will be added as an listener for the\n['connect'][] event.\n\n

\n

Here is an example of a client of echo server as described previously:\n\n

\n
var net = require('net');\nvar client = net.connect({port: 8124},\n    function() { //'connect' listener\n  console.log('client connected');\n  client.write('world!\\r\\n');\n});\nclient.on('data', function(data) {\n  console.log(data.toString());\n  client.end();\n});\nclient.on('end', function() {\n  console.log('client disconnected');\n});
\n

To connect on the socket /tmp/echo.sock the second line would just be\nchanged to\n\n

\n
var client = net.connect({path: '/tmp/echo.sock'},
\n", + "signatures": [ + { + "params": [ + { + "name": "options" + }, + { + "name": "connectionListener", + "optional": true + } + ] + }, + { + "params": [ + { + "name": "options" + }, + { + "name": "connectionListener", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "net.createConnection(options, [connectionListener])", + "type": "method", + "name": "createConnection", + "desc": "

Constructs a new socket object and opens the socket to the given location.\nWhen the socket is established, the ['connect'][] event will be emitted.\n\n

\n

For TCP sockets, options argument should be an object which specifies:\n\n

\n
    \n
  • port: Port the client should connect to (Required).

    \n
  • \n
  • host: Host the client should connect to. Defaults to 'localhost'.

    \n
  • \n
  • localAddress: Local interface to bind to for network connections.

    \n
  • \n
\n

For UNIX domain sockets, options argument should be an object which specifies:\n\n

\n
    \n
  • path: Path the client should connect to (Required).
  • \n
\n

Common options are:\n\n

\n
    \n
  • allowHalfOpen: if true, the socket won't automatically send\na FIN packet when the other end of the socket sends a FIN packet.\nDefaults to false. See ['end'][] event for more information.
  • \n
\n

The connectListener parameter will be added as an listener for the\n['connect'][] event.\n\n

\n

Here is an example of a client of echo server as described previously:\n\n

\n
var net = require('net');\nvar client = net.connect({port: 8124},\n    function() { //'connect' listener\n  console.log('client connected');\n  client.write('world!\\r\\n');\n});\nclient.on('data', function(data) {\n  console.log(data.toString());\n  client.end();\n});\nclient.on('end', function() {\n  console.log('client disconnected');\n});
\n

To connect on the socket /tmp/echo.sock the second line would just be\nchanged to\n\n

\n
var client = net.connect({path: '/tmp/echo.sock'},
\n", + "signatures": [ + { + "params": [ + { + "name": "options" + }, + { + "name": "connectionListener", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "net.connect(port, [host], [connectListener])", + "type": "method", + "name": "connect", + "desc": "

Creates a TCP connection to port on host. If host is omitted,\n'localhost' will be assumed.\nThe connectListener parameter will be added as an listener for the\n['connect'][] event.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "port" + }, + { + "name": "host", + "optional": true + }, + { + "name": "connectListener", + "optional": true + } + ] + }, + { + "params": [ + { + "name": "port" + }, + { + "name": "host", + "optional": true + }, + { + "name": "connectListener", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "net.createConnection(port, [host], [connectListener])", + "type": "method", + "name": "createConnection", + "desc": "

Creates a TCP connection to port on host. If host is omitted,\n'localhost' will be assumed.\nThe connectListener parameter will be added as an listener for the\n['connect'][] event.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "port" + }, + { + "name": "host", + "optional": true + }, + { + "name": "connectListener", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "net.connect(path, [connectListener])", + "type": "method", + "name": "connect", + "desc": "

Creates unix socket connection to path.\nThe connectListener parameter will be added as an listener for the\n['connect'][] event.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "path" + }, + { + "name": "connectListener", + "optional": true + } + ] + }, + { + "params": [ + { + "name": "path" + }, + { + "name": "connectListener", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "net.createConnection(path, [connectListener])", + "type": "method", + "name": "createConnection", + "desc": "

Creates unix socket connection to path.\nThe connectListener parameter will be added as an listener for the\n['connect'][] event.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "path" + }, + { + "name": "connectListener", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "net.isIP(input)", + "type": "method", + "name": "isIP", + "desc": "

Tests if input is an IP address. Returns 0 for invalid strings,\nreturns 4 for IP version 4 addresses, and returns 6 for IP version 6 addresses.\n\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "input" + } + ] + } + ] + }, + { + "textRaw": "net.isIPv4(input)", + "type": "method", + "name": "isIPv4", + "desc": "

Returns true if input is a version 4 IP address, otherwise returns false.\n\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "input" + } + ] + } + ] + }, + { + "textRaw": "net.isIPv6(input)", + "type": "method", + "name": "isIPv6", + "desc": "

Returns true if input is a version 6 IP address, otherwise returns false.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "input" + } + ] + } + ] + } + ], + "classes": [ + { + "textRaw": "Class: net.Server", + "type": "class", + "name": "net.Server", + "desc": "

This class is used to create a TCP or UNIX server.\nA server is a net.Socket that can listen for new incoming connections.\n\n

\n", + "methods": [ + { + "textRaw": "server.listen(port, [host], [backlog], [callback])", + "type": "method", + "name": "listen", + "desc": "

Begin accepting connections on the specified port and host. If the\nhost is omitted, the server will accept connections directed to any\nIPv4 address (INADDR_ANY). A port value of zero will assign a random port.\n\n

\n

Backlog is the maximum length of the queue of pending connections.\nThe actual length will be determined by your OS through sysctl settings such as\ntcp_max_syn_backlog and somaxconn on linux. The default value of this\nparameter is 511 (not 512).\n\n

\n

This function is asynchronous. When the server has been bound,\n['listening'][] event will be emitted. The last parameter callback\nwill be added as an listener for the ['listening'][] event.\n\n

\n

One issue some users run into is getting EADDRINUSE errors. This means that\nanother server is already running on the requested port. One way of handling this\nwould be to wait a second and then try again. This can be done with\n\n

\n
server.on('error', function (e) {\n  if (e.code == 'EADDRINUSE') {\n    console.log('Address in use, retrying...');\n    setTimeout(function () {\n      server.close();\n      server.listen(PORT, HOST);\n    }, 1000);\n  }\n});
\n

(Note: All sockets in Node set SO_REUSEADDR already)\n\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "port" + }, + { + "name": "host", + "optional": true + }, + { + "name": "backlog", + "optional": true + }, + { + "name": "callback", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "server.listen(path, [callback])", + "type": "method", + "name": "listen", + "desc": "

Start a UNIX socket server listening for connections on the given path.\n\n

\n

This function is asynchronous. When the server has been bound,\n['listening'][] event will be emitted. The last parameter callback\nwill be added as an listener for the ['listening'][] event.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "path" + }, + { + "name": "callback", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "server.listen(handle, [callback])", + "type": "method", + "name": "listen", + "signatures": [ + { + "params": [ + { + "textRaw": "`handle` {Object} ", + "name": "handle", + "type": "Object" + }, + { + "textRaw": "`callback` {Function} ", + "name": "callback", + "type": "Function", + "optional": true + } + ] + }, + { + "params": [ + { + "name": "handle" + }, + { + "name": "callback", + "optional": true + } + ] + } + ], + "desc": "

The handle object can be set to either a server or socket (anything\nwith an underlying _handle member), or a {fd: <n>} object.\n\n

\n

This will cause the server to accept connections on the specified\nhandle, but it is presumed that the file descriptor or handle has\nalready been bound to a port or domain socket.\n\n

\n

Listening on a file descriptor is not supported on Windows.\n\n

\n

This function is asynchronous. When the server has been bound,\n'listening' event will be emitted.\nthe last parameter callback will be added as an listener for the\n'listening' event.\n\n

\n" + }, + { + "textRaw": "server.close([callback])", + "type": "method", + "name": "close", + "desc": "

Stops the server from accepting new connections and keeps existing\nconnections. This function is asynchronous, the server is finally\nclosed when all connections are ended and the server emits a 'close'\nevent. Optionally, you can pass a callback to listen for the 'close'\nevent.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "callback", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "server.address()", + "type": "method", + "name": "address", + "desc": "

Returns the bound address, the address family name and port of the server\nas reported by the operating system.\nUseful to find which port was assigned when giving getting an OS-assigned address.\nReturns an object with three properties, e.g.\n{ port: 12346, family: 'IPv4', address: '127.0.0.1' }\n\n

\n

Example:\n\n

\n
var server = net.createServer(function (socket) {\n  socket.end("goodbye\\n");\n});\n\n// grab a random port.\nserver.listen(function() {\n  address = server.address();\n  console.log("opened server on %j", address);\n});
\n

Don't call server.address() until the 'listening' event has been emitted.\n\n

\n", + "signatures": [ + { + "params": [] + } + ] + } + ], + "properties": [ + { + "textRaw": "server.maxConnections", + "name": "maxConnections", + "desc": "

Set this property to reject connections when the server's connection count gets\nhigh.\n\n

\n

It is not recommended to use this option once a socket has been sent to a child\nwith child_process.fork().\n\n

\n" + }, + { + "textRaw": "server.connections", + "name": "connections", + "desc": "

The number of concurrent connections on the server.\n\n

\n

This becomes null when sending a socket to a child with child_process.fork().\n\n

\n

net.Server is an [EventEmitter][] with the following events:\n\n

\n" + } + ], + "events": [ + { + "textRaw": "Event: 'listening'", + "type": "event", + "name": "listening", + "desc": "

Emitted when the server has been bound after calling server.listen.\n\n

\n", + "params": [] + }, + { + "textRaw": "Event: 'connection'", + "type": "event", + "name": "connection", + "params": [], + "desc": "

Emitted when a new connection is made. socket is an instance of\nnet.Socket.\n\n

\n" + }, + { + "textRaw": "Event: 'close'", + "type": "event", + "name": "close", + "desc": "

Emitted when the server closes. Note that if connections exist, this\nevent is not emitted until all connections are ended.\n\n

\n", + "params": [] + }, + { + "textRaw": "Event: 'error'", + "type": "event", + "name": "error", + "params": [], + "desc": "

Emitted when an error occurs. The 'close' event will be called directly\nfollowing this event. See example in discussion of server.listen.\n\n

\n" + } + ] + }, + { + "textRaw": "Class: net.Socket", + "type": "class", + "name": "net.Socket", + "desc": "

This object is an abstraction of a TCP or UNIX socket. net.Socket\ninstances implement a duplex Stream interface. They can be created by the\nuser and used as a client (with connect()) or they can be created by Node\nand passed to the user through the 'connection' event of a server.\n\n

\n", + "methods": [ + { + "textRaw": "new net.Socket([options])", + "type": "method", + "name": "Socket", + "desc": "

Construct a new socket object.\n\n

\n

options is an object with the following defaults:\n\n

\n
{ fd: null\n  type: null\n  allowHalfOpen: false\n}
\n

fd allows you to specify the existing file descriptor of socket. type\nspecified underlying protocol. It can be 'tcp4', 'tcp6', or 'unix'.\nAbout allowHalfOpen, refer to createServer() and 'end' event.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "options", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "socket.connect(port, [host], [connectListener])", + "type": "method", + "name": "connect", + "desc": "

Opens the connection for a given socket. If port and host are given,\nthen the socket will be opened as a TCP socket, if host is omitted,\nlocalhost will be assumed. If a path is given, the socket will be\nopened as a unix socket to that path.\n\n

\n

Normally this method is not needed, as net.createConnection opens the\nsocket. Use this only if you are implementing a custom Socket or if a\nSocket is closed and you want to reuse it to connect to another server.\n\n

\n

This function is asynchronous. When the ['connect'][] event is emitted the\nsocket is established. If there is a problem connecting, the 'connect' event\nwill not be emitted, the 'error' event will be emitted with the exception.\n\n

\n

The connectListener parameter will be added as an listener for the\n['connect'][] event.\n\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "path" + }, + { + "name": "connectListener", + "optional": true + } + ] + }, + { + "params": [ + { + "name": "port" + }, + { + "name": "host", + "optional": true + }, + { + "name": "connectListener", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "socket.connect(path, [connectListener])", + "type": "method", + "name": "connect", + "desc": "

Opens the connection for a given socket. If port and host are given,\nthen the socket will be opened as a TCP socket, if host is omitted,\nlocalhost will be assumed. If a path is given, the socket will be\nopened as a unix socket to that path.\n\n

\n

Normally this method is not needed, as net.createConnection opens the\nsocket. Use this only if you are implementing a custom Socket or if a\nSocket is closed and you want to reuse it to connect to another server.\n\n

\n

This function is asynchronous. When the ['connect'][] event is emitted the\nsocket is established. If there is a problem connecting, the 'connect' event\nwill not be emitted, the 'error' event will be emitted with the exception.\n\n

\n

The connectListener parameter will be added as an listener for the\n['connect'][] event.\n\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "path" + }, + { + "name": "connectListener", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "socket.setEncoding([encoding])", + "type": "method", + "name": "setEncoding", + "desc": "

Set the encoding for the socket as a Readable Stream. See\n[stream.setEncoding()][] for more information.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "encoding", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "socket.write(data, [encoding], [callback])", + "type": "method", + "name": "write", + "desc": "

Sends data on the socket. The second parameter specifies the encoding in the\ncase of a string--it defaults to UTF8 encoding.\n\n

\n

Returns true if the entire data was flushed successfully to the kernel\nbuffer. Returns false if all or part of the data was queued in user memory.\n'drain' will be emitted when the buffer is again free.\n\n

\n

The optional callback parameter will be executed when the data is finally\nwritten out - this may not be immediately.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "data" + }, + { + "name": "encoding", + "optional": true + }, + { + "name": "callback", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "socket.end([data], [encoding])", + "type": "method", + "name": "end", + "desc": "

Half-closes the socket. i.e., it sends a FIN packet. It is possible the\nserver will still send some data.\n\n

\n

If data is specified, it is equivalent to calling\nsocket.write(data, encoding) followed by socket.end().\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "data", + "optional": true + }, + { + "name": "encoding", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "socket.destroy()", + "type": "method", + "name": "destroy", + "desc": "

Ensures that no more I/O activity happens on this socket. Only necessary in\ncase of errors (parse error or so).\n\n

\n", + "signatures": [ + { + "params": [] + } + ] + }, + { + "textRaw": "socket.pause()", + "type": "method", + "name": "pause", + "desc": "

Pauses the reading of data. That is, 'data' events will not be emitted.\nUseful to throttle back an upload.\n\n

\n", + "signatures": [ + { + "params": [] + } + ] + }, + { + "textRaw": "socket.resume()", + "type": "method", + "name": "resume", + "desc": "

Resumes reading after a call to pause().\n\n

\n", + "signatures": [ + { + "params": [] + } + ] + }, + { + "textRaw": "socket.setTimeout(timeout, [callback])", + "type": "method", + "name": "setTimeout", + "desc": "

Sets the socket to timeout after timeout milliseconds of inactivity on\nthe socket. By default net.Socket do not have a timeout.\n\n

\n

When an idle timeout is triggered the socket will receive a 'timeout'\nevent but the connection will not be severed. The user must manually end()\nor destroy() the socket.\n\n

\n

If timeout is 0, then the existing idle timeout is disabled.\n\n

\n

The optional callback parameter will be added as a one time listener for the\n'timeout' event.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "timeout" + }, + { + "name": "callback", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "socket.setNoDelay([noDelay])", + "type": "method", + "name": "setNoDelay", + "desc": "

Disables the Nagle algorithm. By default TCP connections use the Nagle\nalgorithm, they buffer data before sending it off. Setting true for\nnoDelay will immediately fire off data each time socket.write() is called.\nnoDelay defaults to true.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "noDelay", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "socket.setKeepAlive([enable], [initialDelay])", + "type": "method", + "name": "setKeepAlive", + "desc": "

Enable/disable keep-alive functionality, and optionally set the initial\ndelay before the first keepalive probe is sent on an idle socket.\nenable defaults to false.\n\n

\n

Set initialDelay (in milliseconds) to set the delay between the last\ndata packet received and the first keepalive probe. Setting 0 for\ninitialDelay will leave the value unchanged from the default\n(or previous) setting. Defaults to 0.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "enable", + "optional": true + }, + { + "name": "initialDelay", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "socket.address()", + "type": "method", + "name": "address", + "desc": "

Returns the bound address, the address family name and port of the\nsocket as reported by the operating system. Returns an object with\nthree properties, e.g.\n{ port: 12346, family: 'IPv4', address: '127.0.0.1' }\n\n

\n", + "signatures": [ + { + "params": [] + } + ] + } + ], + "properties": [ + { + "textRaw": "socket.bufferSize", + "name": "bufferSize", + "desc": "

net.Socket has the property that socket.write() always works. This is to\nhelp users get up and running quickly. The computer cannot always keep up\nwith the amount of data that is written to a socket - the network connection\nsimply might be too slow. Node will internally queue up the data written to a\nsocket and send it out over the wire when it is possible. (Internally it is\npolling on the socket's file descriptor for being writable).\n\n

\n

The consequence of this internal buffering is that memory may grow. This\nproperty shows the number of characters currently buffered to be written.\n(Number of characters is approximately equal to the number of bytes to be\nwritten, but the buffer may contain strings, and the strings are lazily\nencoded, so the exact number of bytes is not known.)\n\n

\n

Users who experience large or growing bufferSize should attempt to\n"throttle" the data flows in their program with pause() and resume().\n\n\n

\n" + }, + { + "textRaw": "socket.remoteAddress", + "name": "remoteAddress", + "desc": "

The string representation of the remote IP address. For example,\n'74.125.127.100' or '2001:4860:a005::68'.\n\n

\n" + }, + { + "textRaw": "socket.remotePort", + "name": "remotePort", + "desc": "

The numeric representation of the remote port. For example,\n80 or 21.\n\n

\n" + }, + { + "textRaw": "socket.bytesRead", + "name": "bytesRead", + "desc": "

The amount of received bytes.\n\n

\n" + }, + { + "textRaw": "socket.bytesWritten", + "name": "bytesWritten", + "desc": "

The amount of bytes sent.\n\n\n

\n

net.Socket instances are [EventEmitter][] with the following events:\n\n

\n" + } + ], + "events": [ + { + "textRaw": "Event: 'connect'", + "type": "event", + "name": "connect", + "desc": "

Emitted when a socket connection is successfully established.\nSee connect().\n\n

\n", + "params": [] + }, + { + "textRaw": "Event: 'data'", + "type": "event", + "name": "data", + "params": [], + "desc": "

Emitted when data is received. The argument data will be a Buffer or\nString. Encoding of data is set by socket.setEncoding().\n(See the [Readable Stream][] section for more information.)\n\n

\n

Note that the data will be lost if there is no listener when a Socket\nemits a 'data' event.\n\n

\n" + }, + { + "textRaw": "Event: 'end'", + "type": "event", + "name": "end", + "desc": "

Emitted when the other end of the socket sends a FIN packet.\n\n

\n

By default (allowHalfOpen == false) the socket will destroy its file\ndescriptor once it has written out its pending write queue. However, by\nsetting allowHalfOpen == true the socket will not automatically end()\nits side allowing the user to write arbitrary amounts of data, with the\ncaveat that the user is required to end() their side now.\n\n\n

\n", + "params": [] + }, + { + "textRaw": "Event: 'timeout'", + "type": "event", + "name": "timeout", + "desc": "

Emitted if the socket times out from inactivity. This is only to notify that\nthe socket has been idle. The user must manually close the connection.\n\n

\n

See also: socket.setTimeout()\n\n\n

\n", + "params": [] + }, + { + "textRaw": "Event: 'drain'", + "type": "event", + "name": "drain", + "desc": "

Emitted when the write buffer becomes empty. Can be used to throttle uploads.\n\n

\n

See also: the return values of socket.write()\n\n

\n", + "params": [] + }, + { + "textRaw": "Event: 'error'", + "type": "event", + "name": "error", + "params": [], + "desc": "

Emitted when an error occurs. The 'close' event will be called directly\nfollowing this event.\n\n

\n" + }, + { + "textRaw": "Event: 'close'", + "type": "event", + "name": "close", + "params": [], + "desc": "

Emitted once the socket is fully closed. The argument had_error is a boolean\nwhich says if the socket was closed due to a transmission error.\n\n

\n" + } + ] + } + ], + "type": "module", + "displayName": "net" + } + ] +} diff --git a/node-v0.8.14/doc/api/net.markdown b/node-v0.8.14/doc/api/net.markdown new file mode 100644 index 0000000..c5125e6 --- /dev/null +++ b/node-v0.8.14/doc/api/net.markdown @@ -0,0 +1,485 @@ +# net + + Stability: 3 - Stable + +The `net` module provides you with an asynchronous network wrapper. It contains +methods for creating both servers and clients (called streams). You can include +this module with `require('net');` + +## net.createServer([options], [connectionListener]) + +Creates a new TCP server. The `connectionListener` argument is +automatically set as a listener for the ['connection'][] event. + +`options` is an object with the following defaults: + + { allowHalfOpen: false + } + +If `allowHalfOpen` is `true`, then the socket won't automatically send a FIN +packet when the other end of the socket sends a FIN packet. The socket becomes +non-readable, but still writable. You should call the `end()` method explicitly. +See ['end'][] event for more information. + +Here is an example of an echo server which listens for connections +on port 8124: + + var net = require('net'); + var server = net.createServer(function(c) { //'connection' listener + console.log('server connected'); + c.on('end', function() { + console.log('server disconnected'); + }); + c.write('hello\r\n'); + c.pipe(c); + }); + server.listen(8124, function() { //'listening' listener + console.log('server bound'); + }); + +Test this by using `telnet`: + + telnet localhost 8124 + +To listen on the socket `/tmp/echo.sock` the third line from the last would +just be changed to + + server.listen('/tmp/echo.sock', function() { //'listening' listener + +Use `nc` to connect to a UNIX domain socket server: + + nc -U /tmp/echo.sock + +## net.connect(options, [connectionListener]) +## net.createConnection(options, [connectionListener]) + +Constructs a new socket object and opens the socket to the given location. +When the socket is established, the ['connect'][] event will be emitted. + +For TCP sockets, `options` argument should be an object which specifies: + + - `port`: Port the client should connect to (Required). + + - `host`: Host the client should connect to. Defaults to `'localhost'`. + + - `localAddress`: Local interface to bind to for network connections. + +For UNIX domain sockets, `options` argument should be an object which specifies: + + - `path`: Path the client should connect to (Required). + +Common options are: + + - `allowHalfOpen`: if `true`, the socket won't automatically send + a FIN packet when the other end of the socket sends a FIN packet. + Defaults to `false`. See ['end'][] event for more information. + +The `connectListener` parameter will be added as an listener for the +['connect'][] event. + +Here is an example of a client of echo server as described previously: + + var net = require('net'); + var client = net.connect({port: 8124}, + function() { //'connect' listener + console.log('client connected'); + client.write('world!\r\n'); + }); + client.on('data', function(data) { + console.log(data.toString()); + client.end(); + }); + client.on('end', function() { + console.log('client disconnected'); + }); + +To connect on the socket `/tmp/echo.sock` the second line would just be +changed to + + var client = net.connect({path: '/tmp/echo.sock'}, + +## net.connect(port, [host], [connectListener]) +## net.createConnection(port, [host], [connectListener]) + +Creates a TCP connection to `port` on `host`. If `host` is omitted, +`'localhost'` will be assumed. +The `connectListener` parameter will be added as an listener for the +['connect'][] event. + +## net.connect(path, [connectListener]) +## net.createConnection(path, [connectListener]) + +Creates unix socket connection to `path`. +The `connectListener` parameter will be added as an listener for the +['connect'][] event. + +## Class: net.Server + +This class is used to create a TCP or UNIX server. +A server is a `net.Socket` that can listen for new incoming connections. + +### server.listen(port, [host], [backlog], [callback]) + +Begin accepting connections on the specified `port` and `host`. If the +`host` is omitted, the server will accept connections directed to any +IPv4 address (`INADDR_ANY`). A port value of zero will assign a random port. + +Backlog is the maximum length of the queue of pending connections. +The actual length will be determined by your OS through sysctl settings such as +`tcp_max_syn_backlog` and `somaxconn` on linux. The default value of this +parameter is 511 (not 512). + +This function is asynchronous. When the server has been bound, +['listening'][] event will be emitted. The last parameter `callback` +will be added as an listener for the ['listening'][] event. + +One issue some users run into is getting `EADDRINUSE` errors. This means that +another server is already running on the requested port. One way of handling this +would be to wait a second and then try again. This can be done with + + server.on('error', function (e) { + if (e.code == 'EADDRINUSE') { + console.log('Address in use, retrying...'); + setTimeout(function () { + server.close(); + server.listen(PORT, HOST); + }, 1000); + } + }); + +(Note: All sockets in Node set `SO_REUSEADDR` already) + + +### server.listen(path, [callback]) + +Start a UNIX socket server listening for connections on the given `path`. + +This function is asynchronous. When the server has been bound, +['listening'][] event will be emitted. The last parameter `callback` +will be added as an listener for the ['listening'][] event. + +### server.listen(handle, [callback]) + +* `handle` {Object} +* `callback` {Function} + +The `handle` object can be set to either a server or socket (anything +with an underlying `_handle` member), or a `{fd: }` object. + +This will cause the server to accept connections on the specified +handle, but it is presumed that the file descriptor or handle has +already been bound to a port or domain socket. + +Listening on a file descriptor is not supported on Windows. + +This function is asynchronous. When the server has been bound, +['listening'](#event_listening_) event will be emitted. +the last parameter `callback` will be added as an listener for the +['listening'](#event_listening_) event. + +### server.close([callback]) + +Stops the server from accepting new connections and keeps existing +connections. This function is asynchronous, the server is finally +closed when all connections are ended and the server emits a `'close'` +event. Optionally, you can pass a callback to listen for the `'close'` +event. + +### server.address() + +Returns the bound address, the address family name and port of the server +as reported by the operating system. +Useful to find which port was assigned when giving getting an OS-assigned address. +Returns an object with three properties, e.g. +`{ port: 12346, family: 'IPv4', address: '127.0.0.1' }` + +Example: + + var server = net.createServer(function (socket) { + socket.end("goodbye\n"); + }); + + // grab a random port. + server.listen(function() { + address = server.address(); + console.log("opened server on %j", address); + }); + +Don't call `server.address()` until the `'listening'` event has been emitted. + +### server.maxConnections + +Set this property to reject connections when the server's connection count gets +high. + +It is not recommended to use this option once a socket has been sent to a child +with `child_process.fork()`. + +### server.connections + +The number of concurrent connections on the server. + +This becomes `null` when sending a socket to a child with `child_process.fork()`. + +`net.Server` is an [EventEmitter][] with the following events: + +### Event: 'listening' + +Emitted when the server has been bound after calling `server.listen`. + +### Event: 'connection' + +* {Socket object} The connection object + +Emitted when a new connection is made. `socket` is an instance of +`net.Socket`. + +### Event: 'close' + +Emitted when the server closes. Note that if connections exist, this +event is not emitted until all connections are ended. + +### Event: 'error' + +* {Error Object} + +Emitted when an error occurs. The `'close'` event will be called directly +following this event. See example in discussion of `server.listen`. + +## Class: net.Socket + +This object is an abstraction of a TCP or UNIX socket. `net.Socket` +instances implement a duplex Stream interface. They can be created by the +user and used as a client (with `connect()`) or they can be created by Node +and passed to the user through the `'connection'` event of a server. + +### new net.Socket([options]) + +Construct a new socket object. + +`options` is an object with the following defaults: + + { fd: null + type: null + allowHalfOpen: false + } + +`fd` allows you to specify the existing file descriptor of socket. `type` +specified underlying protocol. It can be `'tcp4'`, `'tcp6'`, or `'unix'`. +About `allowHalfOpen`, refer to `createServer()` and `'end'` event. + +### socket.connect(port, [host], [connectListener]) +### socket.connect(path, [connectListener]) + +Opens the connection for a given socket. If `port` and `host` are given, +then the socket will be opened as a TCP socket, if `host` is omitted, +`localhost` will be assumed. If a `path` is given, the socket will be +opened as a unix socket to that path. + +Normally this method is not needed, as `net.createConnection` opens the +socket. Use this only if you are implementing a custom Socket or if a +Socket is closed and you want to reuse it to connect to another server. + +This function is asynchronous. When the ['connect'][] event is emitted the +socket is established. If there is a problem connecting, the `'connect'` event +will not be emitted, the `'error'` event will be emitted with the exception. + +The `connectListener` parameter will be added as an listener for the +['connect'][] event. + + +### socket.bufferSize + +`net.Socket` has the property that `socket.write()` always works. This is to +help users get up and running quickly. The computer cannot always keep up +with the amount of data that is written to a socket - the network connection +simply might be too slow. Node will internally queue up the data written to a +socket and send it out over the wire when it is possible. (Internally it is +polling on the socket's file descriptor for being writable). + +The consequence of this internal buffering is that memory may grow. This +property shows the number of characters currently buffered to be written. +(Number of characters is approximately equal to the number of bytes to be +written, but the buffer may contain strings, and the strings are lazily +encoded, so the exact number of bytes is not known.) + +Users who experience large or growing `bufferSize` should attempt to +"throttle" the data flows in their program with `pause()` and `resume()`. + + +### socket.setEncoding([encoding]) + +Set the encoding for the socket as a Readable Stream. See +[stream.setEncoding()][] for more information. + +### socket.write(data, [encoding], [callback]) + +Sends data on the socket. The second parameter specifies the encoding in the +case of a string--it defaults to UTF8 encoding. + +Returns `true` if the entire data was flushed successfully to the kernel +buffer. Returns `false` if all or part of the data was queued in user memory. +`'drain'` will be emitted when the buffer is again free. + +The optional `callback` parameter will be executed when the data is finally +written out - this may not be immediately. + +### socket.end([data], [encoding]) + +Half-closes the socket. i.e., it sends a FIN packet. It is possible the +server will still send some data. + +If `data` is specified, it is equivalent to calling +`socket.write(data, encoding)` followed by `socket.end()`. + +### socket.destroy() + +Ensures that no more I/O activity happens on this socket. Only necessary in +case of errors (parse error or so). + +### socket.pause() + +Pauses the reading of data. That is, `'data'` events will not be emitted. +Useful to throttle back an upload. + +### socket.resume() + +Resumes reading after a call to `pause()`. + +### socket.setTimeout(timeout, [callback]) + +Sets the socket to timeout after `timeout` milliseconds of inactivity on +the socket. By default `net.Socket` do not have a timeout. + +When an idle timeout is triggered the socket will receive a `'timeout'` +event but the connection will not be severed. The user must manually `end()` +or `destroy()` the socket. + +If `timeout` is 0, then the existing idle timeout is disabled. + +The optional `callback` parameter will be added as a one time listener for the +`'timeout'` event. + +### socket.setNoDelay([noDelay]) + +Disables the Nagle algorithm. By default TCP connections use the Nagle +algorithm, they buffer data before sending it off. Setting `true` for +`noDelay` will immediately fire off data each time `socket.write()` is called. +`noDelay` defaults to `true`. + +### socket.setKeepAlive([enable], [initialDelay]) + +Enable/disable keep-alive functionality, and optionally set the initial +delay before the first keepalive probe is sent on an idle socket. +`enable` defaults to `false`. + +Set `initialDelay` (in milliseconds) to set the delay between the last +data packet received and the first keepalive probe. Setting 0 for +initialDelay will leave the value unchanged from the default +(or previous) setting. Defaults to `0`. + +### socket.address() + +Returns the bound address, the address family name and port of the +socket as reported by the operating system. Returns an object with +three properties, e.g. +`{ port: 12346, family: 'IPv4', address: '127.0.0.1' }` + +### socket.remoteAddress + +The string representation of the remote IP address. For example, +`'74.125.127.100'` or `'2001:4860:a005::68'`. + +### socket.remotePort + +The numeric representation of the remote port. For example, +`80` or `21`. + +### socket.bytesRead + +The amount of received bytes. + +### socket.bytesWritten + +The amount of bytes sent. + + +`net.Socket` instances are [EventEmitter][] with the following events: + +### Event: 'connect' + +Emitted when a socket connection is successfully established. +See `connect()`. + +### Event: 'data' + +* {Buffer object} + +Emitted when data is received. The argument `data` will be a `Buffer` or +`String`. Encoding of data is set by `socket.setEncoding()`. +(See the [Readable Stream][] section for more information.) + +Note that the __data will be lost__ if there is no listener when a `Socket` +emits a `'data'` event. + +### Event: 'end' + +Emitted when the other end of the socket sends a FIN packet. + +By default (`allowHalfOpen == false`) the socket will destroy its file +descriptor once it has written out its pending write queue. However, by +setting `allowHalfOpen == true` the socket will not automatically `end()` +its side allowing the user to write arbitrary amounts of data, with the +caveat that the user is required to `end()` their side now. + + +### Event: 'timeout' + +Emitted if the socket times out from inactivity. This is only to notify that +the socket has been idle. The user must manually close the connection. + +See also: `socket.setTimeout()` + + +### Event: 'drain' + +Emitted when the write buffer becomes empty. Can be used to throttle uploads. + +See also: the return values of `socket.write()` + +### Event: 'error' + +* {Error object} + +Emitted when an error occurs. The `'close'` event will be called directly +following this event. + +### Event: 'close' + +* `had_error` {Boolean} true if the socket had a transmission error + +Emitted once the socket is fully closed. The argument `had_error` is a boolean +which says if the socket was closed due to a transmission error. + +## net.isIP(input) + +Tests if input is an IP address. Returns 0 for invalid strings, +returns 4 for IP version 4 addresses, and returns 6 for IP version 6 addresses. + + +## net.isIPv4(input) + +Returns true if input is a version 4 IP address, otherwise returns false. + + +## net.isIPv6(input) + +Returns true if input is a version 6 IP address, otherwise returns false. + +['connect']: #net_event_connect +['connection']: #net_event_connection +['end']: #net_event_end +[EventEmitter]: events.html#events_class_events_eventemitter +['listening']: #net_event_listening +[Readable Stream]: stream.html#stream_readable_stream +[stream.setEncoding()]: stream.html#stream_stream_setencoding_encoding diff --git a/node-v0.8.14/doc/api/os.html b/node-v0.8.14/doc/api/os.html new file mode 100644 index 0000000..4c8e847 --- /dev/null +++ b/node-v0.8.14/doc/api/os.html @@ -0,0 +1,241 @@ + + + + + os Node.js v0.8.14 Manual & Documentation + + + + + +
+ + + +
+
+ + +
+
+

Node.js v0.8.14 Manual & Documentation

+ +
+
+ + + +
+

os#

+
Stability: 4 - API Frozen
+

Provides a few basic operating-system related utility functions. + +

+

Use require('os') to access this module. + +

+

os.tmpDir()#

+

Returns the operating system's default directory for temp files. + +

+

os.hostname()#

+

Returns the hostname of the operating system. + +

+

os.type()#

+

Returns the operating system name. + +

+

os.platform()#

+

Returns the operating system platform. + +

+

os.arch()#

+

Returns the operating system CPU architecture. + +

+

os.release()#

+

Returns the operating system release. + +

+

os.uptime()#

+

Returns the system uptime in seconds. + +

+

os.loadavg()#

+

Returns an array containing the 1, 5, and 15 minute load averages. + +

+

os.totalmem()#

+

Returns the total amount of system memory in bytes. + +

+

os.freemem()#

+

Returns the amount of free system memory in bytes. + +

+

os.cpus()#

+

Returns an array of objects containing information about each CPU/core installed: model, speed (in MHz), and times (an object containing the number of CPU ticks spent in: user, nice, sys, idle, and irq). + +

+

Example inspection of os.cpus: + +

+
[ { model: 'Intel(R) Core(TM) i7 CPU         860  @ 2.80GHz',
+    speed: 2926,
+    times:
+     { user: 252020,
+       nice: 0,
+       sys: 30340,
+       idle: 1070356870,
+       irq: 0 } },
+  { model: 'Intel(R) Core(TM) i7 CPU         860  @ 2.80GHz',
+    speed: 2926,
+    times:
+     { user: 306960,
+       nice: 0,
+       sys: 26980,
+       idle: 1071569080,
+       irq: 0 } },
+  { model: 'Intel(R) Core(TM) i7 CPU         860  @ 2.80GHz',
+    speed: 2926,
+    times:
+     { user: 248450,
+       nice: 0,
+       sys: 21750,
+       idle: 1070919370,
+       irq: 0 } },
+  { model: 'Intel(R) Core(TM) i7 CPU         860  @ 2.80GHz',
+    speed: 2926,
+    times:
+     { user: 256880,
+       nice: 0,
+       sys: 19430,
+       idle: 1070905480,
+       irq: 20 } },
+  { model: 'Intel(R) Core(TM) i7 CPU         860  @ 2.80GHz',
+    speed: 2926,
+    times:
+     { user: 511580,
+       nice: 20,
+       sys: 40900,
+       idle: 1070842510,
+       irq: 0 } },
+  { model: 'Intel(R) Core(TM) i7 CPU         860  @ 2.80GHz',
+    speed: 2926,
+    times:
+     { user: 291660,
+       nice: 0,
+       sys: 34360,
+       idle: 1070888000,
+       irq: 10 } },
+  { model: 'Intel(R) Core(TM) i7 CPU         860  @ 2.80GHz',
+    speed: 2926,
+    times:
+     { user: 308260,
+       nice: 0,
+       sys: 55410,
+       idle: 1071129970,
+       irq: 880 } },
+  { model: 'Intel(R) Core(TM) i7 CPU         860  @ 2.80GHz',
+    speed: 2926,
+    times:
+     { user: 266450,
+       nice: 1480,
+       sys: 34920,
+       idle: 1072572010,
+       irq: 30 } } ]
+

os.networkInterfaces()#

+

Get a list of network interfaces: + +

+
{ lo0: 
+   [ { address: '::1', family: 'IPv6', internal: true },
+     { address: 'fe80::1', family: 'IPv6', internal: true },
+     { address: '127.0.0.1', family: 'IPv4', internal: true } ],
+  en1: 
+   [ { address: 'fe80::cabc:c8ff:feef:f996', family: 'IPv6',
+       internal: false },
+     { address: '10.0.1.123', family: 'IPv4', internal: false } ],
+  vmnet1: [ { address: '10.99.99.254', family: 'IPv4', internal: false } ],
+  vmnet8: [ { address: '10.88.88.1', family: 'IPv4', internal: false } ],
+  ppp0: [ { address: '10.2.0.231', family: 'IPv4', internal: false } ] }
+

os.EOL#

+

A constant defining the appropriate End-of-line marker for the operating system. +

+ +
+
+
+ + + + + + + + + diff --git a/node-v0.8.14/doc/api/os.json b/node-v0.8.14/doc/api/os.json new file mode 100644 index 0000000..c4ae7cb --- /dev/null +++ b/node-v0.8.14/doc/api/os.json @@ -0,0 +1,155 @@ +{ + "source": "doc/api/os.markdown", + "modules": [ + { + "textRaw": "os", + "name": "os", + "stability": 4, + "stabilityText": "API Frozen", + "desc": "

Provides a few basic operating-system related utility functions.\n\n

\n

Use require('os') to access this module.\n\n

\n", + "methods": [ + { + "textRaw": "os.tmpDir()", + "type": "method", + "name": "tmpDir", + "desc": "

Returns the operating system's default directory for temp files.\n\n

\n", + "signatures": [ + { + "params": [] + } + ] + }, + { + "textRaw": "os.hostname()", + "type": "method", + "name": "hostname", + "desc": "

Returns the hostname of the operating system.\n\n

\n", + "signatures": [ + { + "params": [] + } + ] + }, + { + "textRaw": "os.type()", + "type": "method", + "name": "type", + "desc": "

Returns the operating system name.\n\n

\n", + "signatures": [ + { + "params": [] + } + ] + }, + { + "textRaw": "os.platform()", + "type": "method", + "name": "platform", + "desc": "

Returns the operating system platform.\n\n

\n", + "signatures": [ + { + "params": [] + } + ] + }, + { + "textRaw": "os.arch()", + "type": "method", + "name": "arch", + "desc": "

Returns the operating system CPU architecture.\n\n

\n", + "signatures": [ + { + "params": [] + } + ] + }, + { + "textRaw": "os.release()", + "type": "method", + "name": "release", + "desc": "

Returns the operating system release.\n\n

\n", + "signatures": [ + { + "params": [] + } + ] + }, + { + "textRaw": "os.uptime()", + "type": "method", + "name": "uptime", + "desc": "

Returns the system uptime in seconds.\n\n

\n", + "signatures": [ + { + "params": [] + } + ] + }, + { + "textRaw": "os.loadavg()", + "type": "method", + "name": "loadavg", + "desc": "

Returns an array containing the 1, 5, and 15 minute load averages.\n\n

\n", + "signatures": [ + { + "params": [] + } + ] + }, + { + "textRaw": "os.totalmem()", + "type": "method", + "name": "totalmem", + "desc": "

Returns the total amount of system memory in bytes.\n\n

\n", + "signatures": [ + { + "params": [] + } + ] + }, + { + "textRaw": "os.freemem()", + "type": "method", + "name": "freemem", + "desc": "

Returns the amount of free system memory in bytes.\n\n

\n", + "signatures": [ + { + "params": [] + } + ] + }, + { + "textRaw": "os.cpus()", + "type": "method", + "name": "cpus", + "desc": "

Returns an array of objects containing information about each CPU/core installed: model, speed (in MHz), and times (an object containing the number of CPU ticks spent in: user, nice, sys, idle, and irq).\n\n

\n

Example inspection of os.cpus:\n\n

\n
[ { model: 'Intel(R) Core(TM) i7 CPU         860  @ 2.80GHz',\n    speed: 2926,\n    times:\n     { user: 252020,\n       nice: 0,\n       sys: 30340,\n       idle: 1070356870,\n       irq: 0 } },\n  { model: 'Intel(R) Core(TM) i7 CPU         860  @ 2.80GHz',\n    speed: 2926,\n    times:\n     { user: 306960,\n       nice: 0,\n       sys: 26980,\n       idle: 1071569080,\n       irq: 0 } },\n  { model: 'Intel(R) Core(TM) i7 CPU         860  @ 2.80GHz',\n    speed: 2926,\n    times:\n     { user: 248450,\n       nice: 0,\n       sys: 21750,\n       idle: 1070919370,\n       irq: 0 } },\n  { model: 'Intel(R) Core(TM) i7 CPU         860  @ 2.80GHz',\n    speed: 2926,\n    times:\n     { user: 256880,\n       nice: 0,\n       sys: 19430,\n       idle: 1070905480,\n       irq: 20 } },\n  { model: 'Intel(R) Core(TM) i7 CPU         860  @ 2.80GHz',\n    speed: 2926,\n    times:\n     { user: 511580,\n       nice: 20,\n       sys: 40900,\n       idle: 1070842510,\n       irq: 0 } },\n  { model: 'Intel(R) Core(TM) i7 CPU         860  @ 2.80GHz',\n    speed: 2926,\n    times:\n     { user: 291660,\n       nice: 0,\n       sys: 34360,\n       idle: 1070888000,\n       irq: 10 } },\n  { model: 'Intel(R) Core(TM) i7 CPU         860  @ 2.80GHz',\n    speed: 2926,\n    times:\n     { user: 308260,\n       nice: 0,\n       sys: 55410,\n       idle: 1071129970,\n       irq: 880 } },\n  { model: 'Intel(R) Core(TM) i7 CPU         860  @ 2.80GHz',\n    speed: 2926,\n    times:\n     { user: 266450,\n       nice: 1480,\n       sys: 34920,\n       idle: 1072572010,\n       irq: 30 } } ]
\n", + "signatures": [ + { + "params": [] + } + ] + }, + { + "textRaw": "os.networkInterfaces()", + "type": "method", + "name": "networkInterfaces", + "desc": "

Get a list of network interfaces:\n\n

\n
{ lo0: \n   [ { address: '::1', family: 'IPv6', internal: true },\n     { address: 'fe80::1', family: 'IPv6', internal: true },\n     { address: '127.0.0.1', family: 'IPv4', internal: true } ],\n  en1: \n   [ { address: 'fe80::cabc:c8ff:feef:f996', family: 'IPv6',\n       internal: false },\n     { address: '10.0.1.123', family: 'IPv4', internal: false } ],\n  vmnet1: [ { address: '10.99.99.254', family: 'IPv4', internal: false } ],\n  vmnet8: [ { address: '10.88.88.1', family: 'IPv4', internal: false } ],\n  ppp0: [ { address: '10.2.0.231', family: 'IPv4', internal: false } ] }
\n", + "signatures": [ + { + "params": [] + } + ] + } + ], + "properties": [ + { + "textRaw": "os.EOL", + "name": "EOL", + "desc": "

A constant defining the appropriate End-of-line marker for the operating system.\n

\n" + } + ], + "type": "module", + "displayName": "os" + } + ] +} diff --git a/node-v0.8.14/doc/api/os.markdown b/node-v0.8.14/doc/api/os.markdown new file mode 100644 index 0000000..b5fffcf --- /dev/null +++ b/node-v0.8.14/doc/api/os.markdown @@ -0,0 +1,138 @@ +# os + + Stability: 4 - API Frozen + +Provides a few basic operating-system related utility functions. + +Use `require('os')` to access this module. + +## os.tmpDir() + +Returns the operating system's default directory for temp files. + +## os.hostname() + +Returns the hostname of the operating system. + +## os.type() + +Returns the operating system name. + +## os.platform() + +Returns the operating system platform. + +## os.arch() + +Returns the operating system CPU architecture. + +## os.release() + +Returns the operating system release. + +## os.uptime() + +Returns the system uptime in seconds. + +## os.loadavg() + +Returns an array containing the 1, 5, and 15 minute load averages. + +## os.totalmem() + +Returns the total amount of system memory in bytes. + +## os.freemem() + +Returns the amount of free system memory in bytes. + +## os.cpus() + +Returns an array of objects containing information about each CPU/core installed: model, speed (in MHz), and times (an object containing the number of CPU ticks spent in: user, nice, sys, idle, and irq). + +Example inspection of os.cpus: + + [ { model: 'Intel(R) Core(TM) i7 CPU 860 @ 2.80GHz', + speed: 2926, + times: + { user: 252020, + nice: 0, + sys: 30340, + idle: 1070356870, + irq: 0 } }, + { model: 'Intel(R) Core(TM) i7 CPU 860 @ 2.80GHz', + speed: 2926, + times: + { user: 306960, + nice: 0, + sys: 26980, + idle: 1071569080, + irq: 0 } }, + { model: 'Intel(R) Core(TM) i7 CPU 860 @ 2.80GHz', + speed: 2926, + times: + { user: 248450, + nice: 0, + sys: 21750, + idle: 1070919370, + irq: 0 } }, + { model: 'Intel(R) Core(TM) i7 CPU 860 @ 2.80GHz', + speed: 2926, + times: + { user: 256880, + nice: 0, + sys: 19430, + idle: 1070905480, + irq: 20 } }, + { model: 'Intel(R) Core(TM) i7 CPU 860 @ 2.80GHz', + speed: 2926, + times: + { user: 511580, + nice: 20, + sys: 40900, + idle: 1070842510, + irq: 0 } }, + { model: 'Intel(R) Core(TM) i7 CPU 860 @ 2.80GHz', + speed: 2926, + times: + { user: 291660, + nice: 0, + sys: 34360, + idle: 1070888000, + irq: 10 } }, + { model: 'Intel(R) Core(TM) i7 CPU 860 @ 2.80GHz', + speed: 2926, + times: + { user: 308260, + nice: 0, + sys: 55410, + idle: 1071129970, + irq: 880 } }, + { model: 'Intel(R) Core(TM) i7 CPU 860 @ 2.80GHz', + speed: 2926, + times: + { user: 266450, + nice: 1480, + sys: 34920, + idle: 1072572010, + irq: 30 } } ] + +## os.networkInterfaces() + +Get a list of network interfaces: + + { lo0: + [ { address: '::1', family: 'IPv6', internal: true }, + { address: 'fe80::1', family: 'IPv6', internal: true }, + { address: '127.0.0.1', family: 'IPv4', internal: true } ], + en1: + [ { address: 'fe80::cabc:c8ff:feef:f996', family: 'IPv6', + internal: false }, + { address: '10.0.1.123', family: 'IPv4', internal: false } ], + vmnet1: [ { address: '10.99.99.254', family: 'IPv4', internal: false } ], + vmnet8: [ { address: '10.88.88.1', family: 'IPv4', internal: false } ], + ppp0: [ { address: '10.2.0.231', family: 'IPv4', internal: false } ] } + +## os.EOL + +A constant defining the appropriate End-of-line marker for the operating system. diff --git a/node-v0.8.14/doc/api/path.html b/node-v0.8.14/doc/api/path.html new file mode 100644 index 0000000..7874228 --- /dev/null +++ b/node-v0.8.14/doc/api/path.html @@ -0,0 +1,258 @@ + + + + + Path Node.js v0.8.14 Manual & Documentation + + + + + +
+ + + +
+
+ + +
+
+

Node.js v0.8.14 Manual & Documentation

+ +
+
+ + + +
+

Path#

+
Stability: 3 - Stable
+

This module contains utilities for handling and transforming file +paths. Almost all these methods perform only string transformations. +The file system is not consulted to check whether paths are valid. + +

+

Use require('path') to use this module. The following methods are provided: + +

+

path.normalize(p)#

+

Normalize a string path, taking care of '..' and '.' parts. + +

+

When multiple slashes are found, they're replaced by a single one; +when the path contains a trailing slash, it is preserved. +On windows backslashes are used. + +

+

Example: + +

+
path.normalize('/foo/bar//baz/asdf/quux/..')
+// returns
+'/foo/bar/baz/asdf'
+

path.join([path1], [path2], [...])#

+

Join all arguments together and normalize the resulting path. +Non-string arguments are ignored. + +

+

Example: + +

+
path.join('/foo', 'bar', 'baz/asdf', 'quux', '..')
+// returns
+'/foo/bar/baz/asdf'
+
+path.join('foo', {}, 'bar')
+// returns
+'foo/bar'
+

path.resolve([from ...], to)#

+

Resolves to to an absolute path. + +

+

If to isn't already absolute from arguments are prepended in right to left +order, until an absolute path is found. If after using all from paths still +no absolute path is found, the current working directory is used as well. The +resulting path is normalized, and trailing slashes are removed unless the path +gets resolved to the root directory. Non-string arguments are ignored. + +

+

Another way to think of it is as a sequence of cd commands in a shell. + +

+
path.resolve('foo/bar', '/tmp/file/', '..', 'a/../subfile')
+

Is similar to: + +

+
cd foo/bar
+cd /tmp/file/
+cd ..
+cd a/../subfile
+pwd
+

The difference is that the different paths don't need to exist and may also be +files. + +

+

Examples: + +

+
path.resolve('/foo/bar', './baz')
+// returns
+'/foo/bar/baz'
+
+path.resolve('/foo/bar', '/tmp/file/')
+// returns
+'/tmp/file'
+
+path.resolve('wwwroot', 'static_files/png/', '../gif/image.gif')
+// if currently in /home/myself/node, it returns
+'/home/myself/node/wwwroot/static_files/gif/image.gif'
+

path.relative(from, to)#

+

Solve the relative path from from to to. + +

+

At times we have two absolute paths, and we need to derive the relative +path from one to the other. This is actually the reverse transform of +path.resolve, which means we see that: + +

+
path.resolve(from, path.relative(from, to)) == path.resolve(to)
+

Examples: + +

+
path.relative('C:\\orandea\\test\\aaa', 'C:\\orandea\\impl\\bbb')
+// returns
+'..\\..\\impl\\bbb'
+
+path.relative('/data/orandea/test/aaa', '/data/orandea/impl/bbb')
+// returns
+'../../impl/bbb'
+

path.dirname(p)#

+

Return the directory name of a path. Similar to the Unix dirname command. + +

+

Example: + +

+
path.dirname('/foo/bar/baz/asdf/quux')
+// returns
+'/foo/bar/baz/asdf'
+

path.basename(p, [ext])#

+

Return the last portion of a path. Similar to the Unix basename command. + +

+

Example: + +

+
path.basename('/foo/bar/baz/asdf/quux.html')
+// returns
+'quux.html'
+
+path.basename('/foo/bar/baz/asdf/quux.html', '.html')
+// returns
+'quux'
+

path.extname(p)#

+

Return the extension of the path, from the last '.' to end of string +in the last portion of the path. If there is no '.' in the last portion +of the path or the first character of it is '.', then it returns +an empty string. Examples: + +

+
path.extname('index.html')
+// returns
+'.html'
+
+path.extname('index.')
+// returns
+'.'
+
+path.extname('index')
+// returns
+''
+

path.sep#

+

The platform-specific file separator. '\\' or '/'. + +

+

An example on linux: + +

+
'foo/bar/baz'.split(path.sep)
+// returns
+['foo', 'bar', 'baz']
+

An example on windows: + +

+
'foo\\bar\\baz'.split(path.sep)
+// returns
+['foo', 'bar', 'baz']
+ +
+
+
+ + + + + + + + + diff --git a/node-v0.8.14/doc/api/path.json b/node-v0.8.14/doc/api/path.json new file mode 100644 index 0000000..7b4dc79 --- /dev/null +++ b/node-v0.8.14/doc/api/path.json @@ -0,0 +1,148 @@ +{ + "source": "doc/api/path.markdown", + "modules": [ + { + "textRaw": "Path", + "name": "path", + "stability": 3, + "stabilityText": "Stable", + "desc": "

This module contains utilities for handling and transforming file\npaths. Almost all these methods perform only string transformations.\nThe file system is not consulted to check whether paths are valid.\n\n

\n

Use require('path') to use this module. The following methods are provided:\n\n

\n", + "methods": [ + { + "textRaw": "path.normalize(p)", + "type": "method", + "name": "normalize", + "desc": "

Normalize a string path, taking care of '..' and '.' parts.\n\n

\n

When multiple slashes are found, they're replaced by a single one;\nwhen the path contains a trailing slash, it is preserved.\nOn windows backslashes are used. \n\n

\n

Example:\n\n

\n
path.normalize('/foo/bar//baz/asdf/quux/..')\n// returns\n'/foo/bar/baz/asdf'
\n", + "signatures": [ + { + "params": [ + { + "name": "p" + } + ] + } + ] + }, + { + "textRaw": "path.join([path1], [path2], [...])", + "type": "method", + "name": "join", + "desc": "

Join all arguments together and normalize the resulting path.\nNon-string arguments are ignored.\n\n

\n

Example:\n\n

\n
path.join('/foo', 'bar', 'baz/asdf', 'quux', '..')\n// returns\n'/foo/bar/baz/asdf'\n\npath.join('foo', {}, 'bar')\n// returns\n'foo/bar'
\n", + "signatures": [ + { + "params": [ + { + "name": "path1", + "optional": true + }, + { + "name": "path2", + "optional": true + }, + { + "name": "...", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "path.resolve([from ...], to)", + "type": "method", + "name": "resolve", + "desc": "

Resolves to to an absolute path.\n\n

\n

If to isn't already absolute from arguments are prepended in right to left\norder, until an absolute path is found. If after using all from paths still\nno absolute path is found, the current working directory is used as well. The\nresulting path is normalized, and trailing slashes are removed unless the path \ngets resolved to the root directory. Non-string arguments are ignored.\n\n

\n

Another way to think of it is as a sequence of cd commands in a shell.\n\n

\n
path.resolve('foo/bar', '/tmp/file/', '..', 'a/../subfile')
\n

Is similar to:\n\n

\n
cd foo/bar\ncd /tmp/file/\ncd ..\ncd a/../subfile\npwd
\n

The difference is that the different paths don't need to exist and may also be\nfiles.\n\n

\n

Examples:\n\n

\n
path.resolve('/foo/bar', './baz')\n// returns\n'/foo/bar/baz'\n\npath.resolve('/foo/bar', '/tmp/file/')\n// returns\n'/tmp/file'\n\npath.resolve('wwwroot', 'static_files/png/', '../gif/image.gif')\n// if currently in /home/myself/node, it returns\n'/home/myself/node/wwwroot/static_files/gif/image.gif'
\n", + "signatures": [ + { + "params": [ + { + "name": "from ...", + "optional": true + }, + { + "name": "to" + } + ] + } + ] + }, + { + "textRaw": "path.relative(from, to)", + "type": "method", + "name": "relative", + "desc": "

Solve the relative path from from to to.\n\n

\n

At times we have two absolute paths, and we need to derive the relative\npath from one to the other. This is actually the reverse transform of\npath.resolve, which means we see that:\n\n

\n
path.resolve(from, path.relative(from, to)) == path.resolve(to)
\n

Examples:\n\n

\n
path.relative('C:\\\\orandea\\\\test\\\\aaa', 'C:\\\\orandea\\\\impl\\\\bbb')\n// returns\n'..\\\\..\\\\impl\\\\bbb'\n\npath.relative('/data/orandea/test/aaa', '/data/orandea/impl/bbb')\n// returns\n'../../impl/bbb'
\n", + "signatures": [ + { + "params": [ + { + "name": "from" + }, + { + "name": "to" + } + ] + } + ] + }, + { + "textRaw": "path.dirname(p)", + "type": "method", + "name": "dirname", + "desc": "

Return the directory name of a path. Similar to the Unix dirname command.\n\n

\n

Example:\n\n

\n
path.dirname('/foo/bar/baz/asdf/quux')\n// returns\n'/foo/bar/baz/asdf'
\n", + "signatures": [ + { + "params": [ + { + "name": "p" + } + ] + } + ] + }, + { + "textRaw": "path.basename(p, [ext])", + "type": "method", + "name": "basename", + "desc": "

Return the last portion of a path. Similar to the Unix basename command.\n\n

\n

Example:\n\n

\n
path.basename('/foo/bar/baz/asdf/quux.html')\n// returns\n'quux.html'\n\npath.basename('/foo/bar/baz/asdf/quux.html', '.html')\n// returns\n'quux'
\n", + "signatures": [ + { + "params": [ + { + "name": "p" + }, + { + "name": "ext", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "path.extname(p)", + "type": "method", + "name": "extname", + "desc": "

Return the extension of the path, from the last '.' to end of string\nin the last portion of the path. If there is no '.' in the last portion\nof the path or the first character of it is '.', then it returns\nan empty string. Examples:\n\n

\n
path.extname('index.html')\n// returns\n'.html'\n\npath.extname('index.')\n// returns\n'.'\n\npath.extname('index')\n// returns\n''
\n", + "signatures": [ + { + "params": [ + { + "name": "p" + } + ] + } + ] + } + ], + "properties": [ + { + "textRaw": "path.sep", + "name": "sep", + "desc": "

The platform-specific file separator. '\\\\' or '/'.\n\n

\n

An example on linux:\n\n

\n
'foo/bar/baz'.split(path.sep)\n// returns\n['foo', 'bar', 'baz']
\n

An example on windows:\n\n

\n
'foo\\\\bar\\\\baz'.split(path.sep)\n// returns\n['foo', 'bar', 'baz']
\n" + } + ], + "type": "module", + "displayName": "Path" + } + ] +} diff --git a/node-v0.8.14/doc/api/path.markdown b/node-v0.8.14/doc/api/path.markdown new file mode 100644 index 0000000..d178b53 --- /dev/null +++ b/node-v0.8.14/doc/api/path.markdown @@ -0,0 +1,156 @@ +# Path + + Stability: 3 - Stable + +This module contains utilities for handling and transforming file +paths. Almost all these methods perform only string transformations. +The file system is not consulted to check whether paths are valid. + +Use `require('path')` to use this module. The following methods are provided: + +## path.normalize(p) + +Normalize a string path, taking care of `'..'` and `'.'` parts. + +When multiple slashes are found, they're replaced by a single one; +when the path contains a trailing slash, it is preserved. +On windows backslashes are used. + +Example: + + path.normalize('/foo/bar//baz/asdf/quux/..') + // returns + '/foo/bar/baz/asdf' + +## path.join([path1], [path2], [...]) + +Join all arguments together and normalize the resulting path. +Non-string arguments are ignored. + +Example: + + path.join('/foo', 'bar', 'baz/asdf', 'quux', '..') + // returns + '/foo/bar/baz/asdf' + + path.join('foo', {}, 'bar') + // returns + 'foo/bar' + +## path.resolve([from ...], to) + +Resolves `to` to an absolute path. + +If `to` isn't already absolute `from` arguments are prepended in right to left +order, until an absolute path is found. If after using all `from` paths still +no absolute path is found, the current working directory is used as well. The +resulting path is normalized, and trailing slashes are removed unless the path +gets resolved to the root directory. Non-string arguments are ignored. + +Another way to think of it is as a sequence of `cd` commands in a shell. + + path.resolve('foo/bar', '/tmp/file/', '..', 'a/../subfile') + +Is similar to: + + cd foo/bar + cd /tmp/file/ + cd .. + cd a/../subfile + pwd + +The difference is that the different paths don't need to exist and may also be +files. + +Examples: + + path.resolve('/foo/bar', './baz') + // returns + '/foo/bar/baz' + + path.resolve('/foo/bar', '/tmp/file/') + // returns + '/tmp/file' + + path.resolve('wwwroot', 'static_files/png/', '../gif/image.gif') + // if currently in /home/myself/node, it returns + '/home/myself/node/wwwroot/static_files/gif/image.gif' + +## path.relative(from, to) + +Solve the relative path from `from` to `to`. + +At times we have two absolute paths, and we need to derive the relative +path from one to the other. This is actually the reverse transform of +`path.resolve`, which means we see that: + + path.resolve(from, path.relative(from, to)) == path.resolve(to) + +Examples: + + path.relative('C:\\orandea\\test\\aaa', 'C:\\orandea\\impl\\bbb') + // returns + '..\\..\\impl\\bbb' + + path.relative('/data/orandea/test/aaa', '/data/orandea/impl/bbb') + // returns + '../../impl/bbb' + +## path.dirname(p) + +Return the directory name of a path. Similar to the Unix `dirname` command. + +Example: + + path.dirname('/foo/bar/baz/asdf/quux') + // returns + '/foo/bar/baz/asdf' + +## path.basename(p, [ext]) + +Return the last portion of a path. Similar to the Unix `basename` command. + +Example: + + path.basename('/foo/bar/baz/asdf/quux.html') + // returns + 'quux.html' + + path.basename('/foo/bar/baz/asdf/quux.html', '.html') + // returns + 'quux' + +## path.extname(p) + +Return the extension of the path, from the last '.' to end of string +in the last portion of the path. If there is no '.' in the last portion +of the path or the first character of it is '.', then it returns +an empty string. Examples: + + path.extname('index.html') + // returns + '.html' + + path.extname('index.') + // returns + '.' + + path.extname('index') + // returns + '' + +## path.sep + +The platform-specific file separator. `'\\'` or `'/'`. + +An example on linux: + + 'foo/bar/baz'.split(path.sep) + // returns + ['foo', 'bar', 'baz'] + +An example on windows: + + 'foo\\bar\\baz'.split(path.sep) + // returns + ['foo', 'bar', 'baz'] diff --git a/node-v0.8.14/doc/api/process.html b/node-v0.8.14/doc/api/process.html new file mode 100644 index 0000000..4856723 --- /dev/null +++ b/node-v0.8.14/doc/api/process.html @@ -0,0 +1,537 @@ + + + + + process Node.js v0.8.14 Manual & Documentation + + + + + +
+ + + +
+
+ + +
+
+

Node.js v0.8.14 Manual & Documentation

+ +
+
+ + + +
+

process#

+ + +

The process object is a global object and can be accessed from anywhere. +It is an instance of EventEmitter. + + +

+

Event: 'exit'#

+

Emitted when the process is about to exit. This is a good hook to perform +constant time checks of the module's state (like for unit tests). The main +event loop will no longer be run after the 'exit' callback finishes, so +timers may not be scheduled. + +

+

Example of listening for exit: + +

+
process.on('exit', function () {
+  process.nextTick(function () {
+   console.log('This will not run');
+  });
+  console.log('About to exit.');
+});
+

Event: 'uncaughtException'#

+

Emitted when an exception bubbles all the way back to the event loop. If a +listener is added for this exception, the default action (which is to print +a stack trace and exit) will not occur. + +

+

Example of listening for uncaughtException: + +

+
process.on('uncaughtException', function (err) {
+  console.log('Caught exception: ' + err);
+});
+
+setTimeout(function () {
+  console.log('This will still run.');
+}, 500);
+
+// Intentionally cause an exception, but don't catch it.
+nonexistentFunc();
+console.log('This will not run.');
+

Note that uncaughtException is a very crude mechanism for exception +handling and may be removed in the future. + +

+

Don't use it, use domains instead. If you do use it, restart +your application after every unhandled exception! + +

+

Do not use it as the node.js equivalent of On Error Resume Next. An +unhandled exception means your application - and by extension node.js itself - +is in an undefined state. Blindly resuming means anything could happen. + +

+

Think of resuming as pulling the power cord when you are upgrading your system. +Nine out of ten times nothing happens - but the 10th time, your system is bust. + +

+

You have been warned. + +

+

Signal Events#

+ + + +

Emitted when the processes receives a signal. See sigaction(2) for a list of +standard POSIX signal names such as SIGINT, SIGUSR1, etc. + +

+

Example of listening for SIGINT: + +

+
// Start reading from stdin so we don't exit.
+process.stdin.resume();
+
+process.on('SIGINT', function () {
+  console.log('Got SIGINT.  Press Control-D to exit.');
+});
+

An easy way to send the SIGINT signal is with Control-C in most terminal +programs. + + +

+

process.stdout#

+

A Writable Stream to stdout. + +

+

Example: the definition of console.log + +

+
console.log = function (d) {
+  process.stdout.write(d + '\n');
+};
+

process.stderr and process.stdout are unlike other streams in Node in +that writes to them are usually blocking. They are blocking in the case +that they refer to regular files or TTY file descriptors. In the case they +refer to pipes, they are non-blocking like other streams. + + +

+

process.stderr#

+

A writable stream to stderr. + +

+

process.stderr and process.stdout are unlike other streams in Node in +that writes to them are usually blocking. They are blocking in the case +that they refer to regular files or TTY file descriptors. In the case they +refer to pipes, they are non-blocking like other streams. + + +

+

process.stdin#

+

A Readable Stream for stdin. The stdin stream is paused by default, so one +must call process.stdin.resume() to read from it. + +

+

Example of opening standard input and listening for both events: + +

+
process.stdin.resume();
+process.stdin.setEncoding('utf8');
+
+process.stdin.on('data', function (chunk) {
+  process.stdout.write('data: ' + chunk);
+});
+
+process.stdin.on('end', function () {
+  process.stdout.write('end');
+});
+

process.argv#

+

An array containing the command line arguments. The first element will be +'node', the second element will be the name of the JavaScript file. The +next elements will be any additional command line arguments. + +

+
// print process.argv
+process.argv.forEach(function (val, index, array) {
+  console.log(index + ': ' + val);
+});
+

This will generate: + +

+
$ node process-2.js one two=three four
+0: node
+1: /Users/mjr/work/node/process-2.js
+2: one
+3: two=three
+4: four
+

process.execPath#

+

This is the absolute pathname of the executable that started the process. + +

+

Example: + +

+
/usr/local/bin/node
+

process.abort()#

+

This causes node to emit an abort. This will cause node to exit and +generate a core file. + +

+

process.chdir(directory)#

+

Changes the current working directory of the process or throws an exception if that fails. + +

+
console.log('Starting directory: ' + process.cwd());
+try {
+  process.chdir('/tmp');
+  console.log('New directory: ' + process.cwd());
+}
+catch (err) {
+  console.log('chdir: ' + err);
+}
+

process.cwd()#

+

Returns the current working directory of the process. + +

+
console.log('Current directory: ' + process.cwd());
+

process.env#

+

An object containing the user environment. See environ(7). + + +

+

process.exit([code])#

+

Ends the process with the specified code. If omitted, exit uses the +'success' code 0. + +

+

To exit with a 'failure' code: + +

+
process.exit(1);
+

The shell that executed node should see the exit code as 1. + + +

+

process.getgid()#

+

Note: this function is only available on POSIX platforms (i.e. not Windows) + +

+

Gets the group identity of the process. (See getgid(2).) +This is the numerical group id, not the group name. + +

+
if (process.getgid) {
+  console.log('Current gid: ' + process.getgid());
+}
+

process.setgid(id)#

+

Note: this function is only available on POSIX platforms (i.e. not Windows) + +

+

Sets the group identity of the process. (See setgid(2).) This accepts either +a numerical ID or a groupname string. If a groupname is specified, this method +blocks while resolving it to a numerical ID. + +

+
if (process.getgid && process.setgid) {
+  console.log('Current gid: ' + process.getgid());
+  try {
+    process.setgid(501);
+    console.log('New gid: ' + process.getgid());
+  }
+  catch (err) {
+    console.log('Failed to set gid: ' + err);
+  }
+}
+

process.getuid()#

+

Note: this function is only available on POSIX platforms (i.e. not Windows) + +

+

Gets the user identity of the process. (See getuid(2).) +This is the numerical userid, not the username. + +

+
if (process.getuid) {
+  console.log('Current uid: ' + process.getuid());
+}
+

process.setuid(id)#

+

Note: this function is only available on POSIX platforms (i.e. not Windows) + +

+

Sets the user identity of the process. (See setuid(2).) This accepts either +a numerical ID or a username string. If a username is specified, this method +blocks while resolving it to a numerical ID. + +

+
if (process.getuid && process.setuid) {
+  console.log('Current uid: ' + process.getuid());
+  try {
+    process.setuid(501);
+    console.log('New uid: ' + process.getuid());
+  }
+  catch (err) {
+    console.log('Failed to set uid: ' + err);
+  }
+}
+

process.version#

+

A compiled-in property that exposes NODE_VERSION. + +

+
console.log('Version: ' + process.version);
+

process.versions#

+

A property exposing version strings of node and its dependencies. + +

+
console.log(process.versions);
+

Will output: + +

+
{ node: '0.4.12',
+  v8: '3.1.8.26',
+  ares: '1.7.4',
+  ev: '4.4',
+  openssl: '1.0.0e-fips' }
+

process.config#

+

An Object containing the JavaScript representation of the configure options +that were used to compile the current node executable. This is the same as +the "config.gypi" file that was produced when running the ./configure script. + +

+

An example of the possible output looks like: + +

+
{ target_defaults:
+   { cflags: [],
+     default_configuration: 'Release',
+     defines: [],
+     include_dirs: [],
+     libraries: [] },
+  variables:
+   { host_arch: 'x64',
+     node_install_npm: 'true',
+     node_install_waf: 'true',
+     node_prefix: '',
+     node_shared_v8: 'false',
+     node_shared_zlib: 'false',
+     node_use_dtrace: 'false',
+     node_use_openssl: 'true',
+     node_shared_openssl: 'false',
+     strict_aliasing: 'true',
+     target_arch: 'x64',
+     v8_use_snapshot: 'true' } }
+

process.kill(pid, [signal])#

+

Send a signal to a process. pid is the process id and signal is the +string describing the signal to send. Signal names are strings like +'SIGINT' or 'SIGUSR1'. If omitted, the signal will be 'SIGTERM'. +See kill(2) for more information. + +

+

Note that just because the name of this function is process.kill, it is +really just a signal sender, like the kill system call. The signal sent +may do something other than kill the target process. + +

+

Example of sending a signal to yourself: + +

+
process.on('SIGHUP', function () {
+  console.log('Got SIGHUP signal.');
+});
+
+setTimeout(function () {
+  console.log('Exiting.');
+  process.exit(0);
+}, 100);
+
+process.kill(process.pid, 'SIGHUP');
+

process.pid#

+

The PID of the process. + +

+
console.log('This process is pid ' + process.pid);
+

process.title#

+

Getter/setter to set what is displayed in 'ps'. + + +

+

process.arch#

+

What processor architecture you're running on: 'arm', 'ia32', or 'x64'. + +

+
console.log('This processor architecture is ' + process.arch);
+

process.platform#

+

What platform you're running on: +'darwin', 'freebsd', 'linux', 'sunos' or 'win32' + +

+
console.log('This platform is ' + process.platform);
+

process.memoryUsage()#

+

Returns an object describing the memory usage of the Node process +measured in bytes. + +

+
var util = require('util');
+
+console.log(util.inspect(process.memoryUsage()));
+

This will generate: + +

+
{ rss: 4935680,
+  heapTotal: 1826816,
+  heapUsed: 650472 }
+

heapTotal and heapUsed refer to V8's memory usage. + + +

+

process.nextTick(callback)#

+

On the next loop around the event loop call this callback. +This is not a simple alias to setTimeout(fn, 0), it's much more +efficient. + +

+
process.nextTick(function () {
+  console.log('nextTick callback');
+});
+

process.umask([mask])#

+

Sets or reads the process's file mode creation mask. Child processes inherit +the mask from the parent process. Returns the old mask if mask argument is +given, otherwise returns the current mask. + +

+
var oldmask, newmask = 0644;
+
+oldmask = process.umask(newmask);
+console.log('Changed umask from: ' + oldmask.toString(8) +
+            ' to ' + newmask.toString(8));
+

process.uptime()#

+

Number of seconds Node has been running. + + +

+

process.hrtime()#

+

Returns the current high-resolution real time in a [seconds, nanoseconds] +tuple Array. It is relative to an arbitrary time in the past. It is not +related to the time of day and therefore not subject to clock drift. The +primary use is for measuring performance between intervals. + +

+

You may pass in the result of a previous call to process.hrtime() to get +a diff reading, useful for benchmarks and measuring intervals: + +

+
var time = process.hrtime();
+// [ 1800216, 927643717 ]
+
+setTimeout(function () {
+  var diff = process.hrtime(time);
+  // [ 1, 6962306 ]
+
+  console.log('benchmark took %d seconds and %d nanoseconds',
+              diff[0], diff[1]);
+  // benchmark took 1 seconds and 6962306 nanoseconds
+}, 1000);
+ +
+
+
+ + + + + + + + + diff --git a/node-v0.8.14/doc/api/process.json b/node-v0.8.14/doc/api/process.json new file mode 100644 index 0000000..1ac7309 --- /dev/null +++ b/node-v0.8.14/doc/api/process.json @@ -0,0 +1,291 @@ +{ + "source": "doc/api/process.markdown", + "globals": [ + { + "textRaw": "process", + "name": "process", + "type": "global", + "desc": "

The process object is a global object and can be accessed from anywhere.\nIt is an instance of [EventEmitter][].\n\n\n

\n", + "events": [ + { + "textRaw": "Event: 'exit'", + "type": "event", + "name": "exit", + "desc": "

Emitted when the process is about to exit. This is a good hook to perform\nconstant time checks of the module's state (like for unit tests). The main\nevent loop will no longer be run after the 'exit' callback finishes, so\ntimers may not be scheduled.\n\n

\n

Example of listening for exit:\n\n

\n
process.on('exit', function () {\n  process.nextTick(function () {\n   console.log('This will not run');\n  });\n  console.log('About to exit.');\n});
\n", + "params": [] + }, + { + "textRaw": "Event: 'uncaughtException'", + "type": "event", + "name": "uncaughtException", + "desc": "

Emitted when an exception bubbles all the way back to the event loop. If a\nlistener is added for this exception, the default action (which is to print\na stack trace and exit) will not occur.\n\n

\n

Example of listening for uncaughtException:\n\n

\n
process.on('uncaughtException', function (err) {\n  console.log('Caught exception: ' + err);\n});\n\nsetTimeout(function () {\n  console.log('This will still run.');\n}, 500);\n\n// Intentionally cause an exception, but don't catch it.\nnonexistentFunc();\nconsole.log('This will not run.');
\n

Note that uncaughtException is a very crude mechanism for exception\nhandling and may be removed in the future.\n\n

\n

Don't use it, use domains instead. If you do use it, restart\nyour application after every unhandled exception!\n\n

\n

Do not use it as the node.js equivalent of On Error Resume Next. An\nunhandled exception means your application - and by extension node.js itself -\nis in an undefined state. Blindly resuming means anything could happen.\n\n

\n

Think of resuming as pulling the power cord when you are upgrading your system.\nNine out of ten times nothing happens - but the 10th time, your system is bust.\n\n

\n

You have been warned.\n\n

\n", + "params": [] + }, + { + "textRaw": "Signal Events", + "name": "SIGINT, SIGUSR1, etc.", + "type": "event", + "desc": "

Emitted when the processes receives a signal. See sigaction(2) for a list of\nstandard POSIX signal names such as SIGINT, SIGUSR1, etc.\n\n

\n

Example of listening for SIGINT:\n\n

\n
// Start reading from stdin so we don't exit.\nprocess.stdin.resume();\n\nprocess.on('SIGINT', function () {\n  console.log('Got SIGINT.  Press Control-D to exit.');\n});
\n

An easy way to send the SIGINT signal is with Control-C in most terminal\nprograms.\n\n\n

\n", + "params": [] + } + ], + "properties": [ + { + "textRaw": "process.stdout", + "name": "stdout", + "desc": "

A Writable Stream to stdout.\n\n

\n

Example: the definition of console.log\n\n

\n
console.log = function (d) {\n  process.stdout.write(d + '\\n');\n};
\n

process.stderr and process.stdout are unlike other streams in Node in\nthat writes to them are usually blocking. They are blocking in the case\nthat they refer to regular files or TTY file descriptors. In the case they\nrefer to pipes, they are non-blocking like other streams.\n\n\n

\n" + }, + { + "textRaw": "process.stderr", + "name": "stderr", + "desc": "

A writable stream to stderr.\n\n

\n

process.stderr and process.stdout are unlike other streams in Node in\nthat writes to them are usually blocking. They are blocking in the case\nthat they refer to regular files or TTY file descriptors. In the case they\nrefer to pipes, they are non-blocking like other streams.\n\n\n

\n" + }, + { + "textRaw": "process.stdin", + "name": "stdin", + "desc": "

A Readable Stream for stdin. The stdin stream is paused by default, so one\nmust call process.stdin.resume() to read from it.\n\n

\n

Example of opening standard input and listening for both events:\n\n

\n
process.stdin.resume();\nprocess.stdin.setEncoding('utf8');\n\nprocess.stdin.on('data', function (chunk) {\n  process.stdout.write('data: ' + chunk);\n});\n\nprocess.stdin.on('end', function () {\n  process.stdout.write('end');\n});
\n" + }, + { + "textRaw": "process.argv", + "name": "argv", + "desc": "

An array containing the command line arguments. The first element will be\n'node', the second element will be the name of the JavaScript file. The\nnext elements will be any additional command line arguments.\n\n

\n
// print process.argv\nprocess.argv.forEach(function (val, index, array) {\n  console.log(index + ': ' + val);\n});
\n

This will generate:\n\n

\n
$ node process-2.js one two=three four\n0: node\n1: /Users/mjr/work/node/process-2.js\n2: one\n3: two=three\n4: four
\n" + }, + { + "textRaw": "process.execPath", + "name": "execPath", + "desc": "

This is the absolute pathname of the executable that started the process.\n\n

\n

Example:\n\n

\n
/usr/local/bin/node
\n" + }, + { + "textRaw": "process.env", + "name": "env", + "desc": "

An object containing the user environment. See environ(7).\n\n\n

\n" + }, + { + "textRaw": "process.version", + "name": "version", + "desc": "

A compiled-in property that exposes NODE_VERSION.\n\n

\n
console.log('Version: ' + process.version);
\n" + }, + { + "textRaw": "process.versions", + "name": "versions", + "desc": "

A property exposing version strings of node and its dependencies.\n\n

\n
console.log(process.versions);
\n

Will output:\n\n

\n
{ node: '0.4.12',\n  v8: '3.1.8.26',\n  ares: '1.7.4',\n  ev: '4.4',\n  openssl: '1.0.0e-fips' }
\n" + }, + { + "textRaw": "process.config", + "name": "config", + "desc": "

An Object containing the JavaScript representation of the configure options\nthat were used to compile the current node executable. This is the same as\nthe "config.gypi" file that was produced when running the ./configure script.\n\n

\n

An example of the possible output looks like:\n\n

\n
{ target_defaults:\n   { cflags: [],\n     default_configuration: 'Release',\n     defines: [],\n     include_dirs: [],\n     libraries: [] },\n  variables:\n   { host_arch: 'x64',\n     node_install_npm: 'true',\n     node_install_waf: 'true',\n     node_prefix: '',\n     node_shared_v8: 'false',\n     node_shared_zlib: 'false',\n     node_use_dtrace: 'false',\n     node_use_openssl: 'true',\n     node_shared_openssl: 'false',\n     strict_aliasing: 'true',\n     target_arch: 'x64',\n     v8_use_snapshot: 'true' } }
\n" + }, + { + "textRaw": "process.pid", + "name": "pid", + "desc": "

The PID of the process.\n\n

\n
console.log('This process is pid ' + process.pid);
\n" + }, + { + "textRaw": "process.title", + "name": "title", + "desc": "

Getter/setter to set what is displayed in 'ps'.\n\n\n

\n" + }, + { + "textRaw": "process.arch", + "name": "arch", + "desc": "

What processor architecture you're running on: 'arm', 'ia32', or 'x64'.\n\n

\n
console.log('This processor architecture is ' + process.arch);
\n" + }, + { + "textRaw": "process.platform", + "name": "platform", + "desc": "

What platform you're running on:\n'darwin', 'freebsd', 'linux', 'sunos' or 'win32'\n\n

\n
console.log('This platform is ' + process.platform);
\n" + } + ], + "methods": [ + { + "textRaw": "process.abort()", + "type": "method", + "name": "abort", + "desc": "

This causes node to emit an abort. This will cause node to exit and\ngenerate a core file.\n\n

\n", + "signatures": [ + { + "params": [] + } + ] + }, + { + "textRaw": "process.chdir(directory)", + "type": "method", + "name": "chdir", + "desc": "

Changes the current working directory of the process or throws an exception if that fails.\n\n

\n
console.log('Starting directory: ' + process.cwd());\ntry {\n  process.chdir('/tmp');\n  console.log('New directory: ' + process.cwd());\n}\ncatch (err) {\n  console.log('chdir: ' + err);\n}
\n", + "signatures": [ + { + "params": [ + { + "name": "directory" + } + ] + } + ] + }, + { + "textRaw": "process.cwd()", + "type": "method", + "name": "cwd", + "desc": "

Returns the current working directory of the process.\n\n

\n
console.log('Current directory: ' + process.cwd());
\n", + "signatures": [ + { + "params": [] + } + ] + }, + { + "textRaw": "process.exit([code])", + "type": "method", + "name": "exit", + "desc": "

Ends the process with the specified code. If omitted, exit uses the\n'success' code 0.\n\n

\n

To exit with a 'failure' code:\n\n

\n
process.exit(1);
\n

The shell that executed node should see the exit code as 1.\n\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "code", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "process.getgid()", + "type": "method", + "name": "getgid", + "desc": "

Note: this function is only available on POSIX platforms (i.e. not Windows)\n\n

\n

Gets the group identity of the process. (See getgid(2).)\nThis is the numerical group id, not the group name.\n\n

\n
if (process.getgid) {\n  console.log('Current gid: ' + process.getgid());\n}
\n", + "signatures": [ + { + "params": [] + } + ] + }, + { + "textRaw": "process.setgid(id)", + "type": "method", + "name": "setgid", + "desc": "

Note: this function is only available on POSIX platforms (i.e. not Windows)\n\n

\n

Sets the group identity of the process. (See setgid(2).) This accepts either\na numerical ID or a groupname string. If a groupname is specified, this method\nblocks while resolving it to a numerical ID.\n\n

\n
if (process.getgid && process.setgid) {\n  console.log('Current gid: ' + process.getgid());\n  try {\n    process.setgid(501);\n    console.log('New gid: ' + process.getgid());\n  }\n  catch (err) {\n    console.log('Failed to set gid: ' + err);\n  }\n}
\n", + "signatures": [ + { + "params": [ + { + "name": "id" + } + ] + } + ] + }, + { + "textRaw": "process.getuid()", + "type": "method", + "name": "getuid", + "desc": "

Note: this function is only available on POSIX platforms (i.e. not Windows)\n\n

\n

Gets the user identity of the process. (See getuid(2).)\nThis is the numerical userid, not the username.\n\n

\n
if (process.getuid) {\n  console.log('Current uid: ' + process.getuid());\n}
\n", + "signatures": [ + { + "params": [] + } + ] + }, + { + "textRaw": "process.setuid(id)", + "type": "method", + "name": "setuid", + "desc": "

Note: this function is only available on POSIX platforms (i.e. not Windows)\n\n

\n

Sets the user identity of the process. (See setuid(2).) This accepts either\na numerical ID or a username string. If a username is specified, this method\nblocks while resolving it to a numerical ID.\n\n

\n
if (process.getuid && process.setuid) {\n  console.log('Current uid: ' + process.getuid());\n  try {\n    process.setuid(501);\n    console.log('New uid: ' + process.getuid());\n  }\n  catch (err) {\n    console.log('Failed to set uid: ' + err);\n  }\n}
\n", + "signatures": [ + { + "params": [ + { + "name": "id" + } + ] + } + ] + }, + { + "textRaw": "process.kill(pid, [signal])", + "type": "method", + "name": "kill", + "desc": "

Send a signal to a process. pid is the process id and signal is the\nstring describing the signal to send. Signal names are strings like\n'SIGINT' or 'SIGUSR1'. If omitted, the signal will be 'SIGTERM'.\nSee kill(2) for more information.\n\n

\n

Note that just because the name of this function is process.kill, it is\nreally just a signal sender, like the kill system call. The signal sent\nmay do something other than kill the target process.\n\n

\n

Example of sending a signal to yourself:\n\n

\n
process.on('SIGHUP', function () {\n  console.log('Got SIGHUP signal.');\n});\n\nsetTimeout(function () {\n  console.log('Exiting.');\n  process.exit(0);\n}, 100);\n\nprocess.kill(process.pid, 'SIGHUP');
\n", + "signatures": [ + { + "params": [ + { + "name": "pid" + }, + { + "name": "signal", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "process.memoryUsage()", + "type": "method", + "name": "memoryUsage", + "desc": "

Returns an object describing the memory usage of the Node process\nmeasured in bytes.\n\n

\n
var util = require('util');\n\nconsole.log(util.inspect(process.memoryUsage()));
\n

This will generate:\n\n

\n
{ rss: 4935680,\n  heapTotal: 1826816,\n  heapUsed: 650472 }
\n

heapTotal and heapUsed refer to V8's memory usage.\n\n\n

\n", + "signatures": [ + { + "params": [] + } + ] + }, + { + "textRaw": "process.nextTick(callback)", + "type": "method", + "name": "nextTick", + "desc": "

On the next loop around the event loop call this callback.\nThis is not a simple alias to setTimeout(fn, 0), it's much more\nefficient.\n\n

\n
process.nextTick(function () {\n  console.log('nextTick callback');\n});
\n", + "signatures": [ + { + "params": [ + { + "name": "callback" + } + ] + } + ] + }, + { + "textRaw": "process.umask([mask])", + "type": "method", + "name": "umask", + "desc": "

Sets or reads the process's file mode creation mask. Child processes inherit\nthe mask from the parent process. Returns the old mask if mask argument is\ngiven, otherwise returns the current mask.\n\n

\n
var oldmask, newmask = 0644;\n\noldmask = process.umask(newmask);\nconsole.log('Changed umask from: ' + oldmask.toString(8) +\n            ' to ' + newmask.toString(8));
\n", + "signatures": [ + { + "params": [ + { + "name": "mask", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "process.uptime()", + "type": "method", + "name": "uptime", + "desc": "

Number of seconds Node has been running.\n\n\n

\n", + "signatures": [ + { + "params": [] + } + ] + }, + { + "textRaw": "process.hrtime()", + "type": "method", + "name": "hrtime", + "desc": "

Returns the current high-resolution real time in a [seconds, nanoseconds]\ntuple Array. It is relative to an arbitrary time in the past. It is not\nrelated to the time of day and therefore not subject to clock drift. The\nprimary use is for measuring performance between intervals.\n\n

\n

You may pass in the result of a previous call to process.hrtime() to get\na diff reading, useful for benchmarks and measuring intervals:\n\n

\n
var time = process.hrtime();\n// [ 1800216, 927643717 ]\n\nsetTimeout(function () {\n  var diff = process.hrtime(time);\n  // [ 1, 6962306 ]\n\n  console.log('benchmark took %d seconds and %d nanoseconds',\n              diff[0], diff[1]);\n  // benchmark took 1 seconds and 6962306 nanoseconds\n}, 1000);
\n", + "signatures": [ + { + "params": [] + } + ] + } + ] + } + ] +} diff --git a/node-v0.8.14/doc/api/process.markdown b/node-v0.8.14/doc/api/process.markdown new file mode 100644 index 0000000..fba7f12 --- /dev/null +++ b/node-v0.8.14/doc/api/process.markdown @@ -0,0 +1,432 @@ +# process + + + +The `process` object is a global object and can be accessed from anywhere. +It is an instance of [EventEmitter][]. + + +## Event: 'exit' + +Emitted when the process is about to exit. This is a good hook to perform +constant time checks of the module's state (like for unit tests). The main +event loop will no longer be run after the 'exit' callback finishes, so +timers may not be scheduled. + +Example of listening for `exit`: + + process.on('exit', function () { + process.nextTick(function () { + console.log('This will not run'); + }); + console.log('About to exit.'); + }); + +## Event: 'uncaughtException' + +Emitted when an exception bubbles all the way back to the event loop. If a +listener is added for this exception, the default action (which is to print +a stack trace and exit) will not occur. + +Example of listening for `uncaughtException`: + + process.on('uncaughtException', function (err) { + console.log('Caught exception: ' + err); + }); + + setTimeout(function () { + console.log('This will still run.'); + }, 500); + + // Intentionally cause an exception, but don't catch it. + nonexistentFunc(); + console.log('This will not run.'); + +Note that `uncaughtException` is a very crude mechanism for exception +handling and may be removed in the future. + +Don't use it, use [domains](domain.html) instead. If you do use it, restart +your application after every unhandled exception! + +Do *not* use it as the node.js equivalent of `On Error Resume Next`. An +unhandled exception means your application - and by extension node.js itself - +is in an undefined state. Blindly resuming means *anything* could happen. + +Think of resuming as pulling the power cord when you are upgrading your system. +Nine out of ten times nothing happens - but the 10th time, your system is bust. + +You have been warned. + +## Signal Events + + + + +Emitted when the processes receives a signal. See sigaction(2) for a list of +standard POSIX signal names such as SIGINT, SIGUSR1, etc. + +Example of listening for `SIGINT`: + + // Start reading from stdin so we don't exit. + process.stdin.resume(); + + process.on('SIGINT', function () { + console.log('Got SIGINT. Press Control-D to exit.'); + }); + +An easy way to send the `SIGINT` signal is with `Control-C` in most terminal +programs. + + +## process.stdout + +A `Writable Stream` to `stdout`. + +Example: the definition of `console.log` + + console.log = function (d) { + process.stdout.write(d + '\n'); + }; + +`process.stderr` and `process.stdout` are unlike other streams in Node in +that writes to them are usually blocking. They are blocking in the case +that they refer to regular files or TTY file descriptors. In the case they +refer to pipes, they are non-blocking like other streams. + + +## process.stderr + +A writable stream to stderr. + +`process.stderr` and `process.stdout` are unlike other streams in Node in +that writes to them are usually blocking. They are blocking in the case +that they refer to regular files or TTY file descriptors. In the case they +refer to pipes, they are non-blocking like other streams. + + +## process.stdin + +A `Readable Stream` for stdin. The stdin stream is paused by default, so one +must call `process.stdin.resume()` to read from it. + +Example of opening standard input and listening for both events: + + process.stdin.resume(); + process.stdin.setEncoding('utf8'); + + process.stdin.on('data', function (chunk) { + process.stdout.write('data: ' + chunk); + }); + + process.stdin.on('end', function () { + process.stdout.write('end'); + }); + + +## process.argv + +An array containing the command line arguments. The first element will be +'node', the second element will be the name of the JavaScript file. The +next elements will be any additional command line arguments. + + // print process.argv + process.argv.forEach(function (val, index, array) { + console.log(index + ': ' + val); + }); + +This will generate: + + $ node process-2.js one two=three four + 0: node + 1: /Users/mjr/work/node/process-2.js + 2: one + 3: two=three + 4: four + + +## process.execPath + +This is the absolute pathname of the executable that started the process. + +Example: + + /usr/local/bin/node + + +## process.abort() + +This causes node to emit an abort. This will cause node to exit and +generate a core file. + +## process.chdir(directory) + +Changes the current working directory of the process or throws an exception if that fails. + + console.log('Starting directory: ' + process.cwd()); + try { + process.chdir('/tmp'); + console.log('New directory: ' + process.cwd()); + } + catch (err) { + console.log('chdir: ' + err); + } + + + +## process.cwd() + +Returns the current working directory of the process. + + console.log('Current directory: ' + process.cwd()); + + +## process.env + +An object containing the user environment. See environ(7). + + +## process.exit([code]) + +Ends the process with the specified `code`. If omitted, exit uses the +'success' code `0`. + +To exit with a 'failure' code: + + process.exit(1); + +The shell that executed node should see the exit code as 1. + + +## process.getgid() + +Note: this function is only available on POSIX platforms (i.e. not Windows) + +Gets the group identity of the process. (See getgid(2).) +This is the numerical group id, not the group name. + + if (process.getgid) { + console.log('Current gid: ' + process.getgid()); + } + + +## process.setgid(id) + +Note: this function is only available on POSIX platforms (i.e. not Windows) + +Sets the group identity of the process. (See setgid(2).) This accepts either +a numerical ID or a groupname string. If a groupname is specified, this method +blocks while resolving it to a numerical ID. + + if (process.getgid && process.setgid) { + console.log('Current gid: ' + process.getgid()); + try { + process.setgid(501); + console.log('New gid: ' + process.getgid()); + } + catch (err) { + console.log('Failed to set gid: ' + err); + } + } + + +## process.getuid() + +Note: this function is only available on POSIX platforms (i.e. not Windows) + +Gets the user identity of the process. (See getuid(2).) +This is the numerical userid, not the username. + + if (process.getuid) { + console.log('Current uid: ' + process.getuid()); + } + + +## process.setuid(id) + +Note: this function is only available on POSIX platforms (i.e. not Windows) + +Sets the user identity of the process. (See setuid(2).) This accepts either +a numerical ID or a username string. If a username is specified, this method +blocks while resolving it to a numerical ID. + + if (process.getuid && process.setuid) { + console.log('Current uid: ' + process.getuid()); + try { + process.setuid(501); + console.log('New uid: ' + process.getuid()); + } + catch (err) { + console.log('Failed to set uid: ' + err); + } + } + + +## process.version + +A compiled-in property that exposes `NODE_VERSION`. + + console.log('Version: ' + process.version); + +## process.versions + +A property exposing version strings of node and its dependencies. + + console.log(process.versions); + +Will output: + + { node: '0.4.12', + v8: '3.1.8.26', + ares: '1.7.4', + ev: '4.4', + openssl: '1.0.0e-fips' } + +## process.config + +An Object containing the JavaScript representation of the configure options +that were used to compile the current node executable. This is the same as +the "config.gypi" file that was produced when running the `./configure` script. + +An example of the possible output looks like: + + { target_defaults: + { cflags: [], + default_configuration: 'Release', + defines: [], + include_dirs: [], + libraries: [] }, + variables: + { host_arch: 'x64', + node_install_npm: 'true', + node_install_waf: 'true', + node_prefix: '', + node_shared_v8: 'false', + node_shared_zlib: 'false', + node_use_dtrace: 'false', + node_use_openssl: 'true', + node_shared_openssl: 'false', + strict_aliasing: 'true', + target_arch: 'x64', + v8_use_snapshot: 'true' } } + +## process.kill(pid, [signal]) + +Send a signal to a process. `pid` is the process id and `signal` is the +string describing the signal to send. Signal names are strings like +'SIGINT' or 'SIGUSR1'. If omitted, the signal will be 'SIGTERM'. +See kill(2) for more information. + +Note that just because the name of this function is `process.kill`, it is +really just a signal sender, like the `kill` system call. The signal sent +may do something other than kill the target process. + +Example of sending a signal to yourself: + + process.on('SIGHUP', function () { + console.log('Got SIGHUP signal.'); + }); + + setTimeout(function () { + console.log('Exiting.'); + process.exit(0); + }, 100); + + process.kill(process.pid, 'SIGHUP'); + + +## process.pid + +The PID of the process. + + console.log('This process is pid ' + process.pid); + +## process.title + +Getter/setter to set what is displayed in 'ps'. + + +## process.arch + +What processor architecture you're running on: `'arm'`, `'ia32'`, or `'x64'`. + + console.log('This processor architecture is ' + process.arch); + + +## process.platform + +What platform you're running on: +`'darwin'`, `'freebsd'`, `'linux'`, `'sunos'` or `'win32'` + + console.log('This platform is ' + process.platform); + + +## process.memoryUsage() + +Returns an object describing the memory usage of the Node process +measured in bytes. + + var util = require('util'); + + console.log(util.inspect(process.memoryUsage())); + +This will generate: + + { rss: 4935680, + heapTotal: 1826816, + heapUsed: 650472 } + +`heapTotal` and `heapUsed` refer to V8's memory usage. + + +## process.nextTick(callback) + +On the next loop around the event loop call this callback. +This is *not* a simple alias to `setTimeout(fn, 0)`, it's much more +efficient. + + process.nextTick(function () { + console.log('nextTick callback'); + }); + + +## process.umask([mask]) + +Sets or reads the process's file mode creation mask. Child processes inherit +the mask from the parent process. Returns the old mask if `mask` argument is +given, otherwise returns the current mask. + + var oldmask, newmask = 0644; + + oldmask = process.umask(newmask); + console.log('Changed umask from: ' + oldmask.toString(8) + + ' to ' + newmask.toString(8)); + + +## process.uptime() + +Number of seconds Node has been running. + + +## process.hrtime() + +Returns the current high-resolution real time in a `[seconds, nanoseconds]` +tuple Array. It is relative to an arbitrary time in the past. It is not +related to the time of day and therefore not subject to clock drift. The +primary use is for measuring performance between intervals. + +You may pass in the result of a previous call to `process.hrtime()` to get +a diff reading, useful for benchmarks and measuring intervals: + + var time = process.hrtime(); + // [ 1800216, 927643717 ] + + setTimeout(function () { + var diff = process.hrtime(time); + // [ 1, 6962306 ] + + console.log('benchmark took %d seconds and %d nanoseconds', + diff[0], diff[1]); + // benchmark took 1 seconds and 6962306 nanoseconds + }, 1000); + +[EventEmitter]: events.html#events_class_events_eventemitter diff --git a/node-v0.8.14/doc/api/punycode.html b/node-v0.8.14/doc/api/punycode.html new file mode 100644 index 0000000..b6fe9d6 --- /dev/null +++ b/node-v0.8.14/doc/api/punycode.html @@ -0,0 +1,163 @@ + + + + + punycode Node.js v0.8.14 Manual & Documentation + + + + + +
+ + + +
+
+ + +
+
+

Node.js v0.8.14 Manual & Documentation

+ +
+
+ + + +
+

punycode#

+
Stability: 2 - Unstable
+

Punycode.js is bundled with Node.js v0.6.2+. Use +require('punycode') to access it. (To use it with other Node.js versions, +use npm to install the punycode module first.) + +

+

punycode.decode(string)#

+

Converts a Punycode string of ASCII code points to a string of Unicode code +points. + +

+
// decode domain name parts
+punycode.decode('maana-pta'); // 'mañana'
+punycode.decode('--dqo34k'); // '☃-⌘'
+

punycode.encode(string)#

+

Converts a string of Unicode code points to a Punycode string of ASCII code +points. + +

+
// encode domain name parts
+punycode.encode('mañana'); // 'maana-pta'
+punycode.encode('☃-⌘'); // '--dqo34k'
+

punycode.toUnicode(domain)#

+

Converts a Punycode string representing a domain name to Unicode. Only the +Punycoded parts of the domain name will be converted, i.e. it doesn't matter if +you call it on a string that has already been converted to Unicode. + +

+
// decode domain names
+punycode.toUnicode('xn--maana-pta.com'); // 'mañana.com'
+punycode.toUnicode('xn----dqo34k.com'); // '☃-⌘.com'
+

punycode.toASCII(domain)#

+

Converts a Unicode string representing a domain name to Punycode. Only the +non-ASCII parts of the domain name will be converted, i.e. it doesn't matter if +you call it with a domain that's already in ASCII. + +

+
// encode domain names
+punycode.toASCII('mañana.com'); // 'xn--maana-pta.com'
+punycode.toASCII('☃-⌘.com'); // 'xn----dqo34k.com'
+

punycode.ucs2#

+

punycode.ucs2.decode(string)#

+

Creates an array containing the decimal code points of each Unicode character +in the string. While JavaScript uses UCS-2 +internally, this function +will convert a pair of surrogate halves (each of which UCS-2 exposes as +separate characters) into a single code point, matching UTF-16. + +

+
punycode.ucs2.decode('abc'); // [97, 98, 99]
+// surrogate pair for U+1D306 tetragram for centre:
+punycode.ucs2.decode('\uD834\uDF06'); // [0x1D306]
+

punycode.ucs2.encode(codePoints)#

+

Creates a string based on an array of decimal code points. + +

+
punycode.ucs2.encode([97, 98, 99]); // 'abc'
+punycode.ucs2.encode([0x1D306]); // '\uD834\uDF06'
+

punycode.version#

+

A string representing the current Punycode.js version number. +

+ +
+
+
+ + + + + + + + + diff --git a/node-v0.8.14/doc/api/punycode.json b/node-v0.8.14/doc/api/punycode.json new file mode 100644 index 0000000..fb4ce65 --- /dev/null +++ b/node-v0.8.14/doc/api/punycode.json @@ -0,0 +1,103 @@ +{ + "source": "doc/api/punycode.markdown", + "modules": [ + { + "textRaw": "punycode", + "name": "punycode", + "stability": 2, + "stabilityText": "Unstable", + "desc": "

Punycode.js is bundled with Node.js v0.6.2+. Use\nrequire('punycode') to access it. (To use it with other Node.js versions,\nuse npm to install the punycode module first.)\n\n

\n", + "methods": [ + { + "textRaw": "punycode.decode(string)", + "type": "method", + "name": "decode", + "desc": "

Converts a Punycode string of ASCII code points to a string of Unicode code\npoints.\n\n

\n
// decode domain name parts\npunycode.decode('maana-pta'); // 'mañana'\npunycode.decode('--dqo34k'); // '☃-⌘'
\n", + "signatures": [ + { + "params": [ + { + "name": "string" + } + ] + } + ] + }, + { + "textRaw": "punycode.encode(string)", + "type": "method", + "name": "encode", + "desc": "

Converts a string of Unicode code points to a Punycode string of ASCII code\npoints.\n\n

\n
// encode domain name parts\npunycode.encode('mañana'); // 'maana-pta'\npunycode.encode('☃-⌘'); // '--dqo34k'
\n", + "signatures": [ + { + "params": [ + { + "name": "string" + } + ] + } + ] + }, + { + "textRaw": "punycode.toUnicode(domain)", + "type": "method", + "name": "toUnicode", + "desc": "

Converts a Punycode string representing a domain name to Unicode. Only the\nPunycoded parts of the domain name will be converted, i.e. it doesn't matter if\nyou call it on a string that has already been converted to Unicode.\n\n

\n
// decode domain names\npunycode.toUnicode('xn--maana-pta.com'); // 'mañana.com'\npunycode.toUnicode('xn----dqo34k.com'); // '☃-⌘.com'
\n", + "signatures": [ + { + "params": [ + { + "name": "domain" + } + ] + } + ] + }, + { + "textRaw": "punycode.toASCII(domain)", + "type": "method", + "name": "toASCII", + "desc": "

Converts a Unicode string representing a domain name to Punycode. Only the\nnon-ASCII parts of the domain name will be converted, i.e. it doesn't matter if\nyou call it with a domain that's already in ASCII.\n\n

\n
// encode domain names\npunycode.toASCII('mañana.com'); // 'xn--maana-pta.com'\npunycode.toASCII('☃-⌘.com'); // 'xn----dqo34k.com'
\n", + "signatures": [ + { + "params": [ + { + "name": "domain" + } + ] + } + ] + } + ], + "properties": [ + { + "textRaw": "punycode.ucs2", + "name": "ucs2", + "modules": [ + { + "textRaw": "punycode.ucs2.decode(string)", + "name": "punycode.ucs2.decode(string)", + "desc": "

Creates an array containing the decimal code points of each Unicode character\nin the string. While JavaScript uses UCS-2\ninternally, this function\nwill convert a pair of surrogate halves (each of which UCS-2 exposes as\nseparate characters) into a single code point, matching UTF-16.\n\n

\n
punycode.ucs2.decode('abc'); // [97, 98, 99]\n// surrogate pair for U+1D306 tetragram for centre:\npunycode.ucs2.decode('\\uD834\\uDF06'); // [0x1D306]
\n", + "type": "module", + "displayName": "punycode.ucs2.decode(string)" + }, + { + "textRaw": "punycode.ucs2.encode(codePoints)", + "name": "punycode.ucs2.encode(codepoints)", + "desc": "

Creates a string based on an array of decimal code points.\n\n

\n
punycode.ucs2.encode([97, 98, 99]); // 'abc'\npunycode.ucs2.encode([0x1D306]); // '\\uD834\\uDF06'
\n", + "type": "module", + "displayName": "punycode.ucs2.encode(codePoints)" + } + ] + }, + { + "textRaw": "punycode.version", + "name": "version", + "desc": "

A string representing the current Punycode.js version number.\n

\n" + } + ], + "type": "module", + "displayName": "punycode" + } + ] +} diff --git a/node-v0.8.14/doc/api/punycode.markdown b/node-v0.8.14/doc/api/punycode.markdown new file mode 100644 index 0000000..f8f6a3d --- /dev/null +++ b/node-v0.8.14/doc/api/punycode.markdown @@ -0,0 +1,70 @@ +# punycode + + Stability: 2 - Unstable + +[Punycode.js](http://mths.be/punycode) is bundled with Node.js v0.6.2+. Use +`require('punycode')` to access it. (To use it with other Node.js versions, +use npm to install the `punycode` module first.) + +## punycode.decode(string) + +Converts a Punycode string of ASCII code points to a string of Unicode code +points. + + // decode domain name parts + punycode.decode('maana-pta'); // 'mañana' + punycode.decode('--dqo34k'); // '☃-⌘' + +## punycode.encode(string) + +Converts a string of Unicode code points to a Punycode string of ASCII code +points. + + // encode domain name parts + punycode.encode('mañana'); // 'maana-pta' + punycode.encode('☃-⌘'); // '--dqo34k' + +## punycode.toUnicode(domain) + +Converts a Punycode string representing a domain name to Unicode. Only the +Punycoded parts of the domain name will be converted, i.e. it doesn't matter if +you call it on a string that has already been converted to Unicode. + + // decode domain names + punycode.toUnicode('xn--maana-pta.com'); // 'mañana.com' + punycode.toUnicode('xn----dqo34k.com'); // '☃-⌘.com' + +## punycode.toASCII(domain) + +Converts a Unicode string representing a domain name to Punycode. Only the +non-ASCII parts of the domain name will be converted, i.e. it doesn't matter if +you call it with a domain that's already in ASCII. + + // encode domain names + punycode.toASCII('mañana.com'); // 'xn--maana-pta.com' + punycode.toASCII('☃-⌘.com'); // 'xn----dqo34k.com' + +## punycode.ucs2 + +### punycode.ucs2.decode(string) + +Creates an array containing the decimal code points of each Unicode character +in the string. While [JavaScript uses UCS-2 +internally](http://mathiasbynens.be/notes/javascript-encoding), this function +will convert a pair of surrogate halves (each of which UCS-2 exposes as +separate characters) into a single code point, matching UTF-16. + + punycode.ucs2.decode('abc'); // [97, 98, 99] + // surrogate pair for U+1D306 tetragram for centre: + punycode.ucs2.decode('\uD834\uDF06'); // [0x1D306] + +### punycode.ucs2.encode(codePoints) + +Creates a string based on an array of decimal code points. + + punycode.ucs2.encode([97, 98, 99]); // 'abc' + punycode.ucs2.encode([0x1D306]); // '\uD834\uDF06' + +## punycode.version + +A string representing the current Punycode.js version number. diff --git a/node-v0.8.14/doc/api/querystring.html b/node-v0.8.14/doc/api/querystring.html new file mode 100644 index 0000000..7f766b4 --- /dev/null +++ b/node-v0.8.14/doc/api/querystring.html @@ -0,0 +1,144 @@ + + + + + Query String Node.js v0.8.14 Manual & Documentation + + + + + +
+ + + +
+
+ + +
+
+

Node.js v0.8.14 Manual & Documentation

+ +
+
+ + + +
+

Query String#

+
Stability: 3 - Stable
+ + +

This module provides utilities for dealing with query strings. +It provides the following methods: + +

+

querystring.stringify(obj, [sep], [eq])#

+

Serialize an object to a query string. +Optionally override the default separator ('&') and assignment ('=') +characters. + +

+

Example: + +

+
querystring.stringify({ foo: 'bar', baz: ['qux', 'quux'], corge: '' })
+// returns
+'foo=bar&baz=qux&baz=quux&corge='
+
+querystring.stringify({foo: 'bar', baz: 'qux'}, ';', ':')
+// returns
+'foo:bar;baz:qux'
+

querystring.parse(str, [sep], [eq], [options])#

+

Deserialize a query string to an object. +Optionally override the default separator ('&') and assignment ('=') +characters. + +

+

Options object may contain maxKeys property (equal to 1000 by default), it'll +be used to limit processed keys. Set it to 0 to remove key count limitation. + +

+

Example: + +

+
querystring.parse('foo=bar&baz=qux&baz=quux&corge')
+// returns
+{ foo: 'bar', baz: ['qux', 'quux'], corge: '' }
+

querystring.escape#

+

The escape function used by querystring.stringify, +provided so that it could be overridden if necessary. + +

+

querystring.unescape#

+

The unescape function used by querystring.parse, +provided so that it could be overridden if necessary. +

+ +
+
+
+ + + + + + + + + diff --git a/node-v0.8.14/doc/api/querystring.json b/node-v0.8.14/doc/api/querystring.json new file mode 100644 index 0000000..2906260 --- /dev/null +++ b/node-v0.8.14/doc/api/querystring.json @@ -0,0 +1,78 @@ +{ + "source": "doc/api/querystring.markdown", + "modules": [ + { + "textRaw": "Query String", + "name": "querystring", + "stability": 3, + "stabilityText": "Stable", + "desc": "

This module provides utilities for dealing with query strings.\nIt provides the following methods:\n\n

\n", + "methods": [ + { + "textRaw": "querystring.stringify(obj, [sep], [eq])", + "type": "method", + "name": "stringify", + "desc": "

Serialize an object to a query string.\nOptionally override the default separator ('&') and assignment ('=')\ncharacters.\n\n

\n

Example:\n\n

\n
querystring.stringify({ foo: 'bar', baz: ['qux', 'quux'], corge: '' })\n// returns\n'foo=bar&baz=qux&baz=quux&corge='\n\nquerystring.stringify({foo: 'bar', baz: 'qux'}, ';', ':')\n// returns\n'foo:bar;baz:qux'
\n", + "signatures": [ + { + "params": [ + { + "name": "obj" + }, + { + "name": "sep", + "optional": true + }, + { + "name": "eq", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "querystring.parse(str, [sep], [eq], [options])", + "type": "method", + "name": "parse", + "desc": "

Deserialize a query string to an object.\nOptionally override the default separator ('&') and assignment ('=')\ncharacters.\n\n

\n

Options object may contain maxKeys property (equal to 1000 by default), it'll\nbe used to limit processed keys. Set it to 0 to remove key count limitation.\n\n

\n

Example:\n\n

\n
querystring.parse('foo=bar&baz=qux&baz=quux&corge')\n// returns\n{ foo: 'bar', baz: ['qux', 'quux'], corge: '' }
\n", + "signatures": [ + { + "params": [ + { + "name": "str" + }, + { + "name": "sep", + "optional": true + }, + { + "name": "eq", + "optional": true + }, + { + "name": "options", + "optional": true + } + ] + } + ] + } + ], + "properties": [ + { + "textRaw": "querystring.escape", + "name": "escape", + "desc": "

The escape function used by querystring.stringify,\nprovided so that it could be overridden if necessary.\n\n

\n" + }, + { + "textRaw": "querystring.unescape", + "name": "unescape", + "desc": "

The unescape function used by querystring.parse,\nprovided so that it could be overridden if necessary.\n

\n" + } + ], + "type": "module", + "displayName": "querystring" + } + ] +} diff --git a/node-v0.8.14/doc/api/querystring.markdown b/node-v0.8.14/doc/api/querystring.markdown new file mode 100644 index 0000000..2d5613a --- /dev/null +++ b/node-v0.8.14/doc/api/querystring.markdown @@ -0,0 +1,49 @@ +# Query String + + Stability: 3 - Stable + + + +This module provides utilities for dealing with query strings. +It provides the following methods: + +## querystring.stringify(obj, [sep], [eq]) + +Serialize an object to a query string. +Optionally override the default separator (`'&'`) and assignment (`'='`) +characters. + +Example: + + querystring.stringify({ foo: 'bar', baz: ['qux', 'quux'], corge: '' }) + // returns + 'foo=bar&baz=qux&baz=quux&corge=' + + querystring.stringify({foo: 'bar', baz: 'qux'}, ';', ':') + // returns + 'foo:bar;baz:qux' + +## querystring.parse(str, [sep], [eq], [options]) + +Deserialize a query string to an object. +Optionally override the default separator (`'&'`) and assignment (`'='`) +characters. + +Options object may contain `maxKeys` property (equal to 1000 by default), it'll +be used to limit processed keys. Set it to 0 to remove key count limitation. + +Example: + + querystring.parse('foo=bar&baz=qux&baz=quux&corge') + // returns + { foo: 'bar', baz: ['qux', 'quux'], corge: '' } + +## querystring.escape + +The escape function used by `querystring.stringify`, +provided so that it could be overridden if necessary. + +## querystring.unescape + +The unescape function used by `querystring.parse`, +provided so that it could be overridden if necessary. diff --git a/node-v0.8.14/doc/api/readline.html b/node-v0.8.14/doc/api/readline.html new file mode 100644 index 0000000..e67aabb --- /dev/null +++ b/node-v0.8.14/doc/api/readline.html @@ -0,0 +1,417 @@ + + + + + Readline Node.js v0.8.14 Manual & Documentation + + + + + +
+ + + +
+
+ + +
+
+

Node.js v0.8.14 Manual & Documentation

+ +
+
+ + + +
+

Readline#

+
Stability: 2 - Unstable
+

To use this module, do require('readline'). Readline allows reading of a +stream (such as process.stdin) on a line-by-line basis. + +

+

Note that once you've invoked this module, your node program will not +terminate until you've closed the interface. Here's how to allow your +program to gracefully exit: + +

+
var readline = require('readline');
+
+var rl = readline.createInterface({
+  input: process.stdin,
+  output: process.stdout
+});
+
+rl.question("What do you think of node.js? ", function(answer) {
+  // TODO: Log the answer in a database
+  console.log("Thank you for your valuable feedback:", answer);
+
+  rl.close();
+});
+

readline.createInterface(options)#

+

Creates a readline Interface instance. Accepts an "options" Object that takes +the following values: + +

+
    +
  • input - the readable stream to listen to (Required).

    +
  • +
  • output - the writable stream to write readline data to (Required).

    +
  • +
  • completer - an optional function that is used for Tab autocompletion. See +below for an example of using this.

    +
  • +
  • terminal - pass true if the input and output streams should be +treated like a TTY, and have ANSI/VT100 escape codes written to it. +Defaults to checking isTTY on the output stream upon instantiation.

    +
  • +
+

The completer function is given a the current line entered by the user, and +is supposed to return an Array with 2 entries: + +

+
    +
  1. An Array with matching entries for the completion.

    +
  2. +
  3. The substring that was used for the matching.

    +
  4. +
+

Which ends up looking something like: +[[substr1, substr2, ...], originalsubstring]. + +

+

Example: + +

+
function completer(line) {
+  var completions = '.help .error .exit .quit .q'.split(' ')
+  var hits = completions.filter(function(c) { return c.indexOf(line) == 0 })
+  // show all completions if none found
+  return [hits.length ? hits : completions, line]
+}
+

Also completer can be run in async mode if it accepts two arguments: + +

+
function completer(linePartial, callback) {
+  callback(null, [['123'], linePartial]);
+}
+

createInterface is commonly used with process.stdin and +process.stdout in order to accept user input: + +

+
var readline = require('readline');
+var rl = readline.createInterface({
+  input: process.stdin,
+  output: process.stdout
+});
+

Once you have a readline instance, you most commonly listen for the +"line" event. + +

+

If terminal is true for this instance then the output stream will get +the best compatibility if it defines an output.columns property, and fires +a "resize" event on the output if/when the columns ever change +(process.stdout does this automatically when it is a TTY). + +

+

Class: Interface#

+

The class that represents a readline interface with an input and output +stream. + +

+

rl.setPrompt(prompt, length)#

+

Sets the prompt, for example when you run node on the command line, you see +> , which is node's prompt. + +

+

rl.prompt([preserveCursor])#

+

Readies readline for input from the user, putting the current setPrompt +options on a new line, giving the user a new spot to write. Set preserveCursor +to true to prevent the cursor placement being reset to 0. + +

+

This will also resume the input stream used with createInterface if it has +been paused. + +

+

rl.question(query, callback)#

+

Prepends the prompt with query and invokes callback with the user's +response. Displays the query to the user, and then invokes callback +with the user's response after it has been typed. + +

+

This will also resume the input stream used with createInterface if +it has been paused. + +

+

Example usage: + +

+
interface.question('What is your favorite food?', function(answer) {
+  console.log('Oh, so your favorite food is ' + answer);
+});
+

rl.pause()#

+

Pauses the readline input stream, allowing it to be resumed later if needed. + +

+

rl.resume()#

+

Resumes the readline input stream. + +

+

rl.close()#

+

Closes the Interface instance, relinquishing control on the input and +output streams. The "close" event will also be emitted. + +

+

rl.write(data, [key])#

+

Writes data to output stream. key is an object literal to represent a key +sequence; available if the terminal is a TTY. + +

+

This will also resume the input stream if it has been paused. + +

+

Example: + +

+
rl.write('Delete me!');
+// Simulate ctrl+u to delete the line written previously
+rl.write(null, {ctrl: true, name: 'u'});
+

Events#

+

Event: 'line'#

+

function (line) {} + +

+

Emitted whenever the input stream receives a \n, usually received when the +user hits enter, or return. This is a good hook to listen for user input. + +

+

Example of listening for line: + +

+
rl.on('line', function (cmd) {
+  console.log('You just typed: '+cmd);
+});
+

Event: 'pause'#

+

function () {} + +

+

Emitted whenever the input stream is paused. + +

+

Also emitted whenever the input stream is not paused and receives the +SIGCONT event. (See events SIGTSTP and SIGCONT) + +

+

Example of listening for pause: + +

+
rl.on('pause', function() {
+  console.log('Readline paused.');
+});
+

Event: 'resume'#

+

function () {} + +

+

Emitted whenever the input stream is resumed. + +

+

Example of listening for resume: + +

+
rl.on('resume', function() {
+  console.log('Readline resumed.');
+});
+

Event: 'close'#

+

function () {} + +

+

Emitted when close() is called. + +

+

Also emitted when the input stream receives its "end" event. The Interface +instance should be considered "finished" once this is emitted. For example, when +the input stream receives ^D, respectively known as EOT. + +

+

This event is also called if there is no SIGINT event listener present when +the input stream receives a ^C, respectively known as SIGINT. + +

+

Event: 'SIGINT'#

+

function () {} + +

+

Emitted whenever the input stream receives a ^C, respectively known as +SIGINT. If there is no SIGINT event listener present when the input +stream receives a SIGINT, pause will be triggered. + +

+

Example of listening for SIGINT: + +

+
rl.on('SIGINT', function() {
+  rl.question('Are you sure you want to exit?', function(answer) {
+    if (answer.match(/^y(es)?$/i)) rl.pause();
+  });
+});
+

Event: 'SIGTSTP'#

+

function () {} + +

+

This does not work on Windows. + +

+

Emitted whenever the input stream receives a ^Z, respectively known as +SIGTSTP. If there is no SIGTSTP event listener present when the input +stream receives a SIGTSTP, the program will be sent to the background. + +

+

When the program is resumed with fg, the pause and SIGCONT events will be +emitted. You can use either to resume the stream. + +

+

The pause and SIGCONT events will not be triggered if the stream was paused +before the program was sent to the background. + +

+

Example of listening for SIGTSTP: + +

+
rl.on('SIGTSTP', function() {
+  // This will override SIGTSTP and prevent the program from going to the
+  // background.
+  console.log('Caught SIGTSTP.');
+});
+

Event: 'SIGCONT'#

+

function () {} + +

+

This does not work on Windows. + +

+

Emitted whenever the input stream is sent to the background with ^Z, +respectively known as SIGTSTP, and then continued with fg(1). This event +only emits if the stream was not paused before sending the program to the +background. + +

+

Example of listening for SIGCONT: + +

+
rl.on('SIGCONT', function() {
+  // `prompt` will automatically resume the stream
+  rl.prompt();
+});
+

Example: Tiny CLI#

+

Here's an example of how to use all these together to craft a tiny command +line interface: + +

+
var readline = require('readline'),
+    rl = readline.createInterface(process.stdin, process.stdout);
+
+rl.setPrompt('OHAI> ');
+rl.prompt();
+
+rl.on('line', function(line) {
+  switch(line.trim()) {
+    case 'hello':
+      console.log('world!');
+      break;
+    default:
+      console.log('Say what? I might have heard `' + line.trim() + '`');
+      break;
+  }
+  rl.prompt();
+}).on('close', function() {
+  console.log('Have a great day!');
+  process.exit(0);
+});
+ +
+
+
+ + + + + + + + + diff --git a/node-v0.8.14/doc/api/readline.json b/node-v0.8.14/doc/api/readline.json new file mode 100644 index 0000000..7281ff0 --- /dev/null +++ b/node-v0.8.14/doc/api/readline.json @@ -0,0 +1,204 @@ +{ + "source": "doc/api/readline.markdown", + "modules": [ + { + "textRaw": "Readline", + "name": "readline", + "stability": 2, + "stabilityText": "Unstable", + "desc": "

To use this module, do require('readline'). Readline allows reading of a\nstream (such as process.stdin) on a line-by-line basis.\n\n

\n

Note that once you've invoked this module, your node program will not\nterminate until you've closed the interface. Here's how to allow your\nprogram to gracefully exit:\n\n

\n
var readline = require('readline');\n\nvar rl = readline.createInterface({\n  input: process.stdin,\n  output: process.stdout\n});\n\nrl.question("What do you think of node.js? ", function(answer) {\n  // TODO: Log the answer in a database\n  console.log("Thank you for your valuable feedback:", answer);\n\n  rl.close();\n});
\n", + "methods": [ + { + "textRaw": "readline.createInterface(options)", + "type": "method", + "name": "createInterface", + "desc": "

Creates a readline Interface instance. Accepts an "options" Object that takes\nthe following values:\n\n

\n
    \n
  • input - the readable stream to listen to (Required).

    \n
  • \n
  • output - the writable stream to write readline data to (Required).

    \n
  • \n
  • completer - an optional function that is used for Tab autocompletion. See\nbelow for an example of using this.

    \n
  • \n
  • terminal - pass true if the input and output streams should be\ntreated like a TTY, and have ANSI/VT100 escape codes written to it.\nDefaults to checking isTTY on the output stream upon instantiation.

    \n
  • \n
\n

The completer function is given a the current line entered by the user, and\nis supposed to return an Array with 2 entries:\n\n

\n
    \n
  1. An Array with matching entries for the completion.

    \n
  2. \n
  3. The substring that was used for the matching.

    \n
  4. \n
\n

Which ends up looking something like:\n[[substr1, substr2, ...], originalsubstring].\n\n

\n

Example:\n\n

\n
function completer(line) {\n  var completions = '.help .error .exit .quit .q'.split(' ')\n  var hits = completions.filter(function(c) { return c.indexOf(line) == 0 })\n  // show all completions if none found\n  return [hits.length ? hits : completions, line]\n}
\n

Also completer can be run in async mode if it accepts two arguments:\n\n

\n
function completer(linePartial, callback) {\n  callback(null, [['123'], linePartial]);\n}
\n

createInterface is commonly used with process.stdin and\nprocess.stdout in order to accept user input:\n\n

\n
var readline = require('readline');\nvar rl = readline.createInterface({\n  input: process.stdin,\n  output: process.stdout\n});
\n

Once you have a readline instance, you most commonly listen for the\n"line" event.\n\n

\n

If terminal is true for this instance then the output stream will get\nthe best compatibility if it defines an output.columns property, and fires\na "resize" event on the output if/when the columns ever change\n(process.stdout does this automatically when it is a TTY).\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "options" + } + ] + } + ] + } + ], + "classes": [ + { + "textRaw": "Class: Interface", + "type": "class", + "name": "Interface", + "desc": "

The class that represents a readline interface with an input and output\nstream.\n\n

\n", + "methods": [ + { + "textRaw": "rl.setPrompt(prompt, length)", + "type": "method", + "name": "setPrompt", + "desc": "

Sets the prompt, for example when you run node on the command line, you see\n> , which is node's prompt.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "prompt" + }, + { + "name": "length" + } + ] + } + ] + }, + { + "textRaw": "rl.prompt([preserveCursor])", + "type": "method", + "name": "prompt", + "desc": "

Readies readline for input from the user, putting the current setPrompt\noptions on a new line, giving the user a new spot to write. Set preserveCursor\nto true to prevent the cursor placement being reset to 0.\n\n

\n

This will also resume the input stream used with createInterface if it has\nbeen paused.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "preserveCursor", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "rl.question(query, callback)", + "type": "method", + "name": "question", + "desc": "

Prepends the prompt with query and invokes callback with the user's\nresponse. Displays the query to the user, and then invokes callback\nwith the user's response after it has been typed.\n\n

\n

This will also resume the input stream used with createInterface if\nit has been paused.\n\n

\n

Example usage:\n\n

\n
interface.question('What is your favorite food?', function(answer) {\n  console.log('Oh, so your favorite food is ' + answer);\n});
\n", + "signatures": [ + { + "params": [ + { + "name": "query" + }, + { + "name": "callback" + } + ] + } + ] + }, + { + "textRaw": "rl.pause()", + "type": "method", + "name": "pause", + "desc": "

Pauses the readline input stream, allowing it to be resumed later if needed.\n\n

\n", + "signatures": [ + { + "params": [] + } + ] + }, + { + "textRaw": "rl.resume()", + "type": "method", + "name": "resume", + "desc": "

Resumes the readline input stream.\n\n

\n", + "signatures": [ + { + "params": [] + } + ] + }, + { + "textRaw": "rl.close()", + "type": "method", + "name": "close", + "desc": "

Closes the Interface instance, relinquishing control on the input and\noutput streams. The "close" event will also be emitted.\n\n

\n", + "signatures": [ + { + "params": [] + } + ] + }, + { + "textRaw": "rl.write(data, [key])", + "type": "method", + "name": "write", + "desc": "

Writes data to output stream. key is an object literal to represent a key\nsequence; available if the terminal is a TTY.\n\n

\n

This will also resume the input stream if it has been paused.\n\n

\n

Example:\n\n

\n
rl.write('Delete me!');\n// Simulate ctrl+u to delete the line written previously\nrl.write(null, {ctrl: true, name: 'u'});
\n", + "signatures": [ + { + "params": [ + { + "name": "data" + }, + { + "name": "key", + "optional": true + } + ] + } + ] + } + ] + } + ], + "modules": [ + { + "textRaw": "Events", + "name": "events", + "events": [ + { + "textRaw": "Event: 'line'", + "type": "event", + "name": "line", + "desc": "

function (line) {}\n\n

\n

Emitted whenever the input stream receives a \\n, usually received when the\nuser hits enter, or return. This is a good hook to listen for user input.\n\n

\n

Example of listening for line:\n\n

\n
rl.on('line', function (cmd) {\n  console.log('You just typed: '+cmd);\n});
\n", + "params": [] + }, + { + "textRaw": "Event: 'pause'", + "type": "event", + "name": "pause", + "desc": "

function () {}\n\n

\n

Emitted whenever the input stream is paused.\n\n

\n

Also emitted whenever the input stream is not paused and receives the\nSIGCONT event. (See events SIGTSTP and SIGCONT)\n\n

\n

Example of listening for pause:\n\n

\n
rl.on('pause', function() {\n  console.log('Readline paused.');\n});
\n", + "params": [] + }, + { + "textRaw": "Event: 'resume'", + "type": "event", + "name": "resume", + "desc": "

function () {}\n\n

\n

Emitted whenever the input stream is resumed.\n\n

\n

Example of listening for resume:\n\n

\n
rl.on('resume', function() {\n  console.log('Readline resumed.');\n});
\n", + "params": [] + }, + { + "textRaw": "Event: 'close'", + "type": "event", + "name": "close", + "desc": "

function () {}\n\n

\n

Emitted when close() is called.\n\n

\n

Also emitted when the input stream receives its "end" event. The Interface\ninstance should be considered "finished" once this is emitted. For example, when\nthe input stream receives ^D, respectively known as EOT.\n\n

\n

This event is also called if there is no SIGINT event listener present when\nthe input stream receives a ^C, respectively known as SIGINT.\n\n

\n", + "params": [] + }, + { + "textRaw": "Event: 'SIGINT'", + "type": "event", + "name": "SIGINT", + "desc": "

function () {}\n\n

\n

Emitted whenever the input stream receives a ^C, respectively known as\nSIGINT. If there is no SIGINT event listener present when the input\nstream receives a SIGINT, pause will be triggered.\n\n

\n

Example of listening for SIGINT:\n\n

\n
rl.on('SIGINT', function() {\n  rl.question('Are you sure you want to exit?', function(answer) {\n    if (answer.match(/^y(es)?$/i)) rl.pause();\n  });\n});
\n", + "params": [] + }, + { + "textRaw": "Event: 'SIGTSTP'", + "type": "event", + "name": "SIGTSTP", + "desc": "

function () {}\n\n

\n

This does not work on Windows.\n\n

\n

Emitted whenever the input stream receives a ^Z, respectively known as\nSIGTSTP. If there is no SIGTSTP event listener present when the input\nstream receives a SIGTSTP, the program will be sent to the background.\n\n

\n

When the program is resumed with fg, the pause and SIGCONT events will be\nemitted. You can use either to resume the stream.\n\n

\n

The pause and SIGCONT events will not be triggered if the stream was paused\nbefore the program was sent to the background.\n\n

\n

Example of listening for SIGTSTP:\n\n

\n
rl.on('SIGTSTP', function() {\n  // This will override SIGTSTP and prevent the program from going to the\n  // background.\n  console.log('Caught SIGTSTP.');\n});
\n", + "params": [] + }, + { + "textRaw": "Event: 'SIGCONT'", + "type": "event", + "name": "SIGCONT", + "desc": "

function () {}\n\n

\n

This does not work on Windows.\n\n

\n

Emitted whenever the input stream is sent to the background with ^Z,\nrespectively known as SIGTSTP, and then continued with fg(1). This event\nonly emits if the stream was not paused before sending the program to the\nbackground.\n\n

\n

Example of listening for SIGCONT:\n\n

\n
rl.on('SIGCONT', function() {\n  // `prompt` will automatically resume the stream\n  rl.prompt();\n});
\n

Example: Tiny CLI

\n

Here's an example of how to use all these together to craft a tiny command\nline interface:\n\n

\n
var readline = require('readline'),\n    rl = readline.createInterface(process.stdin, process.stdout);\n\nrl.setPrompt('OHAI> ');\nrl.prompt();\n\nrl.on('line', function(line) {\n  switch(line.trim()) {\n    case 'hello':\n      console.log('world!');\n      break;\n    default:\n      console.log('Say what? I might have heard `' + line.trim() + '`');\n      break;\n  }\n  rl.prompt();\n}).on('close', function() {\n  console.log('Have a great day!');\n  process.exit(0);\n});
\n", + "params": [] + } + ], + "type": "module", + "displayName": "Events" + } + ], + "type": "module", + "displayName": "Readline" + } + ] +} diff --git a/node-v0.8.14/doc/api/readline.markdown b/node-v0.8.14/doc/api/readline.markdown new file mode 100644 index 0000000..d586b64 --- /dev/null +++ b/node-v0.8.14/doc/api/readline.markdown @@ -0,0 +1,283 @@ +# Readline + + Stability: 2 - Unstable + +To use this module, do `require('readline')`. Readline allows reading of a +stream (such as `process.stdin`) on a line-by-line basis. + +Note that once you've invoked this module, your node program will not +terminate until you've closed the interface. Here's how to allow your +program to gracefully exit: + + var readline = require('readline'); + + var rl = readline.createInterface({ + input: process.stdin, + output: process.stdout + }); + + rl.question("What do you think of node.js? ", function(answer) { + // TODO: Log the answer in a database + console.log("Thank you for your valuable feedback:", answer); + + rl.close(); + }); + +## readline.createInterface(options) + +Creates a readline `Interface` instance. Accepts an "options" Object that takes +the following values: + + - `input` - the readable stream to listen to (Required). + + - `output` - the writable stream to write readline data to (Required). + + - `completer` - an optional function that is used for Tab autocompletion. See + below for an example of using this. + + - `terminal` - pass `true` if the `input` and `output` streams should be + treated like a TTY, and have ANSI/VT100 escape codes written to it. + Defaults to checking `isTTY` on the `output` stream upon instantiation. + +The `completer` function is given a the current line entered by the user, and +is supposed to return an Array with 2 entries: + + 1. An Array with matching entries for the completion. + + 2. The substring that was used for the matching. + +Which ends up looking something like: +`[[substr1, substr2, ...], originalsubstring]`. + +Example: + + function completer(line) { + var completions = '.help .error .exit .quit .q'.split(' ') + var hits = completions.filter(function(c) { return c.indexOf(line) == 0 }) + // show all completions if none found + return [hits.length ? hits : completions, line] + } + +Also `completer` can be run in async mode if it accepts two arguments: + + function completer(linePartial, callback) { + callback(null, [['123'], linePartial]); + } + +`createInterface` is commonly used with `process.stdin` and +`process.stdout` in order to accept user input: + + var readline = require('readline'); + var rl = readline.createInterface({ + input: process.stdin, + output: process.stdout + }); + +Once you have a readline instance, you most commonly listen for the +`"line"` event. + +If `terminal` is `true` for this instance then the `output` stream will get +the best compatibility if it defines an `output.columns` property, and fires +a `"resize"` event on the `output` if/when the columns ever change +(`process.stdout` does this automatically when it is a TTY). + +## Class: Interface + +The class that represents a readline interface with an input and output +stream. + +### rl.setPrompt(prompt, length) + +Sets the prompt, for example when you run `node` on the command line, you see +`> `, which is node's prompt. + +### rl.prompt([preserveCursor]) + +Readies readline for input from the user, putting the current `setPrompt` +options on a new line, giving the user a new spot to write. Set `preserveCursor` +to `true` to prevent the cursor placement being reset to `0`. + +This will also resume the `input` stream used with `createInterface` if it has +been paused. + +### rl.question(query, callback) + +Prepends the prompt with `query` and invokes `callback` with the user's +response. Displays the query to the user, and then invokes `callback` +with the user's response after it has been typed. + +This will also resume the `input` stream used with `createInterface` if +it has been paused. + +Example usage: + + interface.question('What is your favorite food?', function(answer) { + console.log('Oh, so your favorite food is ' + answer); + }); + +### rl.pause() + +Pauses the readline `input` stream, allowing it to be resumed later if needed. + +### rl.resume() + +Resumes the readline `input` stream. + +### rl.close() + +Closes the `Interface` instance, relinquishing control on the `input` and +`output` streams. The "close" event will also be emitted. + +### rl.write(data, [key]) + +Writes `data` to `output` stream. `key` is an object literal to represent a key +sequence; available if the terminal is a TTY. + +This will also resume the `input` stream if it has been paused. + +Example: + + rl.write('Delete me!'); + // Simulate ctrl+u to delete the line written previously + rl.write(null, {ctrl: true, name: 'u'}); + +## Events + +### Event: 'line' + +`function (line) {}` + +Emitted whenever the `input` stream receives a `\n`, usually received when the +user hits enter, or return. This is a good hook to listen for user input. + +Example of listening for `line`: + + rl.on('line', function (cmd) { + console.log('You just typed: '+cmd); + }); + +### Event: 'pause' + +`function () {}` + +Emitted whenever the `input` stream is paused. + +Also emitted whenever the `input` stream is not paused and receives the +`SIGCONT` event. (See events `SIGTSTP` and `SIGCONT`) + +Example of listening for `pause`: + + rl.on('pause', function() { + console.log('Readline paused.'); + }); + +### Event: 'resume' + +`function () {}` + +Emitted whenever the `input` stream is resumed. + +Example of listening for `resume`: + + rl.on('resume', function() { + console.log('Readline resumed.'); + }); + +### Event: 'close' + +`function () {}` + +Emitted when `close()` is called. + +Also emitted when the `input` stream receives its "end" event. The `Interface` +instance should be considered "finished" once this is emitted. For example, when +the `input` stream receives `^D`, respectively known as `EOT`. + +This event is also called if there is no `SIGINT` event listener present when +the `input` stream receives a `^C`, respectively known as `SIGINT`. + +### Event: 'SIGINT' + +`function () {}` + +Emitted whenever the `input` stream receives a `^C`, respectively known as +`SIGINT`. If there is no `SIGINT` event listener present when the `input` +stream receives a `SIGINT`, `pause` will be triggered. + +Example of listening for `SIGINT`: + + rl.on('SIGINT', function() { + rl.question('Are you sure you want to exit?', function(answer) { + if (answer.match(/^y(es)?$/i)) rl.pause(); + }); + }); + +### Event: 'SIGTSTP' + +`function () {}` + +**This does not work on Windows.** + +Emitted whenever the `input` stream receives a `^Z`, respectively known as +`SIGTSTP`. If there is no `SIGTSTP` event listener present when the `input` +stream receives a `SIGTSTP`, the program will be sent to the background. + +When the program is resumed with `fg`, the `pause` and `SIGCONT` events will be +emitted. You can use either to resume the stream. + +The `pause` and `SIGCONT` events will not be triggered if the stream was paused +before the program was sent to the background. + +Example of listening for `SIGTSTP`: + + rl.on('SIGTSTP', function() { + // This will override SIGTSTP and prevent the program from going to the + // background. + console.log('Caught SIGTSTP.'); + }); + +### Event: 'SIGCONT' + +`function () {}` + +**This does not work on Windows.** + +Emitted whenever the `input` stream is sent to the background with `^Z`, +respectively known as `SIGTSTP`, and then continued with `fg(1)`. This event +only emits if the stream was not paused before sending the program to the +background. + +Example of listening for `SIGCONT`: + + rl.on('SIGCONT', function() { + // `prompt` will automatically resume the stream + rl.prompt(); + }); + + +## Example: Tiny CLI + +Here's an example of how to use all these together to craft a tiny command +line interface: + + var readline = require('readline'), + rl = readline.createInterface(process.stdin, process.stdout); + + rl.setPrompt('OHAI> '); + rl.prompt(); + + rl.on('line', function(line) { + switch(line.trim()) { + case 'hello': + console.log('world!'); + break; + default: + console.log('Say what? I might have heard `' + line.trim() + '`'); + break; + } + rl.prompt(); + }).on('close', function() { + console.log('Have a great day!'); + process.exit(0); + }); + diff --git a/node-v0.8.14/doc/api/repl.html b/node-v0.8.14/doc/api/repl.html new file mode 100644 index 0000000..9bd4080 --- /dev/null +++ b/node-v0.8.14/doc/api/repl.html @@ -0,0 +1,299 @@ + + + + + REPL Node.js v0.8.14 Manual & Documentation + + + + + +
+ + + +
+
+ + +
+
+

Node.js v0.8.14 Manual & Documentation

+ +
+
+ +
+

Table of Contents

+ + +
+ +
+

REPL#

+

A Read-Eval-Print-Loop (REPL) is available both as a standalone program and +easily includable in other programs. The REPL provides a way to interactively +run JavaScript and see the results. It can be used for debugging, testing, or +just trying things out. + +

+

By executing node without any arguments from the command-line you will be +dropped into the REPL. It has simplistic emacs line-editing. + +

+
mjr:~$ node
+Type '.help' for options.
+> a = [ 1, 2, 3];
+[ 1, 2, 3 ]
+> a.forEach(function (v) {
+...   console.log(v);
+...   });
+1
+2
+3
+

For advanced line-editors, start node with the environmental variable +NODE_NO_READLINE=1. This will start the main and debugger REPL in canonical +terminal settings which will allow you to use with rlwrap. + +

+

For example, you could add this to your bashrc file: + +

+
alias node="env NODE_NO_READLINE=1 rlwrap node"
+

repl.start(options)#

+

Returns and starts a REPLServer instance. Accepts an "options" Object that +takes the following values: + +

+
    +
  • prompt - the prompt and stream for all I/O. Defaults to > .

    +
  • +
  • input - the readable stream to listen to. Defaults to process.stdin.

    +
  • +
  • output - the writable stream to write readline data to. Defaults to +process.stdout.

    +
  • +
  • terminal - pass true if the stream should be treated like a TTY, and +have ANSI/VT100 escape codes written to it. Defaults to checking isTTY +on the output stream upon instantiation.

    +
  • +
  • eval - function that will be used to eval each given line. Defaults to +an async wrapper for eval(). See below for an example of a custom eval.

    +
  • +
  • useColors - a boolean which specifies whether or not the writer function +should output colors. If a different writer function is set then this does +nothing. Defaults to the repl's terminal value.

    +
  • +
  • useGlobal - if set to true, then the repl will use the global object, +instead of running scripts in a separate context. Defaults to false.

    +
  • +
  • ignoreUndefined - if set to true, then the repl will not output the +return value of command if it's undefined. Defaults to false.

    +
  • +
  • writer - the function to invoke for each command that gets evaluated which +returns the formatting (including coloring) to display. Defaults to +util.inspect.

    +
  • +
+

You can use your own eval function if it has following signature: + +

+
function eval(cmd, context, filename, callback) {
+  callback(null, result);
+}
+

Multiple REPLs may be started against the same running instance of node. Each +will share the same global object but will have unique I/O. + +

+

Here is an example that starts a REPL on stdin, a Unix socket, and a TCP socket: + +

+
var net = require("net"),
+    repl = require("repl");
+
+connections = 0;
+
+repl.start({
+  prompt: "node via stdin> ",
+  input: process.stdin,
+  output: process.stdout
+});
+
+net.createServer(function (socket) {
+  connections += 1;
+  repl.start({
+    prompt: "node via Unix socket> ",
+    input: socket,
+    output: socket
+  }).on('exit', function() {
+    socket.end();
+  })
+}).listen("/tmp/node-repl-sock");
+
+net.createServer(function (socket) {
+  connections += 1;
+  repl.start({
+    prompt: "node via TCP socket> ",
+    input: socket,
+    output: socket
+  }).on('exit', function() {
+    socket.end();
+  });
+}).listen(5001);
+

Running this program from the command line will start a REPL on stdin. Other +REPL clients may connect through the Unix socket or TCP socket. telnet is useful +for connecting to TCP sockets, and socat can be used to connect to both Unix and +TCP sockets. + +

+

By starting a REPL from a Unix socket-based server instead of stdin, you can +connect to a long-running node process without restarting it. + +

+

For an example of running a "full-featured" (terminal) REPL over +a net.Server and net.Socket instance, see: https://gist.github.com/2209310 + +

+

For an example of running a REPL instance over curl(1), +see: https://gist.github.com/2053342 + +

+

Event: 'exit'#

+

function () {} + +

+

Emitted when the user exits the REPL in any of the defined ways. Namely, typing +.exit at the repl, pressing Ctrl+C twice to signal SIGINT, or pressing Ctrl+D +to signal "end" on the input stream. + +

+

Example of listening for exit: + +

+
r.on('exit', function () {
+  console.log('Got "exit" event from repl!');
+  process.exit();
+});
+

REPL Features#

+ + +

Inside the REPL, Control+D will exit. Multi-line expressions can be input. +Tab completion is supported for both global and local variables. + +

+

The special variable _ (underscore) contains the result of the last expression. + +

+
> [ "a", "b", "c" ]
+[ 'a', 'b', 'c' ]
+> _.length
+3
+> _ += 1
+4
+

The REPL provides access to any variables in the global scope. You can expose +a variable to the REPL explicitly by assigning it to the context object +associated with each REPLServer. For example: + +

+
// repl_test.js
+var repl = require("repl"),
+    msg = "message";
+
+repl.start().context.m = msg;
+

Things in the context object appear as local within the REPL: + +

+
mjr:~$ node repl_test.js
+> m
+'message'
+

There are a few special REPL commands: + +

+
    +
  • .break - While inputting a multi-line expression, sometimes you get lost +or just don't care about completing it. .break will start over.
  • +
  • .clear - Resets the context object to an empty object and clears any +multi-line expression.
  • +
  • .exit - Close the I/O stream, which will cause the REPL to exit.
  • +
  • .help - Show this list of special commands.
  • +
  • .save - Save the current REPL session to a file
    +

    .save ./file/to/save.js

    +
    +
  • +
  • .load - Load a file into the current REPL session.
    +

    .load ./file/to/load.js

    +
    +
  • +
+

The following key combinations in the REPL have these special effects: + +

+
    +
  • <ctrl>C - Similar to the .break keyword. Terminates the current +command. Press twice on a blank line to forcibly exit.
  • +
  • <ctrl>D - Similar to the .exit keyword.
  • +
+ +
+
+
+ + + + + + + + + diff --git a/node-v0.8.14/doc/api/repl.json b/node-v0.8.14/doc/api/repl.json new file mode 100644 index 0000000..e17ac34 --- /dev/null +++ b/node-v0.8.14/doc/api/repl.json @@ -0,0 +1,46 @@ +{ + "source": "doc/api/repl.markdown", + "modules": [ + { + "textRaw": "REPL", + "name": "repl", + "desc": "

A Read-Eval-Print-Loop (REPL) is available both as a standalone program and\neasily includable in other programs. The REPL provides a way to interactively\nrun JavaScript and see the results. It can be used for debugging, testing, or\njust trying things out.\n\n

\n

By executing node without any arguments from the command-line you will be\ndropped into the REPL. It has simplistic emacs line-editing.\n\n

\n
mjr:~$ node\nType '.help' for options.\n> a = [ 1, 2, 3];\n[ 1, 2, 3 ]\n> a.forEach(function (v) {\n...   console.log(v);\n...   });\n1\n2\n3
\n

For advanced line-editors, start node with the environmental variable\nNODE_NO_READLINE=1. This will start the main and debugger REPL in canonical\nterminal settings which will allow you to use with rlwrap.\n\n

\n

For example, you could add this to your bashrc file:\n\n

\n
alias node="env NODE_NO_READLINE=1 rlwrap node"
\n", + "methods": [ + { + "textRaw": "repl.start(options)", + "type": "method", + "name": "start", + "desc": "

Returns and starts a REPLServer instance. Accepts an "options" Object that\ntakes the following values:\n\n

\n
    \n
  • prompt - the prompt and stream for all I/O. Defaults to > .

    \n
  • \n
  • input - the readable stream to listen to. Defaults to process.stdin.

    \n
  • \n
  • output - the writable stream to write readline data to. Defaults to\nprocess.stdout.

    \n
  • \n
  • terminal - pass true if the stream should be treated like a TTY, and\nhave ANSI/VT100 escape codes written to it. Defaults to checking isTTY\non the output stream upon instantiation.

    \n
  • \n
  • eval - function that will be used to eval each given line. Defaults to\nan async wrapper for eval(). See below for an example of a custom eval.

    \n
  • \n
  • useColors - a boolean which specifies whether or not the writer function\nshould output colors. If a different writer function is set then this does\nnothing. Defaults to the repl's terminal value.

    \n
  • \n
  • useGlobal - if set to true, then the repl will use the global object,\ninstead of running scripts in a separate context. Defaults to false.

    \n
  • \n
  • ignoreUndefined - if set to true, then the repl will not output the\nreturn value of command if it's undefined. Defaults to false.

    \n
  • \n
  • writer - the function to invoke for each command that gets evaluated which\nreturns the formatting (including coloring) to display. Defaults to\nutil.inspect.

    \n
  • \n
\n

You can use your own eval function if it has following signature:\n\n

\n
function eval(cmd, context, filename, callback) {\n  callback(null, result);\n}
\n

Multiple REPLs may be started against the same running instance of node. Each\nwill share the same global object but will have unique I/O.\n\n

\n

Here is an example that starts a REPL on stdin, a Unix socket, and a TCP socket:\n\n

\n
var net = require("net"),\n    repl = require("repl");\n\nconnections = 0;\n\nrepl.start({\n  prompt: "node via stdin> ",\n  input: process.stdin,\n  output: process.stdout\n});\n\nnet.createServer(function (socket) {\n  connections += 1;\n  repl.start({\n    prompt: "node via Unix socket> ",\n    input: socket,\n    output: socket\n  }).on('exit', function() {\n    socket.end();\n  })\n}).listen("/tmp/node-repl-sock");\n\nnet.createServer(function (socket) {\n  connections += 1;\n  repl.start({\n    prompt: "node via TCP socket> ",\n    input: socket,\n    output: socket\n  }).on('exit', function() {\n    socket.end();\n  });\n}).listen(5001);
\n

Running this program from the command line will start a REPL on stdin. Other\nREPL clients may connect through the Unix socket or TCP socket. telnet is useful\nfor connecting to TCP sockets, and socat can be used to connect to both Unix and\nTCP sockets.\n\n

\n

By starting a REPL from a Unix socket-based server instead of stdin, you can\nconnect to a long-running node process without restarting it.\n\n

\n

For an example of running a "full-featured" (terminal) REPL over\na net.Server and net.Socket instance, see: https://gist.github.com/2209310\n\n

\n

For an example of running a REPL instance over curl(1),\nsee: https://gist.github.com/2053342\n\n

\n", + "events": [ + { + "textRaw": "Event: 'exit'", + "type": "event", + "name": "exit", + "desc": "

function () {}\n\n

\n

Emitted when the user exits the REPL in any of the defined ways. Namely, typing\n.exit at the repl, pressing Ctrl+C twice to signal SIGINT, or pressing Ctrl+D\nto signal "end" on the input stream.\n\n

\n

Example of listening for exit:\n\n

\n
r.on('exit', function () {\n  console.log('Got "exit" event from repl!');\n  process.exit();\n});
\n", + "params": [] + } + ], + "signatures": [ + { + "params": [ + { + "name": "options" + } + ] + } + ] + } + ], + "miscs": [ + { + "textRaw": "REPL Features", + "name": "REPL Features", + "type": "misc", + "desc": "

Inside the REPL, Control+D will exit. Multi-line expressions can be input.\nTab completion is supported for both global and local variables.\n\n

\n

The special variable _ (underscore) contains the result of the last expression.\n\n

\n
> [ "a", "b", "c" ]\n[ 'a', 'b', 'c' ]\n> _.length\n3\n> _ += 1\n4
\n

The REPL provides access to any variables in the global scope. You can expose\na variable to the REPL explicitly by assigning it to the context object\nassociated with each REPLServer. For example:\n\n

\n
// repl_test.js\nvar repl = require("repl"),\n    msg = "message";\n\nrepl.start().context.m = msg;
\n

Things in the context object appear as local within the REPL:\n\n

\n
mjr:~$ node repl_test.js\n> m\n'message'
\n

There are a few special REPL commands:\n\n

\n
    \n
  • .break - While inputting a multi-line expression, sometimes you get lost\nor just don't care about completing it. .break will start over.
  • \n
  • .clear - Resets the context object to an empty object and clears any\nmulti-line expression.
  • \n
  • .exit - Close the I/O stream, which will cause the REPL to exit.
  • \n
  • .help - Show this list of special commands.
  • \n
  • .save - Save the current REPL session to a file
    \n

    .save ./file/to/save.js

    \n
    \n
  • \n
  • .load - Load a file into the current REPL session.
    \n

    .load ./file/to/load.js

    \n
    \n
  • \n
\n

The following key combinations in the REPL have these special effects:\n\n

\n
    \n
  • <ctrl>C - Similar to the .break keyword. Terminates the current\ncommand. Press twice on a blank line to forcibly exit.
  • \n
  • <ctrl>D - Similar to the .exit keyword.
  • \n
\n" + } + ], + "type": "module", + "displayName": "REPL" + } + ] +} diff --git a/node-v0.8.14/doc/api/repl.markdown b/node-v0.8.14/doc/api/repl.markdown new file mode 100644 index 0000000..2104136 --- /dev/null +++ b/node-v0.8.14/doc/api/repl.markdown @@ -0,0 +1,188 @@ +# REPL + +A Read-Eval-Print-Loop (REPL) is available both as a standalone program and +easily includable in other programs. The REPL provides a way to interactively +run JavaScript and see the results. It can be used for debugging, testing, or +just trying things out. + +By executing `node` without any arguments from the command-line you will be +dropped into the REPL. It has simplistic emacs line-editing. + + mjr:~$ node + Type '.help' for options. + > a = [ 1, 2, 3]; + [ 1, 2, 3 ] + > a.forEach(function (v) { + ... console.log(v); + ... }); + 1 + 2 + 3 + +For advanced line-editors, start node with the environmental variable +`NODE_NO_READLINE=1`. This will start the main and debugger REPL in canonical +terminal settings which will allow you to use with `rlwrap`. + +For example, you could add this to your bashrc file: + + alias node="env NODE_NO_READLINE=1 rlwrap node" + + +## repl.start(options) + +Returns and starts a `REPLServer` instance. Accepts an "options" Object that +takes the following values: + + - `prompt` - the prompt and `stream` for all I/O. Defaults to `> `. + + - `input` - the readable stream to listen to. Defaults to `process.stdin`. + + - `output` - the writable stream to write readline data to. Defaults to + `process.stdout`. + + - `terminal` - pass `true` if the `stream` should be treated like a TTY, and + have ANSI/VT100 escape codes written to it. Defaults to checking `isTTY` + on the `output` stream upon instantiation. + + - `eval` - function that will be used to eval each given line. Defaults to + an async wrapper for `eval()`. See below for an example of a custom `eval`. + + - `useColors` - a boolean which specifies whether or not the `writer` function + should output colors. If a different `writer` function is set then this does + nothing. Defaults to the repl's `terminal` value. + + - `useGlobal` - if set to `true`, then the repl will use the `global` object, + instead of running scripts in a separate context. Defaults to `false`. + + - `ignoreUndefined` - if set to `true`, then the repl will not output the + return value of command if it's `undefined`. Defaults to `false`. + + - `writer` - the function to invoke for each command that gets evaluated which + returns the formatting (including coloring) to display. Defaults to + `util.inspect`. + +You can use your own `eval` function if it has following signature: + + function eval(cmd, context, filename, callback) { + callback(null, result); + } + +Multiple REPLs may be started against the same running instance of node. Each +will share the same global object but will have unique I/O. + +Here is an example that starts a REPL on stdin, a Unix socket, and a TCP socket: + + var net = require("net"), + repl = require("repl"); + + connections = 0; + + repl.start({ + prompt: "node via stdin> ", + input: process.stdin, + output: process.stdout + }); + + net.createServer(function (socket) { + connections += 1; + repl.start({ + prompt: "node via Unix socket> ", + input: socket, + output: socket + }).on('exit', function() { + socket.end(); + }) + }).listen("/tmp/node-repl-sock"); + + net.createServer(function (socket) { + connections += 1; + repl.start({ + prompt: "node via TCP socket> ", + input: socket, + output: socket + }).on('exit', function() { + socket.end(); + }); + }).listen(5001); + +Running this program from the command line will start a REPL on stdin. Other +REPL clients may connect through the Unix socket or TCP socket. `telnet` is useful +for connecting to TCP sockets, and `socat` can be used to connect to both Unix and +TCP sockets. + +By starting a REPL from a Unix socket-based server instead of stdin, you can +connect to a long-running node process without restarting it. + +For an example of running a "full-featured" (`terminal`) REPL over +a `net.Server` and `net.Socket` instance, see: https://gist.github.com/2209310 + +For an example of running a REPL instance over `curl(1)`, +see: https://gist.github.com/2053342 + +### Event: 'exit' + +`function () {}` + +Emitted when the user exits the REPL in any of the defined ways. Namely, typing +`.exit` at the repl, pressing Ctrl+C twice to signal SIGINT, or pressing Ctrl+D +to signal "end" on the `input` stream. + +Example of listening for `exit`: + + r.on('exit', function () { + console.log('Got "exit" event from repl!'); + process.exit(); + }); + + +## REPL Features + + + +Inside the REPL, Control+D will exit. Multi-line expressions can be input. +Tab completion is supported for both global and local variables. + +The special variable `_` (underscore) contains the result of the last expression. + + > [ "a", "b", "c" ] + [ 'a', 'b', 'c' ] + > _.length + 3 + > _ += 1 + 4 + +The REPL provides access to any variables in the global scope. You can expose +a variable to the REPL explicitly by assigning it to the `context` object +associated with each `REPLServer`. For example: + + // repl_test.js + var repl = require("repl"), + msg = "message"; + + repl.start().context.m = msg; + +Things in the `context` object appear as local within the REPL: + + mjr:~$ node repl_test.js + > m + 'message' + +There are a few special REPL commands: + + - `.break` - While inputting a multi-line expression, sometimes you get lost + or just don't care about completing it. `.break` will start over. + - `.clear` - Resets the `context` object to an empty object and clears any + multi-line expression. + - `.exit` - Close the I/O stream, which will cause the REPL to exit. + - `.help` - Show this list of special commands. + - `.save` - Save the current REPL session to a file + >.save ./file/to/save.js + - `.load` - Load a file into the current REPL session. + >.load ./file/to/load.js + +The following key combinations in the REPL have these special effects: + + - `C` - Similar to the `.break` keyword. Terminates the current + command. Press twice on a blank line to forcibly exit. + - `D` - Similar to the `.exit` keyword. + diff --git a/node-v0.8.14/doc/api/stdio.html b/node-v0.8.14/doc/api/stdio.html new file mode 100644 index 0000000..d3b4675 --- /dev/null +++ b/node-v0.8.14/doc/api/stdio.html @@ -0,0 +1,159 @@ + + + + + console Node.js v0.8.14 Manual & Documentation + + + + + +
+ + + +
+
+ + +
+
+

Node.js v0.8.14 Manual & Documentation

+ +
+
+ + + +
+

console#

+
Stability: 4 - API Frozen
+
    +
  • {Object}
  • +
+ + +

For printing to stdout and stderr. Similar to the console object functions +provided by most web browsers, here the output is sent to stdout or stderr. + +

+

console.log([data], [...])#

+

Prints to stdout with newline. This function can take multiple arguments in a +printf()-like way. Example: + +

+
console.log('count: %d', count);
+

If formatting elements are not found in the first string then util.inspect +is used on each argument. See util.format() for more information. + +

+

console.info([data], [...])#

+

Same as console.log. + +

+

console.error([data], [...])#

+

Same as console.log but prints to stderr. + +

+

console.warn([data], [...])#

+

Same as console.error. + +

+

console.dir(obj)#

+

Uses util.inspect on obj and prints resulting string to stdout. + +

+

console.time(label)#

+

Mark a time. + +

+

console.timeEnd(label)#

+

Finish timer, record output. Example: + +

+
console.time('100-elements');
+for (var i = 0; i < 100; i++) {
+  ;
+}
+console.timeEnd('100-elements');
+

console.trace(label)#

+

Print a stack trace to stderr of the current position. + +

+

console.assert(expression, [message])#

+

Same as assert.ok() where if the expression evaluates as false throw an +AssertionError with message. + +

+ +
+
+
+ + + + + + + + + diff --git a/node-v0.8.14/doc/api/stdio.json b/node-v0.8.14/doc/api/stdio.json new file mode 100644 index 0000000..5197880 --- /dev/null +++ b/node-v0.8.14/doc/api/stdio.json @@ -0,0 +1,174 @@ +{ + "source": "doc/api/stdio.markdown", + "globals": [ + { + "textRaw": "console", + "name": "console", + "stability": 4, + "stabilityText": "API Frozen", + "type": "global", + "desc": "

For printing to stdout and stderr. Similar to the console object functions\nprovided by most web browsers, here the output is sent to stdout or stderr.\n\n

\n", + "methods": [ + { + "textRaw": "console.log([data], [...])", + "type": "method", + "name": "log", + "desc": "

Prints to stdout with newline. This function can take multiple arguments in a\nprintf()-like way. Example:\n\n

\n
console.log('count: %d', count);
\n

If formatting elements are not found in the first string then util.inspect\nis used on each argument. See [util.format()][] for more information.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "data", + "optional": true + }, + { + "name": "...", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "console.info([data], [...])", + "type": "method", + "name": "info", + "desc": "

Same as console.log.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "data", + "optional": true + }, + { + "name": "...", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "console.error([data], [...])", + "type": "method", + "name": "error", + "desc": "

Same as console.log but prints to stderr.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "data", + "optional": true + }, + { + "name": "...", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "console.warn([data], [...])", + "type": "method", + "name": "warn", + "desc": "

Same as console.error.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "data", + "optional": true + }, + { + "name": "...", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "console.dir(obj)", + "type": "method", + "name": "dir", + "desc": "

Uses util.inspect on obj and prints resulting string to stdout.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "obj" + } + ] + } + ] + }, + { + "textRaw": "console.time(label)", + "type": "method", + "name": "time", + "desc": "

Mark a time.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "label" + } + ] + } + ] + }, + { + "textRaw": "console.timeEnd(label)", + "type": "method", + "name": "timeEnd", + "desc": "

Finish timer, record output. Example:\n\n

\n
console.time('100-elements');\nfor (var i = 0; i < 100; i++) {\n  ;\n}\nconsole.timeEnd('100-elements');
\n", + "signatures": [ + { + "params": [ + { + "name": "label" + } + ] + } + ] + }, + { + "textRaw": "console.trace(label)", + "type": "method", + "name": "trace", + "desc": "

Print a stack trace to stderr of the current position.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "label" + } + ] + } + ] + }, + { + "textRaw": "console.assert(expression, [message])", + "type": "method", + "name": "assert", + "desc": "

Same as [assert.ok()][] where if the expression evaluates as false throw an\nAssertionError with message.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "expression" + }, + { + "name": "message", + "optional": true + } + ] + } + ] + } + ] + } + ] +} diff --git a/node-v0.8.14/doc/api/stdio.markdown b/node-v0.8.14/doc/api/stdio.markdown new file mode 100644 index 0000000..0da30a0 --- /dev/null +++ b/node-v0.8.14/doc/api/stdio.markdown @@ -0,0 +1,62 @@ +# console + + Stability: 4 - API Frozen + +* {Object} + + + +For printing to stdout and stderr. Similar to the console object functions +provided by most web browsers, here the output is sent to stdout or stderr. + +## console.log([data], [...]) + +Prints to stdout with newline. This function can take multiple arguments in a +`printf()`-like way. Example: + + console.log('count: %d', count); + +If formatting elements are not found in the first string then `util.inspect` +is used on each argument. See [util.format()][] for more information. + +## console.info([data], [...]) + +Same as `console.log`. + +## console.error([data], [...]) + +Same as `console.log` but prints to stderr. + +## console.warn([data], [...]) + +Same as `console.error`. + +## console.dir(obj) + +Uses `util.inspect` on `obj` and prints resulting string to stdout. + +## console.time(label) + +Mark a time. + +## console.timeEnd(label) + +Finish timer, record output. Example: + + console.time('100-elements'); + for (var i = 0; i < 100; i++) { + ; + } + console.timeEnd('100-elements'); + +## console.trace(label) + +Print a stack trace to stderr of the current position. + +## console.assert(expression, [message]) + +Same as [assert.ok()][] where if the `expression` evaluates as `false` throw an +AssertionError with `message`. + +[assert.ok()]: assert.html#assert_assert_value_message_assert_ok_value_message +[util.format()]: util.html#util_util_format_format diff --git a/node-v0.8.14/doc/api/stream.html b/node-v0.8.14/doc/api/stream.html new file mode 100644 index 0000000..9e83e62 --- /dev/null +++ b/node-v0.8.14/doc/api/stream.html @@ -0,0 +1,322 @@ + + + + + Stream Node.js v0.8.14 Manual & Documentation + + + + + +
+ + + +
+
+ + +
+
+

Node.js v0.8.14 Manual & Documentation

+ +
+
+ + + +
+

Stream#

+
Stability: 2 - Unstable
+

A stream is an abstract interface implemented by various objects in +Node. For example a request to an HTTP server is a stream, as is +stdout. Streams are readable, writable, or both. All streams are +instances of EventEmitter + +

+

You can load up the Stream base class by doing require('stream'). + +

+

Readable Stream#

+ + +

A Readable Stream has the following methods, members, and events. + +

+

Event: 'data'#

+

function (data) { } + +

+

The 'data' event emits either a Buffer (by default) or a string if +setEncoding() was used. + +

+

Note that the data will be lost if there is no listener when a +Readable Stream emits a 'data' event. + +

+

Event: 'end'#

+

function () { } + +

+

Emitted when the stream has received an EOF (FIN in TCP terminology). +Indicates that no more 'data' events will happen. If the stream is +also writable, it may be possible to continue writing. + +

+

Event: 'error'#

+

function (exception) { } + +

+

Emitted if there was an error receiving data. + +

+

Event: 'close'#

+

function () { } + +

+

Emitted when the underlying resource (for example, the backing file +descriptor) has been closed. Not all streams will emit this. + +

+

stream.readable#

+

A boolean that is true by default, but turns false after an +'error' occurred, the stream came to an 'end', or destroy() was +called. + +

+

stream.setEncoding([encoding])#

+

Makes the 'data' event emit a string instead of a Buffer. encoding +can be 'utf8', 'utf16le' ('ucs2'), 'ascii', or 'hex'. Defaults +to 'utf8'. + +

+

stream.pause()#

+

Issues an advisory signal to the underlying communication layer, +requesting that no further data be sent until resume() is called. + +

+

Note that, due to the advisory nature, certain streams will not be +paused immediately, and so 'data' events may be emitted for some +indeterminate period of time even after pause() is called. You may +wish to buffer such 'data' events. + +

+

stream.resume()#

+

Resumes the incoming 'data' events after a pause(). + +

+

stream.destroy()#

+

Closes the underlying file descriptor. Stream is no longer writable +nor readable. The stream will not emit any more 'data', or 'end' +events. Any queued write data will not be sent. The stream should emit +'close' event once its resources have been disposed of. + + +

+

stream.pipe(destination, [options])#

+

This is a Stream.prototype method available on all Streams. + +

+

Connects this read stream to destination WriteStream. Incoming data on +this stream gets written to destination. The destination and source +streams are kept in sync by pausing and resuming as necessary. + +

+

This function returns the destination stream. + +

+

Emulating the Unix cat command: + +

+
process.stdin.resume(); process.stdin.pipe(process.stdout);
+

By default end() is called on the destination when the source stream +emits end, so that destination is no longer writable. Pass { end: +false } as options to keep the destination stream open. + +

+

This keeps process.stdout open so that "Goodbye" can be written at the +end. + +

+
process.stdin.resume();
+
+process.stdin.pipe(process.stdout, { end: false });
+
+process.stdin.on("end", function() {
+process.stdout.write("Goodbye\n"); });
+

Writable Stream#

+ + +

A Writable Stream has the following methods, members, and events. + +

+

Event: 'drain'#

+

function () { } + +

+

Emitted when the stream's write queue empties and it's safe to write without +buffering again. Listen for it when stream.write() returns false. + +

+

The 'drain' event can happen at any time, regardless of whether or not +stream.write() has previously returned false. To avoid receiving unwanted +'drain' events, listen using stream.once(). + +

+

Event: 'error'#

+

function (exception) { } + +

+

Emitted on error with the exception exception. + +

+

Event: 'close'#

+

function () { } + +

+

Emitted when the underlying file descriptor has been closed. + +

+

Event: 'pipe'#

+

function (src) { } + +

+

Emitted when the stream is passed to a readable stream's pipe method. + +

+

stream.writable#

+

A boolean that is true by default, but turns false after an +'error' occurred or end() / destroy() was called. + +

+

stream.write(string, [encoding])#

+

Writes string with the given encoding to the stream. Returns true +if the string has been flushed to the kernel buffer. Returns false to +indicate that the kernel buffer is full, and the data will be sent out +in the future. The 'drain' event will indicate when the kernel buffer +is empty again. The encoding defaults to 'utf8'. + +

+

stream.write(buffer)#

+

Same as the above except with a raw buffer. + +

+

stream.end()#

+

Terminates the stream with EOF or FIN. This call will allow queued +write data to be sent before closing the stream. + +

+

stream.end(string, encoding)#

+

Sends string with the given encoding and terminates the stream with +EOF or FIN. This is useful to reduce the number of packets sent. + +

+

stream.end(buffer)#

+

Same as above but with a buffer. + +

+

stream.destroy()#

+

Closes the underlying file descriptor. Stream is no longer writable +nor readable. The stream will not emit any more 'data', or 'end' +events. Any queued write data will not be sent. The stream should emit +'close' event once its resources have been disposed of. + +

+

stream.destroySoon()#

+

After the write queue is drained, close the file descriptor. +destroySoon() can still destroy straight away, as long as there is no +data left in the queue for writes. + +

+ +
+
+
+ + + + + + + + + diff --git a/node-v0.8.14/doc/api/stream.json b/node-v0.8.14/doc/api/stream.json new file mode 100644 index 0000000..c7e5c5f --- /dev/null +++ b/node-v0.8.14/doc/api/stream.json @@ -0,0 +1,274 @@ +{ + "source": "doc/api/stream.markdown", + "modules": [ + { + "textRaw": "Stream", + "name": "stream", + "stability": 2, + "stabilityText": "Unstable", + "desc": "

A stream is an abstract interface implemented by various objects in\nNode. For example a request to an HTTP server is a stream, as is\nstdout. Streams are readable, writable, or both. All streams are\ninstances of [EventEmitter][]\n\n

\n

You can load up the Stream base class by doing require('stream').\n\n

\n", + "classes": [ + { + "textRaw": "Readable Stream", + "name": "Readable Stream", + "type": "class", + "desc": "

A Readable Stream has the following methods, members, and events.\n\n

\n", + "events": [ + { + "textRaw": "Event: 'data'", + "type": "event", + "name": "data", + "desc": "

function (data) { }\n\n

\n

The 'data' event emits either a Buffer (by default) or a string if\nsetEncoding() was used.\n\n

\n

Note that the data will be lost if there is no listener when a\nReadable Stream emits a 'data' event.\n\n

\n", + "params": [] + }, + { + "textRaw": "Event: 'end'", + "type": "event", + "name": "end", + "desc": "

function () { }\n\n

\n

Emitted when the stream has received an EOF (FIN in TCP terminology).\nIndicates that no more 'data' events will happen. If the stream is\nalso writable, it may be possible to continue writing.\n\n

\n", + "params": [] + }, + { + "textRaw": "Event: 'error'", + "type": "event", + "name": "error", + "desc": "

function (exception) { }\n\n

\n

Emitted if there was an error receiving data.\n\n

\n", + "params": [] + }, + { + "textRaw": "Event: 'close'", + "type": "event", + "name": "close", + "desc": "

function () { }\n\n

\n

Emitted when the underlying resource (for example, the backing file\ndescriptor) has been closed. Not all streams will emit this.\n\n

\n", + "params": [] + } + ], + "properties": [ + { + "textRaw": "stream.readable", + "name": "readable", + "desc": "

A boolean that is true by default, but turns false after an\n'error' occurred, the stream came to an 'end', or destroy() was\ncalled.\n\n

\n" + } + ], + "methods": [ + { + "textRaw": "stream.setEncoding([encoding])", + "type": "method", + "name": "setEncoding", + "desc": "

Makes the 'data' event emit a string instead of a Buffer. encoding\ncan be 'utf8', 'utf16le' ('ucs2'), 'ascii', or 'hex'. Defaults\nto 'utf8'.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "encoding", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "stream.pause()", + "type": "method", + "name": "pause", + "desc": "

Issues an advisory signal to the underlying communication layer,\nrequesting that no further data be sent until resume() is called.\n\n

\n

Note that, due to the advisory nature, certain streams will not be\npaused immediately, and so 'data' events may be emitted for some\nindeterminate period of time even after pause() is called. You may\nwish to buffer such 'data' events.\n\n

\n", + "signatures": [ + { + "params": [] + } + ] + }, + { + "textRaw": "stream.resume()", + "type": "method", + "name": "resume", + "desc": "

Resumes the incoming 'data' events after a pause().\n\n

\n", + "signatures": [ + { + "params": [] + } + ] + }, + { + "textRaw": "stream.destroy()", + "type": "method", + "name": "destroy", + "desc": "

Closes the underlying file descriptor. Stream is no longer writable\nnor readable. The stream will not emit any more 'data', or 'end'\nevents. Any queued write data will not be sent. The stream should emit\n'close' event once its resources have been disposed of.\n\n\n

\n", + "signatures": [ + { + "params": [] + } + ] + }, + { + "textRaw": "stream.pipe(destination, [options])", + "type": "method", + "name": "pipe", + "desc": "

This is a Stream.prototype method available on all Streams.\n\n

\n

Connects this read stream to destination WriteStream. Incoming data on\nthis stream gets written to destination. The destination and source\nstreams are kept in sync by pausing and resuming as necessary.\n\n

\n

This function returns the destination stream.\n\n

\n

Emulating the Unix cat command:\n\n

\n
process.stdin.resume(); process.stdin.pipe(process.stdout);
\n

By default end() is called on the destination when the source stream\nemits end, so that destination is no longer writable. Pass { end:\nfalse } as options to keep the destination stream open.\n\n

\n

This keeps process.stdout open so that "Goodbye" can be written at the\nend.\n\n

\n
process.stdin.resume();\n\nprocess.stdin.pipe(process.stdout, { end: false });\n\nprocess.stdin.on("end", function() {\nprocess.stdout.write("Goodbye\\n"); });
\n", + "signatures": [ + { + "params": [ + { + "name": "destination" + }, + { + "name": "options", + "optional": true + } + ] + } + ] + } + ] + }, + { + "textRaw": "Writable Stream", + "name": "Writable Stream", + "type": "class", + "desc": "

A Writable Stream has the following methods, members, and events.\n\n

\n", + "events": [ + { + "textRaw": "Event: 'drain'", + "type": "event", + "name": "drain", + "desc": "

function () { }\n\n

\n

Emitted when the stream's write queue empties and it's safe to write without\nbuffering again. Listen for it when stream.write() returns false.\n\n

\n

The 'drain' event can happen at any time, regardless of whether or not\nstream.write() has previously returned false. To avoid receiving unwanted\n'drain' events, listen using stream.once().\n\n

\n", + "params": [] + }, + { + "textRaw": "Event: 'error'", + "type": "event", + "name": "error", + "desc": "

function (exception) { }\n\n

\n

Emitted on error with the exception exception.\n\n

\n", + "params": [] + }, + { + "textRaw": "Event: 'close'", + "type": "event", + "name": "close", + "desc": "

function () { }\n\n

\n

Emitted when the underlying file descriptor has been closed.\n\n

\n", + "params": [] + }, + { + "textRaw": "Event: 'pipe'", + "type": "event", + "name": "pipe", + "desc": "

function (src) { }\n\n

\n

Emitted when the stream is passed to a readable stream's pipe method.\n\n

\n", + "params": [] + } + ], + "properties": [ + { + "textRaw": "stream.writable", + "name": "writable", + "desc": "

A boolean that is true by default, but turns false after an\n'error' occurred or end() / destroy() was called.\n\n

\n" + } + ], + "methods": [ + { + "textRaw": "stream.write(string, [encoding])", + "type": "method", + "name": "write", + "desc": "

Writes string with the given encoding to the stream. Returns true\nif the string has been flushed to the kernel buffer. Returns false to\nindicate that the kernel buffer is full, and the data will be sent out\nin the future. The 'drain' event will indicate when the kernel buffer\nis empty again. The encoding defaults to 'utf8'.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "string" + }, + { + "name": "encoding", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "stream.write(buffer)", + "type": "method", + "name": "write", + "desc": "

Same as the above except with a raw buffer.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "buffer" + } + ] + } + ] + }, + { + "textRaw": "stream.end()", + "type": "method", + "name": "end", + "desc": "

Terminates the stream with EOF or FIN. This call will allow queued\nwrite data to be sent before closing the stream.\n\n

\n", + "signatures": [ + { + "params": [] + } + ] + }, + { + "textRaw": "stream.end(string, encoding)", + "type": "method", + "name": "end", + "desc": "

Sends string with the given encoding and terminates the stream with\nEOF or FIN. This is useful to reduce the number of packets sent.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "string" + }, + { + "name": "encoding" + } + ] + } + ] + }, + { + "textRaw": "stream.end(buffer)", + "type": "method", + "name": "end", + "desc": "

Same as above but with a buffer.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "buffer" + } + ] + } + ] + }, + { + "textRaw": "stream.destroy()", + "type": "method", + "name": "destroy", + "desc": "

Closes the underlying file descriptor. Stream is no longer writable\nnor readable. The stream will not emit any more 'data', or 'end'\nevents. Any queued write data will not be sent. The stream should emit\n'close' event once its resources have been disposed of.\n\n

\n", + "signatures": [ + { + "params": [] + } + ] + }, + { + "textRaw": "stream.destroySoon()", + "type": "method", + "name": "destroySoon", + "desc": "

After the write queue is drained, close the file descriptor.\ndestroySoon() can still destroy straight away, as long as there is no\ndata left in the queue for writes.\n\n

\n", + "signatures": [ + { + "params": [] + } + ] + } + ] + } + ], + "type": "module", + "displayName": "Stream" + } + ] +} diff --git a/node-v0.8.14/doc/api/stream.markdown b/node-v0.8.14/doc/api/stream.markdown new file mode 100644 index 0000000..5e0c6f6 --- /dev/null +++ b/node-v0.8.14/doc/api/stream.markdown @@ -0,0 +1,192 @@ +# Stream + + Stability: 2 - Unstable + +A stream is an abstract interface implemented by various objects in +Node. For example a request to an HTTP server is a stream, as is +stdout. Streams are readable, writable, or both. All streams are +instances of [EventEmitter][] + +You can load up the Stream base class by doing `require('stream')`. + +## Readable Stream + + + +A `Readable Stream` has the following methods, members, and events. + +### Event: 'data' + +`function (data) { }` + +The `'data'` event emits either a `Buffer` (by default) or a string if +`setEncoding()` was used. + +Note that the __data will be lost__ if there is no listener when a +`Readable Stream` emits a `'data'` event. + +### Event: 'end' + +`function () { }` + +Emitted when the stream has received an EOF (FIN in TCP terminology). +Indicates that no more `'data'` events will happen. If the stream is +also writable, it may be possible to continue writing. + +### Event: 'error' + +`function (exception) { }` + +Emitted if there was an error receiving data. + +### Event: 'close' + +`function () { }` + +Emitted when the underlying resource (for example, the backing file +descriptor) has been closed. Not all streams will emit this. + +### stream.readable + +A boolean that is `true` by default, but turns `false` after an +`'error'` occurred, the stream came to an `'end'`, or `destroy()` was +called. + +### stream.setEncoding([encoding]) + +Makes the `'data'` event emit a string instead of a `Buffer`. `encoding` +can be `'utf8'`, `'utf16le'` (`'ucs2'`), `'ascii'`, or `'hex'`. Defaults +to `'utf8'`. + +### stream.pause() + +Issues an advisory signal to the underlying communication layer, +requesting that no further data be sent until `resume()` is called. + +Note that, due to the advisory nature, certain streams will not be +paused immediately, and so `'data'` events may be emitted for some +indeterminate period of time even after `pause()` is called. You may +wish to buffer such `'data'` events. + +### stream.resume() + +Resumes the incoming `'data'` events after a `pause()`. + +### stream.destroy() + +Closes the underlying file descriptor. Stream is no longer `writable` +nor `readable`. The stream will not emit any more 'data', or 'end' +events. Any queued write data will not be sent. The stream should emit +'close' event once its resources have been disposed of. + + +### stream.pipe(destination, [options]) + +This is a `Stream.prototype` method available on all `Stream`s. + +Connects this read stream to `destination` WriteStream. Incoming data on +this stream gets written to `destination`. The destination and source +streams are kept in sync by pausing and resuming as necessary. + +This function returns the `destination` stream. + +Emulating the Unix `cat` command: + + process.stdin.resume(); process.stdin.pipe(process.stdout); + + +By default `end()` is called on the destination when the source stream +emits `end`, so that `destination` is no longer writable. Pass `{ end: +false }` as `options` to keep the destination stream open. + +This keeps `process.stdout` open so that "Goodbye" can be written at the +end. + + process.stdin.resume(); + + process.stdin.pipe(process.stdout, { end: false }); + + process.stdin.on("end", function() { + process.stdout.write("Goodbye\n"); }); + + +## Writable Stream + + + +A `Writable Stream` has the following methods, members, and events. + +### Event: 'drain' + +`function () { }` + +Emitted when the stream's write queue empties and it's safe to write without +buffering again. Listen for it when `stream.write()` returns `false`. + +The `'drain'` event can happen at *any* time, regardless of whether or not +`stream.write()` has previously returned `false`. To avoid receiving unwanted +`'drain'` events, listen using `stream.once()`. + +### Event: 'error' + +`function (exception) { }` + +Emitted on error with the exception `exception`. + +### Event: 'close' + +`function () { }` + +Emitted when the underlying file descriptor has been closed. + +### Event: 'pipe' + +`function (src) { }` + +Emitted when the stream is passed to a readable stream's pipe method. + +### stream.writable + +A boolean that is `true` by default, but turns `false` after an +`'error'` occurred or `end()` / `destroy()` was called. + +### stream.write(string, [encoding]) + +Writes `string` with the given `encoding` to the stream. Returns `true` +if the string has been flushed to the kernel buffer. Returns `false` to +indicate that the kernel buffer is full, and the data will be sent out +in the future. The `'drain'` event will indicate when the kernel buffer +is empty again. The `encoding` defaults to `'utf8'`. + +### stream.write(buffer) + +Same as the above except with a raw buffer. + +### stream.end() + +Terminates the stream with EOF or FIN. This call will allow queued +write data to be sent before closing the stream. + +### stream.end(string, encoding) + +Sends `string` with the given `encoding` and terminates the stream with +EOF or FIN. This is useful to reduce the number of packets sent. + +### stream.end(buffer) + +Same as above but with a `buffer`. + +### stream.destroy() + +Closes the underlying file descriptor. Stream is no longer `writable` +nor `readable`. The stream will not emit any more 'data', or 'end' +events. Any queued write data will not be sent. The stream should emit +'close' event once its resources have been disposed of. + +### stream.destroySoon() + +After the write queue is drained, close the file descriptor. +`destroySoon()` can still destroy straight away, as long as there is no +data left in the queue for writes. + +[EventEmitter]: events.html#events_class_events_eventemitter diff --git a/node-v0.8.14/doc/api/string_decoder.html b/node-v0.8.14/doc/api/string_decoder.html new file mode 100644 index 0000000..90dd910 --- /dev/null +++ b/node-v0.8.14/doc/api/string_decoder.html @@ -0,0 +1,116 @@ + + + + + StringDecoder Node.js v0.8.14 Manual & Documentation + + + + + +
+ + + +
+
+ + +
+
+

Node.js v0.8.14 Manual & Documentation

+ +
+
+ +
+

Table of Contents

+ + +
+ +
+

StringDecoder#

+
Stability: 3 - Stable
+

To use this module, do require('string_decoder'). StringDecoder decodes a +buffer to a string. It is a simple interface to buffer.toString() but provides +additional support for utf8. + +

+
var StringDecoder = require('string_decoder').StringDecoder;
+var decoder = new StringDecoder('utf8');
+
+var cent = new Buffer([0xC2, 0xA2]);
+console.log(decoder.write(cent));
+
+var euro = new Buffer([0xE2, 0x82, 0xAC]);
+console.log(decoder.write(euro));
+

Class: StringDecoder#

+

Accepts a single argument, encoding which defaults to utf8. + +

+

StringDecoder.write(buffer)#

+

Returns a decoded string.

+ +
+
+
+ + + + + + + + + diff --git a/node-v0.8.14/doc/api/string_decoder.json b/node-v0.8.14/doc/api/string_decoder.json new file mode 100644 index 0000000..76b6b2e --- /dev/null +++ b/node-v0.8.14/doc/api/string_decoder.json @@ -0,0 +1,39 @@ +{ + "source": "doc/api/string_decoder.markdown", + "modules": [ + { + "textRaw": "StringDecoder", + "name": "stringdecoder", + "stability": 3, + "stabilityText": "Stable", + "desc": "

To use this module, do require('string_decoder'). StringDecoder decodes a\nbuffer to a string. It is a simple interface to buffer.toString() but provides\nadditional support for utf8.\n\n

\n
var StringDecoder = require('string_decoder').StringDecoder;\nvar decoder = new StringDecoder('utf8');\n\nvar cent = new Buffer([0xC2, 0xA2]);\nconsole.log(decoder.write(cent));\n\nvar euro = new Buffer([0xE2, 0x82, 0xAC]);\nconsole.log(decoder.write(euro));
\n", + "classes": [ + { + "textRaw": "Class: StringDecoder", + "type": "class", + "name": "StringDecoder", + "desc": "

Accepts a single argument, encoding which defaults to utf8.\n\n

\n", + "methods": [ + { + "textRaw": "StringDecoder.write(buffer)", + "type": "method", + "name": "write", + "desc": "

Returns a decoded string.

\n", + "signatures": [ + { + "params": [ + { + "name": "buffer" + } + ] + } + ] + } + ] + } + ], + "type": "module", + "displayName": "StringDecoder" + } + ] +} diff --git a/node-v0.8.14/doc/api/string_decoder.markdown b/node-v0.8.14/doc/api/string_decoder.markdown new file mode 100644 index 0000000..2ad2fb1 --- /dev/null +++ b/node-v0.8.14/doc/api/string_decoder.markdown @@ -0,0 +1,24 @@ +# StringDecoder + + Stability: 3 - Stable + +To use this module, do `require('string_decoder')`. StringDecoder decodes a +buffer to a string. It is a simple interface to `buffer.toString()` but provides +additional support for utf8. + + var StringDecoder = require('string_decoder').StringDecoder; + var decoder = new StringDecoder('utf8'); + + var cent = new Buffer([0xC2, 0xA2]); + console.log(decoder.write(cent)); + + var euro = new Buffer([0xE2, 0x82, 0xAC]); + console.log(decoder.write(euro)); + +## Class: StringDecoder + +Accepts a single argument, `encoding` which defaults to `utf8`. + +### StringDecoder.write(buffer) + +Returns a decoded string. \ No newline at end of file diff --git a/node-v0.8.14/doc/api/synopsis.html b/node-v0.8.14/doc/api/synopsis.html new file mode 100644 index 0000000..8441098 --- /dev/null +++ b/node-v0.8.14/doc/api/synopsis.html @@ -0,0 +1,112 @@ + + + + + Synopsis Node.js v0.8.14 Manual & Documentation + + + + + +
+ + + +
+
+ + +
+
+

Node.js v0.8.14 Manual & Documentation

+ +
+
+ +
+

Table of Contents

+ + +
+ +
+

Synopsis#

+ + +

An example of a web server written with Node which responds with 'Hello +World': + +

+
var http = require('http');
+
+http.createServer(function (request, response) {
+  response.writeHead(200, {'Content-Type': 'text/plain'});
+  response.end('Hello World\n');
+}).listen(8124);
+
+console.log('Server running at http://127.0.0.1:8124/');
+

To run the server, put the code into a file called example.js and execute +it with the node program + +

+
> node example.js
+Server running at http://127.0.0.1:8124/
+

All of the examples in the documentation can be run similarly. +

+ +
+
+
+ + + + + + + + + diff --git a/node-v0.8.14/doc/api/synopsis.json b/node-v0.8.14/doc/api/synopsis.json new file mode 100644 index 0000000..0950239 --- /dev/null +++ b/node-v0.8.14/doc/api/synopsis.json @@ -0,0 +1,11 @@ +{ + "source": "doc/api/synopsis.markdown", + "miscs": [ + { + "textRaw": "Synopsis", + "name": "Synopsis", + "type": "misc", + "desc": "

An example of a web server written with Node which responds with 'Hello\nWorld':\n\n

\n
var http = require('http');\n\nhttp.createServer(function (request, response) {\n  response.writeHead(200, {'Content-Type': 'text/plain'});\n  response.end('Hello World\\n');\n}).listen(8124);\n\nconsole.log('Server running at http://127.0.0.1:8124/');
\n

To run the server, put the code into a file called example.js and execute\nit with the node program\n\n

\n
> node example.js\nServer running at http://127.0.0.1:8124/
\n

All of the examples in the documentation can be run similarly.\n

\n" + } + ] +} diff --git a/node-v0.8.14/doc/api/synopsis.markdown b/node-v0.8.14/doc/api/synopsis.markdown new file mode 100644 index 0000000..b3b4608 --- /dev/null +++ b/node-v0.8.14/doc/api/synopsis.markdown @@ -0,0 +1,23 @@ +# Synopsis + + + +An example of a [web server](http.html) written with Node which responds with 'Hello +World': + + var http = require('http'); + + http.createServer(function (request, response) { + response.writeHead(200, {'Content-Type': 'text/plain'}); + response.end('Hello World\n'); + }).listen(8124); + + console.log('Server running at http://127.0.0.1:8124/'); + +To run the server, put the code into a file called `example.js` and execute +it with the node program + + > node example.js + Server running at http://127.0.0.1:8124/ + +All of the examples in the documentation can be run similarly. diff --git a/node-v0.8.14/doc/api/timers.html b/node-v0.8.14/doc/api/timers.html new file mode 100644 index 0000000..f270919 --- /dev/null +++ b/node-v0.8.14/doc/api/timers.html @@ -0,0 +1,126 @@ + + + + + Timers Node.js v0.8.14 Manual & Documentation + + + + + +
+ + + +
+
+ + +
+
+

Node.js v0.8.14 Manual & Documentation

+ +
+
+ + + +
+

Timers#

+
Stability: 5 - Locked
+

All of the timer functions are globals. You do not need to require() +this module in order to use them. + +

+

setTimeout(callback, delay, [arg], [...])#

+

To schedule execution of a one-time callback after delay milliseconds. Returns a +timeoutId for possible use with clearTimeout(). Optionally you can +also pass arguments to the callback. + +

+

It is important to note that your callback will probably not be called in exactly +delay milliseconds - Node.js makes no guarantees about the exact timing of when +the callback will fire, nor of the ordering things will fire in. The callback will +be called as close as possible to the time specified. + +

+

clearTimeout(timeoutId)#

+

Prevents a timeout from triggering. + +

+

setInterval(callback, delay, [arg], [...])#

+

To schedule the repeated execution of callback every delay milliseconds. +Returns a intervalId for possible use with clearInterval(). Optionally +you can also pass arguments to the callback. + +

+

clearInterval(intervalId)#

+

Stops a interval from triggering. +

+ +
+
+
+ + + + + + + + + diff --git a/node-v0.8.14/doc/api/timers.json b/node-v0.8.14/doc/api/timers.json new file mode 100644 index 0000000..692b432 --- /dev/null +++ b/node-v0.8.14/doc/api/timers.json @@ -0,0 +1,98 @@ +{ + "source": "doc/api/timers.markdown", + "modules": [ + { + "textRaw": "Timers", + "name": "timers", + "stability": 5, + "stabilityText": "Locked", + "desc": "

All of the timer functions are globals. You do not need to require()\nthis module in order to use them.\n\n

\n", + "methods": [ + { + "textRaw": "setTimeout(callback, delay, [arg], [...])", + "type": "method", + "name": "setTimeout", + "desc": "

To schedule execution of a one-time callback after delay milliseconds. Returns a\ntimeoutId for possible use with clearTimeout(). Optionally you can\nalso pass arguments to the callback.\n\n

\n

It is important to note that your callback will probably not be called in exactly\ndelay milliseconds - Node.js makes no guarantees about the exact timing of when\nthe callback will fire, nor of the ordering things will fire in. The callback will\nbe called as close as possible to the time specified.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "callback" + }, + { + "name": "delay" + }, + { + "name": "arg", + "optional": true + }, + { + "name": "...", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "clearTimeout(timeoutId)", + "type": "method", + "name": "clearTimeout", + "desc": "

Prevents a timeout from triggering.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "timeoutId" + } + ] + } + ] + }, + { + "textRaw": "setInterval(callback, delay, [arg], [...])", + "type": "method", + "name": "setInterval", + "desc": "

To schedule the repeated execution of callback every delay milliseconds.\nReturns a intervalId for possible use with clearInterval(). Optionally\nyou can also pass arguments to the callback.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "callback" + }, + { + "name": "delay" + }, + { + "name": "arg", + "optional": true + }, + { + "name": "...", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "clearInterval(intervalId)", + "type": "method", + "name": "clearInterval", + "desc": "

Stops a interval from triggering.\n

\n", + "signatures": [ + { + "params": [ + { + "name": "intervalId" + } + ] + } + ] + } + ], + "type": "module", + "displayName": "Timers" + } + ] +} diff --git a/node-v0.8.14/doc/api/timers.markdown b/node-v0.8.14/doc/api/timers.markdown new file mode 100644 index 0000000..114a4b7 --- /dev/null +++ b/node-v0.8.14/doc/api/timers.markdown @@ -0,0 +1,31 @@ +# Timers + + Stability: 5 - Locked + +All of the timer functions are globals. You do not need to `require()` +this module in order to use them. + +## setTimeout(callback, delay, [arg], [...]) + +To schedule execution of a one-time `callback` after `delay` milliseconds. Returns a +`timeoutId` for possible use with `clearTimeout()`. Optionally you can +also pass arguments to the callback. + +It is important to note that your callback will probably not be called in exactly +`delay` milliseconds - Node.js makes no guarantees about the exact timing of when +the callback will fire, nor of the ordering things will fire in. The callback will +be called as close as possible to the time specified. + +## clearTimeout(timeoutId) + +Prevents a timeout from triggering. + +## setInterval(callback, delay, [arg], [...]) + +To schedule the repeated execution of `callback` every `delay` milliseconds. +Returns a `intervalId` for possible use with `clearInterval()`. Optionally +you can also pass arguments to the callback. + +## clearInterval(intervalId) + +Stops a interval from triggering. diff --git a/node-v0.8.14/doc/api/tls.html b/node-v0.8.14/doc/api/tls.html new file mode 100644 index 0000000..bf7263f --- /dev/null +++ b/node-v0.8.14/doc/api/tls.html @@ -0,0 +1,645 @@ + + + + + TLS (SSL) Node.js v0.8.14 Manual & Documentation + + + + + +
+ + + +
+
+ + +
+
+

Node.js v0.8.14 Manual & Documentation

+ +
+
+ + + +
+

TLS (SSL)#

+
Stability: 3 - Stable
+

Use require('tls') to access this module. + +

+

The tls module uses OpenSSL to provide Transport Layer Security and/or +Secure Socket Layer: encrypted stream communication. + +

+

TLS/SSL is a public/private key infrastructure. Each client and each +server must have a private key. A private key is created like this + +

+
openssl genrsa -out ryans-key.pem 1024
+

All severs and some clients need to have a certificate. Certificates are public +keys signed by a Certificate Authority or self-signed. The first step to +getting a certificate is to create a "Certificate Signing Request" (CSR) +file. This is done with: + +

+
openssl req -new -key ryans-key.pem -out ryans-csr.pem
+

To create a self-signed certificate with the CSR, do this: + +

+
openssl x509 -req -in ryans-csr.pem -signkey ryans-key.pem -out ryans-cert.pem
+

Alternatively you can send the CSR to a Certificate Authority for signing. + +

+

(TODO: docs on creating a CA, for now interested users should just look at +test/fixtures/keys/Makefile in the Node source code) + +

+

To create .pfx or .p12, do this: + +

+
openssl pkcs12 -export -in agent5-cert.pem -inkey agent5-key.pem \
+    -certfile ca-cert.pem -out agent5.pfx
+
    +
  • in: certificate
  • +
  • inkey: private key
  • +
  • certfile: all CA certs concatenated in one file like +cat ca1-cert.pem ca2-cert.pem > ca-cert.pem
  • +
+

Client-initiated renegotiation attack mitigation#

+ + +

The TLS protocol lets the client renegotiate certain aspects of the TLS session. +Unfortunately, session renegotiation requires a disproportional amount of +server-side resources, which makes it a potential vector for denial-of-service +attacks. + +

+

To mitigate this, renegotiations are limited to three times every 10 minutes. An +error is emitted on the CleartextStream instance when the threshold is +exceeded. The limits are configurable: + +

+
    +
  • tls.CLIENT_RENEG_LIMIT: renegotiation limit, default is 3.

    +
  • +
  • tls.CLIENT_RENEG_WINDOW: renegotiation window in seconds, default is

    +
                           10 minutes.
    +
  • +
+

Don't change the defaults unless you know what you are doing. + +

+

To test your server, connect to it with openssl s_client -connect address:port +and tap R<CR> (that's the letter R followed by a carriage return) a few +times. + + +

+

NPN and SNI#

+ + +

NPN (Next Protocol Negotiation) and SNI (Server Name Indication) are TLS +handshake extensions allowing you: + +

+
    +
  • NPN - to use one TLS server for multiple protocols (HTTP, SPDY)
  • +
  • SNI - to use one TLS server for multiple hostnames with different SSL +certificates.
  • +
+

tls.createServer(options, [secureConnectionListener])#

+

Creates a new tls.Server. The connectionListener argument is +automatically set as a listener for the secureConnection event. The +options object has these possibilities: + +

+
    +
  • pfx: A string or Buffer containing the private key, certificate and +CA certs of the server in PFX or PKCS12 format. (Mutually exclusive with +the key, cert and ca options.)

    +
  • +
  • key: A string or Buffer containing the private key of the server in +PEM format. (Required)

    +
  • +
  • passphrase: A string of passphrase for the private key or pfx.

    +
  • +
  • cert: A string or Buffer containing the certificate key of the server in +PEM format. (Required)

    +
  • +
  • ca: An array of strings or Buffers of trusted certificates. If this is +omitted several well known "root" CAs will be used, like VeriSign. +These are used to authorize connections.

    +
  • +
  • crl : Either a string or list of strings of PEM encoded CRLs (Certificate +Revocation List)

    +
  • +
  • ciphers: A string describing the ciphers to use or exclude.

    +

    To mitigate BEAST attacks it is recommended that you use this option in +conjunction with the honorCipherOrder option described below to +prioritize the non-CBC cipher.

    +

    Defaults to +ECDHE-RSA-AES128-SHA256:AES128-GCM-SHA256:RC4:HIGH:!MD5:!aNULL:!EDH. +Consult the OpenSSL cipher list format documentation for details on the +format.

    +

    ECDHE-RSA-AES128-SHA256 and AES128-GCM-SHA256 are used when node.js is +linked against OpenSSL 1.0.1 or newer and the client speaks TLS 1.2, RC4 is +used as a secure fallback.

    +

    NOTE: Previous revisions of this section suggested AES256-SHA as an +acceptable cipher. Unfortunately, AES256-SHA is a CBC cipher and therefore +susceptible to BEAST attacks. Do not use it.

    +
  • +
  • honorCipherOrder : When choosing a cipher, use the server's preferences +instead of the client preferences.

    +

    Note that if SSLv2 is used, the server will send its list of preferences +to the client, and the client chooses the cipher.

    +

    Although, this option is disabled by default, it is recommended that you +use this option in conjunction with the ciphers option to mitigate +BEAST attacks.

    +
  • +
  • requestCert: If true the server will request a certificate from +clients that connect and attempt to verify that certificate. Default: +false.

    +
  • +
  • rejectUnauthorized: If true the server will reject any connection +which is not authorized with the list of supplied CAs. This option only +has an effect if requestCert is true. Default: false.

    +
  • +
  • NPNProtocols: An array or Buffer of possible NPN protocols. (Protocols +should be ordered by their priority).

    +
  • +
  • SNICallback: A function that will be called if client supports SNI TLS +extension. Only one argument will be passed to it: servername. And +SNICallback should return SecureContext instance. +(You can use crypto.createCredentials(...).context to get proper +SecureContext). If SNICallback wasn't provided - default callback with +high-level API will be used (see below).

    +
  • +
  • sessionIdContext: A string containing a opaque identifier for session +resumption. If requestCert is true, the default is MD5 hash value +generated from command-line. Otherwise, the default is not provided.

    +
  • +
+

Here is a simple example echo server: + +

+
var tls = require('tls');
+var fs = require('fs');
+
+var options = {
+  key: fs.readFileSync('server-key.pem'),
+  cert: fs.readFileSync('server-cert.pem'),
+
+  // This is necessary only if using the client certificate authentication.
+  requestCert: true,
+
+  // This is necessary only if the client uses the self-signed certificate.
+  ca: [ fs.readFileSync('client-cert.pem') ]
+};
+
+var server = tls.createServer(options, function(cleartextStream) {
+  console.log('server connected',
+              cleartextStream.authorized ? 'authorized' : 'unauthorized');
+  cleartextStream.write("welcome!\n");
+  cleartextStream.setEncoding('utf8');
+  cleartextStream.pipe(cleartextStream);
+});
+server.listen(8000, function() {
+  console.log('server bound');
+});
+

Or + +

+
var tls = require('tls');
+var fs = require('fs');
+
+var options = {
+  pfx: fs.readFileSync('server.pfx'),
+
+  // This is necessary only if using the client certificate authentication.
+  requestCert: true,
+
+};
+
+var server = tls.createServer(options, function(cleartextStream) {
+  console.log('server connected',
+              cleartextStream.authorized ? 'authorized' : 'unauthorized');
+  cleartextStream.write("welcome!\n");
+  cleartextStream.setEncoding('utf8');
+  cleartextStream.pipe(cleartextStream);
+});
+server.listen(8000, function() {
+  console.log('server bound');
+});
+

You can test this server by connecting to it with openssl s_client: + + +

+
openssl s_client -connect 127.0.0.1:8000
+

tls.connect(options, [callback])#

+

tls.connect(port, [host], [options], [callback])#

+

Creates a new client connection to the given port and host (old API) or +options.port and options.host. (If host is omitted, it defaults to +localhost.) options should be an object which specifies: + +

+
    +
  • host: Host the client should connect to

    +
  • +
  • port: Port the client should connect to

    +
  • +
  • socket: Establish secure connection on a given socket rather than +creating a new socket. If this option is specified, host and port +are ignored.

    +
  • +
  • pfx: A string or Buffer containing the private key, certificate and +CA certs of the server in PFX or PKCS12 format.

    +
  • +
  • key: A string or Buffer containing the private key of the client in +PEM format.

    +
  • +
  • passphrase: A string of passphrase for the private key or pfx.

    +
  • +
  • cert: A string or Buffer containing the certificate key of the client in +PEM format.

    +
  • +
  • ca: An array of strings or Buffers of trusted certificates. If this is +omitted several well known "root" CAs will be used, like VeriSign. +These are used to authorize connections.

    +
  • +
  • rejectUnauthorized: If true, the server certificate is verified against +the list of supplied CAs. An 'error' event is emitted if verification +fails. Default: false.

    +
  • +
  • NPNProtocols: An array of string or Buffer containing supported NPN +protocols. Buffer should have following format: 0x05hello0x05world, +where first byte is next protocol name's length. (Passing array should +usually be much simpler: ['hello', 'world'].)

    +
  • +
  • servername: Servername for SNI (Server Name Indication) TLS extension.

    +
  • +
+

The callback parameter will be added as a listener for the +'secureConnect' event. + +

+

tls.connect() returns a CleartextStream object. + +

+

Here is an example of a client of echo server as described previously: + +

+
var tls = require('tls');
+var fs = require('fs');
+
+var options = {
+  // These are necessary only if using the client certificate authentication
+  key: fs.readFileSync('client-key.pem'),
+  cert: fs.readFileSync('client-cert.pem'),
+
+  // This is necessary only if the server uses the self-signed certificate
+  ca: [ fs.readFileSync('server-cert.pem') ]
+};
+
+var cleartextStream = tls.connect(8000, options, function() {
+  console.log('client connected',
+              cleartextStream.authorized ? 'authorized' : 'unauthorized');
+  process.stdin.pipe(cleartextStream);
+  process.stdin.resume();
+});
+cleartextStream.setEncoding('utf8');
+cleartextStream.on('data', function(data) {
+  console.log(data);
+});
+cleartextStream.on('end', function() {
+  server.close();
+});
+

Or + +

+
var tls = require('tls');
+var fs = require('fs');
+
+var options = {
+  pfx: fs.readFileSync('client.pfx')
+};
+
+var cleartextStream = tls.connect(8000, options, function() {
+  console.log('client connected',
+              cleartextStream.authorized ? 'authorized' : 'unauthorized');
+  process.stdin.pipe(cleartextStream);
+  process.stdin.resume();
+});
+cleartextStream.setEncoding('utf8');
+cleartextStream.on('data', function(data) {
+  console.log(data);
+});
+cleartextStream.on('end', function() {
+  server.close();
+});
+

tls.createSecurePair([credentials], [isServer], [requestCert], [rejectUnauthorized])#

+

Creates a new secure pair object with two streams, one of which reads/writes +encrypted data, and one reads/writes cleartext data. +Generally the encrypted one is piped to/from an incoming encrypted data stream, +and the cleartext one is used as a replacement for the initial encrypted stream. + +

+
    +
  • credentials: A credentials object from crypto.createCredentials( ... )

    +
  • +
  • isServer: A boolean indicating whether this tls connection should be +opened as a server or a client.

    +
  • +
  • requestCert: A boolean indicating whether a server should request a +certificate from a connecting client. Only applies to server connections.

    +
  • +
  • rejectUnauthorized: A boolean indicating whether a server should +automatically reject clients with invalid certificates. Only applies to +servers with requestCert enabled.

    +
  • +
+

tls.createSecurePair() returns a SecurePair object with [cleartext][] and +encrypted stream properties. + +

+

Class: SecurePair#

+

Returned by tls.createSecurePair. + +

+

Event: 'secure'#

+

The event is emitted from the SecurePair once the pair has successfully +established a secure connection. + +

+

Similarly to the checking for the server 'secureConnection' event, +pair.cleartext.authorized should be checked to confirm whether the certificate +used properly authorized. + +

+

Class: tls.Server#

+

This class is a subclass of net.Server and has the same methods on it. +Instead of accepting just raw TCP connections, this accepts encrypted +connections using TLS or SSL. + +

+

Event: 'secureConnection'#

+

function (cleartextStream) {} + +

+

This event is emitted after a new connection has been successfully +handshaked. The argument is a instance of CleartextStream. It has all the +common stream methods and events. + +

+

cleartextStream.authorized is a boolean value which indicates if the +client has verified by one of the supplied certificate authorities for the +server. If cleartextStream.authorized is false, then +cleartextStream.authorizationError is set to describe how authorization +failed. Implied but worth mentioning: depending on the settings of the TLS +server, you unauthorized connections may be accepted. +cleartextStream.npnProtocol is a string containing selected NPN protocol. +cleartextStream.servername is a string containing servername requested with +SNI. + + +

+

Event: 'clientError'#

+

function (exception) { } + +

+

When a client connection emits an 'error' event before secure connection is +established - it will be forwarded here. + + +

+

server.listen(port, [host], [callback])#

+

Begin accepting connections on the specified port and host. If the +host is omitted, the server will accept connections directed to any +IPv4 address (INADDR_ANY). + +

+

This function is asynchronous. The last parameter callback will be called +when the server has been bound. + +

+

See net.Server for more information. + + +

+

server.close()#

+

Stops the server from accepting new connections. This function is +asynchronous, the server is finally closed when the server emits a 'close' +event. + +

+

server.address()#

+

Returns the bound address, the address family name and port of the +server as reported by the operating system. See net.Server.address() for +more information. + +

+

server.addContext(hostname, credentials)#

+

Add secure context that will be used if client request's SNI hostname is +matching passed hostname (wildcards can be used). credentials can contain +key, cert and ca. + +

+

server.maxConnections#

+

Set this property to reject connections when the server's connection count +gets high. + +

+

server.connections#

+

The number of concurrent connections on the server. + + +

+

Class: tls.CleartextStream#

+

This is a stream on top of the Encrypted stream that makes it possible to +read/write an encrypted data as a cleartext data. + +

+

This instance implements a duplex Stream interfaces. It has all the +common stream methods and events. + +

+

A ClearTextStream is the clear member of a SecurePair object. + +

+

Event: 'secureConnect'#

+

This event is emitted after a new connection has been successfully handshaked. +The listener will be called no matter if the server's certificate was +authorized or not. It is up to the user to test cleartextStream.authorized +to see if the server certificate was signed by one of the specified CAs. +If cleartextStream.authorized === false then the error can be found in +cleartextStream.authorizationError. Also if NPN was used - you can check +cleartextStream.npnProtocol for negotiated protocol. + +

+

cleartextStream.authorized#

+

A boolean that is true if the peer certificate was signed by one of the +specified CAs, otherwise false + +

+

cleartextStream.authorizationError#

+

The reason why the peer's certificate has not been verified. This property +becomes available only when cleartextStream.authorized === false. + +

+

cleartextStream.getPeerCertificate()#

+

Returns an object representing the peer's certificate. The returned object has +some properties corresponding to the field of the certificate. + +

+

Example: + +

+
{ subject: 
+   { C: 'UK',
+     ST: 'Acknack Ltd',
+     L: 'Rhys Jones',
+     O: 'node.js',
+     OU: 'Test TLS Certificate',
+     CN: 'localhost' },
+  issuer: 
+   { C: 'UK',
+     ST: 'Acknack Ltd',
+     L: 'Rhys Jones',
+     O: 'node.js',
+     OU: 'Test TLS Certificate',
+     CN: 'localhost' },
+  valid_from: 'Nov 11 09:52:22 2009 GMT',
+  valid_to: 'Nov  6 09:52:22 2029 GMT',
+  fingerprint: '2A:7A:C2:DD:E5:F9:CC:53:72:35:99:7A:02:5A:71:38:52:EC:8A:DF' }
+

If the peer does not provide a certificate, it returns null or an empty +object. + +

+

cleartextStream.getCipher()#

+

Returns an object representing the cipher name and the SSL/TLS +protocol version of the current connection. + +

+

Example: +{ name: 'AES256-SHA', version: 'TLSv1/SSLv3' } + +

+

See SSL_CIPHER_get_name() and SSL_CIPHER_get_version() in +http://www.openssl.org/docs/ssl/ssl.html#DEALING_WITH_CIPHERS for more +information. + +

+

cleartextStream.address()#

+

Returns the bound address, the address family name and port of the +underlying socket as reported by the operating system. Returns an +object with three properties, e.g. +{ port: 12346, family: 'IPv4', address: '127.0.0.1' } + +

+

cleartextStream.remoteAddress#

+

The string representation of the remote IP address. For example, +'74.125.127.100' or '2001:4860:a005::68'. + +

+

cleartextStream.remotePort#

+

The numeric representation of the remote port. For example, 443. + +

+ +
+
+
+ + + + + + + + + diff --git a/node-v0.8.14/doc/api/tls.json b/node-v0.8.14/doc/api/tls.json new file mode 100644 index 0000000..a0a4077 --- /dev/null +++ b/node-v0.8.14/doc/api/tls.json @@ -0,0 +1,330 @@ +{ + "source": "doc/api/tls.markdown", + "modules": [ + { + "textRaw": "TLS (SSL)", + "name": "tls_(ssl)", + "stability": 3, + "stabilityText": "Stable", + "desc": "

Use require('tls') to access this module.\n\n

\n

The tls module uses OpenSSL to provide Transport Layer Security and/or\nSecure Socket Layer: encrypted stream communication.\n\n

\n

TLS/SSL is a public/private key infrastructure. Each client and each\nserver must have a private key. A private key is created like this\n\n

\n
openssl genrsa -out ryans-key.pem 1024
\n

All severs and some clients need to have a certificate. Certificates are public\nkeys signed by a Certificate Authority or self-signed. The first step to\ngetting a certificate is to create a "Certificate Signing Request" (CSR)\nfile. This is done with:\n\n

\n
openssl req -new -key ryans-key.pem -out ryans-csr.pem
\n

To create a self-signed certificate with the CSR, do this:\n\n

\n
openssl x509 -req -in ryans-csr.pem -signkey ryans-key.pem -out ryans-cert.pem
\n

Alternatively you can send the CSR to a Certificate Authority for signing.\n\n

\n

(TODO: docs on creating a CA, for now interested users should just look at\ntest/fixtures/keys/Makefile in the Node source code)\n\n

\n

To create .pfx or .p12, do this:\n\n

\n
openssl pkcs12 -export -in agent5-cert.pem -inkey agent5-key.pem \\\n    -certfile ca-cert.pem -out agent5.pfx
\n
    \n
  • in: certificate
  • \n
  • inkey: private key
  • \n
  • certfile: all CA certs concatenated in one file like\ncat ca1-cert.pem ca2-cert.pem > ca-cert.pem
  • \n
\n", + "miscs": [ + { + "textRaw": "Client-initiated renegotiation attack mitigation", + "name": "Client-initiated renegotiation attack mitigation", + "type": "misc", + "desc": "

The TLS protocol lets the client renegotiate certain aspects of the TLS session.\nUnfortunately, session renegotiation requires a disproportional amount of\nserver-side resources, which makes it a potential vector for denial-of-service\nattacks.\n\n

\n

To mitigate this, renegotiations are limited to three times every 10 minutes. An\nerror is emitted on the [CleartextStream][] instance when the threshold is\nexceeded. The limits are configurable:\n\n

\n
    \n
  • tls.CLIENT_RENEG_LIMIT: renegotiation limit, default is 3.

    \n
  • \n
  • tls.CLIENT_RENEG_WINDOW: renegotiation window in seconds, default is

    \n
                           10 minutes.
    \n
  • \n
\n

Don't change the defaults unless you know what you are doing.\n\n

\n

To test your server, connect to it with openssl s_client -connect address:port\nand tap R<CR> (that's the letter R followed by a carriage return) a few\ntimes.\n\n\n

\n" + }, + { + "textRaw": "NPN and SNI", + "name": "NPN and SNI", + "type": "misc", + "desc": "

NPN (Next Protocol Negotiation) and SNI (Server Name Indication) are TLS\nhandshake extensions allowing you:\n\n

\n
    \n
  • NPN - to use one TLS server for multiple protocols (HTTP, SPDY)
  • \n
  • SNI - to use one TLS server for multiple hostnames with different SSL\ncertificates.
  • \n
\n" + } + ], + "methods": [ + { + "textRaw": "tls.createServer(options, [secureConnectionListener])", + "type": "method", + "name": "createServer", + "desc": "

Creates a new [tls.Server][]. The connectionListener argument is\nautomatically set as a listener for the [secureConnection][] event. The\noptions object has these possibilities:\n\n

\n
    \n
  • pfx: A string or Buffer containing the private key, certificate and\nCA certs of the server in PFX or PKCS12 format. (Mutually exclusive with\nthe key, cert and ca options.)

    \n
  • \n
  • key: A string or Buffer containing the private key of the server in\nPEM format. (Required)

    \n
  • \n
  • passphrase: A string of passphrase for the private key or pfx.

    \n
  • \n
  • cert: A string or Buffer containing the certificate key of the server in\nPEM format. (Required)

    \n
  • \n
  • ca: An array of strings or Buffers of trusted certificates. If this is\nomitted several well known "root" CAs will be used, like VeriSign.\nThese are used to authorize connections.

    \n
  • \n
  • crl : Either a string or list of strings of PEM encoded CRLs (Certificate\nRevocation List)

    \n
  • \n
  • ciphers: A string describing the ciphers to use or exclude.

    \n

    To mitigate [BEAST attacks] it is recommended that you use this option in\nconjunction with the honorCipherOrder option described below to\nprioritize the non-CBC cipher.

    \n

    Defaults to\nECDHE-RSA-AES128-SHA256:AES128-GCM-SHA256:RC4:HIGH:!MD5:!aNULL:!EDH.\nConsult the [OpenSSL cipher list format documentation] for details on the\nformat.

    \n

    ECDHE-RSA-AES128-SHA256 and AES128-GCM-SHA256 are used when node.js is\nlinked against OpenSSL 1.0.1 or newer and the client speaks TLS 1.2, RC4 is\nused as a secure fallback.

    \n

    NOTE: Previous revisions of this section suggested AES256-SHA as an\nacceptable cipher. Unfortunately, AES256-SHA is a CBC cipher and therefore\nsusceptible to BEAST attacks. Do not use it.

    \n
  • \n
  • honorCipherOrder : When choosing a cipher, use the server's preferences\ninstead of the client preferences.

    \n

    Note that if SSLv2 is used, the server will send its list of preferences\nto the client, and the client chooses the cipher.

    \n

    Although, this option is disabled by default, it is recommended that you\nuse this option in conjunction with the ciphers option to mitigate\nBEAST attacks.

    \n
  • \n
  • requestCert: If true the server will request a certificate from\nclients that connect and attempt to verify that certificate. Default:\nfalse.

    \n
  • \n
  • rejectUnauthorized: If true the server will reject any connection\nwhich is not authorized with the list of supplied CAs. This option only\nhas an effect if requestCert is true. Default: false.

    \n
  • \n
  • NPNProtocols: An array or Buffer of possible NPN protocols. (Protocols\nshould be ordered by their priority).

    \n
  • \n
  • SNICallback: A function that will be called if client supports SNI TLS\nextension. Only one argument will be passed to it: servername. And\nSNICallback should return SecureContext instance.\n(You can use crypto.createCredentials(...).context to get proper\nSecureContext). If SNICallback wasn't provided - default callback with\nhigh-level API will be used (see below).

    \n
  • \n
  • sessionIdContext: A string containing a opaque identifier for session\nresumption. If requestCert is true, the default is MD5 hash value\ngenerated from command-line. Otherwise, the default is not provided.

    \n
  • \n
\n

Here is a simple example echo server:\n\n

\n
var tls = require('tls');\nvar fs = require('fs');\n\nvar options = {\n  key: fs.readFileSync('server-key.pem'),\n  cert: fs.readFileSync('server-cert.pem'),\n\n  // This is necessary only if using the client certificate authentication.\n  requestCert: true,\n\n  // This is necessary only if the client uses the self-signed certificate.\n  ca: [ fs.readFileSync('client-cert.pem') ]\n};\n\nvar server = tls.createServer(options, function(cleartextStream) {\n  console.log('server connected',\n              cleartextStream.authorized ? 'authorized' : 'unauthorized');\n  cleartextStream.write("welcome!\\n");\n  cleartextStream.setEncoding('utf8');\n  cleartextStream.pipe(cleartextStream);\n});\nserver.listen(8000, function() {\n  console.log('server bound');\n});
\n

Or\n\n

\n
var tls = require('tls');\nvar fs = require('fs');\n\nvar options = {\n  pfx: fs.readFileSync('server.pfx'),\n\n  // This is necessary only if using the client certificate authentication.\n  requestCert: true,\n\n};\n\nvar server = tls.createServer(options, function(cleartextStream) {\n  console.log('server connected',\n              cleartextStream.authorized ? 'authorized' : 'unauthorized');\n  cleartextStream.write("welcome!\\n");\n  cleartextStream.setEncoding('utf8');\n  cleartextStream.pipe(cleartextStream);\n});\nserver.listen(8000, function() {\n  console.log('server bound');\n});
\n

You can test this server by connecting to it with openssl s_client:\n\n\n

\n
openssl s_client -connect 127.0.0.1:8000
\n", + "signatures": [ + { + "params": [ + { + "name": "options" + }, + { + "name": "secureConnectionListener", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "tls.connect(options, [callback])", + "type": "method", + "name": "connect", + "desc": "

Creates a new client connection to the given port and host (old API) or\noptions.port and options.host. (If host is omitted, it defaults to\nlocalhost.) options should be an object which specifies:\n\n

\n
    \n
  • host: Host the client should connect to

    \n
  • \n
  • port: Port the client should connect to

    \n
  • \n
  • socket: Establish secure connection on a given socket rather than\ncreating a new socket. If this option is specified, host and port\nare ignored.

    \n
  • \n
  • pfx: A string or Buffer containing the private key, certificate and\nCA certs of the server in PFX or PKCS12 format.

    \n
  • \n
  • key: A string or Buffer containing the private key of the client in\nPEM format.

    \n
  • \n
  • passphrase: A string of passphrase for the private key or pfx.

    \n
  • \n
  • cert: A string or Buffer containing the certificate key of the client in\nPEM format.

    \n
  • \n
  • ca: An array of strings or Buffers of trusted certificates. If this is\nomitted several well known "root" CAs will be used, like VeriSign.\nThese are used to authorize connections.

    \n
  • \n
  • rejectUnauthorized: If true, the server certificate is verified against\nthe list of supplied CAs. An 'error' event is emitted if verification\nfails. Default: false.

    \n
  • \n
  • NPNProtocols: An array of string or Buffer containing supported NPN\nprotocols. Buffer should have following format: 0x05hello0x05world,\nwhere first byte is next protocol name's length. (Passing array should\nusually be much simpler: ['hello', 'world'].)

    \n
  • \n
  • servername: Servername for SNI (Server Name Indication) TLS extension.

    \n
  • \n
\n

The callback parameter will be added as a listener for the\n['secureConnect'][] event.\n\n

\n

tls.connect() returns a [CleartextStream][] object.\n\n

\n

Here is an example of a client of echo server as described previously:\n\n

\n
var tls = require('tls');\nvar fs = require('fs');\n\nvar options = {\n  // These are necessary only if using the client certificate authentication\n  key: fs.readFileSync('client-key.pem'),\n  cert: fs.readFileSync('client-cert.pem'),\n\n  // This is necessary only if the server uses the self-signed certificate\n  ca: [ fs.readFileSync('server-cert.pem') ]\n};\n\nvar cleartextStream = tls.connect(8000, options, function() {\n  console.log('client connected',\n              cleartextStream.authorized ? 'authorized' : 'unauthorized');\n  process.stdin.pipe(cleartextStream);\n  process.stdin.resume();\n});\ncleartextStream.setEncoding('utf8');\ncleartextStream.on('data', function(data) {\n  console.log(data);\n});\ncleartextStream.on('end', function() {\n  server.close();\n});
\n

Or\n\n

\n
var tls = require('tls');\nvar fs = require('fs');\n\nvar options = {\n  pfx: fs.readFileSync('client.pfx')\n};\n\nvar cleartextStream = tls.connect(8000, options, function() {\n  console.log('client connected',\n              cleartextStream.authorized ? 'authorized' : 'unauthorized');\n  process.stdin.pipe(cleartextStream);\n  process.stdin.resume();\n});\ncleartextStream.setEncoding('utf8');\ncleartextStream.on('data', function(data) {\n  console.log(data);\n});\ncleartextStream.on('end', function() {\n  server.close();\n});
\n", + "signatures": [ + { + "params": [ + { + "name": "port" + }, + { + "name": "host", + "optional": true + }, + { + "name": "options", + "optional": true + }, + { + "name": "callback", + "optional": true + } + ] + }, + { + "params": [ + { + "name": "options" + }, + { + "name": "callback", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "tls.connect(port, [host], [options], [callback])", + "type": "method", + "name": "connect", + "desc": "

Creates a new client connection to the given port and host (old API) or\noptions.port and options.host. (If host is omitted, it defaults to\nlocalhost.) options should be an object which specifies:\n\n

\n
    \n
  • host: Host the client should connect to

    \n
  • \n
  • port: Port the client should connect to

    \n
  • \n
  • socket: Establish secure connection on a given socket rather than\ncreating a new socket. If this option is specified, host and port\nare ignored.

    \n
  • \n
  • pfx: A string or Buffer containing the private key, certificate and\nCA certs of the server in PFX or PKCS12 format.

    \n
  • \n
  • key: A string or Buffer containing the private key of the client in\nPEM format.

    \n
  • \n
  • passphrase: A string of passphrase for the private key or pfx.

    \n
  • \n
  • cert: A string or Buffer containing the certificate key of the client in\nPEM format.

    \n
  • \n
  • ca: An array of strings or Buffers of trusted certificates. If this is\nomitted several well known "root" CAs will be used, like VeriSign.\nThese are used to authorize connections.

    \n
  • \n
  • rejectUnauthorized: If true, the server certificate is verified against\nthe list of supplied CAs. An 'error' event is emitted if verification\nfails. Default: false.

    \n
  • \n
  • NPNProtocols: An array of string or Buffer containing supported NPN\nprotocols. Buffer should have following format: 0x05hello0x05world,\nwhere first byte is next protocol name's length. (Passing array should\nusually be much simpler: ['hello', 'world'].)

    \n
  • \n
  • servername: Servername for SNI (Server Name Indication) TLS extension.

    \n
  • \n
\n

The callback parameter will be added as a listener for the\n['secureConnect'][] event.\n\n

\n

tls.connect() returns a [CleartextStream][] object.\n\n

\n

Here is an example of a client of echo server as described previously:\n\n

\n
var tls = require('tls');\nvar fs = require('fs');\n\nvar options = {\n  // These are necessary only if using the client certificate authentication\n  key: fs.readFileSync('client-key.pem'),\n  cert: fs.readFileSync('client-cert.pem'),\n\n  // This is necessary only if the server uses the self-signed certificate\n  ca: [ fs.readFileSync('server-cert.pem') ]\n};\n\nvar cleartextStream = tls.connect(8000, options, function() {\n  console.log('client connected',\n              cleartextStream.authorized ? 'authorized' : 'unauthorized');\n  process.stdin.pipe(cleartextStream);\n  process.stdin.resume();\n});\ncleartextStream.setEncoding('utf8');\ncleartextStream.on('data', function(data) {\n  console.log(data);\n});\ncleartextStream.on('end', function() {\n  server.close();\n});
\n

Or\n\n

\n
var tls = require('tls');\nvar fs = require('fs');\n\nvar options = {\n  pfx: fs.readFileSync('client.pfx')\n};\n\nvar cleartextStream = tls.connect(8000, options, function() {\n  console.log('client connected',\n              cleartextStream.authorized ? 'authorized' : 'unauthorized');\n  process.stdin.pipe(cleartextStream);\n  process.stdin.resume();\n});\ncleartextStream.setEncoding('utf8');\ncleartextStream.on('data', function(data) {\n  console.log(data);\n});\ncleartextStream.on('end', function() {\n  server.close();\n});
\n", + "signatures": [ + { + "params": [ + { + "name": "port" + }, + { + "name": "host", + "optional": true + }, + { + "name": "options", + "optional": true + }, + { + "name": "callback", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "tls.createSecurePair([credentials], [isServer], [requestCert], [rejectUnauthorized])", + "type": "method", + "name": "createSecurePair", + "desc": "

Creates a new secure pair object with two streams, one of which reads/writes\nencrypted data, and one reads/writes cleartext data.\nGenerally the encrypted one is piped to/from an incoming encrypted data stream,\nand the cleartext one is used as a replacement for the initial encrypted stream.\n\n

\n
    \n
  • credentials: A credentials object from crypto.createCredentials( ... )

    \n
  • \n
  • isServer: A boolean indicating whether this tls connection should be\nopened as a server or a client.

    \n
  • \n
  • requestCert: A boolean indicating whether a server should request a\ncertificate from a connecting client. Only applies to server connections.

    \n
  • \n
  • rejectUnauthorized: A boolean indicating whether a server should\nautomatically reject clients with invalid certificates. Only applies to\nservers with requestCert enabled.

    \n
  • \n
\n

tls.createSecurePair() returns a SecurePair object with [cleartext][] and\nencrypted stream properties.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "credentials", + "optional": true + }, + { + "name": "isServer", + "optional": true + }, + { + "name": "requestCert", + "optional": true + }, + { + "name": "rejectUnauthorized", + "optional": true + } + ] + } + ] + } + ], + "classes": [ + { + "textRaw": "Class: SecurePair", + "type": "class", + "name": "SecurePair", + "desc": "

Returned by tls.createSecurePair.\n\n

\n", + "events": [ + { + "textRaw": "Event: 'secure'", + "type": "event", + "name": "secure", + "desc": "

The event is emitted from the SecurePair once the pair has successfully\nestablished a secure connection.\n\n

\n

Similarly to the checking for the server 'secureConnection' event,\npair.cleartext.authorized should be checked to confirm whether the certificate\nused properly authorized.\n\n

\n", + "params": [] + } + ] + }, + { + "textRaw": "Class: tls.Server", + "type": "class", + "name": "tls.Server", + "desc": "

This class is a subclass of net.Server and has the same methods on it.\nInstead of accepting just raw TCP connections, this accepts encrypted\nconnections using TLS or SSL.\n\n

\n", + "events": [ + { + "textRaw": "Event: 'secureConnection'", + "type": "event", + "name": "secureConnection", + "desc": "

function (cleartextStream) {}\n\n

\n

This event is emitted after a new connection has been successfully\nhandshaked. The argument is a instance of [CleartextStream][]. It has all the\ncommon stream methods and events.\n\n

\n

cleartextStream.authorized is a boolean value which indicates if the\nclient has verified by one of the supplied certificate authorities for the\nserver. If cleartextStream.authorized is false, then\ncleartextStream.authorizationError is set to describe how authorization\nfailed. Implied but worth mentioning: depending on the settings of the TLS\nserver, you unauthorized connections may be accepted.\ncleartextStream.npnProtocol is a string containing selected NPN protocol.\ncleartextStream.servername is a string containing servername requested with\nSNI.\n\n\n

\n", + "params": [] + }, + { + "textRaw": "Event: 'clientError'", + "type": "event", + "name": "clientError", + "desc": "

function (exception) { }\n\n

\n

When a client connection emits an 'error' event before secure connection is\nestablished - it will be forwarded here.\n\n\n

\n", + "params": [] + } + ], + "methods": [ + { + "textRaw": "server.listen(port, [host], [callback])", + "type": "method", + "name": "listen", + "desc": "

Begin accepting connections on the specified port and host. If the\nhost is omitted, the server will accept connections directed to any\nIPv4 address (INADDR_ANY).\n\n

\n

This function is asynchronous. The last parameter callback will be called\nwhen the server has been bound.\n\n

\n

See net.Server for more information.\n\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "port" + }, + { + "name": "host", + "optional": true + }, + { + "name": "callback", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "server.close()", + "type": "method", + "name": "close", + "desc": "

Stops the server from accepting new connections. This function is\nasynchronous, the server is finally closed when the server emits a 'close'\nevent.\n\n

\n", + "signatures": [ + { + "params": [] + } + ] + }, + { + "textRaw": "server.address()", + "type": "method", + "name": "address", + "desc": "

Returns the bound address, the address family name and port of the\nserver as reported by the operating system. See [net.Server.address()][] for\nmore information.\n\n

\n", + "signatures": [ + { + "params": [] + } + ] + }, + { + "textRaw": "server.addContext(hostname, credentials)", + "type": "method", + "name": "addContext", + "desc": "

Add secure context that will be used if client request's SNI hostname is\nmatching passed hostname (wildcards can be used). credentials can contain\nkey, cert and ca.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "hostname" + }, + { + "name": "credentials" + } + ] + } + ] + } + ], + "properties": [ + { + "textRaw": "server.maxConnections", + "name": "maxConnections", + "desc": "

Set this property to reject connections when the server's connection count\ngets high.\n\n

\n" + }, + { + "textRaw": "server.connections", + "name": "connections", + "desc": "

The number of concurrent connections on the server.\n\n\n

\n" + } + ] + }, + { + "textRaw": "Class: tls.CleartextStream", + "type": "class", + "name": "tls.CleartextStream", + "desc": "

This is a stream on top of the Encrypted stream that makes it possible to\nread/write an encrypted data as a cleartext data.\n\n

\n

This instance implements a duplex [Stream][] interfaces. It has all the\ncommon stream methods and events.\n\n

\n

A ClearTextStream is the clear member of a SecurePair object.\n\n

\n", + "events": [ + { + "textRaw": "Event: 'secureConnect'", + "type": "event", + "name": "secureConnect", + "desc": "

This event is emitted after a new connection has been successfully handshaked. \nThe listener will be called no matter if the server's certificate was\nauthorized or not. It is up to the user to test cleartextStream.authorized\nto see if the server certificate was signed by one of the specified CAs.\nIf cleartextStream.authorized === false then the error can be found in\ncleartextStream.authorizationError. Also if NPN was used - you can check\ncleartextStream.npnProtocol for negotiated protocol.\n\n

\n", + "params": [] + } + ], + "properties": [ + { + "textRaw": "cleartextStream.authorized", + "name": "authorized", + "desc": "

A boolean that is true if the peer certificate was signed by one of the\nspecified CAs, otherwise false\n\n

\n" + }, + { + "textRaw": "cleartextStream.authorizationError", + "name": "authorizationError", + "desc": "

The reason why the peer's certificate has not been verified. This property\nbecomes available only when cleartextStream.authorized === false.\n\n

\n" + }, + { + "textRaw": "cleartextStream.remoteAddress", + "name": "remoteAddress", + "desc": "

The string representation of the remote IP address. For example,\n'74.125.127.100' or '2001:4860:a005::68'.\n\n

\n" + }, + { + "textRaw": "cleartextStream.remotePort", + "name": "remotePort", + "desc": "

The numeric representation of the remote port. For example, 443.\n\n

\n" + } + ], + "methods": [ + { + "textRaw": "cleartextStream.getPeerCertificate()", + "type": "method", + "name": "getPeerCertificate", + "desc": "

Returns an object representing the peer's certificate. The returned object has\nsome properties corresponding to the field of the certificate.\n\n

\n

Example:\n\n

\n
{ subject: \n   { C: 'UK',\n     ST: 'Acknack Ltd',\n     L: 'Rhys Jones',\n     O: 'node.js',\n     OU: 'Test TLS Certificate',\n     CN: 'localhost' },\n  issuer: \n   { C: 'UK',\n     ST: 'Acknack Ltd',\n     L: 'Rhys Jones',\n     O: 'node.js',\n     OU: 'Test TLS Certificate',\n     CN: 'localhost' },\n  valid_from: 'Nov 11 09:52:22 2009 GMT',\n  valid_to: 'Nov  6 09:52:22 2029 GMT',\n  fingerprint: '2A:7A:C2:DD:E5:F9:CC:53:72:35:99:7A:02:5A:71:38:52:EC:8A:DF' }
\n

If the peer does not provide a certificate, it returns null or an empty\nobject.\n\n

\n", + "signatures": [ + { + "params": [] + } + ] + }, + { + "textRaw": "cleartextStream.getCipher()", + "type": "method", + "name": "getCipher", + "desc": "

Returns an object representing the cipher name and the SSL/TLS\nprotocol version of the current connection.\n\n

\n

Example:\n{ name: 'AES256-SHA', version: 'TLSv1/SSLv3' }\n\n

\n

See SSL_CIPHER_get_name() and SSL_CIPHER_get_version() in\nhttp://www.openssl.org/docs/ssl/ssl.html#DEALING_WITH_CIPHERS for more\ninformation.\n\n

\n", + "signatures": [ + { + "params": [] + } + ] + }, + { + "textRaw": "cleartextStream.address()", + "type": "method", + "name": "address", + "desc": "

Returns the bound address, the address family name and port of the\nunderlying socket as reported by the operating system. Returns an\nobject with three properties, e.g.\n{ port: 12346, family: 'IPv4', address: '127.0.0.1' }\n\n

\n", + "signatures": [ + { + "params": [] + } + ] + } + ] + } + ], + "type": "module", + "displayName": "TLS (SSL)" + } + ] +} diff --git a/node-v0.8.14/doc/api/tls.markdown b/node-v0.8.14/doc/api/tls.markdown new file mode 100644 index 0000000..40a25e7 --- /dev/null +++ b/node-v0.8.14/doc/api/tls.markdown @@ -0,0 +1,508 @@ +# TLS (SSL) + + Stability: 3 - Stable + +Use `require('tls')` to access this module. + +The `tls` module uses OpenSSL to provide Transport Layer Security and/or +Secure Socket Layer: encrypted stream communication. + +TLS/SSL is a public/private key infrastructure. Each client and each +server must have a private key. A private key is created like this + + openssl genrsa -out ryans-key.pem 1024 + +All severs and some clients need to have a certificate. Certificates are public +keys signed by a Certificate Authority or self-signed. The first step to +getting a certificate is to create a "Certificate Signing Request" (CSR) +file. This is done with: + + openssl req -new -key ryans-key.pem -out ryans-csr.pem + +To create a self-signed certificate with the CSR, do this: + + openssl x509 -req -in ryans-csr.pem -signkey ryans-key.pem -out ryans-cert.pem + +Alternatively you can send the CSR to a Certificate Authority for signing. + +(TODO: docs on creating a CA, for now interested users should just look at +`test/fixtures/keys/Makefile` in the Node source code) + +To create .pfx or .p12, do this: + + openssl pkcs12 -export -in agent5-cert.pem -inkey agent5-key.pem \ + -certfile ca-cert.pem -out agent5.pfx + + - `in`: certificate + - `inkey`: private key + - `certfile`: all CA certs concatenated in one file like + `cat ca1-cert.pem ca2-cert.pem > ca-cert.pem` + + +## Client-initiated renegotiation attack mitigation + + + +The TLS protocol lets the client renegotiate certain aspects of the TLS session. +Unfortunately, session renegotiation requires a disproportional amount of +server-side resources, which makes it a potential vector for denial-of-service +attacks. + +To mitigate this, renegotiations are limited to three times every 10 minutes. An +error is emitted on the [CleartextStream][] instance when the threshold is +exceeded. The limits are configurable: + + - `tls.CLIENT_RENEG_LIMIT`: renegotiation limit, default is 3. + + - `tls.CLIENT_RENEG_WINDOW`: renegotiation window in seconds, default is + 10 minutes. + +Don't change the defaults unless you know what you are doing. + +To test your server, connect to it with `openssl s_client -connect address:port` +and tap `R` (that's the letter `R` followed by a carriage return) a few +times. + + +## NPN and SNI + + + +NPN (Next Protocol Negotiation) and SNI (Server Name Indication) are TLS +handshake extensions allowing you: + + * NPN - to use one TLS server for multiple protocols (HTTP, SPDY) + * SNI - to use one TLS server for multiple hostnames with different SSL + certificates. + + +## tls.createServer(options, [secureConnectionListener]) + +Creates a new [tls.Server][]. The `connectionListener` argument is +automatically set as a listener for the [secureConnection][] event. The +`options` object has these possibilities: + + - `pfx`: A string or `Buffer` containing the private key, certificate and + CA certs of the server in PFX or PKCS12 format. (Mutually exclusive with + the `key`, `cert` and `ca` options.) + + - `key`: A string or `Buffer` containing the private key of the server in + PEM format. (Required) + + - `passphrase`: A string of passphrase for the private key or pfx. + + - `cert`: A string or `Buffer` containing the certificate key of the server in + PEM format. (Required) + + - `ca`: An array of strings or `Buffer`s of trusted certificates. If this is + omitted several well known "root" CAs will be used, like VeriSign. + These are used to authorize connections. + + - `crl` : Either a string or list of strings of PEM encoded CRLs (Certificate + Revocation List) + + - `ciphers`: A string describing the ciphers to use or exclude. + + To mitigate [BEAST attacks] it is recommended that you use this option in + conjunction with the `honorCipherOrder` option described below to + prioritize the non-CBC cipher. + + Defaults to + `ECDHE-RSA-AES128-SHA256:AES128-GCM-SHA256:RC4:HIGH:!MD5:!aNULL:!EDH`. + Consult the [OpenSSL cipher list format documentation] for details on the + format. + + `ECDHE-RSA-AES128-SHA256` and `AES128-GCM-SHA256` are used when node.js is + linked against OpenSSL 1.0.1 or newer and the client speaks TLS 1.2, RC4 is + used as a secure fallback. + + **NOTE**: Previous revisions of this section suggested `AES256-SHA` as an + acceptable cipher. Unfortunately, `AES256-SHA` is a CBC cipher and therefore + susceptible to BEAST attacks. Do *not* use it. + + - `honorCipherOrder` : When choosing a cipher, use the server's preferences + instead of the client preferences. + + Note that if SSLv2 is used, the server will send its list of preferences + to the client, and the client chooses the cipher. + + Although, this option is disabled by default, it is *recommended* that you + use this option in conjunction with the `ciphers` option to mitigate + BEAST attacks. + + - `requestCert`: If `true` the server will request a certificate from + clients that connect and attempt to verify that certificate. Default: + `false`. + + - `rejectUnauthorized`: If `true` the server will reject any connection + which is not authorized with the list of supplied CAs. This option only + has an effect if `requestCert` is `true`. Default: `false`. + + - `NPNProtocols`: An array or `Buffer` of possible NPN protocols. (Protocols + should be ordered by their priority). + + - `SNICallback`: A function that will be called if client supports SNI TLS + extension. Only one argument will be passed to it: `servername`. And + `SNICallback` should return SecureContext instance. + (You can use `crypto.createCredentials(...).context` to get proper + SecureContext). If `SNICallback` wasn't provided - default callback with + high-level API will be used (see below). + + - `sessionIdContext`: A string containing a opaque identifier for session + resumption. If `requestCert` is `true`, the default is MD5 hash value + generated from command-line. Otherwise, the default is not provided. + +Here is a simple example echo server: + + var tls = require('tls'); + var fs = require('fs'); + + var options = { + key: fs.readFileSync('server-key.pem'), + cert: fs.readFileSync('server-cert.pem'), + + // This is necessary only if using the client certificate authentication. + requestCert: true, + + // This is necessary only if the client uses the self-signed certificate. + ca: [ fs.readFileSync('client-cert.pem') ] + }; + + var server = tls.createServer(options, function(cleartextStream) { + console.log('server connected', + cleartextStream.authorized ? 'authorized' : 'unauthorized'); + cleartextStream.write("welcome!\n"); + cleartextStream.setEncoding('utf8'); + cleartextStream.pipe(cleartextStream); + }); + server.listen(8000, function() { + console.log('server bound'); + }); + +Or + + var tls = require('tls'); + var fs = require('fs'); + + var options = { + pfx: fs.readFileSync('server.pfx'), + + // This is necessary only if using the client certificate authentication. + requestCert: true, + + }; + + var server = tls.createServer(options, function(cleartextStream) { + console.log('server connected', + cleartextStream.authorized ? 'authorized' : 'unauthorized'); + cleartextStream.write("welcome!\n"); + cleartextStream.setEncoding('utf8'); + cleartextStream.pipe(cleartextStream); + }); + server.listen(8000, function() { + console.log('server bound'); + }); +You can test this server by connecting to it with `openssl s_client`: + + + openssl s_client -connect 127.0.0.1:8000 + + +## tls.connect(options, [callback]) +## tls.connect(port, [host], [options], [callback]) + +Creates a new client connection to the given `port` and `host` (old API) or +`options.port` and `options.host`. (If `host` is omitted, it defaults to +`localhost`.) `options` should be an object which specifies: + + - `host`: Host the client should connect to + + - `port`: Port the client should connect to + + - `socket`: Establish secure connection on a given socket rather than + creating a new socket. If this option is specified, `host` and `port` + are ignored. + + - `pfx`: A string or `Buffer` containing the private key, certificate and + CA certs of the server in PFX or PKCS12 format. + + - `key`: A string or `Buffer` containing the private key of the client in + PEM format. + + - `passphrase`: A string of passphrase for the private key or pfx. + + - `cert`: A string or `Buffer` containing the certificate key of the client in + PEM format. + + - `ca`: An array of strings or `Buffer`s of trusted certificates. If this is + omitted several well known "root" CAs will be used, like VeriSign. + These are used to authorize connections. + + - `rejectUnauthorized`: If `true`, the server certificate is verified against + the list of supplied CAs. An `'error'` event is emitted if verification + fails. Default: `false`. + + - `NPNProtocols`: An array of string or `Buffer` containing supported NPN + protocols. `Buffer` should have following format: `0x05hello0x05world`, + where first byte is next protocol name's length. (Passing array should + usually be much simpler: `['hello', 'world']`.) + + - `servername`: Servername for SNI (Server Name Indication) TLS extension. + +The `callback` parameter will be added as a listener for the +['secureConnect'][] event. + +`tls.connect()` returns a [CleartextStream][] object. + +Here is an example of a client of echo server as described previously: + + var tls = require('tls'); + var fs = require('fs'); + + var options = { + // These are necessary only if using the client certificate authentication + key: fs.readFileSync('client-key.pem'), + cert: fs.readFileSync('client-cert.pem'), + + // This is necessary only if the server uses the self-signed certificate + ca: [ fs.readFileSync('server-cert.pem') ] + }; + + var cleartextStream = tls.connect(8000, options, function() { + console.log('client connected', + cleartextStream.authorized ? 'authorized' : 'unauthorized'); + process.stdin.pipe(cleartextStream); + process.stdin.resume(); + }); + cleartextStream.setEncoding('utf8'); + cleartextStream.on('data', function(data) { + console.log(data); + }); + cleartextStream.on('end', function() { + server.close(); + }); + +Or + + var tls = require('tls'); + var fs = require('fs'); + + var options = { + pfx: fs.readFileSync('client.pfx') + }; + + var cleartextStream = tls.connect(8000, options, function() { + console.log('client connected', + cleartextStream.authorized ? 'authorized' : 'unauthorized'); + process.stdin.pipe(cleartextStream); + process.stdin.resume(); + }); + cleartextStream.setEncoding('utf8'); + cleartextStream.on('data', function(data) { + console.log(data); + }); + cleartextStream.on('end', function() { + server.close(); + }); + +## tls.createSecurePair([credentials], [isServer], [requestCert], [rejectUnauthorized]) + +Creates a new secure pair object with two streams, one of which reads/writes +encrypted data, and one reads/writes cleartext data. +Generally the encrypted one is piped to/from an incoming encrypted data stream, +and the cleartext one is used as a replacement for the initial encrypted stream. + + - `credentials`: A credentials object from crypto.createCredentials( ... ) + + - `isServer`: A boolean indicating whether this tls connection should be + opened as a server or a client. + + - `requestCert`: A boolean indicating whether a server should request a + certificate from a connecting client. Only applies to server connections. + + - `rejectUnauthorized`: A boolean indicating whether a server should + automatically reject clients with invalid certificates. Only applies to + servers with `requestCert` enabled. + +`tls.createSecurePair()` returns a SecurePair object with [cleartext][] and +`encrypted` stream properties. + +## Class: SecurePair + +Returned by tls.createSecurePair. + +### Event: 'secure' + +The event is emitted from the SecurePair once the pair has successfully +established a secure connection. + +Similarly to the checking for the server 'secureConnection' event, +pair.cleartext.authorized should be checked to confirm whether the certificate +used properly authorized. + +## Class: tls.Server + +This class is a subclass of `net.Server` and has the same methods on it. +Instead of accepting just raw TCP connections, this accepts encrypted +connections using TLS or SSL. + +### Event: 'secureConnection' + +`function (cleartextStream) {}` + +This event is emitted after a new connection has been successfully +handshaked. The argument is a instance of [CleartextStream][]. It has all the +common stream methods and events. + +`cleartextStream.authorized` is a boolean value which indicates if the +client has verified by one of the supplied certificate authorities for the +server. If `cleartextStream.authorized` is false, then +`cleartextStream.authorizationError` is set to describe how authorization +failed. Implied but worth mentioning: depending on the settings of the TLS +server, you unauthorized connections may be accepted. +`cleartextStream.npnProtocol` is a string containing selected NPN protocol. +`cleartextStream.servername` is a string containing servername requested with +SNI. + + +### Event: 'clientError' + +`function (exception) { }` + +When a client connection emits an 'error' event before secure connection is +established - it will be forwarded here. + + +### server.listen(port, [host], [callback]) + +Begin accepting connections on the specified `port` and `host`. If the +`host` is omitted, the server will accept connections directed to any +IPv4 address (`INADDR_ANY`). + +This function is asynchronous. The last parameter `callback` will be called +when the server has been bound. + +See `net.Server` for more information. + + +### server.close() + +Stops the server from accepting new connections. This function is +asynchronous, the server is finally closed when the server emits a `'close'` +event. + +### server.address() + +Returns the bound address, the address family name and port of the +server as reported by the operating system. See [net.Server.address()][] for +more information. + +### server.addContext(hostname, credentials) + +Add secure context that will be used if client request's SNI hostname is +matching passed `hostname` (wildcards can be used). `credentials` can contain +`key`, `cert` and `ca`. + +### server.maxConnections + +Set this property to reject connections when the server's connection count +gets high. + +### server.connections + +The number of concurrent connections on the server. + + +## Class: tls.CleartextStream + +This is a stream on top of the *Encrypted* stream that makes it possible to +read/write an encrypted data as a cleartext data. + +This instance implements a duplex [Stream][] interfaces. It has all the +common stream methods and events. + +A ClearTextStream is the `clear` member of a SecurePair object. + +### Event: 'secureConnect' + +This event is emitted after a new connection has been successfully handshaked. +The listener will be called no matter if the server's certificate was +authorized or not. It is up to the user to test `cleartextStream.authorized` +to see if the server certificate was signed by one of the specified CAs. +If `cleartextStream.authorized === false` then the error can be found in +`cleartextStream.authorizationError`. Also if NPN was used - you can check +`cleartextStream.npnProtocol` for negotiated protocol. + +### cleartextStream.authorized + +A boolean that is `true` if the peer certificate was signed by one of the +specified CAs, otherwise `false` + +### cleartextStream.authorizationError + +The reason why the peer's certificate has not been verified. This property +becomes available only when `cleartextStream.authorized === false`. + +### cleartextStream.getPeerCertificate() + +Returns an object representing the peer's certificate. The returned object has +some properties corresponding to the field of the certificate. + +Example: + + { subject: + { C: 'UK', + ST: 'Acknack Ltd', + L: 'Rhys Jones', + O: 'node.js', + OU: 'Test TLS Certificate', + CN: 'localhost' }, + issuer: + { C: 'UK', + ST: 'Acknack Ltd', + L: 'Rhys Jones', + O: 'node.js', + OU: 'Test TLS Certificate', + CN: 'localhost' }, + valid_from: 'Nov 11 09:52:22 2009 GMT', + valid_to: 'Nov 6 09:52:22 2029 GMT', + fingerprint: '2A:7A:C2:DD:E5:F9:CC:53:72:35:99:7A:02:5A:71:38:52:EC:8A:DF' } + +If the peer does not provide a certificate, it returns `null` or an empty +object. + +### cleartextStream.getCipher() +Returns an object representing the cipher name and the SSL/TLS +protocol version of the current connection. + +Example: +{ name: 'AES256-SHA', version: 'TLSv1/SSLv3' } + +See SSL_CIPHER_get_name() and SSL_CIPHER_get_version() in +http://www.openssl.org/docs/ssl/ssl.html#DEALING_WITH_CIPHERS for more +information. + +### cleartextStream.address() + +Returns the bound address, the address family name and port of the +underlying socket as reported by the operating system. Returns an +object with three properties, e.g. +`{ port: 12346, family: 'IPv4', address: '127.0.0.1' }` + +### cleartextStream.remoteAddress + +The string representation of the remote IP address. For example, +`'74.125.127.100'` or `'2001:4860:a005::68'`. + +### cleartextStream.remotePort + +The numeric representation of the remote port. For example, `443`. + +[OpenSSL cipher list format documentation]: http://www.openssl.org/docs/apps/ciphers.html#CIPHER_LIST_FORMAT +[BEAST attacks]: http://blog.ivanristic.com/2011/10/mitigating-the-beast-attack-on-tls.html +[CleartextStream]: #tls_class_tls_cleartextstream +[net.Server.address()]: net.html#net_server_address +['secureConnect']: #tls_event_secureconnect +[secureConnection]: #tls_event_secureconnection +[Stream]: stream.html#stream_stream +[tls.Server]: #tls_class_tls_server diff --git a/node-v0.8.14/doc/api/tty.html b/node-v0.8.14/doc/api/tty.html new file mode 100644 index 0000000..0cc2ac2 --- /dev/null +++ b/node-v0.8.14/doc/api/tty.html @@ -0,0 +1,178 @@ + + + + + TTY Node.js v0.8.14 Manual & Documentation + + + + + +
+ + + +
+
+ + +
+
+

Node.js v0.8.14 Manual & Documentation

+ +
+
+ + + +
+

TTY#

+
Stability: 2 - Unstable
+

The tty module houses the tty.ReadStream and tty.WriteStream classes. In +most cases, you will not need to use this module directly. + +

+

When node detects that it is being run inside a TTY context, then process.stdin +will be a tty.ReadStream instance and process.stdout will be +a tty.WriteStream instance. The preferred way to check if node is being run in +a TTY context is to check process.stdout.isTTY: + +

+
$ node -p -e "Boolean(process.stdout.isTTY)"
+true
+$ node -p -e "Boolean(process.stdout.isTTY)" | cat
+false
+

tty.isatty(fd)#

+

Returns true or false depending on if the fd is associated with a +terminal. + + +

+

tty.setRawMode(mode)#

+

Deprecated. Use tty.ReadStream#setRawMode() +(i.e. process.stdin.setRawMode()) instead. + + +

+

Class: ReadStream#

+

A net.Socket subclass that represents the readable portion of a tty. In normal +circumstances, process.stdin will be the only tty.ReadStream instance in any +node program (only when isatty(0) is true). + +

+

rs.isRaw#

+

A Boolean that is initialized to false. It represents the current "raw" state +of the tty.ReadStream instance. + +

+

rs.setRawMode(mode)#

+

mode should be true or false. This sets the properties of the +tty.ReadStream to act either as a raw device or default. isRaw will be set +to the resulting mode. + + +

+

Class WriteStream#

+

A net.Socket subclass that represents the writable portion of a tty. In normal +circumstances, process.stdout will be the only tty.WriteStream instance +ever created (and only when isatty(1) is true). + +

+

ws.columns#

+

A Number that gives the number of columns the TTY currently has. This property +gets updated on "resize" events. + +

+

ws.rows#

+

A Number that gives the number of rows the TTY currently has. This property +gets updated on "resize" events. + +

+

Event: 'resize'#

+

function () {} + +

+

Emitted by refreshSize() when either of the columns or rows properties +has changed. + +

+
process.stdout.on('resize', function() {
+  console.log('screen size has changed!');
+  console.log(process.stdout.columns + 'x' + process.stdout.rows);
+});
+ +
+
+
+ + + + + + + + + diff --git a/node-v0.8.14/doc/api/tty.json b/node-v0.8.14/doc/api/tty.json new file mode 100644 index 0000000..80c3b4b --- /dev/null +++ b/node-v0.8.14/doc/api/tty.json @@ -0,0 +1,108 @@ +{ + "source": "doc/api/tty.markdown", + "modules": [ + { + "textRaw": "TTY", + "name": "tty", + "stability": 2, + "stabilityText": "Unstable", + "desc": "

The tty module houses the tty.ReadStream and tty.WriteStream classes. In\nmost cases, you will not need to use this module directly.\n\n

\n

When node detects that it is being run inside a TTY context, then process.stdin\nwill be a tty.ReadStream instance and process.stdout will be\na tty.WriteStream instance. The preferred way to check if node is being run in\na TTY context is to check process.stdout.isTTY:\n\n

\n
$ node -p -e "Boolean(process.stdout.isTTY)"\ntrue\n$ node -p -e "Boolean(process.stdout.isTTY)" | cat\nfalse
\n", + "methods": [ + { + "textRaw": "tty.isatty(fd)", + "type": "method", + "name": "isatty", + "desc": "

Returns true or false depending on if the fd is associated with a\nterminal.\n\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "fd" + } + ] + } + ] + }, + { + "textRaw": "tty.setRawMode(mode)", + "type": "method", + "name": "setRawMode", + "desc": "

Deprecated. Use tty.ReadStream#setRawMode()\n(i.e. process.stdin.setRawMode()) instead.\n\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "mode" + } + ] + } + ] + } + ], + "classes": [ + { + "textRaw": "Class: ReadStream", + "type": "class", + "name": "ReadStream", + "desc": "

A net.Socket subclass that represents the readable portion of a tty. In normal\ncircumstances, process.stdin will be the only tty.ReadStream instance in any\nnode program (only when isatty(0) is true).\n\n

\n", + "properties": [ + { + "textRaw": "rs.isRaw", + "name": "isRaw", + "desc": "

A Boolean that is initialized to false. It represents the current "raw" state\nof the tty.ReadStream instance.\n\n

\n" + } + ], + "methods": [ + { + "textRaw": "rs.setRawMode(mode)", + "type": "method", + "name": "setRawMode", + "desc": "

mode should be true or false. This sets the properties of the\ntty.ReadStream to act either as a raw device or default. isRaw will be set\nto the resulting mode.\n\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "mode" + } + ] + } + ] + } + ] + } + ], + "modules": [ + { + "textRaw": "Class WriteStream", + "name": "class_writestream", + "desc": "

A net.Socket subclass that represents the writable portion of a tty. In normal\ncircumstances, process.stdout will be the only tty.WriteStream instance\never created (and only when isatty(1) is true).\n\n

\n", + "properties": [ + { + "textRaw": "ws.columns", + "name": "columns", + "desc": "

A Number that gives the number of columns the TTY currently has. This property\ngets updated on "resize" events.\n\n

\n" + }, + { + "textRaw": "ws.rows", + "name": "rows", + "desc": "

A Number that gives the number of rows the TTY currently has. This property\ngets updated on "resize" events.\n\n

\n" + } + ], + "events": [ + { + "textRaw": "Event: 'resize'", + "type": "event", + "name": "resize", + "desc": "

function () {}\n\n

\n

Emitted by refreshSize() when either of the columns or rows properties\nhas changed.\n\n

\n
process.stdout.on('resize', function() {\n  console.log('screen size has changed!');\n  console.log(process.stdout.columns + 'x' + process.stdout.rows);\n});
\n", + "params": [] + } + ], + "type": "module", + "displayName": "Class WriteStream" + } + ], + "type": "module", + "displayName": "TTY" + } + ] +} diff --git a/node-v0.8.14/doc/api/tty.markdown b/node-v0.8.14/doc/api/tty.markdown new file mode 100644 index 0000000..104fb8c --- /dev/null +++ b/node-v0.8.14/doc/api/tty.markdown @@ -0,0 +1,75 @@ +# TTY + + Stability: 2 - Unstable + +The `tty` module houses the `tty.ReadStream` and `tty.WriteStream` classes. In +most cases, you will not need to use this module directly. + +When node detects that it is being run inside a TTY context, then `process.stdin` +will be a `tty.ReadStream` instance and `process.stdout` will be +a `tty.WriteStream` instance. The preferred way to check if node is being run in +a TTY context is to check `process.stdout.isTTY`: + + $ node -p -e "Boolean(process.stdout.isTTY)" + true + $ node -p -e "Boolean(process.stdout.isTTY)" | cat + false + + +## tty.isatty(fd) + +Returns `true` or `false` depending on if the `fd` is associated with a +terminal. + + +## tty.setRawMode(mode) + +Deprecated. Use `tty.ReadStream#setRawMode()` +(i.e. `process.stdin.setRawMode()`) instead. + + +## Class: ReadStream + +A `net.Socket` subclass that represents the readable portion of a tty. In normal +circumstances, `process.stdin` will be the only `tty.ReadStream` instance in any +node program (only when `isatty(0)` is true). + +### rs.isRaw + +A `Boolean` that is initialized to `false`. It represents the current "raw" state +of the `tty.ReadStream` instance. + +### rs.setRawMode(mode) + +`mode` should be `true` or `false`. This sets the properties of the +`tty.ReadStream` to act either as a raw device or default. `isRaw` will be set +to the resulting mode. + + +## Class WriteStream + +A `net.Socket` subclass that represents the writable portion of a tty. In normal +circumstances, `process.stdout` will be the only `tty.WriteStream` instance +ever created (and only when `isatty(1)` is true). + +### ws.columns + +A `Number` that gives the number of columns the TTY currently has. This property +gets updated on "resize" events. + +### ws.rows + +A `Number` that gives the number of rows the TTY currently has. This property +gets updated on "resize" events. + +### Event: 'resize' + +`function () {}` + +Emitted by `refreshSize()` when either of the `columns` or `rows` properties +has changed. + + process.stdout.on('resize', function() { + console.log('screen size has changed!'); + console.log(process.stdout.columns + 'x' + process.stdout.rows); + }); diff --git a/node-v0.8.14/doc/api/url.html b/node-v0.8.14/doc/api/url.html new file mode 100644 index 0000000..c0e39a2 --- /dev/null +++ b/node-v0.8.14/doc/api/url.html @@ -0,0 +1,191 @@ + + + + + URL Node.js v0.8.14 Manual & Documentation + + + + + +
+ + + +
+
+ + +
+
+

Node.js v0.8.14 Manual & Documentation

+ +
+
+ + + +
+

URL#

+
Stability: 3 - Stable
+

This module has utilities for URL resolution and parsing. +Call require('url') to use it. + +

+

Parsed URL objects have some or all of the following fields, depending on +whether or not they exist in the URL string. Any parts that are not in the URL +string will not be in the parsed object. Examples are shown for the URL + +

+

'http://user:pass@host.com:8080/p/a/t/h?query=string#hash' + +

+
    +
  • href: The full URL that was originally parsed. Both the protocol and host are lowercased.

    +

    Example: 'http://user:pass@host.com:8080/p/a/t/h?query=string#hash'

    +
  • +
  • protocol: The request protocol, lowercased.

    +

    Example: 'http:'

    +
  • +
  • host: The full lowercased host portion of the URL, including port +information.

    +

    Example: 'host.com:8080'

    +
  • +
  • auth: The authentication information portion of a URL.

    +

    Example: 'user:pass'

    +
  • +
  • hostname: Just the lowercased hostname portion of the host.

    +

    Example: 'host.com'

    +
  • +
  • port: The port number portion of the host.

    +

    Example: '8080'

    +
  • +
  • pathname: The path section of the URL, that comes after the host and +before the query, including the initial slash if present.

    +

    Example: '/p/a/t/h'

    +
  • +
  • search: The 'query string' portion of the URL, including the leading +question mark.

    +

    Example: '?query=string'

    +
  • +
  • path: Concatenation of pathname and search.

    +

    Example: '/p/a/t/h?query=string'

    +
  • +
  • query: Either the 'params' portion of the query string, or a +querystring-parsed object.

    +

    Example: 'query=string' or {'query':'string'}

    +
  • +
  • hash: The 'fragment' portion of the URL including the pound-sign.

    +

    Example: '#hash'

    +
  • +
+

The following methods are provided by the URL module: + +

+

url.parse(urlStr, [parseQueryString], [slashesDenoteHost])#

+

Take a URL string, and return an object. + +

+

Pass true as the second argument to also parse +the query string using the querystring module. +Defaults to false. + +

+

Pass true as the third argument to treat //foo/bar as +{ host: 'foo', pathname: '/bar' } rather than +{ pathname: '//foo/bar' }. Defaults to false. + +

+

url.format(urlObj)#

+

Take a parsed URL object, and return a formatted URL string. + +

+
    +
  • href will be ignored.
  • +
  • protocolis treated the same with or without the trailing : (colon).
      +
    • The protocols http, https, ftp, gopher, file will be +postfixed with :// (colon-slash-slash).
    • +
    • All other protocols mailto, xmpp, aim, sftp, foo, etc will +be postfixed with : (colon)
    • +
    +
  • +
  • auth will be used if present.
  • +
  • hostname will only be used if host is absent.
  • +
  • port will only be used if host is absent.
  • +
  • host will be used in place of hostname and port
  • +
  • pathname is treated the same with or without the leading / (slash)
  • +
  • search will be used in place of query
  • +
  • query (object; see querystring) will only be used if search is absent.
  • +
  • search is treated the same with or without the leading ? (question mark)
  • +
  • hash is treated the same with or without the leading # (pound sign, anchor)
  • +
+

url.resolve(from, to)#

+

Take a base URL, and a href URL, and resolve them as a browser would for +an anchor tag. +

+ +
+
+
+ + + + + + + + + diff --git a/node-v0.8.14/doc/api/url.json b/node-v0.8.14/doc/api/url.json new file mode 100644 index 0000000..ec26586 --- /dev/null +++ b/node-v0.8.14/doc/api/url.json @@ -0,0 +1,72 @@ +{ + "source": "doc/api/url.markdown", + "modules": [ + { + "textRaw": "URL", + "name": "url", + "stability": 3, + "stabilityText": "Stable", + "desc": "

This module has utilities for URL resolution and parsing.\nCall require('url') to use it.\n\n

\n

Parsed URL objects have some or all of the following fields, depending on\nwhether or not they exist in the URL string. Any parts that are not in the URL\nstring will not be in the parsed object. Examples are shown for the URL\n\n

\n

'http://user:pass@host.com:8080/p/a/t/h?query=string#hash'\n\n

\n
    \n
  • href: The full URL that was originally parsed. Both the protocol and host are lowercased.

    \n

    Example: 'http://user:pass@host.com:8080/p/a/t/h?query=string#hash'

    \n
  • \n
  • protocol: The request protocol, lowercased.

    \n

    Example: 'http:'

    \n
  • \n
  • host: The full lowercased host portion of the URL, including port\ninformation.

    \n

    Example: 'host.com:8080'

    \n
  • \n
  • auth: The authentication information portion of a URL.

    \n

    Example: 'user:pass'

    \n
  • \n
  • hostname: Just the lowercased hostname portion of the host.

    \n

    Example: 'host.com'

    \n
  • \n
  • port: The port number portion of the host.

    \n

    Example: '8080'

    \n
  • \n
  • pathname: The path section of the URL, that comes after the host and\nbefore the query, including the initial slash if present.

    \n

    Example: '/p/a/t/h'

    \n
  • \n
  • search: The 'query string' portion of the URL, including the leading\nquestion mark.

    \n

    Example: '?query=string'

    \n
  • \n
  • path: Concatenation of pathname and search.

    \n

    Example: '/p/a/t/h?query=string'

    \n
  • \n
  • query: Either the 'params' portion of the query string, or a\nquerystring-parsed object.

    \n

    Example: 'query=string' or {'query':'string'}

    \n
  • \n
  • hash: The 'fragment' portion of the URL including the pound-sign.

    \n

    Example: '#hash'

    \n
  • \n
\n

The following methods are provided by the URL module:\n\n

\n", + "methods": [ + { + "textRaw": "url.parse(urlStr, [parseQueryString], [slashesDenoteHost])", + "type": "method", + "name": "parse", + "desc": "

Take a URL string, and return an object.\n\n

\n

Pass true as the second argument to also parse\nthe query string using the querystring module.\nDefaults to false.\n\n

\n

Pass true as the third argument to treat //foo/bar as\n{ host: 'foo', pathname: '/bar' } rather than\n{ pathname: '//foo/bar' }. Defaults to false.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "urlStr" + }, + { + "name": "parseQueryString", + "optional": true + }, + { + "name": "slashesDenoteHost", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "url.format(urlObj)", + "type": "method", + "name": "format", + "desc": "

Take a parsed URL object, and return a formatted URL string.\n\n

\n
    \n
  • href will be ignored.
  • \n
  • protocolis treated the same with or without the trailing : (colon).
      \n
    • The protocols http, https, ftp, gopher, file will be\npostfixed with :// (colon-slash-slash).
    • \n
    • All other protocols mailto, xmpp, aim, sftp, foo, etc will\nbe postfixed with : (colon)
    • \n
    \n
  • \n
  • auth will be used if present.
  • \n
  • hostname will only be used if host is absent.
  • \n
  • port will only be used if host is absent.
  • \n
  • host will be used in place of hostname and port
  • \n
  • pathname is treated the same with or without the leading / (slash)
  • \n
  • search will be used in place of query
  • \n
  • query (object; see querystring) will only be used if search is absent.
  • \n
  • search is treated the same with or without the leading ? (question mark)
  • \n
  • hash is treated the same with or without the leading # (pound sign, anchor)
  • \n
\n", + "signatures": [ + { + "params": [ + { + "name": "urlObj" + } + ] + } + ] + }, + { + "textRaw": "url.resolve(from, to)", + "type": "method", + "name": "resolve", + "desc": "

Take a base URL, and a href URL, and resolve them as a browser would for\nan anchor tag.\n

\n", + "signatures": [ + { + "params": [ + { + "name": "from" + }, + { + "name": "to" + } + ] + } + ] + } + ], + "type": "module", + "displayName": "URL" + } + ] +} diff --git a/node-v0.8.14/doc/api/url.markdown b/node-v0.8.14/doc/api/url.markdown new file mode 100644 index 0000000..8e6a63d --- /dev/null +++ b/node-v0.8.14/doc/api/url.markdown @@ -0,0 +1,99 @@ +# URL + + Stability: 3 - Stable + +This module has utilities for URL resolution and parsing. +Call `require('url')` to use it. + +Parsed URL objects have some or all of the following fields, depending on +whether or not they exist in the URL string. Any parts that are not in the URL +string will not be in the parsed object. Examples are shown for the URL + +`'http://user:pass@host.com:8080/p/a/t/h?query=string#hash'` + +* `href`: The full URL that was originally parsed. Both the protocol and host are lowercased. + + Example: `'http://user:pass@host.com:8080/p/a/t/h?query=string#hash'` + +* `protocol`: The request protocol, lowercased. + + Example: `'http:'` + +* `host`: The full lowercased host portion of the URL, including port + information. + + Example: `'host.com:8080'` + +* `auth`: The authentication information portion of a URL. + + Example: `'user:pass'` + +* `hostname`: Just the lowercased hostname portion of the host. + + Example: `'host.com'` + +* `port`: The port number portion of the host. + + Example: `'8080'` + +* `pathname`: The path section of the URL, that comes after the host and + before the query, including the initial slash if present. + + Example: `'/p/a/t/h'` + +* `search`: The 'query string' portion of the URL, including the leading + question mark. + + Example: `'?query=string'` + +* `path`: Concatenation of `pathname` and `search`. + + Example: `'/p/a/t/h?query=string'` + +* `query`: Either the 'params' portion of the query string, or a + querystring-parsed object. + + Example: `'query=string'` or `{'query':'string'}` + +* `hash`: The 'fragment' portion of the URL including the pound-sign. + + Example: `'#hash'` + +The following methods are provided by the URL module: + +## url.parse(urlStr, [parseQueryString], [slashesDenoteHost]) + +Take a URL string, and return an object. + +Pass `true` as the second argument to also parse +the query string using the `querystring` module. +Defaults to `false`. + +Pass `true` as the third argument to treat `//foo/bar` as +`{ host: 'foo', pathname: '/bar' }` rather than +`{ pathname: '//foo/bar' }`. Defaults to `false`. + +## url.format(urlObj) + +Take a parsed URL object, and return a formatted URL string. + +* `href` will be ignored. +* `protocol`is treated the same with or without the trailing `:` (colon). + * The protocols `http`, `https`, `ftp`, `gopher`, `file` will be + postfixed with `://` (colon-slash-slash). + * All other protocols `mailto`, `xmpp`, `aim`, `sftp`, `foo`, etc will + be postfixed with `:` (colon) +* `auth` will be used if present. +* `hostname` will only be used if `host` is absent. +* `port` will only be used if `host` is absent. +* `host` will be used in place of `hostname` and `port` +* `pathname` is treated the same with or without the leading `/` (slash) +* `search` will be used in place of `query` +* `query` (object; see `querystring`) will only be used if `search` is absent. +* `search` is treated the same with or without the leading `?` (question mark) +* `hash` is treated the same with or without the leading `#` (pound sign, anchor) + +## url.resolve(from, to) + +Take a base URL, and a href URL, and resolve them as a browser would for +an anchor tag. diff --git a/node-v0.8.14/doc/api/util.html b/node-v0.8.14/doc/api/util.html new file mode 100644 index 0000000..1ee87c6 --- /dev/null +++ b/node-v0.8.14/doc/api/util.html @@ -0,0 +1,299 @@ + + + + + util Node.js v0.8.14 Manual & Documentation + + + + + +
+ + + +
+
+ + +
+
+

Node.js v0.8.14 Manual & Documentation

+ +
+
+ + + +
+

util#

+
Stability: 5 - Locked
+

These functions are in the module 'util'. Use require('util') to access +them. + + +

+

util.format(format, [...])#

+

Returns a formatted string using the first argument as a printf-like format. + +

+

The first argument is a string that contains zero or more placeholders. +Each placeholder is replaced with the converted value from its corresponding +argument. Supported placeholders are: + +

+
    +
  • %s - String.
  • +
  • %d - Number (both integer and float).
  • +
  • %j - JSON.
  • +
  • % - single percent sign ('%'). This does not consume an argument.
  • +
+

If the placeholder does not have a corresponding argument, the placeholder is +not replaced. + +

+
util.format('%s:%s', 'foo'); // 'foo:%s'
+

If there are more arguments than placeholders, the extra arguments are +converted to strings with util.inspect() and these strings are concatenated, +delimited by a space. + +

+
util.format('%s:%s', 'foo', 'bar', 'baz'); // 'foo:bar baz'
+

If the first argument is not a format string then util.format() returns +a string that is the concatenation of all its arguments separated by spaces. +Each argument is converted to a string with util.inspect(). + +

+
util.format(1, 2, 3); // '1 2 3'
+

util.debug(string)#

+

A synchronous output function. Will block the process and +output string immediately to stderr. + +

+
require('util').debug('message on stderr');
+

util.error([...])#

+

Same as util.debug() except this will output all arguments immediately to +stderr. + +

+

util.puts([...])#

+

A synchronous output function. Will block the process and output all arguments +to stdout with newlines after each argument. + +

+

util.print([...])#

+

A synchronous output function. Will block the process, cast each argument to a +string then output to stdout. Does not place newlines after each argument. + +

+

util.log(string)#

+

Output with timestamp on stdout. + +

+
require('util').log('Timestamped message.');
+

util.inspect(object, [showHidden], [depth], [colors])#

+

Return a string representation of object, which is useful for debugging. + +

+

If showHidden is true, then the object's non-enumerable properties will be +shown too. Defaults to false. + +

+

If depth is provided, it tells inspect how many times to recurse while +formatting the object. This is useful for inspecting large complicated objects. + +

+

The default is to only recurse twice. To make it recurse indefinitely, pass +in null for depth. + +

+

If colors is true, the output will be styled with ANSI color codes. +Defaults to false. + +

+

Example of inspecting all properties of the util object: + +

+
var util = require('util');
+
+console.log(util.inspect(util, true, null));
+

Objects also may define their own inspect(depth) function which util.inspect() +will invoke and use the result of when inspecting the object: + +

+
var util = require('util');
+
+var obj = { name: 'nate' };
+obj.inspect = function(depth) {
+  return '{' + this.name + '}';
+};
+
+util.inspect(obj);
+  // "{nate}"
+

util.isArray(object)#

+

Returns true if the given "object" is an Array. false otherwise. + +

+
var util = require('util');
+
+util.isArray([])
+  // true
+util.isArray(new Array)
+  // true
+util.isArray({})
+  // false
+

util.isRegExp(object)#

+

Returns true if the given "object" is a RegExp. false otherwise. + +

+
var util = require('util');
+
+util.isRegExp(/some regexp/)
+  // true
+util.isRegExp(new RegExp('another regexp'))
+  // true
+util.isRegExp({})
+  // false
+

util.isDate(object)#

+

Returns true if the given "object" is a Date. false otherwise. + +

+
var util = require('util');
+
+util.isDate(new Date())
+  // true
+util.isDate(Date())
+  // false (without 'new' returns a String)
+util.isDate({})
+  // false
+

util.isError(object)#

+

Returns true if the given "object" is an Error. false otherwise. + +

+
var util = require('util');
+
+util.isError(new Error())
+  // true
+util.isError(new TypeError())
+  // true
+util.isError({ name: 'Error', message: 'an error occurred' })
+  // false
+

util.pump(readableStream, writableStream, [callback])#

+
Stability: 0 - Deprecated: Use readableStream.pipe(writableStream)
+

Read the data from readableStream and send it to the writableStream. +When writableStream.write(data) returns false readableStream will be +paused until the drain event occurs on the writableStream. callback gets +an error as its only argument and is called when writableStream is closed or +when an error occurs. + + +

+

util.inherits(constructor, superConstructor)#

+

Inherit the prototype methods from one +constructor +into another. The prototype of constructor will be set to a new +object created from superConstructor. + +

+

As an additional convenience, superConstructor will be accessible +through the constructor.super_ property. + +

+
var util = require("util");
+var events = require("events");
+
+function MyStream() {
+    events.EventEmitter.call(this);
+}
+
+util.inherits(MyStream, events.EventEmitter);
+
+MyStream.prototype.write = function(data) {
+    this.emit("data", data);
+}
+
+var stream = new MyStream();
+
+console.log(stream instanceof events.EventEmitter); // true
+console.log(MyStream.super_ === events.EventEmitter); // true
+
+stream.on("data", function(data) {
+    console.log('Received data: "' + data + '"');
+})
+stream.write("It works!"); // Received data: "It works!"
+ +
+
+
+ + + + + + + + + diff --git a/node-v0.8.14/doc/api/util.json b/node-v0.8.14/doc/api/util.json new file mode 100644 index 0000000..2270e8f --- /dev/null +++ b/node-v0.8.14/doc/api/util.json @@ -0,0 +1,242 @@ +{ + "source": "doc/api/util.markdown", + "modules": [ + { + "textRaw": "util", + "name": "util", + "stability": 5, + "stabilityText": "Locked", + "desc": "

These functions are in the module 'util'. Use require('util') to access\nthem.\n\n\n

\n", + "methods": [ + { + "textRaw": "util.format(format, [...])", + "type": "method", + "name": "format", + "desc": "

Returns a formatted string using the first argument as a printf-like format.\n\n

\n

The first argument is a string that contains zero or more placeholders.\nEach placeholder is replaced with the converted value from its corresponding\nargument. Supported placeholders are:\n\n

\n
    \n
  • %s - String.
  • \n
  • %d - Number (both integer and float).
  • \n
  • %j - JSON.
  • \n
  • % - single percent sign ('%'). This does not consume an argument.
  • \n
\n

If the placeholder does not have a corresponding argument, the placeholder is\nnot replaced.\n\n

\n
util.format('%s:%s', 'foo'); // 'foo:%s'
\n

If there are more arguments than placeholders, the extra arguments are\nconverted to strings with util.inspect() and these strings are concatenated,\ndelimited by a space.\n\n

\n
util.format('%s:%s', 'foo', 'bar', 'baz'); // 'foo:bar baz'
\n

If the first argument is not a format string then util.format() returns\na string that is the concatenation of all its arguments separated by spaces.\nEach argument is converted to a string with util.inspect().\n\n

\n
util.format(1, 2, 3); // '1 2 3'
\n", + "signatures": [ + { + "params": [ + { + "name": "format" + }, + { + "name": "...", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "util.debug(string)", + "type": "method", + "name": "debug", + "desc": "

A synchronous output function. Will block the process and\noutput string immediately to stderr.\n\n

\n
require('util').debug('message on stderr');
\n", + "signatures": [ + { + "params": [ + { + "name": "string" + } + ] + } + ] + }, + { + "textRaw": "util.error([...])", + "type": "method", + "name": "error", + "desc": "

Same as util.debug() except this will output all arguments immediately to\nstderr.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "...", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "util.puts([...])", + "type": "method", + "name": "puts", + "desc": "

A synchronous output function. Will block the process and output all arguments\nto stdout with newlines after each argument.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "...", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "util.print([...])", + "type": "method", + "name": "print", + "desc": "

A synchronous output function. Will block the process, cast each argument to a\nstring then output to stdout. Does not place newlines after each argument.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "...", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "util.log(string)", + "type": "method", + "name": "log", + "desc": "

Output with timestamp on stdout.\n\n

\n
require('util').log('Timestamped message.');
\n", + "signatures": [ + { + "params": [ + { + "name": "string" + } + ] + } + ] + }, + { + "textRaw": "util.inspect(object, [showHidden], [depth], [colors])", + "type": "method", + "name": "inspect", + "desc": "

Return a string representation of object, which is useful for debugging.\n\n

\n

If showHidden is true, then the object's non-enumerable properties will be\nshown too. Defaults to false.\n\n

\n

If depth is provided, it tells inspect how many times to recurse while\nformatting the object. This is useful for inspecting large complicated objects.\n\n

\n

The default is to only recurse twice. To make it recurse indefinitely, pass\nin null for depth.\n\n

\n

If colors is true, the output will be styled with ANSI color codes.\nDefaults to false.\n\n

\n

Example of inspecting all properties of the util object:\n\n

\n
var util = require('util');\n\nconsole.log(util.inspect(util, true, null));
\n

Objects also may define their own inspect(depth) function which util.inspect()\nwill invoke and use the result of when inspecting the object:\n\n

\n
var util = require('util');\n\nvar obj = { name: 'nate' };\nobj.inspect = function(depth) {\n  return '{' + this.name + '}';\n};\n\nutil.inspect(obj);\n  // "{nate}"
\n", + "signatures": [ + { + "params": [ + { + "name": "object" + }, + { + "name": "showHidden", + "optional": true + }, + { + "name": "depth", + "optional": true + }, + { + "name": "colors", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "util.isArray(object)", + "type": "method", + "name": "isArray", + "desc": "

Returns true if the given "object" is an Array. false otherwise.\n\n

\n
var util = require('util');\n\nutil.isArray([])\n  // true\nutil.isArray(new Array)\n  // true\nutil.isArray({})\n  // false
\n", + "signatures": [ + { + "params": [ + { + "name": "object" + } + ] + } + ] + }, + { + "textRaw": "util.isRegExp(object)", + "type": "method", + "name": "isRegExp", + "desc": "

Returns true if the given "object" is a RegExp. false otherwise.\n\n

\n
var util = require('util');\n\nutil.isRegExp(/some regexp/)\n  // true\nutil.isRegExp(new RegExp('another regexp'))\n  // true\nutil.isRegExp({})\n  // false
\n", + "signatures": [ + { + "params": [ + { + "name": "object" + } + ] + } + ] + }, + { + "textRaw": "util.isDate(object)", + "type": "method", + "name": "isDate", + "desc": "

Returns true if the given "object" is a Date. false otherwise.\n\n

\n
var util = require('util');\n\nutil.isDate(new Date())\n  // true\nutil.isDate(Date())\n  // false (without 'new' returns a String)\nutil.isDate({})\n  // false
\n", + "signatures": [ + { + "params": [ + { + "name": "object" + } + ] + } + ] + }, + { + "textRaw": "util.isError(object)", + "type": "method", + "name": "isError", + "desc": "

Returns true if the given "object" is an Error. false otherwise.\n\n

\n
var util = require('util');\n\nutil.isError(new Error())\n  // true\nutil.isError(new TypeError())\n  // true\nutil.isError({ name: 'Error', message: 'an error occurred' })\n  // false
\n", + "signatures": [ + { + "params": [ + { + "name": "object" + } + ] + } + ] + }, + { + "textRaw": "util.pump(readableStream, writableStream, [callback])", + "type": "method", + "name": "pump", + "stability": 0, + "stabilityText": "Deprecated: Use readableStream.pipe(writableStream)", + "desc": "

Read the data from readableStream and send it to the writableStream.\nWhen writableStream.write(data) returns false readableStream will be\npaused until the drain event occurs on the writableStream. callback gets\nan error as its only argument and is called when writableStream is closed or\nwhen an error occurs.\n\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "readableStream" + }, + { + "name": "writableStream" + }, + { + "name": "callback", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "util.inherits(constructor, superConstructor)", + "type": "method", + "name": "inherits", + "desc": "

Inherit the prototype methods from one\nconstructor\ninto another. The prototype of constructor will be set to a new\nobject created from superConstructor.\n\n

\n

As an additional convenience, superConstructor will be accessible\nthrough the constructor.super_ property.\n\n

\n
var util = require("util");\nvar events = require("events");\n\nfunction MyStream() {\n    events.EventEmitter.call(this);\n}\n\nutil.inherits(MyStream, events.EventEmitter);\n\nMyStream.prototype.write = function(data) {\n    this.emit("data", data);\n}\n\nvar stream = new MyStream();\n\nconsole.log(stream instanceof events.EventEmitter); // true\nconsole.log(MyStream.super_ === events.EventEmitter); // true\n\nstream.on("data", function(data) {\n    console.log('Received data: "' + data + '"');\n})\nstream.write("It works!"); // Received data: "It works!"
\n", + "signatures": [ + { + "params": [ + { + "name": "constructor" + }, + { + "name": "superConstructor" + } + ] + } + ] + } + ], + "type": "module", + "displayName": "util" + } + ] +} diff --git a/node-v0.8.14/doc/api/util.markdown b/node-v0.8.14/doc/api/util.markdown new file mode 100644 index 0000000..58bbfb7 --- /dev/null +++ b/node-v0.8.14/doc/api/util.markdown @@ -0,0 +1,203 @@ +# util + + Stability: 5 - Locked + +These functions are in the module `'util'`. Use `require('util')` to access +them. + + +## util.format(format, [...]) + +Returns a formatted string using the first argument as a `printf`-like format. + +The first argument is a string that contains zero or more *placeholders*. +Each placeholder is replaced with the converted value from its corresponding +argument. Supported placeholders are: + +* `%s` - String. +* `%d` - Number (both integer and float). +* `%j` - JSON. +* `%%` - single percent sign (`'%'`). This does not consume an argument. + +If the placeholder does not have a corresponding argument, the placeholder is +not replaced. + + util.format('%s:%s', 'foo'); // 'foo:%s' + +If there are more arguments than placeholders, the extra arguments are +converted to strings with `util.inspect()` and these strings are concatenated, +delimited by a space. + + util.format('%s:%s', 'foo', 'bar', 'baz'); // 'foo:bar baz' + +If the first argument is not a format string then `util.format()` returns +a string that is the concatenation of all its arguments separated by spaces. +Each argument is converted to a string with `util.inspect()`. + + util.format(1, 2, 3); // '1 2 3' + + +## util.debug(string) + +A synchronous output function. Will block the process and +output `string` immediately to `stderr`. + + require('util').debug('message on stderr'); + +## util.error([...]) + +Same as `util.debug()` except this will output all arguments immediately to +`stderr`. + +## util.puts([...]) + +A synchronous output function. Will block the process and output all arguments +to `stdout` with newlines after each argument. + +## util.print([...]) + +A synchronous output function. Will block the process, cast each argument to a +string then output to `stdout`. Does not place newlines after each argument. + +## util.log(string) + +Output with timestamp on `stdout`. + + require('util').log('Timestamped message.'); + + +## util.inspect(object, [showHidden], [depth], [colors]) + +Return a string representation of `object`, which is useful for debugging. + +If `showHidden` is `true`, then the object's non-enumerable properties will be +shown too. Defaults to `false`. + +If `depth` is provided, it tells `inspect` how many times to recurse while +formatting the object. This is useful for inspecting large complicated objects. + +The default is to only recurse twice. To make it recurse indefinitely, pass +in `null` for `depth`. + +If `colors` is `true`, the output will be styled with ANSI color codes. +Defaults to `false`. + +Example of inspecting all properties of the `util` object: + + var util = require('util'); + + console.log(util.inspect(util, true, null)); + +Objects also may define their own `inspect(depth)` function which `util.inspect()` +will invoke and use the result of when inspecting the object: + + var util = require('util'); + + var obj = { name: 'nate' }; + obj.inspect = function(depth) { + return '{' + this.name + '}'; + }; + + util.inspect(obj); + // "{nate}" + + +## util.isArray(object) + +Returns `true` if the given "object" is an `Array`. `false` otherwise. + + var util = require('util'); + + util.isArray([]) + // true + util.isArray(new Array) + // true + util.isArray({}) + // false + + +## util.isRegExp(object) + +Returns `true` if the given "object" is a `RegExp`. `false` otherwise. + + var util = require('util'); + + util.isRegExp(/some regexp/) + // true + util.isRegExp(new RegExp('another regexp')) + // true + util.isRegExp({}) + // false + + +## util.isDate(object) + +Returns `true` if the given "object" is a `Date`. `false` otherwise. + + var util = require('util'); + + util.isDate(new Date()) + // true + util.isDate(Date()) + // false (without 'new' returns a String) + util.isDate({}) + // false + + +## util.isError(object) + +Returns `true` if the given "object" is an `Error`. `false` otherwise. + + var util = require('util'); + + util.isError(new Error()) + // true + util.isError(new TypeError()) + // true + util.isError({ name: 'Error', message: 'an error occurred' }) + // false + + +## util.pump(readableStream, writableStream, [callback]) + + Stability: 0 - Deprecated: Use readableStream.pipe(writableStream) + +Read the data from `readableStream` and send it to the `writableStream`. +When `writableStream.write(data)` returns `false` `readableStream` will be +paused until the `drain` event occurs on the `writableStream`. `callback` gets +an error as its only argument and is called when `writableStream` is closed or +when an error occurs. + + +## util.inherits(constructor, superConstructor) + +Inherit the prototype methods from one +[constructor](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object/constructor) +into another. The prototype of `constructor` will be set to a new +object created from `superConstructor`. + +As an additional convenience, `superConstructor` will be accessible +through the `constructor.super_` property. + + var util = require("util"); + var events = require("events"); + + function MyStream() { + events.EventEmitter.call(this); + } + + util.inherits(MyStream, events.EventEmitter); + + MyStream.prototype.write = function(data) { + this.emit("data", data); + } + + var stream = new MyStream(); + + console.log(stream instanceof events.EventEmitter); // true + console.log(MyStream.super_ === events.EventEmitter); // true + + stream.on("data", function(data) { + console.log('Received data: "' + data + '"'); + }) + stream.write("It works!"); // Received data: "It works!" diff --git a/node-v0.8.14/doc/api/vm.html b/node-v0.8.14/doc/api/vm.html new file mode 100644 index 0000000..4f214c5 --- /dev/null +++ b/node-v0.8.14/doc/api/vm.html @@ -0,0 +1,336 @@ + + + + + Executing JavaScript Node.js v0.8.14 Manual & Documentation + + + + + +
+ + + +
+
+ + +
+
+

Node.js v0.8.14 Manual & Documentation

+ +
+
+ + + +
+

Executing JavaScript#

+
Stability: 2 - Unstable. See Caveats, below.
+ + +

You can access this module with: + +

+
var vm = require('vm');
+

JavaScript code can be compiled and run immediately or compiled, saved, and run later. + +

+

Caveats#

+

The vm module has many known issues and edge cases. If you run into +issues or unexpected behavior, please consult +the open issues on GitHub. +Some of the biggest problems are described below. + +

+

Sandboxes#

+

The sandbox argument to vm.runInNewContext and vm.createContext, +along with the initSandbox argument to vm.createContext, do not +behave as one might normally expect and their behavior varies +between different versions of Node. + +

+

The key issue to be aware of is that V8 provides no way to directly +control the global object used within a context. As a result, while +properties of your sandbox object will be available in the context, +any properties from the prototypes of the sandbox may not be +available. Furthermore, the this expression within the global scope +of the context evaluates to the empty object ({}) instead of to +your sandbox. + +

+

Your sandbox's properties are also not shared directly with the script. +Instead, the properties of the sandbox are copied into the context at +the beginning of execution, and then after execution, the properties +are copied back out in an attempt to propagate any changes. + +

+

Globals#

+

Properties of the global object, like Array and String, have +different values inside of a context. This means that common +expressions like [] instanceof Array or +Object.getPrototypeOf([]) === Array.prototype may not produce +expected results when used inside of scripts evaluated via the vm module. + +

+

Some of these problems have known workarounds listed in the issues for +vm on GitHub. for example, Array.isArray works around +the example problem with Array. + +

+

vm.runInThisContext(code, [filename])#

+

vm.runInThisContext() compiles code, runs it and returns the result. Running +code does not have access to local scope. filename is optional, it's used only +in stack traces. + +

+

Example of using vm.runInThisContext and eval to run the same code: + +

+
var localVar = 123,
+    usingscript, evaled,
+    vm = require('vm');
+
+usingscript = vm.runInThisContext('localVar = 1;',
+  'myfile.vm');
+console.log('localVar: ' + localVar + ', usingscript: ' +
+  usingscript);
+evaled = eval('localVar = 1;');
+console.log('localVar: ' + localVar + ', evaled: ' +
+  evaled);
+
+// localVar: 123, usingscript: 1
+// localVar: 1, evaled: 1
+

vm.runInThisContext does not have access to the local scope, so localVar is unchanged. +eval does have access to the local scope, so localVar is changed. + +

+

In case of syntax error in code, vm.runInThisContext emits the syntax error to stderr +and throws an exception. + + +

+

vm.runInNewContext(code, [sandbox], [filename])#

+

vm.runInNewContext compiles code, then runs it in sandbox and returns the +result. Running code does not have access to local scope. The object sandbox +will be used as the global object for code. +sandbox and filename are optional, filename is only used in stack traces. + +

+

Example: compile and execute code that increments a global variable and sets a new one. +These globals are contained in the sandbox. + +

+
var util = require('util'),
+    vm = require('vm'),
+    sandbox = {
+      animal: 'cat',
+      count: 2
+    };
+
+vm.runInNewContext('count += 1; name = "kitty"', sandbox, 'myfile.vm');
+console.log(util.inspect(sandbox));
+
+// { animal: 'cat', count: 3, name: 'kitty' }
+

Note that running untrusted code is a tricky business requiring great care. To prevent accidental +global variable leakage, vm.runInNewContext is quite useful, but safely running untrusted code +requires a separate process. + +

+

In case of syntax error in code, vm.runInNewContext emits the syntax error to stderr +and throws an exception. + +

+

vm.runInContext(code, context, [filename])#

+

vm.runInContext compiles code, then runs it in context and returns the +result. A (V8) context comprises a global object, together with a set of +built-in objects and functions. Running code does not have access to local scope +and the global object held within context will be used as the global object +for code. +filename is optional, it's used only in stack traces. + +

+

Example: compile and execute code in a existing context. + +

+
var util = require('util'),
+    vm = require('vm'),
+    initSandbox = {
+      animal: 'cat',
+      count: 2
+    },
+    context = vm.createContext(initSandbox);
+
+vm.runInContext('count += 1; name = "CATT"', context, 'myfile.vm');
+console.log(util.inspect(context));
+
+// { animal: 'cat', count: 3, name: 'CATT' }
+

Note that createContext will perform a shallow clone of the supplied sandbox object in order to +initialize the global object of the freshly constructed context. + +

+

Note that running untrusted code is a tricky business requiring great care. To prevent accidental +global variable leakage, vm.runInContext is quite useful, but safely running untrusted code +requires a separate process. + +

+

In case of syntax error in code, vm.runInContext emits the syntax error to stderr +and throws an exception. + +

+

vm.createContext([initSandbox])#

+

vm.createContext creates a new context which is suitable for use as the 2nd argument of a subsequent +call to vm.runInContext. A (V8) context comprises a global object together with a set of +build-in objects and functions. The optional argument initSandbox will be shallow-copied +to seed the initial contents of the global object used by the context. + +

+

vm.createScript(code, [filename])#

+

createScript compiles code but does not run it. Instead, it returns a +vm.Script object representing this compiled code. This script can be run +later many times using methods below. The returned script is not bound to any +global object. It is bound before each run, just for that run. filename is +optional, it's only used in stack traces. + +

+

In case of syntax error in code, createScript prints the syntax error to stderr +and throws an exception. + + +

+

Class: Script#

+

A class for running scripts. Returned by vm.createScript. + +

+

script.runInThisContext()#

+

Similar to vm.runInThisContext but a method of a precompiled Script object. +script.runInThisContext runs the code of script and returns the result. +Running code does not have access to local scope, but does have access to the global object +(v8: in actual context). + +

+

Example of using script.runInThisContext to compile code once and run it multiple times: + +

+
var vm = require('vm');
+
+globalVar = 0;
+
+var script = vm.createScript('globalVar += 1', 'myfile.vm');
+
+for (var i = 0; i < 1000 ; i += 1) {
+  script.runInThisContext();
+}
+
+console.log(globalVar);
+
+// 1000
+

script.runInNewContext([sandbox])#

+

Similar to vm.runInNewContext a method of a precompiled Script object. +script.runInNewContext runs the code of script with sandbox as the global object and returns the result. +Running code does not have access to local scope. sandbox is optional. + +

+

Example: compile code that increments a global variable and sets one, then execute this code multiple times. +These globals are contained in the sandbox. + +

+
var util = require('util'),
+    vm = require('vm'),
+    sandbox = {
+      animal: 'cat',
+      count: 2
+    };
+
+var script = vm.createScript('count += 1; name = "kitty"', 'myfile.vm');
+
+for (var i = 0; i < 10 ; i += 1) {
+  script.runInNewContext(sandbox);
+}
+
+console.log(util.inspect(sandbox));
+
+// { animal: 'cat', count: 12, name: 'kitty' }
+

Note that running untrusted code is a tricky business requiring great care. To prevent accidental +global variable leakage, script.runInNewContext is quite useful, but safely running untrusted code +requires a separate process. +

+ +
+
+
+ + + + + + + + + diff --git a/node-v0.8.14/doc/api/vm.json b/node-v0.8.14/doc/api/vm.json new file mode 100644 index 0000000..d0dbe9d --- /dev/null +++ b/node-v0.8.14/doc/api/vm.json @@ -0,0 +1,177 @@ +{ + "source": "doc/api/vm.markdown", + "modules": [ + { + "textRaw": "Executing JavaScript", + "name": "vm", + "stability": 2, + "stabilityText": "Unstable. See Caveats, below.", + "desc": "

You can access this module with:\n\n

\n
var vm = require('vm');
\n

JavaScript code can be compiled and run immediately or compiled, saved, and run later.\n\n

\n", + "modules": [ + { + "textRaw": "Caveats", + "name": "caveats", + "desc": "

The vm module has many known issues and edge cases. If you run into\nissues or unexpected behavior, please consult\nthe open issues on GitHub.\nSome of the biggest problems are described below.\n\n

\n", + "modules": [ + { + "textRaw": "Sandboxes", + "name": "sandboxes", + "desc": "

The sandbox argument to vm.runInNewContext and vm.createContext,\nalong with the initSandbox argument to vm.createContext, do not\nbehave as one might normally expect and their behavior varies\nbetween different versions of Node.\n\n

\n

The key issue to be aware of is that V8 provides no way to directly\ncontrol the global object used within a context. As a result, while\nproperties of your sandbox object will be available in the context,\nany properties from the prototypes of the sandbox may not be\navailable. Furthermore, the this expression within the global scope\nof the context evaluates to the empty object ({}) instead of to\nyour sandbox.\n\n

\n

Your sandbox's properties are also not shared directly with the script.\nInstead, the properties of the sandbox are copied into the context at\nthe beginning of execution, and then after execution, the properties\nare copied back out in an attempt to propagate any changes.\n\n

\n", + "type": "module", + "displayName": "Sandboxes" + }, + { + "textRaw": "Globals", + "name": "globals", + "desc": "

Properties of the global object, like Array and String, have\ndifferent values inside of a context. This means that common\nexpressions like [] instanceof Array or\nObject.getPrototypeOf([]) === Array.prototype may not produce\nexpected results when used inside of scripts evaluated via the vm module.\n\n

\n

Some of these problems have known workarounds listed in the issues for\nvm on GitHub. for example, Array.isArray works around\nthe example problem with Array.\n\n

\n", + "type": "module", + "displayName": "Globals" + } + ], + "type": "module", + "displayName": "Caveats" + } + ], + "methods": [ + { + "textRaw": "vm.runInThisContext(code, [filename])", + "type": "method", + "name": "runInThisContext", + "desc": "

vm.runInThisContext() compiles code, runs it and returns the result. Running\ncode does not have access to local scope. filename is optional, it's used only\nin stack traces.\n\n

\n

Example of using vm.runInThisContext and eval to run the same code:\n\n

\n
var localVar = 123,\n    usingscript, evaled,\n    vm = require('vm');\n\nusingscript = vm.runInThisContext('localVar = 1;',\n  'myfile.vm');\nconsole.log('localVar: ' + localVar + ', usingscript: ' +\n  usingscript);\nevaled = eval('localVar = 1;');\nconsole.log('localVar: ' + localVar + ', evaled: ' +\n  evaled);\n\n// localVar: 123, usingscript: 1\n// localVar: 1, evaled: 1
\n

vm.runInThisContext does not have access to the local scope, so localVar is unchanged.\neval does have access to the local scope, so localVar is changed.\n\n

\n

In case of syntax error in code, vm.runInThisContext emits the syntax error to stderr\nand throws an exception.\n\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "code" + }, + { + "name": "filename", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "vm.runInNewContext(code, [sandbox], [filename])", + "type": "method", + "name": "runInNewContext", + "desc": "

vm.runInNewContext compiles code, then runs it in sandbox and returns the\nresult. Running code does not have access to local scope. The object sandbox\nwill be used as the global object for code.\nsandbox and filename are optional, filename is only used in stack traces.\n\n

\n

Example: compile and execute code that increments a global variable and sets a new one.\nThese globals are contained in the sandbox.\n\n

\n
var util = require('util'),\n    vm = require('vm'),\n    sandbox = {\n      animal: 'cat',\n      count: 2\n    };\n\nvm.runInNewContext('count += 1; name = "kitty"', sandbox, 'myfile.vm');\nconsole.log(util.inspect(sandbox));\n\n// { animal: 'cat', count: 3, name: 'kitty' }
\n

Note that running untrusted code is a tricky business requiring great care. To prevent accidental\nglobal variable leakage, vm.runInNewContext is quite useful, but safely running untrusted code\nrequires a separate process.\n\n

\n

In case of syntax error in code, vm.runInNewContext emits the syntax error to stderr\nand throws an exception.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "code" + }, + { + "name": "sandbox", + "optional": true + }, + { + "name": "filename", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "vm.runInContext(code, context, [filename])", + "type": "method", + "name": "runInContext", + "desc": "

vm.runInContext compiles code, then runs it in context and returns the\nresult. A (V8) context comprises a global object, together with a set of\nbuilt-in objects and functions. Running code does not have access to local scope\nand the global object held within context will be used as the global object\nfor code.\nfilename is optional, it's used only in stack traces.\n\n

\n

Example: compile and execute code in a existing context.\n\n

\n
var util = require('util'),\n    vm = require('vm'),\n    initSandbox = {\n      animal: 'cat',\n      count: 2\n    },\n    context = vm.createContext(initSandbox);\n\nvm.runInContext('count += 1; name = "CATT"', context, 'myfile.vm');\nconsole.log(util.inspect(context));\n\n// { animal: 'cat', count: 3, name: 'CATT' }
\n

Note that createContext will perform a shallow clone of the supplied sandbox object in order to\ninitialize the global object of the freshly constructed context.\n\n

\n

Note that running untrusted code is a tricky business requiring great care. To prevent accidental\nglobal variable leakage, vm.runInContext is quite useful, but safely running untrusted code\nrequires a separate process.\n\n

\n

In case of syntax error in code, vm.runInContext emits the syntax error to stderr\nand throws an exception.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "code" + }, + { + "name": "context" + }, + { + "name": "filename", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "vm.createContext([initSandbox])", + "type": "method", + "name": "createContext", + "desc": "

vm.createContext creates a new context which is suitable for use as the 2nd argument of a subsequent\ncall to vm.runInContext. A (V8) context comprises a global object together with a set of\nbuild-in objects and functions. The optional argument initSandbox will be shallow-copied\nto seed the initial contents of the global object used by the context.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "initSandbox", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "vm.createScript(code, [filename])", + "type": "method", + "name": "createScript", + "desc": "

createScript compiles code but does not run it. Instead, it returns a\nvm.Script object representing this compiled code. This script can be run\nlater many times using methods below. The returned script is not bound to any\nglobal object. It is bound before each run, just for that run. filename is\noptional, it's only used in stack traces.\n\n

\n

In case of syntax error in code, createScript prints the syntax error to stderr\nand throws an exception.\n\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "code" + }, + { + "name": "filename", + "optional": true + } + ] + } + ] + } + ], + "classes": [ + { + "textRaw": "Class: Script", + "type": "class", + "name": "Script", + "desc": "

A class for running scripts. Returned by vm.createScript.\n\n

\n", + "methods": [ + { + "textRaw": "script.runInThisContext()", + "type": "method", + "name": "runInThisContext", + "desc": "

Similar to vm.runInThisContext but a method of a precompiled Script object.\nscript.runInThisContext runs the code of script and returns the result.\nRunning code does not have access to local scope, but does have access to the global object\n(v8: in actual context).\n\n

\n

Example of using script.runInThisContext to compile code once and run it multiple times:\n\n

\n
var vm = require('vm');\n\nglobalVar = 0;\n\nvar script = vm.createScript('globalVar += 1', 'myfile.vm');\n\nfor (var i = 0; i < 1000 ; i += 1) {\n  script.runInThisContext();\n}\n\nconsole.log(globalVar);\n\n// 1000
\n", + "signatures": [ + { + "params": [] + } + ] + }, + { + "textRaw": "script.runInNewContext([sandbox])", + "type": "method", + "name": "runInNewContext", + "desc": "

Similar to vm.runInNewContext a method of a precompiled Script object.\nscript.runInNewContext runs the code of script with sandbox as the global object and returns the result.\nRunning code does not have access to local scope. sandbox is optional.\n\n

\n

Example: compile code that increments a global variable and sets one, then execute this code multiple times.\nThese globals are contained in the sandbox.\n\n

\n
var util = require('util'),\n    vm = require('vm'),\n    sandbox = {\n      animal: 'cat',\n      count: 2\n    };\n\nvar script = vm.createScript('count += 1; name = "kitty"', 'myfile.vm');\n\nfor (var i = 0; i < 10 ; i += 1) {\n  script.runInNewContext(sandbox);\n}\n\nconsole.log(util.inspect(sandbox));\n\n// { animal: 'cat', count: 12, name: 'kitty' }
\n

Note that running untrusted code is a tricky business requiring great care. To prevent accidental\nglobal variable leakage, script.runInNewContext is quite useful, but safely running untrusted code\nrequires a separate process.\n

\n", + "signatures": [ + { + "params": [ + { + "name": "sandbox", + "optional": true + } + ] + } + ] + } + ] + } + ], + "type": "module", + "displayName": "vm" + } + ] +} diff --git a/node-v0.8.14/doc/api/vm.markdown b/node-v0.8.14/doc/api/vm.markdown new file mode 100644 index 0000000..49df036 --- /dev/null +++ b/node-v0.8.14/doc/api/vm.markdown @@ -0,0 +1,220 @@ +# Executing JavaScript + + Stability: 2 - Unstable. See Caveats, below. + + + +You can access this module with: + + var vm = require('vm'); + +JavaScript code can be compiled and run immediately or compiled, saved, and run later. + +## Caveats + +The `vm` module has many known issues and edge cases. If you run into +issues or unexpected behavior, please consult +[the open issues on GitHub](https://github.com/joyent/node/issues/search?q=vm). +Some of the biggest problems are described below. + +### Sandboxes + +The `sandbox` argument to `vm.runInNewContext` and `vm.createContext`, +along with the `initSandbox` argument to `vm.createContext`, do not +behave as one might normally expect and their behavior varies +between different versions of Node. + +The key issue to be aware of is that V8 provides no way to directly +control the global object used within a context. As a result, while +properties of your `sandbox` object will be available in the context, +any properties from the `prototype`s of the `sandbox` may not be +available. Furthermore, the `this` expression within the global scope +of the context evaluates to the empty object (`{}`) instead of to +your sandbox. + +Your sandbox's properties are also not shared directly with the script. +Instead, the properties of the sandbox are copied into the context at +the beginning of execution, and then after execution, the properties +are copied back out in an attempt to propagate any changes. + +### Globals + +Properties of the global object, like `Array` and `String`, have +different values inside of a context. This means that common +expressions like `[] instanceof Array` or +`Object.getPrototypeOf([]) === Array.prototype` may not produce +expected results when used inside of scripts evaluated via the `vm` module. + +Some of these problems have known workarounds listed in the issues for +`vm` on GitHub. for example, `Array.isArray` works around +the example problem with `Array`. + +## vm.runInThisContext(code, [filename]) + +`vm.runInThisContext()` compiles `code`, runs it and returns the result. Running +code does not have access to local scope. `filename` is optional, it's used only +in stack traces. + +Example of using `vm.runInThisContext` and `eval` to run the same code: + + var localVar = 123, + usingscript, evaled, + vm = require('vm'); + + usingscript = vm.runInThisContext('localVar = 1;', + 'myfile.vm'); + console.log('localVar: ' + localVar + ', usingscript: ' + + usingscript); + evaled = eval('localVar = 1;'); + console.log('localVar: ' + localVar + ', evaled: ' + + evaled); + + // localVar: 123, usingscript: 1 + // localVar: 1, evaled: 1 + +`vm.runInThisContext` does not have access to the local scope, so `localVar` is unchanged. +`eval` does have access to the local scope, so `localVar` is changed. + +In case of syntax error in `code`, `vm.runInThisContext` emits the syntax error to stderr +and throws an exception. + + +## vm.runInNewContext(code, [sandbox], [filename]) + +`vm.runInNewContext` compiles `code`, then runs it in `sandbox` and returns the +result. Running code does not have access to local scope. The object `sandbox` +will be used as the global object for `code`. +`sandbox` and `filename` are optional, `filename` is only used in stack traces. + +Example: compile and execute code that increments a global variable and sets a new one. +These globals are contained in the sandbox. + + var util = require('util'), + vm = require('vm'), + sandbox = { + animal: 'cat', + count: 2 + }; + + vm.runInNewContext('count += 1; name = "kitty"', sandbox, 'myfile.vm'); + console.log(util.inspect(sandbox)); + + // { animal: 'cat', count: 3, name: 'kitty' } + +Note that running untrusted code is a tricky business requiring great care. To prevent accidental +global variable leakage, `vm.runInNewContext` is quite useful, but safely running untrusted code +requires a separate process. + +In case of syntax error in `code`, `vm.runInNewContext` emits the syntax error to stderr +and throws an exception. + +## vm.runInContext(code, context, [filename]) + +`vm.runInContext` compiles `code`, then runs it in `context` and returns the +result. A (V8) context comprises a global object, together with a set of +built-in objects and functions. Running code does not have access to local scope +and the global object held within `context` will be used as the global object +for `code`. +`filename` is optional, it's used only in stack traces. + +Example: compile and execute code in a existing context. + + var util = require('util'), + vm = require('vm'), + initSandbox = { + animal: 'cat', + count: 2 + }, + context = vm.createContext(initSandbox); + + vm.runInContext('count += 1; name = "CATT"', context, 'myfile.vm'); + console.log(util.inspect(context)); + + // { animal: 'cat', count: 3, name: 'CATT' } + +Note that `createContext` will perform a shallow clone of the supplied sandbox object in order to +initialize the global object of the freshly constructed context. + +Note that running untrusted code is a tricky business requiring great care. To prevent accidental +global variable leakage, `vm.runInContext` is quite useful, but safely running untrusted code +requires a separate process. + +In case of syntax error in `code`, `vm.runInContext` emits the syntax error to stderr +and throws an exception. + +## vm.createContext([initSandbox]) + +`vm.createContext` creates a new context which is suitable for use as the 2nd argument of a subsequent +call to `vm.runInContext`. A (V8) context comprises a global object together with a set of +build-in objects and functions. The optional argument `initSandbox` will be shallow-copied +to seed the initial contents of the global object used by the context. + +## vm.createScript(code, [filename]) + +`createScript` compiles `code` but does not run it. Instead, it returns a +`vm.Script` object representing this compiled code. This script can be run +later many times using methods below. The returned script is not bound to any +global object. It is bound before each run, just for that run. `filename` is +optional, it's only used in stack traces. + +In case of syntax error in `code`, `createScript` prints the syntax error to stderr +and throws an exception. + + +## Class: Script + +A class for running scripts. Returned by vm.createScript. + +### script.runInThisContext() + +Similar to `vm.runInThisContext` but a method of a precompiled `Script` object. +`script.runInThisContext` runs the code of `script` and returns the result. +Running code does not have access to local scope, but does have access to the `global` object +(v8: in actual context). + +Example of using `script.runInThisContext` to compile code once and run it multiple times: + + var vm = require('vm'); + + globalVar = 0; + + var script = vm.createScript('globalVar += 1', 'myfile.vm'); + + for (var i = 0; i < 1000 ; i += 1) { + script.runInThisContext(); + } + + console.log(globalVar); + + // 1000 + + +### script.runInNewContext([sandbox]) + +Similar to `vm.runInNewContext` a method of a precompiled `Script` object. +`script.runInNewContext` runs the code of `script` with `sandbox` as the global object and returns the result. +Running code does not have access to local scope. `sandbox` is optional. + +Example: compile code that increments a global variable and sets one, then execute this code multiple times. +These globals are contained in the sandbox. + + var util = require('util'), + vm = require('vm'), + sandbox = { + animal: 'cat', + count: 2 + }; + + var script = vm.createScript('count += 1; name = "kitty"', 'myfile.vm'); + + for (var i = 0; i < 10 ; i += 1) { + script.runInNewContext(sandbox); + } + + console.log(util.inspect(sandbox)); + + // { animal: 'cat', count: 12, name: 'kitty' } + +Note that running untrusted code is a tricky business requiring great care. To prevent accidental +global variable leakage, `script.runInNewContext` is quite useful, but safely running untrusted code +requires a separate process. diff --git a/node-v0.8.14/doc/api/zlib.html b/node-v0.8.14/doc/api/zlib.html new file mode 100644 index 0000000..c6aff93 --- /dev/null +++ b/node-v0.8.14/doc/api/zlib.html @@ -0,0 +1,474 @@ + + + + + Zlib Node.js v0.8.14 Manual & Documentation + + + + + +
+ + + +
+
+ + +
+
+

Node.js v0.8.14 Manual & Documentation

+ +
+
+ + + +
+

Zlib#

+
Stability: 3 - Stable
+

You can access this module with: + +

+
var zlib = require('zlib');
+

This provides bindings to Gzip/Gunzip, Deflate/Inflate, and +DeflateRaw/InflateRaw classes. Each class takes the same options, and +is a readable/writable Stream. + +

+

Examples#

+

Compressing or decompressing a file can be done by piping an +fs.ReadStream into a zlib stream, then into an fs.WriteStream. + +

+
var gzip = zlib.createGzip();
+var fs = require('fs');
+var inp = fs.createReadStream('input.txt');
+var out = fs.createWriteStream('input.txt.gz');
+
+inp.pipe(gzip).pipe(out);
+

Compressing or decompressing data in one step can be done by using +the convenience methods. + +

+
var input = '.................................';
+zlib.deflate(input, function(err, buffer) {
+  if (!err) {
+    console.log(buffer.toString('base64'));
+  }
+});
+
+var buffer = new Buffer('eJzT0yMAAGTvBe8=', 'base64');
+zlib.unzip(buffer, function(err, buffer) {
+  if (!err) {
+    console.log(buffer.toString());
+  }
+});
+

To use this module in an HTTP client or server, use the +accept-encoding +on requests, and the +content-encoding +header on responses. + +

+

Note: these examples are drastically simplified to show +the basic concept. Zlib encoding can be expensive, and the results +ought to be cached. See Memory Usage Tuning +below for more information on the speed/memory/compression +tradeoffs involved in zlib usage. + +

+
// client request example
+var zlib = require('zlib');
+var http = require('http');
+var fs = require('fs');
+var request = http.get({ host: 'izs.me',
+                         path: '/',
+                         port: 80,
+                         headers: { 'accept-encoding': 'gzip,deflate' } });
+request.on('response', function(response) {
+  var output = fs.createWriteStream('izs.me_index.html');
+
+  switch (response.headers['content-encoding']) {
+    // or, just use zlib.createUnzip() to handle both cases
+    case 'gzip':
+      response.pipe(zlib.createGunzip()).pipe(output);
+      break;
+    case 'deflate':
+      response.pipe(zlib.createInflate()).pipe(output);
+      break;
+    default:
+      response.pipe(output);
+      break;
+  }
+});
+
+// server example
+// Running a gzip operation on every request is quite expensive.
+// It would be much more efficient to cache the compressed buffer.
+var zlib = require('zlib');
+var http = require('http');
+var fs = require('fs');
+http.createServer(function(request, response) {
+  var raw = fs.createReadStream('index.html');
+  var acceptEncoding = request.headers['accept-encoding'];
+  if (!acceptEncoding) {
+    acceptEncoding = '';
+  }
+
+  // Note: this is not a conformant accept-encoding parser.
+  // See http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.3
+  if (acceptEncoding.match(/\bdeflate\b/)) {
+    response.writeHead(200, { 'content-encoding': 'deflate' });
+    raw.pipe(zlib.createDeflate()).pipe(response);
+  } else if (acceptEncoding.match(/\bgzip\b/)) {
+    response.writeHead(200, { 'content-encoding': 'gzip' });
+    raw.pipe(zlib.createGzip()).pipe(response);
+  } else {
+    response.writeHead(200, {});
+    raw.pipe(response);
+  }
+}).listen(1337);
+

zlib.createGzip([options])#

+

Returns a new Gzip object with an +options. + +

+

zlib.createGunzip([options])#

+

Returns a new Gunzip object with an +options. + +

+

zlib.createDeflate([options])#

+

Returns a new Deflate object with an +options. + +

+

zlib.createInflate([options])#

+

Returns a new Inflate object with an +options. + +

+

zlib.createDeflateRaw([options])#

+

Returns a new DeflateRaw object with an +options. + +

+

zlib.createInflateRaw([options])#

+

Returns a new InflateRaw object with an +options. + +

+

zlib.createUnzip([options])#

+

Returns a new Unzip object with an +options. + + +

+

Class: zlib.Gzip#

+

Compress data using gzip. + +

+

Class: zlib.Gunzip#

+

Decompress a gzip stream. + +

+

Class: zlib.Deflate#

+

Compress data using deflate. + +

+

Class: zlib.Inflate#

+

Decompress a deflate stream. + +

+

Class: zlib.DeflateRaw#

+

Compress data using deflate, and do not append a zlib header. + +

+

Class: zlib.InflateRaw#

+

Decompress a raw deflate stream. + +

+

Class: zlib.Unzip#

+

Decompress either a Gzip- or Deflate-compressed stream by auto-detecting +the header. + +

+

Convenience Methods#

+ + +

All of these take a string or buffer as the first argument, and call the +supplied callback with callback(error, result). The +compression/decompression engine is created using the default settings +in all convenience methods. To supply different options, use the +zlib classes directly. + +

+

zlib.deflate(buf, callback)#

+

Compress a string with Deflate. + +

+

zlib.deflateRaw(buf, callback)#

+

Compress a string with DeflateRaw. + +

+

zlib.gzip(buf, callback)#

+

Compress a string with Gzip. + +

+

zlib.gunzip(buf, callback)#

+

Decompress a raw Buffer with Gunzip. + +

+

zlib.inflate(buf, callback)#

+

Decompress a raw Buffer with Inflate. + +

+

zlib.inflateRaw(buf, callback)#

+

Decompress a raw Buffer with InflateRaw. + +

+

zlib.unzip(buf, callback)#

+

Decompress a raw Buffer with Unzip. + +

+

Options#

+ + +

Each class takes an options object. All options are optional. (The +convenience methods use the default settings for all options.) + +

+

Note that some options are only +relevant when compressing, and are ignored by the decompression classes. + +

+
    +
  • chunkSize (default: 16*1024)
  • +
  • windowBits
  • +
  • level (compression only)
  • +
  • memLevel (compression only)
  • +
  • strategy (compression only)
  • +
  • dictionary (deflate/inflate only, empty dictionary by default)
  • +
+

See the description of deflateInit2 and inflateInit2 +at http://zlib.net/manual.html#Advanced for more information on these. + +

+

Memory Usage Tuning#

+ + +

From zlib/zconf.h, modified to node's usage: + +

+

The memory requirements for deflate are (in bytes): + +

+
(1 << (windowBits+2)) +  (1 << (memLevel+9))
+

that is: 128K for windowBits=15 + 128K for memLevel = 8 +(default values) plus a few kilobytes for small objects. + +

+

For example, if you want to reduce +the default memory requirements from 256K to 128K, set the options to: + +

+
{ windowBits: 14, memLevel: 7 }
+

Of course this will generally degrade compression (there's no free lunch). + +

+

The memory requirements for inflate are (in bytes) + +

+
1 << windowBits
+

that is, 32K for windowBits=15 (default value) plus a few kilobytes +for small objects. + +

+

This is in addition to a single internal output slab buffer of size +chunkSize, which defaults to 16K. + +

+

The speed of zlib compression is affected most dramatically by the +level setting. A higher level will result in better compression, but +will take longer to complete. A lower level will result in less +compression, but will be much faster. + +

+

In general, greater memory usage options will mean that node has to make +fewer calls to zlib, since it'll be able to process more data in a +single write operation. So, this is another factor that affects the +speed, at the cost of memory usage. + +

+

Constants#

+ + +

All of the constants defined in zlib.h are also defined on +require('zlib'). +In the normal course of operations, you will not need to ever set any of +these. They are documented here so that their presence is not +surprising. This section is taken almost directly from the zlib +documentation. See +

+

http://zlib.net/manual.html#Constants for more details. + +

+

Allowed flush values. + +

+
    +
  • zlib.Z_NO_FLUSH
  • +
  • zlib.Z_PARTIAL_FLUSH
  • +
  • zlib.Z_SYNC_FLUSH
  • +
  • zlib.Z_FULL_FLUSH
  • +
  • zlib.Z_FINISH
  • +
  • zlib.Z_BLOCK
  • +
  • zlib.Z_TREES
  • +
+

Return codes for the compression/decompression functions. Negative +values are errors, positive values are used for special but normal +events. + +

+
    +
  • zlib.Z_OK
  • +
  • zlib.Z_STREAM_END
  • +
  • zlib.Z_NEED_DICT
  • +
  • zlib.Z_ERRNO
  • +
  • zlib.Z_STREAM_ERROR
  • +
  • zlib.Z_DATA_ERROR
  • +
  • zlib.Z_MEM_ERROR
  • +
  • zlib.Z_BUF_ERROR
  • +
  • zlib.Z_VERSION_ERROR
  • +
+

Compression levels. + +

+
    +
  • zlib.Z_NO_COMPRESSION
  • +
  • zlib.Z_BEST_SPEED
  • +
  • zlib.Z_BEST_COMPRESSION
  • +
  • zlib.Z_DEFAULT_COMPRESSION
  • +
+

Compression strategy. + +

+
    +
  • zlib.Z_FILTERED
  • +
  • zlib.Z_HUFFMAN_ONLY
  • +
  • zlib.Z_RLE
  • +
  • zlib.Z_FIXED
  • +
  • zlib.Z_DEFAULT_STRATEGY
  • +
+

Possible values of the data_type field. + +

+
    +
  • zlib.Z_BINARY
  • +
  • zlib.Z_TEXT
  • +
  • zlib.Z_ASCII
  • +
  • zlib.Z_UNKNOWN
  • +
+

The deflate compression method (the only one supported in this version). + +

+
    +
  • zlib.Z_DEFLATED
  • +
+

For initializing zalloc, zfree, opaque. + +

+
    +
  • zlib.Z_NULL
  • +
+ +
+
+
+ + + + + + + + + diff --git a/node-v0.8.14/doc/api/zlib.json b/node-v0.8.14/doc/api/zlib.json new file mode 100644 index 0000000..2a77c72 --- /dev/null +++ b/node-v0.8.14/doc/api/zlib.json @@ -0,0 +1,324 @@ +{ + "source": "doc/api/zlib.markdown", + "modules": [ + { + "textRaw": "Zlib", + "name": "zlib", + "stability": 3, + "stabilityText": "Stable", + "desc": "

You can access this module with:\n\n

\n
var zlib = require('zlib');
\n

This provides bindings to Gzip/Gunzip, Deflate/Inflate, and\nDeflateRaw/InflateRaw classes. Each class takes the same options, and\nis a readable/writable Stream.\n\n

\n

Examples

\n

Compressing or decompressing a file can be done by piping an\nfs.ReadStream into a zlib stream, then into an fs.WriteStream.\n\n

\n
var gzip = zlib.createGzip();\nvar fs = require('fs');\nvar inp = fs.createReadStream('input.txt');\nvar out = fs.createWriteStream('input.txt.gz');\n\ninp.pipe(gzip).pipe(out);
\n

Compressing or decompressing data in one step can be done by using\nthe convenience methods.\n\n

\n
var input = '.................................';\nzlib.deflate(input, function(err, buffer) {\n  if (!err) {\n    console.log(buffer.toString('base64'));\n  }\n});\n\nvar buffer = new Buffer('eJzT0yMAAGTvBe8=', 'base64');\nzlib.unzip(buffer, function(err, buffer) {\n  if (!err) {\n    console.log(buffer.toString());\n  }\n});
\n

To use this module in an HTTP client or server, use the\naccept-encoding\non requests, and the\ncontent-encoding\nheader on responses.\n\n

\n

Note: these examples are drastically simplified to show\nthe basic concept. Zlib encoding can be expensive, and the results\nought to be cached. See Memory Usage Tuning\nbelow for more information on the speed/memory/compression\ntradeoffs involved in zlib usage.\n\n

\n
// client request example\nvar zlib = require('zlib');\nvar http = require('http');\nvar fs = require('fs');\nvar request = http.get({ host: 'izs.me',\n                         path: '/',\n                         port: 80,\n                         headers: { 'accept-encoding': 'gzip,deflate' } });\nrequest.on('response', function(response) {\n  var output = fs.createWriteStream('izs.me_index.html');\n\n  switch (response.headers['content-encoding']) {\n    // or, just use zlib.createUnzip() to handle both cases\n    case 'gzip':\n      response.pipe(zlib.createGunzip()).pipe(output);\n      break;\n    case 'deflate':\n      response.pipe(zlib.createInflate()).pipe(output);\n      break;\n    default:\n      response.pipe(output);\n      break;\n  }\n});\n\n// server example\n// Running a gzip operation on every request is quite expensive.\n// It would be much more efficient to cache the compressed buffer.\nvar zlib = require('zlib');\nvar http = require('http');\nvar fs = require('fs');\nhttp.createServer(function(request, response) {\n  var raw = fs.createReadStream('index.html');\n  var acceptEncoding = request.headers['accept-encoding'];\n  if (!acceptEncoding) {\n    acceptEncoding = '';\n  }\n\n  // Note: this is not a conformant accept-encoding parser.\n  // See http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.3\n  if (acceptEncoding.match(/\\bdeflate\\b/)) {\n    response.writeHead(200, { 'content-encoding': 'deflate' });\n    raw.pipe(zlib.createDeflate()).pipe(response);\n  } else if (acceptEncoding.match(/\\bgzip\\b/)) {\n    response.writeHead(200, { 'content-encoding': 'gzip' });\n    raw.pipe(zlib.createGzip()).pipe(response);\n  } else {\n    response.writeHead(200, {});\n    raw.pipe(response);\n  }\n}).listen(1337);
\n", + "methods": [ + { + "textRaw": "zlib.createGzip([options])", + "type": "method", + "name": "createGzip", + "desc": "

Returns a new Gzip object with an\noptions.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "options", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "zlib.createGunzip([options])", + "type": "method", + "name": "createGunzip", + "desc": "

Returns a new Gunzip object with an\noptions.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "options", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "zlib.createDeflate([options])", + "type": "method", + "name": "createDeflate", + "desc": "

Returns a new Deflate object with an\noptions.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "options", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "zlib.createInflate([options])", + "type": "method", + "name": "createInflate", + "desc": "

Returns a new Inflate object with an\noptions.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "options", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "zlib.createDeflateRaw([options])", + "type": "method", + "name": "createDeflateRaw", + "desc": "

Returns a new DeflateRaw object with an\noptions.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "options", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "zlib.createInflateRaw([options])", + "type": "method", + "name": "createInflateRaw", + "desc": "

Returns a new InflateRaw object with an\noptions.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "options", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "zlib.createUnzip([options])", + "type": "method", + "name": "createUnzip", + "desc": "

Returns a new Unzip object with an\noptions.\n\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "options", + "optional": true + } + ] + } + ] + }, + { + "textRaw": "zlib.deflate(buf, callback)", + "type": "method", + "name": "deflate", + "desc": "

Compress a string with Deflate.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "buf" + }, + { + "name": "callback" + } + ] + } + ] + }, + { + "textRaw": "zlib.deflateRaw(buf, callback)", + "type": "method", + "name": "deflateRaw", + "desc": "

Compress a string with DeflateRaw.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "buf" + }, + { + "name": "callback" + } + ] + } + ] + }, + { + "textRaw": "zlib.gzip(buf, callback)", + "type": "method", + "name": "gzip", + "desc": "

Compress a string with Gzip.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "buf" + }, + { + "name": "callback" + } + ] + } + ] + }, + { + "textRaw": "zlib.gunzip(buf, callback)", + "type": "method", + "name": "gunzip", + "desc": "

Decompress a raw Buffer with Gunzip.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "buf" + }, + { + "name": "callback" + } + ] + } + ] + }, + { + "textRaw": "zlib.inflate(buf, callback)", + "type": "method", + "name": "inflate", + "desc": "

Decompress a raw Buffer with Inflate.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "buf" + }, + { + "name": "callback" + } + ] + } + ] + }, + { + "textRaw": "zlib.inflateRaw(buf, callback)", + "type": "method", + "name": "inflateRaw", + "desc": "

Decompress a raw Buffer with InflateRaw.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "buf" + }, + { + "name": "callback" + } + ] + } + ] + }, + { + "textRaw": "zlib.unzip(buf, callback)", + "type": "method", + "name": "unzip", + "desc": "

Decompress a raw Buffer with Unzip.\n\n

\n", + "signatures": [ + { + "params": [ + { + "name": "buf" + }, + { + "name": "callback" + } + ] + } + ] + } + ], + "classes": [ + { + "textRaw": "Class: zlib.Gzip", + "type": "class", + "name": "zlib.Gzip", + "desc": "

Compress data using gzip.\n\n

\n" + }, + { + "textRaw": "Class: zlib.Gunzip", + "type": "class", + "name": "zlib.Gunzip", + "desc": "

Decompress a gzip stream.\n\n

\n" + }, + { + "textRaw": "Class: zlib.Deflate", + "type": "class", + "name": "zlib.Deflate", + "desc": "

Compress data using deflate.\n\n

\n" + }, + { + "textRaw": "Class: zlib.Inflate", + "type": "class", + "name": "zlib.Inflate", + "desc": "

Decompress a deflate stream.\n\n

\n" + }, + { + "textRaw": "Class: zlib.DeflateRaw", + "type": "class", + "name": "zlib.DeflateRaw", + "desc": "

Compress data using deflate, and do not append a zlib header.\n\n

\n" + }, + { + "textRaw": "Class: zlib.InflateRaw", + "type": "class", + "name": "zlib.InflateRaw", + "desc": "

Decompress a raw deflate stream.\n\n

\n" + }, + { + "textRaw": "Class: zlib.Unzip", + "type": "class", + "name": "zlib.Unzip", + "desc": "

Decompress either a Gzip- or Deflate-compressed stream by auto-detecting\nthe header.\n\n

\n" + } + ], + "miscs": [ + { + "textRaw": "Convenience Methods", + "name": "Convenience Methods", + "type": "misc", + "desc": "

All of these take a string or buffer as the first argument, and call the\nsupplied callback with callback(error, result). The\ncompression/decompression engine is created using the default settings\nin all convenience methods. To supply different options, use the\nzlib classes directly.\n\n

\n" + }, + { + "textRaw": "Options", + "name": "Options", + "type": "misc", + "desc": "

Each class takes an options object. All options are optional. (The\nconvenience methods use the default settings for all options.)\n\n

\n

Note that some options are only\nrelevant when compressing, and are ignored by the decompression classes.\n\n

\n
    \n
  • chunkSize (default: 16*1024)
  • \n
  • windowBits
  • \n
  • level (compression only)
  • \n
  • memLevel (compression only)
  • \n
  • strategy (compression only)
  • \n
  • dictionary (deflate/inflate only, empty dictionary by default)
  • \n
\n

See the description of deflateInit2 and inflateInit2\nat http://zlib.net/manual.html#Advanced for more information on these.\n\n

\n" + }, + { + "textRaw": "Memory Usage Tuning", + "name": "Memory Usage Tuning", + "type": "misc", + "desc": "

From zlib/zconf.h, modified to node's usage:\n\n

\n

The memory requirements for deflate are (in bytes):\n\n

\n
(1 << (windowBits+2)) +  (1 << (memLevel+9))
\n

that is: 128K for windowBits=15 + 128K for memLevel = 8\n(default values) plus a few kilobytes for small objects.\n\n

\n

For example, if you want to reduce\nthe default memory requirements from 256K to 128K, set the options to:\n\n

\n
{ windowBits: 14, memLevel: 7 }
\n

Of course this will generally degrade compression (there's no free lunch).\n\n

\n

The memory requirements for inflate are (in bytes)\n\n

\n
1 << windowBits
\n

that is, 32K for windowBits=15 (default value) plus a few kilobytes\nfor small objects.\n\n

\n

This is in addition to a single internal output slab buffer of size\nchunkSize, which defaults to 16K.\n\n

\n

The speed of zlib compression is affected most dramatically by the\nlevel setting. A higher level will result in better compression, but\nwill take longer to complete. A lower level will result in less\ncompression, but will be much faster.\n\n

\n

In general, greater memory usage options will mean that node has to make\nfewer calls to zlib, since it'll be able to process more data in a\nsingle write operation. So, this is another factor that affects the\nspeed, at the cost of memory usage.\n\n

\n" + }, + { + "textRaw": "Constants", + "name": "Constants", + "type": "misc", + "desc": "

All of the constants defined in zlib.h are also defined on\nrequire('zlib').\nIn the normal course of operations, you will not need to ever set any of\nthese. They are documented here so that their presence is not\nsurprising. This section is taken almost directly from the zlib\ndocumentation. See\n

\n

http://zlib.net/manual.html#Constants for more details.\n\n

\n

Allowed flush values.\n\n

\n
    \n
  • zlib.Z_NO_FLUSH
  • \n
  • zlib.Z_PARTIAL_FLUSH
  • \n
  • zlib.Z_SYNC_FLUSH
  • \n
  • zlib.Z_FULL_FLUSH
  • \n
  • zlib.Z_FINISH
  • \n
  • zlib.Z_BLOCK
  • \n
  • zlib.Z_TREES
  • \n
\n

Return codes for the compression/decompression functions. Negative\nvalues are errors, positive values are used for special but normal\nevents.\n\n

\n
    \n
  • zlib.Z_OK
  • \n
  • zlib.Z_STREAM_END
  • \n
  • zlib.Z_NEED_DICT
  • \n
  • zlib.Z_ERRNO
  • \n
  • zlib.Z_STREAM_ERROR
  • \n
  • zlib.Z_DATA_ERROR
  • \n
  • zlib.Z_MEM_ERROR
  • \n
  • zlib.Z_BUF_ERROR
  • \n
  • zlib.Z_VERSION_ERROR
  • \n
\n

Compression levels.\n\n

\n
    \n
  • zlib.Z_NO_COMPRESSION
  • \n
  • zlib.Z_BEST_SPEED
  • \n
  • zlib.Z_BEST_COMPRESSION
  • \n
  • zlib.Z_DEFAULT_COMPRESSION
  • \n
\n

Compression strategy.\n\n

\n
    \n
  • zlib.Z_FILTERED
  • \n
  • zlib.Z_HUFFMAN_ONLY
  • \n
  • zlib.Z_RLE
  • \n
  • zlib.Z_FIXED
  • \n
  • zlib.Z_DEFAULT_STRATEGY
  • \n
\n

Possible values of the data_type field.\n\n

\n
    \n
  • zlib.Z_BINARY
  • \n
  • zlib.Z_TEXT
  • \n
  • zlib.Z_ASCII
  • \n
  • zlib.Z_UNKNOWN
  • \n
\n

The deflate compression method (the only one supported in this version).\n\n

\n
    \n
  • zlib.Z_DEFLATED
  • \n
\n

For initializing zalloc, zfree, opaque.\n\n

\n
    \n
  • zlib.Z_NULL
  • \n
\n" + } + ], + "type": "module", + "displayName": "Zlib" + } + ] +} diff --git a/node-v0.8.14/doc/api/zlib.markdown b/node-v0.8.14/doc/api/zlib.markdown new file mode 100644 index 0000000..66c9284 --- /dev/null +++ b/node-v0.8.14/doc/api/zlib.markdown @@ -0,0 +1,333 @@ +# Zlib + + Stability: 3 - Stable + +You can access this module with: + + var zlib = require('zlib'); + +This provides bindings to Gzip/Gunzip, Deflate/Inflate, and +DeflateRaw/InflateRaw classes. Each class takes the same options, and +is a readable/writable Stream. + +## Examples + +Compressing or decompressing a file can be done by piping an +fs.ReadStream into a zlib stream, then into an fs.WriteStream. + + var gzip = zlib.createGzip(); + var fs = require('fs'); + var inp = fs.createReadStream('input.txt'); + var out = fs.createWriteStream('input.txt.gz'); + + inp.pipe(gzip).pipe(out); + +Compressing or decompressing data in one step can be done by using +the convenience methods. + + var input = '.................................'; + zlib.deflate(input, function(err, buffer) { + if (!err) { + console.log(buffer.toString('base64')); + } + }); + + var buffer = new Buffer('eJzT0yMAAGTvBe8=', 'base64'); + zlib.unzip(buffer, function(err, buffer) { + if (!err) { + console.log(buffer.toString()); + } + }); + +To use this module in an HTTP client or server, use the +[accept-encoding](http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.3) +on requests, and the +[content-encoding](http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.11) +header on responses. + +**Note: these examples are drastically simplified to show +the basic concept.** Zlib encoding can be expensive, and the results +ought to be cached. See [Memory Usage Tuning](#zlib_memory_usage_tuning) +below for more information on the speed/memory/compression +tradeoffs involved in zlib usage. + + // client request example + var zlib = require('zlib'); + var http = require('http'); + var fs = require('fs'); + var request = http.get({ host: 'izs.me', + path: '/', + port: 80, + headers: { 'accept-encoding': 'gzip,deflate' } }); + request.on('response', function(response) { + var output = fs.createWriteStream('izs.me_index.html'); + + switch (response.headers['content-encoding']) { + // or, just use zlib.createUnzip() to handle both cases + case 'gzip': + response.pipe(zlib.createGunzip()).pipe(output); + break; + case 'deflate': + response.pipe(zlib.createInflate()).pipe(output); + break; + default: + response.pipe(output); + break; + } + }); + + // server example + // Running a gzip operation on every request is quite expensive. + // It would be much more efficient to cache the compressed buffer. + var zlib = require('zlib'); + var http = require('http'); + var fs = require('fs'); + http.createServer(function(request, response) { + var raw = fs.createReadStream('index.html'); + var acceptEncoding = request.headers['accept-encoding']; + if (!acceptEncoding) { + acceptEncoding = ''; + } + + // Note: this is not a conformant accept-encoding parser. + // See http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.3 + if (acceptEncoding.match(/\bdeflate\b/)) { + response.writeHead(200, { 'content-encoding': 'deflate' }); + raw.pipe(zlib.createDeflate()).pipe(response); + } else if (acceptEncoding.match(/\bgzip\b/)) { + response.writeHead(200, { 'content-encoding': 'gzip' }); + raw.pipe(zlib.createGzip()).pipe(response); + } else { + response.writeHead(200, {}); + raw.pipe(response); + } + }).listen(1337); + +## zlib.createGzip([options]) + +Returns a new [Gzip](#zlib_class_zlib_gzip) object with an +[options](#zlib_options). + +## zlib.createGunzip([options]) + +Returns a new [Gunzip](#zlib_class_zlib_gunzip) object with an +[options](#zlib_options). + +## zlib.createDeflate([options]) + +Returns a new [Deflate](#zlib_class_zlib_deflate) object with an +[options](#zlib_options). + +## zlib.createInflate([options]) + +Returns a new [Inflate](#zlib_class_zlib_inflate) object with an +[options](#zlib_options). + +## zlib.createDeflateRaw([options]) + +Returns a new [DeflateRaw](#zlib_class_zlib_deflateraw) object with an +[options](#zlib_options). + +## zlib.createInflateRaw([options]) + +Returns a new [InflateRaw](#zlib_class_zlib_inflateraw) object with an +[options](#zlib_options). + +## zlib.createUnzip([options]) + +Returns a new [Unzip](#zlib_class_zlib_unzip) object with an +[options](#zlib_options). + + +## Class: zlib.Gzip + +Compress data using gzip. + +## Class: zlib.Gunzip + +Decompress a gzip stream. + +## Class: zlib.Deflate + +Compress data using deflate. + +## Class: zlib.Inflate + +Decompress a deflate stream. + +## Class: zlib.DeflateRaw + +Compress data using deflate, and do not append a zlib header. + +## Class: zlib.InflateRaw + +Decompress a raw deflate stream. + +## Class: zlib.Unzip + +Decompress either a Gzip- or Deflate-compressed stream by auto-detecting +the header. + +## Convenience Methods + + + +All of these take a string or buffer as the first argument, and call the +supplied callback with `callback(error, result)`. The +compression/decompression engine is created using the default settings +in all convenience methods. To supply different options, use the +zlib classes directly. + +## zlib.deflate(buf, callback) + +Compress a string with Deflate. + +## zlib.deflateRaw(buf, callback) + +Compress a string with DeflateRaw. + +## zlib.gzip(buf, callback) + +Compress a string with Gzip. + +## zlib.gunzip(buf, callback) + +Decompress a raw Buffer with Gunzip. + +## zlib.inflate(buf, callback) + +Decompress a raw Buffer with Inflate. + +## zlib.inflateRaw(buf, callback) + +Decompress a raw Buffer with InflateRaw. + +## zlib.unzip(buf, callback) + +Decompress a raw Buffer with Unzip. + +## Options + + + +Each class takes an options object. All options are optional. (The +convenience methods use the default settings for all options.) + +Note that some options are only +relevant when compressing, and are ignored by the decompression classes. + +* chunkSize (default: 16*1024) +* windowBits +* level (compression only) +* memLevel (compression only) +* strategy (compression only) +* dictionary (deflate/inflate only, empty dictionary by default) + +See the description of `deflateInit2` and `inflateInit2` +at for more information on these. + +## Memory Usage Tuning + + + +From `zlib/zconf.h`, modified to node's usage: + +The memory requirements for deflate are (in bytes): + + (1 << (windowBits+2)) + (1 << (memLevel+9)) + +that is: 128K for windowBits=15 + 128K for memLevel = 8 +(default values) plus a few kilobytes for small objects. + +For example, if you want to reduce +the default memory requirements from 256K to 128K, set the options to: + + { windowBits: 14, memLevel: 7 } + +Of course this will generally degrade compression (there's no free lunch). + +The memory requirements for inflate are (in bytes) + + 1 << windowBits + +that is, 32K for windowBits=15 (default value) plus a few kilobytes +for small objects. + +This is in addition to a single internal output slab buffer of size +`chunkSize`, which defaults to 16K. + +The speed of zlib compression is affected most dramatically by the +`level` setting. A higher level will result in better compression, but +will take longer to complete. A lower level will result in less +compression, but will be much faster. + +In general, greater memory usage options will mean that node has to make +fewer calls to zlib, since it'll be able to process more data in a +single `write` operation. So, this is another factor that affects the +speed, at the cost of memory usage. + +## Constants + + + +All of the constants defined in zlib.h are also defined on +`require('zlib')`. +In the normal course of operations, you will not need to ever set any of +these. They are documented here so that their presence is not +surprising. This section is taken almost directly from the [zlib +documentation](http://zlib.net/manual.html#Constants). See + for more details. + +Allowed flush values. + +* `zlib.Z_NO_FLUSH` +* `zlib.Z_PARTIAL_FLUSH` +* `zlib.Z_SYNC_FLUSH` +* `zlib.Z_FULL_FLUSH` +* `zlib.Z_FINISH` +* `zlib.Z_BLOCK` +* `zlib.Z_TREES` + +Return codes for the compression/decompression functions. Negative +values are errors, positive values are used for special but normal +events. + +* `zlib.Z_OK` +* `zlib.Z_STREAM_END` +* `zlib.Z_NEED_DICT` +* `zlib.Z_ERRNO` +* `zlib.Z_STREAM_ERROR` +* `zlib.Z_DATA_ERROR` +* `zlib.Z_MEM_ERROR` +* `zlib.Z_BUF_ERROR` +* `zlib.Z_VERSION_ERROR` + +Compression levels. + +* `zlib.Z_NO_COMPRESSION` +* `zlib.Z_BEST_SPEED` +* `zlib.Z_BEST_COMPRESSION` +* `zlib.Z_DEFAULT_COMPRESSION` + +Compression strategy. + +* `zlib.Z_FILTERED` +* `zlib.Z_HUFFMAN_ONLY` +* `zlib.Z_RLE` +* `zlib.Z_FIXED` +* `zlib.Z_DEFAULT_STRATEGY` + +Possible values of the data_type field. + +* `zlib.Z_BINARY` +* `zlib.Z_TEXT` +* `zlib.Z_ASCII` +* `zlib.Z_UNKNOWN` + +The deflate compression method (the only one supported in this version). + +* `zlib.Z_DEFLATED` + +For initializing zalloc, zfree, opaque. + +* `zlib.Z_NULL` diff --git a/node-v0.8.14/doc/api_assets/sh.css b/node-v0.8.14/doc/api_assets/sh.css new file mode 100644 index 0000000..7022e19 --- /dev/null +++ b/node-v0.8.14/doc/api_assets/sh.css @@ -0,0 +1,24 @@ +.sh_sourceCode { + font-weight: normal; + font-style: normal; +} + +.sh_sourceCode .sh_symbol, +.sh_sourceCode .sh_cbracket { + color: #333; +} + +.sh_sourceCode .sh_keyword { + color: #c96; +} + +.sh_sourceCode .sh_string, +.sh_sourceCode .sh_regexp, +.sh_sourceCode .sh_number, +.sh_sourceCode .sh_specialchar { + color: #690; +} + +.sh_sourceCode .sh_comment { + color: #666; +} diff --git a/node-v0.8.14/doc/api_assets/style.css b/node-v0.8.14/doc/api_assets/style.css new file mode 100644 index 0000000..5523984 --- /dev/null +++ b/node-v0.8.14/doc/api_assets/style.css @@ -0,0 +1,518 @@ +/*--------------------- Layout and Typography ----------------------------*/ +html { + -webkit-font-smoothing: antialiased; +} + +body { + font-family: "Lucida Grande", "Lucida Sans Unicode", "Lucida Sans", Verdana, Tahoma, sans-serif; + font-size: 14px; + line-height: 180%; + color: black; + background-color: white; + margin: 0; padding: 49px 0 0 0; + border-top: 6px #8CC84B solid; +} + +a { + color: #480; + text-decoration: underline; +} + +a:visited { + color: #46483e; + text-decoration: underline; +} + +a:hover, +a:focus { + text-decoration: none; +} + +code a:hover { + background: none; + color: #b950b7; +} + +#changelog #gtoc { + display: none; +} + +#gtoc p { + margin: 0; + font-size: 18px; + line-height: 30px; +} + +#gtoc a { + font-family: Georgia, FreeSerif, Times, serif; + text-decoration: none; + color: #46483e; +} + +#gtoc a:hover { + color: #669900; + text-decoration: underline; +} + +.notice { + display: block; + padding: 1em; + margin: 1.4667em 0 2.9334em; + background: #FFF6BF; + color: #514721; + border: 1px solid #FFD324; +} + +.notice p { + margin: 0; +} + +ul.plain { + list-style: none; +} + +abbr { + border-bottom: 1px dotted #454545; +} + +p { + margin: 0 0 1.4667em 0; + position: relative; + text-rendering: optimizeLegibility; +} + +.apidoc #apicontent p, +.apidoc #apicontent li { + font-size: 15px; + line-height: 22px; + color: #000; + font-family: Georgia, FreeSerif, Times, serif; +} + +ol, ul, dl { + margin: 0 0 1em 0; + padding: 0; +} + +ol ul, ol ol, ol dl, +ul ul, ul ol, ul dl, +dl ul, dl ol, dl dl { + margin-bottom: 0; +} + +ol p:first-child, +ul p:first-child, +dl p:first-child { + margin-bottom: 0; +} + +ul, ol { + margin-left: 2em; +} + +dl dt { + position: relative; + margin: 1.5em 0 0; +} + +dl dd { + position: relative; + margin: 0 1em 0; +} + +dd + dt.pre { + margin-top: 1.6em; +} + +h1, h2, h3, h4, h5, h6 { + font-family: Helvetica, Arial, sans-serif; + color: #000; + text-rendering: optimizeLegibility; + position: relative; +} + +header h1 { + font-family: Georgia, FreeSerif, Times, serif; + font-size: 30px; + font-weight: normal; + line-height: 36px; + color: #480; + margin: 15px 0 11px; +} + +h1 { + font-size: 29px; + line-height: 33px; + margin: 2em 0 15px; +} + +#toc + h1 { + margin-top: 1em; + padding-top: 0; +} + +h2 { + font-size: 1.4em; + line-height: 1.0909em; + margin: 1.5em 0 0.5em; +} + +h2 + h2 { + margin: 0 0 0.5em; +} + +h3 { + font-size: 1.3em; + line-height: 1.1282em; + margin: 2.2em 0 0.5em; +} + +h3 + h3 { + margin: 0 0 0.5em; +} + +h2, h3, h4 { + position: relative; + padding-right: 40px; +} + +h1 span, h2 span, h3 span, h4 span { + font-size: 25px; + position: absolute; + display: block; + top: 0; + right: 0; + opacity: 0.3; +} + +h1 span:hover, h2 span:hover, h3 span:hover, h4 span:hover { + opacity: 1; +} + +h1 span a, h2 span a, h3 span a, h4 span a { + font-size: 0.8em; + color: #000; + text-decoration: none; + font-family: Helvetica, Arial, sans-serif; + font-weight: bold; +} + +h1 span a.top, h2 span a.top, h3 span a.top, h4 span a.top { + /* XXX Get an image and clean up these two links + * so that they look nice next to one another. + * http://www.chrisglass.com/work/nodejs/website/v05/docs.html + * -isaacs + */ + display: none; +} + +h5 { + font-size: 1.125em; + line-height: 1.4em; +} + +h6 { + font-size: 1em; + line-height: 1.4667em; +} + +pre, tt, code { + font-size: 14px; + line-height: 1.5438em; + font-family: Monaco, Consolas, "Lucida Console", monospace; + margin: 0; padding: 0; +} + +.pre { + font-family: Monaco, Consolas, "Lucida Console", monospace; + line-height: 1.5438em; + font-size: 0.95em; +} + +pre { + padding: 1em 1.6em 1em 1.2em; + vertical-align: top; + background: #f8f8f8; + border: 1px solid #e8e8e8; + border-width: 1px 1px 1px 6px; + margin: -0.5em 0 1.1em; + overflow-x: auto; +} + +pre + h3 { + margin-top: 2.225em; +} + +code.pre { + white-space: pre; +} + +#intro { + width: 775px; + margin: 0 auto; + text-align: center; + color: #d2d8ba; + /* preload platform-icons.png */ + background-image: url(http://nodejs.org/images/platform-icons.png); + background-repeat: no-repeat; + background-position: -999em -999em; +} + +#intro.interior #logo { + margin-left: -298px; + border: 0; +} + +hr { + background: none; + border: medium none; + border-bottom: 1px solid #ccc; + margin: 1em 0; +} + +#toc { + font-size: 15px; + line-height: 1.5em; + line-height: 22px; + padding-top: 4px; +} + +#toc h2 { + font-size: 15px; + line-height: 21px; + margin: 0 0 0.5em; +} + +#toc h2 a { + float: right; +} + +#toc hr { + margin: 1em 0 2em; +} + +#toc ul, +#api-section-index #apicontent ul li, +#api-section-index #apicontent ul { + font-family: Georgia, FreeSerif, Times, serif; + color: #666 !important; +} + +#toc ul a { + text-decoration: none; + border-bottom: 1px dotted #480; +} + +#toc ul a:hover, +#toc ul a:focus { + border-bottom: 1px dotted #fff; + color: #000; +} + +p tt, +p code { + background: #f8f8ff; + border: 1px solid #dedede; + padding: 0 0.2em; +} + +#content { + width: 953px; + margin: 0 auto; + overflow: visible; + clear: both; + display: block; +} + +#column1.interior { + width: 749px; + float: right; + padding-top: 7px; + padding-top: 11px; + font-size: 18px; +} + +#column2.interior { + width: 140px; + float: left; + margin-top: -55px; + overflow: visible; +} + +#column2.interior ul { + margin-left: 0; +} + +#column2.interior li { + list-style-type: none; +} + +#column2.interior li a { + display: block; + padding: 0 0 0 35px; + color: #878b78; + text-transform: uppercase; + text-decoration: none; + font-size: 11px; + line-height: 23px; +} + +#column2.interior li a.home { background: url(http://nodejs.org/images/icons-interior.png) no-repeat -156px 3px; } +#column2.interior li a.download { background: url(http://nodejs.org/images/icons-interior.png) no-repeat -156px -21px; } +#column2.interior li a.about { background: url(http://nodejs.org/images/icons-interior.png) no-repeat -156px -45px; } +#column2.interior li a.npm { background: url(http://nodejs.org/images/icons-interior.png) no-repeat -156px -69px; } +#column2.interior li a.docs { background: url(http://nodejs.org/images/icons-interior.png) no-repeat -156px -93px; } +#column2.interior li a.blog { background: url(http://nodejs.org/images/icons-interior.png) no-repeat -156px -117px; } +#column2.interior li a.community { background: url(http://nodejs.org/images/icons-interior.png) no-repeat -156px -141px; } +#column2.interior li a.logos { background: url(http://nodejs.org/images/icons-interior.png) no-repeat -156px -165px; } +#column2.interior li a.jobs { background: url(http://nodejs.org/images/icons-interior.png) no-repeat -156px -189px; } + +#column2.interior li a.home.current { background-position: 2px 3px; } +#column2.interior li a.download.current { background-position: 2px -21px; } +#column2.interior li a.about.current { background-position: 2px -45px; } +#column2.interior li a.npm.current { background-position: 2px -69px; } +#column2.interior li a.docs.current { background-position: 2px -93px; } +#column2.interior li a.blog.current { background-position: 2px -117px; } +#column2.interior li a.community.current { background-position: 2px -141px; } +#column2.interior li a.logos.current { background-position: 2px -165px; } +#column2.interior li a.jobs.current { background-position: 2px -189px; } + +#column2.interior li a.home:hover { background-position: -331px 3px; } +#column2.interior li a.download:hover { background-position: -331px -21px; } +#column2.interior li a.about:hover { background-position: -331px -45px; } +#column2.interior li a.npm:hover { background-position: -331px -69px; } +#column2.interior li a.docs:hover { background-position: -331px -93px; } +#column2.interior li a.blog:hover { background-position: -331px -117px; } +#column2.interior li a.community:hover { background-position: -331px -141px; } +#column2.interior li a.logos:hover { background-position: -331px -165px; } +#column2.interior li a.jobs:hover { background-position: -331px -189px; } + +#column2.interior li a.current { + color: #8cc84b; + font-weight: bold; +} + +#column2.interior li a:hover { + color: #000000; + text-decoration: none; +} + +#column2.interior li + li { + border-top: 1px solid #c1c7ac; +} + +#column2.interior p.twitter { + padding-top: 20px; +} + +#column2.interior p.twitter a { + background: url(http://nodejs.org/images/twitter-bird.png) no-repeat 0 4px; + padding-left: 37px; + text-decoration: none; +} + +#column2.interior p.twitter a:hover { + text-decoration: underline; +} + +a.totop { + font-family: "Lucida Grande", "Lucida Sans Unicode", "Lucida Sans", Verdana, Tahoma, sans-serif; + font-weight: bold; + text-indent: -9999999px; + background: url(http://nodejs.org/images/anchor.png) no-repeat top left; + margin-right: 7px; + display: block; + width: 13px; + border-bottom: 1px solid #cccccc; +} + +a.anchor { + font-family: "Lucida Grande", "Lucida Sans Unicode", "Lucida Sans", Verdana, Tahoma, sans-serif; + font-weight: bold; + text-indent: -9999999px; + background: url(http://nodejs.org/images/anchor.png) no-repeat top right; + display: block; + width: 13px; + border-bottom: 1px solid #cccccc; +} + +#footer { + width: 942px; + margin: 150px auto 55px auto; + padding: 0; +} + +#footer p { + font-size: 11px; + line-height: 1em; + padding: 0 0 0 195px; + color: #666; +} + +#footer p, +#footer li { + font-family: "Lucida Grande", "Lucida Sans Unicode", "Lucida Sans", Verdana, Tahoma, sans-serif; +} + +#footer a { + text-decoration: none; + border: none; + color: #480; +} + +#footer a:hover { + color: #000; +} + +#footer p a { + border-bottom: 1px dotted #480; + color: #878b78; +} + +#footer ul { + background: url(http://nodejs.org/images/footer-logo-alt.png) left 17px no-repeat; + padding: 23px 0 0 195px; + height: 26px; + margin-left: -1px; + border-top: 1px solid #626557; +} + +#footer ul li { + list-style-type: none; + float: left; + font-size: 12px; + margin: 0 !important; + padding: 0; + height: 12px; +} + +#footer ul li a { + margin: 0; + padding: 0 6px 0 0; + display: block; + height: 12px; + line-height: 12px; +} + +#footer ul li + li { + margin-left: 3px; +} + +#footer ul li + li a { + padding: 0 6px 0 6px; + border-left: 1px solid #878b78; +} + +#footer ul li a.twitter { + background: url(http://nodejs.org/images/twitter-bird.png) no-repeat 5px 0px; + padding-left: 25px; +} + +/* simpler clearfix */ +.clearfix:after { + content: "."; + display: block; + height: 0; + clear: both; + visibility: hidden; +} diff --git a/node-v0.8.14/doc/blog.html b/node-v0.8.14/doc/blog.html new file mode 100644 index 0000000..153e3ba --- /dev/null +++ b/node-v0.8.14/doc/blog.html @@ -0,0 +1,240 @@ + + + + + + + + + + <%= title || "Node.js Blog" %> + + + + +
+ +
+ +
+
+ + + +
+ +
+

<%- title %>

+ <% if (typeof post !== 'undefined') { + // just one post on this page + %> +

<%- + post.date.toUTCString().replace(/ GMT$/, '') + ' UTC' + + (post.author ? ' - ' + post.author : '') + + (post.category ? ' - ' + + post.category + '' : '') + %>

+ + <%- post.content %> + +

Please post feedback and comments on + the Node.JS + user mailing list.
+ Please post bugs and feature requests on + the Node.JS + github repository.

+ + <% + if (post.next || post.prev) { + if (post.prev) { + %>

← <%= + post.prev.title + %>

+ <% + } + if (post.next) { + %>

<%= + post.next.title + %> →

+ <% + } + } + } else { // not single post page + if (paginated && total > 1 ) { + if (page > 0) { + // add 1 to all of the displayed numbers, because + // humans are not zero-indexed like they ought to be. + %> +

+ ← Page <%- page %> +

+ <% + } + if (page < total - 1) { %> +

+ Page <%- page + 2 %> → +

+ <% + } + } + + posts.forEach(function(post) { + %> +
+

+ +

<%- + post.date.toUTCString().replace(/ GMT$/, '') + ' UTC' + + (post.author ? ' - ' + post.author : '') + + (post.category ? ' - ' + + post.category + '' : '') + %>

+ + <%- post.content %> +
+ <% + }); + + if (paginated && total > 1 ) { + if (page > 0) { + // add 1 to all of the displayed numbers, because + // humans are not zero-indexed like they ought to be. + %> +

+ ← Page <%- page %> +

+ <% + } + if (page < total - 1) { %> +

+ Page <%- page + 2 %> → +

+ <% + } + } // pagination + } // not a single post + %> +
+
+ + + + + + + + + diff --git a/node-v0.8.14/doc/blog/README.md b/node-v0.8.14/doc/blog/README.md new file mode 100644 index 0000000..7d37706 --- /dev/null +++ b/node-v0.8.14/doc/blog/README.md @@ -0,0 +1,28 @@ +title: README.md +status: private + +# How This Blog Works + +Each `.md` file in this folder structure is a blog post. It has a +few headers and a markdown body. (HTML is allowed in the body as well.) + +The relevant headers are: + +1. title +2. author +3. status: Only posts with a status of "publish" are published. +4. category: The "release" category is treated a bit specially. +5. version: Only relevant for "release" category. +6. date +7. slug: The bit that goes on the url. Must be unique, will be + generated from the title and date if missing. + +Posts in the "release" category are only shown in the main lists when +they are the most recent release for that version family. The stable +branch supercedes its unstable counterpart, so the presence of a `0.8.2` +release notice will cause `0.7.10` to be hidden, but `0.6.19` would +be unaffected. + +The folder structure in the blog source does not matter. Organize files +here however makes sense. The metadata will be sorted out in the build +later. diff --git a/node-v0.8.14/doc/blog/Uncategorized/an-easy-way-to-build-scalable-network-programs.md b/node-v0.8.14/doc/blog/Uncategorized/an-easy-way-to-build-scalable-network-programs.md new file mode 100644 index 0000000..a555ac6 --- /dev/null +++ b/node-v0.8.14/doc/blog/Uncategorized/an-easy-way-to-build-scalable-network-programs.md @@ -0,0 +1,16 @@ +title: An Easy Way to Build Scalable Network Programs +author: ryandahl +date: Tue Oct 04 2011 15:39:56 GMT-0700 (PDT) +status: publish +category: Uncategorized +slug: an-easy-way-to-build-scalable-network-programs + +Suppose you're writing a web server which does video encoding on each file upload. Video encoding is very much compute bound. Some recent blog posts suggest that Node.js would fail miserably at this. + +Using Node does not mean that you have to write a video encoding algorithm in JavaScript (a language without even 64 bit integers) and crunch away in the main server event loop. The suggested approach is to separate the I/O bound task of receiving uploads and serving downloads from the compute bound task of video encoding. In the case of video encoding this is accomplished by forking out to ffmpeg. Node provides advanced means of asynchronously controlling subprocesses for work like this. + +It has also been suggested that Node does not take advantage of multicore machines. Node has long supported load-balancing connections over multiple processes in just a few lines of code - in this way a Node server will use the available cores. In coming releases we'll make it even easier: just pass --balance on the command line and Node will manage the cluster of processes. + +Node has a clear purpose: provide an easy way to build scalable network programs. It is not a tool for every problem. Do not write a ray tracer with Node. Do not write a web browser with Node. Do however reach for Node if tasked with writing a DNS server, DHCP server, or even a video encoding server. + +By relying on the kernel to schedule and preempt computationally expensive tasks and to load balance incoming connections, Node appears less magical than server platforms that employ userland scheduling. So far, our focus on simplicity and transparency has paid off: the number of success stories from developers and corporations who are adopting the technology continues to grow. diff --git a/node-v0.8.14/doc/blog/Uncategorized/development-environment.md b/node-v0.8.14/doc/blog/Uncategorized/development-environment.md new file mode 100644 index 0000000..e6015e0 --- /dev/null +++ b/node-v0.8.14/doc/blog/Uncategorized/development-environment.md @@ -0,0 +1,25 @@ +title: Development Environment +author: ryandahl +date: Mon Apr 04 2011 20:16:27 GMT-0700 (PDT) +status: publish +category: Uncategorized +slug: development-environment + +If you're compiling a software package because you need a particular version (e.g. the latest), then it requires a little bit more maintenance than using a package manager like dpkg. Software that you compile yourself should *not* go into /usr, it should go into your home directory. This is part of being a software developer. + +One way of doing this is to install everything into $HOME/local/$PACKAGE. Here is how I install node on my machine:
./configure --prefix=$HOME/local/node-v0.4.5 && make install
+ +To have my paths automatically set I put this inside my $HOME/.zshrc:
PATH="$HOME/local/bin:/opt/local/bin:/usr/bin:/sbin:/bin"
+LD_LIBRARY_PATH="/opt/local/lib:/usr/local/lib:/usr/lib"
+for i in $HOME/local/*; do
+  [ -d $i/bin ] && PATH="${i}/bin:${PATH}"
+  [ -d $i/sbin ] && PATH="${i}/sbin:${PATH}"
+  [ -d $i/include ] && CPATH="${i}/include:${CPATH}"
+  [ -d $i/lib ] && LD_LIBRARY_PATH="${i}/lib:${LD_LIBRARY_PATH}"
+  [ -d $i/lib/pkgconfig ] && PKG_CONFIG_PATH="${i}/lib/pkgconfig:${PKG_CONFIG_PATH}"
+  [ -d $i/share/man ] && MANPATH="${i}/share/man:${MANPATH}"
+done
+ +Node is under sufficiently rapid development that everyone should be compiling it themselves. A corollary of this is that npm (which should be installed alongside Node) does not require root to install packages. + +CPAN and RubyGems have blurred the lines between development tools and system package managers. With npm we wish to draw a clear line: it is not a system package manager. It is not for installing firefox or ffmpeg or OpenSSL; it is for rapidly downloading, building, and setting up Node packages. npm is a development tool. When a program written in Node becomes sufficiently mature it should be distributed as a tarball, .deb, .rpm, or other package system. It should not be distributed to end users with npm. diff --git a/node-v0.8.14/doc/blog/Uncategorized/evolving-the-node-js-brand.md b/node-v0.8.14/doc/blog/Uncategorized/evolving-the-node-js-brand.md new file mode 100644 index 0000000..e631a22 --- /dev/null +++ b/node-v0.8.14/doc/blog/Uncategorized/evolving-the-node-js-brand.md @@ -0,0 +1,34 @@ +title: Evolving the Node.js Brand +author: Emily Tanaka-Delgado +date: Mon Jul 11 2011 12:02:45 GMT-0700 (PDT) +status: publish +category: Uncategorized +slug: evolving-the-node-js-brand + +To echo Node’s evolutionary nature, we have refreshed the identity to help mark an exciting time for developers, businesses and users who benefit from the pioneering technology. + +Building a brand + +We began exploring elements to express Node.js and jettisoned preconceived notions about what we thought Node should look like, and focused on what Node is: kinetic,connectedscalablemodularmechanical and organic. Working with designer Chris Glass, our explorations emphasized Node's dynamism and formed a visual language based on structure, relationships and interconnectedness. + + + +Inspired by process visualization, we discovered pattern, form, and by relief, the hex shape. The angled infrastructure encourages energy to move through the letterforms. + + + +This language can expand into the organic network topography of Node or distill down into a single hex connection point. + +This scaling represents the dynamic nature of Node in a simple, distinct manner. + + + +We look forward to exploring this visual language as the technology charges into a very promising future. + + + +We hope you'll have fun using it. + +To download the new logo, visit nodejs.org/logos. + + diff --git a/node-v0.8.14/doc/blog/Uncategorized/growing-up.md b/node-v0.8.14/doc/blog/Uncategorized/growing-up.md new file mode 100644 index 0000000..10e1d58 --- /dev/null +++ b/node-v0.8.14/doc/blog/Uncategorized/growing-up.md @@ -0,0 +1,12 @@ +title: Growing up +author: ryandahl +date: Thu Dec 15 2011 11:59:15 GMT-0800 (PST) +status: publish +category: Uncategorized +slug: growing-up + +This week Microsoft announced support for Node in Windows Azure, their cloud computing platform. For the Node core team and the community, this is an important milestone. We've worked hard over the past six months reworking Node's machinery to support IO completion ports and Visual Studio to provide a good native port to Windows. The overarching goal of the port was to expand our user base to the largest number of developers. Happily, this has paid off in the form of being a first class citizen on Azure. Many users who would have never used Node as a pure unix tool are now up and running on the Windows platform. More users translates into a deeper and better ecosystem of modules, which makes for a better experience for everyone. + +We also redesigned our website - something that we've put off for a long time because we felt that Node was too nascent to dedicate marketing to it. But now that we have binary distributions for Macintosh and Windows, have bundled npm, and are serving millions of users at various companies, we felt ready to indulge in a new website and share of a few of our success stories on the home page. + +Work is on-going. We continue to improve the software, making performance improvements and adding isolate support, but Node is growing up. diff --git a/node-v0.8.14/doc/blog/Uncategorized/jobs-nodejs-org.md b/node-v0.8.14/doc/blog/Uncategorized/jobs-nodejs-org.md new file mode 100644 index 0000000..fe20efe --- /dev/null +++ b/node-v0.8.14/doc/blog/Uncategorized/jobs-nodejs-org.md @@ -0,0 +1,14 @@ +title: jobs.nodejs.org +author: ryandahl +date: Thu Mar 24 2011 23:05:22 GMT-0700 (PDT) +status: publish +category: Uncategorized +slug: jobs-nodejs-org + +We are starting an official jobs board for Node. There are two goals for this + +1. Promote the small emerging economy around this platform by having a central space for employers to find Node programmers. + +2. Make some money. We work hard to build this platform and taking a small tax for job posts seems a like reasonable "tip jar". + +jobs.nodejs.org diff --git a/node-v0.8.14/doc/blog/Uncategorized/ldapjs-a-reprise-of-ldap.md b/node-v0.8.14/doc/blog/Uncategorized/ldapjs-a-reprise-of-ldap.md new file mode 100644 index 0000000..7174e2b --- /dev/null +++ b/node-v0.8.14/doc/blog/Uncategorized/ldapjs-a-reprise-of-ldap.md @@ -0,0 +1,84 @@ +title: ldapjs: A reprise of LDAP +author: mcavage +date: Thu Sep 08 2011 14:25:43 GMT-0700 (PDT) +status: publish +category: Uncategorized +slug: ldapjs-a-reprise-of-ldap + +This post has been about 10 years in the making. My first job out of college was at IBM working on the Tivoli Directory Server, and at the time I had a preconceived notion that working on anything related to Internet RFCs was about as hot as you could get. I spent a lot of time back then getting "down and dirty" with everything about LDAP: the protocol, performance, storage engines, indexing and querying, caching, customer use cases and patterns, general network server patterns, etc. Basically, I soaked up as much as I possibly could while I was there. On top of that, I listened to all the "gray beards" tell me about the history of LDAP, which was a bizarre marriage of telecommunications conglomerates and graduate students. The point of this blog post is to give you a crash course in LDAP, and explain what makes ldapjs different. Allow me to be the gray beard for a bit... +

What is LDAP and where did it come from?

+ +Directory services were largely pioneered by the telecommunications companies (e.g., AT&T) to allow fast information retrieval of all the crap you'd expect would be in a telephone book and directory. That is, given a name, or an address, or an area code, or a number, or a foo support looking up customer records, billing information, routing information, etc. The efforts of several telcos came to exist in the X.500 standard(s). An X.500 directory is one of the most complicated beasts you can possibly imagine, but on a high note, there's +probably not a thing you can imagine in a directory service that wasn't thought of in there. It is literally the kitchen sink. Oh, and it doesn't run over IP (it's actually on the OSI model). + +Several years after X.500 had been deployed (at telcos, academic institutions, etc.), it became clear that the Internet was "for real." LDAP, the "Lightweight Directory Access Protocol," was invented to act purely as an IP-accessible gateway to an X.500 directory. + +At some point in the early 90's, a graduate student at the University of Michigan (with some help) cooked up the "grandfather" implementation of the LDAP protocol, which wasn't actually a "gateway," but rather a stand-alone implementation of LDAP. Said implementation, like many things at the time, was a process-per-connection concurrency model, and had "backends" (aka storage engine) for the file system and the Unix DB API. At some point the Berkeley Database (BDB) was put in, and still remains the de facto storage engine for most LDAP directories. + +Ok, so some a graduate student at UM wrote an LDAP server that wasn't a gateway. So what? Well, that UM code base turns out to be the thing that pretty much every vendor did a source license for. Those graduate students went off to Netscape later in the 90's, and largely dominated the market of LDAP middleware until Active Directory came along many years later (as far as I know, Active Directory is "from scratch", since while it's "almost" LDAP, it's different in a lot of ways). That Netscape code base was further bought and sold over the years to iPlanet, Sun Microsystems, and Red Hat (I'm probably missing somebody in that chain). It now lives in the Fedora umbrella as '389 Directory Server.' Probably the most popular fork of that code base now is OpenLDAP. + +IBM did the same thing, and the Directory Server I worked on was a fork of the UM code too, but it heavily diverged from the Netscape branches. The divergence was primarily due to: (1) backing to DB2 as opposed to BDB, and (2) needing to run on IBM's big iron like OS/400 and Z series mainframes. + +Macro point is that there have actually been very few "fresh" implementations of LDAP, and it gets a pretty bad reputation because at the end of the day you've got 20 years of "bolt-ons" to grad student code. Oh, and it was born out of ginormous telcos, so of course the protocol is overly complex. + +That said, while there certainly is some wacky stuff in the LDAP protocol itself, it really suffered from poor and buggy implementations more than the fact that LDAP itself was fundamentally flawed. As engine yard pointed out a few years back, you can think of LDAP as the original NoSQL store. +

LDAP: The Good Parts

+ +So what's awesome about LDAP? Since it's a directory system it maintains a hierarchy of your data, which as an information management pattern aligns +with _a lot_ of use case (the quintessential example is white pages for people in your company, but subscriptions to SaaS applications, "host groups" +for tracking machines/instances, physical goods tracking, etc., all have use cases that fit that organization scheme). For example, presumably at your job +you have a "reporting chain." Let's say a given record in LDAP (I'll use myself as a guinea pig here) looks like: +
    firstName: Mark
+    lastName: Cavage
+    city: Seattle
+    uid: markc
+    state: Washington
+    mail: mcavagegmailcom
+    phone: (206) 555-1212
+    title: Software Engineer
+    department: 123456
+    objectclass: joyentPerson
+The record for me would live under the tree of engineers I report to (and as an example some other popular engineers under said vice president) would look like: +
                   uid=david
+                    /
+               uid=bryan
+            /      |      \
+      uid=markc  uid=ryah  uid=isaacs
+Ok, so we've got a tree. It's not tremendously different from your filesystem, but how do we find people? LDAP has a rich search filter syntax that makes a lot of sense for key/value data (far more than tacking Map Reduce jobs on does, imo), and all search queries take a "start point" in the tree. Here's an example: let's say I wanted to find all "Software Engineers" in the entire company, a filter would look like: +
     (title="Software Engineer")
+And I'd just start my search from 'uid=david' in the example above. Let's say I wanted to find all software engineers who worked in Seattle: +
     (&(title="Software Engineer")(city=Seattle))
+I could keep going, but the gist is that LDAP has "full" boolean predicate logic, wildcard filters, etc. It's really rich. + +Oh, and on top of the technical merits, better or worse, it's an established standard for both administrators and applications (i.e., most "shipped" intranet software has either a local user repository or the ability to leverage an LDAP server somewhere). So there's a lot of compelling reasons to look at leveraging LDAP. +

ldapjs: Why do I care?

+ +As I said earlier, I spent a lot of time at IBM observing how customers used LDAP, and the real items I took away from that experience were: +
    +
  • LDAP implementations have suffered a lot from never having been designed from the ground up for a large number of concurrent connections with asynchronous operations.
  • +
  • There are use cases for LDAP that just don't always fit the traditional "here's my server and storage engine" model. A lot of simple customer use cases wanted an LDAP access point, but not be forced into taking the heavy backends that came with it (they wanted the original gateway model!). There was an entire "sub" industry for this known as "meta directories" back in the late 90's and early 2000's.
  • +
  • Replication was always a sticking point. LDAP vendors all tried to offer a big multi-master, multi-site replication model. It was a lot of "bolt-on" complexity, done before the CAP theorem was written, and certainly before it was accepted as "truth."
  • +
  • Nobody uses all of the protocol. In fact, 20% of the features solve 80% of the use cases (I'm making that number up, but you get the idea).
  • +
+ +For all the good parts of LDAP, those are really damned big failing points, and even I eventually abandoned LDAP for the greener pastures of NoSQL somewhere +along the way. But it always nagged at me that LDAP didn't get it's due because of a lot of implementation problems (to be clear, if I could, I'd change some +aspects of the protocol itself too, but that's a lot harder). + +Well, in the last year, I went to work for Joyent, and like everyone else, we have several use problems that are classic directory service problems. If you break down the list I outlined above: +
    +
  • Connection-oriented and asynchronous: Holy smokes batman, node.js is a completely kick-ass event-driven asynchronous server platform that manages connections like a boss. Check!
  • +
  • Lots of use cases: Yeah, we've got some. Man, the sinatra/express paradigm is so easy to slap over anything. How about we just do that and leave as many use cases open as we can. Check!
  • +
  • Replication is hard. CAP is right: There are a lot of distributed databases out vying to solve exactly this problem. At Joyent we went with Riak. Check!
  • +
  • Don't need all of the protocol: I'm lazy. Let's just skip the stupid things most people don't need. Check!
  • +
+ +So that's the crux of ldapjs right there. Giving you the ability to put LDAP back into your application while nailing those 4 fundamental problems that plague most existing LDAP deployments. + +The obvious question is how it turned out, and the answer is, honestly, better than I thought it would. When I set out to do this, I actually assumed I'd be shipping a much smaller percentage of the RFC than is there. There's actually about 95% of the core RFC implemented. I wasn't sure if the marriage of this protocol to node/JavaScript would work out, but if you've used express ever, this should be _really_ familiar. And I tried to make it as natural as possible to use "pure" JavaScript objects, rather than requiring the developer to understand ASN.1 (the binary wire protocol) or the LDAP RFC in detail (this one mostly worked out; ldap_modify is still kind of a PITA). + +Within 24 hours of releasing ldapjs on Twitter, there was an implementation of an address book that works with Thunderbird/Evolution, by the end of that weekend there was some slick integration with CouchDB, and ldapjs even got used in one of the node knockout apps. Off to a pretty good start! + +

The Road Ahead

+ +Hopefully you've been motivated to learn a little bit more about LDAP and try out ldapjs. The best place to start is probably the guide. After that you'll probably need to pick up a book from back in the day. ldapjs itself is still in its infancy; there's quite a bit of room to add some slick client-side logic (e.g., connection pools, automatic reconnects), easy to use schema validation, backends, etc. By the time this post is live, there will be experimental dtrace support if you're running on Mac OS X or preferably Joyent's SmartOS (shameless plug). And that nagging percentage of the protocol I didn't do will get filled in over time I suspect. If you've got an interest in any of this, send me some pull requests, but most importantly, I just want to see LDAP not just be a skeleton in the closet and get used in places where you should be using it. So get out there and write you some LDAP. diff --git a/node-v0.8.14/doc/blog/Uncategorized/libuv-status-report.md b/node-v0.8.14/doc/blog/Uncategorized/libuv-status-report.md new file mode 100644 index 0000000..4d7f3e9 --- /dev/null +++ b/node-v0.8.14/doc/blog/Uncategorized/libuv-status-report.md @@ -0,0 +1,45 @@ +title: libuv status report +author: ryandahl +date: Fri Sep 23 2011 12:45:50 GMT-0700 (PDT) +status: publish +category: Uncategorized +slug: libuv-status-report + +We announced back in July that with Microsoft's support Joyent would be porting Node to Windows. This effort is ongoing but I thought it would be nice to make a status report post about the new platform library libuv which has resulted from porting Node to Windows. + +libuv's purpose is to abstract platform-dependent code in Node into one place where it can be tested for correctness and performance before bindings to V8 are added. Since Node is totally non-blocking, libuv turns out to be a rather useful library itself: a BSD-licensed, minimal, high-performance, cross-platform networking library. + +We attempt to not reinvent the wheel where possible. The entire Unix backend sits heavily on Marc Lehmann's beautiful libraries libev and libeio. For DNS we integrated with Daniel Stenberg's C-Ares. For cross-platform build-system support we're relying on Chrome's GYP meta-build system. + +The current implmented features are: +
    +
  • Non-blocking TCP sockets (using IOCP on Windows)
  • +
  • Non-blocking named pipes
  • +
  • UDP
  • +
  • Timers
  • +
  • Child process spawning
  • +
  • Asynchronous DNS via c-ares or uv_getaddrinfo.
  • +
  • Asynchronous file system APIs uv_fs_*
  • +
  • High resolution time uv_hrtime
  • +
  • Current executable path look up uv_exepath
  • +
  • Thread pool scheduling uv_queue_work
  • +
+The features we are working on still are +
    +
  • File system events (Currently supports inotify, ReadDirectoryChangesW and will support kqueue and event ports in the near future.) uv_fs_event_t
  • +
  • VT100 TTY uv_tty_t
  • +
  • Socket sharing between processes uv_ipc_t (planned API)
  • +
+For complete documentation see the header file: include/uv.h. There are a number of tests in the test directory which demonstrate the API. + +libuv supports Microsoft Windows operating systems since Windows XP SP2. It can be built with either Visual Studio or MinGW. Solaris 121 and later using GCC toolchain. Linux 2.6 or better using the GCC toolchain. Macinotsh Darwin using the GCC or XCode toolchain. It is known to work on the BSDs but we do not check the build regularly. + +In addition to Node v0.5, a number of projects have begun to use libuv: + +We hope to see more people contributing and using libuv in the future! diff --git a/node-v0.8.14/doc/blog/Uncategorized/node-meetup-this-thursday.md b/node-v0.8.14/doc/blog/Uncategorized/node-meetup-this-thursday.md new file mode 100644 index 0000000..6f38e99 --- /dev/null +++ b/node-v0.8.14/doc/blog/Uncategorized/node-meetup-this-thursday.md @@ -0,0 +1,11 @@ +title: Node Meetup this Thursday +author: ryandahl +date: Tue Aug 02 2011 21:37:02 GMT-0700 (PDT) +status: publish +category: Uncategorized +slug: node-meetup-this-thursday + +http://nodejs.org/meetup/ +http://nodemeetup.eventbrite.com/ + +Three companies will describe their distributed Node applications. Sign up soon, space is limited! diff --git a/node-v0.8.14/doc/blog/Uncategorized/node-office-hours-cut-short.md b/node-v0.8.14/doc/blog/Uncategorized/node-office-hours-cut-short.md new file mode 100644 index 0000000..7433944 --- /dev/null +++ b/node-v0.8.14/doc/blog/Uncategorized/node-office-hours-cut-short.md @@ -0,0 +1,12 @@ +title: Node Office Hours Cut Short +author: ryandahl +date: Thu Apr 28 2011 09:04:35 GMT-0700 (PDT) +status: publish +category: Uncategorized +slug: node-office-hours-cut-short + +This week office hours are only from 4pm to 6pm. Isaac will be in the Joyent office in SF - everyone else is out of town. Sign up at http://nodeworkup.eventbrite.com/ if you would like to come. + +The week after, Thursday May 5th, we will all be at NodeConf in Portland. + +Normal office hours resume Thursday May 12th. diff --git a/node-v0.8.14/doc/blog/Uncategorized/office-hours.md b/node-v0.8.14/doc/blog/Uncategorized/office-hours.md new file mode 100644 index 0000000..fc27690 --- /dev/null +++ b/node-v0.8.14/doc/blog/Uncategorized/office-hours.md @@ -0,0 +1,12 @@ +title: Office Hours +author: ryandahl +date: Wed Mar 23 2011 21:42:47 GMT-0700 (PDT) +status: publish +category: Uncategorized +slug: office-hours + +Starting next Thursday Isaac, Tom, and I will be holding weekly office hours at Joyent HQ in San Francisco. Office hours are meant to be subdued working time - there are no talks and no alcohol. Bring your bugs or just come and hack with us. + +Our building requires that everyone attending be on a list so you must sign up at Event Brite. + +We start at 4p and end promptly at 8p. diff --git a/node-v0.8.14/doc/blog/Uncategorized/porting-node-to-windows-with-microsoft%e2%80%99s-help.md b/node-v0.8.14/doc/blog/Uncategorized/porting-node-to-windows-with-microsoft%e2%80%99s-help.md new file mode 100644 index 0000000..cea3e88 --- /dev/null +++ b/node-v0.8.14/doc/blog/Uncategorized/porting-node-to-windows-with-microsoft%e2%80%99s-help.md @@ -0,0 +1,12 @@ +title: Porting Node to Windows With Microsoft’s Help +author: ryandahl +date: Thu Jun 23 2011 15:22:58 GMT-0700 (PDT) +status: publish +category: Uncategorized +slug: porting-node-to-windows-with-microsoft%e2%80%99s-help + +I'm pleased to announce that Microsoft is partnering with Joyent in formally contributing resources towards porting Node to Windows. As you may have heard in a talk we gave earlier this year, we have started the undertaking of a native port to Windows - targeting the high-performance IOCP API. + +This requires a rather large modification of the core structure, and we're very happy to have official guidance and engineering resources from Microsoft. Rackspace is also contributing Bert Belder's time to this undertaking. + +The result will be an official binary node.exe releases on nodejs.org, which will work on Windows Azure and other Windows versions as far back as Server 2003. diff --git a/node-v0.8.14/doc/blog/Uncategorized/profiling-node-js.md b/node-v0.8.14/doc/blog/Uncategorized/profiling-node-js.md new file mode 100644 index 0000000..abb51da --- /dev/null +++ b/node-v0.8.14/doc/blog/Uncategorized/profiling-node-js.md @@ -0,0 +1,60 @@ +title: Profiling Node.js +author: Dave Pacheco +date: Wed Apr 25 2012 13:48:58 GMT-0700 (PDT) +status: publish +category: Uncategorized +slug: profiling-node-js + +It's incredibly easy to visualize where your Node program spends its time using DTrace and node-stackvis (a Node port of Brendan Gregg's FlameGraph tool): + +
    +
  1. Run your Node.js program as usual.
  2. +
  3. In another terminal, run: +
    +$ dtrace -n 'profile-97/execname == "node" && arg1/{
    +    @[jstack(150, 8000)] = count(); } tick-60s { exit(0); }' > stacks.out
    + This will sample about 100 times per second for 60 seconds and emit results to stacks.out. Note that this will sample all running programs called "node". If you want a specific process, replace execname == "node" with pid == 12345 (the process id). +
  4. +
  5. Use the "stackvis" tool to transform this directly into a flame graph. First, install it: +
    $ npm install -g stackvis
    + then use stackvis to convert the DTrace output to a flamegraph: +
    $ stackvis dtrace flamegraph-svg < stacks.out > stacks.svg
    +
  6. +
  7. Open stacks.svg in your favorite browser.
  8. +
+ +You'll be looking at something like this: + + + +This is a visualization of all of the profiled call stacks. This example is from the "hello world" HTTP server on the Node.js home page under load. Start at the bottom, where you have "main", which is present in most Node stacks because Node spends most on-CPU time in the main thread. Above each row, you have the functions called by the frame beneath it. As you move up, you'll see actual JavaScript function names. The boxes in each row are not in chronological order, but their width indicates how much time was spent there. When you hover over each box, you can see exactly what percentage of time is spent in each function. This lets you see at a glance where your program spends its time. + +That's the summary. There are a few prerequisites: + +
    +
  • You must gather data on a system that supports DTrace with the Node.js ustack helper. For now, this pretty much means illumos-based systems like SmartOS, including the Joyent Cloud. MacOS users: OS X supports DTrace, but not ustack helpers. The way to get this changed is to contact your Apple developer liason (if you're lucky enough to have one) or file a bug report at bugreport.apple.com. I'd suggest referencing existing bugs 5273057 and 11206497. More bugs filed (even if closed as dups) show more interest and make it more likely Apple will choose to fix this.
  • +
  • You must be on 32-bit Node.js 0.6.7 or later, built --with-dtrace. The helper doesn't work with 64-bit Node yet. On illumos (including SmartOS), development releases (the 0.7.x train) include DTrace support by default.
  • +
+ +There are a few other notes: + +
    +
  • You can absolutely profile apps in production, not just development, since compiling with DTrace support has very minimal overhead. You can start and stop profiling without restarting your program.
  • +
  • You may want to run the stacks.out output through c++filt to demangle C++ symbols. Be sure to use the c++filt that came with the compiler you used to build Node. For example: +
    c++filt < stacks.out > demangled.out
    + then you can use demangled.out to create the flamegraph. +
  • +
  • If you want, you can filter stacks containing a particular function. The best way to do this is to first collapse the original DTrace output, then grep out what you want: +
    +$ stackvis dtrace collapsed < stacks.out | grep SomeFunction > collapsed.out
    +$ stackvis collapsed flamegraph-svg < collapsed.out > stacks.svg
    +
  • +
  • If you've used Brendan's FlameGraph tools, you'll notice the coloring is a little different in the above flamegraph. I ported his tools to Node first so I could incorporate it more easily into other Node programs, but I've also been playing with different coloring options. The current default uses hue to denote stack depth and saturation to indicate time spent. (These are also indicated by position and size.) Other ideas include coloring by module (so V8, JavaScript, libc, etc. show up as different colors.) +
  • +
+ +For more on the underlying pieces, see my previous post on Node.js profiling and Brendan's post on Flame Graphs. + +
+ +Dave Pacheco blogs at dtrace.org diff --git a/node-v0.8.14/doc/blog/Uncategorized/some-new-node-projects.md b/node-v0.8.14/doc/blog/Uncategorized/some-new-node-projects.md new file mode 100644 index 0000000..2590f54 --- /dev/null +++ b/node-v0.8.14/doc/blog/Uncategorized/some-new-node-projects.md @@ -0,0 +1,13 @@ +title: Some New Node Projects +author: ryandahl +date: Mon Aug 29 2011 08:30:41 GMT-0700 (PDT) +status: publish +category: Uncategorized +slug: some-new-node-projects + +
    +
  • Superfeedr released a Node XMPP Server. "Since astro had been doing an amazing work with his node-xmpp library to build Client, Components and even Server to server modules, the logical next step was to try to build a Client to Server module so that we could have a full blown server. That’s what we worked on the past couple days, and it’s now on Github!
  • + +
  • Joyent's Mark Cavage released LDAP.js. "ldapjs is a pure JavaScript, from-scratch framework for implementing LDAP clients and servers in Node.js. It is intended for developers used to interacting with HTTP services in node and express.
  • + +
  • Microsoft's Tomasz Janczuk released iisnode "The iisnode project provides a native IIS 7.x module that allows hosting of node.js applications in IIS.

    Scott Hanselman posted a detailed walkthrough of how to get started with iisnode diff --git a/node-v0.8.14/doc/blog/Uncategorized/the-videos-from-node-meetup.md b/node-v0.8.14/doc/blog/Uncategorized/the-videos-from-node-meetup.md new file mode 100644 index 0000000..68c5eff --- /dev/null +++ b/node-v0.8.14/doc/blog/Uncategorized/the-videos-from-node-meetup.md @@ -0,0 +1,10 @@ +title: The Videos from the Meetup +author: ryandahl +date: Fri Aug 12 2011 00:14:34 GMT-0700 (PDT) +status: publish +category: Uncategorized +slug: the-videos-from-node-meetup + +Uber, Voxer, and Joyent described how they use Node in production + +http://joyeur.com/2011/08/11/node-js-meetup-distributed-web-architectures/ diff --git a/node-v0.8.14/doc/blog/Uncategorized/trademark.md b/node-v0.8.14/doc/blog/Uncategorized/trademark.md new file mode 100644 index 0000000..1bc177b --- /dev/null +++ b/node-v0.8.14/doc/blog/Uncategorized/trademark.md @@ -0,0 +1,17 @@ +title: Trademark +author: ryandahl +date: Fri Apr 29 2011 01:54:18 GMT-0700 (PDT) +status: publish +category: Uncategorized +slug: trademark + +One of the things Joyent accepted when we took on the Node project was to provide resources to help the community grow. The Node project is amazing because of the expertize, dedication and hard work of the community. However in all communities there is the possibility of people acting inappropriately. We decided to introduce trademarks on the “Node.js” and the “Node logo” in order to ensure that people or organisations who are not investing in the Node community misrepresent, or create confusion about the role of themselves or their products with Node. + +We are big fans of the people who have contributed to Node and we have worked hard to make sure that existing members of the community will be unaffected by this change. For most people they don’t have to do anything they are free to use the Node.js marks in their free open source projects (see guidelines). For others we’ve already granted them licenses to use Node.js marks in their domain names and their businesses. We value all of these contributions to the Node community and hope that we can continue to protect their good names and hard work. + +Where does our trademark policy come from? We started by looking at popular open source foundations like the Apache Software Foundation and Linux. By strongly basing our policy on the one used by the Apache Software Foundation we feel that we’ve created a policy which is liberal enough to allow the open source community to easily make use of the mark in the context of free open source software, but secure enough to protect the community’s work from being misrepresented by other organisations. + +While we realise that any changes involving lawyers can be intimidating to the community we want to make this transition as smoothly as possible and welcome your questions and feedback on the policy and how we are implementing it. + +http://nodejs.org/trademark-policy.pdf +trademark@joyent.com diff --git a/node-v0.8.14/doc/blog/Uncategorized/version-0-6.md b/node-v0.8.14/doc/blog/Uncategorized/version-0-6.md new file mode 100644 index 0000000..8dd9719 --- /dev/null +++ b/node-v0.8.14/doc/blog/Uncategorized/version-0-6.md @@ -0,0 +1,12 @@ +title: Version 0.6 Coming Soon +author: ryandahl +date: Tue Oct 25 2011 15:26:23 GMT-0700 (PDT) +status: publish +category: Uncategorized +slug: version-0-6 + +Version 0.6.0 will be released next week. Please spend some time this week upgrading your code to v0.5.10. Report any API differences at https://github.com/joyent/node/wiki/API-changes-between-v0.4-and-v0.6 or report a bug to us at http://github.com/joyent/node/issues if you hit problems. + +The API changes between v0.4.12 and v0.5.10 are 99% cosmetic, minor, and easy to fix. Most people are able to migrate their code in 10 minutes. Don't fear. + +Once you've ported your code to v0.5.10 please help out by testing third party modules. Make bug reports. Encourage authors to publish new versions of their modules. Go through the list of modules at http://search.npmjs.org/ and try out random ones. This is especially encouraged of Windows users! diff --git a/node-v0.8.14/doc/blog/module/multi-server-continuous-deployment-with-fleet.md b/node-v0.8.14/doc/blog/module/multi-server-continuous-deployment-with-fleet.md new file mode 100644 index 0000000..7849ee4 --- /dev/null +++ b/node-v0.8.14/doc/blog/module/multi-server-continuous-deployment-with-fleet.md @@ -0,0 +1,89 @@ +title: multi-server continuous deployment with fleet +author: Isaac Schlueter +date: Wed May 02 2012 11:00:00 GMT-0700 (PDT) +status: publish +category: module +slug: multi-server-continuous-deployment-with-fleet + +

    substackThis is a guest post by James "SubStack" Halliday, originally posted on his blog, and reposted here with permission.

    + +

    Writing applications as a sequence of tiny services that all talk to each other over the network has many upsides, but it can be annoyingly tedious to get all the subsystems up and running.

    + +

    Running a seaport can help with getting all the services to talk to each other, but running the processes is another matter, especially when you have new code to push into production.

    + +

    fleet aims to make it really easy for anyone on your team to push new code from git to an armada of servers and manage all the processes in your stack.

    + +

    To start using fleet, just install the fleet command with npm:

    + +
    npm install -g fleet 
    + +

    Then on one of your servers, start a fleet hub. From a fresh directory, give it a passphrase and a port to listen on:

    + +
    fleet hub --port=7000 --secret=beepboop 
    + +

    Now fleet is listening on :7000 for commands and has started a git server on :7001 over http. There's no ssh keys or post commit hooks to configure, just run that command and you're ready to go!

    + +

    Next set up some worker drones to run your processes. You can have as many workers as you like on a single server but each worker should be run from a separate directory. Just do:

    + +
    fleet drone --hub=x.x.x.x:7000 --secret=beepboop 
    + +

    where x.x.x.x is the address where the fleet hub is running. Spin up a few of these drones.

    + +

    Now navigate to the directory of the app you want to deploy. First set a remote so you don't need to type --hub and --secret all the time.

    + +
    fleet remote add default --hub=x.x.x.x:7000 --secret=beepboop 
    + +

    Fleet just created a fleet.json file for you to save your settings.

    + +

    From the same app directory, to deploy your code just do:

    + +
    fleet deploy 
    + +

    The deploy command does a git push to the fleet hub's git http server and then the hub instructs all the drones to pull from it. Your code gets checked out into a new directory on all the fleet drones every time you deploy.

    + +

    Because fleet is designed specifically for managing applications with lots of tiny services, the deploy command isn't tied to running any processes. Starting processes is up to the programmer but it's super simple. Just use the fleet spawn command:

    + +
    fleet spawn -- node server.js 8080 
    + +

    By default fleet picks a drone at random to run the process on. You can specify which drone you want to run a particular process on with the --drone switch if it matters.

    + +

    Start a few processes across all your worker drones and then show what is running with the fleet ps command:

    + +
    fleet ps
    +drone#3dfe17b8
    +├─┬ pid#1e99f4
    +│ ├── status:   running
    +│ ├── commit:   webapp/1b8050fcaf8f1b02b9175fcb422644cb67dc8cc5
    +│ └── command:  node server.js 8888
    +└─┬ pid#d7048a
    +  ├── status:   running
    +  ├── commit:   webapp/1b8050fcaf8f1b02b9175fcb422644cb67dc8cc5
    +  └── command:  node server.js 8889
    + +

    Now suppose that you have new code to push out into production. By default, fleet lets you spin up new services without disturbing your existing services. If you fleet deploy again after checking in some new changes to git, the next time you fleet spawn a new process, that process will be spun up in a completely new directory based on the git commit hash. To stop a process, just use fleet stop.

    + +

    This approach lets you verify that the new services work before bringing down the old services. You can even start experimenting with heterogeneous and incremental deployment by hooking into a custom http proxy!

    + +

    Even better, if you use a service registry like seaport for managing the host/port tables, you can spin up new ad-hoc staging clusters all the time without disrupting the normal operation of your site before rolling out new code to users.

    + +

    Fleet has many more commands that you can learn about with its git-style manpage-based help system! Just do fleet help to get a list of all the commands you can run.

    + +
    fleet help
    +Usage: fleet <command> [<args>]
    +
    +The commands are:
    +  deploy   Push code to drones.
    +  drone    Connect to a hub as a worker.
    +  exec     Run commands on drones.
    +  hub      Create a hub for drones to connect.
    +  monitor  Show service events system-wide.
    +  ps       List the running processes on the drones.
    +  remote   Manage the set of remote hubs.
    +  spawn    Run services on drones.
    +  stop     Stop processes running on drones.
    +
    +For help about a command, try `fleet help `.
    + +

    npm install -g fleet and check out the code on github!

    + + diff --git a/node-v0.8.14/doc/blog/module/service-logging-in-json-with-bunyan.md b/node-v0.8.14/doc/blog/module/service-logging-in-json-with-bunyan.md new file mode 100644 index 0000000..8a323c4 --- /dev/null +++ b/node-v0.8.14/doc/blog/module/service-logging-in-json-with-bunyan.md @@ -0,0 +1,337 @@ +title: Service logging in JSON with Bunyan +author: trentmick +date: Wed Mar 28 2012 12:25:26 GMT-0700 (PDT) +status: publish +category: module +slug: service-logging-in-json-with-bunyan + + + +

    Service logs are gold, if you can mine them. We scan them for occasional debugging. Perhaps we grep them looking for errors or warnings, or setup an occasional nagios log regex monitor. If that. This is a waste of the best channel for data about a service.

    + +

    "Log. (Huh) What is it good for. Absolutely ..."

    + +
      +
    • debugging
    • +
    • monitors tools that alert operators
    • +
    • non real-time analysis (business or operational analysis)
    • +
    • historical analysis
    • +
    + +

    These are what logs are good for. The current state of logging is barely adequate for the first of these. Doing reliable analysis, and even monitoring, of varied "printf-style" logs is a grueling or hacky task that most either don't bother with, fallback to paying someone else to do (viz. Splunk's great successes), or, for web sites, punt and use the plethora of JavaScript-based web analytics tools.

    + +

    Let's log in JSON. Let's format log records with a filter outside the app. Let's put more info in log records by not shoehorning into a printf-message. Debuggability can be improved. Monitoring and analysis can definitely be improved. Let's not write another regex-based parser, and use the time we've saved writing tools to collate logs from multiple nodes and services, to query structured logs (from all services, not just web servers), etc.

    + +

    At Joyent we use node.js for running many core services -- loosely coupled through HTTP REST APIs and/or AMQP. In this post I'll draw on experiences from my work on Joyent's SmartDataCenter product and observations of Joyent Cloud operations to suggest some improvements to service logging. I'll show the (open source) Bunyan logging library and tool that we're developing to improve the logging toolchain.

    + +

    Current State of Log Formatting

    + +
    # apache access log
    +10.0.1.22 - - [15/Oct/2010:11:46:46 -0700] "GET /favicon.ico HTTP/1.1" 404 209
    +fe80::6233:4bff:fe29:3173 - - [15/Oct/2010:11:46:58 -0700] "GET / HTTP/1.1" 200 44
    +
    +# apache error log
    +[Fri Oct 15 11:46:46 2010] [error] [client 10.0.1.22] File does not exist: /Library/WebServer/Documents/favicon.ico
    +[Fri Oct 15 11:46:58 2010] [error] [client fe80::6233:4bff:fe29:3173] File does not exist: /Library/WebServer/Documents/favicon.ico
    +
    +# Mac /var/log/secure.log
    +Oct 14 09:20:56 banana loginwindow[41]: in pam_sm_authenticate(): Failed to determine Kerberos principal name.
    +Oct 14 12:32:20 banana com.apple.SecurityServer[25]: UID 501 authenticated as user trentm (UID 501) for right 'system.privilege.admin'
    +
    +# an internal joyent agent log
    +[2012-02-07 00:37:11.898] [INFO] AMQPAgent - Publishing success.
    +[2012-02-07 00:37:11.910] [DEBUG] AMQPAgent - { req_id: '8afb8d99-df8e-4724-8535-3d52adaebf25',
    +  timestamp: '2012-02-07T00:37:11.898Z',
    +
    +# typical expressjs log output
    +[Mon, 21 Nov 2011 20:52:11 GMT] 200 GET /foo (1ms)
    +Blah, some other unstructured output to from a console.log call.
    +
    + +

    What're we doing here? Five logs at random. Five different date formats. As Paul Querna points out we haven't improved log parsability in 20 years. Parsability is enemy number one. You can't use your logs until you can parse the records, and faced with the above the inevitable solution is a one-off regular expression.

    + +

    The current state of the art is various parsing libs, analysis tools and homebrew scripts ranging from grep to Perl, whose scope is limited to a few niches log formats.

    + +

    JSON for Logs

    + +

    JSON.parse() solves all that. Let's log in JSON. But it means a change in thinking: The first-level audience for log files shouldn't be a person, but a machine.

    + +

    That is not said lightly. The "Unix Way" of small focused tools lightly coupled with text output is important. JSON is less "text-y" than, e.g., Apache common log format. JSON makes grep and awk awkward. Using less directly on a log is handy.

    + +

    But not handy enough. That 80's pastel jumpsuit awkwardness you're feeling isn't the JSON, it's your tools. Time to find a json tool -- json is one, bunyan described below is another one. Time to learn your JSON library instead of your regex library: JavaScript, Python, Ruby, Java, Perl.

    + +

    Time to burn your log4j Layout classes and move formatting to the tools side. Creating a log message with semantic information and throwing that away to make a string is silly. The win at being able to trivially parse log records is huge. The possibilities at being able to add ad hoc structured information to individual log records is interesting: think program state metrics, think feeding to Splunk, or loggly, think easy audit logs.

    + +

    Introducing Bunyan

    + +

    Bunyan is a node.js module for logging in JSON and a bunyan CLI tool to view those logs.

    + +

    Logging with Bunyan basically looks like this:

    + +
    $ cat hi.js
    +var Logger = require('bunyan');
    +var log = new Logger({name: 'hello' /*, ... */});
    +log.info("hi %s", "paul");
    +
    + +

    And you'll get a log record like this:

    + +
    $ node hi.js
    +{"name":"hello","hostname":"banana.local","pid":40026,"level":30,"msg":"hi paul","time":"2012-03-28T17:25:37.050Z","v":0}
    +
    + +

    Pipe that through the bunyan tool that is part of the "node-bunyan" install to get more readable output:

    + +
    $ node hi.js | ./node_modules/.bin/bunyan       # formatted text output
    +[2012-02-07T18:50:18.003Z]  INFO: hello/40026 on banana.local: hi paul
    +
    +$ node hi.js | ./node_modules/.bin/bunyan -j    # indented JSON output
    +{
    +  "name": "hello",
    +  "hostname": "banana.local",
    +  "pid": 40087,
    +  "level": 30,
    +  "msg": "hi paul",
    +  "time": "2012-03-28T17:26:38.431Z",
    +  "v": 0
    +}
    +
    + +

    Bunyan is log4j-like: create a Logger with a name, call log.info(...), etc. However it has no intention of reproducing much of the functionality of log4j. IMO, much of that is overkill for the types of services you'll tend to be writing with node.js.

    + +

    Longer Bunyan Example

    + +

    Let's walk through a bigger example to show some interesting things in Bunyan. We'll create a very small "Hello API" server using the excellent restify library -- which we used heavily here at Joyent. (Bunyan doesn't require restify at all, you can easily use Bunyan with Express or whatever.)

    + +

    You can follow along in https://github.com/trentm/hello-json-logging if you like. Note that I'm using the current HEAD of the bunyan and restify trees here, so details might change a bit. Prerequisite: a node 0.6.x installation.

    + +
    git clone https://github.com/trentm/hello-json-logging.git
    +cd hello-json-logging
    +make
    +
    + +

    Bunyan Logger

    + +

    Our server first creates a Bunyan logger:

    + +
    var Logger = require('bunyan');
    +var log = new Logger({
    +  name: 'helloapi',
    +  streams: [
    +    {
    +      stream: process.stdout,
    +      level: 'debug'
    +    },
    +    {
    +      path: 'hello.log',
    +      level: 'trace'
    +    }
    +  ],
    +  serializers: {
    +    req: Logger.stdSerializers.req,
    +    res: restify.bunyan.serializers.response,
    +  },
    +});
    +
    + +

    Every Bunyan logger must have a name. Unlike log4j, this is not a hierarchical dotted namespace. It is just a name field for the log records.

    + +

    Every Bunyan logger has one or more streams, to which log records are written. Here we've defined two: logging at DEBUG level and above is written to stdout, and logging at TRACE and above is appended to 'hello.log'.

    + +

    Bunyan has the concept of serializers: a registry of functions that know how to convert a JavaScript object for a certain log record field to a nice JSON representation for logging. For example, here we register the Logger.stdSerializers.req function to convert HTTP Request objects (using the field name "req") to JSON. More on serializers later.

    + +

    Restify Server

    + +

    Restify 1.x and above has bunyan support baked in. You pass in your Bunyan logger like this:

    + +
    var server = restify.createServer({
    +  name: 'Hello API',
    +  log: log   // Pass our logger to restify.
    +});
    +
    + +

    Our simple API will have a single GET /hello?name=NAME endpoint:

    + +
    server.get({path: '/hello', name: 'SayHello'}, function(req, res, next) {
    +  var caller = req.params.name || 'caller';
    +  req.log.debug('caller is "%s"', caller);
    +  res.send({"hello": caller});
    +  return next();
    +});
    +
    + +

    If we run that, node server.js, and call the endpoint, we get the expected restify response:

    + +
    $ curl -iSs http://0.0.0.0:8080/hello?name=paul
    +HTTP/1.1 200 OK
    +Access-Control-Allow-Origin: *
    +Access-Control-Allow-Headers: Accept, Accept-Version, Content-Length, Content-MD5, Content-Type, Date, X-Api-Version
    +Access-Control-Expose-Headers: X-Api-Version, X-Request-Id, X-Response-Time
    +Server: Hello API
    +X-Request-Id: f6aaf942-c60d-4c72-8ddd-bada459db5e3
    +Access-Control-Allow-Methods: GET
    +Connection: close
    +Content-Length: 16
    +Content-MD5: Xmn3QcFXaIaKw9RPUARGBA==
    +Content-Type: application/json
    +Date: Tue, 07 Feb 2012 19:12:35 GMT
    +X-Response-Time: 4
    +
    +{"hello":"paul"}
    +
    + +

    Setup Server Logging

    + +

    Let's add two things to our server. First, we'll use the server.pre to hook into restify's request handling before routing where we'll log the request.

    + +
    server.pre(function (request, response, next) {
    +  request.log.info({req: request}, 'start');        // (1)
    +  return next();
    +});
    +
    + +

    This is the first time we've seen this log.info style with an object as the first argument. Bunyan logging methods (log.trace, log.debug, ...) all support an optional first object argument with extra log record fields:

    + +
    log.info(<object> fields, <string> msg, ...)
    +
    + +

    Here we pass in the restify Request object, req. The "req" serializer we registered above will come into play here, but bear with me.

    + +

    Remember that we already had this debug log statement in our endpoint handler:

    + +
    req.log.debug('caller is "%s"', caller);            // (2)
    +
    + +

    Second, use the restify server after event to log the response:

    + +
    server.on('after', function (req, res, route) {
    +  req.log.info({res: res}, "finished");             // (3)
    +});
    +
    + +

    Log Output

    + +

    Now lets see what log output we get when somebody hits our API's endpoint:

    + +
    $ curl -iSs http://0.0.0.0:8080/hello?name=paul
    +HTTP/1.1 200 OK
    +...
    +X-Request-Id: 9496dfdd-4ec7-4b59-aae7-3fed57aed5ba
    +...
    +
    +{"hello":"paul"}
    +
    + +

    Here is the server log:

    + +
    [trentm@banana:~/tm/hello-json-logging]$ node server.js
    +... intro "listening at" log message elided ...
    +{"name":"helloapi","hostname":"banana.local","pid":40341,"level":30,"req":{"method":"GET","url":"/hello?name=paul","headers":{"user-agent":"curl/7.19.7 (universal-apple-darwin10.0) libcurl/7.19.7 OpenSSL/0.9.8r zlib/1.2.3","host":"0.0.0.0:8080","accept":"*/*"},"remoteAddress":"127.0.0.1","remotePort":59831},"msg":"start","time":"2012-03-28T17:37:29.506Z","v":0}
    +{"name":"helloapi","hostname":"banana.local","pid":40341,"route":"SayHello","req_id":"9496dfdd-4ec7-4b59-aae7-3fed57aed5ba","level":20,"msg":"caller is \"paul\"","time":"2012-03-28T17:37:29.507Z","v":0}
    +{"name":"helloapi","hostname":"banana.local","pid":40341,"route":"SayHello","req_id":"9496dfdd-4ec7-4b59-aae7-3fed57aed5ba","level":30,"res":{"statusCode":200,"headers":{"access-control-allow-origin":"*","access-control-allow-headers":"Accept, Accept-Version, Content-Length, Content-MD5, Content-Type, Date, X-Api-Version","access-control-expose-headers":"X-Api-Version, X-Request-Id, X-Response-Time","server":"Hello API","x-request-id":"9496dfdd-4ec7-4b59-aae7-3fed57aed5ba","access-control-allow-methods":"GET","connection":"close","content-length":16,"content-md5":"Xmn3QcFXaIaKw9RPUARGBA==","content-type":"application/json","date":"Wed, 28 Mar 2012 17:37:29 GMT","x-response-time":3}},"msg":"finished","time":"2012-03-28T17:37:29.510Z","v":0}
    +
    + +

    Lets look at each in turn to see what is interesting -- pretty-printed with node server.js | ./node_modules/.bin/bunyan -j:

    + +
    {                                                   // (1)
    +  "name": "helloapi",
    +  "hostname": "banana.local",
    +  "pid": 40442,
    +  "level": 30,
    +  "req": {
    +    "method": "GET",
    +    "url": "/hello?name=paul",
    +    "headers": {
    +      "user-agent": "curl/7.19.7 (universal-apple-darwin10.0) libcurl/7.19.7 OpenSSL/0.9.8r zlib/1.2.3",
    +      "host": "0.0.0.0:8080",
    +      "accept": "*/*"
    +    },
    +    "remoteAddress": "127.0.0.1",
    +    "remotePort": 59834
    +  },
    +  "msg": "start",
    +  "time": "2012-03-28T17:39:44.880Z",
    +  "v": 0
    +}
    +
    + +

    Here we logged the incoming request with request.log.info({req: request}, 'start'). The use of the "req" field triggers the "req" serializer registered at Logger creation.

    + +

    Next the req.log.debug in our handler:

    + +
    {                                                   // (2)
    +  "name": "helloapi",
    +  "hostname": "banana.local",
    +  "pid": 40442,
    +  "route": "SayHello",
    +  "req_id": "9496dfdd-4ec7-4b59-aae7-3fed57aed5ba",
    +  "level": 20,
    +  "msg": "caller is \"paul\"",
    +  "time": "2012-03-28T17:39:44.883Z",
    +  "v": 0
    +}
    +
    + +

    and the log of response in the "after" event:

    + +
    {                                                   // (3)
    +  "name": "helloapi",
    +  "hostname": "banana.local",
    +  "pid": 40442,
    +  "route": "SayHello",
    +  "req_id": "9496dfdd-4ec7-4b59-aae7-3fed57aed5ba",
    +  "level": 30,
    +  "res": {
    +    "statusCode": 200,
    +    "headers": {
    +      "access-control-allow-origin": "*",
    +      "access-control-allow-headers": "Accept, Accept-Version, Content-Length, Content-MD5, Content-Type, Date, X-Api-Version",
    +      "access-control-expose-headers": "X-Api-Version, X-Request-Id, X-Response-Time",
    +      "server": "Hello API",
    +      "x-request-id": "9496dfdd-4ec7-4b59-aae7-3fed57aed5ba",
    +      "access-control-allow-methods": "GET",
    +      "connection": "close",
    +      "content-length": 16,
    +      "content-md5": "Xmn3QcFXaIaKw9RPUARGBA==",
    +      "content-type": "application/json",
    +      "date": "Wed, 28 Mar 2012 17:39:44 GMT",
    +      "x-response-time": 5
    +    }
    +  },
    +  "msg": "finished",
    +  "time": "2012-03-28T17:39:44.886Z",
    +  "v": 0
    +}
    +
    + +

    Two useful details of note here:

    + +
      +
    1. The last two log messages include a "req_id" field (added to the req.log logger by restify). Note that this is the same UUID as the "X-Request-Id" header in the curl response. This means that if you use req.log for logging in your API handlers you will get an easy way to collate all logging for particular requests.

      + +

      If your's is an SOA system with many services, a best practice is to carry that X-Request-Id/req_id through your system to enable collating handling of a single top-level request.

    2. +
    3. The last two log messages include a "route" field. This tells you to which handler restify routed the request. While possibly useful for debugging, this can be very helpful for log-based monitoring of endpoints on a server.

    4. +
    + +

    Recall that we also setup all logging to go the "hello.log" file. This was set at the TRACE level. Restify will log more detail of its operation at the trace level. See my "hello.log" for an example. The bunyan tool does a decent job of nicely formatting multiline messages and "req"/"res" keys (with color, not shown in the gist).

    + +

    This is logging you can use effectively.

    + +

    Other Tools

    + +

    Bunyan is just one of many options for logging in node.js-land. Others (that I know of) supporting JSON logging are winston and logmagic. Paul Querna has an excellent post on using JSON for logging, which shows logmagic usage and also touches on topics like the GELF logging format, log transporting, indexing and searching.

    + +

    Final Thoughts

    + +

    Parsing challenges won't ever completely go away, but it can for your logs if you use JSON. Collating log records across logs from multiple nodes is facilitated by a common "time" field. Correlating logging across multiple services is enabled by carrying a common "req_id" (or equivalent) through all such logs.

    + +

    Separate log files for a single service is an anti-pattern. The typical Apache example of separate access and error logs is legacy, not an example to follow. A JSON log provides the structure necessary for tooling to easily filter for log records of a particular type.

    + +

    JSON logs bring possibilities. Feeding to tools like Splunk becomes easy. Ad hoc fields allow for a lightly spec'd comm channel from apps to other services: records with a "metric" could feed to statsd, records with a "loggly: true" could feed to loggly.com.

    + +

    Here I've described a very simple example of restify and bunyan usage for node.js-based API services with easy JSON logging. Restify provides a powerful framework for robust API services. Bunyan provides a light API for nice JSON logging and the beginnings of tooling to help consume Bunyan JSON logs.

    + +

    Update (29-Mar-2012): Fix styles somewhat for RSS readers.

    diff --git a/node-v0.8.14/doc/blog/npm/managing-node-js-dependencies-with-shrinkwrap.md b/node-v0.8.14/doc/blog/npm/managing-node-js-dependencies-with-shrinkwrap.md new file mode 100644 index 0000000..403eada --- /dev/null +++ b/node-v0.8.14/doc/blog/npm/managing-node-js-dependencies-with-shrinkwrap.md @@ -0,0 +1,167 @@ +title: Managing Node.js Dependencies with Shrinkwrap +author: Dave Pacheco +date: Mon Feb 27 2012 10:51:59 GMT-0800 (PST) +status: publish +category: npm +slug: managing-node-js-dependencies-with-shrinkwrap + +


    +Photo by Luc Viatour (flickr)

    + +

    Managing dependencies is a fundamental problem in building complex software. The terrific success of github and npm have made code reuse especially easy in the Node world, where packages don't exist in isolation but rather as nodes in a large graph. The software is constantly changing (releasing new versions), and each package has its own constraints about what other packages it requires to run (dependencies). npm keeps track of these constraints, and authors express what kind of changes are compatible using semantic versioning, allowing authors to specify that their package will work with even future versions of its dependencies as long as the semantic versions are assigned properly. + +

    +

    This does mean that when you "npm install" a package with dependencies, there's no guarantee that you'll get the same set of code now that you would have gotten an hour ago, or that you would get if you were to run it again an hour later. You may get a bunch of bug fixes now that weren't available an hour ago. This is great during development, where you want to keep up with changes upstream. It's not necessarily what you want for deployment, though, where you want to validate whatever bits you're actually shipping. + +

    +

    Put differently, it's understood that all software changes incur some risk, and it's critical to be able to manage this risk on your own terms. Taking that risk in development is good because by definition that's when you're incorporating and testing software changes. On the other hand, if you're shipping production software, you probably don't want to take this risk when cutting a release candidate (i.e. build time) or when you actually ship (i.e. deploy time) because you want to validate whatever you ship. + +

    +

    You can address a simple case of this problem by only depending on specific versions of packages, allowing no semver flexibility at all, but this falls apart when you depend on packages that don't also adopt the same principle. Many of us at Joyent started wondering: can we generalize this approach? + +

    +

    Shrinkwrapping packages

    +

    That brings us to npm shrinkwrap[1]: + +

    +
    NAME
    +       npm-shrinkwrap -- Lock down dependency versions
    +
    +SYNOPSIS
    +       npm shrinkwrap
    +
    +DESCRIPTION
    +       This  command  locks down the versions of a package's dependencies so
    +       that you can control exactly which versions of each  dependency  will
    +       be used when your package is installed.
    +

    Let's consider package A: + +

    +
    {
    +    "name": "A",
    +    "version": "0.1.0",
    +    "dependencies": {
    +        "B": "<0.1.0"
    +    }
    +}
    +

    package B: + +

    +
    {
    +    "name": "B",
    +    "version": "0.0.1",
    +    "dependencies": {
    +        "C": "<0.1.0"
    +    }
    +}
    +

    and package C: + +

    +
    {
    +    "name": "C,
    +    "version": "0.0.1"
    +}
    +

    If these are the only versions of A, B, and C available in the registry, then a normal "npm install A" will install: + +

    +
    A@0.1.0
    +└─┬ B@0.0.1
    +  └── C@0.0.1
    +

    Then if B@0.0.2 is published, then a fresh "npm install A" will install: + +

    +
    A@0.1.0
    +└─┬ B@0.0.2
    +  └── C@0.0.1
    +

    assuming the new version did not modify B's dependencies. Of course, the new version of B could include a new version of C and any number of new dependencies. As we said before, if A's author doesn't want that, she could specify a dependency on B@0.0.1. But if A's author and B's author are not the same person, there's no way for A's author to say that she does not want to pull in newly published versions of C when B hasn't changed at all. + +

    +

    In this case, A's author can use + +

    +
    # npm shrinkwrap
    +

    This generates npm-shrinkwrap.json, which will look something like this: + +

    +
    {
    +    "name": "A",
    +    "dependencies": {
    +        "B": {
    +            "version": "0.0.1",
    +            "dependencies": {
    +                "C": {  "version": "0.1.0" }
    +            }
    +        }
    +    }
    +}
    +

    The shrinkwrap command has locked down the dependencies based on what's currently installed in node_modules. When "npm install" installs a package with a npm-shrinkwrap.json file in the package root, the shrinkwrap file (rather than package.json files) completely drives the installation of that package and all of its dependencies (recursively). So now the author publishes A@0.1.0, and subsequent installs of this package will use B@0.0.1 and C@0.1.0, regardless the dependencies and versions listed in A's, B's, and C's package.json files. If the authors of B and C publish new versions, they won't be used to install A because the shrinkwrap refers to older versions. Even if you generate a new shrinkwrap, it will still reference the older versions, since "npm shrinkwrap" uses what's installed locally rather than what's available in the registry. + +

    +

    Using shrinkwrapped packages

    +

    Using a shrinkwrapped package is no different than using any other package: you can "npm install" it by hand, or add a dependency to your package.json file and "npm install" it. + +

    +

    Building shrinkwrapped packages

    +

    To shrinkwrap an existing package: + +

    +
      +
    1. Run "npm install" in the package root to install the current versions of all dependencies.
    2. +
    3. Validate that the package works as expected with these versions.
    4. +
    5. Run "npm shrinkwrap", add npm-shrinkwrap.json to git, and publish your package.
    6. +
    +

    To add or update a dependency in a shrinkwrapped package: + +

    +
      +
    1. Run "npm install" in the package root to install the current versions of all dependencies.
    2. +
    3. Add or update dependencies. "npm install" each new or updated package individually and then update package.json.
    4. +
    5. Validate that the package works as expected with the new dependencies.
    6. +
    7. Run "npm shrinkwrap", commit the new npm-shrinkwrap.json, and publish your package.
    8. +
    +

    You can still use npm outdated(1) to view which dependencies have newer versions available. + +

    +

    For more details, check out the full docs on npm shrinkwrap, from which much of the above is taken. + +

    +

    Why not just check node_modules into git?

    +

    One previously proposed solution is to "npm install" your dependencies during development and commit the results into source control. Then you deploy your app from a specific git SHA knowing you've got exactly the same bits that you tested in development. This does address the problem, but it has its own issues: for one, binaries are tricky because you need to "npm install" them to get their sources, but this builds the [system-dependent] binary too. You can avoid checking in the binaries and use "npm rebuild" at build time, but we've had a lot of difficulty trying to do this.[2] At best, this is second-class treatment for binary modules, which are critical for many important types of Node applications.[3] + +

    +

    Besides the issues with binary modules, this approach just felt wrong to many of us. There's a reason we don't check binaries into source control, and it's not just because they're platform-dependent. (After all, we could build and check in binaries for all supported platforms and operating systems.) It's because that approach is error-prone and redundant: error-prone because it introduces a new human failure mode where someone checks in a source change but doesn't regenerate all the binaries, and redundant because the binaries can always be built from the sources alone. An important principle of software version control is that you don't check in files derived directly from other files by a simple transformation.[4] Instead, you check in the original sources and automate the transformations via the build process. + +

    +

    Dependencies are just like binaries in this regard: they're files derived from a simple transformation of something else that is (or could easily be) already available: the name and version of the dependency. Checking them in has all the same problems as checking in binaries: people could update package.json without updating the checked-in module (or vice versa). Besides that, adding new dependencies has to be done by hand, introducing more opportunities for error (checking in the wrong files, not checking in certain files, inadvertently changing files, and so on). Our feeling was: why check in this whole dependency tree (and create a mess for binary add-ons) when we could just check in the package name and version and have the build process do the rest? + +

    +

    Finally, the approach of checking in node_modules doesn't really scale for us. We've got at least a dozen repos that will use restify, and it doesn't make sense to check that in everywhere when we could instead just specify which version each one is using. There's another principle at work here, which is separation of concerns: each repo specifies what it needs, while the build process figures out where to get it. + +

    +

    What if an author republishes an existing version of a package?

    +

    We're not suggesting deploying a shrinkwrapped package directly and running "npm install" to install from shrinkwrap in production. We already have a build process to deal with binary modules and other automateable tasks. That's where we do the "npm install". We tar up the result and distribute the tarball. Since we test each build before shipping, we won't deploy something we didn't test. + +

    +

    It's still possible to pick up newly published versions of existing packages at build time. We assume force publish is not that common in the first place, let alone force publish that breaks compatibility. If you're worried about this, you can use git SHAs in the shrinkwrap or even consider maintaining a mirror of the part of the npm registry that you use and require human confirmation before mirroring unpublishes. + +

    +

    Final thoughts

    +

    Of course, the details of each use case matter a lot, and the world doesn't have to pick just one solution. If you like checking in node_modules, you should keep doing that. We've chosen the shrinkwrap route because that works better for us. + +

    +

    It's not exactly news that Joyent is heavy on Node. Node is the heart of our SmartDataCenter (SDC) product, whose public-facing web portal, public API, Cloud Analytics, provisioning, billing, heartbeating, and other services are all implemented in Node. That's why it's so important to us to have robust components (like logging and REST) and tools for understanding production failures post mortem, profile Node apps in production, and now managing Node dependencies. Again, we're interested to hear feedback from others using these tools. + +

    +
    +Dave Pacheco blogs at dtrace.org. + +

    [1] Much of this section is taken directly from the "npm shrinkwrap" documentation. + +

    +

    [2] We've had a lot of trouble with checking in node_modules with binary dependencies. The first problem is figuring out exactly which files not to check in (.o, .node, .dynlib, .so, *.a, ...). When Mark went to apply this to one of our internal services, the "npm rebuild" step blew away half of the dependency tree because it ran "make clean", which in dependency ldapjs brings the repo to a clean slate by blowing away its dependencies. Later, a new (but highly experienced) engineer on our team was tasked with fixing a bug in our Node-based DHCP server. To fix the bug, we went with a new dependency. He tried checking in node_modules, which added 190,000 lines of code (to this repo that was previously a few hundred LOC). And despite doing everything he could think of to do this correctly and test it properly, the change broke the build because of the binary modules. So having tried this approach a few times now, it appears quite difficult to get right, and as I pointed out above, the lack of actual documentation and real world examples suggests others either aren't using binary modules (which we know isn't true) or haven't had much better luck with this approach. + +

    +

    [3] Like a good Node-based distributed system, our architecture uses lots of small HTTP servers. Each of these serves a REST API using restify. restify uses the binary module node-dtrace-provider, which gives each of our services deep DTrace-based observability for free. So literally almost all of our components are or will soon be depending on a binary add-on. Additionally, the foundation of Cloud Analytics are a pair of binary modules that extract data from DTrace and kstat. So this isn't a corner case for us, and we don't believe we're exceptional in this regard. The popular hiredis package for interfacing with redis from Node is also a binary module. + +

    +

    [4] Note that I said this is an important principle for software version control, not using git in general. People use git for lots of things where checking in binaries and other derived files is probably fine. Also, I'm not interested in proselytizing; if you want to do this for software version control too, go ahead. But don't do it out of ignorance of existing successful software engineering practices.

    diff --git a/node-v0.8.14/doc/blog/npm/npm-1-0-global-vs-local-installation.md b/node-v0.8.14/doc/blog/npm/npm-1-0-global-vs-local-installation.md new file mode 100644 index 0000000..77a3fa8 --- /dev/null +++ b/node-v0.8.14/doc/blog/npm/npm-1-0-global-vs-local-installation.md @@ -0,0 +1,64 @@ +title: npm 1.0: Global vs Local installation +author: Isaac Schlueter +date: Wed Mar 23 2011 23:07:13 GMT-0700 (PDT) +status: publish +category: npm +slug: npm-1-0-global-vs-local-installation + +

    npm 1.0 is in release candidate mode. Go get it!

    + +

    More than anything else, the driving force behind the npm 1.0 rearchitecture was the desire to simplify what a package installation directory structure looks like.

    + +

    In npm 0.x, there was a command called bundle that a lot of people liked. bundle let you install your dependencies locally in your project, but even still, it was basically a hack that never really worked very reliably.

    + +

    Also, there was that activation/deactivation thing. That’s confusing.

    + +

    Two paths

    + +

    In npm 1.0, there are two ways to install things:

    + +
    1. globally —- This drops modules in {prefix}/lib/node_modules, and puts executable files in {prefix}/bin, where {prefix} is usually something like /usr/local. It also installs man pages in {prefix}/share/man, if they’re supplied.
    2. locally —- This installs your package in the current working directory. Node modules go in ./node_modules, executables go in ./node_modules/.bin/, and man pages aren’t installed at all.
    + +

    Which to choose

    + +

    Whether to install a package globally or locally depends on the global config, which is aliased to the -g command line switch.

    + +

    Just like how global variables are kind of gross, but also necessary in some cases, global packages are important, but best avoided if not needed.

    + +

    In general, the rule of thumb is:

    + +
    1. If you’re installing something that you want to use in your program, using require('whatever'), then install it locally, at the root of your project.
    2. If you’re installing something that you want to use in your shell, on the command line or something, install it globally, so that its binaries end up in your PATH environment variable.
    + +

    When you can't choose

    + +

    Of course, there are some cases where you want to do both. Coffee-script and Express both are good examples of apps that have a command line interface, as well as a library. In those cases, you can do one of the following:

    + +
    1. Install it in both places. Seriously, are you that short on disk space? It’s fine, really. They’re tiny JavaScript programs.
    2. Install it globally, and then npm link coffee-script or npm link express (if you’re on a platform that supports symbolic links.) Then you only need to update the global copy to update all the symlinks as well.
    + +

    The first option is the best in my opinion. Simple, clear, explicit. The second is really handy if you are going to re-use the same library in a bunch of different projects. (More on npm link in a future installment.)

    + +

    You can probably think of other ways to do it by messing with environment variables. But I don’t recommend those ways. Go with the grain.

    + +

    Slight exception: It’s not always the cwd.

    + +

    Let’s say you do something like this:

    + +
    cd ~/projects/foo     # go into my project
    +npm install express   # ./node_modules/express
    +cd lib/utils          # move around in there
    +vim some-thing.js     # edit some stuff, work work work
    +npm install redis     # ./lib/utils/node_modules/redis!? ew.
    + +

    In this case, npm will install redis into ~/projects/foo/node_modules/redis. Sort of like how git will work anywhere within a git repository, npm will work anywhere within a package, defined by having a node_modules folder.

    + +

    Test runners and stuff

    + +

    If your package's scripts.test command uses a command-line program installed by one of your dependencies, not to worry. npm makes ./node_modules/.bin the first entry in the PATH environment variable when running any lifecycle scripts, so this will work fine, even if your program is not globally installed: + +

    { "name" : "my-program"
    +, "version" : "1.2.3"
    +, "dependencies": { "express": "*", "coffee-script": "*" }
    +, "devDependencies": { "vows": "*" }
    +, "scripts":
    +  { "test": "vows test/*.js"
    +  , "preinstall": "cake build" } }
    diff --git a/node-v0.8.14/doc/blog/npm/npm-1-0-link.md b/node-v0.8.14/doc/blog/npm/npm-1-0-link.md new file mode 100644 index 0000000..9e5c3c8 --- /dev/null +++ b/node-v0.8.14/doc/blog/npm/npm-1-0-link.md @@ -0,0 +1,114 @@ +title: npm 1.0: link +author: Isaac Schlueter +date: Wed Apr 06 2011 17:40:33 GMT-0700 (PDT) +status: publish +category: npm +slug: npm-1-0-link + +

    npm 1.0 is in release candidate mode. Go get it!

    + +

    In npm 0.x, there was a command called link. With it, you could “link-install” a package so that changes would be reflected in real-time. This is especially handy when you’re actually building something. You could make a few changes, run the command again, and voila, your new code would be run without having to re-install every time.

    + +

    Of course, compiled modules still have to be rebuilt. That’s not ideal, but it’s a problem that will take more powerful magic to solve.

    + +

    In npm 0.x, this was a pretty awful kludge. Back then, every package existed in some folder like:

    + +
    prefix/lib/node/.npm/my-package/1.3.6/package
    +
    + +

    and the package’s version and name could be inferred from the path. Then, symbolic links were set up that looked like:

    + +
    prefix/lib/node/my-package@1.3.6 -> ./.npm/my-package/1.3.6/package
    +
    + +

    It was easy enough to point that symlink to a different location. However, since the package.json file could change, that meant that the connection between the version and the folder was not reliable.

    + +

    At first, this was just sort of something that we dealt with by saying, “Relink if you change the version.” However, as more and more edge cases arose, eventually the solution was to give link packages this fakey version of “9999.0.0-LINK-hash” so that npm knew it was an imposter. Sometimes the package was treated as if it had the 9999.0.0 version, and other times it was treated as if it had the version specified in the package.json.

    + +

    A better way

    + +

    For npm 1.0, we backed up and looked at what the actual use cases were. Most of the time when you link something you want one of the following:

    + +
      +
    1. globally install this package I’m working on so that I can run the command it creates and test its stuff as I work on it.
    2. +
    3. locally install my thing into some other thing that depends on it, so that the other thing can require() it.
    4. +
    + +

    And, in both cases, changes should be immediately apparent and not require any re-linking.

    + +

    Also, there’s a third use case that I didn’t really appreciate until I started writing more programs that had more dependencies:

    + +
    1. Globally install something, and use it in development in a bunch of projects, and then update them all at once so that they all use the latest version.

    + +

    Really, the second case above is a special-case of this third case.

    + + + +

    The first step is to link your local project into the global install space. (See global vs local installation for more on this global/local business.)

    + +

    I do this as I’m developing node projects (including npm itself).

    + +
    cd ~/dev/js/node-tap  # go into the project dir
    +npm link              # create symlinks into {prefix}
    +
    + +

    Because of how I have my computer set up, with /usr/local as my install prefix, I end up with a symlink from /usr/local/lib/node_modules/tap pointing to ~/dev/js/node-tap, and the executable linked to /usr/local/bin/tap.

    + +

    Of course, if you set your paths differently, then you’ll have different results. (That’s why I tend to talk in terms of prefix rather than /usr/local.)

    + + + +

    When you want to link the globally-installed package into your local development folder, you run npm link pkg where pkg is the name of the package that you want to install.

    + +

    For example, let’s say that I wanted to write some tap tests for my node-glob package. I’d first do the steps above to link tap into the global install space, and then I’d do this:

    + +
    cd ~/dev/js/node-glob  # go to the project that uses the thing.
    +npm link tap           # link the global thing into my project.
    +
    + +

    Now when I make changes in ~/dev/js/node-tap, they’ll be immediately reflected in ~/dev/js/node-glob/node_modules/tap.

    + + + +

    Let’s say I have 15 sites that all use express. I want the benefits of local development, but I also want to be able to update all my dev folders at once. You can globally install express, and then link it into your local development folder.

    + +
    npm install express -g  # install express globally
    +cd ~/dev/js/my-blog     # development folder one
    +npm link express        # link the global express into ./node_modules
    +cd ~/dev/js/photo-site  # other project folder
    +npm link express        # link express into here, as well
    +
    +                        # time passes
    +                        # TJ releases some new stuff.
    +                        # you want this new stuff.
    +
    +npm update express -g   # update the global install.
    +                        # this also updates my project folders.
    +
    + +

    Caveat: Not For Real Servers

    + +

    npm link is a development tool. It’s awesome for managing packages on your local development box. But deploying with npm link is basically asking for problems, since it makes it super easy to update things without realizing it.

    + +

    Caveat 2: Sorry, Windows!

    + +

    I highly doubt that a native Windows node will ever have comparable symbolic link support to what Unix systems provide. I know that there are junctions and such, and I've heard legends about symbolic links on Windows 7.

    + +

    When there is a native windows port of Node, if that native windows port has `fs.symlink` and `fs.readlink` support that is exactly identical to the way that they work on Unix, then this should work fine.

    + +

    But I wouldn't hold my breath. Any bugs about this not working on a native Windows system (ie, not Cygwin) will most likely be closed with wontfix.

    + + +

    Aside: Credit where Credit’s Due

    + +

    Back before the Great Package Management Wars of Node 0.1, before npm or kiwi or mode or seed.js could do much of anything, and certainly before any of them had more than 2 users, Mikeal Rogers invited me to the Couch.io offices for lunch to talk about this npm registry thingie I’d mentioned wanting to build. (That is, to convince me to use CouchDB for it.)

    + +

    Since he was volunteering to build the first version of it, and since couch is pretty much the ideal candidate for this use-case, it was an easy sell.

    + +

    While I was there, he said, “Look. You need to be able to link a project directory as if it was installed as a package, and then have it all Just Work. Can you do that?”

    + +

    I was like, “Well, I don’t know… I mean, there’s these edge cases, and it doesn’t really fit with the existing folder structure very well…”

    + +

    “Dude. Either you do it, or I’m going to have to do it, and then there’ll be another package manager in node, instead of writing a registry for npm, and it won’t be as good anyway. Don’t be python.”

    + +

    The rest is history.

    diff --git a/node-v0.8.14/doc/blog/npm/npm-1-0-released.md b/node-v0.8.14/doc/blog/npm/npm-1-0-released.md new file mode 100644 index 0000000..d91b279 --- /dev/null +++ b/node-v0.8.14/doc/blog/npm/npm-1-0-released.md @@ -0,0 +1,36 @@ +title: npm 1.0: Released +author: Isaac Schlueter +date: Sun May 01 2011 08:09:45 GMT-0700 (PDT) +status: publish +category: npm +slug: npm-1-0-released + +

    npm 1.0 has been released. Here are the highlights:

    + +
    • Global vs local installation
    • ls displays a tree, instead of being a remote search
    • No more “activation” concept - dependencies are nested
    • Updates to link command
    • Install script cleans up any 0.x cruft it finds. (That is, it removes old packages, so that they can be installed properly.)
    • Simplified “search” command. One line per package, rather than one line per version.
    • Renovated “completion” approach
    • More help topics
    • Simplified folder structure
    + +

    The focus is on npm being a development tool, rather than an apt-wannabe.

    + +

    Installing it

    + +

    To get the new version, run this command:

    + +
    curl http://npmjs.org/install.sh | sh 
    + +

    This will prompt to ask you if it’s ok to remove all the old 0.x cruft. If you want to not be asked, then do this:

    + +
    curl http://npmjs.org/install.sh | clean=yes sh 
    + +

    Or, if you want to not do the cleanup, and leave the old stuff behind, then do this:

    + +
    curl http://npmjs.org/install.sh | clean=no sh 
    + +

    A lot of people in the node community were brave testers and helped make this release a lot better (and swifter) than it would have otherwise been. Thanks :)

    + +

    Code Freeze

    + +

    npm will not have any major feature enhancements or architectural changes for at least 6 months. There are interesting developments planned that leverage npm in some ways, but it’s time to let the client itself settle. Also, I want to focus attention on some other problems for a little while.

    + +

    Of course, bug reports are always welcome.

    + +

    See you at NodeConf!

    diff --git a/node-v0.8.14/doc/blog/npm/npm-1-0-the-new-ls.md b/node-v0.8.14/doc/blog/npm/npm-1-0-the-new-ls.md new file mode 100644 index 0000000..9fef76c --- /dev/null +++ b/node-v0.8.14/doc/blog/npm/npm-1-0-the-new-ls.md @@ -0,0 +1,144 @@ +title: npm 1.0: The New "ls" +author: Isaac Schlueter +date: Thu Mar 17 2011 23:22:17 GMT-0700 (PDT) +status: publish +category: npm +slug: npm-1-0-the-new-ls + +

    This is the first in a series of hopefully more than 1 posts, each detailing some aspect of npm 1.0.

    + +

    In npm 0.x, the ls command was a combination of both searching the registry as well as reporting on what you have installed.

    + +

    As the registry has grown in size, this has gotten unwieldy. Also, since npm 1.0 manages dependencies differently, nesting them in node_modules folder and installing locally by default, there are different things that you want to view.

    + +

    The functionality of the ls command was split into two different parts. search is now the way to find things on the registry (and it only reports one line per package, instead of one line per version), and ls shows a tree view of the packages that are installed locally.

    + +

    Here’s an example of the output:

    + +
    $ npm ls
    +npm@1.0.0 /Users/isaacs/dev-src/js/npm
    +├── semver@1.0.1 
    +├─┬ ronn@0.3.5 
    +│ └── opts@1.2.1 
    +└─┬ express@2.0.0rc3 extraneous 
    +  ├─┬ connect@1.1.0 
    +  │ ├── qs@0.0.7 
    +  │ └── mime@1.2.1 
    +  ├── mime@1.2.1 
    +  └── qs@0.0.7
    +
    + +

    This is after I’ve done npm install semver ronn express in the npm source directory. Since express isn’t actually a dependency of npm, it shows up with that “extraneous” marker.

    + +

    Let’s see what happens when we create a broken situation:

    + +
    $ rm -rf ./node_modules/express/node_modules/connect
    +$ npm ls
    +npm@1.0.0 /Users/isaacs/dev-src/js/npm
    +├── semver@1.0.1 
    +├─┬ ronn@0.3.5 
    +│ └── opts@1.2.1 
    +└─┬ express@2.0.0rc3 extraneous 
    +  ├── UNMET DEPENDENCY connect >= 1.1.0 < 2.0.0
    +  ├── mime@1.2.1 
    +  └── qs@0.0.7
    +
    + +

    Tree views are great for human readability, but some times you want to pipe that stuff to another program. For that output, I took the same datastructure, but instead of building up a treeview string for each line, it spits out just the folders like this:

    + +
    $ npm ls -p
    +/Users/isaacs/dev-src/js/npm
    +/Users/isaacs/dev-src/js/npm/node_modules/semver
    +/Users/isaacs/dev-src/js/npm/node_modules/ronn
    +/Users/isaacs/dev-src/js/npm/node_modules/ronn/node_modules/opts
    +/Users/isaacs/dev-src/js/npm/node_modules/express
    +/Users/isaacs/dev-src/js/npm/node_modules/express/node_modules/connect
    +/Users/isaacs/dev-src/js/npm/node_modules/express/node_modules/connect/node_modules/qs
    +/Users/isaacs/dev-src/js/npm/node_modules/express/node_modules/connect/node_modules/mime
    +/Users/isaacs/dev-src/js/npm/node_modules/express/node_modules/mime
    +/Users/isaacs/dev-src/js/npm/node_modules/express/node_modules/qs
    +
    + +

    Since you sometimes want a bigger view, I added the --long option to (shorthand: -l) to spit out more info:

    + +
    $ npm ls -l
    +npm@1.0.0 
    +│ /Users/isaacs/dev-src/js/npm
    +│ A package manager for node
    +│ git://github.com/isaacs/npm.git
    +│ http://npmjs.org/
    +├── semver@1.0.1 
    +│   ./node_modules/semver
    +│   The semantic version parser used by npm.
    +│   git://github.com/isaacs/node-semver.git
    +├─┬ ronn@0.3.5 
    +│ │ ./node_modules/ronn
    +│ │ markdown to roff and html converter
    +│ └── opts@1.2.1 
    +│     ./node_modules/ronn/node_modules/opts
    +│     Command line argument parser written in the style of commonjs. To be used with node.js
    +└─┬ express@2.0.0rc3 extraneous 
    +  │ ./node_modules/express
    +  │ Sinatra inspired web development framework
    +  ├─┬ connect@1.1.0 
    +  │ │ ./node_modules/express/node_modules/connect
    +  │ │ High performance middleware framework
    +  │ │ git://github.com/senchalabs/connect.git
    +  │ ├── qs@0.0.7 
    +  │ │   ./node_modules/express/node_modules/connect/node_modules/qs
    +  │ │   querystring parser
    +  │ └── mime@1.2.1 
    +  │     ./node_modules/express/node_modules/connect/node_modules/mime
    +  │     A comprehensive library for mime-type mapping
    +  ├── mime@1.2.1 
    +  │   ./node_modules/express/node_modules/mime
    +  │   A comprehensive library for mime-type mapping
    +  └── qs@0.0.7 
    +      ./node_modules/express/node_modules/qs
    +      querystring parser
    +
    +$ npm ls -lp
    +/Users/isaacs/dev-src/js/npm:npm@1.0.0::::
    +/Users/isaacs/dev-src/js/npm/node_modules/semver:semver@1.0.1::::
    +/Users/isaacs/dev-src/js/npm/node_modules/ronn:ronn@0.3.5::::
    +/Users/isaacs/dev-src/js/npm/node_modules/ronn/node_modules/opts:opts@1.2.1::::
    +/Users/isaacs/dev-src/js/npm/node_modules/express:express@2.0.0rc3:EXTRANEOUS:::
    +/Users/isaacs/dev-src/js/npm/node_modules/express/node_modules/connect:connect@1.1.0::::
    +/Users/isaacs/dev-src/js/npm/node_modules/express/node_modules/connect/node_modules/qs:qs@0.0.7::::
    +/Users/isaacs/dev-src/js/npm/node_modules/express/node_modules/connect/node_modules/mime:mime@1.2.1::::
    +/Users/isaacs/dev-src/js/npm/node_modules/express/node_modules/mime:mime@1.2.1::::
    +/Users/isaacs/dev-src/js/npm/node_modules/express/node_modules/qs:qs@0.0.7::::
    +
    + +

    And, if you want to get at the globally-installed modules, you can use ls with the global flag:

    + +
    $ npm ls -g
    +/usr/local
    +├─┬ A@1.2.3 -> /Users/isaacs/dev-src/js/A
    +│ ├── B@1.2.3 -> /Users/isaacs/dev-src/js/B
    +│ └─┬ npm@0.3.15 
    +│   └── semver@1.0.1 
    +├─┬ B@1.2.3 -> /Users/isaacs/dev-src/js/B
    +│ └── A@1.2.3 -> /Users/isaacs/dev-src/js/A
    +├── glob@2.0.5 
    +├─┬ npm@1.0.0 -> /Users/isaacs/dev-src/js/npm
    +│ ├── semver@1.0.1 
    +│ └─┬ ronn@0.3.5 
    +│   └── opts@1.2.1 
    +└── supervisor@0.1.2 -> /Users/isaacs/dev-src/js/node-supervisor
    +
    +$ npm ls -gpl
    +/usr/local:::::
    +/usr/local/lib/node_modules/A:A@1.2.3::::/Users/isaacs/dev-src/js/A
    +/usr/local/lib/node_modules/A/node_modules/npm:npm@0.3.15::::/Users/isaacs/dev-src/js/A/node_modules/npm
    +/usr/local/lib/node_modules/A/node_modules/npm/node_modules/semver:semver@1.0.1::::/Users/isaacs/dev-src/js/A/node_modules/npm/node_modules/semver
    +/usr/local/lib/node_modules/B:B@1.2.3::::/Users/isaacs/dev-src/js/B
    +/usr/local/lib/node_modules/glob:glob@2.0.5::::
    +/usr/local/lib/node_modules/npm:npm@1.0.0::::/Users/isaacs/dev-src/js/npm
    +/usr/local/lib/node_modules/npm/node_modules/semver:semver@1.0.1::::/Users/isaacs/dev-src/js/npm/node_modules/semver
    +/usr/local/lib/node_modules/npm/node_modules/ronn:ronn@0.3.5::::/Users/isaacs/dev-src/js/npm/node_modules/ronn
    +/usr/local/lib/node_modules/npm/node_modules/ronn/node_modules/opts:opts@1.2.1::::/Users/isaacs/dev-src/js/npm/node_modules/ronn/node_modules/opts
    +/usr/local/lib/node_modules/supervisor:supervisor@0.1.2::::/Users/isaacs/dev-src/js/node-supervisor
    +
    + +

    Those -> flags are indications that the package is link-installed, which will be covered in the next installment.

    diff --git a/node-v0.8.14/doc/blog/release/0.6.21.md b/node-v0.8.14/doc/blog/release/0.6.21.md new file mode 100644 index 0000000..6257b68 --- /dev/null +++ b/node-v0.8.14/doc/blog/release/0.6.21.md @@ -0,0 +1,43 @@ +version: 0.6.21 +title: Version 0.6.21 (maintenance) +category: release +slug: node-v0-6-21-maintenance +date: Fri Aug 03 2012 14:44:02 GMT-0700 (PDT) + +2012.08.03 Version 0.6.21 (maintenance) + +* sunos: work around OS bug to prevent fs.watch() from spinning (Bryan Cantrill) + +* net: make pause/resume work with connecting sockets (Bert Belder) + + +Source Code: http://nodejs.org/dist/v0.6.21/node-v0.6.21.tar.gz + +Windows Installer: http://nodejs.org/dist/v0.6.21/node-v0.6.21.msi + +Windows x64 Files: http://nodejs.org/dist/v0.6.21/x64/ + +Macintosh Installer (Universal): http://nodejs.org/dist/v0.6.21/node-v0.6.21.pkg + +Other release files: http://nodejs.org/dist/v0.6.21/ + +Website: http://nodejs.org/docs/v0.6.21/ + +Documentation: http://nodejs.org/docs/v0.6.21/api/ + +Shasums: + +``` +04f58b0da23c3db291d84ac55a924332ad83c427 node-v0.6.21.pkg +31f564bf34c64b07cae3b9a88a87b4a08bab4dc5 node-v0.6.21.tar.gz +1e3184fe2cfe7140a88b5dcc9c2ec7d32f1f5af5 node.exe +b8887a056152622c08ee10f5867bd27910260477 node.exp +c6468ffe2e145e7db1bb3e2d66adb9f5d50271ad node.lib +2a896bcb7c83f2fa710650116580daf4ac5e6c4c node.msi +207441e8c3dc184c478367b775dc7ece1ee36501 node.pdb +715ad9946db5f97c54a53bdea6bbe9ba69f2f299 x64/node.exe +2fa2c2d82fedeec1ed8be5d908b790f473d4a7c2 x64/node.exp +b403cb71d4cf21e97a78d446403cedc9795bcf69 x64/node.lib +ef47520dbc6a1a68ec37d290c421031cfd670048 x64/node.msi +fb15e3991c420f3ae67ade92b11b07bb9112124a x64/node.pdb +``` diff --git a/node-v0.8.14/doc/blog/release/node-v0-4-10.md b/node-v0.8.14/doc/blog/release/node-v0-4-10.md new file mode 100644 index 0000000..5af354e --- /dev/null +++ b/node-v0.8.14/doc/blog/release/node-v0-4-10.md @@ -0,0 +1,25 @@ +version: 0.4.10 +title: Node v0.4.10 +author: ryandahl +date: Wed Jul 20 2011 07:36:38 GMT-0700 (PDT) +status: publish +category: release +slug: node-v0-4-10 + +2011.07.19, Version 0.4.10 (stable) +
    • #394 Fix Buffer drops last null character in UTF-8 +
    • #829 Backport r8577 from V8 (Ben Noordhuis) +
    • #877 Don't wait for HTTP Agent socket pool to establish connections. +
    • #915 Find kqueue on FreeBSD correctly (Brett Kiefer) +
    • #1085 HTTP: Fix race in abort/dispatch code (Stefan Rusu) +
    • #1274 debugger improvement (Yoshihiro Kikuchi) +
    • #1291 Properly respond to HEAD during end(body) hot path (Reid Burke) +
    • #1304 TLS: Fix race in abort/connection code (Stefan Rusu) +
    • #1360 Allow _ in url hostnames. +
    • Revert 37d529f8 - unbreaks debugger command parsing. +
    • Bring back global execScript +
    • Doc improvements
    + +Download: http://nodejs.org/dist/node-v0.4.10.tar.gz +Website: http://nodejs.org/docs/v0.4.10 +Documentation: http://nodejs.org/docs/v0.4.10/api diff --git a/node-v0.8.14/doc/blog/release/node-v0-4-11.md b/node-v0.8.14/doc/blog/release/node-v0-4-11.md new file mode 100644 index 0000000..0bcbc37 --- /dev/null +++ b/node-v0.8.14/doc/blog/release/node-v0-4-11.md @@ -0,0 +1,39 @@ +version: 0.4.11 +title: Node v0.4.11 +author: ryandahl +date: Thu Aug 18 2011 01:44:42 GMT-0700 (PDT) +status: publish +category: release +slug: node-v0-4-11 + +2011.08.17, Version 0.4.11 (stable) +
    • #738 Fix crypto encryption/decryption with Base64. (SAWADA Tadashi) + +
    • #1202 net.createConnection defer DNS lookup error events to next tick (Ben Noordhuis) + +
    • #1374 fix setting ServerResponse.statusCode in writeHead (Trent Mick) + +
    • #1417 Fix http.ClientRequest crashes if end() was called twice + +
    • #1497 querystring: Replace 'in' test with 'hasOwnProperty' (isaacs) + +
    • #1546 http perf improvement + +
    • fix memleak in libeio (Tom Hughes) + +
    • cmake improvements (Tom Hughes) + +
    • node_net.cc: fix incorrect sizeof() (Tom Hughes) + +
    • Windows/cygwin: no more GetConsoleTitleW errors on XP (Bert Belder) + +
    • Doc improvements (koichik, Logan Smyth, Ben Noordhuis, Arnout Kazemier)
    + + + + +Download: http://nodejs.org/dist/node-v0.4.11.tar.gz + +Website: http://nodejs.org/docs/v0.4.11/ + +Documentation: http://nodejs.org/docs/v0.4.11/api/ diff --git a/node-v0.8.14/doc/blog/release/node-v0-4-12.md b/node-v0.8.14/doc/blog/release/node-v0-4-12.md new file mode 100644 index 0000000..8eb53d1 --- /dev/null +++ b/node-v0.8.14/doc/blog/release/node-v0-4-12.md @@ -0,0 +1,29 @@ +version: 0.4.12 +title: Node v0.4.12 +author: ryandahl +date: Thu Sep 15 2011 17:32:07 GMT-0700 (PDT) +status: publish +category: release +slug: node-v0-4-12 + +2011.09.15, Version 0.4.12 (stable) + +
      +
    • Improve docs +
    • #1563 overflow in ChildProcess custom_fd. +
    • #1569, parse error on multi-line HTTP headers. (Ben Noordhuis) +
    • #1586 net: Socket write encoding case sensitivity (koichik) +
    • #1610 Remove DigiNotar CA from trusted list (isaacs) +
    • #1624 buffer: Avoid overrun with 'binary' encoding. (koichik) +
    • #1633 buffer: write() should always set _charsWritten. (koichik) +
    • #1707 hasOwnProperty usage security hole in querystring (isaacs) +
    • #1719 Drain OpenSSL error queue +
    • Fix error reporting in net.Server.listen
    + + + +Download: http://nodejs.org/dist/node-v0.4.12.tar.gz + +Website: http://nodejs.org/docs/v0.4.12/ + +Documentation: http://nodejs.org/docs/v0.4.12/api/ diff --git a/node-v0.8.14/doc/blog/release/node-v0-4-3.md b/node-v0.8.14/doc/blog/release/node-v0-4-3.md new file mode 100644 index 0000000..10a3a5b --- /dev/null +++ b/node-v0.8.14/doc/blog/release/node-v0-4-3.md @@ -0,0 +1,33 @@ +version: 0.4.3 +title: Node v0.4.3 +author: ryandahl +date: Fri Mar 18 2011 22:17:59 GMT-0700 (PDT) +status: publish +category: release +slug: node-v0-4-3 + +2011.03.18, Version 0.4.3 (stable) +
      +
    • Don't decrease server connection counter again if destroy() is called more than once GH-431 (Andreas Reich, Anders Conbere) +
    • Documentation improvements (koichik) +
    • Fix bug with setMaxListeners GH-682 +
    • Start up memory footprint improvement. (Tom Hughes) +
    • Solaris improvements. +
    • Buffer::Length(Buffer*) should not invoke itself recursively GH-759 (Ben Noordhuis) +
    • TLS: Advertise support for client certs GH-774 (Theo Schlossnagle) +
    • HTTP Agent bugs: GH-787, GH-784, GH-803. +
    • Don't call GetMemoryUsage every 5 seconds. +
    • Upgrade V8 to 3.1.8.3 +
    + + + +Download: http://nodejs.org/dist/node-v0.4.3.tar.gz + +Website: http://nodejs.org/docs/v0.4.3/ + +Documentation: http://nodejs.org/docs/v0.4.3/api + +Announcement + +commit diff --git a/node-v0.8.14/doc/blog/release/node-v0-4-4.md b/node-v0.8.14/doc/blog/release/node-v0-4-4.md new file mode 100644 index 0000000..417d73c --- /dev/null +++ b/node-v0.8.14/doc/blog/release/node-v0-4-4.md @@ -0,0 +1,27 @@ +version: 0.4.4 +title: Node v0.4.4 +author: ryandahl +date: Sat Mar 26 2011 08:58:45 GMT-0700 (PDT) +status: publish +category: release +slug: node-v0-4-4 + +2011.03.26, Version 0.4.4 (stable) +
      +
    • CryptoStream.end shouldn't throw if not writable GH-820 +
    • Drop out if connection destroyed before connect() GH-819 +
    • expose https.Agent +
    • Correctly setsid in tty.open GH-815 +
    • Bug fix for failed buffer construction +
    • Added support for removing .once listeners (GH-806) +
    • Upgrade V8 to 3.1.8.5
    + + + +Download: http://nodejs.org/dist/node-v0.4.4.tar.gz + +Website: http://nodejs.org/docs/v0.4.4 + +Documentation: http://nodejs.org/docs/v0.4.4/api + +announcement diff --git a/node-v0.8.14/doc/blog/release/node-v0-4-5.md b/node-v0.8.14/doc/blog/release/node-v0-4-5.md new file mode 100644 index 0000000..6935de0 --- /dev/null +++ b/node-v0.8.14/doc/blog/release/node-v0-4-5.md @@ -0,0 +1,29 @@ +version: 0.4.5 +title: node v0.4.5 +author: ryandahl +date: Sat Apr 02 2011 02:04:58 GMT-0700 (PDT) +status: publish +category: release +slug: node-v0-4-5 + +2011.04.01, Version 0.4.5 (stable) +
      +
    • Fix listener leak in stream.pipe() (Mikeal Rogers) +
    • Retain buffers in fs.read/write() GH-814 (Jorge Chamorro Bieling) +
    • TLS performance improvements +
    • SlowBuffer.prototype.slice bug GH-843 +
    • process.stderr.write should return true +
    • Immediate pause/resume race condition GH-535 (isaacs) +
    • Set default host header properly GH-721 (isaacs) +
    • Upgrade V8 to 3.1.8.8
    + + + +Download: http://nodejs.org/dist/node-v0.4.5.tar.gz + +Website: http://nodejs.org/docs/v0.4.5 + +Documentation: http://nodejs.org/docs/v0.4.5/api + + +announcement diff --git a/node-v0.8.14/doc/blog/release/node-v0-4-6.md b/node-v0.8.14/doc/blog/release/node-v0-4-6.md new file mode 100644 index 0000000..964f3a2 --- /dev/null +++ b/node-v0.8.14/doc/blog/release/node-v0-4-6.md @@ -0,0 +1,27 @@ +version: 0.4.6 +title: Node v0.4.6 +author: ryandahl +date: Thu Apr 14 2011 05:00:30 GMT-0700 (PDT) +status: publish +category: release +slug: node-v0-4-6 + +2011.04.13, Version 0.4.6 (stable) +
    • Don't error on ENOTCONN from shutdown() #670 +
    • Auto completion of built-in debugger suggests prefix match rather than partial match. (koichik) +
    • circular reference in vm modules. #822 (Jakub Lekstan) +
    • http response.readable should be false after 'end' #867 (Abe Fettig) +
    • Implemenet os.cpus() and os.uptime() on Solaris (Scott McWhirter) +
    • fs.ReadStream: Allow omission of end option for range reads #801 (Felix Geisendörfer) +
    • Buffer.write() with UCS-2 should not be write partial char #916 (koichik) +
    • Pass secureProtocol through on tls.Server creation (Theo Schlossnagle) +
    • TLS use RC4-SHA by default +
    • Don't strangely drop out of event loop on HTTPS client uploads #892 +
    • Doc improvements +
    • Upgrade v8 to 3.1.8.10
    + +Download: http://nodejs.org/dist/node-v0.4.6.tar.gz + +Website: http://nodejs.org/docs/v0.4.6/ + +Documentation: http://nodejs.org/docs/v0.4.6/api/ diff --git a/node-v0.8.14/doc/blog/release/node-v0-4-7.md b/node-v0.8.14/doc/blog/release/node-v0-4-7.md new file mode 100644 index 0000000..44e2715 --- /dev/null +++ b/node-v0.8.14/doc/blog/release/node-v0-4-7.md @@ -0,0 +1,23 @@ +version: 0.4.7 +title: Node v0.4.7 +author: ryandahl +date: Sat Apr 23 2011 00:47:55 GMT-0700 (PDT) +status: publish +category: release +slug: node-v0-4-7 + +2011.04.22, Version 0.4.7 (stable) +
    • Don't emit error on ECONNRESET from read() #670 +
    • Fix: Multiple pipes to the same stream were broken #929 (Felix Geisendörfer) +
    • URL parsing/formatting corrections #954 (isaacs) +
    • make it possible to do repl.start('', stream) (Wade Simmons) +
    • Add os.loadavg for SunOS (Robert Mustacchi) +
    • Fix timeouts with floating point numbers #897 (Jorge Chamorro Bieling) +
    • Improve docs.
    + + +Download: http://nodejs.org/dist/node-v0.4.7.tar.gz + +Website: http://nodejs.org/docs/v0.4.7/ + +Documentation: http://nodejs.org/docs/v0.4.7/api diff --git a/node-v0.8.14/doc/blog/release/node-v0-4-8.md b/node-v0.8.14/doc/blog/release/node-v0-4-8.md new file mode 100644 index 0000000..a25aedf --- /dev/null +++ b/node-v0.8.14/doc/blog/release/node-v0-4-8.md @@ -0,0 +1,55 @@ +version: 0.4.8 +title: Node v0.4.8 +author: ryandahl +date: Sat May 21 2011 07:06:00 GMT-0700 (PDT) +status: publish +category: release +slug: node-v0-4-8 + +2011.05.20, Version 0.4.8 (stable) + +* #974 Properly report traceless errors (isaacs) + +* #983 Better JSON.parse error detection in REPL (isaacs) + +* #836 Agent socket errors bubble up to req only if req exists + +* #1041 Fix event listener leak check timing (koichik) + +* #1038 Fix dns.resolve() with 'PTR' throws Error: Unknown type "PTR" + (koichik) + +* #1073 Share SSL context between server connections (Fedor Indutny) + +* Disable compression with OpenSSL. Improves memory perf. + +* Implement os.totalmem() and os.freemem() for SunOS (Alexandre Marangone) + +* Fix a special characters in URL regression (isaacs) + +* Fix idle timeouts in HTTPS (Felix Geisendörfer) + +* SlowBuffer.write() with 'ucs2' throws ReferenceError. (koichik) + +* http.ServerRequest 'close' sometimes gets an error argument + (Felix Geisendörfer) + +* Doc improvements + +* cleartextstream.destroy() should close(2) the socket. Previously was being + mapped to a shutdown(2) syscall. + +* No longer compile out asserts and debug statements in normal build. + +* Debugger improvements. + +* Upgrade V8 to 3.1.8.16. + + + + +Website: http://nodejs.org/docs/v0.4.8/ + +Download: http://nodejs.org/dist/node-v0.4.8.tar.gz + +Documentation: http://nodejs.org/docs/v0.4.8/api/ diff --git a/node-v0.8.14/doc/blog/release/node-v0-4-9.md b/node-v0.8.14/doc/blog/release/node-v0-4-9.md new file mode 100644 index 0000000..8b71bd9 --- /dev/null +++ b/node-v0.8.14/doc/blog/release/node-v0-4-9.md @@ -0,0 +1,30 @@ +version: 0.4.9 +title: Node v0.4.9 +author: ryandahl +date: Wed Jun 29 2011 11:41:05 GMT-0700 (PDT) +status: publish +category: release +slug: node-v0-4-9 + +2011.06.29, Version 0.4.9 (stable)
      +
    • Improve documentation +
    • #1095 error handling bug in stream.pipe() (Felix Geisendörfer) +
    • #1097 Fix a few leaks in node_crypto.cc (Ben Noordhuis) +
    • #562 #1078 Parse file:// urls properly (Ryan Petrello) +
    • #880 Option to disable SSLv2 (Jérémy Lal) +
    • #1087 Disabling SSL compression disabled with early OpenSSLs. +
    • #1144 debugger: don't allow users to input non-valid commands (Siddharth Mahendraker) +
    • Perf improvement for util.inherits +
    • #1166 Support for signature verification with RSA/DSA public keys (Mark Cavage) +
    • #1177 Remove node_modules lookup optimization to better support nested project structures (Mathias Buus) +
    • #1203 Add missing scope.Close to fs.sendfileSync +
    • #1187 Support multiple 'link' headers +
    • #1196 Fix -e/--eval can't load module from node_modules (Koichi Kobayashi) +
    • Upgrade V8 to 3.1.8.25, upgrade http-parser.
    + + +Download: http://nodejs.org/dist/node-v0.4.9.tar.gz + +Website: http://nodejs.org/docs/v0.4.9 + +Documentation: http://nodejs.org/docs/v0.4.9/api diff --git a/node-v0.8.14/doc/blog/release/node-v0-5-0-unstable.md b/node-v0.8.14/doc/blog/release/node-v0-5-0-unstable.md new file mode 100644 index 0000000..68ff2d1 --- /dev/null +++ b/node-v0.8.14/doc/blog/release/node-v0-5-0-unstable.md @@ -0,0 +1,39 @@ +version: 0.5.0 +title: Node v0.5.0 (Unstable) +author: ryandahl +date: Wed Jul 06 2011 02:23:17 GMT-0700 (PDT) +status: publish +category: release +slug: node-v0-5-0-unstable + +2011.07.05, Version 0.5.0 (unstable) + +
  • New non-default libuv backend to support IOCP on Windows. Use --use-uv to enable. +
  • deprecate http.cat +
  • docs improved. +
  • add child_process.fork +
  • add fs.utimes() and fs.futimes() support (Ben Noordhuis) +
  • add process.uptime() (Tom Huges) +
  • add path.relative (Tony Huang) +
  • add os.getNetworkInterfaces() +
  • add remoteAddress and remotePort for client TCP connections (Brian White) +
  • add secureOptions flag, setting ciphers, SSL_OP_CRYPTOPRO_TLSEXT_BUG to TLS (Theo Schlossnagle) +
  • add process.arch (Nathan Rajlich) +
  • add reading/writing of floats and doubles from/to buffers (Brian White) +
  • Allow script to be read from stdin +
  • #477 add Buffer::fill method to do memset (Konstantin Käfer) +
  • #573 Diffie-Hellman support to crypto module (Håvard Stranden) +
  • #695 add 'hex' encoding to buffer (isaacs) +
  • #851 Update how REPLServer uses contexts (Ben Weaver) +
  • #853 add fs.lchow, fs.lchmod, fs.fchmod, fs.fchown (isaacs) +
  • #889 Allow to remove all EventEmitter listeners at once (Felix Geisendörfer) +
  • #926 OpenSSL NPN support (Fedor Indutny) +
  • #955 Change ^C handling in REPL (isaacs) +
  • #979 add support for Unix Domain Sockets to HTTP (Mark Cavage) +
  • #1173 #1170 add AMD, asynchronous module definition (isaacs) +
  • DTrace probes: support X-Forwarded-For (Dave Pacheco)
+Download: http://nodejs.org/dist/node-v0.5.0.tar.gz + +Website: http://nodejs.org/docs/v0.5.0/ + +Documentation: http://nodejs.org/docs/v0.5.0/api/ diff --git a/node-v0.8.14/doc/blog/release/node-v0-5-1.md b/node-v0.8.14/doc/blog/release/node-v0-5-1.md new file mode 100644 index 0000000..8137e8c --- /dev/null +++ b/node-v0.8.14/doc/blog/release/node-v0-5-1.md @@ -0,0 +1,30 @@ +version: 0.5.1 +title: Node v0.5.1 +author: ryandahl +date: Thu Jul 14 2011 23:48:08 GMT-0700 (PDT) +status: publish +category: release +slug: node-v0-5-1 + +2011.07.14, Version 0.5.1 (unstable) +
  • #1233 Fix os.totalmem on FreeBSD amd64 (Artem Zaytsev) +
  • #1149 IDNA and Punycode support in url.parse (Jeremy Selier, Ben Noordhuis, isaacs) +
  • Export $CC and $CXX to uv and V8's build systems +
  • Include pthread-win32 static libraries in build (Igor Zinkovsky) +
  • #1199, #1094 Fix fs can't handle large file on 64bit platform (koichik) +
  • #1281 Make require a public member of module (isaacs) +
  • #1303 Stream.pipe returns the destination (Elijah Insua) +
  • #1229 Addons should not -DEV_MULTIPLICITY=0 (Brian White) +
  • libuv backend improvements +
  • Upgrade V8 to 3.4.10
+ + + + +Download: http://nodejs.org/dist/v0.5.1/node-v0.5.1.tar.gz + +Windows Build: http://nodejs.org/dist/v0.5.1/node.exe + +Documentation: http://nodejs.org/dist/v0.5.1/docs/api/ + +Website: http://nodejs.org/dist/v0.5.1/docs diff --git a/node-v0.8.14/doc/blog/release/node-v0-5-10.md b/node-v0.8.14/doc/blog/release/node-v0-5-10.md new file mode 100644 index 0000000..305813e --- /dev/null +++ b/node-v0.8.14/doc/blog/release/node-v0-5-10.md @@ -0,0 +1,41 @@ +version: 0.5.10 +title: Node v0.5.10 +author: ryandahl +date: Fri Oct 21 2011 19:12:31 GMT-0700 (PDT) +status: publish +category: release +slug: node-v0-5-10 + +2011.10.21, Version 0.5.10 (unstable) +
  • Remove cmake build system, support for Cygwin, legacy code base, process.ENV, process.ARGV, process.memoryUsage().vsize, os.openOSHandle
  • +
  • Documentation improvments (Igor Zinkovsky, Bert Belder, Ilya Dmitrichenko, koichik, Maciej Małecki, Guglielmo Ferri, isaacs)
  • +
  • Performance improvements (Daniel Ennis, Bert Belder, Ben Noordhuis)
  • +
  • Long process.title support (Ben Noordhuis)
  • +
  • net: register net.Server callback only once (Simen Brekken)
  • +
  • net: fix connect queue bugs (Ben Noordhuis)
  • +
  • debugger: fix backtrace err handling (Fedor Indutny)
  • +
  • Use getaddrinfo instead of c-ares for dns.lookup
  • +
  • Emit 'end' from crypto streams on close
  • +
  • repl: print out `undefined` (Nathan Rajlich)
  • +
  • #1902 buffer: use NO_NULL_TERMINATION flag (koichik)
  • +
  • #1907 http: Added support for HTTP PATCH verb (Thomas Parslow)
  • +
  • #1644 add GetCPUInfo on windows (Karl Skomski)
  • +
  • #1484, #1834, #1482, #771 Don't use a separate context for the repl. (isaacs)
  • +
  • #1882 zlib Update 'availOutBefore' value, and test (isaacs)
  • +
  • #1888 child_process.fork: don't modify args (koichik)
  • +
  • #1516 tls: requestCert unusable with Firefox and Chrome (koichik)
  • +
  • #1467 tls: The TLS API is inconsistent with the TCP API (koichik)
  • +
  • #1894 net: fix error handling in listen() (koichik)
  • +
  • #1860 console.error now goes through uv_tty_t
  • +
  • Upgrade V8 to 3.7.0
  • +
  • Upgrade GYP to r1081
+ + + +Download: http://nodejs.org/dist/v0.5.10/node-v0.5.10.tar.gz + +Windows Executable: http://nodejs.org/dist/v0.5.10/node.exe + +Website: http://nodejs.org/docs/v0.5.10/ + +Documentation: http://nodejs.org/docs/v0.5.10/api/ diff --git a/node-v0.8.14/doc/blog/release/node-v0-5-2.md b/node-v0.8.14/doc/blog/release/node-v0-5-2.md new file mode 100644 index 0000000..e87fda3 --- /dev/null +++ b/node-v0.8.14/doc/blog/release/node-v0-5-2.md @@ -0,0 +1,27 @@ +version: 0.5.2 +title: Node v0.5.2 +author: ryandahl +date: Fri Jul 22 2011 11:40:22 GMT-0700 (PDT) +status: publish +category: release +slug: node-v0-5-2 + +2011.07.22, Version 0.5.2 (unstable) +
  • libuv improvements; named pipe support +
  • #1242 check for SSL_COMP_get_compression_methods() (Ben Noordhuis) +
  • #1348 remove require.paths (isaacs) +
  • #1349 Delimit NODE_PATH with ; on Windows (isaacs) +
  • #1335 Remove EventEmitter from C++ +
  • #1357 Load json files with require() (isaacs) +
  • #1374 fix setting ServerResponse.statusCode in writeHead (Trent Mick) +
  • Fixed: GC was being run too often. +
  • Upgrade V8 to 3.4.14 +
  • doc improvements
+ +Download: http://nodejs.org/dist/v0.5.2/node-v0.5.2.tar.gz + +Windows Executable: http://nodejs.org/dist/v0.5.2/node.exe + +Website: http://nodejs.org/dist/v0.5.2/docs/ + +Documentation: http://nodejs.org/dist/v0.5.2/docs/api diff --git a/node-v0.8.14/doc/blog/release/node-v0-5-3.md b/node-v0.8.14/doc/blog/release/node-v0-5-3.md new file mode 100644 index 0000000..0b9e7b8 --- /dev/null +++ b/node-v0.8.14/doc/blog/release/node-v0-5-3.md @@ -0,0 +1,53 @@ +version: 0.5.3 +title: Node v0.5.3 +author: ryandahl +date: Tue Aug 02 2011 08:03:06 GMT-0700 (PDT) +status: publish +category: release +slug: node-v0-5-3 + +2011.08.01, Version 0.5.3 (unstable) + +
  • Fix crypto encryption/decryption with Base64. (SAWADA Tadashi) + +
  • #243 Add an optional length argument to Buffer.write() (koichik) + +
  • #657 convert nonbuffer data to string in fs.writeFile/Sync (Daniel Pihlström) + +
  • Add process.features, remove process.useUV (Ben Noordhuis) + +
  • #324 Fix crypto hmac to accept binary keys + add test cases from rfc 2202 and 4231 (Stefan Bühler) + +
  • Add Socket::bytesRead, Socket::bytesWritten (Alexander Uvarov) + +
  • #572 Don't print result of --eval in CLI (Ben Noordhuis) + +
  • #1223 Fix http.ClientRequest crashes if end() was called twice (koichik) + +
  • #1383 Emit 'close' after all connections have closed (Felix Geisendörfer) + +
  • Add sprintf-like util.format() function (Ben Noordhuis) + +
  • Add support for TLS SNI (Fedor Indutny) + +
  • New http agent implementation. Off by default the command line flag --use-http2 will enable it. make test-http2 will run the tests for the new implementation. (Mikeal Rogers) + +
  • Revert AMD compatibility. (isaacs) + +
  • Windows: improvements, child_process support. + +
  • Remove pkg-config file. + +
  • Fix startup time regressions. + +
  • doc improvements
+ + + +Download: http://nodejs.org/dist/v0.5.3/node-v0.5.3.tar.gz + +Windows Executable: http://nodejs.org/dist/v0.5.3/node.exe + +Website: http://nodejs.org/dist/v0.5.3/docs + +Documentation: http://nodejs.org/dist/v0.5.3/docs/api diff --git a/node-v0.8.14/doc/blog/release/node-v0-5-4.md b/node-v0.8.14/doc/blog/release/node-v0-5-4.md new file mode 100644 index 0000000..9f5f4e2 --- /dev/null +++ b/node-v0.8.14/doc/blog/release/node-v0-5-4.md @@ -0,0 +1,36 @@ +version: 0.5.4 +title: Node v0.5.4 +author: ryandahl +date: Fri Aug 12 2011 08:38:26 GMT-0700 (PDT) +status: publish +category: release +slug: node-v0-5-4 + +2011.08.12, Version 0.5.4 (unstable) + +
  • libuv/Windows compatibility improvements + +
  • Build on Microsoft Visual Studio via GYP. Use generate-projects.bat in the to build sln files. (Peter Bright, Igor Zinkovsky) + +
  • Make Mikeal's HTTP agent client the default. Use old HTTP client with --use-http1 + +
  • Fixes https host header default port handling. (Mikeal Rogers) + +
  • #1440 strip byte order marker when loading *.js and *.json files (Ben Noordhuis) + +
  • #1434 Improve util.format() compatibility with browser. (Koichi Kobayashi) + +
  • Provide unchecked uint entry points for integer Buffer.read/writeInt methods. (Robert Mustacchi) + +
  • CMake improvements (Tom Huges) + +
  • Upgrade V8 to 3.5.4.
+ + +Download: http://nodejs.org/dist/v0.5.4/node-v0.5.4.tar.gz + +Windows Executable: http://nodejs.org/dist/v0.5.4/node.exe + +Website: http://nodejs.org/dist/v0.5.4/docs + +Documentation: http://nodejs.org/dist/v0.5.4/docs/api diff --git a/node-v0.8.14/doc/blog/release/node-v0-5-5.md b/node-v0.8.14/doc/blog/release/node-v0-5-5.md new file mode 100644 index 0000000..683fed4 --- /dev/null +++ b/node-v0.8.14/doc/blog/release/node-v0-5-5.md @@ -0,0 +1,40 @@ +version: 0.5.5 +title: Node v0.5.5 +author: bennoordhuis +date: Fri Aug 26 2011 23:20:10 GMT-0700 (PDT) +status: publish +category: release +slug: node-v0-5-5 + +

2011.08.26, Version 0.5.5 (unstable)

+
    +
  • typed arrays, implementation from Plesk +
  • fix IP multicast on SunOS +
  • fix DNS lookup order: IPv4 first, IPv6 second (--use-uv only) +
  • remove support for UNIX datagram sockets (--use-uv only) +
  • UDP support for Windows (Bert Belder) +
  • #1572 improve tab completion for objects in the REPL (Nathan Rajlich) +
  • #1563 fix buffer overflow in child_process module (reported by Dean McNamee) +
  • #1546 fix performance regression in http module (reported by Brian Geffon) +
  • #1491 add PBKDF2 crypto support (Glen Low) +
  • #1447 remove deprecated http.cat() function (Mikeal Rogers) +
  • #1140 fix incorrect dispatch of vm.runInContext's filename argument
    + (Antranig Basman)

    +
  • #1140 document vm.runInContext() and vm.createContext() (Antranig Basman) +
  • #1428 fix os.freemem() on 64 bits freebsd (Artem Zaytsev) +
  • #1164 make all DNS lookups async, fixes uncatchable exceptions
    + (Koichi Kobayashi)

    +
  • fix incorrect ssl shutdown check (Tom Hughes) +
  • various cmake fixes (Tom Hughes) +
  • improved documentation (Koichi Kobayashi, Logan Smyth, Fedor Indutny,
    + Mikeal Rogers, Maciej Małecki, Antranig Basman, Mickaël Delahaye)

    +
  • upgrade libuv to commit 835782a +
  • upgrade V8 to 3.5.8 +
+

Download: http://nodejs.org/dist/node-v0.5.5.tar.gz

+

Windows Executable: http://nodejs.org/dist/v0.5.5/node.exe

+

Website: http://nodejs.org/docs/v0.5.5/

+

Documentation: http://nodejs.org/docs/v0.5.5/api/

+

+ +Update: The .exe has a bug that results in incompatibility with Windows XP and Server 2003. This has been reported in issue #1592 and fixed. A new binary was made that is compatibile with the older Windows: http://nodejs.org/dist/v0.5.5/node-186364e.exe. diff --git a/node-v0.8.14/doc/blog/release/node-v0-5-6.md b/node-v0.8.14/doc/blog/release/node-v0-5-6.md new file mode 100644 index 0000000..452878c --- /dev/null +++ b/node-v0.8.14/doc/blog/release/node-v0-5-6.md @@ -0,0 +1,49 @@ +version: 0.5.6 +title: Node v0.5.6 (unstable) +author: piscisaureus +date: Fri Sep 09 2011 16:30:39 GMT-0700 (PDT) +status: publish +category: release +slug: node-v0-5-6 + +2011.09.08, Version 0.5.6 (unstable) +
    +
  • #345, #1635, #1648 Documentation improvements (Thomas Shinnick, Abimanyu Raja, AJ ONeal, Koichi Kobayashi, Michael Jackson, Logan Smyth, Ben Noordhuis)
  • +
  • #650 Improve path parsing on windows (Bert Belder)
  • +
  • #752 Remove headers sent check in OutgoingMessage.getHeader() (Peter Lyons)
  • +
  • #1236, #1438, #1506, #1513, #1621, #1640, #1647 Libuv-related bugs fixed (Jorge Chamorro Bieling, Peter Bright, Luis Lavena, Igor Zinkovsky)
  • +
  • #1296, #1612 crypto: Fix BIO's usage. (Koichi Kobayashi)
  • +
  • #1345 Correctly set socket.remoteAddress with libuv backend (Bert Belder)
  • +
  • #1429 Don't clobber quick edit mode on windows (Peter Bright)
  • +
  • #1503 Make libuv backend default on unix, override with `node --use-legacy`
  • +
  • #1565 Fix fs.stat for paths ending with \ on windows (Igor Zinkovsky)
  • +
  • #1568 Fix x509 certificate subject parsing (Koichi Kobayashi)
  • +
  • #1586 Make socket write encoding case-insensitive (Koichi Kobayashi)
  • +
  • #1591, #1656, #1657 Implement fs in libuv, remove libeio and pthread-win32 dependency on windows (Igor Zinkovsky, Ben Noordhuis, Ryan Dahl, Isaac Schlueter)
  • +
  • #1592 Don't load-time link against CreateSymbolicLink on windows (Peter Bright)
  • +
  • #1601 Improve API consistency when dealing with the socket underlying a HTTP client request (Mikeal Rogers)
  • +
  • #1610 Remove DigiNotar CA from trusted list (Isaac Schlueter)
  • +
  • #1617 Added some win32 os functions (Karl Skomski)
  • +
  • #1624 avoid buffer overrun with 'binary' encoding (Koichi Kobayashi)
  • +
  • #1633 make Buffer.write() always set _charsWritten (Koichi Kobayashi)
  • +
  • #1644 Windows: set executables to be console programs (Peter Bright)
  • +
  • #1651 improve inspection for sparse array (Koichi Kobayashi)
  • +
  • #1672 set .code='ECONNRESET' on socket hang up errors (Ben Noordhuis)
  • +
  • Add test case for foaf+ssl client certificate (Niclas Hoyer)
  • +
  • Added RPATH environment variable to override run-time library paths (Ashok Mudukutore)
  • +
  • Added TLS client-side session resumption support (Sean Cunningham)
  • +
  • Added additional properties to getPeerCertificate (Nathan Rixham, Niclas Hoyer)
  • +
  • Don't eval repl command twice when an error is thrown (Nathan Rajlich)
  • +
  • Improve util.isDate() (Nathan Rajlich)
  • +
  • Improvements in libuv backend and bindings, upgrade libuv to bd6066cb349a9b3a1b0d87b146ddaee06db31d10
  • +
  • Show warning when using lib/sys.js (Maciej Malecki)
  • +
  • Support plus sign in url protocol (Maciej Malecki)
  • +
  • Upgrade V8 to 3.6.2
  • +
+Download: http://nodejs.org/dist/v0.5.6/node-v0.5.6.tar.gz + +Windows Executable: http://nodejs.org/dist/v0.5.6/node.exe + +Website: http://nodejs.org/docs/v0.5.6/ + +Documentation: http://nodejs.org/docs/v0.5.6/api/ diff --git a/node-v0.8.14/doc/blog/release/node-v0-5-7-unstable.md b/node-v0.8.14/doc/blog/release/node-v0-5-7-unstable.md new file mode 100644 index 0000000..b125a14 --- /dev/null +++ b/node-v0.8.14/doc/blog/release/node-v0-5-7-unstable.md @@ -0,0 +1,35 @@ +version: 0.5.7 +title: Node v0.5.7 (unstable) +author: ryandahl +date: Fri Sep 16 2011 18:57:03 GMT-0700 (PDT) +status: publish +category: release +slug: node-v0-5-7-unstable + +2011.09.16, Version 0.5.7 (unstable) +
    +
  • Upgrade V8 to 3.6.4 +
  • Improve Windows compatibility +
  • Documentation improvements +
  • Debugger and REPL improvements (Fedor Indutny) +
  • Add legacy API support: net.Stream(fd), process.stdout.writable, process.stdout.fd +
  • Fix mkdir EEXIST handling (isaacs) +
  • Use net_uv instead of net_legacy for stdio +
  • Do not load readline from util.inspect +
  • #1673 Fix bug related to V8 context with accessors (Fedor Indutny) +
  • #1634 util: Fix inspection for Error (koichik) +
  • #1645 fs: Add positioned file writing feature to fs.WriteStream (Thomas Shinnick) +
  • #1637 fs: Unguarded fs.watchFile cache statWatchers checking fixed (Thomas Shinnick) +
  • #1695 Forward customFds to ChildProcess.spawn +
  • #1707 Fix hasOwnProperty security problem in querystring (isaacs) +
  • #1719 Drain OpenSSL error queue
+ + + +Download: http://nodejs.org/dist/v0.5.7/node-v0.5.7.tar.gz + +Windows Executable: http://nodejs.org/dist/v0.5.7/node.exe + +Website: http://nodejs.org/docs/v0.5.7/ + +Documentation: http://nodejs.org/docs/v0.5.7/api/ diff --git a/node-v0.8.14/doc/blog/release/node-v0-5-8.md b/node-v0.8.14/doc/blog/release/node-v0-5-8.md new file mode 100644 index 0000000..6924ff3 --- /dev/null +++ b/node-v0.8.14/doc/blog/release/node-v0-5-8.md @@ -0,0 +1,26 @@ +version: 0.5.8 +title: Node v0.5.8 +author: ryandahl +date: Fri Sep 30 2011 16:47:11 GMT-0700 (PDT) +status: publish +category: release +slug: node-v0-5-8 + +2011.09.30, Version 0.5.8 (unstable)
  • zlib bindings (isaacs) +
  • Windows supports TTY ANSI escape codes (Bert Belder) +
  • Debugger improvements (Fedor Indutny) +
  • crypto: look up SSL errors with ERR_print_errors() (Ben Noordhuis) +
  • dns callbacks go through MakeCallback now +
  • Raise an error when a malformed package.json file is found. (Ben Leslie) +
  • buffers: handle bad length argument in constructor (Ben Noordhuis) +
  • #1726, unref process.stdout +
  • Doc improvements (Ben Noordhuis, Fedor Indutny, koichik) +
  • Upgrade libuv to fe18438
+ +Download: http://nodejs.org/dist/v0.5.8/node-v0.5.8.tar.gz + +Windows Executable: http://nodejs.org/dist/v0.5.8/node.exe + +Website: http://nodejs.org/docs/v0.5.8/ + +Documentation: http://nodejs.org/docs/v0.5.8/api/ diff --git a/node-v0.8.14/doc/blog/release/node-v0-5-9.md b/node-v0.8.14/doc/blog/release/node-v0-5-9.md new file mode 100644 index 0000000..8cf7e81 --- /dev/null +++ b/node-v0.8.14/doc/blog/release/node-v0-5-9.md @@ -0,0 +1,27 @@ +version: 0.5.9 +title: Node v0.5.9 +author: ryandahl +date: Mon Oct 10 2011 19:06:21 GMT-0700 (PDT) +status: publish +category: release +slug: node-v0-5-9 + +2011.10.10, Version 0.5.9 (unstable) +
  • fs.watch interface backed by kqueue, inotify, and ReadDirectoryChangesW (Igor Zinkovsky, Ben Noordhuis)
  • +
  • add dns.resolveTxt (Christian Tellnes)
  • +
  • Remove legacy http library (Ben Noordhuis)
  • +
  • child_process.fork returns and works on Windows. Allows passing handles. (Igor Zinkovsky, Bert Belder)
  • +
  • #1774 Lint and clean up for --harmony_block_scoping (Tyler Larson, Colton Baker)
  • +
  • #1813 Fix ctrl+c on Windows (Bert Belder)
  • +
  • #1844 unbreak --use-legacy (Ben Noordhuis)
  • +
  • process.stderr now goes through libuv. Both process.stdout and process.stderr are blocking when referencing a TTY.
  • +
  • net_uv performance improvements (Ben Noordhuis, Bert Belder)
+ + +Download: http://nodejs.org/dist/v0.5.9/node-v0.5.9.tar.gz + +Windows Executable: http://nodejs.org/dist/v0.5.9/node.exe + +Website: http://nodejs.org/docs/v0.5.9/ + +Documentation: http://nodejs.org/docs/v0.5.9/api/ diff --git a/node-v0.8.14/doc/blog/release/node-v0-6-0.md b/node-v0.8.14/doc/blog/release/node-v0-6-0.md new file mode 100644 index 0000000..5c796e7 --- /dev/null +++ b/node-v0.8.14/doc/blog/release/node-v0-6-0.md @@ -0,0 +1,80 @@ +version: 0.6.0 +title: Node v0.6.0 +author: ryandahl +date: Sat Nov 05 2011 02:07:10 GMT-0700 (PDT) +status: publish +category: release +slug: node-v0-6-0 + +We are happy to announce the third stable branch of Node v0.6. We will be freezing JavaScript, C++, and binary interfaces for all v0.6 releases. + +The major differences between v0.4 and v0.6 are
    +
  • Native Windows support using I/O Completion Ports for sockets. +
  • Integrated load balancing over multiple processes. docs +
  • Better support for IPC between Node instances docs +
  • Improved command line debugger docs +
  • Built-in binding to zlib for compression docs +
  • Upgrade v8 from 3.1 to 3.6
+ +In order to support Windows we reworked much of the core architecture. There was some fear that our work would degrade performance on UNIX systems but this was not the case. Here is a Linux system we benched for demonstration: + + + + + +
v0.4.12 (linux)v0.6.0 (linux)
http_simple.js /bytes/1024 5461 r/s 6263 r/s
io.js read 19.75 mB/s 26.63 mB/s
io.js write 21.60 mB/s 17.40 mB/s
startup.js 74.7 ms 49.6 ms
+ +Bigger is better in http and io benchmarks, smaller is better in startup. The http benchmark was done with 600 clients on a 10GE network served from three load generation machines. + +In the last version of Node, v0.4, we could only run Node on Windows with Cygwin. Therefore we've gotten massive improvements by targeting the native APIs. Benchmarks on the same machine: + + + + + +
v0.4.12 (windows)v0.6.0 (windows)
http_simple.js /bytes/1024 3858 r/s 5823 r/s
io.js read 12.41 mB/s 26.51 mB/s
io.js write 12.61 mB/s 33.58 mB/s
startup.js 152.81 ms 52.04 ms
+ +We consider this a good intermediate stage for the Windows port. There is still work to be done. For example, we are not yet providing users with a blessed path for building addon modules in MS Visual Studio. Work will continue in later releases. + +For users upgrading code bases from v0.4 to v0.6 we've documented most of the issues that you will run into. Most people find the change painless. Despite the long list of changes most core APIs remain untouched. + +Our release cycle will be tightened dramatically now. Expect to see a new stable branch in January. We wish to eventually have our releases in sync with Chrome and V8's 6 week cycle. + +Thank you to everyone who contributed code, tests, docs, or sent in bug reports. + +Here are the changes between v0.5.12 and v0.6.0: + +2011.11.04, Version 0.6.0 (stable) +
  • print undefined on undefined values in REPL (Nathan Rajlich)
  • +
  • doc improvements (koichik, seebees, bnoordhuis, Maciej Małecki, Jacob Kragh)
  • +
  • support native addon loading in windows (Bert Belder)
  • +
  • rename getNetworkInterfaces() to networkInterfaces() (bnoordhuis)
  • +
  • add pending accepts knob for windows (igorzi)
  • +
  • http.request(url.parse(x)) (seebees)
  • +
  • #1929 zlib Respond to 'resume' events properly (isaacs)
  • +
  • stream.pipe: Remove resume and pause events
  • +
  • test fixes for windows (igorzi)
  • +
  • build system improvements (bnoordhuis)
  • +
  • #1936 tls: does not emit 'end' from EncryptedStream (koichik)
  • +
  • #758 tls: add address(), remoteAddress/remotePort
  • +
  • #1399 http: emit Error object after .abort() (bnoordhuis)
  • +
  • #1999 fs: make mkdir() default to 0777 permissions (bnoordhuis)
  • +
  • #2001 fix pipe error codes
  • +
  • #2002 Socket.write should reset timeout timer
  • +
  • stdout and stderr are blocking when associated with file too.
  • +
  • remote debugger support on windows (Bert Belder)
  • +
  • convenience methods for zlib (Matt Robenolt)
  • +
  • process.kill support on windows (igorzi)
  • +
  • process.uptime() support on windows (igorzi)
  • +
  • Return IPv4 addresses before IPv6 addresses from getaddrinfo
  • +
  • util.inspect improvements (Nathan Rajlich)
  • +
  • cluster module api changes
  • +
  • Downgrade V8 to 3.6.6.6
+ +Download: http://nodejs.org/dist/v0.6.0/node-v0.6.0.tar.gz + +Windows Executable: http://nodejs.org/dist/v0.6.0/node.exe + +Website: http://nodejs.org/docs/v0.6.0/ + +Documentation: http://nodejs.org/docs/v0.6.0/api/ diff --git a/node-v0.8.14/doc/blog/release/node-v0-6-1.md b/node-v0.8.14/doc/blog/release/node-v0-6-1.md new file mode 100644 index 0000000..d7fb09c --- /dev/null +++ b/node-v0.8.14/doc/blog/release/node-v0-6-1.md @@ -0,0 +1,33 @@ +version: 0.6.1 +title: Node v0.6.1 +author: ryandahl +date: Fri Nov 11 2011 15:34:15 GMT-0800 (PST) +status: publish +category: release +slug: node-v0-6-1 + +2011.11.11, Version 0.6.1 (stable) +
  • doc improvements (Eric Lovett, Ben Noordhuis, Scott Anderson, Yoji SHIDARA)
  • +
  • crypto: make thread-safe (Ben Noordhuis)
  • +
  • fix process.kill error object
  • +
  • debugger: correctly handle source with multi-byte characters (Shigeki Ohtsu)
  • +
  • make stdout and stderr non-destroyable (Igor Zinkovsky)
  • +
  • fs: don't close uninitialized fs.watch handle (Ben Noordhuis)
  • +
  • #2026 fix man page install on BSDs (Ben Noordhuis)
  • +
  • #2040 fix unrecognized errno assert in uv_err_name
  • +
  • #2043 fs: mkdir() should call callback if mode is omitted
  • +
  • #2045 fs: fix fs.realpath on windows to return on error (Benjamin Pasero)
  • +
  • #2047 minor cluster improvements
  • +
  • #2052 readline get window columns correctly
  • +
  • Upgrade V8 to 3.6.6.7
+ + +Source Code: http://nodejs.org/dist/v0.6.1/node-v0.6.1.tar.gz + +Windows Installer: http://nodejs.org/dist/v0.6.1/node-v0.6.1.msi + +Macintosh Installer: http://nodejs.org/dist/v0.6.1/node-v0.6.1.pkg + +Website: http://nodejs.org/docs/v0.6.1/ + +Documentation: http://nodejs.org/docs/v0.6.1/api/ diff --git a/node-v0.8.14/doc/blog/release/node-v0-6-10.md b/node-v0.8.14/doc/blog/release/node-v0-6-10.md new file mode 100644 index 0000000..7d48993 --- /dev/null +++ b/node-v0.8.14/doc/blog/release/node-v0-6-10.md @@ -0,0 +1,30 @@ +version: 0.6.10 +title: Node v0.6.10 +author: Isaac Schlueter +date: Thu Feb 02 2012 17:22:03 GMT-0800 (PST) +status: publish +category: release +slug: node-v0-6-10 + +

2012.02.02, Version 0.6.10 (stable)

+ +
    +
  • Update V8 to 3.6.6.20

  • +
  • Add npm msysgit bash shim to msi installer (isaacs)

  • +
  • buffers: fix intermittent out of bounds error (Ben Noordhuis)

  • +
  • buffers: honor length argument in base64 decoder (Ben Noordhuis)

  • +
  • windows: Fix path.exists regression (Bert Belder)

  • +
  • Make QueryString.parse run faster (Philip Tellis)

  • +
  • http: avoid freeing http-parser objects too early (koichik)

  • +
  • timers: add v0.4 compatibility hack (Ben Noordhuis)

  • +
  • Proper EPERM error code support (Igor Zinkovsky, Brandon Philips)

  • +
  • dgram: Implement udp multicast methods on windows (Bert Belder)

  • +

Source Code: http://nodejs.org/dist/v0.6.10/node-v0.6.10.tar.gz

+ +

Windows Installer: http://nodejs.org/dist/v0.6.10/node-v0.6.10.msi

+ +

Macintosh Installer: http://nodejs.org/dist/v0.6.10/node-v0.6.10.pkg

+ +

Website: http://nodejs.org/docs/v0.6.10/

+ +

Documentation: http://nodejs.org/docs/v0.6.10/api/

diff --git a/node-v0.8.14/doc/blog/release/node-v0-6-2.md b/node-v0.8.14/doc/blog/release/node-v0-6-2.md new file mode 100644 index 0000000..9a75dcb --- /dev/null +++ b/node-v0.8.14/doc/blog/release/node-v0-6-2.md @@ -0,0 +1,27 @@ +version: 0.6.2 +title: Node v0.6.2 +author: bennoordhuis +date: Fri Nov 18 2011 15:35:32 GMT-0800 (PST) +status: publish +category: release +slug: node-v0-6-2 + +

2011.11.18, Version 0.6.2 (stable)

+
    +
  • doc improvements (Artur Adib, Trevor Burnham, Ryan Emery, Trent Mick)
  • +
  • timers: remember extra setTimeout() arguments when timeout==0
  • +
  • punycode: use Mathias Bynens's punycode library, it's more compliant
  • +
  • repl: improved tab completion (Ryan Emery)
  • +
  • buffer: fix range checks in .writeInt() functions (Lukasz Walukiewicz)
  • +
  • tls: make cipher list configurable
  • +
  • addons: make Buffer and ObjectWrap visible to Windows add-ons (Bert Belder)
  • +
  • crypto: add PKCS#1 a.k.a RSA public key verification support
  • +
  • windows: fix stdout writes when redirected to nul
  • +
  • sunos: fix build on Solaris and Illumos
  • +
  • Upgrade V8 to 3.6.6.8
  • +
+

Source Code: http://nodejs.org/dist/v0.6.2/node-v0.6.2.tar.gz

+

Windows Installer: http://nodejs.org/dist/v0.6.2/node-v0.6.2.msi

+

Macintosh Installer: http://nodejs.org/dist/v0.6.2/node-v0.6.2.pkg

+

Website: http://nodejs.org/docs/v0.6.2/

+

Documentation: http://nodejs.org/docs/v0.6.2/api/

diff --git a/node-v0.8.14/doc/blog/release/node-v0-6-3.md b/node-v0.8.14/doc/blog/release/node-v0-6-3.md new file mode 100644 index 0000000..e61c5f7 --- /dev/null +++ b/node-v0.8.14/doc/blog/release/node-v0-6-3.md @@ -0,0 +1,30 @@ +version: 0.6.3 +title: Node v0.6.3 +author: piscisaureus +date: Fri Nov 25 2011 02:54:08 GMT-0800 (PST) +status: publish +category: release +slug: node-v0-6-3 + +2011.11.25, Version 0.6.3 (stable) +
    +
  • #2083 Land NPM in Node. It is included in packages/installers and installed on `make install`.
  • +
  • #2076 Add logos to windows installer.
  • +
  • #1711 Correctly handle http requests without headers. (Ben Noordhuis, Felix Geisendörfer)
  • +
  • TLS: expose more openssl SSL context options and constants. (Ben Noordhuis)
  • +
  • #2177 Windows: don't kill UDP socket when a packet fails to reach its destination. (Bert Belder)
  • +
  • Windows: support paths longer than 260 characters. (Igor Zinkovsky)
  • +
  • Windows: correctly resolve drive-relative paths. (Bert Belder)
  • +
  • #2166 Don't leave file descriptor open after lchmod. (Isaac Schlueter)
  • +
  • #2084 Add OS X .pkg build script to make file.
  • +
  • #2160 Documentation improvements. (Ben Noordhuis)
  • +
+Source Code: http://nodejs.org/dist/v0.6.3/node-v0.6.3.tar.gz + +Windows Installer: http://nodejs.org/dist/v0.6.3/node-v0.6.3.msi + +Macintosh Installer: http://nodejs.org/dist/v0.6.3/node-v0.6.3.pkg + +Website: http://nodejs.org/docs/v0.6.3/ + +Documentation: http://nodejs.org/docs/v0.6.3/api/ diff --git a/node-v0.8.14/doc/blog/release/node-v0-6-4.md b/node-v0.8.14/doc/blog/release/node-v0-6-4.md new file mode 100644 index 0000000..ee5f633 --- /dev/null +++ b/node-v0.8.14/doc/blog/release/node-v0-6-4.md @@ -0,0 +1,31 @@ +version: 0.6.4 +title: Node v0.6.4 +author: bennoordhuis +date: Thu Dec 01 2011 18:20:14 GMT-0800 (PST) +status: publish +category: release +slug: node-v0-6-4 + +2011.12.02, Version 0.6.4 (stable) +
    +
  • doc improvements (Kyle Young, Tim Oxley, Roman Shtylman, Mathias Bynens)
  • +
  • upgrade bundled npm (Isaac Schlueter)
  • +
  • polish Windows installer (Igor Zinkovsky, Isaac Schlueter)
  • +
  • punycode: upgrade to v0.2.1 (Mathias Bynens)
  • +
  • build: add --without-npm flag to configure script
  • +
  • sys: deprecate module some more, print stack trace if NODE_DEBUG=sys
  • +
  • cli: add -p switch, prints result of --eval
  • +
  • #1997: fix Blowfish ECB encryption and decryption (Ingmar Runge)
  • +
  • #2223: fix socket 'close' event being emitted twice
  • +
  • #2224: fix RSS memory usage > 4 GB reporting (Russ Bradberry)
  • +
  • #2225: fix util.inspect() object stringification bug (Nathan Rajlich)
  • +
+Source Code: http://nodejs.org/dist/v0.6.4/node-v0.6.4.tar.gz + +Windows Installer: http://nodejs.org/dist/v0.6.4/node-v0.6.4.msi + +Macintosh Installer: http://nodejs.org/dist/v0.6.4/node-v0.6.4.pkg + +Website: http://nodejs.org/docs/v0.6.4/ + +Documentation: http://nodejs.org/docs/v0.6.4/api/ diff --git a/node-v0.8.14/doc/blog/release/node-v0-6-5.md b/node-v0.8.14/doc/blog/release/node-v0-6-5.md new file mode 100644 index 0000000..3035894 --- /dev/null +++ b/node-v0.8.14/doc/blog/release/node-v0-6-5.md @@ -0,0 +1,21 @@ +version: 0.6.5 +title: Node v0.6.5 +author: ryandahl +date: Sun Dec 04 2011 00:59:57 GMT-0800 (PST) +status: publish +category: release +slug: node-v0-6-5 + +2011.12.04, Version 0.6.5 (stable) +
  • npm workaround Windows antivirus software (isaacs) +
  • Upgrade V8 to 3.6.6.11
+ +Source Code: http://nodejs.org/dist/v0.6.5/node-v0.6.5.tar.gz + +Windows Installer: http://nodejs.org/dist/v0.6.5/node-v0.6.5.msi + +Macintosh Installer: http://nodejs.org/dist/v0.6.5/node-v0.6.5.pkg + +Website: http://nodejs.org/docs/v0.6.5/ + +Documentation: http://nodejs.org/docs/v0.6.5/api/ diff --git a/node-v0.8.14/doc/blog/release/node-v0-6-6.md b/node-v0.8.14/doc/blog/release/node-v0-6-6.md new file mode 100644 index 0000000..df53398 --- /dev/null +++ b/node-v0.8.14/doc/blog/release/node-v0-6-6.md @@ -0,0 +1,32 @@ +version: 0.6.6 +title: Node v0.6.6 +author: Isaac Schlueter +date: Thu Dec 15 2011 11:07:57 GMT-0800 (PST) +status: publish +category: release +slug: node-v0-6-6 + +2011.12.14, Version 0.6.6 (stable) + +
    +
  • npm update to 1.1.0-beta-4 (Isaac Z. Schlueter)
  • +
  • cli: fix output of --help (Ben Noordhuis)
  • +
  • new website
  • +
  • pause/resume semantics for stdin (Isaac Z. Schlueter)
  • +
  • Travis CI integration (Maciej Małecki)
  • +
  • child_process: Fix bug regarding closed stdin (Ben Noordhuis)
  • +
  • Enable upgrades in MSI. (Igor Zinkovsky)
  • +
  • net: Fixes memory leak (Ben Noordhuis)
  • +
  • fs: handle fractional or NaN ReadStream buffer size (Ben Noordhuis)
  • +
  • crypto: fix memory leaks in PBKDF2 error path (Ben Noordhuis)
  • +
+ +Source Code: http://nodejs.org/dist/v0.6.6/node-v0.6.6.tar.gz + +Windows Installer: http://nodejs.org/dist/v0.6.6/node-v0.6.6.msi + +Macintosh Installer: http://nodejs.org/dist/v0.6.6/node-v0.6.6.pkg + +Website: http://nodejs.org/docs/v0.6.6/ + +Documentation: http://nodejs.org/docs/v0.6.6/api/ diff --git a/node-v0.8.14/doc/blog/release/node-v0-6-7.md b/node-v0.8.14/doc/blog/release/node-v0-6-7.md new file mode 100644 index 0000000..06d9397 --- /dev/null +++ b/node-v0.8.14/doc/blog/release/node-v0-6-7.md @@ -0,0 +1,41 @@ +version: 0.6.7 +title: Node v0.6.7 +author: Isaac Schlueter +date: Fri Jan 06 2012 17:54:49 GMT-0800 (PST) +status: publish +category: release +slug: node-v0-6-7 + +

2012.01.06, Version 0.6.7 (stable)

+ +
    +
  • V8 hash collision fix (Breaks MIPS) (Bert Belder, Erik Corry)

  • +
  • Upgrade V8 to 3.6.6.15

  • +
  • Upgrade npm to 1.1.0-beta-10 (isaacs)

  • +
  • many doc updates (Ben Noordhuis, Jeremy Martin, koichik, Dave Irvine, +Seong-Rak Choi, Shannen, Adam Malcontenti-Wilson, koichik)

  • +
  • Fix segfault in node_http_parser.cc

  • +
  • dgram, timers: fix memory leaks (Ben Noordhuis, Yoshihiro Kikuchi)

  • +
  • repl: fix repl.start not passing the ignoreUndefined arg (Damon Oehlman)

  • +
  • #1980: Socket.pause null reference when called on a closed Stream (koichik)

  • +
  • #2263: XMLHttpRequest piped in a writable file stream hang (koichik)

  • +
  • #2069: http resource leak (koichik)

  • +
  • buffer.readInt global pollution fix (Phil Sung)

  • +
  • timers: fix performance regression (Ben Noordhuis)

  • +
  • #2308, #2246: node swallows openssl error on request (koichik)

  • +
  • #2114: timers: remove _idleTimeout from item in .unenroll() (James Hartig)

  • +
  • #2379: debugger: Request backtrace w/o refs (Fedor Indutny)

  • +
  • simple DTrace ustack helper (Dave Pacheco)

  • +
  • crypto: rewrite HexDecode without snprintf (Roman Shtylman)

  • +
  • crypto: don’t ignore DH init errors (Ben Noordhuis)

  • +
+ +

Source Code: http://nodejs.org/dist/v0.6.7/node-v0.6.7.tar.gz

+ +

Windows Installer: http://nodejs.org/dist/v0.6.7/node-v0.6.7.msi

+ +

Macintosh Installer: http://nodejs.org/dist/v0.6.7/node-v0.6.7.pkg

+ +

Website: http://nodejs.org/docs/v0.6.7/

+ +

Documentation: http://nodejs.org/docs/v0.6.7/api/

diff --git a/node-v0.8.14/doc/blog/release/node-v0-6-8.md b/node-v0.8.14/doc/blog/release/node-v0-6-8.md new file mode 100644 index 0000000..81f7ace --- /dev/null +++ b/node-v0.8.14/doc/blog/release/node-v0-6-8.md @@ -0,0 +1,31 @@ +version: 0.6.8 +title: Node v0.6.8 +author: Isaac Schlueter +date: Thu Jan 19 2012 19:59:53 GMT-0800 (PST) +status: publish +category: release +slug: node-v0-6-8 + +

2012.01.19, Version 0.6.8 (stable)

+ +
    +
  • Update V8 to 3.6.6.19

  • +
  • Numeric key hash collision fix for V8 (Erik Corry, Fedor Indutny)

  • +
  • Add missing TTY key translations for F1-F5 on Windows (Brandon Benvie)

  • +
  • path.extname bugfix with . and .. paths (Bert Belder)

  • +
  • cluster: don't always kill the master on uncaughtException (Ben Noordhuis)

  • +
  • Update npm to 1.1.0-2 (isaacs)

  • +
  • typed arrays: set class name (Ben Noordhuis)

  • +
  • zlib binding cleanup (isaacs, Bert Belder)

  • +
  • dgram: use slab memory allocator (Michael Bernstein)

  • +
  • fix segfault #2473

  • +
  • #2521 60% improvement in fs.stat on Windows (Igor Zinkovsky)

  • +

Source Code: http://nodejs.org/dist/v0.6.8/node-v0.6.8.tar.gz

+ +

Windows Installer: http://nodejs.org/dist/v0.6.8/node-v0.6.8.msi

+ +

Macintosh Installer: http://nodejs.org/dist/v0.6.8/node-v0.6.8.pkg

+ +

Website: http://nodejs.org/docs/v0.6.8/

+ +

Documentation: http://nodejs.org/docs/v0.6.8/api/

diff --git a/node-v0.8.14/doc/blog/release/node-v0-6-9.md b/node-v0.8.14/doc/blog/release/node-v0-6-9.md new file mode 100644 index 0000000..6e95bfd --- /dev/null +++ b/node-v0.8.14/doc/blog/release/node-v0-6-9.md @@ -0,0 +1,30 @@ +version: 0.6.9 +title: Node v0.6.9 +author: Isaac Schlueter +date: Fri Jan 27 2012 16:58:18 GMT-0800 (PST) +status: publish +category: release +slug: node-v0-6-9 + +

2012.01.27, Version 0.6.9 (stable)

+ +
    +
  • +

    dgram: Bring back missing functionality for Unix (Dan VerWeire, +Roman Shtylman, Ben Noordhuis)

    +

    - Note: Windows UDP support not yet complete.

  • +
  • http: Fix parser memory leak (koichik)

  • +
  • zlib: Fix #2365 crashes on invalid input (Nicolas LaCasse)

  • +
  • module: fix --debug-brk on symlinked scripts (Fedor Indutny)

  • +
  • Documentation Restyling (Matthew Fitzsimmons)

  • +
  • Update npm to 1.1.0-3 (isaacs)

  • +
  • Windows: fix regression in stat() calls to C:\ (Bert Belder)

  • +

Source Code: http://nodejs.org/dist/v0.6.9/node-v0.6.9.tar.gz

+ +

Windows Installer: http://nodejs.org/dist/v0.6.9/node-v0.6.9.msi

+ +

Macintosh Installer: http://nodejs.org/dist/v0.6.9/node-v0.6.9.pkg

+ +

Website: http://nodejs.org/docs/v0.6.9/

+ +

Documentation: http://nodejs.org/docs/v0.6.9/api/

diff --git a/node-v0.8.14/doc/blog/release/node-v0-7-0-unstable.md b/node-v0.8.14/doc/blog/release/node-v0-7-0-unstable.md new file mode 100644 index 0000000..2bf3ad5 --- /dev/null +++ b/node-v0.8.14/doc/blog/release/node-v0-7-0-unstable.md @@ -0,0 +1,29 @@ +version: 0.7.0 +title: Node v0.7.0 (Unstable) +author: ryandahl +date: Mon Jan 16 2012 19:58:28 GMT-0800 (PST) +status: publish +category: release +slug: node-v0-7-0-unstable + +This is the first release in the unstable v0.7 series. Almost all users will want to remain using the stable v0.6 releases. + +2012.01.16, Version 0.7.0 (unstable) +
    +
  • Upgrade V8 to 3.8.6 +
  • Use GYP build system on unix (Ben Noordhuis) +
  • Experimenetal isolates support (Ben Noordhuis) +
  • Improvements to Cluster API (Andreas Madsen) +
  • Use isolates for internal debugger (Fedor Indutny) +
  • Bug fixes
+ + +Source Code: http://nodejs.org/dist/v0.7.0/node-v0.7.0.tar.gz + +Windows Installer: http://nodejs.org/dist/v0.7.0/node-v0.7.0.msi + +Macintosh Installer: http://nodejs.org/dist/v0.7.0/node-v0.7.0.pkg + +Website: http://nodejs.org/docs/v0.7.0/ + +Documentation: http://nodejs.org/docs/v0.7.0/api/ diff --git a/node-v0.8.14/doc/blog/release/node-v0-7-1.md b/node-v0.8.14/doc/blog/release/node-v0-7-1.md new file mode 100644 index 0000000..cd3666d --- /dev/null +++ b/node-v0.8.14/doc/blog/release/node-v0-7-1.md @@ -0,0 +1,30 @@ +version: 0.7.1 +title: Node v0.7.1 +author: Isaac Schlueter +date: Mon Jan 23 2012 17:35:59 GMT-0800 (PST) +status: publish +category: release +slug: node-v0-7-1 + +

2012.01.23, Version 0.7.1 (unstable)

+ +
    +
  • Update V8 to 3.8.8

  • +
  • Install node-waf by default (Fedor Indutny)

  • +
  • crypto: Add ability to turn off PKCS padding (Ingmar Runge)

  • +
  • v8: implement VirtualMemory class on SunOS (Ben Noordhuis)

  • +
  • Add cluster.setupMaster (Andreas Madsen)

  • +
  • move path.exists* to fs.exists* (Maciej Małecki)

  • +
  • typed arrays: set class name (Ben Noordhuis)

  • +
  • libuv bug fixes (Igor Zinkovsky, Ben Noordhuis, Dan VerWeire)

  • +
+ +

Source: http://nodejs.org/dist/v0.7.1/node-v0.7.1.tar.gz

+ +

Windows Installer: http://nodejs.org/dist/v0.7.1/node-v0.7.1.msi

+ +

Macintosh Installer: http://nodejs.org/dist/v0.7.1/node-v0.7.1.pkg

+ +

Website: http://nodejs.org/docs/v0.7.1/

+ +

Documentation: http://nodejs.org/docs/v0.7.1/api/

diff --git a/node-v0.8.14/doc/blog/release/node-v0-7-2-unstable.md b/node-v0.8.14/doc/blog/release/node-v0-7-2-unstable.md new file mode 100644 index 0000000..e25e1b4 --- /dev/null +++ b/node-v0.8.14/doc/blog/release/node-v0-7-2-unstable.md @@ -0,0 +1,32 @@ +version: 0.7.2 +title: Node v0.7.2 (unstable) +author: Isaac Schlueter +date: Wed Feb 01 2012 13:13:04 GMT-0800 (PST) +status: publish +category: release +slug: node-v0-7-2-unstable + +

2012.02.01, Version 0.7.2 (unstable)

+ +
    +
  • Update V8 to 3.8.9

  • +
  • Support for sharing streams across Isolates (Igor Zinkovsky)

  • +
  • #2636 - Fix case where http_parsers are freed too early (koichik)

  • +
  • url: Support for IPv6 addresses in URLs (Łukasz Walukiewicz)

  • +
  • child_process: Add disconnect() method to child processes (Andreas Madsen)

  • +
  • fs: add O_EXCL support, exclusive open file (Ben Noordhuis)

  • +
  • fs: more specific error messages (Tj Holowaychuk)

  • +
  • tty: emit 'unknown' key event if key sequence not found (Dan VerWeire, Nathan Rajlich)

  • +
  • build: compile release build too if BUILDTYPE=Debug (Ben Noordhuis)

  • +
  • module: fix --debug-brk on symlinked scripts (Fedor Indutny)

  • +
  • zlib: fix Failed to set dictionary issue (Fedor Indutny)

  • +
  • waf: predict target arch for OS X (Fedor Indutny)

  • +

Source Code: http://nodejs.org/dist/v0.7.2/node-v0.7.2.tar.gz

+ +

Windows Installer: http://nodejs.org/dist/v0.7.2/node-v0.7.2.msi

+ +

Macintosh Installer: http://nodejs.org/dist/v0.7.2/node-v0.7.2.pkg

+ +

Website: http://nodejs.org/docs/v0.7.2/

+ +

Documentation: http://nodejs.org/docs/v0.7.2/api/

diff --git a/node-v0.8.14/doc/blog/release/node-v0-7-3.md b/node-v0.8.14/doc/blog/release/node-v0-7-3.md new file mode 100644 index 0000000..e4942bd --- /dev/null +++ b/node-v0.8.14/doc/blog/release/node-v0-7-3.md @@ -0,0 +1,39 @@ +version: 0.7.3 +title: Node v0.7.3 (unstable) +author: Isaac Schlueter +date: Tue Feb 07 2012 17:08:27 GMT-0800 (PST) +status: publish +category: release +slug: node-v0-7-3 + +

2012.02.07, Version 0.7.3 (unstable) + +

+
    +
  • Upgrade V8 to 3.9.2

    +
  • +
  • Revert support for isolates. (Ben Noordhuis)

    +
  • +
  • cluster: Cleanup docs, event handling, and process.disconnect (Andreas Madsen)

    +
  • +
  • gyp_addon: link with node.lib on Windows (Nathan Rajlich)

    +
  • +
  • http: fix case where http-parser is freed twice (koichik)

    +
  • +
  • Windows: disable RTTI and exceptions (Bert Belder)

    +
  • +
+

Source Code: http://nodejs.org/dist/v0.7.3/node-v0.7.3.tar.gz + +

+

Windows Installer: http://nodejs.org/dist/v0.7.3/node-v0.7.3.msi + +

+

Macintosh Installer: http://nodejs.org/dist/v0.7.3/node-v0.7.3.pkg + +

+

Website: http://nodejs.org/docs/v0.7.3/ + +

+

Documentation: http://nodejs.org/docs/v0.7.3/api/ +

diff --git a/node-v0.8.14/doc/blog/release/node-v0.8.0.md b/node-v0.8.14/doc/blog/release/node-v0.8.0.md new file mode 100644 index 0000000..118668f --- /dev/null +++ b/node-v0.8.14/doc/blog/release/node-v0.8.0.md @@ -0,0 +1,384 @@ +title: Node v0.8.0 +date: Mon Jun 25 2012 09:00:00 GMT-0700 (PDT) +version: 0.8.0 +category: release +author: Isaac Z. Schlueter +slug: node-v0-8-0 +status: publish + +I am thrilled to announce the arrival of a new stable version of +Node.js. + +Compared with the v0.6 releases of Node, this release brings significant +improvements in many key performance metrics, as well as +cleanup in several core APIs, and the addition of new debugging +features. + +## tl;dr + +With version 0.8.0: + +1. Node got a lot faster. +2. Node got more stable. +3. You can do stuff with file descriptors again. +4. The [cluster module](http://nodejs.org/api/cluster.html) is much more + awesome. +5. The [domain module](http://nodejs.org/api/domain.html) was added. +6. The repl is better. +7. The build system changed from waf to gyp. +8. [Some other stuff changed, + too.](https://github.com/joyent/node/wiki/API-changes-between-v0.6-and-v0.8) +9. Scroll to the bottom for the links to install it. + +## Performance + +This version brings a few key enhancements in V8 and libuv that result +in significantly improved throughput. + +All of these benchmarks were run on my OS X laptop, but the results are +typical of what we're seeing on SmartOS, Linux, and Windows. + +``` +# io.js + +# 0.6.19, writes +Wrote 1024 byte buffers: 19.428793471925395 mB/s +Wrote 4096 byte buffers: 59.737156511350065 mB/s +Wrote 16384 byte buffers: 83.97010664203543 mB/s +Wrote 65536 byte buffers: 97.4184120798831 mB/s + +# 0.8.0, writes +Wrote 1024 byte buffers: 61.236987140232706 mB/s +215.19% +Wrote 4096 byte buffers: 109.05125408942203 mB/s +82.55% +Wrote 16384 byte buffers: 182.18254691200585 mB/s +116.96% +Wrote 65536 byte buffers: 181.91740949608877 mB/s +86.74% + +# v0.6.19, reads +Read 1024 byte buffers: 29.96883241428914 mB/s +Read 4096 byte buffers: 62.34413965087282 mB/s +Read 16384 byte buffers: 165.7550140891762 mB/s +Read 65536 byte buffers: 266.73779674579885 mB/s + +# v0.8.0, reads +Read 1024 byte buffers: 57.63688760806916 mB/s +92.32% +Read 4096 byte buffers: 136.7801942278758 mB/s +119.40% +Read 16384 byte buffers: 244.8579823702253 mB/s +47.72% +Read 65536 byte buffers: 302.2974607013301 mB/s +13.33% +``` + +The difference is not small. If you are writing network programs with +node, and pushing a lot of traffic, you will notice this improvement. + +The speed of reading files got quite a bit faster as well: + +``` +# v0.6.19 +read the file 110948 times (higher is better) +90141.32 ns per read (lower is better) +11093.69 reads per sec (higher is better) + +# v0.8.0 +read the file 158193 times (higher is better) +42.58% +63217.16 ns per read (lower is better) -29.87% +15818.48 reads per sec (higher is better) +42.59% +``` + +And of course, the ubiquitous 'hello, world' http server benchmark got +significantly faster, especially for large message sizes: + +``` +$ TYPE=bytes LENGTH=123 bash benchmark/http.sh 2>&1 | grep Req +# 0.6.19 +Requests per second: 3317.24 [#/sec] (mean) +# 0.8.0 +Requests per second: 3795.34 [#/sec] (mean) +14.41% + + +$ TYPE=bytes LENGTH=1024 bash benchmark/http.sh 2>&1 | grep Req +# v0.6.19 +Requests per second: 3258.42 [#/sec] (mean) +# 0.8.0 +Requests per second: 3585.62 [#/sec] (mean) +10.04% + + +$ TYPE=bytes LENGTH=123456 bash benchmark/http.sh 2>&1 | grep Req +# v0.6.19 +Requests per second: 218.51 [#/sec] (mean) +# 0.8.0 +Requests per second: 749.17 [#/sec] (mean) +242.85% +``` + +The difference with Unicode responses is even more pronounced: + +``` +$ TYPE=unicode LENGTH=1024 bash benchmark/http.sh 2>&1 | grep Req +# v0.6.19 +Requests per second: 3228.23 [#/sec] (mean) +# v0.8.0 +Requests per second: 3317.60 [#/sec] (mean) +2.77% + +$ TYPE=unicode LENGTH=12345 bash benchmark/http.sh 2>&1 | grep Req +# v0.6.19 +Requests per second: 1703.96 [#/sec] (mean) +# v0.8.0 +Requests per second: 2431.61 [#/sec] (mean) +42.70% + +$ TYPE=unicode LENGTH=55555 bash benchmark/http.sh 2>&1 | grep Req +#v0.6.19 +Requests per second: 161.65 [#/sec] (mean) +#v0.8.0 +Requests per second: 980.38 [#/sec] (mean) +506.48% + +$ TYPE=unicode LENGTH=99999 bash benchmark/http.sh 2>&1 | grep Req +# v0.6.19 +^C # lost patience after a few hours +# v0.8.0 +Requests per second: 252.69 [#/sec] (mean) +``` + +The more bytes you're pushing, and the more work you're doing, the more +win you'll see with node 0.8 over 0.6. + +The vast majority of the performance boost is due to improvements in V8. +They've been very responsive to the needs of the Node.js project. A lot +of Node's success is due to being built on such a stellar VM. + + +## Build System + +Since its inception Node has used the WAF build system which is a Python +based system similar to SCons. The Chrome project recently changed to +the GYP meta-build system from SCons. GYP generates Makefiles, Visual +Studio project files, or XCode files depending on the target. V8, being +part of the Chrome project, now defines its build in GYP. By using GYP, +Node is able to: + +- integrate with the optimal build system on all platforms, +- easily able to integrate V8's build process into its own, and +- define its compilation declaratively for better manageability + +GYP was used already in Node v0.6 to build on Windows, but now it +defines the build on all platforms. Node is still in the process of +migrating external addon modules to GYP, and node-gyp is included with +npm. In future releases, node-waf will be officially deprecated. If +you are currently using a wscript in your addon, please migrate to gyp +as soon as possible. + + +## Stabler + +The transition from libev and libeio to libuv in 0.6 was somewhat +destabilizing for many node internals. The gambit paid off: libuv is +the obvious choice in cross-platform asynchronous IO libraries, and +Node.js is impressively performant on both Windows and Unix. But it +made the transition from 0.4 to 0.6 was very rocky for a lot of users. +Libuv wasn't as mature as node, and it showed in those early releases. + +At this point, with very few exceptions, if your v0.6 program doesn't +run on v0.8, it should be easy and obvious to make whatever changes are +necessary. Libuv has come a very long way, and Node 0.8 is a simpler +and more efficient machine as a result. + +See the [migration +wiki](https://github.com/joyent/node/wiki/API-changes-between-v0.6-and-v0.8) +for details on the specific APIs that changed. + +## The Return of File Descriptors + +In Node 0.4, there was a `listenFD` method that servers could use to +listen on a specific file descriptor that was already bound to a socket +or port. In 0.6, that functionality went away, largely because it was +very Unix-specific, and couldn't be easily made to work with the new +cross-platform libuv base. + +Since the most common use case for listenFD was as a method for having +servers in multiple node processes share the same underlying handle, the +`cluster` module was added in its place. However, this still left a lot +of use cases unaddressed, and was a reason why some people could not use +node 0.6 for their programs. + +In 0.8, we've replaced this functionality, as `server.listen({ fd: +number })`. + +The other feature in node 0.4 that got dropped in 0.6 was the ability to +pass arbitrary file descriptors as a child process's stdio, using the +`customFds` array. In Node 0.6, `customFds` could be used to inherit +the parent's stdio handles, but not to pass arbitrary handles or file +descriptors to the child's stdio. Also, there was never a way to pass +more than the standard `in, out, err` trio, so programs that expected +FD 4 to be opened in some specific way were out of luck. + +In 0.8, we've added the `stdio` array on the `child_process.spawn` +options. Pass as many file descriptors, handles, etc. as you like, and +the child process will see them as already-opened FDs. + +## More Powerful Cluster + +The cluster module in 0.8 is so much improved over 0.6, it's basically a +complete rewrite. The API is mostly backwards compatible, but not +entirely. (See the [migration +wiki](https://github.com/joyent/node/wiki/API-changes-between-v0.6-and-v0.8) +for details.) + +Barring these very minor API changes, if you were using cluster in 0.6, +then your program will still work, but it'll be faster and more +well-behaved now. And if you aren't taking advantage of the new +features in 0.8's cluster, you're really missing out. + +There's too much even to do it justice here. Go read [the API +docs](http://nodejs.org/api/cluster.html). + +## Domains + +The original idea for Domains was a way to join multiple different IO +actions, so that you can have some context when an error occurs. + +Since Ryan discussed the feature with node users at NodeConf Summer Camp +last year, the domains feature has gone through many revisions. The +problem is fairly well understood, but most attempts to solve it +resulted in serious performance regressions, or uncovered difficult edge +cases. + +What we ended up with in 0.8 is a very stripped-down version of this +idea. It's entirely opt-in, with minimal performance impact when it's +used (and none when it isn't). There are a lot of examples in [the API +documentation](http://nodejs.org/api/domain.html), so check them out, +and start handling your crashes smarter. + +The domain module is still experimental. We are looking forward to your +feedback, so please use it and let us know what you think. + +## Repl, Readline, TTY + +The Repl, Readline, and TTY modules have all had a major facelift. The +interfaces between these three modules are cleaned up and refactored, +removing a lot of common pain points and making it easier to use for +debugging your programs. + +It may seem minor at times, but a good repl dramatically increases the +quality of the overall experience. My personal favorites are: + +1. Typing `fs` or `net` or `path` will automatically load the module. +2. Typing `npm install ...` will give you a helpful message. +3. It doesn't do that stupid thing where long lines wrap and then the + backspace makes it get all confused and crazy. Instead of that, it + does the right thing. + +## Looking Forward + +Like other even-numbered version families before it, v0.8 will maintain +API and ABI stability throughout its lifetime. + +The v0.6 release family will continue to see releases for critical +bugfixes and security issues through the end of 2012. However, it will +not be the main focus of the core team's attention. + +The v0.9 releases will start in the next couple weeks. The main focus +of v0.9 will be: + +* The HTTP implementation - It has seen a lot of real-world use now, but + the http module is in dire need of a cleanup and refactor. Special + attention will be paid to making the interfaces more consistent, + improve performance, and increase correctness in more edge cases. +* The Streams API - The concept of the Stream API is very core to node. + However, it is also (like HTTP) a feature that grew up organically, + and is now in need of a cleanup. It is currently too hard to get + right, especially regarding error handling. +* Libuv Streams - The handle interfaces in libuv are going to be + refactored for added consistency throughout the codebase and across + platforms. + +Looking past that, there are a few areas where Node.js still has room +for improvement in terms of internal consistency, idiomatic JavaScript +usage, and performance. None of these are fully-fleshed out ideas yet, +but these are some of the items on our radar: + +* We ought to move to TypedArrays in favor of Buffers. Buffers will + continue to work, but since TypedArray is a JavaScript native, it + makes sense to move towards that as the preferred API. +* SSL performance leaves much to be desired at the moment. Node's + interface with OpenSSL is somewhat naive and leaves a lot of potential + optimization on the table. +* The VM module needs massive improvement. It lacks features required + to emulate a web browser JavaScript context, which means that it is + inadequate. +* The Crypto module still uses some very dated APIs. In 0.8, it can + accept Buffers for many things (finally!) but it still does not + present a Node-like streaming interface. + +At this point, the scope of Node's feature set is pretty much locked +down. We may move things around internally for these cleanup tasks, but +as you can see, there are no major new features planned. We've drawn +our boundaries, and now it's time to continue focusing on improving +stability and performance of the core, so that more innovation can +happen in **your** programs. + +And now, for those of you who may be wondering what was added since +v0.7.12, your regularly scheduled release announcement: + +## 2012.06.25, Version 0.8.0 (stable) + +* V8: upgrade to v3.11.10.10 + +* npm: Upgrade to 1.1.32 + +* Deprecate iowatcher (Ben Noordhuis) + +* windows: update icon (Bert Belder) + +* http: Hush 'MUST NOT have a body' warnings to debug() (isaacs) + +* Move blog.nodejs.org content into repository (isaacs) + +* Fix #3503: stdin: resume() on pipe(dest) (isaacs) + +* crypto: fix error reporting in SetKey() (Fedor Indutny) + +* Add --no-deprecation and --trace-deprecation command-line flags (isaacs) + +* fs: fix fs.watchFile() (Ben Noordhuis) + +* fs: Fix fs.readfile() on pipes (isaacs) + +* Rename GYP variable node_use_system_openssl to be consistent (Ryan Dahl) + + +Source Code: http://nodejs.org/dist/v0.8.0/node-v0.8.0.tar.gz + +Macintosh Installer (Universal): http://nodejs.org/dist/v0.8.0/node-v0.8.0.pkg + +Windows Installer: http://nodejs.org/dist/v0.8.0/node-v0.8.0-x86.msi + +Windows x64 Installer: http://nodejs.org/dist/v0.8.0/x64/node-v0.8.0-x64.msi + +Windows x64 Files: http://nodejs.org/dist/v0.8.0/x64/ + +Other release files: http://nodejs.org/dist/v0.8.0/ + +Website: http://nodejs.org/docs/v0.8.0/ + +Documentation: http://nodejs.org/docs/v0.8.0/api/ + +Shasums: + +``` +b92208b291ad420025c65661a7df51fc618e21ca license.rtf +0786bcda79bd651b9981682527a1bbabe0250700 node-v0.8.0-x86.msi +8f160a742a01fdfc1b1423b3fc742d184f1ab70c node-v0.8.0-x86.wixpdb +6035d6d59304add21e462cd7eb89491570b4970d node-v0.8.0.pkg +5171fb46fbfee5ac7129c4b17207a3f35a1f57e8 node-v0.8.0.tar.gz +742100a4ee4cd4d190031a30d9b22b2b69b6872e node.exe +52d20d285e9aec53043af0843f5ecc4153210693 node.exp +6d67a64274d844548cc6099c76181a50feafc233 node.lib +aa2af08d5ab869e6c8b67f01ed67129c1cad8bce node.pdb +b92208b291ad420025c65661a7df51fc618e21ca x64/license.rtf +c4d4164d4f78ea68e0e2a85b96f9b355f3b1df8b x64/node-v0.8.0-x64.msi +df8bb178ee4cb9562d93fe80bbe59b2acf1b9e6b x64/node-v0.8.0-x64.wixpdb +fc07b475d943f7681e1904d6d7d666b41874a6fa x64/node.exe +895002806dfb6d5bb141ef0f43cad3b540a4ff6c x64/node.exp +686c60d5ae5dad7fcffcdc88049c63b2cd23cffc x64/node.lib +75549cffab0c11107348a66ab0d94d4897bd6a27 x64/node.pdb +``` + +Edited by Tim Oxley to provide percentage differences in the +benchmarks. diff --git a/node-v0.8.14/doc/blog/release/node-version-0-6-19-stable.md b/node-v0.8.14/doc/blog/release/node-version-0-6-19-stable.md new file mode 100644 index 0000000..cb8febe --- /dev/null +++ b/node-v0.8.14/doc/blog/release/node-version-0-6-19-stable.md @@ -0,0 +1,61 @@ +version: 0.6.19 +title: Node Version 0.6.19 (stable) +author: Isaac Schlueter +date: Wed Jun 06 2012 09:55:37 GMT-0700 (PDT) +status: publish +category: release +slug: node-version-0-6-19-stable + +

2012.06.06 Version 0.6.19 (stable) + +

+
    +
  • npm: upgrade to 1.1.24

    +
  • +
  • fs: no end emit after createReadStream.pause() (Andreas Madsen)

    +
  • +
  • vm: cleanup module memory leakage (Marcel Laverdet)

    +
  • +
  • unix: fix loop starvation under high network load (Ben Noordhuis)

    +
  • +
  • unix: remove abort() in ev_unref() (Ben Noordhuis)

    +
  • +
  • windows/tty: never report error after forcibly aborting line-buffered read (Bert Belder)

    +
  • +
  • windows: skip GetFileAttributes call when opening a file (Bert Belder)

    +
  • +
+

Source Code: http://nodejs.org/dist/v0.6.19/node-v0.6.19.tar.gz + +

+

Windows Installer: http://nodejs.org/dist/v0.6.19/node-v0.6.19.msi + +

+

Windows x64 Files: http://nodejs.org/dist/v0.6.19/x64/ + +

+

Macintosh Installer (Universal): http://nodejs.org/dist/v0.6.19/node-v0.6.19.pkg + +

+

Other release files: http://nodejs.org/dist/v0.6.19/ + +

+

Website: http://nodejs.org/docs/v0.6.19/ + +

+

Documentation: http://nodejs.org/docs/v0.6.19/api/ +

+ +

Shasums:

+
ef4f5c1e5f12f6ef3478a794d6a81f59669332f9  node-v0.6.19.msi
+781616f33208f532f168633758a648c20e1ea68b  node-v0.6.19.pkg
+f6c5cfbadff4788ac3a95f8263a0c2f4e07444b6  node-v0.6.19.tar.gz
+10f729ca236825821d97556441fa64f994cb4ca8  node.exe
+5b8cd02e5f92ed6512aabdac11766ad8c1abc436  node.exp
+20037e4901de605e08e48d0c85531334912844e3  node.lib
+c44f62852918d449850014d9b29dd073cb6920a5  node.pdb
+04db25c93c5357394941dd2de12cb61959eb82d1  x64/node-v0.6.19.msi
+f77c77f2e470cfc9071853af2f277ba91d660b9c  x64/node.exe
+fcf26a3f984a3f19804e0567414604b77b1d3bac  x64/node.exp
+bfed2a24f253dbac99379d6f22fc8e9e85ade7ed  x64/node.lib
+95226c1cc5170ea05c2e54431040f06c3e95e99f  x64/node.pdb
diff --git a/node-v0.8.14/doc/blog/release/node-version-0-7-9-unstable.md b/node-v0.8.14/doc/blog/release/node-version-0-7-9-unstable.md new file mode 100644 index 0000000..683823a --- /dev/null +++ b/node-v0.8.14/doc/blog/release/node-version-0-7-9-unstable.md @@ -0,0 +1,73 @@ +version: 0.7.9 +title: Node Version 0.7.9 (unstable) +author: Isaac Schlueter +date: Tue May 29 2012 10:11:45 GMT-0700 (PDT) +status: publish +category: release +slug: node-version-0-7-9-unstable + +

2012.05.28, Version 0.7.9 (unstable) + +

+
    +
  • Upgrade V8 to 3.11.1

    +
  • +
  • Upgrade npm to 1.1.23

    +
  • +
  • uv: rework reference counting scheme (Ben Noordhuis)

    +
  • +
  • uv: add interface for joining external event loops (Bert Belder)

    +
  • +
  • repl, readline: Handle Ctrl+Z and SIGCONT better (Nathan Rajlich)

    +
  • +
  • fs: 64bit offsets for fs calls (Igor Zinkovsky)

    +
  • +
  • fs: add sync open flags 'rs' and 'rs+' (Kevin Bowman)

    +
  • +
  • windows: enable creating directory junctions with fs.symlink (Igor Zinkovsky, Bert Belder)

    +
  • +
  • windows: fix fs.lstat to properly detect symlinks. (Igor Zinkovsky)

    +
  • +
  • Fix #3270 Escape url.parse delims (isaacs)

    +
  • +
  • http: make http.get() accept a URL (Adam Malcontenti-Wilson)

    +
  • +
  • Cleanup vm module memory leakage (Marcel Laverdet)

    +
  • +
  • Optimize writing strings with Socket.write (Bert Belder)

    +
  • +
  • add support for CESU-8 and UTF-16LE encodings (koichik)

    +
  • +
  • path: add path.sep to get the path separator. (Yi, EungJun)

    +
  • +
  • net, http: add backlog parameter to .listen() (Erik Dubbelboer)

    +
  • +
  • debugger: support mirroring Date objects (Fedor Indutny)

    +
  • +
  • addon: add AtExit() function (Ben Noordhuis)

    +
  • +
  • net: signal localAddress bind failure in connect (Brian Schroeder)

    +
  • +
  • util: handle non-string return value in .inspect() (Alex Kocharin)

    +
  • +
+

Source Code: http://nodejs.org/dist/v0.7.9/node-v0.7.9.tar.gz + +

+

Windows Installer: http://nodejs.org/dist/v0.7.9/node-v0.7.9.msi + +

+

Windows x64 Files: http://nodejs.org/dist/v0.7.9/x64/ + +

+

Macintosh Installer (Universal): http://nodejs.org/dist/v0.7.9/node-v0.7.9.pkg + +

+

Other release files: http://nodejs.org/dist/v0.7.9/ + +

+

Website: http://nodejs.org/docs/v0.7.9/ + +

+

Documentation: http://nodejs.org/docs/v0.7.9/api/ +

diff --git a/node-v0.8.14/doc/blog/release/v0.6.20.md b/node-v0.8.14/doc/blog/release/v0.6.20.md new file mode 100644 index 0000000..8eee1e3 --- /dev/null +++ b/node-v0.8.14/doc/blog/release/v0.6.20.md @@ -0,0 +1,51 @@ +version: 0.6.20 +title: Version 0.6.20 (maintenance) +category: release +slug: node-v0-6-20-maintenance +date: 2012.07.10 18:00 + +2012.07.10 Version 0.6.20 (maintenance) + +* npm: Upgrade to 1.1.37 (isaacs) + +* benchmark: Backport improvements made in master (isaacs) + +* build: always link with -lz (Trent Mick) + +* core: use proper #include directives (Ben Noordhuis) + +* cluster: don't silently drop messages when the write queue gets big (Bert Belder) + +* windows: don't print error when GetConsoleTitleW returns an empty string (Bert Belder) + + +Source Code: http://nodejs.org/dist/v0.6.20/node-v0.6.20.tar.gz + +Windows Installer: http://nodejs.org/dist/v0.6.20/node-v0.6.20.msi + +Windows x64 Files: http://nodejs.org/dist/v0.6.20/x64/ + +Macintosh Installer (Universal): http://nodejs.org/dist/v0.6.20/node-v0.6.20.pkg + +Other release files: http://nodejs.org/dist/v0.6.20/ + +Website: http://nodejs.org/docs/v0.6.20/ + +Documentation: http://nodejs.org/docs/v0.6.20/api/ + +Shasums: + +``` +5029f30e6af79e7a9a1d45396afbe20229059b47 node-v0.6.20.msi +370105015bae2a77e4da41564ad3df8fcd0acaec node-v0.6.20.pkg +91da1dde9badd5250f3d4829c47757de0caab84b node-v0.6.20.tar.gz +efa29addd716c175d945ade5dfa2b9ebd7f6fed8 node.exe +aab0e367adcc9fdee479dbe67a32c6b27ee35960 node.exp +ce6c455937f96eb671f44dc731d628849fa8b350 node.lib +a8db5c269de9c3059684f9aa3de5a4cdbd9b3d12 node.pdb +22f97ba2c678b4c8a1def251269920ee46c90bca x64/node-v0.6.20.msi +276136ae7f6e2e59d0ae26d434e4d6ab65769957 x64/node.exe +af56811749aa4fe013a36f7bccecfb94587c0afd x64/node.exp +a629af1b4f6f4b82e332c35695fff956bd555f3b x64/node.lib +3b2d22b20efeb06bf3d86378168d604dbe52eb08 x64/node.pdb +``` diff --git a/node-v0.8.14/doc/blog/release/v0.8.1.md b/node-v0.8.14/doc/blog/release/v0.8.1.md new file mode 100644 index 0000000..b8c84e2 --- /dev/null +++ b/node-v0.8.14/doc/blog/release/v0.8.1.md @@ -0,0 +1,77 @@ +version: 0.8.1 +title: Version 0.8.1 (stable) +category: release +slug: node-v0-8-1-stable +date: 2012.06.29 + +2012.06.29, Version 0.8.1 (stable) + +* V8: upgrade to v3.11.10.12 + +* npm: upgrade to v1.1.33 + - Support for parallel use of the cache folder + - Retry on registry timeouts or network failures (Trent Mick) + - Reduce 'engines' failures to a warning + - Use new zsh completion if aviailable (Jeremy Cantrell) + +* Fix #3577 Un-break require('sys') + +* util: speed up formatting of large arrays/objects (Ben Noordhuis) + +* windows: make fs.realpath(Sync) work with UNC paths (Bert Belder) + +* build: fix --shared-v8 option (Ben Noordhuis) + +* doc: `detached` is a boolean (Andreas Madsen) + +* build: use proper python interpreter (Ben Noordhuis) + +* build: expand ~ in `./configure --prefix=~/a/b/c` (Ben Noordhuis) + +* build: handle CC env var with spaces (Gabriel de Perthuis) + +* build: fix V8 build when compiling with gcc 4.5 (Ben Noordhuis) + +* build: fix --shared-v8 option (Ben Noordhuis) + +* windows msi: Fix icon issue which caused huge file size (Bert Belder) + +* unix: assume that dlopen() may clobber dlerror() (Ben Noordhuis) + +* sunos: fix memory corruption bugs (Ben Noordhuis) + +* windows: better (f)utimes and (f)stat (Bert Belder) + + +Source Code: http://nodejs.org/dist/v0.8.1/node-v0.8.1.tar.gz + +Macintosh Installer (Universal): http://nodejs.org/dist/v0.8.1/node-v0.8.1.pkg + +Windows Installer: http://nodejs.org/dist/v0.8.1/node-v0.8.1-x86.msi + +Windows x64 Installer: http://nodejs.org/dist/v0.8.1/x64/node-v0.8.1-x64.msi + +Windows x64 Files: http://nodejs.org/dist/v0.8.1/x64/ + +Other release files: http://nodejs.org/dist/v0.8.1/ + +Website: http://nodejs.org/docs/v0.8.1/ + +Documentation: http://nodejs.org/docs/v0.8.1/api/ + +Shasums: + +``` +64f10cb29aaaabda83300c81d61b56a436308126 node-v0.8.1-x86.msi +75a1afca1221719ec4a9dd8ed35c0e0adbaaf153 node-v0.8.1.pkg +892790553b8121ba8624d8293d0cb7d8b01094d7 node-v0.8.1.tar.gz +85ce513182bd66c1aa3e144438022dbe4caa56a7 node.exe +592426620080c904c55ac83e151a85d42275656e node.exp +88a9177dba73597ffc08f30b886542c4d76378e2 node.lib +6b06ffd2b6e28e34189663af7b3efda5d12dd1bf node.pdb +c6d99aa58167c5489e56e2f99da99731fb4f282e x64/node-v0.8.1-x64.msi +4266ba03b2b4516d10cbc5d16eb15d5df13ebb47 x64/node.exe +7a6d0b28be88c6941aae74426199e9fb82ddfaa5 x64/node.exp +ac21ec0f61baaf584f89a92db403cd9d38ff4850 x64/node.lib +9e514c4c6c427dd4ae16edf1d2ad7a46ef9893c0 x64/node.pdb +``` diff --git a/node-v0.8.14/doc/blog/release/v0.8.10.md b/node-v0.8.14/doc/blog/release/v0.8.10.md new file mode 100644 index 0000000..26a490d --- /dev/null +++ b/node-v0.8.14/doc/blog/release/v0.8.10.md @@ -0,0 +1,93 @@ +title: Node v0.8.10 (Stable) +date: Tue Sep 25 15:36:47 PDT 2012 +slug: node-v0-8-10-stable +category: release +version: 0.8.10 + +2012.09.25, Version 0.8.10 (Stable) + +* npm: Upgrade to 1.1.62 + +* repl: make invalid RegExps throw in the REPL (Nathan Rajlich) + +* v8: loosen artificial mmap constraint (Bryan Cantrill) + +* process: fix setuid() and setgid() error reporting (Ben Noordhuis) + +* domain: Properly exit() on domain disposal (isaacs) + +* fs: fix watchFile() missing deletion events (Ben Noordhuis) + +* fs: fix assert in fs.watch() (Ben Noordhuis) + +* fs: don't segfault on deeply recursive stat() (Ben Noordhuis) + +* http: Remove timeout handler when data arrives (Frédéric Germain) + +* http: make the client "res" object gets the same domain as "req" (Nathan Rajlich) + +* windows: don't blow up when an invalid FD is used (Bert Belder) + +* unix: map EDQUOT to UV_ENOSPC (Charlie McConnell) + +* linux: improve /proc/cpuinfo parser (Ben Noordhuis) + +* win/tty: reset background brightness when color is set to default (Bert Belder) + +* unix: put child process stdio fds in blocking mode (Ben Noordhuis) + +* unix: fix EMFILE busy loop (Ben Noordhuis) + +* sunos: don't set TCP_KEEPALIVE (Ben Noordhuis) + +* tls: Use slab allocator for memory management (Fedor Indutny) + +* openssl: Use optimized assembly code for x86 and x64 (Bert Belder) + + +Source Code: http://nodejs.org/dist/v0.8.10/node-v0.8.10.tar.gz + +Macintosh Installer (Universal): http://nodejs.org/dist/v0.8.10/node-v0.8.10.pkg + +Windows Installer: http://nodejs.org/dist/v0.8.10/node-v0.8.10-x86.msi + +Windows x64 Installer: http://nodejs.org/dist/v0.8.10/x64/node-v0.8.10-x64.msi + +Windows x64 Files: http://nodejs.org/dist/v0.8.10/x64/ + +Linux 32-bit Binary: http://nodejs.org/dist/v0.8.10/node-v0.8.10-linux-x86.tar.gz + +Linux 64-bit Binary: http://nodejs.org/dist/v0.8.10/node-v0.8.10-linux-x64.tar.gz + +Solaris 32-bit Binary: http://nodejs.org/dist/v0.8.10/node-v0.8.10-sunos-x86.tar.gz + +Solaris 64-bit Binary: http://nodejs.org/dist/v0.8.10/node-v0.8.10-sunos-x64.tar.gz + +Other release files: http://nodejs.org/dist/v0.8.10/ + +Website: http://nodejs.org/docs/v0.8.10/ + +Documentation: http://nodejs.org/docs/v0.8.10/api/ + +Shasums: + +``` +ae327ce5cc9f46e7d1bdd04f06ea299e44f9a0fc node-v0.8.10-darwin-x64.tar.gz +812405695e3522bfd998d67b6de2daff55ff0a7b node-v0.8.10-darwin-x86.tar.gz +8ef4e489817a79aaea75cffd09cc4b072c38fe2e node-v0.8.10-linux-x64.tar.gz +76f289b12ba41730c43b59d286de5cee571c9064 node-v0.8.10-linux-x86.tar.gz +61e40e8a5e911b26889ad33856029d783388778a node-v0.8.10-sunos-x64.tar.gz +2fd06dc2d145fdba6b2800186ffcaebb0fe3b109 node-v0.8.10-sunos-x86.tar.gz +3e49e1c958815d0144cafe5e43c2fa83e775dd1c node-v0.8.10-x86.msi +9605340dca27725110eebcb15fdf61599622e308 node-v0.8.10.pkg +c596cce77726724441cf7fc98f42df3a5335ab8e node-v0.8.10.tar.gz +f6d172e3452e2bf429dc75836a385eff22407c83 node.exe +ccb8c0e0fa052d8da48ea421cc7a220bb89835f9 node.exp +7ea077e6ca1216d5e8f42e445f75f0542f7d85c4 node.lib +d86ad55c37ac1a0975731ab444fc58c93a7bca47 node.pdb +90fc70b09f92f788fc68a116f589a86ca3309fdb x64/node-v0.8.10-x64.msi +4b62cedf4bbbff1ffb8df6d52c9a57255f383ad3 x64/node.exe +6b4b813c3b065154ce437b7f36a15beceeb76af0 x64/node.exp +9e7dd3ddca3ba37483ac2125c39a52e72035e1d0 x64/node.lib +28de8dd05af5e390f5bd63508bd27b7c683177de x64/node.pdb +``` diff --git a/node-v0.8.14/doc/blog/release/v0.8.11.md b/node-v0.8.14/doc/blog/release/v0.8.11.md new file mode 100644 index 0000000..f378d5b --- /dev/null +++ b/node-v0.8.14/doc/blog/release/v0.8.11.md @@ -0,0 +1,63 @@ +category: release +version: v0.8.11 +date: Thu Sep 27 10:13:12 PDT 2012 +slug: node-v0.8.11 +title: Node v0.8.11 (Stable) + +This is just a minor bugfix release to correct the regression in +[v0.8.10](http://blog.nodejs.org/2012/09/25/node-v0-8-10-stable/). + +If you haven't yet upgraded to v0.8.10, then please use this release +instead. + +2012.09.27, Version 0.8.11 (Stable) + +* fs: Fix stat() size reporting for large files (Ben Noordhuis) + + +Source Code: http://nodejs.org/dist/v0.8.11/node-v0.8.11.tar.gz + +Macintosh Installer (Universal): http://nodejs.org/dist/v0.8.11/node-v0.8.11.pkg + +Windows Installer: http://nodejs.org/dist/v0.8.11/node-v0.8.11-x86.msi + +Windows x64 Installer: http://nodejs.org/dist/v0.8.11/x64/node-v0.8.11-x64.msi + +Windows x64 Files: http://nodejs.org/dist/v0.8.11/x64/ + +Linux 32-bit Binary: http://nodejs.org/dist/v0.8.11/node-v0.8.11-linux-x86.tar.gz + +Linux 64-bit Binary: http://nodejs.org/dist/v0.8.11/node-v0.8.11-linux-x64.tar.gz + +Solaris 32-bit Binary: http://nodejs.org/dist/v0.8.11/node-v0.8.11-sunos-x86.tar.gz + +Solaris 64-bit Binary: http://nodejs.org/dist/v0.8.11/node-v0.8.11-sunos-x64.tar.gz + +Other release files: http://nodejs.org/dist/v0.8.11/ + +Website: http://nodejs.org/docs/v0.8.11/ + +Documentation: http://nodejs.org/docs/v0.8.11/api/ + +Shasums: + +``` +3677fdcce837233d4d3d5cdfb8685123ef38fcc2 node-v0.8.11-darwin-x64.tar.gz +24213b076d5c95a1ee7598c540a454a4d6b1d899 node-v0.8.11-darwin-x86.tar.gz +380e533b7953767ec3a43109d37615238296d15c node-v0.8.11-linux-x64.tar.gz +0d9c1bd3a97aa7a5adf6274271f4a8e7745ff704 node-v0.8.11-linux-x86.tar.gz +d4dbb70ca6a3e06c763b7be5fffaae1c7630bd69 node-v0.8.11-sunos-x64.tar.gz +d8fcd334118576a744a57eb1f3565c242810f4f1 node-v0.8.11-sunos-x86.tar.gz +80a14ed82672d3c5c14f60f41ba3f03d65dde13f node-v0.8.11-x86.msi +8a096cdaf7c3e76ee82373214b51a7c7f306de47 node-v0.8.11.pkg +e9dd36cbbe03c632ee7e9c52e06122fa022981c8 node-v0.8.11.tar.gz +5bf31a7e2518d06df1dd05f135617db8c32d8a2e node.exe +79a21c6de2d8e38937865c4cd36306b92e37c832 node.exp +31862938d8cd95efe0e6121764c7797a1487fe51 node.lib +2bbcad390e7fc122be74cb1a116f5420057e9600 node.pdb +30798c0b6d69b13ba94c3501b222f88212f77149 x64/node-v0.8.11-x64.msi +1e69c413252121ab475420795023f9799823d3f7 x64/node.exe +470683d233c9d0295f45f5635203560b242d6f7c x64/node.exp +2134bf022d719da1e455585792af8782ffe81d33 x64/node.lib +1c2a22d0ce3c902f5dae7fde15d32bd9393a2153 x64/node.pdb +``` diff --git a/node-v0.8.14/doc/blog/release/v0.8.12.md b/node-v0.8.14/doc/blog/release/v0.8.12.md new file mode 100644 index 0000000..b890485 --- /dev/null +++ b/node-v0.8.14/doc/blog/release/v0.8.12.md @@ -0,0 +1,73 @@ +category: release +version: v0.8.12 +date: Fri Oct 12 08:52:06 PDT 2012 +slug: node-v0.8.12 +title: Node v0.8.12 (Stable) + +2012.10.12, Version 0.8.12 (Stable) + +* npm: Upgrade to 1.1.63 + +* crypto: Reduce stability index to 2-Unstable (isaacs) + +* windows: fix handle leak in uv_fs_utime (Bert Belder) + +* windows: fix application crashed popup in debug version (Bert Belder) + +* buffer: report proper retained size in profiler (Ben Noordhuis) + +* buffer: fix byteLength with UTF-16LE (koichik) + +* repl: make "end of input" JSON.parse() errors throw in the REPL (Nathan Rajlich) + +* repl: make invalid RegExp modifiers throw in the REPL (Nathan Rajlich) + +* http: handle multiple Proxy-Authenticate values (Willi Eggeling) + + +Source Code: http://nodejs.org/dist/v0.8.12/node-v0.8.12.tar.gz + +Macintosh Installer (Universal): http://nodejs.org/dist/v0.8.12/node-v0.8.12.pkg + +Windows Installer: http://nodejs.org/dist/v0.8.12/node-v0.8.12-x86.msi + +Windows x64 Installer: http://nodejs.org/dist/v0.8.12/x64/node-v0.8.12-x64.msi + +Windows x64 Files: http://nodejs.org/dist/v0.8.12/x64/ + +Linux 32-bit Binary: http://nodejs.org/dist/v0.8.12/node-v0.8.12-linux-x86.tar.gz + +Linux 64-bit Binary: http://nodejs.org/dist/v0.8.12/node-v0.8.12-linux-x64.tar.gz + +Solaris 32-bit Binary: http://nodejs.org/dist/v0.8.12/node-v0.8.12-sunos-x86.tar.gz + +Solaris 64-bit Binary: http://nodejs.org/dist/v0.8.12/node-v0.8.12-sunos-x64.tar.gz + +Other release files: http://nodejs.org/dist/v0.8.12/ + +Website: http://nodejs.org/docs/v0.8.12/ + +Documentation: http://nodejs.org/docs/v0.8.12/api/ + +Shasums: + +``` +2d40157436b34e9e347c587de9945e7022eb9acc node-v0.8.12-darwin-x64.tar.gz +b6ba1d2e478881e0a5248cb319ce0913ca39a51b node-v0.8.12-darwin-x86.tar.gz +5353dfab2005992deee13e6e00a30509c8c86d4b node-v0.8.12-linux-x64.tar.gz +9e501b995469d554e3356b6f5f85b72abed83310 node-v0.8.12-linux-x86.tar.gz +b3e8e655b3c6f0a2c641dcb0e22372edb6f45ffd node-v0.8.12-sunos-x64.tar.gz +82c46d12a52e09bda3ad4bd0cdb8ad18480e679a node-v0.8.12-sunos-x86.tar.gz +d70e7bc718699651281110cd9f3f13ae50ac36be node-v0.8.12-x86.msi +d24d17d34425eb86cc237b8e68fdd5d199cb0ad8 node-v0.8.12.pkg +719397c7f65365b2ec6510863ac62bd291784910 node-v0.8.12.tar.gz +ac7151c05730982eb37a7f390386219c4d05b57d node.exe +000771bbc1e26f8ac5d11183b6538f25214b64a6 node.exp +b036c368ff65f96ca44ac0ccf8d742c41ce00a95 node.lib +98edc84132157d44df7a4d08b6788843fe542961 node.pdb +d1cccae53dcb54e08a8771ef0f9406e327ac4db3 x64/node-v0.8.12-x64.msi +0aa3088bd6a55864d25e84091b3a3b796ce20ce9 x64/node.exe +1d6dc06515cead63a2e547aacc73cfb7ad8003a2 x64/node.exp +7f55dd2367523c151e4d8492c596f076e0e5d151 x64/node.lib +e34d679b61c77026dd0f437d3d91a84b83a422d3 x64/node.pdb +``` diff --git a/node-v0.8.14/doc/blog/release/v0.8.13.md b/node-v0.8.14/doc/blog/release/v0.8.13.md new file mode 100644 index 0000000..cd8e088 --- /dev/null +++ b/node-v0.8.14/doc/blog/release/v0.8.13.md @@ -0,0 +1,72 @@ +category: release +version: v0.8.13 +date: Thu Oct 25 12:26:44 PDT 2012 +slug: node-v0.8.13 +title: Node v0.8.13 (Stable) + +2012.10.25, Version 0.8.13 (Stable) + +* V8: Upgrade to 3.11.10.25 + +* npm: Upgrade to 1.1.65 + +* url: parse hostnames that start with - or _ (Ben Noordhuis) + +* repl: Fix Windows 8 terminal issue (Bert Belder) + +* typed arrays: use signed char for signed int8s (Aaron Jacobs) + +* crypto: fix bugs in DiffieHellman (Ben Noordhuis) + +* configure: turn on VFPv3 on ARMv7 (Ben Noordhuis) + +* Re-enable OpenSSL UI for entering passphrases via tty (Ben Noordhuis) + +* repl: ensure each REPL instance gets its own "context" (Nathan Rajlich) + + +Source Code: http://nodejs.org/dist/v0.8.13/node-v0.8.13.tar.gz + +Macintosh Installer (Universal): http://nodejs.org/dist/v0.8.13/node-v0.8.13.pkg + +Windows Installer: http://nodejs.org/dist/v0.8.13/node-v0.8.13-x86.msi + +Windows x64 Installer: http://nodejs.org/dist/v0.8.13/x64/node-v0.8.13-x64.msi + +Windows x64 Files: http://nodejs.org/dist/v0.8.13/x64/ + +Linux 32-bit Binary: http://nodejs.org/dist/v0.8.13/node-v0.8.13-linux-x86.tar.gz + +Linux 64-bit Binary: http://nodejs.org/dist/v0.8.13/node-v0.8.13-linux-x64.tar.gz + +Solaris 32-bit Binary: http://nodejs.org/dist/v0.8.13/node-v0.8.13-sunos-x86.tar.gz + +Solaris 64-bit Binary: http://nodejs.org/dist/v0.8.13/node-v0.8.13-sunos-x64.tar.gz + +Other release files: http://nodejs.org/dist/v0.8.13/ + +Website: http://nodejs.org/docs/v0.8.13/ + +Documentation: http://nodejs.org/docs/v0.8.13/api/ + +Shasums: +``` +1f396f068e40639f70e5d60e8e33d0cbb5597748 node-v0.8.13-darwin-x64.tar.gz +afa416c3b6209f3d72926537c85d5943b3b07a0d node-v0.8.13-darwin-x86.tar.gz +bdcf8b69ccba2ca326c8ff2921232c1663a79d78 node-v0.8.13-linux-x64.tar.gz +d1fc168b092234bac665dc65d242f3367dfc0f24 node-v0.8.13-linux-x86.tar.gz +d3d5b19c133c73f060efa4bbe274195c9579f4be node-v0.8.13-sunos-x64.tar.gz +98916b4f0c9855dd02d87223d6369f5fa281cbe5 node-v0.8.13-sunos-x86.tar.gz +732f70fbb800c8fee6202e939502c0f23f76d4a1 node-v0.8.13-x86.msi +e2da495a2f8dd4b0cd25810c3b4e6b2e9e71cfe3 node-v0.8.13.pkg +9112a128d83f3e7d26ba0965eb426de0f18c3149 node-v0.8.13.tar.gz +f8c75e5877f103a842067adff6f6580d1c250c9b node.exe +b950a56fa0a00b78212c5d95e4ca6381f8285df9 node.exp +6fcfb00aaf78be643330f645d2d83d461bc1cbe7 node.lib +b6b0d540061e83bbe165afbc25aeeb19b00fbbf2 node.pdb +8017014664dca6b255724f30827553ca420580af x64/node-v0.8.13-x64.msi +8a9fd20b6b24aa3bb8eda8f2f9fa1ede19588a41 x64/node.exe +74ceab4f7d3192bbd2d13d602fe66e3caf7d08e2 x64/node.exp +780c395cab41a0ef59bdd82fe39f370fa1c5e839 x64/node.lib +526bd6fadffcea8f56b0a761ccae01f65b018947 x64/node.pdb +``` diff --git a/node-v0.8.14/doc/blog/release/v0.8.2.md b/node-v0.8.14/doc/blog/release/v0.8.2.md new file mode 100644 index 0000000..c96585f --- /dev/null +++ b/node-v0.8.14/doc/blog/release/v0.8.2.md @@ -0,0 +1,73 @@ +version: 0.8.2 +title: Version 0.8.2 (stable) +category: release +slug: node-v0-8-2-stable +date: 2012.07.09 + +2012.07.09, Version 0.8.2 (Stable) + +* npm: Upgrade to 1.1.36 + +* readline: don't use Function#call() (Nathan Rajlich) + +* Code cleanup to pass 'use strict' (Jonas Westerlund) + +* module: add filename to require() json errors (TJ Holowaychuk) + +* readline: fix for unicode prompts (Tim Macfarlane) + +* timers: fix handling of large timeouts (Ben Noordhuis) + +* repl: fix passing an empty line inserting "undefined" into the buffer (Nathan Rajlich) + +* repl: fix crashes when buffering command (Maciej Małecki) + +* build: rename strict_aliasing to node_no_strict_aliasing (Ben Noordhuis) + +* build: disable -fstrict-aliasing for any gcc < 4.6.0 (Ben Noordhuis) + +* build: detect cc version with -dumpversion (Ben Noordhuis) + +* build: handle output of localized gcc or clang (Ben Noordhuis) + +* unix: fix memory corruption in freebsd.c (Ben Noordhuis) + +* unix: fix 'zero handles, one request' busy loop (Ben Noordhuis) + +* unix: fix busy loop on unexpected tcp message (Ben Noordhuis) + +* unix: fix EINPROGRESS busy loop (Ben Noordhuis) + + +Source Code: http://nodejs.org/dist/v0.8.2/node-v0.8.2.tar.gz + +Macintosh Installer (Universal): http://nodejs.org/dist/v0.8.2/node-v0.8.2.pkg + +Windows Installer: http://nodejs.org/dist/v0.8.2/node-v0.8.2-x86.msi + +Windows x64 Installer: http://nodejs.org/dist/v0.8.2/x64/node-v0.8.2-x64.msi + +Windows x64 Files: http://nodejs.org/dist/v0.8.2/x64/ + +Other release files: http://nodejs.org/dist/v0.8.2/ + +Website: http://nodejs.org/docs/v0.8.2/ + +Documentation: http://nodejs.org/docs/v0.8.2/api/ + +Shasums: + +``` +6571b7aad17ed4860d9ecb7946098dcd569e3eb0 node-v0.8.2-x86.msi +8436e940b8c3b1dff73bf4d1eee98fd3b1fc6295 node-v0.8.2.pkg +0e743d21b487151e67950f09198def058db19a1e node-v0.8.2.tar.gz +dcc45bee9d4a6b38ccef0f00e4a6028864f07278 node.exe +5417f98a533c90f2b72ed3a2a002c2c36a65cb75 node.exp +57700a9555d16ebf5401898c179669654f045c5f node.lib +5bf7e8777d715d5d6b40c21ea3969c4244c20879 node.pdb +6a5fe7efb56c3e17de357e9b9adc8f1c54db895a x64/node-v0.8.2-x64.msi +72f04cb5bb25bd568cb7bc42eb5e1365e614b672 x64/node.exe +6b402ca44a45a3bc1393854d92247bf79eb3df2b x64/node.exp +ad39add3918fb31aef25e3a4acfe1da499900143 x64/node.lib +fa981c97e0c474ede8e7c28904d710cc3ee3390c x64/node.pdb +``` diff --git a/node-v0.8.14/doc/blog/release/v0.8.3.md b/node-v0.8.14/doc/blog/release/v0.8.3.md new file mode 100644 index 0000000..cc59965 --- /dev/null +++ b/node-v0.8.14/doc/blog/release/v0.8.3.md @@ -0,0 +1,71 @@ +category: release +date: 2012-07-19T17:09:26.413Z +version: 0.8.3 +title: Version 0.8.3 (Stable) +slug: node-v0-8-3-stable + +2012.07.19, Version 0.8.3 (Stable) + +* V8: upgrade to 3.11.10.15 + +* npm: Upgrade to 1.1.43 + +* net: fix net.Server.listen({fd:x}) error reporting (Ben Noordhuis) + +* net: fix bogus errno reporting (Ben Noordhuis) + +* build: Move npm shebang logic into an npm script (isaacs) + +* build: fix add-on loading on freebsd (Ben Noordhuis) + +* build: disable unsafe optimizations (Ben Noordhuis) + +* build: fix spurious mksnapshot crashes for good (Ben Noordhuis) + +* build: speed up genv8constants (Dave Pacheco) + +* fs: make unwatchFile() remove a specific listener (Ben Noordhuis) + +* domain: Remove first arg from intercepted fn (Toshihiro Nakamura) + +* domain: Fix memory leak on error (isaacs) + +* events: Fix memory leak from removeAllListeners (Nathan Rajlich) + +* zlib: Fix memory leak in Unzip class. (isaacs) + +* crypto: Fix memory leak in DecipherUpdate() (Ben Noordhuis) + + +Source Code: http://nodejs.org/dist/v0.8.3/node-v0.8.3.tar.gz + +Macintosh Installer (Universal): http://nodejs.org/dist/v0.8.3/node-v0.8.3.pkg + +Windows Installer: http://nodejs.org/dist/v0.8.3/node-v0.8.3-x86.msi + +Windows x64 Installer: http://nodejs.org/dist/v0.8.3/x64/node-v0.8.3-x64.msi + +Windows x64 Files: http://nodejs.org/dist/v0.8.3/x64/ + +Other release files: http://nodejs.org/dist/v0.8.3/ + +Website: http://nodejs.org/docs/v0.8.3/ + +Documentation: http://nodejs.org/docs/v0.8.3/api/ + +Shasums: + +``` +10d478f3a084bf5e705be3f232c41f3e3d56e57f node-v0.8.3-x86.msi +a6b9168eaa817692914d0de6c0d04702d7615681 node-v0.8.3.pkg +f699d3788e242ed87a9037bae1aa0fa9335e45a9 node-v0.8.3.tar.gz +60294792588e000d846a4c416617f127d5ba6163 node.exe +efc7f597745bcf201a7996ecf9f9b94d9112b89f node.exp +4c5ea551d88fe21465f7d2e4c6f3d39ee02f2209 node.lib +fd2c3873bed6872fd36e5906b65dfb4f1cec32fb node.pdb +64c6ec7db3f7f24e70ccecdada6f7b966c73134c x64/node-v0.8.3-x64.msi +94cd3f41004f1e9b8efd8d4a337b6154c1d5fee2 x64/node.exe +a6ed8354a14577b9200c780b129e2b66f7b85e39 x64/node.exp +3427a95bf9b14f56eec3f59aed80077fbde8f67f x64/node.lib +9af962968551daad044259641a615697f6588616 x64/node.pdb +``` diff --git a/node-v0.8.14/doc/blog/release/v0.8.4.md b/node-v0.8.14/doc/blog/release/v0.8.4.md new file mode 100644 index 0000000..3e1ea5b --- /dev/null +++ b/node-v0.8.14/doc/blog/release/v0.8.4.md @@ -0,0 +1,59 @@ +category: release +date: 2012-07-25T17:21:16.176Z +version: 0.8.4 +title: Version 0.8.4 (Stable) +slug: node-v0-8-4-stable + +2012.07.25, Version 0.8.4 (Stable) + +* V8: Upgrade to 3.11.10.17 + +* npm: Upgrade to 1.1.45 + +* net: fix Socket({ fd: 42 }) api (Ben Noordhuis) + +* readline: Remove event listeners on close (isaacs) + +* windows: correctly prep long path for fs.exists(Sync) (Bert Belder) + +* debugger: wake up the event loop when a debugger command is dispatched (Peter Rybin) + +* tls: verify server's identity (Fedor Indutny) + +* net: ignore socket.setTimeout(Infinity or NaN) (Fedor Indutny) + + +Source Code: http://nodejs.org/dist/v0.8.4/node-v0.8.4.tar.gz + +Macintosh Installer (Universal): http://nodejs.org/dist/v0.8.4/node-v0.8.4.pkg + +Windows Installer: http://nodejs.org/dist/v0.8.4/node-v0.8.4-x86.msi + +Windows x64 Installer: http://nodejs.org/dist/v0.8.4/x64/node-v0.8.4-x64.msi + +Windows x64 Files: http://nodejs.org/dist/v0.8.4/x64/ + +Other release files: http://nodejs.org/dist/v0.8.4/ + +Website: http://nodejs.org/docs/v0.8.4/ + +Documentation: http://nodejs.org/docs/v0.8.4/api/ + +Shasums: + +``` +387d7ac58d79dac301960510dfb7ee96fbf39072 node-v0.8.4-x86.msi +66687da0ef190e8c07d5499ae3c408a6cca7ac30 node-v0.8.4.pkg +8473e3dd48ab3734e2c92de0518cb80c2cdf750f node-v0.8.4.tar.gz +724ec6dc5e86805bfac79c8a702638c353850ea3 node.exe +9bf483f72ad7884988d0678f7dc5bc000f4d21d2 node.exp +3b7bd3915b62896e5c2f5701fd5d1c7fb53cdd27 node.lib +9c3079ee727d471cef9fd91c7067d0a72349bfcb node.pdb +236a693074f2c69157e2918d1342a7850fc939ca npm-1.1.45.tgz +7126700cb321f688901e7773785eb88274906d50 npm-1.1.45.zip +e9f414ba043f1daa5eee65506ef33c5377d87a09 x64/node-v0.8.4-x64.msi +4cc86f21285b7f3d3cbd594ba604f06fb3434502 x64/node.exe +6bf207a6b587bf1b01f18e9d0f2eefb528d82c2f x64/node.exp +e7b0d65992324b0688c61f6e534f3527e7e0b59f x64/node.lib +9a0072f528f9055531dee2bfa991882836b235de x64/node.pdb +``` diff --git a/node-v0.8.14/doc/blog/release/v0.8.5.md b/node-v0.8.14/doc/blog/release/v0.8.5.md new file mode 100644 index 0000000..86915eb --- /dev/null +++ b/node-v0.8.14/doc/blog/release/v0.8.5.md @@ -0,0 +1,77 @@ +version: 0.8.5 +title: Version 0.8.5 (stable) +category: release +slug: node-v0-8-5-stable +date: Thu Aug 02 2012 15:00:45 GMT-0700 (PDT) + +2012.08.02, Version 0.8.5 (Stable) + +* node: tag Encode and friends NODE_EXTERN (Ben Noordhuis) + +* fs: fix ReadStream / WriteStream missing callback (Gil Pedersen) + +* fs: fix readFileSync("/proc/cpuinfo") regression (Ben Noordhuis) + +* installer: don't assume bash is installed (Ben Noordhuis) + +* Report errors properly from --eval and stdin (isaacs) + +* assert: fix throws() throws an error without message property (koichik) + +* cluster: fix libuv assert in net.listen() (Ben Noordhuis) + +* build: always link sunos builds with libumem (Trent Mick) + +* build: improve armv7 / hard-float detection (Adam Malcontenti-Wilson) + +* https: Use host header as effective servername (isaacs) + +* sunos: work around OS bug to prevent fs.watch() from spinning (Bryan Cantrill) + +* linux: fix 'two watchers, one path' segfault (Ben Noordhuis) + +* windows: fix memory leaks in many fs functions (Bert Belder) + +* windows: don't allow directories to be opened for writing/appending (Bert Belder) + +* windows: make fork() work even when not all stdio handles are valid (Bert Belder) + +* windows: make unlink() not remove mount points, and improve performance (Bert Belder) + +* build: Sign pkg installer for OS X (isaacs) + + +Source Code: http://nodejs.org/dist/v0.8.5/node-v0.8.5.tar.gz + +Macintosh Installer (Universal): http://nodejs.org/dist/v0.8.5/node-v0.8.5.pkg + +Windows Installer: http://nodejs.org/dist/v0.8.5/node-v0.8.5-x86.msi + +Windows x64 Installer: http://nodejs.org/dist/v0.8.5/x64/node-v0.8.5-x64.msi + +Windows x64 Files: http://nodejs.org/dist/v0.8.5/x64/ + +Other release files: http://nodejs.org/dist/v0.8.5/ + +Website: http://nodejs.org/docs/v0.8.5/ + +Documentation: http://nodejs.org/docs/v0.8.5/api/ + +Shasums: + +``` +74b470d04c3dac9f5838d4ed61e2fb50e394114a node-v0.8.5-x86.msi +28280575b717306b34440c83aace720dccc3047f node-v0.8.5.pkg +835ba5ca429e56f65aeb1a5d9730fff105e86337 node-v0.8.5.tar.gz +c8ce66eefd6d75b44cdf29bb49aeffe4ea534b7f node.exe +d3832fb5a7a45d739c9d3faa7e13115bdaaa9cc7 node.exp +5dee595f12dbfdee14b6e8aebc07a77ee96e5e45 node.lib +ac62ec2d2508dfcd0c2f5cfcf725286ad876fb7a node.pdb +12876d80668b066b460833d096998525d8eceec7 npm-1.1.46.tgz +4e820e5a99512e194ec30878ede08488211c8391 npm-1.1.46.zip +95882b6aeab74725197b10d31ff4ee3a0723574c x64/node-v0.8.5-x64.msi +9d9c0652e57e05708b59bba78a55bc1237fcfb73 x64/node.exe +f13f377c432c5a8fb4661abaae3a07c46ac74a66 x64/node.exp +a17e3e8742ac084e1f7f99f721470e9d6182e75f x64/node.lib +4026170fed5a55fad6ee569daa9666cbb9d5ae3d x64/node.pdb +``` diff --git a/node-v0.8.14/doc/blog/release/v0.8.6.md b/node-v0.8.14/doc/blog/release/v0.8.6.md new file mode 100644 index 0000000..76cc072 --- /dev/null +++ b/node-v0.8.14/doc/blog/release/v0.8.6.md @@ -0,0 +1,85 @@ +version: 0.8.6 +title: Version 0.8.6 (stable) +category: release +slug: node-v0-8-6-stable +date: 2012-08-07T19:03:55.905Z + +2012.08.07, Version 0.8.6 (Stable) + +This is the first release to include binary distributions for all +supported Unix operating systems (Linux, Darwin, and SunOS). To use +the binary distribution tarballs, you can unpack them directly into a +destination directory: + + cd ~/node/ # or /usr/local if you're feeling brave + tar xzvf /path/to/binary.tar.gz --strip=1 + +This is an experimental feature. Please use it and provide feedback. + +* npm: Upgrade to v1.1.48 + +* Add 'make binary' to build binary tarballs for all Unixes (Nathan Rajlich) + +* zlib: Emit 'close' on destroy(). (Dominic Tarr) + +* child_process: Fix stdout=null when stdio=['pipe'] (Tyler Neylon) + +* installer: prevent ETXTBSY errors (Ben Noordhuis) + +* installer: honor --without-npm, default install path (Ben Noordhuis) + +* net: make pause work with connecting sockets (Bert Belder) + +* installer: fix cross-compile installs (Ben Noordhuis) + +* net: fix .listen({fd:0}) (Ben Noordhuis) + +* windows: map WSANO_DATA to UV_ENOENT (Bert Belder) + + +Source Code: http://nodejs.org/dist/v0.8.6/node-v0.8.6.tar.gz + +Macintosh Installer (Universal): http://nodejs.org/dist/v0.8.6/node-v0.8.6.pkg + +Windows Installer: http://nodejs.org/dist/v0.8.6/node-v0.8.6-x86.msi + +Windows x64 Installer: http://nodejs.org/dist/v0.8.6/x64/node-v0.8.6-x64.msi + +Windows x64 Files: http://nodejs.org/dist/v0.8.6/x64/ + +Linux 32-bit Binary Package: http://nodejs.org/dist/v0.8.6/node-v0.8.6-linux-x86.tar.gz + +Linux 64-bit Binary Package: http://nodejs.org/dist/v0.8.6/node-v0.8.6-linux-x64.tar.gz + +Solaris 32-bit Binary Package: http://nodejs.org/dist/v0.8.6/node-v0.8.6-sunos-x86.tar.gz + +Solaris 64-bit Binary Package: http://nodejs.org/dist/v0.8.6/node-v0.8.6-sunos-x64.tar.gz + +Other release files: http://nodejs.org/dist/v0.8.6/ + +Website: http://nodejs.org/docs/v0.8.6/ + +Documentation: http://nodejs.org/docs/v0.8.6/api/ + +Shasums: + +``` +c23a57601150b3ec59aeeb0eef607d9e430e17c2 node-v0.8.6-darwin-x64.tar.gz +8f7e4e837f61991eff4605678ab27c82e854bc38 node-v0.8.6-darwin-x86.tar.gz +32ce9d28d6a294878ce9ee8f23b6fa7ecb3130e7 node-v0.8.6-linux-x64.tar.gz +6f71518f044705ff1a7d9400a573906a99c5834c node-v0.8.6-linux-x86.tar.gz +ec9c02e9713a81d8f4848924cc38e5ed28a06fc4 node-v0.8.6-sunos-x64.tar.gz +ac96cc4ce3eee4dc54ef7936ad4fd8eb04fbe359 node-v0.8.6-sunos-x86.tar.gz +0a2aca229c9cb2ec4a4a82ff88de7ea0868d1890 node-v0.8.6-x86.msi +84127d73a968f5951a9682b592a79779d1396c9e node-v0.8.6.pkg +34c7ad2bb5450653748c65840155852d67742258 node-v0.8.6.tar.gz +42f3b792326efdfc9b0d95eebd7f9f716cadb1c0 node.exe +fc56e816081ebef450ce7ed92bfd543d53191ac3 node.exp +e91f1648e4e8f7586790443248326222101c286c node.lib +8106b33d1cdae69103ca07b16c7f5d690308d751 node.pdb +6226474859e1cf2f1314d92b6207183bb36c6007 x64/node-v0.8.6-x64.msi +3c1ac597956ea9f1e7eab62f85a23e3e436cd0e8 x64/node.exe +599df091faecff536f52d17463c70e07cf9ed54f x64/node.exp +70bac4dcb9f845c8c8cb9443ff09f839fc86aac7 x64/node.lib +eb59a0ed841c9e93c406b4c636b2048973cbfae4 x64/node.pdb +``` diff --git a/node-v0.8.14/doc/blog/release/v0.8.7.md b/node-v0.8.14/doc/blog/release/v0.8.7.md new file mode 100644 index 0000000..35031cd --- /dev/null +++ b/node-v0.8.14/doc/blog/release/v0.8.7.md @@ -0,0 +1,75 @@ +version: 0.8.7 +title: Version 0.8.7 (stable) +category: release +slug: node-v0-8-7-stable +date: 2012-08-15T23:23:16.131Z + +2012.08.15, Version 0.8.7 (Stable) + +* npm: Upgrade to 1.1.49 + +* website: download page (Golo Roden) + +* crypto: fix uninitialized memory access in openssl (Ben Noordhuis) + +* buffer, crypto: fix buffer decoding (Ben Noordhuis) + +* build: compile with -fno-tree-vrp when gcc >= 4.0 (Ben Noordhuis) + +* tls: handle multiple CN fields when verifying cert (Ben Noordhuis) + +* doc: remove unused util from child_process (Kyle Robinson Young) + +* build: rework -fvisibility=hidden detection (Ben Noordhuis) + +* windows: don't duplicate invalid stdio handles (Bert Belder) + +* windows: fix typos in process-stdio.c (Bert Belder) + + +Source Code: http://nodejs.org/dist/v0.8.7/node-v0.8.7.tar.gz + +Macintosh Installer (Universal): http://nodejs.org/dist/v0.8.7/node-v0.8.7.pkg + +Windows Installer: http://nodejs.org/dist/v0.8.7/node-v0.8.7-x86.msi + +Windows x64 Installer: http://nodejs.org/dist/v0.8.7/x64/node-v0.8.7-x64.msi + +Windows x64 Files: http://nodejs.org/dist/v0.8.7/x64/ + +Linux 32-bit Binary: http://nodejs.org/dist/v0.8.7/node-v0.8.7-linux-x86.tar.gz + +Linux 64-bit Binary: http://nodejs.org/dist/v0.8.7/node-v0.8.7-linux-x64.tar.gz + +Solaris 32-bit Binary: http://nodejs.org/dist/v0.8.7/node-v0.8.7-sunos-x86.tar.gz + +Solaris 64-bit Binary: http://nodejs.org/dist/v0.8.7/node-v0.8.7-sunos-x64.tar.gz + +Other release files: http://nodejs.org/dist/v0.8.7/ + +Website: http://nodejs.org/docs/v0.8.7/ + +Documentation: http://nodejs.org/docs/v0.8.7/api/ + +Shasums: + +``` +3ff82e65a845a2d5f27ea57e8a1e29e6d10f5128 node-v0.8.7-darwin-x64.tar.gz +d72ac02727aaefa094f8d06a0a124078da007df0 node-v0.8.7-darwin-x86.tar.gz +0882e19157e98c3e2214e772e3ae714125863ae6 node-v0.8.7-linux-x64.tar.gz +3e388d47f6e79acccfab117cceaeed19ceb1b14c node-v0.8.7-linux-x86.tar.gz +ffb81708df10d3c225d8f2ce57965a40db6ca556 node-v0.8.7-sunos-x64.tar.gz +19df6ae999e4a5c1dada83b72516b3941eeb701e node-v0.8.7-sunos-x86.tar.gz +19f90a0cfa41c7eaf683393d46d06aecc2f99f84 node-v0.8.7-x86.msi +0c2dcf2d5491be7b429681193a13c18de1ba488a node-v0.8.7.pkg +58ffb5884304e2f8415d8cee7921c42f66fc8d7b node-v0.8.7.tar.gz +ecaee480f0337e92870ca83aed1b49863b3f659d node.exe +ea2e25daad114692357383bfc8b4ac910fe02d99 node.exp +70c8f054a5c42f6d4e3ca5154ca1a360f549d66f node.lib +180bcc036cd5deaef49bf12fddeeafc2e78152e3 node.pdb +12ad712ff9e28eb1bdf7e508ce3a2b872ec37d4d x64/node-v0.8.7-x64.msi +c30607099ad4699b11e3ca37f94a9da196a36dc6 x64/node.exe +f864ed339952604c2205e25927fb4851da5b79b6 x64/node.exp +ce711929befe756f942a039213aeece2ef3edcc1 x64/node.lib +11bb755b054bc6ee2e441758f7d42d131cf6d557 x64/node.pdb +``` diff --git a/node-v0.8.14/doc/blog/release/v0.8.8.md b/node-v0.8.14/doc/blog/release/v0.8.8.md new file mode 100644 index 0000000..83e8308 --- /dev/null +++ b/node-v0.8.14/doc/blog/release/v0.8.8.md @@ -0,0 +1,77 @@ +version: 0.8.8 +title: Version 0.8.8 (stable) +category: release +slug: node-v0-8-8-stable +date: 2012-08-22T19:50:38.833Z + +2012.08.22, Version 0.8.8 (Stable) + +* V8: upgrade to 3.11.10.19 + +* npm: upgrade to 1.1.59 + +* windows: fix uninitialized memory access in uv_update_time() (Bert Belder) + +* unix, windows: fix memory corruption in fs-poll.c (Ben Noordhuis) + +* unix: fix integer overflow in uv_hrtime (Tim Holy) + +* sunos: fix uv_cpu_info() on x86_64 (Ben Noordhuis) + +* tls: update default cipher list (Ben Noordhuis) + +* unix: Fix llvm and older gcc duplicate symbol warnings (Bert Belder) + +* fs: fix use after free in stat watcher (Ben Noordhuis) + +* build: Fix using manually compiled gcc on OS X (Nathan Rajlich) + +* windows: make junctions work again (Bert Belder) + + +Source Code: http://nodejs.org/dist/v0.8.8/node-v0.8.8.tar.gz + +Macintosh Installer (Universal): http://nodejs.org/dist/v0.8.8/node-v0.8.8.pkg + +Windows Installer: http://nodejs.org/dist/v0.8.8/node-v0.8.8-x86.msi + +Windows x64 Installer: http://nodejs.org/dist/v0.8.8/x64/node-v0.8.8-x64.msi + +Windows x64 Files: http://nodejs.org/dist/v0.8.8/x64/ + +Linux 32-bit Binary: http://nodejs.org/dist/v0.8.8/node-v0.8.8-linux-x86.tar.gz + +Linux 64-bit Binary: http://nodejs.org/dist/v0.8.8/node-v0.8.8-linux-x64.tar.gz + +SunOS 32-bit Binary: http://nodejs.org/dist/v0.8.8/node-v0.8.8-sunos-x86.tar.gz + +SunOS 64-bit Binary: http://nodejs.org/dist/v0.8.8/node-v0.8.8-sunos-x64.tar.gz + +Other release files: http://nodejs.org/dist/v0.8.8/ + +Website: http://nodejs.org/docs/v0.8.8/ + +Documentation: http://nodejs.org/docs/v0.8.8/api/ + +Shasums: + +``` +ecf54d3aad371621446ee0432f7c182a4494a1a3 node-v0.8.8-darwin-x64.tar.gz +d1aca7c797fd262e2f0c601fe5cc3815622ce801 node-v0.8.8-darwin-x86.tar.gz +603c36611c54651c149a26dc5bc6f833b0b846d0 node-v0.8.8-linux-x64.tar.gz +30c66fc26845b14ef99d3e043bb4dfcba605bd45 node-v0.8.8-linux-x86.tar.gz +cd0d46d232d882dd4afe955bd8acd6c435c2f5fe node-v0.8.8-sunos-x64.tar.gz +857facbd156d4f7a49b9e1c5610b4a1f893bf534 node-v0.8.8-sunos-x86.tar.gz +bb08591a6f973f3699085abb50f6bdc9586f01f9 node-v0.8.8-x86.msi +14239f6f379953405ca914b129c19b379718ba64 node-v0.8.8.pkg +5ddafc059d2f774e35e6375f5b61157879a46f0f node-v0.8.8.tar.gz +6cc8a0a363c1efa184f6b72970a5d1182b5b44aa node.exe +395c73c055886e2e981b46f3c363837613456d82 node.exp +ca8a9560b3da13ecddbbc2fb15c1b3ab85d7371b node.lib +b8e0e35b0ecc7c3514ad8ca4549c57dd8a221be4 node.pdb +b604a56a236f632cdf55c366a882d3ecb2312fba x64/node-v0.8.8-x64.msi +e80c1f4791e80243c5ddc7ea1e92ebd58fc4e10f x64/node.exe +8baf5b459e7f2074e0237d40c8c80e89b47660a3 x64/node.exp +4448fc2bfef66b7334016c0ab2e118c1cbc8544c x64/node.lib +0ddddf2c2fcd746827863b2454ddb4a8f6c3844e x64/node.pdb +``` diff --git a/node-v0.8.14/doc/blog/release/v0.8.9.md b/node-v0.8.14/doc/blog/release/v0.8.9.md new file mode 100644 index 0000000..7e21796 --- /dev/null +++ b/node-v0.8.14/doc/blog/release/v0.8.9.md @@ -0,0 +1,97 @@ +date: Tue Sep 11 2012 11:50:17 GMT-0700 (PDT) +category: release +version: 0.8.9 +title: Version 0.8.9 (Stable) +slug: node-v0-8-9-stable + +2012.09.11, Version 0.8.9 (Stable) + +* v8: upgrade to 3.11.10.22 + +* GYP: upgrade to r1477 + +* npm: Upgrade to 1.1.61 + +* npm: Don't create world-writable files (isaacs) + +* windows: fix single-accept mode for shared server sockets (Bert Belder) + +* windows: fix uninitialized memory access in uv_update_time() (Bert Belder) + +* windows: don't throw when a signal handler is attached (Bert Belder) + +* unix: fix memory leak in udp (Ben Noordhuis) + +* unix: map errno ESPIPE (Ben Noordhuis) + +* unix, windows: fix memory corruption in fs-poll.c (Ben Noordhuis) + +* sunos: fix os.cpus() on x86_64 (Ben Noordhuis) + +* child process: fix processes with IPC channel don't emit 'close' (Bert Belder) + +* build: add a "--dest-os" option to force a gyp "flavor" (Nathan Rajlich) + +* build: set `process.platform` to "sunos" on SunOS (Nathan Rajlich) + +* build: fix `make -j` fails after `make clean` (Bearice Ren) + +* build: fix openssl configuration for "arm" builds (Nathan Rajlich) + +* tls: support unix domain socket/named pipe in tls.connect (Shigeki Ohtsu) + +* https: make https.get() accept a URL (koichik) + +* http: respect HTTP/1.0 TE header (Ben Noordhuis) + +* crypto, tls: Domainify setSNICallback, pbkdf2, randomBytes (Ben Noordhuis) + +* stream.pipe: Don't call destroy() unless it's a function (isaacs) + + +Source Code: http://nodejs.org/dist/v0.8.9/node-v0.8.9.tar.gz + +Macintosh Installer (Universal): http://nodejs.org/dist/v0.8.9/node-v0.8.9.pkg + +Windows Installer: http://nodejs.org/dist/v0.8.9/node-v0.8.9-x86.msi + +Windows x64 Installer: http://nodejs.org/dist/v0.8.9/x64/node-v0.8.9-x64.msi + +Windows x64 Files: http://nodejs.org/dist/v0.8.9/x64/ + +Linux 32-bit Binary: http://nodejs.org/dist/v0.8.9/node-v0.8.9-linux-x86.tar.gz + +Linux 64-bit Binary: http://nodejs.org/dist/v0.8.9/node-v0.8.9-linux-x64.tar.gz + +Solaris 32-bit Binary: http://nodejs.org/dist/v0.8.9/node-v0.8.9-sunos-x86.tar.gz + +Solaris 64-bit Binary: http://nodejs.org/dist/v0.8.9/node-v0.8.9-sunos-x64.tar.gz + +Other release files: http://nodejs.org/dist/v0.8.9/ + +Website: http://nodejs.org/docs/v0.8.9/ + +Documentation: http://nodejs.org/docs/v0.8.9/api/ + +Shasums: + +``` +68aa7341807fb114f334151b7a1c8859e96b83d4 node-v0.8.9-darwin-x64.tar.gz +9e4a9422c1fd71750e9c46235d58aedaac3ba002 node-v0.8.9-darwin-x86.tar.gz +6236f781632555abf69d77f4bdfeb1e4e83779f3 node-v0.8.9-linux-x64.tar.gz +7f46084541d4909f44cfef2bb95f1e4f7435629e node-v0.8.9-linux-x86.tar.gz +33b0fe68f63519f3c8e6dc4d2aa51c96f62d2a56 node-v0.8.9-sunos-x64.tar.gz +e05863cb3a7d4add340ad434228f57da04a03b3d node-v0.8.9-sunos-x86.tar.gz +104f325d5289c51c6eb6a0634691dcdb39abb1db node-v0.8.9-x86.msi +1dd2cf48fb9b1f3e11e6e6750084ad4b2a2b0a85 node-v0.8.9.pkg +2d3234adceedc2dc87284af88609ede6ecd71734 node-v0.8.9.tar.gz +2997e2075cd04cf693453ce5664fa37615faa9a7 node.exe +d2834bd8ed3569b7880211dfe31a4f21cd475ab8 node.exp +41eac45ae350324de321a85787897bd8aa6b371c node.lib +ab6666144b23b2594521d27a95fb36b0904d48a2 node.pdb +f29db0a61a7bb32a7198ab059eca25b1283b9d6d x64/node-v0.8.9-x64.msi +2a7e69cef1bf7bc88109e007406e6feeaaa007b2 x64/node.exe +0423cd6602684c24e65358b9caa51740af67677b x64/node.exp +92155062a70100bfb5cf1389dd93e8851e7f3d0b x64/node.lib +cbbee351b84d7da0a91f56d6bbf6805e7b85cc8f x64/node.pdb +``` diff --git a/node-v0.8.14/doc/blog/release/v0.9.1.md b/node-v0.8.14/doc/blog/release/v0.9.1.md new file mode 100644 index 0000000..dcc0bb0 --- /dev/null +++ b/node-v0.8.14/doc/blog/release/v0.9.1.md @@ -0,0 +1,116 @@ +version: 0.9.1 +title: Version 0.9.1 (Unstable) +category: release +slug: node-v0-9-1-unstable +date: 2012-08-28T22:33:45.659Z + +2012.08.28, Version 0.9.1 (Unstable) + +* buffer: Add Buffer.isEncoding(enc) to test for valid encoding values (isaacs) + +* Raise UV_ECANCELED on premature close. (Ben Noordhuis) + +* Remove c-ares from libuv, move to a top-level node dependency (Bert Belder) + +* ref/unref for all HandleWraps, timers, servers, and sockets (Timothy J Fontaine) + +* addon: remove node-waf, superseded by node-gyp (Ben Noordhuis) + +* child_process: emit error on exec failure (Ben Noordhuis) + +* cluster: do not use internal server API (Andreas Madsen) + +* constants: add O_DIRECT (Ian Babrou) + +* crypto: add sync interface to crypto.pbkdf2() (Ben Noordhuis) + +* darwin: emulate fdatasync() (Fedor Indutny) + +* dgram: make .bind() always asynchronous (Ben Noordhuis) + +* events: Make emitter.listeners() side-effect free (isaacs, Joe Andaverde) + +* fs: Throw early on invalid encoding args (isaacs) + +* fs: fix naming of truncate/ftruncate functions (isaacs) + +* http: bubble up parser errors to ClientRequest (Brian White) + +* linux: improve cpuinfo parser on ARM and MIPS (Ben Noordhuis) + +* net: add support for IPv6 addresses ending in :: (Josh Erickson) + +* net: support Server.listen(Pipe) (Andreas Madsen) + +* node: don't scan add-on for "init" symbol (Ben Noordhuis) + +* remove process.uvCounters() (Ben Noordhuis) + +* repl: console writes to repl rather than process stdio (Nathan Rajlich) + +* timers: implement setImmediate (Timothy J Fontaine) + +* tls: fix segfault in pummel/test-tls-ci-reneg-attack (Ben Noordhuis) + +* tools: Move gyp addon tools to node-gyp (Nathan Rajlich) + +* unix: preliminary signal handler support (Ben Noordhuis) + +* unix: remove dependency on ev_child (Ben Noordhuis) + +* unix: work around darwin bug, don't poll() on pipe (Fedor Indutny) + +* util: Formally deprecate util.pump() (Ben Noordhuis) + +* windows: make active and closing handle state independent (Bert Belder) + +* windows: report spawn errors to the exit callback (Bert Belder) + +* windows: signal handling support with uv_signal_t (Bert Belder) + + +Source Code: http://nodejs.org/dist/v0.9.1/node-v0.9.1.tar.gz + +Macintosh Installer (Universal): http://nodejs.org/dist/v0.9.1/node-v0.9.1.pkg + +Windows Installer: http://nodejs.org/dist/v0.9.1/node-v0.9.1-x86.msi + +Windows x64 Installer: http://nodejs.org/dist/v0.9.1/x64/node-v0.9.1-x64.msi + +Windows x64 Files: http://nodejs.org/dist/v0.9.1/x64/ + +Linux 32-bit Binary: http://nodejs.org/dist/v0.9.1/node-v0.9.1-linux-x86.tar.gz + +Linux 64-bit Binary: http://nodejs.org/dist/v0.9.1/node-v0.9.1-linux-x64.tar.gz + +Solaris 32-bit Binary: http://nodejs.org/dist/v0.9.1/node-v0.9.1-sunos-x86.tar.gz + +Solaris 64-bit Binary: http://nodejs.org/dist/v0.9.1/node-v0.9.1-sunos-x64.tar.gz + +Other release files: http://nodejs.org/dist/v0.9.1/ + +Website: http://nodejs.org/docs/v0.9.1/ + +Documentation: http://nodejs.org/docs/v0.9.1/api/ + +Shasums: + +``` +b86a5b0b2c9a89d08baaeb3d5270a8f247b4ba43 node-v0.9.1-darwin-x64.tar.gz +800af9d15a4b65e624351bb94dedc3b7eb322b86 node-v0.9.1-darwin-x86.tar.gz +a7ea43b0db472ca84dc9838960dae57ff0abaa72 node-v0.9.1-linux-x64.tar.gz +89c4be492a946eefa45aa87d16787875aa0f2dff node-v0.9.1-linux-x86.tar.gz +6495d2814541e945dba5941b8d3facf2a61dc55d node-v0.9.1-sunos-x64.tar.gz +05ea83ba4d648f5b949833bb28d69e6eeebabb78 node-v0.9.1-sunos-x86.tar.gz +3ccf1ac2fea7f2d05bcaed590bc54ee61c982fbb node-v0.9.1-x86.msi +bd0ede40e4681b16088284fe6a18ae3a5c5a3795 node-v0.9.1.tar.gz +159470a999ef23fa940ad3c54265053c3d2a4332 node.exe +02472e388a44b91e2644178a0fe011354fcd361e node.exp +c6d6ce22be4b47ad022d82dd91ebd4c040742fee node.lib +7b4cec8b4106d90a077388fe483fdbb13119dcb1 node.pdb +a5fbf5e22c7623a9206abc6608d084ff53c7c4c9 x64/node-v0.9.1-x64.msi +9755685a9d7bea6dc63d3260829c26c5b0430a7a x64/node.exe +621f177733647848f7f667926fe4f498a1f50c97 x64/node.exp +5877dffbf012c458dab88f3392af59cb33720d2f x64/node.lib +dc513ce5c16771dcfab9c1777d5949252290b412 x64/node.pdb +``` diff --git a/node-v0.8.14/doc/blog/release/v0.9.2.md b/node-v0.8.14/doc/blog/release/v0.9.2.md new file mode 100644 index 0000000..f12d0cf --- /dev/null +++ b/node-v0.8.14/doc/blog/release/v0.9.2.md @@ -0,0 +1,95 @@ +title: Version 0.9.2 (Unstable) +category: release +version: 0.9.2 +date: Mon Sep 17 18:25:53 PDT 2012 +slug: node-v0-9-2-unstable + +2012.09.17, Version 0.9.2 (Unstable) + +* http_parser: upgrade to ad3b631 + +* openssl: upgrade 1.0.1c + +* darwin: use FSEvents to watch directory changes (Fedor Indutny) + +* unix: support missing API on NetBSD (Shigeki Ohtsu) + +* unix: fix EMFILE busy loop (Ben Noordhuis) + +* windows: un-break writable tty handles (Bert Belder) + +* windows: map WSAESHUTDOWN to UV_EPIPE (Bert Belder) + +* windows: make spawn with custom environment work again (Bert Belder) + +* windows: map ERROR_DIRECTORY to UV_ENOENT (Bert Belder) + +* tls, https: validate server certificate by default (Ben Noordhuis) + +* tls, https: throw exception on missing key/cert (Ben Noordhuis) + +* tls: async session storage (Fedor Indutny) + +* installer: don't install header files (Ben Noordhuis) + +* buffer: implement Buffer.prototype.toJSON() (Nathan Rajlich) + +* buffer: added support for writing NaN and Infinity (koichik) + +* http: make http.ServerResponse emit 'end' (Ben Noordhuis) + +* build: ./configure --ninja (Ben Noordhuis, Timothy J Fontaine) + +* installer: fix --without-npm (Ben Noordhuis) + +* cli: make -p equivalent to -pe (Ben Noordhuis) + +* url: Go much faster by using Url class (isaacs) + + +Source Code: http://nodejs.org/dist/v0.9.2/node-v0.9.2.tar.gz + +Macintosh Installer (Universal): http://nodejs.org/dist/v0.9.2/node-v0.9.2.pkg + +Windows Installer: http://nodejs.org/dist/v0.9.2/node-v0.9.2-x86.msi + +Windows x64 Installer: http://nodejs.org/dist/v0.9.2/x64/node-v0.9.2-x64.msi + +Windows x64 Files: http://nodejs.org/dist/v0.9.2/x64/ + +Linux 32-bit Binary: http://nodejs.org/dist/v0.9.2/node-v0.9.2-linux-x86.tar.gz + +Linux 64-bit Binary: http://nodejs.org/dist/v0.9.2/node-v0.9.2-linux-x64.tar.gz + +Solaris 32-bit Binary: http://nodejs.org/dist/v0.9.2/node-v0.9.2-sunos-x86.tar.gz + +Solaris 64-bit Binary: http://nodejs.org/dist/v0.9.2/node-v0.9.2-sunos-x64.tar.gz + +Other release files: http://nodejs.org/dist/v0.9.2/ + +Website: http://nodejs.org/docs/v0.9.2/ + +Documentation: http://nodejs.org/docs/v0.9.2/api/ + +Shasums: + +``` +3d1bb82013cbefd199abedaf0fe91d18579939b5 node-v0.9.2-darwin-x64.tar.gz +0a8e43e13ae6ce13ee3c8bb281d9a26aacc3ba3c node-v0.9.2-darwin-x86.tar.gz +c5c2708d796d0e37c5a401af39bfa17c9c3b67c0 node-v0.9.2-linux-x64.tar.gz +0d0a09b34b74f2c9f310f044cd142d0b80885c22 node-v0.9.2-linux-x86.tar.gz +0bcc9a23e601cd8bef42a2e250d918ccb03b3f5b node-v0.9.2-sunos-x64.tar.gz +7827998ec5ca442f26f824f46b51f33d0c9bbbb7 node-v0.9.2-sunos-x86.tar.gz +ed1c7d8a966c786969e3b4f68081cc5b3c753a03 node-v0.9.2-x86.msi +e1a1270d3f2a398738a363c68e8f30fd47dd5eb6 node-v0.9.2.pkg +09dd5e2135ab67ee9544f2b6ce0c5ab0e95b02b8 node-v0.9.2.tar.gz +8bfd33550b0115f71aed15a0c114a13cd573e10b node.exe +3484b1c61442bd2ca7e00d06c61ad7fa6f61acad node.exp +37dcaa77234b63a3ce3cecdea27041b7565698cc node.lib +52abfb1b09f6facb0cda7c2e27b1bb48f8e75404 node.pdb +c4c3f87c5dd7a0d36d682fb449cc6a8a245a4789 x64/node-v0.9.2-x64.msi +d60fb389deada9eb753948bedb84b2f797424a93 x64/node.exe +04190c31210b2bc7ee80679167920567c166db75 x64/node.exp +dfb5a231905da844279bf86984813440e152becf x64/node.lib +d5c5e26395e5c714efd4855505dcf0a31c57e22e x64/node.pdb +``` diff --git a/node-v0.8.14/doc/blog/release/v0.9.3.md b/node-v0.8.14/doc/blog/release/v0.9.3.md new file mode 100644 index 0000000..47e3140 --- /dev/null +++ b/node-v0.8.14/doc/blog/release/v0.9.3.md @@ -0,0 +1,87 @@ +category: release +version: v0.9.3 +date: Wed Oct 24 10:04:08 PDT 2012 +slug: node-v0.9.3 +title: Node v0.9.3 (Unstable) + +2012.10.24, Version 0.9.3 (Unstable) + +* V8: Upgrade to 3.13.7.4 + +* crypto: Default to buffers instead of binary strings (isaacs, Fedor Indutny) + +* crypto: add getHashes() and getCiphers() (Ben Noordhuis) + +* unix: add custom thread pool, remove libeio (Ben Noordhuis) + +* util: make `inspect()` accept an "options" argument (Nathan Rajlich) + +* https: fix renegotation attack protection (Ben Noordhuis) + +* cluster: make 'listening' handler see actual port (Aaditya Bhatia) + +* windows: use USERPROFILE to get the user's home dir (Bert Belder) + +* path: add platform specific path delimiter (Paul Serby) + +* http: add response.headersSent property (Pavel Lang) + +* child_process: make .fork()'d child auto-exit (Ben Noordhuis) + +* events: add 'removeListener' event (Ben Noordhuis) + +* string_decoder: Add 'end' method, do base64 properly (isaacs) + +* buffer: include encoding value in exception when invalid (Ricky Ng-Adam) + +* http: make http.ServerResponse no longer emit 'end' (isaacs) + +* streams: fix pipe is destructed by 'end' from destination (koichik) + + +Source Code: http://nodejs.org/dist/v0.9.3/node-v0.9.3.tar.gz + +Macintosh Installer (Universal): http://nodejs.org/dist/v0.9.3/node-v0.9.3.pkg + +Windows Installer: http://nodejs.org/dist/v0.9.3/node-v0.9.3-x86.msi + +Windows x64 Installer: http://nodejs.org/dist/v0.9.3/x64/node-v0.9.3-x64.msi + +Windows x64 Files: http://nodejs.org/dist/v0.9.3/x64/ + +Linux 32-bit Binary: http://nodejs.org/dist/v0.9.3/node-v0.9.3-linux-x86.tar.gz + +Linux 64-bit Binary: http://nodejs.org/dist/v0.9.3/node-v0.9.3-linux-x64.tar.gz + +Solaris 32-bit Binary: http://nodejs.org/dist/v0.9.3/node-v0.9.3-sunos-x86.tar.gz + +Solaris 64-bit Binary: http://nodejs.org/dist/v0.9.3/node-v0.9.3-sunos-x64.tar.gz + +Other release files: http://nodejs.org/dist/v0.9.3/ + +Website: http://nodejs.org/docs/v0.9.3/ + +Documentation: http://nodejs.org/docs/v0.9.3/api/ + +Shasums: + +``` +188b3ffacdc4342dc3c34e7ea8374acc3e186df0 node-v0.9.3-darwin-x64.tar.gz +94ae90f06a5bf72bb6efa8053c0beefde21f8bd7 node-v0.9.3-darwin-x86.tar.gz +ccb065fe242f15ffe35ecd7b22db33d11d6a5951 node-v0.9.3-linux-x64.tar.gz +0febfb1c37a3560b0140f7f952042aa4b4712974 node-v0.9.3-linux-x86.tar.gz +4362fdfefa0ed2985045883cea51ab802555c24c node-v0.9.3-sunos-x64.tar.gz +f43b6ce2a5da3bb384f6c115826cd2fea5f4bc2c node-v0.9.3-sunos-x86.tar.gz +ff6a7f8ff1a6d1af299a2702e09eec2cdfef474a node-v0.9.3-x86.msi +d47f953ee97047e1202350db2b11fb880ce2809b node-v0.9.3.pkg +34b7406e1da49bf0f0967e5a084157fdf8735078 node-v0.9.3.tar.gz +d0829f57b8460807cf58b2154b16176ef68189b1 node.exe +76007380d1f5cefd772b5890cd64f409ba85893e node.exp +fbe95014f9f4e2c5a38bc67b75511683f4a17fa9 node.lib +8c405af98ce922bf9bd82d29723aa343f3ca5488 node.pdb +04c1dce1188f4c52adfda0bc8219c478ed6553a8 x64/node-v0.9.3-x64.msi +fe6af3bd1405ecdef826a31a7c1333819aab4f3b x64/node.exe +abc9afb5ac40276346072f85601bd1a9e5135856 x64/node.exp +41622dce275f0f0f740485cca8d86ba3e63c884e x64/node.lib +8c34040ba4aa916d13c8313514cf93f99f5e3e34 x64/node.pdb +``` diff --git a/node-v0.8.14/doc/blog/release/version-0-6-11-stable.md b/node-v0.8.14/doc/blog/release/version-0-6-11-stable.md new file mode 100644 index 0000000..4c19a14 --- /dev/null +++ b/node-v0.8.14/doc/blog/release/version-0-6-11-stable.md @@ -0,0 +1,64 @@ +version: 0.6.11 +title: Version 0.6.11 (stable) +author: Isaac Schlueter +date: Fri Feb 17 2012 13:32:55 GMT-0800 (PST) +status: publish +category: release +slug: version-0-6-11-stable + +

2012.02.17 Version 0.6.11 (stable) + +

+
    +
  • http: allow multiple WebSocket RFC6455 headers (Einar Otto Stangvik)

    +
  • +
  • http: allow multiple WWW-Authenticate headers (Ben Noordhuis)

    +
  • +
  • windows: support unicode argv and environment variables (Bert Belder)

    +
  • +
  • tls: mitigate session renegotiation attacks (Ben Noordhuis)

    +
  • +
  • tcp, pipe: don't assert on uv_accept() errors (Ben Noordhuis)

    +
  • +
  • tls: Allow establishing secure connection on the existing socket (koichik)

    +
  • +
  • dgram: handle close of dgram socket before DNS lookup completes (Seth Fitzsimmons)

    +
  • +
  • windows: Support half-duplex pipes (Igor Zinkovsky)

    +
  • +
  • build: disable omit-frame-pointer on solaris systems (Dave Pacheco)

    +
  • +
  • debugger: fix --debug-brk (Ben Noordhuis)

    +
  • +
  • net: fix large file downloads failing (koichik)

    +
  • +
  • fs: fix ReadStream failure to read from existing fd (Christopher Jeffrey)

    +
  • +
  • net: destroy socket on DNS error (Stefan Rusu)

    +
  • +
  • dtrace: add missing translator (Dave Pacheco)

    +
  • +
  • unix: don't flush tty on switch to raw mode (Ben Noordhuis)

    +
  • +
  • windows: reset brightness when reverting to default text color (Bert Belder)

    +
  • +
  • npm: update to 1.1.1

    + +

    - Update which, fstream, mkdirp, request, and rimraf
    - Fix #2123 Set path properly for lifecycle scripts on windows
    - Mark the root as seen, so we don't recurse into it. Fixes #1838. (Martin Cooper)

    + +
  • +
+

Source Code: http://nodejs.org/dist/v0.6.11/node-v0.6.11.tar.gz + +

+

Windows Installer: http://nodejs.org/dist/v0.6.11/node-v0.6.11.msi + +

+

Macintosh Installer: http://nodejs.org/dist/v0.6.11/node-v0.6.11.pkg + +

+

Website: http://nodejs.org/docs/v0.6.11/ + +

+

Documentation: http://nodejs.org/docs/v0.6.11/api/ +

diff --git a/node-v0.8.14/doc/blog/release/version-0-6-12-stable.md b/node-v0.8.14/doc/blog/release/version-0-6-12-stable.md new file mode 100644 index 0000000..73e85ee --- /dev/null +++ b/node-v0.8.14/doc/blog/release/version-0-6-12-stable.md @@ -0,0 +1,66 @@ +version: 0.6.12 +title: Version 0.6.12 (stable) +author: Isaac Schlueter +date: Fri Mar 02 2012 13:22:49 GMT-0800 (PST) +status: publish +category: release +slug: version-0-6-12-stable + +

2012.03.02 Version 0.6.12 (stable) + +

+
    +
  • Upgrade V8 to 3.6.6.24

    +
  • +
  • dtrace ustack helper improvements (Dave Pacheco)

    +
  • +
  • API Documentation refactor (isaacs)

    +
  • +
  • #2827 net: fix race write() before and after connect() (koichik)

    +
  • +
  • #2554 #2567 throw if fs args for 'start' or 'end' are strings (AJ ONeal)

    +
  • +
  • punycode: Update to v1.0.0 (Mathias Bynens)

    +
  • +
  • Make a fat binary for the OS X pkg (isaacs)

    +
  • +
  • Fix hang on accessing process.stdin (isaacs)

    +
  • +
  • repl: make tab completion work on non-objects (Nathan Rajlich)

    +
  • +
  • Fix fs.watch on OS X (Ben Noordhuis)

    +
  • +
  • Fix #2515 nested setTimeouts cause premature process exit (Ben Noordhuis)

    +
  • +
  • windows: fix time conversion in stat (Igor Zinkovsky)

    +
  • +
  • windows: fs: handle EOF in read (Brandon Philips)

    +
  • +
  • windows: avoid IOCP short-circuit on non-ifs lsps (Igor Zinkovsky)

    +
  • +
  • Upgrade npm to 1.1.4 (isaacs)

    +

    +- windows fixes
    +- Bundle nested bundleDependencies properly
    +- install: support --save with url install targets
    +- shrinkwrap: behave properly with url-installed modules
    +- support installing uncompressed tars or single file modules from urls etc.
    +- don't run make clean on rebuild
    +- support HTTPS-over-HTTP proxy tunneling
    +

    +
  • +
+

Source Code: http://nodejs.org/dist/v0.6.12/node-v0.6.12.tar.gz + +

+

Windows Installer: http://nodejs.org/dist/v0.6.12/node-v0.6.12.msi + +

+

Macintosh Installer: http://nodejs.org/dist/v0.6.12/node-v0.6.12.pkg + +

+

Website: http://nodejs.org/docs/v0.6.12/ + +

+

Documentation: http://nodejs.org/docs/v0.6.12/api/ +

diff --git a/node-v0.8.14/doc/blog/release/version-0-6-13-stable.md b/node-v0.8.14/doc/blog/release/version-0-6-13-stable.md new file mode 100644 index 0000000..356c0ae --- /dev/null +++ b/node-v0.8.14/doc/blog/release/version-0-6-13-stable.md @@ -0,0 +1,50 @@ +version: 0.6.13 +title: Version 0.6.13 (stable) +author: Isaac Schlueter +date: Thu Mar 15 2012 10:37:02 GMT-0700 (PDT) +status: publish +category: release +slug: version-0-6-13-stable + +

2012.03.15 Version 0.6.13 (stable) + +

+
    +
  • Windows: Many libuv test fixes (Bert Belder)

    +
  • +
  • Windows: avoid uv_guess_handle crash in when fd < 0 (Bert Belder)

    +
  • +
  • Map EBUSY and ENOTEMPTY errors (Bert Belder)

    +
  • +
  • Windows: include syscall in fs errors (Bert Belder)

    +
  • +
  • Fix fs.watch ENOSYS on Linux kernel version mismatch (Ben Noordhuis)

    +
  • +
  • Update npm to 1.1.9

    +

    +- upgrade node-gyp to 0.3.5 (Nathan Rajlich)
    +- Fix isaacs/npm#2249 Add cache-max and cache-min configs
    +- Properly redirect across https/http registry requests
    +- log config usage if undefined key in set function (Kris Windham)
    +- Add support for os/cpu fields in package.json (Adam Blackburn)
    +- Automatically node-gyp packages containing a binding.gyp
    +- Fix failures unpacking in UNC shares
    +- Never create un-listable directories
    +- Handle cases where an optionalDependency fails to build +

    +
  • +
+

Source Code: http://nodejs.org/dist/v0.6.13/node-v0.6.13.tar.gz + +

+

Windows Installer: http://nodejs.org/dist/v0.6.13/node-v0.6.13.msi + +

+

Macintosh Installer: http://nodejs.org/dist/v0.6.13/node-v0.6.13.pkg + +

+

Website: http://nodejs.org/docs/v0.6.13/ + +

+

Documentation: http://nodejs.org/docs/v0.6.13/api/ +

diff --git a/node-v0.8.14/doc/blog/release/version-0-6-14-stable.md b/node-v0.8.14/doc/blog/release/version-0-6-14-stable.md new file mode 100644 index 0000000..96877a2 --- /dev/null +++ b/node-v0.8.14/doc/blog/release/version-0-6-14-stable.md @@ -0,0 +1,55 @@ +version: 0.6.14 +title: Version 0.6.14 (stable) +author: Isaac Schlueter +date: Fri Mar 23 2012 11:22:22 GMT-0700 (PDT) +status: publish +category: release +slug: version-0-6-14-stable + +

2012.03.22 Version 0.6.14 (stable) + +

+
    +
  • net: don't crash when queued write fails (Igor Zinkovsky)

    +
  • +
  • sunos: fix EMFILE on process.memoryUsage() (Bryan Cantrill)

    +
  • +
  • crypto: fix compile-time error with openssl 0.9.7e (Ben Noordhuis)

    +
  • +
  • unix: ignore ECONNABORTED errors from accept() (Ben Noordhuis)

    +
  • +
  • Add UV_ENOSPC and mappings to it (Bert Belder)

    +
  • +
  • http-parser: Fix response body is not read (koichik)

    +
  • +
  • Upgrade npm to 1.1.12

    +

    +- upgrade node-gyp to 0.3.7
    +- work around AV-locked directories on Windows
    +- Fix isaacs/npm#2293 Don't try to 'uninstall' /
    +- Exclude symbolic links from packages.
    +- Fix isaacs/npm#2275 Spurious 'unresolvable cycle' error.
    +- Exclude/include dot files as if they were normal files +

    +
  • +
+

Source Code: http://nodejs.org/dist/v0.6.14/node-v0.6.14.tar.gz + +

+

Windows Installer: http://nodejs.org/dist/v0.6.14/node-v0.6.14.msi + +

+

Windows x64 Files: http://nodejs.org/dist/v0.6.14/x64/ + +

+

Macintosh Installer (Universal): http://nodejs.org/dist/v0.6.14/node-v0.6.14.pkg + +

+

Other release files: http://nodejs.org/dist/v0.6.14/ + +

+

Website: http://nodejs.org/docs/v0.6.14/ + +

+

Documentation: http://nodejs.org/docs/v0.6.14/api/ +

diff --git a/node-v0.8.14/doc/blog/release/version-0-6-15-stable.md b/node-v0.8.14/doc/blog/release/version-0-6-15-stable.md new file mode 100644 index 0000000..5fa6bcf --- /dev/null +++ b/node-v0.8.14/doc/blog/release/version-0-6-15-stable.md @@ -0,0 +1,53 @@ +version: 0.6.15 +title: Version 0.6.15 (stable) +author: Isaac Schlueter +date: Mon Apr 09 2012 10:39:18 GMT-0700 (PDT) +status: publish +category: release +slug: version-0-6-15-stable + +

2012.04.09 Version 0.6.15 (stable) + +

+
    +
  • Update npm to 1.1.16

    +
  • +
  • Show licenses in binary installers.

    +
  • +
  • unix: add uv_fs_read64, uv_fs_write64 and uv_fs_ftruncate64 (Ben Noordhuis)

    +
  • +
  • add 64bit offset fs functions (Igor Zinkovsky)

    +
  • +
  • windows: don't report ENOTSOCK when attempting to bind an udp handle twice (Bert Belder)

    +
  • +
  • windows: backport pipe-connect-to-file fixes from master (Bert Belder)

    +
  • +
  • windows: never call fs event callbacks after closing the watcher (Bert Belder)

    +
  • +
  • fs.readFile: don't make the callback before the fd is closed (Bert Belder)

    +
  • +
  • windows: use 64bit offsets for uv_fs apis (Igor Zinkovsky)

    +
  • +
  • Fix #2061: segmentation fault on OS X due to stat size mismatch (Ben Noordhuis)

    +
  • +
+

Source Code: http://nodejs.org/dist/v0.6.15/node-v0.6.15.tar.gz + +

+

Windows Installer: http://nodejs.org/dist/v0.6.15/node-v0.6.15.msi + +

+

Windows x64 Files: http://nodejs.org/dist/v0.6.15/x64/ + +

+

Macintosh Installer (Universal): http://nodejs.org/dist/v0.6.15/node-v0.6.15.pkg + +

+

Other release files: http://nodejs.org/dist/v0.6.15/ + +

+

Website: http://nodejs.org/docs/v0.6.15/ + +

+

Documentation: http://nodejs.org/docs/v0.6.15/api/ +

diff --git a/node-v0.8.14/doc/blog/release/version-0-6-16-stable.md b/node-v0.8.14/doc/blog/release/version-0-6-16-stable.md new file mode 100644 index 0000000..051a23a --- /dev/null +++ b/node-v0.8.14/doc/blog/release/version-0-6-16-stable.md @@ -0,0 +1,59 @@ +version: 0.6.16 +title: Version 0.6.16 (stable) +author: Isaac Schlueter +date: Mon Apr 30 2012 11:13:50 GMT-0700 (PDT) +status: publish +category: release +slug: version-0-6-16-stable + +

2012.04.30 Version 0.6.16 (stable) + +

+
    +
  • Upgrade V8 to 3.6.6.25

    +
  • +
  • Upgrade npm to 1.1.18

    +
  • +
  • Windows: add mappings for UV_ENOENT (Bert Belder)

    +
  • +
  • linux: add IN_MOVE_SELF to inotify event mask (Ben Noordhuis)

    +
  • +
  • unix: call pipe handle connection cb on accept() error (Ben Noordhuis)

    +
  • +
  • unix: handle EWOULDBLOCK (Ben Noordhuis)

    +
  • +
  • map EWOULDBLOCK to UV_EAGAIN (Ben Noordhuis)

    +
  • +
  • Map ENOMEM to UV_ENOMEM (isaacs)

    +
  • +
  • Child process: support the gid and uid options (Bert Belder)

    +
  • +
  • test: cluster: add worker death event test (Ben Noordhuis)

    +
  • +
  • typo in node_http_parser (isaacs)

    +
  • +
  • http_parser: Eat CRLF between requests, even on connection:close. (Ben Noordhuis)

    +
  • +
  • don't check return value of unsetenv (Ben Noordhuis)

    +
  • +
+

Source Code: http://nodejs.org/dist/v0.6.16/node-v0.6.16.tar.gz + +

+

Windows Installer: http://nodejs.org/dist/v0.6.16/node-v0.6.16.msi + +

+

Windows x64 Files: http://nodejs.org/dist/v0.6.16/x64/ + +

+

Macintosh Installer (Universal): http://nodejs.org/dist/v0.6.16/node-v0.6.16.pkg + +

+

Other release files: http://nodejs.org/dist/v0.6.16/ + +

+

Website: http://nodejs.org/docs/v0.6.16/ + +

+

Documentation: http://nodejs.org/docs/v0.6.16/api/ +

diff --git a/node-v0.8.14/doc/blog/release/version-0-6-17-stable.md b/node-v0.8.14/doc/blog/release/version-0-6-17-stable.md new file mode 100644 index 0000000..3212443 --- /dev/null +++ b/node-v0.8.14/doc/blog/release/version-0-6-17-stable.md @@ -0,0 +1,47 @@ +version: 0.6.17 +title: Version 0.6.17 (stable) +author: Isaac Schlueter +date: Fri May 04 2012 13:33:12 GMT-0700 (PDT) +status: publish +category: release +slug: version-0-6-17-stable + +

2012.05.04 Version 0.6.17 (stable) + +

+
    +
  • Upgrade npm to 1.1.21

    +
  • +
  • uv: Add support for EROFS errors (Ben Noordhuis, Maciej Małecki)

    +
  • +
  • uv: Add support for EIO and ENOSPC errors (Fedor Indutny)

    +
  • +
  • windows: Add support for EXDEV errors (Bert Belder)

    +
  • +
  • http: Fix client memory leaks (isaacs, Vincent Voyer)

    +
  • +
  • fs: fix file descriptor leak in sync functions (Ben Noordhuis)

    +
  • +
  • fs: fix ReadStream / WriteStream double close bug (Ben Noordhuis)

    +
  • +
+

Source Code: http://nodejs.org/dist/v0.6.17/node-v0.6.17.tar.gz + +

+

Windows Installer: http://nodejs.org/dist/v0.6.17/node-v0.6.17.msi + +

+

Windows x64 Files: http://nodejs.org/dist/v0.6.17/x64/ + +

+

Macintosh Installer (Universal): http://nodejs.org/dist/v0.6.17/node-v0.6.17.pkg + +

+

Other release files: http://nodejs.org/dist/v0.6.17/ + +

+

Website: http://nodejs.org/docs/v0.6.17/ + +

+

Documentation: http://nodejs.org/docs/v0.6.17/api/ +

diff --git a/node-v0.8.14/doc/blog/release/version-0-6-18-stable.md b/node-v0.8.14/doc/blog/release/version-0-6-18-stable.md new file mode 100644 index 0000000..13714d9 --- /dev/null +++ b/node-v0.8.14/doc/blog/release/version-0-6-18-stable.md @@ -0,0 +1,59 @@ +version: 0.6.18 +title: Version 0.6.18 (stable) +author: Isaac Schlueter +date: Tue May 15 2012 10:06:13 GMT-0700 (PDT) +status: publish +category: release +slug: version-0-6-18-stable + +

2012.05.15 Version 0.6.18 (stable) + +

+
    +
  • windows: skip GetFileAttributes call when opening a file (Bert Belder)

    +
  • +
  • crypto: add PKCS12/PFX support (Sambasiva Suda)

    +
  • +
  • #3240: child_process: delete NODE_CHANNEL_FD from env in spawn (Ben Noordhuis)

    +
  • +
  • windows: add test for path.normalize with UNC paths (Bert Belder)

    +
  • +
  • windows: make path.normalize convert all slashes to backslashes (Bert Belder)

    +
  • +
  • fs: Automatically close FSWatcher on error (Bert Belder)

    +
  • +
  • #3258: fs.ReadStream.pause() emits duplicate data event (koichik)

    +
  • +
  • pipe_wrap: don't assert() on pipe accept errors (Ben Noordhuis)

    +
  • +
  • Better exception output for module load and process.nextTick (Felix Geisendörfer)

    +
  • +
  • zlib: fix error reporting (Ben Noordhuis)

    +
  • +
  • http: Don't destroy on timeout (isaacs)

    +
  • +
  • #3231: http: Don't try to emit error on a null'ed req object (isaacs)

    +
  • +
  • #3236: http: Refactor ClientRequest.onSocket (isaacs)

    +
  • +
+

Source Code: http://nodejs.org/dist/v0.6.18/node-v0.6.18.tar.gz + +

+

Windows Installer: http://nodejs.org/dist/v0.6.18/node-v0.6.18.msi + +

+

Windows x64 Files: http://nodejs.org/dist/v0.6.18/x64/ + +

+

Macintosh Installer (Universal): http://nodejs.org/dist/v0.6.18/node-v0.6.18.pkg + +

+

Other release files: http://nodejs.org/dist/v0.6.18/ + +

+

Website: http://nodejs.org/docs/v0.6.18/ + +

+

Documentation: http://nodejs.org/docs/v0.6.18/api/ +

diff --git a/node-v0.8.14/doc/blog/release/version-0-7-10-unstable.md b/node-v0.8.14/doc/blog/release/version-0-7-10-unstable.md new file mode 100644 index 0000000..7fe8a42 --- /dev/null +++ b/node-v0.8.14/doc/blog/release/version-0-7-10-unstable.md @@ -0,0 +1,86 @@ +version: 0.7.10 +title: Version 0.7.10 (unstable) +author: Isaac Schlueter +date: Mon Jun 11 2012 09:00:25 GMT-0700 (PDT) +status: publish +category: release +slug: version-0-7-10-unstable + +

2012.06.11, Version 0.7.10 (unstable) + +

+

This is the second-to-last release on the 0.7 branch. Version 0.8.0 +will be released some time next week. As other even-numbered Node +releases before it, the v0.8.x releases will maintain API and binary +compatibility. + +

+

The major changes are detailed in +https://github.com/joyent/node/wiki/API-changes-between-v0.6-and-v0.8 + +

+

Please try out this release. There will be very few changes between +this and the v0.8.x release family. This is the last chance to comment +on the API before it is locked down for stability. + + +

+
    +
  • Roll V8 back to 3.9.24.31

    +
  • +
  • build: x64 target should always pass -m64 (Robert Mustacchi)

    +
  • +
  • add NODE_EXTERN to node::Start (Joel Brandt)

    +
  • +
  • repl: Warn about running npm commands (isaacs)

    +
  • +
  • slab_allocator: fix crash in dtor if V8 is dead (Ben Noordhuis)

    +
  • +
  • slab_allocator: fix leak of Persistent handles (Shigeki Ohtsu)

    +
  • +
  • windows/msi: add node.js prompt to startmenu (Jeroen Janssen)

    +
  • +
  • windows/msi: fix adding node to PATH (Jeroen Janssen)

    +
  • +
  • windows/msi: add start menu links when installing (Jeroen Janssen)

    +
  • +
  • windows: don't install x64 version into the 'program files (x86)' folder (Matt Gollob)

    +
  • +
  • domain: Fix #3379 domain.intercept no longer passes error arg to cb (Marc Harter)

    +
  • +
  • fs: make callbacks run in global context (Ben Noordhuis)

    +
  • +
  • fs: enable fs.realpath on windows (isaacs)

    +
  • +
  • child_process: expose UV_PROCESS_DETACHED as options.detached (Charlie McConnell)

    +
  • +
  • child_process: new stdio API for .spawn() method (Fedor Indutny)

    +
  • +
  • child_process: spawn().ref() and spawn().unref() (Fedor Indutny)

    +
  • +
  • Upgrade npm to 1.1.25

    +
  • +
    • Enable npm link on windows
    • +
    • Properly remove sh-shim on Windows
    • +
    • Abstract out registry client and logger
    +
+

Source Code: http://nodejs.org/dist/v0.7.10/node-v0.7.10.tar.gz + +

+

Windows Installer: http://nodejs.org/dist/v0.7.10/node-v0.7.10.msi + +

+

Windows x64 Files: http://nodejs.org/dist/v0.7.10/x64/ + +

+

Macintosh Installer (Universal): http://nodejs.org/dist/v0.7.10/node-v0.7.10.pkg + +

+

Other release files: http://nodejs.org/dist/v0.7.10/ + +

+

Website: http://nodejs.org/docs/v0.7.10/ + +

+

Documentation: http://nodejs.org/docs/v0.7.10/api/ +

diff --git a/node-v0.8.14/doc/blog/release/version-0-7-11-unstable.md b/node-v0.8.14/doc/blog/release/version-0-7-11-unstable.md new file mode 100644 index 0000000..8e53732 --- /dev/null +++ b/node-v0.8.14/doc/blog/release/version-0-7-11-unstable.md @@ -0,0 +1,80 @@ +version: 0.7.11 +title: Version 0.7.11 (unstable) +author: Isaac Schlueter +date: Fri Jun 15 2012 12:45:20 GMT-0700 (PDT) +status: publish +category: release +slug: version-0-7-11-unstable + +

This is the most stable 0.7 release yet. Please try it out. + +

+

Version 0.8 will be out very soon. You can follow the remaining issues +on the github issue tracker. + +

+

https://github.com/joyent/node/issues?milestone=10&state=open + +

+

2012.06.15, Version 0.7.11 (unstable) + +

+
    +
  • V8: Upgrade to v3.11.10

    +
  • +
  • npm: Upgrade to 1.1.26

    +
  • +
  • doc: Improve cross-linking in API docs markdown (Ben Kelly)

    +
  • +
  • Fix #3425: removeAllListeners should delete array (Reid Burke)

    +
  • +
  • cluster: don't silently drop messages when the write queue gets big (Bert Belder)

    +
  • +
  • Add Buffer.concat method (isaacs)

    +
  • +
  • windows: make symlinks tolerant to forward slashes (Bert Belder)

    +
  • +
  • build: Add node.d and node.1 to installer (isaacs)

    +
  • +
  • cluster: rename worker.unqiueID to worker.id (Andreas Madsen)

    +
  • +
  • Windows: Enable ETW events on Windows for existing DTrace probes. (Igor Zinkovsky)

    +
  • +
  • test: bundle node-weak in test/gc so that it doesn't need to be downloaded (Nathan Rajlich)

    +
  • +
  • Make many tests pass on Windows (Bert Belder)

    +
  • +
  • Fix #3388 Support listening on file descriptors (isaacs)

    +
  • +
  • Fix #3407 Add os.tmpDir() (isaacs)

    +
  • +
  • Unbreak the snapshotted build on Windows (Bert Belder)

    +
  • +
  • Clean up child_process.kill throws (Bert Belder)

    +
  • +
  • crypto: make cipher/decipher accept buffer args (Ben Noordhuis)

    +
  • +
+

Source Code: http://nodejs.org/dist/v0.7.11/node-v0.7.11.tar.gz + +

+

Macintosh Installer (Universal): http://nodejs.org/dist/v0.7.11/node-v0.7.11.pkg + +

+

Windows Installer: http://nodejs.org/dist/v0.7.11/node-v0.7.11-x86.msi + +

+

Windows x64 Installer: http://nodejs.org/dist/v0.7.11/node-v0.7.11-x64.msi + +

+

Windows x64 Files: http://nodejs.org/dist/v0.7.11/x64/ + +

+

Other release files: http://nodejs.org/dist/v0.7.11/ + +

+

Website: http://nodejs.org/docs/v0.7.11/ + +

+

Documentation: http://nodejs.org/docs/v0.7.11/api/ +

diff --git a/node-v0.8.14/doc/blog/release/version-0-7-12.md b/node-v0.8.14/doc/blog/release/version-0-7-12.md new file mode 100644 index 0000000..15514fa --- /dev/null +++ b/node-v0.8.14/doc/blog/release/version-0-7-12.md @@ -0,0 +1,56 @@ +version: 0.7.12 +title: Version 0.7.12 +author: Isaac Schlueter +date: Tue Jun 19 2012 16:31:09 GMT-0700 (PDT) +status: publish +category: release +slug: version-0-7-12 + +

2012.06.19, Version 0.7.12 (unstable)

+

This is the last release on the 0.7 branch. Version 0.8.0 will be released some time later this week, barring any major problems.

+

As with other even-numbered Node releases before it, the v0.8.x releases will maintain API and binary compatibility.

+

The major changes between v0.6 and v0.8 are detailed in https://github.com/joyent/node/wiki/API-changes-between-v0.6-and-v0.8

+

Please try out this release. There will be very virtually no changes between this and the v0.8.x release family. This is the last chance to comment before it is locked down for stability. The API is effectively frozen now.

+

This version adds backwards-compatible shims for binary addons that use libeio and libev directly. If you find that binary modules that could compile on v0.6 can not compile on this version, please let us know. Note that libev is officially deprecated in v0.8, and will be removed in v0.9. You should be porting your modules to use libuv as soon as possible.

+

V8 is on 3.11.10 currently, and will remain on the V8 3.11.x branch for the duration of Node v0.8.x.

+
  • npm: Upgrade to 1.1.30
    - Improved 'npm init'
    - Fix the 'cb never called' error from 'oudated' and 'update'
    - Add --save-bundle|-B config
    - Fix isaacs/npm#2465: Make npm script and windows shims cygwin-aware
    - Fix isaacs/npm#2452 Use --save(-dev|-optional) in npm rm
    - logstream option to replace removed logfd (Rod Vagg)
    - Read default descriptions from README.md files

    +
  • Shims to support deprecated ev_* and eio_* methods (Ben Noordhuis)

    +
  • #3118 net.Socket: Delay pause/resume until after connect (isaacs)

    +
  • #3465 Add ./configure --no-ifaddrs flag (isaacs)

    +
  • child_process: add .stdin stream to forks (Fedor Indutny)

    +
  • build: fix make install DESTDIR=/path (Ben Noordhuis)

    +
  • tls: fix off-by-one error in renegotiation check (Ben Noordhuis)

    +
  • crypto: Fix diffie-hellman key generation UTF-8 errors (Fedor Indutny)

    +
  • node: change the constructor name of process from EventEmitter to process (Andreas Madsen)

    +
  • net: Prevent property access throws during close (Reid Burke)

    +
  • querystring: improved speed and code cleanup (Felix Böhm)

    +
  • sunos: fix assertion errors breaking fs.watch() (Fedor Indutny)

    +
  • unix: stat: detect sub-second changes (Ben Noordhuis)

    +
  • add stat() based file watcher (Ben Noordhuis)

    +

Source Code: http://nodejs.org/dist/v0.7.12/node-v0.7.12.tar.gz

+

Macintosh Installer (Universal): http://nodejs.org/dist/v0.7.12/node-v0.7.12.pkg

+

Windows Installer: http://nodejs.org/dist/v0.7.12/node-v0.7.12-x86.msi

+

Windows x64 Installer: http://nodejs.org/dist/v0.7.12/x64/node-v0.7.12-x64.msi

+

Windows x64 Files: http://nodejs.org/dist/v0.7.12/x64/

+

Other release files: http://nodejs.org/dist/v0.7.12/

+

Website: http://nodejs.org/docs/v0.7.12/

+

Documentation: http://nodejs.org/docs/v0.7.12/api/

+ +

Shasums

+ +
ded6a2197b1149b594eb45fea921e8538ba442aa  blog.html
+dfabff0923d4b4f1d53bd9831514c1ac8c4b1876  email.md
+be313d35511e6d7e43cae5fa2b18f3e0d2275ba1  node-v0.7.12-x86.msi
+8f7ba0c8283e3863de32fd5c034f5b599c78f830  node-v0.7.12.pkg
+cb570abacbf4eb7e23c3d2620d00dd3080d9c19d  node-v0.7.12.tar.gz
+e13a6edfcba1c67ffe794982dd20a222ce8ce40f  node.exe
+20906ad76a43eca52795b2a089654a105e11c1e6  node.exp
+acbcbb87b6f7f2af34a3ed0abe6131d9e7a237af  node.lib
+4013d5b25fe36ae4245433b972818686cd9a2205  node.pdb
+6c0a7a2e8ee360e2800156293fb2f6a5c1a57382  npm-1.1.30.tgz
+9d23e42e8260fa20001d5618d2583a62792bf63f  npm-1.1.30.zip
+840157b2d6f7389ba70b07fc9ddc048b92c501cc  x64/node-v0.7.12-x64.msi
+862d42706c21ea83bf73cd827101f0fe598b0cf7  x64/node.exe
+de0af95fac083762f99c875f91bab830dc030f71  x64/node.exp
+3122bd886dfb96f3b41846cef0bdd7e97326044a  x64/node.lib
+e0fa4e42cd19cadf8179e492ca606b7232bbc018  x64/node.pdb
diff --git a/node-v0.8.14/doc/blog/release/version-0-7-4-unstable.md b/node-v0.8.14/doc/blog/release/version-0-7-4-unstable.md new file mode 100644 index 0000000..38d6615 --- /dev/null +++ b/node-v0.8.14/doc/blog/release/version-0-7-4-unstable.md @@ -0,0 +1,50 @@ +version: 0.7.4 +title: Node v0.7.4 (unstable) +author: Isaac Schlueter +date: Wed Feb 15 2012 11:38:35 GMT-0800 (PST) +status: publish +category: release +slug: version-0-7-4-unstable + +

2012.02.14, Version 0.7.4 (unstable) + +

+
    +
  • Upgrade V8 to 3.9.5

    +
  • +
  • Upgrade npm to 1.1.1

    +
  • +
  • build: Detect host_arch better (Karl Skomski)

    +
  • +
  • debugger: export debug_port to process (Fedor Indutny)

    +
  • +
  • api docs: CSS bug fixes (isaacs)

    +
  • +
  • build: use -fPIC for native addons on UNIX (Nathan Rajlich)

    +
  • +
  • Re-add top-level v8::Locker (Marcel Laverdet)

    +
  • +
  • Move images out of the dist tarballs (isaacs)

    +
  • +
  • libuv: Remove uv_export and uv_import (Ben Noordhuis)

    +
  • +
  • build: Support x64 build on Windows (Igor Zinkovsky)

    +
  • +
+

Source Code: http://nodejs.org/dist/v0.7.4/node-v0.7.4.tar.gz + +

+

Windows Installer: http://nodejs.org/dist/v0.7.4/node-v0.7.4.msi + +

+

Macintosh Installer: http://nodejs.org/dist/v0.7.4/node-v0.7.4.pkg + +

+

Other release files: http://nodejs.org/dist/v0.7.4/ + +

+

Website: http://nodejs.org/docs/v0.7.4/ + +

+

Documentation: http://nodejs.org/docs/v0.7.4/api/ +

diff --git a/node-v0.8.14/doc/blog/release/version-0-7-5-unstable.md b/node-v0.8.14/doc/blog/release/version-0-7-5-unstable.md new file mode 100644 index 0000000..88bd707 --- /dev/null +++ b/node-v0.8.14/doc/blog/release/version-0-7-5-unstable.md @@ -0,0 +1,62 @@ +version: 0.7.5 +title: Version 0.7.5 (unstable) +author: Isaac Schlueter +date: Thu Feb 23 2012 14:45:21 GMT-0800 (PST) +status: publish +category: release +slug: version-0-7-5-unstable + +

2012.02.23, Version 0.7.5 (unstable) + +

+
    +
  • startup speed improvements (Maciej Małecki)

    +
  • +
  • crypto: add function getDiffieHellman() (Tomasz Buchert)

    +
  • +
  • buffer: support decoding of URL-safe base64 (Ben Noordhuis)

    +
  • +
  • Make QueryString.parse() even faster (Brian White)

    +
  • +
  • url: decode url entities in auth section (Ben Noordhuis)

    +
  • +
  • http: support PURGE request method (Ben Noordhuis)

    +
  • +
  • http: Generate Date headers on responses (Mark Nottingham)

    +
  • +
  • Fix #2762: Add callback to close function. (Mikeal Rogers)

    +
  • +
  • dgram: fix out-of-bound memory read (Ben Noordhuis)

    +
  • +
  • repl: add automatic loading of built-in libs (Brandon Benvie)

    +
  • +
  • repl: remove double calls where possible (Fedor Indutny)

    +
  • +
  • Readline improvements. Related: #2737 #2756 (Colton Baker)

    +
  • +
  • build: disable -fomit-frame-pointer on solaris (Dave Pacheco)

    +
  • +
  • build: arch detection improvements (Nathan Rajlich)

    +
  • +
  • build: Make a fat binary for the OS X make pkg. (Nathan Rajlich)

    +
  • +
  • jslint src/ and lib/ on 'make test' (isaacs)

    +
  • +
+

Source Code: http://nodejs.org/dist/v0.7.5/node-v0.7.5.tar.gz + +

+

Windows Installer: http://nodejs.org/dist/v0.7.5/node-v0.7.5.msi + +

+

Macintosh Installer: http://nodejs.org/dist/v0.7.5/node-v0.7.5.pkg + +

+

Other release files: http://nodejs.org/dist/v0.7.5/ + +

+

Website: http://nodejs.org/docs/v0.7.5/ + +

+

Documentation: http://nodejs.org/docs/v0.7.5/api/ +

diff --git a/node-v0.8.14/doc/blog/release/version-0-7-6-unstable.md b/node-v0.8.14/doc/blog/release/version-0-7-6-unstable.md new file mode 100644 index 0000000..1bac491 --- /dev/null +++ b/node-v0.8.14/doc/blog/release/version-0-7-6-unstable.md @@ -0,0 +1,72 @@ +version: 0.7.6 +title: Version 0.7.6 (unstable) +author: Isaac Schlueter +date: Tue Mar 13 2012 14:12:30 GMT-0700 (PDT) +status: publish +category: release +slug: version-0-7-6-unstable + +

2012.03.13, Version 0.7.6 (unstable) + +

+
    +
  • Upgrade v8 to 3.9.17

    +
  • +
  • Upgrade npm to 1.1.8

    +

    +- Add support for os/cpu fields in package.json (Adam Blackburn)
    +- Automatically node-gyp packages containing a binding.gyp
    +- Fix failures unpacking in UNC shares
    +- Never create un-listable directories
    +- Handle cases where an optionalDependency fails to build
    +

    +
  • +
  • events: newListener emit correct fn when using 'once' (Roly Fentanes)

    +
  • +
  • url: Ignore empty port component (Łukasz Walukiewicz)

    +
  • +
  • module: replace 'children' array (isaacs)

    +
  • +
  • tls: parse multiple values of a key in ssl certificate (Sambasiva Suda)

    +
  • +
  • cluster: support passing of named pipes (Ben Noordhuis)

    +
  • +
  • Windows: include syscall in fs errors (Bert Belder)

    +
  • +
  • http: #2888 Emit end event only once (Igor Zinkovsky)

    +
  • +
  • readline: add multiline support (Rlidwka)

    +
  • +
  • process: add process.hrtime() (Nathan Rajlich)

    +
  • +
  • net, http, https: add localAddress option (Dmitry Nizovtsev)

    +
  • +
  • addon improvements (Nathan Rajlich)

    +
  • +
  • build improvements (Ben Noordhuis, Sadique Ali, T.C. Hollingsworth, Nathan Rajlich)

    +
  • +
  • add support for "SEARCH" request methods (Nathan Rajlich)

    +
  • +
  • expose the zlib and http_parser version in process.versions (Nathan Rajlich)

    +
  • +
+

Source Code: http://nodejs.org/dist/v0.7.6/node-v0.7.6.tar.gz + +

+

Windows Installer: http://nodejs.org/dist/v0.7.6/node-v0.7.6.msi + +

+

Windows x64 Files: http://nodejs.org/dist/v0.7.6/x64/ + +

+

Macintosh Installer (Universal): http://nodejs.org/dist/v0.7.6/node-v0.7.6.pkg + +

+

Other release files: http://nodejs.org/dist/v0.7.6/ + +

+

Website: http://nodejs.org/docs/v0.7.6/ + +

+

Documentation: http://nodejs.org/docs/v0.7.6/api/ +

diff --git a/node-v0.8.14/doc/blog/release/version-0-7-7-unstable.md b/node-v0.8.14/doc/blog/release/version-0-7-7-unstable.md new file mode 100644 index 0000000..1336096 --- /dev/null +++ b/node-v0.8.14/doc/blog/release/version-0-7-7-unstable.md @@ -0,0 +1,71 @@ +version: 0.7.7 +title: Version 0.7.7 (unstable) +author: Isaac Schlueter +date: Fri Mar 30 2012 11:56:19 GMT-0700 (PDT) +status: publish +category: release +slug: version-0-7-7-unstable + +

2012.03.30, Version 0.7.7 (unstable) + +

+
    +
  • Upgrade V8 to 3.9.24.7

    +
  • +
  • Upgrade npm to 1.1.15

    +
  • +
  • Handle Emoji characters properly (Erik Corry, Bert Belder)

    +
  • +
  • readline: migrate ansi/vt100 logic from tty to readline (Nathan Rajlich)

    +
  • +
  • readline: Fix multiline handling (Alex Kocharin)

    +
  • +
  • add a -i/--interactive flag to force the REPL (Nathan Rajlich)

    +
  • +
  • debugger: add breakOnException command (Fedor Indutny)

    +
  • +
  • cluster: kill workers when master dies (Andreas Madsen)

    +
  • +
  • cluster: add graceful disconnect support (Andreas Madsen)

    +
  • +
  • child_process: Separate 'close' event from 'exit' (Charlie McConnell)

    +
  • +
  • typed arrays: add Uint8ClampedArray (Mikael Bourges-Sevenier)

    +
  • +
  • buffer: Fix byte alignment issues (Ben Noordhuis, Erik Lundin)

    +
  • +
  • tls: fix CryptoStream.setKeepAlive() (Shigeki Ohtsu)

    +
  • +
  • Expose http parse error codes (Felix Geisendörfer)

    +
  • +
  • events: don't delete the listeners array (Ben Noordhuis, Nathan Rajlich)

    +
  • +
  • process: add process.config to view node's ./configure settings (Nathan Rajlich)

    +
  • +
  • process: process.execArgv to see node's arguments (Micheil Smith)

    +
  • +
  • process: fix process.title setter (Ben Noordhuis)

    +
  • +
  • timers: handle negative or non-numeric timeout values (Ben Noordhuis)

    +
  • +
+

Source Code: http://nodejs.org/dist/v0.7.7/node-v0.7.7.tar.gz + +

+

Windows Installer: http://nodejs.org/dist/v0.7.7/node-v0.7.7.msi + +

+

Windows x64 Files: http://nodejs.org/dist/v0.7.7/x64/ + +

+

Macintosh Installer (Universal): http://nodejs.org/dist/v0.7.7/node-v0.7.7.pkg + +

+

Other release files: http://nodejs.org/dist/v0.7.7/ + +

+

Website: http://nodejs.org/docs/v0.7.7/ + +

+

Documentation: http://nodejs.org/docs/v0.7.7/api/ +

diff --git a/node-v0.8.14/doc/blog/release/version-0-7-8-unstable.md b/node-v0.8.14/doc/blog/release/version-0-7-8-unstable.md new file mode 100644 index 0000000..8dfac6f --- /dev/null +++ b/node-v0.8.14/doc/blog/release/version-0-7-8-unstable.md @@ -0,0 +1,71 @@ +version: 0.7.8 +title: Version 0.7.8 (unstable) +author: Isaac Schlueter +date: Wed Apr 18 2012 10:39:02 GMT-0700 (PDT) +status: publish +category: release +slug: version-0-7-8-unstable + +

2012.04.18, Version 0.7.8, (unstable) + +

+
    +
  • Upgrade V8 to 3.9.24.9

    +
  • +
  • Upgrade OpenSSL to 1.0.0f

    +
  • +
  • Upgrade npm to 1.1.18

    +
  • +
  • Show licenses in Binary installers

    +
  • +
  • Domains (isaacs)

    +
  • +
  • readline: rename "end" to "close" (Nathan Rajlich)

    +
  • +
  • tcp: make getsockname() return address family as string (Shigeki Ohtsu)

    +
  • +
  • http, https: fix .setTimeout() (ssuda)

    +
  • +
  • os: add cross platform EOL character (Mustansir Golawala)

    +
  • +
  • typed arrays: unexport SizeOfArrayElementForType() (Aaron Jacobs)

    +
  • +
  • net: honor 'enable' flag in .setNoDelay() (Ben Noordhuis)

    +
  • +
  • child_process: emit error when .kill fails (Andreas Madsen)

    +
  • +
  • gyp: fix 'argument list too long' build error (Ben Noordhuis)

    +
  • +
  • fs.WriteStream: Handle modifications to fs.open (isaacs)

    +
  • +
  • repl, readline: Handle newlines better (Nathan Rajlich, Nathan Friedly)

    +
  • +
  • build: target OSX 10.5 when building on darwin (Nathan Rajlich)

    +
  • +
  • Fix #3052 Handle errors properly in zlib (isaacs)

    +
  • +
  • build: add support for DTrace and postmortem (Dave Pacheco)

    +
  • +
  • core: add reusable Slab allocator (Ben Noordhuis)

    +
  • +
+

Source Code: http://nodejs.org/dist/v0.7.8/node-v0.7.8.tar.gz + +

+

Windows Installer: http://nodejs.org/dist/v0.7.8/node-v0.7.8.msi + +

+

Windows x64 Files: http://nodejs.org/dist/v0.7.8/x64/ + +

+

Macintosh Installer (Universal): http://nodejs.org/dist/v0.7.8/node-v0.7.8.pkg + +

+

Other release files: http://nodejs.org/dist/v0.7.8/ + +

+

Website: http://nodejs.org/docs/v0.7.8/ + +

+

Documentation: http://nodejs.org/docs/v0.7.8/api/ +

diff --git a/node-v0.8.14/doc/blog/video/bert-belder-libuv-lxjs-2012.md b/node-v0.8.14/doc/blog/video/bert-belder-libuv-lxjs-2012.md new file mode 100644 index 0000000..75aefe1 --- /dev/null +++ b/node-v0.8.14/doc/blog/video/bert-belder-libuv-lxjs-2012.md @@ -0,0 +1,13 @@ +title: Bert Belder - libuv at LXJS 2012 +slug: bert-belder-libuv-lxjs-2012 +category: video +date: Sun Sep 30 10:28:45 PDT 2012 + +Node core committer Bert Belder gave a talk at +[LXJS](http://2012.lxjs.org/). If you are interested in how Node does +asynchronous I/O across platforms, then you should definitely watch +this video. + + diff --git a/node-v0.8.14/doc/blog/video/bryan-cantrill-instrumenting-the-real-time-web.md b/node-v0.8.14/doc/blog/video/bryan-cantrill-instrumenting-the-real-time-web.md new file mode 100644 index 0000000..fa98213 --- /dev/null +++ b/node-v0.8.14/doc/blog/video/bryan-cantrill-instrumenting-the-real-time-web.md @@ -0,0 +1,42 @@ +title: Bryan Cantrill: Instrumenting the Real Time Web +author: Isaac Schlueter +date: Tue May 08 2012 10:00:34 GMT-0700 (PDT) +status: publish +category: video +slug: bryan-cantrill-instrumenting-the-real-time-web + +Bryan Cantrill, VP of Engineering at Joyent, describes the challenges of instrumenting a distributed, dynamic, highly virtualized system -- and what their experiences taught them about the problem, the technologies used to tackle it, and promising approaches. + +This talk was given at Velocity Conf in 2011. + +
+ + +
+ Instrumenting the real-time web + + + + + + + + +
+ View more presentations from bcantrill +
+
+
diff --git a/node-v0.8.14/doc/blog/video/welcome-to-the-node-blog.md b/node-v0.8.14/doc/blog/video/welcome-to-the-node-blog.md new file mode 100644 index 0000000..3ac3985 --- /dev/null +++ b/node-v0.8.14/doc/blog/video/welcome-to-the-node-blog.md @@ -0,0 +1,13 @@ +title: Welcome to the Node blog +author: ryandahl +date: Thu Mar 17 2011 20:17:12 GMT-0700 (PDT) +status: publish +category: video +slug: welcome-to-the-node-blog + +Since Livejournal is disintegrating into Russian spam, I'm moving my technical blog to http://blog.nodejs.org/. I hope to do frequent small posts about what's going on in Node development and include posts from other core Node developers. Please subscribe to the RSS feed. + +To avoid making this post completely devoid of content, here is a new video from a talk I gave at the SF PHP group tastefully produced by Marakana: + diff --git a/node-v0.8.14/doc/blog/vulnerability/http-server-security-vulnerability-please-upgrade-to-0-6-17.md b/node-v0.8.14/doc/blog/vulnerability/http-server-security-vulnerability-please-upgrade-to-0-6-17.md new file mode 100644 index 0000000..b64858d --- /dev/null +++ b/node-v0.8.14/doc/blog/vulnerability/http-server-security-vulnerability-please-upgrade-to-0-6-17.md @@ -0,0 +1,45 @@ +title: HTTP Server Security Vulnerability: Please upgrade to 0.6.17 +author: Isaac Schlueter +date: Mon May 07 2012 10:02:01 GMT-0700 (PDT) +status: publish +category: vulnerability +slug: http-server-security-vulnerability-please-upgrade-to-0-6-17 + +

tl;dr

+ +
  • A carefully crafted attack request can cause the contents of the HTTP parser's buffer to be appended to the attacking request's header, making it appear to come from the attacker. Since it is generally safe to echo back contents of a request, this can allow an attacker to get an otherwise correctly designed server to divulge information about other requests. It is theoretically possible that it could enable header-spoofing attacks, though such an attack has not been demonstrated.

  • +
  • Versions affected: All versions of the 0.5/0.6 branch prior to 0.6.17, and all versions of the 0.7 branch prior to 0.7.8. Versions in the 0.4 branch are not affected.
  • +
  • Fix: Upgrade to v0.6.17, or apply the fix in c9a231d to your system.
+ +

Details

+ +

A few weeks ago, Matthew Daley found a security vulnerability in Node's HTTP implementation, and thankfully did the responsible thing and reported it to us via email. He explained it quite well, so I'll quote him here:

+
+

There is a vulnerability in node's `http_parser` binding which allows information disclosure to a remote attacker: + +

+

In node::StringPtr::Update, an attempt is made at an optimization on certain inputs (`node_http_parser.cc`, line 151). The intent is that if the current string pointer plus the current string size is equal to the incoming string pointer, the current string size is just increased to match, as the incoming string lies just beyond the current string pointer. However, the check to see whether or not this can be done is incorrect; "size" is used whereas "size_" should be used. Therefore, an attacker can call Update with a string of certain length and cause the current string to have other data appended to it. In the case of HTTP being parsed out of incoming socket data, this can be incoming data from other sockets. + +

+

Normally node::StringPtr::Save, which is called after each execution of `http_parser`, would stop this from being exploitable as it converts strings to non-optimizable heap-based strings. However, this is not done to 0-length strings. An attacker can therefore exploit the mistake by making Update set a 0-length string, and then Update past its boundary, so long as it is done in one `http_parser` execution. This can be done with an HTTP header with empty value, followed by a continuation with a value of certain length. + +

+

The attached files demonstrate the issue:

+
$ ./node ~/stringptr-update-poc-server.js &
+[1] 11801
+$ ~/stringptr-update-poc-client.py
+HTTP/1.1 200 OK
+Content-Type: text/plain
+Date: Wed, 18 Apr 2012 00:05:11 GMT
+Connection: close
+Transfer-Encoding: chunked
+
+64
+X header:
+ This is private data, perhaps an HTTP request with a Cookie in it.
+0
+
+

The fix landed on 7b3fb22 and c9a231d, for master and v0.6, respectively. The innocuous commit message does not give away the security implications, precisely because we wanted to get a fix out before making a big deal about it.

+

The first releases with the fix are v0.7.8 and 0.6.17. So now is a good time to make a big deal about it.

+

If you are using node version 0.6 in production, please upgrade to at least v0.6.17, or at least apply the fix in c9a231d to your system. (Version 0.6.17 also fixes some other important bugs, and is without doubt the most stable release of Node 0.6 to date, so it's a good idea to upgrade anyway.)

+

I'm extremely grateful that Matthew took the time to report the problem to us with such an elegant explanation, and in such a way that we had a reasonable amount of time to fix the issue before making it public.

diff --git a/node-v0.8.14/doc/changelog-foot.html b/node-v0.8.14/doc/changelog-foot.html new file mode 100644 index 0000000..aca89c2 --- /dev/null +++ b/node-v0.8.14/doc/changelog-foot.html @@ -0,0 +1,35 @@ + + + + + + + + + + + + diff --git a/node-v0.8.14/doc/changelog-head.html b/node-v0.8.14/doc/changelog-head.html new file mode 100644 index 0000000..fdab340 --- /dev/null +++ b/node-v0.8.14/doc/changelog-head.html @@ -0,0 +1,38 @@ + + + + + Node.js ChangeLog + + + + + +
+ + + +
+
+ + +
+
+

Node.js ChangeLog

+
+
+ +
diff --git a/node-v0.8.14/doc/cla.html b/node-v0.8.14/doc/cla.html new file mode 100644 index 0000000..1be5635 --- /dev/null +++ b/node-v0.8.14/doc/cla.html @@ -0,0 +1,193 @@ + + + + + + + + +

NodeJS

+

Contributor License Agreement ("Agreement")

+ + +

+Thank you for your interest in the NodeJS open source +project being administered by Joyent, Inc , dba NodeJS +("NodeJS"). The form of license below is a document that +clarifies the terms under which You, the person listed +below, may contribute software, bug fixes, configuration +changes, documentation, or any other materials that you send +to us related to the Project (each a "Contribution") to the +project. We appreciate your participation in our project, +and your help in improving the project, so we want you to +understand what will be done with the Contributions. This +license is for your protection as well as the protection of +NodeJS and its licensees; it does not change your rights to +use your own Contributions for any other purpose. Please +complete the following information about you and the +Contributions and sign electronically by filling out the form +below. + +

+If you have questions about these terms, please contact us +at isaacs@joyent.com. + + +

Corporate Contributions:

+ +

+If you are employed as a software engineer, or if your +employer is in the business of developing software, or +otherwise may claim rights in the Contributions, please +provide information about your employer's policy on +contributing to open source projects, including the name of +the supervisor to contact in connection with such +contributions. + + +

You and NodeJS agree:

+ +
    + +
  1. +You grant us the ability to use the Contributions in any +way. You hereby grant to NodeJS, a non-exclusive, +irrevocable, worldwide, royalty-free, sublicenseable, +transferable license under all of Your relevant intellectual +property rights (including copyright, patent, and any other +rights), to use, copy, prepare derivative works of, +distribute and publicly perform and display the +Contributions on any licensing terms, including without +limitation: (a) open source licenses like the GNU General +Public License (GPL), the GNU Lesser General Public License +(LGPL), the Common Public License, or the Berkeley Software +Distribution license (BSD); and (b) binary, proprietary, or +commercial licenses. Except for the licenses granted +herein, You reserve all right, title, and interest in and to +the Contribution. + +
  2. +You are able to grant us these rights. You represent +that You are legally entitled to grant the above license. +If Your employer has rights to intellectual property that +You create, You represent that You have received permission +to make the Contributions on behalf of that employer, or +that Your employer has waived such rights for the +Contributions. + +
  3. +The Contributions are your original work. You represent +that the Contributions are Your original works of +authorship, and to Your knowledge, no other person claims, +or has the right to claim, any right in any invention or +patent related to the Contributions. You also represent +that You are not legally obligated, whether by entering into +an agreement or otherwise, in any way that conflicts with +the terms of this license. For example, if you have signed +an agreement requiring you to assign the intellectual +property rights in the Contributions to an employer or +customer, that would conflict with the terms of this +license. + +
  4. +We determine the code that is in our project. You +understand that the decision to include the Contribution in +any project or source repository is entirely that of NodeJS, +and this agreement does not guarantee that the Contributions +will be included in any product. + +
  5. +No Implied Warranties. NodeJS acknowledges that, except +as explicitly described in this Agreement, the Contribution +is provided on an "AS IS" BASIS, WITHOUT WARRANTIES OR +CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, +INCLUDING, WITHOUT LIMITATION, ANY WARRANTIES OR +CONDITIONS OF TITLE, NON-INFRINGEMENT, MERCHANTABILITY, OR +FITNESS FOR A PARTICULAR PURPOSE. +
+ +
+ + +

Sign Electronically

+ + + + +

As an alternative to electronic signing, you may also print +the document and send the original to: + +

+Joyent, Inc
+One Embarcadero Center, 9th Floor
+San Francisco, CA 94111
+U.S.A. + +

+Scanned agreements may also be emailed in PDF format to +isaacs@joyent.com. You should also keep a copy for your own +records. + +

+Full name: _________________________________________________
+
+Mailing Address: ___________________________________________
+
+____________________________________________________________
+
+Country:   _________________________________________________
+
+Telephone: _________________________________________________
+
+Facsimile: _________________________________________________
+
+E-Mail:    _________________________________________________
+
+Employer:  _________________________________________________
+
+Employer Contact:   ________________________________________
+
+Employer Open Source Contribution Policy:  _________________
+
+____________________________________________________________
+
+____________________________________________________________
+
+Please sign: _______________________________________________
+
+Date: ______________________________________________________
+
+ + diff --git a/node-v0.8.14/doc/community/index.html b/node-v0.8.14/doc/community/index.html new file mode 100644 index 0000000..f12de7b --- /dev/null +++ b/node-v0.8.14/doc/community/index.html @@ -0,0 +1,247 @@ + + + + + + + + + + + + node.js + + + +
+ + + +
+ +
+ + +
+

+ Node's most valuable feature is the friendly and colorful + community of developers. There are many places where this group + congregates on the internet. This page attempts to highlight the + best forums. +

+ +
+
+

Documentation

+

+ Official API docs detail the + node API. +

+

+ Node Manual offers + stylized API docs, as well as tutorials and live code samples +

+

+ Node Bits provides sample + Node.js projects +

+

+ docs.nodejitsu.com + answers many of the common problems people come across. +

+

+ How To Node has a growing + number of useful tutorials. +

+

+ Stack + Overflow node.js tag collects new information every day. +

+
+ +
+

GitHub

+

+ All development takes place at + + http://github.com/joyent/node. The comments on commit + messages are often source of heated discussion regarding core + development. +

+

+ The GitHub Node + wiki is full of useful links for newcomers. Don't miss + + Projects, Applications, and Companies Using Node or the + very long + list of Node modules, many of which are published in the + npm registry. +

+
+
+ +
+
+

Mailing List

+

+ The mailing + list is used for announcements, discussion, and flame wars + about Node. +

+
+ +
+

Periodicals

+

+ Planet Node is an + aggregator of Node developer blogs. +

+

+ NodeUp is a podcast covering + the latest Node news in the community. +

+
+
+ +
+
+

Conferences

+

+ NodeConf conferences are + the main event in the United States; they are organized by + Mikeal Rogers. +

+ +

+ Node Dublin is a Node + conference in Dublin Ireland, organized by Cian O'Maiden. +

+ +

+ NodeFest (東京Node学園祭) is + organized by the Node.js Japan user + group. +

+ +

+ NodeCamp.de in Cologne, + Germany is organized by Rails Love. +

+ +

+ An Italian Node.js + Conference exists as well. +

+ +

+ Node Summit is a conference + in San Francisco focusing on the adoption of Node in larger + companies. +

+ +

+ JSConf organizes the main + JavaScript conferences. +

+
+ +
+

Localized Sites

+

+ nodejs.org does not maintain any translations into + other languages. However there are community websites in various + languages with mailing lists and translations of the website. +

+

+ nodejs.ru Russian blog.
+ nodejs.ir Iran group in + Persian
+ nodejs.jp Japan user group
+ CNodeJS.org Chinese + community
+ nodejs.co.il Israeli wiki
+ HKNoJ Hong Kong community
+ nodejs.tw Taiwan community
+ Node Hispano Spanish + language community
+ Node.js Español Node.js in + Spanish
+ OctoberSkyJs Korea Node.js + community +

+
+
+ +
+
+

IRC

+

+ For real-time chat about Node development go to + irc.freenode.net in the #node.js + channel with an IRC + client or connect in your web + browser to the channel using + + freenode's WebChat. +

+
+
+ +

+ + + +

+
+
+ + + + + + diff --git a/node-v0.8.14/doc/download/index.html b/node-v0.8.14/doc/download/index.html new file mode 100644 index 0000000..c6031e6 --- /dev/null +++ b/node-v0.8.14/doc/download/index.html @@ -0,0 +1,158 @@ + + + + + + + + + + node.js + + +
+ + + +
+
+ +
+
+

+ Download the Node.js source code or a pre-built installer for your platform, and start developing today. +

+

Current version: __VERSION__

+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Windows Installer (.msi)32-bit64-bit
Windows Binary (.exe)32-bit64-bit
Mac OS X Installer (.pkg)Universal
Mac OS X Binaries (.tar.gz)32-bit64-bit
Linux Binaries (.tar.gz)32-bit64-bit
SunOS Binaries (.tar.gz)32-bit64-bit +
Source Code + node-__VERSION__.tar.gz +
+ +

Other Info

+ +
+ +
+

License

+

+ Node.js is released under the MIT + license, and bundles other liberally licensed OSS components. + Download the license

+
+
+
+ + diff --git a/node-v0.8.14/doc/favicon.ico b/node-v0.8.14/doc/favicon.ico new file mode 100644 index 0000000000000000000000000000000000000000..03eaff0b59ecbc755ee7cea24253d4faabf89364 GIT binary patch literal 1150 zcmZQzU<5(|0R|wcz>vYhz#zuJz@P!dKp~(AL>x#lFaYJy!TfjeSU6)PY+1$#rF^L-M6+Zhv`G7C*0XF z|J~0o66ogq{QH}I$)h99!6znsN7sYS4?8*O^O`58%0d2vnX~fAiE4Cpg!r4Doy~{o zU;g-59U=AT@*q8<`XOnL((v2!@^S)t_~PRS9Pj&ez|&Q7hPI%3ZFiZ zT-DW;`|o~vsgJA|nGJGF+?nam(alLYH~Sv3dFk7qpF9g69%=`rXAlOZPf!|1wucxt qC_iD#FQ|GM82;EZFnr)=U^u`I#LW2d1E888@<2WH48U@OfdK%!)7kO> literal 0 HcmV?d00001 diff --git a/node-v0.8.14/doc/full-white-stripe.jpg b/node-v0.8.14/doc/full-white-stripe.jpg new file mode 100644 index 0000000000000000000000000000000000000000..9b990aeff7bc09015ffa89c8c77f400026f185b2 GIT binary patch literal 4383 zcmeH{do-JA9>?Ff#;pWZX=yhNT9s7QwJxKesF1d)C| zqeQF3rA?@ywk}b1t41;^NHOYGwC;7wrgO%g{bSFW-T(IN&i6UzeLv^ zE9_B_lT(5y?NL@yfvCtUs;a4~sEJwSOA*kQOi3xQI8jAGPC-2TA4>E$00IVCfaWAY zhXDx)ND=}PwThPr0s)dBv4CBHrDSBKD=3ZuUFqK$sF$csCM$jsAv#S6q_U)Ny7{w|6&Er}PdA=#6U-_@@)oZSVdGbYGBf!D2^0phEOiQ0=R z7xyLBUf+eZb1BJetFXnB0;SI`Lp8IsvcD|wKWXiPzRIt)9egoO`t>=(QM~W`Hb&sP zpnG_~#?)Nd%g#&Y6Xur%6>${`O}?%FfMR>QVQp3{G(2UiWZpNr*W<;t*_g~-xN|+! zx2UEPj;s>i8Sadzn|XG8n+Vwj)musmSFZAY!POjCy#Ftnh80F+4mPC!(eiKG{l_l< zH-6YZ$_5Jm=>+&6N7=Npm5ST1EzpBEeP$F8r!C3mz5X-hI%Mo>&LLx$RWeMo{X@ZW z!I*NDpKJN-G~s4m=Kfd4&H1zdn1d>M$YtYGM0zk?nHfTct&Ogq;XxMltJmL-po5V3 z0B=9Hx|&MF5jr~kBh7Jw(u$)V>`Pscoy>ZLt>Q-sCy1eg0&dFZ#~w7*PGu306y)LV zrsi>hY^N6phvN1SDS{F5^KRE0)W$ZJ(w0f3fn$qPanc&XHl}4uTO%XPT%BG?^mJlQ zrm8>fFwx5iC5>t(uo?|3mq*xoB-3J#)E-rOJ}bX+-DXZ1`Eu||yH zAsD1{e7zGF#c(2)>6mv~SCcW?ed#vO=PCKU@0K~o$4@<4T+Qtwl~>bP-8?-0LYB&A zx5>4`LN{8CnE?}-M_}B=cb4b--Yf&VRlRhA)Rs4ixxl-7U$TP*IPEb#8t`~w6H+MWXC-;s1 zu#KBl{%|a5Mu()-JENtM(>fFqt>@2$X0mdO`E_gt(()a|)f#_h6`u zxVmxjJX*a@sh{& zp~jplYB`P~Bz1^@JiG`vubRZuG-Yh#QcH46_~l1-NWJ|;8_ikPgS6(-h@w40eSA{p zPDom%(?n4*A%tuFVfS`Oq^g;QW}1&}_ja1!ym|K#VdW+zSaUd2)Sy$!lpym+l>Ym&hMbaqLGL5ypN zU2LIFlj;I3wj^^Qmt*L4X(Z+HCVZevpR+Q_|V?0C&|n=jtB!+#1j&9jbj{< z{#w`uCVoy?NVONV)BVckI(f9m9p6RJ_$ zE62R>4POh2MKUhA>Oa*w?K#r3`aYw9dHlFeI-V0|++hMUS8jlr%glWg)+e=k+vIk2 zr4c{A=szXsSgD}Zclmp9eB79fa6F31MHO0e-N{@>1c{!G0TYLp*n7%q8xW*PAFr(=A1PaK zDz-&@6af~ARb*1WS9rY<5304&Q`zdsE5wJj zwe^SZ?+*?>mX=E?KOzDSk|w{79>AQz@>=ujxt>lt^!WfNYLU5m=aHkQld+3thfd%9 zD_C%1!O*w{-@Nwj<$*!8CnL&wNcBzDxo+#=&4^TX+CXBD@rKoU*Yh~_Dfgx#-BZZI zgZjUa;Y|sBsZ980{4>g%#Dadb|JAECS9)vmNZj?z+e=&4_t`hzj~pwpJo^f=b%y0x z+#u-YXR~|!`&+Od5Ho`V4$Q=4{YkpqL#k>*q=RiaNd(m0tRN}OG(xKCuC_&%SJ#?O zp;0eK#)FEiVdqC4$|_5HivXvX$d&{+0=7!2Z92a)I!y_q76tgvrJf6f<+bvj*3u&h zA*A0=8pago#a6h4p3 zYL0QRnjlvT*^pJ?e*2HpZ+G4@>54re-sqrDY9&>g=M0GCYIpKxs(CLWlo{!wu-@2)%juhsOA$X zQ+8Tb1#Tx|kKM~N&GfH0xuk6~*J!zf_IH#s5ODCALl05j4kyU3h3pf;B^g8KuZyu} z*;tDnO$TjT$dV0q4t@Ah`>+LbFh?Ucqv-uCjxo`gvhNT9&B+esgt>>%_QFkG-yTnh z!7S9r2b3}y9??WBdhC6#a=1SyzqM9v+`td@tkis;`u$%hn-=z0U<(WLgT^u2&gA|& zaI^2QSQBS92;S6g~>Q~=25eyYyam} z+Dr&|ddYabz0$Qjj<{tLu4V%c`w;&AbTT9FUb$&}{h-F)XN)kfEM``7an(BcnuG1Z zoz0^8>7Ll1nBCio`6d1qak=TZrd4?I=j8|Qj&k^cTZrk!RY9ik=YvSr006QlUH;h zn;v`A8R*$pP%MC>i0hE9L;?e*)FA4UhK{2?r@PA + + + + + + + + + node.js + + +
+ + +

Node.js is a platform built on Chrome's JavaScript runtime + for easily building fast, scalable network applications. Node.js + uses an event-driven, non-blocking I/O model that makes it + lightweight and efficient, perfect for data-intensive real-time + applications that run across distributed devices.

+ +

Current Version: __VERSION__

+ + + + Fork me on GitHub +
+ +
+

Node.js in the Industry

+
    +
  • +

    Node gives Azure users the first end-to-end JavaScript + experience for the development of a whole new class of real-time + applications. +
    + Claudio Caldato +
    + Principal Program Manager, Microsoft Open Technologies, Inc.

    +
  • + +
  • +

    Node’s evented I/O model freed us from worrying about locking + and concurrency issues that are common with multithreaded async + I/O. +
    + Subbu Allamarju +
    + Principal Member, Technical Staff

  • + +
  • +

    On the server side, our entire mobile software stack is + completely built in Node. One reason was scale. The second is + Node showed us huge performance gains. +
    + Kiran Prasad +
    + Director of Engineering, Mobile

  • + +
  • +

    Node.js is the execution core of Manhattan. Allowing + developers to build one code base using one language – that is + the nirvana for developers. +
    + Renaud Waldura +
    + Sr. Product Manger, Cocktail

  • +
+
+ +
+
+

An example: Webserver

+

This simple web server written in Node responds with "Hello World" for every request.

+
+var http = require('http');
+http.createServer(function (req, res) {
+  res.writeHead(200, {'Content-Type': 'text/plain'});
+  res.end('Hello World\n');
+}).listen(1337, '127.0.0.1');
+console.log('Server running at http://127.0.0.1:1337/');
+ +

To run the server, put the code into a file example.js and execute it with the node program:

+
+% node example.js
+Server running at http://127.0.0.1:1337/
+ +

Here is an example of a simple TCP server which listens on port 1337 and echoes whatever you send it:

+ +
+var net = require('net');
+
+var server = net.createServer(function (socket) {
+  socket.write('Echo server\r\n');
+  socket.pipe(socket);
+});
+
+server.listen(1337, '127.0.0.1');
+ + +
+
+

Featured

+ + A guided introduction to Node + +

Explore Node.js

+ +
+
+ + + + + + + + + + + diff --git a/node-v0.8.14/doc/logos/index.html b/node-v0.8.14/doc/logos/index.html new file mode 100644 index 0000000..92e749c --- /dev/null +++ b/node-v0.8.14/doc/logos/index.html @@ -0,0 +1,92 @@ + + + + + + + + + + node.js + + +
+ + + +
+
+ + +
+

Logo Downloads

+ + + + + + + + + + + + + + + + + +
Node.js darkNode.js dark
Node.js standard EPSNode.js reversed EPS
Node.js darkNode.js dark
Node.js bright EPSNode.js 1 color EPS
+

Desktop Background

+

Screensavers

+

Select your screen resolution:
+ 1024 x 768
| 1280 x 1024 | 1440 x 900 | 1920 x 1200 | 2560 x 1440

+ +
+
+ + + + + diff --git a/node-v0.8.14/doc/mac_osx_nodejs_installer_logo.png b/node-v0.8.14/doc/mac_osx_nodejs_installer_logo.png new file mode 100644 index 0000000000000000000000000000000000000000..8570d914fd6d6356fc619a1391b1b46b38edc38e GIT binary patch literal 23317 zcmeFXWm_Cg*ELKC5;Rzl;4-+o6Wnd^;O_1o+-(MThr!(?xVyW%1-AfC&g=d9{)GEO zS9RA>)wQkH-hI@HP*RXYLHv#g1qFp7EhPqog8J0=?;`pF_iyBZ(vRt1hvy=$>7rt9 z=HhPXWC|s0VsB(hB5iAEZVEItH1TvCG3AGX`q?ZkCamhQdhUymOQGiaz;o59Wytv; z{vfUeBTn|EG&eUtoQ$?gS-Ib0zVuqdIJ#vJHzhS(xd84F7H9rTOQ6Iq^d*@UnsN~J z8uFNp{igSkP|2y=!bVwpx&C7Y7uyz>v%b5AhMLAk+hg_{0X91HKgoXC;vpM-`R@id z5cj_Ul2DS+e;rgfsn@6fdKQ@fS~SuB+W&j_KO6jC9Q@z6@c)YkxOkMIo^@f_FF%al zG(bxP2?sCL?=&YhSj61k!Ky=!4FK7d4F$p%y=;}TEtDzk53}3Wq8&f(R?ZVoR}RXh z$!WnMTggYyRn&%^*pmmsi2T*XMCGXKsmlwi?5QZ4ZXN`WJ(2iZEM7xEW=u0i4Ae&?XZSb%$!#)0MLM0`Iz}(a@>2riM!Z z#mqf84f{Jec!baV__s<^i70VrCgoK+4Ns?S$wjgMAYnCMRfamXmQSMHYlWRxPE)&K zFw}2@UnXB{l$jf6ch&aTYZH;a-S(OqQ?RX}-u{FXTV*|n6h(WVgq0kJbvuA|ts6E% zW}u6 zK^c9q8Ax5BXz+=HZRqnuvV1!|nRRQKIF=Ep%5}Jn|D{8leA=#ZcYl>6<|m_{6N~=& zUo!c^*;GWu@w4^XPYy;7dQWC3IlC;ZV`j1FxU0uqBBr^MGM z|8}faS<~Xg(5As;37le>87eoiTHgc#{W)6S7j_Bse_n*rMrv^>TS*7IFS&kmD#8>o zwIV@q3Zsam!WX%L{+H?v&d4y5TfIKbeb#G3Vpz7*84xe7ywxv*t29Qlw$8hfA>U77 zEt8E6fz3WF$UuV{Cp2J#X`&r*XwRa$L5J0zVkm|Y1+K6N=0hZdmDch9XLi&>-BtBL zi!vczCct*|ch$i1>Nlw|=z0tvsu{u**nDBMPf-16Q0c)Ho{Xe2BE5Xr;t%WAI*ckB zU$l(y3w|&l{EH^2>8#mAVoxG;nK%!}{7?4)VMw@F3ajKZtrrzJQv5} z(fRI%OBq4DL4%Usxc!QAtMDS_5Mou9b;B+lKY7U=0BnF6LHU;#Is=u4IoLi zjaE&f6ldc_?^h8xiCcNX9a>S|ztEunEB1P+1tH&6ch7yw%2icO(HpgeidhyRLRV8@M0OHiCsw&v2pkKo zZMJ4aBQ8YyuUs_99t#ifO4Ri++)g_=8i7P)iJhu_xSQ&2kp54TCi<&;adxW#YV)zD z&?ID)S&h)|GKBVDL}34OH}jU1VfRha9oB72!f&UsEtp@npNx;8p_W16#a9$6_EAv} zi!(8#Cv@jAz1h(SpfCSm?UO;&XY)d7p~Bv{AM_ti--1$|QvxEf{^tNe5Z@*3cTTCW ztoW$--$^v9WdivI$V9a|%Q=Mqn*lWpP8h_p%zQp3From&ccIKs1v_reD$CUThksDN z>4y=xMt^20X4ORM;EFSR^_ncutGjID-2E~e(T9cbKWkwHifk12{ZymvQICDNVVi%# z$a{1@PDBEdLK(HR8tB!2U2v;uDsRvYkmOT6huBit3e9l_T`ou0O{!*~AvPUD@>F9UlEWt}0pM%qt5uw^||&t1La z8+)jG)HG=vw|Ul76&m;Z6yX28T4+MpV6*0zSyNuMn{!KO+A5kgRPEFwJHk^O&?=Q% z!MWofu$;_Z=Fth2#61dda}ly-T6|z0YSFzIJS)Pr`@E-0Nd1vpu>XV5e~sm~CAOBu zcIfQE{PE@7+4SKQIInN*{hlm`Ok9Ea4Eyrq zvLN#+8$)4G_kKgT4aR3fpm58OzZpXcbs^RV@GU6o0YZU5dSN~@^;dJ_kC|;sZarM@ z$!gk>h0vy~w`-c)1tnqg)Xe)E=xixN1e!dcg8JQUCtUMzq*P3M<<*Fe<*IV}0h+4w z+#VElo4=v&eZ2W{$ZGphaq%6wyUQ?ob<9PHuw2akN@hauYo+PH6TmCqj#olo2y(%& zx`^s6Oxs9QDRH`Gv8K1icefq$@-iNHg5?>xIhOG9VnQA&vuxhqlt9n|z~~E-kzp)3 zmM7ZfL-vRYOtN0n=zf*;^)KB+{E%O>ioU8^R(`#BUd^MdB~W&dAK4w{qr-H{kCj!) z5>!~@YkWh~UBbC6dMgDdDo$tf|A2-bEDqh2U2|MzoPT&Q5zd{)XP=(AN-m=TfeMy;JQJx$tjl+}1Y={rts&%htc#_nzdUzOQ`M;2dQ+ zmNSpQB1y5 zjJ#FUK&#j1lGBha#hj_saQm+#51Y_$&O)|cdoC4COcvfk!UHLN`X?kjqOUjHwrgsB z&!()hWxD8NK;hL7_>(A^E%7ZswKZ>&0IuG`Gv`8+?MrRUMv6&$KK$y{YIy4pqJnDu z`6=RiFMr@rJG->!?n3dO2o+}|PMic5c2>?KHz^f&0qN>@3f~Pb6C9u9+!jUMGem@I zqPC%#mluSkMMDp-J;h_2i@KrXC%(L6wut0_Sj}Or%3hfbhsaBxa6e!Fx5@C`r7%W7 zQ(v&P?A}u7Sqf(|5lm7}#&iAP zbq;yCWOC`7X}hm~@nRYD3t(&TC!#d-{96rd#k%Yy*Ui>EH+fZ7x*>8x0h4|1sB zVjb|UNKEAG5~Fwc!+}R87v<5HzL226Of^{*H`g0Zn`2@CW`gg zm258N(B8#Bwxk-u8AUXi0ZL{jbnTjmuO*;xzhM^VHC`fXvG{R8O(|Kz{38bFgCDKx zT>i5$;%q7OWvZ!!#agO$CV(=r$C*B+g=(A5w|57o<_}?QoKD7AYKjnuAU$ zcVfq9KFeo2_lxWjrJ0gD8ZJHm29($Zc;E^3qYLfAT_P3-4cCTxMano156T+j>U)@s z%18vlp0Z0f0mOeiVqkGK&iXaq`1BCt5SCB0F}ER0FN0^nXP_at&9YJNG-ZO+q6?#s zeBH=seL&!}mWUBLlhg}BP2OsJky$acqem52YL zUxukoZ|Ki~YT5b6##)a})z$1pipoxA@7G1qSY+M~^#Y=+#;Ml(hbA7Qt|~P+CsCH! z6&>lj71lRZefz@Mp4lqn#;%VMAM#LdKE^$~gK~S69RtLt$a97JCLi+wm<&SGTuU46j5^wH&m*li;>cz4J*~^Ca zw^p|X>G2Pl2~^4MX-Pxl_ka*d7t7l!f$6tD8hKRM)?a6yRnt|XsVj+D1pa<~(*+}Q zNk5m(GU(~QZd)aOpm>&)A;E#sPx~Taz#di1> zrYdl*D9ri3FGxo=Ic(J?A-`V`9=)>H_55@dX`wE;wyFIwb4_wvTH2k<3;?xWI;AEe zjfKRXb%B}$nYsvdKf21cWBK+0H7X9bnu+X&Zrl=lr(JC?FkF`!mf8INN zGh6QxiIXUjL9?3j&PSogP5qA6GrV+$ftK*@6xP2x5wP$YH9jJQNIzJ5$S?eNW;Er` z`8SX~c7LITzPny-!KC!GZIRqo(AQVduLr_^kWpC*twAWWF{8bzc(}S3br;_%e|IWnm2Bg=xhMn* zpiiRpDs550pAQUS1@*<=IjtJmQ{G6aqIl*RA z%-RSZ`;-z34&#+J=cQfAe<%Pm(Id0a#9NV?I^Ifw)80w!+J%-4C)!>($bTF?W9W4E z8enU`@Vdp&;<|OfsRWkNAvlynjXU zcFoE>z4g*qQNx&?;Mi7|?izmMSK`9%*G-X)arOngV}hG)|GetMkavX=L#?*fFS|NI znr>oK+yT`onZ#G|`mq2q2Na|qH?2hLERuv$+*^Aw_Oee0jFZHK{E^!s@v=~ zSSE1N-hhiz?1qs(j~$p4U5fMhrU73rW-pnP|N|JL;PF1Kx;an=E=@doCNsAr_a|QAoD*F(R{bV>RhxV1#l9PI| z6$QaDFzq)t3N)K=a;Nv)8{8lmN}8QBlR-=vgmWUKa>ZhjCf|8U1ko=u+t**H8PlGc zl~2N1iEEkCwt|L>yrza;U0DFQUj_`GYTiA6+4*wBEILlt^`z<#8s9xuL9k(~me7aL z7#GgGiIQSDs#C24xjCDWICRHh9nq8EOe%mgQg(ITDuKq0z*Og;`gC6DFNWqKHA9VI zuTfxv0qy3R&m$m@0=NYGfqmz*LIL>rM*_WiO+cZjy+j0n&uN9GnabU|xuODGcKWi(*=gs7%B!q4H)g5Pmxz54rh-;dcCg=uP_Bc(CI4f#huJF!LV2hS;?daGHsmJ4i|9eRjWv4>*1n%R|nW%o5ExoQN zlF!&m%Y=?0DgeyBYU6b{U|FUq8{q~LJUTiS?X2zlp>jY4JhxuOHs;hTbhIi}zjlBmbIQV0QeTJ7+ zSxOQ)l?jized1-g+9xoAKc^P{ zV{?oL_~_h=0k_W$lzqLGEFEd%JhB4Lq5A%;9#eH5I@YaFK4Mk7OTyD;yNX4+p90ghyg0Zw$(>$@Eo!^mXt{a67p!0ct0JR zHnTm$R^`u?%1yXuUc-Xs$?bM!T?tC1jFQYQ{1o(3LsT6@0?HfvH{Br$$>0_Sch19u zmqTU^vQd{E?C_Tu9-_a+>OQSlK_QR1%LU0i)1mVs-z5)_tjOg~YS-9XtfoSkf9P8U zo~#i8>=!Qj@8GM}?|;_!!+vbach^T!5Ie61PkbV5Pd*5aooxbcr(*^L5OU@Sp<6aiE5f(GpPk1=^+kebfV17##9Sw3>^J{yaX-fg5KaCK?&Pkry zXBTXEs3vf4$=5{El(p}=Z9KVc{K0#>qx((~owo(lcYR5-^VTXIt#0fLkcrccqVxCZ zq=22WQGEONyXHzvQ$L7{dEedzXE_!ifM{e9Q9HFj#}ag&O{#p|!3!W-Pb77FXGtXd z)Ai~+8sL<-|HdPUFNZyQl;Ypn zbq2;etnxWCaC|EtY`AmOA_5`5=ZyBBAc|Q~tg;n}LgNLkelm?;l?W-@5t}av=4q~U zOuoYDw14id`O=z0k_ITJ8ZDd**@oMl!YbC0J=mP|Eaw=&uYRr&I>D?0Ja?#o`KJ7e zic6)0%%W?PSlT>;eXV?-MBW_79$e!4J*BLw{8dP`SoBM`v}SG(mn{=yw7EJ8#gyrt zWU}ns`v0VaAgb--d3_rKOf?bAg`FOKhLrv_npF4Q2j4GH`9@zGV)lide*NflDx`wx zSw(+bOe;VVu5QN8J@bYlz%E6H7f@Nr|Z=}WXnU; zS#2h&5oqI#PYtZkf$LfM*ECuau*&CP+_)~QeNP<@_mgZp8{3jE_K(qYnGB0`G0x?- zoso;>`y*Zg*!8byZ+RCZdw+SrKb83}lx6a`6!^W=4t=PkKcY*3fn|OcCoaU7_YNpa`ZIR z^(l*=jyFEfh783uhpjNB$1>^kPN2O7cO}Wcd6Q}WT_|_?LyTWe*4y=`s#f?#2HOx) z_Z((jdL?tT0_BSmErs=TP&tRh+g|CD? zlvv6Ove0s0RJHwLt!?m;odSB|g177^yUbx*#hi4pSNWu0H6KpibNPaVE#&jFg81+k z7f8lyY(l|OldTlg1}K2O53@_1Wds-`CeRnqC3IM;iq@p)E|TAMJuEagQ6lpl)$*iu zO8I-J)$J!So2~DXRRa4L*r(9ESg58RXqWts8`#w~T$`icr@!Ps=l&Jt>-2MPW40Oj zQ)6`_%gNwiWW1By&tHwcPZVtDVX=!y7)vyR%Uc{D?~}~w=8-3*pV=-Jr)UxRuTF+` z;?j~xckxC!s?Xm4TVIYK@7ggyn6`BC7)no=4xc@Ml8q6UVkcI}^$&3hR@rA;#{$;> z6{W>>qv-uJ(OS3Ae~~~0h9~L{khC91oR4)mgR20c!Vm!_wXJ7r^OW<_R33z$-MjZu z`7oZ!L08daREEO6_WNvuORN`q(A)9|0o%o3Pzh;9JN>|4&yfkK5&Eq`1xDdy(L}f^N-5N%3np4SouGDsLu7mC&b9L zK?r0BX*lT*Z{_Nsf@pRMXAcn>Pu$-4HfTH*0Rz(m+_}k^fVGs+Ki5j$)s|Fn`Yr3$ zp^O2YshE-RA_My>iTQE-nBByEsfiW&VEb3L#z5=Hn2d;C2kn6Xh|d=tvu0T`IgOPv zmbqQ6^4{Pydy!m?GYY2~--7M*^`{{zx#;9UJ$363Mj4E>h(T6<->4=ihmPXHnrMz> z{6$(LO^k%bB)WDN7@keTR0J5wLwQ=QGe8)S-FM5^>LJ;4fuV)$<_ig5~t2v#wA;(5gm_3w4CIjA*1&Nr<;#wU>@w9$(-I>Sy(y;$fS*#jti< zcM(dAU2~*hd;jgAGC=SsxF{mYLr?GWGeb=^R5Zf7@uIv_zrkn=f1?S7!G8}`V65bh zlDM>l@AnnFFZNszW3lrOwNR-DCmk(!qnOk8s)NH0-6z?Y`-Ud=s?xKj+2EZELo$5lf2!+Dl1iIgS2#XZT0_4N1*6$231&Dm(^aE*toCi&>{S z?*0{W5pl~om?_Ls?%ypmT`?dTGZx3>irsmA4<{AwWa`#~mK1DEl6FCgY%0Q4th+5;Z#;E z>+x+V=@BL7+l^y%##QP!Q;hp?gGx79k*{UB=A%-qEagKeKLgRr`!JxdQh-rN@{TEw zAhkwm#`_%h5Ob4MoCL9f(`u^PWSU9WD=Nisd6YM_eqqe)sD4X&@;MQIDh|lxP0!`2 zEgRJjq%ALdvyY-loooKL2xs0YW@hh&xZBI@P;-CDPTmNaio%SdhF7h;_wj`O<>=qO zk?!@|mxB^)pThqpn)QJC(6x4@ricfuIOwnfZ{^ND;TIwwvfq!h4_T3on(qu__DrW# zFR{g27(A|d#B;Q>&9$b9-*obeQ#5rB2%a?J%{FJ&;6zblNp}-4d;wA3D`>)1uZoX1 zM5Qdq=X>8Xwr(wMMxyabhvz&*0gU$!OSf9e3%{+&26YtntGw7zqWXrbg{_#_3-|6R zEl?4;4r`Sxk0q?y3rUap`-w;Y>X)YdS`6C;80&|-mB)CQ^Q5G`sD~VIp1$IJ&{|bn zj3m1n-86o~0-XQBeWYG#kV;(cx;Q5?xJF}Qa@d4f0k1XPXrASd(%|3id4$T~llo-a z{SCNujumR}>!?QOsNz2TMWi`A|4kL!MsHbBgW_>S)Ph~a2-n=^k8`ZLC^ILqOzf?U z?_WAbZU^jA-bc~4x2~d|RaOzKk>3LM@UU<%I=TM9rw~j;P@~M`w4{_2({Z^6v%>}xrK)IkcGPh5Jif@U)*Li9^>Y1+ z{F?%*+TRJvDf*sTXFS82zMeb~$0OMyRQ<|W;hbD|p#4@d$tRYmI&z%S;yC6{ST;sL z2Sq_ngBfyi=F}=KO4H_bko$2FH?S-qwv{8Mwr*cJA_dZbzfRFB&J!y`mKQp?{bD=p z`#czfQaXW#;7smzWR#xX{~UsE5Nq~P0pB6~Ncf1O96NW&Vj5vUxzjz9t)Z;-gS)et z0^N?vy-rN$FMY-lJ+}{sWj>Jte8 zdSLTrt^(l|n39KEz3J8Y89Usn|;=;OFnqg>=RCDFjrTb?`taYYIjB#*9lCG{?U#jn#B*@S!|RNppCrQ#~qR zG&VoV6GL>$0J$7nLt?Bjf*sn)$v0l(m+nS+yC!;Q{Cqc~=1JCfa2xL`Zw)`XHx;-D z3CenU_s_i6Qw2YUPF{0Pif`Ld*%N+L?Dp7_#cVLU*aPk4a7BJ9T)dNZ{L zirqxmdJRn(!`Ub0$(T006fXSdTw8yxV2Vz51uFu?_r#sVW0xZ#&RiSqev^3U^anU; zmmPzbNWt^NFRm%{?0qqCJDv9Dpx#N*^cooK9sQ!(`|4nP1LrGXZ&jdE=XZZ6?@d^5 zGS`{i63Jer~VJ-GxRXFnWkN~r)5jDyfj(K!@S8rYhTU0Q?io939kaXI>Ukw3? zz*bj%MF6~Ci0s8ZhSNdJDEwF&JSV ziP8^Y0Fw1;oS^fN1b$+UcFC`FJi{CP?>t_QaWgZF58KzE!sapo(ngqZlx_66tpDQ9}sT+Zr+T0CNWt4><_%Uhaz!l8TX7^0Ja zs2ETF>(=?2ho3FE@Qf>F$o|!KY?see^NeS|Jn3`~xN*j&|JVrZVDeYZ?(IT^VUr#w z!Fk8jg#)~a*i^ByP$6X-+z74i8`&}{vqtBaCEPbU2f?LgdsP@B-w(-?bll+bmPuIYCDA7%&<`%#!~JUd8eWg53OY z?m=N9b1sR_uF3-4qY#Yty>)yYfA|~{^daDeB(a8TPweB8AZL0BiF1?VwhyIQam(kA zXz~ncoQ{I5dd%Fs*9@n#{r5f7wy9<}K@)UB=Sx)fre9Zodtl3}Gt)pH_}arbC%5d? zBPw$SVD8v@oO-#mi-A^3@=7(F!2V~%DczJ<(t~gJp)O+D6Rii-8x5+nMZZUxd_nYB z1@0o}u2ouoJ6SFhbt02|-n}!IULPeP{WV20?wit~yXFSDB&pfoqijNZ9_b@E{bSrV zVZA1~X3trBGGsy0$Ww5v9VON0;qRI5Z2|>lDVH3&dP< z*|U3&TJ~&)36_-x*7SWCspJ20*U-qQFYo)bwQTOSpmi5Tg#Qk1rw~n;X`*J!yS0xx9hjHi3yk7)qS;mbpQ+97Sajbeh z#l^SN*soZE-Q=_Uc&?2cLy4I zc{3r{>RLMaReauzDFkN047Sze2S|0~%7Xov%KJU<82zE$i~ z1;tZTF1*&a`CRGyud%1Gdu-E;SwLihXi2Nmb+~T1IVC9=ttj0x1!5au9y1oFG`q&W zUU|-ggtTi06a`)3_PXZEU=E^UU1 zn$vn9V->77xE$-tx+m*OKYy%378s1TV=j|$h!hFZ`1|26mqo^_NKU=jVfRa8xu44^s+EVb(Ug& zvO-ku&4|=Md5|iYAQLz2U8&FZ*4P=V`vN(k`T2Opv?YFKmz7_O&_${-S-+w)tBL!& zm%GAbwgeJK)-CY`$4*G%m8iRc$c*MqXt|1mT$MEb{NU~Y8?$K_SMNrl7(}O2QT9i8A3JqKx zKhub1p)b?ggl8f3a=w;2DG`ehpxeB3i|8B_3M453$2+qGZP22aT;!$=NF16)!*P}s zGlSm)%WO-;`;si9wzTCSdbIeQn^9@;gXyfDi6iyt?jygygvo$0e-04gmp5n808oXT zTT`hX?gsNs)-y`!U(#vyeBOv=!1o6gjm>f&@4w*fA1Ac^*?4@1h^Z`h`kzD)7jspG zPs`odkZUoJpW804{WeY_{f5rQi}BJmc@)C3S~C|n**E;S?<^IM{BV>1@*gw*PWuP0IoIzZWdost(iu-|6ZQ7pVcMJgX3noqz;aUG>z zv*Msxx_m+JnP6(yGh8g@2WIZ8U3%9Y;qGw5|LDeKve&r%i^Nl*iY{Z=6`Pwp08e$u zv*uuSF2Q(Bwq9Brk#lH)IWFt>$1SC*ZE{XQb8L{W*m9<>7KkF#5G52_f17`+8tys) zF8IgYeZIWgALl(Rem`y!R4q?uyz?>D;*1blFEdAkIApqY4Uzq$xtjexhVPtE_Etre1$_nHX|axM`n3S0Rr+l()^pY(6tRqx+~G#-c!ZZfSwXB=O~) zwG$js0wG{ioYkc*D)o4OyuEB~F|N`tXUQHv5>HaQFm zh}hGZ=QAr?7t#vw(-UnRM}_m)QDSGODzv6E4_n>lg4^ zK3;UzrAjfs?Yd~)f^eN!dnj&odT-d%keQ?nj6S-z-21V@T2azO6qj|#c1F#xkHiX_ zXed^N`itv;5CL$;+#XCnh>gfH6T2q-Fp^@PG3os82#8CkP9G0qM#J5p|D@O6%U@P? zf1bLz9Fs}0+rl=YremSn&K0L}Y1}Cjo7AxiB;)h>)4{qlh+xe9l)g%l5Was@%VfIeiJ7vxrIcf%V9K{x7|T#{J8Va@9{gWdi*_m~VA z&;Lv>)<;0`v95Mcg_q83GU6~C(dLc6pFt^^G&Z$&4w$Av<+^ZXZulbo0V~-o!e?1A;?58vH`t1YFPwZ_m{lEHB2l z$7~a?A)c1!$pj1L`R$X$D(-?(?%o;T!^_!6TJ$kh@$qs*qJ(}Xo+Mkx3v9h>FM;2Y zkCzKmURr5FEwGly^)V!b+PS~;e8j_3Jwh#4c2BVily>&lr+G?v@5}kvJ#vb9|*%ad$B0G5_%k_QhX?+XJkE z+w!~2QHN|YHJbg4D_nnR?Nb0yetwRXtHy&Bx*fI&Z9Pg>MBITm3ot3^!%}HMRPtvH z?mrt?IqW<2&T9_DJ4;}o@Rwfo6i(rq4Rq)HrUiXe2%|`o>&U zi3o$)w4YMxN&7uj`+dfwU-rH(nsJ~^cv?y#%A`A*T@No)j)lEKy*UT?`N60S_}?i-ExD%dyzG_ybq2rLMG+wY< zd}hMiLierOCPBGXeTA8zN1;p%Cz*sOYn4BbKD7U)8m-KTH5X5sc!-8aFX@vr8RN8d zhS@sL5O<@#Q`X7gC_aRu|H>iQz^ciYwbd^4LC}q6<5ijtk%}Z;o_A0XFU`&m=NsGp zw;r?;9@PoHc^khJzKeVwo}W@tu#;ECN9$Tsj-}aikvE$vaRNH}I7c^^-ru9h@8V30 zJu|wS;PwO&J93r=e2b2_@~mjWWfP|h%E4nbSCKOeE84NFLthS}>Rhz@1Fef6CJWb_ z?B9^lc(U3Q9la0_GO0|`?Cz=LfF;qh>_x&veZR4fcs}kx4-~UnO_!CNs9Y#XtodG% z1e#wnKt_*Xrm{Ru+unE%Yj&~k6zRiusdPdVu_6v7Vhhx!m%-D)19cJ9hSAPj5l2wQ z_Bix}bnIEID*Yr#j)`zgw5PubDggep6li%h#i~;MQ%kik_Ag$aUCT+fKz{PtA>sfC z5_a6&eCSEQH=?fZpfq^B@4m&tt1QWLRjvlUE@1NLMQm=7)@cp^$i@Dx)BO1L)panJ z3ie{S$mFT13Mtp$P_#Hyv>DGSv}~yO#VadOu61)&C0v_#s)6Zb6i-{$CL&=_|5TmS zNENMHLX)J?6NVBse*at=m_cD4PB;W|PlSu^-0e!s@APxhKP=W-O6cInSFSj+D)_MH z!FGBdCYZM}CS!8VWtR~?slDb|odiTiUJVM%fac}CnASDKb1r~VhJVmYY{dnzno%ow zlQG06v9b{%2~5yV>RvN7PtQx}y5f9`_%gXj{2b}wc0p1P97>QpruDt0_H~C;r#jv% z3fW3yw2Z^QPKyv~dI@fFRJ2;BnLP+udh_0mA2jStrfH?MoNg0d?(y6$7o?Szib-k! zvtUmoVZlGtEy>OZm@f(?Q~+B$g_h*;$)#&IqW)rQm{Fso&+Im)JhXPmZ7G>lno7_!w?Dw>xUg-dw?=Wi3EUo`pBcn; z4yhU^r8Y$r$g>USJy6h}ALjoUN=a->*UX!3 z>T=1?xPQE<^S-3<*{mDpz@}8{3*3i6M#%D>qwdeVB`_B=h3KUlFxv7TERkiuJ~W$L zN1EzvxQga9(YndevamDFUbtuFx^gK_v0@ek^MKngR#S#7DHX$}6MgIxHJ>ZSy;M<(ay-;WA*GO2KmSs zmQn>N!8!OYBeP}YtCWw@dmDefcP}9t06bE7i?y&a+B4ArNH%?oXTa6<@ml4a!8P-c z9ksnQ_-H>o+$i-p3v&c8{)ELJH|iOfqM|i)7aIZiTfotsQ<&p#6{A*=8>Fy#xk~u; zr_03)2V1w&$aO;7hp|idf!DG5-852`>YVDupiMxxvn@rc4xdV4{MylSk!$>01#dRn zz@GM6bzp0nGB_4?C?(D^qU(D=1Hn{AU;^>}oRlv{;kylF%`WyCaLH;K;$hO%n}F7* zSu|skKE*~0S%@ta-GQ7} zW{d4<&Rj?5Ri%S~qJFQb-rpNK>}SOjQA*@+i{*3`##WwKH;nB!UMx!}(@}`>j{Nf9 zH_-u)>n3P+!0koejKW{{20;!`j8#=Kq>hBcjG2aaNh^6oRcq?U5W!}L*V?J|zhf~= z87h%7p)UP<8nac8IyY}9?s6X{bE_xSEI5`p-HL|j2RvahnB>3c9@BFPziLXkZ}4+? z7ljS!J~ZGt`A;Q-P4JCIV9X+E_w%Tpk?t-I=IMwnZ^Qqw@ZQ+Gzz}s&tF9x;2_E^Q zII{jmIj1lDjD!)(Omx#*pV;&$PxC**Ew*rX~FjuxlwV* zCh3#H(rsqdQ42gQWr%9Xg}2UNh|~=NS)uOIsKZi(5^UBxjQO3RUD34PPC*h&=SRQM z`+7gcOfU8h_4HM<>41M=NtIR!&E|(OQ|tI6fl;P(uQDxsKsj`wk4Z+D&~En zB%>CG-$-TmipMjGkY=}KiYU$uB_LSki~@hcV$a{`8aHiYMzx|K8F8ulALhsEinkMW z1utR)cjEo(_kPSp;mW+?ZTtP^w-hSXCjh5asN=58Kj0{*6}Aua$uvq@9zl649O4>3 zNU{;~t1>;-nhaow93&Q*yt>>j{24yknU>{7FIhOB^9s$Z2o1u*&&v8FTqT(yk_J;6twvU<{hgb+4@YYwD^wem$&E!h6?cD6`56_s|n%}H#gOa{+! zwZ!hb`s6ByBssnlFqeaVTQ1F`MH4@s21=Dj^E&qBLG7gnsMHw}=_D62CxPs|&8@ID zXPZ}zl_^g%L7lE2zy`DtwMjO$ROq8KQlC?K92n>VOk{$sKqeuVZ)5_Gdz9GM&tq;G zE&G!~@^Aa2kDC(4*&-`qH?_bcNn={zq#RvI-3IOn3wdQEYp1luQXlr5$Xn$|dvONF z*0>qz*@eX-+bETNCEXtV3GgkV+_j`{^ewQ}yUhB~)w&o;cHB0P5vjA@Ua|cuXc;cpKde{bp#WYXP2=hhzJ;wb}o#7z}6PT$nICmIISXkI(_FZ^2kA7ZNoWH*H``1e^evi!6JBn`a}#V zh4~WsG8on-{f&_TY|C$I(1z&4XX=TyM8=UR`WMIDfQ#u zW{eGIL!dq)Yaxq1+S`8rD|^9=0twAa8-iduzS^0(bi7Xv-4!hC@NG&5rkpZPEinxh zjgetzW~d02lBCeGaHy>$2h6TF#%=8nd(&znZ8+mp6R2a-^(lLVn&jxuG#9JCw>0?| z&HDNebzP0e8J^KSOT@L7?H<={P~E9nSUD9ZB6>H{9sCvb|#%^8K zuHE-qlNAwQ^b>WCw@Dyb;_cmB^DX%XACI%wm8cE*EoG8amXz`{b^^OVqS)Zw3hLlH z?23ih7b>kk1G1zV^4q`7`h#?Tj2R&d7r*FKP5)>n3N3+Ymr5HbtdhnhTvLV|=1X(a zAE-iLT1m|z`_zVad?G7YHX^p%+dUo_BbKCvr0&0z%6+mi4j5v5Ds%EPa(dHLO?Rao zv`TQV^yZM=9sQ^#CmD*}d@_;et83xN6ub|I+(Jp!{O)n3O(wZBX=cc>svdpXE+6%L zKj3J~PFj`e2BOh&$cP?U1r!&`k3KB4=Bt#8-IB-jX$!T`5 zWXvE|CWUqCZVQKUY1u8R80M4~_}{66CIZ>VNDh1q66t--sMTKp%z4a2b(Fk3{?MpSX@}}MSMNEM_QXep4!3>{ zBK2&2T4!x3m}n_}6BJ@Z_?Ntgm|4>+vOgzqE)CP;Btk=g{MyYIlcqV@`4?SY>xdDm z(Akyk*jFu50guLSf7EC{Uwu?tR)w@i-f$(O)bQM*F9AKFJu;*>3%__2VWvgZ8ja%r%+00Iw{a3me~BYHVU*$ zYN|0c+6F>1f+H$b(h;tt)sPUj6iZ~VpnHlEo8_4@p9tmc$IbDwnSHW0cA}uhq;STu ztD71x6Q+=6$eA5O)>Z*64eCyh(E0q4pI0Y#yi5GWGF#HMgjVUcH|l#+^}SHr7bwiD zIaJ=dbBALztIA@1GbeiL<@#r45GFBK+qaKvwcM^|^L|%xn?*5SZA=Tb9iX3g(cxy- zV{wB&)6aJ}!e^lqla3jg$@2JFs?Xb*18|T>cfMz!2@B>*!1v|s6B3lc;VOBs??op4 zYQ@`et#?W_csQf__LDKkv0a>c@lhAns>{f1pRLl9y5eNqKIc@Gzws7$k1$GRm99B4 zPNmHpP4L*{jJUmkT1E-Sxp3F!e!6y0D{`FVI$geV<(_;el~9JsISly@ zBqDh&h%~U}zIrxRd-~F;e-(b2sel0-pn!JE1$``Bvb>_nl~N!qd&Qabw!T+v*14^- zx0g#SovXzWm#%ahtFGF{rp`g5xM5(SN zbwHPTAD@Hr($7xy<3JVNeo4& zmYXNxF(nly;>pnw@Ho()aZmu5Q}0jJ>~7Se)%Qbf4E!8J{@D94s_9xOIGf62m~5*jPP)LL~^t`S^oxEwlOM z{f?42(|MO>g~TjabQ4Em(~>w}=HeqIc%HsQ(WZ$R6Z$I~{w-}+`wL@EHv*_r3O!>%2bUSt~H#f<$V==KbizdIi$oRIP&$J(dTk&TxBEQTJ^0yFZolN zLW3z+Qz2GUQ^F6$ZnJ3(N1up>^OWN!XhP_o`r!%s{vvJvNM%s?a92WIUGMtS6pf8D zO)TWXb~uEJ?EkCneHo9<@ltxCC+mB2b}=HdylIJMCh~L7R}Ny9kJQqyMGsSkO(L2l zRjX@g!T073d=eKbZcn>dwj1>2Ggb_1n8oggN(?zt*>MBs%n<<#mW|HDCH@hY#_x+q z#JGJxf9ECo>wlI8rDdnY4d=xApn81E_$%FgTqnoE?Z^66JzcH8_Zt1-pXEbN`~=#5 zwQr6}hIxx`PQ~e$cJhD23oDRVc`Z%kApI;+eo|lI$W1G~D0eAEIh}9zZRhEK2Hc_T z10@IBUBe&|OB8r9N<8js;*nDc)#~+}BpRs+GZJ4;HNYN&&tAPn@$RXiWYbTn%-=a| zT%%WFMCSU+M$Wzgf&+VDn$lk=C+Bf&9q5|cIgLHyP}Vn%%VAQ+(S1VOvxeOXi&u=% z&o5jjUa=Z-nW@u7FQ zc`?-JHRhgr_Pw;dQ+G1Qnlp9ReTgGmdO5f)K;ImpzC7$_HGbZC=MC*-AO6S%=TXCS z4wWStgHp{i{y|^f&1I$zlLj`7h#0CE&$bZ!s8pF+?nhb_<@=AkV~HrXg?gX36x-k3 zQyjN)E^CEmCWUs`e<98EPER{i=;WDytUqGL=)?5a7KN&YOr?TALYFX(isONrVF;Kr zZe1B~wb&aYXGbKCSEPU)<+!w2c|Deq;`LN|p54{&r2E|!>u7pX`f;kWUoq+Bw`Qc* zb|85SMA!|@a+&{qTx}(G(h3)I&YnL^E+mOT+XivqNWUd-EzYUrH*VFEl18PoMS(LSVAq{TgDVi9DTHtOw9fN*O@+R zuX*LeJxANBXue*j?bBpqqDisW6#vUv=`&hyl7pA(cW3K$|D9gMS-RtH!MYR%`C68m z*Esv=>R}I9mLa-1J?!BpO1=(U6tU-LJE;fdTHW_TefK$ie+ifR=MiVsubzsj6RgVe zV|B};^%}>*i69vV?>LUD*xLr^k^L;#>(|WCZbvMl6JN12-SNjhv)GqA*}#7cmz4~x zOwGc?@F#vOXFW?wr$X+(5=7!&#-S^AV85X-ty2}U(FvLGHw)!+4OXe-F4J8ul2R*h zZClmUH~;D8qIO)rsju8qv_hs2)Am%of+NIvU}hb1DJ|xkPt3qkyj*DUlVB9ZTtb>C zo+C~8#N$`cjt4KI^{Z!_ji$J# zCB?eMe42iIyjAH)!k6m%v#7L^5^MxX3kX8o8Uh$Sv6<@zGKdlzZbi zjH~>6rnX1x_ZGLfL!6x73+wv59($pFXExCv(1tyycP{aB*M3wm z8A7L#?}(7|JD|80V%PM-iB+#ZW-cs&6ep?3i{_0Z?{XcJbsLYx9%h@mmrXs!VHyi0^ z7v4_yJZlB*aKIwkux8fj+19)Ha+$tf>6qgOn#M2FaeKHHFc2ZVlsk3vH}u2JLy!Th!mLpZ`Fa zAl5mO3}YOn-#lN+QZWZrdvfRj7cWTtN`{>inDnyzZVTukuicf_-qJ@YFV6I>6pPAV z>YE1_Djsjrr?H*s!5#IR5cP=di=0{-OI*eAkJ7!mM#nR(n9%ZZ-S^_bY8cL1GK?e* zeo|q(AUe^wR?ewBBWb1P3!;#6j%)cvQVNF)cSm!=S@OvZnUjdpWQf(4Yf2l7yhpeG zGLb_^FBwLXm*|4cI%eqs+768GhdEB<+)#wN%WRg|1jG5{{HauvP0;>DF6>zaF<&?E zV%w1r_ghFuJYgj*-(x`=Cb-L5S6%HrT)&>0FdK=oA(yvSOdxoh{G!P& zuo;PAXA!d!G0)OIy0?DVlPEt~JhfT>#85FaCA9r66Lf@fipzGJD80?v6T{Ajll1R1 z^!R_d53Yr2 z;<8-I%En?6aa1#BqSZOdAL;1@t1?lN(KfMfOY;b3l{QK?6bm);NA>m1PTeyfF{yX? z&wA~j)H{B;@q2nV`|9hMBw0=(3sk0{Zb$ME;v}+O5_0G-_8bKG*ST}+T)BR1sctbQ z!yLojuUkGkH|fp?!sqnbwCN&Ae2!kLsV7(DN~ER1SMmEivrr{`2>Lmf$}MFkeE$ah zzdiZ(`GGkEi$5%{ZOtDx6{VeIX6XHTh2F>&g*sB`9Q{#cHh87Jw+t~$T#u~Rdz;jI zvq}+{>UK+4_opVVYCxFNj;%vyOOcG8$3wj=`&#Sk^@G*=w2+FQZjQk?RAQJbcIrOg zrCY9-GKJ5(Y0JY0U3-n*kriCsTkmBtlb;D=fU#r!HNiBobd1*BGF1fW4gnYFi9ex4 z$TDm^&FSQqBr0luA?JKPO+Qg`m_5u-!&Xa?u^CcgQ%qU6%orkLge(r~x-I1So7(8P zPWAK_C;jgf%Ms0z9CsDcIVyu2)cDLKw&plyxAp`!rs5A$+LZs1OJ|ua0q=8!@p<}c z>gj!Kex+sAn!HNWu~3UT ztE%swksgyDThwq&q6+2Irsb&yZE;(z??3Apwm%YuUYa@6#XL}xrelwFu_k$??(!)8 zw0)T!Cr1GDUh72E7!H*%Asi+JkIrjPbc4RXUO&Csg1l)+3BC$WHzr;jW^$@iI#tZKN>=9xA4BT*hI4< zo?c30xjeqPn8B*2JVv{@SYO37N^EVcp4$zUltbT|qsN8AB!u$?naJ7uQ5nN$#dg0| zYMJPu7N@*FmA2^*7KAXSytQ3%jsATTvpFahNiXIFhMbN~p04e?de8r*uMcnw@pZIy z;)hhaGC!tNMTmLDzIvcRsZU|k`Wd=hC7L2weE3Q7uGDsh4#G#5o??=4F5*>?2oqay zm?Jc)Gt`AG;v$#m8=SOkF@uv^(et-B*tcpISdjMH^`19%la3@%z;RZ3%7xL#%2uHu zTgWf<_{T{ZuJH4%Y<`)|>+wY(Hp$OwhD(xE7-=H6u)wgtO@icaey>+g#2DHaYrh&3 z|9%=(b&GjG2t7PU@B2#Kc!{=?-8Qq2oAg&!}cvCl=9pFiW6 z;x{?LV%}ibC7g__xWsW$tGCvH1)^t#;)K!&1z?_Xy|F8xPk7Vs=K7m+6K_mrNgh%-hQd=4-VN zpQ5ijNs;tERxefAV=NZ(jk?VoyKWgQKV8M1Nxd?bRSB8I@0fpt!;W@_D!=*sZ?VqjBds7fZIOs2|^P8O3m z-&xvGN0RGuOMuyEKc#)}6YZ*pmx&u_?>Nb}ABxkFY^tt~JGM^4b}1Kxivpo$L#%l zHAj%0hAEd-#*Te|Q8tG8D%uJi4O(K_Np07;MfMCQeJ`abFRw2T#-5N~5#TFy|93md z^BN4EATKQOly3X5zFIb$?@*r!_CXAR`2tfzSq$j+b!0!1EESm)nJZG%f}+&| z{J2Z3Zk}fw(TxE%xJBj1Zt*>x%M2z-Hk3F7!NC^kkGX~aDs*Rp-?{c=x@w(Pe$%YS)YrJJo48_J}!RCw<$RVVr+M_4FWTNd`aj2 z_w@DQ`g(XlH@HaP@qeY}LrgpL-}5-_ABZ6^E10LExtagWB`mkk<``qDyJ>XKz_7Ag zS1VKTCuKBVri{f7F8<9NWBys+UxqH46(eVfK7OSAc>!J(>i-Kc0E3`8X+E`jMgRZ+07*qoM6N<$g4sxIi2wiq literal 0 HcmV?d00001 diff --git a/node-v0.8.14/doc/node.1 b/node-v0.8.14/doc/node.1 new file mode 100644 index 0000000..9603a91 --- /dev/null +++ b/node-v0.8.14/doc/node.1 @@ -0,0 +1,446 @@ +.TH NODE.JS "1" "2010" "" "" + + +.SH "NAME" +node \- Server-side JavaScript + +.SH SYNOPSIS + + +.B node +[ +.B \-v +] +[ +.B \-\-debug +| +.B \-\-debug-brk +] +[ +.B \-\-v8-options +] +.br + [ +.B \-e +.I command +| +.I script.js +] +[ +.I arguments +] + +Execute without arguments to start the REPL. + + +.SH DESCRIPTION + +Node is a set of libraries for javascript which allows +it to be used outside of the browser. It is primarily +focused on creating simple, easy to build network clients +and servers. + + +.SH OPTIONS + + -v, --version print node's version + + -e, --eval script evaluate script + + -p, --print print result of --eval + + -i, --interactive always enter the REPL even if stdin + does not appear to be a terminal + + --no-deprecation silence deprecation warnings + + --trace-deprecation show stack traces on deprecations + + --v8-options print v8 command line options + + --max-stack-size=val set max v8 stack size (bytes) + + +.SH ENVIRONMENT VARIABLES + +.IP NODE_PATH +\':\'\-separated list of directories prefixed to the module search path. + +.IP NODE_MODULE_CONTEXTS +If set to 1 then modules will load in their own global contexts. + +.IP NODE_DISABLE_COLORS +If set to 1 then colors will not be used in the REPL. + +.SH V8 OPTIONS + + --use_strict (enforce strict mode) + type: bool default: false + --es5_readonly (activate correct semantics for inheriting readonliness) + type: bool default: false + --es52_globals (activate new semantics for global var declarations) + type: bool default: false + --harmony_typeof (enable harmony semantics for typeof) + type: bool default: false + --harmony_scoping (enable harmony block scoping) + type: bool default: false + --harmony_modules (enable harmony modules (implies block scoping)) + type: bool default: false + --harmony_proxies (enable harmony proxies) + type: bool default: false + --harmony_collections (enable harmony collections (sets, maps, and weak maps)) + type: bool default: false + --harmony (enable all harmony features (except typeof)) + type: bool default: false + --packed_arrays (optimizes arrays that have no holes) + type: bool default: false + --smi_only_arrays (tracks arrays with only smi values) + type: bool default: true + --clever_optimizations (Optimize object size, Array shift, DOM strings and string +) + type: bool default: true + --unbox_double_arrays (automatically unbox arrays of doubles) + type: bool default: true + --string_slices (use string slices) + type: bool default: true + --crankshaft (use crankshaft) + type: bool default: true + --hydrogen_filter (optimization filter) + type: string default: + --use_range (use hydrogen range analysis) + type: bool default: true + --eliminate_dead_phis (eliminate dead phis) + type: bool default: true + --use_gvn (use hydrogen global value numbering) + type: bool default: true + --use_canonicalizing (use hydrogen instruction canonicalizing) + type: bool default: true + --use_inlining (use function inlining) + type: bool default: true + --max_inlined_source_size (maximum source size in bytes considered for a single inlining) + type: int default: 600 + --max_inlined_nodes (maximum number of AST nodes considered for a single inlining) + type: int default: 196 + --max_inlined_nodes_cumulative (maximum cumulative number of AST nodes considered for inlining) + type: int default: 196 + --loop_invariant_code_motion (loop invariant code motion) + type: bool default: true + --collect_megamorphic_maps_from_stub_cache (crankshaft harvests type feedback from stub cache) + type: bool default: true + --hydrogen_stats (print statistics for hydrogen) + type: bool default: false + --trace_hydrogen (trace generated hydrogen to file) + type: bool default: false + --trace_phase (trace generated IR for specified phases) + type: string default: Z + --trace_inlining (trace inlining decisions) + type: bool default: false + --trace_alloc (trace register allocator) + type: bool default: false + --trace_all_uses (trace all use positions) + type: bool default: false + --trace_range (trace range analysis) + type: bool default: false + --trace_gvn (trace global value numbering) + type: bool default: false + --trace_representation (trace representation types) + type: bool default: false + --stress_pointer_maps (pointer map for every instruction) + type: bool default: false + --stress_environments (environment for every instruction) + type: bool default: false + --deopt_every_n_times (deoptimize every n times a deopt point is passed) + type: int default: 0 + --trap_on_deopt (put a break point before deoptimizing) + type: bool default: false + --deoptimize_uncommon_cases (deoptimize uncommon cases) + type: bool default: true + --polymorphic_inlining (polymorphic inlining) + type: bool default: true + --use_osr (use on-stack replacement) + type: bool default: true + --array_bounds_checks_elimination (perform array bounds checks elimination) + type: bool default: false + --array_index_dehoisting (perform array index dehoisting) + type: bool default: false + --trace_osr (trace on-stack replacement) + type: bool default: false + --stress_runs (number of stress runs) + type: int default: 0 + --optimize_closures (optimize closures) + type: bool default: true + --inline_construct (inline constructor calls) + type: bool default: true + --inline_arguments (inline functions with arguments object) + type: bool default: true + --loop_weight (loop weight for representation inference) + type: int default: 1 + --optimize_for_in (optimize functions containing for-in loops) + type: bool default: true + --experimental_profiler (enable all profiler experiments) + type: bool default: true + --watch_ic_patching (profiler considers IC stability) + type: bool default: false + --frame_count (number of stack frames inspected by the profiler) + type: int default: 1 + --self_optimization (primitive functions trigger their own optimization) + type: bool default: false + --direct_self_opt (call recompile stub directly when self-optimizing) + type: bool default: false + --retry_self_opt (re-try self-optimization if it failed) + type: bool default: false + --count_based_interrupts (trigger profiler ticks based on counting instead of timing) + type: bool default: false + --interrupt_at_exit (insert an interrupt check at function exit) + type: bool default: false + --weighted_back_edges (weight back edges by jump distance for interrupt triggering) + type: bool default: false + --interrupt_budget (execution budget before interrupt is triggered) + type: int default: 5900 + --type_info_threshold (percentage of ICs that must have type info to allow optimization) + type: int default: 15 + --self_opt_count (call count before self-optimization) + type: int default: 130 + --trace_opt_verbose (extra verbose compilation tracing) + type: bool default: false + --debug_code (generate extra code (assertions) for debugging) + type: bool default: false + --code_comments (emit comments in code disassembly) + type: bool default: false + --enable_sse2 (enable use of SSE2 instructions if available) + type: bool default: true + --enable_sse3 (enable use of SSE3 instructions if available) + type: bool default: true + --enable_sse4_1 (enable use of SSE4.1 instructions if available) + type: bool default: true + --enable_cmov (enable use of CMOV instruction if available) + type: bool default: true + --enable_rdtsc (enable use of RDTSC instruction if available) + type: bool default: true + --enable_sahf (enable use of SAHF instruction if available (X64 only)) + type: bool default: true + --enable_vfp3 (enable use of VFP3 instructions if available - this implies enabling ARMv7 instructions (ARM only)) + type: bool default: true + --enable_armv7 (enable use of ARMv7 instructions if available (ARM only)) + type: bool default: true + --enable_fpu (enable use of MIPS FPU instructions if available (MIPS only)) + type: bool default: true + --expose_natives_as (expose natives in global object) + type: string default: NULL + --expose_debug_as (expose debug in global object) + type: string default: NULL + --expose_gc (expose gc extension) + type: bool default: false + --expose_externalize_string (expose externalize string extension) + type: bool default: false + --stack_trace_limit (number of stack frames to capture) + type: int default: 10 + --builtins_in_stack_traces (show built-in functions in stack traces) + type: bool default: false + --disable_native_files (disable builtin natives files) + type: bool default: false + --inline_new (use fast inline allocation) + type: bool default: true + --stack_trace_on_abort (print a stack trace if an assertion failure occurs) + type: bool default: true + --trace (trace function calls) + type: bool default: false + --mask_constants_with_cookie (use random jit cookie to mask large constants) + type: bool default: true + --lazy (use lazy compilation) + type: bool default: true + --trace_opt (trace lazy optimization) + type: bool default: false + --trace_opt_stats (trace lazy optimization statistics) + type: bool default: false + --opt (use adaptive optimizations) + type: bool default: true + --always_opt (always try to optimize functions) + type: bool default: false + --prepare_always_opt (prepare for turning on always opt) + type: bool default: false + --trace_deopt (trace deoptimization) + type: bool default: false + --min_preparse_length (minimum length for automatic enable preparsing) + type: int default: 1024 + --always_full_compiler (try to use the dedicated run-once backend for all code) + type: bool default: false + --trace_bailout (print reasons for falling back to using the classic V8 backend) + type: bool default: false + --compilation_cache (enable compilation cache) + type: bool default: true + --cache_prototype_transitions (cache prototype transitions) + type: bool default: true + --trace_debug_json (trace debugging JSON request/response) + type: bool default: false + --debugger_auto_break (automatically set the debug break flag when debugger commands are in the queue) + type: bool default: true + --enable_liveedit (enable liveedit experimental feature) + type: bool default: true + --break_on_abort (always cause a debug break before aborting) + type: bool default: true + --stack_size (default size of stack region v8 is allowed to use (in kBytes)) + type: int default: 984 + --max_stack_trace_source_length (maximum length of function source code printed in a stack trace.) + type: int default: 300 + --always_inline_smi_code (always inline smi code in non-opt code) + type: bool default: false + --max_new_space_size (max size of the new generation (in kBytes)) + type: int default: 0 + --max_old_space_size (max size of the old generation (in Mbytes)) + type: int default: 0 + --max_executable_size (max size of executable memory (in Mbytes)) + type: int default: 0 + --gc_global (always perform global GCs) + type: bool default: false + --gc_interval (garbage collect after allocations) + type: int default: -1 + --trace_gc (print one trace line following each garbage collection) + type: bool default: false + --trace_gc_nvp (print one detailed trace line in name=value format after each garbage collection) + type: bool default: false + --print_cumulative_gc_stat (print cumulative GC statistics in name=value format on exit) + type: bool default: false + --trace_gc_verbose (print more details following each garbage collection) + type: bool default: false + --trace_fragmentation (report fragmentation for old pointer and data pages) + type: bool default: false + --collect_maps (garbage collect maps from which no objects can be reached) + type: bool default: true + --flush_code (flush code that we expect not to use again before full gc) + type: bool default: true + --incremental_marking (use incremental marking) + type: bool default: true + --incremental_marking_steps (do incremental marking steps) + type: bool default: true + --trace_incremental_marking (trace progress of the incremental marking) + type: bool default: false + --use_idle_notification (Use idle notification to reduce memory footprint.) + type: bool default: true + --send_idle_notification (Send idle notifcation between stress runs.) + type: bool default: false + --use_ic (use inline caching) + type: bool default: true + --native_code_counters (generate extra code for manipulating stats counters) + type: bool default: false + --always_compact (Perform compaction on every full GC) + type: bool default: false + --lazy_sweeping (Use lazy sweeping for old pointer and data spaces) + type: bool default: true + --never_compact (Never perform compaction on full GC - testing only) + type: bool default: false + --compact_code_space (Compact code space on full non-incremental collections) + type: bool default: true + --cleanup_code_caches_at_gc (Flush inline caches prior to mark compact collection and flush code caches in maps during mark compact cycle.) + type: bool default: true + --random_seed (Default seed for initializing random generator (0, the default, means to use system random).) + type: int default: 0 + --use_verbose_printer (allows verbose printing) + type: bool default: true + --allow_natives_syntax (allow natives syntax) + type: bool default: false + --trace_sim (Trace simulator execution) + type: bool default: false + --check_icache (Check icache flushes in ARM and MIPS simulator) + type: bool default: false + --stop_sim_at (Simulator stop after x number of instructions) + type: int default: 0 + --sim_stack_alignment (Stack alingment in bytes in simulator (4 or 8, 8 is default)) + type: int default: 8 + --trace_exception (print stack trace when throwing exceptions) + type: bool default: false + --preallocate_message_memory (preallocate some memory to build stack traces.) + type: bool default: false + --randomize_hashes (randomize hashes to avoid predictable hash collisions (with snapshots this option cannot override the baked-in seed)) + type: bool default: true + --hash_seed (Fixed seed to use to hash property keys (0 means random)(with snapshots this option cannot override the baked-in seed)) + type: int default: 0 + --preemption (activate a 100ms timer that switches between V8 threads) + type: bool default: false + --regexp_optimization (generate optimized regexp code) + type: bool default: true + --testing_bool_flag (testing_bool_flag) + type: bool default: true + --testing_int_flag (testing_int_flag) + type: int default: 13 + --testing_float_flag (float-flag) + type: float default: 2.500000 + --testing_string_flag (string-flag) + type: string default: Hello, world! + --testing_prng_seed (Seed used for threading test randomness) + type: int default: 42 + --testing_serialization_file (file in which to serialize heap) + type: string default: /tmp/serdes + --help (Print usage message, including flags, on console) + type: bool default: true + --dump_counters (Dump counters on exit) + type: bool default: false + --debugger (Enable JavaScript debugger) + type: bool default: false + --remote_debugger (Connect JavaScript debugger to the debugger agent in another process) + type: bool default: false + --debugger_agent (Enable debugger agent) + type: bool default: false + --debugger_port (Port to use for remote debugging) + type: int default: 5858 + --map_counters (Map counters to a file) + type: string default: + --js_arguments (Pass all remaining arguments to the script. Alias for "--".) + type: arguments default: + --debug_compile_events (Enable debugger compile events) + type: bool default: true + --debug_script_collected_events (Enable debugger script collected events) + type: bool default: true + --gdbjit (enable GDBJIT interface (disables compacting GC)) + type: bool default: false + --gdbjit_full (enable GDBJIT interface for all code objects) + type: bool default: false + --gdbjit_dump (dump elf objects with debug info to disk) + type: bool default: false + --gdbjit_dump_filter (dump only objects containing this substring) + type: string default: + --force_marking_deque_overflows (force overflows of marking deque by reducing it's size to 64 words) + type: bool default: false + --stress_compaction (stress the GC compactor to flush out bugs (implies --force_marking_deque_overflows)) + type: bool default: false + --log (Minimal logging (no API, code, GC, suspect, or handles samples).) + type: bool default: false + --log_all (Log all events to the log file.) + type: bool default: false + --log_runtime (Activate runtime system %Log call.) + type: bool default: false + --log_api (Log API events to the log file.) + type: bool default: false + --log_code (Log code events to the log file without profiling.) + type: bool default: false + --log_gc (Log heap samples on garbage collection for the hp2ps tool.) + type: bool default: false + --log_handles (Log global handle events.) + type: bool default: false + --log_snapshot_positions (log positions of (de)serialized objects in the snapshot.) + type: bool default: false + --log_suspect (Log suspect operations.) + type: bool default: false + --prof (Log statistical profiling information (implies --log-code).) + type: bool default: false + --prof_auto (Used with --prof, starts profiling automatically) + type: bool default: true + --prof_lazy (Used with --prof, only does sampling and logging when profiler is active (implies --noprof_auto).) + type: bool default: false + --prof_browser_mode (Used with --prof, turns on browser-compatible mode for profiling.) + type: bool default: true + --log_regexp (Log regular expression execution.) + type: bool default: false + --sliding_state_window (Update sliding state window counters.) + type: bool default: false + --logfile (Specify the name of the log file.) + type: string default: v8.log + --ll_prof (Enable low-level linux profiler.) + type: bool default: false + +.SH RESOURCES AND DOCUMENTATION + +See the website for documentation http://nodejs.org/ + +Mailing list: http://groups.google.com/group/nodejs + +IRC: irc.freenode.net #node.js diff --git a/node-v0.8.14/doc/pipe.css b/node-v0.8.14/doc/pipe.css new file mode 100644 index 0000000..01b4416 --- /dev/null +++ b/node-v0.8.14/doc/pipe.css @@ -0,0 +1,658 @@ +html { + -webkit-font-smoothing: antialiased; + -webkit-text-stroke: .1px; +} + +body { + background: #46483e; + color: #eee; + font-size: 12px; + line-height: 180%; + font-family: "Lucida Grande", "Lucida Sans Unicode", "Lucida Sans", Verdana, Tahoma, sans-serif; + margin: 0; + padding-top: 40px; + border-top: 6px #8cc84b solid; +} + +body.alt { + background: white; + color: #46483e; +} + +body.int { + padding-top: 49px; +} + +img { + border: 0; +} + +ul { + margin: 0px; + padding: 0px; +} + +@media all and (min-height: 650px) { + #toc { + position: fixed; + } +} + +#toctitle { + display: none; +} + +h1, h2, h3, h4 { + color: #d2d8ba; + font-family: Helvetica, Arial, sans-serif; + margin-top: 2em; + margin-right: 0; + margin-bottom: 10px; + margin-left: 0; + text-transform: uppercase; +} + +h1 { + font-family: Georgia, FreeSerif, Times, serif; + font-size: 30px; + line-height: 36px; + text-transform: none; + color: #669900; + font-weight: normal; + margin: 15px 0 11px; +} + +h2 { + font-size: 12px; + font-weight: normal; +} + +h1 code, h2 code, h3 code, h4 code, +h1 a, h2 a, h3 a, h4 a { + color: inherit; + font-size: inherit; +} + +#intro { + width: 775px; + margin: 0 auto; + text-align: center; + color: #d2d8ba; +} + +#intro p { + width: 680px; + line-height: 180%; + padding-top: 30px; + margin: 0 auto; + font-size: 14px; +} + +#intro.interior #logo { + margin-left: -298px; +} + +#intro p.version { + padding-top: 10px; + font-size: 12px; +} + +#intro .buttons { + height: auto; + overflow: hidden; + _zoom: 1; + width: 300px; + margin: 0 auto; +} + +#intro .button { + font-family: helvetica,arial,sans-serif; + font-size: 12px; + line-height: 36px; + -webkit-text-transform: uppercase; + -moz-text-transform: uppercase; + text-transform: uppercase; + -webkit-border-radius: 2px; + -moz-border-radius: 2px; + border-radius: 2px; + + -webkit-transition: .2s all ease-in-out; + -moz-transition: .2s all ease-in-out; + transition: .2s all ease-in-out; + + margin: 10px 4px; + display: inline-block; + color: #46483e; + background-color: #9a9f8b; + width: 96px; +} + +#intro .forkme { + position: absolute; + top: 0; + right: 0; + border: 0; +} + +#intro .button:hover { + text-decoration: none; + background-color: #aab293; +} + +#intro #docsbutton { + clear: left; +} + +#intro .downloadbutton { + background-color: #8BC84B; + width: 200px; + font-size: 14px; + font-weight: bold; + display: block; + margin: 30px auto 0px auto; +} + +#intro .downloadbutton:hover { + background-color: #73a53e; +} + +#quotes { + text-align: center; + width: 100%; + background-color: #33342d; + margin-top: 40px; + padding-top: 20px; + padding-bottom: 20px; +} + +#quotes h2 { + margin-top: 0; +} + +#quotes ul { + display: block; + width: 775px; + margin: 0 auto; + padding-top: 20px; +} + +#quotes ul li { + display: block; + text-align: left; + width: 180px; + float: left; + padding-right: 15px; + font-size: 11px; +} + +#quotes ul li:last-child { + padding-right: 0; +} + +#quotes ul li p span { + font-size: 10px; +} + +#quotes ul li p { + color: #D2D8BA +} + +#content { + width: 775px; + margin: 0 auto; + overflow: visible; + clear: both; + display: block; +} + +.int #content { + width: 953px; +} + +#column1 { + width: 460px; + float: left; +} + +#content p, +#content ul { + font-size: 14px; + line-height: 24px; +} + +#content ul { + margin-top: 1em; +} + +#content table { + font-size: 14px; + line-height: 24px; + width: 100%; +} + +#download-page #installers { + width: 600px; + display: table; + margin-bottom: 1em; +} + +#download-page #installers ul { + width: auto; + text-align: center; + margin: 0 auto; + display: table-row; + width: 600px; +} + +#download-page #installers ul img { + display: block; + margin: 0 auto; +} + +#download-page #installers ul a { + display: block; + width: 100%; + text-decoration: none; + font-size: 16px; + padding-top: 1em; +} + +#download-page #installers ul a:hover, +#download-page #installers ul a:active { + background: #666; + color: #8cc84b; +} + +#download-page #installers ul li { + width: 33%; + display: table-cell; +} + +#download-page #installers a small { + font-size: 10px; + display: block; + color: #eee; +} + +#download-page #content th { + text-align: left; + width: 33%; +} + +#download-page #content table { + table-collapse: separate; +} + +#download-page #content td, +#download-page #content th { + border: 1px solid #666; +} + +#download-page #content td a { + display: block; + height: 100%; + width: 100%; + text-align: center; +} + +#download-page #content td a:hover, +#download-page #content td a:active { + background: #666; + color: #8cc84b; +} + +#front #content p { + font-size: 12px; +} + +#content h1 + p { + font-size: 18px; + line-height: 30px; + color: #46483e; + font-family: Georgia, FreeSerif, Times, serif; +} + +#column2 { + width: 260px; + float: right; +} + +#column1.interior { + width: 600px; + float: right; + padding-top: 11px; + font-size: 18px; + padding-right: 150px; +} + +#column2.interior { + width: 140px; + float: left; + margin-top: -54px; + overflow: visible; +} + +#column2.interior ul { + margin-left: 0; +} + +#column2.interior li { + list-style-type: none; +} + +#column2.interior li a { + display: block; + padding: 0 0 0 35px; + color: #878b78; + text-transform: uppercase; + text-decoration: none; + font-size: 11px; + line-height: 23px; +} + +#column2.interior li a.home { background: url(http://nodejs.org/images/icons-interior.png) no-repeat -156px 3px; } +#column2.interior li a.download { background: url(http://nodejs.org/images/icons-interior.png) no-repeat -156px -21px; } +#column2.interior li a.about { background: url(http://nodejs.org/images/icons-interior.png) no-repeat -156px -45px; } +#column2.interior li a.npm { background: url(http://nodejs.org/images/icons-interior.png) no-repeat -156px -69px; } +#column2.interior li a.docs { background: url(http://nodejs.org/images/icons-interior.png) no-repeat -156px -93px; } +#column2.interior li a.blog { background: url(http://nodejs.org/images/icons-interior.png) no-repeat -156px -117px; } +#column2.interior li a.community { background: url(http://nodejs.org/images/icons-interior.png) no-repeat -156px -141px; } +#column2.interior li a.logos { background: url(http://nodejs.org/images/icons-interior.png) no-repeat -156px -165px; } +#column2.interior li a.jobs { background: url(http://nodejs.org/images/icons-interior.png) no-repeat -156px -189px; } + +#column2.interior li a.home.current { background-position: 2px 3px; } +#column2.interior li a.download.current { background-position: 2px -21px; } +#column2.interior li a.about.current { background-position: 2px -45px; } +#column2.interior li a.npm.current { background-position: 2px -69px; } +#column2.interior li a.docs.current { background-position: 2px -93px; } +#column2.interior li a.blog.current { background-position: 2px -117px; } +#column2.interior li a.community.current { background-position: 2px -141px; } +#column2.interior li a.logos.current { background-position: 2px -165px; } +#column2.interior li a.jobs.current { background-position: 2px -189px; } + +#column2.interior li a.home:hover { background-position: -331px 3px; } +#column2.interior li a.download:hover { background-position: -331px -21px; } +#column2.interior li a.about:hover { background-position: -331px -45px; } +#column2.interior li a.npm:hover { background-position: -331px -69px; } +#column2.interior li a.docs:hover { background-position: -331px -93px; } +#column2.interior li a.blog:hover { background-position: -331px -117px; } +#column2.interior li a.community:hover { background-position: -331px -141px; } +#column2.interior li a.logos:hover { background-position: -331px -165px; } +#column2.interior li a.jobs:hover { background-position: -331px -189px; } + +#column2.interior li a.current { + color: #8cc84b; + font-weight: bold; +} + +#column2.interior li a:hover { + color: #000000; + text-decoration: none; +} + +#column2.interior li + li { + border-top: 1px solid #c1c7ac; + border-top: 1px solid #65675c; +} +.alt #column2.interior li + li { + border-top: 1px solid #c1c7ac; +} + +#column2.interior p.twitter { + padding-top: 20px; +} + +#column2.interior p.twitter a { + background: url(http://nodejs.org/images/twitter-bird.png) no-repeat 0 4px; + padding-left: 37px; +} + +.row { + padding-top: 10px; + padding-bottom: 10px; +} + +.row + .row { + border-top: 1px solid #626557; +} + +.row h2 { + font-size: 24px; + color: white; + text-transform: none; + font-family: Georgia, FreeSerif, Times, serif; + background: url(http://nodejs.org/images/community-icons.png) no-repeat; + padding-left: 45px; + padding-top: 6px; + padding-bottom: 10px; + margin-top: 10px; +} + +.row h2.github { background-position: left -92px; } +.row h2.mailing { background-position: left -308px; } +.row h2.periodicals { background-position: left -198px; padding-top: 9px; margin-top: 7px; } +.row h2.conferences { background-position: left -522px; } +.row h2.localized { background-position: left -414px; } +.row h2.irc { background-position: left -626px; } +.row h2.installers { background-position: left -522px; } + +.block { + width: 280px; + float: left; +} + +.block + .block { + margin-left: 20px; + width: 300px; +} + +#content .block p { + font-size: 13px; + line-height: 21px; +} + +#explore { + background: url(http://nodejs.org/images/home-icons.png) no-repeat left 17px; +} + +#explore li { + font-size: 12px; + list-style-type: none; + color: #d2d8ba; + line-height: 14px; + padding: 10px 0 10px 40px; + border-top: 1px solid #626557; +} + +#explore li span { +} + +#explore li a.explore { + text-transform: uppercase; +} + +#explore ol.jobs { + padding: 0; +} + +#explore ol.jobs li { + display: inline; + padding: 0; + border: none; +} + +#explore ol.jobs li:after { + content: ', '; +} + +#explore ol.jobs li:last-child:after { + content: ''; +} + +#footer { + width: 942px; + margin: 150px auto 55px auto; + padding: 0; +} + +#footer p { + font-size: 11px; + line-height: 1em; + padding: 0 0 0 195px; + color: #666; + font-family: "Lucida Grande", "Lucida Sans Unicode", "Lucida Sans", Verdana, Tahoma, sans-serif; +} + +#front #footer { + width: 775px; + margin: 50px auto 30px auto; + padding-top: 15px; +} + +#front #footer ul { + margin-right: 0; + padding-right: 0; +} + +#footer a { + text-decoration: none; + border: none; + color: #690; +} + +#footer a:hover { + color: #000; +} + +#front #footer a:hover { + color: #fff; +} + +#footer p a { + border-bottom: 1px dotted #690; + color: #878b78; +} + +#footer ul { + background: url(http://nodejs.org/images/footer-logo.png) left 17px no-repeat; + border-top: 1px solid #626557; + border-color: #90918b; + padding-top: 23px; + padding-left: 195px; + height: 26px; + margin-right: 137px; +} + +.alt #footer ul { + background-image: url(http://nodejs.org/images/footer-logo-alt.png); +} + +#footer ul li { + list-style-type: none; + float: left; + font-size: 12px; + margin: 0 !important; + height: 12px; +} + +#footer ul li a { + margin: 0; + padding: 0 6px 0 0; + display: block; + height: 12px; + line-height: 12px; +} + +#footer ul li + li { + margin-left: 3px; +} + +#footer ul li + li a { + padding: 0 6px 0 6px; + border-left: 1px solid #878b78; +} + +#footer ul li a.twitter { + background: url(http://nodejs.org/images/twitter-bird.png) no-repeat 5px 0px; + padding-left: 25px; +} + +pre, tt, code { + color: #d2d8ba; + font-size: 14px; + line-height: 22px; + font-family: Monaco, Consolas, "Lucida Console", monospace; + margin: 0; padding: 0; +} + +#front pre, #front tt, #front code { + font-size: 12px; + line-height: 22px; +} + +pre { + padding-left: 1em; + margin-left: -1em; + border-left-width: 1px; + border-left-style: solid; + border-left-color: #626557; +} + +.alt pre { + font-size: 14px; + margin-left: 0; + border-left: 2px solid #dadad7; + background-color: #f4f4f2; + color: #46483e; + padding: 1em 1.5em; + line-height: 2em; +} + +.alt code { + color: #996633; +} + +dd { + margin: 1em 0; + margin-left: 1em; +} + +a { + color: #690; + text-decoration: none; +} + +a:hover { + text-decoration: underline; +} + +.alt a { + background-color: #eff2db; + padding: 0 2px; +} + +.alt #intro a, +.alt #footer a { + background-color: transparent; +} + +.highlight { + background: #733; + padding: 0.2em 0; +} +.desktops { + font-size: 12px; +} + +.release { + margin: 0 0 0 2em; +} + +/* simpler clearfix */ +.clearfix:after { + content: "."; + display: block; + height: 0; + clear: both; + visibility: hidden; +} diff --git a/node-v0.8.14/doc/robots.txt b/node-v0.8.14/doc/robots.txt new file mode 100644 index 0000000..1f6fa9b --- /dev/null +++ b/node-v0.8.14/doc/robots.txt @@ -0,0 +1,6 @@ +User-Agent: * +Disallow: /dist/ +Disallow: /docs/ +Allow: /dist/latest/ +Allow: /dist/latest/docs/api/ +Allow: /api/ diff --git a/node-v0.8.14/doc/rss.xml b/node-v0.8.14/doc/rss.xml new file mode 100644 index 0000000..a96aa78 --- /dev/null +++ b/node-v0.8.14/doc/rss.xml @@ -0,0 +1,45 @@ + + + + + Node.js Blog + + http://blog.nodejs.org/ + The Blog about Node.js + <%= new Date().toUTCString() %> + en + weekly + 1 + http://nodejs.org/ + + http://nodejs.org/images/logo-light.png + Node.js + http://blog.nodejs.org/ + + <% + posts.forEach(function(post) { + %> + + <%= post.title %> + http://blog.nodejs.org<%= post.permalink %> + <%= post.date.toUTCString() %> + <%= post.author %> + ]]> + + http://blog.nodejs.org<%= post.permalink %> + ]]> + ]]> + + <% + }); + %> + + diff --git a/node-v0.8.14/doc/sh.css b/node-v0.8.14/doc/sh.css new file mode 100644 index 0000000..7022e19 --- /dev/null +++ b/node-v0.8.14/doc/sh.css @@ -0,0 +1,24 @@ +.sh_sourceCode { + font-weight: normal; + font-style: normal; +} + +.sh_sourceCode .sh_symbol, +.sh_sourceCode .sh_cbracket { + color: #333; +} + +.sh_sourceCode .sh_keyword { + color: #c96; +} + +.sh_sourceCode .sh_string, +.sh_sourceCode .sh_regexp, +.sh_sourceCode .sh_number, +.sh_sourceCode .sh_specialchar { + color: #690; +} + +.sh_sourceCode .sh_comment { + color: #666; +} diff --git a/node-v0.8.14/doc/sh_javascript.min.js b/node-v0.8.14/doc/sh_javascript.min.js new file mode 100644 index 0000000..d12482c --- /dev/null +++ b/node-v0.8.14/doc/sh_javascript.min.js @@ -0,0 +1 @@ +if(!this.sh_languages){this.sh_languages={}}sh_languages.javascript=[[[/\/\/\//g,"sh_comment",1],[/\/\//g,"sh_comment",7],[/\/\*\*/g,"sh_comment",8],[/\/\*/g,"sh_comment",9],[/\b(?:abstract|break|case|catch|class|const|continue|debugger|default|delete|do|else|enum|export|extends|false|final|finally|for|function|goto|if|implements|in|instanceof|interface|native|new|null|private|protected|prototype|public|return|static|super|switch|synchronized|throw|throws|this|transient|true|try|typeof|var|volatile|while|with)\b/g,"sh_keyword",-1],[/(\+\+|--|\)|\])(\s*)(\/=?(?![*\/]))/g,["sh_symbol","sh_normal","sh_symbol"],-1],[/(0x[A-Fa-f0-9]+|(?:[\d]*\.)?[\d]+(?:[eE][+-]?[\d]+)?)(\s*)(\/(?![*\/]))/g,["sh_number","sh_normal","sh_symbol"],-1],[/([A-Za-z$_][A-Za-z0-9$_]*\s*)(\/=?(?![*\/]))/g,["sh_normal","sh_symbol"],-1],[/\/(?:\\.|[^*\\\/])(?:\\.|[^\\\/])*\/[gim]*/g,"sh_regexp",-1],[/\b[+-]?(?:(?:0x[A-Fa-f0-9]+)|(?:(?:[\d]*\.)?[\d]+(?:[eE][+-]?[\d]+)?))u?(?:(?:int(?:8|16|32|64))|L)?\b/g,"sh_number",-1],[/"/g,"sh_string",10],[/'/g,"sh_string",11],[/~|!|%|\^|\*|\(|\)|-|\+|=|\[|\]|\\|:|;|,|\.|\/|\?|&|<|>|\|/g,"sh_symbol",-1],[/\{|\}/g,"sh_cbracket",-1],[/\b(?:Math|Infinity|NaN|undefined|arguments)\b/g,"sh_predef_var",-1],[/\b(?:Array|Boolean|Date|Error|EvalError|Function|Number|Object|RangeError|ReferenceError|RegExp|String|SyntaxError|TypeError|URIError|decodeURI|decodeURIComponent|encodeURI|encodeURIComponent|eval|isFinite|isNaN|parseFloat|parseInt)\b/g,"sh_predef_func",-1],[/(?:[A-Za-z]|_)[A-Za-z0-9_]*(?=[ \t]*\()/g,"sh_function",-1]],[[/$/g,null,-2],[/(?:?)|(?:?)/g,"sh_url",-1],[/<\?xml/g,"sh_preproc",2,1],[//g,"sh_keyword",-1],[/<(?:\/)?[A-Za-z](?:[A-Za-z0-9_:.-]*)/g,"sh_keyword",6,1],[/&(?:[A-Za-z0-9]+);/g,"sh_preproc",-1],[/<(?:\/)?[A-Za-z][A-Za-z0-9]*(?:\/)?>/g,"sh_keyword",-1],[/<(?:\/)?[A-Za-z][A-Za-z0-9]*/g,"sh_keyword",6,1],[/@[A-Za-z]+/g,"sh_type",-1],[/(?:TODO|FIXME|BUG)(?:[:]?)/g,"sh_todo",-1]],[[/\?>/g,"sh_preproc",-2],[/([^=" \t>]+)([ \t]*)(=?)/g,["sh_type","sh_normal","sh_symbol"],-1],[/"/g,"sh_string",3]],[[/\\(?:\\|")/g,null,-1],[/"/g,"sh_string",-2]],[[/>/g,"sh_preproc",-2],[/([^=" \t>]+)([ \t]*)(=?)/g,["sh_type","sh_normal","sh_symbol"],-1],[/"/g,"sh_string",3]],[[/-->/g,"sh_comment",-2],[/ ' + data); + actualData += data; + }); + filter.on('exit', function(code) { + if (code) throw 'Return code was ' + code; + assert.equal(actualData, 'hella warld\n'); + console.log(' Talked to another process successfully'); + }); + echo.on('exit', function(code) { + if (code) throw 'Return code was ' + code; + filter.stdin.end(); + fs.unlinkSync(helloPath); + }); +} + +test1(test2); diff --git a/node-v0.8.14/test/disabled/test-child-process-uid-gid.js b/node-v0.8.14/test/disabled/test-child-process-uid-gid.js new file mode 100644 index 0000000..41c2169 --- /dev/null +++ b/node-v0.8.14/test/disabled/test-child-process-uid-gid.js @@ -0,0 +1,83 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + + + +var common = require('../common'); +var assert = require('assert'); +var spawn = require('child_process').spawn; +var fs = require('fs'); + +var myUid = process.getuid(); +var myGid = process.getgid(); + +if (myUid != 0) { + console.error('must be run as root, otherwise the gid/uid setting will' + + ' fail.'); + process.exit(1); +} + +// get a different user. +// don't care who it is, as long as it's not root +var passwd = fs.readFileSync('/etc/passwd', 'utf8'); +passwd = passwd.trim().split(/\n/); + +for (var i = 0, l = passwd.length; i < l; i++) { + if (passwd[i].charAt(0) === '#') continue; + passwd[i] = passwd[i].split(':'); + var otherName = passwd[i][0]; + var otherUid = +passwd[i][2]; + var otherGid = +passwd[i][3]; + if (otherUid && otherUid !== myUid && + otherGid && otherGid !== myGid && + otherUid > 0) { + break; + } +} +if (!otherUid && !otherGid) throw new Error('failed getting passwd info.'); + +console.error('name, id, gid = %j', [otherName, otherUid, otherGid]); + +var whoNumber = spawn('id', [], { uid: otherUid, gid: otherGid }); +var whoName = spawn('id', [], { uid: otherName, gid: otherGid }); + +whoNumber.stdout.buf = 'byNumber:'; +whoName.stdout.buf = 'byName:'; +whoNumber.stdout.on('data', onData); +whoName.stdout.on('data', onData); +function onData(c) { this.buf += c; } + +whoNumber.on('exit', onExit); +whoName.on('exit', onExit); + +function onExit(code) { + var buf = this.stdout.buf; + console.log(buf); + var expr = new RegExp('^(byName|byNumber):uid=' + + otherUid + + '\\(' + + otherName + + '\\) gid=' + + otherGid + + '\\('); + assert.ok(buf.match(expr), 'uid and gid should match ' + otherName); +} diff --git a/node-v0.8.14/test/disabled/test-dgram-multicast.js b/node-v0.8.14/test/disabled/test-dgram-multicast.js new file mode 100644 index 0000000..8795026 --- /dev/null +++ b/node-v0.8.14/test/disabled/test-dgram-multicast.js @@ -0,0 +1,119 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + + + +var common = require('../common'); +var assert = require('assert'); + +var dgram = require('dgram'), + util = require('util'), + assert = require('assert'), + Buffer = require('buffer').Buffer; +var LOCAL_BROADCAST_HOST = '224.0.0.1'; +var sendMessages = [ + new Buffer('First message to send'), + new Buffer('Second message to send'), + new Buffer('Third message to send'), + new Buffer('Fourth message to send') +]; + +var listenSockets = []; + +var sendSocket = dgram.createSocket('udp4'); + +sendSocket.on('close', function() { + console.error('sendSocket closed'); +}); + +sendSocket.setBroadcast(true); +sendSocket.setMulticastTTL(1); +sendSocket.setMulticastLoopback(true); + +var i = 0; + +sendSocket.sendNext = function() { + var buf = sendMessages[i++]; + + if (!buf) { + try { sendSocket.close(); } catch (e) {} + return; + } + + sendSocket.send(buf, 0, buf.length, + common.PORT, LOCAL_BROADCAST_HOST, function(err) { + if (err) throw err; + console.error('sent %s to %s', util.inspect(buf.toString()), + LOCAL_BROADCAST_HOST + common.PORT); + process.nextTick(sendSocket.sendNext); + }); +}; + +var listener_count = 0; + +function mkListener() { + var receivedMessages = []; + var listenSocket = dgram.createSocket('udp4'); + listenSocket.addMembership(LOCAL_BROADCAST_HOST); + + listenSocket.on('message', function(buf, rinfo) { + console.error('received %s from %j', util.inspect(buf.toString()), rinfo); + receivedMessages.push(buf); + + if (receivedMessages.length == sendMessages.length) { + listenSocket.dropMembership(LOCAL_BROADCAST_HOST); + process.nextTick(function() { // TODO should be changed to below. + // listenSocket.dropMembership(LOCAL_BROADCAST_HOST, function() { + listenSocket.close(); + }); + } + }); + + listenSocket.on('close', function() { + console.error('listenSocket closed -- checking received messages'); + var count = 0; + receivedMessages.forEach(function(buf) { + for (var i = 0; i < sendMessages.length; ++i) { + if (buf.toString() === sendMessages[i].toString()) { + count++; + break; + } + } + }); + console.error('count %d', count); + //assert.strictEqual(count, sendMessages.length); + }); + + listenSocket.on('listening', function() { + listenSockets.push(listenSocket); + if (listenSockets.length == 3) { + sendSocket.sendNext(); + } + }); + + listenSocket.bind(common.PORT); +} + +mkListener(); +mkListener(); +mkListener(); + diff --git a/node-v0.8.14/test/disabled/test-dgram-unix-anon.js b/node-v0.8.14/test/disabled/test-dgram-unix-anon.js new file mode 100644 index 0000000..db14ea1 --- /dev/null +++ b/node-v0.8.14/test/disabled/test-dgram-unix-anon.js @@ -0,0 +1,81 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + + + +var common = require('../common'); +var assert = require('assert'); + +var Buffer = require('buffer').Buffer, + fs = require('fs'), + dgram = require('dgram'), server, client, + server_path = '/tmp/dgram_server_sock', + messages_to_send = [ + new Buffer('First message to send'), + new Buffer('Second message to send'), + new Buffer('Third message to send'), + new Buffer('Fourth message to send') + ], + timer; + +server = dgram.createSocket('unix_dgram'); +server.bind(server_path); +server.messages = []; +server.on('message', function(msg, rinfo) { + console.log('server got: ' + msg); + assert.strictEqual(rinfo.address, ''); // anon client sending + server.messages.push(msg.toString()); + if (server.messages.length === messages_to_send.length) { + server.messages.forEach(function(m, i) { + assert.strictEqual(m, messages_to_send[i].toString()); + }); + server.close(); + client.close(); + } +}); +server.on('listening', function() { + console.log('server is listening'); + client = dgram.createSocket('unix_dgram'); + messages_to_send.forEach(function(m) { + client.send(m, 0, m.length, server_path, function(err, bytes) { + if (err) { + console.log('Caught error in client send.'); + throw err; + } + console.log('client wrote ' + bytes + ' bytes.'); + }); + }); + client.on('close', function() { + if (server.fd === null) { + clearTimeout(timer); + } + }); +}); +server.on('close', function() { + if (client.fd === null) { + clearTimeout(timer); + } +}); + +timer = setTimeout(function() { + throw new Error('Timeout'); +}, 500); diff --git a/node-v0.8.14/test/disabled/test-dgram-unix.js b/node-v0.8.14/test/disabled/test-dgram-unix.js new file mode 100644 index 0000000..4da0525 --- /dev/null +++ b/node-v0.8.14/test/disabled/test-dgram-unix.js @@ -0,0 +1,75 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + + + +var common = require('../common'); +var assert = require('assert'); + +var fs = require('fs'); +var dgram = require('dgram'); + +// TODO use common.tmpDir here +var serverPath = '/tmp/dgram_server_sock'; +var clientPath = '/tmp/dgram_client_sock'; + +var msgToSend = new Buffer('A message to send'); + +var server = dgram.createSocket('unix_dgram'); +server.on('message', function(msg, rinfo) { + console.log('server got: ' + msg + ' from ' + rinfo.address); + assert.strictEqual(rinfo.address, clientPath); + assert.strictEqual(msg.toString(), msgToSend.toString()); + server.send(msg, 0, msg.length, rinfo.address); +}); + +server.on('listening', function() { + console.log('server is listening'); + + var client = dgram.createSocket('unix_dgram'); + + client.on('message', function(msg, rinfo) { + console.log('client got: ' + msg + ' from ' + rinfo.address); + assert.strictEqual(rinfo.address, serverPath); + assert.strictEqual(msg.toString(), msgToSend.toString()); + client.close(); + server.close(); + }); + + client.on('listening', function() { + console.log('client is listening'); + client.send(msgToSend, 0, msgToSend.length, serverPath, + function(err, bytes) { + if (err) { + console.log('Caught error in client send.'); + throw err; + } + console.log('client wrote ' + bytes + ' bytes.'); + assert.strictEqual(bytes, msgToSend.length); + }); + }); + + + client.bind(clientPath); +}); + +server.bind(serverPath); diff --git a/node-v0.8.14/test/disabled/test-dns.js b/node-v0.8.14/test/disabled/test-dns.js new file mode 100644 index 0000000..f53c539 --- /dev/null +++ b/node-v0.8.14/test/disabled/test-dns.js @@ -0,0 +1,231 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + + + +var common = require('../common'); +var assert = require('assert'); + +var dns = require('dns'), + child_process = require('child_process'); + + +// Try resolution without callback + +assert.throws(function() { + dns.resolve('google.com', 'A'); +}); +assert.throws(function() { + dns.resolve('127.0.0.1', 'PTR'); +}); + + +var hosts = ['example.com', + 'example.org', + 'ietf.org', // AAAA + 'google.com', // MX, multiple A records + '_xmpp-client._tcp.google.com', // SRV + 'oakalynhall.co.uk' // Multiple PTR replies +]; + +var records = ['A', 'AAAA', 'MX', 'TXT', 'SRV']; + +var i = hosts.length; +while (i--) { + + var j = records.length; + while (j--) { + var hostCmd = 'dig -t ' + records[j] + ' ' + hosts[i] + + '| grep "^' + hosts[i] + '\\.\\W.*IN.*' + records[j] + '"' + + '| sed -E "s/[[:space:]]+/ /g" | cut -d " " -f 5- ' + + '| sed -e "s/\\.$//"'; + child_process.exec(hostCmd, checkDnsRecord(hosts[i], records[j])); + } +} + +// CNAME should resolve +var resolveCNAME = 'before'; +dns.resolve('labs.nrcmedia.nl', 'CNAME', function(err, result) { + assert.deepEqual(result, ['nrcmedia.nl']); + assert.equal(resolveCNAME, 'beforeafter'); +}); +resolveCNAME += 'after'; + +// CNAME should not resolve +dns.resolve('nrcmedia.nl', 'CNAME', function(err, result) { + assert.ok(err.errno, dns.NODATA); +}); + +function checkDnsRecord(host, record) { + var myHost = host, + myRecord = record; + return function(err, stdout) { + var expected = []; + var footprints = 'before'; + if (stdout.length) + expected = stdout.substr(0, stdout.length - 1).split('\n'); + + switch (myRecord) { + case 'A': + case 'AAAA': + dns.resolve(myHost, myRecord, function(error, result, ttl, cname) { + if (error) result = []; + cmpResults(expected, result, ttl, cname); + + // do reverse lookup check + var ll = result.length; + while (ll--) { + var ip = result[ll]; + var reverseCmd = 'host ' + ip + + '| cut -d " " -f 5-' + + '| sed -e "s/\\.$//"'; + + child_process.exec(reverseCmd, checkReverse(ip)); + } + assert.equal(footprints, 'beforeafter'); + }); + break; + case 'MX': + dns.resolve(myHost, myRecord, function(error, result, ttl, cname) { + if (error) result = []; + + var strResult = []; + var ll = result.length; + while (ll--) { + strResult.push(result[ll].priority + ' ' + result[ll].exchange); + } + cmpResults(expected, strResult, ttl, cname); + assert.equal(footprints, 'beforeafter'); + }); + break; + case 'TXT': + dns.resolve(myHost, myRecord, function(error, result, ttl, cname) { + if (error) result = []; + + var strResult = []; + var ll = result.length; + while (ll--) { + strResult.push('"' + result[ll] + '"'); + } + cmpResults(expected, strResult, ttl, cname); + assert.equal(footprints, 'beforeafter'); + }); + break; + case 'SRV': + dns.resolve(myHost, myRecord, function(error, result, ttl, cname) { + if (error) result = []; + + var strResult = []; + var ll = result.length; + while (ll--) { + strResult.push(result[ll].priority + ' ' + + result[ll].weight + ' ' + + result[ll].port + ' ' + + result[ll].name); + } + cmpResults(expected, strResult, ttl, cname); + assert.equal(footprints, 'beforeafter'); + }); + break; + } + footprints += 'after'; + } +} + +function checkReverse(ip) { + var myIp = ip; + + return function(errr, stdout) { + var expected = stdout.substr(0, stdout.length - 1).split('\n'); + + var reversing = dns.reverse(myIp, function(error, domains, ttl, cname) { + if (error) domains = []; + cmpResults(expected, domains, ttl, cname); + }); + } +} + +function cmpResults(expected, result, ttl, cname) { + if (expected.length != result.length) { + if (expected.length == 1 && + expected[0] == '3(NXDOMAIN)' && + result.length == 0) { + // it's ok, dig returns NXDOMAIN, while dns module returns nothing + } else { + console.log('---WARNING---\nexpected ' + expected + + '\nresult ' + result + '\n-------------'); + } + return; + } + expected.sort(); + result.sort(); + + var ll = expected.length; + while (ll--) { + assert.equal(result[ll], expected[ll]); + console.log('Result ' + result[ll] + + ' was equal to expected ' + expected[ll]); + } +} + +// #1164 +var getHostByName = 'before'; +dns.getHostByName('localhost', function() { + assert.equal(getHostByName, 'beforeafter'); +}); +getHostByName += 'after'; + +var getHostByAddr = 'before'; +dns.getHostByAddr('127.0.0.1', function() { + assert.equal(getHostByAddr, 'beforeafter'); +}); +getHostByAddr += 'after'; + +var lookupEmpty = 'before'; +dns.lookup('', function() { + assert.equal(lookupEmpty, 'beforeafter'); +}); +lookupEmpty += 'after'; + +var lookupIp = 'before'; +dns.lookup('127.0.0.1', function() { + assert.equal(lookupIp, 'beforeafter'); +}); +lookupIp += 'after'; + +var lookupIp4 = 'before'; +dns.lookup('127.0.0.1', 4, function() { + assert.equal(lookupIp4, 'beforeafter'); +}); +lookupIp4 += 'after'; + +var lookupIp6 = 'before'; +dns.lookup('ietf.org', 6, function() { + assert.equal(lookupIp6, 'beforeafter'); +}); +lookupIp6 += 'after'; + +var lookupLocal = 'before'; +dns.lookup('localhost', function() { + assert.equal(lookupLocal, 'beforeafter'); +}); +lookupLocal += 'after'; diff --git a/node-v0.8.14/test/disabled/test-eio-race3.js b/node-v0.8.14/test/disabled/test-eio-race3.js new file mode 100644 index 0000000..eb76fa7 --- /dev/null +++ b/node-v0.8.14/test/disabled/test-eio-race3.js @@ -0,0 +1,43 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + + + +/* XXX Can this test be modified to not call the now-removed wait()? */ + +var common = require('../common'); +var assert = require('assert'); + + +console.log('first stat ...'); + +fs.stat(__filename) + .addCallback(function(stats) { + console.log('second stat ...'); + fs.stat(__filename) + .timeout(1000) + .wait(); + console.log('test passed'); + }) + .addErrback(function() { + throw new Exception(); + }); diff --git a/node-v0.8.14/test/disabled/test-fs-sendfile.js b/node-v0.8.14/test/disabled/test-fs-sendfile.js new file mode 100644 index 0000000..44169bd --- /dev/null +++ b/node-v0.8.14/test/disabled/test-fs-sendfile.js @@ -0,0 +1,52 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + + + +var common = require('../common'); +var assert = require('assert'); + +var net = require('net'); +var util = require('util'); +var x = path.join(common.fixturesDir, 'x.txt'); +var expected = 'xyz'; + +var server = net.createServer(function(socket) { + socket.on('receive', function(data) { + found = data; + client.close(); + socket.close(); + server.close(); + assert.equal(expected, found); + }); +}); +server.listen(common.PORT); + +var client = net.createConnection(common.PORT); +client.on('connect', function() { + fs.open(x, 'r').addCallback(function(fd) { + fs.sendfile(client.fd, fd, 0, expected.length) + .addCallback(function(size) { + assert.equal(expected.length, size); + }); + }); +}); diff --git a/node-v0.8.14/test/disabled/test-http-agent2.js b/node-v0.8.14/test/disabled/test-http-agent2.js new file mode 100644 index 0000000..dc41dbd --- /dev/null +++ b/node-v0.8.14/test/disabled/test-http-agent2.js @@ -0,0 +1,87 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + + + +var common = require('../common'); +var assert = require('assert'); +var http = require('http'); + +var reqEndCount = 0; + +var server = http.Server(function(req, res) { + res.writeHead(200); + res.end('hello world\n'); + + var buffer = ''; + + req.setEncoding('utf8'); + + req.on('data', function(s) { + buffer += s; + }); + + req.on('end', function() { + reqEndCount++; + assert.equal(body, buffer); + }); +}); + +var responses = 0; +var N = 10; +var M = 10; + +var body = ''; +for (var i = 0; i < 1000; i++) { + body += 'hello world'; +} + +var options = { + port: common.PORT, + path: '/', + method: 'PUT' +}; + +server.listen(common.PORT, function() { + for (var i = 0; i < N; i++) { + setTimeout(function() { + for (var j = 0; j < M; j++) { + + var req = http.request(options, function(res) { + console.log(res.statusCode); + if (++responses == N * M) server.close(); + }).on('error', function(e) { + console.log(e.message); + process.exit(1); + }); + + req.end(body); + } + }, i); + } +}); + + +process.on('exit', function() { + assert.equal(N * M, responses); + assert.equal(N * M, reqEndCount); +}); diff --git a/node-v0.8.14/test/disabled/test-http-big-proxy-responses.js b/node-v0.8.14/test/disabled/test-http-big-proxy-responses.js new file mode 100644 index 0000000..bac0ddf --- /dev/null +++ b/node-v0.8.14/test/disabled/test-http-big-proxy-responses.js @@ -0,0 +1,135 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + + + +var common = require('../common'); +var assert = require('assert'); +var util = require('util'), + fs = require('fs'), + http = require('http'), + url = require('url'); + +var chunk = '01234567890123456789'; + +// Produce a very large response. +var chargen = http.createServer(function(req, res) { + var len = parseInt(req.headers['x-len'], 10); + assert.ok(len > 0); + res.writeHead(200, {'transfer-encoding': 'chunked'}); + for (var i = 0; i < len; i++) { + if (i % 1000 == 0) common.print(','); + res.write(chunk); + } + res.end(); +}); +chargen.listen(9000, ready); + +// Proxy to the chargen server. +var proxy = http.createServer(function(req, res) { + var len = parseInt(req.headers['x-len'], 10); + assert.ok(len > 0); + + var sent = 0; + + + function onError(e) { + console.log('proxy client error. sent ' + sent); + throw e; + } + + var proxy_req = http.request({ + host: 'localhost', + port: 9000, + method: req.method, + path: req.url, + headers: req.headers + }, function(proxy_res) { + res.writeHead(proxy_res.statusCode, proxy_res.headers); + + var count = 0; + + proxy_res.on('data', function(d) { + if (count++ % 1000 == 0) common.print('.'); + res.write(d); + sent += d.length; + assert.ok(sent <= (len * chunk.length)); + }); + + proxy_res.on('end', function() { + res.end(); + }); + + }); + proxy_req.on('error', onError); + proxy_req.end(); +}); +proxy.listen(9001, ready); + +var done = false; + +function call_chargen(list) { + if (list.length > 0) { + var len = list.shift(); + + common.debug('calling chargen for ' + len + ' chunks.'); + + var recved = 0; + + var req = http.request({ + port: 9001, + host: 'localhost', + path: '/', + headers: {'x-len': len} + }, function(res) { + + res.on('data', function(d) { + recved += d.length; + assert.ok(recved <= (len * chunk.length)); + }); + + res.on('end', function() { + assert.ok(recved <= (len * chunk.length)); + common.debug('end for ' + len + ' chunks.'); + call_chargen(list); + }); + + }); + req.end(); + + } else { + console.log('End of list. closing servers'); + proxy.close(); + chargen.close(); + done = true; + } +} + +var serversRunning = 0; +function ready() { + if (++serversRunning < 2) return; + call_chargen([100, 1000, 10000, 100000, 1000000]); +} + +process.on('exit', function() { + assert.ok(done); +}); diff --git a/node-v0.8.14/test/disabled/test-http-default-port.js b/node-v0.8.14/test/disabled/test-http-default-port.js new file mode 100644 index 0000000..ec7f69f --- /dev/null +++ b/node-v0.8.14/test/disabled/test-http-default-port.js @@ -0,0 +1,68 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + + + +// This must be run as root. + +var common = require('../common'); +var http = require('http'), + https = require('https'), + PORT = 80, + SSLPORT = 443, + assert = require('assert'), + hostExpect = 'localhost', + fs = require('fs'), + path = require('path'), + fixtures = path.resolve(__dirname, '../fixtures/keys'), + options = { + key: fs.readFileSync(fixtures + '/agent1-key.pem'), + cert: fs.readFileSync(fixtures + '/agent1-cert.pem') + }; + +http.createServer(function(req, res) { + console.error(req.headers); + assert.equal(req.headers.host, hostExpect); + res.writeHead(200); + res.end('ok'); + this.close(); +}).listen(PORT); + +https.createServer(options, function(req, res) { + console.error(req.headers); + assert.equal(req.headers.host, hostExpect); + res.writeHead(200); + res.end('ok'); + this.close(); +}).listen(SSLPORT); + +http + .get({ host: 'localhost', + port: PORT, + headers: { 'x-port': PORT } }) + .on('response', function(res) {}); + +https + .get({ host: 'localhost', + port: SSLPORT, + headers: { 'x-port': SSLPORT } }) + .on('response', function(res) {}); diff --git a/node-v0.8.14/test/disabled/test-http-head-request.js b/node-v0.8.14/test/disabled/test-http-head-request.js new file mode 100644 index 0000000..226d8e8 --- /dev/null +++ b/node-v0.8.14/test/disabled/test-http-head-request.js @@ -0,0 +1,67 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + + + +var common = require('../common'); +var assert = require('assert'); + +var assert = require('assert'); +var http = require('http'); +var util = require('util'); + +var body = 'hello world'; + +var server = http.createServer(function(req, res) { + res.writeHeader(200, + {'Content-Length': body.length.toString(), + 'Content-Type': 'text/plain' + }); + console.log('method: ' + req.method); + if (req.method != 'HEAD') res.write(body); + res.end(); +}); +server.listen(common.PORT); + +var gotEnd = false; + +server.on('listening', function() { + var request = http.request({ + port: common.PORT, + method: 'HEAD', + path: '/' + }, function(response) { + console.log('got response'); + response.on('data', function() { + process.exit(2); + }); + response.on('end', function() { + process.exit(0); + }); + }); + request.end(); +}); + +//give a bit of time for the server to respond before we check it +setTimeout(function() { + process.exit(1); +}, 2000); diff --git a/node-v0.8.14/test/disabled/test-http-stress.js b/node-v0.8.14/test/disabled/test-http-stress.js new file mode 100644 index 0000000..875c840 --- /dev/null +++ b/node-v0.8.14/test/disabled/test-http-stress.js @@ -0,0 +1,66 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + + + +var common = require('../common'); +var assert = require('assert'); + +var http = require('http'); + +var request_count = 1000; +var body = '{"ok": true}'; + +var server = http.createServer(function(req, res) { + res.writeHead(200, {'Content-Type': 'text/javascript'}); + res.write(body); + res.end(); +}); +server.listen(common.PORT); + +var requests_ok = 0; +var requests_complete = 0; + +server.on('listening', function() { + for (var i = 0; i < request_count; i++) { + http.cat('http://localhost:' + common.PORT + '/', 'utf8', + function(err, content) { + requests_complete++; + if (err) { + common.print('-'); + } else { + assert.equal(body, content); + common.print('.'); + requests_ok++; + } + if (requests_complete == request_count) { + console.log('\nrequests ok: ' + requests_ok); + server.close(); + } + }); + } +}); + +process.on('exit', function() { + assert.equal(request_count, requests_complete); + assert.equal(request_count, requests_ok); +}); diff --git a/node-v0.8.14/test/disabled/test-http-tls.js b/node-v0.8.14/test/disabled/test-http-tls.js new file mode 100644 index 0000000..7ea084f --- /dev/null +++ b/node-v0.8.14/test/disabled/test-http-tls.js @@ -0,0 +1,178 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + + + +var common = require('../common'); +var assert = require('assert'); + +var net = require('net'); +var http = require('http'); +var url = require('url'); +var qs = require('querystring'); +var fs = require('fs'); + +var have_openssl; +try { + var crypto = require('crypto'); + var dummy_server = http.createServer(function() {}); + dummy_server.setSecure(); + have_openssl = true; +} catch (e) { + have_openssl = false; + console.log('Not compiled with OPENSSL support.'); + process.exit(); +} + +var request_number = 0; +var requests_sent = 0; +var server_response = ''; +var client_got_eof = false; +var caPem = fs.readFileSync(common.fixturesDir + '/test_ca.pem', 'ascii'); +var certPem = fs.readFileSync(common.fixturesDir + '/test_cert.pem', 'ascii'); +var keyPem = fs.readFileSync(common.fixturesDir + '/test_key.pem', 'ascii'); + +try { + var credentials = crypto.createCredentials( + { key: keyPem, + cert: certPem, + ca: caPem + }); +} catch (e) { + console.log('Not compiled with OPENSSL support.'); + process.exit(); +} + + +var https_server = http.createServer(function(req, res) { + res.id = request_number; + req.id = request_number++; + + var verified = res.connection.verifyPeer(); + var peerDN = JSON.stringify(req.connection.getPeerCertificate()); + assert.equal(verified, true); + assert.equal(peerDN, + '{"subject":"/C=UK/ST=Acknack Ltd/L=Rhys Jones' + + '/O=node.js/OU=Test TLS Certificate/CN=localhost",' + + '"issuer":"/C=UK/ST=Acknack Ltd/L=Rhys Jones/O=node.js' + + '/OU=Test TLS Certificate/CN=localhost",' + + '"valid_from":"Nov 11 09:52:22 2009 GMT",' + + '"valid_to":"Nov 6 09:52:22 2029 GMT",' + + '"fingerprint":"2A:7A:C2:DD:E5:F9:CC:53:72:35:99:7A:02:' + + '5A:71:38:52:EC:8A:DF"}'); + + if (req.id == 0) { + assert.equal('GET', req.method); + assert.equal('/hello', url.parse(req.url).pathname); + assert.equal('world', qs.parse(url.parse(req.url).query).hello); + assert.equal('b==ar', qs.parse(url.parse(req.url).query).foo); + } + + if (req.id == 1) { + assert.equal('POST', req.method); + assert.equal('/quit', url.parse(req.url).pathname); + } + + if (req.id == 2) { + assert.equal('foo', req.headers['x-x']); + } + + if (req.id == 3) { + assert.equal('bar', req.headers['x-x']); + this.close(); + //console.log('server closed'); + } + setTimeout(function() { + res.writeHead(200, {'Content-Type': 'text/plain'}); + res.write(url.parse(req.url).pathname); + res.end(); + }, 1); + +}); +https_server.setSecure(credentials); +https_server.listen(common.PORT); + +https_server.on('listening', function() { + var c = net.createConnection(common.PORT); + + c.setEncoding('utf8'); + + c.on('connect', function() { + c.setSecure(credentials); + }); + + c.on('secure', function() { + var verified = c.verifyPeer(); + var peerDN = JSON.stringify(c.getPeerCertificate()); + assert.equal(verified, true); + assert.equal(peerDN, + '{"subject":"/C=UK/ST=Acknack Ltd/L=Rhys Jones' + + '/O=node.js/OU=Test TLS Certificate/CN=localhost",' + + '"issuer":"/C=UK/ST=Acknack Ltd/L=Rhys Jones/O=node.js' + + '/OU=Test TLS Certificate/CN=localhost",' + + '"valid_from":"Nov 11 09:52:22 2009 GMT",' + + '"valid_to":"Nov 6 09:52:22 2029 GMT",' + + '"fingerprint":"2A:7A:C2:DD:E5:F9:CC:53:72:35:99:7A:02:' + + '5A:71:38:52:EC:8A:DF"}'); + c.write('GET /hello?hello=world&foo=b==ar HTTP/1.1\r\n\r\n'); + requests_sent += 1; + }); + + c.on('data', function(chunk) { + server_response += chunk; + + if (requests_sent == 1) { + c.write('POST /quit HTTP/1.1\r\n\r\n'); + requests_sent += 1; + } + + if (requests_sent == 2) { + c.write('GET / HTTP/1.1\r\nX-X: foo\r\n\r\n' + + 'GET / HTTP/1.1\r\nX-X: bar\r\n\r\n'); + c.end(); + assert.equal(c.readyState, 'readOnly'); + requests_sent += 2; + } + + }); + + c.on('end', function() { + client_got_eof = true; + }); + + c.on('close', function() { + assert.equal(c.readyState, 'closed'); + }); +}); + +process.on('exit', function() { + assert.equal(4, request_number); + assert.equal(4, requests_sent); + + var hello = new RegExp('/hello'); + assert.equal(true, hello.exec(server_response) != null); + + var quit = new RegExp('/quit'); + assert.equal(true, quit.exec(server_response) != null); + + assert.equal(true, client_got_eof); +}); diff --git a/node-v0.8.14/test/disabled/test-https-loop-to-google.js b/node-v0.8.14/test/disabled/test-https-loop-to-google.js new file mode 100644 index 0000000..112902b --- /dev/null +++ b/node-v0.8.14/test/disabled/test-https-loop-to-google.js @@ -0,0 +1,56 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + + + +// Failing test for https + +// Will fail with "socket hang up" for 4 out of 10 requests +// Tested on node 0.5.0-pre commit 9851574 + + +var common = require('../common'); +var https = require('https'); + +for (var i = 0; i < 10; ++i) +{ + https.get( + { + host: 'www.google.com', + path: '/accounts/o8/id', + port: 443 + }, function(res) + { + var data = ''; + res.on('data', function(chunk) + { + data += chunk; + }); + res.on('end', function() + { + console.log(res.statusCode); + }); + }).on('error', function(error) + { + console.log(error); + }); +} diff --git a/node-v0.8.14/test/disabled/test-idle-watcher.js b/node-v0.8.14/test/disabled/test-idle-watcher.js new file mode 100644 index 0000000..4a46bd0 --- /dev/null +++ b/node-v0.8.14/test/disabled/test-idle-watcher.js @@ -0,0 +1,39 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + + + +var common = require('../common'); +var assert = require('assert'); + +var complete = false; +var idle = new process.IdleWatcher(); +idle.callback = function() { + complete = true; + idle.stop(); +}; +idle.setPriority(process.EVMAXPRI); +idle.start(); + +process.on('exit', function() { + assert.ok(complete); +}); diff --git a/node-v0.8.14/test/disabled/test-net-fd-passing.js b/node-v0.8.14/test/disabled/test-net-fd-passing.js new file mode 100644 index 0000000..55b214c --- /dev/null +++ b/node-v0.8.14/test/disabled/test-net-fd-passing.js @@ -0,0 +1,94 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + + + +var common = require('../common'); +var assert = require('assert'); +var net = require('net'); + +var tests_run = 0; + +function fdPassingTest(path, port) { + var greeting = 'howdy'; + var message = 'beep toot'; + var expectedData = ['[greeting] ' + greeting, '[echo] ' + message]; + + var receiverArgs = [common.fixturesDir + '/net-fd-passing-receiver.js', + path, + greeting]; + var receiver = process.createChildProcess(process.ARGV[0], receiverArgs); + + var initializeSender = function() { + var fdHighway = new net.Socket(); + + fdHighway.on('connect', function() { + var sender = net.createServer(function(socket) { + fdHighway.sendFD(socket); + socket.flush(); + socket.forceClose(); // want to close() the fd, not shutdown() + }); + + sender.on('listening', function() { + var client = net.createConnection(port); + + client.on('connect', function() { + client.write(message); + }); + + client.on('data', function(data) { + assert.equal(expectedData[0], data); + if (expectedData.length > 1) { + expectedData.shift(); + } + else { + // time to shut down + fdHighway.close(); + sender.close(); + client.forceClose(); + } + }); + }); + + tests_run += 1; + sender.listen(port); + }); + + fdHighway.connect(path); + + + }; + + receiver.on('output', function(data) { + var initialized = false; + if ((! initialized) && (data == 'ready')) { + initializeSender(); + initialized = true; + } + }); +} + +fdPassingTest('/tmp/passing-socket-test', 31075); + +process.on('exit', function() { + assert.equal(1, tests_run); +}); diff --git a/node-v0.8.14/test/disabled/test-net-tls-pummel.js b/node-v0.8.14/test/disabled/test-net-tls-pummel.js new file mode 100644 index 0000000..178c275 --- /dev/null +++ b/node-v0.8.14/test/disabled/test-net-tls-pummel.js @@ -0,0 +1,150 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + + + +var common = require('../common'); +var assert = require('assert'); + +var net = require('net'); +var fs = require('fs'); + +var tests_run = 0; + +function tlsTest(port, host, caPem, keyPem, certPem) { + var N = 50; + var count = 0; + var sent_final_ping = false; + + var server = net.createServer(function(socket) { + assert.equal(true, socket.remoteAddress !== null); + assert.equal(true, socket.remoteAddress !== undefined); + if (host === '127.0.0.1') + assert.equal(socket.remoteAddress, '127.0.0.1'); + else if (host == null) + assert.equal(socket.remoteAddress, '127.0.0.1'); + + socket.setEncoding('utf8'); + socket.setNoDelay(); + socket.timeout = 0; + + socket.on('data', function(data) { + var verified = socket.verifyPeer(); + var peerDN = socket.getPeerCertificate('DNstring'); + assert.equal(verified, 1); + assert.equal(peerDN, + 'C=UK,ST=Acknack Ltd,L=Rhys Jones,O=node.js,' + + 'OU=Test TLS Certificate,CN=localhost'); + console.log('server got: ' + JSON.stringify(data)); + assert.equal('open', socket.readyState); + assert.equal(true, count <= N); + if (/PING/.exec(data)) { + socket.write('PONG'); + } + }); + + socket.on('end', function() { + assert.equal('writeOnly', socket.readyState); + socket.end(); + }); + + socket.on('close', function(had_error) { + assert.equal(false, had_error); + assert.equal('closed', socket.readyState); + socket.server.close(); + }); + }); + + server.setSecure('X509_PEM', caPem, 0, keyPem, certPem); + server.listen(port, host); + + var client = net.createConnection(port, host); + + client.setEncoding('utf8'); + client.setSecure('X509_PEM', caPem, 0, keyPem, caPem); + + client.on('connect', function() { + assert.equal('open', client.readyState); + var verified = client.verifyPeer(); + var peerDN = client.getPeerCertificate('DNstring'); + assert.equal(verified, 1); + assert.equal(peerDN, + 'C=UK,ST=Acknack Ltd,L=Rhys Jones,O=node.js,' + + 'OU=Test TLS Certificate,CN=localhost'); + client.write('PING'); + }); + + client.on('data', function(data) { + assert.equal('PONG', data); + count += 1; + + console.log('client got PONG'); + + if (sent_final_ping) { + assert.equal('readOnly', client.readyState); + return; + } else { + assert.equal('open', client.readyState); + } + + if (count < N) { + client.write('PING'); + } else { + sent_final_ping = true; + client.write('PING'); + client.end(); + } + }); + + client.on('close', function() { + assert.equal(N + 1, count); + assert.equal(true, sent_final_ping); + tests_run += 1; + }); +} + + +var have_tls; +try { + var dummy_server = net.createServer(); + dummy_server.setSecure(); + have_tls = true; +} catch (e) { + have_tls = false; +} + +if (have_tls) { + var caPem = fs.readFileSync(common.fixturesDir + '/test_ca.pem'); + var certPem = fs.readFileSync(common.fixturesDir + '/test_cert.pem'); + var keyPem = fs.readFileSync(common.fixturesDir + '/test_key.pem'); + + /* All are run at once, so run on different ports */ + tlsTest(common.PORT, 'localhost', caPem, keyPem, certPem); + tlsTest(common.PORT + 1, null, caPem, keyPem, certPem); + + process.on('exit', function() { + assert.equal(2, tests_run); + }); +} else { + console.log('Not compiled with TLS support -- skipping test'); + process.exit(0); +} diff --git a/node-v0.8.14/test/disabled/test-net-tls.js b/node-v0.8.14/test/disabled/test-net-tls.js new file mode 100644 index 0000000..48344ba --- /dev/null +++ b/node-v0.8.14/test/disabled/test-net-tls.js @@ -0,0 +1,135 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + + + +var common = require('../common'); +var assert = require('assert'); +var fs = require('fs'); +var net = require('net'); + +var have_openssl; +try { + var crypto = require('crypto'); + have_openssl = true; +} catch (e) { + have_openssl = false; + console.log('Not compiled with OPENSSL support.'); + process.exit(); +} + +var caPem = fs.readFileSync(common.fixturesDir + '/test_ca.pem', 'ascii'); +var certPem = fs.readFileSync(common.fixturesDir + '/test_cert.pem', 'ascii'); +var keyPem = fs.readFileSync(common.fixturesDir + '/test_key.pem', 'ascii'); + +try { + var credentials = crypto.createCredentials( + { key: keyPem, + cert: certPem, + ca: caPem + }); +} catch (e) { + console.log('Not compiled with OPENSSL support.'); + process.exit(); +} + +var testData = 'TEST123'; +var serverData = ''; +var clientData = ''; +var gotSecureServer = false; +var gotSecureClient = false; + +var secureServer = net.createServer(function(connection) { + var self = this; + connection.setSecure(credentials); + connection.setEncoding('UTF8'); + + connection.on('secure', function() { + gotSecureServer = true; + var verified = connection.verifyPeer(); + var peerDN = JSON.stringify(connection.getPeerCertificate()); + assert.equal(verified, true); + assert.equal(peerDN, + '{"subject":"/C=UK/ST=Acknack Ltd/L=Rhys Jones' + + '/O=node.js/OU=Test TLS Certificate/CN=localhost",' + + '"issuer":"/C=UK/ST=Acknack Ltd/L=Rhys Jones/O=node.js' + + '/OU=Test TLS Certificate/CN=localhost",' + + '"valid_from":"Nov 11 09:52:22 2009 GMT",' + + '"valid_to":"Nov 6 09:52:22 2029 GMT",' + + '"fingerprint":"2A:7A:C2:DD:E5:F9:CC:53:72:35:99:7A:02:' + + '5A:71:38:52:EC:8A:DF"}'); + + }); + + connection.on('data', function(chunk) { + serverData += chunk; + connection.write(chunk); + }); + + connection.on('end', function() { + assert.equal(serverData, testData); + connection.end(); + self.close(); + }); +}); +secureServer.listen(common.PORT); + +secureServer.on('listening', function() { + var secureClient = net.createConnection(common.PORT); + + secureClient.setEncoding('UTF8'); + secureClient.on('connect', function() { + secureClient.setSecure(credentials); + }); + + secureClient.on('secure', function() { + gotSecureClient = true; + var verified = secureClient.verifyPeer(); + var peerDN = JSON.stringify(secureClient.getPeerCertificate()); + assert.equal(verified, true); + assert.equal(peerDN, + '{"subject":"/C=UK/ST=Acknack Ltd/L=Rhys Jones' + + '/O=node.js/OU=Test TLS Certificate/CN=localhost",' + + '"issuer":"/C=UK/ST=Acknack Ltd/L=Rhys Jones/O=node.js' + + '/OU=Test TLS Certificate/CN=localhost",' + + '"valid_from":"Nov 11 09:52:22 2009 GMT",' + + '"valid_to":"Nov 6 09:52:22 2029 GMT",' + + '"fingerprint":"2A:7A:C2:DD:E5:F9:CC:53:72:35:99:7A:02:' + + '5A:71:38:52:EC:8A:DF"}'); + + secureClient.write(testData); + secureClient.end(); + }); + + secureClient.on('data', function(chunk) { + clientData += chunk; + }); + + secureClient.on('end', function() { + assert.equal(clientData, testData); + }); +}); + +process.on('exit', function() { + assert.ok(gotSecureServer, 'Did not get secure event for server'); + assert.ok(gotSecureClient, 'Did not get secure event for client'); +}); diff --git a/node-v0.8.14/test/disabled/test-process-title.js b/node-v0.8.14/test/disabled/test-process-title.js new file mode 100644 index 0000000..591c949 --- /dev/null +++ b/node-v0.8.14/test/disabled/test-process-title.js @@ -0,0 +1,63 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + + + +var common = require('../common'); +var assert = require('assert'); +var spawn = require('child_process').spawn; + +if (process.title === '') { + console.log('skipping test -- not implemented for the host platform'); + //return; +} + +// disabled because of two things +// - not tested on linux (can ps show process title on Linux?) +// - unable to verify effect on Darwin/OS X (only avail through GUI tools AFAIK) + +function verifyProcessName(str, callback) { + process.title = str; + var buf = ''; + ps = spawn('ps'); + ps.stdout.setEncoding('utf8'); + ps.stdout.on('data', function(s) { buf += s; }); + ps.on('exit', function(c) { + try { + assert.equal(0, c); + assert.ok(new RegExp(process.pid + ' ', 'm').test(buf)); + assert.ok(new RegExp(str, 'm').test(buf)); + callback(); + } catch (err) { + callback(err); + } + }); +} + +verifyProcessName('3kd023mslkfp--unique-string--sksdf', function(err) { + if (err) throw err; + console.log('title is now %j', process.title); + verifyProcessName('3kd023mslxxx--unique-string--xxx', function(err) { + if (err) throw err; + console.log('title is now %j', process.title); + }); +}); diff --git a/node-v0.8.14/test/disabled/test-readline.js b/node-v0.8.14/test/disabled/test-readline.js new file mode 100644 index 0000000..0c08afe --- /dev/null +++ b/node-v0.8.14/test/disabled/test-readline.js @@ -0,0 +1,136 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + + + +// Can't test this when 'make test' doesn't assign a tty to the stdout. +// Yet another use-case for require('tty').spawn ? +var common = require('../common'); +var assert = require('assert'); +var readline = require('readline'); + +var key = { + xterm: { + home: [27, 91, 72], + end: [27, 91, 70], + metab: [27, 98], + metaf: [27, 102], + metad: [27, 100] + }, + gnome: { + home: [27, 79, 72], + end: [27, 79, 70] + }, + rxvt: { + home: [27, 91, 55], + end: [27, 91, 56] + }, + putty: { + home: [27, 91, 49, 126], + end: [27, 91, 52, 126] + } +}; + +var readlineFakeStream = function() { + var written_bytes = []; + var rl = readline.createInterface( + { fd: 1, + write: function(b) { + written_bytes.push(b); + } + }, + function(text) { + return [[], '']; + }); + rl.written_bytes = written_bytes; + return rl; +}; + +var rl = readlineFakeStream(); +var written_bytes_length, refreshed; + +rl.write('foo'); +assert.equal(3, rl.cursor); +rl.write(key.xterm.home); +assert.equal(0, rl.cursor); +rl.write(key.xterm.end); +assert.equal(3, rl.cursor); +rl.write(key.rxvt.home); +assert.equal(0, rl.cursor); +rl.write(key.rxvt.end); +assert.equal(3, rl.cursor); +rl.write(key.gnome.home); +assert.equal(0, rl.cursor); +rl.write(key.gnome.end); +assert.equal(3, rl.cursor); +rl.write(key.putty.home); +assert.equal(0, rl.cursor); +rl.write(key.putty.end); +assert.equal(3, rl.cursor); + +rl = readlineFakeStream(); +rl.write('foo bar.hop/zoo'); +rl.write(key.xterm.home); +written_bytes_length = rl.written_bytes.length; +rl.write(key.xterm.metaf); +assert.equal(3, rl.cursor); +refreshed = written_bytes_length !== rl.written_bytes.length; +assert.equal(true, refreshed); +rl.write(key.xterm.metaf); +assert.equal(7, rl.cursor); +rl.write(key.xterm.metaf); +assert.equal(11, rl.cursor); +written_bytes_length = rl.written_bytes.length; +rl.write(key.xterm.metaf); +assert.equal(15, rl.cursor); +refreshed = written_bytes_length !== rl.written_bytes.length; +assert.equal(true, refreshed); +written_bytes_length = rl.written_bytes.length; +rl.write(key.xterm.metab); +assert.equal(12, rl.cursor); +refreshed = written_bytes_length !== rl.written_bytes.length; +assert.equal(true, refreshed); +rl.write(key.xterm.metab); +assert.equal(8, rl.cursor); +rl.write(key.xterm.metab); +assert.equal(4, rl.cursor); +written_bytes_length = rl.written_bytes.length; +rl.write(key.xterm.metab); +assert.equal(0, rl.cursor); +refreshed = written_bytes_length !== rl.written_bytes.length; +assert.equal(true, refreshed); + +rl = readlineFakeStream(); +rl.write('foo bar.hop/zoo'); +rl.write(key.xterm.home); +rl.write(key.xterm.metad); +assert.equal(0, rl.cursor); +assert.equal(' bar.hop/zoo', rl.line); +rl.write(key.xterm.metad); +assert.equal(0, rl.cursor); +assert.equal('.hop/zoo', rl.line); +rl.write(key.xterm.metad); +assert.equal(0, rl.cursor); +assert.equal('/zoo', rl.line); +rl.write(key.xterm.metad); +assert.equal(0, rl.cursor); +assert.equal('', rl.line); diff --git a/node-v0.8.14/test/disabled/test-remote-module-loading.js b/node-v0.8.14/test/disabled/test-remote-module-loading.js new file mode 100644 index 0000000..183d3c2 --- /dev/null +++ b/node-v0.8.14/test/disabled/test-remote-module-loading.js @@ -0,0 +1,62 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + + + +var common = require('../common'); +var assert = require('assert'); + +var http = require('http'); +var util = require('util'); +var url = require('url'); +var modulesLoaded = 0; + +var server = http.createServer(function(req, res) { + var body = 'exports.httpPath = function() {' + + 'return ' + JSON.stringify(url.parse(req.url).pathname) + ';' + + '};'; + res.writeHead(200, {'Content-Type': 'text/javascript'}); + res.write(body); + res.end(); +}); +server.listen(common.PORT); + +assert.throws(function() { + var httpModule = require('http://localhost:' + common.PORT + '/moduleA.js'); + assert.equal('/moduleA.js', httpModule.httpPath()); + modulesLoaded++; +}); + +var nodeBinary = process.ARGV[0]; +var cmd = 'NODE_PATH=' + common.libDir + ' ' + nodeBinary + + ' http://localhost:' + common.PORT + '/moduleB.js'; + +util.exec(cmd, function(err, stdout, stderr) { + if (err) throw err; + console.log('success!'); + modulesLoaded++; + server.close(); +}); + +process.on('exit', function() { + assert.equal(1, modulesLoaded); +}); diff --git a/node-v0.8.14/test/disabled/test-sendfd.js b/node-v0.8.14/test/disabled/test-sendfd.js new file mode 100644 index 0000000..7352d79 --- /dev/null +++ b/node-v0.8.14/test/disabled/test-sendfd.js @@ -0,0 +1,149 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + + + +// Test sending and receiving a file descriptor. +// +// This test is pretty complex. It ends up spawning test/fixtures/recvfd.js +// as a child to test desired behavior. What happens is +// +// 1. Create an in-memory pipe via pipe(2). These two file descriptors +// are not visible to any other process, and so make a good test-case +// for sharing. +// 2. Create a a UNIX socket at SOCK_PATH. When a client connects to this +// path, they are sent the write end of the pipe from above. +// 3. The client is sent n JSON representations of the DATA variable, each +// with a different ordinal. We send these delimited by '\n' strings +// so that the receiving end can avoid any coalescing that hapepns +// due to the stream nature of the socket (e.g. '{}{}' is not a valid +// JSON string). +// 4. The child process receives file descriptors and JSON blobs and, +// whenever it has at least one of each, writes a modified JSON blob +// to the FD. The blob is modified to include the child's process ID. +// 5. Once the child process has sent n responses, it closes the write end +// of the pipe, which signals to the parent that there is no more data +// coming. +// 6. The parent listens to the read end of the pipe, accumulating JSON +// blobs (again, delimited by '\n') and verifying that a) the 'pid' +// attribute belongs to the child and b) the 'ord' field has not been +// seen in a response yet. This is intended to ensure that all blobs +// sent out have been relayed back to us. + +var common = require('../common'); +var assert = require('assert'); + +var buffer = require('buffer'); +var child_process = require('child_process'); +var fs = require('fs'); +var net = require('net'); +var netBinding = process.binding('net'); +var path = require('path'); + +var DATA = { + 'ppid' : process.pid, + 'ord' : 0 +}; + +var SOCK_PATH = path.join(__dirname, + '..', + path.basename(__filename, '.js') + '.sock'); + +var logChild = function(d) { + if (typeof d == 'object') { + d = d.toString(); + } + + d.split('\n').forEach(function(l) { + if (l.length > 0) { + common.debug('CHILD: ' + l); + } + }); +}; + +// Create a pipe +// +// We establish a listener on the read end of the pipe so that we can +// validate any data sent back by the child. We send the write end of the +// pipe to the child and close it off in our process. +var pipeFDs = netBinding.pipe(); +assert.equal(pipeFDs.length, 2); + +var seenOrdinals = []; + +var pipeReadStream = new net.Stream(); +pipeReadStream.on('data', function(data) { + data.toString('utf8').trim().split('\n').forEach(function(d) { + var rd = JSON.parse(d); + + assert.equal(rd.pid, cpp); + assert.equal(seenOrdinals.indexOf(rd.ord), -1); + + seenOrdinals.unshift(rd.ord); + }); +}); +pipeReadStream.open(pipeFDs[0]); +pipeReadStream.resume(); + +// Create a UNIX socket at SOCK_PATH and send DATA and the write end +// of the pipe to whoever connects. +// +// We send two messages here, both with the same pipe FD: one string, and +// one buffer. We want to make sure that both datatypes are handled +// correctly. +var srv = net.createServer(function(s) { + var str = JSON.stringify(DATA) + '\n'; + + DATA.ord = DATA.ord + 1; + var buf = new buffer.Buffer(str.length); + buf.write(JSON.stringify(DATA) + '\n', 'utf8'); + + s.write(str, 'utf8', pipeFDs[1]); + if (s.write(buf, pipeFDs[1])) { + netBinding.close(pipeFDs[1]); + } else { + s.on('drain', function() { + netBinding.close(pipeFDs[1]); + }); + } +}); +srv.listen(SOCK_PATH); + +// Spawn a child running test/fixtures/recvfd.js +var cp = child_process.spawn(process.argv[0], + [path.join(common.fixturesDir, 'recvfd.js'), + SOCK_PATH]); + +cp.stdout.on('data', logChild); +cp.stderr.on('data', logChild); + +// When the child exits, clean up and validate its exit status +var cpp = cp.pid; +cp.on('exit', function(code, signal) { + srv.close(); + // fs.unlinkSync(SOCK_PATH); + + assert.equal(code, 0); + assert.equal(seenOrdinals.length, 2); +}); + +// vim:ts=2 sw=2 et diff --git a/node-v0.8.14/test/disabled/test-setuidgid.js b/node-v0.8.14/test/disabled/test-setuidgid.js new file mode 100644 index 0000000..3d33e00 --- /dev/null +++ b/node-v0.8.14/test/disabled/test-setuidgid.js @@ -0,0 +1,46 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + + + +// Requires special privlages +var common = require('../common'); +var assert = require('assert'); + +var oldgid = process.getgid(); +process.setgid('nobody'); +var newgid = process.getgid(); +assert.notEqual(newgid, oldgid, 'gids expected to be different'); + +var olduid = process.getuid(); +process.setuid('nobody'); +var newuid = process.getuid(); +assert.notEqual(newuid, olduid, 'uids expected to be different'); + +try { + process.setuid('nobody1234'); +} catch (e) { + assert.equal(e.message, + 'failed to resolve group', + 'unexpected error message' + ); +} diff --git a/node-v0.8.14/test/disabled/test-tls-large-push.js b/node-v0.8.14/test/disabled/test-tls-large-push.js new file mode 100644 index 0000000..9b168cd --- /dev/null +++ b/node-v0.8.14/test/disabled/test-tls-large-push.js @@ -0,0 +1,87 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + + + +// Server sends a large string. Client counts bytes and pauses every few +// seconds. Makes sure that pause and resume work properly. +var common = require('../common'); +var assert = require('assert'); +var tls = require('tls'); +var fs = require('fs'); + + +var body = ''; + +process.stdout.write('build body...'); +for (var i = 0; i < 10 * 1024 * 1024; i++) { + body += 'hello world\n'; +} +process.stdout.write('done\n'); + + +var options = { + key: fs.readFileSync(common.fixturesDir + '/keys/agent2-key.pem'), + cert: fs.readFileSync(common.fixturesDir + '/keys/agent2-cert.pem') +}; + +var connections = 0; + + +var server = tls.Server(options, function(socket) { + socket.end(body); + connections++; +}); + +var recvCount = 0; + +server.listen(common.PORT, function() { + var client = tls.connect(common.PORT); + + client.on('data', function(d) { + process.stdout.write('.'); + recvCount += d.length; + + /* + client.pause(); + process.nextTick(function () { + client.resume(); + }); + */ + }); + + + client.on('close', function() { + debugger; + console.log('close'); + server.close(); + }); +}); + + + +process.on('exit', function() { + assert.equal(1, connections); + console.log('body.length: %d', body.length); + console.log(' recvCount: %d', recvCount); + assert.equal(body.length, recvCount); +}); diff --git a/node-v0.8.14/test/disabled/test-tls-server.js b/node-v0.8.14/test/disabled/test-tls-server.js new file mode 100644 index 0000000..6450d46 --- /dev/null +++ b/node-v0.8.14/test/disabled/test-tls-server.js @@ -0,0 +1,59 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + + + +// Example of new TLS API. Test with: +// +// $> openssl s_client -connect localhost:12346 \ +// -key test/fixtures/agent.key -cert test/fixtures/agent.crt +// +// $> openssl s_client -connect localhost:12346 +// +var common = require('../common'); +var tls = require('tls'); +var fs = require('fs'); +var join = require('path').join; + +var key = fs.readFileSync(join(common.fixturesDir, 'agent.key')).toString(); +var cert = fs.readFileSync(join(common.fixturesDir, 'agent.crt')).toString(); + +s = tls.Server({ key: key, + cert: cert, + ca: [], + requestCert: true, + rejectUnauthorized: true }); + +s.listen(common.PORT, function() { + console.log('TLS server on 127.0.0.1:%d', common.PORT); +}); + + +s.on('authorized', function(c) { + console.log('authed connection'); + c.end('bye authorized friend.\n'); +}); + +s.on('unauthorized', function(c, e) { + console.log('unauthed connection: %s', e); + c.end('bye unauthorized person.\n'); +}); diff --git a/node-v0.8.14/test/disabled/test-tty-stdio.js b/node-v0.8.14/test/disabled/test-tty-stdio.js new file mode 100644 index 0000000..558f1b1 --- /dev/null +++ b/node-v0.8.14/test/disabled/test-tty-stdio.js @@ -0,0 +1,36 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + + + +// Can't test this when 'make test' doesn't assign a tty to the stdout. +var common = require('../common'); +var assert = require('assert'); +var tty = require('tty'); + +assert.ok(process.stdin instanceof tty.ReadStream); +assert.ok(process.stdin.readable); +assert.ok(!process.stdin.writable); + +assert.ok(process.stdout instanceof tty.WriteStream); +assert.ok(!process.stdout.readable); +assert.ok(process.stdout.writable); diff --git a/node-v0.8.14/test/disabled/tls-client.js b/node-v0.8.14/test/disabled/tls-client.js new file mode 100644 index 0000000..d144603 --- /dev/null +++ b/node-v0.8.14/test/disabled/tls-client.js @@ -0,0 +1,46 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + + + +var common = require('../common'); +var tls = require('tls'); +var fs = require('fs'); + + +// most servers don't require certificates + +var options = { + key: fs.readFileSync(common.fixturesDir + '/keys/agent1-key.pem') +}; + + +var s = tls.connect(443, 'joyent.com', options, function() { + if (!s.authorized) { + console.error('CONNECTED: ' + s.authorizationError); + s.destroy(); + return; + } + s.pipe(process.stdout); + process.openStdin().pipe(s); +}); + diff --git a/node-v0.8.14/test/disabled/tls_client.js b/node-v0.8.14/test/disabled/tls_client.js new file mode 100644 index 0000000..462bceb --- /dev/null +++ b/node-v0.8.14/test/disabled/tls_client.js @@ -0,0 +1,67 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + + + +var common = require('../common'); +var assert = require('assert'); + +var util = require('util'); +var net = require('net'); +var fs = require('fs'); +var crypto = require('crypto'); + +//var client = net.createConnection(4443, 'localhost'); +var client = net.createConnection(443, 'www.microsoft.com'); +//var client = net.createConnection(443, 'www.google.com'); + +var caPem = fs.readFileSync(common.fixturesDir + '/msca.pem'); +//var caPem = fs.readFileSync('ca.pem'); + +try { + var credentials = crypto.createCredentials({ca: caPem}); +} catch (e) { + console.log('Not compiled with OPENSSL support.'); + process.exit(); +} + +client.setEncoding('UTF8'); +client.on('connect', function() { + console.log('client connected.'); + client.setSecure(credentials); +}); + +client.on('secure', function() { + console.log('client secure : ' + JSON.stringify(client.getCipher())); + console.log(JSON.stringify(client.getPeerCertificate())); + console.log('verifyPeer : ' + client.verifyPeer()); + client.write('GET / HTTP/1.0\r\n\r\n'); +}); + +client.on('data', function(chunk) { + common.error(chunk); +}); + +client.on('end', function() { + console.log('client disconnected.'); +}); + diff --git a/node-v0.8.14/test/disabled/tls_server.js b/node-v0.8.14/test/disabled/tls_server.js new file mode 100644 index 0000000..031e196 --- /dev/null +++ b/node-v0.8.14/test/disabled/tls_server.js @@ -0,0 +1,70 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + + + +var common = require('../common'); +var assert = require('assert'); + +var util = require('util'); +var net = require('net'); +var fs = require('fs'); +var crypto = require('crypto'); + +var keyPem = fs.readFileSync(common.fixturesDir + '/cert.pem'); +var certPem = fs.readFileSync(common.fixturesDir + '/cert.pem'); + +try { + var credentials = crypto.createCredentials({key: keyPem, cert: certPem}); +} catch (e) { + console.log('Not compiled with OPENSSL support.'); + process.exit(); +} +var i = 0; +var server = net.createServer(function(connection) { + connection.setSecure(credentials); + connection.setEncoding('binary'); + + connection.on('secure', function() { + //console.log('Secure'); + }); + + connection.on('data', function(chunk) { + console.log('recved: ' + JSON.stringify(chunk)); + connection.write('HTTP/1.0 200 OK\r\n' + + 'Content-type: text/plain\r\n' + + 'Content-length: 9\r\n' + + '\r\n' + + 'OK : ' + i + + '\r\n\r\n'); + i = i + 1; + connection.end(); + }); + + connection.on('end', function() { + connection.end(); + }); + +}); +server.listen(4443); + + diff --git a/node-v0.8.14/test/fixtures/GH-1899-output.js b/node-v0.8.14/test/fixtures/GH-1899-output.js new file mode 100644 index 0000000..d6b5133 --- /dev/null +++ b/node-v0.8.14/test/fixtures/GH-1899-output.js @@ -0,0 +1,23 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +console.log('hello, world!'); + diff --git a/node-v0.8.14/test/fixtures/GH-892-request.js b/node-v0.8.14/test/fixtures/GH-892-request.js new file mode 100644 index 0000000..a43398e --- /dev/null +++ b/node-v0.8.14/test/fixtures/GH-892-request.js @@ -0,0 +1,48 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// Called by test/simple/test-regress-GH-892.js + +var https = require('https'); +var fs = require('fs'); +var assert = require('assert'); + +var PORT = parseInt(process.argv[2]); +var bytesExpected = parseInt(process.argv[3]); + +var gotResponse = false; + +var options = { + method: 'POST', + port: PORT +}; + +var req = https.request(options, function(res) { + assert.equal(200, res.statusCode); + gotResponse = true; + console.error('DONE'); +}); + +req.end(new Buffer(bytesExpected)); + +process.on('exit', function() { + assert.ok(gotResponse); +}); diff --git a/node-v0.8.14/test/fixtures/a.js b/node-v0.8.14/test/fixtures/a.js new file mode 100644 index 0000000..fa010b0 --- /dev/null +++ b/node-v0.8.14/test/fixtures/a.js @@ -0,0 +1,46 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var c = require('./b/c'); + +console.error('load fixtures/a.js'); + +var string = 'A'; + +exports.SomeClass = c.SomeClass; + +exports.A = function() { + return string; +}; + +exports.C = function() { + return c.C(); +}; + +exports.D = function() { + return c.D(); +}; + +exports.number = 42; + +process.on('exit', function() { + string = 'A done'; +}); diff --git a/node-v0.8.14/test/fixtures/a1.js b/node-v0.8.14/test/fixtures/a1.js new file mode 100644 index 0000000..fa010b0 --- /dev/null +++ b/node-v0.8.14/test/fixtures/a1.js @@ -0,0 +1,46 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var c = require('./b/c'); + +console.error('load fixtures/a.js'); + +var string = 'A'; + +exports.SomeClass = c.SomeClass; + +exports.A = function() { + return string; +}; + +exports.C = function() { + return c.C(); +}; + +exports.D = function() { + return c.D(); +}; + +exports.number = 42; + +process.on('exit', function() { + string = 'A done'; +}); diff --git a/node-v0.8.14/test/fixtures/agent.crt b/node-v0.8.14/test/fixtures/agent.crt new file mode 100644 index 0000000..5883cd4 --- /dev/null +++ b/node-v0.8.14/test/fixtures/agent.crt @@ -0,0 +1,21 @@ +-----BEGIN CERTIFICATE----- +MIIDXTCCAkWgAwIBAgIJAMUSOvlaeyQHMA0GCSqGSIb3DQEBBQUAMEUxCzAJBgNV +BAYTAkFVMRMwEQYDVQQIDApTb21lLVN0YXRlMSEwHwYDVQQKDBhJbnRlcm5ldCBX +aWRnaXRzIFB0eSBMdGQwHhcNMTAxMTE2MDkzMjQ5WhcNMTMxMTE1MDkzMjQ5WjBF +MQswCQYDVQQGEwJBVTETMBEGA1UECAwKU29tZS1TdGF0ZTEhMB8GA1UECgwYSW50 +ZXJuZXQgV2lkZ2l0cyBQdHkgTHRkMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIB +CgKCAQEAz+LXZOjcQCJq3+ZKUFabj71oo/ex/XsBcFqtBThjjTw9CVEVwfPQQp4X +wtPiB204vnYXwQ1/R2NdTQqCZu47l79LssL/u2a5Y9+0NEU3nQA5qdt+1FAE0c5o +exPimXOrR3GWfKz7PmZ2O0117IeCUUXPG5U8umhDe/4mDF4ZNJiKc404WthquTqg +S7rLQZHhZ6D0EnGnOkzlmxJMYPNHSOY1/6ivdNUUcC87awNEA3lgfhy25IyBK3QJ +c+aYKNTbt70Lery3bu2wWLFGtmNiGlQTS4JsxImRsECTI727ObS7/FWAQsqW+COL +0Sa5BuMFrFIpjPrEe0ih7vRRbdmXRwIDAQABo1AwTjAdBgNVHQ4EFgQUDnV4d6mD +tOnluLoCjkUHTX/n4agwHwYDVR0jBBgwFoAUDnV4d6mDtOnluLoCjkUHTX/n4agw +DAYDVR0TBAUwAwEB/zANBgkqhkiG9w0BAQUFAAOCAQEAFwV4MQfTo+qMv9JMiyno +IEiqfOz4RgtmBqRnXUffcjS2dhc7/z+FPZnM79Kej8eLHoVfxCyWRHFlzm93vEdv +wxOCrD13EDOi08OOZfxWyIlCa6Bg8cMAKqQzd2OvQOWqlRWBTThBJIhWflU33izX +Qn5GdmYqhfpc+9ZHHGhvXNydtRQkdxVK2dZNzLBvBlLlRmtoClU7xm3A+/5dddeP +AQHEPtyFlUw49VYtZ3ru6KqPms7MKvcRhYLsy9rwSfuuniMlx4d0bDR7TOkw0QQS +A0N8MGQRQpzl4mw4jLzyM5d5QtuGBh2P6hPGa0YQxtI3RPT/p6ENzzBiAKXiSfzo +xw== +-----END CERTIFICATE----- diff --git a/node-v0.8.14/test/fixtures/agent.key b/node-v0.8.14/test/fixtures/agent.key new file mode 100644 index 0000000..f31ff3d --- /dev/null +++ b/node-v0.8.14/test/fixtures/agent.key @@ -0,0 +1,27 @@ +-----BEGIN RSA PRIVATE KEY----- +MIIEowIBAAKCAQEAz+LXZOjcQCJq3+ZKUFabj71oo/ex/XsBcFqtBThjjTw9CVEV +wfPQQp4XwtPiB204vnYXwQ1/R2NdTQqCZu47l79LssL/u2a5Y9+0NEU3nQA5qdt+ +1FAE0c5oexPimXOrR3GWfKz7PmZ2O0117IeCUUXPG5U8umhDe/4mDF4ZNJiKc404 +WthquTqgS7rLQZHhZ6D0EnGnOkzlmxJMYPNHSOY1/6ivdNUUcC87awNEA3lgfhy2 +5IyBK3QJc+aYKNTbt70Lery3bu2wWLFGtmNiGlQTS4JsxImRsECTI727ObS7/FWA +QsqW+COL0Sa5BuMFrFIpjPrEe0ih7vRRbdmXRwIDAQABAoIBAGe4+9VqZfJN+dsq +8Osyuz01uQ8OmC0sAWTIqUlQgENIyf9rCJsUBlYmwR5BT6Z69XP6QhHdpSK+TiAR +XUz0EqG9HYzcxHIBaACP7j6iRoQ8R4kbbiWKo0z3WqQGIOqFjvD/mKEuQdE5mEYw +eOUCG6BnX1WY2Yr8WKd2AA/tp0/Y4d8z04u9eodMpSTbHTzYMJb5SbBN1vo6FY7q +8zSuO0BMzXlAxUsCwHsk1GQHFr8Oh3zIR7bQGtMBouI+6Lhh7sjFYsfxJboqMTBV +IKaA216M6ggHG7MU1/jeKcMGDmEfqQLQoyWp29rMK6TklUgipME2L3UD7vTyAVzz +xbVOpZkCgYEA8CXW4sZBBrSSrLR5SB+Ubu9qNTggLowOsC/kVKB2WJ4+xooc5HQo +mFhq1v/WxPQoWIxdYsfg2odlL+JclK5Qcy6vXmRSdAQ5lK9gBDKxZSYc3NwAw2HA +zyHCTK+I0n8PBYQ+yGcrxu0WqTGnlLW+Otk4CejO34WlgHwbH9bbY5UCgYEA3ZvT +C4+OoMHXlmICSt29zUrYiL33IWsR3/MaONxTEDuvgkOSXXQOl/8Ebd6Nu+3WbsSN +bjiPC/JyL1YCVmijdvFpl4gjtgvfJifs4G+QHvO6YfsYoVANk4u6g6rUuBIOwNK4 +RwYxwDc0oysp+g7tPxoSgDHReEVKJNzGBe9NGGsCgYEA4O4QP4gCEA3B9BF2J5+s +n9uPVxmiyvZUK6Iv8zP4pThTBBMIzNIf09G9AHPQ7djikU2nioY8jXKTzC3xGTHM +GJZ5m6fLsu7iH+nDvSreDSeNkTBfZqGAvoGYQ8uGE+L+ZuRfCcXYsxIOT5s6o4c3 +Dle2rVFpsuKzCY00urW796ECgYBn3go75+xEwrYGQSer6WR1nTgCV29GVYXKPooy +zmmMOT1Yw80NSkEw0pFD4cTyqVYREsTrPU0mn1sPfrOXxnGfZSVFpcR/Je9QVfQ7 +eW7GYxwfom335aqHVj10SxRqteP+UoWWnHujCPz94VRKZMakBddYCIGSan+G6YdS +7sdmwwKBgBc2qj0wvGXDF2kCLwSGfWoMf8CS1+5fIiUIdT1e/+7MfDdbmLMIFVjF +QKS3zVViXCbrG5SY6wS9hxoc57f6E2A8vcaX6zy2xkZlGHQCpWRtEM5R01OWJQaH +HsHMmQZGUQVoDm1oRkDhrTFK4K3ukc3rAxzeTZ96utOQN8/KJsTv +-----END RSA PRIVATE KEY----- diff --git a/node-v0.8.14/test/fixtures/alice.crt b/node-v0.8.14/test/fixtures/alice.crt new file mode 100644 index 0000000..b4e986b --- /dev/null +++ b/node-v0.8.14/test/fixtures/alice.crt @@ -0,0 +1,24 @@ +-----BEGIN CERTIFICATE----- +MIID8DCCAtigAwIBAgIJALmw0zKhqlY1MA0GCSqGSIb3DQEBBQUAMFgxDjAMBgNV +BAMTBWFsaWNlMUYwRAYDVR0RFD11bmlmb3JtUmVzb3VyY2VJZGVudGlmaWVyOmh0 +dHA6Ly9sb2NhbGhvc3Q6ODAwMC9hbGljZS5mb2FmI21lMB4XDTExMDgyNDA1NTUx +NFoXDTExMDkyMzA1NTUxNFowWDEOMAwGA1UEAxMFYWxpY2UxRjBEBgNVHREUPXVu +aWZvcm1SZXNvdXJjZUlkZW50aWZpZXI6aHR0cDovL2xvY2FsaG9zdDo4MDAwL2Fs +aWNlLmZvYWYjbWUwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDP4tdk +6NxAImrf5kpQVpuPvWij97H9ewFwWq0FOGONPD0JURXB89BCnhfC0+IHbTi+dhfB +DX9HY11NCoJm7juXv0uywv+7Zrlj37Q0RTedADmp237UUATRzmh7E+KZc6tHcZZ8 +rPs+ZnY7TXXsh4JRRc8blTy6aEN7/iYMXhk0mIpzjTha2Gq5OqBLustBkeFnoPQS +cac6TOWbEkxg80dI5jX/qK901RRwLztrA0QDeWB+HLbkjIErdAlz5pgo1Nu3vQt6 +vLdu7bBYsUa2Y2IaVBNLgmzEiZGwQJMjvbs5tLv8VYBCypb4I4vRJrkG4wWsUimM ++sR7SKHu9FFt2ZdHAgMBAAGjgbwwgbkwHQYDVR0OBBYEFA51eHepg7Tp5bi6Ao5F +B01/5+GoMIGJBgNVHSMEgYEwf4AUDnV4d6mDtOnluLoCjkUHTX/n4aihXKRaMFgx +DjAMBgNVBAMTBWFsaWNlMUYwRAYDVR0RFD11bmlmb3JtUmVzb3VyY2VJZGVudGlm +aWVyOmh0dHA6Ly9sb2NhbGhvc3Q6ODAwMC9hbGljZS5mb2FmI21lggkAubDTMqGq +VjUwDAYDVR0TBAUwAwEB/zANBgkqhkiG9w0BAQUFAAOCAQEAreudH4Y7R9Vl2GJo +2xRUEwZiMj/ogomZ7B+IZtcuMIR8X2mzQ30xmPKaCy/fjbueqBroIDdxFeQ4eWZf +MD3AK/q5lJXwSInDjnn7jE9gNgLdQeCnajV0/QH+eDxIe/Alvx+RuvrDiNOudEs4 +vhqv5zEaL6VEXoWVb4/cghDbynQucSpyOMmGGPYYw2zmg0nNXdQauYWDUZIaDwQ6 +tM/pi2ewYubHPZdwJv5jvxTN3Z7RuuGHM+aLAZSAqSgAi0ml8PYYd2eRzXMaEI0c +eajcEvVa405aYT6dxuF1qqRDYx14As/R7O5RKCpz7wsxD6ICD/Ynv3GCUGxANQim +bcCjpg== +-----END CERTIFICATE----- diff --git a/node-v0.8.14/test/fixtures/b/c.js b/node-v0.8.14/test/fixtures/b/c.js new file mode 100644 index 0000000..6e5080d --- /dev/null +++ b/node-v0.8.14/test/fixtures/b/c.js @@ -0,0 +1,49 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var d = require('./d'); + +var assert = require('assert'); + +var package = require('./package'); + +assert.equal('world', package.hello); + +console.error('load fixtures/b/c.js'); + +var string = 'C'; + +exports.SomeClass = function() { + +}; + +exports.C = function() { + return string; +}; + +exports.D = function() { + return d.D(); +}; + +process.on('exit', function() { + string = 'C done'; + console.log('b/c.js exit'); +}); diff --git a/node-v0.8.14/test/fixtures/b/d.js b/node-v0.8.14/test/fixtures/b/d.js new file mode 100644 index 0000000..37fefc2 --- /dev/null +++ b/node-v0.8.14/test/fixtures/b/d.js @@ -0,0 +1,33 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +console.error('load fixtures/b/d.js'); + +var string = 'D'; + +exports.D = function() { + return string; +}; + +process.on('exit', function() { + string = 'D done'; +}); + diff --git a/node-v0.8.14/test/fixtures/b/package/index.js b/node-v0.8.14/test/fixtures/b/package/index.js new file mode 100644 index 0000000..c88d605 --- /dev/null +++ b/node-v0.8.14/test/fixtures/b/package/index.js @@ -0,0 +1,23 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +exports.hello = 'world'; +console.error('load package/index.js'); diff --git a/node-v0.8.14/test/fixtures/breakpoints.js b/node-v0.8.14/test/fixtures/breakpoints.js new file mode 100644 index 0000000..4824767 --- /dev/null +++ b/node-v0.8.14/test/fixtures/breakpoints.js @@ -0,0 +1,23 @@ +debugger; +function a(x) { + var i = 10; + while (--i != 0); + debugger; + return i; +} +function b() { + return ['hello', 'world'].join(' '); +} +a(); +a(1); +b(); +b(); + + + +setInterval(function() { +}, 5000); + + +now = new Date(); +debugger; diff --git a/node-v0.8.14/test/fixtures/breakpoints_utf8.js b/node-v0.8.14/test/fixtures/breakpoints_utf8.js new file mode 100644 index 0000000..cd05c76 --- /dev/null +++ b/node-v0.8.14/test/fixtures/breakpoints_utf8.js @@ -0,0 +1,19 @@ +debugger; +function a(x) { + var i = 10; + while (--i != 0); + debugger; + return i; +} +function b() { + return ['こんにち', 'わ'].join(' '); +} +a(); +a(1); +b(); +b(); + + + +setInterval(function() { +}, 5000); diff --git a/node-v0.8.14/test/fixtures/catch-stdout-error.js b/node-v0.8.14/test/fixtures/catch-stdout-error.js new file mode 100644 index 0000000..a244946 --- /dev/null +++ b/node-v0.8.14/test/fixtures/catch-stdout-error.js @@ -0,0 +1,38 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +function write() { + try { + process.stdout.write('Hello, world\n'); + } catch (ex) { + throw new Error('this should never happen'); + } + process.nextTick(function() { + write(); + }); +} + +process.stdout.on('error', function(er) { + console.error(JSON.stringify(er)); + process.exit(42); +}); + +write(); diff --git a/node-v0.8.14/test/fixtures/cert.pem b/node-v0.8.14/test/fixtures/cert.pem new file mode 100644 index 0000000..33854c2 --- /dev/null +++ b/node-v0.8.14/test/fixtures/cert.pem @@ -0,0 +1,35 @@ +-----BEGIN CERTIFICATE----- +MIIDNDCCAp2gAwIBAgIJAJvXLQpGPpm7MA0GCSqGSIb3DQEBBQUAMHAxCzAJBgNV +BAYTAkdCMRAwDgYDVQQIEwdHd3luZWRkMREwDwYDVQQHEwhXYXVuZmF3cjEUMBIG +A1UEChMLQWNrbmFjayBMdGQxEjAQBgNVBAsTCVRlc3QgQ2VydDESMBAGA1UEAxMJ +bG9jYWxob3N0MB4XDTA5MTEwMjE5MzMwNVoXDTEwMTEwMjE5MzMwNVowcDELMAkG +A1UEBhMCR0IxEDAOBgNVBAgTB0d3eW5lZGQxETAPBgNVBAcTCFdhdW5mYXdyMRQw +EgYDVQQKEwtBY2tuYWNrIEx0ZDESMBAGA1UECxMJVGVzdCBDZXJ0MRIwEAYDVQQD +Ewlsb2NhbGhvc3QwgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBANdym7nGe2yw +6LlJfJrQtC5TmKOGrSXiyolYCbGOy4xZI4KD31d3097jhlQFJyF+10gwkE62DuJe +fLvBZDUsvLe1R8bzlVhZnBVn+3QJyUIWQAL+DsRj8P3KoD7k363QN5dIaA1GOAg2 +vZcPy1HCUsvOgvDXGRUCZqNLAyt+h/cpAgMBAAGjgdUwgdIwHQYDVR0OBBYEFK4s +VBV4shKUj3UX/fvSJnFaaPBjMIGiBgNVHSMEgZowgZeAFK4sVBV4shKUj3UX/fvS +JnFaaPBjoXSkcjBwMQswCQYDVQQGEwJHQjEQMA4GA1UECBMHR3d5bmVkZDERMA8G +A1UEBxMIV2F1bmZhd3IxFDASBgNVBAoTC0Fja25hY2sgTHRkMRIwEAYDVQQLEwlU +ZXN0IENlcnQxEjAQBgNVBAMTCWxvY2FsaG9zdIIJAJvXLQpGPpm7MAwGA1UdEwQF +MAMBAf8wDQYJKoZIhvcNAQEFBQADgYEAFxR7BA1mUlsYqPiogtxSIfLzHWh+s0bJ +SBuhNrHes4U8QxS8+x/KWjd/81gzsf9J1C2VzTlFaydAgigz3SkQYgs+TMnFkT2o +9jqoJrcdf4WpZ2DQXUALaZgwNzPumMUSx8Ac5gO+BY/RHyP6fCodYvdNwyKslnI3 +US7eCSHZsVo= +-----END CERTIFICATE----- +-----BEGIN RSA PRIVATE KEY----- +MIICXgIBAAKBgQDXcpu5xntssOi5SXya0LQuU5ijhq0l4sqJWAmxjsuMWSOCg99X +d9Pe44ZUBSchftdIMJBOtg7iXny7wWQ1LLy3tUfG85VYWZwVZ/t0CclCFkAC/g7E +Y/D9yqA+5N+t0DeXSGgNRjgINr2XD8tRwlLLzoLw1xkVAmajSwMrfof3KQIDAQAB +AoGBAIBHR/tT93ce2mJAJAXV0AJpWc+7x2pwX2FpXtQujnlxNZhnRlrBCRCD7h4m +t0bVS/86kyGaesBDvAbavfx/N5keYzzmmSp5Ht8IPqKPydGWdigk4x90yWvktai7 +dWuRKF94FXr0GUuBONb/dfHdp4KBtzN7oIF9WydYGGXA9ZmBAkEA8/k01bfwQZIu +AgcdNEM94Zcug1gSspXtUu8exNQX4+PNVbadghZb1+OnUO4d3gvWfqvAnaXD3KV6 +N4OtUhQQ0QJBAOIRbKMfaymQ9yE3CQQxYfKmEhHXWARXVwuYqIFqjmhSjSXx0l/P +7mSHz1I9uDvxkJev8sQgu1TKIyTOdqPH1tkCQQDPa6H1yYoj1Un0Q2Qa2Mg1kTjk +Re6vkjPQ/KcmJEOjZjtekgFbZfLzmwLXFXqjG2FjFFaQMSxR3QYJSJQEYjbhAkEA +sy7OZcjcXnjZeEkv61Pc57/7qIp/6Aj2JGnefZ1gvI1Z9Q5kCa88rA/9Iplq8pA4 +ZBKAoDW1ZbJGAsFmxc/6mQJAdPilhci0qFN86IGmf+ZBnwsDflIwHKDaVofti4wQ +sPWhSOb9VQjMXekI4Y2l8fqAVTS2Fn6+8jkVKxXBywSVCw== +-----END RSA PRIVATE KEY----- diff --git a/node-v0.8.14/test/fixtures/child-process-message-and-exit.js b/node-v0.8.14/test/fixtures/child-process-message-and-exit.js new file mode 100644 index 0000000..56e83ce --- /dev/null +++ b/node-v0.8.14/test/fixtures/child-process-message-and-exit.js @@ -0,0 +1,3 @@ + +process.send('hello'); +process.exit(0); diff --git a/node-v0.8.14/test/fixtures/child-process-persistent.js b/node-v0.8.14/test/fixtures/child-process-persistent.js new file mode 100644 index 0000000..226ab33 --- /dev/null +++ b/node-v0.8.14/test/fixtures/child-process-persistent.js @@ -0,0 +1 @@ +setInterval(function () {}, 500); diff --git a/node-v0.8.14/test/fixtures/child-process-spawn-node.js b/node-v0.8.14/test/fixtures/child-process-spawn-node.js new file mode 100644 index 0000000..9bc6c19 --- /dev/null +++ b/node-v0.8.14/test/fixtures/child-process-spawn-node.js @@ -0,0 +1,10 @@ +var assert = require('assert'); + +process.on('message', function(m) { + console.log('CHILD got message:', m); + assert.ok(m.hello); + // Note that we have to force exit. + process.exit(); +}); + +process.send({ foo: 'bar' }); diff --git a/node-v0.8.14/test/fixtures/child_process_should_emit_error.js b/node-v0.8.14/test/fixtures/child_process_should_emit_error.js new file mode 100644 index 0000000..6e63235 --- /dev/null +++ b/node-v0.8.14/test/fixtures/child_process_should_emit_error.js @@ -0,0 +1,29 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var exec = require('child_process').exec; + +[0, 1].forEach(function(i) { + exec('ls', function(err, stdout, stderr) { + console.log(i); + throw new Error('hello world'); + }); +}); diff --git a/node-v0.8.14/test/fixtures/create-file.js b/node-v0.8.14/test/fixtures/create-file.js new file mode 100644 index 0000000..1e87bc9 --- /dev/null +++ b/node-v0.8.14/test/fixtures/create-file.js @@ -0,0 +1,29 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var fs = require('fs'); + +var file_name = process.argv[2]; +var file_size = parseInt(process.argv[3]); + +var fd = fs.openSync(file_name, 'w'); +fs.truncateSync(fd, file_size); +fs.closeSync(fd); diff --git a/node-v0.8.14/test/fixtures/cycles/folder/foo.js b/node-v0.8.14/test/fixtures/cycles/folder/foo.js new file mode 100644 index 0000000..07da5c9 --- /dev/null +++ b/node-v0.8.14/test/fixtures/cycles/folder/foo.js @@ -0,0 +1,27 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + +var root = require('./../root'); + +exports.hello = function() { + return root.calledFromFoo(); +}; diff --git a/node-v0.8.14/test/fixtures/cycles/root.js b/node-v0.8.14/test/fixtures/cycles/root.js new file mode 100644 index 0000000..ddce47d --- /dev/null +++ b/node-v0.8.14/test/fixtures/cycles/root.js @@ -0,0 +1,31 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + +var foo = exports.foo = require('./folder/foo'); + +exports.hello = 'hello'; +exports.sayHello = function() { + return foo.hello(); +}; +exports.calledFromFoo = function() { + return exports.hello; +}; diff --git a/node-v0.8.14/test/fixtures/deprecated.js b/node-v0.8.14/test/fixtures/deprecated.js new file mode 100644 index 0000000..be4bc4a --- /dev/null +++ b/node-v0.8.14/test/fixtures/deprecated.js @@ -0,0 +1 @@ +require('util').p('This is deprecated'); diff --git a/node-v0.8.14/test/fixtures/destroy-stdin.js b/node-v0.8.14/test/fixtures/destroy-stdin.js new file mode 100644 index 0000000..12b12fb --- /dev/null +++ b/node-v0.8.14/test/fixtures/destroy-stdin.js @@ -0,0 +1 @@ +process.stdin.destroy(); diff --git a/node-v0.8.14/test/fixtures/echo.js b/node-v0.8.14/test/fixtures/echo.js new file mode 100644 index 0000000..e5fc06b --- /dev/null +++ b/node-v0.8.14/test/fixtures/echo.js @@ -0,0 +1,31 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); + +common.print('hello world\r\n'); + +var stdin = process.openStdin(); + +stdin.on('data', function(data) { + process.stdout.write(data.toString()); +}); diff --git a/node-v0.8.14/test/fixtures/elipses.txt b/node-v0.8.14/test/fixtures/elipses.txt new file mode 100644 index 0000000..6105600 --- /dev/null +++ b/node-v0.8.14/test/fixtures/elipses.txt @@ -0,0 +1 @@ +………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………… \ No newline at end of file diff --git a/node-v0.8.14/test/fixtures/empty.js b/node-v0.8.14/test/fixtures/empty.js new file mode 100644 index 0000000..e69de29 diff --git a/node-v0.8.14/test/fixtures/empty.txt b/node-v0.8.14/test/fixtures/empty.txt new file mode 100644 index 0000000..e69de29 diff --git a/node-v0.8.14/test/fixtures/empty/.gitkeep b/node-v0.8.14/test/fixtures/empty/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/node-v0.8.14/test/fixtures/exit.js b/node-v0.8.14/test/fixtures/exit.js new file mode 100644 index 0000000..7e0fd7d --- /dev/null +++ b/node-v0.8.14/test/fixtures/exit.js @@ -0,0 +1,22 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +process.exit(process.argv[2] || 1); diff --git a/node-v0.8.14/test/fixtures/fixture.ini b/node-v0.8.14/test/fixtures/fixture.ini new file mode 100644 index 0000000..dcf1348 --- /dev/null +++ b/node-v0.8.14/test/fixtures/fixture.ini @@ -0,0 +1,19 @@ +; a comment +root=something + +url = http://example.com/?foo=bar + + [ the section with whitespace ] +this has whitespace = yep ; and a comment; and then another + + just a flag, no value. + +[section] +one=two +Foo=Bar +this=Your Mother! +blank= + +[Section Two] +something else=blah + remove = whitespace \ No newline at end of file diff --git a/node-v0.8.14/test/fixtures/foafssl.crt b/node-v0.8.14/test/fixtures/foafssl.crt new file mode 100644 index 0000000..f4b5905 --- /dev/null +++ b/node-v0.8.14/test/fixtures/foafssl.crt @@ -0,0 +1,25 @@ +Bag Attributes + friendlyName: Me's Not a Certification Authority ID + localKeyID: 98 CC 02 91 83 8D 14 4A 60 40 B7 11 E8 EF A9 01 4B D7 16 8A +subject=/O=FOAF+SSL/OU=The Community Of Self Signers/UID=http://example.com/#me/CN=Me +issuer=/O=FOAF+SSL/OU=The Community of Self Signers/CN=Not a Certification Authority +-----BEGIN CERTIFICATE----- +MIIDVDCCAr2gAwIBAgIQRLIhwZ2N3ciEdpWb6kPmPzANBgkqhkiG9w0BAQUFADBj +MREwDwYDVQQKDAhGT0FGK1NTTDEmMCQGA1UECwwdVGhlIENvbW11bml0eSBvZiBT +ZWxmIFNpZ25lcnMxJjAkBgNVBAMMHU5vdCBhIENlcnRpZmljYXRpb24gQXV0aG9y +aXR5MB4XDTExMDgzMDE3MzIwNFoXDTEyMDgyMDE5MzIwNFowcDERMA8GA1UECgwI +Rk9BRitTU0wxJjAkBgNVBAsMHVRoZSBDb21tdW5pdHkgT2YgU2VsZiBTaWduZXJz +MSYwJAYKCZImiZPyLGQBAQwWaHR0cDovL2V4YW1wbGUuY29tLyNtZTELMAkGA1UE +AwwCTWUwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCm9EqcJXkUMSFP +XIevngQBd6i7iayAP34Ju8OlUZ80nNm5xAvkNtCqgjqUFH4myJJIraK+PdTTTowo +lkaUsgR9IXtPEpk3Hqk6g8iauUQHJBMeZfKwFh3pVgzenBNFVVKy9Jzw+wDY13Uy +MkkT9vgP8p0KEx0p2wav+L4ZG3kg3C2uHCbqgqR4R6EDke879qq7PMQP+CEAsDpP +D/GAknjk3f2n3pVO1W3HrZpH7rw313GjZvxgpby3I3O+wYBkmz76DpCScHIQtBuQ +Ayuxi8kfIEbr2vEZH0pOJtcYecTHhnti/NUI6M5m6C0SinHpFYCfz0To3ndAZ/He +XXC5wDaHAgMBAAGjeDB2MAwGA1UdEwEB/wQCMAAwDgYDVR0PAQH/BAQDAgLsMBEG +CWCGSAGG+EIBAQQEAwIFoDAdBgNVHQ4EFgQU3gJIUFpe8rKklsjEdsxlaT6rZhow +JAYDVR0RAQH/BBowGIYWaHR0cDovL2V4YW1wbGUuY29tLyNtZTANBgkqhkiG9w0B +AQUFAAOBgQBLhwWbYMdeSkVZ4biVUle+XHP4Gv8V9WSfldvgn1PntS1lpVR46Exl +AkLO1SrnN5WHeAjv6VNb3KmTF+QhLt/4a1l9CEEeZSg5ml5aeXE+veobgypDoam+ +NKYAeIW9Wx+HcgBL4leIX3WiCKu/eal+a5ro18LQ8hkZqryHeVESIw== +-----END CERTIFICATE----- diff --git a/node-v0.8.14/test/fixtures/foafssl.key b/node-v0.8.14/test/fixtures/foafssl.key new file mode 100644 index 0000000..62e953a --- /dev/null +++ b/node-v0.8.14/test/fixtures/foafssl.key @@ -0,0 +1,32 @@ +Bag Attributes + friendlyName: Me's Not a Certification Authority ID + localKeyID: 98 CC 02 91 83 8D 14 4A 60 40 B7 11 E8 EF A9 01 4B D7 16 8A +Key Attributes: +-----BEGIN PRIVATE KEY----- +MIIEvwIBADANBgkqhkiG9w0BAQEFAASCBKkwggSlAgEAAoIBAQCm9EqcJXkUMSFP +XIevngQBd6i7iayAP34Ju8OlUZ80nNm5xAvkNtCqgjqUFH4myJJIraK+PdTTTowo +lkaUsgR9IXtPEpk3Hqk6g8iauUQHJBMeZfKwFh3pVgzenBNFVVKy9Jzw+wDY13Uy +MkkT9vgP8p0KEx0p2wav+L4ZG3kg3C2uHCbqgqR4R6EDke879qq7PMQP+CEAsDpP +D/GAknjk3f2n3pVO1W3HrZpH7rw313GjZvxgpby3I3O+wYBkmz76DpCScHIQtBuQ +Ayuxi8kfIEbr2vEZH0pOJtcYecTHhnti/NUI6M5m6C0SinHpFYCfz0To3ndAZ/He +XXC5wDaHAgMBAAECggEAEhwrv7Zc5PDTYS1zVnx4iMQ3HGi5uouom1uvxE4PTAC7 +qWf3tkCv798Cha+XY5OcMqALKEHCxU0e7QQoEdchn4UzQAePcSg1STCkYQw5seCa +5lA+vBUaF4aLDNa3TG0N9HWOVKGVnO/6OYC05qKClBBIMqCSKEkm942u6UBOql6q +71Sj1Nd/4eP9AcvgO5cgyUszM2I25LzXIZW7JLgdqXiJRj8CuY3X5FVURvadENgk +ctw5EjdT7LNdc67Ot9Bs6qcVr2ld/U+4ZSC2+cqtPyn7mnA4hrYXlpA1Ilv3oRwZ +aUJfG5HVV4jjNVHxDqddBh3UhOxJYZ1DNEMndTBx8QKBgQDcsrLfkE6utaj8w/of +Hk/aq1JRNLgSvhoP2wVmK7USvYFj7DIvL4CqyghY5TLgNk272v8mT0Q7R6AtsOUk +Gf50uZFAtIoPvTsvBu6cbRsPTeGJ0i1+LLme/AJu3MexXLF6mlzoGmlx8V7CoFqI +9hvqBA5rZ6ecoSjmU2q2xWKXKQKBgQDBqNqicSp2jnHiTXYbG/tsnxhFwALdEjvb +EgZprmoBzo1eQFOY/DNBdDiEZBstu9mJBX3XWTU1F4c6tYRocNCMDwLBZAB6NnVM +JjoddJApa5Qg3uoXmk53saZhcVkOzh+P/Dxg9c9O3q4DDUegnkM95ZSbCPtIBq6K +bPA3OS+GLwKBgQCY0022LjGuHbFlRzg+sDjPzW71OLJ2mBln/VyhwYZj8cJVtUuT +DSvmGHzrQduXE0OE4ENq/dzbx9+NhD9IXo+ruIxy6BHqkDkZeY1l2M+yK1YQn/BM +vR/UjeIJbu0BTpS/t4C6YP+/nUrnLy9CRFpUFHb/vQl+FsNBq2XsJob88QKBgQCD +6B5bbNduf2HEsdxTZMDhYJAo2jtZFxVcBzAFBb7A0k7qNsh6OLY0zBO+4Wy9vujR +8sKfTuz157u9WmwAs27pJ0RKM3I7zCIjJxqIe5/CBruTlCJAx2LRFljsoEb31aAb +88Owi12ULAq8m2wBVCsa2uhYnUqC6cIzGTaZdsMPEwKBgQDJXI+J2d36IWzFrByH +yskssFldbLxm/7EexzAYuoSpHuQIxGJYHTHn6CZhqrX8UbxVnS909ES+17kdLZVP +egvaxn1mtfZInnH64PiQDQrsNnbP4Zg8yvLvIcEVIPqnSQ5QrhdR29tjYuDwUIKM +4BMR2yfkFp6URRX7ZD1UQsduww== +-----END PRIVATE KEY----- diff --git a/node-v0.8.14/test/fixtures/foo b/node-v0.8.14/test/fixtures/foo new file mode 100644 index 0000000..66390ff --- /dev/null +++ b/node-v0.8.14/test/fixtures/foo @@ -0,0 +1,2 @@ + +exports.foo = "ok" diff --git a/node-v0.8.14/test/fixtures/fork2.js b/node-v0.8.14/test/fixtures/fork2.js new file mode 100644 index 0000000..900183a --- /dev/null +++ b/node-v0.8.14/test/fixtures/fork2.js @@ -0,0 +1,23 @@ +var assert = require('assert'); +var net = require('net'); + +var connections = 0; + +process.on('message', function(m, serverHandle) { + console.log('CHILD got message:', m); + assert.ok(m.hello); + + assert.ok(serverHandle); + + var server = new net.Server(function(c) { + connections++; + console.log('CHILD got connection'); + c.destroy(); + process.send({ childConnections: connections }); + }); + + server.listen(serverHandle, /* backlog */ 9, function() { + process.send({ gotHandle: true }); + }); +}); + diff --git a/node-v0.8.14/test/fixtures/global/plain.js b/node-v0.8.14/test/fixtures/global/plain.js new file mode 100644 index 0000000..f983d7c --- /dev/null +++ b/node-v0.8.14/test/fixtures/global/plain.js @@ -0,0 +1,25 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +foo = 'foo'; +global.bar = 'bar'; + +exports.fooBar = {foo: global.foo, bar: bar}; diff --git a/node-v0.8.14/test/fixtures/invalid.json b/node-v0.8.14/test/fixtures/invalid.json new file mode 100644 index 0000000..e4e825e --- /dev/null +++ b/node-v0.8.14/test/fixtures/invalid.json @@ -0,0 +1,5 @@ +{ + "name": "foo", + "version": "0.0.1" + "description": "im broken" +} \ No newline at end of file diff --git a/node-v0.8.14/test/fixtures/keys/Makefile b/node-v0.8.14/test/fixtures/keys/Makefile new file mode 100644 index 0000000..0c75a55 --- /dev/null +++ b/node-v0.8.14/test/fixtures/keys/Makefile @@ -0,0 +1,139 @@ +all: agent1-cert.pem agent2-cert.pem agent3-cert.pem agent4-cert.pem ca2-crl.pem + + +# +# Create Certificate Authority: ca1 +# ('password' is used for the CA password.) +# +ca1-cert.pem: ca1.cnf + openssl req -new -x509 -days 9999 -config ca1.cnf -keyout ca1-key.pem -out ca1-cert.pem + +# +# Create Certificate Authority: ca2 +# ('password' is used for the CA password.) +# +ca2-cert.pem: ca2.cnf + openssl req -new -x509 -days 9999 -config ca2.cnf -keyout ca2-key.pem -out ca2-cert.pem + echo '01' > ca2-serial + touch ca2-database.txt + + +# +# agent1 is signed by ca1. +# + +agent1-key.pem: + openssl genrsa -out agent1-key.pem 1024 + +agent1-csr.pem: agent1.cnf agent1-key.pem + openssl req -new -config agent1.cnf -key agent1-key.pem -out agent1-csr.pem + +agent1-cert.pem: agent1-csr.pem ca1-cert.pem ca1-key.pem + openssl x509 -req \ + -days 9999 \ + -passin "pass:password" \ + -in agent1-csr.pem \ + -CA ca1-cert.pem \ + -CAkey ca1-key.pem \ + -CAcreateserial \ + -out agent1-cert.pem + +agent1-verify: agent1-cert.pem ca1-cert.pem + openssl verify -CAfile ca1-cert.pem agent1-cert.pem + + +# +# agent2 has a self signed cert +# +# Generate new private key +agent2-key.pem: + openssl genrsa -out agent2-key.pem 1024 + +# Create a Certificate Signing Request for the key +agent2-csr.pem: agent2-key.pem agent2.cnf + openssl req -new -config agent2.cnf -key agent2-key.pem -out agent2-csr.pem + +# Create a Certificate for the agent. +agent2-cert.pem: agent2-csr.pem agent2-key.pem + openssl x509 -req \ + -days 9999 \ + -in agent2-csr.pem \ + -signkey agent2-key.pem \ + -out agent2-cert.pem + +agent2-verify: agent2-cert.pem + openssl verify -CAfile agent2-cert.pem agent2-cert.pem + +# +# agent3 is signed by ca2. +# + +agent3-key.pem: + openssl genrsa -out agent3-key.pem 1024 + +agent3-csr.pem: agent3.cnf agent3-key.pem + openssl req -new -config agent3.cnf -key agent3-key.pem -out agent3-csr.pem + +agent3-cert.pem: agent3-csr.pem ca2-cert.pem ca2-key.pem + openssl x509 -req \ + -days 9999 \ + -passin "pass:password" \ + -in agent3-csr.pem \ + -CA ca2-cert.pem \ + -CAkey ca2-key.pem \ + -CAcreateserial \ + -out agent3-cert.pem + +agent3-verify: agent3-cert.pem ca2-cert.pem + openssl verify -CAfile ca2-cert.pem agent3-cert.pem + + +# +# agent4 is signed by ca2 (client cert) +# + +agent4-key.pem: + openssl genrsa -out agent4-key.pem 1024 + +agent4-csr.pem: agent4.cnf agent4-key.pem + openssl req -new -config agent4.cnf -key agent4-key.pem -out agent4-csr.pem + +agent4-cert.pem: agent4-csr.pem ca2-cert.pem ca2-key.pem + openssl x509 -req \ + -days 9999 \ + -passin "pass:password" \ + -in agent4-csr.pem \ + -CA ca2-cert.pem \ + -CAkey ca2-key.pem \ + -CAcreateserial \ + -extfile agent4.cnf \ + -extensions ext_key_usage \ + -out agent4-cert.pem + +agent4-verify: agent4-cert.pem ca2-cert.pem + openssl verify -CAfile ca2-cert.pem agent4-cert.pem + +# +# Make CRL with agent4 being rejected +# +ca2-crl.pem: ca2-key.pem ca2-cert.pem ca2.cnf + openssl ca -revoke agent4-cert.pem \ + -keyfile ca2-key.pem \ + -cert ca2-cert.pem \ + -config ca2.cnf \ + -passin 'pass:password' + openssl ca \ + -keyfile ca2-key.pem \ + -cert ca2-cert.pem \ + -config ca2.cnf \ + -gencrl \ + -out ca2-crl.pem \ + -passin 'pass:password' + +clean: + rm -f *.pem *.srl ca2-database.txt ca2-serial + +test: agent1-verify agent2-verify agent3-verify agent4-verify + + +.PHONY: all clean test agent1-verify agent2-verify agent3-verify agent4-verify diff --git a/node-v0.8.14/test/fixtures/keys/agent1-cert.pem b/node-v0.8.14/test/fixtures/keys/agent1-cert.pem new file mode 100644 index 0000000..816f6fb --- /dev/null +++ b/node-v0.8.14/test/fixtures/keys/agent1-cert.pem @@ -0,0 +1,14 @@ +-----BEGIN CERTIFICATE----- +MIICKjCCAZMCCQDQ8o4kHKdCPDANBgkqhkiG9w0BAQUFADB6MQswCQYDVQQGEwJV +UzELMAkGA1UECBMCQ0ExCzAJBgNVBAcTAlNGMQ8wDQYDVQQKEwZKb3llbnQxEDAO +BgNVBAsTB05vZGUuanMxDDAKBgNVBAMTA2NhMTEgMB4GCSqGSIb3DQEJARYRcnlA +dGlueWNsb3Vkcy5vcmcwHhcNMTEwMzE0MTgyOTEyWhcNMzgwNzI5MTgyOTEyWjB9 +MQswCQYDVQQGEwJVUzELMAkGA1UECBMCQ0ExCzAJBgNVBAcTAlNGMQ8wDQYDVQQK +EwZKb3llbnQxEDAOBgNVBAsTB05vZGUuanMxDzANBgNVBAMTBmFnZW50MTEgMB4G +CSqGSIb3DQEJARYRcnlAdGlueWNsb3Vkcy5vcmcwXDANBgkqhkiG9w0BAQEFAANL +ADBIAkEAnzpAqcoXZxWJz/WFK7BXwD23jlREyG11x7gkydteHvn6PrVBbB5yfu6c +bk8w3/Ar608AcyMQ9vHjkLQKH7cjEQIDAQABMA0GCSqGSIb3DQEBBQUAA4GBAKha +HqjCfTIut+m/idKy3AoFh48tBHo3p9Nl5uBjQJmahKdZAaiksL24Pl+NzPQ8LIU+ +FyDHFp6OeJKN6HzZ72Bh9wpBVu6Uj1hwhZhincyTXT80wtSI/BoUAW8Ls2kwPdus +64LsJhhxqj2m4vPKNRbHB2QxnNrGi30CUf3kt3Ia +-----END CERTIFICATE----- diff --git a/node-v0.8.14/test/fixtures/keys/agent1-csr.pem b/node-v0.8.14/test/fixtures/keys/agent1-csr.pem new file mode 100644 index 0000000..748fd00 --- /dev/null +++ b/node-v0.8.14/test/fixtures/keys/agent1-csr.pem @@ -0,0 +1,10 @@ +-----BEGIN CERTIFICATE REQUEST----- +MIIBXTCCAQcCAQAwfTELMAkGA1UEBhMCVVMxCzAJBgNVBAgTAkNBMQswCQYDVQQH +EwJTRjEPMA0GA1UEChMGSm95ZW50MRAwDgYDVQQLEwdOb2RlLmpzMQ8wDQYDVQQD +EwZhZ2VudDExIDAeBgkqhkiG9w0BCQEWEXJ5QHRpbnljbG91ZHMub3JnMFwwDQYJ +KoZIhvcNAQEBBQADSwAwSAJBAJ86QKnKF2cVic/1hSuwV8A9t45URMhtdce4JMnb +Xh75+j61QWwecn7unG5PMN/wK+tPAHMjEPbx45C0Ch+3IxECAwEAAaAlMCMGCSqG +SIb3DQEJBzEWExRBIGNoYWxsZW5nZSBwYXNzd29yZDANBgkqhkiG9w0BAQUFAANB +AF+AfG64hNyYHum46m6i7RgnUBrJSOynGjs23TekV4he3QdMSAAPPqbll8W14+y3 +vOo7/yQ2v2uTqxCjakUNPPs= +-----END CERTIFICATE REQUEST----- diff --git a/node-v0.8.14/test/fixtures/keys/agent1-key.pem b/node-v0.8.14/test/fixtures/keys/agent1-key.pem new file mode 100644 index 0000000..5dae7eb --- /dev/null +++ b/node-v0.8.14/test/fixtures/keys/agent1-key.pem @@ -0,0 +1,9 @@ +-----BEGIN RSA PRIVATE KEY----- +MIIBOwIBAAJBAJ86QKnKF2cVic/1hSuwV8A9t45URMhtdce4JMnbXh75+j61QWwe +cn7unG5PMN/wK+tPAHMjEPbx45C0Ch+3IxECAwEAAQJBAI2cU1IuR+4IO87WPyAB +76kruoo87AeNQkjjvuQ/00+b/6IS45mcEP5Kw0NukbqBhIw2di9uQ9J51DJ/ZfQr ++YECIQDUHaN3ZjIdJ7/w8Yq9Zzz+3kY2F/xEz6e4ftOFW8bY2QIhAMAref+WYckC +oECgOLAvAxB1lI4j7oCbAaawfxKdnPj5AiEAi95rXx09aGpAsBGmSdScrPdG1v6j +83/2ebrvoZ1uFqkCIB0AssnrRVjUB6GZTNTyU3ERfdkx/RX1zvr8WkFR/lXpAiB7 +cUZ1i8ZkZrPrdVgw2cb28UJM7qZHQnXcMHTXFFvxeQ== +-----END RSA PRIVATE KEY----- diff --git a/node-v0.8.14/test/fixtures/keys/agent1.cnf b/node-v0.8.14/test/fixtures/keys/agent1.cnf new file mode 100644 index 0000000..81d2f09 --- /dev/null +++ b/node-v0.8.14/test/fixtures/keys/agent1.cnf @@ -0,0 +1,19 @@ +[ req ] +default_bits = 1024 +days = 999 +distinguished_name = req_distinguished_name +attributes = req_attributes +prompt = no + +[ req_distinguished_name ] +C = US +ST = CA +L = SF +O = Joyent +OU = Node.js +CN = agent1 +emailAddress = ry@tinyclouds.org + +[ req_attributes ] +challengePassword = A challenge password + diff --git a/node-v0.8.14/test/fixtures/keys/agent2-cert.pem b/node-v0.8.14/test/fixtures/keys/agent2-cert.pem new file mode 100644 index 0000000..8e4354d --- /dev/null +++ b/node-v0.8.14/test/fixtures/keys/agent2-cert.pem @@ -0,0 +1,13 @@ +-----BEGIN CERTIFICATE----- +MIIB7DCCAZYCCQC7gs0MDNn6MTANBgkqhkiG9w0BAQUFADB9MQswCQYDVQQGEwJV +UzELMAkGA1UECBMCQ0ExCzAJBgNVBAcTAlNGMQ8wDQYDVQQKEwZKb3llbnQxEDAO +BgNVBAsTB05vZGUuanMxDzANBgNVBAMTBmFnZW50MjEgMB4GCSqGSIb3DQEJARYR +cnlAdGlueWNsb3Vkcy5vcmcwHhcNMTEwMzE0MTgyOTEyWhcNMzgwNzI5MTgyOTEy +WjB9MQswCQYDVQQGEwJVUzELMAkGA1UECBMCQ0ExCzAJBgNVBAcTAlNGMQ8wDQYD +VQQKEwZKb3llbnQxEDAOBgNVBAsTB05vZGUuanMxDzANBgNVBAMTBmFnZW50MjEg +MB4GCSqGSIb3DQEJARYRcnlAdGlueWNsb3Vkcy5vcmcwXDANBgkqhkiG9w0BAQEF +AANLADBIAkEAyXb8FrRdKbhrKLgLSsn61i1C7w7fVVVd7OQsmV/7p9WB2lWFiDlC +WKGU9SiIz/A6wNZDUAuc2E+VwtpCT561AQIDAQABMA0GCSqGSIb3DQEBBQUAA0EA +C8HzpuNhFLCI3A5KkBS5zHAQax6TFUOhbpBCR0aTDbJ6F1liDTK1lmU/BjvPoj+9 +1LHwrmh29rK8kBPEjmymCQ== +-----END CERTIFICATE----- diff --git a/node-v0.8.14/test/fixtures/keys/agent2-csr.pem b/node-v0.8.14/test/fixtures/keys/agent2-csr.pem new file mode 100644 index 0000000..a670c4c --- /dev/null +++ b/node-v0.8.14/test/fixtures/keys/agent2-csr.pem @@ -0,0 +1,10 @@ +-----BEGIN CERTIFICATE REQUEST----- +MIIBXTCCAQcCAQAwfTELMAkGA1UEBhMCVVMxCzAJBgNVBAgTAkNBMQswCQYDVQQH +EwJTRjEPMA0GA1UEChMGSm95ZW50MRAwDgYDVQQLEwdOb2RlLmpzMQ8wDQYDVQQD +EwZhZ2VudDIxIDAeBgkqhkiG9w0BCQEWEXJ5QHRpbnljbG91ZHMub3JnMFwwDQYJ +KoZIhvcNAQEBBQADSwAwSAJBAMl2/Ba0XSm4ayi4C0rJ+tYtQu8O31VVXezkLJlf ++6fVgdpVhYg5QlihlPUoiM/wOsDWQ1ALnNhPlcLaQk+etQECAwEAAaAlMCMGCSqG +SIb3DQEJBzEWExRBIGNoYWxsZW5nZSBwYXNzd29yZDANBgkqhkiG9w0BAQUFAANB +AJnll2pt5l0pzskQSpjjLVTlFDFmJr/AZ3UK8v0WxBjYjCe5Jx4YehkChpxIyDUm +U3J9q9MDUf0+Y2+EGkssFfk= +-----END CERTIFICATE REQUEST----- diff --git a/node-v0.8.14/test/fixtures/keys/agent2-key.pem b/node-v0.8.14/test/fixtures/keys/agent2-key.pem new file mode 100644 index 0000000..522903c --- /dev/null +++ b/node-v0.8.14/test/fixtures/keys/agent2-key.pem @@ -0,0 +1,9 @@ +-----BEGIN RSA PRIVATE KEY----- +MIIBOgIBAAJBAMl2/Ba0XSm4ayi4C0rJ+tYtQu8O31VVXezkLJlf+6fVgdpVhYg5 +QlihlPUoiM/wOsDWQ1ALnNhPlcLaQk+etQECAwEAAQJBAMT6Bf34+UHKY1ObpsbH +9u2jsVblFq1rWvs8GPMY6oertzvwm3DpuSUp7PTgOB1nLTLYtCERbQ4ovtN8tn3p +OHUCIQDzIEGsoCr5vlxXvy2zJwu+fxYuhTZWMVuo1397L0VyhwIhANQh+yzqUgaf +WRtSB4T2W7ADtJI35ET61jKBty3CqJY3AiAIwju7dVW3A5WeD6Qc1SZGKZvp9yCb +AFI2BfVwwaY11wIgXF3PeGcvACMyMWsuSv7aPXHfliswAbkWuzcwA4TW01ECIGWa +cgsDvVFxmfM5NPSuT/UDTa6R5BFISB5ea0N0AR3I +-----END RSA PRIVATE KEY----- diff --git a/node-v0.8.14/test/fixtures/keys/agent2.cnf b/node-v0.8.14/test/fixtures/keys/agent2.cnf new file mode 100644 index 0000000..0a9f2c7 --- /dev/null +++ b/node-v0.8.14/test/fixtures/keys/agent2.cnf @@ -0,0 +1,19 @@ +[ req ] +default_bits = 1024 +days = 999 +distinguished_name = req_distinguished_name +attributes = req_attributes +prompt = no + +[ req_distinguished_name ] +C = US +ST = CA +L = SF +O = Joyent +OU = Node.js +CN = agent2 +emailAddress = ry@tinyclouds.org + +[ req_attributes ] +challengePassword = A challenge password + diff --git a/node-v0.8.14/test/fixtures/keys/agent3-cert.pem b/node-v0.8.14/test/fixtures/keys/agent3-cert.pem new file mode 100644 index 0000000..e4a2350 --- /dev/null +++ b/node-v0.8.14/test/fixtures/keys/agent3-cert.pem @@ -0,0 +1,14 @@ +-----BEGIN CERTIFICATE----- +MIICKjCCAZMCCQCDBr594bsJmTANBgkqhkiG9w0BAQUFADB6MQswCQYDVQQGEwJV +UzELMAkGA1UECBMCQ0ExCzAJBgNVBAcTAlNGMQ8wDQYDVQQKEwZKb3llbnQxEDAO +BgNVBAsTB05vZGUuanMxDDAKBgNVBAMTA2NhMjEgMB4GCSqGSIb3DQEJARYRcnlA +dGlueWNsb3Vkcy5vcmcwHhcNMTEwMzE0MTgyOTEyWhcNMzgwNzI5MTgyOTEyWjB9 +MQswCQYDVQQGEwJVUzELMAkGA1UECBMCQ0ExCzAJBgNVBAcTAlNGMQ8wDQYDVQQK +EwZKb3llbnQxEDAOBgNVBAsTB05vZGUuanMxDzANBgNVBAMTBmFnZW50MzEgMB4G +CSqGSIb3DQEJARYRcnlAdGlueWNsb3Vkcy5vcmcwXDANBgkqhkiG9w0BAQEFAANL +ADBIAkEAtlNDZ+bHeBI0B2gD/IWqA7Aq1hwsnS4+XpnLesjTQcL2JwFFpkR0oWrw +yjrYhCogi7c5gjKrLZF1d2JD5JgHgQIDAQABMA0GCSqGSIb3DQEBBQUAA4GBAJoK +bXwsImk7vJz9649yrmsXwnuGbEKVYMvqcGyjaZNP9lYEG41y5CeRzxhWy2rlYdhE +f2nqE2lg75oJP7LQqfQY7aCqwahM3q/GQbsfKVCGjF7TVyq9TQzd8iW+FEJIQzSE +3aN85hR67+3VAXeSzmkGSVBO2m1SJIug4qftIkc2 +-----END CERTIFICATE----- diff --git a/node-v0.8.14/test/fixtures/keys/agent3-csr.pem b/node-v0.8.14/test/fixtures/keys/agent3-csr.pem new file mode 100644 index 0000000..e6c0c74 --- /dev/null +++ b/node-v0.8.14/test/fixtures/keys/agent3-csr.pem @@ -0,0 +1,10 @@ +-----BEGIN CERTIFICATE REQUEST----- +MIIBXTCCAQcCAQAwfTELMAkGA1UEBhMCVVMxCzAJBgNVBAgTAkNBMQswCQYDVQQH +EwJTRjEPMA0GA1UEChMGSm95ZW50MRAwDgYDVQQLEwdOb2RlLmpzMQ8wDQYDVQQD +EwZhZ2VudDMxIDAeBgkqhkiG9w0BCQEWEXJ5QHRpbnljbG91ZHMub3JnMFwwDQYJ +KoZIhvcNAQEBBQADSwAwSAJBALZTQ2fmx3gSNAdoA/yFqgOwKtYcLJ0uPl6Zy3rI +00HC9icBRaZEdKFq8Mo62IQqIIu3OYIyqy2RdXdiQ+SYB4ECAwEAAaAlMCMGCSqG +SIb3DQEJBzEWExRBIGNoYWxsZW5nZSBwYXNzd29yZDANBgkqhkiG9w0BAQUFAANB +AEGo76iH+a8pnE+RWQT+wg9/BL+iIuqrcFXLs0rbGonqderrwXAe15ODwql/Bfu3 +zgMt8ooTsgMPcMX9EgmubEM= +-----END CERTIFICATE REQUEST----- diff --git a/node-v0.8.14/test/fixtures/keys/agent3-key.pem b/node-v0.8.14/test/fixtures/keys/agent3-key.pem new file mode 100644 index 0000000..d72f071 --- /dev/null +++ b/node-v0.8.14/test/fixtures/keys/agent3-key.pem @@ -0,0 +1,9 @@ +-----BEGIN RSA PRIVATE KEY----- +MIIBOwIBAAJBALZTQ2fmx3gSNAdoA/yFqgOwKtYcLJ0uPl6Zy3rI00HC9icBRaZE +dKFq8Mo62IQqIIu3OYIyqy2RdXdiQ+SYB4ECAwEAAQJAIk+G9s2SKgFa8y3a2jGZ +LfqABSzmJGooaIsOpLuYLd6eCC31XUDlT4rPVGRhysKQCQ4+NMjgdnj9ZqNnvXY/ +RQIhAOgbdltr3Ey2hy7RuDW5rmOeJTuVqCrZ7QI8ifyCEbYTAiEAyRfvWSvvASeP +kZTMUhATRUpuyDQW+058NE0oJSinTpsCIQCR/FPhBGI3TcaQyA9Ym0T4GwvIAkUX +TqInefRAAX8qSQIgZVJPAdIWGbHSL9sWW97HpukLCorcbYEtKbkamiZyrjMCIQCX +lX76ttkeId5OsJGQcF67eFMMr2UGZ1WMf6M39lCYHQ== +-----END RSA PRIVATE KEY----- diff --git a/node-v0.8.14/test/fixtures/keys/agent3.cnf b/node-v0.8.14/test/fixtures/keys/agent3.cnf new file mode 100644 index 0000000..26db5ba --- /dev/null +++ b/node-v0.8.14/test/fixtures/keys/agent3.cnf @@ -0,0 +1,19 @@ +[ req ] +default_bits = 1024 +days = 999 +distinguished_name = req_distinguished_name +attributes = req_attributes +prompt = no + +[ req_distinguished_name ] +C = US +ST = CA +L = SF +O = Joyent +OU = Node.js +CN = agent3 +emailAddress = ry@tinyclouds.org + +[ req_attributes ] +challengePassword = A challenge password + diff --git a/node-v0.8.14/test/fixtures/keys/agent4-cert.pem b/node-v0.8.14/test/fixtures/keys/agent4-cert.pem new file mode 100644 index 0000000..07157b9 --- /dev/null +++ b/node-v0.8.14/test/fixtures/keys/agent4-cert.pem @@ -0,0 +1,15 @@ +-----BEGIN CERTIFICATE----- +MIICSDCCAbGgAwIBAgIJAIMGvn3huwmaMA0GCSqGSIb3DQEBBQUAMHoxCzAJBgNV +BAYTAlVTMQswCQYDVQQIEwJDQTELMAkGA1UEBxMCU0YxDzANBgNVBAoTBkpveWVu +dDEQMA4GA1UECxMHTm9kZS5qczEMMAoGA1UEAxMDY2EyMSAwHgYJKoZIhvcNAQkB +FhFyeUB0aW55Y2xvdWRzLm9yZzAeFw0xMTAzMTQxODI5MTJaFw0zODA3MjkxODI5 +MTJaMH0xCzAJBgNVBAYTAlVTMQswCQYDVQQIEwJDQTELMAkGA1UEBxMCU0YxDzAN +BgNVBAoTBkpveWVudDEQMA4GA1UECxMHTm9kZS5qczEPMA0GA1UEAxMGYWdlbnQ0 +MSAwHgYJKoZIhvcNAQkBFhFyeUB0aW55Y2xvdWRzLm9yZzBcMA0GCSqGSIb3DQEB +AQUAA0sAMEgCQQDN/yMfmQ8zdvmjlGk7b3Mn6wY2FjaMb4c5ENJX15vyYhKS1zhx +6n0kQIn2vf6yqG7tO5Okz2IJiD9Sa06mK6GrAgMBAAGjFzAVMBMGA1UdJQQMMAoG +CCsGAQUFBwMCMA0GCSqGSIb3DQEBBQUAA4GBAA8FXpRmdrHBdlofNvxa14zLvv0N +WnUGUmxVklFLKXvpVWTanOhVgI2TDCMrT5WvCRTD25iT1EUKWxjDhFJrklQJ+IfC +KC6fsgO7AynuxWSfSkc8/acGiAH+20vW9QxR53HYiIDMXEV/wnE0KVcr3t/d70lr +ImanTrunagV+3O4O +-----END CERTIFICATE----- diff --git a/node-v0.8.14/test/fixtures/keys/agent4-csr.pem b/node-v0.8.14/test/fixtures/keys/agent4-csr.pem new file mode 100644 index 0000000..97e115d --- /dev/null +++ b/node-v0.8.14/test/fixtures/keys/agent4-csr.pem @@ -0,0 +1,10 @@ +-----BEGIN CERTIFICATE REQUEST----- +MIIBXTCCAQcCAQAwfTELMAkGA1UEBhMCVVMxCzAJBgNVBAgTAkNBMQswCQYDVQQH +EwJTRjEPMA0GA1UEChMGSm95ZW50MRAwDgYDVQQLEwdOb2RlLmpzMQ8wDQYDVQQD +EwZhZ2VudDQxIDAeBgkqhkiG9w0BCQEWEXJ5QHRpbnljbG91ZHMub3JnMFwwDQYJ +KoZIhvcNAQEBBQADSwAwSAJBAM3/Ix+ZDzN2+aOUaTtvcyfrBjYWNoxvhzkQ0lfX +m/JiEpLXOHHqfSRAifa9/rKobu07k6TPYgmIP1JrTqYroasCAwEAAaAlMCMGCSqG +SIb3DQEJBzEWExRBIGNoYWxsZW5nZSBwYXNzd29yZDANBgkqhkiG9w0BAQUFAANB +AMzo7GUOBtGm5MSck1rrEE2C1bU3qoVvXVuiN3A/57zXeNeq24FZMLnkDeL9U+/b +Kj646XFou04gla982Xp74p0= +-----END CERTIFICATE REQUEST----- diff --git a/node-v0.8.14/test/fixtures/keys/agent4-key.pem b/node-v0.8.14/test/fixtures/keys/agent4-key.pem new file mode 100644 index 0000000..b770b01 --- /dev/null +++ b/node-v0.8.14/test/fixtures/keys/agent4-key.pem @@ -0,0 +1,9 @@ +-----BEGIN RSA PRIVATE KEY----- +MIIBOQIBAAJBAM3/Ix+ZDzN2+aOUaTtvcyfrBjYWNoxvhzkQ0lfXm/JiEpLXOHHq +fSRAifa9/rKobu07k6TPYgmIP1JrTqYroasCAwEAAQJAN8RQb+dx1A7rejtdWbfM +Rww7PD07Oz2eL/a72wgFsdIabRuVypIoHunqV0sAegYtNJt9yu+VhREw0R5tx/qz +EQIhAPY+nmzp0b4iFRk7mtGUmCTr9iwwzoqzITwphE7FpQnFAiEA1ihUHFT9YPHO +f85skM6qZv77NEgXHO8NJmQZ5GX1ZK8CICzle+Mluo0tD6W7HV4q9pZ8wzSJbY8S +W/PpKetm09F1AiAWTw8sAGKAtc/IGo3Oq+iuYAN1F8lolzJsfGMCGujsOwIgAJKP +t3eXilwX3ZlsDWSklWNZ7iYcfYrvAc3JqU6gFCE= +-----END RSA PRIVATE KEY----- diff --git a/node-v0.8.14/test/fixtures/keys/agent4.cnf b/node-v0.8.14/test/fixtures/keys/agent4.cnf new file mode 100644 index 0000000..5e583eb --- /dev/null +++ b/node-v0.8.14/test/fixtures/keys/agent4.cnf @@ -0,0 +1,21 @@ +[ req ] +default_bits = 1024 +days = 999 +distinguished_name = req_distinguished_name +attributes = req_attributes +prompt = no + +[ req_distinguished_name ] +C = US +ST = CA +L = SF +O = Joyent +OU = Node.js +CN = agent4 +emailAddress = ry@tinyclouds.org + +[ req_attributes ] +challengePassword = A challenge password + +[ ext_key_usage ] +extendedKeyUsage = clientAuth diff --git a/node-v0.8.14/test/fixtures/keys/ca1-cert.pem b/node-v0.8.14/test/fixtures/keys/ca1-cert.pem new file mode 100644 index 0000000..1951de7 --- /dev/null +++ b/node-v0.8.14/test/fixtures/keys/ca1-cert.pem @@ -0,0 +1,15 @@ +-----BEGIN CERTIFICATE----- +MIICazCCAdQCCQDTlFdg2h0DBjANBgkqhkiG9w0BAQUFADB6MQswCQYDVQQGEwJV +UzELMAkGA1UECBMCQ0ExCzAJBgNVBAcTAlNGMQ8wDQYDVQQKEwZKb3llbnQxEDAO +BgNVBAsTB05vZGUuanMxDDAKBgNVBAMTA2NhMTEgMB4GCSqGSIb3DQEJARYRcnlA +dGlueWNsb3Vkcy5vcmcwHhcNMTEwMzE0MTgyOTEyWhcNMzgwNzI5MTgyOTEyWjB6 +MQswCQYDVQQGEwJVUzELMAkGA1UECBMCQ0ExCzAJBgNVBAcTAlNGMQ8wDQYDVQQK +EwZKb3llbnQxEDAOBgNVBAsTB05vZGUuanMxDDAKBgNVBAMTA2NhMTEgMB4GCSqG +SIb3DQEJARYRcnlAdGlueWNsb3Vkcy5vcmcwgZ8wDQYJKoZIhvcNAQEBBQADgY0A +MIGJAoGBAKxbsLdJbi53pcP1pzg8lgJhLEvcNlV2ogr97WURp+gPjK+HFXj2xl9w +qDQrxpmvTya+urBG7OagTjV1E7dRE7PTr4TkEqehmxF026Opb0PZewuIBOKX4UgG +PSfk0fksrje6YJb+OkiBfA/q7eznZF8cmq7MRrs7LWe9A6Bic/apAgMBAAEwDQYJ +KoZIhvcNAQEFBQADgYEAk6hlYgjCBihG4dM+3324W1WsvjU8QscsTXu8SGL0y9b6 +82zZikj0W9FU6u98WHtXwuFt3mKlGCcou2pluZvj02T2iVKSMs2oYL8JOlvM8hVf +GEeg2EriLlzmdxNz4/I86DlBiyoTijZh8/qrItsK7+a56P0exH8ouXzlhL1Bhjw= +-----END CERTIFICATE----- diff --git a/node-v0.8.14/test/fixtures/keys/ca1-cert.srl b/node-v0.8.14/test/fixtures/keys/ca1-cert.srl new file mode 100644 index 0000000..046be14 --- /dev/null +++ b/node-v0.8.14/test/fixtures/keys/ca1-cert.srl @@ -0,0 +1 @@ +D0F28E241CA7423C diff --git a/node-v0.8.14/test/fixtures/keys/ca1-key.pem b/node-v0.8.14/test/fixtures/keys/ca1-key.pem new file mode 100644 index 0000000..a4e4516 --- /dev/null +++ b/node-v0.8.14/test/fixtures/keys/ca1-key.pem @@ -0,0 +1,17 @@ +-----BEGIN ENCRYPTED PRIVATE KEY----- +MIICxjBABgkqhkiG9w0BBQ0wMzAbBgkqhkiG9w0BBQwwDgQIrulhMUmafvECAggA +MBQGCCqGSIb3DQMHBAjsjahmkf3zGwSCAoANt0xX8ZZT2CxeyUadbOuku6NrHoFy +YBvnEFvuq3TGm3NB72BxprvfMUNR5Xi6e6rJgtRQttPRX6oN2qfB8+W11vFBeFWG +gxarEotklca4bujPMwxRowyMT20n+yXvRc+Fd5tYrMcaBeweQZD69J242HJMJJmq +Lzvo2qYGaOxjpc8aUDzeDsv8cnlh5Xk1ZcRucRPM9j26KOPSt0wOd4RdN83AE8cW +Xu+k5TSMlPQLWihjS+KzEQ8Rs9CuubxrdmecF6DM70u0kYCLZ1Ex7+kBZu06CUpJ +PODaLca4W92XkBq4X25WgAAaCAj4nZZmgn0X0Fwl1lBqjOK5nEnYpjxuwjjJ2KVz +3j+kBK5tW6RBE4BM37r7NiM1FAzi8sgNYSVS9oa4m1qGfadEEQdhaMsAfM0SZ/8M +6NUPKlQmoDda9aCO7rqRuQ7pYQ9mpNxcWEBQi0cG6/3VXtqi/TewAKT1T5DToAzg +pL4eOTqeDp4VKif5r2u7Nj0EiM4j2TT88onGsdgRtjgUpNmJCRWYaCzs3QZggdYE +nLZt7ZRXpJ11tERKG3b28qrIw9jHULRAjjWEkEGbxYTpAlrgXklV/04XXnxxAVOP +0YjDzbfx5QCRCq5UHV4Gl3ELoBaOuxcIIN8YrE2oC1CY9uV/HSk4CSlxHNtWyxbA +WbCU2SoEHnwBVlTPbZyfErM33c3u4LJyNx6ah7NzMh5AoQ+cPXlzxFBEGIyAmW37 +pItxDNwL1PzXHGpfOM/QZ5wjzGIwXsh8j94jDNB+TIMG4+dm4aXkolevPjJrYAeG +XZC5mvfMsntNGNFszT/8iXLwt7tlMlQQQl/2b5m6L5yffy6m39wGqTVa +-----END ENCRYPTED PRIVATE KEY----- diff --git a/node-v0.8.14/test/fixtures/keys/ca1.cnf b/node-v0.8.14/test/fixtures/keys/ca1.cnf new file mode 100644 index 0000000..ea43127 --- /dev/null +++ b/node-v0.8.14/test/fixtures/keys/ca1.cnf @@ -0,0 +1,20 @@ +[ req ] +default_bits = 1024 +days = 999 +distinguished_name = req_distinguished_name +attributes = req_attributes +prompt = no +output_password = password + +[ req_distinguished_name ] +C = US +ST = CA +L = SF +O = Joyent +OU = Node.js +CN = ca1 +emailAddress = ry@tinyclouds.org + +[ req_attributes ] +challengePassword = A challenge password + diff --git a/node-v0.8.14/test/fixtures/keys/ca2-cert.pem b/node-v0.8.14/test/fixtures/keys/ca2-cert.pem new file mode 100644 index 0000000..95e3041 --- /dev/null +++ b/node-v0.8.14/test/fixtures/keys/ca2-cert.pem @@ -0,0 +1,15 @@ +-----BEGIN CERTIFICATE----- +MIICazCCAdQCCQDVGbMO4Y2VUTANBgkqhkiG9w0BAQUFADB6MQswCQYDVQQGEwJV +UzELMAkGA1UECBMCQ0ExCzAJBgNVBAcTAlNGMQ8wDQYDVQQKEwZKb3llbnQxEDAO +BgNVBAsTB05vZGUuanMxDDAKBgNVBAMTA2NhMjEgMB4GCSqGSIb3DQEJARYRcnlA +dGlueWNsb3Vkcy5vcmcwHhcNMTEwMzE0MTgyOTEyWhcNMzgwNzI5MTgyOTEyWjB6 +MQswCQYDVQQGEwJVUzELMAkGA1UECBMCQ0ExCzAJBgNVBAcTAlNGMQ8wDQYDVQQK +EwZKb3llbnQxEDAOBgNVBAsTB05vZGUuanMxDDAKBgNVBAMTA2NhMjEgMB4GCSqG +SIb3DQEJARYRcnlAdGlueWNsb3Vkcy5vcmcwgZ8wDQYJKoZIhvcNAQEBBQADgY0A +MIGJAoGBAMOOtRmmjoBZmyYreB1D1fjftMW6sEGBzfSKZRcn+kiEpqXELq21O/TV +jLJGbo+0PDqxECQyDbOgoQZXcCevFnFhdsSQOYb+0O2kAiMVYGxDtqoKM5g8wj0D +BiE6fnyZoQTDv5lEuvfG0+youCtXlxiK/9cfhikI+hVXuTgwQXt9AgMBAAEwDQYJ +KoZIhvcNAQEFBQADgYEAbMrLydFajwfZXDH3PfpKtDPCm+yV3qvEMGWLfjBdN50g +PwsZE/OIp+KJttdS+MjMG1TfwfWIqa5zGG2ctxx+fHsKH+t3NsO76Eol1p+dKqZp +PdFp2UhViMgURkrpP593AsTTO9BGaz+awSaESDHm8pO+cLaeGKQp93W0sgC0lHQ= +-----END CERTIFICATE----- diff --git a/node-v0.8.14/test/fixtures/keys/ca2-cert.srl b/node-v0.8.14/test/fixtures/keys/ca2-cert.srl new file mode 100644 index 0000000..00dca7d --- /dev/null +++ b/node-v0.8.14/test/fixtures/keys/ca2-cert.srl @@ -0,0 +1 @@ +8306BE7DE1BB099A diff --git a/node-v0.8.14/test/fixtures/keys/ca2-crl.pem b/node-v0.8.14/test/fixtures/keys/ca2-crl.pem new file mode 100644 index 0000000..166df74 --- /dev/null +++ b/node-v0.8.14/test/fixtures/keys/ca2-crl.pem @@ -0,0 +1,10 @@ +-----BEGIN X509 CRL----- +MIIBXTCBxzANBgkqhkiG9w0BAQQFADB6MQswCQYDVQQGEwJVUzELMAkGA1UECBMC +Q0ExCzAJBgNVBAcTAlNGMQ8wDQYDVQQKEwZKb3llbnQxEDAOBgNVBAsTB05vZGUu +anMxDDAKBgNVBAMTA2NhMjEgMB4GCSqGSIb3DQEJARYRcnlAdGlueWNsb3Vkcy5v +cmcXDTExMDMxNDE4MjkxNloXDTEzMTIwNzE4MjkxNlowHDAaAgkAgwa+feG7CZoX +DTExMDMxNDE4MjkxNFowDQYJKoZIhvcNAQEEBQADgYEArRKuEkOla61fm4zlZtHe +LTXFV0Hgo21PScHAp6JqPol4rN5R9+EmUkv7gPCVVBJ9VjIgxSosHiLsDiz3zR+u +txHemhzbdIVANAIiChnFct8sEqH2eL4N6XNUIlMIR06NjNl7NbN8w8haqiearnuT +wmnaL4TThPmpbpKAF7N7JqQ= +-----END X509 CRL----- diff --git a/node-v0.8.14/test/fixtures/keys/ca2-database.txt b/node-v0.8.14/test/fixtures/keys/ca2-database.txt new file mode 100644 index 0000000..a0966d2 --- /dev/null +++ b/node-v0.8.14/test/fixtures/keys/ca2-database.txt @@ -0,0 +1 @@ +R 380729182912Z 110314182914Z 8306BE7DE1BB099A unknown /C=US/ST=CA/L=SF/O=Joyent/OU=Node.js/CN=agent4/emailAddress=ry@tinyclouds.org diff --git a/node-v0.8.14/test/fixtures/keys/ca2-key.pem b/node-v0.8.14/test/fixtures/keys/ca2-key.pem new file mode 100644 index 0000000..49f678a --- /dev/null +++ b/node-v0.8.14/test/fixtures/keys/ca2-key.pem @@ -0,0 +1,17 @@ +-----BEGIN ENCRYPTED PRIVATE KEY----- +MIICxjBABgkqhkiG9w0BBQ0wMzAbBgkqhkiG9w0BBQwwDgQIbhsCgrscf9MCAggA +MBQGCCqGSIb3DQMHBAjz0LdWOB2KVQSCAoDu+sHRLP6v6QiEwqynnF43yP02/F+8 +Jssz6cgFPpm4MWm+xwzvMsS4ET0UYE68OTZz/QgihwH0mp/34tkUnP0HqtdbnTH1 +fkG47hb8fVSEyDQSzs1ha/u31GIachNURKyhWR5mr15AJxu2B94Z3ldNv1yjI+Fy +M1muuyx/cdkKTdpfpYr6n//wF1tup2u8Y7nkKsFus/mCuRlpItxKcRb1+nvW0s+K +3bSR8CTlEWd1Tx6Qx+ogRbP8gwqd6gelcz/Zj8nInx/Y0gTkQ4eodmLJ5iqsvC36 +SgQB5LuP12ujTyXB3Hwqb8LJ4lULERX6AYHAa7h0c+fxuFr0W9/8atplrd22hoiP +zZhgPHeH3R1fibB4M4xW2xgtbysOHj74RYlhQm1TCXLlqvzKkvT2oQ1bk7tUUqoR +ozRxVzdL9oKWLzvR4LF8S67i35JlnOPU1AhcxD2+5ywRvTpugPyCE1mZOeVLHlGW +2pdmSKbdd2gm2iSfadDPJ1DPdHLp844jRg/D6XDs4rlBnt9FjMWaXYo+ELmokoYe +Yljv2MGfy6zsb5iKcNsx+llu04xGXfZ9BAuG+aT6DLCIcDIVvE0d6asc4Lz1xZli +BrgyB8el2a/PomPbbf1vI2vtDi3Rg/pQhu/2++ODI08jI9Rudz1EltQQ4Lo38Ton +nSZegTAy6afXiEh2ty09KxMo4sWs+F2I46e5Q3zGY9b/K19bbQTFxeBf2Rfwa8BF +cf8Xs+DlcOMz5w0U2iBQfT1cV7dWLlaop7avYkpQ0fLa1pConlNhpguezcaAB8Lb +VCfpoTh6VfHRtCLokQlkq0mlKPUSlMr/JAyVdvppp/T6Abt0VirM9ILV +-----END ENCRYPTED PRIVATE KEY----- diff --git a/node-v0.8.14/test/fixtures/keys/ca2-serial b/node-v0.8.14/test/fixtures/keys/ca2-serial new file mode 100644 index 0000000..8a0f05e --- /dev/null +++ b/node-v0.8.14/test/fixtures/keys/ca2-serial @@ -0,0 +1 @@ +01 diff --git a/node-v0.8.14/test/fixtures/keys/ca2.cnf b/node-v0.8.14/test/fixtures/keys/ca2.cnf new file mode 100644 index 0000000..7af9f8c --- /dev/null +++ b/node-v0.8.14/test/fixtures/keys/ca2.cnf @@ -0,0 +1,33 @@ +[ ca ] +default_ca = CA_default + +[ CA_default ] +serial = ca2-serial +crl = ca2-crl.pem +database = ca2-database.txt +name_opt = CA_default +cert_opt = CA_default +default_crl_days = 999 +default_md = md5 + + +[ req ] +default_bits = 1024 +days = 999 +distinguished_name = req_distinguished_name +attributes = req_attributes +prompt = no +output_password = password + +[ req_distinguished_name ] +C = US +ST = CA +L = SF +O = Joyent +OU = Node.js +CN = ca2 +emailAddress = ry@tinyclouds.org + +[ req_attributes ] +challengePassword = A challenge password + diff --git a/node-v0.8.14/test/fixtures/module-load-order/file1 b/node-v0.8.14/test/fixtures/module-load-order/file1 new file mode 100644 index 0000000..7f287a8 --- /dev/null +++ b/node-v0.8.14/test/fixtures/module-load-order/file1 @@ -0,0 +1 @@ +exports.file1 = 'file1'; diff --git a/node-v0.8.14/test/fixtures/module-load-order/file1.js b/node-v0.8.14/test/fixtures/module-load-order/file1.js new file mode 100644 index 0000000..d378d84 --- /dev/null +++ b/node-v0.8.14/test/fixtures/module-load-order/file1.js @@ -0,0 +1,22 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +exports.file1 = 'file1.js'; diff --git a/node-v0.8.14/test/fixtures/module-load-order/file1.node b/node-v0.8.14/test/fixtures/module-load-order/file1.node new file mode 100644 index 0000000..af84f65 --- /dev/null +++ b/node-v0.8.14/test/fixtures/module-load-order/file1.node @@ -0,0 +1 @@ +exports.file1 = 'file1.node'; diff --git a/node-v0.8.14/test/fixtures/module-load-order/file1.reg b/node-v0.8.14/test/fixtures/module-load-order/file1.reg new file mode 100644 index 0000000..857b61b --- /dev/null +++ b/node-v0.8.14/test/fixtures/module-load-order/file1.reg @@ -0,0 +1 @@ +exports.file1 = 'file1.reg'; diff --git a/node-v0.8.14/test/fixtures/module-load-order/file1.reg2 b/node-v0.8.14/test/fixtures/module-load-order/file1.reg2 new file mode 100644 index 0000000..c38de9c --- /dev/null +++ b/node-v0.8.14/test/fixtures/module-load-order/file1.reg2 @@ -0,0 +1 @@ +exports.file1 = 'file1.reg2'; diff --git a/node-v0.8.14/test/fixtures/module-load-order/file2.js b/node-v0.8.14/test/fixtures/module-load-order/file2.js new file mode 100644 index 0000000..e87d595 --- /dev/null +++ b/node-v0.8.14/test/fixtures/module-load-order/file2.js @@ -0,0 +1,22 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +exports.file2 = 'file2.js'; diff --git a/node-v0.8.14/test/fixtures/module-load-order/file2.node b/node-v0.8.14/test/fixtures/module-load-order/file2.node new file mode 100644 index 0000000..2c7c4b6 --- /dev/null +++ b/node-v0.8.14/test/fixtures/module-load-order/file2.node @@ -0,0 +1 @@ +exports.file2 = 'file2.node'; diff --git a/node-v0.8.14/test/fixtures/module-load-order/file2.reg b/node-v0.8.14/test/fixtures/module-load-order/file2.reg new file mode 100644 index 0000000..ee5edeb --- /dev/null +++ b/node-v0.8.14/test/fixtures/module-load-order/file2.reg @@ -0,0 +1 @@ +exports.file2 = 'file2.reg'; diff --git a/node-v0.8.14/test/fixtures/module-load-order/file2.reg2 b/node-v0.8.14/test/fixtures/module-load-order/file2.reg2 new file mode 100644 index 0000000..95c2a59 --- /dev/null +++ b/node-v0.8.14/test/fixtures/module-load-order/file2.reg2 @@ -0,0 +1 @@ +exports.file2 = 'file2.reg2'; diff --git a/node-v0.8.14/test/fixtures/module-load-order/file2/index.js b/node-v0.8.14/test/fixtures/module-load-order/file2/index.js new file mode 100644 index 0000000..720da31 --- /dev/null +++ b/node-v0.8.14/test/fixtures/module-load-order/file2/index.js @@ -0,0 +1,22 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +exports.file2 = 'file2/index.js'; diff --git a/node-v0.8.14/test/fixtures/module-load-order/file2/index.node b/node-v0.8.14/test/fixtures/module-load-order/file2/index.node new file mode 100644 index 0000000..a987dc4 --- /dev/null +++ b/node-v0.8.14/test/fixtures/module-load-order/file2/index.node @@ -0,0 +1 @@ +exports.file2 = 'file2/index.node'; diff --git a/node-v0.8.14/test/fixtures/module-load-order/file2/index.reg b/node-v0.8.14/test/fixtures/module-load-order/file2/index.reg new file mode 100644 index 0000000..61d7b91 --- /dev/null +++ b/node-v0.8.14/test/fixtures/module-load-order/file2/index.reg @@ -0,0 +1 @@ +exports.file2 = 'file2/index.reg'; diff --git a/node-v0.8.14/test/fixtures/module-load-order/file2/index.reg2 b/node-v0.8.14/test/fixtures/module-load-order/file2/index.reg2 new file mode 100644 index 0000000..ecc8240 --- /dev/null +++ b/node-v0.8.14/test/fixtures/module-load-order/file2/index.reg2 @@ -0,0 +1 @@ +exports.file2 = 'file2/index.reg2'; diff --git a/node-v0.8.14/test/fixtures/module-load-order/file3.node b/node-v0.8.14/test/fixtures/module-load-order/file3.node new file mode 100644 index 0000000..f9d4784 --- /dev/null +++ b/node-v0.8.14/test/fixtures/module-load-order/file3.node @@ -0,0 +1 @@ +exports.file3 = 'file3.node'; diff --git a/node-v0.8.14/test/fixtures/module-load-order/file3.reg b/node-v0.8.14/test/fixtures/module-load-order/file3.reg new file mode 100644 index 0000000..41e5b9f --- /dev/null +++ b/node-v0.8.14/test/fixtures/module-load-order/file3.reg @@ -0,0 +1 @@ +exports.file3 = 'file3.reg'; diff --git a/node-v0.8.14/test/fixtures/module-load-order/file3.reg2 b/node-v0.8.14/test/fixtures/module-load-order/file3.reg2 new file mode 100644 index 0000000..902a0a0 --- /dev/null +++ b/node-v0.8.14/test/fixtures/module-load-order/file3.reg2 @@ -0,0 +1 @@ +exports.file3 = 'file3.reg2'; diff --git a/node-v0.8.14/test/fixtures/module-load-order/file3/index.js b/node-v0.8.14/test/fixtures/module-load-order/file3/index.js new file mode 100644 index 0000000..2d9936a --- /dev/null +++ b/node-v0.8.14/test/fixtures/module-load-order/file3/index.js @@ -0,0 +1,22 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +exports.file3 = 'file3/index.js'; diff --git a/node-v0.8.14/test/fixtures/module-load-order/file3/index.node b/node-v0.8.14/test/fixtures/module-load-order/file3/index.node new file mode 100644 index 0000000..451e075 --- /dev/null +++ b/node-v0.8.14/test/fixtures/module-load-order/file3/index.node @@ -0,0 +1 @@ +exports.file3 = 'file3/index.node'; diff --git a/node-v0.8.14/test/fixtures/module-load-order/file3/index.reg b/node-v0.8.14/test/fixtures/module-load-order/file3/index.reg new file mode 100644 index 0000000..b93aa80 --- /dev/null +++ b/node-v0.8.14/test/fixtures/module-load-order/file3/index.reg @@ -0,0 +1 @@ +exports.file3 = 'file3/index.reg'; diff --git a/node-v0.8.14/test/fixtures/module-load-order/file3/index.reg2 b/node-v0.8.14/test/fixtures/module-load-order/file3/index.reg2 new file mode 100644 index 0000000..4e1d9cc --- /dev/null +++ b/node-v0.8.14/test/fixtures/module-load-order/file3/index.reg2 @@ -0,0 +1 @@ +exports.file3 = 'file3/index.reg2'; diff --git a/node-v0.8.14/test/fixtures/module-load-order/file4.reg b/node-v0.8.14/test/fixtures/module-load-order/file4.reg new file mode 100644 index 0000000..1026207 --- /dev/null +++ b/node-v0.8.14/test/fixtures/module-load-order/file4.reg @@ -0,0 +1 @@ +exports.file4 = 'file4.reg'; diff --git a/node-v0.8.14/test/fixtures/module-load-order/file4.reg2 b/node-v0.8.14/test/fixtures/module-load-order/file4.reg2 new file mode 100644 index 0000000..62e1341 --- /dev/null +++ b/node-v0.8.14/test/fixtures/module-load-order/file4.reg2 @@ -0,0 +1 @@ +exports.file4 = 'file4.reg2'; diff --git a/node-v0.8.14/test/fixtures/module-load-order/file4/index.js b/node-v0.8.14/test/fixtures/module-load-order/file4/index.js new file mode 100644 index 0000000..0ded410 --- /dev/null +++ b/node-v0.8.14/test/fixtures/module-load-order/file4/index.js @@ -0,0 +1,22 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +exports.file4 = 'file4/index.js'; diff --git a/node-v0.8.14/test/fixtures/module-load-order/file4/index.node b/node-v0.8.14/test/fixtures/module-load-order/file4/index.node new file mode 100644 index 0000000..a4f7a0b --- /dev/null +++ b/node-v0.8.14/test/fixtures/module-load-order/file4/index.node @@ -0,0 +1 @@ +exports.file4 = 'file4/index.node'; diff --git a/node-v0.8.14/test/fixtures/module-load-order/file4/index.reg b/node-v0.8.14/test/fixtures/module-load-order/file4/index.reg new file mode 100644 index 0000000..e7c5fae --- /dev/null +++ b/node-v0.8.14/test/fixtures/module-load-order/file4/index.reg @@ -0,0 +1 @@ +exports.file4 = 'file4/index.reg'; diff --git a/node-v0.8.14/test/fixtures/module-load-order/file4/index.reg2 b/node-v0.8.14/test/fixtures/module-load-order/file4/index.reg2 new file mode 100644 index 0000000..c52c108 --- /dev/null +++ b/node-v0.8.14/test/fixtures/module-load-order/file4/index.reg2 @@ -0,0 +1 @@ +exports.file4 = 'file4/index.reg2'; diff --git a/node-v0.8.14/test/fixtures/module-load-order/file5.reg2 b/node-v0.8.14/test/fixtures/module-load-order/file5.reg2 new file mode 100644 index 0000000..651141c --- /dev/null +++ b/node-v0.8.14/test/fixtures/module-load-order/file5.reg2 @@ -0,0 +1 @@ +exports.file5 = 'file5.reg2'; diff --git a/node-v0.8.14/test/fixtures/module-load-order/file5/index.js b/node-v0.8.14/test/fixtures/module-load-order/file5/index.js new file mode 100644 index 0000000..9d3a033 --- /dev/null +++ b/node-v0.8.14/test/fixtures/module-load-order/file5/index.js @@ -0,0 +1,22 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +exports.file5 = 'file5/index.js'; diff --git a/node-v0.8.14/test/fixtures/module-load-order/file5/index.node b/node-v0.8.14/test/fixtures/module-load-order/file5/index.node new file mode 100644 index 0000000..07c559d --- /dev/null +++ b/node-v0.8.14/test/fixtures/module-load-order/file5/index.node @@ -0,0 +1 @@ +exports.file5 = 'file5/index.node'; diff --git a/node-v0.8.14/test/fixtures/module-load-order/file5/index.reg b/node-v0.8.14/test/fixtures/module-load-order/file5/index.reg new file mode 100644 index 0000000..75c2ab4 --- /dev/null +++ b/node-v0.8.14/test/fixtures/module-load-order/file5/index.reg @@ -0,0 +1 @@ +exports.file5 = 'file5/index.reg'; diff --git a/node-v0.8.14/test/fixtures/module-load-order/file5/index.reg2 b/node-v0.8.14/test/fixtures/module-load-order/file5/index.reg2 new file mode 100644 index 0000000..8200474 --- /dev/null +++ b/node-v0.8.14/test/fixtures/module-load-order/file5/index.reg2 @@ -0,0 +1 @@ +exports.file5 = 'file5/index.reg2'; diff --git a/node-v0.8.14/test/fixtures/module-load-order/file6/index.js b/node-v0.8.14/test/fixtures/module-load-order/file6/index.js new file mode 100644 index 0000000..9d890bf --- /dev/null +++ b/node-v0.8.14/test/fixtures/module-load-order/file6/index.js @@ -0,0 +1,22 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +exports.file6 = 'file6/index.js'; diff --git a/node-v0.8.14/test/fixtures/module-load-order/file6/index.node b/node-v0.8.14/test/fixtures/module-load-order/file6/index.node new file mode 100644 index 0000000..c77e34b --- /dev/null +++ b/node-v0.8.14/test/fixtures/module-load-order/file6/index.node @@ -0,0 +1 @@ +exports.file6 = 'file6/index.node'; diff --git a/node-v0.8.14/test/fixtures/module-load-order/file6/index.reg b/node-v0.8.14/test/fixtures/module-load-order/file6/index.reg new file mode 100644 index 0000000..5eeff75 --- /dev/null +++ b/node-v0.8.14/test/fixtures/module-load-order/file6/index.reg @@ -0,0 +1 @@ +exports.file6 = 'file6/index.reg'; diff --git a/node-v0.8.14/test/fixtures/module-load-order/file6/index.reg2 b/node-v0.8.14/test/fixtures/module-load-order/file6/index.reg2 new file mode 100644 index 0000000..391a008 --- /dev/null +++ b/node-v0.8.14/test/fixtures/module-load-order/file6/index.reg2 @@ -0,0 +1 @@ +exports.file6 = 'file6/index.reg2'; diff --git a/node-v0.8.14/test/fixtures/module-load-order/file7/index.node b/node-v0.8.14/test/fixtures/module-load-order/file7/index.node new file mode 100644 index 0000000..350ffbf --- /dev/null +++ b/node-v0.8.14/test/fixtures/module-load-order/file7/index.node @@ -0,0 +1 @@ +exports.file7 = 'file7/index.node'; diff --git a/node-v0.8.14/test/fixtures/module-load-order/file7/index.reg b/node-v0.8.14/test/fixtures/module-load-order/file7/index.reg new file mode 100644 index 0000000..bff6ec3 --- /dev/null +++ b/node-v0.8.14/test/fixtures/module-load-order/file7/index.reg @@ -0,0 +1 @@ +exports.file7 = 'file7/index.reg'; diff --git a/node-v0.8.14/test/fixtures/module-load-order/file7/index.reg2 b/node-v0.8.14/test/fixtures/module-load-order/file7/index.reg2 new file mode 100644 index 0000000..a4e1093 --- /dev/null +++ b/node-v0.8.14/test/fixtures/module-load-order/file7/index.reg2 @@ -0,0 +1 @@ +exports.file7 = 'file7/index.reg2'; diff --git a/node-v0.8.14/test/fixtures/module-load-order/file8/index.reg b/node-v0.8.14/test/fixtures/module-load-order/file8/index.reg new file mode 100644 index 0000000..278d047 --- /dev/null +++ b/node-v0.8.14/test/fixtures/module-load-order/file8/index.reg @@ -0,0 +1 @@ +exports.file8 = 'file8/index.reg'; diff --git a/node-v0.8.14/test/fixtures/module-load-order/file8/index.reg2 b/node-v0.8.14/test/fixtures/module-load-order/file8/index.reg2 new file mode 100644 index 0000000..5522829 --- /dev/null +++ b/node-v0.8.14/test/fixtures/module-load-order/file8/index.reg2 @@ -0,0 +1 @@ +exports.file8 = 'file8/index.reg2'; diff --git a/node-v0.8.14/test/fixtures/module-load-order/file9/index.reg2 b/node-v0.8.14/test/fixtures/module-load-order/file9/index.reg2 new file mode 100644 index 0000000..c747b1e --- /dev/null +++ b/node-v0.8.14/test/fixtures/module-load-order/file9/index.reg2 @@ -0,0 +1 @@ +exports.file9 = 'file9/index.reg2'; diff --git a/node-v0.8.14/test/fixtures/module-loading-error.node b/node-v0.8.14/test/fixtures/module-loading-error.node new file mode 100644 index 0000000..323fae0 --- /dev/null +++ b/node-v0.8.14/test/fixtures/module-loading-error.node @@ -0,0 +1 @@ +foobar diff --git a/node-v0.8.14/test/fixtures/module-require/child/index.js b/node-v0.8.14/test/fixtures/module-require/child/index.js new file mode 100644 index 0000000..6c2fd4e --- /dev/null +++ b/node-v0.8.14/test/fixtures/module-require/child/index.js @@ -0,0 +1,2 @@ +exports.loaded = require('target'); +exports.module = module; diff --git a/node-v0.8.14/test/fixtures/module-require/parent/index.js b/node-v0.8.14/test/fixtures/module-require/parent/index.js new file mode 100644 index 0000000..e174cba --- /dev/null +++ b/node-v0.8.14/test/fixtures/module-require/parent/index.js @@ -0,0 +1,5 @@ +var child = require('../child'); +//console.log(child.module.require, child.module); +console.log(child.module.require('target')); +console.log(child.loaded); +exports.loaded = child.module.require('target'); diff --git a/node-v0.8.14/test/fixtures/msca.pem b/node-v0.8.14/test/fixtures/msca.pem new file mode 100644 index 0000000..247368e --- /dev/null +++ b/node-v0.8.14/test/fixtures/msca.pem @@ -0,0 +1,15 @@ +-----BEGIN CERTIFICATE----- +MIICWjCCAcMCAgGlMA0GCSqGSIb3DQEBBAUAMHUxCzAJBgNVBAYTAlVTMRgwFgYD +VQQKEw9HVEUgQ29ycG9yYXRpb24xJzAlBgNVBAsTHkdURSBDeWJlclRydXN0IFNv +bHV0aW9ucywgSW5jLjEjMCEGA1UEAxMaR1RFIEN5YmVyVHJ1c3QgR2xvYmFsIFJv +b3QwHhcNOTgwODEzMDAyOTAwWhcNMTgwODEzMjM1OTAwWjB1MQswCQYDVQQGEwJV +UzEYMBYGA1UEChMPR1RFIENvcnBvcmF0aW9uMScwJQYDVQQLEx5HVEUgQ3liZXJU +cnVzdCBTb2x1dGlvbnMsIEluYy4xIzAhBgNVBAMTGkdURSBDeWJlclRydXN0IEds +b2JhbCBSb290MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCVD6C28FCc6HrH +iM3dFw4usJTQGz0O9pTAipTHBsiQl8i4ZBp6fmw8U+E3KHNgf7KXUwefU/ltWJTS +r41tiGeA5u2ylc9yMcqlHHK6XALnZELn+aks1joNrI1CqiQBOeacPwGFVw1Yh0X4 +04Wqk2kmhXBIgD8SFcd5tB8FLztimQIDAQABMA0GCSqGSIb3DQEBBAUAA4GBAG3r +GwnpXtlR22ciYaQqPEh346B8pt5zohQDhT37qw4wxYMWM4ETCJ57NE7fQMh017l9 +3PR2VX2bY1QY6fDq81yx2YtCHrnAlU66+tXifPVoYb+O7AWXX1uw16OFNMQkpw0P +lZPvy5TYnh+dXIVtx6quTx8itc2VrbqnzPmrC3p/ +-----END CERTIFICATE----- diff --git a/node-v0.8.14/test/fixtures/multi-alice.crt b/node-v0.8.14/test/fixtures/multi-alice.crt new file mode 100644 index 0000000..db57385 --- /dev/null +++ b/node-v0.8.14/test/fixtures/multi-alice.crt @@ -0,0 +1,22 @@ +-----BEGIN CERTIFICATE----- +MIIDnjCCAoYCCQCXooHS0l6bHDANBgkqhkiG9w0BAQUFADCBkDELMAkGA1UEBhMC +QVUxEzARBgNVBAgMClNvbWUtU3RhdGUxITAfBgNVBAoMGEludGVybmV0IFdpZGdp +dHMgUHR5IEx0ZDEfMB0GA1UECwwWSW5mb3JtYXRpb24gVGVjaG5vbG9neTEUMBIG +A1UECwwLRW5naW5lZXJpbmcxEjAQBgNVBAsMCU1hcmtldGluZzAeFw0xMjAzMDQx +NDA4MDVaFw0xMjA0MDMxNDA4MDVaMIGQMQswCQYDVQQGEwJBVTETMBEGA1UECAwK +U29tZS1TdGF0ZTEhMB8GA1UECgwYSW50ZXJuZXQgV2lkZ2l0cyBQdHkgTHRkMR8w +HQYDVQQLDBZJbmZvcm1hdGlvbiBUZWNobm9sb2d5MRQwEgYDVQQLDAtFbmdpbmVl +cmluZzESMBAGA1UECwwJTWFya2V0aW5nMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8A +MIIBCgKCAQEAz+LXZOjcQCJq3+ZKUFabj71oo/ex/XsBcFqtBThjjTw9CVEVwfPQ +Qp4XwtPiB204vnYXwQ1/R2NdTQqCZu47l79LssL/u2a5Y9+0NEU3nQA5qdt+1FAE +0c5oexPimXOrR3GWfKz7PmZ2O0117IeCUUXPG5U8umhDe/4mDF4ZNJiKc404Wthq +uTqgS7rLQZHhZ6D0EnGnOkzlmxJMYPNHSOY1/6ivdNUUcC87awNEA3lgfhy25IyB +K3QJc+aYKNTbt70Lery3bu2wWLFGtmNiGlQTS4JsxImRsECTI727ObS7/FWAQsqW ++COL0Sa5BuMFrFIpjPrEe0ih7vRRbdmXRwIDAQABMA0GCSqGSIb3DQEBBQUAA4IB +AQC7kyzjGXy7SnT1tvefdvtdAtErDuD375/sB2l1V72+BNXlIlddmEC8IkAVSKg2 +5Y7MuQ4yMsHlhrdUxj/XOOVMHY/49xsZiN5hF2jb2mdq7KdvlVMYqyf126bW2mOx +cLVSiuucdp88zoJopWBUnNyVOYhh18St9bNosGgPzppGBCpL+MJvoSn3wrnFn8ER +wwN1m3ga590wHa4fny+qlD/hJNww16wbwgdF9NqsuR/e+sj9ZsoIYRCF8iKBajzt +3o7cZIRlvGtJfJRM87YCAn4BR3JgQPXfbhx31KwtMXtAJNzOHk26bblW3jTC8c7+ +Cu1gNEM083vUq6/UxJUM8lOM +-----END CERTIFICATE----- diff --git a/node-v0.8.14/test/fixtures/nested-index/one/hello.js b/node-v0.8.14/test/fixtures/nested-index/one/hello.js new file mode 100644 index 0000000..c0c8c4f --- /dev/null +++ b/node-v0.8.14/test/fixtures/nested-index/one/hello.js @@ -0,0 +1,23 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +exports.hello = 'hello from one!'; + diff --git a/node-v0.8.14/test/fixtures/nested-index/one/index.js b/node-v0.8.14/test/fixtures/nested-index/one/index.js new file mode 100644 index 0000000..9beac59 --- /dev/null +++ b/node-v0.8.14/test/fixtures/nested-index/one/index.js @@ -0,0 +1,22 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +exports.hello = require('./hello').hello; diff --git a/node-v0.8.14/test/fixtures/nested-index/three.js b/node-v0.8.14/test/fixtures/nested-index/three.js new file mode 100644 index 0000000..dcceb09 --- /dev/null +++ b/node-v0.8.14/test/fixtures/nested-index/three.js @@ -0,0 +1,21 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + diff --git a/node-v0.8.14/test/fixtures/nested-index/three/index.js b/node-v0.8.14/test/fixtures/nested-index/three/index.js new file mode 100644 index 0000000..dcceb09 --- /dev/null +++ b/node-v0.8.14/test/fixtures/nested-index/three/index.js @@ -0,0 +1,21 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + diff --git a/node-v0.8.14/test/fixtures/nested-index/two/hello.js b/node-v0.8.14/test/fixtures/nested-index/two/hello.js new file mode 100644 index 0000000..339276c --- /dev/null +++ b/node-v0.8.14/test/fixtures/nested-index/two/hello.js @@ -0,0 +1,23 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +exports.hello = 'hello from two!'; + diff --git a/node-v0.8.14/test/fixtures/nested-index/two/index.js b/node-v0.8.14/test/fixtures/nested-index/two/index.js new file mode 100644 index 0000000..9beac59 --- /dev/null +++ b/node-v0.8.14/test/fixtures/nested-index/two/index.js @@ -0,0 +1,22 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +exports.hello = require('./hello').hello; diff --git a/node-v0.8.14/test/fixtures/net-fd-passing-receiver.js b/node-v0.8.14/test/fixtures/net-fd-passing-receiver.js new file mode 100644 index 0000000..8e0ba14 --- /dev/null +++ b/node-v0.8.14/test/fixtures/net-fd-passing-receiver.js @@ -0,0 +1,53 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +process.mixin(require('../common')); +net = require('net'); + +path = process.ARGV[2]; +greeting = process.ARGV[3]; + +receiver = net.createServer(function(socket) { + socket.on('fd', function(fd) { + var peerInfo = process.getpeername(fd); + peerInfo.fd = fd; + var passedSocket = new net.Socket(peerInfo); + + passedSocket.on('eof', function() { + passedSocket.close(); + }); + + passedSocket.on('data', function(data) { + passedSocket.send('[echo] ' + data); + }); + passedSocket.on('close', function() { + receiver.close(); + }); + passedSocket.send('[greeting] ' + greeting); + }); +}); + +/* To signal the test runne we're up and listening */ +receiver.on('listening', function() { + common.print('ready'); +}); + +receiver.listen(path); diff --git a/node-v0.8.14/test/fixtures/not-main-module.js b/node-v0.8.14/test/fixtures/not-main-module.js new file mode 100644 index 0000000..0bee402 --- /dev/null +++ b/node-v0.8.14/test/fixtures/not-main-module.js @@ -0,0 +1,25 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var assert = require('assert'); +assert.notEqual(module, require.main, 'require.main should not == module'); +assert.notEqual(module, process.mainModule, + 'process.mainModule should not === module'); diff --git a/node-v0.8.14/test/fixtures/packages/main-index/package-main-module/index.js b/node-v0.8.14/test/fixtures/packages/main-index/package-main-module/index.js new file mode 100644 index 0000000..c361a6d --- /dev/null +++ b/node-v0.8.14/test/fixtures/packages/main-index/package-main-module/index.js @@ -0,0 +1,22 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +exports.ok = 'ok'; diff --git a/node-v0.8.14/test/fixtures/packages/main-index/package.json b/node-v0.8.14/test/fixtures/packages/main-index/package.json new file mode 100644 index 0000000..13a7d58 --- /dev/null +++ b/node-v0.8.14/test/fixtures/packages/main-index/package.json @@ -0,0 +1,3 @@ +{"name":"package-name" +,"version":"1.2.3" +,"main":"package-main-module"} diff --git a/node-v0.8.14/test/fixtures/packages/main/package-main-module.js b/node-v0.8.14/test/fixtures/packages/main/package-main-module.js new file mode 100644 index 0000000..c361a6d --- /dev/null +++ b/node-v0.8.14/test/fixtures/packages/main/package-main-module.js @@ -0,0 +1,22 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +exports.ok = 'ok'; diff --git a/node-v0.8.14/test/fixtures/packages/main/package.json b/node-v0.8.14/test/fixtures/packages/main/package.json new file mode 100644 index 0000000..13a7d58 --- /dev/null +++ b/node-v0.8.14/test/fixtures/packages/main/package.json @@ -0,0 +1,3 @@ +{"name":"package-name" +,"version":"1.2.3" +,"main":"package-main-module"} diff --git a/node-v0.8.14/test/fixtures/parent-process-nonpersistent.js b/node-v0.8.14/test/fixtures/parent-process-nonpersistent.js new file mode 100644 index 0000000..a71d1a3 --- /dev/null +++ b/node-v0.8.14/test/fixtures/parent-process-nonpersistent.js @@ -0,0 +1,13 @@ + +var spawn = require('child_process').spawn, + path = require('path'), + childPath = path.join(__dirname, 'child-process-persistent.js'); + +var child = spawn(process.execPath, [ childPath ], { + detached: true, + stdio: 'ignore' +}); + +console.log(child.pid); + +child.unref(); diff --git a/node-v0.8.14/test/fixtures/pass-cert.pem b/node-v0.8.14/test/fixtures/pass-cert.pem new file mode 100644 index 0000000..1b355a8 --- /dev/null +++ b/node-v0.8.14/test/fixtures/pass-cert.pem @@ -0,0 +1,12 @@ +-----BEGIN CERTIFICATE----- +MIIB2TCCAUICCQDQv9q5AAtoEzANBgkqhkiG9w0BAQUFADAxMQswCQYDVQQGEwJK +UDEOMAwGA1UECBMFVG9reW8xEjAQBgNVBAoUCW5vZGVqc19qcDAeFw0xMTExMjYx +NzA0MDhaFw0yMTExMjMxNzA0MDhaMDExCzAJBgNVBAYTAkpQMQ4wDAYDVQQIEwVU +b2t5bzESMBAGA1UEChQJbm9kZWpzX2pwMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCB +iQKBgQChmQeFwsaomtQbw9Nm55Dn6KSR9bkY8PDroQUeTNa90BlIbhGsKYm4l7bE +RaasFgOrkcQpk45fdDVYPjKxraZiGXXKjSIDYeDAIC/+CkwQKrejgCPmJs4gV4g+ +npvwi1gVr2NAg7fkJOyEW2TDp4dsAD8qtG8Aml0C1hJXwFYmBwIDAQABMA0GCSqG +SIb3DQEBBQUAA4GBAGJYkr3VgHUZSyGrdUWeGKiKS4EY3D4ki8Luv9Jf/IpxJLbZ +NGaKUbXSVYSW3US0yR1+lsNvWchmc0wLsbNEHbIiS4BQPkqX7F8FCthM1gwRLQPa +Sofz3dRNFKDmivG9mdbQDPD/duft7Kn6E3JS5myYUJ0dRKeYfOXLXCY2pZpG +-----END CERTIFICATE----- diff --git a/node-v0.8.14/test/fixtures/pass-csr.pem b/node-v0.8.14/test/fixtures/pass-csr.pem new file mode 100644 index 0000000..8436f51 --- /dev/null +++ b/node-v0.8.14/test/fixtures/pass-csr.pem @@ -0,0 +1,10 @@ +-----BEGIN CERTIFICATE REQUEST----- +MIIBcDCB2gIBADAxMQswCQYDVQQGEwJKUDEOMAwGA1UECBMFVG9reW8xEjAQBgNV +BAoUCW5vZGVqc19qcDCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEAoZkHhcLG +qJrUG8PTZueQ5+ikkfW5GPDw66EFHkzWvdAZSG4RrCmJuJe2xEWmrBYDq5HEKZOO +X3Q1WD4ysa2mYhl1yo0iA2HgwCAv/gpMECq3o4Aj5ibOIFeIPp6b8ItYFa9jQIO3 +5CTshFtkw6eHbAA/KrRvAJpdAtYSV8BWJgcCAwEAAaAAMA0GCSqGSIb3DQEBBQUA +A4GBAC9g7s3rG6G7JSTUOizY1u9Ij6QM9Y6PqQthr4OJHa+Hln5FJQahpgJmA4kC +WYoWvBMBgFPFBCYAj0yMPohrlAwlbd9MADe4gg3lxuO9UxXDzp/lOVRBAEa4n5i+ +Lw7VEiJtPha4NXgeNzxi5OyBJwxAOPFwsyCdR0SynlifTFHI +-----END CERTIFICATE REQUEST----- diff --git a/node-v0.8.14/test/fixtures/pass-key.pem b/node-v0.8.14/test/fixtures/pass-key.pem new file mode 100644 index 0000000..9a0c5f1 --- /dev/null +++ b/node-v0.8.14/test/fixtures/pass-key.pem @@ -0,0 +1,18 @@ +-----BEGIN RSA PRIVATE KEY----- +Proc-Type: 4,ENCRYPTED +DEK-Info: DES-EDE3-CBC,CE30CF10CDD3C074 + +A9Vjoxw1Z6pfyxMHXxDi88JVcLN0uWJAjo97nsdzV1cYmEk4bQUe6XVu8UGCzbYX +1RVeglOwyKfp631l5j5KHNfzA4lEU46uqAkRZbkzaHg6sVK7nuSBamiDqkO+BSEU +kDCDqImcx+wUXjlFsYc2UO3DJen8QVEVYQthpxqS7UGh6SCGKyb8FzHu+nzOtRrZ +y2Y9r8vyllH5+qxyGymkJJgPGYd9a/q3uTjxjBsb252SC6JEMt/njXdtlt3zUCQl +8aEok8xXIyDFsrhkQ1chXYt/neWdgVh+R9HulVvSLKkACSfX19F2ooIIWhoml4C1 +VE9iX7wytbD7LxLK4kWQL0sRi0MQPwBEag6m9K6skcsN8qIRJwJZeevc3xw+08uI +IqUL4Ouy+eNMYQIxxgKBcgVWV51X1HWCcwjBkDp9x/qU+URKBmGcpTKEiOrKGG/I +8JN3IreJU5EhtGqE15J4ep/hS4CwJ9+CFysRs0vFCw24GS+O2CXWT9rgza4VX1we +dUVnGGodJcXgAf0sNECm8zYk2fjy1SICm+fknsN466d2pmCO43/WpBhZyjbLEHsJ +a5pUVQroZdU2W70eGh2yIGVrMmgVbYPitTBafruW8w03oarG4XWA4caEmJMEVC68 +WZxuQ1Wg1J+fNl+Klq3b+4yImmoFrelh2gBANwYKnE9Z+JLtfv01et9DNOXR2DQM +6pPzrL0JUHetqko4mJTVNvW8h/Jv+0UVwmxmwm6mR4IBcKwQyY5V5VqeFfnXlvM1 +xpg33AEKNquAPC8G4pIHwG4aBo9fLp+I3cxPuY6dnR6i2tyQ5ONvvw== +-----END RSA PRIVATE KEY----- diff --git a/node-v0.8.14/test/fixtures/person.jpg b/node-v0.8.14/test/fixtures/person.jpg new file mode 100644 index 0000000000000000000000000000000000000000..4f71881c5584d824d5993245c839fff1c9636544 GIT binary patch literal 57928 zcmbTc1yo!?wl;bicXxO9;O_1kJV@j25G+`5r*Q}t90CLlgoNPk1P>nE3C`=x+&44- zUF+WW)?eLS=R3Q0_1U${zS`X{KVNb0Q}72-Gm10Vwk05B#E>(4-_ML*)ro z`iuXaZsq~#Hvzy5yP_r))xYKczYw;Sn}-(wfHa}nudKnIR!|%P#ZJCnZhz%xP>g5k z_!q;#{ly+o1EHAcFSh+BX8VWEKe6OrZ0+n~4b}N;vzxWE^r_;R(4R#1;uC{y4o^OED8WfXtw`>E&l_1 zf&HL%0)ULGo4<#>t(_MYlNB=+w~&w^l_J>J3GC&?u4!TAXyIW^CFAPsX5r!w0RL?B z-&z39U*A$eoy^ZI#Lv&p!vS^wztaC&_%E&h9sKRve`;K6{iDx71f&0!{k!hJWv;~l zAb1V+P4d5Gme~N%8VLYIOaGS9eEcAw{2ecLUS4j(oSeSCz8v;oD~`Vo z{a5<`RQQ+X{|x@)c^rSA_b=a3$%1Vxyq&zL{yNpl)ydV{gUZv*!U{~q{@(}j|8>Rx zFzY|;VABTMfIYx2&`0S*N145gEwsB`tnIz*U0tZ`UH+#Y{=cmDA2$4j{~Xs)fLripniN1wK>zADRb+kO@60ox-23Oahhk{?Kl1-0gGqwk!g$)- zQvDUnXzNm0d3*T$#n3tNH-iUI089W6AOfVPIj6F;N0PY;o{+P;40u+;CkU^;5OjS;GW^p;mP1x z;f3Lq;9tYr!u!HU!9(Cb!Z*YB!Oy|(z~3MsAP^uhA_yQTA{Zh#AiPD0N61I0NBD*? zg|LNijfjXyjL3>8hNyvPf#`)8g_w<4gV>EYjktq&i-d|qiNu2>k7R`8f)s`XL8?Of ziZqS1hxCAqg-nkujI4odjqHz{gj|Z;fjoh{gZzMkjlzf`hN6q&fbtF{3#AUF4`l`A z5)~Dd22}`E3)LPq6g3O=6Y3!92I?Ie4jK!Z44Mg=H(DZEIodb0MYKzFbaV!ENpvH0 zFZ4w8O7tJ-Yv{KaxELH5N*LA{AsD$BEf~`nCz!~X^q5kZW|#q(5X>gb3CtrbWGn_O z87vE|V60rMcB}=gYiwL>Zfp%~XY6?FD(oTb-#Cak3^;N));JM3B{)BDws2u_X>nz6 zt#HF}OL6;fckmGK81aj9f?zjTZvam;7C|Vv`BnO z3P}1$j!5xHMM$kkV@VrHm&jnqSje==-jbD&jgnoHQ;;i=yOC#;{~$l2AfS+>aG*%1 z_)4))iAyO?X-}C>*-d#sg-<0#k4!H}Z%3a=KS2M7fsw(0;XOku!*50+MkU4o#%jhD zCUhnVCU>S{rdehLWJ6Eqezv=Z&5~3uxP31mKcqgg;>IKa*(Q#I+5m*_KMWO^alQo!JDc#j}{sh#TM6=N|t$+XI3&+nO29^ zlGf?g`(QC}DtOOE%qG?5x2>3Mn(e-wgdN20$X>=i$NtdoXG>Am42 z?vv|t>#OhEcDq_8$nV*MZut8%ix|6+K`Bl zolu3)igzgQ9N&$FafPLZU4oC#YRjg}PR@SJvCEmumCmitBg>1)`;%{-KV2YMP*+G^ z7*}}z!T!U~B88%sVuoT!2||fa$!@8B=|GuaS>;EPk8vNL%3aETRcKfARti*BR*_XD zRl`(!SMS%D)J)dO*0$BL*A>+h)W>}SK6!sSXn4~w->A~q(8t5Jr8|)ks9%>&J9Bv)qA88ro8*Lur8*3itA8(lu zm}r|6n(UYoo%%X0G5vi;cBX$;X?A2zeQs)AZ~o_k$-=Ln)<1tQIxU_r`7Avwhpxb{ z#I9nkLe|LEir1Of>woe8>e`Uq7~Ry_T;8(UI^6c$e%y)JMc;+&QSMd#=K0;ZFTX!| zV0^H1=yv#U6m^V!oOi->^7&NqboA`?+0MDg`O8K8CGlnX74KEgwdVEOjq}aJpV(XC z+lo8EyMcRy`@IL>N5sdhC+4S)XO-ub7w4Ckmt*BTO*>aFS5G@vH>y`0T!5gok{ays zUt$1YL3i)JoC5U!UjLTC{ev_BCS)*BS^>b2!4Lxo7FK@=(qD*TFVnB7b5)=a&!OVIe&RPptSxE3jpBTKgkV@ zBmjLwAj)qQzg++vifq{YdH^acg{)Za&KQCzib@}gA|9SuN z4Zuc%a!R4 z?0=R*1+Z}N2>&R=0$@O}urP2i2#B!I48{`#1B(p@z*FOJOKBnCTF|(^!{bRQLd0*7 zrv0uxwegC;@{G=Gv+3hQ^cVtFcbKl&~wT({{55mq*G2#C$8>KI-+xQ8|$25KcdJhTmPNU*TZ(Dq=% z!u_=vUJGh5g8RD^o}z{`yzf&Rw9@$6mLBJ?=y+wq2vT+Ei>(@a5Iv{)Hf6&JbPQx?$ra%Jh8MHw&0P0d_IR~?KZYkX!_WQY=(wqIpUAt&f%MgDRi{yK3S$hN32 z8Ycbz48qOtyjxISK_sCq7~w}$JKEeHHxIuPuPRJmPXEdM=~UuAoufQ93!~lpUJ^bkoX?ab2D2u0(v0=j zM&BAoy>z=9rk%ImbQ@I@>Xm<_!LUEaxEkq~K|;C4SwRM&@6Pzmd!h@(Pp~GMz+;;B`!S{xUyPI&+j|D~H@U63eMH_Dcb&IvaZ}it4 zwHMO+F;(`20_sK^vdGRT33nY87`=(q`nAvc2HjYw$rbA*n8QNIA1KS{%9wSYGnm%d z3-y0``u{naDR0qU8R@Kc`!W1%*@}ZzTfRDISvL^xAOuQ%zwqpsz;>H@ne( z33o4-n^IoZhAp};-%grM!c0pW7F#zvDk@5M?=N_^a+Lep%>FVc;AFVhlxNhrj)dPf zB}cfb$#W%8X7j0jdE`8oAx!E7`Q)7=d~<0^52GFq){w_3ErKR!b3%KlWq=LT2ona5 z%o*GZQ}9ZZ^Nl`F(R;@dFcrEVTi<6I+ll(@L3_z>N0&Rq-!gcnMy74P(%|B~H>yBH ziUO~1BV;Y-GDmBZ^=S6yQXrFIitVu(`*V`PWUcFUeO1*MZ?Yr|-zd_C9!Ib3mL&bP z-=l;rM1>l^BO#64Yhce zXx-t?5+Iu#waLe4lz(8bc_6Y|%^__qC)g-bv>W?9Vksgx@BCaxmfG5d@nKC_rkY)x zGwx_x^?QuYT2c8ZLyqFuegb}%Tte2xay=pA=2O}LbA)2XpmsS)Ttl;P{P$7Cogz)+ z=)^oFYL->RDDVMoA2#)q>!o4ApK*!HRBbu2-2~nsy896`+zP3Mdw{+EtLLgZ&c!j>lHjhGOk0-XI%Sfad(Ly8G-wt8|l&7+$Jinhn^@O_B zBg!G_c5qyHj^+_L2HundSOUm}bS@W{4%tTjF+EB(GBIpCD=w;EM9Q&}e0ewG=Qv!_k{mANuIGkcr6A(TNy zZ!krMY1nY#y7zvL#&y~k3!=G}wic+OWk!b*yY0mND>I<`*6MPH-_%Iw#04*@&;3&; z&gmP9w~tMaOQ`Pkjym+iGV%~lnpfxL81E3R1}LZoC9kE7p0%Hy4{!8I;$Yd_jTH!T zSygGhnt`k-F)pTbmluG5u5rVw@G@yVTW(~?I#p3k<-Rj3ZLQSGQ4w9|!hGT$oZkA! z$diqrdTjOeD?lP0{e010WiWs+_c|y5`6?pk z(Jp|=`R;V%Hi6#NIYF9^9a@7gNr|n;Tc#1E!nKi9Y9v`cVSbsWUt~MEYH64LWLdTU zZQ)N)*Yg7B($KH3=*#Y%X~P~G7++v}R_IDXXKO*)m>Y?%rFA;{)`fXYKV&boTyE|& z)jBjVjN|WR%*2%p(&x-a#Z8iKa#V~cGceD3Jq=5|iApKc1+=yNIO={SGcB(v3y7VK zR67ZEuAqfmaa?#2V(z>EJc{@Up94(Kb{<4WS?tXzXwe*d$*;C1plj%Ky3_}UOfCDH zg+C3!kJygR?mWF`tqj{mrv8#qDpdDNL#YC^-2yyHbp*XfD2&J^1$yDh$dmpsDDRhSJbRzGU2?U4&^uG z%hQMK99y{s>D$xlkuu@^#MTttX$wsV9TiQw%wd|D_^OJgqV*e?-YKjj`yEWAb z4C``sX2BQZmF3GOuS-#5PbOH52-Yp#p82_bvs?*`8!0}o#SA)Ao5AHvl|U6|f3 z{OUC)B5|vAWyi8Xt(~ zx2cm6&V@&BEju+SEA=Ap_K+o0LKqDB$T6^8@lr^0J*JhUf5g@=o-R|T&;B5$)RaE3 zl(^F&$zUGiOC?$eI^BKPQJ32r+((c<_Wx0Ret>c8Q?0b)b= z+>&YtDP(3TUuFa^mWHZL$@mV%uuzxbIEtTuP(m zo2$Q9RUDFwaU^Zf_gPCd$E$OJOkx|<&+ANa7B%sVT|TCR~yie^y4Y9=HdTPiXEVTB>%Vq@MM4ZHFk znwj*O^HOaFID%k`VV^1a$1rhBGM9Tn8zh5lLhx30>t!QOd-anT0lmlcMR!cJFj_^2?N>QT!J@VdnkQC$zV?Co(%o?KX%fczm^!X0gp zj)9tk6cPEmSvq#}Zo1&&Rl@Yx8Cb@mVDllEJIrxKjnlQBqkeJ9Ms^L353TMuh6Z=- z*2O`(Gqhh`W-%RW4hbCI#87oKM$#o|e9fSXPCfx)-(XU5MhN_|zj3nS@~-lOtp(8$lKjSxmK0x$~i%h8QehugQ@8 zkryn&;(EQ4qLcFlMVr`1wB?%crZEvM>Pa$$&+cS|o%aycksxu}T>6HpW!hXg+j{p~ zAoX@Rk7H9%-Vk8gdCxb-@?>G#grTY%JY-Y24irM`lc zkE2?*+Pm_kh->+X!HY?00!WQJ7C(A*zU+Iy0Bq~__YnjaCT9DdNj1Zo>BZBrR}3E( zj^9K{`he5WLchk(Ji8y*=9*rTm4*cMJ9l7e%ex^y5}0j?{lNEOInr~iu#lN)|0Y*W zIa}Ofh{faCWClRG2_-a+RjyVzJS3EE7rWr+5mf6;1^uWqkhx5n&8((!B65Y%t4)>FTilur4vST_kG!A zZ-2(?;0jpKTIBP>1LaN+{UNAW0lEmy30!J_taMp`_;SK8e<~0mj*a7Mv1IwJWvDmj zR}!giqLcgR|Bi-1>R@Zci|=EtqpcP3yi*GMN{Wj`irE>jvKSXVe8DP-#{9FkY4I6Bdim51)P;9K#L-~r0$XdE{3XFXLmjY8uXWrFDEGjGxs3T&1ZmK&^?i%Fhty z&U{z?>?*aY0}m;N#@I=*_}CfQ=w7Y>y%KwjmEZ-uQM5}K>3b10EC!Jf++e$l^7Ptf za!#qKYmuSrFSaj$+V!3G1{jPznY8*y);1+!d;Dl9h&{b4&BiO+({^V6I$-du2vcC0;d=j?gLT$@}9{#>NrPYM_PIUHk(To+}i$l~# zkd|YkBu3pF6h4$NUo}qL4SKu)C8BXd;VF(4Q{QV9s$FGFpYxiOU5VH%ndrOI{|KWv zEXfKu3}~iqQc5egVttlI#BLCMcbGDaoP1*GvOHHIL3?_T&S(^jAzb)}=DO~6aPb<2 z)>2lZt(o*E-;0o3Z{P($6ZSqrCl_gMrJAds8o&y&C^pv&d6`eY+mdP^amg)zJuOmL z)o3C^E02>h+lYYvtwT{LP$9MMjZF+04ejiV_^)qQwer3x#YzeS?`LdMOZ%fcv126d ziYgx{M>6_>xPv*lLc`w|Jv6O;B^_<|U&NYmR6NcD3cFHE!-(7Q-zP1{e4SV{`6_r% zFhyA8k8^YI^ME8UUhTO0K6O8;&MGeSs#gc6p_MapX~aF1&HLGrDKjHD@DLQZzFl4U zq?eSO-zB#tIn%qM7cxkR3T_Y~wZ=GNy$sl=f9$^m8O54Z6hUW?M>dycPuyvwu~|4) zMLrGg*nXEfTxR*R>2ISN$o+g-xeQ}He5b}441u{?f_@j;JLIjb`>a(VBl{G)Ze|mE z;iO%P1b6hXpWj`1h+$cnwu_rNFd1)KZ_ljoM_a)8iMk^%039r6e&Ou6E!4lAJI2Dtt&AnK?rF(c7OJXKR6F^uWfiwC&xNiJ(k|s zKSp(%U6zr#aZ7JfBYSNz$2Z-4%DC@C#&I3dKKJ?Igqf}pk!D(;ykwNPIK|pbSC34u z+Y!z}rf!H7L5XnpeKI(~>BE=LGe;j0=Q!21GFW!&A~Ja%mE<;KqJd-G77FIOjlFtK z$7j0+67Xz-^G5;&Hr0Iv>ttT-{OxV=>DE6^ojij*?=G!jaW4^bt{lf)?oXBs!L4oS zqUz`AmN1dk%#2B@f<@o4DR!`nl>9E?BLli0F>iL_l%itl_Pfj2ek^w#WT&W=Q=a;h zxE+Yk1-h$=LoN)q2Qscn7n{FS(dVXLeSR$tACrMdO&ewDFz3Rwew0h9h-uz3?e(C7 z|EcL6yR)ViO*EX=6@c?ZS zxu;WsG1|z*{fthBdquVpE1za0vE4L@fn|slXNnyt<*t65gfpW?`$6BHU`Yv1v_$&K z2mU>kutCfqJ@s_AuxNPY`ggFaKh2oicdQX&*~(`d5e`&+<9kO1iSsAd7l2mhenUUk zWXhoS>C+2P06l!05Y)Jie)XJ!Z<0eOLX>mW7Ku&|Ys6@Fjgb?lf2!%5wdRxL8`gk( z0rE2EKOZZ3F*}`T?`^j2p0}k0Fw7xVh=AML`DM~ZI^Q|NFXYrxw?PDp!0AoH-?7|d z5|2DcLRFEF#;zJeCRCny_LMG+UYoKHw!YUkv^zNI{1~28IdBAlX%~h0088Yd62gA8 zaleyT=5}66aJkILV1q$Y^zK7( zD!0e@@yXq0EU+N6e6YYiLpqnp`2;SZ&mY;g<(D|i#pZYMiNzk!COXe9G+r@z=^-i= zj6tpRl%rW#f<%3^s!unKO`HwOQetFxrpv+PpvOt+XI2DOA zt>&c6KE0@dresGoMp=yHtgiQos0`g}K{inD-n~rGb*OSj`H84V-d}0DHtj}lhYBM% zCA5@^gK2)8NLR-#*bkAnKoO~@(h`81E+1g{o^3}nc9d)~M&tHt2oBp5BJ<2b$ zqKQ%yzgRwKZ3(a@iR`6Et92&wM;%1LTDKI4+cb|9r+bjF#QvLX{;6$ z_$hc-PcBjutCWicOmCcu)5+BB`ef2m@F`hVYSZx?Q%+|hm(Mz z5-&gH&KPklPWdwYc-6wZhi=MyR&C8;Vq7Iptyvtt5l?{B{J=VLw5uwfGS?!SDm+7% zG3-`7C&A%t**Zz_OIV40G)f8k^(&T&&8lxMn8zWFeazcNC4Ck0=iG)?_z7RaHCZpe zWlnw7yF_THzYAcDqG@IBO!K%UN{B`biR<&If*frSncWmF@t3+(^170Yu2T$4f+QvdBz%F-h)wnd+pRMk!6k6w;Pi=TiyJkxD z8!*(b;IJPn+n!32g#hQX7*bK=i_0th^1CK58%e;D{meQfPTlID#!l%L*|quEF^#@P zyh+?_5~&FKKfkjp+7}?lU7BEPC|IY>jAx%9LcbKr3jbK3#n2nG@4QITl)qJYL1MfW7lYO7H!4{>u&)GFYzdLj+W=JT~C^M3?Ni{X6YbY+3 zpkooI3Uyw~4$ey>A8WDNK5tJtq1?$#bef=pxfWtT>mKpBuNecH67?g9B2G#4BrQQ` zt6#~gsgm^D7j&047jZ9QcjfR|EAe+U8lJO8lwW{!9@&$1Jb`rZG}Xng zVOIvvh1aTTpucC|!R?MlF--=qIF3Lp@)ROscPHfsSKrEA9OcM;zPaxTJMhu(Htc9l zwGuW_opx8Wq<)^Y2vRb*@pr#XI~o=QNKsgO0I6p)f7@Z<{t}O8hq*U1N4*hBcIGoY zF%BW#ET6dDf`zDIeRQy*XSOc*3;lQ1NOkA@jrMg02F#*ly;F%5U#ALYbyr+5Fk2_3 zu?~!EBrL#vT4|-o;A+}FUl(1rhkSLJJ^uV!q<{Vq1vxFOz-qs0S5^+;`w(*@ zzx0lH2idag0a69!$Jsh{zPF|8vfCkHLP6EjUrx`$FZLnNr(^XC+p#SKQ&~IH))1!U zo7IZPsQywNr-5O)qwUR@+8Hra?JnVc<2}n!Aih}u#j%+i(HdLsigSA*o5Sgv+KRlp zo}zfe@Es_EK@cP;)h_9!Q;nKN$-m64PhcxP5n2b4kbt?dKr}<;` zU3eYeg|NNb(tsZ^Q6=H4r_@sKqD1-4V6y%p*>yKhT3Vt7fB(Hqvl+?9oz`eo@p_En z!Y&7<&21cw_e&!stkE32eTwhrwno=X#Q2O~L8Coe&|%x?GhgDnOUXGzi9cUUeQqJD zcfM4cocy(dO~>?-F~ur}F?W=JOM{e~A}<9e82jcYZcjJi;_X+?_uM>|Nm|`kA?tjD zh+!e)QU~{Zy9qlLSIdK(aIPLUcCk$t)GX8Z>|easH%EBCMQb??3~i=Su1JjVAoAO$ zf<(5nUP-VyvhoQ8qo23Yux*7y zUS=)@v3>L&xu)yQkUK)lm%{PQE;2n%{2LB5zA|}q!Y0vts2k?5K>UI4AYYT~!rbt! z)&SoGgC(hH){G82=UnG3W!3-`Cpey#%dT!{Dr?@A!txEI4|t1j%l$^@AgI z3q{3ylfk)jFUpfb`e#Va!x+~ps0jsqD1Mq>r}9Qn10u;M;~} zIYX_8^KiF1vr2ipFI^DtG9E|9#P4PABMRjpI%^fG_W@ayJE5LR+wVwmL=sCFzGvAP zUH9jIRC9DG729^8khIr>Jv#1=Im}QekaEmwe5dmM1wgz99>v?~LYf#EjIG8{KRR66 zKUXA38QKpP6z4CT4iC1Rv#8Zcc2o zDt0G=S$fv2gD9Ntnk*or^P$vj#pLXzCga}%0qxv1 zsMw``Up|xusTk#N#ZBUJxvE8z34tU7&_<(wFAh@K#40lQfwfcn`^YskrHcAkrTSPi z@vRFKIlO%}5eeVTD~RbSnH9cLWwIpVI<~+)=R&YwmwOsaV!~oZJCkBN~5?rNPAsr+O-)O@@Yx-a;OWm$ttPg znZ{_7)juY#{5W|@QC^SiZCo8AOK4}M;($X7o#VXP!B`{aI?t%AQOAq#F~08^p+R@W ztR_S`0qpQTR54V|bM=~#p%LW8{eZA2)7q~gd-_qkj`;x#+$#qx;o^nHrif%Ggqs?VehncASP=A%<^px+B1 zK$aLhIS@a!(pbAl-@UUASs(5v9bv6_^EqQ%rLur7N1aWp$4zZ6?7}E%EqL4tJbz{~ zP(5=MERj$%T)=%dQo1kfv}6)s!occJ>wEk2O9SIEH+2Bi%2%v%6+%V*a;{e|0AGR7 z>(99tjT4GrE?e?3J`HyGo)(1Yp3C$zu#`eKtXX24;#(EAZe@|n1}8$TslLcBON*Vj zDz0b|gxG_Y;B5u-3&#f`cCIVFt?ho^PZu><#o?MY*Uy@WtB^74kJTEi+(#Tlu+O6# z?BO}u!Q*nxY5q>1`BP=5AgS^gO1yf~%w6I$0vB5h+#xS>drR`w-uFrjt?y1~QNSs* zd`~~|d{RRz;&nE6J3S2xF~x66lH${)?L8G6jF;&-PO>9ZgwL;0xnKlGCOu5UgD3i; z^ZnhP)P?$`sx(N4_bu6}=Sr==L_(M?wRGjA9f<=xY#vPf;wugW|G?T9&}cn}G|up9 zFs~~d40iaGV9upZ8QH2h#&jmIXam{G@T-QTrg{l~8HC zULq5?i637QgSA{-Y1MAVxx6{nLLFRCl>QNxWS%CKU3*jba&z6W{{va0`$h^{5eHLP zD9hFW)lh?0tl7IeXY{tuo%wmF?^86fB*Ah$+}R?n7?VY7Tm^dbXqUjPwOMQ>(XzS!06UkY4`jh) zc}Ue(5F3S+^NEplrp`4>l8F0K{o0*}IRR9bA!eV}WY5>JDWhRf?#mYt-H&hn+I^3U zV!6sOZKTpvV{9j3)gb)*O8!Rz?fQn#3&6VZR5NM)4crEstJOH<#FyKHhVk4~FSuiu z!-exo?>d+uU^;QU`>eY;{!AH;a^TXK)~m>S_s}m#uw=_~UtR&h-DOsOix{cblWpLJ zaPtMQNN&gew2gT6+V6eZUg3nZI=O;QV_Rf?=AYPpNvWL%QGeHO1{-4w;P4F>rezll zRnDR3m`n8N{3k(`M<+=OWnZ`o36@cOusF%p^&f@8k23@9(i>zK(gUpv6!m2TgW#)Q8rNuA9gZiok;c0R4czq zpWnrNJhn=Zo{Lr|d3F366ZRR3j=p z6Z6`Wp^a9HBHem9b9w+8Wo(YiO%UE3|MloDiqq*Xa8kmHBt$c(nqYp4yf;8!9Cd>o ztIasXJmb~P-?ww?qL5j)H^ZK8`sA*N?Vb|HDq#Mu`bK=l#@cfWSG?Zvs!5ctAxQsT zWL5rcclDFW=-d_Utrind9P2#8N&g8wx$aO$j-~v=^9ss}$5QyiAnGF>Xtb8J$q7?q z=cz_7>rTF3hz%|tgd-Bj=rHL%ygkUH#QO!@0@l-0r)x}WuxP6f0Q>x;gDfr5_8Vdm zNNP6xbYZ>Su2n7QzB3E#a;!2sAat_ILWt7m-uh${}W7p}YA1LV--TUvDN?E7N9y<`r1Kz2d}ES9@r2>PbnL zr1N@oYry`@w>lr4vbKN7D&-C%F|UFm>lY1GgWi@Cx*DO(&H+ER zbfCE?gX#gAtLi=N=b$7FLVW>1*$gLD$E47Z$EYFipTzH- zo3~B&WeM_mqqNpdLy)l3QG#Rw7EA#)ctxbh7KG;g8H|sCT=WntP1C#BQP*0~#~uew zfO*sl_M?Wf3(&mDk0l(GF*nq5MZ4Fh7jvUElr+h+IEZ1N0`g+HxHGg$AW?W5{vBI| zTXg6rpd?t}oU)tmucA~ixn}A>aOz5?7-?k9x{|{rapb`s$vk)ZwZUWDN7Kg~^wR=~ z^JO8_p;0Viesg!)euwFED!e5!X`qxAq!eYxC>|KR|N61wgxqo0g8fp70J3`^i*3w1 zdhYJp*opWtdSaPdJ{?t)b4=B0g7Ap- zXmIx?3OB_KU&zj_>t}}9I8tm+uB(#NT1Bi->j+y-KYv;K5`-F5Nhk-*B!YK5=IudIc4{4@%& zQ0xxDT!^h9s-6_hWo^kM!CXw4Q%Jlsxobp&_+t(1H-(Nhz}D#-8eL(<`MlmA2>Ec` zhg_Ie&lXipCeSxOy%WUj_sK~2$ak5RR*KW+(qZuq%)4AGke8!(!PngDbl59^WyM=z zIWpkHU?9s@7Pv0J_Fnq&+rpdIWnR8nL>tKi!_12|ltfPjY|SPGuO;904HZl3A4UB! zny#s{NEAaZwRb))D@u+uu$z~X8pKf9%9tQ{rLSp;jeHl@{Us_0k4JV>H%cC@GnCeS zD45`>W3^^ zrqG5pWbiaPr526UFnO2dX@#*(neEk9UsKwm(rRBKc}Ay&BKiR{vONecZz!@t3!e*T+2T^wh&7`^b`LTi>Ed%D~k9GTB9V@niI>MQf~MZd608^=(2= zrj6MPfI=Y>QXkHcqmy5t&Q@-cwU8geUN8D(_n1`9RMA1L0uiz*YeNkag;Mnb;69a% zJR`z+Z4#P{SkuoLn_sAxTZqNW87bCTgde6QqdB^t2mIKs_!7czX&q5C>NKcG9*%YC zQ+BvQC$$fDh_s@$=uFG0Yk_x_ODcw{{0MO;qgp={erq-&fVr-%c-J?Wm@+W( z3%b$gJVt4cvN;o!Amawn+9*`UkLF{4a-ci(c_+U|EKtxm8xuJZzRyE4V}h2b$xD*xsntE3{IISe<; zwPN6X%l8^>Eg6>B_wnbwRcrB5-9#890m7G0aXqRuThdobRf;~dhgG{o=lS=867IF|TLV~}Esg$zC!mbT_h=(liXNNW%#>J=x( zY7kgGckJ3mGxu$*?o((zw$7YlEv`BUaINH)jn~etqfA4k4ONa^0}^jqPIqR?zP9Bm z&((jIv2!yZI76(p-ytZH1<456J@>6*zn;JqE}NJqqoR$j zQS12PnL_M0^GwLN(Qhh58y)dygg_!I;3)cDS%Z#2b3p(Y_#Hk~;UXI|TA{h(Z>3w} zTY86iQMJ2ZL}7JlUh=kPX^wYJ=Rm=w6f~&IavvIq+82x&m$Woo?va`75>vE0&KKl? zN>{oKvkb3ew9DXh-IVqo{$zkJUwK4prhp5UEwths?g()!tJBA%h=LGuc&Sn5z_To- zD-EUi1|Mxh56MgK`ka=8tPE|qu@6|Nyen72wUH&LV-gy1sE)20>iyr23QI5*91JU% zaeQ1;P&YdOJ(99OkSKpcZXLiB!Q~Sa-h@jwmAqWAqJb6hMahLXIPgwZ(Jf@>oG;Tf z)7@-=twC?n{2{)Hex^^H%3IS~q$HsZ0uD^u9zQq9Ut5nVExz9;Aqe*^F|U34VKj1` zvp+@1vSN@Sgt?5j`2~88W{bD5Pp?X?jzgE{RHl`T>1cPrS(`iJQo+lX;gv2ZgTD$R z%|>YtSrxU{_ugb3s}MZrD_oYa7gt+dEIHp-SObMCBY-!+lv^S!CT~sJHl(a#}C|9kCD5C)9ykalw z#?mXCt=vC*UQCR{H>dbjuvrEsv_ z9s?UsIjG11`#z=8t?V1C*}7;bTh$^`_r=HdnxFOyJS(dMXn8WP`8Rz*eyQl>Fadc3 zizAjsJLIXZ{6-4S6(*}at(f+e5O=(obGV9flJI7HBn!wSyNUeF3ov3%W$3?U_@$%G zIIDKD+C({zHsLjvo?S^2znQr$uxumaI}P#CH*!uF_9?_!UN)|fmBm9Tx!nGsz=jTim{&dk%%a+8YuDdj$h+PU|jH|rEew;jm8i`V^mnfav=#G59s8gI{( zteYl{*xjNCVLIh<)XB|Sl1JxCFdSn(=YK+M=31H-QJpO+kPEYAm(ow@(+Mez^cWnf z(=ultYwlY9&TBy|J{qlzgYoOux-GI{gEy`#z~121k8y|o;eI}ScddsvN5F&0!i`5~ z*7wys9?H_r{qL2-xdfYasM-iD`THbePgQP-F3PzqTyQ`jrb$G&4L6vd!hW7!2PuVC z8?!g&JZL*Fnv`E1PoHgi@MhP*o-%XEN~fK2fMsZCbm~&=T0(%nJ|j(8Sns-PG`YsU zqH~yirLtadW~y?(@xB`ajG^9Wu4QFkp(NJvIn$Lc@|h|7KGu7aIfXji+Rz}~yP+h= z<}`eeMqRmK)Oo3k^?=Fp%Uf$i{-G!4`p24lVGE6^v?7U{mNwTPVLOm14I5}2C3wzT zO@8;}q-W~bt0TZyN6njWSOl|?)}Z)4&O9bcCym`nsO1Nx&d`2=(`8+Lk>TL9a?vdA zIr+H72=g{sr(ZzkxbV(R{awNyDmw?w5cyFt&BL^ayMB(e!Xg77*!&6?qWBG^qBsqE+!JZFz#|%%kHyg%VfTew;6852>}eHHdx%yENry*V zk1#Y1f0^C=^HqC_{kYwDiPyq%m%-MSJ`Vqlzdll@T1q4}Zq$|)n zQqCUX2eeR|=;@*Ap~;pXzt`!obkNQ7AoHz=#{*}I8W*@{+tEuu6>=CQ3;at{@ys<< zBZ*vlA^Rp&HQ}V~IZH}JL~z=bEC+S)NW3%=VD@PJE8hIdW`^-{)$f}@M26{hqaaTGp`jE8Qpy?WcAK`I43dftsTVuyZisc-dD#(xkUXh z9nu2Q4bri6N_TgNu)+dMcL@^G(kV!HcY`1z4Wgu!w1h~bl=^$ndyRX&@B6!dy#L+( zz``@<%$YOa=ggUzXJ^l$W3TQng~L`0ZHk848k<(@qpT%o6l~x3svGAmWh;M^t6DDU zzZn!v-*};<-1nL4t&(TT%MSC0hc*LK^Bs9GzY@Nw4{iqfO?Ow_qI?WO&s&&=k=s3+ zBi?lmS71vW4z@esG$(lxLDVCNLua(__`4F9ttM8D%tUhGdn2P1oe7U*-j98k)*huQzAg%-Zr1ma8p9#)&CEy5xtBJ|T$B!C=i@M`yh@?0@>A89iYnaih zaTwT|A2BUv-b^-sMA>_n^fpGPn{AP|XZ`WVqs*#`cbG$p)k*PF=xOtcFzH(dntCgg zjf>bv7ON6Pc<^!wmG3bX5TCn9doAk6FUlsR$MIw*^KPm+ z7DB8GZo+UvY9om41?3sbT1>9*#ggVHZknKuh07o`K83a`3z&SFT*@lsg_T+)CL`%z zKOiYt!|u7WN*5wUndVxyASSHhA{*@ybwDSM@6-O7M9n^6+T_`F*cRoRey}Kap?N(f%bGjavu`^{VyQ#tltryFy z?F~P`a|dCBnfLm}@Lia1YAhW!;WF{pCMJ1*ul zSqV!F-teR~=aFo%V;OLmaeCVIB8ksWuQe>XiEyVVWq@JfetLfsLU60YhE|(*{E6PQFcC6)bdVd5l$2oz0>1*A=M_37!j|;Ph0&_kXUv`()HZo(Bm*# zcz~@Ti@QICcKo^#OeWmCYQ`p**5S103kWIk)UHqT(0nmN%tgpy($&ai>)EUJ>2!B^ z`cn;Nu~FdZY_M{o_|5sJ2}EZD9DqCY3^$RRsG9J5!Y>yypiOx?$9d@IxfYYNb>DQ7 zrlBToJ~~ljK4FfnC+KYoDsY0d&`Xx_;6}t*$lg2t#;NdX7>NPCC&L%e0c{2k6%C>s z)zMLE99U!s`La7HB!g`@YeAZcs7QDJY|UlJ!V`H9ulcT0|Dx6B_Q{mH_)A`R4T#sL zaT5Df>LxfU^BSrflXth(Y8((9SfdW5ks2#cQ#HfpzDymB)Nf88zC2wE#HFaHcUz3x zzs(m+KS@FAKQ;JjF&KA>VIA=d%=v-ACaz|+uj8=+v+|SThIt#(2S6g z;j2*S;v1H2$yXumG0f4L3euwPw(Fxpi>fG3sgb!m^f~b|Z6Q>rNQbr=5}!O5(ySeI zz55e=llPsPBJ_os{+gJN-X)$}YHtY;J|z>@)hIr!e-Iz1j)c0^*oRJl-Y1AO_bT~u znvP*sAAFIR`gp}|dr#5RX*Ens&7! zAJ*`8M5%!FSj#BTW%RK^sZ=~zO{E>409*N^Sdyg_lZhvSUXDzloYKo{otNBX(Oh*F zTHBQydB8Uh1P91&B`bJvJH|{V%eh>ZNnCOxYusdl8(1kfO>P(kcT~9UH0V!;g>WEI z*83jij>CExr%hH|Nzymys*3h&9@|(nPt)7e2e(VGOiV_3oMH6eER!(;UA~@>-eFq- z89rr3x)pbMleXdhvY@4wRAc)jB1h zOJ3ou^`}q?uBbHM=`+1Et^Ci%XTBBh;TLS0s8#byTgQQoGYwW5hR!K1$|r}Y)Y>Nl zM|NbiS!2Lio9QEMSC*Eu7+dD*Bt7#BBW+3_RK41}J-cva;sk+B-qj}E_<3|4&5sB@ zZoam?g%K-ZeqU$8ZskeX!o<@P0}u}{Ii{@gLkx-BENjF1#-pBd-24gJ`1U|fia2~8 z%hwJ`+~RM#Dr_+E(-OIQU+TTm5$Ru_s%Y>wZ7?>=9&(_IE=nnuQZLSpW!hi0Qof(( zs+-Ge`F@DNEdEStIOWDDYc3YX^FaL_mg;Qs>WW&G8-rX%x9Nv#U0UJOyQt7lvY$P) zB#~+BEsuB>$!PQB{w1{{rPiVDgHl493@~AQ5OE&-O~h01fvtuusm5h_&B=^yWq#me zR_8Gt%91ajlNP*W!5}`; zuTBxYXzthbRw_(s6FBDXt0jHeNCJK4tNYe~Jbn(En~J9Hv70K&5O2moOp#onTZ%#n z63+La5jKD{hk1wSu5RTZ(g0J+3D1X-`WJIT%`Q?Z{1cWfjVIbFj3?{@Y2Y&K(9ih3 z>ABo1c3ee4pUth;_hwNWW1KYou-_$GGpsE|4>J%H)4gSMHYi$qQI!v)Ov^OvoJ^N9 z!+eF!;+qJg^;`uOgmm)nlGfMef((jgXFIC=tVjec4agTVZ_H>txV{y!%dgJ=*|trM zyu99qPQX8`BJ|v0#Sb_fhno^5@TpXNrHmj-VJ{+&71JUOcgiY5-7k?5I24N8gI>+6 z&B=@C5Ra-{q0fphsy#tDnSd1T&7Yk7!j}Op8$^o^j)*08hkRT^HBV=2ze9vmvL!bo zE>Msi(uRS)O5h!-gNtak=6j$$HUTaX%ebf4NTAc!mH}~CAY96SWuw(35tXwxyYW`G z63T>BQxmH#5bGT4PAWilf5$F~?)yj&z3 zJ2;i6ud~6eym(OMW;LNrMy5~*S>FTCSuw!n&-GwWzQ#FTrzJ@^0KSeWJnlDh>P(kZ z)NtO|0U67ks-Rsbi<>fi3hrI=mqNd!syX!=9Ijw5{RDoyV$JhO(!i|1z+hg%S0uiV z$Lu2xI8mc>4)m$uv(|+{GV~q_MX`OKThEEz-iguxT4Y_nxyG{yAx5g>KGU}NvpxN` zdn2;2N6APrB&QY_>(EjE?7Zjs5@8p9mg@nGFp^pvZ_HYHj`CZqZiTIvl`lJ$R6nAA zc#n}FxVA;oMniHcvmbNfd`SgY7nLcix$x!H;nLP#L=}Rqjt0GzdGxZ_ggJ>%l#{l~ z*ts6K+)n;X2lQF@G-Y2v{b6HExEa}OG`3Ho5*|gs8cTnE#L9x26Gwx5PSJ9F?CeWo zsJJltI_x&ZqcWeq`^|XmqB24&r7tJtA#((BM(q$(hElbeO((_nIz!R6oBSAXTb~?R z;3qCqinjR~Y>MLLN{VjUl|``?kaWf$e-e9U^jIHpycbT#gVz3S{s*G5IkfoWwz7CH zs@&Mg>?&mg!(40rbcGEa;3OrANf8p;6Q#p@M|i6WZG0Y;km}}a@VTt(Hp_q)Q{jxN zgi)g;f89jGD36VvP-9l1mlZ72`k}g|MNR4(rWMro{wmNGrXYoKt+&Je+WxjpMZ?>1 zkI*!)x}zc4NuKvoLq$V`X+ALg1MlHcN0nh#9YSy}IBedp{T8H-ag9D#AeVx9M^qA4 z=b&8Cz#k!C-d3+Jh95Q{)hvP&ce*xW`<&~A^lsn%A{L8tv%@zmZ6-sQxb~}7ltCjT z9rL;Ix{QlArG~(chfdrseqY9xDa;RrHgzp*+FoZr;W@6aeaF^?2#l(Dnic-j>Nt7i z*Nupkinz~@Z&eY<47N|r09$#StesqX?4=v{93h}XBsNX&fMA2^gtfYwSntOvWWes7 z%~=AG+fk>L^A_!D0On_bGFMylC)W3XL!nNH6m55li*X|=43oA3nBQMh2Th3b??tq* z4&1_%Ho1s(bhDCY!7QpPaGv-0L%}PxCZ#!e^J{+Goygy2R2-RBW{EmD8(wo~fL? zs5#X>?ZJ_}-WaYW-7q%yDybq>es!NI?r|*H=fO4CC1+J5pV5mxk^DEZ3o#~PyB@=Z zAxdkDOdOA7W)&%Jm7#uO3RtCNFwb6Sa>K4yOh;K3gm6OmP$CW5{T`6*6abmCp4Y zINyAY!B-#k>T-lP9LK4>q#5&zN4aeQ_e z-lxTh;qDtB)XX9@YM#NBR%^_`=iV5D^vwG2aA|9+*%p>t-{?kfH#ws5>?@_3c1?P0&%E<)=N1?YmPIAdpk%OgIBeAE!}rv6 zZpxG+moG!-kDeUzx1oQRm2xZPjZ^y=J6%(422CsND=&o*K4vQfgw8X?nUo-Pz7=RJ zouw@`SM((&%@szZ3tTv^+`;VTxPheOJ z5;KS|?&n3TlXk!25j3~M6L=?y5#fVG%FXG^PMEh19IQIR>`ymVWQQ~8u1-=@f4a+s zu3Z*UNoh$SZFuQuEOQ})`0xuzWJK+f$yU7TPJsS%`?tEiB|~rD_}BAEUDd= zM8kNS?_RPOlvBeRA%o;TZ(4ANJ~=l`VxOV8wB3QZnw~{#B3%dWUO^vQS6m)ST!kuu z#7Kc`esHAT93GB;{AiS7F`XL)5ffi`gYk_!M&ZM_&P|Dj=oKBG`w&=^SdX(fZ{MLW zGZ^3&c8U^Y*1mil{8WWy({BiyZu?v`+`uPEv|*xTP(?$mjJ1}ZM#k%gcxlCRW{j%d zto@KX_}Jj%$032_eAT{r)Q_$Ilw=a@XUURm;D%=xP4uznXfe%I zxI)RWy`=*)=XFV`uWNmLzy4&iH1T7<57$y8Wz#H>cH-t{VD4o;toC&24Rt#CI*JES zyF|V2KGtw?6<3ASV;vrZiKKJaZEk*)v1MzqqA!z2S!ofC)rSF6%(R{7a}UmIIoD=V zwiR9|R5%~^=yh?0m?z07l8irhrQISbtuMj9j?>orR79?a)UC%T+Vunh4FBMRllJ)7 zc;&NLu`+6&QyHz@r^yQ0URp!Wocz;)?!5Va_+}1HpB%I2SZfaV63r6n8=kZcwnfWL zI6Mh|76JquDK5=MB1Iy_K$WIPox`t+2Fu*K9#INB3ic=(kI1cfcCac=+yq)uESg+Q zp|0L906hz0>xqr6p}a60oqg{GWkoGPDa*_9k9(B#`n?23hd#iD*vFzxg5^%{u zxU17NReFbh8(EtfY;3&Oyx5_UPIyfCR6d7Xh|Y>Az~k2p@6ToUaRzZv1Y7v5=q!;W zL-tISlG|!d!UHVz(F+FQbXlnb{ttB?$~`zn+0wU9m~hZ#qN?gsQ|+`o^Bb(BhE;JG zdy5%|6Ave)&Qf3IgcTQ!aywEgg{FIF0o%fqG<|Y)txv~Em(BpbkGB;@l@kn?#|az= zq=(TO8t?MMO?7mY-dfQwjiH_+(1~`BagtPJ4vSH5F%Bw_^XH)qL4tmkY)ISFFiK_j zq+=+Jx}z#zfO00_UBaPEcsZgV?7qoaqi5u%(MFk}%3MZt?M>O7?}1{wb2Vv+7y^mp zT62<7EJBsbd5x0AwlmRG=FK_y?6ow#n=3pF{_5{<>%Mf6VbR76=uJZ5afz7T`Ou}H zw4paY=D$=Rl`K+nUd{6GdN8U|3nAUxg~8Ix*Dvq4>%@rVc_-J*y}TyZ?8ZH@dwer` zM6IrKW`JIF%mOVxH;_CopX~|C?CZ$EXTI$08h{&^`5JEuk^XBWB%D3#TB#IdJw7Fo z#ysXGx#KU(w4VAZ>L4Hrsl5w3hbP35gNvP$10-_G6Nn3H19hdk3$=vV zi_+}1b<$A5%tdMRcvU!69HpREFnMohsFt^?wwbq$nV>n%EirTvPa#h`M?0u1gv!&- z*4{|i!CPB14G7dsc2hm&7` zl}g(UN~HyLq~hYD0&{ZmQ-QgKz+6H+oK%0jXvEN|M4ZhngfyjP|7Z}n5~cYmzN!Z| zyMwbO2M}*okb@J<0S2=H9BeLL_O1|5HhUM^D-qvhNCSa(onek&1Cn0Jgxqy-a}}kb z0q9hJ2zP~9{E+?&Zda7A!2Qe)^@RNc`xWJH>;U%PRsTi!pEu=a*$_7X+CTdF3-fo; z00+mlJd zd@m5n^{O)GFO?ntjC}Tc5#Px_DqbNdqyn*liqc3y>>cdCs{XCe!5nJ)M=6!Gf}Dc3 zgff+azK#}^04FDvg4PdC1v?-fnjXyD)k>5G%*iMC7m6~}-tsGnpZ6z{z9!Vg!Pf2S zz5}&*I61g}R5SP=Xg^3g_AtOuz+bCf!7n5Oyy-%nUA~Is1cNz$COJB|xH&_$VRk@I zxj1+@e{ zNgAl*3iE~n4&eWzmW=1OUP{6sE`O-P$-(_Yc@>D~Uo_sH>I3m9{@9vM^hy77+5-43PMfGE#0X zt`2sZPemI*KcCIEP_zk>0V_g72h;sS0GV99?B zfv=|V6}Ydw|AXbK!#tt3`qF@L0w8`J5PuG%uQI-p4Spv7Ig|h&B?O=Zv+%mIn4gS9 zP@7Xwh*Lm_m+L3fy5g2{h60>_;r^{5e&=>@)^>0J?DpHt@gusT@>N`MX8_f&C<2a8 z2rv*A1$zqsVP3#Ve6EdF2DxnW(QN*{SYK;3vsc!3QP_N zyt-w8kNDF=T(u($bGGw3^fH>pMstzz0 zs3z3h?Q1~GU&vO@4t790W)grq`_`c5|3a7inXU`7v%R71umY5j zzw)dMi};161~mUa zR5gIw+B$grW9_fl{3BJu$qn+4#4Diwk*MzG>}dPXWRF_WO4%fA9Y9 zxc-j9@3{U3#_yQ^iplSI{tC_Sc>a#i@3?*g)c2wLk2w8?a^*18AjmsU&Kct60xZw~ZzKz`b%B0w8!!>5 z6p;S`stSNFN&}>jfkK?WQ>DJ{nbe&fEPyqrD2)uTbT>DLn*W{-EEAzubFnm^geS>ttLf+~O^}zD`&XKT zz2#L8**Mt+1bGCxf0g>@-t5m+sJzRv^}gq9F9F9mgNsXx(`k>!(+1oLnU@^kX>@^ka?NODU_@=0)m zB_#QI_+@#%J{h1A`L=exS_OW65b*61=6u!64+Eh3TC52LR!mn5#IIm|EBm%{__hi8 zRwC$B*gOD)wfGqnAo>q z;UXMYPcMMWuljx`{s&}bp$Nxc z01&w{kM9HSCrq@UPJih(Co2`_ud=@*0*oqFD&Xx`^0%u$1&MI{t*LJeKRqo1TKrZ9 zJcR-tfpL6)2KI+4e>|-Ezxwm-HveBq|3mJ7jr=Qs|AXs4xc(Ia|BCrP>-rC_e}%xm zV*by%{)6jZA@Hx5|Ff?D;QChx{43`Ftm{9x{uKiMiuph5`VX#uhro|hG{C3JqBI`B z85tmtniL2D$VCSH053$~2MHC(;)RHWj)H=Wih+)SaSi?2HB2l#984@+tZUbB2yt+) z;}Z}NU|`=MBE%=c!zaMM5(0;Cm5U7t4G9SiAM+X}{=a^G&7}q;psW8Wm)dh6RV@e( z@hVZ;w-jo?I|`6t3>6*$4Gx6<0=fK)m%Lg}z>9t(C_a6i$<~BS7WRU`uk$!6FDsS#p zPBUZ_fXIsrf&)^rAs{3Dsm|BbVbq9MIoTjiNY`ls;`V_IXI-!GX_pVUB{k^?q<+mX z)+SQWe1~EPlQ+DACvH+R0i{c8Hi2}DBBsW&#|B?d{~e6}UM=IU;jLc90&dxOdrVgt0XS1@1pN&FLB zl@gZAh>OG$n#2%h`J+H3WHj1vQV4}QZQ;FAZfuRjn6OrvN~FS#br{;4!=50_ z!4nQNO;bI_>sFF&Mn#Y$;ZPuR#>yCna2W@>(ZH_Jw2NA5@;&;Fn3dJiQp1Siqk0+T zS{CJDm)IQDYgkV=3bC%2qMLDj&?Xb1tL*ZWPO1{Z*0RnA88zsZwcU9?EJVyi;X(#B zdo3hQ=F^R^*YhZW9l;-AtvpwRyLao|qvSHvJ$vv+U4&SYAu77wV!Q4#2YU&Hf zVbErSoWN~t$Ux0fJ2SHeQdnu&T$=aj`Kec`c~nAaPfHj|Au$^1K@WNU9uW_NF(@*B zK0Ff#X<$xeTsvWZtCP}i?5)Rp>TsHkCuxi&Q}LNBBr+JxIg+^(%BArBKvKpfvmA01 zaxpAFIYre)S7S`}p!9?Y^za7!>+;nJ;`9c0WZ~S!R``mA!^uH?&Zx8zTv|&3oijR- zZHDQWYL$xw(>@6aTF}uipa(L&Z)v!(9&DzCp7v!;0vTSqwp!Fmx2&WmZy1#BoaiLs zRraf+uWJWOkUmCAPku4pyku(WznLO9X)ca1wX8jMZ;3X-`rrYvs^>)L?8paWY#Fi4 zxVZ7H!xfzdg!r+X{p=HjyIb;e;m;2;1|8*!-B4a1$iFOOw#x5dF3arHvf6H8CMnqF z>0vFjU{!j+b4nMBCeYWkJdP5`gi+7bBv0vFw_gz=vC<|r_%Q#x$mC7^asA1Jp@q`j z0SP6?DC-^{AakvfaBQvgML(P~@|q)dzEf!M?smKXeD*`0DDnBxadS2f(sb0CIfJ)Z zuIpo>&_W~?zQ+v%O2y3Ug_VI7nAZZ{dfnBN6<)LR?{y~&rHBl4v?s|cEPn7)3vm~8l1Yy4H(c^MS3ZhS0=mEkc_lq!~c3QN2&Mkd2kvL&pD(wP2d>w^_H z%iSmiPviu7RZ9XxO7|GTs;Y|PbCb3b*;wl#m|}g%Om{t3nW$N1pOHEVlHe~ScdLlC zUYt|Q*W7#);WBjJMZc)Uh!3NwiV9(mtD=n3M!`F2%b^Zxg=VjN;7gJ z7j1o$JZoN?c5;>XN zY)xQ8Qxu;m6LPoM9Fv%;HY1z=#4$t6nvIpsP={orR$4yFESpedBsu|37A}2C%Vr?H z@fAgJ#KZS3V)TVYhO`H=j7o3~w1d%Y_)Gjg3FB1Tt4tUw%$~`oVccYJlZ_9zNE~`G zr)hZ<-%`GZ=hAU;QJWBNRwxfq8O%mzsLif31+~z{yZeJxk-7S$g6{jU@k`q{+@d~| zQ;(mKVwdgaDxP22{vVI84-1q(xqnM zD8Wa_M<>w)gfF1#+*RwEcp=1NX-=$?Hb&;%|ydt$-!m%q7$x12bGROep~A41Krch*=?Qy(hZqG zkUsQjKT6BH9xb@OI89fmmI<*ozV3)y{ubNG{`_Y4IDVXro@zO5B5Pd^t)Df5E^t#{QKw-M}b5|KPowC@H}B~TvWS!%g(^R0s;3gpMhOl8wwp&K2HAEK7o zz)G2^Ll{bNyVnVaAcY`80g!psZ49!2XdZIC77Fg{js<0t@jynh*34qz6{D22l#KNB zW<%B#Ug_pX8$3GJHRbO}%e${5vyj;9fBvvMZ&^dI+}-vn?1gizDFrhB65q5Rqd9vx z-}GWy_GQZcXi3AK&>ji80*vh>xr%3@)LJ2q1{X|AfGYRsB10Qvl~`~U`T~BLR$lwY zjG@{^t37VU%Xf+Vk zxop`H&W}DtjHG8BgXF=??xXG8brx!ySIJYNo}?3~A73?$F3tS-#Yaf<`Cq2@ zv*M{Z@gn>_YHkZG6sR~s!Ph4q`$VX%0N>+cC%nhBZV3I9Z1|MVY>JTZ7GH>|Ute%4 zYYyn059jtnY+;z7i-8=5UTbT8QDJeaTmp~kFrlM&MzF?X@=tUg%SYm|kN9j`vz8Z= z&mSkwx72RgOxm?Rv3u3-cU^w0Zm4A@F=MrGlF|Pj(iupgI9??O*n}jc(T#L8k(&YlE5V`=m)QJ!SPLk(1D;lN>5ZnIsdU9r&4uKC0mmmI2x`U`UoYcofO(mB~tjMz{pMHPzUA%BQM%@9ER z)HP&7(A&f;#!Z$*zGE&>x021_()+HFD{-&g5X#^%s_501g;aAf{`|Mf_t+-YWLZ) ztsMxbgH1ik8%1ZxT|W3?dCrwM3L)7@qpCO>F_#>pa9U(Wd$SEd8Q+(Q8_P?rx1b z?pmG?7ub}R%}t)8x;&9(D&`|)CUU(~hWWtEp090`qon=y22*}XS2E#z^nK=Xs1Zf> z{rjIzX|Z;WiI(^-5|Jq{O)JA;WqeUN9di}3Cz|YdFQ}U5H;bvtbE9hs&8~+V`={~D z$Ag)dmT=o91m5-t(KHvY;@U{7wr*QG6=?=r=(ZX8hKH?Z0{~|)tL%eb~*Jd zN;{$LQo1%o&59>b1Rc8NEc-sEPgYdmWl2Obob>!76s31J)^ItB)q>N?TQrI*#w61o zs%vPD-9|j&k;yjGVVU$V;i5CA3$^ei)uv_KQH8ft)K0g#i~2GQ&z`p$`Jg+JQOiXx zd~WVALP$yDH7|KQoaC{~3{!qlNCb?TP-O$bs@qKuCHsW}Z4vTP4L*xTgu9KM%YAsu z`=}wJRkl$C8f&se4KNd;`47#;HjwP>+`!h-++2%iy$`jJSNzr|j>&A>_6t!#7b`KX zF+Cxn)mFv4ws+Uv#*d~*h{_mCl01gt=-mf5yK^)1oltK|_bd@<*Y(_ZIG4q}uncK~#rt6rbrAq0>R5Lmdw-ya!+OpCodfKCO*%i|9 zb^X!8oX$M~6bru1(r{3|vaIEzUZkOvdLY1{_4&JwygC`h8qI8+0Upggx|X=t-0)bO z`l|?JTn>ou{RnL8KSq4QzMsPzX|KBtWu{OpHJwwS!w8!hbvj(GZ411A&`K2pwr{-H zh`O&k|9-qjPr*n8vy zn$0mL*ApohGinQfNQB(Bqsdhl-|B*_j+KMsmd6NMF z{{183$oC#t;M-t!JySt4Q};GZLpIFRg#G!g?)A4pJ#PmQl<`A*(|q_N$t81w9s`L| zyZUX7HqRdseQOe(@~mA_$Y^C7~FXsg+NZo10Z zbFe$?xo!YF?*{cX*?WDA8_|J_9}WpM8eMCQ#EP9e;$E)474m6yw5Y&qFoK{W zz#VRvJhD3;tOyaf6DgdPG8%dvCHLX;An}88mfrI9vsO)dq~R?Rzwp9nYP`Oiy}IUz zlpY%~Rfy{LhAOtOGYJiQT~L)C+k=<-OuIK2LOvD6FY?Z2F7Wc4@VIY33V1jYcVmpw zb5`dGah%6epx&eI2ag&>XyoIl{EUUN^;P}#v8nf7=`Sd#!HS<;t2eA=&LDSxJX|=A ze|$ir;1-d|D;r_)T$Nxo>gcnB=QdaKL7h4R)`(ft^}PWi>D0%zf)z<59r1Gz{E2vt zIkpJ`I|bb4G4KMT&CAkIHX_$#gU8dIND6O=VzG%QM?FEd`bWd49dnnhr3%B;?LJ+o z0VN!{jZcS@^~R1}r-ihnv@~H`Z%UFLRQ6{P)9pUXETRRSSF7k%Yr4#XWka3;A^2Xd zggG_Fb-7GyAHMf0T9JCL%6{VB4asd?G?UjSD6#g+abVEMES9*nT`hGfAPfox$sQb` z8`dZC*?Bp~$S4$CE_`UQx!V#XIt4*fj)|pi{frR4$NVTT*I7H+ZGf@}PnB1NKP{?C zR)OfKW;*OKftd#U5N&->RGXRc&hTq=6lc#Q|M;>%TU-wXYegnk=ri7gk>s1QkNb^B z$gH35(Y8=zgHe>t4@`XEhS0}D8OWJcvR(7jw0ck&i|&mttafN<+<{>D;>W!>5eO73 z8Y@uva3btV#vMi@SyMp+XUu)4JFMu=e!Pieyn;=7AC42Xc=mGG7FQe`~+HpsXS4otDui9&9^5J4i;299ZJXPomePqE{bIDlD|G z!K36~phcH6*0j{q?UAZ=#@`^k_6P;9Ko(XPR;iyidk+g8W)C1S-@-im);&p0oX{DIQMp3>|U_i>`k z!GH#@Y}+faw#KInVVIT27>^QeP{eFk)7@g7O%!n9C<0auEPWWg7!jL#JUH4Y?@5E7~w*%h33UpJsDAO z#u0t*13~PShaAQyk{jDFxfQM}J-d)3oMdy&uWL&{~Gq{^>oOMR@jWX*bbH@jBDZ?tSb!kzm95fKB zl;bkzG4D*jHpUIb+i8o3=Ut5UALsGFSpY+K)8C`D##7N0{Qs|lR4 zZ1XQh199~cxmw@7jnMG;j6JP@jEfx+2dOB+e1DOMY=1pmaf^jIdY#PmNHOH5mHyeo zi`rpzWJ^SNS^d>c(h9!Yt7!=3trNmdyqX__;xB^Y#|0S?{6`*q)LRr4IzTa8riYur zHMSmO?w4W{q4ybd3muM^O?io5(+?qzdxY8iey&pRQiddH_6{7K-S7d!b3O~&x5bVO zpFaf;EzYt?ACvXJavj&!)=|SsXQG>A)LDa=Xr)k{40(vkzl)U@A)c8SA){qVt#L2( zV2lv|Xi9*)Z{pH8#~V_9p;((6PBC!NR8W-cbvry3Ov6%&485DPCLsB=s>%W3L$a1i zZgvfwPsMdRyUS-qgd#Mq${j*9rw&A|rL0JY1$Bits(U&jT|WsdAbgl<3SuI7&)euN zCiyOPtyV!viT|~2k_&5ub)8FitNpW`cUvqc1Mi-?X7QFb@yv~Fr)i}Rs;$lwY#dv^ zQn+3b7+^rQQMq+N=_qWuNTx4_yK!R3MyRtLVOh|sJ{%Mpkt?XTsWTaRL?+P8lv(td zziNCt$|h%zSK#Q~alKZvhCf1(J#EVvXAdw<-|F| zB64niS%pD%$VVi4?Mkw#4@tp_J064h36P^(FM0=6^$$i-Zav-3CycW>_$;_-8(d7~ znW#JGoHisUIG!?9^N0#pZ%R~oL_@#wT`0YVA>sm6RH8STndc~un@a+V;Sy4jN&DFy z9hrR*5*G4;6N{7%1?%FL!^#1Cfb^#__>=g>q{hs8do11 zG|(7u;ZkH%b|TbrRU*EPB8VO*Ai1Txb&tI$S~`yH#YfB&>skf;$QO5Hqm+=G4Z-{7kKW~%JxE)k?9#-fsn-Pp*km%5FjAcw>emOKXyOFJgQ&LZKaf$N za=L3;5o0hvG~$}iyY;klH<~p`H=NkVZrds0(>za+{H~c7kh^1I88ERt|Aqzx@zFI zs^4kgE5*}3F-VFZ6HQX)_5Bnl<#&Lc9{ zi^_-w5)~_7YTV};Za_vgE2l!9ZP*tOPI_puz8KDeT|GZT(N@^yY->gY*LeP2-q8=9 z3x)ILaHe{GUfRv5#;oMc4d_q4J(?Gxi~Ryh#eFqk-A-6gcC=RD?V@Q4TSD!&!Hjf= z_b?Oa_0IG^c;OyqQ`f_95r#|$+Y&QeH0M>-61z-c2O4j97O^#KM{MMP#bnKM5bIT! zI^Ws*f)Y%z;YgeF6l8`_gkp;Ji3N>VAr*1p#(Zvx55k*Gvt{?swrQoG5D0lbq7#+8 zjkJIMRGYTkoWpUrlq+trq}LOrA>0nfs61oU-u)w^j{&BQ!s@#LuhmdAAO@2bb4es} zt$%Q>wr_@901&xt=HqG}Vw&Aef892>4mK5^R%g;XFX!`N@3jYtf_dIDP-s?k5vcP! zv|Z9RM^eBQs6>@%j7&Tb%k8(O@`$FUJ9tM!iGyMuBH!^W`*1+eF7>g!Gu#WV#i~0D zL-lN&5WPVjyxUf>IQ-hOEl^gW=3Nv`u?L-ak0~NJs-^wN9T3yIU%gEWRD#|*w%{Vi zZ$pq26RNuw1gCv3SR)t_Bi(!m+2Vn+)A`kwOr>@EPQ^Oi{7}c7>w;|6*z;GgDMN4U z=;E@HFah^~aVJ^d{_MINUAPbG>^&^?o{c@9F!f5$6+e^ze3?k8tnGR|TgQE}V0&kJ zEr`=aLbksMQiQLCOwUIq{?0D?*E|-+* z#*G;F%gtyK_HL=l%EoY-ap(CR{sQkI0s=S35ZGFPlWxMJ>$pSQp!HPA4FA9uNEdab z$9W)DUkt+VK};G`6S+NZiqiBvTdQ|h;hP;dowvyahQvEAGHR@@$ASE(?id6&#fg|K z?24RdC$jOUwQUTi`MK8aQo%gq_RNF)`L_mK&YM#4Ui+we`kx9iuScxkozRY^_l=J= zlO$2j5kPX5y&)k14gM&!Q`E_0^^$c zd3ZxFGmCB&p>I7)dgc7~#P#KgP%D0(4KIPYYl3~Lh9;dy)D7EPUWxT#{MathxKsGS z4Z1^dnW!i3_0~$!xzQ^0(EbEorq4!igi5zz$y@nR$w%V8oLlcuwlmn= z2UV0Ryo@T!>{Xy7y73|YbDuH#>$>sd!8lzH=z?x7bdk5Yk=cV&cLUtZDDpx*rDT$h zLQMGZ6KtrUm<_!|mak*Xp5yC!Ez<$xv|WTQQCM%9J?n6rr1Z(k(N>d`{CXy*IV033 z{p@~D5<-c_%ac`F0-jqgf)DjgJhL(bG>?)GTXZhu?BZSvrsUaeBB1*U-Q~7}D}+{L z7`#Sy&@k<(eZH2tAl`{OUr)kOGHvWJ^?9eNzycKXhP0@K^i4s?SOf0-&Bh))J&nTi zG)`-?`2+SbrRrnXF1T=%92EZgd6Gew5~nCnl~svpV}7YswczZF8Y2+Y#QE-YihS<26!v2V1z5?!3_MUQgz~Jvpe`?nb~A;(JOUK z#iy_Di~2Eoi+hB?FRYg4>m1DsN)QnW;nt|Sr;m)ch~8==W0=W-@lorY-+kzmcO)Op zA;{0oE^gdS7ck)ucA7t6OpX;`a7&!-h0YrFHoQ6kPgV4)ZO+3EV8l@t8b-Rf&tmxk zbL4Mh052z2j*u`Ll~`@RUV7EgXfeo`hUTj|SUI7$0G)y|58p>E7Di@%#j*M>cf7}h zGRFB)PgHI3=W>(pSPPpSsFm#q1qwItvSk!tQ5c%3usUkT-i{G8OHw*<7yY#F?YaUV z%t>WchHtoV{h?>iTb|^{&_=^^h0ThZuoBv|$HO>Ovyz4SiNrDjw=EF_m!rvppxoq| zJOQ}$0)4CZ(j26mvoG$%j?b?|r&W#Q8yM=pBF0q`ybE83!ztG^6f`f&2ag!*nR=ej z1fo&I7^rZAt0*nI@ZLIbbE@YhU}!Yq%jJVJHus&&&k|a;8gm@k)8|;j0~24 z0i7&<77?;qX&isUuKe^`l%C(^$1k85RC>5Ow-8gD2HSYqtII~*#@4kqh|n05BD8Eg zdahT_$uleCsU=z}{KtFh{gM64bS;YA%>qnI1yn!xD2@@x=4gfEvR#n=1+?cFCZZX{GSyknpUVGsM5R-?t#TylgHMZQ z`EdSyAk92K?gT}~r&IV!_@uj(n&u87>+0JQy_@u-FWl~&tvZh1xH#9W7!)=e7s!q5 zBZe>4C6ZK~M@B#>1T9s+972?0z}J#>u{anEYSW%6v0`Ru9lPdJVGI}BL$S1;N1d3L z(Wc~fT!-y*pjF)1Ja`sUr9-kq0D`F)eoW(!c08g#@jZi?wdpCykqyb9MUYA1t20c} zt-iwBsPg%+gAPxE0*6kwTSU^SV|;5Trx?=cBO2LbUzl7e#23f}HOvygF&d`}Di6qT zX@lJ)@7G?^^WBwbk~)^ssvF)-IL&?1aFo`Gw`&5eOh#gh3^w7WTBs!n$vwrO@6Q5r_gM$TgzIY3K>Br#q>TVg07` z7to4O;L$Lq5wx|>DzEViXleiX1k6=|kO5Co9-Fn`HQDaa^^YC;OA%g%^V!l=kLD|a zIsGtOy>mx-?K<@rw)1g9qf?JJHRFjRyj%u0c2xS!+?d`HV#zKlh+v;5Kkqx(VJ0_3 zd^QQ)Z=oNQw;^E0_Xr_i7@}#w*%AgmX+$WrLG4vij;6S&f zbk~iL^Lr<3gNk-i8ob7sxrKXcW9kKp)e+ZkCil=CZxFG2bKH&$6v$qALowBu9(cD; z)fe9WY$lHxFEgQsUidbVCwIT3U-{CYA7>JNm8E&$k6s zt60O8APrJdYQeer0ZcjQ_vlQSvns_$SDy*pL|;2)-^k}D=fa9=oye)kBi(|!ZyzLC zm?Mz8-2n=^`yZO zZhMi_GsXwI+c~Txq(a(r?s^fnv6!_H!82032Nl2dxU_0J1ni86f`tQ>EyR(z-tQfq9njdr$D*)9hogNC$42un6|BicA#FyL ze5sY0J}kB=!-lv#!BH%$+3_^;v-$o7V3%0BL(JZ-GkRR=BwzUc4sJbCy1h5xEFD;SMm?^g1@!MNO{$+XU> z!^8xyYtDNvR{Y~KWjep3?OnR!`DIl7i8JdWcb$E~+29ws2V!jXO^M+m$x^f6(VDf6 zw*af+{HEW)-HeC~BZ`@5>%AWY9;Jd88sLAYn z5*N8iYeQIJVP(TO(IPCQwO)c2D;27VrEPw1Uxt~XxCWslSgRCS|G{Sdxr_WFPtREV zk=+ELq4l6143eDu#QZTc$TUoSEp`p-k*N3aD4sj{2;@ElAx)*2V(BI38PnukMiYOX z(!nu)l^)Hbl@kAYqgFpWH?7EfX8!sst4QP;0S`EJZ^jxvW1*kzF=h<$CcY`9Lsnm= zNmqpA0U`1?L2%Bp07YifsU$(`pc6`L_v5FN(`=r!&s8S6$z!;2;JQS5az+ zJ}fB$sS^tgG-|PGsqYM{()bVd#R}qOaA;p+NUqE+l990%q>ch@B0mH54F%33h$D!H zxICP{y-HW<>he&*TH!1!hvy{loq-H;X^{=y^UCe&0kYDaF+@SD%T|AV%i^%(C02QM zP*WI1nF*@l3;|MhmQuC}e?41Yq8ODJ{23XV=7@^!d&T7yzh%qFJXE z{?fK1UsEn}bwp}N$h&&<EqbSFA6-&Gv(I!9h2lpNiX6nc6klGF_XmUDv z(f9#)^hr`-)*r|QC3sIZ8f(@x3xt?g0?;TiRsmwAP(C=_TUDJo$H+Q zYryl>QA`r@;#2pGr~`A+QU{KhO=zJhF=C`{d2u9%*}d3~*y2q-0p_%tFAIHnvsctl zaTl7pr^3Wn1&u*O18{Z&qjV?gdL9RHv_jm-0QjW~^)8jCx!z~0r*TG-V6 zeE2Dq2xtcDHl`ds<-*D}7c+H4ELn90YOrx8%kcsbpz34WN!rdH$ORn zT`a9#tnW7@o>-=yD$3W9CurAfWZPWq6%45hRH#~pP!C3x zKn?w1Fn(M-1t_#Ax=E0F_B=^C_W`;vR{TbIWRmMmV%x4X)m~D!lOTPd4!!>Xyqo6@Lj;dE5#kaWb za8F*mRLo0rWN?CX{3+JK)D1P8a5d%pD+bSsfS$z(#y&)U$Agw?23@R{EkDf4EB(#F zN2KU(H&~@73WBG~f-|4>5^;~4ahF!9rsong)0xy{A@pcZ8r9d^>+@Ud*1xm**f(N2=z4*oEt*21kXp>&w zql%ucSYtt5CKW@F0Ll4dgK~rjG81KIjXrHM;ByC1ss7D#juuqv2dR8ab2|MunOV#& zQ&7M#QrBtyA%++My8sc;f!uWBm(Zh7hdqFixe}`^YmB%kj=9$t&2LYqYV`%;y7gHF z6Tr0>3WlCQf_EWzF((5(2M95&@U%czv_OEOS4_PMU=!;Hr(a{lm~~H6WQNt1uA&5B z`N`1t`{RpMD4(k@_G)fgTWxll7^AtpOm!DKimUmP$Ryk&C7S_P(}1c25uf4e8yfRf z#rj@4A(@-JCE6_<@xRn+K442(Q8P<0qJll_Nyr6ScLMo=MW(jt09Ue> zVI-+dMqYs+{fG4tEiZ=j2ELcFj2I^eY2d!yzyPLBBP~ z;%Yw&RJG>Arurs1d2yxVrg+-Na*lQg(bPR`j-(8S8$cb-Fmv13p1f&O#G0;v;iu1Q z`k~p0d3XiFJvv=6$)K$?)f0(mT^1JtWiv^-EaRcef)0H>M}C}4)_sWG6zZ;N4c$8G z8#gX&I(=oD-0@sxGQkXRR?AT0Pb@TU;7Ncp-`Em5V<5FEm8!VLgWPeSa;y$}g};x? z{E%9f-%~ZdTCo$n5RkG+7a(MToc<(!ylLf-PX&1*VQU8%?Zi{8)aU!SNhJuxHbKLC z6YayKtlpHcQ&#DFU2Jxk{HC@+6UQuS(kR#iGkfl1mfhdfIA;k~Fv5Q2aMs+v)rnE3 zt_ev=TTk$nHB!y8CZ%FGB;W#iV>^{uhBBu;I1TiJyq3KR<$_1$c0))}$wh0nRo7S3 zS5?nQh}BmA05NH1Cj~sEX&mEd7&#?}Qg|$A7DLRF3X=HK@c~zTxLowsnVywxR%+31 zy){f^Ni4gt7|438P&wRJvkk}Ca2tziKP!fsbA�l6O~%xe0FuZ~%ylj05tW`q7l-%Y~xSfQt zg-~wCq!tCRLhd7qv0b5t!8AV*@X&PU?@p<&F}YI9CxYDtsq`9E(_LbYx`wV*t-GzF zu_gpr$3qMOXYv z^7hxu4P|MvS><|~6}KeGQ0NoQ-sF}F9q>AwdX7K`rg+i7;@gkIw-V2V(;HeyxH=vv zicSw`aNRq2U*$%V=9TMI4QpEV`yH0fw+E<-6FEs5qBxY8!3^p*oywn78sqIt)XhAS{&Eii{1;jr6uw>fT>t3?vqt<<#?iybQO#ALw>Ki?&WT(Q9? z1d;8=!wD<|rWzzSqH}}U89f}p{uEi ziHR_|D^KSyw1GUS4iB*;5&-B1Gf7|;0T3%a*Cje>ooXnx2rQL<0a%h26zZ9o83=FU z%7xq9Fg}x05%qyJdIDwcEV?9Qe>9&gkt{vF7xPd1A{n=}x(>1z=3JNP6EvT>a zqQHI{T-ABRlB-U+8NkMKwUDa!wM`wqpVS?;?O5b>DI*ug?VzHT1dw-QJ=oDzq3s7L<{EiV4?FAvxvr~O z@bNt@=gBa5osN%8Tl9XCx@rh#md9ODSw@gDOGg#CV)9WpK?WtL+@pMjjzC_g0Pt^S z{{3q87(p!|k|aqNw2d#X83?L5oLqQYh50J~05>kLdSb^}OD$as8e3zT){d*qSyDt3 zFI8L|t05qqspxP)$7Mp9uEP3v03VjBZ^Tn$fG1K1nirOKT!bofoa5VyB^Iy@{{S!;;0wc^)I z?`LZ2sG)_T@8vOh6k!~U^~gp53@$jVlLP}3qL~fM9Bwy3eIemXRdc^X>S?5&pG`ew z6!xoZ6txXpDymvlnd@t+9Y#>Nz}ltRSQSvHH&KTHr^MjmEMt$)>aWFOJH}*a_4)-& zo5Sw9x$_e1%lh`CwQ8GeO*HgZYS`dN)Gl+qMh;Y|QJkrZYIJ^{zRAOL3@>M^|pG(~D=0no3)3zBy?miKBLrjQCd(KG?^lR0I3~ zHhA((O$XvboW>Ur=9w-a0@%vnIO<6x88HGOX1UqNgh(6v)P3{{f1{qCP1^>arP6eE zL`L$y0?TJu;)5Z)x|UM8D6%saJ=4l3aAp9<5roAx!xM=mz=LuLCg1E`ZAgI=0$OGf zl-*D?$-a^Y*L`>|uNwB!lu*#sTGst(pry=-M-sIz=;iX2rAfeV-j_SJm;2j5%DW1U zYPA^5gER)%1E~h^;9!|KMuI@Gu%On=8VhIn{Qeg;d}m!K?;O^ms-UV`>NdBk$5OEf zgn?YIMGBw+j0`Bq8OL5dE3ha30G&!kQ+XT-B$4Ef!kpBBO@0|*rm5Gmd}NU&JT$(0 zM=MC4X4eD&(fWgYk44G#5V_)guI#vCb7j{0!Hap5WU-Ny5@HlDo)u!Zp4x(cF{Sfs z;D0hh>TJgsQ}sR1*F0}gB+_Yj1e@@t`@PJ*lc}JMcEJqrOvU3xV^IsjxZp);ky4IILbF?JlKG z0BngCynz!WSctQhH|_^IsBr?&b@Uv4?4w-A=JicJv$Egxj1-AePiPb|m5C)O7U?9B zB9!Fg_s^LWhG5zB^~u;?&7+9HzK$`@BR+CVh?8j2AP62E4)U#IL8KjAo0;dpPveb~ zdc*ctHsm(R#!P&513R} zE}-jMsB1Mna96xr(OVYArRL_$(HA*DSqFY0TRnCLJqMv?;ZA+Ibn^Z zh$8@C0HYY}?Q!C-H2{JI{#_9}l^RCRczT*Uq&`y#UTRn=kq^WjkuxVz=_O;B2FFHa z$i{f7_cql*j>@{dr>~S3?pn!l(>2u95LD92C~(3hg^I99pQ+eWDj0ihJw3Ry4%Sg- zx}o1Q1#^DcanYAQ78hiZ?sqL!c%3cMTI=IVm_*R0nG~TyM$U)f(THX~hHkH%5PMFM z7-znjjHJ7fCfA;2XVq`*65T;1OJe3OlGb(d+2&D4Q#~|L{9Ru9rlpz{Wm$Iv8p9dL zVyxvFM_^S{u6Y33)aWtQ8Kj$UwShko>uK@>F{Sxu>%YBvq<1@>pSMGMvqf@Sb?GT& zma}TIQx(|q86lH!EHLa@4&no35)Vx3cryG$E3lEAl6Y+v8`{?Nx)?Rhs07BdufLa? z3sy-)0#;=2O{qc;{$W%YgfWRl*jP%Yp?Jx~A@ZqooO@iLT z0x5t}o<&(ByWOvIN#&72ZS#Uj0GVCc!YY+Lfh2meHsBrs?ONiECXzLDeowtsU7+CB zH9>icBTLO%_k8X(RM{kT{{S}^9R)iu0IX-g7Q4l+x*HW`bJIG}HBB@kX3h(=o7I03 zqdh&b#6#L%S`F{``lvO{F3L4ediv2{d)D=0-$7Mg@Y6zNS~_=|V8O=ipyTuTaR@Mt zq6A$|uOb~0pzQPpABVcs(MKfFup&rQpw98!GZNiBvfn=BILWwJ4S3Y4Ik6!#+ zbsnhatOdtQ+-Op(OIF^B(#FqMMhZko1q!$kG6GNo?f3FWw-k1U4vXv5532?Di*%nj zS#24ZTQNNrHhyN^h1#;NpF*g*)r6ikxYSIKG)Ol|98vj88>^}v%Yl$euT~4jQ0)2@ z+FHy(IdzD(x~feEyhB~5zAN2#&$+d23HYv5)7p}09zygI)kG(E&!CN%WhWkv#Gub^ z2f=ntEF(buTc2E(jdOT8U^ zN1rRG-U9@YoGt-Ep;bzcSMeP2ULJ)SFCnI0H8!3yVlH*!paXLOGDo|h2%iA_v&MqH z7P(xK0qKsXgq=xwZBW#@-pwK$xv1HJ->NX;F8E4us@tLUa62ES-{yF)K#?KF%VibF+b_O+YWaeuIY*Sl5JuCt zr(=wMyg4&4oGZNzs>5gGJY2`n>r)Np-#T3CBbKx*azBvlg%}vKyKp!o z-0^)z(ta3>K=7Z7)NSa1cxzhe(Pdq%qNJj;m~;)krK+f;NtU9nNg`%7GN>#?Slsvu zcQHMG006J0f-P*gfwU?M83GNu^XQky&&%yIQ_>`8fuC-Dg{Es-fK1tftzu|44ucWeq3(SEG(7+2Ld4Zt!f|v374037it%| zJ+j`F=_N3Rr6(V_NQ(>^4&?x67$o#RhIpp1pmO))LnDmx@>Sy6*EPBLq};=^#ZRj$ zs~ShRT`D9F7D&Y;P|Fgac)(V5m-t9!a48MO2L-Ayl4#gOEPB974*iS4}xv;S#r+mdXo_`%<+e6VoKGPi&qWq>>

5OONuA?9Iq6T2!C~+h^9WEbT8Yd3~;$Ax|JA{$I?$;h~~WH&h0;>;ml4} zo?deXx~``Y>4-f0jSw{{ERuq$9C4NIrKU2uBrjqYrx_Kn^=MQKEf8Wi>Q3MRVd|$% z!mG6Ki1k1_mBKw+%-eKVs?5Fa?@LBzX_g#EEU1qr=OIuia(6KRbjcm~KQDDeibFtS ztXW>>naVXr&)N-rvsLMRA!o4A3L8zG=BA_(#IVL<*%-ng>$h^BUNFQl&Pn5)>}FK& zYSgQDINaE6z*=Whx*fQ8(IM3}a-#zvWrt61spG6yt!E|r_0N3!@RCp38bF%H$XT|c z)*)l^97Wm`;aLgq3l*Q?(rHph00&%xpn^arX~ueEx8sfgaD#PdTkKWYsF)EEpJ7il z1~LGDgtl;h1J~u-ipe4@oJQ$})2N=|dcRZo#Upx#bbNJD(J_PmpyJmwwV;%N%__q3 zC!4puAz-;_VEbrl1hPZs4>1+7g28eK7$o4506qF+fS%77a7si%LwnG_(tc)gYOd^* zx@st|GFzIWx-HQ8FHZFcWnVFU3}Jlb!Ni1;dlIWu$%d#&i)uF8Q)DZ_Ab?>wb5E9c z>fU7AY;(}Yi&<3h)Wv9)DsfMd=9+3!R!57>50!JcA~x^5$`&|Qv6x|2xgqWNW+aJ; zB0x8vt@T;-`^^3}$&w>Y^;1iJwW_sPE3LJ9dh<_wx7-C3b{l=No^+(8X!b-Mr=e(( z!@X_teW9L zWUq$4s)6X~E7r{*nwF}fG>UOmPLY_>dSx>d>JQwMu}y=As3}*9%w!R#AGVsuq9&Cd z==hAEr;@BX@00qUTJvK^XqzpPrl(WZTjGpc7`AEH;mDDjJ7bL*OF!KJWqK7H1LLO9 zDr@c|sJ~5jTQnOjx$0L=`7hvKmi&~^QqbKkpVGVS#+6~a+-l~KMN^D1i6RUYVhx-r z1&{F(coz{)m|!)Vn295R>F(;-7?*~D0CCsf(N>;+_&Cxs>-%j|M|HBo)kv_(OD~@c zLpj^z$~NP8!W7semz3(!wp$ z$U0?Rn8>F&#??K3d}-INT*#&en$5#CjeOK3bo;AMr+g~tO?9S_!+5<|D$H*j)KzlF zIyU4g%0r+eVD}C62aGy3-%aFHhPZ5WKK$10c1u5KW@EP+gm;oi211X1cMU_smWQ+54E4so>5-=U~9ArEg5)^gtONZNYyaHdM6X=0X&t>KwM zxmH#xKqs;60SC7ljCs^qXV#_NyCJwldk;Ew7Ko^&)sz=hxaxa`DJm;2(R@s^Cc)+- zl0jk=M7x2=0~zbV9q|Maa)dNQ5Oh2i-ec<>Q_O3PTdnGhT&|`UT2v)z(lk;$xc3&u z2_P{iyA#)_60@0{J;MJ0ltl^-Eg`?!irFr-^miHvu5^*sPe(puYK08(Oc-UAhfs2Z zw@!nK9wZU5`Xec|tsoI_r5+)*IMsZx(^V$ZM@dsfUsFpx!kN_?vDs1AFpj`R6V=$T zJ=l^(!&2_+y};@PxNGP0RpP`JMu11YYP6Qg&vWz78pt)^KA?TLNhjSA38>Xpwb*3Y zFPKz&?N)E_;x5pq0!py5TVCgGj#UgK2;(Y>OJ}xo+pc;Hb?e4)H!9LNr5b)ag`MPd zq6Q75G?Sd*0hVRylbm%KAD<0lWYY>AqAf3X(zmPJazd9FE>xvrlXz(&o++7`c8n0O z8fPSZ;f>uuGOSn=?#iZS1`0Ux(x#-#NmDdXrA$m6c8;6JzW{;avL?vi%`3H_+H|g> zu7-i*qSSPg%?-zBr#@tJKnckU>GOs%ahwtu0;fWVkA({8(Zb3-sddhi)i)Zr>#ai5 zbC!-O$u$j*{{UA7ViFmiS&}%Vf>HvpV(_TJIA!U?o?Jvfeu_QY97A}aZl9`q4gUR4 zaMo2c)HgaLcBYzYm8d94dN}s}@2ds`mdYnjzqk$wVHFz>GamL;7M6S{@yUM*TKkz+ z`VB_~Y&vewAz4n)gKuQo2gnx znj`?Y^0yYiJu`p@U!NQKWUhE3H!ZpSs5C9$B-(b@U1q6O^XaC(z5zX(Ytoz%-y`S6 zqYF{sI53gIHBoJ5Fxl{Wr*9DzR()~H%Dd$aIkdDY9Sk>kDrvr_%ahBHdws+6^qwcktTdp*88qWUnPYoQ`D=Jh)&TdhJaZ1E00FFIa%1THcletbZqZQMp3rISt)OpMt-4u4W zOe|GqXs$0)8tn4kmYd92Q~|YpCvx;2;Ag4p!gdfi+5Z3~I#|NU1-~?croz=%w|W|u zm`tl9M^wRP6P%egp;462VUpPIz~>E7qhr&C+N;JTg~Xe6{Dg;@FjUj&YF3y@iUyF}qx4JTnse~=*aN-^E#fW!fe{{Zv;Tmnq$uUTtdPYng4|zHCEANzDHOdrl;YlmV%Y8H1u!@ z+sz9+tt%;U67MR5p=TS20|v}9Nv1&Je#oxaKl++a{5S5Mbf+?{mWoIxuCJr?k_w81 zV9D5$6qAy3)4vgOA37}74A2QgRp;%GP}JM)7TZM)(uUtOHMKJ8L*-G`vNC{@DIkcK zdogywJ68%jo0@JKcTsgB80XEx&zpLiMBi_6+$`6wUQ%6Jc_`W|P4!kEA|(;WpETeC zszBOEDpx&o#)Dik-Df$j4ls*82)T2lxzDfe<4`V3-5Rlt7O|2>_KuS+AyjXDk%CYj)AfC{;2jJPBLrN?<_tM^Zq`oMU5>m zJ};;8s$Yxm7m)J)icLGGOqG|}06>r-b_~oB6+rvaGZ3nyxj#-aD^zwchKn$JlgV%4 zFwMfZynWs8=9{@+;I~HGG;-=rcw1)Gda~shtFET1sgj0cgo9l-6t z99q{>!vJ2x?~mhcB1EWEsaqEE+71@^``dG`AtL49DYU+b)t3!t%G>2{*!HR^lBY@B zXL^c8l33YdG0x=65CmkY-Z9uO3l3@3s_Lw4W%i%QuYG`Qf*5{gzmV{xTs;odf>A@fgBSryNrWwIKlN@y&pM@`Qd&Pp}@wNN5 zVaa0sZMlRN2;prw@K|cAeEmFBP$8V zn5?6yVeSD1NFamMaUoQPWp&gICb(v8l74Ahjq=HEx?53Zr!3LPrUKPbFaYg&e~AZR zJD&dlJ}SgCNPBnssnK(;$8D!XAZ6IwNx}IOgTQFDfx`DaJ-A6Nkn9SipmVqq7-W8& zAegCesGc~P7HMKrleHve7|(2Hfd2s6R?b}14;1r6iwqLFAW-mU)9;>#`}m9Q3VbmA z<{}n`gIm*CZWkRLd7!t*u+s*jtf8lxTG42{{NHPuW-7 z4rl6G5BxXonC*Ok=3EU}YBWV$^3?GLYMyEw>+C6Q7BH7Bsp-Ijoj;6Wm!yRf<3r2W+wS1NrfW zT%X`?Vvcgs^8&XM9t2h5%&A-{^1pJ*nHd3gU%jo)sgK=a#VfT<7qdKn;`if zE~pD>Wfsn3%Tw!bB?^xd94>fX-$_^7T;8RyStWY9ma3$P8C~Q%m;g6_f#Wsiq>65I zg?#|RbG5K}DmSZniDdB;HBOk*HJ4i}#a~Zxt*?u6K~GB`m?x=VtO0F@%Z#3-u<`j-y72aJ!}lsgfMbmZ$!GiX?c>l)p~Y@rlEvMJ50fe7-n2|9lwzO01i27mn5#8 zngo{BL2d)ZjJQypVdb=~nX0 zk35n{j8%`CvZ=wxLyn{BI&eC zZGA@it5>DDr4)Bq;-Wu7zYkK-XYVe=cm!;ZW?%g4H31CbS4B+$xJDh;ub3H<==P-CKpASusGX1tp_FokGlU?asFE2TFW~r{f z)W#rRDN8nROUT5Zsb*#%btQ=7mKax(d&8;IiCsypMWZ;@HQFxTK|V=F`Pdu#h4`KYHo`V`#s2VwOpRY`3j9{7FLjOPuimb*$^(qw5C zN@rG$4mT2{4l1umzN-Z>E+h!zc2mMu6xiofFwhB;uvAAz=o@D!thW6fYLHD^TO(aB zwcz!tk$o}6lm3Yb+N0>r_nh(USUe!YurvLRzW6UK#o|sXp{cO29KR=ZUHnsDq`6%H zc?(lhws&{jexLmLaYtyr!Kkj!Wyw`)u4iIoa#wfola(Xbam*9C=oEt8a};*?A&70- zxH|`9?~~K~c)g|sDhp)FSMik-lIjt`_cDb)rZ{p*Pn0Iw3Mk-@Fp{yisYvUC#RAIG zq}p>)U$p!p8&%S}j+{y6wIp%}rg#3ai24cok)N*A6QWZ$nU5o=OAUi_< zeJlV6BoWx~^y-&*4dp@XXoodHHC^KSq%@*d+iBwv)HBk}J1?4GR$O6+-SuRzP)2^Z z;h9=V4cS{#fnXVqs4B9QQQv4ALHTsy)E4_)$*lf-k<-&o?w|uzNfkn<&wNO&gPaVE ze7IUA5{p!tR_#435*rv-c-7fj-DHadjP_x;etmdwLxhC`V+ZbsS!1(q(!09k_8(8> zz$>6KVM=tBZ1720Pe>AK`KjDfz~p-0*a7Z-pFD7~hmRJDw>{LV7gI3n5!HJJv#hO# zp=M>2y0WsoF_51;BLXr$M07ug778@lLxV((5U$4JT*p&=M-c5nC+?f|E%JMu2~Sh- za)@6jVWFmof)r(mjwL6d_dH)DpkM_kJZ0HoRq8yYCj|jwTRc?iEo4TwKK)d?_f?W~7C?X64b1wQK4VoX)k+|- zTRsY!4=jW;)PbS1h?EzE&04)>Y8uKG=gX_^(3vD%4qSShZp?1k4 z$rS`F4pVBWCqF_->GA}gLqNP7X-rUpr4(Lf}S0X!!V!I+yVHKpbP=$4xOkyO<7DmK;}*ru}IWsFNT4Fv*8 z3|amal1UY$?0s8QA7SoBb#}1B$Q@B^!#=2*Y;%VYE%YmzHtVF6{Z&N0I;r4*NI`11 zKBB6qjlCNb9;*@B!}9mx%ZW_^ZqpSIuA+vju40tb(s{qVEI}*PS06HVoP9Wfk{~IF z3VCwo8{F7ahLxd_Olcq;>v6da3w+JL$6qu5akuP1qTaPz8TzE^382Y!OZ8NoMPW7Ueq%;pr6oAT$CrK22;gN;_^&gK9x=7J(p5-Mn zp}LLabYK~>4_uOc_*2bB5Z_s8Yi5+Eg}y&^MC?@{2cQ6Cl5zDI`SDkF5rY!_!fLWv zr@BW_mbgvA;WF&o0|Vu$$Ek@pQb_uA{#OfVhIyIIx;@eI9>J`mrWMUyYPm@o39b~Z ztW28*;?bW=jOXNW@5OZK3ShJ=@feq49o{$z$f2V}a$T8%2)2GRp-qatP>3dQt9ms z^$P6QYN@2Dm&+q;B0^Y}C$i{ZCVSng|pL z72A0S)IIwBdhyR=9t+@Vx*Q`2WTC8Z0T3i(cU|gw{{YjB=zxx0L;aH40>h?xd8#>; zbVXaO&hVOE*)flNu_#n|Rxg*B@&HfD5%TI4M~wMNjR5L@i21Eb6khfc!JscQrdIy| zGi~gzh09fG{{WAi%#^Z9TP)MYBxBG4)Q*D~=s44E1(7ajCz{1Qr&vQ-P_zw!Bj~?4 zkktqfZ$6HUxbL5*1A?zfyyH_O#j*pD+pyszoh|bdWRM>5Rv|e(x5mT!;{)^I!eW-k zCg{N<42QAz;@y-{PeNa>mg}rEwtIwhbrr1`5=x=Eh4#-)#1n#j`g`$hK`rU*s@Pzn zJwGSxm3In@rF8;aE|pTXMD;a8dl?wyl~ILWr#%M(5K6XTNU3x+I*cN!51_{lmx^q~ zEE-apFT66tx%S~gS*)~H=vx)ZSK{qdb%b>ud?CNTg$dK0qfgRXqYzQiQ_(^X`M6_M z1M&lh3M5@j?2!eMGyAi&XDqn<_?S*qt)!va($p=<1$H%sP1{Y_sC1QXukWg;|R%Ml;la zN`)C65p&l(R^QvF$`$e6Re-29(zULa8R{{$UCZFPWA!ASr2Nkubiflbk47+W`J(P+pZ!O+fbgxSVk4szol4p z1Tf;1)@#QRK1Ro=`Hv(?t{I1W4+9>0gUI}kRe5zZm%57dp53P{x{iue-5pI;Cz~W* zrVSAxhuvV^56`|a$4Jmfv4zSP2AC^{CCmDl=jF#fx>d0T)&6`W$;#82Dyrzlf6Ag^ zA7Au~`^5c9mHz;1gp%J&bN>J}lq7UH&vA|>9HK&)P`ygMJ3~8DR7O%rB~hKO4p%=h zoDK?WWGV}y>e^cCh1%IkT^I_rFr>RfWGN%4{EkQEz|LuD%2dGwNK0doV+DafE+U;~ zN-$g!PtQCuaJHhLZ&1h8f5(PSwm}}&^nh@Bk-|z8g4)UEqcRB)uXzRtIl<~Ul%*1$ z;I_3y2lp{MAoP@%0R2vSjw2~Vs-4arOjljCRdn_%Ty(EA%_T>la56^j-C31(lBAQ^ zHa>&55tQQEsD-nay3dzT)LlN(qqNb$JlWj5j)SnyHuvm5LBvQ0P^JoHy6ai1F6mnu z(j&43sQ7=~tjr0+;9~@WGvBDs3|gifH%epX9yfWWqB6(*AQCU(k%Nz}GsH6SPtdFP z;bWTi&UEOyTMb<`ZB_Et5|~z7sa~PYGVUTd5lJkhXX z0_O{#Rf$^!@IYY@5EI5-`$X30Iyy}Y%nN?2iki7;E-P)Ks4)4j3riY`qx+}IhBzJe zu-%j^!&b!ijmj02FwUgx&xK4ZGzoFKQNl=7c}DP0u*v@b59h!v8Jq$=<{C=&@kV2y zs;zQH`msog0KtJ-B)L=m@||7D+PlY0ou>onc<0wgDTh4|^Wi5-Y3dr5YI?L8dTA11 zK41`k!};)&C6!dBmg7|j1(FHgH3PmfcAwK6I!V&eM_W-<5+gVu{lNW5{67zVCJ6;Z zfNZU=EmYI!${KN0wJ!$cV5^TWB#^o8e-q!Y%Za?^Ih8;~l$;Wyrd0Rz@e3!>edd#% zq@Qz+8aN~t$j(otPJO@U!xbq?mUoLRp>gtI+l2`ww(9Bp;!qWn1FU^NEO6Y@rv()t zZz#csK)dmg`F7$d(j!3i5|T-Xp7}kvkWtYgzUfJ>wz{fSDg^PA+|daa2j;8@KbYb~ zN^KQo=4T{f<>eGrQ{Ad1dYLxIPvu9DxGY_;H*M%ZIKdLIRiMfkynkk$jJ{NC zz%r&h#UN+ZgM-lIaT!z5ST78EHkVS}#bDNUeI+Fk^Ch^jnd?MjsWHH#4A=(;cmVg$ z8F<$Wxl3n;!g}hoFon%_W*>bK&zX^H%daH4qs_Z@$u%B}thLFeY3p^ZQI_>bN$~+( zK!5;`BTKu~SnT!$kV(O_D@2(hcP8<)sxdV?$H-^{kO6bynbFwpI4lWJdJ;2(kET!R ze!OTPl;2Ep{#a>knyTY*qqXU&nqMxmR(2+M$pV;#Q?^F?z#fGGInPcGqeDurATrZ`rdHjS$wVDT%LBfB{+t9(p%@jB@H?Zl^|J6egQ(<& zrm`E7*|hb$cH(Op15H%pun?q?gwOHH4?>(uknsb}H9$M36TquCs4ufebd*ISg*|bc zalQZ=u5!m!&hBpOy;-X@7s2Xl{Y~fKRaOXF5mQqFpp=FL#BnIjFp4`wGpvXJv3#T-*ST+e>n5`@RKLaCvs338Nx}O z-CG&_&khPmgGJ0ry){WI(A*=6vPIYwda^yvJ7*n1KKSBA@F6%7QEQi+(4*A!a8p)Q zg}8u2KHaL|b|iZ?JB}jPN{g5QmZ|!yCIMV$*zoEQy%{I*_8c*?No_oBA?>(<*dE+8 zl<=LXt*rzgp=lM)PJTo1_Th?nPc-z~@e88H#~`VE5U2Cc3dturOJ_tAG8V^K2k8fkbQItjG z)r$2tu(mAr6JHC;sv)j{e4^PHExFJhxadwkd=FafAQ)EDaBHN6GVx!kZu9DSELGPk zYV|@Y8Y^vD%}Er5Y#?lRj7T@#!Pv zPX&Nb#ak^1btMlfY_t}QGfjB6H59bh8WV3VOC(}Ol18g?3bQF-LyVre9^7;^^D=`# zZ1U^HbJYtSS8W-wMmJr~cgyW8W zsSa^15Ens65YQZCqt_~`g{gUS9U}ZSEY#6W?V+w$%C zamfGxfV$F4jFgz3ow#(%J>G@E>IVrVvZFHDsN@}dsbz$L><-so?|;*TnQfyUXjSsn zwt>`x(}qr#p%I?tN8!`;;w4BGvX1jD9ZE?XIuvh9sUe0v_(@8iS-IDLu|W(pwe3?9 zHhj9M)sT;uZ19AHW+$@atK^=T&VF1X=WLiYv2|wY z8O=0pBwkAtQqh(NYY~#9`{St3(~AnFD2}+mrK1c6;nQjB`f&(PD|x!_Rsc#t>QR>& z{PV(u@|8nzBMj*#&7nf7cON5@f#0VIB^1`W9^ZevwN*tb$XQi#@q&5`VCO%l50n(j zJvT1x^d$LIK@Ktk#yfoa0m3W^2PVmM{1nAlz)GIIv7R7UqzVe^3jI%O7YZk$t`zc2 z#7tl;lCFLBlYmAtK3`5ES_-o@p)y*Mw_8?KFvU}DJxWK$~oh!IMU*cRQMDSv49 zc57pq9{&I;!GLvBE_ghHqu;7FbF-M5Pe*dzqwLLle1dkOG=w0QP2gbQQ~4_v?2H1y z;2phG04o0g={}>{7~)T#;>z#-S9ZeU#(~s-YoGPJtG!)ql=nNlmfbyWt3x$3S89bx zq(X8EQmV9pPq8SfM{bzl?(h>RD1^S>5?XGW9*_}GsRbNMBqM76?y_J`4_p=LjtQiE zOg#SSs)?lG$f6}=vd>cfQ#v9YfGUDIanqO!l@fGRhneda^xET53W(CHWlJa>ozxfo zTPO45j-+LQcDR5AS7p&f8?WMcwG6fc=^suKNp+-(ku3o^H6RG{?JDHQ`sJ7Xz7l2S zJn+*;pHntE07~`x@RO%YB=+eXrF;|0&(T^rwr%U*7&#;5!zT(sY0wFLt0_-=qJo$* zt4UZHBvO5ffPQ1K#|$Km6A+BLd&9PkdI)Ojue01iP|Wnzkw*)D2Wf16d`vfrftf_z zAImK@qpA|7(`tq)ow!=59j2ED*gF%9kLu%v0WPX#NU9ZABri+?Iv@CU;gU*H5@i{| z`3w`oCrTi1yo9F-Ev(1%HJf}t=6Vfb`E%ZHuQLWx#cYH4Ma3`)(PTPPU%6Z7GTN)shz zB<`+ENsQwp<3EAVw-q^A3s#oYcMS)r=|(okubjb#g(EIUl5EMQm31+9$ zw>=TeT`Om5s!3`nF08S*l_rhRDpauCyOE9y90EpL0P%eLNSqyaWKSeIAztb&k zLc~iTbAng%{{S93Vp}&0mX0M;erCvzt7R*IJ{}Np^Vm4#DSQjI#Qy-4``JYa$l}y0 z*gFBjNqxDK)TFB~sYv!CsNp1>ZwiTctvK4PD=-7wJ%7CLl1bJ~zDG~543coCy;M_d z5aKeOn0NeshlYgmo+vNZJB>sX{{R~#j_d$eV~>|#kox0Ay(}e{o36`=7nQ{i;g|qj)x)FoKBZ7H^ z%Uc~>YTj!41_FWd@7o+P3FSv>ows-E?0@IOM+C)TE0;r@ zjQbyMCuG{FUbDIUENL1(WrA9H9-!=T(xZM}N?`;ITA8Qat<>mS>6a4K(Ee0o_xSdq7lb8l`gYH()&?EPg_UCRN`a*M90A0;r=+GD1&eP55XZ`65jcI24lLm+UNxQr#_(J3Uq^*9V8GrHo zMvMNWE$kgEUg)1XJ6YIU{G@wd=m-yY;0q0*_(F$!fPkJa^vnxQY3FVadZBNAwzUVE zx&i=@h(GJyfacaOH0ukE=%T4E@j?p%0I-Nwf1=I)M7sgK+$4e>;^t1!IxiP7ln%kPXSddCM+B=y#cmn{xjrmtW|7ly&7bA1C@o{rAu`{#% z$x#1C@c&`?d2fHCF4TVAGcfGYKkEL8&#@2y;JtdWP5d8qW*GoLYZw54yZA>PWj+9a z@^ar=#{V=P?4SN(?dImh&%)yA>B$TNnlt}2=)cSVmEr$E`I9{6pWXf2JfxC9OH+3{ zH`1SWGk3Iebax?jbuu*vk~00>iT}TD_|JMUssk;7EfKpc$%ATbaC5Qe!g2-v^xn{$45&2cQ5j0eApn00n>+zyx3i z@Bjn=q5vs?JU|7Y3D5%=1Iz)|0DFK7z!TsL2m*uy-U8wQDS%8s9-tUd0jLEu09pZE zfKPyazzARhFbh}$tO2$G2Y^$+HQ@dwkimc#5^Mo%9c&Nm9PADp0vr(>6PyT~ z8k_~37hDWn0bCQ@2;2(X8Qcdv6g(C@9lQ{{8oUMk6Zi=DEchDu0r(XJ00IF58-fgi z34#|w0zw5sAHovC1;QU93L+Jv5TX{M17ZMT8e$FN5aJdR8WIDN6p{&208$oG3(_3Y z8PXpz8Zr~I9I^$n7jhbM9r6_N2?_~{5Q+hcA4(2N7s?9C6Dk}k6{-}f8LAIz7HS*n z8X6iJ8=3~12U-?d584L$HFPv|4s;##N9alDP3S8a7#KVl1{fh26&O<(H<)mk447(| zZkQ>UZI~Na1XvPSc35dxeOL$BVAxdHO4tvuQ?R?R_i(6iRB-%oDsUEX-f(en#c&;P z<8a$>_wZ=&H1I<3n(#L8LGbDDweWrL%kUQn2ngf|d5?gvO-7l*6>ae2ZCw`33V7 z3muCSOB>4zD+}vA)*3bhHZ`^!wjFjHb_4bt_8krpju;LQClaR?XA0*BE&;A6E)X{g zw+?p}_YRK~PYTZ#F9EL=Zv`I`pB`Tg-xEIk8pn+hK5S);nP@V8K zVG-dd;S~`vkqnU&Q3g>D(IGK5u_&<(aWe4-;yn@!5@8Y$Nis<{$v!C-sTippX*y{y z=_wf@nJk$*SpnG>vU_qGaxL;;@;dSr3U~@$3QLM)iq90Mlq8f&l)jWzl#5hwRJ>Hy zRB2QLR6nR`sCB5{P`6Tlr@^I>qw%4sqFJUzq7|WarY)qMp@XL5rL(2Wp_`xwr{|)# zrq7}uX8>p5W&kndFibK+G4e4wFcvb-Ga)jGF?ldmF|9LWGb=I&Gq*Ayvrw|=vm~$# zuspGHvD&c~vo5irv&pjsvvshYv(vMivuCl-a3FC=a|Cd-ah!27Z~{4VIlppYa4B)U z;rh(=$j!s;!d=U~$3w~UiYJ?Ao)?o>l{cDqkPnJaoG*Z{i|>}7o8OJUf&WB+Nx)X1 zQsBEFjUZ64Sa4H_T*y?YKxj>vRQQ!}zVMm|nTV-Kp~!|Pg{XySspzg4otTYSwb-#Z ztGJ7Jv-l4QehEK`kCG6QGLlh}U!>5bw4^enzDbiyTS-?*pUQB_yq5VW3ni-{n;<(c zMZPAprMedu%Sq==%U!61g<2nl%%w*Or`9g+^PalkyA-hSy81? zbyn?EgH}^j%Tn7>XH)l8AJD+iFwv;gxYiWcjMH4wqSbQO`mBwjZKz$L{X<7mCsAij zmqpi4cSH|g52V+o52LTGU#fp)AZ3tZux-d?7;ZRcL}TP-G-Ql#Y-jx51jWSEr12Hh zE1g%BuO3WQObbn~%;e0n%}&iF%+t&dEJQ7mE%tyyz(nA#rI2N!<##I~t0b#EYZ2>I z>qC$PC=+yMBWsgq^TSrfw#@d~PRFj!9@hSqeY*p?gRMiaBeA2GUbh5Jj(IL~<71m8r*q~PR-DUqp9(~{HuGjcN{v&yrR zb6Rs>=MCrAzFK_!zF@a-w&<~VzZAF(wH&pAx{~^h@LS<3-D=$$_uBh)$@S3f_m)LoL@itp^-yY{5_CiV^Xw-1~S?hnI{(2lZ?X^)#uL{COfbx*g? zT+W`)qc89-$}TxCKVPX{eY>{5zW)(*gLhMY%X>R;r*pS^@A&}pkp4*b*zu(BwES%U z{QP_*pRH=`=;r8Z?dU|x!ORNa6_-Roln>#xEo(lbb=>&AJHnjr&LLtnZtbhK(SO6XDOFe+1P%``I*N95gr}^9v%@D@mKl%=bsDM%NmV@h=hxZii?SijEwp7 z3mFsb7l!uR4yM7E!^i`u$QzP00Z{3{3}C) zgn|Hv1_Qvr!oeee0l>i_{*1m?ZFc2?a;I3fc5NMD9C^B?5 zF*RrmQ*!4ZO!kBV7_546icjj3>m1l-r<5+iXH*iL8i|Ds=B}T)Bx#b08o6;aE!=vh zHejhk;NWrbLX)MWi<`8kwP^9rH!pf;wl0D0VJRieeY4wFmLB1$r7it)JJ&oiI#!-< z(#l!~=68Sa%IaEsMWmOv4SxN8L&qnl2l9^0sAwNr*t@0Ym)E!PiOQ_(7+&1Jdl^3X ziBu?rYYgRv5Mv~+cnm7HS5;ycQ3WKFID(zw2H%VB)v4`{T; zndI~{yEc-U3LZ`p$H!@RDRwnx97g4`?m0Z?i+7Ptl5iS{SfxCl-SJA4L+wANKTA?C z>tPO?P5oGtq)@M8R@YVk^a8#d}k^?V)qZ&TcbJb=K|1 zzd|UcVK$|ZN^|f~n>J17GrSlTU)^hvlF zt@N-p8@vzWN4|^;+JeF2Z%$L$xb1gx%gS*@)Oo|NYotVnVlsqa&XZJfC!6C~6&!#q zEz`9%_J)sdI@`nut=|;MX|E4FF%C)I1)4JDnOdhN>RW4LyV_G?zw4tyk(T|O*9&yn zS(zlAy}T!QyVH^Qs+Rjoy(?-eMW`Kdc9)Hv+m2Hayf3r=`0ivfc8}6l8jYUD`b{rB z7b$uZ3BJyZVXZh#-Ie~whEX@o?)oYF%~##}RXAE@rR2z>r6$iSzgpa_ntof#Drq`dRyJzYM`(lrKM z`1u?U_ZqQ}+SlT9TP0-jS2nsX`$}v))-8>kWl;x<9m5?5*+MlJCw!*SLPs5PIiY}7 z1=|=`A8Hw31Zw~f28Lx0?gq=a#Y%ZboF!-l(fdpW?nTx08AWv=Jh@O@a9dMm4RN;& zo+=Tln=IEmxbKe2;1a+?XSf)Q1zq;T_qn>1ZXhv&_)0wDoysE3L9OH}^ z1?L)tUDsmnwb~S=y7GDuu}W1S!|I4hA~IeYT8vBLdix&Tz+Rj)Tp??#ldIdi*CNAG z4@5s4o{Y#>wlL;qC4y?aI%(SeD$_HeEAvUaXq+p{Q_3~F=LCr+o?(?(9 z?6&PR?6JtQ?W?}kn~RY}j1S-7;?mFA*V)(?*r{R`w~*p(5GdG*`V_ht>Ysgf zrXfjY;Xrf$Ol*daX&-e7789p5F>llt1r~C}#3ii&erLu{_8?TIn&|F$+HBKLeg8 z(-#jGYu=YMSCZ7S_nk>u#2f#&Jh=76H>a&p93<;N~%)#%NBIE#@B-{!_DB<}FW+0s1 zGCYRnhZ&@Mp2e%FP5@{0KNL*v6Df^(g%2Gy{HbgC;k$5|P25RCZ%G3lV_m6-mM z`jh>^wKo1+2u5cE8SE?uMGCiOK>DN*D{ZpFGXR^iVcjk7B5pN9YGlYFQC3Oet}8w1 zTd}#VERx2#$@m>Gx%G#>Dv!;8Jc-~p=6Pj;gg=0 z!_Dj!Yj6}8Gz7Y4if$Zoy#I=i4uxeH+^e3IU>NmQzHFMNLr!f<_PtF8@7Y4&rY6O0 zM~gWG(=n4TWpTo-<@MqY?|VM0R)4kOZ5@ZT_@V+nMb?up-BYZgLR%enP7DLsC?Tj3 zUoExMOg2XG232RRkr%V5=YnT`vb%N~M|$5iPLPZiSdAr0f~Lh;q7tsax*k`oFIqNk za*?E6U^TH~W}WVY^@`kai%F7s z)YZJ0YuDmwm%hpK2%U~p+3|HPBZinWpS$6pY(E3oWwBzKe2h-F?*&KcK_he)v)qig_LNJ9uwt;bqEU7D&FhGOMo>v}CAj6&(a@2sEVtb0HA3fk8636A;E^ z-@`J>tC!Pg(K*Nhx%IfRwNtl`%$@wSK@?g9w3uJfRC%}C0%HP41>-I!)>{!# z_=;Mx=opwU{tgej51;0%%ciYfYfc}-z!gNX@|AO~L|T%F^~i2W`5Qmk-&Tzr5EUvA zeMycUy-q?^lD((hsjiBlUX`*o_CNnpQMP1ABtD0bQKX$ZGn$<+xZ=4v4Z)yNlsmV> zu_v2EMsWJ-W5{_e{W;2DIr*DWVr$tx7~bn=faQ(+n}%0E6BDDT>Z`&noYdX2puw{+ z--BlWpJl-7{19b92in*3YoFuKRLCh+cCs{6VcMmU5z!K>XC>Y-oawMN^Lzxwnv`Tb z1HMQ`#MC8zV{isx80-t@v?&wf%!Wj4F4;B8%k{$Td?t)1Nu}1~B0@%U#7rQ_a+#77 z?}@5gI9Vb~p6S6OQ5D}e6S>vEPoW#*O2nP_JK1^$2sK<>Vc&FhA-?6d-IB9^2J{Hq z1|^K{%6BJF)_uf!1&9jZa*C_QA(ogSd7kDyUmU73l4eP@-c6P8S{$w#7c8dRMX#vz z)!H;^$Q#MLA>j0W8Q1{glOMRPpZc<{fsq_>kt1q|$=xRr?QQL(_;Q(>8{WFb(U54j z{n5}lSjNqkj=SEZuEit@uGzXfMcE;#NL$={hXTEGK5|%*DRm5cVj=cL3U+1tliCfd zyCMZGNMsTCyvDX?fO!Zq?SS(hO`#b?f4ATjk8jr=8>?Ir$)oEa6LQ8A8AT)|0>nuee$@HZI(zeV{Xt8((~ z^I^X*NduD#bAGGywVuvxyG5a&<}^j;^9+h@^#Qict4Pw0hA_%Fl@BSD5%I@hXxAtt zETKFa^v*9_O8Ue3a?l9vG@xEzBs0Wcdz~NJ`qA&*xWk5>; z1QrrO3AY|3Q>i-hXx}6Ve@OEdpt9<2Cun4L!mHzX2)10|TsOobhChl1a9JOZFmWCr z*kZ>{nTTJLwoIAuXISif^d;LWW4CSe%N{~2Xz6Qc@lx3}oNCQ_ND|5%A>As4N>b63r*yFk`WHi6f*UP&=F!9!yHh0N`alQ{dNE1!ukwEfXrL5w!W7Fzj zquM=VY5^pE;e5p1U+l|GC>>S1QQwg!fccgK!~@%~ZQ9eT(YfdT3}9RZ-GySG z8yfGq##IliCKpacT~g=IAH50}^#CRz27ZX1esbQo$}+kjEDrGNx9>nvmv(}Az&73# z>cR4$Kh&}OGE>;1hf3=ddW@c%Nm~U|fqC;`+?cO!4B;i(6WPT3-oDIB zCZVxje8lNqvjFuoQO>V)qR<~bZW@jlw`mRAm+X+sLAs`nU!m~dzc0aiQfs*GoL#RPv9}0y4fHlaL2kqd_@_RkYbhMagZ?=FD z%(C=LJ;f26lbT7*nWjAS#KOS!jAb^#$;@oGhqzfhgW3iKu%*W#SpXl!753VB?pM6` zD1#bbp8><~FYJ(;yYEUadizs!{mUW1zJ)!_-;->AraAyClz9n4vpg5-r4m!jkHjf#!0ZWB21(pKFjo>(d9^JhFSCy0bL_PwBo?| z26!Vp;y*wV5rNJ~G)3VkWzTp9}y?X{c^wK_SNIx0*OlYQol&V&x$h!I-4Hb)6dg4!8PUt?qg4b#UiP2I97VhU z7rzrgM5Pu8!0@*|FH5dzCSnnryb>6?>a=pSm`Vyw9A|O>S`_#weX<`>m_ZSRd zV{{V@>_5U54fL=z1jCS;eOAd1*ro2d(}x%g=8j)s747?uE9qIcz$Icu#MidO>*DRX zU0j8eV@C<1jG!t1R2ZN%0=pCyE;8z5Ba>f5ciAw0JLvKZC=z@-6p~P<_!_sWI2*t^M zGL61JGJoC=@~c{1|H5y?YK!R&R>tD*JkJBN+yT!3M1J=}BqD+4R?^wJ$pKV9(?S!~ zfakg7+fA{0e21(u-6?^*$_7IT3TgC&nFeU2j~%jnzA}lmuPh@8$th;0h1Wh_)<}CM z6w1l)yqUI4Ebfo!LW>l&E~vOC8A<5}yxpIb%G3LP{+YbhtEi*xu2ZNPUBTtdC+~e? zaWGyx)|e3*@DEi@;cg%ZG8QDpx{2@Q8*`z7>ydnVLm?v7q3 zFy=;XGGy?dq4j?8IJx#QFTaC-*|&9G?C&7tU<@{X8lQaar&y7!w)A7}%93EB{-(jl zRQIFl&$TSdfV;g|&XuqMG84n$U2;W=S3E8srt;we-AXw7PRy(V$qi%Dz@Uq;M8Iq+yjzG4`d{GK`9QG8XZi>N#6m!c(n3?7G+oKL=e{ zKwwH%BZk_DB|lFh)ws_1Cq6nP6ip%HJR707vAK!y2qKcHN1zm*G* ztljG_VeDCYzn_tyR7P^*jqkKCJnQSMB%FG#vo(-%MX=D^SxJ?ZeA%Qc3>BFILq-v9 zW;5$RyLy;KAd6zsGUax!fc361h{;}6jXVNU?GiC`vzN9pv`wkY_KQhcnm%^h-6138 zG)+peMHt;)J6F-kwZQ;I9FePCt^wl6`Q5ZehjV#`J_DC(7@qYMzK&UdIZJ{ySi)`H z7krkKYV~_<5cZ-Rq+pTwr3cg-QhuGtK`OGTZhpa#iq%g*M{n{mr%$LOc#;)QmIBNO z+6H&FG9qV>j?VxJjk|U2EW=5in#Xs~fZUhOw;^`5t+s;{Af)Dj9Ot}ECt({vUX{0O2 z9%??bhO8}>w*Z*jIQ$9KIWqRp1wT*`7Iy5iAz)nLk$qS0Twm9SX|VN;x}Np^aaUNKi$Va?;riWnY>CrZG4{n04YegQenC)vVc0W(b~An^1kX=wKFwKV z>*$j7>2$v&@QlRRvV4f7yj5zKru5O-a?Ce3t!ywClp>ymYkv$G)8`Fm)v_i`f4=ca zczoeA*ai~&&NJY7;=)Bx%paLd?lDs}uLvFo9k!qZMeQi6R$CQ705*YwsMW3NDH2QH zAzg7_ua(lL!%RQg&3Gue_+uW=mM9nx>>2QuWZk4Eq0dD2N%Quj-fhUG`}A4(C8WCY z^1yo2p5=*4idT&PoU@CS|6b`+}>f;pFcH!aDhntbdq z-f)cEX>AA+%{5h`=kfL)p6<+&Tis68CXcI%ao~I};lrm+GheW)$Y($#@Z2GeGq*>% zC3AWCn-NnNSld)sMi)p-OvN|El5Q5f_O@Uywk zJ^`V6(;$*vlSNOH2AiBAMZigg%TCx*Mr;ccI)@)FTj+L?j5trLESL=qDy7L(3q#hU zv00 zZRr>Fl}n$o>6v52bcU!hTzpKM{GfFKU0-+WLlaKkO4pU-a)TQa0Tb}H&!sZ;a2?n9 zI&YD?*r9^c5r1@*cvuunw491YSerqn%I%|Jo$!_$1x>&m&S@{wY?V+OWu_&GoV1F7(AZT!Yaj9K)+X!UD_gMr@ zucp3LHs7zdmb-y-Y<{v$qN)~d6gHlKEtqDKJ-wuO24p&mV{Z=mYqS}&?_q~(7sHxk z9Z8&SDcWQ9G{3BpxAfoiEW_u%F!;;Ngi0WU(45z(K2~A^x1Z_=Kh0R836kDr?ieH8 z9@rLA#}ufP=u2598ktbm7Z!?8(hHLY+JDRN&rTv5YcbzCYmYl7*-neK8>a-n;-g0F z9`U%V9s@MSYKP*6p5SYVnt>s%d?2hMjni(Q*Ie9Kz&MZEk-}oAz}i-+e@Y*be+DG8 zOCGOc@+1SNNYA%74S8QzIG{Rh8p9T?5geWIP{b$sv%N3zw}PX&Q&fXMtsEQ?6ZNr= z<+LO+d7h#?Urlc^5*b+xPjj_`SROp%|5jNY!xnQ3xicD0JK?`=TrFjK1O`tE)3zK3?VUPp7HIlrOel(VcE+0%@vpPbIMxARTX;V>_N0G{D9KCJQQJntPP0?k=({XLC= z0poB<_e4Bd-9+B>?($1&I*Yg@hJlgwn0d%|%dNyItc_b|tAb0Q)DI3bM@^lR6`<3R z{<#NuxTN4*^S#O)Nh#=0Lv#(?;@iRKAQfZg2SIQs4`-?T~28N{$w>BbcriBpH-}CPo?3#@NqMLc( zZJXI(EYPGbS+?dgnC-5}%!#_|hzr;Cg20l?De*IXIbpzP3h9pbb+7dOxIXt$U)Yz; zxfO|N5QN|H6VgSjZ2F*VH3y3Hyg6SDjob zC~)V!y?4`$r$ryOTO$;O>yQic-rLY_Y@w^XSsW>1h+yXIlYKM0Ir_~|h|7TE86dRz z;Xjt z#t7%f2sOKbp^YSxWswnf7;dXXFoCUf4iQG1%wqAm{?WFuZ+vCz`cMFd)G`OaHXk|j z2prN8Z%4<=LPo<}xW$(v+hkpK1mWA8O8ix2W*J?C(WDP6Y3Xf%X4J((q`VdBRvP3H{xjv5zUG};CcFj7tKTKfpx0R7_K9*Y%v7O_&m+!*t>pTc8XYV{Wcs+q8DmPc%rlMCgc%*Mx4d7HvY3?hj3iCo zC(wTc(+0Q;3s`s=@SbD|od@hdmlb_87^l>*K0#;3H%gnno`56Iy>Vf%hP zf7U^vj08g_&2ZgzV)XuWbLcg(9sBzFvLohRuMT%ZiA4XEeg#b32Yr39!i#P`??MqK zZ~w<_;+U(g7)*<2z=wR%sMY;LWm8$%JHx@*GdGgsJgTSE%=s;Ko^KDqW+X_t$)>@Q>tX^P%N}%Lo5o?f;c?tjyy3Yl8U9hi3+wx60v|&B+L9$r8Zs1#wv&oV!6)q$G~Dxq=Nk#mgM$ zRQE?6G0}KJUWuM=|d1gP(4$w4j3ANTj+o7QMdgJVA3;| z^Ank?sWA(0rMrT|XHnL=SNDnaRQGnj(F+(F<+BP6gcg+@neIN5iiy2qf;e9q;h(xo zFy0rRfkN<@kRVhV)Kq=2^Y`_72JjHZ`cDi*PcApqEKqfCucodJ_Y;gTl)q|9*;1&; zrOZ@jRQv3tG#h-bANS4wi#c%a)Nr6``qEz{rg}J+?RKPikKb<5(8rLP!JESK=4)p? z%@G@!&x@8E3{vHM1^rTvm(KvMTt3~Vtn-F(+0KiW9OQR{9iAt-0h(tL{nYfuFALTT zo@L>U0%Nzlz(u_sj@o2jSm)wG7lwi(Vki#Upc!yW#^l`go{x$3l52CTpYz>$HELmq zYW3BVD$Gjim_=!o3Ip3AGcLr_=sHtKrn>(ZspceayC&{L$;s42X=FK0EpfW{!qYtG zo78Lp&$GLW(pBzva@4Is#}x3u1PZRlub3W*f#uN}8#`UDdU+_q*F|yB$>Jba*?NN| zD(2&iPzC<8D+E?>-jN9xqY(e`zK9%er$=SJez8gwg5fDiI@_8pbm*&T?Adw#OJrv zXAU)kh_H8+GewUW`Xxw~3y?ph!*Rdl<|$jtuIq{_aOO{D55Y5BaZ~~Wub%+|1hVdQ zR$NglTWd12lic)Odfi^Dt@nifgxRoF=Bbu4%V*;wtF&F;%d<(k7oeG`eXHk z#YbQpM3!2^kR4anXGG+u#yZ|@>r7U34y`MHY@eyvFWslz&C#dwkR$^a1{7`u?mGuw znY=}tu6xol(9RAs(wlg&y{?P{*Ek!`0Mqz(w0B!Dm%3hWl6LdP?UjjSG#c8%a?*Z8 z^^1ya*9&?(e$-hXn+JxhJJ2pUAS<#AJw;w1MdUp4Dm>VUn#y}ZmW$BuSemObWe6v) zUWD%~`e`WI`U@v6b=0APAMHg2!fhZ4f02=TTr%cpkSZ~fgAJmf!Z*bi42m!o&_r8h z$&__+yq!^b=xu$-wxh{n8-pn_@H2a&v_Ov3Nl^Y6MslGAEmfbe+B#D`JeMffaFaXw zH7wwHPGO|+`yF!F9b&`s>hb`kj;dy-zrY zEE%wiTp>NtKYlK`4VHr>S}0Zt4@pD0a;0vgP$N#ZSW253cm}XFzs-u_-}tij;4FyV z<;-(j#0kqsKC2jGasszIKvfuijTWU&GekG-*3I3wed8dLR=YdRlx+0qEQ{ux@Rotc zB&h0Ic-qp!brVClPVcf&kh0!S`%Yj*`gM2Jqv7c6CB=;zEub*Uewu~q9a4Plfrb=) zS^m>9{Ibhp$o(L~10~pK4MC$Fiput5wO0DAbUz;>WHcDMfG>^Bg!Ay$AiErAC$I&m zrKL>SkW_ElR_6os_)3|&xIodbhl(w#TL0C7;byBwF}M5H*!R6{rT#vSoq0NRxHczS z?|D8P*-Of=Hrc&)UV&h+aBS?9&5}mVea;XDf6^Do7&sRt>KNI?uTA?Omx9OvWXWgZCPI>QwvH zMtqe#MLO7=48unb7EEQO`xd*;3CW_AZVyiNXiZ!za}f#O_6``toWVur6yPPj!UYR! zkm#<{9;*Apvz;T6+A;%ILgks5p~e>XRTm@>T)<{4dr$hANeKK9o&jJP)W?-a1n-^! zqk5b_Vm~$A;wy+x-C4??1E2`bZ#s20ZW=))G1A$i6c&v`slg|s*zwr(C_Ic%van$- z(9L_($fdrlRH^2wMz>L;jx}JVpKVkDbfaz%r7H3cfaVQuRDQpd*`bz8irqe~$ZNHs zxC!=!L1a(@m>d21t)6)dzRc^8PiP8kfca=f|r2|GF73Uav<-;8XqPaFwl!}Ki} zmNRKZ4qceS=w?qo)VqA~Q1vhY`)Ufy@;o1C(;yT&x3Mz?+NNzvgffF8@D)=_Er#FL zj|L3heJCwICbHczWx9~VPTkp;L^I$VJ#%(!=z=MY7++$OPDT?~L>Bmp=}>Z;0yWmy z!;qs(|_^$FWz7c=;IR8qw#LY7ucRhY! zm~O$61ottQvDq+JS2U<^s8CeZwAY7wZ!p8#sj}+-+L1O{T(E-F!U1gVm_x?8b1Tzi3I}cLZ~w}a&na!%M8=!a{`#^1Uq+* z2&9Z;ZIsGkQdcA`$-u+mE1v-vk3}O-FpzE=IEEt@RI>&q=gMWKLeWzCvbClm2TAdW zw$5ihJzM3S0o-O5p#`IMgR(>+s23h32g{UVdqA5oa|+Wwxr4NgFqGG(n3q`uLJ0B? zsm_F?s|WnAjYoJ;R@G&1`vzkZ21eFi7W&MGaP?6}d+Z`O3_tSQ59)r}w>t~(7#)&{ zpy?<2^yU*SHcR88l2fkl8`>M-wtfJ2AE#Z!TG8Zn-do$Il&J6QnN3+(e-EV4@HfG* zpGRw#C!RXjJ0efy-WX&MmE|%4XQRK8^}TSdywzi5F1j*CCOzLC4Et7?vPvIO7@YY1 zn~uHC1)qcZ6kl(LVj7Yup9MMrh$1>r6CFQMCUFMiQ~kQgUS=sA0quSV(egL5H!5u{ zDQ0MQ(PzDt-=fXlA_7NWwSMk;2G~ya8VEybDjYtpQqtWxK*Ibw%sSSH_jL5 z7)nw$l!U5}c2meouok&2EOd&T9o0U30m`VwlET3@6Y-tU`y_V|)y&{bl(bbt?|e$p zVk$|Q7(h)V2a`Z7YE4KlC@v=ryHuCfZgFY1Z}Y%VnRV zl@}1+%JwA6oblk8G^YdyM2_?`otPv&11{q9{ok58)_G?SFD{?uae#W0pzB*-*&|kaXq`SmU0AW{}rgbSPv}yuKHrIeBA0SRuyS0AZW43WM8L4YYln>+fio z80ZZ%l{3D+1{;?5BG`HZvu|LOBjYkfSetV!IWxbZNUu)5N*!H)D|?Tj3MDeMbhzy; zo1*Xh@$%K=(81?Zn|g;WR|zd(0aE=z%BrhV+-s4>InF)7jDRA{td#eWMnXl5tB9|3 zW(bb(YrHjX+btQ-a!F-gTPhW(V5Y=z-(HXI;wiUPh0|H)D#J61w>%X!`)ie*4)3Ug z+X|vnXy%2ufHYQZ<{1>4v-jTl3F_0R=H{mN&OolX3;Eqm;m1OK zbhMt)KuS%l~Zx+C{i}JqNOzF>&!0+LnX+E9k4$SjPYyN(1L^*UWWzEyhET6 zWOo5-nLPtm4!chmoB*-cEhpR4B_G8U9JJ7=DiOjqL={3YXagrpP^)k+-|Q26cM36MzBTFeGVh; zZoh`)I~!Q&4hcV%1wD zX%=}3(a4T=8}x6phpY;i84{f0xg}7S!2}ub?Ex!-AZ_;zhOu(qGp@45;TzcRi!R_E zk_+Fy8R(DgwSu2^DcX4IU;>x=Tq>Y41R2rwT}1@nmss~1>6@iGZjaa|ncGbA8AWcY zpu4m;AbwboDbo|Rgia|_tPU+924-?Fm2{(O<;_&=oj!1uO(!H2G-ed_QhKfsur;?% zG*zW_#2izKCM-zPn+NmP@e$lE1i|MGwu6w-Fy;LUY|!o!Dx69_G8nH41~OJIz;>UP zwpV`z&9g7B3?ODp=yGp(f_Wt(5rO+;4=jwB>2DJyI&$mF*q0lwd~QVnRirv&MxH^I zm*IyrW5JrHPB0ltPd@`jOi1;-H}yI@+6>ZbCaMhOvngV9QMIg#;<$}XtN=@v5}s43 z9@_f$$^0I9=u1lm<&u(^@I^P~j_K0~$P05B9I90_VH#_Gzx0XI6i;|GLLMD??Z%=ltbU#I z?Ry`P4oA-yoBrW`E^TME`&Wm6d&Bu_m#*|rE7|NM#a(-!Du%PLH);{oq3Lt>@W&o2 zonjs2v*=kN0lp}Pp&^!RKyG5t9F+!a0);wCZ{(TZR(1pdw=$+SiuYZHK@F6m}$A9j(2*pVz1$@8ySeK++d<+4l0)u z>S#)Hqzrqa&A5wl-=Iq%OSaI{Np`O<^0Pb%86;PhuOGEve9y2?Yu5SN0)~6&k*@Bc zI)~p>WiqKi#iidbA0@H^2n{j$5TVeooiSCrGY}H@b0Zi zWVl8WlO1164~fRmUas9mZBBvS;FNs948|GJ7t;~CEy6A@pR_Oh+t+osF}ny%%;ZBv zhlS+#Qv%M~nc^}F)LcN5^LHq+R9$IP_34~P)J(zx7Ol-KF{UlDAK}Xj1HqEB!^^|j z`gyCdVag9k3QlM`rkOW!KI4Ug1kNSRLNDlL@A(*^ixDiHow-x3pDbrg&pT{0N9Bm$ zy8vN8p1(t2=hIJ$QMhW+D>zv$WFzizcGzGW+p6V`A**BxUQ~@$9%vYjZiUCs`~bKO z?h3S;V&V?WMWL&WFnL1GvmLdheQxDZx{pu@NQQ!04b?LWd7jz%@j-o(>8Rack<-*{ zhuX@D>MhnQZ=F{3F0buSu8_|0t4M|Yd1y%s*h{b=0+!GG_lSX(5mQ4|LlZ4M-&ZM7 zHIPiQQ|DS?js{L;Rn9R^w;~q5%4E`r=6V+=Vw$KbhT%H)rtTS%R)-L@XD-U&;zFud z(C^nm!E%y^0+}MTFFo^ZkU9yqlp~EIN%+mmN5m`f!goJND}4?BUInURKa>)5A>~%q z&R$v)7{P#tlF%?QH!NceM0R+Cm*B&aT+;YH*}w+1xTWQ6>Kis#G6$D}@A;Up216@B z6Q?;UA?007>dLLjaAs`MYwJ|!PtKIg?*=QuP*mQu#sck(UcJ+W*-FhR+4uKuoaU-z zs{U4}TrD2>Jv5A}o(+o8GT4@IDW3hudUcRk%!vrYFHU%fYX z?R2BiU0!Wb2i>DJC=%zxU5==2Dc-oIs!@1v7Br0m-SDb5lk3J7qS-Kgpkc~x1;%py z;}0^s-Y883u@JP~Y>}Ml6L+5_d_cKsFvH|FLB&vb22i+}n2i1Sp*Fm#J$(yFfZCT` zsN=YW6sw$oh@$=j$#UV_Y}*f*lY^9NHSVrA&yGD)>ZNOF+9u9DuXx{0gODcK2}`KesrRUC_W*g1&=q0$2P zaoAnxJuO$lZAxfBsNoG!cn*BBv{mgU7$@-r#mV1IV5cIbAX+{GyA*j%o@dwcO1VIl zmdUA5x)^8p6!RV%^*O0Lqeo-wynD{Zhy9yf(`sG!**hNn`_(7AD` zbE89)D=MUSR+5R5iL3#GTzd(W;hLcz&gV;ocq#8@2vLq#M19=LOSEpb6LJpcUP*sf z;s!Pe7d7-po}qgH5F;%5eJ9IxSNEqBEHMqP>ASqyR)&sOagNNHZNT*qhcH8NQ?=~d z-h)hR&=TZ5?M+LT1t^*J`5nHeCN>KPbbYSkLcp!j;w2O9oqNa0we(QtuLsxqN^rs% z?MwblNW4RpMf|r#F%ZJ=j3-P~kUB`Q)@wBD)TW=*qf_y+n{%LyF$S+lMT&V64-Zhg z=93V2ld6C$46c9GQIIYj=2Z0z7@nVZyHDW`(CLVXZN)w;OB-uB#WaQiNGj5zZoxK;!tti>832`hV?Q8tZn2sp?8@&r>t^7(_j$5w zKHCGF>PC%Tc%1tg5T=+cO0)bi3HNr0WAVm%M=+KMaK z^M5r<-dvxs9Gk4RoV3K$7rK)M`wZYK^_HeR!-={LKRMuOnTvb}!q>y}qJ9RPQRHxv zl0(XnUR-1(unUerKlG%8=P-@ttw_@0mT8~fZn=(FdO@F{x0xvnu3A5J&8C@Qu6d(3 zLt@OMCJ!hz&al)LHNR^~J>FNTcZ76gj5(KtYN@@+P>)!8p1T-p`aT0WakCYSMqJb6 zzM61q$Q?#COH2?rH#|9Zk6a@Tcl)X-+^3_9ZE;{!{S`)b%2)R3ggU#*4ARS)hOXBU zJ1Wax^ejqj`<9w{zQ498r5DSFWo5M0Kj&^PQ#^9SFwr|!*Zn|)@T8COHtnvfK}pfy znwd0dDie=9sX?|n<_9Ybc!LW40w|mE_1BTX-g4=CdYHkeY|X;1PeAj%o;%?cwIFKs zC@CrK8o5v0qtflgN(6oS1sZdq8e~281Eg>yzikRhOi+b_-D??u$ATZ=gIbzQ z&C1l$&l>a&rOqs$p#1d=LwGQN^@eE+hQzlg_QOEZ~y&*$w#2Pmj~Ke zwA9$I-7R_seBm1+6iJoy%CZpl~ z(1krAMc&ji;CcQ+(~Y71HqMUzU5bvyy@4i)FRV_3S>G{Ol_*wltIs==9?T-j4{hn# zo-|+WL=fY}Ec~@*>^I&=tjv78(gSdE5g|z{zC{!(%(KyNYPsmULo1%4NbCw`B~HNP zwEF6p!Xf(YQ;jVWW@a*5|Afw@mf+y_Turmjt7aqf{1HdW*s`>83Dxq#c)HU~YeoMe zH|;_$tD_Mt^Tb<;(KMWK#zJJo-eBEBhIjcy?`j&9aE93o45>yNTsy$CKas*;<$r!_ zg)i0FUmf*1n%4Hc{{xvkiN?8hNF}yy4m);YC|(gb4de~`nVp&)f!afL{ndh9ZEQNyRf@{hhj3;*rYGqC-$AXGdw7K^a$bFy@9~o#?OvG1tA!x}ldw-}2By+U=Te zO_AXzO9a7$uqcSrAX-8RE)lB_3o(q6Y20{)WQzX78!!H$<8jU2qs-2k8MbCgEjl)+ zN*udt5%6h8B0}N&Gl0=gL-L^oANbi%dqRE8F@~R}3P_%+>Fn&6Y7o znnYpnO9oMRZN4Ogl(GjY+gnSadS#1?AL;_E@%gOuh*olO7BoUI_M(n?RC%84I#r0O zn`|k010!nQ+&OLpJWpJprN!_*R;q4PVa3RuL=`b2S!SZmS?8z*B-0)|1JL^5-*IWO zazQ#K!YbD2GGYp8&XCL|K}GuTq^5rHqlU`|P{6ZC#p8LH{@8-G$Y$y?#zn2zlUWeu zEy)k>M1gS?Ca{e!A$9K7Gn#~ia;2u*C+ths)L_L+eJHbEQ7^YC@RQC2&MgI|0~T&vC{xOs z?^-^XP8H78P;3(>%)R=^-oF(n0slZ+e-kh~TEkrV$iA~-!}%z#XI`SGw=Cx;m^i>` z{sWagS*?2s@L2Msaj%yOd<{cf?l9oqcV&Nar7#2+-8g8W_Bo25mh^JqRcGSuiEiiX zF=OG?#ktX6s$2OS6Y4LdGdU1? zhrQZf_Ern96Jl{H<$k}>Eqg{7`kS@`ZO-_@uu)JemG2)6g=!~j0? zkXE+OLv34@C{s~JV_y}+RD$1~c=;&&*&s_7a=IT(%ag)kr}!FoY6&j!va>4Do3t=~ zHos0$PruNHCtGe;>lyGC#-t32>Ak}F>kITvxlV4+TGMxJ`RsSnZu<;F-gKo4%3=mB z;yjHr&EuT5I{YnprQX({T${J5R+jY{-{>}Ay9Vn3dq{l5iVZ%Fr(37{wl&Q=)1GfK zy&Eq^q-QygBu2_curqx@m}fqt<4#JWj9S?2h3pZ_0bL@djkH@-g}jBt^oK&?phic< znr5CTUW?8qRbkACA&E9Y)P$R@F}q&2FOtUt{$&i7cjo8c7&=WxkkA}9tw}=1@INdU zCTi2J(nyT3JDodoxCT5=trJ_E^MBX2wC((w|DN-*so{X>6XeURN+jRlxp|i$3;neP zvQ{3g_fn(|OKP}lZsBDskD7N_NQJV7gUJ#OIEP|V_X!Hqn@`$mtdIA}N+W#Py)(Ip zL2@{0b+C$1Yz84c@m9In!N0e8{fJxQ3`yK+R$h)4RimG>7es%ApbD4~;yHZ}Fde6eA3si%~DOa5MBiLy&lkS%JedD#$*;}JEhNWeL&VomT$4^m(i)~%~ecYRiEpc z_hd=kZi&>8Y@S-0OsUC`-8`jB$ciU?8s2hSb5S<%9lswCEdD0F5@!-|>^WK*uCTRA z$C56!C{HX>1^Y-Bv`Ip3uDeq1b)hCD(sT!mZp-Ws7vmK zCj1P5uc2>HtqN&f_>`7MuT0L6Q{bCWs&8X#*=QurounA_=qJfUYZ|GL!u1UB$69|H zp>sefc#}>wb6ICBDeGxU$RJ*UpGhC(g*ehP)ceIx<$3zTvKdp=M!g5Fl8F!9Mggsz z@`@L%MIBR>SGNVF#{?p(klsY)N0j4@9?p}EqShP-ZZV>irh6%U?x)J7fioAHuZY}D zF_RBtTsa4d3hY8Q)w7sFvC=<)20}23bJZ*x(y>x{xDKHwi7lAv6VsT?Qd}R)lOsKL zuT{*W)apNjRlZYO0x!gwGVNOoJY>_n6tQwoP9}!jXSdDb|3hEc}kY6*Dpo_ugipdop;IW8xCw{`E}GPAmlm z_)gjSeFM7ydrSk#sGo##CW7SDiAA?r_Z~YtyEH788VR+P<9UnL0H&9=OKYwSk!%$_ zPwebSpe@xwUYbbSH|MS?X3Exv9P$o|NpHDuZhC77i0)hYg|tvr?hRl(rMlAY5rM&U z>aOBU_BZ1~dTDQDShy{J_|gUtF=)(WYk|Ek8DRR9Py~}uql_gsRw7*-7Ok^{ zjvAOa9wT2)=}wGG$KBIxgkx+FIf~}entTpl^WkX#fL z!9?7eStIieU$jg0^5qQUX=!!in;uh4!UC)qQuW-??PGC&^j)lGx(U=M=y$b$Kq~lJ zQR(N_lsKq6+a`&Z6>yD^CN7<633ZsTv;gv`@?~_O%x-SfD%O%e1KKC+^b9aYiYmFu zWn5};Ld>Mxx$SfCz)Y>%2$wz2UgTv)wY)nIlAx#PzFP{pYhc}4NZXhDB3I*b*{Ab~ zE!-kSN*;f@*NtKix3Z}M69cug|D&KxAAx(HL9E*q1Uq=hwX^2*)O79Vc;PBC&KoI> zf;TfT+8Lb=lhpT|4bnv(X7m}5dgs=n8i_H^E(Pz$8sxVY>78qh^ zie1r*q|D103Vf^eRwm>UW>424X~t2Tj(u}Jn% z5K&$>&f!F&@Fv?Q?`2ziMPam6J4^=T|eEXh&0<`y#^u(=PP zDn&MQE91zPu(V=5;+(~m=_BG)+l@j?WCA%!!l8gq;?0>SY6cn1UX;|8F~-WWB`~+V zJ{2sA*bifJ0v_L4>vas=)jCOXl?_q1oW14pcod)ShsaV$ehi>Q8~;bd8!ny#6Gou&c8?6}VO+kt$em z_m1H$Mi{I@J2vIc%5dew*9reFtvKN#pVa!L2?UuocaE9kOPbg*mB#LcAu6FMOSs~~ zV4{R#ruQ(5U!#XV`!O@Cy@Y{jaXw}N0x5q+!7535F*#% zQestdk^owRWPMzK8a~RJ=03LOd=}&)!tjD#{9g7>_CPmNQZIWu2UmVCA@X0H^S{tP zt69iNf3djP3X%UhU5fNY3sMP37a%DoGdq(xD?2MG8#5a_Co2yxBdMl4kW>TcM9RiS z%FfElL(0y<&(6lr$x8ZrAs2=x6?Cz%%PG^Q_^ppyMZkK z=>0Et`-%KA+@INjUZDTN{uB8R_7~g#Gxxu4%Ac7{-M#)VUB7VrrGnEor+=M%_Rn4X z8~&r=PYd!Znc4z{$R$i293B2t>1YA8`@NP_QcgxrQ%sRmPFG8Vl$Vv2R8Hd$PC0v1 zE1(X@!p&NUoSl`M?{A1A(81~##KZL`NLL-`>S*Ww^S-}8oUANte_(q52kZ|>%K`M_ zDD1zWpXTS6dil}@y14#o#>&pl`e(?=(be4rs0p%v87UhJC+nX;4QqEdH=v7#6A);j zZEENK!okbU$-&FT&BDg|tNg($t?X`Z26Pc3=lor%U$tURKo_@{?tgFn7fjOB?Uz^; z7tqU$Hnsa{BUU~pR&FMCE=@Kzel~7?E-nUEcK$z$`Bx*!mo{!7AE3qmqgMYKr8vmc z^>N2#m;)Vv5~fZ+hoHh?_WKYjg9>$FWc`^;BUPD2hUXnc>(QoC0}m1!*AaE?`iZ0 ztoLX5UsLHNM*W{*C(|UFzT5jxL&x zj&}cAIsQ0ZQSs-w;w~>%{l)$g`1oHO#8uA0^2Nejygv=`VvU#8gZ*D5E6cCHzp%fs zGV?OAb1<`$+W*m!w4JG|_0NOJUpP#Ev+lp5z%Ll&V()3{^3#Etf7kXUZu0+o@^dkB z{JZk6J|pHzs_`;_f1`2^<}SY?v8kOV@I{=9=}#B>m;3yk1LWZLXXsyk`cn62H8iYW zLawLlpE<>Uox$z^bp1=MgrkF-i>d2h`qcQTz`ut4=Pq5G{@z^C-Toz@ybMdj-qF#` z`epY0wR1a17iC9~>x<)AxSRjIM+s{eNBb8!=3+15>^Fhx{}){R&$u?o%Hd@h0*cu? zy8qQGzYYKIwt7)Q)*bk_ntvXwj0+Ix@HggPb^pvR{u0Ul#{IMEpP65Rk=-x9{p(oF zT>czVe%8spFxmZNR0o3p;9aj2z3aXpwKRfS# z9rr)6{O9ohiR(YD@K0R-VT^xb`nyg3iRbU8`6r(Lw9r3s{ez+YJ$3)9o&JI2Kh5+H zO#f-6e_;9#BmD!<-)-~{EPprAKd}6#h5mu*pFGLQ4&<+y4Unic9|m`?qTU1^?X$ zKQ(+=*SY?IL+K?!cXR;$&cgM76!JS0&maB#T7ZBK>ZTST_ZJlyUe?{eW0Ef$O_1GR zr2mdcSy%y;OkHjNwnC{oy1GfYI6D3JrQ~ISd%$pq+Tp8ZEEKV{5QwT z?Ep%+yLbSVO@C(giXaD|smmYjf9;u6T^ubzKbuOur0y0LK#PCIU(!V2&$U>RTTGfu zOiGNKor{Y{T0)AKS6qUXkB{f&S6q@qLgJ5TXzHr*`%X-VT+_w<53PQVO7rI~>?JQ? zXXRw&_zR*4v~>F|W#HuG{wpNz==PEn{{;DX__+9Z{sOB1zHTw|@o{l+{1p>(u=+Vd zCRS!%K2AQ4zxMjCz1hFA#(&kz0)OlA-`VEBfZq~S)<2K*XZ7DkDQ5SQ9a?ycIlXwx z&*1fM@ZbB)mkiI!)ZAN6Ra4?$)|Hax787UZuny;N}$PkPzn<<6svP=i%g$ z=KS?!fK>3e-1%n~_-lLn`$po|M&SYw>+TG#z9OysW zTS$5TzSsB-WBE-73v+%~cQYHHx!bSn-=0^9n_B&L_1mQ#NcgwI!Ub7=zx*rs$MNC+ zmEm6pivKqTC+q)${C?>8e?fmcd;I?hva$UY{_W~tBNSx$n*jv>GU5JY6AhsA-}+}| zBxU_CqF-heBk9Z6KZ*WVM}jQ>A?i1VKRqq_`4Ecb_oq<8@PaJ=eg^ity#F7U{|Wh@ zkpBt!pOF6v`Ja&g3HhIp{|Wh@kpBt!pOF6v`Ja&g3Hkr45cog-7Y)$CLWtaxTtxVJ z2_ON000;m1c`1-DA1GKTC`d>sco-OHSVVY4L0!O9268BCK3V?=Kt&R>s@MqQ$W+7-lf(HAO--yAR+$r z5;Xt}Bos6(I0PIR0R9D+|Mjjka7ajqpTc3FzyM%B-=l^GjShezV}r#Y7sFID#bS33 zN`RvfFThqetN%pFA>k6-Fu8t)gGZ&|+H)Ebnq1iY`K2#{m&QxqpkZD> zE;PVTIS|lL|5E4ItHa13f4-B=)ENqcJSgFmy`cWnBqqiB8Hcz!C6>fr-!RrGSkh)p zJc7g(S;LtytDXe&N#nSXqeL>|icy-dsuCbT$GZ@e$fv#G{52{T*CUYB7LBh~4&8wg znbJG@dKVlIbUAOrMNvHOsnB0qo4R6IQkuv(jh$LaXPHxwC}raTt|+a*Mo}Rozl#{Zp zqjIpZ58#`M@j3U$r%fQ@4=m?fQK@epf0FC+*+0^&ZO7Ato0Ruj*kImOB_s7U)rYu^&B{vssPc;@Da8f`#ZlMz z0%Zi`kGrMF7?tqmY}cBEf|RwNyd+cV_)#=$iU9`A+Ety#N2C0Bbi}TN?B-wjB?*0d zAWr(ylb9g_A-1Xu1v&cn4$@PrjJ{n!YGFA?R`8>YT&}+Q)PQ*SeVzfb0zOS6-XDg{O1qj0Gv@SpX(TXXlio3E@($$XvBnRe zA6;Ut1Z7{mVG8FBe+HCOXh4f)LEvP8D-Vh;I9Uq`-6tDOYU21Yl+HohI5rvA7OJe! zqDDEB2@o{C`Em%Bh~PeMn7J%*`qjhJiep(R61+#%LiZde$--RDdhQwEIBdI1gylXp zqNie|nVVa0T3V~$R#}wZd*hv95tCHe*B${=iU&t<)<;x)g3C#51c)wPj?6`c8d_4C z)=WCx>m~`9+VMOhizMHDpGjLWmzc|dFNH{7AYM45SP32ozy++C7ZAY^2_px{$Sbe9 z86h!;W+z3#M>b<($i7PwrP4E&2J;Z!;4T-4BmxY$z*0o9X{-fxFK9(~>SsTw)UIO9 z`z9r60LPyJAyWN2~ zDC6OH2U^#sVS?!po9J3)Nn9FFYr@4gIwgkR7T=Ybd~3RFx|-3qR4^M7Q*es0>GP#m zbWsq9Z;-qn1apDjazZI~eiL@Q-xau=|CTdGba{N*f{BG78@7H)Zzs=fdrAmc3Z=xI z)jXt7PQP7R8(f2g5VYfMrXww|Wgpn@LHLF^I@rkpzo?RH+!`YMVh1D8cyb+QNhQES zefh_z$hKuBXJ!l8-I7?t_*46 zuaujeX>o448nnBl7bU%+0}9V1K)J+9=7lDSp;GB=~s2Sy4`EroD7xCo1wh4J!>w&S}hC3<{E zbfVh1w)w;2hyJm7cZkkOmoGoYkzdX26U1hBESN?G8Zc|lg7bs6X$!VBl|H=UB{u}u zij@^o!5Gt3FC}2NwBM`Eja;0<2UE>)l>@ct*Ub`k)OE@gMBi7Y?$`I?tAB~-!u8mfs-?nkSNtRGlm^mPzhb(yQR}_UZTQZ^Aw!&J0wToY+A0a zDl?*Oa@FBV!}-wE4f&0)0PU2C9)ax2&};(|q5i&1Jd(DKB4p<>s)-8{%+ft<Ex2pW%Cv#_C?pM4xMVR359+1kSU*gEI142~JOkbp zZrao*@>o`79k#z68_IvHDK~5}#(x&ULnINU3TuqV8*jPc2y9E#<@;3tDf-f^k=pe~$p;7p` z(;~8^%6~7Oo-t@ziCQ(%b3rmv+WN%sB~e||QmlQ;jbOob8>y_2`_LUSSH8TQfZR${ z3~;(C$`w~R{@Mfp=6b80my$`GCp(oHR?wmO&8*l*KeF<>an8OGz2J1(^6*fHnJVo* zgaZvOe!9Fv4?AfR$pyNVhARj6HhWZw>@?vk>Fh~(gR|*#*eY94B|TX6v{sT|V8uu`8NKxZd)Jtn5zGg+k6fiTZB9ORlq=424ex>z?XIZEs6k$&s9$b zQKzG$sjRd-Lnet+c@*2pCnroTi|CQkbNxazKAqdHBX4~*^)4%UxxHb}cGkY*z5QfY z0EX;T<4F5La?WPyEN$Rxs9OMUd7@HSvV`HhffP;q_q(i|FW#2=o{^DKZYi6tU}Txp zxD-&y?nE-$xHK?KGtNS1UQ86A<~D23`FSn9VmZqDt%4*M{nB|IC8`{X zT6Q5**ZAVs$SW|0K_6>A>5OOGDt$^IT?#LJ21w~RNxvOz7xGW7YzZ&iRzgbI)sZey zZD6l*5Fcp*1`4o_YSPEPp>(z<9Z&o7a1Ks14aSP(2wI_%r3(IAYI-z4EMX5n3Q}z4k-) zTB>m3hq9G~RdO<*uegL^wakt6VHyG^!s&y*<+OKI(XapLxPFvZK?H-zHl2(33@}yy z#FFwOhE~z=EIu53~prD89~`qNhf4T$so{U2{AkPk0$*SPPKp-CQI z)kcDTIxBRX#xa74sK z`lw()T8MX|A}SS3aycDF;Q(g~jip>AEVH^@t-NMRJoBxpn);L>zPT2|Y+wZ& zr3K|1OFsfl3fe>pY+Ezfi3oHDu6NL9J<+rpt}>BJOXpGi3Tj`uh!VlXFI^Yt zip#>IK=jy3yAakr?m95}U*sstpx5d#8PuXYZ0%kB!L9sZ!-eYXVzAVNG3K8#tN{y^aT;G__axb0lBO4 z*30^#M$(#|0YIC(gAYZGQu6ic`KUvj>L--#312zDky&*&Aqd$VA&&yEY@2>WJ)-y* za78<4?*r+HLi=`xArvv+^k@3=L=%Y@gl17TtbZD`Gx&ZNl9c^pd_FdHfq>*3 zD{`vP+iFX>HS)M&zB{E1(M=Y|&h|RW9CxqHVQIe3#cQ}HqE|ZzoNJd1LHhLo?QU%F z>h(FcT8mq~!IUPi042EUNW#SC4!>`QlVuHhvw^hArPG*~XXJA3QMp{wQI@^RSer2yPmW&u zY;9+asu0Ly=B*efL%5O|S$2FiDfk}}mrOBd64jQNX0Yt#(AuWhS7>b~D&H{Sx~1x6 z&38k|eZ!4M!J8fT0@&$ZjKY3cdg!Q>8zt-V{RA6S!BW`raWqwD>e6kVUqeDe9klnY zA|<4DFb|LN_;YR<1>o+TlFmDI*JXC;@Xuz?fQgL==az&|uJfAbN8V){61~dIR~|j4 zg&nKrvbtCmHr@q})M~lqVj}zRBp!GL0B-=&XBY7LP08H$-Y#)cawQKd*X_1u?V&<* zrf`aJ@njuO5RoVJ>A{6AnyKzXBxUHzTuMBdF?G^%xEJ;F5m{K~YTzRjO`$QJ=0=C3 zU*Ta~yix)atAg#&JmqZU>D+*yxst|GX{56Tjm8LVdQT|YiSyZE6fMq7e8EQGr{7Q$ z(JSS<6=!Pn!O)hyo?hAfpr&SQis*-#@a2j(Sh#GeMDF@Zz>Sb2f?T}5h8)a@!?-7+ z%=k3X#3@nEHhTconM|}A0Z`D2vj50&vC-N|o1v&$mJZ(M(@dZMzv#V7ze9VVowDvq z-M31-1|O!42S`MPqFjr0#l7Q#anfHyuD9k6l-`^pMGny%Jb_CYeVIit_B9Q*V;Bx~ z8V*Z~lzZ7{2RFy)&juwRZtbYWSQGi^_fql*Orm?Eb=B~{Ha z2O0+7(Lwvg`JqxOL@z0x>@0kJ2K>A8S-F+2EpV9Pd$`zY+WPh;$`b;W?nE4Hgmf76 z4`-ctWoLfnMav{3w)74}u}m}OA|o;HOk=)d^%i62Oq{D^Fk?|7UaQI_q1P@ITY<@a zFY^-Uu!t9V6GhZq3A~YcKNmQu zv#*Nehs%hjxR-d;M7zwNdQD>DKw>`0ahWW2Hl)TS-8spwsrHy70J8R+;#5EjjavNF zYF4iG9Y&PjPg#yRh!5IcRdbg%#gdCSs(8vLwj;N6TLEckpLfWMjwxlRBL?VkG}p{$=4!FIpJXX-GeR*?I%T5y$D7)Rs;p4mkwqd;bCk zZ2ktGYH3V2FAxVg#aKNUJGvOaNe%2HVku|$S^kD31AL6Qe`Lc=&1S-DlBfX>{f+5v}4Wak_u*tNqf~;-9NOy8}ZBIbka9=?;2A`j9 z3a{=Innw<4!a&@SmK7!Qgl_GUxp~ggM3W3mQp5^N_Ke0$rbi zO4$=iPs#Z)*BeIY=hdiZMMcgh0`6kr*9tnsE$+J`Nk+nEDVJWG>Ax+zGkqdt3*%lu z`|i%#Xh78>wT-`YdA5``s`OQx0;bMU4WdplA$J+cc>b#q+8gx4&O~so)!4vkPERBb ztJiT$Ed+Kmcd_esP0jiegm&hM1;o8#6~LbnU~a2jjf+qd@(qpHwWkl@m~o81I8+=iQ(5Y-(s0?u6O zKSC4lLldX@Xdwc}LVoD13h|%8=&w_O&7c|COwkWYFbPum4!ge@O_WZXz^orM#Y;#> zYCBr0<$I9APgyhuqqHAAqweLlq}VBUqJDY|8(Cdskh~-uoOGMk)YMWz&ZeWBrPbOp zHPJ{Ty&CZpl0Ar*6~tSZ86%{i%c%D#^`wmw{qYJ5?bO7zWr-`i`d+@FFp_xazO|$* z)!Q&Ko}HYb5*lb$u*EC>v98V$;yP7BsW88u(zgb~-u~fp8MYv~o8kw4@*79oj!H(T z^OD9=oOgX6qTL>OS0JtzT0`luj<{NUgvAdswi@IV6nMVcrMNOi*)+OFb~t=KJlJEn z8anvsmd91u%DFVPpQ({Otg^X`wR>qZDTh%L9Hd9MTf28p;v`_TN~kN0wtJ<|gsrt7 zWmVFlIvV;Ws*q3TyVmTR3qsyDy4 zrFR>ngi%N^1}CHWv;mO~wFBG-wKI3rtI&nTRW*9~;Xk0LG;0axu2aI~4?Tx5lT0r} zzVr_(>z<9nhCfSG3+-n@w-8G3pe+{b4r0dpLOX^e*pMj|4$};VPoK1QAdF_H{`-H}n`t*!m zWr#Q$8nu@7OlMmR4@VnPQ-wHx%Vw5dGr1lc8gV{JH$($lE#yuNR_rtuzKHhTYv!_8 z$poe^Kaj3$8sspezZgr$C_uUBMVQV&e|M5yo8wOrr4K2-I4G_P$y_7(q>e=1r2Py) z%cZNJCB4ztZ3??mM-2l9knS~I6B5I+dZ=6DA=1A!U|TK{`Ph9N%b21aiRWv-@0|3w z%vmOTZ0=qB447F*D@^i~ih*!1nAXn>zBMxCxwY0qqO?^vvyqFgXs7^aqc`b(BR35v zwTO0Nrp~I;AS>m%qhNKHqR%C(8!}W5xCx#eE2yHJcAn~k(mW6|aj%Pt8?4aQ!z%A; zhfS1TN?jI!2t+2p^|DDJR&&Ldw!s=P616qMzyIygydY)#Gav(P za>%9&yQJ!3tHj4u{S{~pw#ODJ+5_CvoVVX6H}LF>M}%!-ACF}OG$m+HSbx=mOIbts zA&vP(c=P9|y-|BS14m>!8_u(M@5YSf?*1<%?8LiH6a^mv<`88tuizdT;PB)!Act_4 z3oCpfzI``e_jt0)tbByP=KKMVTd@=E(ECx7qS}JRX|$3pVYQ;)3#K{J9@U^aXVbys z2d%FjlC9k4!I1an8@P>UfChaQ~ z1jZA~#h@e2p|UW}9cp6rnon4&JdT|Y6m8MOU?oa1Rcd21A;N`&Hl&`hWRzzI0zLv*q$^PN|QgP}*N|9bqS;gLNdEzQub@Ytj8#Ho3I~$I$$Ky#< zN-`RHT#xC;PQqTN4_U4Ug#@HHIB^~i-(&Hadn9UWTO!G)U6v1dN_8cfrU5aS)?tahY_jL=I?a3iHcM9X_8*za6@3?WC6I z;~lz6sW7@-2J_r_AY##o;?h~#mpN0+)pd)|M<#O1M9SdzKBr8&>|D7`T=92c7TI!PS-2%RRH~^{ zddA?`iFhYBMev}w#-hz(hBa%CB;>+gc{JH5#1_UXQ2_^&xagh?XkjQUXpSx7-c!RK zW1dlyT6!{%##S%{ zrS28Sq+W>nvF;tf?B_6f3@a(rcpKDIIVb_~wG+bwm!1#@8+$Ml*-<}*P=<=Ed?M;} zCv;%XI1citA})I4B_Wk^5pKebnPf`}L~8EGwfY)o-ixX2y-xZ5*Cb6A(3xk>JKx8z ze7|wA*D4{qoy%%L3-ryt^)E<)s8E}@+N8kZ6mjKyt83zwmm8#hk$T>)buVL|@RcvE z$o@M7ydS?Ahdo#+uqH?EE3~89tGQF5NzXMZy%o@H8#s54%=4$9O4iip?AGNNlQv z<=@vE2-@d-VCF(S3aftxJPb4Qqn&b|!%sD-8`+|ebLAkYh%5|o)mnqFH!Q-ad0-_P zMd20?F$r_?3Bh7F8tKY!zWNIV(E5mahJ&wcRu*erEc1!sV)LWbD|=**O}7h)bP`f8 z6o9zNbneXFIu~8Y#lWuh{2m`c=L! zgU&#BF_vlu+GwBSxq}O24G~|8Gb2lQgsoD%Wujt~`VuPkr1rz{6Nct*bEgS1{gs_3dz`W&vCD@8rJM)JIfMWM++`k}isu>L%k! z@fun|@U6!Zg#tN<)H#FDsCWl9UuQZ>xa8j($4@VB#Aeow73=BiPU4{{@R@;Ep|Z-f zj)X1?af3s~du7}e(*elk5r=Br!D=e2?tS*o+?|`au&7&1xC^<#j4b??a&!T(W?}#< zLDbs71cIxfp|RoWXTa6!lOVtKM$7a!X2p*PF**ScKb`?`uvB2iB9Lj$!<}5r@2bY! zr?xeAWzHHnBZ=6#XEmj%BxEIsZkB}rs2rcUu~iUiTHfYx?a#}Z$UfOKX)184JOW?A ziWF?XD@Yf;Gq{pUY?yZ|)31atA9d*;z=K&vo0a7yjm-~~L1qL}@@#j%dF#khcfNvu zqUQ;8nRz!;2o-7$XyIso(}>h|>&(7~n&`2s*13FXS#^kS z8Nif9ox@A%R+1iY;xyq^3|XA=3}{+PPoOMWbo{a zDRnD$){ezo`?jlBj~4qs1BiIgW{7hhZ@_E8Q_M)zEgS{6RrkgEzf+BWaW}r*behJw zzf-Rn7BHXYEsP$(1FzJ^6<1z{hJYvqti78Ufs~-e)R1UfV7rOD@XkRB*p+MDab-C~s*SzKyHX!au|UfRyxqWb(v1T~J;5-Gaw6S zN2K7Q2qiF8sb?uSC((E7e6J7T!SP|h;3<#G@Vm8)L=FqeO9SAR3}U%{3jrW3g6=O9_p}(c`3>!uQP=nce8eCcxTMD5mHz6AqHq zzLIuP1nHz=dE&24%K0-RYFgHf+RLEt<~LE55oAn6oUfvXCEH#ux-ba`16#*(ju$0Ha&KIpDR zdFwCdOOmE9*MzYKAa(c@j&s>}>#pn%swoJ(ZRg= z8{dfMTC#)929*849c~wj=piEoKNb@{34#h+^&qYe&ey4xxhwIG=i&A7O*1pw)pJP& zPCVd6GM)^1mFpNI6-=8YBvir*i-YJ2;9pa|qR*=p9pC)SPXoVo!@OI}L&Sz0(=k&} zQ$(-_^w>X3v9y37@<3J5$Y$M}4yv5NeAOwg8De~~PNepUFGb0dRh&!@P@Z5FNu+!0 zJkafRkoUgX32c9r)ho^yrNeU!~^XpaJ-3LhTcS1`VP ze+eNKoTfB5@$aD>1iCGiyRIFYjzNcGLhJ&;ik70#Y)2;-w`b%I;PEibz|mOW^QrOT z2RR!eA=6HSTJDV6Tweyev{8LD&afDU&HO}i*~Q|(5_Z>k%5$Xty-a5C_Pu*H&IcRO zxgXE~Ye1C0LO#tO7z5t-swYo+J*H`DNJ3F}X5^$J%Gs)7zE1T0)*ZNk%#4;SZzhjs z)4fo`1)a~`I){~bTa#W{VUNaXDKvDWWV(qi8nLud`)31c9_4OD<@?gGTaN~|k$;Na`GRYz8 zns5vXvUc|&l9l8B)8oL~bO+5!sYC=Z5dx`aKy}_pEE7L{0{X4S^;~o&HV@oRzKsd( zxT-#6^bDh2f=o6`#YJAlAuo6i^KoOIHOIWY$^v44f@<>PhR=kZ?-J)((KuPFy294s z6$b|CLX#&A;Fag##>SpCgM9ihnKGAf$_&5w5tG;)P9^_LX_z9~pkQdyD;Df2*1>39 zs8`Z3Y9CYB(eZaePJnfxC+`M66lm5jx6!Y-RaTc*AUimWH!-wkMJG((2X0C-vcvJ{ zh@_tCP0P%h%xjH1&dhMR6&$fKVqR7$QU+Y?A5)euufyuj+}f0RXr1ychJ7hK6J}~^ zO^y^yl~`mSuiyHxqtvZqaM*(XHfj!u1B;7kSnfM*^pLDga+BLsxam8&z#VK=R?MSU z-+OI{GUOvqP~s$}oe7by<{mI#2aaQ^bTTbMq&%$deu#g+ui&FnZki9OMYi1nVQ=!I zT9yWjE5I$er09GU0N*9Fn<~lJk&1n|lw{AfO=xgx`s$uqu_g6|h`^;~UqS23EN{C( zpP{uismgg;IBluw;2{M%zodBm8^~03-Xi41IPX{7AatILse2*|8^$6!S8+}k|X>Ic~?kXs}qe+YcIRmJUtZDK3REnOuydI(=OrsK7 zH{^TqovZ9BXWvxfh5Zb+zRj=>$TT(ey+sy1;8ld`R{R!nx{%N1IJyVXn5n-hM5aoxi4qR3J`wFcw{GUHKY^1$JNcs}$T7EJ`|)Y`%_DJdI1vKYX3 z=+A(Gk>EuLQ3%m+*SE`to0PR~u5aaRJl}B8zG0HLnS|f<7OknjFu%Pnu6!J}YnwSQXg-M0MZwcYl$CR{>)~%v1 zFO%?I!9qHG0>m;EukAZ=w-)|?0*gO%zy`32nTCezv$ZVJ$n8eQ&rDs{jnuQ#Ek+C>-!D<=m(IO8?C-+CTfa#DiQ>j&XpAzUTz?cl3)$_kS+$Wg?kCPT*>kO0AzCO`8B_Z|;s z>c{Mm+72sdayog@{{X%?wNg=j=X|l&a{9L4ZLw2PR#U-kHMdB&wM9gNwmtia>D8Mc z4%zwmz!1L8nOcL_qQ}>Lh19Q<*2acFcXrU=FVx(?)aU_S?z1WV};!QpQ z=CqnG3w?RBSJY2&7n-`K!o*hvjX^{MaCQTubSLV19tUx>Lfpsz_@xW=E|sUb-e;<( zaYmA0v|B*KU;=u4_$ieLXa?&xrW`%x!pb!lGj&8PS#8i#Sf-vT%GZ%6XxD6JKu@Tu`c;or9RUN0Wog+W#=B6m zu=s%HE|(zLwZ-zyg2hF)x#_?xFvrkGQZO^$hREItWeJ`=cc>PEii}??Qi_f0rKYD9 z45JV`qD0lF|&{6=_WlIu-k+paX#UQ)M{ zAbp??z5f8?!x17Bn(VFxPv|uzJ#-BOu}4=<{aGA!A6$0_fr|@FizCHWxMgsViJY^R!x`UGYg&FQ zbc>Vn3zhyXxw88I0GxLlvMEo8+X8|9vpx^k3_m>ab`FuHKsDOjp)r*OO2;mO2cmPm z_{HX}r%>H!lV0DWik_}mV?kXe6+@5!$@yc0a)byn6J=+OK5a7Ka|ckV{>^ia7F6m7 zseDXxI{i19Sq6A?1$$QzI8mONNSP$6j2 zB#BCBbyWpzvI;AGBEeX+sT77o>m^VFv!_+`=NZq>fwGyBw3$>uXbWY(O08W#ol`5T zxyT<*BIn)!SF)C2B&khDCNy=z5lLyaU7p}6%~Z0rOpcMNobB2UcM*)|Aut3%zct9>YCj89wdTX7`X)Jfai!y?c-qHuj&=yq)IDsDqzs1}KpoC7bKBUS zylGR!ny!H1r_XEpq1lOfcm={eI$bfzpsh636NzYD78e3#GfBEEaJ-G-8$+UH!f^CePx>5@mysx!3=O#%TVG^EHrN5Nq{ro*b+KpAhjx$s<_63 z+;N|BtPXpHzmLrPkXn}CQ#HO?u@k%ykg`Y@AY_4@{v>|9Y2}bl1$iQ2YX=zZ#8a%) z=li%xB?!beLBo3!?Zc$3-juLYR_S|PY<8IZrnW&7$1G~nDA)rtd+uYF-QUzWX9-p? z!hYp&*4)3)mHxiF==Ke1w5r`9OGyhIVFcucr0iZL(G#3lK9i{0atyv zT=dqNo|SD@YSC`JHB4klEW5B6$a<_$IowyX4aeAU8;fc`D~6hN(P*`f!&2`7xgRCW zYWjz-j#;FW;v{!6yqPD=W0FtLu1VnC1OT$ND&XoKL-PKr`ER+)sq|FQRv@Xkio5)g z`P+$CF&LmGG8h~dSLzA&!42-IQk#V{mBPbu$4+Buo{6C8DYr{_LA7gJu(sN@Zi=g{ zRYJm)+~!fZorJN4P;SSh76q_E?jwq^U7?1-G(QmV&~)eTPN}akxl+p~g53qF^cq#u zU1E;9hOSkuyRD+JDP)XDVQ9k5B4y*1HnCHMFSW8yqbnENH1H+$YdUFw2mnifG2++Z zxK%o!rX|NkSNuxy_See|Wofcm<$9VGw=o8J}Ox8(K)XIvyyBP7i2s-8*<+85D==U!FozuBu-kOEIc}D#MH1Vs)U_0g9V+j{ zWWftR-zA1zvB4(U7?J|uf=MH=1G)KdhJ{$` zL?fzQqmUP&tEq~Ki7>eY14t2yf!bh1=XPK9ihh9CNtLE1c&zftV3vJw}%4wu=I;9oV?XKL!Gp@pLFm6^ zbH79CX{4T?O+954_N#0ZwGCVuahVMo_rG+NIf86;P-*QHKGi#NgsAV~@}3 zuf<|J#$;&q`UOmz!|uAd^AhXJ`u3x>YMX3LH1t<$*x*RiE_1y`4pga8oUkJuc!nz- zLkUm4sBI)$h?&*}pzHO8lKPFNGdQdDt~r5Aaj1|-S8lD-i)W6SN?UEdIcX$`qjr&u z_*W4=*vF+*1N;Csc=Ak52jWAV#upIgnJyp#*vjBI>PaLSF#;iGx!K2rNE`dqee?={ zqn@8l+XkPd(sXu2M)JM_%V${PgCV@SmQuMWvNIMv)5<4sW&p<#gvB+(6Nx3jgK`Nb z-|Ss&NP!aqT4oWH-B2{izLE#meRwag8urqZP|(#{*8ORqrOb&(616VqrlToYa9$ei>k< zsn@c6WRWF2G`@RBD@dMZ*8~93`h$FrMalILx#E4U?6_icW!Cz^i+Ph|v5}M#ViYf) z6=JuZ+Jb*ErSogxe=*HMt%9uL*?VB4a8;zm8V;+`ioLji>$HH)qd(PL3L0=u5`UffFQHh_jYA?gu)kaRShF^c;Qcqg==4^-VsrvfuQK6p2$$ zXcRG(i6to(=_HXNl;q?0&zTg4VA=Hb$=F`aqlm%2jxo+7K5|QllW5W)2p$~{@~vY* zq#azFndiVy*r8(mhF5Dch5#LlC6rAv z*c^E4uo{aGm{eCTpzDr@kM;c^KRqv%y7u*^=^-_DYN(=;)lD37`SCLuK@d`?9+=e1 zsuw3LP7W{z*Jrd*rsq1s#{2-(&#y&(9rX({R5r9v1hZRIYJE3JQ&*|Ecc|>p-DxGH zrk?WzkwxeNKQ=N^LptSDk(I^ z(6Pt|r?l*Gq8M9`<16rn;!&WGXA zh-N;9Zm*mWdrpxUXTF(?q`Q$O*Pdl()o<+*-9aTwV&*QA)^+mP=21seJv31KU0(X8 zrJ5CGS$6{(!x_k8tmPUvnf=rPq9q?>QGfj<%JY4QUxrTJ&;zrA{-cRQY+ zw?ligMRHqp=_zEEvud(a71;6_A(L<{Fzi_l;saz74@~NKGWTUp@2avf?1;*Nvf}H)Hl6^yAdwpEh)D1xGPd!Ne@r=~SR6ostz$e^{^v*c# zFby>D;jjcvg5JXdDS%R*MOh=e-LG>=<&i;c^MXkLnO)h!DwREfBzm$o;2r_(TH=i+ zk~MUGPrX%Lpy1XuL3xWKOU+vMeC{<=*(7!U05=yM1v@YRtY^R$yTz`$8x>`9(>l>L zO*A5A&I`1g)qfJBJw36+L)uNnLa4gcgq}6H)J%^wNH<9wQTa<7tEwH# zfsjhCRtv^Z?D`ejTFgN?b%?gQs!ayGLtUr7E8Ta`xwUNx_^wpb+LCD=Li7^VL??I8 zppBSiCmxQ(pwDgx!FEk7BS8IIpKtcdCz&y}gFpu}Dnk!q;QJlzuT>S)JiMUMH~l4D za;%(G(ZH3J)D-e&qvFe~f<5FYjRKVgy-XMpv~kc=$yJWZY-D|rd2B%4Z09F5ZrZCu zP|(!r<$}~py&Zi=pDU=|0|b$rE&)QJRZ5Rn@f`799)%h&A*Nn6Hl8wKE_LFd19Jf~ zN4ua1p8))`#)7^Uxm=O~>5iv_ok@9ZP}I8K%_1DRsM&$vsxaa%_)2lAv)0O=CXh)i ziWdwNvgL^#@;i^yfE^)SD?4jan%O1{TB1$tGK6|?J0GUs=6J6_ks-#*WfjQVFTQ+g z`GTf7N0h`6M$@;aV~l>hIWsVvE4>Y>!)N3?T*uJsQw`?dI$Y`_mb5H#MrKnwxhd;S zgKGuG?Y&7L9wN$t^vg)NKhlc30u8$J=$FUO%k48$(bs8vBhy7vwUN=( zdf{mlxg@8?C@R~Vc=y2QF~)ho_E;`0bAdK6Parj)B}=JM2ZVdzpJ?xTznd2N8e4BG z`E9b@D~f8GS)#Vc?@^2pJ~%Yqpu0d;+SurG)tc_l!+2Wfo={0TTTA}{Cvussq5x}W z=7GK;^u6OoYb#BH{ceKKc(zd*YKk~21wzE$Yc>pln{mSooyV?zTyD}VES3TX0wDRV zY9Ij#mzQ-HY8SaZvfh>HB`}7iCm*;-iwqeKPP&SM6US0Bz2#huzu6c1s zkFhP*+3M$x`WoFFWF<5d2$b=vf>m}BV`51ecT>|HI(4%Ph-EtMeq6w8dLuEIXI8_y zn_u07!>X^G^3vv#WxhvQS5rw^51&0;TToOeIT4ZFN`-Bs?vsE>;EY9Y)KoRYGRe?s z<<$*C3^4RX68y!ZUC&>lud=O0RE;1ZRGxr?kUqE^LdvaIO*vcP61SR`$_tJAQne%# z(r;uQ(nwAcBvOjiYNITuN0C9e|4USraqu_FWaXKaJebEl^B!9(obH9 z=Dg(2?LVa9%uZIGUULSzuBQ>{h&=m^5H%?*l7gumah2|+rZTxCFJc#`85OYgXjBX> z5Mnp#PT&Dy>ZeV@tF-Wl^*}q7!aZBe+jLi|%)RdKOGajCmK;YcsE;P+Ay6oCcQF8T z$sPDVFLgwULqKD!SzhLu$~8vM+6{fPRq1^pXRy!;8%>?&rlb+Xu*PE97{Vayw{o9e zFvKy=N#mXDW>oKL)T?(m+}LfvT4z(b9k_SVA=Nc{Z#Qm=O`5VNWy$G5~*sws3y~*X7%a$s#PAM(KvrsGi|^zf<|eBYK8(e05RLF@ye~ z;@32_pp=2lD#G$7o436oV7X~v`)FzevP0$%F%_|b!Ey)~B;b+&J^EvSp3fL?N<>0K zd(gkqer9rNuI!Y$YACNVTbiP}EztQdPW1?7Uom|QVSMGm#DtQ26020nhNwx4YBt+b zWGlfSfMGauPnLJ;-elWsbI`_%Syb`V#b}l)aZi!vnrc#3M~lo4m2FjXk|Ry^Q%ioes7;YlB_!Kllq@p^J7P7n=O*2r&HEj;*47uwrSYm$dQ{nV~rV0 zKivRjdKDZ4Q_$rFW_I6{FKmA(A_Pc(!1@(m0`QwYUYqd zQ;ac*A`BH`4V))ef}hg8CgJc{g9_ zthczSfH6|i!Y$IsI%Qp$$fr5R)jfWEY1gh?$fgIH&BHZ~eAFa#`>RiLs;7(=IsKW)&* z2UJw=vo*~lLJ0M~%C<$}-nNMZQR*vTLEHCJb^S*UakS9ip{O(=4{s3Ga^CMq+IsVF zrb?t~VwQ@n;h93YR#qxNC$a1S2e%rGdDK~F)}`IMA-F_)4?1-gh^VF2lowRE>U)MM zDl0D0d`z<@!R8~9L1Gj{yMf398SB9v@dOcagfv7DbUYT`W9uDL%xjHXt?G&9_6 zD$+Qm8h$&4o#b?)1`VV%lbqlImSyRaoOKx=pABPV(+VA;EiZS{x2xQ8LYEjWRHb5* zcxfV@DVdpej1aFHXC!^$jom;ptXLE7%BE%p3OMr8rliYBQ#4SeOiUeij+@870DtwPgtmX0dPH4Tpc09OTK5*eOZk~pP;QUbAJ@TkE!W$DD8Ttq*9iapyL zLwKQXpQ?Ke{{2sI)>SmrH##JCrkZM%s3=H!IQIVUs|Ey?$|q01xDE+n6&nvT9`;oh zmV7Aj$$tu3`b*;#aHAOnlTiVt#aPyp za;@Ko&kfdYLfWgVK0EErOIW5ltNm3lj#hv%WQA9A6+pzX^<|C=9)JK`;^OM%&_3T^ zp9EOZw1ECkzq-}0{6cB{FLg_F*J=rBhgMTA-={%?gP&r4d~;RtuX*s99Cq>xrNj1g zHe3iiH}g@QL0bnlsbHs}G1aG&H1SOt-LRxYj=w#}h~b`JSUCHI9Ai7G4rt}|RVw$Z zXVUf69~lgrsai&wBmlVbw-&%XGk^zQpBwpPu6QChExG-uG%esH+IH7nW~o*4>88HE z0X>^*(wq_BBj?4V3sK-WFp=Bm22QzYz#_V{$&lR>7E)K-O?Q!LZYZc&7BO2jGvjy+h)N=P1)xlS^p71O2* zNII$1dCVN$6n3{vELCP`t}jy>?DF20o6J~L0kwT6a`YbHXQ}JLb`Ut({{SUASi;B! zzchlT!qr!|dK#9POsgYDRKaEwoS8PEQIyYNlGyLS=M7P#W7CG(tHvdT#G7^egol|h zRMY8dR+vfTwL_{FK9b-rMm}I;C**hvkp04WDOU$LJdm88r>6!gSEr^r{(L%0Nz0hv zpH)+(M3KiImo7ZV3K_Ow0iS<-eGe78MB!NtCt*u}kRbC)G2P{W!~u-|0Q3G_0!-?! zS!-QS4F#g*OqFmY&_YOy%ncyPP<64c=R?%d>M_3-F zr{SrVf|af`^l%B=%?muOD=Bdj?<#|#XB&tE2Fx=_ra;n|hl>-*0lN}&5UQiOKTa|$ zRCX|ii!ghW$#3B>&BC|5eckWoo4H@$w?^AEa_UZaTV~aIvgH`7uBNJ~m8k7|hJ2Mo zWfD4!2a&fO!0o^sTGvv;0A9oIkK=73M5t7$TNd)#4i@?Q+jFlWBIVyHw7!Vdmknpi z+vRWA_Npn8r%BvrdWuGpSlMDR&g9Dw1Z1h+G1xB)4r$e@>a1*K`OJ@dsAC;koe@g0 z2R7rBC@lJ7)pfb*{$uKDXlU)$=bDa|gkhkntUx^J!5|4EMgdo*8Nof19CaO^g)eY> z#e(GVwfnZ@X}MhF*Bs!Q=cucRsd$4(&*l~Y4a`U#dXtXl`}o$YS)h;*wCLJS>NWoW zXcrnn9yfLbXU>L0pVWWX@#4Py;7+Q}<%d+BPG#O1$&S8lr>PQ3!L#`uBj3Ehox%s1=82S`r}VWM?RHHM`tDbgBdV*q$^2to1led@%jyA{K^&Thm!?7abjWpts1d(*~lfp{JT!*$k2*Bo8z)Ve)?H+7988 zFgUXbIS3q2*;m^RXX;uH{5S5H?R1_8s$%3@mXG z3lvpgGb?v2Yip^s6*Jr2;ko&593=wo65y!D;f&{}UIH@L4y#nbrs2sN?0R#={-afb zj+0bZgZvQ7PQ&$8$MfK_95-2DvDyW3{2KCCnHqYo;i);Fd9I~e2WY75rsk7oMoc?S zVmm+zapmNkpHLVBjC@uglIBf@zmLz7(xXB$klURtw;x>-pNW4KG`d1Ltd@2Y+*wFf zia-?yY_awO`SFHa>iXHCbaZg-pg6dy-{D_G&CZ_@_WSMr;T3Y&eB053&K_*lk?l%y zRDIavX*Z9XAo(6Hs0(Rj7S3bKQ|oUf3Xc;UE_hzwNmtuk-lecvC3?D+s-%b+UF18M z05^Yu<2B}_if(j;eE`C9wXk_AH>-JxWbqRm5W?Xk2 zzmWd`4moO?EF=riDD^m3MVuRFz`_u{{X>d6IROQ)`y ze$y0}3su63otUdsR8mPA2hKk60DU|0FhoFAy6b+ax65C4hPIkDl$8|nvoKX%pcN2a5}kX_D$BJ1fD8Mr-DJ0l_Fdp{(pxF zI?fvn*hsFn$&L?wiGlO)!b(z^UO+%e3MXIy=r|BTxm#|LW|#_Prs;*wkfHWmHs1Io ze~%T_bTqhdQ^3;iF%;>Oydt+Qe!>QAWT}iD)qd3+z;E9%R z4q9Ks)|Xvd%o*a<+WNS-q@{7@)5TG+kRn1qdg=jVBMqtsRYo#&h8WqPU*tb4Fk-%lx_S9kD}l_S`3%oDok z6oTDz6n6L_h;7=qI|pO$lhgcoy`}^z3uMYy@s$&j>Jh>BGKD{;IC4o(lqT8=DBzDU zlCig`Nb7^e0?N{)+H+A~wEQ9)RnoeSoJr=jBytC)cmA=6`U(1xpRW^+DWw%O$2+9B zO0>6XG`H2r>kLms3c)aJD2d}{^!GSDRObW^{808sh$|Z4Y_{tiF-9n>s>L9ps>4cB z6-d@yi~}nmJ3|0{EC2^25!mqb>XAnOaE=*;`V9U>T06DzcPO-)I{_`E=pb7W-Yvtp0qF)6-7wpaWG& z6+)=bd`PW>oD7V7xLPF=i&UCc?L90K8yHu3)!ACzWQzoh_F=eweRyy~goOiR2kwVi zW3z73ySn7|A5Z1LE1)uAN_3TM@JU%uND^xKsoYb*3@_U>KPgC%6h+imSp{9s}6lIByB`2ZxJYOWBU;`mGRop64h7Gc_P&Z5|+JVP# zKPHLXW!Yg>>O7?<1p#7PJXGo}WJb3>{Zza6Rg!cTK!4f| z%=(%>V^u2EN+7XYJ_?!-EQB-Eg_dbUpS|cv#`b1L1JFv^eb~;Ql)Ie##!9!6*F`CKp=0OE z7hUc;Y+s%abMqfgJMO{k!$MxUSgk0aO0~Efe7y^CND9>(N&W zZ8cV+)Ov=YcF7{i6$C5}Q);OvKSD|A@&umaj<^scofj}>%?h9Rq>=%u7TrlA$xlI% zG@xUA$GG~1?f9H~an9qPoPt+Hf@ot%Rql3hW`(Y3S&w*L0IedjZ#`21#SlKqQa>JSPyrn42jzrRD2 zrn28!g(Z zRYbiyso;P}L29=?qN=Eky&DuBs}b76^7rA(iA@1+(-jb|qK2xjVwBX)VASs9nd2;3(+}Klwm7$SLZ1Oi{C$7=lWRAJw%4`jAB|+vy1XbnWp6jM- zW;XY{P$D%o!k5Tdm9jzgt~X-}P855C>^Om>Y1DCUg<5Kgl-LfV*ij3wCwX^p^QvRM zS80d{>R87$I+A)3<}h$E?Vrzx$WVfXaA>)0Gqq|?^`e%fG!IP_fXa&}NfdqIk%j>E zACC{ZNYQSdULxT#|kGQ_V&Y-&tvEW|XIezCU$D>{TEKpa5i&arGGa z@mF>cgA)D1YO-0Ux<^o!xJ|<0GVI#}1Ldj5sfjpJNcwdCR|{x{d6~_+J<;+W!K|aE z70q30xk(xct`w}SOq&Mc(Vt6<=j3tk#dPTkV6-do7?)xl-Z%;5B6{&W)OS&MM%2_U z)7dW;%lu$~BcFW~#{(EUwFo^l3hdWvsidiw%Oh+eLRgk3wh#a@><8h+6W$z~Z}uOQKp8w+?fLvJ zesi|{Pg8rE2ownw+j$4nJ^KB6@y}x(3*c(H93u#1p{#HL5F}%FUFv%O0Mm@4yL1M}g+VwT4y=)oflhq3qK-IP&JLSL_z>#Q`kdxUg#6|EQ&N};-i_Rmek6M}vE zd+}{SE$Qs4*kGbPKPT*!cM6N8bpl*2l~T1t^)*9#85rc1QH5ToJqH31O15E0sdP0u zj3TNJpvMiDifqL!8d91syfVYN_TfTVth83>TNTMy;_Xy*gmoT#A-}(c3DcdUPtseX z5K+-n(LxXTxMNiV@&ktoBwbAGkp+@7`?IuXEV%smm`+r!q@mi<)Ga$Y^w?XWKR%fD zAJ2&>M(Ag+HU65@HEktb#-5f%VH?uYznvKKE_39d)5HIfNdQ1$w+jJS%`sVFLqwZHqx^nSUtJKR< zAo68}S&J-2Gt_`eg&7?YbJsjp-`l6k74hCxfT%UnwXT;L>M^xl%iy_V^(3C8{LdWY z++5;UNYRzBwmW%Is3&d|llgr3ZJ|21{{XXJ#J$@9Zgjyn5?agHV&qC%KZy-K}1LpxJc zMp8&6QJt<1S3fbF4hm~zDhs0O+FI*{+Sy567z(v8q`O08DI=)-jz{Id&S`1NRKWyD zOJk5@1%W>shNV>027oBeDgk_AnaY1oS8*|qcT)DhLxu~{kXlAK~6=D94vNbCxa2`PK zg4qFrGL;=39~{R5=L?@ziCYBlKw%IN6UJTpMAqm!I!z1A3x2DLnz?B%D{Z2vF!`?w zOB#x!`=`o=I34z|-IOcCR>b#>$`zC_&ZO+mg-k3o330kn!bnwlM(|It$^QTk=fEr( zoB}=O8cO!@Mq{9=t#U^Cu}F#l!+J}lTm1=Pn)C1#7a! z*ZXnEpZ@@^BTwTBy5Hj~qLrGS^KYt=Xtf=6lgvBjhLTT2l4Ea~ji&^vs6U2%_}yzH zXt0Zb)Gkoh^7{V(ZnDjImfa-QSS3g#xl{h~on6V=yT?qOrvvDC=hsImhdmGT;U`LI z>Kc}6dbAmOX%b*QU=V-9`S6n^l~ksd<5dU+k_p~51HLkLpVJ&VNz&0rTTxXKBRC-a z!2L-4KM#H;2?a!eY^|>?RMY6n8gW#$F9zjctB)@vkh$)E6W_1PiM-}Hl|V(5oD!p^ zRQL4p3n$Ti=98YJpL32HI3yOx&QGOIeZS|!6)8%VcZ)2caq?l?g$X6L>goLAP!*E{ ztbIQ$aNN_U1r;D~D8Yw7yYZ3vcH$}0BS7^Ml1Yf3`8~LhQPCm3=}E4(x~f$w1o4#I z(Fqp^=Bx-mnBqiAZ53taXCz_eqKLz zF~Fk?*aruA0Qb)sc-IWMOJ|0{dg`<=h0S(mAAJ$enUQPDuOzvn&AWBUH6DwswaKPw z>vgSBmi0$T@c~>wfB=spOS{xq?DhnZNx`!#M42LYCh@eYF*Q5K$Y=wQ0dwJ*(b(=d zED2D05;KF3rcdgAyl5bl-%N7;SZQsVs^f8^wdtvvUoNs%b|!eq0+@wUwnqEF9)$rp z&rS}bLrSh7H3wF))V1HOI!oCHpx7!{H5 zJEOGqvhX>BsN{yGvKx}wwDr4o;%gZLO;qEs5TucW&+*C+LYzvF@dM2@Ks%=sz^gZ? zFSAErH9?r!V7S*tY{!Rl-MP3PcMRtQ@WQ&R$M2oHAvxTqs}N zlPAq5a!?r=!bzRoTN(V%4hl$vMa)XQHAySb+#`yzMc5R2vOUf_XB|O4_~J$IAvh9I zYnPnRqtx_pQ&v@lxPU`G-KyYrBzrbHjw07ei5tck36*&9HP1~;%dJ};ow6i0nir>zWxBeg(p3f?uP8QFFsIUeJBbAL z#|~s@q|i52isP$luNOJ1>MEM9wo{j=nqM+UKT>=9^y0D=l9MV{*2)Z4%9+ptfGkW# z-|FO#Z)3tylttv#iuE?Iwk-A&Ukl2rA+CXZqS+WNxzHZC=uSR-4_fUY7*^A8YovuT z@n5QL^XhplRo5zN^+GBdD{WfMNfd-^AZ&MxNH%)5Gj-dO(*n#bKI)WiQm*p%+e8JV zr+32`vKPMb=_BM%1%Ob+TP+B6B@ZfWv=)ssO?bC86tveG6K^d`Bw|LAMyqlPvngOh zjGnn3+;lYaGJ`;D^6SNO)e9Y2&U2%OA0=5imv6UHUFe{ug)Ow?HAPJ=GB=k<(n*mT z7wS)z5a6DKUo=*D9)osd;l9BK$Qh)X`1kj*FS9renB{xx{g< zefIU?>4|#>Ke~Fu_MOodE_Ic4v#gOu(x$+<2eBQ;f1e#OXeDyt7Z94l)A9JAC>9!Yl~~CdqXC6vbG;N}j#3o*-DH3JU59 z{ZDHb3MZnj6!J{OOkgaMu6_2CfJQPtUrr)g3bQq#GFp4QVJSI3b&k>r&fn%z?NdfL04H9%U+jNoqvzVGsM{?ey?9F?8f_9=bgdmnp z;9%fW`70Lei~_*m9lcZlD*piKKBL+g;!mIA%J2SHcEaMufz*F%pY^<}y5LcOgD;wnMBf?n0E~;fnsufoxFH8bD zANY3Rl1fq%Wf{Tw3=_iv6$9%0CrTi1yo9F-Ev(1%HJf}t=6Vfb`E%ZHuQLWx#cYH4Ma z3`)(PTPPU%6Z7GTN)shzB<`+ENsQwp<3EAVw-q^A3s#oYcMS)r=|(okubjb#g(EIUl5EMQm31+9$w>=TeT`Om5s!3`nF08S*l_rhRDpauCyOE9y90EpL0P%e< ziM>LNSqyaWKSeIAztb&kLc~iTbAng%{{S93Vp}&0mX0M;erCvzt7R*IJ{}Np^Vm4# zDSQjI#Qy-4``JYa$l}y0*gFBjNqxDK)TFB~sYv!CsNp1>ZwiTctvK4PD=-7wJ%7CL zl1bJ~zDG~543coCy;M_d5aKeOn0NeshlYgmo+vNZJB>sX{{R~#j_d$eV~>|#kox0< zl&g!N?6TT)m9~lQDP1bAUZ$Tra#*nnPh1S(WDme+iy9y*oMg#Tnrmw(Q#6DF{d4{t zB!NpIjgh?*GmQFym*x5AJSa|=!BWWm1GHn@_58SaO)F~GN{-Bssw(3NBVYs2=coL5 zXbJU79`RKx%E~;xhpPdF`Q(0o_2HnWl*vAy(}e{o36`=7 znQ{i;g|qj)x)FoKBZ7H^%Uc~>YTj!41_FWd@7o+P3FSv> zows-E?0@IOM+C)TE0;r@jQbyMCuG{FUbDIUENL1(WrA9H9-!=T(xZM}N?`;ITA8Qat<>mS>6a4K(Ee0o_x gSdq7lT$%-zmM#GS1?g_-UXWTs8kX*o-lbg0 z$M^Sp=e={@U+=v;@z30uGoLea=g!Q1n15IYkiJz`QwCsQ000<|3Gi?akXF=Ddi5Tp zBgJa>k(XASUL2@}poqX6z@}*jQND__(+@PYCe|2?_8C2#AQuNr{NbhzSTtsY%HwD5 z!14%*jqzUs_@9D-`8Y=$+$VVW1dj@hqyS6|AP^G^_@7xnY6m>F1F*=j$)5_o!lBT% z!ew)#6bebod&2&@_7|1TB$7k;gL^0*J~a(39sM&-F7D?qL`22JB_yR3-zX`osH(ly zeXpl)U}$7){n5tO?vuTPho_gf55(6m>~nZTWK?uaa?01#wDfP^Gx7@xi;7E1%gXEO z8ycIMTUy(Cdi(kZ;DbZMQ`0lEh`ITN#f{Ca?Va7dKl=x$v-69~tH0=f*Z<+d0093R z>#_cCu>XUL?2!u-3k!&a`yVb0OrOUBB*VgfDu_e=N*mY8je<=mw<}NFb?!&c!V4r>kC%_*QqC@lkbz~4QtXRM^-XbSg-Ng}`Z;e6p)E#CAuSc! zJ*sH2uMYqcFOwi_hv{L@{0L2;`InR(!ND8pT3O=hTho8v;MG!))xW*j0zt&fhCB|} zKjf{%-Y${5Z#fLoupA6PwgBQ(b0a629%hC|_gs!Dn^^ah$m4>e8RJv0{+=HV7&;oH zemLx4Q{)Oy^X%p4IT)2`-{ceUQ=3MAul2(2YQU{(4QnK*9c{IlMWH!ES2SDwvTrni z6SPP5630p>^U@`?3lLQ_>#ISKIL=@T_t?g{^pBKyCt4OURS%3{wbik zjQCA2hV*~`{l+0{Jni@au>K4Q@zB17}Z zoDH7(y2oEdFKa=8+zTNw**f>N2LBSr?$qz`+BY8nkxg}7y){t=Zc79AAN{-*bQmwU z!?mvwvVZ$e*4wJ6+_@!BnQSY%3T zwh~Rtv%}sgEFi(|vzm--VaLhoXtK>Q+P&w{y_n3A`11fDy?urX+Pn|PjTEi$A7$fF z^mWfysQd_eIb;?e!AOHemQ&;jdyxfWg=#j`H)MUNo#xZ{IUf3cB)O=5+1Z=Xr$!$2 z_lRKQ3dM2HiS{pDhA^0YtM#7tV6@|sc_9=myx0OJynTh*J6hO^^?w=D#^btN)Va?|AxEZN=K;sP(epZ|FPX2XkA0c9Z}xlcbOZ9Px6O*Y$6CWvhul;W*Vw; zu0Zl97sZZOh-+|IF)S#3gajuANY=Kw5zVRLUsuZ{;qa%!YEu)~ciogoDUMfaujb-H zY1HD`LM%uh=h~e*AidiM<{Rk74i|0e%zS~XhSmrb_3oZ_ZW;26%<2zq0g zY0qXsV6O{F9tJgNI5jA->@R-KX+Kx!^|f!$-?QIl_89e$<3zz@F3pTzt&@$(OV!3M{Py*Ofg&K&c}-46r6{NE@nQ9E&e4m!oB>W2K3PCD23? zX0hCQLIRY@$*Ey<7eIrJBbd01L!HoVV>T_*)wa6~sd1qQ4Y&Ctg?X$qb)Om#GNL(e z{y=`=FQ&hl{5xjNfu!;>BUX=YZbN=lR!1p&*uHVLP$M&7niF|d0O*{kSsI=^c@Mp+ zZ+eaCi;uw*!HUtG(Oz6B&K#K-IF-}j61EwHgVup7b*h7+JyvZ81PZ7vG* z54JHf0A|5dS^Nh8#=v5K3HHaqdJ~ph`iP1Wh{F)`iQ&=l-zO8+K-pm6zOlB@U`To@ zJ6i|)`grt*yZoXi)bh{YFy?TB8?h-@J?KVXf?lwszUlMs_3Xw|fb)O^Rf?9BkeY|G z11Ho6IFAU-+GLV9XlsA8%;xs&*-#Lp5YDIhxZrsidIg8wxM?Ak4J~3~6*moRt|Zm@ zJ(0YSf`khU=KBz`#> z@NI>s=K)~f6&8fdf&|L?EAiQEcG7*mGWcRC36xY^4y9|O*R)VHHZ3pxLiTk3?X-O<bPdzd20YJ?8io@8Y(TzLo-8;N_$hkEmD%cP>ZhkoleO-sb`Z5oZ zR)OSAap5`pdv>US@l2`5+*&U8jY}7d>fhGsrcTwWYfXz(IRqHMvjvi<7hly4ugoWM zk}3<)vzjjsL{URlqp&?hiHGP@>rCE zF%{Q7&8nLgzrv}ClvR}-7Y%HdyuN9B@6n6;7lB9c`AK)8*l34t1| z-|+E{Gu<65?_U)&1Q2LzNWqqUrJKU7QwjbiYBkIz)7$efM|u%8b@8We1aKZ6Hzm?# z9Nc*CQUBwzbOGsP!Ku#DkF7Z?HZ9(x7M!K0) zjIT3$u9doa5+jYXtKW&0mC0xSDG3^bJCxtiF#6N~>)PZj+pxg7pJc{qMg`VlS0zR` z*&w`LiU^A|lNUzCVTPr^o^5_L*1E$3c_!A$k)p*|A|C)mx3alP^h#Ge+y$<&!Bbca zO9xtN)x{^*3{U9Q3ZKLjMau@$$q&QCKua^Xs_6J!v~+hH(~P(AD12cPg?-`w!IG9; z#QJFq--_ePCCS3p8`QJ%<|r4JOUJuSP@@|E6iF^V0KTzW>u56cW!mJ+zTavsDtp(r zVWhPIjIZ=Gnx87jA1Yl(7FrQ!6|(2k_#SPQr?d`^g9%R^AI}>f2%4<)^VEJ=HC2sI z_8qbnJ-pURam=^By3%*$rJi6-keJIarKQ>nqU7y(Rg5lBMs!FzH2Y}9m$VJVM=?gM zE{BEuB$oYTe*QC|t3ObB5=!Mvx!8E&J^Fl!P@`L<>Q8RAriUx~0nnFm6y6|D(9%4h zZ>G1n7Br2&tP7<;fqK6-_36Bisn zqJ3MDj^^4-N3jGSWgw4dD$gCECGjcT*pb^k5q*A~6Dp$SyVyxaPlkW~8XP5ETN>M8 z&yb|`(sNZUEoGF;8{@X9O z%j~INP;5g0_1GDc(RP4lYrAu9>Nu;rKmNbdjl^EZ@#vt2y|@~v-6p}(QWxF<%cm)) zxexu6FWJN8eYoT-Y8i?}T(gg>g(A+p3n^2ijgb&FL@;D^TR$1@4;f_K_RiB9(Ntg3@n^vfls z*$+=0q(7gO+7$fb-f=MiDLnei_;LM|rfjGAnmMEZ>W$Vc{?kN_-1pNf8g1hh#E!NR zGCBK9NRIzw6PAx+iEik6Vz1*M)xWJTrk$#vZHJ$mOi7sI&a<;dp(Z+aERP&p0>v9B zHa2w_7BCqlo4AgFbjSR%FPHC^U=%2pI2h)^qFs0;=Zu$K2IiO7LVb8&at1Mj@T2+S zvX#Seew6E>VrzDci}==C(=zhc}B(6Vvnny%JXno z`*K`cP6v`5N=3$qFl5=iGmG{0cp4)70N_nscz6E-)%pXIl}GQvVk{2yT!GJ&f;QnMvTdsX9koqaxPZuTio{T3_^ku8@sI%qDpQgbLb zGHx-W&SI!&NhEK~#4TEF9A;WwEx6^f;Vss zD+$Z6RBeGpV=a^4<-gr3YsRv;y zd=|0eU*jHU;to6m?smn{57exKmR?9+h_8XGKUGl8kTI*pj@vmAR|2<*TWbQPMhjuI z^^*f}nsZjf|p|7|lZaW)0W6)|}t* z5nA~1tw7O>tH=WJo>M9^H?C{`4)l%MKiIgd?|kc#nsuU8zoRqnu<~hd4xT*>m~2L9 z+}BL>J?(G=e>&{f&YB5e4@VumrdUMtUkdP#^#c6x;Ww4djL?Nm)_1a>UW@^`hHD~?)i3UbMITD+4Z+o z8pRURvuC)QPN&z6Q%$^3>3HH)Q>eb9MLpH9E7*&{PtCGRt{ar!QCzB;do&HB~U-0^WGF zv0`BqHbA9k{O|34uP6{xYMo?xG0`^^MjJf=bd-=eO5$mm(QICt1@TsR&J zov{H$lI~H~PKj;(ud{zp3?AyqF+$=Wuh8=0?@S%U)$LvKjxK38bQ1X4Y-6<31_v&J zrZcX($Q{Jmw8Bcw%~fj`e}Osb>c0S#bPUgrh@jtZxX~F)x=8UT^KLb8frIhRIh>nT z|CN`3Wz~V&I8~v`?8M3F8qr~fOU~x20`y|<@RYNAoAV;Oh=Jn0pHTeok~DMgyGb+R zmg}bQQW<8V2!c*x(3V^va{(LUkdJzfTbj^PaiJWMV0$X8dMqgjz=a z7yahbax}NbKPRg5GT~Bu<;%}~jn(mtl{hSuH%*zbJ^YwcO81k8iXC9W?K8Rc3e1|! zX0hyBC)GY5lZh27%+Kt}e5`{un?K74BS(}Rx=I=Edx8Dw8kftRjPX!UKJWlNfAp0y!pr&fHs9~FFPp=x zMZvr{Lf&Nq9%(h&sNI?e0G>rc!wTn6+=Q{JrJ=!z>R$A#BX3UHce9mWlG1O~(Hyr1 zXqQE;B-i3kl^ku;JI8x$A$0rqvtII#b|s3gL8gP+zZ>%z&xmFn@dKW-r6ge7pG>0> z*=0}aQACYjp(@UpeZM=umOlW(p_4XS(LuKIi&jN5({^D{_uMos_WBOsCoVc558yDd z6Olis;CCNcV{r>WX*Ff@{50~^^wCS+T{EeDhF}pytNpc1sEE%^0Eu4UWCelCjFmi` zUua^LGBFV=VhX+Jyw9=TWa2k*Y{~DaZH+4!=ye~g6bQm3vW0MU`&snf$*B`D(GzgG zAL1y_pQ$}nU?fa2TD^|i|2nnpSsG&#Ff zA2uO|C7u-4vp5mX4W;D(8*&!m2D7&|o3}_Ys{u zJ!`e_-k0Ix`ab9T@IKPYZ)wgNg~eP)x7=_m^z7L}`fwGj1RDi}uL|AOHtaX#V8cB& zY9f;ct!G5(X82~Ww<#FecWGIzxxj0O=Do#@G3C4Aq=ix4*Z; zLe;o-TrO7+r5sk(AgfH^T8sGtMG>-i*hgqcLe8<}^^6=XVq;cYMAPbK*^4ICnqS4ZuWCsn7Oy(mdkAJ!bE9rD5x{CcY^i{~uka~Sb_1FZy4$;Cv z=#b!;Mwlbnocv2A(O+twfy)SEoBX0f3Q~2^wQY}38h~$d!jWrtqTfNoIHnmS(xS6= z@?^(R`I)FZ*=S;eI$Ur-u)%u>U&1;p)=Ylcdj%E z$?juKHAQRT=;`BiWcZDU*lUJ%9?#>ZOSYQ4 zkBh4h#hgRgmc(tv7gSBi7J7D_NnN=;Y-sQJdBw^bpu&MNt)C#f3&x*?tBPy!@Uha2 z{%#>6`l0k=nmQ}vgHOFYZg&$t#9=aCH5y1*Do$tdv(f&RpUBal=WOwryIGMaF}$rB zMo-GDv_4^Y(1)%?oggxk!!@E?eU8}vK&rdn>e9CA=yw8y!Rxhm3tTnYqy9hE7`DQ{ z1@*9Ome_DWGptzGx5CS1f5vAfCV0>?E<(8a zg+K!{>6$NE$30RWJ#p3Bzj~8Z)t3bFM>pT!Nt;k}6e~zb0yCyC@HSLxsC0D@l?_qM zCL>YDTkq6(*QTpLxiomR+jH=sMv}gNa)J;Td_6tnG{f;`=<8uKbtI&*S$}zO$yeu% zi?mn4RoY#Chjq1M#>?K*@TRDA7+cDaru*^Rfl{CgH{O^czoe^STd861?eC>7lty1?*-jxerpNnxys7fjDGk-Qnt$9=<{joSesW!1u!t@ zT4~65ozXLS&)!=CdD%n1GVI%B-p>Ek)vVP~{A4JznxZQ9g*Xw6! znHIY>$TFs`xTHT<1Y?*2{Ic)LyW%g@16~d+dKUpj zge`=kz3&ibORjf@2=RnQ+bO7$b+ys*zowKyLHaYfiEr90KP8;*q^4JjgJY&Qt5eD= zujONA=9eS>xiDf}c?0uY@SAV~*)oi-`z?4T! z6?rF2L9JqKH8mm) zH+mQ4-Te-G;gMxbOeS=PV=q7?kO)V4Ms%b}i?&DkGKD?nSfJr%R6WdN`o%GvY6i`t z9I@7W7Mqhc%)4^n!|!qR{fRVX?H!ssF=ef}~1IEmETYejFwWC!|be+>1-G;6fK% zY0P-Oq*{TTZ=}bN1Ybtoo9T?|l4){x6AxE^Cu(St96M>ekPE3+DZEu_XpA{~KdC_@ zJV1N<8EeSAs~d28xR*nCASZBFb9UuPU6n(3KSumyG&kcZU*PI>P94XE&p!os)P0elx{63g>S|)!&4IyC zO|LK82k!p{OKOHIi6@UU&K>~x_rLXn0HS50{Vx9YU-mu8zz-etYn<|qyE*FEIN z_)L3G-%})Hwa?xWY>|ZDKR=L4D=TyW$PSw*G8HX;<9B^Fbhl*Hp1l(9=W|6}h2n?U zA=U$g6>#16bqO_}GY0;hZtdpqESD$mvP&d_ENOD~EXtD{zOy>^;**sriT^do@f;&U zMR~A@X83mChxwKq-RihwHG^(wv->Kw#Qu&dmCE)&M~&KK-VBta8qM}^n8P?s9cL{m zDF}gM`T%HhL(eg-gJK>7P#!4%w`h+oiQmku`mOYV^$i38s_Jaa5C+p734FJdFf*U% zMu~;14yq@=))X*%<;9`A`cfcH zY)Ybs@Z(kG#_1dCQrq~gQ<^0RuYGfq^7Zfx-u;}Vx@2tN^fv=u-{m0lS%iHT***R0 zd_QONU6yS3yPu8oZ_l1!lyT3yjOTA1-+snvE$7F z&z|g_S7-1?==U5k#|Y5w)yg2uOL9#?TTDDXV%Q&H%js=}sIVp>{IBmoN@in#?JYz* zD1v$@09@)wv1{_Dx2>Krcq#Bo*59^OmO`gx3Py)M?Ej(~)a+8@vguzeX<6G5f|;EQ zfLxS+{bv^LP7*7}X);QG)4fRf!9=x3$;(wrUGV8`kqeG@*24Z-(p=2Z?Njo7bH+}@ z_{qCBZQj{{d*Y-f+21)uzFi3y=ng69Gi&QMZgY%M)rEiC-@ldF%A(yRk7F+H4670o zZ`n8IwQ1DOY=YRqScNv}XD^6|7TE(5Wv4yWhh%(9A$|aT$8$$7Xz#u6=evEbneFH}u1Kz|)}Uf<{4R z4@PlPU&}io#|w%9eb)y-kMPEgX4uiO2jMems`=%>ujMLw)NfJ~c4ee6rQ>3PzLZSN zxFTb__jMCehokAO|3!+3K<%b}tU=x>D*>QeH+E3A8K}p)I*1(d2@7QrUX4@sp_irO zY~Y;ka#_zmA$1g1RB-#Iar$!U{mSFZhGwW8uth_rK4N(xod?|iH#eKi?fF81HLM@{ z{6>zI`8lG2xXnCg)1I|C_>78vW>8sHyjHYGyt;^e=JF+l`Jz1w;jNnwW&Xh=5iBLMMH*XT*+4x?Vd9P^GurutuTMNO;$fmiUKwFFW0NyqQvNwnF z^-8>wF=a6xK!-WO$kADj%-@Wk6xAo+jEoN_muXNj!BDq{h6`dbF#T(%j9B1`&ZDmxaqMaoC$2 zfhNtWP^K-j?-obL4$F({4}kKOE7xv6Or|!!j1rXM`d-9k4b_O>q^Xgbh{M^lxB*IA V$!9S&9?O68iny#6$KVeO{{!3ra})po literal 0 HcmV?d00001 diff --git a/node-v0.8.14/test/fixtures/semicolon.js b/node-v0.8.14/test/fixtures/semicolon.js new file mode 100644 index 0000000..79a3084 --- /dev/null +++ b/node-v0.8.14/test/fixtures/semicolon.js @@ -0,0 +1,22 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +; diff --git a/node-v0.8.14/test/fixtures/should_exit.js b/node-v0.8.14/test/fixtures/should_exit.js new file mode 100644 index 0000000..fd16817 --- /dev/null +++ b/node-v0.8.14/test/fixtures/should_exit.js @@ -0,0 +1,27 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +function tmp() {} +process.on('SIGINT', tmp); +process.removeListener('SIGINT', tmp); +setInterval(function() { + process.stdout.write('keep alive\n'); +}, 1000); diff --git a/node-v0.8.14/test/fixtures/stdio-filter.js b/node-v0.8.14/test/fixtures/stdio-filter.js new file mode 100644 index 0000000..9bb9af5 --- /dev/null +++ b/node-v0.8.14/test/fixtures/stdio-filter.js @@ -0,0 +1,32 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var util = require('util'); + +var regexIn = process.argv[2]; +var replacement = process.argv[3]; +var re = new RegExp(regexIn, 'g'); +var stdin = process.openStdin(); + +stdin.on('data', function(data) { + data = data.toString(); + process.stdout.write(data.replace(re, replacement)); +}); diff --git a/node-v0.8.14/test/fixtures/test-init-index/index.js b/node-v0.8.14/test/fixtures/test-init-index/index.js new file mode 100644 index 0000000..31272c8 --- /dev/null +++ b/node-v0.8.14/test/fixtures/test-init-index/index.js @@ -0,0 +1,25 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +(function() { + require('util').print('Loaded successfully!'); +})(); + diff --git a/node-v0.8.14/test/fixtures/test-init-native/fs.js b/node-v0.8.14/test/fixtures/test-init-native/fs.js new file mode 100644 index 0000000..06392c6 --- /dev/null +++ b/node-v0.8.14/test/fixtures/test-init-native/fs.js @@ -0,0 +1,28 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +(function() { + var fs = require('fs'); + if (fs.readFile) { + require('util').print('fs loaded successfully'); + } +})(); + diff --git a/node-v0.8.14/test/fixtures/test-regress-GH-4015.js b/node-v0.8.14/test/fixtures/test-regress-GH-4015.js new file mode 100644 index 0000000..0d9c05d --- /dev/null +++ b/node-v0.8.14/test/fixtures/test-regress-GH-4015.js @@ -0,0 +1,7 @@ +var fs = require('fs'); + +function load() { + fs.statSync('.'); + load(); +} +load(); diff --git a/node-v0.8.14/test/fixtures/test_ca.pem b/node-v0.8.14/test/fixtures/test_ca.pem new file mode 100644 index 0000000..a3c1e4a --- /dev/null +++ b/node-v0.8.14/test/fixtures/test_ca.pem @@ -0,0 +1,20 @@ +-----BEGIN CERTIFICATE----- +MIIDXDCCAsWgAwIBAgIJAKL0UG+mRkSPMA0GCSqGSIb3DQEBBQUAMH0xCzAJBgNV +BAYTAlVLMRQwEgYDVQQIEwtBY2tuYWNrIEx0ZDETMBEGA1UEBxMKUmh5cyBKb25l +czEQMA4GA1UEChMHbm9kZS5qczEdMBsGA1UECxMUVGVzdCBUTFMgQ2VydGlmaWNh +dGUxEjAQBgNVBAMTCWxvY2FsaG9zdDAeFw0wOTExMTEwOTUyMjJaFw0yOTExMDYw +OTUyMjJaMH0xCzAJBgNVBAYTAlVLMRQwEgYDVQQIEwtBY2tuYWNrIEx0ZDETMBEG +A1UEBxMKUmh5cyBKb25lczEQMA4GA1UEChMHbm9kZS5qczEdMBsGA1UECxMUVGVz +dCBUTFMgQ2VydGlmaWNhdGUxEjAQBgNVBAMTCWxvY2FsaG9zdDCBnzANBgkqhkiG +9w0BAQEFAAOBjQAwgYkCgYEA8d8Hc6atq78Jt1HLp9agA/wpQfsFvkYUdZ1YsdvO +kL2janjwHQgMMCy/Njal3FUEW0OLPebKZUJ8L44JBXSlVxU4zyiiSOWld8EkTetR +AVT3WKQq3ud+cnxv7g8rGRQp1UHZwmdbZ1wEfAYq8QjYx6m1ciMgRo7DaDQhD29k +d+UCAwEAAaOB4zCB4DAdBgNVHQ4EFgQUL9miTJn+HKNuTmx/oMWlZP9cd4QwgbAG +A1UdIwSBqDCBpYAUL9miTJn+HKNuTmx/oMWlZP9cd4ShgYGkfzB9MQswCQYDVQQG +EwJVSzEUMBIGA1UECBMLQWNrbmFjayBMdGQxEzARBgNVBAcTClJoeXMgSm9uZXMx +EDAOBgNVBAoTB25vZGUuanMxHTAbBgNVBAsTFFRlc3QgVExTIENlcnRpZmljYXRl +MRIwEAYDVQQDEwlsb2NhbGhvc3SCCQCi9FBvpkZEjzAMBgNVHRMEBTADAQH/MA0G +CSqGSIb3DQEBBQUAA4GBADRXXA2xSUK5W1i3oLYWW6NEDVWkTQ9RveplyeS9MOkP +e7yPcpz0+O0ZDDrxR9chAiZ7fmdBBX1Tr+pIuCrG/Ud49SBqeS5aMJGVwiSd7o1n +dhU2Sz3Q60DwJEL1VenQHiVYlWWtqXBThe9ggqRPnCfsCRTP8qifKkjk45zWPcpN +-----END CERTIFICATE----- diff --git a/node-v0.8.14/test/fixtures/test_cert.pem b/node-v0.8.14/test/fixtures/test_cert.pem new file mode 100644 index 0000000..a3c1e4a --- /dev/null +++ b/node-v0.8.14/test/fixtures/test_cert.pem @@ -0,0 +1,20 @@ +-----BEGIN CERTIFICATE----- +MIIDXDCCAsWgAwIBAgIJAKL0UG+mRkSPMA0GCSqGSIb3DQEBBQUAMH0xCzAJBgNV +BAYTAlVLMRQwEgYDVQQIEwtBY2tuYWNrIEx0ZDETMBEGA1UEBxMKUmh5cyBKb25l +czEQMA4GA1UEChMHbm9kZS5qczEdMBsGA1UECxMUVGVzdCBUTFMgQ2VydGlmaWNh +dGUxEjAQBgNVBAMTCWxvY2FsaG9zdDAeFw0wOTExMTEwOTUyMjJaFw0yOTExMDYw +OTUyMjJaMH0xCzAJBgNVBAYTAlVLMRQwEgYDVQQIEwtBY2tuYWNrIEx0ZDETMBEG +A1UEBxMKUmh5cyBKb25lczEQMA4GA1UEChMHbm9kZS5qczEdMBsGA1UECxMUVGVz +dCBUTFMgQ2VydGlmaWNhdGUxEjAQBgNVBAMTCWxvY2FsaG9zdDCBnzANBgkqhkiG +9w0BAQEFAAOBjQAwgYkCgYEA8d8Hc6atq78Jt1HLp9agA/wpQfsFvkYUdZ1YsdvO +kL2janjwHQgMMCy/Njal3FUEW0OLPebKZUJ8L44JBXSlVxU4zyiiSOWld8EkTetR +AVT3WKQq3ud+cnxv7g8rGRQp1UHZwmdbZ1wEfAYq8QjYx6m1ciMgRo7DaDQhD29k +d+UCAwEAAaOB4zCB4DAdBgNVHQ4EFgQUL9miTJn+HKNuTmx/oMWlZP9cd4QwgbAG +A1UdIwSBqDCBpYAUL9miTJn+HKNuTmx/oMWlZP9cd4ShgYGkfzB9MQswCQYDVQQG +EwJVSzEUMBIGA1UECBMLQWNrbmFjayBMdGQxEzARBgNVBAcTClJoeXMgSm9uZXMx +EDAOBgNVBAoTB25vZGUuanMxHTAbBgNVBAsTFFRlc3QgVExTIENlcnRpZmljYXRl +MRIwEAYDVQQDEwlsb2NhbGhvc3SCCQCi9FBvpkZEjzAMBgNVHRMEBTADAQH/MA0G +CSqGSIb3DQEBBQUAA4GBADRXXA2xSUK5W1i3oLYWW6NEDVWkTQ9RveplyeS9MOkP +e7yPcpz0+O0ZDDrxR9chAiZ7fmdBBX1Tr+pIuCrG/Ud49SBqeS5aMJGVwiSd7o1n +dhU2Sz3Q60DwJEL1VenQHiVYlWWtqXBThe9ggqRPnCfsCRTP8qifKkjk45zWPcpN +-----END CERTIFICATE----- diff --git a/node-v0.8.14/test/fixtures/test_cert.pfx b/node-v0.8.14/test/fixtures/test_cert.pfx new file mode 100644 index 0000000000000000000000000000000000000000..fd28781a051e19d99ac266bf9d98ef3fd7694971 GIT binary patch literal 1970 zcmY+Ec{tRI8pnULm@$K)W*8yLw4f6sV;z^0#*)Z#S}bK96v^1ma7<%trBc%<;UvaB z%2qf<$TrQ5!Hgwj97iH#U$b=eJon!2{o{S!_xXOm&->T=e((%<2^a*yGvJ{xghqm8 z!m1Pq4$5M{eV`1u$ByiVXF#=nTCgkzbl;Ao1O@>+P4=e)!Yjd$|K1=8g5gn6arX-r zsuy5h=fGfbfX;wSFdVsVTBS4kMYj%nRufGRb1k-S&}TNuZ+5TtYTOFZ zA>aat!_Csmu7bGdKEep=N%!GE?nryI*QG4;@Kq4`olexHjE<4ygy`>YPE3i~bDX3- zjKuM=HGc6gVrws2wZ91%eR%!6EfGE2_lEUF4ER*72lb*Fhz*csosYK?y*X^*WTwm-_qVs#Ofv|%)zbR|u8qfGve3PTuvS~))B z?CsILw4)zmkKnexH3hF-iPF^04ulzj1d2~k+EYj0NfE!OS162U#?@JrFw0HWFY>0} z6ZDPD;umQd6BKedYN^;2*a=+JT*$0VFN zN(6Ti)n{r^LssM7voBC?<8&)#(Dy*qbIlo3qUe26iRjhb^shsPLjf(PZvJH(w8X3M zc8+T(B@K@Rr^mK2*Pre7-=rtaoan0JS_Kafy zUuQz_CtaE3>g-wS)#@U}&F?MDD_YA|>X%!sH*L^+U!rTVQN!4V921Zbu=7~2iNk5; zU+KTE>4GSS9*j@kXF?1Yca@`egKQdKlY%CT+2e#cA!g-7HG=1{6EBrNTFj+OURVbqN9414x zXq&Z!96=9QX@8x?-eWIbfE_;n{^zY#0n@FnOnj-hhYOIY2)B@phF4luy`2x-Wk1CA zuekDIRlLN!BkH#a#+5u&n8>(ryii#{so4;F79fUL@HL1(ZqAx&uOD8}0XSOvpXk%kkRw@ko?D@>Oh+NXP zEz{vayRe$l_&GIsjo$^x2!AuZr2^xXwH zcD%x~u>zrXRNEz+b1xI;Pt+1xBJMk0PyJ9|U8s@2cN3wM=UW zW3qg5xBF&q744EZDiGyb8y-?z#T3VyZ3*>9YP?19b0PA57=Z~(zyu(^a;(NG8>)RW zuh&?J{dVdDofg}luJYUDOp0dx!NY6ODTtFp4f1WsjDZA-Y0VYVlBT^KdljY_Va4?u~i!A>Zb7RpkZuafi`9D(S}fz0y4Ci21UPmZb~Pf2$2D zisk=;I;~0QWQD32VKQ}nC`;tF8Z~*Llfs>t{xABlA^+^Qxa?%O4W)u-ZE;$x1J^C(8Rl$8}R&+f_+Qx z35XI7+90r~ID5A6Vd@Plf2#5WE{@rf5oS7;w=3&aA@L>M4RN(Sw=5Swlr`5;_jjEh zoTmP@9N46;9q!A;(r)oZjvc+stORqlPXvLGo8J+RD;u8hG zhAt$=J_nw{hrNQ;Pq*V-V$2@aNrJlpM825eJIJ$>hko?%0N-mX8$sE@;k80Kx z6t!77owgkJ&;DE-R8gtGcOma`itpE(Z@RA^cJ^M!9YuCn`d4!fYoK;mVn}c04llPo z`{X(XXZ>`z{IZLD;Ry~!q0E~*fsgYF)@p)V4#}n{1ny2V_vm^nM@@IIPC7U@Lr(9W z$m=}*?#z%0p)JyrV)swx_M}&G>Q{VMp3#imAF9_!)U+M&xc^=?LRMQ2iqVK{92#41 zbEN2|MS`7!4IHMEhVe&!hA`U7%1Xc);3BXOI0^Uw6d)Av2gp0+1$gYtK6q{Xemnvu tb_4|hD~JJ5%=fGLxYQd=zDdL*j?EyiytotSfQnC;#nAn{;z2)N;a^BNk`Vv^ literal 0 HcmV?d00001 diff --git a/node-v0.8.14/test/fixtures/test_dsa_params.pem b/node-v0.8.14/test/fixtures/test_dsa_params.pem new file mode 100644 index 0000000..7007372 --- /dev/null +++ b/node-v0.8.14/test/fixtures/test_dsa_params.pem @@ -0,0 +1,14 @@ +-----BEGIN DSA PARAMETERS----- +MIICIAKCAQEAiJCR40HCtA6pk864XhKceke8N4chlrpwcphAXpHwSQGHlv1JJFyj +aPqugWtzwZH55g7qpIiT3fmg6V6PfzNfx4sQGlSjckZaN02WRUAacn0va6UbwyYV +7LZzuHlHzayHLl/btGeTF+zL+9eMLKfll+r+5bJXDMWh3xUD1Nldf+fsIsbVZI9Q +Nzf3L1/07XVTLedQYaE77OqVuu+cfoBtb+K5MsQdHMMN20BGjKIvGkJICuC448Gk +Dx1wpxz2vSJEi6FqXruM6c9yrPvhJKSfbVFYK2n82MMXMNNu9Dwqwsv6Ig6dIVyw +dKDrSw1Nz9j9TWA5BolNta3yMPHrEjCuIQIVAKq0ZZ0/36sZE1cqt6j0hZTisWUV +AoIBAFbI9MKn9DBJ7lo7+LRblgNKg9lk4D/6NBBRgOeCN4WnOxHQrqpSTUBG+VcA +BDKEfoHfEPI9KZKpEgpzGTpr7mGxDPLHfGL+vvf1EYbmcTDrUWlf9B/3+L3uwIdd +v3NYLepyEZ8L8g6eRGSQ4Svg1oSR/GAUTeGJczPg6qW0b/LTpf4eeDNWYGF6aogJ +UphnPcZ0Xqw+yvq/i1uzAVirUxp9Crb7km0dfA0G/HBiSdcEt6l8LdQd6qmcL0nx +cm9x6L+tSol5hXNynV0wcxdCQz4Xj5na+NoRGb9jPYxgLkoq07hwAkqkQDyF61tx +fWgGc7zmh/x6JMGe/Xhg1TvgxLs= +-----END DSA PARAMETERS----- diff --git a/node-v0.8.14/test/fixtures/test_dsa_privkey.pem b/node-v0.8.14/test/fixtures/test_dsa_privkey.pem new file mode 100644 index 0000000..6f06041 --- /dev/null +++ b/node-v0.8.14/test/fixtures/test_dsa_privkey.pem @@ -0,0 +1,20 @@ +-----BEGIN DSA PRIVATE KEY----- +MIIDPwIBAAKCAQEAiJCR40HCtA6pk864XhKceke8N4chlrpwcphAXpHwSQGHlv1J +JFyjaPqugWtzwZH55g7qpIiT3fmg6V6PfzNfx4sQGlSjckZaN02WRUAacn0va6Ub +wyYV7LZzuHlHzayHLl/btGeTF+zL+9eMLKfll+r+5bJXDMWh3xUD1Nldf+fsIsbV +ZI9QNzf3L1/07XVTLedQYaE77OqVuu+cfoBtb+K5MsQdHMMN20BGjKIvGkJICuC4 +48GkDx1wpxz2vSJEi6FqXruM6c9yrPvhJKSfbVFYK2n82MMXMNNu9Dwqwsv6Ig6d +IVywdKDrSw1Nz9j9TWA5BolNta3yMPHrEjCuIQIVAKq0ZZ0/36sZE1cqt6j0hZTi +sWUVAoIBAFbI9MKn9DBJ7lo7+LRblgNKg9lk4D/6NBBRgOeCN4WnOxHQrqpSTUBG ++VcABDKEfoHfEPI9KZKpEgpzGTpr7mGxDPLHfGL+vvf1EYbmcTDrUWlf9B/3+L3u +wIddv3NYLepyEZ8L8g6eRGSQ4Svg1oSR/GAUTeGJczPg6qW0b/LTpf4eeDNWYGF6 +aogJUphnPcZ0Xqw+yvq/i1uzAVirUxp9Crb7km0dfA0G/HBiSdcEt6l8LdQd6qmc +L0nxcm9x6L+tSol5hXNynV0wcxdCQz4Xj5na+NoRGb9jPYxgLkoq07hwAkqkQDyF +61txfWgGc7zmh/x6JMGe/Xhg1TvgxLsCggEBAIXcOokkhVjC+i/I/grM9qTh6fCV +jzSbOsIVi9Hfj7GCTRYA/QFnNbiWbOWzP7t2cEQFLfZoJmTK71+htZql9/GRMzV+ +dnyhwuRh9YWkuCOlFHD7hDFBC+e1VqhV7ltaokqkZU18BsmgZG/fxeqOAfElEKLE +796rOAXmtx8F14Mn+IQteEAmifF1140C0bFzH67RSZU13pRCB7TKbruTevnhdQct +LOzhgpMuoEWAjSWni5+WklOg/LxrMZ7MFz+Kqph1PxSX7kg/S8yCjNFtaviY7HrJ +E7wUqi3Z/VPV4HKGeHzX1k1Z9RE/oJTsR2yT2rtJvSGO9lDk6Fj5tIv1fC8CFQCd +3V7C07NVeTiUU1WTP2nFNgMqEQ== +-----END DSA PRIVATE KEY----- diff --git a/node-v0.8.14/test/fixtures/test_dsa_pubkey.pem b/node-v0.8.14/test/fixtures/test_dsa_pubkey.pem new file mode 100644 index 0000000..1f1dad6 --- /dev/null +++ b/node-v0.8.14/test/fixtures/test_dsa_pubkey.pem @@ -0,0 +1,20 @@ +-----BEGIN PUBLIC KEY----- +MIIDOzCCAi0GByqGSM44BAEwggIgAoIBAQCIkJHjQcK0DqmTzrheEpx6R7w3hyGW +unBymEBekfBJAYeW/UkkXKNo+q6Ba3PBkfnmDuqkiJPd+aDpXo9/M1/HixAaVKNy +Rlo3TZZFQBpyfS9rpRvDJhXstnO4eUfNrIcuX9u0Z5MX7Mv714wsp+WX6v7lslcM +xaHfFQPU2V1/5+wixtVkj1A3N/cvX/TtdVMt51BhoTvs6pW675x+gG1v4rkyxB0c +ww3bQEaMoi8aQkgK4LjjwaQPHXCnHPa9IkSLoWpeu4zpz3Ks++EkpJ9tUVgrafzY +wxcw0270PCrCy/oiDp0hXLB0oOtLDU3P2P1NYDkGiU21rfIw8esSMK4hAhUAqrRl +nT/fqxkTVyq3qPSFlOKxZRUCggEAVsj0wqf0MEnuWjv4tFuWA0qD2WTgP/o0EFGA +54I3hac7EdCuqlJNQEb5VwAEMoR+gd8Q8j0pkqkSCnMZOmvuYbEM8sd8Yv6+9/UR +huZxMOtRaV/0H/f4ve7Ah12/c1gt6nIRnwvyDp5EZJDhK+DWhJH8YBRN4YlzM+Dq +pbRv8tOl/h54M1ZgYXpqiAlSmGc9xnRerD7K+r+LW7MBWKtTGn0KtvuSbR18DQb8 +cGJJ1wS3qXwt1B3qqZwvSfFyb3Hov61KiXmFc3KdXTBzF0JDPhePmdr42hEZv2M9 +jGAuSirTuHACSqRAPIXrW3F9aAZzvOaH/HokwZ79eGDVO+DEuwOCAQYAAoIBAQCF +3DqJJIVYwvovyP4KzPak4enwlY80mzrCFYvR34+xgk0WAP0BZzW4lmzlsz+7dnBE +BS32aCZkyu9fobWapffxkTM1fnZ8ocLkYfWFpLgjpRRw+4QxQQvntVaoVe5bWqJK +pGVNfAbJoGRv38XqjgHxJRCixO/eqzgF5rcfBdeDJ/iELXhAJonxddeNAtGxcx+u +0UmVNd6UQge0ym67k3r54XUHLSzs4YKTLqBFgI0lp4uflpJToPy8azGezBc/iqqY +dT8Ul+5IP0vMgozRbWr4mOx6yRO8FKot2f1T1eByhnh819ZNWfURP6CU7Edsk9q7 +Sb0hjvZQ5OhY+bSL9Xwv +-----END PUBLIC KEY----- diff --git a/node-v0.8.14/test/fixtures/test_key.pem b/node-v0.8.14/test/fixtures/test_key.pem new file mode 100644 index 0000000..48fd93c --- /dev/null +++ b/node-v0.8.14/test/fixtures/test_key.pem @@ -0,0 +1,15 @@ +-----BEGIN RSA PRIVATE KEY----- +MIICXQIBAAKBgQDx3wdzpq2rvwm3Ucun1qAD/ClB+wW+RhR1nVix286QvaNqePAd +CAwwLL82NqXcVQRbQ4s95splQnwvjgkFdKVXFTjPKKJI5aV3wSRN61EBVPdYpCre +535yfG/uDysZFCnVQdnCZ1tnXAR8BirxCNjHqbVyIyBGjsNoNCEPb2R35QIDAQAB +AoGBAJNem9C4ftrFNGtQ2DB0Udz7uDuucepkErUy4MbFsc947GfENjDKJXr42Kx0 +kYx09ImS1vUpeKpH3xiuhwqe7tm4FsCBg4TYqQle14oxxm7TNeBwwGC3OB7hiokb +aAjbPZ1hAuNs6ms3Ybvvj6Lmxzx42m8O5DXCG2/f+KMvaNUhAkEA/ekrOsWkNoW9 +2n3m+msdVuxeek4B87EoTOtzCXb1dybIZUVv4J48VAiM43hhZHWZck2boD/hhwjC +M5NWd4oY6QJBAPPcgBVNdNZSZ8hR4ogI4nzwWrQhl9MRbqqtfOn2TK/tjMv10ALg +lPmn3SaPSNRPKD2hoLbFuHFERlcS79pbCZ0CQQChX3PuIna/gDitiJ8oQLOg7xEM +wk9TRiDK4kl2lnhjhe6PDpaQN4E4F0cTuwqLAoLHtrNWIcOAQvzKMrYdu1MhAkBm +Et3qDMnjDAs05lGT72QeN90/mPAcASf5eTTYGahv21cb6IBxM+AnwAPpqAAsHhYR +9h13Y7uYbaOjvuF23LRhAkBoI9eaSMn+l81WXOVUHnzh3ZwB4GuTyxMXXNOhuiFd +0z4LKAMh99Z4xQmqSoEkXsfM4KPpfhYjF/bwIcP5gOei +-----END RSA PRIVATE KEY----- diff --git a/node-v0.8.14/test/fixtures/test_rsa_privkey.pem b/node-v0.8.14/test/fixtures/test_rsa_privkey.pem new file mode 100644 index 0000000..425518a --- /dev/null +++ b/node-v0.8.14/test/fixtures/test_rsa_privkey.pem @@ -0,0 +1,15 @@ +-----BEGIN RSA PRIVATE KEY----- +MIICXgIBAAKBgQDCFENGw33yGihy92pDjZQhl0C36rPJj+CvfSC8+q28hxA161QF +NUd13wuCTUcq0Qd2qsBe/2hFyc2DCJJg0h1L78+6Z4UMR7EOcpfdUE9Hf3m/hs+F +UR45uBJeDK1HSFHD8bHKD6kv8FPGfJTotc+2xjJwoYi+1hqp1fIekaxsyQIDAQAB +AoGBAJR8ZkCUvx5kzv+utdl7T5MnordT1TvoXXJGXK7ZZ+UuvMNUCdN2QPc4sBiA +QWvLw1cSKt5DsKZ8UETpYPy8pPYnnDEz2dDYiaew9+xEpubyeW2oH4Zx71wqBtOK +kqwrXa/pzdpiucRRjk6vE6YY7EBBs/g7uanVpGibOVAEsqH1AkEA7DkjVH28WDUg +f1nqvfn2Kj6CT7nIcE3jGJsZZ7zlZmBmHFDONMLUrXR/Zm3pR5m0tCmBqa5RK95u +412jt1dPIwJBANJT3v8pnkth48bQo/fKel6uEYyboRtA5/uHuHkZ6FQF7OUkGogc +mSJluOdc5t6hI1VsLn0QZEjQZMEOWr+wKSMCQQCC4kXJEsHAve77oP6HtG/IiEn7 +kpyUXRNvFsDE0czpJJBvL/aRFUJxuRK91jhjC68sA7NsKMGg5OXb5I5Jj36xAkEA +gIT7aFOYBFwGgQAQkWNKLvySgKbAZRTeLBacpHMuQdl1DfdntvAyqpAZ0lY0RKmW +G6aFKaqQfOXKCyWoUiVknQJAXrlgySFci/2ueKlIE1QqIiLSZ8V8OlpFLRnb1pzI +7U1yQXnTAEFYM560yJlzUpOb1V4cScGd365tiSMvxLOvTA== +-----END RSA PRIVATE KEY----- diff --git a/node-v0.8.14/test/fixtures/test_rsa_privkey_2.pem b/node-v0.8.14/test/fixtures/test_rsa_privkey_2.pem new file mode 100644 index 0000000..092bd85 --- /dev/null +++ b/node-v0.8.14/test/fixtures/test_rsa_privkey_2.pem @@ -0,0 +1,15 @@ +-----BEGIN RSA PRIVATE KEY----- +MIICWQIBAAKBgQCsMgRdxxEeeXscPvqFzp/6/IIdoeKSlBn7361FWZwMQUG0qCbr +XYtdXPyqp2B4GThviIqiaJZITCTY87CiV7bFvH2lmUMJLsCc3BaQ4XFQbEU5D5jN +FfP7g78MEKbCb9rEfYMI2EGwbfKRUZUrYeBadzIMHEMEHDyiBXrCohTXMQIBIwKB +gHEoLsFITRQGr/yeah1qhmMa9ms+fvKb1o+S/NXNLAgNoDTjh0o2KGHspgm+cpgQ +kszzU8nPszbS86SC4cnEnKy/g3uw3Lf55a2P8vgh1P386/PzI+Im8s6E/EpDwn/P +R2E5gqTfePl8m7r9oeIARZXysmHHgBtEm5pTUav6QvOLAkEA2arx2R/3Yb6yZ5oO +3ldZEzCBNmB6mCoczrH6jjBosb4Gj7TK+asNlbinw1gj8sgdkzAw6jGnJ2IUfftm +QMykwQJBAMqFDclCf2b9cwi82+Xg+mjlT8BEf+l5xdRrweOyjB6DmUhgeqDISJUK +JgxGr4TxIQ6DGeEWxChGzzU6utlRnnECQDf4wdi/E7oMdwSylhvqkz9y32XBCZTX +oQHzQG20rTUE+l93oeht0EsSOcSEYQPqUL9yyr/g4dbtVbn+0SabBcsCQEs4u/pL +5i2RVpzYbu77yrk/OuEDf/eiQipT6O4sX+4Tn1VlqePynp3B8N/8/11DnpBclJVu +2yTnGcNQVAeTWBsCQFMekiY/KbwAgTopqpCUg5CLNph91FVW5PIntLmd5gSj8ZJS +uNuro8CURrOe8iiI3pG9m4KkbDdOBSOMADXJojE= +-----END RSA PRIVATE KEY----- diff --git a/node-v0.8.14/test/fixtures/test_rsa_pubkey.pem b/node-v0.8.14/test/fixtures/test_rsa_pubkey.pem new file mode 100644 index 0000000..b3bbf6c --- /dev/null +++ b/node-v0.8.14/test/fixtures/test_rsa_pubkey.pem @@ -0,0 +1,6 @@ +-----BEGIN PUBLIC KEY----- +MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDCFENGw33yGihy92pDjZQhl0C3 +6rPJj+CvfSC8+q28hxA161QFNUd13wuCTUcq0Qd2qsBe/2hFyc2DCJJg0h1L78+6 +Z4UMR7EOcpfdUE9Hf3m/hs+FUR45uBJeDK1HSFHD8bHKD6kv8FPGfJTotc+2xjJw +oYi+1hqp1fIekaxsyQIDAQAB +-----END PUBLIC KEY----- diff --git a/node-v0.8.14/test/fixtures/test_rsa_pubkey_2.pem b/node-v0.8.14/test/fixtures/test_rsa_pubkey_2.pem new file mode 100644 index 0000000..eafcf73 --- /dev/null +++ b/node-v0.8.14/test/fixtures/test_rsa_pubkey_2.pem @@ -0,0 +1,5 @@ +-----BEGIN RSA PUBLIC KEY----- +MIGHAoGBAKwyBF3HER55exw++oXOn/r8gh2h4pKUGfvfrUVZnAxBQbSoJutdi11c +/KqnYHgZOG+IiqJolkhMJNjzsKJXtsW8faWZQwkuwJzcFpDhcVBsRTkPmM0V8/uD +vwwQpsJv2sR9gwjYQbBt8pFRlSth4Fp3MgwcQwQcPKIFesKiFNcxAgEj +-----END RSA PUBLIC KEY----- diff --git a/node-v0.8.14/test/fixtures/throws_error.js b/node-v0.8.14/test/fixtures/throws_error.js new file mode 100644 index 0000000..b380008 --- /dev/null +++ b/node-v0.8.14/test/fixtures/throws_error.js @@ -0,0 +1,22 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +throw new Error('blah'); diff --git a/node-v0.8.14/test/fixtures/throws_error1.js b/node-v0.8.14/test/fixtures/throws_error1.js new file mode 100644 index 0000000..b380008 --- /dev/null +++ b/node-v0.8.14/test/fixtures/throws_error1.js @@ -0,0 +1,22 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +throw new Error('blah'); diff --git a/node-v0.8.14/test/fixtures/throws_error2.js b/node-v0.8.14/test/fixtures/throws_error2.js new file mode 100644 index 0000000..e1b3a69 --- /dev/null +++ b/node-v0.8.14/test/fixtures/throws_error2.js @@ -0,0 +1,24 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + +JSON.parse(undefined); + diff --git a/node-v0.8.14/test/fixtures/throws_error3.js b/node-v0.8.14/test/fixtures/throws_error3.js new file mode 100644 index 0000000..a53084c --- /dev/null +++ b/node-v0.8.14/test/fixtures/throws_error3.js @@ -0,0 +1,24 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +process.nextTick(function() { + JSON.parse(undefined); +}); diff --git a/node-v0.8.14/test/fixtures/utf8-bom.js b/node-v0.8.14/test/fixtures/utf8-bom.js new file mode 100644 index 0000000..0a6f80d --- /dev/null +++ b/node-v0.8.14/test/fixtures/utf8-bom.js @@ -0,0 +1 @@ +module.exports = 42; diff --git a/node-v0.8.14/test/fixtures/utf8-bom.json b/node-v0.8.14/test/fixtures/utf8-bom.json new file mode 100644 index 0000000..68264e1 --- /dev/null +++ b/node-v0.8.14/test/fixtures/utf8-bom.json @@ -0,0 +1 @@ +42 diff --git a/node-v0.8.14/test/fixtures/x.txt b/node-v0.8.14/test/fixtures/x.txt new file mode 100644 index 0000000..cd470e6 --- /dev/null +++ b/node-v0.8.14/test/fixtures/x.txt @@ -0,0 +1 @@ +xyz diff --git a/node-v0.8.14/test/gc/test-http-client-connaborted.js b/node-v0.8.14/test/gc/test-http-client-connaborted.js new file mode 100644 index 0000000..80ac055 --- /dev/null +++ b/node-v0.8.14/test/gc/test-http-client-connaborted.js @@ -0,0 +1,64 @@ +// just like test/gc/http-client.js, +// but aborting every connection that comes in. + +function serverHandler(req, res) { + res.connection.destroy(); +} + +var http = require('http'), + weak = require('weak'), + done = 0, + count = 0, + countGC = 0, + todo = 500, + common = require('../common.js'), + assert = require('assert'), + PORT = common.PORT; + +console.log('We should do '+ todo +' requests'); + +var http = require('http'); +var server = http.createServer(serverHandler); +server.listen(PORT, getall); + +function getall() { + for (var i = 0; i < todo; i++) { + (function(){ + function cb(res) { + done+=1; + statusLater(); + } + + var req = http.get({ + hostname: 'localhost', + pathname: '/', + port: PORT + }, cb).on('error', cb); + + count++; + weak(req, afterGC); + })() + } +} + +function afterGC(){ + countGC ++; +} + +var timer; +function statusLater() { + gc(); + if (timer) clearTimeout(timer); + timer = setTimeout(status, 1); +} + +function status() { + gc(); + console.log('Done: %d/%d', done, todo); + console.log('Collected: %d/%d', countGC, count); + if (done === todo) { + console.log('All should be collected now.'); + assert(count === countGC); + process.exit(0); + } +} diff --git a/node-v0.8.14/test/gc/test-http-client-onerror.js b/node-v0.8.14/test/gc/test-http-client-onerror.js new file mode 100644 index 0000000..6bea7c0 --- /dev/null +++ b/node-v0.8.14/test/gc/test-http-client-onerror.js @@ -0,0 +1,69 @@ +// just like test/gc/http-client.js, +// but with an on('error') handler that does nothing. + +function serverHandler(req, res) { + res.writeHead(200, {'Content-Type': 'text/plain'}); + res.end('Hello World\n'); +} + +var http = require('http'), + weak = require('weak'), + done = 0, + count = 0, + countGC = 0, + todo = 500, + common = require('../common.js'), + assert = require('assert'), + PORT = common.PORT; + +console.log('We should do '+ todo +' requests'); + +var http = require('http'); +var server = http.createServer(serverHandler); +server.listen(PORT, getall); + +function getall() { + for (var i = 0; i < todo; i++) { + (function(){ + function cb(res) { + done+=1; + statusLater(); + } + function onerror(er) { + throw er; + } + + var req = http.get({ + hostname: 'localhost', + pathname: '/', + port: PORT + }, cb).on('error', onerror); + + count++; + weak(req, afterGC); + })() + } +} + +function afterGC(){ + countGC ++; +} + +var timer; +function statusLater() { + gc(); + if (timer) clearTimeout(timer); + timer = setTimeout(status, 1); +} + +function status() { + gc(); + console.log('Done: %d/%d', done, todo); + console.log('Collected: %d/%d', countGC, count); + if (done === todo) { + console.log('All should be collected now.'); + assert(count === countGC); + process.exit(0); + } +} + diff --git a/node-v0.8.14/test/gc/test-http-client-timeout.js b/node-v0.8.14/test/gc/test-http-client-timeout.js new file mode 100644 index 0000000..6d705b4 --- /dev/null +++ b/node-v0.8.14/test/gc/test-http-client-timeout.js @@ -0,0 +1,72 @@ +// just like test/gc/http-client.js, +// but with a timeout set + +function serverHandler(req, res) { + setTimeout(function () { + res.writeHead(200) + res.end('hello\n'); + }, 100); +} + +var http = require('http'), + weak = require('weak'), + done = 0, + count = 0, + countGC = 0, + todo = 550, + common = require('../common.js'), + assert = require('assert'), + PORT = common.PORT; + +console.log('We should do '+ todo +' requests'); + +var http = require('http'); +var server = http.createServer(serverHandler); +server.listen(PORT, getall); + +function getall() { + for (var i = 0; i < todo; i++) { + (function(){ + function cb() { + done+=1; + statusLater(); + } + + var req = http.get({ + hostname: 'localhost', + pathname: '/', + port: PORT + }, cb); + req.on('error', cb); + req.setTimeout(10, function(){ + console.log('timeout (expected)') + }); + + count++; + weak(req, afterGC); + })() + } +} + +function afterGC(){ + countGC ++; +} + +var timer; +function statusLater() { + gc(); + if (timer) clearTimeout(timer); + timer = setTimeout(status, 1); +} + +function status() { + gc(); + console.log('Done: %d/%d', done, todo); + console.log('Collected: %d/%d', countGC, count); + if (done === todo) { + console.log('All should be collected now.'); + assert(count === countGC); + process.exit(0); + } +} + diff --git a/node-v0.8.14/test/gc/test-http-client.js b/node-v0.8.14/test/gc/test-http-client.js new file mode 100644 index 0000000..33be9ea --- /dev/null +++ b/node-v0.8.14/test/gc/test-http-client.js @@ -0,0 +1,67 @@ +// just a simple http server and client. + +function serverHandler(req, res) { + res.writeHead(200, {'Content-Type': 'text/plain'}); + res.end('Hello World\n'); +} + +var http = require('http'), + weak = require('weak'), + done = 0, + count = 0, + countGC = 0, + todo = 500, + common = require('../common.js'), + assert = require('assert'), + PORT = common.PORT; + +console.log('We should do '+ todo +' requests'); + +var http = require('http'); +var server = http.createServer(serverHandler); +server.listen(PORT, getall); + + +function getall() { + for (var i = 0; i < todo; i++) { + (function(){ + function cb(res) { + console.error('in cb') + done+=1; + res.on('end', statusLater); + } + + var req = http.get({ + hostname: 'localhost', + pathname: '/', + port: PORT + }, cb) + + count++; + weak(req, afterGC); + })() + } +} + +function afterGC(){ + countGC ++; +} + +var timer; +function statusLater() { + gc(); + if (timer) clearTimeout(timer); + timer = setTimeout(status, 1); +} + +function status() { + gc(); + console.log('Done: %d/%d', done, todo); + console.log('Collected: %d/%d', countGC, count); + if (done === todo) { + console.log('All should be collected now.'); + assert(count === countGC); + process.exit(0); + } +} + diff --git a/node-v0.8.14/test/gc/test-net-timeout.js b/node-v0.8.14/test/gc/test-net-timeout.js new file mode 100644 index 0000000..91d314b --- /dev/null +++ b/node-v0.8.14/test/gc/test-net-timeout.js @@ -0,0 +1,69 @@ +// just like test/gc/http-client-timeout.js, +// but using a net server/client instead + +function serverHandler(sock) { + sock.setTimeout(120000); + setTimeout(function () { + sock.end('hello\n'); + }, 100); +} + +var net = require('net'), + weak = require('weak'), + done = 0, + count = 0, + countGC = 0, + todo = 500, + common = require('../common.js'), + assert = require('assert'), + PORT = common.PORT; + +console.log('We should do '+ todo +' requests'); + +var server = net.createServer(serverHandler); +server.listen(PORT, getall); + +function getall() { + for (var i = 0; i < todo; i++) { + (function(){ + var req = net.connect(PORT, '127.0.0.1'); + req.setTimeout(10, function() { + console.log('timeout (expected)') + req.destroy(); + done++; + statusLater(); + }); + + count++; + weak(req, afterGC); + })(); + } +} + +function afterGC(){ + countGC ++; +} + +var timer; +function statusLater() { + gc(); + if (timer) clearTimeout(timer); + timer = setTimeout(status, 1); +} + +function status() { + gc(); + console.log('Done: %d/%d', done, todo); + console.log('Collected: %d/%d', countGC, count); + if (done === todo) { + /* Give libuv some time to make close callbacks. */ + setTimeout(function() { + gc(); + console.log('All should be collected now.'); + console.log('Collected: %d/%d', countGC, count); + assert(count === countGC); + process.exit(0); + }, 200); + } +} + diff --git a/node-v0.8.14/test/gc/testcfg.py b/node-v0.8.14/test/gc/testcfg.py new file mode 100644 index 0000000..30f3bdb --- /dev/null +++ b/node-v0.8.14/test/gc/testcfg.py @@ -0,0 +1,133 @@ +# Copyright 2008 the V8 project authors. All rights reserved. +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above +# copyright notice, this list of conditions and the following +# disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of Google Inc. nor the names of its +# contributors may be used to endorse or promote products derived +# from this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +import test +import os +import shutil +from shutil import rmtree +from os import mkdir +from glob import glob +from os.path import join, dirname, exists +import re + + +FLAGS_PATTERN = re.compile(r"//\s+Flags:(.*)") +FILES_PATTERN = re.compile(r"//\s+Files:(.*)") + + +class GCTestCase(test.TestCase): + + def __init__(self, path, file, mode, context, config): + super(GCTestCase, self).__init__(context, path, mode) + self.file = file + self.config = config + self.mode = mode + self.tmpdir = join(dirname(self.config.root), 'tmp') + + def AfterRun(self, result): + # delete the whole tmp dir + try: + rmtree(self.tmpdir) + except: + pass + # make it again. + try: + mkdir(self.tmpdir) + except: + pass + + def BeforeRun(self): + # delete the whole tmp dir + try: + rmtree(self.tmpdir) + except: + pass + # make it again. + # intermittently fails on win32, so keep trying + while not os.path.exists(self.tmpdir): + try: + mkdir(self.tmpdir) + except: + pass + + def GetLabel(self): + return "%s %s" % (self.mode, self.GetName()) + + def GetName(self): + return self.path[-1] + + def GetCommand(self): + result = [self.config.context.GetVm(self.mode)] + source = open(self.file).read() + flags_match = FLAGS_PATTERN.search(source) + if flags_match: + result += flags_match.group(1).strip().split() + files_match = FILES_PATTERN.search(source); + additional_files = [] + if files_match: + additional_files += files_match.group(1).strip().split() + for a_file in additional_files: + result.append(join(dirname(self.config.root), '..', a_file)) + result += ["--expose-gc"] + result += [self.file] + return result + + def GetSource(self): + return open(self.file).read() + + +class GCTestConfiguration(test.TestConfiguration): + + def __init__(self, context, root): + super(GCTestConfiguration, self).__init__(context, root) + + def Ls(self, path): + def SelectTest(name): + return name.startswith('test-') and name.endswith('.js') + return [f[:-3] for f in os.listdir(path) if SelectTest(f)] + + def ListTests(self, current_path, path, mode): + all_tests = [current_path + [t] for t in self.Ls(join(self.root))] + result = [] + for test in all_tests: + if self.Contains(path, test): + file_path = join(self.root, reduce(join, test[1:], "") + ".js") + result.append(GCTestCase(test, file_path, mode, self.context, self)) + return result + + def GetBuildRequirements(self): + return ['sample', 'sample=shell'] + + def GetTestStatus(self, sections, defs): + status_file = join(self.root, 'gc.status') + if exists(status_file): + test.ReadConfigurationInto(status_file, sections, defs) + + + +def GetConfiguration(context, root): + return GCTestConfiguration(context, root) diff --git a/node-v0.8.14/test/internet/internet.status b/node-v0.8.14/test/internet/internet.status new file mode 100644 index 0000000..34aea6a --- /dev/null +++ b/node-v0.8.14/test/internet/internet.status @@ -0,0 +1 @@ +prefix internet diff --git a/node-v0.8.14/test/internet/test-dns.js b/node-v0.8.14/test/internet/test-dns.js new file mode 100644 index 0000000..a079ec8 --- /dev/null +++ b/node-v0.8.14/test/internet/test-dns.js @@ -0,0 +1,405 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'), + dns = require('dns'), + net = require('net'), + isIP = net.isIP, + isIPv4 = net.isIPv4, + isIPv6 = net.isIPv6; + +var expected = 0, + completed = 0, + running = false, + queue = []; + + +function TEST(f) { + function next() { + var f = queue.shift(); + if (f) { + running = true; + console.log(f.name); + f(done); + } + } + + function done() { + running = false; + completed++; + process.nextTick(next); + } + + expected++; + queue.push(f); + + if (!running) { + next(); + } +} + + +function checkWrap(req) { + assert.ok(typeof req === 'object'); +} + + +TEST(function test_resolve4(done) { + var req = dns.resolve4('www.google.com', function(err, ips) { + if (err) throw err; + + assert.ok(ips.length > 0); + + for (var i = 0; i < ips.length; i++) { + assert.ok(isIPv4(ips[i])); + } + + done(); + }); + + checkWrap(req); +}); + + +TEST(function test_resolve6(done) { + var req = dns.resolve6('ipv6.google.com', function(err, ips) { + if (err) throw err; + + assert.ok(ips.length > 0); + + for (var i = 0; i < ips.length; i++) { + assert.ok(isIPv6(ips[i])); + } + + done(); + }); + + checkWrap(req); +}); + + +TEST(function test_reverse_ipv4(done) { + var req = dns.reverse('8.8.8.8', function(err, domains) { + if (err) throw err; + + assert.ok(domains.length > 0); + + for (var i = 0; i < domains.length; i++) { + assert.ok(domains[i]); + assert.ok(typeof domains[i] === 'string'); + } + + done(); + }); + + checkWrap(req); +}); + + +TEST(function test_reverse_ipv6(done) { + var req = dns.reverse('2001:4860:4860::8888', function(err, domains) { + if (err) throw err; + + assert.ok(domains.length > 0); + + for (var i = 0; i < domains.length; i++) { + assert.ok(domains[i]); + assert.ok(typeof domains[i] === 'string'); + } + + done(); + }); + + checkWrap(req); +}); + + +TEST(function test_reverse_bogus(done) { + var error; + + try { + var req = dns.reverse('bogus ip', function() { + assert.ok(false); + }); + } catch (e) { + error = e; + } + + assert.ok(error instanceof Error); + assert.strictEqual(error.errno, 'ENOTIMP'); + + done(); +}); + + +TEST(function test_resolveMx(done) { + var req = dns.resolveMx('gmail.com', function(err, result) { + if (err) throw err; + + assert.ok(result.length > 0); + + for (var i = 0; i < result.length; i++) { + var item = result[i]; + assert.ok(item); + assert.ok(typeof item === 'object'); + + assert.ok(item.exchange); + assert.ok(typeof item.exchange === 'string'); + + assert.ok(typeof item.priority === 'number'); + } + + done(); + }); + + checkWrap(req); +}); + + +TEST(function test_resolveNs(done) { + var req = dns.resolveNs('rackspace.com', function(err, names) { + if (err) throw err; + + assert.ok(names.length > 0); + + for (var i = 0; i < names.length; i++) { + var name = names[i]; + assert.ok(name); + assert.ok(typeof name === 'string'); + } + + done(); + }); + + checkWrap(req); +}); + + +TEST(function test_resolveSrv(done) { + var req = dns.resolveSrv('_jabber._tcp.google.com', function(err, result) { + if (err) throw err; + + assert.ok(result.length > 0); + + for (var i = 0; i < result.length; i++) { + var item = result[i]; + assert.ok(item); + assert.ok(typeof item === 'object'); + + assert.ok(item.name); + assert.ok(typeof item.name === 'string'); + + assert.ok(typeof item.port === 'number'); + assert.ok(typeof item.priority === 'number'); + assert.ok(typeof item.weight === 'number'); + } + + done(); + }); + + checkWrap(req); +}); + + +TEST(function test_resolveCname(done) { + var req = dns.resolveCname('www.microsoft.com', function(err, names) { + if (err) throw err; + + assert.ok(names.length > 0); + + for (var i = 0; i < names.length; i++) { + var name = names[i]; + assert.ok(name); + assert.ok(typeof name === 'string'); + } + + done(); + }); + + checkWrap(req); +}); + + +TEST(function test_resolveTxt(done) { + var req = dns.resolveTxt('google.com', function(err, records) { + if (err) throw err; + assert.equal(records.length, 1); + assert.equal(records[0].indexOf('v=spf1'), 0); + done(); + }); + + checkWrap(req); +}); + + +TEST(function test_lookup_ipv4_explicit(done) { + var req = dns.lookup('www.google.com', 4, function(err, ip, family) { + if (err) throw err; + assert.ok(net.isIPv4(ip)); + assert.strictEqual(family, 4); + + done(); + }); + + checkWrap(req); +}); + + +TEST(function test_lookup_ipv4_implicit(done) { + var req = dns.lookup('www.google.com', function(err, ip, family) { + if (err) throw err; + assert.ok(net.isIPv4(ip)); + assert.strictEqual(family, 4); + + done(); + }); + + checkWrap(req); +}); + + +TEST(function test_lookup_ipv6_explicit(done) { + var req = dns.lookup('ipv6.google.com', 6, function(err, ip, family) { + if (err) throw err; + assert.ok(net.isIPv6(ip)); + assert.strictEqual(family, 6); + + done(); + }); + + checkWrap(req); +}); + + +TEST(function test_lookup_ipv6_implicit(done) { + var req = dns.lookup('ipv6.google.com', function(err, ip, family) { + if (err) throw err; + assert.ok(net.isIPv6(ip)); + assert.strictEqual(family, 6); + + done(); + }); + + checkWrap(req); +}); + + +TEST(function test_lookup_failure(done) { + var req = dns.lookup('does.not.exist', 4, function(err, ip, family) { + assert.ok(err instanceof Error); + assert.strictEqual(err.errno, dns.NOTFOUND); + assert.strictEqual(err.errno, 'ENOTFOUND'); + + done(); + }); + + checkWrap(req); +}); + + +TEST(function test_lookup_null(done) { + var req = dns.lookup(null, function(err, ip, family) { + if (err) throw err; + assert.strictEqual(ip, null); + assert.strictEqual(family, 4); + + done(); + }); + + checkWrap(req); +}); + + +TEST(function test_lookup_ip_ipv4(done) { + var req = dns.lookup('127.0.0.1', function(err, ip, family) { + if (err) throw err; + assert.strictEqual(ip, '127.0.0.1'); + assert.strictEqual(family, 4); + + done(); + }); + + checkWrap(req); +}); + + +TEST(function test_lookup_ip_ipv6(done) { + var req = dns.lookup('::1', function(err, ip, family) { + if (err) throw err; + assert.ok(net.isIPv6(ip)); + assert.strictEqual(family, 6); + + done(); + }); + + checkWrap(req); +}); + + +TEST(function test_lookup_localhost_ipv4(done) { + var req = dns.lookup('localhost', 4, function(err, ip, family) { + if (err) throw err; + assert.strictEqual(ip, '127.0.0.1'); + assert.strictEqual(family, 4); + + done(); + }); + + checkWrap(req); +}); + + +/* Disabled because it appears to be not working on linux. */ +/* TEST(function test_lookup_localhost_ipv6(done) { + var req = dns.lookup('localhost', 6, function(err, ip, family) { + if (err) throw err; + assert.ok(net.isIPv6(ip)); + assert.strictEqual(family, 6); + + done(); + }); + + checkWrap(req); +}); */ + + +var getaddrinfoCallbackCalled = false; + +console.log('looking up nodejs.org...'); +var req = process.binding('cares_wrap').getaddrinfo('nodejs.org'); + +req.oncomplete = function(domains) { + console.log('nodejs.org = ', domains); + assert.ok(Array.isArray(domains)); + assert.ok(domains.length >= 1); + assert.ok(typeof domains[0] == 'string'); + getaddrinfoCallbackCalled = true; +}; + + + +process.on('exit', function() { + console.log(completed + ' tests completed'); + assert.equal(running, false); + assert.strictEqual(expected, completed); + assert.ok(getaddrinfoCallbackCalled); +}); diff --git a/node-v0.8.14/test/internet/testcfg.py b/node-v0.8.14/test/internet/testcfg.py new file mode 100644 index 0000000..3e3e900 --- /dev/null +++ b/node-v0.8.14/test/internet/testcfg.py @@ -0,0 +1,132 @@ +# Copyright 2008 the V8 project authors. All rights reserved. +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above +# copyright notice, this list of conditions and the following +# disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of Google Inc. nor the names of its +# contributors may be used to endorse or promote products derived +# from this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +import test +import os +import shutil +from shutil import rmtree +from os import mkdir +from glob import glob +from os.path import join, dirname, exists +import re + + +FLAGS_PATTERN = re.compile(r"//\s+Flags:(.*)") +FILES_PATTERN = re.compile(r"//\s+Files:(.*)") + + +class InternetTestCase(test.TestCase): + + def __init__(self, path, file, mode, context, config): + super(InternetTestCase, self).__init__(context, path, mode) + self.file = file + self.config = config + self.mode = mode + self.tmpdir = join(dirname(self.config.root), 'tmp') + + def AfterRun(self, result): + # delete the whole tmp dir + try: + rmtree(self.tmpdir) + except: + pass + # make it again. + try: + mkdir(self.tmpdir) + except: + pass + + def BeforeRun(self): + # delete the whole tmp dir + try: + rmtree(self.tmpdir) + except: + pass + # make it again. + # intermittently fails on win32, so keep trying + while not os.path.exists(self.tmpdir): + try: + mkdir(self.tmpdir) + except: + pass + + def GetLabel(self): + return "%s %s" % (self.mode, self.GetName()) + + def GetName(self): + return self.path[-1] + + def GetCommand(self): + result = [self.config.context.GetVm(self.mode)] + source = open(self.file).read() + flags_match = FLAGS_PATTERN.search(source) + if flags_match: + result += flags_match.group(1).strip().split() + files_match = FILES_PATTERN.search(source); + additional_files = [] + if files_match: + additional_files += files_match.group(1).strip().split() + for a_file in additional_files: + result.append(join(dirname(self.config.root), '..', a_file)) + result += [self.file] + return result + + def GetSource(self): + return open(self.file).read() + + +class InternetTestConfiguration(test.TestConfiguration): + + def __init__(self, context, root): + super(InternetTestConfiguration, self).__init__(context, root) + + def Ls(self, path): + def SelectTest(name): + return name.startswith('test-') and name.endswith('.js') + return [f[:-3] for f in os.listdir(path) if SelectTest(f)] + + def ListTests(self, current_path, path, mode): + all_tests = [current_path + [t] for t in self.Ls(join(self.root))] + result = [] + for test in all_tests: + if self.Contains(path, test): + file_path = join(self.root, reduce(join, test[1:], "") + ".js") + result.append(InternetTestCase(test, file_path, mode, self.context, self)) + return result + + def GetBuildRequirements(self): + return ['sample', 'sample=shell'] + + def GetTestStatus(self, sections, defs): + status_file = join(self.root, 'simple.status') + if exists(status_file): + test.ReadConfigurationInto(status_file, sections, defs) + + + +def GetConfiguration(context, root): + return InternetTestConfiguration(context, root) diff --git a/node-v0.8.14/test/message/2100bytes.js b/node-v0.8.14/test/message/2100bytes.js new file mode 100644 index 0000000..ead0881 --- /dev/null +++ b/node-v0.8.14/test/message/2100bytes.js @@ -0,0 +1,73 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + + + +var common = require('../common'); +var assert = require('assert'); +var util = require('util'); + +console.log([ + '_______________________________________________50', + '______________________________________________100', + '______________________________________________150', + '______________________________________________200', + '______________________________________________250', + '______________________________________________300', + '______________________________________________350', + '______________________________________________400', + '______________________________________________450', + '______________________________________________500', + '______________________________________________550', + '______________________________________________600', + '______________________________________________650', + '______________________________________________700', + '______________________________________________750', + '______________________________________________800', + '______________________________________________850', + '______________________________________________900', + '______________________________________________950', + '_____________________________________________1000', + '_____________________________________________1050', + '_____________________________________________1100', + '_____________________________________________1150', + '_____________________________________________1200', + '_____________________________________________1250', + '_____________________________________________1300', + '_____________________________________________1350', + '_____________________________________________1400', + '_____________________________________________1450', + '_____________________________________________1500', + '_____________________________________________1550', + '_____________________________________________1600', + '_____________________________________________1650', + '_____________________________________________1700', + '_____________________________________________1750', + '_____________________________________________1800', + '_____________________________________________1850', + '_____________________________________________1900', + '_____________________________________________1950', + '_____________________________________________2000', + '_____________________________________________2050', + '_____________________________________________2100' +].join('\n')); + diff --git a/node-v0.8.14/test/message/2100bytes.out b/node-v0.8.14/test/message/2100bytes.out new file mode 100644 index 0000000..59040cc --- /dev/null +++ b/node-v0.8.14/test/message/2100bytes.out @@ -0,0 +1,42 @@ +_______________________________________________50 +______________________________________________100 +______________________________________________150 +______________________________________________200 +______________________________________________250 +______________________________________________300 +______________________________________________350 +______________________________________________400 +______________________________________________450 +______________________________________________500 +______________________________________________550 +______________________________________________600 +______________________________________________650 +______________________________________________700 +______________________________________________750 +______________________________________________800 +______________________________________________850 +______________________________________________900 +______________________________________________950 +_____________________________________________1000 +_____________________________________________1050 +_____________________________________________1100 +_____________________________________________1150 +_____________________________________________1200 +_____________________________________________1250 +_____________________________________________1300 +_____________________________________________1350 +_____________________________________________1400 +_____________________________________________1450 +_____________________________________________1500 +_____________________________________________1550 +_____________________________________________1600 +_____________________________________________1650 +_____________________________________________1700 +_____________________________________________1750 +_____________________________________________1800 +_____________________________________________1850 +_____________________________________________1900 +_____________________________________________1950 +_____________________________________________2000 +_____________________________________________2050 +_____________________________________________2100 diff --git a/node-v0.8.14/test/message/eval_messages.js b/node-v0.8.14/test/message/eval_messages.js new file mode 100644 index 0000000..d03c0eb --- /dev/null +++ b/node-v0.8.14/test/message/eval_messages.js @@ -0,0 +1,53 @@ + +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); + +var spawn = require('child_process').spawn; + +function run(cmd, strict, cb) { + var args = []; + if (strict) args.push('--use_strict'); + args.push('-pe', cmd); + var child = spawn(process.execPath, args); + child.stdout.pipe(process.stdout); + child.stderr.pipe(process.stdout); + child.on('close', cb); +} + +var queue = + [ 'with(this){__filename}', + '42', + 'throw new Error("hello")', + 'var x = 100; y = x;', + 'var ______________________________________________; throw 10' ]; + +function go() { + var c = queue.shift(); + if (!c) return console.log('done'); + run(c, false, function() { + run(c, true, go); + }); +} + +go(); diff --git a/node-v0.8.14/test/message/eval_messages.out b/node-v0.8.14/test/message/eval_messages.out new file mode 100644 index 0000000..378fe94 --- /dev/null +++ b/node-v0.8.14/test/message/eval_messages.out @@ -0,0 +1,58 @@ +[eval] + +[eval]:1 +with(this){__filename} +^^^^ +SyntaxError: Strict mode code may not include a with statement + at Object. ([eval]-wrapper:*:*) + at Module._compile (module.js:*:*) + at evalScript (node.js:*:*) + at startup (node.js:*:*) + at node.js:*:* +42 +42 + +[eval]:1 +throw new Error("hello") + ^ +Error: hello + at [eval]:1:7 + at Object. ([eval]-wrapper:*:*) + at Module._compile (module.js:*:*) + at evalScript (node.js:*:*) + at startup (node.js:*:*) + at node.js:*:* + +[eval]:1 +throw new Error("hello") + ^ +Error: hello + at [eval]:1:7 + at Object. ([eval]-wrapper:*:*) + at Module._compile (module.js:*:*) + at evalScript (node.js:*:*) + at startup (node.js:*:*) + at node.js:*:* +100 + +[eval]:1 +var x = 100; y = x; + ^ +ReferenceError: y is not defined + at [eval]:1:16 + at Object. ([eval]-wrapper:*:*) + at Module._compile (module.js:*:*) + at evalScript (node.js:*:*) + at startup (node.js:*:*) + at node.js:*:* + +[eval]:1 +var ______________________________________________; throw 10 + ^ +10 + +[eval]:1 +var ______________________________________________; throw 10 + ^ +10 +done diff --git a/node-v0.8.14/test/message/hello_world.js b/node-v0.8.14/test/message/hello_world.js new file mode 100644 index 0000000..6f216f9 --- /dev/null +++ b/node-v0.8.14/test/message/hello_world.js @@ -0,0 +1,28 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + + + +var common = require('../common'); +var assert = require('assert'); + +console.log('hello world'); diff --git a/node-v0.8.14/test/message/hello_world.out b/node-v0.8.14/test/message/hello_world.out new file mode 100644 index 0000000..3b18e51 --- /dev/null +++ b/node-v0.8.14/test/message/hello_world.out @@ -0,0 +1 @@ +hello world diff --git a/node-v0.8.14/test/message/stack_overflow.js b/node-v0.8.14/test/message/stack_overflow.js new file mode 100644 index 0000000..91974be --- /dev/null +++ b/node-v0.8.14/test/message/stack_overflow.js @@ -0,0 +1,36 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + + + +var common = require('../common'); +var assert = require('assert'); + +common.error('before'); + +// stack overflow +function stackOverflow() { + stackOverflow(); +} +stackOverflow(); + +common.error('after'); diff --git a/node-v0.8.14/test/message/stack_overflow.out b/node-v0.8.14/test/message/stack_overflow.out new file mode 100644 index 0000000..72dc019 --- /dev/null +++ b/node-v0.8.14/test/message/stack_overflow.out @@ -0,0 +1,6 @@ +before + +*test*message*stack_overflow.js:31 +function stackOverflow() { + ^ +RangeError: Maximum call stack size exceeded diff --git a/node-v0.8.14/test/message/stdin_messages.js b/node-v0.8.14/test/message/stdin_messages.js new file mode 100644 index 0000000..b1eaf47 --- /dev/null +++ b/node-v0.8.14/test/message/stdin_messages.js @@ -0,0 +1,54 @@ + +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); + +var spawn = require('child_process').spawn; + +function run(cmd, strict, cb) { + var args = []; + if (strict) args.push('--use_strict'); + args.push('-p'); + var child = spawn(process.execPath, args); + child.stdout.pipe(process.stdout); + child.stderr.pipe(process.stdout); + child.stdin.end(cmd); + child.on('close', cb); +} + +var queue = + [ 'with(this){__filename}', + '42', + 'throw new Error("hello")', + 'var x = 100; y = x;', + 'var ______________________________________________; throw 10' ]; + +function go() { + var c = queue.shift(); + if (!c) return console.log('done'); + run(c, false, function() { + run(c, true, go); + }); +} + +go(); diff --git a/node-v0.8.14/test/message/stdin_messages.out b/node-v0.8.14/test/message/stdin_messages.out new file mode 100644 index 0000000..7cdd79e --- /dev/null +++ b/node-v0.8.14/test/message/stdin_messages.out @@ -0,0 +1,62 @@ +[stdin] + +[stdin]:1 +with(this){__filename} +^^^^ +SyntaxError: Strict mode code may not include a with statement + at Object. ([stdin]-wrapper:*:*) + at Module._compile (module.js:*:*) + at evalScript (node.js:*:*) + at Socket. (node.js:*:*) + at Socket.EventEmitter.emit (events.js:*:*) + at Pipe.onread (net.js:*:*) +42 +42 + +[stdin]:1 +throw new Error("hello") + ^ +Error: hello + at [stdin]:1:7 + at Object. ([stdin]-wrapper:*:*) + at Module._compile (module.js:*:*) + at evalScript (node.js:*:*) + at Socket. (node.js:*:*) + at Socket.EventEmitter.emit (events.js:*:*) + at Pipe.onread (net.js:*:*) + +[stdin]:1 +throw new Error("hello") + ^ +Error: hello + at [stdin]:1:7 + at Object. ([stdin]-wrapper:*:*) + at Module._compile (module.js:*:*) + at evalScript (node.js:*:*) + at Socket. (node.js:*:*) + at Socket.EventEmitter.emit (events.js:*:*) + at Pipe.onread (net.js:*:*) +100 + +[stdin]:1 +var x = 100; y = x; + ^ +ReferenceError: y is not defined + at [stdin]:1:16 + at Object. ([stdin]-wrapper:*:*) + at Module._compile (module.js:*:*) + at evalScript (node.js:*:*) + at Socket. (node.js:*:*) + at Socket.EventEmitter.emit (events.js:*:*) + at Pipe.onread (net.js:*:*) + +[stdin]:1 +var ______________________________________________; throw 10 + ^ +10 + +[stdin]:1 +var ______________________________________________; throw 10 + ^ +10 +done diff --git a/node-v0.8.14/test/message/testcfg.py b/node-v0.8.14/test/message/testcfg.py new file mode 100644 index 0000000..105fac6 --- /dev/null +++ b/node-v0.8.14/test/message/testcfg.py @@ -0,0 +1,145 @@ +# Copyright 2008 the V8 project authors. All rights reserved. +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above +# copyright notice, this list of conditions and the following +# disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of Google Inc. nor the names of its +# contributors may be used to endorse or promote products derived +# from this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +import test +import os +from os.path import join, dirname, exists, basename, isdir +import re + +FLAGS_PATTERN = re.compile(r"//\s+Flags:(.*)") + +class MessageTestCase(test.TestCase): + + def __init__(self, path, file, expected, mode, context, config): + super(MessageTestCase, self).__init__(context, path, mode) + self.file = file + self.expected = expected + self.config = config + self.mode = mode + + def IgnoreLine(self, str): + """Ignore empty lines and valgrind output.""" + if not str.strip(): return True + else: return str.startswith('==') or str.startswith('**') + + def IsFailureOutput(self, output): + f = file(self.expected) + # Skip initial '#' comment and spaces + #for line in f: + # if (not line.startswith('#')) and (not line.strip()): + # break + # Convert output lines to regexps that we can match + env = { 'basename': basename(self.file) } + patterns = [ ] + for line in f: + if not line.strip(): + continue + pattern = re.escape(line.rstrip() % env) + pattern = pattern.replace('\\*', '.*') + pattern = '^%s$' % pattern + patterns.append(pattern) + # Compare actual output with the expected + raw_lines = (output.stdout + output.stderr).split('\n') + outlines = [ s for s in raw_lines if not self.IgnoreLine(s) ] + if len(outlines) != len(patterns): + print "length differs." + print "expect=%d" % len(patterns) + print "actual=%d" % len(outlines) + print "patterns:" + for i in xrange(len(patterns)): + print "pattern = %s" % patterns[i] + print "outlines:" + for i in xrange(len(outlines)): + print "outline = %s" % outlines[i] + return True + for i in xrange(len(patterns)): + if not re.match(patterns[i], outlines[i]): + print "match failed" + print "line=%d" % i + print "expect=%s" % patterns[i] + print "actual=%s" % outlines[i] + return True + return False + + def GetLabel(self): + return "%s %s" % (self.mode, self.GetName()) + + def GetName(self): + return self.path[-1] + + def GetCommand(self): + result = [self.config.context.GetVm(self.mode)] + source = open(self.file).read() + flags_match = FLAGS_PATTERN.search(source) + if flags_match: + result += flags_match.group(1).strip().split() + result.append(self.file) + return result + + def GetSource(self): + return (open(self.file).read() + + "\n--- expected output ---\n" + + open(self.expected).read()) + + +class MessageTestConfiguration(test.TestConfiguration): + + def __init__(self, context, root): + super(MessageTestConfiguration, self).__init__(context, root) + + def Ls(self, path): + if isdir(path): + return [f[:-3] for f in os.listdir(path) if f.endswith('.js')] + else: + return [] + + def ListTests(self, current_path, path, mode): + all_tests = [current_path + [t] for t in self.Ls(self.root)] + result = [] + for test in all_tests: + if self.Contains(path, test): + file_prefix = join(self.root, reduce(join, test[1:], "")) + file_path = file_prefix + ".js" + output_path = file_prefix + ".out" + if not exists(output_path): + print "Could not find %s" % output_path + continue + result.append(MessageTestCase(test, file_path, output_path, mode, + self.context, self)) + return result + + def GetBuildRequirements(self): + return ['sample', 'sample=shell'] + + def GetTestStatus(self, sections, defs): + status_file = join(self.root, 'message.status') + if exists(status_file): + test.ReadConfigurationInto(status_file, sections, defs) + + +def GetConfiguration(context, root): + return MessageTestConfiguration(context, root) diff --git a/node-v0.8.14/test/message/throw_custom_error.js b/node-v0.8.14/test/message/throw_custom_error.js new file mode 100644 index 0000000..b92298d --- /dev/null +++ b/node-v0.8.14/test/message/throw_custom_error.js @@ -0,0 +1,33 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + + + +var common = require('../common'); +var assert = require('assert'); + +common.error('before'); + +// custom error throwing +throw ({ name: 'MyCustomError', message: 'This is a custom message' }); + +common.error('after'); diff --git a/node-v0.8.14/test/message/throw_custom_error.out b/node-v0.8.14/test/message/throw_custom_error.out new file mode 100644 index 0000000..e8c9903 --- /dev/null +++ b/node-v0.8.14/test/message/throw_custom_error.out @@ -0,0 +1,6 @@ +before + +*test*message*throw_custom_error.js:31 +throw ({ name: 'MyCustomError', message: 'This is a custom message' }); +^ +MyCustomError: This is a custom message diff --git a/node-v0.8.14/test/message/throw_in_line_with_tabs.js b/node-v0.8.14/test/message/throw_in_line_with_tabs.js new file mode 100644 index 0000000..f01bc0e --- /dev/null +++ b/node-v0.8.14/test/message/throw_in_line_with_tabs.js @@ -0,0 +1,35 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + + + +var common = require('../common'); +var assert = require('assert'); + +common.error('before'); + +(function () { + // these lines should contain tab! + throw ({ foo: 'bar' }); +})(); + +common.error('after'); diff --git a/node-v0.8.14/test/message/throw_in_line_with_tabs.out b/node-v0.8.14/test/message/throw_in_line_with_tabs.out new file mode 100644 index 0000000..d91f8c0 --- /dev/null +++ b/node-v0.8.14/test/message/throw_in_line_with_tabs.out @@ -0,0 +1,6 @@ +before + +*test*message*throw_in_line_with_tabs.js:32 + throw ({ foo: 'bar' }); + ^ +[object Object] diff --git a/node-v0.8.14/test/message/throw_non_error.js b/node-v0.8.14/test/message/throw_non_error.js new file mode 100644 index 0000000..defa079 --- /dev/null +++ b/node-v0.8.14/test/message/throw_non_error.js @@ -0,0 +1,33 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + + + +var common = require('../common'); +var assert = require('assert'); + +common.error('before'); + +// custom error throwing +throw ({ foo: 'bar' }); + +common.error('after'); diff --git a/node-v0.8.14/test/message/throw_non_error.out b/node-v0.8.14/test/message/throw_non_error.out new file mode 100644 index 0000000..378874f --- /dev/null +++ b/node-v0.8.14/test/message/throw_non_error.out @@ -0,0 +1,6 @@ +before + +*test*message*throw_non_error.js:31 +throw ({ foo: 'bar' }); +^ +[object Object] diff --git a/node-v0.8.14/test/message/undefined_reference_in_new_context.js b/node-v0.8.14/test/message/undefined_reference_in_new_context.js new file mode 100644 index 0000000..cdd232d --- /dev/null +++ b/node-v0.8.14/test/message/undefined_reference_in_new_context.js @@ -0,0 +1,36 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + + + +var common = require('../common'); +var assert = require('assert'); + +common.error('before'); + +var Script = process.binding('evals').NodeScript; + +// undefined reference +script = new Script('foo.bar = 5;'); +script.runInNewContext(); + +common.error('after'); diff --git a/node-v0.8.14/test/message/undefined_reference_in_new_context.out b/node-v0.8.14/test/message/undefined_reference_in_new_context.out new file mode 100644 index 0000000..f4e9b5c --- /dev/null +++ b/node-v0.8.14/test/message/undefined_reference_in_new_context.out @@ -0,0 +1,14 @@ +before + +*test*message*undefined_reference_in_new_context.js:34 +script.runInNewContext(); + ^ +ReferenceError: foo is not defined + at evalmachine.:* + at Object. (*test*message*undefined_reference_in_new_context.js:*) + at Module._compile (module.js:*) + at *..js (module.js:*) + at Module.load (module.js:*) + at *._load (module.js:*) + at Module.runMain (module.js:*) + at *._tickCallback (node.js:*) diff --git a/node-v0.8.14/test/pummel/pummel.status b/node-v0.8.14/test/pummel/pummel.status new file mode 100644 index 0000000..87224bb --- /dev/null +++ b/node-v0.8.14/test/pummel/pummel.status @@ -0,0 +1 @@ +prefix pummel diff --git a/node-v0.8.14/test/pummel/test-buffer-big.js b/node-v0.8.14/test/pummel/test-buffer-big.js new file mode 100644 index 0000000..8a26c4e --- /dev/null +++ b/node-v0.8.14/test/pummel/test-buffer-big.js @@ -0,0 +1,29 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); + +// The tests below should throw an error, not abort the process... +assert.throws(function() { new Buffer(0x3fffffff + 1) }, RangeError); +assert.throws(function() { new Int8Array(0x3fffffff + 1) }, RangeError); +assert.throws(function() { new ArrayBuffer(0x3fffffff + 1) }, RangeError); +assert.throws(function() { new Float64Array(0x7ffffff + 1) }, RangeError); diff --git a/node-v0.8.14/test/pummel/test-child-process-spawn-loop.js b/node-v0.8.14/test/pummel/test-child-process-spawn-loop.js new file mode 100644 index 0000000..631d9fc --- /dev/null +++ b/node-v0.8.14/test/pummel/test-child-process-spawn-loop.js @@ -0,0 +1,64 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + + + +var common = require('../common'); +var assert = require('assert'); + +var spawn = require('child_process').spawn; + +var is_windows = process.platform === 'win32'; + +var SIZE = 1000 * 1024; +var N = 40; +var finished = false; + +function doSpawn(i) { + var child = spawn('python', ['-c', 'print ' + SIZE + ' * "C"']); + var count = 0; + + child.stdout.setEncoding('ascii'); + child.stdout.on('data', function(chunk) { + count += chunk.length; + }); + + child.stderr.on('data', function(chunk) { + console.log('stderr: ' + chunk); + }); + + child.on('close', function() { + // + 1 for \n or + 2 for \r\n on Windows + assert.equal(SIZE + (is_windows ? 2 : 1), count); + if (i < N) { + doSpawn(i + 1); + } else { + finished = true; + } + }); +} + +doSpawn(0); + +process.on('exit', function() { + assert.ok(finished); +}); diff --git a/node-v0.8.14/test/pummel/test-crypto-dh.js b/node-v0.8.14/test/pummel/test-crypto-dh.js new file mode 100644 index 0000000..8637a7f --- /dev/null +++ b/node-v0.8.14/test/pummel/test-crypto-dh.js @@ -0,0 +1,70 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); + +try { + var crypto = require('crypto'); +} catch (e) { + console.log('Not compiled with OPENSSL support.'); + process.exit(); +} + +assert.throws(function() { + crypto.getDiffieHellman('unknown-group'); +}); +assert.throws(function() { + crypto.getDiffieHellman('modp1').setPrivateKey(''); +}); +assert.throws(function() { + crypto.getDiffieHellman('modp1').setPublicKey(''); +}); + +var hashes = { + modp1 : "b4b330a6ffeacfbd861e7fe2135b4431", + modp2 : "7c3c5cad8b9f378d88f1dd64a4b6413a", + modp5 : "b1d2acc22c542e08669a5c5ae812694d", + modp14 : "8d041538cecc1a7d915ba4b718f8ad20", + modp15 : "dc3b93def24e078c4fbf92d5e14ba69b", + modp16 : "a273487f46f699461f613b3878d9dfd9", + modp17 : "dc76e09935310348c492de9bd82014d0", + modp18 : "db08973bfd2371758a69db180871c993" +} + +for (var name in hashes) { + var group = crypto.getDiffieHellman(name); + var private_key = group.getPrime('hex'); + var hash1 = hashes[name]; + var hash2 = crypto.createHash('md5').update(private_key.toUpperCase()).digest('hex'); + assert.equal(hash1, hash2); + assert.equal(group.getGenerator('hex'), '02'); +} + +for (var name in hashes) { + var group1 = crypto.getDiffieHellman(name); + var group2 = crypto.getDiffieHellman(name); + group1.generateKeys(); + group2.generateKeys(); + var key1 = group1.computeSecret(group2.getPublicKey()); + var key2 = group2.computeSecret(group1.getPublicKey()); + assert.equal(key1, key2); +} diff --git a/node-v0.8.14/test/pummel/test-debugger-debug-brk.js b/node-v0.8.14/test/pummel/test-debugger-debug-brk.js new file mode 100644 index 0000000..eabef59 --- /dev/null +++ b/node-v0.8.14/test/pummel/test-debugger-debug-brk.js @@ -0,0 +1,49 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + +var common = require('../common'); +var assert = require('assert'); +var spawn = require('child_process').spawn; + +var script = common.fixturesDir + '/empty.js'; + +function fail() { + assert(0); // `node --debug-brk script.js` should not quit +} + +function test(arg) { + var child = spawn(process.execPath, [arg, script]); + child.on('exit', fail); + + // give node time to start up the debugger + setTimeout(function() { + child.removeListener('exit', fail); + child.kill(); + }, 2000); + + process.on('exit', function() { + assert(child.killed); + }); +} + +test('--debug-brk'); +test('--debug-brk=5959'); diff --git a/node-v0.8.14/test/pummel/test-dh-regr.js b/node-v0.8.14/test/pummel/test-dh-regr.js new file mode 100644 index 0000000..2e626bd --- /dev/null +++ b/node-v0.8.14/test/pummel/test-dh-regr.js @@ -0,0 +1,41 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); + +var crypto = require('crypto'); + +var p = crypto.createDiffieHellman(256).getPrime(); + +for (var i = 0; i < 2000; i++) { + var a = crypto.createDiffieHellman(p), + b = crypto.createDiffieHellman(p); + + a.generateKeys(); + b.generateKeys(); + + assert.equal( + a.computeSecret(b.getPublicKey()), + b.computeSecret(a.getPublicKey()), + 'secrets should be equal!' + ); +} diff --git a/node-v0.8.14/test/pummel/test-exec.js b/node-v0.8.14/test/pummel/test-exec.js new file mode 100644 index 0000000..6eacda7 --- /dev/null +++ b/node-v0.8.14/test/pummel/test-exec.js @@ -0,0 +1,123 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var exec = require('child_process').exec; + +if (process.platform !== 'win32') { + // Unix. + var SLEEP3_COMMAND = "sleep 3"; +} else { + // Windows: `choice` is a command built into cmd.exe. Use another cmd process + // to create a process tree, so we can catch bugs related to it. + var SLEEP3_COMMAND = "cmd /c choice /t 3 /c X /d X"; +} + + +var success_count = 0; +var error_count = 0; + + +exec(process.execPath + ' -p -e process.versions', + function(err, stdout, stderr) { + if (err) { + error_count++; + console.log('error!: ' + err.code); + console.log('stdout: ' + JSON.stringify(stdout)); + console.log('stderr: ' + JSON.stringify(stderr)); + assert.equal(false, err.killed); + } else { + success_count++; + console.dir(stdout); + } +}); + + +exec('thisisnotavalidcommand', function(err, stdout, stderr) { + if (err) { + error_count++; + assert.equal('', stdout); + assert.equal(true, err.code != 0); + assert.equal(false, err.killed); + assert.strictEqual(null, err.signal); + console.log('error code: ' + err.code); + console.log('stdout: ' + JSON.stringify(stdout)); + console.log('stderr: ' + JSON.stringify(stderr)); + } else { + success_count++; + console.dir(stdout); + assert.equal(true, stdout != ''); + } +}); + + + +var sleeperStart = new Date(); +exec(SLEEP3_COMMAND, { timeout: 50 }, function(err, stdout, stderr) { + var diff = (new Date()) - sleeperStart; + console.log('\'sleep 3\' with timeout 50 took %d ms', diff); + assert.ok(diff < 500); + assert.ok(err); + assert.ok(err.killed); + assert.equal(err.signal, 'SIGTERM'); +}); + + + + +var startSleep3 = new Date(); +var killMeTwice = exec(SLEEP3_COMMAND, {timeout: 1000}, killMeTwiceCallback); + +process.nextTick(function() { + console.log('kill pid %d', killMeTwice.pid); + // make sure there is no race condition in starting the process + // the PID SHOULD exist directly following the exec() call. + assert.equal('number', typeof killMeTwice._handle.pid); + // Kill the process + killMeTwice.kill(); +}); + +function killMeTwiceCallback(err, stdout, stderr) { + var diff = (new Date()) - startSleep3; + // We should have already killed this process. Assert that the timeout still + // works and that we are getting the proper callback parameters. + assert.ok(err); + assert.ok(err.killed); + assert.equal(err.signal, 'SIGTERM'); + + // the timeout should still be in effect + console.log('\'sleep 3\' was already killed. Took %d ms', diff); + assert.ok(diff < 1500); +} + + +exec('python -c "print 200000*\'C\'"', {maxBuffer: 1000}, + function(err, stdout, stderr) { + assert.ok(err); + assert.ok(/maxBuffer/.test(err.message)); + }); + + +process.on('exit', function() { + assert.equal(1, success_count); + assert.equal(1, error_count); +}); diff --git a/node-v0.8.14/test/pummel/test-fs-largefile.js b/node-v0.8.14/test/pummel/test-fs-largefile.js new file mode 100644 index 0000000..ffd6261 --- /dev/null +++ b/node-v0.8.14/test/pummel/test-fs-largefile.js @@ -0,0 +1,58 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + + + +var common = require('../common'); +var assert = require('assert'); +var path = require('path'), + fs = require('fs'), + filepath = path.join(common.tmpDir, 'large.txt'), + fd = fs.openSync(filepath, 'w+'), + offset = 5 * 1024 * 1024 * 1024, // 5GB + message = 'Large File'; + +fs.truncateSync(fd, offset); +assert.equal(fs.statSync(filepath).size, offset); +var writeBuf = new Buffer(message); +fs.writeSync(fd, writeBuf, 0, writeBuf.length, offset); +var readBuf = new Buffer(writeBuf.length); +fs.readSync(fd, readBuf, 0, readBuf.length, offset); +assert.equal(readBuf.toString(), message); +fs.readSync(fd, readBuf, 0, 1, 0); +assert.equal(readBuf[0], 0); + +var exceptionRaised = false; +try { + fs.writeSync(fd, writeBuf, 0, writeBuf.length, 42.000001); +} catch (err) { + console.log(err); + exceptionRaised = true; + assert.equal(err.message, 'Not an integer'); +} +assert.ok(exceptionRaised); +fs.close(fd); + +process.on('exit', function() { + fs.unlinkSync(filepath); +}); + diff --git a/node-v0.8.14/test/pummel/test-fs-watch-file-slow.js b/node-v0.8.14/test/pummel/test-fs-watch-file-slow.js new file mode 100644 index 0000000..4124e0b --- /dev/null +++ b/node-v0.8.14/test/pummel/test-fs-watch-file-slow.js @@ -0,0 +1,73 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var path = require('path'); +var fs = require('fs'); + +var FILENAME = path.join(common.tmpDir, 'watch-me'); +var TIMEOUT = 1300; + +var nevents = 0; + +try { + fs.unlinkSync(FILENAME); +} +catch (e) { + // swallow +} + +fs.watchFile(FILENAME, {interval:TIMEOUT - 250}, function(curr, prev) { + console.log([curr, prev]); + switch (++nevents) { + case 1: + case 2: + assert.equal(fs.existsSync(FILENAME), true); + break; + case 3: + assert.equal(fs.existsSync(FILENAME), false); + fs.unwatchFile(FILENAME); + break; + default: + assert(0); + } +}); + +process.on('exit', function() { + assert.equal(nevents, 3); +}); + +setTimeout(createFile, TIMEOUT); + +function createFile() { + fs.writeFileSync(FILENAME, "test"); + setTimeout(touchFile, TIMEOUT); +} + +function touchFile() { + fs.writeFileSync(FILENAME, "test"); + setTimeout(removeFile, TIMEOUT); +} + +function removeFile() { + fs.unlinkSync(FILENAME); +} diff --git a/node-v0.8.14/test/pummel/test-fs-watch-file.js b/node-v0.8.14/test/pummel/test-fs-watch-file.js new file mode 100644 index 0000000..4dddb25 --- /dev/null +++ b/node-v0.8.14/test/pummel/test-fs-watch-file.js @@ -0,0 +1,128 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var path = require('path'); +var fs = require('fs'); + +var watchSeenOne = 0; +var watchSeenTwo = 0; +var watchSeenThree = 0; + +var startDir = process.cwd(); +var testDir = common.tmpDir; + +var filenameOne = 'watch.txt'; +var filepathOne = path.join(testDir, filenameOne); + +var filenameTwo = 'hasOwnProperty'; +var filepathTwo = filenameTwo; +var filepathTwoAbs = path.join(testDir, filenameTwo); + +var filenameThree = 'charm'; // because the third time is + + +process.on('exit', function() { + fs.unlinkSync(filepathOne); + fs.unlinkSync(filepathTwoAbs); + fs.unlinkSync(filenameThree); + assert.equal(1, watchSeenOne); + assert.equal(2, watchSeenTwo); + assert.equal(1, watchSeenThree); +}); + + +fs.writeFileSync(filepathOne, 'hello'); + +assert.throws( + function() { + fs.watchFile(filepathOne); + }, + function(e) { + return e.message === 'watchFile requires a listener function'; + } +); + +assert.doesNotThrow( + function() { + fs.watchFile(filepathOne, function(curr, prev) { + fs.unwatchFile(filepathOne); + ++watchSeenOne; + }); + } +); + +setTimeout(function() { + fs.writeFileSync(filepathOne, 'world'); +}, 1000); + + +process.chdir(testDir); + +fs.writeFileSync(filepathTwoAbs, 'howdy'); + +assert.throws( + function() { + fs.watchFile(filepathTwo); + }, + function(e) { + return e.message === 'watchFile requires a listener function'; + } +); + +assert.doesNotThrow( + function() { + function a(curr, prev) { + fs.unwatchFile(filepathTwo, a); + ++watchSeenTwo; + } + function b(curr, prev) { + fs.unwatchFile(filepathTwo, b); + ++watchSeenTwo; + } + fs.watchFile(filepathTwo, a); + fs.watchFile(filepathTwo, b); + } +); + +setTimeout(function() { + fs.writeFileSync(filepathTwoAbs, 'pardner'); +}, 1000); + +assert.doesNotThrow( + function() { + function a(curr, prev) { + assert.ok(0); // should not run + } + function b(curr, prev) { + fs.unwatchFile(filenameThree, b); + ++watchSeenThree; + } + fs.watchFile(filenameThree, a); + fs.watchFile(filenameThree, b); + fs.unwatchFile(filenameThree, a); + } +); + +setTimeout(function() { + fs.writeFileSync(filenameThree, 'pardner'); +}, 1000); diff --git a/node-v0.8.14/test/pummel/test-http-client-reconnect-bug.js b/node-v0.8.14/test/pummel/test-http-client-reconnect-bug.js new file mode 100644 index 0000000..a85cc13 --- /dev/null +++ b/node-v0.8.14/test/pummel/test-http-client-reconnect-bug.js @@ -0,0 +1,69 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); + +var net = require('net'), + util = require('util'), + http = require('http'); + +var errorCount = 0; +var eofCount = 0; + +var server = net.createServer(function(socket) { + socket.end(); +}); + +server.on('listening', function() { + var client = http.createClient(common.PORT); + + client.on('error', function(err) { + // We should receive one error + console.log('ERROR! ' + err.message); + errorCount++; + }); + + client.on('end', function() { + // When we remove the old Client interface this will most likely have to be + // changed. + console.log('EOF!'); + eofCount++; + }); + + var request = client.request('GET', '/', {'host': 'localhost'}); + request.end(); + request.on('response', function(response) { + console.log('STATUS: ' + response.statusCode); + }); +}); + +server.listen(common.PORT); + +setTimeout(function() { + server.close(); +}, 500); + + +process.on('exit', function() { + assert.equal(1, errorCount); + assert.equal(1, eofCount); +}); diff --git a/node-v0.8.14/test/pummel/test-http-upload-timeout.js b/node-v0.8.14/test/pummel/test-http-upload-timeout.js new file mode 100644 index 0000000..417749c --- /dev/null +++ b/node-v0.8.14/test/pummel/test-http-upload-timeout.js @@ -0,0 +1,69 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// This tests setTimeout() by having multiple clients connecting and sending +// data in random intervals. Clients are also randomly disconnecting until there +// are no more clients left. If no false timeout occurs, this test has passed. +var common = require('../common'), + assert = require('assert'), + http = require('http'), + server = http.createServer(), + connections = 0; + +server.on('request', function(req, res) { + req.socket.setTimeout(1000); + req.socket.on('timeout', function() { + throw new Error('Unexpected timeout'); + }); + req.on('end', function() { + connections--; + res.writeHead(200); + res.end('done\n'); + if (connections == 0) { + server.close(); + } + }); +}); + +server.listen(common.PORT, '127.0.0.1', function() { + for (var i = 0; i < 10; i++) { + connections++; + + setTimeout(function() { + var request = http.request({ + port: common.PORT, + method: 'POST', + path: '/' + }); + + function ping() { + var nextPing = (Math.random() * 900).toFixed(); + if (nextPing > 600) { + request.end(); + return; + } + request.write('ping'); + setTimeout(ping, nextPing); + } + ping(); + }, i * 50); + } +}); diff --git a/node-v0.8.14/test/pummel/test-https-ci-reneg-attack.js b/node-v0.8.14/test/pummel/test-https-ci-reneg-attack.js new file mode 100644 index 0000000..83b76b4 --- /dev/null +++ b/node-v0.8.14/test/pummel/test-https-ci-reneg-attack.js @@ -0,0 +1,106 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var spawn = require('child_process').spawn; +var tls = require('tls'); +var https = require('https'); +var fs = require('fs'); + +// renegotiation limits to test +var LIMITS = [0, 1, 2, 3, 5, 10, 16]; + +if (process.platform === 'win32') { + console.log('Skipping test, you probably don\'t have openssl installed.'); + process.exit(); +} + +(function() { + var n = 0; + function next() { + if (n >= LIMITS.length) return; + tls.CLIENT_RENEG_LIMIT = LIMITS[n++]; + test(next); + } + next(); +})(); + +function test(next) { + var options = { + cert: fs.readFileSync(common.fixturesDir + '/test_cert.pem'), + key: fs.readFileSync(common.fixturesDir + '/test_key.pem') + }; + + var seenError = false; + + var server = https.createServer(options, function(req, res) { + var conn = req.connection; + conn.on('error', function(err) { + console.error('Caught exception: ' + err); + assert(/TLS session renegotiation attack/.test(err)); + conn.destroy(); + seenError = true; + }); + res.end('ok'); + }); + + server.listen(common.PORT, function() { + var args = ('s_client -connect 127.0.0.1:' + common.PORT).split(' '); + var child = spawn('openssl', args); + + child.stdout.pipe(process.stdout); + child.stderr.pipe(process.stderr); + + // count handshakes, start the attack after the initial handshake is done + var handshakes = 0; + var renegs = 0; + + child.stderr.on('data', function(data) { + if (seenError) return; + handshakes += (('' + data).match(/verify return:1/g) || []).length; + if (handshakes === 2) spam(); + renegs += (('' + data).match(/RENEGOTIATING/g) || []).length; + }); + + child.on('exit', function() { + assert.equal(renegs, tls.CLIENT_RENEG_LIMIT + 1); + server.close(); + process.nextTick(next); + }); + + var closed = false; + child.stdin.on('error', function(err) { + assert.equal(err.code, 'EPIPE'); + closed = true; + }); + child.stdin.on('close', function() { + closed = true; + }); + + // simulate renegotiation attack + function spam() { + if (closed) return; + child.stdin.write('R\n'); + setTimeout(spam, 50); + } + }); +} diff --git a/node-v0.8.14/test/pummel/test-https-large-response.js b/node-v0.8.14/test/pummel/test-https-large-response.js new file mode 100644 index 0000000..e5382c4 --- /dev/null +++ b/node-v0.8.14/test/pummel/test-https-large-response.js @@ -0,0 +1,84 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + + + +var common = require('../common'); +var assert = require('assert'); + +var fs = require('fs'); +var https = require('https'); + +var options = { + key: fs.readFileSync(common.fixturesDir + '/keys/agent1-key.pem'), + cert: fs.readFileSync(common.fixturesDir + '/keys/agent1-cert.pem') +}; + +var reqCount = 0; +var body = ''; + +process.stdout.write('build body...'); +for (var i = 0; i < 1024 * 1024; i++) { + body += 'hello world\n'; +} +process.stdout.write('done\n'); + +var server = https.createServer(options, function(req, res) { + reqCount++; + console.log('got request'); + res.writeHead(200, { 'content-type': 'text/plain' }); + res.end(body); +}); + +var count = 0; +var gotResEnd = false; + +server.listen(common.PORT, function() { + https.get({ port: common.PORT }, function(res) { + console.log('response!'); + + res.on('data', function(d) { + process.stdout.write('.'); + count += d.length; + res.pause(); + process.nextTick(function() { + res.resume(); + }); + }); + + res.on('end', function(d) { + process.stdout.write('\n'); + console.log('expected: ', body.length); + console.log(' got: ', count); + server.close(); + gotResEnd = true; + }); + }); +}); + + +process.on('exit', function() { + assert.equal(1, reqCount); + assert.equal(body.length, count); + assert.ok(gotResEnd); +}); + diff --git a/node-v0.8.14/test/pummel/test-keep-alive.js b/node-v0.8.14/test/pummel/test-keep-alive.js new file mode 100644 index 0000000..47ab09d --- /dev/null +++ b/node-v0.8.14/test/pummel/test-keep-alive.js @@ -0,0 +1,90 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + + + +// This test requires the program 'ab' +var common = require('../common'); +var assert = require('assert'); +var http = require('http'); +var exec = require('child_process').exec; + +var body = 'hello world\n'; +var server = http.createServer(function(req, res) { + res.writeHead(200, { + 'Content-Length': body.length, + 'Content-Type': 'text/plain' + }); + res.write(body); + res.end(); +}); + +var keepAliveReqSec = 0; +var normalReqSec = 0; + + +function runAb(opts, callback) { + var command = 'ab ' + opts + ' http://127.0.0.1:' + common.PORT + '/'; + exec(command, function(err, stdout, stderr) { + if (err) { + if (stderr.indexOf('ab') >= 0) { + console.log('ab not installed? skipping test.\n' + stderr); + process.reallyExit(0); + } + return; + } + if (err) throw err; + var matches = /Requests per second:\s*(\d+)\./mi.exec(stdout); + var reqSec = parseInt(matches[1]); + + matches = /Keep-Alive requests:\s*(\d+)/mi.exec(stdout); + var keepAliveRequests; + if (matches) { + keepAliveRequests = parseInt(matches[1]); + } else { + keepAliveRequests = 0; + } + + callback(reqSec, keepAliveRequests); + }); +} + +server.listen(common.PORT, function() { + runAb('-k -c 100 -t 2', function(reqSec, keepAliveRequests) { + keepAliveReqSec = reqSec; + assert.equal(true, keepAliveRequests > 0); + console.log('keep-alive: ' + keepAliveReqSec + ' req/sec'); + + runAb('-c 100 -t 2', function(reqSec, keepAliveRequests) { + normalReqSec = reqSec; + assert.equal(0, keepAliveRequests); + console.log('normal: ' + normalReqSec + ' req/sec'); + server.close(); + }); + }); +}); + +process.on('exit', function() { + assert.equal(true, normalReqSec > 50); + assert.equal(true, keepAliveReqSec > 50); + assert.equal(true, normalReqSec < keepAliveReqSec); +}); diff --git a/node-v0.8.14/test/pummel/test-net-connect-econnrefused.js b/node-v0.8.14/test/pummel/test-net-connect-econnrefused.js new file mode 100644 index 0000000..bb3ef59 --- /dev/null +++ b/node-v0.8.14/test/pummel/test-net-connect-econnrefused.js @@ -0,0 +1,64 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// verify that connect reqs are properly cleaned up + +var common = require('../common'); +var assert = require('assert'); +var net = require('net'); + +var ROUNDS = 5; +var ATTEMPTS_PER_ROUND = 200; +var rounds = 0; +var reqs = 0; + +pummel(); + +function pummel() { + console.log('Round', rounds, '/', ROUNDS); + + for (var pending = 0; pending < ATTEMPTS_PER_ROUND; pending++) { + net.createConnection(common.PORT).on('error', function(err) { + assert.equal(err.code, 'ECONNREFUSED'); + if (--pending > 0) return; + if (++rounds < ROUNDS) return pummel(); + check(); + }); + reqs++; + } +} + +function check() { + process.nextTick(function() { + process.nextTick(function() { + assert.equal(process._getActiveRequests().length, 0); + assert.equal(process._getActiveHandles().length, 0); + check_called = true; + }); + }); +} +var check_called = false; + +process.on('exit', function() { + assert.equal(rounds, ROUNDS); + assert.equal(reqs, ROUNDS * ATTEMPTS_PER_ROUND); + assert(check_called); +}); diff --git a/node-v0.8.14/test/pummel/test-net-many-clients.js b/node-v0.8.14/test/pummel/test-net-many-clients.js new file mode 100644 index 0000000..3f394b8 --- /dev/null +++ b/node-v0.8.14/test/pummel/test-net-many-clients.js @@ -0,0 +1,104 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var net = require('net'); + +// settings +var bytes = 1024 * 40; +var concurrency = 100; +var connections_per_client = 5; + +// measured +var total_connections = 0; + +var body = ''; +for (var i = 0; i < bytes; i++) { + body += 'C'; +} + +var server = net.createServer(function(c) { + c.on('connect', function() { + total_connections++; + common.print('#'); + c.write(body); + c.end(); + }); +}); + +function runClient(callback) { + var client = net.createConnection(common.PORT); + + client.connections = 0; + + client.setEncoding('utf8'); + + client.on('connect', function() { + common.print('c'); + client.recved = ''; + client.connections += 1; + }); + + client.on('data', function(chunk) { + this.recved += chunk; + }); + + client.on('end', function() { + client.end(); + }); + + client.on('error', function(e) { + console.log('\n\nERROOOOOr'); + throw e; + }); + + client.on('close', function(had_error) { + common.print('.'); + assert.equal(false, had_error); + assert.equal(bytes, client.recved.length); + + if (client.fd) { + console.log(client.fd); + } + assert.ok(!client.fd); + + if (this.connections < connections_per_client) { + this.connect(common.PORT); + } else { + callback(); + } + }); +} + +server.listen(common.PORT, function() { + var finished_clients = 0; + for (var i = 0; i < concurrency; i++) { + runClient(function() { + if (++finished_clients == concurrency) server.close(); + }); + } +}); + +process.on('exit', function() { + assert.equal(connections_per_client * concurrency, total_connections); + console.log('\nokay!'); +}); diff --git a/node-v0.8.14/test/pummel/test-net-pause.js b/node-v0.8.14/test/pummel/test-net-pause.js new file mode 100644 index 0000000..740869d --- /dev/null +++ b/node-v0.8.14/test/pummel/test-net-pause.js @@ -0,0 +1,89 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var net = require('net'); + +var N = 200; +var recv = '', chars_recved = 0; + +var server = net.createServer(function(connection) { + function write(j) { + if (j >= N) { + connection.end(); + return; + } + setTimeout(function() { + connection.write('C'); + write(j + 1); + }, 10); + } + write(0); +}); + +server.on('listening', function() { + var client = net.createConnection(common.PORT); + client.setEncoding('ascii'); + client.on('data', function(d) { + common.print(d); + recv += d; + }); + + setTimeout(function() { + chars_recved = recv.length; + console.log('pause at: ' + chars_recved); + assert.equal(true, chars_recved > 1); + client.pause(); + setTimeout(function() { + console.log('resume at: ' + chars_recved); + assert.equal(chars_recved, recv.length); + client.resume(); + + setTimeout(function() { + chars_recved = recv.length; + console.log('pause at: ' + chars_recved); + client.pause(); + + setTimeout(function() { + console.log('resume at: ' + chars_recved); + assert.equal(chars_recved, recv.length); + client.resume(); + + }, 500); + + }, 500); + + }, 500); + + }, 500); + + client.on('end', function() { + server.close(); + client.end(); + }); +}); +server.listen(common.PORT); + +process.on('exit', function() { + assert.equal(N, recv.length); + common.debug('Exit'); +}); diff --git a/node-v0.8.14/test/pummel/test-net-pingpong-delay.js b/node-v0.8.14/test/pummel/test-net-pingpong-delay.js new file mode 100644 index 0000000..7b1d590 --- /dev/null +++ b/node-v0.8.14/test/pummel/test-net-pingpong-delay.js @@ -0,0 +1,114 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var net = require('net'); + + +var tests_run = 0; + +function pingPongTest(port, host, on_complete) { + var N = 100; + var DELAY = 1; + var count = 0; + var client_ended = false; + + var server = net.createServer({ allowHalfOpen: true }, function(socket) { + socket.setEncoding('utf8'); + + socket.on('data', function(data) { + console.log(data); + assert.equal('PING', data); + assert.equal('open', socket.readyState); + assert.equal(true, count <= N); + setTimeout(function() { + assert.equal('open', socket.readyState); + socket.write('PONG'); + }, DELAY); + }); + + socket.on('timeout', function() { + common.debug('server-side timeout!!'); + assert.equal(false, true); + }); + + socket.on('end', function() { + console.log('server-side socket EOF'); + assert.equal('writeOnly', socket.readyState); + socket.end(); + }); + + socket.on('close', function(had_error) { + console.log('server-side socket.end'); + assert.equal(false, had_error); + assert.equal('closed', socket.readyState); + socket.server.close(); + }); + }); + + server.listen(port, host, function() { + var client = net.createConnection(port, host); + + client.setEncoding('utf8'); + + client.on('connect', function() { + assert.equal('open', client.readyState); + client.write('PING'); + }); + + client.on('data', function(data) { + console.log(data); + assert.equal('PONG', data); + assert.equal('open', client.readyState); + + setTimeout(function() { + assert.equal('open', client.readyState); + if (count++ < N) { + client.write('PING'); + } else { + console.log('closing client'); + client.end(); + client_ended = true; + } + }, DELAY); + }); + + client.on('timeout', function() { + common.debug('client-side timeout!!'); + assert.equal(false, true); + }); + + client.on('close', function() { + console.log('client.end'); + assert.equal(N + 1, count); + assert.ok(client_ended); + if (on_complete) on_complete(); + tests_run += 1; + }); + }); +} + +pingPongTest(common.PORT); + +process.on('exit', function() { + assert.equal(1, tests_run); +}); diff --git a/node-v0.8.14/test/pummel/test-net-pingpong.js b/node-v0.8.14/test/pummel/test-net-pingpong.js new file mode 100644 index 0000000..c665444 --- /dev/null +++ b/node-v0.8.14/test/pummel/test-net-pingpong.js @@ -0,0 +1,123 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + + + +var common = require('../common'); +var assert = require('assert'); +var net = require('net'); + +var tests_run = 0; + +function pingPongTest(port, host, on_complete) { + var N = 1000; + var count = 0; + var sent_final_ping = false; + + var server = net.createServer({ allowHalfOpen: true }, function(socket) { + assert.equal(true, socket.remoteAddress !== null); + assert.equal(true, socket.remoteAddress !== undefined); + if (host === '127.0.0.1' || host === 'localhost' || !host) { + assert.equal(socket.remoteAddress, '127.0.0.1'); + } else { + console.log('host = ' + host + + ', remoteAddress = ' + socket.remoteAddress); + assert.equal(socket.remoteAddress, '::1'); + } + + socket.setEncoding('utf8'); + socket.setNoDelay(); + socket.timeout = 0; + + socket.on('data', function(data) { + console.log('server got: ' + JSON.stringify(data)); + assert.equal('open', socket.readyState); + assert.equal(true, count <= N); + if (/PING/.exec(data)) { + socket.write('PONG'); + } + }); + + socket.on('end', function() { + assert.equal('writeOnly', socket.readyState); + socket.end(); + }); + + socket.on('close', function(had_error) { + assert.equal(false, had_error); + assert.equal('closed', socket.readyState); + socket.server.close(); + }); + }); + + server.listen(port, host, function() { + var client = net.createConnection(port, host); + + client.setEncoding('utf8'); + + client.on('connect', function() { + assert.equal('open', client.readyState); + client.write('PING'); + }); + + client.on('data', function(data) { + console.log('client got: ' + data); + + assert.equal('PONG', data); + count += 1; + + if (sent_final_ping) { + assert.equal('readOnly', client.readyState); + return; + } else { + assert.equal('open', client.readyState); + } + + if (count < N) { + client.write('PING'); + } else { + sent_final_ping = true; + client.write('PING'); + client.end(); + } + }); + + client.on('close', function() { + assert.equal(N + 1, count); + assert.equal(true, sent_final_ping); + if (on_complete) on_complete(); + tests_run += 1; + }); + }); +} + +/* All are run at once, so run on different ports */ +pingPongTest(common.PORT, 'localhost'); +pingPongTest(common.PORT + 1, null); + +// This IPv6 isn't working on Solaris +var solaris = /sunos/i.test(process.platform); +if (!solaris) pingPongTest(common.PORT + 2, '::1'); + +process.on('exit', function() { + assert.equal(solaris ? 2 : 3, tests_run); +}); diff --git a/node-v0.8.14/test/pummel/test-net-throttle.js b/node-v0.8.14/test/pummel/test-net-throttle.js new file mode 100644 index 0000000..29fd184 --- /dev/null +++ b/node-v0.8.14/test/pummel/test-net-throttle.js @@ -0,0 +1,87 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + + + +var common = require('../common'); +var assert = require('assert'); +var net = require('net'); + +var N = 1024 * 1024; +var part_N = N / 3; +var chars_recved = 0; +var npauses = 0; + +console.log('build big string'); +var body = ''; +for (var i = 0; i < N; i++) { + body += 'C'; +} + +console.log('start server on port ' + common.PORT); + +var server = net.createServer(function(connection) { + connection.on('connect', function() { + connection.write(body.slice(0, part_N)); + connection.write(body.slice(part_N, 2 * part_N)); + assert.equal(false, connection.write(body.slice(2 * part_N, N))); + console.log('bufferSize: ' + connection.bufferSize); + assert.ok(0 <= connection.bufferSize && + connection.bufferSize <= N); + connection.end(); + }); +}); + +server.listen(common.PORT, function() { + var paused = false; + var client = net.createConnection(common.PORT); + client.setEncoding('ascii'); + client.on('data', function(d) { + chars_recved += d.length; + console.log('got ' + chars_recved); + if (!paused) { + client.pause(); + npauses += 1; + paused = true; + console.log('pause'); + var x = chars_recved; + setTimeout(function() { + assert.equal(chars_recved, x); + client.resume(); + console.log('resume'); + paused = false; + }, 100); + } + }); + + client.on('end', function() { + server.close(); + client.end(); + }); +}); + + + +process.on('exit', function() { + assert.equal(N, chars_recved); + assert.equal(true, npauses > 2); +}); diff --git a/node-v0.8.14/test/pummel/test-net-timeout.js b/node-v0.8.14/test/pummel/test-net-timeout.js new file mode 100644 index 0000000..4fc43c8 --- /dev/null +++ b/node-v0.8.14/test/pummel/test-net-timeout.js @@ -0,0 +1,109 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var net = require('net'); + +var exchanges = 0; +var starttime = null; +var timeouttime = null; +var timeout = 1000; + +var echo_server = net.createServer(function(socket) { + socket.setTimeout(timeout); + + socket.on('timeout', function() { + console.log('server timeout'); + timeouttime = new Date; + console.dir(timeouttime); + socket.destroy(); + }); + + socket.on('error', function(e) { + throw new Error('Server side socket should not get error. ' + + 'We disconnect willingly.'); + }); + + socket.on('data', function(d) { + console.log(d); + socket.write(d); + }); + + socket.on('end', function() { + socket.end(); + }); +}); + +echo_server.listen(common.PORT, function() { + console.log('server listening at ' + common.PORT); + + var client = net.createConnection(common.PORT); + client.setEncoding('UTF8'); + client.setTimeout(0); // disable the timeout for client + client.on('connect', function() { + console.log('client connected.'); + client.write('hello\r\n'); + }); + + client.on('data', function(chunk) { + assert.equal('hello\r\n', chunk); + if (exchanges++ < 5) { + setTimeout(function() { + console.log('client write "hello"'); + client.write('hello\r\n'); + }, 500); + + if (exchanges == 5) { + console.log('wait for timeout - should come in ' + timeout + ' ms'); + starttime = new Date; + console.dir(starttime); + } + } + }); + + client.on('timeout', function() { + throw new Error("client timeout - this shouldn't happen"); + }); + + client.on('end', function() { + console.log('client end'); + client.end(); + }); + + client.on('close', function() { + console.log('client disconnect'); + echo_server.close(); + }); +}); + +process.on('exit', function() { + assert.ok(starttime != null); + assert.ok(timeouttime != null); + + diff = timeouttime - starttime; + console.log('diff = ' + diff); + + assert.ok(timeout < diff); + + // Allow for 800 milliseconds more + assert.ok(diff < timeout + 800); +}); diff --git a/node-v0.8.14/test/pummel/test-net-timeout2.js b/node-v0.8.14/test/pummel/test-net-timeout2.js new file mode 100644 index 0000000..5f9c03e --- /dev/null +++ b/node-v0.8.14/test/pummel/test-net-timeout2.js @@ -0,0 +1,65 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// socket.write was not resetting the timeout timer. See +// https://github.com/joyent/node/issues/2002 + +var common = require('../common'); +var assert = require('assert'); +var net = require('net'); + +var seconds = 5; +var gotTimeout = false; +var counter = 0; + +var server = net.createServer(function(socket) { + socket.setTimeout((seconds / 2) * 1000, function() { + gotTimeout = true; + console.log('timeout!!'); + socket.destroy(); + process.exit(1); + }); + + var interval = setInterval(function() { + counter++; + + if (counter == seconds) { + clearInterval(interval); + server.close(); + socket.destroy(); + } + + if (socket.writable) { + socket.write(Date.now() + '\n'); + } + }, 1000); +}); + + +server.listen(8888, function() { + var s = net.connect(8888); + s.pipe(process.stdout); +}); + + +process.on('exit', function() { + assert.equal(false, gotTimeout); +}); diff --git a/node-v0.8.14/test/pummel/test-net-write-callbacks.js b/node-v0.8.14/test/pummel/test-net-write-callbacks.js new file mode 100644 index 0000000..45d1d59 --- /dev/null +++ b/node-v0.8.14/test/pummel/test-net-write-callbacks.js @@ -0,0 +1,56 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var net = require('net'); +var assert = require('assert'); + +var cbcount = 0; +var N = 500000; + +var server = net.Server(function(socket) { + socket.on('data', function(d) { + console.error('got %d bytes', d.length); + }); + + socket.on('end', function() { + console.error('end'); + socket.destroy(); + server.close(); + }); +}); + +server.listen(common.PORT, function() { + var client = net.createConnection(common.PORT); + + client.on('connect', function() { + for (var i = 0; i < N; i++) { + client.write('hello world', function() { + cbcount++; + }); + } + client.end(); + }); +}); + +process.on('exit', function() { + assert.equal(N, cbcount); +}); diff --git a/node-v0.8.14/test/pummel/test-next-tick-loops-quick.js b/node-v0.8.14/test/pummel/test-next-tick-loops-quick.js new file mode 100644 index 0000000..42d4818 --- /dev/null +++ b/node-v0.8.14/test/pummel/test-next-tick-loops-quick.js @@ -0,0 +1,48 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + + + +var common = require('../common'); +var assert = require('assert'); + +// Regression test GH-511: https://github.com/joyent/node/issues/issue/511 +// Make sure nextTick loops quickly + +setTimeout(function() { + t = Date.now() - t; + STOP = 1; + console.log(['ctr: ', ctr, ', t:', t, 'ms -> ', (ctr / t).toFixed(2), 'KHz'] + .join('')); + assert.ok(ctr > 1000); +}, 2000); + +var ctr = 0; +var STOP = 0; +var t = Date.now() + 2; +while (t > Date.now()); //get in sync with clock + +(function foo() { + if (STOP) return; + process.nextTick(foo); + ctr++; +})(); diff --git a/node-v0.8.14/test/pummel/test-process-hrtime.js b/node-v0.8.14/test/pummel/test-process-hrtime.js new file mode 100644 index 0000000..74608d1 --- /dev/null +++ b/node-v0.8.14/test/pummel/test-process-hrtime.js @@ -0,0 +1,40 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); + +var start = process.hrtime(); + +// process.hrtime() should return an Array +assert(Array.isArray(start)); + +// busy-loop for 2 seconds +var now = Date.now(); +while (Date.now() - now < 2000); + +// get a diff reading +var diff = process.hrtime(start); + +// should be at least 1 second, at most 2 seconds later +// (the while loop will usually exit a few nanoseconds before 2) +assert(diff[0] >= 1); +assert(diff[0] <= 2); diff --git a/node-v0.8.14/test/pummel/test-process-uptime.js b/node-v0.8.14/test/pummel/test-process-uptime.js new file mode 100644 index 0000000..602f777 --- /dev/null +++ b/node-v0.8.14/test/pummel/test-process-uptime.js @@ -0,0 +1,39 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + + + +var common = require('../common'); +var assert = require('assert'); + +console.error(process.uptime()); +assert.ok(process.uptime() <= 2); + +var original = process.uptime(); + +setTimeout(function() { + var uptime = process.uptime(); + // some wiggle room to account for timer + // granularity, processor speed, and scheduling + assert.ok(uptime >= original + 2); + assert.ok(uptime <= original + 3); +}, 2000); diff --git a/node-v0.8.14/test/pummel/test-regress-GH-814.js b/node-v0.8.14/test/pummel/test-regress-GH-814.js new file mode 100644 index 0000000..e4c9c92 --- /dev/null +++ b/node-v0.8.14/test/pummel/test-regress-GH-814.js @@ -0,0 +1,92 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// Flags: --expose_gc + +function newBuffer(size, value) { + var buffer = new Buffer(size); + while (size--) { + buffer[size] = value; + } + //buffer[buffer.length-2]= 0x0d; + buffer[buffer.length - 1] = 0x0a; + return buffer; +} + + +var common = require('../common'); +var fs = require('fs'); +var testFileName = require('path').join(common.tmpDir, 'GH-814_testFile.txt'); +var testFileFD = fs.openSync(testFileName, 'w'); +console.log(testFileName); + + + +var kBufSize = 128 * 1024; +var PASS = true; +var neverWrittenBuffer = newBuffer(kBufSize, 0x2e); //0x2e === '.' +var bufPool = []; + + + +var tail = require('child_process').spawn('tail', ['-f', testFileName]); +tail.stdout.on('data', tailCB); + +function tailCB(data) { + PASS = data.toString().indexOf('.') < 0; +} + + + +var timeToQuit = Date.now() + 8e3; //Test during no more than this seconds. +(function main() { + + if (PASS) { + fs.write(testFileFD, newBuffer(kBufSize, 0x61), 0, kBufSize, -1, cb); + gc(); + var nuBuf = new Buffer(kBufSize); + neverWrittenBuffer.copy(nuBuf); + if (bufPool.push(nuBuf) > 100) { + bufPool.length = 0; + } + } + else { + throw Error("Buffer GC'ed test -> FAIL"); + } + + if (Date.now() < timeToQuit) { + process.nextTick(main); + } + else { + tail.kill(); + console.log("Buffer GC'ed test -> PASS (OK)"); + } + +})(); + + +function cb(err, written) { + if (err) { + throw err; + } +} + + diff --git a/node-v0.8.14/test/pummel/test-regress-GH-814_2.js b/node-v0.8.14/test/pummel/test-regress-GH-814_2.js new file mode 100644 index 0000000..8015f4e --- /dev/null +++ b/node-v0.8.14/test/pummel/test-regress-GH-814_2.js @@ -0,0 +1,106 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// Flags: --expose_gc + +var common = require('../common'); + +var fs = require('fs'); +var testFileName = require('path').join(common.tmpDir, 'GH-814_test.txt'); +var testFD = fs.openSync(testFileName, 'w'); +console.error(testFileName + '\n'); + + +var tailProc = require('child_process').spawn('tail', ['-f', testFileName]); +tailProc.stdout.on('data', tailCB); + +function tailCB(data) { + PASS = data.toString().indexOf('.') < 0; + + if (PASS) { + //console.error('i'); + } else { + console.error('[FAIL]\n DATA -> '); + console.error(data); + console.error('\n'); + throw Error('Buffers GC test -> FAIL'); + } +} + + +var PASS = true; +var bufPool = []; +var kBufSize = 16 * 1024 * 1024; +var neverWrittenBuffer = newBuffer(kBufSize, 0x2e); //0x2e === '.' + +var timeToQuit = Date.now() + 5e3; //Test should last no more than this. +writer(); + +function writer() { + + if (PASS) { + if (Date.now() > timeToQuit) { + setTimeout(function() { + process.kill(tailProc.pid); + console.error('\nBuffers GC test -> PASS (OK)\n'); + }, 555); + } else { + fs.write(testFD, newBuffer(kBufSize, 0x61), 0, kBufSize, -1, writerCB); + gc(); + gc(); + gc(); + gc(); + gc(); + gc(); + var nuBuf = new Buffer(kBufSize); + neverWrittenBuffer.copy(nuBuf); + if (bufPool.push(nuBuf) > 100) { + bufPool.length = 0; + } + process.nextTick(writer); + //console.error('o'); + } + } + +} + +function writerCB(err, written) { + //console.error('cb.'); + if (err) { + throw err; + } +} + + + + +// ******************* UTILITIES + + +function newBuffer(size, value) { + var buffer = new Buffer(size); + while (size--) { + buffer[size] = value; + } + buffer[buffer.length - 1] = 0x0d; + buffer[buffer.length - 1] = 0x0a; + return buffer; +} diff --git a/node-v0.8.14/test/pummel/test-regress-GH-892.js b/node-v0.8.14/test/pummel/test-regress-GH-892.js new file mode 100644 index 0000000..901e4e9 --- /dev/null +++ b/node-v0.8.14/test/pummel/test-regress-GH-892.js @@ -0,0 +1,108 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + + + +// Uploading a big file via HTTPS causes node to drop out of the event loop. +// https://github.com/joyent/node/issues/892 +// In this test we set up an HTTPS in this process and launch a subprocess +// to POST a 32mb file to us. A bug in the pause/resume functionality of the +// TLS server causes the child process to exit cleanly before having sent +// the entire buffer. +var common = require('../common'); +var assert = require('assert'); +var spawn = require('child_process').spawn; +var https = require('https'); +var fs = require('fs'); + +var PORT = 8000; + + +var bytesExpected = 1024 * 1024 * 32; +var gotResponse = false; + +var started = false; + +var childScript = require('path').join(common.fixturesDir, 'GH-892-request.js'); + +function makeRequest() { + if (started) return; + started = true; + + var stderrBuffer = ''; + + var child = spawn(process.execPath, + [childScript, common.PORT, bytesExpected]); + + child.on('exit', function(code) { + assert.ok(/DONE/.test(stderrBuffer)); + assert.equal(0, code); + }); + + // The following two lines forward the stdio from the child + // to parent process for debugging. + child.stderr.pipe(process.stderr); + child.stdout.pipe(process.stdout); + + + // Buffer the stderr so that we can check that it got 'DONE' + child.stderr.setEncoding('ascii'); + child.stderr.on('data', function(d) { + stderrBuffer += d; + }); +} + + +var serverOptions = { + key: fs.readFileSync(common.fixturesDir + '/keys/agent1-key.pem'), + cert: fs.readFileSync(common.fixturesDir + '/keys/agent1-cert.pem') +}; + +var uploadCount = 0; + +var server = https.Server(serverOptions, function(req, res) { + // Close the server immediately. This test is only doing a single upload. + // We need to make sure the server isn't keeping the event loop alive + // while the upload is in progress. + server.close(); + + req.on('data', function(d) { + process.stderr.write('.'); + uploadCount += d.length; + }); + + req.on('end', function() { + assert.equal(bytesExpected, uploadCount); + res.writeHead(200, {'content-type': 'text/plain'}); + res.end('successful upload\n'); + }); +}); + +server.listen(common.PORT, function() { + console.log('expecting %d bytes', bytesExpected); + makeRequest(); +}); + +process.on('exit', function() { + console.error('got %d bytes', uploadCount); + assert.equal(uploadCount, bytesExpected); +}); diff --git a/node-v0.8.14/test/pummel/test-timer-wrap.js b/node-v0.8.14/test/pummel/test-timer-wrap.js new file mode 100644 index 0000000..fbf82d5 --- /dev/null +++ b/node-v0.8.14/test/pummel/test-timer-wrap.js @@ -0,0 +1,40 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); + +var timeouts = 0; +var Timer = process.binding('timer_wrap').Timer; + +var t = new Timer(); + +t.start(1000, 0); + +t.ontimeout = function() { + timeouts++; + console.log('timeout'); + t.close(); +}; + +process.on('exit', function() { + assert.equal(1, timeouts); +}); diff --git a/node-v0.8.14/test/pummel/test-timer-wrap2.js b/node-v0.8.14/test/pummel/test-timer-wrap2.js new file mode 100644 index 0000000..4fb424a --- /dev/null +++ b/node-v0.8.14/test/pummel/test-timer-wrap2.js @@ -0,0 +1,29 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); + +// Test that allocating a timer does not increase the loop's reference +// count. + +var Timer = process.binding('timer_wrap').Timer; +var t = new Timer(); diff --git a/node-v0.8.14/test/pummel/test-timers.js b/node-v0.8.14/test/pummel/test-timers.js new file mode 100644 index 0000000..2c45bf0 --- /dev/null +++ b/node-v0.8.14/test/pummel/test-timers.js @@ -0,0 +1,128 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); + +var WINDOW = 200; // why is does this need to be so big? + +var interval_count = 0; +var setTimeout_called = false; + +// check that these don't blow up. +clearTimeout(null); +clearInterval(null); + +assert.equal(true, setTimeout instanceof Function); +var starttime = new Date; +setTimeout(function() { + var endtime = new Date; + + var diff = endtime - starttime; + assert.ok(diff > 0); + console.error('diff: ' + diff); + + assert.equal(true, 1000 - WINDOW < diff && diff < 1000 + WINDOW); + setTimeout_called = true; +}, 1000); + +// this timer shouldn't execute +var id = setTimeout(function() { assert.equal(true, false); }, 500); +clearTimeout(id); + +setInterval(function() { + interval_count += 1; + var endtime = new Date; + + var diff = endtime - starttime; + assert.ok(diff > 0); + console.error('diff: ' + diff); + + var t = interval_count * 1000; + + assert.equal(true, t - WINDOW < diff && diff < t + WINDOW); + + assert.equal(true, interval_count <= 3); + if (interval_count == 3) + clearInterval(this); +}, 1000); + + +// Single param: +setTimeout(function(param) { + assert.equal('test param', param); +}, 1000, 'test param'); + +var interval_count2 = 0; +setInterval(function(param) { + ++interval_count2; + assert.equal('test param', param); + + if (interval_count2 == 3) + clearInterval(this); +}, 1000, 'test param'); + + +// Multiple param +setTimeout(function(param1, param2) { + assert.equal('param1', param1); + assert.equal('param2', param2); +}, 1000, 'param1', 'param2'); + +var interval_count3 = 0; +setInterval(function(param1, param2) { + ++interval_count3; + assert.equal('param1', param1); + assert.equal('param2', param2); + + if (interval_count3 == 3) + clearInterval(this); +}, 1000, 'param1', 'param2'); + +// setInterval(cb, 0) should be called multiple times. +var count4 = 0; +var interval4 = setInterval(function() { + if (++count4 > 10) clearInterval(interval4); +}, 0); + + +// we should be able to clearTimeout multiple times without breakage. +var expectedTimeouts = 3; + +function t() { + expectedTimeouts--; +} + +var w = setTimeout(t, 200); +var x = setTimeout(t, 200); +var y = setTimeout(t, 200); + +clearTimeout(y); +var z = setTimeout(t, 200); +clearTimeout(y); + + +process.on('exit', function() { + assert.equal(true, setTimeout_called); + assert.equal(3, interval_count); + assert.equal(11, count4); + assert.equal(0, expectedTimeouts, 'clearTimeout cleared too many timeouts'); +}); diff --git a/node-v0.8.14/test/pummel/test-tls-ci-reneg-attack.js b/node-v0.8.14/test/pummel/test-tls-ci-reneg-attack.js new file mode 100644 index 0000000..778e288 --- /dev/null +++ b/node-v0.8.14/test/pummel/test-tls-ci-reneg-attack.js @@ -0,0 +1,104 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var spawn = require('child_process').spawn; +var tls = require('tls'); +var fs = require('fs'); + +// renegotiation limits to test +var LIMITS = [0, 1, 2, 3, 5, 10, 16]; + +if (process.platform === 'win32') { + console.log('Skipping test, you probably don\'t have openssl installed.'); + process.exit(); +} + +(function() { + var n = 0; + function next() { + if (n >= LIMITS.length) return; + tls.CLIENT_RENEG_LIMIT = LIMITS[n++]; + test(next); + } + next(); +})(); + +function test(next) { + var options = { + cert: fs.readFileSync(common.fixturesDir + '/test_cert.pem'), + key: fs.readFileSync(common.fixturesDir + '/test_key.pem') + }; + + var seenError = false; + + var server = tls.createServer(options, function(conn) { + conn.on('error', function(err) { + console.error('Caught exception: ' + err); + assert(/TLS session renegotiation attack/.test(err)); + conn.destroy(); + seenError = true; + }); + conn.pipe(conn); + }); + + server.listen(common.PORT, function() { + var args = ('s_client -connect 127.0.0.1:' + common.PORT).split(' '); + var child = spawn('openssl', args); + + child.stdout.pipe(process.stdout); + child.stderr.pipe(process.stderr); + + // count handshakes, start the attack after the initial handshake is done + var handshakes = 0; + var renegs = 0; + + child.stderr.on('data', function(data) { + if (seenError) return; + handshakes += (('' + data).match(/verify return:1/g) || []).length; + if (handshakes === 2) spam(); + renegs += (('' + data).match(/RENEGOTIATING/g) || []).length; + }); + + child.on('exit', function() { + assert.equal(renegs, tls.CLIENT_RENEG_LIMIT + 1); + server.close(); + process.nextTick(next); + }); + + var closed = false; + child.stdin.on('error', function(err) { + assert.equal(err.code, 'EPIPE'); + closed = true; + }); + child.stdin.on('close', function() { + closed = true; + }); + + // simulate renegotiation attack + function spam() { + if (closed) return; + child.stdin.write('R\n'); + setTimeout(spam, 50); + } + }); +} diff --git a/node-v0.8.14/test/pummel/test-tls-throttle.js b/node-v0.8.14/test/pummel/test-tls-throttle.js new file mode 100644 index 0000000..fcbc8c7 --- /dev/null +++ b/node-v0.8.14/test/pummel/test-tls-throttle.js @@ -0,0 +1,92 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + + + +// Server sends a large string. Client counts bytes and pauses every few +// seconds. Makes sure that pause and resume work properly. +var common = require('../common'); +var assert = require('assert'); +var tls = require('tls'); +var fs = require('fs'); + + +var body = ''; + +process.stdout.write('build body...'); +for (var i = 0; i < 1024 * 1024; i++) { + body += 'hello world\n'; +} +process.stdout.write('done\n'); + + +var options = { + key: fs.readFileSync(common.fixturesDir + '/keys/agent2-key.pem'), + cert: fs.readFileSync(common.fixturesDir + '/keys/agent2-cert.pem') +}; + +var connections = 0; + + +var server = tls.Server(options, function(socket) { + socket.end(body); + connections++; +}); + +var recvCount = 0; + +server.listen(common.PORT, function() { + var client = tls.connect(common.PORT); + + client.on('data', function(d) { + process.stdout.write('.'); + recvCount += d.length; + + client.pause(); + process.nextTick(function() { + client.resume(); + }); + }); + + + client.on('close', function() { + console.error('close'); + server.close(); + clearTimeout(timeout); + }); +}); + + +function displayCounts() { + console.log('body.length: %d', body.length); + console.log(' recvCount: %d', recvCount); +} + + +var timeout = setTimeout(displayCounts, 10 * 1000); + + +process.on('exit', function() { + displayCounts(); + assert.equal(1, connections); + assert.equal(body.length, recvCount); +}); diff --git a/node-v0.8.14/test/pummel/test-vm-memleak.js b/node-v0.8.14/test/pummel/test-vm-memleak.js new file mode 100644 index 0000000..e0b087d --- /dev/null +++ b/node-v0.8.14/test/pummel/test-vm-memleak.js @@ -0,0 +1,48 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var assert = require('assert'); +var common = require('../common'); + +var start = Date.now(); +var maxMem = 0; + +var interval = setInterval(function() { + try { + require('vm').runInNewContext('throw 1;'); + } catch (e) { + } + + var rss = process.memoryUsage().rss; + maxMem = Math.max(rss, maxMem); + + + if (Date.now() - start > 5 * 1000) { + // wait 10 seconds. + clearInterval(interval); + } +}, 1); + +process.on('exit', function() { + console.error('max mem: %dmb', Math.round(maxMem / (1024 * 1024))); + // make sure we stay below 100mb + assert.ok(maxMem < 50 * 1024 * 1024); +}); diff --git a/node-v0.8.14/test/pummel/test-watch-file.js b/node-v0.8.14/test/pummel/test-watch-file.js new file mode 100644 index 0000000..1a3d854 --- /dev/null +++ b/node-v0.8.14/test/pummel/test-watch-file.js @@ -0,0 +1,54 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); + +var fs = require('fs'); +var path = require('path'); + +var f = path.join(common.fixturesDir, 'x.txt'); +var f2 = path.join(common.fixturesDir, 'x2.txt'); + +console.log('watching for changes of ' + f); + +var changes = 0; +function watchFile() { + fs.watchFile(f, function(curr, prev) { + console.log(f + ' change'); + changes++; + assert.ok(curr.mtime != prev.mtime); + fs.unwatchFile(f); + watchFile(); + fs.unwatchFile(f); + }); +} + +watchFile(); + + +var fd = fs.openSync(f, 'w+'); +fs.writeSync(fd, 'xyz\n'); +fs.closeSync(fd); + +process.on('exit', function() { + assert.ok(changes > 0); +}); diff --git a/node-v0.8.14/test/pummel/testcfg.py b/node-v0.8.14/test/pummel/testcfg.py new file mode 100644 index 0000000..02f5ec6 --- /dev/null +++ b/node-v0.8.14/test/pummel/testcfg.py @@ -0,0 +1,130 @@ +# Copyright 2008 the V8 project authors. All rights reserved. +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above +# copyright notice, this list of conditions and the following +# disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of Google Inc. nor the names of its +# contributors may be used to endorse or promote products derived +# from this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +import test +import os +import shutil +from shutil import rmtree +from os import mkdir +from glob import glob +from os.path import join, dirname, exists +import re + + +FLAGS_PATTERN = re.compile(r"//\s+Flags:(.*)") +FILES_PATTERN = re.compile(r"//\s+Files:(.*)") + + +class PummelTestCase(test.TestCase): + + def __init__(self, path, file, mode, context, config): + super(PummelTestCase, self).__init__(context, path, mode) + self.file = file + self.config = config + self.mode = mode + self.tmpdir = join(dirname(self.config.root), 'tmp') + + def AfterRun(self, result): + # delete the whole tmp dir + try: + rmtree(self.tmpdir) + except: + pass + # make it again. + try: + mkdir(self.tmpdir) + except: + pass + + def BeforeRun(self): + # delete the whole tmp dir + try: + rmtree(self.tmpdir) + except: + pass + # make it again. + try: + mkdir(self.tmpdir) + except: + pass + + def GetLabel(self): + return "%s %s" % (self.mode, self.GetName()) + + def GetName(self): + return self.path[-1] + + def GetCommand(self): + result = [self.config.context.GetVm(self.mode)] + source = open(self.file).read() + flags_match = FLAGS_PATTERN.search(source) + if flags_match: + result += flags_match.group(1).strip().split() + files_match = FILES_PATTERN.search(source); + additional_files = [] + if files_match: + additional_files += files_match.group(1).strip().split() + for a_file in additional_files: + result.append(join(dirname(self.config.root), '..', a_file)) + result += [self.file] + return result + + def GetSource(self): + return open(self.file).read() + + +class PummelTestConfiguration(test.TestConfiguration): + + def __init__(self, context, root): + super(PummelTestConfiguration, self).__init__(context, root) + + def Ls(self, path): + def SelectTest(name): + return name.startswith('test-') and name.endswith('.js') + return [f[:-3] for f in os.listdir(path) if SelectTest(f)] + + def ListTests(self, current_path, path, mode): + all_tests = [current_path + [t] for t in self.Ls(join(self.root))] + result = [] + for test in all_tests: + if self.Contains(path, test): + file_path = join(self.root, reduce(join, test[1:], "") + ".js") + result.append(PummelTestCase(test, file_path, mode, self.context, self)) + return result + + def GetBuildRequirements(self): + return ['sample', 'sample=shell'] + + def GetTestStatus(self, sections, defs): + status_file = join(self.root, 'simple.status') + if exists(status_file): + test.ReadConfigurationInto(status_file, sections, defs) + + + +def GetConfiguration(context, root): + return PummelTestConfiguration(context, root) diff --git a/node-v0.8.14/test/simple/path.js b/node-v0.8.14/test/simple/path.js new file mode 100644 index 0000000..21c08d3 --- /dev/null +++ b/node-v0.8.14/test/simple/path.js @@ -0,0 +1,32 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + + + +// This is actually more a fixture than a test. It is used to make +var common = require('../common'); +// sure that require('./path') and require('path') do different things. +// It has to be in the same directory as the test 'test-module-loading.js' +// and it has to have the same name as an internal module. +exports.path_func = function() { + return 'path_func'; +}; diff --git a/node-v0.8.14/test/simple/simple.status b/node-v0.8.14/test/simple/simple.status new file mode 100644 index 0000000..438ce39 --- /dev/null +++ b/node-v0.8.14/test/simple/simple.status @@ -0,0 +1 @@ +prefix simple diff --git a/node-v0.8.14/test/simple/test-assert.js b/node-v0.8.14/test/simple/test-assert.js new file mode 100644 index 0000000..081eb76 --- /dev/null +++ b/node-v0.8.14/test/simple/test-assert.js @@ -0,0 +1,295 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var a = require('assert'); + +function makeBlock(f) { + var args = Array.prototype.slice.call(arguments, 1); + return function() { + return f.apply(this, args); + }; +} + +assert.ok(common.indirectInstanceOf(a.AssertionError.prototype, Error), + 'a.AssertionError instanceof Error'); + +assert.throws(makeBlock(a, false), a.AssertionError, 'ok(false)'); + +assert.doesNotThrow(makeBlock(a, true), a.AssertionError, 'ok(true)'); + +assert.doesNotThrow(makeBlock(a, 'test', 'ok(\'test\')')); + +assert.throws(makeBlock(a.ok, false), + a.AssertionError, 'ok(false)'); + +assert.doesNotThrow(makeBlock(a.ok, true), + a.AssertionError, 'ok(true)'); + +assert.doesNotThrow(makeBlock(a.ok, 'test'), 'ok(\'test\')'); + +assert.throws(makeBlock(a.equal, true, false), a.AssertionError, 'equal'); + +assert.doesNotThrow(makeBlock(a.equal, null, null), 'equal'); + +assert.doesNotThrow(makeBlock(a.equal, undefined, undefined), 'equal'); + +assert.doesNotThrow(makeBlock(a.equal, null, undefined), 'equal'); + +assert.doesNotThrow(makeBlock(a.equal, true, true), 'equal'); + +assert.doesNotThrow(makeBlock(a.equal, 2, '2'), 'equal'); + +assert.doesNotThrow(makeBlock(a.notEqual, true, false), 'notEqual'); + +assert.throws(makeBlock(a.notEqual, true, true), + a.AssertionError, 'notEqual'); + +assert.throws(makeBlock(a.strictEqual, 2, '2'), + a.AssertionError, 'strictEqual'); + +assert.throws(makeBlock(a.strictEqual, null, undefined), + a.AssertionError, 'strictEqual'); + +assert.doesNotThrow(makeBlock(a.notStrictEqual, 2, '2'), 'notStrictEqual'); + +// deepEquals joy! +// 7.2 +assert.doesNotThrow(makeBlock(a.deepEqual, new Date(2000, 3, 14), + new Date(2000, 3, 14)), 'deepEqual date'); + +assert.throws(makeBlock(a.deepEqual, new Date(), new Date(2000, 3, 14)), + a.AssertionError, + 'deepEqual date'); + +// 7.3 +assert.doesNotThrow(makeBlock(a.deepEqual, /a/, /a/)); +assert.doesNotThrow(makeBlock(a.deepEqual, /a/g, /a/g)); +assert.doesNotThrow(makeBlock(a.deepEqual, /a/i, /a/i)); +assert.doesNotThrow(makeBlock(a.deepEqual, /a/m, /a/m)); +assert.doesNotThrow(makeBlock(a.deepEqual, /a/igm, /a/igm)); +assert.throws(makeBlock(a.deepEqual, /ab/, /a/)); +assert.throws(makeBlock(a.deepEqual, /a/g, /a/)); +assert.throws(makeBlock(a.deepEqual, /a/i, /a/)); +assert.throws(makeBlock(a.deepEqual, /a/m, /a/)); +assert.throws(makeBlock(a.deepEqual, /a/igm, /a/im)); + +var re1 = /a/; +re1.lastIndex = 3; +assert.throws(makeBlock(a.deepEqual, re1, /a/)); + + +// 7.4 +assert.doesNotThrow(makeBlock(a.deepEqual, 4, '4'), 'deepEqual == check'); +assert.doesNotThrow(makeBlock(a.deepEqual, true, 1), 'deepEqual == check'); +assert.throws(makeBlock(a.deepEqual, 4, '5'), + a.AssertionError, + 'deepEqual == check'); + +// 7.5 +// having the same number of owned properties && the same set of keys +assert.doesNotThrow(makeBlock(a.deepEqual, {a: 4}, {a: 4})); +assert.doesNotThrow(makeBlock(a.deepEqual, {a: 4, b: '2'}, {a: 4, b: '2'})); +assert.doesNotThrow(makeBlock(a.deepEqual, [4], ['4'])); +assert.throws(makeBlock(a.deepEqual, {a: 4}, {a: 4, b: true}), + a.AssertionError); +assert.doesNotThrow(makeBlock(a.deepEqual, ['a'], {0: 'a'})); +//(although not necessarily the same order), +assert.doesNotThrow(makeBlock(a.deepEqual, {a: 4, b: '1'}, {b: '1', a: 4})); +var a1 = [1, 2, 3]; +var a2 = [1, 2, 3]; +a1.a = 'test'; +a1.b = true; +a2.b = true; +a2.a = 'test'; +assert.throws(makeBlock(a.deepEqual, Object.keys(a1), Object.keys(a2)), + a.AssertionError); +assert.doesNotThrow(makeBlock(a.deepEqual, a1, a2)); + +// having an identical prototype property +var nbRoot = { + toString: function() { return this.first + ' ' + this.last; } +}; + +function nameBuilder(first, last) { + this.first = first; + this.last = last; + return this; +} +nameBuilder.prototype = nbRoot; + +function nameBuilder2(first, last) { + this.first = first; + this.last = last; + return this; +} +nameBuilder2.prototype = nbRoot; + +var nb1 = new nameBuilder('Ryan', 'Dahl'); +var nb2 = new nameBuilder2('Ryan', 'Dahl'); + +assert.doesNotThrow(makeBlock(a.deepEqual, nb1, nb2)); + +nameBuilder2.prototype = Object; +nb2 = new nameBuilder2('Ryan', 'Dahl'); +assert.throws(makeBlock(a.deepEqual, nb1, nb2), a.AssertionError); + +// String literal + object blew up my implementation... +assert.throws(makeBlock(a.deepEqual, 'a', {}), a.AssertionError); + +// Testing the throwing +function thrower(errorConstructor) { + throw new errorConstructor('test'); +} +var aethrow = makeBlock(thrower, a.AssertionError); +aethrow = makeBlock(thrower, a.AssertionError); + +// the basic calls work +assert.throws(makeBlock(thrower, a.AssertionError), + a.AssertionError, 'message'); +assert.throws(makeBlock(thrower, a.AssertionError), a.AssertionError); +assert.throws(makeBlock(thrower, a.AssertionError)); + +// if not passing an error, catch all. +assert.throws(makeBlock(thrower, TypeError)); + +// when passing a type, only catch errors of the appropriate type +var threw = false; +try { + a.throws(makeBlock(thrower, TypeError), a.AssertionError); +} catch (e) { + threw = true; + assert.ok(e instanceof TypeError, 'type'); +} +assert.equal(true, threw, + 'a.throws with an explicit error is eating extra errors', + a.AssertionError); +threw = false; + +// doesNotThrow should pass through all errors +try { + a.doesNotThrow(makeBlock(thrower, TypeError), a.AssertionError); +} catch (e) { + threw = true; + assert.ok(e instanceof TypeError); +} +assert.equal(true, threw, + 'a.doesNotThrow with an explicit error is eating extra errors'); + +// key difference is that throwing our correct error makes an assertion error +try { + a.doesNotThrow(makeBlock(thrower, TypeError), TypeError); +} catch (e) { + threw = true; + assert.ok(e instanceof a.AssertionError); +} +assert.equal(true, threw, + 'a.doesNotThrow is not catching type matching errors'); + +assert.throws(function() {assert.ifError(new Error('test error'))}); +assert.doesNotThrow(function() {assert.ifError(null)}); +assert.doesNotThrow(function() {assert.ifError()}); + +// make sure that validating using constructor really works +threw = false; +try { + assert.throws( + function() { + throw ({}); + }, + Array + ); +} catch (e) { + threw = true; +} +assert.ok(threw, 'wrong constructor validation'); + +// use a RegExp to validate error message +a.throws(makeBlock(thrower, TypeError), /test/); + +// use a fn to validate error object +a.throws(makeBlock(thrower, TypeError), function(err) { + if ((err instanceof TypeError) && /test/.test(err)) { + return true; + } +}); + + +// GH-207. Make sure deepEqual doesn't loop forever on circular refs + +var b = {}; +b.b = b; + +var c = {}; +c.b = c; + +var gotError = false; +try { + assert.deepEqual(b, c); +} catch (e) { + gotError = true; +} + +console.log('All OK'); +assert.ok(gotError); + + +// #217 +function testAssertionMessage(actual, expected) { + try { + assert.equal(actual, ''); + } catch (e) { + assert.equal(e.toString(), + ['AssertionError:', expected, '==', '""'].join(' ')); + } +} +testAssertionMessage(undefined, '"undefined"'); +testAssertionMessage(null, 'null'); +testAssertionMessage(true, 'true'); +testAssertionMessage(false, 'false'); +testAssertionMessage(0, '0'); +testAssertionMessage(100, '100'); +testAssertionMessage(NaN, '"NaN"'); +testAssertionMessage(Infinity, '"Infinity"'); +testAssertionMessage(-Infinity, '"-Infinity"'); +testAssertionMessage('', '""'); +testAssertionMessage('foo', '"foo"'); +testAssertionMessage([], '[]'); +testAssertionMessage([1, 2, 3], '[1,2,3]'); +testAssertionMessage(/a/, '"/a/"'); +testAssertionMessage(/abc/gim, '"/abc/gim"'); +testAssertionMessage(function f() {}, '"function f() {}"'); +testAssertionMessage({}, '{}'); +testAssertionMessage({a: undefined, b: null}, '{"a":"undefined","b":null}'); +testAssertionMessage({a: NaN, b: Infinity, c: -Infinity}, + '{"a":"NaN","b":"Infinity","c":"-Infinity"}'); + +// #2893 +try { + assert.throws(function () { + assert.ifError(null); + }); +} catch (e) { + threw = true; + assert.equal(e.message, 'Missing expected exception..'); +} +assert.ok(threw); diff --git a/node-v0.8.14/test/simple/test-bad-unicode.js b/node-v0.8.14/test/simple/test-bad-unicode.js new file mode 100644 index 0000000..0e57909 --- /dev/null +++ b/node-v0.8.14/test/simple/test-bad-unicode.js @@ -0,0 +1,31 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var assert = require('assert'), + exception = null; + +try { + eval('"\\uc/ef"'); +} catch (e) { + exception = e; +} + +assert(exception instanceof SyntaxError); diff --git a/node-v0.8.14/test/simple/test-buffer-concat.js b/node-v0.8.14/test/simple/test-buffer-concat.js new file mode 100644 index 0000000..858d692 --- /dev/null +++ b/node-v0.8.14/test/simple/test-buffer-concat.js @@ -0,0 +1,41 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); + +var zero = []; +var one = [ new Buffer('asdf') ]; +var long = []; +for (var i = 0; i < 10; i++) long.push(new Buffer('asdf')); + +var flatZero = Buffer.concat(zero); +var flatOne = Buffer.concat(one); +var flatLong = Buffer.concat(long); +var flatLongLen = Buffer.concat(long, 40); + +assert(flatZero.length === 0); +assert(flatOne.toString() === 'asdf'); +assert(flatOne === one[0]); +assert(flatLong.toString() === (new Array(10+1).join('asdf'))); +assert(flatLongLen.toString() === (new Array(10+1).join('asdf'))); + +console.log("ok"); diff --git a/node-v0.8.14/test/simple/test-buffer-regress-GH-2659.js b/node-v0.8.14/test/simple/test-buffer-regress-GH-2659.js new file mode 100644 index 0000000..19a1362 --- /dev/null +++ b/node-v0.8.14/test/simple/test-buffer-regress-GH-2659.js @@ -0,0 +1,30 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); + +// This is not a great test. It depends on a Node internal, namely the slab +// size. Maybe we should expose that in some way. Then again, maybe not... +for (var n = 1; n <= 8192; ++n) { + Buffer(n); + Buffer(0).write('', 'base64'); +} diff --git a/node-v0.8.14/test/simple/test-buffer.js b/node-v0.8.14/test/simple/test-buffer.js new file mode 100644 index 0000000..e423c76 --- /dev/null +++ b/node-v0.8.14/test/simple/test-buffer.js @@ -0,0 +1,739 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); + +var Buffer = require('buffer').Buffer; + +var b = Buffer(1024); // safe constructor + +console.log('b.length == ' + b.length); +assert.strictEqual(1024, b.length); + +b[0] = -1; +assert.equal(b[0], 255); + +for (var i = 0; i < 1024; i++) { + b[i] = i % 256; +} + +for (var i = 0; i < 1024; i++) { + assert.equal(i % 256, b[i]); +} + +var c = new Buffer(512); +console.log('c.length == %d', c.length); +assert.strictEqual(512, c.length); + +// copy 512 bytes, from 0 to 512. +var copied = b.copy(c, 0, 0, 512); +console.log('copied ' + copied + ' bytes from b into c'); +assert.equal(512, copied); +for (var i = 0; i < c.length; i++) { + common.print('.'); + assert.equal(i % 256, c[i]); +} +console.log(''); + +// try to copy 513 bytes, and hope we don't overrun c, which is only 512 long +var copied = b.copy(c, 0, 0, 513); +console.log('copied ' + copied + ' bytes from b into c'); +assert.strictEqual(512, copied); +for (var i = 0; i < c.length; i++) { + assert.equal(i % 256, c[i]); +} + +// copy all of c back into b, without specifying sourceEnd +var copied = c.copy(b, 0, 0); +console.log('copied ' + copied + ' bytes from c back into b'); +assert.strictEqual(512, copied); +for (var i = 0; i < b.length; i++) { + assert.equal(i % 256, b[i]); +} + +// copy 768 bytes from b into b +var copied = b.copy(b, 0, 256, 1024); +console.log('copied ' + copied + ' bytes from b into c'); +assert.strictEqual(768, copied); +for (var i = 0; i < c.length; i++) { + assert.equal(i % 256, c[i]); +} + +var caught_error = null; + +// try to copy from before the beginning of b +caught_error = null; +try { + var copied = b.copy(c, 0, 100, 10); +} catch (err) { + caught_error = err; +} +assert.strictEqual('sourceEnd < sourceStart', caught_error.message); + +// try to copy to before the beginning of c +caught_error = null; +try { + var copied = b.copy(c, -1, 0, 10); +} catch (err) { + caught_error = err; +} +assert.strictEqual('targetStart out of bounds', caught_error.message); + +// try to copy to after the end of c +caught_error = null; +try { + var copied = b.copy(c, 512, 0, 10); +} catch (err) { + caught_error = err; +} +assert.strictEqual('targetStart out of bounds', caught_error.message); + +// try to copy starting before the beginning of b +caught_error = null; +try { + var copied = b.copy(c, 0, -1, 1); +} catch (err) { + caught_error = err; +} +assert.strictEqual('sourceStart out of bounds', caught_error.message); + +// try to copy starting after the end of b +caught_error = null; +try { + var copied = b.copy(c, 0, 1024, 1025); +} catch (err) { + caught_error = err; +} +assert.strictEqual('sourceStart out of bounds', caught_error.message); + +// a too-low sourceEnd will get caught by earlier checks + +// try to copy ending after the end of b +try { + var copied = b.copy(c, 0, 1023, 1025); +} catch (err) { + caught_error = err; +} +assert.strictEqual('sourceEnd out of bounds', caught_error.message); + +// try to create 0-length buffers +new Buffer(''); +new Buffer('', 'ascii'); +new Buffer('', 'binary'); +new Buffer(0); + +// try to write a 0-length string beyond the end of b +b.write('', 1024); +b.write('', 2048); + +// try to copy 0 bytes worth of data into an empty buffer +b.copy(new Buffer(0), 0, 0, 0); + +// try to copy 0 bytes past the end of the target buffer +b.copy(new Buffer(0), 1, 1, 1); +b.copy(new Buffer(1), 1, 1, 1); + +// try to copy 0 bytes from past the end of the source buffer +b.copy(new Buffer(1), 0, 2048, 2048); + +// try to toString() a 0-length slice of a buffer, both within and without the +// valid buffer range +assert.equal(new Buffer('abc').toString('ascii', 0, 0), ''); +assert.equal(new Buffer('abc').toString('ascii', -100, -100), ''); +assert.equal(new Buffer('abc').toString('ascii', 100, 100), ''); + +// try toString() with a object as a encoding +assert.equal(new Buffer('abc').toString({toString: function() { + return 'ascii'; +}}), 'abc'); + +// testing for smart defaults and ability to pass string values as offset +var writeTest = new Buffer('abcdes'); +writeTest.write('n', 'ascii'); +writeTest.write('o', 'ascii', '1'); +writeTest.write('d', '2', 'ascii'); +writeTest.write('e', 3, 'ascii'); +writeTest.write('j', 'ascii', 4); +assert.equal(writeTest.toString(), 'nodejs'); + +var asciiString = 'hello world'; +var offset = 100; +for (var j = 0; j < 500; j++) { + + for (var i = 0; i < asciiString.length; i++) { + b[i] = asciiString.charCodeAt(i); + } + var asciiSlice = b.toString('ascii', 0, asciiString.length); + assert.equal(asciiString, asciiSlice); + + var written = b.write(asciiString, offset, 'ascii'); + assert.equal(asciiString.length, written); + var asciiSlice = b.toString('ascii', offset, offset + asciiString.length); + assert.equal(asciiString, asciiSlice); + + var sliceA = b.slice(offset, offset + asciiString.length); + var sliceB = b.slice(offset, offset + asciiString.length); + for (var i = 0; i < asciiString.length; i++) { + assert.equal(sliceA[i], sliceB[i]); + } + + // TODO utf8 slice tests +} + + +for (var j = 0; j < 100; j++) { + var slice = b.slice(100, 150); + assert.equal(50, slice.length); + for (var i = 0; i < 50; i++) { + assert.equal(b[100 + i], slice[i]); + } +} + + + +// Bug regression test +var testValue = '\u00F6\u65E5\u672C\u8A9E'; // ö日本語 +var buffer = new Buffer(32); +var size = buffer.write(testValue, 0, 'utf8'); +console.log('bytes written to buffer: ' + size); +var slice = buffer.toString('utf8', 0, size); +assert.equal(slice, testValue); + + +// Test triple slice +var a = new Buffer(8); +for (var i = 0; i < 8; i++) a[i] = i; +var b = a.slice(4, 8); +assert.equal(4, b[0]); +assert.equal(5, b[1]); +assert.equal(6, b[2]); +assert.equal(7, b[3]); +var c = b.slice(2, 4); +assert.equal(6, c[0]); +assert.equal(7, c[1]); + + +var d = new Buffer([23, 42, 255]); +assert.equal(d.length, 3); +assert.equal(d[0], 23); +assert.equal(d[1], 42); +assert.equal(d[2], 255); +assert.deepEqual(d, new Buffer(d)); + +var e = new Buffer('über'); +console.error('uber: \'%s\'', e.toString()); +assert.deepEqual(e, new Buffer([195, 188, 98, 101, 114])); + +var f = new Buffer('über', 'ascii'); +console.error('f.length: %d (should be 4)', f.length); +assert.deepEqual(f, new Buffer([252, 98, 101, 114])); + +['ucs2', 'ucs-2', 'utf16le', 'utf-16le'].forEach(function(encoding) { + var f = new Buffer('über', encoding); + console.error('f.length: %d (should be 8)', f.length); + assert.deepEqual(f, new Buffer([252, 0, 98, 0, 101, 0, 114, 0])); + + var f = new Buffer('привет', encoding); + console.error('f.length: %d (should be 12)', f.length); + assert.deepEqual(f, new Buffer([63, 4, 64, 4, 56, 4, 50, 4, 53, 4, 66, 4])); + assert.equal(f.toString(encoding), 'привет'); + + var f = new Buffer([0, 0, 0, 0, 0]); + assert.equal(f.length, 5); + var size = f.write('あいうえお', encoding); + var charsWritten = Buffer._charsWritten; // Copy value out. + console.error('bytes written to buffer: %d (should be 4)', size); + console.error('chars written to buffer: %d (should be 2)', charsWritten); + assert.equal(size, 4); + assert.equal(charsWritten, 2); + assert.deepEqual(f, new Buffer([0x42, 0x30, 0x44, 0x30, 0x00])); +}); + +var f = new Buffer('\uD83D\uDC4D', 'utf-16le'); // THUMBS UP SIGN (U+1F44D) +assert.equal(f.length, 4); +assert.deepEqual(f, new Buffer('3DD84DDC', 'hex')); + + +var arrayIsh = {0: 0, 1: 1, 2: 2, 3: 3, length: 4}; +var g = new Buffer(arrayIsh); +assert.deepEqual(g, new Buffer([0, 1, 2, 3])); +var strArrayIsh = {0: '0', 1: '1', 2: '2', 3: '3', length: 4}; +g = new Buffer(strArrayIsh); +assert.deepEqual(g, new Buffer([0, 1, 2, 3])); + + +// +// Test toString('base64') +// +assert.equal('TWFu', (new Buffer('Man')).toString('base64')); + +// test that regular and URL-safe base64 both work +var expected = [0xff, 0xff, 0xbe, 0xff, 0xef, 0xbf, 0xfb, 0xef, 0xff]; +assert.deepEqual(Buffer('//++/++/++//', 'base64'), Buffer(expected)); +assert.deepEqual(Buffer('__--_--_--__', 'base64'), Buffer(expected)); + +// big example +var quote = 'Man is distinguished, not only by his reason, but by this ' + + 'singular passion from other animals, which is a lust ' + + 'of the mind, that by a perseverance of delight in the continued ' + + 'and indefatigable generation of knowledge, exceeds the short ' + + 'vehemence of any carnal pleasure.'; +var expected = 'TWFuIGlzIGRpc3Rpbmd1aXNoZWQsIG5vdCBvbmx5IGJ5IGhpcyByZWFzb24s' + + 'IGJ1dCBieSB0aGlzIHNpbmd1bGFyIHBhc3Npb24gZnJvbSBvdGhlciBhbmltY' + + 'WxzLCB3aGljaCBpcyBhIGx1c3Qgb2YgdGhlIG1pbmQsIHRoYXQgYnkgYSBwZX' + + 'JzZXZlcmFuY2Ugb2YgZGVsaWdodCBpbiB0aGUgY29udGludWVkIGFuZCBpbmR' + + 'lZmF0aWdhYmxlIGdlbmVyYXRpb24gb2Yga25vd2xlZGdlLCBleGNlZWRzIHRo' + + 'ZSBzaG9ydCB2ZWhlbWVuY2Ugb2YgYW55IGNhcm5hbCBwbGVhc3VyZS4='; +assert.equal(expected, (new Buffer(quote)).toString('base64')); + + +b = new Buffer(1024); +var bytesWritten = b.write(expected, 0, 'base64'); +assert.equal(quote.length, bytesWritten); +assert.equal(quote, b.toString('ascii', 0, quote.length)); + +// check that the base64 decoder ignores whitespace +var expectedWhite = expected.slice(0, 60) + ' \n' + + expected.slice(60, 120) + ' \n' + + expected.slice(120, 180) + ' \n' + + expected.slice(180, 240) + ' \n' + + expected.slice(240, 300) + '\n' + + expected.slice(300, 360) + '\n'; +b = new Buffer(1024); +bytesWritten = b.write(expectedWhite, 0, 'base64'); +assert.equal(quote.length, bytesWritten); +assert.equal(quote, b.toString('ascii', 0, quote.length)); + +// check that the base64 decoder on the constructor works +// even in the presence of whitespace. +b = new Buffer(expectedWhite, 'base64'); +assert.equal(quote.length, b.length); +assert.equal(quote, b.toString('ascii', 0, quote.length)); + +// check that the base64 decoder ignores illegal chars +var expectedIllegal = expected.slice(0, 60) + ' \x80' + + expected.slice(60, 120) + ' \xff' + + expected.slice(120, 180) + ' \x00' + + expected.slice(180, 240) + ' \x98' + + expected.slice(240, 300) + '\x03' + + expected.slice(300, 360); +b = new Buffer(expectedIllegal, 'base64'); +assert.equal(quote.length, b.length); +assert.equal(quote, b.toString('ascii', 0, quote.length)); + + +assert.equal(new Buffer('', 'base64').toString(), ''); +assert.equal(new Buffer('K', 'base64').toString(), ''); + +// multiple-of-4 with padding +assert.equal(new Buffer('Kg==', 'base64').toString(), '*'); +assert.equal(new Buffer('Kio=', 'base64').toString(), '**'); +assert.equal(new Buffer('Kioq', 'base64').toString(), '***'); +assert.equal(new Buffer('KioqKg==', 'base64').toString(), '****'); +assert.equal(new Buffer('KioqKio=', 'base64').toString(), '*****'); +assert.equal(new Buffer('KioqKioq', 'base64').toString(), '******'); +assert.equal(new Buffer('KioqKioqKg==', 'base64').toString(), '*******'); +assert.equal(new Buffer('KioqKioqKio=', 'base64').toString(), '********'); +assert.equal(new Buffer('KioqKioqKioq', 'base64').toString(), '*********'); +assert.equal(new Buffer('KioqKioqKioqKg==', 'base64').toString(), + '**********'); +assert.equal(new Buffer('KioqKioqKioqKio=', 'base64').toString(), + '***********'); +assert.equal(new Buffer('KioqKioqKioqKioq', 'base64').toString(), + '************'); +assert.equal(new Buffer('KioqKioqKioqKioqKg==', 'base64').toString(), + '*************'); +assert.equal(new Buffer('KioqKioqKioqKioqKio=', 'base64').toString(), + '**************'); +assert.equal(new Buffer('KioqKioqKioqKioqKioq', 'base64').toString(), + '***************'); +assert.equal(new Buffer('KioqKioqKioqKioqKioqKg==', 'base64').toString(), + '****************'); +assert.equal(new Buffer('KioqKioqKioqKioqKioqKio=', 'base64').toString(), + '*****************'); +assert.equal(new Buffer('KioqKioqKioqKioqKioqKioq', 'base64').toString(), + '******************'); +assert.equal(new Buffer('KioqKioqKioqKioqKioqKioqKg==', 'base64').toString(), + '*******************'); +assert.equal(new Buffer('KioqKioqKioqKioqKioqKioqKio=', 'base64').toString(), + '********************'); + +// no padding, not a multiple of 4 +assert.equal(new Buffer('Kg', 'base64').toString(), '*'); +assert.equal(new Buffer('Kio', 'base64').toString(), '**'); +assert.equal(new Buffer('KioqKg', 'base64').toString(), '****'); +assert.equal(new Buffer('KioqKio', 'base64').toString(), '*****'); +assert.equal(new Buffer('KioqKioqKg', 'base64').toString(), '*******'); +assert.equal(new Buffer('KioqKioqKio', 'base64').toString(), '********'); +assert.equal(new Buffer('KioqKioqKioqKg', 'base64').toString(), '**********'); +assert.equal(new Buffer('KioqKioqKioqKio', 'base64').toString(), '***********'); +assert.equal(new Buffer('KioqKioqKioqKioqKg', 'base64').toString(), + '*************'); +assert.equal(new Buffer('KioqKioqKioqKioqKio', 'base64').toString(), + '**************'); +assert.equal(new Buffer('KioqKioqKioqKioqKioqKg', 'base64').toString(), + '****************'); +assert.equal(new Buffer('KioqKioqKioqKioqKioqKio', 'base64').toString(), + '*****************'); +assert.equal(new Buffer('KioqKioqKioqKioqKioqKioqKg', 'base64').toString(), + '*******************'); +assert.equal(new Buffer('KioqKioqKioqKioqKioqKioqKio', 'base64').toString(), + '********************'); + +// handle padding graciously, multiple-of-4 or not +assert.equal(new Buffer('72INjkR5fchcxk9+VgdGPFJDxUBFR5/rMFsghgxADiw==', + 'base64').length, 32); +assert.equal(new Buffer('72INjkR5fchcxk9+VgdGPFJDxUBFR5/rMFsghgxADiw=', + 'base64').length, 32); +assert.equal(new Buffer('72INjkR5fchcxk9+VgdGPFJDxUBFR5/rMFsghgxADiw', + 'base64').length, 32); +assert.equal(new Buffer('w69jACy6BgZmaFvv96HG6MYksWytuZu3T1FvGnulPg==', + 'base64').length, 31); +assert.equal(new Buffer('w69jACy6BgZmaFvv96HG6MYksWytuZu3T1FvGnulPg=', + 'base64').length, 31); +assert.equal(new Buffer('w69jACy6BgZmaFvv96HG6MYksWytuZu3T1FvGnulPg', + 'base64').length, 31); + +// This string encodes single '.' character in UTF-16 +var dot = new Buffer('//4uAA==', 'base64'); +assert.equal(dot[0], 0xff); +assert.equal(dot[1], 0xfe); +assert.equal(dot[2], 0x2e); +assert.equal(dot[3], 0x00); +assert.equal(dot.toString('base64'), '//4uAA=='); + +// Writing base64 at a position > 0 should not mangle the result. +// +// https://github.com/joyent/node/issues/402 +var segments = ['TWFkbmVzcz8h', 'IFRoaXM=', 'IGlz', 'IG5vZGUuanMh']; +var buf = new Buffer(64); +var pos = 0; + +for (var i = 0; i < segments.length; ++i) { + pos += b.write(segments[i], pos, 'base64'); +} +assert.equal(b.toString('binary', 0, pos), 'Madness?! This is node.js!'); + +// Creating buffers larger than pool size. +var l = Buffer.poolSize + 5; +var s = ''; +for (i = 0; i < l; i++) { + s += 'h'; +} + +var b = new Buffer(s); + +for (i = 0; i < l; i++) { + assert.equal('h'.charCodeAt(0), b[i]); +} + +var sb = b.toString(); +assert.equal(sb.length, s.length); +assert.equal(sb, s); + + +// Single argument slice +b = new Buffer('abcde'); +assert.equal('bcde', b.slice(1).toString()); + +// byte length +assert.equal(14, Buffer.byteLength('Il était tué')); +assert.equal(14, Buffer.byteLength('Il était tué', 'utf8')); +['ucs2', 'ucs-2', 'utf16le', 'utf-16le'].forEach(function(encoding) { + assert.equal(24, Buffer.byteLength('Il était tué', encoding)); +}); +assert.equal(12, Buffer.byteLength('Il était tué', 'ascii')); +assert.equal(12, Buffer.byteLength('Il était tué', 'binary')); + +// slice(0,0).length === 0 +assert.equal(0, Buffer('hello').slice(0, 0).length); + +// test hex toString +console.log('Create hex string from buffer'); +var hexb = new Buffer(256); +for (var i = 0; i < 256; i++) { + hexb[i] = i; +} +var hexStr = hexb.toString('hex'); +assert.equal(hexStr, + '000102030405060708090a0b0c0d0e0f' + + '101112131415161718191a1b1c1d1e1f' + + '202122232425262728292a2b2c2d2e2f' + + '303132333435363738393a3b3c3d3e3f' + + '404142434445464748494a4b4c4d4e4f' + + '505152535455565758595a5b5c5d5e5f' + + '606162636465666768696a6b6c6d6e6f' + + '707172737475767778797a7b7c7d7e7f' + + '808182838485868788898a8b8c8d8e8f' + + '909192939495969798999a9b9c9d9e9f' + + 'a0a1a2a3a4a5a6a7a8a9aaabacadaeaf' + + 'b0b1b2b3b4b5b6b7b8b9babbbcbdbebf' + + 'c0c1c2c3c4c5c6c7c8c9cacbcccdcecf' + + 'd0d1d2d3d4d5d6d7d8d9dadbdcdddedf' + + 'e0e1e2e3e4e5e6e7e8e9eaebecedeeef' + + 'f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff'); + +console.log('Create buffer from hex string'); +var hexb2 = new Buffer(hexStr, 'hex'); +for (var i = 0; i < 256; i++) { + assert.equal(hexb2[i], hexb[i]); +} + +// test an invalid slice end. +console.log('Try to slice off the end of the buffer'); +var b = new Buffer([1, 2, 3, 4, 5]); +var b2 = b.toString('hex', 1, 10000); +var b3 = b.toString('hex', 1, 5); +var b4 = b.toString('hex', 1); +assert.equal(b2, b3); +assert.equal(b2, b4); + + +// Test slice on SlowBuffer GH-843 +var SlowBuffer = process.binding('buffer').SlowBuffer; + +function buildSlowBuffer(data) { + if (Array.isArray(data)) { + var buffer = new SlowBuffer(data.length); + data.forEach(function(v, k) { + buffer[k] = v; + }); + return buffer; + } + return null; +} + +var x = buildSlowBuffer([0x81, 0xa3, 0x66, 0x6f, 0x6f, 0xa3, 0x62, 0x61, 0x72]); + +console.log(x.inspect()); +assert.equal('', x.inspect()); + +var z = x.slice(4); +console.log(z.inspect()); +console.log(z.length); +assert.equal(5, z.length); +assert.equal(0x6f, z[0]); +assert.equal(0xa3, z[1]); +assert.equal(0x62, z[2]); +assert.equal(0x61, z[3]); +assert.equal(0x72, z[4]); + +var z = x.slice(0); +console.log(z.inspect()); +console.log(z.length); +assert.equal(z.length, x.length); + +var z = x.slice(0, 4); +console.log(z.inspect()); +console.log(z.length); +assert.equal(4, z.length); +assert.equal(0x81, z[0]); +assert.equal(0xa3, z[1]); + +var z = x.slice(0, 9); +console.log(z.inspect()); +console.log(z.length); +assert.equal(9, z.length); + +var z = x.slice(1, 4); +console.log(z.inspect()); +console.log(z.length); +assert.equal(3, z.length); +assert.equal(0xa3, z[0]); + +var z = x.slice(2, 4); +console.log(z.inspect()); +console.log(z.length); +assert.equal(2, z.length); +assert.equal(0x66, z[0]); +assert.equal(0x6f, z[1]); + +assert.equal(0, Buffer('hello').slice(0, 0).length); + +b = new Buffer(50); +b.fill('h'); +for (var i = 0; i < b.length; i++) { + assert.equal('h'.charCodeAt(0), b[i]); +} + +b.fill(0); +for (var i = 0; i < b.length; i++) { + assert.equal(0, b[i]); +} + +b.fill(1, 16, 32); +for (var i = 0; i < 16; i++) assert.equal(0, b[i]); +for (; i < 32; i++) assert.equal(1, b[i]); +for (; i < b.length; i++) assert.equal(0, b[i]); + +['ucs2', 'ucs-2', 'utf16le', 'utf-16le'].forEach(function(encoding) { + var b = new SlowBuffer(10); + b.write('あいうえお', encoding); + assert.equal(b.toString(encoding), 'あいうえお'); +}); + +// Binary encoding should write only one byte per character. +var b = Buffer([0xde, 0xad, 0xbe, 0xef]); +var s = String.fromCharCode(0xffff); +b.write(s, 0, 'binary'); +assert.equal(0xff, b[0]); +assert.equal(0xad, b[1]); +assert.equal(0xbe, b[2]); +assert.equal(0xef, b[3]); +s = String.fromCharCode(0xaaee); +b.write(s, 0, 'binary'); +assert.equal(0xee, b[0]); +assert.equal(0xad, b[1]); +assert.equal(0xbe, b[2]); +assert.equal(0xef, b[3]); + + +// This should not segfault the program. +assert.throws(function() { + new Buffer('"pong"', 0, 6, 8031, '127.0.0.1'); +}); + +// #1210 Test UTF-8 string includes null character +var buf = new Buffer('\0'); +assert.equal(buf.length, 1); +buf = new Buffer('\0\0'); +assert.equal(buf.length, 2); + +buf = new Buffer(2); +var written = buf.write(''); // 0byte +assert.equal(written, 0); +written = buf.write('\0'); // 1byte (v8 adds null terminator) +assert.equal(written, 1); +written = buf.write('a\0'); // 1byte * 2 +assert.equal(written, 2); +written = buf.write('あ'); // 3bytes +assert.equal(written, 0); +written = buf.write('\0あ'); // 1byte + 3bytes +assert.equal(written, 1); +written = buf.write('\0\0あ'); // 1byte * 2 + 3bytes +assert.equal(written, 2); + +buf = new Buffer(10); +written = buf.write('あいう'); // 3bytes * 3 (v8 adds null terminator) +assert.equal(written, 9); +written = buf.write('あいう\0'); // 3bytes * 3 + 1byte +assert.equal(written, 10); + +// #243 Test write() with maxLength +var buf = new Buffer(4); +buf.fill(0xFF); +var written = buf.write('abcd', 1, 2, 'utf8'); +console.log(buf); +assert.equal(written, 2); +assert.equal(buf[0], 0xFF); +assert.equal(buf[1], 0x61); +assert.equal(buf[2], 0x62); +assert.equal(buf[3], 0xFF); + +buf.fill(0xFF); +written = buf.write('abcd', 1, 4); +console.log(buf); +assert.equal(written, 3); +assert.equal(buf[0], 0xFF); +assert.equal(buf[1], 0x61); +assert.equal(buf[2], 0x62); +assert.equal(buf[3], 0x63); + +buf.fill(0xFF); +written = buf.write('abcd', 'utf8', 1, 2); // legacy style +console.log(buf); +assert.equal(written, 2); +assert.equal(buf[0], 0xFF); +assert.equal(buf[1], 0x61); +assert.equal(buf[2], 0x62); +assert.equal(buf[3], 0xFF); + +buf.fill(0xFF); +written = buf.write('abcdef', 1, 2, 'hex'); +console.log(buf); +assert.equal(written, 2); +assert.equal(buf[0], 0xFF); +assert.equal(buf[1], 0xAB); +assert.equal(buf[2], 0xCD); +assert.equal(buf[3], 0xFF); + +['ucs2', 'ucs-2', 'utf16le', 'utf-16le'].forEach(function(encoding) { + buf.fill(0xFF); + written = buf.write('abcd', 0, 2, encoding); + console.log(buf); + assert.equal(written, 2); + assert.equal(buf[0], 0x61); + assert.equal(buf[1], 0x00); + assert.equal(buf[2], 0xFF); + assert.equal(buf[3], 0xFF); +}); + +// test for buffer overrun +buf = new Buffer([0, 0, 0, 0, 0]); // length: 5 +var sub = buf.slice(0, 4); // length: 4 +written = sub.write('12345', 'binary'); +assert.equal(written, 4); +assert.equal(buf[4], 0); + +// test for _charsWritten +buf = new Buffer(9); +buf.write('あいうえ', 'utf8'); // 3bytes * 4 +assert.equal(Buffer._charsWritten, 3); +['ucs2', 'ucs-2', 'utf16le', 'utf-16le'].forEach(function(encoding) { + buf.write('あいうえお', encoding); // 2bytes * 5 + assert.equal(Buffer._charsWritten, 4); +}); +buf.write('0123456789', 'ascii'); +assert.equal(Buffer._charsWritten, 9); +buf.write('0123456789', 'binary'); +assert.equal(Buffer._charsWritten, 9); +buf.write('123456', 'base64'); +assert.equal(Buffer._charsWritten, 4); +buf.write('00010203040506070809', 'hex'); +assert.equal(Buffer._charsWritten, 18); + +// Check for fractional length args, junk length args, etc. +// https://github.com/joyent/node/issues/1758 +Buffer(3.3).toString(); // throws bad argument error in commit 43cb4ec +assert.equal(Buffer(-1).length, 0); +assert.equal(Buffer(NaN).length, 0); +assert.equal(Buffer(3.3).length, 4); +assert.equal(Buffer({length: 3.3}).length, 4); +assert.equal(Buffer({length: 'BAM'}).length, 0); + +// Make sure that strings are not coerced to numbers. +assert.equal(Buffer('99').length, 2); +assert.equal(Buffer('13.37').length, 5); + +// Ensure that the length argument is respected. +'ascii utf8 hex base64 binary'.split(' ').forEach(function(enc) { + assert.equal(Buffer(1).write('aaaaaa', 0, 1, enc), 1); +}); + +// Regression test, guard against buffer overrun in the base64 decoder. +var a = Buffer(3); +var b = Buffer('xxx'); +a.write('aaaaaaaa', 'base64'); +assert.equal(b.toString(), 'xxx'); + +// issue GH-3416 +Buffer(Buffer(0), 0, 0); diff --git a/node-v0.8.14/test/simple/test-c-ares.js b/node-v0.8.14/test/simple/test-c-ares.js new file mode 100644 index 0000000..7210dc2 --- /dev/null +++ b/node-v0.8.14/test/simple/test-c-ares.js @@ -0,0 +1,53 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); + +var dns = require('dns'); + + +// Try resolution without callback + +dns.lookup(null, function(error, result, addressType) { + assert.equal(null, result); + assert.equal(4, addressType); +}); + +dns.lookup('127.0.0.1', function(error, result, addressType) { + assert.equal('127.0.0.1', result); + assert.equal(4, addressType); +}); + +dns.lookup('::1', function(error, result, addressType) { + assert.equal('::1', result); + assert.equal(6, addressType); +}); + +// Windows doesn't usually have an entry for localhost 127.0.0.1 in +// C:\Windows\System32\drivers\etc\hosts +// so we disable this test on Windows. +if (process.platform != 'win32') { + dns.resolve('127.0.0.1', 'PTR', function(error, domains) { + if (error) throw error; + assert.ok(Array.isArray(domains)); + }); +} diff --git a/node-v0.8.14/test/simple/test-chdir.js b/node-v0.8.14/test/simple/test-chdir.js new file mode 100644 index 0000000..7454bee --- /dev/null +++ b/node-v0.8.14/test/simple/test-chdir.js @@ -0,0 +1,40 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var fs = require('fs'); +var path = require('path'); + +assert.equal(true, process.cwd() !== __dirname); + +process.chdir(__dirname); +assert.equal(true, process.cwd() === __dirname); + +var dir = path.resolve(common.fixturesDir, + 'weird \uc3a4\uc3ab\uc3af characters \u00e1\u00e2\u00e3'); +fs.mkdirSync(dir); +process.chdir(dir); +assert(process.cwd() == dir); + +process.chdir('..'); +assert(process.cwd() == path.resolve(common.fixturesDir)); +fs.rmdirSync(dir); diff --git a/node-v0.8.14/test/simple/test-child-process-buffering.js b/node-v0.8.14/test/simple/test-child-process-buffering.js new file mode 100644 index 0000000..3fb13b6 --- /dev/null +++ b/node-v0.8.14/test/simple/test-child-process-buffering.js @@ -0,0 +1,65 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); + +var spawn = require('child_process').spawn; + +var pwd_called = false; +var childClosed = false; +var childExited = false; + +function pwd(callback) { + var output = ''; + var child = common.spawnPwd(); + + child.stdout.setEncoding('utf8'); + child.stdout.on('data', function(s) { + console.log('stdout: ' + JSON.stringify(s)); + output += s; + }); + + child.on('exit', function(c) { + console.log('exit: ' + c); + assert.equal(0, c); + childExited = true; + }); + + child.on('close', function () { + callback(output); + pwd_called = true; + childClosed = true; + }); +} + + +pwd(function(result) { + console.dir(result); + assert.equal(true, result.length > 1); + assert.equal('\n', result[result.length - 1]); +}); + +process.on('exit', function() { + assert.equal(true, pwd_called); + assert.equal(true, childExited); + assert.equal(true, childClosed); +}); diff --git a/node-v0.8.14/test/simple/test-child-process-customfd-bounded.js b/node-v0.8.14/test/simple/test-child-process-customfd-bounded.js new file mode 100644 index 0000000..c1efd83 --- /dev/null +++ b/node-v0.8.14/test/simple/test-child-process-customfd-bounded.js @@ -0,0 +1,29 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); + +var bigish = Array(200); + +for (var i = 0, il = bigish.length; i < il; ++i) + bigish[i] = -1; + +common.spawnPwd({ customFds: bigish }); diff --git a/node-v0.8.14/test/simple/test-child-process-cwd.js b/node-v0.8.14/test/simple/test-child-process-cwd.js new file mode 100644 index 0000000..dc8283b --- /dev/null +++ b/node-v0.8.14/test/simple/test-child-process-cwd.js @@ -0,0 +1,81 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var spawn = require('child_process').spawn; +var path = require('path'); + +var returns = 0; + +/* + Spawns 'pwd' with given options, then test + - whether the exit code equals forCode, + - optionally whether the stdout result matches forData + (after removing traling whitespace) +*/ +function testCwd(options, forCode, forData) { + var data = ''; + + var child = common.spawnPwd(options); + + child.stdout.setEncoding('utf8'); + + child.stdout.on('data', function(chunk) { + data += chunk; + }); + + child.on('exit', function(code, signal) { + assert.strictEqual(forCode, code); + }); + + child.on('close', function () { + forData && assert.strictEqual(forData, data.replace(/[\s\r\n]+$/, '')); + returns--; + }); + + returns++; +} + +// Assume these exist, and 'pwd' gives us the right directory back +if (process.platform == 'win32') { + testCwd({cwd: process.env.windir}, 0, process.env.windir); + testCwd({cwd: 'c:\\'}, 0, 'c:\\'); +} else { + testCwd({cwd: '/dev'}, 0, '/dev'); + testCwd({cwd: '/'}, 0, '/'); +} + +// Assume this doesn't exist, we expect exitcode=127 +testCwd({cwd: 'does-not-exist'}, 127); + +// Spawn() shouldn't try to chdir() so this should just work +testCwd(undefined, 0); +testCwd({}, 0); +testCwd({cwd: ''}, 0); +testCwd({cwd: undefined}, 0); +testCwd({cwd: null}, 0); + +// Check whether all tests actually returned +assert.notEqual(0, returns); +process.on('exit', function() { + assert.equal(0, returns); +}); diff --git a/node-v0.8.14/test/simple/test-child-process-detached.js b/node-v0.8.14/test/simple/test-child-process-detached.js new file mode 100644 index 0000000..10ce5d1 --- /dev/null +++ b/node-v0.8.14/test/simple/test-child-process-detached.js @@ -0,0 +1,45 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var path = require('path'); + +var spawn = require('child_process').spawn; +var childPath = path.join(__dirname, '..', 'fixtures', 'parent-process-nonpersistent.js'); +var persistentPid = -1; + +var child = spawn(process.execPath, [ childPath ]); + +child.stdout.on('data', function (data) { + persistentPid = parseInt(data, 10); +}); + +process.on('exit', function () { + assert(persistentPid !== -1); + assert.throws(function () { + process.kill(child.pid); + }); + assert.doesNotThrow(function () { + process.kill(persistentPid); + }); +}); + diff --git a/node-v0.8.14/test/simple/test-child-process-disconnect.js b/node-v0.8.14/test/simple/test-child-process-disconnect.js new file mode 100644 index 0000000..2136aaf --- /dev/null +++ b/node-v0.8.14/test/simple/test-child-process-disconnect.js @@ -0,0 +1,106 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var assert = require('assert'); +var common = require('../common'); +var fork = require('child_process').fork; +var net = require('net'); + +// child +if (process.argv[2] === 'child') { + + var server = net.createServer(); + + server.on('connection', function(socket) { + + process.on('disconnect', function() { + socket.end((process.connected).toString()); + }); + + // when the socket is closed, we will close the server + // allowing the process to self terminate + socket.on('end', function() { + server.close(); + }); + + socket.write('ready'); + }); + + // when the server is ready tell parent + server.on('listening', function() { + process.send('ready'); + }); + + server.listen(common.PORT); + +} else { + // testcase + var child = fork(process.argv[1], ['child']); + + var childFlag = false; + var childSelfTerminate = false; + var parentEmit = false; + var parentFlag = false; + + // when calling .disconnect the event should emit + // and the disconnected flag should be true. + child.on('disconnect', function() { + parentEmit = true; + parentFlag = child.connected; + }); + + // the process should also self terminate without using signals + child.on('exit', function() { + childSelfTerminate = true; + }); + + // when child is listning + child.on('message', function(msg) { + if (msg === 'ready') { + + // connect to child using TCP to know if disconnect was emitted + var socket = net.connect(common.PORT); + + socket.on('data', function(data) { + data = data.toString(); + + // ready to be disconnected + if (data === 'ready') { + child.disconnect(); + assert.throws(child.disconnect.bind(child), Error); + return; + } + + // disconnect is emitted + childFlag = (data === 'true'); + }); + + } + }); + + process.on('exit', function() { + assert.equal(childFlag, false); + assert.equal(parentFlag, false); + + assert.ok(childSelfTerminate); + assert.ok(parentEmit); + }); +} diff --git a/node-v0.8.14/test/simple/test-child-process-double-pipe.js b/node-v0.8.14/test/simple/test-child-process-double-pipe.js new file mode 100644 index 0000000..84fbf4f --- /dev/null +++ b/node-v0.8.14/test/simple/test-child-process-double-pipe.js @@ -0,0 +1,117 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var is_windows = process.platform === 'win32'; + +var common = require('../common'); +var assert = require('assert'), + util = require('util'), + spawn = require('child_process').spawn; + +// We're trying to reproduce: +// $ echo "hello\nnode\nand\nworld" | grep o | sed s/o/a/ + +var grep = spawn('grep', ['o']), + sed = spawn('sed', ['s/o/O/']), + echo; + +if (is_windows) { + echo = spawn('cmd.exe', + ['/c', 'echo', 'hello&&', 'echo', + 'node&&', 'echo', 'and&&', 'echo', 'world']); +} else { + echo = spawn('echo', ['hello\nnode\nand\nworld\n']); +} + +/* + * grep and sed hang if the spawn function leaks file descriptors to child + * processes. + * This happens when calling pipe(2) and then forgetting to set the + * FD_CLOEXEC flag on the resulting file descriptors. + * + * This test checks child processes exit, meaning they don't hang like + * explained above. + */ + + + +// pipe echo | grep +echo.stdout.on('data', function(data) { + console.error('grep stdin write ' + data.length); + if (!grep.stdin.write(data)) { + echo.stdout.pause(); + } +}); + +grep.stdin.on('drain', function(data) { + echo.stdout.resume(); +}); + +// propagate end from echo to grep +echo.stdout.on('end', function(code) { + grep.stdin.end(); +}); + +echo.on('exit', function() { + console.error('echo exit'); +}); + +grep.on('exit', function() { + console.error('grep exit'); +}); + +sed.on('exit', function() { + console.error('sed exit'); +}); + + + +// pipe grep | sed +grep.stdout.on('data', function(data) { + console.error('grep stdout ' + data.length); + if (!sed.stdin.write(data)) { + grep.stdout.pause(); + } +}); + +sed.stdin.on('drain', function(data) { + grep.stdout.resume(); +}); + +// propagate end from grep to sed +grep.stdout.on('end', function(code) { + console.error('grep stdout end'); + sed.stdin.end(); +}); + + + +var result = ''; + +// print sed's output +sed.stdout.on('data', function(data) { + result += data.toString('utf8', 0, data.length); + util.print(data); +}); + +sed.stdout.on('end', function(code) { + assert.equal(result, 'hellO\nnOde\nwOrld\n'); +}); diff --git a/node-v0.8.14/test/simple/test-child-process-env.js b/node-v0.8.14/test/simple/test-child-process-env.js new file mode 100644 index 0000000..caeb193 --- /dev/null +++ b/node-v0.8.14/test/simple/test-child-process-env.js @@ -0,0 +1,55 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); + +var spawn = require('child_process').spawn; + +var isWindows = process.platform === 'win32'; + +var env = { + 'HELLO': 'WORLD' +}; +env.__proto__ = { + 'FOO': 'BAR' +}; + +if (isWindows) { + var child = spawn('cmd.exe', ['/c', 'set'], {env: env}); +} else { + var child = spawn('/usr/bin/env', [], {env: env}); +} + + +var response = ''; + +child.stdout.setEncoding('utf8'); + +child.stdout.on('data', function(chunk) { + console.log('stdout: ' + chunk); + response += chunk; +}); + +process.on('exit', function() { + assert.ok(response.indexOf('HELLO=WORLD') >= 0); + assert.ok(response.indexOf('FOO=BAR') >= 0); +}); diff --git a/node-v0.8.14/test/simple/test-child-process-exec-cwd.js b/node-v0.8.14/test/simple/test-child-process-exec-cwd.js new file mode 100644 index 0000000..282faec --- /dev/null +++ b/node-v0.8.14/test/simple/test-child-process-exec-cwd.js @@ -0,0 +1,56 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +require('../common'); +var assert = require('assert'); +var exec = require('child_process').exec; + +var success_count = 0; +var error_count = 0; + +var pwdcommand, dir; + +if (process.platform == 'win32') { + pwdcommand = 'echo %cd%'; + dir = 'c:\\windows'; +} else { + pwdcommand = 'pwd'; + dir = '/dev'; +} + +var child = exec(pwdcommand, {cwd: dir}, function(err, stdout, stderr) { + if (err) { + error_count++; + console.log('error!: ' + err.code); + console.log('stdout: ' + JSON.stringify(stdout)); + console.log('stderr: ' + JSON.stringify(stderr)); + assert.equal(false, err.killed); + } else { + success_count++; + console.log(stdout); + assert.ok(stdout.indexOf(dir) == 0); + } +}); + +process.on('exit', function() { + assert.equal(1, success_count); + assert.equal(0, error_count); +}); diff --git a/node-v0.8.14/test/simple/test-child-process-exec-env.js b/node-v0.8.14/test/simple/test-child-process-exec-env.js new file mode 100644 index 0000000..b14ce74 --- /dev/null +++ b/node-v0.8.14/test/simple/test-child-process-exec-env.js @@ -0,0 +1,62 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + + + +var common = require('../common'); +var assert = require('assert'); +var exec = require('child_process').exec; +var success_count = 0; +var error_count = 0; +var response = ''; +var child; + +function after(err, stdout, stderr) { + if (err) { + error_count++; + console.log('error!: ' + err.code); + console.log('stdout: ' + JSON.stringify(stdout)); + console.log('stderr: ' + JSON.stringify(stderr)); + assert.equal(false, err.killed); + } else { + success_count++; + assert.equal(true, stdout != ''); + } +} + +if (process.platform !== 'win32') { + child = exec('/usr/bin/env', { env: { 'HELLO': 'WORLD' } }, after); +} else { + child = exec('set', { env: { 'HELLO': 'WORLD' } }, after); +} + +child.stdout.setEncoding('utf8'); +child.stdout.on('data', function(chunk) { + response += chunk; +}); + +process.on('exit', function() { + console.log('response: ', response); + assert.equal(1, success_count); + assert.equal(0, error_count); + assert.ok(response.indexOf('HELLO=WORLD') >= 0); +}); diff --git a/node-v0.8.14/test/simple/test-child-process-exit-code.js b/node-v0.8.14/test/simple/test-child-process-exit-code.js new file mode 100644 index 0000000..c0c2585 --- /dev/null +++ b/node-v0.8.14/test/simple/test-child-process-exit-code.js @@ -0,0 +1,53 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var spawn = require('child_process').spawn; +var path = require('path'); + +var exits = 0; + +var exitScript = path.join(common.fixturesDir, 'exit.js'); +var exitChild = spawn(process.argv[0], [exitScript, 23]); +exitChild.on('exit', function(code, signal) { + assert.strictEqual(code, 23); + assert.strictEqual(signal, null); + + exits++; +}); + + + +var errorScript = path.join(common.fixturesDir, + 'child_process_should_emit_error.js'); +var errorChild = spawn(process.argv[0], [errorScript]); +errorChild.on('exit', function(code, signal) { + assert.ok(code !== 0); + assert.strictEqual(signal, null); + + exits++; +}); + + +process.on('exit', function() { + assert.equal(2, exits); +}); diff --git a/node-v0.8.14/test/simple/test-child-process-fork-and-spawn.js b/node-v0.8.14/test/simple/test-child-process-fork-and-spawn.js new file mode 100644 index 0000000..989bf7e --- /dev/null +++ b/node-v0.8.14/test/simple/test-child-process-fork-and-spawn.js @@ -0,0 +1,53 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var spawn = require('child_process').spawn; +var fork = require('child_process').fork; + +// Fork, then spawn. The spawned process should not hang. +switch (process.argv[2] || '') { +case '': + fork(__filename, ['fork']).on('exit', checkExit); + process.on('exit', haveExit); + break; +case 'fork': + spawn(process.execPath, [__filename, 'spawn']).on('exit', checkExit); + process.on('exit', haveExit); + break; +case 'spawn': + break; +default: + assert(0); +} + +var seenExit = false; + +function checkExit(statusCode) { + seenExit = true; + assert.equal(statusCode, 0); + process.nextTick(process.exit); +} + +function haveExit() { + assert.equal(seenExit, true); +} diff --git a/node-v0.8.14/test/simple/test-child-process-fork-close.js b/node-v0.8.14/test/simple/test-child-process-fork-close.js new file mode 100644 index 0000000..342cffe --- /dev/null +++ b/node-v0.8.14/test/simple/test-child-process-fork-close.js @@ -0,0 +1,57 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var assert = require('assert'), + common = require('../common'), + fork = require('child_process').fork, + fork = require('child_process').fork; + +var cp = fork(common.fixturesDir + '/child-process-message-and-exit.js'); + +var gotMessage = false, + gotExit = false, + gotClose = false; + +cp.on('message', function(message) { + assert(!gotMessage); + assert(!gotClose); + assert.strictEqual(message, 'hello'); + gotMessage = true; +}); + +cp.on('exit', function() { + assert(!gotExit); + assert(!gotClose); + gotExit = true; +}); + +cp.on('close', function() { + assert(gotMessage); + assert(gotExit); + assert(!gotClose); + gotClose = true; +}); + +process.on('exit', function() { + assert(gotMessage); + assert(gotExit); + assert(gotClose); +}); diff --git a/node-v0.8.14/test/simple/test-child-process-fork-exec-argv.js b/node-v0.8.14/test/simple/test-child-process-fork-exec-argv.js new file mode 100644 index 0000000..2fbc379 --- /dev/null +++ b/node-v0.8.14/test/simple/test-child-process-fork-exec-argv.js @@ -0,0 +1,47 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var assert = require('assert'); +var child_process = require('child_process'); +var spawn = child_process.spawn; +var fork = child_process.fork; + +if (process.argv[2] === 'fork') { + process.stdout.write(JSON.stringify(process.execArgv), function() { + process.exit(); + }); +} else if (process.argv[2] === 'child') { + fork(__filename, ['fork']); +} else { + var execArgv = ['--harmony_proxies', '--max-stack-size=0']; + var args = [__filename, 'child', 'arg0']; + + var child = spawn(process.execPath, execArgv.concat(args)); + var out = ''; + + child.stdout.on('data', function (chunk) { + out += chunk; + }); + + child.on('exit', function () { + assert.deepEqual(JSON.parse(out), execArgv); + }); +} diff --git a/node-v0.8.14/test/simple/test-child-process-fork-net.js b/node-v0.8.14/test/simple/test-child-process-fork-net.js new file mode 100644 index 0000000..39b22d2 --- /dev/null +++ b/node-v0.8.14/test/simple/test-child-process-fork-net.js @@ -0,0 +1,205 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var assert = require('assert'); +var common = require('../common'); +var fork = require('child_process').fork; +var net = require('net'); + +// progress tracker +function ProgressTracker(missing, callback) { + this.missing = missing; + this.callback = callback; +} +ProgressTracker.prototype.done = function() { + this.missing -= 1; + this.check(); +}; +ProgressTracker.prototype.check = function() { + if (this.missing === 0) this.callback(); +}; + +if (process.argv[2] === 'child') { + + var serverScope; + + process.on('message', function onServer(msg, server) { + if (msg.what !== 'server') return; + process.removeListener('message', onServer); + + serverScope = server; + + server.on('connection', function(socket) { + console.log('CHILD: got connection'); + process.send({what: 'connection'}); + socket.destroy(); + }); + + // start making connection from parent + console.log('CHILD: server listening'); + process.send({what: 'listening'}); + }); + + process.on('message', function onClose(msg) { + if (msg.what !== 'close') return; + process.removeListener('message', onClose); + + serverScope.on('close', function() { + process.send({what: 'close'}); + }); + serverScope.close(); + }); + + process.on('message', function onSocket(msg, socket) { + if (msg.what !== 'socket') return; + process.removeListener('message', onSocket); + socket.end('echo'); + console.log('CHILD: got socket'); + }); + + process.send({what: 'ready'}); +} else { + + var child = fork(process.argv[1], ['child']); + + child.on('exit', function() { + console.log('CHILD: died'); + }); + + // send net.Server to child and test by connecting + var testServer = function(callback) { + + // destroy server execute callback when done + var progress = new ProgressTracker(2, function() { + server.on('close', function() { + console.log('PARENT: server closed'); + child.send({what: 'close'}); + }); + server.close(); + }); + + // we expect 10 connections and close events + var connections = new ProgressTracker(10, progress.done.bind(progress)); + var closed = new ProgressTracker(10, progress.done.bind(progress)); + + // create server and send it to child + var server = net.createServer(); + server.on('connection', function(socket) { + console.log('PARENT: got connection'); + socket.destroy(); + connections.done(); + }); + server.on('listening', function() { + console.log('PARENT: server listening'); + child.send({what: 'server'}, server); + }); + server.listen(common.PORT); + + // handle client messages + var messageHandlers = function(msg) { + + if (msg.what === 'listening') { + // make connections + var socket; + for (var i = 0; i < 10; i++) { + socket = net.connect(common.PORT, function() { + console.log('CLIENT: connected'); + }); + socket.on('close', function() { + closed.done(); + console.log('CLIENT: closed'); + }); + } + + } else if (msg.what === 'connection') { + // child got connection + connections.done(); + } else if (msg.what === 'close') { + child.removeListener('message', messageHandlers); + callback(); + } + }; + + child.on('message', messageHandlers); + }; + + // send net.Socket to child + var testSocket = function(callback) { + + // create a new server and connect to it, + // but the socket will be handled by the child + var server = net.createServer(); + server.on('connection', function(socket) { + socket.on('close', function() { + console.log('CLIENT: socket closed'); + }); + child.send({what: 'socket'}, socket); + }); + server.on('close', function() { + console.log('PARENT: server closed'); + callback(); + }); + // don't listen on the same port, because SmartOS sometimes says + // that the server's fd is closed, but it still cannot listen + // on the same port again. + // + // An isolated test for this would be lovely, but for now, this + // will have to do. + server.listen(common.PORT + 1, function() { + console.error('testSocket, listening'); + var connect = net.connect(common.PORT + 1); + var store = ''; + connect.on('data', function(chunk) { + store += chunk; + console.log('CLIENT: got data'); + }); + connect.on('close', function() { + console.log('CLIENT: closed'); + assert.equal(store, 'echo'); + server.close(); + }); + }); + }; + + // create server and send it to child + var serverSucess = false; + var socketSucess = false; + child.on('message', function onReady(msg) { + if (msg.what !== 'ready') return; + child.removeListener('message', onReady); + + testServer(function() { + serverSucess = true; + + testSocket(function() { + socketSucess = true; + child.kill(); + }); + }); + + }); + + process.on('exit', function() { + assert.ok(serverSucess); + assert.ok(socketSucess); + }); + +} diff --git a/node-v0.8.14/test/simple/test-child-process-fork-net2.js b/node-v0.8.14/test/simple/test-child-process-fork-net2.js new file mode 100644 index 0000000..4871356 --- /dev/null +++ b/node-v0.8.14/test/simple/test-child-process-fork-net2.js @@ -0,0 +1,131 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var assert = require('assert'); +var common = require('../common'); +var fork = require('child_process').fork; +var net = require('net'); + +if (process.argv[2] === 'child') { + + var endMe = null; + + process.on('message', function(m, socket) { + if (!socket) return; + + // will call .end('end') or .write('write'); + socket[m](m); + + // store the unfinished socket + if (m === 'write') { + endMe = socket; + } + }); + + process.on('message', function(m) { + if (m !== 'close') return; + endMe.end('end'); + endMe = null; + }); + + process.on('disconnect', function() { + endMe.end('end'); + endMe = null; + }); + +} else { + + var child1 = fork(process.argv[1], ['child']); + var child2 = fork(process.argv[1], ['child']); + var child3 = fork(process.argv[1], ['child']); + + var server = net.createServer(); + + var connected = 0; + server.on('connection', function(socket) { + switch (connected) { + case 0: + child1.send('end', socket); break; + case 1: + child1.send('write', socket); break; + case 2: + child2.send('end', socket); break; + case 3: + child2.send('write', socket); break; + case 4: + child3.send('end', socket); break; + case 5: + child3.send('write', socket); break; + } + connected += 1; + + if (connected === 6) { + closeServer(); + } + }); + + var disconnected = 0; + server.on('listening', function() { + + var j = 6, client; + while (j--) { + client = net.connect(common.PORT, '127.0.0.1'); + client.on('close', function() { + disconnected += 1; + }); + } + }); + + var closeEmitted = false; + server.on('close', function() { + closeEmitted = true; + + child1.kill(); + child2.kill(); + child3.kill(); + }); + + server.listen(common.PORT, '127.0.0.1'); + + var timeElasped = 0; + var closeServer = function() { + var startTime = Date.now(); + server.on('close', function() { + timeElasped = Date.now() - startTime; + }); + + server.close(); + + setTimeout(function() { + child1.send('close'); + child2.send('close'); + child3.disconnect(); + }, 200); + }; + + process.on('exit', function() { + assert.equal(disconnected, 6); + assert.equal(connected, 6); + assert.ok(closeEmitted); + assert.ok(timeElasped >= 190 && timeElasped <= 1000, + 'timeElasped was not between 190 and 1000 ms'); + }); +} diff --git a/node-v0.8.14/test/simple/test-child-process-fork.js b/node-v0.8.14/test/simple/test-child-process-fork.js new file mode 100644 index 0000000..41cc28c --- /dev/null +++ b/node-v0.8.14/test/simple/test-child-process-fork.js @@ -0,0 +1,52 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var assert = require('assert'); +var common = require('../common'); +var fork = require('child_process').fork; +var args = ['foo', 'bar']; + +var n = fork(common.fixturesDir + '/child-process-spawn-node.js', args); +assert.deepEqual(args, ['foo', 'bar']); + +var messageCount = 0; + +n.on('message', function(m) { + console.log('PARENT got message:', m); + assert.ok(m.foo); + messageCount++; +}); + +// https://github.com/joyent/node/issues/2355 - JSON.stringify(undefined) +// returns "undefined" but JSON.parse() cannot parse that... +assert.throws(function() { n.send(undefined); }, TypeError); +assert.throws(function() { n.send(); }, TypeError); + +n.send({ hello: 'world' }); + +var childExitCode = -1; +n.on('exit', function(c) { + childExitCode = c; +}); + +process.on('exit', function() { + assert.ok(childExitCode == 0); +}); diff --git a/node-v0.8.14/test/simple/test-child-process-fork2.js b/node-v0.8.14/test/simple/test-child-process-fork2.js new file mode 100644 index 0000000..6add596 --- /dev/null +++ b/node-v0.8.14/test/simple/test-child-process-fork2.js @@ -0,0 +1,73 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var assert = require('assert'); +var common = require('../common'); +var fork = require('child_process').fork; +var net = require('net'); + +var socketCloses = 0; +var N = 10; + +var n = fork(common.fixturesDir + '/fork2.js'); + +var messageCount = 0; + +var server = new net.Server(function(c) { + console.log('PARENT got connection'); + c.destroy(); +}); + +server.listen(common.PORT, /* backlog */ 9, function() { + console.log('PARENT send child server handle'); + n.send({ hello: 'world' }, server._handle); +}); + +function makeConnections() { + for (var i = 0; i < N; i++) { + var socket = net.connect(common.PORT, function() { + console.log('CLIENT connected'); + }); + + socket.on('close', function() { + socketCloses++; + console.log('CLIENT closed ' + socketCloses); + if (socketCloses == N) { + n.kill(); + server.close(); + } + }); + } +} + +n.on('message', function(m) { + console.log('PARENT got message:', m); + if (m.gotHandle) { + makeConnections(); + } + messageCount++; +}); + +process.on('exit', function() { + assert.equal(10, socketCloses); + assert.ok(messageCount > 1); +}); + diff --git a/node-v0.8.14/test/simple/test-child-process-internal.js b/node-v0.8.14/test/simple/test-child-process-internal.js new file mode 100644 index 0000000..dd7ce55 --- /dev/null +++ b/node-v0.8.14/test/simple/test-child-process-internal.js @@ -0,0 +1,58 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); + +//messages +var PREFIX = 'NODE_'; +var normal = {cmd: 'foo' + PREFIX}; +var internal = {cmd: PREFIX + 'bar'}; + +if (process.argv[2] === 'child') { + //send non-internal message containing PREFIX at a non prefix position + process.send(normal); + + //send inernal message + process.send(internal); + + process.exit(0); + +} else { + + var fork = require('child_process').fork; + var child = fork(process.argv[1], ['child']); + + var gotNormal; + child.once('message', function(data) { + gotNormal = data; + }); + + var gotInternal; + child.once('internalMessage', function(data) { + gotInternal = data; + }); + + process.on('exit', function() { + assert.deepEqual(gotNormal, normal); + assert.deepEqual(gotInternal, internal); + }); +} diff --git a/node-v0.8.14/test/simple/test-child-process-ipc.js b/node-v0.8.14/test/simple/test-child-process-ipc.js new file mode 100644 index 0000000..8ccc505 --- /dev/null +++ b/node-v0.8.14/test/simple/test-child-process-ipc.js @@ -0,0 +1,63 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); + +var spawn = require('child_process').spawn; + +var path = require('path'); + +var sub = path.join(common.fixturesDir, 'echo.js'); + +var gotHelloWorld = false; +var gotEcho = false; + +var child = spawn(process.argv[0], [sub]); + +child.stderr.on('data', function(data) { + console.log('parent stderr: ' + data); +}); + +child.stdout.setEncoding('utf8'); + +child.stdout.on('data', function(data) { + console.log('child said: ' + JSON.stringify(data)); + if (!gotHelloWorld) { + assert.equal('hello world\r\n', data); + gotHelloWorld = true; + child.stdin.write('echo me\r\n'); + } else { + assert.equal('echo me\r\n', data); + gotEcho = true; + child.stdin.end(); + } +}); + +child.stdout.on('end', function(data) { + console.log('child end'); +}); + + +process.on('exit', function() { + assert.ok(gotHelloWorld); + assert.ok(gotEcho); +}); diff --git a/node-v0.8.14/test/simple/test-child-process-kill-throw.js b/node-v0.8.14/test/simple/test-child-process-kill-throw.js new file mode 100644 index 0000000..f85bf51 --- /dev/null +++ b/node-v0.8.14/test/simple/test-child-process-kill-throw.js @@ -0,0 +1,50 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); + +if (process.argv[2] === 'child') { + process.exit(0); +} else { + var spawn = require('child_process').spawn; + var child = spawn(process.execPath, [process.argv[1], 'child']); + + var error = {}; + child.on('exit', function() { + child._handle = { + kill: function() { + global.errno = 42; + return -1; + } + }; + child.once('error', function(err) { + error = err; + }); + child.kill(); + }); + + process.on('exit', function() { + // we shouldn't reset errno since it accturlly isn't set + // because of the fake .kill method + assert.equal(error.syscall, 'kill'); + }); +} diff --git a/node-v0.8.14/test/simple/test-child-process-kill.js b/node-v0.8.14/test/simple/test-child-process-kill.js new file mode 100644 index 0000000..08a0185 --- /dev/null +++ b/node-v0.8.14/test/simple/test-child-process-kill.js @@ -0,0 +1,66 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + + + +var common = require('../common'); +var assert = require('assert'); + +var spawn = require('child_process').spawn; + +var is_windows = process.platform === 'win32'; + +var exitCode; +var termSignal; +var gotStdoutEOF = false; +var gotStderrEOF = false; + +var cat = spawn(is_windows ? 'cmd' : 'cat'); + + +cat.stdout.on('end', function() { + gotStdoutEOF = true; +}); + +cat.stderr.on('data', function(chunk) { + assert.ok(false); +}); + +cat.stderr.on('end', function() { + gotStderrEOF = true; +}); + +cat.on('exit', function(code, signal) { + exitCode = code; + termSignal = signal; +}); + +assert.equal(cat.killed, false); +cat.kill(); +assert.equal(cat.killed, true); + +process.on('exit', function() { + assert.strictEqual(exitCode, null); + assert.strictEqual(termSignal, 'SIGTERM'); + assert.ok(gotStdoutEOF); + assert.ok(gotStderrEOF); +}); diff --git a/node-v0.8.14/test/simple/test-child-process-set-blocking.js b/node-v0.8.14/test/simple/test-child-process-set-blocking.js new file mode 100644 index 0000000..030b682 --- /dev/null +++ b/node-v0.8.14/test/simple/test-child-process-set-blocking.js @@ -0,0 +1,40 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var ch = require('child_process'); + +var SIZE = 100000; +var childGone = false; + +var cp = ch.spawn('python', ['-c', 'print ' + SIZE + ' * "C"'], { + customFds: [0, 1, 2] +}); + +cp.on('exit', function(code) { + childGone = true; + assert.equal(0, code); +}); + +process.on('exit', function() { + assert.ok(childGone); +}); diff --git a/node-v0.8.14/test/simple/test-child-process-silent.js b/node-v0.8.14/test/simple/test-child-process-silent.js new file mode 100644 index 0000000..e34daa3 --- /dev/null +++ b/node-v0.8.14/test/simple/test-child-process-silent.js @@ -0,0 +1,106 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var childProcess = require('child_process'); + +// Child pipe test +if (process.argv[2] === 'pipetest') { + process.stdout.write('stdout message'); + process.stderr.write('stderr message'); + +} else if (process.argv[2] === 'ipctest') { + // Child IPC test + process.send('message from child'); + process.on('message', function() { + process.send('got message from master'); + }); + +} else if (process.argv[2] === 'parent') { + // Parent | start child pipe test + + var child = childProcess.fork(process.argv[1], ['pipetest'], {silent: true}); + + // Allow child process to self terminate + child._channel.close(); + child._channel = null; + + child.on('exit', function() { + process.exit(0); + }); + +} else { + // testcase | start parent && child IPC test + + // testing: is stderr and stdout piped to parent + var args = [process.argv[1], 'parent']; + var parent = childProcess.spawn(process.execPath, args); + + //got any stderr or std data + var stdoutData = false; + parent.stdout.on('data', function() { + stdoutData = true; + }); + var stderrData = false; + parent.stdout.on('data', function() { + stderrData = true; + }); + + // testing: do message system work when using silent + var child = childProcess.fork(process.argv[1], ['ipctest'], {silent: true}); + + // Manual pipe so we will get errors + child.stderr.pipe(process.stderr, {end: false}); + child.stdout.pipe(process.stdout, {end: false}); + + var childSending = false; + var childReciveing = false; + child.on('message', function(message) { + if (childSending === false) { + childSending = (message === 'message from child'); + } + + if (childReciveing === false) { + childReciveing = (message === 'got message from master'); + } + + if (childReciveing === true) { + child.kill(); + } + }); + child.send('message to child'); + + // Check all values + process.on('exit', function() { + // clean up + child.kill(); + parent.kill(); + + // Check std(out|err) pipes + assert.ok(!stdoutData, 'The stdout socket was piped to parent'); + assert.ok(!stderrData, 'The stderr socket was piped to parent'); + + // Check message system + assert.ok(childSending, 'The child was able to send a message'); + assert.ok(childReciveing, 'The child was able to receive a message'); + }); +} diff --git a/node-v0.8.14/test/simple/test-child-process-stdin.js b/node-v0.8.14/test/simple/test-child-process-stdin.js new file mode 100644 index 0000000..fdb40cc --- /dev/null +++ b/node-v0.8.14/test/simple/test-child-process-stdin.js @@ -0,0 +1,89 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); + +var spawn = require('child_process').spawn; +var is_windows = process.platform === 'win32'; + +var cat = spawn(is_windows ? 'more' : 'cat'); +cat.stdin.write('hello'); +cat.stdin.write(' '); +cat.stdin.write('world'); + +assert.ok(cat.stdin.writable); +assert.ok(!cat.stdin.readable); + +cat.stdin.end(); + +var response = ''; +var exitStatus = -1; +var closed = false; + +var gotStdoutEOF = false; + +cat.stdout.setEncoding('utf8'); +cat.stdout.on('data', function(chunk) { + console.log('stdout: ' + chunk); + response += chunk; +}); + +cat.stdout.on('end', function() { + gotStdoutEOF = true; +}); + + +var gotStderrEOF = false; + +cat.stderr.on('data', function(chunk) { + // shouldn't get any stderr output + assert.ok(false); +}); + +cat.stderr.on('end', function(chunk) { + gotStderrEOF = true; +}); + + +cat.on('exit', function(status) { + console.log('exit event'); + exitStatus = status; +}); + +cat.on('close', function () { + closed = true; + if (is_windows) { + assert.equal('hello world\r\n', response); + } else { + assert.equal('hello world', response); + } +}); + +process.on('exit', function() { + assert.equal(0, exitStatus); + assert(closed); + if (is_windows) { + assert.equal('hello world\r\n', response); + } else { + assert.equal('hello world', response); + } +}); diff --git a/node-v0.8.14/test/simple/test-child-process-stdio.js b/node-v0.8.14/test/simple/test-child-process-stdio.js new file mode 100644 index 0000000..32da15f --- /dev/null +++ b/node-v0.8.14/test/simple/test-child-process-stdio.js @@ -0,0 +1,36 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var spawn = require('child_process').spawn; + +var options = {stdio: ['pipe']}; +var child = common.spawnPwd(options); + +assert.notEqual(child.stdout, null); +assert.notEqual(child.stderr, null); + +options = {stdio: 'ignore'}; +child = common.spawnPwd(options); + +assert.equal(child.stdout, null); +assert.equal(child.stderr, null); diff --git a/node-v0.8.14/test/simple/test-child-process-stdout-flush.js b/node-v0.8.14/test/simple/test-child-process-stdout-flush.js new file mode 100644 index 0000000..adb33f5 --- /dev/null +++ b/node-v0.8.14/test/simple/test-child-process-stdout-flush.js @@ -0,0 +1,52 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + + + +var common = require('../common'); +var assert = require('assert'); +var path = require('path'); +var spawn = require('child_process').spawn; +var sub = path.join(common.fixturesDir, 'print-chars.js'); + +var n = 500000; + +var child = spawn(process.argv[0], [sub, n]); + +var count = 0; + +child.stderr.setEncoding('utf8'); +child.stderr.on('data', function(data) { + console.log('parent stderr: ' + data); + assert.ok(false); +}); + +child.stdout.setEncoding('utf8'); +child.stdout.on('data', function(data) { + count += data.length; + console.log(count); +}); + +child.on('close', function(data) { + assert.equal(n, count); + console.log('okay'); +}); diff --git a/node-v0.8.14/test/simple/test-cli-eval.js b/node-v0.8.14/test/simple/test-cli-eval.js new file mode 100644 index 0000000..7e3e0cd --- /dev/null +++ b/node-v0.8.14/test/simple/test-cli-eval.js @@ -0,0 +1,81 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +if (module.parent) { + // signal we've been loaded as a module + console.log('Loaded as a module, exiting with status code 42.'); + process.exit(42); +} + +var common = require('../common.js'), + assert = require('assert'), + child = require('child_process'), + nodejs = '"' + process.execPath + '"'; + + +// replace \ by / because windows uses backslashes in paths, but they're still +// interpreted as the escape character when put between quotes. +var filename = __filename.replace(/\\/g, '/'); + +// assert that nothing is written to stdout +child.exec(nodejs + ' --eval 42', + function(err, stdout, stderr) { + assert.equal(stdout, ''); + }); + +// assert that "42\n" is written to stderr +child.exec(nodejs + ' --eval "console.error(42)"', + function(err, stdout, stderr) { + assert.equal(stderr, '42\n'); + }); + +// assert that the expected output is written to stdout +['--print --eval', '-p -e', '-pe'].forEach(function(s) { + var cmd = nodejs + ' ' + s + ' '; + + child.exec(cmd + '42', + function(err, stdout, stderr) { + assert.equal(stdout, '42\n'); + }); + + child.exec(cmd + "'[]'", + function(err, stdout, stderr) { + assert.equal(stdout, '[]\n'); + }); +}); + +// assert that module loading works +child.exec(nodejs + ' --eval "require(\'' + filename + '\')"', + function(status, stdout, stderr) { + assert.equal(status.code, 42); + }); + +// module path resolve bug, regression test +child.exec(nodejs + ' --eval "require(\'./test/simple/test-cli-eval.js\')"', + function(status, stdout, stderr) { + assert.equal(status.code, 42); + }); + +// empty program should do nothing +child.exec(nodejs + ' -e ""', function(status, stdout, stderr) { + assert.equal(stdout, ''); + assert.equal(stderr, ''); +}); diff --git a/node-v0.8.14/test/simple/test-cluster-basic.js b/node-v0.8.14/test/simple/test-cluster-basic.js new file mode 100644 index 0000000..88ba6ed --- /dev/null +++ b/node-v0.8.14/test/simple/test-cluster-basic.js @@ -0,0 +1,183 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + +var common = require('../common'); +var assert = require('assert'); +var cluster = require('cluster'); + +assert.equal('NODE_UNIQUE_ID' in process.env, false, + 'NODE_UNIQUE_ID should be removed on startup'); + +function forEach(obj, fn) { + Object.keys(obj).forEach(function(name, index) { + fn(obj[name], name, index); + }); +} + + +if (cluster.isWorker) { + var http = require('http'); + http.Server(function() { + + }).listen(common.PORT, '127.0.0.1'); +} + +else if (cluster.isMaster) { + + var checks = { + cluster: { + events: { + fork: false, + online: false, + listening: false, + exit: false + }, + equal: { + fork: false, + online: false, + listening: false, + exit: false + } + }, + + worker: { + events: { + online: false, + listening: false, + exit: false + }, + equal: { + online: false, + listening: false, + exit: false + }, + states: { + none: false, + online: false, + listening: false, + dead: false + } + } + }; + + var worker; + var stateNames = Object.keys(checks.worker.states); + + //Check events, states, and emit arguments + forEach(checks.cluster.events, function(bool, name, index) { + + //Listen on event + cluster.on(name, function(/* worker */) { + + //Set event + checks.cluster.events[name] = true; + + //Check argument + checks.cluster.equal[name] = worker === arguments[0]; + + //Check state + var state = stateNames[index]; + checks.worker.states[state] = (state === worker.state); + }); + }); + + //Kill worker when listening + cluster.on('listening', function() { + worker.destroy(); + }); + + //Kill process when worker is killed + cluster.on('exit', function() { + process.exit(0); + }); + + //Create worker + worker = cluster.fork(); + assert.equal(worker.id, 1); + assert.ok(worker instanceof cluster.Worker, + 'the worker is not a instance of the Worker constructor'); + + //Check event + forEach(checks.worker.events, function(bool, name, index) { + worker.on(name, function() { + //Set event + checks.worker.events[name] = true; + + //Check argument + checks.worker.equal[name] = (worker === this); + + switch (name) { + case 'exit': + assert.equal(arguments[0], worker.process.exitCode); + assert.equal(arguments[1], worker.process.signalCode); + assert.equal(arguments.length, 2); + break; + + case 'listening': + assert.equal(arguments.length, 1); + var expect = { address: '127.0.0.1', + port: common.PORT, + addressType: 4, + fd: undefined }; + assert.deepEqual(arguments[0], expect); + break; + + default: + assert.equal(arguments.length, 0); + break; + } + }); + }); + + //Check all values + process.once('exit', function() { + //Check cluster events + forEach(checks.cluster.events, function(check, name) { + assert.ok(check, 'The cluster event "' + name + '" on the cluster ' + + 'object did not fire'); + }); + + //Check cluster event arguments + forEach(checks.cluster.equal, function(check, name) { + assert.ok(check, 'The cluster event "' + name + '" did not emit ' + + 'with correct argument'); + }); + + //Check worker states + forEach(checks.worker.states, function(check, name) { + assert.ok(check, 'The worker state "' + name + '" was not set to true'); + }); + + //Check worker events + forEach(checks.worker.events, function(check, name) { + assert.ok(check, 'The worker event "' + name + '" on the worker object ' + + 'did not fire'); + }); + + //Check worker event arguments + forEach(checks.worker.equal, function(check, name) { + assert.ok(check, 'The worker event "' + name + '" did not emit with ' + + 'corrent argument'); + }); + }); + +} diff --git a/node-v0.8.14/test/simple/test-cluster-disconnect.js b/node-v0.8.14/test/simple/test-cluster-disconnect.js new file mode 100644 index 0000000..4ea6afc --- /dev/null +++ b/node-v0.8.14/test/simple/test-cluster-disconnect.js @@ -0,0 +1,122 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + +var common = require('../common'); +var assert = require('assert'); +var cluster = require('cluster'); +var net = require('net'); + +if (cluster.isWorker) { + net.createServer(function(socket) { + socket.end('echo'); + }).listen(common.PORT, '127.0.0.1'); + + net.createServer(function(socket) { + socket.end('echo'); + }).listen(common.PORT + 1, '127.0.0.1'); + +} else if (cluster.isMaster) { + + // test a single TCP server + var testConnection = function(port, cb) { + var socket = net.connect(port, '127.0.0.1', function() { + // buffer result + var result = ''; + socket.on('data', function(chunk) { result += chunk; }); + + // check result + socket.on('end', function() { + cb(result === 'echo'); + }); + }); + }; + + // test both servers created in the cluster + var testCluster = function(cb) { + var servers = 2; + var done = 0; + + for (var i = 0, l = servers; i < l; i++) { + testConnection(common.PORT + i, function(sucess) { + assert.ok(sucess); + done += 1; + if (done === servers) { + cb(); + } + }); + } + }; + + // start two workers and execute callback when both is listening + var startCluster = function(cb) { + var workers = 2; + var online = 0; + + for (var i = 0, l = workers; i < l; i++) { + + var worker = cluster.fork(); + worker.on('listening', function() { + online += 1; + if (online === workers) { + cb(); + } + }); + } + }; + + + var results = { + start: 0, + test: 0, + disconnect: 0 + }; + + var test = function(again) { + //1. start cluster + startCluster(function() { + results.start += 1; + + //2. test cluster + testCluster(function() { + results.test += 1; + + //3. disconnect cluster + cluster.disconnect(function() { + results.disconnect += 1; + + // run test again to confirm cleanup + if (again) { + test(); + } + }); + }); + }); + }; + + test(true); + + process.once('exit', function() { + assert.equal(results.start, 2); + assert.equal(results.test, 2); + assert.equal(results.disconnect, 2); + }); +} diff --git a/node-v0.8.14/test/simple/test-cluster-fork-env.js b/node-v0.8.14/test/simple/test-cluster-fork-env.js new file mode 100644 index 0000000..a0b50ae --- /dev/null +++ b/node-v0.8.14/test/simple/test-cluster-fork-env.js @@ -0,0 +1,63 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + +var common = require('../common'); +var assert = require('assert'); +var cluster = require('cluster'); + +if (cluster.isWorker) { + cluster.worker.send({ + prop: process.env['cluster_test_prop'], + overwrite: process.env['cluster_test_overwrite'] + }); + +} else if (cluster.isMaster) { + + var checks = { + using: false, + overwrite: false + }; + + // To check that the cluster extend on the process.env we will overwrite a + // property + process.env['cluster_test_overwrite'] = 'old'; + + // Fork worker + var worker = cluster.fork({ + 'cluster_test_prop': 'custom', + 'cluster_test_overwrite': 'new' + }); + + // Checks worker env + worker.on('message', function(data) { + checks.using = (data.prop === 'custom'); + checks.overwrite = (data.overwrite === 'new'); + process.exit(0); + }); + + process.once('exit', function() { + assert.ok(checks.using, 'The worker did not receive the correct env.'); + assert.ok(checks.overwrite, 'The custom environment did not overwrite ' + + 'the existing environment.'); + }); + +} diff --git a/node-v0.8.14/test/simple/test-cluster-http-pipe.js b/node-v0.8.14/test/simple/test-cluster-http-pipe.js new file mode 100644 index 0000000..46d429a --- /dev/null +++ b/node-v0.8.14/test/simple/test-cluster-http-pipe.js @@ -0,0 +1,62 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// It is not possible to send pipe handles over the IPC pipe on Windows. +if (process.platform === 'win32') { + process.exit(0); +} + +var common = require('../common'); +var assert = require('assert'); +var cluster = require('cluster'); +var http = require('http'); + +if (cluster.isMaster) { + var ok = false; + var worker = cluster.fork(); + worker.on('message', function(msg) { + assert.equal(msg, 'DONE'); + ok = true; + }); + worker.on('exit', function() { + process.exit(); + }); + process.on('exit', function() { + assert(ok); + }); + return; +} + +http.createServer(function(req, res) { + assert.equal(req.connection.remoteAddress, undefined); + assert.equal(req.connection.localAddress, undefined); // TODO common.PIPE? + res.writeHead(200); + res.end('OK'); +}).listen(common.PIPE, function() { + var self = this; + http.get({ socketPath: common.PIPE, path: '/' }, function(res) { + res.on('end', function(err) { + if (err) throw err; + process.send('DONE'); + process.exit(); + }); + }); +}); diff --git a/node-v0.8.14/test/simple/test-cluster-master-error.js b/node-v0.8.14/test/simple/test-cluster-master-error.js new file mode 100644 index 0000000..5e0e3fa --- /dev/null +++ b/node-v0.8.14/test/simple/test-cluster-master-error.js @@ -0,0 +1,139 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + +var common = require('../common'); +var assert = require('assert'); +var cluster = require('cluster'); + +// Cluster setup +if (cluster.isWorker) { + var http = require('http'); + http.Server(function() { + + }).listen(common.PORT, '127.0.0.1'); + +} else if (process.argv[2] === 'cluster') { + + var totalWorkers = 2; + + // Send PID to testcase process + var forkNum = 0; + cluster.on('fork', function forkEvent(worker) { + + // Send PID + process.send({ + cmd: 'worker', + workerPID: worker.process.pid + }); + + // Stop listening when done + if (++forkNum === totalWorkers) { + cluster.removeListener('fork', forkEvent); + } + }); + + // Throw accidently error when all workers are listening + var listeningNum = 0; + cluster.on('listening', function listeningEvent() { + + // When all workers are listening + if (++listeningNum === totalWorkers) { + // Stop listening + cluster.removeListener('listening', listeningEvent); + + // throw accidently error + process.nextTick(function() { + throw 'accidently error'; + }); + } + + }); + + // Startup a basic cluster + cluster.fork(); + cluster.fork(); + +} else { + // This is the testcase + + var fork = require('child_process').fork; + + var isAlive = function(pid) { + try { + //this will throw an error if the process is dead + process.kill(pid, 0); + + return true; + } catch (e) { + return false; + } + }; + + var existMaster = false; + var existWorker = false; + + // List all workers + var workers = []; + + // Spawn a cluster process + var master = fork(process.argv[1], ['cluster'], {silent: true}); + + // Handle messages from the cluster + master.on('message', function(data) { + + // Add worker pid to list and progress tracker + if (data.cmd === 'worker') { + workers.push(data.workerPID); + } + }); + + // When cluster is dead + master.on('exit', function(code) { + + // Check that the cluster died accidently + existMaster = (code === 1); + + // Give the workers time to shut down + setTimeout(checkWorkers, 200); + + function checkWorkers() { + // When master is dead all workers should be dead to + var alive = false; + workers.forEach(function(pid) { + if (isAlive(pid)) { + alive = true; + } + }); + + // If a worker was alive this did not act as expected + existWorker = !alive; + } + }); + + process.once('exit', function() { + var m = 'The master did not die after an error was throwed'; + assert.ok(existMaster, m); + m = 'The workers did not die after an error in the master'; + assert.ok(existWorker, m); + }); + +} diff --git a/node-v0.8.14/test/simple/test-cluster-master-kill.js b/node-v0.8.14/test/simple/test-cluster-master-kill.js new file mode 100644 index 0000000..3625403 --- /dev/null +++ b/node-v0.8.14/test/simple/test-cluster-master-kill.js @@ -0,0 +1,98 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + +var common = require('../common'); +var assert = require('assert'); +var cluster = require('cluster'); + +if (cluster.isWorker) { + + // keep the worker alive + var http = require('http'); + http.Server().listen(common.PORT, '127.0.0.1'); + +} else if (process.argv[2] === 'cluster') { + + var worker = cluster.fork(); + + // send PID info to testcase process + process.send({ + pid: worker.process.pid + }); + + // terminate the cluster process + worker.once('listening', function() { + setTimeout(function() { + process.exit(0); + }, 1000); + }); + +} else { + + // This is the testcase + var fork = require('child_process').fork; + + // is process alive helper + var isAlive = function(pid) { + try { + //this will throw an error if the process is dead + process.kill(pid, 0); + + return true; + } catch (e) { + return false; + } + }; + + // Spawn a cluster process + var master = fork(process.argv[1], ['cluster']); + + // get pid info + var pid = null; + master.once('message', function(data) { + pid = data.pid; + }); + + // When master is dead + var alive = true; + master.on('exit', function(code) { + + // make sure that the master died by purpose + assert.equal(code, 0); + + // check worker process status + setTimeout(function() { + alive = isAlive(pid); + }, 200); + }); + + process.once('exit', function() { + // cleanup: kill the worker if alive + if (alive) { + process.kill(pid); + } + + assert.equal(typeof pid, 'number', 'did not get worker pid info'); + assert.equal(alive, false, 'worker was alive after master died'); + }); + +} diff --git a/node-v0.8.14/test/simple/test-cluster-message.js b/node-v0.8.14/test/simple/test-cluster-message.js new file mode 100644 index 0000000..313355f --- /dev/null +++ b/node-v0.8.14/test/simple/test-cluster-message.js @@ -0,0 +1,139 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + +var common = require('../common'); +var assert = require('assert'); +var cluster = require('cluster'); +var net = require('net'); + +function forEach(obj, fn) { + Object.keys(obj).forEach(function(name, index) { + fn(obj[name], name, index); + }); +} + +if (cluster.isWorker) { + // Create a tcp server. This will be used as cluster-shared-server and as an + // alternative IPC channel. + var server = net.Server(); + var socket, message; + + function maybeReply() { + if (!socket || !message) return; + + // Tell master using TCP socket that a message is received. + socket.write(JSON.stringify({ + code: 'received message', + echo: message + })); + } + + server.on('connection', function(socket_) { + socket = socket_; + maybeReply(); + + // Send a message back over the IPC channel. + process.send('message from worker'); + }); + + process.on('message', function(message_) { + message = message_; + maybeReply(); + }); + + server.listen(common.PORT, '127.0.0.1'); +} + +else if (cluster.isMaster) { + + var checks = { + master: { + 'receive': false, + 'correct': false + }, + worker: { + 'receive': false, + 'correct': false + } + }; + + + var client; + var check = function(type, result) { + checks[type].receive = true; + checks[type].correct = result; + + var missing = false; + forEach(checks, function(type) { + if (type.receive === false) missing = true; + }); + + if (missing === false) { + client.end(); + } + }; + + // Spawn worker + var worker = cluster.fork(); + + // When a IPC message is resicved form the worker + worker.on('message', function(message) { + check('master', message === 'message from worker'); + }); + + // When a TCP connection is made with the worker connect to it + worker.on('listening', function() { + + client = net.connect(common.PORT, function() { + // Send message to worker. + worker.send('message from master'); + }); + + client.on('data', function(data) { + // All data is JSON + data = JSON.parse(data.toString()); + + if (data.code === 'received message') { + check('worker', data.echo === 'message from master'); + } else { + throw new Error('wrong TCP message recived: ' + data); + } + }); + + // When the connection ends kill worker and shutdown process + client.on('end', function() { + worker.destroy(); + }); + + worker.on('exit', function() { + process.exit(0); + }); + }); + + process.once('exit', function() { + forEach(checks, function(check, type) { + assert.ok(check.receive, 'The ' + type + ' did not receive any message'); + assert.ok(check.correct, + 'The ' + type + ' did not get the correct message'); + }); + }); +} diff --git a/node-v0.8.14/test/simple/test-cluster-net-listen.js b/node-v0.8.14/test/simple/test-cluster-net-listen.js new file mode 100644 index 0000000..927169c --- /dev/null +++ b/node-v0.8.14/test/simple/test-cluster-net-listen.js @@ -0,0 +1,41 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var cluster = require('cluster'); +var net = require('net'); + +if (cluster.isMaster) { + // ensure that the worker exits peacefully + var worker = cluster.fork(); + worker.on('exit', function(statusCode) { + assert.equal(statusCode, 0); + worker = null; + }); + process.on('exit', function() { + assert.equal(worker, null); + }); +} +else { + // listen() without port should not trigger a libuv assert + net.createServer(assert.fail).listen(process.exit); +} diff --git a/node-v0.8.14/test/simple/test-cluster-setup-master.js b/node-v0.8.14/test/simple/test-cluster-setup-master.js new file mode 100644 index 0000000..7dbbc32 --- /dev/null +++ b/node-v0.8.14/test/simple/test-cluster-setup-master.js @@ -0,0 +1,90 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + +var common = require('../common'); +var assert = require('assert'); +var cluster = require('cluster'); + +if (cluster.isWorker) { + + // Just keep the worker alive + process.send(process.argv[2]); + +} else if (cluster.isMaster) { + + var checks = { + args: false, + setupEvent: false, + settingsObject: false + }; + + var totalWorkers = 2; + + cluster.once('setup', function() { + checks.setupEvent = true; + + var settings = cluster.settings; + if (settings && + settings.args && settings.args[0] === 'custom argument' && + settings.silent === true && + settings.exec === process.argv[1]) { + checks.settingsObject = true; + } + }); + + // Setup master + cluster.setupMaster({ + args: ['custom argument'], + silent: true + }); + + var correctIn = 0; + + cluster.on('online', function lisenter(worker) { + + worker.once('message', function(data) { + correctIn += (data === 'custom argument' ? 1 : 0); + if (correctIn === totalWorkers) { + checks.args = true; + } + worker.destroy(); + }); + + // All workers are online + if (cluster.onlineWorkers === totalWorkers) { + checks.workers = true; + } + }); + + // Start all workers + cluster.fork(); + cluster.fork(); + + // Check all values + process.once('exit', function() { + assert.ok(checks.args, 'The arguments was noy send to the worker'); + assert.ok(checks.setupEvent, 'The setup event was never emitted'); + var m = 'The settingsObject do not have correct properties'; + assert.ok(checks.settingsObject, m); + }); + +} diff --git a/node-v0.8.14/test/simple/test-cluster-uncaught-exception.js b/node-v0.8.14/test/simple/test-cluster-uncaught-exception.js new file mode 100644 index 0000000..48a8251 --- /dev/null +++ b/node-v0.8.14/test/simple/test-cluster-uncaught-exception.js @@ -0,0 +1,59 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// Installing a custom uncaughtException handler should override the default +// one that the cluster module installs. +// https://github.com/joyent/node/issues/2556 + +var common = require('../common'); +var assert = require('assert'); +var cluster = require('cluster'); +var fork = require('child_process').fork; + +var MAGIC_EXIT_CODE = 42; + +var isTestRunner = process.argv[2] != 'child'; + +if (isTestRunner) { + var exitCode = -1; + + process.on('exit', function() { + assert.equal(exitCode, MAGIC_EXIT_CODE); + }); + + var master = fork(__filename, ['child']); + master.on('exit', function(code) { + exitCode = code; + }); +} +else if (cluster.isMaster) { + process.on('uncaughtException', function() { + process.nextTick(function() { + process.exit(MAGIC_EXIT_CODE); + }); + }); + + cluster.fork(); + throw new Error('kill master'); +} +else { // worker + process.exit(); +} diff --git a/node-v0.8.14/test/simple/test-cluster-worker-death.js b/node-v0.8.14/test/simple/test-cluster-worker-death.js new file mode 100644 index 0000000..ccd4855 --- /dev/null +++ b/node-v0.8.14/test/simple/test-cluster-worker-death.js @@ -0,0 +1,46 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var cluster = require('cluster'); + +if (!cluster.isMaster) { + process.exit(42); +} +else { + var seenExit = 0; + var seenDeath = 0; + var worker = cluster.fork(); + worker.on('exit', function(exitCode, signalCode) { + assert.equal(exitCode, 42); + assert.equal(signalCode, null); + seenExit++; + }); + cluster.on('exit', function(worker_) { + assert.equal(worker_, worker); + seenDeath++; + }); + process.on('exit', function() { + assert.equal(seenExit, 1); + assert.equal(seenDeath, 1); + }); +} diff --git a/node-v0.8.14/test/simple/test-cluster-worker-disconnect.js b/node-v0.8.14/test/simple/test-cluster-worker-disconnect.js new file mode 100644 index 0000000..15329c9 --- /dev/null +++ b/node-v0.8.14/test/simple/test-cluster-worker-disconnect.js @@ -0,0 +1,110 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + +var common = require('../common'); +var assert = require('assert'); +var cluster = require('cluster'); + +if (cluster.isWorker) { + var http = require('http'); + http.Server(function() { + + }).listen(common.PORT, '127.0.0.1'); + +} else if (cluster.isMaster) { + + var checks = { + cluster: { + emitDisconnect: false, + emitExit: false, + callback: false + }, + worker: { + emitDisconnect: false, + emitExit: false, + state: false, + suicideMode: false, + died: false + } + }; + + // helper function to check if a process is alive + var alive = function(pid) { + try { + process.kill(pid, 0); + return true; + } catch (e) { + return false; + } + }; + + // start worker + var worker = cluster.fork(); + + // Disconnect worker when it is ready + worker.once('listening', function() { + worker.disconnect(); + }); + + // Check cluster events + cluster.once('disconnect', function() { + checks.cluster.emitDisconnect = true; + }); + cluster.once('exit', function() { + checks.cluster.emitExit = true; + }); + + // Check worker eventes and properties + worker.once('disconnect', function() { + checks.worker.emitDisconnect = true; + checks.worker.suicideMode = worker.suicide; + checks.worker.state = worker.state; + }); + + // Check that the worker died + worker.once('exit', function() { + checks.worker.emitExit = true; + checks.worker.died = !alive(worker.process.pid); + process.nextTick(function() { + process.exit(0); + }); + }); + + process.once('exit', function() { + + var w = checks.worker; + var c = checks.cluster; + + // events + assert.ok(w.emitDisconnect, 'Disconnect event did not emit'); + assert.ok(c.emitDisconnect, 'Disconnect event did not emit'); + assert.ok(w.emitExit, 'Exit event did not emit'); + assert.ok(c.emitExit, 'Exit event did not emit'); + + // flags + assert.equal(w.state, 'disconnected', 'The state property was not set'); + assert.equal(w.suicideMode, true, 'Suicide mode was not set'); + + // is process alive + assert.ok(w.died, 'The worker did not die'); + }); +} diff --git a/node-v0.8.14/test/simple/test-cluster-worker-exit.js b/node-v0.8.14/test/simple/test-cluster-worker-exit.js new file mode 100644 index 0000000..38b44c1 --- /dev/null +++ b/node-v0.8.14/test/simple/test-cluster-worker-exit.js @@ -0,0 +1,152 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + +// test-cluster-worker-exit.js +// verifies that, when a child process exits (by calling `process.exit(code)`) +// - the parent receives the proper events in the proper order, no duplicates +// - the exitCode and signalCode are correct in the 'exit' event +// - the worker.suicide flag, and worker.state are correct +// - the worker process actually goes away + +var common = require('../common'); +var assert = require('assert'); +var cluster = require('cluster'); + +var EXIT_CODE = 42; + +if (cluster.isWorker) { + var http = require('http'); + var server = http.Server(function() { }); + + server.once('listening', function() { + process.exit(EXIT_CODE); + }); + server.listen(common.PORT, '127.0.0.1'); + +} else if (cluster.isMaster) { + + var expected_results = { + cluster_emitDisconnect: [1, "the cluster did not emit 'disconnect'"], + cluster_emitExit: [1, "the cluster did not emit 'exit'"], + cluster_exitCode: [EXIT_CODE, 'the cluster exited w/ incorrect exitCode'], + cluster_signalCode: [null, 'the cluster exited w/ incorrect signalCode'], + worker_emitDisconnect: [1, "the worker did not emit 'disconnect'"], + worker_emitExit: [1, "the worker did not emit 'exit'"], + worker_state: ['disconnected', 'the worker state is incorrect'], + worker_suicideMode: [false, 'the worker.suicide flag is incorrect'], + worker_died: [true, 'the worker is still running'], + worker_exitCode: [EXIT_CODE, 'the worker exited w/ incorrect exitCode'], + worker_signalCode: [null, 'the worker exited w/ incorrect signalCode'] + }; + var results = { + cluster_emitDisconnect: 0, + cluster_emitExit: 0, + worker_emitDisconnect: 0, + worker_emitExit: 0 + }; + + + // start worker + var worker = cluster.fork(); + + worker.once('listening', function() { + // the worker is up and running... + }); + + + // Check cluster events + cluster.on('disconnect', function() { + results.cluster_emitDisconnect += 1; + }); + cluster.on('exit', function(worker) { + results.cluster_exitCode = worker.process.exitCode; + results.cluster_signalCode = worker.process.signalCode; + results.cluster_emitExit += 1; + assert.ok(results.cluster_emitDisconnect, + "cluster: 'exit' event before 'disconnect' event"); + }); + + // Check worker eventes and properties + worker.on('disconnect', function() { + results.worker_emitDisconnect += 1; + results.worker_suicideMode = worker.suicide; + results.worker_state = worker.state; + }); + + // Check that the worker died + worker.once('exit', function(exitCode, signalCode) { + results.worker_exitCode = exitCode; + results.worker_signalCode = signalCode; + results.worker_emitExit += 1; + results.worker_died = !alive(worker.process.pid); + assert.ok(results.worker_emitDisconnect, + "worker: 'exit' event before 'disconnect' event"); + + process.nextTick(function() { finish_test(); }); + }); + + var finish_test = function() { + try { + checkResults(expected_results, results); + } catch (exc) { + console.error('FAIL: ' + exc.message); + if (exc.name != 'AssertionError') { + console.trace(exc); + } + + process.exit(1); + return; + } + process.exit(0); + }; +} + +// some helper functions ... + + function checkResults(expected_results, results) { + for (var k in expected_results) { + var actual = results[k], + expected = expected_results[k]; + + if (typeof expected === 'function') { + expected(r[k]); + } else { + var msg = (expected[1] || '') + + (' [expected: ' + expected[0] + ' / actual: ' + actual + ']'); + + if (expected && expected.length) { + assert.equal(actual, expected[0], msg); + } else { + assert.equal(actual, expected, msg); + } + } + } + } + + function alive(pid) { + try { + process.kill(pid, 'SIGCONT'); + return true; + } catch (e) { + return false; + } + } diff --git a/node-v0.8.14/test/simple/test-cluster-worker-kill.js b/node-v0.8.14/test/simple/test-cluster-worker-kill.js new file mode 100644 index 0000000..284b83e --- /dev/null +++ b/node-v0.8.14/test/simple/test-cluster-worker-kill.js @@ -0,0 +1,149 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + +// test-cluster-worker-kill.js +// verifies that, when a child process is killed (we use SIGKILL) +// - the parent receives the proper events in the proper order, no duplicates +// - the exitCode and signalCode are correct in the 'exit' event +// - the worker.suicide flag, and worker.state are correct +// - the worker process actually goes away + +var common = require('../common'); +var assert = require('assert'); +var cluster = require('cluster'); + +if (cluster.isWorker) { + var http = require('http'); + var server = http.Server(function() { }); + + server.once('listening', function() { }); + server.listen(common.PORT, '127.0.0.1'); + +} else if (cluster.isMaster) { + + var KILL_SIGNAL = 'SIGKILL', + expected_results = { + cluster_emitDisconnect: [1, "the cluster did not emit 'disconnect'"], + cluster_emitExit: [1, "the cluster did not emit 'exit'"], + cluster_exitCode: [null, 'the cluster exited w/ incorrect exitCode'], + cluster_signalCode: [KILL_SIGNAL, 'the cluster exited w/ incorrect signalCode'], + worker_emitDisconnect: [1, "the worker did not emit 'disconnect'"], + worker_emitExit: [1, "the worker did not emit 'exit'"], + worker_state: ['disconnected', 'the worker state is incorrect'], + worker_suicideMode: [false, 'the worker.suicide flag is incorrect'], + worker_died: [true, 'the worker is still running'], + worker_exitCode: [null, 'the worker exited w/ incorrect exitCode'], + worker_signalCode: [KILL_SIGNAL, 'the worker exited w/ incorrect signalCode'] + }, + results = { + cluster_emitDisconnect: 0, + cluster_emitExit: 0, + worker_emitDisconnect: 0, + worker_emitExit: 0 + }; + + + // start worker + var worker = cluster.fork(); + + // when the worker is up and running, kill it + worker.once('listening', function() { + worker.process.kill(KILL_SIGNAL); + }); + + + // Check cluster events + cluster.on('disconnect', function() { + results.cluster_emitDisconnect += 1; + }); + cluster.on('exit', function(worker) { + results.cluster_exitCode = worker.process.exitCode; + results.cluster_signalCode = worker.process.signalCode; + results.cluster_emitExit += 1; + assert.ok(results.cluster_emitDisconnect, + "cluster: 'exit' event before 'disconnect' event"); + }); + + // Check worker eventes and properties + worker.on('disconnect', function() { + results.worker_emitDisconnect += 1; + results.worker_suicideMode = worker.suicide; + results.worker_state = worker.state; + }); + + // Check that the worker died + worker.once('exit', function(exitCode, signalCode) { + results.worker_exitCode = exitCode; + results.worker_signalCode = signalCode; + results.worker_emitExit += 1; + results.worker_died = !alive(worker.process.pid); + assert.ok(results.worker_emitDisconnect, + "worker: 'exit' event before 'disconnect' event"); + + process.nextTick(function() { finish_test(); }); + }); + + var finish_test = function() { + try { + checkResults(expected_results, results); + } catch (exc) { + console.error('FAIL: ' + exc.message); + if (exc.name != 'AssertionError') { + console.trace(exc); + } + + process.exit(1); + return; + } + process.exit(0); + }; +} + +// some helper functions ... + + function checkResults(expected_results, results) { + for (var k in expected_results) { + var actual = results[k], + expected = expected_results[k]; + + if (typeof expected === 'function') { + expected(r[k]); + } else { + var msg = (expected[1] || '') + + (' [expected: ' + expected[0] + ' / actual: ' + actual + ']'); + if (expected && expected.length) { + assert.equal(actual, expected[0], msg); + } else { + assert.equal(actual, expected, msg); + } + } + } + } + + function alive(pid) { + try { + process.kill(pid, 'SIGCONT'); + return true; + } catch (e) { + return false; + } + } diff --git a/node-v0.8.14/test/simple/test-console-not-call-toString.js b/node-v0.8.14/test/simple/test-console-not-call-toString.js new file mode 100644 index 0000000..a62004f --- /dev/null +++ b/node-v0.8.14/test/simple/test-console-not-call-toString.js @@ -0,0 +1,36 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + + + +var common = require('../common'); +var assert = require('assert'); + +var func = function() {}; +var toStringCalled = false; +func.toString = function() { + toStringCalled = true; +}; + +require('util').inspect(func); + +assert.ok(!toStringCalled); diff --git a/node-v0.8.14/test/simple/test-console.js b/node-v0.8.14/test/simple/test-console.js new file mode 100644 index 0000000..d07ca50 --- /dev/null +++ b/node-v0.8.14/test/simple/test-console.js @@ -0,0 +1,61 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + + + +var common = require('../common'); +var assert = require('assert'); + +assert.ok(process.stdout.writable); +assert.ok(process.stderr.writable); +// Support legacy API +assert.equal('number', typeof process.stdout.fd); +assert.equal('number', typeof process.stderr.fd); + + +var stdout_write = global.process.stdout.write; +var strings = []; +global.process.stdout.write = function(string) { + strings.push(string); +}; + +console.log('foo'); +console.log('foo', 'bar'); +console.log('%s %s', 'foo', 'bar', 'hop'); +console.log({slashes: '\\\\'}); + +global.process.stdout.write = stdout_write; +assert.equal('foo\n', strings.shift()); +assert.equal('foo bar\n', strings.shift()); +assert.equal('foo bar hop\n', strings.shift()); +assert.equal("{ slashes: '\\\\\\\\' }\n", strings.shift()); + +process.stderr.write('hello world'); + +assert.throws(function () { + console.timeEnd('no such label'); +}); + +assert.doesNotThrow(function () { + console.time('label'); + console.timeEnd('label'); +}); diff --git a/node-v0.8.14/test/simple/test-crypto-ecb.js b/node-v0.8.14/test/simple/test-crypto-ecb.js new file mode 100644 index 0000000..1ffaa4f --- /dev/null +++ b/node-v0.8.14/test/simple/test-crypto-ecb.js @@ -0,0 +1,51 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + + + +var common = require('../common'); +var assert = require('assert'); + +try { + var crypto = require('crypto'); +} catch (e) { + console.log('Not compiled with OPENSSL support.'); + process.exit(); +} + +// Testing whether EVP_CipherInit_ex is functioning correctly. +// Reference: bug#1997 + +(function() { + var encrypt = crypto.createCipheriv('BF-ECB', 'SomeRandomBlahz0c5GZVnR', ''); + var hex = encrypt.update('Hello World!', 'ascii', 'hex'); + hex += encrypt.final('hex'); + assert.equal(hex.toUpperCase(), '6D385F424AAB0CFBF0BB86E07FFB7D71'); +}()); + +(function() { + var decrypt = crypto.createDecipheriv('BF-ECB', 'SomeRandomBlahz0c5GZVnR', + ''); + var msg = decrypt.update('6D385F424AAB0CFBF0BB86E07FFB7D71', 'hex', 'ascii'); + msg += decrypt.final('ascii'); + assert.equal(msg, 'Hello World!'); +}()); diff --git a/node-v0.8.14/test/simple/test-crypto-padding.js b/node-v0.8.14/test/simple/test-crypto-padding.js new file mode 100644 index 0000000..f3f6632 --- /dev/null +++ b/node-v0.8.14/test/simple/test-crypto-padding.js @@ -0,0 +1,130 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); + +try { + var crypto = require('crypto'); +} catch (e) { + console.log('Not compiled with OPENSSL support.'); + process.exit(); +} + + +/* + * Input data + */ + +var ODD_LENGTH_PLAIN = 'Hello node world!', + EVEN_LENGTH_PLAIN = 'Hello node world!AbC09876dDeFgHi'; + +var KEY_PLAIN = 'S3c.r.e.t.K.e.Y!', + IV_PLAIN = 'blahFizz2011Buzz'; + +var CIPHER_NAME = 'aes-128-cbc'; + + +/* + * Expected result data + */ + +// echo -n 'Hello node world!' | \ +// openssl enc -aes-128-cbc -e -K 5333632e722e652e742e4b2e652e5921 \ +// -iv 626c616846697a7a3230313142757a7a | xxd -p -c256 +var ODD_LENGTH_ENCRYPTED = + '7f57859550d4d2fdb9806da2a750461a9fe77253cd1cbd4b07beee4e070d561f'; + +// echo -n 'Hello node world!AbC09876dDeFgHi' | \ +// openssl enc -aes-128-cbc -e -K 5333632e722e652e742e4b2e652e5921 \ +// -iv 626c616846697a7a3230313142757a7a | xxd -p -c256 +var EVEN_LENGTH_ENCRYPTED = + '7f57859550d4d2fdb9806da2a750461ab46e71b3d78ebe2d9684dfc87f7575b988' + + '6119866912cb8c7bcaf76c5ebc2378'; + +// echo -n 'Hello node world!AbC09876dDeFgHi' | \ +// openssl enc -aes-128-cbc -e -K 5333632e722e652e742e4b2e652e5921 \ +// -iv 626c616846697a7a3230313142757a7a -nopad | xxd -p -c256 +var EVEN_LENGTH_ENCRYPTED_NOPAD = + '7f57859550d4d2fdb9806da2a750461ab46e' + + '71b3d78ebe2d9684dfc87f7575b9'; + + +/* + * Helper wrappers + */ + +function enc(plain, pad) { + var encrypt = crypto.createCipheriv(CIPHER_NAME, KEY_PLAIN, IV_PLAIN); + encrypt.setAutoPadding(pad); + var hex = encrypt.update(plain, 'ascii', 'hex'); + hex += encrypt.final('hex'); + return hex; +} + +function dec(encd, pad) { + var decrypt = crypto.createDecipheriv(CIPHER_NAME, KEY_PLAIN, IV_PLAIN); + decrypt.setAutoPadding(pad); + var plain = decrypt.update(encd, 'hex'); + plain += decrypt.final('binary'); + return plain; +} + + +/* + * Test encryption + */ + +assert.equal(enc(ODD_LENGTH_PLAIN, true), ODD_LENGTH_ENCRYPTED); +assert.equal(enc(EVEN_LENGTH_PLAIN, true), EVEN_LENGTH_ENCRYPTED); + +assert.throws(function() { + // input must have block length % + enc(ODD_LENGTH_PLAIN, false); +}); + +assert.doesNotThrow(function() { + assert.equal(enc(EVEN_LENGTH_PLAIN, false), EVEN_LENGTH_ENCRYPTED_NOPAD); +}); + + +/* + * Test decryption + */ + +assert.equal(dec(ODD_LENGTH_ENCRYPTED, true), ODD_LENGTH_PLAIN); +assert.equal(dec(EVEN_LENGTH_ENCRYPTED, true), EVEN_LENGTH_PLAIN); + +assert.doesNotThrow(function() { + // returns including original padding + assert.equal(dec(ODD_LENGTH_ENCRYPTED, false).length, 32); + assert.equal(dec(EVEN_LENGTH_ENCRYPTED, false).length, 48); +}); + +assert.throws(function() { + // must have at least 1 byte of padding (PKCS): + assert.equal(dec(EVEN_LENGTH_ENCRYPTED_NOPAD, true), EVEN_LENGTH_PLAIN); +}); + +assert.doesNotThrow(function() { + // no-pad encrypted string should return the same: + assert.equal(dec(EVEN_LENGTH_ENCRYPTED_NOPAD, false), EVEN_LENGTH_PLAIN); +}); diff --git a/node-v0.8.14/test/simple/test-crypto-random.js b/node-v0.8.14/test/simple/test-crypto-random.js new file mode 100644 index 0000000..284c7ed --- /dev/null +++ b/node-v0.8.14/test/simple/test-crypto-random.js @@ -0,0 +1,70 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); + +try { + var crypto = require('crypto'); +} catch (e) { + console.log('Not compiled with OPENSSL support.'); + process.exit(); +} + +// bump, we register a lot of exit listeners +process.setMaxListeners(256); + +[crypto.randomBytes, + crypto.pseudoRandomBytes +].forEach(function(f) { + [-1, + undefined, + null, + false, + true, + {}, + [] + ].forEach(function(value) { + assert.throws(function() { f(value); }); + assert.throws(function() { f(value, function() {}); }); + }); + + [0, 1, 2, 4, 16, 256, 1024].forEach(function(len) { + f(len, checkCall(function(ex, buf) { + assert.equal(null, ex); + assert.equal(len, buf.length); + assert.ok(Buffer.isBuffer(buf)); + })); + }); +}); + +// assert that the callback is indeed called +function checkCall(cb, desc) { + var called_ = false; + + process.on('exit', function() { + assert.equal(true, called_, desc || ('callback not called: ' + cb)); + }); + + return function() { + return called_ = true, cb.apply(cb, Array.prototype.slice.call(arguments)); + }; +} diff --git a/node-v0.8.14/test/simple/test-crypto.js b/node-v0.8.14/test/simple/test-crypto.js new file mode 100644 index 0000000..535af76 --- /dev/null +++ b/node-v0.8.14/test/simple/test-crypto.js @@ -0,0 +1,667 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + + + +var common = require('../common'); +var assert = require('assert'); + +try { + var crypto = require('crypto'); +} catch (e) { + console.log('Not compiled with OPENSSL support.'); + process.exit(); +} + +var fs = require('fs'); +var path = require('path'); + +// Test Certificates +var caPem = fs.readFileSync(common.fixturesDir + '/test_ca.pem', 'ascii'); +var certPem = fs.readFileSync(common.fixturesDir + '/test_cert.pem', 'ascii'); +var certPfx = fs.readFileSync(common.fixturesDir + '/test_cert.pfx'); +var keyPem = fs.readFileSync(common.fixturesDir + '/test_key.pem', 'ascii'); +var rsaPubPem = fs.readFileSync(common.fixturesDir + '/test_rsa_pubkey.pem', + 'ascii'); +var rsaKeyPem = fs.readFileSync(common.fixturesDir + '/test_rsa_privkey.pem', + 'ascii'); + +try { + var credentials = crypto.createCredentials( + {key: keyPem, + cert: certPem, + ca: caPem}); +} catch (e) { + console.log('Not compiled with OPENSSL support.'); + process.exit(); +} + +// PFX tests +assert.doesNotThrow(function() { + crypto.createCredentials({pfx:certPfx, passphrase:'sample'}); +}); + +assert.throws(function() { + crypto.createCredentials({pfx:certPfx}); +}, 'mac verify failure'); + +assert.throws(function() { + crypto.createCredentials({pfx:certPfx, passphrase:'test'}); +}, 'mac verify failure'); + +assert.throws(function() { + crypto.createCredentials({pfx:'sample', passphrase:'test'}); +}, 'not enough data'); + +// Test HMAC +var h1 = crypto.createHmac('sha1', 'Node') + .update('some data') + .update('to hmac') + .digest('hex'); +assert.equal(h1, '19fd6e1ba73d9ed2224dd5094a71babe85d9a892', 'test HMAC'); + +// Test HMAC-SHA-* (rfc 4231 Test Cases) +var rfc4231 = [ + { + key: new Buffer('0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b', 'hex'), + data: new Buffer('4869205468657265', 'hex'), // 'Hi There' + hmac: { + sha224: '896fb1128abbdf196832107cd49df33f47b4b1169912ba4f53684b22', + sha256: + 'b0344c61d8db38535ca8afceaf0bf12b881dc200c9833da726e9376c' + + '2e32cff7', + sha384: + 'afd03944d84895626b0825f4ab46907f15f9dadbe4101ec682aa034c' + + '7cebc59cfaea9ea9076ede7f4af152e8b2fa9cb6', + sha512: + '87aa7cdea5ef619d4ff0b4241a1d6cb02379f4e2ce4ec2787ad0b305' + + '45e17cdedaa833b7d6b8a702038b274eaea3f4e4be9d914eeb61f170' + + '2e696c203a126854' + } + }, + { + key: new Buffer('4a656665', 'hex'), // 'Jefe' + data: new Buffer('7768617420646f2079612077616e7420666f72206e6f74686' + + '96e673f', 'hex'), // 'what do ya want for nothing?' + hmac: { + sha224: 'a30e01098bc6dbbf45690f3a7e9e6d0f8bbea2a39e6148008fd05e44', + sha256: + '5bdcc146bf60754e6a042426089575c75a003f089d2739839dec58b9' + + '64ec3843', + sha384: + 'af45d2e376484031617f78d2b58a6b1b9c7ef464f5a01b47e42ec373' + + '6322445e8e2240ca5e69e2c78b3239ecfab21649', + sha512: + '164b7a7bfcf819e2e395fbe73b56e0a387bd64222e831fd610270cd7' + + 'ea2505549758bf75c05a994a6d034f65f8f0e6fdcaeab1a34d4a6b4b' + + '636e070a38bce737' + } + }, + { + key: new Buffer('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', 'hex'), + data: new Buffer('ddddddddddddddddddddddddddddddddddddddddddddddddd' + + 'ddddddddddddddddddddddddddddddddddddddddddddddddddd', + 'hex'), + hmac: { + sha224: '7fb3cb3588c6c1f6ffa9694d7d6ad2649365b0c1f65d69d1ec8333ea', + sha256: + '773ea91e36800e46854db8ebd09181a72959098b3ef8c122d9635514' + + 'ced565fe', + sha384: + '88062608d3e6ad8a0aa2ace014c8a86f0aa635d947ac9febe83ef4e5' + + '5966144b2a5ab39dc13814b94e3ab6e101a34f27', + sha512: + 'fa73b0089d56a284efb0f0756c890be9b1b5dbdd8ee81a3655f83e33' + + 'b2279d39bf3e848279a722c806b485a47e67c807b946a337bee89426' + + '74278859e13292fb' + } + }, + { + key: new Buffer('0102030405060708090a0b0c0d0e0f10111213141516171819', + 'hex'), + data: new Buffer('cdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdc' + + 'dcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcd', + 'hex'), + hmac: { + sha224: '6c11506874013cac6a2abc1bb382627cec6a90d86efc012de7afec5a', + sha256: + '82558a389a443c0ea4cc819899f2083a85f0faa3e578f8077a2e3ff4' + + '6729665b', + sha384: + '3e8a69b7783c25851933ab6290af6ca77a9981480850009cc5577c6e' + + '1f573b4e6801dd23c4a7d679ccf8a386c674cffb', + sha512: + 'b0ba465637458c6990e5a8c5f61d4af7e576d97ff94b872de76f8050' + + '361ee3dba91ca5c11aa25eb4d679275cc5788063a5f19741120c4f2d' + + 'e2adebeb10a298dd' + } + }, + + { + key: new Buffer('0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c', 'hex'), + // 'Test With Truncation' + data: new Buffer('546573742057697468205472756e636174696f6e', 'hex'), + hmac: { + sha224: '0e2aea68a90c8d37c988bcdb9fca6fa8', + sha256: 'a3b6167473100ee06e0c796c2955552b', + sha384: '3abf34c3503b2a23a46efc619baef897', + sha512: '415fad6271580a531d4179bc891d87a6' + }, + truncate: true + }, + { + key: new Buffer('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + + 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + + 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + + 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + + 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + + 'aaaaaaaaaaaa', 'hex'), + // 'Test Using Larger Than Block-Size Key - Hash Key First' + data: new Buffer('54657374205573696e67204c6172676572205468616e20426' + + 'c6f636b2d53697a65204b6579202d2048617368204b657920' + + '4669727374', 'hex'), + hmac: { + sha224: '95e9a0db962095adaebe9b2d6f0dbce2d499f112f2d2b7273fa6870e', + sha256: + '60e431591ee0b67f0d8a26aacbf5b77f8e0bc6213728c5140546040f' + + '0ee37f54', + sha384: + '4ece084485813e9088d2c63a041bc5b44f9ef1012a2b588f3cd11f05' + + '033ac4c60c2ef6ab4030fe8296248df163f44952', + sha512: + '80b24263c7c1a3ebb71493c1dd7be8b49b46d1f41b4aeec1121b0137' + + '83f8f3526b56d037e05f2598bd0fd2215d6a1e5295e64f73f63f0aec' + + '8b915a985d786598' + } + }, + { + key: new Buffer('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + + 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + + 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + + 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + + 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + + 'aaaaaaaaaaaa', 'hex'), + // 'This is a test using a larger than block-size key and a larger ' + + // 'than block-size data. The key needs to be hashed before being ' + + // 'used by the HMAC algorithm.' + data: new Buffer('5468697320697320612074657374207573696e672061206c6' + + '172676572207468616e20626c6f636b2d73697a65206b6579' + + '20616e642061206c6172676572207468616e20626c6f636b2' + + 'd73697a6520646174612e20546865206b6579206e65656473' + + '20746f20626520686173686564206265666f7265206265696' + + 'e6720757365642062792074686520484d414320616c676f72' + + '6974686d2e', 'hex'), + hmac: { + sha224: '3a854166ac5d9f023f54d517d0b39dbd946770db9c2b95c9f6f565d1', + sha256: + '9b09ffa71b942fcb27635fbcd5b0e944bfdc63644f0713938a7f5153' + + '5c3a35e2', + sha384: + '6617178e941f020d351e2f254e8fd32c602420feb0b8fb9adccebb82' + + '461e99c5a678cc31e799176d3860e6110c46523e', + sha512: + 'e37b6a775dc87dbaa4dfa9f96e5e3ffddebd71f8867289865df5a32d' + + '20cdc944b6022cac3c4982b10d5eeb55c3e4de15134676fb6de04460' + + '65c97440fa8c6a58' + } + } +]; + +for (var i = 0, l = rfc4231.length; i < l; i++) { + for (var hash in rfc4231[i]['hmac']) { + var result = crypto.createHmac(hash, rfc4231[i]['key']) + .update(rfc4231[i]['data']) + .digest('hex'); + if (rfc4231[i]['truncate']) { + result = result.substr(0, 32); // first 128 bits == 32 hex chars + } + assert.equal(rfc4231[i]['hmac'][hash], + result, + 'Test HMAC-' + hash + ': Test case ' + (i + 1) + ' rfc 4231'); + } +} + +// Test HMAC-MD5/SHA1 (rfc 2202 Test Cases) +var rfc2202_md5 = [ + { + key: new Buffer('0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b', 'hex'), + data: 'Hi There', + hmac: '9294727a3638bb1c13f48ef8158bfc9d' + }, + { + key: 'Jefe', + data: 'what do ya want for nothing?', + hmac: '750c783e6ab0b503eaa86e310a5db738' + }, + { + key: new Buffer('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', 'hex'), + data: new Buffer('ddddddddddddddddddddddddddddddddddddddddddddddddd' + + 'ddddddddddddddddddddddddddddddddddddddddddddddddddd', + 'hex'), + hmac: '56be34521d144c88dbb8c733f0e8b3f6' + }, + { + key: new Buffer('0102030405060708090a0b0c0d0e0f10111213141516171819', + 'hex'), + data: new Buffer('cdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdc' + + 'dcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcd' + + 'cdcdcdcdcd', + 'hex'), + hmac: '697eaf0aca3a3aea3a75164746ffaa79' + }, + { + key: new Buffer('0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c', 'hex'), + data: 'Test With Truncation', + hmac: '56461ef2342edc00f9bab995690efd4c' + }, + { + key: new Buffer('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + + 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + + 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + + 'aaaaaaaaaaaaaaaaaaaaaa', + 'hex'), + data: 'Test Using Larger Than Block-Size Key - Hash Key First', + hmac: '6b1ab7fe4bd7bf8f0b62e6ce61b9d0cd' + }, + { + key: new Buffer('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + + 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + + 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + + 'aaaaaaaaaaaaaaaaaaaaaa', + 'hex'), + data: + 'Test Using Larger Than Block-Size Key and Larger Than One ' + + 'Block-Size Data', + hmac: '6f630fad67cda0ee1fb1f562db3aa53e' + } +]; +var rfc2202_sha1 = [ + { + key: new Buffer('0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b', 'hex'), + data: 'Hi There', + hmac: 'b617318655057264e28bc0b6fb378c8ef146be00' + }, + { + key: 'Jefe', + data: 'what do ya want for nothing?', + hmac: 'effcdf6ae5eb2fa2d27416d5f184df9c259a7c79' + }, + { + key: new Buffer('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', 'hex'), + data: new Buffer('ddddddddddddddddddddddddddddddddddddddddddddd' + + 'ddddddddddddddddddddddddddddddddddddddddddddd' + + 'dddddddddd', + 'hex'), + hmac: '125d7342b9ac11cd91a39af48aa17b4f63f175d3' + }, + { + key: new Buffer('0102030405060708090a0b0c0d0e0f10111213141516171819', + 'hex'), + data: new Buffer('cdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdc' + + 'dcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcd' + + 'cdcdcdcdcd', + 'hex'), + hmac: '4c9007f4026250c6bc8414f9bf50c86c2d7235da' + }, + { + key: new Buffer('0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c', 'hex'), + data: 'Test With Truncation', + hmac: '4c1a03424b55e07fe7f27be1d58bb9324a9a5a04' + }, + { + key: new Buffer('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + + 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + + 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + + 'aaaaaaaaaaaaaaaaaaaaaa', + 'hex'), + data: 'Test Using Larger Than Block-Size Key - Hash Key First', + hmac: 'aa4ae5e15272d00e95705637ce8a3b55ed402112' + }, + { + key: new Buffer('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + + 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + + 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + + 'aaaaaaaaaaaaaaaaaaaaaa', + 'hex'), + data: + 'Test Using Larger Than Block-Size Key and Larger Than One ' + + 'Block-Size Data', + hmac: 'e8e99d0f45237d786d6bbaa7965c7808bbff1a91' + } +]; + +for (var i = 0, l = rfc2202_md5.length; i < l; i++) { + assert.equal(rfc2202_md5[i]['hmac'], + crypto.createHmac('md5', rfc2202_md5[i]['key']) + .update(rfc2202_md5[i]['data']) + .digest('hex'), + 'Test HMAC-MD5 : Test case ' + (i + 1) + ' rfc 2202'); +} +for (var i = 0, l = rfc2202_sha1.length; i < l; i++) { + assert.equal(rfc2202_sha1[i]['hmac'], + crypto.createHmac('sha1', rfc2202_sha1[i]['key']) + .update(rfc2202_sha1[i]['data']) + .digest('hex'), + 'Test HMAC-SHA1 : Test case ' + (i + 1) + ' rfc 2202'); +} + +// Test hashing +var a0 = crypto.createHash('sha1').update('Test123').digest('hex'); +var a1 = crypto.createHash('md5').update('Test123').digest('binary'); +var a2 = crypto.createHash('sha256').update('Test123').digest('base64'); +var a3 = crypto.createHash('sha512').update('Test123').digest(); // binary + +assert.equal(a0, '8308651804facb7b9af8ffc53a33a22d6a1c8ac2', 'Test SHA1'); +assert.equal(a1, 'h\u00ea\u00cb\u0097\u00d8o\fF!\u00fa+\u000e\u0017\u00ca' + + '\u00bd\u008c', 'Test MD5 as binary'); +assert.equal(a2, '2bX1jws4GYKTlxhloUB09Z66PoJZW+y+hq5R8dnx9l4=', + 'Test SHA256 as base64'); +assert.equal(a3, '\u00c1(4\u00f1\u0003\u001fd\u0097!O\'\u00d4C/&Qz\u00d4' + + '\u0094\u0015l\u00b8\u008dQ+\u00db\u001d\u00c4\u00b5}\u00b2' + + '\u00d6\u0092\u00a3\u00df\u00a2i\u00a1\u009b\n\n*\u000f' + + '\u00d7\u00d6\u00a2\u00a8\u0085\u00e3<\u0083\u009c\u0093' + + '\u00c2\u0006\u00da0\u00a1\u00879(G\u00ed\'', + 'Test SHA512 as assumed binary'); + +// Test multiple updates to same hash +var h1 = crypto.createHash('sha1').update('Test123').digest('hex'); +var h2 = crypto.createHash('sha1').update('Test').update('123').digest('hex'); +assert.equal(h1, h2, 'multipled updates'); + +// Test hashing for binary files +var fn = path.join(common.fixturesDir, 'sample.png'); +var sha1Hash = crypto.createHash('sha1'); +var fileStream = fs.createReadStream(fn); +fileStream.on('data', function(data) { + sha1Hash.update(data); +}); +fileStream.on('close', function() { + assert.equal(sha1Hash.digest('hex'), + '22723e553129a336ad96e10f6aecdf0f45e4149e', + 'Test SHA1 of sample.png'); +}); + +// Issue #2227: unknown digest method should throw an error. +assert.throws(function() { + crypto.createHash('xyzzy'); +}); + +// Test signing and verifying +var s1 = crypto.createSign('RSA-SHA1') + .update('Test123') + .sign(keyPem, 'base64'); +var verified = crypto.createVerify('RSA-SHA1') + .update('Test') + .update('123') + .verify(certPem, s1, 'base64'); +assert.strictEqual(verified, true, 'sign and verify (base 64)'); + +var s2 = crypto.createSign('RSA-SHA256') + .update('Test123') + .sign(keyPem); // binary +var verified = crypto.createVerify('RSA-SHA256') + .update('Test') + .update('123') + .verify(certPem, s2); // binary +assert.strictEqual(verified, true, 'sign and verify (binary)'); + + +function testCipher1(key) { + // Test encryption and decryption + var plaintext = 'Keep this a secret? No! Tell everyone about node.js!'; + var cipher = crypto.createCipher('aes192', key); + + // encrypt plaintext which is in utf8 format + // to a ciphertext which will be in hex + var ciph = cipher.update(plaintext, 'utf8', 'hex'); + // Only use binary or hex, not base64. + ciph += cipher.final('hex'); + + var decipher = crypto.createDecipher('aes192', key); + var txt = decipher.update(ciph, 'hex', 'utf8'); + txt += decipher.final('utf8'); + + assert.equal(txt, plaintext, 'encryption and decryption'); +} + + +function testCipher2(key) { + // encryption and decryption with Base64 + // reported in https://github.com/joyent/node/issues/738 + var plaintext = + '32|RmVZZkFUVmpRRkp0TmJaUm56ZU9qcnJkaXNNWVNpTTU*|iXmckfRWZBGWWELw' + + 'eCBsThSsfUHLeRe0KCsK8ooHgxie0zOINpXxfZi/oNG7uq9JWFVCk70gfzQH8ZUJ' + + 'jAfaFg**'; + var cipher = crypto.createCipher('aes256', key); + + // encrypt plaintext which is in utf8 format + // to a ciphertext which will be in Base64 + var ciph = cipher.update(plaintext, 'utf8', 'base64'); + ciph += cipher.final('base64'); + + var decipher = crypto.createDecipher('aes256', key); + var txt = decipher.update(ciph, 'base64', 'utf8'); + txt += decipher.final('utf8'); + + assert.equal(txt, plaintext, 'encryption and decryption with Base64'); +} + + +function testCipher3(key, iv) { + // Test encyrption and decryption with explicit key and iv + var plaintext = + '32|RmVZZkFUVmpRRkp0TmJaUm56ZU9qcnJkaXNNWVNpTTU*|iXmckfRWZBGWWELw' + + 'eCBsThSsfUHLeRe0KCsK8ooHgxie0zOINpXxfZi/oNG7uq9JWFVCk70gfzQH8ZUJ' + + 'jAfaFg**'; + var cipher = crypto.createCipheriv('des-ede3-cbc', key, iv); + var ciph = cipher.update(plaintext, 'utf8', 'hex'); + ciph += cipher.final('hex'); + + var decipher = crypto.createDecipheriv('des-ede3-cbc', key, iv); + var txt = decipher.update(ciph, 'hex', 'utf8'); + txt += decipher.final('utf8'); + + assert.equal(txt, plaintext, 'encryption and decryption with key and iv'); +} + + +testCipher1('MySecretKey123'); +testCipher1(new Buffer('MySecretKey123')); + +testCipher2('0123456789abcdef'); +testCipher2(new Buffer('0123456789abcdef')); + +testCipher3('0123456789abcd0123456789', '12345678'); +testCipher3('0123456789abcd0123456789', new Buffer('12345678')); +testCipher3(new Buffer('0123456789abcd0123456789'), '12345678'); +testCipher3(new Buffer('0123456789abcd0123456789'), new Buffer('12345678')); + + +// update() should only take buffers / strings +assert.throws(function() { + crypto.createHash('sha1').update({foo: 'bar'}); +}, /string or buffer/); + + +// Test Diffie-Hellman with two parties sharing a secret, +// using various encodings as we go along +var dh1 = crypto.createDiffieHellman(256); +var p1 = dh1.getPrime('base64'); +var dh2 = crypto.createDiffieHellman(p1, 'base64'); +var key1 = dh1.generateKeys(); +var key2 = dh2.generateKeys('hex'); +var secret1 = dh1.computeSecret(key2, 'hex', 'base64'); +var secret2 = dh2.computeSecret(key1, 'binary', 'base64'); + +assert.equal(secret1, secret2); + +// Create "another dh1" using generated keys from dh1, +// and compute secret again +var dh3 = crypto.createDiffieHellman(p1, 'base64'); +var privkey1 = dh1.getPrivateKey(); +dh3.setPublicKey(key1); +dh3.setPrivateKey(privkey1); + +assert.equal(dh1.getPrime(), dh3.getPrime()); +assert.equal(dh1.getGenerator(), dh3.getGenerator()); +assert.equal(dh1.getPublicKey(), dh3.getPublicKey()); +assert.equal(dh1.getPrivateKey(), dh3.getPrivateKey()); + +var secret3 = dh3.computeSecret(key2, 'hex', 'base64'); + +assert.equal(secret1, secret3); + +assert.throws(function() { + dh3.computeSecret(''); +}, /key is too small/i); + +// https://github.com/joyent/node/issues/2338 +assert.throws(function() { + var p = 'FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74' + + '020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F1437' + + '4FE1356D6D51C245E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED' + + 'EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE65381FFFFFFFFFFFFFFFF'; + crypto.createDiffieHellman(p, 'hex'); +}); + +// Test RSA key signing/verification +var rsaSign = crypto.createSign('RSA-SHA1'); +var rsaVerify = crypto.createVerify('RSA-SHA1'); +assert.ok(rsaSign); +assert.ok(rsaVerify); + +rsaSign.update(rsaPubPem); +var rsaSignature = rsaSign.sign(rsaKeyPem, 'hex'); +assert.equal(rsaSignature, + '5c50e3145c4e2497aadb0eabc83b342d0b0021ece0d4c4a064b7c' + + '8f020d7e2688b122bfb54c724ac9ee169f83f66d2fe90abeb95e8' + + 'e1290e7e177152a4de3d944cf7d4883114a20ed0f78e70e25ef0f' + + '60f06b858e6af42a2f276ede95bbc6bc9a9bbdda15bd663186a6f' + + '40819a7af19e577bb2efa5e579a1f5ce8a0d4ca8b8f6'); + +rsaVerify.update(rsaPubPem); +assert.strictEqual(rsaVerify.verify(rsaPubPem, rsaSignature, 'hex'), true); + + +// +// Test RSA signing and verification +// +(function() { + var privateKey = fs.readFileSync( + common.fixturesDir + '/test_rsa_privkey_2.pem'); + + var publicKey = fs.readFileSync( + common.fixturesDir + '/test_rsa_pubkey_2.pem'); + + var input = 'I AM THE WALRUS'; + + var signature = + '79d59d34f56d0e94aa6a3e306882b52ed4191f07521f25f505a078dc2f89' + + '396e0c8ac89e996fde5717f4cb89199d8fec249961fcb07b74cd3d2a4ffa' + + '235417b69618e4bcd76b97e29975b7ce862299410e1b522a328e44ac9bb2' + + '8195e0268da7eda23d9825ac43c724e86ceeee0d0d4465678652ccaf6501' + + '0ddfb299bedeb1ad'; + + var sign = crypto.createSign('RSA-SHA256'); + sign.update(input); + + var output = sign.sign(privateKey, 'hex'); + assert.equal(output, signature); + + var verify = crypto.createVerify('RSA-SHA256'); + verify.update(input); + + assert.strictEqual(verify.verify(publicKey, signature, 'hex'), true); +})(); + + +// +// Test DSA signing and verification +// +(function() { + var privateKey = fs.readFileSync( + common.fixturesDir + '/test_dsa_privkey.pem'); + + var publicKey = fs.readFileSync( + common.fixturesDir + '/test_dsa_pubkey.pem'); + + var input = 'I AM THE WALRUS'; + + // DSA signatures vary across runs so there is no static string to verify + // against + var sign = crypto.createSign('DSS1'); + sign.update(input); + var signature = sign.sign(privateKey, 'hex'); + + var verify = crypto.createVerify('DSS1'); + verify.update(input); + + assert.strictEqual(verify.verify(publicKey, signature, 'hex'), true); +})(); + + +// +// Test PBKDF2 with RFC 6070 test vectors (except #4) +// +crypto.pbkdf2('password', 'salt', 1, 20, function(err, result) { + assert.equal(result, + '\x0c\x60\xc8\x0f\x96\x1f\x0e\x71\xf3\xa9\xb5\x24' + + '\xaf\x60\x12\x06\x2f\xe0\x37\xa6', + 'pbkdf1 test vector 1'); +}); + +crypto.pbkdf2('password', 'salt', 2, 20, function(err, result) { + assert.equal(result, + '\xea\x6c\x01\x4d\xc7\x2d\x6f\x8c\xcd\x1e\xd9\x2a' + + '\xce\x1d\x41\xf0\xd8\xde\x89\x57', + 'pbkdf1 test vector 2'); +}); + +crypto.pbkdf2('password', 'salt', 4096, 20, function(err, result) { + assert.equal(result, + '\x4b\x00\x79\x01\xb7\x65\x48\x9a\xbe\xad\x49\xd9\x26' + + '\xf7\x21\xd0\x65\xa4\x29\xc1', + 'pbkdf1 test vector 3'); +}); + +crypto.pbkdf2( + 'passwordPASSWORDpassword', + 'saltSALTsaltSALTsaltSALTsaltSALTsalt', + 4096, + 25, function(err, result) { + assert.equal(result, + '\x3d\x2e\xec\x4f\xe4\x1c\x84\x9b\x80\xc8\xd8\x36\x62' + + '\xc0\xe4\x4a\x8b\x29\x1a\x96\x4c\xf2\xf0\x70\x38', + 'pbkdf1 test vector 5'); + }); + +crypto.pbkdf2('pass\0word', 'sa\0lt', 4096, 16, function(err, result) { + assert.equal(result, + '\x56\xfa\x6a\xa7\x55\x48\x09\x9d\xcc\x37\xd7\xf0\x34' + + '\x25\xe0\xc3', + 'pbkdf1 test vector 6'); +}); + +// Error path should not leak memory (check with valgrind). +assert.throws(function() { + crypto.pbkdf2('password', 'salt', 1, 20, null); +}); diff --git a/node-v0.8.14/test/simple/test-debugger-client.js b/node-v0.8.14/test/simple/test-debugger-client.js new file mode 100644 index 0000000..5102a7b --- /dev/null +++ b/node-v0.8.14/test/simple/test-debugger-client.js @@ -0,0 +1,200 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + + + +var common = require('../common'); +var assert = require('assert'); +var debug = require('_debugger'); + +var spawn = require('child_process').spawn; + + +var resCount = 0; +var p = new debug.Protocol(); +p.onResponse = function(res) { + resCount++; +}; + +p.execute('Type: connect\r\n' + + 'V8-Version: 3.0.4.1\r\n' + + 'Protocol-Version: 1\r\n' + + 'Embedding-Host: node v0.3.3-pre\r\n' + + 'Content-Length: 0\r\n\r\n'); +assert.equal(1, resCount); + +// Make sure split messages go in. + +var parts = []; +parts.push('Content-Length: 336\r\n'); +assert.equal(21, parts[0].length); +parts.push('\r\n'); +assert.equal(2, parts[1].length); +var bodyLength = 0; + +parts.push('{"seq":12,"type":"event","event":"break","body":' + + '{"invocationText":"#'); +assert.equal(78, parts[2].length); +bodyLength += parts[2].length; + +parts.push('.[anonymous](req=#, ' + + 'res=#)","sourceLine"'); +assert.equal(78, parts[3].length); +bodyLength += parts[3].length; + +parts.push(':45,"sourceColumn":4,"sourceLineText":" debugger;",' + + '"script":{"id":24,"name":"/home/ryan/projects/node/' + + 'benchmark/http_simple.js","lineOffset":0,"columnOffset":0,' + + '"lineCount":98}}}'); +assert.equal(180, parts[4].length); +bodyLength += parts[4].length; + +assert.equal(336, bodyLength); + +for (var i = 0; i < parts.length; i++) { + p.execute(parts[i]); +} +assert.equal(2, resCount); + + +// Make sure that if we get backed up, we still manage to get all the +// messages +var d = 'Content-Length: 466\r\n\r\n' + + '{"seq":10,"type":"event","event":"afterCompile","success":true,' + + '"body":{"script":{"handle":1,"type":"script","name":"dns.js",' + + '"id":34,"lineOffset":0,"columnOffset":0,"lineCount":241,' + + '"sourceStart":"(function (module, exports, require) {' + + 'var dns = process.binding(\'cares\')' + + ';\\nvar ne","sourceLength":6137,"scriptType":2,"compilationType":0,' + + '"context":{"ref":0},"text":"dns.js (lines: 241)"}},"refs":' + + '[{"handle":0' + + ',"type":"context","text":"#"}],"running":true}' + + 'Content-Length: 119\r\n\r\n' + + '{"seq":11,"type":"event","event":"scriptCollected","success":true,' + + '"body":{"script":{"id":26}},"refs":[],"running":true}'; +p.execute(d); +assert.equal(4, resCount); + +var expectedConnections = 0; +var tests = []; +function addTest(cb) { + expectedConnections++; + tests.push(cb); +} + +addTest(function(client, done) { + console.error('requesting version'); + client.reqVersion(function(err, v) { + assert.ok(!err); + console.log('version: %s', v); + assert.equal(process.versions.v8, v); + done(); + }); +}); + +addTest(function(client, done) { + console.error('requesting scripts'); + client.reqScripts(function(err) { + assert.ok(!err); + console.error('got %d scripts', Object.keys(client.scripts).length); + + var foundMainScript = false; + for (var k in client.scripts) { + var script = client.scripts[k]; + if (script && script.name === 'node.js') { + foundMainScript = true; + break; + } + } + assert.ok(foundMainScript); + done(); + }); +}); + +addTest(function(client, done) { + console.error('eval 2+2'); + client.reqEval('2+2', function(err, res) { + console.error(res); + assert.ok(!err); + assert.equal('4', res.text); + assert.equal(4, res.value); + done(); + }); +}); + + +var connectCount = 0; + +function doTest(cb, done) { + var nodeProcess = spawn(process.execPath, + ['-e', 'setInterval(function () { console.log("blah"); }, 100);']); + + nodeProcess.stdout.once('data', function() { + console.log('>>> new node process: %d', nodeProcess.pid); + process._debugProcess(nodeProcess.pid); + console.log('>>> starting debugger session'); + }); + + var didTryConnect = false; + nodeProcess.stderr.setEncoding('utf8'); + var b = ''; + nodeProcess.stderr.on('data', function(data) { + b += data; + if (didTryConnect == false && /debugger listening on port/.test(b)) { + didTryConnect = true; + + setTimeout(function() { + // Wait for some data before trying to connect + var c = new debug.Client(); + process.stdout.write('>>> connecting...'); + c.connect(debug.port); + c.on('ready', function() { + connectCount++; + console.log('ready!'); + cb(c, function() { + console.error('>>> killing node process %d\n\n', nodeProcess.pid); + nodeProcess.kill(); + done(); + }); + }); + }, 100); + } + }); +} + + +function run() { + var t = tests[0]; + if (!t) return; + + doTest(t, function() { + tests.shift(); + run(); + }); +} + +run(); + +process.on('exit', function() { + assert.equal(expectedConnections, connectCount); +}); + diff --git a/node-v0.8.14/test/simple/test-debugger-repl-utf8.js b/node-v0.8.14/test/simple/test-debugger-repl-utf8.js new file mode 100644 index 0000000..e141913 --- /dev/null +++ b/node-v0.8.14/test/simple/test-debugger-repl-utf8.js @@ -0,0 +1,178 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + +var common = require('../common'); +var assert = require('assert'); +var spawn = require('child_process').spawn; +var debug = require('_debugger'); + +var port = common.PORT + 1337; + +var script = common.fixturesDir + '/breakpoints_utf8.js'; + +var child = spawn(process.execPath, ['debug', '--port=' + port, script]); + +console.error('./node', 'debug', '--port=' + port, script); + +var buffer = ''; +child.stdout.setEncoding('utf-8'); +child.stdout.on('data', function(data) { + data = (buffer + data.toString()).split(/\n/g); + buffer = data.pop(); + data.forEach(function(line) { + child.emit('line', line); + }); +}); +child.stderr.pipe(process.stdout); + +var expected = []; + +child.on('line', function(line) { + line = line.replace(/^(debug> )+/, 'debug> '); + console.error('line> ' + line); + assert.ok(expected.length > 0, 'Got unexpected line: ' + line); + + var expectedLine = expected[0].lines.shift(); + assert.ok(line.match(expectedLine) !== null, line + ' != ' + expectedLine); + + if (expected[0].lines.length === 0) { + var callback = expected[0].callback; + expected.shift(); + callback && callback(); + } +}); + +function addTest(input, output) { + function next() { + if (expected.length > 0) { + child.stdin.write(expected[0].input + '\n'); + + if (!expected[0].lines) { + setTimeout(function() { + var callback = expected[0].callback; + expected.shift(); + + callback && callback(); + }, 50); + } + } else { + finish(); + } + }; + expected.push({input: input, lines: output, callback: next}); +} + +// Initial lines +addTest(null, [ + /listening on port \d+/, + /connecting... ok/, + /break in .*:1/, + /1/, /2/, /3/ +]); + +// Next +addTest('n', [ + /break in .*:11/, + /9/, /10/, /11/, /12/, /13/ +]); + +// Watch +addTest('watch("\'x\'")'); + +// Continue +addTest('c', [ + /break in .*:5/, + /Watchers/, + /0:\s+'x' = "x"/, + /()/, + /3/, /4/, /5/, /6/, /7/ +]); + +// Show watchers +addTest('watchers', [ + /0:\s+'x' = "x"/ +]); + +// Unwatch +addTest('unwatch("\'x\'")'); + +// Step out +addTest('o', [ + /break in .*:12/, + /10/, /11/, /12/, /13/, /14/ +]); + +// Continue +addTest('c', [ + /break in .*:5/, + /3/, /4/, /5/, /6/, /7/ +]); + +// Set breakpoint by function name +addTest('sb("setInterval()", "!(setInterval.flag++)")', [ + /1/, /2/, /3/, /4/, /5/, /6/, /7/, /8/, /9/, /10/ +]); + +// Continue +addTest('c', [ + /break in node.js:\d+/, + /\d/, /\d/, /\d/, /\d/, /\d/ +]); + +function finish() { + process.exit(0); +} + +function quit() { + if (quit.called) return; + quit.called = true; + child.stdin.write('quit'); +} + +setTimeout(function() { + console.error('dying badly'); + var err = 'Timeout'; + if (expected.length > 0 && expected[0].lines) { + err = err + '. Expected: ' + expected[0].lines.shift(); + } + quit(); + child.kill('SIGKILL'); + + // give the sigkill time to work. + setTimeout(function() { + throw new Error(err); + }, 100); + +}, 5000); + +process.once('uncaughtException', function(e) { + quit(); + console.error(e.toString()); + process.exit(1); +}); + +process.on('exit', function(code) { + quit(); + if (code === 0) { + assert.equal(expected.length, 0); + } +}); diff --git a/node-v0.8.14/test/simple/test-debugger-repl.js b/node-v0.8.14/test/simple/test-debugger-repl.js new file mode 100644 index 0000000..14092bc --- /dev/null +++ b/node-v0.8.14/test/simple/test-debugger-repl.js @@ -0,0 +1,195 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + +var common = require('../common'); +var assert = require('assert'); +var spawn = require('child_process').spawn; +var debug = require('_debugger'); + +var port = common.PORT + 1337; + +var script = common.fixturesDir + '/breakpoints.js'; + +var child = spawn(process.execPath, ['debug', '--port=' + port, script]); + +console.error('./node', 'debug', '--port=' + port, script); + +var buffer = ''; +child.stdout.setEncoding('utf-8'); +child.stdout.on('data', function(data) { + data = (buffer + data.toString()).split(/\n/g); + buffer = data.pop(); + data.forEach(function(line) { + child.emit('line', line); + }); +}); +child.stderr.pipe(process.stdout); + +var expected = []; + +child.on('line', function(line) { + line = line.replace(/^(debug> )+/, 'debug> '); + console.error('line> ' + line); + assert.ok(expected.length > 0, 'Got unexpected line: ' + line); + + var expectedLine = expected[0].lines.shift(); + assert.ok(line.match(expectedLine) !== null, line + ' != ' + expectedLine); + + if (expected[0].lines.length === 0) { + var callback = expected[0].callback; + expected.shift(); + callback && callback(); + } +}); + +function addTest(input, output) { + function next() { + if (expected.length > 0) { + var res = child.stdin.write(expected[0].input + '\n'), + callback; + + if (!expected[0].lines) { + callback = expected[0].callback; + expected.shift(); + } + + if (callback) { + if (res !== true) { + child.stdin.on('drain', callback); + } else { + process.nextTick(callback); + } + } + } else { + finish(); + } + }; + expected.push({input: input, lines: output, callback: next}); +} + +// Initial lines +addTest(null, [ + /listening on port \d+/, + /connecting... ok/, + /break in .*:1/, + /1/, /2/, /3/ +]); + +// Next +addTest('n', [ + /break in .*:11/, + /9/, /10/, /11/, /12/, /13/ +]); + +// Watch +addTest('watch("\'x\'"), true', [/true/]); + +// Continue +addTest('c', [ + /break in .*:5/, + /Watchers/, + /0:\s+'x' = "x"/, + /()/, + /3/, /4/, /5/, /6/, /7/ +]); + +// Show watchers +addTest('watchers', [ + /0:\s+'x' = "x"/ +]); + +// Unwatch +addTest('unwatch("\'x\'"), true', [/true/]); + +// Step out +addTest('o', [ + /break in .*:12/, + /10/, /11/, /12/, /13/, /14/ +]); + +// Continue +addTest('c', [ + /break in .*:5/, + /3/, /4/, /5/, /6/, /7/ +]); + +// Set breakpoint by function name +addTest('sb("setInterval()", "!(setInterval.flag++)")', [ + /1/, /2/, /3/, /4/, /5/, /6/, /7/, /8/, /9/, /10/ +]); + +// Continue +addTest('c', [ + /break in node.js:\d+/, + /\d/, /\d/, /\d/, /\d/, /\d/ +]); + +addTest('c', [ + /break in .*breakpoints.js:\d+/, + /\d/, /\d/, /\d/, /\d/, /\d/ +]); + +addTest('repl', [ + /Press Ctrl \+ C to leave debug repl/ +]); + +addTest('now', [ + /\w* \w* \d* \d* \d*:\d*:\d* GMT[+-]\d* (\w*)/ +]); + +function finish() { + process.exit(0); +} + +function quit() { + if (quit.called) return; + quit.called = true; + child.stdin.write('quit'); +} + +setTimeout(function() { + var err = 'Timeout'; + if (expected.length > 0 && expected[0].lines) { + err = err + '. Expected: ' + expected[0].lines.shift(); + } + quit(); + child.kill('SIGKILL'); + + // give the sigkill time to work. + setTimeout(function() { + throw new Error(err); + }, 100); + +}, 5000); + +process.once('uncaughtException', function(e) { + quit(); + console.error(e.toString()); + process.exit(1); +}); + +process.on('exit', function(code) { + quit(); + if (code === 0) { + assert.equal(expected.length, 0); + } +}); diff --git a/node-v0.8.14/test/simple/test-delayed-require.js b/node-v0.8.14/test/simple/test-delayed-require.js new file mode 100644 index 0000000..31c3249 --- /dev/null +++ b/node-v0.8.14/test/simple/test-delayed-require.js @@ -0,0 +1,34 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); + +var a; +setTimeout(function() { + a = require('../fixtures/a'); +}, 50); + +process.on('exit', function() { + assert.equal(true, 'A' in a); + assert.equal('A', a.A()); + assert.equal('D', a.D()); +}); diff --git a/node-v0.8.14/test/simple/test-deprecation-flags.js b/node-v0.8.14/test/simple/test-deprecation-flags.js new file mode 100644 index 0000000..81605da --- /dev/null +++ b/node-v0.8.14/test/simple/test-deprecation-flags.js @@ -0,0 +1,57 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var execFile = require('child_process').execFile; +var depmod = require.resolve('../fixtures/deprecated.js'); +var node = process.execPath; + +var normal = [depmod]; +var noDep = ['--no-deprecation', depmod]; +var traceDep = ['--trace-deprecation', depmod]; + +execFile(node, normal, function(er, stdout, stderr) { + console.error('normal: show deprecation warning'); + assert.equal(er, null); + assert.equal(stdout, ''); + assert.equal(stderr, 'util.p: Use console.error() instead.\n\'This is deprecated\'\n'); + console.log('normal ok'); +}); + +execFile(node, noDep, function(er, stdout, stderr) { + console.error('--no-deprecation: silence deprecations'); + assert.equal(er, null); + assert.equal(stdout, ''); + assert.equal(stderr, '\'This is deprecated\'\n'); + console.log('silent ok'); +}); + +execFile(node, traceDep, function(er, stdout, stderr) { + console.error('--trace-deprecation: show stack'); + assert.equal(er, null); + assert.equal(stdout, ''); + var stack = stderr.trim().split('\n'); + // just check the top and bottom. + assert.equal(stack[0], 'Trace: util.p: Use console.error() instead.'); + assert.equal(stack.pop(), '\'This is deprecated\''); + console.log('trace ok'); +}); diff --git a/node-v0.8.14/test/simple/test-dgram-address.js b/node-v0.8.14/test/simple/test-dgram-address.js new file mode 100644 index 0000000..30d8eb0 --- /dev/null +++ b/node-v0.8.14/test/simple/test-dgram-address.js @@ -0,0 +1,64 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var dgram = require('dgram'); + +// IPv4 Test +var localhost_ipv4 = '127.0.0.1'; +var socket_ipv4 = dgram.createSocket('udp4'); +var family_ipv4 = 'IPv4'; + +socket_ipv4.on('listening', function() { + var address_ipv4 = socket_ipv4.address(); + assert.strictEqual(address_ipv4.address, localhost_ipv4); + assert.strictEqual(address_ipv4.port, common.PORT); + assert.strictEqual(address_ipv4.family, family_ipv4); + socket_ipv4.close(); +}); + +socket_ipv4.on('error', function(e) { + console.log('Error on udp4 socket. ' + e.toString()); + socket_ipv4.close(); +}); + +socket_ipv4.bind(common.PORT, localhost_ipv4); + +// IPv6 Test +var localhost_ipv6 = '::1'; +var socket_ipv6 = dgram.createSocket('udp6'); +var family_ipv6 = 'IPv6'; + +socket_ipv6.on('listening', function() { + var address_ipv6 = socket_ipv6.address(); + assert.strictEqual(address_ipv6.address, localhost_ipv6); + assert.strictEqual(address_ipv6.port, common.PORT); + assert.strictEqual(address_ipv6.family, family_ipv6); + socket_ipv6.close(); +}); + +socket_ipv6.on('error', function(e) { + console.log('Error on udp6 socket. ' + e.toString()); + socket_ipv6.close(); +}); + +socket_ipv6.bind(common.PORT, localhost_ipv6); diff --git a/node-v0.8.14/test/simple/test-dgram-bind.js b/node-v0.8.14/test/simple/test-dgram-bind.js new file mode 100644 index 0000000..8ee6763 --- /dev/null +++ b/node-v0.8.14/test/simple/test-dgram-bind.js @@ -0,0 +1,32 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var dgram = require('dgram'); + +var socket = dgram.createSocket('udp4'); + +socket.on('listening', function () { + socket.close(); +}); + +socket.bind(); // should not throw diff --git a/node-v0.8.14/test/simple/test-dgram-broadcast-multi-process.js b/node-v0.8.14/test/simple/test-dgram-broadcast-multi-process.js new file mode 100644 index 0000000..7b3aa4d --- /dev/null +++ b/node-v0.8.14/test/simple/test-dgram-broadcast-multi-process.js @@ -0,0 +1,220 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'), + assert = require('assert'), + dgram = require('dgram'), + util = require('util'), + assert = require('assert'), + Buffer = require('buffer').Buffer, + fork = require('child_process').fork, + LOCAL_BROADCAST_HOST = '255.255.255.255', + TIMEOUT = 5000, + messages = [ + new Buffer('First message to send'), + new Buffer('Second message to send'), + new Buffer('Third message to send'), + new Buffer('Fourth message to send') + ]; + +if (process.argv[2] !== 'child') { + var workers = {}, + listeners = 3, + listening = 0, + dead = 0, + i = 0, + done = 0, + timer = null; + + //exit the test if it doesn't succeed within TIMEOUT + timer = setTimeout(function() { + console.error('[PARENT] Responses were not received within %d ms.', + TIMEOUT); + console.error('[PARENT] Fail'); + + killChildren(workers); + + process.exit(1); + }, TIMEOUT); + + //launch child processes + for (var x = 0; x < listeners; x++) { + (function() { + var worker = fork(process.argv[1], ['child']); + workers[worker.pid] = worker; + + worker.messagesReceived = []; + + //handle the death of workers + worker.on('exit', function(code, signal) { + // don't consider this the true death if the worker + // has finished successfully + // or if the exit code is 0 + if (worker.isDone || code == 0) { + return; + } + + dead += 1; + console.error('[PARENT] Worker %d died. %d dead of %d', + worker.pid, + dead, + listeners); + + if (dead === listeners) { + console.error('[PARENT] All workers have died.'); + console.error('[PARENT] Fail'); + + killChildren(workers); + + process.exit(1); + } + }); + + worker.on('message', function(msg) { + if (msg.listening) { + listening += 1; + + if (listening === listeners) { + //all child process are listening, so start sending + sendSocket.sendNext(); + } + } + else if (msg.message) { + worker.messagesReceived.push(msg.message); + + if (worker.messagesReceived.length === messages.length) { + done += 1; + worker.isDone = true; + console.error('[PARENT] %d received %d messages total.', + worker.pid, + worker.messagesReceived.length); + } + + if (done === listeners) { + console.error('[PARENT] All workers have received the ' + + 'required number of ' + + 'messages. Will now compare.'); + + Object.keys(workers).forEach(function(pid) { + var worker = workers[pid]; + + var count = 0; + + worker.messagesReceived.forEach(function(buf) { + for (var i = 0; i < messages.length; ++i) { + if (buf.toString() === messages[i].toString()) { + count++; + break; + } + } + }); + + console.error('[PARENT] %d received %d matching messges.', + worker.pid, + count); + + assert.equal(count, messages.length, + 'A worker received an invalid multicast message'); + }); + + clearTimeout(timer); + console.error('[PARENT] Success'); + killChildren(workers); + } + } + }); + })(x); + } + + var sendSocket = dgram.createSocket('udp4'); + + sendSocket.bind(common.PORT); + sendSocket.setBroadcast(true); + + sendSocket.on('close', function() { + console.error('[PARENT] sendSocket closed'); + }); + + sendSocket.sendNext = function() { + var buf = messages[i++]; + + if (!buf) { + try { sendSocket.close(); } catch (e) {} + return; + } + + sendSocket.send(buf, 0, buf.length, + common.PORT, LOCAL_BROADCAST_HOST, function(err) { + + if (err) throw err; + + console.error('[PARENT] sent %s to %s:%s', + util.inspect(buf.toString()), + LOCAL_BROADCAST_HOST, common.PORT); + + process.nextTick(sendSocket.sendNext); + }); + }; + + function killChildren(children) { + Object.keys(children).forEach(function(key) { + var child = children[key]; + child.kill(); + }); + } +} + +if (process.argv[2] === 'child') { + var receivedMessages = []; + var listenSocket = dgram.createSocket('udp4'); + + listenSocket.on('message', function(buf, rinfo) { + console.error('[CHILD] %s received %s from %j', + process.pid, + util.inspect(buf.toString()), + rinfo); + + receivedMessages.push(buf); + + process.send({ message: buf.toString() }); + + if (receivedMessages.length == messages.length) { + process.nextTick(function() { + listenSocket.close(); + }); + } + }); + + listenSocket.on('close', function() { + //HACK: Wait to exit the process to ensure that the parent + //process has had time to receive all messages via process.send() + //This may be indicitave of some other issue. + setTimeout(function() { + process.exit(); + }, 1000); + }); + + listenSocket.on('listening', function() { + process.send({ listening: true }); + }); + + listenSocket.bind(common.PORT); +} diff --git a/node-v0.8.14/test/simple/test-dgram-close.js b/node-v0.8.14/test/simple/test-dgram-close.js new file mode 100644 index 0000000..58d7aa7 --- /dev/null +++ b/node-v0.8.14/test/simple/test-dgram-close.js @@ -0,0 +1,35 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// Ensure that if a dgram socket is closed before the DNS lookup completes, it +// won't crash. + +var assert = require('assert'), + common = require('../common'), + dgram = require('dgram'); + +var buf = new Buffer(1024); +buf.fill(42); + +var socket = dgram.createSocket('udp4'); + +socket.send(buf, 0, buf.length, common.port, 'localhost'); +socket.close(); diff --git a/node-v0.8.14/test/simple/test-dgram-multicast-multi-process.js b/node-v0.8.14/test/simple/test-dgram-multicast-multi-process.js new file mode 100644 index 0000000..4f07820 --- /dev/null +++ b/node-v0.8.14/test/simple/test-dgram-multicast-multi-process.js @@ -0,0 +1,225 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'), + assert = require('assert'), + dgram = require('dgram'), + util = require('util'), + assert = require('assert'), + Buffer = require('buffer').Buffer, + fork = require('child_process').fork, + LOCAL_BROADCAST_HOST = '224.0.0.114', + TIMEOUT = 5000, + messages = [ + new Buffer('First message to send'), + new Buffer('Second message to send'), + new Buffer('Third message to send'), + new Buffer('Fourth message to send') + ]; + +if (process.argv[2] !== 'child') { + var workers = {}, + listeners = 3, + listening = 0, + dead = 0, + i = 0, + done = 0, + timer = null; + + //exit the test if it doesn't succeed within TIMEOUT + timer = setTimeout(function() { + console.error('[PARENT] Responses were not received within %d ms.', + TIMEOUT); + console.error('[PARENT] Fail'); + + killChildren(workers); + + process.exit(1); + }, TIMEOUT); + + //launch child processes + for (var x = 0; x < listeners; x++) { + (function() { + var worker = fork(process.argv[1], ['child']); + workers[worker.pid] = worker; + + worker.messagesReceived = []; + + //handle the death of workers + worker.on('exit', function(code, signal) { + // don't consider this the true death if the + // worker has finished successfully + + // or if the exit code is 0 + if (worker.isDone || code === 0) { + return; + } + + dead += 1; + console.error('[PARENT] Worker %d died. %d dead of %d', + worker.pid, + dead, + listeners); + + if (dead === listeners) { + console.error('[PARENT] All workers have died.'); + console.error('[PARENT] Fail'); + + killChildren(workers); + + process.exit(1); + } + }); + + worker.on('message', function(msg) { + if (msg.listening) { + listening += 1; + + if (listening === listeners) { + //all child process are listening, so start sending + sendSocket.sendNext(); + } + } + else if (msg.message) { + worker.messagesReceived.push(msg.message); + + if (worker.messagesReceived.length === messages.length) { + done += 1; + worker.isDone = true; + console.error('[PARENT] %d received %d messages total.', + worker.pid, + worker.messagesReceived.length); + } + + if (done === listeners) { + console.error('[PARENT] All workers have received the ' + + 'required number of messages. Will now compare.'); + + Object.keys(workers).forEach(function(pid) { + var worker = workers[pid]; + + var count = 0; + + worker.messagesReceived.forEach(function(buf) { + for (var i = 0; i < messages.length; ++i) { + if (buf.toString() === messages[i].toString()) { + count++; + break; + } + } + }); + + console.error('[PARENT] %d received %d matching messages.', + worker.pid, count); + + assert.equal(count, messages.length, + 'A worker received an invalid multicast message'); + }); + + clearTimeout(timer); + console.error('[PARENT] Success'); + killChildren(workers); + } + } + }); + })(x); + } + + var sendSocket = dgram.createSocket('udp4'); + // FIXME a libuv limitation makes it necessary to bind() + // before calling any of the set*() functions - the bind() + // call is what creates the actual socket... + sendSocket.bind(); + + sendSocket.setTTL(1); + sendSocket.setBroadcast(true); + sendSocket.setMulticastTTL(1); + sendSocket.setMulticastLoopback(true); + + sendSocket.on('close', function() { + console.error('[PARENT] sendSocket closed'); + }); + + sendSocket.sendNext = function() { + var buf = messages[i++]; + + if (!buf) { + try { sendSocket.close(); } catch (e) {} + return; + } + + sendSocket.send(buf, 0, buf.length, + common.PORT, LOCAL_BROADCAST_HOST, function(err) { + if (err) throw err; + console.error('[PARENT] sent %s to %s:%s', + util.inspect(buf.toString()), + LOCAL_BROADCAST_HOST, common.PORT); + process.nextTick(sendSocket.sendNext); + }); + }; + + function killChildren(children) { + Object.keys(children).forEach(function(key) { + var child = children[key]; + child.kill(); + }); + } +} + +if (process.argv[2] === 'child') { + var receivedMessages = []; + var listenSocket = dgram.createSocket('udp4'); + + listenSocket.on('message', function(buf, rinfo) { + console.error('[CHILD] %s received %s from %j', process.pid, + util.inspect(buf.toString()), rinfo); + + receivedMessages.push(buf); + + process.send({ message: buf.toString() }); + + if (receivedMessages.length == messages.length) { + listenSocket.dropMembership(LOCAL_BROADCAST_HOST); + + process.nextTick(function() { // TODO should be changed to below. + // listenSocket.dropMembership(LOCAL_BROADCAST_HOST, function() { + listenSocket.close(); + }); + } + }); + + listenSocket.on('close', function() { + //HACK: Wait to exit the process to ensure that the parent + //process has had time to receive all messages via process.send() + //This may be indicitave of some other issue. + setTimeout(function() { + process.exit(); + }, 1000); + }); + + listenSocket.on('listening', function() { + process.send({ listening: true }); + }); + + listenSocket.bind(common.PORT); + + listenSocket.addMembership(LOCAL_BROADCAST_HOST); +} diff --git a/node-v0.8.14/test/simple/test-dgram-multicast-setTTL.js b/node-v0.8.14/test/simple/test-dgram-multicast-setTTL.js new file mode 100644 index 0000000..8d1c0a0 --- /dev/null +++ b/node-v0.8.14/test/simple/test-dgram-multicast-setTTL.js @@ -0,0 +1,41 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'), + assert = require('assert'), + dgram = require('dgram'), + thrown = false, + socket = dgram.createSocket('udp4'); + +socket.bind(common.PORT); +socket.setMulticastTTL(16); + +//Try to set an invalid TTL (valid ttl is > 0 and < 256) +try { + socket.setMulticastTTL(1000); +} catch (e) { + thrown = true; +} + +assert(thrown, 'Setting an invalid multicast TTL should throw some error'); + +//close the socket +socket.close(); diff --git a/node-v0.8.14/test/simple/test-dgram-oob-buffer.js b/node-v0.8.14/test/simple/test-dgram-oob-buffer.js new file mode 100644 index 0000000..a3967fb --- /dev/null +++ b/node-v0.8.14/test/simple/test-dgram-oob-buffer.js @@ -0,0 +1,52 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// Some operating systems report errors when an UDP message is sent to an +// unreachable host. This error can be reported by sendto() and even by +// recvfrom(). Node should not propagate this error to the user. + +var common = require('../common'); +var assert = require('assert'); +var dgram = require('dgram'); + +var socket = dgram.createSocket('udp4'); +var buf = Buffer([1,2,3,4]); + +function ok() {} +socket.send(buf, 0, 0, common.PORT, '127.0.0.1', ok); // useful? no +socket.send(buf, 0, 4, common.PORT, '127.0.0.1', ok); +socket.send(buf, 1, 3, common.PORT, '127.0.0.1', ok); +socket.send(buf, 3, 1, common.PORT, '127.0.0.1', ok); + +assert.throws(function() { + socket.send(buf, 0, 5, common.PORT, '127.0.0.1', assert.fail); +}); +assert.throws(function() { + socket.send(buf, 2, 3, common.PORT, '127.0.0.1', assert.fail); +}); +assert.throws(function() { + socket.send(buf, 4, 0, common.PORT, '127.0.0.1', assert.fail); +}); +assert.throws(function() { + socket.send(buf, 4, 4, common.PORT, '127.0.0.1', assert.fail); +}); + +socket.close(); // FIXME should not be necessary diff --git a/node-v0.8.14/test/simple/test-dgram-pingpong.js b/node-v0.8.14/test/simple/test-dgram-pingpong.js new file mode 100644 index 0000000..18b39b5 --- /dev/null +++ b/node-v0.8.14/test/simple/test-dgram-pingpong.js @@ -0,0 +1,113 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + + + +var common = require('../common'); +var assert = require('assert'); +var Buffer = require('buffer').Buffer; +var dgram = require('dgram'); + +var tests_run = 0; + +function pingPongTest(port, host) { + var callbacks = 0; + var N = 500; + var count = 0; + var sent_final_ping = false; + + var server = dgram.createSocket('udp4', function(msg, rinfo) { + console.log('server got: ' + msg + + ' from ' + rinfo.address + ':' + rinfo.port); + + if (/PING/.exec(msg)) { + var buf = new Buffer(4); + buf.write('PONG'); + server.send(buf, 0, buf.length, + rinfo.port, rinfo.address, + function(err, sent) { + callbacks++; + }); + } + }); + + server.on('error', function(e) { + throw e; + }); + + server.on('listening', function() { + console.log('server listening on ' + port + ' ' + host); + + var buf = new Buffer('PING'), + client = dgram.createSocket('udp4'); + + client.on('message', function(msg, rinfo) { + console.log('client got: ' + msg + + ' from ' + rinfo.address + ':' + rinfo.port); + assert.equal('PONG', msg.toString('ascii')); + + count += 1; + + if (count < N) { + client.send(buf, 0, buf.length, port, 'localhost'); + } else { + sent_final_ping = true; + client.send(buf, 0, buf.length, port, 'localhost', function() { + client.close(); + }); + } + }); + + client.on('close', function() { + console.log('client has closed, closing server'); + assert.equal(N, count); + tests_run += 1; + server.close(); + assert.equal(N - 1, callbacks); + }); + + client.on('error', function(e) { + throw e; + }); + + console.log('Client sending to ' + port + ', localhost ' + buf); + client.send(buf, 0, buf.length, port, 'localhost', function(err, bytes) { + if (err) { + throw err; + } + console.log('Client sent ' + bytes + ' bytes'); + }); + count += 1; + }); + server.bind(port, host); +} + +// All are run at once, so run on different ports +pingPongTest(20989, 'localhost'); +pingPongTest(20990, 'localhost'); +pingPongTest(20988); +//pingPongTest('/tmp/pingpong.sock'); + +process.on('exit', function() { + assert.equal(3, tests_run); + console.log('done'); +}); diff --git a/node-v0.8.14/test/simple/test-dgram-ref.js b/node-v0.8.14/test/simple/test-dgram-ref.js new file mode 100644 index 0000000..ebbbac2 --- /dev/null +++ b/node-v0.8.14/test/simple/test-dgram-ref.js @@ -0,0 +1,27 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var dgram = require('dgram'); + +// should not hang, see #1282 +dgram.createSocket('udp4'); +dgram.createSocket('udp6'); diff --git a/node-v0.8.14/test/simple/test-dgram-send-error.js b/node-v0.8.14/test/simple/test-dgram-send-error.js new file mode 100644 index 0000000..346f36d --- /dev/null +++ b/node-v0.8.14/test/simple/test-dgram-send-error.js @@ -0,0 +1,81 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// Some operating systems report errors when an UDP message is sent to an +// unreachable host. This error can be reported by sendto() and even by +// recvfrom(). Node should not propagate this error to the user. + +// We test this by sending a bunch of packets to random IPs. In the meantime +// we also send packets to ourselves to verify that after receiving an error +// we can still receive packets successfully. + +var ITERATIONS = 1000; + +var assert = require('assert'), + common = require('../common'), + dgram = require('dgram'); + +var buf = new Buffer(1024); +buf.fill(42); + +var packetsReceived = 0, + packetsSent = 0; + +var socket = dgram.createSocket('udp4'); + +socket.on('message', onMessage); +socket.on('listening', doSend); +socket.bind(common.PORT); + +function onMessage(message, info) { + packetsReceived++; + if (packetsReceived < ITERATIONS) { + doSend(); + } else { + socket.close(); + } +} + +function afterSend(err) { + if (err) throw err; + packetsSent++; +} + +function doSend() { + // Generate a random IP. + var parts = []; + for (var i = 0; i < 4; i++) { + // Generate a random number in the range 1..254. + parts.push(Math.floor(Math.random() * 254) + 1); + } + var ip = parts.join('.'); + + socket.send(buf, 0, buf.length, 1, ip, afterSend); + socket.send(buf, 0, buf.length, common.PORT, '127.0.0.1', afterSend); +} + +process.on('exit', function() { + console.log(packetsSent + ' UDP packets sent, ' + + packetsReceived + ' received'); + + assert.strictEqual(packetsSent, ITERATIONS * 2); + assert.strictEqual(packetsReceived, ITERATIONS); +}); diff --git a/node-v0.8.14/test/simple/test-dgram-udp4.js b/node-v0.8.14/test/simple/test-dgram-udp4.js new file mode 100644 index 0000000..9a82de5 --- /dev/null +++ b/node-v0.8.14/test/simple/test-dgram-udp4.js @@ -0,0 +1,81 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + + + +var common = require('../common'); +var assert = require('assert'); + +var Buffer = require('buffer').Buffer, + fs = require('fs'), + dgram = require('dgram'), server, client, + server_port = 20989, + message_to_send = new Buffer('A message to send'), + timer; + +server = dgram.createSocket('udp4'); +server.on('message', function(msg, rinfo) { + console.log('server got: ' + msg + + ' from ' + rinfo.address + ':' + rinfo.port); + assert.strictEqual(rinfo.address, '127.0.0.1'); + assert.strictEqual(msg.toString(), message_to_send.toString()); + server.send(msg, 0, msg.length, rinfo.port, rinfo.address); +}); +server.on('listening', function() { + var address = server.address(); + console.log('server is listening on ' + address.address + ':' + address.port); + client = dgram.createSocket('udp4'); + client.on('message', function(msg, rinfo) { + console.log('client got: ' + msg + + ' from ' + rinfo.address + ':' + address.port); + assert.strictEqual(rinfo.address, '127.0.0.1'); + assert.strictEqual(rinfo.port, server_port); + assert.strictEqual(msg.toString(), message_to_send.toString()); + client.close(); + server.close(); + }); + client.send(message_to_send, 0, message_to_send.length, + server_port, 'localhost', function(err, bytes) { + if (err) { + console.log('Caught error in client send.'); + throw err; + } + console.log('client wrote ' + bytes + ' bytes.'); + assert.strictEqual(bytes, message_to_send.length); + }); + client.on('close', + function() { + if (server.fd === null) { + clearTimeout(timer); + } + }); +}); +server.on('close', function() { + if (client.fd === null) { + clearTimeout(timer); + } +}); +server.bind(server_port); + +timer = setTimeout(function() { + throw new Error('Timeout'); +}, 200); diff --git a/node-v0.8.14/test/simple/test-domain-crypto.js b/node-v0.8.14/test/simple/test-domain-crypto.js new file mode 100644 index 0000000..66e9628 --- /dev/null +++ b/node-v0.8.14/test/simple/test-domain-crypto.js @@ -0,0 +1,37 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +try { + var crypto = require('crypto'); +} catch (e) { + console.log('Not compiled with OPENSSL support.'); + process.exit(); +} + +// the missing var keyword is intentional +domain = require('domain'); + +// should not throw a 'TypeError: undefined is not a function' exception +crypto.randomBytes(8); +crypto.randomBytes(8, function() {}); +crypto.pseudoRandomBytes(8); +crypto.pseudoRandomBytes(8, function() {}); +crypto.pbkdf2('password', 'salt', 8, 8, function() {}); diff --git a/node-v0.8.14/test/simple/test-domain-exit-dispose.js b/node-v0.8.14/test/simple/test-domain-exit-dispose.js new file mode 100644 index 0000000..fd99091 --- /dev/null +++ b/node-v0.8.14/test/simple/test-domain-exit-dispose.js @@ -0,0 +1,67 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common.js'); +var assert = require('assert'); +var domain = require('domain'); +var disposalFailed = false; + +// no matter what happens, we should increment a 10 times. +var a = 0; +log(); +function log(){ + console.log(a++, process.domain); + if (a < 10) setTimeout(log, 20); +} + +// in 50ms we'll throw an error. +setTimeout(err, 50); +function err(){ + var d = domain.create(); + d.on('error', handle); + d.run(err2); + + function err2() { + // this timeout should never be called, since the domain gets + // disposed when the error happens. + setTimeout(function() { + console.error('This should not happen.'); + disposalFailed = true; + process.exit(1); + }); + + // this function doesn't exist, and throws an error as a result. + err3(); + } + + function handle(e) { + // this should clean up everything properly. + d.dispose(); + console.error(e); + console.error('in handler', process.domain, process.domain === d); + } +} + +process.on('exit', function() { + assert.equal(a, 10); + assert.equal(disposalFailed, false); + console.log('ok'); +}); diff --git a/node-v0.8.14/test/simple/test-domain-http-server.js b/node-v0.8.14/test/simple/test-domain-http-server.js new file mode 100644 index 0000000..f9962d3 --- /dev/null +++ b/node-v0.8.14/test/simple/test-domain-http-server.js @@ -0,0 +1,121 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var domain = require('domain'); +var http = require('http'); +var assert = require('assert'); +var common = require('../common.js'); + +var objects = { foo: 'bar', baz: {}, num: 42, arr: [1,2,3] }; +objects.baz.asdf = objects; + +var serverCaught = 0; +var clientCaught = 0; +var disposeEmit = 0; + +var server = http.createServer(function(req, res) { + var dom = domain.create(); + dom.add(req); + dom.add(res); + + dom.on('error', function(er) { + serverCaught++; + console.log('server error', er); + // try to send a 500. If that fails, oh well. + res.writeHead(500, {'content-type':'text/plain'}); + res.end(er.stack || er.message || 'Unknown error'); + }); + + var data; + dom.run(function() { + // Now, an action that has the potential to fail! + // if you request 'baz', then it'll throw a JSON circular ref error. + data = JSON.stringify(objects[req.url.replace(/[^a-z]/g, '')]); + + // this line will throw if you pick an unknown key + assert(data !== undefined, 'Data should not be undefined'); + + res.writeHead(200); + res.end(data); + }); +}); + +server.listen(common.PORT, next); + +function next() { + console.log('listening on localhost:%d', common.PORT); + + // now hit it a few times + var dom = domain.create(); + var requests = 0; + var responses = 0; + + makeReq('/'); + makeReq('/foo'); + makeReq('/arr'); + makeReq('/baz'); + makeReq('/num'); + + function makeReq(p) { + requests++; + + var dom = domain.create(); + dom.on('error', function(er) { + clientCaught++; + console.log('client error', er); + // kill everything. + dom.dispose(); + }); + + dom.on('dispose', function() { + disposeEmit += 1; + }); + + var req = http.get({ host: 'localhost', port: common.PORT, path: p }); + dom.add(req); + req.on('response', function(res) { + responses++; + console.error('requests=%d responses=%d', requests, responses); + if (responses === requests) { + console.error('done, closing server'); + // no more coming. + server.close(); + } + + dom.add(res); + var d = ''; + res.on('data', function(c) { + d += c; + }); + res.on('end', function() { + d = JSON.parse(d); + console.log('json!', d); + }); + }); + } +} + +process.on('exit', function() { + assert.equal(serverCaught, 2); + assert.equal(clientCaught, 2); + assert.equal(disposeEmit, 2); + console.log('ok'); +}); diff --git a/node-v0.8.14/test/simple/test-domain-implicit-fs.js b/node-v0.8.14/test/simple/test-domain-implicit-fs.js new file mode 100644 index 0000000..665a821 --- /dev/null +++ b/node-v0.8.14/test/simple/test-domain-implicit-fs.js @@ -0,0 +1,72 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + +// Simple tests of most basic domain functionality. + +var common = require('../common'); +var assert = require('assert'); +var domain = require('domain'); +var events = require('events'); +var caught = 0; +var expectCaught = 1; + +var d = new domain.Domain(); +var e = new events.EventEmitter(); + +d.on('error', function(er) { + console.error('caught', er); + + assert.strictEqual(er.domain, d); + assert.strictEqual(er.domain_thrown, true); + assert.ok(!er.domain_emitter); + assert.strictEqual(er.code, 'ENOENT'); + assert.ok(/\bthis file does not exist\b/i.test(er.path)); + assert.strictEqual(typeof er.errno, 'number'); + + caught++; +}); + +process.on('exit', function() { + console.error('exit'); + assert.equal(caught, expectCaught); + console.log('ok'); +}); + + +// implicit handling of thrown errors while in a domain, via the +// single entry points of ReqWrap and MakeCallback. Even if +// we try very hard to escape, there should be no way to, even if +// we go many levels deep through timeouts and multiple IO calls. +// Everything that happens between the domain.enter() and domain.exit() +// calls will be bound to the domain, even if multiple levels of +// handles are created. +d.run(function() { + setTimeout(function() { + var fs = require('fs'); + fs.readdir(__dirname, function() { + fs.open('this file does not exist', 'r', function(er) { + if (er) throw er; + throw new Error('should not get here!'); + }); + }); + }, 100); +}); diff --git a/node-v0.8.14/test/simple/test-domain-multi.js b/node-v0.8.14/test/simple/test-domain-multi.js new file mode 100644 index 0000000..68e4b11 --- /dev/null +++ b/node-v0.8.14/test/simple/test-domain-multi.js @@ -0,0 +1,99 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + +// Tests of multiple domains happening at once. + +var common = require('../common'); +var assert = require('assert'); +var domain = require('domain'); +var events = require('events'); + +var caughtA = false; +var caughtB = false; +var caughtC = false; + + +var a = domain.create(); +a.enter(); // this will be our "root" domain +a.on('error', function(er) { + caughtA = true; + console.log('This should not happen'); + throw er; +}); + + +var http = require('http'); +var server = http.createServer(function (req, res) { + // child domain of a. + var b = domain.create(); + a.add(b); + + // treat these EE objects as if they are a part of the b domain + // so, an 'error' event on them propagates to the domain, rather + // than being thrown. + b.add(req); + b.add(res); + + b.on('error', function (er) { + caughtB = true; + console.error('Error encountered', er) + if (res) { + res.writeHead(500); + res.end('An error occurred'); + } + // res.writeHead(500), res.destroy, etc. + server.close(); + }); + + // XXX this bind should not be necessary. + // the write cb behavior in http/net should use an + // event so that it picks up the domain handling. + res.write('HELLO\n', b.bind(function() { + throw new Error('this kills domain B, not A'); + })); + +}).listen(common.PORT); + +var c = domain.create(); +var req = http.get({ host: 'localhost', port: common.PORT }) + +// add the request to the C domain +c.add(req); + +req.on('response', function(res) { + console.error('got response'); + // add the response object to the C domain + c.add(res); + res.pipe(process.stdout); +}); + +c.on('error', function(er) { + caughtC = true; + console.error('Error on c', er.message); +}); + +process.on('exit', function() { + assert.equal(caughtA, false); + assert.equal(caughtB, true) + assert.equal(caughtC, true) + console.log('ok - Errors went where they were supposed to go'); +}); diff --git a/node-v0.8.14/test/simple/test-domain-stack.js b/node-v0.8.14/test/simple/test-domain-stack.js new file mode 100644 index 0000000..4d3eeb8 --- /dev/null +++ b/node-v0.8.14/test/simple/test-domain-stack.js @@ -0,0 +1,46 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + +// Make sure that the domain stack doesn't get out of hand. + +var common = require('../common'); +var assert = require('assert'); +var domain = require('domain'); +var events = require('events'); + +var a = domain.create(); +a.name = 'a'; + +a.on('error', function() { + if (domain._stack.length > 5) { + console.error('leaking!', domain._stack); + process.exit(1); + } +}); + +var foo = a.bind(function() { + throw new Error('error from foo'); +}); + +for (var i = 0; i < 1000; i++) { + process.nextTick(foo); +} diff --git a/node-v0.8.14/test/simple/test-domain.js b/node-v0.8.14/test/simple/test-domain.js new file mode 100644 index 0000000..a478c1e --- /dev/null +++ b/node-v0.8.14/test/simple/test-domain.js @@ -0,0 +1,233 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + +// Simple tests of most basic domain functionality. + +var common = require('../common'); +var assert = require('assert'); +var domain = require('domain'); +var events = require('events'); +var caught = 0; +var expectCaught = 8; + +var d = new domain.Domain(); +var e = new events.EventEmitter(); + +d.on('error', function(er) { + console.error('caught', er); + + var er_message = er.message; + var er_path = er.path + + // On windows, error messages can contain full path names. If this is the + // case, remove the directory part. + if (typeof er_path === 'string') { + var slash = er_path.lastIndexOf('\\'); + if (slash !== -1) { + var dir = er_path.slice(0, slash + 1); + er_path = er_path.replace(dir, ''); + er_message = er_message.replace(dir, ''); + } + } + + switch (er_message) { + case 'emitted': + assert.equal(er.domain, d); + assert.equal(er.domain_emitter, e); + assert.equal(er.domain_thrown, false); + break; + + case 'bound': + assert.ok(!er.domain_emitter); + assert.equal(er.domain, d); + assert.equal(er.domain_bound, fn); + assert.equal(er.domain_thrown, false); + break; + + case 'thrown': + assert.ok(!er.domain_emitter); + assert.equal(er.domain, d); + assert.equal(er.domain_thrown, true); + break; + + case "ENOENT, open 'this file does not exist'": + assert.equal(er.domain, d); + assert.equal(er.domain_thrown, false); + assert.equal(typeof er.domain_bound, 'function'); + assert.ok(!er.domain_emitter); + assert.equal(er.code, 'ENOENT'); + assert.equal(er_path, 'this file does not exist'); + assert.equal(typeof er.errno, 'number'); + break; + + case "ENOENT, open 'stream for nonexistent file'": + assert.equal(typeof er.errno, 'number'); + assert.equal(er.code, 'ENOENT'); + assert.equal(er_path, 'stream for nonexistent file'); + assert.equal(er.domain, d); + assert.equal(er.domain_emitter, fst); + assert.ok(!er.domain_bound); + assert.equal(er.domain_thrown, false); + break; + + case 'implicit': + assert.equal(er.domain_emitter, implicit); + assert.equal(er.domain, d); + assert.equal(er.domain_thrown, false); + assert.ok(!er.domain_bound); + break; + + case 'implicit timer': + assert.equal(er.domain, d); + assert.equal(er.domain_thrown, true); + assert.ok(!er.domain_emitter); + assert.ok(!er.domain_bound); + break; + + case 'Cannot call method \'isDirectory\' of undefined': + assert.equal(er.domain, d); + assert.ok(!er.domain_emitter); + assert.ok(!er.domain_bound); + break; + + default: + console.error('unexpected error, throwing %j', er.message); + throw er; + } + + caught++; +}); + +process.on('exit', function() { + console.error('exit'); + assert.equal(caught, expectCaught); + console.log('ok'); +}); + + + +// Event emitters added to the domain have their errors routed. +d.add(e); +e.emit('error', new Error('emitted')); + + + +// get rid of the `if (er) return cb(er)` malarky, by intercepting +// the cb functions to the domain, and using the intercepted function +// as a callback instead. +function fn(er) { + throw new Error('This function should never be called!'); + process.exit(1); +} + +var bound = d.intercept(fn); +bound(new Error('bound')); + +// intercepted should never pass first argument to callback +function fn2(data) { + assert.equal(data, 'data', 'should not be null err argument') +} + +var bound = d.intercept(fn2); +bound(null, 'data'); + +// intercepted should never pass first argument to callback +// even if arguments length is more than 2. +function fn3(data, data2) { + assert.equal(data, 'data', 'should not be null err argument'); + assert.equal(data2, 'data2', 'should not be data argument'); +} + +bound = d.intercept(fn3); +bound(null, 'data', 'data2'); + +// throwing in a bound fn is also caught, +// even if it's asynchronous, by hitting the +// global uncaughtException handler. This doesn't +// require interception, since throws are always +// caught by the domain. +function thrower() { + throw new Error('thrown'); +} +setTimeout(d.bind(thrower), 100); + + + +// Pass an intercepted function to an fs operation that fails. +var fs = require('fs'); +fs.open('this file does not exist', 'r', d.intercept(function(er) { + console.error('should not get here!', er); + throw new Error('should not get here!'); +}, true)); + + + +// catch thrown errors no matter how many times we enter the event loop +// this only uses implicit binding, except for the first function +// passed to d.run(). The rest are implicitly bound by virtue of being +// set up while in the scope of the d domain. +d.run(function() { + process.nextTick(function() { + var i = setInterval(function () { + clearInterval(i); + setTimeout(function() { + fs.stat('this file does not exist', function(er, stat) { + // uh oh! stat isn't set! + // pretty common error. + console.log(stat.isDirectory()); + }); + }); + }); + }); +}); + + + +// implicit addition by being created within a domain-bound context. +var implicit; + +d.run(function() { + implicit = new events.EventEmitter; +}); + +setTimeout(function() { + // escape from the domain, but implicit is still bound to it. + implicit.emit('error', new Error('implicit')); +}, 10); + + + +// implicit addition of a timer created within a domain-bound context. +d.run(function() { + setTimeout(function() { + throw new Error('implicit timer'); + }); +}); + +var result = d.run(function () { + return 'return value'; +}); +assert.equal(result, 'return value'); + + +var fst = fs.createReadStream('stream for nonexistent file') +d.add(fst) diff --git a/node-v0.8.14/test/simple/test-eio-limit.js b/node-v0.8.14/test/simple/test-eio-limit.js new file mode 100644 index 0000000..5902db4 --- /dev/null +++ b/node-v0.8.14/test/simple/test-eio-limit.js @@ -0,0 +1,50 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'), + zlib = require('zlib'), + started = 0, + done = 0; + +function repeat(fn) { + if (started != 0) { + assert.ok(started - done < 200); + } + + process.nextTick(function() { + fn(); + repeat(fn); + }); +} + +repeat(function() { + if (started > 1000) return process.exit(0); + + for (var i = 0; i < 30; i++) { + started++; + var deflate = zlib.createDeflate(); + deflate.write('123'); + deflate.flush(function() { + done++; + }); + } +}); diff --git a/node-v0.8.14/test/simple/test-eio-race.js b/node-v0.8.14/test/simple/test-eio-race.js new file mode 100644 index 0000000..558d09a --- /dev/null +++ b/node-v0.8.14/test/simple/test-eio-race.js @@ -0,0 +1,85 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + +var common = require('../common'); +var assert = require('assert'); + +var count = 100; +var fs = require('fs'); + +// person.jpg is 57kb. We just need some file that is sufficently large. +var filename = require('path').join(common.fixturesDir, 'person.jpg'); + +function tryToKillEventLoop() { + console.log('trying to kill event loop ...'); + + fs.stat(__filename, function(err) { + if (err) { + throw new Exception('first fs.stat failed'); + } else { + fs.stat(__filename, function(err) { + if (err) { + throw new Exception('second fs.stat failed'); + } else { + console.log('could not kill event loop, retrying...'); + + setTimeout(function() { + if (--count) { + tryToKillEventLoop(); + } else { + console.log('done trying to kill event loop'); + process.exit(0); + } + }, 1); + } + }); + } + }); +} + +// Generate a lot of thread pool events +var pos = 0; +fs.open(filename, 'r', 0666, function(err, fd) { + if (err) throw err; + + function readChunk() { + fs.read(fd, 1024, 0, 'binary', function(err, chunk, bytesRead) { + if (err) throw err; + if (chunk) { + pos += bytesRead; + //console.log(pos); + readChunk(); + } else { + fs.closeSync(fd); + throw new Exception("Shouldn't get EOF"); + } + }); + } + readChunk(); +}); + +tryToKillEventLoop(); + +process.on('exit', function() { + console.log('done with test'); + assert.ok(pos > 10000); +}); diff --git a/node-v0.8.14/test/simple/test-eio-race2.js b/node-v0.8.14/test/simple/test-eio-race2.js new file mode 100644 index 0000000..d6439f1 --- /dev/null +++ b/node-v0.8.14/test/simple/test-eio-race2.js @@ -0,0 +1,45 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var path = require('path'); +var testTxt = path.join(common.fixturesDir, 'x.txt'); +var fs = require('fs'); + +setTimeout(function() { + // put this in a timeout, just so it doesn't get bunched up with the + // require() calls.. + var N = 30; + for (var i = 0; i < N; i++) { + console.log('start ' + i); + fs.readFile(testTxt, function(err, data) { + if (err) { + console.log('error! ' + e); + process.exit(1); + } else { + console.log('finish'); + } + }); + } +}, 100); + + diff --git a/node-v0.8.14/test/simple/test-eio-race4.js b/node-v0.8.14/test/simple/test-eio-race4.js new file mode 100644 index 0000000..8eaeda2 --- /dev/null +++ b/node-v0.8.14/test/simple/test-eio-race4.js @@ -0,0 +1,42 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var fs = require('fs'); +var N = 100; +var j = 0; + +for (var i = 0; i < N; i++) { + // these files don't exist + fs.stat('does-not-exist-' + i, function(err) { + if (err) { + j++; // only makes it to about 17 + console.log('finish ' + j); + } else { + throw new Error('this shouldn\'t be called'); + } + }); +} + +process.on('exit', function() { + assert.equal(N, j); +}); diff --git a/node-v0.8.14/test/simple/test-error-reporting.js b/node-v0.8.14/test/simple/test-error-reporting.js new file mode 100644 index 0000000..22c6f97 --- /dev/null +++ b/node-v0.8.14/test/simple/test-error-reporting.js @@ -0,0 +1,76 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + + + +var common = require('../common'); +var assert = require('assert'); +var exec = require('child_process').exec; +var path = require('path'); + +var exits = 0; + +function errExec(script, callback) { + var cmd = '"' + process.argv[0] + '" "' + + path.join(common.fixturesDir, script) + '"'; + return exec(cmd, function(err, stdout, stderr) { + // There was some error + assert.ok(err); + + // More than one line of error output. + assert.ok(stderr.split('\n').length > 2); + + // Assert the script is mentioned in error output. + assert.ok(stderr.indexOf(script) >= 0); + + // Proxy the args for more tests. + callback(err, stdout, stderr); + + // Count the tests + exits++; + + console.log('.'); + }); +} + + +// Simple throw error +errExec('throws_error.js', function(err, stdout, stderr) { + assert.ok(/blah/.test(stderr)); +}); + + +// Trying to JSON.parse(undefined) +errExec('throws_error2.js', function(err, stdout, stderr) { + assert.ok(/SyntaxError/.test(stderr)); +}); + + +// Trying to JSON.parse(undefined) in nextTick +errExec('throws_error3.js', function(err, stdout, stderr) { + assert.ok(/SyntaxError/.test(stderr)); +}); + + +process.on('exit', function() { + assert.equal(3, exits); +}); diff --git a/node-v0.8.14/test/simple/test-eval-require.js b/node-v0.8.14/test/simple/test-eval-require.js new file mode 100644 index 0000000..dfef416 --- /dev/null +++ b/node-v0.8.14/test/simple/test-eval-require.js @@ -0,0 +1,38 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + + + +var common = require('../common'); +var assert = require('assert'); +var spawn = require('child_process').spawn; +var path = require('path'); +var fs = require('fs'); + +var options = { + cwd: common.fixturesDir +}; +var child = spawn(process.execPath, ['-e', 'require("foo")'], options); +child.on('exit', function(code) { + assert.equal(code, 0); +}); + diff --git a/node-v0.8.14/test/simple/test-eval.js b/node-v0.8.14/test/simple/test-eval.js new file mode 100644 index 0000000..9c656a8 --- /dev/null +++ b/node-v0.8.14/test/simple/test-eval.js @@ -0,0 +1,50 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + + + +require('../common'); +var util = require('util'); +var assert = require('assert'); +var exec = require('child_process').exec; + +var success_count = 0; +var error_count = 0; + +var cmd = [process.execPath, '-e', '"console.error(process.argv)"', + 'foo', 'bar'].join(' '); +var expected = util.format([process.execPath, 'foo', 'bar']) + '\n'; +var child = exec(cmd, function(err, stdout, stderr) { + if (err) { + console.log(err.toString()); + ++error_count; + return; + } + assert.equal(stderr, expected); + ++success_count; +}); + +process.on('exit', function() { + assert.equal(1, success_count); + assert.equal(0, error_count); +}); + diff --git a/node-v0.8.14/test/simple/test-event-emitter-add-listeners.js b/node-v0.8.14/test/simple/test-event-emitter-add-listeners.js new file mode 100644 index 0000000..0806e04 --- /dev/null +++ b/node-v0.8.14/test/simple/test-event-emitter-add-listeners.js @@ -0,0 +1,68 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var events = require('events'); + +var e = new events.EventEmitter(); + +var events_new_listener_emited = []; +var listeners_new_listener_emited = []; +var times_hello_emited = 0; + +// sanity check +assert.equal(e.addListener, e.on); + +e.on('newListener', function(event, listener) { + console.log('newListener: ' + event); + events_new_listener_emited.push(event); + listeners_new_listener_emited.push(listener); +}); + +function hello(a, b) { + console.log('hello'); + times_hello_emited += 1; + assert.equal('a', a); + assert.equal('b', b); +} +e.on('hello', hello); + +var foo = function() {}; +e.once('foo', foo); + +console.log('start'); + +e.emit('hello', 'a', 'b'); + + +// just make sure that this doesn't throw: +var f = new events.EventEmitter(); +f.setMaxListeners(0); + + +process.on('exit', function() { + assert.deepEqual(['hello', 'foo'], events_new_listener_emited); + assert.deepEqual([hello, foo], listeners_new_listener_emited); + assert.equal(1, times_hello_emited); +}); + + diff --git a/node-v0.8.14/test/simple/test-event-emitter-check-listener-leaks.js b/node-v0.8.14/test/simple/test-event-emitter-check-listener-leaks.js new file mode 100644 index 0000000..7d9c203 --- /dev/null +++ b/node-v0.8.14/test/simple/test-event-emitter-check-listener-leaks.js @@ -0,0 +1,58 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var events = require('events'); + +var e = new events.EventEmitter(); + +// default +for (var i = 0; i < 10; i++) { + e.on('default', function() {}); +} +assert.ok(!e._events['default'].hasOwnProperty('warned')); +e.on('default', function() {}); +assert.ok(e._events['default'].warned); + +// specific +e.setMaxListeners(5); +for (var i = 0; i < 5; i++) { + e.on('specific', function() {}); +} +assert.ok(!e._events['specific'].hasOwnProperty('warned')); +e.on('specific', function() {}); +assert.ok(e._events['specific'].warned); + +// only one +e.setMaxListeners(1); +e.on('only one', function() {}); +assert.ok(!e._events['only one'].hasOwnProperty('warned')); +e.on('only one', function() {}); +assert.ok(e._events['only one'].hasOwnProperty('warned')); + +// unlimited +e.setMaxListeners(0); +for (var i = 0; i < 1000; i++) { + e.on('unlimited', function() {}); +} +assert.ok(!e._events['unlimited'].hasOwnProperty('warned')); + diff --git a/node-v0.8.14/test/simple/test-event-emitter-max-listeners.js b/node-v0.8.14/test/simple/test-event-emitter-max-listeners.js new file mode 100644 index 0000000..3dea94b --- /dev/null +++ b/node-v0.8.14/test/simple/test-event-emitter-max-listeners.js @@ -0,0 +1,41 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var events = require('events'); + +var gotEvent = false; + +process.on('exit', function() { + assert(gotEvent); +}); + +var e = new events.EventEmitter(); + +e.on('maxListeners', function() { + gotEvent = true; +}); + +// Should not corrupt the 'maxListeners' queue. +e.setMaxListeners(42); + +e.emit('maxListeners'); diff --git a/node-v0.8.14/test/simple/test-event-emitter-modify-in-emit.js b/node-v0.8.14/test/simple/test-event-emitter-modify-in-emit.js new file mode 100644 index 0000000..738af09 --- /dev/null +++ b/node-v0.8.14/test/simple/test-event-emitter-modify-in-emit.js @@ -0,0 +1,77 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var events = require('events'); + +var callbacks_called = []; + +var e = new events.EventEmitter(); + +function callback1() { + callbacks_called.push('callback1'); + e.on('foo', callback2); + e.on('foo', callback3); + e.removeListener('foo', callback1); +} + +function callback2() { + callbacks_called.push('callback2'); + e.removeListener('foo', callback2); +} + +function callback3() { + callbacks_called.push('callback3'); + e.removeListener('foo', callback3); +} + +e.on('foo', callback1); +assert.equal(1, e.listeners('foo').length); + +e.emit('foo'); +assert.equal(2, e.listeners('foo').length); +assert.deepEqual(['callback1'], callbacks_called); + +e.emit('foo'); +assert.equal(0, e.listeners('foo').length); +assert.deepEqual(['callback1', 'callback2', 'callback3'], callbacks_called); + +e.emit('foo'); +assert.equal(0, e.listeners('foo').length); +assert.deepEqual(['callback1', 'callback2', 'callback3'], callbacks_called); + +e.on('foo', callback1); +e.on('foo', callback2); +assert.equal(2, e.listeners('foo').length); +e.removeAllListeners('foo'); +assert.equal(0, e.listeners('foo').length); + +// Verify that removing callbacks while in emit allows emits to propagate to +// all listeners +callbacks_called = []; + +e.on('foo', callback2); +e.on('foo', callback3); +assert.equal(2, e.listeners('foo').length); +e.emit('foo'); +assert.deepEqual(['callback2', 'callback3'], callbacks_called); +assert.equal(0, e.listeners('foo').length); diff --git a/node-v0.8.14/test/simple/test-event-emitter-num-args.js b/node-v0.8.14/test/simple/test-event-emitter-num-args.js new file mode 100644 index 0000000..037c569 --- /dev/null +++ b/node-v0.8.14/test/simple/test-event-emitter-num-args.js @@ -0,0 +1,48 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var events = require('events'); + +var e = new events.EventEmitter(), + num_args_emited = []; + +e.on('numArgs', function() { + var numArgs = arguments.length; + console.log('numArgs: ' + numArgs); + num_args_emited.push(numArgs); +}); + +console.log('start'); + +e.emit('numArgs'); +e.emit('numArgs', null); +e.emit('numArgs', null, null); +e.emit('numArgs', null, null, null); +e.emit('numArgs', null, null, null, null); +e.emit('numArgs', null, null, null, null, null); + +process.on('exit', function() { + assert.deepEqual([0, 1, 2, 3, 4, 5], num_args_emited); +}); + + diff --git a/node-v0.8.14/test/simple/test-event-emitter-once.js b/node-v0.8.14/test/simple/test-event-emitter-once.js new file mode 100644 index 0000000..1f0a207 --- /dev/null +++ b/node-v0.8.14/test/simple/test-event-emitter-once.js @@ -0,0 +1,49 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var events = require('events'); + +var e = new events.EventEmitter(); +var times_hello_emited = 0; + +e.once('hello', function(a, b) { + times_hello_emited++; +}); + +e.emit('hello', 'a', 'b'); +e.emit('hello', 'a', 'b'); +e.emit('hello', 'a', 'b'); +e.emit('hello', 'a', 'b'); + +var remove = function() { + assert.fail(1, 0, 'once->foo should not be emitted', '!'); +}; + +e.once('foo', remove); +e.removeListener('foo', remove); +e.emit('foo'); + +process.on('exit', function() { + assert.equal(1, times_hello_emited); +}); + diff --git a/node-v0.8.14/test/simple/test-event-emitter-remove-all-listeners.js b/node-v0.8.14/test/simple/test-event-emitter-remove-all-listeners.js new file mode 100644 index 0000000..38cfb79 --- /dev/null +++ b/node-v0.8.14/test/simple/test-event-emitter-remove-all-listeners.js @@ -0,0 +1,58 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var events = require('events'); + + +function listener() {} + +var e1 = new events.EventEmitter(); +e1.on('foo', listener); +e1.on('bar', listener); +e1.on('baz', listener); +e1.on('baz', listener); +var fooListeners = e1.listeners('foo'); +var barListeners = e1.listeners('bar'); +var bazListeners = e1.listeners('baz'); +e1.removeAllListeners('bar'); +e1.removeAllListeners('baz'); +assert.deepEqual(e1.listeners('foo'), [listener]); +assert.deepEqual(e1.listeners('bar'), []); +assert.deepEqual(e1.listeners('baz'), []); +// after calling removeAllListeners, +// the old listeners array should stay unchanged +assert.deepEqual(fooListeners, [listener]); +assert.deepEqual(barListeners, [listener]); +assert.deepEqual(bazListeners, [listener, listener]); +// after calling removeAllListeners, +// new listeners arrays are different from the old +assert.notEqual(e1.listeners('bar'), barListeners); +assert.notEqual(e1.listeners('baz'), bazListeners); + +var e2 = new events.EventEmitter(); +e2.on('foo', listener); +e2.on('bar', listener); +e2.removeAllListeners(); +console.error(e2); +assert.deepEqual([], e2.listeners('foo')); +assert.deepEqual([], e2.listeners('bar')); diff --git a/node-v0.8.14/test/simple/test-event-emitter-remove-listeners.js b/node-v0.8.14/test/simple/test-event-emitter-remove-listeners.js new file mode 100644 index 0000000..7052666 --- /dev/null +++ b/node-v0.8.14/test/simple/test-event-emitter-remove-listeners.js @@ -0,0 +1,61 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var events = require('events'); + + +var count = 0; + +function listener1() { + console.log('listener1'); + count++; +} + +function listener2() { + console.log('listener2'); + count++; +} + +function listener3() { + console.log('listener3'); + count++; +} + +var e1 = new events.EventEmitter(); +e1.on('hello', listener1); +e1.removeListener('hello', listener1); +assert.deepEqual([], e1.listeners('hello')); + +var e2 = new events.EventEmitter(); +e2.on('hello', listener1); +e2.removeListener('hello', listener2); +assert.deepEqual([listener1], e2.listeners('hello')); + +var e3 = new events.EventEmitter(); +e3.on('hello', listener1); +e3.on('hello', listener2); +e3.removeListener('hello', listener1); +assert.deepEqual([listener2], e3.listeners('hello')); + + + diff --git a/node-v0.8.14/test/simple/test-event-emitter-subclass.js b/node-v0.8.14/test/simple/test-event-emitter-subclass.js new file mode 100644 index 0000000..a71a7c7 --- /dev/null +++ b/node-v0.8.14/test/simple/test-event-emitter-subclass.js @@ -0,0 +1,43 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var EventEmitter = require('events').EventEmitter; +var util = require('util'); + +util.inherits(MyEE, EventEmitter); + +function MyEE(cb) { + this.on('foo', cb); + process.nextTick(this.emit.bind(this, 'foo')); + EventEmitter.call(this); +} + +var called = false; +var myee = new MyEE(function() { + called = true; +}); + +process.on('exit', function() { + assert(called); + console.log('ok'); +}); diff --git a/node-v0.8.14/test/simple/test-exception-handler.js b/node-v0.8.14/test/simple/test-exception-handler.js new file mode 100644 index 0000000..38137b8 --- /dev/null +++ b/node-v0.8.14/test/simple/test-exception-handler.js @@ -0,0 +1,47 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); + +var MESSAGE = 'catch me if you can'; +var caughtException = false; + +process.on('uncaughtException', function(e) { + console.log('uncaught exception! 1'); + assert.equal(MESSAGE, e.message); + caughtException = true; +}); + +process.on('uncaughtException', function(e) { + console.log('uncaught exception! 2'); + assert.equal(MESSAGE, e.message); + caughtException = true; +}); + +setTimeout(function() { + throw new Error(MESSAGE); +}, 10); + +process.on('exit', function() { + console.log('exit'); + assert.equal(true, caughtException); +}); diff --git a/node-v0.8.14/test/simple/test-exception-handler2.js b/node-v0.8.14/test/simple/test-exception-handler2.js new file mode 100644 index 0000000..6b8afa9 --- /dev/null +++ b/node-v0.8.14/test/simple/test-exception-handler2.js @@ -0,0 +1,42 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); + +process.on('uncaughtException', function(err) { + console.log('Caught exception: ' + err); +}); + +var timeoutFired = false; +setTimeout(function() { + console.log('This will still run.'); + timeoutFired = true; +}, 500); + +process.on('exit', function() { + assert.ok(timeoutFired); +}); + +// Intentionally cause an exception, but don't catch it. +nonexistentFunc(); +console.log('This will not run.'); + diff --git a/node-v0.8.14/test/simple/test-exec-max-buffer.js b/node-v0.8.14/test/simple/test-exec-max-buffer.js new file mode 100644 index 0000000..3157fc7 --- /dev/null +++ b/node-v0.8.14/test/simple/test-exec-max-buffer.js @@ -0,0 +1,34 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + + + +var common = require('../common'); +var exec = require('child_process').exec; +var assert = require('assert'); + +var cmd = 'echo "hello world"'; + +exec(cmd, { maxBuffer: 5 }, function(err, stdout, stderr) { + assert.ok(err); + assert.ok(/maxBuffer/.test(err.message)); +}); diff --git a/node-v0.8.14/test/simple/test-executable-path.js b/node-v0.8.14/test/simple/test-executable-path.js new file mode 100644 index 0000000..8d82b74 --- /dev/null +++ b/node-v0.8.14/test/simple/test-executable-path.js @@ -0,0 +1,52 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var path = require('path'); +var match = false; + +var isDebug = process.features.debug; + +var debugPaths = [path.normalize(path.join(__dirname, '..', '..', + 'out', 'Debug', 'node')), + path.normalize(path.join(__dirname, '..', '..', + 'Debug', 'node'))]; +var defaultPaths = [path.normalize(path.join(__dirname, '..', '..', + 'out', 'Release', 'node')), + path.normalize(path.join(__dirname, '..', '..', + 'Release', 'node'))]; + +console.error('debugPaths: ' + debugPaths); +console.error('defaultPaths: ' + defaultPaths); +console.error('process.execPath: ' + process.execPath); + +if (isDebug) { + debugPaths.forEach(function(path) { + match = match || process.execPath.indexOf(path) == 0; + }); +} else { + defaultPaths.forEach(function(path) { + match = match || process.execPath.indexOf(path) == 0; + }); +} + +assert.ok(match); diff --git a/node-v0.8.14/test/simple/test-file-read-noexist.js b/node-v0.8.14/test/simple/test-file-read-noexist.js new file mode 100644 index 0000000..aa5e761 --- /dev/null +++ b/node-v0.8.14/test/simple/test-file-read-noexist.js @@ -0,0 +1,42 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var path = require('path'); +var fs = require('fs'); +var got_error = false; + +var filename = path.join(common.fixturesDir, 'does_not_exist.txt'); +fs.readFile(filename, 'raw', function(err, content) { + if (err) { + got_error = true; + } else { + common.debug('cat returned some content: ' + content); + common.debug('this shouldn\'t happen as the file doesn\'t exist...'); + assert.equal(true, false); + } +}); + +process.on('exit', function() { + console.log('done'); + assert.equal(true, got_error); +}); diff --git a/node-v0.8.14/test/simple/test-file-write-stream.js b/node-v0.8.14/test/simple/test-file-write-stream.js new file mode 100644 index 0000000..5d2286c --- /dev/null +++ b/node-v0.8.14/test/simple/test-file-write-stream.js @@ -0,0 +1,81 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); + +var path = require('path'), + fs = require('fs'), + fn = path.join(common.tmpDir, 'write.txt'), + file = fs.createWriteStream(fn), + + EXPECTED = '012345678910', + + callbacks = { + open: -1, + drain: -2, + close: -1, + endCb: -1 + }; + +file + .on('open', function(fd) { + callbacks.open++; + assert.equal('number', typeof fd); + }) + .on('error', function(err) { + throw err; + }) + .on('drain', function() { + callbacks.drain++; + if (callbacks.drain == -1) { + assert.equal(EXPECTED, fs.readFileSync(fn)); + file.write(EXPECTED); + } else if (callbacks.drain == 0) { + assert.equal(EXPECTED + EXPECTED, fs.readFileSync(fn)); + file.end(function(err) { + assert.ok(!err); + callbacks.endCb++; + }); + } + }) + .on('close', function() { + assert.strictEqual(file.bytesWritten, EXPECTED.length * 2); + + callbacks.close++; + assert.throws(function() { + file.write('should not work anymore'); + }); + + fs.unlinkSync(fn); + }); + +for (var i = 0; i < 11; i++) { + (function(i) { + assert.strictEqual(false, file.write(i)); + })(i); +} + +process.on('exit', function() { + for (var k in callbacks) { + assert.equal(0, callbacks[k], k + ' count off by ' + callbacks[k]); + } +}); diff --git a/node-v0.8.14/test/simple/test-file-write-stream2.js b/node-v0.8.14/test/simple/test-file-write-stream2.js new file mode 100644 index 0000000..9b5d7ff --- /dev/null +++ b/node-v0.8.14/test/simple/test-file-write-stream2.js @@ -0,0 +1,98 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); + +var path = require('path'), + fs = require('fs'), + util = require('util'); + + +var filepath = path.join(common.tmpDir, 'write.txt'), + file; + +var EXPECTED = '012345678910'; + +var cb_expected = 'write open drain write drain close error ', + cb_occurred = ''; + +var countDrains = 0; + + +process.on('exit', function() { + removeTestFile(); + if (cb_occurred !== cb_expected) { + console.log(' Test callback events missing or out of order:'); + console.log(' expected: %j', cb_expected); + console.log(' occurred: %j', cb_occurred); + assert.strictEqual(cb_occurred, cb_expected, + 'events missing or out of order: "' + + cb_occurred + '" !== "' + cb_expected + '"'); + } +}); + +function removeTestFile() { + try { + fs.unlinkSync(filepath); + } catch (e) {} +} + + +removeTestFile(); + +file = fs.createWriteStream(filepath); + +file.on('open', function(fd) { + cb_occurred += 'open '; + assert.equal(typeof fd, 'number'); +}); + +file.on('drain', function() { + cb_occurred += 'drain '; + ++countDrains; + if (countDrains === 1) { + assert.equal(fs.readFileSync(filepath), EXPECTED); + file.write(EXPECTED); + cb_occurred += 'write '; + } else if (countDrains == 2) { + assert.equal(fs.readFileSync(filepath), EXPECTED + EXPECTED); + file.end(); + } +}); + +file.on('close', function() { + cb_occurred += 'close '; + assert.strictEqual(file.bytesWritten, EXPECTED.length * 2); + file.write('should not work anymore'); +}); + + +file.on('error', function(err) { + cb_occurred += 'error '; + assert.ok(err.message.indexOf('not writable') >= 0); +}); + + +for (var i = 0; i < 11; i++) { + assert.strictEqual(file.write(i), false); +} +cb_occurred += 'write '; diff --git a/node-v0.8.14/test/simple/test-file-write-stream3.js b/node-v0.8.14/test/simple/test-file-write-stream3.js new file mode 100644 index 0000000..0139462 --- /dev/null +++ b/node-v0.8.14/test/simple/test-file-write-stream3.js @@ -0,0 +1,206 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); + +var path = require('path'), + fs = require('fs'), + util = require('util'); + + +var filepath = path.join(common.tmpDir, 'write_pos.txt'); + + +var cb_expected = 'write open close write open close write open close ', + cb_occurred = ''; + +var fileDataInitial = 'abcdefghijklmnopqrstuvwxyz'; + +var fileDataExpected_1 = 'abcdefghijklmnopqrstuvwxyz'; +var fileDataExpected_2 = 'abcdefghij123456qrstuvwxyz'; +var fileDataExpected_3 = 'abcdefghij\u2026\u2026qrstuvwxyz'; + + +process.on('exit', function() { + removeTestFile(); + if (cb_occurred !== cb_expected) { + console.log(' Test callback events missing or out of order:'); + console.log(' expected: %j', cb_expected); + console.log(' occurred: %j', cb_occurred); + assert.strictEqual(cb_occurred, cb_expected, + 'events missing or out of order: "' + + cb_occurred + '" !== "' + cb_expected + '"'); + } +}); + +function removeTestFile() { + try { + fs.unlinkSync(filepath); + } catch (ex) { } +} + + +removeTestFile(); + + +function run_test_1() { + var file, buffer, options; + + options = {}; + file = fs.createWriteStream(filepath, options); + console.log(' (debug: start ', file.start); + console.log(' (debug: pos ', file.pos); + + file.on('open', function(fd) { + cb_occurred += 'open '; + }); + + file.on('close', function() { + cb_occurred += 'close '; + console.log(' (debug: bytesWritten ', file.bytesWritten); + console.log(' (debug: start ', file.start); + console.log(' (debug: pos ', file.pos); + assert.strictEqual(file.bytesWritten, buffer.length); + var fileData = fs.readFileSync(filepath, 'utf8'); + console.log(' (debug: file data ', fileData); + console.log(' (debug: expected ', fileDataExpected_1); + assert.equal(fileData, fileDataExpected_1); + + run_test_2(); + }); + + file.on('error', function(err) { + cb_occurred += 'error '; + console.log(' (debug: err event ', err); + throw err; + }); + + buffer = new Buffer(fileDataInitial); + file.write(buffer); + cb_occurred += 'write '; + + file.end(); +} + + +function run_test_2() { + var file, buffer, options; + + buffer = new Buffer('123456'); + + options = { start: 10, + flags: 'r+' }; + file = fs.createWriteStream(filepath, options); + console.log(' (debug: start ', file.start); + console.log(' (debug: pos ', file.pos); + + file.on('open', function(fd) { + cb_occurred += 'open '; + }); + + file.on('close', function() { + cb_occurred += 'close '; + console.log(' (debug: bytesWritten ', file.bytesWritten); + console.log(' (debug: start ', file.start); + console.log(' (debug: pos ', file.pos); + assert.strictEqual(file.bytesWritten, buffer.length); + var fileData = fs.readFileSync(filepath, 'utf8'); + console.log(' (debug: file data ', fileData); + console.log(' (debug: expected ', fileDataExpected_2); + assert.equal(fileData, fileDataExpected_2); + + run_test_3(); + }); + + file.on('error', function(err) { + cb_occurred += 'error '; + console.log(' (debug: err event ', err); + throw err; + }); + + file.write(buffer); + cb_occurred += 'write '; + + file.end(); +} + + +function run_test_3() { + var file, buffer, options; + + var data = '\u2026\u2026', // 3 bytes * 2 = 6 bytes in UTF-8 + fileData; + + options = { start: 10, + flags: 'r+' }; + file = fs.createWriteStream(filepath, options); + console.log(' (debug: start ', file.start); + console.log(' (debug: pos ', file.pos); + + file.on('open', function(fd) { + cb_occurred += 'open '; + }); + + file.on('close', function() { + cb_occurred += 'close '; + console.log(' (debug: bytesWritten ', file.bytesWritten); + console.log(' (debug: start ', file.start); + console.log(' (debug: pos ', file.pos); + assert.strictEqual(file.bytesWritten, data.length * 3); + fileData = fs.readFileSync(filepath, 'utf8'); + console.log(' (debug: file data ', fileData); + console.log(' (debug: expected ', fileDataExpected_3); + assert.equal(fileData, fileDataExpected_3); + + run_test_4(); + }); + + file.on('error', function(err) { + cb_occurred += 'error '; + console.log(' (debug: err event ', err); + throw err; + }); + + file.write(data, 'utf8'); + cb_occurred += 'write '; + + file.end(); +} + + +function run_test_4() { + var file, options; + + options = { start: -5, + flags: 'r+' }; + + // Error: start must be >= zero + assert.throws( + function() { + file = fs.createWriteStream(filepath, options); + }, + /start must be/ + ); + +} + +run_test_1(); diff --git a/node-v0.8.14/test/simple/test-force-repl.js b/node-v0.8.14/test/simple/test-force-repl.js new file mode 100644 index 0000000..60ba348 --- /dev/null +++ b/node-v0.8.14/test/simple/test-force-repl.js @@ -0,0 +1,44 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var spawn = require('child_process').spawn; + +// spawn a node child process in "interactive" mode (force the repl) +var cp = spawn(process.execPath, ['-i']); +var gotToEnd = false; +var timeoutId = setTimeout(function() { + throw new Error('timeout!'); +}, 1000); // give node + the repl 1 second to boot up + +cp.stdout.setEncoding('utf8'); + +cp.stdout.once('data', function(b) { + clearTimeout(timeoutId); + assert.equal(b, '> '); + gotToEnd = true; + cp.kill(); +}); + +process.on('exit', function() { + assert(gotToEnd); +}); diff --git a/node-v0.8.14/test/simple/test-fs-append-file-sync.js b/node-v0.8.14/test/simple/test-fs-append-file-sync.js new file mode 100644 index 0000000..5e1158f --- /dev/null +++ b/node-v0.8.14/test/simple/test-fs-append-file-sync.js @@ -0,0 +1,94 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var join = require('path').join; +var fs = require('fs'); + +var currentFileData = 'ABCD'; + +var num = 220; +var data = '南越国是前203年至前111年存在于岭南地区的一个国家,国都位于番禺,疆域包括今天中国的广东、' + + '广西两省区的大部份地区,福建省、湖南、贵州、云南的一小部份地区和越南的北部。' + + '南越国是秦朝灭亡后,由南海郡尉赵佗于前203年起兵兼并桂林郡和象郡后建立。' + + '前196年和前179年,南越国曾先后两次名义上臣属于西汉,成为西汉的“外臣”。前112年,' + + '南越国末代君主赵建德与西汉发生战争,被汉武帝于前111年所灭。南越国共存在93年,' + + '历经五代君主。南越国是岭南地区的第一个有记载的政权国家,采用封建制和郡县制并存的制度,' + + '它的建立保证了秦末乱世岭南地区社会秩序的稳定,有效的改善了岭南地区落后的政治、##济现状。\n'; + +// test that empty file will be created and have content added +var filename = join(common.fixturesDir, 'append-sync.txt'); + +common.error('appending to ' + filename); +fs.appendFileSync(filename, data); + +var fileData = fs.readFileSync(filename); + +assert.equal(Buffer.byteLength(data), fileData.length); + +// test that appends data to a non empty file +var filename2 = join(common.fixturesDir, 'append-sync2.txt'); +fs.writeFileSync(filename2, currentFileData); + +common.error('appending to ' + filename2); +fs.appendFileSync(filename2, data); + +var fileData2 = fs.readFileSync(filename2); + +assert.equal(Buffer.byteLength(data) + currentFileData.length, + fileData2.length); + +// test that appendFileSync accepts buffers +var filename3 = join(common.fixturesDir, 'append-sync3.txt'); +fs.writeFileSync(filename3, currentFileData); + +common.error('appending to ' + filename3); + +var buf = new Buffer(data, 'utf8'); +fs.appendFileSync(filename3, buf); + +var fileData3 = fs.readFileSync(filename3); + +assert.equal(buf.length + currentFileData.length, fileData3.length); + +// test that appendFile accepts numbers. +var filename4 = join(common.fixturesDir, 'append-sync4.txt'); +fs.writeFileSync(filename4, currentFileData); + +common.error('appending to ' + filename4); +fs.appendFileSync(filename4, num); + +var fileData4 = fs.readFileSync(filename4); + +assert.equal(Buffer.byteLength('' + num) + currentFileData.length, + fileData4.length); + +//exit logic for cleanup + +process.on('exit', function() { + common.error('done'); + + fs.unlinkSync(filename); + fs.unlinkSync(filename2); + fs.unlinkSync(filename3); + fs.unlinkSync(filename4); +}); diff --git a/node-v0.8.14/test/simple/test-fs-append-file.js b/node-v0.8.14/test/simple/test-fs-append-file.js new file mode 100644 index 0000000..34be240 --- /dev/null +++ b/node-v0.8.14/test/simple/test-fs-append-file.js @@ -0,0 +1,127 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var fs = require('fs'); +var join = require('path').join; + +var filename = join(common.fixturesDir, 'append.txt'); + +common.error('appending to ' + filename); + +var currentFileData = 'ABCD'; + +var n = 220; +var s = '南越国是前203年至前111年存在于岭南地区的一个国家,国都位于番禺,疆域包括今天中国的广东、' + + '广西两省区的大部份地区,福建省、湖南、贵州、云南的一小部份地区和越南的北部。' + + '南越国是秦朝灭亡后,由南海郡尉赵佗于前203年起兵兼并桂林郡和象郡后建立。' + + '前196年和前179年,南越国曾先后两次名义上臣属于西汉,成为西汉的“外臣”。前112年,' + + '南越国末代君主赵建德与西汉发生战争,被汉武帝于前111年所灭。南越国共存在93年,' + + '历经五代君主。南越国是岭南地区的第一个有记载的政权国家,采用封建制和郡县制并存的制度,' + + '它的建立保证了秦末乱世岭南地区社会秩序的稳定,有效的改善了岭南地区落后的政治、##济现状。\n'; + +var ncallbacks = 0; + +// test that empty file will be created and have content added +fs.appendFile(filename, s, function(e) { + if (e) throw e; + + ncallbacks++; + common.error('appended to file'); + + fs.readFile(filename, function(e, buffer) { + if (e) throw e; + common.error('file read'); + ncallbacks++; + assert.equal(Buffer.byteLength(s), buffer.length); + }); +}); + +// test that appends data to a non empty file +var filename2 = join(common.fixturesDir, 'append2.txt'); +fs.writeFileSync(filename2, currentFileData); + +fs.appendFile(filename2, s, function(e) { + if (e) throw e; + + ncallbacks++; + common.error('appended to file2'); + + fs.readFile(filename2, function(e, buffer) { + if (e) throw e; + common.error('file2 read'); + ncallbacks++; + assert.equal(Buffer.byteLength(s) + currentFileData.length, buffer.length); + }); +}); + +// test that appendFile accepts buffers +var filename3 = join(common.fixturesDir, 'append3.txt'); +fs.writeFileSync(filename3, currentFileData); + +var buf = new Buffer(s, 'utf8'); +common.error('appending to ' + filename3); + +fs.appendFile(filename3, buf, function(e) { + if (e) throw e; + + ncallbacks++; + common.error('appended to file3'); + + fs.readFile(filename3, function(e, buffer) { + if (e) throw e; + common.error('file3 read'); + ncallbacks++; + assert.equal(buf.length + currentFileData.length, buffer.length); + }); +}); + +// test that appendFile accepts numbers. +var filename4 = join(common.fixturesDir, 'append4.txt'); +fs.writeFileSync(filename4, currentFileData); + +common.error('appending to ' + filename4); + +fs.appendFile(filename4, n, function(e) { + if (e) throw e; + + ncallbacks++; + common.error('appended to file4'); + + fs.readFile(filename4, function(e, buffer) { + if (e) throw e; + common.error('file4 read'); + ncallbacks++; + assert.equal(Buffer.byteLength('' + n) + currentFileData.length, + buffer.length); + }); +}); + +process.on('exit', function() { + common.error('done'); + assert.equal(8, ncallbacks); + + fs.unlinkSync(filename); + fs.unlinkSync(filename2); + fs.unlinkSync(filename3); + fs.unlinkSync(filename4); +}); diff --git a/node-v0.8.14/test/simple/test-fs-chmod.js b/node-v0.8.14/test/simple/test-fs-chmod.js new file mode 100644 index 0000000..12fd820 --- /dev/null +++ b/node-v0.8.14/test/simple/test-fs-chmod.js @@ -0,0 +1,161 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var path = require('path'); +var fs = require('fs'); +var got_error = false; +var success_count = 0; +var mode_async; +var mode_sync; +var is_windows = process.platform === 'win32'; + +// Need to hijack fs.open/close to make sure that things +// get closed once they're opened. +fs._open = fs.open; +fs._openSync = fs.openSync; +fs.open = open; +fs.openSync = openSync; +fs._close = fs.close; +fs._closeSync = fs.closeSync; +fs.close = close; +fs.closeSync = closeSync; + +var openCount = 0; + +function open() { + openCount++; + return fs._open.apply(fs, arguments); +} + +function openSync() { + openCount++; + return fs._openSync.apply(fs, arguments); +} + +function close() { + openCount--; + return fs._close.apply(fs, arguments); +} + +function closeSync() { + openCount--; + return fs._closeSync.apply(fs, arguments); +} + + +// On Windows chmod is only able to manipulate read-only bit +if (is_windows) { + mode_async = 0400; // read-only + mode_sync = 0600; // read-write +} else { + mode_async = 0777; + mode_sync = 0644; +} + +var file1 = path.join(common.fixturesDir, 'a.js'), + file2 = path.join(common.fixturesDir, 'a1.js'); + +fs.chmod(file1, mode_async.toString(8), function(err) { + if (err) { + got_error = true; + } else { + console.log(fs.statSync(file1).mode); + + if (is_windows) { + assert.ok((fs.statSync(file1).mode & 0777) & mode_async); + } else { + assert.equal(mode_async, fs.statSync(file1).mode & 0777); + } + + fs.chmodSync(file1, mode_sync); + if (is_windows) { + assert.ok((fs.statSync(file1).mode & 0777) & mode_sync); + } else { + assert.equal(mode_sync, fs.statSync(file1).mode & 0777); + } + success_count++; + } +}); + +fs.open(file2, 'a', function(err, fd) { + if (err) { + got_error = true; + console.error(err.stack); + return; + } + fs.fchmod(fd, mode_async.toString(8), function(err) { + if (err) { + got_error = true; + } else { + console.log(fs.fstatSync(fd).mode); + + if (is_windows) { + assert.ok((fs.fstatSync(fd).mode & 0777) & mode_async); + } else { + assert.equal(mode_async, fs.fstatSync(fd).mode & 0777); + } + + fs.fchmodSync(fd, mode_sync); + if (is_windows) { + assert.ok((fs.fstatSync(fd).mode & 0777) & mode_sync); + } else { + assert.equal(mode_sync, fs.fstatSync(fd).mode & 0777); + } + success_count++; + fs.close(fd); + } + }); +}); + +// lchmod +if (fs.lchmod) { + var link = path.join(common.tmpDir, 'symbolic-link'); + + try { + fs.unlinkSync(link); + } catch (er) {} + fs.symlinkSync(file2, link); + + fs.lchmod(link, mode_async, function(err) { + if (err) { + got_error = true; + } else { + console.log(fs.lstatSync(link).mode); + assert.equal(mode_async, fs.lstatSync(link).mode & 0777); + + fs.lchmodSync(link, mode_sync); + assert.equal(mode_sync, fs.lstatSync(link).mode & 0777); + success_count++; + } + }); +} else { + success_count++; +} + + +process.on('exit', function() { + assert.equal(3, success_count); + assert.equal(0, openCount); + assert.equal(false, got_error); +}); + diff --git a/node-v0.8.14/test/simple/test-fs-empty-readStream.js b/node-v0.8.14/test/simple/test-fs-empty-readStream.js new file mode 100644 index 0000000..a9b378f --- /dev/null +++ b/node-v0.8.14/test/simple/test-fs-empty-readStream.js @@ -0,0 +1,66 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var path = require('path'); +var fs = require('fs'); + +var emptyFile = path.join(common.fixturesDir, 'empty.txt'); + +fs.open(emptyFile, 'r', function (error, fd) { + assert.ifError(error); + + var read = fs.createReadStream(emptyFile, { 'fd': fd }); + + read.once('data', function () { + throw new Error("data event should not emit"); + }); + + var readEmit = false; + read.once('end', function () { + readEmit = true; + }); + + setTimeout(function () { + assert.equal(readEmit, true); + }, 50); +}); + +fs.open(emptyFile, 'r', function (error, fd) { + assert.ifError(error); + + var read = fs.createReadStream(emptyFile, { 'fd': fd }); + read.pause(); + + read.once('data', function () { + throw new Error("data event should not emit"); + }); + + var readEmit = false; + read.once('end', function () { + readEmit = true; + }); + + setTimeout(function () { + assert.equal(readEmit, false); + }, 50); +}); diff --git a/node-v0.8.14/test/simple/test-fs-error-messages.js b/node-v0.8.14/test/simple/test-fs-error-messages.js new file mode 100644 index 0000000..772966b --- /dev/null +++ b/node-v0.8.14/test/simple/test-fs-error-messages.js @@ -0,0 +1,189 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + + + +var common = require('../common'); +var assert = require('assert'); + +var path = require('path'), + fs = require('fs'), + fn = path.join(common.fixturesDir, 'non-existent'), + existingFile = path.join(common.fixturesDir, 'exit.js'); + +// ASYNC_CALL + +fs.stat(fn, function(err) { + assert.equal(fn, err.path); + assert.ok(0 <= err.message.indexOf(fn)); +}); + +fs.lstat(fn, function(err) { + assert.ok(0 <= err.message.indexOf(fn)); +}); + +fs.readlink(fn, function(err) { + assert.ok(0 <= err.message.indexOf(fn)); +}); + +fs.link(fn, 'foo', function(err) { + assert.ok(0 <= err.message.indexOf(fn)); +}); + +fs.unlink(fn, function(err) { + assert.ok(0 <= err.message.indexOf(fn)); +}); + +fs.rename(fn, 'foo', function(err) { + assert.ok(0 <= err.message.indexOf(fn)); +}); + +fs.rmdir(fn, function(err) { + assert.ok(0 <= err.message.indexOf(fn)); +}); + +fs.mkdir(existingFile, 0666, function(err) { + assert.ok(0 <= err.message.indexOf(existingFile)); +}); + +fs.rmdir(existingFile, function(err) { + assert.ok(0 <= err.message.indexOf(existingFile)); +}); + +fs.chmod(fn, 0666, function(err) { + assert.ok(0 <= err.message.indexOf(fn)); +}); + +fs.open(fn, 'r', 0666, function(err) { + assert.ok(0 <= err.message.indexOf(fn)); +}); + +fs.readFile(fn, function(err) { + assert.ok(0 <= err.message.indexOf(fn)); +}); + +// Sync + +var errors = [], + expected = 0; + +try { + ++expected; + fs.statSync(fn); +} catch (err) { + errors.push('stat'); + assert.ok(0 <= err.message.indexOf(fn)); +} + +try { + ++expected; + fs.mkdirSync(existingFile, 0666); +} catch (err) { + errors.push('mkdir'); + assert.ok(0 <= err.message.indexOf(existingFile)); +} + +try { + ++expected; + fs.chmodSync(fn, 0666); +} catch (err) { + errors.push('chmod'); + assert.ok(0 <= err.message.indexOf(fn)); +} + +try { + ++expected; + fs.lstatSync(fn); +} catch (err) { + errors.push('lstat'); + assert.ok(0 <= err.message.indexOf(fn)); +} + +try { + ++expected; + fs.readlinkSync(fn); +} catch (err) { + errors.push('readlink'); + assert.ok(0 <= err.message.indexOf(fn)); +} + +try { + ++expected; + fs.linkSync(fn, 'foo'); +} catch (err) { + errors.push('link'); + assert.ok(0 <= err.message.indexOf(fn)); +} + +try { + ++expected; + fs.unlinkSync(fn); +} catch (err) { + errors.push('unlink'); + assert.ok(0 <= err.message.indexOf(fn)); +} + +try { + ++expected; + fs.rmdirSync(fn); +} catch (err) { + errors.push('rmdir'); + assert.ok(0 <= err.message.indexOf(fn)); +} + +try { + ++expected; + fs.rmdirSync(existingFile); +} catch (err) { + errors.push('rmdir'); + assert.ok(0 <= err.message.indexOf(existingFile)); +} + +try { + ++expected; + fs.openSync(fn, 'r'); +} catch (err) { + errors.push('opens'); + assert.ok(0 <= err.message.indexOf(fn)); +} + +try { + ++expected; + fs.renameSync(fn, 'foo'); +} catch (err) { + errors.push('rename'); + assert.ok(0 <= err.message.indexOf(fn)); +} + +try { + ++expected; + fs.readdirSync(fn); +} catch (err) { + errors.push('readdir'); + assert.ok(0 <= err.message.indexOf(fn)); +} + +process.on('exit', function() { + assert.equal(expected, errors.length, + 'Test fs sync exceptions raised, got ' + errors.length + + ' expected ' + expected); +}); diff --git a/node-v0.8.14/test/simple/test-fs-exists.js b/node-v0.8.14/test/simple/test-fs-exists.js new file mode 100644 index 0000000..3775730 --- /dev/null +++ b/node-v0.8.14/test/simple/test-fs-exists.js @@ -0,0 +1,43 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var fs = require('fs'); +var f = __filename; +var exists; +var doesNotExist; + +fs.exists(f, function(y) { + exists = y; +}); + +fs.exists(f + '-NO', function(y) { + doesNotExist = y; +}); + +assert(fs.existsSync(f)); +assert(!fs.existsSync(f + '-NO')); + +process.on('exit', function() { + assert.strictEqual(exists, true); + assert.strictEqual(doesNotExist, false); +}); diff --git a/node-v0.8.14/test/simple/test-fs-fsync.js b/node-v0.8.14/test/simple/test-fs-fsync.js new file mode 100644 index 0000000..e624ed7 --- /dev/null +++ b/node-v0.8.14/test/simple/test-fs-fsync.js @@ -0,0 +1,59 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); + +var path = require('path'); +var fs = require('fs'); +var successes = 0; + +var file = path.join(common.fixturesDir, 'a.js'); + +common.error('open ' + file); + +fs.open(file, 'a', 0777, function(err, fd) { + common.error('fd ' + fd); + if (err) throw err; + + fs.fdatasyncSync(fd); + common.error('fdatasync SYNC: ok'); + successes++; + + fs.fsyncSync(fd); + common.error('fsync SYNC: ok'); + successes++; + + fs.fdatasync(fd, function(err) { + if (err) throw err; + common.error('fdatasync ASYNC: ok'); + successes++; + fs.fsync(fd, function(err) { + if (err) throw err; + common.error('fsync ASYNC: ok'); + successes++; + }); + }); +}); + +process.on('exit', function() { + assert.equal(4, successes); +}); diff --git a/node-v0.8.14/test/simple/test-fs-long-path.js b/node-v0.8.14/test/simple/test-fs-long-path.js new file mode 100644 index 0000000..eac58f6 --- /dev/null +++ b/node-v0.8.14/test/simple/test-fs-long-path.js @@ -0,0 +1,51 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var fs = require('fs'); +var path = require('path'); +var assert = require('assert'); + +var successes = 0; + +// make a path that will be at least 260 chars long. +var fileNameLen = Math.max(260 - common.tmpDir.length - 1, 1); +var fileName = path.join(common.tmpDir, new Array(fileNameLen + 1).join('x')); +var fullPath = path.resolve(fileName); + +console.log({ + filenameLength: fileName.length, + fullPathLength: fullPath.length +}); + +fs.writeFile(fullPath, 'ok', function(err) { + if (err) throw err; + successes++; + + fs.stat(fullPath, function(err, stats) { + if (err) throw err; + successes++; + }); +}); + +process.on('exit', function() { + assert.equal(2, successes); +}); diff --git a/node-v0.8.14/test/simple/test-fs-mkdir.js b/node-v0.8.14/test/simple/test-fs-mkdir.js new file mode 100644 index 0000000..d99cd37 --- /dev/null +++ b/node-v0.8.14/test/simple/test-fs-mkdir.js @@ -0,0 +1,83 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var fs = require('fs'); + +function unlink(pathname) { + try { + fs.rmdirSync(pathname); + } catch (e) { + } +} + +(function() { + var ncalls = 0; + var pathname = common.tmpDir + '/test1'; + + unlink(pathname); + + fs.mkdir(pathname, function(err) { + assert.equal(err, null); + assert.equal(fs.existsSync(pathname), true); + ncalls++; + }); + + process.on('exit', function() { + unlink(pathname); + assert.equal(ncalls, 1); + }); +})(); + +(function() { + var ncalls = 0; + var pathname = common.tmpDir + '/test2'; + + unlink(pathname); + + fs.mkdir(pathname, 511 /*=0777*/, function(err) { + assert.equal(err, null); + assert.equal(fs.existsSync(pathname), true); + ncalls++; + }); + + process.on('exit', function() { + unlink(pathname); + assert.equal(ncalls, 1); + }); +})(); + +(function() { + var pathname = common.tmpDir + '/test3'; + + unlink(pathname); + fs.mkdirSync(pathname); + + var exists = fs.existsSync(pathname); + unlink(pathname); + + assert.equal(exists, true); +})(); + +// Keep the event loop alive so the async mkdir() requests +// have a chance to run (since they don't ref the event loop). +process.nextTick(function() {}); diff --git a/node-v0.8.14/test/simple/test-fs-non-number-arguments-throw.js b/node-v0.8.14/test/simple/test-fs-non-number-arguments-throw.js new file mode 100644 index 0000000..7a1e7bd --- /dev/null +++ b/node-v0.8.14/test/simple/test-fs-non-number-arguments-throw.js @@ -0,0 +1,24 @@ +var assert = require('assert'), + fs = require('fs'), + saneEmitter, + sanity = 'ire(\'assert\')'; + +saneEmitter = fs.createReadStream(__filename, { start: 17, end: 29 }); + +assert.throws(function () { + fs.createReadStream(__filename, { start: "17", end: 29 }); +}, "start as string didn't throw an error for createReadStream"); + +assert.throws(function () { + fs.createReadStream(__filename, { start: 17, end: "29" }); +}, "end as string didn't throw an error"); + +assert.throws(function () { + fs.createWriteStream(__filename, { start: "17" }); +}, "start as string didn't throw an error for createWriteStream"); + +saneEmitter.on('data', function (data) { + // a sanity check when using numbers instead of strings + assert.strictEqual(sanity, data.toString('utf8'), 'read ' + + data.toString('utf8') + ' instead of ' + sanity); +}); diff --git a/node-v0.8.14/test/simple/test-fs-open-flags.js b/node-v0.8.14/test/simple/test-fs-open-flags.js new file mode 100644 index 0000000..e1c6c3b --- /dev/null +++ b/node-v0.8.14/test/simple/test-fs-open-flags.js @@ -0,0 +1,60 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); + +var constants = require('constants'); +var fs = require('fs'); + +var O_APPEND = constants.O_APPEND || 0; +var O_CREAT = constants.O_CREAT || 0; +var O_DIRECTORY = constants.O_DIRECTORY || 0; +var O_EXCL = constants.O_EXCL || 0; +var O_NOCTTY = constants.O_NOCTTY || 0; +var O_NOFOLLOW = constants.O_NOFOLLOW || 0; +var O_RDONLY = constants.O_RDONLY || 0; +var O_RDWR = constants.O_RDWR || 0; +var O_SYMLINK = constants.O_SYMLINK || 0; +var O_SYNC = constants.O_SYNC || 0; +var O_TRUNC = constants.O_TRUNC || 0; +var O_WRONLY = constants.O_WRONLY || 0; + +assert.equal(fs._stringToFlags('r'), O_RDONLY); +assert.equal(fs._stringToFlags('r+'), O_RDWR); +assert.equal(fs._stringToFlags('w'), O_TRUNC | O_CREAT | O_WRONLY); +assert.equal(fs._stringToFlags('w+'), O_TRUNC | O_CREAT | O_RDWR); +assert.equal(fs._stringToFlags('a'), O_APPEND | O_CREAT | O_WRONLY); +assert.equal(fs._stringToFlags('a+'), O_APPEND | O_CREAT | O_RDWR); + +assert.equal(fs._stringToFlags('wx'), O_TRUNC | O_CREAT | O_WRONLY | O_EXCL); +assert.equal(fs._stringToFlags('xw'), O_TRUNC | O_CREAT | O_WRONLY | O_EXCL); +assert.equal(fs._stringToFlags('wx+'), O_TRUNC | O_CREAT | O_RDWR | O_EXCL); +assert.equal(fs._stringToFlags('xw+'), O_TRUNC | O_CREAT | O_RDWR | O_EXCL); +assert.equal(fs._stringToFlags('ax'), O_APPEND | O_CREAT | O_WRONLY | O_EXCL); +assert.equal(fs._stringToFlags('xa'), O_APPEND | O_CREAT | O_WRONLY | O_EXCL); +assert.equal(fs._stringToFlags('ax+'), O_APPEND | O_CREAT | O_RDWR | O_EXCL); +assert.equal(fs._stringToFlags('xa+'), O_APPEND | O_CREAT | O_RDWR | O_EXCL); + +('+ +a +r +w rw wa war raw r++ a++ w++' + + 'x +x x+ rx rx+ wxx wax xwx xxx').split(' ').forEach(function(flags) { + assert.throws(function() { fs._stringToFlags(flags); }); +}); diff --git a/node-v0.8.14/test/simple/test-fs-open.js b/node-v0.8.14/test/simple/test-fs-open.js new file mode 100644 index 0000000..e334de9 --- /dev/null +++ b/node-v0.8.14/test/simple/test-fs-open.js @@ -0,0 +1,59 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var constants = require('constants'); +var common = require('../common'); +var assert = require('assert'); +var fs = require('fs'); + +var caughtException = false; +try { + // should throw ENOENT, not EBADF + // see https://github.com/joyent/node/pull/1228 + fs.openSync('/path/to/file/that/does/not/exist', 'r'); +} +catch (e) { + assert.equal(e.code, 'ENOENT'); + caughtException = true; +} +assert.ok(caughtException); + +var openFd; +fs.open(__filename, 'r', function(err, fd) { + if (err) { + throw err; + } + openFd = fd; +}); + +var openFd2; +fs.open(__filename, 'rs', function(err, fd) { + if (err) { + throw err; + } + openFd2 = fd; +}); + +process.on('exit', function() { + assert.ok(openFd); + assert.ok(openFd2); +}); + diff --git a/node-v0.8.14/test/simple/test-fs-read-buffer.js b/node-v0.8.14/test/simple/test-fs-read-buffer.js new file mode 100644 index 0000000..96f7003 --- /dev/null +++ b/node-v0.8.14/test/simple/test-fs-read-buffer.js @@ -0,0 +1,50 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + + + +var common = require('../common'); +var assert = require('assert'); +var path = require('path'), + Buffer = require('buffer').Buffer, + fs = require('fs'), + filepath = path.join(common.fixturesDir, 'x.txt'), + fd = fs.openSync(filepath, 'r'), + expected = 'xyz\n', + bufferAsync = new Buffer(expected.length), + bufferSync = new Buffer(expected.length), + readCalled = 0; + +fs.read(fd, bufferAsync, 0, expected.length, 0, function(err, bytesRead) { + readCalled++; + + assert.equal(bytesRead, expected.length); + assert.deepEqual(bufferAsync, new Buffer(expected)); +}); + +var r = fs.readSync(fd, bufferSync, 0, expected.length, 0); +assert.deepEqual(bufferSync, new Buffer(expected)); +assert.equal(r, expected.length); + +process.on('exit', function() { + assert.equal(readCalled, 1); +}); diff --git a/node-v0.8.14/test/simple/test-fs-read-file-sync-hostname.js b/node-v0.8.14/test/simple/test-fs-read-file-sync-hostname.js new file mode 100644 index 0000000..758e2ae --- /dev/null +++ b/node-v0.8.14/test/simple/test-fs-read-file-sync-hostname.js @@ -0,0 +1,30 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var fs = require('fs'); + +// test reading from hostname +if (process.platform === 'linux2') { + var hostname = fs.readFileSync('/proc/sys/kernel/hostname'); + assert.ok(hostname.length > 0); +} diff --git a/node-v0.8.14/test/simple/test-fs-read-file-sync.js b/node-v0.8.14/test/simple/test-fs-read-file-sync.js new file mode 100644 index 0000000..518d32c --- /dev/null +++ b/node-v0.8.14/test/simple/test-fs-read-file-sync.js @@ -0,0 +1,33 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var path = require('path'); +var fs = require('fs'); + +var fn = path.join(common.fixturesDir, 'elipses.txt'); + +var s = fs.readFileSync(fn, 'utf8'); +for (var i = 0; i < s.length; i++) { + assert.equal('\u2026', s[i]); +} +assert.equal(10000, s.length); diff --git a/node-v0.8.14/test/simple/test-fs-read-stream-fd.js b/node-v0.8.14/test/simple/test-fs-read-stream-fd.js new file mode 100644 index 0000000..835ed97 --- /dev/null +++ b/node-v0.8.14/test/simple/test-fs-read-stream-fd.js @@ -0,0 +1,44 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var fs = require('fs'); +var assert = require('assert'); +var path = require('path'); + +var common = require('../common'); + +var file = path.join(common.tmpDir, '/read_stream_fd_test.txt'); +var input = 'hello world'; +var output = ''; +var fd, stream; + +fs.writeFileSync(file, input); +fd = fs.openSync(file, 'r'); + +stream = fs.createReadStream(null, { fd: fd, encoding: 'utf8' }); +stream.on('data', function(data) { + output += data; +}); + +process.on('exit', function() { + fs.unlinkSync(file); + assert.equal(output, input); +}); diff --git a/node-v0.8.14/test/simple/test-fs-read-stream-resume.js b/node-v0.8.14/test/simple/test-fs-read-stream-resume.js new file mode 100644 index 0000000..c3ace49 --- /dev/null +++ b/node-v0.8.14/test/simple/test-fs-read-stream-resume.js @@ -0,0 +1,51 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); + +var fs = require('fs'); +var path = require('path'); + +var file = path.join(common.fixturesDir, 'x.txt'); +var data = ''; +var first = true; + +var stream = fs.createReadStream(file); +stream.setEncoding('utf8'); +stream.on('data', function(chunk) { + data += chunk; + if (first) { + first = false; + stream.resume(); + } +}); + +process.nextTick(function() { + stream.pause(); + setTimeout(function() { + stream.resume(); + }, 100); +}); + +process.on('exit', function() { + assert.equal(data, 'xyz\n'); +}); diff --git a/node-v0.8.14/test/simple/test-fs-read-stream.js b/node-v0.8.14/test/simple/test-fs-read-stream.js new file mode 100644 index 0000000..d500fc4 --- /dev/null +++ b/node-v0.8.14/test/simple/test-fs-read-stream.js @@ -0,0 +1,169 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + + + +var common = require('../common'); +var assert = require('assert'); + +// TODO Improved this test. test_ca.pem is too small. A proper test would +// great a large utf8 (with multibyte chars) file and stream it in, +// performing sanity checks throughout. + +var path = require('path'); +var fs = require('fs'); +var fn = path.join(common.fixturesDir, 'elipses.txt'); +var rangeFile = path.join(common.fixturesDir, 'x.txt'); + +var callbacks = { open: 0, end: 0, close: 0, destroy: 0 }; + +var paused = false; + +var file = fs.ReadStream(fn); + +file.on('open', function(fd) { + file.length = 0; + callbacks.open++; + assert.equal('number', typeof fd); + assert.ok(file.readable); + + // GH-535 + file.pause(); + file.resume(); + file.pause(); + file.resume(); +}); + +file.on('data', function(data) { + assert.ok(data instanceof Buffer); + assert.ok(!paused); + file.length += data.length; + + paused = true; + file.pause(); + assert.ok(file.paused); + + setTimeout(function() { + paused = false; + file.resume(); + assert.ok(!file.paused); + }, 10); +}); + + +file.on('end', function(chunk) { + callbacks.end++; +}); + + +file.on('close', function() { + callbacks.close++; + assert.ok(!file.readable); + + //assert.equal(fs.readFileSync(fn), fileContent); +}); + +var file2 = fs.createReadStream(fn); +file2.destroy(function(err) { + assert.ok(!err); + callbacks.destroy++; + + file2.destroy(function(err) { + assert.ok(!err); + callbacks.destroy++; + }); +}); + +var file3 = fs.createReadStream(fn, {encoding: 'utf8'}); +file3.length = 0; +file3.on('data', function(data) { + assert.equal('string', typeof(data)); + file3.length += data.length; + + for (var i = 0; i < data.length; i++) { + // http://www.fileformat.info/info/unicode/char/2026/index.htm + assert.equal('\u2026', data[i]); + } +}); + +file3.on('close', function() { + callbacks.close++; +}); + +process.on('exit', function() { + assert.equal(1, callbacks.open); + assert.equal(1, callbacks.end); + assert.equal(2, callbacks.destroy); + + assert.equal(2, callbacks.close); + + assert.equal(30000, file.length); + assert.equal(10000, file3.length); +}); + +var file4 = fs.createReadStream(rangeFile, {bufferSize: 1, start: 1, end: 2}); +var contentRead = ''; +file4.on('data', function(data) { + contentRead += data.toString('utf-8'); +}); +file4.on('end', function(data) { + assert.equal(contentRead, 'yz'); +}); + +var file5 = fs.createReadStream(rangeFile, {bufferSize: 1, start: 1}); +file5.data = ''; +file5.on('data', function(data) { + file5.data += data.toString('utf-8'); +}); +file5.on('end', function() { + assert.equal(file5.data, 'yz\n'); +}); + +// https://github.com/joyent/node/issues/2320 +var file6 = fs.createReadStream(rangeFile, {bufferSize: 1.23, start: 1}); +file6.data = ''; +file6.on('data', function(data) { + file6.data += data.toString('utf-8'); +}); +file6.on('end', function() { + assert.equal(file6.data, 'yz\n'); +}); + +assert.throws(function() { + fs.createReadStream(rangeFile, {start: 10, end: 2}); +}, /start must be <= end/); + +var stream = fs.createReadStream(rangeFile, { start: 0, end: 0 }); +stream.data = ''; + +stream.on('data', function(chunk) { + stream.data += chunk; +}); + +stream.on('end', function() { + assert.equal('x', stream.data); +}); + +// pause and then resume immediately. +var pauseRes = fs.createReadStream(rangeFile); +pauseRes.pause(); +pauseRes.resume(); diff --git a/node-v0.8.14/test/simple/test-fs-read.js b/node-v0.8.14/test/simple/test-fs-read.js new file mode 100644 index 0000000..4a90f90 --- /dev/null +++ b/node-v0.8.14/test/simple/test-fs-read.js @@ -0,0 +1,48 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + + + +var common = require('../common'); +var assert = require('assert'); +var path = require('path'), + fs = require('fs'), + filepath = path.join(common.fixturesDir, 'x.txt'), + fd = fs.openSync(filepath, 'r'), + expected = 'xyz\n', + readCalled = 0; + +fs.read(fd, expected.length, 0, 'utf-8', function(err, str, bytesRead) { + readCalled++; + + assert.ok(!err); + assert.equal(str, expected); + assert.equal(bytesRead, expected.length); +}); + +var r = fs.readSync(fd, expected.length, 0, 'utf-8'); +assert.equal(r[0], expected); +assert.equal(r[1], expected.length); + +process.on('exit', function() { + assert.equal(readCalled, 1); +}); diff --git a/node-v0.8.14/test/simple/test-fs-readfile-empty.js b/node-v0.8.14/test/simple/test-fs-readfile-empty.js new file mode 100644 index 0000000..31b8356 --- /dev/null +++ b/node-v0.8.14/test/simple/test-fs-readfile-empty.js @@ -0,0 +1,38 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); + +var path = require('path'), + fs = require('fs'), + fn = path.join(common.fixturesDir, 'empty.txt'); + +fs.readFile(fn, function(err, data) { + assert.ok(data); +}); + +fs.readFile(fn, 'utf8', function(err, data) { + assert.strictEqual('', data); +}); + +assert.ok(fs.readFileSync(fn)); +assert.strictEqual('', fs.readFileSync(fn, 'utf8')); diff --git a/node-v0.8.14/test/simple/test-fs-readfile-pipe.js b/node-v0.8.14/test/simple/test-fs-readfile-pipe.js new file mode 100644 index 0000000..8ca1651 --- /dev/null +++ b/node-v0.8.14/test/simple/test-fs-readfile-pipe.js @@ -0,0 +1,55 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); + +// simulate `cat readfile.js | node readfile.js` + +// TODO: Have some way to make this work on windows. +if (process.platform === 'win32') { + console.error('No /dev/stdin on windows. Skipping test.'); + process.exit(); +} + +var fs = require('fs'); + +var dataExpected = fs.readFileSync(__filename, 'utf8'); + +if (process.argv[2] === 'child') { + fs.readFile('/dev/stdin', function(er, data) { + if (er) throw er; + process.stdout.write(data); + }); + return; +} + +var exec = require('child_process').exec; +var f = JSON.stringify(__filename); +var node = JSON.stringify(process.execPath); +var cmd = 'cat ' + f + ' | ' + node + ' ' + f + ' child'; +exec(cmd, function(err, stdout, stderr) { + if (err) console.error(err); + assert(!err, 'it exits normally'); + assert(stdout === dataExpected, 'it reads the file and outputs it'); + assert(stderr === '', 'it does not write to stderr'); + console.log('ok'); +}); diff --git a/node-v0.8.14/test/simple/test-fs-readfile-unlink.js b/node-v0.8.14/test/simple/test-fs-readfile-unlink.js new file mode 100644 index 0000000..0bb4a67 --- /dev/null +++ b/node-v0.8.14/test/simple/test-fs-readfile-unlink.js @@ -0,0 +1,48 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var assert = require('assert'), + common = require('../common'), + fs = require('fs'), + path = require('path'), + dirName = path.resolve(common.fixturesDir, 'test-readfile-unlink'), + fileName = path.resolve(dirName, 'test.bin'); + +var buf = new Buffer(512 * 1024); +buf.fill(42); + +try { + fs.mkdirSync(dirName); +} catch (e) { + // Ignore if the directory already exists. + if (e.code != 'EEXIST') throw e; +} + +fs.writeFileSync(fileName, buf); + +fs.readFile(fileName, function(err, data) { + assert.ifError(err); + assert(data.length == buf.length); + assert.strictEqual(buf[0], 42); + + fs.unlinkSync(fileName); + fs.rmdirSync(dirName); +}); diff --git a/node-v0.8.14/test/simple/test-fs-readfile-zero-byte-liar.js b/node-v0.8.14/test/simple/test-fs-readfile-zero-byte-liar.js new file mode 100644 index 0000000..60f4122 --- /dev/null +++ b/node-v0.8.14/test/simple/test-fs-readfile-zero-byte-liar.js @@ -0,0 +1,58 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var fs = require('fs'); + +var dataExpected = fs.readFileSync(__filename, 'utf8'); + +// sometimes stat returns size=0, but it's a lie. +fs._fstat = fs.fstat; +fs._fstatSync = fs.fstatSync; + +fs.fstat = function(fd, cb) { + fs._fstat(fd, function(er, st) { + if (er) return cb(er); + st.size = 0; + return cb(er, st); + }); +}; + +fs.fstatSync = function(fd) { + var st = fs._fstatSync; + st.size = 0; + return st; +}; + +var d = fs.readFileSync(__filename, 'utf8'); +assert.equal(d, dataExpected); + +var called = false; +fs.readFile(__filename, 'utf8', function (er, d) { + assert.equal(d, dataExpected); + called = true; +}); + +process.on('exit', function() { + assert(called); + console.log("ok"); +}); diff --git a/node-v0.8.14/test/simple/test-fs-realpath.js b/node-v0.8.14/test/simple/test-fs-realpath.js new file mode 100644 index 0000000..2f126ea --- /dev/null +++ b/node-v0.8.14/test/simple/test-fs-realpath.js @@ -0,0 +1,594 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var fs = require('fs'); +var path = require('path'); +var exec = require('child_process').exec; +var async_completed = 0, async_expected = 0, unlink = []; +var isWindows = process.platform === 'win32'; +var skipSymlinks = false; + +var root = '/'; +if (isWindows) { + // something like "C:\\" + root = process.cwd().substr(0, 3); + + // On Windows, creating symlinks requires admin privileges. + // We'll only try to run symlink test if we have enough privileges. + try { + exec('whoami /priv', function(err, o) { + if (err || o.indexOf('SeCreateSymbolicLinkPrivilege') == -1) { + skipSymlinks = true; + } + runTest(); + }); + } catch (er) { + // better safe than sorry + skipSymlinks = true; + process.nextTick(runTest); + } +} else { + process.nextTick(runTest); +} + + +function tmp(p) { + return path.join(common.tmpDir, p); +} + +var fixturesAbsDir = common.fixturesDir; +var tmpAbsDir = common.tmpDir; + +console.error("absolutes\n%s\n%s", fixturesAbsDir, tmpAbsDir); + +function asynctest(testBlock, args, callback, assertBlock) { + async_expected++; + testBlock.apply(testBlock, args.concat(function(err) { + var ignoreError = false; + if (assertBlock) { + try { + ignoreError = assertBlock.apply(assertBlock, arguments); + } + catch (e) { + err = e; + } + } + async_completed++; + callback(ignoreError ? null : err); + })); +} + +// sub-tests: +function test_simple_error_callback(cb) { + var ncalls = 0; + + fs.realpath('/this/path/does/not/exist', function(err, s) { + assert(err); + assert(!s); + ncalls++; + cb(); + }); + + process.on('exit', function() { + assert.equal(ncalls, 1); + }); +} + +function test_simple_relative_symlink(callback) { + console.log('test_simple_relative_symlink'); + if (skipSymlinks) { + console.log('skipping symlink test (no privs)'); + return runNextTest(); + } + var entry = common.tmpDir + '/symlink', + expected = common.tmpDir + '/cycles/root.js'; + [ + [entry, '../tmp/cycles/root.js'] + ].forEach(function(t) { + try {fs.unlinkSync(t[0]);}catch (e) {} + console.log('fs.symlinkSync(%j, %j, %j)', t[1], t[0], 'file'); + fs.symlinkSync(t[1], t[0], 'file'); + unlink.push(t[0]); + }); + var result = fs.realpathSync(entry); + assert.equal(result, path.resolve(expected), + 'got ' + common.inspect(result) + ' expected ' + + common.inspect(expected)); + asynctest(fs.realpath, [entry], callback, function(err, result) { + assert.equal(result, path.resolve(expected), + 'got ' + + common.inspect(result) + + ' expected ' + + common.inspect(expected)); + }); +} + +function test_simple_absolute_symlink(callback) { + console.log('test_simple_absolute_symlink'); + + // this one should still run, even if skipSymlinks is set, + // because it uses a junction. + var type = skipSymlinks ? 'junction' : 'dir'; + + console.log('using type=%s', type); + + var entry = tmpAbsDir + '/symlink', + expected = fixturesAbsDir + '/nested-index/one'; + [ + [entry, expected] + ].forEach(function(t) { + try {fs.unlinkSync(t[0]);} catch (e) {} + console.error('fs.symlinkSync(%j, %j, %j)', t[1], t[0], type); + fs.symlinkSync(t[1], t[0], type); + unlink.push(t[0]); + }); + var result = fs.realpathSync(entry); + assert.equal(result, path.resolve(expected), + 'got ' + + common.inspect(result) + + ' expected ' + + common.inspect(expected)); + asynctest(fs.realpath, [entry], callback, function(err, result) { + assert.equal(result, path.resolve(expected), + 'got ' + + common.inspect(result) + + ' expected ' + + common.inspect(expected)); + }); +} + +function test_deep_relative_file_symlink(callback) { + console.log('test_deep_relative_file_symlink'); + if (skipSymlinks) { + console.log('skipping symlink test (no privs)'); + return runNextTest(); + } + + var expected = path.join(common.fixturesDir, 'cycles', 'root.js'); + var linkData1 = '../../cycles/root.js'; + var linkPath1 = path.join(common.fixturesDir, + 'nested-index', 'one', 'symlink1.js'); + try {fs.unlinkSync(linkPath1);} catch (e) {} + fs.symlinkSync(linkData1, linkPath1, 'file'); + + var linkData2 = '../one/symlink1.js'; + var entry = path.join(common.fixturesDir, + 'nested-index', 'two', 'symlink1-b.js'); + try {fs.unlinkSync(entry);} catch (e) {} + fs.symlinkSync(linkData2, entry, 'file'); + unlink.push(linkPath1); + unlink.push(entry); + + assert.equal(fs.realpathSync(entry), path.resolve(expected)); + asynctest(fs.realpath, [entry], callback, function(err, result) { + assert.equal(result, path.resolve(expected), + 'got ' + + common.inspect(result) + + ' expected ' + + common.inspect(path.resolve(expected))); + }); +} + +function test_deep_relative_dir_symlink(callback) { + console.log('test_deep_relative_dir_symlink'); + if (skipSymlinks) { + console.log('skipping symlink test (no privs)'); + return runNextTest(); + } + var expected = path.join(common.fixturesDir, 'cycles', 'folder'); + var linkData1b = '../../cycles/folder'; + var linkPath1b = path.join(common.fixturesDir, + 'nested-index', 'one', 'symlink1-dir'); + try {fs.unlinkSync(linkPath1b);} catch (e) {} + fs.symlinkSync(linkData1b, linkPath1b, 'dir'); + + var linkData2b = '../one/symlink1-dir'; + var entry = path.join(common.fixturesDir, + 'nested-index', 'two', 'symlink12-dir'); + try {fs.unlinkSync(entry);} catch (e) {} + fs.symlinkSync(linkData2b, entry, 'dir'); + unlink.push(linkPath1b); + unlink.push(entry); + + assert.equal(fs.realpathSync(entry), path.resolve(expected)); + + asynctest(fs.realpath, [entry], callback, function(err, result) { + assert.equal(result, path.resolve(expected), + 'got ' + + common.inspect(result) + + ' expected ' + + common.inspect(path.resolve(expected))); + }); +} + +function test_cyclic_link_protection(callback) { + console.log('test_cyclic_link_protection'); + if (skipSymlinks) { + console.log('skipping symlink test (no privs)'); + return runNextTest(); + } + var entry = common.tmpDir + '/cycles/realpath-3a'; + [ + [entry, '../cycles/realpath-3b'], + [common.tmpDir + '/cycles/realpath-3b', '../cycles/realpath-3c'], + [common.tmpDir + '/cycles/realpath-3c', '../cycles/realpath-3a'] + ].forEach(function(t) { + try {fs.unlinkSync(t[0]);} catch (e) {} + fs.symlinkSync(t[1], t[0], 'dir'); + unlink.push(t[0]); + }); + assert.throws(function() { fs.realpathSync(entry); }); + asynctest(fs.realpath, [entry], callback, function(err, result) { + assert.ok(err && true); + return true; + }); +} + +function test_cyclic_link_overprotection(callback) { + console.log('test_cyclic_link_overprotection'); + if (skipSymlinks) { + console.log('skipping symlink test (no privs)'); + return runNextTest(); + } + var cycles = common.tmpDir + '/cycles'; + var expected = fs.realpathSync(cycles); + var folder = cycles + '/folder'; + var link = folder + '/cycles'; + var testPath = cycles; + for (var i = 0; i < 10; i++) testPath += '/folder/cycles'; + try {fs.unlinkSync(link)} catch (ex) {} + fs.symlinkSync(cycles, link, 'dir'); + unlink.push(link); + assert.equal(fs.realpathSync(testPath), path.resolve(expected)); + asynctest(fs.realpath, [testPath], callback, function(er, res) { + assert.equal(res, path.resolve(expected)); + }); +} + +function test_relative_input_cwd(callback) { + console.log('test_relative_input_cwd'); + + // we need to get the relative path to the tmp dir from cwd. + // When the test runner is running it, that will be .../node/test + // but it's more common to run `./node test/.../`, so detect it here. + var entrydir = process.cwd(); + var entry = common.tmpDir.substr(entrydir.length + 1) + '/cycles/realpath-3a'; + var expected = common.tmpDir + '/cycles/root.js'; + [ + [entry, '../cycles/realpath-3b'], + [common.tmpDir + '/cycles/realpath-3b', '../cycles/realpath-3c'], + [common.tmpDir + '/cycles/realpath-3c', 'root.js'] + ].forEach(function(t) { + var fn = t[0]; + console.error('fn=%j', fn); + try {fs.unlinkSync(fn);} catch (e) {} + var b = path.basename(t[1]); + var type = (b === 'root.js' ? 'file' : 'dir'); + console.log('fs.symlinkSync(%j, %j, %j)', t[1], fn, type); + fs.symlinkSync(t[1], fn, 'file'); + unlink.push(fn); + }); + + var origcwd = process.cwd(); + process.chdir(entrydir); + assert.equal(fs.realpathSync(entry), path.resolve(expected)); + asynctest(fs.realpath, [entry], callback, function(err, result) { + process.chdir(origcwd); + assert.equal(result, path.resolve(expected), + 'got ' + + common.inspect(result) + + ' expected ' + + common.inspect(path.resolve(expected))); + return true; + }); +} + +function test_deep_symlink_mix(callback) { + console.log('test_deep_symlink_mix'); + if (isWindows) { + // This one is a mix of files and directories, and it's quite tricky + // to get the file/dir links sorted out correctly. + console.log('skipping symlink test (no way to work on windows)'); + return runNextTest(); + } + + // todo: check to see that common.fixturesDir is not rooted in the + // same directory as our test symlink. + /* + /tmp/node-test-realpath-f1 -> ../tmp/node-test-realpath-d1/foo + /tmp/node-test-realpath-d1 -> ../node-test-realpath-d2 + /tmp/node-test-realpath-d2/foo -> ../node-test-realpath-f2 + /tmp/node-test-realpath-f2 + -> /node/test/fixtures/nested-index/one/realpath-c + /node/test/fixtures/nested-index/one/realpath-c + -> /node/test/fixtures/nested-index/two/realpath-c + /node/test/fixtures/nested-index/two/realpath-c -> ../../cycles/root.js + /node/test/fixtures/cycles/root.js (hard) + */ + var entry = tmp('node-test-realpath-f1'); + try { fs.unlinkSync(tmp('node-test-realpath-d2/foo')); } catch (e) {} + try { fs.rmdirSync(tmp('node-test-realpath-d2')); } catch (e) {} + fs.mkdirSync(tmp('node-test-realpath-d2'), 0700); + try { + [ + [entry, '../tmp/node-test-realpath-d1/foo'], + [tmp('node-test-realpath-d1'), '../tmp/node-test-realpath-d2'], + [tmp('node-test-realpath-d2/foo'), '../node-test-realpath-f2'], + [tmp('node-test-realpath-f2'), fixturesAbsDir + + '/nested-index/one/realpath-c'], + [fixturesAbsDir + '/nested-index/one/realpath-c', fixturesAbsDir + + '/nested-index/two/realpath-c'], + [fixturesAbsDir + '/nested-index/two/realpath-c', + '../../../tmp/cycles/root.js'] + ].forEach(function(t) { + //common.debug('setting up '+t[0]+' -> '+t[1]); + try { fs.unlinkSync(t[0]); } catch (e) {} + fs.symlinkSync(t[1], t[0]); + unlink.push(t[0]); + }); + } finally { + unlink.push(tmp('node-test-realpath-d2')); + } + var expected = tmpAbsDir + '/cycles/root.js'; + assert.equal(fs.realpathSync(entry), path.resolve(expected)); + asynctest(fs.realpath, [entry], callback, function(err, result) { + assert.equal(result, path.resolve(expected), + 'got ' + + common.inspect(result) + + ' expected ' + + common.inspect(path.resolve(expected))); + return true; + }); +} + +function test_non_symlinks(callback) { + console.log('test_non_symlinks'); + var entrydir = path.dirname(tmpAbsDir); + var entry = tmpAbsDir.substr(entrydir.length + 1) + '/cycles/root.js'; + var expected = tmpAbsDir + '/cycles/root.js'; + var origcwd = process.cwd(); + process.chdir(entrydir); + assert.equal(fs.realpathSync(entry), path.resolve(expected)); + asynctest(fs.realpath, [entry], callback, function(err, result) { + process.chdir(origcwd); + assert.equal(result, path.resolve(expected), + 'got ' + + common.inspect(result) + + ' expected ' + + common.inspect(path.resolve(expected))); + return true; + }); +} + +var upone = path.join(process.cwd(), '..'); +function test_escape_cwd(cb) { + console.log('test_escape_cwd'); + asynctest(fs.realpath, ['..'], cb, function(er, uponeActual) { + assert.equal(upone, uponeActual, + 'realpath("..") expected: ' + path.resolve(upone) + ' actual:' + uponeActual); + }); +} +var uponeActual = fs.realpathSync('..'); +assert.equal(upone, uponeActual, + 'realpathSync("..") expected: ' + path.resolve(upone) + ' actual:' + uponeActual); + + +// going up with .. multiple times +// . +// `-- a/ +// |-- b/ +// | `-- e -> .. +// `-- d -> .. +// realpath(a/b/e/d/a/b/e/d/a) ==> a +function test_up_multiple(cb) { + console.error('test_up_multiple'); + if (skipSymlinks) { + console.log('skipping symlink test (no privs)'); + return runNextTest(); + } + fs.mkdirSync(tmp('a'), 0755); + fs.mkdirSync(tmp('a/b'), 0755); + fs.symlinkSync('..', tmp('a/d'), 'dir'); + unlink.push(tmp('a/d')); + fs.symlinkSync('..', tmp('a/b/e'), 'dir'); + unlink.push(tmp('a/b/e')); + + var abedabed = tmp('abedabed'.split('').join('/')); + var abedabed_real = tmp(''); + + var abedabeda = tmp('abedabeda'.split('').join('/')); + var abedabeda_real = tmp('a'); + + assert.equal(fs.realpathSync(abedabeda), abedabeda_real); + assert.equal(fs.realpathSync(abedabed), abedabed_real); + fs.realpath(abedabeda, function (er, real) { + if (er) throw er; + assert.equal(abedabeda_real, real); + fs.realpath(abedabed, function (er, real) { + if (er) throw er; + assert.equal(abedabed_real, real); + cb(); + }); + }); +} + + +// absolute symlinks with children. +// . +// `-- a/ +// |-- b/ +// | `-- c/ +// | `-- x.txt +// `-- link -> /tmp/node-test-realpath-abs-kids/a/b/ +// realpath(root+'/a/link/c/x.txt') ==> root+'/a/b/c/x.txt' +function test_abs_with_kids(cb) { + console.log('test_abs_with_kids'); + + // this one should still run, even if skipSymlinks is set, + // because it uses a junction. + var type = skipSymlinks ? 'junction' : 'dir'; + + console.log('using type=%s', type); + + var root = tmpAbsDir + '/node-test-realpath-abs-kids'; + function cleanup() { + ['/a/b/c/x.txt', + '/a/link' + ].forEach(function(file) { + try {fs.unlinkSync(root + file)} catch (ex) {} + }); + ['/a/b/c', + '/a/b', + '/a', + '' + ].forEach(function(folder) { + try {fs.rmdirSync(root + folder)} catch (ex) {} + }); + } + function setup() { + cleanup(); + ['', + '/a', + '/a/b', + '/a/b/c' + ].forEach(function(folder) { + console.log('mkdir ' + root + folder); + fs.mkdirSync(root + folder, 0700); + }); + fs.writeFileSync(root + '/a/b/c/x.txt', 'foo'); + fs.symlinkSync(root + '/a/b', root + '/a/link', type); + } + setup(); + var linkPath = root + '/a/link/c/x.txt'; + var expectPath = root + '/a/b/c/x.txt'; + var actual = fs.realpathSync(linkPath); + // console.log({link:linkPath,expect:expectPath,actual:actual},'sync'); + assert.equal(actual, path.resolve(expectPath)); + asynctest(fs.realpath, [linkPath], cb, function(er, actual) { + // console.log({link:linkPath,expect:expectPath,actual:actual},'async'); + assert.equal(actual, path.resolve(expectPath)); + cleanup(); + }); +} + +function test_lying_cache_liar(cb) { + var n = 2; + + // this should not require *any* stat calls, since everything + // checked by realpath will be found in the cache. + console.log('test_lying_cache_liar'); + var cache = { '/foo/bar/baz/bluff' : '/foo/bar/bluff', + '/1/2/3/4/5/6/7' : '/1', + '/a' : '/a', + '/a/b' : '/a/b', + '/a/b/c' : '/a/b', + '/a/b/d' : '/a/b/d' }; + if (isWindows) { + var wc = {}; + Object.keys(cache).forEach(function(k) { + wc[ path.resolve(k) ] = path.resolve(cache[k]); + }); + cache = wc; + } + + var bluff = path.resolve('/foo/bar/baz/bluff'); + var rps = fs.realpathSync(bluff, cache); + assert.equal(cache[bluff], rps); + var nums = path.resolve('/1/2/3/4/5/6/7'); + var called = false; // no sync cb calling! + fs.realpath(nums, cache, function(er, rp) { + called = true; + assert.equal(cache[nums], rp); + if (--n === 0) cb(); + }); + assert(called === false); + + var test = path.resolve('/a/b/c/d'), + expect = path.resolve('/a/b/d'); + var actual = fs.realpathSync(test, cache); + assert.equal(expect, actual); + fs.realpath(test, cache, function(er, actual) { + assert.equal(expect, actual); + if (--n === 0) cb(); + }); +} + +// ---------------------------------------------------------------------------- + +var tests = [ + test_simple_error_callback, + test_simple_relative_symlink, + test_simple_absolute_symlink, + test_deep_relative_file_symlink, + test_deep_relative_dir_symlink, + test_cyclic_link_protection, + test_cyclic_link_overprotection, + test_relative_input_cwd, + test_deep_symlink_mix, + test_non_symlinks, + test_escape_cwd, + test_abs_with_kids, + test_lying_cache_liar, + test_up_multiple +]; +var numtests = tests.length; +var testsRun = 0; +function runNextTest(err) { + if (err) throw err; + var test = tests.shift(); + if (!test) { + return console.log(numtests + + ' subtests completed OK for fs.realpath'); + } + testsRun++; + test(runNextTest); +} + + +assert.equal(root, fs.realpathSync('/')); +fs.realpath('/', function(err, result) { + assert.equal(null, err); + assert.equal(root, result); +}); + + +function runTest() { + var tmpDirs = ['cycles', 'cycles/folder']; + tmpDirs.forEach(function(t) { + t = tmp(t); + var s; + try { s = fs.statSync(t); } catch (ex) {} + if (s) return; + fs.mkdirSync(t, 0700); + }); + fs.writeFileSync(tmp('cycles/root.js'), "console.error('roooot!');"); + console.error('start tests'); + runNextTest(); +} + + +process.on('exit', function() { + assert.equal(numtests, testsRun); + unlink.forEach(function(path) { try {fs.unlinkSync(path);} catch (e) {} }); + assert.equal(async_completed, async_expected); +}); diff --git a/node-v0.8.14/test/simple/test-fs-sir-writes-alot.js b/node-v0.8.14/test/simple/test-fs-sir-writes-alot.js new file mode 100644 index 0000000..e16f56b --- /dev/null +++ b/node-v0.8.14/test/simple/test-fs-sir-writes-alot.js @@ -0,0 +1,71 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var fs = require('fs'); +var assert = require('assert'); +var join = require('path').join; + +var filename = join(common.tmpDir, 'out.txt'); + +try { + fs.unlinkSync(filename); +} catch (e) { + // might not exist, that's okay. +} + +var fd = fs.openSync(filename, 'w'); + +var line = 'aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n'; + +var N = 10240, complete = 0; +for (var i = 0; i < N; i++) { + // Create a new buffer for each write. Before the write is actually + // executed by the thread pool, the buffer will be collected. + var buffer = new Buffer(line); + fs.write(fd, buffer, 0, buffer.length, null, function(er, written) { + complete++; + if (complete === N) { + fs.closeSync(fd); + var s = fs.createReadStream(filename); + s.on('data', testBuffer); + } + }); +} + +var bytesChecked = 0; + +function testBuffer(b) { + for (var i = 0; i < b.length; i++) { + bytesChecked++; + if (b[i] !== 'a'.charCodeAt(0) && b[i] !== '\n'.charCodeAt(0)) { + throw new Error('invalid char ' + i + ',' + b[i]); + } + } +} + +process.on('exit', function() { + // Probably some of the writes are going to overlap, so we can't assume + // that we get (N * line.length). Let's just make sure we've checked a + // few... + assert.ok(bytesChecked > 1000); +}); + diff --git a/node-v0.8.14/test/simple/test-fs-stat.js b/node-v0.8.14/test/simple/test-fs-stat.js new file mode 100644 index 0000000..90b0ba5 --- /dev/null +++ b/node-v0.8.14/test/simple/test-fs-stat.js @@ -0,0 +1,123 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var fs = require('fs'); +var got_error = false; +var success_count = 0; + +fs.stat('.', function(err, stats) { + if (err) { + got_error = true; + } else { + console.dir(stats); + assert.ok(stats.mtime instanceof Date); + success_count++; + } + assert(this === global); +}); + +fs.lstat('.', function(err, stats) { + if (err) { + got_error = true; + } else { + console.dir(stats); + assert.ok(stats.mtime instanceof Date); + success_count++; + } + assert(this === global); +}); + +// fstat +fs.open('.', 'r', undefined, function(err, fd) { + assert.ok(!err); + assert.ok(fd); + + fs.fstat(fd, function(err, stats) { + if (err) { + got_error = true; + } else { + console.dir(stats); + assert.ok(stats.mtime instanceof Date); + success_count++; + fs.close(fd); + } + assert(this === global); + }); + + assert(this === global); +}); + +// fstatSync +fs.open('.', 'r', undefined, function(err, fd) { + var stats; + try { + stats = fs.fstatSync(fd); + } catch (err) { + got_error = true; + } + if (stats) { + console.dir(stats); + assert.ok(stats.mtime instanceof Date); + success_count++; + } + fs.close(fd); +}); + +console.log('stating: ' + __filename); +fs.stat(__filename, function(err, s) { + if (err) { + got_error = true; + } else { + console.dir(s); + success_count++; + + console.log('isDirectory: ' + JSON.stringify(s.isDirectory())); + assert.equal(false, s.isDirectory()); + + console.log('isFile: ' + JSON.stringify(s.isFile())); + assert.equal(true, s.isFile()); + + console.log('isSocket: ' + JSON.stringify(s.isSocket())); + assert.equal(false, s.isSocket()); + + console.log('isBlockDevice: ' + JSON.stringify(s.isBlockDevice())); + assert.equal(false, s.isBlockDevice()); + + console.log('isCharacterDevice: ' + JSON.stringify(s.isCharacterDevice())); + assert.equal(false, s.isCharacterDevice()); + + console.log('isFIFO: ' + JSON.stringify(s.isFIFO())); + assert.equal(false, s.isFIFO()); + + console.log('isSymbolicLink: ' + JSON.stringify(s.isSymbolicLink())); + assert.equal(false, s.isSymbolicLink()); + + assert.ok(s.mtime instanceof Date); + } +}); + +process.on('exit', function() { + assert.equal(5, success_count); + assert.equal(false, got_error); +}); + diff --git a/node-v0.8.14/test/simple/test-fs-stream-double-close.js b/node-v0.8.14/test/simple/test-fs-stream-double-close.js new file mode 100644 index 0000000..89386b6 --- /dev/null +++ b/node-v0.8.14/test/simple/test-fs-stream-double-close.js @@ -0,0 +1,61 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var fs = require('fs'); + +test1(fs.createReadStream(__filename)); +test2(fs.createReadStream(__filename)); +test3(fs.createReadStream(__filename)); + +test1(fs.createWriteStream(common.tmpDir + '/dummy1')); +test2(fs.createWriteStream(common.tmpDir + '/dummy2')); +test3(fs.createWriteStream(common.tmpDir + '/dummy3')); + +function test1(stream) { + stream.destroy(); + stream.destroy(); +} + +function test2(stream) { + stream.destroy(); + stream.on('open', function(fd) { + stream.destroy(); + open_cb_called++; + }); + process.on('exit', function() { + assert.equal(open_cb_called, 1); + }); + var open_cb_called = 0; +} + +function test3(stream) { + stream.on('open', function(fd) { + stream.destroy(); + stream.destroy(); + open_cb_called++; + }); + process.on('exit', function() { + assert.equal(open_cb_called, 1); + }); + var open_cb_called = 0; +} diff --git a/node-v0.8.14/test/simple/test-fs-symlink-dir-junction.js b/node-v0.8.14/test/simple/test-fs-symlink-dir-junction.js new file mode 100644 index 0000000..c675b92 --- /dev/null +++ b/node-v0.8.14/test/simple/test-fs-symlink-dir-junction.js @@ -0,0 +1,68 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var path = require('path'); +var fs = require('fs'); +var completed = 0; +var expected_tests = 4; + +// test creating and reading symbolic link +var linkData = path.join(common.fixturesDir, 'cycles/'); +var linkPath = path.join(common.tmpDir, 'cycles_link'); + +// Delete previously created link +try { + fs.unlinkSync(linkPath); +} catch (e) {} + +console.log('linkData: ' + linkData); +console.log('linkPath: ' + linkPath); + +fs.symlink(linkData, linkPath, 'junction', function(err) { + if (err) throw err; + completed++; + + fs.lstat(linkPath, function(err, stats) { + if (err) throw err; + assert.ok(stats.isSymbolicLink()); + completed++; + + fs.readlink(linkPath, function(err, destination) { + if (err) throw err; + assert.equal(destination, linkData); + completed++; + + fs.unlink(linkPath, function(err) { + if (err) throw err; + assert(!fs.existsSync(linkPath)); + assert(fs.existsSync(linkData)); + completed++; + }); + }); + }); +}); + +process.on('exit', function() { + assert.equal(completed, expected_tests); +}); + diff --git a/node-v0.8.14/test/simple/test-fs-symlink.js b/node-v0.8.14/test/simple/test-fs-symlink.js new file mode 100644 index 0000000..6b23b1e --- /dev/null +++ b/node-v0.8.14/test/simple/test-fs-symlink.js @@ -0,0 +1,92 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var path = require('path'); +var fs = require('fs'); +var exec = require('child_process').exec; +var completed = 0; +var expected_tests = 2; + +var is_windows = process.platform === 'win32'; + +var runtest = function(skip_symlinks) { + if (!skip_symlinks) { + // test creating and reading symbolic link + var linkData = path.join(common.fixturesDir, '/cycles/root.js'); + var linkPath = path.join(common.tmpDir, 'symlink1.js'); + + // Delete previously created link + try { + fs.unlinkSync(linkPath); + } catch (e) {} + + fs.symlink(linkData, linkPath, function(err) { + if (err) throw err; + console.log('symlink done'); + // todo: fs.lstat? + fs.readlink(linkPath, function(err, destination) { + if (err) throw err; + assert.equal(destination, linkData); + completed++; + }); + }); + } + + // test creating and reading hard link + var srcPath = path.join(common.fixturesDir, 'cycles', 'root.js'); + var dstPath = path.join(common.tmpDir, 'link1.js'); + + // Delete previously created link + try { + fs.unlinkSync(dstPath); + } catch (e) {} + + fs.link(srcPath, dstPath, function(err) { + if (err) throw err; + console.log('hard link done'); + var srcContent = fs.readFileSync(srcPath, 'utf8'); + var dstContent = fs.readFileSync(dstPath, 'utf8'); + assert.equal(srcContent, dstContent); + completed++; + }); +}; + +if (is_windows) { + // On Windows, creating symlinks requires admin privileges. + // We'll only try to run symlink test if we have enough privileges. + exec('whoami /priv', function(err, o) { + if (err || o.indexOf('SeCreateSymbolicLinkPrivilege') == -1) { + expected_tests = 1; + runtest(true); + } else { + runtest(false); + } + }); +} else { + runtest(false); +} + +process.on('exit', function() { + assert.equal(completed, expected_tests); +}); + diff --git a/node-v0.8.14/test/simple/test-fs-sync-fd-leak.js b/node-v0.8.14/test/simple/test-fs-sync-fd-leak.js new file mode 100644 index 0000000..fe932c7 --- /dev/null +++ b/node-v0.8.14/test/simple/test-fs-sync-fd-leak.js @@ -0,0 +1,69 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var fs = require('fs'); + +// ensure that (read|write|append)FileSync() closes the file descriptor +fs.openSync = function() { + return 42; +}; +fs.closeSync = function(fd) { + assert.equal(fd, 42); + close_called++; +}; +fs.readSync = function() { + throw new Error('BAM'); +}; +fs.writeSync = function() { + throw new Error('BAM'); +}; + +fs.fstatSync = function() { + throw new Error('BAM'); +}; + +ensureThrows(function() { + fs.readFileSync('dummy'); +}); +ensureThrows(function() { + fs.writeFileSync('dummy', 'xxx'); +}); +ensureThrows(function() { + fs.appendFileSync('dummy', 'xxx'); +}); + +var close_called = 0; +function ensureThrows(cb) { + var got_exception = false; + + close_called = 0; + try { + cb(); + } catch (e) { + assert.equal(e.message, 'BAM'); + got_exception = true; + } + + assert.equal(close_called, 1); + assert.equal(got_exception, true); +} diff --git a/node-v0.8.14/test/simple/test-fs-utimes.js b/node-v0.8.14/test/simple/test-fs-utimes.js new file mode 100644 index 0000000..eae8023 --- /dev/null +++ b/node-v0.8.14/test/simple/test-fs-utimes.js @@ -0,0 +1,160 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var util = require('util'); +var fs = require('fs'); + +var is_windows = process.platform === 'win32'; + +var tests_ok = 0; +var tests_run = 0; + +function stat_resource(resource) { + if (typeof resource == 'string') { + return fs.statSync(resource); + } else { + // ensure mtime has been written to disk + fs.fsyncSync(resource); + return fs.fstatSync(resource); + } +} + +function check_mtime(resource, mtime) { + var mtime = fs._toUnixTimestamp(mtime); + var stats = stat_resource(resource); + var real_mtime = fs._toUnixTimestamp(stats.mtime); + // check up to single-second precision + // sub-second precision is OS and fs dependant + return Math.floor(mtime) == Math.floor(real_mtime); +} + +function expect_errno(syscall, resource, err, errno) { + if (err && (err.code === errno || err.code === 'ENOSYS')) { + tests_ok++; + } else { + console.log('FAILED:', arguments.callee.name, util.inspect(arguments)); + } +} + +function expect_ok(syscall, resource, err, atime, mtime) { + if (!err && check_mtime(resource, mtime) || + err && err.code === 'ENOSYS') { + tests_ok++; + } else { + console.log('FAILED:', arguments.callee.name, util.inspect(arguments)); + } +} + +// the tests assume that __filename belongs to the user running the tests +// this should be a fairly safe assumption; testing against a temp file +// would be even better though (node doesn't have such functionality yet) +function runTest(atime, mtime, callback) { + + var fd, err; + // + // test synchronized code paths, these functions throw on failure + // + function syncTests() { + fs.utimesSync(__filename, atime, mtime); + expect_ok('utimesSync', __filename, undefined, atime, mtime); + tests_run++; + + // some systems don't have futimes + // if there's an error, it should be ENOSYS + try { + tests_run++; + fs.futimesSync(fd, atime, mtime); + expect_ok('futimesSync', fd, undefined, atime, mtime); + } catch (ex) { + expect_errno('futimesSync', fd, ex, 'ENOSYS'); + } + + var err; + err = undefined; + try { + fs.utimesSync('foobarbaz', atime, mtime); + } catch (ex) { + err = ex; + } + expect_errno('utimesSync', 'foobarbaz', err, 'ENOENT'); + tests_run++; + + err = undefined; + try { + fs.futimesSync(-1, atime, mtime); + } catch (ex) { + err = ex; + } + expect_errno('futimesSync', -1, err, 'EBADF'); + tests_run++; + } + + // + // test async code paths + // + fs.utimes(__filename, atime, mtime, function(err) { + expect_ok('utimes', __filename, err, atime, mtime); + + fs.utimes('foobarbaz', atime, mtime, function(err) { + expect_errno('utimes', 'foobarbaz', err, 'ENOENT'); + + // don't close this fd + if (is_windows) { + fd = fs.openSync(__filename, 'r+'); + } else { + fd = fs.openSync(__filename, 'r'); + } + + fs.futimes(fd, atime, mtime, function(err) { + expect_ok('futimes', fd, err, atime, mtime); + + fs.futimes(-1, atime, mtime, function(err) { + expect_errno('futimes', -1, err, 'EBADF'); + syncTests(); + callback(); + }); + tests_run++; + }); + tests_run++; + }); + tests_run++; + }); + tests_run++; +} + +var stats = fs.statSync(__filename); + +runTest(new Date('1982-09-10 13:37'), new Date('1982-09-10 13:37'), function() { + runTest(new Date(), new Date(), function() { + runTest(123456.789, 123456.789, function() { + runTest(stats.mtime, stats.mtime, function() { + // done + }); + }); + }); +}); + +process.on('exit', function() { + console.log('Tests run / ok:', tests_run, '/', tests_ok); + assert.equal(tests_ok, tests_run); +}); diff --git a/node-v0.8.14/test/simple/test-fs-watch.js b/node-v0.8.14/test/simple/test-fs-watch.js new file mode 100644 index 0000000..2ad05f2 --- /dev/null +++ b/node-v0.8.14/test/simple/test-fs-watch.js @@ -0,0 +1,133 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var path = require('path'); +var fs = require('fs'); + +var expectFilePath = process.platform == 'win32' || process.platform == 'linux'; + +var watchSeenOne = 0; +var watchSeenTwo = 0; +var watchSeenThree = 0; + +var testDir = common.tmpDir; + +var filenameOne = 'watch.txt'; +var filepathOne = path.join(testDir, filenameOne); + +var filenameTwo = 'hasOwnProperty'; +var filepathTwo = filenameTwo; +var filepathTwoAbs = path.join(testDir, filenameTwo); + +var filenameThree = 'newfile.txt'; +var testsubdir = path.join(testDir, 'testsubdir'); +var filepathThree = path.join(testsubdir, filenameThree); + + +process.on('exit', function() { + assert.ok(watchSeenOne > 0); + assert.ok(watchSeenTwo > 0); + assert.ok(watchSeenThree > 0); +}); + +// Clean up stale files (if any) from previous run. +try { fs.unlinkSync(filepathOne); } catch (e) { } +try { fs.unlinkSync(filepathTwoAbs); } catch (e) { } +try { fs.unlinkSync(filepathThree); } catch (e) { } +try { fs.rmdirSync(testsubdir); } catch (e) { } + +fs.writeFileSync(filepathOne, 'hello'); + +assert.doesNotThrow( + function() { + var watcher = fs.watch(filepathOne) + watcher.on('change', function(event, filename) { + assert.equal('change', event); + if (expectFilePath) { + assert.equal('watch.txt', filename); + } else { + assert.equal(null, filename); + } + watcher.close(); + ++watchSeenOne; + }); + } +); + +setTimeout(function() { + fs.writeFileSync(filepathOne, 'world'); +}, 1000); + + +process.chdir(testDir); + +fs.writeFileSync(filepathTwoAbs, 'howdy'); + +assert.doesNotThrow( + function() { + var watcher = fs.watch(filepathTwo, function(event, filename) { + assert.equal('change', event); + if (expectFilePath) { + assert.equal('hasOwnProperty', filename); + } else { + assert.equal(null, filename); + } + watcher.close(); + ++watchSeenTwo; + }); + } +); + +setTimeout(function() { + fs.writeFileSync(filepathTwoAbs, 'pardner'); +}, 1000); + +try { fs.unlinkSync(filepathThree); } catch (e) {} +try { fs.mkdirSync(testsubdir, 0700); } catch (e) {} + +assert.doesNotThrow( + function() { + var watcher = fs.watch(testsubdir, function(event, filename) { + var renameEv = process.platform === 'sunos' ? 'change' : 'rename'; + assert.equal(renameEv, event); + if (expectFilePath) { + assert.equal('newfile.txt', filename); + } else { + assert.equal(null, filename); + } + watcher.close(); + ++watchSeenThree; + }); + } +); + +setTimeout(function() { + var fd = fs.openSync(filepathThree, 'w'); + fs.closeSync(fd); +}, 1000); + +// https://github.com/joyent/node/issues/2293 - non-persistent watcher should +// not block the event loop +fs.watch(__filename, {persistent: false}, function() { + assert(0); +}); diff --git a/node-v0.8.14/test/simple/test-fs-write-buffer.js b/node-v0.8.14/test/simple/test-fs-write-buffer.js new file mode 100644 index 0000000..46013bd --- /dev/null +++ b/node-v0.8.14/test/simple/test-fs-write-buffer.js @@ -0,0 +1,54 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var path = require('path'), + Buffer = require('buffer').Buffer, + fs = require('fs'), + filename = path.join(common.tmpDir, 'write.txt'), + expected = new Buffer('hello'), + openCalled = 0, + writeCalled = 0; + + +fs.open(filename, 'w', 0644, function(err, fd) { + openCalled++; + if (err) throw err; + + fs.write(fd, expected, 0, expected.length, null, function(err, written) { + writeCalled++; + if (err) throw err; + + assert.equal(expected.length, written); + fs.closeSync(fd); + + var found = fs.readFileSync(filename, 'utf8'); + assert.deepEqual(expected.toString(), found); + fs.unlinkSync(filename); + }); +}); + +process.on('exit', function() { + assert.equal(1, openCalled); + assert.equal(1, writeCalled); +}); + diff --git a/node-v0.8.14/test/simple/test-fs-write-file-buffer.js b/node-v0.8.14/test/simple/test-fs-write-file-buffer.js new file mode 100644 index 0000000..dfe7cf5 --- /dev/null +++ b/node-v0.8.14/test/simple/test-fs-write-file-buffer.js @@ -0,0 +1,51 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var join = require('path').join; +var util = require('util'); +var fs = require('fs'); + +var data = [ + '/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAUDBAQEAwUEBAQFBQUGBwwIBwcH', + 'Bw8LCwkMEQ8SEhEPERETFhwXExQaFRERGCEYGh0dHx8fExciJCIeJBweHx7/', + '2wBDAQUFBQcGBw4ICA4eFBEUHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4e', + 'Hh4eHh4eHh4eHh4eHh4eHh4eHh4eHh7/wAARCAAQABADASIAAhEBAxEB/8QA', + 'HwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUF', + 'BAQAAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkK', + 'FhcYGRolJicoKSo0NTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1', + 'dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXG', + 'x8jJytLT1NXW19jZ2uHi4+Tl5ufo6erx8vP09fb3+Pn6/8QAHwEAAwEBAQEB', + 'AQEBAQAAAAAAAAECAwQFBgcICQoL/8QAtREAAgECBAQDBAcFBAQAAQJ3AAEC', + 'AxEEBSExBhJBUQdhcRMiMoEIFEKRobHBCSMzUvAVYnLRChYkNOEl8RcYGRom', + 'JygpKjU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6goOE', + 'hYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU', + '1dbX2Nna4uPk5ebn6Onq8vP09fb3+Pn6/9oADAMBAAIRAxEAPwDhfBUFl/wk', + 'OmPqKJJZw3aiZFBw4z93jnkkc9u9dj8XLfSI/EBt7DTo7ea2Ox5YXVo5FC7g', + 'Tjq24nJPXNVtO0KATRvNHCIg3zoWJWQHqp+o4pun+EtJ0zxBq8mnLJa2d1L5', + '0NvnKRjJBUE5PAx3NYxxUY0pRtvYHSc5Ka2X9d7H/9k=']; + +data = data.join('\n'); + +var buf = new Buffer(data, 'base64'); +fs.writeFileSync(join(common.tmpDir, 'test.jpg'), buf); + +util.log('Done!'); diff --git a/node-v0.8.14/test/simple/test-fs-write-file.js b/node-v0.8.14/test/simple/test-fs-write-file.js new file mode 100644 index 0000000..7a487bb --- /dev/null +++ b/node-v0.8.14/test/simple/test-fs-write-file.js @@ -0,0 +1,101 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var fs = require('fs'); +var join = require('path').join; + +var filename = join(common.fixturesDir, 'test.txt'); + +common.error('writing to ' + filename); + +var n = 220; +var s = '南越国是前203年至前111年存在于岭南地区的一个国家,国都位于番禺,疆域包括今天中国的广东、' + + '广西两省区的大部份地区,福建省、湖南、贵州、云南的一小部份地区和越南的北部。' + + '南越国是秦朝灭亡后,由南海郡尉赵佗于前203年起兵兼并桂林郡和象郡后建立。' + + '前196年和前179年,南越国曾先后两次名义上臣属于西汉,成为西汉的“外臣”。前112年,' + + '南越国末代君主赵建德与西汉发生战争,被汉武帝于前111年所灭。南越国共存在93年,' + + '历经五代君主。南越国是岭南地区的第一个有记载的政权国家,采用封建制和郡县制并存的制度,' + + '它的建立保证了秦末乱世岭南地区社会秩序的稳定,有效的改善了岭南地区落后的政治、##济现状。\n'; + +var ncallbacks = 0; + +fs.writeFile(filename, s, function(e) { + if (e) throw e; + + ncallbacks++; + common.error('file written'); + + fs.readFile(filename, function(e, buffer) { + if (e) throw e; + common.error('file read'); + ncallbacks++; + assert.equal(Buffer.byteLength(s), buffer.length); + }); +}); + +// test that writeFile accepts buffers +var filename2 = join(common.fixturesDir, 'test2.txt'); +var buf = new Buffer(s, 'utf8'); +common.error('writing to ' + filename2); + +fs.writeFile(filename2, buf, function(e) { + if (e) throw e; + + ncallbacks++; + common.error('file2 written'); + + fs.readFile(filename2, function(e, buffer) { + if (e) throw e; + common.error('file2 read'); + ncallbacks++; + assert.equal(buf.length, buffer.length); + }); +}); + +// test that writeFile accepts numbers. +var filename3 = join(common.fixturesDir, 'test3.txt'); +common.error('writing to ' + filename3); + +fs.writeFile(filename3, n, function(e) { + if (e) throw e; + + ncallbacks++; + common.error('file3 written'); + + fs.readFile(filename3, function(e, buffer) { + if (e) throw e; + common.error('file3 read'); + ncallbacks++; + assert.equal(Buffer.byteLength('' + n), buffer.length); + }); +}); + + +process.on('exit', function() { + common.error('done'); + assert.equal(6, ncallbacks); + + fs.unlinkSync(filename); + fs.unlinkSync(filename2); + fs.unlinkSync(filename3); +}); diff --git a/node-v0.8.14/test/simple/test-fs-write-stream-change-open.js b/node-v0.8.14/test/simple/test-fs-write-stream-change-open.js new file mode 100644 index 0000000..d025e8d --- /dev/null +++ b/node-v0.8.14/test/simple/test-fs-write-stream-change-open.js @@ -0,0 +1,52 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); + +var path = require('path'), + fs = require('fs'); + +var file = path.join(common.tmpDir, 'write.txt'); + +var stream = fs.WriteStream(file), + _fs_close = fs.close, + _fs_open = fs.open; + +// change the fs.open with an identical function after the WriteStream +// has pushed it onto its internal action queue, but before it's +// returned. This simulates AOP-style extension of the fs lib. +fs.open = function() { + return _fs_open.apply(fs, arguments); +}; + +fs.close = function(fd) { + assert.ok(fd, 'fs.close must not be called with an undefined fd.'); + fs.close = _fs_close; + fs.open = _fs_open; +} + +stream.write('foo'); +stream.end(); + +process.on('exit', function() { + assert.equal(fs.open, _fs_open); +}); diff --git a/node-v0.8.14/test/simple/test-fs-write-stream-end.js b/node-v0.8.14/test/simple/test-fs-write-stream-end.js new file mode 100644 index 0000000..6c0f29c --- /dev/null +++ b/node-v0.8.14/test/simple/test-fs-write-stream-end.js @@ -0,0 +1,46 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); + +var path = require('path'), + fs = require('fs'); + +var writeEndOk = false; +(function() { + debugger; + var file = path.join(common.tmpDir, 'write-end-test.txt'); + var stream = fs.createWriteStream(file); + + stream.end('a\n', 'utf8', function() { + var content = fs.readFileSync(file, 'utf8'); + assert.equal(content, 'a\n'); + writeEndOk = true; + }); + +})(); + + +process.on('exit', function() { + assert.ok(writeEndOk); +}); + diff --git a/node-v0.8.14/test/simple/test-fs-write-stream.js b/node-v0.8.14/test/simple/test-fs-write-stream.js new file mode 100644 index 0000000..da75e26 --- /dev/null +++ b/node-v0.8.14/test/simple/test-fs-write-stream.js @@ -0,0 +1,50 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); + +var path = require('path'), + fs = require('fs'); + +var file = path.join(common.tmpDir, 'write.txt'); + +(function() { + var stream = fs.WriteStream(file), + _fs_close = fs.close; + + fs.close = function(fd) { + assert.ok(fd, 'fs.close must not be called without an undefined fd.'); + fs.close = _fs_close; + } + stream.destroy(); +})(); + +(function() { + var stream = fs.createWriteStream(file); + + stream.on('drain', function() { + assert.fail('\'drain\' event must not be emitted before ' + + 'stream.write() has been called at least once.'); + }); + stream.destroy(); +})(); + diff --git a/node-v0.8.14/test/simple/test-fs-write-sync.js b/node-v0.8.14/test/simple/test-fs-write-sync.js new file mode 100644 index 0000000..c3dbfe3 --- /dev/null +++ b/node-v0.8.14/test/simple/test-fs-write-sync.js @@ -0,0 +1,42 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var path = require('path'); +var fs = require('fs'); +var fn = path.join(common.tmpDir, 'write.txt'); + + +var foo = 'foo'; +var fd = fs.openSync(fn, 'w'); + +var written = fs.writeSync(fd, ''); +assert.strictEqual(0, written); + +fs.writeSync(fd, foo); + +var bar = 'bár'; +written = fs.writeSync(fd, new Buffer(bar), 0, Buffer.byteLength(bar)); +assert.ok(written > 3); +fs.closeSync(fd); + +assert.equal(fs.readFileSync(fn), 'foobár'); diff --git a/node-v0.8.14/test/simple/test-fs-write.js b/node-v0.8.14/test/simple/test-fs-write.js new file mode 100644 index 0000000..3d7a357 --- /dev/null +++ b/node-v0.8.14/test/simple/test-fs-write.js @@ -0,0 +1,76 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var path = require('path'); +var Buffer = require('buffer').Buffer; +var fs = require('fs'); +var fn = path.join(common.tmpDir, 'write.txt'); +var fn2 = path.join(common.tmpDir, 'write2.txt'); +var expected = 'ümlaut.'; +var constants = require('constants'); +var found, found2; + +fs.open(fn, 'w', 0644, function(err, fd) { + if (err) throw err; + console.log('open done'); + fs.write(fd, '', 0, 'utf8', function(err, written) { + assert.equal(0, written); + }); + fs.write(fd, expected, 0, 'utf8', function(err, written) { + console.log('write done'); + if (err) throw err; + assert.equal(Buffer.byteLength(expected), written); + fs.closeSync(fd); + found = fs.readFileSync(fn, 'utf8'); + console.log('expected: "%s"', expected); + console.log('found: "%s"', found); + fs.unlinkSync(fn); + }); +}); + + +fs.open(fn2, constants.O_CREAT | constants.O_WRONLY | constants.O_TRUNC, 0644, + function(err, fd) { + if (err) throw err; + console.log('open done'); + fs.write(fd, '', 0, 'utf8', function(err, written) { + assert.equal(0, written); + }); + fs.write(fd, expected, 0, 'utf8', function(err, written) { + console.log('write done'); + if (err) throw err; + assert.equal(Buffer.byteLength(expected), written); + fs.closeSync(fd); + found2 = fs.readFileSync(fn2, 'utf8'); + console.log('expected: "%s"', expected); + console.log('found: "%s"', found2); + fs.unlinkSync(fn2); + }); + }); + + +process.on('exit', function() { + assert.equal(expected, found); + assert.equal(expected, found2); +}); + diff --git a/node-v0.8.14/test/simple/test-global.js b/node-v0.8.14/test/simple/test-global.js new file mode 100644 index 0000000..4cc9799 --- /dev/null +++ b/node-v0.8.14/test/simple/test-global.js @@ -0,0 +1,39 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); + +common.globalCheck = false; + +baseFoo = 'foo'; +global.baseBar = 'bar'; + +assert.equal('foo', global.baseFoo, 'x -> global.x in base level not working'); + +assert.equal('bar', baseBar, 'global.x -> x in base level not working'); + +var module = require('../fixtures/global/plain'), + fooBar = module.fooBar; + +assert.equal('foo', fooBar.foo, 'x -> global.x in sub level not working'); + +assert.equal('bar', fooBar.bar, 'global.x -> x in sub level not working'); diff --git a/node-v0.8.14/test/simple/test-http-1.0-keep-alive.js b/node-v0.8.14/test/simple/test-http-1.0-keep-alive.js new file mode 100644 index 0000000..623facb --- /dev/null +++ b/node-v0.8.14/test/simple/test-http-1.0-keep-alive.js @@ -0,0 +1,148 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var http = require('http'); +var net = require('net'); + +// Check that our HTTP server correctly handles HTTP/1.0 keep-alive requests. +check([{ + name: 'keep-alive, no TE header', + requests: [{ + expectClose: true, + data: 'POST / HTTP/1.0\r\n' + + 'Connection: keep-alive\r\n' + + '\r\n' + }, { + expectClose: true, + data: 'POST / HTTP/1.0\r\n' + + 'Connection: keep-alive\r\n' + + '\r\n' + }], + responses: [{ + headers: {'Connection': 'keep-alive'}, + chunks: ['OK'] + }, { + chunks: [] + }] +}, { + name: 'keep-alive, with TE: chunked', + requests: [{ + expectClose: false, + data: 'POST / HTTP/1.0\r\n' + + 'Connection: keep-alive\r\n' + + 'TE: chunked\r\n' + + '\r\n' + }, { + expectClose: true, + data: 'POST / HTTP/1.0\r\n' + + '\r\n' + }], + responses: [{ + headers: {'Connection': 'keep-alive'}, + chunks: ['OK'] + }, { + chunks: [] + }] +}, { + name: 'keep-alive, with Transfer-Encoding: chunked', + requests: [{ + expectClose: false, + data: 'POST / HTTP/1.0\r\n' + + 'Connection: keep-alive\r\n' + + '\r\n' + }, { + expectClose: true, + data: 'POST / HTTP/1.0\r\n' + + '\r\n' + }], + responses: [{ + headers: {'Connection': 'keep-alive', + 'Transfer-Encoding': 'chunked'}, + chunks: ['OK'] + }, { + chunks: [] + }] +}, { + name: 'keep-alive, with Content-Length', + requests: [{ + expectClose: false, + data: 'POST / HTTP/1.0\r\n' + + 'Connection: keep-alive\r\n' + + '\r\n' + }, { + expectClose: true, + data: 'POST / HTTP/1.0\r\n' + + '\r\n' + }], + responses: [{ + headers: {'Connection': 'keep-alive', + 'Content-Length': '2'}, + chunks: ['OK'] + }, { + chunks: [] + }] +}]); + +function check(tests) { + var test = tests[0]; + if (test) http.createServer(server).listen(common.PORT, '127.0.0.1', client); + var current = 0; + + function next() { + check(tests.slice(1)); + } + + function server(req, res) { + if (current + 1 === test.responses.length) this.close(); + var ctx = test.responses[current]; + res.writeHead(200, ctx.headers); + ctx.chunks.slice(0, -1).forEach(function(chunk) { res.write(chunk) }); + res.end(ctx.chunks[ctx.chunks.length - 1]); + } + + function client() { + if (current === test.requests.length) return next(); + var conn = net.createConnection(common.PORT, '127.0.0.1', connected); + + function connected() { + var ctx = test.requests[current]; + conn.setEncoding('utf8'); + conn.write(ctx.data); + + function onclose() { + if (!ctx.expectClose) throw new Error('unexpected close'); + client(); + } + conn.on('close', onclose); + + function ondata(s) { + current++; + if (ctx.expectClose) return; + conn.removeListener('close', onclose); + conn.removeListener('data', ondata);; + connected(); + } + conn.on('data', ondata); + } + } +} diff --git a/node-v0.8.14/test/simple/test-http-1.0.js b/node-v0.8.14/test/simple/test-http-1.0.js new file mode 100644 index 0000000..f5f3aef --- /dev/null +++ b/node-v0.8.14/test/simple/test-http-1.0.js @@ -0,0 +1,181 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var net = require('net'); +var http = require('http'); + +var body = 'hello world\n'; + +var common_port = common.PORT; + +function test(handler, request_generator, response_validator) { + var port = common_port++; + var server = http.createServer(handler); + + var client_got_eof = false; + var server_response = { + data: '', + chunks: [] + }; + + function cleanup() { + server.close(); + response_validator(server_response, client_got_eof, true); + } + var timer = setTimeout(cleanup, 1000); + process.on('exit', cleanup); + + server.listen(port); + server.on('listening', function() { + var c = net.createConnection(port); + + c.setEncoding('utf8'); + + c.on('connect', function() { + c.write(request_generator()); + }); + + c.on('data', function(chunk) { + server_response.data += chunk; + server_response.chunks.push(chunk); + }); + + c.on('end', function() { + client_got_eof = true; + c.end(); + server.close(); + clearTimeout(timer); + process.removeListener('exit', cleanup); + response_validator(server_response, client_got_eof, false); + }); + }); +} + +(function() { + function handler(req, res) { + assert.equal('1.0', req.httpVersion); + assert.equal(1, req.httpVersionMajor); + assert.equal(0, req.httpVersionMinor); + res.writeHead(200, {'Content-Type': 'text/plain'}); + res.end(body); + } + + function request_generator() { + return 'GET / HTTP/1.0\r\n\r\n'; + } + + function response_validator(server_response, client_got_eof, timed_out) { + var m = server_response.data.split('\r\n\r\n'); + assert.equal(m[1], body); + assert.equal(true, client_got_eof); + assert.equal(false, timed_out); + } + + test(handler, request_generator, response_validator); +})(); + +// +// Don't send HTTP/1.1 status lines to HTTP/1.0 clients. +// +// https://github.com/joyent/node/issues/1234 +// +(function() { + function handler(req, res) { + assert.equal('1.0', req.httpVersion); + assert.equal(1, req.httpVersionMajor); + assert.equal(0, req.httpVersionMinor); + res.sendDate = false; + res.writeHead(200, {'Content-Type': 'text/plain'}); + res.write('Hello, '); res._send(''); + res.write('world!'); res._send(''); + res.end(); + } + + function request_generator() { + return ('GET / HTTP/1.0\r\n' + + 'User-Agent: curl/7.19.7 (x86_64-pc-linux-gnu) libcurl/7.19.7 ' + + 'OpenSSL/0.9.8k zlib/1.2.3.3 libidn/1.15\r\n' + + 'Host: 127.0.0.1:1337\r\n' + + 'Accept: */*\r\n' + + '\r\n'); + } + + function response_validator(server_response, client_got_eof, timed_out) { + var expected_response = ('HTTP/1.1 200 OK\r\n' + + 'Content-Type: text/plain\r\n' + + 'Connection: close\r\n' + + '\r\n' + + 'Hello, world!'); + + assert.equal(expected_response, server_response.data); + assert.equal(1, server_response.chunks.length); + assert.equal(true, client_got_eof); + assert.equal(false, timed_out); + } + + test(handler, request_generator, response_validator); +})(); + +(function() { + function handler(req, res) { + assert.equal('1.1', req.httpVersion); + assert.equal(1, req.httpVersionMajor); + assert.equal(1, req.httpVersionMinor); + res.sendDate = false; + res.writeHead(200, {'Content-Type': 'text/plain'}); + res.write('Hello, '); res._send(''); + res.write('world!'); res._send(''); + res.end(); + } + + function request_generator() { + return ('GET / HTTP/1.1\r\n' + + 'User-Agent: curl/7.19.7 (x86_64-pc-linux-gnu) libcurl/7.19.7 ' + + 'OpenSSL/0.9.8k zlib/1.2.3.3 libidn/1.15\r\n' + + 'Connection: close\r\n' + + 'Host: 127.0.0.1:1337\r\n' + + 'Accept: */*\r\n' + + '\r\n'); + } + + function response_validator(server_response, client_got_eof, timed_out) { + var expected_response = ('HTTP/1.1 200 OK\r\n' + + 'Content-Type: text/plain\r\n' + + 'Connection: close\r\n' + + 'Transfer-Encoding: chunked\r\n' + + '\r\n' + + '7\r\n' + + 'Hello, \r\n' + + '6\r\n' + + 'world!\r\n' + + '0\r\n' + + '\r\n'); + + assert.equal(expected_response, server_response.data); + assert.equal(1, server_response.chunks.length); + assert.equal(true, client_got_eof); + assert.equal(false, timed_out); + } + + test(handler, request_generator, response_validator); +})(); diff --git a/node-v0.8.14/test/simple/test-http-304.js b/node-v0.8.14/test/simple/test-http-304.js new file mode 100644 index 0000000..fcef21a --- /dev/null +++ b/node-v0.8.14/test/simple/test-http-304.js @@ -0,0 +1,46 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + + + +var common = require('../common'); +var assert = require('assert'); + +var http = require('http'); +var childProcess = require('child_process'); + +var s = http.createServer(function(request, response) { + response.writeHead(304); + response.end(); +}); + +s.listen(common.PORT, function() { + childProcess.exec('curl -i http://127.0.0.1:' + common.PORT + '/', + function(err, stdout, stderr) { + if (err) throw err; + s.close(); + common.error('curled response correctly'); + common.error(common.inspect(stdout)); + }); +}); + +console.log('Server running at http://127.0.0.1:' + common.PORT + '/'); diff --git a/node-v0.8.14/test/simple/test-http-abort-before-end.js b/node-v0.8.14/test/simple/test-http-abort-before-end.js new file mode 100644 index 0000000..11e424f --- /dev/null +++ b/node-v0.8.14/test/simple/test-http-abort-before-end.js @@ -0,0 +1,43 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var http = require('http'); +var assert = require('assert'); + +var server = http.createServer(function(req, res) { + assert(false); // should not be called +}); + +server.listen(common.PORT, function() { + var req = http.request({method: 'GET', host: '127.0.0.1', port: common.PORT}); + + req.on('error', function(ex) { + // https://github.com/joyent/node/issues/1399#issuecomment-2597359 + // abort() should emit an Error, not the net.Socket object + assert(ex instanceof Error); + }); + + req.abort(); + req.end(); + + server.close(); +}); diff --git a/node-v0.8.14/test/simple/test-http-abort-client.js b/node-v0.8.14/test/simple/test-http-abort-client.js new file mode 100644 index 0000000..6acdd6f --- /dev/null +++ b/node-v0.8.14/test/simple/test-http-abort-client.js @@ -0,0 +1,67 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var http = require('http'); +var assert = require('assert'); + +var server = http.Server(function(req, res) { + console.log('Server accepted request.'); + res.writeHead(200); + res.write('Part of my res.'); + + res.destroy(); +}); + +var responseClose = false; + +server.listen(common.PORT, function() { + var client = http.get({ + port: common.PORT, + headers: { connection: 'keep-alive' } + + }, function(res) { + server.close(); + + console.log('Got res: ' + res.statusCode); + console.dir(res.headers); + + res.on('data', function(chunk) { + console.log('Read ' + chunk.length + ' bytes'); + console.log(chunk.toString()); + }); + + res.on('end', function() { + console.log('Response ended.'); + }); + + // it would be nice if this worked: + res.on('close', function() { + console.log('Response aborted'); + responseClose = true; + }); + }); +}); + + +process.on('exit', function() { + assert.ok(responseClose); +}); diff --git a/node-v0.8.14/test/simple/test-http-after-connect.js b/node-v0.8.14/test/simple/test-http-after-connect.js new file mode 100644 index 0000000..d6451bb --- /dev/null +++ b/node-v0.8.14/test/simple/test-http-after-connect.js @@ -0,0 +1,89 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var http = require('http'); + +var serverConnected = false; +var serverRequests = 0; +var clientResponses = 0; + +var server = http.createServer(function(req, res) { + common.debug('Server got GET request'); + ++serverRequests; + res.writeHead(200); + res.write(''); + setTimeout(function() { + res.end(req.url); + }, 50); +}); +server.on('connect', function(req, socket, firstBodyChunk) { + common.debug('Server got CONNECT request'); + serverConnected = true; + socket.write('HTTP/1.1 200 Connection established\r\n\r\n'); + socket.on('end', function() { + socket.end(); + }); +}); +server.listen(common.PORT, function() { + var req = http.request({ + port: common.PORT, + method: 'CONNECT', + path: 'google.com:80' + }); + req.on('connect', function(res, socket, firstBodyChunk) { + common.debug('Client got CONNECT response'); + socket.end(); + socket.on('end', function() { + doRequest(0); + doRequest(1); + }); + }); + req.end(); +}); + +function doRequest(i) { + var req = http.get({ + port: common.PORT, + path: '/request' + i + }, function(res) { + common.debug('Client got GET response'); + var data = ''; + res.setEncoding('utf8'); + res.on('data', function(chunk) { + data += chunk; + }); + res.on('end', function() { + assert.equal(data, '/request' + i); + ++clientResponses; + if (clientResponses === 2) { + server.close(); + } + }); + }); +} + +process.on('exit', function() { + assert(serverConnected); + assert.equal(serverRequests, 2); + assert.equal(clientResponses, 2); +}); diff --git a/node-v0.8.14/test/simple/test-http-agent.js b/node-v0.8.14/test/simple/test-http-agent.js new file mode 100644 index 0000000..a1ce456 --- /dev/null +++ b/node-v0.8.14/test/simple/test-http-agent.js @@ -0,0 +1,57 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + + + +var common = require('../common'); +var assert = require('assert'); +var http = require('http'); + +var server = http.Server(function(req, res) { + res.writeHead(200); + res.end('hello world\n'); +}); + +var responses = 0; +var N = 10; +var M = 10; + +server.listen(common.PORT, function() { + for (var i = 0; i < N; i++) { + setTimeout(function() { + for (var j = 0; j < M; j++) { + http.get({ port: common.PORT, path: '/' }, function(res) { + console.log(res.statusCode); + if (++responses == N * M) server.close(); + }).on('error', function(e) { + console.log(e.message); + process.exit(1); + }); + } + }, i); + } +}); + + +process.on('exit', function() { + assert.equal(N * M, responses); +}); diff --git a/node-v0.8.14/test/simple/test-http-allow-req-after-204-res.js b/node-v0.8.14/test/simple/test-http-allow-req-after-204-res.js new file mode 100644 index 0000000..8f89043 --- /dev/null +++ b/node-v0.8.14/test/simple/test-http-allow-req-after-204-res.js @@ -0,0 +1,65 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var http = require('http'); +var assert = require('assert'); + +// first 204 or 304 works, subsequent anything fails +var codes = [204, 200]; + +// Methods don't really matter, but we put in something realistic. +var methods = ['DELETE', 'DELETE']; + +var server = http.createServer(function(req, res) { + var code = codes.shift(); + assert.equal('number', typeof code); + assert.ok(code > 0); + console.error('writing %d response', code); + res.writeHead(code, {}); + res.end(); +}); + +function nextRequest() { + var method = methods.shift(); + console.error('writing request: %s', method); + + var request = http.request({ + port: common.PORT, + method: method, + path: '/' + }, function(response) { + response.on('end', function() { + if (methods.length == 0) { + console.error('close server'); + server.close(); + } else { + // throws error: + nextRequest(); + // works just fine: + //process.nextTick(nextRequest); + } + }); + }); + request.end(); +} + +server.listen(common.PORT, nextRequest); diff --git a/node-v0.8.14/test/simple/test-http-bind-twice.js b/node-v0.8.14/test/simple/test-http-bind-twice.js new file mode 100644 index 0000000..59d69ef --- /dev/null +++ b/node-v0.8.14/test/simple/test-http-bind-twice.js @@ -0,0 +1,47 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var http = require('http'); + +var gotError = false; + +process.on('exit', function() { + assert(gotError); +}); + +function dontCall() { + assert(false); +} + +var server1 = http.createServer(dontCall); +server1.listen(common.PORT, '127.0.0.1', function() {}); + +var server2 = http.createServer(dontCall); +server2.listen(common.PORT, '127.0.0.1', dontCall); + +server2.on('error', function(e) { + assert.equal(e.code, 'EADDRINUSE'); + server1.close(); + gotError = true; +}); + diff --git a/node-v0.8.14/test/simple/test-http-blank-header.js b/node-v0.8.14/test/simple/test-http-blank-header.js new file mode 100644 index 0000000..bd9be86 --- /dev/null +++ b/node-v0.8.14/test/simple/test-http-blank-header.js @@ -0,0 +1,68 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var http = require('http'); +var net = require('net'); + +var gotReq = false; + +var server = http.createServer(function(req, res) { + common.error('got req'); + gotReq = true; + assert.equal('GET', req.method); + assert.equal('/blah', req.url); + assert.deepEqual({ + host: 'mapdevel.trolologames.ru:443', + origin: 'http://mapdevel.trolologames.ru', + cookie: '' + }, req.headers); +}); + + +server.listen(common.PORT, function() { + var c = net.createConnection(common.PORT); + + c.on('connect', function() { + common.error('client wrote message'); + c.write('GET /blah HTTP/1.1\r\n' + + 'Host: mapdevel.trolologames.ru:443\r\n' + + 'Cookie:\r\n' + + 'Origin: http://mapdevel.trolologames.ru\r\n' + + '\r\n\r\nhello world' + ); + }); + + c.on('end', function() { + c.end(); + }); + + c.on('close', function() { + common.error('client close'); + server.close(); + }); +}); + + +process.on('exit', function() { + assert.ok(gotReq); +}); diff --git a/node-v0.8.14/test/simple/test-http-buffer-sanity.js b/node-v0.8.14/test/simple/test-http-buffer-sanity.js new file mode 100644 index 0000000..2e650d9 --- /dev/null +++ b/node-v0.8.14/test/simple/test-http-buffer-sanity.js @@ -0,0 +1,91 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var http = require('http'); +var util = require('util'); + +var bufferSize = 5 * 1024 * 1024; +var measuredSize = 0; + +var buffer = Buffer(bufferSize); +for (var i = 0; i < buffer.length; i++) { + buffer[i] = i % 256; +} + + +var web = http.Server(function(req, res) { + web.close(); + + console.log(req.headers); + + var i = 0; + + req.on('data', function(d) { + process.stdout.write(','); + measuredSize += d.length; + for (var j = 0; j < d.length; j++) { + assert.equal(buffer[i], d[j]); + i++; + } + }); + + + req.on('end', function() { + res.writeHead(200); + res.write('thanks'); + res.end(); + console.log('response with \'thanks\''); + }); + + req.connection.on('error', function(e) { + console.log('http server-side error: ' + e.message); + process.exit(1); + }); +}); + +var gotThanks = false; + +web.listen(common.PORT, function() { + console.log('Making request'); + + var req = http.request({ + port: common.PORT, + method: 'GET', + path: '/', + headers: { 'content-length': buffer.length } + }, function(res) { + console.log('Got response'); + res.setEncoding('utf8'); + res.on('data', function(string) { + assert.equal('thanks', string); + gotThanks = true; + }); + }); + req.end(buffer); +}); + + +process.on('exit', function() { + assert.equal(bufferSize, measuredSize); + assert.ok(gotThanks); +}); diff --git a/node-v0.8.14/test/simple/test-http-chunked.js b/node-v0.8.14/test/simple/test-http-chunked.js new file mode 100644 index 0000000..c5def3d --- /dev/null +++ b/node-v0.8.14/test/simple/test-http-chunked.js @@ -0,0 +1,63 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var http = require('http'); + +var UTF8_STRING = '南越国是前203年至前111年存在于岭南地区的一个国家,' + + '国都位于番禺,疆域包括今天中国的广东、广西两省区的大部份地区,福建省、湖南、' + + '贵州、云南的一小部份地区和越南的北部。南越国是秦朝灭亡后,' + + '由南海郡尉赵佗于前203年起兵兼并桂林郡和象郡后建立。前196年和前179年,' + + '南越国曾先后两次名义上臣属于西汉,成为西汉的“外臣”。前112年,' + + '南越国末代君主赵建德与西汉发生战争,被汉武帝于前111年所灭。' + + '南越国共存在93年,历经五代君主。南越国是岭南地区的第一个有记载的政权国家,' + + '采用封建制和郡县制并存的制度,它的建立保证了秦末乱世岭南地区社会秩序的稳定,' + + '有效的改善了岭南地区落后的政治、经济现状。'; + +var server = http.createServer(function(req, res) { + res.writeHead(200, {'Content-Type': 'text/plain; charset=utf8'}); + res.end(UTF8_STRING, 'utf8'); +}); +server.listen(common.PORT, function() { + var data = ''; + var get = http.get({ + path: '/', + host: 'localhost', + port: common.PORT + }, function(x) { + x.setEncoding('utf8'); + x.on('data', function(c) {data += c}); + x.on('error', function(e) { + throw e; + }); + x.on('end', function() { + assert.equal('string', typeof data); + console.log('here is the response:'); + assert.equal(UTF8_STRING, data); + console.log(data); + server.close(); + }); + }); + get.on('error', function(e) {throw e}); + get.end(); + +}); diff --git a/node-v0.8.14/test/simple/test-http-client-abort.js b/node-v0.8.14/test/simple/test-http-client-abort.js new file mode 100644 index 0000000..c9b5eb0 --- /dev/null +++ b/node-v0.8.14/test/simple/test-http-client-abort.js @@ -0,0 +1,80 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var http = require('http'); + +var clientAborts = 0; + +var server = http.Server(function(req, res) { + console.log('Got connection'); + res.writeHead(200); + res.write('Working on it...'); + + // I would expect an error event from req or res that the client aborted + // before completing the HTTP request / response cycle, or maybe a new + // event like "aborted" or something. + req.on('aborted', function() { + clientAborts++; + console.log('Got abort ' + clientAborts); + if (clientAborts === N) { + console.log('All aborts detected, you win.'); + server.close(); + } + }); + + // since there is already clientError, maybe that would be appropriate, + // since "error" is magical + req.on('clientError', function() { + console.log('Got clientError'); + }); +}); + +var responses = 0; +var N = http.Agent.defaultMaxSockets - 1; +var requests = []; + +server.listen(common.PORT, function() { + console.log('Server listening.'); + + for (var i = 0; i < N; i++) { + console.log('Making client ' + i); + var options = { port: common.PORT, path: '/?id=' + i }; + var req = http.get(options, function(res) { + console.log('Client response code ' + res.statusCode); + + if (++responses == N) { + console.log('All clients connected, destroying.'); + requests.forEach(function(outReq) { + console.log('abort'); + outReq.abort(); + }); + } + }); + + requests.push(req); + } +}); + +process.on('exit', function() { + assert.equal(N, clientAborts); +}); diff --git a/node-v0.8.14/test/simple/test-http-client-abort2.js b/node-v0.8.14/test/simple/test-http-client-abort2.js new file mode 100644 index 0000000..17efb7e --- /dev/null +++ b/node-v0.8.14/test/simple/test-http-client-abort2.js @@ -0,0 +1,41 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + + + +var common = require('../common'); +var assert = require('assert'); +var http = require('http'); + +var server = http.createServer(function(req, res) { + res.end('Hello'); +}); + +server.listen(common.PORT, function() { + var req = http.get({port: common.PORT}, function(res) { + res.on('data', function(data) { + req.abort(); + server.close(); + }); + }); +}); + diff --git a/node-v0.8.14/test/simple/test-http-client-agent.js b/node-v0.8.14/test/simple/test-http-client-agent.js new file mode 100644 index 0000000..f7112e3 --- /dev/null +++ b/node-v0.8.14/test/simple/test-http-client-agent.js @@ -0,0 +1,69 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var http = require('http'); + +var name = 'localhost:' + common.PORT; +var max = 3; +var count = 0; + +var server = http.Server(function(req, res) { + if (req.url === '/0') { + setTimeout(function() { + res.writeHead(200); + res.end('Hello, World!'); + }, 100); + } else { + res.writeHead(200); + res.end('Hello, World!'); + } +}); +server.listen(common.PORT, function() { + for (var i = 0; i < max; ++i) { + request(i); + } +}); + +function request(i) { + var req = http.get({ + port: common.PORT, + path: '/' + i + }, function(res) { + var socket = req.socket; + socket.on('close', function() { + ++count; + if (count < max) { + assert.equal(http.globalAgent.sockets[name].length, max - count); + assert.equal(http.globalAgent.sockets[name].indexOf(socket), -1); + } else { + assert(!http.globalAgent.sockets.hasOwnProperty(name)); + assert(!http.globalAgent.requests.hasOwnProperty(name)); + server.close(); + } + }); + }); +} + +process.on('exit', function() { + assert.equal(count, max); +}); diff --git a/node-v0.8.14/test/simple/test-http-client-get-url.js b/node-v0.8.14/test/simple/test-http-client-get-url.js new file mode 100644 index 0000000..451f5ee --- /dev/null +++ b/node-v0.8.14/test/simple/test-http-client-get-url.js @@ -0,0 +1,44 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var http = require('http'); + +var seen_req = false; + +var server = http.createServer(function(req, res) { + assert.equal('GET', req.method); + assert.equal('/foo?bar', req.url); + res.writeHead(200, {'Content-Type': 'text/plain'}); + res.write('hello\n'); + res.end(); + server.close(); + seen_req = true; +}); + +server.listen(common.PORT, function() { + http.get('http://127.0.0.1:' + common.PORT + '/foo?bar'); +}); + +process.on('exit', function() { + assert(seen_req); +}); diff --git a/node-v0.8.14/test/simple/test-http-client-parse-error.js b/node-v0.8.14/test/simple/test-http-client-parse-error.js new file mode 100644 index 0000000..91baa47 --- /dev/null +++ b/node-v0.8.14/test/simple/test-http-client-parse-error.js @@ -0,0 +1,61 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); + +var http = require('http'); +var net = require('net'); + +// Create a TCP server +var srv = net.createServer(function(c) { + c.write('bad http - should trigger parse error\r\n'); + + console.log('connection'); + + c.on('end', function() { c.end(); }); +}); + +var parseError = false; + +srv.listen(common.PORT, '127.0.0.1', function() { + var req = http.request({ + host: '127.0.0.1', + port: common.PORT, + method: 'GET', + path: '/'}); + req.end(); + + req.on('error', function(e) { + console.log('got error from client'); + srv.close(); + assert.ok(e.message.indexOf('Parse Error') >= 0); + assert.equal(e.code, 'HPE_INVALID_CONSTANT'); + parseError = true; + }); +}); + + +process.on('exit', function() { + assert.ok(parseError); +}); + + diff --git a/node-v0.8.14/test/simple/test-http-client-pipe-end.js b/node-v0.8.14/test/simple/test-http-client-pipe-end.js new file mode 100644 index 0000000..7cb592e --- /dev/null +++ b/node-v0.8.14/test/simple/test-http-client-pipe-end.js @@ -0,0 +1,58 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// see https://github.com/joyent/node/issues/3257 + +var common = require('../common'); +var assert = require('assert'); +var http = require('http'); + +var server = http.createServer(function(req, res) { + req.once('end', function() { + res.writeHead(200); + res.end(); + server.close(); + }); +}); + +server.listen(common.PIPE, function() { + var req = http.request({ + socketPath: common.PIPE, + headers: {'Content-Length':'1'}, + method: 'POST', + path: '/' + }); + + req.write('.'); + + sched(function() { req.end() }, 5); +}); + +// schedule a callback after `ticks` event loop ticks +function sched(cb, ticks) { + function fn() { + if (--ticks) + process.nextTick(fn); + else + cb(); + } + process.nextTick(fn); +} diff --git a/node-v0.8.14/test/simple/test-http-client-race-2.js b/node-v0.8.14/test/simple/test-http-client-race-2.js new file mode 100644 index 0000000..6b7c508 --- /dev/null +++ b/node-v0.8.14/test/simple/test-http-client-race-2.js @@ -0,0 +1,118 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var http = require('http'); +var url = require('url'); + +// +// Slight variation on test-http-client-race to test for another race +// condition involving the parsers FreeList used internally by http.Client. +// + +var body1_s = '1111111111111111'; +var body2_s = '22222'; +var body3_s = '3333333333333333333'; + +var server = http.createServer(function(req, res) { + var pathname = url.parse(req.url).pathname; + + var body; + switch (pathname) { + case '/1': body = body1_s; break; + case '/2': body = body2_s; break; + default: body = body3_s; + } + + res.writeHead(200, + {'Content-Type': 'text/plain', 'Content-Length': body.length}); + res.end(body); +}); +server.listen(common.PORT); + +var body1 = ''; +var body2 = ''; +var body3 = ''; + +server.on('listening', function() { + var client = http.createClient(common.PORT); + + // + // Client #1 is assigned Parser #1 + // + var req1 = client.request('/1'); + req1.end(); + req1.on('response', function(res1) { + res1.setEncoding('utf8'); + + res1.on('data', function(chunk) { + body1 += chunk; + }); + + res1.on('end', function() { + // + // Delay execution a little to allow the 'close' event to be processed + // (required to trigger this bug!) + // + setTimeout(function() { + // + // The bug would introduce itself here: Client #2 would be allocated the + // parser that previously belonged to Client #1. But we're not finished + // with Client #1 yet! + // + var client2 = http.createClient(common.PORT); + + // + // At this point, the bug would manifest itself and crash because the + // internal state of the parser was no longer valid for use by Client #1 + // + var req2 = client.request('/2'); + req2.end(); + req2.on('response', function(res2) { + res2.setEncoding('utf8'); + res2.on('data', function(chunk) { body2 += chunk; }); + res2.on('end', function() { + + // + // Just to be really sure we've covered all our bases, execute a + // request using client2. + // + var req3 = client2.request('/3'); + req3.end(); + req3.on('response', function(res3) { + res3.setEncoding('utf8'); + res3.on('data', function(chunk) { body3 += chunk }); + res3.on('end', function() { server.close(); }); + }); + }); + }); + }, 500); + }); + }); +}); + +process.on('exit', function() { + assert.equal(body1_s, body1); + assert.equal(body2_s, body2); + assert.equal(body3_s, body3); +}); + diff --git a/node-v0.8.14/test/simple/test-http-client-race.js b/node-v0.8.14/test/simple/test-http-client-race.js new file mode 100644 index 0000000..0f50c8e --- /dev/null +++ b/node-v0.8.14/test/simple/test-http-client-race.js @@ -0,0 +1,66 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var http = require('http'); +var url = require('url'); + +var body1_s = '1111111111111111'; +var body2_s = '22222'; + +var server = http.createServer(function(req, res) { + var body = url.parse(req.url).pathname === '/1' ? body1_s : body2_s; + res.writeHead(200, + {'Content-Type': 'text/plain', 'Content-Length': body.length}); + res.end(body); +}); +server.listen(common.PORT); + +var body1 = ''; +var body2 = ''; + +server.on('listening', function() { + var req1 = http.request({ port: common.PORT, path: '/1' }); + req1.end(); + req1.on('response', function(res1) { + res1.setEncoding('utf8'); + + res1.on('data', function(chunk) { + body1 += chunk; + }); + + res1.on('end', function() { + var req2 = http.request({ port: common.PORT, path: '/2' }); + req2.end(); + req2.on('response', function(res2) { + res2.setEncoding('utf8'); + res2.on('data', function(chunk) { body2 += chunk; }); + res2.on('end', function() { server.close(); }); + }); + }); + }); +}); + +process.on('exit', function() { + assert.equal(body1_s, body1); + assert.equal(body2_s, body2); +}); diff --git a/node-v0.8.14/test/simple/test-http-client-response-domain.js b/node-v0.8.14/test/simple/test-http-client-response-domain.js new file mode 100644 index 0000000..7a3c41b --- /dev/null +++ b/node-v0.8.14/test/simple/test-http-client-response-domain.js @@ -0,0 +1,65 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'), + assert = require('assert'), + http = require('http'), + domain = require('domain'); + +var gotDomainError = false; +var d; + +process.on('exit', function() { + assert(gotDomainError); +}); + +// first fire up a simple HTTP server +var server = http.createServer(function(req, res) { + res.writeHead(200); + res.end(); + server.close(); +}); +server.listen(common.PIPE, function() { + // create a domain + d = domain.create(); + d.run(test); +}); + +function test() { + + d.on('error', function(err) { + gotDomainError = true; + assert.equal('should be caught by domain', err.message); + }); + + var req = http.get({ + socketPath: common.PIPE, + headers: {'Content-Length':'1'}, + method: 'POST', + path: '/' + }); + req.on('response', function(res) { + res.on('end', function() { + res.emit('error', new Error('should be caught by domain')); + }); + }); + req.end(); +} diff --git a/node-v0.8.14/test/simple/test-http-client-timeout-agent.js b/node-v0.8.14/test/simple/test-http-client-timeout-agent.js new file mode 100644 index 0000000..79d0a24 --- /dev/null +++ b/node-v0.8.14/test/simple/test-http-client-timeout-agent.js @@ -0,0 +1,96 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var http = require('http'); + +var request_number = 0; +var requests_sent = 0; +var requests_done = 0; +var options = { + method: 'GET', + port: common.PORT, + host: '127.0.0.1', +}; + +//http.globalAgent.maxSockets = 15; + +var server = http.createServer(function(req, res) { + var m = /\/(.*)/.exec(req.url), + reqid = parseInt(m[1], 10); + if ( reqid % 2 ) { + // do not reply the request + } else { + res.writeHead(200, {'Content-Type': 'text/plain'}); + res.write(reqid.toString()); + res.end(); + } + request_number+=1; +}); + +server.listen(options.port, options.host, function() { + var req; + + for (requests_sent = 0; requests_sent < 30; requests_sent+=1) { + options.path = '/' + requests_sent; + req = http.request(options); + req.id = requests_sent; + req.on('response', function(res) { + res.on('data', function(data) { + console.log('res#'+this.req.id+' data:'+data); + }); + res.on('end', function(data) { + console.log('res#'+this.req.id+' end'); + requests_done += 1; + }); + }); + req.on('close', function() { + console.log('req#'+this.id+' close'); + }); + req.on('error', function() { + console.log('req#'+this.id+' error'); + this.destroy(); + }); + req.setTimeout(50, function () { + var req = this; + console.log('req#'+this.id + ' timeout'); + req.abort(); + requests_done += 1; + }); + req.end(); + } + + setTimeout(function maybeDone() { + if (requests_done >= requests_sent) { + setTimeout(function() { + server.close(); + }, 100); + } else { + setTimeout(maybeDone, 100); + } + }, 100); +}); + +process.on('exit', function() { + console.error('done=%j sent=%j', requests_done, requests_sent); + assert.ok(requests_done == requests_sent, 'timeout on http request called too much'); +}); diff --git a/node-v0.8.14/test/simple/test-http-client-timeout-with-data.js b/node-v0.8.14/test/simple/test-http-client-timeout-with-data.js new file mode 100644 index 0000000..d169065 --- /dev/null +++ b/node-v0.8.14/test/simple/test-http-client-timeout-with-data.js @@ -0,0 +1,67 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var http = require('http'); + +var ntimeouts = 0; +var nchunks = 0; + +process.on('exit', function() { + assert.equal(ntimeouts, 1); + assert.equal(nchunks, 2); +}); + +var options = { + method: 'GET', + port: common.PORT, + host: '127.0.0.1', + path: '/' +}; + +var server = http.createServer(function(req, res) { + res.writeHead(200, {'Content-Length':'2'}); + res.write('*'); + setTimeout(function() { res.end('*') }, 20); +}); + +server.listen(options.port, options.host, function() { + var req = http.request(options, onresponse); + req.end(); + + function onresponse(res) { + req.setTimeout(10, function() { + assert.equal(nchunks, 1); // should have received the first chunk by now + ntimeouts++; + }); + + res.on('data', function(data) { + assert.equal('' + data, '*'); + nchunks++; + }); + + res.on('end', function() { + assert.equal(nchunks, 2); + server.close(); + }); + } +}); diff --git a/node-v0.8.14/test/simple/test-http-client-timeout.js b/node-v0.8.14/test/simple/test-http-client-timeout.js new file mode 100644 index 0000000..98eb553 --- /dev/null +++ b/node-v0.8.14/test/simple/test-http-client-timeout.js @@ -0,0 +1,50 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var http = require('http'); + +var options = { + method: 'GET', + port: common.PORT, + host: '127.0.0.1', + path: '/' +}; + +var server = http.createServer(function(req, res) { + // this space intentionally left blank +}); + +server.listen(options.port, options.host, function() { + var req = http.request(options, function(res) { + // this space intentionally left blank + }); + req.on('close', function() { + server.close(); + }); + function destroy() { + req.destroy(); + } + req.setTimeout(1, destroy); + req.on('error', destroy); + req.end(); +}); diff --git a/node-v0.8.14/test/simple/test-http-client-upload-buf.js b/node-v0.8.14/test/simple/test-http-client-upload-buf.js new file mode 100644 index 0000000..73e07e7 --- /dev/null +++ b/node-v0.8.14/test/simple/test-http-client-upload-buf.js @@ -0,0 +1,74 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var http = require('http'); + +var N = 1024; +var bytesRecieved = 0; +var server_req_complete = false; +var client_res_complete = false; + +var server = http.createServer(function(req, res) { + assert.equal('POST', req.method); + + req.on('data', function(chunk) { + bytesRecieved += chunk.length; + }); + + req.on('end', function() { + server_req_complete = true; + console.log('request complete from server'); + res.writeHead(200, {'Content-Type': 'text/plain'}); + res.write('hello\n'); + res.end(); + }); +}); +server.listen(common.PORT); + +server.on('listening', function() { + var req = http.request({ + port: common.PORT, + method: 'POST', + path: '/' + }, function(res) { + res.setEncoding('utf8'); + res.on('data', function(chunk) { + console.log(chunk); + }); + res.on('end', function() { + client_res_complete = true; + server.close(); + }); + }); + + req.write(new Buffer(N)); + req.end(); + + common.error('client finished sending request'); +}); + +process.on('exit', function() { + assert.equal(N, bytesRecieved); + assert.equal(true, server_req_complete); + assert.equal(true, client_res_complete); +}); diff --git a/node-v0.8.14/test/simple/test-http-client-upload.js b/node-v0.8.14/test/simple/test-http-client-upload.js new file mode 100644 index 0000000..912ca96 --- /dev/null +++ b/node-v0.8.14/test/simple/test-http-client-upload.js @@ -0,0 +1,77 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var http = require('http'); + +var sent_body = ''; +var server_req_complete = false; +var client_res_complete = false; + +var server = http.createServer(function(req, res) { + assert.equal('POST', req.method); + req.setEncoding('utf8'); + + req.on('data', function(chunk) { + console.log('server got: ' + JSON.stringify(chunk)); + sent_body += chunk; + }); + + req.on('end', function() { + server_req_complete = true; + console.log('request complete from server'); + res.writeHead(200, {'Content-Type': 'text/plain'}); + res.write('hello\n'); + res.end(); + }); +}); +server.listen(common.PORT); + +server.on('listening', function() { + var req = http.request({ + port: common.PORT, + method: 'POST', + path: '/' + }, function(res) { + res.setEncoding('utf8'); + res.on('data', function(chunk) { + console.log(chunk); + }); + res.on('end', function() { + client_res_complete = true; + server.close(); + }); + }); + + req.write('1\n'); + req.write('2\n'); + req.write('3\n'); + req.end(); + + common.error('client finished sending request'); +}); + +process.on('exit', function() { + assert.equal('1\n2\n3\n', sent_body); + assert.equal(true, server_req_complete); + assert.equal(true, client_res_complete); +}); diff --git a/node-v0.8.14/test/simple/test-http-conn-reset.js b/node-v0.8.14/test/simple/test-http-conn-reset.js new file mode 100644 index 0000000..908d433 --- /dev/null +++ b/node-v0.8.14/test/simple/test-http-conn-reset.js @@ -0,0 +1,57 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var http = require('http'); +var net = require('net'); + +var caughtError = false; + +var options = { + host: '127.0.0.1', + port: common.PORT +}; + +// start a tcp server that closes incoming connections immediately +var server = net.createServer(function(client) { + client.destroy(); + server.close(); +}); +server.listen(options.port, options.host, onListen); + +// do a GET request, expect it to fail +function onListen() { + var req = http.request(options, function(res) { + assert.ok(false, 'this should never run'); + }); + req.on('error', function(err) { + assert.equal(err.code, 'ECONNRESET'); + assert.equal(err.message, 'socket hang up'); + caughtError = true; + }); + req.end(); +} + +process.on('exit', function() { + assert.equal(caughtError, true); +}); + diff --git a/node-v0.8.14/test/simple/test-http-connect.js b/node-v0.8.14/test/simple/test-http-connect.js new file mode 100644 index 0000000..668dda7 --- /dev/null +++ b/node-v0.8.14/test/simple/test-http-connect.js @@ -0,0 +1,105 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var http = require('http'); + +var serverGotConnect = false; +var clientGotConnect = false; + +var server = http.createServer(function(req, res) { + assert(false); +}); +server.on('connect', function(req, socket, firstBodyChunk) { + assert.equal(req.method, 'CONNECT'); + assert.equal(req.url, 'google.com:443'); + common.debug('Server got CONNECT request'); + serverGotConnect = true; + + socket.write('HTTP/1.1 200 Connection established\r\n\r\n'); + + var data = firstBodyChunk.toString(); + socket.on('data', function(buf) { + data += buf.toString(); + }); + socket.on('end', function() { + socket.end(data); + }); +}); +server.listen(common.PORT, function() { + var req = http.request({ + port: common.PORT, + method: 'CONNECT', + path: 'google.com:443' + }, function(res) { + assert(false); + }); + + var clientRequestClosed = false; + req.on('close', function() { + clientRequestClosed = true; + }); + + req.on('connect', function(res, socket, firstBodyChunk) { + common.debug('Client got CONNECT request'); + clientGotConnect = true; + + // Make sure this request got removed from the pool. + var name = 'localhost:' + common.PORT; + assert(!http.globalAgent.sockets.hasOwnProperty(name)); + assert(!http.globalAgent.requests.hasOwnProperty(name)); + + // Make sure this socket has detached. + assert(!socket.ondata); + assert(!socket.onend); + assert.equal(socket.listeners('connect').length, 0); + assert.equal(socket.listeners('data').length, 0); + assert.equal(socket.listeners('end').length, 0); + assert.equal(socket.listeners('free').length, 0); + assert.equal(socket.listeners('close').length, 0); + assert.equal(socket.listeners('error').length, 0); + assert.equal(socket.listeners('agentRemove').length, 0); + + var data = firstBodyChunk.toString(); + socket.on('data', function(buf) { + data += buf.toString(); + }); + socket.on('end', function() { + assert.equal(data, 'HeadBody'); + assert(clientRequestClosed); + server.close(); + }); + socket.write('Body'); + socket.end(); + }); + + // It is legal for the client to send some data intended for the server + // before the "200 Connection established" (or any other success or + // error code) is received. + req.write('Head'); + req.end(); +}); + +process.on('exit', function() { + assert.ok(serverGotConnect); + assert.ok(clientGotConnect); +}); diff --git a/node-v0.8.14/test/simple/test-http-contentLength0.js b/node-v0.8.14/test/simple/test-http-contentLength0.js new file mode 100644 index 0000000..4d6e616 --- /dev/null +++ b/node-v0.8.14/test/simple/test-http-contentLength0.js @@ -0,0 +1,42 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var http = require('http'); + +// Simple test of Node's HTTP Client choking on a response +// with a 'Content-Length: 0 ' response header. +// I.E. a space character after the 'Content-Length' throws an `error` event. + + +var s = http.createServer(function(req, res) { + res.writeHead(200, {'Content-Length': '0 '}); + res.end(); +}); +s.listen(common.PORT, function() { + + var request = http.request({ port: common.PORT }, function(response) { + console.log('STATUS: ' + response.statusCode); + s.close(); + }); + + request.end(); +}); diff --git a/node-v0.8.14/test/simple/test-http-curl-chunk-problem.js b/node-v0.8.14/test/simple/test-http-curl-chunk-problem.js new file mode 100644 index 0000000..908b0dd --- /dev/null +++ b/node-v0.8.14/test/simple/test-http-curl-chunk-problem.js @@ -0,0 +1,91 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +if (!process.versions.openssl) { + console.error('Skipping because node compiled without OpenSSL.'); + process.exit(0); +} + +// http://groups.google.com/group/nodejs/browse_thread/thread/f66cd3c960406919 +var common = require('../common'); +var assert = require('assert'); +var http = require('http'); +var cp = require('child_process'); +var fs = require('fs'); + +var filename = require('path').join(common.tmpDir || '/tmp', 'big'); + +// Clean up after ourselves. Leaving files around +// in the tmp/ directory may break tests that depend +// on a certain number of files being there. +process.on('exit', function() { + fs.unlink(filename); +}); + +var count = 0; +function maybeMakeRequest() { + if (++count < 2) return; + console.log('making curl request'); + var cmd = 'curl http://127.0.0.1:' + common.PORT + '/ | openssl sha1'; + cp.exec(cmd, function(err, stdout, stderr) { + if (err) throw err; + var hex = stdout.match(/([A-Fa-f0-9]{40})/)[0]; + assert.equal('8c206a1a87599f532ce68675536f0b1546900d7a', hex); + console.log('got the correct response'); + server.close(); + }); +} + + +var ddcmd = common.ddCommand(filename, 10240); +console.log('dd command: ', ddcmd); + +cp.exec(ddcmd, function(err, stdout, stderr) { + if (err) throw err; + maybeMakeRequest(); +}); + + +var server = http.createServer(function(req, res) { + res.writeHead(200); + + // Create the subprocess + var cat = cp.spawn('cat', [filename]); + + // Stream the data through to the response as binary chunks + cat.stdout.on('data', function(data) { + res.write(data); + }); + + // End the response on exit (and log errors) + cat.on('exit', function(code) { + if (code !== 0) { + console.error('subprocess exited with code ' + code); + exit(1); + } + res.end(); + }); + +}); + +server.listen(common.PORT, maybeMakeRequest); + +console.log('Server running at http://localhost:8080'); diff --git a/node-v0.8.14/test/simple/test-http-date-header.js b/node-v0.8.14/test/simple/test-http-date-header.js new file mode 100644 index 0000000..8ed5281 --- /dev/null +++ b/node-v0.8.14/test/simple/test-http-date-header.js @@ -0,0 +1,54 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var http = require('http'); + +var testResBody = 'other stuff!\n'; + +var server = http.createServer(function(req, res) { + assert.ok(! ('date' in req.headers), + 'Request headers contained a Date.'); + res.writeHead(200, { + 'Content-Type': 'text/plain' + }); + res.end(testResBody); +}); +server.listen(common.PORT); + + +server.addListener('listening', function() { + var options = { + port: common.PORT, + path: '/', + method: 'GET' + }; + var req = http.request(options, function(res) { + assert.ok('date' in res.headers, + 'Response headers didn\'t contain a Date.'); + res.addListener('end', function() { + server.close(); + process.exit(); + }); + }); + req.end(); +}); diff --git a/node-v0.8.14/test/simple/test-http-default-encoding.js b/node-v0.8.14/test/simple/test-http-default-encoding.js new file mode 100644 index 0000000..4e4741a --- /dev/null +++ b/node-v0.8.14/test/simple/test-http-default-encoding.js @@ -0,0 +1,61 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var http = require('http'); + +var expected = 'This is a unicode text: سلام'; +var result = ''; + +var server = http.Server(function(req, res) { + req.setEncoding('utf8'); + req.on('data', function(chunk) { + result += chunk; + }).on('end', function() { + clearTimeout(timeout); + server.close(); + }); + + var timeout = setTimeout(function() { + process.exit(1); + }, 100); + + res.writeHead(200); + res.end('hello world\n'); +}); + +server.listen(common.PORT, function() { + http.request({ + port: common.PORT, + path: '/', + method: 'POST' + }, function(res) { + console.log(res.statusCode); + }).on('error', function(e) { + console.log(e.message); + process.exit(1); + }).end(expected); +}); + +process.on('exit', function() { + assert.equal(expected, result); +}); diff --git a/node-v0.8.14/test/simple/test-http-dns-error.js b/node-v0.8.14/test/simple/test-http-dns-error.js new file mode 100644 index 0000000..fc6d6b8 --- /dev/null +++ b/node-v0.8.14/test/simple/test-http-dns-error.js @@ -0,0 +1,68 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); + +var http = require('http'); +var https = require('https'); + +var expected_bad_requests = 0; +var actual_bad_requests = 0; + +var host = '********'; +host += host; +host += host; +host += host; +host += host; +host += host; + +function do_not_call() { + throw new Error('This function should not have been called.'); +} + +function test(mod) { + expected_bad_requests += 2; + + // Bad host name should not throw an uncatchable exception. + // Ensure that there is time to attach an error listener. + var req = mod.get({host: host, port: 42}, do_not_call); + req.on('error', function(err) { + assert.equal(err.code, 'ENOTFOUND'); + actual_bad_requests++; + }); + // http.get() called req.end() for us + + var req = mod.request({method: 'GET', host: host, port: 42}, do_not_call); + req.on('error', function(err) { + assert.equal(err.code, 'ENOTFOUND'); + actual_bad_requests++; + }); + req.end(); +} + +test(https); +test(http); + +process.on('exit', function() { + assert.equal(actual_bad_requests, expected_bad_requests); +}); + diff --git a/node-v0.8.14/test/simple/test-http-dns-fail.js b/node-v0.8.14/test/simple/test-http-dns-fail.js new file mode 100644 index 0000000..7d87b8e --- /dev/null +++ b/node-v0.8.14/test/simple/test-http-dns-fail.js @@ -0,0 +1,62 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +/* + * Repeated requests for a domain that fails to resolve + * should trigger the error event after each attempt. + */ + +var common = require('../common'); +var assert = require('assert'); +var http = require('http'); + +var resDespiteError = false; +var hadError = 0; + +function httpreq(count) { + if (1 < count) return; + + var req = http.request({ + host: 'not-a-real-domain-name.nobody-would-register-this-as-a-tld', + port: 80, + path: '/', + method: 'GET' + }, function(res) { + resDespiteError = true; + }); + + req.on('error', function(e) { + console.log(e.message); + assert.strictEqual(e.code, 'ENOTFOUND'); + hadError++; + httpreq(count + 1); + }); + + req.end(); +} + +httpreq(0); + + +process.on('exit', function() { + assert.equal(false, resDespiteError); + assert.equal(2, hadError); +}); diff --git a/node-v0.8.14/test/simple/test-http-eof-on-connect.js b/node-v0.8.14/test/simple/test-http-eof-on-connect.js new file mode 100644 index 0000000..95d6fdc --- /dev/null +++ b/node-v0.8.14/test/simple/test-http-eof-on-connect.js @@ -0,0 +1,40 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var net = require('net'); +var http = require('http'); + +// This is a regression test for https://github.com/joyent/node/issues/44 +// It is separate from test-http-malformed-request.js because it is only +// reproduceable on the first packet on the first connection to a server. + +var server = http.createServer(function(req, res) {}); +server.listen(common.PORT); + +server.on('listening', function() { + net.createConnection(common.PORT).on('connect', function() { + this.destroy(); + }).on('close', function() { + server.close(); + }); +}); diff --git a/node-v0.8.14/test/simple/test-http-exceptions.js b/node-v0.8.14/test/simple/test-http-exceptions.js new file mode 100644 index 0000000..1501d94 --- /dev/null +++ b/node-v0.8.14/test/simple/test-http-exceptions.js @@ -0,0 +1,47 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var http = require('http'); + +var server = http.createServer(function(req, res) { + intentionally_not_defined(); + res.writeHead(200, {'Content-Type': 'text/plain'}); + res.write('Thank you, come again.'); + res.end(); +}); + +server.listen(common.PORT, function() { + var req; + for (var i = 0; i < 4; i += 1) { + req = http.get({ port: common.PORT, path: '/busy/' + i }); + } +}); + +var exception_count = 0; + +process.on('uncaughtException', function(err) { + console.log('Caught an exception: ' + err); + if (err.name === 'AssertionError') throw err; + if (++exception_count == 4) process.exit(0); +}); + diff --git a/node-v0.8.14/test/simple/test-http-expect-continue.js b/node-v0.8.14/test/simple/test-http-expect-continue.js new file mode 100644 index 0000000..54c04cc --- /dev/null +++ b/node-v0.8.14/test/simple/test-http-expect-continue.js @@ -0,0 +1,88 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var http = require('http'); + +var outstanding_reqs = 0; +var test_req_body = 'some stuff...\n'; +var test_res_body = 'other stuff!\n'; +var sent_continue = false; +var got_continue = false; + +function handler(req, res) { + assert.equal(sent_continue, true, 'Full response sent before 100 Continue'); + common.debug('Server sending full response...'); + res.writeHead(200, { + 'Content-Type' : 'text/plain', + 'ABCD' : '1' + }); + res.end(test_res_body); +} + +var server = http.createServer(handler); +server.on('checkContinue', function(req, res) { + common.debug('Server got Expect: 100-continue...'); + res.writeContinue(); + sent_continue = true; + setTimeout(function() { + handler(req, res); + }, 100); +}); +server.listen(common.PORT); + + + +server.on('listening', function() { + var req = http.request({ + port: common.PORT, + method: 'POST', + path: '/world', + headers: { 'Expect': '100-continue' } + }); + common.debug('Client sending request...'); + outstanding_reqs++; + var body = ''; + req.on('continue', function() { + common.debug('Client got 100 Continue...'); + got_continue = true; + req.end(test_req_body); + }); + req.on('response', function(res) { + assert.equal(got_continue, true, + 'Full response received before 100 Continue'); + assert.equal(200, res.statusCode, + 'Final status code was ' + res.statusCode + ', not 200.'); + res.setEncoding('utf8'); + res.on('data', function(chunk) { body += chunk; }); + res.on('end', function() { + common.debug('Got full response.'); + assert.equal(body, test_res_body, 'Response body doesn\'t match.'); + assert.ok('abcd' in res.headers, 'Response headers missing.'); + outstanding_reqs--; + if (outstanding_reqs == 0) { + server.close(); + process.exit(); + } + }); + }); +}); diff --git a/node-v0.8.14/test/simple/test-http-extra-response.js b/node-v0.8.14/test/simple/test-http-extra-response.js new file mode 100644 index 0000000..1649a6a --- /dev/null +++ b/node-v0.8.14/test/simple/test-http-extra-response.js @@ -0,0 +1,86 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var http = require('http'); +var net = require('net'); + +// If an HTTP server is broken and sends data after the end of the response, +// node should ignore it and drop the connection. +// Demos this bug: https://github.com/joyent/node/issues/680 + +var body = 'hello world\r\n'; +var fullResponse = + 'HTTP/1.1 500 Internal Server Error\r\n' + + 'Content-Length: ' + body.length + '\r\n' + + 'Content-Type: text/plain\r\n' + + 'Date: Fri + 18 Feb 2011 06:22:45 GMT\r\n' + + 'Host: 10.20.149.2\r\n' + + 'Access-Control-Allow-Credentials: true\r\n' + + 'Server: badly broken/0.1 (OS NAME)\r\n' + + '\r\n' + + body; + +var gotResponse = false; + + +var server = net.createServer(function(socket) { + var postBody = ''; + + socket.setEncoding('utf8'); + + socket.on('data', function(chunk) { + postBody += chunk; + + if (postBody.indexOf('\r\n') > -1) { + socket.write(fullResponse); + // omg, I wrote the response twice, what a terrible HTTP server I am. + socket.end(fullResponse); + } + }); +}); + + +server.listen(common.PORT, function() { + http.get({ port: common.PORT }, function(res) { + var buffer = ''; + console.log('Got res code: ' + res.statusCode); + + res.setEncoding('utf8'); + res.on('data', function(chunk) { + buffer += chunk; + }); + + res.on('end', function() { + console.log('Response ended, read ' + buffer.length + ' bytes'); + assert.equal(body, buffer); + server.close(); + gotResponse = true; + }); + }); +}); + + +process.on('exit', function() { + assert.ok(gotResponse); +}); + diff --git a/node-v0.8.14/test/simple/test-http-full-response.js b/node-v0.8.14/test/simple/test-http-full-response.js new file mode 100644 index 0000000..d33df8b --- /dev/null +++ b/node-v0.8.14/test/simple/test-http-full-response.js @@ -0,0 +1,96 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + + + +var common = require('../common'); +var assert = require('assert'); +// This test requires the program 'ab' +var http = require('http'); +var exec = require('child_process').exec; + +var bodyLength = 12345; + +var body = ''; +for (var i = 0; i < bodyLength; i++) { + body += 'c'; +} + +var server = http.createServer(function(req, res) { + res.writeHead(200, { + 'Content-Length': bodyLength, + 'Content-Type': 'text/plain' + }); + res.end(body); +}); + +var runs = 0; + +function runAb(opts, callback) { + var command = 'ab ' + opts + ' http://127.0.0.1:' + common.PORT + '/'; + exec(command, function(err, stdout, stderr) { + if (err) { + if (/ab|apr/mi.test(stderr)) { + console.log('problem spawning ab - skipping test.\n' + stderr); + process.reallyExit(0); + } + process.exit(); + return; + } + + var m = /Document Length:\s*(\d+) bytes/mi.exec(stdout); + var documentLength = parseInt(m[1]); + + var m = /Complete requests:\s*(\d+)/mi.exec(stdout); + var completeRequests = parseInt(m[1]); + + var m = /HTML transferred:\s*(\d+) bytes/mi.exec(stdout); + var htmlTransfered = parseInt(m[1]); + + assert.equal(bodyLength, documentLength); + assert.equal(completeRequests * documentLength, htmlTransfered); + + runs++; + + if (callback) callback(); + }); +} + +server.listen(common.PORT, function() { + runAb('-c 1 -n 10', function() { + console.log('-c 1 -n 10 okay'); + + runAb('-c 1 -n 100', function() { + console.log('-c 1 -n 100 okay'); + + runAb('-c 1 -n 1000', function() { + console.log('-c 1 -n 1000 okay'); + server.close(); + }); + }); + }); + +}); + +process.on('exit', function() { + assert.equal(3, runs); +}); diff --git a/node-v0.8.14/test/simple/test-http-get-pipeline-problem.js b/node-v0.8.14/test/simple/test-http-get-pipeline-problem.js new file mode 100644 index 0000000..720ce4b --- /dev/null +++ b/node-v0.8.14/test/simple/test-http-get-pipeline-problem.js @@ -0,0 +1,111 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + + + +// We are demonstrating a problem with http.get when queueing up many +// transfers. The server simply introduces some delay and sends a file. +// Note this is demonstrated with connection: close. +var common = require('../common'); +var assert = require('assert'); +var http = require('http'); +var fs = require('fs'); + +var image = fs.readFileSync(common.fixturesDir + '/person.jpg'); + +console.log('image.length = ' + image.length); + +var total = 100; +var requests = 0, responses = 0; + +var server = http.Server(function(req, res) { + if (++requests == total) { + server.close(); + } + + setTimeout(function() { + res.writeHead(200, { + 'content-type': 'image/jpeg', + 'connection': 'close', + 'content-length': image.length + }); + res.end(image); + }, 1); +}); + + +server.listen(common.PORT, function() { + for (var i = 0; i < total; i++) { + (function() { + var x = i; + + var opts = { + port: common.PORT, + headers: { connection: 'close' } + }; + + http.get(opts, function(res) { + console.error('recv ' + x); + var s = fs.createWriteStream(common.tmpDir + '/' + x + '.jpg'); + res.pipe(s); + + // TODO there should be a callback to pipe() that will allow + // us to get a callback when the pipe is finished. + res.on('end', function() { + console.error('done ' + x); + if (++responses == total) { + s.on('close', checkFiles); + } + }); + }).on('error', function(e) { + console.error('error! ', e.message); + throw e; + }); + })(); + } +}); + + +var checkedFiles = false; +function checkFiles() { + // Should see 1.jpg, 2.jpg, ..., 100.jpg in tmpDir + var files = fs.readdirSync(common.tmpDir); + assert(total <= files.length); + + for (var i = 0; i < total; i++) { + var fn = i + '.jpg'; + assert.ok(files.indexOf(fn) >= 0, "couldn't find '" + fn + "'"); + var stat = fs.statSync(common.tmpDir + '/' + fn); + assert.equal(image.length, stat.size, + "size doesn't match on '" + fn + + "'. Got " + stat.size + ' bytes'); + } + + checkedFiles = true; +} + + +process.on('exit', function() { + assert.equal(total, requests); + assert.equal(total, responses); + assert.ok(checkedFiles); +}); diff --git a/node-v0.8.14/test/simple/test-http-head-request.js b/node-v0.8.14/test/simple/test-http-head-request.js new file mode 100644 index 0000000..6b6b876 --- /dev/null +++ b/node-v0.8.14/test/simple/test-http-head-request.js @@ -0,0 +1,56 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var http = require('http'); +var util = require('util'); + + +var body = 'hello world\n'; + +var server = http.createServer(function(req, res) { + common.error('req: ' + req.method); + res.writeHead(200, {'Content-Length': body.length}); + res.end(); + server.close(); +}); + +var gotEnd = false; + +server.listen(common.PORT, function() { + var request = http.request({ + port: common.PORT, + method: 'HEAD', + path: '/' + }, function(response) { + common.error('response start'); + response.on('end', function() { + common.error('response end'); + gotEnd = true; + }); + }); + request.end(); +}); + +process.on('exit', function() { + assert.ok(gotEnd); +}); diff --git a/node-v0.8.14/test/simple/test-http-head-response-has-no-body-end.js b/node-v0.8.14/test/simple/test-http-head-response-has-no-body-end.js new file mode 100644 index 0000000..8ad3bca --- /dev/null +++ b/node-v0.8.14/test/simple/test-http-head-response-has-no-body-end.js @@ -0,0 +1,61 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + + + +var common = require('../common'); +var assert = require('assert'); + +var http = require('http'); + +// This test is to make sure that when the HTTP server +// responds to a HEAD request with data to res.end, +// it does not send any body. + +var server = http.createServer(function(req, res) { + res.writeHead(200); + res.end('FAIL'); // broken: sends FAIL from hot path. +}); +server.listen(common.PORT); + +var responseComplete = false; + +server.on('listening', function() { + var req = http.request({ + port: common.PORT, + method: 'HEAD', + path: '/' + }, function(res) { + common.error('response'); + res.on('end', function() { + common.error('response end'); + server.close(); + responseComplete = true; + }); + }); + common.error('req'); + req.end(); +}); + +process.on('exit', function() { + assert.ok(responseComplete); +}); diff --git a/node-v0.8.14/test/simple/test-http-head-response-has-no-body.js b/node-v0.8.14/test/simple/test-http-head-response-has-no-body.js new file mode 100644 index 0000000..620ad75 --- /dev/null +++ b/node-v0.8.14/test/simple/test-http-head-response-has-no-body.js @@ -0,0 +1,58 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); + +var http = require('http'); + +// This test is to make sure that when the HTTP server +// responds to a HEAD request, it does not send any body. +// In this case it was sending '0\r\n\r\n' + +var server = http.createServer(function(req, res) { + res.writeHead(200); // broken: defaults to TE chunked + res.end(); +}); +server.listen(common.PORT); + +var responseComplete = false; + +server.on('listening', function() { + var req = http.request({ + port: common.PORT, + method: 'HEAD', + path: '/' + }, function(res) { + common.error('response'); + res.on('end', function() { + common.error('response end'); + server.close(); + responseComplete = true; + }); + }); + common.error('req'); + req.end(); +}); + +process.on('exit', function() { + assert.ok(responseComplete); +}); diff --git a/node-v0.8.14/test/simple/test-http-header-read.js b/node-v0.8.14/test/simple/test-http-header-read.js new file mode 100644 index 0000000..de20df6 --- /dev/null +++ b/node-v0.8.14/test/simple/test-http-header-read.js @@ -0,0 +1,52 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var http = require('http'); + +// Verify that ServerResponse.getHeader() works correctly even after +// the response header has been sent. Issue 752 on github. + +var s = http.createServer(function(req, res) { + var contentType = 'Content-Type'; + var plain = 'text/plain'; + res.setHeader(contentType, plain); + res.writeHead(200); + res.end('hello world\n'); + // This checks that after the headers have been sent, getHeader works + // and does not throw an exception (Issue 752) + assert.doesNotThrow( + function() { + assert.equal(plain, res.getHeader(contentType)); + } + ); +}); + +s.listen(common.PORT, runTest); + +function runTest() { + http.get({ port: common.PORT }, function(response) { + response.on('end', function() { + s.close(); + }); + }); +} diff --git a/node-v0.8.14/test/simple/test-http-host-headers.js b/node-v0.8.14/test/simple/test-http-host-headers.js new file mode 100644 index 0000000..2e92ae5 --- /dev/null +++ b/node-v0.8.14/test/simple/test-http-host-headers.js @@ -0,0 +1,163 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + + + +var http = require('http'), + https = require('https'), + fs = require('fs'), + common = require('../common'), + assert = require('assert'), + options = { + key: fs.readFileSync(common.fixturesDir + '/keys/agent1-key.pem'), + cert: fs.readFileSync(common.fixturesDir + '/keys/agent1-cert.pem') + }, + httpServer = http.createServer(reqHandler), + httpsServer = https.createServer(options, reqHandler); + +function reqHandler(req, res) { + console.log('Got request: ' + req.headers.host + ' ' + req.url); + if (req.url === '/setHostFalse5') { + assert.equal(req.headers.host, undefined); + } else { + assert.equal(req.headers.host, 'localhost:' + common.PORT, + 'Wrong host header for req[' + req.url + ']: ' + + req.headers.host); + } + res.writeHead(200, {}); + //process.nextTick(function() { res.end('ok'); }); + res.end('ok'); +} + +function thrower(er) { + throw er; +} + +testHttp(); + +function testHttp() { + + console.log('testing http on port ' + common.PORT); + + var counter = 0; + + function cb() { + counter--; + console.log('back from http request. counter = ' + counter); + if (counter === 0) { + httpServer.close(); + testHttps(); + } + } + + httpServer.listen(common.PORT, function(er) { + console.error('listening on ' + common.PORT); + + if (er) throw er; + + http.get({ method: 'GET', + path: '/' + (counter++), + host: 'localhost', + //agent: false, + port: common.PORT }, cb).on('error', thrower); + + http.request({ method: 'GET', + path: '/' + (counter++), + host: 'localhost', + //agent: false, + port: common.PORT }, cb).on('error', thrower).end(); + + http.request({ method: 'POST', + path: '/' + (counter++), + host: 'localhost', + //agent: false, + port: common.PORT }, cb).on('error', thrower).end(); + + http.request({ method: 'PUT', + path: '/' + (counter++), + host: 'localhost', + //agent: false, + port: common.PORT }, cb).on('error', thrower).end(); + + http.request({ method: 'DELETE', + path: '/' + (counter++), + host: 'localhost', + //agent: false, + port: common.PORT }, cb).on('error', thrower).end(); + }); +} + +function testHttps() { + + console.log('testing https on port ' + common.PORT); + + var counter = 0; + + function cb() { + counter--; + console.log('back from https request. counter = ' + counter); + if (counter === 0) { + httpsServer.close(); + console.log('ok'); + } + } + + httpsServer.listen(common.PORT, function(er) { + if (er) throw er; + + https.get({ method: 'GET', + path: '/' + (counter++), + host: 'localhost', + //agent: false, + port: common.PORT }, cb).on('error', thrower); + + https.request({ method: 'GET', + path: '/' + (counter++), + host: 'localhost', + //agent: false, + port: common.PORT }, cb).on('error', thrower).end(); + + https.request({ method: 'POST', + path: '/' + (counter++), + host: 'localhost', + //agent: false, + port: common.PORT }, cb).on('error', thrower).end(); + + https.request({ method: 'PUT', + path: '/' + (counter++), + host: 'localhost', + //agent: false, + port: common.PORT }, cb).on('error', thrower).end(); + + https.request({ method: 'DELETE', + path: '/' + (counter++), + host: 'localhost', + //agent: false, + port: common.PORT }, cb).on('error', thrower).end(); + + https.get({ method: 'GET', + path: '/setHostFalse' + (counter++), + host: 'localhost', + setHost: false, + port: common.PORT }, cb).on('error', thrower).end(); + }); +} diff --git a/node-v0.8.14/test/simple/test-http-keep-alive-close-on-header.js b/node-v0.8.14/test/simple/test-http-keep-alive-close-on-header.js new file mode 100644 index 0000000..8fd7348 --- /dev/null +++ b/node-v0.8.14/test/simple/test-http-keep-alive-close-on-header.js @@ -0,0 +1,94 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var http = require('http'); +var util = require('util'); + +var body = 'hello world\n'; +var headers = {'connection': 'keep-alive'}; + +var server = http.createServer(function(req, res) { + res.writeHead(200, {'Content-Length': body.length, 'Connection': 'close'}); + res.write(body); + res.end(); +}); + +var connectCount = 0; + + +server.listen(common.PORT, function() { + var agent = new http.Agent({ maxSockets: 1 }); + var request = http.request({ + method: 'GET', + path: '/', + headers: headers, + port: common.PORT, + agent: agent + }, function() { + assert.equal(1, agent.sockets['localhost:' + common.PORT].length); + }); + request.on('socket', function(s) { + s.on('connect', function() { + connectCount++; + }); + }); + request.end(); + + request = http.request({ + method: 'GET', + path: '/', + headers: headers, + port: common.PORT, + agent: agent + }, function() { + assert.equal(1, agent.sockets['localhost:' + common.PORT].length); + }); + request.on('socket', function(s) { + s.on('connect', function() { + connectCount++; + }); + }); + request.end(); + request = http.request({ + method: 'GET', + path: '/', + headers: headers, + port: common.PORT, + agent: agent + }, function(response) { + response.on('end', function() { + assert.equal(1, agent.sockets['localhost:' + common.PORT].length); + server.close(); + }); + }); + request.on('socket', function(s) { + s.on('connect', function() { + connectCount++; + }); + }); + request.end(); +}); + +process.on('exit', function() { + assert.equal(3, connectCount); +}); diff --git a/node-v0.8.14/test/simple/test-http-keep-alive.js b/node-v0.8.14/test/simple/test-http-keep-alive.js new file mode 100644 index 0000000..aa03639 --- /dev/null +++ b/node-v0.8.14/test/simple/test-http-keep-alive.js @@ -0,0 +1,68 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var http = require('http'); + +var body = 'hello world\n'; + +var server = http.createServer(function(req, res) { + res.writeHead(200, {'Content-Length': body.length}); + res.write(body); + res.end(); +}); + +var connectCount = 0; +var name = 'localhost:' + common.PORT; +var agent = new http.Agent({maxSockets: 1}); +var headers = {'connection': 'keep-alive'}; + +server.listen(common.PORT, function() { + http.get({ + path: '/', headers: headers, port: common.PORT, agent: agent + }, function(response) { + assert.equal(agent.sockets[name].length, 1); + assert.equal(agent.requests[name].length, 2); + }); + + http.get({ + path: '/', headers: headers, port: common.PORT, agent: agent + }, function(response) { + assert.equal(agent.sockets[name].length, 1); + assert.equal(agent.requests[name].length, 1); + }); + + http.get({ + path: '/', headers: headers, port: common.PORT, agent: agent + }, function(response) { + response.on('end', function() { + assert.equal(agent.sockets[name].length, 1); + assert(!agent.requests.hasOwnProperty(name)); + server.close(); + }); + }); +}); + +process.on('exit', function() { + assert(!agent.sockets.hasOwnProperty(name)); + assert(!agent.requests.hasOwnProperty(name)); +}); diff --git a/node-v0.8.14/test/simple/test-http-legacy.js b/node-v0.8.14/test/simple/test-http-legacy.js new file mode 100644 index 0000000..dd3eb6f --- /dev/null +++ b/node-v0.8.14/test/simple/test-http-legacy.js @@ -0,0 +1,104 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + + + +var common = require('../common'); +var assert = require('assert'); +var http = require('http'); +var url = require('url'); + +function p(x) { + common.error(common.inspect(x)); +} + +var responses_sent = 0; +var responses_recvd = 0; +var body0 = ''; +var body1 = ''; + +var server = http.createServer(function(req, res) { + if (responses_sent == 0) { + assert.equal('GET', req.method); + assert.equal('/hello', url.parse(req.url).pathname); + + console.dir(req.headers); + assert.equal(true, 'accept' in req.headers); + assert.equal('*/*', req.headers['accept']); + + assert.equal(true, 'foo' in req.headers); + assert.equal('bar', req.headers['foo']); + } + + if (responses_sent == 1) { + assert.equal('POST', req.method); + assert.equal('/world', url.parse(req.url).pathname); + this.close(); + } + + req.on('end', function() { + res.writeHead(200, {'Content-Type': 'text/plain'}); + res.write('The path was ' + url.parse(req.url).pathname); + res.end(); + responses_sent += 1; + }); + + //assert.equal('127.0.0.1', res.connection.remoteAddress); +}); + +server.listen(common.PORT, function() { + var client = http.createClient(common.PORT); + var req = client.request('/hello', {'Accept': '*/*', 'Foo': 'bar'}); + setTimeout(function() { + req.end(); + }, 100); + req.on('response', function(res) { + assert.equal(200, res.statusCode); + responses_recvd += 1; + res.setEncoding('utf8'); + res.on('data', function(chunk) { body0 += chunk; }); + common.debug('Got /hello response'); + }); + + setTimeout(function() { + var req = client.request('POST', '/world'); + req.end(); + req.on('response', function(res) { + assert.equal(200, res.statusCode); + responses_recvd += 1; + res.setEncoding('utf8'); + res.on('data', function(chunk) { body1 += chunk; }); + common.debug('Got /world response'); + }); + }, 1); +}); + +process.on('exit', function() { + common.debug('responses_recvd: ' + responses_recvd); + assert.equal(2, responses_recvd); + + common.debug('responses_sent: ' + responses_sent); + assert.equal(2, responses_sent); + + assert.equal('The path was /hello', body0); + assert.equal('The path was /world', body1); +}); diff --git a/node-v0.8.14/test/simple/test-http-localaddress-bind-error.js b/node-v0.8.14/test/simple/test-http-localaddress-bind-error.js new file mode 100644 index 0000000..0f9cdbb --- /dev/null +++ b/node-v0.8.14/test/simple/test-http-localaddress-bind-error.js @@ -0,0 +1,56 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var http = require('http'); + +var invalidLocalAddress = '1.2.3.4'; +var gotError = false; + +var server = http.createServer(function(req, res) { + console.log("Connect from: " + req.connection.remoteAddress); + + req.on('end', function() { + res.writeHead(200, { 'Content-Type': 'text/plain' }); + res.end('You are from: ' + req.connection.remoteAddress); + }); +}); + +server.listen(common.PORT, "127.0.0.1", function() { + var req = http.request({ + host: 'localhost', + port: common.PORT, + path: '/', + method: 'GET', + localAddress: invalidLocalAddress + }, function(res) { + assert.fail('unexpectedly got response from server'); + }).on('error', function(e) { + console.log('client got error: ' + e.message); + gotError = true; + server.close(); + }).end(); +}); + +process.on('exit', function() { + assert.ok(gotError); +}); diff --git a/node-v0.8.14/test/simple/test-http-localaddress.js b/node-v0.8.14/test/simple/test-http-localaddress.js new file mode 100644 index 0000000..1843d82 --- /dev/null +++ b/node-v0.8.14/test/simple/test-http-localaddress.js @@ -0,0 +1,55 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var http = require('http'), + assert = require('assert'); + +if (['linux', 'win32'].indexOf(process.platform) == -1) { + console.log('Skipping platform-specific test.'); + process.exit(); +} + +var server = http.createServer(function (req, res) { + console.log("Connect from: " + req.connection.remoteAddress); + assert.equal('127.0.0.2', req.connection.remoteAddress); + + req.on('end', function() { + res.writeHead(200, { 'Content-Type': 'text/plain' }); + res.end('You are from: ' + req.connection.remoteAddress); + }); +}); + +server.listen(common.PORT, "127.0.0.1", function() { + var options = { host: 'localhost', + port: common.PORT, + path: '/', + method: 'GET', + localAddress: '127.0.0.2' }; + + var req = http.request(options, function(res) { + res.on('end', function() { + server.close(); + process.exit(); + }); + }); + req.end(); +}); diff --git a/node-v0.8.14/test/simple/test-http-malformed-request.js b/node-v0.8.14/test/simple/test-http-malformed-request.js new file mode 100644 index 0000000..52165a2 --- /dev/null +++ b/node-v0.8.14/test/simple/test-http-malformed-request.js @@ -0,0 +1,57 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var net = require('net'); +var http = require('http'); +var url = require('url'); + +// Make sure no exceptions are thrown when receiving malformed HTTP +// requests. + +var nrequests_completed = 0; +var nrequests_expected = 1; + +var server = http.createServer(function(req, res) { + console.log('req: ' + JSON.stringify(url.parse(req.url))); + + res.writeHead(200, {'Content-Type': 'text/plain'}); + res.write('Hello World'); + res.end(); + + if (++nrequests_completed == nrequests_expected) server.close(); +}); +server.listen(common.PORT); + +server.on('listening', function() { + var c = net.createConnection(common.PORT); + c.on('connect', function() { + c.write('GET /hello?foo=%99bar HTTP/1.1\r\n\r\n'); + c.end(); + }); + + // TODO add more! +}); + +process.on('exit', function() { + assert.equal(nrequests_expected, nrequests_completed); +}); diff --git a/node-v0.8.14/test/simple/test-http-many-keep-alive-connections.js b/node-v0.8.14/test/simple/test-http-many-keep-alive-connections.js new file mode 100644 index 0000000..4714cd5 --- /dev/null +++ b/node-v0.8.14/test/simple/test-http-many-keep-alive-connections.js @@ -0,0 +1,68 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var http = require('http'); + +var expected = 10000; +var responses = 0; +var requests = 0; +var connection; + +var server = http.Server(function(req, res) { + requests++; + assert.equal(req.connection, connection); + res.writeHead(200); + res.end('hello world\n'); +}); + +server.once('connection', function(c) { + connection = c; +}); + +server.listen(common.PORT, function() { + var callee = arguments.callee; + var request = http.get({ + port: common.PORT, + path: '/', + headers: { + 'Connection': 'Keep-alive' + } + }, function(res) { + res.on('end', function() { + if (++responses < expected) { + callee(); + } else { + server.close(); + } + }); + }).on('error', function(e) { + console.log(e.message); + process.exit(1); + }); + request.agent.maxSockets = 1; +}); + +process.on('exit', function() { + assert.equal(expected, responses); + assert.equal(expected, requests); +}); diff --git a/node-v0.8.14/test/simple/test-http-max-headers-count.js b/node-v0.8.14/test/simple/test-http-max-headers-count.js new file mode 100644 index 0000000..97fce2c --- /dev/null +++ b/node-v0.8.14/test/simple/test-http-max-headers-count.js @@ -0,0 +1,87 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var http = require('http'); + +var requests = 0; +var responses = 0; + +var headers = {}; +var N = 2000; +for (var i = 0; i < N; ++i) { + headers['key' + i] = i; +} + +var maxAndExpected = [ // for server + [50, 50], + [1500, 1500], + [0, N + 2] // Host and Connection +]; +var max = maxAndExpected[requests][0]; +var expected = maxAndExpected[requests][1]; + +var server = http.createServer(function(req, res) { + assert.equal(Object.keys(req.headers).length, expected); + if (++requests < maxAndExpected.length) { + max = maxAndExpected[requests][0]; + expected = maxAndExpected[requests][1]; + server.maxHeadersCount = max; + } + res.writeHead(200, headers); + res.end(); +}); +server.maxHeadersCount = max; + +server.listen(common.PORT, function() { + var maxAndExpected = [ // for client + [20, 20], + [1200, 1200], + [0, N + 3] // Connection, Date and Transfer-Encoding + ]; + doRequest(); + + function doRequest() { + var max = maxAndExpected[responses][0]; + var expected = maxAndExpected[responses][1]; + var req = http.request({ + port: common.PORT, + headers: headers + }, function(res) { + assert.equal(Object.keys(res.headers).length, expected); + res.on('end', function() { + if (++responses < maxAndExpected.length) { + doRequest(); + } else { + server.close(); + } + }); + }); + req.maxHeadersCount = max; + req.end(); + } +}); + +process.on('exit', function() { + assert.equal(requests, maxAndExpected.length); + assert.equal(responses, maxAndExpected.length); +}); diff --git a/node-v0.8.14/test/simple/test-http-multi-line-headers.js b/node-v0.8.14/test/simple/test-http-multi-line-headers.js new file mode 100644 index 0000000..a212a04 --- /dev/null +++ b/node-v0.8.14/test/simple/test-http-multi-line-headers.js @@ -0,0 +1,59 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); + +var http = require('http'); +var net = require('net'); + +var gotResponse = false; + +var server = net.createServer(function(conn) { + var body = 'Yet another node.js server.'; + + var response = + 'HTTP/1.1 200 OK\r\n' + + 'Connection: close\r\n' + + 'Content-Length: ' + body.length + '\r\n' + + 'Content-Type: text/plain;\r\n' + + ' x-unix-mode=0600;\r\n' + + ' name=\"hello.txt\"\r\n' + + '\r\n' + + body; + + conn.write(response, function() { + conn.destroy(); + server.close(); + }); +}); + +server.listen(common.PORT, function() { + http.get({host: '127.0.0.1', port: common.PORT}, function(res) { + assert.equal(res.headers['content-type'], + 'text/plain;x-unix-mode=0600;name="hello.txt"'); + gotResponse = true; + }); +}); + +process.on('exit', function() { + assert.ok(gotResponse); +}); diff --git a/node-v0.8.14/test/simple/test-http-mutable-headers.js b/node-v0.8.14/test/simple/test-http-mutable-headers.js new file mode 100644 index 0000000..6106ac6 --- /dev/null +++ b/node-v0.8.14/test/simple/test-http-mutable-headers.js @@ -0,0 +1,153 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var http = require('http'); + +// Simple test of Node's HTTP Client mutable headers +// OutgoingMessage.prototype.setHeader(name, value) +// OutgoingMessage.prototype.getHeader(name) +// OutgoingMessage.prototype.removeHeader(name, value) +// ServerResponse.prototype.statusCode +// .method +// .path + +var testsComplete = 0; +var test = 'headers'; +var content = 'hello world\n'; +var cookies = [ + 'session_token=; path=/; expires=Sun, 15-Sep-2030 13:48:52 GMT', + 'prefers_open_id=; path=/; expires=Thu, 01-Jan-1970 00:00:00 GMT' +]; + +var s = http.createServer(function(req, res) { + switch (test) { + case 'headers': + assert.throws(function() { res.setHeader() }); + assert.throws(function() { res.setHeader('someHeader') }); + assert.throws(function() { res.getHeader() }); + assert.throws(function() { res.removeHeader() }); + + res.setHeader('x-test-header', 'testing'); + res.setHeader('X-TEST-HEADER2', 'testing'); + res.setHeader('set-cookie', cookies); + res.setHeader('x-test-array-header', [1, 2, 3]); + + var val1 = res.getHeader('x-test-header'); + var val2 = res.getHeader('x-test-header2'); + assert.equal(val1, 'testing'); + assert.equal(val2, 'testing'); + + res.removeHeader('x-test-header2'); + break; + + case 'contentLength': + res.setHeader('content-length', content.length); + assert.equal(content.length, res.getHeader('Content-Length')); + break; + + case 'transferEncoding': + res.setHeader('transfer-encoding', 'chunked'); + assert.equal(res.getHeader('Transfer-Encoding'), 'chunked'); + break; + + case 'writeHead': + res.statusCode = 404; + res.setHeader('x-foo', 'keyboard cat'); + res.writeHead(200, { 'x-foo': 'bar', 'x-bar': 'baz' }); + break; + } + + res.statusCode = 201; + res.end(content); +}); + +s.listen(common.PORT, nextTest); + + +function nextTest() { + if (test === 'end') { + return s.close(); + } + + var bufferedResponse = ''; + + http.get({ port: common.PORT }, function(response) { + console.log('TEST: ' + test); + console.log('STATUS: ' + response.statusCode); + console.log('HEADERS: '); + console.dir(response.headers); + + switch (test) { + case 'headers': + assert.equal(response.statusCode, 201); + assert.equal(response.headers['x-test-header'], + 'testing'); + assert.equal(response.headers['x-test-array-header'], + [1, 2, 3].join(', ')); + assert.deepEqual(cookies, + response.headers['set-cookie']); + assert.equal(response.headers['x-test-header2'] !== undefined, false); + // Make the next request + test = 'contentLength'; + console.log('foobar'); + break; + + case 'contentLength': + assert.equal(response.headers['content-length'], content.length); + test = 'transferEncoding'; + break; + + case 'transferEncoding': + assert.equal(response.headers['transfer-encoding'], 'chunked'); + test = 'writeHead'; + break; + + case 'writeHead': + assert.equal(response.headers['x-foo'], 'bar'); + assert.equal(response.headers['x-bar'], 'baz'); + assert.equal(200, response.statusCode); + test = 'end'; + break; + + default: + throw Error('?'); + } + + response.setEncoding('utf8'); + response.on('data', function(s) { + bufferedResponse += s; + }); + + response.on('end', function() { + assert.equal(content, bufferedResponse); + testsComplete++; + nextTest(); + }); + }); +} + + +process.on('exit', function() { + assert.equal(4, testsComplete); +}); + diff --git a/node-v0.8.14/test/simple/test-http-no-content-length.js b/node-v0.8.14/test/simple/test-http-no-content-length.js new file mode 100644 index 0000000..8c565ae --- /dev/null +++ b/node-v0.8.14/test/simple/test-http-no-content-length.js @@ -0,0 +1,46 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var net = require('net'); +var http = require('http'); + +var body = ''; + +var server = net.createServer(function(socket) { + // Neither Content-Length nor Connection + socket.end('HTTP/1.1 200 ok\r\n\r\nHello'); +}).listen(common.PORT, function() { + var req = http.get({port: common.PORT}, function(res) { + res.setEncoding('utf8'); + res.on('data', function(chunk) { + body += chunk; + }); + res.on('end', function() { + server.close(); + }); + }); +}); + +process.on('exit', function() { + assert.equal(body, 'Hello'); +}); diff --git a/node-v0.8.14/test/simple/test-http-parser-bad-ref.js b/node-v0.8.14/test/simple/test-http-parser-bad-ref.js new file mode 100644 index 0000000..4a9c705 --- /dev/null +++ b/node-v0.8.14/test/simple/test-http-parser-bad-ref.js @@ -0,0 +1,81 @@ +// Run this program with valgrind or efence with --expose_gc to expose the +// problem. + +// Flags: --expose_gc + +var common = require('../common'); +var assert = require('assert'); +var HTTPParser = process.binding('http_parser').HTTPParser; + +var headersComplete = 0; +var messagesComplete = 0; + +function flushPool() { + new Buffer(Buffer.poolSize - 1); + gc(); +} + +function demoBug(part1, part2) { + flushPool(); + + var parser = new HTTPParser('REQUEST'); + + parser.headers = []; + parser.url = ''; + + parser.onHeaders = function(headers, url) { + parser.headers = parser.headers.concat(headers); + parser.url += url; + }; + + parser.onHeadersComplete = function(info) { + headersComplete++; + console.log('url', info.url); + }; + + parser.onBody = function(b, start, len) { }; + + parser.onMessageComplete = function() { + messagesComplete++; + }; + + + // We use a function to eliminate references to the Buffer b + // We want b to be GCed. The parser will hold a bad reference to it. + (function() { + var b = Buffer(part1); + flushPool(); + + console.log('parse the first part of the message'); + parser.execute(b, 0, b.length); + })(); + + flushPool(); + + (function() { + var b = Buffer(part2); + + console.log('parse the second part of the message'); + parser.execute(b, 0, b.length); + parser.finish(); + })(); + + flushPool(); +} + + +demoBug('POST /1', '/22 HTTP/1.1\r\n' + + 'Content-Type: text/plain\r\n' + + 'Content-Length: 4\r\n\r\n' + + 'pong'); + +demoBug('POST /1/22 HTTP/1.1\r\n' + + 'Content-Type: tex', 't/plain\r\n' + + 'Content-Length: 4\r\n\r\n' + + 'pong'); + +process.on('exit', function() { + assert.equal(2, headersComplete); + assert.equal(2, messagesComplete); + console.log('done!'); +}); diff --git a/node-v0.8.14/test/simple/test-http-parser-free.js b/node-v0.8.14/test/simple/test-http-parser-free.js new file mode 100644 index 0000000..bbf4a50 --- /dev/null +++ b/node-v0.8.14/test/simple/test-http-parser-free.js @@ -0,0 +1,54 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var http = require('http'); +var N = 100; +var responses = 0; + +var server = http.createServer(function(req, res) { + res.end('Hello'); +}); + +server.listen(common.PORT, function() { + http.globalAgent.maxSockets = 1; + var parser; + for (var i = 0; i < N; ++i) { + (function makeRequest(i) { + var req = http.get({port: common.PORT}, function(res) { + if (!parser) { + parser = req.parser; + } else { + assert.strictEqual(req.parser, parser); + } + + if (++responses === N) { + server.close(); + } + }); + })(i); + } +}); + +process.on('exit', function() { + assert.equal(responses, N); +}); diff --git a/node-v0.8.14/test/simple/test-http-parser.js b/node-v0.8.14/test/simple/test-http-parser.js new file mode 100644 index 0000000..e8c8095 --- /dev/null +++ b/node-v0.8.14/test/simple/test-http-parser.js @@ -0,0 +1,549 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); + +var HTTPParser = process.binding('http_parser').HTTPParser; + +var CRLF = '\r\n'; +var REQUEST = HTTPParser.REQUEST; +var RESPONSE = HTTPParser.RESPONSE; + +// The purpose of this test is not to check HTTP compliance but to test the +// binding. Tests for pathological http messages should be submitted +// upstream to https://github.com/joyent/http-parser for inclusion into +// deps/http-parser/test.c + + +function newParser(type) { + var parser = new HTTPParser(type); + + parser.headers = []; + parser.url = ''; + + parser.onHeaders = function(headers, url) { + parser.headers = parser.headers.concat(headers); + parser.url += url; + }; + + parser.onHeadersComplete = function(info) { + }; + + parser.onBody = function(b, start, len) { + assert.ok(false, 'Function should not be called.'); + }; + + parser.onMessageComplete = function() { + }; + + return parser; +} + + +function mustCall(f, times) { + var actual = 0; + + process.setMaxListeners(256); + process.on('exit', function() { + assert.equal(actual, times || 1); + }); + + return function() { + actual++; + return f.apply(this, Array.prototype.slice.call(arguments)); + }; +} + + +function expectBody(expected) { + return mustCall(function(buf, start, len) { + var body = '' + buf.slice(start, start + len); + assert.equal(body, expected); + }); +} + + +// +// Simple request test. +// +(function() { + var request = Buffer( + 'GET /hello HTTP/1.1' + CRLF + + CRLF); + + var parser = newParser(REQUEST); + + parser.onHeadersComplete = mustCall(function(info) { + assert.equal(info.method, 'GET'); + assert.equal(info.url || parser.url, '/hello'); + assert.equal(info.versionMajor, 1); + assert.equal(info.versionMinor, 1); + }); + + parser.execute(request, 0, request.length); + + // + // Check that if we throw an error in the callbacks that error will be + // thrown from parser.execute() + // + + parser.onHeadersComplete = function(info) { + throw new Error('hello world'); + }; + + parser.reinitialize(HTTPParser.REQUEST); + + assert.throws(function() { + parser.execute(request, 0, request.length); + }, Error, 'hello world'); +})(); + + +// +// Simple response test. +// +(function() { + var request = Buffer( + 'HTTP/1.1 200 OK' + CRLF + + 'Content-Type: text/plain' + CRLF + + 'Content-Length: 4' + CRLF + + CRLF + + 'pong'); + + var parser = newParser(RESPONSE); + + parser.onHeadersComplete = mustCall(function(info) { + assert.equal(info.method, undefined); + assert.equal(info.versionMajor, 1); + assert.equal(info.versionMinor, 1); + assert.equal(info.statusCode, 200); + }); + + parser.onBody = mustCall(function(buf, start, len) { + var body = '' + buf.slice(start, start + len); + assert.equal(body, 'pong'); + }); + + parser.execute(request, 0, request.length); +})(); + + +// +// Response with no headers. +// +(function() { + var request = Buffer( + 'HTTP/1.0 200 Connection established' + CRLF + + CRLF); + + var parser = newParser(RESPONSE); + + parser.onHeadersComplete = mustCall(function(info) { + assert.equal(info.method, undefined); + assert.equal(info.versionMajor, 1); + assert.equal(info.versionMinor, 0); + assert.equal(info.statusCode, 200); + assert.deepEqual(info.headers || parser.headers, []); + }); + + parser.execute(request, 0, request.length); +})(); + + +// +// Trailing headers. +// +(function() { + var request = Buffer( + 'POST /it HTTP/1.1' + CRLF + + 'Transfer-Encoding: chunked' + CRLF + + CRLF + + '4' + CRLF + + 'ping' + CRLF + + '0' + CRLF + + 'Vary: *' + CRLF + + 'Content-Type: text/plain' + CRLF + + CRLF); + + var seen_body = false; + + function onHeaders(headers, url) { + assert.ok(seen_body); // trailers should come after the body + assert.deepEqual(headers, + ['Vary', '*', 'Content-Type', 'text/plain']); + } + + var parser = newParser(REQUEST); + + parser.onHeadersComplete = mustCall(function(info) { + assert.equal(info.method, 'POST'); + assert.equal(info.url || parser.url, '/it'); + assert.equal(info.versionMajor, 1); + assert.equal(info.versionMinor, 1); + // expect to see trailing headers now + parser.onHeaders = mustCall(onHeaders); + }); + + parser.onBody = mustCall(function(buf, start, len) { + var body = '' + buf.slice(start, start + len); + assert.equal(body, 'ping'); + seen_body = true; + }); + + parser.execute(request, 0, request.length); +})(); + + +// +// Test header ordering. +// +(function() { + var request = Buffer( + 'GET / HTTP/1.0' + CRLF + + 'X-Filler: 1337' + CRLF + + 'X-Filler: 42' + CRLF + + 'X-Filler2: 42' + CRLF + + CRLF); + + var parser = newParser(REQUEST); + + parser.onHeadersComplete = mustCall(function(info) { + assert.equal(info.method, 'GET'); + assert.equal(info.versionMajor, 1); + assert.equal(info.versionMinor, 0); + assert.deepEqual(info.headers || parser.headers, + ['X-Filler', '1337', + 'X-Filler', '42', + 'X-Filler2', '42']); + }); + + parser.execute(request, 0, request.length); +})(); + + +// +// Test large number of headers +// +(function() { + // 256 X-Filler headers + var lots_of_headers = 'X-Filler: 42' + CRLF; + for (var i = 0; i < 8; ++i) lots_of_headers += lots_of_headers; + + var request = Buffer( + 'GET /foo/bar/baz?quux=42#1337 HTTP/1.0' + CRLF + + lots_of_headers + + CRLF); + + var parser = newParser(REQUEST); + + parser.onHeadersComplete = mustCall(function(info) { + assert.equal(info.method, 'GET'); + assert.equal(info.url || parser.url, '/foo/bar/baz?quux=42#1337'); + assert.equal(info.versionMajor, 1); + assert.equal(info.versionMinor, 0); + + var headers = info.headers || parser.headers; + + assert.equal(headers.length, 2 * 256); // 256 key/value pairs + for (var i = 0; i < headers.length; i += 2) { + assert.equal(headers[i], 'X-Filler'); + assert.equal(headers[i + 1], '42'); + } + }); + + parser.execute(request, 0, request.length); +})(); + + +// +// Test request body +// +(function() { + var request = Buffer( + 'POST /it HTTP/1.1' + CRLF + + 'Content-Type: application/x-www-form-urlencoded' + CRLF + + 'Content-Length: 15' + CRLF + + CRLF + + 'foo=42&bar=1337'); + + var parser = newParser(REQUEST); + + parser.onHeadersComplete = mustCall(function(info) { + assert.equal(info.method, 'POST'); + assert.equal(info.url || parser.url, '/it'); + assert.equal(info.versionMajor, 1); + assert.equal(info.versionMinor, 1); + }); + + parser.onBody = mustCall(function(buf, start, len) { + var body = '' + buf.slice(start, start + len); + assert.equal(body, 'foo=42&bar=1337'); + }); + + parser.execute(request, 0, request.length); +})(); + + +// +// Test chunked request body +// +(function() { + var request = Buffer( + 'POST /it HTTP/1.1' + CRLF + + 'Content-Type: text/plain' + CRLF + + 'Transfer-Encoding: chunked' + CRLF + + CRLF + + '3' + CRLF + + '123' + CRLF + + '6' + CRLF + + '123456' + CRLF + + 'A' + CRLF + + '1234567890' + CRLF + + '0' + CRLF); + + var parser = newParser(REQUEST); + + parser.onHeadersComplete = mustCall(function(info) { + assert.equal(info.method, 'POST'); + assert.equal(info.url || parser.url, '/it'); + assert.equal(info.versionMajor, 1); + assert.equal(info.versionMinor, 1); + }); + + var body_part = 0, + body_parts = ['123', '123456', '1234567890']; + + function onBody(buf, start, len) { + var body = '' + buf.slice(start, start + len); + assert.equal(body, body_parts[body_part++]); + } + + parser.onBody = mustCall(onBody, body_parts.length); + parser.execute(request, 0, request.length); +})(); + + +// +// Test chunked request body spread over multiple buffers (packets) +// +(function() { + var request = Buffer( + 'POST /it HTTP/1.1' + CRLF + + 'Content-Type: text/plain' + CRLF + + 'Transfer-Encoding: chunked' + CRLF + + CRLF + + '3' + CRLF + + '123' + CRLF + + '6' + CRLF + + '123456' + CRLF); + + var parser = newParser(REQUEST); + + parser.onHeadersComplete = mustCall(function(info) { + assert.equal(info.method, 'POST'); + assert.equal(info.url || parser.url, '/it'); + assert.equal(info.versionMajor, 1); + assert.equal(info.versionMinor, 1); + }); + + var body_part = 0, + body_parts = [ + '123', '123456', '123456789', + '123456789ABC', '123456789ABCDEF']; + + function onBody(buf, start, len) { + var body = '' + buf.slice(start, start + len); + assert.equal(body, body_parts[body_part++]); + } + + parser.onBody = mustCall(onBody, body_parts.length); + parser.execute(request, 0, request.length); + + request = Buffer( + '9' + CRLF + + '123456789' + CRLF + + 'C' + CRLF + + '123456789ABC' + CRLF + + 'F' + CRLF + + '123456789ABCDEF' + CRLF + + '0' + CRLF); + + parser.execute(request, 0, request.length); +})(); + + +// +// Stress test. +// +(function() { + var request = Buffer( + 'POST /helpme HTTP/1.1' + CRLF + + 'Content-Type: text/plain' + CRLF + + 'Transfer-Encoding: chunked' + CRLF + + CRLF + + '3' + CRLF + + '123' + CRLF + + '6' + CRLF + + '123456' + CRLF + + '9' + CRLF + + '123456789' + CRLF + + 'C' + CRLF + + '123456789ABC' + CRLF + + 'F' + CRLF + + '123456789ABCDEF' + CRLF + + '0' + CRLF); + + function test(a, b) { + var parser = newParser(REQUEST); + + parser.onHeadersComplete = mustCall(function(info) { + assert.equal(info.method, 'POST'); + assert.equal(info.url || parser.url, '/helpme'); + assert.equal(info.versionMajor, 1); + assert.equal(info.versionMinor, 1); + }); + + var expected_body = '123123456123456789123456789ABC123456789ABCDEF'; + + parser.onBody = function(buf, start, len) { + var chunk = '' + buf.slice(start, start + len); + assert.equal(expected_body.indexOf(chunk), 0); + expected_body = expected_body.slice(chunk.length); + }; + + parser.execute(a, 0, a.length); + parser.execute(b, 0, b.length); + + assert.equal(expected_body, ''); + } + + for (var i = 1; i < request.length - 1; ++i) { + var a = request.slice(0, i); + console.error('request.slice(0, ' + i + ') = ', + JSON.stringify(a.toString())); + var b = request.slice(i); + console.error('request.slice(' + i + ') = ', + JSON.stringify(b.toString())); + test(a, b); + } +})(); + + +// +// Byte by byte test. +// +(function() { + var request = Buffer( + 'POST /it HTTP/1.1' + CRLF + + 'Content-Type: text/plain' + CRLF + + 'Transfer-Encoding: chunked' + CRLF + + CRLF + + '3' + CRLF + + '123' + CRLF + + '6' + CRLF + + '123456' + CRLF + + '9' + CRLF + + '123456789' + CRLF + + 'C' + CRLF + + '123456789ABC' + CRLF + + 'F' + CRLF + + '123456789ABCDEF' + CRLF + + '0' + CRLF); + + var parser = newParser(REQUEST); + + parser.onHeadersComplete = mustCall(function(info) { + assert.equal(info.method, 'POST'); + assert.equal(info.url || parser.url, '/it'); + assert.equal(info.versionMajor, 1); + assert.equal(info.versionMinor, 1); + assert.deepEqual(info.headers || parser.headers, + ['Content-Type', 'text/plain', + 'Transfer-Encoding', 'chunked']); + }); + + var expected_body = '123123456123456789123456789ABC123456789ABCDEF'; + + parser.onBody = function(buf, start, len) { + var chunk = '' + buf.slice(start, start + len); + assert.equal(expected_body.indexOf(chunk), 0); + expected_body = expected_body.slice(chunk.length); + }; + + for (var i = 0; i < request.length; ++i) { + parser.execute(request, i, 1); + } + + assert.equal(expected_body, ''); +})(); + + +// +// Test parser reinit sequence. +// +(function() { + var req1 = Buffer( + 'PUT /this HTTP/1.1' + CRLF + + 'Content-Type: text/plain' + CRLF + + 'Transfer-Encoding: chunked' + CRLF + + CRLF + + '4' + CRLF + + 'ping' + CRLF + + '0' + CRLF); + + var req2 = Buffer( + 'POST /that HTTP/1.0' + CRLF + + 'Content-Type: text/plain' + CRLF + + 'Content-Length: 4' + CRLF + + CRLF + + 'pong'); + + function onHeadersComplete1(info) { + assert.equal(info.method, 'PUT'); + assert.equal(info.url, '/this'); + assert.equal(info.versionMajor, 1); + assert.equal(info.versionMinor, 1); + assert.deepEqual(info.headers, + ['Content-Type', 'text/plain', + 'Transfer-Encoding', 'chunked']); + }; + + function onHeadersComplete2(info) { + assert.equal(info.method, 'POST'); + assert.equal(info.url, '/that'); + assert.equal(info.versionMajor, 1); + assert.equal(info.versionMinor, 0); + assert.deepEqual(info.headers, + ['Content-Type', 'text/plain', + 'Content-Length', '4']); + }; + + var parser = newParser(REQUEST); + parser.onHeadersComplete = onHeadersComplete1; + parser.onBody = expectBody('ping'); + parser.execute(req1, 0, req1.length); + + parser.reinitialize(REQUEST); + parser.onBody = expectBody('pong'); + parser.onHeadersComplete = onHeadersComplete2; + parser.execute(req2, 0, req2.length); +})(); diff --git a/node-v0.8.14/test/simple/test-http-pause-resume-one-end.js b/node-v0.8.14/test/simple/test-http-pause-resume-one-end.js new file mode 100644 index 0000000..d5a4cb9 --- /dev/null +++ b/node-v0.8.14/test/simple/test-http-pause-resume-one-end.js @@ -0,0 +1,58 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var http = require('http'); + +var server = http.Server(function(req, res) { + res.writeHead(200, {'Content-Type': 'text/plain'}); + res.end('Hello World\n'); + server.close(); +}); + + +var dataCount = 0, endCount = 0; + +server.listen(common.PORT, function() { + var opts = { + port: common.PORT, + headers: { connection: 'close' } + }; + + http.get(opts, function(res) { + res.on('data', function(chunk) { + dataCount++; + res.pause(); + }); + + res.on('end', function() { + endCount++; + res.resume(); + }); + }); +}); + + +process.on('exit', function() { + assert.equal(1, dataCount); + assert.equal(1, endCount); +}); diff --git a/node-v0.8.14/test/simple/test-http-pause.js b/node-v0.8.14/test/simple/test-http-pause.js new file mode 100644 index 0000000..0edf6d6 --- /dev/null +++ b/node-v0.8.14/test/simple/test-http-pause.js @@ -0,0 +1,75 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var http = require('http'); + +var expectedServer = 'Request Body from Client'; +var resultServer = ''; +var expectedClient = 'Response Body from Server'; +var resultClient = ''; + +var server = http.createServer(function(req, res) { + common.debug('pause server request'); + req.pause(); + setTimeout(function() { + common.debug('resume server request'); + req.resume(); + req.setEncoding('utf8'); + req.on('data', function(chunk) { + resultServer += chunk; + }); + req.on('end', function() { + common.debug(resultServer); + res.writeHead(200); + res.end(expectedClient); + }); + }, 100); +}); + +server.listen(common.PORT, function() { + var req = http.request({ + port: common.PORT, + path: '/', + method: 'POST' + }, function(res) { + common.debug('pause client response'); + res.pause(); + setTimeout(function() { + common.debug('resume client response'); + res.resume(); + res.on('data', function(chunk) { + resultClient += chunk; + }); + res.on('end', function() { + common.debug(resultClient); + server.close(); + }); + }, 100); + }); + req.end(expectedServer); +}); + +process.on('exit', function() { + assert.equal(expectedServer, resultServer); + assert.equal(expectedClient, resultClient); +}); diff --git a/node-v0.8.14/test/simple/test-http-pipe-fs.js b/node-v0.8.14/test/simple/test-http-pipe-fs.js new file mode 100644 index 0000000..bc033fe --- /dev/null +++ b/node-v0.8.14/test/simple/test-http-pipe-fs.js @@ -0,0 +1,68 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var http = require('http'); +var fs = require('fs'); +var path = require('path'); + +var file = path.join(common.tmpDir, 'http-pipe-fs-test.txt'); +var requests = 0; + +var server = http.createServer(function(req, res) { + ++requests; + var stream = fs.createWriteStream(file); + req.pipe(stream); + stream.on('close', function() { + res.writeHead(200); + res.end(); + }); +}).listen(common.PORT, function() { + http.globalAgent.maxSockets = 1; + + for (var i = 0; i < 2; ++i) { + (function(i) { + var req = http.request({ + port: common.PORT, + method: 'POST', + headers: { + 'Content-Length': 5 + } + }, function(res) { + res.on('end', function() { + common.debug('res' + i + ' end'); + if (i === 2) { + server.close(); + } + }); + }); + req.on('socket', function(s) { + common.debug('req' + i + ' start'); + }); + req.end('12345'); + }(i + 1)); + } +}); + +process.on('exit', function() { + assert.equal(requests, 2); +}); diff --git a/node-v0.8.14/test/simple/test-http-proxy.js b/node-v0.8.14/test/simple/test-http-proxy.js new file mode 100644 index 0000000..099afb9 --- /dev/null +++ b/node-v0.8.14/test/simple/test-http-proxy.js @@ -0,0 +1,109 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var http = require('http'); +var url = require('url'); + +var PROXY_PORT = common.PORT; +var BACKEND_PORT = common.PORT + 1; + +var cookies = [ + 'session_token=; path=/; expires=Sun, 15-Sep-2030 13:48:52 GMT', + 'prefers_open_id=; path=/; expires=Thu, 01-Jan-1970 00:00:00 GMT' +]; + +var headers = {'content-type': 'text/plain', + 'set-cookie': cookies, + 'hello': 'world' }; + +var backend = http.createServer(function(req, res) { + common.debug('backend request'); + res.writeHead(200, headers); + res.write('hello world\n'); + res.end(); +}); + +var proxy = http.createServer(function(req, res) { + common.debug('proxy req headers: ' + JSON.stringify(req.headers)); + var proxy_req = http.get({ + port: BACKEND_PORT, + path: url.parse(req.url).pathname + }, function(proxy_res) { + + common.debug('proxy res headers: ' + JSON.stringify(proxy_res.headers)); + + assert.equal('world', proxy_res.headers['hello']); + assert.equal('text/plain', proxy_res.headers['content-type']); + assert.deepEqual(cookies, proxy_res.headers['set-cookie']); + + res.writeHead(proxy_res.statusCode, proxy_res.headers); + + proxy_res.on('data', function(chunk) { + res.write(chunk); + }); + + proxy_res.on('end', function() { + res.end(); + common.debug('proxy res'); + }); + }); +}); + +var body = ''; + +var nlistening = 0; +function startReq() { + nlistening++; + if (nlistening < 2) return; + + var client = http.get({ + port: PROXY_PORT, + path: '/test' + }, function(res) { + common.debug('got res'); + assert.equal(200, res.statusCode); + + assert.equal('world', res.headers['hello']); + assert.equal('text/plain', res.headers['content-type']); + assert.deepEqual(cookies, res.headers['set-cookie']); + + res.setEncoding('utf8'); + res.on('data', function(chunk) { body += chunk; }); + res.on('end', function() { + proxy.close(); + backend.close(); + common.debug('closed both'); + }); + }); + common.debug('client req'); +} + +common.debug('listen proxy'); +proxy.listen(PROXY_PORT, startReq); + +common.debug('listen backend'); +backend.listen(BACKEND_PORT, startReq); + +process.on('exit', function() { + assert.equal(body, 'hello world\n'); +}); diff --git a/node-v0.8.14/test/simple/test-http-request-end-twice.js b/node-v0.8.14/test/simple/test-http-request-end-twice.js new file mode 100644 index 0000000..f33cc6d --- /dev/null +++ b/node-v0.8.14/test/simple/test-http-request-end-twice.js @@ -0,0 +1,41 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + + + +var common = require('../common'); +var assert = require('assert'); +var http = require('http'); + +var server = http.Server(function(req, res) { + res.writeHead(200, {'Content-Type': 'text/plain'}); + res.end('hello world\n'); +}); +server.listen(common.PORT, function() { + var req = http.get({port: common.PORT}, function(res) { + res.on('end', function() { + assert.ok(!req.end()); + server.close(); + }); + }); +}); + diff --git a/node-v0.8.14/test/simple/test-http-request-end.js b/node-v0.8.14/test/simple/test-http-request-end.js new file mode 100644 index 0000000..f5da0fa --- /dev/null +++ b/node-v0.8.14/test/simple/test-http-request-end.js @@ -0,0 +1,58 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var http = require('http'); + +var expected = 'Post Body For Test'; +var result = ''; + +var server = http.Server(function(req, res) { + req.setEncoding('utf8'); + req.on('data', function(chunk) { + result += chunk; + }); + + req.on('end', function() { + server.close(); + }); + + res.writeHead(200); + res.end('hello world\n'); +}); + +server.listen(common.PORT, function() { + http.request({ + port: common.PORT, + path: '/', + method: 'POST' + }, function(res) { + console.log(res.statusCode); + }).on('error', function(e) { + console.log(e.message); + process.exit(1); + }).end(expected); +}); + +process.on('exit', function() { + assert.equal(expected, result); +}); diff --git a/node-v0.8.14/test/simple/test-http-request-methods.js b/node-v0.8.14/test/simple/test-http-request-methods.js new file mode 100644 index 0000000..f0be3a0 --- /dev/null +++ b/node-v0.8.14/test/simple/test-http-request-methods.js @@ -0,0 +1,72 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var net = require('net'); +var http = require('http'); + +// Test that the PATCH and PURGE verbs get passed through correctly + +['PATCH', 'PURGE'].forEach(function(method, index) { + var port = common.PORT + index; + + var server_response = ''; + var received_method = null; + + var server = http.createServer(function(req, res) { + received_method = req.method; + res.writeHead(200, {'Content-Type': 'text/plain'}); + res.write('hello '); + res.write('world\n'); + res.end(); + }); + server.listen(port); + + server.on('listening', function() { + var c = net.createConnection(port); + + c.setEncoding('utf8'); + + c.on('connect', function() { + c.write(method + ' / HTTP/1.0\r\n\r\n'); + }); + + c.on('data', function(chunk) { + console.log(chunk); + server_response += chunk; + }); + + c.on('end', function() { + c.end(); + }); + + c.on('close', function() { + server.close(); + }); + }); + + process.on('exit', function() { + var m = server_response.split('\r\n\r\n'); + assert.equal(m[1], 'hello world\n'); + assert.equal(received_method, method); + }); +}); diff --git a/node-v0.8.14/test/simple/test-http-res-write-end-dont-take-array.js b/node-v0.8.14/test/simple/test-http-res-write-end-dont-take-array.js new file mode 100644 index 0000000..f4b3f8c --- /dev/null +++ b/node-v0.8.14/test/simple/test-http-res-write-end-dont-take-array.js @@ -0,0 +1,64 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var http = require('http'); + +var test = 1; + +var server = http.createServer(function(req, res) { + res.writeHead(200, {'Content-Type': 'text/plain'}); + if (test === 1) { + // write should accept string + res.write('string'); + // write should accept buffer + res.write(new Buffer('asdf')); + + // write should not accept an Array + assert.throws(function() { + res.write(['array']); + }, TypeError, 'first argument must be a string or Buffer'); + + // end should not accept an Array + assert.throws(function() { + res.end(['moo']); + }, TypeError, 'first argument must be a string or Buffer'); + + // end should accept string + res.end('string'); + } else if (test === 2) { + // end should accept Buffer + res.end(new Buffer('asdf')); + } +}); + +server.listen(common.PORT, function() { + // just make a request, other tests handle responses + http.get({port: common.PORT}, function() { + // lazy serial test, becuase we can only call end once per request + test += 1; + // do it again to test .end(Buffer); + http.get({port: common.PORT}, function() { + server.close(); + }); + }); +}); diff --git a/node-v0.8.14/test/simple/test-http-response-close.js b/node-v0.8.14/test/simple/test-http-response-close.js new file mode 100644 index 0000000..be89682 --- /dev/null +++ b/node-v0.8.14/test/simple/test-http-response-close.js @@ -0,0 +1,61 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var http = require('http'); + +var requestGotEnd = false; +var responseGotEnd = false; + +var server = http.createServer(function(req, res) { + res.writeHead(200); + res.write('a'); + + req.on('close', function() { + console.error('request aborted'); + requestGotEnd = true; + }); + res.on('close', function() { + console.error('response aborted'); + responseGotEnd = true; + }); +}); +server.listen(common.PORT); + +server.on('listening', function() { + console.error('make req'); + http.get({ + port: common.PORT + }, function(res) { + console.error('got res'); + res.on('data', function(data) { + console.error('destroy res'); + res.destroy(); + server.close(); + }); + }); +}); + +process.on('exit', function() { + assert.ok(requestGotEnd); + assert.ok(responseGotEnd); +}); diff --git a/node-v0.8.14/test/simple/test-http-response-no-headers.js b/node-v0.8.14/test/simple/test-http-response-no-headers.js new file mode 100644 index 0000000..cc5250d --- /dev/null +++ b/node-v0.8.14/test/simple/test-http-response-no-headers.js @@ -0,0 +1,80 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var http = require('http'); +var net = require('net'); + +var expected = { + '0.9': 'I AM THE WALRUS', + '1.0': 'I AM THE WALRUS', + '1.1': '' +}; + +var gotExpected = false; + +function test(httpVersion, callback) { + process.on('exit', function() { + assert(gotExpected); + }); + + var server = net.createServer(function(conn) { + var reply = 'HTTP/' + httpVersion + ' 200 OK\r\n\r\n' + + expected[httpVersion]; + + conn.write(reply, function() { + conn.destroy(); + }); + }); + + server.listen(common.PORT, '127.0.0.1', function() { + var options = { + host: '127.0.0.1', + port: common.PORT + }; + + var req = http.get(options, function(res) { + var body = ''; + + res.on('data', function(data) { + body += data; + }); + + res.on('end', function() { + assert.equal(body, expected[httpVersion]); + gotExpected = true; + server.close(); + if (callback) process.nextTick(callback); + }); + }); + + req.on('error', function(err) { + throw err; + }); + }); +} + +test('0.9', function() { + test('1.0', function() { + test('1.1'); + }); +}); diff --git a/node-v0.8.14/test/simple/test-http-response-readable.js b/node-v0.8.14/test/simple/test-http-response-readable.js new file mode 100644 index 0000000..b31fcc3 --- /dev/null +++ b/node-v0.8.14/test/simple/test-http-response-readable.js @@ -0,0 +1,40 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var http = require('http'); + +var testServer = new http.Server(function(req, res) { + res.writeHead(200); + res.end('Hello world'); +}); + +testServer.listen(common.PORT, function() { + http.get({ port: common.PORT }, function(res) { + assert.equal(res.readable, true, 'res.readable initially true'); + res.on('end', function() { + assert.equal(res.readable, false, 'res.readable set to false after end'); + testServer.close(); + }); + }); +}); + diff --git a/node-v0.8.14/test/simple/test-http-server-multiheaders.js b/node-v0.8.14/test/simple/test-http-server-multiheaders.js new file mode 100644 index 0000000..b287169 --- /dev/null +++ b/node-v0.8.14/test/simple/test-http-server-multiheaders.js @@ -0,0 +1,74 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// Verify that the HTTP server implementation handles multiple instances +// of the same header as per RFC2616: joining the handful of fields by ', ' +// that support it, and dropping duplicates for other fields. + +var common = require('../common'); +var assert = require('assert'); +var http = require('http'); + +var srv = http.createServer(function(req, res) { + assert.equal(req.headers.accept, 'abc, def, ghijklmnopqrst'); + assert.equal(req.headers.host, 'foo'); + assert.equal(req.headers['www-authenticate'], 'foo, bar, baz'); + assert.equal(req.headers['proxy-authenticate'], 'foo, bar, baz'); + assert.equal(req.headers['x-foo'], 'bingo'); + assert.equal(req.headers['x-bar'], 'banjo, bango'); + assert.equal(req.headers['sec-websocket-protocol'], 'chat, share'); + assert.equal(req.headers['sec-websocket-extensions'], 'foo; 1, bar; 2, baz'); + + res.writeHead(200, {'Content-Type' : 'text/plain'}); + res.end('EOF'); + + srv.close(); +}); + +srv.listen(common.PORT, function() { + http.get({ + host: 'localhost', + port: common.PORT, + path: '/', + headers: [ + ['accept', 'abc'], + ['accept', 'def'], + ['Accept', 'ghijklmnopqrst'], + ['host', 'foo'], + ['Host', 'bar'], + ['hOst', 'baz'], + ['www-authenticate', 'foo'], + ['WWW-Authenticate', 'bar'], + ['WWW-AUTHENTICATE', 'baz'], + ['proxy-authenticate','foo'], + ['Proxy-Authenticate','bar'], + ['PROXY-AUTHENTICATE','baz'], + ['x-foo', 'bingo'], + ['x-bar', 'banjo'], + ['x-bar', 'bango'], + ['sec-websocket-protocol', 'chat'], + ['sec-websocket-protocol', 'share'], + ['sec-websocket-extensions', 'foo; 1'], + ['sec-websocket-extensions', 'bar; 2'], + ['sec-websocket-extensions', 'baz'] + ] + }); +}); diff --git a/node-v0.8.14/test/simple/test-http-server.js b/node-v0.8.14/test/simple/test-http-server.js new file mode 100644 index 0000000..7d97382 --- /dev/null +++ b/node-v0.8.14/test/simple/test-http-server.js @@ -0,0 +1,128 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var net = require('net'); +var http = require('http'); +var url = require('url'); +var qs = require('querystring'); + +var request_number = 0; +var requests_sent = 0; +var server_response = ''; +var client_got_eof = false; + +var server = http.createServer(function(req, res) { + res.id = request_number; + req.id = request_number++; + + if (req.id == 0) { + assert.equal('GET', req.method); + assert.equal('/hello', url.parse(req.url).pathname); + assert.equal('world', qs.parse(url.parse(req.url).query).hello); + assert.equal('b==ar', qs.parse(url.parse(req.url).query).foo); + } + + if (req.id == 1) { + common.error('req 1'); + assert.equal('POST', req.method); + assert.equal('/quit', url.parse(req.url).pathname); + } + + if (req.id == 2) { + common.error('req 2'); + assert.equal('foo', req.headers['x-x']); + } + + if (req.id == 3) { + common.error('req 3'); + assert.equal('bar', req.headers['x-x']); + this.close(); + common.error('server closed'); + } + + setTimeout(function() { + res.writeHead(200, {'Content-Type': 'text/plain'}); + res.write(url.parse(req.url).pathname); + res.end(); + }, 1); + +}); +server.listen(common.PORT); + +server.httpAllowHalfOpen = true; + +server.on('listening', function() { + var c = net.createConnection(common.PORT); + + c.setEncoding('utf8'); + + c.on('connect', function() { + c.write('GET /hello?hello=world&foo=b==ar HTTP/1.1\r\n\r\n'); + requests_sent += 1; + }); + + c.on('data', function(chunk) { + server_response += chunk; + + if (requests_sent == 1) { + c.write('POST /quit HTTP/1.1\r\n\r\n'); + requests_sent += 1; + } + + if (requests_sent == 2) { + c.write('GET / HTTP/1.1\r\nX-X: foo\r\n\r\n' + + 'GET / HTTP/1.1\r\nX-X: bar\r\n\r\n'); + // Note: we are making the connection half-closed here + // before we've gotten the response from the server. This + // is a pretty bad thing to do and not really supported + // by many http servers. Node supports it optionally if + // you set server.httpAllowHalfOpen=true, which we've done + // above. + c.end(); + assert.equal(c.readyState, 'readOnly'); + requests_sent += 2; + } + + }); + + c.on('end', function() { + client_got_eof = true; + }); + + c.on('close', function() { + assert.equal(c.readyState, 'closed'); + }); +}); + +process.on('exit', function() { + assert.equal(4, request_number); + assert.equal(4, requests_sent); + + var hello = new RegExp('/hello'); + assert.equal(true, hello.exec(server_response) != null); + + var quit = new RegExp('/quit'); + assert.equal(true, quit.exec(server_response) != null); + + assert.equal(true, client_got_eof); +}); diff --git a/node-v0.8.14/test/simple/test-http-set-cookies.js b/node-v0.8.14/test/simple/test-http-set-cookies.js new file mode 100644 index 0000000..bff34d8 --- /dev/null +++ b/node-v0.8.14/test/simple/test-http-set-cookies.js @@ -0,0 +1,84 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var http = require('http'); + +var nresponses = 0; + +var server = http.createServer(function(req, res) { + if (req.url == '/one') { + res.writeHead(200, [['set-cookie', 'A'], + ['content-type', 'text/plain']]); + res.end('one\n'); + } else { + res.writeHead(200, [['set-cookie', 'A'], + ['set-cookie', 'B'], + ['content-type', 'text/plain']]); + res.end('two\n'); + } +}); +server.listen(common.PORT); + +server.on('listening', function() { + // + // one set-cookie header + // + http.get({ port: common.PORT, path: '/one' }, function(res) { + // set-cookie headers are always return in an array. + // even if there is only one. + assert.deepEqual(['A'], res.headers['set-cookie']); + assert.equal('text/plain', res.headers['content-type']); + + res.on('data', function(chunk) { + console.log(chunk.toString()); + }); + + res.on('end', function() { + if (++nresponses == 2) { + server.close(); + } + }); + }); + + // two set-cookie headers + + http.get({ port: common.PORT, path: '/two' }, function(res) { + assert.deepEqual(['A', 'B'], res.headers['set-cookie']); + assert.equal('text/plain', res.headers['content-type']); + + res.on('data', function(chunk) { + console.log(chunk.toString()); + }); + + res.on('end', function() { + if (++nresponses == 2) { + server.close(); + } + }); + }); + +}); + +process.on('exit', function() { + assert.equal(2, nresponses); +}); diff --git a/node-v0.8.14/test/simple/test-http-set-timeout.js b/node-v0.8.14/test/simple/test-http-set-timeout.js new file mode 100644 index 0000000..1feb946 --- /dev/null +++ b/node-v0.8.14/test/simple/test-http-set-timeout.js @@ -0,0 +1,51 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var http = require('http'); + +var server = http.createServer(function(req, res) { + console.log('got request. setting 1 second timeout'); + req.connection.setTimeout(500); + + req.connection.on('timeout', function() { + req.connection.destroy(); + common.debug('TIMEOUT'); + server.close(); + }); +}); + +server.listen(common.PORT, function() { + console.log('Server running at http://127.0.0.1:' + common.PORT + '/'); + + var errorTimer = setTimeout(function() { + throw new Error('Timeout was not sucessful'); + }, 2000); + + var x = http.get({port: common.PORT, path: '/'}); + x.on('error', function() { + clearTimeout(errorTimer); + console.log('HTTP REQUEST COMPLETE (this is good)'); + }); + x.end(); + +}); diff --git a/node-v0.8.14/test/simple/test-http-set-trailers.js b/node-v0.8.14/test/simple/test-http-set-trailers.js new file mode 100644 index 0000000..a0896df --- /dev/null +++ b/node-v0.8.14/test/simple/test-http-set-trailers.js @@ -0,0 +1,111 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var http = require('http'); +var net = require('net'); + +var outstanding_reqs = 0; + +var server = http.createServer(function(req, res) { + res.writeHead(200, [['content-type', 'text/plain']]); + res.addTrailers({'x-foo': 'bar'}); + res.end('stuff' + '\n'); +}); +server.listen(common.PORT); + + +// first, we test an HTTP/1.0 request. +server.on('listening', function() { + var c = net.createConnection(common.PORT); + var res_buffer = ''; + + c.setEncoding('utf8'); + + c.on('connect', function() { + outstanding_reqs++; + c.write('GET / HTTP/1.0\r\n\r\n'); + }); + + c.on('data', function(chunk) { + //console.log(chunk); + res_buffer += chunk; + }); + + c.on('end', function() { + c.end(); + assert.ok(! /x-foo/.test(res_buffer), 'Trailer in HTTP/1.0 response.'); + outstanding_reqs--; + if (outstanding_reqs == 0) { + server.close(); + process.exit(); + } + }); +}); + +// now, we test an HTTP/1.1 request. +server.on('listening', function() { + var c = net.createConnection(common.PORT); + var res_buffer = ''; + var tid; + + c.setEncoding('utf8'); + + c.on('connect', function() { + outstanding_reqs++; + c.write('GET / HTTP/1.1\r\n\r\n'); + tid = setTimeout(assert.fail, 2000, 'Couldn\'t find last chunk.'); + }); + + c.on('data', function(chunk) { + //console.log(chunk); + res_buffer += chunk; + if (/0\r\n/.test(res_buffer)) { // got the end. + outstanding_reqs--; + clearTimeout(tid); + assert.ok( + /0\r\nx-foo: bar\r\n\r\n$/.test(res_buffer), + 'No trailer in HTTP/1.1 response.' + ); + if (outstanding_reqs == 0) { + server.close(); + process.exit(); + } + } + }); +}); + +// now, see if the client sees the trailers. +server.on('listening', function() { + http.get({ port: common.PORT, path: '/hello', headers: {} }, function(res) { + res.on('end', function() { + //console.log(res.trailers); + assert.ok('x-foo' in res.trailers, 'Client doesn\'t see trailers.'); + outstanding_reqs--; + if (outstanding_reqs == 0) { + server.close(); + process.exit(); + } + }); + }); + outstanding_reqs++; +}); diff --git a/node-v0.8.14/test/simple/test-http-should-keep-alive.js b/node-v0.8.14/test/simple/test-http-should-keep-alive.js new file mode 100644 index 0000000..fc1f5c6 --- /dev/null +++ b/node-v0.8.14/test/simple/test-http-should-keep-alive.js @@ -0,0 +1,71 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var http = require('http'); +var net = require('net'); + +var SERVER_RESPONSES = [ + 'HTTP/1.0 200 ok\r\nContent-Length: 0\r\n\r\n', + 'HTTP/1.0 200 ok\r\nContent-Length: 0\r\nConnection: keep-alive\r\n\r\n', + 'HTTP/1.0 200 ok\r\nContent-Length: 0\r\nConnection: close\r\n\r\n', + 'HTTP/1.1 200 ok\r\nContent-Length: 0\r\n\r\n', + 'HTTP/1.1 200 ok\r\nContent-Length: 0\r\nConnection: keep-alive\r\n\r\n', + 'HTTP/1.1 200 ok\r\nContent-Length: 0\r\nConnection: close\r\n\r\n' +]; +var SHOULD_KEEP_ALIVE = [ + false, // HTTP/1.0, default + true, // HTTP/1.0, Connection: keep-alive + false, // HTTP/1.0, Connection: close + true, // HTTP/1.1, default + true, // HTTP/1.1, Connection: keep-alive + false // HTTP/1.1, Connection: close +]; +var requests = 0; +var responses = 0; + +var server = net.createServer(function(socket) { + socket.write(SERVER_RESPONSES[requests]); + ++requests; +}).listen(common.PORT, function() { + function makeRequest() { + var req = http.get({port: common.PORT}, function(res) { + assert.equal(req.shouldKeepAlive, SHOULD_KEEP_ALIVE[responses], + SERVER_RESPONSES[responses] + ' should ' + + (SHOULD_KEEP_ALIVE[responses] ? '' : 'not ') + + 'Keep-Alive'); + ++responses; + if (responses < SHOULD_KEEP_ALIVE.length) { + makeRequest(); + } else { + server.close(); + } + }); + } + + makeRequest(); +}); + +process.on('exit', function() { + assert.equal(requests, SERVER_RESPONSES.length); + assert.equal(responses, SHOULD_KEEP_ALIVE.length); +}); diff --git a/node-v0.8.14/test/simple/test-http-status-code.js b/node-v0.8.14/test/simple/test-http-status-code.js new file mode 100644 index 0000000..3956238 --- /dev/null +++ b/node-v0.8.14/test/simple/test-http-status-code.js @@ -0,0 +1,69 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + + + +var common = require('../common'); +var assert = require('assert'); +var http = require('http'); + +// Simple test of Node's HTTP ServerResponse.statusCode +// ServerResponse.prototype.statusCode + +var testsComplete = 0; +var tests = [200, 202, 300, 404, 500]; +var testIdx = 0; + +var s = http.createServer(function(req, res) { + var t = tests[testIdx]; + res.writeHead(t, {'Content-Type': 'text/plain'}); + console.log('--\nserver: statusCode after writeHead: ' + res.statusCode); + assert.equal(res.statusCode, t); + res.end('hello world\n'); +}); + +s.listen(common.PORT, nextTest); + + +function nextTest() { + if (testIdx + 1 === tests.length) { + return s.close(); + } + var test = tests[testIdx]; + + http.get({ port: common.PORT }, function(response) { + console.log('client: expected status: ' + test); + console.log('client: statusCode: ' + response.statusCode); + assert.equal(response.statusCode, test); + response.on('end', function() { + testsComplete++; + testIdx += 1; + nextTest(); + }); + }); +} + + +process.on('exit', function() { + assert.equal(4, testsComplete); +}); + diff --git a/node-v0.8.14/test/simple/test-http-timeout.js b/node-v0.8.14/test/simple/test-http-timeout.js new file mode 100644 index 0000000..5170d79 --- /dev/null +++ b/node-v0.8.14/test/simple/test-http-timeout.js @@ -0,0 +1,63 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + +var common = require('../common'); +var assert = require('assert'); + +var http = require('http'); + +var port = 12345; +var server = http.createServer(function(req, res) { + res.writeHead(200, {'Content-Type': 'text/plain'}); + res.end('OK'); +}); + +var agent = new http.Agent({maxSockets: 1}); + +server.listen(port, function() { + + for (var i = 0; i < 11; ++i) { + createRequest().end(); + } + + function callback(){} + + var count = 0; + + function createRequest() { + var req = http.request({port: port, path: '/', agent: agent}, function(res) { + + req.clearTimeout(callback); + + res.on('end', function() { + count++; + + if (count == 11) { + server.close(); + } + }) + }); + + req.setTimeout(1000, callback); + return req; + } +}); diff --git a/node-v0.8.14/test/simple/test-http-unix-socket.js b/node-v0.8.14/test/simple/test-http-unix-socket.js new file mode 100644 index 0000000..01c29c1 --- /dev/null +++ b/node-v0.8.14/test/simple/test-http-unix-socket.js @@ -0,0 +1,87 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var fs = require('fs'); +var http = require('http'); + +var status_ok = false; // status code == 200? +var headers_ok = false; +var body_ok = false; + +var server = http.createServer(function(req, res) { + res.writeHead(200, { + 'Content-Type': 'text/plain', + 'Connection': 'close' + }); + res.write('hello '); + res.write('world\n'); + res.end(); +}); + +server.listen(common.PIPE, function() { + + var options = { + socketPath: common.PIPE, + path: '/' + }; + + var req = http.get(options, function(res) { + assert.equal(res.statusCode, 200); + status_ok = true; + + assert.equal(res.headers['content-type'], 'text/plain'); + headers_ok = true; + + res.body = ''; + res.setEncoding('utf8'); + + res.on('data', function(chunk) { + res.body += chunk; + }); + + res.on('end', function() { + assert.equal(res.body, 'hello world\n'); + body_ok = true; + server.close(); + }); + }); + + req.on('error', function(e) { + console.log(e.stack); + process.exit(1); + }); + + req.end(); + +}); + +process.on('exit', function() { + assert.ok(status_ok); + assert.ok(headers_ok); + assert.ok(body_ok); + + // Double close should throw. Follows net_legacy behaviour. + assert.throws(function() { + server.close(); + }); +}); diff --git a/node-v0.8.14/test/simple/test-http-upgrade-agent.js b/node-v0.8.14/test/simple/test-http-upgrade-agent.js new file mode 100644 index 0000000..1077a98 --- /dev/null +++ b/node-v0.8.14/test/simple/test-http-upgrade-agent.js @@ -0,0 +1,93 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// Verify that the 'upgrade' header causes an 'upgrade' event to be emitted to +// the HTTP client. This test uses a raw TCP server to better control server +// behavior. + +var common = require('../common'); +var assert = require('assert'); + +var http = require('http'); +var net = require('net'); + +// Create a TCP server +var srv = net.createServer(function(c) { + var data = ''; + c.on('data', function(d) { + data += d.toString('utf8'); + + c.write('HTTP/1.1 101\r\n'); + c.write('hello: world\r\n'); + c.write('connection: upgrade\r\n'); + c.write('upgrade: websocket\r\n'); + c.write('\r\n'); + c.write('nurtzo'); + }); + + c.on('end', function() { + c.end(); + }); +}); + +var gotUpgrade = false; + +srv.listen(common.PORT, '127.0.0.1', function() { + + var options = { + port: common.PORT, + host: '127.0.0.1', + headers: { + 'upgrade': 'websocket' + } + }; + var name = options.host + ':' + options.port; + + var req = http.request(options); + req.end(); + + req.on('upgrade', function(res, socket, upgradeHead) { + // XXX: This test isn't fantastic, as it assumes that the entire response + // from the server will arrive in a single data callback + assert.equal(upgradeHead, 'nurtzo'); + + console.log(res.headers); + var expectedHeaders = { 'hello': 'world', + 'connection': 'upgrade', + 'upgrade': 'websocket' }; + assert.deepEqual(expectedHeaders, res.headers); + + // Make sure this request got removed from the pool. + assert(!http.globalAgent.sockets.hasOwnProperty(name)); + + req.on('close', function() { + socket.end(); + srv.close(); + + gotUpgrade = true; + }); + }); + +}); + +process.on('exit', function() { + assert.ok(gotUpgrade); +}); diff --git a/node-v0.8.14/test/simple/test-http-upgrade-client.js b/node-v0.8.14/test/simple/test-http-upgrade-client.js new file mode 100644 index 0000000..3bf5bec --- /dev/null +++ b/node-v0.8.14/test/simple/test-http-upgrade-client.js @@ -0,0 +1,76 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// Verify that the 'upgrade' header causes an 'upgrade' event to be emitted to +// the HTTP client. This test uses a raw TCP server to better control server +// behavior. + +var common = require('../common'); +var assert = require('assert'); + +var http = require('http'); +var net = require('net'); + +// Create a TCP server +var srv = net.createServer(function(c) { + var data = ''; + c.on('data', function(d) { + data += d.toString('utf8'); + + c.write('HTTP/1.1 101\r\n'); + c.write('hello: world\r\n'); + c.write('connection: upgrade\r\n'); + c.write('upgrade: websocket\r\n'); + c.write('\r\n'); + c.write('nurtzo'); + }); + + c.on('end', function() { + c.end(); + }); +}); + +var gotUpgrade = false; + +srv.listen(common.PORT, '127.0.0.1', function() { + + var req = http.get({ port: common.PORT }); + req.on('upgrade', function(res, socket, upgradeHead) { + // XXX: This test isn't fantastic, as it assumes that the entire response + // from the server will arrive in a single data callback + assert.equal(upgradeHead, 'nurtzo'); + + console.log(res.headers); + var expectedHeaders = {'hello': 'world', + 'connection': 'upgrade', + 'upgrade': 'websocket' }; + assert.deepEqual(expectedHeaders, res.headers); + + socket.end(); + srv.close(); + + gotUpgrade = true; + }); +}); + +process.on('exit', function() { + assert.ok(gotUpgrade); +}); diff --git a/node-v0.8.14/test/simple/test-http-upgrade-client2.js b/node-v0.8.14/test/simple/test-http-upgrade-client2.js new file mode 100644 index 0000000..fa39f2a --- /dev/null +++ b/node-v0.8.14/test/simple/test-http-upgrade-client2.js @@ -0,0 +1,86 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var http = require('http'); + +var CRLF = '\r\n'; + +var server = http.createServer(); +server.on('upgrade', function(req, socket, head) { + socket.write('HTTP/1.1 101 Ok' + CRLF + + 'Connection: Upgrade' + CRLF + + 'Upgrade: Test' + CRLF + CRLF + 'head'); + socket.on('end', function() { + socket.end(); + }); +}); + +var successCount = 0; + +server.listen(common.PORT, function() { + + function upgradeRequest(fn) { + console.log('req'); + var header = { 'Connection': 'Upgrade', 'Upgrade': 'Test' }; + var request = http.request({ port: common.PORT, headers: header }); + var wasUpgrade = false; + + function onUpgrade(res, socket, head) { + console.log('client upgraded'); + wasUpgrade = true; + + request.removeListener('upgrade', onUpgrade); + socket.end(); + } + request.on('upgrade', onUpgrade); + + function onEnd() { + console.log('client end'); + request.removeListener('end', onEnd); + if (!wasUpgrade) { + throw new Error('hasn\'t received upgrade event'); + } else { + fn && process.nextTick(fn); + } + } + request.on('close', onEnd); + + request.write('head'); + + } + + upgradeRequest(function() { + successCount++; + upgradeRequest(function() { + successCount++; + // Test pass + console.log('Pass!'); + server.close(); + }); + }); + +}); + +process.on('exit', function() { + assert.equal(2, successCount); +}); diff --git a/node-v0.8.14/test/simple/test-http-upgrade-server.js b/node-v0.8.14/test/simple/test-http-upgrade-server.js new file mode 100644 index 0000000..6a14d39 --- /dev/null +++ b/node-v0.8.14/test/simple/test-http-upgrade-server.js @@ -0,0 +1,185 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); + +var util = require('util'); +var net = require('net'); +var http = require('http'); + + +var requests_recv = 0; +var requests_sent = 0; +var request_upgradeHead = null; + +function createTestServer() { + return new testServer(); +} + +function testServer() { + var server = this; + http.Server.call(server, function() {}); + + server.on('connection', function() { + requests_recv++; + }); + + server.on('request', function(req, res) { + res.writeHead(200, {'Content-Type': 'text/plain'}); + res.write('okay'); + res.end(); + }); + + server.on('upgrade', function(req, socket, upgradeHead) { + socket.write('HTTP/1.1 101 Web Socket Protocol Handshake\r\n' + + 'Upgrade: WebSocket\r\n' + + 'Connection: Upgrade\r\n' + + '\r\n\r\n'); + + request_upgradeHead = upgradeHead; + + socket.ondata = function(d, start, end) { + var data = d.toString('utf8', start, end); + if (data == 'kill') { + socket.end(); + } else { + socket.write(data, 'utf8'); + } + }; + }); +} + +util.inherits(testServer, http.Server); + + +function writeReq(socket, data, encoding) { + requests_sent++; + socket.write(data); +} + + +/*----------------------------------------------- + connection: Upgrade with listener +-----------------------------------------------*/ +function test_upgrade_with_listener(_server) { + var conn = net.createConnection(common.PORT); + conn.setEncoding('utf8'); + var state = 0; + + conn.on('connect', function() { + writeReq(conn, + 'GET / HTTP/1.1\r\n' + + 'Upgrade: WebSocket\r\n' + + 'Connection: Upgrade\r\n' + + '\r\n' + + 'WjN}|M(6'); + }); + + conn.on('data', function(data) { + state++; + + assert.equal('string', typeof data); + + if (state == 1) { + assert.equal('HTTP/1.1 101', data.substr(0, 12)); + assert.equal('WjN}|M(6', request_upgradeHead.toString('utf8')); + conn.write('test', 'utf8'); + } else if (state == 2) { + assert.equal('test', data); + conn.write('kill', 'utf8'); + } + }); + + conn.on('end', function() { + assert.equal(2, state); + conn.end(); + _server.removeAllListeners('upgrade'); + test_upgrade_no_listener(); + }); +} + +/*----------------------------------------------- + connection: Upgrade, no listener +-----------------------------------------------*/ +var test_upgrade_no_listener_ended = false; + +function test_upgrade_no_listener() { + var conn = net.createConnection(common.PORT); + conn.setEncoding('utf8'); + + conn.on('connect', function() { + writeReq(conn, + 'GET / HTTP/1.1\r\n' + + 'Upgrade: WebSocket\r\n' + + 'Connection: Upgrade\r\n' + + '\r\n'); + }); + + conn.on('end', function() { + test_upgrade_no_listener_ended = true; + conn.end(); + }); + + conn.on('close', function() { + test_standard_http(); + }); +} + +/*----------------------------------------------- + connection: normal +-----------------------------------------------*/ +function test_standard_http() { + var conn = net.createConnection(common.PORT); + conn.setEncoding('utf8'); + + conn.on('connect', function() { + writeReq(conn, 'GET / HTTP/1.1\r\n\r\n'); + }); + + conn.on('data', function(data) { + assert.equal('string', typeof data); + assert.equal('HTTP/1.1 200', data.substr(0, 12)); + conn.end(); + }); + + conn.on('close', function() { + server.close(); + }); +} + + +var server = createTestServer(); + +server.listen(common.PORT, function() { + // All tests get chained after this: + test_upgrade_with_listener(server); +}); + + +/*----------------------------------------------- + Fin. +-----------------------------------------------*/ +process.on('exit', function() { + assert.equal(3, requests_recv); + assert.equal(3, requests_sent); + assert.ok(test_upgrade_no_listener_ended); +}); diff --git a/node-v0.8.14/test/simple/test-http-upgrade-server2.js b/node-v0.8.14/test/simple/test-http-upgrade-server2.js new file mode 100644 index 0000000..e617d3b --- /dev/null +++ b/node-v0.8.14/test/simple/test-http-upgrade-server2.js @@ -0,0 +1,72 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var http = require('http'); +var net = require('net'); + +var server = http.createServer(function(req, res) { + common.error('got req'); + throw new Error('This shouldn\'t happen.'); +}); + +server.on('upgrade', function(req, socket, upgradeHead) { + common.error('got upgrade event'); + // test that throwing an error from upgrade gets + // is uncaught + throw new Error('upgrade error'); +}); + +var gotError = false; + +process.on('uncaughtException', function(e) { + common.error('got \'clientError\' event'); + assert.equal('upgrade error', e.message); + gotError = true; + process.exit(0); +}); + + +server.listen(common.PORT, function() { + var c = net.createConnection(common.PORT); + + c.on('connect', function() { + common.error('client wrote message'); + c.write('GET /blah HTTP/1.1\r\n' + + 'Upgrade: WebSocket\r\n' + + 'Connection: Upgrade\r\n' + + '\r\n\r\nhello world'); + }); + + c.on('end', function() { + c.end(); + }); + + c.on('close', function() { + common.error('client close'); + server.close(); + }); +}); + +process.on('exit', function() { + assert.ok(gotError); +}); diff --git a/node-v0.8.14/test/simple/test-http-url.parse-auth-with-header-in-request.js b/node-v0.8.14/test/simple/test-http-url.parse-auth-with-header-in-request.js new file mode 100644 index 0000000..5ac7890 --- /dev/null +++ b/node-v0.8.14/test/simple/test-http-url.parse-auth-with-header-in-request.js @@ -0,0 +1,50 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var http = require('http'); +var url = require('url'); + +var testURL = url.parse('http://asdf:qwer@localhost:' + common.PORT); +// the test here is if you set a specific authorization header in the +// request we should not override that with basic auth +testURL.headers = { + Authorization: 'NoAuthForYOU' +}; + +function check(request) { + // the correct authorization header is be passed + assert.strictEqual(request.headers.authorization, 'NoAuthForYOU'); +} + +var server = http.createServer(function(request, response) { + // run the check function + check.call(this, request, response); + response.writeHead(200, {}); + response.end('ok'); + server.close(); +}); + +server.listen(common.PORT, function() { + // make the request + http.request(testURL).end(); +}); diff --git a/node-v0.8.14/test/simple/test-http-url.parse-auth.js b/node-v0.8.14/test/simple/test-http-url.parse-auth.js new file mode 100644 index 0000000..4c07d5f --- /dev/null +++ b/node-v0.8.14/test/simple/test-http-url.parse-auth.js @@ -0,0 +1,46 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var http = require('http'); +var url = require('url'); + +// username = "user", password = "pass:" +var testURL = url.parse('http://user:pass%3A@localhost:' + common.PORT); + +function check(request) { + // the correct authorization header is be passed + assert.strictEqual(request.headers.authorization, 'Basic dXNlcjpwYXNzOg=='); +} + +var server = http.createServer(function(request, response) { + // run the check function + check.call(this, request, response); + response.writeHead(200, {}); + response.end('ok'); + server.close(); +}); + +server.listen(common.PORT, function() { + // make the request + http.request(testURL).end(); +}); diff --git a/node-v0.8.14/test/simple/test-http-url.parse-basic.js b/node-v0.8.14/test/simple/test-http-url.parse-basic.js new file mode 100644 index 0000000..8bf12b1 --- /dev/null +++ b/node-v0.8.14/test/simple/test-http-url.parse-basic.js @@ -0,0 +1,55 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var http = require('http'); +var url = require('url'); + +var testURL = url.parse('http://localhost:' + common.PORT); + +// make sure the basics work +function check(request) { + // default method should still be get + assert.strictEqual(request.method, 'GET'); + // there are no URL params, so you should not see any + assert.strictEqual(request.url, '/'); + // the host header should use the url.parse.hostname + assert.strictEqual(request.headers.host, + testURL.hostname + ':' + testURL.port); +} + +var server = http.createServer(function(request, response) { + // run the check function + check.call(this, request, response); + response.writeHead(200, {}); + response.end('ok'); + server.close(); +}); + +server.listen(common.PORT, function() { + // make the request + var clientRequest = http.request(testURL); + // since there is a little magic with the agent + // make sure that an http request uses the http.Agent + assert.ok(clientRequest.agent instanceof http.Agent); + clientRequest.end(); +}); diff --git a/node-v0.8.14/test/simple/test-http-url.parse-https.request.js b/node-v0.8.14/test/simple/test-http-url.parse-https.request.js new file mode 100644 index 0000000..6756db5 --- /dev/null +++ b/node-v0.8.14/test/simple/test-http-url.parse-https.request.js @@ -0,0 +1,57 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var https = require('https'); +var url = require('url'); +var fs = require('fs'); +var clientRequest; + +// https options +var httpsOptions = { + key: fs.readFileSync(common.fixturesDir + '/keys/agent1-key.pem'), + cert: fs.readFileSync(common.fixturesDir + '/keys/agent1-cert.pem') +}; + +var testURL = url.parse('https://localhost:' + common.PORT); + +function check(request) { + // assert that I'm https + assert.ok(request.socket.encrypted); +} + +var server = https.createServer(httpsOptions, function(request, response) { + // run the check function + check.call(this, request, response); + response.writeHead(200, {}); + response.end('ok'); + server.close(); +}); + +server.listen(common.PORT, function() { + // make the request + var clientRequest = https.request(testURL); + // since there is a little magic with the agent + // make sure that the request uses the https.Agent + assert.ok(clientRequest.agent instanceof https.Agent); + clientRequest.end(); +}); diff --git a/node-v0.8.14/test/simple/test-http-url.parse-only-support-http-https-protocol.js b/node-v0.8.14/test/simple/test-http-url.parse-only-support-http-https-protocol.js new file mode 100644 index 0000000..c77df5e --- /dev/null +++ b/node-v0.8.14/test/simple/test-http-url.parse-only-support-http-https-protocol.js @@ -0,0 +1,82 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var http = require('http'); +var url = require('url'); + + +assert.throws(function() { + http.request(url.parse('file:///whatever')); +}, function(err) { + if (err instanceof Error) { + assert.strictEqual(err.message, 'Protocol:file: not supported.'); + return true; + } +}); + +assert.throws(function() { + http.request(url.parse('mailto:asdf@asdf.com')); +}, function(err) { + if (err instanceof Error) { + assert.strictEqual(err.message, 'Protocol:mailto: not supported.'); + return true; + } +}); + +assert.throws(function() { + http.request(url.parse('ftp://www.example.com')); +}, function(err) { + if (err instanceof Error) { + assert.strictEqual(err.message, 'Protocol:ftp: not supported.'); + return true; + } +}); + +assert.throws(function() { + http.request(url.parse('javascript:alert(\'hello\');')); +}, function(err) { + if (err instanceof Error) { + assert.strictEqual(err.message, 'Protocol:javascript: not supported.'); + return true; + } +}); + +assert.throws(function() { + http.request(url.parse('xmpp:isaacschlueter@jabber.org')); +}, function(err) { + if (err instanceof Error) { + assert.strictEqual(err.message, 'Protocol:xmpp: not supported.'); + return true; + } +}); + +assert.throws(function() { + http.request(url.parse('f://some.host/path')); +}, function(err) { + if (err instanceof Error) { + assert.strictEqual(err.message, 'Protocol:f: not supported.'); + return true; + } +}); + +//TODO do I need to test url.parse(notPrococol.example.com)? diff --git a/node-v0.8.14/test/simple/test-http-url.parse-path.js b/node-v0.8.14/test/simple/test-http-url.parse-path.js new file mode 100644 index 0000000..8ef0952 --- /dev/null +++ b/node-v0.8.14/test/simple/test-http-url.parse-path.js @@ -0,0 +1,45 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var http = require('http'); +var url = require('url'); + +var testURL = url.parse('http://localhost:' + common.PORT + '/asdf'); + +function check(request) { + // a path should come over + assert.strictEqual(request.url, '/asdf'); +} + +var server = http.createServer(function(request, response) { + // run the check function + check.call(this, request, response); + response.writeHead(200, {}); + response.end('ok'); + server.close(); +}); + +server.listen(common.PORT, function() { + // make the request + http.request(testURL).end(); +}); diff --git a/node-v0.8.14/test/simple/test-http-url.parse-post.js b/node-v0.8.14/test/simple/test-http-url.parse-post.js new file mode 100644 index 0000000..be93166 --- /dev/null +++ b/node-v0.8.14/test/simple/test-http-url.parse-post.js @@ -0,0 +1,52 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var http = require('http'); +var https = require('https'); +var url = require('url'); + +var testURL = url.parse('http://localhost:' + common.PORT + '/asdf?qwer=zxcv'); +testURL.method = 'POST'; + +function check(request) { + //url.parse should not mess with the method + assert.strictEqual(request.method, 'POST'); + //everything else should be right + assert.strictEqual(request.url, '/asdf?qwer=zxcv'); + //the host header should use the url.parse.hostname + assert.strictEqual(request.headers.host, + testURL.hostname + ':' + testURL.port); +} + +var server = http.createServer(function(request, response) { + // run the check function + check.call(this, request, response); + response.writeHead(200, {}); + response.end('ok'); + server.close(); +}); + +server.listen(common.PORT, function() { + // make the request + http.request(testURL).end(); +}); diff --git a/node-v0.8.14/test/simple/test-http-url.parse-search.js b/node-v0.8.14/test/simple/test-http-url.parse-search.js new file mode 100644 index 0000000..3b6727d --- /dev/null +++ b/node-v0.8.14/test/simple/test-http-url.parse-search.js @@ -0,0 +1,46 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var http = require('http'); +var https = require('https'); +var url = require('url'); + +var testURL = url.parse('http://localhost:' + common.PORT + '/asdf?qwer=zxcv'); + +function check(request) { + // a path should come over with params + assert.strictEqual(request.url, '/asdf?qwer=zxcv'); +} + +var server = http.createServer(function(request, response) { + // run the check function + check.call(this, request, response); + response.writeHead(200, {}); + response.end('ok'); + server.close(); +}); + +server.listen(common.PORT, function() { + // make the request + http.request(testURL).end(); +}); diff --git a/node-v0.8.14/test/simple/test-http-wget.js b/node-v0.8.14/test/simple/test-http-wget.js new file mode 100644 index 0000000..b6cf7d8 --- /dev/null +++ b/node-v0.8.14/test/simple/test-http-wget.js @@ -0,0 +1,87 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var net = require('net'); +var http = require('http'); + +// wget sends an HTTP/1.0 request with Connection: Keep-Alive +// +// Sending back a chunked response to an HTTP/1.0 client would be wrong, +// so what has to happen in this case is that the connection is closed +// by the server after the entity body if the Content-Length was not +// sent. +// +// If the Content-Length was sent, we can probably safely honor the +// keep-alive request, even though HTTP 1.0 doesn't say that the +// connection can be kept open. Presumably any client sending this +// header knows that it is extending HTTP/1.0 and can handle the +// response. We don't test that here however, just that if the +// content-length is not provided, that the connection is in fact +// closed. + +var server_response = ''; +var client_got_eof = false; +var connection_was_closed = false; + +var server = http.createServer(function(req, res) { + res.writeHead(200, {'Content-Type': 'text/plain'}); + res.write('hello '); + res.write('world\n'); + res.end(); +}); +server.listen(common.PORT); + +server.on('listening', function() { + var c = net.createConnection(common.PORT); + + c.setEncoding('utf8'); + + c.on('connect', function() { + c.write('GET / HTTP/1.0\r\n' + + 'Connection: Keep-Alive\r\n\r\n'); + }); + + c.on('data', function(chunk) { + console.log(chunk); + server_response += chunk; + }); + + c.on('end', function() { + client_got_eof = true; + console.log('got end'); + c.end(); + }); + + c.on('close', function() { + connection_was_closed = true; + console.log('got close'); + server.close(); + }); +}); + +process.on('exit', function() { + var m = server_response.split('\r\n\r\n'); + assert.equal(m[1], 'hello world\n'); + assert.ok(client_got_eof); + assert.ok(connection_was_closed); +}); diff --git a/node-v0.8.14/test/simple/test-http-write-empty-string.js b/node-v0.8.14/test/simple/test-http-write-empty-string.js new file mode 100644 index 0000000..baf9c27 --- /dev/null +++ b/node-v0.8.14/test/simple/test-http-write-empty-string.js @@ -0,0 +1,57 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); + +var http = require('http'); + +var server = http.createServer(function(request, response) { + console.log('responding to ' + request.url); + + response.writeHead(200, {'Content-Type': 'text/plain'}); + response.write('1\n'); + response.write(''); + response.write('2\n'); + response.write(''); + response.end('3\n'); + + this.close(); +}); + +var response = ''; + +process.on('exit', function() { + assert.equal('1\n2\n3\n', response); +}); + + +server.listen(common.PORT, function() { + http.get({ port: common.PORT }, function(res) { + assert.equal(200, res.statusCode); + res.setEncoding('ascii'); + res.on('data', function(chunk) { + response += chunk; + }); + common.error('Got /hello response'); + }); +}); + diff --git a/node-v0.8.14/test/simple/test-http.js b/node-v0.8.14/test/simple/test-http.js new file mode 100644 index 0000000..1915e24 --- /dev/null +++ b/node-v0.8.14/test/simple/test-http.js @@ -0,0 +1,108 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var http = require('http'); +var url = require('url'); + +function p(x) { + common.error(common.inspect(x)); +} + +var responses_sent = 0; +var responses_recvd = 0; +var body0 = ''; +var body1 = ''; + +var server = http.Server(function(req, res) { + if (responses_sent == 0) { + assert.equal('GET', req.method); + assert.equal('/hello', url.parse(req.url).pathname); + + console.dir(req.headers); + assert.equal(true, 'accept' in req.headers); + assert.equal('*/*', req.headers['accept']); + + assert.equal(true, 'foo' in req.headers); + assert.equal('bar', req.headers['foo']); + } + + if (responses_sent == 1) { + assert.equal('POST', req.method); + assert.equal('/world', url.parse(req.url).pathname); + this.close(); + } + + req.on('end', function() { + res.writeHead(200, {'Content-Type': 'text/plain'}); + res.write('The path was ' + url.parse(req.url).pathname); + res.end(); + responses_sent += 1; + }); + + //assert.equal('127.0.0.1', res.connection.remoteAddress); +}); +server.listen(common.PORT); + +server.on('listening', function() { + var agent = new http.Agent({ port: common.PORT, maxSockets: 1 }); + http.get({ + port: common.PORT, + path: '/hello', + headers: {'Accept': '*/*', 'Foo': 'bar'}, + agent: agent + }, function(res) { + assert.equal(200, res.statusCode); + responses_recvd += 1; + res.setEncoding('utf8'); + res.on('data', function(chunk) { body0 += chunk; }); + common.debug('Got /hello response'); + }); + + setTimeout(function() { + var req = http.request({ + port: common.PORT, + method: 'POST', + path: '/world', + agent: agent + }, function(res) { + assert.equal(200, res.statusCode); + responses_recvd += 1; + res.setEncoding('utf8'); + res.on('data', function(chunk) { body1 += chunk; }); + common.debug('Got /world response'); + }); + req.end(); + }, 1); +}); + +process.on('exit', function() { + common.debug('responses_recvd: ' + responses_recvd); + assert.equal(2, responses_recvd); + + common.debug('responses_sent: ' + responses_sent); + assert.equal(2, responses_sent); + + assert.equal('The path was /hello', body0); + assert.equal('The path was /world', body1); +}); + diff --git a/node-v0.8.14/test/simple/test-https-agent.js b/node-v0.8.14/test/simple/test-https-agent.js new file mode 100644 index 0000000..41aa034 --- /dev/null +++ b/node-v0.8.14/test/simple/test-https-agent.js @@ -0,0 +1,70 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + + + +if (!process.versions.openssl) { + console.error('Skipping because node compiled without OpenSSL.'); + process.exit(0); +} + +var common = require('../common'); +var assert = require('assert'); +var https = require('https'); +var fs = require('fs'); + +var options = { + key: fs.readFileSync(common.fixturesDir + '/keys/agent1-key.pem'), + cert: fs.readFileSync(common.fixturesDir + '/keys/agent1-cert.pem') +}; + + +var server = https.Server(options, function(req, res) { + res.writeHead(200); + res.end('hello world\n'); +}); + + +var responses = 0; +var N = 10; +var M = 10; + +server.listen(common.PORT, function() { + for (var i = 0; i < N; i++) { + setTimeout(function() { + for (var j = 0; j < M; j++) { + https.get({ port: common.PORT, path: '/' }, function(res) { + console.log(res.statusCode); + if (++responses == N * M) server.close(); + }).on('error', function(e) { + console.log(e.message); + process.exit(1); + }); + } + }, i); + } +}); + + +process.on('exit', function() { + assert.equal(N * M, responses); +}); diff --git a/node-v0.8.14/test/simple/test-https-client-get-url.js b/node-v0.8.14/test/simple/test-https-client-get-url.js new file mode 100644 index 0000000..c6ddb03 --- /dev/null +++ b/node-v0.8.14/test/simple/test-https-client-get-url.js @@ -0,0 +1,55 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +if (!process.versions.openssl) { + console.error('Skipping because node compiled without OpenSSL.'); + process.exit(0); +} + +var common = require('../common'); +var assert = require('assert'); +var https = require('https'); +var fs = require('fs'); + +var seen_req = false; + +var options = { + key: fs.readFileSync(common.fixturesDir + '/keys/agent1-key.pem'), + cert: fs.readFileSync(common.fixturesDir + '/keys/agent1-cert.pem') +}; + +var server = https.createServer(options, function(req, res) { + assert.equal('GET', req.method); + assert.equal('/foo?bar', req.url); + res.writeHead(200, {'Content-Type': 'text/plain'}); + res.write('hello\n'); + res.end(); + server.close(); + seen_req = true; +}); + +server.listen(common.PORT, function() { + https.get('https://127.0.0.1:' + common.PORT + '/foo?bar'); +}); + +process.on('exit', function() { + assert(seen_req); +}); diff --git a/node-v0.8.14/test/simple/test-https-client-reject.js b/node-v0.8.14/test/simple/test-https-client-reject.js new file mode 100644 index 0000000..700caee --- /dev/null +++ b/node-v0.8.14/test/simple/test-https-client-reject.js @@ -0,0 +1,95 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +if (!process.versions.openssl) { + console.error('Skipping because node compiled without OpenSSL.'); + process.exit(0); +} + +var common = require('../common'); +var assert = require('assert'); +var https = require('https'); +var fs = require('fs'); +var path = require('path'); + +var options = { + key: fs.readFileSync(path.join(common.fixturesDir, 'test_key.pem')), + cert: fs.readFileSync(path.join(common.fixturesDir, 'test_cert.pem')) +}; + +var reqCount = 0; + +var server = https.createServer(options, function(req, res) { + ++reqCount; + res.writeHead(200); + res.end(); +}).listen(common.PORT, function() { + unauthorized(); +}); + +function unauthorized() { + var req = https.request({ + port: common.PORT + }, function(res) { + assert(!req.socket.authorized); + rejectUnauthorized(); + }); + req.on('error', function(err) { + assert(false); + }); + req.end(); +} + +function rejectUnauthorized() { + var options = { + port: common.PORT, + rejectUnauthorized: true + }; + options.agent = new https.Agent(options); + var req = https.request(options, function(res) { + assert(false); + }); + req.on('error', function(err) { + authorized(); + }); + req.end(); +} + +function authorized() { + var options = { + port: common.PORT, + rejectUnauthorized: true, + ca: [fs.readFileSync(path.join(common.fixturesDir, 'test_cert.pem'))] + }; + options.agent = new https.Agent(options); + var req = https.request(options, function(res) { + assert(req.socket.authorized); + server.close(); + }); + req.on('error', function(err) { + assert(false); + }); + req.end(); +} + +process.on('exit', function() { + assert.equal(reqCount, 2); +}); diff --git a/node-v0.8.14/test/simple/test-https-connecting-to-http.js b/node-v0.8.14/test/simple/test-https-connecting-to-http.js new file mode 100644 index 0000000..50bb2a8 --- /dev/null +++ b/node-v0.8.14/test/simple/test-https-connecting-to-http.js @@ -0,0 +1,64 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + + + +// This tests the situation where you try to connect a https client +// to an http server. You should get an error and exit. +var common = require('../common'); +var assert = require('assert'); +var https = require('https'); +var http = require('http'); + + +var reqCount = 0; +var resCount = 0; +var reqErrorCount = 0; +var body = 'hello world\n'; + + +var server = http.createServer(function(req, res) { + reqCount++; + console.log('got request'); + res.writeHead(200, { 'content-type': 'text/plain' }); + res.end(body); +}); + + +server.listen(common.PORT, function() { + var req = https.get({ port: common.PORT }, function(res) { + resCount++; + }); + + req.on('error', function(e) { + console.log('Got expected error: ', e.message); + server.close(); + reqErrorCount++; + }); +}); + + +process.on('exit', function() { + assert.equal(0, reqCount); + assert.equal(0, resCount); + assert.equal(1, reqErrorCount); +}); diff --git a/node-v0.8.14/test/simple/test-https-drain.js b/node-v0.8.14/test/simple/test-https-drain.js new file mode 100644 index 0000000..314944b --- /dev/null +++ b/node-v0.8.14/test/simple/test-https-drain.js @@ -0,0 +1,93 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +if (!process.versions.openssl) { + console.error('Skipping because node compiled without OpenSSL.'); + process.exit(0); +} + +var common = require('../common'); +var assert = require('assert'); +var https = require('https'); +var fs = require('fs'); +var path = require('path'); + +var options = { + key: fs.readFileSync(path.join(common.fixturesDir, 'test_key.pem')), + cert: fs.readFileSync(path.join(common.fixturesDir, 'test_cert.pem')) +}; + +var bufSize = 1024 * 1024; +var sent = 0; +var received = 0; + +var server = https.createServer(options, function(req, res) { + res.writeHead(200); + req.pipe(res); +}); + +server.listen(common.PORT, function() { + var resumed = false; + var req = https.request({ + port: common.PORT, + method: 'POST' + }, function(res) { + var timer; + res.pause(); + common.debug('paused'); + send(); + function send() { + if (req.write(new Buffer(bufSize))) { + sent += bufSize; + assert.ok(sent < 100 * 1024 * 1024); // max 100MB + return process.nextTick(send); + } + sent += bufSize; + common.debug('sent: ' + sent); + resumed = true; + res.resume(); + common.debug('resumed'); + timer = setTimeout(function() { + process.exit(1); + }, 1000); + } + + res.on('data', function(data) { + assert.ok(resumed); + if (timer) { + clearTimeout(timer); + timer = null; + } + received += data.length; + if (received >= sent) { + common.debug('received: ' + received); + req.end(); + server.close(); + } + }); + }); + req.write('a'); + ++sent; +}); + +process.on('exit', function() { + assert.equal(sent, received); +}); diff --git a/node-v0.8.14/test/simple/test-https-eof-for-eom.js b/node-v0.8.14/test/simple/test-https-eof-for-eom.js new file mode 100644 index 0000000..d5b5111 --- /dev/null +++ b/node-v0.8.14/test/simple/test-https-eof-for-eom.js @@ -0,0 +1,101 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + + + +// I hate HTTP. One way of terminating an HTTP response is to not send +// a content-length header, not send a transfer-encoding: chunked header, +// and simply terminate the TCP connection. That is identity +// transfer-encoding. +// +// This test is to be sure that the https client is handling this case +// correctly. +if (!process.versions.openssl) { + console.error('Skipping because node compiled without OpenSSL.'); + process.exit(0); +} + +var common = require('../common'); +var assert = require('assert'); +var tls = require('tls'); +var https = require('https'); +var fs = require('fs'); + +var options = { + key: fs.readFileSync(common.fixturesDir + '/keys/agent1-key.pem'), + cert: fs.readFileSync(common.fixturesDir + '/keys/agent1-cert.pem') +}; + + +var server = tls.Server(options, function(socket) { + console.log('2) Server got request'); + socket.write('HTTP/1.1 200 OK\r\n' + + 'Date: Tue, 15 Feb 2011 22:14:54 GMT\r\n' + + 'Expires: -1\r\n' + + 'Cache-Control: private, max-age=0\r\n' + + 'Set-Cookie: xyz\r\n' + + 'Set-Cookie: abc\r\n' + + 'Server: gws\r\n' + + 'X-XSS-Protection: 1; mode=block\r\n' + + 'Connection: close\r\n' + + '\r\n'); + + socket.write('hello world\n'); + + setTimeout(function() { + socket.end('hello world\n'); + console.log('4) Server finished response'); + }, 100); +}); + + +var gotHeaders = false; +var gotEnd = false; +var bodyBuffer = ''; + +server.listen(common.PORT, function() { + console.log('1) Making Request'); + var req = https.get({ port: common.PORT }, function(res) { + server.close(); + console.log('3) Client got response headers.'); + + assert.equal('gws', res.headers.server); + gotHeaders = true; + + res.setEncoding('utf8'); + res.on('data', function(s) { + bodyBuffer += s; + }); + + res.on('close', function() { + console.log('5) Client got "end" event.'); + gotEnd = true; + }); + }); +}); + +process.on('exit', function() { + assert.ok(gotHeaders); + assert.ok(gotEnd); + assert.equal('hello world\nhello world\n', bodyBuffer); +}); + diff --git a/node-v0.8.14/test/simple/test-https-foafssl.js b/node-v0.8.14/test/simple/test-https-foafssl.js new file mode 100644 index 0000000..2336e5c --- /dev/null +++ b/node-v0.8.14/test/simple/test-https-foafssl.js @@ -0,0 +1,89 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +if (!process.versions.openssl) { + console.error('Skipping because node compiled without OpenSSL.'); + process.exit(0); +} + +var common = require('../common'); +var assert = require('assert'); +var join = require('path').join; + +var fs = require('fs'); +var exec = require('child_process').exec; + +var https = require('https'); + +var options = { + key: fs.readFileSync(common.fixturesDir + '/agent.key'), + cert: fs.readFileSync(common.fixturesDir + '/agent.crt'), + requestCert: true +}; + +var reqCount = 0; +var body = 'hello world\n'; +var cert; +var subjectaltname; +var modulus; +var exponent; + +var server = https.createServer(options, function(req, res) { + reqCount++; + console.log('got request'); + + cert = req.connection.getPeerCertificate(); + + subjectaltname = cert.subjectaltname; + modulus = cert.modulus; + exponent = cert.exponent; + + res.writeHead(200, { 'content-type': 'text/plain' }); + res.end(body); +}); + + +server.listen(common.PORT, function() { + var cmd = 'curl --insecure https://127.0.0.1:' + common.PORT + '/'; + cmd += ' --cert ' + join(common.fixturesDir, 'foafssl.crt'); + cmd += ' --key ' + join(common.fixturesDir, 'foafssl.key'); + console.error('executing %j', cmd); + exec(cmd, function(err, stdout, stderr) { + if (err) throw err; + common.error(common.inspect(stdout)); + assert.equal(body, stdout); + server.close(); + }); + +}); + +process.on('exit', function() { + assert.equal(subjectaltname, 'URI:http://example.com/#me'); + assert.equal(modulus, 'A6F44A9C25791431214F5C87AF9E040177A8BB89AC803F7E09' + + 'BBC3A5519F349CD9B9C40BE436D0AA823A94147E26C89248ADA2BE3DD4D34E8C2896' + + '4694B2047D217B4F1299371EA93A83C89AB9440724131E65F2B0161DE9560CDE9C13' + + '455552B2F49CF0FB00D8D77532324913F6F80FF29D0A131D29DB06AFF8BE191B7920' + + 'DC2DAE1C26EA82A47847A10391EF3BF6AABB3CC40FF82100B03A4F0FF1809278E4DD' + + 'FDA7DE954ED56DC7AD9A47EEBC37D771A366FC60A5BCB72373BEC180649B3EFA0E90' + + '92707210B41B90032BB18BC91F2046EBDAF1191F4A4E26D71879C4C7867B62FCD508' + + 'E8CE66E82D128A71E915809FCF44E8DE774067F1DE5D70B9C03687'); + assert.equal(exponent, '10001'); +}); diff --git a/node-v0.8.14/test/simple/test-https-invalid-key.js b/node-v0.8.14/test/simple/test-https-invalid-key.js new file mode 100644 index 0000000..82e05a2 --- /dev/null +++ b/node-v0.8.14/test/simple/test-https-invalid-key.js @@ -0,0 +1,62 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +if (!process.versions.openssl) { + console.error('Skipping because node compiled without OpenSSL.'); + process.exit(0); +} + +var common = require('../common'); +var assert = require('assert'); +var https = require('https'); +var fs = require('fs'); +var path = require('path'); + +var options = { + key: fs.readFileSync(path.join(common.fixturesDir, 'keys/agent1-key.pem')), + cert: fs.readFileSync(path.join(common.fixturesDir, 'test_cert.pem')) +}; +var serverErrorHappened = false; +var clientErrorHappened = false; + +var server = https.Server(options, function(req, res) { + assert(false); +}); +server.on('clientError', function(err) { + serverErrorHappened = true; + common.debug('Server: ' + err); + server.close(); +}); + +server.listen(common.PORT, function() { + var req = https.get({port: common.PORT}, function(res) { + assert(false); + }); + req.on('error', function(err) { + clientErrorHappened = true; + common.debug('Client: ' + err); + }); +}); + +process.on('exit', function() { + assert(serverErrorHappened); + assert(clientErrorHappened); +}); diff --git a/node-v0.8.14/test/simple/test-https-localaddress-bind-error.js b/node-v0.8.14/test/simple/test-https-localaddress-bind-error.js new file mode 100644 index 0000000..157df05 --- /dev/null +++ b/node-v0.8.14/test/simple/test-https-localaddress-bind-error.js @@ -0,0 +1,62 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var https = require('https'); +var fs = require('fs'); + +var options = { + key: fs.readFileSync(common.fixturesDir + '/keys/agent1-key.pem'), + cert: fs.readFileSync(common.fixturesDir + '/keys/agent1-cert.pem') +}; + +var invalidLocalAddress = '1.2.3.4'; +var gotError = false; + +var server = https.createServer(options, function(req, res) { + console.log("Connect from: " + req.connection.remoteAddress); + + req.on('end', function() { + res.writeHead(200, { 'Content-Type': 'text/plain' }); + res.end('You are from: ' + req.connection.remoteAddress); + }); +}); + +server.listen(common.PORT, "127.0.0.1", function() { + var req = https.request({ + host: 'localhost', + port: common.PORT, + path: '/', + method: 'GET', + localAddress: invalidLocalAddress + }, function(res) { + assert.fail('unexpectedly got response from server'); + }).on('error', function(e) { + console.log('client got error: ' + e.message); + gotError = true; + server.close(); + }).end(); +}); + +process.on('exit', function() { + assert.ok(gotError); +}); diff --git a/node-v0.8.14/test/simple/test-https-localaddress.js b/node-v0.8.14/test/simple/test-https-localaddress.js new file mode 100644 index 0000000..b171225 --- /dev/null +++ b/node-v0.8.14/test/simple/test-https-localaddress.js @@ -0,0 +1,61 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var https = require('https'), + fs = require('fs'), + assert = require('assert'); + +if (['linux', 'win32'].indexOf(process.platform) == -1) { + console.log('Skipping platform-specific test.'); + process.exit(); +} + +var options = { + key: fs.readFileSync(common.fixturesDir + '/keys/agent1-key.pem'), + cert: fs.readFileSync(common.fixturesDir + '/keys/agent1-cert.pem') +}; + +var server = https.createServer(options, function (req, res) { + console.log("Connect from: " + req.connection.socket.remoteAddress); + assert.equal('127.0.0.2', req.connection.socket.remoteAddress); + + req.on('end', function() { + res.writeHead(200, { 'Content-Type': 'text/plain' }); + res.end('You are from: ' + req.connection.remoteAddress); + }); +}); + +server.listen(common.PORT, "127.0.0.1", function() { + var options = { host: 'localhost', + port: common.PORT, + path: '/', + method: 'GET', + localAddress: '127.0.0.2' }; + + var req = https.request(options, function(res) { + res.on('end', function() { + server.close(); + process.exit(); + }); + }); + req.end(); +}); diff --git a/node-v0.8.14/test/simple/test-https-pfx.js b/node-v0.8.14/test/simple/test-https-pfx.js new file mode 100644 index 0000000..bfed64a --- /dev/null +++ b/node-v0.8.14/test/simple/test-https-pfx.js @@ -0,0 +1,56 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var https = require('https'); +var fs = require('fs'); + +var pfx = fs.readFileSync(common.fixturesDir + '/test_cert.pfx'); + +var options = { + host: '127.0.0.1', + port: common.PORT, + path: '/', + pfx: pfx, + passphrase: 'sample', + requestCert: true +}; + +var server = https.createServer(options, function(req, res) { + assert.equal(req.socket.authorized, false); // not a client cert + assert.equal(req.socket.authorizationError, 'UNABLE_TO_GET_ISSUER_CERT'); + res.writeHead(200); + res.end('OK'); +}); + +server.listen(options.port, options.host, function() { + var data = ''; + + https.get(options, function(res) { + res.on('data', function(data_) { data += data_ }); + res.on('end', function() { server.close() }); + }); + + process.on('exit', function() { + assert.equal(data, 'OK'); + }); +}); diff --git a/node-v0.8.14/test/simple/test-https-simple.js b/node-v0.8.14/test/simple/test-https-simple.js new file mode 100644 index 0000000..552450c --- /dev/null +++ b/node-v0.8.14/test/simple/test-https-simple.js @@ -0,0 +1,75 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + + + +if (!process.versions.openssl) { + console.error('Skipping because node compiled without OpenSSL.'); + process.exit(0); +} + +var common = require('../common'); +var assert = require('assert'); + +var fs = require('fs'); +var exec = require('child_process').exec; + +var https = require('https'); + +var options = { + key: fs.readFileSync(common.fixturesDir + '/keys/agent1-key.pem'), + cert: fs.readFileSync(common.fixturesDir + '/keys/agent1-cert.pem') +}; + +var reqCount = 0; +var body = 'hello world\n'; + +var server = https.createServer(options, function(req, res) { + reqCount++; + console.log('got request'); + res.writeHead(200, { 'content-type': 'text/plain' }); + res.end(body); +}); + + +server.listen(common.PORT, function() { + var cmd = 'curl --insecure https://127.0.0.1:' + common.PORT + '/'; + console.error('executing %j', cmd); + exec(cmd, function(err, stdout, stderr) { + if (err) throw err; + common.error(common.inspect(stdout)); + assert.equal(body, stdout); + + // Do the same thing now without --insecure + // The connection should not be accepted. + var cmd = 'curl https://127.0.0.1:' + common.PORT + '/'; + console.error('executing %j', cmd); + exec(cmd, function(err, stdout, stderr) { + assert.ok(err); + server.close(); + }); + }); +}); + +process.on('exit', function() { + assert.equal(1, reqCount); +}); diff --git a/node-v0.8.14/test/simple/test-https-socket-options.js b/node-v0.8.14/test/simple/test-https-socket-options.js new file mode 100644 index 0000000..f021664 --- /dev/null +++ b/node-v0.8.14/test/simple/test-https-socket-options.js @@ -0,0 +1,83 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + + + +if (!process.versions.openssl) { + console.error('Skipping because node compiled without OpenSSL.'); + process.exit(0); +} + +var common = require('../common'); +var assert = require('assert'); + +var fs = require('fs'); +var exec = require('child_process').exec; + +var http = require('http'); +var https = require('https'); + +var options = { + key: fs.readFileSync(common.fixturesDir + '/keys/agent1-key.pem'), + cert: fs.readFileSync(common.fixturesDir + '/keys/agent1-cert.pem') +}; + +var body = 'hello world\n'; + +// Try first with http server + +var server_http = http.createServer(function(req, res) { + console.log('got HTTP request'); + res.writeHead(200, { 'content-type': 'text/plain' }); + res.end(body); +}); + + +server_http.listen(common.PORT, function() { + var req = http.request({ port: common.PORT }, function(res) { + server_http.close(); + }); + // These methods should exist on the request and get passed down to the socket + req.setNoDelay(true); + req.setTimeout(1000, function() { }); + req.setSocketKeepAlive(true, 1000); + req.end(); +}); + +// Then try https server (requires functions to be mirroed in tls.js's CryptoStream) + +var server_https = https.createServer(options, function(req, res) { + console.log('got HTTPS request'); + res.writeHead(200, { 'content-type': 'text/plain' }); + res.end(body); +}); + +server_https.listen(common.PORT+1, function() { + var req = https.request({ port: common.PORT+1 }, function(res) { + server_https.close(); + }); + // These methods should exist on the request and get passed down to the socket + req.setNoDelay(true); + req.setTimeout(1000, function() { }); + req.setSocketKeepAlive(true, 1000); + req.end(); +}); diff --git a/node-v0.8.14/test/simple/test-https-strict.js b/node-v0.8.14/test/simple/test-https-strict.js new file mode 100644 index 0000000..e62c0d5 --- /dev/null +++ b/node-v0.8.14/test/simple/test-https-strict.js @@ -0,0 +1,218 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +if (!process.versions.openssl) { + console.error('Skipping because node compiled without OpenSSL.'); + process.exit(0); +} + +var common = require('../common'); +var assert = require('assert'); + +var fs = require('fs'); +var path = require('path'); +var https = require('https'); + +function file(fname) { + return path.resolve(common.fixturesDir, 'keys', fname); +} + +function read(fname) { + return fs.readFileSync(file(fname)); +} + +// key1 is signed by ca1. +var key1 = read('agent1-key.pem'); +var cert1 = read('agent1-cert.pem'); + +// key2 has a self signed cert +var key2 = read('agent2-key.pem'); +var cert2 = read('agent2-cert.pem'); + +// key3 is signed by ca2. +var key3 = read('agent3-key.pem'); +var cert3 = read('agent3-cert.pem'); + +var ca1 = read('ca1-cert.pem'); +var ca2 = read('ca2-cert.pem'); + +// different agents to use different CA lists. +// this api is beyond bad. +var agent0 = new https.Agent(); +var agent1 = new https.Agent({ ca: [ca1] }); +var agent2 = new https.Agent({ ca: [ca2] }); +var agent3 = new https.Agent({ ca: [ca1, ca2] }); + +var options1 = { + key: key1, + cert: cert1 +}; + +var options2 = { + key: key2, + cert: cert2 +}; + +var options3 = { + key: key3, + cert: cert3 +}; + +var server1 = server(options1); +var server2 = server(options2); +var server3 = server(options3); + +var listenWait = 0; + +var port = common.PORT; +var port1 = port++; +var port2 = port++; +var port3 = port++; +server1.listen(port1, listening()); +server2.listen(port2, listening()); +server3.listen(port3, listening()); + +var responseErrors = {}; +var expectResponseCount = 0; +var responseCount = 0; +var pending = 0; + + + +function server(options, port) { + var s = https.createServer(options, handler); + s.requests = []; + s.expectCount = 0; + return s; +} + +function handler(req, res) { + this.requests.push(req.url); + res.statusCode = 200; + res.setHeader('foo', 'bar'); + res.end('hello, world\n'); +} + +function listening() { + listenWait++; + return function() { + listenWait--; + if (listenWait === 0) { + allListening(); + } + } +} + +function makeReq(path, port, error, host, ca) { + pending++; + var options = { + port: port, + path: path, + ca: ca + }; + var whichCa = 0; + if (!ca) { + options.agent = agent0; + } else { + if (!Array.isArray(ca)) ca = [ca]; + if (-1 !== ca.indexOf(ca1) && -1 !== ca.indexOf(ca2)) { + options.agent = agent3; + } else if (-1 !== ca.indexOf(ca1)) { + options.agent = agent1; + } else if (-1 !== ca.indexOf(ca2)) { + options.agent = agent2; + } else { + options.agent = agent0; + } + } + + if (host) { + options.headers = { host: host } + } + var req = https.get(options); + expectResponseCount++; + var server = port === port1 ? server1 + : port === port2 ? server2 + : port === port3 ? server3 + : null; + + if (!server) throw new Error('invalid port: '+port); + server.expectCount++; + + req.on('response', function(res) { + responseCount++; + assert.equal(res.connection.authorizationError, error); + responseErrors[path] = res.connection.authorizationError; + pending--; + if (pending === 0) { + server1.close(); + server2.close(); + server3.close(); + } + }) +} + +function allListening() { + // ok, ready to start the tests! + + // server1: host 'agent1', signed by ca1 + makeReq('/inv1', port1, 'UNABLE_TO_VERIFY_LEAF_SIGNATURE'); + makeReq('/inv1-ca1', port1, + 'Hostname/IP doesn\'t match certificate\'s altnames', + null, ca1); + makeReq('/inv1-ca1ca2', port1, + 'Hostname/IP doesn\'t match certificate\'s altnames', + null, [ca1, ca2]); + makeReq('/val1-ca1', port1, null, 'agent1', ca1); + makeReq('/val1-ca1ca2', port1, null, 'agent1', [ca1, ca2]); + makeReq('/inv1-ca2', port1, + 'UNABLE_TO_VERIFY_LEAF_SIGNATURE', 'agent1', ca2); + + // server2: self-signed, host = 'agent2' + // doesn't matter that thename matches, all of these will error. + makeReq('/inv2', port2, 'DEPTH_ZERO_SELF_SIGNED_CERT'); + makeReq('/inv2-ca1', port2, 'DEPTH_ZERO_SELF_SIGNED_CERT', + 'agent2', ca1); + makeReq('/inv2-ca1ca2', port2, 'DEPTH_ZERO_SELF_SIGNED_CERT', + 'agent2', [ca1, ca2]); + + // server3: host 'agent3', signed by ca2 + makeReq('/inv3', port3, 'UNABLE_TO_VERIFY_LEAF_SIGNATURE'); + makeReq('/inv3-ca2', port3, + 'Hostname/IP doesn\'t match certificate\'s altnames', + null, ca2); + makeReq('/inv3-ca1ca2', port3, + 'Hostname/IP doesn\'t match certificate\'s altnames', + null, [ca1, ca2]); + makeReq('/val3-ca2', port3, null, 'agent3', ca2); + makeReq('/val3-ca1ca2', port3, null, 'agent3', [ca1, ca2]); + makeReq('/inv3-ca1', port3, + 'UNABLE_TO_VERIFY_LEAF_SIGNATURE', 'agent1', ca1); + +} + +process.on('exit', function() { + console.error(responseErrors); + assert.equal(server1.requests.length, server1.expectCount); + assert.equal(server2.requests.length, server2.expectCount); + assert.equal(server3.requests.length, server3.expectCount); + assert.equal(responseCount, expectResponseCount); +}); diff --git a/node-v0.8.14/test/simple/test-https-timeout.js b/node-v0.8.14/test/simple/test-https-timeout.js new file mode 100644 index 0000000..8a8ae00 --- /dev/null +++ b/node-v0.8.14/test/simple/test-https-timeout.js @@ -0,0 +1,73 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +if (!process.versions.openssl) { + console.error('Skipping because node compiled without OpenSSL.'); + process.exit(0); +} + +var common = require('../common'); +var assert = require('assert'); +var fs = require('fs'); +var exec = require('child_process').exec; +var https = require('https'); + +var options = { + key: fs.readFileSync(common.fixturesDir + '/keys/agent1-key.pem'), + cert: fs.readFileSync(common.fixturesDir + '/keys/agent1-cert.pem') +}; + +// a server that never replies +var server = https.createServer(options, function() { + console.log('Got request. Doing nothing.'); +}).listen(common.PORT, function() { + var req = https.request({ + host: 'localhost', + port: common.PORT, + path: '/', + method: 'GET' + }); + req.setTimeout(10); + req.end(); + + req.on('response', function(res) { + console.log('got response'); + }); + + req.on('socket', function() { + console.log('got a socket'); + + req.socket.on('connect', function() { + console.log('socket connected'); + }); + + setTimeout(function() { + throw new Error('Did not get timeout event'); + }, 200); + }); + + req.on('timeout', function() { + console.log('timeout occurred outside'); + req.destroy(); + server.close(); + process.exit(0); + }); +}); diff --git a/node-v0.8.14/test/simple/test-init.js b/node-v0.8.14/test/simple/test-init.js new file mode 100644 index 0000000..da05984 --- /dev/null +++ b/node-v0.8.14/test/simple/test-init.js @@ -0,0 +1,68 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + + + +(function() { + var assert = require('assert'), + child = require('child_process'), + util = require('util'), + common = require('../common'); + if (process.env['TEST_INIT']) { + util.print('Loaded successfully!'); + } else { + // change CWD as we do this test so its not dependant on current CWD + // being in the test folder + process.chdir(__dirname); + + child.exec(process.execPath + ' test-init', {env: {'TEST_INIT': 1}}, + function(err, stdout, stderr) { + assert.equal(stdout, 'Loaded successfully!', + '`node test-init` failed!'); + }); + child.exec(process.execPath + ' test-init.js', {env: {'TEST_INIT': 1}}, + function(err, stdout, stderr) { + assert.equal(stdout, 'Loaded successfully!', + '`node test-init.js` failed!'); + }); + + // test-init-index is in fixtures dir as requested by ry, so go there + process.chdir(common.fixturesDir); + + child.exec(process.execPath + ' test-init-index', {env: {'TEST_INIT': 1}}, + function(err, stdout, stderr) { + assert.equal(stdout, 'Loaded successfully!', + '`node test-init-index failed!'); + }); + + // ensures that `node fs` does not mistakenly load the native 'fs' module + // instead of the desired file and that the fs module loads as + // expected in node + process.chdir(common.fixturesDir + '/test-init-native/'); + + child.exec(process.execPath + ' fs', {env: {'TEST_INIT': 1}}, + function(err, stdout, stderr) { + assert.equal(stdout, 'fs loaded successfully', + '`node fs` failed!'); + }); + } +})(); diff --git a/node-v0.8.14/test/simple/test-listen-fd-cluster.js b/node-v0.8.14/test/simple/test-listen-fd-cluster.js new file mode 100644 index 0000000..0d6d774 --- /dev/null +++ b/node-v0.8.14/test/simple/test-listen-fd-cluster.js @@ -0,0 +1,136 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var http = require('http'); +var net = require('net'); +var PORT = common.PORT; +var spawn = require('child_process').spawn; +var cluster = require('cluster'); + +console.error('Cluster listen fd test', process.argv.slice(2)); + +if (process.platform === 'win32') { + console.error('This test is disabled on windows.'); + return; +} + +switch (process.argv[2]) { + case 'master': return master(); + case 'worker': return worker(); + case 'parent': return parent(); + default: return test(); +} + +// spawn the parent, and listen for it to tell us the pid of the cluster. +// WARNING: This is an example of listening on some arbitrary FD number +// that has already been bound elsewhere in advance. However, binding +// server handles to stdio fd's is NOT a good or reliable way to do +// concurrency in HTTP servers! Use the cluster module, or if you want +// a more low-level approach, use child process IPC manually. +function test() { + var parent = spawn(process.execPath, [__filename, 'parent'], { + stdio: [ 0, 'pipe', 2 ] + }); + var json = ''; + parent.stdout.on('data', function(c) { + json += c.toString(); + if (json.indexOf('\n') !== -1) next(); + }); + function next() { + console.error('output from parent = %s', json); + var cluster = JSON.parse(json); + // now make sure that we can request to the worker, then kill it. + http.get({ + server: 'localhost', + port: PORT, + path: '/', + }).on('response', function (res) { + var s = ''; + res.on('data', function(c) { + s += c.toString(); + }); + res.on('end', function() { + // kill the worker before we start doing asserts. + // it's really annoying when tests leave orphans! + parent.kill(); + process.kill(cluster.master, 'SIGKILL'); + + assert.equal(s, 'hello from worker\n'); + assert.equal(res.statusCode, 200); + console.log('ok'); + }); + }) + } +} + +function parent() { + console.error('about to listen in parent'); + var server = net.createServer(function(conn) { + console.error('connection on parent'); + conn.end('hello from parent\n'); + }).listen(PORT, function() { + console.error('server listening on %d', PORT); + + var spawn = require('child_process').spawn; + var master = spawn(process.execPath, [__filename, 'master'], { + stdio: [ 0, 1, 2, server._handle ], + detached: true + }); + + // Now close the parent, so that the master is the only thing + // referencing that handle. Note that connections will still + // be accepted, because the master has the fd open. + server.close(); + + master.on('exit', function(code) { + console.error('master exited', code); + }); + + master.on('close', function() { + console.error('master closed'); + }); + console.error('master spawned'); + }); +} + +function master() { + console.error('in master, spawning worker'); + cluster.setupMaster({ + args: [ 'worker' ] + }); + var worker = cluster.fork(); + console.log('%j\n', { master: process.pid, worker: worker.pid }); +} + + +function worker() { + console.error('worker, about to create server and listen on fd=3'); + // start a server on fd=3 + http.createServer(function(req, res) { + console.error('request on worker'); + console.error('%s %s', req.method, req.url, req.headers); + res.end('hello from worker\n'); + }).listen({ fd: 3 }, function() { + console.error('worker listening on fd=3'); + }); +} diff --git a/node-v0.8.14/test/simple/test-listen-fd-detached-inherit.js b/node-v0.8.14/test/simple/test-listen-fd-detached-inherit.js new file mode 100644 index 0000000..dabc46c --- /dev/null +++ b/node-v0.8.14/test/simple/test-listen-fd-detached-inherit.js @@ -0,0 +1,119 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var http = require('http'); +var net = require('net'); +var PORT = common.PORT; +var spawn = require('child_process').spawn; + +if (process.platform === 'win32') { + console.error('This test is disabled on windows.'); + return; +} + +switch (process.argv[2]) { + case 'child': return child(); + case 'parent': return parent(); + default: return test(); +} + +// spawn the parent, and listen for it to tell us the pid of the child. +// WARNING: This is an example of listening on some arbitrary FD number +// that has already been bound elsewhere in advance. However, binding +// server handles to stdio fd's is NOT a good or reliable way to do +// concurrency in HTTP servers! Use the cluster module, or if you want +// a more low-level approach, use child process IPC manually. +function test() { + var parent = spawn(process.execPath, [__filename, 'parent'], { + stdio: [ 0, 'pipe', 2 ] + }); + var json = ''; + parent.stdout.on('data', function(c) { + json += c.toString(); + if (json.indexOf('\n') !== -1) next(); + }); + function next() { + console.error('output from parent = %s', json); + var child = JSON.parse(json); + // now make sure that we can request to the child, then kill it. + http.get({ + server: 'localhost', + port: PORT, + path: '/', + }).on('response', function (res) { + var s = ''; + res.on('data', function(c) { + s += c.toString(); + }); + res.on('end', function() { + // kill the child before we start doing asserts. + // it's really annoying when tests leave orphans! + process.kill(child.pid, 'SIGKILL'); + try { + parent.kill(); + } catch (e) {} + + assert.equal(s, 'hello from child\n'); + assert.equal(res.statusCode, 200); + }); + }) + } +} + +// Listen on PORT, and then pass the handle to the detached child. +// Then output the child's pid, and immediately exit. +function parent() { + var server = net.createServer(function(conn) { + throw new Error('Should not see connections on parent'); + conn.end('HTTP/1.1 403 Forbidden\r\n\r\nI got problems.\r\n'); + }).listen(PORT, function() { + console.error('server listening on %d', PORT); + + var child = spawn(process.execPath, [__filename, 'child'], { + stdio: [ 0, 1, 2, server._handle ], + detached: true + }); + + console.log('%j\n', { pid: child.pid }); + + // Now close the parent, so that the child is the only thing + // referencing that handle. Note that connections will still + // be accepted, because the child has the fd open, but the parent + // will exit gracefully. + server.close(); + child.unref(); + }); +} + +// Run as a child of the parent() mode. +function child() { + // start a server on fd=3 + http.createServer(function(req, res) { + console.error('request on child'); + console.error('%s %s', req.method, req.url, req.headers); + res.end('hello from child\n'); + }).listen({ fd: 3 }, function() { + console.error('child listening on fd=3'); + }); +} + diff --git a/node-v0.8.14/test/simple/test-listen-fd-detached.js b/node-v0.8.14/test/simple/test-listen-fd-detached.js new file mode 100644 index 0000000..3d98abe --- /dev/null +++ b/node-v0.8.14/test/simple/test-listen-fd-detached.js @@ -0,0 +1,117 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var http = require('http'); +var net = require('net'); +var PORT = common.PORT; +var spawn = require('child_process').spawn; + +if (process.platform === 'win32') { + console.error('This test is disabled on windows.'); + return; +} + +switch (process.argv[2]) { + case 'child': return child(); + case 'parent': return parent(); + default: return test(); +} + +// spawn the parent, and listen for it to tell us the pid of the child. +// WARNING: This is an example of listening on some arbitrary FD number +// that has already been bound elsewhere in advance. However, binding +// server handles to stdio fd's is NOT a good or reliable way to do +// concurrency in HTTP servers! Use the cluster module, or if you want +// a more low-level approach, use child process IPC manually. +function test() { + var parent = spawn(process.execPath, [__filename, 'parent'], { + stdio: [ 0, 'pipe', 2 ] + }); + var json = ''; + parent.stdout.on('data', function(c) { + json += c.toString(); + if (json.indexOf('\n') !== -1) next(); + }); + function next() { + console.error('output from parent = %s', json); + var child = JSON.parse(json); + // now make sure that we can request to the child, then kill it. + http.get({ + server: 'localhost', + port: PORT, + path: '/', + }).on('response', function (res) { + var s = ''; + res.on('data', function(c) { + s += c.toString(); + }); + res.on('end', function() { + // kill the child before we start doing asserts. + // it's really annoying when tests leave orphans! + process.kill(child.pid, 'SIGKILL'); + try { + parent.kill(); + } catch (e) {} + + assert.equal(s, 'hello from child\n'); + assert.equal(res.statusCode, 200); + }); + }) + } +} + +function parent() { + var server = net.createServer(function(conn) { + console.error('connection on parent'); + conn.end('hello from parent\n'); + }).listen(PORT, function() { + console.error('server listening on %d', PORT); + + var spawn = require('child_process').spawn; + var child = spawn(process.execPath, [__filename, 'child'], { + stdio: [ 'ignore', 'ignore', 'ignore', server._handle ], + detached: true + }); + + console.log('%j\n', { pid: child.pid }); + + // Now close the parent, so that the child is the only thing + // referencing that handle. Note that connections will still + // be accepted, because the child has the fd open, but the parent + // will exit gracefully. + server.close(); + child.unref(); + }); +} + +function child() { + // start a server on fd=3 + http.createServer(function(req, res) { + console.error('request on child'); + console.error('%s %s', req.method, req.url, req.headers); + res.end('hello from child\n'); + }).listen({ fd: 3 }, function() { + console.error('child listening on fd=3'); + }); +} + diff --git a/node-v0.8.14/test/simple/test-listen-fd-ebadf.js b/node-v0.8.14/test/simple/test-listen-fd-ebadf.js new file mode 100644 index 0000000..6c0f20a --- /dev/null +++ b/node-v0.8.14/test/simple/test-listen-fd-ebadf.js @@ -0,0 +1,38 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var net = require('net'); + +var gotError = 0; + +process.on('exit', function() { + assert.equal(gotError, 2); +}); + +net.createServer(assert.fail).listen({fd:2}).on('error', onError); +net.createServer(assert.fail).listen({fd:42}).on('error', onError); + +function onError(ex) { + assert.equal(ex.code, 'EINVAL'); + gotError++; +} diff --git a/node-v0.8.14/test/simple/test-listen-fd-server.js b/node-v0.8.14/test/simple/test-listen-fd-server.js new file mode 100644 index 0000000..8f3454f --- /dev/null +++ b/node-v0.8.14/test/simple/test-listen-fd-server.js @@ -0,0 +1,122 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var http = require('http'); +var net = require('net'); +var PORT = common.PORT; +var spawn = require('child_process').spawn; + +if (process.platform === 'win32') { + console.error('This test is disabled on windows.'); + return; +} + +switch (process.argv[2]) { + case 'child': return child(); + case 'parent': return parent(); + default: return test(); +} + +// spawn the parent, and listen for it to tell us the pid of the child. +// WARNING: This is an example of listening on some arbitrary FD number +// that has already been bound elsewhere in advance. However, binding +// server handles to stdio fd's is NOT a good or reliable way to do +// concurrency in HTTP servers! Use the cluster module, or if you want +// a more low-level approach, use child process IPC manually. +function test() { + var parent = spawn(process.execPath, [__filename, 'parent'], { + stdio: [ 0, 'pipe', 2 ] + }); + var json = ''; + parent.stdout.on('data', function(c) { + json += c.toString(); + if (json.indexOf('\n') !== -1) next(); + }); + function next() { + console.error('output from parent = %s', json); + var child = JSON.parse(json); + // now make sure that we can request to the child, then kill it. + http.get({ + server: 'localhost', + port: PORT, + path: '/', + }).on('response', function (res) { + var s = ''; + res.on('data', function(c) { + s += c.toString(); + }); + res.on('end', function() { + // kill the child before we start doing asserts. + // it's really annoying when tests leave orphans! + process.kill(child.pid, 'SIGKILL'); + try { + parent.kill(); + } catch (e) {} + + assert.equal(s, 'hello from child\n'); + assert.equal(res.statusCode, 200); + }); + }) + } +} + +function child() { + // start a server on fd=3 + http.createServer(function(req, res) { + console.error('request on child'); + console.error('%s %s', req.method, req.url, req.headers); + res.end('hello from child\n'); + }).listen({ fd: 3 }, function() { + console.error('child listening on fd=3'); + }); +} + +function parent() { + var server = net.createServer(function(conn) { + console.error('connection on parent'); + conn.end('hello from parent\n'); + }).listen(PORT, function() { + console.error('server listening on %d', PORT); + + var spawn = require('child_process').spawn; + var child = spawn(process.execPath, [__filename, 'child'], { + stdio: [ 0, 1, 2, server._handle ] + }); + + console.log('%j\n', { pid: child.pid }); + + // Now close the parent, so that the child is the only thing + // referencing that handle. Note that connections will still + // be accepted, because the child has the fd open. + server.close(); + + child.on('exit', function(code) { + console.error('child exited', code); + }); + + child.on('close', function() { + console.error('child closed'); + }); + console.error('child spawned'); + }); +} diff --git a/node-v0.8.14/test/simple/test-memory-usage-emfile.js b/node-v0.8.14/test/simple/test-memory-usage-emfile.js new file mode 100644 index 0000000..aaed899 --- /dev/null +++ b/node-v0.8.14/test/simple/test-memory-usage-emfile.js @@ -0,0 +1,37 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + + + +var common = require('../common'); +var assert = require('assert'); + +var fs = require('fs'); + +var files = []; + +while (files.length < 256) + files.push(fs.openSync(__filename, 'r')); + +var r = process.memoryUsage(); +console.log(common.inspect(r)); +assert.equal(true, r['rss'] > 0); diff --git a/node-v0.8.14/test/simple/test-memory-usage.js b/node-v0.8.14/test/simple/test-memory-usage.js new file mode 100644 index 0000000..0df1742 --- /dev/null +++ b/node-v0.8.14/test/simple/test-memory-usage.js @@ -0,0 +1,30 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + + + +var common = require('../common'); +var assert = require('assert'); + +var r = process.memoryUsage(); +console.log(common.inspect(r)); +assert.equal(true, r['rss'] > 0); diff --git a/node-v0.8.14/test/simple/test-mkdir-rmdir.js b/node-v0.8.14/test/simple/test-mkdir-rmdir.js new file mode 100644 index 0000000..7353455 --- /dev/null +++ b/node-v0.8.14/test/simple/test-mkdir-rmdir.js @@ -0,0 +1,61 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var path = require('path'); +var fs = require('fs'); + +var dirname = path.dirname(__filename); +var d = path.join(common.tmpDir, 'dir'); + +var mkdir_error = false; +var rmdir_error = false; + +fs.mkdir(d, 0666, function(err) { + if (err) { + console.log('mkdir error: ' + err.message); + mkdir_error = true; + } else { + fs.mkdir(d, 0666, function(err) { + console.log('expect EEXIST error: ', err); + assert.ok(err.message.match(/^EEXIST/), 'got EEXIST message'); + assert.equal(err.code, 'EEXIST', 'got EEXIST code'); + assert.equal(err.path, d, 'got proper path for EEXIST'); + + console.log('mkdir okay!'); + fs.rmdir(d, function(err) { + if (err) { + console.log('rmdir error: ' + err.message); + rmdir_error = true; + } else { + console.log('rmdir okay!'); + } + }); + }); + } +}); + +process.on('exit', function() { + assert.equal(false, mkdir_error); + assert.equal(false, rmdir_error); + console.log('exit'); +}); diff --git a/node-v0.8.14/test/simple/test-module-loading-error.js b/node-v0.8.14/test/simple/test-module-loading-error.js new file mode 100644 index 0000000..c1afd58 --- /dev/null +++ b/node-v0.8.14/test/simple/test-module-loading-error.js @@ -0,0 +1,44 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); + +common.debug('load test-module-loading-error.js'); + +var error_desc = { + win32: '%1 is not a valid Win32 application', + linux: 'file too short', + sunos: 'unknown file type' +}; + +var dlerror_msg = error_desc[process.platform]; + +if (!dlerror_msg) { + console.error('Skipping test, platform not supported.'); + process.exit(); +} + +try { + require('../fixtures/module-loading-error.node'); +} catch (e) { + assert.notEqual(e.toString().indexOf(dlerror_msg), -1); +} diff --git a/node-v0.8.14/test/simple/test-module-loading.js b/node-v0.8.14/test/simple/test-module-loading.js new file mode 100644 index 0000000..eadd667 --- /dev/null +++ b/node-v0.8.14/test/simple/test-module-loading.js @@ -0,0 +1,297 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + + + +var common = require('../common'); +var assert = require('assert'); +var path = require('path'); +var fs = require('fs'); + +common.debug('load test-module-loading.js'); + +// assert that this is the main module. +assert.equal(require.main.id, '.', 'main module should have id of \'.\''); +assert.equal(require.main, module, 'require.main should === module'); +assert.equal(process.mainModule, module, + 'process.mainModule should === module'); +// assert that it's *not* the main module in the required module. +require('../fixtures/not-main-module.js'); + +// require a file with a request that includes the extension +var a_js = require('../fixtures/a.js'); +assert.equal(42, a_js.number); + +// require a file without any extensions +var foo_no_ext = require('../fixtures/foo'); +assert.equal('ok', foo_no_ext.foo); + +var a = require('../fixtures/a'); +var c = require('../fixtures/b/c'); +var d = require('../fixtures/b/d'); +var d2 = require('../fixtures/b/d'); +// Absolute +var d3 = require(path.join(__dirname, '../fixtures/b/d')); +// Relative +var d4 = require('../fixtures/b/d'); + +assert.equal(false, false, 'testing the test program.'); + +assert.equal(true, common.indirectInstanceOf(a.A, Function)); +assert.equal('A', a.A()); + +assert.equal(true, common.indirectInstanceOf(a.C, Function)); +assert.equal('C', a.C()); + +assert.equal(true, common.indirectInstanceOf(a.D, Function)); +assert.equal('D', a.D()); + +assert.equal(true, common.indirectInstanceOf(d.D, Function)); +assert.equal('D', d.D()); + +assert.equal(true, common.indirectInstanceOf(d2.D, Function)); +assert.equal('D', d2.D()); + +assert.equal(true, common.indirectInstanceOf(d3.D, Function)); +assert.equal('D', d3.D()); + +assert.equal(true, common.indirectInstanceOf(d4.D, Function)); +assert.equal('D', d4.D()); + +assert.ok((new a.SomeClass) instanceof c.SomeClass); + +common.debug('test index.js modules ids and relative loading'); +var one = require('../fixtures/nested-index/one'), + two = require('../fixtures/nested-index/two'); +assert.notEqual(one.hello, two.hello); + +common.debug('test index.js in a folder with a trailing slash'); +var three = require('../fixtures/nested-index/three'), + threeFolder = require('../fixtures/nested-index/three/'), + threeIndex = require('../fixtures/nested-index/three/index.js'); +assert.equal(threeFolder, threeIndex); +assert.notEqual(threeFolder, three); + +common.debug('test package.json require() loading'); +assert.equal(require('../fixtures/packages/main').ok, 'ok', + 'Failed loading package'); +assert.equal(require('../fixtures/packages/main-index').ok, 'ok', + 'Failed loading package with index.js in main subdir'); + +common.debug('test cycles containing a .. path'); +var root = require('../fixtures/cycles/root'), + foo = require('../fixtures/cycles/folder/foo'); +assert.equal(root.foo, foo); +assert.equal(root.sayHello(), root.hello); + +common.debug('test node_modules folders'); +// asserts are in the fixtures files themselves, +// since they depend on the folder structure. +require('../fixtures/node_modules/foo'); + +common.debug('test name clashes'); +// this one exists and should import the local module +var my_path = require('./path'); +assert.ok(common.indirectInstanceOf(my_path.path_func, Function)); +// this one does not exist and should throw +assert.throws(function() { require('./utils')}); + +var errorThrown = false; +try { + require('../fixtures/throws_error'); +} catch (e) { + errorThrown = true; + assert.equal('blah', e.message); +} + +assert.equal(require('path').dirname(__filename), __dirname); + +common.debug('load custom file types with extensions'); +require.extensions['.test'] = function(module, filename) { + var content = fs.readFileSync(filename).toString(); + assert.equal('this is custom source\n', content); + content = content.replace('this is custom source', + 'exports.test = \'passed\''); + module._compile(content, filename); +}; + +assert.equal(require('../fixtures/registerExt').test, 'passed'); +// unknown extension, load as .js +assert.equal(require('../fixtures/registerExt.hello.world').test, 'passed'); + +common.debug('load custom file types that return non-strings'); +require.extensions['.test'] = function(module, filename) { + module.exports = { + custom: 'passed' + }; +}; + +assert.equal(require('../fixtures/registerExt2').custom, 'passed'); + +assert.equal(require('../fixtures/foo').foo, 'ok', + 'require module with no extension'); + +assert.throws(function() { + require.paths; +}, /removed/, 'Accessing require.paths should throw.'); + +// Should not attempt to load a directory +try { + require('../fixtures/empty'); +} catch (err) { + assert.equal(err.message, 'Cannot find module \'../fixtures/empty\''); +} + +// Check load order is as expected +common.debug('load order'); + +var loadOrder = '../fixtures/module-load-order/', + msg = 'Load order incorrect.'; + +require.extensions['.reg'] = require.extensions['.js']; +require.extensions['.reg2'] = require.extensions['.js']; + +assert.equal(require(loadOrder + 'file1').file1, 'file1', msg); +assert.equal(require(loadOrder + 'file2').file2, 'file2.js', msg); +try { + require(loadOrder + 'file3'); +} catch (e) { + // Not a real .node module, but we know we require'd the right thing. + assert.ok(e.message.replace(/\\/g, '/').match(/file3\.node/)); +} +assert.equal(require(loadOrder + 'file4').file4, 'file4.reg', msg); +assert.equal(require(loadOrder + 'file5').file5, 'file5.reg2', msg); +assert.equal(require(loadOrder + 'file6').file6, 'file6/index.js', msg); +try { + require(loadOrder + 'file7'); +} catch (e) { + assert.ok(e.message.replace(/\\/g, '/').match(/file7\/index\.node/)); +} +assert.equal(require(loadOrder + 'file8').file8, 'file8/index.reg', msg); +assert.equal(require(loadOrder + 'file9').file9, 'file9/index.reg2', msg); + + +// make sure that module.require() is the same as +// doing require() inside of that module. +var parent = require('../fixtures/module-require/parent/'); +var child = require('../fixtures/module-require/child/'); +assert.equal(child.loaded, parent.loaded); + + +// #1357 Loading JSON files with require() +var json = require('../fixtures/packages/main/package.json'); +assert.deepEqual(json, { + name: 'package-name', + version: '1.2.3', + main: 'package-main-module' +}); + + +// now verify that module.children contains all the different +// modules that we've required, and that all of them contain +// the appropriate children, and so on. + +var children = module.children.reduce(function red(set, child) { + var id = path.relative(path.dirname(__dirname), child.id) + id = id.replace(/\\/g, '/'); + set[id] = child.children.reduce(red, {}); + return set; +}, {}); + +assert.deepEqual(children, { + 'common.js': {}, + 'fixtures/not-main-module.js': {}, + 'fixtures/a.js': { + 'fixtures/b/c.js': { + 'fixtures/b/d.js': {}, + 'fixtures/b/package/index.js': {} + } + }, + 'fixtures/foo': {}, + 'fixtures/nested-index/one/index.js': { + 'fixtures/nested-index/one/hello.js': {} + }, + 'fixtures/nested-index/two/index.js': { + 'fixtures/nested-index/two/hello.js': {} + }, + 'fixtures/nested-index/three.js': {}, + 'fixtures/nested-index/three/index.js': {}, + 'fixtures/packages/main/package-main-module.js': {}, + 'fixtures/packages/main-index/package-main-module/index.js': {}, + 'fixtures/cycles/root.js': { + 'fixtures/cycles/folder/foo.js': {} + }, + 'fixtures/node_modules/foo.js': { + 'fixtures/node_modules/baz/index.js': { + 'fixtures/node_modules/bar.js': {}, + 'fixtures/node_modules/baz/node_modules/asdf.js': {} + } + }, + 'simple/path.js': {}, + 'fixtures/throws_error.js': {}, + 'fixtures/registerExt.test': {}, + 'fixtures/registerExt.hello.world': {}, + 'fixtures/registerExt2.test': {}, + 'fixtures/empty.js': {}, + 'fixtures/module-load-order/file1': {}, + 'fixtures/module-load-order/file2.js': {}, + 'fixtures/module-load-order/file3.node': {}, + 'fixtures/module-load-order/file4.reg': {}, + 'fixtures/module-load-order/file5.reg2': {}, + 'fixtures/module-load-order/file6/index.js': {}, + 'fixtures/module-load-order/file7/index.node': {}, + 'fixtures/module-load-order/file8/index.reg': {}, + 'fixtures/module-load-order/file9/index.reg2': {}, + 'fixtures/module-require/parent/index.js': { + 'fixtures/module-require/child/index.js': { + 'fixtures/module-require/child/node_modules/target.js': {} + } + }, + 'fixtures/packages/main/package.json': {} +}); + + +process.on('exit', function() { + assert.ok(common.indirectInstanceOf(a.A, Function)); + assert.equal('A done', a.A()); + + assert.ok(common.indirectInstanceOf(a.C, Function)); + assert.equal('C done', a.C()); + + assert.ok(common.indirectInstanceOf(a.D, Function)); + assert.equal('D done', a.D()); + + assert.ok(common.indirectInstanceOf(d.D, Function)); + assert.equal('D done', d.D()); + + assert.ok(common.indirectInstanceOf(d2.D, Function)); + assert.equal('D done', d2.D()); + + assert.equal(true, errorThrown); + + console.log('exit'); +}); + + +// #1440 Loading files with a byte order marker. +assert.equal(42, require('../fixtures/utf8-bom.js')); +assert.equal(42, require('../fixtures/utf8-bom.json')); diff --git a/node-v0.8.14/test/simple/test-net-after-close.js b/node-v0.8.14/test/simple/test-net-after-close.js new file mode 100644 index 0000000..65fda21 --- /dev/null +++ b/node-v0.8.14/test/simple/test-net-after-close.js @@ -0,0 +1,52 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var net = require('net'); +var closed = false; + +var server = net.createServer(function(s) { + s.end(); +}); + +server.listen(common.PORT, function() { + var c = net.createConnection(common.PORT); + c.on('close', function() { + assert.strictEqual(c._handle, null); + closed = true; + assert.doesNotThrow(function() { + c.setNoDelay(); + c.setKeepAlive(); + c.bufferSize; + c.pause(); + c.resume(); + c.address(); + c.remoteAddress; + c.remotePort; + }); + server.close(); + }); +}); + +process.on('exit', function() { + assert(closed); +}); diff --git a/node-v0.8.14/test/simple/test-net-binary.js b/node-v0.8.14/test/simple/test-net-binary.js new file mode 100644 index 0000000..349e2da --- /dev/null +++ b/node-v0.8.14/test/simple/test-net-binary.js @@ -0,0 +1,97 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var net = require('net'); + +var binaryString = ''; +for (var i = 255; i >= 0; i--) { + var s = '\'\\' + i.toString(8) + '\''; + var S = eval(s); + common.error(s + + ' ' + + JSON.stringify(S) + + ' ' + + JSON.stringify(String.fromCharCode(i)) + + ' ' + + S.charCodeAt(0)); + assert.ok(S.charCodeAt(0) == i); + assert.ok(S == String.fromCharCode(i)); + binaryString += S; +} + +// safe constructor +var echoServer = net.Server(function(connection) { + connection.setEncoding('binary'); + connection.on('data', function(chunk) { + common.error('recved: ' + JSON.stringify(chunk)); + connection.write(chunk, 'binary'); + }); + connection.on('end', function() { + connection.end(); + }); +}); +echoServer.listen(common.PORT); + +var recv = ''; + +echoServer.on('listening', function() { + var j = 0; + var c = net.createConnection(common.PORT); + + c.setEncoding('binary'); + c.on('data', function(chunk) { + if (j < 256) { + common.error('write ' + j); + c.write(String.fromCharCode(j), 'binary'); + j++; + } else { + c.end(); + } + recv += chunk; + }); + + c.on('connect', function() { + c.write(binaryString, 'binary'); + }); + + c.on('close', function() { + console.dir(recv); + echoServer.close(); + }); +}); + +process.on('exit', function() { + console.log('recv: ' + JSON.stringify(recv)); + + assert.equal(2 * 256, recv.length); + + var a = recv.split(''); + + var first = a.slice(0, 256).reverse().join(''); + console.log('first: ' + JSON.stringify(first)); + + var second = a.slice(256, 2 * 256).join(''); + console.log('second: ' + JSON.stringify(second)); + + assert.equal(first, second); +}); diff --git a/node-v0.8.14/test/simple/test-net-bind-twice.js b/node-v0.8.14/test/simple/test-net-bind-twice.js new file mode 100644 index 0000000..58086cc --- /dev/null +++ b/node-v0.8.14/test/simple/test-net-bind-twice.js @@ -0,0 +1,46 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var net = require('net'); + +var gotError = false; + +process.on('exit', function() { + assert(gotError); +}); + +function dontCall() { + assert(false); +} + +var server1 = net.createServer(dontCall); +server1.listen(common.PORT, '127.0.0.1', function() {}); + +var server2 = net.createServer(dontCall); +server2.listen(common.PORT, '127.0.0.1', dontCall); + +server2.on('error', function(e) { + assert.equal(e.code, 'EADDRINUSE'); + server1.close(); + gotError = true; +}); diff --git a/node-v0.8.14/test/simple/test-net-bytes-stats.js b/node-v0.8.14/test/simple/test-net-bytes-stats.js new file mode 100644 index 0000000..a406e99 --- /dev/null +++ b/node-v0.8.14/test/simple/test-net-bytes-stats.js @@ -0,0 +1,74 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + + + +var common = require('../common'); +var assert = require('assert'); +var net = require('net'); + +var tcpPort = common.PORT; +var bytesRead = 0; +var bytesWritten = 0; +var count = 0; + +var tcp = net.Server(function(s) { + console.log('tcp server connection'); + + s.on('end', function() { + bytesRead += s.bytesRead; + console.log('tcp socket disconnect #' + count); + }); +}); + +tcp.listen(common.PORT, function() { + var socket = net.createConnection(tcpPort); + + socket.on('connect', function() { + count++; + console.log('tcp client connection #' + count); + + socket.write('foo', function() { + socket.end('bar'); + }); + }); + + socket.on('end', function() { + bytesWritten += socket.bytesWritten; + console.log('tcp client disconnect #' + count); + }); + + socket.on('close', function() { + console.log('Bytes read: ' + bytesRead); + console.log('Bytes written: ' + bytesWritten); + if (count < 2) { + socket.connect(tcpPort); + } else { + tcp.close(); + } + }); +}); + +process.on('exit', function() { + assert.equal(bytesRead, 12); + assert.equal(bytesWritten, 12); +}); diff --git a/node-v0.8.14/test/simple/test-net-can-reset-timeout.js b/node-v0.8.14/test/simple/test-net-can-reset-timeout.js new file mode 100644 index 0000000..bb9b071 --- /dev/null +++ b/node-v0.8.14/test/simple/test-net-can-reset-timeout.js @@ -0,0 +1,62 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var net = require('net'); +var common = require('../common'); +var assert = require('assert'); + +var timeoutCount = 0; + +var server = net.createServer(function(stream) { + stream.setTimeout(100); + + stream.on('timeout', function() { + console.log('timeout'); + // try to reset the timeout. + stream.write('WHAT.'); + // don't worry, the socket didn't *really* time out, we're just thinking + // it did. + timeoutCount += 1; + }); + + stream.on('end', function() { + console.log('server side end'); + stream.end(); + }); +}); + +server.listen(common.PORT, function() { + var c = net.createConnection(common.PORT); + + c.on('data', function() { + c.end(); + }); + + c.on('end', function() { + console.log('client side end'); + server.close(); + }); +}); + + +process.on('exit', function() { + assert.equal(1, timeoutCount); +}); diff --git a/node-v0.8.14/test/simple/test-net-connect-buffer.js b/node-v0.8.14/test/simple/test-net-connect-buffer.js new file mode 100644 index 0000000..0950593 --- /dev/null +++ b/node-v0.8.14/test/simple/test-net-connect-buffer.js @@ -0,0 +1,110 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var net = require('net'); + +var tcpPort = common.PORT; +var dataWritten = false; +var connectHappened = false; + +var tcp = net.Server(function(s) { + tcp.close(); + + console.log('tcp server connection'); + + var buf = ''; + s.on('data', function(d) { + buf += d; + }); + + s.on('end', function() { + assert.equal(buf, "L'État, c'est moi"); + console.log('tcp socket disconnect'); + s.end(); + }); + + s.on('error', function(e) { + console.log('tcp server-side error: ' + e.message); + process.exit(1); + }); +}); + +tcp.listen(common.PORT, function() { + var socket = net.Stream(); + + console.log('Connecting to socket '); + + socket.connect(tcpPort, function() { + console.log('socket connected'); + connectHappened = true; + }); + + console.log('_connecting = ' + socket._connecting); + + assert.equal('opening', socket.readyState); + + // Make sure that anything besides a buffer or a string throws. + [null, + true, + false, + undefined, + 1, + 1.0, + 1 / 0, + +Infinity, + -Infinity, + [], + {} + ].forEach(function(v) { + function f() { + socket.write(v); + } + assert.throws(f, TypeError); + }); + + // Write a string that contains a multi-byte character sequence to test that + // `bytesWritten` is incremented with the # of bytes, not # of characters. + var a = "L'État, c'est "; + var b = 'moi'; + + // We're still connecting at this point so the datagram is first pushed onto + // the connect queue. Make sure that it's not added to `bytesWritten` again + // when the actual write happens. + var r = socket.write(a, function() { + dataWritten = true; + assert.ok(connectHappened); + assert.equal(socket.bytesWritten, Buffer(a + b).length); + console.error('data written'); + }); + assert.equal(socket.bytesWritten, Buffer(a).length); + + assert.equal(false, r); + socket.end(b); + + assert.equal('opening', socket.readyState); +}); + +process.on('exit', function() { + assert.ok(connectHappened); + assert.ok(dataWritten); +}); diff --git a/node-v0.8.14/test/simple/test-net-connect-handle-econnrefused.js b/node-v0.8.14/test/simple/test-net-connect-handle-econnrefused.js new file mode 100644 index 0000000..e890b6a --- /dev/null +++ b/node-v0.8.14/test/simple/test-net-connect-handle-econnrefused.js @@ -0,0 +1,48 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + + + +var common = require('../common'); +var net = require('net'); +var assert = require('assert'); + + +// Hopefully nothing is running on common.PORT +var c = net.createConnection(common.PORT); + +c.on('connect', function() { + console.error('connected?!'); + assert.ok(false); +}); + +var gotError = false; +c.on('error', function(e) { + console.error('couldn\'t connect.'); + gotError = true; + assert.equal('ECONNREFUSED', e.code); +}); + + +process.on('exit', function() { + assert.ok(gotError); +}); diff --git a/node-v0.8.14/test/simple/test-net-connect-options.js b/node-v0.8.14/test/simple/test-net-connect-options.js new file mode 100644 index 0000000..8df692e --- /dev/null +++ b/node-v0.8.14/test/simple/test-net-connect-options.js @@ -0,0 +1,58 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var net = require('net'); + +var serverGotEnd = false; +var clientGotEnd = false; + +var server = net.createServer({allowHalfOpen: true}, function(socket) { + socket.on('end', function() { + serverGotEnd = true; + }); + socket.end(); +}); + +server.listen(common.PORT, function() { + var client = net.connect({ + host: '127.0.0.1', + port: common.PORT, + allowHalfOpen: true + }, function() { + client.on('end', function() { + clientGotEnd = true; + setTimeout(function() { + assert(client.writable); + client.end(); + }, 10); + }); + client.on('close', function() { + server.close(); + }); + }); +}); + +process.on('exit', function() { + assert(serverGotEnd); + assert(clientGotEnd); +}); diff --git a/node-v0.8.14/test/simple/test-net-connect-timeout.js b/node-v0.8.14/test/simple/test-net-connect-timeout.js new file mode 100644 index 0000000..a5a11a8 --- /dev/null +++ b/node-v0.8.14/test/simple/test-net-connect-timeout.js @@ -0,0 +1,94 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// This example attempts to time out before the connection is established +// https://groups.google.com/forum/#!topic/nodejs/UE0ZbfLt6t8 +// https://groups.google.com/forum/#!topic/nodejs-dev/jR7-5UDqXkw +// +// TODO: how to do this without relying on the responses of specific sites? + +var common = require('../common'); +var net = require('net'); +var assert = require('assert'); + +var start = new Date(); + +var gotTimeout0 = false; +var gotTimeout1 = false; + +var gotConnect0 = false; +var gotConnect1 = false; + +var T = 100; + + +// With DNS + +var socket0 = net.createConnection(9999, 'google.com'); + +socket0.setTimeout(T); + +socket0.on('timeout', function() { + console.error('timeout'); + gotTimeout0 = true; + var now = new Date(); + assert.ok(now - start < T + 500); + socket0.destroy(); +}); + +socket0.on('connect', function() { + console.error('connect'); + gotConnect0 = true; + socket0.destroy(); +}); + + +// Without DNS + +var socket1 = net.createConnection(9999, '24.24.24.24'); + +socket1.setTimeout(T); + +socket1.on('timeout', function() { + console.error('timeout'); + gotTimeout1 = true; + var now = new Date(); + assert.ok(now - start < T + 500); + socket1.destroy(); +}); + +socket1.on('connect', function() { + console.error('connect'); + gotConnect1 = true; + socket1.destroy(); +}); + + + + + +process.on('exit', function() { + assert.ok(gotTimeout0); + assert.ok(!gotConnect0); + + assert.ok(gotTimeout1); + assert.ok(!gotConnect1); +}); diff --git a/node-v0.8.14/test/simple/test-net-create-connection.js b/node-v0.8.14/test/simple/test-net-create-connection.js new file mode 100644 index 0000000..c21be15 --- /dev/null +++ b/node-v0.8.14/test/simple/test-net-create-connection.js @@ -0,0 +1,50 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var net = require('net'); + +var tcpPort = common.PORT; +var clientConnected = 0; +var serverConnected = 0; + +var server = net.createServer(function(socket) { + socket.end(); + if (++serverConnected === 4) { + server.close(); + } +}); +server.listen(tcpPort, 'localhost', function() { + function cb() { + ++clientConnected; + } + + net.createConnection(tcpPort).on('connect', cb); + net.createConnection(tcpPort, 'localhost').on('connect', cb); + net.createConnection(tcpPort, cb); + net.createConnection(tcpPort, 'localhost', cb); +}); + +process.on('exit', function() { + assert.equal(clientConnected, 4); +}); + diff --git a/node-v0.8.14/test/simple/test-net-dns-error.js b/node-v0.8.14/test/simple/test-net-dns-error.js new file mode 100644 index 0000000..10857a9 --- /dev/null +++ b/node-v0.8.14/test/simple/test-net-dns-error.js @@ -0,0 +1,49 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); + +var net = require('net'); + +var expected_bad_connections = 1; +var actual_bad_connections = 0; + +var host = '********'; +host += host; +host += host; +host += host; +host += host; +host += host; + +function do_not_call() { + throw new Error('This function should not have been called.'); +} + +var socket = net.connect(42, host, do_not_call); +socket.on('error', function(err) { + assert.equal(err.code, 'ENOTFOUND'); + actual_bad_connections++; +}); + +process.on('exit', function() { + assert.equal(actual_bad_connections, expected_bad_connections); +}); diff --git a/node-v0.8.14/test/simple/test-net-during-close.js b/node-v0.8.14/test/simple/test-net-during-close.js new file mode 100644 index 0000000..0bcdd4d --- /dev/null +++ b/node-v0.8.14/test/simple/test-net-during-close.js @@ -0,0 +1,47 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var net = require('net'); +var accessedProperties = false; + +var server = net.createServer(function(socket) { + socket.end(); +}); + +server.listen(common.PORT, function() { + var client = net.createConnection(common.PORT); + server.close(); + // server connection event has not yet fired + // client is still attempting to connect + assert.doesNotThrow(function() { + client.remoteAddress; + client.remotePort; + }); + accessedProperties = true; + // exit now, do not wait for the client error event + process.exit(0); +}); + +process.on('exit', function() { + assert(accessedProperties); +}); diff --git a/node-v0.8.14/test/simple/test-net-eaddrinuse.js b/node-v0.8.14/test/simple/test-net-eaddrinuse.js new file mode 100644 index 0000000..2192ea2 --- /dev/null +++ b/node-v0.8.14/test/simple/test-net-eaddrinuse.js @@ -0,0 +1,35 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var net = require('net'); + +var server1 = net.createServer(function(socket) { +}); +var server2 = net.createServer(function(socket) { +}); +server1.listen(common.PORT); +server2.on('error', function(error) { + assert.equal(true, error.message.indexOf('EADDRINUSE') >= 0); + server1.close(); +}); +server2.listen(common.PORT); diff --git a/node-v0.8.14/test/simple/test-net-isip.js b/node-v0.8.14/test/simple/test-net-isip.js new file mode 100644 index 0000000..4f60f50 --- /dev/null +++ b/node-v0.8.14/test/simple/test-net-isip.js @@ -0,0 +1,48 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var net = require('net'); + +assert.equal(net.isIP('127.0.0.1'), 4); +assert.equal(net.isIP('x127.0.0.1'), 0); +assert.equal(net.isIP('example.com'), 0); +assert.equal(net.isIP('0000:0000:0000:0000:0000:0000:0000:0000'), 6); +assert.equal(net.isIP('0000:0000:0000:0000:0000:0000:0000:0000::0000'), 0); +assert.equal(net.isIP('1050:0:0:0:5:600:300c:326b'), 6); +assert.equal(net.isIP('2001:252:0:1::2008:6'), 6); +assert.equal(net.isIP('2001:dead:beef:1::2008:6'), 6); +assert.equal(net.isIP('ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff'), 6); +assert.equal(net.isIP('::1'), 6); +assert.equal(net.isIP('::'), 6); +assert.equal(net.isIP('0000:0000:0000:0000:0000:0000:12345:0000'), 0); +assert.equal(net.isIP('0'), 0); +assert.equal(net.isIP(), 0); +assert.equal(net.isIP(""), 0); + +assert.equal(net.isIPv4('127.0.0.1'), true); +assert.equal(net.isIPv4('example.com'), false); +assert.equal(net.isIPv4('2001:252:0:1::2008:6'), false); + +assert.equal(net.isIPv6('127.0.0.1'), false); +assert.equal(net.isIPv6('example.com'), false); +assert.equal(net.isIPv6('2001:252:0:1::2008:6'), true); \ No newline at end of file diff --git a/node-v0.8.14/test/simple/test-net-keepalive.js b/node-v0.8.14/test/simple/test-net-keepalive.js new file mode 100644 index 0000000..b09d9d5 --- /dev/null +++ b/node-v0.8.14/test/simple/test-net-keepalive.js @@ -0,0 +1,51 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var net = require('net'); + +var serverConnection; +var echoServer = net.createServer(function(connection) { + serverConnection = connection; + connection.setTimeout(0); + assert.notEqual(connection.setKeepAlive, undefined); + // send a keepalive packet after 1000 ms + connection.setKeepAlive(true, 1000); + connection.on('end', function() { + connection.end(); + }); +}); +echoServer.listen(common.PORT); + +echoServer.on('listening', function() { + var clientConnection = net.createConnection(common.PORT); + clientConnection.setTimeout(0); + + setTimeout(function() { + // make sure both connections are still open + assert.equal(serverConnection.readyState, 'open'); + assert.equal(clientConnection.readyState, 'open'); + serverConnection.end(); + clientConnection.end(); + echoServer.close(); + }, 1200); +}); diff --git a/node-v0.8.14/test/simple/test-net-large-string.js b/node-v0.8.14/test/simple/test-net-large-string.js new file mode 100644 index 0000000..877dc7c --- /dev/null +++ b/node-v0.8.14/test/simple/test-net-large-string.js @@ -0,0 +1,55 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var net = require('net'); + +var kPoolSize = 40 * 1024; +var data = ''; +for (var i = 0; i < kPoolSize; ++i) { + data += 'あ'; // 3bytes +} +var receivedSize = 0; +var encoding = 'UTF-8'; + +var server = net.createServer(function(socket) { + socket.setEncoding(encoding); + socket.on('data', function(data) { + receivedSize += data.length; + }); + socket.on('end', function() { + socket.end(); + }); +}); + +server.listen(common.PORT, function() { + var client = net.createConnection(common.PORT); + client.on('end', function() { + server.close(); + }); + client.write(data, encoding); + client.end(); +}); + +process.on('exit', function() { + assert.equal(receivedSize, kPoolSize); +}); diff --git a/node-v0.8.14/test/simple/test-net-listen-error.js b/node-v0.8.14/test/simple/test-net-listen-error.js new file mode 100644 index 0000000..17ec762 --- /dev/null +++ b/node-v0.8.14/test/simple/test-net-listen-error.js @@ -0,0 +1,39 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var net = require('net'); +var gotError = false; + +var server = net.createServer(function(socket) { +}); +server.listen(1, '1.1.1.1', function() { // EACCESS or EADDRNOTAVAIL + assert(false); +}); +server.on('error', function(error) { + common.debug(error); + gotError = true; +}); + +process.on('exit', function() { + assert(gotError); +}); diff --git a/node-v0.8.14/test/simple/test-net-listen-fd0.js b/node-v0.8.14/test/simple/test-net-listen-fd0.js new file mode 100644 index 0000000..ba0d598 --- /dev/null +++ b/node-v0.8.14/test/simple/test-net-listen-fd0.js @@ -0,0 +1,36 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var net = require('net'); + +var gotError = false; + +process.on('exit', function() { + assert.equal(gotError, true); +}); + +// this should fail with an async EINVAL error, not throw an exception +net.createServer(assert.fail).listen({fd:0}).on('error', function(e) { + assert.equal(e.code, 'EINVAL'); + gotError = true; +}); diff --git a/node-v0.8.14/test/simple/test-net-pause-resume-connecting.js b/node-v0.8.14/test/simple/test-net-pause-resume-connecting.js new file mode 100644 index 0000000..264dc96 --- /dev/null +++ b/node-v0.8.14/test/simple/test-net-pause-resume-connecting.js @@ -0,0 +1,101 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'), + assert = require('assert'), + net = require('net'); + +var connections = 0, + dataEvents = 0, + conn; + + +// Server +var server = net.createServer(function(conn) { + connections++; + conn.end('This was the year he fell to pieces.'); + + if (connections === 5) + server.close(); +}); + +server.listen(common.PORT); + + +// Client 1 +conn = require('net').createConnection(common.PORT, 'localhost'); +conn.resume(); +conn.on('data', onDataOk); + + +// Client 2 +conn = require('net').createConnection(common.PORT, 'localhost'); +conn.pause(); +conn.resume(); +conn.on('data', onDataOk); + + +// Client 3 +conn = require('net').createConnection(common.PORT, 'localhost'); +conn.pause(); +conn.on('data', onDataError); +scheduleTearDown(conn); + + +// Client 4 +conn = require('net').createConnection(common.PORT, 'localhost'); +conn.resume(); +conn.pause(); +conn.resume(); +conn.on('data', onDataOk); + + +// Client 5 +conn = require('net').createConnection(common.PORT, 'localhost'); +conn.resume(); +conn.resume(); +conn.pause(); +conn.on('data', onDataError); +scheduleTearDown(conn); + + +// Client helper functions +function onDataError() { + assert(false); +} + +function onDataOk() { + dataEvents++; +} + +function scheduleTearDown(conn) { + setTimeout(function() { + conn.removeAllListeners('data'); + conn.resume(); + }, 100); +} + + +// Exit sanity checks +process.on('exit', function() { + assert.strictEqual(connections, 5); + assert.strictEqual(dataEvents, 3); +}); diff --git a/node-v0.8.14/test/simple/test-net-pingpong.js b/node-v0.8.14/test/simple/test-net-pingpong.js new file mode 100644 index 0000000..a81f0dc --- /dev/null +++ b/node-v0.8.14/test/simple/test-net-pingpong.js @@ -0,0 +1,140 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); + +var net = require('net'); + +var tests_run = 0; + +function pingPongTest(port, host) { + var N = 1000; + var count = 0; + var sentPongs = 0; + var sent_final_ping = false; + + var server = net.createServer({ allowHalfOpen: true }, function(socket) { + console.log('connection: ' + socket.remoteAddress); + assert.equal(server, socket.server); + assert.equal(1, server.connections); + + socket.setNoDelay(); + socket.timeout = 0; + + socket.setEncoding('utf8'); + socket.on('data', function(data) { + // Since we never queue data (we're always waiting for the PING + // before sending a pong) the writeQueueSize should always be less + // than one message. + assert.ok(0 <= socket.bufferSize && socket.bufferSize <= 4); + + console.log('server got: ' + data); + assert.equal(true, socket.writable); + assert.equal(true, socket.readable); + assert.equal(true, count <= N); + if (/PING/.exec(data)) { + socket.write('PONG', function() { + sentPongs++; + console.error('sent PONG'); + }); + } + }); + + socket.on('end', function() { + assert.equal(true, socket.writable); // because allowHalfOpen + assert.equal(false, socket.readable); + socket.end(); + }); + + socket.on('error', function(e) { + throw e; + }); + + socket.on('close', function() { + console.log('server socket.endd'); + assert.equal(false, socket.writable); + assert.equal(false, socket.readable); + socket.server.close(); + }); + }); + + + server.listen(port, host, function() { + console.log('server listening on ' + port + ' ' + host); + + var client = net.createConnection(port, host); + + client.setEncoding('ascii'); + client.on('connect', function() { + assert.equal(true, client.readable); + assert.equal(true, client.writable); + client.write('PING'); + }); + + client.on('data', function(data) { + console.log('client got: ' + data); + + assert.equal('PONG', data); + count += 1; + + if (sent_final_ping) { + assert.equal(false, client.writable); + assert.equal(true, client.readable); + return; + } else { + assert.equal(true, client.writable); + assert.equal(true, client.readable); + } + + if (count < N) { + client.write('PING'); + } else { + sent_final_ping = true; + client.write('PING'); + client.end(); + } + }); + + client.on('close', function() { + console.log('client.end'); + assert.equal(N + 1, count); + assert.equal(N + 1, sentPongs); + assert.equal(true, sent_final_ping); + tests_run += 1; + }); + + client.on('error', function(e) { + throw e; + }); + }); +} + +/* All are run at once, so run on different ports */ +pingPongTest(common.PIPE); +pingPongTest(20988); +pingPongTest(20989, 'localhost'); +pingPongTest(20997, '::1'); + +process.on('exit', function() { + assert.equal(4, tests_run); + console.log('done'); +}); diff --git a/node-v0.8.14/test/simple/test-net-pipe-connect-errors.js b/node-v0.8.14/test/simple/test-net-pipe-connect-errors.js new file mode 100644 index 0000000..8200a16 --- /dev/null +++ b/node-v0.8.14/test/simple/test-net-pipe-connect-errors.js @@ -0,0 +1,86 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var fs = require('fs'); +var net = require('net'); +var path = require('path'); +var assert = require('assert'); +var common = require('../common'); + +var notSocketErrorFired = false; +var noEntErrorFired = false; +var accessErrorFired = false; + +// Test if ENOTSOCK is fired when trying to connect to a file which is not +// a socket. +var emptyTxt = path.join(common.fixturesDir, 'empty.txt'); +var notSocketClient = net.createConnection(emptyTxt, function() { + assert.ok(false); +}); + +notSocketClient.on('error', function(err) { + assert(err.code === 'ENOTSOCK' || err.code === 'ECONNREFUSED'); + notSocketErrorFired = true; +}); + + +// Trying to connect to not-existing socket should result in ENOENT error +var noEntSocketClient = net.createConnection('no-ent-file', function() { + assert.ok(false); +}); + +noEntSocketClient.on('error', function(err) { + assert.equal(err.code, 'ENOENT'); + noEntErrorFired = true; +}); + + +// On Windows or when running as root, a chmod has no effect on named pipes +if (process.platform !== 'win32' && process.getuid() !== 0) { + // Trying to connect to a socket one has no access to should result in EACCES + var accessServer = net.createServer(function() { + assert.ok(false); + }); + accessServer.listen(common.PIPE, function() { + fs.chmodSync(common.PIPE, 0); + + var accessClient = net.createConnection(common.PIPE, function() { + assert.ok(false); + }); + + accessClient.on('error', function(err) { + assert.equal(err.code, 'EACCES'); + accessErrorFired = true; + accessServer.close(); + }); + }); +} + + +// Assert that all error events were fired +process.on('exit', function() { + assert.ok(notSocketErrorFired); + assert.ok(noEntErrorFired); + if (process.platform !== 'win32' && process.getuid() !== 0) { + assert.ok(accessErrorFired); + } +}); + diff --git a/node-v0.8.14/test/simple/test-net-reconnect.js b/node-v0.8.14/test/simple/test-net-reconnect.js new file mode 100644 index 0000000..f7fcb8b --- /dev/null +++ b/node-v0.8.14/test/simple/test-net-reconnect.js @@ -0,0 +1,78 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); + +var net = require('net'); + +var N = 50; +var c = 0; +var client_recv_count = 0; +var disconnect_count = 0; + +var server = net.createServer(function(socket) { + socket.on('connect', function() { + socket.write('hello\r\n'); + }); + + socket.on('end', function() { + socket.end(); + }); + + socket.on('close', function(had_error) { + //console.log('server had_error: ' + JSON.stringify(had_error)); + assert.equal(false, had_error); + }); +}); + +server.listen(common.PORT, function() { + console.log('listening'); + var client = net.createConnection(common.PORT); + + client.setEncoding('UTF8'); + + client.on('connect', function() { + console.log('client connected.'); + }); + + client.on('data', function(chunk) { + client_recv_count += 1; + console.log('client_recv_count ' + client_recv_count); + assert.equal('hello\r\n', chunk); + client.end(); + }); + + client.on('close', function(had_error) { + console.log('disconnect'); + assert.equal(false, had_error); + if (disconnect_count++ < N) + client.connect(common.PORT); // reconnect + else + server.close(); + }); +}); + +process.on('exit', function() { + assert.equal(N + 1, disconnect_count); + assert.equal(N + 1, client_recv_count); +}); + diff --git a/node-v0.8.14/test/simple/test-net-remote-address-port.js b/node-v0.8.14/test/simple/test-net-remote-address-port.js new file mode 100644 index 0000000..9b585fc --- /dev/null +++ b/node-v0.8.14/test/simple/test-net-remote-address-port.js @@ -0,0 +1,56 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); + +var net = require('net'); + +var conns = 0, conns_closed = 0; + +var server = net.createServer(function(socket) { + conns++; + assert.equal('127.0.0.1', socket.remoteAddress); + assert.ok(socket.remotePort); + assert.notEqual(socket.remotePort, common.PORT); + socket.on('end', function() { + if (++conns_closed == 2) server.close(); + }); +}); + +server.listen(common.PORT, 'localhost', function() { + var client = net.createConnection(common.PORT, 'localhost'); + var client2 = net.createConnection(common.PORT); + client.on('connect', function() { + assert.equal('127.0.0.1', client.remoteAddress); + assert.equal(common.PORT, client.remotePort); + client.end(); + }); + client2.on('connect', function() { + assert.equal('127.0.0.1', client2.remoteAddress); + assert.equal(common.PORT, client2.remotePort); + client2.end(); + }); +}); + +process.on('exit', function() { + assert.equal(2, conns); +}); diff --git a/node-v0.8.14/test/simple/test-net-server-address.js b/node-v0.8.14/test/simple/test-net-server-address.js new file mode 100644 index 0000000..a9f92c4 --- /dev/null +++ b/node-v0.8.14/test/simple/test-net-server-address.js @@ -0,0 +1,58 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var net = require('net'); + +// Test on IPv4 Server +var localhost_ipv4 = '127.0.0.1'; +var family_ipv4 = 'IPv4'; +var server_ipv4 = net.createServer(); + +server_ipv4.on('error', function(e) { + console.log('Error on ipv4 socket: ' + e.toString()); +}); + +server_ipv4.listen(common.PORT, localhost_ipv4, function() { + var address_ipv4 = server_ipv4.address(); + assert.strictEqual(address_ipv4.address, localhost_ipv4); + assert.strictEqual(address_ipv4.port, common.PORT); + assert.strictEqual(address_ipv4.family, family_ipv4); + server_ipv4.close(); +}); + +// Test on IPv6 Server +var localhost_ipv6 = '::1'; +var family_ipv6 = 'IPv6'; +var server_ipv6 = net.createServer(); + +server_ipv6.on('error', function(e) { + console.log('Error on ipv6 socket: ' + e.toString()); +}); + +server_ipv6.listen(common.PORT, localhost_ipv6, function() { + var address_ipv6 = server_ipv6.address(); + assert.strictEqual(address_ipv6.address, localhost_ipv6); + assert.strictEqual(address_ipv6.port, common.PORT); + assert.strictEqual(address_ipv6.family, family_ipv6); + server_ipv6.close(); +}); diff --git a/node-v0.8.14/test/simple/test-net-server-bind.js b/node-v0.8.14/test/simple/test-net-server-bind.js new file mode 100644 index 0000000..0951aa2 --- /dev/null +++ b/node-v0.8.14/test/simple/test-net-server-bind.js @@ -0,0 +1,95 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var net = require('net'); + + +// With only a callback, server should get a port assigned by the OS + +var address0; +var server0 = net.createServer(function(socket) { }); + +server0.listen(function() { + address0 = server0.address(); + console.log('address0 %j', address0); + server0.close(); +}); + + +// No callback to listen(), assume we can bind in 100 ms + +var address1; +var server1 = net.createServer(function(socket) { }); + +server1.listen(common.PORT); + +setTimeout(function() { + address1 = server1.address(); + console.log('address1 %j', address1); + server1.close(); +}, 100); + + +// Callback to listen() + +var address2; +var server2 = net.createServer(function(socket) { }); + +server2.listen(common.PORT + 1, function() { + address2 = server2.address(); + console.log('address2 %j', address2); + server2.close(); +}); + + +// Backlog argument + +var address3; +var server3 = net.createServer(function(socket) { }); + +server3.listen(common.PORT + 2, '0.0.0.0', 127, function() { + address3 = server3.address(); + console.log('address3 %j', address3); + server3.close(); +}); + + +// Backlog argument without host argument + +var address4; +var server4 = net.createServer(function(socket) { }); + +server4.listen(common.PORT + 3, 127, function() { + address4 = server4.address(); + console.log('address4 %j', address4); + server4.close(); +}); + + +process.on('exit', function() { + assert.ok(address0.port > 100); + assert.equal(common.PORT, address1.port); + assert.equal(common.PORT + 1, address2.port); + assert.equal(common.PORT + 2, address3.port); + assert.equal(common.PORT + 3, address4.port); +}); diff --git a/node-v0.8.14/test/simple/test-net-server-close.js b/node-v0.8.14/test/simple/test-net-server-close.js new file mode 100644 index 0000000..b87a84d --- /dev/null +++ b/node-v0.8.14/test/simple/test-net-server-close.js @@ -0,0 +1,54 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var net = require('net'); + +var events = []; +var sockets = []; + +process.on('exit', function() { + assert.equal(server.connections, 0); + assert.deepEqual(events, 'client client server'.split(' ')); +}); + +var server = net.createServer(function(c) { + c.on('close', function() { + events.push('client'); + }); + + sockets.push(c); + + if (sockets.length === 2) { + server.close(); + sockets.forEach(function(c) { c.destroy() }); + } +}); + +server.on('close', function() { + events.push('server'); +}); + +server.listen(common.PORT, function() { + net.createConnection(common.PORT); + net.createConnection(common.PORT); +}); diff --git a/node-v0.8.14/test/simple/test-net-server-listen-remove-callback.js b/node-v0.8.14/test/simple/test-net-server-listen-remove-callback.js new file mode 100644 index 0000000..e10231d --- /dev/null +++ b/node-v0.8.14/test/simple/test-net-server-listen-remove-callback.js @@ -0,0 +1,43 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var net = require('net'); + +// Server should only fire listen callback once +var server = net.createServer(); + +server.on('close', function() { + var listeners = server.listeners('listening'); + console.log('Closed, listeners:', listeners.length); + assert.equal(0, listeners.length); +}); + +server.listen(common.PORT, function() { + server.close(); +}); + +server.once('close', function() { + server.listen(common.PORT + 1, function() { + server.close(); + }); +}); diff --git a/node-v0.8.14/test/simple/test-net-server-max-connections.js b/node-v0.8.14/test/simple/test-net-server-max-connections.js new file mode 100644 index 0000000..43bc2fe --- /dev/null +++ b/node-v0.8.14/test/simple/test-net-server-max-connections.js @@ -0,0 +1,107 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); + +var net = require('net'); + +// This test creates 200 connections to a server and sets the server's +// maxConnections property to 100. The first 100 connections make it through +// and the last 100 connections are rejected. +// TODO: test that the server can accept more connections after it reaches +// its maximum and some are closed. + +var N = 200; +var count = 0; +var closes = 0; +var waits = []; + +var server = net.createServer(function(connection) { + console.error('connect %d', count++); + connection.write('hello'); + waits.push(function() { connection.end(); }); +}); + +server.listen(common.PORT, function() { + makeConnection(0); +}); + +server.maxConnections = N / 2; + +console.error('server.maxConnections = %d', server.maxConnections); + + +function makeConnection(index) { + var c = net.createConnection(common.PORT); + var gotData = false; + + c.on('connect', function() { + if (index + 1 < N) { + makeConnection(index + 1); + } + }); + + c.on('end', function() { c.end(); }); + + c.on('data', function(b) { + gotData = true; + assert.ok(0 < b.length); + }); + + c.on('error', function(e) { + console.error('error %d: %s', index, e); + }); + + c.on('close', function() { + console.error('closed %d', index); + closes++; + + if (closes < N / 2) { + assert.ok(server.maxConnections <= index, + index + + ' was one of the first closed connections ' + + 'but shouldnt have been'); + } + + if (closes === N / 2) { + var cb; + console.error('calling wait callback.'); + while (cb = waits.shift()) { + cb(); + } + server.close(); + } + + if (index < server.maxConnections) { + assert.equal(true, gotData, + index + ' didn\'t get data, but should have'); + } else { + assert.equal(false, gotData, + index + ' got data, but shouldn\'t have'); + } + }); +} + + +process.on('exit', function() { + assert.equal(N, closes); +}); diff --git a/node-v0.8.14/test/simple/test-net-server-try-ports.js b/node-v0.8.14/test/simple/test-net-server-try-ports.js new file mode 100644 index 0000000..5eca9d0 --- /dev/null +++ b/node-v0.8.14/test/simple/test-net-server-try-ports.js @@ -0,0 +1,76 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// This tests binds to one port, then attempts to start a server on that +// port. It should be EADDRINUSE but be able to then bind to another port. +var common = require('../common'); +var assert = require('assert'); +var net = require('net'); + +var connections = 0; + +var server1listening = false; +var server2listening = false; + +var server1 = net.Server(function(socket) { + connections++; + socket.destroy(); +}); + +var server2 = net.Server(function(socket) { + connections++; + socket.destroy(); +}); + +var server2errors = 0; +server2.on('error', function() { + server2errors++; + console.error('server2 error'); +}); + + +server1.listen(common.PORT, function() { + console.error('server1 listening'); + server1listening = true; + // This should make server2 emit EADDRINUSE + server2.listen(common.PORT); + + // Wait a bit, now try again. + // TODO, the listen callback should report if there was an error. + // Then we could avoid this very unlikely but potential race condition + // here. + setTimeout(function() { + server2.listen(common.PORT + 1, function() { + console.error('server2 listening'); + server2listening = true; + + server1.close(); + server2.close(); + }); + }, 100); +}); + + +process.on('exit', function() { + assert.equal(1, server2errors); + assert.ok(server2listening); + assert.ok(server1listening); +}); diff --git a/node-v0.8.14/test/simple/test-net-settimeout.js b/node-v0.8.14/test/simple/test-net-settimeout.js new file mode 100644 index 0000000..da13385 --- /dev/null +++ b/node-v0.8.14/test/simple/test-net-settimeout.js @@ -0,0 +1,56 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// This example sets a timeout then immediately attempts to disable the timeout +// https://github.com/joyent/node/pull/2245 + +var common = require('../common'); +var net = require('net'); +var assert = require('assert'); + +var T = 100; + +var server = net.createServer(function(c) { + c.write('hello'); +}); +server.listen(common.PORT); + +var killers = [0, Infinity, NaN]; + +var left = killers.length; +killers.forEach(function(killer) { + var socket = net.createConnection(common.PORT, 'localhost'); + + socket.setTimeout(T, function() { + socket.destroy(); + if (--left === 0) server.close(); + assert.ok(killer !== 0); + clearTimeout(timeout); + }); + + socket.setTimeout(killer); + + var timeout = setTimeout(function() { + socket.destroy(); + if (--left === 0) server.close(); + assert.ok(killer === 0); + }, T * 2); +}); diff --git a/node-v0.8.14/test/simple/test-net-socket-destroy-twice.js b/node-v0.8.14/test/simple/test-net-socket-destroy-twice.js new file mode 100644 index 0000000..882e3a1 --- /dev/null +++ b/node-v0.8.14/test/simple/test-net-socket-destroy-twice.js @@ -0,0 +1,43 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var net = require('net'); + +var nerrors = 0; +var ncloses = 0; + +process.on('exit', function() { + assert.equal(nerrors, 1); + assert.equal(ncloses, 1); +}); + +var conn = net.createConnection(common.PORT); + +conn.on('error', function() { + nerrors++; + conn.destroy(); +}); + +conn.on('close', function() { + ncloses++; +}); diff --git a/node-v0.8.14/test/simple/test-net-socket-timeout.js b/node-v0.8.14/test/simple/test-net-socket-timeout.js new file mode 100644 index 0000000..2256d68 --- /dev/null +++ b/node-v0.8.14/test/simple/test-net-socket-timeout.js @@ -0,0 +1,44 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var net = require('net'); +var assert = require('assert'); + +var timedout = false; + +var server = net.Server(); +server.listen(common.PORT, function() { + var socket = net.createConnection(common.PORT); + socket.setTimeout(100, function() { + timedout = true; + socket.destroy(); + server.close(); + clearTimeout(timer); + }); + var timer = setTimeout(function() { + process.exit(1); + }, 200); +}); + +process.on('exit', function() { + assert.ok(timedout); +}); diff --git a/node-v0.8.14/test/simple/test-net-stream.js b/node-v0.8.14/test/simple/test-net-stream.js new file mode 100644 index 0000000..429995a --- /dev/null +++ b/node-v0.8.14/test/simple/test-net-stream.js @@ -0,0 +1,39 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); + +var net = require('net'); + +var s = new net.Stream(); + +// test that destroy called on a stream with a server only ever decrements the +// server connection count once + +s.server = new net.Server(); +s.server.connections = 10; + +assert.equal(10, s.server.connections); +s.destroy(); +assert.equal(9, s.server.connections); +s.destroy(); +assert.equal(9, s.server.connections); diff --git a/node-v0.8.14/test/simple/test-net-write-after-close.js b/node-v0.8.14/test/simple/test-net-write-after-close.js new file mode 100644 index 0000000..b77e9af --- /dev/null +++ b/node-v0.8.14/test/simple/test-net-write-after-close.js @@ -0,0 +1,51 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var net = require('net'); + +var gotError = false; +var gotWriteCB = false; + +process.on('exit', function() { + assert(gotError); + assert(gotWriteCB); +}); + +var server = net.createServer(function(socket) { + socket.on('error', function(error) { + server.close(); + gotError = true; + }); + + setTimeout(function() { + socket.write('test', function(e) { + gotWriteCB = true; + }); + }, 250); +}); + +server.listen(common.PORT, function() { + var client = net.connect(common.PORT, function() { + client.end(); + }); +}); diff --git a/node-v0.8.14/test/simple/test-net-write-connect-write.js b/node-v0.8.14/test/simple/test-net-write-connect-write.js new file mode 100644 index 0000000..cb65af8 --- /dev/null +++ b/node-v0.8.14/test/simple/test-net-write-connect-write.js @@ -0,0 +1,48 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var net = require('net'); + +var received = ''; + +var server = net.createServer(function(socket) { + socket.pipe(socket); +}).listen(common.PORT, function() { + var conn = net.connect(common.PORT); + conn.setEncoding('utf8'); + conn.write('before'); + conn.on('connect', function() { + conn.write('after'); + }); + conn.on('data', function(buf) { + received += buf; + conn.end(); + }); + conn.on('end', function() { + server.close(); + }); +}); + +process.on('exit', function() { + assert.equal(received, 'before' + 'after'); +}); diff --git a/node-v0.8.14/test/simple/test-net-write-slow.js b/node-v0.8.14/test/simple/test-net-write-slow.js new file mode 100644 index 0000000..468c311 --- /dev/null +++ b/node-v0.8.14/test/simple/test-net-write-slow.js @@ -0,0 +1,67 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var net = require('net'); + +var SIZE = 2E5; +var N = 10; +var flushed = 0; +var received = 0; +var buf = new Buffer(SIZE); +buf.fill(0x61); // 'a' + +var server = net.createServer(function(socket) { + socket.setNoDelay(); + socket.setTimeout(1000); + socket.on('timeout', function() { + assert.fail('flushed: ' + flushed + + ', received: ' + received + '/' + SIZE * N); + }); + + for (var i = 0; i < N; ++i) { + socket.write(buf, function() { + ++flushed; + if (flushed === N) { + socket.setTimeout(0); + } + }); + } + socket.end(); + +}).listen(common.PORT, function() { + var conn = net.connect(common.PORT); + conn.on('data', function(buf) { + received += buf.length; + conn.pause(); + setTimeout(function() { + conn.resume(); + }, 20); + }); + conn.on('end', function() { + server.close(); + }); +}); + +process.on('exit', function() { + assert.equal(received, SIZE * N); +}); diff --git a/node-v0.8.14/test/simple/test-next-tick-doesnt-hang.js b/node-v0.8.14/test/simple/test-next-tick-doesnt-hang.js new file mode 100644 index 0000000..3d26bd3 --- /dev/null +++ b/node-v0.8.14/test/simple/test-next-tick-doesnt-hang.js @@ -0,0 +1,30 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + +/* + * This test verifies that having a single nextTick statement and nothing else + * does not hang the event loop. If this test times out it has failed. + */ + +process.nextTick(function() { + // Nothing +}); diff --git a/node-v0.8.14/test/simple/test-next-tick-errors.js b/node-v0.8.14/test/simple/test-next-tick-errors.js new file mode 100644 index 0000000..bf3c2e3 --- /dev/null +++ b/node-v0.8.14/test/simple/test-next-tick-errors.js @@ -0,0 +1,57 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); + +var order = [], + exceptionHandled = false; + +// This nextTick function will throw an error. It should only be called once. +// When it throws an error, it should still get removed from the queue. +process.nextTick(function() { + order.push('A'); + // cause an error + what(); +}); + +// This nextTick function should remain in the queue when the first one +// is removed. It should be called if the error in the first one is +// caught (which we do in this test). +process.nextTick(function() { + order.push('C'); +}); + +process.on('uncaughtException', function() { + if (!exceptionHandled) { + exceptionHandled = true; + order.push('B'); + } + else { + // If we get here then the first process.nextTick got called twice + order.push('OOPS!'); + } +}); + +process.on('exit', function() { + assert.deepEqual(['A', 'B', 'C'], order); +}); + diff --git a/node-v0.8.14/test/simple/test-next-tick-ordering.js b/node-v0.8.14/test/simple/test-next-tick-ordering.js new file mode 100644 index 0000000..5dc1dfb --- /dev/null +++ b/node-v0.8.14/test/simple/test-next-tick-ordering.js @@ -0,0 +1,55 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var i; + +var N = 30; +var done = []; + +function get_printer(timeout) { + return function() { + console.log('Running from setTimeout ' + timeout); + done.push(timeout); + }; +} + +process.nextTick(function() { + console.log('Running from nextTick'); + done.push('nextTick'); +}); + +for (i = 0; i < N; i += 1) { + setTimeout(get_printer(i), i); +} + +console.log('Running from main.'); + + +process.on('exit', function() { + assert.equal('nextTick', done[0]); + /* Disabling this test. I don't think we can ensure the order + for (i = 0; i < N; i += 1) { + assert.equal(i, done[i + 1]); + } + */ +}); diff --git a/node-v0.8.14/test/simple/test-next-tick-ordering2.js b/node-v0.8.14/test/simple/test-next-tick-ordering2.js new file mode 100644 index 0000000..94fd20f --- /dev/null +++ b/node-v0.8.14/test/simple/test-next-tick-ordering2.js @@ -0,0 +1,38 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); + +var order = []; +process.nextTick(function() { + setTimeout(function() { + order.push('setTimeout'); + }, 0); + + process.nextTick(function() { + order.push('nextTick'); + }); +}); + +process.on('exit', function() { + assert.deepEqual(order, ['nextTick', 'setTimeout']); +}); diff --git a/node-v0.8.14/test/simple/test-next-tick-starvation.js b/node-v0.8.14/test/simple/test-next-tick-starvation.js new file mode 100644 index 0000000..bf678a0 --- /dev/null +++ b/node-v0.8.14/test/simple/test-next-tick-starvation.js @@ -0,0 +1,52 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); + + +var ran = false; +var stop = false; +var start = +new Date(); + +function spin() { + var now = +new Date(); + if (now - start > 100) { + throw new Error('The timer is starving'); + } + + if (!stop) { + ran = true; + process.nextTick(spin); + } +} + +function onTimeout() { + stop = true; +} + +spin(); +setTimeout(onTimeout, 50); + +process.on('exit', function() { + assert.ok(ran); + assert.ok(stop); +}); diff --git a/node-v0.8.14/test/simple/test-next-tick.js b/node-v0.8.14/test/simple/test-next-tick.js new file mode 100644 index 0000000..894729c --- /dev/null +++ b/node-v0.8.14/test/simple/test-next-tick.js @@ -0,0 +1,50 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); + +var complete = 0; + +process.nextTick(function() { + complete++; + process.nextTick(function() { + complete++; + process.nextTick(function() { + complete++; + }); + }); +}); + +setTimeout(function() { + process.nextTick(function() { + complete++; + }); +}, 50); + +process.nextTick(function() { + complete++; +}); + + +process.on('exit', function() { + assert.equal(5, complete); +}); diff --git a/node-v0.8.14/test/simple/test-os.js b/node-v0.8.14/test/simple/test-os.js new file mode 100644 index 0000000..b141f00 --- /dev/null +++ b/node-v0.8.14/test/simple/test-os.js @@ -0,0 +1,96 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + + + +var common = require('../common'); +var assert = require('assert'); +var os = require('os'); + + +process.env.TMPDIR = '/tmpdir'; +process.env.TMP = '/tmp'; +process.env.TEMP = '/temp'; +var t = ( process.platform === 'win32' ? 'c:\\windows\\temp' : '/tmp' ); +assert.equal(os.tmpDir(), '/tmpdir'); +process.env.TMPDIR = ''; +assert.equal(os.tmpDir(), '/tmp'); +process.env.TMP = ''; +assert.equal(os.tmpDir(), '/temp'); +process.env.TEMP = ''; +assert.equal(os.tmpDir(), t); + +var hostname = os.hostname(); +console.log('hostname = %s', hostname); +assert.ok(hostname.length > 0); + +var uptime = os.uptime(); +console.log('uptime = %d', uptime); +assert.ok(uptime > 0); + +var cpus = os.cpus(); +console.log('cpus = ', cpus); +assert.ok(cpus.length > 0); + +var type = os.type(); +console.log('type = ', type); +assert.ok(type.length > 0); + +var release = os.release(); +console.log('release = ', release); +assert.ok(release.length > 0); + +var platform = os.platform(); +console.log('platform = ', platform); +assert.ok(platform.length > 0); + +var arch = os.arch(); +console.log('arch = ', arch); +assert.ok(arch.length > 0); + +if (process.platform != 'sunos') { + // not implemeneted yet + assert.ok(os.loadavg().length > 0); + assert.ok(os.freemem() > 0); + assert.ok(os.totalmem() > 0); +} + + +var interfaces = os.networkInterfaces(); +console.error(interfaces); +switch (platform) { + case 'linux': + var filter = function(e) { return e.address == '127.0.0.1'; }; + var actual = interfaces.lo.filter(filter); + var expected = [{ address: '127.0.0.1', family: 'IPv4', internal: true }]; + assert.deepEqual(actual, expected); + break; + case 'win32': + var filter = function(e) { return e.address == '127.0.0.1'; }; + var actual = interfaces['Loopback Pseudo-Interface 1'].filter(filter); + var expected = [{ address: '127.0.0.1', family: 'IPv4', internal: true }]; + assert.deepEqual(actual, expected); + break; +} + +var EOL = os.EOL; +assert.ok(EOL.length > 0); diff --git a/node-v0.8.14/test/simple/test-path-makelong.js b/node-v0.8.14/test/simple/test-path-makelong.js new file mode 100644 index 0000000..0ec298f --- /dev/null +++ b/node-v0.8.14/test/simple/test-path-makelong.js @@ -0,0 +1,38 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +if (process.platform === 'win32') { + var assert = require('assert'); + var path = require('path'); + var common = require('../common'); + + var file = path.join(common.fixturesDir, 'a.js'); + var resolvedFile = path.resolve(file); + + assert.equal('\\\\?\\' + resolvedFile, path._makeLong(file)); + assert.equal('\\\\?\\' + resolvedFile, path._makeLong('\\\\?\\' + file)); + assert.equal('\\\\?\\UNC\\someserver\\someshare\\somefile', + path._makeLong('\\\\someserver\\someshare\\somefile')); + assert.equal('\\\\?\\UNC\\someserver\\someshare\\somefile', + path._makeLong('\\\\?\\UNC\\someserver\\someshare\\somefile')); + assert.equal('\\\\.\\pipe\\somepipe', + path._makeLong('\\\\.\\pipe\\somepipe')); +} diff --git a/node-v0.8.14/test/simple/test-path.js b/node-v0.8.14/test/simple/test-path.js new file mode 100644 index 0000000..38a8dab --- /dev/null +++ b/node-v0.8.14/test/simple/test-path.js @@ -0,0 +1,285 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); + +var path = require('path'); + +var isWindows = process.platform === 'win32'; + +var f = __filename; + +assert.equal(path.basename(f), 'test-path.js'); +assert.equal(path.basename(f, '.js'), 'test-path'); + +// POSIX filenames may include control characters +// c.f. http://www.dwheeler.com/essays/fixing-unix-linux-filenames.html +if (!isWindows) { + var controlCharFilename = 'Icon' + String.fromCharCode(13); + assert.equal(path.basename('/a/b/' + controlCharFilename), + controlCharFilename); +} + +assert.equal(path.extname(f), '.js'); + +assert.equal(path.dirname(f).substr(-11), + isWindows ? 'test\\simple' : 'test/simple'); +assert.equal(path.dirname('/a/b/'), '/a'); +assert.equal(path.dirname('/a/b'), '/a'); +assert.equal(path.dirname('/a'), '/'); +assert.equal(path.dirname('/'), '/'); + +if (isWindows) { + assert.equal(path.dirname('c:\\'), 'c:\\'); + assert.equal(path.dirname('c:\\foo'), 'c:\\'); + assert.equal(path.dirname('c:\\foo\\'), 'c:\\'); + assert.equal(path.dirname('c:\\foo\\bar'), 'c:\\foo'); + assert.equal(path.dirname('c:\\foo\\bar\\'), 'c:\\foo'); + assert.equal(path.dirname('c:\\foo\\bar\\baz'), 'c:\\foo\\bar'); + assert.equal(path.dirname('\\'), '\\'); + assert.equal(path.dirname('\\foo'), '\\'); + assert.equal(path.dirname('\\foo\\'), '\\'); + assert.equal(path.dirname('\\foo\\bar'), '\\foo'); + assert.equal(path.dirname('\\foo\\bar\\'), '\\foo'); + assert.equal(path.dirname('\\foo\\bar\\baz'), '\\foo\\bar'); + assert.equal(path.dirname('c:'), 'c:'); + assert.equal(path.dirname('c:foo'), 'c:'); + assert.equal(path.dirname('c:foo\\'), 'c:'); + assert.equal(path.dirname('c:foo\\bar'), 'c:foo'); + assert.equal(path.dirname('c:foo\\bar\\'), 'c:foo'); + assert.equal(path.dirname('c:foo\\bar\\baz'), 'c:foo\\bar'); + assert.equal(path.dirname('\\\\unc\\share'), '\\\\unc\\share'); + assert.equal(path.dirname('\\\\unc\\share\\foo'), '\\\\unc\\share\\'); + assert.equal(path.dirname('\\\\unc\\share\\foo\\'), '\\\\unc\\share\\'); + assert.equal(path.dirname('\\\\unc\\share\\foo\\bar'), + '\\\\unc\\share\\foo'); + assert.equal(path.dirname('\\\\unc\\share\\foo\\bar\\'), + '\\\\unc\\share\\foo'); + assert.equal(path.dirname('\\\\unc\\share\\foo\\bar\\baz'), + '\\\\unc\\share\\foo\\bar'); +} + + +assert.equal(path.extname(''), ''); +assert.equal(path.extname('/path/to/file'), ''); +assert.equal(path.extname('/path/to/file.ext'), '.ext'); +assert.equal(path.extname('/path.to/file.ext'), '.ext'); +assert.equal(path.extname('/path.to/file'), ''); +assert.equal(path.extname('/path.to/.file'), ''); +assert.equal(path.extname('/path.to/.file.ext'), '.ext'); +assert.equal(path.extname('/path/to/f.ext'), '.ext'); +assert.equal(path.extname('/path/to/..ext'), '.ext'); +assert.equal(path.extname('file'), ''); +assert.equal(path.extname('file.ext'), '.ext'); +assert.equal(path.extname('.file'), ''); +assert.equal(path.extname('.file.ext'), '.ext'); +assert.equal(path.extname('/file'), ''); +assert.equal(path.extname('/file.ext'), '.ext'); +assert.equal(path.extname('/.file'), ''); +assert.equal(path.extname('/.file.ext'), '.ext'); +assert.equal(path.extname('.path/file.ext'), '.ext'); +assert.equal(path.extname('file.ext.ext'), '.ext'); +assert.equal(path.extname('file.'), '.'); +assert.equal(path.extname('.'), ''); +assert.equal(path.extname('./'), ''); +assert.equal(path.extname('.file.ext'), '.ext'); +assert.equal(path.extname('.file'), ''); +assert.equal(path.extname('.file.'), '.'); +assert.equal(path.extname('.file..'), '.'); +assert.equal(path.extname('..'), ''); +assert.equal(path.extname('../'), ''); +assert.equal(path.extname('..file.ext'), '.ext'); +assert.equal(path.extname('..file'), '.file'); +assert.equal(path.extname('..file.'), '.'); +assert.equal(path.extname('..file..'), '.'); +assert.equal(path.extname('...'), '.'); +assert.equal(path.extname('...ext'), '.ext'); +assert.equal(path.extname('....'), '.'); +assert.equal(path.extname('file.ext/'), ''); + +if (isWindows) { + // On windows, backspace is a path separator. + assert.equal(path.extname('.\\'), ''); + assert.equal(path.extname('..\\'), ''); + assert.equal(path.extname('file.ext\\'), ''); +} else { + // On unix, backspace is a valid name component like any other character. + assert.equal(path.extname('.\\'), ''); + assert.equal(path.extname('..\\'), '.\\'); + assert.equal(path.extname('file.ext\\'), '.ext\\'); +} + +// path.join tests +var failures = []; +var joinTests = + // arguments result + [[['.', 'x/b', '..', '/b/c.js'], 'x/b/c.js'], + [['/.', 'x/b', '..', '/b/c.js'], '/x/b/c.js'], + [['/foo', '../../../bar'], '/bar'], + [['foo', '../../../bar'], '../../bar'], + [['foo/', '../../../bar'], '../../bar'], + [['foo/x', '../../../bar'], '../bar'], + [['foo/x', './bar'], 'foo/x/bar'], + [['foo/x/', './bar'], 'foo/x/bar'], + [['foo/x/', '.', 'bar'], 'foo/x/bar'], + [['./'], './'], + [['.', './'], './'], + [['.', '.', '.'], '.'], + [['.', './', '.'], '.'], + [['.', '/./', '.'], '.'], + [['.', '/////./', '.'], '.'], + [['.'], '.'], + [['', '.'], '.'], + [['', 'foo'], 'foo'], + [['foo', '/bar'], 'foo/bar'], + [['', '/foo'], '/foo'], + [['', '', '/foo'], '/foo'], + [['', '', 'foo'], 'foo'], + [['foo', ''], 'foo'], + [['foo/', ''], 'foo/'], + [['foo', '', '/bar'], 'foo/bar'], + [['./', '..', '/foo'], '../foo'], + [['./', '..', '..', '/foo'], '../../foo'], + [['.', '..', '..', '/foo'], '../../foo'], + [['', '..', '..', '/foo'], '../../foo'], + [['/'], '/'], + [['/', '.'], '/'], + [['/', '..'], '/'], + [['/', '..', '..'], '/'], + [[''], '.'], + [['', ''], '.'], + [[' /foo'], ' /foo'], + [[' ', 'foo'], ' /foo'], + [[' ', '.'], ' '], + [[' ', '/'], ' /'], + [[' ', ''], ' '], + // filtration of non-strings. + [['x', true, 7, 'y', null, {}], 'x/y'] + ]; +joinTests.forEach(function(test) { + var actual = path.join.apply(path, test[0]); + var expected = isWindows ? test[1].replace(/\//g, '\\') : test[1]; + var message = 'path.join(' + test[0].map(JSON.stringify).join(',') + ')' + + '\n expect=' + JSON.stringify(expected) + + '\n actual=' + JSON.stringify(actual); + if (actual !== expected) failures.push('\n' + message); + // assert.equal(actual, expected, message); +}); +assert.equal(failures.length, 0, failures.join('')); + +// path normalize tests +if (isWindows) { + assert.equal(path.normalize('./fixtures///b/../b/c.js'), + 'fixtures\\b\\c.js'); + assert.equal(path.normalize('/foo/../../../bar'), '\\bar'); + assert.equal(path.normalize('a//b//../b'), 'a\\b'); + assert.equal(path.normalize('a//b//./c'), 'a\\b\\c'); + assert.equal(path.normalize('a//b//.'), 'a\\b'); + assert.equal(path.normalize('//server/share/dir/file.ext'), + '\\\\server\\share\\dir\\file.ext'); +} else { + assert.equal(path.normalize('./fixtures///b/../b/c.js'), + 'fixtures/b/c.js'); + assert.equal(path.normalize('/foo/../../../bar'), '/bar'); + assert.equal(path.normalize('a//b//../b'), 'a/b'); + assert.equal(path.normalize('a//b//./c'), 'a/b/c'); + assert.equal(path.normalize('a//b//.'), 'a/b'); +} + +// path.resolve tests +if (isWindows) { + // windows + var resolveTests = + // arguments result + [[['c:/blah\\blah', 'd:/games', 'c:../a'], 'c:\\blah\\a'], + [['c:/ignore', 'd:\\a/b\\c/d', '\\e.exe'], 'd:\\e.exe'], + [['c:/ignore', 'c:/some/file'], 'c:\\some\\file'], + [['d:/ignore', 'd:some/dir//'], 'd:\\ignore\\some\\dir'], + [['.'], process.cwd()], + [['//server/share', '..', 'relative\\'], '\\\\server\\share\\relative']]; +} else { + // Posix + var resolveTests = + // arguments result + [[['/var/lib', '../', 'file/'], '/var/file'], + [['/var/lib', '/../', 'file/'], '/file'], + [['a/b/c/', '../../..'], process.cwd()], + [['.'], process.cwd()], + [['/some/dir', '.', '/absolute/'], '/absolute']]; +} +var failures = []; +resolveTests.forEach(function(test) { + var actual = path.resolve.apply(path, test[0]); + var expected = test[1]; + var message = 'path.resolve(' + test[0].map(JSON.stringify).join(',') + ')' + + '\n expect=' + JSON.stringify(expected) + + '\n actual=' + JSON.stringify(actual); + if (actual !== expected) failures.push('\n' + message); + // assert.equal(actual, expected, message); +}); +assert.equal(failures.length, 0, failures.join('')); + +// path.relative tests +if (isWindows) { + // windows + var relativeTests = + // arguments result + [['c:/blah\\blah', 'd:/games', 'd:\\games'], + ['c:/aaaa/bbbb', 'c:/aaaa', '..'], + ['c:/aaaa/bbbb', 'c:/cccc', '..\\..\\cccc'], + ['c:/aaaa/bbbb', 'c:/aaaa/bbbb', ''], + ['c:/aaaa/bbbb', 'c:/aaaa/cccc', '..\\cccc'], + ['c:/aaaa/', 'c:/aaaa/cccc', 'cccc'], + ['c:/', 'c:\\aaaa\\bbbb', 'aaaa\\bbbb'], + ['c:/aaaa/bbbb', 'd:\\', 'd:\\']]; +} else { + // posix + var relativeTests = + // arguments result + [['/var/lib', '/var', '..'], + ['/var/lib', '/bin', '../../bin'], + ['/var/lib', '/var/lib', ''], + ['/var/lib', '/var/apache', '../apache'], + ['/var/', '/var/lib', 'lib'], + ['/', '/var/lib', 'var/lib']]; +} +var failures = []; +relativeTests.forEach(function(test) { + var actual = path.relative(test[0], test[1]); + var expected = test[2]; + var message = 'path.relative(' + + test.slice(0, 2).map(JSON.stringify).join(',') + + ')' + + '\n expect=' + JSON.stringify(expected) + + '\n actual=' + JSON.stringify(actual); + if (actual !== expected) failures.push('\n' + message); +}); +assert.equal(failures.length, 0, failures.join('')); + +// path.sep tests +if (isWindows) { + // windows + assert.equal(path.sep, '\\'); +} else { + // posix + assert.equal(path.sep, '/'); +} diff --git a/node-v0.8.14/test/simple/test-pipe-address.js b/node-v0.8.14/test/simple/test-pipe-address.js new file mode 100644 index 0000000..6b29d2a --- /dev/null +++ b/node-v0.8.14/test/simple/test-pipe-address.js @@ -0,0 +1,39 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var net = require('net'); + +var address = null; + +var server = net.createServer(function() { + assert(false); // should not be called +}); + +server.listen(common.PIPE, function() { + address = server.address(); + server.close(); +}); + +process.on('exit', function() { + assert.equal(address, common.PIPE); +}); diff --git a/node-v0.8.14/test/simple/test-pipe-file-to-http.js b/node-v0.8.14/test/simple/test-pipe-file-to-http.js new file mode 100644 index 0000000..99fad6e --- /dev/null +++ b/node-v0.8.14/test/simple/test-pipe-file-to-http.js @@ -0,0 +1,96 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var fs = require('fs'); +var http = require('http'); +var path = require('path'); +var cp = require('child_process'); + +var filename = path.join(common.tmpDir || '/tmp', 'big'); +var clientReqComplete = false; +var count = 0; + +var server = http.createServer(function(req, res) { + var timeoutId; + assert.equal('POST', req.method); + req.pause(); + common.error('request paused'); + + setTimeout(function() { + req.resume(); + common.error('request resumed'); + }, 1000); + + req.on('data', function(chunk) { + common.error('recv data! nchars = ' + chunk.length); + count += chunk.length; + }); + + req.on('end', function() { + if (timeoutId) { + clearTimeout(timeoutId); + } + console.log('request complete from server'); + res.writeHead(200, {'Content-Type': 'text/plain'}); + res.end(); + }); +}); +server.listen(common.PORT); + +server.on('listening', function() { + var cmd = common.ddCommand(filename, 10240); + console.log('dd command: ', cmd); + + cp.exec(cmd, function(err, stdout, stderr) { + if (err) throw err; + makeRequest(); + }); +}); + +function makeRequest() { + var req = http.request({ + port: common.PORT, + path: '/', + method: 'POST' + }); + + common.error('pipe!'); + var s = fs.ReadStream(filename); + s.pipe(req); + s.on('close', function(err) { + if (err) throw err; + clientReqComplete = true; + common.error('client finished sending request'); + }); + + req.on('response', function(res) { + res.on('end', function() { + server.close(); + }); + }); +} + +process.on('exit', function() { + assert.equal(1024 * 10240, count); + assert.ok(clientReqComplete); +}); diff --git a/node-v0.8.14/test/simple/test-pipe-head.js b/node-v0.8.14/test/simple/test-pipe-head.js new file mode 100644 index 0000000..a049be6 --- /dev/null +++ b/node-v0.8.14/test/simple/test-pipe-head.js @@ -0,0 +1,48 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + + + +var common = require('../common'); +var assert = require('assert'); + +var exec = require('child_process').exec; +var join = require('path').join; + +var nodePath = process.argv[0]; +var script = join(common.fixturesDir, 'print-10-lines.js'); + +var cmd = '"' + nodePath + '" "' + script + '" | head -2'; + +var finished = false; + +exec(cmd, function(err, stdout, stderr) { + if (err) throw err; + var lines = stdout.split('\n'); + assert.equal(3, lines.length); + finished = true; +}); + + +process.on('exit', function() { + assert.ok(finished); +}); diff --git a/node-v0.8.14/test/simple/test-pipe-return-val.js b/node-v0.8.14/test/simple/test-pipe-return-val.js new file mode 100644 index 0000000..274e9f5 --- /dev/null +++ b/node-v0.8.14/test/simple/test-pipe-return-val.js @@ -0,0 +1,37 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + + + +// This test ensures SourceStream.pipe(DestStream) returns DestStream + +var common = require('../common'); +var Stream = require('stream').Stream; +var assert = require('assert'); +var util = require('util'); + +var sourceStream = new Stream(); +var destStream = new Stream(); +var result = sourceStream.pipe(destStream); + +assert.strictEqual(result, destStream); + diff --git a/node-v0.8.14/test/simple/test-pipe-stream.js b/node-v0.8.14/test/simple/test-pipe-stream.js new file mode 100644 index 0000000..b2b2a55 --- /dev/null +++ b/node-v0.8.14/test/simple/test-pipe-stream.js @@ -0,0 +1,86 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var net = require('net'); + +function test(clazz, cb) { + var have_ping = false; + var have_pong = false; + + function check() { + assert.ok(have_ping); + assert.ok(have_pong); + } + + function ping() { + var conn = new clazz(); + + conn.on('error', function(err) { + throw err; + }); + + conn.connect(common.PIPE, function() { + conn.write('PING', 'utf-8'); + }); + + conn.on('data', function(data) { + assert.equal(data.toString(), 'PONG'); + have_pong = true; + conn.destroy(); + }); + } + + function pong(conn) { + conn.on('error', function(err) { + throw err; + }); + + conn.on('data', function(data) { + assert.equal(data.toString(), 'PING'); + have_ping = true; + conn.write('PONG', 'utf-8'); + }); + + conn.on('close', function() { + server.close(); + }); + } + + var timeout = setTimeout(function() { + server.close(); + }, 2000); + + var server = net.Server(); + server.listen(common.PIPE, ping); + server.on('connection', pong); + server.on('close', function() { + clearTimeout(timeout); + check(); + cb && cb(); + }); +} + +test(net.Stream, function() { + test(net.Socket); +}); + diff --git a/node-v0.8.14/test/simple/test-pipe.js b/node-v0.8.14/test/simple/test-pipe.js new file mode 100644 index 0000000..3dd2437 --- /dev/null +++ b/node-v0.8.14/test/simple/test-pipe.js @@ -0,0 +1,134 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + + + +var common = require('../common'); +var assert = require('assert'); +var http = require('http'); +var net = require('net'); + +var webPort = common.PORT; +var tcpPort = webPort + 1; + +var listenCount = 0; +var gotThanks = false; +var tcpLengthSeen = 0; +var bufferSize = 5 * 1024 * 1024; + + +/* + * 5MB of random buffer. + */ +var buffer = Buffer(bufferSize); +for (var i = 0; i < buffer.length; i++) { + buffer[i] = parseInt(Math.random() * 10000) % 256; +} + + +var web = http.Server(function(req, res) { + web.close(); + + console.log(req.headers); + + var socket = net.Stream(); + socket.connect(tcpPort); + + socket.on('connect', function() { + console.log('socket connected'); + }); + + req.pipe(socket); + + req.on('end', function() { + res.writeHead(200); + res.write('thanks'); + res.end(); + console.log('response with \'thanks\''); + }); + + req.connection.on('error', function(e) { + console.log('http server-side error: ' + e.message); + process.exit(1); + }); +}); +web.listen(webPort, startClient); + + + +var tcp = net.Server(function(s) { + tcp.close(); + + console.log('tcp server connection'); + + var i = 0; + + s.on('data', function(d) { + process.stdout.write('.'); + tcpLengthSeen += d.length; + for (var j = 0; j < d.length; j++) { + assert.equal(buffer[i], d[j]); + i++; + } + }); + + s.on('end', function() { + console.log('tcp socket disconnect'); + s.end(); + }); + + s.on('error', function(e) { + console.log('tcp server-side error: ' + e.message); + process.exit(1); + }); +}); +tcp.listen(tcpPort, startClient); + + +function startClient() { + listenCount++; + if (listenCount < 2) return; + + console.log('Making request'); + + var req = http.request({ + port: common.PORT, + method: 'GET', + path: '/', + headers: { 'content-length': buffer.length } + }, function(res) { + console.log('Got response'); + res.setEncoding('utf8'); + res.on('data', function(string) { + assert.equal('thanks', string); + gotThanks = true; + }); + }); + req.write(buffer); + req.end(); +} + +process.on('exit', function() { + assert.ok(gotThanks); + assert.equal(bufferSize, tcpLengthSeen); +}); + diff --git a/node-v0.8.14/test/simple/test-process-active-wraps.js b/node-v0.8.14/test/simple/test-process-active-wraps.js new file mode 100644 index 0000000..3fdf993 --- /dev/null +++ b/node-v0.8.14/test/simple/test-process-active-wraps.js @@ -0,0 +1,56 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var spawn = require('child_process').spawn; +var net = require('net'); + +function expect(activeHandles, activeRequests) { + assert.equal(process._getActiveHandles().length, activeHandles); + assert.equal(process._getActiveRequests().length, activeRequests); +} + +(function() { + expect(0, 0); + var server = net.createServer().listen(common.PORT); + expect(1, 0); + server.close(); + expect(1, 0); // server handle doesn't shut down until next tick +})(); + +(function() { + expect(1, 0); + var conn = net.createConnection(common.PORT); + conn.on('error', function() { /* ignore */ }); + expect(2, 1); + conn.destroy(); + expect(2, 1); // client handle doesn't shut down until next tick +})(); + +process.nextTick(function() { + process.nextTick(function() { + process.nextTick(function() { + // the handles should be gone but the connect req could still be alive + assert.equal(process._getActiveHandles().length, 0); + }); + }); +}); diff --git a/node-v0.8.14/test/simple/test-process-argv-0.js b/node-v0.8.14/test/simple/test-process-argv-0.js new file mode 100644 index 0000000..0c38f6a --- /dev/null +++ b/node-v0.8.14/test/simple/test-process-argv-0.js @@ -0,0 +1,55 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. +var util = require('util'); +var path = require('path'); +var assert = require('assert'); +var spawn = require('child_process').spawn; +var common = require('../common'); + +console.error('argv=%j', process.argv); +console.error('exec=%j', process.execPath); + +if (process.argv[2] !== "child") { + var child = spawn('./node', [__filename, "child"], { + cwd: path.dirname(process.execPath) + }); + + var childArgv0 = ''; + var childErr = ''; + child.stdout.on('data', function(chunk) { + childArgv0 += chunk; + }); + child.stderr.on('data', function(chunk) { + childErr += chunk; + }); + child.on('exit', function () { + console.error('CHILD: %s', childErr.trim().split('\n').join('\nCHILD: ')); + if (process.platform === 'win32') { + // On Windows argv[0] is not expanded into full path + assert.equal(childArgv0, './node'); + } else { + assert.equal(childArgv0, process.execPath); + } + }); +} +else { + process.stdout.write(process.argv[0]); +} diff --git a/node-v0.8.14/test/simple/test-process-config.js b/node-v0.8.14/test/simple/test-process-config.js new file mode 100644 index 0000000..b3236cd --- /dev/null +++ b/node-v0.8.14/test/simple/test-process-config.js @@ -0,0 +1,44 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var fs = require('fs'); +var path = require('path'); + +// check for existence +assert(process.hasOwnProperty('config')); + +// ensure that `process.config` is an Object +assert(Object(process.config) === process.config); + +var configPath = path.resolve(__dirname, '..', '..', 'config.gypi'); +var config = fs.readFileSync(configPath, 'utf8'); + +// clean up comment at the first line +config = config.split('\n').slice(1).join('\n').replace(/'/g, '"'); +config = JSON.parse(config, function(key, value) { + if (value === 'true') return true; + if (value === 'false') return false; + return value; +}); + +assert.deepEqual(config, process.config); diff --git a/node-v0.8.14/test/simple/test-process-env.js b/node-v0.8.14/test/simple/test-process-env.js new file mode 100644 index 0000000..fdf35ba --- /dev/null +++ b/node-v0.8.14/test/simple/test-process-env.js @@ -0,0 +1,69 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// first things first, set the timezone; see tzset(3) +process.env.TZ = 'Europe/Amsterdam'; + +var common = require('../common'); +var assert = require('assert'); +var spawn = require('child_process').spawn; + +/* For the moment we are not going to support setting the timezone via the + * environment variables. The problem is that various V8 platform backends + * deal with timezone in different ways. The windows platform backend caches + * the timezone value while the Linux one hits libc for every query. + +https://github.com/joyent/node/blob/08782931205bc4f6d28102ebc29fd806e8ccdf1f/deps/v8/src/platform-linux.cc#L339-345 +https://github.com/joyent/node/blob/08782931205bc4f6d28102ebc29fd806e8ccdf1f/deps/v8/src/platform-win32.cc#L590-596 + + +// time difference between Greenwich and Amsterdam is +2 hours in the summer +date = new Date('Fri, 10 Sep 1982 03:15:00 GMT'); +assert.equal(3, date.getUTCHours()); +assert.equal(5, date.getHours()); +*/ + + +// changes in environment should be visible to child processes +if (process.argv[2] == 'you-are-the-child') { + // failed assertion results in process exiting with status code 1 + assert.equal(false, 'NODE_PROCESS_ENV_DELETED' in process.env); + assert.equal(42, process.env.NODE_PROCESS_ENV); + process.exit(0); +} else { + process.env.NODE_PROCESS_ENV = 42; + assert.equal(42, process.env.NODE_PROCESS_ENV); + + process.env.NODE_PROCESS_ENV_DELETED = 42; + assert.equal(true, 'NODE_PROCESS_ENV_DELETED' in process.env); + + delete process.env.NODE_PROCESS_ENV_DELETED; + assert.equal(false, 'NODE_PROCESS_ENV_DELETED' in process.env); + + var child = spawn(process.argv[0], [process.argv[1], 'you-are-the-child']); + child.stdout.on('data', function(data) { console.log(data.toString()); }); + child.stderr.on('data', function(data) { console.log(data.toString()); }); + child.on('exit', function(statusCode) { + if (statusCode != 0) { + process.exit(statusCode); // failed assertion in child process + } + }); +} diff --git a/node-v0.8.14/test/simple/test-process-exec-argv.js b/node-v0.8.14/test/simple/test-process-exec-argv.js new file mode 100644 index 0000000..96ed817 --- /dev/null +++ b/node-v0.8.14/test/simple/test-process-exec-argv.js @@ -0,0 +1,40 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var assert = require('assert'); +var spawn = require('child_process').spawn; + +if (process.argv[2] === 'child') { + process.stdout.write(JSON.stringify(process.execArgv)); +} else { + var execArgv = ['--harmony_proxies', '--max-stack-size=0']; + var args = [__filename, 'child', 'arg0']; + var child = spawn(process.execPath, execArgv.concat(args)); + var out = ''; + + child.stdout.on('data', function (chunk) { + out += chunk; + }); + + child.on('exit', function () { + assert.deepEqual(JSON.parse(out), execArgv); + }); +} diff --git a/node-v0.8.14/test/simple/test-process-exit-recursive.js b/node-v0.8.14/test/simple/test-process-exit-recursive.js new file mode 100644 index 0000000..556ab13 --- /dev/null +++ b/node-v0.8.14/test/simple/test-process-exit-recursive.js @@ -0,0 +1,35 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var assert = require('assert'); + +// recursively calling .exit() should not overflow the call stack +var nexits = 0; + +process.on('exit', function(code) { + assert.equal(nexits++, 0); + assert.equal(code, 1); + + // now override the exit code of 1 with 0 so that the test passes + process.exit(); +}); + +process.exit(1); diff --git a/node-v0.8.14/test/simple/test-process-exit.js b/node-v0.8.14/test/simple/test-process-exit.js new file mode 100644 index 0000000..365d5f1 --- /dev/null +++ b/node-v0.8.14/test/simple/test-process-exit.js @@ -0,0 +1,34 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); + +// calling .exit() from within "exit" should not overflow the call stack +var nexits = 0; + +process.on('exit', function(code) { + assert.equal(nexits++, 0); + assert.equal(code, 0); + process.exit(); +}); + +// "exit" should be emitted unprovoked diff --git a/node-v0.8.14/test/simple/test-process-hrtime.js b/node-v0.8.14/test/simple/test-process-hrtime.js new file mode 100644 index 0000000..d8ffcaf --- /dev/null +++ b/node-v0.8.14/test/simple/test-process-hrtime.js @@ -0,0 +1,46 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); + +// the default behavior, return an Array "tuple" of numbers +var tuple = process.hrtime(); + +// validate the default behavior +validateTuple(tuple); + +// validate that passing an existing tuple returns another valid tuple +validateTuple(process.hrtime(tuple)); + +// test that only an Array may be passed to process.hrtime() +assert.throws(function() { + process.hrtime(1); +}); + +function validateTuple(tuple) { + assert(Array.isArray(tuple)); + assert.equal(2, tuple.length); + tuple.forEach(function (v) { + assert.equal('number', typeof v); + assert(isFinite(v)); + }); +} diff --git a/node-v0.8.14/test/simple/test-process-kill-null.js b/node-v0.8.14/test/simple/test-process-kill-null.js new file mode 100644 index 0000000..708e27d --- /dev/null +++ b/node-v0.8.14/test/simple/test-process-kill-null.js @@ -0,0 +1,42 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + +var common = require('../common'); +var assert = require('assert'); +var spawn = require('child_process').spawn; + +var cat = spawn('cat'); +var called; + +process.kill(cat.pid, 0); + +cat.stdout.on('data', function() { + called = true; + process.kill(cat.pid, 'SIGKILL'); +}); + +// EPIPE when null sig fails +cat.stdin.write('test'); + +process.on('exit', function() { + assert.ok(called); +}); diff --git a/node-v0.8.14/test/simple/test-process-next-tick.js b/node-v0.8.14/test/simple/test-process-next-tick.js new file mode 100644 index 0000000..0322a03 --- /dev/null +++ b/node-v0.8.14/test/simple/test-process-next-tick.js @@ -0,0 +1,45 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var N = 2; +var tickCount = 0; +var exceptionCount = 0; + +function cb() { + ++tickCount; + throw new Error(); +} + +for (var i = 0; i < N; ++i) { + process.nextTick(cb); +} + +process.on('uncaughtException', function() { + ++exceptionCount; +}); + +process.on('exit', function() { + process.removeAllListeners('uncaughtException'); + assert.equal(tickCount, N); + assert.equal(exceptionCount, N); +}); diff --git a/node-v0.8.14/test/simple/test-process-wrap.js b/node-v0.8.14/test/simple/test-process-wrap.js new file mode 100644 index 0000000..655c828 --- /dev/null +++ b/node-v0.8.14/test/simple/test-process-wrap.js @@ -0,0 +1,73 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + + + +var common = require('../common'); +var assert = require('assert'); +var Process = process.binding('process_wrap').Process; +var Pipe = process.binding('pipe_wrap').Pipe; +var pipe = new Pipe(); +var p = new Process(); + +var processExited = false; +var gotPipeEOF = false; +var gotPipeData = false; + +p.onexit = function(exitCode, signal) { + console.log('exit'); + p.close(); + pipe.readStart(); + + assert.equal(0, exitCode); + assert.equal(0, signal); + + processExited = true; +}; + +pipe.onread = function(b, off, len) { + assert.ok(processExited); + if (b) { + gotPipeData = true; + console.log('read %d', len); + } else { + gotPipeEOF = true; + pipe.close(); + } +}; + +p.spawn({ + file: process.execPath, + args: [process.execPath, '-v'], + stdio: [ + { type: 'ignore' }, + { type: 'pipe', handle: pipe }, + { type: 'ignore' } + ] +}); + + +process.on('exit', function() { + assert.ok(processExited); + assert.ok(gotPipeEOF); + assert.ok(gotPipeData); +}); diff --git a/node-v0.8.14/test/simple/test-pump-file2tcp-noexist.js b/node-v0.8.14/test/simple/test-pump-file2tcp-noexist.js new file mode 100644 index 0000000..8017db7 --- /dev/null +++ b/node-v0.8.14/test/simple/test-pump-file2tcp-noexist.js @@ -0,0 +1,72 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var net = require('net'); +var fs = require('fs'); +var util = require('util'); +var path = require('path'); +var fn = path.join(common.fixturesDir, 'does_not_exist.txt'); + +var got_error = false; +var conn_closed = false; + +var server = net.createServer(function(stream) { + common.error('pump!'); + util.pump(fs.createReadStream(fn), stream, function(err) { + common.error('util.pump\'s callback fired'); + if (err) { + got_error = true; + } else { + common.debug('util.pump\'s callback fired with no error'); + common.debug('this shouldn\'t happen as the file doesn\'t exist...'); + assert.equal(true, false); + } + server.close(); + }); +}); + +server.listen(common.PORT, function() { + var conn = net.createConnection(common.PORT); + conn.setEncoding('utf8'); + conn.on('data', function(chunk) { + common.error('recv data! nchars = ' + chunk.length); + buffer += chunk; + }); + + conn.on('end', function() { + conn.end(); + }); + + conn.on('close', function() { + common.error('client connection close'); + conn_closed = true; + }); +}); + +var buffer = ''; + +process.on('exit', function() { + assert.equal(true, got_error); + assert.equal(true, conn_closed); + console.log('exiting'); +}); diff --git a/node-v0.8.14/test/simple/test-pump-file2tcp.js b/node-v0.8.14/test/simple/test-pump-file2tcp.js new file mode 100644 index 0000000..60c0fdd --- /dev/null +++ b/node-v0.8.14/test/simple/test-pump-file2tcp.js @@ -0,0 +1,65 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var net = require('net'); +var fs = require('fs'); +var util = require('util'); +var path = require('path'); +var fn = path.join(common.fixturesDir, 'elipses.txt'); + +var expected = fs.readFileSync(fn, 'utf8'); + +var server = net.createServer(function(stream) { + common.error('pump!'); + util.pump(fs.createReadStream(fn), stream, function() { + common.error('server stream close'); + common.error('server close'); + server.close(); + }); +}); + +server.listen(common.PORT, function() { + var conn = net.createConnection(common.PORT); + conn.setEncoding('utf8'); + conn.on('data', function(chunk) { + common.error('recv data! nchars = ' + chunk.length); + buffer += chunk; + }); + + conn.on('end', function() { + conn.end(); + }); + conn.on('close', function() { + common.error('client connection close'); + }); +}); + +var buffer = ''; +var count = 0; + +server.on('listening', function() { +}); + +process.on('exit', function() { + assert.equal(expected, buffer); +}); diff --git a/node-v0.8.14/test/simple/test-punycode.js b/node-v0.8.14/test/simple/test-punycode.js new file mode 100644 index 0000000..f3d6dd7 --- /dev/null +++ b/node-v0.8.14/test/simple/test-punycode.js @@ -0,0 +1,182 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// Copyright (C) 2011 by Ben Noordhuis +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +var common = require('../common'); +var punycode = require('punycode'); +var assert = require('assert'); + +assert.equal(punycode.encode('ü'), 'tda'); +assert.equal(punycode.encode('Goethe'), 'Goethe-'); +assert.equal(punycode.encode('Bücher'), 'Bcher-kva'); +assert.equal(punycode.encode( + 'Willst du die Blüthe des frühen, die Früchte des späteren Jahres'), + 'Willst du die Blthe des frhen, die Frchte des spteren Jahres-x9e96lkal'); +assert.equal(punycode.encode('日本語'), 'wgv71a119e'); + +assert.equal(punycode.decode('tda'), 'ü'); +assert.equal(punycode.decode('Goethe-'), 'Goethe'); +assert.equal(punycode.decode('Bcher-kva'), 'Bücher'); +assert.equal(punycode.decode( + 'Willst du die Blthe des frhen, die Frchte des spteren Jahres-x9e96lkal'), + 'Willst du die Blüthe des frühen, die Früchte des späteren Jahres'); +assert.equal(punycode.decode('wgv71a119e'), '日本語'); + +// http://tools.ietf.org/html/rfc3492#section-7.1 +var tests = { + // (A) Arabic (Egyptian) + 'egbpdaj6bu4bxfgehfvwxn': + '\u0644\u064A\u0647\u0645\u0627\u0628\u062A\u0643\u0644\u0645\u0648' + + '\u0634\u0639\u0631\u0628\u064A\u061F', + + // (B) Chinese (simplified) + 'ihqwcrb4cv8a8dqg056pqjye': + '\u4ED6\u4EEC\u4E3A\u4EC0\u4E48\u4E0D\u8BF4\u4E2D\u6587', + + // (C) Chinese (traditional) + 'ihqwctvzc91f659drss3x8bo0yb': + '\u4ED6\u5011\u7232\u4EC0\u9EBD\u4E0D\u8AAA\u4E2D\u6587', + + // (D) Czech: Proprostnemluvesky + 'Proprostnemluvesky-uyb24dma41a': + '\u0050\u0072\u006F\u010D\u0070\u0072\u006F\u0073\u0074\u011B\u006E' + + '\u0065\u006D\u006C\u0075\u0076\u00ED\u010D\u0065\u0073\u006B\u0079', + + // (E) Hebrew + '4dbcagdahymbxekheh6e0a7fei0b': + '\u05DC\u05DE\u05D4\u05D4\u05DD\u05E4\u05E9\u05D5\u05D8\u05DC\u05D0' + + '\u05DE\u05D3\u05D1\u05E8\u05D9\u05DD\u05E2\u05D1\u05E8\u05D9\u05EA', + + // (F) Hindi (Devanagari) + 'i1baa7eci9glrd9b2ae1bj0hfcgg6iyaf8o0a1dig0cd': + '\u092F\u0939\u0932\u094B\u0917\u0939\u093F\u0928\u094D\u0926\u0940' + + '\u0915\u094D\u092F\u094B\u0902\u0928\u0939\u0940\u0902\u092C\u094B' + + '\u0932\u0938\u0915\u0924\u0947\u0939\u0948\u0902', + + // (G) Japanese (kanji and hiragana) + 'n8jok5ay5dzabd5bym9f0cm5685rrjetr6pdxa': + '\u306A\u305C\u307F\u3093\u306A\u65E5\u672C\u8A9E\u3092\u8A71\u3057' + + '\u3066\u304F\u308C\u306A\u3044\u306E\u304B', + + // (H) Korean (Hangul syllables) + '989aomsvi5e83db1d2a355cv1e0vak1dwrv93d5xbh15a0dt30a5jpsd879ccm6fea98c': + '\uC138\uACC4\uC758\uBAA8\uB4E0\uC0AC\uB78C\uB4E4\uC774\uD55C\uAD6D' + + '\uC5B4\uB97C\uC774\uD574\uD55C\uB2E4\uBA74\uC5BC\uB9C8\uB098\uC88B' + + '\uC744\uAE4C', + + // (I) Russian (Cyrillic) + /* XXX disabled, fails - possibly a bug in the RFC + 'b1abfaaepdrnnbgefbaDotcwatmq2g4l': + '\u043F\u043E\u0447\u0435\u043C\u0443\u0436\u0435\u043E\u043D\u0438' + + '\u043D\u0435\u0433\u043E\u0432\u043E\u0440\u044F\u0442\u043F\u043E' + + '\u0440\u0443\u0441\u0441\u043A\u0438', + */ + + // (J) Spanish: PorqunopuedensimplementehablarenEspaol + 'PorqunopuedensimplementehablarenEspaol-fmd56a': + '\u0050\u006F\u0072\u0071\u0075\u00E9\u006E\u006F\u0070\u0075\u0065' + + '\u0064\u0065\u006E\u0073\u0069\u006D\u0070\u006C\u0065\u006D\u0065' + + '\u006E\u0074\u0065\u0068\u0061\u0062\u006C\u0061\u0072\u0065\u006E' + + '\u0045\u0073\u0070\u0061\u00F1\u006F\u006C', + + // (K) Vietnamese: Tisaohkhngth + // chnitingVit + 'TisaohkhngthchnitingVit-kjcr8268qyxafd2f1b9g': + '\u0054\u1EA1\u0069\u0073\u0061\u006F\u0068\u1ECD\u006B\u0068\u00F4' + + '\u006E\u0067\u0074\u0068\u1EC3\u0063\u0068\u1EC9\u006E\u00F3\u0069' + + '\u0074\u0069\u1EBF\u006E\u0067\u0056\u0069\u1EC7\u0074', + + // (L) 3B + '3B-ww4c5e180e575a65lsy2b': + '\u0033\u5E74\u0042\u7D44\u91D1\u516B\u5148\u751F', + + // (M) -with-SUPER-MONKEYS + '-with-SUPER-MONKEYS-pc58ag80a8qai00g7n9n': + '\u5B89\u5BA4\u5948\u7F8E\u6075\u002D\u0077\u0069\u0074\u0068\u002D' + + '\u0053\u0055\u0050\u0045\u0052\u002D\u004D\u004F\u004E\u004B\u0045' + + '\u0059\u0053', + + // (N) Hello-Another-Way- + 'Hello-Another-Way--fc4qua05auwb3674vfr0b': + '\u0048\u0065\u006C\u006C\u006F\u002D\u0041\u006E\u006F\u0074\u0068' + + '\u0065\u0072\u002D\u0057\u0061\u0079\u002D\u305D\u308C\u305E\u308C' + + '\u306E\u5834\u6240', + + // (O) 2 + '2-u9tlzr9756bt3uc0v': + '\u3072\u3068\u3064\u5C4B\u6839\u306E\u4E0B\u0032', + + // (P) MajiKoi5 + 'MajiKoi5-783gue6qz075azm5e': + '\u004D\u0061\u006A\u0069\u3067\u004B\u006F\u0069\u3059\u308B\u0035' + + '\u79D2\u524D', + + // (Q) de + 'de-jg4avhby1noc0d': + '\u30D1\u30D5\u30A3\u30FC\u0064\u0065\u30EB\u30F3\u30D0', + + // (R) + 'd9juau41awczczp': + '\u305D\u306E\u30B9\u30D4\u30FC\u30C9\u3067', + + // (S) -> $1.00 <- + '-> $1.00 <--': + '\u002D\u003E\u0020\u0024\u0031\u002E\u0030\u0030\u0020\u003C\u002D' +}; + +var errors = 0; + +for (var encoded in tests) { + var decoded = tests[encoded]; + try { + assert.equal(punycode.encode(decoded), encoded); + } catch (e) { + console.error('FAIL: expected %j, got %j', e.expected, e.actual); + errors++; + } + try { + assert.equal(punycode.decode(encoded), decoded); + } catch (e) { + console.error('FAIL: expected %j, got %j', e.expected, e.actual); + errors++; + } +} + +assert.equal(errors, 0); diff --git a/node-v0.8.14/test/simple/test-querystring.js b/node-v0.8.14/test/simple/test-querystring.js new file mode 100644 index 0000000..2d86625 --- /dev/null +++ b/node-v0.8.14/test/simple/test-querystring.js @@ -0,0 +1,231 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); + +// test using assert +var qs = require('querystring'); + +// folding block, commented to pass gjslint +// {{{ +// [ wonkyQS, canonicalQS, obj ] +var qsTestCases = [ + ['foo=918854443121279438895193', + 'foo=918854443121279438895193', + {'foo': '918854443121279438895193'}], + ['foo=bar', 'foo=bar', {'foo': 'bar'}], + ['foo=bar&foo=quux', 'foo=bar&foo=quux', {'foo': ['bar', 'quux']}], + ['foo=1&bar=2', 'foo=1&bar=2', {'foo': '1', 'bar': '2'}], + ['my+weird+field=q1%212%22%27w%245%267%2Fz8%29%3F', + 'my%20weird%20field=q1!2%22\'w%245%267%2Fz8)%3F', + {'my weird field': 'q1!2"\'w$5&7/z8)?' }], + ['foo%3Dbaz=bar', 'foo%3Dbaz=bar', {'foo=baz': 'bar'}], + ['foo=baz=bar', 'foo=baz%3Dbar', {'foo': 'baz=bar'}], + ['str=foo&arr=1&arr=2&arr=3&somenull=&undef=', + 'str=foo&arr=1&arr=2&arr=3&somenull=&undef=', + { 'str': 'foo', + 'arr': ['1', '2', '3'], + 'somenull': '', + 'undef': ''}], + [' foo = bar ', '%20foo%20=%20bar%20', {' foo ': ' bar '}], + ['foo=%zx', 'foo=%25zx', {'foo': '%zx'}], + ['foo=%EF%BF%BD', 'foo=%EF%BF%BD', {'foo': '\ufffd' }], + // See: https://github.com/joyent/node/issues/1707 + ['hasOwnProperty=x&toString=foo&valueOf=bar&__defineGetter__=baz', + 'hasOwnProperty=x&toString=foo&valueOf=bar&__defineGetter__=baz', + { hasOwnProperty: 'x', + toString: 'foo', + valueOf: 'bar', + __defineGetter__: 'baz' }], + // See: https://github.com/joyent/node/issues/3058 + ['foo&bar=baz', 'foo=&bar=baz', { foo: '', bar: 'baz' }] +]; + +// [ wonkyQS, canonicalQS, obj ] +var qsColonTestCases = [ + ['foo:bar', 'foo:bar', {'foo': 'bar'}], + ['foo:bar;foo:quux', 'foo:bar;foo:quux', {'foo': ['bar', 'quux']}], + ['foo:1&bar:2;baz:quux', + 'foo:1%26bar%3A2;baz:quux', + {'foo': '1&bar:2', 'baz': 'quux'}], + ['foo%3Abaz:bar', 'foo%3Abaz:bar', {'foo:baz': 'bar'}], + ['foo:baz:bar', 'foo:baz%3Abar', {'foo': 'baz:bar'}] +]; + +// [wonkyObj, qs, canonicalObj] +var extendedFunction = function() {}; +extendedFunction.prototype = {a: 'b'}; +var qsWeirdObjects = [ + [{regexp: /./g}, 'regexp=', {'regexp': ''}], + [{regexp: new RegExp('.', 'g')}, 'regexp=', {'regexp': ''}], + [{fn: function() {}}, 'fn=', {'fn': ''}], + [{fn: new Function('')}, 'fn=', {'fn': ''}], + [{math: Math}, 'math=', {'math': ''}], + [{e: extendedFunction}, 'e=', {'e': ''}], + [{d: new Date()}, 'd=', {'d': ''}], + [{d: Date}, 'd=', {'d': ''}], + [{f: new Boolean(false), t: new Boolean(true)}, 'f=&t=', {'f': '', 't': ''}], + [{f: false, t: true}, 'f=false&t=true', {'f': 'false', 't': 'true'}], + [{n: null}, 'n=', {'n': ''}], + [{nan: NaN}, 'nan=', {'nan': ''}], + [{inf: Infinity}, 'inf=', {'inf': ''}] +]; +// }}} + +var Script = require('vm').Script; +var foreignObject = Script.runInContext('({"foo": ["bar", "baz"]})', + Script.createContext()); + +var qsNoMungeTestCases = [ + ['', {}], + ['foo=bar&foo=baz', {'foo': ['bar', 'baz']}], + ['foo=bar&foo=baz', foreignObject], + ['blah=burp', {'blah': 'burp'}], + ['gragh=1&gragh=3&goo=2', {'gragh': ['1', '3'], 'goo': '2'}], + ['frappucino=muffin&goat%5B%5D=scone&pond=moose', + {'frappucino': 'muffin', 'goat[]': 'scone', 'pond': 'moose'}], + ['trololol=yes&lololo=no', {'trololol': 'yes', 'lololo': 'no'}] +]; + +assert.strictEqual('918854443121279438895193', + qs.parse('id=918854443121279438895193').id); + +// test that the canonical qs is parsed properly. +qsTestCases.forEach(function(testCase) { + assert.deepEqual(testCase[2], qs.parse(testCase[0])); +}); + +// test that the colon test cases can do the same +qsColonTestCases.forEach(function(testCase) { + assert.deepEqual(testCase[2], qs.parse(testCase[0], ';', ':')); +}); + +// test the weird objects, that they get parsed properly +qsWeirdObjects.forEach(function(testCase) { + assert.deepEqual(testCase[2], qs.parse(testCase[1])); +}); + +qsNoMungeTestCases.forEach(function(testCase) { + assert.deepEqual(testCase[0], qs.stringify(testCase[1], '&', '=', false)); +}); + +// test the nested qs-in-qs case +(function() { + var f = qs.parse('a=b&q=x%3Dy%26y%3Dz'); + f.q = qs.parse(f.q); + assert.deepEqual(f, { a: 'b', q: { x: 'y', y: 'z' } }); +})(); + +// nested in colon +(function() { + var f = qs.parse('a:b;q:x%3Ay%3By%3Az', ';', ':'); + f.q = qs.parse(f.q, ';', ':'); + assert.deepEqual(f, { a: 'b', q: { x: 'y', y: 'z' } }); +})(); + +// now test stringifying + +// basic +qsTestCases.forEach(function(testCase) { + assert.equal(testCase[1], qs.stringify(testCase[2])); +}); + +qsColonTestCases.forEach(function(testCase) { + assert.equal(testCase[1], qs.stringify(testCase[2], ';', ':')); +}); + +qsWeirdObjects.forEach(function(testCase) { + assert.equal(testCase[1], qs.stringify(testCase[0])); +}); + +// nested +var f = qs.stringify({ + a: 'b', + q: qs.stringify({ + x: 'y', + y: 'z' + }) +}); +assert.equal(f, 'a=b&q=x%3Dy%26y%3Dz'); + +assert.doesNotThrow(function() { + qs.parse(undefined); +}); + +// nested in colon +var f = qs.stringify({ + a: 'b', + q: qs.stringify({ + x: 'y', + y: 'z' + }, ';', ':') +}, ';', ':'); +assert.equal(f, 'a:b;q:x%3Ay%3By%3Az'); + + +assert.deepEqual({}, qs.parse()); + + +// Test limiting +assert.equal( + Object.keys(qs.parse('a=1&b=1&c=1', null, null, { maxKeys: 1 })).length, + 1); + +// Test removing limit +function testUnlimitedKeys() { + var query = {}, + url; + + for (var i = 0; i < 2000; i++) query[i] = i; + + url = qs.stringify(query); + + assert.equal( + Object.keys(qs.parse(url, null, null, { maxKeys: 0 })).length, + 2000); +} +testUnlimitedKeys(); + + +var b = qs.unescapeBuffer('%d3%f2Ug%1f6v%24%5e%98%cb' + + '%0d%ac%a2%2f%9d%eb%d8%a2%e6'); +// +assert.equal(0xd3, b[0]); +assert.equal(0xf2, b[1]); +assert.equal(0x55, b[2]); +assert.equal(0x67, b[3]); +assert.equal(0x1f, b[4]); +assert.equal(0x36, b[5]); +assert.equal(0x76, b[6]); +assert.equal(0x24, b[7]); +assert.equal(0x5e, b[8]); +assert.equal(0x98, b[9]); +assert.equal(0xcb, b[10]); +assert.equal(0x0d, b[11]); +assert.equal(0xac, b[12]); +assert.equal(0xa2, b[13]); +assert.equal(0x2f, b[14]); +assert.equal(0x9d, b[15]); +assert.equal(0xeb, b[16]); +assert.equal(0xd8, b[17]); +assert.equal(0xa2, b[18]); +assert.equal(0xe6, b[19]); diff --git a/node-v0.8.14/test/simple/test-readdir.js b/node-v0.8.14/test/simple/test-readdir.js new file mode 100644 index 0000000..2499724 --- /dev/null +++ b/node-v0.8.14/test/simple/test-readdir.js @@ -0,0 +1,91 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var path = require('path'); +var fs = require('fs'); + +var got_error = false, + readdirDir = path.join(common.fixturesDir, 'readdir'); + +var files = ['are', + 'dir', + 'empty', + 'files', + 'for', + 'just', + 'testing.js', + 'these']; + + +console.log('readdirSync ' + readdirDir); +var f = fs.readdirSync(readdirDir); +console.dir(f); +assert.deepEqual(files, f.sort()); + + +console.log('readdir ' + readdirDir); +fs.readdir(readdirDir, function(err, f) { + if (err) { + console.log('error'); + got_error = true; + } else { + console.dir(f); + assert.deepEqual(files, f.sort()); + } +}); + +process.on('exit', function() { + assert.equal(false, got_error); + console.log('exit'); +}); + + +// readdir() on file should throw ENOTDIR +// https://github.com/joyent/node/issues/1869 +(function() { + var has_caught = false; + + try { + fs.readdirSync(__filename); + } + catch (e) { + has_caught = true; + assert.equal(e.code, 'ENOTDIR'); + } + + assert(has_caught); +})(); + + +(function() { + var readdir_cb_called = false; + + fs.readdir(__filename, function(e) { + readdir_cb_called = true; + assert.equal(e.code, 'ENOTDIR'); + }); + + process.on('exit', function() { + assert(readdir_cb_called); + }); +})(); diff --git a/node-v0.8.14/test/simple/test-readdouble.js b/node-v0.8.14/test/simple/test-readdouble.js new file mode 100644 index 0000000..9fa23e0 --- /dev/null +++ b/node-v0.8.14/test/simple/test-readdouble.js @@ -0,0 +1,131 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +/* + * Tests to verify we're reading in doubles correctly + */ +var SlowBuffer = process.binding('buffer').SlowBuffer; +var common = require('../common'); +var ASSERT = require('assert'); + +/* + * Test (64 bit) double + */ +function test(clazz) { + var buffer = new clazz(8); + + buffer[0] = 0x55; + buffer[1] = 0x55; + buffer[2] = 0x55; + buffer[3] = 0x55; + buffer[4] = 0x55; + buffer[5] = 0x55; + buffer[6] = 0xd5; + buffer[7] = 0x3f; + ASSERT.equal(1.1945305291680097e+103, buffer.readDoubleBE(0)); + ASSERT.equal(0.3333333333333333, buffer.readDoubleLE(0)); + + buffer[0] = 1; + buffer[1] = 0; + buffer[2] = 0; + buffer[3] = 0; + buffer[4] = 0; + buffer[5] = 0; + buffer[6] = 0xf0; + buffer[7] = 0x3f; + ASSERT.equal(7.291122019655968e-304, buffer.readDoubleBE(0)); + ASSERT.equal(1.0000000000000002, buffer.readDoubleLE(0)); + + buffer[0] = 2; + ASSERT.equal(4.778309726801735e-299, buffer.readDoubleBE(0)); + ASSERT.equal(1.0000000000000004, buffer.readDoubleLE(0)); + + buffer[0] = 1; + buffer[6] = 0; + buffer[7] = 0; + ASSERT.equal(7.291122019556398e-304, buffer.readDoubleBE(0)); + ASSERT.equal(5e-324, buffer.readDoubleLE(0)); + + buffer[0] = 0xff; + buffer[1] = 0xff; + buffer[2] = 0xff; + buffer[3] = 0xff; + buffer[4] = 0xff; + buffer[5] = 0xff; + buffer[6] = 0x0f; + buffer[7] = 0x00; + ASSERT.ok(isNaN(buffer.readDoubleBE(0))); + ASSERT.equal(2.225073858507201e-308, buffer.readDoubleLE(0)); + + buffer[6] = 0xef; + buffer[7] = 0x7f; + ASSERT.ok(isNaN(buffer.readDoubleBE(0))); + ASSERT.equal(1.7976931348623157e+308, buffer.readDoubleLE(0)); + + buffer[0] = 0; + buffer[1] = 0; + buffer[2] = 0; + buffer[3] = 0; + buffer[4] = 0; + buffer[5] = 0; + buffer[6] = 0xf0; + buffer[7] = 0x3f; + ASSERT.equal(3.03865e-319, buffer.readDoubleBE(0)); + ASSERT.equal(1, buffer.readDoubleLE(0)); + + buffer[6] = 0; + buffer[7] = 0x40; + ASSERT.equal(3.16e-322, buffer.readDoubleBE(0)); + ASSERT.equal(2, buffer.readDoubleLE(0)); + + buffer[7] = 0xc0; + ASSERT.equal(9.5e-322, buffer.readDoubleBE(0)); + ASSERT.equal(-2, buffer.readDoubleLE(0)); + + buffer[6] = 0x10; + buffer[7] = 0; + ASSERT.equal(2.0237e-320, buffer.readDoubleBE(0)); + ASSERT.equal(2.2250738585072014e-308, buffer.readDoubleLE(0)); + + buffer[6] = 0; + ASSERT.equal(0, buffer.readDoubleBE(0)); + ASSERT.equal(0, buffer.readDoubleLE(0)); + ASSERT.equal(false, 1 / buffer.readDoubleLE(0) < 0); + + buffer[7] = 0x80; + ASSERT.equal(6.3e-322, buffer.readDoubleBE(0)); + ASSERT.equal(0, buffer.readDoubleLE(0)); + ASSERT.equal(true, 1 / buffer.readDoubleLE(0) < 0); + + buffer[6] = 0xf0; + buffer[7] = 0x7f; + ASSERT.equal(3.0418e-319, buffer.readDoubleBE(0)); + ASSERT.equal(Infinity, buffer.readDoubleLE(0)); + + buffer[6] = 0xf0; + buffer[7] = 0xff; + ASSERT.equal(3.04814e-319, buffer.readDoubleBE(0)); + ASSERT.equal(-Infinity, buffer.readDoubleLE(0)); +} + + +test(Buffer); +test(SlowBuffer); diff --git a/node-v0.8.14/test/simple/test-readfloat.js b/node-v0.8.14/test/simple/test-readfloat.js new file mode 100644 index 0000000..373fa20 --- /dev/null +++ b/node-v0.8.14/test/simple/test-readfloat.js @@ -0,0 +1,93 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +/* + * Tests to verify we're reading in floats correctly + */ +var SlowBuffer = process.binding('buffer').SlowBuffer; +var common = require('../common'); +var ASSERT = require('assert'); + +/* + * Test (32 bit) float + */ +function test(clazz) { + var buffer = new clazz(4); + + buffer[0] = 0; + buffer[1] = 0; + buffer[2] = 0x80; + buffer[3] = 0x3f; + ASSERT.equal(4.600602988224807e-41, buffer.readFloatBE(0)); + ASSERT.equal(1, buffer.readFloatLE(0)); + + buffer[0] = 0; + buffer[1] = 0; + buffer[2] = 0; + buffer[3] = 0xc0; + ASSERT.equal(2.6904930515036488e-43, buffer.readFloatBE(0)); + ASSERT.equal(-2, buffer.readFloatLE(0)); + + buffer[0] = 0xff; + buffer[1] = 0xff; + buffer[2] = 0x7f; + buffer[3] = 0x7f; + ASSERT.ok(isNaN(buffer.readFloatBE(0))); + ASSERT.equal(3.4028234663852886e+38, buffer.readFloatLE(0)); + + buffer[0] = 0xab; + buffer[1] = 0xaa; + buffer[2] = 0xaa; + buffer[3] = 0x3e; + ASSERT.equal(-1.2126478207002966e-12, buffer.readFloatBE(0)); + ASSERT.equal(0.3333333432674408, buffer.readFloatLE(0)); + + buffer[0] = 0; + buffer[1] = 0; + buffer[2] = 0; + buffer[3] = 0; + ASSERT.equal(0, buffer.readFloatBE(0)); + ASSERT.equal(0, buffer.readFloatLE(0)); + ASSERT.equal(false, 1 / buffer.readFloatLE(0) < 0); + + buffer[3] = 0x80; + ASSERT.equal(1.793662034335766e-43, buffer.readFloatBE(0)); + ASSERT.equal(0, buffer.readFloatLE(0)); + ASSERT.equal(true, 1 / buffer.readFloatLE(0) < 0); + + buffer[0] = 0; + buffer[1] = 0; + buffer[2] = 0x80; + buffer[3] = 0x7f; + ASSERT.equal(4.609571298396486e-41, buffer.readFloatBE(0)); + ASSERT.equal(Infinity, buffer.readFloatLE(0)); + + buffer[0] = 0; + buffer[1] = 0; + buffer[2] = 0x80; + buffer[3] = 0xff; + ASSERT.equal(4.627507918739843e-41, buffer.readFloatBE(0)); + ASSERT.equal(-Infinity, buffer.readFloatLE(0)); +} + + +test(Buffer); +test(SlowBuffer); diff --git a/node-v0.8.14/test/simple/test-readint.js b/node-v0.8.14/test/simple/test-readint.js new file mode 100644 index 0000000..f1bae2d --- /dev/null +++ b/node-v0.8.14/test/simple/test-readint.js @@ -0,0 +1,122 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +/* + * Tests to verify we're reading in signed integers correctly + */ +var SlowBuffer = process.binding('buffer').SlowBuffer; +var common = require('../common'); +var ASSERT = require('assert'); + +/* + * Test 8 bit signed integers + */ +function test8(clazz) { + var data = new clazz(4); + + data[0] = 0x23; + ASSERT.equal(0x23, data.readInt8(0)); + + data[0] = 0xff; + ASSERT.equal(-1, data.readInt8(0)); + + data[0] = 0x87; + data[1] = 0xab; + data[2] = 0x7c; + data[3] = 0xef; + ASSERT.equal(-121, data.readInt8(0)); + ASSERT.equal(-85, data.readInt8(1)); + ASSERT.equal(124, data.readInt8(2)); + ASSERT.equal(-17, data.readInt8(3)); +} + + +function test16(clazz) { + var buffer = new clazz(6); + + buffer[0] = 0x16; + buffer[1] = 0x79; + ASSERT.equal(0x1679, buffer.readInt16BE(0)); + ASSERT.equal(0x7916, buffer.readInt16LE(0)); + + buffer[0] = 0xff; + buffer[1] = 0x80; + ASSERT.equal(-128, buffer.readInt16BE(0)); + ASSERT.equal(-32513, buffer.readInt16LE(0)); + + /* test offset with weenix */ + buffer[0] = 0x77; + buffer[1] = 0x65; + buffer[2] = 0x65; + buffer[3] = 0x6e; + buffer[4] = 0x69; + buffer[5] = 0x78; + ASSERT.equal(0x7765, buffer.readInt16BE(0)); + ASSERT.equal(0x6565, buffer.readInt16BE(1)); + ASSERT.equal(0x656e, buffer.readInt16BE(2)); + ASSERT.equal(0x6e69, buffer.readInt16BE(3)); + ASSERT.equal(0x6978, buffer.readInt16BE(4)); + ASSERT.equal(0x6577, buffer.readInt16LE(0)); + ASSERT.equal(0x6565, buffer.readInt16LE(1)); + ASSERT.equal(0x6e65, buffer.readInt16LE(2)); + ASSERT.equal(0x696e, buffer.readInt16LE(3)); + ASSERT.equal(0x7869, buffer.readInt16LE(4)); +} + + +function test32(clazz) { + var buffer = new clazz(6); + + buffer[0] = 0x43; + buffer[1] = 0x53; + buffer[2] = 0x16; + buffer[3] = 0x79; + ASSERT.equal(0x43531679, buffer.readInt32BE(0)); + ASSERT.equal(0x79165343, buffer.readInt32LE(0)); + + buffer[0] = 0xff; + buffer[1] = 0xfe; + buffer[2] = 0xef; + buffer[3] = 0xfa; + ASSERT.equal(-69638, buffer.readInt32BE(0)); + ASSERT.equal(-84934913, buffer.readInt32LE(0)); + + buffer[0] = 0x42; + buffer[1] = 0xc3; + buffer[2] = 0x95; + buffer[3] = 0xa9; + buffer[4] = 0x36; + buffer[5] = 0x17; + ASSERT.equal(0x42c395a9, buffer.readInt32BE(0)); + ASSERT.equal(-1013601994, buffer.readInt32BE(1)); + ASSERT.equal(-1784072681, buffer.readInt32BE(2)); + ASSERT.equal(-1449802942, buffer.readInt32LE(0)); + ASSERT.equal(917083587, buffer.readInt32LE(1)); + ASSERT.equal(389458325, buffer.readInt32LE(2)); +} + + +test8(Buffer); +test8(SlowBuffer); +test16(Buffer); +test16(SlowBuffer); +test32(Buffer); +test32(SlowBuffer); diff --git a/node-v0.8.14/test/simple/test-readline-interface.js b/node-v0.8.14/test/simple/test-readline-interface.js new file mode 100644 index 0000000..568b73a --- /dev/null +++ b/node-v0.8.14/test/simple/test-readline-interface.js @@ -0,0 +1,131 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + + +var assert = require('assert'); +var readline = require('readline'); +var EventEmitter = require('events').EventEmitter; +var inherits = require('util').inherits; + +function FakeInput() { + EventEmitter.call(this); +} +inherits(FakeInput, EventEmitter); +FakeInput.prototype.resume = function() {}; +FakeInput.prototype.pause = function() {}; + +var fi; +var rli; +var called; + +// sending a full line +fi = new FakeInput(); +rli = new readline.Interface(fi, {}); +called = false; +rli.on('line', function(line) { + called = true; + assert.equal(line, 'asdf\n'); +}); +fi.emit('data', 'asdf\n'); +assert.ok(called); + +// sending a blank line +fi = new FakeInput(); +rli = new readline.Interface(fi, {}); +called = false; +rli.on('line', function(line) { + called = true; + assert.equal(line, '\n'); +}); +fi.emit('data', '\n'); +assert.ok(called); + +// sending a single character with no newline +fi = new FakeInput(); +rli = new readline.Interface(fi, {}); +called = false; +rli.on('line', function(line) { + called = true; +}); +fi.emit('data', 'a'); +assert.ok(!called); +rli.close(); + +// sending a single character with no newline and then a newline +fi = new FakeInput(); +rli = new readline.Interface(fi, {}); +called = false; +rli.on('line', function(line) { + called = true; + assert.equal(line, 'a\n'); +}); +fi.emit('data', 'a'); +assert.ok(!called); +fi.emit('data', '\n'); +assert.ok(called); +rli.close(); + +// sending multiple newlines at once +fi = new FakeInput(); +rli = new readline.Interface(fi, {}); +var expectedLines = ['foo\n', 'bar\n', 'baz\n']; +var callCount = 0; +rli.on('line', function(line) { + assert.equal(line, expectedLines[callCount]); + callCount++; +}); +fi.emit('data', expectedLines.join('')); +assert.equal(callCount, expectedLines.length); +rli.close(); + +// sending multiple newlines at once that does not end with a new line +fi = new FakeInput(); +rli = new readline.Interface(fi, {}); +var expectedLines = ['foo\n', 'bar\n', 'baz\n', 'bat']; +var callCount = 0; +rli.on('line', function(line) { + assert.equal(line, expectedLines[callCount]); + callCount++; +}); +fi.emit('data', expectedLines.join('')); +assert.equal(callCount, expectedLines.length - 1); +rli.close(); + +// sending a multi-byte utf8 char over multiple writes +var buf = Buffer('☮', 'utf8'); +fi = new FakeInput(); +rli = new readline.Interface(fi, {}); +callCount = 0; +rli.on('line', function(line) { + callCount++; + assert.equal(line, buf.toString('utf8') + '\n'); +}); +[].forEach.call(buf, function(i) { + fi.emit('data', Buffer([i])); +}); +assert.equal(callCount, 0); +fi.emit('data', '\n'); +assert.equal(callCount, 1); +rli.close(); + +assert.deepEqual(fi.listeners('end'), []); +assert.deepEqual(fi.listeners('data'), []); diff --git a/node-v0.8.14/test/simple/test-readline-set-raw-mode.js b/node-v0.8.14/test/simple/test-readline-set-raw-mode.js new file mode 100644 index 0000000..5bca527 --- /dev/null +++ b/node-v0.8.14/test/simple/test-readline-set-raw-mode.js @@ -0,0 +1,91 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + + +var assert = require('assert'); +var readline = require('readline'); +var Stream = require('stream'); + +var stream = new Stream(); +var expectedRawMode = true; +var rawModeCalled = false; +var resumeCalled = false; +var pauseCalled = false; + +stream.setRawMode = function(mode) { + rawModeCalled = true; + assert.equal(mode, expectedRawMode); +}; +stream.resume = function() { + resumeCalled = true; +}; +stream.pause = function() { + pauseCalled = true; +}; + +// when the "readline" starts in "terminal" mode, +// then setRawMode(true) should be called +var rli = readline.createInterface({ + input: stream, + output: stream, + terminal: true +}); +assert(rli.terminal) +assert(rawModeCalled); +assert(resumeCalled); +assert(!pauseCalled); + + +// pause() should call *not* call setRawMode() +rawModeCalled = false; +resumeCalled = false; +pauseCalled = false; +rli.pause(); +assert(!rawModeCalled); +assert(!resumeCalled); +assert(pauseCalled); + + +// resume() should *not* call setRawMode() +rawModeCalled = false; +resumeCalled = false; +pauseCalled = false; +rli.resume(); +assert(!rawModeCalled); +assert(resumeCalled); +assert(!pauseCalled); + + +// close() should call setRawMode(false) +expectedRawMode = false; +rawModeCalled = false; +resumeCalled = false; +pauseCalled = false; +rli.close(); +assert(rawModeCalled); +assert(!resumeCalled); +assert(pauseCalled); + +assert.deepEqual(stream.listeners('end'), []); +assert.deepEqual(stream.listeners('keypress'), []); +// one data listener for the keypress events. +assert.equal(stream.listeners('data').length, 1); diff --git a/node-v0.8.14/test/simple/test-readuint.js b/node-v0.8.14/test/simple/test-readuint.js new file mode 100644 index 0000000..e63bba7 --- /dev/null +++ b/node-v0.8.14/test/simple/test-readuint.js @@ -0,0 +1,113 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +/* + * A battery of tests to help us read a series of uints + */ + +var SlowBuffer = process.binding('buffer').SlowBuffer; +var common = require('../common'); +var ASSERT = require('assert'); + +/* + * We need to check the following things: + * - We are correctly resolving big endian (doesn't mean anything for 8 bit) + * - Correctly resolving little endian (doesn't mean anything for 8 bit) + * - Correctly using the offsets + * - Correctly interpreting values that are beyond the signed range as unsigned + */ +function test8(clazz) { + var data = new clazz(4); + + data[0] = 23; + data[1] = 23; + data[2] = 23; + data[3] = 23; + ASSERT.equal(23, data.readUInt8(0)); + ASSERT.equal(23, data.readUInt8(1)); + ASSERT.equal(23, data.readUInt8(2)); + ASSERT.equal(23, data.readUInt8(3)); + + data[0] = 255; /* If it became a signed int, would be -1 */ + ASSERT.equal(255, data.readUInt8(0)); +} + + +/* + * Test 16 bit unsigned integers. We need to verify the same set as 8 bit, only + * now some of the issues actually matter: + * - We are correctly resolving big endian + * - Correctly resolving little endian + * - Correctly using the offsets + * - Correctly interpreting values that are beyond the signed range as unsigned + */ +function test16(clazz) { + var data = new clazz(4); + + data[0] = 0; + data[1] = 0x23; + data[2] = 0x42; + data[3] = 0x3f; + ASSERT.equal(0x23, data.readUInt16BE(0)); + ASSERT.equal(0x2342, data.readUInt16BE(1)); + ASSERT.equal(0x423f, data.readUInt16BE(2)); + ASSERT.equal(0x2300, data.readUInt16LE(0)); + ASSERT.equal(0x4223, data.readUInt16LE(1)); + ASSERT.equal(0x3f42, data.readUInt16LE(2)); + + data[0] = 0xfe; + data[1] = 0xfe; + ASSERT.equal(0xfefe, data.readUInt16BE(0)); + ASSERT.equal(0xfefe, data.readUInt16LE(0)); +} + + +/* + * Test 32 bit unsigned integers. We need to verify the same set as 8 bit, only + * now some of the issues actually matter: + * - We are correctly resolving big endian + * - Correctly using the offsets + * - Correctly interpreting values that are beyond the signed range as unsigned + */ +function test32(clazz) { + var data = new clazz(8); + + data[0] = 0x32; + data[1] = 0x65; + data[2] = 0x42; + data[3] = 0x56; + data[4] = 0x23; + data[5] = 0xff; + ASSERT.equal(0x32654256, data.readUInt32BE(0)); + ASSERT.equal(0x65425623, data.readUInt32BE(1)); + ASSERT.equal(0x425623ff, data.readUInt32BE(2)); + ASSERT.equal(0x56426532, data.readUInt32LE(0)); + ASSERT.equal(0x23564265, data.readUInt32LE(1)); + ASSERT.equal(0xff235642, data.readUInt32LE(2)); +} + + +test8(Buffer); +test8(SlowBuffer); +test16(Buffer); +test16(SlowBuffer); +test32(Buffer); +test32(SlowBuffer); diff --git a/node-v0.8.14/test/simple/test-regress-GH-1531.js b/node-v0.8.14/test/simple/test-regress-GH-1531.js new file mode 100644 index 0000000..58086e0 --- /dev/null +++ b/node-v0.8.14/test/simple/test-regress-GH-1531.js @@ -0,0 +1,62 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +if (!process.versions.openssl) { + console.error('Skipping because node compiled without OpenSSL.'); + process.exit(0); +} + +var https = require('https'); +var assert = require('assert'); +var fs = require('fs'); +var common = require('../common'); + +var options = { + key: fs.readFileSync(common.fixturesDir + '/keys/agent1-key.pem'), + cert: fs.readFileSync(common.fixturesDir + '/keys/agent1-cert.pem') +}; + +var gotCallback = false; + +var server = https.createServer(options, function(req, res) { + res.writeHead(200); + res.end('hello world\n'); +}); + +server.listen(common.PORT, function() { + https.get({ + path: '/', + port: common.PORT, + agent: false + }, function(res) { + console.error(res.statusCode); + gotCallback = true; + server.close(); + }).on('error', function(e) { + console.error(e.message); + process.exit(1); + }); +}); + +process.on('exit', function() { + assert.ok(gotCallback); +}); + diff --git a/node-v0.8.14/test/simple/test-regress-GH-1697.js b/node-v0.8.14/test/simple/test-regress-GH-1697.js new file mode 100644 index 0000000..82aed3e --- /dev/null +++ b/node-v0.8.14/test/simple/test-regress-GH-1697.js @@ -0,0 +1,70 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var net = require('net'), + cp = require('child_process'), + util = require('util'); + +if (process.argv[2] === 'server') { + // Server + + var server = net.createServer(function(conn) { + conn.on('data', function(data) { + console.log('server received ' + data.length + ' bytes'); + }); + + conn.on('close', function() { + server.close(); + }); + }); + + server.listen(1234, '127.0.0.1', function() { + console.log('Server running.'); + }); + +} else { + // Client + + var serverProcess = cp.spawn(process.execPath, [process.argv[1], 'server']); + serverProcess.stdout.pipe(process.stdout); + serverProcess.stderr.pipe(process.stdout); + + serverProcess.stdout.once('data', function() { + var client = net.createConnection(1234, '127.0.0.1'); + client.on('connect', function() { + var alot = new Buffer(1024), + alittle = new Buffer(1); + + for (var i = 0; i < 100; i++) { + client.write(alot); + } + + // Block the event loop for 1 second + var start = (new Date()).getTime(); + while ((new Date).getTime() < start + 1000) {} + + client.write(alittle); + + client.destroySoon(); + }); + }); +} diff --git a/node-v0.8.14/test/simple/test-regress-GH-1726.js b/node-v0.8.14/test/simple/test-regress-GH-1726.js new file mode 100644 index 0000000..2ed3004 --- /dev/null +++ b/node-v0.8.14/test/simple/test-regress-GH-1726.js @@ -0,0 +1,64 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// 'Software'), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// Open a chain of five Node processes each a child of the next. The final +// process exits immediately. Each process in the chain is instructed to +// exit when its child exits. +// https://github.com/joyent/node/issues/1726 + +var common = require('../common'); +var assert = require('assert'); +var ch = require('child_process'); + +var gen = +(process.argv[2] || 0); +var maxGen = 5; + + +if (gen === maxGen) { + console.error('hit maxGen, exiting', maxGen); + return; +} + +var child = ch.spawn(process.execPath, [__filename, gen + 1], { + customFds: [0, -1, 2] +}); +assert.ok(!child.stdin); +assert.ok(child.stdout); +assert.ok(!child.stderr); + +console.error('gen=%d, pid=%d', gen, process.pid); + +/* +var timer = setTimeout(function () { + throw new Error('timeout! gen='+gen); +}, 1000); +*/ + +child.on('exit', function(code) { + console.error('exit %d from gen %d', code, gen + 1); + //clearTimeout(timer); +}); + +child.stdout.pipe(process.stdout); + +child.stdout.on('close', function() { + console.error('child.stdout close gen=%d', gen); +}); diff --git a/node-v0.8.14/test/simple/test-regress-GH-1899.js b/node-v0.8.14/test/simple/test-regress-GH-1899.js new file mode 100644 index 0000000..7fc8007 --- /dev/null +++ b/node-v0.8.14/test/simple/test-regress-GH-1899.js @@ -0,0 +1,40 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var path = require('path'); +var assert = require('assert'); +var spawn = require('child_process').spawn; +var common = require('../common'); + +var child = spawn(process.argv[0], [ + path.join(common.fixturesDir, 'GH-1899-output.js') +]); +var output = ''; + +child.stdout.on('data', function(data) { + output += data; +}); + +child.on('exit', function(code, signal) { + assert.equal(code, 0); + assert.equal(output, 'hello, world!\n'); +}); + diff --git a/node-v0.8.14/test/simple/test-regress-GH-3542.js b/node-v0.8.14/test/simple/test-regress-GH-3542.js new file mode 100644 index 0000000..90e0b78 --- /dev/null +++ b/node-v0.8.14/test/simple/test-regress-GH-3542.js @@ -0,0 +1,54 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// This test is only relevant on Windows. +if (process.platform !== 'win32') { + return process.exit(0); +} + +var common = require('../common.js'), + assert = require('assert'), + fs = require('fs'), + path = require('path'), + succeeded = 0; + +function test(p) { + var result = fs.realpathSync(p); + assert.strictEqual(result, path.resolve(p)); + + fs.realpath(p, function(err, result) { + assert.ok(!err); + assert.strictEqual(result, path.resolve(p)); + succeeded++; + }); +} + +test('//localhost/c$/windows/system32'); +test('//localhost/c$/windows'); +test('//localhost/c$/') +test('\\\\localhost\\c$') +test('c:\\'); +test('c:'); +test(process.env.windir); + +process.on('exit', function() { + assert.strictEqual(succeeded, 7); +}); \ No newline at end of file diff --git a/node-v0.8.14/test/simple/test-regress-GH-3739.js b/node-v0.8.14/test/simple/test-regress-GH-3739.js new file mode 100644 index 0000000..9370687 --- /dev/null +++ b/node-v0.8.14/test/simple/test-regress-GH-3739.js @@ -0,0 +1,66 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common.js'), + assert = require('assert'), + fs = require('fs'), + path = require('path'); + +var dir = path.resolve(common.fixturesDir), + dirs = []; + +// Make a long path. +for (var i = 0; i < 50; i++) { + dir = dir + '/123456790'; + try { + fs.mkdirSync(dir, '0777'); + } catch (e) { + if (e.code == 'EEXIST') { + // Ignore; + } else { + cleanup(); + throw e; + } + } + dirs.push(dir); +} + +// Test existsSync +var r = fs.existsSync(dir); +if (r !== true) { + cleanup(); + throw new Error('fs.existsSync returned false'); +} + +// Text exists +fs.exists(dir, function(r) { + cleanup(); + if (r !== true) { + throw new Error('fs.exists reported false'); + } +}); + +// Remove all created directories +function cleanup() { + for (var i = dirs.length - 1; i >= 0; i--) { + fs.rmdirSync(dirs[i]); + } +} diff --git a/node-v0.8.14/test/simple/test-regress-GH-4015.js b/node-v0.8.14/test/simple/test-regress-GH-4015.js new file mode 100644 index 0000000..b66584f --- /dev/null +++ b/node-v0.8.14/test/simple/test-regress-GH-4015.js @@ -0,0 +1,33 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var exec = require('child_process').exec; + +var cmd = process.execPath + + ' ' + + common.fixturesDir + + '/test-regress-GH-4015.js'; + +exec(cmd, function(err, stdout, stderr) { + assert(/RangeError: Maximum call stack size exceeded/.test(stderr)); +}); diff --git a/node-v0.8.14/test/simple/test-regress-GH-4027.js b/node-v0.8.14/test/simple/test-regress-GH-4027.js new file mode 100644 index 0000000..3dff168 --- /dev/null +++ b/node-v0.8.14/test/simple/test-regress-GH-4027.js @@ -0,0 +1,41 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var path = require('path'); +var fs = require('fs'); + +var filename = path.join(common.tmpDir, 'watched'); +fs.writeFileSync(filename, 'quis custodiet ipsos custodes'); +setTimeout(fs.unlinkSync, 100, filename); + +var seenEvent = 0; +process.on('exit', function() { + assert.equal(seenEvent, 1); +}); + +fs.watchFile(filename, { interval: 50 }, function(curr, prev) { + assert.equal(prev.nlink, 1); + assert.equal(curr.nlink, 0); + fs.unwatchFile(filename); + seenEvent++; +}); diff --git a/node-v0.8.14/test/simple/test-regress-GH-746.js b/node-v0.8.14/test/simple/test-regress-GH-746.js new file mode 100644 index 0000000..29f1456 --- /dev/null +++ b/node-v0.8.14/test/simple/test-regress-GH-746.js @@ -0,0 +1,50 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// Just test that destroying stdin doesn't mess up listening on a server. +// This is a regression test for GH-746. + +var common = require('../common'); +var assert = require('assert'); +var net = require('net'); + +process.stdin.destroy(); + +var accepted = null; +var server = net.createServer(function(socket) { + console.log('accepted'); + accepted = socket; + socket.end(); + server.close(); +}); + + +server.listen(common.PORT, function() { + console.log('listening...'); + + net.createConnection(common.PORT); +}); + + +process.on('exit', function() { + assert.ok(accepted); +}); + diff --git a/node-v0.8.14/test/simple/test-regress-GH-784.js b/node-v0.8.14/test/simple/test-regress-GH-784.js new file mode 100644 index 0000000..c2039a9 --- /dev/null +++ b/node-v0.8.14/test/simple/test-regress-GH-784.js @@ -0,0 +1,157 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// Regression test for GH-784 +// https://github.com/joyent/node/issues/784 +// +// The test works by making a total of 8 requests to the server. The first +// two are made with the server off - they should come back as ECONNREFUSED. +// The next two are made with server on - they should come back successful. +// The next two are made with the server off - and so on. Without the fix +// we were experiencing parse errors and instead of ECONNREFUSED. +var common = require('../common'); +var http = require('http'); +var assert = require('assert'); + + +var server = http.createServer(function(req, res) { + var body = ''; + + req.setEncoding('utf8'); + req.on('data', function(chunk) { + body += chunk; + }); + + req.on('end', function() { + assert.equal('PING', body); + res.writeHead(200); + res.end('PONG'); + }); +}); + + +server.on('listening', pingping); + + +function serverOn() { + console.error('Server ON'); + server.listen(common.PORT); +} + + +function serverOff() { + console.error('Server OFF'); + server.close(); + pingping(); +} + +var responses = []; + + +function afterPing(result) { + responses.push(result); + console.error('afterPing. responses.length = ' + responses.length); + switch (responses.length) { + case 2: + assert.ok(/ECONNREFUSED/.test(responses[0])); + assert.ok(/ECONNREFUSED/.test(responses[1])); + serverOn(); + break; + + case 4: + assert.ok(/success/.test(responses[2])); + assert.ok(/success/.test(responses[3])); + serverOff(); + break; + + case 6: + assert.ok(/ECONNREFUSED/.test(responses[4])); + assert.ok(/ECONNREFUSED/.test(responses[5])); + serverOn(); + break; + + case 8: + assert.ok(/success/.test(responses[6])); + assert.ok(/success/.test(responses[7])); + server.close(); + // we should go to process.on('exit') from here. + break; + } +} + + +function ping() { + console.error('making req'); + + var opt = { + port: common.PORT, + path: '/ping', + method: 'POST' + }; + + var req = http.request(opt, function(res) { + var body = ''; + + res.setEncoding('utf8'); + res.on('data', function(chunk) { + body += chunk; + }); + + res.on('end', function() { + assert.equal('PONG', body); + assert.ok(!hadError); + gotEnd = true; + afterPing('success'); + }); + }); + + req.end('PING'); + + var gotEnd = false; + var hadError = false; + + req.on('error', function(error) { + console.log('Error making ping req: ' + error); + hadError = true; + assert.ok(!gotEnd); + afterPing(error.message); + }); +} + + + +function pingping() { + ping(); + ping(); +} + + +pingping(); + + + + +process.on('exit', function() { + console.error("process.on('exit')"); + console.error(responses); + + assert.equal(8, responses.length); +}); diff --git a/node-v0.8.14/test/simple/test-regress-GH-819.js b/node-v0.8.14/test/simple/test-regress-GH-819.js new file mode 100644 index 0000000..874d99e --- /dev/null +++ b/node-v0.8.14/test/simple/test-regress-GH-819.js @@ -0,0 +1,28 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var net = require('net'); +var assert = require('assert'); + +// Connect to something that we need to DNS resolve +var c = net.createConnection(80, 'google.com'); +c.destroy(); diff --git a/node-v0.8.14/test/simple/test-regress-GH-877.js b/node-v0.8.14/test/simple/test-regress-GH-877.js new file mode 100644 index 0000000..d431118 --- /dev/null +++ b/node-v0.8.14/test/simple/test-regress-GH-877.js @@ -0,0 +1,71 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var http = require('http'); +var assert = require('assert'); + +var N = 20; +var responses = 0; +var maxQueued = 0; + +var agent = http.globalAgent; +agent.maxSockets = 10; + +var server = http.createServer(function(req, res) { + res.writeHead(200); + res.end('Hello World\n'); +}); + +var addrString = '127.0.0.1:' + common.PORT; + +server.listen(common.PORT, '127.0.0.1', function() { + for (var i = 0; i < N; i++) { + var options = { + host: '127.0.0.1', + port: common.PORT + }; + + var req = http.get(options, function(res) { + if (++responses == N) { + server.close(); + } + }); + + assert.equal(req.agent, agent); + + console.log('Socket: ' + agent.sockets[addrString].length + '/' + + agent.maxSockets + ' queued: ' + (agent.requests[addrString] ? + agent.requests['127.0.0.1:' + common.PORT].length : 0)); + + var agentRequests = agent.requests[addrString] ? + agent.requests[addrString].length : 0; + + if (maxQueued < agentRequests) { + maxQueued = agentRequests; + } + } +}); + +process.on('exit', function() { + assert.ok(responses == N); + assert.ok(maxQueued <= 10); +}); diff --git a/node-v0.8.14/test/simple/test-regress-GH-897.js b/node-v0.8.14/test/simple/test-regress-GH-897.js new file mode 100644 index 0000000..dd4399f --- /dev/null +++ b/node-v0.8.14/test/simple/test-regress-GH-897.js @@ -0,0 +1,35 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); + +var t = Date.now(); +var diff; +setTimeout(function() { + diff = Date.now() - t; + console.error(diff); +}, 0.1); + + +process.on('exit', function() { + assert.ok(diff < 100); +}); diff --git a/node-v0.8.14/test/simple/test-regression-object-prototype.js b/node-v0.8.14/test/simple/test-regression-object-prototype.js new file mode 100644 index 0000000..158532a --- /dev/null +++ b/node-v0.8.14/test/simple/test-regression-object-prototype.js @@ -0,0 +1,27 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +//console.log('puts before'); + +Object.prototype.xadsadsdasasdxx = function() { +}; + +console.log('puts after'); diff --git a/node-v0.8.14/test/simple/test-repl-.save.load.js b/node-v0.8.14/test/simple/test-repl-.save.load.js new file mode 100644 index 0000000..b5749c8 --- /dev/null +++ b/node-v0.8.14/test/simple/test-repl-.save.load.js @@ -0,0 +1,98 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var assert = require('assert'); +var util = require('util'); +var join = require('path').join; +var fs = require('fs'); +var common = require('../common'); + +var repl = require('repl'); + +// A stream to push an array into a REPL +function ArrayStream() { + this.run = function(data) { + var self = this; + data.forEach(function(line) { + self.emit('data', line + '\n'); + }); + } +} +util.inherits(ArrayStream, require('stream').Stream); +ArrayStream.prototype.readable = true; +ArrayStream.prototype.writable = true; +ArrayStream.prototype.resume = function() {}; +ArrayStream.prototype.write = function() {}; + +var works = [['inner.one'], 'inner.o']; + +var putIn = new ArrayStream(); +var testMe = repl.start('', putIn); + + +var testFile = [ + 'var top = function () {', + 'var inner = {one:1};' +]; +var saveFileName = join(common.tmpDir, 'test.save.js'); + +// input some data +putIn.run(testFile); + +// save it to a file +putIn.run(['.save ' + saveFileName]); + +// the file should have what I wrote +assert.equal(fs.readFileSync(saveFileName, 'utf8'), testFile.join('\n') + '\n'); + +// make sure that the REPL data is "correct" +// so when I load it back I know I'm good +testMe.complete('inner.o', function(error, data) { + assert.deepEqual(data, works); +}); + +// clear the REPL +putIn.run(['.clear']); + +// Load the file back in +putIn.run(['.load ' + saveFileName]); + +// make sure that the REPL data is "correct" +testMe.complete('inner.o', function(error, data) { + assert.deepEqual(data, works); +}); + +// clear the REPL +putIn.run(['.clear']); + +var loadFile = join(common.tmpDir, 'file.does.not.exist'); + +// shold not break +putIn.write = function(data) { + // make sure I get a failed to load message and not some crazy error + assert.equal(data, 'Failed to load:' + loadFile + '\n'); + // eat me to avoid work + putIn.write = function() {}; +}; +putIn.run(['.load ' + loadFile]); + + +//TODO how do I do a failed .save test? diff --git a/node-v0.8.14/test/simple/test-repl-autolibs.js b/node-v0.8.14/test/simple/test-repl-autolibs.js new file mode 100644 index 0000000..0f4ae8b --- /dev/null +++ b/node-v0.8.14/test/simple/test-repl-autolibs.js @@ -0,0 +1,79 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var assert = require('assert'); +var util = require('util'); +var repl = require('repl'); + +// A stream to push an array into a REPL +function ArrayStream() { + this.run = function (data) { + var self = this; + data.forEach(function (line) { + self.emit('data', line + '\n'); + }); + } +} +util.inherits(ArrayStream, require('stream').Stream); +ArrayStream.prototype.readable = true; +ArrayStream.prototype.writable = true; +ArrayStream.prototype.resume = function () {}; +ArrayStream.prototype.write = function () {}; + +var putIn = new ArrayStream; +var testMe = repl.start('', putIn, null, true); + +test1(); + +function test1(){ + var gotWrite = false; + putIn.write = function (data) { + gotWrite = true; + if (data.length) { + // inspect output matches repl output + assert.equal(data, util.inspect(require('fs'), null, null, false) + '\n'); + // globally added lib matches required lib + assert.equal(global.fs, require('fs')); + test2(); + } + }; + assert(!gotWrite); + putIn.run(['fs']); + assert(gotWrite); +} + +function test2(){ + var gotWrite = false; + putIn.write = function(data) { + gotWrite = true; + if (data.length) { + // repl response error message + assert.equal(data.indexOf('A different'), 0); + // original value wasn't overwritten + assert.equal(val, global.url); + } + }; + var val = {}; + global.url = val; + assert(!gotWrite); + putIn.run(['url']); + assert(gotWrite); +} diff --git a/node-v0.8.14/test/simple/test-repl-end-emits-exit.js b/node-v0.8.14/test/simple/test-repl-end-emits-exit.js new file mode 100644 index 0000000..46eca2e --- /dev/null +++ b/node-v0.8.14/test/simple/test-repl-end-emits-exit.js @@ -0,0 +1,77 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'), + assert = require('assert'), + Stream = require('stream'), + repl = require('repl'), + terminalExit = 0, + regularExit = 0; + +// create a dummy stream that does nothing +var stream = new Stream(); +stream.write = stream.pause = stream.resume = function(){}; +stream.readable = stream.writable = true; + +function testTerminalMode() { + var r1 = repl.start({ + input: stream, + output: stream, + terminal: true + }); + + process.nextTick(function() { + // manually fire a ^D keypress + stream.emit('data', '\u0004'); + }); + + r1.on('exit', function() { + // should be fired from the simulated ^D keypress + terminalExit++; + testRegularMode(); + }); +} + +function testRegularMode() { + var r2 = repl.start({ + input: stream, + output: stream, + terminal: false + }); + + process.nextTick(function() { + stream.emit('end'); + }); + + r2.on('exit', function() { + // should be fired from the simulated 'end' event + regularExit++; + }); +} + +process.on('exit', function() { + assert.equal(terminalExit, 1); + assert.equal(regularExit, 1); +}); + + +// start +testTerminalMode(); diff --git a/node-v0.8.14/test/simple/test-repl-options.js b/node-v0.8.14/test/simple/test-repl-options.js new file mode 100644 index 0000000..d3fcd58 --- /dev/null +++ b/node-v0.8.14/test/simple/test-repl-options.js @@ -0,0 +1,71 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'), + assert = require('assert'), + Stream = require('stream'), + repl = require('repl'); + +common.globalCheck = false; + +// create a dummy stream that does nothing +var stream = new Stream(); +stream.write = stream.pause = stream.resume = function(){}; +stream.readable = stream.writable = true; + +// 1, mostly defaults +var r1 = repl.start({ + input: stream, + output: stream, + terminal: true +}); +assert.equal(r1.rli.input, stream); +assert.equal(r1.rli.output, stream); +assert.equal(r1.rli.input, r1.inputStream); +assert.equal(r1.rli.output, r1.outputStream); +assert.equal(r1.rli.terminal, true); +assert.equal(r1.useColors, r1.rli.terminal); +assert.equal(r1.useGlobal, false); +assert.equal(r1.ignoreUndefined, false); + +// 2 +function writer() {} +function evaler() {} +var r2 = repl.start({ + input: stream, + output: stream, + terminal: false, + useColors: true, + useGlobal: true, + ignoreUndefined: true, + eval: evaler, + writer: writer +}); +assert.equal(r2.rli.input, stream); +assert.equal(r2.rli.output, stream); +assert.equal(r2.rli.input, r2.inputStream); +assert.equal(r2.rli.output, r2.outputStream); +assert.equal(r2.rli.terminal, false); +assert.equal(r2.useColors, true); +assert.equal(r2.useGlobal, true); +assert.equal(r2.ignoreUndefined, true); +assert.equal(r2.eval, evaler); +assert.equal(r2.writer, writer); diff --git a/node-v0.8.14/test/simple/test-repl-tab-complete.js b/node-v0.8.14/test/simple/test-repl-tab-complete.js new file mode 100644 index 0000000..4e9df6b --- /dev/null +++ b/node-v0.8.14/test/simple/test-repl-tab-complete.js @@ -0,0 +1,210 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var util = require('util'); + +var repl = require('repl'); + +// A stream to push an array into a REPL +function ArrayStream() { + this.run = function(data) { + var self = this; + data.forEach(function(line) { + self.emit('data', line + '\n'); + }); + } +} +util.inherits(ArrayStream, require('stream').Stream); +ArrayStream.prototype.readable = true; +ArrayStream.prototype.writable = true; +ArrayStream.prototype.resume = function() {}; +ArrayStream.prototype.write = function() {}; + +var works = [['inner.one'], 'inner.o']; +var doesNotBreak = [[], 'inner.o']; + +var putIn = new ArrayStream(); +var testMe = repl.start('', putIn); + +// Tab Complete will not break in an object literal +putIn.run(['.clear']); +putIn.run([ + 'var inner = {', + 'one:1' +]); +testMe.complete('inner.o', function(error, data) { + assert.deepEqual(data, doesNotBreak); +}); + +// Tab Complete will return globaly scoped variables +putIn.run(['};']); +testMe.complete('inner.o', function(error, data) { + assert.deepEqual(data, works); +}); + +putIn.run(['.clear']); + +// Tab Complete will not break in an ternary operator with () +putIn.run([ + 'var inner = ( true ' , + '?', + '{one: 1} : ' +]); +testMe.complete('inner.o', function(error, data) { + assert.deepEqual(data, doesNotBreak); +}); + +putIn.run(['.clear']); + +// Tab Complete will return a simple local variable +putIn.run([ + 'var top = function () {', + 'var inner = {one:1};' +]); +testMe.complete('inner.o', function(error, data) { + assert.deepEqual(data, works); +}); + +// When you close the function scope tab complete will not return the +// locally scoped variable +putIn.run(['};']); +testMe.complete('inner.o', function(error, data) { + assert.deepEqual(data, doesNotBreak); +}); + +putIn.run(['.clear']); + +// Tab Complete will return a complex local variable +putIn.run([ + 'var top = function () {', + 'var inner = {', + ' one:1', + '};' +]); +testMe.complete('inner.o', function(error, data) { + assert.deepEqual(data, works); +}); + +putIn.run(['.clear']); + +// Tab Complete will return a complex local variable even if the function +// has paramaters +putIn.run([ + 'var top = function (one, two) {', + 'var inner = {', + ' one:1', + '};' +]); +testMe.complete('inner.o', function(error, data) { + assert.deepEqual(data, works); +}); + +putIn.run(['.clear']); + +// Tab Complete will return a complex local variable even if the +// scope is nested inside an immediately executed function +putIn.run([ + 'var top = function () {', + '(function test () {', + 'var inner = {', + ' one:1', + '};' +]); +testMe.complete('inner.o', function(error, data) { + assert.deepEqual(data, works); +}); + +putIn.run(['.clear']); + +// currently does not work, but should not break note the inner function +// def has the params and { on a seperate line +putIn.run([ + 'var top = function () {', + 'r = function test (', + ' one, two) {', + 'var inner = {', + ' one:1', + '};' +]); +testMe.complete('inner.o', function(error, data) { + assert.deepEqual(data, doesNotBreak); +}); + +putIn.run(['.clear']); + +// currently does not work, but should not break, not the { +putIn.run([ + 'var top = function () {', + 'r = function test ()', + '{', + 'var inner = {', + ' one:1', + '};' +]); +testMe.complete('inner.o', function(error, data) { + assert.deepEqual(data, doesNotBreak); +}); + +putIn.run(['.clear']); + +// currently does not work, but should not break +putIn.run([ + 'var top = function () {', + 'r = function test (', + ')', + '{', + 'var inner = {', + ' one:1', + '};' +]); +testMe.complete('inner.o', function(error, data) { + assert.deepEqual(data, doesNotBreak); +}); + +putIn.run(['.clear']); + +// make sure tab completion works on non-Objects +putIn.run([ + 'var str = "test";' +]); +testMe.complete('str.len', function(error, data) { + assert.deepEqual(data, [['str.length'], 'str.len']); +}); + +putIn.run(['.clear']); + +// tab completion should not break on spaces +var spaceTimeout = setTimeout(function() { + throw new Error('timeout'); +}, 1000); + +testMe.complete(' ', function(error, data) { + assert.deepEqual(data, [[],undefined]); + clearTimeout(spaceTimeout); +}); + +// tab completion should pick up the global "toString" object, and +// any other properties up the "global" object's prototype chain +testMe.complete('toSt', function(error, data) { + assert.deepEqual(data, [['toString'], 'toSt']); +}); diff --git a/node-v0.8.14/test/simple/test-repl.js b/node-v0.8.14/test/simple/test-repl.js new file mode 100644 index 0000000..aeca81c --- /dev/null +++ b/node-v0.8.14/test/simple/test-repl.js @@ -0,0 +1,310 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); + +common.globalCheck = false; + +var net = require('net'), + repl = require('repl'), + message = 'Read, Eval, Print Loop', + prompt_unix = 'node via Unix socket> ', + prompt_tcp = 'node via TCP socket> ', + prompt_multiline = '... ', + prompt_npm = 'npm should be run outside of the ' + + 'node repl, in your normal shell.\n' + + '(Press Control-D to exit.)\n', + expect_npm = prompt_npm + prompt_unix, + server_tcp, server_unix, client_tcp, client_unix, timer; + + +// absolute path to test/fixtures/a.js +var moduleFilename = require('path').join(common.fixturesDir, 'a'); + +common.error('repl test'); + +// function for REPL to run +invoke_me = function(arg) { + return 'invoked ' + arg; +}; + +function send_expect(list) { + if (list.length > 0) { + var cur = list.shift(); + + common.error('sending ' + JSON.stringify(cur.send)); + + cur.client.expect = cur.expect; + cur.client.list = list; + if (cur.send.length > 0) { + cur.client.write(cur.send + '\n'); + } + } +} + +function clean_up() { + client_tcp.end(); + client_unix.end(); + clearTimeout(timer); +} + +function error_test() { + // The other stuff is done so reuse unix socket + var read_buffer = ''; + client_unix.removeAllListeners('data'); + + client_unix.on('data', function(data) { + read_buffer += data.toString('ascii', 0, data.length); + common.error('Unix data: ' + JSON.stringify(read_buffer) + ', expecting ' + + (client_unix.expect.exec ? + client_unix.expect : + JSON.stringify(client_unix.expect))); + + if (read_buffer.indexOf(prompt_unix) !== -1) { + // if it's an exact match, then don't do the regexp + if (read_buffer !== client_unix.expect) { + assert.ok(read_buffer.match(client_unix.expect)); + common.error('match'); + } + read_buffer = ''; + if (client_unix.list && client_unix.list.length > 0) { + send_expect(client_unix.list); + } else { + common.error('End of Error test, running TCP test.'); + tcp_test(); + } + + } else if (read_buffer.indexOf(prompt_multiline) !== -1) { + // Check that you meant to send a multiline test + assert.strictEqual(prompt_multiline, client_unix.expect); + read_buffer = ''; + if (client_unix.list && client_unix.list.length > 0) { + send_expect(client_unix.list); + } else { + common.error('End of Error test, running TCP test.\n'); + tcp_test(); + } + + } else { + common.error('didn\'t see prompt yet, buffering.'); + } + }); + + send_expect([ + // Uncaught error throws and prints out + { client: client_unix, send: 'throw new Error(\'test error\');', + expect: /^Error: test error/ }, + // Common syntax error is treated as multiline command + { client: client_unix, send: 'function test_func() {', + expect: prompt_multiline }, + // You can recover with the .break command + { client: client_unix, send: '.break', + expect: prompt_unix }, + // Can parse valid JSON + { client: client_unix, send: 'JSON.parse(\'{"valid": "json"}\');', + expect: '{ valid: \'json\' }'}, + // invalid input to JSON.parse error is special case of syntax error, + // should throw + { client: client_unix, send: 'JSON.parse(\'{invalid: \\\'json\\\'}\');', + expect: /^SyntaxError: Unexpected token i/ }, + // end of input to JSON.parse error is special case of syntax error, + // should throw + { client: client_unix, send: 'JSON.parse(\'{\');', + expect: /^SyntaxError: Unexpected end of input/ }, + // invalid RegExps are a special case of syntax error, + // should throw + { client: client_unix, send: '/(/;', + expect: /^SyntaxError: Invalid regular expression\:/ }, + // invalid RegExp modifiers are a special case of syntax error, + // should throw (GH-4012) + { client: client_unix, send: 'new RegExp("foo", "wrong modifier");', + expect: /^SyntaxError: Invalid flags supplied to RegExp constructor/ }, + // Named functions can be used: + { client: client_unix, send: 'function blah() { return 1; }', + expect: prompt_unix }, + { client: client_unix, send: 'blah()', + expect: '1\n' + prompt_unix }, + // Functions should not evaluate twice (#2773) + { client: client_unix, send: 'var I = [1,2,3,function() {}]; I.pop()', + expect: '[Function]' }, + // Multiline object + { client: client_unix, send: '{ a: ', + expect: prompt_multiline }, + { client: client_unix, send: '1 }', + expect: '{ a: 1 }' }, + // Multiline anonymous function with comment + { client: client_unix, send: '(function () {', + expect: prompt_multiline }, + { client: client_unix, send: '// blah', + expect: prompt_multiline }, + { client: client_unix, send: 'return 1;', + expect: prompt_multiline }, + { client: client_unix, send: '})()', + expect: '1' }, + // npm prompt error message + { client: client_unix, send: 'npm install foobar', + expect: expect_npm }, + { client: client_unix, send: '(function () {\n\nreturn 1;\n})()', + expect: '1' }, + { client: client_unix, send: '{\n\na: 1\n}', + expect: '{ a: 1 }' } + ]); +} + +function tcp_test() { + server_tcp = net.createServer(function(socket) { + assert.strictEqual(server_tcp, socket.server); + + socket.on('end', function() { + socket.end(); + }); + + repl.start(prompt_tcp, socket); + }); + + server_tcp.listen(common.PORT, function() { + var read_buffer = ''; + + client_tcp = net.createConnection(common.PORT); + + client_tcp.on('connect', function() { + assert.equal(true, client_tcp.readable); + assert.equal(true, client_tcp.writable); + + send_expect([ + { client: client_tcp, send: '', + expect: prompt_tcp }, + { client: client_tcp, send: 'invoke_me(333)', + expect: ('\'' + 'invoked 333' + '\'\n' + prompt_tcp) }, + { client: client_tcp, send: 'a += 1', + expect: ('12346' + '\n' + prompt_tcp) }, + { client: client_tcp, + send: 'require(' + JSON.stringify(moduleFilename) + ').number', + expect: ('42' + '\n' + prompt_tcp) } + ]); + }); + + client_tcp.on('data', function(data) { + read_buffer += data.toString('ascii', 0, data.length); + common.error('TCP data: ' + JSON.stringify(read_buffer) + + ', expecting ' + JSON.stringify(client_tcp.expect)); + if (read_buffer.indexOf(prompt_tcp) !== -1) { + assert.strictEqual(client_tcp.expect, read_buffer); + common.error('match'); + read_buffer = ''; + if (client_tcp.list && client_tcp.list.length > 0) { + send_expect(client_tcp.list); + } else { + common.error('End of TCP test.\n'); + clean_up(); + } + } else { + common.error('didn\'t see prompt yet, buffering'); + } + }); + + client_tcp.on('error', function(e) { + throw e; + }); + + client_tcp.on('close', function() { + server_tcp.close(); + }); + }); + +} + +function unix_test() { + server_unix = net.createServer(function(socket) { + assert.strictEqual(server_unix, socket.server); + + socket.on('end', function() { + socket.end(); + }); + + repl.start({ + prompt: prompt_unix, + input: socket, + output: socket, + useGlobal: true + }).context.message = message; + }); + + server_unix.on('listening', function() { + var read_buffer = ''; + + client_unix = net.createConnection(common.PIPE); + + client_unix.on('connect', function() { + assert.equal(true, client_unix.readable); + assert.equal(true, client_unix.writable); + + send_expect([ + { client: client_unix, send: '', + expect: prompt_unix }, + { client: client_unix, send: 'message', + expect: ('\'' + message + '\'\n' + prompt_unix) }, + { client: client_unix, send: 'invoke_me(987)', + expect: ('\'' + 'invoked 987' + '\'\n' + prompt_unix) }, + { client: client_unix, send: 'a = 12345', + expect: ('12345' + '\n' + prompt_unix) }, + { client: client_unix, send: '{a:1}', + expect: ('{ a: 1 }' + '\n' + prompt_unix) } + ]); + }); + + client_unix.on('data', function(data) { + read_buffer += data.toString('ascii', 0, data.length); + common.error('Unix data: ' + JSON.stringify(read_buffer) + + ', expecting ' + JSON.stringify(client_unix.expect)); + if (read_buffer.indexOf(prompt_unix) !== -1) { + assert.strictEqual(client_unix.expect, read_buffer); + common.error('match'); + read_buffer = ''; + if (client_unix.list && client_unix.list.length > 0) { + send_expect(client_unix.list); + } else { + common.error('End of Unix test, running Error test.\n'); + process.nextTick(error_test); + } + } else { + common.error('didn\'t see prompt yet, buffering.'); + } + }); + + client_unix.on('error', function(e) { + throw e; + }); + + client_unix.on('close', function() { + server_unix.close(); + }); + }); + + server_unix.listen(common.PIPE); +} + +unix_test(); + +timer = setTimeout(function() { + assert.fail('Timeout'); +}, 5000); diff --git a/node-v0.8.14/test/simple/test-require-cache-without-stat.js b/node-v0.8.14/test/simple/test-require-cache-without-stat.js new file mode 100644 index 0000000..c2c6c06 --- /dev/null +++ b/node-v0.8.14/test/simple/test-require-cache-without-stat.js @@ -0,0 +1,72 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// We've experienced a regression where the module loader stats a bunch of +// directories on require() even if it's been called before. The require() +// should caching the request. +var common = require('../common'); +var fs = require('fs'); +var assert = require('assert'); + +var counter = 0; + +// Switch out the two stat implementations so that they increase a counter +// each time they are called. + +var _statSync = fs.statSync; +var _stat = fs.stat; + +fs.statSync = function() { + counter++; + return _statSync.apply(this, arguments); +}; + +fs.stat = function() { + counter++; + return _stat.apply(this, arguments); +}; + +// Load the module 'a' and 'http' once. It should become cached. +require(common.fixturesDir + '/a'); +require('../fixtures/a.js'); +require('./../fixtures/a.js'); +require('http'); + +console.log('counterBefore = %d', counter); +var counterBefore = counter; + +// Now load the module a bunch of times with equivalent paths. +// stat should not be called. +for (var i = 0; i < 100; i++) { + require(common.fixturesDir + '/a'); + require('../fixtures/a.js'); + require('./../fixtures/a.js'); +} + +// Do the same with a built-in module +for (var i = 0; i < 100; i++) { + require('http'); +} + +console.log('counterAfter = %d', counter); +var counterAfter = counter; + +assert.equal(counterBefore, counterAfter); diff --git a/node-v0.8.14/test/simple/test-require-cache.js b/node-v0.8.14/test/simple/test-require-cache.js new file mode 100644 index 0000000..2f81204 --- /dev/null +++ b/node-v0.8.14/test/simple/test-require-cache.js @@ -0,0 +1,43 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); + +(function testInjectFakeModule() { + var relativePath = '../fixtures/semicolon'; + var absolutePath = require.resolve(relativePath); + var fakeModule = {}; + + require.cache[absolutePath] = {exports: fakeModule}; + + assert.strictEqual(require(relativePath), fakeModule); +})(); + + +(function testInjectFakeNativeModule() { + var relativePath = 'fs'; + var fakeModule = {}; + + require.cache[relativePath] = {exports: fakeModule}; + + assert.strictEqual(require(relativePath), fakeModule); +})(); diff --git a/node-v0.8.14/test/simple/test-require-exceptions.js b/node-v0.8.14/test/simple/test-require-exceptions.js new file mode 100644 index 0000000..307e3e2 --- /dev/null +++ b/node-v0.8.14/test/simple/test-require-exceptions.js @@ -0,0 +1,42 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); + +// A module with an error in it should throw +assert.throws(function() { + require(common.fixturesDir + '/throws_error'); +}); + +// Requiring the same module again should throw as well +assert.throws(function() { + require(common.fixturesDir + '/throws_error'); +}); + +// Requiring a module that does not exist should throw an +// error with its `code` set to MODULE_NOT_FOUND +assert.throws(function() { + require(common.fixturesDir + '/DOES_NOT_EXIST'); +}, function(e) { + assert.equal('MODULE_NOT_FOUND', e.code); + return true; +}); diff --git a/node-v0.8.14/test/simple/test-require-json.js b/node-v0.8.14/test/simple/test-require-json.js new file mode 100644 index 0000000..59b1e3d --- /dev/null +++ b/node-v0.8.14/test/simple/test-require-json.js @@ -0,0 +1,30 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var assert = require('assert'); + +try { + require('../fixtures/invalid.json'); +} catch (err) { + var re = /test[\/\\]fixtures[\/\\]invalid.json: Unexpected string/; + var i = err.message.match(re); + assert(null !== i, 'require() json error should include path'); +} diff --git a/node-v0.8.14/test/simple/test-require-resolve.js b/node-v0.8.14/test/simple/test-require-resolve.js new file mode 100644 index 0000000..1e4ff7f --- /dev/null +++ b/node-v0.8.14/test/simple/test-require-resolve.js @@ -0,0 +1,35 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var fixturesDir = common.fixturesDir; +var assert = require('assert'); +var path = require('path'); + +assert.equal(path.join(__dirname, '../fixtures/a.js'), + require.resolve('../fixtures/a')); +assert.equal(path.join(fixturesDir, 'a.js'), + require.resolve(path.join(fixturesDir, 'a'))); +assert.equal(path.join(fixturesDir, 'nested-index', 'one', 'index.js'), + require.resolve('../fixtures/nested-index/one')); +assert.equal('path', require.resolve('path')); + +console.log('ok'); diff --git a/node-v0.8.14/test/simple/test-script-context.js b/node-v0.8.14/test/simple/test-script-context.js new file mode 100644 index 0000000..f29af23 --- /dev/null +++ b/node-v0.8.14/test/simple/test-script-context.js @@ -0,0 +1,71 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); + +var vm = require('vm'); +var Script = vm.Script; +var script = new Script('"passed";'); + +common.debug('run in a new empty context'); +var context = script.createContext(); +var result = script.runInContext(context); +assert.equal('passed', result); + +common.debug('create a new pre-populated context'); +context = script.createContext({'foo': 'bar', 'thing': 'lala'}); +assert.equal('bar', context.foo); +assert.equal('lala', context.thing); + +common.debug('test updating context'); +script = new Script('foo = 3;'); +result = script.runInContext(context); +assert.equal(3, context.foo); +assert.equal('lala', context.thing); + + +// Issue GH-227: +Script.runInNewContext('', null, 'some.js'); + +// Issue GH-1140: +common.debug('test runInContext signature'); +var gh1140Exception; +try { + Script.runInContext('throw new Error()', context, 'expected-filename.js'); +} +catch (e) { + gh1140Exception = e; + assert.ok(/expected-filename/.test(e.stack), + 'expected appearance of filename in Error stack'); +} +assert.ok(gh1140Exception, + 'expected exception from runInContext signature test'); + +// GH-558, non-context argument segfaults / raises assertion +function isTypeError(o) { + return o instanceof TypeError; +} + +([undefined, null, 0, 0.0, '', {}, []].forEach(function(e) { + assert.throws(function() { script.runInContext(e); }, isTypeError); + assert.throws(function() { vm.runInContext('', e); }, isTypeError); +})); diff --git a/node-v0.8.14/test/simple/test-script-new.js b/node-v0.8.14/test/simple/test-script-new.js new file mode 100644 index 0000000..7894bb9 --- /dev/null +++ b/node-v0.8.14/test/simple/test-script-new.js @@ -0,0 +1,93 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var Script = require('vm').Script; + +common.globalCheck = false; + +common.debug('run a string'); +var script = new Script('\'passed\';'); +common.debug('script created'); +var result1 = script.runInNewContext(); +var result2 = script.runInNewContext(); +assert.equal('passed', result1); +assert.equal('passed', result2); + +common.debug('thrown error'); +script = new Script('throw new Error(\'test\');'); +assert.throws(function() { + script.runInNewContext(); +}); + + + +common.debug('undefined reference'); +var error; +script = new Script('foo.bar = 5;'); +try { + script.runInNewContext(); +} catch (e) { + error = e; +} +assert.ok(error); +assert.ok(error.message.indexOf('not defined') >= 0); + +common.debug('error.message: ' + error.message); + + +hello = 5; +script = new Script('hello = 2'); +script.runInNewContext(); +assert.equal(5, hello); + + +common.debug('pass values in and out'); +code = 'foo = 1;' + + 'bar = 2;' + + 'if (baz !== 3) throw new Error(\'test fail\');'; +foo = 2; +obj = { foo: 0, baz: 3 }; +script = new Script(code); +var baz = script.runInNewContext(obj); +assert.equal(1, obj.foo); +assert.equal(2, obj.bar); +assert.equal(2, foo); + +common.debug('call a function by reference'); +script = new Script('f()'); +function changeFoo() { foo = 100 } +script.runInNewContext({ f: changeFoo }); +assert.equal(foo, 100); + +common.debug('modify an object by reference'); +script = new Script('f.a = 2'); +var f = { a: 1 }; +script.runInNewContext({ f: f }); +assert.equal(f.a, 2); + +common.debug('invalid this'); +assert.throws(function() { + script.runInNewContext.call('\'hello\';'); +}); + + diff --git a/node-v0.8.14/test/simple/test-script-static-context.js b/node-v0.8.14/test/simple/test-script-static-context.js new file mode 100644 index 0000000..d2cb701 --- /dev/null +++ b/node-v0.8.14/test/simple/test-script-static-context.js @@ -0,0 +1,40 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); + +var Script = require('vm').Script; + +common.debug('run in a new empty context'); +var context = Script.createContext(); +var result = Script.runInContext('"passed";', context); +assert.equal('passed', result); + +common.debug('create a new pre-populated context'); +context = Script.createContext({'foo': 'bar', 'thing': 'lala'}); +assert.equal('bar', context.foo); +assert.equal('lala', context.thing); + +common.debug('test updating context'); +result = Script.runInContext('var foo = 3;', context); +assert.equal(3, context.foo); +assert.equal('lala', context.thing); diff --git a/node-v0.8.14/test/simple/test-script-static-new.js b/node-v0.8.14/test/simple/test-script-static-new.js new file mode 100644 index 0000000..eaac2d9 --- /dev/null +++ b/node-v0.8.14/test/simple/test-script-static-new.js @@ -0,0 +1,62 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var Script = require('vm').Script; + +common.globalCheck = false; + +common.debug('run a string'); +var result = Script.runInNewContext('\'passed\';'); +assert.equal('passed', result); + +common.debug('thrown error'); +assert.throws(function() { + Script.runInNewContext('throw new Error(\'test\');'); +}); + +hello = 5; +Script.runInNewContext('hello = 2'); +assert.equal(5, hello); + + +common.debug('pass values in and out'); +code = 'foo = 1;' + + 'bar = 2;' + + 'if (baz !== 3) throw new Error(\'test fail\');'; +foo = 2; +obj = { foo: 0, baz: 3 }; +var baz = Script.runInNewContext(code, obj); +assert.equal(1, obj.foo); +assert.equal(2, obj.bar); +assert.equal(2, foo); + +common.debug('call a function by reference'); +function changeFoo() { foo = 100 } +Script.runInNewContext('f()', { f: changeFoo }); +assert.equal(foo, 100); + +common.debug('modify an object by reference'); +var f = { a: 1 }; +Script.runInNewContext('f.a = 2', { f: f }); +assert.equal(f.a, 2); + diff --git a/node-v0.8.14/test/simple/test-script-static-this.js b/node-v0.8.14/test/simple/test-script-static-this.js new file mode 100644 index 0000000..63c1133 --- /dev/null +++ b/node-v0.8.14/test/simple/test-script-static-this.js @@ -0,0 +1,56 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var Script = require('vm').Script; + +common.globalCheck = false; + +common.debug('run a string'); +var result = Script.runInThisContext('\'passed\';'); +assert.equal('passed', result); + +common.debug('thrown error'); +assert.throws(function() { + Script.runInThisContext('throw new Error(\'test\');'); +}); + +hello = 5; +Script.runInThisContext('hello = 2'); +assert.equal(2, hello); + + +common.debug('pass values'); +code = 'foo = 1;' + + 'bar = 2;' + + 'if (typeof baz !== \'undefined\') throw new Error(\'test fail\');'; +foo = 2; +obj = { foo: 0, baz: 3 }; +var baz = Script.runInThisContext(code); +assert.equal(0, obj.foo); +assert.equal(2, bar); +assert.equal(1, foo); + +common.debug('call a function'); +f = function() { foo = 100 }; +Script.runInThisContext('f()'); +assert.equal(100, foo); diff --git a/node-v0.8.14/test/simple/test-script-this.js b/node-v0.8.14/test/simple/test-script-this.js new file mode 100644 index 0000000..a55a490 --- /dev/null +++ b/node-v0.8.14/test/simple/test-script-this.js @@ -0,0 +1,61 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var Script = require('vm').Script; + +common.globalCheck = false; + +common.debug('run a string'); +var script = new Script('\'passed\';'); +var result = script.runInThisContext(script); +assert.equal('passed', result); + +common.debug('thrown error'); +script = new Script('throw new Error(\'test\');'); +assert.throws(function() { + script.runInThisContext(script); +}); + +hello = 5; +script = new Script('hello = 2'); +script.runInThisContext(script); +assert.equal(2, hello); + + +common.debug('pass values'); +code = 'foo = 1;' + + 'bar = 2;' + + 'if (typeof baz !== \'undefined\') throw new Error(\'test fail\');'; +foo = 2; +obj = { foo: 0, baz: 3 }; +script = new Script(code); +script.runInThisContext(script); +assert.equal(0, obj.foo); +assert.equal(2, bar); +assert.equal(1, foo); + +common.debug('call a function'); +f = function() { foo = 100 }; +script = new Script('f()'); +script.runInThisContext(script); +assert.equal(100, foo); diff --git a/node-v0.8.14/test/simple/test-setproctitle.js b/node-v0.8.14/test/simple/test-setproctitle.js new file mode 100644 index 0000000..7ae1382 --- /dev/null +++ b/node-v0.8.14/test/simple/test-setproctitle.js @@ -0,0 +1,45 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// Original test written by Jakub Lekstan + +// FIXME add sunos support +if ('linux freebsd'.indexOf(process.platform) === -1) { + console.error('Skipping test, platform not supported.'); + process.exit(); +} + +var common = require('../common'); +var assert = require('assert'); +var exec = require('child_process').exec; + +var title = 'testTestTESTtest123123123123123123HiHaiJo'; + +assert.notEqual(process.title, title); +process.title = title; +assert.equal(process.title, title); + +exec('ps -p ' + process.pid + ' -o args=', function(error, stdout, stderr) { + assert.equal(error, null); + assert.equal(stderr, ''); + // omitting trailing whitespace and \n + assert.equal(stdout.replace(/\s+$/, ''), title); +}); diff --git a/node-v0.8.14/test/simple/test-sigint-infinite-loop.js b/node-v0.8.14/test/simple/test-sigint-infinite-loop.js new file mode 100644 index 0000000..4ff2745 --- /dev/null +++ b/node-v0.8.14/test/simple/test-sigint-infinite-loop.js @@ -0,0 +1,61 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + + + +// This test is to assert that we can SIGINT a script which loops forever. +// Ref(http): +// groups.google.com/group/nodejs-dev/browse_thread/thread/e20f2f8df0296d3f +var common = require('../common'); +var assert = require('assert'); +var spawn = require('child_process').spawn; + +console.log('start'); + +var c = spawn(process.execPath, ['-e', 'while(true) { console.log("hi"); }']); + +var sentKill = false; +var gotChildExit = true; + +c.stdout.on('data', function(s) { + // Prevent race condition: + // Wait for the first bit of output from the child process + // so that we're sure that it's in the V8 event loop and not + // just in the startup phase of execution. + if (!sentKill) { + c.kill('SIGINT'); + console.log('SIGINT infinite-loop.js'); + sentKill = true; + } +}); + +c.on('exit', function(code) { + assert.ok(code !== 0); + console.log('killed infinite-loop.js'); + gotChildExit = true; +}); + +process.on('exit', function() { + assert.ok(sentKill); + assert.ok(gotChildExit); +}); + diff --git a/node-v0.8.14/test/simple/test-signal-handler.js b/node-v0.8.14/test/simple/test-signal-handler.js new file mode 100644 index 0000000..5531e2f --- /dev/null +++ b/node-v0.8.14/test/simple/test-signal-handler.js @@ -0,0 +1,71 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + +// SIGUSR1 and SIGHUP are not supported on Windows +if (process.platform === 'win32') { + process.exit(0); +} + +var common = require('../common'); +var assert = require('assert'); + +console.log('process.pid: ' + process.pid); + +var first = 0, + second = 0; + +var sighup = false; + +process.on('SIGUSR1', function() { + console.log('Interrupted by SIGUSR1'); + first += 1; +}); + +process.on('SIGUSR1', function() { + second += 1; + setTimeout(function() { + console.log('End.'); + process.exit(0); + }, 5); +}); + +var i = 0; +setInterval(function() { + console.log('running process...' + ++i); + + if (i == 5) { + process.kill(process.pid, 'SIGUSR1'); + } +}, 1); + +// Test on condition where a watcher for SIGNAL +// has been previously registered, and `process.listeners(SIGNAL).length === 1` +process.on('SIGHUP', function() {}); +process.removeAllListeners('SIGHUP'); +process.on('SIGHUP', function() { sighup = true }); +process.kill(process.pid, 'SIGHUP'); + +process.on('exit', function() { + assert.equal(1, first); + assert.equal(1, second); + assert.equal(true, sighup); +}); diff --git a/node-v0.8.14/test/simple/test-signal-unregister.js b/node-v0.8.14/test/simple/test-signal-unregister.js new file mode 100644 index 0000000..d65e0a0 --- /dev/null +++ b/node-v0.8.14/test/simple/test-signal-unregister.js @@ -0,0 +1,56 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + + + +var common = require('../common'); +var assert = require('assert'); + +var childKilled = false, done = false, + spawn = require('child_process').spawn, + util = require('util'), + child; + +var join = require('path').join; + +child = spawn(process.argv[0], [join(common.fixturesDir, 'should_exit.js')]); +child.on('exit', function() { + if (!done) childKilled = true; +}); + +setTimeout(function() { + console.log('Sending SIGINT'); + child.kill('SIGINT'); + setTimeout(function() { + console.log('Chance has been given to die'); + done = true; + if (!childKilled) { + // Cleanup + console.log('Child did not die on SIGINT, sending SIGTERM'); + child.kill('SIGTERM'); + } + }, 200); +}, 200); + +process.on('exit', function() { + assert.ok(childKilled); +}); diff --git a/node-v0.8.14/test/simple/test-stdin-child-proc.js b/node-v0.8.14/test/simple/test-stdin-child-proc.js new file mode 100644 index 0000000..6a4ea94 --- /dev/null +++ b/node-v0.8.14/test/simple/test-stdin-child-proc.js @@ -0,0 +1,28 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// This tests that pausing and resuming stdin does not hang and timeout +// when done in a child process. See test/simple/test-stdin-pause-resume.js +var common = require('../common'); +var child_process = require('child_process'); +var path = require('path'); +child_process.spawn(process.execPath, + [path.resolve(__dirname, 'test-stdin-pause-resume.js')]); diff --git a/node-v0.8.14/test/simple/test-stdin-from-file.js b/node-v0.8.14/test/simple/test-stdin-from-file.js new file mode 100644 index 0000000..9c2ddfd --- /dev/null +++ b/node-v0.8.14/test/simple/test-stdin-from-file.js @@ -0,0 +1,65 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + + + +var common = require('../common'); +var assert = require('assert'); +var join = require('path').join; +var childProccess = require('child_process'); +var fs = require('fs'); + +var stdoutScript = join(common.fixturesDir, 'echo.js'); +var tmpFile = join(common.fixturesDir, 'stdin.txt'); + +var cmd = '"' + process.argv[0] + '" "' + stdoutScript + '" < "' + + tmpFile + '"'; + +var string = 'abc\nümlaut.\nsomething else\n' + + '南越国是前203年至前111年存在于岭南地区的一个国家,国都位于番禺,' + + '疆域包括今天中国的广东、广西两省区的大部份地区,福建省、湖南、贵州、' + + '云南的一小部份地区和越南的北部。南越国是秦朝灭亡后,' + + '由南海郡尉赵佗于前203年起兵兼并桂林郡和象郡后建立。前196年和前179年,' + + '南越国曾先后两次名义上臣属于西汉,成为西汉的“外臣”。前112年,' + + '南越国末代君主赵建德与西汉发生战争,被汉武帝于前111年所灭。南越国共存在93年,' + + '历经五代君主。南越国是岭南地区的第一个有记载的政权国家,' + + '采用封建制和郡县制并存的制度,' + + '它的建立保证了秦末乱世岭南地区社会秩序的稳定,' + + '有效的改善了岭南地区落后的政治、##济现状。\n'; + + +console.log(cmd + '\n\n'); + +try { + fs.unlinkSync(tmpFile); +} catch (e) {} + +fs.writeFileSync(tmpFile, string); + +childProccess.exec(cmd, function(err, stdout, stderr) { + fs.unlinkSync(tmpFile); + + if (err) throw err; + console.log(stdout); + assert.equal(stdout, 'hello world\r\n' + string); + assert.equal('', stderr); +}); diff --git a/node-v0.8.14/test/simple/test-stdin-hang.js b/node-v0.8.14/test/simple/test-stdin-hang.js new file mode 100644 index 0000000..1edbf8c --- /dev/null +++ b/node-v0.8.14/test/simple/test-stdin-hang.js @@ -0,0 +1,31 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); + +// This test *only* verifies that invoking the stdin getter does not +// cause node to hang indefinitely. +// If it does, then the test-runner will nuke it. + +// invoke the getter. +process.stdin; + +console.error('Should exit normally now.'); diff --git a/node-v0.8.14/test/simple/test-stdin-pause-resume-sync.js b/node-v0.8.14/test/simple/test-stdin-pause-resume-sync.js new file mode 100644 index 0000000..0e202a3 --- /dev/null +++ b/node-v0.8.14/test/simple/test-stdin-pause-resume-sync.js @@ -0,0 +1,31 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +console.error('before opening stdin'); +process.stdin.resume(); +console.error('stdin opened'); +console.error('pausing stdin'); +process.stdin.pause(); +console.error('opening again'); +process.stdin.resume(); +console.error('pausing again'); +process.stdin.pause(); +console.error('should exit now'); diff --git a/node-v0.8.14/test/simple/test-stdin-pause-resume.js b/node-v0.8.14/test/simple/test-stdin-pause-resume.js new file mode 100644 index 0000000..fed5d66 --- /dev/null +++ b/node-v0.8.14/test/simple/test-stdin-pause-resume.js @@ -0,0 +1,37 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +console.error('before opening stdin'); +process.stdin.resume(); +console.error('stdin opened'); +setTimeout(function() { + console.error('pausing stdin'); + process.stdin.pause(); + setTimeout(function() { + console.error('opening again'); + process.stdin.resume(); + setTimeout(function() { + console.error('pausing again'); + process.stdin.pause(); + console.error('should exit now'); + }, 1); + }, 1); +}, 1); diff --git a/node-v0.8.14/test/simple/test-stdin-pipe-resume.js b/node-v0.8.14/test/simple/test-stdin-pipe-resume.js new file mode 100644 index 0000000..163d836 --- /dev/null +++ b/node-v0.8.14/test/simple/test-stdin-pipe-resume.js @@ -0,0 +1,48 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// This tests that piping stdin will cause it to resume() as well. +var common = require('../common'); +var assert = require('assert'); + +if (process.argv[2] === 'child') { + process.stdin.pipe(process.stdout); +} else { + var spawn = require('child_process').spawn; + var buffers = []; + var child = spawn(process.execPath, [__filename, 'child']); + child.stdout.on('data', function(c) { + buffers.push(c); + }); + child.stdout.on('close', function() { + var b = Buffer.concat(buffers).toString(); + assert.equal(b, 'Hello, world\n'); + console.log('ok'); + }); + child.stdin.write('Hel'); + child.stdin.write('lo,'); + child.stdin.write(' wo'); + setTimeout(function() { + child.stdin.write('rld\n'); + child.stdin.end(); + }, 10); +} + diff --git a/node-v0.8.14/test/simple/test-stdin-resume-pause.js b/node-v0.8.14/test/simple/test-stdin-resume-pause.js new file mode 100644 index 0000000..2d2af2f --- /dev/null +++ b/node-v0.8.14/test/simple/test-stdin-resume-pause.js @@ -0,0 +1,23 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +process.stdin.resume(); +process.stdin.pause(); diff --git a/node-v0.8.14/test/simple/test-stdout-close-catch.js b/node-v0.8.14/test/simple/test-stdout-close-catch.js new file mode 100644 index 0000000..f517a6c --- /dev/null +++ b/node-v0.8.14/test/simple/test-stdout-close-catch.js @@ -0,0 +1,56 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + +var common = require('../common'); +var assert = require('assert'); +var path = require('path'); +var child_process = require('child_process'); +var fs = require('fs'); + +var testScript = path.join(common.fixturesDir, 'catch-stdout-error.js'); + +var cmd = JSON.stringify(process.execPath) + ' ' + + JSON.stringify(testScript) + ' | ' + + JSON.stringify(process.execPath) + ' ' + + '-pe "process.exit(1);"'; + +var child = child_process.exec(cmd); +var output = ''; +var outputExpect = { 'code': 'EPIPE', + 'errno': 'EPIPE', + 'syscall': 'write' }; + +child.stderr.on('data', function(c) { + output += c; +}); + +child.on('close', function(code) { + try { + output = JSON.parse(output); + } catch (er) { + console.error(output); + process.exit(1); + } + + assert.deepEqual(output, outputExpect); + console.log('ok'); +}); diff --git a/node-v0.8.14/test/simple/test-stdout-to-file.js b/node-v0.8.14/test/simple/test-stdout-to-file.js new file mode 100644 index 0000000..83ea4f0 --- /dev/null +++ b/node-v0.8.14/test/simple/test-stdout-to-file.js @@ -0,0 +1,77 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + + + +var common = require('../common'); +var assert = require('assert'); +var path = require('path'); +var childProccess = require('child_process'); +var fs = require('fs'); + +var scriptString = path.join(common.fixturesDir, 'print-chars.js'); +var scriptBuffer = path.join(common.fixturesDir, 'print-chars-from-buffer.js'); +var tmpFile = path.join(common.fixturesDir, 'stdout.txt'); + +function test(size, useBuffer, cb) { + var cmd = '"' + process.argv[0] + '"' + + ' ' + + '"' + (useBuffer ? scriptBuffer : scriptString) + '"' + + ' ' + + size + + ' > ' + + '"' + tmpFile + '"'; + + try { + fs.unlinkSync(tmpFile); + } catch (e) {} + + common.print(size + ' chars to ' + tmpFile + '...'); + + childProccess.exec(cmd, function(err) { + if (err) throw err; + + console.log('done!'); + + var stat = fs.statSync(tmpFile); + + console.log(tmpFile + ' has ' + stat.size + ' bytes'); + + assert.equal(size, stat.size); + fs.unlinkSync(tmpFile); + + cb(); + }); +} + +var finished = false; +test(1024 * 1024, false, function() { + console.log('Done printing with string'); + test(1024 * 1024, true, function() { + console.log('Done printing with buffer'); + finished = true; + }); +}); + +process.on('exit', function() { + assert.ok(finished); +}); diff --git a/node-v0.8.14/test/simple/test-stream-pipe-cleanup.js b/node-v0.8.14/test/simple/test-stream-pipe-cleanup.js new file mode 100644 index 0000000..5a72a48 --- /dev/null +++ b/node-v0.8.14/test/simple/test-stream-pipe-cleanup.js @@ -0,0 +1,96 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// This test asserts that Stream.prototype.pipe does not leave listeners +// hanging on the source or dest. + +var common = require('../common'); +var stream = require('stream'); +var assert = require('assert'); +var util = require('util'); + +function Writable() { + this.writable = true; + this.endCalls = 0; + stream.Stream.call(this); +} +util.inherits(Writable, stream.Stream); +Writable.prototype.end = function() { + this.endCalls++; +}; + +Writable.prototype.destroy = function() { + this.endCalls++; +}; + +function Readable() { + this.readable = true; + stream.Stream.call(this); +} +util.inherits(Readable, stream.Stream); + +var i = 0; +var limit = 100; + +var w = new Writable(); + +console.error = function(text) { + throw new Error(text); +}; + +var r; + +for (i = 0; i < limit; i++) { + r = new Readable(); + r.pipe(w); + r.emit('end'); +} +assert.equal(0, r.listeners('end').length); +assert.equal(limit, w.endCalls); + +w.endCalls = 0; + +for (i = 0; i < limit; i++) { + r = new Readable(); + r.pipe(w); + r.emit('close'); +} +assert.equal(0, r.listeners('close').length); +assert.equal(limit, w.endCalls); + +w.endCalls = 0; + +r = new Readable(); + +for (i = 0; i < limit; i++) { + w = new Writable(); + r.pipe(w); + w.emit('end'); +} +assert.equal(0, w.listeners('end').length); + +for (i = 0; i < limit; i++) { + w = new Writable(); + r.pipe(w); + w.emit('close'); +} +assert.equal(0, w.listeners('close').length); + diff --git a/node-v0.8.14/test/simple/test-stream-pipe-error-handling.js b/node-v0.8.14/test/simple/test-stream-pipe-error-handling.js new file mode 100644 index 0000000..df81573 --- /dev/null +++ b/node-v0.8.14/test/simple/test-stream-pipe-error-handling.js @@ -0,0 +1,58 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var Stream = require('stream').Stream; + +(function testErrorListenerCatches() { + var source = new Stream(); + var dest = new Stream(); + + source.pipe(dest); + + var gotErr = null; + source.on('error', function(err) { + gotErr = err; + }); + + var err = new Error('This stream turned into bacon.'); + source.emit('error', err); + assert.strictEqual(gotErr, err); +})(); + +(function testErrorWithoutListenerThrows() { + var source = new Stream(); + var dest = new Stream(); + + source.pipe(dest); + + var err = new Error('This stream turned into bacon.'); + + var gotErr = null; + try { + source.emit('error', err); + } catch (e) { + gotErr = e; + } + + assert.strictEqual(gotErr, err); +})(); diff --git a/node-v0.8.14/test/simple/test-stream-pipe-event.js b/node-v0.8.14/test/simple/test-stream-pipe-event.js new file mode 100644 index 0000000..cb9d5fe --- /dev/null +++ b/node-v0.8.14/test/simple/test-stream-pipe-event.js @@ -0,0 +1,49 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var stream = require('stream'); +var assert = require('assert'); +var util = require('util'); + +function Writable() { + this.writable = true; + stream.Stream.call(this); +} +util.inherits(Writable, stream.Stream); + +function Readable() { + this.readable = true; + stream.Stream.call(this); +} +util.inherits(Readable, stream.Stream); + +var passed = false; + +var w = new Writable(); +w.on('pipe', function(src) { + passed = true; +}); + +var r = new Readable(); +r.pipe(w); + +assert.ok(passed); diff --git a/node-v0.8.14/test/simple/test-stream-pipe-multi.js b/node-v0.8.14/test/simple/test-stream-pipe-multi.js new file mode 100644 index 0000000..9a8535f --- /dev/null +++ b/node-v0.8.14/test/simple/test-stream-pipe-multi.js @@ -0,0 +1,121 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// Test that having a bunch of streams piping in parallel +// doesn't break anything. + +var common = require('../common'); +var assert = require('assert'); +var Stream = require('stream').Stream; +var rr = []; +var ww = []; +var cnt = 100; +var chunks = 1000; +var chunkSize = 250; +var data = new Buffer(chunkSize); +var wclosed = 0; +var rclosed = 0; + +function FakeStream() { + Stream.apply(this); + this.wait = false; + this.writable = true; + this.readable = true; +} + +FakeStream.prototype = Object.create(Stream.prototype); + +FakeStream.prototype.write = function(chunk) { + console.error(this.ID, 'write', this.wait); + if (this.wait) { + process.nextTick(this.emit.bind(this, 'drain')); + } + this.wait = !this.wait; + return this.wait; +}; + +FakeStream.prototype.end = function() { + this.emit('end'); + process.nextTick(this.close.bind(this)); +}; + +// noop - closes happen automatically on end. +FakeStream.prototype.close = function() { + this.emit('close'); +}; + + +// expect all streams to close properly. +process.on('exit', function() { + assert.equal(cnt, wclosed, 'writable streams closed'); + assert.equal(cnt, rclosed, 'readable streams closed'); +}); + +for (var i = 0; i < chunkSize; i++) { + chunkSize[i] = i % 256; +} + +for (var i = 0; i < cnt; i++) { + var r = new FakeStream(); + r.on('close', function() { + console.error(this.ID, 'read close'); + rclosed++; + }); + rr.push(r); + + var w = new FakeStream(); + w.on('close', function() { + console.error(this.ID, 'write close'); + wclosed++; + }); + ww.push(w); + + r.ID = w.ID = i; + r.pipe(w); +} + +// now start passing through data +// simulate a relatively fast async stream. +rr.forEach(function(r) { + var cnt = chunks; + var paused = false; + + r.on('pause', function() { + paused = true; + }); + + r.on('resume', function() { + paused = false; + step(); + }); + + function step() { + r.emit('data', data); + if (--cnt === 0) { + r.end(); + return; + } + if (paused) return; + process.nextTick(step); + } + + process.nextTick(step); +}); diff --git a/node-v0.8.14/test/simple/test-string-decoder.js b/node-v0.8.14/test/simple/test-string-decoder.js new file mode 100644 index 0000000..0da66f6 --- /dev/null +++ b/node-v0.8.14/test/simple/test-string-decoder.js @@ -0,0 +1,163 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var StringDecoder = require('string_decoder').StringDecoder; +var decoder = new StringDecoder('utf8'); + + + +var buffer = new Buffer('$'); +assert.deepEqual('$', decoder.write(buffer)); + +buffer = new Buffer('¢'); +assert.deepEqual('', decoder.write(buffer.slice(0, 1))); +assert.deepEqual('¢', decoder.write(buffer.slice(1, 2))); + +buffer = new Buffer('€'); +assert.deepEqual('', decoder.write(buffer.slice(0, 1))); +assert.deepEqual('', decoder.write(buffer.slice(1, 2))); +assert.deepEqual('€', decoder.write(buffer.slice(2, 3))); + +buffer = new Buffer([0xF0, 0xA4, 0xAD, 0xA2]); +var s = ''; +s += decoder.write(buffer.slice(0, 1)); +s += decoder.write(buffer.slice(1, 2)); +s += decoder.write(buffer.slice(2, 3)); +s += decoder.write(buffer.slice(3, 4)); +assert.ok(s.length > 0); + +// CESU-8 +buffer = new Buffer('EDA0BDEDB18D', 'hex'); // THUMBS UP SIGN (in CESU-8) +var s = ''; +s += decoder.write(buffer.slice(0, 1)); +s += decoder.write(buffer.slice(1, 2)); +s += decoder.write(buffer.slice(2, 3)); // complete lead surrogate +assert.equal(s, ''); +s += decoder.write(buffer.slice(3, 4)); +s += decoder.write(buffer.slice(4, 5)); +s += decoder.write(buffer.slice(5, 6)); // complete trail surrogate +assert.equal(s, '\uD83D\uDC4D'); // THUMBS UP SIGN (in UTF-16) + +var s = ''; +s += decoder.write(buffer.slice(0, 2)); +s += decoder.write(buffer.slice(2, 4)); // complete lead surrogate +assert.equal(s, ''); +s += decoder.write(buffer.slice(4, 6)); // complete trail surrogate +assert.equal(s, '\uD83D\uDC4D'); // THUMBS UP SIGN (in UTF-16) + +var s = ''; +s += decoder.write(buffer.slice(0, 3)); // complete lead surrogate +assert.equal(s, ''); +s += decoder.write(buffer.slice(3, 6)); // complete trail surrogate +assert.equal(s, '\uD83D\uDC4D'); // THUMBS UP SIGN (in UTF-16) + +var s = ''; +s += decoder.write(buffer.slice(0, 4)); // complete lead surrogate +assert.equal(s, ''); +s += decoder.write(buffer.slice(4, 5)); +s += decoder.write(buffer.slice(5, 6)); // complete trail surrogate +assert.equal(s, '\uD83D\uDC4D'); // THUMBS UP SIGN (in UTF-16) + +var s = ''; +s += decoder.write(buffer.slice(0, 5)); // complete lead surrogate +assert.equal(s, ''); +s += decoder.write(buffer.slice(5, 6)); // complete trail surrogate +assert.equal(s, '\uD83D\uDC4D'); // THUMBS UP SIGN (in UTF-16) + +var s = ''; +s += decoder.write(buffer.slice(0, 6)); +assert.equal(s, '\uD83D\uDC4D'); // THUMBS UP SIGN (in UTF-16) + + +// UCS-2 +decoder = new StringDecoder('ucs2'); +buffer = new Buffer('ab', 'ucs2'); +assert.equal(decoder.write(buffer), 'ab'); // 2 complete chars +buffer = new Buffer('abc', 'ucs2'); +assert.equal(decoder.write(buffer.slice(0, 3)), 'a'); // 'a' and first of 'b' +assert.equal(decoder.write(buffer.slice(3, 6)), 'bc'); // second of 'b' and 'c' + + +// UTF-16LE +buffer = new Buffer('3DD84DDC', 'hex'); // THUMBS UP SIGN (in CESU-8) +var s = ''; +s += decoder.write(buffer.slice(0, 1)); +s += decoder.write(buffer.slice(1, 2)); // complete lead surrogate +assert.equal(s, ''); +s += decoder.write(buffer.slice(2, 3)); +s += decoder.write(buffer.slice(3, 4)); // complete trail surrogate +assert.equal(s, '\uD83D\uDC4D'); // THUMBS UP SIGN (in UTF-16) + +var s = ''; +s += decoder.write(buffer.slice(0, 2)); // complete lead surrogate +assert.equal(s, ''); +s += decoder.write(buffer.slice(2, 4)); // complete trail surrogate +assert.equal(s, '\uD83D\uDC4D'); // THUMBS UP SIGN (in UTF-16) + +var s = ''; +s += decoder.write(buffer.slice(0, 3)); // complete lead surrogate +assert.equal(s, ''); +s += decoder.write(buffer.slice(3, 4)); // complete trail surrogate +assert.equal(s, '\uD83D\uDC4D'); // THUMBS UP SIGN (in UTF-16) + +var s = ''; +s += decoder.write(buffer.slice(0, 4)); +assert.equal(s, '\uD83D\uDC4D'); // THUMBS UP SIGN (in UTF-16) + + +// A mixed ascii and non-ascii string +// Test stolen from deps/v8/test/cctest/test-strings.cc +// U+02E4 -> CB A4 +// U+0064 -> 64 +// U+12E4 -> E1 8B A4 +// U+0030 -> 30 +// U+3045 -> E3 81 85 +var expected = '\u02e4\u0064\u12e4\u0030\u3045'; +var buffer = new Buffer([0xCB, 0xA4, 0x64, 0xE1, 0x8B, 0xA4, + 0x30, 0xE3, 0x81, 0x85]); +var charLengths = [0, 0, 1, 2, 2, 2, 3, 4, 4, 4, 5, 5]; + +// Split the buffer into 3 segments +// |----|------|-------| +// 0 i j buffer.length +// Scan through every possible 3 segment combination +// and make sure that the string is always parsed. +common.print('scanning '); +for (var j = 2; j < buffer.length; j++) { + for (var i = 1; i < j; i++) { + var decoder = new StringDecoder('utf8'); + + var sum = decoder.write(buffer.slice(0, i)); + + // just check that we've received the right amount + // after the first write + assert.equal(charLengths[i], sum.length); + + sum += decoder.write(buffer.slice(i, j)); + sum += decoder.write(buffer.slice(j, buffer.length)); + assert.equal(expected, sum); + common.print('.'); + } +} +console.log(' crayon!'); + diff --git a/node-v0.8.14/test/simple/test-sync-fileread.js b/node-v0.8.14/test/simple/test-sync-fileread.js new file mode 100644 index 0000000..428838a --- /dev/null +++ b/node-v0.8.14/test/simple/test-sync-fileread.js @@ -0,0 +1,32 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + + + +var common = require('../common'); +var assert = require('assert'); +var path = require('path'); +var fs = require('fs'); + +var fixture = path.join(__dirname, '../fixtures/x.txt'); + +assert.equal('xyz\n', fs.readFileSync(fixture)); diff --git a/node-v0.8.14/test/simple/test-sys.js b/node-v0.8.14/test/simple/test-sys.js new file mode 100644 index 0000000..6ea3316 --- /dev/null +++ b/node-v0.8.14/test/simple/test-sys.js @@ -0,0 +1,129 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); + +assert.equal('0', common.inspect(0)); +assert.equal('1', common.inspect(1)); +assert.equal('false', common.inspect(false)); +assert.equal("''", common.inspect('')); +assert.equal("'hello'", common.inspect('hello')); +assert.equal('[Function]', common.inspect(function() {})); +assert.equal('undefined', common.inspect(undefined)); +assert.equal('null', common.inspect(null)); +assert.equal('/foo(bar\\n)?/gi', common.inspect(/foo(bar\n)?/gi)); +assert.equal(new Date('2010-02-14T12:48:40+01:00').toString(), + common.inspect(new Date('Sun, 14 Feb 2010 11:48:40 GMT'))); + +assert.equal("'\\n\\u0001'", common.inspect('\n\u0001')); + +assert.equal('[]', common.inspect([])); +assert.equal('{}', common.inspect(Object.create([]))); +assert.equal('[ 1, 2 ]', common.inspect([1, 2])); +assert.equal('[ 1, [ 2, 3 ] ]', common.inspect([1, [2, 3]])); + +assert.equal('{}', common.inspect({})); +assert.equal('{ a: 1 }', common.inspect({a: 1})); +assert.equal('{ a: [Function] }', common.inspect({a: function() {}})); +assert.equal('{ a: 1, b: 2 }', common.inspect({a: 1, b: 2})); +assert.equal('{ a: {} }', common.inspect({'a': {}})); +assert.equal('{ a: { b: 2 } }', common.inspect({'a': {'b': 2}})); +assert.equal('{ a: { b: { c: [Object] } } }', + common.inspect({'a': {'b': { 'c': { 'd': 2 }}}})); +assert.equal('{ a: { b: { c: { d: 2 } } } }', + common.inspect({'a': {'b': { 'c': { 'd': 2 }}}}, false, null)); +assert.equal('[ 1, 2, 3, [length]: 3 ]', common.inspect([1, 2, 3], true)); +assert.equal('{ a: [Object] }', + common.inspect({'a': {'b': { 'c': 2}}}, false, 0)); +assert.equal('{ a: { b: [Object] } }', + common.inspect({'a': {'b': { 'c': 2}}}, false, 1)); +assert.equal('{ visible: 1 }', + common.inspect(Object.create({}, + {visible: {value: 1, enumerable: true}, hidden: {value: 2}})) +); + +// Due to the hash seed randomization it's not deterministic the order that +// the following ways this hash is displayed. +// See http://codereview.chromium.org/9124004/ + +var out = common.inspect(Object.create({}, + {visible: {value: 1, enumerable: true}, hidden: {value: 2}}), true); +if (out !== '{ [hidden]: 2, visible: 1 }' && + out !== '{ visible: 1, [hidden]: 2 }') { + assert.ok(false); +} + + +// Objects without prototype +var out = common.inspect(Object.create(null, + { name: {value: 'Tim', enumerable: true}, + hidden: {value: 'secret'}}), true); +if (out !== "{ [hidden]: 'secret', name: 'Tim' }" && + out !== "{ name: 'Tim', [hidden]: 'secret' }") { + assert(false); +} + + +assert.equal('{ name: \'Tim\' }', + common.inspect(Object.create(null, + {name: {value: 'Tim', enumerable: true}, + hidden: {value: 'secret'}})) +); + + +// Dynamic properties +assert.equal('{ readonly: [Getter] }', + common.inspect({get readonly() {}})); + +assert.equal('{ readwrite: [Getter/Setter] }', + common.inspect({get readwrite() {},set readwrite(val) {}})); + +assert.equal('{ writeonly: [Setter] }', + common.inspect({set writeonly(val) {}})); + +var value = {}; +value['a'] = value; +assert.equal('{ a: [Circular] }', common.inspect(value)); + +// Array with dynamic properties +value = [1, 2, 3]; +value.__defineGetter__('growingLength', function() { + this.push(true); return this.length; +}); +assert.equal('[ 1, 2, 3, growingLength: [Getter] ]', common.inspect(value)); + +// Function with properties +value = function() {}; +value.aprop = 42; +assert.equal('{ [Function] aprop: 42 }', common.inspect(value)); + +// Regular expressions with properties +value = /123/ig; +value.aprop = 42; +assert.equal('{ /123/gi aprop: 42 }', common.inspect(value)); + +// Dates with properties +value = new Date('Sun, 14 Feb 2010 11:48:40 GMT'); +value.aprop = 42; +assert.equal('{ Sun, 14 Feb 2010 11:48:40 GMT aprop: 42 }', + common.inspect(value) +); diff --git a/node-v0.8.14/test/simple/test-tcp-wrap-connect.js b/node-v0.8.14/test/simple/test-tcp-wrap-connect.js new file mode 100644 index 0000000..b8ac6aa --- /dev/null +++ b/node-v0.8.14/test/simple/test-tcp-wrap-connect.js @@ -0,0 +1,71 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var TCP = process.binding('tcp_wrap').TCP; + +function makeConnection() { + var client = new TCP(); + + var req = client.connect('127.0.0.1', common.PORT); + req.oncomplete = function(status, client_, req_) { + assert.equal(0, status); + assert.equal(client, client_); + assert.equal(req, req_); + + console.log('connected'); + var shutdownReq = client.shutdown(); + shutdownReq.oncomplete = function(status, client_, req_) { + console.log('shutdown complete'); + assert.equal(0, status); + assert.equal(client, client_); + assert.equal(shutdownReq, req_); + shutdownCount++; + client.close(); + }; + }; +} + +///// + +var connectCount = 0; +var endCount = 0; +var shutdownCount = 0; + +var server = require('net').Server(function(s) { + console.log('got connection'); + connectCount++; + s.on('end', function() { + console.log('got eof'); + endCount++; + s.destroy(); + server.close(); + }); +}); + +server.listen(common.PORT, makeConnection); + +process.on('exit', function() { + assert.equal(1, shutdownCount); + assert.equal(1, connectCount); + assert.equal(1, endCount); +}); diff --git a/node-v0.8.14/test/simple/test-tcp-wrap-listen.js b/node-v0.8.14/test/simple/test-tcp-wrap-listen.js new file mode 100644 index 0000000..a272a19 --- /dev/null +++ b/node-v0.8.14/test/simple/test-tcp-wrap-listen.js @@ -0,0 +1,116 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); + +var TCP = process.binding('tcp_wrap').TCP; + +var server = new TCP(); + +var r = server.bind('0.0.0.0', common.PORT); +assert.equal(0, r); + +server.listen(128); + +var slice, sliceCount = 0, eofCount = 0; + +var writeCount = 0; +var recvCount = 0; + +server.onconnection = function(client) { + assert.equal(0, client.writeQueueSize); + console.log('got connection'); + + function maybeCloseClient() { + if (client.pendingWrites.length == 0 && client.gotEOF) { + console.log('close client'); + client.close(); + } + } + + client.readStart(); + client.pendingWrites = []; + client.onread = function(buffer, offset, length) { + if (buffer) { + assert.ok(length > 0); + + assert.equal(0, client.writeQueueSize); + + var req = client.writeBuffer(buffer.slice(offset, offset + length)); + client.pendingWrites.push(req); + + console.log('client.writeQueueSize: ' + client.writeQueueSize); + // 11 bytes should flush + assert.equal(0, client.writeQueueSize); + + req.oncomplete = function(status, client_, req_) { + assert.equal(req, client.pendingWrites.shift()); + + // Check parameters. + assert.equal(0, status); + assert.equal(client, client_); + assert.equal(req, req_); + + console.log('client.writeQueueSize: ' + client.writeQueueSize); + assert.equal(0, client.writeQueueSize); + + writeCount++; + console.log('write ' + writeCount); + maybeCloseClient(); + }; + + sliceCount++; + } else { + console.log('eof'); + client.gotEOF = true; + server.close(); + eofCount++; + maybeCloseClient(); + } + }; +}; + +var net = require('net'); + +var c = net.createConnection(common.PORT); +c.on('connect', function() { + c.end('hello world'); +}); + +c.setEncoding('utf8'); +c.on('data', function(d) { + assert.equal('hello world', d); + recvCount++; +}); + +c.on('close', function() { + console.error('client closed'); +}); + +process.on('exit', function() { + assert.equal(1, sliceCount); + assert.equal(1, eofCount); + assert.equal(1, writeCount); + assert.equal(1, recvCount); +}); + + diff --git a/node-v0.8.14/test/simple/test-tcp-wrap.js b/node-v0.8.14/test/simple/test-tcp-wrap.js new file mode 100644 index 0000000..1e9e115 --- /dev/null +++ b/node-v0.8.14/test/simple/test-tcp-wrap.js @@ -0,0 +1,39 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); + +var TCP = process.binding('tcp_wrap').TCP; + +var handle = new TCP(); + +// Should be able to bind to the common.PORT +var r = handle.bind('0.0.0.0', common.PORT); +assert.equal(0, r); + +// Should not be able to bind to the same port again +var r = handle.bind('0.0.0.0', common.PORT); +assert.equal(-1, r); +console.log(errno); +assert.equal(errno, 'EINVAL'); + +handle.close(); diff --git a/node-v0.8.14/test/simple/test-timers-linked-list.js b/node-v0.8.14/test/simple/test-timers-linked-list.js new file mode 100644 index 0000000..0b6bf4b --- /dev/null +++ b/node-v0.8.14/test/simple/test-timers-linked-list.js @@ -0,0 +1,120 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var L = require('_linklist'); + + +var list = { name: 'list' }; +var A = { name: 'A' }; +var B = { name: 'B' }; +var C = { name: 'C' }; +var D = { name: 'D' }; + + +L.init(list); +L.init(A); +L.init(B); +L.init(C); +L.init(D); + +assert.ok(L.isEmpty(list)); +assert.equal(null, L.peek(list)); + +L.append(list, A); +// list -> A +assert.equal(A, L.peek(list)); + +L.append(list, B); +// list -> A -> B +assert.equal(A, L.peek(list)); + +L.append(list, C); +// list -> A -> B -> C +assert.equal(A, L.peek(list)); + +L.append(list, D); +// list -> A -> B -> C -> D +assert.equal(A, L.peek(list)); + +var x = L.shift(list); +assert.equal(A, x); +// list -> B -> C -> D +assert.equal(B, L.peek(list)); + +x = L.shift(list); +assert.equal(B, x); +// list -> C -> D +assert.equal(C, L.peek(list)); + +// B is already removed, so removing it again shouldn't hurt. +L.remove(B); +// list -> C -> D +assert.equal(C, L.peek(list)); + +// Put B back on the list +L.append(list, B); +// list -> C -> D -> B +assert.equal(C, L.peek(list)); + +L.remove(C); +// list -> D -> B +assert.equal(D, L.peek(list)); + +L.remove(B); +// list -> D +assert.equal(D, L.peek(list)); + +L.remove(D); +// list +assert.equal(null, L.peek(list)); + + +assert.ok(L.isEmpty(list)); + + +L.append(list, D); +// list -> D +assert.equal(D, L.peek(list)); + +L.append(list, C); +L.append(list, B); +L.append(list, A); +// list -> D -> C -> B -> A + +// Append should REMOVE C from the list and append it to the end. +L.append(list, C); + +// list -> D -> B -> A -> C +assert.equal(D, L.shift(list)); +// list -> B -> A -> C +assert.equal(B, L.peek(list)); +assert.equal(B, L.shift(list)); +// list -> A -> C +assert.equal(A, L.peek(list)); +assert.equal(A, L.shift(list)); +// list -> C +assert.equal(C, L.peek(list)); +assert.equal(C, L.shift(list)); +// list +assert.ok(L.isEmpty(list)); + diff --git a/node-v0.8.14/test/simple/test-timers-uncaught-exception.js b/node-v0.8.14/test/simple/test-timers-uncaught-exception.js new file mode 100644 index 0000000..0d2f488 --- /dev/null +++ b/node-v0.8.14/test/simple/test-timers-uncaught-exception.js @@ -0,0 +1,52 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); + +var exceptions = 0; +var timer1 = 0; +var timer2 = 0; + +// the first timer throws... +setTimeout(function() { + timer1++; + throw new Error('BAM!'); +}, 100); + +// ...but the second one should still run +setTimeout(function() { + assert.equal(timer1, 1); + timer2++; +}, 100); + +function uncaughtException(err) { + assert.equal(err.message, 'BAM!'); + exceptions++; +} +process.on('uncaughtException', uncaughtException); + +process.on('exit', function() { + process.removeListener('uncaughtException', uncaughtException); + assert.equal(exceptions, 1); + assert.equal(timer1, 1); + assert.equal(timer2, 1); +}); diff --git a/node-v0.8.14/test/simple/test-timers-zero-timeout.js b/node-v0.8.14/test/simple/test-timers-zero-timeout.js new file mode 100644 index 0000000..eb43f18 --- /dev/null +++ b/node-v0.8.14/test/simple/test-timers-zero-timeout.js @@ -0,0 +1,59 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); + +// https://github.com/joyent/node/issues/2079 - zero timeout drops extra args +(function() { + var ncalled = 0; + + setTimeout(f, 0, 'foo', 'bar', 'baz'); + var timer = setTimeout(function() {}, 0); + + function f(a, b, c) { + assert.equal(a, 'foo'); + assert.equal(b, 'bar'); + assert.equal(c, 'baz'); + ncalled++; + } + + process.on('exit', function() { + assert.equal(ncalled, 1); + }); +})(); + +(function() { + var ncalled = 0; + + var iv = setInterval(f, 0, 'foo', 'bar', 'baz'); + + function f(a, b, c) { + assert.equal(a, 'foo'); + assert.equal(b, 'bar'); + assert.equal(c, 'baz'); + if (++ncalled == 3) clearTimeout(iv); + } + + process.on('exit', function() { + assert.equal(ncalled, 3); + }); +})(); diff --git a/node-v0.8.14/test/simple/test-timers.js b/node-v0.8.14/test/simple/test-timers.js new file mode 100644 index 0000000..98e6bc3 --- /dev/null +++ b/node-v0.8.14/test/simple/test-timers.js @@ -0,0 +1,72 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); + +var inputs = [ + undefined, + null, + true, + false, + '', + [], + {}, + NaN, + +Infinity, + -Infinity, + (1.0 / 0.0), // sanity check + parseFloat('x'), // NaN + -10, + -1, + -0.5, + -0.0, + 0, + 0.0, + 0.5, + 1, + 1.0, + 10, + 2147483648, // browser behaviour: timeouts > 2^31-1 run on next tick + 12345678901234 // ditto +]; + +var timeouts = []; +var intervals = []; + +inputs.forEach(function(value, index) { + setTimeout(function() { + timeouts[index] = true; + }, value); + + var handle = setInterval(function() { + clearInterval(handle); // disarm timer or we'll never finish + intervals[index] = true; + }, value); +}); + +process.on('exit', function() { + // assert that all timers have run + inputs.forEach(function(value, index) { + assert.equal(true, timeouts[index]); + assert.equal(true, intervals[index]); + }); +}); diff --git a/node-v0.8.14/test/simple/test-tls-check-server-identity.js b/node-v0.8.14/test/simple/test-tls-check-server-identity.js new file mode 100644 index 0000000..39093a7 --- /dev/null +++ b/node-v0.8.14/test/simple/test-tls-check-server-identity.js @@ -0,0 +1,204 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var util = require('util'); +var tls = require('tls'); + +var tests = [ + // Basic CN handling + { host: 'a.com', cert: { subject: { CN: 'a.com' } }, result: true }, + { host: 'a.com', cert: { subject: { CN: 'A.COM' } }, result: true }, + { host: 'a.com', cert: { subject: { CN: 'b.com' } }, result: false }, + { host: 'a.com', cert: { subject: { CN: 'a.com.' } }, result: true }, + + // No wildcards in CN + { host: 'b.a.com', cert: { subject: { CN: '*.a.com' } }, result: false }, + + // Multiple CN fields + { + host: 'foo.com', cert: { + subject: { CN: ['foo.com', 'bar.com'] } // CN=foo.com; CN=bar.com; + }, + result: true + }, + + // DNS names and CN + { + host: 'a.com', cert: { + subjectaltname: 'DNS:*', + subject: { CN: 'b.com' } + }, + result: false + }, + { + host: 'a.com', cert: { + subjectaltname: 'DNS:*.com', + subject: { CN: 'b.com' } + }, + result: false + }, + { + host: 'a.co.uk', cert: { + subjectaltname: 'DNS:*.co.uk', + subject: { CN: 'b.com' } + }, + result: true + }, + { + host: 'a.com', cert: { + subjectaltname: 'DNS:*.a.com', + subject: { CN: 'a.com' } + }, + result: true + }, + { + host: 'a.com', cert: { + subjectaltname: 'DNS:*.a.com', + subject: { CN: 'b.com' } + }, + result: false + }, + { + host: 'a.com', cert: { + subjectaltname: 'DNS:a.com', + subject: { CN: 'b.com' } + }, + result: true + }, + { + host: 'a.com', cert: { + subjectaltname: 'DNS:A.COM', + subject: { CN: 'b.com' } + }, + result: true + }, + + // DNS names + { + host: 'a.com', cert: { + subjectaltname: 'DNS:*.a.com', + subject: {} + }, + result: false + }, + { + host: 'b.a.com', cert: { + subjectaltname: 'DNS:*.a.com', + subject: {} + }, + result: true + }, + { + host: 'c.b.a.com', cert: { + subjectaltname: 'DNS:*.a.com', + subject: {} + }, + result: false + }, + { + host: 'b.a.com', cert: { + subjectaltname: 'DNS:*b.a.com', + subject: {} + }, + result: true + }, + { + host: 'a-cb.a.com', cert: { + subjectaltname: 'DNS:*b.a.com', + subject: {} + }, + result: true + }, + { + host: 'a.b.a.com', cert: { + subjectaltname: 'DNS:*b.a.com', + subject: {} + }, + result: false + }, + // Mutliple DNS names + { + host: 'a.b.a.com', cert: { + subjectaltname: 'DNS:*b.a.com, DNS:a.b.a.com', + subject: {} + }, + result: true + }, + // URI names + { + host: 'a.b.a.com', cert: { + subjectaltname: 'URI:http://a.b.a.com/', + subject: {} + }, + result: true + }, + { + host: 'a.b.a.com', cert: { + subjectaltname: 'URI:http://*.b.a.com/', + subject: {} + }, + result: false + }, + // IP addresses + { + host: 'a.b.a.com', cert: { + subjectaltname: 'IP Address:127.0.0.1', + subject: {} + }, + result: false + }, + { + host: '127.0.0.1', cert: { + subjectaltname: 'IP Address:127.0.0.1', + subject: {} + }, + result: true + }, + { + host: '127.0.0.2', cert: { + subjectaltname: 'IP Address:127.0.0.1', + subject: {} + }, + result: false + }, + { + host: '127.0.0.1', cert: { + subjectaltname: 'DNS:a.com', + subject: {} + }, + result: false + }, + { + host: 'localhost', cert: { + subjectaltname: 'DNS:a.com', + subject: { CN: 'localhost' } + }, + result: true + }, +]; + +tests.forEach(function(test, i) { + assert.equal(tls.checkServerIdentity(test.host, test.cert), + test.result, + 'Test#' + i + ' failed: ' + util.inspect(test)); +}); diff --git a/node-v0.8.14/test/simple/test-tls-client-abort.js b/node-v0.8.14/test/simple/test-tls-client-abort.js new file mode 100644 index 0000000..8958ceb --- /dev/null +++ b/node-v0.8.14/test/simple/test-tls-client-abort.js @@ -0,0 +1,44 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +if (!process.versions.openssl) { + console.error('Skipping because node compiled without OpenSSL.'); + process.exit(0); +} + +var common = require('../common'); +var assert = require('assert'); +var fs = require('fs'); +var tls = require('tls'); +var path = require('path'); + +var cert = fs.readFileSync(path.join(common.fixturesDir, 'test_cert.pem')); +var key = fs.readFileSync(path.join(common.fixturesDir, 'test_key.pem')); + +var conn = tls.connect({cert: cert, key: key, port: common.PORT}, function() { + assert.ok(false); // callback should never be executed +}); +conn.on('error', function() { +}); +assert.doesNotThrow(function() { + conn.destroy(); +}); + diff --git a/node-v0.8.14/test/simple/test-tls-client-abort2.js b/node-v0.8.14/test/simple/test-tls-client-abort2.js new file mode 100644 index 0000000..f811962 --- /dev/null +++ b/node-v0.8.14/test/simple/test-tls-client-abort2.js @@ -0,0 +1,45 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +if (!process.versions.openssl) { + console.error('Skipping because node compiled without OpenSSL.'); + process.exit(0); +} + +var common = require('../common'); +var assert = require('assert'); +var tls = require('tls'); + +var errors = 0; + +var conn = tls.connect(common.PORT, function() { + assert(false); // callback should never be executed +}); +conn.on('error', function() { + ++errors; + assert.doesNotThrow(function() { + conn.destroy(); + }); +}); + +process.on('exit', function() { + assert.equal(errors, 1); +}); diff --git a/node-v0.8.14/test/simple/test-tls-client-reject.js b/node-v0.8.14/test/simple/test-tls-client-reject.js new file mode 100644 index 0000000..5f5056e --- /dev/null +++ b/node-v0.8.14/test/simple/test-tls-client-reject.js @@ -0,0 +1,92 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +if (!process.versions.openssl) { + console.error('Skipping because node compiled without OpenSSL.'); + process.exit(0); +} + +var common = require('../common'); +var assert = require('assert'); +var tls = require('tls'); +var fs = require('fs'); +var path = require('path'); + +var options = { + key: fs.readFileSync(path.join(common.fixturesDir, 'test_key.pem')), + cert: fs.readFileSync(path.join(common.fixturesDir, 'test_cert.pem')) +}; + +var connectCount = 0; + +var server = tls.createServer(options, function(socket) { + ++connectCount; + socket.on('data', function(data) { + common.debug(data.toString()); + assert.equal(data, 'ok'); + }); +}).listen(common.PORT, function() { + unauthorized(); +}); + +function unauthorized() { + var socket = tls.connect(common.PORT, function() { + assert(!socket.authorized); + socket.end(); + rejectUnauthorized(); + }); + socket.on('error', function(err) { + assert(false); + }); + socket.write('ok'); +} + +function rejectUnauthorized() { + var socket = tls.connect(common.PORT, { + rejectUnauthorized: true + }, function() { + assert(false); + }); + socket.on('error', function(err) { + common.debug(err); + authorized(); + }); + socket.write('ng'); +} + +function authorized() { + var socket = tls.connect(common.PORT, { + rejectUnauthorized: true, + ca: [fs.readFileSync(path.join(common.fixturesDir, 'test_cert.pem'))] + }, function() { + assert(socket.authorized); + socket.end(); + server.close(); + }); + socket.on('error', function(err) { + assert(false); + }); + socket.write('ok'); +} + +process.on('exit', function() { + assert.equal(connectCount, 3); +}); diff --git a/node-v0.8.14/test/simple/test-tls-client-resume.js b/node-v0.8.14/test/simple/test-tls-client-resume.js new file mode 100644 index 0000000..9fc84da --- /dev/null +++ b/node-v0.8.14/test/simple/test-tls-client-resume.js @@ -0,0 +1,77 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// Create an ssl server. First connection, validate that not resume. +// Cache session and close connection. Use session on second connection. +// ASSERT resumption. + +if (!process.versions.openssl) { + console.error('Skipping because node compiled without OpenSSL.'); + process.exit(0); +} + +var common = require('../common'); +var assert = require('assert'); +var tls = require('tls'); +var fs = require('fs'); + +var options = { + key: fs.readFileSync(common.fixturesDir + '/keys/agent2-key.pem'), + cert: fs.readFileSync(common.fixturesDir + '/keys/agent2-cert.pem') +}; + +var connections = 0; + +// create server +var server = tls.Server(options, function(socket) { + socket.end('Goodbye'); + connections++; +}); + +// start listening +server.listen(common.PORT, function() { + + var session1 = null; + var client1 = tls.connect({port: common.PORT}, function() { + console.log('connect1'); + assert.ok(!client1.isSessionReused(), 'Session *should not* be reused.'); + session1 = client1.getSession(); + }); + + client1.on('close', function() { + console.log('close1'); + + var opts = { 'session': session1, port: common.PORT }; + var client2 = tls.connect(opts, function() { + console.log('connect2'); + assert.ok(client2.isSessionReused(), 'Session *should* be reused.'); + }); + + client2.on('close', function() { + console.log('close2'); + server.close(); + }); + }); +}); + +process.on('exit', function() { + assert.equal(2, connections); +}); diff --git a/node-v0.8.14/test/simple/test-tls-client-verify.js b/node-v0.8.14/test/simple/test-tls-client-verify.js new file mode 100644 index 0000000..9b1083f --- /dev/null +++ b/node-v0.8.14/test/simple/test-tls-client-verify.js @@ -0,0 +1,154 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +if (!process.versions.openssl) { + console.error('Skipping because node compiled without OpenSSL.'); + process.exit(0); +} + + +var hosterr = 'Hostname/IP doesn\'t match certificate\'s altnames'; +var testCases = + [{ ca: ['ca1-cert'], + key: 'agent2-key', + cert: 'agent2-cert', + servers: [ + { ok: true, key: 'agent1-key', cert: 'agent1-cert' }, + { ok: false, key: 'agent2-key', cert: 'agent2-cert' }, + { ok: false, key: 'agent3-key', cert: 'agent3-cert' } + ] + }, + + { ca: [], + key: 'agent2-key', + cert: 'agent2-cert', + servers: [ + { ok: false, key: 'agent1-key', cert: 'agent1-cert' }, + { ok: false, key: 'agent2-key', cert: 'agent2-cert' }, + { ok: false, key: 'agent3-key', cert: 'agent3-cert' } + ] + }, + + { ca: ['ca1-cert', 'ca2-cert'], + key: 'agent2-key', + cert: 'agent2-cert', + servers: [ + { ok: true, key: 'agent1-key', cert: 'agent1-cert' }, + { ok: false, key: 'agent2-key', cert: 'agent2-cert' }, + { ok: true, key: 'agent3-key', cert: 'agent3-cert' } + ] + } + ]; + + +var common = require('../common'); +var assert = require('assert'); +var fs = require('fs'); +var tls = require('tls'); + + +function filenamePEM(n) { + return require('path').join(common.fixturesDir, 'keys', n + '.pem'); +} + + +function loadPEM(n) { + return fs.readFileSync(filenamePEM(n)); +} + +var successfulTests = 0; + +function testServers(index, servers, clientOptions, cb) { + var serverOptions = servers[index]; + if (!serverOptions) { + cb(); + return; + } + + var ok = serverOptions.ok; + + if (serverOptions.key) { + serverOptions.key = loadPEM(serverOptions.key); + } + + if (serverOptions.cert) { + serverOptions.cert = loadPEM(serverOptions.cert); + } + + var server = tls.createServer(serverOptions, function(s) { + s.end('hello world\n'); + }); + + server.listen(common.PORT, function() { + var b = ''; + + console.error('connecting...'); + var client = tls.connect(clientOptions, function() { + var authorized = client.authorized || + client.authorizationError === hosterr; + + console.error('expected: ' + ok + ' authed: ' + authorized); + + assert.equal(ok, authorized); + server.close(); + }); + + client.on('data', function(d) { + b += d.toString(); + }); + + client.on('end', function() { + assert.equal('hello world\n', b); + }); + + client.on('close', function() { + testServers(index + 1, servers, clientOptions, cb); + }); + }); +} + + +function runTest(testIndex) { + var tcase = testCases[testIndex]; + if (!tcase) return; + + var clientOptions = { + port: common.PORT, + ca: tcase.ca.map(loadPEM), + key: loadPEM(tcase.key), + cert: loadPEM(tcase.cert) + }; + + + testServers(0, tcase.servers, clientOptions, function() { + successfulTests++; + runTest(testIndex + 1); + }); +} + + +runTest(0); + + +process.on('exit', function() { + console.log('successful tests: %d', successfulTests); + assert.equal(successfulTests, testCases.length); +}); diff --git a/node-v0.8.14/test/simple/test-tls-connect-given-socket.js b/node-v0.8.14/test/simple/test-tls-connect-given-socket.js new file mode 100644 index 0000000..e341dfc --- /dev/null +++ b/node-v0.8.14/test/simple/test-tls-connect-given-socket.js @@ -0,0 +1,59 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var tls = require('tls'); +var net = require('net'); +var fs = require('fs'); +var path = require('path'); + +var serverConnected = false; +var clientConnected = false; + +var options = { + key: fs.readFileSync(path.join(common.fixturesDir, 'test_key.pem')), + cert: fs.readFileSync(path.join(common.fixturesDir, 'test_cert.pem')) +}; + +var server = tls.createServer(options, function(socket) { + serverConnected = true; + socket.end('Hello'); +}).listen(common.PORT, function() { + var socket = net.connect(common.PORT, function() { + var client = tls.connect({socket: socket}, function() { + clientConnected = true; + var data = ''; + client.on('data', function(chunk) { + data += chunk.toString(); + }); + client.on('end', function() { + assert.equal(data, 'Hello'); + server.close(); + }); + }); + }); +}); + +process.on('exit', function() { + assert(serverConnected); + assert(clientConnected); +}); diff --git a/node-v0.8.14/test/simple/test-tls-connect-pipe.js b/node-v0.8.14/test/simple/test-tls-connect-pipe.js new file mode 100644 index 0000000..f58aaab --- /dev/null +++ b/node-v0.8.14/test/simple/test-tls-connect-pipe.js @@ -0,0 +1,49 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var tls = require('tls'); +var fs = require('fs'); + +var clientConnected = 0; +var serverConnected = 0; + +var options = { + key: fs.readFileSync(common.fixturesDir + '/keys/agent1-key.pem'), + cert: fs.readFileSync(common.fixturesDir + '/keys/agent1-cert.pem') +}; + +var server = tls.Server(options, function(socket) { + ++serverConnected; + server.close(); +}); +server.listen(common.PIPE, function() { + var client = tls.connect(common.PIPE, function() { + ++clientConnected; + client.end(); + }); +}); + +process.on('exit', function() { + assert.equal(clientConnected, 1); + assert.equal(serverConnected, 1); +}); diff --git a/node-v0.8.14/test/simple/test-tls-connect-simple.js b/node-v0.8.14/test/simple/test-tls-connect-simple.js new file mode 100644 index 0000000..6c07f4c --- /dev/null +++ b/node-v0.8.14/test/simple/test-tls-connect-simple.js @@ -0,0 +1,57 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var tls = require('tls'); +var fs = require('fs'); + +var clientConnected = 0; +var serverConnected = 0; + +var options = { + key: fs.readFileSync(common.fixturesDir + '/keys/agent1-key.pem'), + cert: fs.readFileSync(common.fixturesDir + '/keys/agent1-cert.pem') +}; + +var server = tls.Server(options, function(socket) { + if (++serverConnected === 2) { + server.close(); + } +}); + +server.listen(common.PORT, function() { + var client1 = tls.connect({port: common.PORT}, function() { + ++clientConnected; + client1.end(); + }); + + var client2 = tls.connect({port: common.PORT}); + client2.on('secureConnect', function() { + ++clientConnected; + client2.end(); + }); +}); + +process.on('exit', function() { + assert.equal(clientConnected, 2); + assert.equal(serverConnected, 2); +}); diff --git a/node-v0.8.14/test/simple/test-tls-connect.js b/node-v0.8.14/test/simple/test-tls-connect.js new file mode 100644 index 0000000..fe2d17f --- /dev/null +++ b/node-v0.8.14/test/simple/test-tls-connect.js @@ -0,0 +1,52 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +if (!process.versions.openssl) { + console.error('Skipping because node compiled without OpenSSL.'); + process.exit(0); +} + +var common = require('../common'); +var assert = require('assert'); +var fs = require('fs'); +var tls = require('tls'); +var path = require('path'); + +// https://github.com/joyent/node/issues/1218 +// uncatchable exception on TLS connection error +(function() { + var cert = fs.readFileSync(path.join(common.fixturesDir, 'test_cert.pem')); + var key = fs.readFileSync(path.join(common.fixturesDir, 'test_key.pem')); + + var errorEmitted = false; + + process.on('exit', function() { + assert.ok(errorEmitted); + }); + + var conn = tls.connect({cert: cert, key: key, port: common.PORT}, function() { + assert.ok(false); // callback should never be executed + }); + + conn.on('error', function() { + errorEmitted = true; + }); +})(); diff --git a/node-v0.8.14/test/simple/test-tls-getcipher.js b/node-v0.8.14/test/simple/test-tls-getcipher.js new file mode 100644 index 0000000..2f8c290 --- /dev/null +++ b/node-v0.8.14/test/simple/test-tls-getcipher.js @@ -0,0 +1,53 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var tls = require('tls'); +var fs = require('fs'); +var cipher_list = ['RC4-SHA', 'AES256-SHA']; +var cipher_version_pattern = /TLS|SSL/; +var options = { + key: fs.readFileSync(common.fixturesDir + '/keys/agent2-key.pem'), + cert: fs.readFileSync(common.fixturesDir + '/keys/agent2-cert.pem'), + ciphers: cipher_list.join(':'), + honorCipherOrder: true +}; + +var nconns = 0; + +process.on('exit', function() { + assert.equal(nconns, 1); +}); + +var server = tls.createServer(options, function(cleartextStream) { + nconns++; +}); + +server.listen(common.PORT, '127.0.0.1', function() { + var client = tls.connect(common.PORT, '127.0.0.1', function() { + var cipher = client.getCipher(); + assert.equal(cipher.name, cipher_list[0]); + assert(cipher_version_pattern.test(cipher.version)); + client.end(); + server.close(); + }); +}); diff --git a/node-v0.8.14/test/simple/test-tls-honorcipherorder.js b/node-v0.8.14/test/simple/test-tls-honorcipherorder.js new file mode 100644 index 0000000..cc25843 --- /dev/null +++ b/node-v0.8.14/test/simple/test-tls-honorcipherorder.js @@ -0,0 +1,86 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var tls = require('tls'); +var fs = require('fs'); +var nconns = 0; +// test only in TLSv1 to use DES which is no longer supported TLSv1.2 +// to be safe when the default method is updated in the future +var SSL_Method = 'TLSv1_method'; +var localhost = '127.0.0.1'; + +process.on('exit', function() { + assert.equal(nconns, 4); +}); + +function test(honorCipherOrder, clientCipher, expectedCipher, cb) { + var soptions = { + secureProtocol: SSL_Method, + key: fs.readFileSync(common.fixturesDir + '/keys/agent2-key.pem'), + cert: fs.readFileSync(common.fixturesDir + '/keys/agent2-cert.pem'), + ciphers: 'AES256-SHA:RC4-SHA:DES-CBC-SHA', + honorCipherOrder: !!honorCipherOrder + }; + + var server = tls.createServer(soptions, function(cleartextStream) { + nconns++; + }); + server.listen(common.PORT, localhost, function() { + var coptions = {secureProtocol: SSL_Method}; + if (clientCipher) { + coptions.ciphers = clientCipher; + } + var client = tls.connect(common.PORT, localhost, coptions, function() { + var cipher = client.getCipher(); + client.end(); + server.close(); + assert.equal(cipher.name, expectedCipher); + if (cb) cb(); + }); + }); +} + +test1(); + +function test1() { + // Client has the preference of cipher suites by default + test(false, 'DES-CBC-SHA:RC4-SHA:AES256-SHA','DES-CBC-SHA', test2); +} + +function test2() { + // Server has the preference of cipher suites where AES256-SHA is in + // the first. + test(true, 'DES-CBC-SHA:RC4-SHA:AES256-SHA', 'AES256-SHA', test3); +} + +function test3() { + // Server has the preference of cipher suites. RC4-SHA is given + // higher priority over DES-CBC-SHA among client cipher suites. + test(true, 'DES-CBC-SHA:RC4-SHA', 'RC4-SHA', test4); +} + +function test4() { + // As client has only one cipher, server has no choice in regardless + // of honorCipherOrder. + test(true, 'DES-CBC-SHA', 'DES-CBC-SHA'); +} diff --git a/node-v0.8.14/test/simple/test-tls-invalid-key.js b/node-v0.8.14/test/simple/test-tls-invalid-key.js new file mode 100644 index 0000000..b4d842f --- /dev/null +++ b/node-v0.8.14/test/simple/test-tls-invalid-key.js @@ -0,0 +1,62 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +if (!process.versions.openssl) { + console.error('Skipping because node compiled without OpenSSL.'); + process.exit(0); +} + +var common = require('../common'); +var assert = require('assert'); +var tls = require('tls'); +var fs = require('fs'); +var path = require('path'); + +var options = { + key: fs.readFileSync(path.join(common.fixturesDir, 'keys/agent1-key.pem')), + cert: fs.readFileSync(path.join(common.fixturesDir, 'test_cert.pem')) +}; +var serverErrorHappened = false; +var clientErrorHappened = false; + +var server = tls.Server(options, function(socket) { + assert(false); +}); +server.on('clientError', function(err) { + serverErrorHappened = true; + common.debug('Server: ' + err); + server.close(); +}); + +server.listen(common.PORT, function() { + var client = tls.connect(common.PORT, function() { + assert(false); + }); + client.on('error', function(err) { + clientErrorHappened = true; + common.debug('Client: ' + err); + }); +}); + +process.on('exit', function() { + assert(serverErrorHappened); + assert(clientErrorHappened); +}); diff --git a/node-v0.8.14/test/simple/test-tls-junk-closes-server.js b/node-v0.8.14/test/simple/test-tls-junk-closes-server.js new file mode 100644 index 0000000..d4f9f1d --- /dev/null +++ b/node-v0.8.14/test/simple/test-tls-junk-closes-server.js @@ -0,0 +1,54 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +if (!process.versions.openssl) { + console.error('Skipping because node compiled without OpenSSL.'); + process.exit(0); +} + +var common = require('../common'); +var tls = require('tls'); +var fs = require('fs'); +var net = require('net'); + +var options = { + key: fs.readFileSync(common.fixturesDir + '/keys/agent2-key.pem'), + cert: fs.readFileSync(common.fixturesDir + '/keys/agent2-cert.pem') +}; + +var server = tls.createServer(function(s) { + s.write('welcome!\n'); + s.pipe(s); +}); + +server.listen(common.PORT, function() { + var c = net.createConnection(common.PORT); + + c.on('connect', function() { + c.write('blah\nblah\nblah\n'); + }); + + c.on('end', function() { + server.close(); + }); + +}); + diff --git a/node-v0.8.14/test/simple/test-tls-npn-server-client.js b/node-v0.8.14/test/simple/test-tls-npn-server-client.js new file mode 100644 index 0000000..cf8014a --- /dev/null +++ b/node-v0.8.14/test/simple/test-tls-npn-server-client.js @@ -0,0 +1,102 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +if (!process.features.tls_npn) { + console.error('Skipping because node compiled without OpenSSL or ' + + 'with old OpenSSL version.'); + process.exit(0); +} + +var common = require('../common'), + assert = require('assert'), + fs = require('fs'), + tls = require('tls'); + +function filenamePEM(n) { + return require('path').join(common.fixturesDir, 'keys', n + '.pem'); +} + +function loadPEM(n) { + return fs.readFileSync(filenamePEM(n)); +} + +var serverOptions = { + key: loadPEM('agent2-key'), + cert: loadPEM('agent2-cert'), + crl: loadPEM('ca2-crl'), + NPNProtocols: ['a', 'b', 'c'] +}; + +var serverPort = common.PORT; + +var clientsOptions = [{ + port: serverPort, + key: serverOptions.key, + cert: serverOptions.cert, + crl: serverOptions.crl, + NPNProtocols: ['a', 'b', 'c'] +},{ + port: serverPort, + key: serverOptions.key, + cert: serverOptions.cert, + crl: serverOptions.crl, + NPNProtocols: ['c', 'b', 'e'] +},{ + port: serverPort, + key: serverOptions.key, + cert: serverOptions.cert, + crl: serverOptions.crl, + NPNProtocols: ['first-priority-unsupported', 'x', 'y'] +}]; + +var serverResults = [], + clientsResults = []; + +var server = tls.createServer(serverOptions, function(c) { + serverResults.push(c.npnProtocol); +}); +server.listen(serverPort, startTest); + +function startTest() { + function connectClient(options, callback) { + var client = tls.connect(options, function() { + clientsResults.push(client.npnProtocol); + client.destroy(); + + callback(); + }); + }; + + connectClient(clientsOptions[0], function() { + connectClient(clientsOptions[1], function() { + connectClient(clientsOptions[2], function() { + server.close(); + }); + }); + }); +} + +process.on('exit', function() { + assert.equal(serverResults[0], clientsResults[0]); + assert.equal(serverResults[1], clientsResults[1]); + assert.equal(serverResults[2], 'first-priority-unsupported'); + assert.equal(clientsResults[2], false); +}); diff --git a/node-v0.8.14/test/simple/test-tls-over-http-tunnel.js b/node-v0.8.14/test/simple/test-tls-over-http-tunnel.js new file mode 100644 index 0000000..4a5e221 --- /dev/null +++ b/node-v0.8.14/test/simple/test-tls-over-http-tunnel.js @@ -0,0 +1,173 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + + + +if (!process.versions.openssl) { + console.error('Skipping because node compiled without OpenSSL.'); + process.exit(0); +} + +var common = require('../common'); +var assert = require('assert'); + +var fs = require('fs'); +var net = require('net'); +var http = require('http'); +var https = require('https'); + +var proxyPort = common.PORT + 1; +var gotRequest = false; + +var key = fs.readFileSync(common.fixturesDir + '/keys/agent1-key.pem'); +var cert = fs.readFileSync(common.fixturesDir + '/keys/agent1-cert.pem'); + +var options = { + key: key, + cert: cert +}; + +var server = https.createServer(options, function(req, res) { + console.log('SERVER: got request'); + res.writeHead(200, { + 'content-type': 'text/plain' + }); + console.log('SERVER: sending response'); + res.end('hello world\n'); +}); + +var proxy = net.createServer(function(clientSocket) { + console.log('PROXY: got a client connection'); + + var serverSocket = null; + + clientSocket.on('data', function(chunk) { + if (!serverSocket) { + // Verify the CONNECT request + assert.equal('CONNECT localhost:' + common.PORT + ' HTTP/1.1\r\n' + + 'Proxy-Connections: keep-alive\r\n' + + 'Host: localhost:' + proxyPort + '\r\n\r\n', + chunk); + + console.log('PROXY: got CONNECT request'); + console.log('PROXY: creating a tunnel'); + + // create the tunnel + serverSocket = net.connect(common.PORT, function() { + console.log('PROXY: replying to client CONNECT request'); + + // Send the response + clientSocket.write('HTTP/1.1 200 OK\r\nProxy-Connections: keep' + + '-alive\r\nConnections: keep-alive\r\nVia: ' + + 'localhost:' + proxyPort + '\r\n\r\n'); + }); + + serverSocket.on('data', function(chunk) { + clientSocket.write(chunk); + }); + + serverSocket.on('end', function() { + clientSocket.destroy(); + }); + } else { + serverSocket.write(chunk); + } + }); + + clientSocket.on('end', function() { + serverSocket.destroy(); + }); +}); + +server.listen(common.PORT); + +proxy.listen(proxyPort, function() { + console.log('CLIENT: Making CONNECT request'); + + var req = http.request({ + port: proxyPort, + method: 'CONNECT', + path: 'localhost:' + common.PORT, + headers: { + 'Proxy-Connections': 'keep-alive' + } + }); + req.useChunkedEncodingByDefault = false; // for v0.6 + req.on('response', onResponse); // for v0.6 + req.on('upgrade', onUpgrade); // for v0.6 + req.on('connect', onConnect); // for v0.7 or later + req.end(); + + function onResponse(res) { + // Very hacky. This is necessary to avoid http-parser leaks. + res.upgrade = true; + } + + function onUpgrade(res, socket, head) { + // Hacky. + process.nextTick(function() { + onConnect(res, socket, head); + }); + } + + function onConnect(res, socket, header) { + assert.equal(200, res.statusCode); + console.log('CLIENT: got CONNECT response'); + + // detach the socket + socket.removeAllListeners('data'); + socket.removeAllListeners('close'); + socket.removeAllListeners('error'); + socket.removeAllListeners('drain'); + socket.removeAllListeners('end'); + socket.ondata = null; + socket.onend = null; + socket.ondrain = null; + + console.log('CLIENT: Making HTTPS request'); + + https.get({ + path: '/foo', + key: key, + cert: cert, + socket: socket, // reuse the socket + agent: false + }, function(res) { + assert.equal(200, res.statusCode); + + res.on('data', function(chunk) { + assert.equal('hello world\n', chunk); + console.log('CLIENT: got HTTPS response'); + gotRequest = true; + }); + + res.on('end', function() { + proxy.close(); + server.close(); + }); + }).end(); + } +}); + +process.on('exit', function() { + assert.ok(gotRequest); +}); diff --git a/node-v0.8.14/test/simple/test-tls-passphrase.js b/node-v0.8.14/test/simple/test-tls-passphrase.js new file mode 100644 index 0000000..e3c0f2a --- /dev/null +++ b/node-v0.8.14/test/simple/test-tls-passphrase.js @@ -0,0 +1,73 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +if (!process.versions.openssl) { + console.error('Skipping because node compiled without OpenSSL.'); + process.exit(0); +} + +var common = require('../common'); +var assert = require('assert'); +var tls = require('tls'); +var fs = require('fs'); +var path = require('path'); + +var key = fs.readFileSync(path.join(common.fixturesDir, 'pass-key.pem')); +var cert = fs.readFileSync(path.join(common.fixturesDir, 'pass-cert.pem')); + +var server = tls.Server({ + key: key, + passphrase: 'passphrase', + cert: cert, + ca: [cert], + requestCert: true, + rejectUnauthorized: true +}, function(s) { + s.end(); +}); + +var connectCount = 0; +server.listen(common.PORT, function() { + var c = tls.connect({ + port: common.PORT, + key: key, + passphrase: 'passphrase', + cert: cert + }, function() { + ++connectCount; + }); + c.on('end', function() { + server.close(); + }); +}); + +assert.throws(function() { + tls.connect({ + port: common.PORT, + key: key, + passphrase: 'invalid', + cert: cert + }); +}); + +process.on('exit', function() { + assert.equal(connectCount, 1); +}); diff --git a/node-v0.8.14/test/simple/test-tls-pause-close.js b/node-v0.8.14/test/simple/test-tls-pause-close.js new file mode 100644 index 0000000..a53d017 --- /dev/null +++ b/node-v0.8.14/test/simple/test-tls-pause-close.js @@ -0,0 +1,100 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +if (!process.versions.openssl) { + console.error('Skipping because node compiled without OpenSSL.'); + process.exit(0); +} + +var common = require('../common'); +var assert = require('assert'); +var tls = require('tls'); +var fs = require('fs'); +var path = require('path'); + +var serverClosed = false; +var serverSocketClosed = false; +var clientClosed = false; +var clientSocketClosed = false; + +var options = { + key: fs.readFileSync(path.join(common.fixturesDir, 'test_key.pem')), + cert: fs.readFileSync(path.join(common.fixturesDir, 'test_cert.pem')) +}; + +var server = tls.createServer(options, function(s) { + console.log('server connected'); + s.socket.on('end', function() { + console.log('server socket ended'); + }); + s.socket.on('close', function() { + console.log('server socket closed'); + serverSocketClosed = true; + }); + s.on('end', function() { + console.log('server ended'); + }); + s.on('close', function() { + console.log('server closed'); + serverClosed = true; + }); + s.pause(); + console.log('server paused'); + process.nextTick(function() { + s.resume(); + console.log('server resumed'); + }); + s.end(); +}); + +server.listen(common.PORT, function() { + var c = tls.connect({port: common.PORT}, function() { + console.log('client connected'); + c.socket.on('end', function() { + console.log('client socket ended'); + }); + c.socket.on('close', function() { + console.log('client socket closed'); + clientSocketClosed = true; + }); + c.pause(); + console.log('client paused'); + process.nextTick(function() { + c.resume(); + console.log('client resumed'); + }); + }); + c.on('end', function() { + console.log('client ended'); + }); + c.on('close', function() { + console.log('client closed'); + clientClosed = true; + server.close(); + }); +}); + +process.on('exit', function() { + assert(serverClosed); + assert(serverSocketClosed); + assert(clientClosed); + assert(clientSocketClosed); +}); diff --git a/node-v0.8.14/test/simple/test-tls-pause.js b/node-v0.8.14/test/simple/test-tls-pause.js new file mode 100644 index 0000000..9ca3dfb --- /dev/null +++ b/node-v0.8.14/test/simple/test-tls-pause.js @@ -0,0 +1,78 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +if (!process.versions.openssl) { + console.error('Skipping because node compiled without OpenSSL.'); + process.exit(0); +} + +var common = require('../common'); +var assert = require('assert'); +var tls = require('tls'); +var fs = require('fs'); +var path = require('path'); + +var options = { + key: fs.readFileSync(path.join(common.fixturesDir, 'test_key.pem')), + cert: fs.readFileSync(path.join(common.fixturesDir, 'test_cert.pem')) +}; + +var bufSize = 1024 * 1024; +var sent = 0; +var received = 0; + +var server = tls.Server(options, function(socket) { + socket.pipe(socket); +}); + +server.listen(common.PORT, function() { + var resumed = false; + var client = tls.connect({port: common.PORT}, function() { + client.pause(); + common.debug('paused'); + send(); + function send() { + if (client.write(new Buffer(bufSize))) { + sent += bufSize; + assert.ok(sent < 100 * 1024 * 1024); // max 100MB + return process.nextTick(send); + } + sent += bufSize; + common.debug('sent: ' + sent); + resumed = true; + client.resume(); + common.debug('resumed'); + } + }); + client.on('data', function(data) { + assert.ok(resumed); + received += data.length; + if (received >= sent) { + common.debug('received: ' + received); + client.end(); + server.close(); + } + }); +}); + +process.on('exit', function() { + assert.equal(sent, received); +}); diff --git a/node-v0.8.14/test/simple/test-tls-peer-certificate-multi-keys.js b/node-v0.8.14/test/simple/test-tls-peer-certificate-multi-keys.js new file mode 100644 index 0000000..070b528 --- /dev/null +++ b/node-v0.8.14/test/simple/test-tls-peer-certificate-multi-keys.js @@ -0,0 +1,58 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +if (!process.versions.openssl) { + console.error('Skipping because node compiled without OpenSSL.'); + process.exit(0); +} + +var common = require('../common'); +var assert = require('assert'); +var tls = require('tls'); +var fs = require('fs'); +var util = require('util'); +var join = require('path').join; +var spawn = require('child_process').spawn; + +var options = { + key: fs.readFileSync(join(common.fixturesDir, 'agent.key')), + cert: fs.readFileSync(join(common.fixturesDir, 'multi-alice.crt')) +}; +var verified = false; + +var server = tls.createServer(options, function(cleartext) { + cleartext.end('World'); +}); +server.listen(common.PORT, function() { + var socket = tls.connect({port: common.PORT}, function() { + var peerCert = socket.getPeerCertificate(); + common.debug(util.inspect(peerCert)); + assert.deepEqual(peerCert.subject.OU, + ['Information Technology', 'Engineering', 'Marketing']); + verified = true; + server.close(); + }); + socket.end('Hello'); +}); + +process.on('exit', function() { + assert.ok(verified); +}); diff --git a/node-v0.8.14/test/simple/test-tls-peer-certificate.js b/node-v0.8.14/test/simple/test-tls-peer-certificate.js new file mode 100644 index 0000000..ea3245a --- /dev/null +++ b/node-v0.8.14/test/simple/test-tls-peer-certificate.js @@ -0,0 +1,58 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +if (!process.versions.openssl) { + console.error('Skipping because node compiled without OpenSSL.'); + process.exit(0); +} + +var common = require('../common'); +var assert = require('assert'); +var tls = require('tls'); +var fs = require('fs'); +var util = require('util'); +var join = require('path').join; +var spawn = require('child_process').spawn; + +var options = { + key: fs.readFileSync(join(common.fixturesDir, 'agent.key')), + cert: fs.readFileSync(join(common.fixturesDir, 'alice.crt')) +}; +var verified = false; + +var server = tls.createServer(options, function(cleartext) { + cleartext.end('World'); +}); +server.listen(common.PORT, function() { + var socket = tls.connect({port: common.PORT}, function() { + var peerCert = socket.getPeerCertificate(); + common.debug(util.inspect(peerCert)); + assert.equal(peerCert.subject.subjectAltName, + 'uniformResourceIdentifier:http://localhost:8000/alice.foaf#me'); + verified = true; + server.close(); + }); + socket.end('Hello'); +}); + +process.on('exit', function() { + assert.ok(verified); +}); diff --git a/node-v0.8.14/test/simple/test-tls-remote.js b/node-v0.8.14/test/simple/test-tls-remote.js new file mode 100644 index 0000000..9aa51ab --- /dev/null +++ b/node-v0.8.14/test/simple/test-tls-remote.js @@ -0,0 +1,61 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +if (!process.versions.openssl) { + console.error('Skipping because node compiled without OpenSSL.'); + process.exit(0); +} + +var common = require('../common'); +var assert = require('assert'); +var tls = require('tls'); +var fs = require('fs'); +var path = require('path'); + +var options = { + key: fs.readFileSync(path.join(common.fixturesDir, 'test_key.pem')), + cert: fs.readFileSync(path.join(common.fixturesDir, 'test_cert.pem')) +}; + +var server = tls.Server(options, function(s) { + assert.equal(s.address().address, s.socket.address().address); + assert.equal(s.address().port, s.socket.address().port); + + assert.equal(s.remoteAddress, s.socket.remoteAddress); + assert.equal(s.remotePort, s.socket.remotePort); + s.end(); +}); + +server.listen(common.PORT, '127.0.0.1', function() { + assert.equal(server.address().address, '127.0.0.1'); + assert.equal(server.address().port, common.PORT); + + var c = tls.connect({port: common.PORT, host: '127.0.0.1'}, function() { + assert.equal(c.address().address, c.socket.address().address); + assert.equal(c.address().port, c.socket.address().port); + + assert.equal(c.remoteAddress, '127.0.0.1'); + assert.equal(c.remotePort, common.PORT); + }); + c.on('end', function() { + server.close(); + }); +}); diff --git a/node-v0.8.14/test/simple/test-tls-request-timeout.js b/node-v0.8.14/test/simple/test-tls-request-timeout.js new file mode 100644 index 0000000..c44ecef --- /dev/null +++ b/node-v0.8.14/test/simple/test-tls-request-timeout.js @@ -0,0 +1,50 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var tls = require('tls'); +var fs = require('fs'); + +var hadTimeout = false; + +var options = { + key: fs.readFileSync(common.fixturesDir + '/keys/agent1-key.pem'), + cert: fs.readFileSync(common.fixturesDir + '/keys/agent1-cert.pem') +}; + +var server = tls.Server(options, function(socket) { + socket.setTimeout(100); + + socket.on('timeout', function(err) { + hadTimeout = true; + socket.end(); + server.close(); + }); +}); + +server.listen(common.PORT, function() { + var socket = tls.connect({port: common.PORT}); +}); + +process.on('exit', function() { + assert.ok(hadTimeout); +}); diff --git a/node-v0.8.14/test/simple/test-tls-securepair-client.js b/node-v0.8.14/test/simple/test-tls-securepair-client.js new file mode 100644 index 0000000..e361a14 --- /dev/null +++ b/node-v0.8.14/test/simple/test-tls-securepair-client.js @@ -0,0 +1,201 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +if (!process.versions.openssl) { + console.error('Skipping because node compiled without OpenSSL.'); + process.exit(0); +} + +var common = require('../common'); +var join = require('path').join; +var net = require('net'); +var assert = require('assert'); +var fs = require('fs'); +var crypto = require('crypto'); +var tls = require('tls'); +var exec = require('child_process').exec; +var spawn = require('child_process').spawn; + +maybe(test1); + +// There is a bug with 'openssl s_server' which makes it not flush certain +// important events to stdout when done over a pipe. Therefore we skip this +// test for all openssl versions less than 1.0.0. +function maybe(cb) { + exec('openssl version', function(err, data) { + if (err) throw err; + if (/OpenSSL 0\./.test(data)) { + console.error('Skipping due to old OpenSSL version.'); + return; + } + cb(); + }); +} + +// simple/test-tls-securepair-client +function test1() { + test('agent.key', 'agent.crt', null, test2); +} + +// simple/test-tls-ext-key-usage +function test2() { + function check(pair) { + // "TLS Web Client Authentication" + assert.equal(pair.cleartext.getPeerCertificate().ext_key_usage.length, 1); + assert.equal(pair.cleartext.getPeerCertificate().ext_key_usage[0], + '1.3.6.1.5.5.7.3.2'); + } + test('keys/agent4-key.pem', 'keys/agent4-cert.pem', check); +} + +function test(keyfn, certfn, check, next) { + // FIXME: Avoid the common PORT as this test currently hits a C-level + // assertion error with node_g. The program aborts without HUPing + // the openssl s_server thus causing many tests to fail with + // EADDRINUSE. + var PORT = common.PORT + 5; + + var connections = 0; + + keyfn = join(common.fixturesDir, keyfn); + var key = fs.readFileSync(keyfn).toString(); + + certfn = join(common.fixturesDir, certfn); + var cert = fs.readFileSync(certfn).toString(); + + var server = spawn('openssl', ['s_server', + '-accept', PORT, + '-cert', certfn, + '-key', keyfn]); + server.stdout.pipe(process.stdout); + server.stderr.pipe(process.stdout); + + + var state = 'WAIT-ACCEPT'; + + var serverStdoutBuffer = ''; + server.stdout.setEncoding('utf8'); + server.stdout.on('data', function(s) { + serverStdoutBuffer += s; + console.error(state); + switch (state) { + case 'WAIT-ACCEPT': + if (/ACCEPT/g.test(serverStdoutBuffer)) { + // Give s_server half a second to start up. + setTimeout(startClient, 500); + state = 'WAIT-HELLO'; + } + break; + + case 'WAIT-HELLO': + if (/hello/g.test(serverStdoutBuffer)) { + + // End the current SSL connection and exit. + // See s_server(1ssl). + server.stdin.write('Q'); + + state = 'WAIT-SERVER-CLOSE'; + } + break; + + default: + break; + } + }); + + + var timeout = setTimeout(function() { + server.kill(); + process.exit(1); + }, 5000); + + var gotWriteCallback = false; + var serverExitCode = -1; + + server.on('exit', function(code) { + serverExitCode = code; + clearTimeout(timeout); + if (next) next(); + }); + + + function startClient() { + var s = new net.Stream(); + + var sslcontext = crypto.createCredentials({key: key, cert: cert}); + sslcontext.context.setCiphers('RC4-SHA:AES128-SHA:AES256-SHA'); + + var pair = tls.createSecurePair(sslcontext, false); + + assert.ok(pair.encrypted.writable); + assert.ok(pair.cleartext.writable); + + pair.encrypted.pipe(s); + s.pipe(pair.encrypted); + + s.connect(PORT); + + s.on('connect', function() { + console.log('client connected'); + }); + + pair.on('secure', function() { + console.log('client: connected+secure!'); + console.log('client pair.cleartext.getPeerCertificate(): %j', + pair.cleartext.getPeerCertificate()); + console.log('client pair.cleartext.getCipher(): %j', + pair.cleartext.getCipher()); + if (check) check(pair); + setTimeout(function() { + pair.cleartext.write('hello\r\n', function() { + gotWriteCallback = true; + }); + }, 500); + }); + + pair.cleartext.on('data', function(d) { + console.log('cleartext: %s', d.toString()); + }); + + s.on('close', function() { + console.log('client close'); + }); + + pair.encrypted.on('error', function(err) { + console.log('encrypted error: ' + err); + }); + + s.on('error', function(err) { + console.log('socket error: ' + err); + }); + + pair.on('error', function(err) { + console.log('secure error: ' + err); + }); + } + + + process.on('exit', function() { + assert.equal(0, serverExitCode); + assert.equal('WAIT-SERVER-CLOSE', state); + assert.ok(gotWriteCallback); + }); +} diff --git a/node-v0.8.14/test/simple/test-tls-securepair-server.js b/node-v0.8.14/test/simple/test-tls-securepair-server.js new file mode 100644 index 0000000..3b4eec1 --- /dev/null +++ b/node-v0.8.14/test/simple/test-tls-securepair-server.js @@ -0,0 +1,154 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +if (!process.versions.openssl) { + console.error('Skipping because node compiled without OpenSSL.'); + process.exit(0); +} + + +var common = require('../common'); +var assert = require('assert'); + +var join = require('path').join; +var net = require('net'); +var fs = require('fs'); +var crypto = require('crypto'); +var tls = require('tls'); +var spawn = require('child_process').spawn; + +var connections = 0; +var key = fs.readFileSync(join(common.fixturesDir, 'agent.key')).toString(); +var cert = fs.readFileSync(join(common.fixturesDir, 'agent.crt')).toString(); + +function log(a) { + console.error('***server*** ' + a); +} + +var server = net.createServer(function(socket) { + connections++; + log('connection fd=' + socket.fd); + var sslcontext = crypto.createCredentials({key: key, cert: cert}); + sslcontext.context.setCiphers('RC4-SHA:AES128-SHA:AES256-SHA'); + + var pair = tls.createSecurePair(sslcontext, true); + + assert.ok(pair.encrypted.writable); + assert.ok(pair.cleartext.writable); + + pair.encrypted.pipe(socket); + socket.pipe(pair.encrypted); + + log('i set it secure'); + + pair.on('secure', function() { + log('connected+secure!'); + pair.cleartext.write('hello\r\n'); + log(pair.cleartext.getPeerCertificate()); + log(pair.cleartext.getCipher()); + }); + + pair.cleartext.on('data', function(data) { + log('read bytes ' + data.length); + pair.cleartext.write(data); + }); + + socket.on('end', function() { + log('socket end'); + }); + + pair.cleartext.on('error', function(err) { + log('got error: '); + log(err); + log(err.stack); + socket.destroy(); + }); + + pair.encrypted.on('error', function(err) { + log('encrypted error: '); + log(err); + log(err.stack); + socket.destroy(); + }); + + socket.on('error', function(err) { + log('socket error: '); + log(err); + log(err.stack); + socket.destroy(); + }); + + socket.on('close', function(err) { + log('socket closed'); + }); + + pair.on('error', function(err) { + log('secure error: '); + log(err); + log(err.stack); + socket.destroy(); + }); +}); + +var gotHello = false; +var sentWorld = false; +var gotWorld = false; +var opensslExitCode = -1; + +server.listen(common.PORT, function() { + // To test use: openssl s_client -connect localhost:8000 + var client = spawn('openssl', ['s_client', '-connect', '127.0.0.1:' + + common.PORT]); + + + var out = ''; + + client.stdout.setEncoding('utf8'); + client.stdout.on('data', function(d) { + out += d; + + if (!gotHello && /hello/.test(out)) { + gotHello = true; + client.stdin.write('world\r\n'); + sentWorld = true; + } + + if (!gotWorld && /world/.test(out)) { + gotWorld = true; + client.stdin.end(); + } + }); + + client.stdout.pipe(process.stdout, { end: false }); + + client.on('exit', function(code) { + opensslExitCode = code; + server.close(); + }); +}); + +process.on('exit', function() { + assert.equal(1, connections); + assert.ok(gotHello); + assert.ok(sentWorld); + assert.ok(gotWorld); + assert.equal(0, opensslExitCode); +}); diff --git a/node-v0.8.14/test/simple/test-tls-server-verify.js b/node-v0.8.14/test/simple/test-tls-server-verify.js new file mode 100644 index 0000000..2b09d82 --- /dev/null +++ b/node-v0.8.14/test/simple/test-tls-server-verify.js @@ -0,0 +1,290 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + + + +if (!process.versions.openssl) { + console.error('Skipping because node compiled without OpenSSL.'); + process.exit(0); +} + +// This is a rather complex test which sets up various TLS servers with node +// and connects to them using the 'openssl s_client' command line utility +// with various keys. Depending on the certificate authority and other +// parameters given to the server, the various clients are +// - rejected, +// - accepted and "unauthorized", or +// - accepted and "authorized". + +var testCases = + [{ title: 'Do not request certs. Everyone is unauthorized.', + requestCert: false, + rejectUnauthorized: false, + CAs: ['ca1-cert'], + clients: + [{ name: 'agent1', shouldReject: false, shouldAuth: false }, + { name: 'agent2', shouldReject: false, shouldAuth: false }, + { name: 'agent3', shouldReject: false, shouldAuth: false }, + { name: 'nocert', shouldReject: false, shouldAuth: false } + ] + }, + + { title: 'Allow both authed and unauthed connections with CA1', + requestCert: true, + rejectUnauthorized: false, + CAs: ['ca1-cert'], + clients: + [{ name: 'agent1', shouldReject: false, shouldAuth: true }, + { name: 'agent2', shouldReject: false, shouldAuth: false }, + { name: 'agent3', shouldReject: false, shouldAuth: false }, + { name: 'nocert', shouldReject: false, shouldAuth: false } + ] + }, + + { title: 'Allow only authed connections with CA1', + requestCert: true, + rejectUnauthorized: true, + CAs: ['ca1-cert'], + clients: + [{ name: 'agent1', shouldReject: false, shouldAuth: true }, + { name: 'agent2', shouldReject: true }, + { name: 'agent3', shouldReject: true }, + { name: 'nocert', shouldReject: true } + ] + }, + + { title: 'Allow only authed connections with CA1 and CA2', + requestCert: true, + rejectUnauthorized: true, + CAs: ['ca1-cert', 'ca2-cert'], + clients: + [{ name: 'agent1', shouldReject: false, shouldAuth: true }, + { name: 'agent2', shouldReject: true }, + { name: 'agent3', shouldReject: false, shouldAuth: true }, + { name: 'nocert', shouldReject: true } + ] + }, + + + { title: 'Allow only certs signed by CA2 but not in the CRL', + requestCert: true, + rejectUnauthorized: true, + CAs: ['ca2-cert'], + crl: 'ca2-crl', + clients: + [ + { name: 'agent1', shouldReject: true, shouldAuth: false }, + { name: 'agent2', shouldReject: true, shouldAuth: false }, + { name: 'agent3', shouldReject: false, shouldAuth: true }, + // Agent4 has a cert in the CRL. + { name: 'agent4', shouldReject: true, shouldAuth: false }, + { name: 'nocert', shouldReject: true } + ] + } + ]; + + +var common = require('../common'); +var assert = require('assert'); +var fs = require('fs'); +var tls = require('tls'); +var spawn = require('child_process').spawn; + + +function filenamePEM(n) { + return require('path').join(common.fixturesDir, 'keys', n + '.pem'); +} + + +function loadPEM(n) { + return fs.readFileSync(filenamePEM(n)); +} + + +var serverKey = loadPEM('agent2-key'); +var serverCert = loadPEM('agent2-cert'); + + +function runClient(options, cb) { + + // Client can connect in three ways: + // - Self-signed cert + // - Certificate, but not signed by CA. + // - Certificate signed by CA. + + var args = ['s_client', '-connect', '127.0.0.1:' + common.PORT]; + + + console.log(' connecting with', options.name); + + switch (options.name) { + case 'agent1': + // Signed by CA1 + args.push('-key'); + args.push(filenamePEM('agent1-key')); + args.push('-cert'); + args.push(filenamePEM('agent1-cert')); + break; + + case 'agent2': + // Self-signed + // This is also the key-cert pair that the server will use. + args.push('-key'); + args.push(filenamePEM('agent2-key')); + args.push('-cert'); + args.push(filenamePEM('agent2-cert')); + break; + + case 'agent3': + // Signed by CA2 + args.push('-key'); + args.push(filenamePEM('agent3-key')); + args.push('-cert'); + args.push(filenamePEM('agent3-cert')); + break; + + case 'agent4': + // Signed by CA2 (rejected by ca2-crl) + args.push('-key'); + args.push(filenamePEM('agent4-key')); + args.push('-cert'); + args.push(filenamePEM('agent4-cert')); + break; + + case 'nocert': + // Do not send certificate + break; + + default: + throw new Error('Unknown agent name'); + } + + // To test use: openssl s_client -connect localhost:8000 + var client = spawn('openssl', args); + + var out = ''; + + var rejected = true; + var authed = false; + + client.stdout.setEncoding('utf8'); + client.stdout.on('data', function(d) { + out += d; + + if (/_unauthed/g.test(out)) { + console.error(' * unauthed'); + client.stdin.end('goodbye\n'); + authed = false; + rejected = false; + } + + if (/_authed/g.test(out)) { + console.error(' * authed'); + client.stdin.end('goodbye\n'); + authed = true; + rejected = false; + } + }); + + //client.stdout.pipe(process.stdout); + + client.on('exit', function(code) { + //assert.equal(0, code, options.name + + // ": s_client exited with error code " + code); + if (options.shouldReject) { + assert.equal(true, rejected, options.name + + ' NOT rejected, but should have been'); + } else { + assert.equal(false, rejected, options.name + + ' rejected, but should NOT have been'); + assert.equal(options.shouldAuth, authed); + } + + cb(); + }); +} + + +// Run the tests +var successfulTests = 0; +function runTest(testIndex) { + var tcase = testCases[testIndex]; + if (!tcase) return; + + console.error("Running '%s'", tcase.title); + + var cas = tcase.CAs.map(loadPEM); + + var crl = tcase.crl ? loadPEM(tcase.crl) : null; + + var serverOptions = { + key: serverKey, + cert: serverCert, + ca: cas, + crl: crl, + requestCert: tcase.requestCert, + rejectUnauthorized: tcase.rejectUnauthorized + }; + + var connections = 0; + + var server = tls.Server(serverOptions, function(c) { + connections++; + if (c.authorized) { + console.error('- authed connection: ' + + c.getPeerCertificate().subject.CN); + c.write('\n_authed\n'); + } else { + console.error('- unauthed connection: %s', c.authorizationError); + c.write('\n_unauthed\n'); + } + }); + + function runNextClient(clientIndex) { + var options = tcase.clients[clientIndex]; + if (options) { + runClient(options, function() { + runNextClient(clientIndex + 1); + }); + } else { + server.close(); + successfulTests++; + runTest(testIndex + 1); + } + } + + server.listen(common.PORT, function() { + if (tcase.debug) { + console.error('TLS server running on port ' + common.PORT); + } else { + runNextClient(0); + } + }); +} + + +runTest(0); + + +process.on('exit', function() { + assert.equal(successfulTests, testCases.length); +}); diff --git a/node-v0.8.14/test/simple/test-tls-session-cache.js b/node-v0.8.14/test/simple/test-tls-session-cache.js new file mode 100644 index 0000000..64e4199 --- /dev/null +++ b/node-v0.8.14/test/simple/test-tls-session-cache.js @@ -0,0 +1,78 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +if (!process.versions.openssl) { + console.error('Skipping because node compiled without OpenSSL.'); + process.exit(0); +} +require('child_process').exec('openssl version', function(err) { + if (err !== null) { + console.error('Skipping because openssl command is not available.'); + process.exit(0); + } + doTest(); +}); + +function doTest() { + var common = require('../common'); + var assert = require('assert'); + var tls = require('tls'); + var fs = require('fs'); + var join = require('path').join; + var spawn = require('child_process').spawn; + + var keyFile = join(common.fixturesDir, 'agent.key'); + var certFile = join(common.fixturesDir, 'agent.crt'); + var key = fs.readFileSync(keyFile); + var cert = fs.readFileSync(certFile); + var options = { + key: key, + cert: cert, + ca: [cert], + requestCert: true + }; + var requestCount = 0; + + var server = tls.createServer(options, function(cleartext) { + ++requestCount; + cleartext.end(); + }); + server.listen(common.PORT, function() { + var client = spawn('openssl', [ + 's_client', + '-connect', 'localhost:' + common.PORT, + '-key', join(common.fixturesDir, 'agent.key'), + '-cert', join(common.fixturesDir, 'agent.crt'), + '-reconnect' + ], { + customFds: [0, 1, 2] + }); + client.on('exit', function(code) { + assert.equal(code, 0); + server.close(); + }); + }); + + process.on('exit', function() { + // initial request + reconnect requests (5 times) + assert.equal(requestCount, 6); + }); +} diff --git a/node-v0.8.14/test/simple/test-tls-set-ciphers.js b/node-v0.8.14/test/simple/test-tls-set-ciphers.js new file mode 100644 index 0000000..576094d --- /dev/null +++ b/node-v0.8.14/test/simple/test-tls-set-ciphers.js @@ -0,0 +1,62 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var exec = require('child_process').exec; +var tls = require('tls'); +var fs = require('fs'); + +if (process.platform === 'win32') { + console.log("Skipping test, you probably don't have openssl installed."); + process.exit(); +} + +var options = { + key: fs.readFileSync(common.fixturesDir + '/keys/agent2-key.pem'), + cert: fs.readFileSync(common.fixturesDir + '/keys/agent2-cert.pem'), + ciphers: 'NULL-MD5' // it's ultra-fast! +}; + +var reply = 'I AM THE WALRUS'; // something recognizable +var nconns = 0; +var response = ''; + +process.on('exit', function() { + assert.equal(nconns, 1); + assert.notEqual(response.indexOf(reply), -1); +}); + +var server = tls.createServer(options, function(conn) { + conn.end(reply); + nconns++; +}); + +server.listen(common.PORT, '127.0.0.1', function() { + var cmd = 'openssl s_client -cipher NULL-MD5 -connect 127.0.0.1:' + + common.PORT; + + exec(cmd, function(err, stdout, stderr) { + if (err) throw err; + response = stdout; + server.close(); + }); +}); diff --git a/node-v0.8.14/test/simple/test-tls-set-encoding.js b/node-v0.8.14/test/simple/test-tls-set-encoding.js new file mode 100644 index 0000000..8850a67 --- /dev/null +++ b/node-v0.8.14/test/simple/test-tls-set-encoding.js @@ -0,0 +1,71 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var tls = require('tls'); +var fs = require('fs'); + + +var options = { + key: fs.readFileSync(common.fixturesDir + '/keys/agent2-key.pem'), + cert: fs.readFileSync(common.fixturesDir + '/keys/agent2-cert.pem') +}; + +var connections = 0; +var message = 'hello world\n'; + + +var server = tls.Server(options, function(socket) { + socket.end(message); + connections++; +}); + + +server.listen(common.PORT, function() { + var client = tls.connect({port: common.PORT}); + + var buffer = ''; + + client.setEncoding('utf8'); + + client.on('data', function(d) { + assert.ok(typeof d === 'string'); + buffer += d; + }); + + + client.on('close', function() { + // readyState is deprecated but we want to make + // sure this isn't triggering an assert in lib/net.js + // See issue #1069. + assert.equal('closed', client.readyState); + + assert.equal(buffer, message); + console.log(message); + server.close(); + }); +}); + + +process.on('exit', function() { + assert.equal(1, connections); +}); diff --git a/node-v0.8.14/test/simple/test-tls-sni-server-client.js b/node-v0.8.14/test/simple/test-tls-sni-server-client.js new file mode 100644 index 0000000..093d0fd --- /dev/null +++ b/node-v0.8.14/test/simple/test-tls-sni-server-client.js @@ -0,0 +1,119 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + + + +if (!process.features.tls_sni) { + console.error('Skipping because node compiled without OpenSSL or ' + + 'with old OpenSSL version.'); + process.exit(0); +} + +var common = require('../common'), + assert = require('assert'), + fs = require('fs'), + tls = require('tls'); + +function filenamePEM(n) { + return require('path').join(common.fixturesDir, 'keys', n + '.pem'); +} + +function loadPEM(n) { + return fs.readFileSync(filenamePEM(n)); +} + +var serverOptions = { + key: loadPEM('agent2-key'), + cert: loadPEM('agent2-cert') +}; + +var SNIContexts = { + 'a.example.com': { + key: loadPEM('agent1-key'), + cert: loadPEM('agent1-cert') + }, + 'asterisk.test.com': { + key: loadPEM('agent3-key'), + cert: loadPEM('agent3-cert') + } +}; + +var serverPort = common.PORT; + +var clientsOptions = [{ + port: serverPort, + key: loadPEM('agent1-key'), + cert: loadPEM('agent1-cert'), + ca: [loadPEM('ca1-cert')], + servername: 'a.example.com' +},{ + port: serverPort, + key: loadPEM('agent2-key'), + cert: loadPEM('agent2-cert'), + ca: [loadPEM('ca2-cert')], + servername: 'b.test.com' +},{ + port: serverPort, + key: loadPEM('agent3-key'), + cert: loadPEM('agent3-cert'), + ca: [loadPEM('ca1-cert')], + servername: 'c.wrong.com' +}]; + +var serverResults = [], + clientResults = []; + +var server = tls.createServer(serverOptions, function(c) { + serverResults.push(c.servername); +}); + +server.addContext('a.example.com', SNIContexts['a.example.com']); +server.addContext('*.test.com', SNIContexts['asterisk.test.com']); + +server.listen(serverPort, startTest); + +function startTest() { + function connectClient(options, callback) { + var client = tls.connect(options, function() { + clientResults.push( + client.authorizationError && + /Hostname\/IP doesn't/.test(client.authorizationError)); + client.destroy(); + + callback(); + }); + }; + + connectClient(clientsOptions[0], function() { + connectClient(clientsOptions[1], function() { + connectClient(clientsOptions[2], function() { + server.close(); + }); + }); + }); +} + +process.on('exit', function() { + assert.deepEqual(serverResults, ['a.example.com', 'b.test.com', + 'c.wrong.com']); + assert.deepEqual(clientResults, [true, true, false]); +}); diff --git a/node-v0.8.14/test/simple/test-tty-stdout-end.js b/node-v0.8.14/test/simple/test-tty-stdout-end.js new file mode 100644 index 0000000..1fc2790 --- /dev/null +++ b/node-v0.8.14/test/simple/test-tty-stdout-end.js @@ -0,0 +1,36 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// Can't test this when 'make test' doesn't assign a tty to the stdout. +var common = require('../common'); +var assert = require('assert'); + +var exceptionCaught = false; + +try { + process.stdout.end(); +} catch (e) { + exceptionCaught = true; + assert.ok(common.isError(e)); + assert.equal('process.stdout cannot be closed.', e.message); +} + +assert.ok(exceptionCaught); diff --git a/node-v0.8.14/test/simple/test-tty-wrap.js b/node-v0.8.14/test/simple/test-tty-wrap.js new file mode 100644 index 0000000..da661c4 --- /dev/null +++ b/node-v0.8.14/test/simple/test-tty-wrap.js @@ -0,0 +1,52 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); + +var TTY = process.binding('tty_wrap').TTY; +var isTTY = process.binding('tty_wrap').isTTY; + +if (isTTY(1) == false) { + console.error('fd 1 is not a tty. skipping test.'); + process.exit(0); +} + +var handle = new TTY(1); +var callbacks = 0; + +var req1 = handle.write(Buffer('hello world\n')); +req1.oncomplete = function() { + callbacks++; +}; + +var req2 = handle.write(Buffer('hello world\n')); +req2.oncomplete = function() { + callbacks++; +}; + +handle.close(); + +process.on('exit', function() { + assert.equal(2, callbacks); +}); + + diff --git a/node-v0.8.14/test/simple/test-typed-arrays.js b/node-v0.8.14/test/simple/test-typed-arrays.js new file mode 100644 index 0000000..00bf613 --- /dev/null +++ b/node-v0.8.14/test/simple/test-typed-arrays.js @@ -0,0 +1,184 @@ +// Copyright Joyent, Inc. and other Node contributors. + +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: + +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. + +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +/* + * Test to verify we are using Typed Arrays + * (http://www.khronos.org/registry/typedarray/specs/latest/) correctly Test to + * verify Buffer can used in Typed Arrays + */ + +var common = require('../common'); +var assert = require('assert'); + +[ + 'ArrayBuffer', + 'Int8Array', + 'Uint8Array', + 'Int16Array', + 'Uint16Array', + 'Int32Array', + 'Uint32Array', + 'Float32Array', + 'Float64Array', + 'Uint8ClampedArray' +].forEach(function(name) { + var expected = '[object ' + name + ']'; + var clazz = global[name]; + var obj = new clazz(1); + + assert.equal(obj.toString(), expected); + assert.equal(Object.prototype.toString.call(obj), expected); + + obj = new DataView(obj); + assert.equal(obj.toString(), '[object DataView]'); + assert.equal(Object.prototype.toString.call(obj), '[object DataView]'); +}); + +// initialize a zero-filled buffer +var buffer = new Buffer(16); +buffer.fill(0); + +// only one of these instantiations should succeed, as the other ones will be +// unaligned +var errors = 0; +var offset; +for (var i = 0; i < 8; i++) { + try { + new Float64Array(buffer, i); + offset = i; + } catch (e) { + errors += 1; + } +} + +assert.equal(errors, 7); + +var uint8 = new Uint8Array(buffer, offset); +var uint16 = new Uint16Array(buffer, offset); +var uint16slice = new Uint16Array(buffer, offset + 2, 2); +var uint32 = new Uint32Array(buffer, offset); + +assert.equal(uint8.BYTES_PER_ELEMENT, 1); +assert.equal(uint16.BYTES_PER_ELEMENT, 2); +assert.equal(uint16slice.BYTES_PER_ELEMENT, 2); +assert.equal(uint32.BYTES_PER_ELEMENT, 4); + +// now change the underlying buffer +buffer[offset ] = 0x08; +buffer[offset + 1] = 0x09; +buffer[offset + 2] = 0x0a; +buffer[offset + 3] = 0x0b; +buffer[offset + 4] = 0x0c; +buffer[offset + 5] = 0x0d; +buffer[offset + 6] = 0x0e; +buffer[offset + 7] = 0x0f; + +/* + This is what we expect the variables to look like at this point (on + little-endian machines): + + uint8 | 0x08 | 0x09 | 0x0a | 0x0b | 0x0c | 0x0d | 0x0e | 0x0f | + uint16 | 0x0908 | 0x0b0a | 0x0d0c | 0x0f0e | + uint16slice --------------| 0x0b0a | 0x0d0c |-------------- + uint32 | 0x0b0a0908 | 0x0f0e0d0c | +*/ + +assert.equal(uint8[0], 0x08); +assert.equal(uint8[1], 0x09); +assert.equal(uint8[2], 0x0a); +assert.equal(uint8[3], 0x0b); +assert.equal(uint8[4], 0x0c); +assert.equal(uint8[5], 0x0d); +assert.equal(uint8[6], 0x0e); +assert.equal(uint8[7], 0x0f); + +// determine whether or not typed array values are stored little-endian first +// internally +var IS_LITTLE_ENDIAN = (new Uint16Array([0x1234])).buffer[0] === 0x34; + +if (IS_LITTLE_ENDIAN) { + assert.equal(uint16[0], 0x0908); + assert.equal(uint16[1], 0x0b0a); + assert.equal(uint16[2], 0x0d0c); + assert.equal(uint16[3], 0x0f0e); + + assert.equal(uint16slice[0], 0x0b0a); + assert.equal(uint16slice[1], 0x0d0c); + + assert.equal(uint32[0], 0x0b0a0908); + assert.equal(uint32[1], 0x0f0e0d0c); +} else { + assert.equal(uint16[0], 0x0809); + assert.equal(uint16[1], 0x0a0b); + assert.equal(uint16[2], 0x0c0d); + assert.equal(uint16[3], 0x0e0f); + + assert.equal(uint16slice[0], 0x0a0b); + assert.equal(uint16slice[1], 0x0c0d); + + assert.equal(uint32[0], 0x08090a0b); + assert.equal(uint32[1], 0x0c0d0e0f); +} + +// test .subarray(begin, end) +var sub = uint8.subarray(2, 4); + +assert.ok(sub instanceof Uint8Array); +assert.equal(sub[0], 0x0a); +assert.equal(sub[1], 0x0b); + +// modifications of a value in the subarray of `uint8` should propagate to +// the other views +sub[0] = 0x12; +sub[1] = 0x34; + +assert.equal(uint8[2], 0x12); +assert.equal(uint8[3], 0x34); + +// test .set(index, value), .set(arr, offset) and .get(index) +uint8.set(1, 0x09); +uint8.set([0x0a, 0x0b], 2); + +assert.equal(uint8.get(1), 0x09); +assert.equal(uint8.get(2), 0x0a); +assert.equal(uint8.get(3), 0x0b); + +// test clamped array +var uint8c = new Uint8ClampedArray(buffer); +uint8c[0] = -1; +uint8c[1] = 257; + +assert.equal(uint8c[0], 0); +assert.equal(uint8c[1], 255); + +uint8c.set(0, -10); +uint8c.set(1, 260); + +assert.equal(uint8c[0], 0); +assert.equal(uint8c[1], 255); + +(function() { + var numbers = []; + for (var i = 128; i <= 255; ++i) numbers.push(i); + var array = new Uint8Array(numbers); + var view = new DataView(array.buffer); + for (var i = 128; i <= 255; ++i) assert.equal(view.getInt8(i - 128), i - 256); +})(); diff --git a/node-v0.8.14/test/simple/test-umask.js b/node-v0.8.14/test/simple/test-umask.js new file mode 100644 index 0000000..a41c46b --- /dev/null +++ b/node-v0.8.14/test/simple/test-umask.js @@ -0,0 +1,41 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); + +// Note in Windows one can only set the "user" bits. +var mask; +if (process.platform == 'win32') { + mask = '0600'; +} else { + mask = '0664'; +} + +var old = process.umask(mask); + +assert.equal(parseInt(mask, 8), process.umask(old)); + +// confirm reading the umask does not modify it. +// 1. If the test fails, this call will succeed, but the mask will be set to 0 +assert.equal(old, process.umask()); +// 2. If the test fails, process.umask() will return 0 +assert.equal(old, process.umask()); diff --git a/node-v0.8.14/test/simple/test-url.js b/node-v0.8.14/test/simple/test-url.js new file mode 100644 index 0000000..764a541 --- /dev/null +++ b/node-v0.8.14/test/simple/test-url.js @@ -0,0 +1,1374 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); + +var url = require('url'), + util = require('util'); + +// URLs to parse, and expected data +// { url : parsed } +var parseTests = { + '//some_path' : { + 'href': '//some_path', + 'pathname': '//some_path', + 'path': '//some_path' + }, + + 'HTTP://www.example.com/' : { + 'href': 'http://www.example.com/', + 'protocol': 'http:', + 'slashes': true, + 'host': 'www.example.com', + 'hostname': 'www.example.com', + 'pathname': '/', + 'path': '/' + }, + + 'http://www.ExAmPlE.com/' : { + 'href': 'http://www.example.com/', + 'protocol': 'http:', + 'slashes': true, + 'host': 'www.example.com', + 'hostname': 'www.example.com', + 'pathname': '/', + 'path': '/' + }, + + 'http://user:pw@www.ExAmPlE.com/' : { + 'href': 'http://user:pw@www.example.com/', + 'protocol': 'http:', + 'slashes': true, + 'auth': 'user:pw', + 'host': 'www.example.com', + 'hostname': 'www.example.com', + 'pathname': '/', + 'path': '/' + }, + + 'http://USER:PW@www.ExAmPlE.com/' : { + 'href': 'http://USER:PW@www.example.com/', + 'protocol': 'http:', + 'slashes': true, + 'auth': 'USER:PW', + 'host': 'www.example.com', + 'hostname': 'www.example.com', + 'pathname': '/', + 'path': '/' + }, + + 'http://user@www.example.com/' : { + 'href': 'http://user@www.example.com/', + 'protocol': 'http:', + 'slashes': true, + 'auth': 'user', + 'host': 'www.example.com', + 'hostname': 'www.example.com', + 'pathname': '/', + 'path': '/' + }, + + 'http://user%3Apw@www.example.com/' : { + 'href': 'http://user:pw@www.example.com/', + 'protocol': 'http:', + 'slashes': true, + 'auth': 'user:pw', + 'host': 'www.example.com', + 'hostname': 'www.example.com', + 'pathname': '/', + 'path': '/' + }, + + 'http://x.com/path?that\'s#all, folks' : { + 'href': 'http://x.com/path?that%27s#all,%20folks', + 'protocol': 'http:', + 'slashes': true, + 'host': 'x.com', + 'hostname': 'x.com', + 'search': '?that%27s', + 'query': 'that%27s', + 'pathname': '/path', + 'hash': '#all,%20folks', + 'path': '/path?that%27s' + }, + + 'HTTP://X.COM/Y' : { + 'href': 'http://x.com/Y', + 'protocol': 'http:', + 'slashes': true, + 'host': 'x.com', + 'hostname': 'x.com', + 'pathname': '/Y', + 'path': '/Y' + }, + + // an unexpected invalid char in the hostname. + 'HtTp://x.y.cOm*a/b/c?d=e#f gi' : { + 'href': 'http://x.y.com/*a/b/c?d=e#f%20g%3Ch%3Ei', + 'protocol': 'http:', + 'slashes': true, + 'host': 'x.y.com', + 'hostname': 'x.y.com', + 'pathname': '/*a/b/c', + 'search': '?d=e', + 'query': 'd=e', + 'hash': '#f%20g%3Ch%3Ei', + 'path': '/*a/b/c?d=e' + }, + + // make sure that we don't accidentally lcast the path parts. + 'HtTp://x.y.cOm*A/b/c?d=e#f gi' : { + 'href': 'http://x.y.com/*A/b/c?d=e#f%20g%3Ch%3Ei', + 'protocol': 'http:', + 'slashes': true, + 'host': 'x.y.com', + 'hostname': 'x.y.com', + 'pathname': '/*A/b/c', + 'search': '?d=e', + 'query': 'd=e', + 'hash': '#f%20g%3Ch%3Ei', + 'path': '/*A/b/c?d=e' + }, + + 'http://x...y...#p': { + 'href': 'http://x...y.../#p', + 'protocol': 'http:', + 'slashes': true, + 'host': 'x...y...', + 'hostname': 'x...y...', + 'hash': '#p', + 'pathname': '/', + 'path': '/' + }, + + 'http://x/p/"quoted"': { + 'href': 'http://x/p/%22quoted%22', + 'protocol': 'http:', + 'slashes': true, + 'host': 'x', + 'hostname': 'x', + 'pathname': '/p/%22quoted%22', + 'path': '/p/%22quoted%22' + }, + + ' Is a URL!': { + 'href': '%3Chttp://goo.corn/bread%3E%20Is%20a%20URL!', + 'pathname': '%3Chttp://goo.corn/bread%3E%20Is%20a%20URL!', + 'path': '%3Chttp://goo.corn/bread%3E%20Is%20a%20URL!' + }, + + 'http://www.narwhaljs.org/blog/categories?id=news' : { + 'href': 'http://www.narwhaljs.org/blog/categories?id=news', + 'protocol': 'http:', + 'slashes': true, + 'host': 'www.narwhaljs.org', + 'hostname': 'www.narwhaljs.org', + 'search': '?id=news', + 'query': 'id=news', + 'pathname': '/blog/categories', + 'path': '/blog/categories?id=news' + }, + + 'http://mt0.google.com/vt/lyrs=m@114&hl=en&src=api&x=2&y=2&z=3&s=' : { + 'href': 'http://mt0.google.com/vt/lyrs=m@114&hl=en&src=api&x=2&y=2&z=3&s=', + 'protocol': 'http:', + 'slashes': true, + 'host': 'mt0.google.com', + 'hostname': 'mt0.google.com', + 'pathname': '/vt/lyrs=m@114&hl=en&src=api&x=2&y=2&z=3&s=', + 'path': '/vt/lyrs=m@114&hl=en&src=api&x=2&y=2&z=3&s=' + }, + + 'http://mt0.google.com/vt/lyrs=m@114???&hl=en&src=api&x=2&y=2&z=3&s=' : { + 'href': 'http://mt0.google.com/vt/lyrs=m@114???&hl=en&src=api' + + '&x=2&y=2&z=3&s=', + 'protocol': 'http:', + 'slashes': true, + 'host': 'mt0.google.com', + 'hostname': 'mt0.google.com', + 'search': '???&hl=en&src=api&x=2&y=2&z=3&s=', + 'query': '??&hl=en&src=api&x=2&y=2&z=3&s=', + 'pathname': '/vt/lyrs=m@114', + 'path': '/vt/lyrs=m@114???&hl=en&src=api&x=2&y=2&z=3&s=' + }, + + 'http://user:pass@mt0.google.com/vt/lyrs=m@114???&hl=en&src=api&x=2&y=2&z=3&s=': + { + 'href': 'http://user:pass@mt0.google.com/vt/lyrs=m@114???' + + '&hl=en&src=api&x=2&y=2&z=3&s=', + 'protocol': 'http:', + 'slashes': true, + 'host': 'mt0.google.com', + 'auth': 'user:pass', + 'hostname': 'mt0.google.com', + 'search': '???&hl=en&src=api&x=2&y=2&z=3&s=', + 'query': '??&hl=en&src=api&x=2&y=2&z=3&s=', + 'pathname': '/vt/lyrs=m@114', + 'path': '/vt/lyrs=m@114???&hl=en&src=api&x=2&y=2&z=3&s=' + }, + + 'file:///etc/passwd' : { + 'href': 'file:///etc/passwd', + 'slashes': true, + 'protocol': 'file:', + 'pathname': '/etc/passwd', + 'hostname': '', + 'host': '', + 'path': '/etc/passwd' + }, + + 'file://localhost/etc/passwd' : { + 'href': 'file://localhost/etc/passwd', + 'protocol': 'file:', + 'slashes': true, + 'pathname': '/etc/passwd', + 'hostname': 'localhost', + 'host': 'localhost', + 'path': '/etc/passwd' + }, + + 'file://foo/etc/passwd' : { + 'href': 'file://foo/etc/passwd', + 'protocol': 'file:', + 'slashes': true, + 'pathname': '/etc/passwd', + 'hostname': 'foo', + 'host': 'foo', + 'path': '/etc/passwd' + }, + + 'file:///etc/node/' : { + 'href': 'file:///etc/node/', + 'slashes': true, + 'protocol': 'file:', + 'pathname': '/etc/node/', + 'hostname': '', + 'host': '', + 'path': '/etc/node/' + }, + + 'file://localhost/etc/node/' : { + 'href': 'file://localhost/etc/node/', + 'protocol': 'file:', + 'slashes': true, + 'pathname': '/etc/node/', + 'hostname': 'localhost', + 'host': 'localhost', + 'path': '/etc/node/' + }, + + 'file://foo/etc/node/' : { + 'href': 'file://foo/etc/node/', + 'protocol': 'file:', + 'slashes': true, + 'pathname': '/etc/node/', + 'hostname': 'foo', + 'host': 'foo', + 'path': '/etc/node/' + }, + + 'http:/baz/../foo/bar' : { + 'href': 'http:/baz/../foo/bar', + 'protocol': 'http:', + 'pathname': '/baz/../foo/bar', + 'path': '/baz/../foo/bar' + }, + + 'http://user:pass@example.com:8000/foo/bar?baz=quux#frag' : { + 'href': 'http://user:pass@example.com:8000/foo/bar?baz=quux#frag', + 'protocol': 'http:', + 'slashes': true, + 'host': 'example.com:8000', + 'auth': 'user:pass', + 'port': '8000', + 'hostname': 'example.com', + 'hash': '#frag', + 'search': '?baz=quux', + 'query': 'baz=quux', + 'pathname': '/foo/bar', + 'path': '/foo/bar?baz=quux' + }, + + '//user:pass@example.com:8000/foo/bar?baz=quux#frag' : { + 'href': '//user:pass@example.com:8000/foo/bar?baz=quux#frag', + 'slashes': true, + 'host': 'example.com:8000', + 'auth': 'user:pass', + 'port': '8000', + 'hostname': 'example.com', + 'hash': '#frag', + 'search': '?baz=quux', + 'query': 'baz=quux', + 'pathname': '/foo/bar', + 'path': '/foo/bar?baz=quux' + }, + + '/foo/bar?baz=quux#frag' : { + 'href': '/foo/bar?baz=quux#frag', + 'hash': '#frag', + 'search': '?baz=quux', + 'query': 'baz=quux', + 'pathname': '/foo/bar', + 'path': '/foo/bar?baz=quux' + }, + + 'http:/foo/bar?baz=quux#frag' : { + 'href': 'http:/foo/bar?baz=quux#frag', + 'protocol': 'http:', + 'hash': '#frag', + 'search': '?baz=quux', + 'query': 'baz=quux', + 'pathname': '/foo/bar', + 'path': '/foo/bar?baz=quux' + }, + + 'mailto:foo@bar.com?subject=hello' : { + 'href': 'mailto:foo@bar.com?subject=hello', + 'protocol': 'mailto:', + 'host': 'bar.com', + 'auth' : 'foo', + 'hostname' : 'bar.com', + 'search': '?subject=hello', + 'query': 'subject=hello', + 'path': '?subject=hello' + }, + + 'javascript:alert(\'hello\');' : { + 'href': 'javascript:alert(\'hello\');', + 'protocol': 'javascript:', + 'pathname': 'alert(\'hello\');', + 'path': 'alert(\'hello\');' + }, + + 'xmpp:isaacschlueter@jabber.org' : { + 'href': 'xmpp:isaacschlueter@jabber.org', + 'protocol': 'xmpp:', + 'host': 'jabber.org', + 'auth': 'isaacschlueter', + 'hostname': 'jabber.org' + }, + + 'http://atpass:foo%40bar@127.0.0.1:8080/path?search=foo#bar' : { + 'href' : 'http://atpass:foo%40bar@127.0.0.1:8080/path?search=foo#bar', + 'protocol' : 'http:', + 'slashes': true, + 'host' : '127.0.0.1:8080', + 'auth' : 'atpass:foo@bar', + 'hostname' : '127.0.0.1', + 'port' : '8080', + 'pathname': '/path', + 'search' : '?search=foo', + 'query' : 'search=foo', + 'hash' : '#bar', + 'path': '/path?search=foo' + }, + + 'svn+ssh://foo/bar': { + 'href': 'svn+ssh://foo/bar', + 'host': 'foo', + 'hostname': 'foo', + 'protocol': 'svn+ssh:', + 'pathname': '/bar', + 'path': '/bar', + 'slashes': true + }, + + 'dash-test://foo/bar': { + 'href': 'dash-test://foo/bar', + 'host': 'foo', + 'hostname': 'foo', + 'protocol': 'dash-test:', + 'pathname': '/bar', + 'path': '/bar', + 'slashes': true + }, + + 'dash-test:foo/bar': { + 'href': 'dash-test:foo/bar', + 'host': 'foo', + 'hostname': 'foo', + 'protocol': 'dash-test:', + 'pathname': '/bar', + 'path': '/bar' + }, + + 'dot.test://foo/bar': { + 'href': 'dot.test://foo/bar', + 'host': 'foo', + 'hostname': 'foo', + 'protocol': 'dot.test:', + 'pathname': '/bar', + 'path': '/bar', + 'slashes': true + }, + + 'dot.test:foo/bar': { + 'href': 'dot.test:foo/bar', + 'host': 'foo', + 'hostname': 'foo', + 'protocol': 'dot.test:', + 'pathname': '/bar', + 'path': '/bar' + }, + + // IDNA tests + 'http://www.日本語.com/' : { + 'href': 'http://www.xn--wgv71a119e.com/', + 'protocol': 'http:', + 'slashes': true, + 'host': 'www.xn--wgv71a119e.com', + 'hostname': 'www.xn--wgv71a119e.com', + 'pathname': '/', + 'path': '/' + }, + + 'http://example.Bücher.com/' : { + 'href': 'http://example.xn--bcher-kva.com/', + 'protocol': 'http:', + 'slashes': true, + 'host': 'example.xn--bcher-kva.com', + 'hostname': 'example.xn--bcher-kva.com', + 'pathname': '/', + 'path': '/' + }, + + 'http://www.Äffchen.com/' : { + 'href': 'http://www.xn--ffchen-9ta.com/', + 'protocol': 'http:', + 'slashes': true, + 'host': 'www.xn--ffchen-9ta.com', + 'hostname': 'www.xn--ffchen-9ta.com', + 'pathname': '/', + 'path': '/' + }, + + 'http://www.Äffchen.cOm*A/b/c?d=e#f gi' : { + 'href': 'http://www.xn--ffchen-9ta.com/*A/b/c?d=e#f%20g%3Ch%3Ei', + 'protocol': 'http:', + 'slashes': true, + 'host': 'www.xn--ffchen-9ta.com', + 'hostname': 'www.xn--ffchen-9ta.com', + 'pathname': '/*A/b/c', + 'search': '?d=e', + 'query': 'd=e', + 'hash': '#f%20g%3Ch%3Ei', + 'path': '/*A/b/c?d=e' + }, + + 'http://SÉLIER.COM/' : { + 'href': 'http://xn--slier-bsa.com/', + 'protocol': 'http:', + 'slashes': true, + 'host': 'xn--slier-bsa.com', + 'hostname': 'xn--slier-bsa.com', + 'pathname': '/', + 'path': '/' + }, + + 'http://ليهمابتكلموشعربي؟.ي؟/' : { + 'href': 'http://xn--egbpdaj6bu4bxfgehfvwxn.xn--egb9f/', + 'protocol': 'http:', + 'slashes': true, + 'host': 'xn--egbpdaj6bu4bxfgehfvwxn.xn--egb9f', + 'hostname': 'xn--egbpdaj6bu4bxfgehfvwxn.xn--egb9f', + 'pathname': '/', + 'path': '/' + }, + + 'http://➡.ws/➡' : { + 'href': 'http://xn--hgi.ws/➡', + 'protocol': 'http:', + 'slashes': true, + 'host': 'xn--hgi.ws', + 'hostname': 'xn--hgi.ws', + 'pathname': '/➡', + 'path': '/➡' + }, + + 'http://bucket_name.s3.amazonaws.com/image.jpg': { + protocol: 'http:', + 'slashes': true, + slashes: true, + host: 'bucket_name.s3.amazonaws.com', + hostname: 'bucket_name.s3.amazonaws.com', + pathname: '/image.jpg', + href: 'http://bucket_name.s3.amazonaws.com/image.jpg', + 'path': '/image.jpg' + }, + + 'git+http://github.com/joyent/node.git': { + protocol: 'git+http:', + slashes: true, + host: 'github.com', + hostname: 'github.com', + pathname: '/joyent/node.git', + path: '/joyent/node.git', + href: 'git+http://github.com/joyent/node.git' + }, + + //if local1@domain1 is uses as a relative URL it may + //be parse into auth@hostname, but here there is no + //way to make it work in url.parse, I add the test to be explicit + 'local1@domain1': { + 'pathname': 'local1@domain1', + 'path': 'local1@domain1', + 'href': 'local1@domain1' + }, + + //While this may seem counter-intuitive, a browser will parse + // as a path. + 'www.example.com' : { + 'href': 'www.example.com', + 'pathname': 'www.example.com', + 'path': 'www.example.com' + }, + + // ipv6 support + '[fe80::1]': { + 'href': '[fe80::1]', + 'pathname': '[fe80::1]', + 'path': '[fe80::1]' + }, + + 'coap://[FEDC:BA98:7654:3210:FEDC:BA98:7654:3210]': { + 'protocol': 'coap:', + 'slashes': true, + 'host': '[fedc:ba98:7654:3210:fedc:ba98:7654:3210]', + 'hostname': 'fedc:ba98:7654:3210:fedc:ba98:7654:3210', + 'href': 'coap://[fedc:ba98:7654:3210:fedc:ba98:7654:3210]/', + 'pathname': '/', + 'path': '/' + }, + + 'coap://[1080:0:0:0:8:800:200C:417A]:61616/': { + 'protocol': 'coap:', + 'slashes': true, + 'host': '[1080:0:0:0:8:800:200c:417a]:61616', + 'port': '61616', + 'hostname': '1080:0:0:0:8:800:200c:417a', + 'href': 'coap://[1080:0:0:0:8:800:200c:417a]:61616/', + 'pathname': '/', + 'path': '/' + }, + + 'http://user:password@[3ffe:2a00:100:7031::1]:8080': { + 'protocol': 'http:', + 'slashes': true, + 'auth': 'user:password', + 'host': '[3ffe:2a00:100:7031::1]:8080', + 'port': '8080', + 'hostname': '3ffe:2a00:100:7031::1', + 'href': 'http://user:password@[3ffe:2a00:100:7031::1]:8080/', + 'pathname': '/', + 'path': '/' + }, + + 'coap://u:p@[::192.9.5.5]:61616/.well-known/r?n=Temperature': { + 'protocol': 'coap:', + 'slashes': true, + 'auth': 'u:p', + 'host': '[::192.9.5.5]:61616', + 'port': '61616', + 'hostname': '::192.9.5.5', + 'href': 'coap://u:p@[::192.9.5.5]:61616/.well-known/r?n=Temperature', + 'search': '?n=Temperature', + 'query': 'n=Temperature', + 'pathname': '/.well-known/r', + 'path': '/.well-known/r?n=Temperature' + }, + + // empty port + 'http://example.com:': { + 'protocol': 'http:', + 'slashes': true, + 'host': 'example.com', + 'hostname': 'example.com', + 'href': 'http://example.com/', + 'pathname': '/', + 'path': '/' + }, + + 'http://example.com:/a/b.html': { + 'protocol': 'http:', + 'slashes': true, + 'host': 'example.com', + 'hostname': 'example.com', + 'href': 'http://example.com/a/b.html', + 'pathname': '/a/b.html', + 'path': '/a/b.html' + }, + + 'http://example.com:?a=b': { + 'protocol': 'http:', + 'slashes': true, + 'host': 'example.com', + 'hostname': 'example.com', + 'href': 'http://example.com/?a=b', + 'search': '?a=b', + 'query': 'a=b', + 'pathname': '/', + 'path': '/?a=b' + }, + + 'http://example.com:#abc': { + 'protocol': 'http:', + 'slashes': true, + 'host': 'example.com', + 'hostname': 'example.com', + 'href': 'http://example.com/#abc', + 'hash': '#abc', + 'pathname': '/', + 'path': '/' + }, + + 'http://[fe80::1]:/a/b?a=b#abc': { + 'protocol': 'http:', + 'slashes': true, + 'host': '[fe80::1]', + 'hostname': 'fe80::1', + 'href': 'http://[fe80::1]/a/b?a=b#abc', + 'search': '?a=b', + 'query': 'a=b', + 'hash': '#abc', + 'pathname': '/a/b', + 'path': '/a/b?a=b' + }, + + 'http://-lovemonsterz.tumblr.com/rss': { + 'protocol': 'http:', + 'slashes': true, + 'host': '-lovemonsterz.tumblr.com', + 'hostname': '-lovemonsterz.tumblr.com', + 'href': 'http://-lovemonsterz.tumblr.com/rss', + 'pathname': '/rss', + 'path': '/rss', + }, + + 'http://-lovemonsterz.tumblr.com:80/rss': { + 'protocol': 'http:', + 'slashes': true, + 'port': '80', + 'host': '-lovemonsterz.tumblr.com:80', + 'hostname': '-lovemonsterz.tumblr.com', + 'href': 'http://-lovemonsterz.tumblr.com:80/rss', + 'pathname': '/rss', + 'path': '/rss', + }, + + 'http://user:pass@-lovemonsterz.tumblr.com/rss': { + 'protocol': 'http:', + 'slashes': true, + 'auth': 'user:pass', + 'host': '-lovemonsterz.tumblr.com', + 'hostname': '-lovemonsterz.tumblr.com', + 'href': 'http://user:pass@-lovemonsterz.tumblr.com/rss', + 'pathname': '/rss', + 'path': '/rss', + }, + + 'http://user:pass@-lovemonsterz.tumblr.com:80/rss': { + 'protocol': 'http:', + 'slashes': true, + 'auth': 'user:pass', + 'port': '80', + 'host': '-lovemonsterz.tumblr.com:80', + 'hostname': '-lovemonsterz.tumblr.com', + 'href': 'http://user:pass@-lovemonsterz.tumblr.com:80/rss', + 'pathname': '/rss', + 'path': '/rss', + }, + + 'http://_jabber._tcp.google.com/test': { + 'protocol': 'http:', + 'slashes': true, + 'host': '_jabber._tcp.google.com', + 'hostname': '_jabber._tcp.google.com', + 'href': 'http://_jabber._tcp.google.com/test', + 'pathname': '/test', + 'path': '/test', + }, + + 'http://user:pass@_jabber._tcp.google.com/test': { + 'protocol': 'http:', + 'slashes': true, + 'auth': 'user:pass', + 'host': '_jabber._tcp.google.com', + 'hostname': '_jabber._tcp.google.com', + 'href': 'http://user:pass@_jabber._tcp.google.com/test', + 'pathname': '/test', + 'path': '/test', + }, + + 'http://_jabber._tcp.google.com:80/test': { + 'protocol': 'http:', + 'slashes': true, + 'port': '80', + 'host': '_jabber._tcp.google.com:80', + 'hostname': '_jabber._tcp.google.com', + 'href': 'http://_jabber._tcp.google.com:80/test', + 'pathname': '/test', + 'path': '/test', + }, + + 'http://user:pass@_jabber._tcp.google.com:80/test': { + 'protocol': 'http:', + 'slashes': true, + 'auth': 'user:pass', + 'port': '80', + 'host': '_jabber._tcp.google.com:80', + 'hostname': '_jabber._tcp.google.com', + 'href': 'http://user:pass@_jabber._tcp.google.com:80/test', + 'pathname': '/test', + 'path': '/test', + }, + +}; + +for (var u in parseTests) { + var actual = url.parse(u), + spaced = url.parse(' \t ' + u + '\n\t'); + expected = parseTests[u]; + + assert.deepEqual(actual, expected); + assert.deepEqual(spaced, expected); + + var expected = parseTests[u].href, + actual = url.format(parseTests[u]); + + assert.equal(actual, expected, + 'format(' + u + ') == ' + u + '\nactual:' + actual); +} + +var parseTestsWithQueryString = { + '/foo/bar?baz=quux#frag' : { + 'href': '/foo/bar?baz=quux#frag', + 'hash': '#frag', + 'search': '?baz=quux', + 'query': { + 'baz': 'quux' + }, + 'pathname': '/foo/bar', + 'path': '/foo/bar?baz=quux' + }, + 'http://example.com' : { + 'href': 'http://example.com/', + 'protocol': 'http:', + 'slashes': true, + 'host': 'example.com', + 'hostname': 'example.com', + 'query': {}, + 'search': '', + 'pathname': '/', + 'path': '/' + } +}; +for (var u in parseTestsWithQueryString) { + var actual = url.parse(u, true); + var expected = parseTestsWithQueryString[u]; + + assert.deepEqual(actual, expected); +} + +// some extra formatting tests, just to verify +// that it'll format slightly wonky content to a valid url. +var formatTests = { + 'http://example.com?' : { + 'href': 'http://example.com/?', + 'protocol': 'http:', + 'slashes': true, + 'host': 'example.com', + 'hostname': 'example.com', + 'search': '?', + 'query': {}, + 'pathname': '/' + }, + 'http://example.com?foo=bar#frag' : { + 'href': 'http://example.com/?foo=bar#frag', + 'protocol': 'http:', + 'host': 'example.com', + 'hostname': 'example.com', + 'hash': '#frag', + 'search': '?foo=bar', + 'query': 'foo=bar', + 'pathname': '/' + }, + 'http://example.com?foo=@bar#frag' : { + 'href': 'http://example.com/?foo=@bar#frag', + 'protocol': 'http:', + 'host': 'example.com', + 'hostname': 'example.com', + 'hash': '#frag', + 'search': '?foo=@bar', + 'query': 'foo=@bar', + 'pathname': '/' + }, + 'http://example.com?foo=/bar/#frag' : { + 'href': 'http://example.com/?foo=/bar/#frag', + 'protocol': 'http:', + 'host': 'example.com', + 'hostname': 'example.com', + 'hash': '#frag', + 'search': '?foo=/bar/', + 'query': 'foo=/bar/', + 'pathname': '/' + }, + 'http://example.com?foo=?bar/#frag' : { + 'href': 'http://example.com/?foo=?bar/#frag', + 'protocol': 'http:', + 'host': 'example.com', + 'hostname': 'example.com', + 'hash': '#frag', + 'search': '?foo=?bar/', + 'query': 'foo=?bar/', + 'pathname': '/' + }, + 'http://example.com#frag=?bar/#frag' : { + 'href': 'http://example.com/#frag=?bar/#frag', + 'protocol': 'http:', + 'host': 'example.com', + 'hostname': 'example.com', + 'hash': '#frag=?bar/#frag', + 'pathname': '/' + }, + 'http://google.com" onload="alert(42)/' : { + 'href': 'http://google.com/%22%20onload=%22alert(42)/', + 'protocol': 'http:', + 'host': 'google.com', + 'pathname': '/%22%20onload=%22alert(42)/' + }, + 'http://a.com/a/b/c?s#h' : { + 'href': 'http://a.com/a/b/c?s#h', + 'protocol': 'http', + 'host': 'a.com', + 'pathname': 'a/b/c', + 'hash': 'h', + 'search': 's' + }, + 'xmpp:isaacschlueter@jabber.org' : { + 'href': 'xmpp:isaacschlueter@jabber.org', + 'protocol': 'xmpp:', + 'host': 'jabber.org', + 'auth': 'isaacschlueter', + 'hostname': 'jabber.org' + }, + 'http://atpass:foo%40bar@127.0.0.1/' : { + 'href': 'http://atpass:foo%40bar@127.0.0.1/', + 'auth': 'atpass:foo@bar', + 'hostname': '127.0.0.1', + 'protocol': 'http:', + 'pathname': '/' + }, + 'http://atslash%2F%40:%2F%40@foo/' : { + 'href': 'http://atslash%2F%40:%2F%40@foo/', + 'auth': 'atslash/@:/@', + 'hostname': 'foo', + 'protocol': 'http:', + 'pathname': '/' + }, + 'svn+ssh://foo/bar': { + 'href': 'svn+ssh://foo/bar', + 'hostname': 'foo', + 'protocol': 'svn+ssh:', + 'pathname': '/bar', + 'slashes': true + }, + 'dash-test://foo/bar': { + 'href': 'dash-test://foo/bar', + 'hostname': 'foo', + 'protocol': 'dash-test:', + 'pathname': '/bar', + 'slashes': true + }, + 'dash-test:foo/bar': { + 'href': 'dash-test:foo/bar', + 'hostname': 'foo', + 'protocol': 'dash-test:', + 'pathname': '/bar' + }, + 'dot.test://foo/bar': { + 'href': 'dot.test://foo/bar', + 'hostname': 'foo', + 'protocol': 'dot.test:', + 'pathname': '/bar', + 'slashes': true + }, + 'dot.test:foo/bar': { + 'href': 'dot.test:foo/bar', + 'hostname': 'foo', + 'protocol': 'dot.test:', + 'pathname': '/bar' + }, + // ipv6 support + 'coap:u:p@[::1]:61616/.well-known/r?n=Temperature': { + 'href': 'coap:u:p@[::1]:61616/.well-known/r?n=Temperature', + 'protocol': 'coap:', + 'auth': 'u:p', + 'hostname': '::1', + 'port': '61616', + 'pathname': '/.well-known/r', + 'search': 'n=Temperature' + }, + 'coap:[fedc:ba98:7654:3210:fedc:ba98:7654:3210]:61616/s/stopButton': { + 'href': 'coap:[fedc:ba98:7654:3210:fedc:ba98:7654:3210]:61616/s/stopButton', + 'protocol': 'coap', + 'host': '[fedc:ba98:7654:3210:fedc:ba98:7654:3210]:61616', + 'pathname': '/s/stopButton' + } +}; +for (var u in formatTests) { + var expect = formatTests[u].href; + delete formatTests[u].href; + var actual = url.format(u); + var actualObj = url.format(formatTests[u]); + assert.equal(actual, expect, + 'wonky format(' + u + ') == ' + expect + + '\nactual:' + actual); + assert.equal(actualObj, expect, + 'wonky format(' + JSON.stringify(formatTests[u]) + + ') == ' + expect + + '\nactual: ' + actualObj); +} + +/* + [from, path, expected] +*/ +var relativeTests = [ + ['/foo/bar/baz', 'quux', '/foo/bar/quux'], + ['/foo/bar/baz', 'quux/asdf', '/foo/bar/quux/asdf'], + ['/foo/bar/baz', 'quux/baz', '/foo/bar/quux/baz'], + ['/foo/bar/baz', '../quux/baz', '/foo/quux/baz'], + ['/foo/bar/baz', '/bar', '/bar'], + ['/foo/bar/baz/', 'quux', '/foo/bar/baz/quux'], + ['/foo/bar/baz/', 'quux/baz', '/foo/bar/baz/quux/baz'], + ['/foo/bar/baz', '../../../../../../../../quux/baz', '/quux/baz'], + ['/foo/bar/baz', '../../../../../../../quux/baz', '/quux/baz'], + ['foo/bar', '../../../baz', '../../baz'], + ['foo/bar/', '../../../baz', '../baz'], + ['http://example.com/b//c//d;p?q#blarg', 'https:#hash2', 'https:///#hash2'], + ['http://example.com/b//c//d;p?q#blarg', + 'https:/p/a/t/h?s#hash2', + 'https://p/a/t/h?s#hash2'], + ['http://example.com/b//c//d;p?q#blarg', + 'https://u:p@h.com/p/a/t/h?s#hash2', + 'https://u:p@h.com/p/a/t/h?s#hash2'], + ['http://example.com/b//c//d;p?q#blarg', + 'https:/a/b/c/d', + 'https://a/b/c/d'], + ['http://example.com/b//c//d;p?q#blarg', + 'http:#hash2', + 'http://example.com/b//c//d;p?q#hash2'], + ['http://example.com/b//c//d;p?q#blarg', + 'http:/p/a/t/h?s#hash2', + 'http://example.com/p/a/t/h?s#hash2'], + ['http://example.com/b//c//d;p?q#blarg', + 'http://u:p@h.com/p/a/t/h?s#hash2', + 'http://u:p@h.com/p/a/t/h?s#hash2'], + ['http://example.com/b//c//d;p?q#blarg', + 'http:/a/b/c/d', + 'http://example.com/a/b/c/d'], + ['/foo/bar/baz', '/../etc/passwd', '/etc/passwd'] +]; +relativeTests.forEach(function(relativeTest) { + var a = url.resolve(relativeTest[0], relativeTest[1]), + e = relativeTest[2]; + assert.equal(a, e, + 'resolve(' + [relativeTest[0], relativeTest[1]] + ') == ' + e + + '\n actual=' + a); +}); + + +// https://github.com/joyent/node/issues/568 +[ + undefined, + null, + true, + false, + 0.0, + 0, + [], + {} +].forEach(function(val) { + assert.throws(function() { url.parse(val); }, TypeError); +}); + + +// +// Tests below taken from Chiron +// http://code.google.com/p/chironjs/source/browse/trunk/src/test/http/url.js +// +// Copyright (c) 2002-2008 Kris Kowal +// used with permission under MIT License +// +// Changes marked with @isaacs + +var bases = [ + 'http://a/b/c/d;p?q', + 'http://a/b/c/d;p?q=1/2', + 'http://a/b/c/d;p=1/2?q', + 'fred:///s//a/b/c', + 'http:///s//a/b/c' +]; + +//[to, from, result] +var relativeTests2 = [ + // http://lists.w3.org/Archives/Public/uri/2004Feb/0114.html + ['../c', 'foo:a/b', 'foo:c'], + ['foo:.', 'foo:a', 'foo:'], + ['/foo/../../../bar', 'zz:abc', 'zz:/bar'], + ['/foo/../bar', 'zz:abc', 'zz:/bar'], + // @isaacs Disagree. Not how web browsers resolve this. + ['foo/../../../bar', 'zz:abc', 'zz:bar'], + // ['foo/../../../bar', 'zz:abc', 'zz:../../bar'], // @isaacs Added + ['foo/../bar', 'zz:abc', 'zz:bar'], + ['zz:.', 'zz:abc', 'zz:'], + ['/.', bases[0], 'http://a/'], + ['/.foo', bases[0], 'http://a/.foo'], + ['.foo', bases[0], 'http://a/b/c/.foo'], + + // http://gbiv.com/protocols/uri/test/rel_examples1.html + // examples from RFC 2396 + ['g:h', bases[0], 'g:h'], + ['g', bases[0], 'http://a/b/c/g'], + ['./g', bases[0], 'http://a/b/c/g'], + ['g/', bases[0], 'http://a/b/c/g/'], + ['/g', bases[0], 'http://a/g'], + ['//g', bases[0], 'http://g/'], + // changed with RFC 2396bis + //('?y', bases[0], 'http://a/b/c/d;p?y'], + ['?y', bases[0], 'http://a/b/c/d;p?y'], + ['g?y', bases[0], 'http://a/b/c/g?y'], + // changed with RFC 2396bis + //('#s', bases[0], CURRENT_DOC_URI + '#s'], + ['#s', bases[0], 'http://a/b/c/d;p?q#s'], + ['g#s', bases[0], 'http://a/b/c/g#s'], + ['g?y#s', bases[0], 'http://a/b/c/g?y#s'], + [';x', bases[0], 'http://a/b/c/;x'], + ['g;x', bases[0], 'http://a/b/c/g;x'], + ['g;x?y#s' , bases[0], 'http://a/b/c/g;x?y#s'], + // changed with RFC 2396bis + //('', bases[0], CURRENT_DOC_URI], + ['', bases[0], 'http://a/b/c/d;p?q'], + ['.', bases[0], 'http://a/b/c/'], + ['./', bases[0], 'http://a/b/c/'], + ['..', bases[0], 'http://a/b/'], + ['../', bases[0], 'http://a/b/'], + ['../g', bases[0], 'http://a/b/g'], + ['../..', bases[0], 'http://a/'], + ['../../', bases[0], 'http://a/'], + ['../../g' , bases[0], 'http://a/g'], + ['../../../g', bases[0], ('http://a/../g', 'http://a/g')], + ['../../../../g', bases[0], ('http://a/../../g', 'http://a/g')], + // changed with RFC 2396bis + //('/./g', bases[0], 'http://a/./g'], + ['/./g', bases[0], 'http://a/g'], + // changed with RFC 2396bis + //('/../g', bases[0], 'http://a/../g'], + ['/../g', bases[0], 'http://a/g'], + ['g.', bases[0], 'http://a/b/c/g.'], + ['.g', bases[0], 'http://a/b/c/.g'], + ['g..', bases[0], 'http://a/b/c/g..'], + ['..g', bases[0], 'http://a/b/c/..g'], + ['./../g', bases[0], 'http://a/b/g'], + ['./g/.', bases[0], 'http://a/b/c/g/'], + ['g/./h', bases[0], 'http://a/b/c/g/h'], + ['g/../h', bases[0], 'http://a/b/c/h'], + ['g;x=1/./y', bases[0], 'http://a/b/c/g;x=1/y'], + ['g;x=1/../y', bases[0], 'http://a/b/c/y'], + ['g?y/./x', bases[0], 'http://a/b/c/g?y/./x'], + ['g?y/../x', bases[0], 'http://a/b/c/g?y/../x'], + ['g#s/./x', bases[0], 'http://a/b/c/g#s/./x'], + ['g#s/../x', bases[0], 'http://a/b/c/g#s/../x'], + ['http:g', bases[0], ('http:g', 'http://a/b/c/g')], + ['http:', bases[0], ('http:', bases[0])], + // not sure where this one originated + ['/a/b/c/./../../g', bases[0], 'http://a/a/g'], + + // http://gbiv.com/protocols/uri/test/rel_examples2.html + // slashes in base URI's query args + ['g', bases[1], 'http://a/b/c/g'], + ['./g', bases[1], 'http://a/b/c/g'], + ['g/', bases[1], 'http://a/b/c/g/'], + ['/g', bases[1], 'http://a/g'], + ['//g', bases[1], 'http://g/'], + // changed in RFC 2396bis + //('?y', bases[1], 'http://a/b/c/?y'], + ['?y', bases[1], 'http://a/b/c/d;p?y'], + ['g?y', bases[1], 'http://a/b/c/g?y'], + ['g?y/./x' , bases[1], 'http://a/b/c/g?y/./x'], + ['g?y/../x', bases[1], 'http://a/b/c/g?y/../x'], + ['g#s', bases[1], 'http://a/b/c/g#s'], + ['g#s/./x' , bases[1], 'http://a/b/c/g#s/./x'], + ['g#s/../x', bases[1], 'http://a/b/c/g#s/../x'], + ['./', bases[1], 'http://a/b/c/'], + ['../', bases[1], 'http://a/b/'], + ['../g', bases[1], 'http://a/b/g'], + ['../../', bases[1], 'http://a/'], + ['../../g' , bases[1], 'http://a/g'], + + // http://gbiv.com/protocols/uri/test/rel_examples3.html + // slashes in path params + // all of these changed in RFC 2396bis + ['g', bases[2], 'http://a/b/c/d;p=1/g'], + ['./g', bases[2], 'http://a/b/c/d;p=1/g'], + ['g/', bases[2], 'http://a/b/c/d;p=1/g/'], + ['g?y', bases[2], 'http://a/b/c/d;p=1/g?y'], + [';x', bases[2], 'http://a/b/c/d;p=1/;x'], + ['g;x', bases[2], 'http://a/b/c/d;p=1/g;x'], + ['g;x=1/./y', bases[2], 'http://a/b/c/d;p=1/g;x=1/y'], + ['g;x=1/../y', bases[2], 'http://a/b/c/d;p=1/y'], + ['./', bases[2], 'http://a/b/c/d;p=1/'], + ['../', bases[2], 'http://a/b/c/'], + ['../g', bases[2], 'http://a/b/c/g'], + ['../../', bases[2], 'http://a/b/'], + ['../../g' , bases[2], 'http://a/b/g'], + + // http://gbiv.com/protocols/uri/test/rel_examples4.html + // double and triple slash, unknown scheme + ['g:h', bases[3], 'g:h'], + ['g', bases[3], 'fred:///s//a/b/g'], + ['./g', bases[3], 'fred:///s//a/b/g'], + ['g/', bases[3], 'fred:///s//a/b/g/'], + ['/g', bases[3], 'fred:///g'], // may change to fred:///s//a/g + ['//g', bases[3], 'fred://g'], // may change to fred:///s//g + ['//g/x', bases[3], 'fred://g/x'], // may change to fred:///s//g/x + ['///g', bases[3], 'fred:///g'], + ['./', bases[3], 'fred:///s//a/b/'], + ['../', bases[3], 'fred:///s//a/'], + ['../g', bases[3], 'fred:///s//a/g'], + + ['../../', bases[3], 'fred:///s//'], + ['../../g' , bases[3], 'fred:///s//g'], + ['../../../g', bases[3], 'fred:///s/g'], + // may change to fred:///s//a/../../../g + ['../../../../g', bases[3], 'fred:///g'], + + // http://gbiv.com/protocols/uri/test/rel_examples5.html + // double and triple slash, well-known scheme + ['g:h', bases[4], 'g:h'], + ['g', bases[4], 'http:///s//a/b/g'], + ['./g', bases[4], 'http:///s//a/b/g'], + ['g/', bases[4], 'http:///s//a/b/g/'], + ['/g', bases[4], 'http:///g'], // may change to http:///s//a/g + ['//g', bases[4], 'http://g/'], // may change to http:///s//g + ['//g/x', bases[4], 'http://g/x'], // may change to http:///s//g/x + ['///g', bases[4], 'http:///g'], + ['./', bases[4], 'http:///s//a/b/'], + ['../', bases[4], 'http:///s//a/'], + ['../g', bases[4], 'http:///s//a/g'], + ['../../', bases[4], 'http:///s//'], + ['../../g' , bases[4], 'http:///s//g'], + // may change to http:///s//a/../../g + ['../../../g', bases[4], 'http:///s/g'], + // may change to http:///s//a/../../../g + ['../../../../g', bases[4], 'http:///g'], + + // from Dan Connelly's tests in http://www.w3.org/2000/10/swap/uripath.py + ['bar:abc', 'foo:xyz', 'bar:abc'], + ['../abc', 'http://example/x/y/z', 'http://example/x/abc'], + ['http://example/x/abc', 'http://example2/x/y/z', 'http://example/x/abc'], + ['../r', 'http://ex/x/y/z', 'http://ex/x/r'], + ['q/r', 'http://ex/x/y', 'http://ex/x/q/r'], + ['q/r#s', 'http://ex/x/y', 'http://ex/x/q/r#s'], + ['q/r#s/t', 'http://ex/x/y', 'http://ex/x/q/r#s/t'], + ['ftp://ex/x/q/r', 'http://ex/x/y', 'ftp://ex/x/q/r'], + ['', 'http://ex/x/y', 'http://ex/x/y'], + ['', 'http://ex/x/y/', 'http://ex/x/y/'], + ['', 'http://ex/x/y/pdq', 'http://ex/x/y/pdq'], + ['z/', 'http://ex/x/y/', 'http://ex/x/y/z/'], + ['#Animal', + 'file:/swap/test/animal.rdf', + 'file:/swap/test/animal.rdf#Animal'], + ['../abc', 'file:/e/x/y/z', 'file:/e/x/abc'], + ['/example/x/abc', 'file:/example2/x/y/z', 'file:/example/x/abc'], + ['../r', 'file:/ex/x/y/z', 'file:/ex/x/r'], + ['/r', 'file:/ex/x/y/z', 'file:/r'], + ['q/r', 'file:/ex/x/y', 'file:/ex/x/q/r'], + ['q/r#s', 'file:/ex/x/y', 'file:/ex/x/q/r#s'], + ['q/r#', 'file:/ex/x/y', 'file:/ex/x/q/r#'], + ['q/r#s/t', 'file:/ex/x/y', 'file:/ex/x/q/r#s/t'], + ['ftp://ex/x/q/r', 'file:/ex/x/y', 'ftp://ex/x/q/r'], + ['', 'file:/ex/x/y', 'file:/ex/x/y'], + ['', 'file:/ex/x/y/', 'file:/ex/x/y/'], + ['', 'file:/ex/x/y/pdq', 'file:/ex/x/y/pdq'], + ['z/', 'file:/ex/x/y/', 'file:/ex/x/y/z/'], + ['file://meetings.example.com/cal#m1', + 'file:/devel/WWW/2000/10/swap/test/reluri-1.n3', + 'file://meetings.example.com/cal#m1'], + ['file://meetings.example.com/cal#m1', + 'file:/home/connolly/w3ccvs/WWW/2000/10/swap/test/reluri-1.n3', + 'file://meetings.example.com/cal#m1'], + ['./#blort', 'file:/some/dir/foo', 'file:/some/dir/#blort'], + ['./#', 'file:/some/dir/foo', 'file:/some/dir/#'], + // Ryan Lee + ['./', 'http://example/x/abc.efg', 'http://example/x/'], + + + // Graham Klyne's tests + // http://www.ninebynine.org/Software/HaskellUtils/Network/UriTest.xls + // 01-31 are from Connelly's cases + + // 32-49 + ['./q:r', 'http://ex/x/y', 'http://ex/x/q:r'], + ['./p=q:r', 'http://ex/x/y', 'http://ex/x/p=q:r'], + ['?pp/rr', 'http://ex/x/y?pp/qq', 'http://ex/x/y?pp/rr'], + ['y/z', 'http://ex/x/y?pp/qq', 'http://ex/x/y/z'], + ['local/qual@domain.org#frag', + 'mailto:local', + 'mailto:local/qual@domain.org#frag'], + ['more/qual2@domain2.org#frag', + 'mailto:local/qual1@domain1.org', + 'mailto:local/more/qual2@domain2.org#frag'], + ['y?q', 'http://ex/x/y?q', 'http://ex/x/y?q'], + ['/x/y?q', 'http://ex?p', 'http://ex/x/y?q'], + ['c/d', 'foo:a/b', 'foo:a/c/d'], + ['/c/d', 'foo:a/b', 'foo:/c/d'], + ['', 'foo:a/b?c#d', 'foo:a/b?c'], + ['b/c', 'foo:a', 'foo:b/c'], + ['../b/c', 'foo:/a/y/z', 'foo:/a/b/c'], + ['./b/c', 'foo:a', 'foo:b/c'], + ['/./b/c', 'foo:a', 'foo:/b/c'], + ['../../d', 'foo://a//b/c', 'foo://a/d'], + ['.', 'foo:a', 'foo:'], + ['..', 'foo:a', 'foo:'], + + // 50-57[cf. TimBL comments -- + // http://lists.w3.org/Archives/Public/uri/2003Feb/0028.html, + // http://lists.w3.org/Archives/Public/uri/2003Jan/0008.html) + ['abc', 'http://example/x/y%2Fz', 'http://example/x/abc'], + ['../../x%2Fabc', 'http://example/a/x/y/z', 'http://example/a/x%2Fabc'], + ['../x%2Fabc', 'http://example/a/x/y%2Fz', 'http://example/a/x%2Fabc'], + ['abc', 'http://example/x%2Fy/z', 'http://example/x%2Fy/abc'], + ['q%3Ar', 'http://ex/x/y', 'http://ex/x/q%3Ar'], + ['/x%2Fabc', 'http://example/x/y%2Fz', 'http://example/x%2Fabc'], + ['/x%2Fabc', 'http://example/x/y/z', 'http://example/x%2Fabc'], + ['/x%2Fabc', 'http://example/x/y%2Fz', 'http://example/x%2Fabc'], + + // 70-77 + ['local2@domain2', 'mailto:local1@domain1?query1', 'mailto:local2@domain2'], + ['local2@domain2?query2', + 'mailto:local1@domain1', + 'mailto:local2@domain2?query2'], + ['local2@domain2?query2', + 'mailto:local1@domain1?query1', + 'mailto:local2@domain2?query2'], + ['?query2', 'mailto:local@domain?query1', 'mailto:local@domain?query2'], + ['local@domain?query2', 'mailto:?query1', 'mailto:local@domain?query2'], + ['?query2', 'mailto:local@domain?query1', 'mailto:local@domain?query2'], + ['http://example/a/b?c/../d', 'foo:bar', 'http://example/a/b?c/../d'], + ['http://example/a/b#c/../d', 'foo:bar', 'http://example/a/b#c/../d'], + + // 82-88 + // @isaacs Disagree. Not how browsers do it. + // ['http:this', 'http://example.org/base/uri', 'http:this'], + // @isaacs Added + ['http:this', 'http://example.org/base/uri', 'http://example.org/base/this'], + ['http:this', 'http:base', 'http:this'], + ['.//g', 'f:/a', 'f://g'], + ['b/c//d/e', 'f://example.org/base/a', 'f://example.org/base/b/c//d/e'], + ['m2@example.ord/c2@example.org', + 'mid:m@example.ord/c@example.org', + 'mid:m@example.ord/m2@example.ord/c2@example.org'], + ['mini1.xml', + 'file:///C:/DEV/Haskell/lib/HXmlToolbox-3.01/examples/', + 'file:///C:/DEV/Haskell/lib/HXmlToolbox-3.01/examples/mini1.xml'], + ['../b/c', 'foo:a/y/z', 'foo:a/b/c'], + + //changeing auth + ['http://diff:auth@www.example.com', + 'http://asdf:qwer@www.example.com', + 'http://diff:auth@www.example.com/'] +]; +relativeTests2.forEach(function(relativeTest) { + var a = url.resolve(relativeTest[1], relativeTest[0]), + e = relativeTest[2]; + assert.equal(a, e, + 'resolve(' + [relativeTest[1], relativeTest[0]] + ') == ' + e + + '\n actual=' + a); +}); + +//if format and parse are inverse operations then +//resolveObject(parse(x), y) == parse(resolve(x, y)) + +//host and hostname are special, in this case a '' value is important +var emptyIsImportant = {'host': true, 'hostname': ''}; + +//format: [from, path, expected] +relativeTests.forEach(function(relativeTest) { + var actual = url.resolveObject(url.parse(relativeTest[0]), relativeTest[1]), + expected = url.parse(relativeTest[2]); + + //because of evaluation order + //resolveObject(parse(x), y) == parse(resolve(x, y)) will differ by + //false-ish values. remove all except host and hostname + for (var i in actual) { + if (actual[i] === undefined || + (!emptyIsImportant.hasOwnProperty(i) && !actual[i])) { + delete actual[i]; + } + } + + assert.deepEqual(actual, expected); + + expected = relativeTest[2]; + actual = url.format(actual); + + assert.equal(actual, expected, + 'format(' + actual + ') == ' + expected + '\nactual:' + actual); +}); + +//format: [to, from, result] +// the test: ['.//g', 'f:/a', 'f://g'] is a fundimental problem +// url.parse('f:/a') does not have a host +// url.resolve('f:/a', './/g') does not have a host becuase you have moved +// down to the g directory. i.e. f: //g, however when this url is parsed +// f:// will indicate that the host is g which is not the case. +// it is unclear to me how to keep this information from being lost +// it may be that a pathname of ////g should colapse to /g but this seems +// to be a lot of work for an edge case. Right now I remove the test +if (relativeTests2[181][0] === './/g' && + relativeTests2[181][1] === 'f:/a' && + relativeTests2[181][2] === 'f://g') { + relativeTests2.splice(181, 1); +} +relativeTests2.forEach(function(relativeTest) { + var actual = url.resolveObject(url.parse(relativeTest[1]), relativeTest[0]), + expected = url.parse(relativeTest[2]); + + //because of evaluation order + //resolveObject(parse(x), y) == parse(resolve(x, y)) will differ by + //false-ish values. remove all except host and hostname + for (var i in actual) { + if (actual[i] === undefined || + (!emptyIsImportant.hasOwnProperty(i) && !actual[i])) { + delete actual[i]; + } + } + + assert.deepEqual(actual, expected); + + var expected = relativeTest[2], + actual = url.format(actual); + + assert.equal(actual, expected, + 'format(' + relativeTest[1] + ') == ' + expected + + '\nactual:' + actual); +}); diff --git a/node-v0.8.14/test/simple/test-utf8-scripts.js b/node-v0.8.14/test/simple/test-utf8-scripts.js new file mode 100644 index 0000000..4639304 --- /dev/null +++ b/node-v0.8.14/test/simple/test-utf8-scripts.js @@ -0,0 +1,30 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); + +// üäö + +console.log('Σὲ γνωρίζω ἀπὸ τὴν κόψη'); + +assert.equal(true, /Hellö Wörld/.test('Hellö Wörld')); + diff --git a/node-v0.8.14/test/simple/test-util-format.js b/node-v0.8.14/test/simple/test-util-format.js new file mode 100644 index 0000000..b559220 --- /dev/null +++ b/node-v0.8.14/test/simple/test-util-format.js @@ -0,0 +1,62 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + + + +var common = require('../common'); +var assert = require('assert'); +var util = require('util'); + +assert.equal(util.format(), ''); +assert.equal(util.format(''), ''); +assert.equal(util.format([]), '[]'); +assert.equal(util.format({}), '{}'); +assert.equal(util.format(null), 'null'); +assert.equal(util.format(true), 'true'); +assert.equal(util.format(false), 'false'); +assert.equal(util.format('test'), 'test'); + +// CHECKME this is for console.log() compatibility - but is it *right*? +assert.equal(util.format('foo', 'bar', 'baz'), 'foo bar baz'); + +assert.equal(util.format('%d', 42.0), '42'); +assert.equal(util.format('%d', 42), '42'); +assert.equal(util.format('%s', 42), '42'); +assert.equal(util.format('%j', 42), '42'); + +assert.equal(util.format('%d', '42.0'), '42'); +assert.equal(util.format('%d', '42'), '42'); +assert.equal(util.format('%s', '42'), '42'); +assert.equal(util.format('%j', '42'), '"42"'); + +assert.equal(util.format('%%s%s', 'foo'), '%sfoo'); + +assert.equal(util.format('%s'), '%s'); +assert.equal(util.format('%s', undefined), 'undefined'); +assert.equal(util.format('%s', 'foo'), 'foo'); +assert.equal(util.format('%s:%s'), '%s:%s'); +assert.equal(util.format('%s:%s', undefined), 'undefined:%s'); +assert.equal(util.format('%s:%s', 'foo'), 'foo:%s'); +assert.equal(util.format('%s:%s', 'foo', 'bar'), 'foo:bar'); +assert.equal(util.format('%s:%s', 'foo', 'bar', 'baz'), 'foo:bar baz'); +assert.equal(util.format('%%%s%%', 'hi'), '%hi%'); +assert.equal(util.format('%%%s%%%%', 'hi'), '%hi%%'); diff --git a/node-v0.8.14/test/simple/test-util-inspect.js b/node-v0.8.14/test/simple/test-util-inspect.js new file mode 100644 index 0000000..b6f5bfa --- /dev/null +++ b/node-v0.8.14/test/simple/test-util-inspect.js @@ -0,0 +1,116 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + + + +var common = require('../common'); +var assert = require('assert'); +var util = require('util'); + +// test the internal isDate implementation +var Date2 = require('vm').runInNewContext('Date'); +var d = new Date2(); +var orig = util.inspect(d); +Date2.prototype.foo = 'bar'; +var after = util.inspect(d); +assert.equal(orig, after); + +// test for sparse array +var a = ['foo', 'bar', 'baz']; +assert.equal(util.inspect(a), '[ \'foo\', \'bar\', \'baz\' ]'); +delete a[1]; +assert.equal(util.inspect(a), '[ \'foo\', , \'baz\' ]'); +assert.equal(util.inspect(a, true), '[ \'foo\', , \'baz\', [length]: 3 ]'); +assert.equal(util.inspect(new Array(5)), '[ , , , , ]'); + +// test for property descriptors +var getter = Object.create(null, { + a: { + get: function() { return 'aaa'; } + } +}); +var setter = Object.create(null, { + b: { + set: function() {} + } +}); +var getterAndSetter = Object.create(null, { + c: { + get: function() { return 'ccc'; }, + set: function() {} + } +}); +assert.equal(util.inspect(getter, true), '{ [a]: [Getter] }'); +assert.equal(util.inspect(setter, true), '{ [b]: [Setter] }'); +assert.equal(util.inspect(getterAndSetter, true), '{ [c]: [Getter/Setter] }'); + +// exceptions should print the error message, not '{}' +assert.equal(util.inspect(new Error()), '[Error]'); +assert.equal(util.inspect(new Error('FAIL')), '[Error: FAIL]'); +assert.equal(util.inspect(new TypeError('FAIL')), '[TypeError: FAIL]'); +assert.equal(util.inspect(new SyntaxError('FAIL')), '[SyntaxError: FAIL]'); +try { + undef(); +} catch (e) { + assert.equal(util.inspect(e), '[ReferenceError: undef is not defined]'); +} +var ex = util.inspect(new Error('FAIL'), true); +assert.ok(ex.indexOf('[Error: FAIL]') != -1); +assert.ok(ex.indexOf('[stack]') != -1); +assert.ok(ex.indexOf('[message]') != -1); +assert.ok(ex.indexOf('[arguments]') != -1); +assert.ok(ex.indexOf('[type]') != -1); + +// GH-1941 +// should not throw: +assert.equal(util.inspect(Object.create(Date.prototype)), '{}'); + +// GH-1944 +assert.doesNotThrow(function() { + var d = new Date(); + d.toUTCString = null; + util.inspect(d); +}); + +assert.doesNotThrow(function() { + var r = /regexp/; + r.toString = null; + util.inspect(r); +}); + +// bug with user-supplied inspect function returns non-string +assert.doesNotThrow(function() { + util.inspect([{ + inspect: function() { return 123; } + }]); +}); + +// GH-2225 +var x = { inspect: util.inspect }; +assert.ok(util.inspect(x).indexOf('inspect') != -1); + +// an object with "hasOwnProperty" overwritten should not throw +assert.doesNotThrow(function() { + util.inspect({ + hasOwnProperty: null + }); +}); diff --git a/node-v0.8.14/test/simple/test-util.js b/node-v0.8.14/test/simple/test-util.js new file mode 100644 index 0000000..7c30f5e --- /dev/null +++ b/node-v0.8.14/test/simple/test-util.js @@ -0,0 +1,80 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + +var common = require('../common'); +var assert = require('assert'); +var util = require('util'); +var context = require('vm').runInNewContext; + +// isArray +assert.equal(true, util.isArray([])); +assert.equal(true, util.isArray(Array())); +assert.equal(true, util.isArray(new Array())); +assert.equal(true, util.isArray(new Array(5))); +assert.equal(true, util.isArray(new Array('with', 'some', 'entries'))); +assert.equal(true, util.isArray(context('Array')())); +assert.equal(false, util.isArray({})); +assert.equal(false, util.isArray({ push: function() {} })); +assert.equal(false, util.isArray(/regexp/)); +assert.equal(false, util.isArray(new Error)); +assert.equal(false, util.isArray(Object.create(Array.prototype))); + +// isRegExp +assert.equal(true, util.isRegExp(/regexp/)); +assert.equal(true, util.isRegExp(RegExp())); +assert.equal(true, util.isRegExp(new RegExp())); +assert.equal(true, util.isRegExp(context('RegExp')())); +assert.equal(false, util.isRegExp({})); +assert.equal(false, util.isRegExp([])); +assert.equal(false, util.isRegExp(new Date())); +assert.equal(false, util.isRegExp(Object.create(RegExp.prototype))); + +// isDate +assert.equal(true, util.isDate(new Date())); +assert.equal(true, util.isDate(new Date(0))); +assert.equal(true, util.isDate(new (context('Date')))); +assert.equal(false, util.isDate(Date())); +assert.equal(false, util.isDate({})); +assert.equal(false, util.isDate([])); +assert.equal(false, util.isDate(new Error)); +assert.equal(false, util.isDate(Object.create(Date.prototype))); + +// isError +assert.equal(true, util.isError(new Error)); +assert.equal(true, util.isError(new TypeError)); +assert.equal(true, util.isError(new SyntaxError)); +assert.equal(true, util.isError(new (context('Error')))); +assert.equal(true, util.isError(new (context('TypeError')))); +assert.equal(true, util.isError(new (context('SyntaxError')))); +assert.equal(false, util.isError({})); +assert.equal(false, util.isError({ name: 'Error', message: '' })); +assert.equal(false, util.isError([])); +assert.equal(false, util.isError(Object.create(Error.prototype))); + +// _extend +assert.deepEqual(util._extend({a:1}), {a:1}); +assert.deepEqual(util._extend({a:1}, []), {a:1}); +assert.deepEqual(util._extend({a:1}, null), {a:1}); +assert.deepEqual(util._extend({a:1}, true), {a:1}); +assert.deepEqual(util._extend({a:1}, false), {a:1}); +assert.deepEqual(util._extend({a:1}, {b:2}), {a:1, b:2}); +assert.deepEqual(util._extend({a:1, b:2}, {b:3}), {a:1, b:3}); diff --git a/node-v0.8.14/test/simple/test-vm-create-context-accessors.js b/node-v0.8.14/test/simple/test-vm-create-context-accessors.js new file mode 100644 index 0000000..f062224 --- /dev/null +++ b/node-v0.8.14/test/simple/test-vm-create-context-accessors.js @@ -0,0 +1,47 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var vm = require('vm'); + +var ctx = {}; + +Object.defineProperty(ctx, 'getter', { + get: function() { + return 'ok'; + } +}); + +var val; +Object.defineProperty(ctx, 'setter', { + set: function(_val) { + val = _val; + }, + get: function() { + return 'ok=' + val; + } +}); + +ctx = vm.createContext(ctx); + +var result = vm.runInContext('setter = "test";[getter,setter]', ctx); +assert.deepEqual(result, ['ok', 'ok=test']); diff --git a/node-v0.8.14/test/simple/test-vm-create-context-arg.js b/node-v0.8.14/test/simple/test-vm-create-context-arg.js new file mode 100644 index 0000000..27cd5e1 --- /dev/null +++ b/node-v0.8.14/test/simple/test-vm-create-context-arg.js @@ -0,0 +1,33 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var vm = require('vm'); + +assert.throws(function() { + var ctx = vm.createContext('string is not supported'); +}); + +assert.doesNotThrow(function() { + var ctx = vm.createContext({ a: 1 }); + ctx = vm.createContext([0, 1, 2, 3]); +}); diff --git a/node-v0.8.14/test/simple/test-vm-create-context-circular-reference.js b/node-v0.8.14/test/simple/test-vm-create-context-circular-reference.js new file mode 100644 index 0000000..ae5b48c --- /dev/null +++ b/node-v0.8.14/test/simple/test-vm-create-context-circular-reference.js @@ -0,0 +1,34 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var vm = require('vm'); + +var sbx = {}; +sbx.window = sbx; + +sbx = vm.createContext(sbx); + +sbx.test = 123; + +assert.equal(sbx.window.window.window.window.window.test, 123); + diff --git a/node-v0.8.14/test/simple/test-writedouble.js b/node-v0.8.14/test/simple/test-writedouble.js new file mode 100644 index 0000000..829ba29 --- /dev/null +++ b/node-v0.8.14/test/simple/test-writedouble.js @@ -0,0 +1,130 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +/* + * Tests to verify we're writing doubles correctly + */ +var SlowBuffer = process.binding('buffer').SlowBuffer; +var common = require('../common'); +var ASSERT = require('assert'); + +function test(clazz) { + var buffer = new clazz(16); + + buffer.writeDoubleBE(2.225073858507201e-308, 0); + buffer.writeDoubleLE(2.225073858507201e-308, 8); + ASSERT.equal(0x00, buffer[0]); + ASSERT.equal(0x0f, buffer[1]); + ASSERT.equal(0xff, buffer[2]); + ASSERT.equal(0xff, buffer[3]); + ASSERT.equal(0xff, buffer[4]); + ASSERT.equal(0xff, buffer[5]); + ASSERT.equal(0xff, buffer[6]); + ASSERT.equal(0xff, buffer[7]); + ASSERT.equal(0xff, buffer[8]); + ASSERT.equal(0xff, buffer[9]); + ASSERT.equal(0xff, buffer[10]); + ASSERT.equal(0xff, buffer[11]); + ASSERT.equal(0xff, buffer[12]); + ASSERT.equal(0xff, buffer[13]); + ASSERT.equal(0x0f, buffer[14]); + ASSERT.equal(0x00, buffer[15]); + + buffer.writeDoubleBE(1.0000000000000004, 0); + buffer.writeDoubleLE(1.0000000000000004, 8); + ASSERT.equal(0x3f, buffer[0]); + ASSERT.equal(0xf0, buffer[1]); + ASSERT.equal(0x00, buffer[2]); + ASSERT.equal(0x00, buffer[3]); + ASSERT.equal(0x00, buffer[4]); + ASSERT.equal(0x00, buffer[5]); + ASSERT.equal(0x00, buffer[6]); + ASSERT.equal(0x02, buffer[7]); + ASSERT.equal(0x02, buffer[8]); + ASSERT.equal(0x00, buffer[9]); + ASSERT.equal(0x00, buffer[10]); + ASSERT.equal(0x00, buffer[11]); + ASSERT.equal(0x00, buffer[12]); + ASSERT.equal(0x00, buffer[13]); + ASSERT.equal(0xf0, buffer[14]); + ASSERT.equal(0x3f, buffer[15]); + + buffer.writeDoubleBE(-2, 0); + buffer.writeDoubleLE(-2, 8); + ASSERT.equal(0xc0, buffer[0]); + ASSERT.equal(0x00, buffer[1]); + ASSERT.equal(0x00, buffer[2]); + ASSERT.equal(0x00, buffer[3]); + ASSERT.equal(0x00, buffer[4]); + ASSERT.equal(0x00, buffer[5]); + ASSERT.equal(0x00, buffer[6]); + ASSERT.equal(0x00, buffer[7]); + ASSERT.equal(0x00, buffer[8]); + ASSERT.equal(0x00, buffer[9]); + ASSERT.equal(0x00, buffer[10]); + ASSERT.equal(0x00, buffer[11]); + ASSERT.equal(0x00, buffer[12]); + ASSERT.equal(0x00, buffer[13]); + ASSERT.equal(0x00, buffer[14]); + ASSERT.equal(0xc0, buffer[15]); + + buffer.writeDoubleBE(1.7976931348623157e+308, 0); + buffer.writeDoubleLE(1.7976931348623157e+308, 8); + ASSERT.equal(0x7f, buffer[0]); + ASSERT.equal(0xef, buffer[1]); + ASSERT.equal(0xff, buffer[2]); + ASSERT.equal(0xff, buffer[3]); + ASSERT.equal(0xff, buffer[4]); + ASSERT.equal(0xff, buffer[5]); + ASSERT.equal(0xff, buffer[6]); + ASSERT.equal(0xff, buffer[7]); + ASSERT.equal(0xff, buffer[8]); + ASSERT.equal(0xff, buffer[9]); + ASSERT.equal(0xff, buffer[10]); + ASSERT.equal(0xff, buffer[11]); + ASSERT.equal(0xff, buffer[12]); + ASSERT.equal(0xff, buffer[13]); + ASSERT.equal(0xef, buffer[14]); + ASSERT.equal(0x7f, buffer[15]); + + buffer.writeDoubleBE(0 * -1, 0); + buffer.writeDoubleLE(0 * -1, 8); + ASSERT.equal(0x80, buffer[0]); + ASSERT.equal(0x00, buffer[1]); + ASSERT.equal(0x00, buffer[2]); + ASSERT.equal(0x00, buffer[3]); + ASSERT.equal(0x00, buffer[4]); + ASSERT.equal(0x00, buffer[5]); + ASSERT.equal(0x00, buffer[6]); + ASSERT.equal(0x00, buffer[7]); + ASSERT.equal(0x00, buffer[8]); + ASSERT.equal(0x00, buffer[9]); + ASSERT.equal(0x00, buffer[10]); + ASSERT.equal(0x00, buffer[11]); + ASSERT.equal(0x00, buffer[12]); + ASSERT.equal(0x00, buffer[13]); + ASSERT.equal(0x00, buffer[14]); + ASSERT.equal(0x80, buffer[15]); +} + + +test(Buffer); +test(SlowBuffer); diff --git a/node-v0.8.14/test/simple/test-writefloat.js b/node-v0.8.14/test/simple/test-writefloat.js new file mode 100644 index 0000000..d10cb75 --- /dev/null +++ b/node-v0.8.14/test/simple/test-writefloat.js @@ -0,0 +1,90 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +/* + * Tests to verify we're writing floats correctly + */ +var SlowBuffer = process.binding('buffer').SlowBuffer; +var common = require('../common'); +var ASSERT = require('assert'); + +function test(clazz) { + var buffer = new clazz(8); + + buffer.writeFloatBE(1, 0); + buffer.writeFloatLE(1, 4); + ASSERT.equal(0x3f, buffer[0]); + ASSERT.equal(0x80, buffer[1]); + ASSERT.equal(0x00, buffer[2]); + ASSERT.equal(0x00, buffer[3]); + ASSERT.equal(0x00, buffer[4]); + ASSERT.equal(0x00, buffer[5]); + ASSERT.equal(0x80, buffer[6]); + ASSERT.equal(0x3f, buffer[7]); + + buffer.writeFloatBE(1.793662034335766e-43, 0); + buffer.writeFloatLE(1.793662034335766e-43, 4); + ASSERT.equal(0x00, buffer[0]); + ASSERT.equal(0x00, buffer[1]); + ASSERT.equal(0x00, buffer[2]); + ASSERT.equal(0x80, buffer[3]); + ASSERT.equal(0x80, buffer[4]); + ASSERT.equal(0x00, buffer[5]); + ASSERT.equal(0x00, buffer[6]); + ASSERT.equal(0x00, buffer[7]); + + buffer.writeFloatBE(1 / 3, 0); + buffer.writeFloatLE(1 / 3, 4); + ASSERT.equal(0x3e, buffer[0]); + ASSERT.equal(0xaa, buffer[1]); + ASSERT.equal(0xaa, buffer[2]); + ASSERT.equal(0xab, buffer[3]); + ASSERT.equal(0xab, buffer[4]); + ASSERT.equal(0xaa, buffer[5]); + ASSERT.equal(0xaa, buffer[6]); + ASSERT.equal(0x3e, buffer[7]); + + buffer.writeFloatBE(3.4028234663852886e+38, 0); + buffer.writeFloatLE(3.4028234663852886e+38, 4); + ASSERT.equal(0x7f, buffer[0]); + ASSERT.equal(0x7f, buffer[1]); + ASSERT.equal(0xff, buffer[2]); + ASSERT.equal(0xff, buffer[3]); + ASSERT.equal(0xff, buffer[4]); + ASSERT.equal(0xff, buffer[5]); + ASSERT.equal(0x7f, buffer[6]); + ASSERT.equal(0x7f, buffer[7]); + + buffer.writeFloatBE(0 * -1, 0); + buffer.writeFloatLE(0 * -1, 4); + ASSERT.equal(0x80, buffer[0]); + ASSERT.equal(0x00, buffer[1]); + ASSERT.equal(0x00, buffer[2]); + ASSERT.equal(0x00, buffer[3]); + ASSERT.equal(0x00, buffer[4]); + ASSERT.equal(0x00, buffer[5]); + ASSERT.equal(0x00, buffer[6]); + ASSERT.equal(0x80, buffer[7]); +} + + +test(Buffer); +test(SlowBuffer); diff --git a/node-v0.8.14/test/simple/test-writeint.js b/node-v0.8.14/test/simple/test-writeint.js new file mode 100644 index 0000000..b7ebd69 --- /dev/null +++ b/node-v0.8.14/test/simple/test-writeint.js @@ -0,0 +1,192 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +/* + * Tests to verify we're writing signed integers correctly + */ +var SlowBuffer = process.binding('buffer').SlowBuffer; +var common = require('../common'); +var ASSERT = require('assert'); + +function test8(clazz) { + var buffer = new clazz(2); + + buffer.writeInt8(0x23, 0); + buffer.writeInt8(-5, 1); + + ASSERT.equal(0x23, buffer[0]); + ASSERT.equal(0xfb, buffer[1]); + + /* Make sure we handle truncation correctly */ + ASSERT.throws(function() { + buffer.writeInt8(0xabc, 0); + }); + ASSERT.throws(function() { + buffer.writeInt8(0xabc, 0); + }); + + /* Make sure we handle min/max correctly */ + buffer.writeInt8(0x7f, 0); + buffer.writeInt8(-0x80, 1); + + ASSERT.equal(0x7f, buffer[0]); + ASSERT.equal(0x80, buffer[1]); + ASSERT.throws(function() { + buffer.writeInt8(0x7f + 1, 0); + }); + ASSERT.throws(function() { + buffer.writeInt8(-0x80 - 1, 0); + }); +} + + +function test16(clazz) { + var buffer = new clazz(6); + + buffer.writeInt16BE(0x0023, 0); + buffer.writeInt16LE(0x0023, 2); + ASSERT.equal(0x00, buffer[0]); + ASSERT.equal(0x23, buffer[1]); + ASSERT.equal(0x23, buffer[2]); + ASSERT.equal(0x00, buffer[3]); + + buffer.writeInt16BE(-5, 0); + buffer.writeInt16LE(-5, 2); + ASSERT.equal(0xff, buffer[0]); + ASSERT.equal(0xfb, buffer[1]); + ASSERT.equal(0xfb, buffer[2]); + ASSERT.equal(0xff, buffer[3]); + + buffer.writeInt16BE(-1679, 1); + buffer.writeInt16LE(-1679, 3); + ASSERT.equal(0xf9, buffer[1]); + ASSERT.equal(0x71, buffer[2]); + ASSERT.equal(0x71, buffer[3]); + ASSERT.equal(0xf9, buffer[4]); + + /* Make sure we handle min/max correctly */ + buffer.writeInt16BE(0x7fff, 0); + buffer.writeInt16BE(-0x8000, 2); + ASSERT.equal(0x7f, buffer[0]); + ASSERT.equal(0xff, buffer[1]); + ASSERT.equal(0x80, buffer[2]); + ASSERT.equal(0x00, buffer[3]); + ASSERT.throws(function() { + buffer.writeInt16BE(0x7fff + 1, 0); + }); + ASSERT.throws(function() { + buffer.writeInt16BE(-0x8000 - 1, 0); + }); + + buffer.writeInt16LE(0x7fff, 0); + buffer.writeInt16LE(-0x8000, 2); + ASSERT.equal(0xff, buffer[0]); + ASSERT.equal(0x7f, buffer[1]); + ASSERT.equal(0x00, buffer[2]); + ASSERT.equal(0x80, buffer[3]); + ASSERT.throws(function() { + buffer.writeInt16LE(0x7fff + 1, 0); + }); + ASSERT.throws(function() { + buffer.writeInt16LE(-0x8000 - 1, 0); + }); +} + + +function test32(clazz) { + var buffer = new clazz(8); + + buffer.writeInt32BE(0x23, 0); + buffer.writeInt32LE(0x23, 4); + ASSERT.equal(0x00, buffer[0]); + ASSERT.equal(0x00, buffer[1]); + ASSERT.equal(0x00, buffer[2]); + ASSERT.equal(0x23, buffer[3]); + ASSERT.equal(0x23, buffer[4]); + ASSERT.equal(0x00, buffer[5]); + ASSERT.equal(0x00, buffer[6]); + ASSERT.equal(0x00, buffer[7]); + + buffer.writeInt32BE(-5, 0); + buffer.writeInt32LE(-5, 4); + ASSERT.equal(0xff, buffer[0]); + ASSERT.equal(0xff, buffer[1]); + ASSERT.equal(0xff, buffer[2]); + ASSERT.equal(0xfb, buffer[3]); + ASSERT.equal(0xfb, buffer[4]); + ASSERT.equal(0xff, buffer[5]); + ASSERT.equal(0xff, buffer[6]); + ASSERT.equal(0xff, buffer[7]); + + buffer.writeInt32BE(-805306713, 0); + buffer.writeInt32LE(-805306713, 4); + ASSERT.equal(0xcf, buffer[0]); + ASSERT.equal(0xff, buffer[1]); + ASSERT.equal(0xfe, buffer[2]); + ASSERT.equal(0xa7, buffer[3]); + ASSERT.equal(0xa7, buffer[4]); + ASSERT.equal(0xfe, buffer[5]); + ASSERT.equal(0xff, buffer[6]); + ASSERT.equal(0xcf, buffer[7]); + + /* Make sure we handle min/max correctly */ + buffer.writeInt32BE(0x7fffffff, 0); + buffer.writeInt32BE(-0x80000000, 4); + ASSERT.equal(0x7f, buffer[0]); + ASSERT.equal(0xff, buffer[1]); + ASSERT.equal(0xff, buffer[2]); + ASSERT.equal(0xff, buffer[3]); + ASSERT.equal(0x80, buffer[4]); + ASSERT.equal(0x00, buffer[5]); + ASSERT.equal(0x00, buffer[6]); + ASSERT.equal(0x00, buffer[7]); + ASSERT.throws(function() { + buffer.writeInt32BE(0x7fffffff + 1, 0); + }); + ASSERT.throws(function() { + buffer.writeInt32BE(-0x80000000 - 1, 0); + }); + + buffer.writeInt32LE(0x7fffffff, 0); + buffer.writeInt32LE(-0x80000000, 4); + ASSERT.equal(0xff, buffer[0]); + ASSERT.equal(0xff, buffer[1]); + ASSERT.equal(0xff, buffer[2]); + ASSERT.equal(0x7f, buffer[3]); + ASSERT.equal(0x00, buffer[4]); + ASSERT.equal(0x00, buffer[5]); + ASSERT.equal(0x00, buffer[6]); + ASSERT.equal(0x80, buffer[7]); + ASSERT.throws(function() { + buffer.writeInt32LE(0x7fffffff + 1, 0); + }); + ASSERT.throws(function() { + buffer.writeInt32LE(-0x80000000 - 1, 0); + }); +} + + +test8(Buffer); +test8(SlowBuffer); +test16(Buffer); +test16(SlowBuffer); +test32(Buffer); +test32(SlowBuffer); diff --git a/node-v0.8.14/test/simple/test-writeuint.js b/node-v0.8.14/test/simple/test-writeuint.js new file mode 100644 index 0000000..91b5c6c --- /dev/null +++ b/node-v0.8.14/test/simple/test-writeuint.js @@ -0,0 +1,151 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +/* + * A battery of tests to help us read a series of uints + */ +var SlowBuffer = process.binding('buffer').SlowBuffer; +var common = require('../common'); +var ASSERT = require('assert'); + +/* + * We need to check the following things: + * - We are correctly resolving big endian (doesn't mean anything for 8 bit) + * - Correctly resolving little endian (doesn't mean anything for 8 bit) + * - Correctly using the offsets + * - Correctly interpreting values that are beyond the signed range as unsigned + */ +function test8(clazz) { + var data = new clazz(4); + + data.writeUInt8(23, 0); + data.writeUInt8(23, 1); + data.writeUInt8(23, 2); + data.writeUInt8(23, 3); + ASSERT.equal(23, data[0]); + ASSERT.equal(23, data[1]); + ASSERT.equal(23, data[2]); + ASSERT.equal(23, data[3]); + + data.writeUInt8(23, 0); + data.writeUInt8(23, 1); + data.writeUInt8(23, 2); + data.writeUInt8(23, 3); + ASSERT.equal(23, data[0]); + ASSERT.equal(23, data[1]); + ASSERT.equal(23, data[2]); + ASSERT.equal(23, data[3]); + + data.writeUInt8(255, 0); + ASSERT.equal(255, data[0]); + + data.writeUInt8(255, 0); + ASSERT.equal(255, data[0]); +} + + +function test16(clazz) { + var value = 0x2343; + var data = new clazz(4); + + data.writeUInt16BE(value, 0); + ASSERT.equal(0x23, data[0]); + ASSERT.equal(0x43, data[1]); + + data.writeUInt16BE(value, 1); + ASSERT.equal(0x23, data[1]); + ASSERT.equal(0x43, data[2]); + + data.writeUInt16BE(value, 2); + ASSERT.equal(0x23, data[2]); + ASSERT.equal(0x43, data[3]); + + data.writeUInt16LE(value, 0); + ASSERT.equal(0x23, data[1]); + ASSERT.equal(0x43, data[0]); + + data.writeUInt16LE(value, 1); + ASSERT.equal(0x23, data[2]); + ASSERT.equal(0x43, data[1]); + + data.writeUInt16LE(value, 2); + ASSERT.equal(0x23, data[3]); + ASSERT.equal(0x43, data[2]); + + value = 0xff80; + data.writeUInt16LE(value, 0); + ASSERT.equal(0xff, data[1]); + ASSERT.equal(0x80, data[0]); + + data.writeUInt16BE(value, 0); + ASSERT.equal(0xff, data[0]); + ASSERT.equal(0x80, data[1]); +} + + +function test32(clazz) { + var data = new clazz(6); + var value = 0xe7f90a6d; + + data.writeUInt32BE(value, 0); + ASSERT.equal(0xe7, data[0]); + ASSERT.equal(0xf9, data[1]); + ASSERT.equal(0x0a, data[2]); + ASSERT.equal(0x6d, data[3]); + + data.writeUInt32BE(value, 1); + ASSERT.equal(0xe7, data[1]); + ASSERT.equal(0xf9, data[2]); + ASSERT.equal(0x0a, data[3]); + ASSERT.equal(0x6d, data[4]); + + data.writeUInt32BE(value, 2); + ASSERT.equal(0xe7, data[2]); + ASSERT.equal(0xf9, data[3]); + ASSERT.equal(0x0a, data[4]); + ASSERT.equal(0x6d, data[5]); + + data.writeUInt32LE(value, 0); + ASSERT.equal(0xe7, data[3]); + ASSERT.equal(0xf9, data[2]); + ASSERT.equal(0x0a, data[1]); + ASSERT.equal(0x6d, data[0]); + + data.writeUInt32LE(value, 1); + ASSERT.equal(0xe7, data[4]); + ASSERT.equal(0xf9, data[3]); + ASSERT.equal(0x0a, data[2]); + ASSERT.equal(0x6d, data[1]); + + data.writeUInt32LE(value, 2); + ASSERT.equal(0xe7, data[5]); + ASSERT.equal(0xf9, data[4]); + ASSERT.equal(0x0a, data[3]); + ASSERT.equal(0x6d, data[2]); +} + + +test8(Buffer); +test8(SlowBuffer); +test16(Buffer); +test16(SlowBuffer); +test32(Buffer); +test32(SlowBuffer); diff --git a/node-v0.8.14/test/simple/test-zerolengthbufferbug.js b/node-v0.8.14/test/simple/test-zerolengthbufferbug.js new file mode 100644 index 0000000..395e35b --- /dev/null +++ b/node-v0.8.14/test/simple/test-zerolengthbufferbug.js @@ -0,0 +1,57 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// Serving up a zero-length buffer should work. + +var common = require('../common'); +var assert = require('assert'); +var http = require('http'); + +var server = http.createServer(function(req, res) { + var buffer = new Buffer(0); + // FIXME: WTF gjslint want this? + res.writeHead(200, {'Content-Type': 'text/html', + 'Content-Length': buffer.length}); + res.end(buffer); +}); + +var gotResponse = false; +var resBodySize = 0; + +server.listen(common.PORT, function() { + http.get({ port: common.PORT }, function(res) { + gotResponse = true; + + res.on('data', function(d) { + resBodySize += d.length; + }); + + res.on('end', function(d) { + server.close(); + }); + }); +}); + +process.on('exit', function() { + assert.ok(gotResponse); + assert.equal(0, resBodySize); +}); + diff --git a/node-v0.8.14/test/simple/test-zlib-destroy.js b/node-v0.8.14/test/simple/test-zlib-destroy.js new file mode 100644 index 0000000..7a1120e --- /dev/null +++ b/node-v0.8.14/test/simple/test-zlib-destroy.js @@ -0,0 +1,36 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var zlib = require('zlib'); + +['Deflate', 'Inflate', 'Gzip', 'Gunzip', 'DeflateRaw', 'InflateRaw', 'Unzip'] + .forEach(function (name) { + var a = false; + var zStream = new zlib[name](); + zStream.on('close', function () { + a = true; + }); + zStream.destroy(); + + assert.equal(a, true, name+'#destroy() must emit \'close\''); + }); diff --git a/node-v0.8.14/test/simple/test-zlib-dictionary.js b/node-v0.8.14/test/simple/test-zlib-dictionary.js new file mode 100644 index 0000000..f3b1446 --- /dev/null +++ b/node-v0.8.14/test/simple/test-zlib-dictionary.js @@ -0,0 +1,95 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// test compression/decompresion with dictionary + +var common = require('../common.js'); +var assert = require('assert'); +var zlib = require('zlib'); +var path = require('path'); + +var spdyDict = new Buffer([ + 'optionsgetheadpostputdeletetraceacceptaccept-charsetaccept-encodingaccept-', + 'languageauthorizationexpectfromhostif-modified-sinceif-matchif-none-matchi', + 'f-rangeif-unmodifiedsincemax-forwardsproxy-authorizationrangerefererteuser', + '-agent10010120020120220320420520630030130230330430530630740040140240340440', + '5406407408409410411412413414415416417500501502503504505accept-rangesageeta', + 'glocationproxy-authenticatepublicretry-afterservervarywarningwww-authentic', + 'ateallowcontent-basecontent-encodingcache-controlconnectiondatetrailertran', + 'sfer-encodingupgradeviawarningcontent-languagecontent-lengthcontent-locati', + 'oncontent-md5content-rangecontent-typeetagexpireslast-modifiedset-cookieMo', + 'ndayTuesdayWednesdayThursdayFridaySaturdaySundayJanFebMarAprMayJunJulAugSe', + 'pOctNovDecchunkedtext/htmlimage/pngimage/jpgimage/gifapplication/xmlapplic', + 'ation/xhtmltext/plainpublicmax-agecharset=iso-8859-1utf-8gzipdeflateHTTP/1', + '.1statusversionurl\0' +].join('')); + +var deflate = zlib.createDeflate({ dictionary: spdyDict }); + +var input = [ + 'HTTP/1.1 200 Ok', + 'Server: node.js', + 'Content-Length: 0', + '' +].join('\r\n'); + +var called = 0; + +// +// We'll use clean-new inflate stream each time +// and .reset() old dirty deflate one +// +function run(num) { + var inflate = zlib.createInflate({ dictionary: spdyDict }); + + if (num === 2) { + deflate.reset(); + deflate.removeAllListeners('data'); + } + + // Put data into deflate stream + deflate.on('data', function(chunk) { + inflate.write(chunk); + }); + + // Get data from inflate stream + var output = []; + inflate.on('data', function(chunk) { + output.push(chunk); + }); + inflate.on('end', function() { + called++; + + assert.equal(output.join(''), input); + + if (num < 2) run(num + 1); + }); + + deflate.write(input); + deflate.flush(function() { + inflate.end(); + }); +} +run(1); + +process.on('exit', function() { + assert.equal(called, 2); +}); diff --git a/node-v0.8.14/test/simple/test-zlib-from-gzip.js b/node-v0.8.14/test/simple/test-zlib-from-gzip.js new file mode 100644 index 0000000..3993542 --- /dev/null +++ b/node-v0.8.14/test/simple/test-zlib-from-gzip.js @@ -0,0 +1,48 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// test unzipping a file that was created with a non-node gzip lib, +// piped in as fast as possible. + +var common = require('../common.js'); +var assert = require('assert'); +var zlib = require('zlib'); +var path = require('path'); + +var gunzip = zlib.createGunzip(); + +var fs = require('fs'); + +var fixture = path.resolve(common.fixturesDir, 'person.jpg.gz'); +var unzippedFixture = path.resolve(common.fixturesDir, 'person.jpg'); +var outputFile = path.resolve(common.tmpDir, 'person.jpg'); +var expect = fs.readFileSync(unzippedFixture); +var inp = fs.createReadStream(fixture); +var out = fs.createWriteStream(outputFile); + +inp.pipe(gunzip).pipe(out); +out.on('close', function() { + var actual = fs.readFileSync(outputFile); + assert.equal(actual.length, expect.length, 'length should match'); + for (var i = 0, l = actual.length; i < l; i++) { + assert.equal(actual[i], expect[i], 'byte[' + i + ']'); + } +}); diff --git a/node-v0.8.14/test/simple/test-zlib-from-string.js b/node-v0.8.14/test/simple/test-zlib-from-string.js new file mode 100644 index 0000000..83bdeea --- /dev/null +++ b/node-v0.8.14/test/simple/test-zlib-from-string.js @@ -0,0 +1,78 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// test compressing and uncompressing a string with zlib + +var common = require('../common.js'); +var assert = require('assert'); +var zlib = require('zlib'); + +var inputString = 'ΩΩLorem ipsum dolor sit amet, consectetur adipiscing el' + + 'it. Morbi faucibus, purus at gravida dictum, libero arcu convallis la' + + 'cus, in commodo libero metus eu nisi. Nullam commodo, neque nec porta' + + ' placerat, nisi est fermentum augue, vitae gravida tellus sapien sit ' + + 'amet tellus. Aenean non diam orci. Proin quis elit turpis. Suspendiss' + + 'e non diam ipsum. Suspendisse nec ullamcorper odio. Vestibulum arcu m' + + 'i, sodales non suscipit id, ultrices ut massa. Sed ac sem sit amet ar' + + 'cu malesuada fermentum. Nunc sed. '; +var expectedBase64Deflate = 'eJxdUUtOQzEMvMoc4OndgT0gJCT2buJWlpI4jePeqZfpm' + + 'XAKLRKbLOzx/HK73q6vOrhCunlF1qIDJhNUeW5I2ozT5OkDlKWLJWkncJG5403HQXAkT3' + + 'Jw29B9uIEmToMukglZ0vS6ociBh4JG8sV4oVLEUCitK2kxq1WzPnChHDzsaGKy491Lofo' + + 'AbWh8do43oeuYhB5EPCjcLjzYJo48KrfQBvnJecNFJvHT1+RSQsGoC7dn2t/xjhduTA1N' + + 'WyQIZR0pbHwMDatnD+crPqKSqGPHp1vnlsWM/07ubf7bheF7kqSj84Bm0R1fYTfaK8vqq' + + 'qfKBtNMhe3OZh6N95CTvMX5HJJi4xOVzCgUOIMSLH7wmeOHaFE4RdpnGavKtrB5xzfO/Ll9'; +var expectedBase64Gzip = 'H4sIAAAAAAAAA11RS05DMQy8yhzg6d2BPSAkJPZu4laWkjiN' + + '496pl+mZcAotEpss7PH8crverq86uEK6eUXWogMmE1R5bkjajNPk6QOUpYslaSdwkbnjT' + + 'cdBcCRPcnDb0H24gSZOgy6SCVnS9LqhyIGHgkbyxXihUsRQKK0raTGrVbM+cKEcPOxoYr' + + 'Lj3Uuh+gBtaHx2jjeh65iEHkQ8KNwuPNgmjjwqt9AG+cl5w0Um8dPX5FJCwagLt2fa3/G' + + 'OF25MDU1bJAhlHSlsfAwNq2cP5ys+opKoY8enW+eWxYz/Tu5t/tuF4XuSpKPzgGbRHV9h' + + 'N9ory+qqp8oG00yF7c5mHo33kJO8xfkckmLjE5XMKBQ4gxIsfvCZ44doUThF2mcZq8q2s' + + 'HnHNzRtagj5AQAA'; + +zlib.deflate(inputString, function(err, buffer) { + assert.equal(buffer.toString('base64'), expectedBase64Deflate, + 'deflate encoded string should match'); +}); + +zlib.gzip(inputString, function(err, buffer) { + // Can't actually guarantee that we'll get exactly the same + // deflated bytes when we compress a string, since the header + // depends on stuff other than the input string itself. + // However, decrypting it should definitely yield the same + // result that we're expecting, and this should match what we get + // from inflating the known valid deflate data. + zlib.gunzip(buffer, function(err, gunzipped) { + assert.equal(gunzipped.toString(), inputString, + 'Should get original string after gzip/gunzip'); + }); +}); + +var buffer = new Buffer(expectedBase64Deflate, 'base64'); +zlib.unzip(buffer, function(err, buffer) { + assert.equal(buffer.toString(), inputString, + 'decoded inflated string should match'); +}); + +buffer = new Buffer(expectedBase64Gzip, 'base64'); +zlib.unzip(buffer, function(err, buffer) { + assert.equal(buffer.toString(), inputString, + 'decoded gunzipped string should match'); +}); diff --git a/node-v0.8.14/test/simple/test-zlib-invalid-input.js b/node-v0.8.14/test/simple/test-zlib-invalid-input.js new file mode 100644 index 0000000..f97c583 --- /dev/null +++ b/node-v0.8.14/test/simple/test-zlib-invalid-input.js @@ -0,0 +1,72 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// test uncompressing invalid input + +var common = require('../common.js'), + assert = require('assert'), + zlib = require('zlib'); + +var nonStringInputs = [1, true, {a: 1}, ['a']]; + +console.error('Doing the non-strings'); +nonStringInputs.forEach(function(input) { + // zlib.gunzip should not throw an error when called with bad input. + assert.doesNotThrow(function() { + zlib.gunzip(input, function(err, buffer) { + // zlib.gunzip should pass the error to the callback. + assert.ok(err); + }); + }); +}); + +console.error('Doing the unzips'); +// zlib.Unzip classes need to get valid data, or else they'll throw. +var unzips = [ zlib.Unzip(), + zlib.Gunzip(), + zlib.Inflate(), + zlib.InflateRaw() ]; +var hadError = []; +unzips.forEach(function (uz, i) { + console.error('Error for '+uz.constructor.name); + uz.on('error', function(er) { + console.error('Error event', er); + hadError[i] = true; + + // to be friendly to the Stream API, zlib objects just return true and + // ignore data on the floor after an error. It's up to the user to + // catch the 'error' event and do something intelligent. They do not + // emit any more data, however. + assert.equal(uz.write('also invalid'), true); + assert.equal(uz.end(), true); + }); + + uz.on('end', function(er) { + throw new Error('end event should not be emitted '+uz.constructor.name); + }); + + // this will trigger error event + uz.write('this is not valid compressed data.'); +}); + +process.on('exit', function() { + assert.deepEqual(hadError, [true, true, true, true], 'expect 4 errors'); +}); diff --git a/node-v0.8.14/test/simple/test-zlib-random-byte-pipes.js b/node-v0.8.14/test/simple/test-zlib-random-byte-pipes.js new file mode 100644 index 0000000..f9723cc --- /dev/null +++ b/node-v0.8.14/test/simple/test-zlib-random-byte-pipes.js @@ -0,0 +1,164 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var crypto = require('crypto'); +var stream = require('stream'); +var Stream = stream.Stream; +var util = require('util'); +var assert = require('assert'); +var zlib = require('zlib'); + + + +// emit random bytes, and keep a shasum +function RandomReadStream(opt) { + Stream.call(this); + + this.readable = true; + this._paused = false; + this._processing = false; + + this._hasher = crypto.createHash('sha1'); + opt = opt || {}; + + // base block size. + opt.block = opt.block || 256 * 1024; + + // total number of bytes to emit + opt.total = opt.total || 256 * 1024 * 1024; + this._remaining = opt.total; + + // how variable to make the block sizes + opt.jitter = opt.jitter || 1024; + + this._opt = opt; + + this._process = this._process.bind(this); + + process.nextTick(this._process); +} + +util.inherits(RandomReadStream, Stream); + +RandomReadStream.prototype.pause = function() { + this._paused = true; + this.emit('pause'); +}; + +RandomReadStream.prototype.resume = function() { + // console.error("rrs resume"); + this._paused = false; + this.emit('resume'); + this._process(); +}; + +RandomReadStream.prototype._process = function() { + if (this._processing) return; + if (this._paused) return; + + this._processing = true; + + if (!this._remaining) { + this._hash = this._hasher.digest('hex').toLowerCase().trim(); + this._processing = false; + + this.emit('end'); + return; + } + + // figure out how many bytes to output + // if finished, then just emit end. + var block = this._opt.block; + var jitter = this._opt.jitter; + if (jitter) { + block += Math.ceil(Math.random() * jitter - (jitter / 2)); + } + block = Math.min(block, this._remaining); + var buf = new Buffer(block); + for (var i = 0; i < block; i++) { + buf[i] = Math.random() * 256; + } + + this._hasher.update(buf); + + this._remaining -= block; + + console.error('block=%d\nremain=%d\n', block, this._remaining); + this._processing = false; + + this.emit('data', buf); + process.nextTick(this._process); +}; + + +// a filter that just verifies a shasum +function HashStream() { + Stream.call(this); + + this.readable = this.writable = true; + this._hasher = crypto.createHash('sha1'); +} + +util.inherits(HashStream, Stream); + +HashStream.prototype.write = function(c) { + // Simulate the way that an fs.ReadStream returns false + // on *every* write like a jerk, only to resume a + // moment later. + this._hasher.update(c); + process.nextTick(this.resume.bind(this)); + return false; +}; + +HashStream.prototype.resume = function() { + this.emit('resume'); + process.nextTick(this.emit.bind(this, 'drain')); +}; + +HashStream.prototype.end = function(c) { + if (c) { + this.write(c); + } + this._hash = this._hasher.digest('hex').toLowerCase().trim(); + this.emit('data', this._hash); + this.emit('end'); +}; + + + + +var inp = new RandomReadStream({ total: 1024, block: 256, jitter: 16 }); +var out = new HashStream(); +var gzip = zlib.createGzip(); +var gunz = zlib.createGunzip(); +inp.pipe(gzip).pipe(gunz).pipe(out); + +var didSomething = false; +out.on('data', function(c) { + didSomething = true; + console.error('hash=%s', c); + assert.equal(c, inp._hash, 'hashes should match'); +}); + +process.on('exit', function() { + assert(didSomething, 'should have done something'); +}); diff --git a/node-v0.8.14/test/simple/test-zlib.js b/node-v0.8.14/test/simple/test-zlib.js new file mode 100644 index 0000000..b926752 --- /dev/null +++ b/node-v0.8.14/test/simple/test-zlib.js @@ -0,0 +1,229 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common.js'); +var assert = require('assert'); +var zlib = require('zlib'); +var path = require('path'); + +var zlibPairs = + [[zlib.Deflate, zlib.Inflate], + [zlib.Gzip, zlib.Gunzip], + [zlib.Deflate, zlib.Unzip], + [zlib.Gzip, zlib.Unzip], + [zlib.DeflateRaw, zlib.InflateRaw]]; + +// how fast to trickle through the slowstream +var trickle = [128, 1024, 1024 * 1024]; + +// tunable options for zlib classes. + +// several different chunk sizes +var chunkSize = [128, 1024, 1024 * 16, 1024 * 1024]; + +// this is every possible value. +var level = [-1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]; +var windowBits = [8, 9, 10, 11, 12, 13, 14, 15]; +var memLevel = [1, 2, 3, 4, 5, 6, 7, 8, 9]; +var strategy = [0, 1, 2, 3, 4]; + +// it's nice in theory to test every combination, but it +// takes WAY too long. Maybe a pummel test could do this? +if (!process.env.PUMMEL) { + trickle = [1024]; + chunkSize = [1024 * 16]; + level = [6]; + memLevel = [8]; + windowBits = [15]; + strategy = [0]; +} + +var fs = require('fs'); + +var testFiles = ['person.jpg', 'elipses.txt', 'empty.txt']; + +if (process.env.FAST) { + zlibPairs = [[zlib.Gzip, zlib.Unzip]]; + var testFiles = ['person.jpg']; +} + +var tests = {}; +testFiles.forEach(function(file) { + tests[file] = fs.readFileSync(path.resolve(common.fixturesDir, file)); +}); + +var util = require('util'); +var stream = require('stream'); + + +// stream that saves everything +function BufferStream() { + this.chunks = []; + this.length = 0; + this.writable = true; + this.readable = true; +} + +util.inherits(BufferStream, stream.Stream); + +BufferStream.prototype.write = function(c) { + this.chunks.push(c); + this.length += c.length; + return true; +}; + +BufferStream.prototype.end = function(c) { + if (c) this.write(c); + // flatten + var buf = new Buffer(this.length); + var i = 0; + this.chunks.forEach(function(c) { + c.copy(buf, i); + i += c.length; + }); + this.emit('data', buf); + this.emit('end'); + return true; +}; + + +function SlowStream(trickle) { + this.trickle = trickle; + this.offset = 0; + this.readable = this.writable = true; +} + +util.inherits(SlowStream, stream.Stream); + +SlowStream.prototype.write = function() { + throw new Error('not implemented, just call ss.end(chunk)'); +}; + +SlowStream.prototype.pause = function() { + this.paused = true; + this.emit('pause'); +}; + +SlowStream.prototype.resume = function() { + var self = this; + if (self.ended) return; + self.emit('resume'); + if (!self.chunk) return; + self.paused = false; + emit(); + function emit() { + if (self.paused) return; + if (self.offset >= self.length) { + self.ended = true; + return self.emit('end'); + } + var end = Math.min(self.offset + self.trickle, self.length); + var c = self.chunk.slice(self.offset, end); + self.offset += c.length; + self.emit('data', c); + process.nextTick(emit); + } +}; + +SlowStream.prototype.end = function(chunk) { + // walk over the chunk in blocks. + var self = this; + self.chunk = chunk; + self.length = chunk.length; + self.resume(); + return self.ended; +}; + + + +// for each of the files, make sure that compressing and +// decompressing results in the same data, for every combination +// of the options set above. +var failures = 0; +var total = 0; +var done = 0; + +Object.keys(tests).forEach(function(file) { + var test = tests[file]; + chunkSize.forEach(function(chunkSize) { + trickle.forEach(function(trickle) { + windowBits.forEach(function(windowBits) { + level.forEach(function(level) { + memLevel.forEach(function(memLevel) { + strategy.forEach(function(strategy) { + zlibPairs.forEach(function(pair) { + var Def = pair[0]; + var Inf = pair[1]; + var opts = { level: level, + windowBits: windowBits, + memLevel: memLevel, + strategy: strategy }; + + total++; + + var def = new Def(opts); + var inf = new Inf(opts); + var ss = new SlowStream(trickle); + var buf = new BufferStream(); + + // verify that the same exact buffer comes out the other end. + buf.on('data', function(c) { + var msg = file + ' ' + + chunkSize + ' ' + + JSON.stringify(opts) + ' ' + + Def.name + ' -> ' + Inf.name; + var ok = true; + var testNum = ++done; + for (var i = 0; i < Math.max(c.length, test.length); i++) { + if (c[i] !== test[i]) { + ok = false; + failures++; + break; + } + } + if (ok) { + console.log('ok ' + (testNum) + ' ' + msg); + } else { + console.log('not ok ' + (testNum) + ' ' + msg); + console.log(' ...'); + console.log(' testfile: ' + file); + console.log(' type: ' + Def.name + ' -> ' + Inf.name); + console.log(' position: ' + i); + console.log(' options: ' + JSON.stringify(opts)); + console.log(' expect: ' + test[i]); + console.log(' actual: ' + c[i]); + console.log(' chunkSize: ' + chunkSize); + console.log(' ---'); + } + }); + + // the magic happens here. + ss.pipe(def).pipe(inf).pipe(buf); + ss.end(test); + }); + }); }); }); }); }); }); // sad stallman is sad. +}); + +process.on('exit', function(code) { + console.log('1..' + done); + assert.equal(done, total, (total - done) + ' tests left unfinished'); + assert.ok(!failures, 'some test failures'); +}); diff --git a/node-v0.8.14/test/simple/testcfg.py b/node-v0.8.14/test/simple/testcfg.py new file mode 100644 index 0000000..bb2c4d1 --- /dev/null +++ b/node-v0.8.14/test/simple/testcfg.py @@ -0,0 +1,132 @@ +# Copyright 2008 the V8 project authors. All rights reserved. +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above +# copyright notice, this list of conditions and the following +# disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of Google Inc. nor the names of its +# contributors may be used to endorse or promote products derived +# from this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +import test +import os +import shutil +from shutil import rmtree +from os import mkdir +from glob import glob +from os.path import join, dirname, exists +import re + + +FLAGS_PATTERN = re.compile(r"//\s+Flags:(.*)") +FILES_PATTERN = re.compile(r"//\s+Files:(.*)") + + +class SimpleTestCase(test.TestCase): + + def __init__(self, path, file, mode, context, config): + super(SimpleTestCase, self).__init__(context, path, mode) + self.file = file + self.config = config + self.mode = mode + self.tmpdir = join(dirname(self.config.root), 'tmp') + + def AfterRun(self, result): + # delete the whole tmp dir + try: + rmtree(self.tmpdir) + except: + pass + # make it again. + try: + mkdir(self.tmpdir) + except: + pass + + def BeforeRun(self): + # delete the whole tmp dir + try: + rmtree(self.tmpdir) + except: + pass + # make it again. + # intermittently fails on win32, so keep trying + while not os.path.exists(self.tmpdir): + try: + mkdir(self.tmpdir) + except: + pass + + def GetLabel(self): + return "%s %s" % (self.mode, self.GetName()) + + def GetName(self): + return self.path[-1] + + def GetCommand(self): + result = [self.config.context.GetVm(self.mode)] + source = open(self.file).read() + flags_match = FLAGS_PATTERN.search(source) + if flags_match: + result += flags_match.group(1).strip().split() + files_match = FILES_PATTERN.search(source); + additional_files = [] + if files_match: + additional_files += files_match.group(1).strip().split() + for a_file in additional_files: + result.append(join(dirname(self.config.root), '..', a_file)) + result += [self.file] + return result + + def GetSource(self): + return open(self.file).read() + + +class SimpleTestConfiguration(test.TestConfiguration): + + def __init__(self, context, root): + super(SimpleTestConfiguration, self).__init__(context, root) + + def Ls(self, path): + def SelectTest(name): + return name.startswith('test-') and name.endswith('.js') + return [f[:-3] for f in os.listdir(path) if SelectTest(f)] + + def ListTests(self, current_path, path, mode): + all_tests = [current_path + [t] for t in self.Ls(join(self.root))] + result = [] + for test in all_tests: + if self.Contains(path, test): + file_path = join(self.root, reduce(join, test[1:], "") + ".js") + result.append(SimpleTestCase(test, file_path, mode, self.context, self)) + return result + + def GetBuildRequirements(self): + return ['sample', 'sample=shell'] + + def GetTestStatus(self, sections, defs): + status_file = join(self.root, 'simple.status') + if exists(status_file): + test.ReadConfigurationInto(status_file, sections, defs) + + + +def GetConfiguration(context, root): + return SimpleTestConfiguration(context, root) diff --git a/node-v0.8.14/tools/addon.gypi b/node-v0.8.14/tools/addon.gypi new file mode 100644 index 0000000..89e71c0 --- /dev/null +++ b/node-v0.8.14/tools/addon.gypi @@ -0,0 +1,24 @@ +{ + 'target_defaults': { + 'type': 'loadable_module', + 'product_extension': 'node', + 'product_prefix': '', + 'include_dirs': [ + '<(node_root_dir)/src', + '<(node_root_dir)/deps/uv/include', + '<(node_root_dir)/deps/v8/include' + ], + + 'conditions': [ + [ 'OS=="mac"', { + 'libraries': [ '-undefined dynamic_lookup' ], + }], + [ 'OS=="win"', { + 'libraries': [ '-l<(node_root_dir)/$(Configuration)/node.lib' ], + }], + [ 'OS=="freebsd" or OS=="openbsd" or OS=="solaris" or (OS=="linux" and target_arch!="ia32")', { + 'cflags': [ '-fPIC' ], + }] + ] + } +} diff --git a/node-v0.8.14/tools/blog/README.md b/node-v0.8.14/tools/blog/README.md new file mode 100644 index 0000000..52a3be7 --- /dev/null +++ b/node-v0.8.14/tools/blog/README.md @@ -0,0 +1,5 @@ +# node-blog-gen + +Generates the node blog from the markdown files in doc/blog/. + + diff --git a/node-v0.8.14/tools/blog/generate.js b/node-v0.8.14/tools/blog/generate.js new file mode 100644 index 0000000..8a310fa --- /dev/null +++ b/node-v0.8.14/tools/blog/generate.js @@ -0,0 +1,283 @@ +#!/usr/bin/env node +var fs = require('fs'); +var marked = require('marked'); +var mkdirp = require('mkdirp'); +var glob = require('glob'); +var ejs = require('ejs'); +var path = require('path'); +var semver = require('semver'); + +var input = path.resolve(process.argv[2]); +var output = path.resolve(process.argv[3]); +var template = path.resolve(process.argv[4]); +var rssTemplate = path.resolve(process.argv[5]); + +var config = { + postsPerPage: 4 +}; + +console.error("argv=%j", process.argv) + +fs.readFile(template, 'utf8', function(er, contents) { + if (er) throw er; + template = ejs.compile(contents, template); + template.filename = 'index.html'; + fs.readFile(rssTemplate, 'utf8', function(er, contents) { + if (er) throw er; + rssTemplate = ejs.compile(contents, rssTemplate); + rssTemplate.filename = 'index.xml'; + readInput(); + }); +}); + +function readInput() { + glob(input + '/**/*.md', function(er, files) { + if (er) throw er; + readFiles(files); + }); +} + +function readFiles(files) { + var n = files.length; + var data = { files: {}, feeds: {}, posts: {}}; + + files.forEach(function(file) { + fs.readFile(file, 'utf8', next(file)); + }); + + function next(file) { return function(er, contents) { + if (er) throw er; + if (contents) { + contents = parseFile(file, contents); + if (contents) { + data.files[file] = contents + } + } + if (--n === 0) { + buildOutput(data); + } + }} +} + +function parseFile(file, contents) { + var c = contents.split('\n\n'); + var head = c.shift(); + c = c.join('\n\n'); + var post = head.split('\n').reduce(function(set, kv) { + kv = kv.split(':'); + var key = kv.shift().trim(); + var val = kv.join(':').trim(); + set[key] = val; + return set; + }, {}); + if (post.status && post.status !== 'publish') return null; + post.body = c; + post.src = file; + return post; +} + +function buildPermalinks(data) { + Object.keys(data.files).forEach(function(k) { + data.posts[k] = buildPermalink(k, data.files[k]); + }); +} + +function buildPermalink(key, post) { + var data = {}; + data.pageid = post.slug; + data.title = post.title; + data.content = post.content = marked.parse(post.body); + + // Fix for chjj/marked#56 + data.content = post.content = data.content + .replace(/\1<\/a>/g, '$1'); + + data.post = post; + + if (!post.date) throw new Error('post date is required ' + post.src); + else post.date = new Date(post.date); + var d = post.date; + + var y = d.getYear() + 1900; + var m = d.getMonth() + 1; + if (m < 10) m = '0' + m; + var d = d.getDate(); + if (d < 10) d = '0' + d; + var uri = '/' + y + '/' + m + '/' + d + '/' + post.slug + '/'; + post.data = data; + post.uri = uri; + + post.permalink = data.permalink = uri; + return data; +} + +function writeFile(uri, data, templ) { + if (!templ) templ = template; + data.uri = path.join(data.uri); + uri = path.join(uri); + var contents = templ(data); + var outdir = path.join(output, uri); + mkdirp(outdir, function(er) { + if (er) throw er; + var file = path.resolve(outdir, templ.filename); + fs.writeFile(file, contents, 'utf8', function(er) { + if (er) throw er; + console.log('wrote: ', data.pageid, path.relative(process.cwd(), file)); + }); + }); +} + +// sort in reverse chronological order +// prune out any releases that are not the most recent on their branch. +function buildFeeds(data) { + // first, sort by date. + var posts = Object.keys(data.posts).map(function(k) { + return data.posts[k].post; + }).sort(function(a, b) { + a = a.date.getTime(); + b = b.date.getTime(); + return (a === b) ? 0 : a > b ? -1 : 1; + }) + + // separate release posts by release families. + var releases = posts.reduce(function(releases, post) { + if (post.category !== 'release') return releases; + var ver = semver.parse(post.version); + if (!ver) return; + var major = +ver[1]; + var minor = +ver[2]; + var patch = +ver[3]; + var family = [major, minor]; + ver = [major, minor, patch, post]; + if (family[1] % 2) family[1]++; + family = family.join('.'); + post.family = family; + releases[family] = releases[family] || []; + releases[family].push(post); + return releases; + }, {}); + + // separate by categories. + var categories = posts.reduce(function(categories, post) { + if (!post.category) return categories; + if (!categories[post.category]) { + categories[post.category] = []; + } + categories[post.category].push(post); + return categories; + }, {}); + + // paginate categories. + for (var cat in categories) { + categories[cat] = paginate(categories[cat], cat); + } + + // filter non-latest release notices out of main feeds. + // still show the first stable release of the family, since + // it usually is an important milestone with benchmarks and stuff. + var main = posts.filter(function(post) { + if (post.version && post.family) { + var ver = semver.parse(post.version) + if (+ver[2] % 2 === 0 && +ver[3] === 0) { + // 0.x.0, where x is event + return true; + } + if (post.version && post.family && post !== releases[post.family][0]) { + return false; + } + } + return true; + }); + + // add previous/next based on main feed. + main.forEach(function (post, i, posts) { + post.next = posts[i - 1]; + post.prev = posts[i + 1]; + }) + + // paginate each feed. + main = paginate(main, ''); + + // put previous/next links on orphaned old releases so you can get back + for (var family in releases) { + releases[family].forEach(function(post, i, family) { + if (!post.next) post.next = family[i - 1]; + if (!post.next) post.next = family[0].next; + // if (!post.next) post.next = family[0]; + + if (!post.prev) post.prev = family[i + 1]; + if (!post.prev) post.prev = family[0].prev; + }); + // paginate + releases[family] = paginate(releases[family], 'release-' + family); + } + + // paginate + data.feeds = { + main: main, + categories: categories, + releases: releases + }; +} + +function paginate(set, title) { + var pp = config.postsPerPage || 5 + var pages = []; + for (var i = 0; i < set.length; i += pp) { + pages.push(set.slice(i, i + pp)); + } + var id = title.replace(/[^a-zA-Z0-9.]+/g, '-'); + return { id: id || 'index', pageid: id, posts: set, pages: pages, title: title }; +} + +function writePermalinks(data) { + Object.keys(data.posts).forEach(function(k) { + var post = data.posts[k]; + writeFile(post.permalink, post); + }); +} + +function writeFeeds(data) { + writeFeed(data.feeds.main); + + for (var feed in data.feeds.categories) { + writeFeed(data.feeds.categories[feed]); + } + for (var feed in data.feeds.releases) { + writeFeed(data.feeds.releases[feed]); + } +} + +function writeFeed(feed) { + var title = feed.title; + feed.pages.forEach(function(page, p, pages) { + writePaginated(feed.title, page, p, pages.length, feed.id); + }); +} + +function writePaginated(title, posts, p, total, id) { + var uri = '/' + encodeURIComponent(title) + '/'; + var d = { + title: title, + page: p, + posts: posts, + total: total, + paginated: true, + pageid: id + '-' + p, + uri: uri + }; + if (p === 0) { + writeFile(uri, d); + writeFile('/feed' + uri, d, rssTemplate); + } + writeFile(uri + p, d); + writeFile('/feed' + uri + p, d, rssTemplate); +} + +function buildOutput(data) { + buildPermalinks(data); + buildFeeds(data); + writePermalinks(data); + writeFeeds(data); +} + diff --git a/node-v0.8.14/tools/blog/templates/index.ejs b/node-v0.8.14/tools/blog/templates/index.ejs new file mode 100644 index 0000000..0db16e5 --- /dev/null +++ b/node-v0.8.14/tools/blog/templates/index.ejs @@ -0,0 +1 @@ +This is some ejs diff --git a/node-v0.8.14/tools/blog/wp-to-markdown.js b/node-v0.8.14/tools/blog/wp-to-markdown.js new file mode 100644 index 0000000..65ec2d5 --- /dev/null +++ b/node-v0.8.14/tools/blog/wp-to-markdown.js @@ -0,0 +1,189 @@ +var sax = require('sax'); +var fs = require('fs'); +var parser = sax.parser(false, { lowercase: true }); +var assert = require('assert'); +var mkdirp = require('mkdirp'); +var url = require('url'); + +var input = fs.createReadStream(process.argv[2]); +input.on('data', function(c) { + parser.write(c.toString()); +}); +input.on('end', parser.end.bind(parser)); + +var post = null; +var author = null; +var authors = {}; +mkdirp.sync('out'); + +parser.onopentag = function (tag) { + switch (tag.name) { + case 'wp:author': + assert(author === null); + author = {}; + author.text = ''; + return; + + case 'wp:author_login': + assert(author); + author.field = 'login'; + author.text = ''; + return; + + case 'wp:author_display_name': + assert(author); + author.field = 'name'; + author.text = ''; + return + + case 'wp:author_first_name': + assert(author); + author.field = 'first_name'; + author.text = ''; + return; + + case 'wp:author_last_name': + assert(author); + author.field = 'last_name'; + author.text = ''; + return; + + case 'item': + assert(post === null); + post = {}; + post.text = ''; + return; + + case 'title': + if (post === null) return; + post.field = 'title'; + return + + case 'pubDate': + case 'wp:post_date': + post.field = 'date'; + return; + + case 'dc:creator': + post.field = 'author'; + return; + + case 'wp:status': + post.field = 'status'; + return; + + case 'category': + post.field = 'category'; + return; + + case 'content:encoded': + post.field = 'body'; + return; + + case 'link': + if (post) post.field = 'link'; + return; + + default: + if (post) post.field = null; + if (author) author.field = null; + return; + } +}; + +parser.onclosetag = function (tagName, tag) { + switch (tagName) { + case 'wp:author': + assert(author); + finishAuthor(); + return; + case 'item': + assert(post); + finishPost(); + return; + default: + if (post && post.field || author && author.field) finishField(); + return; + } +}; + +parser.ontext = parser.oncdata = function (text) { + if (author) { + if (author.field) author.text += text; + else author.text = ''; + } else if (post) { + if (post.field) post.text += text; + else post.field = ''; + } +}; + +function finishField() { + if (post && post.field) { + post[post.field] = post.text; + post.field = null; + post.text = ''; + } else if (author && author.field) { + author[author.field] = author.text; + author.field = null; + author.text = ''; + } +} + +function finishPost() { + // don't port drafts. + if (post.status === 'draft') { + return post = null; + } + post.date = new Date(post.date); + + if (post.link) { + post.slug = + url.parse(post.link) + .pathname + .replace(/\/+$/, '') + .split('/') + .pop(); + } + if (!post.slug) { + post.slug = + (post.title + '-' + post.date.toISOString()) + .replace(/[^a-z0-9]+/gi, '-') + .replace(/^-|-$/g, '') + .toLowerCase(); + } + post.slug = post.slug || '-'; + + delete post.text + delete post.link + delete post.field + post.author = authors[post.author] || post.author; + + post.body = post.body || ''; + + // actually write it! + var output = []; + Object.keys(post) + .filter(function (f) { return f !== 'body' }).forEach(function (k) { + output.push(k + ': ' + post[k]); + }) + output = output.join('\n') + '\n\n' + post.body.trim() + '\n'; + + var f = 'out/' + post.category + '/' + post.slug + '.md'; + console.log(f, post.title); + mkdirp.sync('out/' + post.category) + fs.writeFileSync(f, output, 'utf8'); + + post = null; +} + +function finishAuthor () { + author.name = author.name || + (author.first_name + ' ' + author.last_name) || + author.login; + delete author.first_name + delete author.last_name + delete author.text + delete author.field + authors[author.login] = author.name + author = null; +} diff --git a/node-v0.8.14/tools/build-changelog.sh b/node-v0.8.14/tools/build-changelog.sh new file mode 100644 index 0000000..c6c219d --- /dev/null +++ b/node-v0.8.14/tools/build-changelog.sh @@ -0,0 +1,16 @@ +#!/bin/bash +cat ChangeLog \ + | sed -E 's|([^/ ]+/[^#]+)#([0-9]+)|[\1#\2](https://github.com/\1/issues/\2)|g' \ + | sed -E 's| #([0-9]+)| [#\1](https://github.com/joyent/node/issues/\1)|g' \ + | sed -E 's|([0-9]+\.[0-9]+\.[0-9]+),? Version ([0-9]+\.[0-9]+\.[0-9]+)|\ +# \1 Version \2|g' \ + | sed -E 's|(,? ?)([0-9a-g]{6})[0-9a-g]{34}|\1[\2](https://github.com/joyent/node/commit/\2)|g' \ + | ./node tools/doc/node_modules/.bin/marked > out/doc/changelog-body.html + +cat doc/changelog-head.html \ + out/doc/changelog-body.html \ + doc/changelog-foot.html \ + | sed -E 's|__VERSION__|v'$(python tools/getnodeversion.py)'|g' \ + > out/doc/changelog.html + +rm out/doc/changelog-body.html diff --git a/node-v0.8.14/tools/changelog-head.sh b/node-v0.8.14/tools/changelog-head.sh new file mode 100644 index 0000000..e0cec16 --- /dev/null +++ b/node-v0.8.14/tools/changelog-head.sh @@ -0,0 +1,15 @@ +#!/bin/bash +cat ChangeLog | { + s=-1 + while read line; do + if [ "${line:0:1}" == "2" ]; then + let "++s" + fi + if [ $s -eq 1 ]; then + exit + else + echo "$line" + fi + done +} + diff --git a/node-v0.8.14/tools/closure_linter/PKG-INFO b/node-v0.8.14/tools/closure_linter/PKG-INFO new file mode 100644 index 0000000..b6e71c8 --- /dev/null +++ b/node-v0.8.14/tools/closure_linter/PKG-INFO @@ -0,0 +1,10 @@ +Metadata-Version: 1.0 +Name: closure_linter +Version: 2.2.6 +Summary: Closure Linter +Home-page: http://code.google.com/p/closure-linter +Author: The Closure Linter Authors +Author-email: opensource@google.com +License: Apache +Description: UNKNOWN +Platform: UNKNOWN diff --git a/node-v0.8.14/tools/closure_linter/README b/node-v0.8.14/tools/closure_linter/README new file mode 100644 index 0000000..4a21b2d --- /dev/null +++ b/node-v0.8.14/tools/closure_linter/README @@ -0,0 +1,9 @@ +This repository contains the Closure Linter - a style checker for JavaScript. + +To install the application, run + python ./setup.py install + +After installing, you get two helper applications installed into /usr/local/bin: + + gjslint.py - runs the linter and checks for errors + fixjsstyle.py - tries to fix errors automatically diff --git a/node-v0.8.14/tools/closure_linter/closure_linter.egg-info/PKG-INFO b/node-v0.8.14/tools/closure_linter/closure_linter.egg-info/PKG-INFO new file mode 100644 index 0000000..918e243 --- /dev/null +++ b/node-v0.8.14/tools/closure_linter/closure_linter.egg-info/PKG-INFO @@ -0,0 +1,10 @@ +Metadata-Version: 1.0 +Name: closure-linter +Version: 2.2.6 +Summary: Closure Linter +Home-page: http://code.google.com/p/closure-linter +Author: The Closure Linter Authors +Author-email: opensource@google.com +License: Apache +Description: UNKNOWN +Platform: UNKNOWN diff --git a/node-v0.8.14/tools/closure_linter/closure_linter.egg-info/SOURCES.txt b/node-v0.8.14/tools/closure_linter/closure_linter.egg-info/SOURCES.txt new file mode 100644 index 0000000..b64d829 --- /dev/null +++ b/node-v0.8.14/tools/closure_linter/closure_linter.egg-info/SOURCES.txt @@ -0,0 +1,41 @@ +README +setup.py +closure_linter/__init__.py +closure_linter/checker.py +closure_linter/checkerbase.py +closure_linter/ecmalintrules.py +closure_linter/ecmametadatapass.py +closure_linter/error_fixer.py +closure_linter/errorrules.py +closure_linter/errors.py +closure_linter/fixjsstyle.py +closure_linter/fixjsstyle_test.py +closure_linter/full_test.py +closure_linter/gjslint.py +closure_linter/indentation.py +closure_linter/javascriptlintrules.py +closure_linter/javascriptstatetracker.py +closure_linter/javascriptstatetracker_test.py +closure_linter/javascripttokenizer.py +closure_linter/javascripttokens.py +closure_linter/statetracker.py +closure_linter/tokenutil.py +closure_linter.egg-info/PKG-INFO +closure_linter.egg-info/SOURCES.txt +closure_linter.egg-info/dependency_links.txt +closure_linter.egg-info/entry_points.txt +closure_linter.egg-info/requires.txt +closure_linter.egg-info/top_level.txt +closure_linter/common/__init__.py +closure_linter/common/error.py +closure_linter/common/erroraccumulator.py +closure_linter/common/errorhandler.py +closure_linter/common/errorprinter.py +closure_linter/common/filetestcase.py +closure_linter/common/htmlutil.py +closure_linter/common/lintrunner.py +closure_linter/common/matcher.py +closure_linter/common/position.py +closure_linter/common/simplefileflags.py +closure_linter/common/tokenizer.py +closure_linter/common/tokens.py \ No newline at end of file diff --git a/node-v0.8.14/tools/closure_linter/closure_linter.egg-info/dependency_links.txt b/node-v0.8.14/tools/closure_linter/closure_linter.egg-info/dependency_links.txt new file mode 100644 index 0000000..8b13789 --- /dev/null +++ b/node-v0.8.14/tools/closure_linter/closure_linter.egg-info/dependency_links.txt @@ -0,0 +1 @@ + diff --git a/node-v0.8.14/tools/closure_linter/closure_linter.egg-info/entry_points.txt b/node-v0.8.14/tools/closure_linter/closure_linter.egg-info/entry_points.txt new file mode 100644 index 0000000..459b9d0 --- /dev/null +++ b/node-v0.8.14/tools/closure_linter/closure_linter.egg-info/entry_points.txt @@ -0,0 +1,4 @@ +[console_scripts] +fixjsstyle = closure_linter.fixjsstyle:main +gjslint = closure_linter.gjslint:main + diff --git a/node-v0.8.14/tools/closure_linter/closure_linter.egg-info/requires.txt b/node-v0.8.14/tools/closure_linter/closure_linter.egg-info/requires.txt new file mode 100644 index 0000000..71b67f1 --- /dev/null +++ b/node-v0.8.14/tools/closure_linter/closure_linter.egg-info/requires.txt @@ -0,0 +1 @@ +python-gflags \ No newline at end of file diff --git a/node-v0.8.14/tools/closure_linter/closure_linter.egg-info/top_level.txt b/node-v0.8.14/tools/closure_linter/closure_linter.egg-info/top_level.txt new file mode 100644 index 0000000..7ece71f --- /dev/null +++ b/node-v0.8.14/tools/closure_linter/closure_linter.egg-info/top_level.txt @@ -0,0 +1 @@ +closure_linter diff --git a/node-v0.8.14/tools/closure_linter/closure_linter/__init__.py b/node-v0.8.14/tools/closure_linter/closure_linter/__init__.py new file mode 100755 index 0000000..4265cc3 --- /dev/null +++ b/node-v0.8.14/tools/closure_linter/closure_linter/__init__.py @@ -0,0 +1 @@ +#!/usr/bin/env python diff --git a/node-v0.8.14/tools/closure_linter/closure_linter/checker.py b/node-v0.8.14/tools/closure_linter/closure_linter/checker.py new file mode 100755 index 0000000..4cdac93 --- /dev/null +++ b/node-v0.8.14/tools/closure_linter/closure_linter/checker.py @@ -0,0 +1,82 @@ +#!/usr/bin/env python +# +# Copyright 2007 The Closure Linter Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS-IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Core methods for checking JS files for common style guide violations.""" + +__author__ = ('robbyw@google.com (Robert Walker)', + 'ajp@google.com (Andy Perelson)') + +import gflags as flags + +from closure_linter import checkerbase +from closure_linter import ecmametadatapass +from closure_linter import errors +from closure_linter import javascriptlintrules +from closure_linter import javascriptstatetracker +from closure_linter.common import errorprinter +from closure_linter.common import lintrunner + +flags.DEFINE_list('limited_doc_files', ['dummy.js', 'externs.js'], + 'List of files with relaxed documentation checks. Will not ' + 'report errors for missing documentation, some missing ' + 'descriptions, or methods whose @return tags don\'t have a ' + 'matching return statement.') + + +class JavaScriptStyleChecker(checkerbase.CheckerBase): + """Checker that applies JavaScriptLintRules.""" + + def __init__(self, error_handler): + """Initialize an JavaScriptStyleChecker object. + + Args: + error_handler: Error handler to pass all errors to + """ + checkerbase.CheckerBase.__init__( + self, + error_handler=error_handler, + lint_rules=javascriptlintrules.JavaScriptLintRules(), + state_tracker=javascriptstatetracker.JavaScriptStateTracker( + closurized_namespaces=flags.FLAGS.closurized_namespaces), + metadata_pass=ecmametadatapass.EcmaMetaDataPass(), + limited_doc_files=flags.FLAGS.limited_doc_files) + + +class GJsLintRunner(lintrunner.LintRunner): + """Wrapper class to run GJsLint.""" + + def Run(self, filenames, error_handler=None): + """Run GJsLint on the given filenames. + + Args: + filenames: The filenames to check + error_handler: An optional ErrorHandler object, an ErrorPrinter is used if + none is specified. + + Returns: + error_count, file_count: The number of errors and the number of files that + contain errors. + """ + if not error_handler: + error_handler = errorprinter.ErrorPrinter(errors.NEW_ERRORS) + + checker = JavaScriptStyleChecker(error_handler) + + # Check the list of files. + for filename in filenames: + checker.Check(filename) + + return error_handler diff --git a/node-v0.8.14/tools/closure_linter/closure_linter/checkerbase.py b/node-v0.8.14/tools/closure_linter/closure_linter/checkerbase.py new file mode 100755 index 0000000..123cb72 --- /dev/null +++ b/node-v0.8.14/tools/closure_linter/closure_linter/checkerbase.py @@ -0,0 +1,237 @@ +#!/usr/bin/env python +# +# Copyright 2008 The Closure Linter Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS-IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Base classes for writing checkers that operate on tokens.""" + +__author__ = ('robbyw@google.com (Robert Walker)', + 'ajp@google.com (Andy Perelson)', + 'jacobr@google.com (Jacob Richman)') + +import traceback + +import gflags as flags +from closure_linter import ecmametadatapass +from closure_linter import errorrules +from closure_linter import errors +from closure_linter import javascripttokenizer +from closure_linter.common import error +from closure_linter.common import htmlutil + +FLAGS = flags.FLAGS +flags.DEFINE_boolean('debug_tokens', False, + 'Whether to print all tokens for debugging.') + +flags.DEFINE_boolean('error_trace', False, + 'Whether to show error exceptions.') + +class LintRulesBase(object): + """Base class for all classes defining the lint rules for a language.""" + + def __init__(self): + self.__checker = None + + def Initialize(self, checker, limited_doc_checks, is_html): + """Initializes to prepare to check a file. + + Args: + checker: Class to report errors to. + limited_doc_checks: Whether doc checking is relaxed for this file. + is_html: Whether the file is an HTML file with extracted contents. + """ + self.__checker = checker + self._limited_doc_checks = limited_doc_checks + self._is_html = is_html + + def _HandleError(self, code, message, token, position=None, + fix_data=None): + """Call the HandleError function for the checker we are associated with.""" + if errorrules.ShouldReportError(code): + self.__checker.HandleError(code, message, token, position, fix_data) + + def CheckToken(self, token, parser_state): + """Checks a token, given the current parser_state, for warnings and errors. + + Args: + token: The current token under consideration. + parser_state: Object that indicates the parser state in the page. + + Raises: + TypeError: If not overridden. + """ + raise TypeError('Abstract method CheckToken not implemented') + + def Finalize(self, parser_state, tokenizer_mode): + """Perform all checks that need to occur after all lines are processed. + + Args: + parser_state: State of the parser after parsing all tokens + tokenizer_mode: Mode of the tokenizer after parsing the entire page + + Raises: + TypeError: If not overridden. + """ + raise TypeError('Abstract method Finalize not implemented') + + +class CheckerBase(object): + """This class handles checking a LintRules object against a file.""" + + def __init__(self, error_handler, lint_rules, state_tracker, + limited_doc_files=None, metadata_pass=None): + """Initialize a checker object. + + Args: + error_handler: Object that handles errors. + lint_rules: LintRules object defining lint errors given a token + and state_tracker object. + state_tracker: Object that tracks the current state in the token stream. + limited_doc_files: List of filenames that are not required to have + documentation comments. + metadata_pass: Object that builds metadata about the token stream. + """ + self.__error_handler = error_handler + self.__lint_rules = lint_rules + self.__state_tracker = state_tracker + self.__metadata_pass = metadata_pass + self.__limited_doc_files = limited_doc_files + self.__tokenizer = javascripttokenizer.JavaScriptTokenizer() + self.__has_errors = False + + def HandleError(self, code, message, token, position=None, + fix_data=None): + """Prints out the given error message including a line number. + + Args: + code: The error code. + message: The error to print. + token: The token where the error occurred, or None if it was a file-wide + issue. + position: The position of the error, defaults to None. + fix_data: Metadata used for fixing the error. + """ + self.__has_errors = True + self.__error_handler.HandleError( + error.Error(code, message, token, position, fix_data)) + + def HasErrors(self): + """Returns true if the style checker has found any errors. + + Returns: + True if the style checker has found any errors. + """ + return self.__has_errors + + def Check(self, filename): + """Checks the file, printing warnings and errors as they are found. + + Args: + filename: The name of the file to check. + """ + try: + f = open(filename) + except IOError: + self.__error_handler.HandleFile(filename, None) + self.HandleError(errors.FILE_NOT_FOUND, 'File not found', None) + self.__error_handler.FinishFile() + return + + try: + if filename.endswith('.html') or filename.endswith('.htm'): + self.CheckLines(filename, htmlutil.GetScriptLines(f), True) + else: + self.CheckLines(filename, f, False) + finally: + f.close() + + def CheckLines(self, filename, lines_iter, is_html): + """Checks a file, given as an iterable of lines, for warnings and errors. + + Args: + filename: The name of the file to check. + lines_iter: An iterator that yields one line of the file at a time. + is_html: Whether the file being checked is an HTML file with extracted + contents. + + Returns: + A boolean indicating whether the full file could be checked or if checking + failed prematurely. + """ + limited_doc_checks = False + if self.__limited_doc_files: + for limited_doc_filename in self.__limited_doc_files: + if filename.endswith(limited_doc_filename): + limited_doc_checks = True + break + + state_tracker = self.__state_tracker + lint_rules = self.__lint_rules + state_tracker.Reset() + lint_rules.Initialize(self, limited_doc_checks, is_html) + + token = self.__tokenizer.TokenizeFile(lines_iter) + + parse_error = None + if self.__metadata_pass: + try: + self.__metadata_pass.Reset() + self.__metadata_pass.Process(token) + except ecmametadatapass.ParseError, caught_parse_error: + if FLAGS.error_trace: + traceback.print_exc() + parse_error = caught_parse_error + except Exception: + print 'Internal error in %s' % filename + traceback.print_exc() + return False + + self.__error_handler.HandleFile(filename, token) + + while token: + if FLAGS.debug_tokens: + print token + + if parse_error and parse_error.token == token: + # Report any parse errors from above once we find the token. + message = ('Error parsing file at token "%s". Unable to ' + 'check the rest of file.' % token.string) + self.HandleError(errors.FILE_DOES_NOT_PARSE, message, token) + self.__error_handler.FinishFile() + return False + + if FLAGS.error_trace: + state_tracker.HandleToken(token, state_tracker.GetLastNonSpaceToken()) + else: + try: + state_tracker.HandleToken(token, state_tracker.GetLastNonSpaceToken()) + except: + self.HandleError(errors.FILE_DOES_NOT_PARSE, + ('Error parsing file at token "%s". Unable to ' + 'check the rest of file.' % token.string), + token) + self.__error_handler.FinishFile() + return False + + # Check the token for style guide violations. + lint_rules.CheckToken(token, state_tracker) + + state_tracker.HandleAfterToken(token) + + # Move to the next token. + token = token.next + + lint_rules.Finalize(state_tracker, self.__tokenizer.mode) + self.__error_handler.FinishFile() + return True diff --git a/node-v0.8.14/tools/closure_linter/closure_linter/common/__init__.py b/node-v0.8.14/tools/closure_linter/closure_linter/common/__init__.py new file mode 100755 index 0000000..4265cc3 --- /dev/null +++ b/node-v0.8.14/tools/closure_linter/closure_linter/common/__init__.py @@ -0,0 +1 @@ +#!/usr/bin/env python diff --git a/node-v0.8.14/tools/closure_linter/closure_linter/common/error.py b/node-v0.8.14/tools/closure_linter/closure_linter/common/error.py new file mode 100755 index 0000000..0e3b476 --- /dev/null +++ b/node-v0.8.14/tools/closure_linter/closure_linter/common/error.py @@ -0,0 +1,65 @@ +#!/usr/bin/env python +# +# Copyright 2007 The Closure Linter Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS-IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Error object commonly used in linters.""" + +__author__ = ('robbyw@google.com (Robert Walker)', + 'ajp@google.com (Andy Perelson)') + + +class Error(object): + """Object representing a style error.""" + + def __init__(self, code, message, token, position, fix_data): + """Initialize the error object. + + Args: + code: The numeric error code. + message: The error message string. + token: The tokens.Token where the error occurred. + position: The position of the error within the token. + fix_data: Data to be used in autofixing. Codes with fix_data are: + GOOG_REQUIRES_NOT_ALPHABETIZED - List of string value tokens that are + class names in goog.requires calls. + """ + self.code = code + self.message = message + self.token = token + self.position = position + if token: + self.start_index = token.start_index + else: + self.start_index = 0 + self.fix_data = fix_data + if self.position: + self.start_index += self.position.start + + def Compare(a, b): + """Compare two error objects, by source code order. + + Args: + a: First error object. + b: Second error object. + + Returns: + A Negative/0/Positive number when a is before/the same as/after b. + """ + line_diff = a.token.line_number - b.token.line_number + if line_diff: + return line_diff + + return a.start_index - b.start_index + Compare = staticmethod(Compare) diff --git a/node-v0.8.14/tools/closure_linter/closure_linter/common/erroraccumulator.py b/node-v0.8.14/tools/closure_linter/closure_linter/common/erroraccumulator.py new file mode 100755 index 0000000..7bb0c97 --- /dev/null +++ b/node-v0.8.14/tools/closure_linter/closure_linter/common/erroraccumulator.py @@ -0,0 +1,46 @@ +#!/usr/bin/env python +# +# Copyright 2008 The Closure Linter Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS-IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Linter error handler class that accumulates an array of errors.""" + +__author__ = ('robbyw@google.com (Robert Walker)', + 'ajp@google.com (Andy Perelson)') + + +from closure_linter.common import errorhandler + + +class ErrorAccumulator(errorhandler.ErrorHandler): + """Error handler object that accumulates errors in a list.""" + + def __init__(self): + self._errors = [] + + def HandleError(self, error): + """Append the error to the list. + + Args: + error: The error object + """ + self._errors.append((error.token.line_number, error.code)) + + def GetErrors(self): + """Returns the accumulated errors. + + Returns: + A sequence of errors. + """ + return self._errors diff --git a/node-v0.8.14/tools/closure_linter/closure_linter/common/errorhandler.py b/node-v0.8.14/tools/closure_linter/closure_linter/common/errorhandler.py new file mode 100755 index 0000000..764d54d --- /dev/null +++ b/node-v0.8.14/tools/closure_linter/closure_linter/common/errorhandler.py @@ -0,0 +1,61 @@ +#!/usr/bin/env python +# +# Copyright 2008 The Closure Linter Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS-IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Interface for a linter error handler. + +Error handlers aggregate a set of errors from multiple files and can optionally +perform some action based on the reported errors, for example, logging the error +or automatically fixing it. +""" + +__author__ = ('robbyw@google.com (Robert Walker)', + 'ajp@google.com (Andy Perelson)') + + +class ErrorHandler(object): + """Error handler interface.""" + + def __init__(self): + if self.__class__ == ErrorHandler: + raise NotImplementedError('class ErrorHandler is abstract') + + def HandleFile(self, filename, first_token): + """Notifies this ErrorHandler that subsequent errors are in filename. + + Args: + filename: The file being linted. + first_token: The first token of the file. + """ + + def HandleError(self, error): + """Append the error to the list. + + Args: + error: The error object + """ + + def FinishFile(self): + """Finishes handling the current file. + + Should be called after all errors in a file have been handled. + """ + + def GetErrors(self): + """Returns the accumulated errors. + + Returns: + A sequence of errors. + """ diff --git a/node-v0.8.14/tools/closure_linter/closure_linter/common/errorprinter.py b/node-v0.8.14/tools/closure_linter/closure_linter/common/errorprinter.py new file mode 100755 index 0000000..c975406 --- /dev/null +++ b/node-v0.8.14/tools/closure_linter/closure_linter/common/errorprinter.py @@ -0,0 +1,203 @@ +#!/usr/bin/env python +# +# Copyright 2008 The Closure Linter Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS-IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Linter error handler class that prints errors to stdout.""" + +__author__ = ('robbyw@google.com (Robert Walker)', + 'ajp@google.com (Andy Perelson)') + +from closure_linter.common import error +from closure_linter.common import errorhandler + +Error = error.Error + + +# The error message is of the format: +# Line , E:: message +DEFAULT_FORMAT = 1 + +# The error message is of the format: +# filename:[line number]:message +UNIX_FORMAT = 2 + + +class ErrorPrinter(errorhandler.ErrorHandler): + """ErrorHandler that prints errors to stdout.""" + + def __init__(self, new_errors=None): + """Initializes this error printer. + + Args: + new_errors: A sequence of error codes representing recently introduced + errors, defaults to None. + """ + # Number of errors + self._error_count = 0 + + # Number of new errors + self._new_error_count = 0 + + # Number of files checked + self._total_file_count = 0 + + # Number of files with errors + self._error_file_count = 0 + + # Dict of file name to number of errors + self._file_table = {} + + # List of errors for each file + self._file_errors = None + + # Current file + self._filename = None + + self._format = DEFAULT_FORMAT + + if new_errors: + self._new_errors = frozenset(new_errors) + else: + self._new_errors = frozenset(set()) + + def SetFormat(self, format): + """Sets the print format of errors. + + Args: + format: One of {DEFAULT_FORMAT, UNIX_FORMAT}. + """ + self._format = format + + def HandleFile(self, filename, first_token): + """Notifies this ErrorPrinter that subsequent errors are in filename. + + Sets the current file name, and sets a flag stating the header for this file + has not been printed yet. + + Should be called by a linter before a file is style checked. + + Args: + filename: The name of the file about to be checked. + first_token: The first token in the file, or None if there was an error + opening the file + """ + if self._filename and self._file_table[self._filename]: + print + + self._filename = filename + self._file_table[filename] = 0 + self._total_file_count += 1 + self._file_errors = [] + + def HandleError(self, error): + """Prints a formatted error message about the specified error. + + The error message is of the format: + Error #, line #: message + + Args: + error: The error object + """ + self._file_errors.append(error) + self._file_table[self._filename] += 1 + self._error_count += 1 + + if self._new_errors and error.code in self._new_errors: + self._new_error_count += 1 + + def _PrintError(self, error): + """Prints a formatted error message about the specified error. + + Args: + error: The error object + """ + new_error = self._new_errors and error.code in self._new_errors + if self._format == DEFAULT_FORMAT: + line = '' + if error.token: + line = 'Line %d, ' % error.token.line_number + + code = 'E:%04d' % error.code + if new_error: + print '%s%s: (New error) %s' % (line, code, error.message) + else: + print '%s%s: %s' % (line, code, error.message) + else: + # UNIX format + filename = self._filename + line = '' + if error.token: + line = '%d' % error.token.line_number + + error_code = '%04d' % error.code + if new_error: + error_code = 'New Error ' + error_code + print '%s:%s:(%s) %s' % (filename, line, error_code, error.message) + + def FinishFile(self): + """Finishes handling the current file.""" + if self._file_errors: + self._error_file_count += 1 + + if self._format != UNIX_FORMAT: + print '----- FILE : %s -----' % (self._filename) + + self._file_errors.sort(Error.Compare) + + for error in self._file_errors: + self._PrintError(error) + + def HasErrors(self): + """Whether this error printer encountered any errors. + + Returns: + True if the error printer encountered any errors. + """ + return self._error_count + + def HasNewErrors(self): + """Whether this error printer encountered any new errors. + + Returns: + True if the error printer encountered any new errors. + """ + return self._new_error_count + + def HasOldErrors(self): + """Whether this error printer encountered any old errors. + + Returns: + True if the error printer encountered any old errors. + """ + return self._error_count - self._new_error_count + + def PrintSummary(self): + """Print a summary of the number of errors and files.""" + if self.HasErrors() or self.HasNewErrors(): + print ('Found %d errors, including %d new errors, in %d files ' + '(%d files OK).' % ( + self._error_count, + self._new_error_count, + self._error_file_count, + self._total_file_count - self._error_file_count)) + else: + print '%d files checked, no errors found.' % self._total_file_count + + def PrintFileSummary(self): + """Print a detailed summary of the number of errors in each file.""" + keys = self._file_table.keys() + keys.sort() + for filename in keys: + print '%s: %d' % (filename, self._file_table[filename]) diff --git a/node-v0.8.14/tools/closure_linter/closure_linter/common/filetestcase.py b/node-v0.8.14/tools/closure_linter/closure_linter/common/filetestcase.py new file mode 100755 index 0000000..ae4b883 --- /dev/null +++ b/node-v0.8.14/tools/closure_linter/closure_linter/common/filetestcase.py @@ -0,0 +1,105 @@ +#!/usr/bin/env python +# +# Copyright 2007 The Closure Linter Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS-IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Test case that runs a checker on a file, matching errors against annotations. + +Runs the given checker on the given file, accumulating all errors. The list +of errors is then matched against those annotated in the file. Based heavily +on devtools/javascript/gpylint/full_test.py. +""" + +__author__ = ('robbyw@google.com (Robert Walker)', + 'ajp@google.com (Andy Perelson)') + +import re + +import unittest as googletest +from closure_linter.common import erroraccumulator + + +class AnnotatedFileTestCase(googletest.TestCase): + """Test case to run a linter against a single file.""" + + # Matches an all caps letters + underscores error identifer + _MESSAGE = {'msg': '[A-Z][A-Z_]+'} + # Matches a //, followed by an optional line number with a +/-, followed by a + # list of message IDs. Used to extract expected messages from testdata files. + # TODO(robbyw): Generalize to use different commenting patterns. + _EXPECTED_RE = re.compile(r'\s*//\s*(?:(?P[+-]?[0-9]+):)?' + r'\s*(?P%(msg)s(?:,\s*%(msg)s)*)' % _MESSAGE) + + def __init__(self, filename, runner, converter): + """Create a single file lint test case. + + Args: + filename: Filename to test. + runner: Object implementing the LintRunner interface that lints a file. + converter: Function taking an error string and returning an error code. + """ + + googletest.TestCase.__init__(self, 'runTest') + self._filename = filename + self._messages = [] + self._runner = runner + self._converter = converter + + def shortDescription(self): + """Provides a description for the test.""" + return 'Run linter on %s' % self._filename + + def runTest(self): + """Runs the test.""" + try: + filename = self._filename + stream = open(filename) + except IOError, ex: + raise IOError('Could not find testdata resource for %s: %s' % + (self._filename, ex)) + + expected = self._GetExpectedMessages(stream) + got = self._ProcessFileAndGetMessages(filename) + self.assertEqual(expected, got) + + def _GetExpectedMessages(self, stream): + """Parse a file and get a sorted list of expected messages.""" + messages = [] + for i, line in enumerate(stream): + match = self._EXPECTED_RE.search(line) + if match: + line = match.group('line') + msg_ids = match.group('msgs') + if line is None: + line = i + 1 + elif line.startswith('+') or line.startswith('-'): + line = i + 1 + int(line) + else: + line = int(line) + for msg_id in msg_ids.split(','): + # Ignore a spurious message from the license preamble. + if msg_id != 'WITHOUT': + messages.append((line, self._converter(msg_id.strip()))) + stream.seek(0) + messages.sort() + return messages + + def _ProcessFileAndGetMessages(self, filename): + """Trap gpylint's output parse it to get messages added.""" + errors = erroraccumulator.ErrorAccumulator() + self._runner.Run([filename], errors) + + errors = errors.GetErrors() + errors.sort() + return errors diff --git a/node-v0.8.14/tools/closure_linter/closure_linter/common/htmlutil.py b/node-v0.8.14/tools/closure_linter/closure_linter/common/htmlutil.py new file mode 100755 index 0000000..26d44c5 --- /dev/null +++ b/node-v0.8.14/tools/closure_linter/closure_linter/common/htmlutil.py @@ -0,0 +1,170 @@ +#!/usr/bin/env python +# +# Copyright 2007 The Closure Linter Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS-IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Utilities for dealing with HTML.""" + +__author__ = ('robbyw@google.com (Robert Walker)') + +import cStringIO +import formatter +import htmllib +import HTMLParser +import re + + +class ScriptExtractor(htmllib.HTMLParser): + """Subclass of HTMLParser that extracts script contents from an HTML file. + + Also inserts appropriate blank lines so that line numbers in the extracted + code match the line numbers in the original HTML. + """ + + def __init__(self): + """Initialize a ScriptExtractor.""" + htmllib.HTMLParser.__init__(self, formatter.NullFormatter()) + self._in_script = False + self._text = '' + + def start_script(self, attrs): + """Internal handler for the start of a script tag. + + Args: + attrs: The attributes of the script tag, as a list of tuples. + """ + for attribute in attrs: + if attribute[0].lower() == 'src': + # Skip script tags with a src specified. + return + self._in_script = True + + def end_script(self): + """Internal handler for the end of a script tag.""" + self._in_script = False + + def handle_data(self, data): + """Internal handler for character data. + + Args: + data: The character data from the HTML file. + """ + if self._in_script: + # If the last line contains whitespace only, i.e. is just there to + # properly align a tag, strip the whitespace. + if data.rstrip(' \t') != data.rstrip(' \t\n\r\f'): + data = data.rstrip(' \t') + self._text += data + else: + self._AppendNewlines(data) + + def handle_comment(self, data): + """Internal handler for HTML comments. + + Args: + data: The text of the comment. + """ + self._AppendNewlines(data) + + def _AppendNewlines(self, data): + """Count the number of newlines in the given string and append them. + + This ensures line numbers are correct for reported errors. + + Args: + data: The data to count newlines in. + """ + # We append 'x' to both sides of the string to ensure that splitlines + # gives us an accurate count. + for i in xrange(len(('x' + data + 'x').splitlines()) - 1): + self._text += '\n' + + def GetScriptLines(self): + """Return the extracted script lines. + + Returns: + The extracted script lines as a list of strings. + """ + return self._text.splitlines() + + +def GetScriptLines(f): + """Extract script tag contents from the given HTML file. + + Args: + f: The HTML file. + + Returns: + Lines in the HTML file that are from script tags. + """ + extractor = ScriptExtractor() + + # The HTML parser chokes on text like Array., so we patch + # that bug by replacing the < with < - escaping all text inside script + # tags would be better but it's a bit of a catch 22. + contents = f.read() + contents = re.sub(r'<([^\s\w/])', + lambda x: '<%s' % x.group(1), + contents) + + extractor.feed(contents) + extractor.close() + return extractor.GetScriptLines() + + +def StripTags(str): + """Returns the string with HTML tags stripped. + + Args: + str: An html string. + + Returns: + The html string with all tags stripped. If there was a parse error, returns + the text successfully parsed so far. + """ + # Brute force approach to stripping as much HTML as possible. If there is a + # parsing error, don't strip text before parse error position, and continue + # trying from there. + final_text = '' + finished = False + while not finished: + try: + strip = _HtmlStripper() + strip.feed(str) + strip.close() + str = strip.get_output() + final_text += str + finished = True + except HTMLParser.HTMLParseError, e: + final_text += str[:e.offset] + str = str[e.offset + 1:] + + return final_text + + +class _HtmlStripper(HTMLParser.HTMLParser): + """Simple class to strip tags from HTML. + + Does so by doing nothing when encountering tags, and appending character data + to a buffer when that is encountered. + """ + def __init__(self): + self.reset() + self.__output = cStringIO.StringIO() + + def handle_data(self, d): + self.__output.write(d) + + def get_output(self): + return self.__output.getvalue() diff --git a/node-v0.8.14/tools/closure_linter/closure_linter/common/lintrunner.py b/node-v0.8.14/tools/closure_linter/closure_linter/common/lintrunner.py new file mode 100755 index 0000000..07842c7 --- /dev/null +++ b/node-v0.8.14/tools/closure_linter/closure_linter/common/lintrunner.py @@ -0,0 +1,39 @@ +#!/usr/bin/env python +# +# Copyright 2008 The Closure Linter Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS-IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Interface for a lint running wrapper.""" + +__author__ = ('robbyw@google.com (Robert Walker)', + 'ajp@google.com (Andy Perelson)') + + +class LintRunner(object): + """Interface for a lint running wrapper.""" + + def __init__(self): + if self.__class__ == LintRunner: + raise NotImplementedError('class LintRunner is abstract') + + def Run(self, filenames, error_handler): + """Run a linter on the given filenames. + + Args: + filenames: The filenames to check + error_handler: An ErrorHandler object + + Returns: + The error handler, which may have been used to collect error info. + """ diff --git a/node-v0.8.14/tools/closure_linter/closure_linter/common/matcher.py b/node-v0.8.14/tools/closure_linter/closure_linter/common/matcher.py new file mode 100755 index 0000000..9b4402c --- /dev/null +++ b/node-v0.8.14/tools/closure_linter/closure_linter/common/matcher.py @@ -0,0 +1,60 @@ +#!/usr/bin/env python +# +# Copyright 2007 The Closure Linter Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS-IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Regular expression based JavaScript matcher classes.""" + +__author__ = ('robbyw@google.com (Robert Walker)', + 'ajp@google.com (Andy Perelson)') + +from closure_linter.common import position +from closure_linter.common import tokens + +# Shorthand +Token = tokens.Token +Position = position.Position + + +class Matcher(object): + """A token matcher. + + Specifies a pattern to match, the type of token it represents, what mode the + token changes to, and what mode the token applies to. + + Modes allow more advanced grammars to be incorporated, and are also necessary + to tokenize line by line. We can have different patterns apply to different + modes - i.e. looking for documentation while in comment mode. + + Attributes: + regex: The regular expression representing this matcher. + type: The type of token indicated by a successful match. + result_mode: The mode to move to after a successful match. + """ + + def __init__(self, regex, token_type, result_mode=None, line_start=False): + """Create a new matcher template. + + Args: + regex: The regular expression to match. + token_type: The type of token a successful match indicates. + result_mode: What mode to change to after a successful match. Defaults to + None, which means to not change the current mode. + line_start: Whether this matcher should only match string at the start + of a line. + """ + self.regex = regex + self.type = token_type + self.result_mode = result_mode + self.line_start = line_start diff --git a/node-v0.8.14/tools/closure_linter/closure_linter/common/position.py b/node-v0.8.14/tools/closure_linter/closure_linter/common/position.py new file mode 100755 index 0000000..cebf17e --- /dev/null +++ b/node-v0.8.14/tools/closure_linter/closure_linter/common/position.py @@ -0,0 +1,126 @@ +#!/usr/bin/env python +# +# Copyright 2008 The Closure Linter Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS-IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Classes to represent positions within strings.""" + +__author__ = ('robbyw@google.com (Robert Walker)', + 'ajp@google.com (Andy Perelson)') + + +class Position(object): + """Object representing a segment of a string. + + Attributes: + start: The index in to the string where the segment starts. + length: The length of the string segment. + """ + + def __init__(self, start, length): + """Initialize the position object. + + Args: + start: The start index. + length: The number of characters to include. + """ + self.start = start + self.length = length + + def Get(self, string): + """Returns this range of the given string. + + Args: + string: The string to slice. + + Returns: + The string within the range specified by this object. + """ + return string[self.start:self.start + self.length] + + def Set(self, target, source): + """Sets this range within the target string to the source string. + + Args: + target: The target string. + source: The source string. + + Returns: + The resulting string + """ + return target[:self.start] + source + target[self.start + self.length:] + + def AtEnd(string): + """Create a Position representing the end of the given string. + + Args: + string: The string to represent the end of. + + Returns: + The created Position object. + """ + return Position(len(string), 0) + AtEnd = staticmethod(AtEnd) + + def IsAtEnd(self, string): + """Returns whether this position is at the end of the given string. + + Args: + string: The string to test for the end of. + + Returns: + Whether this position is at the end of the given string. + """ + return self.start == len(string) and self.length == 0 + + def AtBeginning(): + """Create a Position representing the beginning of any string. + + Returns: + The created Position object. + """ + return Position(0, 0) + AtBeginning = staticmethod(AtBeginning) + + def IsAtBeginning(self): + """Returns whether this position is at the beginning of any string. + + Returns: + Whether this position is at the beginning of any string. + """ + return self.start == 0 and self.length == 0 + + def All(string): + """Create a Position representing the entire string. + + Args: + string: The string to represent the entirety of. + + Returns: + The created Position object. + """ + return Position(0, len(string)) + All = staticmethod(All) + + def Index(index): + """Returns a Position object for the specified index. + + Args: + index: The index to select, inclusively. + + Returns: + The created Position object. + """ + return Position(index, 1) + Index = staticmethod(Index) diff --git a/node-v0.8.14/tools/closure_linter/closure_linter/common/simplefileflags.py b/node-v0.8.14/tools/closure_linter/closure_linter/common/simplefileflags.py new file mode 100755 index 0000000..3402bef --- /dev/null +++ b/node-v0.8.14/tools/closure_linter/closure_linter/common/simplefileflags.py @@ -0,0 +1,190 @@ +#!/usr/bin/env python +# +# Copyright 2008 The Closure Linter Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS-IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Determines the list of files to be checked from command line arguments.""" + +__author__ = ('robbyw@google.com (Robert Walker)', + 'ajp@google.com (Andy Perelson)') + +import glob +import os +import re + +import gflags as flags + + +FLAGS = flags.FLAGS + +flags.DEFINE_multistring( + 'recurse', + None, + 'Recurse in to the subdirectories of the given path', + short_name='r') +flags.DEFINE_list( + 'exclude_directories', + ('_demos'), + 'Exclude the specified directories (only applicable along with -r or ' + '--presubmit)', + short_name='e') +flags.DEFINE_list( + 'exclude_files', + ('deps.js'), + 'Exclude the specified files', + short_name='x') + + +def MatchesSuffixes(filename, suffixes): + """Returns whether the given filename matches one of the given suffixes. + + Args: + filename: Filename to check. + suffixes: Sequence of suffixes to check. + + Returns: + Whether the given filename matches one of the given suffixes. + """ + suffix = filename[filename.rfind('.'):] + return suffix in suffixes + + +def _GetUserSpecifiedFiles(argv, suffixes): + """Returns files to be linted, specified directly on the command line. + + Can handle the '*' wildcard in filenames, but no other wildcards. + + Args: + argv: Sequence of command line arguments. The second and following arguments + are assumed to be files that should be linted. + suffixes: Expected suffixes for the file type being checked. + + Returns: + A sequence of files to be linted. + """ + files = argv[1:] or [] + all_files = [] + lint_files = [] + + # Perform any necessary globs. + for f in files: + if f.find('*') != -1: + for result in glob.glob(f): + all_files.append(result) + else: + all_files.append(f) + + for f in all_files: + if MatchesSuffixes(f, suffixes): + lint_files.append(f) + return lint_files + + +def _GetRecursiveFiles(suffixes): + """Returns files to be checked specified by the --recurse flag. + + Args: + suffixes: Expected suffixes for the file type being checked. + + Returns: + A list of files to be checked. + """ + lint_files = [] + # Perform any request recursion + if FLAGS.recurse: + for start in FLAGS.recurse: + for root, subdirs, files in os.walk(start): + for f in files: + if MatchesSuffixes(f, suffixes): + lint_files.append(os.path.join(root, f)) + return lint_files + + +def GetAllSpecifiedFiles(argv, suffixes): + """Returns all files specified by the user on the commandline. + + Args: + argv: Sequence of command line arguments. The second and following arguments + are assumed to be files that should be linted. + suffixes: Expected suffixes for the file type + + Returns: + A list of all files specified directly or indirectly (via flags) on the + command line by the user. + """ + files = _GetUserSpecifiedFiles(argv, suffixes) + + if FLAGS.recurse: + files += _GetRecursiveFiles(suffixes) + + return FilterFiles(files) + + +def FilterFiles(files): + """Filters the list of files to be linted be removing any excluded files. + + Filters out files excluded using --exclude_files and --exclude_directories. + + Args: + files: Sequence of files that needs filtering. + + Returns: + Filtered list of files to be linted. + """ + num_files = len(files) + + ignore_dirs_regexs = [] + for ignore in FLAGS.exclude_directories: + ignore_dirs_regexs.append(re.compile(r'(^|[\\/])%s[\\/]' % ignore)) + + result_files = [] + for f in files: + add_file = True + for exclude in FLAGS.exclude_files: + if f.endswith('/' + exclude) or f == exclude: + add_file = False + break + for ignore in ignore_dirs_regexs: + if ignore.search(f): + # Break out of ignore loop so we don't add to + # filtered files. + add_file = False + break + if add_file: + # Convert everything to absolute paths so we can easily remove duplicates + # using a set. + result_files.append(os.path.abspath(f)) + + skipped = num_files - len(result_files) + if skipped: + print 'Skipping %d file(s).' % skipped + + return set(result_files) + + +def GetFileList(argv, file_type, suffixes): + """Parse the flags and return the list of files to check. + + Args: + argv: Sequence of command line arguments. + suffixes: Sequence of acceptable suffixes for the file type. + + Returns: + The list of files to check. + """ + return sorted(GetAllSpecifiedFiles(argv, suffixes)) + + +def IsEmptyArgumentList(argv): + return not (len(argv[1:]) or FLAGS.recurse) diff --git a/node-v0.8.14/tools/closure_linter/closure_linter/common/tokenizer.py b/node-v0.8.14/tools/closure_linter/closure_linter/common/tokenizer.py new file mode 100755 index 0000000..0234720 --- /dev/null +++ b/node-v0.8.14/tools/closure_linter/closure_linter/common/tokenizer.py @@ -0,0 +1,184 @@ +#!/usr/bin/env python +# +# Copyright 2007 The Closure Linter Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS-IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Regular expression based lexer.""" + +__author__ = ('robbyw@google.com (Robert Walker)', + 'ajp@google.com (Andy Perelson)') + +from closure_linter.common import tokens + +# Shorthand +Type = tokens.TokenType + + +class Tokenizer(object): + """General purpose tokenizer. + + Attributes: + mode: The latest mode of the tokenizer. This allows patterns to distinguish + if they are mid-comment, mid-parameter list, etc. + matchers: Dictionary of modes to sequences of matchers that define the + patterns to check at any given time. + default_types: Dictionary of modes to types, defining what type to give + non-matched text when in the given mode. Defaults to Type.NORMAL. + """ + + def __init__(self, starting_mode, matchers, default_types): + """Initialize the tokenizer. + + Args: + starting_mode: Mode to start in. + matchers: Dictionary of modes to sequences of matchers that defines the + patterns to check at any given time. + default_types: Dictionary of modes to types, defining what type to give + non-matched text when in the given mode. Defaults to Type.NORMAL. + """ + self.__starting_mode = starting_mode + self.matchers = matchers + self.default_types = default_types + + def TokenizeFile(self, file): + """Tokenizes the given file. + + Args: + file: An iterable that yields one line of the file at a time. + + Returns: + The first token in the file + """ + # The current mode. + self.mode = self.__starting_mode + # The first token in the stream. + self.__first_token = None + # The last token added to the token stream. + self.__last_token = None + # The current line number. + self.__line_number = 0 + + for line in file: + self.__line_number += 1 + self.__TokenizeLine(line) + + return self.__first_token + + def _CreateToken(self, string, token_type, line, line_number, values=None): + """Creates a new Token object (or subclass). + + Args: + string: The string of input the token represents. + token_type: The type of token. + line: The text of the line this token is in. + line_number: The line number of the token. + values: A dict of named values within the token. For instance, a + function declaration may have a value called 'name' which captures the + name of the function. + + Returns: + The newly created Token object. + """ + return tokens.Token(string, token_type, line, line_number, values) + + def __TokenizeLine(self, line): + """Tokenizes the given line. + + Args: + line: The contents of the line. + """ + string = line.rstrip('\n\r\f') + line_number = self.__line_number + self.__start_index = 0 + + if not string: + self.__AddToken(self._CreateToken('', Type.BLANK_LINE, line, line_number)) + return + + normal_token = '' + index = 0 + while index < len(string): + for matcher in self.matchers[self.mode]: + if matcher.line_start and index > 0: + continue + + match = matcher.regex.match(string, index) + + if match: + if normal_token: + self.__AddToken( + self.__CreateNormalToken(self.mode, normal_token, line, + line_number)) + normal_token = '' + + # Add the match. + self.__AddToken(self._CreateToken(match.group(), matcher.type, line, + line_number, match.groupdict())) + + # Change the mode to the correct one for after this match. + self.mode = matcher.result_mode or self.mode + + # Shorten the string to be matched. + index = match.end() + + break + + else: + # If the for loop finishes naturally (i.e. no matches) we just add the + # first character to the string of consecutive non match characters. + # These will constitute a NORMAL token. + if string: + normal_token += string[index:index + 1] + index += 1 + + if normal_token: + self.__AddToken( + self.__CreateNormalToken(self.mode, normal_token, line, line_number)) + + def __CreateNormalToken(self, mode, string, line, line_number): + """Creates a normal token. + + Args: + mode: The current mode. + string: The string to tokenize. + line: The line of text. + line_number: The line number within the file. + + Returns: + A Token object, of the default type for the current mode. + """ + type = Type.NORMAL + if mode in self.default_types: + type = self.default_types[mode] + return self._CreateToken(string, type, line, line_number) + + def __AddToken(self, token): + """Add the given token to the token stream. + + Args: + token: The token to add. + """ + # Store the first token, or point the previous token to this one. + if not self.__first_token: + self.__first_token = token + else: + self.__last_token.next = token + + # Establish the doubly linked list + token.previous = self.__last_token + self.__last_token = token + + # Compute the character indices + token.start_index = self.__start_index + self.__start_index += token.length diff --git a/node-v0.8.14/tools/closure_linter/closure_linter/common/tokens.py b/node-v0.8.14/tools/closure_linter/closure_linter/common/tokens.py new file mode 100755 index 0000000..5eaffa8 --- /dev/null +++ b/node-v0.8.14/tools/closure_linter/closure_linter/common/tokens.py @@ -0,0 +1,125 @@ +#!/usr/bin/env python +# +# Copyright 2008 The Closure Linter Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS-IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Classes to represent tokens and positions within them.""" + +__author__ = ('robbyw@google.com (Robert Walker)', + 'ajp@google.com (Andy Perelson)') + + +class TokenType(object): + """Token types common to all languages.""" + NORMAL = 'normal' + WHITESPACE = 'whitespace' + BLANK_LINE = 'blank line' + + +class Token(object): + """Token class for intelligent text splitting. + + The token class represents a string of characters and an identifying type. + + Attributes: + type: The type of token. + string: The characters the token comprises. + length: The length of the token. + line: The text of the line the token is found in. + line_number: The number of the line the token is found in. + values: Dictionary of values returned from the tokens regex match. + previous: The token before this one. + next: The token after this one. + start_index: The character index in the line where this token starts. + attached_object: Object containing more information about this token. + metadata: Object containing metadata about this token. Must be added by + a separate metadata pass. + """ + + def __init__(self, string, token_type, line, line_number, values=None): + """Creates a new Token object. + + Args: + string: The string of input the token contains. + token_type: The type of token. + line: The text of the line this token is in. + line_number: The line number of the token. + values: A dict of named values within the token. For instance, a + function declaration may have a value called 'name' which captures the + name of the function. + """ + self.type = token_type + self.string = string + self.length = len(string) + self.line = line + self.line_number = line_number + self.values = values + + # These parts can only be computed when the file is fully tokenized + self.previous = None + self.next = None + self.start_index = None + + # This part is set in statetracker.py + # TODO(robbyw): Wrap this in to metadata + self.attached_object = None + + # This part is set in *metadatapass.py + self.metadata = None + + def IsFirstInLine(self): + """Tests if this token is the first token in its line. + + Returns: + Whether the token is the first token in its line. + """ + return not self.previous or self.previous.line_number != self.line_number + + def IsLastInLine(self): + """Tests if this token is the last token in its line. + + Returns: + Whether the token is the last token in its line. + """ + return not self.next or self.next.line_number != self.line_number + + def IsType(self, token_type): + """Tests if this token is of the given type. + + Args: + token_type: The type to test for. + + Returns: + True if the type of this token matches the type passed in. + """ + return self.type == token_type + + def IsAnyType(self, *token_types): + """Tests if this token is any of the given types. + + Args: + token_types: The types to check. Also accepts a single array. + + Returns: + True if the type of this token is any of the types passed in. + """ + if not isinstance(token_types[0], basestring): + return self.type in token_types[0] + else: + return self.type in token_types + + def __repr__(self): + return '' % (self.type, self.string, + self.values, self.line_number, + self.metadata) diff --git a/node-v0.8.14/tools/closure_linter/closure_linter/ecmalintrules.py b/node-v0.8.14/tools/closure_linter/closure_linter/ecmalintrules.py new file mode 100755 index 0000000..a971b44 --- /dev/null +++ b/node-v0.8.14/tools/closure_linter/closure_linter/ecmalintrules.py @@ -0,0 +1,752 @@ +#!/usr/bin/env python +# +# Copyright 2008 The Closure Linter Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS-IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Core methods for checking EcmaScript files for common style guide violations. +""" + +__author__ = ('robbyw@google.com (Robert Walker)', + 'ajp@google.com (Andy Perelson)', + 'jacobr@google.com (Jacob Richman)') + +import re + +from closure_linter import checkerbase +from closure_linter import ecmametadatapass +from closure_linter import errors +from closure_linter import indentation +from closure_linter import javascripttokens +from closure_linter import javascripttokenizer +from closure_linter import statetracker +from closure_linter import tokenutil +from closure_linter.common import error +from closure_linter.common import htmlutil +from closure_linter.common import lintrunner +from closure_linter.common import position +from closure_linter.common import tokens +import gflags as flags + +FLAGS = flags.FLAGS +flags.DEFINE_boolean('strict', False, + 'Whether to validate against the stricter Closure style.') +flags.DEFINE_list('custom_jsdoc_tags', '', 'Extra jsdoc tags to allow') + +# TODO(robbyw): Check for extra parens on return statements +# TODO(robbyw): Check for 0px in strings +# TODO(robbyw): Ensure inline jsDoc is in {} +# TODO(robbyw): Check for valid JS types in parameter docs + +# Shorthand +Context = ecmametadatapass.EcmaContext +Error = error.Error +Modes = javascripttokenizer.JavaScriptModes +Position = position.Position +Type = javascripttokens.JavaScriptTokenType + +class EcmaScriptLintRules(checkerbase.LintRulesBase): + """EmcaScript lint style checking rules. + + Can be used to find common style errors in JavaScript, ActionScript and other + Ecma like scripting languages. Style checkers for Ecma scripting languages + should inherit from this style checker. + Please do not add any state to EcmaScriptLintRules or to any subclasses. + + All state should be added to the StateTracker subclass used for a particular + language. + """ + + # Static constants. + MAX_LINE_LENGTH = 80 + + MISSING_PARAMETER_SPACE = re.compile(r',\S') + + EXTRA_SPACE = re.compile('(\(\s|\s\))') + + ENDS_WITH_SPACE = re.compile('\s$') + + ILLEGAL_TAB = re.compile(r'\t') + + # Regex used to split up complex types to check for invalid use of ? and |. + TYPE_SPLIT = re.compile(r'[,<>()]') + + # Regex for form of author lines after the @author tag. + AUTHOR_SPEC = re.compile(r'(\s*)[^\s]+@[^(\s]+(\s*)\(.+\)') + + # Acceptable tokens to remove for line too long testing. + LONG_LINE_IGNORE = frozenset(['*', '//', '@see'] + + ['@%s' % tag for tag in statetracker.DocFlag.HAS_TYPE]) + + def __init__(self): + """Initialize this lint rule object.""" + checkerbase.LintRulesBase.__init__(self) + + def Initialize(self, checker, limited_doc_checks, is_html): + """Initialize this lint rule object before parsing a new file.""" + checkerbase.LintRulesBase.Initialize(self, checker, limited_doc_checks, + is_html) + self._indentation = indentation.IndentationRules() + + def HandleMissingParameterDoc(self, token, param_name): + """Handle errors associated with a parameter missing a @param tag.""" + raise TypeError('Abstract method HandleMissingParameterDoc not implemented') + + def _CheckLineLength(self, last_token, state): + """Checks whether the line is too long. + + Args: + last_token: The last token in the line. + """ + # Start from the last token so that we have the flag object attached to + # and DOC_FLAG tokens. + line_number = last_token.line_number + token = last_token + + # Build a representation of the string where spaces indicate potential + # line-break locations. + line = [] + while token and token.line_number == line_number: + if state.IsTypeToken(token): + line.insert(0, 'x' * len(token.string)) + elif token.type in (Type.IDENTIFIER, Type.NORMAL): + # Dots are acceptable places to wrap. + line.insert(0, token.string.replace('.', ' ')) + else: + line.insert(0, token.string) + token = token.previous + + line = ''.join(line) + line = line.rstrip('\n\r\f') + try: + length = len(unicode(line, 'utf-8')) + except: + # Unknown encoding. The line length may be wrong, as was originally the + # case for utf-8 (see bug 1735846). For now just accept the default + # length, but as we find problems we can either add test for other + # possible encodings or return without an error to protect against + # false positives at the cost of more false negatives. + length = len(line) + + if length > self.MAX_LINE_LENGTH: + + # If the line matches one of the exceptions, then it's ok. + for long_line_regexp in self.GetLongLineExceptions(): + if long_line_regexp.match(last_token.line): + return + + # If the line consists of only one "word", or multiple words but all + # except one are ignoreable, then it's ok. + parts = set(line.split()) + + # We allow two "words" (type and name) when the line contains @param + max = 1 + if '@param' in parts: + max = 2 + + # Custom tags like @requires may have url like descriptions, so ignore + # the tag, similar to how we handle @see. + custom_tags = set(['@%s' % f for f in FLAGS.custom_jsdoc_tags]) + if (len(parts.difference(self.LONG_LINE_IGNORE | custom_tags)) > max): + self._HandleError(errors.LINE_TOO_LONG, + 'Line too long (%d characters).' % len(line), last_token) + + def _CheckJsDocType(self, token): + """Checks the given type for style errors. + + Args: + token: The DOC_FLAG token for the flag whose type to check. + """ + flag = token.attached_object + type = flag.type + if type and type is not None and not type.isspace(): + pieces = self.TYPE_SPLIT.split(type) + if len(pieces) == 1 and type.count('|') == 1 and ( + type.endswith('|null') or type.startswith('null|')): + self._HandleError(errors.JSDOC_PREFER_QUESTION_TO_PIPE_NULL, + 'Prefer "?Type" to "Type|null": "%s"' % type, token) + + for p in pieces: + if p.count('|') and p.count('?'): + # TODO(robbyw): We should do actual parsing of JsDoc types. As is, + # this won't report an error for {number|Array.?}, etc. + self._HandleError(errors.JSDOC_ILLEGAL_QUESTION_WITH_PIPE, + 'JsDoc types cannot contain both "?" and "|": "%s"' % p, token) + + if FLAGS.strict and (flag.type_start_token.type != Type.DOC_START_BRACE or + flag.type_end_token.type != Type.DOC_END_BRACE): + self._HandleError(errors.MISSING_BRACES_AROUND_TYPE, + 'Type must always be surrounded by curly braces.', token) + + def _CheckForMissingSpaceBeforeToken(self, token): + """Checks for a missing space at the beginning of a token. + + Reports a MISSING_SPACE error if the token does not begin with a space or + the previous token doesn't end with a space and the previous token is on the + same line as the token. + + Args: + token: The token being checked + """ + # TODO(user): Check if too many spaces? + if (len(token.string) == len(token.string.lstrip()) and + token.previous and token.line_number == token.previous.line_number and + len(token.previous.string) - len(token.previous.string.rstrip()) == 0): + self._HandleError( + errors.MISSING_SPACE, + 'Missing space before "%s"' % token.string, + token, + Position.AtBeginning()) + + def _ExpectSpaceBeforeOperator(self, token): + """Returns whether a space should appear before the given operator token. + + Args: + token: The operator token. + + Returns: + Whether there should be a space before the token. + """ + if token.string == ',' or token.metadata.IsUnaryPostOperator(): + return False + + # Colons should appear in labels, object literals, the case of a switch + # statement, and ternary operator. Only want a space in the case of the + # ternary operator. + if (token.string == ':' and + token.metadata.context.type in (Context.LITERAL_ELEMENT, + Context.CASE_BLOCK, + Context.STATEMENT)): + return False + + if token.metadata.IsUnaryOperator() and token.IsFirstInLine(): + return False + + return True + + def CheckToken(self, token, state): + """Checks a token, given the current parser_state, for warnings and errors. + + Args: + token: The current token under consideration + state: parser_state object that indicates the current state in the page + """ + # Store some convenience variables + first_in_line = token.IsFirstInLine() + last_in_line = token.IsLastInLine() + last_non_space_token = state.GetLastNonSpaceToken() + + type = token.type + + # Process the line change. + if not self._is_html and FLAGS.strict: + # TODO(robbyw): Support checking indentation in HTML files. + indentation_errors = self._indentation.CheckToken(token, state) + for indentation_error in indentation_errors: + self._HandleError(*indentation_error) + + if last_in_line: + self._CheckLineLength(token, state) + + if type == Type.PARAMETERS: + # Find missing spaces in parameter lists. + if self.MISSING_PARAMETER_SPACE.search(token.string): + self._HandleError(errors.MISSING_SPACE, 'Missing space after ","', + token) + + # Find extra spaces at the beginning of parameter lists. Make sure + # we aren't at the beginning of a continuing multi-line list. + if not first_in_line: + space_count = len(token.string) - len(token.string.lstrip()) + if space_count: + self._HandleError(errors.EXTRA_SPACE, 'Extra space after "("', + token, Position(0, space_count)) + + elif (type == Type.START_BLOCK and + token.metadata.context.type == Context.BLOCK): + self._CheckForMissingSpaceBeforeToken(token) + + elif type == Type.END_BLOCK: + # This check is for object literal end block tokens, but there is no need + # to test that condition since a comma at the end of any other kind of + # block is undoubtedly a parse error. + last_code = token.metadata.last_code + if last_code.IsOperator(','): + self._HandleError(errors.COMMA_AT_END_OF_LITERAL, + 'Illegal comma at end of object literal', last_code, + Position.All(last_code.string)) + + if state.InFunction() and state.IsFunctionClose(): + is_immediately_called = (token.next and + token.next.type == Type.START_PAREN) + if state.InTopLevelFunction(): + # When the function was top-level and not immediately called, check + # that it's terminated by a semi-colon. + if state.InAssignedFunction(): + if not is_immediately_called and (last_in_line or + not token.next.type == Type.SEMICOLON): + self._HandleError(errors.MISSING_SEMICOLON_AFTER_FUNCTION, + 'Missing semicolon after function assigned to a variable', + token, Position.AtEnd(token.string)) + else: + if not last_in_line and token.next.type == Type.SEMICOLON: + self._HandleError(errors.ILLEGAL_SEMICOLON_AFTER_FUNCTION, + 'Illegal semicolon after function declaration', + token.next, Position.All(token.next.string)) + + if (state.InInterfaceMethod() and last_code.type != Type.START_BLOCK): + self._HandleError(errors.INTERFACE_METHOD_CANNOT_HAVE_CODE, + 'Interface methods cannot contain code', last_code) + + elif (state.IsBlockClose() and + token.next and token.next.type == Type.SEMICOLON): + self._HandleError(errors.REDUNDANT_SEMICOLON, + 'No semicolon is required to end a code block', + token.next, Position.All(token.next.string)) + + elif type == Type.SEMICOLON: + if token.previous and token.previous.type == Type.WHITESPACE: + self._HandleError(errors.EXTRA_SPACE, 'Extra space before ";"', + token.previous, Position.All(token.previous.string)) + + if token.next and token.next.line_number == token.line_number: + if token.metadata.context.type != Context.FOR_GROUP_BLOCK: + # TODO(robbyw): Error about no multi-statement lines. + pass + + elif token.next.type not in ( + Type.WHITESPACE, Type.SEMICOLON, Type.END_PAREN): + self._HandleError(errors.MISSING_SPACE, + 'Missing space after ";" in for statement', + token.next, + Position.AtBeginning()) + + last_code = token.metadata.last_code + if last_code and last_code.type == Type.SEMICOLON: + # Allow a single double semi colon in for loops for cases like: + # for (;;) { }. + # NOTE(user): This is not a perfect check, and will not throw an error + # for cases like: for (var i = 0;; i < n; i++) {}, but then your code + # probably won't work either. + for_token = tokenutil.CustomSearch(last_code, + lambda token: token.type == Type.KEYWORD and token.string == 'for', + end_func=lambda token: token.type == Type.SEMICOLON, + distance=None, + reverse=True) + + if not for_token: + self._HandleError(errors.REDUNDANT_SEMICOLON, 'Redundant semicolon', + token, Position.All(token.string)) + + elif type == Type.START_PAREN: + if token.previous and token.previous.type == Type.KEYWORD: + self._HandleError(errors.MISSING_SPACE, 'Missing space before "("', + token, Position.AtBeginning()) + elif token.previous and token.previous.type == Type.WHITESPACE: + before_space = token.previous.previous + if (before_space and before_space.line_number == token.line_number and + before_space.type == Type.IDENTIFIER): + self._HandleError(errors.EXTRA_SPACE, 'Extra space before "("', + token.previous, Position.All(token.previous.string)) + + elif type == Type.START_BRACKET: + if (not first_in_line and token.previous.type == Type.WHITESPACE and + last_non_space_token and + last_non_space_token.type in Type.EXPRESSION_ENDER_TYPES): + self._HandleError(errors.EXTRA_SPACE, 'Extra space before "["', + token.previous, Position.All(token.previous.string)) + # If the [ token is the first token in a line we shouldn't complain + # about a missing space before [. This is because some Ecma script + # languages allow syntax like: + # [Annotation] + # class MyClass {...} + # So we don't want to blindly warn about missing spaces before [. + # In the the future, when rules for computing exactly how many spaces + # lines should be indented are added, then we can return errors for + # [ tokens that are improperly indented. + # For example: + # var someVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryLongVariableName = + # [a,b,c]; + # should trigger a proper indentation warning message as [ is not indented + # by four spaces. + elif (not first_in_line and token.previous and + not token.previous.type in ( + [Type.WHITESPACE, Type.START_PAREN, Type.START_BRACKET] + + Type.EXPRESSION_ENDER_TYPES)): + self._HandleError(errors.MISSING_SPACE, 'Missing space before "["', + token, Position.AtBeginning()) + + elif type in (Type.END_PAREN, Type.END_BRACKET): + # Ensure there is no space before closing parentheses, except when + # it's in a for statement with an omitted section, or when it's at the + # beginning of a line. + if (token.previous and token.previous.type == Type.WHITESPACE and + not token.previous.IsFirstInLine() and + not (last_non_space_token and last_non_space_token.line_number == + token.line_number and + last_non_space_token.type == Type.SEMICOLON)): + self._HandleError(errors.EXTRA_SPACE, 'Extra space before "%s"' % + token.string, token.previous, Position.All(token.previous.string)) + + if token.type == Type.END_BRACKET: + last_code = token.metadata.last_code + if last_code.IsOperator(','): + self._HandleError(errors.COMMA_AT_END_OF_LITERAL, + 'Illegal comma at end of array literal', last_code, + Position.All(last_code.string)) + + elif type == Type.WHITESPACE: + if self.ILLEGAL_TAB.search(token.string): + if token.IsFirstInLine(): + self._HandleError(errors.ILLEGAL_TAB, + 'Illegal tab in whitespace before "%s"' % token.next.string, + token, Position.All(token.string)) + else: + self._HandleError(errors.ILLEGAL_TAB, + 'Illegal tab in whitespace after "%s"' % token.previous.string, + token, Position.All(token.string)) + + # Check whitespace length if it's not the first token of the line and + # if it's not immediately before a comment. + if last_in_line: + # Check for extra whitespace at the end of a line. + self._HandleError(errors.EXTRA_SPACE, 'Extra space at end of line', + token, Position.All(token.string)) + elif not first_in_line and not token.next.IsComment(): + if token.length > 1: + self._HandleError(errors.EXTRA_SPACE, 'Extra space after "%s"' % + token.previous.string, token, + Position(1, len(token.string) - 1)) + + elif type == Type.OPERATOR: + last_code = token.metadata.last_code + + if not self._ExpectSpaceBeforeOperator(token): + if (token.previous and token.previous.type == Type.WHITESPACE and + last_code and last_code.type in (Type.NORMAL, Type.IDENTIFIER)): + self._HandleError(errors.EXTRA_SPACE, + 'Extra space before "%s"' % token.string, token.previous, + Position.All(token.previous.string)) + + elif (token.previous and + not token.previous.IsComment() and + token.previous.type in Type.EXPRESSION_ENDER_TYPES): + self._HandleError(errors.MISSING_SPACE, + 'Missing space before "%s"' % token.string, token, + Position.AtBeginning()) + + # Check that binary operators are not used to start lines. + if ((not last_code or last_code.line_number != token.line_number) and + not token.metadata.IsUnaryOperator()): + self._HandleError(errors.LINE_STARTS_WITH_OPERATOR, + 'Binary operator should go on previous line "%s"' % token.string, + token) + + elif type == Type.DOC_FLAG: + flag = token.attached_object + + if flag.flag_type == 'bug': + # TODO(robbyw): Check for exactly 1 space on the left. + string = token.next.string.lstrip() + string = string.split(' ', 1)[0] + + if not string.isdigit(): + self._HandleError(errors.NO_BUG_NUMBER_AFTER_BUG_TAG, + '@bug should be followed by a bug number', token) + + elif flag.flag_type == 'suppress': + if flag.type is None: + # A syntactically invalid suppress tag will get tokenized as a normal + # flag, indicating an error. + self._HandleError(errors.INCORRECT_SUPPRESS_SYNTAX, + 'Invalid suppress syntax: should be @suppress {errortype}. ' + 'Spaces matter.', token) + elif flag.type not in state.GetDocFlag().SUPPRESS_TYPES: + self._HandleError(errors.INVALID_SUPPRESS_TYPE, + 'Invalid suppression type: %s' % flag.type, + token) + + elif FLAGS.strict and flag.flag_type == 'author': + # TODO(user): In non strict mode check the author tag for as much as + # it exists, though the full form checked below isn't required. + string = token.next.string + result = self.AUTHOR_SPEC.match(string) + if not result: + self._HandleError(errors.INVALID_AUTHOR_TAG_DESCRIPTION, + 'Author tag line should be of the form: ' + '@author foo@somewhere.com (Your Name)', + token.next) + else: + # Check spacing between email address and name. Do this before + # checking earlier spacing so positions are easier to calculate for + # autofixing. + num_spaces = len(result.group(2)) + if num_spaces < 1: + self._HandleError(errors.MISSING_SPACE, + 'Missing space after email address', + token.next, Position(result.start(2), 0)) + elif num_spaces > 1: + self._HandleError(errors.EXTRA_SPACE, + 'Extra space after email address', + token.next, + Position(result.start(2) + 1, num_spaces - 1)) + + # Check for extra spaces before email address. Can't be too few, if + # not at least one we wouldn't match @author tag. + num_spaces = len(result.group(1)) + if num_spaces > 1: + self._HandleError(errors.EXTRA_SPACE, + 'Extra space before email address', + token.next, Position(1, num_spaces - 1)) + + elif (flag.flag_type in state.GetDocFlag().HAS_DESCRIPTION and + not self._limited_doc_checks): + if flag.flag_type == 'param': + if flag.name is None: + self._HandleError(errors.MISSING_JSDOC_PARAM_NAME, + 'Missing name in @param tag', token) + + if not flag.description or flag.description is None: + flag_name = token.type + if 'name' in token.values: + flag_name = '@' + token.values['name'] + self._HandleError(errors.MISSING_JSDOC_TAG_DESCRIPTION, + 'Missing description in %s tag' % flag_name, token) + else: + self._CheckForMissingSpaceBeforeToken(flag.description_start_token) + + # We want punctuation to be inside of any tags ending a description, + # so strip tags before checking description. See bug 1127192. Note + # that depending on how lines break, the real description end token + # may consist only of stripped html and the effective end token can + # be different. + end_token = flag.description_end_token + end_string = htmlutil.StripTags(end_token.string).strip() + while (end_string == '' and not + end_token.type in Type.FLAG_ENDING_TYPES): + end_token = end_token.previous + if end_token.type in Type.FLAG_DESCRIPTION_TYPES: + end_string = htmlutil.StripTags(end_token.string).rstrip() + + if not (end_string.endswith('.') or end_string.endswith('?') or + end_string.endswith('!')): + # Find the position for the missing punctuation, inside of any html + # tags. + desc_str = end_token.string.rstrip() + while desc_str.endswith('>'): + start_tag_index = desc_str.rfind('<') + if start_tag_index < 0: + break + desc_str = desc_str[:start_tag_index].rstrip() + end_position = Position(len(desc_str), 0) + + self._HandleError( + errors.JSDOC_TAG_DESCRIPTION_ENDS_WITH_INVALID_CHARACTER, + ('%s descriptions must end with valid punctuation such as a ' + 'period.' % token.string), + end_token, end_position) + + if flag.flag_type in state.GetDocFlag().HAS_TYPE: + if flag.type_start_token is not None: + self._CheckForMissingSpaceBeforeToken( + token.attached_object.type_start_token) + + if flag.type and flag.type != '' and not flag.type.isspace(): + self._CheckJsDocType(token) + + if type in (Type.DOC_FLAG, Type.DOC_INLINE_FLAG): + if (token.values['name'] not in state.GetDocFlag().LEGAL_DOC and + token.values['name'] not in FLAGS.custom_jsdoc_tags): + self._HandleError(errors.INVALID_JSDOC_TAG, + 'Invalid JsDoc tag: %s' % token.values['name'], token) + + if (FLAGS.strict and token.values['name'] == 'inheritDoc' and + type == Type.DOC_INLINE_FLAG): + self._HandleError(errors.UNNECESSARY_BRACES_AROUND_INHERIT_DOC, + 'Unnecessary braces around @inheritDoc', + token) + + elif type == Type.SIMPLE_LVALUE: + identifier = token.values['identifier'] + + if ((not state.InFunction() or state.InConstructor()) and + not state.InParentheses() and not state.InObjectLiteralDescendant()): + jsdoc = state.GetDocComment() + if not state.HasDocComment(identifier): + # Only test for documentation on identifiers with .s in them to + # avoid checking things like simple variables. We don't require + # documenting assignments to .prototype itself (bug 1880803). + if (not state.InConstructor() and + identifier.find('.') != -1 and not + identifier.endswith('.prototype') and not + self._limited_doc_checks): + comment = state.GetLastComment() + if not (comment and comment.lower().count('jsdoc inherited')): + self._HandleError(errors.MISSING_MEMBER_DOCUMENTATION, + "No docs found for member '%s'" % identifier, + token); + elif jsdoc and (not state.InConstructor() or + identifier.startswith('this.')): + # We are at the top level and the function/member is documented. + if identifier.endswith('_') and not identifier.endswith('__'): + if jsdoc.HasFlag('override'): + self._HandleError(errors.INVALID_OVERRIDE_PRIVATE, + '%s should not override a private member.' % identifier, + jsdoc.GetFlag('override').flag_token) + # Can have a private class which inherits documentation from a + # public superclass. + if jsdoc.HasFlag('inheritDoc') and not jsdoc.HasFlag('constructor'): + self._HandleError(errors.INVALID_INHERIT_DOC_PRIVATE, + '%s should not inherit from a private member.' % identifier, + jsdoc.GetFlag('inheritDoc').flag_token) + if (not jsdoc.HasFlag('private') and + not ('underscore' in jsdoc.suppressions)): + self._HandleError(errors.MISSING_PRIVATE, + 'Member "%s" must have @private JsDoc.' % + identifier, token) + if jsdoc.HasFlag('private') and 'underscore' in jsdoc.suppressions: + self._HandleError(errors.UNNECESSARY_SUPPRESS, + '@suppress {underscore} is not necessary with @private', + jsdoc.suppressions['underscore']) + elif jsdoc.HasFlag('private'): + self._HandleError(errors.EXTRA_PRIVATE, + 'Member "%s" must not have @private JsDoc' % + identifier, token) + + if ((jsdoc.HasFlag('desc') or jsdoc.HasFlag('hidden')) + and not identifier.startswith('MSG_') + and identifier.find('.MSG_') == -1): + # TODO(user): Update error message to show the actual invalid + # tag, either @desc or @hidden. + self._HandleError(errors.INVALID_USE_OF_DESC_TAG, + 'Member "%s" should not have @desc JsDoc' % identifier, + token) + + # Check for illegaly assigning live objects as prototype property values. + index = identifier.find('.prototype.') + # Ignore anything with additional .s after the prototype. + if index != -1 and identifier.find('.', index + 11) == -1: + equal_operator = tokenutil.SearchExcept(token, Type.NON_CODE_TYPES) + next_code = tokenutil.SearchExcept(equal_operator, Type.NON_CODE_TYPES) + if next_code and ( + next_code.type in (Type.START_BRACKET, Type.START_BLOCK) or + next_code.IsOperator('new')): + self._HandleError(errors.ILLEGAL_PROTOTYPE_MEMBER_VALUE, + 'Member %s cannot have a non-primitive value' % identifier, + token) + + elif type == Type.END_PARAMETERS: + # Find extra space at the end of parameter lists. We check the token + # prior to the current one when it is a closing paren. + if (token.previous and token.previous.type == Type.PARAMETERS + and self.ENDS_WITH_SPACE.search(token.previous.string)): + self._HandleError(errors.EXTRA_SPACE, 'Extra space before ")"', + token.previous) + + jsdoc = state.GetDocComment() + if state.GetFunction().is_interface: + if token.previous and token.previous.type == Type.PARAMETERS: + self._HandleError(errors.INTERFACE_CONSTRUCTOR_CANNOT_HAVE_PARAMS, + 'Interface constructor cannot have parameters', + token.previous) + elif (state.InTopLevel() and jsdoc and not jsdoc.HasFlag('see') + and not jsdoc.InheritsDocumentation() + and not state.InObjectLiteralDescendant() and not + jsdoc.IsInvalidated()): + distance, edit = jsdoc.CompareParameters(state.GetParams()) + if distance: + params_iter = iter(state.GetParams()) + docs_iter = iter(jsdoc.ordered_params) + + for op in edit: + if op == 'I': + # Insertion. + # Parsing doc comments is the same for all languages + # but some languages care about parameters that don't have + # doc comments and some languages don't care. + # Languages that don't allow variables to by typed such as + # JavaScript care but languages such as ActionScript or Java + # that allow variables to be typed don't care. + self.HandleMissingParameterDoc(token, params_iter.next()) + + elif op == 'D': + # Deletion + self._HandleError(errors.EXTRA_PARAMETER_DOCUMENTATION, + 'Found docs for non-existing parameter: "%s"' % + docs_iter.next(), token) + elif op == 'S': + # Substitution + self._HandleError(errors.WRONG_PARAMETER_DOCUMENTATION, + 'Parameter mismatch: got "%s", expected "%s"' % + (params_iter.next(), docs_iter.next()), token) + + else: + # Equality - just advance the iterators + params_iter.next() + docs_iter.next() + + elif type == Type.STRING_TEXT: + # If this is the first token after the start of the string, but it's at + # the end of a line, we know we have a multi-line string. + if token.previous.type in (Type.SINGLE_QUOTE_STRING_START, + Type.DOUBLE_QUOTE_STRING_START) and last_in_line: + self._HandleError(errors.MULTI_LINE_STRING, + 'Multi-line strings are not allowed', token) + + + # This check is orthogonal to the ones above, and repeats some types, so + # it is a plain if and not an elif. + if token.type in Type.COMMENT_TYPES: + if self.ILLEGAL_TAB.search(token.string): + self._HandleError(errors.ILLEGAL_TAB, + 'Illegal tab in comment "%s"' % token.string, token) + + trimmed = token.string.rstrip() + if last_in_line and token.string != trimmed: + # Check for extra whitespace at the end of a line. + self._HandleError(errors.EXTRA_SPACE, 'Extra space at end of line', + token, Position(len(trimmed), len(token.string) - len(trimmed))) + + # This check is also orthogonal since it is based on metadata. + if token.metadata.is_implied_semicolon: + self._HandleError(errors.MISSING_SEMICOLON, + 'Missing semicolon at end of line', token) + + def Finalize(self, state, tokenizer_mode): + last_non_space_token = state.GetLastNonSpaceToken() + # Check last line for ending with newline. + if state.GetLastLine() and not (state.GetLastLine().isspace() or + state.GetLastLine().rstrip('\n\r\f') != state.GetLastLine()): + self._HandleError( + errors.FILE_MISSING_NEWLINE, + 'File does not end with new line. (%s)' % state.GetLastLine(), + last_non_space_token) + + # Check that the mode is not mid comment, argument list, etc. + if not tokenizer_mode == Modes.TEXT_MODE: + self._HandleError( + errors.FILE_IN_BLOCK, + 'File ended in mode "%s".' % tokenizer_mode, + last_non_space_token) + + try: + self._indentation.Finalize() + except Exception, e: + self._HandleError( + errors.FILE_DOES_NOT_PARSE, + str(e), + last_non_space_token) + + def GetLongLineExceptions(self): + """Gets a list of regexps for lines which can be longer than the limit.""" + return [] diff --git a/node-v0.8.14/tools/closure_linter/closure_linter/ecmametadatapass.py b/node-v0.8.14/tools/closure_linter/closure_linter/ecmametadatapass.py new file mode 100755 index 0000000..2c797b3 --- /dev/null +++ b/node-v0.8.14/tools/closure_linter/closure_linter/ecmametadatapass.py @@ -0,0 +1,521 @@ +#!/usr/bin/env python +# +# Copyright 2010 The Closure Linter Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS-IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Metadata pass for annotating tokens in EcmaScript files.""" + +__author__ = ('robbyw@google.com (Robert Walker)') + +from closure_linter import javascripttokens +from closure_linter import tokenutil + + +TokenType = javascripttokens.JavaScriptTokenType + + +class ParseError(Exception): + """Exception indicating a parse error at the given token. + + Attributes: + token: The token where the parse error occurred. + """ + + def __init__(self, token, message=None): + """Initialize a parse error at the given token with an optional message. + + Args: + token: The token where the parse error occurred. + message: A message describing the parse error. + """ + Exception.__init__(self, message) + self.token = token + + +class EcmaContext(object): + """Context object for EcmaScript languages. + + Attributes: + type: The context type. + start_token: The token where this context starts. + end_token: The token where this context ends. + parent: The parent context. + """ + + # The root context. + ROOT = 'root' + + # A block of code. + BLOCK = 'block' + + # A pseudo-block of code for a given case or default section. + CASE_BLOCK = 'case_block' + + # Block of statements in a for loop's parentheses. + FOR_GROUP_BLOCK = 'for_block' + + # An implied block of code for 1 line if, while, and for statements + IMPLIED_BLOCK = 'implied_block' + + # An index in to an array or object. + INDEX = 'index' + + # An array literal in []. + ARRAY_LITERAL = 'array_literal' + + # An object literal in {}. + OBJECT_LITERAL = 'object_literal' + + # An individual element in an array or object literal. + LITERAL_ELEMENT = 'literal_element' + + # The portion of a ternary statement between ? and : + TERNARY_TRUE = 'ternary_true' + + # The portion of a ternary statment after : + TERNARY_FALSE = 'ternary_false' + + # The entire switch statment. This will contain a GROUP with the variable + # and a BLOCK with the code. + + # Since that BLOCK is not a normal block, it can not contain statements except + # for case and default. + SWITCH = 'switch' + + # A normal comment. + COMMENT = 'comment' + + # A JsDoc comment. + DOC = 'doc' + + # An individual statement. + STATEMENT = 'statement' + + # Code within parentheses. + GROUP = 'group' + + # Parameter names in a function declaration. + PARAMETERS = 'parameters' + + # A set of variable declarations appearing after the 'var' keyword. + VAR = 'var' + + # Context types that are blocks. + BLOCK_TYPES = frozenset([ + ROOT, BLOCK, CASE_BLOCK, FOR_GROUP_BLOCK, IMPLIED_BLOCK]) + + def __init__(self, type, start_token, parent): + """Initializes the context object. + + Args: + type: The context type. + start_token: The token where this context starts. + parent: The parent context. + """ + self.type = type + self.start_token = start_token + self.end_token = None + self.parent = parent + + def __repr__(self): + """Returns a string representation of the context object.""" + stack = [] + context = self + while context: + stack.append(context.type) + context = context.parent + return 'Context(%s)' % ' > '.join(stack) + + +class EcmaMetaData(object): + """Token metadata for EcmaScript languages. + + Attributes: + last_code: The last code token to appear before this one. + context: The context this token appears in. + operator_type: The operator type, will be one of the *_OPERATOR constants + defined below. + """ + + UNARY_OPERATOR = 'unary' + + UNARY_POST_OPERATOR = 'unary_post' + + BINARY_OPERATOR = 'binary' + + TERNARY_OPERATOR = 'ternary' + + def __init__(self): + """Initializes a token metadata object.""" + self.last_code = None + self.context = None + self.operator_type = None + self.is_implied_semicolon = False + self.is_implied_block = False + self.is_implied_block_close = False + + def __repr__(self): + """Returns a string representation of the context object.""" + parts = ['%r' % self.context] + if self.operator_type: + parts.append('optype: %r' % self.operator_type) + if self.is_implied_semicolon: + parts.append('implied;') + return 'MetaData(%s)' % ', '.join(parts) + + def IsUnaryOperator(self): + return self.operator_type in (EcmaMetaData.UNARY_OPERATOR, + EcmaMetaData.UNARY_POST_OPERATOR) + + def IsUnaryPostOperator(self): + return self.operator_type == EcmaMetaData.UNARY_POST_OPERATOR + + +class EcmaMetaDataPass(object): + """A pass that iterates over all tokens and builds metadata about them.""" + + def __init__(self): + """Initialize the meta data pass object.""" + self.Reset() + + def Reset(self): + """Resets the metadata pass to prepare for the next file.""" + self._token = None + self._context = None + self._AddContext(EcmaContext.ROOT) + self._last_code = None + + def _CreateContext(self, type): + """Overridable by subclasses to create the appropriate context type.""" + return EcmaContext(type, self._token, self._context) + + def _CreateMetaData(self): + """Overridable by subclasses to create the appropriate metadata type.""" + return EcmaMetaData() + + def _AddContext(self, type): + """Adds a context of the given type to the context stack. + + Args: + type: The type of context to create + """ + self._context = self._CreateContext(type) + + def _PopContext(self): + """Moves up one level in the context stack. + + Returns: + The former context. + + Raises: + ParseError: If the root context is popped. + """ + top_context = self._context + top_context.end_token = self._token + self._context = top_context.parent + if self._context: + return top_context + else: + raise ParseError(self._token) + + def _PopContextType(self, *stop_types): + """Pops the context stack until a context of the given type is popped. + + Args: + stop_types: The types of context to pop to - stops at the first match. + + Returns: + The context object of the given type that was popped. + """ + last = None + while not last or last.type not in stop_types: + last = self._PopContext() + return last + + def _EndStatement(self): + """Process the end of a statement.""" + self._PopContextType(EcmaContext.STATEMENT) + if self._context.type == EcmaContext.IMPLIED_BLOCK: + self._token.metadata.is_implied_block_close = True + self._PopContext() + + def _ProcessContext(self): + """Process the context at the current token. + + Returns: + The context that should be assigned to the current token, or None if + the current context after this method should be used. + + Raises: + ParseError: When the token appears in an invalid context. + """ + token = self._token + token_type = token.type + + if self._context.type in EcmaContext.BLOCK_TYPES: + # Whenever we're in a block, we add a statement context. We make an + # exception for switch statements since they can only contain case: and + # default: and therefore don't directly contain statements. + # The block we add here may be immediately removed in some cases, but + # that causes no harm. + parent = self._context.parent + if not parent or parent.type != EcmaContext.SWITCH: + self._AddContext(EcmaContext.STATEMENT) + + elif self._context.type == EcmaContext.ARRAY_LITERAL: + self._AddContext(EcmaContext.LITERAL_ELEMENT) + + if token_type == TokenType.START_PAREN: + if self._last_code and self._last_code.IsKeyword('for'): + # for loops contain multiple statements in the group unlike while, + # switch, if, etc. + self._AddContext(EcmaContext.FOR_GROUP_BLOCK) + else: + self._AddContext(EcmaContext.GROUP) + + elif token_type == TokenType.END_PAREN: + result = self._PopContextType(EcmaContext.GROUP, + EcmaContext.FOR_GROUP_BLOCK) + keyword_token = result.start_token.metadata.last_code + # keyword_token will not exist if the open paren is the first line of the + # file, for example if all code is wrapped in an immediately executed + # annonymous function. + if keyword_token and keyword_token.string in ('if', 'for', 'while'): + next_code = tokenutil.SearchExcept(token, TokenType.NON_CODE_TYPES) + if next_code.type != TokenType.START_BLOCK: + # Check for do-while. + is_do_while = False + pre_keyword_token = keyword_token.metadata.last_code + if (pre_keyword_token and + pre_keyword_token.type == TokenType.END_BLOCK): + start_block_token = pre_keyword_token.metadata.context.start_token + is_do_while = start_block_token.metadata.last_code.string == 'do' + + # If it's not do-while, it's an implied block. + if not is_do_while: + self._AddContext(EcmaContext.IMPLIED_BLOCK) + token.metadata.is_implied_block = True + + return result + + # else (not else if) with no open brace after it should be considered the + # start of an implied block, similar to the case with if, for, and while + # above. + elif (token_type == TokenType.KEYWORD and + token.string == 'else'): + next_code = tokenutil.SearchExcept(token, TokenType.NON_CODE_TYPES) + if (next_code.type != TokenType.START_BLOCK and + (next_code.type != TokenType.KEYWORD or next_code.string != 'if')): + self._AddContext(EcmaContext.IMPLIED_BLOCK) + token.metadata.is_implied_block = True + + elif token_type == TokenType.START_PARAMETERS: + self._AddContext(EcmaContext.PARAMETERS) + + elif token_type == TokenType.END_PARAMETERS: + return self._PopContextType(EcmaContext.PARAMETERS) + + elif token_type == TokenType.START_BRACKET: + if (self._last_code and + self._last_code.type in TokenType.EXPRESSION_ENDER_TYPES): + self._AddContext(EcmaContext.INDEX) + else: + self._AddContext(EcmaContext.ARRAY_LITERAL) + + elif token_type == TokenType.END_BRACKET: + return self._PopContextType(EcmaContext.INDEX, EcmaContext.ARRAY_LITERAL) + + elif token_type == TokenType.START_BLOCK: + if (self._last_code.type in (TokenType.END_PAREN, + TokenType.END_PARAMETERS) or + self._last_code.IsKeyword('else') or + self._last_code.IsKeyword('do') or + self._last_code.IsKeyword('try') or + self._last_code.IsKeyword('finally') or + (self._last_code.IsOperator(':') and + self._last_code.metadata.context.type == EcmaContext.CASE_BLOCK)): + # else, do, try, and finally all might have no () before {. + # Also, handle the bizzare syntax case 10: {...}. + self._AddContext(EcmaContext.BLOCK) + else: + self._AddContext(EcmaContext.OBJECT_LITERAL) + + elif token_type == TokenType.END_BLOCK: + context = self._PopContextType(EcmaContext.BLOCK, + EcmaContext.OBJECT_LITERAL) + if self._context.type == EcmaContext.SWITCH: + # The end of the block also means the end of the switch statement it + # applies to. + return self._PopContext() + return context + + elif token.IsKeyword('switch'): + self._AddContext(EcmaContext.SWITCH) + + elif (token_type == TokenType.KEYWORD and + token.string in ('case', 'default')): + # Pop up to but not including the switch block. + while self._context.parent.type != EcmaContext.SWITCH: + self._PopContext() + + elif token.IsOperator('?'): + self._AddContext(EcmaContext.TERNARY_TRUE) + + elif token.IsOperator(':'): + if self._context.type == EcmaContext.OBJECT_LITERAL: + self._AddContext(EcmaContext.LITERAL_ELEMENT) + + elif self._context.type == EcmaContext.TERNARY_TRUE: + self._PopContext() + self._AddContext(EcmaContext.TERNARY_FALSE) + + # Handle nested ternary statements like: + # foo = bar ? baz ? 1 : 2 : 3 + # When we encounter the second ":" the context is + # ternary_false > ternary_true > statement > root + elif (self._context.type == EcmaContext.TERNARY_FALSE and + self._context.parent.type == EcmaContext.TERNARY_TRUE): + self._PopContext() # Leave current ternary false context. + self._PopContext() # Leave current parent ternary true + self._AddContext(EcmaContext.TERNARY_FALSE) + + elif self._context.parent.type == EcmaContext.SWITCH: + self._AddContext(EcmaContext.CASE_BLOCK) + + elif token.IsKeyword('var'): + self._AddContext(EcmaContext.VAR) + + elif token.IsOperator(','): + while self._context.type not in (EcmaContext.VAR, + EcmaContext.ARRAY_LITERAL, + EcmaContext.OBJECT_LITERAL, + EcmaContext.STATEMENT, + EcmaContext.PARAMETERS, + EcmaContext.GROUP): + self._PopContext() + + elif token_type == TokenType.SEMICOLON: + self._EndStatement() + + def Process(self, first_token): + """Processes the token stream starting with the given token.""" + self._token = first_token + while self._token: + self._ProcessToken() + + if self._token.IsCode(): + self._last_code = self._token + + self._token = self._token.next + + try: + self._PopContextType(self, EcmaContext.ROOT) + except ParseError: + # Ignore the "popped to root" error. + pass + + def _ProcessToken(self): + """Process the given token.""" + token = self._token + token.metadata = self._CreateMetaData() + context = (self._ProcessContext() or self._context) + token.metadata.context = context + token.metadata.last_code = self._last_code + + # Determine the operator type of the token, if applicable. + if token.type == TokenType.OPERATOR: + token.metadata.operator_type = self._GetOperatorType(token) + + # Determine if there is an implied semicolon after the token. + if token.type != TokenType.SEMICOLON: + next_code = tokenutil.SearchExcept(token, TokenType.NON_CODE_TYPES) + # A statement like if (x) does not need a semicolon after it + is_implied_block = self._context == EcmaContext.IMPLIED_BLOCK + is_last_code_in_line = token.IsCode() and ( + not next_code or next_code.line_number != token.line_number) + is_continued_identifier = (token.type == TokenType.IDENTIFIER and + token.string.endswith('.')) + is_continued_operator = (token.type == TokenType.OPERATOR and + not token.metadata.IsUnaryPostOperator()) + is_continued_dot = token.string == '.' + next_code_is_operator = next_code and next_code.type == TokenType.OPERATOR + next_code_is_dot = next_code and next_code.string == '.' + is_end_of_block = (token.type == TokenType.END_BLOCK and + token.metadata.context.type != EcmaContext.OBJECT_LITERAL) + is_multiline_string = token.type == TokenType.STRING_TEXT + next_code_is_block = next_code and next_code.type == TokenType.START_BLOCK + if (is_last_code_in_line and + self._StatementCouldEndInContext() and + not is_multiline_string and + not is_end_of_block and + not is_continued_identifier and + not is_continued_operator and + not is_continued_dot and + not next_code_is_dot and + not next_code_is_operator and + not is_implied_block and + not next_code_is_block): + token.metadata.is_implied_semicolon = True + self._EndStatement() + + def _StatementCouldEndInContext(self): + """Returns whether the current statement (if any) may end in this context.""" + # In the basic statement or variable declaration context, statement can + # always end in this context. + if self._context.type in (EcmaContext.STATEMENT, EcmaContext.VAR): + return True + + # End of a ternary false branch inside a statement can also be the + # end of the statement, for example: + # var x = foo ? foo.bar() : null + # In this case the statement ends after the null, when the context stack + # looks like ternary_false > var > statement > root. + if (self._context.type == EcmaContext.TERNARY_FALSE and + self._context.parent.type in (EcmaContext.STATEMENT, EcmaContext.VAR)): + return True + + # In all other contexts like object and array literals, ternary true, etc. + # the statement can't yet end. + return False + + def _GetOperatorType(self, token): + """Returns the operator type of the given operator token. + + Args: + token: The token to get arity for. + + Returns: + The type of the operator. One of the *_OPERATOR constants defined in + EcmaMetaData. + """ + if token.string == '?': + return EcmaMetaData.TERNARY_OPERATOR + + if token.string in TokenType.UNARY_OPERATORS: + return EcmaMetaData.UNARY_OPERATOR + + last_code = token.metadata.last_code + if not last_code or last_code.type == TokenType.END_BLOCK: + return EcmaMetaData.UNARY_OPERATOR + + if (token.string in TokenType.UNARY_POST_OPERATORS and + last_code.type in TokenType.EXPRESSION_ENDER_TYPES): + return EcmaMetaData.UNARY_POST_OPERATOR + + if (token.string in TokenType.UNARY_OK_OPERATORS and + last_code.type not in TokenType.EXPRESSION_ENDER_TYPES and + last_code.string not in TokenType.UNARY_POST_OPERATORS): + return EcmaMetaData.UNARY_OPERATOR + + return EcmaMetaData.BINARY_OPERATOR diff --git a/node-v0.8.14/tools/closure_linter/closure_linter/error_fixer.py b/node-v0.8.14/tools/closure_linter/closure_linter/error_fixer.py new file mode 100755 index 0000000..904cf86 --- /dev/null +++ b/node-v0.8.14/tools/closure_linter/closure_linter/error_fixer.py @@ -0,0 +1,336 @@ +#!/usr/bin/env python +# +# Copyright 2007 The Closure Linter Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS-IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Main class responsible for automatically fixing simple style violations.""" + +__author__ = 'robbyw@google.com (Robert Walker)' + +import re + +import gflags as flags +from closure_linter import errors +from closure_linter import javascriptstatetracker +from closure_linter import javascripttokens +from closure_linter import tokenutil +from closure_linter.common import errorhandler + +# Shorthand +Token = javascripttokens.JavaScriptToken +Type = javascripttokens.JavaScriptTokenType + +END_OF_FLAG_TYPE = re.compile(r'(}?\s*)$') + +FLAGS = flags.FLAGS +flags.DEFINE_boolean('disable_indentation_fixing', False, + 'Whether to disable automatic fixing of indentation.') + +class ErrorFixer(errorhandler.ErrorHandler): + """Object that fixes simple style errors.""" + + def __init__(self, external_file = None): + """Initialize the error fixer. + + Args: + external_file: If included, all output will be directed to this file + instead of overwriting the files the errors are found in. + """ + self._file_name = None + self._file_token = None + self._external_file = external_file + + def HandleFile(self, filename, first_token): + """Notifies this ErrorPrinter that subsequent errors are in filename. + + Args: + filename: The name of the file about to be checked. + first_token: The first token in the file. + """ + self._file_name = filename + self._file_token = first_token + self._file_fix_count = 0 + self._file_changed_lines = set() + + def _AddFix(self, tokens): + """Adds the fix to the internal count. + + Args: + tokens: The token or sequence of tokens changed to fix an error. + """ + self._file_fix_count += 1 + if hasattr(tokens, 'line_number'): + self._file_changed_lines.add(tokens.line_number) + else: + for token in tokens: + self._file_changed_lines.add(token.line_number) + + def HandleError(self, error): + """Attempts to fix the error. + + Args: + error: The error object + """ + code = error.code + token = error.token + + if code == errors.JSDOC_PREFER_QUESTION_TO_PIPE_NULL: + iterator = token.attached_object.type_start_token + if iterator.type == Type.DOC_START_BRACE or iterator.string.isspace(): + iterator = iterator.next + + leading_space = len(iterator.string) - len(iterator.string.lstrip()) + iterator.string = '%s?%s' % (' ' * leading_space, + iterator.string.lstrip()) + + # Cover the no outer brace case where the end token is part of the type. + while iterator and iterator != token.attached_object.type_end_token.next: + iterator.string = iterator.string.replace( + 'null|', '').replace('|null', '') + iterator = iterator.next + + # Create a new flag object with updated type info. + token.attached_object = javascriptstatetracker.JsDocFlag(token) + self._AddFix(token) + + elif code in (errors.MISSING_SEMICOLON_AFTER_FUNCTION, + errors.MISSING_SEMICOLON): + semicolon_token = Token(';', Type.SEMICOLON, token.line, + token.line_number) + tokenutil.InsertTokenAfter(semicolon_token, token) + token.metadata.is_implied_semicolon = False + semicolon_token.metadata.is_implied_semicolon = False + self._AddFix(token) + + elif code in (errors.ILLEGAL_SEMICOLON_AFTER_FUNCTION, + errors.REDUNDANT_SEMICOLON, + errors.COMMA_AT_END_OF_LITERAL): + tokenutil.DeleteToken(token) + self._AddFix(token) + + elif code == errors.INVALID_JSDOC_TAG: + if token.string == '@returns': + token.string = '@return' + self._AddFix(token) + + elif code == errors.FILE_MISSING_NEWLINE: + # This error is fixed implicitly by the way we restore the file + self._AddFix(token) + + elif code == errors.MISSING_SPACE: + if error.position: + if error.position.IsAtBeginning(): + tokenutil.InsertSpaceTokenAfter(token.previous) + elif error.position.IsAtEnd(token.string): + tokenutil.InsertSpaceTokenAfter(token) + else: + token.string = error.position.Set(token.string, ' ') + self._AddFix(token) + + elif code == errors.EXTRA_SPACE: + if error.position: + token.string = error.position.Set(token.string, '') + self._AddFix(token) + + elif code == errors.JSDOC_TAG_DESCRIPTION_ENDS_WITH_INVALID_CHARACTER: + token.string = error.position.Set(token.string, '.') + self._AddFix(token) + + elif code == errors.MISSING_LINE: + if error.position.IsAtBeginning(): + tokenutil.InsertLineAfter(token.previous) + else: + tokenutil.InsertLineAfter(token) + self._AddFix(token) + + elif code == errors.EXTRA_LINE: + tokenutil.DeleteToken(token) + self._AddFix(token) + + elif code == errors.WRONG_BLANK_LINE_COUNT: + if not token.previous: + # TODO(user): Add an insertBefore method to tokenutil. + return + + num_lines = error.fix_data + should_delete = False + + if num_lines < 0: + num_lines = num_lines * -1 + should_delete = True + + for i in xrange(1, num_lines + 1): + if should_delete: + # TODO(user): DeleteToken should update line numbers. + tokenutil.DeleteToken(token.previous) + else: + tokenutil.InsertLineAfter(token.previous) + self._AddFix(token) + + elif code == errors.UNNECESSARY_DOUBLE_QUOTED_STRING: + end_quote = tokenutil.Search(token, Type.DOUBLE_QUOTE_STRING_END) + if end_quote: + single_quote_start = Token("'", Type.SINGLE_QUOTE_STRING_START, + token.line, token.line_number) + single_quote_end = Token("'", Type.SINGLE_QUOTE_STRING_START, + end_quote.line, token.line_number) + + tokenutil.InsertTokenAfter(single_quote_start, token) + tokenutil.InsertTokenAfter(single_quote_end, end_quote) + tokenutil.DeleteToken(token) + tokenutil.DeleteToken(end_quote) + self._AddFix([token, end_quote]) + + elif code == errors.MISSING_BRACES_AROUND_TYPE: + fixed_tokens = [] + start_token = token.attached_object.type_start_token + + if start_token.type != Type.DOC_START_BRACE: + leading_space = (len(start_token.string) - + len(start_token.string.lstrip())) + if leading_space: + start_token = tokenutil.SplitToken(start_token, leading_space) + # Fix case where start and end token were the same. + if token.attached_object.type_end_token == start_token.previous: + token.attached_object.type_end_token = start_token + + new_token = Token("{", Type.DOC_START_BRACE, start_token.line, + start_token.line_number) + tokenutil.InsertTokenAfter(new_token, start_token.previous) + token.attached_object.type_start_token = new_token + fixed_tokens.append(new_token) + + end_token = token.attached_object.type_end_token + if end_token.type != Type.DOC_END_BRACE: + # If the start token was a brace, the end token will be a + # FLAG_ENDING_TYPE token, if there wasn't a starting brace then + # the end token is the last token of the actual type. + last_type = end_token + if not len(fixed_tokens): + last_type = end_token.previous + + while last_type.string.isspace(): + last_type = last_type.previous + + # If there was no starting brace then a lone end brace wouldn't have + # been type end token. Now that we've added any missing start brace, + # see if the last effective type token was an end brace. + if last_type.type != Type.DOC_END_BRACE: + trailing_space = (len(last_type.string) - + len(last_type.string.rstrip())) + if trailing_space: + tokenutil.SplitToken(last_type, + len(last_type.string) - trailing_space) + + new_token = Token("}", Type.DOC_END_BRACE, last_type.line, + last_type.line_number) + tokenutil.InsertTokenAfter(new_token, last_type) + token.attached_object.type_end_token = new_token + fixed_tokens.append(new_token) + + self._AddFix(fixed_tokens) + + elif code in (errors.GOOG_REQUIRES_NOT_ALPHABETIZED, + errors.GOOG_PROVIDES_NOT_ALPHABETIZED): + tokens = error.fix_data + strings = map(lambda x: x.string, tokens) + sorted_strings = sorted(strings) + + index = 0 + changed_tokens = [] + for token in tokens: + if token.string != sorted_strings[index]: + token.string = sorted_strings[index] + changed_tokens.append(token) + index += 1 + + self._AddFix(changed_tokens) + + elif code == errors.UNNECESSARY_BRACES_AROUND_INHERIT_DOC: + if token.previous.string == '{' and token.next.string == '}': + tokenutil.DeleteToken(token.previous) + tokenutil.DeleteToken(token.next) + self._AddFix([token]) + + elif (code == errors.WRONG_INDENTATION and + not FLAGS.disable_indentation_fixing): + token = tokenutil.GetFirstTokenInSameLine(token) + actual = error.position.start + expected = error.position.length + + if token.type in (Type.WHITESPACE, Type.PARAMETERS): + token.string = token.string.lstrip() + (' ' * expected) + self._AddFix([token]) + else: + # We need to add indentation. + new_token = Token(' ' * expected, Type.WHITESPACE, + token.line, token.line_number) + # Note that we'll never need to add indentation at the first line, + # since it will always not be indented. Therefore it's safe to assume + # token.previous exists. + tokenutil.InsertTokenAfter(new_token, token.previous) + self._AddFix([token]) + + elif code == errors.EXTRA_GOOG_REQUIRE: + fixed_tokens = [] + while token: + if token.type == Type.IDENTIFIER: + if token.string not in ['goog.require', 'goog.provide']: + # Stop iterating over tokens once we're out of the requires and + # provides. + break + if token.string == 'goog.require': + # Text of form: goog.require('required'), skipping past open paren + # and open quote to the string text. + required = token.next.next.next.string + if required in error.fix_data: + fixed_tokens.append(token) + # Want to delete: goog.require + open paren + open single-quote + + # text + close single-quote + close paren + semi-colon = 7. + tokenutil.DeleteTokens(token, 7) + token = token.next + + self._AddFix(fixed_tokens) + + def FinishFile(self): + """Called when the current file has finished style checking. + + Used to go back and fix any errors in the file. + """ + if self._file_fix_count: + f = self._external_file + if not f: + print "Fixed %d errors in %s" % (self._file_fix_count, self._file_name) + f = open(self._file_name, 'w') + + token = self._file_token + char_count = 0 + while token: + f.write(token.string) + char_count += len(token.string) + + if token.IsLastInLine(): + f.write('\n') + if char_count > 80 and token.line_number in self._file_changed_lines: + print "WARNING: Line %d of %s is now longer than 80 characters." % ( + token.line_number, self._file_name) + + char_count = 0 + self._file_changed_lines + + token = token.next + + if not self._external_file: + # Close the file if we created it + f.close() diff --git a/node-v0.8.14/tools/closure_linter/closure_linter/errorrules.py b/node-v0.8.14/tools/closure_linter/closure_linter/errorrules.py new file mode 100755 index 0000000..afb6fa9 --- /dev/null +++ b/node-v0.8.14/tools/closure_linter/closure_linter/errorrules.py @@ -0,0 +1,42 @@ +#!/usr/bin/env python +# +# Copyright 2010 The Closure Linter Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS-IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Linter error rules class for Closure Linter.""" + +__author__ = 'robbyw@google.com (Robert Walker)' + +import gflags as flags +from closure_linter import errors + + +FLAGS = flags.FLAGS +flags.DEFINE_boolean('jsdoc', True, + 'Whether to report errors for missing JsDoc.') + + +def ShouldReportError(error): + """Whether the given error should be reported. + + Returns: + True for all errors except missing documentation errors. For these, + it returns the value of the jsdoc flag. + """ + return FLAGS.jsdoc or error not in ( + errors.MISSING_PARAMETER_DOCUMENTATION, + errors.MISSING_RETURN_DOCUMENTATION, + errors.MISSING_MEMBER_DOCUMENTATION, + errors.MISSING_PRIVATE, + errors.MISSING_JSDOC_TAG_THIS) diff --git a/node-v0.8.14/tools/closure_linter/closure_linter/errors.py b/node-v0.8.14/tools/closure_linter/closure_linter/errors.py new file mode 100755 index 0000000..7c86941 --- /dev/null +++ b/node-v0.8.14/tools/closure_linter/closure_linter/errors.py @@ -0,0 +1,131 @@ +#!/usr/bin/env python +# +# Copyright 2007 The Closure Linter Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS-IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Error codes for JavaScript style checker.""" + +__author__ = ('robbyw@google.com (Robert Walker)', + 'ajp@google.com (Andy Perelson)') + +def ByName(name): + """Get the error code for the given error name. + + Args: + name: The name of the error + + Returns: + The error code + """ + return globals()[name] + + +# "File-fatal" errors - these errors stop further parsing of a single file +FILE_NOT_FOUND = -1 +FILE_DOES_NOT_PARSE = -2 + +# Spacing +EXTRA_SPACE = 1 +MISSING_SPACE = 2 +EXTRA_LINE = 3 +MISSING_LINE = 4 +ILLEGAL_TAB = 5 +WRONG_INDENTATION = 6 +WRONG_BLANK_LINE_COUNT = 7 + +# Semicolons +MISSING_SEMICOLON = 10 +MISSING_SEMICOLON_AFTER_FUNCTION = 11 +ILLEGAL_SEMICOLON_AFTER_FUNCTION = 12 +REDUNDANT_SEMICOLON = 13 + +# Miscellaneous +ILLEGAL_PROTOTYPE_MEMBER_VALUE = 100 +LINE_TOO_LONG = 110 +LINE_STARTS_WITH_OPERATOR = 120 +COMMA_AT_END_OF_LITERAL = 121 +MULTI_LINE_STRING = 130 +UNNECESSARY_DOUBLE_QUOTED_STRING = 131 + +# Requires, provides +GOOG_REQUIRES_NOT_ALPHABETIZED = 140 +GOOG_PROVIDES_NOT_ALPHABETIZED = 141 +MISSING_GOOG_REQUIRE = 142 +MISSING_GOOG_PROVIDE = 143 +EXTRA_GOOG_REQUIRE = 144 + +# JsDoc +INVALID_JSDOC_TAG = 200 +INVALID_USE_OF_DESC_TAG = 201 +NO_BUG_NUMBER_AFTER_BUG_TAG = 202 +MISSING_PARAMETER_DOCUMENTATION = 210 +EXTRA_PARAMETER_DOCUMENTATION = 211 +WRONG_PARAMETER_DOCUMENTATION = 212 +MISSING_JSDOC_TAG_TYPE = 213 +MISSING_JSDOC_TAG_DESCRIPTION = 214 +MISSING_JSDOC_PARAM_NAME = 215 +OUT_OF_ORDER_JSDOC_TAG_TYPE = 216 +MISSING_RETURN_DOCUMENTATION = 217 +UNNECESSARY_RETURN_DOCUMENTATION = 218 +MISSING_BRACES_AROUND_TYPE = 219 +MISSING_MEMBER_DOCUMENTATION = 220 +MISSING_PRIVATE = 221 +EXTRA_PRIVATE = 222 +INVALID_OVERRIDE_PRIVATE = 223 +INVALID_INHERIT_DOC_PRIVATE = 224 +MISSING_JSDOC_TAG_THIS = 225 +UNNECESSARY_BRACES_AROUND_INHERIT_DOC = 226 +INVALID_AUTHOR_TAG_DESCRIPTION = 227 +JSDOC_PREFER_QUESTION_TO_PIPE_NULL = 230 +JSDOC_ILLEGAL_QUESTION_WITH_PIPE = 231 +JSDOC_TAG_DESCRIPTION_ENDS_WITH_INVALID_CHARACTER = 240 +# TODO(robbyw): Split this in to more specific syntax problems. +INCORRECT_SUPPRESS_SYNTAX = 250 +INVALID_SUPPRESS_TYPE = 251 +UNNECESSARY_SUPPRESS = 252 + +# File ending +FILE_MISSING_NEWLINE = 300 +FILE_IN_BLOCK = 301 + +# Interfaces +INTERFACE_CONSTRUCTOR_CANNOT_HAVE_PARAMS = 400 +INTERFACE_METHOD_CANNOT_HAVE_CODE = 401 + +# ActionScript specific errors: +# TODO(user): move these errors to their own file and move all JavaScript +# specific errors to their own file as well. +# All ActionScript specific errors should have error number at least 1000. +FUNCTION_MISSING_RETURN_TYPE = 1132 +PARAMETER_MISSING_TYPE = 1133 +VAR_MISSING_TYPE = 1134 +PARAMETER_MISSING_DEFAULT_VALUE = 1135 +IMPORTS_NOT_ALPHABETIZED = 1140 +IMPORT_CONTAINS_WILDCARD = 1141 +UNUSED_IMPORT = 1142 +INVALID_TRACE_SEVERITY_LEVEL = 1250 +MISSING_TRACE_SEVERITY_LEVEL = 1251 +MISSING_TRACE_MESSAGE = 1252 +REMOVE_TRACE_BEFORE_SUBMIT = 1253 +REMOVE_COMMENT_BEFORE_SUBMIT = 1254 +# End of list of ActionScript specific errors. + +NEW_ERRORS = frozenset([ + # Errors added after 2.0.2: + WRONG_INDENTATION, + MISSING_SEMICOLON, + # Errors added after 2.2.5: + WRONG_BLANK_LINE_COUNT, + EXTRA_GOOG_REQUIRE, + ]) diff --git a/node-v0.8.14/tools/closure_linter/closure_linter/fixjsstyle.py b/node-v0.8.14/tools/closure_linter/closure_linter/fixjsstyle.py new file mode 100755 index 0000000..8782e64 --- /dev/null +++ b/node-v0.8.14/tools/closure_linter/closure_linter/fixjsstyle.py @@ -0,0 +1,47 @@ +#!/usr/bin/env python +# +# Copyright 2007 The Closure Linter Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS-IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Automatically fix simple style guide violations.""" + +__author__ = 'robbyw@google.com (Robert Walker)' + +import sys + +import gflags as flags +from closure_linter import checker +from closure_linter import error_fixer +from closure_linter.common import simplefileflags as fileflags + + +def main(argv = None): + """Main function. + + Args: + argv: Sequence of command line arguments. + """ + if argv is None: + argv = flags.FLAGS(sys.argv) + + files = fileflags.GetFileList(argv, 'JavaScript', ['.js']) + + style_checker = checker.JavaScriptStyleChecker(error_fixer.ErrorFixer()) + + # Check the list of files. + for filename in files: + style_checker.Check(filename) + +if __name__ == '__main__': + main() diff --git a/node-v0.8.14/tools/closure_linter/closure_linter/fixjsstyle_test.py b/node-v0.8.14/tools/closure_linter/closure_linter/fixjsstyle_test.py new file mode 100755 index 0000000..42e9c59 --- /dev/null +++ b/node-v0.8.14/tools/closure_linter/closure_linter/fixjsstyle_test.py @@ -0,0 +1,61 @@ +#!/usr/bin/env python +# +# Copyright 2008 The Closure Linter Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS-IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Medium tests for the gpylint auto-fixer.""" + +__author__ = 'robbyw@google.com (Robby Walker)' + +import StringIO + +import gflags as flags +import unittest as googletest +from closure_linter import checker +from closure_linter import error_fixer + +_RESOURCE_PREFIX = 'closure_linter/testdata' + +flags.FLAGS.strict = True +flags.FLAGS.limited_doc_files = ('dummy.js', 'externs.js') +flags.FLAGS.closurized_namespaces = ('goog', 'dummy') + +class FixJsStyleTest(googletest.TestCase): + """Test case to for gjslint auto-fixing.""" + + def testFixJsStyle(self): + input_filename = None + try: + input_filename = '%s/fixjsstyle.in.js' % (_RESOURCE_PREFIX) + + golden_filename = '%s/fixjsstyle.out.js' % (_RESOURCE_PREFIX) + except IOError, ex: + raise IOError('Could not find testdata resource for %s: %s' % + (self._filename, ex)) + + # Autofix the file, sending output to a fake file. + actual = StringIO.StringIO() + style_checker = checker.JavaScriptStyleChecker( + error_fixer.ErrorFixer(actual)) + style_checker.Check(input_filename) + + # Now compare the files. + actual.seek(0) + expected = open(golden_filename, 'r') + + self.assertEqual(actual.readlines(), expected.readlines()) + + +if __name__ == '__main__': + googletest.main() diff --git a/node-v0.8.14/tools/closure_linter/closure_linter/full_test.py b/node-v0.8.14/tools/closure_linter/closure_linter/full_test.py new file mode 100755 index 0000000..f11f235 --- /dev/null +++ b/node-v0.8.14/tools/closure_linter/closure_linter/full_test.py @@ -0,0 +1,99 @@ +#!/usr/bin/env python +# +# Copyright 2007 The Closure Linter Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS-IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Full regression-type (Medium) tests for gjslint. + +Tests every error that can be thrown by gjslint. Based heavily on +devtools/javascript/gpylint/full_test.py +""" + +__author__ = ('robbyw@google.com (Robert Walker)', + 'ajp@google.com (Andy Perelson)') + +import re +import os +import sys +import unittest + +import gflags as flags +import unittest as googletest + +from closure_linter import checker +from closure_linter import errors +from closure_linter.common import filetestcase + +_RESOURCE_PREFIX = 'closure_linter/testdata' + +flags.FLAGS.strict = True +flags.FLAGS.custom_jsdoc_tags = ('customtag', 'requires') +flags.FLAGS.closurized_namespaces = ('goog', 'dummy') +flags.FLAGS.limited_doc_files = ('externs.js', 'dummy.js') + +# List of files under testdata to test. +# We need to list files explicitly since pyglib can't list directories. +_TEST_FILES = [ + 'all_js_wrapped.js', + 'blank_lines.js', + 'ends_with_block.js', + 'externs.js', + 'html_parse_error.html', + 'indentation.js', + 'interface.js', + 'jsdoc.js', + 'minimal.js', + 'other.js', + 'require_all_caps.js', + 'require_extra.js', + 'require_function.js', + 'require_function_missing.js', + 'require_function_through_both.js', + 'require_function_through_namespace.js', + 'require_interface.js', + 'require_lower_case.js', + 'require_numeric.js', + 'require_provide_ok.js', + 'require_provide_missing.js', + 'simple.html', + 'spaces.js', + 'tokenizer.js', + 'unparseable.js', + 'utf8.html' + ] + + +class GJsLintTestSuite(unittest.TestSuite): + """Test suite to run a GJsLintTest for each of several files. + + If sys.argv[1:] is non-empty, it is interpreted as a list of filenames in + testdata to test. Otherwise, _TEST_FILES is used. + """ + + def __init__(self, tests=()): + unittest.TestSuite.__init__(self, tests) + + argv = sys.argv and sys.argv[1:] or [] + if argv: + test_files = argv + else: + test_files = _TEST_FILES + for test_file in test_files: + resource_path = os.path.join(_RESOURCE_PREFIX, test_file) + self.addTest(filetestcase.AnnotatedFileTestCase(resource_path, + checker.GJsLintRunner(), errors.ByName)) + +if __name__ == '__main__': + # Don't let main parse args; it happens in the TestSuite. + googletest.main(argv=sys.argv[0:1], defaultTest='GJsLintTestSuite') diff --git a/node-v0.8.14/tools/closure_linter/closure_linter/gjslint.py b/node-v0.8.14/tools/closure_linter/closure_linter/gjslint.py new file mode 100755 index 0000000..e33bddd --- /dev/null +++ b/node-v0.8.14/tools/closure_linter/closure_linter/gjslint.py @@ -0,0 +1,142 @@ +#!/usr/bin/env python +# +# Copyright 2007 The Closure Linter Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS-IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Checks JavaScript files for common style guide violations. + +gjslint.py is designed to be used as a PRESUBMIT script to check for javascript +style guide violations. As of now, it checks for the following violations: + + * Missing and extra spaces + * Lines longer than 80 characters + * Missing newline at end of file + * Missing semicolon after function declaration + * Valid JsDoc including parameter matching + +Someday it will validate to the best of its ability against the entirety of the +JavaScript style guide. + +This file is a front end that parses arguments and flags. The core of the code +is in tokenizer.py and checker.py. +""" + +__author__ = ('robbyw@google.com (Robert Walker)', + 'ajp@google.com (Andy Perelson)') + +import sys +import time + +from closure_linter import checker +from closure_linter import errors +from closure_linter.common import errorprinter +from closure_linter.common import simplefileflags as fileflags +import gflags as flags + + +FLAGS = flags.FLAGS +flags.DEFINE_boolean('unix_mode', False, + 'Whether to emit warnings in standard unix format.') +flags.DEFINE_boolean('beep', True, 'Whether to beep when errors are found.') +flags.DEFINE_boolean('time', False, 'Whether to emit timing statistics.') +flags.DEFINE_boolean('check_html', False, + 'Whether to check javascript in html files.') +flags.DEFINE_boolean('summary', False, + 'Whether to show an error count summary.') + +GJSLINT_ONLY_FLAGS = ['--unix_mode', '--beep', '--nobeep', '--time', + '--check_html', '--summary'] + + +def FormatTime(t): + """Formats a duration as a human-readable string. + + Args: + t: A duration in seconds. + + Returns: + A formatted duration string. + """ + if t < 1: + return '%dms' % round(t * 1000) + else: + return '%.2fs' % t + + +def main(argv = None): + """Main function. + + Args: + argv: Sequence of command line arguments. + """ + if argv is None: + argv = flags.FLAGS(sys.argv) + + if FLAGS.time: + start_time = time.time() + + suffixes = ['.js'] + if FLAGS.check_html: + suffixes += ['.html', '.htm'] + files = fileflags.GetFileList(argv, 'JavaScript', suffixes) + + error_handler = None + if FLAGS.unix_mode: + error_handler = errorprinter.ErrorPrinter(errors.NEW_ERRORS) + error_handler.SetFormat(errorprinter.UNIX_FORMAT) + + runner = checker.GJsLintRunner() + result = runner.Run(files, error_handler) + result.PrintSummary() + + exit_code = 0 + if result.HasOldErrors(): + exit_code += 1 + if result.HasNewErrors(): + exit_code += 2 + + if exit_code: + if FLAGS.summary: + result.PrintFileSummary() + + if FLAGS.beep: + # Make a beep noise. + sys.stdout.write(chr(7)) + + # Write out instructions for using fixjsstyle script to fix some of the + # reported errors. + fix_args = [] + for flag in sys.argv[1:]: + for f in GJSLINT_ONLY_FLAGS: + if flag.startswith(f): + break + else: + fix_args.append(flag) + + print """ +Some of the errors reported by GJsLint may be auto-fixable using the script +fixjsstyle. Please double check any changes it makes and report any bugs. The +script can be run by executing: + +fixjsstyle %s +""" % ' '.join(fix_args) + + if FLAGS.time: + print 'Done in %s.' % FormatTime(time.time() - start_time) + + sys.exit(exit_code) + + +if __name__ == '__main__': + main() diff --git a/node-v0.8.14/tools/closure_linter/closure_linter/indentation.py b/node-v0.8.14/tools/closure_linter/closure_linter/indentation.py new file mode 100755 index 0000000..d740607 --- /dev/null +++ b/node-v0.8.14/tools/closure_linter/closure_linter/indentation.py @@ -0,0 +1,543 @@ +#!/usr/bin/env python +# +# Copyright 2010 The Closure Linter Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS-IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Methods for checking EcmaScript files for indentation issues.""" + +__author__ = ('robbyw@google.com (Robert Walker)') + +from closure_linter import ecmametadatapass +from closure_linter import errors +from closure_linter import javascripttokens +from closure_linter import tokenutil +from closure_linter.common import error +from closure_linter.common import position + +import gflags as flags + +flags.DEFINE_boolean('debug_indentation', False, + 'Whether to print debugging information for indentation.') + + +# Shorthand +Context = ecmametadatapass.EcmaContext +Error = error.Error +Position = position.Position +Type = javascripttokens.JavaScriptTokenType + + +# The general approach: +# +# 1. Build a stack of tokens that can affect indentation. +# For each token, we determine if it is a block or continuation token. +# Some tokens need to be temporarily overwritten in case they are removed +# before the end of the line. +# Much of the work here is determining which tokens to keep on the stack +# at each point. Operators, for example, should be removed once their +# expression or line is gone, while parentheses must stay until the matching +# end parentheses is found. +# +# 2. Given that stack, determine the allowable indentations. +# Due to flexible indentation rules in JavaScript, there may be many +# allowable indentations for each stack. We follows the general +# "no false positives" approach of GJsLint and build the most permissive +# set possible. + + +class TokenInfo(object): + """Stores information about a token. + + Attributes: + token: The token + is_block: Whether the token represents a block indentation. + is_transient: Whether the token should be automatically removed without + finding a matching end token. + overridden_by: TokenInfo for a token that overrides the indentation that + this token would require. + is_permanent_override: Whether the override on this token should persist + even after the overriding token is removed from the stack. For example: + x([ + 1], + 2); + needs this to be set so the last line is not required to be a continuation + indent. + line_number: The effective line number of this token. Will either be the + actual line number or the one before it in the case of a mis-wrapped + operator. + """ + + def __init__(self, token, is_block=False): + """Initializes a TokenInfo object. + + Args: + token: The token + is_block: Whether the token represents a block indentation. + """ + self.token = token + self.overridden_by = None + self.is_permanent_override = False + self.is_block = is_block + self.is_transient = not is_block and not token.type in ( + Type.START_PAREN, Type.START_PARAMETERS) + self.line_number = token.line_number + + def __repr__(self): + result = '\n %s' % self.token + if self.overridden_by: + result = '%s OVERRIDDEN [by "%s"]' % ( + result, self.overridden_by.token.string) + result += ' {is_block: %s, is_transient: %s}' % ( + self.is_block, self.is_transient) + return result + + +class IndentationRules(object): + """EmcaScript indentation rules. + + Can be used to find common indentation errors in JavaScript, ActionScript and + other Ecma like scripting languages. + """ + + def __init__(self): + """Initializes the IndentationRules checker.""" + self._stack = [] + + # Map from line number to number of characters it is off in indentation. + self._start_index_offset = {} + + def Finalize(self): + if self._stack: + old_stack = self._stack + self._stack = [] + raise Exception("INTERNAL ERROR: indentation stack is not empty: %r" % + old_stack) + + def CheckToken(self, token, state): + """Checks a token for indentation errors. + + Args: + token: The current token under consideration + state: Additional information about the current tree state + + Returns: + An error array [error code, error string, error token] if the token is + improperly indented, or None if indentation is correct. + """ + + token_type = token.type + indentation_errors = [] + stack = self._stack + is_first = self._IsFirstNonWhitespaceTokenInLine(token) + + # Add tokens that could decrease indentation before checking. + if token_type == Type.END_PAREN: + self._PopTo(Type.START_PAREN) + + elif token_type == Type.END_PARAMETERS: + self._PopTo(Type.START_PARAMETERS) + + elif token_type == Type.END_BRACKET: + self._PopTo(Type.START_BRACKET) + + elif token_type == Type.END_BLOCK: + self._PopTo(Type.START_BLOCK) + + elif token_type == Type.KEYWORD and token.string in ('case', 'default'): + self._Add(self._PopTo(Type.START_BLOCK)) + + elif is_first and token.string == '.': + # This token should have been on the previous line, so treat it as if it + # was there. + info = TokenInfo(token) + info.line_number = token.line_number - 1 + self._Add(info) + + elif token_type == Type.SEMICOLON: + self._PopTransient() + + not_binary_operator = (token_type != Type.OPERATOR or + token.metadata.IsUnaryOperator()) + not_dot = token.string != '.' + if is_first and not_binary_operator and not_dot and token.type not in ( + Type.COMMENT, Type.DOC_PREFIX, Type.STRING_TEXT): + if flags.FLAGS.debug_indentation: + print 'Line #%d: stack %r' % (token.line_number, stack) + + # Ignore lines that start in JsDoc since we don't check them properly yet. + # TODO(robbyw): Support checking JsDoc indentation. + # Ignore lines that start as multi-line strings since indentation is N/A. + # Ignore lines that start with operators since we report that already. + # Ignore lines with tabs since we report that already. + expected = self._GetAllowableIndentations() + actual = self._GetActualIndentation(token) + + # Special case comments describing else, case, and default. Allow them + # to outdent to the parent block. + if token_type in Type.COMMENT_TYPES: + next_code = tokenutil.SearchExcept(token, Type.NON_CODE_TYPES) + if next_code and next_code.type == Type.END_BLOCK: + next_code = tokenutil.SearchExcept(next_code, Type.NON_CODE_TYPES) + if next_code and next_code.string in ('else', 'case', 'default'): + # TODO(robbyw): This almost certainly introduces false negatives. + expected |= self._AddToEach(expected, -2) + + if actual >= 0 and actual not in expected: + expected = sorted(expected) + indentation_errors.append([ + errors.WRONG_INDENTATION, + 'Wrong indentation: expected any of {%s} but got %d' % ( + ', '.join( + ['%d' % x for x in expected]), actual), + token, + Position(actual, expected[0])]) + self._start_index_offset[token.line_number] = expected[0] - actual + + # Add tokens that could increase indentation. + if token_type == Type.START_BRACKET: + self._Add(TokenInfo(token=token, + is_block=token.metadata.context.type == Context.ARRAY_LITERAL)) + + elif token_type == Type.START_BLOCK or token.metadata.is_implied_block: + self._Add(TokenInfo(token=token, is_block=True)) + + elif token_type in (Type.START_PAREN, Type.START_PARAMETERS): + self._Add(TokenInfo(token=token, is_block=False)) + + elif token_type == Type.KEYWORD and token.string == 'return': + self._Add(TokenInfo(token)) + + elif not token.IsLastInLine() and ( + token.IsAssignment() or token.IsOperator('?')): + self._Add(TokenInfo(token=token)) + + # Handle implied block closes. + if token.metadata.is_implied_block_close: + self._PopToImpliedBlock() + + # Add some tokens only if they appear at the end of the line. + is_last = self._IsLastCodeInLine(token) + if is_last: + if token_type == Type.OPERATOR: + if token.string == ':': + if (stack and stack[-1].token.string == '?'): + # When a ternary : is on a different line than its '?', it doesn't + # add indentation. + if (token.line_number == stack[-1].token.line_number): + self._Add(TokenInfo(token)) + elif token.metadata.context.type == Context.CASE_BLOCK: + # Pop transient tokens from say, line continuations, e.g., + # case x. + # y: + # Want to pop the transient 4 space continuation indent. + self._PopTransient() + # Starting the body of the case statement, which is a type of + # block. + self._Add(TokenInfo(token=token, is_block=True)) + elif token.metadata.context.type == Context.LITERAL_ELEMENT: + # When in an object literal, acts as operator indicating line + # continuations. + self._Add(TokenInfo(token)) + pass + else: + # ':' might also be a statement label, no effect on indentation in + # this case. + pass + + elif token.string != ',': + self._Add(TokenInfo(token)) + else: + # The token is a comma. + if token.metadata.context.type == Context.VAR: + self._Add(TokenInfo(token)) + elif token.metadata.context.type != Context.PARAMETERS: + self._PopTransient() + + elif (token.string.endswith('.') + and token_type in (Type.IDENTIFIER, Type.NORMAL)): + self._Add(TokenInfo(token)) + elif token_type == Type.PARAMETERS and token.string.endswith(','): + # Parameter lists. + self._Add(TokenInfo(token)) + elif token.metadata.is_implied_semicolon: + self._PopTransient() + elif token.IsAssignment(): + self._Add(TokenInfo(token)) + + return indentation_errors + + def _AddToEach(self, original, amount): + """Returns a new set with the given amount added to each element. + + Args: + original: The original set of numbers + amount: The amount to add to each element + + Returns: + A new set containing each element of the original set added to the amount. + """ + return set([x + amount for x in original]) + + _HARD_STOP_TYPES = (Type.START_PAREN, Type.START_PARAMETERS, + Type.START_BRACKET) + + _HARD_STOP_STRINGS = ('return', '?') + + def _IsHardStop(self, token): + """Determines if the given token can have a hard stop after it. + + Hard stops are indentations defined by the position of another token as in + indentation lined up with return, (, [, and ?. + """ + return (token.type in self._HARD_STOP_TYPES or + token.string in self._HARD_STOP_STRINGS or + token.IsAssignment()) + + def _GetAllowableIndentations(self): + """Computes the set of allowable indentations. + + Returns: + The set of allowable indentations, given the current stack. + """ + expected = set([0]) + hard_stops = set([]) + + # Whether the tokens are still in the same continuation, meaning additional + # indentation is optional. As an example: + # x = 5 + + # 6 + + # 7; + # The second '+' does not add any required indentation. + in_same_continuation = False + + for token_info in self._stack: + token = token_info.token + + # Handle normal additive indentation tokens. + if not token_info.overridden_by and token.string != 'return': + if token_info.is_block: + expected = self._AddToEach(expected, 2) + hard_stops = self._AddToEach(hard_stops, 2) + in_same_continuation = False + elif in_same_continuation: + expected |= self._AddToEach(expected, 4) + hard_stops |= self._AddToEach(hard_stops, 4) + else: + expected = self._AddToEach(expected, 4) + hard_stops |= self._AddToEach(hard_stops, 4) + in_same_continuation = True + + # Handle hard stops after (, [, return, =, and ? + if self._IsHardStop(token): + override_is_hard_stop = (token_info.overridden_by and + self._IsHardStop(token_info.overridden_by.token)) + if not override_is_hard_stop: + start_index = token.start_index + if token.line_number in self._start_index_offset: + start_index += self._start_index_offset[token.line_number] + if (token.type in (Type.START_PAREN, Type.START_PARAMETERS) and + not token_info.overridden_by): + hard_stops.add(start_index + 1) + + elif token.string == 'return' and not token_info.overridden_by: + hard_stops.add(start_index + 7) + + elif (token.type == Type.START_BRACKET): + hard_stops.add(start_index + 1) + + elif token.IsAssignment(): + hard_stops.add(start_index + len(token.string) + 1) + + elif token.IsOperator('?') and not token_info.overridden_by: + hard_stops.add(start_index + 2) + + return (expected | hard_stops) or set([0]) + + def _GetActualIndentation(self, token): + """Gets the actual indentation of the line containing the given token. + + Args: + token: Any token on the line. + + Returns: + The actual indentation of the line containing the given token. Returns + -1 if this line should be ignored due to the presence of tabs. + """ + # Move to the first token in the line + token = tokenutil.GetFirstTokenInSameLine(token) + + # If it is whitespace, it is the indentation. + if token.type == Type.WHITESPACE: + if token.string.find('\t') >= 0: + return -1 + else: + return len(token.string) + elif token.type == Type.PARAMETERS: + return len(token.string) - len(token.string.lstrip()) + else: + return 0 + + def _IsFirstNonWhitespaceTokenInLine(self, token): + """Determines if the given token is the first non-space token on its line. + + Args: + token: The token. + + Returns: + True if the token is the first non-whitespace token on its line. + """ + if token.type in (Type.WHITESPACE, Type.BLANK_LINE): + return False + if token.IsFirstInLine(): + return True + return (token.previous and token.previous.IsFirstInLine() and + token.previous.type == Type.WHITESPACE) + + def _IsLastCodeInLine(self, token): + """Determines if the given token is the last code token on its line. + + Args: + token: The token. + + Returns: + True if the token is the last code token on its line. + """ + if token.type in Type.NON_CODE_TYPES: + return False + start_token = token + while True: + token = token.next + if not token or token.line_number != start_token.line_number: + return True + if token.type not in Type.NON_CODE_TYPES: + return False + + def _Add(self, token_info): + """Adds the given token info to the stack. + + Args: + token_info: The token information to add. + """ + if self._stack and self._stack[-1].token == token_info.token: + # Don't add the same token twice. + return + + if token_info.is_block or token_info.token.type == Type.START_PAREN: + index = 1 + while index <= len(self._stack): + stack_info = self._stack[-index] + stack_token = stack_info.token + + if stack_info.line_number == token_info.line_number: + # In general, tokens only override each other when they are on + # the same line. + stack_info.overridden_by = token_info + if (token_info.token.type == Type.START_BLOCK and + (stack_token.IsAssignment() or + stack_token.type in (Type.IDENTIFIER, Type.START_PAREN))): + # Multi-line blocks have lasting overrides, as in: + # callFn({ + # a: 10 + # }, + # 30); + close_block = token_info.token.metadata.context.end_token + stack_info.is_permanent_override = \ + close_block.line_number != token_info.token.line_number + elif (token_info.token.type == Type.START_BLOCK and + token_info.token.metadata.context.type == Context.BLOCK and + (stack_token.IsAssignment() or + stack_token.type == Type.IDENTIFIER)): + # When starting a function block, the override can transcend lines. + # For example + # long.long.name = function( + # a) { + # In this case the { and the = are on different lines. But the + # override should still apply. + stack_info.overridden_by = token_info + stack_info.is_permanent_override = True + else: + break + index += 1 + + self._stack.append(token_info) + + def _Pop(self): + """Pops the top token from the stack. + + Returns: + The popped token info. + """ + token_info = self._stack.pop() + if token_info.token.type not in (Type.START_BLOCK, Type.START_BRACKET): + # Remove any temporary overrides. + self._RemoveOverrides(token_info) + else: + # For braces and brackets, which can be object and array literals, remove + # overrides when the literal is closed on the same line. + token_check = token_info.token + same_type = token_check.type + goal_type = None + if token_info.token.type == Type.START_BRACKET: + goal_type = Type.END_BRACKET + else: + goal_type = Type.END_BLOCK + line_number = token_info.token.line_number + count = 0 + while token_check and token_check.line_number == line_number: + if token_check.type == goal_type: + count -= 1 + if not count: + self._RemoveOverrides(token_info) + break + if token_check.type == same_type: + count += 1 + token_check = token_check.next + return token_info + + def _PopToImpliedBlock(self): + """Pops the stack until an implied block token is found.""" + while not self._Pop().token.metadata.is_implied_block: + pass + + def _PopTo(self, stop_type): + """Pops the stack until a token of the given type is popped. + + Args: + stop_type: The type of token to pop to. + + Returns: + The token info of the given type that was popped. + """ + last = None + while True: + last = self._Pop() + if last.token.type == stop_type: + break + return last + + def _RemoveOverrides(self, token_info): + """Marks any token that was overridden by this token as active again. + + Args: + token_info: The token that is being removed from the stack. + """ + for stack_token in self._stack: + if (stack_token.overridden_by == token_info and + not stack_token.is_permanent_override): + stack_token.overridden_by = None + + def _PopTransient(self): + """Pops all transient tokens - i.e. not blocks, literals, or parens.""" + while self._stack and self._stack[-1].is_transient: + self._Pop() diff --git a/node-v0.8.14/tools/closure_linter/closure_linter/javascriptlintrules.py b/node-v0.8.14/tools/closure_linter/closure_linter/javascriptlintrules.py new file mode 100755 index 0000000..6b9f1be --- /dev/null +++ b/node-v0.8.14/tools/closure_linter/closure_linter/javascriptlintrules.py @@ -0,0 +1,395 @@ +#!/usr/bin/env python +# +# Copyright 2008 The Closure Linter Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS-IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Methods for checking JS files for common style guide violations. + +These style guide violations should only apply to JavaScript and not an Ecma +scripting languages. +""" + +__author__ = ('robbyw@google.com (Robert Walker)', + 'ajp@google.com (Andy Perelson)', + 'jacobr@google.com (Jacob Richman)') + +import gflags as flags +from closure_linter import ecmalintrules +from closure_linter import errors +from closure_linter import javascripttokenizer +from closure_linter import javascripttokens +from closure_linter import tokenutil +from closure_linter.common import error +from closure_linter.common import position + +FLAGS = flags.FLAGS +flags.DEFINE_list('closurized_namespaces', '', + 'Namespace prefixes, used for testing of' + 'goog.provide/require') +flags.DEFINE_list('ignored_extra_namespaces', '', + 'Fully qualified namespaces that should be not be reported ' + 'as extra by the linter.') + +# Shorthand +Error = error.Error +Position = position.Position +Type = javascripttokens.JavaScriptTokenType + + +class JavaScriptLintRules(ecmalintrules.EcmaScriptLintRules): + """JavaScript lint rules that catch JavaScript specific style errors.""" + + def HandleMissingParameterDoc(self, token, param_name): + """Handle errors associated with a parameter missing a param tag.""" + self._HandleError(errors.MISSING_PARAMETER_DOCUMENTATION, + 'Missing docs for parameter: "%s"' % param_name, token) + + def __ContainsRecordType(self, token): + """Check whether the given token contains a record type. + + Args: + token: The token being checked + """ + # If we see more than one left-brace in the string of an annotation token, + # then there's a record type in there. + return (token and token.type == Type.DOC_FLAG and + token.attached_object.type is not None and + token.attached_object.type.find('{') != token.string.rfind('{')) + + + def CheckToken(self, token, state): + """Checks a token, given the current parser_state, for warnings and errors. + + Args: + token: The current token under consideration + state: parser_state object that indicates the current state in the page + """ + if self.__ContainsRecordType(token): + # We should bail out and not emit any warnings for this annotation. + # TODO(nicksantos): Support record types for real. + state.GetDocComment().Invalidate() + return + + # Call the base class's CheckToken function. + super(JavaScriptLintRules, self).CheckToken(token, state) + + # Store some convenience variables + first_in_line = token.IsFirstInLine() + last_in_line = token.IsLastInLine() + type = token.type + + if type == Type.DOC_FLAG: + flag = token.attached_object + + if flag.flag_type == 'param' and flag.name_token is not None: + self._CheckForMissingSpaceBeforeToken( + token.attached_object.name_token) + + if flag.flag_type in state.GetDocFlag().HAS_TYPE: + # Check for both missing type token and empty type braces '{}' + # Missing suppress types are reported separately and we allow enums + # without types. + if (flag.flag_type not in ('suppress', 'enum') and + (flag.type == None or flag.type == '' or flag.type.isspace())): + self._HandleError(errors.MISSING_JSDOC_TAG_TYPE, + 'Missing type in %s tag' % token.string, token) + + elif flag.name_token and flag.type_end_token and tokenutil.Compare( + flag.type_end_token, flag.name_token) > 0: + self._HandleError( + errors.OUT_OF_ORDER_JSDOC_TAG_TYPE, + 'Type should be immediately after %s tag' % token.string, + token) + + elif type == Type.DOUBLE_QUOTE_STRING_START: + next = token.next + while next.type == Type.STRING_TEXT: + if javascripttokenizer.JavaScriptTokenizer.SINGLE_QUOTE.search( + next.string): + break + next = next.next + else: + self._HandleError( + errors.UNNECESSARY_DOUBLE_QUOTED_STRING, + 'Single-quoted string preferred over double-quoted string.', + token, + Position.All(token.string)) + + elif type == Type.END_DOC_COMMENT: + if (FLAGS.strict and not self._is_html and state.InTopLevel() and + not state.InBlock()): + + # Check if we're in a fileoverview or constructor JsDoc. + doc_comment = state.GetDocComment() + is_constructor = (doc_comment.HasFlag('constructor') or + doc_comment.HasFlag('interface')) + is_file_overview = doc_comment.HasFlag('fileoverview') + + # If the comment is not a file overview, and it does not immediately + # precede some code, skip it. + # NOTE: The tokenutil methods are not used here because of their + # behavior at the top of a file. + next = token.next + if (not next or + (not is_file_overview and next.type in Type.NON_CODE_TYPES)): + return + + # Find the start of this block (include comments above the block, unless + # this is a file overview). + block_start = doc_comment.start_token + if not is_file_overview: + token = block_start.previous + while token and token.type in Type.COMMENT_TYPES: + block_start = token + token = token.previous + + # Count the number of blank lines before this block. + blank_lines = 0 + token = block_start.previous + while token and token.type in [Type.WHITESPACE, Type.BLANK_LINE]: + if token.type == Type.BLANK_LINE: + # A blank line. + blank_lines += 1 + elif token.type == Type.WHITESPACE and not token.line.strip(): + # A line with only whitespace on it. + blank_lines += 1 + token = token.previous + + # Log errors. + error_message = False + expected_blank_lines = 0 + + if is_file_overview and blank_lines == 0: + error_message = 'Should have a blank line before a file overview.' + expected_blank_lines = 1 + elif is_constructor and blank_lines != 3: + error_message = ('Should have 3 blank lines before a constructor/' + 'interface.') + expected_blank_lines = 3 + elif not is_file_overview and not is_constructor and blank_lines != 2: + error_message = 'Should have 2 blank lines between top-level blocks.' + expected_blank_lines = 2 + + if error_message: + self._HandleError(errors.WRONG_BLANK_LINE_COUNT, error_message, + block_start, Position.AtBeginning(), + expected_blank_lines - blank_lines) + + elif type == Type.END_BLOCK: + if state.InFunction() and state.IsFunctionClose(): + is_immediately_called = (token.next and + token.next.type == Type.START_PAREN) + + function = state.GetFunction() + if not self._limited_doc_checks: + if (function.has_return and function.doc and + not is_immediately_called and + not function.doc.HasFlag('return') and + not function.doc.InheritsDocumentation() and + not function.doc.HasFlag('constructor')): + # Check for proper documentation of return value. + self._HandleError( + errors.MISSING_RETURN_DOCUMENTATION, + 'Missing @return JsDoc in function with non-trivial return', + function.doc.end_token, Position.AtBeginning()) + elif (not function.has_return and function.doc and + function.doc.HasFlag('return') and + not state.InInterfaceMethod()): + return_flag = function.doc.GetFlag('return') + if (return_flag.type is None or ( + 'undefined' not in return_flag.type and + 'void' not in return_flag.type and + '*' not in return_flag.type)): + self._HandleError( + errors.UNNECESSARY_RETURN_DOCUMENTATION, + 'Found @return JsDoc on function that returns nothing', + return_flag.flag_token, Position.AtBeginning()) + + if state.InFunction() and state.IsFunctionClose(): + is_immediately_called = (token.next and + token.next.type == Type.START_PAREN) + if (function.has_this and function.doc and + not function.doc.HasFlag('this') and + not function.is_constructor and + not function.is_interface and + '.prototype.' not in function.name): + self._HandleError( + errors.MISSING_JSDOC_TAG_THIS, + 'Missing @this JsDoc in function referencing "this". (' + 'this usually means you are trying to reference "this" in ' + 'a static function, or you have forgotten to mark a ' + 'constructor with @constructor)', + function.doc.end_token, Position.AtBeginning()) + + elif type == Type.IDENTIFIER: + if token.string == 'goog.inherits' and not state.InFunction(): + if state.GetLastNonSpaceToken().line_number == token.line_number: + self._HandleError( + errors.MISSING_LINE, + 'Missing newline between constructor and goog.inherits', + token, + Position.AtBeginning()) + + extra_space = state.GetLastNonSpaceToken().next + while extra_space != token: + if extra_space.type == Type.BLANK_LINE: + self._HandleError( + errors.EXTRA_LINE, + 'Extra line between constructor and goog.inherits', + extra_space) + extra_space = extra_space.next + + # TODO(robbyw): Test the last function was a constructor. + # TODO(robbyw): Test correct @extends and @implements documentation. + + elif type == Type.OPERATOR: + # If the token is unary and appears to be used in a unary context + # it's ok. Otherwise, if it's at the end of the line or immediately + # before a comment, it's ok. + # Don't report an error before a start bracket - it will be reported + # by that token's space checks. + if (not token.metadata.IsUnaryOperator() and not last_in_line + and not token.next.IsComment() + and not token.next.IsOperator(',') + and not token.next.type in (Type.WHITESPACE, Type.END_PAREN, + Type.END_BRACKET, Type.SEMICOLON, + Type.START_BRACKET)): + self._HandleError( + errors.MISSING_SPACE, + 'Missing space after "%s"' % token.string, + token, + Position.AtEnd(token.string)) + elif type == Type.WHITESPACE: + # Check whitespace length if it's not the first token of the line and + # if it's not immediately before a comment. + if not last_in_line and not first_in_line and not token.next.IsComment(): + # Ensure there is no space after opening parentheses. + if (token.previous.type in (Type.START_PAREN, Type.START_BRACKET, + Type.FUNCTION_NAME) + or token.next.type == Type.START_PARAMETERS): + self._HandleError( + errors.EXTRA_SPACE, + 'Extra space after "%s"' % token.previous.string, + token, + Position.All(token.string)) + + def Finalize(self, state, tokenizer_mode): + """Perform all checks that need to occur after all lines are processed.""" + # Call the base class's Finalize function. + super(JavaScriptLintRules, self).Finalize(state, tokenizer_mode) + + # Check for sorted requires statements. + goog_require_tokens = state.GetGoogRequireTokens() + requires = [require_token.string for require_token in goog_require_tokens] + sorted_requires = sorted(requires) + index = 0 + bad = False + for item in requires: + if item != sorted_requires[index]: + bad = True + break + index += 1 + + if bad: + self._HandleError( + errors.GOOG_REQUIRES_NOT_ALPHABETIZED, + 'goog.require classes must be alphabetized. The correct code is:\n' + + '\n'.join(map(lambda x: 'goog.require(\'%s\');' % x, + sorted_requires)), + goog_require_tokens[index], + position=Position.AtBeginning(), + fix_data=goog_require_tokens) + + # Check for sorted provides statements. + goog_provide_tokens = state.GetGoogProvideTokens() + provides = [provide_token.string for provide_token in goog_provide_tokens] + sorted_provides = sorted(provides) + index = 0 + bad = False + for item in provides: + if item != sorted_provides[index]: + bad = True + break + index += 1 + + if bad: + self._HandleError( + errors.GOOG_PROVIDES_NOT_ALPHABETIZED, + 'goog.provide classes must be alphabetized. The correct code is:\n' + + '\n'.join(map(lambda x: 'goog.provide(\'%s\');' % x, + sorted_provides)), + goog_provide_tokens[index], + position=Position.AtBeginning(), + fix_data=goog_provide_tokens) + + if FLAGS.closurized_namespaces: + # Check that we provide everything we need. + provided_namespaces = state.GetProvidedNamespaces() + missing_provides = provided_namespaces - set(provides) + if missing_provides: + self._HandleError( + errors.MISSING_GOOG_PROVIDE, + 'Missing the following goog.provide statements:\n' + + '\n'.join(map(lambda x: 'goog.provide(\'%s\');' % x, + sorted(missing_provides))), + state.GetFirstToken(), position=Position.AtBeginning(), + fix_data=missing_provides) + + # Compose a set of all available namespaces. Explicitly omit goog + # because if you can call goog.require, you already have goog. + available_namespaces = (set(requires) | set(provides) | set(['goog']) | + provided_namespaces) + + # Check that we require everything we need. + missing_requires = set() + for namespace_variants in state.GetUsedNamespaces(): + # Namespace variants is a list of potential things to require. If we + # find we're missing one, we are lazy and choose to require the first + # in the sequence - which should be the namespace. + if not set(namespace_variants) & available_namespaces: + missing_requires.add(namespace_variants[0]) + + if missing_requires: + self._HandleError( + errors.MISSING_GOOG_REQUIRE, + 'Missing the following goog.require statements:\n' + + '\n'.join(map(lambda x: 'goog.require(\'%s\');' % x, + sorted(missing_requires))), + state.GetFirstToken(), position=Position.AtBeginning(), + fix_data=missing_requires) + + # Check that we don't require things we don't actually use. + namespace_variants = state.GetUsedNamespaces() + used_namespaces = set() + for a, b in namespace_variants: + used_namespaces.add(a) + used_namespaces.add(b) + + extra_requires = set() + for i in requires: + baseNamespace = i.split('.')[0] + if (i not in used_namespaces and + baseNamespace in FLAGS.closurized_namespaces and + i not in FLAGS.ignored_extra_namespaces): + extra_requires.add(i) + + if extra_requires: + self._HandleError( + errors.EXTRA_GOOG_REQUIRE, + 'The following goog.require statements appear unnecessary:\n' + + '\n'.join(map(lambda x: 'goog.require(\'%s\');' % x, + sorted(extra_requires))), + state.GetFirstToken(), position=Position.AtBeginning(), + fix_data=extra_requires) + diff --git a/node-v0.8.14/tools/closure_linter/closure_linter/javascriptstatetracker.py b/node-v0.8.14/tools/closure_linter/closure_linter/javascriptstatetracker.py new file mode 100755 index 0000000..9cce376 --- /dev/null +++ b/node-v0.8.14/tools/closure_linter/closure_linter/javascriptstatetracker.py @@ -0,0 +1,238 @@ +#!/usr/bin/env python +# +# Copyright 2008 The Closure Linter Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS-IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Parser for JavaScript files.""" + + + +from closure_linter import javascripttokens +from closure_linter import statetracker +from closure_linter import tokenutil + +# Shorthand +Type = javascripttokens.JavaScriptTokenType + + +class JsDocFlag(statetracker.DocFlag): + """Javascript doc flag object. + + Attribute: + flag_type: param, return, define, type, etc. + flag_token: The flag token. + type_start_token: The first token specifying the flag JS type, + including braces. + type_end_token: The last token specifying the flag JS type, + including braces. + type: The JavaScript type spec. + name_token: The token specifying the flag name. + name: The flag name + description_start_token: The first token in the description. + description_end_token: The end token in the description. + description: The description. + """ + + # Please keep these lists alphabetized. + + # Some projects use the following extensions to JsDoc. + # TODO(robbyw): determine which of these, if any, should be illegal. + EXTENDED_DOC = frozenset([ + 'class', 'code', 'desc', 'final', 'hidden', 'inheritDoc', 'link', + 'protected', 'notypecheck', 'throws']) + + LEGAL_DOC = EXTENDED_DOC | statetracker.DocFlag.LEGAL_DOC + + def __init__(self, flag_token): + """Creates the JsDocFlag object and attaches it to the given start token. + + Args: + flag_token: The starting token of the flag. + """ + statetracker.DocFlag.__init__(self, flag_token) + + +class JavaScriptStateTracker(statetracker.StateTracker): + """JavaScript state tracker. + + Inherits from the core EcmaScript StateTracker adding extra state tracking + functionality needed for JavaScript. + """ + + def __init__(self, closurized_namespaces=''): + """Initializes a JavaScript token stream state tracker. + + Args: + closurized_namespaces: An optional list of namespace prefixes used for + testing of goog.provide/require. + """ + statetracker.StateTracker.__init__(self, JsDocFlag) + self.__closurized_namespaces = closurized_namespaces + + def Reset(self): + """Resets the state tracker to prepare for processing a new page.""" + super(JavaScriptStateTracker, self).Reset() + + self.__goog_require_tokens = [] + self.__goog_provide_tokens = [] + self.__provided_namespaces = set() + self.__used_namespaces = [] + + def InTopLevel(self): + """Compute whether we are at the top level in the class. + + This function call is language specific. In some languages like + JavaScript, a function is top level if it is not inside any parenthesis. + In languages such as ActionScript, a function is top level if it is directly + within a class. + + Returns: + Whether we are at the top level in the class. + """ + return not self.InParentheses() + + def GetGoogRequireTokens(self): + """Returns list of require tokens.""" + return self.__goog_require_tokens + + def GetGoogProvideTokens(self): + """Returns list of provide tokens.""" + return self.__goog_provide_tokens + + def GetProvidedNamespaces(self): + """Returns list of provided namespaces.""" + return self.__provided_namespaces + + def GetUsedNamespaces(self): + """Returns list of used namespaces, is a list of sequences.""" + return self.__used_namespaces + + def GetBlockType(self, token): + """Determine the block type given a START_BLOCK token. + + Code blocks come after parameters, keywords like else, and closing parens. + + Args: + token: The current token. Can be assumed to be type START_BLOCK + Returns: + Code block type for current token. + """ + last_code = tokenutil.SearchExcept(token, Type.NON_CODE_TYPES, None, + True) + if last_code.type in (Type.END_PARAMETERS, Type.END_PAREN, + Type.KEYWORD) and not last_code.IsKeyword('return'): + return self.CODE + else: + return self.OBJECT_LITERAL + + def HandleToken(self, token, last_non_space_token): + """Handles the given token and updates state. + + Args: + token: The token to handle. + last_non_space_token: + """ + super(JavaScriptStateTracker, self).HandleToken(token, + last_non_space_token) + + if token.IsType(Type.IDENTIFIER): + if token.string == 'goog.require': + class_token = tokenutil.Search(token, Type.STRING_TEXT) + self.__goog_require_tokens.append(class_token) + + elif token.string == 'goog.provide': + class_token = tokenutil.Search(token, Type.STRING_TEXT) + self.__goog_provide_tokens.append(class_token) + + elif self.__closurized_namespaces: + self.__AddUsedNamespace(token.string) + if token.IsType(Type.SIMPLE_LVALUE) and not self.InFunction(): + identifier = token.values['identifier'] + + if self.__closurized_namespaces: + namespace = self.GetClosurizedNamespace(identifier) + if namespace and identifier == namespace: + self.__provided_namespaces.add(namespace) + if (self.__closurized_namespaces and + token.IsType(Type.DOC_FLAG) and + token.attached_object.flag_type == 'implements'): + # Interfaces should be goog.require'd. + doc_start = tokenutil.Search(token, Type.DOC_START_BRACE) + interface = tokenutil.Search(doc_start, Type.COMMENT) + self.__AddUsedNamespace(interface.string) + + def __AddUsedNamespace(self, identifier): + """Adds the namespace of an identifier to the list of used namespaces. + + Args: + identifier: An identifier which has been used. + """ + namespace = self.GetClosurizedNamespace(identifier) + + if namespace: + # We add token.string as a 'namespace' as it is something that could + # potentially be provided to satisfy this dependency. + self.__used_namespaces.append([namespace, identifier]) + + def GetClosurizedNamespace(self, identifier): + """Given an identifier, returns the namespace that identifier is from. + + Args: + identifier: The identifier to extract a namespace from. + + Returns: + The namespace the given identifier resides in, or None if one could not + be found. + """ + parts = identifier.split('.') + for part in parts: + if part.endswith('_'): + # Ignore private variables / inner classes. + return None + + if identifier.startswith('goog.global'): + # Ignore goog.global, since it is, by definition, global. + return None + + for namespace in self.__closurized_namespaces: + if identifier.startswith(namespace + '.'): + last_part = parts[-1] + if not last_part: + # TODO(robbyw): Handle this: it's a multi-line identifier. + return None + + if last_part in ('apply', 'inherits', 'call'): + # Calling one of Function's methods usually indicates use of a + # superclass. + parts.pop() + last_part = parts[-1] + + for i in xrange(1, len(parts)): + part = parts[i] + if part.isupper(): + # If an identifier is of the form foo.bar.BAZ.x or foo.bar.BAZ, + # the namespace is foo.bar. + return '.'.join(parts[:i]) + if part == 'prototype': + # If an identifier is of the form foo.bar.prototype.x, the + # namespace is foo.bar. + return '.'.join(parts[:i]) + + if last_part.isupper() or not last_part[0].isupper(): + # Strip off the last part of an enum or constant reference. + parts.pop() + + return '.'.join(parts) + + return None diff --git a/node-v0.8.14/tools/closure_linter/closure_linter/javascriptstatetracker_test.py b/node-v0.8.14/tools/closure_linter/closure_linter/javascriptstatetracker_test.py new file mode 100755 index 0000000..e4288b7 --- /dev/null +++ b/node-v0.8.14/tools/closure_linter/closure_linter/javascriptstatetracker_test.py @@ -0,0 +1,53 @@ +#!/usr/bin/env python +# +# Copyright 2010 The Closure Linter Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS-IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Unit tests for JavaScriptStateTracker.""" + + + +import unittest as googletest +from closure_linter import javascriptstatetracker + +class JavaScriptStateTrackerTest(googletest.TestCase): + + __test_cases = { + 'package.CONSTANT' : 'package', + 'package.methodName' : 'package', + 'package.subpackage.methodName' : 'package.subpackage', + 'package.ClassName.something' : 'package.ClassName', + 'package.ClassName.Enum.VALUE.methodName' : 'package.ClassName.Enum', + 'package.ClassName.CONSTANT' : 'package.ClassName', + 'package.ClassName.inherits' : 'package.ClassName', + 'package.ClassName.apply' : 'package.ClassName', + 'package.ClassName.methodName.apply' : 'package.ClassName', + 'package.ClassName.methodName.call' : 'package.ClassName', + 'package.ClassName.prototype.methodName' : 'package.ClassName', + 'package.ClassName.privateMethod_' : None, + 'package.ClassName.prototype.methodName.apply' : 'package.ClassName' + } + + def testGetClosurizedNamespace(self): + stateTracker = javascriptstatetracker.JavaScriptStateTracker(['package']) + for identifier, expected_namespace in self.__test_cases.items(): + actual_namespace = stateTracker.GetClosurizedNamespace(identifier) + self.assertEqual(expected_namespace, actual_namespace, + 'expected namespace "' + str(expected_namespace) + + '" for identifier "' + str(identifier) + '" but was "' + + str(actual_namespace) + '"') + +if __name__ == '__main__': + googletest.main() + diff --git a/node-v0.8.14/tools/closure_linter/closure_linter/javascripttokenizer.py b/node-v0.8.14/tools/closure_linter/closure_linter/javascripttokenizer.py new file mode 100755 index 0000000..097d3fd --- /dev/null +++ b/node-v0.8.14/tools/closure_linter/closure_linter/javascripttokenizer.py @@ -0,0 +1,365 @@ +#!/usr/bin/env python +# +# Copyright 2007 The Closure Linter Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS-IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Regular expression based JavaScript parsing classes.""" + +__author__ = ('robbyw@google.com (Robert Walker)', + 'ajp@google.com (Andy Perelson)') + +import copy +import re + +from closure_linter import javascripttokens +from closure_linter.common import matcher +from closure_linter.common import tokenizer + +# Shorthand +Type = javascripttokens.JavaScriptTokenType +Matcher = matcher.Matcher + + +class JavaScriptModes(object): + """Enumeration of the different matcher modes used for JavaScript.""" + TEXT_MODE = 'text' + SINGLE_QUOTE_STRING_MODE = 'single_quote_string' + DOUBLE_QUOTE_STRING_MODE = 'double_quote_string' + BLOCK_COMMENT_MODE = 'block_comment' + DOC_COMMENT_MODE = 'doc_comment' + DOC_COMMENT_LEX_SPACES_MODE = 'doc_comment_spaces' + LINE_COMMENT_MODE = 'line_comment' + PARAMETER_MODE = 'parameter' + FUNCTION_MODE = 'function' + + +class JavaScriptTokenizer(tokenizer.Tokenizer): + """JavaScript tokenizer. + + Convert JavaScript code in to an array of tokens. + """ + + # Useful patterns for JavaScript parsing. + IDENTIFIER_CHAR = r'A-Za-z0-9_$.'; + + # Number patterns based on: + # http://www.mozilla.org/js/language/js20-2000-07/formal/lexer-grammar.html + MANTISSA = r""" + (\d+(?!\.)) | # Matches '10' + (\d+\.(?!\d)) | # Matches '10.' + (\d*\.\d+) # Matches '.5' or '10.5' + """ + DECIMAL_LITERAL = r'(%s)([eE][-+]?\d+)?' % MANTISSA + HEX_LITERAL = r'0[xX][0-9a-fA-F]+' + NUMBER = re.compile(r""" + ((%s)|(%s)) + """ % (HEX_LITERAL, DECIMAL_LITERAL), re.VERBOSE) + + # Strings come in three parts - first we match the start of the string, then + # the contents, then the end. The contents consist of any character except a + # backslash or end of string, or a backslash followed by any character, or a + # backslash followed by end of line to support correct parsing of multi-line + # strings. + SINGLE_QUOTE = re.compile(r"'") + SINGLE_QUOTE_TEXT = re.compile(r"([^'\\]|\\(.|$))+") + DOUBLE_QUOTE = re.compile(r'"') + DOUBLE_QUOTE_TEXT = re.compile(r'([^"\\]|\\(.|$))+') + + START_SINGLE_LINE_COMMENT = re.compile(r'//') + END_OF_LINE_SINGLE_LINE_COMMENT = re.compile(r'//$') + + START_DOC_COMMENT = re.compile(r'/\*\*') + START_BLOCK_COMMENT = re.compile(r'/\*') + END_BLOCK_COMMENT = re.compile(r'\*/') + BLOCK_COMMENT_TEXT = re.compile(r'([^*]|\*(?!/))+') + + # Comment text is anything that we are not going to parse into another special + # token like (inline) flags or end comments. Complicated regex to match + # most normal characters, and '*', '{', '}', and '@' when we are sure that + # it is safe. Expression [^*{\s]@ must come first, or the other options will + # match everything before @, and we won't match @'s that aren't part of flags + # like in email addresses in the @author tag. + DOC_COMMENT_TEXT = re.compile(r'([^*{}\s]@|[^*{}@]|\*(?!/))+') + DOC_COMMENT_NO_SPACES_TEXT = re.compile(r'([^*{}\s]@|[^*{}@\s]|\*(?!/))+') + + # Match the prefix ' * ' that starts every line of jsdoc. Want to include + # spaces after the '*', but nothing else that occurs after a '*', and don't + # want to match the '*' in '*/'. + DOC_PREFIX = re.compile(r'\s*\*(\s+|(?!/))') + + START_BLOCK = re.compile('{') + END_BLOCK = re.compile('}') + + REGEX_CHARACTER_CLASS = r""" + \[ # Opening bracket + ([^\]\\]|\\.)* # Anything but a ] or \, + # or a backslash followed by anything + \] # Closing bracket + """ + # We ensure the regex is followed by one of the above tokens to avoid + # incorrectly parsing something like x / y / z as x REGEX(/ y /) z + POST_REGEX_LIST = [ + ';', ',', r'\.', r'\)', r'\]', '$', r'\/\/', r'\/\*', ':', '}'] + + REGEX = re.compile(r""" + / # opening slash + (?!\*) # not the start of a comment + (\\.|[^\[\/\\]|(%s))* # a backslash followed by anything, + # or anything but a / or [ or \, + # or a character class + / # closing slash + [gimsx]* # optional modifiers + (?=\s*(%s)) + """ % (REGEX_CHARACTER_CLASS, '|'.join(POST_REGEX_LIST)), + re.VERBOSE) + + ANYTHING = re.compile(r'.*') + PARAMETERS = re.compile(r'[^\)]+') + CLOSING_PAREN_WITH_SPACE = re.compile(r'\)\s*') + + FUNCTION_DECLARATION = re.compile(r'\bfunction\b') + + OPENING_PAREN = re.compile(r'\(') + CLOSING_PAREN = re.compile(r'\)') + + OPENING_BRACKET = re.compile(r'\[') + CLOSING_BRACKET = re.compile(r'\]') + + # We omit these JS keywords from the list: + # function - covered by FUNCTION_DECLARATION. + # delete, in, instanceof, new, typeof - included as operators. + # this - included in identifiers. + # null, undefined - not included, should go in some "special constant" list. + KEYWORD_LIST = ['break', 'case', 'catch', 'continue', 'default', 'do', 'else', + 'finally', 'for', 'if', 'return', 'switch', 'throw', 'try', 'var', + 'while', 'with'] + # Match a keyword string followed by a non-identifier character in order to + # not match something like doSomething as do + Something. + KEYWORD = re.compile('(%s)((?=[^%s])|$)' % ( + '|'.join(KEYWORD_LIST), IDENTIFIER_CHAR)) + + # List of regular expressions to match as operators. Some notes: for our + # purposes, the comma behaves similarly enough to a normal operator that we + # include it here. r'\bin\b' actually matches 'in' surrounded by boundary + # characters - this may not match some very esoteric uses of the in operator. + # Operators that are subsets of larger operators must come later in this list + # for proper matching, e.g., '>>' must come AFTER '>>>'. + OPERATOR_LIST = [',', r'\+\+', '===', '!==', '>>>=', '>>>', '==', '>=', '<=', + '!=', '<<=', '>>=', '<<', '>>', '>', '<', r'\+=', r'\+', + '--', '\^=', '-=', '-', '/=', '/', r'\*=', r'\*', '%=', '%', + '&&', r'\|\|', '&=', '&', r'\|=', r'\|', '=', '!', ':', '\?', + r'\bdelete\b', r'\bin\b', r'\binstanceof\b', r'\bnew\b', + r'\btypeof\b', r'\bvoid\b'] + OPERATOR = re.compile('|'.join(OPERATOR_LIST)) + + WHITESPACE = re.compile(r'\s+') + SEMICOLON = re.compile(r';') + # Technically JavaScript identifiers can't contain '.', but we treat a set of + # nested identifiers as a single identifier. + NESTED_IDENTIFIER = r'[a-zA-Z_$][%s.]*' % IDENTIFIER_CHAR + IDENTIFIER = re.compile(NESTED_IDENTIFIER) + + SIMPLE_LVALUE = re.compile(r""" + (?P%s) # a valid identifier + (?=\s* # optional whitespace + \= # look ahead to equal sign + (?!=)) # not follwed by equal + """ % NESTED_IDENTIFIER, re.VERBOSE) + + # A doc flag is a @ sign followed by non-space characters that appears at the + # beginning of the line, after whitespace, or after a '{'. The look-behind + # check is necessary to not match someone@google.com as a flag. + DOC_FLAG = re.compile(r'(^|(?<=\s))@(?P[a-zA-Z]+)') + # To properly parse parameter names, we need to tokenize whitespace into a + # token. + DOC_FLAG_LEX_SPACES = re.compile(r'(^|(?<=\s))@(?P%s)\b' % + '|'.join(['param'])) + + DOC_INLINE_FLAG = re.compile(r'(?<={)@(?P[a-zA-Z]+)') + + # Star followed by non-slash, i.e a star that does not end a comment. + # This is used for TYPE_GROUP below. + SAFE_STAR = r'(\*(?!/))' + + COMMON_DOC_MATCHERS = [ + # Find the end of the comment. + Matcher(END_BLOCK_COMMENT, Type.END_DOC_COMMENT, + JavaScriptModes.TEXT_MODE), + + # Tokenize documented flags like @private. + Matcher(DOC_INLINE_FLAG, Type.DOC_INLINE_FLAG), + Matcher(DOC_FLAG_LEX_SPACES, Type.DOC_FLAG, + JavaScriptModes.DOC_COMMENT_LEX_SPACES_MODE), + Matcher(DOC_FLAG, Type.DOC_FLAG), + + # Tokenize braces so we can find types. + Matcher(START_BLOCK, Type.DOC_START_BRACE), + Matcher(END_BLOCK, Type.DOC_END_BRACE), + Matcher(DOC_PREFIX, Type.DOC_PREFIX, None, True)] + + + # The token matcher groups work as follows: it is an list of Matcher objects. + # The matchers will be tried in this order, and the first to match will be + # returned. Hence the order is important because the matchers that come first + # overrule the matchers that come later. + JAVASCRIPT_MATCHERS = { + # Matchers for basic text mode. + JavaScriptModes.TEXT_MODE: [ + # Check a big group - strings, starting comments, and regexes - all + # of which could be intertwined. 'string with /regex/', + # /regex with 'string'/, /* comment with /regex/ and string */ (and so on) + Matcher(START_DOC_COMMENT, Type.START_DOC_COMMENT, + JavaScriptModes.DOC_COMMENT_MODE), + Matcher(START_BLOCK_COMMENT, Type.START_BLOCK_COMMENT, + JavaScriptModes.BLOCK_COMMENT_MODE), + Matcher(END_OF_LINE_SINGLE_LINE_COMMENT, + Type.START_SINGLE_LINE_COMMENT), + Matcher(START_SINGLE_LINE_COMMENT, Type.START_SINGLE_LINE_COMMENT, + JavaScriptModes.LINE_COMMENT_MODE), + Matcher(SINGLE_QUOTE, Type.SINGLE_QUOTE_STRING_START, + JavaScriptModes.SINGLE_QUOTE_STRING_MODE), + Matcher(DOUBLE_QUOTE, Type.DOUBLE_QUOTE_STRING_START, + JavaScriptModes.DOUBLE_QUOTE_STRING_MODE), + Matcher(REGEX, Type.REGEX), + + # Next we check for start blocks appearing outside any of the items above. + Matcher(START_BLOCK, Type.START_BLOCK), + Matcher(END_BLOCK, Type.END_BLOCK), + + # Then we search for function declarations. + Matcher(FUNCTION_DECLARATION, Type.FUNCTION_DECLARATION, + JavaScriptModes.FUNCTION_MODE), + + # Next, we convert non-function related parens to tokens. + Matcher(OPENING_PAREN, Type.START_PAREN), + Matcher(CLOSING_PAREN, Type.END_PAREN), + + # Next, we convert brackets to tokens. + Matcher(OPENING_BRACKET, Type.START_BRACKET), + Matcher(CLOSING_BRACKET, Type.END_BRACKET), + + # Find numbers. This has to happen before operators because scientific + # notation numbers can have + and - in them. + Matcher(NUMBER, Type.NUMBER), + + # Find operators and simple assignments + Matcher(SIMPLE_LVALUE, Type.SIMPLE_LVALUE), + Matcher(OPERATOR, Type.OPERATOR), + + # Find key words and whitespace + Matcher(KEYWORD, Type.KEYWORD), + Matcher(WHITESPACE, Type.WHITESPACE), + + # Find identifiers + Matcher(IDENTIFIER, Type.IDENTIFIER), + + # Finally, we convert semicolons to tokens. + Matcher(SEMICOLON, Type.SEMICOLON)], + + + # Matchers for single quote strings. + JavaScriptModes.SINGLE_QUOTE_STRING_MODE: [ + Matcher(SINGLE_QUOTE_TEXT, Type.STRING_TEXT), + Matcher(SINGLE_QUOTE, Type.SINGLE_QUOTE_STRING_END, + JavaScriptModes.TEXT_MODE)], + + + # Matchers for double quote strings. + JavaScriptModes.DOUBLE_QUOTE_STRING_MODE: [ + Matcher(DOUBLE_QUOTE_TEXT, Type.STRING_TEXT), + Matcher(DOUBLE_QUOTE, Type.DOUBLE_QUOTE_STRING_END, + JavaScriptModes.TEXT_MODE)], + + + # Matchers for block comments. + JavaScriptModes.BLOCK_COMMENT_MODE: [ + # First we check for exiting a block comment. + Matcher(END_BLOCK_COMMENT, Type.END_BLOCK_COMMENT, + JavaScriptModes.TEXT_MODE), + + # Match non-comment-ending text.. + Matcher(BLOCK_COMMENT_TEXT, Type.COMMENT)], + + + # Matchers for doc comments. + JavaScriptModes.DOC_COMMENT_MODE: COMMON_DOC_MATCHERS + [ + Matcher(DOC_COMMENT_TEXT, Type.COMMENT)], + + JavaScriptModes.DOC_COMMENT_LEX_SPACES_MODE: COMMON_DOC_MATCHERS + [ + Matcher(WHITESPACE, Type.COMMENT), + Matcher(DOC_COMMENT_NO_SPACES_TEXT, Type.COMMENT)], + + # Matchers for single line comments. + JavaScriptModes.LINE_COMMENT_MODE: [ + # We greedy match until the end of the line in line comment mode. + Matcher(ANYTHING, Type.COMMENT, JavaScriptModes.TEXT_MODE)], + + + # Matchers for code after the function keyword. + JavaScriptModes.FUNCTION_MODE: [ + # Must match open paren before anything else and move into parameter mode, + # otherwise everything inside the parameter list is parsed incorrectly. + Matcher(OPENING_PAREN, Type.START_PARAMETERS, + JavaScriptModes.PARAMETER_MODE), + Matcher(WHITESPACE, Type.WHITESPACE), + Matcher(IDENTIFIER, Type.FUNCTION_NAME)], + + + # Matchers for function parameters + JavaScriptModes.PARAMETER_MODE: [ + # When in function parameter mode, a closing paren is treated specially. + # Everything else is treated as lines of parameters. + Matcher(CLOSING_PAREN_WITH_SPACE, Type.END_PARAMETERS, + JavaScriptModes.TEXT_MODE), + Matcher(PARAMETERS, Type.PARAMETERS, JavaScriptModes.PARAMETER_MODE)]} + + + # When text is not matched, it is given this default type based on mode. + # If unspecified in this map, the default default is Type.NORMAL. + JAVASCRIPT_DEFAULT_TYPES = { + JavaScriptModes.DOC_COMMENT_MODE: Type.COMMENT, + JavaScriptModes.DOC_COMMENT_LEX_SPACES_MODE: Type.COMMENT + } + + def __init__(self, parse_js_doc = True): + """Create a tokenizer object. + + Args: + parse_js_doc: Whether to do detailed parsing of javascript doc comments, + or simply treat them as normal comments. Defaults to parsing JsDoc. + """ + matchers = self.JAVASCRIPT_MATCHERS + if not parse_js_doc: + # Make a copy so the original doesn't get modified. + matchers = copy.deepcopy(matchers) + matchers[JavaScriptModes.DOC_COMMENT_MODE] = matchers[ + JavaScriptModes.BLOCK_COMMENT_MODE] + + tokenizer.Tokenizer.__init__(self, JavaScriptModes.TEXT_MODE, matchers, + self.JAVASCRIPT_DEFAULT_TYPES) + + def _CreateToken(self, string, token_type, line, line_number, values=None): + """Creates a new JavaScriptToken object. + + Args: + string: The string of input the token contains. + token_type: The type of token. + line: The text of the line this token is in. + line_number: The line number of the token. + values: A dict of named values within the token. For instance, a + function declaration may have a value called 'name' which captures the + name of the function. + """ + return javascripttokens.JavaScriptToken(string, token_type, line, + line_number, values) diff --git a/node-v0.8.14/tools/closure_linter/closure_linter/javascripttokens.py b/node-v0.8.14/tools/closure_linter/closure_linter/javascripttokens.py new file mode 100755 index 0000000..f46d4e1 --- /dev/null +++ b/node-v0.8.14/tools/closure_linter/closure_linter/javascripttokens.py @@ -0,0 +1,147 @@ +#!/usr/bin/env python +# +# Copyright 2008 The Closure Linter Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS-IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Classes to represent JavaScript tokens.""" + +__author__ = ('robbyw@google.com (Robert Walker)', + 'ajp@google.com (Andy Perelson)') + +from closure_linter.common import tokens + +class JavaScriptTokenType(tokens.TokenType): + """Enumeration of JavaScript token types, and useful sets of token types.""" + NUMBER = 'number' + START_SINGLE_LINE_COMMENT = '//' + START_BLOCK_COMMENT = '/*' + START_DOC_COMMENT = '/**' + END_BLOCK_COMMENT = '*/' + END_DOC_COMMENT = 'doc */' + COMMENT = 'comment' + SINGLE_QUOTE_STRING_START = "'string" + SINGLE_QUOTE_STRING_END = "string'" + DOUBLE_QUOTE_STRING_START = '"string' + DOUBLE_QUOTE_STRING_END = 'string"' + STRING_TEXT = 'string' + START_BLOCK = '{' + END_BLOCK = '}' + START_PAREN = '(' + END_PAREN = ')' + START_BRACKET = '[' + END_BRACKET = ']' + REGEX = '/regex/' + FUNCTION_DECLARATION = 'function(...)' + FUNCTION_NAME = 'function functionName(...)' + START_PARAMETERS = 'startparams(' + PARAMETERS = 'pa,ra,ms' + END_PARAMETERS = ')endparams' + SEMICOLON = ';' + DOC_FLAG = '@flag' + DOC_INLINE_FLAG = '{@flag ...}' + DOC_START_BRACE = 'doc {' + DOC_END_BRACE = 'doc }' + DOC_PREFIX = 'comment prefix: * ' + SIMPLE_LVALUE = 'lvalue=' + KEYWORD = 'keyword' + OPERATOR = 'operator' + IDENTIFIER = 'identifier' + + STRING_TYPES = frozenset([ + SINGLE_QUOTE_STRING_START, SINGLE_QUOTE_STRING_END, + DOUBLE_QUOTE_STRING_START, DOUBLE_QUOTE_STRING_END, STRING_TEXT]) + + COMMENT_TYPES = frozenset([START_SINGLE_LINE_COMMENT, COMMENT, + START_BLOCK_COMMENT, START_DOC_COMMENT, + END_BLOCK_COMMENT, END_DOC_COMMENT, + DOC_START_BRACE, DOC_END_BRACE, + DOC_FLAG, DOC_INLINE_FLAG, DOC_PREFIX]) + + FLAG_DESCRIPTION_TYPES = frozenset([ + DOC_INLINE_FLAG, COMMENT, DOC_START_BRACE, DOC_END_BRACE]) + + FLAG_ENDING_TYPES = frozenset([DOC_FLAG, END_DOC_COMMENT]) + + NON_CODE_TYPES = COMMENT_TYPES | frozenset([ + tokens.TokenType.WHITESPACE, tokens.TokenType.BLANK_LINE]) + + UNARY_OPERATORS = ['!', 'new', 'delete', 'typeof', 'void'] + + UNARY_OK_OPERATORS = ['--', '++', '-', '+'] + UNARY_OPERATORS + + UNARY_POST_OPERATORS = ['--', '++'] + + # An expression ender is any token that can end an object - i.e. we could have + # x.y or [1, 2], or (10 + 9) or {a: 10}. + EXPRESSION_ENDER_TYPES = [tokens.TokenType.NORMAL, IDENTIFIER, NUMBER, + SIMPLE_LVALUE, END_BRACKET, END_PAREN, END_BLOCK, + SINGLE_QUOTE_STRING_END, DOUBLE_QUOTE_STRING_END] + + +class JavaScriptToken(tokens.Token): + """JavaScript token subclass of Token, provides extra instance checks. + + The following token types have data in attached_object: + - All JsDoc flags: a parser.JsDocFlag object. + """ + + def IsKeyword(self, keyword): + """Tests if this token is the given keyword. + + Args: + keyword: The keyword to compare to. + + Returns: + True if this token is a keyword token with the given name. + """ + return self.type == JavaScriptTokenType.KEYWORD and self.string == keyword + + def IsOperator(self, operator): + """Tests if this token is the given operator. + + Args: + operator: The operator to compare to. + + Returns: + True if this token is a operator token with the given name. + """ + return self.type == JavaScriptTokenType.OPERATOR and self.string == operator + + def IsAssignment(self): + """Tests if this token is an assignment operator. + + Returns: + True if this token is an assignment operator. + """ + return (self.type == JavaScriptTokenType.OPERATOR and + self.string.endswith('=') and + self.string not in ('==', '!=', '>=', '<=', '===', '!==')) + + def IsComment(self): + """Tests if this token is any part of a comment. + + Returns: + True if this token is any part of a comment. + """ + return self.type in JavaScriptTokenType.COMMENT_TYPES + + def IsCode(self): + """Tests if this token is code, as opposed to a comment or whitespace.""" + return self.type not in JavaScriptTokenType.NON_CODE_TYPES + + def __repr__(self): + return '' % (self.line_number, + self.type, self.string, + self.values, + self.metadata) diff --git a/node-v0.8.14/tools/closure_linter/closure_linter/statetracker.py b/node-v0.8.14/tools/closure_linter/closure_linter/statetracker.py new file mode 100755 index 0000000..5630c17 --- /dev/null +++ b/node-v0.8.14/tools/closure_linter/closure_linter/statetracker.py @@ -0,0 +1,964 @@ +#!/usr/bin/env python +# +# Copyright 2007 The Closure Linter Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS-IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Light weight EcmaScript state tracker that reads tokens and tracks state.""" + +__author__ = ('robbyw@google.com (Robert Walker)', + 'ajp@google.com (Andy Perelson)') + +import re + +from closure_linter import javascripttokenizer +from closure_linter import javascripttokens +from closure_linter import tokenutil + +# Shorthand +Type = javascripttokens.JavaScriptTokenType + + +class DocFlag(object): + """Generic doc flag object. + + Attribute: + flag_type: param, return, define, type, etc. + flag_token: The flag token. + type_start_token: The first token specifying the flag type, + including braces. + type_end_token: The last token specifying the flag type, + including braces. + type: The type spec. + name_token: The token specifying the flag name. + name: The flag name + description_start_token: The first token in the description. + description_end_token: The end token in the description. + description: The description. + """ + + # Please keep these lists alphabetized. + + # The list of standard jsdoc tags is from + STANDARD_DOC = frozenset([ + 'author', + 'bug', + 'const', + 'constructor', + 'define', + 'deprecated', + 'enum', + 'export', + 'extends', + 'externs', + 'fileoverview', + 'implements', + 'implicitCast', + 'interface', + 'license', + 'noalias', + 'nocompile', + 'nosideeffects', + 'override', + 'owner', + 'param', + 'preserve', + 'private', + 'return', + 'see', + 'supported', + 'template', + 'this', + 'type', + 'typedef', + ]) + + ANNOTATION = frozenset(['preserveTry', 'suppress']) + + LEGAL_DOC = STANDARD_DOC | ANNOTATION + + # Includes all Closure Compiler @suppress types. + # Not all of these annotations are interpreted by Closure Linter. + SUPPRESS_TYPES = frozenset([ + 'accessControls', + 'checkRegExp', + 'checkTypes', + 'checkVars', + 'deprecated', + 'duplicate', + 'fileoverviewTags', + 'invalidCasts', + 'missingProperties', + 'nonStandardJsDocs', + 'strictModuleDepCheck', + 'undefinedVars', + 'underscore', + 'unknownDefines', + 'uselessCode', + 'visibility', + 'with']) + + HAS_DESCRIPTION = frozenset([ + 'define', 'deprecated', 'desc', 'fileoverview', 'license', 'param', + 'preserve', 'return', 'supported']) + + HAS_TYPE = frozenset([ + 'define', 'enum', 'extends', 'implements', 'param', 'return', 'type', + 'suppress']) + + TYPE_ONLY = frozenset(['enum', 'extends', 'implements', 'suppress', 'type']) + + HAS_NAME = frozenset(['param']) + + EMPTY_COMMENT_LINE = re.compile(r'^\s*\*?\s*$') + EMPTY_STRING = re.compile(r'^\s*$') + + def __init__(self, flag_token): + """Creates the DocFlag object and attaches it to the given start token. + + Args: + flag_token: The starting token of the flag. + """ + self.flag_token = flag_token + self.flag_type = flag_token.string.strip().lstrip('@') + + # Extract type, if applicable. + self.type = None + self.type_start_token = None + self.type_end_token = None + if self.flag_type in self.HAS_TYPE: + brace = tokenutil.SearchUntil(flag_token, [Type.DOC_START_BRACE], + Type.FLAG_ENDING_TYPES) + if brace: + end_token, contents = _GetMatchingEndBraceAndContents(brace) + self.type = contents + self.type_start_token = brace + self.type_end_token = end_token + elif (self.flag_type in self.TYPE_ONLY and + flag_token.next.type not in Type.FLAG_ENDING_TYPES): + self.type_start_token = flag_token.next + self.type_end_token, self.type = _GetEndTokenAndContents( + self.type_start_token) + if self.type is not None: + self.type = self.type.strip() + + # Extract name, if applicable. + self.name_token = None + self.name = None + if self.flag_type in self.HAS_NAME: + # Handle bad case, name could be immediately after flag token. + self.name_token = _GetNextIdentifierToken(flag_token) + + # Handle good case, if found token is after type start, look for + # identifier after type end, since types contain identifiers. + if (self.type and self.name_token and + tokenutil.Compare(self.name_token, self.type_start_token) > 0): + self.name_token = _GetNextIdentifierToken(self.type_end_token) + + if self.name_token: + self.name = self.name_token.string + + # Extract description, if applicable. + self.description_start_token = None + self.description_end_token = None + self.description = None + if self.flag_type in self.HAS_DESCRIPTION: + search_start_token = flag_token + if self.name_token and self.type_end_token: + if tokenutil.Compare(self.type_end_token, self.name_token) > 0: + search_start_token = self.type_end_token + else: + search_start_token = self.name_token + elif self.name_token: + search_start_token = self.name_token + elif self.type: + search_start_token = self.type_end_token + + interesting_token = tokenutil.Search(search_start_token, + Type.FLAG_DESCRIPTION_TYPES | Type.FLAG_ENDING_TYPES) + if interesting_token.type in Type.FLAG_DESCRIPTION_TYPES: + self.description_start_token = interesting_token + self.description_end_token, self.description = ( + _GetEndTokenAndContents(interesting_token)) + + +class DocComment(object): + """JavaScript doc comment object. + + Attributes: + ordered_params: Ordered list of parameters documented. + start_token: The token that starts the doc comment. + end_token: The token that ends the doc comment. + suppressions: Map of suppression type to the token that added it. + """ + def __init__(self, start_token): + """Create the doc comment object. + + Args: + start_token: The first token in the doc comment. + """ + self.__params = {} + self.ordered_params = [] + self.__flags = {} + self.start_token = start_token + self.end_token = None + self.suppressions = {} + self.invalidated = False + + def Invalidate(self): + """Indicate that the JSDoc is well-formed but we had problems parsing it. + + This is a short-circuiting mechanism so that we don't emit false + positives about well-formed doc comments just because we don't support + hot new syntaxes. + """ + self.invalidated = True + + def IsInvalidated(self): + """Test whether Invalidate() has been called.""" + return self.invalidated + + def AddParam(self, name, param_type): + """Add a new documented parameter. + + Args: + name: The name of the parameter to document. + param_type: The parameter's declared JavaScript type. + """ + self.ordered_params.append(name) + self.__params[name] = param_type + + def AddSuppression(self, token): + """Add a new error suppression flag. + + Args: + token: The suppression flag token. + """ + #TODO(user): Error if no braces + brace = tokenutil.SearchUntil(token, [Type.DOC_START_BRACE], + [Type.DOC_FLAG]) + if brace: + end_token, contents = _GetMatchingEndBraceAndContents(brace) + self.suppressions[contents] = token + + def AddFlag(self, flag): + """Add a new document flag. + + Args: + flag: DocFlag object. + """ + self.__flags[flag.flag_type] = flag + + def InheritsDocumentation(self): + """Test if the jsdoc implies documentation inheritance. + + Returns: + True if documentation may be pulled off the superclass. + """ + return (self.HasFlag('inheritDoc') or + (self.HasFlag('override') and + not self.HasFlag('return') and + not self.HasFlag('param'))) + + def HasFlag(self, flag_type): + """Test if the given flag has been set. + + Args: + flag_type: The type of the flag to check. + + Returns: + True if the flag is set. + """ + return flag_type in self.__flags + + def GetFlag(self, flag_type): + """Gets the last flag of the given type. + + Args: + flag_type: The type of the flag to get. + + Returns: + The last instance of the given flag type in this doc comment. + """ + return self.__flags[flag_type] + + def CompareParameters(self, params): + """Computes the edit distance and list from the function params to the docs. + + Uses the Levenshtein edit distance algorithm, with code modified from + http://en.wikibooks.org/wiki/Algorithm_implementation/Strings/Levenshtein_distance#Python + + Args: + params: The parameter list for the function declaration. + + Returns: + The edit distance, the edit list. + """ + source_len, target_len = len(self.ordered_params), len(params) + edit_lists = [[]] + distance = [[]] + for i in range(target_len+1): + edit_lists[0].append(['I'] * i) + distance[0].append(i) + + for j in range(1, source_len+1): + edit_lists.append([['D'] * j]) + distance.append([j]) + + for i in range(source_len): + for j in range(target_len): + cost = 1 + if self.ordered_params[i] == params[j]: + cost = 0 + + deletion = distance[i][j+1] + 1 + insertion = distance[i+1][j] + 1 + substitution = distance[i][j] + cost + + edit_list = None + best = None + if deletion <= insertion and deletion <= substitution: + # Deletion is best. + best = deletion + edit_list = list(edit_lists[i][j+1]) + edit_list.append('D') + + elif insertion <= substitution: + # Insertion is best. + best = insertion + edit_list = list(edit_lists[i+1][j]) + edit_list.append('I') + edit_lists[i+1].append(edit_list) + + else: + # Substitution is best. + best = substitution + edit_list = list(edit_lists[i][j]) + if cost: + edit_list.append('S') + else: + edit_list.append('=') + + edit_lists[i+1].append(edit_list) + distance[i+1].append(best) + + return distance[source_len][target_len], edit_lists[source_len][target_len] + + def __repr__(self): + """Returns a string representation of this object. + + Returns: + A string representation of this object. + """ + return '' % (str(self.__params), str(self.__flags)) + + +# +# Helper methods used by DocFlag and DocComment to parse out flag information. +# + + +def _GetMatchingEndBraceAndContents(start_brace): + """Returns the matching end brace and contents between the two braces. + + If any FLAG_ENDING_TYPE token is encountered before a matching end brace, then + that token is used as the matching ending token. Contents will have all + comment prefixes stripped out of them, and all comment prefixes in between the + start and end tokens will be split out into separate DOC_PREFIX tokens. + + Args: + start_brace: The DOC_START_BRACE token immediately before desired contents. + + Returns: + The matching ending token (DOC_END_BRACE or FLAG_ENDING_TYPE) and a string + of the contents between the matching tokens, minus any comment prefixes. + """ + open_count = 1 + close_count = 0 + contents = [] + + # We don't consider the start brace part of the type string. + token = start_brace.next + while open_count != close_count: + if token.type == Type.DOC_START_BRACE: + open_count += 1 + elif token.type == Type.DOC_END_BRACE: + close_count += 1 + + if token.type != Type.DOC_PREFIX: + contents.append(token.string) + + if token.type in Type.FLAG_ENDING_TYPES: + break + token = token.next + + #Don't include the end token (end brace, end doc comment, etc.) in type. + token = token.previous + contents = contents[:-1] + + return token, ''.join(contents) + + +def _GetNextIdentifierToken(start_token): + """Searches for and returns the first identifier at the beginning of a token. + + Searches each token after the start to see if it starts with an identifier. + If found, will split the token into at most 3 piecies: leading whitespace, + identifier, rest of token, returning the identifier token. If no identifier is + found returns None and changes no tokens. Search is abandoned when a + FLAG_ENDING_TYPE token is found. + + Args: + start_token: The token to start searching after. + + Returns: + The identifier token is found, None otherwise. + """ + token = start_token.next + + while token and not token.type in Type.FLAG_ENDING_TYPES: + match = javascripttokenizer.JavaScriptTokenizer.IDENTIFIER.match( + token.string) + if (match is not None and token.type == Type.COMMENT and + len(token.string) == len(match.group(0))): + return token + + token = token.next + + return None + + +def _GetEndTokenAndContents(start_token): + """Returns last content token and all contents before FLAG_ENDING_TYPE token. + + Comment prefixes are split into DOC_PREFIX tokens and stripped from the + returned contents. + + Args: + start_token: The token immediately before the first content token. + + Returns: + The last content token and a string of all contents including start and + end tokens, with comment prefixes stripped. + """ + iterator = start_token + last_line = iterator.line_number + last_token = None + contents = '' + while not iterator.type in Type.FLAG_ENDING_TYPES: + if (iterator.IsFirstInLine() and + DocFlag.EMPTY_COMMENT_LINE.match(iterator.line)): + # If we have a blank comment line, consider that an implicit + # ending of the description. This handles a case like: + # + # * @return {boolean} True + # * + # * Note: This is a sentence. + # + # The note is not part of the @return description, but there was + # no definitive ending token. Rather there was a line containing + # only a doc comment prefix or whitespace. + break + + if iterator.type in Type.FLAG_DESCRIPTION_TYPES: + contents += iterator.string + last_token = iterator + + iterator = iterator.next + if iterator.line_number != last_line: + contents += '\n' + last_line = iterator.line_number + + end_token = last_token + if DocFlag.EMPTY_STRING.match(contents): + contents = None + else: + # Strip trailing newline. + contents = contents[:-1] + + return end_token, contents + + +class Function(object): + """Data about a JavaScript function. + + Attributes: + block_depth: Block depth the function began at. + doc: The DocComment associated with the function. + has_return: If the function has a return value. + has_this: If the function references the 'this' object. + is_assigned: If the function is part of an assignment. + is_constructor: If the function is a constructor. + name: The name of the function, whether given in the function keyword or + as the lvalue the function is assigned to. + """ + + def __init__(self, block_depth, is_assigned, doc, name): + self.block_depth = block_depth + self.is_assigned = is_assigned + self.is_constructor = doc and doc.HasFlag('constructor') + self.is_interface = doc and doc.HasFlag('interface') + self.has_return = False + self.has_this = False + self.name = name + self.doc = doc + + +class StateTracker(object): + """EcmaScript state tracker. + + Tracks block depth, function names, etc. within an EcmaScript token stream. + """ + + OBJECT_LITERAL = 'o' + CODE = 'c' + + def __init__(self, doc_flag=DocFlag): + """Initializes a JavaScript token stream state tracker. + + Args: + doc_flag: An optional custom DocFlag used for validating + documentation flags. + """ + self._doc_flag = doc_flag + self.Reset() + + def Reset(self): + """Resets the state tracker to prepare for processing a new page.""" + self._block_depth = 0 + self._is_block_close = False + self._paren_depth = 0 + self._functions = [] + self._functions_by_name = {} + self._last_comment = None + self._doc_comment = None + self._cumulative_params = None + self._block_types = [] + self._last_non_space_token = None + self._last_line = None + self._first_token = None + self._documented_identifiers = set() + + def InFunction(self): + """Returns true if the current token is within a function. + + Returns: + True if the current token is within a function. + """ + return bool(self._functions) + + def InConstructor(self): + """Returns true if the current token is within a constructor. + + Returns: + True if the current token is within a constructor. + """ + return self.InFunction() and self._functions[-1].is_constructor + + def InInterfaceMethod(self): + """Returns true if the current token is within an interface method. + + Returns: + True if the current token is within an interface method. + """ + if self.InFunction(): + if self._functions[-1].is_interface: + return True + else: + name = self._functions[-1].name + prototype_index = name.find('.prototype.') + if prototype_index != -1: + class_function_name = name[0:prototype_index] + if (class_function_name in self._functions_by_name and + self._functions_by_name[class_function_name].is_interface): + return True + + return False + + def InTopLevelFunction(self): + """Returns true if the current token is within a top level function. + + Returns: + True if the current token is within a top level function. + """ + return len(self._functions) == 1 and self.InTopLevel() + + def InAssignedFunction(self): + """Returns true if the current token is within a function variable. + + Returns: + True if if the current token is within a function variable + """ + return self.InFunction() and self._functions[-1].is_assigned + + def IsFunctionOpen(self): + """Returns true if the current token is a function block open. + + Returns: + True if the current token is a function block open. + """ + return (self._functions and + self._functions[-1].block_depth == self._block_depth - 1) + + def IsFunctionClose(self): + """Returns true if the current token is a function block close. + + Returns: + True if the current token is a function block close. + """ + return (self._functions and + self._functions[-1].block_depth == self._block_depth) + + def InBlock(self): + """Returns true if the current token is within a block. + + Returns: + True if the current token is within a block. + """ + return bool(self._block_depth) + + def IsBlockClose(self): + """Returns true if the current token is a block close. + + Returns: + True if the current token is a block close. + """ + return self._is_block_close + + def InObjectLiteral(self): + """Returns true if the current token is within an object literal. + + Returns: + True if the current token is within an object literal. + """ + return self._block_depth and self._block_types[-1] == self.OBJECT_LITERAL + + def InObjectLiteralDescendant(self): + """Returns true if the current token has an object literal ancestor. + + Returns: + True if the current token has an object literal ancestor. + """ + return self.OBJECT_LITERAL in self._block_types + + def InParentheses(self): + """Returns true if the current token is within parentheses. + + Returns: + True if the current token is within parentheses. + """ + return bool(self._paren_depth) + + def InTopLevel(self): + """Whether we are at the top level in the class. + + This function call is language specific. In some languages like + JavaScript, a function is top level if it is not inside any parenthesis. + In languages such as ActionScript, a function is top level if it is directly + within a class. + """ + raise TypeError('Abstract method InTopLevel not implemented') + + def GetBlockType(self, token): + """Determine the block type given a START_BLOCK token. + + Code blocks come after parameters, keywords like else, and closing parens. + + Args: + token: The current token. Can be assumed to be type START_BLOCK. + Returns: + Code block type for current token. + """ + raise TypeError('Abstract method GetBlockType not implemented') + + def GetParams(self): + """Returns the accumulated input params as an array. + + In some EcmasSript languages, input params are specified like + (param:Type, param2:Type2, ...) + in other they are specified just as + (param, param2) + We handle both formats for specifying parameters here and leave + it to the compilers for each language to detect compile errors. + This allows more code to be reused between lint checkers for various + EcmaScript languages. + + Returns: + The accumulated input params as an array. + """ + params = [] + if self._cumulative_params: + params = re.compile(r'\s+').sub('', self._cumulative_params).split(',') + # Strip out the type from parameters of the form name:Type. + params = map(lambda param: param.split(':')[0], params) + + return params + + def GetLastComment(self): + """Return the last plain comment that could be used as documentation. + + Returns: + The last plain comment that could be used as documentation. + """ + return self._last_comment + + def GetDocComment(self): + """Return the most recent applicable documentation comment. + + Returns: + The last applicable documentation comment. + """ + return self._doc_comment + + def HasDocComment(self, identifier): + """Returns whether the identifier has been documented yet. + + Args: + identifier: The identifier. + + Returns: + Whether the identifier has been documented yet. + """ + return identifier in self._documented_identifiers + + def InDocComment(self): + """Returns whether the current token is in a doc comment. + + Returns: + Whether the current token is in a doc comment. + """ + return self._doc_comment and self._doc_comment.end_token is None + + def GetDocFlag(self): + """Returns the current documentation flags. + + Returns: + The current documentation flags. + """ + return self._doc_flag + + def IsTypeToken(self, t): + if self.InDocComment() and t.type not in (Type.START_DOC_COMMENT, + Type.DOC_FLAG, Type.DOC_INLINE_FLAG, Type.DOC_PREFIX): + f = tokenutil.SearchUntil(t, [Type.DOC_FLAG], [Type.START_DOC_COMMENT], + None, True) + if f and f.attached_object.type_start_token is not None: + return (tokenutil.Compare(t, f.attached_object.type_start_token) > 0 and + tokenutil.Compare(t, f.attached_object.type_end_token) < 0) + return False + + def GetFunction(self): + """Return the function the current code block is a part of. + + Returns: + The current Function object. + """ + if self._functions: + return self._functions[-1] + + def GetBlockDepth(self): + """Return the block depth. + + Returns: + The current block depth. + """ + return self._block_depth + + def GetLastNonSpaceToken(self): + """Return the last non whitespace token.""" + return self._last_non_space_token + + def GetLastLine(self): + """Return the last line.""" + return self._last_line + + def GetFirstToken(self): + """Return the very first token in the file.""" + return self._first_token + + def HandleToken(self, token, last_non_space_token): + """Handles the given token and updates state. + + Args: + token: The token to handle. + last_non_space_token: + """ + self._is_block_close = False + + if not self._first_token: + self._first_token = token + + # Track block depth. + type = token.type + if type == Type.START_BLOCK: + self._block_depth += 1 + + # Subclasses need to handle block start very differently because + # whether a block is a CODE or OBJECT_LITERAL block varies significantly + # by language. + self._block_types.append(self.GetBlockType(token)) + + # Track block depth. + elif type == Type.END_BLOCK: + self._is_block_close = not self.InObjectLiteral() + self._block_depth -= 1 + self._block_types.pop() + + # Track parentheses depth. + elif type == Type.START_PAREN: + self._paren_depth += 1 + + # Track parentheses depth. + elif type == Type.END_PAREN: + self._paren_depth -= 1 + + elif type == Type.COMMENT: + self._last_comment = token.string + + elif type == Type.START_DOC_COMMENT: + self._last_comment = None + self._doc_comment = DocComment(token) + + elif type == Type.END_DOC_COMMENT: + self._doc_comment.end_token = token + + elif type in (Type.DOC_FLAG, Type.DOC_INLINE_FLAG): + flag = self._doc_flag(token) + token.attached_object = flag + self._doc_comment.AddFlag(flag) + + if flag.flag_type == 'param' and flag.name: + self._doc_comment.AddParam(flag.name, flag.type) + elif flag.flag_type == 'suppress': + self._doc_comment.AddSuppression(token) + + elif type == Type.FUNCTION_DECLARATION: + last_code = tokenutil.SearchExcept(token, Type.NON_CODE_TYPES, None, + True) + doc = None + # Only functions outside of parens are eligible for documentation. + if not self._paren_depth: + doc = self._doc_comment + + name = '' + is_assigned = last_code and (last_code.IsOperator('=') or + last_code.IsOperator('||') or last_code.IsOperator('&&') or + (last_code.IsOperator(':') and not self.InObjectLiteral())) + if is_assigned: + # TODO(robbyw): This breaks for x[2] = ... + # Must use loop to find full function name in the case of line-wrapped + # declarations (bug 1220601) like: + # my.function.foo. + # bar = function() ... + identifier = tokenutil.Search(last_code, Type.SIMPLE_LVALUE, None, True) + while identifier and identifier.type in ( + Type.IDENTIFIER, Type.SIMPLE_LVALUE): + name = identifier.string + name + # Traverse behind us, skipping whitespace and comments. + while True: + identifier = identifier.previous + if not identifier or not identifier.type in Type.NON_CODE_TYPES: + break + + else: + next_token = tokenutil.SearchExcept(token, Type.NON_CODE_TYPES) + while next_token and next_token.IsType(Type.FUNCTION_NAME): + name += next_token.string + next_token = tokenutil.Search(next_token, Type.FUNCTION_NAME, 2) + + function = Function(self._block_depth, is_assigned, doc, name) + self._functions.append(function) + self._functions_by_name[name] = function + + elif type == Type.START_PARAMETERS: + self._cumulative_params = '' + + elif type == Type.PARAMETERS: + self._cumulative_params += token.string + + elif type == Type.KEYWORD and token.string == 'return': + next_token = tokenutil.SearchExcept(token, Type.NON_CODE_TYPES) + if not next_token.IsType(Type.SEMICOLON): + function = self.GetFunction() + if function: + function.has_return = True + + elif type == Type.SIMPLE_LVALUE: + identifier = token.values['identifier'] + jsdoc = self.GetDocComment() + if jsdoc: + self._documented_identifiers.add(identifier) + + self._HandleIdentifier(identifier, True) + + elif type == Type.IDENTIFIER: + self._HandleIdentifier(token.string, False) + + # Detect documented non-assignments. + next_token = tokenutil.SearchExcept(token, Type.NON_CODE_TYPES) + if next_token.IsType(Type.SEMICOLON): + if (self._last_non_space_token and + self._last_non_space_token.IsType(Type.END_DOC_COMMENT)): + self._documented_identifiers.add(token.string) + + def _HandleIdentifier(self, identifier, is_assignment): + """Process the given identifier. + + Currently checks if it references 'this' and annotates the function + accordingly. + + Args: + identifier: The identifer to process. + is_assignment: Whether the identifer is being written to. + """ + if identifier == 'this' or identifier.startswith('this.'): + function = self.GetFunction() + if function: + function.has_this = True + + + def HandleAfterToken(self, token): + """Handle updating state after a token has been checked. + + This function should be used for destructive state changes such as + deleting a tracked object. + + Args: + token: The token to handle. + """ + type = token.type + if type == Type.SEMICOLON or type == Type.END_PAREN or ( + type == Type.END_BRACKET and + self._last_non_space_token.type not in ( + Type.SINGLE_QUOTE_STRING_END, Type.DOUBLE_QUOTE_STRING_END)): + # We end on any numeric array index, but keep going for string based + # array indices so that we pick up manually exported identifiers. + self._doc_comment = None + self._last_comment = None + + elif type == Type.END_BLOCK: + self._doc_comment = None + self._last_comment = None + + if self.InFunction() and self.IsFunctionClose(): + # TODO(robbyw): Detect the function's name for better errors. + self._functions.pop() + + elif type == Type.END_PARAMETERS and self._doc_comment: + self._doc_comment = None + self._last_comment = None + + if not token.IsAnyType(Type.WHITESPACE, Type.BLANK_LINE): + self._last_non_space_token = token + + self._last_line = token.line diff --git a/node-v0.8.14/tools/closure_linter/closure_linter/tokenutil.py b/node-v0.8.14/tools/closure_linter/closure_linter/tokenutil.py new file mode 100755 index 0000000..6ed5f7f --- /dev/null +++ b/node-v0.8.14/tools/closure_linter/closure_linter/tokenutil.py @@ -0,0 +1,285 @@ +#!/usr/bin/env python +# +# Copyright 2007 The Closure Linter Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS-IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Token utility functions.""" + +__author__ = ('robbyw@google.com (Robert Walker)', + 'ajp@google.com (Andy Perelson)') + +from closure_linter.common import tokens +from closure_linter import javascripttokens + +import copy + +# Shorthand +JavaScriptToken = javascripttokens.JavaScriptToken +Type = tokens.TokenType + +def GetFirstTokenInSameLine(token): + """Returns the first token in the same line as token. + + Args: + token: Any token in the line. + + Returns: + The first token in the same line as token. + """ + while not token.IsFirstInLine(): + token = token.previous + return token + + +def CustomSearch(start_token, func, end_func=None, distance=None, + reverse=False): + """Returns the first token where func is True within distance of this token. + + Args: + start_token: The token to start searching from + func: The function to call to test a token for applicability + end_func: The function to call to test a token to determine whether to abort + the search. + distance: The number of tokens to look through before failing search. Must + be positive. If unspecified, will search until the end of the token + chain + reverse: When true, search the tokens before this one instead of the tokens + after it + + Returns: + The first token matching func within distance of this token, or None if no + such token is found. + """ + token = start_token + if reverse: + while token and (distance is None or distance > 0): + previous = token.previous + if previous: + if func(previous): + return previous + if end_func and end_func(previous): + return None + + token = previous + if distance is not None: + distance -= 1 + + else: + while token and (distance is None or distance > 0): + next = token.next + if next: + if func(next): + return next + if end_func and end_func(next): + return None + + token = next + if distance is not None: + distance -= 1 + + return None + + +def Search(start_token, token_types, distance=None, reverse=False): + """Returns the first token of type in token_types within distance. + + Args: + start_token: The token to start searching from + token_types: The allowable types of the token being searched for + distance: The number of tokens to look through before failing search. Must + be positive. If unspecified, will search until the end of the token + chain + reverse: When true, search the tokens before this one instead of the tokens + after it + + Returns: + The first token of any type in token_types within distance of this token, or + None if no such token is found. + """ + return CustomSearch(start_token, lambda token: token.IsAnyType(token_types), + None, distance, reverse) + + +def SearchExcept(start_token, token_types, distance=None, reverse=False): + """Returns the first token not of any type in token_types within distance. + + Args: + start_token: The token to start searching from + token_types: The unallowable types of the token being searched for + distance: The number of tokens to look through before failing search. Must + be positive. If unspecified, will search until the end of the token + chain + reverse: When true, search the tokens before this one instead of the tokens + after it + + + Returns: + The first token of any type in token_types within distance of this token, or + None if no such token is found. + """ + return CustomSearch(start_token, + lambda token: not token.IsAnyType(token_types), + None, distance, reverse) + + +def SearchUntil(start_token, token_types, end_types, distance=None, + reverse=False): + """Returns the first token of type in token_types before a token of end_type. + + Args: + start_token: The token to start searching from. + token_types: The allowable types of the token being searched for. + end_types: Types of tokens to abort search if we find. + distance: The number of tokens to look through before failing search. Must + be positive. If unspecified, will search until the end of the token + chain + reverse: When true, search the tokens before this one instead of the tokens + after it + + Returns: + The first token of any type in token_types within distance of this token + before any tokens of type in end_type, or None if no such token is found. + """ + return CustomSearch(start_token, lambda token: token.IsAnyType(token_types), + lambda token: token.IsAnyType(end_types), + distance, reverse) + + +def DeleteToken(token): + """Deletes the given token from the linked list. + + Args: + token: The token to delete + """ + if token.previous: + token.previous.next = token.next + + if token.next: + token.next.previous = token.previous + + following_token = token.next + while following_token and following_token.metadata.last_code == token: + following_token.metadata.last_code = token.metadata.last_code + following_token = following_token.next + +def DeleteTokens(token, tokenCount): + """Deletes the given number of tokens starting with the given token. + + Args: + token: The token to start deleting at. + tokenCount: The total number of tokens to delete. + """ + for i in xrange(1, tokenCount): + DeleteToken(token.next) + DeleteToken(token) + +def InsertTokenAfter(new_token, token): + """Insert new_token after token + + Args: + new_token: A token to be added to the stream + token: A token already in the stream + """ + new_token.previous = token + new_token.next = token.next + + new_token.metadata = copy.copy(token.metadata) + + if token.IsCode(): + new_token.metadata.last_code = token + + if new_token.IsCode(): + following_token = token.next + while following_token and following_token.metadata.last_code == token: + following_token.metadata.last_code = new_token + following_token = following_token.next + + token.next = new_token + if new_token.next: + new_token.next.previous = new_token + + if new_token.start_index is None: + if new_token.line_number == token.line_number: + new_token.start_index = token.start_index + len(token.string) + else: + new_token.start_index = 0 + + iterator = new_token.next + while iterator and iterator.line_number == new_token.line_number: + iterator.start_index += len(new_token.string) + iterator = iterator.next + + +def InsertSpaceTokenAfter(token): + """Inserts a space token after the given token. + + Args: + token: The token to insert a space token after + + Returns: + A single space token""" + space_token = JavaScriptToken(' ', Type.WHITESPACE, token.line, + token.line_number) + InsertTokenAfter(space_token, token) + + +def InsertLineAfter(token): + """Inserts a blank line after the given token. + + Args: + token: The token to insert a blank line after + + Returns: + A single space token""" + blank_token = JavaScriptToken('', Type.BLANK_LINE, '', + token.line_number + 1) + InsertTokenAfter(blank_token, token) + # Update all subsequent ine numbers. + blank_token = blank_token.next + while blank_token: + blank_token.line_number += 1 + blank_token = blank_token.next + + +def SplitToken(token, position): + """Splits the token into two tokens at position. + + Args: + token: The token to split + position: The position to split at. Will be the beginning of second token. + + Returns: + The new second token. + """ + new_string = token.string[position:] + token.string = token.string[:position] + + new_token = JavaScriptToken(new_string, token.type, token.line, + token.line_number) + InsertTokenAfter(new_token, token) + + return new_token + + +def Compare(token1, token2): + """Compares two tokens and determines their relative order. + + Returns: + A negative integer, zero, or a positive integer as the first token is + before, equal, or after the second in the token stream. + """ + if token2.line_number != token1.line_number: + return token1.line_number - token2.line_number + else: + return token1.start_index - token2.start_index diff --git a/node-v0.8.14/tools/closure_linter/gflags.py b/node-v0.8.14/tools/closure_linter/gflags.py new file mode 100644 index 0000000..21aa88e --- /dev/null +++ b/node-v0.8.14/tools/closure_linter/gflags.py @@ -0,0 +1,2489 @@ +#!/usr/bin/env python + +# Copyright (c) 2007, Google Inc. +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above +# copyright notice, this list of conditions and the following disclaimer +# in the documentation and/or other materials provided with the +# distribution. +# * Neither the name of Google Inc. nor the names of its +# contributors may be used to endorse or promote products derived from +# this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# +# --- +# Author: Chad Lester +# Design and style contributions by: +# Amit Patel, Bogdan Cocosel, Daniel Dulitz, Eric Tiedemann, +# Eric Veach, Laurence Gonsalves, Matthew Springer +# Code reorganized a bit by Craig Silverstein + +"""This module is used to define and parse command line flags. + +This module defines a *distributed* flag-definition policy: rather than +an application having to define all flags in or near main(), each python +module defines flags that are useful to it. When one python module +imports another, it gains access to the other's flags. (This is +implemented by having all modules share a common, global registry object +containing all the flag information.) + +Flags are defined through the use of one of the DEFINE_xxx functions. +The specific function used determines how the flag is parsed, checked, +and optionally type-converted, when it's seen on the command line. + + +IMPLEMENTATION: DEFINE_* creates a 'Flag' object and registers it with a +'FlagValues' object (typically the global FlagValues FLAGS, defined +here). The 'FlagValues' object can scan the command line arguments and +pass flag arguments to the corresponding 'Flag' objects for +value-checking and type conversion. The converted flag values are +available as attributes of the 'FlagValues' object. + +Code can access the flag through a FlagValues object, for instance +gflags.FLAGS.myflag. Typically, the __main__ module passes the +command line arguments to gflags.FLAGS for parsing. + +At bottom, this module calls getopt(), so getopt functionality is +supported, including short- and long-style flags, and the use of -- to +terminate flags. + +Methods defined by the flag module will throw 'FlagsError' exceptions. +The exception argument will be a human-readable string. + + +FLAG TYPES: This is a list of the DEFINE_*'s that you can do. All flags +take a name, default value, help-string, and optional 'short' name +(one-letter name). Some flags have other arguments, which are described +with the flag. + +DEFINE_string: takes any input, and interprets it as a string. + +DEFINE_bool or +DEFINE_boolean: typically does not take an argument: say --myflag to + set FLAGS.myflag to true, or --nomyflag to set + FLAGS.myflag to false. Alternately, you can say + --myflag=true or --myflag=t or --myflag=1 or + --myflag=false or --myflag=f or --myflag=0 + +DEFINE_float: takes an input and interprets it as a floating point + number. Takes optional args lower_bound and upper_bound; + if the number specified on the command line is out of + range, it will raise a FlagError. + +DEFINE_integer: takes an input and interprets it as an integer. Takes + optional args lower_bound and upper_bound as for floats. + +DEFINE_enum: takes a list of strings which represents legal values. If + the command-line value is not in this list, raise a flag + error. Otherwise, assign to FLAGS.flag as a string. + +DEFINE_list: Takes a comma-separated list of strings on the commandline. + Stores them in a python list object. + +DEFINE_spaceseplist: Takes a space-separated list of strings on the + commandline. Stores them in a python list object. + Example: --myspacesepflag "foo bar baz" + +DEFINE_multistring: The same as DEFINE_string, except the flag can be + specified more than once on the commandline. The + result is a python list object (list of strings), + even if the flag is only on the command line once. + +DEFINE_multi_int: The same as DEFINE_integer, except the flag can be + specified more than once on the commandline. The + result is a python list object (list of ints), even if + the flag is only on the command line once. + + +SPECIAL FLAGS: There are a few flags that have special meaning: + --help prints a list of all the flags in a human-readable fashion + --helpshort prints a list of all key flags (see below). + --helpxml prints a list of all flags, in XML format. DO NOT parse + the output of --help and --helpshort. Instead, parse + the output of --helpxml. For more info, see + "OUTPUT FOR --helpxml" below. + --flagfile=foo read flags from file foo. + --undefok=f1,f2 ignore unrecognized option errors for f1,f2. + For boolean flags, you should use --undefok=boolflag, and + --boolflag and --noboolflag will be accepted. Do not use + --undefok=noboolflag. + -- as in getopt(), terminates flag-processing + + +NOTE ON --flagfile: + +Flags may be loaded from text files in addition to being specified on +the commandline. + +Any flags you don't feel like typing, throw them in a file, one flag per +line, for instance: + --myflag=myvalue + --nomyboolean_flag +You then specify your file with the special flag '--flagfile=somefile'. +You CAN recursively nest flagfile= tokens OR use multiple files on the +command line. Lines beginning with a single hash '#' or a double slash +'//' are comments in your flagfile. + +Any flagfile= will be interpreted as having a relative path from +the current working directory rather than from the place the file was +included from: + myPythonScript.py --flagfile=config/somefile.cfg + +If somefile.cfg includes further --flagfile= directives, these will be +referenced relative to the original CWD, not from the directory the +including flagfile was found in! + +The caveat applies to people who are including a series of nested files +in a different dir than they are executing out of. Relative path names +are always from CWD, not from the directory of the parent include +flagfile. We do now support '~' expanded directory names. + +Absolute path names ALWAYS work! + + +EXAMPLE USAGE: + + import gflags + FLAGS = gflags.FLAGS + + # Flag names are globally defined! So in general, we need to be + # careful to pick names that are unlikely to be used by other libraries. + # If there is a conflict, we'll get an error at import time. + gflags.DEFINE_string('name', 'Mr. President', 'your name') + gflags.DEFINE_integer('age', None, 'your age in years', lower_bound=0) + gflags.DEFINE_boolean('debug', False, 'produces debugging output') + gflags.DEFINE_enum('gender', 'male', ['male', 'female'], 'your gender') + + def main(argv): + try: + argv = FLAGS(argv) # parse flags + except gflags.FlagsError, e: + print '%s\\nUsage: %s ARGS\\n%s' % (e, sys.argv[0], FLAGS) + sys.exit(1) + if FLAGS.debug: print 'non-flag arguments:', argv + print 'Happy Birthday', FLAGS.name + if FLAGS.age is not None: + print 'You are a %s, who is %d years old' % (FLAGS.gender, FLAGS.age) + + if __name__ == '__main__': + main(sys.argv) + + +KEY FLAGS: + +As we already explained, each module gains access to all flags defined +by all the other modules it transitively imports. In the case of +non-trivial scripts, this means a lot of flags ... For documentation +purposes, it is good to identify the flags that are key (i.e., really +important) to a module. Clearly, the concept of "key flag" is a +subjective one. When trying to determine whether a flag is key to a +module or not, assume that you are trying to explain your module to a +potential user: which flags would you really like to mention first? + +We'll describe shortly how to declare which flags are key to a module. +For the moment, assume we know the set of key flags for each module. +Then, if you use the app.py module, you can use the --helpshort flag to +print only the help for the flags that are key to the main module, in a +human-readable format. + +NOTE: If you need to parse the flag help, do NOT use the output of +--help / --helpshort. That output is meant for human consumption, and +may be changed in the future. Instead, use --helpxml; flags that are +key for the main module are marked there with a yes element. + +The set of key flags for a module M is composed of: + +1. Flags defined by module M by calling a DEFINE_* function. + +2. Flags that module M explictly declares as key by using the function + + DECLARE_key_flag() + +3. Key flags of other modules that M specifies by using the function + + ADOPT_module_key_flags() + + This is a "bulk" declaration of key flags: each flag that is key for + becomes key for the current module too. + +Notice that if you do not use the functions described at points 2 and 3 +above, then --helpshort prints information only about the flags defined +by the main module of our script. In many cases, this behavior is good +enough. But if you move part of the main module code (together with the +related flags) into a different module, then it is nice to use +DECLARE_key_flag / ADOPT_module_key_flags and make sure --helpshort +lists all relevant flags (otherwise, your code refactoring may confuse +your users). + +Note: each of DECLARE_key_flag / ADOPT_module_key_flags has its own +pluses and minuses: DECLARE_key_flag is more targeted and may lead a +more focused --helpshort documentation. ADOPT_module_key_flags is good +for cases when an entire module is considered key to the current script. +Also, it does not require updates to client scripts when a new flag is +added to the module. + + +EXAMPLE USAGE 2 (WITH KEY FLAGS): + +Consider an application that contains the following three files (two +auxiliary modules and a main module): + +File libfoo.py: + + import gflags + + gflags.DEFINE_integer('num_replicas', 3, 'Number of replicas to start') + gflags.DEFINE_boolean('rpc2', True, 'Turn on the usage of RPC2.') + + ... some code ... + +File libbar.py: + + import gflags + + gflags.DEFINE_string('bar_gfs_path', '/gfs/path', + 'Path to the GFS files for libbar.') + gflags.DEFINE_string('email_for_bar_errors', 'bar-team@google.com', + 'Email address for bug reports about module libbar.') + gflags.DEFINE_boolean('bar_risky_hack', False, + 'Turn on an experimental and buggy optimization.') + + ... some code ... + +File myscript.py: + + import gflags + import libfoo + import libbar + + gflags.DEFINE_integer('num_iterations', 0, 'Number of iterations.') + + # Declare that all flags that are key for libfoo are + # key for this module too. + gflags.ADOPT_module_key_flags(libfoo) + + # Declare that the flag --bar_gfs_path (defined in libbar) is key + # for this module. + gflags.DECLARE_key_flag('bar_gfs_path') + + ... some code ... + +When myscript is invoked with the flag --helpshort, the resulted help +message lists information about all the key flags for myscript: +--num_iterations, --num_replicas, --rpc2, and --bar_gfs_path (in +addition to the special flags --help and --helpshort). + +Of course, myscript uses all the flags declared by it (in this case, +just --num_replicas) or by any of the modules it transitively imports +(e.g., the modules libfoo, libbar). E.g., it can access the value of +FLAGS.bar_risky_hack, even if --bar_risky_hack is not declared as a key +flag for myscript. + + +OUTPUT FOR --helpxml: + +The --helpxml flag generates output with the following structure: + + + + PROGRAM_BASENAME + MAIN_MODULE_DOCSTRING + ( + [yes] + DECLARING_MODULE + FLAG_NAME + FLAG_HELP_MESSAGE + DEFAULT_FLAG_VALUE + CURRENT_FLAG_VALUE + FLAG_TYPE + [OPTIONAL_ELEMENTS] + )* + + +Notes: + +1. The output is intentionally similar to the output generated by the +C++ command-line flag library. The few differences are due to the +Python flags that do not have a C++ equivalent (at least not yet), +e.g., DEFINE_list. + +2. New XML elements may be added in the future. + +3. DEFAULT_FLAG_VALUE is in serialized form, i.e., the string you can +pass for this flag on the command-line. E.g., for a flag defined +using DEFINE_list, this field may be foo,bar, not ['foo', 'bar']. + +4. CURRENT_FLAG_VALUE is produced using str(). This means that the +string 'false' will be represented in the same way as the boolean +False. Using repr() would have removed this ambiguity and simplified +parsing, but would have broken the compatibility with the C++ +command-line flags. + +5. OPTIONAL_ELEMENTS describe elements relevant for certain kinds of +flags: lower_bound, upper_bound (for flags that specify bounds), +enum_value (for enum flags), list_separator (for flags that consist of +a list of values, separated by a special token). + +6. We do not provide any example here: please use --helpxml instead. +""" + +import cgi +import getopt +import os +import re +import string +import sys + +# Are we running at least python 2.2? +try: + if tuple(sys.version_info[:3]) < (2,2,0): + raise NotImplementedError("requires python 2.2.0 or later") +except AttributeError: # a very old python, that lacks sys.version_info + raise NotImplementedError("requires python 2.2.0 or later") + +# If we're not running at least python 2.2.1, define True, False, and bool. +# Thanks, Guido, for the code. +try: + True, False, bool +except NameError: + False = 0 + True = 1 + def bool(x): + if x: + return True + else: + return False + +# Are we running under pychecker? +_RUNNING_PYCHECKER = 'pychecker.python' in sys.modules + + +def _GetCallingModule(): + """Returns the name of the module that's calling into this module. + + We generally use this function to get the name of the module calling a + DEFINE_foo... function. + """ + # Walk down the stack to find the first globals dict that's not ours. + for depth in range(1, sys.getrecursionlimit()): + if not sys._getframe(depth).f_globals is globals(): + globals_for_frame = sys._getframe(depth).f_globals + module_name = _GetModuleObjectAndName(globals_for_frame)[1] + if module_name is not None: + return module_name + raise AssertionError("No module was found") + + +def _GetThisModuleObjectAndName(): + """Returns: (module object, module name) for this module.""" + return _GetModuleObjectAndName(globals()) + + +# module exceptions: +class FlagsError(Exception): + """The base class for all flags errors.""" + pass + + +class DuplicateFlag(FlagsError): + """Raised if there is a flag naming conflict.""" + pass + + +class DuplicateFlagCannotPropagateNoneToSwig(DuplicateFlag): + """Special case of DuplicateFlag -- SWIG flag value can't be set to None. + + This can be raised when a duplicate flag is created. Even if allow_override is + True, we still abort if the new value is None, because it's currently + impossible to pass None default value back to SWIG. See FlagValues.SetDefault + for details. + """ + pass + + +# A DuplicateFlagError conveys more information than a +# DuplicateFlag. Since there are external modules that create +# DuplicateFlags, the interface to DuplicateFlag shouldn't change. +class DuplicateFlagError(DuplicateFlag): + + def __init__(self, flagname, flag_values): + self.flagname = flagname + message = "The flag '%s' is defined twice." % self.flagname + flags_by_module = flag_values.FlagsByModuleDict() + for module in flags_by_module: + for flag in flags_by_module[module]: + if flag.name == flagname or flag.short_name == flagname: + message = message + " First from " + module + "," + break + message = message + " Second from " + _GetCallingModule() + DuplicateFlag.__init__(self, message) + + +class IllegalFlagValue(FlagsError): + """The flag command line argument is illegal.""" + pass + + +class UnrecognizedFlag(FlagsError): + """Raised if a flag is unrecognized.""" + pass + + +# An UnrecognizedFlagError conveys more information than an +# UnrecognizedFlag. Since there are external modules that create +# DuplicateFlags, the interface to DuplicateFlag shouldn't change. +class UnrecognizedFlagError(UnrecognizedFlag): + def __init__(self, flagname): + self.flagname = flagname + UnrecognizedFlag.__init__( + self, "Unknown command line flag '%s'" % flagname) + + +# Global variable used by expvar +_exported_flags = {} +_help_width = 80 # width of help output + + +def GetHelpWidth(): + """Returns: an integer, the width of help lines that is used in TextWrap.""" + return _help_width + + +def CutCommonSpacePrefix(text): + """Removes a common space prefix from the lines of a multiline text. + + If the first line does not start with a space, it is left as it is and + only in the remaining lines a common space prefix is being searched + for. That means the first line will stay untouched. This is especially + useful to turn doc strings into help texts. This is because some + people prefer to have the doc comment start already after the + apostrophy and then align the following lines while others have the + apostrophies on a seperately line. + + The function also drops trailing empty lines and ignores empty lines + following the initial content line while calculating the initial + common whitespace. + + Args: + text: text to work on + + Returns: + the resulting text + """ + text_lines = text.splitlines() + # Drop trailing empty lines + while text_lines and not text_lines[-1]: + text_lines = text_lines[:-1] + if text_lines: + # We got some content, is the first line starting with a space? + if text_lines[0] and text_lines[0][0].isspace(): + text_first_line = [] + else: + text_first_line = [text_lines.pop(0)] + # Calculate length of common leading whitesppace (only over content lines) + common_prefix = os.path.commonprefix([line for line in text_lines if line]) + space_prefix_len = len(common_prefix) - len(common_prefix.lstrip()) + # If we have a common space prefix, drop it from all lines + if space_prefix_len: + for index in xrange(len(text_lines)): + if text_lines[index]: + text_lines[index] = text_lines[index][space_prefix_len:] + return '\n'.join(text_first_line + text_lines) + return '' + + +def TextWrap(text, length=None, indent='', firstline_indent=None, tabs=' '): + """Wraps a given text to a maximum line length and returns it. + + We turn lines that only contain whitespaces into empty lines. We keep + new lines and tabs (e.g., we do not treat tabs as spaces). + + Args: + text: text to wrap + length: maximum length of a line, includes indentation + if this is None then use GetHelpWidth() + indent: indent for all but first line + firstline_indent: indent for first line; if None, fall back to indent + tabs: replacement for tabs + + Returns: + wrapped text + + Raises: + FlagsError: if indent not shorter than length + FlagsError: if firstline_indent not shorter than length + """ + # Get defaults where callee used None + if length is None: + length = GetHelpWidth() + if indent is None: + indent = '' + if len(indent) >= length: + raise FlagsError('Indent must be shorter than length') + # In line we will be holding the current line which is to be started + # with indent (or firstline_indent if available) and then appended + # with words. + if firstline_indent is None: + firstline_indent = '' + line = indent + else: + line = firstline_indent + if len(firstline_indent) >= length: + raise FlagsError('First iline indent must be shorter than length') + + # If the callee does not care about tabs we simply convert them to + # spaces If callee wanted tabs to be single space then we do that + # already here. + if not tabs or tabs == ' ': + text = text.replace('\t', ' ') + else: + tabs_are_whitespace = not tabs.strip() + + line_regex = re.compile('([ ]*)(\t*)([^ \t]+)', re.MULTILINE) + + # Split the text into lines and the lines with the regex above. The + # resulting lines are collected in result[]. For each split we get the + # spaces, the tabs and the next non white space (e.g. next word). + result = [] + for text_line in text.splitlines(): + # Store result length so we can find out whether processing the next + # line gave any new content + old_result_len = len(result) + # Process next line with line_regex. For optimization we do an rstrip(). + # - process tabs (changes either line or word, see below) + # - process word (first try to squeeze on line, then wrap or force wrap) + # Spaces found on the line are ignored, they get added while wrapping as + # needed. + for spaces, current_tabs, word in line_regex.findall(text_line.rstrip()): + # If tabs weren't converted to spaces, handle them now + if current_tabs: + # If the last thing we added was a space anyway then drop + # it. But let's not get rid of the indentation. + if (((result and line != indent) or + (not result and line != firstline_indent)) and line[-1] == ' '): + line = line[:-1] + # Add the tabs, if that means adding whitespace, just add it at + # the line, the rstrip() code while shorten the line down if + # necessary + if tabs_are_whitespace: + line += tabs * len(current_tabs) + else: + # if not all tab replacement is whitespace we prepend it to the word + word = tabs * len(current_tabs) + word + # Handle the case where word cannot be squeezed onto current last line + if len(line) + len(word) > length and len(indent) + len(word) <= length: + result.append(line.rstrip()) + line = indent + word + word = '' + # No space left on line or can we append a space? + if len(line) + 1 >= length: + result.append(line.rstrip()) + line = indent + else: + line += ' ' + # Add word and shorten it up to allowed line length. Restart next + # line with indent and repeat, or add a space if we're done (word + # finished) This deals with words that caanot fit on one line + # (e.g. indent + word longer than allowed line length). + while len(line) + len(word) >= length: + line += word + result.append(line[:length]) + word = line[length:] + line = indent + # Default case, simply append the word and a space + if word: + line += word + ' ' + # End of input line. If we have content we finish the line. If the + # current line is just the indent but we had content in during this + # original line then we need to add an emoty line. + if (result and line != indent) or (not result and line != firstline_indent): + result.append(line.rstrip()) + elif len(result) == old_result_len: + result.append('') + line = indent + + return '\n'.join(result) + + +def DocToHelp(doc): + """Takes a __doc__ string and reformats it as help.""" + + # Get rid of starting and ending white space. Using lstrip() or even + # strip() could drop more than maximum of first line and right space + # of last line. + doc = doc.strip() + + # Get rid of all empty lines + whitespace_only_line = re.compile('^[ \t]+$', re.M) + doc = whitespace_only_line.sub('', doc) + + # Cut out common space at line beginnings + doc = CutCommonSpacePrefix(doc) + + # Just like this module's comment, comments tend to be aligned somehow. + # In other words they all start with the same amount of white space + # 1) keep double new lines + # 2) keep ws after new lines if not empty line + # 3) all other new lines shall be changed to a space + # Solution: Match new lines between non white space and replace with space. + doc = re.sub('(?<=\S)\n(?=\S)', ' ', doc, re.M) + + return doc + + +def _GetModuleObjectAndName(globals_dict): + """Returns the module that defines a global environment, and its name. + + Args: + globals_dict: A dictionary that should correspond to an environment + providing the values of the globals. + + Returns: + A pair consisting of (1) module object and (2) module name (a + string). Returns (None, None) if the module could not be + identified. + """ + # The use of .items() (instead of .iteritems()) is NOT a mistake: if + # a parallel thread imports a module while we iterate over + # .iteritems() (not nice, but possible), we get a RuntimeError ... + # Hence, we use the slightly slower but safer .items(). + for name, module in sys.modules.items(): + if getattr(module, '__dict__', None) is globals_dict: + if name == '__main__': + # Pick a more informative name for the main module. + name = sys.argv[0] + return (module, name) + return (None, None) + + +def _GetMainModule(): + """Returns the name of the module from which execution started.""" + for depth in range(1, sys.getrecursionlimit()): + try: + globals_of_main = sys._getframe(depth).f_globals + except ValueError: + return _GetModuleObjectAndName(globals_of_main)[1] + raise AssertionError("No module was found") + + +class FlagValues: + """Registry of 'Flag' objects. + + A 'FlagValues' can then scan command line arguments, passing flag + arguments through to the 'Flag' objects that it owns. It also + provides easy access to the flag values. Typically only one + 'FlagValues' object is needed by an application: gflags.FLAGS + + This class is heavily overloaded: + + 'Flag' objects are registered via __setitem__: + FLAGS['longname'] = x # register a new flag + + The .value attribute of the registered 'Flag' objects can be accessed + as attributes of this 'FlagValues' object, through __getattr__. Both + the long and short name of the original 'Flag' objects can be used to + access its value: + FLAGS.longname # parsed flag value + FLAGS.x # parsed flag value (short name) + + Command line arguments are scanned and passed to the registered 'Flag' + objects through the __call__ method. Unparsed arguments, including + argv[0] (e.g. the program name) are returned. + argv = FLAGS(sys.argv) # scan command line arguments + + The original registered Flag objects can be retrieved through the use + of the dictionary-like operator, __getitem__: + x = FLAGS['longname'] # access the registered Flag object + + The str() operator of a 'FlagValues' object provides help for all of + the registered 'Flag' objects. + """ + + def __init__(self): + # Since everything in this class is so heavily overloaded, the only + # way of defining and using fields is to access __dict__ directly. + + # Dictionary: flag name (string) -> Flag object. + self.__dict__['__flags'] = {} + # Dictionary: module name (string) -> list of Flag objects that are defined + # by that module. + self.__dict__['__flags_by_module'] = {} + # Dictionary: module name (string) -> list of Flag objects that are + # key for that module. + self.__dict__['__key_flags_by_module'] = {} + + # Set if we should use new style gnu_getopt rather than getopt when parsing + # the args. Only possible with Python 2.3+ + self.UseGnuGetOpt(False) + + def UseGnuGetOpt(self, use_gnu_getopt=True): + self.__dict__['__use_gnu_getopt'] = use_gnu_getopt + + def IsGnuGetOpt(self): + return self.__dict__['__use_gnu_getopt'] + + def FlagDict(self): + return self.__dict__['__flags'] + + def FlagsByModuleDict(self): + """Returns the dictionary of module_name -> list of defined flags. + + Returns: + A dictionary. Its keys are module names (strings). Its values + are lists of Flag objects. + """ + return self.__dict__['__flags_by_module'] + + def KeyFlagsByModuleDict(self): + """Returns the dictionary of module_name -> list of key flags. + + Returns: + A dictionary. Its keys are module names (strings). Its values + are lists of Flag objects. + """ + return self.__dict__['__key_flags_by_module'] + + def _RegisterFlagByModule(self, module_name, flag): + """Records the module that defines a specific flag. + + We keep track of which flag is defined by which module so that we + can later sort the flags by module. + + Args: + module_name: A string, the name of a Python module. + flag: A Flag object, a flag that is key to the module. + """ + flags_by_module = self.FlagsByModuleDict() + flags_by_module.setdefault(module_name, []).append(flag) + + def _RegisterKeyFlagForModule(self, module_name, flag): + """Specifies that a flag is a key flag for a module. + + Args: + module_name: A string, the name of a Python module. + flag: A Flag object, a flag that is key to the module. + """ + key_flags_by_module = self.KeyFlagsByModuleDict() + # The list of key flags for the module named module_name. + key_flags = key_flags_by_module.setdefault(module_name, []) + # Add flag, but avoid duplicates. + if flag not in key_flags: + key_flags.append(flag) + + def _GetFlagsDefinedByModule(self, module): + """Returns the list of flags defined by a module. + + Args: + module: A module object or a module name (a string). + + Returns: + A new list of Flag objects. Caller may update this list as he + wishes: none of those changes will affect the internals of this + FlagValue object. + """ + if not isinstance(module, str): + module = module.__name__ + + return list(self.FlagsByModuleDict().get(module, [])) + + def _GetKeyFlagsForModule(self, module): + """Returns the list of key flags for a module. + + Args: + module: A module object or a module name (a string) + + Returns: + A new list of Flag objects. Caller may update this list as he + wishes: none of those changes will affect the internals of this + FlagValue object. + """ + if not isinstance(module, str): + module = module.__name__ + + # Any flag is a key flag for the module that defined it. NOTE: + # key_flags is a fresh list: we can update it without affecting the + # internals of this FlagValues object. + key_flags = self._GetFlagsDefinedByModule(module) + + # Take into account flags explicitly declared as key for a module. + for flag in self.KeyFlagsByModuleDict().get(module, []): + if flag not in key_flags: + key_flags.append(flag) + return key_flags + + def AppendFlagValues(self, flag_values): + """Appends flags registered in another FlagValues instance. + + Args: + flag_values: registry to copy from + """ + for flag_name, flag in flag_values.FlagDict().iteritems(): + # Each flags with shortname appears here twice (once under its + # normal name, and again with its short name). To prevent + # problems (DuplicateFlagError) with double flag registration, we + # perform a check to make sure that the entry we're looking at is + # for its normal name. + if flag_name == flag.name: + self[flag_name] = flag + + def RemoveFlagValues(self, flag_values): + """Remove flags that were previously appended from another FlagValues. + + Args: + flag_values: registry containing flags to remove. + """ + for flag_name in flag_values.FlagDict(): + self.__delattr__(flag_name) + + def __setitem__(self, name, flag): + """Registers a new flag variable.""" + fl = self.FlagDict() + if not isinstance(flag, Flag): + raise IllegalFlagValue(flag) + if not isinstance(name, type("")): + raise FlagsError("Flag name must be a string") + if len(name) == 0: + raise FlagsError("Flag name cannot be empty") + # If running under pychecker, duplicate keys are likely to be + # defined. Disable check for duplicate keys when pycheck'ing. + if (fl.has_key(name) and not flag.allow_override and + not fl[name].allow_override and not _RUNNING_PYCHECKER): + raise DuplicateFlagError(name, self) + short_name = flag.short_name + if short_name is not None: + if (fl.has_key(short_name) and not flag.allow_override and + not fl[short_name].allow_override and not _RUNNING_PYCHECKER): + raise DuplicateFlagError(short_name, self) + fl[short_name] = flag + fl[name] = flag + global _exported_flags + _exported_flags[name] = flag + + def __getitem__(self, name): + """Retrieves the Flag object for the flag --name.""" + return self.FlagDict()[name] + + def __getattr__(self, name): + """Retrieves the 'value' attribute of the flag --name.""" + fl = self.FlagDict() + if not fl.has_key(name): + raise AttributeError(name) + return fl[name].value + + def __setattr__(self, name, value): + """Sets the 'value' attribute of the flag --name.""" + fl = self.FlagDict() + fl[name].value = value + return value + + def _FlagIsRegistered(self, flag_obj): + """Checks whether a Flag object is registered under some name. + + Note: this is non trivial: in addition to its normal name, a flag + may have a short name too. In self.FlagDict(), both the normal and + the short name are mapped to the same flag object. E.g., calling + only "del FLAGS.short_name" is not unregistering the corresponding + Flag object (it is still registered under the longer name). + + Args: + flag_obj: A Flag object. + + Returns: + A boolean: True iff flag_obj is registered under some name. + """ + flag_dict = self.FlagDict() + # Check whether flag_obj is registered under its long name. + name = flag_obj.name + if flag_dict.get(name, None) == flag_obj: + return True + # Check whether flag_obj is registered under its short name. + short_name = flag_obj.short_name + if (short_name is not None and + flag_dict.get(short_name, None) == flag_obj): + return True + # The flag cannot be registered under any other name, so we do not + # need to do a full search through the values of self.FlagDict(). + return False + + def __delattr__(self, flag_name): + """Deletes a previously-defined flag from a flag object. + + This method makes sure we can delete a flag by using + + del flag_values_object. + + E.g., + + flags.DEFINE_integer('foo', 1, 'Integer flag.') + del flags.FLAGS.foo + + Args: + flag_name: A string, the name of the flag to be deleted. + + Raises: + AttributeError: When there is no registered flag named flag_name. + """ + fl = self.FlagDict() + if flag_name not in fl: + raise AttributeError(flag_name) + + flag_obj = fl[flag_name] + del fl[flag_name] + + if not self._FlagIsRegistered(flag_obj): + # If the Flag object indicated by flag_name is no longer + # registered (please see the docstring of _FlagIsRegistered), then + # we delete the occurences of the flag object in all our internal + # dictionaries. + self.__RemoveFlagFromDictByModule(self.FlagsByModuleDict(), flag_obj) + self.__RemoveFlagFromDictByModule(self.KeyFlagsByModuleDict(), flag_obj) + + def __RemoveFlagFromDictByModule(self, flags_by_module_dict, flag_obj): + """Removes a flag object from a module -> list of flags dictionary. + + Args: + flags_by_module_dict: A dictionary that maps module names to lists of + flags. + flag_obj: A flag object. + """ + for unused_module, flags_in_module in flags_by_module_dict.iteritems(): + # while (as opposed to if) takes care of multiple occurences of a + # flag in the list for the same module. + while flag_obj in flags_in_module: + flags_in_module.remove(flag_obj) + + def SetDefault(self, name, value): + """Changes the default value of the named flag object.""" + fl = self.FlagDict() + if not fl.has_key(name): + raise AttributeError(name) + fl[name].SetDefault(value) + + def __contains__(self, name): + """Returns True if name is a value (flag) in the dict.""" + return name in self.FlagDict() + + has_key = __contains__ # a synonym for __contains__() + + def __iter__(self): + return self.FlagDict().iterkeys() + + def __call__(self, argv): + """Parses flags from argv; stores parsed flags into this FlagValues object. + + All unparsed arguments are returned. Flags are parsed using the GNU + Program Argument Syntax Conventions, using getopt: + + http://www.gnu.org/software/libc/manual/html_mono/libc.html#Getopt + + Args: + argv: argument list. Can be of any type that may be converted to a list. + + Returns: + The list of arguments not parsed as options, including argv[0] + + Raises: + FlagsError: on any parsing error + """ + # Support any sequence type that can be converted to a list + argv = list(argv) + + shortopts = "" + longopts = [] + + fl = self.FlagDict() + + # This pre parses the argv list for --flagfile=<> options. + argv = argv[:1] + self.ReadFlagsFromFiles(argv[1:], force_gnu=False) + + # Correct the argv to support the google style of passing boolean + # parameters. Boolean parameters may be passed by using --mybool, + # --nomybool, --mybool=(true|false|1|0). getopt does not support + # having options that may or may not have a parameter. We replace + # instances of the short form --mybool and --nomybool with their + # full forms: --mybool=(true|false). + original_argv = list(argv) # list() makes a copy + shortest_matches = None + for name, flag in fl.items(): + if not flag.boolean: + continue + if shortest_matches is None: + # Determine the smallest allowable prefix for all flag names + shortest_matches = self.ShortestUniquePrefixes(fl) + no_name = 'no' + name + prefix = shortest_matches[name] + no_prefix = shortest_matches[no_name] + + # Replace all occurences of this boolean with extended forms + for arg_idx in range(1, len(argv)): + arg = argv[arg_idx] + if arg.find('=') >= 0: continue + if arg.startswith('--'+prefix) and ('--'+name).startswith(arg): + argv[arg_idx] = ('--%s=true' % name) + elif arg.startswith('--'+no_prefix) and ('--'+no_name).startswith(arg): + argv[arg_idx] = ('--%s=false' % name) + + # Loop over all of the flags, building up the lists of short options + # and long options that will be passed to getopt. Short options are + # specified as a string of letters, each letter followed by a colon + # if it takes an argument. Long options are stored in an array of + # strings. Each string ends with an '=' if it takes an argument. + for name, flag in fl.items(): + longopts.append(name + "=") + if len(name) == 1: # one-letter option: allow short flag type also + shortopts += name + if not flag.boolean: + shortopts += ":" + + longopts.append('undefok=') + undefok_flags = [] + + # In case --undefok is specified, loop to pick up unrecognized + # options one by one. + unrecognized_opts = [] + args = argv[1:] + while True: + try: + if self.__dict__['__use_gnu_getopt']: + optlist, unparsed_args = getopt.gnu_getopt(args, shortopts, longopts) + else: + optlist, unparsed_args = getopt.getopt(args, shortopts, longopts) + break + except getopt.GetoptError, e: + if not e.opt or e.opt in fl: + # Not an unrecognized option, reraise the exception as a FlagsError + raise FlagsError(e) + # Handle an unrecognized option. + unrecognized_opts.append(e.opt) + # Remove offender from args and try again + for arg_index in range(len(args)): + if ((args[arg_index] == '--' + e.opt) or + (args[arg_index] == '-' + e.opt) or + args[arg_index].startswith('--' + e.opt + '=')): + args = args[0:arg_index] + args[arg_index+1:] + break + else: + # We should have found the option, so we don't expect to get + # here. We could assert, but raising the original exception + # might work better. + raise FlagsError(e) + + for name, arg in optlist: + if name == '--undefok': + flag_names = arg.split(',') + undefok_flags.extend(flag_names) + # For boolean flags, if --undefok=boolflag is specified, then we should + # also accept --noboolflag, in addition to --boolflag. + # Since we don't know the type of the undefok'd flag, this will affect + # non-boolean flags as well. + # NOTE: You shouldn't use --undefok=noboolflag, because then we will + # accept --nonoboolflag here. We are choosing not to do the conversion + # from noboolflag -> boolflag because of the ambiguity that flag names + # can start with 'no'. + undefok_flags.extend('no' + name for name in flag_names) + continue + if name.startswith('--'): + # long option + name = name[2:] + short_option = 0 + else: + # short option + name = name[1:] + short_option = 1 + if fl.has_key(name): + flag = fl[name] + if flag.boolean and short_option: arg = 1 + flag.Parse(arg) + + # If there were unrecognized options, raise an exception unless + # the options were named via --undefok. + for opt in unrecognized_opts: + if opt not in undefok_flags: + raise UnrecognizedFlagError(opt) + + if unparsed_args: + if self.__dict__['__use_gnu_getopt']: + # if using gnu_getopt just return the program name + remainder of argv. + return argv[:1] + unparsed_args + else: + # unparsed_args becomes the first non-flag detected by getopt to + # the end of argv. Because argv may have been modified above, + # return original_argv for this region. + return argv[:1] + original_argv[-len(unparsed_args):] + else: + return argv[:1] + + def Reset(self): + """Resets the values to the point before FLAGS(argv) was called.""" + for f in self.FlagDict().values(): + f.Unparse() + + def RegisteredFlags(self): + """Returns: a list of the names and short names of all registered flags.""" + return self.FlagDict().keys() + + def FlagValuesDict(self): + """Returns: a dictionary that maps flag names to flag values.""" + flag_values = {} + + for flag_name in self.RegisteredFlags(): + flag = self.FlagDict()[flag_name] + flag_values[flag_name] = flag.value + + return flag_values + + def __str__(self): + """Generates a help string for all known flags.""" + return self.GetHelp() + + def GetHelp(self, prefix=''): + """Generates a help string for all known flags.""" + helplist = [] + + flags_by_module = self.FlagsByModuleDict() + if flags_by_module: + + modules = flags_by_module.keys() + modules.sort() + + # Print the help for the main module first, if possible. + main_module = _GetMainModule() + if main_module in modules: + modules.remove(main_module) + modules = [main_module] + modules + + for module in modules: + self.__RenderOurModuleFlags(module, helplist) + + self.__RenderModuleFlags('gflags', + _SPECIAL_FLAGS.FlagDict().values(), + helplist) + + else: + # Just print one long list of flags. + self.__RenderFlagList( + self.FlagDict().values() + _SPECIAL_FLAGS.FlagDict().values(), + helplist, prefix) + + return '\n'.join(helplist) + + def __RenderModuleFlags(self, module, flags, output_lines, prefix=""): + """Generates a help string for a given module.""" + if not isinstance(module, str): + module = module.__name__ + output_lines.append('\n%s%s:' % (prefix, module)) + self.__RenderFlagList(flags, output_lines, prefix + " ") + + def __RenderOurModuleFlags(self, module, output_lines, prefix=""): + """Generates a help string for a given module.""" + flags = self._GetFlagsDefinedByModule(module) + if flags: + self.__RenderModuleFlags(module, flags, output_lines, prefix) + + def __RenderOurModuleKeyFlags(self, module, output_lines, prefix=""): + """Generates a help string for the key flags of a given module. + + Args: + module: A module object or a module name (a string). + output_lines: A list of strings. The generated help message + lines will be appended to this list. + prefix: A string that is prepended to each generated help line. + """ + key_flags = self._GetKeyFlagsForModule(module) + if key_flags: + self.__RenderModuleFlags(module, key_flags, output_lines, prefix) + + def ModuleHelp(self, module): + """Describe the key flags of a module. + + Args: + module: A module object or a module name (a string). + + Returns: + string describing the key flags of a module. + """ + helplist = [] + self.__RenderOurModuleKeyFlags(module, helplist) + return '\n'.join(helplist) + + def MainModuleHelp(self): + """Describe the key flags of the main module. + + Returns: + string describing the key flags of a module. + """ + return self.ModuleHelp(_GetMainModule()) + + def __RenderFlagList(self, flaglist, output_lines, prefix=" "): + fl = self.FlagDict() + special_fl = _SPECIAL_FLAGS.FlagDict() + flaglist = [(flag.name, flag) for flag in flaglist] + flaglist.sort() + flagset = {} + for (name, flag) in flaglist: + # It's possible this flag got deleted or overridden since being + # registered in the per-module flaglist. Check now against the + # canonical source of current flag information, the FlagDict. + if fl.get(name, None) != flag and special_fl.get(name, None) != flag: + # a different flag is using this name now + continue + # only print help once + if flagset.has_key(flag): continue + flagset[flag] = 1 + flaghelp = "" + if flag.short_name: flaghelp += "-%s," % flag.short_name + if flag.boolean: + flaghelp += "--[no]%s" % flag.name + ":" + else: + flaghelp += "--%s" % flag.name + ":" + flaghelp += " " + if flag.help: + flaghelp += flag.help + flaghelp = TextWrap(flaghelp, indent=prefix+" ", + firstline_indent=prefix) + if flag.default_as_str: + flaghelp += "\n" + flaghelp += TextWrap("(default: %s)" % flag.default_as_str, + indent=prefix+" ") + if flag.parser.syntactic_help: + flaghelp += "\n" + flaghelp += TextWrap("(%s)" % flag.parser.syntactic_help, + indent=prefix+" ") + output_lines.append(flaghelp) + + def get(self, name, default): + """Returns the value of a flag (if not None) or a default value. + + Args: + name: A string, the name of a flag. + default: Default value to use if the flag value is None. + """ + + value = self.__getattr__(name) + if value is not None: # Can't do if not value, b/c value might be '0' or "" + return value + else: + return default + + def ShortestUniquePrefixes(self, fl): + """Returns: dictionary; maps flag names to their shortest unique prefix.""" + # Sort the list of flag names + sorted_flags = [] + for name, flag in fl.items(): + sorted_flags.append(name) + if flag.boolean: + sorted_flags.append('no%s' % name) + sorted_flags.sort() + + # For each name in the sorted list, determine the shortest unique + # prefix by comparing itself to the next name and to the previous + # name (the latter check uses cached info from the previous loop). + shortest_matches = {} + prev_idx = 0 + for flag_idx in range(len(sorted_flags)): + curr = sorted_flags[flag_idx] + if flag_idx == (len(sorted_flags) - 1): + next = None + else: + next = sorted_flags[flag_idx+1] + next_len = len(next) + for curr_idx in range(len(curr)): + if (next is None + or curr_idx >= next_len + or curr[curr_idx] != next[curr_idx]): + # curr longer than next or no more chars in common + shortest_matches[curr] = curr[:max(prev_idx, curr_idx) + 1] + prev_idx = curr_idx + break + else: + # curr shorter than (or equal to) next + shortest_matches[curr] = curr + prev_idx = curr_idx + 1 # next will need at least one more char + return shortest_matches + + def __IsFlagFileDirective(self, flag_string): + """Checks whether flag_string contain a --flagfile= directive.""" + if isinstance(flag_string, type("")): + if flag_string.startswith('--flagfile='): + return 1 + elif flag_string == '--flagfile': + return 1 + elif flag_string.startswith('-flagfile='): + return 1 + elif flag_string == '-flagfile': + return 1 + else: + return 0 + return 0 + + def ExtractFilename(self, flagfile_str): + """Returns filename from a flagfile_str of form -[-]flagfile=filename. + + The cases of --flagfile foo and -flagfile foo shouldn't be hitting + this function, as they are dealt with in the level above this + function. + """ + if flagfile_str.startswith('--flagfile='): + return os.path.expanduser((flagfile_str[(len('--flagfile=')):]).strip()) + elif flagfile_str.startswith('-flagfile='): + return os.path.expanduser((flagfile_str[(len('-flagfile=')):]).strip()) + else: + raise FlagsError('Hit illegal --flagfile type: %s' % flagfile_str) + + def __GetFlagFileLines(self, filename, parsed_file_list): + """Returns the useful (!=comments, etc) lines from a file with flags. + + Args: + filename: A string, the name of the flag file. + parsed_file_list: A list of the names of the files we have + already read. MUTATED BY THIS FUNCTION. + + Returns: + List of strings. See the note below. + + NOTE(springer): This function checks for a nested --flagfile= + tag and handles the lower file recursively. It returns a list of + all the lines that _could_ contain command flags. This is + EVERYTHING except whitespace lines and comments (lines starting + with '#' or '//'). + """ + line_list = [] # All line from flagfile. + flag_line_list = [] # Subset of lines w/o comments, blanks, flagfile= tags. + try: + file_obj = open(filename, 'r') + except IOError, e_msg: + print e_msg + print 'ERROR:: Unable to open flagfile: %s' % (filename) + return flag_line_list + + line_list = file_obj.readlines() + file_obj.close() + parsed_file_list.append(filename) + + # This is where we check each line in the file we just read. + for line in line_list: + if line.isspace(): + pass + # Checks for comment (a line that starts with '#'). + elif line.startswith('#') or line.startswith('//'): + pass + # Checks for a nested "--flagfile=" flag in the current file. + # If we find one, recursively parse down into that file. + elif self.__IsFlagFileDirective(line): + sub_filename = self.ExtractFilename(line) + # We do a little safety check for reparsing a file we've already done. + if not sub_filename in parsed_file_list: + included_flags = self.__GetFlagFileLines(sub_filename, + parsed_file_list) + flag_line_list.extend(included_flags) + else: # Case of hitting a circularly included file. + print >>sys.stderr, ('Warning: Hit circular flagfile dependency: %s' + % sub_filename) + else: + # Any line that's not a comment or a nested flagfile should get + # copied into 2nd position. This leaves earlier arguements + # further back in the list, thus giving them higher priority. + flag_line_list.append(line.strip()) + return flag_line_list + + def ReadFlagsFromFiles(self, argv, force_gnu=True): + """Processes command line args, but also allow args to be read from file. + Args: + argv: A list of strings, usually sys.argv[1:], which may contain one or + more flagfile directives of the form --flagfile="./filename". + Note that the name of the program (sys.argv[0]) should be omitted. + force_gnu: If False, --flagfile parsing obeys normal flag semantics. + If True, --flagfile parsing instead follows gnu_getopt semantics. + *** WARNING *** force_gnu=False may become the future default! + + Returns: + + A new list which has the original list combined with what we read + from any flagfile(s). + + References: Global gflags.FLAG class instance. + + This function should be called before the normal FLAGS(argv) call. + This function scans the input list for a flag that looks like: + --flagfile=. Then it opens , reads all valid key + and value pairs and inserts them into the input list between the + first item of the list and any subsequent items in the list. + + Note that your application's flags are still defined the usual way + using gflags DEFINE_flag() type functions. + + Notes (assuming we're getting a commandline of some sort as our input): + --> Flags from the command line argv _should_ always take precedence! + --> A further "--flagfile=" CAN be nested in a flagfile. + It will be processed after the parent flag file is done. + --> For duplicate flags, first one we hit should "win". + --> In a flagfile, a line beginning with # or // is a comment. + --> Entirely blank lines _should_ be ignored. + """ + parsed_file_list = [] + rest_of_args = argv + new_argv = [] + while rest_of_args: + current_arg = rest_of_args[0] + rest_of_args = rest_of_args[1:] + if self.__IsFlagFileDirective(current_arg): + # This handles the case of -(-)flagfile foo. In this case the + # next arg really is part of this one. + if current_arg == '--flagfile' or current_arg == '-flagfile': + if not rest_of_args: + raise IllegalFlagValue('--flagfile with no argument') + flag_filename = os.path.expanduser(rest_of_args[0]) + rest_of_args = rest_of_args[1:] + else: + # This handles the case of (-)-flagfile=foo. + flag_filename = self.ExtractFilename(current_arg) + new_argv[0:0] = self.__GetFlagFileLines(flag_filename, parsed_file_list) + else: + new_argv.append(current_arg) + # Stop parsing after '--', like getopt and gnu_getopt. + if current_arg == '--': + break + # Stop parsing after a non-flag, like getopt. + if not current_arg.startswith('-'): + if not force_gnu and not self.__dict__['__use_gnu_getopt']: + break + + if rest_of_args: + new_argv.extend(rest_of_args) + + return new_argv + + def FlagsIntoString(self): + """Returns a string with the flags assignments from this FlagValues object. + + This function ignores flags whose value is None. Each flag + assignment is separated by a newline. + + NOTE: MUST mirror the behavior of the C++ function + CommandlineFlagsIntoString from google3/base/commandlineflags.cc. + """ + s = '' + for flag in self.FlagDict().values(): + if flag.value is not None: + s += flag.Serialize() + '\n' + return s + + def AppendFlagsIntoFile(self, filename): + """Appends all flags assignments from this FlagInfo object to a file. + + Output will be in the format of a flagfile. + + NOTE: MUST mirror the behavior of the C++ version of + AppendFlagsIntoFile from google3/base/commandlineflags.cc. + """ + out_file = open(filename, 'a') + out_file.write(self.FlagsIntoString()) + out_file.close() + + def WriteHelpInXMLFormat(self, outfile=None): + """Outputs flag documentation in XML format. + + NOTE: We use element names that are consistent with those used by + the C++ command-line flag library, from + google3/base/commandlineflags_reporting.cc. We also use a few new + elements (e.g., ), but we do not interfere / overlap with + existing XML elements used by the C++ library. Please maintain this + consistency. + + Args: + outfile: File object we write to. Default None means sys.stdout. + """ + outfile = outfile or sys.stdout + + outfile.write('\n') + outfile.write('\n') + indent = ' ' + _WriteSimpleXMLElement(outfile, 'program', os.path.basename(sys.argv[0]), + indent) + + usage_doc = sys.modules['__main__'].__doc__ + if not usage_doc: + usage_doc = '\nUSAGE: %s [flags]\n' % sys.argv[0] + else: + usage_doc = usage_doc.replace('%s', sys.argv[0]) + _WriteSimpleXMLElement(outfile, 'usage', usage_doc, indent) + + # Get list of key flags for the main module. + key_flags = self._GetKeyFlagsForModule(_GetMainModule()) + + # Sort flags by declaring module name and next by flag name. + flags_by_module = self.FlagsByModuleDict() + all_module_names = list(flags_by_module.keys()) + all_module_names.sort() + for module_name in all_module_names: + flag_list = [(f.name, f) for f in flags_by_module[module_name]] + flag_list.sort() + for unused_flag_name, flag in flag_list: + is_key = flag in key_flags + flag.WriteInfoInXMLFormat(outfile, module_name, + is_key=is_key, indent=indent) + + outfile.write('\n') + outfile.flush() +# end of FlagValues definition + + +# The global FlagValues instance +FLAGS = FlagValues() + + +def _MakeXMLSafe(s): + """Escapes <, >, and & from s, and removes XML 1.0-illegal chars.""" + s = cgi.escape(s) # Escape <, >, and & + # Remove characters that cannot appear in an XML 1.0 document + # (http://www.w3.org/TR/REC-xml/#charsets). + # + # NOTE: if there are problems with current solution, one may move to + # XML 1.1, which allows such chars, if they're entity-escaped (&#xHH;). + s = re.sub(r'[\x00-\x08\x0b\x0c\x0e-\x1f]', '', s) + return s + + +def _WriteSimpleXMLElement(outfile, name, value, indent): + """Writes a simple XML element. + + Args: + outfile: File object we write the XML element to. + name: A string, the name of XML element. + value: A Python object, whose string representation will be used + as the value of the XML element. + indent: A string, prepended to each line of generated output. + """ + value_str = str(value) + if isinstance(value, bool): + # Display boolean values as the C++ flag library does: no caps. + value_str = value_str.lower() + outfile.write('%s<%s>%s\n' % + (indent, name, _MakeXMLSafe(value_str), name)) + + +class Flag: + """Information about a command-line flag. + + 'Flag' objects define the following fields: + .name - the name for this flag + .default - the default value for this flag + .default_as_str - default value as repr'd string, e.g., "'true'" (or None) + .value - the most recent parsed value of this flag; set by Parse() + .help - a help string or None if no help is available + .short_name - the single letter alias for this flag (or None) + .boolean - if 'true', this flag does not accept arguments + .present - true if this flag was parsed from command line flags. + .parser - an ArgumentParser object + .serializer - an ArgumentSerializer object + .allow_override - the flag may be redefined without raising an error + + The only public method of a 'Flag' object is Parse(), but it is + typically only called by a 'FlagValues' object. The Parse() method is + a thin wrapper around the 'ArgumentParser' Parse() method. The parsed + value is saved in .value, and the .present attribute is updated. If + this flag was already present, a FlagsError is raised. + + Parse() is also called during __init__ to parse the default value and + initialize the .value attribute. This enables other python modules to + safely use flags even if the __main__ module neglects to parse the + command line arguments. The .present attribute is cleared after + __init__ parsing. If the default value is set to None, then the + __init__ parsing step is skipped and the .value attribute is + initialized to None. + + Note: The default value is also presented to the user in the help + string, so it is important that it be a legal value for this flag. + """ + + def __init__(self, parser, serializer, name, default, help_string, + short_name=None, boolean=0, allow_override=0): + self.name = name + + if not help_string: + help_string = '(no help available)' + + self.help = help_string + self.short_name = short_name + self.boolean = boolean + self.present = 0 + self.parser = parser + self.serializer = serializer + self.allow_override = allow_override + self.value = None + + self.SetDefault(default) + + def __GetParsedValueAsString(self, value): + if value is None: + return None + if self.serializer: + return repr(self.serializer.Serialize(value)) + if self.boolean: + if value: + return repr('true') + else: + return repr('false') + return repr(str(value)) + + def Parse(self, argument): + try: + self.value = self.parser.Parse(argument) + except ValueError, e: # recast ValueError as IllegalFlagValue + raise IllegalFlagValue("flag --%s=%s: %s" % (self.name, argument, e)) + self.present += 1 + + def Unparse(self): + if self.default is None: + self.value = None + else: + self.Parse(self.default) + self.present = 0 + + def Serialize(self): + if self.value is None: + return '' + if self.boolean: + if self.value: + return "--%s" % self.name + else: + return "--no%s" % self.name + else: + if not self.serializer: + raise FlagsError("Serializer not present for flag %s" % self.name) + return "--%s=%s" % (self.name, self.serializer.Serialize(self.value)) + + def SetDefault(self, value): + """Changes the default value (and current value too) for this Flag.""" + # We can't allow a None override because it may end up not being + # passed to C++ code when we're overriding C++ flags. So we + # cowardly bail out until someone fixes the semantics of trying to + # pass None to a C++ flag. See swig_flags.Init() for details on + # this behavior. + if value is None and self.allow_override: + raise DuplicateFlagCannotPropagateNoneToSwig(self.name) + + self.default = value + self.Unparse() + self.default_as_str = self.__GetParsedValueAsString(self.value) + + def Type(self): + """Returns: a string that describes the type of this Flag.""" + # NOTE: we use strings, and not the types.*Type constants because + # our flags can have more exotic types, e.g., 'comma separated list + # of strings', 'whitespace separated list of strings', etc. + return self.parser.Type() + + def WriteInfoInXMLFormat(self, outfile, module_name, is_key=False, indent=''): + """Writes common info about this flag, in XML format. + + This is information that is relevant to all flags (e.g., name, + meaning, etc.). If you defined a flag that has some other pieces of + info, then please override _WriteCustomInfoInXMLFormat. + + Please do NOT override this method. + + Args: + outfile: File object we write to. + module_name: A string, the name of the module that defines this flag. + is_key: A boolean, True iff this flag is key for main module. + indent: A string that is prepended to each generated line. + """ + outfile.write(indent + '\n') + inner_indent = indent + ' ' + if is_key: + _WriteSimpleXMLElement(outfile, 'key', 'yes', inner_indent) + _WriteSimpleXMLElement(outfile, 'file', module_name, inner_indent) + # Print flag features that are relevant for all flags. + _WriteSimpleXMLElement(outfile, 'name', self.name, inner_indent) + if self.short_name: + _WriteSimpleXMLElement(outfile, 'short_name', self.short_name, + inner_indent) + if self.help: + _WriteSimpleXMLElement(outfile, 'meaning', self.help, inner_indent) + # The default flag value can either be represented as a string like on the + # command line, or as a Python object. We serialize this value in the + # latter case in order to remain consistent. + if self.serializer and not isinstance(self.default, str): + default_serialized = self.serializer.Serialize(self.default) + else: + default_serialized = self.default + _WriteSimpleXMLElement(outfile, 'default', default_serialized, inner_indent) + _WriteSimpleXMLElement(outfile, 'current', self.value, inner_indent) + _WriteSimpleXMLElement(outfile, 'type', self.Type(), inner_indent) + # Print extra flag features this flag may have. + self._WriteCustomInfoInXMLFormat(outfile, inner_indent) + outfile.write(indent + '\n') + + def _WriteCustomInfoInXMLFormat(self, outfile, indent): + """Writes extra info about this flag, in XML format. + + "Extra" means "not already printed by WriteInfoInXMLFormat above." + + Args: + outfile: File object we write to. + indent: A string that is prepended to each generated line. + """ + # Usually, the parser knows the extra details about the flag, so + # we just forward the call to it. + self.parser.WriteCustomInfoInXMLFormat(outfile, indent) +# End of Flag definition + + +class ArgumentParser: + """Base class used to parse and convert arguments. + + The Parse() method checks to make sure that the string argument is a + legal value and convert it to a native type. If the value cannot be + converted, it should throw a 'ValueError' exception with a human + readable explanation of why the value is illegal. + + Subclasses should also define a syntactic_help string which may be + presented to the user to describe the form of the legal values. + """ + syntactic_help = "" + + def Parse(self, argument): + """Default implementation: always returns its argument unmodified.""" + return argument + + def Type(self): + return 'string' + + def WriteCustomInfoInXMLFormat(self, outfile, indent): + pass + + +class ArgumentSerializer: + """Base class for generating string representations of a flag value.""" + + def Serialize(self, value): + return str(value) + + +class ListSerializer(ArgumentSerializer): + + def __init__(self, list_sep): + self.list_sep = list_sep + + def Serialize(self, value): + return self.list_sep.join([str(x) for x in value]) + + +# The DEFINE functions are explained in mode details in the module doc string. + + +def DEFINE(parser, name, default, help, flag_values=FLAGS, serializer=None, + **args): + """Registers a generic Flag object. + + NOTE: in the docstrings of all DEFINE* functions, "registers" is short + for "creates a new flag and registers it". + + Auxiliary function: clients should use the specialized DEFINE_ + function instead. + + Args: + parser: ArgumentParser that is used to parse the flag arguments. + name: A string, the flag name. + default: The default value of the flag. + help: A help string. + flag_values: FlagValues object the flag will be registered with. + serializer: ArgumentSerializer that serializes the flag value. + args: Dictionary with extra keyword args that are passes to the + Flag __init__. + """ + DEFINE_flag(Flag(parser, serializer, name, default, help, **args), + flag_values) + + +def DEFINE_flag(flag, flag_values=FLAGS): + """Registers a 'Flag' object with a 'FlagValues' object. + + By default, the global FLAGS 'FlagValue' object is used. + + Typical users will use one of the more specialized DEFINE_xxx + functions, such as DEFINE_string or DEFINE_integer. But developers + who need to create Flag objects themselves should use this function + to register their flags. + """ + # copying the reference to flag_values prevents pychecker warnings + fv = flag_values + fv[flag.name] = flag + # Tell flag_values who's defining the flag. + if isinstance(flag_values, FlagValues): + # Regarding the above isinstance test: some users pass funny + # values of flag_values (e.g., {}) in order to avoid the flag + # registration (in the past, there used to be a flag_values == + # FLAGS test here) and redefine flags with the same name (e.g., + # debug). To avoid breaking their code, we perform the + # registration only if flag_values is a real FlagValues object. + flag_values._RegisterFlagByModule(_GetCallingModule(), flag) + + +def _InternalDeclareKeyFlags(flag_names, + flag_values=FLAGS, key_flag_values=None): + """Declares a flag as key for the calling module. + + Internal function. User code should call DECLARE_key_flag or + ADOPT_module_key_flags instead. + + Args: + flag_names: A list of strings that are names of already-registered + Flag objects. + flag_values: A FlagValues object that the flags listed in + flag_names have registered with (the value of the flag_values + argument from the DEFINE_* calls that defined those flags). + This should almost never need to be overridden. + key_flag_values: A FlagValues object that (among possibly many + other things) keeps track of the key flags for each module. + Default None means "same as flag_values". This should almost + never need to be overridden. + + Raises: + UnrecognizedFlagError: when we refer to a flag that was not + defined yet. + """ + key_flag_values = key_flag_values or flag_values + + module = _GetCallingModule() + + for flag_name in flag_names: + if flag_name not in flag_values: + raise UnrecognizedFlagError(flag_name) + flag = flag_values.FlagDict()[flag_name] + key_flag_values._RegisterKeyFlagForModule(module, flag) + + +def DECLARE_key_flag(flag_name, flag_values=FLAGS): + """Declares one flag as key to the current module. + + Key flags are flags that are deemed really important for a module. + They are important when listing help messages; e.g., if the + --helpshort command-line flag is used, then only the key flags of the + main module are listed (instead of all flags, as in the case of + --help). + + Sample usage: + + flags.DECLARED_key_flag('flag_1') + + Args: + flag_name: A string, the name of an already declared flag. + (Redeclaring flags as key, including flags implicitly key + because they were declared in this module, is a no-op.) + flag_values: A FlagValues object. This should almost never + need to be overridden. + """ + if flag_name in _SPECIAL_FLAGS: + # Take care of the special flags, e.g., --flagfile, --undefok. + # These flags are defined in _SPECIAL_FLAGS, and are treated + # specially during flag parsing, taking precedence over the + # user-defined flags. + _InternalDeclareKeyFlags([flag_name], + flag_values=_SPECIAL_FLAGS, + key_flag_values=flag_values) + return + _InternalDeclareKeyFlags([flag_name], flag_values=flag_values) + + +def ADOPT_module_key_flags(module, flag_values=FLAGS): + """Declares that all flags key to a module are key to the current module. + + Args: + module: A module object. + flag_values: A FlagValues object. This should almost never need + to be overridden. + + Raises: + FlagsError: When given an argument that is a module name (a + string), instead of a module object. + """ + # NOTE(salcianu): an even better test would be if not + # isinstance(module, types.ModuleType) but I didn't want to import + # types for such a tiny use. + if isinstance(module, str): + raise FlagsError('Received module name %s; expected a module object.' + % module) + _InternalDeclareKeyFlags( + [f.name for f in flag_values._GetKeyFlagsForModule(module.__name__)], + flag_values=flag_values) + # If module is this flag module, take _SPECIAL_FLAGS into account. + if module == _GetThisModuleObjectAndName()[0]: + _InternalDeclareKeyFlags( + # As we associate flags with _GetCallingModule(), the special + # flags defined in this module are incorrectly registered with + # a different module. So, we can't use _GetKeyFlagsForModule. + # Instead, we take all flags from _SPECIAL_FLAGS (a private + # FlagValues, where no other module should register flags). + [f.name for f in _SPECIAL_FLAGS.FlagDict().values()], + flag_values=_SPECIAL_FLAGS, + key_flag_values=flag_values) + + +# +# STRING FLAGS +# + + +def DEFINE_string(name, default, help, flag_values=FLAGS, **args): + """Registers a flag whose value can be any string.""" + parser = ArgumentParser() + serializer = ArgumentSerializer() + DEFINE(parser, name, default, help, flag_values, serializer, **args) + + +# +# BOOLEAN FLAGS +# +# and the special HELP flags. + +class BooleanParser(ArgumentParser): + """Parser of boolean values.""" + + def Convert(self, argument): + """Converts the argument to a boolean; raise ValueError on errors.""" + if type(argument) == str: + if argument.lower() in ['true', 't', '1']: + return True + elif argument.lower() in ['false', 'f', '0']: + return False + + bool_argument = bool(argument) + if argument == bool_argument: + # The argument is a valid boolean (True, False, 0, or 1), and not just + # something that always converts to bool (list, string, int, etc.). + return bool_argument + + raise ValueError('Non-boolean argument to boolean flag', argument) + + def Parse(self, argument): + val = self.Convert(argument) + return val + + def Type(self): + return 'bool' + + +class BooleanFlag(Flag): + """Basic boolean flag. + + Boolean flags do not take any arguments, and their value is either + True (1) or False (0). The false value is specified on the command + line by prepending the word 'no' to either the long or the short flag + name. + + For example, if a Boolean flag was created whose long name was + 'update' and whose short name was 'x', then this flag could be + explicitly unset through either --noupdate or --nox. + """ + + def __init__(self, name, default, help, short_name=None, **args): + p = BooleanParser() + Flag.__init__(self, p, None, name, default, help, short_name, 1, **args) + if not self.help: self.help = "a boolean value" + + +def DEFINE_boolean(name, default, help, flag_values=FLAGS, **args): + """Registers a boolean flag. + + Such a boolean flag does not take an argument. If a user wants to + specify a false value explicitly, the long option beginning with 'no' + must be used: i.e. --noflag + + This flag will have a value of None, True or False. None is possible + if default=None and the user does not specify the flag on the command + line. + """ + DEFINE_flag(BooleanFlag(name, default, help, **args), flag_values) + +# Match C++ API to unconfuse C++ people. +DEFINE_bool = DEFINE_boolean + +class HelpFlag(BooleanFlag): + """ + HelpFlag is a special boolean flag that prints usage information and + raises a SystemExit exception if it is ever found in the command + line arguments. Note this is called with allow_override=1, so other + apps can define their own --help flag, replacing this one, if they want. + """ + def __init__(self): + BooleanFlag.__init__(self, "help", 0, "show this help", + short_name="?", allow_override=1) + def Parse(self, arg): + if arg: + doc = sys.modules["__main__"].__doc__ + flags = str(FLAGS) + print doc or ("\nUSAGE: %s [flags]\n" % sys.argv[0]) + if flags: + print "flags:" + print flags + sys.exit(1) + + +class HelpXMLFlag(BooleanFlag): + """Similar to HelpFlag, but generates output in XML format.""" + + def __init__(self): + BooleanFlag.__init__(self, 'helpxml', False, + 'like --help, but generates XML output', + allow_override=1) + + def Parse(self, arg): + if arg: + FLAGS.WriteHelpInXMLFormat(sys.stdout) + sys.exit(1) + + +class HelpshortFlag(BooleanFlag): + """ + HelpshortFlag is a special boolean flag that prints usage + information for the "main" module, and rasies a SystemExit exception + if it is ever found in the command line arguments. Note this is + called with allow_override=1, so other apps can define their own + --helpshort flag, replacing this one, if they want. + """ + def __init__(self): + BooleanFlag.__init__(self, "helpshort", 0, + "show usage only for this module", allow_override=1) + def Parse(self, arg): + if arg: + doc = sys.modules["__main__"].__doc__ + flags = FLAGS.MainModuleHelp() + print doc or ("\nUSAGE: %s [flags]\n" % sys.argv[0]) + if flags: + print "flags:" + print flags + sys.exit(1) + +# +# Numeric parser - base class for Integer and Float parsers +# + + +class NumericParser(ArgumentParser): + """Parser of numeric values. + + Parsed value may be bounded to a given upper and lower bound. + """ + + def Parse(self, argument): + val = self.Convert(argument) + if ((self.lower_bound is not None and val < self.lower_bound) or + (self.upper_bound is not None and val > self.upper_bound)): + raise ValueError("%s is not %s" % (val, self.syntactic_help)) + return val + + def WriteCustomInfoInXMLFormat(self, outfile, indent): + if self.lower_bound is not None: + _WriteSimpleXMLElement(outfile, 'lower_bound', self.lower_bound, indent) + if self.upper_bound is not None: + _WriteSimpleXMLElement(outfile, 'upper_bound', self.upper_bound, indent) + + def Convert(self, argument): + """Default implementation: always returns its argument unmodified.""" + return argument + +# End of Numeric Parser + +# +# FLOAT FLAGS +# + +class FloatParser(NumericParser): + """Parser of floating point values. + + Parsed value may be bounded to a given upper and lower bound. + """ + number_article = "a" + number_name = "number" + syntactic_help = " ".join((number_article, number_name)) + + def __init__(self, lower_bound=None, upper_bound=None): + self.lower_bound = lower_bound + self.upper_bound = upper_bound + sh = self.syntactic_help + if lower_bound is not None and upper_bound is not None: + sh = ("%s in the range [%s, %s]" % (sh, lower_bound, upper_bound)) + elif lower_bound == 0: + sh = "a non-negative %s" % self.number_name + elif upper_bound == 0: + sh = "a non-positive %s" % self.number_name + elif upper_bound is not None: + sh = "%s <= %s" % (self.number_name, upper_bound) + elif lower_bound is not None: + sh = "%s >= %s" % (self.number_name, lower_bound) + self.syntactic_help = sh + + def Convert(self, argument): + """Converts argument to a float; raises ValueError on errors.""" + return float(argument) + + def Type(self): + return 'float' +# End of FloatParser + + +def DEFINE_float(name, default, help, lower_bound=None, upper_bound=None, + flag_values=FLAGS, **args): + """Registers a flag whose value must be a float. + + If lower_bound or upper_bound are set, then this flag must be + within the given range. + """ + parser = FloatParser(lower_bound, upper_bound) + serializer = ArgumentSerializer() + DEFINE(parser, name, default, help, flag_values, serializer, **args) + + +# +# INTEGER FLAGS +# + + +class IntegerParser(NumericParser): + """Parser of an integer value. + + Parsed value may be bounded to a given upper and lower bound. + """ + number_article = "an" + number_name = "integer" + syntactic_help = " ".join((number_article, number_name)) + + def __init__(self, lower_bound=None, upper_bound=None): + self.lower_bound = lower_bound + self.upper_bound = upper_bound + sh = self.syntactic_help + if lower_bound is not None and upper_bound is not None: + sh = ("%s in the range [%s, %s]" % (sh, lower_bound, upper_bound)) + elif lower_bound == 1: + sh = "a positive %s" % self.number_name + elif upper_bound == -1: + sh = "a negative %s" % self.number_name + elif lower_bound == 0: + sh = "a non-negative %s" % self.number_name + elif upper_bound == 0: + sh = "a non-positive %s" % self.number_name + elif upper_bound is not None: + sh = "%s <= %s" % (self.number_name, upper_bound) + elif lower_bound is not None: + sh = "%s >= %s" % (self.number_name, lower_bound) + self.syntactic_help = sh + + def Convert(self, argument): + __pychecker__ = 'no-returnvalues' + if type(argument) == str: + base = 10 + if len(argument) > 2 and argument[0] == "0" and argument[1] == "x": + base = 16 + try: + return int(argument, base) + # ValueError is thrown when argument is a string, and overflows an int. + except ValueError: + return long(argument, base) + else: + try: + return int(argument) + # OverflowError is thrown when argument is numeric, and overflows an int. + except OverflowError: + return long(argument) + + def Type(self): + return 'int' + + +def DEFINE_integer(name, default, help, lower_bound=None, upper_bound=None, + flag_values=FLAGS, **args): + """Registers a flag whose value must be an integer. + + If lower_bound, or upper_bound are set, then this flag must be + within the given range. + """ + parser = IntegerParser(lower_bound, upper_bound) + serializer = ArgumentSerializer() + DEFINE(parser, name, default, help, flag_values, serializer, **args) + + +# +# ENUM FLAGS +# + + +class EnumParser(ArgumentParser): + """Parser of a string enum value (a string value from a given set). + + If enum_values (see below) is not specified, any string is allowed. + """ + + def __init__(self, enum_values=None): + self.enum_values = enum_values + + def Parse(self, argument): + if self.enum_values and argument not in self.enum_values: + raise ValueError("value should be one of <%s>" % + "|".join(self.enum_values)) + return argument + + def Type(self): + return 'string enum' + + +class EnumFlag(Flag): + """Basic enum flag; its value can be any string from list of enum_values.""" + + def __init__(self, name, default, help, enum_values=None, + short_name=None, **args): + enum_values = enum_values or [] + p = EnumParser(enum_values) + g = ArgumentSerializer() + Flag.__init__(self, p, g, name, default, help, short_name, **args) + if not self.help: self.help = "an enum string" + self.help = "<%s>: %s" % ("|".join(enum_values), self.help) + + def _WriteCustomInfoInXMLFormat(self, outfile, indent): + for enum_value in self.parser.enum_values: + _WriteSimpleXMLElement(outfile, 'enum_value', enum_value, indent) + + +def DEFINE_enum(name, default, enum_values, help, flag_values=FLAGS, + **args): + """Registers a flag whose value can be any string from enum_values.""" + DEFINE_flag(EnumFlag(name, default, help, enum_values, ** args), + flag_values) + + +# +# LIST FLAGS +# + + +class BaseListParser(ArgumentParser): + """Base class for a parser of lists of strings. + + To extend, inherit from this class; from the subclass __init__, call + + BaseListParser.__init__(self, token, name) + + where token is a character used to tokenize, and name is a description + of the separator. + """ + + def __init__(self, token=None, name=None): + assert name + self._token = token + self._name = name + self.syntactic_help = "a %s separated list" % self._name + + def Parse(self, argument): + if isinstance(argument, list): + return argument + elif argument == '': + return [] + else: + return [s.strip() for s in argument.split(self._token)] + + def Type(self): + return '%s separated list of strings' % self._name + + +class ListParser(BaseListParser): + """Parser for a comma-separated list of strings.""" + + def __init__(self): + BaseListParser.__init__(self, ',', 'comma') + + def WriteCustomInfoInXMLFormat(self, outfile, indent): + BaseListParser.WriteCustomInfoInXMLFormat(self, outfile, indent) + _WriteSimpleXMLElement(outfile, 'list_separator', repr(','), indent) + + +class WhitespaceSeparatedListParser(BaseListParser): + """Parser for a whitespace-separated list of strings.""" + + def __init__(self): + BaseListParser.__init__(self, None, 'whitespace') + + def WriteCustomInfoInXMLFormat(self, outfile, indent): + BaseListParser.WriteCustomInfoInXMLFormat(self, outfile, indent) + separators = list(string.whitespace) + separators.sort() + for ws_char in string.whitespace: + _WriteSimpleXMLElement(outfile, 'list_separator', repr(ws_char), indent) + + +def DEFINE_list(name, default, help, flag_values=FLAGS, **args): + """Registers a flag whose value is a comma-separated list of strings.""" + parser = ListParser() + serializer = ListSerializer(',') + DEFINE(parser, name, default, help, flag_values, serializer, **args) + + +def DEFINE_spaceseplist(name, default, help, flag_values=FLAGS, **args): + """Registers a flag whose value is a whitespace-separated list of strings. + + Any whitespace can be used as a separator. + """ + parser = WhitespaceSeparatedListParser() + serializer = ListSerializer(' ') + DEFINE(parser, name, default, help, flag_values, serializer, **args) + + +# +# MULTI FLAGS +# + + +class MultiFlag(Flag): + """A flag that can appear multiple time on the command-line. + + The value of such a flag is a list that contains the individual values + from all the appearances of that flag on the command-line. + + See the __doc__ for Flag for most behavior of this class. Only + differences in behavior are described here: + + * The default value may be either a single value or a list of values. + A single value is interpreted as the [value] singleton list. + + * The value of the flag is always a list, even if the option was + only supplied once, and even if the default value is a single + value + """ + + def __init__(self, *args, **kwargs): + Flag.__init__(self, *args, **kwargs) + self.help += ';\n repeat this option to specify a list of values' + + def Parse(self, arguments): + """Parses one or more arguments with the installed parser. + + Args: + arguments: a single argument or a list of arguments (typically a + list of default values); a single argument is converted + internally into a list containing one item. + """ + if not isinstance(arguments, list): + # Default value may be a list of values. Most other arguments + # will not be, so convert them into a single-item list to make + # processing simpler below. + arguments = [arguments] + + if self.present: + # keep a backup reference to list of previously supplied option values + values = self.value + else: + # "erase" the defaults with an empty list + values = [] + + for item in arguments: + # have Flag superclass parse argument, overwriting self.value reference + Flag.Parse(self, item) # also increments self.present + values.append(self.value) + + # put list of option values back in the 'value' attribute + self.value = values + + def Serialize(self): + if not self.serializer: + raise FlagsError("Serializer not present for flag %s" % self.name) + if self.value is None: + return '' + + s = '' + + multi_value = self.value + + for self.value in multi_value: + if s: s += ' ' + s += Flag.Serialize(self) + + self.value = multi_value + + return s + + def Type(self): + return 'multi ' + self.parser.Type() + + +def DEFINE_multi(parser, serializer, name, default, help, flag_values=FLAGS, + **args): + """Registers a generic MultiFlag that parses its args with a given parser. + + Auxiliary function. Normal users should NOT use it directly. + + Developers who need to create their own 'Parser' classes for options + which can appear multiple times can call this module function to + register their flags. + """ + DEFINE_flag(MultiFlag(parser, serializer, name, default, help, **args), + flag_values) + + +def DEFINE_multistring(name, default, help, flag_values=FLAGS, **args): + """Registers a flag whose value can be a list of any strings. + + Use the flag on the command line multiple times to place multiple + string values into the list. The 'default' may be a single string + (which will be converted into a single-element list) or a list of + strings. + """ + parser = ArgumentParser() + serializer = ArgumentSerializer() + DEFINE_multi(parser, serializer, name, default, help, flag_values, **args) + + +def DEFINE_multi_int(name, default, help, lower_bound=None, upper_bound=None, + flag_values=FLAGS, **args): + """Registers a flag whose value can be a list of arbitrary integers. + + Use the flag on the command line multiple times to place multiple + integer values into the list. The 'default' may be a single integer + (which will be converted into a single-element list) or a list of + integers. + """ + parser = IntegerParser(lower_bound, upper_bound) + serializer = ArgumentSerializer() + DEFINE_multi(parser, serializer, name, default, help, flag_values, **args) + + +# Now register the flags that we want to exist in all applications. +# These are all defined with allow_override=1, so user-apps can use +# these flagnames for their own purposes, if they want. +DEFINE_flag(HelpFlag()) +DEFINE_flag(HelpshortFlag()) +DEFINE_flag(HelpXMLFlag()) + +# Define special flags here so that help may be generated for them. +# NOTE: Please do NOT use _SPECIAL_FLAGS from outside this module. +_SPECIAL_FLAGS = FlagValues() + + +DEFINE_string( + 'flagfile', "", + "Insert flag definitions from the given file into the command line.", + _SPECIAL_FLAGS) + +DEFINE_string( + 'undefok', "", + "comma-separated list of flag names that it is okay to specify " + "on the command line even if the program does not define a flag " + "with that name. IMPORTANT: flags in this list that have " + "arguments MUST use the --flag=value format.", _SPECIAL_FLAGS) diff --git a/node-v0.8.14/tools/closure_linter/setup.cfg b/node-v0.8.14/tools/closure_linter/setup.cfg new file mode 100644 index 0000000..861a9f5 --- /dev/null +++ b/node-v0.8.14/tools/closure_linter/setup.cfg @@ -0,0 +1,5 @@ +[egg_info] +tag_build = +tag_date = 0 +tag_svn_revision = 0 + diff --git a/node-v0.8.14/tools/closure_linter/setup.py b/node-v0.8.14/tools/closure_linter/setup.py new file mode 100755 index 0000000..1d1764f --- /dev/null +++ b/node-v0.8.14/tools/closure_linter/setup.py @@ -0,0 +1,38 @@ +#!/usr/bin/env python +# +# Copyright 2010 The Closure Linter Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS-IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +try: + from setuptools import setup +except ImportError: + from distutils.core import setup + +setup(name='closure_linter', + version='2.2.6', + description='Closure Linter', + license='Apache', + author='The Closure Linter Authors', + author_email='opensource@google.com', + url='http://code.google.com/p/closure-linter', + install_requires=['python-gflags'], + package_dir={'closure_linter': 'closure_linter'}, + packages=['closure_linter', 'closure_linter.common'], + entry_points = { + 'console_scripts': [ + 'gjslint = closure_linter.gjslint:main', + 'fixjsstyle = closure_linter.fixjsstyle:main' + ] + } +) diff --git a/node-v0.8.14/tools/cpplint.py b/node-v0.8.14/tools/cpplint.py new file mode 100644 index 0000000..86154ed --- /dev/null +++ b/node-v0.8.14/tools/cpplint.py @@ -0,0 +1,3126 @@ +#!/usr/bin/python2.4 +# +# Copyright (c) 2009 Google Inc. All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above +# copyright notice, this list of conditions and the following disclaimer +# in the documentation and/or other materials provided with the +# distribution. +# * Neither the name of Google Inc. nor the names of its +# contributors may be used to endorse or promote products derived from +# this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +# Here are some issues that I've had people identify in my code during reviews, +# that I think are possible to flag automatically in a lint tool. If these were +# caught by lint, it would save time both for myself and that of my reviewers. +# Most likely, some of these are beyond the scope of the current lint framework, +# but I think it is valuable to retain these wish-list items even if they cannot +# be immediately implemented. +# +# Suggestions +# ----------- +# - Check for no 'explicit' for multi-arg ctor +# - Check for boolean assign RHS in parens +# - Check for ctor initializer-list colon position and spacing +# - Check that if there's a ctor, there should be a dtor +# - Check accessors that return non-pointer member variables are +# declared const +# - Check accessors that return non-const pointer member vars are +# *not* declared const +# - Check for using public includes for testing +# - Check for spaces between brackets in one-line inline method +# - Check for no assert() +# - Check for spaces surrounding operators +# - Check for 0 in pointer context (should be NULL) +# - Check for 0 in char context (should be '\0') +# - Check for camel-case method name conventions for methods +# that are not simple inline getters and setters +# - Check that base classes have virtual destructors +# put " // namespace" after } that closes a namespace, with +# namespace's name after 'namespace' if it is named. +# - Do not indent namespace contents +# - Avoid inlining non-trivial constructors in header files +# include base/basictypes.h if DISALLOW_EVIL_CONSTRUCTORS is used +# - Check for old-school (void) cast for call-sites of functions +# ignored return value +# - Check gUnit usage of anonymous namespace +# - Check for class declaration order (typedefs, consts, enums, +# ctor(s?), dtor, friend declarations, methods, member vars) +# + +"""Does google-lint on c++ files. + +The goal of this script is to identify places in the code that *may* +be in non-compliance with google style. It does not attempt to fix +up these problems -- the point is to educate. It does also not +attempt to find all problems, or to ensure that everything it does +find is legitimately a problem. + +In particular, we can get very confused by /* and // inside strings! +We do a small hack, which is to ignore //'s with "'s after them on the +same line, but it is far from perfect (in either direction). +""" + +import codecs +import getopt +import math # for log +import os +import re +import sre_compile +import string +import sys +import unicodedata + + +_USAGE = """ +Syntax: cpplint.py [--verbose=#] [--output=vs7] [--filter=-x,+y,...] + [--counting=total|toplevel|detailed] + [file] ... + + The style guidelines this tries to follow are those in + http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml + + Every problem is given a confidence score from 1-5, with 5 meaning we are + certain of the problem, and 1 meaning it could be a legitimate construct. + This will miss some errors, and is not a substitute for a code review. + + To suppress false-positive errors of a certain category, add a + 'NOLINT(category)' comment to the line. NOLINT or NOLINT(*) + suppresses errors of all categories on that line. + + The files passed in will be linted; at least one file must be provided. + Linted extensions are .cc, .cpp, and .h. Other file types will be ignored. + + Flags: + + output=vs7 + By default, the output is formatted to ease emacs parsing. Visual Studio + compatible output (vs7) may also be used. Other formats are unsupported. + + verbose=# + Specify a number 0-5 to restrict errors to certain verbosity levels. + + filter=-x,+y,... + Specify a comma-separated list of category-filters to apply: only + error messages whose category names pass the filters will be printed. + (Category names are printed with the message and look like + "[whitespace/indent]".) Filters are evaluated left to right. + "-FOO" and "FOO" means "do not print categories that start with FOO". + "+FOO" means "do print categories that start with FOO". + + Examples: --filter=-whitespace,+whitespace/braces + --filter=whitespace,runtime/printf,+runtime/printf_format + --filter=-,+build/include_what_you_use + + To see a list of all the categories used in cpplint, pass no arg: + --filter= + + counting=total|toplevel|detailed + The total number of errors found is always printed. If + 'toplevel' is provided, then the count of errors in each of + the top-level categories like 'build' and 'whitespace' will + also be printed. If 'detailed' is provided, then a count + is provided for each category like 'build/class'. +""" + +# We categorize each error message we print. Here are the categories. +# We want an explicit list so we can list them all in cpplint --filter=. +# If you add a new error message with a new category, add it to the list +# here! cpplint_unittest.py should tell you if you forget to do this. +# \ used for clearer layout -- pylint: disable-msg=C6013 +_ERROR_CATEGORIES = [ + 'build/class', + 'build/deprecated', + 'build/endif_comment', + 'build/forward_decl', + 'build/header_guard', + 'build/include', + 'build/include_alpha', + 'build/include_order', + 'build/include_what_you_use', + 'build/namespaces', + 'build/printf_format', + 'build/storage_class', + 'legal/copyright', + 'readability/braces', + 'readability/casting', + 'readability/check', + 'readability/constructors', + 'readability/fn_size', + 'readability/function', + 'readability/multiline_comment', + 'readability/multiline_string', + 'readability/nolint', + 'readability/streams', + 'readability/todo', + 'readability/utf8', + 'runtime/arrays', + 'runtime/casting', + 'runtime/explicit', + 'runtime/int', + 'runtime/init', + 'runtime/invalid_increment', + 'runtime/member_string_references', + 'runtime/memset', + 'runtime/operator', + 'runtime/printf', + 'runtime/printf_format', + 'runtime/references', + 'runtime/rtti', + 'runtime/sizeof', + 'runtime/string', + 'runtime/threadsafe_fn', + 'runtime/virtual', + 'whitespace/blank_line', + 'whitespace/braces', + 'whitespace/comma', + 'whitespace/comments', + 'whitespace/end_of_line', + 'whitespace/ending_newline', + 'whitespace/indent', + 'whitespace/labels', + 'whitespace/line_length', + 'whitespace/newline', + 'whitespace/operators', + 'whitespace/parens', + 'whitespace/semicolon', + 'whitespace/tab', + 'whitespace/todo' + ] + +# The default state of the category filter. This is overrided by the --filter= +# flag. By default all errors are on, so only add here categories that should be +# off by default (i.e., categories that must be enabled by the --filter= flags). +# All entries here should start with a '-' or '+', as in the --filter= flag. +_DEFAULT_FILTERS = [ '-build/include_alpha' ] + +# We used to check for high-bit characters, but after much discussion we +# decided those were OK, as long as they were in UTF-8 and didn't represent +# hard-coded international strings, which belong in a seperate i18n file. + +# Headers that we consider STL headers. +_STL_HEADERS = frozenset([ + 'algobase.h', 'algorithm', 'alloc.h', 'bitset', 'deque', 'exception', + 'function.h', 'functional', 'hash_map', 'hash_map.h', 'hash_set', + 'hash_set.h', 'iterator', 'list', 'list.h', 'map', 'memory', 'new', + 'pair.h', 'pthread_alloc', 'queue', 'set', 'set.h', 'sstream', 'stack', + 'stl_alloc.h', 'stl_relops.h', 'type_traits.h', + 'utility', 'vector', 'vector.h', + ]) + + +# Non-STL C++ system headers. +_CPP_HEADERS = frozenset([ + 'algo.h', 'builtinbuf.h', 'bvector.h', 'cassert', 'cctype', + 'cerrno', 'cfloat', 'ciso646', 'climits', 'clocale', 'cmath', + 'complex', 'complex.h', 'csetjmp', 'csignal', 'cstdarg', 'cstddef', + 'cstdio', 'cstdlib', 'cstring', 'ctime', 'cwchar', 'cwctype', + 'defalloc.h', 'deque.h', 'editbuf.h', 'exception', 'fstream', + 'fstream.h', 'hashtable.h', 'heap.h', 'indstream.h', 'iomanip', + 'iomanip.h', 'ios', 'iosfwd', 'iostream', 'iostream.h', 'istream.h', + 'iterator.h', 'limits', 'map.h', 'multimap.h', 'multiset.h', + 'numeric', 'ostream.h', 'parsestream.h', 'pfstream.h', 'PlotFile.h', + 'procbuf.h', 'pthread_alloc.h', 'rope', 'rope.h', 'ropeimpl.h', + 'SFile.h', 'slist', 'slist.h', 'stack.h', 'stdexcept', + 'stdiostream.h', 'streambuf.h', 'stream.h', 'strfile.h', 'string', + 'strstream', 'strstream.h', 'tempbuf.h', 'tree.h', 'typeinfo', 'valarray', + ]) + + +# Assertion macros. These are defined in base/logging.h and +# testing/base/gunit.h. Note that the _M versions need to come first +# for substring matching to work. +_CHECK_MACROS = [ + 'DCHECK', 'CHECK', + 'EXPECT_TRUE_M', 'EXPECT_TRUE', + 'ASSERT_TRUE_M', 'ASSERT_TRUE', + 'EXPECT_FALSE_M', 'EXPECT_FALSE', + 'ASSERT_FALSE_M', 'ASSERT_FALSE', + ] + +# Replacement macros for CHECK/DCHECK/EXPECT_TRUE/EXPECT_FALSE +_CHECK_REPLACEMENT = dict([(m, {}) for m in _CHECK_MACROS]) + +for op, replacement in [('==', 'EQ'), ('!=', 'NE'), + ('>=', 'GE'), ('>', 'GT'), + ('<=', 'LE'), ('<', 'LT')]: + _CHECK_REPLACEMENT['DCHECK'][op] = 'DCHECK_%s' % replacement + _CHECK_REPLACEMENT['CHECK'][op] = 'CHECK_%s' % replacement + _CHECK_REPLACEMENT['EXPECT_TRUE'][op] = 'EXPECT_%s' % replacement + _CHECK_REPLACEMENT['ASSERT_TRUE'][op] = 'ASSERT_%s' % replacement + _CHECK_REPLACEMENT['EXPECT_TRUE_M'][op] = 'EXPECT_%s_M' % replacement + _CHECK_REPLACEMENT['ASSERT_TRUE_M'][op] = 'ASSERT_%s_M' % replacement + +for op, inv_replacement in [('==', 'NE'), ('!=', 'EQ'), + ('>=', 'LT'), ('>', 'LE'), + ('<=', 'GT'), ('<', 'GE')]: + _CHECK_REPLACEMENT['EXPECT_FALSE'][op] = 'EXPECT_%s' % inv_replacement + _CHECK_REPLACEMENT['ASSERT_FALSE'][op] = 'ASSERT_%s' % inv_replacement + _CHECK_REPLACEMENT['EXPECT_FALSE_M'][op] = 'EXPECT_%s_M' % inv_replacement + _CHECK_REPLACEMENT['ASSERT_FALSE_M'][op] = 'ASSERT_%s_M' % inv_replacement + + +# These constants define types of headers for use with +# _IncludeState.CheckNextIncludeOrder(). +_C_SYS_HEADER = 1 +_CPP_SYS_HEADER = 2 +_LIKELY_MY_HEADER = 3 +_POSSIBLE_MY_HEADER = 4 +_OTHER_HEADER = 5 + + +_regexp_compile_cache = {} + +# Finds occurrences of NOLINT or NOLINT(...). +_RE_SUPPRESSION = re.compile(r'\bNOLINT\b(\([^)]*\))?') + +# {str, set(int)}: a map from error categories to sets of linenumbers +# on which those errors are expected and should be suppressed. +_error_suppressions = {} + +def ParseNolintSuppressions(filename, raw_line, linenum, error): + """Updates the global list of error-suppressions. + + Parses any NOLINT comments on the current line, updating the global + error_suppressions store. Reports an error if the NOLINT comment + was malformed. + + Args: + filename: str, the name of the input file. + raw_line: str, the line of input text, with comments. + linenum: int, the number of the current line. + error: function, an error handler. + """ + # FIXME(adonovan): "NOLINT(" is misparsed as NOLINT(*). + m = _RE_SUPPRESSION.search(raw_line) + if m: + category = m.group(1) + if category in (None, '(*)'): # => "suppress all" + _error_suppressions.setdefault(None, set()).add(linenum) + else: + if category.startswith('(') and category.endswith(')'): + category = category[1:-1] + if category in _ERROR_CATEGORIES: + _error_suppressions.setdefault(category, set()).add(linenum) + else: + error(filename, linenum, 'readability/nolint', 5, + 'Unknown NOLINT error category: %s' % category) + + +def ResetNolintSuppressions(): + "Resets the set of NOLINT suppressions to empty." + _error_suppressions.clear() + + +def IsErrorSuppressedByNolint(category, linenum): + """Returns true if the specified error category is suppressed on this line. + + Consults the global error_suppressions map populated by + ParseNolintSuppressions/ResetNolintSuppressions. + + Args: + category: str, the category of the error. + linenum: int, the current line number. + Returns: + bool, True iff the error should be suppressed due to a NOLINT comment. + """ + return (linenum in _error_suppressions.get(category, set()) or + linenum in _error_suppressions.get(None, set())) + +def Match(pattern, s): + """Matches the string with the pattern, caching the compiled regexp.""" + # The regexp compilation caching is inlined in both Match and Search for + # performance reasons; factoring it out into a separate function turns out + # to be noticeably expensive. + if not pattern in _regexp_compile_cache: + _regexp_compile_cache[pattern] = sre_compile.compile(pattern) + return _regexp_compile_cache[pattern].match(s) + + +def Search(pattern, s): + """Searches the string for the pattern, caching the compiled regexp.""" + if not pattern in _regexp_compile_cache: + _regexp_compile_cache[pattern] = sre_compile.compile(pattern) + return _regexp_compile_cache[pattern].search(s) + + +class _IncludeState(dict): + """Tracks line numbers for includes, and the order in which includes appear. + + As a dict, an _IncludeState object serves as a mapping between include + filename and line number on which that file was included. + + Call CheckNextIncludeOrder() once for each header in the file, passing + in the type constants defined above. Calls in an illegal order will + raise an _IncludeError with an appropriate error message. + + """ + # self._section will move monotonically through this set. If it ever + # needs to move backwards, CheckNextIncludeOrder will raise an error. + _INITIAL_SECTION = 0 + _MY_H_SECTION = 1 + _C_SECTION = 2 + _CPP_SECTION = 3 + _OTHER_H_SECTION = 4 + + _TYPE_NAMES = { + _C_SYS_HEADER: 'C system header', + _CPP_SYS_HEADER: 'C++ system header', + _LIKELY_MY_HEADER: 'header this file implements', + _POSSIBLE_MY_HEADER: 'header this file may implement', + _OTHER_HEADER: 'other header', + } + _SECTION_NAMES = { + _INITIAL_SECTION: "... nothing. (This can't be an error.)", + _MY_H_SECTION: 'a header this file implements', + _C_SECTION: 'C system header', + _CPP_SECTION: 'C++ system header', + _OTHER_H_SECTION: 'other header', + } + + def __init__(self): + dict.__init__(self) + # The name of the current section. + self._section = self._INITIAL_SECTION + # The path of last found header. + self._last_header = '' + + def CanonicalizeAlphabeticalOrder(self, header_path): + """Returns a path canonicalized for alphabetical comparisson. + + - replaces "-" with "_" so they both cmp the same. + - removes '-inl' since we don't require them to be after the main header. + - lowercase everything, just in case. + + Args: + header_path: Path to be canonicalized. + + Returns: + Canonicalized path. + """ + return header_path.replace('-inl.h', '.h').replace('-', '_').lower() + + def IsInAlphabeticalOrder(self, header_path): + """Check if a header is in alphabetical order with the previous header. + + Args: + header_path: Header to be checked. + + Returns: + Returns true if the header is in alphabetical order. + """ + canonical_header = self.CanonicalizeAlphabeticalOrder(header_path) + if self._last_header > canonical_header: + return False + self._last_header = canonical_header + return True + + def CheckNextIncludeOrder(self, header_type): + """Returns a non-empty error message if the next header is out of order. + + This function also updates the internal state to be ready to check + the next include. + + Args: + header_type: One of the _XXX_HEADER constants defined above. + + Returns: + The empty string if the header is in the right order, or an + error message describing what's wrong. + + """ + error_message = ('Found %s after %s' % + (self._TYPE_NAMES[header_type], + self._SECTION_NAMES[self._section])) + + last_section = self._section + + if header_type == _C_SYS_HEADER: + if self._section <= self._C_SECTION: + self._section = self._C_SECTION + else: + self._last_header = '' + return error_message + elif header_type == _CPP_SYS_HEADER: + if self._section <= self._CPP_SECTION: + self._section = self._CPP_SECTION + else: + self._last_header = '' + return error_message + elif header_type == _LIKELY_MY_HEADER: + if self._section <= self._MY_H_SECTION: + self._section = self._MY_H_SECTION + else: + self._section = self._OTHER_H_SECTION + elif header_type == _POSSIBLE_MY_HEADER: + if self._section <= self._MY_H_SECTION: + self._section = self._MY_H_SECTION + else: + # This will always be the fallback because we're not sure + # enough that the header is associated with this file. + self._section = self._OTHER_H_SECTION + else: + assert header_type == _OTHER_HEADER + self._section = self._OTHER_H_SECTION + + if last_section != self._section: + self._last_header = '' + + return '' + + +class _CppLintState(object): + """Maintains module-wide state..""" + + def __init__(self): + self.verbose_level = 1 # global setting. + self.error_count = 0 # global count of reported errors + # filters to apply when emitting error messages + self.filters = _DEFAULT_FILTERS[:] + self.counting = 'total' # In what way are we counting errors? + self.errors_by_category = {} # string to int dict storing error counts + + # output format: + # "emacs" - format that emacs can parse (default) + # "vs7" - format that Microsoft Visual Studio 7 can parse + self.output_format = 'emacs' + + def SetOutputFormat(self, output_format): + """Sets the output format for errors.""" + self.output_format = output_format + + def SetVerboseLevel(self, level): + """Sets the module's verbosity, and returns the previous setting.""" + last_verbose_level = self.verbose_level + self.verbose_level = level + return last_verbose_level + + def SetCountingStyle(self, counting_style): + """Sets the module's counting options.""" + self.counting = counting_style + + def SetFilters(self, filters): + """Sets the error-message filters. + + These filters are applied when deciding whether to emit a given + error message. + + Args: + filters: A string of comma-separated filters (eg "+whitespace/indent"). + Each filter should start with + or -; else we die. + + Raises: + ValueError: The comma-separated filters did not all start with '+' or '-'. + E.g. "-,+whitespace,-whitespace/indent,whitespace/badfilter" + """ + # Default filters always have less priority than the flag ones. + self.filters = _DEFAULT_FILTERS[:] + for filt in filters.split(','): + clean_filt = filt.strip() + if clean_filt: + self.filters.append(clean_filt) + for filt in self.filters: + if not (filt.startswith('+') or filt.startswith('-')): + raise ValueError('Every filter in --filters must start with + or -' + ' (%s does not)' % filt) + + def ResetErrorCounts(self): + """Sets the module's error statistic back to zero.""" + self.error_count = 0 + self.errors_by_category = {} + + def IncrementErrorCount(self, category): + """Bumps the module's error statistic.""" + self.error_count += 1 + if self.counting in ('toplevel', 'detailed'): + if self.counting != 'detailed': + category = category.split('/')[0] + if category not in self.errors_by_category: + self.errors_by_category[category] = 0 + self.errors_by_category[category] += 1 + + def PrintErrorCounts(self): + """Print a summary of errors by category, and the total.""" + for category, count in self.errors_by_category.iteritems(): + sys.stderr.write('Category \'%s\' errors found: %d\n' % + (category, count)) + sys.stderr.write('Total errors found: %d\n' % self.error_count) + +_cpplint_state = _CppLintState() + + +def _OutputFormat(): + """Gets the module's output format.""" + return _cpplint_state.output_format + + +def _SetOutputFormat(output_format): + """Sets the module's output format.""" + _cpplint_state.SetOutputFormat(output_format) + + +def _VerboseLevel(): + """Returns the module's verbosity setting.""" + return _cpplint_state.verbose_level + + +def _SetVerboseLevel(level): + """Sets the module's verbosity, and returns the previous setting.""" + return _cpplint_state.SetVerboseLevel(level) + + +def _SetCountingStyle(level): + """Sets the module's counting options.""" + _cpplint_state.SetCountingStyle(level) + + +def _Filters(): + """Returns the module's list of output filters, as a list.""" + return _cpplint_state.filters + + +def _SetFilters(filters): + """Sets the module's error-message filters. + + These filters are applied when deciding whether to emit a given + error message. + + Args: + filters: A string of comma-separated filters (eg "whitespace/indent"). + Each filter should start with + or -; else we die. + """ + _cpplint_state.SetFilters(filters) + + +class _FunctionState(object): + """Tracks current function name and the number of lines in its body.""" + + _NORMAL_TRIGGER = 250 # for --v=0, 500 for --v=1, etc. + _TEST_TRIGGER = 400 # about 50% more than _NORMAL_TRIGGER. + + def __init__(self): + self.in_a_function = False + self.lines_in_function = 0 + self.current_function = '' + + def Begin(self, function_name): + """Start analyzing function body. + + Args: + function_name: The name of the function being tracked. + """ + self.in_a_function = True + self.lines_in_function = 0 + self.current_function = function_name + + def Count(self): + """Count line in current function body.""" + if self.in_a_function: + self.lines_in_function += 1 + + def Check(self, error, filename, linenum): + """Report if too many lines in function body. + + Args: + error: The function to call with any errors found. + filename: The name of the current file. + linenum: The number of the line to check. + """ + if Match(r'T(EST|est)', self.current_function): + base_trigger = self._TEST_TRIGGER + else: + base_trigger = self._NORMAL_TRIGGER + trigger = base_trigger * 2**_VerboseLevel() + + if self.lines_in_function > trigger: + error_level = int(math.log(self.lines_in_function / base_trigger, 2)) + # 50 => 0, 100 => 1, 200 => 2, 400 => 3, 800 => 4, 1600 => 5, ... + if error_level > 5: + error_level = 5 + error(filename, linenum, 'readability/fn_size', error_level, + 'Small and focused functions are preferred:' + ' %s has %d non-comment lines' + ' (error triggered by exceeding %d lines).' % ( + self.current_function, self.lines_in_function, trigger)) + + def End(self): + """Stop analizing function body.""" + self.in_a_function = False + + +class _IncludeError(Exception): + """Indicates a problem with the include order in a file.""" + pass + + +class FileInfo: + """Provides utility functions for filenames. + + FileInfo provides easy access to the components of a file's path + relative to the project root. + """ + + def __init__(self, filename): + self._filename = filename + + def FullName(self): + """Make Windows paths like Unix.""" + return os.path.abspath(self._filename).replace('\\', '/') + + def RepositoryName(self): + """FullName after removing the local path to the repository. + + If we have a real absolute path name here we can try to do something smart: + detecting the root of the checkout and truncating /path/to/checkout from + the name so that we get header guards that don't include things like + "C:\Documents and Settings\..." or "/home/username/..." in them and thus + people on different computers who have checked the source out to different + locations won't see bogus errors. + """ + fullname = self.FullName() + + if os.path.exists(fullname): + project_dir = os.path.dirname(fullname) + + if os.path.exists(os.path.join(project_dir, ".svn")): + # If there's a .svn file in the current directory, we recursively look + # up the directory tree for the top of the SVN checkout + root_dir = project_dir + one_up_dir = os.path.dirname(root_dir) + while os.path.exists(os.path.join(one_up_dir, ".svn")): + root_dir = os.path.dirname(root_dir) + one_up_dir = os.path.dirname(one_up_dir) + + prefix = os.path.commonprefix([root_dir, project_dir]) + return fullname[len(prefix) + 1:] + + # Not SVN? Try to find a git or hg top level directory by searching up + # from the current path. + root_dir = os.path.dirname(fullname) + while (root_dir != os.path.dirname(root_dir) and + not os.path.exists(os.path.join(root_dir, ".git")) and + not os.path.exists(os.path.join(root_dir, ".hg"))): + root_dir = os.path.dirname(root_dir) + + if (os.path.exists(os.path.join(root_dir, ".git")) or + os.path.exists(os.path.join(root_dir, ".hg"))): + prefix = os.path.commonprefix([root_dir, project_dir]) + return fullname[len(prefix) + 1:] + + # Don't know what to do; header guard warnings may be wrong... + return fullname + + def Split(self): + """Splits the file into the directory, basename, and extension. + + For 'chrome/browser/browser.cc', Split() would + return ('chrome/browser', 'browser', '.cc') + + Returns: + A tuple of (directory, basename, extension). + """ + + googlename = self.RepositoryName() + project, rest = os.path.split(googlename) + return (project,) + os.path.splitext(rest) + + def BaseName(self): + """File base name - text after the final slash, before the final period.""" + return self.Split()[1] + + def Extension(self): + """File extension - text following the final period.""" + return self.Split()[2] + + def NoExtension(self): + """File has no source file extension.""" + return '/'.join(self.Split()[0:2]) + + def IsSource(self): + """File has a source file extension.""" + return self.Extension()[1:] in ('c', 'cc', 'cpp', 'cxx') + + +def _ShouldPrintError(category, confidence, linenum): + """Returns true iff confidence >= verbose, category passes + filter and is not NOLINT-suppressed.""" + + # There are three ways we might decide not to print an error message: + # a "NOLINT(category)" comment appears in the source, + # the verbosity level isn't high enough, or the filters filter it out. + if IsErrorSuppressedByNolint(category, linenum): + return False + if confidence < _cpplint_state.verbose_level: + return False + + is_filtered = False + for one_filter in _Filters(): + if one_filter.startswith('-'): + if category.startswith(one_filter[1:]): + is_filtered = True + elif one_filter.startswith('+'): + if category.startswith(one_filter[1:]): + is_filtered = False + else: + assert False # should have been checked for in SetFilter. + if is_filtered: + return False + + return True + + +def Error(filename, linenum, category, confidence, message): + """Logs the fact we've found a lint error. + + We log where the error was found, and also our confidence in the error, + that is, how certain we are this is a legitimate style regression, and + not a misidentification or a use that's sometimes justified. + + False positives can be suppressed by the use of + "cpplint(category)" comments on the offending line. These are + parsed into _error_suppressions. + + Args: + filename: The name of the file containing the error. + linenum: The number of the line containing the error. + category: A string used to describe the "category" this bug + falls under: "whitespace", say, or "runtime". Categories + may have a hierarchy separated by slashes: "whitespace/indent". + confidence: A number from 1-5 representing a confidence score for + the error, with 5 meaning that we are certain of the problem, + and 1 meaning that it could be a legitimate construct. + message: The error message. + """ + if _ShouldPrintError(category, confidence, linenum): + _cpplint_state.IncrementErrorCount(category) + if _cpplint_state.output_format == 'vs7': + sys.stderr.write('%s(%s): %s [%s] [%d]\n' % ( + filename, linenum, message, category, confidence)) + else: + sys.stderr.write('%s:%s: %s [%s] [%d]\n' % ( + filename, linenum, message, category, confidence)) + + +# Matches standard C++ escape esequences per 2.13.2.3 of the C++ standard. +_RE_PATTERN_CLEANSE_LINE_ESCAPES = re.compile( + r'\\([abfnrtv?"\\\']|\d+|x[0-9a-fA-F]+)') +# Matches strings. Escape codes should already be removed by ESCAPES. +_RE_PATTERN_CLEANSE_LINE_DOUBLE_QUOTES = re.compile(r'"[^"]*"') +# Matches characters. Escape codes should already be removed by ESCAPES. +_RE_PATTERN_CLEANSE_LINE_SINGLE_QUOTES = re.compile(r"'.'") +# Matches multi-line C++ comments. +# This RE is a little bit more complicated than one might expect, because we +# have to take care of space removals tools so we can handle comments inside +# statements better. +# The current rule is: We only clear spaces from both sides when we're at the +# end of the line. Otherwise, we try to remove spaces from the right side, +# if this doesn't work we try on left side but only if there's a non-character +# on the right. +_RE_PATTERN_CLEANSE_LINE_C_COMMENTS = re.compile( + r"""(\s*/\*.*\*/\s*$| + /\*.*\*/\s+| + \s+/\*.*\*/(?=\W)| + /\*.*\*/)""", re.VERBOSE) + + +def IsCppString(line): + """Does line terminate so, that the next symbol is in string constant. + + This function does not consider single-line nor multi-line comments. + + Args: + line: is a partial line of code starting from the 0..n. + + Returns: + True, if next character appended to 'line' is inside a + string constant. + """ + + line = line.replace(r'\\', 'XX') # after this, \\" does not match to \" + return ((line.count('"') - line.count(r'\"') - line.count("'\"'")) & 1) == 1 + + +def FindNextMultiLineCommentStart(lines, lineix): + """Find the beginning marker for a multiline comment.""" + while lineix < len(lines): + if lines[lineix].strip().startswith('/*'): + # Only return this marker if the comment goes beyond this line + if lines[lineix].strip().find('*/', 2) < 0: + return lineix + lineix += 1 + return len(lines) + + +def FindNextMultiLineCommentEnd(lines, lineix): + """We are inside a comment, find the end marker.""" + while lineix < len(lines): + if lines[lineix].strip().endswith('*/'): + return lineix + lineix += 1 + return len(lines) + + +def RemoveMultiLineCommentsFromRange(lines, begin, end): + """Clears a range of lines for multi-line comments.""" + # Having // dummy comments makes the lines non-empty, so we will not get + # unnecessary blank line warnings later in the code. + for i in range(begin, end): + lines[i] = '// dummy' + + +def RemoveMultiLineComments(filename, lines, error): + """Removes multiline (c-style) comments from lines.""" + lineix = 0 + while lineix < len(lines): + lineix_begin = FindNextMultiLineCommentStart(lines, lineix) + if lineix_begin >= len(lines): + return + lineix_end = FindNextMultiLineCommentEnd(lines, lineix_begin) + if lineix_end >= len(lines): + error(filename, lineix_begin + 1, 'readability/multiline_comment', 5, + 'Could not find end of multi-line comment') + return + RemoveMultiLineCommentsFromRange(lines, lineix_begin, lineix_end + 1) + lineix = lineix_end + 1 + + +def CleanseComments(line): + """Removes //-comments and single-line C-style /* */ comments. + + Args: + line: A line of C++ source. + + Returns: + The line with single-line comments removed. + """ + commentpos = line.find('//') + if commentpos != -1 and not IsCppString(line[:commentpos]): + line = line[:commentpos] + # get rid of /* ... */ + return _RE_PATTERN_CLEANSE_LINE_C_COMMENTS.sub('', line) + + +class CleansedLines(object): + """Holds 3 copies of all lines with different preprocessing applied to them. + + 1) elided member contains lines without strings and comments, + 2) lines member contains lines without comments, and + 3) raw member contains all the lines without processing. + All these three members are of , and of the same length. + """ + + def __init__(self, lines): + self.elided = [] + self.lines = [] + self.raw_lines = lines + self.num_lines = len(lines) + for linenum in range(len(lines)): + self.lines.append(CleanseComments(lines[linenum])) + elided = self._CollapseStrings(lines[linenum]) + self.elided.append(CleanseComments(elided)) + + def NumLines(self): + """Returns the number of lines represented.""" + return self.num_lines + + @staticmethod + def _CollapseStrings(elided): + """Collapses strings and chars on a line to simple "" or '' blocks. + + We nix strings first so we're not fooled by text like '"http://"' + + Args: + elided: The line being processed. + + Returns: + The line with collapsed strings. + """ + if not _RE_PATTERN_INCLUDE.match(elided): + # Remove escaped characters first to make quote/single quote collapsing + # basic. Things that look like escaped characters shouldn't occur + # outside of strings and chars. + elided = _RE_PATTERN_CLEANSE_LINE_ESCAPES.sub('', elided) + elided = _RE_PATTERN_CLEANSE_LINE_SINGLE_QUOTES.sub("''", elided) + elided = _RE_PATTERN_CLEANSE_LINE_DOUBLE_QUOTES.sub('""', elided) + return elided + + +def CloseExpression(clean_lines, linenum, pos): + """If input points to ( or { or [, finds the position that closes it. + + If lines[linenum][pos] points to a '(' or '{' or '[', finds the the + linenum/pos that correspond to the closing of the expression. + + Args: + clean_lines: A CleansedLines instance containing the file. + linenum: The number of the line to check. + pos: A position on the line. + + Returns: + A tuple (line, linenum, pos) pointer *past* the closing brace, or + (line, len(lines), -1) if we never find a close. Note we ignore + strings and comments when matching; and the line we return is the + 'cleansed' line at linenum. + """ + + line = clean_lines.elided[linenum] + startchar = line[pos] + if startchar not in '({[': + return (line, clean_lines.NumLines(), -1) + if startchar == '(': endchar = ')' + if startchar == '[': endchar = ']' + if startchar == '{': endchar = '}' + + num_open = line.count(startchar) - line.count(endchar) + while linenum < clean_lines.NumLines() and num_open > 0: + linenum += 1 + line = clean_lines.elided[linenum] + num_open += line.count(startchar) - line.count(endchar) + # OK, now find the endchar that actually got us back to even + endpos = len(line) + while num_open >= 0: + endpos = line.rfind(')', 0, endpos) + num_open -= 1 # chopped off another ) + return (line, linenum, endpos + 1) + + +def CheckForCopyright(filename, lines, error): + """Logs an error if no Copyright message appears at the top of the file.""" + + # We'll say it should occur by line 10. Don't forget there's a + # dummy line at the front. + for line in xrange(1, min(len(lines), 11)): + if re.search(r'Copyright', lines[line], re.I): break + else: # means no copyright line was found + error(filename, 0, 'legal/copyright', 5, + 'No copyright message found. ' + 'You should have a line: "Copyright [year] "') + + +def GetHeaderGuardCPPVariable(filename): + """Returns the CPP variable that should be used as a header guard. + + Args: + filename: The name of a C++ header file. + + Returns: + The CPP variable that should be used as a header guard in the + named file. + + """ + + # Restores original filename in case that cpplint is invoked from Emacs's + # flymake. + filename = re.sub(r'_flymake\.h$', '.h', filename) + + fileinfo = FileInfo(filename) + return re.sub(r'[-./\s]', '_', fileinfo.RepositoryName()).upper() + '_' + + +def CheckForHeaderGuard(filename, lines, error): + """Checks that the file contains a header guard. + + Logs an error if no #ifndef header guard is present. For other + headers, checks that the full pathname is used. + + Args: + filename: The name of the C++ header file. + lines: An array of strings, each representing a line of the file. + error: The function to call with any errors found. + """ + + cppvar = GetHeaderGuardCPPVariable(filename) + + ifndef = None + ifndef_linenum = 0 + define = None + endif = None + endif_linenum = 0 + for linenum, line in enumerate(lines): + linesplit = line.split() + if len(linesplit) >= 2: + # find the first occurrence of #ifndef and #define, save arg + if not ifndef and linesplit[0] == '#ifndef': + # set ifndef to the header guard presented on the #ifndef line. + ifndef = linesplit[1] + ifndef_linenum = linenum + if not define and linesplit[0] == '#define': + define = linesplit[1] + # find the last occurrence of #endif, save entire line + if line.startswith('#endif'): + endif = line + endif_linenum = linenum + + if not ifndef or not define or ifndef != define: + error(filename, 0, 'build/header_guard', 5, + 'No #ifndef header guard found, suggested CPP variable is: %s' % + cppvar) + return + + # The guard should be PATH_FILE_H_, but we also allow PATH_FILE_H__ + # for backward compatibility. + if ifndef != cppvar: + error_level = 0 + if ifndef != cppvar + '_': + error_level = 5 + + ParseNolintSuppressions(filename, lines[ifndef_linenum], ifndef_linenum, + error) + error(filename, ifndef_linenum, 'build/header_guard', error_level, + '#ifndef header guard has wrong style, please use: %s' % cppvar) + + if endif != ('#endif // %s' % cppvar): + error_level = 0 + if endif != ('#endif // %s' % (cppvar + '_')): + error_level = 5 + + ParseNolintSuppressions(filename, lines[endif_linenum], endif_linenum, + error) + error(filename, endif_linenum, 'build/header_guard', error_level, + '#endif line should be "#endif // %s"' % cppvar) + + +def CheckForUnicodeReplacementCharacters(filename, lines, error): + """Logs an error for each line containing Unicode replacement characters. + + These indicate that either the file contained invalid UTF-8 (likely) + or Unicode replacement characters (which it shouldn't). Note that + it's possible for this to throw off line numbering if the invalid + UTF-8 occurred adjacent to a newline. + + Args: + filename: The name of the current file. + lines: An array of strings, each representing a line of the file. + error: The function to call with any errors found. + """ + for linenum, line in enumerate(lines): + if u'\ufffd' in line: + error(filename, linenum, 'readability/utf8', 5, + 'Line contains invalid UTF-8 (or Unicode replacement character).') + + +def CheckForNewlineAtEOF(filename, lines, error): + """Logs an error if there is no newline char at the end of the file. + + Args: + filename: The name of the current file. + lines: An array of strings, each representing a line of the file. + error: The function to call with any errors found. + """ + + # The array lines() was created by adding two newlines to the + # original file (go figure), then splitting on \n. + # To verify that the file ends in \n, we just have to make sure the + # last-but-two element of lines() exists and is empty. + if len(lines) < 3 or lines[-2]: + error(filename, len(lines) - 2, 'whitespace/ending_newline', 5, + 'Could not find a newline character at the end of the file.') + + +def CheckForMultilineCommentsAndStrings(filename, clean_lines, linenum, error): + """Logs an error if we see /* ... */ or "..." that extend past one line. + + /* ... */ comments are legit inside macros, for one line. + Otherwise, we prefer // comments, so it's ok to warn about the + other. Likewise, it's ok for strings to extend across multiple + lines, as long as a line continuation character (backslash) + terminates each line. Although not currently prohibited by the C++ + style guide, it's ugly and unnecessary. We don't do well with either + in this lint program, so we warn about both. + + Args: + filename: The name of the current file. + clean_lines: A CleansedLines instance containing the file. + linenum: The number of the line to check. + error: The function to call with any errors found. + """ + line = clean_lines.elided[linenum] + + # Remove all \\ (escaped backslashes) from the line. They are OK, and the + # second (escaped) slash may trigger later \" detection erroneously. + line = line.replace('\\\\', '') + + if line.count('/*') > line.count('*/'): + error(filename, linenum, 'readability/multiline_comment', 5, + 'Complex multi-line /*...*/-style comment found. ' + 'Lint may give bogus warnings. ' + 'Consider replacing these with //-style comments, ' + 'with #if 0...#endif, ' + 'or with more clearly structured multi-line comments.') + + if (line.count('"') - line.count('\\"')) % 2: + error(filename, linenum, 'readability/multiline_string', 5, + 'Multi-line string ("...") found. This lint script doesn\'t ' + 'do well with such strings, and may give bogus warnings. They\'re ' + 'ugly and unnecessary, and you should use concatenation instead".') + + +threading_list = ( + ('asctime(', 'asctime_r('), + ('ctime(', 'ctime_r('), + ('getgrgid(', 'getgrgid_r('), + ('getgrnam(', 'getgrnam_r('), + ('getlogin(', 'getlogin_r('), + ('getpwnam(', 'getpwnam_r('), + ('getpwuid(', 'getpwuid_r('), + ('gmtime(', 'gmtime_r('), + ('localtime(', 'localtime_r('), + ('rand(', 'rand_r('), + ('readdir(', 'readdir_r('), + ('strtok(', 'strtok_r('), + ('ttyname(', 'ttyname_r('), + ) + + +def CheckPosixThreading(filename, clean_lines, linenum, error): + """Checks for calls to thread-unsafe functions. + + Much code has been originally written without consideration of + multi-threading. Also, engineers are relying on their old experience; + they have learned posix before threading extensions were added. These + tests guide the engineers to use thread-safe functions (when using + posix directly). + + Args: + filename: The name of the current file. + clean_lines: A CleansedLines instance containing the file. + linenum: The number of the line to check. + error: The function to call with any errors found. + """ + line = clean_lines.elided[linenum] + for single_thread_function, multithread_safe_function in threading_list: + ix = line.find(single_thread_function) + # Comparisons made explicit for clarity -- pylint: disable-msg=C6403 + if ix >= 0 and (ix == 0 or (not line[ix - 1].isalnum() and + line[ix - 1] not in ('_', '.', '>'))): + error(filename, linenum, 'runtime/threadsafe_fn', 2, + 'Consider using ' + multithread_safe_function + + '...) instead of ' + single_thread_function + + '...) for improved thread safety.') + + +# Matches invalid increment: *count++, which moves pointer instead of +# incrementing a value. +_RE_PATTERN_INVALID_INCREMENT = re.compile( + r'^\s*\*\w+(\+\+|--);') + + +def CheckInvalidIncrement(filename, clean_lines, linenum, error): + """Checks for invalid increment *count++. + + For example following function: + void increment_counter(int* count) { + *count++; + } + is invalid, because it effectively does count++, moving pointer, and should + be replaced with ++*count, (*count)++ or *count += 1. + + Args: + filename: The name of the current file. + clean_lines: A CleansedLines instance containing the file. + linenum: The number of the line to check. + error: The function to call with any errors found. + """ + line = clean_lines.elided[linenum] + if _RE_PATTERN_INVALID_INCREMENT.match(line): + error(filename, linenum, 'runtime/invalid_increment', 5, + 'Changing pointer instead of value (or unused value of operator*).') + + +class _ClassInfo(object): + """Stores information about a class.""" + + def __init__(self, name, linenum): + self.name = name + self.linenum = linenum + self.seen_open_brace = False + self.is_derived = False + self.virtual_method_linenumber = None + self.has_virtual_destructor = False + self.brace_depth = 0 + + +class _ClassState(object): + """Holds the current state of the parse relating to class declarations. + + It maintains a stack of _ClassInfos representing the parser's guess + as to the current nesting of class declarations. The innermost class + is at the top (back) of the stack. Typically, the stack will either + be empty or have exactly one entry. + """ + + def __init__(self): + self.classinfo_stack = [] + + def CheckFinished(self, filename, error): + """Checks that all classes have been completely parsed. + + Call this when all lines in a file have been processed. + Args: + filename: The name of the current file. + error: The function to call with any errors found. + """ + if self.classinfo_stack: + # Note: This test can result in false positives if #ifdef constructs + # get in the way of brace matching. See the testBuildClass test in + # cpplint_unittest.py for an example of this. + error(filename, self.classinfo_stack[0].linenum, 'build/class', 5, + 'Failed to find complete declaration of class %s' % + self.classinfo_stack[0].name) + + +def CheckForNonStandardConstructs(filename, clean_lines, linenum, + class_state, error): + """Logs an error if we see certain non-ANSI constructs ignored by gcc-2. + + Complain about several constructs which gcc-2 accepts, but which are + not standard C++. Warning about these in lint is one way to ease the + transition to new compilers. + - put storage class first (e.g. "static const" instead of "const static"). + - "%lld" instead of %qd" in printf-type functions. + - "%1$d" is non-standard in printf-type functions. + - "\%" is an undefined character escape sequence. + - text after #endif is not allowed. + - invalid inner-style forward declaration. + - >? and ?= and )\?=?\s*(\w+|[+-]?\d+)(\.\d*)?', + line): + error(filename, linenum, 'build/deprecated', 3, + '>? and ))?' + # r'\s*const\s*' + type_name + '\s*&\s*\w+\s*;' + error(filename, linenum, 'runtime/member_string_references', 2, + 'const string& members are dangerous. It is much better to use ' + 'alternatives, such as pointers or simple constants.') + + # Track class entry and exit, and attempt to find cases within the + # class declaration that don't meet the C++ style + # guidelines. Tracking is very dependent on the code matching Google + # style guidelines, but it seems to perform well enough in testing + # to be a worthwhile addition to the checks. + classinfo_stack = class_state.classinfo_stack + # Look for a class declaration + class_decl_match = Match( + r'\s*(template\s*<[\w\s<>,:]*>\s*)?(class|struct)\s+(\w+(::\w+)*)', line) + if class_decl_match: + classinfo_stack.append(_ClassInfo(class_decl_match.group(3), linenum)) + + # Everything else in this function uses the top of the stack if it's + # not empty. + if not classinfo_stack: + return + + classinfo = classinfo_stack[-1] + + # If the opening brace hasn't been seen look for it and also + # parent class declarations. + if not classinfo.seen_open_brace: + # If the line has a ';' in it, assume it's a forward declaration or + # a single-line class declaration, which we won't process. + if line.find(';') != -1: + classinfo_stack.pop() + return + classinfo.seen_open_brace = (line.find('{') != -1) + # Look for a bare ':' + if Search('(^|[^:]):($|[^:])', line): + classinfo.is_derived = True + if not classinfo.seen_open_brace: + return # Everything else in this function is for after open brace + + # The class may have been declared with namespace or classname qualifiers. + # The constructor and destructor will not have those qualifiers. + base_classname = classinfo.name.split('::')[-1] + + # Look for single-argument constructors that aren't marked explicit. + # Technically a valid construct, but against style. + args = Match(r'(? 1: + error(filename, linenum, 'whitespace/todo', 2, + 'Too many spaces before TODO') + + username = match.group(2) + if not username: + error(filename, linenum, 'readability/todo', 2, + 'Missing username in TODO; it should look like ' + '"// TODO(my_username): Stuff."') + + middle_whitespace = match.group(3) + # Comparisons made explicit for correctness -- pylint: disable-msg=C6403 + if middle_whitespace != ' ' and middle_whitespace != '': + error(filename, linenum, 'whitespace/todo', 2, + 'TODO(my_username) should be followed by a space') + + +def CheckSpacing(filename, clean_lines, linenum, error): + """Checks for the correctness of various spacing issues in the code. + + Things we check for: spaces around operators, spaces after + if/for/while/switch, no spaces around parens in function calls, two + spaces between code and comment, don't start a block with a blank + line, don't end a function with a blank line, don't have too many + blank lines in a row. + + Args: + filename: The name of the current file. + clean_lines: A CleansedLines instance containing the file. + linenum: The number of the line to check. + error: The function to call with any errors found. + """ + + raw = clean_lines.raw_lines + line = raw[linenum] + + # Before nixing comments, check if the line is blank for no good + # reason. This includes the first line after a block is opened, and + # blank lines at the end of a function (ie, right before a line like '}' + if IsBlankLine(line): + elided = clean_lines.elided + prev_line = elided[linenum - 1] + prevbrace = prev_line.rfind('{') + # TODO(unknown): Don't complain if line before blank line, and line after, + # both start with alnums and are indented the same amount. + # This ignores whitespace at the start of a namespace block + # because those are not usually indented. + if (prevbrace != -1 and prev_line[prevbrace:].find('}') == -1 + and prev_line[:prevbrace].find('namespace') == -1): + # OK, we have a blank line at the start of a code block. Before we + # complain, we check if it is an exception to the rule: The previous + # non-empty line has the paramters of a function header that are indented + # 4 spaces (because they did not fit in a 80 column line when placed on + # the same line as the function name). We also check for the case where + # the previous line is indented 6 spaces, which may happen when the + # initializers of a constructor do not fit into a 80 column line. + exception = False + if Match(r' {6}\w', prev_line): # Initializer list? + # We are looking for the opening column of initializer list, which + # should be indented 4 spaces to cause 6 space indentation afterwards. + search_position = linenum-2 + while (search_position >= 0 + and Match(r' {6}\w', elided[search_position])): + search_position -= 1 + exception = (search_position >= 0 + and elided[search_position][:5] == ' :') + else: + # Search for the function arguments or an initializer list. We use a + # simple heuristic here: If the line is indented 4 spaces; and we have a + # closing paren, without the opening paren, followed by an opening brace + # or colon (for initializer lists) we assume that it is the last line of + # a function header. If we have a colon indented 4 spaces, it is an + # initializer list. + exception = (Match(r' {4}\w[^\(]*\)\s*(const\s*)?(\{\s*$|:)', + prev_line) + or Match(r' {4}:', prev_line)) + + if not exception: + error(filename, linenum, 'whitespace/blank_line', 2, + 'Blank line at the start of a code block. Is this needed?') + # This doesn't ignore whitespace at the end of a namespace block + # because that is too hard without pairing open/close braces; + # however, a special exception is made for namespace closing + # brackets which have a comment containing "namespace". + # + # Also, ignore blank lines at the end of a block in a long if-else + # chain, like this: + # if (condition1) { + # // Something followed by a blank line + # + # } else if (condition2) { + # // Something else + # } + if linenum + 1 < clean_lines.NumLines(): + next_line = raw[linenum + 1] + if (next_line + and Match(r'\s*}', next_line) + and next_line.find('namespace') == -1 + and next_line.find('} else ') == -1): + error(filename, linenum, 'whitespace/blank_line', 3, + 'Blank line at the end of a code block. Is this needed?') + + # Next, we complain if there's a comment too near the text + commentpos = line.find('//') + if commentpos != -1: + # Check if the // may be in quotes. If so, ignore it + # Comparisons made explicit for clarity -- pylint: disable-msg=C6403 + if (line.count('"', 0, commentpos) - + line.count('\\"', 0, commentpos)) % 2 == 0: # not in quotes + # Allow one space for new scopes, two spaces otherwise: + if (not Match(r'^\s*{ //', line) and + ((commentpos >= 1 and + line[commentpos-1] not in string.whitespace) or + (commentpos >= 2 and + line[commentpos-2] not in string.whitespace))): + error(filename, linenum, 'whitespace/comments', 2, + 'At least two spaces is best between code and comments') + # There should always be a space between the // and the comment + commentend = commentpos + 2 + if commentend < len(line) and not line[commentend] == ' ': + # but some lines are exceptions -- e.g. if they're big + # comment delimiters like: + # //---------------------------------------------------------- + # or are an empty C++ style Doxygen comment, like: + # /// + # or they begin with multiple slashes followed by a space: + # //////// Header comment + match = (Search(r'[=/-]{4,}\s*$', line[commentend:]) or + Search(r'^/$', line[commentend:]) or + Search(r'^/+ ', line[commentend:])) + if not match: + error(filename, linenum, 'whitespace/comments', 4, + 'Should have a space between // and comment') + CheckComment(line[commentpos:], filename, linenum, error) + + line = clean_lines.elided[linenum] # get rid of comments and strings + + # Don't try to do spacing checks for operator methods + line = re.sub(r'operator(==|!=|<|<<|<=|>=|>>|>)\(', 'operator\(', line) + + # We allow no-spaces around = within an if: "if ( (a=Foo()) == 0 )". + # Otherwise not. Note we only check for non-spaces on *both* sides; + # sometimes people put non-spaces on one side when aligning ='s among + # many lines (not that this is behavior that I approve of...) + if Search(r'[\w.]=[\w.]', line) and not Search(r'\b(if|while) ', line): + error(filename, linenum, 'whitespace/operators', 4, + 'Missing spaces around =') + + # It's ok not to have spaces around binary operators like + - * /, but if + # there's too little whitespace, we get concerned. It's hard to tell, + # though, so we punt on this one for now. TODO. + + # You should always have whitespace around binary operators. + # Alas, we can't test < or > because they're legitimately used sans spaces + # (a->b, vector a). The only time we can tell is a < with no >, and + # only if it's not template params list spilling into the next line. + match = Search(r'[^<>=!\s](==|!=|<=|>=)[^<>=!\s]', line) + if not match: + # Note that while it seems that the '<[^<]*' term in the following + # regexp could be simplified to '<.*', which would indeed match + # the same class of strings, the [^<] means that searching for the + # regexp takes linear rather than quadratic time. + if not Search(r'<[^<]*,\s*$', line): # template params spill + match = Search(r'[^<>=!\s](<)[^<>=!\s]([^>]|->)*$', line) + if match: + error(filename, linenum, 'whitespace/operators', 3, + 'Missing spaces around %s' % match.group(1)) + # We allow no-spaces around << and >> when used like this: 10<<20, but + # not otherwise (particularly, not when used as streams) + match = Search(r'[^0-9\s](<<|>>)[^0-9\s]', line) + if match: + error(filename, linenum, 'whitespace/operators', 3, + 'Missing spaces around %s' % match.group(1)) + + # There shouldn't be space around unary operators + match = Search(r'(!\s|~\s|[\s]--[\s;]|[\s]\+\+[\s;])', line) + if match: + error(filename, linenum, 'whitespace/operators', 4, + 'Extra space for operator %s' % match.group(1)) + + # A pet peeve of mine: no spaces after an if, while, switch, or for + match = Search(r' (if\(|for\(|while\(|switch\()', line) + if match: + error(filename, linenum, 'whitespace/parens', 5, + 'Missing space before ( in %s' % match.group(1)) + + # For if/for/while/switch, the left and right parens should be + # consistent about how many spaces are inside the parens, and + # there should either be zero or one spaces inside the parens. + # We don't want: "if ( foo)" or "if ( foo )". + # Exception: "for ( ; foo; bar)" and "for (foo; bar; )" are allowed. + match = Search(r'\b(if|for|while|switch)\s*' + r'\(([ ]*)(.).*[^ ]+([ ]*)\)\s*{\s*$', + line) + if match: + if len(match.group(2)) != len(match.group(4)): + if not (match.group(3) == ';' and + len(match.group(2)) == 1 + len(match.group(4)) or + not match.group(2) and Search(r'\bfor\s*\(.*; \)', line)): + error(filename, linenum, 'whitespace/parens', 5, + 'Mismatching spaces inside () in %s' % match.group(1)) + if not len(match.group(2)) in [0, 1]: + error(filename, linenum, 'whitespace/parens', 5, + 'Should have zero or one spaces inside ( and ) in %s' % + match.group(1)) + + # You should always have a space after a comma (either as fn arg or operator) + if Search(r',[^\s]', line): + error(filename, linenum, 'whitespace/comma', 3, + 'Missing space after ,') + + # Next we will look for issues with function calls. + CheckSpacingForFunctionCall(filename, line, linenum, error) + + # Except after an opening paren, you should have spaces before your braces. + # And since you should never have braces at the beginning of a line, this is + # an easy test. + if Search(r'[^ (]{', line): + error(filename, linenum, 'whitespace/braces', 5, + 'Missing space before {') + + # Make sure '} else {' has spaces. + if Search(r'}else', line): + error(filename, linenum, 'whitespace/braces', 5, + 'Missing space before else') + + # You shouldn't have spaces before your brackets, except maybe after + # 'delete []' or 'new char * []'. + if Search(r'\w\s+\[', line) and not Search(r'delete\s+\[', line): + error(filename, linenum, 'whitespace/braces', 5, + 'Extra space before [') + + # You shouldn't have a space before a semicolon at the end of the line. + # There's a special case for "for" since the style guide allows space before + # the semicolon there. + if Search(r':\s*;\s*$', line): + error(filename, linenum, 'whitespace/semicolon', 5, + 'Semicolon defining empty statement. Use { } instead.') + elif Search(r'^\s*;\s*$', line): + error(filename, linenum, 'whitespace/semicolon', 5, + 'Line contains only semicolon. If this should be an empty statement, ' + 'use { } instead.') + elif (Search(r'\s+;\s*$', line) and + not Search(r'\bfor\b', line)): + error(filename, linenum, 'whitespace/semicolon', 5, + 'Extra space before last semicolon. If this should be an empty ' + 'statement, use { } instead.') + + +def GetPreviousNonBlankLine(clean_lines, linenum): + """Return the most recent non-blank line and its line number. + + Args: + clean_lines: A CleansedLines instance containing the file contents. + linenum: The number of the line to check. + + Returns: + A tuple with two elements. The first element is the contents of the last + non-blank line before the current line, or the empty string if this is the + first non-blank line. The second is the line number of that line, or -1 + if this is the first non-blank line. + """ + + prevlinenum = linenum - 1 + while prevlinenum >= 0: + prevline = clean_lines.elided[prevlinenum] + if not IsBlankLine(prevline): # if not a blank line... + return (prevline, prevlinenum) + prevlinenum -= 1 + return ('', -1) + + +def CheckBraces(filename, clean_lines, linenum, error): + """Looks for misplaced braces (e.g. at the end of line). + + Args: + filename: The name of the current file. + clean_lines: A CleansedLines instance containing the file. + linenum: The number of the line to check. + error: The function to call with any errors found. + """ + + line = clean_lines.elided[linenum] # get rid of comments and strings + + if Match(r'\s*{\s*$', line): + # We allow an open brace to start a line in the case where someone + # is using braces in a block to explicitly create a new scope, + # which is commonly used to control the lifetime of + # stack-allocated variables. We don't detect this perfectly: we + # just don't complain if the last non-whitespace character on the + # previous non-blank line is ';', ':', '{', or '}'. + prevline = GetPreviousNonBlankLine(clean_lines, linenum)[0] + if not Search(r'[;:}{]\s*$', prevline): + error(filename, linenum, 'whitespace/braces', 4, + '{ should almost always be at the end of the previous line') + + # An else clause should be on the same line as the preceding closing brace. + if Match(r'\s*else\s*', line): + prevline = GetPreviousNonBlankLine(clean_lines, linenum)[0] + if Match(r'\s*}\s*$', prevline): + error(filename, linenum, 'whitespace/newline', 4, + 'An else should appear on the same line as the preceding }') + + # If braces come on one side of an else, they should be on both. + # However, we have to worry about "else if" that spans multiple lines! + if Search(r'}\s*else[^{]*$', line) or Match(r'[^}]*else\s*{', line): + if Search(r'}\s*else if([^{]*)$', line): # could be multi-line if + # find the ( after the if + pos = line.find('else if') + pos = line.find('(', pos) + if pos > 0: + (endline, _, endpos) = CloseExpression(clean_lines, linenum, pos) + if endline[endpos:].find('{') == -1: # must be brace after if + error(filename, linenum, 'readability/braces', 5, + 'If an else has a brace on one side, it should have it on both') + else: # common case: else not followed by a multi-line if + error(filename, linenum, 'readability/braces', 5, + 'If an else has a brace on one side, it should have it on both') + + # Likewise, an else should never have the else clause on the same line + if Search(r'\belse [^\s{]', line) and not Search(r'\belse if\b', line): + error(filename, linenum, 'whitespace/newline', 4, + 'Else clause should never be on same line as else (use 2 lines)') + + # In the same way, a do/while should never be on one line + if Match(r'\s*do [^\s{]', line): + error(filename, linenum, 'whitespace/newline', 4, + 'do/while clauses should not be on a single line') + + # Braces shouldn't be followed by a ; unless they're defining a struct + # or initializing an array. + # We can't tell in general, but we can for some common cases. + prevlinenum = linenum + while True: + (prevline, prevlinenum) = GetPreviousNonBlankLine(clean_lines, prevlinenum) + if Match(r'\s+{.*}\s*;', line) and not prevline.count(';'): + line = prevline + line + else: + break + if (Search(r'{.*}\s*;', line) and + line.count('{') == line.count('}') and + not Search(r'struct|class|enum|\s*=\s*{', line)): + error(filename, linenum, 'readability/braces', 4, + "You don't need a ; after a }") + + +def ReplaceableCheck(operator, macro, line): + """Determine whether a basic CHECK can be replaced with a more specific one. + + For example suggest using CHECK_EQ instead of CHECK(a == b) and + similarly for CHECK_GE, CHECK_GT, CHECK_LE, CHECK_LT, CHECK_NE. + + Args: + operator: The C++ operator used in the CHECK. + macro: The CHECK or EXPECT macro being called. + line: The current source line. + + Returns: + True if the CHECK can be replaced with a more specific one. + """ + + # This matches decimal and hex integers, strings, and chars (in that order). + match_constant = r'([-+]?(\d+|0[xX][0-9a-fA-F]+)[lLuU]{0,3}|".*"|\'.*\')' + + # Expression to match two sides of the operator with something that + # looks like a literal, since CHECK(x == iterator) won't compile. + # This means we can't catch all the cases where a more specific + # CHECK is possible, but it's less annoying than dealing with + # extraneous warnings. + match_this = (r'\s*' + macro + r'\((\s*' + + match_constant + r'\s*' + operator + r'[^<>].*|' + r'.*[^<>]' + operator + r'\s*' + match_constant + + r'\s*\))') + + # Don't complain about CHECK(x == NULL) or similar because + # CHECK_EQ(x, NULL) won't compile (requires a cast). + # Also, don't complain about more complex boolean expressions + # involving && or || such as CHECK(a == b || c == d). + return Match(match_this, line) and not Search(r'NULL|&&|\|\|', line) + + +def CheckCheck(filename, clean_lines, linenum, error): + """Checks the use of CHECK and EXPECT macros. + + Args: + filename: The name of the current file. + clean_lines: A CleansedLines instance containing the file. + linenum: The number of the line to check. + error: The function to call with any errors found. + """ + + # Decide the set of replacement macros that should be suggested + raw_lines = clean_lines.raw_lines + current_macro = '' + for macro in _CHECK_MACROS: + if raw_lines[linenum].find(macro) >= 0: + current_macro = macro + break + if not current_macro: + # Don't waste time here if line doesn't contain 'CHECK' or 'EXPECT' + return + + line = clean_lines.elided[linenum] # get rid of comments and strings + + # Encourage replacing plain CHECKs with CHECK_EQ/CHECK_NE/etc. + for operator in ['==', '!=', '>=', '>', '<=', '<']: + if ReplaceableCheck(operator, current_macro, line): + error(filename, linenum, 'readability/check', 2, + 'Consider using %s instead of %s(a %s b)' % ( + _CHECK_REPLACEMENT[current_macro][operator], + current_macro, operator)) + break + + +def GetLineWidth(line): + """Determines the width of the line in column positions. + + Args: + line: A string, which may be a Unicode string. + + Returns: + The width of the line in column positions, accounting for Unicode + combining characters and wide characters. + """ + if isinstance(line, unicode): + width = 0 + for c in unicodedata.normalize('NFC', line): + if unicodedata.east_asian_width(c) in ('W', 'F'): + width += 2 + elif not unicodedata.combining(c): + width += 1 + return width + else: + return len(line) + + +def CheckStyle(filename, clean_lines, linenum, file_extension, error): + """Checks rules from the 'C++ style rules' section of cppguide.html. + + Most of these rules are hard to test (naming, comment style), but we + do what we can. In particular we check for 2-space indents, line lengths, + tab usage, spaces inside code, etc. + + Args: + filename: The name of the current file. + clean_lines: A CleansedLines instance containing the file. + linenum: The number of the line to check. + file_extension: The extension (without the dot) of the filename. + error: The function to call with any errors found. + """ + + raw_lines = clean_lines.raw_lines + line = raw_lines[linenum] + + if line.find('\t') != -1: + error(filename, linenum, 'whitespace/tab', 1, + 'Tab found; better to use spaces') + + # One or three blank spaces at the beginning of the line is weird; it's + # hard to reconcile that with 2-space indents. + # NOTE: here are the conditions rob pike used for his tests. Mine aren't + # as sophisticated, but it may be worth becoming so: RLENGTH==initial_spaces + # if(RLENGTH > 20) complain = 0; + # if(match($0, " +(error|private|public|protected):")) complain = 0; + # if(match(prev, "&& *$")) complain = 0; + # if(match(prev, "\\|\\| *$")) complain = 0; + # if(match(prev, "[\",=><] *$")) complain = 0; + # if(match($0, " <<")) complain = 0; + # if(match(prev, " +for \\(")) complain = 0; + # if(prevodd && match(prevprev, " +for \\(")) complain = 0; + initial_spaces = 0 + cleansed_line = clean_lines.elided[linenum] + while initial_spaces < len(line) and line[initial_spaces] == ' ': + initial_spaces += 1 + if line and line[-1].isspace(): + error(filename, linenum, 'whitespace/end_of_line', 4, + 'Line ends in whitespace. Consider deleting these extra spaces.') + # There are certain situations we allow one space, notably for labels + elif ((initial_spaces == 1 or initial_spaces == 3) and + not Match(r'\s*\w+\s*:\s*$', cleansed_line)): + error(filename, linenum, 'whitespace/indent', 3, + 'Weird number of spaces at line-start. ' + 'Are you using a 2-space indent?') + # Labels should always be indented at least one space. + elif not initial_spaces and line[:2] != '//' and Search(r'[^:]:\s*$', + line): + error(filename, linenum, 'whitespace/labels', 4, + 'Labels should always be indented at least one space. ' + 'If this is a member-initializer list in a constructor or ' + 'the base class list in a class definition, the colon should ' + 'be on the following line.') + + + # Check if the line is a header guard. + is_header_guard = False + if file_extension == 'h': + cppvar = GetHeaderGuardCPPVariable(filename) + if (line.startswith('#ifndef %s' % cppvar) or + line.startswith('#define %s' % cppvar) or + line.startswith('#endif // %s' % cppvar)): + is_header_guard = True + # #include lines and header guards can be long, since there's no clean way to + # split them. + # + # URLs can be long too. It's possible to split these, but it makes them + # harder to cut&paste. + if (not line.startswith('#include') and not is_header_guard and + not Match(r'^\s*//.*http(s?)://\S*$', line)): + line_width = GetLineWidth(line) + if line_width > 100: + error(filename, linenum, 'whitespace/line_length', 4, + 'Lines should very rarely be longer than 100 characters') + elif line_width > 80: + error(filename, linenum, 'whitespace/line_length', 2, + 'Lines should be <= 80 characters long') + + if (cleansed_line.count(';') > 1 and + # for loops are allowed two ;'s (and may run over two lines). + cleansed_line.find('for') == -1 and + (GetPreviousNonBlankLine(clean_lines, linenum)[0].find('for') == -1 or + GetPreviousNonBlankLine(clean_lines, linenum)[0].find(';') != -1) and + # It's ok to have many commands in a switch case that fits in 1 line + not ((cleansed_line.find('case ') != -1 or + cleansed_line.find('default:') != -1) and + cleansed_line.find('break;') != -1)): + error(filename, linenum, 'whitespace/newline', 4, + 'More than one command on the same line') + + # Some more style checks + CheckBraces(filename, clean_lines, linenum, error) + CheckSpacing(filename, clean_lines, linenum, error) + CheckCheck(filename, clean_lines, linenum, error) + + +_RE_PATTERN_INCLUDE_NEW_STYLE = re.compile(r'#include +"[^/]+\.h"') +_RE_PATTERN_INCLUDE = re.compile(r'^\s*#\s*include\s*([<"])([^>"]*)[>"].*$') +# Matches the first component of a filename delimited by -s and _s. That is: +# _RE_FIRST_COMPONENT.match('foo').group(0) == 'foo' +# _RE_FIRST_COMPONENT.match('foo.cc').group(0) == 'foo' +# _RE_FIRST_COMPONENT.match('foo-bar_baz.cc').group(0) == 'foo' +# _RE_FIRST_COMPONENT.match('foo_bar-baz.cc').group(0) == 'foo' +_RE_FIRST_COMPONENT = re.compile(r'^[^-_.]+') + + +def _DropCommonSuffixes(filename): + """Drops common suffixes like _test.cc or -inl.h from filename. + + For example: + >>> _DropCommonSuffixes('foo/foo-inl.h') + 'foo/foo' + >>> _DropCommonSuffixes('foo/bar/foo.cc') + 'foo/bar/foo' + >>> _DropCommonSuffixes('foo/foo_internal.h') + 'foo/foo' + >>> _DropCommonSuffixes('foo/foo_unusualinternal.h') + 'foo/foo_unusualinternal' + + Args: + filename: The input filename. + + Returns: + The filename with the common suffix removed. + """ + for suffix in ('test.cc', 'regtest.cc', 'unittest.cc', + 'inl.h', 'impl.h', 'internal.h'): + if (filename.endswith(suffix) and len(filename) > len(suffix) and + filename[-len(suffix) - 1] in ('-', '_')): + return filename[:-len(suffix) - 1] + return os.path.splitext(filename)[0] + + +def _IsTestFilename(filename): + """Determines if the given filename has a suffix that identifies it as a test. + + Args: + filename: The input filename. + + Returns: + True if 'filename' looks like a test, False otherwise. + """ + if (filename.endswith('_test.cc') or + filename.endswith('_unittest.cc') or + filename.endswith('_regtest.cc')): + return True + else: + return False + + +def _ClassifyInclude(fileinfo, include, is_system): + """Figures out what kind of header 'include' is. + + Args: + fileinfo: The current file cpplint is running over. A FileInfo instance. + include: The path to a #included file. + is_system: True if the #include used <> rather than "". + + Returns: + One of the _XXX_HEADER constants. + + For example: + >>> _ClassifyInclude(FileInfo('foo/foo.cc'), 'stdio.h', True) + _C_SYS_HEADER + >>> _ClassifyInclude(FileInfo('foo/foo.cc'), 'string', True) + _CPP_SYS_HEADER + >>> _ClassifyInclude(FileInfo('foo/foo.cc'), 'foo/foo.h', False) + _LIKELY_MY_HEADER + >>> _ClassifyInclude(FileInfo('foo/foo_unknown_extension.cc'), + ... 'bar/foo_other_ext.h', False) + _POSSIBLE_MY_HEADER + >>> _ClassifyInclude(FileInfo('foo/foo.cc'), 'foo/bar.h', False) + _OTHER_HEADER + """ + # This is a list of all standard c++ header files, except + # those already checked for above. + is_stl_h = include in _STL_HEADERS + is_cpp_h = is_stl_h or include in _CPP_HEADERS + + if is_system: + if is_cpp_h: + return _CPP_SYS_HEADER + else: + return _C_SYS_HEADER + + # If the target file and the include we're checking share a + # basename when we drop common extensions, and the include + # lives in . , then it's likely to be owned by the target file. + target_dir, target_base = ( + os.path.split(_DropCommonSuffixes(fileinfo.RepositoryName()))) + include_dir, include_base = os.path.split(_DropCommonSuffixes(include)) + if target_base == include_base and ( + include_dir == target_dir or + include_dir == os.path.normpath(target_dir + '/../public')): + return _LIKELY_MY_HEADER + + # If the target and include share some initial basename + # component, it's possible the target is implementing the + # include, so it's allowed to be first, but we'll never + # complain if it's not there. + target_first_component = _RE_FIRST_COMPONENT.match(target_base) + include_first_component = _RE_FIRST_COMPONENT.match(include_base) + if (target_first_component and include_first_component and + target_first_component.group(0) == + include_first_component.group(0)): + return _POSSIBLE_MY_HEADER + + return _OTHER_HEADER + + + +def CheckIncludeLine(filename, clean_lines, linenum, include_state, error): + """Check rules that are applicable to #include lines. + + Strings on #include lines are NOT removed from elided line, to make + certain tasks easier. However, to prevent false positives, checks + applicable to #include lines in CheckLanguage must be put here. + + Args: + filename: The name of the current file. + clean_lines: A CleansedLines instance containing the file. + linenum: The number of the line to check. + include_state: An _IncludeState instance in which the headers are inserted. + error: The function to call with any errors found. + """ + fileinfo = FileInfo(filename) + + line = clean_lines.lines[linenum] + + # "include" should use the new style "foo/bar.h" instead of just "bar.h" + if _RE_PATTERN_INCLUDE_NEW_STYLE.search(line): + error(filename, linenum, 'build/include', 4, + 'Include the directory when naming .h files') + + # we shouldn't include a file more than once. actually, there are a + # handful of instances where doing so is okay, but in general it's + # not. + match = _RE_PATTERN_INCLUDE.search(line) + if match: + include = match.group(2) + is_system = (match.group(1) == '<') + if include in include_state: + error(filename, linenum, 'build/include', 4, + '"%s" already included at %s:%s' % + (include, filename, include_state[include])) + else: + include_state[include] = linenum + + # We want to ensure that headers appear in the right order: + # 1) for foo.cc, foo.h (preferred location) + # 2) c system files + # 3) cpp system files + # 4) for foo.cc, foo.h (deprecated location) + # 5) other google headers + # + # We classify each include statement as one of those 5 types + # using a number of techniques. The include_state object keeps + # track of the highest type seen, and complains if we see a + # lower type after that. + error_message = include_state.CheckNextIncludeOrder( + _ClassifyInclude(fileinfo, include, is_system)) + if error_message: + error(filename, linenum, 'build/include_order', 4, + '%s. Should be: %s.h, c system, c++ system, other.' % + (error_message, fileinfo.BaseName())) + if not include_state.IsInAlphabeticalOrder(include): + error(filename, linenum, 'build/include_alpha', 4, + 'Include "%s" not in alphabetical order' % include) + + # Look for any of the stream classes that are part of standard C++. + match = _RE_PATTERN_INCLUDE.match(line) + if match: + include = match.group(2) + if Match(r'(f|ind|io|i|o|parse|pf|stdio|str|)?stream$', include): + # Many unit tests use cout, so we exempt them. + if not _IsTestFilename(filename): + error(filename, linenum, 'readability/streams', 3, + 'Streams are highly discouraged.') + +def CheckLanguage(filename, clean_lines, linenum, file_extension, include_state, + error): + """Checks rules from the 'C++ language rules' section of cppguide.html. + + Some of these rules are hard to test (function overloading, using + uint32 inappropriately), but we do the best we can. + + Args: + filename: The name of the current file. + clean_lines: A CleansedLines instance containing the file. + linenum: The number of the line to check. + file_extension: The extension (without the dot) of the filename. + include_state: An _IncludeState instance in which the headers are inserted. + error: The function to call with any errors found. + """ + # If the line is empty or consists of entirely a comment, no need to + # check it. + line = clean_lines.elided[linenum] + if not line: + return + + match = _RE_PATTERN_INCLUDE.search(line) + if match: + CheckIncludeLine(filename, clean_lines, linenum, include_state, error) + return + + # Create an extended_line, which is the concatenation of the current and + # next lines, for more effective checking of code that may span more than one + # line. + if linenum + 1 < clean_lines.NumLines(): + extended_line = line + clean_lines.elided[linenum + 1] + else: + extended_line = line + + # Make Windows paths like Unix. + fullname = os.path.abspath(filename).replace('\\', '/') + + # TODO(unknown): figure out if they're using default arguments in fn proto. + + # Check for non-const references in functions. This is tricky because & + # is also used to take the address of something. We allow <> for templates, + # (ignoring whatever is between the braces) and : for classes. + # These are complicated re's. They try to capture the following: + # paren (for fn-prototype start), typename, &, varname. For the const + # version, we're willing for const to be before typename or after + # Don't check the implemention on same line. + fnline = line.split('{', 1)[0] + if (len(re.findall(r'\([^()]*\b(?:[\w:]|<[^()]*>)+(\s?&|&\s?)\w+', fnline)) > + len(re.findall(r'\([^()]*\bconst\s+(?:typename\s+)?(?:struct\s+)?' + r'(?:[\w:]|<[^()]*>)+(\s?&|&\s?)\w+', fnline)) + + len(re.findall(r'\([^()]*\b(?:[\w:]|<[^()]*>)+\s+const(\s?&|&\s?)[\w]+', + fnline))): + + # We allow non-const references in a few standard places, like functions + # called "swap()" or iostream operators like "<<" or ">>". + if not Search( + r'(swap|Swap|operator[<>][<>])\s*\(\s*(?:[\w:]|<.*>)+\s*&', + fnline): + error(filename, linenum, 'runtime/references', 2, + 'Is this a non-const reference? ' + 'If so, make const or use a pointer.') + + # Check to see if they're using an conversion function cast. + # I just try to capture the most common basic types, though there are more. + # Parameterless conversion functions, such as bool(), are allowed as they are + # probably a member operator declaration or default constructor. + match = Search( + r'(\bnew\s+)?\b' # Grab 'new' operator, if it's there + r'(int|float|double|bool|char|int32|uint32|int64|uint64)\([^)]', line) + if match: + # gMock methods are defined using some variant of MOCK_METHODx(name, type) + # where type may be float(), int(string), etc. Without context they are + # virtually indistinguishable from int(x) casts. + if (match.group(1) is None and # If new operator, then this isn't a cast + not Match(r'^\s*MOCK_(CONST_)?METHOD\d+(_T)?\(', line)): + error(filename, linenum, 'readability/casting', 4, + 'Using deprecated casting style. ' + 'Use static_cast<%s>(...) instead' % + match.group(2)) + + CheckCStyleCast(filename, linenum, line, clean_lines.raw_lines[linenum], + 'static_cast', + r'\((int|float|double|bool|char|u?int(16|32|64))\)', + error) + # This doesn't catch all cases. Consider (const char * const)"hello". + CheckCStyleCast(filename, linenum, line, clean_lines.raw_lines[linenum], + 'reinterpret_cast', r'\((\w+\s?\*+\s?)\)', error) + + # In addition, we look for people taking the address of a cast. This + # is dangerous -- casts can assign to temporaries, so the pointer doesn't + # point where you think. + if Search( + r'(&\([^)]+\)[\w(])|(&(static|dynamic|reinterpret)_cast\b)', line): + error(filename, linenum, 'runtime/casting', 4, + ('Are you taking an address of a cast? ' + 'This is dangerous: could be a temp var. ' + 'Take the address before doing the cast, rather than after')) + + # Check for people declaring static/global STL strings at the top level. + # This is dangerous because the C++ language does not guarantee that + # globals with constructors are initialized before the first access. + match = Match( + r'((?:|static +)(?:|const +))string +([a-zA-Z0-9_:]+)\b(.*)', + line) + # Make sure it's not a function. + # Function template specialization looks like: "string foo(...". + # Class template definitions look like: "string Foo::Method(...". + if match and not Match(r'\s*(<.*>)?(::[a-zA-Z0-9_]+)?\s*\(([^"]|$)', + match.group(3)): + error(filename, linenum, 'runtime/string', 4, + 'For a static/global string constant, use a C style string instead: ' + '"%schar %s[]".' % + (match.group(1), match.group(2))) + + # Check that we're not using RTTI outside of testing code. + if Search(r'\bdynamic_cast<', line) and not _IsTestFilename(filename): + error(filename, linenum, 'runtime/rtti', 5, + 'Do not use dynamic_cast<>. If you need to cast within a class ' + "hierarchy, use static_cast<> to upcast. Google doesn't support " + 'RTTI.') + + if Search(r'\b([A-Za-z0-9_]*_)\(\1\)', line): + error(filename, linenum, 'runtime/init', 4, + 'You seem to be initializing a member variable with itself.') + + if file_extension == 'h': + # TODO(unknown): check that 1-arg constructors are explicit. + # How to tell it's a constructor? + # (handled in CheckForNonStandardConstructs for now) + # TODO(unknown): check that classes have DISALLOW_EVIL_CONSTRUCTORS + # (level 1 error) + pass + + # Check if people are using the verboten C basic types. The only exception + # we regularly allow is "unsigned short port" for port. + if Search(r'\bshort port\b', line): + if not Search(r'\bunsigned short port\b', line): + error(filename, linenum, 'runtime/int', 4, + 'Use "unsigned short" for ports, not "short"') + else: + match = Search(r'\b(short|long(?! +double)|long long)\b', line) + if match: + error(filename, linenum, 'runtime/int', 4, + 'Use int16/int64/etc, rather than the C type %s' % match.group(1)) + + # When snprintf is used, the second argument shouldn't be a literal. + match = Search(r'snprintf\s*\(([^,]*),\s*([0-9]*)\s*,', line) + if match and match.group(2) != '0': + # If 2nd arg is zero, snprintf is used to calculate size. + error(filename, linenum, 'runtime/printf', 3, + 'If you can, use sizeof(%s) instead of %s as the 2nd arg ' + 'to snprintf.' % (match.group(1), match.group(2))) + + # Check if some verboten C functions are being used. + if Search(r'\bsprintf\b', line): + error(filename, linenum, 'runtime/printf', 5, + 'Never use sprintf. Use snprintf instead.') + match = Search(r'\b(strcpy|strcat)\b', line) + if match: + error(filename, linenum, 'runtime/printf', 4, + 'Almost always, snprintf is better than %s' % match.group(1)) + + if Search(r'\bsscanf\b', line): + error(filename, linenum, 'runtime/printf', 1, + 'sscanf can be ok, but is slow and can overflow buffers.') + + # Check if some verboten operator overloading is going on + # TODO(unknown): catch out-of-line unary operator&: + # class X {}; + # int operator&(const X& x) { return 42; } // unary operator& + # The trick is it's hard to tell apart from binary operator&: + # class Y { int operator&(const Y& x) { return 23; } }; // binary operator& + if Search(r'\boperator\s*&\s*\(\s*\)', line): + error(filename, linenum, 'runtime/operator', 4, + 'Unary operator& is dangerous. Do not use it.') + + # Check for suspicious usage of "if" like + # } if (a == b) { + if Search(r'\}\s*if\s*\(', line): + error(filename, linenum, 'readability/braces', 4, + 'Did you mean "else if"? If not, start a new line for "if".') + + # Check for potential format string bugs like printf(foo). + # We constrain the pattern not to pick things like DocidForPrintf(foo). + # Not perfect but it can catch printf(foo.c_str()) and printf(foo->c_str()) + match = re.search(r'\b((?:string)?printf)\s*\(([\w.\->()]+)\)', line, re.I) + if match: + error(filename, linenum, 'runtime/printf', 4, + 'Potential format string bug. Do %s("%%s", %s) instead.' + % (match.group(1), match.group(2))) + + # Check for potential memset bugs like memset(buf, sizeof(buf), 0). + match = Search(r'memset\s*\(([^,]*),\s*([^,]*),\s*0\s*\)', line) + if match and not Match(r"^''|-?[0-9]+|0x[0-9A-Fa-f]$", match.group(2)): + error(filename, linenum, 'runtime/memset', 4, + 'Did you mean "memset(%s, 0, %s)"?' + % (match.group(1), match.group(2))) + + if Search(r'\busing namespace\b', line): + error(filename, linenum, 'build/namespaces', 5, + 'Do not use namespace using-directives. ' + 'Use using-declarations instead.') + + # Detect variable-length arrays. + match = Match(r'\s*(.+::)?(\w+) [a-z]\w*\[(.+)];', line) + if (match and match.group(2) != 'return' and match.group(2) != 'delete' and + match.group(3).find(']') == -1): + # Split the size using space and arithmetic operators as delimiters. + # If any of the resulting tokens are not compile time constants then + # report the error. + tokens = re.split(r'\s|\+|\-|\*|\/|<<|>>]', match.group(3)) + is_const = True + skip_next = False + for tok in tokens: + if skip_next: + skip_next = False + continue + + if Search(r'sizeof\(.+\)', tok): continue + if Search(r'arraysize\(\w+\)', tok): continue + + tok = tok.lstrip('(') + tok = tok.rstrip(')') + if not tok: continue + if Match(r'\d+', tok): continue + if Match(r'0[xX][0-9a-fA-F]+', tok): continue + if Match(r'k[A-Z0-9]\w*', tok): continue + if Match(r'(.+::)?k[A-Z0-9]\w*', tok): continue + if Match(r'(.+::)?[A-Z][A-Z0-9_]*', tok): continue + # A catch all for tricky sizeof cases, including 'sizeof expression', + # 'sizeof(*type)', 'sizeof(const type)', 'sizeof(struct StructName)' + # requires skipping the next token becasue we split on ' ' and '*'. + if tok.startswith('sizeof'): + skip_next = True + continue + is_const = False + break + if not is_const: + error(filename, linenum, 'runtime/arrays', 1, + 'Do not use variable-length arrays. Use an appropriately named ' + "('k' followed by CamelCase) compile-time constant for the size.") + + # If DISALLOW_EVIL_CONSTRUCTORS, DISALLOW_COPY_AND_ASSIGN, or + # DISALLOW_IMPLICIT_CONSTRUCTORS is present, then it should be the last thing + # in the class declaration. + match = Match( + (r'\s*' + r'(DISALLOW_(EVIL_CONSTRUCTORS|COPY_AND_ASSIGN|IMPLICIT_CONSTRUCTORS))' + r'\(.*\);$'), + line) + if match and linenum + 1 < clean_lines.NumLines(): + next_line = clean_lines.elided[linenum + 1] + if not Search(r'^\s*};', next_line): + error(filename, linenum, 'readability/constructors', 3, + match.group(1) + ' should be the last thing in the class') + + # Check for use of unnamed namespaces in header files. Registration + # macros are typically OK, so we allow use of "namespace {" on lines + # that end with backslashes. + if (file_extension == 'h' + and Search(r'\bnamespace\s*{', line) + and line[-1] != '\\'): + error(filename, linenum, 'build/namespaces', 4, + 'Do not use unnamed namespaces in header files. See ' + 'http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml#Namespaces' + ' for more information.') + + +def CheckCStyleCast(filename, linenum, line, raw_line, cast_type, pattern, + error): + """Checks for a C-style cast by looking for the pattern. + + This also handles sizeof(type) warnings, due to similarity of content. + + Args: + filename: The name of the current file. + linenum: The number of the line to check. + line: The line of code to check. + raw_line: The raw line of code to check, with comments. + cast_type: The string for the C++ cast to recommend. This is either + reinterpret_cast or static_cast, depending. + pattern: The regular expression used to find C-style casts. + error: The function to call with any errors found. + """ + match = Search(pattern, line) + if not match: + return + + # e.g., sizeof(int) + sizeof_match = Match(r'.*sizeof\s*$', line[0:match.start(1) - 1]) + if sizeof_match: + error(filename, linenum, 'runtime/sizeof', 1, + 'Using sizeof(type). Use sizeof(varname) instead if possible') + return + + remainder = line[match.end(0):] + + # The close paren is for function pointers as arguments to a function. + # eg, void foo(void (*bar)(int)); + # The semicolon check is a more basic function check; also possibly a + # function pointer typedef. + # eg, void foo(int); or void foo(int) const; + # The equals check is for function pointer assignment. + # eg, void *(*foo)(int) = ... + # + # Right now, this will only catch cases where there's a single argument, and + # it's unnamed. It should probably be expanded to check for multiple + # arguments with some unnamed. + function_match = Match(r'\s*(\)|=|(const)?\s*(;|\{|throw\(\)))', remainder) + if function_match: + if (not function_match.group(3) or + function_match.group(3) == ';' or + raw_line.find('/*') < 0): + error(filename, linenum, 'readability/function', 3, + 'All parameters should be named in a function') + return + + # At this point, all that should be left is actual casts. + error(filename, linenum, 'readability/casting', 4, + 'Using C-style cast. Use %s<%s>(...) instead' % + (cast_type, match.group(1))) + + +_HEADERS_CONTAINING_TEMPLATES = ( + ('', ('deque',)), + ('', ('unary_function', 'binary_function', + 'plus', 'minus', 'multiplies', 'divides', 'modulus', + 'negate', + 'equal_to', 'not_equal_to', 'greater', 'less', + 'greater_equal', 'less_equal', + 'logical_and', 'logical_or', 'logical_not', + 'unary_negate', 'not1', 'binary_negate', 'not2', + 'bind1st', 'bind2nd', + 'pointer_to_unary_function', + 'pointer_to_binary_function', + 'ptr_fun', + 'mem_fun_t', 'mem_fun', 'mem_fun1_t', 'mem_fun1_ref_t', + 'mem_fun_ref_t', + 'const_mem_fun_t', 'const_mem_fun1_t', + 'const_mem_fun_ref_t', 'const_mem_fun1_ref_t', + 'mem_fun_ref', + )), + ('', ('numeric_limits',)), + ('', ('list',)), + ('', ('map', 'multimap',)), + ('', ('allocator',)), + ('', ('queue', 'priority_queue',)), + ('', ('set', 'multiset',)), + ('', ('stack',)), + ('', ('char_traits', 'basic_string',)), + ('', ('pair',)), + ('', ('vector',)), + + # gcc extensions. + # Note: std::hash is their hash, ::hash is our hash + ('', ('hash_map', 'hash_multimap',)), + ('', ('hash_set', 'hash_multiset',)), + ('', ('slist',)), + ) + +_HEADERS_ACCEPTED_BUT_NOT_PROMOTED = { + # We can trust with reasonable confidence that map gives us pair<>, too. + 'pair<>': ('map', 'multimap', 'hash_map', 'hash_multimap') +} + +_RE_PATTERN_STRING = re.compile(r'\bstring\b') + +_re_pattern_algorithm_header = [] +for _template in ('copy', 'max', 'min', 'min_element', 'sort', 'swap', + 'transform'): + # Match max(..., ...), max(..., ...), but not foo->max, foo.max or + # type::max(). + _re_pattern_algorithm_header.append( + (re.compile(r'[^>.]\b' + _template + r'(<.*?>)?\([^\)]'), + _template, + '')) + +_re_pattern_templates = [] +for _header, _templates in _HEADERS_CONTAINING_TEMPLATES: + for _template in _templates: + _re_pattern_templates.append( + (re.compile(r'(\<|\b)' + _template + r'\s*\<'), + _template + '<>', + _header)) + + +def FilesBelongToSameModule(filename_cc, filename_h): + """Check if these two filenames belong to the same module. + + The concept of a 'module' here is a as follows: + foo.h, foo-inl.h, foo.cc, foo_test.cc and foo_unittest.cc belong to the + same 'module' if they are in the same directory. + some/path/public/xyzzy and some/path/internal/xyzzy are also considered + to belong to the same module here. + + If the filename_cc contains a longer path than the filename_h, for example, + '/absolute/path/to/base/sysinfo.cc', and this file would include + 'base/sysinfo.h', this function also produces the prefix needed to open the + header. This is used by the caller of this function to more robustly open the + header file. We don't have access to the real include paths in this context, + so we need this guesswork here. + + Known bugs: tools/base/bar.cc and base/bar.h belong to the same module + according to this implementation. Because of this, this function gives + some false positives. This should be sufficiently rare in practice. + + Args: + filename_cc: is the path for the .cc file + filename_h: is the path for the header path + + Returns: + Tuple with a bool and a string: + bool: True if filename_cc and filename_h belong to the same module. + string: the additional prefix needed to open the header file. + """ + + if not filename_cc.endswith('.cc'): + return (False, '') + filename_cc = filename_cc[:-len('.cc')] + if filename_cc.endswith('_unittest'): + filename_cc = filename_cc[:-len('_unittest')] + elif filename_cc.endswith('_test'): + filename_cc = filename_cc[:-len('_test')] + filename_cc = filename_cc.replace('/public/', '/') + filename_cc = filename_cc.replace('/internal/', '/') + + if not filename_h.endswith('.h'): + return (False, '') + filename_h = filename_h[:-len('.h')] + if filename_h.endswith('-inl'): + filename_h = filename_h[:-len('-inl')] + filename_h = filename_h.replace('/public/', '/') + filename_h = filename_h.replace('/internal/', '/') + + files_belong_to_same_module = filename_cc.endswith(filename_h) + common_path = '' + if files_belong_to_same_module: + common_path = filename_cc[:-len(filename_h)] + return files_belong_to_same_module, common_path + + +def UpdateIncludeState(filename, include_state, io=codecs): + """Fill up the include_state with new includes found from the file. + + Args: + filename: the name of the header to read. + include_state: an _IncludeState instance in which the headers are inserted. + io: The io factory to use to read the file. Provided for testability. + + Returns: + True if a header was succesfully added. False otherwise. + """ + headerfile = None + try: + headerfile = io.open(filename, 'r', 'utf8', 'replace') + except IOError: + return False + linenum = 0 + for line in headerfile: + linenum += 1 + clean_line = CleanseComments(line) + match = _RE_PATTERN_INCLUDE.search(clean_line) + if match: + include = match.group(2) + # The value formatting is cute, but not really used right now. + # What matters here is that the key is in include_state. + include_state.setdefault(include, '%s:%d' % (filename, linenum)) + return True + + +def CheckForIncludeWhatYouUse(filename, clean_lines, include_state, error, + io=codecs): + """Reports for missing stl includes. + + This function will output warnings to make sure you are including the headers + necessary for the stl containers and functions that you use. We only give one + reason to include a header. For example, if you use both equal_to<> and + less<> in a .h file, only one (the latter in the file) of these will be + reported as a reason to include the . + + Args: + filename: The name of the current file. + clean_lines: A CleansedLines instance containing the file. + include_state: An _IncludeState instance. + error: The function to call with any errors found. + io: The IO factory to use to read the header file. Provided for unittest + injection. + """ + required = {} # A map of header name to linenumber and the template entity. + # Example of required: { '': (1219, 'less<>') } + + for linenum in xrange(clean_lines.NumLines()): + line = clean_lines.elided[linenum] + if not line or line[0] == '#': + continue + + # String is special -- it is a non-templatized type in STL. + m = _RE_PATTERN_STRING.search(line) + if m: + # Don't warn about strings in non-STL namespaces: + # (We check only the first match per line; good enough.) + prefix = line[:m.start()] + if prefix.endswith('std::') or not prefix.endswith('::'): + required[''] = (linenum, 'string') + + for pattern, template, header in _re_pattern_algorithm_header: + if pattern.search(line): + required[header] = (linenum, template) + + # The following function is just a speed up, no semantics are changed. + if not '<' in line: # Reduces the cpu time usage by skipping lines. + continue + + for pattern, template, header in _re_pattern_templates: + if pattern.search(line): + required[header] = (linenum, template) + + # The policy is that if you #include something in foo.h you don't need to + # include it again in foo.cc. Here, we will look at possible includes. + # Let's copy the include_state so it is only messed up within this function. + include_state = include_state.copy() + + # Did we find the header for this file (if any) and succesfully load it? + header_found = False + + # Use the absolute path so that matching works properly. + abs_filename = os.path.abspath(filename) + + # For Emacs's flymake. + # If cpplint is invoked from Emacs's flymake, a temporary file is generated + # by flymake and that file name might end with '_flymake.cc'. In that case, + # restore original file name here so that the corresponding header file can be + # found. + # e.g. If the file name is 'foo_flymake.cc', we should search for 'foo.h' + # instead of 'foo_flymake.h' + abs_filename = re.sub(r'_flymake\.cc$', '.cc', abs_filename) + + # include_state is modified during iteration, so we iterate over a copy of + # the keys. + for header in include_state.keys(): #NOLINT + (same_module, common_path) = FilesBelongToSameModule(abs_filename, header) + fullpath = common_path + header + if same_module and UpdateIncludeState(fullpath, include_state, io): + header_found = True + + # If we can't find the header file for a .cc, assume it's because we don't + # know where to look. In that case we'll give up as we're not sure they + # didn't include it in the .h file. + # TODO(unknown): Do a better job of finding .h files so we are confident that + # not having the .h file means there isn't one. + if filename.endswith('.cc') and not header_found: + return + + # All the lines have been processed, report the errors found. + for required_header_unstripped in required: + template = required[required_header_unstripped][1] + if template in _HEADERS_ACCEPTED_BUT_NOT_PROMOTED: + headers = _HEADERS_ACCEPTED_BUT_NOT_PROMOTED[template] + if [True for header in headers if header in include_state]: + continue + if required_header_unstripped.strip('<>"') not in include_state: + error(filename, required[required_header_unstripped][0], + 'build/include_what_you_use', 4, + 'Add #include ' + required_header_unstripped + ' for ' + template) + + +def ProcessLine(filename, file_extension, + clean_lines, line, include_state, function_state, + class_state, error): + """Processes a single line in the file. + + Args: + filename: Filename of the file that is being processed. + file_extension: The extension (dot not included) of the file. + clean_lines: An array of strings, each representing a line of the file, + with comments stripped. + line: Number of line being processed. + include_state: An _IncludeState instance in which the headers are inserted. + function_state: A _FunctionState instance which counts function lines, etc. + class_state: A _ClassState instance which maintains information about + the current stack of nested class declarations being parsed. + error: A callable to which errors are reported, which takes 4 arguments: + filename, line number, error level, and message + + """ + raw_lines = clean_lines.raw_lines + ParseNolintSuppressions(filename, raw_lines[line], line, error) + CheckForFunctionLengths(filename, clean_lines, line, function_state, error) + CheckForMultilineCommentsAndStrings(filename, clean_lines, line, error) + CheckStyle(filename, clean_lines, line, file_extension, error) + CheckLanguage(filename, clean_lines, line, file_extension, include_state, + error) + CheckForNonStandardConstructs(filename, clean_lines, line, + class_state, error) + CheckPosixThreading(filename, clean_lines, line, error) + CheckInvalidIncrement(filename, clean_lines, line, error) + + +def ProcessFileData(filename, file_extension, lines, error): + """Performs lint checks and reports any errors to the given error function. + + Args: + filename: Filename of the file that is being processed. + file_extension: The extension (dot not included) of the file. + lines: An array of strings, each representing a line of the file, with the + last element being empty if the file is termined with a newline. + error: A callable to which errors are reported, which takes 4 arguments: + """ + lines = (['// marker so line numbers and indices both start at 1'] + lines + + ['// marker so line numbers end in a known way']) + + include_state = _IncludeState() + function_state = _FunctionState() + class_state = _ClassState() + + ResetNolintSuppressions() + + CheckForCopyright(filename, lines, error) + + if file_extension == 'h': + CheckForHeaderGuard(filename, lines, error) + + RemoveMultiLineComments(filename, lines, error) + clean_lines = CleansedLines(lines) + for line in xrange(clean_lines.NumLines()): + ProcessLine(filename, file_extension, clean_lines, line, + include_state, function_state, class_state, error) + class_state.CheckFinished(filename, error) + + CheckForIncludeWhatYouUse(filename, clean_lines, include_state, error) + + # We check here rather than inside ProcessLine so that we see raw + # lines rather than "cleaned" lines. + CheckForUnicodeReplacementCharacters(filename, lines, error) + + CheckForNewlineAtEOF(filename, lines, error) + +def ProcessFile(filename, vlevel): + """Does google-lint on a single file. + + Args: + filename: The name of the file to parse. + + vlevel: The level of errors to report. Every error of confidence + >= verbose_level will be reported. 0 is a good default. + """ + + _SetVerboseLevel(vlevel) + + try: + # Support the UNIX convention of using "-" for stdin. Note that + # we are not opening the file with universal newline support + # (which codecs doesn't support anyway), so the resulting lines do + # contain trailing '\r' characters if we are reading a file that + # has CRLF endings. + # If after the split a trailing '\r' is present, it is removed + # below. If it is not expected to be present (i.e. os.linesep != + # '\r\n' as in Windows), a warning is issued below if this file + # is processed. + + if filename == '-': + lines = codecs.StreamReaderWriter(sys.stdin, + codecs.getreader('utf8'), + codecs.getwriter('utf8'), + 'replace').read().split('\n') + else: + lines = codecs.open(filename, 'r', 'utf8', 'replace').read().split('\n') + + carriage_return_found = False + # Remove trailing '\r'. + for linenum in range(len(lines)): + if lines[linenum].endswith('\r'): + lines[linenum] = lines[linenum].rstrip('\r') + carriage_return_found = True + + except IOError: + sys.stderr.write( + "Skipping input '%s': Can't open for reading\n" % filename) + return + + # Note, if no dot is found, this will give the entire filename as the ext. + file_extension = filename[filename.rfind('.') + 1:] + + # When reading from stdin, the extension is unknown, so no cpplint tests + # should rely on the extension. + if (filename != '-' and file_extension != 'cc' and file_extension != 'h' + and file_extension != 'cpp'): + sys.stderr.write('Ignoring %s; not a .cc or .h file\n' % filename) + else: + ProcessFileData(filename, file_extension, lines, Error) + if carriage_return_found and os.linesep != '\r\n': + # Use 0 for linenum since outputing only one error for potentially + # several lines. + Error(filename, 0, 'whitespace/newline', 1, + 'One or more unexpected \\r (^M) found;' + 'better to use only a \\n') + + sys.stderr.write('Done processing %s\n' % filename) + + +def PrintUsage(message): + """Prints a brief usage string and exits, optionally with an error message. + + Args: + message: The optional error message. + """ + sys.stderr.write(_USAGE) + if message: + sys.exit('\nFATAL ERROR: ' + message) + else: + sys.exit(1) + + +def PrintCategories(): + """Prints a list of all the error-categories used by error messages. + + These are the categories used to filter messages via --filter. + """ + sys.stderr.write(''.join(' %s\n' % cat for cat in _ERROR_CATEGORIES)) + sys.exit(0) + + +def ParseArguments(args): + """Parses the command line arguments. + + This may set the output format and verbosity level as side-effects. + + Args: + args: The command line arguments: + + Returns: + The list of filenames to lint. + """ + try: + (opts, filenames) = getopt.getopt(args, '', ['help', 'output=', 'verbose=', + 'counting=', + 'filter=']) + except getopt.GetoptError: + PrintUsage('Invalid arguments.') + + verbosity = _VerboseLevel() + output_format = _OutputFormat() + filters = '' + counting_style = '' + + for (opt, val) in opts: + if opt == '--help': + PrintUsage(None) + elif opt == '--output': + if not val in ('emacs', 'vs7'): + PrintUsage('The only allowed output formats are emacs and vs7.') + output_format = val + elif opt == '--verbose': + verbosity = int(val) + elif opt == '--filter': + filters = val + if not filters: + PrintCategories() + elif opt == '--counting': + if val not in ('total', 'toplevel', 'detailed'): + PrintUsage('Valid counting options are total, toplevel, and detailed') + counting_style = val + + if not filenames: + PrintUsage('No files were specified.') + + _SetOutputFormat(output_format) + _SetVerboseLevel(verbosity) + _SetFilters(filters) + _SetCountingStyle(counting_style) + + return filenames + + +def main(): + filenames = ParseArguments(sys.argv[1:]) + + # Change stderr to write with replacement characters so we don't die + # if we try to print something containing non-ASCII characters. + sys.stderr = codecs.StreamReaderWriter(sys.stderr, + codecs.getreader('utf8'), + codecs.getwriter('utf8'), + 'replace') + + _cpplint_state.ResetErrorCounts() + for filename in filenames: + ProcessFile(filename, _cpplint_state.verbose_level) + _cpplint_state.PrintErrorCounts() + + sys.exit(_cpplint_state.error_count > 0) + + +if __name__ == '__main__': + main() diff --git a/node-v0.8.14/tools/doc/LICENSE b/node-v0.8.14/tools/doc/LICENSE new file mode 100644 index 0000000..e3d4e69 --- /dev/null +++ b/node-v0.8.14/tools/doc/LICENSE @@ -0,0 +1,18 @@ +Copyright Joyent, Inc. and other Node contributors. All rights reserved. +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to +deal in the Software without restriction, including without limitation the +rights to use, copy, modify, merge, publish, distribute, sublicense, and/or +sell copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS +IN THE SOFTWARE. diff --git a/node-v0.8.14/tools/doc/README.md b/node-v0.8.14/tools/doc/README.md new file mode 100644 index 0000000..67ff2e1 --- /dev/null +++ b/node-v0.8.14/tools/doc/README.md @@ -0,0 +1,96 @@ +Here's how the node docs work. + +1:1 relationship from `lib/.js` to `doc/api/.markdown` + +Each type of heading has a description block. + + + ## module + + Stability: 3 - Stable + + description and examples. + + ### module.property + + * Type + + description of the property. + + ### module.someFunction(x, y, [z=100]) + + * `x` {String} the description of the string + * `y` {Boolean} Should I stay or should I go? + * `z` {Number} How many zebras to bring. + + A description of the function. + + ### Event: 'blerg' + + * Argument: SomeClass object. + + Modules don't usually raise events on themselves. `cluster` is the + only exception. + + ## Class: SomeClass + + description of the class. + + ### Class Method: SomeClass.classMethod(anArg) + + * `anArg` {Object} Just an argument + * `field` {String} anArg can have this field. + * `field2` {Boolean} Another field. Default: `false`. + * Return: {Boolean} `true` if it worked. + + Description of the method for humans. + + ### someClass.nextSibling() + + * Return: {SomeClass object | null} The next someClass in line. + + ### someClass.someProperty + + * String + + The indication of what someProperty is. + + ### Event: 'grelb' + + * `isBlerg` {Boolean} + + This event is emitted on instances of SomeClass, not on the module itself. + + +* Modules have (description, Properties, Functions, Classes, Examples) +* Properties have (type, description) +* Functions have (list of arguments, description) +* Classes have (description, Properties, Methods, Events) +* Events have (list of arguments, description) +* Methods have (list of arguments, description) +* Properties have (type, description) + +## Stability ratings: 0-5 + +These can show up below any section heading, and apply to that section. + +0 - Deprecated. This feature is known to be problematic, and changes are +planned. Do not rely on it. Use of the feature may cause warnings. Backwards +compatibility should not be expected. + +1 - Experimental. This feature was introduced recently, and may change +or be removed in future versions. Please try it out and provide feedback. +If it addresses a use-case that is important to you, tell the node core team. + +2 - Unstable. The API is in the process of settling, but has not yet had +sufficient real-world testing to be considered stable. Backwards-compatibility +will be maintained if reasonable. + +3 - Stable. The API has proven satisfactory, but cleanup in the underlying +code may cause minor changes. Backwards-compatibility is guaranteed. + +4 - API Frozen. This API has been tested extensively in production and is +unlikely to ever have to change. + +5 - Locked. Unless serious bugs are found, this code will not ever +change. Please do not suggest changes in this area, they will be refused. diff --git a/node-v0.8.14/tools/doc/generate.js b/node-v0.8.14/tools/doc/generate.js new file mode 100755 index 0000000..2bab2f3 --- /dev/null +++ b/node-v0.8.14/tools/doc/generate.js @@ -0,0 +1,119 @@ +#!/usr/bin/env node +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var marked = require('marked'); +var fs = require('fs'); +var path = require('path'); + +// parse the args. +// Don't use nopt or whatever for this. It's simple enough. + +var args = process.argv.slice(2); +var format = 'json'; +var template = null; +var inputFile = null; + +args.forEach(function (arg) { + if (!arg.match(/^\-\-/)) { + inputFile = arg; + } else if (arg.match(/^\-\-format=/)) { + format = arg.replace(/^\-\-format=/, ''); + } else if (arg.match(/^\-\-template=/)) { + template = arg.replace(/^\-\-template=/, ''); + } +}) + + +if (!inputFile) { + throw new Error('No input file specified'); +} + + +console.error('Input file = %s', inputFile); +fs.readFile(inputFile, 'utf8', function(er, input) { + if (er) throw er; + // process the input for @include lines + processIncludes(input, next); +}); + + +var includeExpr = /^@include\s+([A-Za-z0-9-_]+)(?:\.)?([a-zA-Z]*)$/gmi; +var includeData = {}; +function processIncludes(input, cb) { + var includes = input.match(includeExpr); + if (includes === null) return cb(null, input); + var errState = null; + console.error(includes); + var incCount = includes.length; + if (incCount === 0) cb(null, input); + includes.forEach(function(include) { + var fname = include.replace(/^@include\s+/, ''); + if (!fname.match(/\.markdown$/)) fname += '.markdown'; + + if (includeData.hasOwnProperty(fname)) { + input = input.split(include).join(includeData[fname]); + incCount--; + if (incCount === 0) { + return cb(null, input); + } + } + + var fullFname = path.resolve(path.dirname(inputFile), fname); + fs.readFile(fullFname, 'utf8', function(er, inc) { + if (errState) return; + if (er) return cb(errState = er); + processIncludes(inc, function(er, inc) { + if (errState) return; + if (er) return cb(errState = er); + incCount--; + includeData[fname] = inc; + input = input.split(include+'\n').join(includeData[fname]+'\n'); + if (incCount === 0) { + return cb(null, input); + } + }); + }); + }); +} + + +function next(er, input) { + if (er) throw er; + switch (format) { + case 'json': + require('./json.js')(input, inputFile, function(er, obj) { + console.log(JSON.stringify(obj, null, 2)); + if (er) throw er; + }); + break; + + case 'html': + require('./html.js')(input, inputFile, template, function(er, html) { + if (er) throw er; + console.log(html); + }); + break; + + default: + throw new Error('Invalid format: ' + format); + } +} diff --git a/node-v0.8.14/tools/doc/html.js b/node-v0.8.14/tools/doc/html.js new file mode 100644 index 0000000..63c7c14 --- /dev/null +++ b/node-v0.8.14/tools/doc/html.js @@ -0,0 +1,174 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var fs = require('fs'); +var marked = require('marked'); +var path = require('path'); + +module.exports = toHTML; + +function toHTML(input, filename, template, cb) { + var lexed = marked.lexer(input); + fs.readFile(template, 'utf8', function(er, template) { + if (er) return cb(er); + render(lexed, filename, template, cb); + }); +} + +function render(lexed, filename, template, cb) { + // get the section + var section = getSection(lexed); + + filename = path.basename(filename, '.markdown'); + + lexed = parseLists(lexed); + + // generate the table of contents. + // this mutates the lexed contents in-place. + buildToc(lexed, filename, function(er, toc) { + if (er) return cb(er); + + template = template.replace(/__FILENAME__/g, filename); + template = template.replace(/__SECTION__/g, section); + template = template.replace(/__VERSION__/g, process.version); + template = template.replace(/__TOC__/g, toc); + + // content has to be the last thing we do with + // the lexed tokens, because it's destructive. + content = marked.parser(lexed); + template = template.replace(/__CONTENT__/g, content); + + cb(null, template); + }); +} + + +// just update the list item text in-place. +// lists that come right after a heading are what we're after. +function parseLists(input) { + var state = null; + var depth = 0; + var output = []; + output.links = input.links; + input.forEach(function(tok) { + if (state === null) { + if (tok.type === 'heading') { + state = 'AFTERHEADING'; + } + output.push(tok); + return; + } + if (state === 'AFTERHEADING') { + if (tok.type === 'list_start') { + state = 'LIST'; + if (depth === 0) { + output.push({ type:'html', text: '

' }); + } + depth++; + output.push(tok); + return; + } + state = null; + output.push(tok); + return; + } + if (state === 'LIST') { + if (tok.type === 'list_start') { + depth++; + output.push(tok); + return; + } + if (tok.type === 'list_end') { + depth--; + if (depth === 0) { + state = null; + output.push({ type:'html', text: '
' }); + } + output.push(tok); + return; + } + if (tok.text) { + tok.text = parseListItem(tok.text); + } + } + output.push(tok); + }); + + return output; +} + + +function parseListItem(text) { + text = text.replace(/\{([^\}]+)\}/, '$1'); + //XXX maybe put more stuff here? + return text; +} + + +// section is just the first heading +function getSection(lexed) { + var section = ''; + for (var i = 0, l = lexed.length; i < l; i++) { + var tok = lexed[i]; + if (tok.type === 'heading') return tok.text; + } + return ''; +} + + +function buildToc(lexed, filename, cb) { + var indent = 0; + var toc = []; + var depth = 0; + lexed.forEach(function(tok) { + if (tok.type !== 'heading') return; + if (tok.depth - depth > 1) { + return cb(new Error('Inappropriate heading level\n' + + JSON.stringify(tok))); + } + + depth = tok.depth; + var id = getId(filename + '_' + tok.text.trim()); + toc.push(new Array((depth - 1) * 2 + 1).join(' ') + + '* ' + + tok.text + ''); + tok.text += '#'; + }); + + toc = marked.parse(toc.join('\n')); + cb(null, toc); +} + +var idCounters = {}; +function getId(text) { + text = text.toLowerCase(); + text = text.replace(/[^a-z0-9]+/g, '_'); + text = text.replace(/^_+|_+$/, ''); + text = text.replace(/^([^a-z])/, '_$1'); + if (idCounters.hasOwnProperty(text)) { + text += '_' + (++idCounters[text]); + } else { + idCounters[text] = 0; + } + return text; +} + diff --git a/node-v0.8.14/tools/doc/json.js b/node-v0.8.14/tools/doc/json.js new file mode 100644 index 0000000..2459bc2 --- /dev/null +++ b/node-v0.8.14/tools/doc/json.js @@ -0,0 +1,557 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +module.exports = doJSON; + +// Take the lexed input, and return a JSON-encoded object +// A module looks like this: https://gist.github.com/1777387 + +var marked = require('marked'); + +function doJSON(input, filename, cb) { + var root = {source: filename}; + var stack = [root]; + var depth = 0; + var current = root; + var state = null; + var lexed = marked.lexer(input); + lexed.forEach(function (tok) { + var type = tok.type; + var text = tok.text; + + // + // This is for cases where the markdown semantic structure is lacking. + if (type === 'paragraph' || type === 'html') { + var metaExpr = /\n*/g; + text = text.replace(metaExpr, function(_0, k, v) { + current[k.trim()] = v.trim(); + return ''; + }); + text = text.trim(); + if (!text) return; + } + + if (type === 'heading' && + !text.trim().match(/^example/i)) { + if (tok.depth - depth > 1) { + return cb(new Error('Inappropriate heading level\n'+ + JSON.stringify(tok))); + } + + // Sometimes we have two headings with a single + // blob of description. Treat as a clone. + if (current && + state === 'AFTERHEADING' && + depth === tok.depth) { + var clone = current; + current = newSection(tok); + current.clone = clone; + // don't keep it around on the stack. + stack.pop(); + } else { + // if the level is greater than the current depth, + // then it's a child, so we should just leave the stack + // as it is. + // However, if it's a sibling or higher, then it implies + // the closure of the other sections that came before. + // root is always considered the level=0 section, + // and the lowest heading is 1, so this should always + // result in having a valid parent node. + var d = tok.depth; + while (d <= depth) { + finishSection(stack.pop(), stack[stack.length - 1]); + d++; + } + current = newSection(tok); + } + + depth = tok.depth; + stack.push(current); + state = 'AFTERHEADING'; + return; + } // heading + + // Immediately after a heading, we can expect the following + // + // { type: 'code', text: 'Stability: ...' }, + // + // a list: starting with list_start, ending with list_end, + // maybe containing other nested lists in each item. + // + // If one of these isnt' found, then anything that comes between + // here and the next heading should be parsed as the desc. + var stability + if (state === 'AFTERHEADING') { + if (type === 'code' && + (stability = text.match(/^Stability: ([0-5])(?:\s*-\s*)?(.*)$/))) { + current.stability = parseInt(stability[1], 10); + current.stabilityText = stability[2].trim(); + return; + } else if (type === 'list_start' && !tok.ordered) { + state = 'AFTERHEADING_LIST'; + current.list = current.list || []; + current.list.push(tok); + current.list.level = 1; + } else { + current.desc = current.desc || []; + if (!Array.isArray(current.desc)) { + current.shortDesc = current.desc; + current.desc = []; + } + current.desc.push(tok); + state = 'DESC'; + } + return; + } + + if (state === 'AFTERHEADING_LIST') { + current.list.push(tok); + if (type === 'list_start') { + current.list.level++; + } else if (type === 'list_end') { + current.list.level--; + } + if (current.list.level === 0) { + state = 'AFTERHEADING'; + processList(current); + } + return; + } + + current.desc = current.desc || []; + current.desc.push(tok); + + }); + + // finish any sections left open + while (root !== (current = stack.pop())) { + finishSection(current, stack[stack.length - 1]); + } + + return cb(null, root) +} + + +// go from something like this: +// [ { type: 'list_item_start' }, +// { type: 'text', +// text: '`settings` Object, Optional' }, +// { type: 'list_start', ordered: false }, +// { type: 'list_item_start' }, +// { type: 'text', +// text: 'exec: String, file path to worker file. Default: `__filename`' }, +// { type: 'list_item_end' }, +// { type: 'list_item_start' }, +// { type: 'text', +// text: 'args: Array, string arguments passed to worker.' }, +// { type: 'text', +// text: 'Default: `process.argv.slice(2)`' }, +// { type: 'list_item_end' }, +// { type: 'list_item_start' }, +// { type: 'text', +// text: 'silent: Boolean, whether or not to send output to parent\'s stdio.' }, +// { type: 'text', text: 'Default: `false`' }, +// { type: 'space' }, +// { type: 'list_item_end' }, +// { type: 'list_end' }, +// { type: 'list_item_end' }, +// { type: 'list_end' } ] +// to something like: +// [ { name: 'settings', +// type: 'object', +// optional: true, +// settings: +// [ { name: 'exec', +// type: 'string', +// desc: 'file path to worker file', +// default: '__filename' }, +// { name: 'args', +// type: 'array', +// default: 'process.argv.slice(2)', +// desc: 'string arguments passed to worker.' }, +// { name: 'silent', +// type: 'boolean', +// desc: 'whether or not to send output to parent\'s stdio.', +// default: 'false' } ] } ] + +function processList(section) { + var list = section.list; + var values = []; + var current; + var stack = []; + + // for now, *just* build the heirarchical list + list.forEach(function(tok) { + var type = tok.type; + if (type === 'space') return; + if (type === 'list_item_start') { + if (!current) { + var n = {}; + values.push(n); + current = n; + } else { + current.options = current.options || []; + stack.push(current); + var n = {}; + current.options.push(n); + current = n; + } + return; + } else if (type === 'list_item_end') { + if (!current) { + throw new Error('invalid list - end without current item\n' + + JSON.stringify(tok) + '\n' + + JSON.stringify(list)); + } + current = stack.pop(); + } else if (type === 'text') { + if (!current) { + throw new Error('invalid list - text without current item\n' + + JSON.stringify(tok) + '\n' + + JSON.stringify(list)); + } + current.textRaw = current.textRaw || ''; + current.textRaw += tok.text + ' '; + } + }); + + // shove the name in there for properties, since they are always + // just going to be the value etc. + if (section.type === 'property' && values[0]) { + values[0].textRaw = '`' + section.name + '` ' + values[0].textRaw; + } + + // now pull the actual values out of the text bits. + values.forEach(parseListItem); + + // Now figure out what this list actually means. + // depending on the section type, the list could be different things. + + switch (section.type) { + case 'ctor': + case 'classMethod': + case 'method': + // each item is an argument, unless the name is 'return', + // in which case it's the return value. + section.signatures = section.signatures || []; + var sig = {} + section.signatures.push(sig); + sig.params = values.filter(function(v) { + if (v.name === 'return') { + sig.return = v; + return false; + } + return true; + }); + parseSignature(section.textRaw, sig); + break; + + case 'property': + // there should be only one item, which is the value. + // copy the data up to the section. + var value = values[0] || {}; + delete value.name; + section.typeof = value.type; + delete value.type; + Object.keys(value).forEach(function(k) { + section[k] = value[k]; + }); + break; + + case 'event': + // event: each item is an argument. + section.params = values; + break; + } + + // section.listParsed = values; + delete section.list; +} + + +// textRaw = "someobject.someMethod(a, [b=100], [c])" +function parseSignature(text, sig) { + var params = text.match(paramExpr); + if (!params) return; + params = params[1]; + // the ] is irrelevant. [ indicates optionalness. + params = params.replace(/\]/g, ''); + params = params.split(/,/) + params.forEach(function(p, i, _) { + p = p.trim(); + if (!p) return; + var param = sig.params[i]; + var optional = false; + var def; + // [foo] -> optional + if (p.charAt(0) === '[') { + optional = true; + p = p.substr(1); + } + var eq = p.indexOf('='); + if (eq !== -1) { + def = p.substr(eq + 1); + p = p.substr(0, eq); + } + if (!param) { + param = sig.params[i] = { name: p }; + } + // at this point, the name should match. + if (p !== param.name) { + console.error('Warning: invalid param "%s"', p); + console.error(' > ' + JSON.stringify(param)); + console.error(' > ' + text); + } + if (optional) param.optional = true; + if (def !== undefined) param.default = def; + }); +} + + +function parseListItem(item) { + if (item.options) item.options.forEach(parseListItem); + if (!item.textRaw) return; + + // the goal here is to find the name, type, default, and optional. + // anything left over is 'desc' + var text = item.textRaw.trim(); + // text = text.replace(/^(Argument|Param)s?\s*:?\s*/i, ''); + + text = text.replace(/^, /, '').trim(); + var retExpr = /^returns?\s*:?\s*/i; + var ret = text.match(retExpr); + if (ret) { + item.name = 'return'; + text = text.replace(retExpr, ''); + } else { + var nameExpr = /^['`"]?([^'`": \{]+)['`"]?\s*:?\s*/; + var name = text.match(nameExpr); + if (name) { + item.name = name[1]; + text = text.replace(nameExpr, ''); + } + } + + text = text.trim(); + var defaultExpr = /\(default\s*[:=]?\s*['"`]?([^, '"`]*)['"`]?\)/i; + var def = text.match(defaultExpr); + if (def) { + item.default = def[1]; + text = text.replace(defaultExpr, ''); + } + + text = text.trim(); + var typeExpr = /^\{([^\}]+)\}/; + var type = text.match(typeExpr); + if (type) { + item.type = type[1]; + text = text.replace(typeExpr, ''); + } + + text = text.trim(); + var optExpr = /^Optional\.|(?:, )?Optional$/; + var optional = text.match(optExpr); + if (optional) { + item.optional = true; + text = text.replace(optExpr, ''); + } + + text = text.replace(/^\s*-\s*/, ''); + text = text.trim(); + if (text) item.desc = text; +} + + +function finishSection(section, parent) { + if (!section || !parent) { + throw new Error('Invalid finishSection call\n'+ + JSON.stringify(section) + '\n' + + JSON.stringify(parent)); + } + + if (!section.type) { + section.type = 'module'; + if (parent && (parent.type === 'misc')) { + section.type = 'misc'; + } + section.displayName = section.name; + section.name = section.name.toLowerCase() + .trim().replace(/\s+/g, '_'); + } + + if (section.desc && Array.isArray(section.desc)) { + section.desc.links = section.desc.links || []; + section.desc = marked.parser(section.desc); + } + + if (!section.list) section.list = []; + processList(section); + + // classes sometimes have various 'ctor' children + // which are actually just descriptions of a constructor + // class signature. + // Merge them into the parent. + if (section.type === 'class' && section.ctors) { + section.signatures = section.signatures || []; + var sigs = section.signatures; + section.ctors.forEach(function(ctor) { + ctor.signatures = ctor.signatures || [{}]; + ctor.signatures.forEach(function(sig) { + sig.desc = ctor.desc; + }); + sigs.push.apply(sigs, ctor.signatures); + }); + delete section.ctors; + } + + // properties are a bit special. + // their "type" is the type of object, not "property" + if (section.properties) { + section.properties.forEach(function (p) { + if (p.typeof) p.type = p.typeof; + else delete p.type; + delete p.typeof; + }); + } + + // handle clones + if (section.clone) { + var clone = section.clone; + delete section.clone; + delete clone.clone; + deepCopy(section, clone); + finishSection(clone, parent); + } + + var plur; + if (section.type.slice(-1) === 's') { + plur = section.type + 'es'; + } else if (section.type.slice(-1) === 'y') { + plur = section.type.replace(/y$/, 'ies'); + } else { + plur = section.type + 's'; + } + + // if the parent's type is 'misc', then it's just a random + // collection of stuff, like the "globals" section. + // Make the children top-level items. + if (section.type === 'misc') { + Object.keys(section).forEach(function(k) { + switch (k) { + case 'textRaw': + case 'name': + case 'type': + case 'desc': + case 'miscs': + return; + default: + if (parent.type === 'misc') { + return; + } + if (Array.isArray(k) && parent[k]) { + parent[k] = parent[k].concat(section[k]); + } else if (!parent[k]) { + parent[k] = section[k]; + } else { + // parent already has, and it's not an array. + return; + } + } + }); + } + + parent[plur] = parent[plur] || []; + parent[plur].push(section); +} + + +// Not a general purpose deep copy. +// But sufficient for these basic things. +function deepCopy(src, dest) { + Object.keys(src).filter(function(k) { + return !dest.hasOwnProperty(k); + }).forEach(function(k) { + dest[k] = deepCopy_(src[k]); + }); +} + +function deepCopy_(src) { + if (!src) return src; + if (Array.isArray(src)) { + var c = new Array(src.length); + src.forEach(function(v, i) { + c[i] = deepCopy_(v); + }); + return c; + } + if (typeof src === 'object') { + var c = {}; + Object.keys(src).forEach(function(k) { + c[k] = deepCopy_(src[k]); + }); + return c; + } + return src; +} + + +// these parse out the contents of an H# tag +var eventExpr = /^Event(?::|\s)+['"]?([^"']+).*$/i; +var classExpr = /^Class:\s*([^ ]+).*?$/i; +var propExpr = /^(?:property:?\s*)?[^\.]+\.([^ \.\(\)]+)\s*?$/i; +var braceExpr = /^(?:property:?\s*)?[^\.\[]+(\[[^\]]+\])\s*?$/i; +var classMethExpr = + /^class\s*method\s*:?[^\.]+\.([^ \.\(\)]+)\([^\)]*\)\s*?$/i; +var methExpr = + /^(?:method:?\s*)?(?:[^\.]+\.)?([^ \.\(\)]+)\([^\)]*\)\s*?$/i; +var newExpr = /^new ([A-Z][a-z]+)\([^\)]*\)\s*?$/; +var paramExpr = /\((.*)\);?$/; + +function newSection(tok) { + var section = {}; + // infer the type from the text. + var text = section.textRaw = tok.text; + if (text.match(eventExpr)) { + section.type = 'event'; + section.name = text.replace(eventExpr, '$1'); + } else if (text.match(classExpr)) { + section.type = 'class'; + section.name = text.replace(classExpr, '$1'); + } else if (text.match(braceExpr)) { + section.type = 'property'; + section.name = text.replace(braceExpr, '$1'); + } else if (text.match(propExpr)) { + section.type = 'property'; + section.name = text.replace(propExpr, '$1'); + } else if (text.match(classMethExpr)) { + section.type = 'classMethod'; + section.name = text.replace(classMethExpr, '$1'); + } else if (text.match(methExpr)) { + section.type = 'method'; + section.name = text.replace(methExpr, '$1'); + } else if (text.match(newExpr)) { + section.type = 'ctor'; + section.name = text.replace(newExpr, '$1'); + } else { + section.name = text; + } + return section; +} diff --git a/node-v0.8.14/tools/doc/package.json b/node-v0.8.14/tools/doc/package.json new file mode 100644 index 0000000..d87c934 --- /dev/null +++ b/node-v0.8.14/tools/doc/package.json @@ -0,0 +1,15 @@ +{ + "author": "Isaac Z. Schlueter (http://blog.izs.me/)", + "name": "node-doc-generator", + "description": "Internal tool for generating Node.js API docs", + "version": "0.0.0", + "engines": { + "node": ">=0.6.10" + }, + "dependencies": { + "marked": "~0.1.9" + }, + "devDependencies": {}, + "optionalDependencies": {}, + "bin": "./generate.js" +} diff --git a/node-v0.8.14/tools/email-footer.md b/node-v0.8.14/tools/email-footer.md new file mode 100644 index 0000000..3eb22d9 --- /dev/null +++ b/node-v0.8.14/tools/email-footer.md @@ -0,0 +1,23 @@ +Source Code: http://nodejs.org/dist/__VERSION__/node-__VERSION__.tar.gz + +Macintosh Installer (Universal): http://nodejs.org/dist/__VERSION__/node-__VERSION__.pkg + +Windows Installer: http://nodejs.org/dist/__VERSION__/node-__VERSION__-x86.msi + +Windows x64 Installer: http://nodejs.org/dist/__VERSION__/x64/node-__VERSION__-x64.msi + +Windows x64 Files: http://nodejs.org/dist/__VERSION__/x64/ + +Linux 32-bit Binary: http://nodejs.org/dist/__VERSION__/node-__VERSION__-linux-x86.tar.gz + +Linux 64-bit Binary: http://nodejs.org/dist/__VERSION__/node-__VERSION__-linux-x64.tar.gz + +Solaris 32-bit Binary: http://nodejs.org/dist/__VERSION__/node-__VERSION__-sunos-x86.tar.gz + +Solaris 64-bit Binary: http://nodejs.org/dist/__VERSION__/node-__VERSION__-sunos-x64.tar.gz + +Other release files: http://nodejs.org/dist/__VERSION__/ + +Website: http://nodejs.org/docs/__VERSION__/ + +Documentation: http://nodejs.org/docs/__VERSION__/api/ diff --git a/node-v0.8.14/tools/genv8constants.py b/node-v0.8.14/tools/genv8constants.py new file mode 100755 index 0000000..efc6441 --- /dev/null +++ b/node-v0.8.14/tools/genv8constants.py @@ -0,0 +1,82 @@ +#!/usr/bin/env python + +# +# genv8constants.py output_file libv8_base.a +# +# Emits v8dbg constants stored in libv8_base.a in a format suitable for the V8 +# ustack helper. +# + +import re +import subprocess +import sys + +if len(sys.argv) != 3: + print "usage: objsym.py outfile libv8_base.a" + sys.exit(2); + +outfile = file(sys.argv[1], 'w'); +pipe = subprocess.Popen([ 'objdump', '-z', '-D', sys.argv[2] ], + bufsize=-1, stdout=subprocess.PIPE).stdout; +pattern = re.compile('00000000 <(v8dbg_.*)>:'); +numpattern = re.compile('[0-9a-fA-F]{2}'); + +outfile.write(""" +/* + * File automatically generated by genv8constants. Do not edit. + * + * The following offsets are dynamically from libv8_base.a. See src/v8ustack.d + * for details on how these values are used. + */ + +#ifndef V8_CONSTANTS_H +#define V8_CONSTANTS_H + +#if defined(__i386) +"""); + +curr_sym = None; +curr_val = 0; +curr_octet = 0; + +for line in pipe: + if curr_sym != None: + # + # This bit of code has nasty knowledge of the objdump text output + # format, but this is the most obvious robust approach. We could almost + # rely on looking at numbered fields, but some instructions look very + # much like hex numbers (e.g., "adc"), and we don't want to risk picking + # those up by mistake, so we look at character-based columns intead. + # + for i in range (0, 3): + # 6-character margin, 2-characters + 1 space for each field + idx = 6 + i * 3; + octetstr = line[idx:idx+2] + if not numpattern.match(octetstr): + break; + + curr_val += int('0x%s' % octetstr, 16) << (curr_octet * 8); + curr_octet += 1; + + if curr_octet < 4: + continue; + + outfile.write("#define %s 0x%x\n" % (curr_sym.upper(), curr_val)); + curr_sym = None; + curr_val = 0; + curr_octet = 0; + continue; + + match = pattern.match(line) + if match == None: + continue; + + curr_sym = match.group(1); + +outfile.write(""" +#else +#error "only i386 is supported for DTrace ustack helper" +#endif + +#endif /* V8_CONSTANTS_H */ +"""); diff --git a/node-v0.8.14/tools/getnodeisrelease.py b/node-v0.8.14/tools/getnodeisrelease.py new file mode 100644 index 0000000..a23ad2c --- /dev/null +++ b/node-v0.8.14/tools/getnodeisrelease.py @@ -0,0 +1,11 @@ +import sys,os,re + +node_version_h = os.path.join(os.path.dirname(__file__), '..', 'src', + 'node_version.h') + +f = open(node_version_h) + +for line in f: + if re.match('#define NODE_VERSION_IS_RELEASE', line): + release = int(line.split()[2]) + print release diff --git a/node-v0.8.14/tools/getnodeversion.py b/node-v0.8.14/tools/getnodeversion.py new file mode 100644 index 0000000..766e4f6 --- /dev/null +++ b/node-v0.8.14/tools/getnodeversion.py @@ -0,0 +1,16 @@ +import os,re + +node_version_h = os.path.join(os.path.dirname(__file__), '..', 'src', + 'node_version.h') + +f = open(node_version_h) + +for line in f: + if re.match('#define NODE_MAJOR_VERSION', line): + major = line.split()[2] + if re.match('#define NODE_MINOR_VERSION', line): + minor = line.split()[2] + if re.match('#define NODE_PATCH_VERSION', line): + patch = line.split()[2] + +print '%(major)s.%(minor)s.%(patch)s'% locals() diff --git a/node-v0.8.14/tools/gyp/.gitignore b/node-v0.8.14/tools/gyp/.gitignore new file mode 100644 index 0000000..0d20b64 --- /dev/null +++ b/node-v0.8.14/tools/gyp/.gitignore @@ -0,0 +1 @@ +*.pyc diff --git a/node-v0.8.14/tools/gyp/AUTHORS b/node-v0.8.14/tools/gyp/AUTHORS new file mode 100644 index 0000000..6db82b9 --- /dev/null +++ b/node-v0.8.14/tools/gyp/AUTHORS @@ -0,0 +1,6 @@ +# Names should be added to this file like so: +# Name or Organization + +Google Inc. +Steven Knight +Ryan Norton diff --git a/node-v0.8.14/tools/gyp/DEPS b/node-v0.8.14/tools/gyp/DEPS new file mode 100644 index 0000000..c17571a --- /dev/null +++ b/node-v0.8.14/tools/gyp/DEPS @@ -0,0 +1,26 @@ +# DEPS file for gclient use in buildbot execution of gyp tests. +# +# (You don't need to use gclient for normal GYP development work.) + +vars = { + "chrome_trunk": "http://src.chromium.org/svn/trunk", + "googlecode_url": "http://%s.googlecode.com/svn", +} + +deps = { + "scons": + Var("chrome_trunk") + "/src/third_party/scons@44099", +} + +deps_os = { + "win": { + "third_party/cygwin": + Var("chrome_trunk") + "/deps/third_party/cygwin@66844", + + "third_party/python_26": + Var("chrome_trunk") + "/tools/third_party/python_26@89111", + + "src/third_party/pefile": + (Var("googlecode_url") % "pefile") + "/trunk@63", + }, +} diff --git a/node-v0.8.14/tools/gyp/LICENSE b/node-v0.8.14/tools/gyp/LICENSE new file mode 100644 index 0000000..ab6b011 --- /dev/null +++ b/node-v0.8.14/tools/gyp/LICENSE @@ -0,0 +1,27 @@ +Copyright (c) 2009 Google Inc. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above +copyright notice, this list of conditions and the following disclaimer +in the documentation and/or other materials provided with the +distribution. + * Neither the name of Google Inc. nor the names of its +contributors may be used to endorse or promote products derived from +this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/node-v0.8.14/tools/gyp/MANIFEST b/node-v0.8.14/tools/gyp/MANIFEST new file mode 100644 index 0000000..925ecc1 --- /dev/null +++ b/node-v0.8.14/tools/gyp/MANIFEST @@ -0,0 +1,21 @@ +setup.py +gyp +LICENSE +AUTHORS +pylib/gyp/MSVSNew.py +pylib/gyp/MSVSProject.py +pylib/gyp/MSVSToolFile.py +pylib/gyp/MSVSUserFile.py +pylib/gyp/MSVSVersion.py +pylib/gyp/SCons.py +pylib/gyp/__init__.py +pylib/gyp/common.py +pylib/gyp/input.py +pylib/gyp/xcodeproj_file.py +pylib/gyp/generator/__init__.py +pylib/gyp/generator/gypd.py +pylib/gyp/generator/gypsh.py +pylib/gyp/generator/make.py +pylib/gyp/generator/msvs.py +pylib/gyp/generator/scons.py +pylib/gyp/generator/xcode.py diff --git a/node-v0.8.14/tools/gyp/OWNERS b/node-v0.8.14/tools/gyp/OWNERS new file mode 100644 index 0000000..72e8ffc --- /dev/null +++ b/node-v0.8.14/tools/gyp/OWNERS @@ -0,0 +1 @@ +* diff --git a/node-v0.8.14/tools/gyp/PRESUBMIT.py b/node-v0.8.14/tools/gyp/PRESUBMIT.py new file mode 100644 index 0000000..0338fb4 --- /dev/null +++ b/node-v0.8.14/tools/gyp/PRESUBMIT.py @@ -0,0 +1,109 @@ +# Copyright (c) 2012 Google Inc. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + + +"""Top-level presubmit script for GYP. + +See http://dev.chromium.org/developers/how-tos/depottools/presubmit-scripts +for more details about the presubmit API built into gcl. +""" + + +PYLINT_BLACKLIST = [ + # TODO: fix me. + # From SCons, not done in google style. + 'test/lib/TestCmd.py', + 'test/lib/TestCommon.py', + 'test/lib/TestGyp.py', + # Needs style fix. + 'pylib/gyp/generator/scons.py', + 'pylib/gyp/generator/xcode.py', +] + + +PYLINT_DISABLED_WARNINGS = [ + # TODO: fix me. + # Many tests include modules they don't use. + 'W0611', + # Include order doesn't properly include local files? + 'F0401', + # Some use of built-in names. + 'W0622', + # Some unused variables. + 'W0612', + # Operator not preceded/followed by space. + 'C0323', + 'C0322', + # Unnecessary semicolon. + 'W0301', + # Unused argument. + 'W0613', + # String has no effect (docstring in wrong place). + 'W0105', + # Comma not followed by space. + 'C0324', + # Access to a protected member. + 'W0212', + # Bad indent. + 'W0311', + # Line too long. + 'C0301', + # Undefined variable. + 'E0602', + # Not exception type specified. + 'W0702', + # No member of that name. + 'E1101', + # Dangerous default {}. + 'W0102', + # Others, too many to sort. + 'W0201', 'W0232', 'E1103', 'W0621', 'W0108', 'W0223', 'W0231', + 'R0201', 'E0101', 'C0321', + # ************* Module copy + # W0104:427,12:_test.odict.__setitem__: Statement seems to have no effect + 'W0104', +] + + +def CheckChangeOnUpload(input_api, output_api): + report = [] + report.extend(input_api.canned_checks.PanProjectChecks( + input_api, output_api)) + return report + + +def CheckChangeOnCommit(input_api, output_api): + report = [] + license = ( + r'.*? Copyright \(c\) %(year)s Google Inc\. All rights reserved\.\n' + r'.*? Use of this source code is governed by a BSD-style license that ' + r'can be\n' + r'.*? found in the LICENSE file\.\n' + ) % { + 'year': input_api.time.strftime('%Y'), + } + + report.extend(input_api.canned_checks.PanProjectChecks( + input_api, output_api, license_header=license)) + report.extend(input_api.canned_checks.CheckTreeIsOpen( + input_api, output_api, + 'http://gyp-status.appspot.com/status', + 'http://gyp-status.appspot.com/current')) + + import sys + old_sys_path = sys.path + try: + sys.path = ['pylib', 'test/lib'] + sys.path + report.extend(input_api.canned_checks.RunPylint( + input_api, + output_api, + black_list=PYLINT_BLACKLIST, + disabled_warnings=PYLINT_DISABLED_WARNINGS)) + finally: + sys.path = old_sys_path + return report + + +def GetPreferredTrySlaves(): + return ['gyp-win32', 'gyp-win64', 'gyp-linux', 'gyp-mac'] diff --git a/node-v0.8.14/tools/gyp/buildbot/buildbot_run.py b/node-v0.8.14/tools/gyp/buildbot/buildbot_run.py new file mode 100755 index 0000000..57fdb65 --- /dev/null +++ b/node-v0.8.14/tools/gyp/buildbot/buildbot_run.py @@ -0,0 +1,98 @@ +#!/usr/bin/env python +# Copyright (c) 2012 Google Inc. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + + +"""Argument-less script to select what to run on the buildbots.""" + + +import os +import shutil +import subprocess +import sys + + +if sys.platform in ['win32', 'cygwin']: + EXE_SUFFIX = '.exe' +else: + EXE_SUFFIX = '' + + +BUILDBOT_DIR = os.path.dirname(os.path.abspath(__file__)) +TRUNK_DIR = os.path.dirname(BUILDBOT_DIR) +ROOT_DIR = os.path.dirname(TRUNK_DIR) +OUT_DIR = os.path.join(TRUNK_DIR, 'out') + + +def GypTestFormat(title, format=None, msvs_version=None): + """Run the gyp tests for a given format, emitting annotator tags. + + See annotator docs at: + https://sites.google.com/a/chromium.org/dev/developers/testing/chromium-build-infrastructure/buildbot-annotations + Args: + format: gyp format to test. + Returns: + 0 for sucesss, 1 for failure. + """ + if not format: + format = title + + print '@@@BUILD_STEP ' + title + '@@@' + sys.stdout.flush() + env = os.environ.copy() + # TODO(bradnelson): remove this when this issue is resolved: + # http://code.google.com/p/chromium/issues/detail?id=108251 + if format == 'ninja': + env['NOGOLD'] = '1' + if msvs_version: + env['GYP_MSVS_VERSION'] = msvs_version + retcode = subprocess.call(' '.join( + [sys.executable, 'trunk/gyptest.py', + '--all', + '--passed', + '--format', format, + '--chdir', 'trunk', + '--path', '../scons']), + cwd=ROOT_DIR, env=env, shell=True) + if retcode: + # Emit failure tag, and keep going. + print '@@@STEP_FAILURE@@@' + return 1 + return 0 + + +def GypBuild(): + # Dump out/ directory. + print '@@@BUILD_STEP cleanup@@@' + print 'Removing %s...' % OUT_DIR + shutil.rmtree(OUT_DIR, ignore_errors=True) + print 'Done.' + + retcode = 0 + if sys.platform.startswith('linux'): + retcode += GypTestFormat('ninja') + retcode += GypTestFormat('scons') + retcode += GypTestFormat('make') + elif sys.platform == 'darwin': + retcode += GypTestFormat('ninja') + retcode += GypTestFormat('xcode') + retcode += GypTestFormat('make') + elif sys.platform == 'win32': + retcode += GypTestFormat('ninja') + retcode += GypTestFormat('msvs-2008', format='msvs', msvs_version='2008') + if os.environ['BUILDBOT_BUILDERNAME'] == 'gyp-win64': + retcode += GypTestFormat('msvs-2010', format='msvs', msvs_version='2010') + else: + raise Exception('Unknown platform') + if retcode: + # TODO(bradnelson): once the annotator supports a postscript (section for + # after the build proper that could be used for cumulative failures), + # use that instead of this. This isolates the final return value so + # that it isn't misattributed to the last stage. + print '@@@BUILD_STEP failures@@@' + sys.exit(retcode) + + +if __name__ == '__main__': + GypBuild() diff --git a/node-v0.8.14/tools/gyp/codereview.settings b/node-v0.8.14/tools/gyp/codereview.settings new file mode 100644 index 0000000..a04a244 --- /dev/null +++ b/node-v0.8.14/tools/gyp/codereview.settings @@ -0,0 +1,10 @@ +# This file is used by gcl to get repository specific information. +CODE_REVIEW_SERVER: codereview.chromium.org +CC_LIST: gyp-developer@googlegroups.com +VIEW_VC: http://code.google.com/p/gyp/source/detail?r= +TRY_ON_UPLOAD: True +TRYSERVER_PROJECT: gyp +TRYSERVER_PATCHLEVEL: 0 +TRYSERVER_ROOT: trunk +TRYSERVER_SVN_URL: svn://svn.chromium.org/chrome-try/try-nacl + diff --git a/node-v0.8.14/tools/gyp/gyp b/node-v0.8.14/tools/gyp/gyp new file mode 100755 index 0000000..d52e711 --- /dev/null +++ b/node-v0.8.14/tools/gyp/gyp @@ -0,0 +1,18 @@ +#!/usr/bin/env python + +# Copyright (c) 2009 Google Inc. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +import sys + +# TODO(mark): sys.path manipulation is some temporary testing stuff. +try: + import gyp +except ImportError, e: + import os.path + sys.path.append(os.path.join(os.path.dirname(sys.argv[0]), 'pylib')) + import gyp + +if __name__ == '__main__': + sys.exit(gyp.main(sys.argv[1:])) diff --git a/node-v0.8.14/tools/gyp/gyp.bat b/node-v0.8.14/tools/gyp/gyp.bat new file mode 100755 index 0000000..90fbc6d --- /dev/null +++ b/node-v0.8.14/tools/gyp/gyp.bat @@ -0,0 +1,5 @@ +@rem Copyright (c) 2009 Google Inc. All rights reserved. +@rem Use of this source code is governed by a BSD-style license that can be +@rem found in the LICENSE file. + +@python "%~dp0/gyp" %* diff --git a/node-v0.8.14/tools/gyp/gyp_dummy.c b/node-v0.8.14/tools/gyp/gyp_dummy.c new file mode 100644 index 0000000..fb55bbc --- /dev/null +++ b/node-v0.8.14/tools/gyp/gyp_dummy.c @@ -0,0 +1,7 @@ +/* Copyright (c) 2009 Google Inc. All rights reserved. + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. */ + +int main() { + return 0; +} diff --git a/node-v0.8.14/tools/gyp/gyptest.py b/node-v0.8.14/tools/gyp/gyptest.py new file mode 100755 index 0000000..c84f3d3 --- /dev/null +++ b/node-v0.8.14/tools/gyp/gyptest.py @@ -0,0 +1,264 @@ +#!/usr/bin/env python + +# Copyright (c) 2012 Google Inc. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +__doc__ = """ +gyptest.py -- test runner for GYP tests. +""" + +import os +import optparse +import subprocess +import sys + +class CommandRunner: + """ + Executor class for commands, including "commands" implemented by + Python functions. + """ + verbose = True + active = True + + def __init__(self, dictionary={}): + self.subst_dictionary(dictionary) + + def subst_dictionary(self, dictionary): + self._subst_dictionary = dictionary + + def subst(self, string, dictionary=None): + """ + Substitutes (via the format operator) the values in the specified + dictionary into the specified command. + + The command can be an (action, string) tuple. In all cases, we + perform substitution on strings and don't worry if something isn't + a string. (It's probably a Python function to be executed.) + """ + if dictionary is None: + dictionary = self._subst_dictionary + if dictionary: + try: + string = string % dictionary + except TypeError: + pass + return string + + def display(self, command, stdout=None, stderr=None): + if not self.verbose: + return + if type(command) == type(()): + func = command[0] + args = command[1:] + s = '%s(%s)' % (func.__name__, ', '.join(map(repr, args))) + if type(command) == type([]): + # TODO: quote arguments containing spaces + # TODO: handle meta characters? + s = ' '.join(command) + else: + s = self.subst(command) + if not s.endswith('\n'): + s += '\n' + sys.stdout.write(s) + sys.stdout.flush() + + def execute(self, command, stdout=None, stderr=None): + """ + Executes a single command. + """ + if not self.active: + return 0 + if type(command) == type(''): + command = self.subst(command) + cmdargs = shlex.split(command) + if cmdargs[0] == 'cd': + command = (os.chdir,) + tuple(cmdargs[1:]) + if type(command) == type(()): + func = command[0] + args = command[1:] + return func(*args) + else: + if stdout is sys.stdout: + # Same as passing sys.stdout, except python2.4 doesn't fail on it. + subout = None + else: + # Open pipe for anything else so Popen works on python2.4. + subout = subprocess.PIPE + if stderr is sys.stderr: + # Same as passing sys.stderr, except python2.4 doesn't fail on it. + suberr = None + elif stderr is None: + # Merge with stdout if stderr isn't specified. + suberr = subprocess.STDOUT + else: + # Open pipe for anything else so Popen works on python2.4. + suberr = subprocess.PIPE + p = subprocess.Popen(command, + shell=(sys.platform == 'win32'), + stdout=subout, + stderr=suberr) + p.wait() + if stdout is None: + self.stdout = p.stdout.read() + elif stdout is not sys.stdout: + stdout.write(p.stdout.read()) + if stderr not in (None, sys.stderr): + stderr.write(p.stderr.read()) + return p.returncode + + def run(self, command, display=None, stdout=None, stderr=None): + """ + Runs a single command, displaying it first. + """ + if display is None: + display = command + self.display(display) + return self.execute(command, stdout, stderr) + + +class Unbuffered: + def __init__(self, fp): + self.fp = fp + def write(self, arg): + self.fp.write(arg) + self.fp.flush() + def __getattr__(self, attr): + return getattr(self.fp, attr) + +sys.stdout = Unbuffered(sys.stdout) +sys.stderr = Unbuffered(sys.stderr) + + +def find_all_gyptest_files(directory): + result = [] + for root, dirs, files in os.walk(directory): + if '.svn' in dirs: + dirs.remove('.svn') + result.extend([ os.path.join(root, f) for f in files + if f.startswith('gyptest') and f.endswith('.py') ]) + result.sort() + return result + + +def main(argv=None): + if argv is None: + argv = sys.argv + + usage = "gyptest.py [-ahlnq] [-f formats] [test ...]" + parser = optparse.OptionParser(usage=usage) + parser.add_option("-a", "--all", action="store_true", + help="run all tests") + parser.add_option("-C", "--chdir", action="store", default=None, + help="chdir to the specified directory") + parser.add_option("-f", "--format", action="store", default='', + help="run tests with the specified formats") + parser.add_option("-G", '--gyp_option', action="append", default=[], + help="Add -G options to the gyp command line") + parser.add_option("-l", "--list", action="store_true", + help="list available tests and exit") + parser.add_option("-n", "--no-exec", action="store_true", + help="no execute, just print the command line") + parser.add_option("--passed", action="store_true", + help="report passed tests") + parser.add_option("--path", action="append", default=[], + help="additional $PATH directory") + parser.add_option("-q", "--quiet", action="store_true", + help="quiet, don't print test command lines") + opts, args = parser.parse_args(argv[1:]) + + if opts.chdir: + os.chdir(opts.chdir) + + if opts.path: + os.environ['PATH'] += ':' + ':'.join(opts.path) + + if not args: + if not opts.all: + sys.stderr.write('Specify -a to get all tests.\n') + return 1 + args = ['test'] + + tests = [] + for arg in args: + if os.path.isdir(arg): + tests.extend(find_all_gyptest_files(os.path.normpath(arg))) + else: + tests.append(arg) + + if opts.list: + for test in tests: + print test + sys.exit(0) + + CommandRunner.verbose = not opts.quiet + CommandRunner.active = not opts.no_exec + cr = CommandRunner() + + os.environ['PYTHONPATH'] = os.path.abspath('test/lib') + if not opts.quiet: + sys.stdout.write('PYTHONPATH=%s\n' % os.environ['PYTHONPATH']) + + passed = [] + failed = [] + no_result = [] + + if opts.format: + format_list = opts.format.split(',') + else: + # TODO: not duplicate this mapping from pylib/gyp/__init__.py + format_list = { + 'freebsd7': ['make'], + 'freebsd8': ['make'], + 'cygwin': ['msvs'], + 'win32': ['msvs', 'ninja'], + 'linux2': ['make', 'ninja'], + 'linux3': ['make', 'ninja'], + 'darwin': ['make', 'ninja', 'xcode'], + }[sys.platform] + + for format in format_list: + os.environ['TESTGYP_FORMAT'] = format + if not opts.quiet: + sys.stdout.write('TESTGYP_FORMAT=%s\n' % format) + + gyp_options = [] + for option in opts.gyp_option: + gyp_options += ['-G', option] + if gyp_options and not opts.quiet: + sys.stdout.write('Extra Gyp options: %s\n' % gyp_options) + + for test in tests: + status = cr.run([sys.executable, test] + gyp_options, + stdout=sys.stdout, + stderr=sys.stderr) + if status == 2: + no_result.append(test) + elif status: + failed.append(test) + else: + passed.append(test) + + if not opts.quiet: + def report(description, tests): + if tests: + if len(tests) == 1: + sys.stdout.write("\n%s the following test:\n" % description) + else: + fmt = "\n%s the following %d tests:\n" + sys.stdout.write(fmt % (description, len(tests))) + sys.stdout.write("\t" + "\n\t".join(tests) + "\n") + + if opts.passed: + report("Passed", passed) + report("Failed", failed) + report("No result from", no_result) + + if failed: + return 1 + else: + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/node-v0.8.14/tools/gyp/pylib/gyp/MSVSNew.py b/node-v0.8.14/tools/gyp/pylib/gyp/MSVSNew.py new file mode 100644 index 0000000..0865973 --- /dev/null +++ b/node-v0.8.14/tools/gyp/pylib/gyp/MSVSNew.py @@ -0,0 +1,341 @@ +# Copyright (c) 2012 Google Inc. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +"""New implementation of Visual Studio project generation for SCons.""" + +import os +import random + +import gyp.common + +# hashlib is supplied as of Python 2.5 as the replacement interface for md5 +# and other secure hashes. In 2.6, md5 is deprecated. Import hashlib if +# available, avoiding a deprecation warning under 2.6. Import md5 otherwise, +# preserving 2.4 compatibility. +try: + import hashlib + _new_md5 = hashlib.md5 +except ImportError: + import md5 + _new_md5 = md5.new + + +# Initialize random number generator +random.seed() + +# GUIDs for project types +ENTRY_TYPE_GUIDS = { + 'project': '{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}', + 'folder': '{2150E333-8FDC-42A3-9474-1A3956D46DE8}', +} + +#------------------------------------------------------------------------------ +# Helper functions + + +def MakeGuid(name, seed='msvs_new'): + """Returns a GUID for the specified target name. + + Args: + name: Target name. + seed: Seed for MD5 hash. + Returns: + A GUID-line string calculated from the name and seed. + + This generates something which looks like a GUID, but depends only on the + name and seed. This means the same name/seed will always generate the same + GUID, so that projects and solutions which refer to each other can explicitly + determine the GUID to refer to explicitly. It also means that the GUID will + not change when the project for a target is rebuilt. + """ + # Calculate a MD5 signature for the seed and name. + d = _new_md5(str(seed) + str(name)).hexdigest().upper() + # Convert most of the signature to GUID form (discard the rest) + guid = ('{' + d[:8] + '-' + d[8:12] + '-' + d[12:16] + '-' + d[16:20] + + '-' + d[20:32] + '}') + return guid + +#------------------------------------------------------------------------------ + + +class MSVSFolder(object): + """Folder in a Visual Studio project or solution.""" + + def __init__(self, path, name = None, entries = None, + guid = None, items = None): + """Initializes the folder. + + Args: + path: Full path to the folder. + name: Name of the folder. + entries: List of folder entries to nest inside this folder. May contain + Folder or Project objects. May be None, if the folder is empty. + guid: GUID to use for folder, if not None. + items: List of solution items to include in the folder project. May be + None, if the folder does not directly contain items. + """ + if name: + self.name = name + else: + # Use last layer. + self.name = os.path.basename(path) + + self.path = path + self.guid = guid + + # Copy passed lists (or set to empty lists) + self.entries = list(entries or []) + self.items = list(items or []) + + self.entry_type_guid = ENTRY_TYPE_GUIDS['folder'] + + def get_guid(self): + if self.guid is None: + # Use consistent guids for folders (so things don't regenerate). + self.guid = MakeGuid(self.path, seed='msvs_folder') + return self.guid + + +#------------------------------------------------------------------------------ + + +class MSVSProject(object): + """Visual Studio project.""" + + def __init__(self, path, name = None, dependencies = None, guid = None, + spec = None, build_file = None, config_platform_overrides = None, + fixpath_prefix = None): + """Initializes the project. + + Args: + path: Absolute path to the project file. + name: Name of project. If None, the name will be the same as the base + name of the project file. + dependencies: List of other Project objects this project is dependent + upon, if not None. + guid: GUID to use for project, if not None. + spec: Dictionary specifying how to build this project. + build_file: Filename of the .gyp file that the vcproj file comes from. + config_platform_overrides: optional dict of configuration platforms to + used in place of the default for this target. + fixpath_prefix: the path used to adjust the behavior of _fixpath + """ + self.path = path + self.guid = guid + self.spec = spec + self.build_file = build_file + # Use project filename if name not specified + self.name = name or os.path.splitext(os.path.basename(path))[0] + + # Copy passed lists (or set to empty lists) + self.dependencies = list(dependencies or []) + + self.entry_type_guid = ENTRY_TYPE_GUIDS['project'] + + if config_platform_overrides: + self.config_platform_overrides = config_platform_overrides + else: + self.config_platform_overrides = {} + self.fixpath_prefix = fixpath_prefix + self.msbuild_toolset = None + + def set_dependencies(self, dependencies): + self.dependencies = list(dependencies or []) + + def get_guid(self): + if self.guid is None: + # Set GUID from path + # TODO(rspangler): This is fragile. + # 1. We can't just use the project filename sans path, since there could + # be multiple projects with the same base name (for example, + # foo/unittest.vcproj and bar/unittest.vcproj). + # 2. The path needs to be relative to $SOURCE_ROOT, so that the project + # GUID is the same whether it's included from base/base.sln or + # foo/bar/baz/baz.sln. + # 3. The GUID needs to be the same each time this builder is invoked, so + # that we don't need to rebuild the solution when the project changes. + # 4. We should be able to handle pre-built project files by reading the + # GUID from the files. + self.guid = MakeGuid(self.name) + return self.guid + + def set_msbuild_toolset(self, msbuild_toolset): + self.msbuild_toolset = msbuild_toolset + +#------------------------------------------------------------------------------ + + +class MSVSSolution: + """Visual Studio solution.""" + + def __init__(self, path, version, entries=None, variants=None, + websiteProperties=True): + """Initializes the solution. + + Args: + path: Path to solution file. + version: Format version to emit. + entries: List of entries in solution. May contain Folder or Project + objects. May be None, if the folder is empty. + variants: List of build variant strings. If none, a default list will + be used. + websiteProperties: Flag to decide if the website properties section + is generated. + """ + self.path = path + self.websiteProperties = websiteProperties + self.version = version + + # Copy passed lists (or set to empty lists) + self.entries = list(entries or []) + + if variants: + # Copy passed list + self.variants = variants[:] + else: + # Use default + self.variants = ['Debug|Win32', 'Release|Win32'] + # TODO(rspangler): Need to be able to handle a mapping of solution config + # to project config. Should we be able to handle variants being a dict, + # or add a separate variant_map variable? If it's a dict, we can't + # guarantee the order of variants since dict keys aren't ordered. + + + # TODO(rspangler): Automatically write to disk for now; should delay until + # node-evaluation time. + self.Write() + + + def Write(self, writer=gyp.common.WriteOnDiff): + """Writes the solution file to disk. + + Raises: + IndexError: An entry appears multiple times. + """ + # Walk the entry tree and collect all the folders and projects. + all_entries = set() + entries_to_check = self.entries[:] + while entries_to_check: + e = entries_to_check.pop(0) + + # If this entry has been visited, nothing to do. + if e in all_entries: + continue + + all_entries.add(e) + + # If this is a folder, check its entries too. + if isinstance(e, MSVSFolder): + entries_to_check += e.entries + + # Sort by name then guid (so things are in order on vs2008). + def NameThenGuid(a, b): + if a.name < b.name: return -1 + if a.name > b.name: return 1 + if a.get_guid() < b.get_guid(): return -1 + if a.get_guid() > b.get_guid(): return 1 + return 0 + + all_entries = sorted(all_entries, NameThenGuid) + + # Open file and print header + f = writer(self.path) + f.write('Microsoft Visual Studio Solution File, ' + 'Format Version %s\r\n' % self.version.SolutionVersion()) + f.write('# %s\r\n' % self.version.Description()) + + # Project entries + sln_root = os.path.split(self.path)[0] + for e in all_entries: + relative_path = gyp.common.RelativePath(e.path, sln_root) + # msbuild does not accept an empty folder_name. + # use '.' in case relative_path is empty. + folder_name = relative_path.replace('/', '\\') or '.' + f.write('Project("%s") = "%s", "%s", "%s"\r\n' % ( + e.entry_type_guid, # Entry type GUID + e.name, # Folder name + folder_name, # Folder name (again) + e.get_guid(), # Entry GUID + )) + + # TODO(rspangler): Need a way to configure this stuff + if self.websiteProperties: + f.write('\tProjectSection(WebsiteProperties) = preProject\r\n' + '\t\tDebug.AspNetCompiler.Debug = "True"\r\n' + '\t\tRelease.AspNetCompiler.Debug = "False"\r\n' + '\tEndProjectSection\r\n') + + if isinstance(e, MSVSFolder): + if e.items: + f.write('\tProjectSection(SolutionItems) = preProject\r\n') + for i in e.items: + f.write('\t\t%s = %s\r\n' % (i, i)) + f.write('\tEndProjectSection\r\n') + + if isinstance(e, MSVSProject): + if e.dependencies: + f.write('\tProjectSection(ProjectDependencies) = postProject\r\n') + for d in e.dependencies: + f.write('\t\t%s = %s\r\n' % (d.get_guid(), d.get_guid())) + f.write('\tEndProjectSection\r\n') + + f.write('EndProject\r\n') + + # Global section + f.write('Global\r\n') + + # Configurations (variants) + f.write('\tGlobalSection(SolutionConfigurationPlatforms) = preSolution\r\n') + for v in self.variants: + f.write('\t\t%s = %s\r\n' % (v, v)) + f.write('\tEndGlobalSection\r\n') + + # Sort config guids for easier diffing of solution changes. + config_guids = [] + config_guids_overrides = {} + for e in all_entries: + if isinstance(e, MSVSProject): + config_guids.append(e.get_guid()) + config_guids_overrides[e.get_guid()] = e.config_platform_overrides + config_guids.sort() + + f.write('\tGlobalSection(ProjectConfigurationPlatforms) = postSolution\r\n') + for g in config_guids: + for v in self.variants: + nv = config_guids_overrides[g].get(v, v) + # Pick which project configuration to build for this solution + # configuration. + f.write('\t\t%s.%s.ActiveCfg = %s\r\n' % ( + g, # Project GUID + v, # Solution build configuration + nv, # Project build config for that solution config + )) + + # Enable project in this solution configuration. + f.write('\t\t%s.%s.Build.0 = %s\r\n' % ( + g, # Project GUID + v, # Solution build configuration + nv, # Project build config for that solution config + )) + f.write('\tEndGlobalSection\r\n') + + # TODO(rspangler): Should be able to configure this stuff too (though I've + # never seen this be any different) + f.write('\tGlobalSection(SolutionProperties) = preSolution\r\n') + f.write('\t\tHideSolutionNode = FALSE\r\n') + f.write('\tEndGlobalSection\r\n') + + # Folder mappings + # TODO(rspangler): Should omit this section if there are no folders + f.write('\tGlobalSection(NestedProjects) = preSolution\r\n') + for e in all_entries: + if not isinstance(e, MSVSFolder): + continue # Does not apply to projects, only folders + for subentry in e.entries: + f.write('\t\t%s = %s\r\n' % (subentry.get_guid(), e.get_guid())) + f.write('\tEndGlobalSection\r\n') + + f.write('EndGlobal\r\n') + + f.close() diff --git a/node-v0.8.14/tools/gyp/pylib/gyp/MSVSProject.py b/node-v0.8.14/tools/gyp/pylib/gyp/MSVSProject.py new file mode 100644 index 0000000..db1ceed --- /dev/null +++ b/node-v0.8.14/tools/gyp/pylib/gyp/MSVSProject.py @@ -0,0 +1,208 @@ +# Copyright (c) 2012 Google Inc. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +"""Visual Studio project reader/writer.""" + +import gyp.common +import gyp.easy_xml as easy_xml + +#------------------------------------------------------------------------------ + + +class Tool(object): + """Visual Studio tool.""" + + def __init__(self, name, attrs=None): + """Initializes the tool. + + Args: + name: Tool name. + attrs: Dict of tool attributes; may be None. + """ + self._attrs = attrs or {} + self._attrs['Name'] = name + + def _GetSpecification(self): + """Creates an element for the tool. + + Returns: + A new xml.dom.Element for the tool. + """ + return ['Tool', self._attrs] + +class Filter(object): + """Visual Studio filter - that is, a virtual folder.""" + + def __init__(self, name, contents=None): + """Initializes the folder. + + Args: + name: Filter (folder) name. + contents: List of filenames and/or Filter objects contained. + """ + self.name = name + self.contents = list(contents or []) + + +#------------------------------------------------------------------------------ + + +class Writer(object): + """Visual Studio XML project writer.""" + + def __init__(self, project_path, version, name, guid=None, platforms=None): + """Initializes the project. + + Args: + project_path: Path to the project file. + version: Format version to emit. + name: Name of the project. + guid: GUID to use for project, if not None. + platforms: Array of string, the supported platforms. If null, ['Win32'] + """ + self.project_path = project_path + self.version = version + self.name = name + self.guid = guid + + # Default to Win32 for platforms. + if not platforms: + platforms = ['Win32'] + + # Initialize the specifications of the various sections. + self.platform_section = ['Platforms'] + for platform in platforms: + self.platform_section.append(['Platform', {'Name': platform}]) + self.tool_files_section = ['ToolFiles'] + self.configurations_section = ['Configurations'] + self.files_section = ['Files'] + + # Keep a dict keyed on filename to speed up access. + self.files_dict = dict() + + def AddToolFile(self, path): + """Adds a tool file to the project. + + Args: + path: Relative path from project to tool file. + """ + self.tool_files_section.append(['ToolFile', {'RelativePath': path}]) + + def _GetSpecForConfiguration(self, config_type, config_name, attrs, tools): + """Returns the specification for a configuration. + + Args: + config_type: Type of configuration node. + config_name: Configuration name. + attrs: Dict of configuration attributes; may be None. + tools: List of tools (strings or Tool objects); may be None. + Returns: + """ + # Handle defaults + if not attrs: + attrs = {} + if not tools: + tools = [] + + # Add configuration node and its attributes + node_attrs = attrs.copy() + node_attrs['Name'] = config_name + specification = [config_type, node_attrs] + + # Add tool nodes and their attributes + if tools: + for t in tools: + if isinstance(t, Tool): + specification.append(t._GetSpecification()) + else: + specification.append(Tool(t)._GetSpecification()) + return specification + + + def AddConfig(self, name, attrs=None, tools=None): + """Adds a configuration to the project. + + Args: + name: Configuration name. + attrs: Dict of configuration attributes; may be None. + tools: List of tools (strings or Tool objects); may be None. + """ + spec = self._GetSpecForConfiguration('Configuration', name, attrs, tools) + self.configurations_section.append(spec) + + def _AddFilesToNode(self, parent, files): + """Adds files and/or filters to the parent node. + + Args: + parent: Destination node + files: A list of Filter objects and/or relative paths to files. + + Will call itself recursively, if the files list contains Filter objects. + """ + for f in files: + if isinstance(f, Filter): + node = ['Filter', {'Name': f.name}] + self._AddFilesToNode(node, f.contents) + else: + node = ['File', {'RelativePath': f}] + self.files_dict[f] = node + parent.append(node) + + def AddFiles(self, files): + """Adds files to the project. + + Args: + files: A list of Filter objects and/or relative paths to files. + + This makes a copy of the file/filter tree at the time of this call. If you + later add files to a Filter object which was passed into a previous call + to AddFiles(), it will not be reflected in this project. + """ + self._AddFilesToNode(self.files_section, files) + # TODO(rspangler) This also doesn't handle adding files to an existing + # filter. That is, it doesn't merge the trees. + + def AddFileConfig(self, path, config, attrs=None, tools=None): + """Adds a configuration to a file. + + Args: + path: Relative path to the file. + config: Name of configuration to add. + attrs: Dict of configuration attributes; may be None. + tools: List of tools (strings or Tool objects); may be None. + + Raises: + ValueError: Relative path does not match any file added via AddFiles(). + """ + # Find the file node with the right relative path + parent = self.files_dict.get(path) + if not parent: + raise ValueError('AddFileConfig: file "%s" not in project.' % path) + + # Add the config to the file node + spec = self._GetSpecForConfiguration('FileConfiguration', config, attrs, + tools) + parent.append(spec) + + def WriteIfChanged(self): + """Writes the project file.""" + # First create XML content definition + content = [ + 'VisualStudioProject', + {'ProjectType': 'Visual C++', + 'Version': self.version.ProjectVersion(), + 'Name': self.name, + 'ProjectGUID': self.guid, + 'RootNamespace': self.name, + 'Keyword': 'Win32Proj' + }, + self.platform_section, + self.tool_files_section, + self.configurations_section, + ['References'], # empty section + self.files_section, + ['Globals'] # empty section + ] + easy_xml.WriteXmlIfChanged(content, self.project_path, + encoding="Windows-1252") diff --git a/node-v0.8.14/tools/gyp/pylib/gyp/MSVSSettings.py b/node-v0.8.14/tools/gyp/pylib/gyp/MSVSSettings.py new file mode 100644 index 0000000..d0d4990 --- /dev/null +++ b/node-v0.8.14/tools/gyp/pylib/gyp/MSVSSettings.py @@ -0,0 +1,1046 @@ +# Copyright (c) 2012 Google Inc. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +"""Code to validate and convert settings of the Microsoft build tools. + +This file contains code to validate and convert settings of the Microsoft +build tools. The function ConvertToMSBuildSettings(), ValidateMSVSSettings(), +and ValidateMSBuildSettings() are the entry points. + +This file was created by comparing the projects created by Visual Studio 2008 +and Visual Studio 2010 for all available settings through the user interface. +The MSBuild schemas were also considered. They are typically found in the +MSBuild install directory, e.g. c:\Program Files (x86)\MSBuild +""" + +import sys +import re + +# Dictionaries of settings validators. The key is the tool name, the value is +# a dictionary mapping setting names to validation functions. +_msvs_validators = {} +_msbuild_validators = {} + + +# A dictionary of settings converters. The key is the tool name, the value is +# a dictionary mapping setting names to conversion functions. +_msvs_to_msbuild_converters = {} + + +# Tool name mapping from MSVS to MSBuild. +_msbuild_name_of_tool = {} + + +class _Tool(object): + """Represents a tool used by MSVS or MSBuild. + + Attributes: + msvs_name: The name of the tool in MSVS. + msbuild_name: The name of the tool in MSBuild. + """ + + def __init__(self, msvs_name, msbuild_name): + self.msvs_name = msvs_name + self.msbuild_name = msbuild_name + + +def _AddTool(tool): + """Adds a tool to the four dictionaries used to process settings. + + This only defines the tool. Each setting also needs to be added. + + Args: + tool: The _Tool object to be added. + """ + _msvs_validators[tool.msvs_name] = {} + _msbuild_validators[tool.msbuild_name] = {} + _msvs_to_msbuild_converters[tool.msvs_name] = {} + _msbuild_name_of_tool[tool.msvs_name] = tool.msbuild_name + + +def _GetMSBuildToolSettings(msbuild_settings, tool): + """Returns an MSBuild tool dictionary. Creates it if needed.""" + return msbuild_settings.setdefault(tool.msbuild_name, {}) + + +class _Type(object): + """Type of settings (Base class).""" + + def ValidateMSVS(self, value): + """Verifies that the value is legal for MSVS. + + Args: + value: the value to check for this type. + + Raises: + ValueError if value is not valid for MSVS. + """ + + def ValidateMSBuild(self, value): + """Verifies that the value is legal for MSBuild. + + Args: + value: the value to check for this type. + + Raises: + ValueError if value is not valid for MSBuild. + """ + + def ConvertToMSBuild(self, value): + """Returns the MSBuild equivalent of the MSVS value given. + + Args: + value: the MSVS value to convert. + + Returns: + the MSBuild equivalent. + + Raises: + ValueError if value is not valid. + """ + return value + + +class _String(_Type): + """A setting that's just a string.""" + + def ValidateMSVS(self, value): + if not isinstance(value, basestring): + raise ValueError('expected string; got %r' % value) + + def ValidateMSBuild(self, value): + if not isinstance(value, basestring): + raise ValueError('expected string; got %r' % value) + + def ConvertToMSBuild(self, value): + # Convert the macros + return ConvertVCMacrosToMSBuild(value) + + +class _StringList(_Type): + """A settings that's a list of strings.""" + + def ValidateMSVS(self, value): + if not isinstance(value, basestring) and not isinstance(value, list): + raise ValueError('expected string list; got %r' % value) + + def ValidateMSBuild(self, value): + if not isinstance(value, basestring) and not isinstance(value, list): + raise ValueError('expected string list; got %r' % value) + + def ConvertToMSBuild(self, value): + # Convert the macros + if isinstance(value, list): + return [ConvertVCMacrosToMSBuild(i) for i in value] + else: + return ConvertVCMacrosToMSBuild(value) + + +class _Boolean(_Type): + """Boolean settings, can have the values 'false' or 'true'.""" + + def _Validate(self, value): + if value != 'true' and value != 'false': + raise ValueError('expected bool; got %r' % value) + + def ValidateMSVS(self, value): + self._Validate(value) + + def ValidateMSBuild(self, value): + self._Validate(value) + + def ConvertToMSBuild(self, value): + self._Validate(value) + return value + + +class _Integer(_Type): + """Integer settings.""" + + def __init__(self, msbuild_base=10): + _Type.__init__(self) + self._msbuild_base = msbuild_base + + def ValidateMSVS(self, value): + # Try to convert, this will raise ValueError if invalid. + self.ConvertToMSBuild(value) + + def ValidateMSBuild(self, value): + # Try to convert, this will raise ValueError if invalid. + int(value, self._msbuild_base) + + def ConvertToMSBuild(self, value): + msbuild_format = (self._msbuild_base == 10) and '%d' or '0x%04x' + return msbuild_format % int(value) + + +class _Enumeration(_Type): + """Type of settings that is an enumeration. + + In MSVS, the values are indexes like '0', '1', and '2'. + MSBuild uses text labels that are more representative, like 'Win32'. + + Constructor args: + label_list: an array of MSBuild labels that correspond to the MSVS index. + In the rare cases where MSVS has skipped an index value, None is + used in the array to indicate the unused spot. + new: an array of labels that are new to MSBuild. + """ + + def __init__(self, label_list, new=None): + _Type.__init__(self) + self._label_list = label_list + self._msbuild_values = set(value for value in label_list + if value is not None) + if new is not None: + self._msbuild_values.update(new) + + def ValidateMSVS(self, value): + # Try to convert. It will raise an exception if not valid. + self.ConvertToMSBuild(value) + + def ValidateMSBuild(self, value): + if value not in self._msbuild_values: + raise ValueError('unrecognized enumerated value %s' % value) + + def ConvertToMSBuild(self, value): + index = int(value) + if index < 0 or index >= len(self._label_list): + raise ValueError('index value (%d) not in expected range [0, %d)' % + (index, len(self._label_list))) + label = self._label_list[index] + if label is None: + raise ValueError('converted value for %s not specified.' % value) + return label + + +# Instantiate the various generic types. +_boolean = _Boolean() +_integer = _Integer() +# For now, we don't do any special validation on these types: +_string = _String() +_file_name = _String() +_folder_name = _String() +_file_list = _StringList() +_folder_list = _StringList() +_string_list = _StringList() +# Some boolean settings went from numerical values to boolean. The +# mapping is 0: default, 1: false, 2: true. +_newly_boolean = _Enumeration(['', 'false', 'true']) + + +def _Same(tool, name, setting_type): + """Defines a setting that has the same name in MSVS and MSBuild. + + Args: + tool: a dictionary that gives the names of the tool for MSVS and MSBuild. + name: the name of the setting. + setting_type: the type of this setting. + """ + _Renamed(tool, name, name, setting_type) + + +def _Renamed(tool, msvs_name, msbuild_name, setting_type): + """Defines a setting for which the name has changed. + + Args: + tool: a dictionary that gives the names of the tool for MSVS and MSBuild. + msvs_name: the name of the MSVS setting. + msbuild_name: the name of the MSBuild setting. + setting_type: the type of this setting. + """ + + def _Translate(value, msbuild_settings): + msbuild_tool_settings = _GetMSBuildToolSettings(msbuild_settings, tool) + msbuild_tool_settings[msbuild_name] = setting_type.ConvertToMSBuild(value) + + _msvs_validators[tool.msvs_name][msvs_name] = setting_type.ValidateMSVS + _msbuild_validators[tool.msbuild_name][msbuild_name] = ( + setting_type.ValidateMSBuild) + _msvs_to_msbuild_converters[tool.msvs_name][msvs_name] = _Translate + + +def _Moved(tool, settings_name, msbuild_tool_name, setting_type): + _MovedAndRenamed(tool, settings_name, msbuild_tool_name, settings_name, + setting_type) + + +def _MovedAndRenamed(tool, msvs_settings_name, msbuild_tool_name, + msbuild_settings_name, setting_type): + """Defines a setting that may have moved to a new section. + + Args: + tool: a dictionary that gives the names of the tool for MSVS and MSBuild. + msvs_settings_name: the MSVS name of the setting. + msbuild_tool_name: the name of the MSBuild tool to place the setting under. + msbuild_settings_name: the MSBuild name of the setting. + setting_type: the type of this setting. + """ + + def _Translate(value, msbuild_settings): + tool_settings = msbuild_settings.setdefault(msbuild_tool_name, {}) + tool_settings[msbuild_settings_name] = setting_type.ConvertToMSBuild(value) + + _msvs_validators[tool.msvs_name][msvs_settings_name] = ( + setting_type.ValidateMSVS) + validator = setting_type.ValidateMSBuild + _msbuild_validators[msbuild_tool_name][msbuild_settings_name] = validator + _msvs_to_msbuild_converters[tool.msvs_name][msvs_settings_name] = _Translate + + +def _MSVSOnly(tool, name, setting_type): + """Defines a setting that is only found in MSVS. + + Args: + tool: a dictionary that gives the names of the tool for MSVS and MSBuild. + name: the name of the setting. + setting_type: the type of this setting. + """ + + def _Translate(unused_value, unused_msbuild_settings): + # Since this is for MSVS only settings, no translation will happen. + pass + + _msvs_validators[tool.msvs_name][name] = setting_type.ValidateMSVS + _msvs_to_msbuild_converters[tool.msvs_name][name] = _Translate + + +def _MSBuildOnly(tool, name, setting_type): + """Defines a setting that is only found in MSBuild. + + Args: + tool: a dictionary that gives the names of the tool for MSVS and MSBuild. + name: the name of the setting. + setting_type: the type of this setting. + """ + _msbuild_validators[tool.msbuild_name][name] = setting_type.ValidateMSBuild + + +def _ConvertedToAdditionalOption(tool, msvs_name, flag): + """Defines a setting that's handled via a command line option in MSBuild. + + Args: + tool: a dictionary that gives the names of the tool for MSVS and MSBuild. + msvs_name: the name of the MSVS setting that if 'true' becomes a flag + flag: the flag to insert at the end of the AdditionalOptions + """ + + def _Translate(value, msbuild_settings): + if value == 'true': + tool_settings = _GetMSBuildToolSettings(msbuild_settings, tool) + if 'AdditionalOptions' in tool_settings: + new_flags = '%s %s' % (tool_settings['AdditionalOptions'], flag) + else: + new_flags = flag + tool_settings['AdditionalOptions'] = new_flags + _msvs_validators[tool.msvs_name][msvs_name] = _boolean.ValidateMSVS + _msvs_to_msbuild_converters[tool.msvs_name][msvs_name] = _Translate + + +def _CustomGeneratePreprocessedFile(tool, msvs_name): + def _Translate(value, msbuild_settings): + tool_settings = _GetMSBuildToolSettings(msbuild_settings, tool) + if value == '0': + tool_settings['PreprocessToFile'] = 'false' + tool_settings['PreprocessSuppressLineNumbers'] = 'false' + elif value == '1': # /P + tool_settings['PreprocessToFile'] = 'true' + tool_settings['PreprocessSuppressLineNumbers'] = 'false' + elif value == '2': # /EP /P + tool_settings['PreprocessToFile'] = 'true' + tool_settings['PreprocessSuppressLineNumbers'] = 'true' + else: + raise ValueError('value must be one of [0, 1, 2]; got %s' % value) + # Create a bogus validator that looks for '0', '1', or '2' + msvs_validator = _Enumeration(['a', 'b', 'c']).ValidateMSVS + _msvs_validators[tool.msvs_name][msvs_name] = msvs_validator + msbuild_validator = _boolean.ValidateMSBuild + msbuild_tool_validators = _msbuild_validators[tool.msbuild_name] + msbuild_tool_validators['PreprocessToFile'] = msbuild_validator + msbuild_tool_validators['PreprocessSuppressLineNumbers'] = msbuild_validator + _msvs_to_msbuild_converters[tool.msvs_name][msvs_name] = _Translate + + +fix_vc_macro_slashes_regex_list = ('IntDir', 'OutDir') +fix_vc_macro_slashes_regex = re.compile( + r'(\$\((?:%s)\))(?:[\\/]+)' % "|".join(fix_vc_macro_slashes_regex_list) +) + +def FixVCMacroSlashes(s): + """Replace macros which have excessive following slashes. + + These macros are known to have a built-in trailing slash. Furthermore, many + scripts hiccup on processing paths with extra slashes in the middle. + + This list is probably not exhaustive. Add as needed. + """ + if '$' in s: + s = fix_vc_macro_slashes_regex.sub(r'\1', s) + return s + + +def ConvertVCMacrosToMSBuild(s): + """Convert the the MSVS macros found in the string to the MSBuild equivalent. + + This list is probably not exhaustive. Add as needed. + """ + if '$' in s: + replace_map = { + '$(ConfigurationName)': '$(Configuration)', + '$(InputDir)': '%(RootDir)%(Directory)', + '$(InputExt)': '%(Extension)', + '$(InputFileName)': '%(Filename)%(Extension)', + '$(InputName)': '%(Filename)', + '$(InputPath)': '%(FullPath)', + '$(ParentName)': '$(ProjectFileName)', + '$(PlatformName)': '$(Platform)', + '$(SafeInputName)': '%(Filename)', + } + for old, new in replace_map.iteritems(): + s = s.replace(old, new) + s = FixVCMacroSlashes(s) + return s + + +def ConvertToMSBuildSettings(msvs_settings, stderr=sys.stderr): + """Converts MSVS settings (VS2008 and earlier) to MSBuild settings (VS2010+). + + Args: + msvs_settings: A dictionary. The key is the tool name. The values are + themselves dictionaries of settings and their values. + stderr: The stream receiving the error messages. + + Returns: + A dictionary of MSBuild settings. The key is either the MSBuild tool name + or the empty string (for the global settings). The values are themselves + dictionaries of settings and their values. + """ + msbuild_settings = {} + for msvs_tool_name, msvs_tool_settings in msvs_settings.iteritems(): + if msvs_tool_name in _msvs_to_msbuild_converters: + msvs_tool = _msvs_to_msbuild_converters[msvs_tool_name] + for msvs_setting, msvs_value in msvs_tool_settings.iteritems(): + if msvs_setting in msvs_tool: + # Invoke the translation function. + try: + msvs_tool[msvs_setting](msvs_value, msbuild_settings) + except ValueError, e: + print >> stderr, ('Warning: while converting %s/%s to MSBuild, ' + '%s' % (msvs_tool_name, msvs_setting, e)) + else: + # We don't know this setting. Give a warning. + print >> stderr, ('Warning: unrecognized setting %s/%s ' + 'while converting to MSBuild.' % + (msvs_tool_name, msvs_setting)) + else: + print >> stderr, ('Warning: unrecognized tool %s while converting to ' + 'MSBuild.' % msvs_tool_name) + return msbuild_settings + + +def ValidateMSVSSettings(settings, stderr=sys.stderr): + """Validates that the names of the settings are valid for MSVS. + + Args: + settings: A dictionary. The key is the tool name. The values are + themselves dictionaries of settings and their values. + stderr: The stream receiving the error messages. + """ + _ValidateSettings(_msvs_validators, settings, stderr) + + +def ValidateMSBuildSettings(settings, stderr=sys.stderr): + """Validates that the names of the settings are valid for MSBuild. + + Args: + settings: A dictionary. The key is the tool name. The values are + themselves dictionaries of settings and their values. + stderr: The stream receiving the error messages. + """ + _ValidateSettings(_msbuild_validators, settings, stderr) + + +def _ValidateSettings(validators, settings, stderr): + """Validates that the settings are valid for MSBuild or MSVS. + + We currently only validate the names of the settings, not their values. + + Args: + validators: A dictionary of tools and their validators. + settings: A dictionary. The key is the tool name. The values are + themselves dictionaries of settings and their values. + stderr: The stream receiving the error messages. + """ + for tool_name in settings: + if tool_name in validators: + tool_validators = validators[tool_name] + for setting, value in settings[tool_name].iteritems(): + if setting in tool_validators: + try: + tool_validators[setting](value) + except ValueError, e: + print >> stderr, ('Warning: for %s/%s, %s' % + (tool_name, setting, e)) + else: + print >> stderr, ('Warning: unrecognized setting %s/%s' % + (tool_name, setting)) + else: + print >> stderr, ('Warning: unrecognized tool %s' % tool_name) + + +# MSVS and MBuild names of the tools. +_compile = _Tool('VCCLCompilerTool', 'ClCompile') +_link = _Tool('VCLinkerTool', 'Link') +_midl = _Tool('VCMIDLTool', 'Midl') +_rc = _Tool('VCResourceCompilerTool', 'ResourceCompile') +_lib = _Tool('VCLibrarianTool', 'Lib') +_manifest = _Tool('VCManifestTool', 'Manifest') + + +_AddTool(_compile) +_AddTool(_link) +_AddTool(_midl) +_AddTool(_rc) +_AddTool(_lib) +_AddTool(_manifest) +# Add sections only found in the MSBuild settings. +_msbuild_validators[''] = {} +_msbuild_validators['ProjectReference'] = {} +_msbuild_validators['ManifestResourceCompile'] = {} + +# Descriptions of the compiler options, i.e. VCCLCompilerTool in MSVS and +# ClCompile in MSBuild. +# See "c:\Program Files (x86)\MSBuild\Microsoft.Cpp\v4.0\1033\cl.xml" for +# the schema of the MSBuild ClCompile settings. + +# Options that have the same name in MSVS and MSBuild +_Same(_compile, 'AdditionalIncludeDirectories', _folder_list) # /I +_Same(_compile, 'AdditionalOptions', _string_list) +_Same(_compile, 'AdditionalUsingDirectories', _folder_list) # /AI +_Same(_compile, 'AssemblerListingLocation', _file_name) # /Fa +_Same(_compile, 'BrowseInformationFile', _file_name) +_Same(_compile, 'BufferSecurityCheck', _boolean) # /GS +_Same(_compile, 'DisableLanguageExtensions', _boolean) # /Za +_Same(_compile, 'DisableSpecificWarnings', _string_list) # /wd +_Same(_compile, 'EnableFiberSafeOptimizations', _boolean) # /GT +_Same(_compile, 'EnablePREfast', _boolean) # /analyze Visible='false' +_Same(_compile, 'ExpandAttributedSource', _boolean) # /Fx +_Same(_compile, 'FloatingPointExceptions', _boolean) # /fp:except +_Same(_compile, 'ForceConformanceInForLoopScope', _boolean) # /Zc:forScope +_Same(_compile, 'ForcedIncludeFiles', _file_list) # /FI +_Same(_compile, 'ForcedUsingFiles', _file_list) # /FU +_Same(_compile, 'GenerateXMLDocumentationFiles', _boolean) # /doc +_Same(_compile, 'IgnoreStandardIncludePath', _boolean) # /X +_Same(_compile, 'MinimalRebuild', _boolean) # /Gm +_Same(_compile, 'OmitDefaultLibName', _boolean) # /Zl +_Same(_compile, 'OmitFramePointers', _boolean) # /Oy +_Same(_compile, 'PreprocessorDefinitions', _string_list) # /D +_Same(_compile, 'ProgramDataBaseFileName', _file_name) # /Fd +_Same(_compile, 'RuntimeTypeInfo', _boolean) # /GR +_Same(_compile, 'ShowIncludes', _boolean) # /showIncludes +_Same(_compile, 'SmallerTypeCheck', _boolean) # /RTCc +_Same(_compile, 'StringPooling', _boolean) # /GF +_Same(_compile, 'SuppressStartupBanner', _boolean) # /nologo +_Same(_compile, 'TreatWChar_tAsBuiltInType', _boolean) # /Zc:wchar_t +_Same(_compile, 'UndefineAllPreprocessorDefinitions', _boolean) # /u +_Same(_compile, 'UndefinePreprocessorDefinitions', _string_list) # /U +_Same(_compile, 'UseFullPaths', _boolean) # /FC +_Same(_compile, 'WholeProgramOptimization', _boolean) # /GL +_Same(_compile, 'XMLDocumentationFileName', _file_name) + +_Same(_compile, 'AssemblerOutput', + _Enumeration(['NoListing', + 'AssemblyCode', # /FA + 'All', # /FAcs + 'AssemblyAndMachineCode', # /FAc + 'AssemblyAndSourceCode'])) # /FAs +_Same(_compile, 'BasicRuntimeChecks', + _Enumeration(['Default', + 'StackFrameRuntimeCheck', # /RTCs + 'UninitializedLocalUsageCheck', # /RTCu + 'EnableFastChecks'])) # /RTC1 +_Same(_compile, 'BrowseInformation', + _Enumeration(['false', + 'true', # /FR + 'true'])) # /Fr +_Same(_compile, 'CallingConvention', + _Enumeration(['Cdecl', # /Gd + 'FastCall', # /Gr + 'StdCall'])) # /Gz +_Same(_compile, 'CompileAs', + _Enumeration(['Default', + 'CompileAsC', # /TC + 'CompileAsCpp'])) # /TP +_Same(_compile, 'DebugInformationFormat', + _Enumeration(['', # Disabled + 'OldStyle', # /Z7 + None, + 'ProgramDatabase', # /Zi + 'EditAndContinue'])) # /ZI +_Same(_compile, 'EnableEnhancedInstructionSet', + _Enumeration(['NotSet', + 'StreamingSIMDExtensions', # /arch:SSE + 'StreamingSIMDExtensions2'])) # /arch:SSE2 +_Same(_compile, 'ErrorReporting', + _Enumeration(['None', # /errorReport:none + 'Prompt', # /errorReport:prompt + 'Queue'], # /errorReport:queue + new=['Send'])) # /errorReport:send" +_Same(_compile, 'ExceptionHandling', + _Enumeration(['false', + 'Sync', # /EHsc + 'Async'], # /EHa + new=['SyncCThrow'])) # /EHs +_Same(_compile, 'FavorSizeOrSpeed', + _Enumeration(['Neither', + 'Speed', # /Ot + 'Size'])) # /Os +_Same(_compile, 'FloatingPointModel', + _Enumeration(['Precise', # /fp:precise + 'Strict', # /fp:strict + 'Fast'])) # /fp:fast +_Same(_compile, 'InlineFunctionExpansion', + _Enumeration(['Default', + 'OnlyExplicitInline', # /Ob1 + 'AnySuitable'], # /Ob2 + new=['Disabled'])) # /Ob0 +_Same(_compile, 'Optimization', + _Enumeration(['Disabled', # /Od + 'MinSpace', # /O1 + 'MaxSpeed', # /O2 + 'Full'])) # /Ox +_Same(_compile, 'RuntimeLibrary', + _Enumeration(['MultiThreaded', # /MT + 'MultiThreadedDebug', # /MTd + 'MultiThreadedDLL', # /MD + 'MultiThreadedDebugDLL'])) # /MDd +_Same(_compile, 'StructMemberAlignment', + _Enumeration(['Default', + '1Byte', # /Zp1 + '2Bytes', # /Zp2 + '4Bytes', # /Zp4 + '8Bytes', # /Zp8 + '16Bytes'])) # /Zp16 +_Same(_compile, 'WarningLevel', + _Enumeration(['TurnOffAllWarnings', # /W0 + 'Level1', # /W1 + 'Level2', # /W2 + 'Level3', # /W3 + 'Level4'], # /W4 + new=['EnableAllWarnings'])) # /Wall + +# Options found in MSVS that have been renamed in MSBuild. +_Renamed(_compile, 'EnableFunctionLevelLinking', 'FunctionLevelLinking', + _boolean) # /Gy +_Renamed(_compile, 'EnableIntrinsicFunctions', 'IntrinsicFunctions', + _boolean) # /Oi +_Renamed(_compile, 'KeepComments', 'PreprocessKeepComments', _boolean) # /C +_Renamed(_compile, 'ObjectFile', 'ObjectFileName', _file_name) # /Fo +_Renamed(_compile, 'OpenMP', 'OpenMPSupport', _boolean) # /openmp +_Renamed(_compile, 'PrecompiledHeaderThrough', 'PrecompiledHeaderFile', + _file_name) # Used with /Yc and /Yu +_Renamed(_compile, 'PrecompiledHeaderFile', 'PrecompiledHeaderOutputFile', + _file_name) # /Fp +_Renamed(_compile, 'UsePrecompiledHeader', 'PrecompiledHeader', + _Enumeration(['NotUsing', # VS recognized '' for this value too. + 'Create', # /Yc + 'Use'])) # /Yu +_Renamed(_compile, 'WarnAsError', 'TreatWarningAsError', _boolean) # /WX + +_ConvertedToAdditionalOption(_compile, 'DefaultCharIsUnsigned', '/J') + +# MSVS options not found in MSBuild. +_MSVSOnly(_compile, 'Detect64BitPortabilityProblems', _boolean) +_MSVSOnly(_compile, 'UseUnicodeResponseFiles', _boolean) + +# MSBuild options not found in MSVS. +_MSBuildOnly(_compile, 'BuildingInIDE', _boolean) +_MSBuildOnly(_compile, 'CompileAsManaged', + _Enumeration([], new=['false', + 'true', # /clr + 'Pure', # /clr:pure + 'Safe', # /clr:safe + 'OldSyntax'])) # /clr:oldSyntax +_MSBuildOnly(_compile, 'CreateHotpatchableImage', _boolean) # /hotpatch +_MSBuildOnly(_compile, 'MultiProcessorCompilation', _boolean) # /MP +_MSBuildOnly(_compile, 'PreprocessOutputPath', _string) # /Fi +_MSBuildOnly(_compile, 'ProcessorNumber', _integer) # the number of processors +_MSBuildOnly(_compile, 'TrackerLogDirectory', _folder_name) +_MSBuildOnly(_compile, 'TreatSpecificWarningsAsErrors', _string_list) # /we +_MSBuildOnly(_compile, 'UseUnicodeForAssemblerListing', _boolean) # /FAu + +# Defines a setting that needs very customized processing +_CustomGeneratePreprocessedFile(_compile, 'GeneratePreprocessedFile') + + +# Directives for converting MSVS VCLinkerTool to MSBuild Link. +# See "c:\Program Files (x86)\MSBuild\Microsoft.Cpp\v4.0\1033\link.xml" for +# the schema of the MSBuild Link settings. + +# Options that have the same name in MSVS and MSBuild +_Same(_link, 'AdditionalDependencies', _file_list) +_Same(_link, 'AdditionalLibraryDirectories', _folder_list) # /LIBPATH +# /MANIFESTDEPENDENCY: +_Same(_link, 'AdditionalManifestDependencies', _file_list) +_Same(_link, 'AdditionalOptions', _string_list) +_Same(_link, 'AddModuleNamesToAssembly', _file_list) # /ASSEMBLYMODULE +_Same(_link, 'AllowIsolation', _boolean) # /ALLOWISOLATION +_Same(_link, 'AssemblyLinkResource', _file_list) # /ASSEMBLYLINKRESOURCE +_Same(_link, 'BaseAddress', _string) # /BASE +_Same(_link, 'CLRUnmanagedCodeCheck', _boolean) # /CLRUNMANAGEDCODECHECK +_Same(_link, 'DelayLoadDLLs', _file_list) # /DELAYLOAD +_Same(_link, 'DelaySign', _boolean) # /DELAYSIGN +_Same(_link, 'EmbedManagedResourceFile', _file_list) # /ASSEMBLYRESOURCE +_Same(_link, 'EnableUAC', _boolean) # /MANIFESTUAC +_Same(_link, 'EntryPointSymbol', _string) # /ENTRY +_Same(_link, 'ForceSymbolReferences', _file_list) # /INCLUDE +_Same(_link, 'FunctionOrder', _file_name) # /ORDER +_Same(_link, 'GenerateDebugInformation', _boolean) # /DEBUG +_Same(_link, 'GenerateMapFile', _boolean) # /MAP +_Same(_link, 'HeapCommitSize', _string) +_Same(_link, 'HeapReserveSize', _string) # /HEAP +_Same(_link, 'IgnoreAllDefaultLibraries', _boolean) # /NODEFAULTLIB +_Same(_link, 'IgnoreEmbeddedIDL', _boolean) # /IGNOREIDL +_Same(_link, 'ImportLibrary', _file_name) # /IMPLIB +_Same(_link, 'KeyContainer', _file_name) # /KEYCONTAINER +_Same(_link, 'KeyFile', _file_name) # /KEYFILE +_Same(_link, 'ManifestFile', _file_name) # /ManifestFile +_Same(_link, 'MapExports', _boolean) # /MAPINFO:EXPORTS +_Same(_link, 'MapFileName', _file_name) +_Same(_link, 'MergedIDLBaseFileName', _file_name) # /IDLOUT +_Same(_link, 'MergeSections', _string) # /MERGE +_Same(_link, 'MidlCommandFile', _file_name) # /MIDL +_Same(_link, 'ModuleDefinitionFile', _file_name) # /DEF +_Same(_link, 'OutputFile', _file_name) # /OUT +_Same(_link, 'PerUserRedirection', _boolean) +_Same(_link, 'Profile', _boolean) # /PROFILE +_Same(_link, 'ProfileGuidedDatabase', _file_name) # /PGD +_Same(_link, 'ProgramDatabaseFile', _file_name) # /PDB +_Same(_link, 'RegisterOutput', _boolean) +_Same(_link, 'SetChecksum', _boolean) # /RELEASE +_Same(_link, 'StackCommitSize', _string) +_Same(_link, 'StackReserveSize', _string) # /STACK +_Same(_link, 'StripPrivateSymbols', _file_name) # /PDBSTRIPPED +_Same(_link, 'SupportUnloadOfDelayLoadedDLL', _boolean) # /DELAY:UNLOAD +_Same(_link, 'SuppressStartupBanner', _boolean) # /NOLOGO +_Same(_link, 'SwapRunFromCD', _boolean) # /SWAPRUN:CD +_Same(_link, 'TurnOffAssemblyGeneration', _boolean) # /NOASSEMBLY +_Same(_link, 'TypeLibraryFile', _file_name) # /TLBOUT +_Same(_link, 'TypeLibraryResourceID', _integer) # /TLBID +_Same(_link, 'UACUIAccess', _boolean) # /uiAccess='true' +_Same(_link, 'Version', _string) # /VERSION + +_Same(_link, 'EnableCOMDATFolding', _newly_boolean) # /OPT:ICF +_Same(_link, 'FixedBaseAddress', _newly_boolean) # /FIXED +_Same(_link, 'LargeAddressAware', _newly_boolean) # /LARGEADDRESSAWARE +_Same(_link, 'OptimizeReferences', _newly_boolean) # /OPT:REF +_Same(_link, 'RandomizedBaseAddress', _newly_boolean) # /DYNAMICBASE +_Same(_link, 'TerminalServerAware', _newly_boolean) # /TSAWARE + +_subsystem_enumeration = _Enumeration( + ['NotSet', + 'Console', # /SUBSYSTEM:CONSOLE + 'Windows', # /SUBSYSTEM:WINDOWS + 'Native', # /SUBSYSTEM:NATIVE + 'EFI Application', # /SUBSYSTEM:EFI_APPLICATION + 'EFI Boot Service Driver', # /SUBSYSTEM:EFI_BOOT_SERVICE_DRIVER + 'EFI ROM', # /SUBSYSTEM:EFI_ROM + 'EFI Runtime', # /SUBSYSTEM:EFI_RUNTIME_DRIVER + 'WindowsCE'], # /SUBSYSTEM:WINDOWSCE + new=['POSIX']) # /SUBSYSTEM:POSIX + +_target_machine_enumeration = _Enumeration( + ['NotSet', + 'MachineX86', # /MACHINE:X86 + None, + 'MachineARM', # /MACHINE:ARM + 'MachineEBC', # /MACHINE:EBC + 'MachineIA64', # /MACHINE:IA64 + None, + 'MachineMIPS', # /MACHINE:MIPS + 'MachineMIPS16', # /MACHINE:MIPS16 + 'MachineMIPSFPU', # /MACHINE:MIPSFPU + 'MachineMIPSFPU16', # /MACHINE:MIPSFPU16 + None, + None, + None, + 'MachineSH4', # /MACHINE:SH4 + None, + 'MachineTHUMB', # /MACHINE:THUMB + 'MachineX64']) # /MACHINE:X64 + +_Same(_link, 'AssemblyDebug', + _Enumeration(['', + 'true', # /ASSEMBLYDEBUG + 'false'])) # /ASSEMBLYDEBUG:DISABLE +_Same(_link, 'CLRImageType', + _Enumeration(['Default', + 'ForceIJWImage', # /CLRIMAGETYPE:IJW + 'ForcePureILImage', # /Switch="CLRIMAGETYPE:PURE + 'ForceSafeILImage'])) # /Switch="CLRIMAGETYPE:SAFE +_Same(_link, 'CLRThreadAttribute', + _Enumeration(['DefaultThreadingAttribute', # /CLRTHREADATTRIBUTE:NONE + 'MTAThreadingAttribute', # /CLRTHREADATTRIBUTE:MTA + 'STAThreadingAttribute'])) # /CLRTHREADATTRIBUTE:STA +_Same(_link, 'DataExecutionPrevention', + _Enumeration(['', + 'false', # /NXCOMPAT:NO + 'true'])) # /NXCOMPAT +_Same(_link, 'Driver', + _Enumeration(['NotSet', + 'Driver', # /Driver + 'UpOnly', # /DRIVER:UPONLY + 'WDM'])) # /DRIVER:WDM +_Same(_link, 'LinkTimeCodeGeneration', + _Enumeration(['Default', + 'UseLinkTimeCodeGeneration', # /LTCG + 'PGInstrument', # /LTCG:PGInstrument + 'PGOptimization', # /LTCG:PGOptimize + 'PGUpdate'])) # /LTCG:PGUpdate +_Same(_link, 'ShowProgress', + _Enumeration(['NotSet', + 'LinkVerbose', # /VERBOSE + 'LinkVerboseLib'], # /VERBOSE:Lib + new=['LinkVerboseICF', # /VERBOSE:ICF + 'LinkVerboseREF', # /VERBOSE:REF + 'LinkVerboseSAFESEH', # /VERBOSE:SAFESEH + 'LinkVerboseCLR'])) # /VERBOSE:CLR +_Same(_link, 'SubSystem', _subsystem_enumeration) +_Same(_link, 'TargetMachine', _target_machine_enumeration) +_Same(_link, 'UACExecutionLevel', + _Enumeration(['AsInvoker', # /level='asInvoker' + 'HighestAvailable', # /level='highestAvailable' + 'RequireAdministrator'])) # /level='requireAdministrator' + + +# Options found in MSVS that have been renamed in MSBuild. +_Renamed(_link, 'ErrorReporting', 'LinkErrorReporting', + _Enumeration(['NoErrorReport', # /ERRORREPORT:NONE + 'PromptImmediately', # /ERRORREPORT:PROMPT + 'QueueForNextLogin'], # /ERRORREPORT:QUEUE + new=['SendErrorReport'])) # /ERRORREPORT:SEND +_Renamed(_link, 'IgnoreDefaultLibraryNames', 'IgnoreSpecificDefaultLibraries', + _file_list) # /NODEFAULTLIB +_Renamed(_link, 'ResourceOnlyDLL', 'NoEntryPoint', _boolean) # /NOENTRY +_Renamed(_link, 'SwapRunFromNet', 'SwapRunFromNET', _boolean) # /SWAPRUN:NET + +_Moved(_link, 'GenerateManifest', '', _boolean) +_Moved(_link, 'IgnoreImportLibrary', '', _boolean) +_Moved(_link, 'LinkIncremental', '', _newly_boolean) +_Moved(_link, 'LinkLibraryDependencies', 'ProjectReference', _boolean) +_Moved(_link, 'UseLibraryDependencyInputs', 'ProjectReference', _boolean) + +# MSVS options not found in MSBuild. +_MSVSOnly(_link, 'OptimizeForWindows98', _newly_boolean) +_MSVSOnly(_link, 'UseUnicodeResponseFiles', _boolean) +# TODO(jeanluc) I don't think these are genuine settings but byproducts of Gyp. +_MSVSOnly(_link, 'AdditionalLibraryDirectories_excluded', _folder_list) + +# MSBuild options not found in MSVS. +_MSBuildOnly(_link, 'BuildingInIDE', _boolean) +_MSBuildOnly(_link, 'ImageHasSafeExceptionHandlers', _boolean) # /SAFESEH +_MSBuildOnly(_link, 'LinkDLL', _boolean) # /DLL Visible='false' +_MSBuildOnly(_link, 'LinkStatus', _boolean) # /LTCG:STATUS +_MSBuildOnly(_link, 'PreventDllBinding', _boolean) # /ALLOWBIND +_MSBuildOnly(_link, 'SupportNobindOfDelayLoadedDLL', _boolean) # /DELAY:NOBIND +_MSBuildOnly(_link, 'TrackerLogDirectory', _folder_name) +_MSBuildOnly(_link, 'TreatLinkerWarningAsErrors', _boolean) # /WX +_MSBuildOnly(_link, 'MinimumRequiredVersion', _string) +_MSBuildOnly(_link, 'MSDOSStubFileName', _file_name) # /STUB Visible='false' +_MSBuildOnly(_link, 'SectionAlignment', _integer) # /ALIGN +_MSBuildOnly(_link, 'SpecifySectionAttributes', _string) # /SECTION +_MSBuildOnly(_link, 'ForceFileOutput', + _Enumeration([], new=['Enabled', # /FORCE + # /FORCE:MULTIPLE + 'MultiplyDefinedSymbolOnly', + 'UndefinedSymbolOnly'])) # /FORCE:UNRESOLVED +_MSBuildOnly(_link, 'CreateHotPatchableImage', + _Enumeration([], new=['Enabled', # /FUNCTIONPADMIN + 'X86Image', # /FUNCTIONPADMIN:5 + 'X64Image', # /FUNCTIONPADMIN:6 + 'ItaniumImage'])) # /FUNCTIONPADMIN:16 +_MSBuildOnly(_link, 'CLRSupportLastError', + _Enumeration([], new=['Enabled', # /CLRSupportLastError + 'Disabled', # /CLRSupportLastError:NO + # /CLRSupportLastError:SYSTEMDLL + 'SystemDlls'])) + + +# Directives for converting VCResourceCompilerTool to ResourceCompile. +# See "c:\Program Files (x86)\MSBuild\Microsoft.Cpp\v4.0\1033\rc.xml" for +# the schema of the MSBuild ResourceCompile settings. + +_Same(_rc, 'AdditionalOptions', _string_list) +_Same(_rc, 'AdditionalIncludeDirectories', _folder_list) # /I +_Same(_rc, 'Culture', _Integer(msbuild_base=16)) +_Same(_rc, 'IgnoreStandardIncludePath', _boolean) # /X +_Same(_rc, 'PreprocessorDefinitions', _string_list) # /D +_Same(_rc, 'ResourceOutputFileName', _string) # /fo +_Same(_rc, 'ShowProgress', _boolean) # /v +# There is no UI in VisualStudio 2008 to set the following properties. +# However they are found in CL and other tools. Include them here for +# completeness, as they are very likely to have the same usage pattern. +_Same(_rc, 'SuppressStartupBanner', _boolean) # /nologo +_Same(_rc, 'UndefinePreprocessorDefinitions', _string_list) # /u + +# MSBuild options not found in MSVS. +_MSBuildOnly(_rc, 'NullTerminateStrings', _boolean) # /n +_MSBuildOnly(_rc, 'TrackerLogDirectory', _folder_name) + + +# Directives for converting VCMIDLTool to Midl. +# See "c:\Program Files (x86)\MSBuild\Microsoft.Cpp\v4.0\1033\midl.xml" for +# the schema of the MSBuild Midl settings. + +_Same(_midl, 'AdditionalIncludeDirectories', _folder_list) # /I +_Same(_midl, 'AdditionalOptions', _string_list) +_Same(_midl, 'CPreprocessOptions', _string) # /cpp_opt +_Same(_midl, 'ErrorCheckAllocations', _boolean) # /error allocation +_Same(_midl, 'ErrorCheckBounds', _boolean) # /error bounds_check +_Same(_midl, 'ErrorCheckEnumRange', _boolean) # /error enum +_Same(_midl, 'ErrorCheckRefPointers', _boolean) # /error ref +_Same(_midl, 'ErrorCheckStubData', _boolean) # /error stub_data +_Same(_midl, 'GenerateStublessProxies', _boolean) # /Oicf +_Same(_midl, 'GenerateTypeLibrary', _boolean) +_Same(_midl, 'HeaderFileName', _file_name) # /h +_Same(_midl, 'IgnoreStandardIncludePath', _boolean) # /no_def_idir +_Same(_midl, 'InterfaceIdentifierFileName', _file_name) # /iid +_Same(_midl, 'MkTypLibCompatible', _boolean) # /mktyplib203 +_Same(_midl, 'OutputDirectory', _string) # /out +_Same(_midl, 'PreprocessorDefinitions', _string_list) # /D +_Same(_midl, 'ProxyFileName', _file_name) # /proxy +_Same(_midl, 'RedirectOutputAndErrors', _file_name) # /o +_Same(_midl, 'SuppressStartupBanner', _boolean) # /nologo +_Same(_midl, 'TypeLibraryName', _file_name) # /tlb +_Same(_midl, 'UndefinePreprocessorDefinitions', _string_list) # /U +_Same(_midl, 'WarnAsError', _boolean) # /WX + +_Same(_midl, 'DefaultCharType', + _Enumeration(['Unsigned', # /char unsigned + 'Signed', # /char signed + 'Ascii'])) # /char ascii7 +_Same(_midl, 'TargetEnvironment', + _Enumeration(['NotSet', + 'Win32', # /env win32 + 'Itanium', # /env ia64 + 'X64'])) # /env x64 +_Same(_midl, 'EnableErrorChecks', + _Enumeration(['EnableCustom', + 'None', # /error none + 'All'])) # /error all +_Same(_midl, 'StructMemberAlignment', + _Enumeration(['NotSet', + '1', # Zp1 + '2', # Zp2 + '4', # Zp4 + '8'])) # Zp8 +_Same(_midl, 'WarningLevel', + _Enumeration(['0', # /W0 + '1', # /W1 + '2', # /W2 + '3', # /W3 + '4'])) # /W4 + +_Renamed(_midl, 'DLLDataFileName', 'DllDataFileName', _file_name) # /dlldata +_Renamed(_midl, 'ValidateParameters', 'ValidateAllParameters', + _boolean) # /robust + +# MSBuild options not found in MSVS. +_MSBuildOnly(_midl, 'ApplicationConfigurationMode', _boolean) # /app_config +_MSBuildOnly(_midl, 'ClientStubFile', _file_name) # /cstub +_MSBuildOnly(_midl, 'GenerateClientFiles', + _Enumeration([], new=['Stub', # /client stub + 'None'])) # /client none +_MSBuildOnly(_midl, 'GenerateServerFiles', + _Enumeration([], new=['Stub', # /client stub + 'None'])) # /client none +_MSBuildOnly(_midl, 'LocaleID', _integer) # /lcid DECIMAL +_MSBuildOnly(_midl, 'ServerStubFile', _file_name) # /sstub +_MSBuildOnly(_midl, 'SuppressCompilerWarnings', _boolean) # /no_warn +_MSBuildOnly(_midl, 'TrackerLogDirectory', _folder_name) +_MSBuildOnly(_midl, 'TypeLibFormat', + _Enumeration([], new=['NewFormat', # /newtlb + 'OldFormat'])) # /oldtlb + + +# Directives for converting VCLibrarianTool to Lib. +# See "c:\Program Files (x86)\MSBuild\Microsoft.Cpp\v4.0\1033\lib.xml" for +# the schema of the MSBuild Lib settings. + +_Same(_lib, 'AdditionalDependencies', _file_list) +_Same(_lib, 'AdditionalLibraryDirectories', _folder_list) # /LIBPATH +_Same(_lib, 'AdditionalOptions', _string_list) +_Same(_lib, 'ExportNamedFunctions', _string_list) # /EXPORT +_Same(_lib, 'ForceSymbolReferences', _string) # /INCLUDE +_Same(_lib, 'IgnoreAllDefaultLibraries', _boolean) # /NODEFAULTLIB +_Same(_lib, 'IgnoreSpecificDefaultLibraries', _file_list) # /NODEFAULTLIB +_Same(_lib, 'ModuleDefinitionFile', _file_name) # /DEF +_Same(_lib, 'OutputFile', _file_name) # /OUT +_Same(_lib, 'SuppressStartupBanner', _boolean) # /NOLOGO +_Same(_lib, 'UseUnicodeResponseFiles', _boolean) +_Same(_lib, 'LinkTimeCodeGeneration', _boolean) # /LTCG + +# TODO(jeanluc) _link defines the same value that gets moved to +# ProjectReference. We may want to validate that they are consistent. +_Moved(_lib, 'LinkLibraryDependencies', 'ProjectReference', _boolean) + +# TODO(jeanluc) I don't think these are genuine settings but byproducts of Gyp. +_MSVSOnly(_lib, 'AdditionalLibraryDirectories_excluded', _folder_list) + +_MSBuildOnly(_lib, 'DisplayLibrary', _string) # /LIST Visible='false' +_MSBuildOnly(_lib, 'ErrorReporting', + _Enumeration([], new=['PromptImmediately', # /ERRORREPORT:PROMPT + 'QueueForNextLogin', # /ERRORREPORT:QUEUE + 'SendErrorReport', # /ERRORREPORT:SEND + 'NoErrorReport'])) # /ERRORREPORT:NONE +_MSBuildOnly(_lib, 'MinimumRequiredVersion', _string) +_MSBuildOnly(_lib, 'Name', _file_name) # /NAME +_MSBuildOnly(_lib, 'RemoveObjects', _file_list) # /REMOVE +_MSBuildOnly(_lib, 'SubSystem', _subsystem_enumeration) +_MSBuildOnly(_lib, 'TargetMachine', _target_machine_enumeration) +_MSBuildOnly(_lib, 'TrackerLogDirectory', _folder_name) +_MSBuildOnly(_lib, 'TreatLibWarningAsErrors', _boolean) # /WX +_MSBuildOnly(_lib, 'Verbose', _boolean) + + +# Directives for converting VCManifestTool to Mt. +# See "c:\Program Files (x86)\MSBuild\Microsoft.Cpp\v4.0\1033\mt.xml" for +# the schema of the MSBuild Lib settings. + +# Options that have the same name in MSVS and MSBuild +_Same(_manifest, 'AdditionalManifestFiles', _file_list) # /manifest +_Same(_manifest, 'AdditionalOptions', _string_list) +_Same(_manifest, 'AssemblyIdentity', _string) # /identity: +_Same(_manifest, 'ComponentFileName', _file_name) # /dll +_Same(_manifest, 'GenerateCatalogFiles', _boolean) # /makecdfs +_Same(_manifest, 'InputResourceManifests', _string) # /inputresource +_Same(_manifest, 'OutputManifestFile', _file_name) # /out +_Same(_manifest, 'RegistrarScriptFile', _file_name) # /rgs +_Same(_manifest, 'ReplacementsFile', _file_name) # /replacements +_Same(_manifest, 'SuppressStartupBanner', _boolean) # /nologo +_Same(_manifest, 'TypeLibraryFile', _file_name) # /tlb: +_Same(_manifest, 'UpdateFileHashes', _boolean) # /hashupdate +_Same(_manifest, 'UpdateFileHashesSearchPath', _file_name) +_Same(_manifest, 'VerboseOutput', _boolean) # /verbose + +# Options that have moved location. +_MovedAndRenamed(_manifest, 'ManifestResourceFile', + 'ManifestResourceCompile', + 'ResourceOutputFileName', + _file_name) +_Moved(_manifest, 'EmbedManifest', '', _boolean) + +# MSVS options not found in MSBuild. +_MSVSOnly(_manifest, 'DependencyInformationFile', _file_name) +_MSVSOnly(_manifest, 'UseFAT32Workaround', _boolean) +_MSVSOnly(_manifest, 'UseUnicodeResponseFiles', _boolean) + +# MSBuild options not found in MSVS. +_MSBuildOnly(_manifest, 'EnableDPIAwareness', _boolean) +_MSBuildOnly(_manifest, 'GenerateCategoryTags', _boolean) # /category +_MSBuildOnly(_manifest, 'ManifestFromManagedAssembly', + _file_name) # /managedassemblyname +_MSBuildOnly(_manifest, 'OutputResourceManifests', _string) # /outputresource +_MSBuildOnly(_manifest, 'SuppressDependencyElement', _boolean) # /nodependency +_MSBuildOnly(_manifest, 'TrackerLogDirectory', _folder_name) diff --git a/node-v0.8.14/tools/gyp/pylib/gyp/MSVSSettings_test.py b/node-v0.8.14/tools/gyp/pylib/gyp/MSVSSettings_test.py new file mode 100755 index 0000000..4e06da3 --- /dev/null +++ b/node-v0.8.14/tools/gyp/pylib/gyp/MSVSSettings_test.py @@ -0,0 +1,1482 @@ +#!/usr/bin/env python + +# Copyright (c) 2012 Google Inc. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +"""Unit tests for the MSVSSettings.py file.""" + +import StringIO +import unittest +import gyp.MSVSSettings as MSVSSettings + + +class TestSequenceFunctions(unittest.TestCase): + + def setUp(self): + self.stderr = StringIO.StringIO() + + def _ExpectedWarnings(self, expected): + """Compares recorded lines to expected warnings.""" + self.stderr.seek(0) + actual = self.stderr.read().split('\n') + actual = [line for line in actual if line] + self.assertEqual(sorted(expected), sorted(actual)) + + def testValidateMSVSSettings_tool_names(self): + """Tests that only MSVS tool names are allowed.""" + MSVSSettings.ValidateMSVSSettings( + {'VCCLCompilerTool': {}, + 'VCLinkerTool': {}, + 'VCMIDLTool': {}, + 'foo': {}, + 'VCResourceCompilerTool': {}, + 'VCLibrarianTool': {}, + 'VCManifestTool': {}, + 'ClCompile': {}}, + self.stderr) + self._ExpectedWarnings([ + 'Warning: unrecognized tool foo', + 'Warning: unrecognized tool ClCompile']) + + def testValidateMSVSSettings_settings(self): + """Tests that for invalid MSVS settings.""" + MSVSSettings.ValidateMSVSSettings( + {'VCCLCompilerTool': { + 'AdditionalIncludeDirectories': 'folder1;folder2', + 'AdditionalOptions': ['string1', 'string2'], + 'AdditionalUsingDirectories': 'folder1;folder2', + 'AssemblerListingLocation': 'a_file_name', + 'AssemblerOutput': '0', + 'BasicRuntimeChecks': '5', + 'BrowseInformation': 'fdkslj', + 'BrowseInformationFile': 'a_file_name', + 'BufferSecurityCheck': 'true', + 'CallingConvention': '-1', + 'CompileAs': '1', + 'DebugInformationFormat': '2', + 'DefaultCharIsUnsigned': 'true', + 'Detect64BitPortabilityProblems': 'true', + 'DisableLanguageExtensions': 'true', + 'DisableSpecificWarnings': 'string1;string2', + 'EnableEnhancedInstructionSet': '1', + 'EnableFiberSafeOptimizations': 'true', + 'EnableFunctionLevelLinking': 'true', + 'EnableIntrinsicFunctions': 'true', + 'EnablePREfast': 'true', + 'Enableprefast': 'bogus', + 'ErrorReporting': '1', + 'ExceptionHandling': '1', + 'ExpandAttributedSource': 'true', + 'FavorSizeOrSpeed': '1', + 'FloatingPointExceptions': 'true', + 'FloatingPointModel': '1', + 'ForceConformanceInForLoopScope': 'true', + 'ForcedIncludeFiles': 'file1;file2', + 'ForcedUsingFiles': 'file1;file2', + 'GeneratePreprocessedFile': '1', + 'GenerateXMLDocumentationFiles': 'true', + 'IgnoreStandardIncludePath': 'true', + 'InlineFunctionExpansion': '1', + 'KeepComments': 'true', + 'MinimalRebuild': 'true', + 'ObjectFile': 'a_file_name', + 'OmitDefaultLibName': 'true', + 'OmitFramePointers': 'true', + 'OpenMP': 'true', + 'Optimization': '1', + 'PrecompiledHeaderFile': 'a_file_name', + 'PrecompiledHeaderThrough': 'a_file_name', + 'PreprocessorDefinitions': 'string1;string2', + 'ProgramDataBaseFileName': 'a_file_name', + 'RuntimeLibrary': '1', + 'RuntimeTypeInfo': 'true', + 'ShowIncludes': 'true', + 'SmallerTypeCheck': 'true', + 'StringPooling': 'true', + 'StructMemberAlignment': '1', + 'SuppressStartupBanner': 'true', + 'TreatWChar_tAsBuiltInType': 'true', + 'UndefineAllPreprocessorDefinitions': 'true', + 'UndefinePreprocessorDefinitions': 'string1;string2', + 'UseFullPaths': 'true', + 'UsePrecompiledHeader': '1', + 'UseUnicodeResponseFiles': 'true', + 'WarnAsError': 'true', + 'WarningLevel': '1', + 'WholeProgramOptimization': 'true', + 'XMLDocumentationFileName': 'a_file_name', + 'ZZXYZ': 'bogus'}, + 'VCLinkerTool': { + 'AdditionalDependencies': 'file1;file2', + 'AdditionalLibraryDirectories': 'folder1;folder2', + 'AdditionalManifestDependencies': 'file1;file2', + 'AdditionalOptions': 'a string1', + 'AddModuleNamesToAssembly': 'file1;file2', + 'AllowIsolation': 'true', + 'AssemblyDebug': '2', + 'AssemblyLinkResource': 'file1;file2', + 'BaseAddress': 'a string1', + 'CLRImageType': '2', + 'CLRThreadAttribute': '2', + 'CLRUnmanagedCodeCheck': 'true', + 'DataExecutionPrevention': '2', + 'DelayLoadDLLs': 'file1;file2', + 'DelaySign': 'true', + 'Driver': '2', + 'EmbedManagedResourceFile': 'file1;file2', + 'EnableCOMDATFolding': '2', + 'EnableUAC': 'true', + 'EntryPointSymbol': 'a string1', + 'ErrorReporting': '2', + 'FixedBaseAddress': '2', + 'ForceSymbolReferences': 'file1;file2', + 'FunctionOrder': 'a_file_name', + 'GenerateDebugInformation': 'true', + 'GenerateManifest': 'true', + 'GenerateMapFile': 'true', + 'HeapCommitSize': 'a string1', + 'HeapReserveSize': 'a string1', + 'IgnoreAllDefaultLibraries': 'true', + 'IgnoreDefaultLibraryNames': 'file1;file2', + 'IgnoreEmbeddedIDL': 'true', + 'IgnoreImportLibrary': 'true', + 'ImportLibrary': 'a_file_name', + 'KeyContainer': 'a_file_name', + 'KeyFile': 'a_file_name', + 'LargeAddressAware': '2', + 'LinkIncremental': '2', + 'LinkLibraryDependencies': 'true', + 'LinkTimeCodeGeneration': '2', + 'ManifestFile': 'a_file_name', + 'MapExports': 'true', + 'MapFileName': 'a_file_name', + 'MergedIDLBaseFileName': 'a_file_name', + 'MergeSections': 'a string1', + 'MidlCommandFile': 'a_file_name', + 'ModuleDefinitionFile': 'a_file_name', + 'OptimizeForWindows98': '1', + 'OptimizeReferences': '2', + 'OutputFile': 'a_file_name', + 'PerUserRedirection': 'true', + 'Profile': 'true', + 'ProfileGuidedDatabase': 'a_file_name', + 'ProgramDatabaseFile': 'a_file_name', + 'RandomizedBaseAddress': '2', + 'RegisterOutput': 'true', + 'ResourceOnlyDLL': 'true', + 'SetChecksum': 'true', + 'ShowProgress': '2', + 'StackCommitSize': 'a string1', + 'StackReserveSize': 'a string1', + 'StripPrivateSymbols': 'a_file_name', + 'SubSystem': '2', + 'SupportUnloadOfDelayLoadedDLL': 'true', + 'SuppressStartupBanner': 'true', + 'SwapRunFromCD': 'true', + 'SwapRunFromNet': 'true', + 'TargetMachine': '2', + 'TerminalServerAware': '2', + 'TurnOffAssemblyGeneration': 'true', + 'TypeLibraryFile': 'a_file_name', + 'TypeLibraryResourceID': '33', + 'UACExecutionLevel': '2', + 'UACUIAccess': 'true', + 'UseLibraryDependencyInputs': 'true', + 'UseUnicodeResponseFiles': 'true', + 'Version': 'a string1'}, + 'VCMIDLTool': { + 'AdditionalIncludeDirectories': 'folder1;folder2', + 'AdditionalOptions': 'a string1', + 'CPreprocessOptions': 'a string1', + 'DefaultCharType': '1', + 'DLLDataFileName': 'a_file_name', + 'EnableErrorChecks': '1', + 'ErrorCheckAllocations': 'true', + 'ErrorCheckBounds': 'true', + 'ErrorCheckEnumRange': 'true', + 'ErrorCheckRefPointers': 'true', + 'ErrorCheckStubData': 'true', + 'GenerateStublessProxies': 'true', + 'GenerateTypeLibrary': 'true', + 'HeaderFileName': 'a_file_name', + 'IgnoreStandardIncludePath': 'true', + 'InterfaceIdentifierFileName': 'a_file_name', + 'MkTypLibCompatible': 'true', + 'notgood': 'bogus', + 'OutputDirectory': 'a string1', + 'PreprocessorDefinitions': 'string1;string2', + 'ProxyFileName': 'a_file_name', + 'RedirectOutputAndErrors': 'a_file_name', + 'StructMemberAlignment': '1', + 'SuppressStartupBanner': 'true', + 'TargetEnvironment': '1', + 'TypeLibraryName': 'a_file_name', + 'UndefinePreprocessorDefinitions': 'string1;string2', + 'ValidateParameters': 'true', + 'WarnAsError': 'true', + 'WarningLevel': '1'}, + 'VCResourceCompilerTool': { + 'AdditionalOptions': 'a string1', + 'AdditionalIncludeDirectories': 'folder1;folder2', + 'Culture': '1003', + 'IgnoreStandardIncludePath': 'true', + 'notgood2': 'bogus', + 'PreprocessorDefinitions': 'string1;string2', + 'ResourceOutputFileName': 'a string1', + 'ShowProgress': 'true', + 'SuppressStartupBanner': 'true', + 'UndefinePreprocessorDefinitions': 'string1;string2'}, + 'VCLibrarianTool': { + 'AdditionalDependencies': 'file1;file2', + 'AdditionalLibraryDirectories': 'folder1;folder2', + 'AdditionalOptions': 'a string1', + 'ExportNamedFunctions': 'string1;string2', + 'ForceSymbolReferences': 'a string1', + 'IgnoreAllDefaultLibraries': 'true', + 'IgnoreSpecificDefaultLibraries': 'file1;file2', + 'LinkLibraryDependencies': 'true', + 'ModuleDefinitionFile': 'a_file_name', + 'OutputFile': 'a_file_name', + 'SuppressStartupBanner': 'true', + 'UseUnicodeResponseFiles': 'true'}, + 'VCManifestTool': { + 'AdditionalManifestFiles': 'file1;file2', + 'AdditionalOptions': 'a string1', + 'AssemblyIdentity': 'a string1', + 'ComponentFileName': 'a_file_name', + 'DependencyInformationFile': 'a_file_name', + 'GenerateCatalogFiles': 'true', + 'InputResourceManifests': 'a string1', + 'ManifestResourceFile': 'a_file_name', + 'OutputManifestFile': 'a_file_name', + 'RegistrarScriptFile': 'a_file_name', + 'ReplacementsFile': 'a_file_name', + 'SuppressStartupBanner': 'true', + 'TypeLibraryFile': 'a_file_name', + 'UpdateFileHashes': 'truel', + 'UpdateFileHashesSearchPath': 'a_file_name', + 'UseFAT32Workaround': 'true', + 'UseUnicodeResponseFiles': 'true', + 'VerboseOutput': 'true'}}, + self.stderr) + self._ExpectedWarnings([ + 'Warning: for VCCLCompilerTool/BasicRuntimeChecks, ' + 'index value (5) not in expected range [0, 4)', + 'Warning: for VCCLCompilerTool/BrowseInformation, ' + "invalid literal for int() with base 10: 'fdkslj'", + 'Warning: for VCCLCompilerTool/CallingConvention, ' + 'index value (-1) not in expected range [0, 3)', + 'Warning: for VCCLCompilerTool/DebugInformationFormat, ' + 'converted value for 2 not specified.', + 'Warning: unrecognized setting VCCLCompilerTool/Enableprefast', + 'Warning: unrecognized setting VCCLCompilerTool/ZZXYZ', + 'Warning: for VCLinkerTool/TargetMachine, ' + 'converted value for 2 not specified.', + 'Warning: unrecognized setting VCMIDLTool/notgood', + 'Warning: unrecognized setting VCResourceCompilerTool/notgood2', + 'Warning: for VCManifestTool/UpdateFileHashes, ' + "expected bool; got 'truel'" + '']) + + def testValidateMSBuildSettings_settings(self): + """Tests that for invalid MSBuild settings.""" + MSVSSettings.ValidateMSBuildSettings( + {'ClCompile': { + 'AdditionalIncludeDirectories': 'folder1;folder2', + 'AdditionalOptions': ['string1', 'string2'], + 'AdditionalUsingDirectories': 'folder1;folder2', + 'AssemblerListingLocation': 'a_file_name', + 'AssemblerOutput': 'NoListing', + 'BasicRuntimeChecks': 'StackFrameRuntimeCheck', + 'BrowseInformation': 'false', + 'BrowseInformationFile': 'a_file_name', + 'BufferSecurityCheck': 'true', + 'BuildingInIDE': 'true', + 'CallingConvention': 'Cdecl', + 'CompileAs': 'CompileAsC', + 'CompileAsManaged': 'Pure', + 'CreateHotpatchableImage': 'true', + 'DebugInformationFormat': 'ProgramDatabase', + 'DisableLanguageExtensions': 'true', + 'DisableSpecificWarnings': 'string1;string2', + 'EnableEnhancedInstructionSet': 'StreamingSIMDExtensions', + 'EnableFiberSafeOptimizations': 'true', + 'EnablePREfast': 'true', + 'Enableprefast': 'bogus', + 'ErrorReporting': 'Prompt', + 'ExceptionHandling': 'SyncCThrow', + 'ExpandAttributedSource': 'true', + 'FavorSizeOrSpeed': 'Neither', + 'FloatingPointExceptions': 'true', + 'FloatingPointModel': 'Precise', + 'ForceConformanceInForLoopScope': 'true', + 'ForcedIncludeFiles': 'file1;file2', + 'ForcedUsingFiles': 'file1;file2', + 'FunctionLevelLinking': 'false', + 'GenerateXMLDocumentationFiles': 'true', + 'IgnoreStandardIncludePath': 'true', + 'InlineFunctionExpansion': 'OnlyExplicitInline', + 'IntrinsicFunctions': 'false', + 'MinimalRebuild': 'true', + 'MultiProcessorCompilation': 'true', + 'ObjectFileName': 'a_file_name', + 'OmitDefaultLibName': 'true', + 'OmitFramePointers': 'true', + 'OpenMPSupport': 'true', + 'Optimization': 'Disabled', + 'PrecompiledHeader': 'NotUsing', + 'PrecompiledHeaderFile': 'a_file_name', + 'PrecompiledHeaderOutputFile': 'a_file_name', + 'PreprocessKeepComments': 'true', + 'PreprocessorDefinitions': 'string1;string2', + 'PreprocessOutputPath': 'a string1', + 'PreprocessSuppressLineNumbers': 'false', + 'PreprocessToFile': 'false', + 'ProcessorNumber': '33', + 'ProgramDataBaseFileName': 'a_file_name', + 'RuntimeLibrary': 'MultiThreaded', + 'RuntimeTypeInfo': 'true', + 'ShowIncludes': 'true', + 'SmallerTypeCheck': 'true', + 'StringPooling': 'true', + 'StructMemberAlignment': '1Byte', + 'SuppressStartupBanner': 'true', + 'TrackerLogDirectory': 'a_folder', + 'TreatSpecificWarningsAsErrors': 'string1;string2', + 'TreatWarningAsError': 'true', + 'TreatWChar_tAsBuiltInType': 'true', + 'UndefineAllPreprocessorDefinitions': 'true', + 'UndefinePreprocessorDefinitions': 'string1;string2', + 'UseFullPaths': 'true', + 'UseUnicodeForAssemblerListing': 'true', + 'WarningLevel': 'TurnOffAllWarnings', + 'WholeProgramOptimization': 'true', + 'XMLDocumentationFileName': 'a_file_name', + 'ZZXYZ': 'bogus'}, + 'Link': { + 'AdditionalDependencies': 'file1;file2', + 'AdditionalLibraryDirectories': 'folder1;folder2', + 'AdditionalManifestDependencies': 'file1;file2', + 'AdditionalOptions': 'a string1', + 'AddModuleNamesToAssembly': 'file1;file2', + 'AllowIsolation': 'true', + 'AssemblyDebug': '', + 'AssemblyLinkResource': 'file1;file2', + 'BaseAddress': 'a string1', + 'BuildingInIDE': 'true', + 'CLRImageType': 'ForceIJWImage', + 'CLRSupportLastError': 'Enabled', + 'CLRThreadAttribute': 'MTAThreadingAttribute', + 'CLRUnmanagedCodeCheck': 'true', + 'CreateHotPatchableImage': 'X86Image', + 'DataExecutionPrevention': 'false', + 'DelayLoadDLLs': 'file1;file2', + 'DelaySign': 'true', + 'Driver': 'NotSet', + 'EmbedManagedResourceFile': 'file1;file2', + 'EnableCOMDATFolding': 'false', + 'EnableUAC': 'true', + 'EntryPointSymbol': 'a string1', + 'FixedBaseAddress': 'false', + 'ForceFileOutput': 'Enabled', + 'ForceSymbolReferences': 'file1;file2', + 'FunctionOrder': 'a_file_name', + 'GenerateDebugInformation': 'true', + 'GenerateMapFile': 'true', + 'HeapCommitSize': 'a string1', + 'HeapReserveSize': 'a string1', + 'IgnoreAllDefaultLibraries': 'true', + 'IgnoreEmbeddedIDL': 'true', + 'IgnoreSpecificDefaultLibraries': 'a_file_list', + 'ImageHasSafeExceptionHandlers': 'true', + 'ImportLibrary': 'a_file_name', + 'KeyContainer': 'a_file_name', + 'KeyFile': 'a_file_name', + 'LargeAddressAware': 'false', + 'LinkDLL': 'true', + 'LinkErrorReporting': 'SendErrorReport', + 'LinkStatus': 'true', + 'LinkTimeCodeGeneration': 'UseLinkTimeCodeGeneration', + 'ManifestFile': 'a_file_name', + 'MapExports': 'true', + 'MapFileName': 'a_file_name', + 'MergedIDLBaseFileName': 'a_file_name', + 'MergeSections': 'a string1', + 'MidlCommandFile': 'a_file_name', + 'MinimumRequiredVersion': 'a string1', + 'ModuleDefinitionFile': 'a_file_name', + 'MSDOSStubFileName': 'a_file_name', + 'NoEntryPoint': 'true', + 'OptimizeReferences': 'false', + 'OutputFile': 'a_file_name', + 'PerUserRedirection': 'true', + 'PreventDllBinding': 'true', + 'Profile': 'true', + 'ProfileGuidedDatabase': 'a_file_name', + 'ProgramDatabaseFile': 'a_file_name', + 'RandomizedBaseAddress': 'false', + 'RegisterOutput': 'true', + 'SectionAlignment': '33', + 'SetChecksum': 'true', + 'ShowProgress': 'LinkVerboseREF', + 'SpecifySectionAttributes': 'a string1', + 'StackCommitSize': 'a string1', + 'StackReserveSize': 'a string1', + 'StripPrivateSymbols': 'a_file_name', + 'SubSystem': 'Console', + 'SupportNobindOfDelayLoadedDLL': 'true', + 'SupportUnloadOfDelayLoadedDLL': 'true', + 'SuppressStartupBanner': 'true', + 'SwapRunFromCD': 'true', + 'SwapRunFromNET': 'true', + 'TargetMachine': 'MachineX86', + 'TerminalServerAware': 'false', + 'TrackerLogDirectory': 'a_folder', + 'TreatLinkerWarningAsErrors': 'true', + 'TurnOffAssemblyGeneration': 'true', + 'TypeLibraryFile': 'a_file_name', + 'TypeLibraryResourceID': '33', + 'UACExecutionLevel': 'AsInvoker', + 'UACUIAccess': 'true', + 'Version': 'a string1'}, + 'ResourceCompile': { + 'AdditionalIncludeDirectories': 'folder1;folder2', + 'AdditionalOptions': 'a string1', + 'Culture': '0x236', + 'IgnoreStandardIncludePath': 'true', + 'NullTerminateStrings': 'true', + 'PreprocessorDefinitions': 'string1;string2', + 'ResourceOutputFileName': 'a string1', + 'ShowProgress': 'true', + 'SuppressStartupBanner': 'true', + 'TrackerLogDirectory': 'a_folder', + 'UndefinePreprocessorDefinitions': 'string1;string2'}, + 'Midl': { + 'AdditionalIncludeDirectories': 'folder1;folder2', + 'AdditionalOptions': 'a string1', + 'ApplicationConfigurationMode': 'true', + 'ClientStubFile': 'a_file_name', + 'CPreprocessOptions': 'a string1', + 'DefaultCharType': 'Signed', + 'DllDataFileName': 'a_file_name', + 'EnableErrorChecks': 'EnableCustom', + 'ErrorCheckAllocations': 'true', + 'ErrorCheckBounds': 'true', + 'ErrorCheckEnumRange': 'true', + 'ErrorCheckRefPointers': 'true', + 'ErrorCheckStubData': 'true', + 'GenerateClientFiles': 'Stub', + 'GenerateServerFiles': 'None', + 'GenerateStublessProxies': 'true', + 'GenerateTypeLibrary': 'true', + 'HeaderFileName': 'a_file_name', + 'IgnoreStandardIncludePath': 'true', + 'InterfaceIdentifierFileName': 'a_file_name', + 'LocaleID': '33', + 'MkTypLibCompatible': 'true', + 'OutputDirectory': 'a string1', + 'PreprocessorDefinitions': 'string1;string2', + 'ProxyFileName': 'a_file_name', + 'RedirectOutputAndErrors': 'a_file_name', + 'ServerStubFile': 'a_file_name', + 'StructMemberAlignment': 'NotSet', + 'SuppressCompilerWarnings': 'true', + 'SuppressStartupBanner': 'true', + 'TargetEnvironment': 'Itanium', + 'TrackerLogDirectory': 'a_folder', + 'TypeLibFormat': 'NewFormat', + 'TypeLibraryName': 'a_file_name', + 'UndefinePreprocessorDefinitions': 'string1;string2', + 'ValidateAllParameters': 'true', + 'WarnAsError': 'true', + 'WarningLevel': '1'}, + 'Lib': { + 'AdditionalDependencies': 'file1;file2', + 'AdditionalLibraryDirectories': 'folder1;folder2', + 'AdditionalOptions': 'a string1', + 'DisplayLibrary': 'a string1', + 'ErrorReporting': 'PromptImmediately', + 'ExportNamedFunctions': 'string1;string2', + 'ForceSymbolReferences': 'a string1', + 'IgnoreAllDefaultLibraries': 'true', + 'IgnoreSpecificDefaultLibraries': 'file1;file2', + 'LinkTimeCodeGeneration': 'true', + 'MinimumRequiredVersion': 'a string1', + 'ModuleDefinitionFile': 'a_file_name', + 'Name': 'a_file_name', + 'OutputFile': 'a_file_name', + 'RemoveObjects': 'file1;file2', + 'SubSystem': 'Console', + 'SuppressStartupBanner': 'true', + 'TargetMachine': 'MachineX86i', + 'TrackerLogDirectory': 'a_folder', + 'TreatLibWarningAsErrors': 'true', + 'UseUnicodeResponseFiles': 'true', + 'Verbose': 'true'}, + 'Manifest': { + 'AdditionalManifestFiles': 'file1;file2', + 'AdditionalOptions': 'a string1', + 'AssemblyIdentity': 'a string1', + 'ComponentFileName': 'a_file_name', + 'EnableDPIAwareness': 'fal', + 'GenerateCatalogFiles': 'truel', + 'GenerateCategoryTags': 'true', + 'InputResourceManifests': 'a string1', + 'ManifestFromManagedAssembly': 'a_file_name', + 'notgood3': 'bogus', + 'OutputManifestFile': 'a_file_name', + 'OutputResourceManifests': 'a string1', + 'RegistrarScriptFile': 'a_file_name', + 'ReplacementsFile': 'a_file_name', + 'SuppressDependencyElement': 'true', + 'SuppressStartupBanner': 'true', + 'TrackerLogDirectory': 'a_folder', + 'TypeLibraryFile': 'a_file_name', + 'UpdateFileHashes': 'true', + 'UpdateFileHashesSearchPath': 'a_file_name', + 'VerboseOutput': 'true'}, + 'ProjectReference': { + 'LinkLibraryDependencies': 'true', + 'UseLibraryDependencyInputs': 'true'}, + 'ManifestResourceCompile': { + 'ResourceOutputFileName': 'a_file_name'}, + '': { + 'EmbedManifest': 'true', + 'GenerateManifest': 'true', + 'IgnoreImportLibrary': 'true', + 'LinkIncremental': 'false'}}, + self.stderr) + self._ExpectedWarnings([ + 'Warning: unrecognized setting ClCompile/Enableprefast', + 'Warning: unrecognized setting ClCompile/ZZXYZ', + 'Warning: unrecognized setting Manifest/notgood3', + 'Warning: for Manifest/GenerateCatalogFiles, ' + "expected bool; got 'truel'", + 'Warning: for Lib/TargetMachine, unrecognized enumerated value ' + 'MachineX86i', + "Warning: for Manifest/EnableDPIAwareness, expected bool; got 'fal'"]) + + def testConvertToMSBuildSettings_empty(self): + """Tests an empty conversion.""" + msvs_settings = {} + expected_msbuild_settings = {} + actual_msbuild_settings = MSVSSettings.ConvertToMSBuildSettings( + msvs_settings, + self.stderr) + self.assertEqual(expected_msbuild_settings, actual_msbuild_settings) + self._ExpectedWarnings([]) + + def testConvertToMSBuildSettings_minimal(self): + """Tests a minimal conversion.""" + msvs_settings = { + 'VCCLCompilerTool': { + 'AdditionalIncludeDirectories': 'dir1', + 'AdditionalOptions': '/foo', + 'BasicRuntimeChecks': '0', + }, + 'VCLinkerTool': { + 'LinkTimeCodeGeneration': '1', + 'ErrorReporting': '1', + 'DataExecutionPrevention': '2', + }, + } + expected_msbuild_settings = { + 'ClCompile': { + 'AdditionalIncludeDirectories': 'dir1', + 'AdditionalOptions': '/foo', + 'BasicRuntimeChecks': 'Default', + }, + 'Link': { + 'LinkTimeCodeGeneration': 'UseLinkTimeCodeGeneration', + 'LinkErrorReporting': 'PromptImmediately', + 'DataExecutionPrevention': 'true', + }, + } + actual_msbuild_settings = MSVSSettings.ConvertToMSBuildSettings( + msvs_settings, + self.stderr) + self.assertEqual(expected_msbuild_settings, actual_msbuild_settings) + self._ExpectedWarnings([]) + + def testConvertToMSBuildSettings_warnings(self): + """Tests conversion that generates warnings.""" + msvs_settings = { + 'VCCLCompilerTool': { + 'AdditionalIncludeDirectories': '1', + 'AdditionalOptions': '2', + # These are incorrect values: + 'BasicRuntimeChecks': '12', + 'BrowseInformation': '21', + 'UsePrecompiledHeader': '13', + 'GeneratePreprocessedFile': '14'}, + 'VCLinkerTool': { + # These are incorrect values: + 'Driver': '10', + 'LinkTimeCodeGeneration': '31', + 'ErrorReporting': '21', + 'FixedBaseAddress': '6'}, + 'VCResourceCompilerTool': { + # Custom + 'Culture': '1003'}} + expected_msbuild_settings = { + 'ClCompile': { + 'AdditionalIncludeDirectories': '1', + 'AdditionalOptions': '2'}, + 'Link': {}, + 'ResourceCompile': { + # Custom + 'Culture': '0x03eb'}} + actual_msbuild_settings = MSVSSettings.ConvertToMSBuildSettings( + msvs_settings, + self.stderr) + self.assertEqual(expected_msbuild_settings, actual_msbuild_settings) + self._ExpectedWarnings([ + 'Warning: while converting VCCLCompilerTool/BasicRuntimeChecks to ' + 'MSBuild, index value (12) not in expected range [0, 4)', + 'Warning: while converting VCCLCompilerTool/BrowseInformation to ' + 'MSBuild, index value (21) not in expected range [0, 3)', + 'Warning: while converting VCCLCompilerTool/UsePrecompiledHeader to ' + 'MSBuild, index value (13) not in expected range [0, 3)', + 'Warning: while converting VCCLCompilerTool/GeneratePreprocessedFile to ' + 'MSBuild, value must be one of [0, 1, 2]; got 14', + + 'Warning: while converting VCLinkerTool/Driver to ' + 'MSBuild, index value (10) not in expected range [0, 4)', + 'Warning: while converting VCLinkerTool/LinkTimeCodeGeneration to ' + 'MSBuild, index value (31) not in expected range [0, 5)', + 'Warning: while converting VCLinkerTool/ErrorReporting to ' + 'MSBuild, index value (21) not in expected range [0, 3)', + 'Warning: while converting VCLinkerTool/FixedBaseAddress to ' + 'MSBuild, index value (6) not in expected range [0, 3)', + ]) + + def testConvertToMSBuildSettings_full_synthetic(self): + """Tests conversion of all the MSBuild settings.""" + msvs_settings = { + 'VCCLCompilerTool': { + 'AdditionalIncludeDirectories': 'folder1;folder2;folder3', + 'AdditionalOptions': 'a_string', + 'AdditionalUsingDirectories': 'folder1;folder2;folder3', + 'AssemblerListingLocation': 'a_file_name', + 'AssemblerOutput': '0', + 'BasicRuntimeChecks': '1', + 'BrowseInformation': '2', + 'BrowseInformationFile': 'a_file_name', + 'BufferSecurityCheck': 'true', + 'CallingConvention': '0', + 'CompileAs': '1', + 'DebugInformationFormat': '4', + 'DefaultCharIsUnsigned': 'true', + 'Detect64BitPortabilityProblems': 'true', + 'DisableLanguageExtensions': 'true', + 'DisableSpecificWarnings': 'd1;d2;d3', + 'EnableEnhancedInstructionSet': '0', + 'EnableFiberSafeOptimizations': 'true', + 'EnableFunctionLevelLinking': 'true', + 'EnableIntrinsicFunctions': 'true', + 'EnablePREfast': 'true', + 'ErrorReporting': '1', + 'ExceptionHandling': '2', + 'ExpandAttributedSource': 'true', + 'FavorSizeOrSpeed': '0', + 'FloatingPointExceptions': 'true', + 'FloatingPointModel': '1', + 'ForceConformanceInForLoopScope': 'true', + 'ForcedIncludeFiles': 'file1;file2;file3', + 'ForcedUsingFiles': 'file1;file2;file3', + 'GeneratePreprocessedFile': '1', + 'GenerateXMLDocumentationFiles': 'true', + 'IgnoreStandardIncludePath': 'true', + 'InlineFunctionExpansion': '2', + 'KeepComments': 'true', + 'MinimalRebuild': 'true', + 'ObjectFile': 'a_file_name', + 'OmitDefaultLibName': 'true', + 'OmitFramePointers': 'true', + 'OpenMP': 'true', + 'Optimization': '3', + 'PrecompiledHeaderFile': 'a_file_name', + 'PrecompiledHeaderThrough': 'a_file_name', + 'PreprocessorDefinitions': 'd1;d2;d3', + 'ProgramDataBaseFileName': 'a_file_name', + 'RuntimeLibrary': '0', + 'RuntimeTypeInfo': 'true', + 'ShowIncludes': 'true', + 'SmallerTypeCheck': 'true', + 'StringPooling': 'true', + 'StructMemberAlignment': '1', + 'SuppressStartupBanner': 'true', + 'TreatWChar_tAsBuiltInType': 'true', + 'UndefineAllPreprocessorDefinitions': 'true', + 'UndefinePreprocessorDefinitions': 'd1;d2;d3', + 'UseFullPaths': 'true', + 'UsePrecompiledHeader': '1', + 'UseUnicodeResponseFiles': 'true', + 'WarnAsError': 'true', + 'WarningLevel': '2', + 'WholeProgramOptimization': 'true', + 'XMLDocumentationFileName': 'a_file_name'}, + 'VCLinkerTool': { + 'AdditionalDependencies': 'file1;file2;file3', + 'AdditionalLibraryDirectories': 'folder1;folder2;folder3', + 'AdditionalLibraryDirectories_excluded': 'folder1;folder2;folder3', + 'AdditionalManifestDependencies': 'file1;file2;file3', + 'AdditionalOptions': 'a_string', + 'AddModuleNamesToAssembly': 'file1;file2;file3', + 'AllowIsolation': 'true', + 'AssemblyDebug': '0', + 'AssemblyLinkResource': 'file1;file2;file3', + 'BaseAddress': 'a_string', + 'CLRImageType': '1', + 'CLRThreadAttribute': '2', + 'CLRUnmanagedCodeCheck': 'true', + 'DataExecutionPrevention': '0', + 'DelayLoadDLLs': 'file1;file2;file3', + 'DelaySign': 'true', + 'Driver': '1', + 'EmbedManagedResourceFile': 'file1;file2;file3', + 'EnableCOMDATFolding': '0', + 'EnableUAC': 'true', + 'EntryPointSymbol': 'a_string', + 'ErrorReporting': '0', + 'FixedBaseAddress': '1', + 'ForceSymbolReferences': 'file1;file2;file3', + 'FunctionOrder': 'a_file_name', + 'GenerateDebugInformation': 'true', + 'GenerateManifest': 'true', + 'GenerateMapFile': 'true', + 'HeapCommitSize': 'a_string', + 'HeapReserveSize': 'a_string', + 'IgnoreAllDefaultLibraries': 'true', + 'IgnoreDefaultLibraryNames': 'file1;file2;file3', + 'IgnoreEmbeddedIDL': 'true', + 'IgnoreImportLibrary': 'true', + 'ImportLibrary': 'a_file_name', + 'KeyContainer': 'a_file_name', + 'KeyFile': 'a_file_name', + 'LargeAddressAware': '2', + 'LinkIncremental': '1', + 'LinkLibraryDependencies': 'true', + 'LinkTimeCodeGeneration': '2', + 'ManifestFile': 'a_file_name', + 'MapExports': 'true', + 'MapFileName': 'a_file_name', + 'MergedIDLBaseFileName': 'a_file_name', + 'MergeSections': 'a_string', + 'MidlCommandFile': 'a_file_name', + 'ModuleDefinitionFile': 'a_file_name', + 'OptimizeForWindows98': '1', + 'OptimizeReferences': '0', + 'OutputFile': 'a_file_name', + 'PerUserRedirection': 'true', + 'Profile': 'true', + 'ProfileGuidedDatabase': 'a_file_name', + 'ProgramDatabaseFile': 'a_file_name', + 'RandomizedBaseAddress': '1', + 'RegisterOutput': 'true', + 'ResourceOnlyDLL': 'true', + 'SetChecksum': 'true', + 'ShowProgress': '0', + 'StackCommitSize': 'a_string', + 'StackReserveSize': 'a_string', + 'StripPrivateSymbols': 'a_file_name', + 'SubSystem': '2', + 'SupportUnloadOfDelayLoadedDLL': 'true', + 'SuppressStartupBanner': 'true', + 'SwapRunFromCD': 'true', + 'SwapRunFromNet': 'true', + 'TargetMachine': '3', + 'TerminalServerAware': '2', + 'TurnOffAssemblyGeneration': 'true', + 'TypeLibraryFile': 'a_file_name', + 'TypeLibraryResourceID': '33', + 'UACExecutionLevel': '1', + 'UACUIAccess': 'true', + 'UseLibraryDependencyInputs': 'false', + 'UseUnicodeResponseFiles': 'true', + 'Version': 'a_string'}, + 'VCResourceCompilerTool': { + 'AdditionalIncludeDirectories': 'folder1;folder2;folder3', + 'AdditionalOptions': 'a_string', + 'Culture': '1003', + 'IgnoreStandardIncludePath': 'true', + 'PreprocessorDefinitions': 'd1;d2;d3', + 'ResourceOutputFileName': 'a_string', + 'ShowProgress': 'true', + 'SuppressStartupBanner': 'true', + 'UndefinePreprocessorDefinitions': 'd1;d2;d3'}, + 'VCMIDLTool': { + 'AdditionalIncludeDirectories': 'folder1;folder2;folder3', + 'AdditionalOptions': 'a_string', + 'CPreprocessOptions': 'a_string', + 'DefaultCharType': '0', + 'DLLDataFileName': 'a_file_name', + 'EnableErrorChecks': '2', + 'ErrorCheckAllocations': 'true', + 'ErrorCheckBounds': 'true', + 'ErrorCheckEnumRange': 'true', + 'ErrorCheckRefPointers': 'true', + 'ErrorCheckStubData': 'true', + 'GenerateStublessProxies': 'true', + 'GenerateTypeLibrary': 'true', + 'HeaderFileName': 'a_file_name', + 'IgnoreStandardIncludePath': 'true', + 'InterfaceIdentifierFileName': 'a_file_name', + 'MkTypLibCompatible': 'true', + 'OutputDirectory': 'a_string', + 'PreprocessorDefinitions': 'd1;d2;d3', + 'ProxyFileName': 'a_file_name', + 'RedirectOutputAndErrors': 'a_file_name', + 'StructMemberAlignment': '3', + 'SuppressStartupBanner': 'true', + 'TargetEnvironment': '1', + 'TypeLibraryName': 'a_file_name', + 'UndefinePreprocessorDefinitions': 'd1;d2;d3', + 'ValidateParameters': 'true', + 'WarnAsError': 'true', + 'WarningLevel': '4'}, + 'VCLibrarianTool': { + 'AdditionalDependencies': 'file1;file2;file3', + 'AdditionalLibraryDirectories': 'folder1;folder2;folder3', + 'AdditionalLibraryDirectories_excluded': 'folder1;folder2;folder3', + 'AdditionalOptions': 'a_string', + 'ExportNamedFunctions': 'd1;d2;d3', + 'ForceSymbolReferences': 'a_string', + 'IgnoreAllDefaultLibraries': 'true', + 'IgnoreSpecificDefaultLibraries': 'file1;file2;file3', + 'LinkLibraryDependencies': 'true', + 'ModuleDefinitionFile': 'a_file_name', + 'OutputFile': 'a_file_name', + 'SuppressStartupBanner': 'true', + 'UseUnicodeResponseFiles': 'true'}, + 'VCManifestTool': { + 'AdditionalManifestFiles': 'file1;file2;file3', + 'AdditionalOptions': 'a_string', + 'AssemblyIdentity': 'a_string', + 'ComponentFileName': 'a_file_name', + 'DependencyInformationFile': 'a_file_name', + 'EmbedManifest': 'true', + 'GenerateCatalogFiles': 'true', + 'InputResourceManifests': 'a_string', + 'ManifestResourceFile': 'my_name', + 'OutputManifestFile': 'a_file_name', + 'RegistrarScriptFile': 'a_file_name', + 'ReplacementsFile': 'a_file_name', + 'SuppressStartupBanner': 'true', + 'TypeLibraryFile': 'a_file_name', + 'UpdateFileHashes': 'true', + 'UpdateFileHashesSearchPath': 'a_file_name', + 'UseFAT32Workaround': 'true', + 'UseUnicodeResponseFiles': 'true', + 'VerboseOutput': 'true'}} + expected_msbuild_settings = { + 'ClCompile': { + 'AdditionalIncludeDirectories': 'folder1;folder2;folder3', + 'AdditionalOptions': 'a_string /J', + 'AdditionalUsingDirectories': 'folder1;folder2;folder3', + 'AssemblerListingLocation': 'a_file_name', + 'AssemblerOutput': 'NoListing', + 'BasicRuntimeChecks': 'StackFrameRuntimeCheck', + 'BrowseInformation': 'true', + 'BrowseInformationFile': 'a_file_name', + 'BufferSecurityCheck': 'true', + 'CallingConvention': 'Cdecl', + 'CompileAs': 'CompileAsC', + 'DebugInformationFormat': 'EditAndContinue', + 'DisableLanguageExtensions': 'true', + 'DisableSpecificWarnings': 'd1;d2;d3', + 'EnableEnhancedInstructionSet': 'NotSet', + 'EnableFiberSafeOptimizations': 'true', + 'EnablePREfast': 'true', + 'ErrorReporting': 'Prompt', + 'ExceptionHandling': 'Async', + 'ExpandAttributedSource': 'true', + 'FavorSizeOrSpeed': 'Neither', + 'FloatingPointExceptions': 'true', + 'FloatingPointModel': 'Strict', + 'ForceConformanceInForLoopScope': 'true', + 'ForcedIncludeFiles': 'file1;file2;file3', + 'ForcedUsingFiles': 'file1;file2;file3', + 'FunctionLevelLinking': 'true', + 'GenerateXMLDocumentationFiles': 'true', + 'IgnoreStandardIncludePath': 'true', + 'InlineFunctionExpansion': 'AnySuitable', + 'IntrinsicFunctions': 'true', + 'MinimalRebuild': 'true', + 'ObjectFileName': 'a_file_name', + 'OmitDefaultLibName': 'true', + 'OmitFramePointers': 'true', + 'OpenMPSupport': 'true', + 'Optimization': 'Full', + 'PrecompiledHeader': 'Create', + 'PrecompiledHeaderFile': 'a_file_name', + 'PrecompiledHeaderOutputFile': 'a_file_name', + 'PreprocessKeepComments': 'true', + 'PreprocessorDefinitions': 'd1;d2;d3', + 'PreprocessSuppressLineNumbers': 'false', + 'PreprocessToFile': 'true', + 'ProgramDataBaseFileName': 'a_file_name', + 'RuntimeLibrary': 'MultiThreaded', + 'RuntimeTypeInfo': 'true', + 'ShowIncludes': 'true', + 'SmallerTypeCheck': 'true', + 'StringPooling': 'true', + 'StructMemberAlignment': '1Byte', + 'SuppressStartupBanner': 'true', + 'TreatWarningAsError': 'true', + 'TreatWChar_tAsBuiltInType': 'true', + 'UndefineAllPreprocessorDefinitions': 'true', + 'UndefinePreprocessorDefinitions': 'd1;d2;d3', + 'UseFullPaths': 'true', + 'WarningLevel': 'Level2', + 'WholeProgramOptimization': 'true', + 'XMLDocumentationFileName': 'a_file_name'}, + 'Link': { + 'AdditionalDependencies': 'file1;file2;file3', + 'AdditionalLibraryDirectories': 'folder1;folder2;folder3', + 'AdditionalManifestDependencies': 'file1;file2;file3', + 'AdditionalOptions': 'a_string', + 'AddModuleNamesToAssembly': 'file1;file2;file3', + 'AllowIsolation': 'true', + 'AssemblyDebug': '', + 'AssemblyLinkResource': 'file1;file2;file3', + 'BaseAddress': 'a_string', + 'CLRImageType': 'ForceIJWImage', + 'CLRThreadAttribute': 'STAThreadingAttribute', + 'CLRUnmanagedCodeCheck': 'true', + 'DataExecutionPrevention': '', + 'DelayLoadDLLs': 'file1;file2;file3', + 'DelaySign': 'true', + 'Driver': 'Driver', + 'EmbedManagedResourceFile': 'file1;file2;file3', + 'EnableCOMDATFolding': '', + 'EnableUAC': 'true', + 'EntryPointSymbol': 'a_string', + 'FixedBaseAddress': 'false', + 'ForceSymbolReferences': 'file1;file2;file3', + 'FunctionOrder': 'a_file_name', + 'GenerateDebugInformation': 'true', + 'GenerateMapFile': 'true', + 'HeapCommitSize': 'a_string', + 'HeapReserveSize': 'a_string', + 'IgnoreAllDefaultLibraries': 'true', + 'IgnoreEmbeddedIDL': 'true', + 'IgnoreSpecificDefaultLibraries': 'file1;file2;file3', + 'ImportLibrary': 'a_file_name', + 'KeyContainer': 'a_file_name', + 'KeyFile': 'a_file_name', + 'LargeAddressAware': 'true', + 'LinkErrorReporting': 'NoErrorReport', + 'LinkTimeCodeGeneration': 'PGInstrument', + 'ManifestFile': 'a_file_name', + 'MapExports': 'true', + 'MapFileName': 'a_file_name', + 'MergedIDLBaseFileName': 'a_file_name', + 'MergeSections': 'a_string', + 'MidlCommandFile': 'a_file_name', + 'ModuleDefinitionFile': 'a_file_name', + 'NoEntryPoint': 'true', + 'OptimizeReferences': '', + 'OutputFile': 'a_file_name', + 'PerUserRedirection': 'true', + 'Profile': 'true', + 'ProfileGuidedDatabase': 'a_file_name', + 'ProgramDatabaseFile': 'a_file_name', + 'RandomizedBaseAddress': 'false', + 'RegisterOutput': 'true', + 'SetChecksum': 'true', + 'ShowProgress': 'NotSet', + 'StackCommitSize': 'a_string', + 'StackReserveSize': 'a_string', + 'StripPrivateSymbols': 'a_file_name', + 'SubSystem': 'Windows', + 'SupportUnloadOfDelayLoadedDLL': 'true', + 'SuppressStartupBanner': 'true', + 'SwapRunFromCD': 'true', + 'SwapRunFromNET': 'true', + 'TargetMachine': 'MachineARM', + 'TerminalServerAware': 'true', + 'TurnOffAssemblyGeneration': 'true', + 'TypeLibraryFile': 'a_file_name', + 'TypeLibraryResourceID': '33', + 'UACExecutionLevel': 'HighestAvailable', + 'UACUIAccess': 'true', + 'Version': 'a_string'}, + 'ResourceCompile': { + 'AdditionalIncludeDirectories': 'folder1;folder2;folder3', + 'AdditionalOptions': 'a_string', + 'Culture': '0x03eb', + 'IgnoreStandardIncludePath': 'true', + 'PreprocessorDefinitions': 'd1;d2;d3', + 'ResourceOutputFileName': 'a_string', + 'ShowProgress': 'true', + 'SuppressStartupBanner': 'true', + 'UndefinePreprocessorDefinitions': 'd1;d2;d3'}, + 'Midl': { + 'AdditionalIncludeDirectories': 'folder1;folder2;folder3', + 'AdditionalOptions': 'a_string', + 'CPreprocessOptions': 'a_string', + 'DefaultCharType': 'Unsigned', + 'DllDataFileName': 'a_file_name', + 'EnableErrorChecks': 'All', + 'ErrorCheckAllocations': 'true', + 'ErrorCheckBounds': 'true', + 'ErrorCheckEnumRange': 'true', + 'ErrorCheckRefPointers': 'true', + 'ErrorCheckStubData': 'true', + 'GenerateStublessProxies': 'true', + 'GenerateTypeLibrary': 'true', + 'HeaderFileName': 'a_file_name', + 'IgnoreStandardIncludePath': 'true', + 'InterfaceIdentifierFileName': 'a_file_name', + 'MkTypLibCompatible': 'true', + 'OutputDirectory': 'a_string', + 'PreprocessorDefinitions': 'd1;d2;d3', + 'ProxyFileName': 'a_file_name', + 'RedirectOutputAndErrors': 'a_file_name', + 'StructMemberAlignment': '4', + 'SuppressStartupBanner': 'true', + 'TargetEnvironment': 'Win32', + 'TypeLibraryName': 'a_file_name', + 'UndefinePreprocessorDefinitions': 'd1;d2;d3', + 'ValidateAllParameters': 'true', + 'WarnAsError': 'true', + 'WarningLevel': '4'}, + 'Lib': { + 'AdditionalDependencies': 'file1;file2;file3', + 'AdditionalLibraryDirectories': 'folder1;folder2;folder3', + 'AdditionalOptions': 'a_string', + 'ExportNamedFunctions': 'd1;d2;d3', + 'ForceSymbolReferences': 'a_string', + 'IgnoreAllDefaultLibraries': 'true', + 'IgnoreSpecificDefaultLibraries': 'file1;file2;file3', + 'ModuleDefinitionFile': 'a_file_name', + 'OutputFile': 'a_file_name', + 'SuppressStartupBanner': 'true', + 'UseUnicodeResponseFiles': 'true'}, + 'Manifest': { + 'AdditionalManifestFiles': 'file1;file2;file3', + 'AdditionalOptions': 'a_string', + 'AssemblyIdentity': 'a_string', + 'ComponentFileName': 'a_file_name', + 'GenerateCatalogFiles': 'true', + 'InputResourceManifests': 'a_string', + 'OutputManifestFile': 'a_file_name', + 'RegistrarScriptFile': 'a_file_name', + 'ReplacementsFile': 'a_file_name', + 'SuppressStartupBanner': 'true', + 'TypeLibraryFile': 'a_file_name', + 'UpdateFileHashes': 'true', + 'UpdateFileHashesSearchPath': 'a_file_name', + 'VerboseOutput': 'true'}, + 'ManifestResourceCompile': { + 'ResourceOutputFileName': 'my_name'}, + 'ProjectReference': { + 'LinkLibraryDependencies': 'true', + 'UseLibraryDependencyInputs': 'false'}, + '': { + 'EmbedManifest': 'true', + 'GenerateManifest': 'true', + 'IgnoreImportLibrary': 'true', + 'LinkIncremental': 'false'}} + actual_msbuild_settings = MSVSSettings.ConvertToMSBuildSettings( + msvs_settings, + self.stderr) + self.assertEqual(expected_msbuild_settings, actual_msbuild_settings) + self._ExpectedWarnings([]) + + def testConvertToMSBuildSettings_actual(self): + """Tests the conversion of an actual project. + + A VS2008 project with most of the options defined was created through the + VS2008 IDE. It was then converted to VS2010. The tool settings found in + the .vcproj and .vcxproj files were converted to the two dictionaries + msvs_settings and expected_msbuild_settings. + + Note that for many settings, the VS2010 converter adds macros like + %(AdditionalIncludeDirectories) to make sure than inherited values are + included. Since the Gyp projects we generate do not use inheritance, + we removed these macros. They were: + ClCompile: + AdditionalIncludeDirectories: ';%(AdditionalIncludeDirectories)' + AdditionalOptions: ' %(AdditionalOptions)' + AdditionalUsingDirectories: ';%(AdditionalUsingDirectories)' + DisableSpecificWarnings: ';%(DisableSpecificWarnings)', + ForcedIncludeFiles: ';%(ForcedIncludeFiles)', + ForcedUsingFiles: ';%(ForcedUsingFiles)', + PreprocessorDefinitions: ';%(PreprocessorDefinitions)', + UndefinePreprocessorDefinitions: + ';%(UndefinePreprocessorDefinitions)', + Link: + AdditionalDependencies: ';%(AdditionalDependencies)', + AdditionalLibraryDirectories: ';%(AdditionalLibraryDirectories)', + AdditionalManifestDependencies: + ';%(AdditionalManifestDependencies)', + AdditionalOptions: ' %(AdditionalOptions)', + AddModuleNamesToAssembly: ';%(AddModuleNamesToAssembly)', + AssemblyLinkResource: ';%(AssemblyLinkResource)', + DelayLoadDLLs: ';%(DelayLoadDLLs)', + EmbedManagedResourceFile: ';%(EmbedManagedResourceFile)', + ForceSymbolReferences: ';%(ForceSymbolReferences)', + IgnoreSpecificDefaultLibraries: + ';%(IgnoreSpecificDefaultLibraries)', + ResourceCompile: + AdditionalIncludeDirectories: ';%(AdditionalIncludeDirectories)', + AdditionalOptions: ' %(AdditionalOptions)', + PreprocessorDefinitions: ';%(PreprocessorDefinitions)', + Manifest: + AdditionalManifestFiles: ';%(AdditionalManifestFiles)', + AdditionalOptions: ' %(AdditionalOptions)', + InputResourceManifests: ';%(InputResourceManifests)', + """ + msvs_settings = { + 'VCCLCompilerTool': { + 'AdditionalIncludeDirectories': 'dir1', + 'AdditionalOptions': '/more', + 'AdditionalUsingDirectories': 'test', + 'AssemblerListingLocation': '$(IntDir)\\a', + 'AssemblerOutput': '1', + 'BasicRuntimeChecks': '3', + 'BrowseInformation': '1', + 'BrowseInformationFile': '$(IntDir)\\e', + 'BufferSecurityCheck': 'false', + 'CallingConvention': '1', + 'CompileAs': '1', + 'DebugInformationFormat': '4', + 'DefaultCharIsUnsigned': 'true', + 'Detect64BitPortabilityProblems': 'true', + 'DisableLanguageExtensions': 'true', + 'DisableSpecificWarnings': 'abc', + 'EnableEnhancedInstructionSet': '1', + 'EnableFiberSafeOptimizations': 'true', + 'EnableFunctionLevelLinking': 'true', + 'EnableIntrinsicFunctions': 'true', + 'EnablePREfast': 'true', + 'ErrorReporting': '2', + 'ExceptionHandling': '2', + 'ExpandAttributedSource': 'true', + 'FavorSizeOrSpeed': '2', + 'FloatingPointExceptions': 'true', + 'FloatingPointModel': '1', + 'ForceConformanceInForLoopScope': 'false', + 'ForcedIncludeFiles': 'def', + 'ForcedUsingFiles': 'ge', + 'GeneratePreprocessedFile': '2', + 'GenerateXMLDocumentationFiles': 'true', + 'IgnoreStandardIncludePath': 'true', + 'InlineFunctionExpansion': '1', + 'KeepComments': 'true', + 'MinimalRebuild': 'true', + 'ObjectFile': '$(IntDir)\\b', + 'OmitDefaultLibName': 'true', + 'OmitFramePointers': 'true', + 'OpenMP': 'true', + 'Optimization': '3', + 'PrecompiledHeaderFile': '$(IntDir)\\$(TargetName).pche', + 'PrecompiledHeaderThrough': 'StdAfx.hd', + 'PreprocessorDefinitions': 'WIN32;_DEBUG;_CONSOLE', + 'ProgramDataBaseFileName': '$(IntDir)\\vc90b.pdb', + 'RuntimeLibrary': '3', + 'RuntimeTypeInfo': 'false', + 'ShowIncludes': 'true', + 'SmallerTypeCheck': 'true', + 'StringPooling': 'true', + 'StructMemberAlignment': '3', + 'SuppressStartupBanner': 'false', + 'TreatWChar_tAsBuiltInType': 'false', + 'UndefineAllPreprocessorDefinitions': 'true', + 'UndefinePreprocessorDefinitions': 'wer', + 'UseFullPaths': 'true', + 'UsePrecompiledHeader': '0', + 'UseUnicodeResponseFiles': 'false', + 'WarnAsError': 'true', + 'WarningLevel': '3', + 'WholeProgramOptimization': 'true', + 'XMLDocumentationFileName': '$(IntDir)\\c'}, + 'VCLinkerTool': { + 'AdditionalDependencies': 'zx', + 'AdditionalLibraryDirectories': 'asd', + 'AdditionalManifestDependencies': 's2', + 'AdditionalOptions': '/mor2', + 'AddModuleNamesToAssembly': 'd1', + 'AllowIsolation': 'false', + 'AssemblyDebug': '1', + 'AssemblyLinkResource': 'd5', + 'BaseAddress': '23423', + 'CLRImageType': '3', + 'CLRThreadAttribute': '1', + 'CLRUnmanagedCodeCheck': 'true', + 'DataExecutionPrevention': '0', + 'DelayLoadDLLs': 'd4', + 'DelaySign': 'true', + 'Driver': '2', + 'EmbedManagedResourceFile': 'd2', + 'EnableCOMDATFolding': '1', + 'EnableUAC': 'false', + 'EntryPointSymbol': 'f5', + 'ErrorReporting': '2', + 'FixedBaseAddress': '1', + 'ForceSymbolReferences': 'd3', + 'FunctionOrder': 'fssdfsd', + 'GenerateDebugInformation': 'true', + 'GenerateManifest': 'false', + 'GenerateMapFile': 'true', + 'HeapCommitSize': '13', + 'HeapReserveSize': '12', + 'IgnoreAllDefaultLibraries': 'true', + 'IgnoreDefaultLibraryNames': 'flob;flok', + 'IgnoreEmbeddedIDL': 'true', + 'IgnoreImportLibrary': 'true', + 'ImportLibrary': 'f4', + 'KeyContainer': 'f7', + 'KeyFile': 'f6', + 'LargeAddressAware': '2', + 'LinkIncremental': '0', + 'LinkLibraryDependencies': 'false', + 'LinkTimeCodeGeneration': '1', + 'ManifestFile': + '$(IntDir)\\$(TargetFileName).2intermediate.manifest', + 'MapExports': 'true', + 'MapFileName': 'd5', + 'MergedIDLBaseFileName': 'f2', + 'MergeSections': 'f5', + 'MidlCommandFile': 'f1', + 'ModuleDefinitionFile': 'sdsd', + 'OptimizeForWindows98': '2', + 'OptimizeReferences': '2', + 'OutputFile': '$(OutDir)\\$(ProjectName)2.exe', + 'PerUserRedirection': 'true', + 'Profile': 'true', + 'ProfileGuidedDatabase': '$(TargetDir)$(TargetName).pgdd', + 'ProgramDatabaseFile': 'Flob.pdb', + 'RandomizedBaseAddress': '1', + 'RegisterOutput': 'true', + 'ResourceOnlyDLL': 'true', + 'SetChecksum': 'false', + 'ShowProgress': '1', + 'StackCommitSize': '15', + 'StackReserveSize': '14', + 'StripPrivateSymbols': 'd3', + 'SubSystem': '1', + 'SupportUnloadOfDelayLoadedDLL': 'true', + 'SuppressStartupBanner': 'false', + 'SwapRunFromCD': 'true', + 'SwapRunFromNet': 'true', + 'TargetMachine': '1', + 'TerminalServerAware': '1', + 'TurnOffAssemblyGeneration': 'true', + 'TypeLibraryFile': 'f3', + 'TypeLibraryResourceID': '12', + 'UACExecutionLevel': '2', + 'UACUIAccess': 'true', + 'UseLibraryDependencyInputs': 'true', + 'UseUnicodeResponseFiles': 'false', + 'Version': '333'}, + 'VCResourceCompilerTool': { + 'AdditionalIncludeDirectories': 'f3', + 'AdditionalOptions': '/more3', + 'Culture': '3084', + 'IgnoreStandardIncludePath': 'true', + 'PreprocessorDefinitions': '_UNICODE;UNICODE2', + 'ResourceOutputFileName': '$(IntDir)/$(InputName)3.res', + 'ShowProgress': 'true'}, + 'VCManifestTool': { + 'AdditionalManifestFiles': 'sfsdfsd', + 'AdditionalOptions': 'afdsdafsd', + 'AssemblyIdentity': 'sddfdsadfsa', + 'ComponentFileName': 'fsdfds', + 'DependencyInformationFile': '$(IntDir)\\mt.depdfd', + 'EmbedManifest': 'false', + 'GenerateCatalogFiles': 'true', + 'InputResourceManifests': 'asfsfdafs', + 'ManifestResourceFile': + '$(IntDir)\\$(TargetFileName).embed.manifest.resfdsf', + 'OutputManifestFile': '$(TargetPath).manifestdfs', + 'RegistrarScriptFile': 'sdfsfd', + 'ReplacementsFile': 'sdffsd', + 'SuppressStartupBanner': 'false', + 'TypeLibraryFile': 'sfsd', + 'UpdateFileHashes': 'true', + 'UpdateFileHashesSearchPath': 'sfsd', + 'UseFAT32Workaround': 'true', + 'UseUnicodeResponseFiles': 'false', + 'VerboseOutput': 'true'}} + expected_msbuild_settings = { + 'ClCompile': { + 'AdditionalIncludeDirectories': 'dir1', + 'AdditionalOptions': '/more /J', + 'AdditionalUsingDirectories': 'test', + 'AssemblerListingLocation': '$(IntDir)a', + 'AssemblerOutput': 'AssemblyCode', + 'BasicRuntimeChecks': 'EnableFastChecks', + 'BrowseInformation': 'true', + 'BrowseInformationFile': '$(IntDir)e', + 'BufferSecurityCheck': 'false', + 'CallingConvention': 'FastCall', + 'CompileAs': 'CompileAsC', + 'DebugInformationFormat': 'EditAndContinue', + 'DisableLanguageExtensions': 'true', + 'DisableSpecificWarnings': 'abc', + 'EnableEnhancedInstructionSet': 'StreamingSIMDExtensions', + 'EnableFiberSafeOptimizations': 'true', + 'EnablePREfast': 'true', + 'ErrorReporting': 'Queue', + 'ExceptionHandling': 'Async', + 'ExpandAttributedSource': 'true', + 'FavorSizeOrSpeed': 'Size', + 'FloatingPointExceptions': 'true', + 'FloatingPointModel': 'Strict', + 'ForceConformanceInForLoopScope': 'false', + 'ForcedIncludeFiles': 'def', + 'ForcedUsingFiles': 'ge', + 'FunctionLevelLinking': 'true', + 'GenerateXMLDocumentationFiles': 'true', + 'IgnoreStandardIncludePath': 'true', + 'InlineFunctionExpansion': 'OnlyExplicitInline', + 'IntrinsicFunctions': 'true', + 'MinimalRebuild': 'true', + 'ObjectFileName': '$(IntDir)b', + 'OmitDefaultLibName': 'true', + 'OmitFramePointers': 'true', + 'OpenMPSupport': 'true', + 'Optimization': 'Full', + 'PrecompiledHeader': 'NotUsing', # Actual conversion gives '' + 'PrecompiledHeaderFile': 'StdAfx.hd', + 'PrecompiledHeaderOutputFile': '$(IntDir)$(TargetName).pche', + 'PreprocessKeepComments': 'true', + 'PreprocessorDefinitions': 'WIN32;_DEBUG;_CONSOLE', + 'PreprocessSuppressLineNumbers': 'true', + 'PreprocessToFile': 'true', + 'ProgramDataBaseFileName': '$(IntDir)vc90b.pdb', + 'RuntimeLibrary': 'MultiThreadedDebugDLL', + 'RuntimeTypeInfo': 'false', + 'ShowIncludes': 'true', + 'SmallerTypeCheck': 'true', + 'StringPooling': 'true', + 'StructMemberAlignment': '4Bytes', + 'SuppressStartupBanner': 'false', + 'TreatWarningAsError': 'true', + 'TreatWChar_tAsBuiltInType': 'false', + 'UndefineAllPreprocessorDefinitions': 'true', + 'UndefinePreprocessorDefinitions': 'wer', + 'UseFullPaths': 'true', + 'WarningLevel': 'Level3', + 'WholeProgramOptimization': 'true', + 'XMLDocumentationFileName': '$(IntDir)c'}, + 'Link': { + 'AdditionalDependencies': 'zx', + 'AdditionalLibraryDirectories': 'asd', + 'AdditionalManifestDependencies': 's2', + 'AdditionalOptions': '/mor2', + 'AddModuleNamesToAssembly': 'd1', + 'AllowIsolation': 'false', + 'AssemblyDebug': 'true', + 'AssemblyLinkResource': 'd5', + 'BaseAddress': '23423', + 'CLRImageType': 'ForceSafeILImage', + 'CLRThreadAttribute': 'MTAThreadingAttribute', + 'CLRUnmanagedCodeCheck': 'true', + 'DataExecutionPrevention': '', + 'DelayLoadDLLs': 'd4', + 'DelaySign': 'true', + 'Driver': 'UpOnly', + 'EmbedManagedResourceFile': 'd2', + 'EnableCOMDATFolding': 'false', + 'EnableUAC': 'false', + 'EntryPointSymbol': 'f5', + 'FixedBaseAddress': 'false', + 'ForceSymbolReferences': 'd3', + 'FunctionOrder': 'fssdfsd', + 'GenerateDebugInformation': 'true', + 'GenerateMapFile': 'true', + 'HeapCommitSize': '13', + 'HeapReserveSize': '12', + 'IgnoreAllDefaultLibraries': 'true', + 'IgnoreEmbeddedIDL': 'true', + 'IgnoreSpecificDefaultLibraries': 'flob;flok', + 'ImportLibrary': 'f4', + 'KeyContainer': 'f7', + 'KeyFile': 'f6', + 'LargeAddressAware': 'true', + 'LinkErrorReporting': 'QueueForNextLogin', + 'LinkTimeCodeGeneration': 'UseLinkTimeCodeGeneration', + 'ManifestFile': '$(IntDir)$(TargetFileName).2intermediate.manifest', + 'MapExports': 'true', + 'MapFileName': 'd5', + 'MergedIDLBaseFileName': 'f2', + 'MergeSections': 'f5', + 'MidlCommandFile': 'f1', + 'ModuleDefinitionFile': 'sdsd', + 'NoEntryPoint': 'true', + 'OptimizeReferences': 'true', + 'OutputFile': '$(OutDir)$(ProjectName)2.exe', + 'PerUserRedirection': 'true', + 'Profile': 'true', + 'ProfileGuidedDatabase': '$(TargetDir)$(TargetName).pgdd', + 'ProgramDatabaseFile': 'Flob.pdb', + 'RandomizedBaseAddress': 'false', + 'RegisterOutput': 'true', + 'SetChecksum': 'false', + 'ShowProgress': 'LinkVerbose', + 'StackCommitSize': '15', + 'StackReserveSize': '14', + 'StripPrivateSymbols': 'd3', + 'SubSystem': 'Console', + 'SupportUnloadOfDelayLoadedDLL': 'true', + 'SuppressStartupBanner': 'false', + 'SwapRunFromCD': 'true', + 'SwapRunFromNET': 'true', + 'TargetMachine': 'MachineX86', + 'TerminalServerAware': 'false', + 'TurnOffAssemblyGeneration': 'true', + 'TypeLibraryFile': 'f3', + 'TypeLibraryResourceID': '12', + 'UACExecutionLevel': 'RequireAdministrator', + 'UACUIAccess': 'true', + 'Version': '333'}, + 'ResourceCompile': { + 'AdditionalIncludeDirectories': 'f3', + 'AdditionalOptions': '/more3', + 'Culture': '0x0c0c', + 'IgnoreStandardIncludePath': 'true', + 'PreprocessorDefinitions': '_UNICODE;UNICODE2', + 'ResourceOutputFileName': '$(IntDir)%(Filename)3.res', + 'ShowProgress': 'true'}, + 'Manifest': { + 'AdditionalManifestFiles': 'sfsdfsd', + 'AdditionalOptions': 'afdsdafsd', + 'AssemblyIdentity': 'sddfdsadfsa', + 'ComponentFileName': 'fsdfds', + 'GenerateCatalogFiles': 'true', + 'InputResourceManifests': 'asfsfdafs', + 'OutputManifestFile': '$(TargetPath).manifestdfs', + 'RegistrarScriptFile': 'sdfsfd', + 'ReplacementsFile': 'sdffsd', + 'SuppressStartupBanner': 'false', + 'TypeLibraryFile': 'sfsd', + 'UpdateFileHashes': 'true', + 'UpdateFileHashesSearchPath': 'sfsd', + 'VerboseOutput': 'true'}, + 'ProjectReference': { + 'LinkLibraryDependencies': 'false', + 'UseLibraryDependencyInputs': 'true'}, + '': { + 'EmbedManifest': 'false', + 'GenerateManifest': 'false', + 'IgnoreImportLibrary': 'true', + 'LinkIncremental': '' + }, + 'ManifestResourceCompile': { + 'ResourceOutputFileName': + '$(IntDir)$(TargetFileName).embed.manifest.resfdsf'} + } + actual_msbuild_settings = MSVSSettings.ConvertToMSBuildSettings( + msvs_settings, + self.stderr) + self.assertEqual(expected_msbuild_settings, actual_msbuild_settings) + self._ExpectedWarnings([]) + + +if __name__ == '__main__': + unittest.main() diff --git a/node-v0.8.14/tools/gyp/pylib/gyp/MSVSToolFile.py b/node-v0.8.14/tools/gyp/pylib/gyp/MSVSToolFile.py new file mode 100644 index 0000000..74e529a --- /dev/null +++ b/node-v0.8.14/tools/gyp/pylib/gyp/MSVSToolFile.py @@ -0,0 +1,58 @@ +# Copyright (c) 2012 Google Inc. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +"""Visual Studio project reader/writer.""" + +import gyp.common +import gyp.easy_xml as easy_xml + + +class Writer(object): + """Visual Studio XML tool file writer.""" + + def __init__(self, tool_file_path, name): + """Initializes the tool file. + + Args: + tool_file_path: Path to the tool file. + name: Name of the tool file. + """ + self.tool_file_path = tool_file_path + self.name = name + self.rules_section = ['Rules'] + + def AddCustomBuildRule(self, name, cmd, description, + additional_dependencies, + outputs, extensions): + """Adds a rule to the tool file. + + Args: + name: Name of the rule. + description: Description of the rule. + cmd: Command line of the rule. + additional_dependencies: other files which may trigger the rule. + outputs: outputs of the rule. + extensions: extensions handled by the rule. + """ + rule = ['CustomBuildRule', + {'Name': name, + 'ExecutionDescription': description, + 'CommandLine': cmd, + 'Outputs': ';'.join(outputs), + 'FileExtensions': ';'.join(extensions), + 'AdditionalDependencies': + ';'.join(additional_dependencies) + }] + self.rules_section.append(rule) + + def WriteIfChanged(self): + """Writes the tool file.""" + content = ['VisualStudioToolFile', + {'Version': '8.00', + 'Name': self.name + }, + self.rules_section + ] + easy_xml.WriteXmlIfChanged(content, self.tool_file_path, + encoding="Windows-1252") diff --git a/node-v0.8.14/tools/gyp/pylib/gyp/MSVSUserFile.py b/node-v0.8.14/tools/gyp/pylib/gyp/MSVSUserFile.py new file mode 100644 index 0000000..6c07e9a --- /dev/null +++ b/node-v0.8.14/tools/gyp/pylib/gyp/MSVSUserFile.py @@ -0,0 +1,147 @@ +# Copyright (c) 2012 Google Inc. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +"""Visual Studio user preferences file writer.""" + +import os +import re +import socket # for gethostname + +import gyp.common +import gyp.easy_xml as easy_xml + + +#------------------------------------------------------------------------------ + +def _FindCommandInPath(command): + """If there are no slashes in the command given, this function + searches the PATH env to find the given command, and converts it + to an absolute path. We have to do this because MSVS is looking + for an actual file to launch a debugger on, not just a command + line. Note that this happens at GYP time, so anything needing to + be built needs to have a full path.""" + if '/' in command or '\\' in command: + # If the command already has path elements (either relative or + # absolute), then assume it is constructed properly. + return command + else: + # Search through the path list and find an existing file that + # we can access. + paths = os.environ.get('PATH','').split(os.pathsep) + for path in paths: + item = os.path.join(path, command) + if os.path.isfile(item) and os.access(item, os.X_OK): + return item + return command + +def _QuoteWin32CommandLineArgs(args): + new_args = [] + for arg in args: + # Replace all double-quotes with double-double-quotes to escape + # them for cmd shell, and then quote the whole thing if there + # are any. + if arg.find('"') != -1: + arg = '""'.join(arg.split('"')) + arg = '"%s"' % arg + + # Otherwise, if there are any spaces, quote the whole arg. + elif re.search(r'[ \t\n]', arg): + arg = '"%s"' % arg + new_args.append(arg) + return new_args + +class Writer(object): + """Visual Studio XML user user file writer.""" + + def __init__(self, user_file_path, version, name): + """Initializes the user file. + + Args: + user_file_path: Path to the user file. + version: Version info. + name: Name of the user file. + """ + self.user_file_path = user_file_path + self.version = version + self.name = name + self.configurations = {} + + def AddConfig(self, name): + """Adds a configuration to the project. + + Args: + name: Configuration name. + """ + self.configurations[name] = ['Configuration', {'Name': name}] + + def AddDebugSettings(self, config_name, command, environment = {}, + working_directory=""): + """Adds a DebugSettings node to the user file for a particular config. + + Args: + command: command line to run. First element in the list is the + executable. All elements of the command will be quoted if + necessary. + working_directory: other files which may trigger the rule. (optional) + """ + command = _QuoteWin32CommandLineArgs(command) + + abs_command = _FindCommandInPath(command[0]) + + if environment and isinstance(environment, dict): + env_list = ['%s="%s"' % (key, val) + for (key,val) in environment.iteritems()] + environment = ' '.join(env_list) + else: + environment = '' + + n_cmd = ['DebugSettings', + {'Command': abs_command, + 'WorkingDirectory': working_directory, + 'CommandArguments': " ".join(command[1:]), + 'RemoteMachine': socket.gethostname(), + 'Environment': environment, + 'EnvironmentMerge': 'true', + # Currently these are all "dummy" values that we're just setting + # in the default manner that MSVS does it. We could use some of + # these to add additional capabilities, I suppose, but they might + # not have parity with other platforms then. + 'Attach': 'false', + 'DebuggerType': '3', # 'auto' debugger + 'Remote': '1', + 'RemoteCommand': '', + 'HttpUrl': '', + 'PDBPath': '', + 'SQLDebugging': '', + 'DebuggerFlavor': '0', + 'MPIRunCommand': '', + 'MPIRunArguments': '', + 'MPIRunWorkingDirectory': '', + 'ApplicationCommand': '', + 'ApplicationArguments': '', + 'ShimCommand': '', + 'MPIAcceptMode': '', + 'MPIAcceptFilter': '' + }] + + # Find the config, and add it if it doesn't exist. + if config_name not in self.configurations: + self.AddConfig(config_name) + + # Add the DebugSettings onto the appropriate config. + self.configurations[config_name].append(n_cmd) + + def WriteIfChanged(self): + """Writes the user file.""" + configs = ['Configurations'] + for config, spec in sorted(self.configurations.iteritems()): + configs.append(spec) + + content = ['VisualStudioUserFile', + {'Version': self.version.ProjectVersion(), + 'Name': self.name + }, + configs] + easy_xml.WriteXmlIfChanged(content, self.user_file_path, + encoding="Windows-1252") diff --git a/node-v0.8.14/tools/gyp/pylib/gyp/MSVSVersion.py b/node-v0.8.14/tools/gyp/pylib/gyp/MSVSVersion.py new file mode 100644 index 0000000..eeec2e6 --- /dev/null +++ b/node-v0.8.14/tools/gyp/pylib/gyp/MSVSVersion.py @@ -0,0 +1,353 @@ +# Copyright (c) 2012 Google Inc. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +"""Handle version information related to Visual Stuio.""" + +import errno +import os +import re +import subprocess +import sys + + +class VisualStudioVersion(object): + """Information regarding a version of Visual Studio.""" + + def __init__(self, short_name, description, + solution_version, project_version, flat_sln, uses_vcxproj, + path, sdk_based, default_toolset=None): + self.short_name = short_name + self.description = description + self.solution_version = solution_version + self.project_version = project_version + self.flat_sln = flat_sln + self.uses_vcxproj = uses_vcxproj + self.path = path + self.sdk_based = sdk_based + self.default_toolset = default_toolset + + def ShortName(self): + return self.short_name + + def Description(self): + """Get the full description of the version.""" + return self.description + + def SolutionVersion(self): + """Get the version number of the sln files.""" + return self.solution_version + + def ProjectVersion(self): + """Get the version number of the vcproj or vcxproj files.""" + return self.project_version + + def FlatSolution(self): + return self.flat_sln + + def UsesVcxproj(self): + """Returns true if this version uses a vcxproj file.""" + return self.uses_vcxproj + + def ProjectExtension(self): + """Returns the file extension for the project.""" + return self.uses_vcxproj and '.vcxproj' or '.vcproj' + + def Path(self): + """Returns the path to Visual Studio installation.""" + return self.path + + def ToolPath(self, tool): + """Returns the path to a given compiler tool. """ + return os.path.normpath(os.path.join(self.path, "VC/bin", tool)) + + def DefaultToolset(self): + """Returns the msbuild toolset version that will be used in the absence + of a user override.""" + return self.default_toolset + + def SetupScript(self, target_arch): + """Returns a command (with arguments) to be used to set up the + environment.""" + # Check if we are running in the SDK command line environment and use + # the setup script from the SDK if so. |target_arch| should be either + # 'x86' or 'x64'. + assert target_arch in ('x86', 'x64') + sdk_dir = os.environ.get('WindowsSDKDir') + if self.sdk_based and sdk_dir: + return [os.path.normpath(os.path.join(sdk_dir, 'Bin/SetEnv.Cmd')), + '/' + target_arch] + else: + # We don't use VC/vcvarsall.bat for x86 because vcvarsall calls + # vcvars32, which it can only find if VS??COMNTOOLS is set, which it + # isn't always. + if target_arch == 'x86': + return [os.path.normpath( + os.path.join(self.path, 'Common7/Tools/vsvars32.bat'))] + else: + assert target_arch == 'x64' + arg = 'x86_amd64' + if (os.environ.get('PROCESSOR_ARCHITECTURE') == 'AMD64' or + os.environ.get('PROCESSOR_ARCHITEW6432') == 'AMD64'): + # Use the 64-on-64 compiler if we can. + arg = 'amd64' + return [os.path.normpath( + os.path.join(self.path, 'VC/vcvarsall.bat')), arg] + + +def _RegistryQueryBase(sysdir, key, value): + """Use reg.exe to read a particular key. + + While ideally we might use the win32 module, we would like gyp to be + python neutral, so for instance cygwin python lacks this module. + + Arguments: + sysdir: The system subdirectory to attempt to launch reg.exe from. + key: The registry key to read from. + value: The particular value to read. + Return: + stdout from reg.exe, or None for failure. + """ + # Skip if not on Windows or Python Win32 setup issue + if sys.platform not in ('win32', 'cygwin'): + return None + # Setup params to pass to and attempt to launch reg.exe + cmd = [os.path.join(os.environ.get('WINDIR', ''), sysdir, 'reg.exe'), + 'query', key] + if value: + cmd.extend(['/v', value]) + p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE) + # Obtain the stdout from reg.exe, reading to the end so p.returncode is valid + # Note that the error text may be in [1] in some cases + text = p.communicate()[0] + # Check return code from reg.exe; officially 0==success and 1==error + if p.returncode: + return None + return text + + +def _RegistryQuery(key, value=None): + """Use reg.exe to read a particular key through _RegistryQueryBase. + + First tries to launch from %WinDir%\Sysnative to avoid WoW64 redirection. If + that fails, it falls back to System32. Sysnative is available on Vista and + up and available on Windows Server 2003 and XP through KB patch 942589. Note + that Sysnative will always fail if using 64-bit python due to it being a + virtual directory and System32 will work correctly in the first place. + + KB 942589 - http://support.microsoft.com/kb/942589/en-us. + + Arguments: + key: The registry key. + value: The particular registry value to read (optional). + Return: + stdout from reg.exe, or None for failure. + """ + text = None + try: + text = _RegistryQueryBase('Sysnative', key, value) + except OSError, e: + if e.errno == errno.ENOENT: + text = _RegistryQueryBase('System32', key, value) + else: + raise + return text + + +def _RegistryGetValue(key, value): + """Use reg.exe to obtain the value of a registry key. + + Args: + key: The registry key. + value: The particular registry value to read. + Return: + contents of the registry key's value, or None on failure. + """ + text = _RegistryQuery(key, value) + if not text: + return None + # Extract value. + match = re.search(r'REG_\w+\s+([^\r]+)\r\n', text) + if not match: + return None + return match.group(1) + + +def _RegistryKeyExists(key): + """Use reg.exe to see if a key exists. + + Args: + key: The registry key to check. + Return: + True if the key exists + """ + if not _RegistryQuery(key): + return False + return True + + +def _CreateVersion(name, path, sdk_based=False): + """Sets up MSVS project generation. + + Setup is based off the GYP_MSVS_VERSION environment variable or whatever is + autodetected if GYP_MSVS_VERSION is not explicitly specified. If a version is + passed in that doesn't match a value in versions python will throw a error. + """ + versions = { + '2012': VisualStudioVersion('2012', + 'Visual Studio 2012', + solution_version='12.00', + project_version='4.0', + flat_sln=False, + uses_vcxproj=True, + path=path, + sdk_based=sdk_based, + default_toolset='v110'), + '2012e': VisualStudioVersion('2012e', + 'Visual Studio 2012', + solution_version='12.00', + project_version='4.0', + flat_sln=True, + uses_vcxproj=True, + path=path, + sdk_based=sdk_based, + default_toolset='v110'), + '2010': VisualStudioVersion('2010', + 'Visual Studio 2010', + solution_version='11.00', + project_version='4.0', + flat_sln=False, + uses_vcxproj=True, + path=path, + sdk_based=sdk_based), + '2010e': VisualStudioVersion('2010e', + 'Visual Studio 2010', + solution_version='11.00', + project_version='4.0', + flat_sln=True, + uses_vcxproj=True, + path=path, + sdk_based=sdk_based), + '2008': VisualStudioVersion('2008', + 'Visual Studio 2008', + solution_version='10.00', + project_version='9.00', + flat_sln=False, + uses_vcxproj=False, + path=path, + sdk_based=sdk_based), + '2008e': VisualStudioVersion('2008e', + 'Visual Studio 2008', + solution_version='10.00', + project_version='9.00', + flat_sln=True, + uses_vcxproj=False, + path=path, + sdk_based=sdk_based), + '2005': VisualStudioVersion('2005', + 'Visual Studio 2005', + solution_version='9.00', + project_version='8.00', + flat_sln=False, + uses_vcxproj=False, + path=path, + sdk_based=sdk_based), + '2005e': VisualStudioVersion('2005e', + 'Visual Studio 2005', + solution_version='9.00', + project_version='8.00', + flat_sln=True, + uses_vcxproj=False, + path=path, + sdk_based=sdk_based), + } + return versions[str(name)] + + +def _DetectVisualStudioVersions(versions_to_check, force_express): + """Collect the list of installed visual studio versions. + + Returns: + A list of visual studio versions installed in descending order of + usage preference. + Base this on the registry and a quick check if devenv.exe exists. + Only versions 8-10 are considered. + Possibilities are: + 2005(e) - Visual Studio 2005 (8) + 2008(e) - Visual Studio 2008 (9) + 2010(e) - Visual Studio 2010 (10) + 2012(e) - Visual Studio 2012 (11) + Where (e) is e for express editions of MSVS and blank otherwise. + """ + version_to_year = { + '8.0': '2005', '9.0': '2008', '10.0': '2010', '11.0': '2012'} + versions = [] + for version in versions_to_check: + # Old method of searching for which VS version is installed + # We don't use the 2010-encouraged-way because we also want to get the + # path to the binaries, which it doesn't offer. + keys = [r'HKLM\Software\Microsoft\VisualStudio\%s' % version, + r'HKLM\Software\Wow6432Node\Microsoft\VisualStudio\%s' % version, + r'HKLM\Software\Microsoft\VCExpress\%s' % version, + r'HKLM\Software\Wow6432Node\Microsoft\VCExpress\%s' % version] + for index in range(len(keys)): + path = _RegistryGetValue(keys[index], 'InstallDir') + if not path: + continue + # Check for full. + full_path = os.path.join(path, 'devenv.exe') + express_path = os.path.join(path, 'vcexpress.exe') + if not force_express and os.path.exists(full_path): + # Add this one. + versions.append(_CreateVersion(version_to_year[version], + os.path.join(path, '..', '..'))) + # Check for express. + elif os.path.exists(express_path): + # Add this one. + versions.append(_CreateVersion(version_to_year[version] + 'e', + os.path.join(path, '..', '..'))) + + # The old method above does not work when only SDK is installed. + keys = [r'HKLM\Software\Microsoft\VisualStudio\SxS\VC7', + r'HKLM\Software\Wow6432Node\Microsoft\VisualStudio\SxS\VC7'] + for index in range(len(keys)): + path = _RegistryGetValue(keys[index], version) + if not path: + continue + versions.append(_CreateVersion(version_to_year[version] + 'e', + os.path.join(path, '..'), sdk_based=True)) + + return versions + + +def SelectVisualStudioVersion(version='auto'): + """Select which version of Visual Studio projects to generate. + + Arguments: + version: Hook to allow caller to force a particular version (vs auto). + Returns: + An object representing a visual studio project format version. + """ + # In auto mode, check environment variable for override. + if version == 'auto': + version = os.environ.get('GYP_MSVS_VERSION', 'auto') + version_map = { + 'auto': ('10.0', '9.0', '8.0', '11.0'), + '2005': ('8.0',), + '2005e': ('8.0',), + '2008': ('9.0',), + '2008e': ('9.0',), + '2010': ('10.0',), + '2010e': ('10.0',), + '2012': ('11.0',), + '2012e': ('11.0',), + } + version = str(version) + versions = _DetectVisualStudioVersions(version_map[version], 'e' in version) + if not versions: + if version == 'auto': + # Default to 2005 if we couldn't find anything + return _CreateVersion('2005', None) + else: + return _CreateVersion(version, None) + return versions[0] diff --git a/node-v0.8.14/tools/gyp/pylib/gyp/SCons.py b/node-v0.8.14/tools/gyp/pylib/gyp/SCons.py new file mode 100644 index 0000000..42d845e --- /dev/null +++ b/node-v0.8.14/tools/gyp/pylib/gyp/SCons.py @@ -0,0 +1,199 @@ +# Copyright (c) 2012 Google Inc. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +""" +SCons generator. + +This contains class definitions and supporting functions for generating +pieces of SCons files for the different types of GYP targets. +""" + +import os + + +def WriteList(fp, list, prefix='', + separator=',\n ', + preamble=None, + postamble=None): + fp.write(preamble or '') + fp.write((separator or ' ').join([prefix + l for l in list])) + fp.write(postamble or '') + + +class TargetBase(object): + """ + Base class for a SCons representation of a GYP target. + """ + is_ignored = False + target_prefix = '' + target_suffix = '' + def __init__(self, spec): + self.spec = spec + def full_product_name(self): + """ + Returns the full name of the product being built: + + * Uses 'product_name' if it's set, else prefix + 'target_name'. + * Prepends 'product_dir' if set. + * Appends SCons suffix variables for the target type (or + product_extension). + """ + suffix = self.target_suffix + product_extension = self.spec.get('product_extension') + if product_extension: + suffix = '.' + product_extension + prefix = self.spec.get('product_prefix', self.target_prefix) + name = self.spec['target_name'] + name = prefix + self.spec.get('product_name', name) + suffix + product_dir = self.spec.get('product_dir') + if product_dir: + name = os.path.join(product_dir, name) + else: + name = os.path.join(self.out_dir, name) + return name + + def write_input_files(self, fp): + """ + Writes the definition of the input files (sources). + """ + sources = self.spec.get('sources') + if not sources: + fp.write('\ninput_files = []\n') + return + preamble = '\ninput_files = [\n ' + postamble = ',\n]\n' + WriteList(fp, map(repr, sources), preamble=preamble, postamble=postamble) + + def builder_call(self): + """ + Returns the actual SCons builder call to build this target. + """ + name = self.full_product_name() + return 'env.%s(env.File(%r), input_files)' % (self.builder_name, name) + def write_target(self, fp, src_dir='', pre=''): + """ + Writes the lines necessary to build this target. + """ + fp.write('\n' + pre) + fp.write('_outputs = %s\n' % self.builder_call()) + fp.write('target_files.extend(_outputs)\n') + + +class NoneTarget(TargetBase): + """ + A GYP target type of 'none', implicitly or explicitly. + """ + def write_target(self, fp, src_dir='', pre=''): + fp.write('\ntarget_files.extend(input_files)\n') + + +class SettingsTarget(TargetBase): + """ + A GYP target type of 'settings'. + """ + is_ignored = True + + +compilable_sources_template = """ +_result = [] +for infile in input_files: + if env.compilable(infile): + if (type(infile) == type('') + and (infile.startswith(%(src_dir)r) + or not os.path.isabs(env.subst(infile)))): + # Force files below the build directory by replacing all '..' + # elements in the path with '__': + base, ext = os.path.splitext(os.path.normpath(infile)) + base = [d == '..' and '__' or d for d in base.split('/')] + base = os.path.join(*base) + object = '${OBJ_DIR}/${COMPONENT_NAME}/${TARGET_NAME}/' + base + if not infile.startswith(%(src_dir)r): + infile = %(src_dir)r + infile + infile = env.%(name)s(object, infile)[0] + else: + infile = env.%(name)s(infile)[0] + _result.append(infile) +input_files = _result +""" + +class CompilableSourcesTargetBase(TargetBase): + """ + An abstract base class for targets that compile their source files. + + We explicitly transform compilable files into object files, + even though SCons could infer that for us, because we want + to control where the object file ends up. (The implicit rules + in SCons always put the object file next to the source file.) + """ + intermediate_builder_name = None + def write_target(self, fp, src_dir='', pre=''): + if self.intermediate_builder_name is None: + raise NotImplementedError + if src_dir and not src_dir.endswith('/'): + src_dir += '/' + variables = { + 'src_dir': src_dir, + 'name': self.intermediate_builder_name, + } + fp.write(compilable_sources_template % variables) + super(CompilableSourcesTargetBase, self).write_target(fp) + + +class ProgramTarget(CompilableSourcesTargetBase): + """ + A GYP target type of 'executable'. + """ + builder_name = 'GypProgram' + intermediate_builder_name = 'StaticObject' + target_prefix = '${PROGPREFIX}' + target_suffix = '${PROGSUFFIX}' + out_dir = '${TOP_BUILDDIR}' + + +class StaticLibraryTarget(CompilableSourcesTargetBase): + """ + A GYP target type of 'static_library'. + """ + builder_name = 'GypStaticLibrary' + intermediate_builder_name = 'StaticObject' + target_prefix = '${LIBPREFIX}' + target_suffix = '${LIBSUFFIX}' + out_dir = '${LIB_DIR}' + + +class SharedLibraryTarget(CompilableSourcesTargetBase): + """ + A GYP target type of 'shared_library'. + """ + builder_name = 'GypSharedLibrary' + intermediate_builder_name = 'SharedObject' + target_prefix = '${SHLIBPREFIX}' + target_suffix = '${SHLIBSUFFIX}' + out_dir = '${LIB_DIR}' + + +class LoadableModuleTarget(CompilableSourcesTargetBase): + """ + A GYP target type of 'loadable_module'. + """ + builder_name = 'GypLoadableModule' + intermediate_builder_name = 'SharedObject' + target_prefix = '${SHLIBPREFIX}' + target_suffix = '${SHLIBSUFFIX}' + out_dir = '${TOP_BUILDDIR}' + + +TargetMap = { + None : NoneTarget, + 'none' : NoneTarget, + 'settings' : SettingsTarget, + 'executable' : ProgramTarget, + 'static_library' : StaticLibraryTarget, + 'shared_library' : SharedLibraryTarget, + 'loadable_module' : LoadableModuleTarget, +} + + +def Target(spec): + return TargetMap[spec.get('type')](spec) diff --git a/node-v0.8.14/tools/gyp/pylib/gyp/__init__.py b/node-v0.8.14/tools/gyp/pylib/gyp/__init__.py new file mode 100755 index 0000000..54488e5 --- /dev/null +++ b/node-v0.8.14/tools/gyp/pylib/gyp/__init__.py @@ -0,0 +1,517 @@ +#!/usr/bin/env python + +# Copyright (c) 2012 Google Inc. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +import copy +import gyp.input +import optparse +import os.path +import re +import shlex +import sys +import traceback + +# Default debug modes for GYP +debug = {} + +# List of "official" debug modes, but you can use anything you like. +DEBUG_GENERAL = 'general' +DEBUG_VARIABLES = 'variables' +DEBUG_INCLUDES = 'includes' + + +def DebugOutput(mode, message): + if 'all' in gyp.debug.keys() or mode in gyp.debug.keys(): + ctx = ('unknown', 0, 'unknown') + try: + f = traceback.extract_stack(limit=2) + if f: + ctx = f[0][:3] + except: + pass + print '%s:%s:%d:%s %s' % (mode.upper(), os.path.basename(ctx[0]), + ctx[1], ctx[2], message) + +def FindBuildFiles(): + extension = '.gyp' + files = os.listdir(os.getcwd()) + build_files = [] + for file in files: + if file.endswith(extension): + build_files.append(file) + return build_files + + +class GypError(Exception): + """Error class representing an error, which is to be presented + to the user. The main entry point will catch and display this. + """ + pass + + +def Load(build_files, format, default_variables={}, + includes=[], depth='.', params=None, check=False, circular_check=True): + """ + Loads one or more specified build files. + default_variables and includes will be copied before use. + Returns the generator for the specified format and the + data returned by loading the specified build files. + """ + if params is None: + params = {} + + flavor = None + if '-' in format: + format, params['flavor'] = format.split('-', 1) + + default_variables = copy.copy(default_variables) + + # Default variables provided by this program and its modules should be + # named WITH_CAPITAL_LETTERS to provide a distinct "best practice" namespace, + # avoiding collisions with user and automatic variables. + default_variables['GENERATOR'] = format + + # Format can be a custom python file, or by default the name of a module + # within gyp.generator. + if format.endswith('.py'): + generator_name = os.path.splitext(format)[0] + path, generator_name = os.path.split(generator_name) + + # Make sure the path to the custom generator is in sys.path + # Don't worry about removing it once we are done. Keeping the path + # to each generator that is used in sys.path is likely harmless and + # arguably a good idea. + path = os.path.abspath(path) + if path not in sys.path: + sys.path.insert(0, path) + else: + generator_name = 'gyp.generator.' + format + + # These parameters are passed in order (as opposed to by key) + # because ActivePython cannot handle key parameters to __import__. + generator = __import__(generator_name, globals(), locals(), generator_name) + for (key, val) in generator.generator_default_variables.items(): + default_variables.setdefault(key, val) + + # Give the generator the opportunity to set additional variables based on + # the params it will receive in the output phase. + if getattr(generator, 'CalculateVariables', None): + generator.CalculateVariables(default_variables, params) + + # Give the generator the opportunity to set generator_input_info based on + # the params it will receive in the output phase. + if getattr(generator, 'CalculateGeneratorInputInfo', None): + generator.CalculateGeneratorInputInfo(params) + + # Fetch the generator specific info that gets fed to input, we use getattr + # so we can default things and the generators only have to provide what + # they need. + generator_input_info = { + 'generator_wants_absolute_build_file_paths': + getattr(generator, 'generator_wants_absolute_build_file_paths', False), + 'generator_handles_variants': + getattr(generator, 'generator_handles_variants', False), + 'non_configuration_keys': + getattr(generator, 'generator_additional_non_configuration_keys', []), + 'path_sections': + getattr(generator, 'generator_additional_path_sections', []), + 'extra_sources_for_rules': + getattr(generator, 'generator_extra_sources_for_rules', []), + 'generator_supports_multiple_toolsets': + getattr(generator, 'generator_supports_multiple_toolsets', False), + 'generator_wants_static_library_dependencies_adjusted': + getattr(generator, + 'generator_wants_static_library_dependencies_adjusted', True), + 'generator_wants_sorted_dependencies': + getattr(generator, 'generator_wants_sorted_dependencies', False), + } + + # Process the input specific to this generator. + result = gyp.input.Load(build_files, default_variables, includes[:], + depth, generator_input_info, check, circular_check) + return [generator] + result + +def NameValueListToDict(name_value_list): + """ + Takes an array of strings of the form 'NAME=VALUE' and creates a dictionary + of the pairs. If a string is simply NAME, then the value in the dictionary + is set to True. If VALUE can be converted to an integer, it is. + """ + result = { } + for item in name_value_list: + tokens = item.split('=', 1) + if len(tokens) == 2: + # If we can make it an int, use that, otherwise, use the string. + try: + token_value = int(tokens[1]) + except ValueError: + token_value = tokens[1] + # Set the variable to the supplied value. + result[tokens[0]] = token_value + else: + # No value supplied, treat it as a boolean and set it. + result[tokens[0]] = True + return result + +def ShlexEnv(env_name): + flags = os.environ.get(env_name, []) + if flags: + flags = shlex.split(flags) + return flags + +def FormatOpt(opt, value): + if opt.startswith('--'): + return '%s=%s' % (opt, value) + return opt + value + +def RegenerateAppendFlag(flag, values, predicate, env_name, options): + """Regenerate a list of command line flags, for an option of action='append'. + + The |env_name|, if given, is checked in the environment and used to generate + an initial list of options, then the options that were specified on the + command line (given in |values|) are appended. This matches the handling of + environment variables and command line flags where command line flags override + the environment, while not requiring the environment to be set when the flags + are used again. + """ + flags = [] + if options.use_environment and env_name: + for flag_value in ShlexEnv(env_name): + value = FormatOpt(flag, predicate(flag_value)) + if value in flags: + flags.remove(value) + flags.append(value) + if values: + for flag_value in values: + flags.append(FormatOpt(flag, predicate(flag_value))) + return flags + +def RegenerateFlags(options): + """Given a parsed options object, and taking the environment variables into + account, returns a list of flags that should regenerate an equivalent options + object (even in the absence of the environment variables.) + + Any path options will be normalized relative to depth. + + The format flag is not included, as it is assumed the calling generator will + set that as appropriate. + """ + def FixPath(path): + path = gyp.common.FixIfRelativePath(path, options.depth) + if not path: + return os.path.curdir + return path + + def Noop(value): + return value + + # We always want to ignore the environment when regenerating, to avoid + # duplicate or changed flags in the environment at the time of regeneration. + flags = ['--ignore-environment'] + for name, metadata in options._regeneration_metadata.iteritems(): + opt = metadata['opt'] + value = getattr(options, name) + value_predicate = metadata['type'] == 'path' and FixPath or Noop + action = metadata['action'] + env_name = metadata['env_name'] + if action == 'append': + flags.extend(RegenerateAppendFlag(opt, value, value_predicate, + env_name, options)) + elif action in ('store', None): # None is a synonym for 'store'. + if value: + flags.append(FormatOpt(opt, value_predicate(value))) + elif options.use_environment and env_name and os.environ.get(env_name): + flags.append(FormatOpt(opt, value_predicate(os.environ.get(env_name)))) + elif action in ('store_true', 'store_false'): + if ((action == 'store_true' and value) or + (action == 'store_false' and not value)): + flags.append(opt) + elif options.use_environment and env_name: + print >>sys.stderr, ('Warning: environment regeneration unimplemented ' + 'for %s flag %r env_name %r' % (action, opt, + env_name)) + else: + print >>sys.stderr, ('Warning: regeneration unimplemented for action %r ' + 'flag %r' % (action, opt)) + + return flags + +class RegeneratableOptionParser(optparse.OptionParser): + def __init__(self): + self.__regeneratable_options = {} + optparse.OptionParser.__init__(self) + + def add_option(self, *args, **kw): + """Add an option to the parser. + + This accepts the same arguments as OptionParser.add_option, plus the + following: + regenerate: can be set to False to prevent this option from being included + in regeneration. + env_name: name of environment variable that additional values for this + option come from. + type: adds type='path', to tell the regenerator that the values of + this option need to be made relative to options.depth + """ + env_name = kw.pop('env_name', None) + if 'dest' in kw and kw.pop('regenerate', True): + dest = kw['dest'] + + # The path type is needed for regenerating, for optparse we can just treat + # it as a string. + type = kw.get('type') + if type == 'path': + kw['type'] = 'string' + + self.__regeneratable_options[dest] = { + 'action': kw.get('action'), + 'type': type, + 'env_name': env_name, + 'opt': args[0], + } + + optparse.OptionParser.add_option(self, *args, **kw) + + def parse_args(self, *args): + values, args = optparse.OptionParser.parse_args(self, *args) + values._regeneration_metadata = self.__regeneratable_options + return values, args + +def gyp_main(args): + my_name = os.path.basename(sys.argv[0]) + + parser = RegeneratableOptionParser() + usage = 'usage: %s [options ...] [build_file ...]' + parser.set_usage(usage.replace('%s', '%prog')) + parser.add_option('-D', dest='defines', action='append', metavar='VAR=VAL', + env_name='GYP_DEFINES', + help='sets variable VAR to value VAL') + parser.add_option('-f', '--format', dest='formats', action='append', + env_name='GYP_GENERATORS', regenerate=False, + help='output formats to generate') + parser.add_option('--msvs-version', dest='msvs_version', + regenerate=False, + help='Deprecated; use -G msvs_version=MSVS_VERSION instead') + parser.add_option('-I', '--include', dest='includes', action='append', + metavar='INCLUDE', type='path', + help='files to include in all loaded .gyp files') + parser.add_option('--depth', dest='depth', metavar='PATH', type='path', + help='set DEPTH gyp variable to a relative path to PATH') + parser.add_option('-d', '--debug', dest='debug', metavar='DEBUGMODE', + action='append', default=[], help='turn on a debugging ' + 'mode for debugging GYP. Supported modes are "variables", ' + '"includes" and "general" or "all" for all of them.') + parser.add_option('-S', '--suffix', dest='suffix', default='', + help='suffix to add to generated files') + parser.add_option('-G', dest='generator_flags', action='append', default=[], + metavar='FLAG=VAL', env_name='GYP_GENERATOR_FLAGS', + help='sets generator flag FLAG to VAL') + parser.add_option('--generator-output', dest='generator_output', + action='store', default=None, metavar='DIR', type='path', + env_name='GYP_GENERATOR_OUTPUT', + help='puts generated build files under DIR') + parser.add_option('--ignore-environment', dest='use_environment', + action='store_false', default=True, regenerate=False, + help='do not read options from environment variables') + parser.add_option('--check', dest='check', action='store_true', + help='check format of gyp files') + parser.add_option('--toplevel-dir', dest='toplevel_dir', action='store', + default=None, metavar='DIR', type='path', + help='directory to use as the root of the source tree') + # --no-circular-check disables the check for circular relationships between + # .gyp files. These relationships should not exist, but they've only been + # observed to be harmful with the Xcode generator. Chromium's .gyp files + # currently have some circular relationships on non-Mac platforms, so this + # option allows the strict behavior to be used on Macs and the lenient + # behavior to be used elsewhere. + # TODO(mark): Remove this option when http://crbug.com/35878 is fixed. + parser.add_option('--no-circular-check', dest='circular_check', + action='store_false', default=True, regenerate=False, + help="don't check for circular relationships between files") + + # We read a few things from ~/.gyp, so set up a var for that. + home_vars = ['HOME'] + if sys.platform in ('cygwin', 'win32'): + home_vars.append('USERPROFILE') + home = None + home_dot_gyp = None + for home_var in home_vars: + home = os.getenv(home_var) + if home != None: + home_dot_gyp = os.path.join(home, '.gyp') + if not os.path.exists(home_dot_gyp): + home_dot_gyp = None + else: + break + + # TODO(thomasvl): add support for ~/.gyp/defaults + + options, build_files_arg = parser.parse_args(args) + build_files = build_files_arg + + if not options.formats: + # If no format was given on the command line, then check the env variable. + generate_formats = [] + if options.use_environment: + generate_formats = os.environ.get('GYP_GENERATORS', []) + if generate_formats: + generate_formats = re.split('[\s,]', generate_formats) + if generate_formats: + options.formats = generate_formats + else: + # Nothing in the variable, default based on platform. + if sys.platform == 'darwin': + options.formats = ['xcode'] + elif sys.platform in ('win32', 'cygwin'): + options.formats = ['msvs'] + else: + options.formats = ['make'] + + if not options.generator_output and options.use_environment: + g_o = os.environ.get('GYP_GENERATOR_OUTPUT') + if g_o: + options.generator_output = g_o + + for mode in options.debug: + gyp.debug[mode] = 1 + + # Do an extra check to avoid work when we're not debugging. + if DEBUG_GENERAL in gyp.debug.keys(): + DebugOutput(DEBUG_GENERAL, 'running with these options:') + for option, value in sorted(options.__dict__.items()): + if option[0] == '_': + continue + if isinstance(value, basestring): + DebugOutput(DEBUG_GENERAL, " %s: '%s'" % (option, value)) + else: + DebugOutput(DEBUG_GENERAL, " %s: %s" % (option, str(value))) + + if not build_files: + build_files = FindBuildFiles() + if not build_files: + raise GypError((usage + '\n\n%s: error: no build_file') % + (my_name, my_name)) + + # TODO(mark): Chromium-specific hack! + # For Chromium, the gyp "depth" variable should always be a relative path + # to Chromium's top-level "src" directory. If no depth variable was set + # on the command line, try to find a "src" directory by looking at the + # absolute path to each build file's directory. The first "src" component + # found will be treated as though it were the path used for --depth. + if not options.depth: + for build_file in build_files: + build_file_dir = os.path.abspath(os.path.dirname(build_file)) + build_file_dir_components = build_file_dir.split(os.path.sep) + components_len = len(build_file_dir_components) + for index in xrange(components_len - 1, -1, -1): + if build_file_dir_components[index] == 'src': + options.depth = os.path.sep.join(build_file_dir_components) + break + del build_file_dir_components[index] + + # If the inner loop found something, break without advancing to another + # build file. + if options.depth: + break + + if not options.depth: + raise GypError('Could not automatically locate src directory. This is' + 'a temporary Chromium feature that will be removed. Use' + '--depth as a workaround.') + + # If toplevel-dir is not set, we assume that depth is the root of our source + # tree. + if not options.toplevel_dir: + options.toplevel_dir = options.depth + + # -D on the command line sets variable defaults - D isn't just for define, + # it's for default. Perhaps there should be a way to force (-F?) a + # variable's value so that it can't be overridden by anything else. + cmdline_default_variables = {} + defines = [] + if options.use_environment: + defines += ShlexEnv('GYP_DEFINES') + if options.defines: + defines += options.defines + cmdline_default_variables = NameValueListToDict(defines) + if DEBUG_GENERAL in gyp.debug.keys(): + DebugOutput(DEBUG_GENERAL, + "cmdline_default_variables: %s" % cmdline_default_variables) + + # Set up includes. + includes = [] + + # If ~/.gyp/include.gypi exists, it'll be forcibly included into every + # .gyp file that's loaded, before anything else is included. + if home_dot_gyp != None: + default_include = os.path.join(home_dot_gyp, 'include.gypi') + if os.path.exists(default_include): + print 'Using overrides found in ' + default_include + includes.append(default_include) + + # Command-line --include files come after the default include. + if options.includes: + includes.extend(options.includes) + + # Generator flags should be prefixed with the target generator since they + # are global across all generator runs. + gen_flags = [] + if options.use_environment: + gen_flags += ShlexEnv('GYP_GENERATOR_FLAGS') + if options.generator_flags: + gen_flags += options.generator_flags + generator_flags = NameValueListToDict(gen_flags) + if DEBUG_GENERAL in gyp.debug.keys(): + DebugOutput(DEBUG_GENERAL, "generator_flags: %s" % generator_flags) + + # TODO: Remove this and the option after we've gotten folks to move to the + # generator flag. + if options.msvs_version: + print >>sys.stderr, \ + 'DEPRECATED: Use generator flag (-G msvs_version=' + \ + options.msvs_version + ') instead of --msvs-version=' + \ + options.msvs_version + generator_flags['msvs_version'] = options.msvs_version + + # Generate all requested formats (use a set in case we got one format request + # twice) + for format in set(options.formats): + params = {'options': options, + 'build_files': build_files, + 'generator_flags': generator_flags, + 'cwd': os.getcwd(), + 'build_files_arg': build_files_arg, + 'gyp_binary': sys.argv[0], + 'home_dot_gyp': home_dot_gyp} + + # Start with the default variables from the command line. + [generator, flat_list, targets, data] = Load(build_files, format, + cmdline_default_variables, + includes, options.depth, + params, options.check, + options.circular_check) + + # TODO(mark): Pass |data| for now because the generator needs a list of + # build files that came in. In the future, maybe it should just accept + # a list, and not the whole data dict. + # NOTE: flat_list is the flattened dependency graph specifying the order + # that targets may be built. Build systems that operate serially or that + # need to have dependencies defined before dependents reference them should + # generate targets in the order specified in flat_list. + generator.GenerateOutput(flat_list, targets, data, params) + + # Done + return 0 + + +def main(args): + try: + return gyp_main(args) + except GypError, e: + sys.stderr.write("gyp: %s\n" % e) + return 1 + +if __name__ == '__main__': + sys.exit(main(sys.argv[1:])) diff --git a/node-v0.8.14/tools/gyp/pylib/gyp/common.py b/node-v0.8.14/tools/gyp/pylib/gyp/common.py new file mode 100644 index 0000000..6144d2f --- /dev/null +++ b/node-v0.8.14/tools/gyp/pylib/gyp/common.py @@ -0,0 +1,461 @@ +# Copyright (c) 2012 Google Inc. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +from __future__ import with_statement + +import errno +import filecmp +import os.path +import re +import tempfile +import sys + + +# A minimal memoizing decorator. It'll blow up if the args aren't immutable, +# among other "problems". +class memoize(object): + def __init__(self, func): + self.func = func + self.cache = {} + def __call__(self, *args): + try: + return self.cache[args] + except KeyError: + result = self.func(*args) + self.cache[args] = result + return result + + +def ExceptionAppend(e, msg): + """Append a message to the given exception's message.""" + if not e.args: + e.args = (msg,) + elif len(e.args) == 1: + e.args = (str(e.args[0]) + ' ' + msg,) + else: + e.args = (str(e.args[0]) + ' ' + msg,) + e.args[1:] + + +def ParseQualifiedTarget(target): + # Splits a qualified target into a build file, target name and toolset. + + # NOTE: rsplit is used to disambiguate the Windows drive letter separator. + target_split = target.rsplit(':', 1) + if len(target_split) == 2: + [build_file, target] = target_split + else: + build_file = None + + target_split = target.rsplit('#', 1) + if len(target_split) == 2: + [target, toolset] = target_split + else: + toolset = None + + return [build_file, target, toolset] + + +def ResolveTarget(build_file, target, toolset): + # This function resolves a target into a canonical form: + # - a fully defined build file, either absolute or relative to the current + # directory + # - a target name + # - a toolset + # + # build_file is the file relative to which 'target' is defined. + # target is the qualified target. + # toolset is the default toolset for that target. + [parsed_build_file, target, parsed_toolset] = ParseQualifiedTarget(target) + + if parsed_build_file: + if build_file: + # If a relative path, parsed_build_file is relative to the directory + # containing build_file. If build_file is not in the current directory, + # parsed_build_file is not a usable path as-is. Resolve it by + # interpreting it as relative to build_file. If parsed_build_file is + # absolute, it is usable as a path regardless of the current directory, + # and os.path.join will return it as-is. + build_file = os.path.normpath(os.path.join(os.path.dirname(build_file), + parsed_build_file)) + # Further (to handle cases like ../cwd), make it relative to cwd) + if not os.path.isabs(build_file): + build_file = RelativePath(build_file, '.') + else: + build_file = parsed_build_file + + if parsed_toolset: + toolset = parsed_toolset + + return [build_file, target, toolset] + + +def BuildFile(fully_qualified_target): + # Extracts the build file from the fully qualified target. + return ParseQualifiedTarget(fully_qualified_target)[0] + + +def GetEnvironFallback(var_list, default): + """Look up a key in the environment, with fallback to secondary keys + and finally falling back to a default value.""" + for var in var_list: + if var in os.environ: + return os.environ[var] + return default + + +def QualifiedTarget(build_file, target, toolset): + # "Qualified" means the file that a target was defined in and the target + # name, separated by a colon, suffixed by a # and the toolset name: + # /path/to/file.gyp:target_name#toolset + fully_qualified = build_file + ':' + target + if toolset: + fully_qualified = fully_qualified + '#' + toolset + return fully_qualified + + +@memoize +def RelativePath(path, relative_to): + # Assuming both |path| and |relative_to| are relative to the current + # directory, returns a relative path that identifies path relative to + # relative_to. + + # Convert to absolute (and therefore normalized paths). + path = os.path.abspath(path) + relative_to = os.path.abspath(relative_to) + + # Split the paths into components. + path_split = path.split(os.path.sep) + relative_to_split = relative_to.split(os.path.sep) + + # Determine how much of the prefix the two paths share. + prefix_len = len(os.path.commonprefix([path_split, relative_to_split])) + + # Put enough ".." components to back up out of relative_to to the common + # prefix, and then append the part of path_split after the common prefix. + relative_split = [os.path.pardir] * (len(relative_to_split) - prefix_len) + \ + path_split[prefix_len:] + + if len(relative_split) == 0: + # The paths were the same. + return '' + + # Turn it back into a string and we're done. + return os.path.join(*relative_split) + + +def FixIfRelativePath(path, relative_to): + # Like RelativePath but returns |path| unchanged if it is absolute. + if os.path.isabs(path): + return path + return RelativePath(path, relative_to) + + +def UnrelativePath(path, relative_to): + # Assuming that |relative_to| is relative to the current directory, and |path| + # is a path relative to the dirname of |relative_to|, returns a path that + # identifies |path| relative to the current directory. + rel_dir = os.path.dirname(relative_to) + return os.path.normpath(os.path.join(rel_dir, path)) + + +# re objects used by EncodePOSIXShellArgument. See IEEE 1003.1 XCU.2.2 at +# http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_02 +# and the documentation for various shells. + +# _quote is a pattern that should match any argument that needs to be quoted +# with double-quotes by EncodePOSIXShellArgument. It matches the following +# characters appearing anywhere in an argument: +# \t, \n, space parameter separators +# # comments +# $ expansions (quoted to always expand within one argument) +# % called out by IEEE 1003.1 XCU.2.2 +# & job control +# ' quoting +# (, ) subshell execution +# *, ?, [ pathname expansion +# ; command delimiter +# <, >, | redirection +# = assignment +# {, } brace expansion (bash) +# ~ tilde expansion +# It also matches the empty string, because "" (or '') is the only way to +# represent an empty string literal argument to a POSIX shell. +# +# This does not match the characters in _escape, because those need to be +# backslash-escaped regardless of whether they appear in a double-quoted +# string. +_quote = re.compile('[\t\n #$%&\'()*;<=>?[{|}~]|^$') + +# _escape is a pattern that should match any character that needs to be +# escaped with a backslash, whether or not the argument matched the _quote +# pattern. _escape is used with re.sub to backslash anything in _escape's +# first match group, hence the (parentheses) in the regular expression. +# +# _escape matches the following characters appearing anywhere in an argument: +# " to prevent POSIX shells from interpreting this character for quoting +# \ to prevent POSIX shells from interpreting this character for escaping +# ` to prevent POSIX shells from interpreting this character for command +# substitution +# Missing from this list is $, because the desired behavior of +# EncodePOSIXShellArgument is to permit parameter (variable) expansion. +# +# Also missing from this list is !, which bash will interpret as the history +# expansion character when history is enabled. bash does not enable history +# by default in non-interactive shells, so this is not thought to be a problem. +# ! was omitted from this list because bash interprets "\!" as a literal string +# including the backslash character (avoiding history expansion but retaining +# the backslash), which would not be correct for argument encoding. Handling +# this case properly would also be problematic because bash allows the history +# character to be changed with the histchars shell variable. Fortunately, +# as history is not enabled in non-interactive shells and +# EncodePOSIXShellArgument is only expected to encode for non-interactive +# shells, there is no room for error here by ignoring !. +_escape = re.compile(r'(["\\`])') + +def EncodePOSIXShellArgument(argument): + """Encodes |argument| suitably for consumption by POSIX shells. + + argument may be quoted and escaped as necessary to ensure that POSIX shells + treat the returned value as a literal representing the argument passed to + this function. Parameter (variable) expansions beginning with $ are allowed + to remain intact without escaping the $, to allow the argument to contain + references to variables to be expanded by the shell. + """ + + if not isinstance(argument, str): + argument = str(argument) + + if _quote.search(argument): + quote = '"' + else: + quote = '' + + encoded = quote + re.sub(_escape, r'\\\1', argument) + quote + + return encoded + + +def EncodePOSIXShellList(list): + """Encodes |list| suitably for consumption by POSIX shells. + + Returns EncodePOSIXShellArgument for each item in list, and joins them + together using the space character as an argument separator. + """ + + encoded_arguments = [] + for argument in list: + encoded_arguments.append(EncodePOSIXShellArgument(argument)) + return ' '.join(encoded_arguments) + + +def DeepDependencyTargets(target_dicts, roots): + """Returns the recursive list of target dependencies.""" + dependencies = set() + pending = set(roots) + while pending: + # Pluck out one. + r = pending.pop() + # Skip if visited already. + if r in dependencies: + continue + # Add it. + dependencies.add(r) + # Add its children. + spec = target_dicts[r] + pending.update(set(spec.get('dependencies', []))) + pending.update(set(spec.get('dependencies_original', []))) + return list(dependencies - set(roots)) + + +def BuildFileTargets(target_list, build_file): + """From a target_list, returns the subset from the specified build_file. + """ + return [p for p in target_list if BuildFile(p) == build_file] + + +def AllTargets(target_list, target_dicts, build_file): + """Returns all targets (direct and dependencies) for the specified build_file. + """ + bftargets = BuildFileTargets(target_list, build_file) + deptargets = DeepDependencyTargets(target_dicts, bftargets) + return bftargets + deptargets + + +def WriteOnDiff(filename): + """Write to a file only if the new contents differ. + + Arguments: + filename: name of the file to potentially write to. + Returns: + A file like object which will write to temporary file and only overwrite + the target if it differs (on close). + """ + + class Writer: + """Wrapper around file which only covers the target if it differs.""" + def __init__(self): + # Pick temporary file. + tmp_fd, self.tmp_path = tempfile.mkstemp( + suffix='.tmp', + prefix=os.path.split(filename)[1] + '.gyp.', + dir=os.path.split(filename)[0]) + try: + self.tmp_file = os.fdopen(tmp_fd, 'wb') + except Exception: + # Don't leave turds behind. + os.unlink(self.tmp_path) + raise + + def __getattr__(self, attrname): + # Delegate everything else to self.tmp_file + return getattr(self.tmp_file, attrname) + + def close(self): + try: + # Close tmp file. + self.tmp_file.close() + # Determine if different. + same = False + try: + same = filecmp.cmp(self.tmp_path, filename, False) + except OSError, e: + if e.errno != errno.ENOENT: + raise + + if same: + # The new file is identical to the old one, just get rid of the new + # one. + os.unlink(self.tmp_path) + else: + # The new file is different from the old one, or there is no old one. + # Rename the new file to the permanent name. + # + # tempfile.mkstemp uses an overly restrictive mode, resulting in a + # file that can only be read by the owner, regardless of the umask. + # There's no reason to not respect the umask here, which means that + # an extra hoop is required to fetch it and reset the new file's mode. + # + # No way to get the umask without setting a new one? Set a safe one + # and then set it back to the old value. + umask = os.umask(077) + os.umask(umask) + os.chmod(self.tmp_path, 0666 & ~umask) + if sys.platform == 'win32' and os.path.exists(filename): + # NOTE: on windows (but not cygwin) rename will not replace an + # existing file, so it must be preceded with a remove. Sadly there + # is no way to make the switch atomic. + os.remove(filename) + os.rename(self.tmp_path, filename) + except Exception: + # Don't leave turds behind. + os.unlink(self.tmp_path) + raise + + return Writer() + + +def GetFlavor(params): + """Returns |params.flavor| if it's set, the system's default flavor else.""" + flavors = { + 'cygwin': 'win', + 'win32': 'win', + 'darwin': 'mac', + 'sunos5': 'solaris', + 'freebsd7': 'freebsd', + 'freebsd8': 'freebsd', + 'freebsd9': 'freebsd', + } + flavor = flavors.get(sys.platform, 'linux') + return params.get('flavor', flavor) + + +def CopyTool(flavor, out_path): + """Finds (mac|sun|win)_tool.gyp in the gyp directory and copies it + to |out_path|.""" + prefix = { 'solaris': 'sun', 'mac': 'mac', 'win': 'win' }.get(flavor, None) + if not prefix: + return + + # Slurp input file. + source_path = os.path.join( + os.path.dirname(os.path.abspath(__file__)), '%s_tool.py' % prefix) + with open(source_path) as source_file: + source = source_file.readlines() + + # Add header and write it out. + tool_path = os.path.join(out_path, 'gyp-%s-tool' % prefix) + with open(tool_path, 'w') as tool_file: + tool_file.write( + ''.join([source[0], '# Generated by gyp. Do not edit.\n'] + source[1:])) + + # Make file executable. + os.chmod(tool_path, 0755) + + +# From Alex Martelli, +# http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52560 +# ASPN: Python Cookbook: Remove duplicates from a sequence +# First comment, dated 2001/10/13. +# (Also in the printed Python Cookbook.) + +def uniquer(seq, idfun=None): + if idfun is None: + idfun = lambda x: x + seen = {} + result = [] + for item in seq: + marker = idfun(item) + if marker in seen: continue + seen[marker] = 1 + result.append(item) + return result + + +class CycleError(Exception): + """An exception raised when an unexpected cycle is detected.""" + def __init__(self, nodes): + self.nodes = nodes + def __str__(self): + return 'CycleError: cycle involving: ' + str(self.nodes) + + +def TopologicallySorted(graph, get_edges): + """Topologically sort based on a user provided edge definition. + + Args: + graph: A list of node names. + get_edges: A function mapping from node name to a hashable collection + of node names which this node has outgoing edges to. + Returns: + A list containing all of the node in graph in topological order. + It is assumed that calling get_edges once for each node and caching is + cheaper than repeatedly calling get_edges. + Raises: + CycleError in the event of a cycle. + Example: + graph = {'a': '$(b) $(c)', 'b': 'hi', 'c': '$(b)'} + def GetEdges(node): + return re.findall(r'\$\(([^))]\)', graph[node]) + print TopologicallySorted(graph.keys(), GetEdges) + ==> + ['a', 'c', b'] + """ + get_edges = memoize(get_edges) + visited = set() + visiting = set() + ordered_nodes = [] + def Visit(node): + if node in visiting: + raise CycleError(visiting) + if node in visited: + return + visited.add(node) + visiting.add(node) + for neighbor in get_edges(node): + Visit(neighbor) + visiting.remove(node) + ordered_nodes.insert(0, node) + for node in sorted(graph): + Visit(node) + return ordered_nodes diff --git a/node-v0.8.14/tools/gyp/pylib/gyp/common_test.py b/node-v0.8.14/tools/gyp/pylib/gyp/common_test.py new file mode 100755 index 0000000..aabaf34 --- /dev/null +++ b/node-v0.8.14/tools/gyp/pylib/gyp/common_test.py @@ -0,0 +1,44 @@ +#!/usr/bin/env python + +# Copyright (c) 2012 Google Inc. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +"""Unit tests for the common.py file.""" + +import gyp.common +import unittest + + +class TestTopologicallySorted(unittest.TestCase): + def test_Valid(self): + """Test that sorting works on a valid graph with one possible order.""" + graph = { + 'a': ['b', 'c'], + 'b': [], + 'c': ['d'], + 'd': ['b'], + } + def GetEdge(node): + return tuple(graph[node]) + self.assertEqual( + gyp.common.TopologicallySorted(graph.keys(), GetEdge), + ['a', 'c', 'd', 'b']) + + def test_Cycle(self): + """Test that an exception is thrown on a cyclic graph.""" + graph = { + 'a': ['b'], + 'b': ['c'], + 'c': ['d'], + 'd': ['a'], + } + def GetEdge(node): + return tuple(graph[node]) + self.assertRaises( + gyp.common.CycleError, gyp.common.TopologicallySorted, + graph.keys(), GetEdge) + + +if __name__ == '__main__': + unittest.main() diff --git a/node-v0.8.14/tools/gyp/pylib/gyp/easy_xml.py b/node-v0.8.14/tools/gyp/pylib/gyp/easy_xml.py new file mode 100644 index 0000000..bf949b6 --- /dev/null +++ b/node-v0.8.14/tools/gyp/pylib/gyp/easy_xml.py @@ -0,0 +1,157 @@ +# Copyright (c) 2011 Google Inc. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +import re +import os + + +def XmlToString(content, encoding='utf-8', pretty=False): + """ Writes the XML content to disk, touching the file only if it has changed. + + Visual Studio files have a lot of pre-defined structures. This function makes + it easy to represent these structures as Python data structures, instead of + having to create a lot of function calls. + + Each XML element of the content is represented as a list composed of: + 1. The name of the element, a string, + 2. The attributes of the element, a dictionary (optional), and + 3+. The content of the element, if any. Strings are simple text nodes and + lists are child elements. + + Example 1: + + becomes + ['test'] + + Example 2: + + This is + it! + + + becomes + ['myelement', {'a':'value1', 'b':'value2'}, + ['childtype', 'This is'], + ['childtype', 'it!'], + ] + + Args: + content: The structured content to be converted. + encoding: The encoding to report on the first XML line. + pretty: True if we want pretty printing with indents and new lines. + + Returns: + The XML content as a string. + """ + # We create a huge list of all the elements of the file. + xml_parts = ['' % encoding] + if pretty: + xml_parts.append('\n') + _ConstructContentList(xml_parts, content, pretty) + + # Convert it to a string + return ''.join(xml_parts) + + +def _ConstructContentList(xml_parts, specification, pretty, level=0): + """ Appends the XML parts corresponding to the specification. + + Args: + xml_parts: A list of XML parts to be appended to. + specification: The specification of the element. See EasyXml docs. + pretty: True if we want pretty printing with indents and new lines. + level: Indentation level. + """ + # The first item in a specification is the name of the element. + if pretty: + indentation = ' ' * level + new_line = '\n' + else: + indentation = '' + new_line = '' + name = specification[0] + if not isinstance(name, str): + raise Exception('The first item of an EasyXml specification should be ' + 'a string. Specification was ' + str(specification)) + xml_parts.append(indentation + '<' + name) + + # Optionally in second position is a dictionary of the attributes. + rest = specification[1:] + if rest and isinstance(rest[0], dict): + for at, val in sorted(rest[0].iteritems()): + xml_parts.append(' %s="%s"' % (at, _XmlEscape(val, attr=True))) + rest = rest[1:] + if rest: + xml_parts.append('>') + all_strings = reduce(lambda x, y: x and isinstance(y, str), rest, True) + multi_line = not all_strings + if multi_line and new_line: + xml_parts.append(new_line) + for child_spec in rest: + # If it's a string, append a text node. + # Otherwise recurse over that child definition + if isinstance(child_spec, str): + xml_parts.append(_XmlEscape(child_spec)) + else: + _ConstructContentList(xml_parts, child_spec, pretty, level + 1) + if multi_line and indentation: + xml_parts.append(indentation) + xml_parts.append('%s' % (name, new_line)) + else: + xml_parts.append('/>%s' % new_line) + + +def WriteXmlIfChanged(content, path, encoding='utf-8', pretty=False, + win32=False): + """ Writes the XML content to disk, touching the file only if it has changed. + + Args: + content: The structured content to be written. + path: Location of the file. + encoding: The encoding to report on the first line of the XML file. + pretty: True if we want pretty printing with indents and new lines. + """ + xml_string = XmlToString(content, encoding, pretty) + if win32 and os.linesep != '\r\n': + xml_string = xml_string.replace('\n', '\r\n') + + # Get the old content + try: + f = open(path, 'r') + existing = f.read() + f.close() + except: + existing = None + + # It has changed, write it + if existing != xml_string: + f = open(path, 'w') + f.write(xml_string) + f.close() + + +_xml_escape_map = { + '"': '"', + "'": ''', + '<': '<', + '>': '>', + '&': '&', + '\n': ' ', + '\r': ' ', +} + + +_xml_escape_re = re.compile( + "(%s)" % "|".join(map(re.escape, _xml_escape_map.keys()))) + + +def _XmlEscape(value, attr=False): + """ Escape a string for inclusion in XML.""" + def replace(match): + m = match.string[match.start() : match.end()] + # don't replace single quotes in attrs + if attr and m == "'": + return m + return _xml_escape_map[m] + return _xml_escape_re.sub(replace, value) diff --git a/node-v0.8.14/tools/gyp/pylib/gyp/easy_xml_test.py b/node-v0.8.14/tools/gyp/pylib/gyp/easy_xml_test.py new file mode 100755 index 0000000..df64354 --- /dev/null +++ b/node-v0.8.14/tools/gyp/pylib/gyp/easy_xml_test.py @@ -0,0 +1,103 @@ +#!/usr/bin/env python + +# Copyright (c) 2011 Google Inc. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +""" Unit tests for the easy_xml.py file. """ + +import gyp.easy_xml as easy_xml +import unittest +import StringIO + + +class TestSequenceFunctions(unittest.TestCase): + + def setUp(self): + self.stderr = StringIO.StringIO() + + def test_EasyXml_simple(self): + self.assertEqual( + easy_xml.XmlToString(['test']), + '') + + self.assertEqual( + easy_xml.XmlToString(['test'], encoding='Windows-1252'), + '') + + def test_EasyXml_simple_with_attributes(self): + self.assertEqual( + easy_xml.XmlToString(['test2', {'a': 'value1', 'b': 'value2'}]), + '') + + def test_EasyXml_escaping(self): + original = '\'"\r&\nfoo' + converted = '<test>\'" & foo' + converted_apos = converted.replace("'", ''') + self.assertEqual( + easy_xml.XmlToString(['test3', {'a': original}, original]), + '%s' % + (converted, converted_apos)) + + def test_EasyXml_pretty(self): + self.assertEqual( + easy_xml.XmlToString( + ['test3', + ['GrandParent', + ['Parent1', + ['Child'] + ], + ['Parent2'] + ] + ], + pretty=True), + '\n' + '\n' + ' \n' + ' \n' + ' \n' + ' \n' + ' \n' + ' \n' + '\n') + + + def test_EasyXml_complex(self): + # We want to create: + target = ( + '' + '' + '' + '{D2250C20-3A94-4FB9-AF73-11BC5B73884B}' + 'Win32Proj' + 'automated_ui_tests' + '' + '' + '' + 'Application' + 'Unicode' + '' + '') + + xml = easy_xml.XmlToString( + ['Project', + ['PropertyGroup', {'Label': 'Globals'}, + ['ProjectGuid', '{D2250C20-3A94-4FB9-AF73-11BC5B73884B}'], + ['Keyword', 'Win32Proj'], + ['RootNamespace', 'automated_ui_tests'] + ], + ['Import', {'Project': '$(VCTargetsPath)\\Microsoft.Cpp.props'}], + ['PropertyGroup', + {'Condition': "'$(Configuration)|$(Platform)'=='Debug|Win32'", + 'Label': 'Configuration'}, + ['ConfigurationType', 'Application'], + ['CharacterSet', 'Unicode'] + ] + ]) + self.assertEqual(xml, target) + + +if __name__ == '__main__': + unittest.main() diff --git a/node-v0.8.14/tools/gyp/pylib/gyp/generator/__init__.py b/node-v0.8.14/tools/gyp/pylib/gyp/generator/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/node-v0.8.14/tools/gyp/pylib/gyp/generator/android.py b/node-v0.8.14/tools/gyp/pylib/gyp/generator/android.py new file mode 100644 index 0000000..0cecf7a --- /dev/null +++ b/node-v0.8.14/tools/gyp/pylib/gyp/generator/android.py @@ -0,0 +1,1077 @@ +# Copyright (c) 2012 Google Inc. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +# Notes: +# +# This generates makefiles suitable for inclusion into the Android build system +# via an Android.mk file. It is based on make.py, the standard makefile +# generator. +# +# The code below generates a separate .mk file for each target, but +# all are sourced by the top-level GypAndroid.mk. This means that all +# variables in .mk-files clobber one another, and furthermore that any +# variables set potentially clash with other Android build system variables. +# Try to avoid setting global variables where possible. + +import gyp +import gyp.common +import gyp.generator.make as make # Reuse global functions from make backend. +import os +import re + +generator_default_variables = { + 'OS': 'android', + 'EXECUTABLE_PREFIX': '', + 'EXECUTABLE_SUFFIX': '', + 'STATIC_LIB_PREFIX': 'lib', + 'SHARED_LIB_PREFIX': 'lib', + 'STATIC_LIB_SUFFIX': '.a', + 'SHARED_LIB_SUFFIX': '.so', + 'INTERMEDIATE_DIR': '$(gyp_intermediate_dir)', + 'SHARED_INTERMEDIATE_DIR': '$(gyp_shared_intermediate_dir)', + 'PRODUCT_DIR': '$(gyp_shared_intermediate_dir)', + 'SHARED_LIB_DIR': '$(builddir)/lib.$(TOOLSET)', + 'LIB_DIR': '$(obj).$(TOOLSET)', + 'RULE_INPUT_ROOT': '%(INPUT_ROOT)s', # This gets expanded by Python. + 'RULE_INPUT_DIRNAME': '%(INPUT_DIRNAME)s', # This gets expanded by Python. + 'RULE_INPUT_PATH': '$(RULE_SOURCES)', + 'RULE_INPUT_EXT': '$(suffix $<)', + 'RULE_INPUT_NAME': '$(notdir $<)', +} + +# Make supports multiple toolsets +generator_supports_multiple_toolsets = True + + +SHARED_FOOTER = """\ +# "gyp_all_modules" is a concatenation of the "gyp_all_modules" targets from +# all the included sub-makefiles. This is just here to clarify. +gyp_all_modules: +""" + +header = """\ +# This file is generated by gyp; do not edit. + +""" + +android_standard_include_paths = set([ + # JNI_H_INCLUDE in build/core/binary.mk + 'dalvik/libnativehelper/include/nativehelper', + # from SRC_HEADERS in build/core/config.mk + 'system/core/include', + 'hardware/libhardware/include', + 'hardware/libhardware_legacy/include', + 'hardware/ril/include', + 'dalvik/libnativehelper/include', + 'frameworks/native/include', + 'frameworks/native/opengl/include', + 'frameworks/base/include', + 'frameworks/base/opengl/include', + 'frameworks/base/native/include', + 'external/skia/include', + # TARGET_C_INCLUDES in build/core/combo/TARGET_linux-arm.mk + 'bionic/libc/arch-arm/include', + 'bionic/libc/include', + 'bionic/libstdc++/include', + 'bionic/libc/kernel/common', + 'bionic/libc/kernel/arch-arm', + 'bionic/libm/include', + 'bionic/libm/include/arm', + 'bionic/libthread_db/include', + ]) + + +# Map gyp target types to Android module classes. +MODULE_CLASSES = { + 'static_library': 'STATIC_LIBRARIES', + 'shared_library': 'SHARED_LIBRARIES', + 'executable': 'EXECUTABLES', +} + + +def IsCPPExtension(ext): + return make.COMPILABLE_EXTENSIONS.get(ext) == 'cxx' + + +def Sourceify(path): + """Convert a path to its source directory form. The Android backend does not + support options.generator_output, so this function is a noop.""" + return path + + +# Map from qualified target to path to output. +# For Android, the target of these maps is a tuple ('static', 'modulename'), +# ('dynamic', 'modulename'), or ('path', 'some/path') instead of a string, +# since we link by module. +target_outputs = {} +# Map from qualified target to any linkable output. A subset +# of target_outputs. E.g. when mybinary depends on liba, we want to +# include liba in the linker line; when otherbinary depends on +# mybinary, we just want to build mybinary first. +target_link_deps = {} + + +class AndroidMkWriter(object): + """AndroidMkWriter packages up the writing of one target-specific Android.mk. + + Its only real entry point is Write(), and is mostly used for namespacing. + """ + + def __init__(self, android_top_dir): + self.android_top_dir = android_top_dir + + def Write(self, qualified_target, base_path, output_filename, spec, configs, + part_of_all): + """The main entry point: writes a .mk file for a single target. + + Arguments: + qualified_target: target we're generating + base_path: path relative to source root we're building in, used to resolve + target-relative paths + output_filename: output .mk file name to write + spec, configs: gyp info + part_of_all: flag indicating this target is part of 'all' + """ + make.ensure_directory_exists(output_filename) + + self.fp = open(output_filename, 'w') + + self.fp.write(header) + + self.qualified_target = qualified_target + self.path = base_path + self.target = spec['target_name'] + self.type = spec['type'] + self.toolset = spec['toolset'] + + deps, link_deps = self.ComputeDeps(spec) + + # Some of the generation below can add extra output, sources, or + # link dependencies. All of the out params of the functions that + # follow use names like extra_foo. + extra_outputs = [] + extra_sources = [] + + self.android_class = MODULE_CLASSES.get(self.type, 'NONE') + self.android_module = self.ComputeAndroidModule(spec) + (self.android_stem, self.android_suffix) = self.ComputeOutputParts(spec) + self.output = self.output_binary = self.ComputeOutput(spec) + + # Standard header. + self.WriteLn('include $(CLEAR_VARS)\n') + + # Module class and name. + self.WriteLn('LOCAL_MODULE_CLASS := ' + self.android_class) + self.WriteLn('LOCAL_MODULE := ' + self.android_module) + # Only emit LOCAL_MODULE_STEM if it's different to LOCAL_MODULE. + # The library module classes fail if the stem is set. ComputeOutputParts + # makes sure that stem == modulename in these cases. + if self.android_stem != self.android_module: + self.WriteLn('LOCAL_MODULE_STEM := ' + self.android_stem) + self.WriteLn('LOCAL_MODULE_SUFFIX := ' + self.android_suffix) + self.WriteLn('LOCAL_MODULE_TAGS := optional') + if self.toolset == 'host': + self.WriteLn('LOCAL_IS_HOST_MODULE := true') + + # Grab output directories; needed for Actions and Rules. + self.WriteLn('gyp_intermediate_dir := $(call local-intermediates-dir)') + self.WriteLn('gyp_shared_intermediate_dir := ' + '$(call intermediates-dir-for,GYP,shared)') + self.WriteLn() + + # List files this target depends on so that actions/rules/copies/sources + # can depend on the list. + # TODO: doesn't pull in things through transitive link deps; needed? + target_dependencies = [x[1] for x in deps if x[0] == 'path'] + self.WriteLn('# Make sure our deps are built first.') + self.WriteList(target_dependencies, 'GYP_TARGET_DEPENDENCIES', + local_pathify=True) + + # Actions must come first, since they can generate more OBJs for use below. + if 'actions' in spec: + self.WriteActions(spec['actions'], extra_sources, extra_outputs) + + # Rules must be early like actions. + if 'rules' in spec: + self.WriteRules(spec['rules'], extra_sources, extra_outputs) + + if 'copies' in spec: + self.WriteCopies(spec['copies'], extra_outputs) + + # GYP generated outputs. + self.WriteList(extra_outputs, 'GYP_GENERATED_OUTPUTS', local_pathify=True) + + # Set LOCAL_ADDITIONAL_DEPENDENCIES so that Android's build rules depend + # on both our dependency targets and our generated files. + self.WriteLn('# Make sure our deps and generated files are built first.') + self.WriteLn('LOCAL_ADDITIONAL_DEPENDENCIES := $(GYP_TARGET_DEPENDENCIES) ' + '$(GYP_GENERATED_OUTPUTS)') + self.WriteLn() + + # Sources. + if spec.get('sources', []) or extra_sources: + self.WriteSources(spec, configs, extra_sources) + + self.WriteTarget(spec, configs, deps, link_deps, part_of_all) + + # Update global list of target outputs, used in dependency tracking. + target_outputs[qualified_target] = ('path', self.output_binary) + + # Update global list of link dependencies. + if self.type == 'static_library': + target_link_deps[qualified_target] = ('static', self.android_module) + elif self.type == 'shared_library': + target_link_deps[qualified_target] = ('shared', self.android_module) + + self.fp.close() + return self.android_module + + + def WriteActions(self, actions, extra_sources, extra_outputs): + """Write Makefile code for any 'actions' from the gyp input. + + extra_sources: a list that will be filled in with newly generated source + files, if any + extra_outputs: a list that will be filled in with any outputs of these + actions (used to make other pieces dependent on these + actions) + """ + for action in actions: + name = make.StringToMakefileVariable('%s_%s' % (self.qualified_target, + action['action_name'])) + self.WriteLn('### Rules for action "%s":' % action['action_name']) + inputs = action['inputs'] + outputs = action['outputs'] + + # Build up a list of outputs. + # Collect the output dirs we'll need. + dirs = set() + for out in outputs: + if not out.startswith('$'): + print ('WARNING: Action for target "%s" writes output to local path ' + '"%s".' % (self.target, out)) + dir = os.path.split(out)[0] + if dir: + dirs.add(dir) + if int(action.get('process_outputs_as_sources', False)): + extra_sources += outputs + + # Prepare the actual command. + command = gyp.common.EncodePOSIXShellList(action['action']) + if 'message' in action: + quiet_cmd = 'Gyp action: %s ($@)' % action['message'] + else: + quiet_cmd = 'Gyp action: %s ($@)' % name + if len(dirs) > 0: + command = 'mkdir -p %s' % ' '.join(dirs) + '; ' + command + + cd_action = 'cd $(gyp_local_path)/%s; ' % self.path + command = cd_action + command + + # The makefile rules are all relative to the top dir, but the gyp actions + # are defined relative to their containing dir. This replaces the gyp_* + # variables for the action rule with an absolute version so that the + # output goes in the right place. + # Only write the gyp_* rules for the "primary" output (:1); + # it's superfluous for the "extra outputs", and this avoids accidentally + # writing duplicate dummy rules for those outputs. + main_output = make.QuoteSpaces(self.LocalPathify(outputs[0])) + self.WriteLn('%s: gyp_local_path := $(LOCAL_PATH)' % main_output) + self.WriteLn('%s: gyp_intermediate_dir := ' + '$(GYP_ABS_ANDROID_TOP_DIR)/$(gyp_intermediate_dir)' % + main_output) + self.WriteLn('%s: gyp_shared_intermediate_dir := ' + '$(GYP_ABS_ANDROID_TOP_DIR)/$(gyp_shared_intermediate_dir)' % + main_output) + + for input in inputs: + assert ' ' not in input, ( + "Spaces in action input filenames not supported (%s)" % input) + for output in outputs: + assert ' ' not in output, ( + "Spaces in action output filenames not supported (%s)" % output) + + self.WriteLn('%s: %s $(GYP_TARGET_DEPENDENCIES)' % + (main_output, ' '.join(map(self.LocalPathify, inputs)))) + self.WriteLn('\t@echo "%s"' % quiet_cmd) + self.WriteLn('\t$(hide)%s\n' % command) + for output in outputs[1:]: + # Make each output depend on the main output, with an empty command + # to force make to notice that the mtime has changed. + self.WriteLn('%s: %s ;' % (self.LocalPathify(output), main_output)) + + extra_outputs += outputs + self.WriteLn() + + self.WriteLn() + + + def WriteRules(self, rules, extra_sources, extra_outputs): + """Write Makefile code for any 'rules' from the gyp input. + + extra_sources: a list that will be filled in with newly generated source + files, if any + extra_outputs: a list that will be filled in with any outputs of these + rules (used to make other pieces dependent on these rules) + """ + if len(rules) == 0: + return + rule_trigger = '%s_rule_trigger' % self.android_module + + did_write_rule = False + for rule in rules: + if len(rule.get('rule_sources', [])) == 0: + continue + did_write_rule = True + name = make.StringToMakefileVariable('%s_%s' % (self.qualified_target, + rule['rule_name'])) + self.WriteLn('\n### Generated for rule "%s":' % name) + self.WriteLn('# "%s":' % rule) + + inputs = rule.get('inputs') + for rule_source in rule.get('rule_sources', []): + (rule_source_dirname, rule_source_basename) = os.path.split(rule_source) + (rule_source_root, rule_source_ext) = \ + os.path.splitext(rule_source_basename) + + outputs = [self.ExpandInputRoot(out, rule_source_root, + rule_source_dirname) + for out in rule['outputs']] + + dirs = set() + for out in outputs: + if not out.startswith('$'): + print ('WARNING: Rule for target %s writes output to local path %s' + % (self.target, out)) + dir = os.path.dirname(out) + if dir: + dirs.add(dir) + extra_outputs += outputs + if int(rule.get('process_outputs_as_sources', False)): + extra_sources.extend(outputs) + + components = [] + for component in rule['action']: + component = self.ExpandInputRoot(component, rule_source_root, + rule_source_dirname) + if '$(RULE_SOURCES)' in component: + component = component.replace('$(RULE_SOURCES)', + rule_source) + components.append(component) + + command = gyp.common.EncodePOSIXShellList(components) + cd_action = 'cd $(gyp_local_path)/%s; ' % self.path + command = cd_action + command + if dirs: + command = 'mkdir -p %s' % ' '.join(dirs) + '; ' + command + + # We set up a rule to build the first output, and then set up + # a rule for each additional output to depend on the first. + outputs = map(self.LocalPathify, outputs) + main_output = outputs[0] + self.WriteLn('%s: gyp_local_path := $(LOCAL_PATH)' % main_output) + self.WriteLn('%s: gyp_intermediate_dir := ' + '$(GYP_ABS_ANDROID_TOP_DIR)/$(gyp_intermediate_dir)' + % main_output) + self.WriteLn('%s: gyp_shared_intermediate_dir := ' + '$(GYP_ABS_ANDROID_TOP_DIR)/$(gyp_shared_intermediate_dir)' + % main_output) + + main_output_deps = self.LocalPathify(rule_source) + if inputs: + main_output_deps += ' ' + main_output_deps += ' '.join([self.LocalPathify(f) for f in inputs]) + + self.WriteLn('%s: %s $(GYP_TARGET_DEPENDENCIES)' % + (main_output, main_output_deps)) + self.WriteLn('\t%s\n' % command) + for output in outputs[1:]: + self.WriteLn('%s: %s' % (output, main_output)) + self.WriteLn('.PHONY: %s' % (rule_trigger)) + self.WriteLn('%s: %s' % (rule_trigger, main_output)) + self.WriteLn('') + if did_write_rule: + extra_sources.append(rule_trigger) # Force all rules to run. + self.WriteLn('### Finished generating for all rules') + self.WriteLn('') + + + def WriteCopies(self, copies, extra_outputs): + """Write Makefile code for any 'copies' from the gyp input. + + extra_outputs: a list that will be filled in with any outputs of this action + (used to make other pieces dependent on this action) + """ + self.WriteLn('### Generated for copy rule.') + + variable = make.StringToMakefileVariable(self.qualified_target + '_copies') + outputs = [] + for copy in copies: + for path in copy['files']: + # The Android build system does not allow generation of files into the + # source tree. The destination should start with a variable, which will + # typically be $(gyp_intermediate_dir) or + # $(gyp_shared_intermediate_dir). Note that we can't use an assertion + # because some of the gyp tests depend on this. + if not copy['destination'].startswith('$'): + print ('WARNING: Copy rule for target %s writes output to ' + 'local path %s' % (self.target, copy['destination'])) + + # LocalPathify() calls normpath, stripping trailing slashes. + path = Sourceify(self.LocalPathify(path)) + filename = os.path.split(path)[1] + output = Sourceify(self.LocalPathify(os.path.join(copy['destination'], + filename))) + + self.WriteLn('%s: %s $(GYP_TARGET_DEPENDENCIES) | $(ACP)' % + (output, path)) + self.WriteLn('\t@echo Copying: $@') + self.WriteLn('\t$(hide) mkdir -p $(dir $@)') + self.WriteLn('\t$(hide) $(ACP) -r $< $@') + self.WriteLn() + outputs.append(output) + self.WriteLn('%s = %s' % (variable, + ' '.join(map(make.QuoteSpaces, outputs)))) + extra_outputs.append('$(%s)' % variable) + self.WriteLn() + + + def WriteSourceFlags(self, spec, configs): + """Write out the flags and include paths used to compile source files for + the current target. + + Args: + spec, configs: input from gyp. + """ + config = configs[spec['default_configuration']] + extracted_includes = [] + + self.WriteLn('\n# Flags passed to both C and C++ files.') + cflags, includes_from_cflags = self.ExtractIncludesFromCFlags( + config.get('cflags')) + extracted_includes.extend(includes_from_cflags) + self.WriteList(cflags, 'MY_CFLAGS') + + cflags_c, includes_from_cflags_c = self.ExtractIncludesFromCFlags( + config.get('cflags_c')) + extracted_includes.extend(includes_from_cflags_c) + self.WriteList(cflags_c, 'MY_CFLAGS_C') + + self.WriteList(config.get('defines'), 'MY_DEFS', prefix='-D', + quoter=make.EscapeCppDefine) + self.WriteLn('LOCAL_CFLAGS := $(MY_CFLAGS_C) $(MY_CFLAGS) $(MY_DEFS)') + + # Undefine ANDROID for host modules + # TODO: the source code should not use macro ANDROID to tell if it's host or + # target module. + if self.toolset == 'host': + self.WriteLn('# Undefine ANDROID for host modules') + self.WriteLn('LOCAL_CFLAGS += -UANDROID') + + self.WriteLn('\n# Include paths placed before CFLAGS/CPPFLAGS') + includes = list(config.get('include_dirs', [])) + includes.extend(extracted_includes) + includes = map(Sourceify, map(self.LocalPathify, includes)) + includes = self.NormalizeIncludePaths(includes) + self.WriteList(includes, 'LOCAL_C_INCLUDES') + self.WriteLn('LOCAL_C_INCLUDES := $(GYP_COPIED_SOURCE_ORIGIN_DIRS) ' + '$(LOCAL_C_INCLUDES)') + + self.WriteLn('\n# Flags passed to only C++ (and not C) files.') + self.WriteList(config.get('cflags_cc'), 'LOCAL_CPPFLAGS') + + + def WriteSources(self, spec, configs, extra_sources): + """Write Makefile code for any 'sources' from the gyp input. + These are source files necessary to build the current target. + We need to handle shared_intermediate directory source files as + a special case by copying them to the intermediate directory and + treating them as a genereated sources. Otherwise the Android build + rules won't pick them up. + + Args: + spec, configs: input from gyp. + extra_sources: Sources generated from Actions or Rules. + """ + sources = filter(make.Compilable, spec.get('sources', [])) + generated_not_sources = [x for x in extra_sources if not make.Compilable(x)] + extra_sources = filter(make.Compilable, extra_sources) + + # Determine and output the C++ extension used by these sources. + # We simply find the first C++ file and use that extension. + all_sources = sources + extra_sources + local_cpp_extension = '.cpp' + for source in all_sources: + (root, ext) = os.path.splitext(source) + if IsCPPExtension(ext): + local_cpp_extension = ext + break + if local_cpp_extension != '.cpp': + self.WriteLn('LOCAL_CPP_EXTENSION := %s' % local_cpp_extension) + + # We need to move any non-generated sources that are coming from the + # shared intermediate directory out of LOCAL_SRC_FILES and put them + # into LOCAL_GENERATED_SOURCES. We also need to move over any C++ files + # that don't match our local_cpp_extension, since Android will only + # generate Makefile rules for a single LOCAL_CPP_EXTENSION. + local_files = [] + for source in sources: + (root, ext) = os.path.splitext(source) + if '$(gyp_shared_intermediate_dir)' in source: + extra_sources.append(source) + elif '$(gyp_intermediate_dir)' in source: + extra_sources.append(source) + elif IsCPPExtension(ext) and ext != local_cpp_extension: + extra_sources.append(source) + else: + local_files.append(os.path.normpath(os.path.join(self.path, source))) + + # For any generated source, if it is coming from the shared intermediate + # directory then we add a Make rule to copy them to the local intermediate + # directory first. This is because the Android LOCAL_GENERATED_SOURCES + # must be in the local module intermediate directory for the compile rules + # to work properly. If the file has the wrong C++ extension, then we add + # a rule to copy that to intermediates and use the new version. + final_generated_sources = [] + # If a source file gets copied, we still need to add the orginal source + # directory as header search path, for GCC searches headers in the + # directory that contains the source file by default. + origin_src_dirs = [] + for source in extra_sources: + local_file = source + if not '$(gyp_intermediate_dir)/' in local_file: + basename = os.path.basename(local_file) + local_file = '$(gyp_intermediate_dir)/' + basename + (root, ext) = os.path.splitext(local_file) + if IsCPPExtension(ext) and ext != local_cpp_extension: + local_file = root + local_cpp_extension + if local_file != source: + self.WriteLn('%s: %s' % (local_file, self.LocalPathify(source))) + self.WriteLn('\tmkdir -p $(@D); cp $< $@') + origin_src_dirs.append(os.path.dirname(source)) + final_generated_sources.append(local_file) + + # We add back in all of the non-compilable stuff to make sure that the + # make rules have dependencies on them. + final_generated_sources.extend(generated_not_sources) + self.WriteList(final_generated_sources, 'LOCAL_GENERATED_SOURCES') + + origin_src_dirs = gyp.common.uniquer(origin_src_dirs) + origin_src_dirs = map(Sourceify, map(self.LocalPathify, origin_src_dirs)) + self.WriteList(origin_src_dirs, 'GYP_COPIED_SOURCE_ORIGIN_DIRS') + + self.WriteList(local_files, 'LOCAL_SRC_FILES') + + # Write out the flags used to compile the source; this must be done last + # so that GYP_COPIED_SOURCE_ORIGIN_DIRS can be used as an include path. + self.WriteSourceFlags(spec, configs) + + + def ComputeAndroidModule(self, spec): + """Return the Android module name used for a gyp spec. + + We use the complete qualified target name to avoid collisions between + duplicate targets in different directories. We also add a suffix to + distinguish gyp-generated module names. + """ + + if self.type == 'shared_library': + # For reasons of convention, the Android build system requires that all + # shared library modules are named 'libfoo' when generating -l flags. + prefix = 'lib_' + else: + prefix = '' + + if spec['toolset'] == 'host': + suffix = '_host_gyp' + else: + suffix = '_gyp' + + if self.path: + name = '%s%s_%s%s' % (prefix, self.path, self.target, suffix) + else: + name = '%s%s%s' % (prefix, self.target, suffix) + + return make.StringToMakefileVariable(name) + + + def ComputeOutputParts(self, spec): + """Return the 'output basename' of a gyp spec, split into filename + ext. + + Android libraries must be named the same thing as their module name, + otherwise the linker can't find them, so product_name and so on must be + ignored if we are building a library, and the "lib" prepending is + not done for Android. + """ + assert self.type != 'loadable_module' # TODO: not supported? + + target = spec['target_name'] + target_prefix = '' + target_ext = '' + if self.type == 'static_library': + target = self.ComputeAndroidModule(spec) + target_ext = '.a' + elif self.type == 'shared_library': + target = self.ComputeAndroidModule(spec) + target_ext = '.so' + elif self.type == 'none': + target_ext = '.stamp' + elif self.type != 'executable': + print ("ERROR: What output file should be generated?", + "type", self.type, "target", target) + + if self.type != 'static_library' and self.type != 'shared_library': + target_prefix = spec.get('product_prefix', target_prefix) + target = spec.get('product_name', target) + product_ext = spec.get('product_extension') + if product_ext: + target_ext = '.' + product_ext + + target_stem = target_prefix + target + return (target_stem, target_ext) + + + def ComputeOutputBasename(self, spec): + """Return the 'output basename' of a gyp spec. + + E.g., the loadable module 'foobar' in directory 'baz' will produce + 'libfoobar.so' + """ + return ''.join(self.ComputeOutputParts(spec)) + + + def ComputeOutput(self, spec): + """Return the 'output' (full output path) of a gyp spec. + + E.g., the loadable module 'foobar' in directory 'baz' will produce + '$(obj)/baz/libfoobar.so' + """ + if self.type == 'executable' and self.toolset == 'host': + # We install host executables into shared_intermediate_dir so they can be + # run by gyp rules that refer to PRODUCT_DIR. + path = '$(gyp_shared_intermediate_dir)' + elif self.type == 'shared_library': + if self.toolset == 'host': + path = '$(HOST_OUT_INTERMEDIATE_LIBRARIES)' + else: + path = '$(TARGET_OUT_INTERMEDIATE_LIBRARIES)' + else: + # Other targets just get built into their intermediate dir. + if self.toolset == 'host': + path = '$(call intermediates-dir-for,%s,%s,true)' % (self.android_class, + self.android_module) + else: + path = '$(call intermediates-dir-for,%s,%s)' % (self.android_class, + self.android_module) + + assert spec.get('product_dir') is None # TODO: not supported? + return os.path.join(path, self.ComputeOutputBasename(spec)) + + + def NormalizeLdFlags(self, ld_flags): + """ Clean up ldflags from gyp file. + Remove any ldflags that contain android_top_dir. + + Args: + ld_flags: ldflags from gyp files. + + Returns: + clean ldflags + """ + clean_ldflags = [] + for flag in ld_flags: + if self.android_top_dir in flag: + continue + clean_ldflags.append(flag) + return clean_ldflags + + def NormalizeIncludePaths(self, include_paths): + """ Normalize include_paths. + Convert absolute paths to relative to the Android top directory; + filter out include paths that are already brought in by the Android build + system. + + Args: + include_paths: A list of unprocessed include paths. + Returns: + A list of normalized include paths. + """ + normalized = [] + for path in include_paths: + if path[0] == '/': + path = gyp.common.RelativePath(path, self.android_top_dir) + + # Filter out the Android standard search path. + if path not in android_standard_include_paths: + normalized.append(path) + return normalized + + def ExtractIncludesFromCFlags(self, cflags): + """Extract includes "-I..." out from cflags + + Args: + cflags: A list of compiler flags, which may be mixed with "-I.." + Returns: + A tuple of lists: (clean_clfags, include_paths). "-I.." is trimmed. + """ + clean_cflags = [] + include_paths = [] + if cflags: + for flag in cflags: + if flag.startswith('-I'): + include_paths.append(flag[2:]) + else: + clean_cflags.append(flag) + + return (clean_cflags, include_paths) + + def ComputeAndroidLibraryModuleNames(self, libraries): + """Compute the Android module names from libraries, ie spec.get('libraries') + + Args: + libraries: the value of spec.get('libraries') + Returns: + A tuple (static_lib_modules, dynamic_lib_modules) + """ + static_lib_modules = [] + dynamic_lib_modules = [] + for libs in libraries: + # Libs can have multiple words. + for lib in libs.split(): + # Filter the system libraries, which are added by default by the Android + # build system. + if (lib == '-lc' or lib == '-lstdc++' or lib == '-lm' or + lib.endswith('libgcc.a')): + continue + match = re.search(r'([^/]+)\.a$', lib) + if match: + static_lib_modules.append(match.group(1)) + continue + match = re.search(r'([^/]+)\.so$', lib) + if match: + dynamic_lib_modules.append(match.group(1)) + continue + # "-lstlport" -> libstlport + if lib.startswith('-l'): + if lib.endswith('_static'): + static_lib_modules.append('lib' + lib[2:]) + else: + dynamic_lib_modules.append('lib' + lib[2:]) + return (static_lib_modules, dynamic_lib_modules) + + + def ComputeDeps(self, spec): + """Compute the dependencies of a gyp spec. + + Returns a tuple (deps, link_deps), where each is a list of + filenames that will need to be put in front of make for either + building (deps) or linking (link_deps). + """ + deps = [] + link_deps = [] + if 'dependencies' in spec: + deps.extend([target_outputs[dep] for dep in spec['dependencies'] + if target_outputs[dep]]) + for dep in spec['dependencies']: + if dep in target_link_deps: + link_deps.append(target_link_deps[dep]) + deps.extend(link_deps) + return (gyp.common.uniquer(deps), gyp.common.uniquer(link_deps)) + + + def WriteTargetFlags(self, spec, configs, link_deps): + """Write Makefile code to specify the link flags and library dependencies. + + spec, configs: input from gyp. + link_deps: link dependency list; see ComputeDeps() + """ + config = configs[spec['default_configuration']] + + # LDFLAGS + ldflags = list(config.get('ldflags', [])) + static_flags, dynamic_flags = self.ComputeAndroidLibraryModuleNames( + ldflags) + self.WriteLn('') + self.WriteList(self.NormalizeLdFlags(ldflags), 'LOCAL_LDFLAGS') + + # Libraries (i.e. -lfoo) + libraries = gyp.common.uniquer(spec.get('libraries', [])) + static_libs, dynamic_libs = self.ComputeAndroidLibraryModuleNames( + libraries) + + # Link dependencies (i.e. libfoo.a, libfoo.so) + static_link_deps = [x[1] for x in link_deps if x[0] == 'static'] + shared_link_deps = [x[1] for x in link_deps if x[0] == 'shared'] + self.WriteLn('') + self.WriteList(static_flags + static_libs + static_link_deps, + 'LOCAL_STATIC_LIBRARIES') + self.WriteLn('# Enable grouping to fix circular references') + self.WriteLn('LOCAL_GROUP_STATIC_LIBRARIES := true') + self.WriteLn('') + self.WriteList(dynamic_flags + dynamic_libs + shared_link_deps, + 'LOCAL_SHARED_LIBRARIES') + + + def WriteTarget(self, spec, configs, deps, link_deps, part_of_all): + """Write Makefile code to produce the final target of the gyp spec. + + spec, configs: input from gyp. + deps, link_deps: dependency lists; see ComputeDeps() + part_of_all: flag indicating this target is part of 'all' + """ + self.WriteLn('### Rules for final target.') + + if self.type != 'none': + self.WriteTargetFlags(spec, configs, link_deps) + + # Add to the set of targets which represent the gyp 'all' target. We use the + # name 'gyp_all_modules' as the Android build system doesn't allow the use + # of the Make target 'all' and because 'all_modules' is the equivalent of + # the Make target 'all' on Android. + if part_of_all: + self.WriteLn('# Add target alias to "gyp_all_modules" target.') + self.WriteLn('.PHONY: gyp_all_modules') + self.WriteLn('gyp_all_modules: %s' % self.android_module) + self.WriteLn('') + + # Add an alias from the gyp target name to the Android module name. This + # simplifies manual builds of the target, and is required by the test + # framework. + self.WriteLn('# Alias gyp target name.') + self.WriteLn('.PHONY: %s' % self.target) + self.WriteLn('%s: %s' % (self.target, self.android_module)) + self.WriteLn('') + + # Add the command to trigger build of the target type depending + # on the toolset. Ex: BUILD_STATIC_LIBRARY vs. BUILD_HOST_STATIC_LIBRARY + # NOTE: This has to come last! + modifier = '' + if self.toolset == 'host': + modifier = 'HOST_' + if self.type == 'static_library': + self.WriteLn('include $(BUILD_%sSTATIC_LIBRARY)' % modifier) + elif self.type == 'shared_library': + self.WriteLn('LOCAL_PRELINK_MODULE := false') + self.WriteLn('include $(BUILD_%sSHARED_LIBRARY)' % modifier) + elif self.type == 'executable': + if self.toolset == 'host': + self.WriteLn('LOCAL_MODULE_PATH := $(gyp_shared_intermediate_dir)') + else: + # Don't install target executables for now, as it results in them being + # included in ROM. This can be revisited if there's a reason to install + # them later. + self.WriteLn('LOCAL_UNINSTALLABLE_MODULE := true') + self.WriteLn('include $(BUILD_%sEXECUTABLE)' % modifier) + else: + self.WriteLn('LOCAL_MODULE_PATH := $(PRODUCT_OUT)/gyp_stamp') + self.WriteLn('LOCAL_UNINSTALLABLE_MODULE := true') + self.WriteLn() + self.WriteLn('include $(BUILD_SYSTEM)/base_rules.mk') + self.WriteLn() + self.WriteLn('$(LOCAL_BUILT_MODULE): $(LOCAL_ADDITIONAL_DEPENDENCIES)') + self.WriteLn('\t$(hide) echo "Gyp timestamp: $@"') + self.WriteLn('\t$(hide) mkdir -p $(dir $@)') + self.WriteLn('\t$(hide) touch $@') + + + def WriteList(self, value_list, variable=None, prefix='', + quoter=make.QuoteIfNecessary, local_pathify=False): + """Write a variable definition that is a list of values. + + E.g. WriteList(['a','b'], 'foo', prefix='blah') writes out + foo = blaha blahb + but in a pretty-printed style. + """ + values = '' + if value_list: + value_list = [quoter(prefix + l) for l in value_list] + if local_pathify: + value_list = [self.LocalPathify(l) for l in value_list] + values = ' \\\n\t' + ' \\\n\t'.join(value_list) + self.fp.write('%s :=%s\n\n' % (variable, values)) + + + def WriteLn(self, text=''): + self.fp.write(text + '\n') + + + def LocalPathify(self, path): + """Convert a subdirectory-relative path into a normalized path which starts + with the make variable $(LOCAL_PATH) (i.e. the top of the project tree). + Absolute paths, or paths that contain variables, are just normalized.""" + if '$(' in path or os.path.isabs(path): + # path is not a file in the project tree in this case, but calling + # normpath is still important for trimming trailing slashes. + return os.path.normpath(path) + local_path = os.path.join('$(LOCAL_PATH)', self.path, path) + local_path = os.path.normpath(local_path) + # Check that normalizing the path didn't ../ itself out of $(LOCAL_PATH) + # - i.e. that the resulting path is still inside the project tree. The + # path may legitimately have ended up containing just $(LOCAL_PATH), though, + # so we don't look for a slash. + assert local_path.startswith('$(LOCAL_PATH)'), ( + 'Path %s attempts to escape from gyp path %s !)' % (path, self.path)) + return local_path + + + def ExpandInputRoot(self, template, expansion, dirname): + if '%(INPUT_ROOT)s' not in template and '%(INPUT_DIRNAME)s' not in template: + return template + path = template % { + 'INPUT_ROOT': expansion, + 'INPUT_DIRNAME': dirname, + } + return path + + +def WriteAutoRegenerationRule(params, root_makefile, makefile_name, + build_files): + """Write the target to regenerate the Makefile.""" + options = params['options'] + # Sort to avoid non-functional changes to makefile. + build_files = sorted([os.path.join('$(LOCAL_PATH)', f) for f in build_files]) + build_files_args = [gyp.common.RelativePath(filename, options.toplevel_dir) + for filename in params['build_files_arg']] + build_files_args = [os.path.join('$(PRIVATE_LOCAL_PATH)', f) + for f in build_files_args] + gyp_binary = gyp.common.FixIfRelativePath(params['gyp_binary'], + options.toplevel_dir) + makefile_path = os.path.join('$(LOCAL_PATH)', makefile_name) + if not gyp_binary.startswith(os.sep): + gyp_binary = os.path.join('.', gyp_binary) + root_makefile.write('GYP_FILES := \\\n %s\n\n' % + '\\\n '.join(map(Sourceify, build_files))) + root_makefile.write('%s: PRIVATE_LOCAL_PATH := $(LOCAL_PATH)\n' % + makefile_path) + root_makefile.write('%s: $(GYP_FILES)\n' % makefile_path) + root_makefile.write('\techo ACTION Regenerating $@\n\t%s\n\n' % + gyp.common.EncodePOSIXShellList([gyp_binary, '-fandroid'] + + gyp.RegenerateFlags(options) + + build_files_args)) + + +def GenerateOutput(target_list, target_dicts, data, params): + options = params['options'] + generator_flags = params.get('generator_flags', {}) + builddir_name = generator_flags.get('output_dir', 'out') + limit_to_target_all = generator_flags.get('limit_to_target_all', False) + android_top_dir = os.environ.get('ANDROID_BUILD_TOP') + assert android_top_dir, '$ANDROID_BUILD_TOP not set; you need to run lunch.' + + def CalculateMakefilePath(build_file, base_name): + """Determine where to write a Makefile for a given gyp file.""" + # Paths in gyp files are relative to the .gyp file, but we want + # paths relative to the source root for the master makefile. Grab + # the path of the .gyp file as the base to relativize against. + # E.g. "foo/bar" when we're constructing targets for "foo/bar/baz.gyp". + base_path = gyp.common.RelativePath(os.path.dirname(build_file), + options.depth) + # We write the file in the base_path directory. + output_file = os.path.join(options.depth, base_path, base_name) + assert not options.generator_output, ( + 'The Android backend does not support options.generator_output.') + base_path = gyp.common.RelativePath(os.path.dirname(build_file), + options.toplevel_dir) + return base_path, output_file + + # TODO: search for the first non-'Default' target. This can go + # away when we add verification that all targets have the + # necessary configurations. + default_configuration = None + toolsets = set([target_dicts[target]['toolset'] for target in target_list]) + for target in target_list: + spec = target_dicts[target] + if spec['default_configuration'] != 'Default': + default_configuration = spec['default_configuration'] + break + if not default_configuration: + default_configuration = 'Default' + + srcdir = '.' + makefile_name = 'GypAndroid.mk' + options.suffix + makefile_path = os.path.join(options.toplevel_dir, makefile_name) + assert not options.generator_output, ( + 'The Android backend does not support options.generator_output.') + make.ensure_directory_exists(makefile_path) + root_makefile = open(makefile_path, 'w') + + root_makefile.write(header) + + # We set LOCAL_PATH just once, here, to the top of the project tree. This + # allows all the other paths we use to be relative to the Android.mk file, + # as the Android build system expects. + root_makefile.write('\nLOCAL_PATH := $(call my-dir)\n') + + # Find the list of targets that derive from the gyp file(s) being built. + needed_targets = set() + for build_file in params['build_files']: + for target in gyp.common.AllTargets(target_list, target_dicts, build_file): + needed_targets.add(target) + + build_files = set() + include_list = set() + android_modules = {} + for qualified_target in target_list: + build_file, target, toolset = gyp.common.ParseQualifiedTarget( + qualified_target) + build_files.add(gyp.common.RelativePath(build_file, options.toplevel_dir)) + included_files = data[build_file]['included_files'] + for included_file in included_files: + # The included_files entries are relative to the dir of the build file + # that included them, so we have to undo that and then make them relative + # to the root dir. + relative_include_file = gyp.common.RelativePath( + gyp.common.UnrelativePath(included_file, build_file), + options.toplevel_dir) + abs_include_file = os.path.abspath(relative_include_file) + # If the include file is from the ~/.gyp dir, we should use absolute path + # so that relocating the src dir doesn't break the path. + if (params['home_dot_gyp'] and + abs_include_file.startswith(params['home_dot_gyp'])): + build_files.add(abs_include_file) + else: + build_files.add(relative_include_file) + + base_path, output_file = CalculateMakefilePath(build_file, + target + '.' + toolset + options.suffix + '.mk') + + spec = target_dicts[qualified_target] + configs = spec['configurations'] + + part_of_all = (qualified_target in needed_targets and + not int(spec.get('suppress_wildcard', False))) + if limit_to_target_all and not part_of_all: + continue + writer = AndroidMkWriter(android_top_dir) + android_module = writer.Write(qualified_target, base_path, output_file, + spec, configs, part_of_all=part_of_all) + if android_module in android_modules: + print ('ERROR: Android module names must be unique. The following ' + 'targets both generate Android module name %s.\n %s\n %s' % + (android_module, android_modules[android_module], + qualified_target)) + return + android_modules[android_module] = qualified_target + + # Our root_makefile lives at the source root. Compute the relative path + # from there to the output_file for including. + mkfile_rel_path = gyp.common.RelativePath(output_file, + os.path.dirname(makefile_path)) + include_list.add(mkfile_rel_path) + + # Some tools need to know the absolute path of the top directory. + root_makefile.write('GYP_ABS_ANDROID_TOP_DIR := $(shell pwd)\n') + + # Write out the sorted list of includes. + root_makefile.write('\n') + for include_file in sorted(include_list): + root_makefile.write('include $(LOCAL_PATH)/' + include_file + '\n') + root_makefile.write('\n') + + if generator_flags.get('auto_regeneration', True): + WriteAutoRegenerationRule(params, root_makefile, makefile_name, build_files) + + root_makefile.write(SHARED_FOOTER) + + root_makefile.close() diff --git a/node-v0.8.14/tools/gyp/pylib/gyp/generator/dump_dependency_json.py b/node-v0.8.14/tools/gyp/pylib/gyp/generator/dump_dependency_json.py new file mode 100644 index 0000000..acee72e --- /dev/null +++ b/node-v0.8.14/tools/gyp/pylib/gyp/generator/dump_dependency_json.py @@ -0,0 +1,66 @@ +# Copyright (c) 2011 Google Inc. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +import collections +import gyp +import gyp.common +import json +import sys + +generator_supports_multiple_toolsets = True + +generator_wants_static_library_dependencies_adjusted = False + +generator_default_variables = { +} +for dirname in ['INTERMEDIATE_DIR', 'SHARED_INTERMEDIATE_DIR', 'PRODUCT_DIR', + 'LIB_DIR', 'SHARED_LIB_DIR']: + # Some gyp steps fail if these are empty(!). + generator_default_variables[dirname] = 'dir' +for unused in ['RULE_INPUT_PATH', 'RULE_INPUT_ROOT', 'RULE_INPUT_NAME', + 'RULE_INPUT_DIRNAME', 'RULE_INPUT_EXT', + 'EXECUTABLE_PREFIX', 'EXECUTABLE_SUFFIX', + 'STATIC_LIB_PREFIX', 'STATIC_LIB_SUFFIX', + 'SHARED_LIB_PREFIX', 'SHARED_LIB_SUFFIX']: + generator_default_variables[unused] = '' + + +def CalculateVariables(default_variables, params): + generator_flags = params.get('generator_flags', {}) + for key, val in generator_flags.items(): + default_variables.setdefault(key, val) + default_variables.setdefault('OS', gyp.common.GetFlavor(params)) + + +def CalculateGeneratorInputInfo(params): + """Calculate the generator specific info that gets fed to input (called by + gyp).""" + generator_flags = params.get('generator_flags', {}) + if generator_flags.get('adjust_static_libraries', False): + global generator_wants_static_library_dependencies_adjusted + generator_wants_static_library_dependencies_adjusted = True + + +def GenerateOutput(target_list, target_dicts, data, params): + # Map of target -> list of targets it depends on. + edges = {} + + # Queue of targets to visit. + targets_to_visit = target_list[:] + + while len(targets_to_visit) > 0: + target = targets_to_visit.pop() + if target in edges: + continue + edges[target] = [] + + for dep in target_dicts[target].get('dependencies', []): + edges[target].append(dep) + targets_to_visit.append(dep) + + filename = 'dump.json' + f = open(filename, 'w') + json.dump(edges, f) + f.close() + print 'Wrote json to %s.' % filename diff --git a/node-v0.8.14/tools/gyp/pylib/gyp/generator/eclipse.py b/node-v0.8.14/tools/gyp/pylib/gyp/generator/eclipse.py new file mode 100644 index 0000000..0f90b5e --- /dev/null +++ b/node-v0.8.14/tools/gyp/pylib/gyp/generator/eclipse.py @@ -0,0 +1,273 @@ +# Copyright (c) 2012 Google Inc. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +"""GYP backend that generates Eclipse CDT settings files. + +This backend DOES NOT generate Eclipse CDT projects. Instead, it generates XML +files that can be imported into an Eclipse CDT project. The XML file contains a +list of include paths and symbols (i.e. defines). + +Because a full .cproject definition is not created by this generator, it's not +possible to properly define the include dirs and symbols for each file +individually. Instead, one set of includes/symbols is generated for the entire +project. This works fairly well (and is a vast improvement in general), but may +still result in a few indexer issues here and there. + +This generator has no automated tests, so expect it to be broken. +""" + +from xml.sax.saxutils import escape +import os.path +import subprocess +import gyp +import gyp.common +import shlex + +generator_wants_static_library_dependencies_adjusted = False + +generator_default_variables = { +} + +for dirname in ['INTERMEDIATE_DIR', 'PRODUCT_DIR', 'LIB_DIR', 'SHARED_LIB_DIR']: + # Some gyp steps fail if these are empty(!). + generator_default_variables[dirname] = 'dir' + +for unused in ['RULE_INPUT_PATH', 'RULE_INPUT_ROOT', 'RULE_INPUT_NAME', + 'RULE_INPUT_DIRNAME', 'RULE_INPUT_EXT', + 'EXECUTABLE_PREFIX', 'EXECUTABLE_SUFFIX', + 'STATIC_LIB_PREFIX', 'STATIC_LIB_SUFFIX', + 'SHARED_LIB_PREFIX', 'SHARED_LIB_SUFFIX', + 'CONFIGURATION_NAME']: + generator_default_variables[unused] = '' + +# Include dirs will occasionaly use the SHARED_INTERMEDIATE_DIR variable as +# part of the path when dealing with generated headers. This value will be +# replaced dynamically for each configuration. +generator_default_variables['SHARED_INTERMEDIATE_DIR'] = \ + '$SHARED_INTERMEDIATES_DIR' + + +def CalculateVariables(default_variables, params): + generator_flags = params.get('generator_flags', {}) + for key, val in generator_flags.items(): + default_variables.setdefault(key, val) + default_variables.setdefault('OS', gyp.common.GetFlavor(params)) + + +def CalculateGeneratorInputInfo(params): + """Calculate the generator specific info that gets fed to input (called by + gyp).""" + generator_flags = params.get('generator_flags', {}) + if generator_flags.get('adjust_static_libraries', False): + global generator_wants_static_library_dependencies_adjusted + generator_wants_static_library_dependencies_adjusted = True + + +def GetAllIncludeDirectories(target_list, target_dicts, + shared_intermediates_dir, config_name): + """Calculate the set of include directories to be used. + + Returns: + A list including all the include_dir's specified for every target followed + by any include directories that were added as cflag compiler options. + """ + + gyp_includes_set = set() + compiler_includes_list = [] + + for target_name in target_list: + target = target_dicts[target_name] + if config_name in target['configurations']: + config = target['configurations'][config_name] + + # Look for any include dirs that were explicitly added via cflags. This + # may be done in gyp files to force certain includes to come at the end. + # TODO(jgreenwald): Change the gyp files to not abuse cflags for this, and + # remove this. + cflags = config['cflags'] + for cflag in cflags: + include_dir = '' + if cflag.startswith('-I'): + include_dir = cflag[2:] + if include_dir and not include_dir in compiler_includes_list: + compiler_includes_list.append(include_dir) + + # Find standard gyp include dirs. + if config.has_key('include_dirs'): + include_dirs = config['include_dirs'] + for include_dir in include_dirs: + include_dir = include_dir.replace('$SHARED_INTERMEDIATES_DIR', + shared_intermediates_dir) + if not os.path.isabs(include_dir): + base_dir = os.path.dirname(target_name) + + include_dir = base_dir + '/' + include_dir + include_dir = os.path.abspath(include_dir) + + if not include_dir in gyp_includes_set: + gyp_includes_set.add(include_dir) + + + # Generate a list that has all the include dirs. + all_includes_list = list(gyp_includes_set) + all_includes_list.sort() + for compiler_include in compiler_includes_list: + if not compiler_include in gyp_includes_set: + all_includes_list.append(compiler_include) + + # All done. + return all_includes_list + + +def GetCompilerPath(target_list, target_dicts, data): + """Determine a command that can be used to invoke the compiler. + + Returns: + If this is a gyp project that has explicit make settings, try to determine + the compiler from that. Otherwise, see if a compiler was specified via the + CC_target environment variable. + """ + + # First, see if the compiler is configured in make's settings. + build_file, _, _ = gyp.common.ParseQualifiedTarget(target_list[0]) + make_global_settings_dict = data[build_file].get('make_global_settings', {}) + for key, value in make_global_settings_dict: + if key in ['CC', 'CXX']: + return value + + # Check to see if the compiler was specified as an environment variable. + for key in ['CC_target', 'CC', 'CXX']: + compiler = os.environ.get(key) + if compiler: + return compiler + + return 'gcc' + + +def GetAllDefines(target_list, target_dicts, data, config_name): + """Calculate the defines for a project. + + Returns: + A dict that includes explict defines declared in gyp files along with all of + the default defines that the compiler uses. + """ + + # Get defines declared in the gyp files. + all_defines = {} + for target_name in target_list: + target = target_dicts[target_name] + + if config_name in target['configurations']: + config = target['configurations'][config_name] + for define in config['defines']: + split_define = define.split('=', 1) + if len(split_define) == 1: + split_define.append('1') + if split_define[0].strip() in all_defines: + # Already defined + continue + + all_defines[split_define[0].strip()] = split_define[1].strip() + + # Get default compiler defines (if possible). + cc_target = GetCompilerPath(target_list, target_dicts, data) + if cc_target: + command = shlex.split(cc_target) + command.extend(['-E', '-dM', '-']) + cpp_proc = subprocess.Popen(args=command, cwd='.', + stdin=subprocess.PIPE, stdout=subprocess.PIPE) + cpp_output = cpp_proc.communicate()[0] + cpp_lines = cpp_output.split('\n') + for cpp_line in cpp_lines: + if not cpp_line.strip(): + continue + cpp_line_parts = cpp_line.split(' ', 2) + key = cpp_line_parts[1] + if len(cpp_line_parts) >= 3: + val = cpp_line_parts[2] + else: + val = '1' + all_defines[key] = val + + return all_defines + + +def WriteIncludePaths(out, eclipse_langs, include_dirs): + """Write the includes section of a CDT settings export file.""" + + out.write('
\n') + out.write(' \n') + for lang in eclipse_langs: + out.write(' \n' % lang) + for include_dir in include_dirs: + out.write(' %s\n' % + include_dir) + out.write(' \n') + out.write('
\n') + + +def WriteMacros(out, eclipse_langs, defines): + """Write the macros section of a CDT settings export file.""" + + out.write('
\n') + out.write(' \n') + for lang in eclipse_langs: + out.write(' \n' % lang) + for key in sorted(defines.iterkeys()): + out.write(' %s%s\n' % + (escape(key), escape(defines[key]))) + out.write(' \n') + out.write('
\n') + + +def GenerateOutputForConfig(target_list, target_dicts, data, params, + config_name): + options = params['options'] + generator_flags = params.get('generator_flags', {}) + + # build_dir: relative path from source root to our output files. + # e.g. "out/Debug" + build_dir = os.path.join(generator_flags.get('output_dir', 'out'), + config_name) + + toplevel_build = os.path.join(options.toplevel_dir, build_dir) + shared_intermediate_dir = os.path.join(toplevel_build, 'obj', 'gen') + + if not os.path.exists(toplevel_build): + os.makedirs(toplevel_build) + out = open(os.path.join(toplevel_build, 'eclipse-cdt-settings.xml'), 'w') + + out.write('\n') + out.write('\n') + + eclipse_langs = ['C++ Source File', 'C Source File', 'Assembly Source File', + 'GNU C++', 'GNU C', 'Assembly'] + include_dirs = GetAllIncludeDirectories(target_list, target_dicts, + shared_intermediate_dir, config_name) + WriteIncludePaths(out, eclipse_langs, include_dirs) + defines = GetAllDefines(target_list, target_dicts, data, config_name) + WriteMacros(out, eclipse_langs, defines) + + out.write('\n') + out.close() + + +def GenerateOutput(target_list, target_dicts, data, params): + """Generate an XML settings file that can be imported into a CDT project.""" + + if params['options'].generator_output: + raise NotImplementedError, "--generator_output not implemented for eclipse" + + user_config = params.get('generator_flags', {}).get('config', None) + if user_config: + GenerateOutputForConfig(target_list, target_dicts, data, params, + user_config) + else: + config_names = target_dicts[target_list[0]]['configurations'].keys() + for config_name in config_names: + GenerateOutputForConfig(target_list, target_dicts, data, params, + config_name) + diff --git a/node-v0.8.14/tools/gyp/pylib/gyp/generator/gypd.py b/node-v0.8.14/tools/gyp/pylib/gyp/generator/gypd.py new file mode 100644 index 0000000..22ef57f --- /dev/null +++ b/node-v0.8.14/tools/gyp/pylib/gyp/generator/gypd.py @@ -0,0 +1,87 @@ +# Copyright (c) 2011 Google Inc. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +"""gypd output module + +This module produces gyp input as its output. Output files are given the +.gypd extension to avoid overwriting the .gyp files that they are generated +from. Internal references to .gyp files (such as those found in +"dependencies" sections) are not adjusted to point to .gypd files instead; +unlike other paths, which are relative to the .gyp or .gypd file, such paths +are relative to the directory from which gyp was run to create the .gypd file. + +This generator module is intended to be a sample and a debugging aid, hence +the "d" for "debug" in .gypd. It is useful to inspect the results of the +various merges, expansions, and conditional evaluations performed by gyp +and to see a representation of what would be fed to a generator module. + +It's not advisable to rename .gypd files produced by this module to .gyp, +because they will have all merges, expansions, and evaluations already +performed and the relevant constructs not present in the output; paths to +dependencies may be wrong; and various sections that do not belong in .gyp +files such as such as "included_files" and "*_excluded" will be present. +Output will also be stripped of comments. This is not intended to be a +general-purpose gyp pretty-printer; for that, you probably just want to +run "pprint.pprint(eval(open('source.gyp').read()))", which will still strip +comments but won't do all of the other things done to this module's output. + +The specific formatting of the output generated by this module is subject +to change. +""" + + +import gyp.common +import errno +import os +import pprint + + +# These variables should just be spit back out as variable references. +_generator_identity_variables = [ + 'EXECUTABLE_PREFIX', + 'EXECUTABLE_SUFFIX', + 'INTERMEDIATE_DIR', + 'PRODUCT_DIR', + 'RULE_INPUT_ROOT', + 'RULE_INPUT_DIRNAME', + 'RULE_INPUT_EXT', + 'RULE_INPUT_NAME', + 'RULE_INPUT_PATH', + 'SHARED_INTERMEDIATE_DIR', +] + +# gypd doesn't define a default value for OS like many other generator +# modules. Specify "-D OS=whatever" on the command line to provide a value. +generator_default_variables = { +} + +# gypd supports multiple toolsets +generator_supports_multiple_toolsets = True + +# TODO(mark): This always uses <, which isn't right. The input module should +# notify the generator to tell it which phase it is operating in, and this +# module should use < for the early phase and then switch to > for the late +# phase. Bonus points for carrying @ back into the output too. +for v in _generator_identity_variables: + generator_default_variables[v] = '<(%s)' % v + + +def GenerateOutput(target_list, target_dicts, data, params): + output_files = {} + for qualified_target in target_list: + [input_file, target] = \ + gyp.common.ParseQualifiedTarget(qualified_target)[0:2] + + if input_file[-4:] != '.gyp': + continue + input_file_stem = input_file[:-4] + output_file = input_file_stem + params['options'].suffix + '.gypd' + + if not output_file in output_files: + output_files[output_file] = input_file + + for output_file, input_file in output_files.iteritems(): + output = open(output_file, 'w') + pprint.pprint(data[input_file], output) + output.close() diff --git a/node-v0.8.14/tools/gyp/pylib/gyp/generator/gypsh.py b/node-v0.8.14/tools/gyp/pylib/gyp/generator/gypsh.py new file mode 100644 index 0000000..bd405f4 --- /dev/null +++ b/node-v0.8.14/tools/gyp/pylib/gyp/generator/gypsh.py @@ -0,0 +1,56 @@ +# Copyright (c) 2011 Google Inc. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +"""gypsh output module + +gypsh is a GYP shell. It's not really a generator per se. All it does is +fire up an interactive Python session with a few local variables set to the +variables passed to the generator. Like gypd, it's intended as a debugging +aid, to facilitate the exploration of .gyp structures after being processed +by the input module. + +The expected usage is "gyp -f gypsh -D OS=desired_os". +""" + + +import code +import sys + + +# All of this stuff about generator variables was lovingly ripped from gypd.py. +# That module has a much better description of what's going on and why. +_generator_identity_variables = [ + 'EXECUTABLE_PREFIX', + 'EXECUTABLE_SUFFIX', + 'INTERMEDIATE_DIR', + 'PRODUCT_DIR', + 'RULE_INPUT_ROOT', + 'RULE_INPUT_DIRNAME', + 'RULE_INPUT_EXT', + 'RULE_INPUT_NAME', + 'RULE_INPUT_PATH', + 'SHARED_INTERMEDIATE_DIR', +] + +generator_default_variables = { +} + +for v in _generator_identity_variables: + generator_default_variables[v] = '<(%s)' % v + + +def GenerateOutput(target_list, target_dicts, data, params): + locals = { + 'target_list': target_list, + 'target_dicts': target_dicts, + 'data': data, + } + + # Use a banner that looks like the stock Python one and like what + # code.interact uses by default, but tack on something to indicate what + # locals are available, and identify gypsh. + banner='Python %s on %s\nlocals.keys() = %s\ngypsh' % \ + (sys.version, sys.platform, repr(sorted(locals.keys()))) + + code.interact(banner, local=locals) diff --git a/node-v0.8.14/tools/gyp/pylib/gyp/generator/make.py b/node-v0.8.14/tools/gyp/pylib/gyp/generator/make.py new file mode 100644 index 0000000..4648bd9 --- /dev/null +++ b/node-v0.8.14/tools/gyp/pylib/gyp/generator/make.py @@ -0,0 +1,2145 @@ +# Copyright (c) 2012 Google Inc. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +# Notes: +# +# This is all roughly based on the Makefile system used by the Linux +# kernel, but is a non-recursive make -- we put the entire dependency +# graph in front of make and let it figure it out. +# +# The code below generates a separate .mk file for each target, but +# all are sourced by the top-level Makefile. This means that all +# variables in .mk-files clobber one another. Be careful to use := +# where appropriate for immediate evaluation, and similarly to watch +# that you're not relying on a variable value to last beween different +# .mk files. +# +# TODOs: +# +# Global settings and utility functions are currently stuffed in the +# toplevel Makefile. It may make sense to generate some .mk files on +# the side to keep the the files readable. + +import os +import re +import sys +import gyp +import gyp.common +import gyp.system_test +import gyp.xcode_emulation +from gyp.common import GetEnvironFallback + +generator_default_variables = { + 'EXECUTABLE_PREFIX': '', + 'EXECUTABLE_SUFFIX': '', + 'STATIC_LIB_PREFIX': 'lib', + 'SHARED_LIB_PREFIX': 'lib', + 'STATIC_LIB_SUFFIX': '.a', + 'INTERMEDIATE_DIR': '$(obj).$(TOOLSET)/$(TARGET)/geni', + 'SHARED_INTERMEDIATE_DIR': '$(obj)/gen', + 'PRODUCT_DIR': '$(builddir)', + 'RULE_INPUT_ROOT': '%(INPUT_ROOT)s', # This gets expanded by Python. + 'RULE_INPUT_DIRNAME': '%(INPUT_DIRNAME)s', # This gets expanded by Python. + 'RULE_INPUT_PATH': '$(abspath $<)', + 'RULE_INPUT_EXT': '$(suffix $<)', + 'RULE_INPUT_NAME': '$(notdir $<)', + 'CONFIGURATION_NAME': '$(BUILDTYPE)', +} + +# Make supports multiple toolsets +generator_supports_multiple_toolsets = True + +# Request sorted dependencies in the order from dependents to dependencies. +generator_wants_sorted_dependencies = False + +# Placates pylint. +generator_additional_non_configuration_keys = [] +generator_additional_path_sections = [] +generator_extra_sources_for_rules = [] + + +def CalculateVariables(default_variables, params): + """Calculate additional variables for use in the build (called by gyp).""" + flavor = gyp.common.GetFlavor(params) + if flavor == 'mac': + default_variables.setdefault('OS', 'mac') + default_variables.setdefault('SHARED_LIB_SUFFIX', '.dylib') + default_variables.setdefault('SHARED_LIB_DIR', + generator_default_variables['PRODUCT_DIR']) + default_variables.setdefault('LIB_DIR', + generator_default_variables['PRODUCT_DIR']) + + # Copy additional generator configuration data from Xcode, which is shared + # by the Mac Make generator. + import gyp.generator.xcode as xcode_generator + global generator_additional_non_configuration_keys + generator_additional_non_configuration_keys = getattr(xcode_generator, + 'generator_additional_non_configuration_keys', []) + global generator_additional_path_sections + generator_additional_path_sections = getattr(xcode_generator, + 'generator_additional_path_sections', []) + global generator_extra_sources_for_rules + generator_extra_sources_for_rules = getattr(xcode_generator, + 'generator_extra_sources_for_rules', []) + COMPILABLE_EXTENSIONS.update({'.m': 'objc', '.mm' : 'objcxx'}) + else: + operating_system = flavor + if flavor == 'android': + operating_system = 'linux' # Keep this legacy behavior for now. + default_variables.setdefault('OS', operating_system) + default_variables.setdefault('SHARED_LIB_SUFFIX', '.so') + default_variables.setdefault('SHARED_LIB_DIR','$(builddir)/lib.$(TOOLSET)') + default_variables.setdefault('LIB_DIR', '$(obj).$(TOOLSET)') + + +def CalculateGeneratorInputInfo(params): + """Calculate the generator specific info that gets fed to input (called by + gyp).""" + generator_flags = params.get('generator_flags', {}) + android_ndk_version = generator_flags.get('android_ndk_version', None) + # Android NDK requires a strict link order. + if android_ndk_version: + global generator_wants_sorted_dependencies + generator_wants_sorted_dependencies = True + + +def ensure_directory_exists(path): + dir = os.path.dirname(path) + if dir and not os.path.exists(dir): + os.makedirs(dir) + + +# The .d checking code below uses these functions: +# wildcard, sort, foreach, shell, wordlist +# wildcard can handle spaces, the rest can't. +# Since I could find no way to make foreach work with spaces in filenames +# correctly, the .d files have spaces replaced with another character. The .d +# file for +# Chromium\ Framework.framework/foo +# is for example +# out/Release/.deps/out/Release/Chromium?Framework.framework/foo +# This is the replacement character. +SPACE_REPLACEMENT = '?' + + +LINK_COMMANDS_LINUX = """\ +quiet_cmd_alink = AR($(TOOLSET)) $@ +cmd_alink = rm -f $@ && $(AR.$(TOOLSET)) $(ARFLAGS.$(TOOLSET)) $@ $(filter %.o,$^) + +# Due to circular dependencies between libraries :(, we wrap the +# special "figure out circular dependencies" flags around the entire +# input list during linking. +quiet_cmd_link = LINK($(TOOLSET)) $@ +cmd_link = $(LINK.$(TOOLSET)) $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -o $@ -Wl,--start-group $(LD_INPUTS) -Wl,--end-group $(LIBS) + +# We support two kinds of shared objects (.so): +# 1) shared_library, which is just bundling together many dependent libraries +# into a link line. +# 2) loadable_module, which is generating a module intended for dlopen(). +# +# They differ only slightly: +# In the former case, we want to package all dependent code into the .so. +# In the latter case, we want to package just the API exposed by the +# outermost module. +# This means shared_library uses --whole-archive, while loadable_module doesn't. +# (Note that --whole-archive is incompatible with the --start-group used in +# normal linking.) + +# Other shared-object link notes: +# - Set SONAME to the library filename so our binaries don't reference +# the local, absolute paths used on the link command-line. +quiet_cmd_solink = SOLINK($(TOOLSET)) $@ +cmd_solink = $(LINK.$(TOOLSET)) -shared $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -Wl,-soname=$(@F) -o $@ -Wl,--whole-archive $(LD_INPUTS) -Wl,--no-whole-archive $(LIBS) + +quiet_cmd_solink_module = SOLINK_MODULE($(TOOLSET)) $@ +cmd_solink_module = $(LINK.$(TOOLSET)) -shared $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -Wl,-soname=$(@F) -o $@ -Wl,--start-group $(filter-out FORCE_DO_CMD, $^) -Wl,--end-group $(LIBS) +""" + +LINK_COMMANDS_MAC = """\ +quiet_cmd_alink = LIBTOOL-STATIC $@ +cmd_alink = rm -f $@ && ./gyp-mac-tool filter-libtool libtool -static -o $@ $(filter %.o,$^) + +quiet_cmd_link = LINK($(TOOLSET)) $@ +cmd_link = $(LINK.$(TOOLSET)) $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -o "$@" $(LD_INPUTS) $(LIBS) + +# TODO(thakis): Find out and document the difference between shared_library and +# loadable_module on mac. +quiet_cmd_solink = SOLINK($(TOOLSET)) $@ +cmd_solink = $(LINK.$(TOOLSET)) -shared $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -o "$@" $(LD_INPUTS) $(LIBS) + +# TODO(thakis): The solink_module rule is likely wrong. Xcode seems to pass +# -bundle -single_module here (for osmesa.so). +quiet_cmd_solink_module = SOLINK_MODULE($(TOOLSET)) $@ +cmd_solink_module = $(LINK.$(TOOLSET)) -shared $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -o $@ $(filter-out FORCE_DO_CMD, $^) $(LIBS) +""" + +LINK_COMMANDS_ANDROID = """\ +quiet_cmd_alink = AR($(TOOLSET)) $@ +cmd_alink = rm -f $@ && $(AR.$(TOOLSET)) $(ARFLAGS.$(TOOLSET)) $@ $(filter %.o,$^) + +# Due to circular dependencies between libraries :(, we wrap the +# special "figure out circular dependencies" flags around the entire +# input list during linking. +quiet_cmd_link = LINK($(TOOLSET)) $@ +quiet_cmd_link_host = LINK($(TOOLSET)) $@ +cmd_link = $(LINK.$(TOOLSET)) $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -o $@ -Wl,--start-group $(LD_INPUTS) -Wl,--end-group $(LIBS) +cmd_link_host = $(LINK.$(TOOLSET)) $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -o $@ $(LD_INPUTS) $(LIBS) + +# Other shared-object link notes: +# - Set SONAME to the library filename so our binaries don't reference +# the local, absolute paths used on the link command-line. +quiet_cmd_solink = SOLINK($(TOOLSET)) $@ +cmd_solink = $(LINK.$(TOOLSET)) -shared $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -Wl,-soname=$(@F) -o $@ -Wl,--whole-archive $(LD_INPUTS) -Wl,--no-whole-archive $(LIBS) + +quiet_cmd_solink_module = SOLINK_MODULE($(TOOLSET)) $@ +cmd_solink_module = $(LINK.$(TOOLSET)) -shared $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -Wl,-soname=$(@F) -o $@ -Wl,--start-group $(filter-out FORCE_DO_CMD, $^) -Wl,--end-group $(LIBS) +quiet_cmd_solink_module_host = SOLINK_MODULE($(TOOLSET)) $@ +cmd_solink_module_host = $(LINK.$(TOOLSET)) -shared $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -Wl,-soname=$(@F) -o $@ $(filter-out FORCE_DO_CMD, $^) $(LIBS) +""" + + +# Header of toplevel Makefile. +# This should go into the build tree, but it's easier to keep it here for now. +SHARED_HEADER = ("""\ +# We borrow heavily from the kernel build setup, though we are simpler since +# we don't have Kconfig tweaking settings on us. + +# The implicit make rules have it looking for RCS files, among other things. +# We instead explicitly write all the rules we care about. +# It's even quicker (saves ~200ms) to pass -r on the command line. +MAKEFLAGS=-r + +# The source directory tree. +srcdir := %(srcdir)s +abs_srcdir := $(abspath $(srcdir)) + +# The name of the builddir. +builddir_name ?= %(builddir)s + +# The V=1 flag on command line makes us verbosely print command lines. +ifdef V + quiet= +else + quiet=quiet_ +endif + +# Specify BUILDTYPE=Release on the command line for a release build. +BUILDTYPE ?= %(default_configuration)s + +# Directory all our build output goes into. +# Note that this must be two directories beneath src/ for unit tests to pass, +# as they reach into the src/ directory for data with relative paths. +builddir ?= $(builddir_name)/$(BUILDTYPE) +abs_builddir := $(abspath $(builddir)) +depsdir := $(builddir)/.deps + +# Object output directory. +obj := $(builddir)/obj +abs_obj := $(abspath $(obj)) + +# We build up a list of every single one of the targets so we can slurp in the +# generated dependency rule Makefiles in one pass. +all_deps := + +%(make_global_settings)s + +# C++ apps need to be linked with g++. +# +# Note: flock is used to seralize linking. Linking is a memory-intensive +# process so running parallel links can often lead to thrashing. To disable +# the serialization, override LINK via an envrionment variable as follows: +# +# export LINK=g++ +# +# This will allow make to invoke N linker processes as specified in -jN. +LINK ?= %(flock)s $(builddir)/linker.lock $(CXX) + +CC.target ?= %(CC.target)s +CFLAGS.target ?= $(CFLAGS) +CXX.target ?= %(CXX.target)s +CXXFLAGS.target ?= $(CXXFLAGS) +LINK.target ?= %(LINK.target)s +LDFLAGS.target ?= $(LDFLAGS) +AR.target ?= $(AR) +ARFLAGS.target ?= %(ARFLAGS.target)s + +# N.B.: the logic of which commands to run should match the computation done +# in gyp's make.py where ARFLAGS.host etc. is computed. +# TODO(evan): move all cross-compilation logic to gyp-time so we don't need +# to replicate this environment fallback in make as well. +CC.host ?= %(CC.host)s +CFLAGS.host ?= +CXX.host ?= %(CXX.host)s +CXXFLAGS.host ?= +LINK.host ?= %(LINK.host)s +LDFLAGS.host ?= +AR.host ?= %(AR.host)s +ARFLAGS.host := %(ARFLAGS.host)s + +# Define a dir function that can handle spaces. +# http://www.gnu.org/software/make/manual/make.html#Syntax-of-Functions +# "leading spaces cannot appear in the text of the first argument as written. +# These characters can be put into the argument value by variable substitution." +empty := +space := $(empty) $(empty) + +# http://stackoverflow.com/questions/1189781/using-make-dir-or-notdir-on-a-path-with-spaces +replace_spaces = $(subst $(space),""" + SPACE_REPLACEMENT + """,$1) +unreplace_spaces = $(subst """ + SPACE_REPLACEMENT + """,$(space),$1) +dirx = $(call unreplace_spaces,$(dir $(call replace_spaces,$1))) + +# Flags to make gcc output dependency info. Note that you need to be +# careful here to use the flags that ccache and distcc can understand. +# We write to a dep file on the side first and then rename at the end +# so we can't end up with a broken dep file. +depfile = $(depsdir)/$(call replace_spaces,$@).d +DEPFLAGS = -MMD -MF $(depfile).raw + +# We have to fixup the deps output in a few ways. +# (1) the file output should mention the proper .o file. +# ccache or distcc lose the path to the target, so we convert a rule of +# the form: +# foobar.o: DEP1 DEP2 +# into +# path/to/foobar.o: DEP1 DEP2 +# (2) we want missing files not to cause us to fail to build. +# We want to rewrite +# foobar.o: DEP1 DEP2 \\ +# DEP3 +# to +# DEP1: +# DEP2: +# DEP3: +# so if the files are missing, they're just considered phony rules. +# We have to do some pretty insane escaping to get those backslashes +# and dollar signs past make, the shell, and sed at the same time. +# Doesn't work with spaces, but that's fine: .d files have spaces in +# their names replaced with other characters.""" +r""" +define fixup_dep +# The depfile may not exist if the input file didn't have any #includes. +touch $(depfile).raw +# Fixup path as in (1). +sed -e "s|^$(notdir $@)|$@|" $(depfile).raw >> $(depfile) +# Add extra rules as in (2). +# We remove slashes and replace spaces with new lines; +# remove blank lines; +# delete the first line and append a colon to the remaining lines. +sed -e 's|\\||' -e 'y| |\n|' $(depfile).raw |\ + grep -v '^$$' |\ + sed -e 1d -e 's|$$|:|' \ + >> $(depfile) +rm $(depfile).raw +endef +""" +""" +# Command definitions: +# - cmd_foo is the actual command to run; +# - quiet_cmd_foo is the brief-output summary of the command. + +quiet_cmd_cc = CC($(TOOLSET)) $@ +cmd_cc = $(CC.$(TOOLSET)) $(GYP_CFLAGS) $(DEPFLAGS) $(CFLAGS.$(TOOLSET)) -c -o $@ $< + +quiet_cmd_cxx = CXX($(TOOLSET)) $@ +cmd_cxx = $(CXX.$(TOOLSET)) $(GYP_CXXFLAGS) $(DEPFLAGS) $(CXXFLAGS.$(TOOLSET)) -c -o $@ $< +%(extra_commands)s +quiet_cmd_touch = TOUCH $@ +cmd_touch = touch $@ + +quiet_cmd_copy = COPY $@ +# send stderr to /dev/null to ignore messages when linking directories. +cmd_copy = ln -f "$<" "$@" 2>/dev/null || (rm -rf "$@" && cp -af "$<" "$@") + +%(link_commands)s +""" + +r""" +# Define an escape_quotes function to escape single quotes. +# This allows us to handle quotes properly as long as we always use +# use single quotes and escape_quotes. +escape_quotes = $(subst ','\'',$(1)) +# This comment is here just to include a ' to unconfuse syntax highlighting. +# Define an escape_vars function to escape '$' variable syntax. +# This allows us to read/write command lines with shell variables (e.g. +# $LD_LIBRARY_PATH), without triggering make substitution. +escape_vars = $(subst $$,$$$$,$(1)) +# Helper that expands to a shell command to echo a string exactly as it is in +# make. This uses printf instead of echo because printf's behaviour with respect +# to escape sequences is more portable than echo's across different shells +# (e.g., dash, bash). +exact_echo = printf '%%s\n' '$(call escape_quotes,$(1))' +""" +""" +# Helper to compare the command we're about to run against the command +# we logged the last time we ran the command. Produces an empty +# string (false) when the commands match. +# Tricky point: Make has no string-equality test function. +# The kernel uses the following, but it seems like it would have false +# positives, where one string reordered its arguments. +# arg_check = $(strip $(filter-out $(cmd_$(1)), $(cmd_$@)) \\ +# $(filter-out $(cmd_$@), $(cmd_$(1)))) +# We instead substitute each for the empty string into the other, and +# say they're equal if both substitutions produce the empty string. +# .d files contain """ + SPACE_REPLACEMENT + \ + """ instead of spaces, take that into account. +command_changed = $(or $(subst $(cmd_$(1)),,$(cmd_$(call replace_spaces,$@))),\\ + $(subst $(cmd_$(call replace_spaces,$@)),,$(cmd_$(1)))) + +# Helper that is non-empty when a prerequisite changes. +# Normally make does this implicitly, but we force rules to always run +# so we can check their command lines. +# $? -- new prerequisites +# $| -- order-only dependencies +prereq_changed = $(filter-out FORCE_DO_CMD,$(filter-out $|,$?)) + +# Helper that executes all postbuilds, and deletes the output file when done +# if any of the postbuilds failed. +define do_postbuilds + @E=0;\\ + for p in $(POSTBUILDS); do\\ + eval $$p;\\ + F=$$?;\\ + if [ $$F -ne 0 ]; then\\ + E=$$F;\\ + fi;\\ + done;\\ + if [ $$E -ne 0 ]; then\\ + rm -rf "$@";\\ + exit $$E;\\ + fi +endef + +# do_cmd: run a command via the above cmd_foo names, if necessary. +# Should always run for a given target to handle command-line changes. +# Second argument, if non-zero, makes it do asm/C/C++ dependency munging. +# Third argument, if non-zero, makes it do POSTBUILDS processing. +# Note: We intentionally do NOT call dirx for depfile, since it contains """ + \ + SPACE_REPLACEMENT + """ for +# spaces already and dirx strips the """ + SPACE_REPLACEMENT + \ + """ characters. +define do_cmd +$(if $(or $(command_changed),$(prereq_changed)), + @$(call exact_echo, $($(quiet)cmd_$(1))) + @mkdir -p "$(call dirx,$@)" "$(dir $(depfile))" + $(if $(findstring flock,$(word %(flock_index)d,$(cmd_$1))), + @$(cmd_$(1)) + @echo " $(quiet_cmd_$(1)): Finished", + @$(cmd_$(1)) + ) + @$(call exact_echo,$(call escape_vars,cmd_$(call replace_spaces,$@) := $(cmd_$(1)))) > $(depfile) + @$(if $(2),$(fixup_dep)) + $(if $(and $(3), $(POSTBUILDS)), + $(call do_postbuilds) + ) +) +endef + +# Declare the "%(default_target)s" target first so it is the default, +# even though we don't have the deps yet. +.PHONY: %(default_target)s +%(default_target)s: + +# make looks for ways to re-generate included makefiles, but in our case, we +# don't have a direct way. Explicitly telling make that it has nothing to do +# for them makes it go faster. +%%.d: ; + +# Use FORCE_DO_CMD to force a target to run. Should be coupled with +# do_cmd. +.PHONY: FORCE_DO_CMD +FORCE_DO_CMD: + +""") + +SHARED_HEADER_MAC_COMMANDS = """ +quiet_cmd_objc = CXX($(TOOLSET)) $@ +cmd_objc = $(CC.$(TOOLSET)) $(GYP_OBJCFLAGS) $(DEPFLAGS) -c -o $@ $< + +quiet_cmd_objcxx = CXX($(TOOLSET)) $@ +cmd_objcxx = $(CXX.$(TOOLSET)) $(GYP_OBJCXXFLAGS) $(DEPFLAGS) -c -o $@ $< + +# Commands for precompiled header files. +quiet_cmd_pch_c = CXX($(TOOLSET)) $@ +cmd_pch_c = $(CC.$(TOOLSET)) $(GYP_PCH_CFLAGS) $(DEPFLAGS) $(CXXFLAGS.$(TOOLSET)) -c -o $@ $< +quiet_cmd_pch_cc = CXX($(TOOLSET)) $@ +cmd_pch_cc = $(CC.$(TOOLSET)) $(GYP_PCH_CXXFLAGS) $(DEPFLAGS) $(CXXFLAGS.$(TOOLSET)) -c -o $@ $< +quiet_cmd_pch_m = CXX($(TOOLSET)) $@ +cmd_pch_m = $(CC.$(TOOLSET)) $(GYP_PCH_OBJCFLAGS) $(DEPFLAGS) -c -o $@ $< +quiet_cmd_pch_mm = CXX($(TOOLSET)) $@ +cmd_pch_mm = $(CC.$(TOOLSET)) $(GYP_PCH_OBJCXXFLAGS) $(DEPFLAGS) -c -o $@ $< + +# gyp-mac-tool is written next to the root Makefile by gyp. +# Use $(4) for the command, since $(2) and $(3) are used as flag by do_cmd +# already. +quiet_cmd_mac_tool = MACTOOL $(4) $< +cmd_mac_tool = ./gyp-mac-tool $(4) $< "$@" + +quiet_cmd_mac_package_framework = PACKAGE FRAMEWORK $@ +cmd_mac_package_framework = ./gyp-mac-tool package-framework "$@" $(4) + +quiet_cmd_infoplist = INFOPLIST $@ +cmd_infoplist = $(CC.$(TOOLSET)) -E -P -Wno-trigraphs -x c $(INFOPLIST_DEFINES) "$<" -o "$@" +""" + +SHARED_HEADER_SUN_COMMANDS = """ +# gyp-sun-tool is written next to the root Makefile by gyp. +# Use $(4) for the command, since $(2) and $(3) are used as flag by do_cmd +# already. +quiet_cmd_sun_tool = SUNTOOL $(4) $< +cmd_sun_tool = ./gyp-sun-tool $(4) $< "$@" +""" + + +def WriteRootHeaderSuffixRules(writer): + extensions = sorted(COMPILABLE_EXTENSIONS.keys(), key=str.lower) + + writer.write('# Suffix rules, putting all outputs into $(obj).\n') + for ext in extensions: + writer.write('$(obj).$(TOOLSET)/%%.o: $(srcdir)/%%%s FORCE_DO_CMD\n' % ext) + writer.write('\t@$(call do_cmd,%s,1)\n' % COMPILABLE_EXTENSIONS[ext]) + + writer.write('\n# Try building from generated source, too.\n') + for ext in extensions: + writer.write( + '$(obj).$(TOOLSET)/%%.o: $(obj).$(TOOLSET)/%%%s FORCE_DO_CMD\n' % ext) + writer.write('\t@$(call do_cmd,%s,1)\n' % COMPILABLE_EXTENSIONS[ext]) + writer.write('\n') + for ext in extensions: + writer.write('$(obj).$(TOOLSET)/%%.o: $(obj)/%%%s FORCE_DO_CMD\n' % ext) + writer.write('\t@$(call do_cmd,%s,1)\n' % COMPILABLE_EXTENSIONS[ext]) + writer.write('\n') + + +SHARED_HEADER_SUFFIX_RULES_COMMENT1 = ("""\ +# Suffix rules, putting all outputs into $(obj). +""") + + +SHARED_HEADER_SUFFIX_RULES_COMMENT2 = ("""\ +# Try building from generated source, too. +""") + + +SHARED_FOOTER = """\ +# "all" is a concatenation of the "all" targets from all the included +# sub-makefiles. This is just here to clarify. +all: + +# Add in dependency-tracking rules. $(all_deps) is the list of every single +# target in our tree. Only consider the ones with .d (dependency) info: +d_files := $(wildcard $(foreach f,$(all_deps),$(depsdir)/$(f).d)) +ifneq ($(d_files),) + include $(d_files) +endif +""" + +header = """\ +# This file is generated by gyp; do not edit. + +""" + +# Maps every compilable file extension to the do_cmd that compiles it. +COMPILABLE_EXTENSIONS = { + '.c': 'cc', + '.cc': 'cxx', + '.cpp': 'cxx', + '.cxx': 'cxx', + '.s': 'cc', + '.S': 'cc', +} + +def Compilable(filename): + """Return true if the file is compilable (should be in OBJS).""" + for res in (filename.endswith(e) for e in COMPILABLE_EXTENSIONS): + if res: + return True + return False + + +def Linkable(filename): + """Return true if the file is linkable (should be on the link line).""" + return filename.endswith('.o') + + +def Target(filename): + """Translate a compilable filename to its .o target.""" + return os.path.splitext(filename)[0] + '.o' + + +def EscapeShellArgument(s): + """Quotes an argument so that it will be interpreted literally by a POSIX + shell. Taken from + http://stackoverflow.com/questions/35817/whats-the-best-way-to-escape-ossystem-calls-in-python + """ + return "'" + s.replace("'", "'\\''") + "'" + + +def EscapeMakeVariableExpansion(s): + """Make has its own variable expansion syntax using $. We must escape it for + string to be interpreted literally.""" + return s.replace('$', '$$') + + +def EscapeCppDefine(s): + """Escapes a CPP define so that it will reach the compiler unaltered.""" + s = EscapeShellArgument(s) + s = EscapeMakeVariableExpansion(s) + # '#' characters must be escaped even embedded in a string, else Make will + # treat it as the start of a comment. + return s.replace('#', r'\#') + + +def QuoteIfNecessary(string): + """TODO: Should this ideally be replaced with one or more of the above + functions?""" + if '"' in string: + string = '"' + string.replace('"', '\\"') + '"' + return string + + +def StringToMakefileVariable(string): + """Convert a string to a value that is acceptable as a make variable name.""" + return re.sub('[^a-zA-Z0-9_]', '_', string) + + +srcdir_prefix = '' +def Sourceify(path): + """Convert a path to its source directory form.""" + if '$(' in path: + return path + if os.path.isabs(path): + return path + return srcdir_prefix + path + + +def QuoteSpaces(s, quote=r'\ '): + return s.replace(' ', quote) + + +def InvertRelativePath(path): + """Given a relative path like foo/bar, return the inverse relative path: + the path from the relative path back to the origin dir. + + E.g. os.path.normpath(os.path.join(path, InvertRelativePath(path))) + should always produce the empty string.""" + + if not path: + return path + # Only need to handle relative paths into subdirectories for now. + assert '..' not in path, path + depth = len(path.split(os.path.sep)) + return os.path.sep.join(['..'] * depth) + + +# Map from qualified target to path to output. +target_outputs = {} +# Map from qualified target to any linkable output. A subset +# of target_outputs. E.g. when mybinary depends on liba, we want to +# include liba in the linker line; when otherbinary depends on +# mybinary, we just want to build mybinary first. +target_link_deps = {} + + +class MakefileWriter: + """MakefileWriter packages up the writing of one target-specific foobar.mk. + + Its only real entry point is Write(), and is mostly used for namespacing. + """ + + def __init__(self, generator_flags, flavor): + self.generator_flags = generator_flags + self.flavor = flavor + + self.suffix_rules_srcdir = {} + self.suffix_rules_objdir1 = {} + self.suffix_rules_objdir2 = {} + + # Generate suffix rules for all compilable extensions. + for ext in COMPILABLE_EXTENSIONS.keys(): + # Suffix rules for source folder. + self.suffix_rules_srcdir.update({ext: ("""\ +$(obj).$(TOOLSET)/$(TARGET)/%%.o: $(srcdir)/%%%s FORCE_DO_CMD + @$(call do_cmd,%s,1) +""" % (ext, COMPILABLE_EXTENSIONS[ext]))}) + + # Suffix rules for generated source files. + self.suffix_rules_objdir1.update({ext: ("""\ +$(obj).$(TOOLSET)/$(TARGET)/%%.o: $(obj).$(TOOLSET)/%%%s FORCE_DO_CMD + @$(call do_cmd,%s,1) +""" % (ext, COMPILABLE_EXTENSIONS[ext]))}) + self.suffix_rules_objdir2.update({ext: ("""\ +$(obj).$(TOOLSET)/$(TARGET)/%%.o: $(obj)/%%%s FORCE_DO_CMD + @$(call do_cmd,%s,1) +""" % (ext, COMPILABLE_EXTENSIONS[ext]))}) + + + def Write(self, qualified_target, base_path, output_filename, spec, configs, + part_of_all): + """The main entry point: writes a .mk file for a single target. + + Arguments: + qualified_target: target we're generating + base_path: path relative to source root we're building in, used to resolve + target-relative paths + output_filename: output .mk file name to write + spec, configs: gyp info + part_of_all: flag indicating this target is part of 'all' + """ + ensure_directory_exists(output_filename) + + self.fp = open(output_filename, 'w') + + self.fp.write(header) + + self.qualified_target = qualified_target + self.path = base_path + self.target = spec['target_name'] + self.type = spec['type'] + self.toolset = spec['toolset'] + + self.is_mac_bundle = gyp.xcode_emulation.IsMacBundle(self.flavor, spec) + if self.flavor == 'mac': + self.xcode_settings = gyp.xcode_emulation.XcodeSettings(spec) + else: + self.xcode_settings = None + + deps, link_deps = self.ComputeDeps(spec) + + # Some of the generation below can add extra output, sources, or + # link dependencies. All of the out params of the functions that + # follow use names like extra_foo. + extra_outputs = [] + extra_sources = [] + extra_link_deps = [] + extra_mac_bundle_resources = [] + mac_bundle_deps = [] + + if self.is_mac_bundle: + self.output = self.ComputeMacBundleOutput(spec) + self.output_binary = self.ComputeMacBundleBinaryOutput(spec) + else: + self.output = self.output_binary = self.ComputeOutput(spec) + + self._INSTALLABLE_TARGETS = ('executable', 'loadable_module', + 'shared_library') + if self.type in self._INSTALLABLE_TARGETS: + self.alias = os.path.basename(self.output) + install_path = self._InstallableTargetInstallPath() + else: + self.alias = self.output + install_path = self.output + + self.WriteLn("TOOLSET := " + self.toolset) + self.WriteLn("TARGET := " + self.target) + + # Actions must come first, since they can generate more OBJs for use below. + if 'actions' in spec: + self.WriteActions(spec['actions'], extra_sources, extra_outputs, + extra_mac_bundle_resources, part_of_all) + + # Rules must be early like actions. + if 'rules' in spec: + self.WriteRules(spec['rules'], extra_sources, extra_outputs, + extra_mac_bundle_resources, part_of_all) + + if 'copies' in spec: + self.WriteCopies(spec['copies'], extra_outputs, part_of_all) + + # Bundle resources. + if self.is_mac_bundle: + all_mac_bundle_resources = ( + spec.get('mac_bundle_resources', []) + extra_mac_bundle_resources) + self.WriteMacBundleResources(all_mac_bundle_resources, mac_bundle_deps) + self.WriteMacInfoPlist(mac_bundle_deps) + + # Sources. + all_sources = spec.get('sources', []) + extra_sources + if all_sources: + self.WriteSources( + configs, deps, all_sources, extra_outputs, + extra_link_deps, part_of_all, + gyp.xcode_emulation.MacPrefixHeader( + self.xcode_settings, lambda p: Sourceify(self.Absolutify(p)), + self.Pchify)) + sources = filter(Compilable, all_sources) + if sources: + self.WriteLn(SHARED_HEADER_SUFFIX_RULES_COMMENT1) + extensions = set([os.path.splitext(s)[1] for s in sources]) + for ext in extensions: + if ext in self.suffix_rules_srcdir: + self.WriteLn(self.suffix_rules_srcdir[ext]) + self.WriteLn(SHARED_HEADER_SUFFIX_RULES_COMMENT2) + for ext in extensions: + if ext in self.suffix_rules_objdir1: + self.WriteLn(self.suffix_rules_objdir1[ext]) + for ext in extensions: + if ext in self.suffix_rules_objdir2: + self.WriteLn(self.suffix_rules_objdir2[ext]) + self.WriteLn('# End of this set of suffix rules') + + # Add dependency from bundle to bundle binary. + if self.is_mac_bundle: + mac_bundle_deps.append(self.output_binary) + + self.WriteTarget(spec, configs, deps, extra_link_deps + link_deps, + mac_bundle_deps, extra_outputs, part_of_all) + + # Update global list of target outputs, used in dependency tracking. + target_outputs[qualified_target] = install_path + + # Update global list of link dependencies. + if self.type in ('static_library', 'shared_library'): + target_link_deps[qualified_target] = self.output_binary + + # Currently any versions have the same effect, but in future the behavior + # could be different. + if self.generator_flags.get('android_ndk_version', None): + self.WriteAndroidNdkModuleRule(self.target, all_sources, link_deps) + + self.fp.close() + + + def WriteSubMake(self, output_filename, makefile_path, targets, build_dir): + """Write a "sub-project" Makefile. + + This is a small, wrapper Makefile that calls the top-level Makefile to build + the targets from a single gyp file (i.e. a sub-project). + + Arguments: + output_filename: sub-project Makefile name to write + makefile_path: path to the top-level Makefile + targets: list of "all" targets for this sub-project + build_dir: build output directory, relative to the sub-project + """ + ensure_directory_exists(output_filename) + self.fp = open(output_filename, 'w') + self.fp.write(header) + # For consistency with other builders, put sub-project build output in the + # sub-project dir (see test/subdirectory/gyptest-subdir-all.py). + self.WriteLn('export builddir_name ?= %s' % + os.path.join(os.path.dirname(output_filename), build_dir)) + self.WriteLn('.PHONY: all') + self.WriteLn('all:') + if makefile_path: + makefile_path = ' -C ' + makefile_path + self.WriteLn('\t$(MAKE)%s %s' % (makefile_path, ' '.join(targets))) + self.fp.close() + + + def WriteActions(self, actions, extra_sources, extra_outputs, + extra_mac_bundle_resources, part_of_all): + """Write Makefile code for any 'actions' from the gyp input. + + extra_sources: a list that will be filled in with newly generated source + files, if any + extra_outputs: a list that will be filled in with any outputs of these + actions (used to make other pieces dependent on these + actions) + part_of_all: flag indicating this target is part of 'all' + """ + for action in actions: + name = StringToMakefileVariable('%s_%s' % (self.qualified_target, + action['action_name'])) + self.WriteLn('### Rules for action "%s":' % action['action_name']) + inputs = action['inputs'] + outputs = action['outputs'] + + # Build up a list of outputs. + # Collect the output dirs we'll need. + dirs = set() + for out in outputs: + dir = os.path.split(out)[0] + if dir: + dirs.add(dir) + if int(action.get('process_outputs_as_sources', False)): + extra_sources += outputs + if int(action.get('process_outputs_as_mac_bundle_resources', False)): + extra_mac_bundle_resources += outputs + + # Write the actual command. + command = gyp.common.EncodePOSIXShellList(action['action']) + if 'message' in action: + self.WriteLn('quiet_cmd_%s = ACTION %s $@' % (name, action['message'])) + else: + self.WriteLn('quiet_cmd_%s = ACTION %s $@' % (name, name)) + if len(dirs) > 0: + command = 'mkdir -p %s' % ' '.join(dirs) + '; ' + command + + cd_action = 'cd %s; ' % Sourceify(self.path or '.') + + # command and cd_action get written to a toplevel variable called + # cmd_foo. Toplevel variables can't handle things that change per + # makefile like $(TARGET), so hardcode the target. + command = command.replace('$(TARGET)', self.target) + cd_action = cd_action.replace('$(TARGET)', self.target) + + # Set LD_LIBRARY_PATH in case the action runs an executable from this + # build which links to shared libs from this build. + # actions run on the host, so they should in theory only use host + # libraries, but until everything is made cross-compile safe, also use + # target libraries. + # TODO(piman): when everything is cross-compile safe, remove lib.target + self.WriteLn('cmd_%s = LD_LIBRARY_PATH=$(builddir)/lib.host:' + '$(builddir)/lib.target:$$LD_LIBRARY_PATH; ' + 'export LD_LIBRARY_PATH; ' + '%s%s' + % (name, cd_action, command)) + self.WriteLn() + outputs = map(self.Absolutify, outputs) + # The makefile rules are all relative to the top dir, but the gyp actions + # are defined relative to their containing dir. This replaces the obj + # variable for the action rule with an absolute version so that the output + # goes in the right place. + # Only write the 'obj' and 'builddir' rules for the "primary" output (:1); + # it's superfluous for the "extra outputs", and this avoids accidentally + # writing duplicate dummy rules for those outputs. + # Same for environment. + self.WriteLn("%s: obj := $(abs_obj)" % QuoteSpaces(outputs[0])) + self.WriteLn("%s: builddir := $(abs_builddir)" % QuoteSpaces(outputs[0])) + self.WriteSortedXcodeEnv(outputs[0], self.GetSortedXcodeEnv()) + + for input in inputs: + assert ' ' not in input, ( + "Spaces in action input filenames not supported (%s)" % input) + for output in outputs: + assert ' ' not in output, ( + "Spaces in action output filenames not supported (%s)" % output) + + # See the comment in WriteCopies about expanding env vars. + env = self.GetSortedXcodeEnv() + outputs = [gyp.xcode_emulation.ExpandEnvVars(o, env) for o in outputs] + inputs = [gyp.xcode_emulation.ExpandEnvVars(i, env) for i in inputs] + + self.WriteDoCmd(outputs, map(Sourceify, map(self.Absolutify, inputs)), + part_of_all=part_of_all, command=name) + + # Stuff the outputs in a variable so we can refer to them later. + outputs_variable = 'action_%s_outputs' % name + self.WriteLn('%s := %s' % (outputs_variable, ' '.join(outputs))) + extra_outputs.append('$(%s)' % outputs_variable) + self.WriteLn() + + self.WriteLn() + + + def WriteRules(self, rules, extra_sources, extra_outputs, + extra_mac_bundle_resources, part_of_all): + """Write Makefile code for any 'rules' from the gyp input. + + extra_sources: a list that will be filled in with newly generated source + files, if any + extra_outputs: a list that will be filled in with any outputs of these + rules (used to make other pieces dependent on these rules) + part_of_all: flag indicating this target is part of 'all' + """ + for rule in rules: + name = StringToMakefileVariable('%s_%s' % (self.qualified_target, + rule['rule_name'])) + count = 0 + self.WriteLn('### Generated for rule %s:' % name) + + all_outputs = [] + + for rule_source in rule.get('rule_sources', []): + dirs = set() + (rule_source_dirname, rule_source_basename) = os.path.split(rule_source) + (rule_source_root, rule_source_ext) = \ + os.path.splitext(rule_source_basename) + + outputs = [self.ExpandInputRoot(out, rule_source_root, + rule_source_dirname) + for out in rule['outputs']] + + for out in outputs: + dir = os.path.dirname(out) + if dir: + dirs.add(dir) + if int(rule.get('process_outputs_as_sources', False)): + extra_sources += outputs + if int(rule.get('process_outputs_as_mac_bundle_resources', False)): + extra_mac_bundle_resources += outputs + inputs = map(Sourceify, map(self.Absolutify, [rule_source] + + rule.get('inputs', []))) + actions = ['$(call do_cmd,%s_%d)' % (name, count)] + + if name == 'resources_grit': + # HACK: This is ugly. Grit intentionally doesn't touch the + # timestamp of its output file when the file doesn't change, + # which is fine in hash-based dependency systems like scons + # and forge, but not kosher in the make world. After some + # discussion, hacking around it here seems like the least + # amount of pain. + actions += ['@touch --no-create $@'] + + outputs = map(self.Absolutify, outputs) + all_outputs += outputs + # Only write the 'obj' and 'builddir' rules for the "primary" output + # (:1); it's superfluous for the "extra outputs", and this avoids + # accidentally writing duplicate dummy rules for those outputs. + self.WriteLn('%s: obj := $(abs_obj)' % outputs[0]) + self.WriteLn('%s: builddir := $(abs_builddir)' % outputs[0]) + self.WriteMakeRule(outputs, inputs + ['FORCE_DO_CMD'], actions) + for output in outputs: + assert ' ' not in output, ( + "Spaces in rule filenames not yet supported (%s)" % output) + self.WriteLn('all_deps += %s' % ' '.join(outputs)) + + action = [self.ExpandInputRoot(ac, rule_source_root, + rule_source_dirname) + for ac in rule['action']] + mkdirs = '' + if len(dirs) > 0: + mkdirs = 'mkdir -p %s; ' % ' '.join(dirs) + cd_action = 'cd %s; ' % Sourceify(self.path or '.') + + # action, cd_action, and mkdirs get written to a toplevel variable + # called cmd_foo. Toplevel variables can't handle things that change + # per makefile like $(TARGET), so hardcode the target. + action = gyp.common.EncodePOSIXShellList(action) + action = action.replace('$(TARGET)', self.target) + cd_action = cd_action.replace('$(TARGET)', self.target) + mkdirs = mkdirs.replace('$(TARGET)', self.target) + + # Set LD_LIBRARY_PATH in case the rule runs an executable from this + # build which links to shared libs from this build. + # rules run on the host, so they should in theory only use host + # libraries, but until everything is made cross-compile safe, also use + # target libraries. + # TODO(piman): when everything is cross-compile safe, remove lib.target + self.WriteLn( + "cmd_%(name)s_%(count)d = LD_LIBRARY_PATH=" + "$(builddir)/lib.host:$(builddir)/lib.target:$$LD_LIBRARY_PATH; " + "export LD_LIBRARY_PATH; " + "%(cd_action)s%(mkdirs)s%(action)s" % { + 'action': action, + 'cd_action': cd_action, + 'count': count, + 'mkdirs': mkdirs, + 'name': name, + }) + self.WriteLn( + 'quiet_cmd_%(name)s_%(count)d = RULE %(name)s_%(count)d $@' % { + 'count': count, + 'name': name, + }) + self.WriteLn() + count += 1 + + outputs_variable = 'rule_%s_outputs' % name + self.WriteList(all_outputs, outputs_variable) + extra_outputs.append('$(%s)' % outputs_variable) + + self.WriteLn('### Finished generating for rule: %s' % name) + self.WriteLn() + self.WriteLn('### Finished generating for all rules') + self.WriteLn('') + + + def WriteCopies(self, copies, extra_outputs, part_of_all): + """Write Makefile code for any 'copies' from the gyp input. + + extra_outputs: a list that will be filled in with any outputs of this action + (used to make other pieces dependent on this action) + part_of_all: flag indicating this target is part of 'all' + """ + self.WriteLn('### Generated for copy rule.') + + variable = StringToMakefileVariable(self.qualified_target + '_copies') + outputs = [] + for copy in copies: + for path in copy['files']: + # Absolutify() calls normpath, stripping trailing slashes. + path = Sourceify(self.Absolutify(path)) + filename = os.path.split(path)[1] + output = Sourceify(self.Absolutify(os.path.join(copy['destination'], + filename))) + + # If the output path has variables in it, which happens in practice for + # 'copies', writing the environment as target-local doesn't work, + # because the variables are already needed for the target name. + # Copying the environment variables into global make variables doesn't + # work either, because then the .d files will potentially contain spaces + # after variable expansion, and .d file handling cannot handle spaces. + # As a workaround, manually expand variables at gyp time. Since 'copies' + # can't run scripts, there's no need to write the env then. + # WriteDoCmd() will escape spaces for .d files. + env = self.GetSortedXcodeEnv() + output = gyp.xcode_emulation.ExpandEnvVars(output, env) + path = gyp.xcode_emulation.ExpandEnvVars(path, env) + self.WriteDoCmd([output], [path], 'copy', part_of_all) + outputs.append(output) + self.WriteLn('%s = %s' % (variable, ' '.join(map(QuoteSpaces, outputs)))) + extra_outputs.append('$(%s)' % variable) + self.WriteLn() + + + def WriteMacBundleResources(self, resources, bundle_deps): + """Writes Makefile code for 'mac_bundle_resources'.""" + self.WriteLn('### Generated for mac_bundle_resources') + + for output, res in gyp.xcode_emulation.GetMacBundleResources( + generator_default_variables['PRODUCT_DIR'], self.xcode_settings, + map(Sourceify, map(self.Absolutify, resources))): + self.WriteDoCmd([output], [res], 'mac_tool,,,copy-bundle-resource', + part_of_all=True) + bundle_deps.append(output) + + + def WriteMacInfoPlist(self, bundle_deps): + """Write Makefile code for bundle Info.plist files.""" + info_plist, out, defines, extra_env = gyp.xcode_emulation.GetMacInfoPlist( + generator_default_variables['PRODUCT_DIR'], self.xcode_settings, + lambda p: Sourceify(self.Absolutify(p))) + if not info_plist: + return + if defines: + # Create an intermediate file to store preprocessed results. + intermediate_plist = ('$(obj).$(TOOLSET)/$(TARGET)/' + + os.path.basename(info_plist)) + self.WriteList(defines, intermediate_plist + ': INFOPLIST_DEFINES', '-D', + quoter=EscapeCppDefine) + self.WriteMakeRule([intermediate_plist], [info_plist], + ['$(call do_cmd,infoplist)', + # "Convert" the plist so that any weird whitespace changes from the + # preprocessor do not affect the XML parser in mac_tool. + '@plutil -convert xml1 $@ $@']) + info_plist = intermediate_plist + # plists can contain envvars and substitute them into the file. + self.WriteSortedXcodeEnv( + out, self.GetSortedXcodeEnv(additional_settings=extra_env)) + self.WriteDoCmd([out], [info_plist], 'mac_tool,,,copy-info-plist', + part_of_all=True) + bundle_deps.append(out) + + + def WriteSources(self, configs, deps, sources, + extra_outputs, extra_link_deps, + part_of_all, precompiled_header): + """Write Makefile code for any 'sources' from the gyp input. + These are source files necessary to build the current target. + + configs, deps, sources: input from gyp. + extra_outputs: a list of extra outputs this action should be dependent on; + used to serialize action/rules before compilation + extra_link_deps: a list that will be filled in with any outputs of + compilation (to be used in link lines) + part_of_all: flag indicating this target is part of 'all' + """ + + # Write configuration-specific variables for CFLAGS, etc. + for configname in sorted(configs.keys()): + config = configs[configname] + self.WriteList(config.get('defines'), 'DEFS_%s' % configname, prefix='-D', + quoter=EscapeCppDefine) + + if self.flavor == 'mac': + cflags = self.xcode_settings.GetCflags(configname) + cflags_c = self.xcode_settings.GetCflagsC(configname) + cflags_cc = self.xcode_settings.GetCflagsCC(configname) + cflags_objc = self.xcode_settings.GetCflagsObjC(configname) + cflags_objcc = self.xcode_settings.GetCflagsObjCC(configname) + else: + cflags = config.get('cflags') + cflags_c = config.get('cflags_c') + cflags_cc = config.get('cflags_cc') + + self.WriteLn("# Flags passed to all source files."); + self.WriteList(cflags, 'CFLAGS_%s' % configname) + self.WriteLn("# Flags passed to only C files."); + self.WriteList(cflags_c, 'CFLAGS_C_%s' % configname) + self.WriteLn("# Flags passed to only C++ files."); + self.WriteList(cflags_cc, 'CFLAGS_CC_%s' % configname) + if self.flavor == 'mac': + self.WriteLn("# Flags passed to only ObjC files."); + self.WriteList(cflags_objc, 'CFLAGS_OBJC_%s' % configname) + self.WriteLn("# Flags passed to only ObjC++ files."); + self.WriteList(cflags_objcc, 'CFLAGS_OBJCC_%s' % configname) + includes = config.get('include_dirs') + if includes: + includes = map(Sourceify, map(self.Absolutify, includes)) + self.WriteList(includes, 'INCS_%s' % configname, prefix='-I') + + compilable = filter(Compilable, sources) + objs = map(self.Objectify, map(self.Absolutify, map(Target, compilable))) + self.WriteList(objs, 'OBJS') + + for obj in objs: + assert ' ' not in obj, ( + "Spaces in object filenames not supported (%s)" % obj) + self.WriteLn('# Add to the list of files we specially track ' + 'dependencies for.') + self.WriteLn('all_deps += $(OBJS)') + self.WriteLn() + + # Make sure our dependencies are built first. + if deps: + self.WriteMakeRule(['$(OBJS)'], deps, + comment = 'Make sure our dependencies are built ' + 'before any of us.', + order_only = True) + + # Make sure the actions and rules run first. + # If they generate any extra headers etc., the per-.o file dep tracking + # will catch the proper rebuilds, so order only is still ok here. + if extra_outputs: + self.WriteMakeRule(['$(OBJS)'], extra_outputs, + comment = 'Make sure our actions/rules run ' + 'before any of us.', + order_only = True) + + pchdeps = precompiled_header.GetObjDependencies(compilable, objs ) + if pchdeps: + self.WriteLn('# Dependencies from obj files to their precompiled headers') + for source, obj, gch in pchdeps: + self.WriteLn('%s: %s' % (obj, gch)) + self.WriteLn('# End precompiled header dependencies') + + if objs: + extra_link_deps.append('$(OBJS)') + self.WriteLn("""\ +# CFLAGS et al overrides must be target-local. +# See "Target-specific Variable Values" in the GNU Make manual.""") + self.WriteLn("$(OBJS): TOOLSET := $(TOOLSET)") + self.WriteLn("$(OBJS): GYP_CFLAGS := " + "$(DEFS_$(BUILDTYPE)) " + "$(INCS_$(BUILDTYPE)) " + "%s " % precompiled_header.GetInclude('c') + + "$(CFLAGS_$(BUILDTYPE)) " + "$(CFLAGS_C_$(BUILDTYPE))") + self.WriteLn("$(OBJS): GYP_CXXFLAGS := " + "$(DEFS_$(BUILDTYPE)) " + "$(INCS_$(BUILDTYPE)) " + "%s " % precompiled_header.GetInclude('cc') + + "$(CFLAGS_$(BUILDTYPE)) " + "$(CFLAGS_CC_$(BUILDTYPE))") + if self.flavor == 'mac': + self.WriteLn("$(OBJS): GYP_OBJCFLAGS := " + "$(DEFS_$(BUILDTYPE)) " + "$(INCS_$(BUILDTYPE)) " + "%s " % precompiled_header.GetInclude('m') + + "$(CFLAGS_$(BUILDTYPE)) " + "$(CFLAGS_C_$(BUILDTYPE)) " + "$(CFLAGS_OBJC_$(BUILDTYPE))") + self.WriteLn("$(OBJS): GYP_OBJCXXFLAGS := " + "$(DEFS_$(BUILDTYPE)) " + "$(INCS_$(BUILDTYPE)) " + "%s " % precompiled_header.GetInclude('mm') + + "$(CFLAGS_$(BUILDTYPE)) " + "$(CFLAGS_CC_$(BUILDTYPE)) " + "$(CFLAGS_OBJCC_$(BUILDTYPE))") + + self.WritePchTargets(precompiled_header.GetPchBuildCommands()) + + # If there are any object files in our input file list, link them into our + # output. + extra_link_deps += filter(Linkable, sources) + + self.WriteLn() + + def WritePchTargets(self, pch_commands): + """Writes make rules to compile prefix headers.""" + if not pch_commands: + return + + for gch, lang_flag, lang, input in pch_commands: + extra_flags = { + 'c': '$(CFLAGS_C_$(BUILDTYPE))', + 'cc': '$(CFLAGS_CC_$(BUILDTYPE))', + 'm': '$(CFLAGS_C_$(BUILDTYPE)) $(CFLAGS_OBJC_$(BUILDTYPE))', + 'mm': '$(CFLAGS_CC_$(BUILDTYPE)) $(CFLAGS_OBJCC_$(BUILDTYPE))', + }[lang] + var_name = { + 'c': 'GYP_PCH_CFLAGS', + 'cc': 'GYP_PCH_CXXFLAGS', + 'm': 'GYP_PCH_OBJCFLAGS', + 'mm': 'GYP_PCH_OBJCXXFLAGS', + }[lang] + self.WriteLn("%s: %s := %s " % (gch, var_name, lang_flag) + + "$(DEFS_$(BUILDTYPE)) " + "$(INCS_$(BUILDTYPE)) " + "$(CFLAGS_$(BUILDTYPE)) " + + extra_flags) + + self.WriteLn('%s: %s FORCE_DO_CMD' % (gch, input)) + self.WriteLn('\t@$(call do_cmd,pch_%s,1)' % lang) + self.WriteLn('') + assert ' ' not in gch, ( + "Spaces in gch filenames not supported (%s)" % gch) + self.WriteLn('all_deps += %s' % gch) + self.WriteLn('') + + + def ComputeOutputBasename(self, spec): + """Return the 'output basename' of a gyp spec. + + E.g., the loadable module 'foobar' in directory 'baz' will produce + 'libfoobar.so' + """ + assert not self.is_mac_bundle + + if self.flavor == 'mac' and self.type in ( + 'static_library', 'executable', 'shared_library', 'loadable_module'): + return self.xcode_settings.GetExecutablePath() + + target = spec['target_name'] + target_prefix = '' + target_ext = '' + if self.type == 'static_library': + if target[:3] == 'lib': + target = target[3:] + target_prefix = 'lib' + target_ext = '.a' + elif self.type in ('loadable_module', 'shared_library'): + if target[:3] == 'lib': + target = target[3:] + target_prefix = 'lib' + target_ext = '.so' + elif self.type == 'none': + target = '%s.stamp' % target + elif self.type != 'executable': + print ("ERROR: What output file should be generated?", + "type", self.type, "target", target) + + target_prefix = spec.get('product_prefix', target_prefix) + target = spec.get('product_name', target) + product_ext = spec.get('product_extension') + if product_ext: + target_ext = '.' + product_ext + + return target_prefix + target + target_ext + + + def _InstallImmediately(self): + return self.toolset == 'target' and self.flavor == 'mac' and self.type in ( + 'static_library', 'executable', 'shared_library', 'loadable_module') + + + def ComputeOutput(self, spec): + """Return the 'output' (full output path) of a gyp spec. + + E.g., the loadable module 'foobar' in directory 'baz' will produce + '$(obj)/baz/libfoobar.so' + """ + assert not self.is_mac_bundle + + path = os.path.join('$(obj).' + self.toolset, self.path) + if self.type == 'executable' or self._InstallImmediately(): + path = '$(builddir)' + path = spec.get('product_dir', path) + return os.path.join(path, self.ComputeOutputBasename(spec)) + + + def ComputeMacBundleOutput(self, spec): + """Return the 'output' (full output path) to a bundle output directory.""" + assert self.is_mac_bundle + path = generator_default_variables['PRODUCT_DIR'] + return os.path.join(path, self.xcode_settings.GetWrapperName()) + + + def ComputeMacBundleBinaryOutput(self, spec): + """Return the 'output' (full output path) to the binary in a bundle.""" + path = generator_default_variables['PRODUCT_DIR'] + return os.path.join(path, self.xcode_settings.GetExecutablePath()) + + + def ComputeDeps(self, spec): + """Compute the dependencies of a gyp spec. + + Returns a tuple (deps, link_deps), where each is a list of + filenames that will need to be put in front of make for either + building (deps) or linking (link_deps). + """ + deps = [] + link_deps = [] + if 'dependencies' in spec: + deps.extend([target_outputs[dep] for dep in spec['dependencies'] + if target_outputs[dep]]) + for dep in spec['dependencies']: + if dep in target_link_deps: + link_deps.append(target_link_deps[dep]) + deps.extend(link_deps) + # TODO: It seems we need to transitively link in libraries (e.g. -lfoo)? + # This hack makes it work: + # link_deps.extend(spec.get('libraries', [])) + return (gyp.common.uniquer(deps), gyp.common.uniquer(link_deps)) + + + def WriteDependencyOnExtraOutputs(self, target, extra_outputs): + self.WriteMakeRule([self.output_binary], extra_outputs, + comment = 'Build our special outputs first.', + order_only = True) + + + def WriteTarget(self, spec, configs, deps, link_deps, bundle_deps, + extra_outputs, part_of_all): + """Write Makefile code to produce the final target of the gyp spec. + + spec, configs: input from gyp. + deps, link_deps: dependency lists; see ComputeDeps() + extra_outputs: any extra outputs that our target should depend on + part_of_all: flag indicating this target is part of 'all' + """ + + self.WriteLn('### Rules for final target.') + + if extra_outputs: + self.WriteDependencyOnExtraOutputs(self.output_binary, extra_outputs) + self.WriteMakeRule(extra_outputs, deps, + comment=('Preserve order dependency of ' + 'special output on deps.'), + order_only = True) + + target_postbuilds = {} + if self.type != 'none': + for configname in sorted(configs.keys()): + config = configs[configname] + if self.flavor == 'mac': + ldflags = self.xcode_settings.GetLdflags(configname, + generator_default_variables['PRODUCT_DIR'], + lambda p: Sourceify(self.Absolutify(p))) + + # TARGET_POSTBUILDS_$(BUILDTYPE) is added to postbuilds later on. + gyp_to_build = InvertRelativePath(self.path) + target_postbuild = self.xcode_settings.GetTargetPostbuilds( + configname, + QuoteSpaces(os.path.normpath(os.path.join(gyp_to_build, + self.output))), + QuoteSpaces(os.path.normpath(os.path.join(gyp_to_build, + self.output_binary)))) + if target_postbuild: + target_postbuilds[configname] = target_postbuild + else: + ldflags = config.get('ldflags', []) + # Compute an rpath for this output if needed. + if any(dep.endswith('.so') for dep in deps): + # We want to get the literal string "$ORIGIN" into the link command, + # so we need lots of escaping. + ldflags.append(r'-Wl,-rpath=\$$ORIGIN/lib.%s/' % self.toolset) + ldflags.append(r'-Wl,-rpath-link=\$(builddir)/lib.%s/' % + self.toolset) + self.WriteList(ldflags, 'LDFLAGS_%s' % configname) + libraries = spec.get('libraries') + if libraries: + # Remove duplicate entries + libraries = gyp.common.uniquer(libraries) + if self.flavor == 'mac': + libraries = self.xcode_settings.AdjustLibraries(libraries) + self.WriteList(libraries, 'LIBS') + self.WriteLn('%s: GYP_LDFLAGS := $(LDFLAGS_$(BUILDTYPE))' % + QuoteSpaces(self.output_binary)) + self.WriteLn('%s: LIBS := $(LIBS)' % QuoteSpaces(self.output_binary)) + + # Postbuild actions. Like actions, but implicitly depend on the target's + # output. + postbuilds = [] + if self.flavor == 'mac': + if target_postbuilds: + postbuilds.append('$(TARGET_POSTBUILDS_$(BUILDTYPE))') + postbuilds.extend( + gyp.xcode_emulation.GetSpecPostbuildCommands(spec)) + + if postbuilds: + # Envvars may be referenced by TARGET_POSTBUILDS_$(BUILDTYPE), + # so we must output its definition first, since we declare variables + # using ":=". + self.WriteSortedXcodeEnv(self.output, self.GetSortedXcodePostbuildEnv()) + + for configname in target_postbuilds: + self.WriteLn('%s: TARGET_POSTBUILDS_%s := %s' % + (QuoteSpaces(self.output), + configname, + gyp.common.EncodePOSIXShellList(target_postbuilds[configname]))) + + # Postbuilds expect to be run in the gyp file's directory, so insert an + # implicit postbuild to cd to there. + postbuilds.insert(0, gyp.common.EncodePOSIXShellList(['cd', self.path])) + for i in xrange(len(postbuilds)): + if not postbuilds[i].startswith('$'): + postbuilds[i] = EscapeShellArgument(postbuilds[i]) + self.WriteLn('%s: builddir := $(abs_builddir)' % QuoteSpaces(self.output)) + self.WriteLn('%s: POSTBUILDS := %s' % ( + QuoteSpaces(self.output), ' '.join(postbuilds))) + + # A bundle directory depends on its dependencies such as bundle resources + # and bundle binary. When all dependencies have been built, the bundle + # needs to be packaged. + if self.is_mac_bundle: + # If the framework doesn't contain a binary, then nothing depends + # on the actions -- make the framework depend on them directly too. + self.WriteDependencyOnExtraOutputs(self.output, extra_outputs) + + # Bundle dependencies. Note that the code below adds actions to this + # target, so if you move these two lines, move the lines below as well. + self.WriteList(map(QuoteSpaces, bundle_deps), 'BUNDLE_DEPS') + self.WriteLn('%s: $(BUNDLE_DEPS)' % QuoteSpaces(self.output)) + + # After the framework is built, package it. Needs to happen before + # postbuilds, since postbuilds depend on this. + if self.type in ('shared_library', 'loadable_module'): + self.WriteLn('\t@$(call do_cmd,mac_package_framework,,,%s)' % + self.xcode_settings.GetFrameworkVersion()) + + # Bundle postbuilds can depend on the whole bundle, so run them after + # the bundle is packaged, not already after the bundle binary is done. + if postbuilds: + self.WriteLn('\t@$(call do_postbuilds)') + postbuilds = [] # Don't write postbuilds for target's output. + + # Needed by test/mac/gyptest-rebuild.py. + self.WriteLn('\t@true # No-op, used by tests') + + # Since this target depends on binary and resources which are in + # nested subfolders, the framework directory will be older than + # its dependencies usually. To prevent this rule from executing + # on every build (expensive, especially with postbuilds), expliclity + # update the time on the framework directory. + self.WriteLn('\t@touch -c %s' % QuoteSpaces(self.output)) + + if postbuilds: + assert not self.is_mac_bundle, ('Postbuilds for bundles should be done ' + 'on the bundle, not the binary (target \'%s\')' % self.target) + assert 'product_dir' not in spec, ('Postbuilds do not work with ' + 'custom product_dir') + + if self.type == 'executable': + self.WriteLn('%s: LD_INPUTS := %s' % ( + QuoteSpaces(self.output_binary), + ' '.join(map(QuoteSpaces, link_deps)))) + if self.toolset == 'host' and self.flavor == 'android': + self.WriteDoCmd([self.output_binary], link_deps, 'link_host', + part_of_all, postbuilds=postbuilds) + else: + self.WriteDoCmd([self.output_binary], link_deps, 'link', part_of_all, + postbuilds=postbuilds) + + elif self.type == 'static_library': + for link_dep in link_deps: + assert ' ' not in link_dep, ( + "Spaces in alink input filenames not supported (%s)" % link_dep) + self.WriteDoCmd([self.output_binary], link_deps, 'alink', part_of_all, + postbuilds=postbuilds) + elif self.type == 'shared_library': + self.WriteLn('%s: LD_INPUTS := %s' % ( + QuoteSpaces(self.output_binary), + ' '.join(map(QuoteSpaces, link_deps)))) + self.WriteDoCmd([self.output_binary], link_deps, 'solink', part_of_all, + postbuilds=postbuilds) + elif self.type == 'loadable_module': + for link_dep in link_deps: + assert ' ' not in link_dep, ( + "Spaces in module input filenames not supported (%s)" % link_dep) + if self.toolset == 'host' and self.flavor == 'android': + self.WriteDoCmd([self.output_binary], link_deps, 'solink_module_host', + part_of_all, postbuilds=postbuilds) + else: + self.WriteDoCmd( + [self.output_binary], link_deps, 'solink_module', part_of_all, + postbuilds=postbuilds) + elif self.type == 'none': + # Write a stamp line. + self.WriteDoCmd([self.output_binary], deps, 'touch', part_of_all, + postbuilds=postbuilds) + else: + print "WARNING: no output for", self.type, target + + # Add an alias for each target (if there are any outputs). + # Installable target aliases are created below. + if ((self.output and self.output != self.target) and + (self.type not in self._INSTALLABLE_TARGETS)): + self.WriteMakeRule([self.target], [self.output], + comment='Add target alias', phony = True) + if part_of_all: + self.WriteMakeRule(['all'], [self.target], + comment = 'Add target alias to "all" target.', + phony = True) + + # Add special-case rules for our installable targets. + # 1) They need to install to the build dir or "product" dir. + # 2) They get shortcuts for building (e.g. "make chrome"). + # 3) They are part of "make all". + if self.type in self._INSTALLABLE_TARGETS: + if self.type == 'shared_library': + file_desc = 'shared library' + else: + file_desc = 'executable' + install_path = self._InstallableTargetInstallPath() + installable_deps = [self.output] + if (self.flavor == 'mac' and not 'product_dir' in spec and + self.toolset == 'target'): + # On mac, products are created in install_path immediately. + assert install_path == self.output, '%s != %s' % ( + install_path, self.output) + + # Point the target alias to the final binary output. + self.WriteMakeRule([self.target], [install_path], + comment='Add target alias', phony = True) + if install_path != self.output: + assert not self.is_mac_bundle # See comment a few lines above. + self.WriteDoCmd([install_path], [self.output], 'copy', + comment = 'Copy this to the %s output path.' % + file_desc, part_of_all=part_of_all) + installable_deps.append(install_path) + if self.output != self.alias and self.alias != self.target: + self.WriteMakeRule([self.alias], installable_deps, + comment = 'Short alias for building this %s.' % + file_desc, phony = True) + if part_of_all: + self.WriteMakeRule(['all'], [install_path], + comment = 'Add %s to "all" target.' % file_desc, + phony = True) + + + def WriteList(self, value_list, variable=None, prefix='', + quoter=QuoteIfNecessary): + """Write a variable definition that is a list of values. + + E.g. WriteList(['a','b'], 'foo', prefix='blah') writes out + foo = blaha blahb + but in a pretty-printed style. + """ + values = '' + if value_list: + value_list = [quoter(prefix + l) for l in value_list] + values = ' \\\n\t' + ' \\\n\t'.join(value_list) + self.fp.write('%s :=%s\n\n' % (variable, values)) + + + def WriteDoCmd(self, outputs, inputs, command, part_of_all, comment=None, + postbuilds=False): + """Write a Makefile rule that uses do_cmd. + + This makes the outputs dependent on the command line that was run, + as well as support the V= make command line flag. + """ + suffix = '' + if postbuilds: + assert ',' not in command + suffix = ',,1' # Tell do_cmd to honor $POSTBUILDS + self.WriteMakeRule(outputs, inputs, + actions = ['$(call do_cmd,%s%s)' % (command, suffix)], + comment = comment, + force = True) + # Add our outputs to the list of targets we read depfiles from. + # all_deps is only used for deps file reading, and for deps files we replace + # spaces with ? because escaping doesn't work with make's $(sort) and + # other functions. + outputs = [QuoteSpaces(o, SPACE_REPLACEMENT) for o in outputs] + self.WriteLn('all_deps += %s' % ' '.join(outputs)) + + + def WriteMakeRule(self, outputs, inputs, actions=None, comment=None, + order_only=False, force=False, phony=False): + """Write a Makefile rule, with some extra tricks. + + outputs: a list of outputs for the rule (note: this is not directly + supported by make; see comments below) + inputs: a list of inputs for the rule + actions: a list of shell commands to run for the rule + comment: a comment to put in the Makefile above the rule (also useful + for making this Python script's code self-documenting) + order_only: if true, makes the dependency order-only + force: if true, include FORCE_DO_CMD as an order-only dep + phony: if true, the rule does not actually generate the named output, the + output is just a name to run the rule + """ + outputs = map(QuoteSpaces, outputs) + inputs = map(QuoteSpaces, inputs) + + if comment: + self.WriteLn('# ' + comment) + if phony: + self.WriteLn('.PHONY: ' + ' '.join(outputs)) + # TODO(evanm): just make order_only a list of deps instead of these hacks. + if order_only: + order_insert = '| ' + pick_output = ' '.join(outputs) + else: + order_insert = '' + pick_output = outputs[0] + if force: + force_append = ' FORCE_DO_CMD' + else: + force_append = '' + if actions: + self.WriteLn("%s: TOOLSET := $(TOOLSET)" % outputs[0]) + self.WriteLn('%s: %s%s%s' % (pick_output, order_insert, ' '.join(inputs), + force_append)) + if actions: + for action in actions: + self.WriteLn('\t%s' % action) + if not order_only and len(outputs) > 1: + # If we have more than one output, a rule like + # foo bar: baz + # that for *each* output we must run the action, potentially + # in parallel. That is not what we're trying to write -- what + # we want is that we run the action once and it generates all + # the files. + # http://www.gnu.org/software/hello/manual/automake/Multiple-Outputs.html + # discusses this problem and has this solution: + # 1) Write the naive rule that would produce parallel runs of + # the action. + # 2) Make the outputs seralized on each other, so we won't start + # a parallel run until the first run finishes, at which point + # we'll have generated all the outputs and we're done. + self.WriteLn('%s: %s' % (' '.join(outputs[1:]), outputs[0])) + # Add a dummy command to the "extra outputs" rule, otherwise make seems to + # think these outputs haven't (couldn't have?) changed, and thus doesn't + # flag them as changed (i.e. include in '$?') when evaluating dependent + # rules, which in turn causes do_cmd() to skip running dependent commands. + self.WriteLn('%s: ;' % (' '.join(outputs[1:]))) + self.WriteLn() + + + def WriteAndroidNdkModuleRule(self, module_name, all_sources, link_deps): + """Write a set of LOCAL_XXX definitions for Android NDK. + + These variable definitions will be used by Android NDK but do nothing for + non-Android applications. + + Arguments: + module_name: Android NDK module name, which must be unique among all + module names. + all_sources: A list of source files (will be filtered by Compilable). + link_deps: A list of link dependencies, which must be sorted in + the order from dependencies to dependents. + """ + if self.type not in ('executable', 'shared_library', 'static_library'): + return + + self.WriteLn('# Variable definitions for Android applications') + self.WriteLn('include $(CLEAR_VARS)') + self.WriteLn('LOCAL_MODULE := ' + module_name) + self.WriteLn('LOCAL_CFLAGS := $(CFLAGS_$(BUILDTYPE)) ' + '$(DEFS_$(BUILDTYPE)) ' + # LOCAL_CFLAGS is applied to both of C and C++. There is + # no way to specify $(CFLAGS_C_$(BUILDTYPE)) only for C + # sources. + '$(CFLAGS_C_$(BUILDTYPE)) ' + # $(INCS_$(BUILDTYPE)) includes the prefix '-I' while + # LOCAL_C_INCLUDES does not expect it. So put it in + # LOCAL_CFLAGS. + '$(INCS_$(BUILDTYPE))') + # LOCAL_CXXFLAGS is obsolete and LOCAL_CPPFLAGS is preferred. + self.WriteLn('LOCAL_CPPFLAGS := $(CFLAGS_CC_$(BUILDTYPE))') + self.WriteLn('LOCAL_C_INCLUDES :=') + self.WriteLn('LOCAL_LDLIBS := $(LDFLAGS_$(BUILDTYPE)) $(LIBS)') + + # Detect the C++ extension. + cpp_ext = {'.cc': 0, '.cpp': 0, '.cxx': 0} + default_cpp_ext = '.cpp' + for filename in all_sources: + ext = os.path.splitext(filename)[1] + if ext in cpp_ext: + cpp_ext[ext] += 1 + if cpp_ext[ext] > cpp_ext[default_cpp_ext]: + default_cpp_ext = ext + self.WriteLn('LOCAL_CPP_EXTENSION := ' + default_cpp_ext) + + self.WriteList(map(self.Absolutify, filter(Compilable, all_sources)), + 'LOCAL_SRC_FILES') + + # Filter out those which do not match prefix and suffix and produce + # the resulting list without prefix and suffix. + def DepsToModules(deps, prefix, suffix): + modules = [] + for filepath in deps: + filename = os.path.basename(filepath) + if filename.startswith(prefix) and filename.endswith(suffix): + modules.append(filename[len(prefix):-len(suffix)]) + return modules + + # Retrieve the default value of 'SHARED_LIB_SUFFIX' + params = {'flavor': 'linux'} + default_variables = {} + CalculateVariables(default_variables, params) + + self.WriteList( + DepsToModules(link_deps, + generator_default_variables['SHARED_LIB_PREFIX'], + default_variables['SHARED_LIB_SUFFIX']), + 'LOCAL_SHARED_LIBRARIES') + self.WriteList( + DepsToModules(link_deps, + generator_default_variables['STATIC_LIB_PREFIX'], + generator_default_variables['STATIC_LIB_SUFFIX']), + 'LOCAL_STATIC_LIBRARIES') + + if self.type == 'executable': + self.WriteLn('include $(BUILD_EXECUTABLE)') + elif self.type == 'shared_library': + self.WriteLn('include $(BUILD_SHARED_LIBRARY)') + elif self.type == 'static_library': + self.WriteLn('include $(BUILD_STATIC_LIBRARY)') + self.WriteLn() + + + def WriteLn(self, text=''): + self.fp.write(text + '\n') + + + def GetSortedXcodeEnv(self, additional_settings=None): + return gyp.xcode_emulation.GetSortedXcodeEnv( + self.xcode_settings, "$(abs_builddir)", + os.path.join("$(abs_srcdir)", self.path), "$(BUILDTYPE)", + additional_settings) + + + def GetSortedXcodePostbuildEnv(self): + # CHROMIUM_STRIP_SAVE_FILE is a chromium-specific hack. + # TODO(thakis): It would be nice to have some general mechanism instead. + strip_save_file = self.xcode_settings.GetPerTargetSetting( + 'CHROMIUM_STRIP_SAVE_FILE', '') + # Even if strip_save_file is empty, explicitly write it. Else a postbuild + # might pick up an export from an earlier target. + return self.GetSortedXcodeEnv( + additional_settings={'CHROMIUM_STRIP_SAVE_FILE': strip_save_file}) + + + def WriteSortedXcodeEnv(self, target, env): + for k, v in env: + # For + # foo := a\ b + # the escaped space does the right thing. For + # export foo := a\ b + # it does not -- the backslash is written to the env as literal character. + # So don't escape spaces in |env[k]|. + self.WriteLn('%s: export %s := %s' % (QuoteSpaces(target), k, v)) + + + def Objectify(self, path): + """Convert a path to its output directory form.""" + if '$(' in path: + path = path.replace('$(obj)/', '$(obj).%s/$(TARGET)/' % self.toolset) + if not '$(obj)' in path: + path = '$(obj).%s/$(TARGET)/%s' % (self.toolset, path) + return path + + + def Pchify(self, path, lang): + """Convert a prefix header path to its output directory form.""" + path = self.Absolutify(path) + if '$(' in path: + path = path.replace('$(obj)/', '$(obj).%s/$(TARGET)/pch-%s' % + (self.toolset, lang)) + return path + return '$(obj).%s/$(TARGET)/pch-%s/%s' % (self.toolset, lang, path) + + + def Absolutify(self, path): + """Convert a subdirectory-relative path into a base-relative path. + Skips over paths that contain variables.""" + if '$(' in path: + # path is no existing file in this case, but calling normpath is still + # important for trimming trailing slashes. + return os.path.normpath(path) + return os.path.normpath(os.path.join(self.path, path)) + + + def ExpandInputRoot(self, template, expansion, dirname): + if '%(INPUT_ROOT)s' not in template and '%(INPUT_DIRNAME)s' not in template: + return template + path = template % { + 'INPUT_ROOT': expansion, + 'INPUT_DIRNAME': dirname, + } + return path + + + def _InstallableTargetInstallPath(self): + """Returns the location of the final output for an installable target.""" + # Xcode puts shared_library results into PRODUCT_DIR, and some gyp files + # rely on this. Emulate this behavior for mac. + if (self.type == 'shared_library' and + (self.flavor != 'mac' or self.toolset != 'target')): + # Install all shared libs into a common directory (per toolset) for + # convenient access with LD_LIBRARY_PATH. + return '$(builddir)/lib.%s/%s' % (self.toolset, self.alias) + return '$(builddir)/' + self.alias + + +def WriteAutoRegenerationRule(params, root_makefile, makefile_name, + build_files): + """Write the target to regenerate the Makefile.""" + options = params['options'] + build_files_args = [gyp.common.RelativePath(filename, options.toplevel_dir) + for filename in params['build_files_arg']] + gyp_binary = gyp.common.FixIfRelativePath(params['gyp_binary'], + options.toplevel_dir) + if not gyp_binary.startswith(os.sep): + gyp_binary = os.path.join('.', gyp_binary) + root_makefile.write( + "quiet_cmd_regen_makefile = ACTION Regenerating $@\n" + "cmd_regen_makefile = %(cmd)s\n" + "%(makefile_name)s: %(deps)s\n" + "\t$(call do_cmd,regen_makefile)\n\n" % { + 'makefile_name': makefile_name, + 'deps': ' '.join(map(Sourceify, build_files)), + 'cmd': gyp.common.EncodePOSIXShellList( + [gyp_binary, '-fmake'] + + gyp.RegenerateFlags(options) + + build_files_args)}) + + +def RunSystemTests(flavor): + """Run tests against the system to compute default settings for commands. + + Returns: + dictionary of settings matching the block of command-lines used in + SHARED_HEADER. E.g. the dictionary will contain a ARFLAGS.target + key for the default ARFLAGS for the target ar command. + """ + # Compute flags used for building static archives. + # N.B.: this fallback logic should match the logic in SHARED_HEADER. + # See comment there for more details. + ar_target = GetEnvironFallback(('AR_target', 'AR'), 'ar') + cc_target = GetEnvironFallback(('CC_target', 'CC'), 'cc') + arflags_target = 'crs' + # ar -T enables thin archives on Linux. OS X's ar supports a -T flag, but it + # does something useless (it limits filenames in the archive to 15 chars). + if flavor != 'mac' and gyp.system_test.TestArSupportsT(ar_command=ar_target, + cc_command=cc_target): + arflags_target = 'crsT' + + ar_host = os.environ.get('AR_host', 'ar') + cc_host = os.environ.get('CC_host', 'gcc') + arflags_host = 'crs' + # It feels redundant to compute this again given that most builds aren't + # cross-compiles, but due to quirks of history CC_host defaults to 'gcc' + # while CC_target defaults to 'cc', so the commands really are different + # even though they're nearly guaranteed to run the same code underneath. + if flavor != 'mac' and gyp.system_test.TestArSupportsT(ar_command=ar_host, + cc_command=cc_host): + arflags_host = 'crsT' + + return { 'ARFLAGS.target': arflags_target, + 'ARFLAGS.host': arflags_host } + + +def GenerateOutput(target_list, target_dicts, data, params): + options = params['options'] + flavor = gyp.common.GetFlavor(params) + generator_flags = params.get('generator_flags', {}) + builddir_name = generator_flags.get('output_dir', 'out') + android_ndk_version = generator_flags.get('android_ndk_version', None) + default_target = generator_flags.get('default_target', 'all') + + def CalculateMakefilePath(build_file, base_name): + """Determine where to write a Makefile for a given gyp file.""" + # Paths in gyp files are relative to the .gyp file, but we want + # paths relative to the source root for the master makefile. Grab + # the path of the .gyp file as the base to relativize against. + # E.g. "foo/bar" when we're constructing targets for "foo/bar/baz.gyp". + base_path = gyp.common.RelativePath(os.path.dirname(build_file), + options.depth) + # We write the file in the base_path directory. + output_file = os.path.join(options.depth, base_path, base_name) + if options.generator_output: + output_file = os.path.join(options.generator_output, output_file) + base_path = gyp.common.RelativePath(os.path.dirname(build_file), + options.toplevel_dir) + return base_path, output_file + + # TODO: search for the first non-'Default' target. This can go + # away when we add verification that all targets have the + # necessary configurations. + default_configuration = None + toolsets = set([target_dicts[target]['toolset'] for target in target_list]) + for target in target_list: + spec = target_dicts[target] + if spec['default_configuration'] != 'Default': + default_configuration = spec['default_configuration'] + break + if not default_configuration: + default_configuration = 'Default' + + srcdir = '.' + makefile_name = 'Makefile' + options.suffix + makefile_path = os.path.join(options.toplevel_dir, makefile_name) + if options.generator_output: + global srcdir_prefix + makefile_path = os.path.join(options.generator_output, makefile_path) + srcdir = gyp.common.RelativePath(srcdir, options.generator_output) + srcdir_prefix = '$(srcdir)/' + + flock_command= 'flock' + header_params = { + 'default_target': default_target, + 'builddir': builddir_name, + 'default_configuration': default_configuration, + 'flock': flock_command, + 'flock_index': 1, + 'link_commands': LINK_COMMANDS_LINUX, + 'extra_commands': '', + 'srcdir': srcdir, + } + if flavor == 'mac': + flock_command = './gyp-mac-tool flock' + header_params.update({ + 'flock': flock_command, + 'flock_index': 2, + 'link_commands': LINK_COMMANDS_MAC, + 'extra_commands': SHARED_HEADER_MAC_COMMANDS, + }) + elif flavor == 'android': + header_params.update({ + 'link_commands': LINK_COMMANDS_ANDROID, + }) + elif flavor == 'solaris': + header_params.update({ + 'flock': './gyp-sun-tool flock', + 'flock_index': 2, + 'extra_commands': SHARED_HEADER_SUN_COMMANDS, + }) + elif flavor == 'freebsd': + header_params.update({ + 'flock': 'lockf', + }) + + header_params.update(RunSystemTests(flavor)) + header_params.update({ + 'CC.target': GetEnvironFallback(('CC_target', 'CC'), '$(CC)'), + 'AR.target': GetEnvironFallback(('AR_target', 'AR'), '$(AR)'), + 'CXX.target': GetEnvironFallback(('CXX_target', 'CXX'), '$(CXX)'), + 'LINK.target': GetEnvironFallback(('LD_target', 'LD'), '$(LINK)'), + 'CC.host': GetEnvironFallback(('CC_host',), 'gcc'), + 'AR.host': GetEnvironFallback(('AR_host',), 'ar'), + 'CXX.host': GetEnvironFallback(('CXX_host',), 'g++'), + 'LINK.host': GetEnvironFallback(('LD_host',), 'g++'), + }) + + build_file, _, _ = gyp.common.ParseQualifiedTarget(target_list[0]) + make_global_settings_array = data[build_file].get('make_global_settings', []) + make_global_settings = '' + for key, value in make_global_settings_array: + if value[0] != '$': + value = '$(abspath %s)' % value + if key == 'LINK': + make_global_settings += ('%s ?= %s $(builddir)/linker.lock %s\n' % + (key, flock_command, value)) + elif key in ('CC', 'CC.host', 'CXX', 'CXX.host'): + make_global_settings += ( + 'ifneq (,$(filter $(origin %s), undefined default))\n' % key) + # Let gyp-time envvars win over global settings. + if key in os.environ: + value = os.environ[key] + make_global_settings += ' %s = %s\n' % (key, value) + make_global_settings += 'endif\n' + else: + make_global_settings += '%s ?= %s\n' % (key, value) + header_params['make_global_settings'] = make_global_settings + + ensure_directory_exists(makefile_path) + root_makefile = open(makefile_path, 'w') + root_makefile.write(SHARED_HEADER % header_params) + # Currently any versions have the same effect, but in future the behavior + # could be different. + if android_ndk_version: + root_makefile.write( + '# Define LOCAL_PATH for build of Android applications.\n' + 'LOCAL_PATH := $(call my-dir)\n' + '\n') + for toolset in toolsets: + root_makefile.write('TOOLSET := %s\n' % toolset) + WriteRootHeaderSuffixRules(root_makefile) + + # Put build-time support tools next to the root Makefile. + dest_path = os.path.dirname(makefile_path) + gyp.common.CopyTool(flavor, dest_path) + + # Find the list of targets that derive from the gyp file(s) being built. + needed_targets = set() + for build_file in params['build_files']: + for target in gyp.common.AllTargets(target_list, target_dicts, build_file): + needed_targets.add(target) + + build_files = set() + include_list = set() + for qualified_target in target_list: + build_file, target, toolset = gyp.common.ParseQualifiedTarget( + qualified_target) + + this_make_global_settings = data[build_file].get('make_global_settings', []) + assert make_global_settings_array == this_make_global_settings, ( + "make_global_settings needs to be the same for all targets.") + + build_files.add(gyp.common.RelativePath(build_file, options.toplevel_dir)) + included_files = data[build_file]['included_files'] + for included_file in included_files: + # The included_files entries are relative to the dir of the build file + # that included them, so we have to undo that and then make them relative + # to the root dir. + relative_include_file = gyp.common.RelativePath( + gyp.common.UnrelativePath(included_file, build_file), + options.toplevel_dir) + abs_include_file = os.path.abspath(relative_include_file) + # If the include file is from the ~/.gyp dir, we should use absolute path + # so that relocating the src dir doesn't break the path. + if (params['home_dot_gyp'] and + abs_include_file.startswith(params['home_dot_gyp'])): + build_files.add(abs_include_file) + else: + build_files.add(relative_include_file) + + base_path, output_file = CalculateMakefilePath(build_file, + target + '.' + toolset + options.suffix + '.mk') + + spec = target_dicts[qualified_target] + configs = spec['configurations'] + + if flavor == 'mac': + gyp.xcode_emulation.MergeGlobalXcodeSettingsToSpec(data[build_file], spec) + + writer = MakefileWriter(generator_flags, flavor) + writer.Write(qualified_target, base_path, output_file, spec, configs, + part_of_all=qualified_target in needed_targets) + + # Our root_makefile lives at the source root. Compute the relative path + # from there to the output_file for including. + mkfile_rel_path = gyp.common.RelativePath(output_file, + os.path.dirname(makefile_path)) + include_list.add(mkfile_rel_path) + + # Write out per-gyp (sub-project) Makefiles. + depth_rel_path = gyp.common.RelativePath(options.depth, os.getcwd()) + for build_file in build_files: + # The paths in build_files were relativized above, so undo that before + # testing against the non-relativized items in target_list and before + # calculating the Makefile path. + build_file = os.path.join(depth_rel_path, build_file) + gyp_targets = [target_dicts[target]['target_name'] for target in target_list + if target.startswith(build_file) and + target in needed_targets] + # Only generate Makefiles for gyp files with targets. + if not gyp_targets: + continue + base_path, output_file = CalculateMakefilePath(build_file, + os.path.splitext(os.path.basename(build_file))[0] + '.Makefile') + makefile_rel_path = gyp.common.RelativePath(os.path.dirname(makefile_path), + os.path.dirname(output_file)) + writer.WriteSubMake(output_file, makefile_rel_path, gyp_targets, + builddir_name) + + + # Write out the sorted list of includes. + root_makefile.write('\n') + for include_file in sorted(include_list): + # We wrap each .mk include in an if statement so users can tell make to + # not load a file by setting NO_LOAD. The below make code says, only + # load the .mk file if the .mk filename doesn't start with a token in + # NO_LOAD. + root_makefile.write( + "ifeq ($(strip $(foreach prefix,$(NO_LOAD),\\\n" + " $(findstring $(join ^,$(prefix)),\\\n" + " $(join ^," + include_file + ")))),)\n") + root_makefile.write(" include " + include_file + "\n") + root_makefile.write("endif\n") + root_makefile.write('\n') + + if (not generator_flags.get('standalone') + and generator_flags.get('auto_regeneration', True)): + WriteAutoRegenerationRule(params, root_makefile, makefile_name, build_files) + + root_makefile.write(SHARED_FOOTER) + + root_makefile.close() diff --git a/node-v0.8.14/tools/gyp/pylib/gyp/generator/msvs.py b/node-v0.8.14/tools/gyp/pylib/gyp/generator/msvs.py new file mode 100644 index 0000000..7015248 --- /dev/null +++ b/node-v0.8.14/tools/gyp/pylib/gyp/generator/msvs.py @@ -0,0 +1,3143 @@ +# Copyright (c) 2012 Google Inc. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +import copy +import ntpath +import os +import posixpath +import re +import subprocess +import sys + +import gyp.common +import gyp.easy_xml as easy_xml +import gyp.MSVSNew as MSVSNew +import gyp.MSVSProject as MSVSProject +import gyp.MSVSSettings as MSVSSettings +import gyp.MSVSToolFile as MSVSToolFile +import gyp.MSVSUserFile as MSVSUserFile +import gyp.MSVSVersion as MSVSVersion + + +# Regular expression for validating Visual Studio GUIDs. If the GUID +# contains lowercase hex letters, MSVS will be fine. However, +# IncrediBuild BuildConsole will parse the solution file, but then +# silently skip building the target causing hard to track down errors. +# Note that this only happens with the BuildConsole, and does not occur +# if IncrediBuild is executed from inside Visual Studio. This regex +# validates that the string looks like a GUID with all uppercase hex +# letters. +VALID_MSVS_GUID_CHARS = re.compile('^[A-F0-9\-]+$') + + +generator_default_variables = { + 'EXECUTABLE_PREFIX': '', + 'EXECUTABLE_SUFFIX': '.exe', + 'STATIC_LIB_PREFIX': '', + 'SHARED_LIB_PREFIX': '', + 'STATIC_LIB_SUFFIX': '.lib', + 'SHARED_LIB_SUFFIX': '.dll', + 'INTERMEDIATE_DIR': '$(IntDir)', + 'SHARED_INTERMEDIATE_DIR': '$(OutDir)obj/global_intermediate', + 'OS': 'win', + 'PRODUCT_DIR': '$(OutDir)', + 'LIB_DIR': '$(OutDir)lib', + 'RULE_INPUT_ROOT': '$(InputName)', + 'RULE_INPUT_DIRNAME': '$(InputDir)', + 'RULE_INPUT_EXT': '$(InputExt)', + 'RULE_INPUT_NAME': '$(InputFileName)', + 'RULE_INPUT_PATH': '$(InputPath)', + 'CONFIGURATION_NAME': '$(ConfigurationName)', +} + + +# The msvs specific sections that hold paths +generator_additional_path_sections = [ + 'msvs_cygwin_dirs', + 'msvs_props', +] + + +generator_additional_non_configuration_keys = [ + 'msvs_cygwin_dirs', + 'msvs_cygwin_shell', + 'msvs_shard', +] + + +# List of precompiled header related keys. +precomp_keys = [ + 'msvs_precompiled_header', + 'msvs_precompiled_source', +] + + +cached_username = None + + +cached_domain = None + + +# TODO(gspencer): Switch the os.environ calls to be +# win32api.GetDomainName() and win32api.GetUserName() once the +# python version in depot_tools has been updated to work on Vista +# 64-bit. +def _GetDomainAndUserName(): + if sys.platform not in ('win32', 'cygwin'): + return ('DOMAIN', 'USERNAME') + global cached_username + global cached_domain + if not cached_domain or not cached_username: + domain = os.environ.get('USERDOMAIN') + username = os.environ.get('USERNAME') + if not domain or not username: + call = subprocess.Popen(['net', 'config', 'Workstation'], + stdout=subprocess.PIPE) + config = call.communicate()[0] + username_re = re.compile('^User name\s+(\S+)', re.MULTILINE) + username_match = username_re.search(config) + if username_match: + username = username_match.group(1) + domain_re = re.compile('^Logon domain\s+(\S+)', re.MULTILINE) + domain_match = domain_re.search(config) + if domain_match: + domain = domain_match.group(1) + cached_domain = domain + cached_username = username + return (cached_domain, cached_username) + +fixpath_prefix = None + + +def _NormalizedSource(source): + """Normalize the path. + + But not if that gets rid of a variable, as this may expand to something + larger than one directory. + + Arguments: + source: The path to be normalize.d + + Returns: + The normalized path. + """ + normalized = os.path.normpath(source) + if source.count('$') == normalized.count('$'): + source = normalized + return source + + +def _FixPath(path): + """Convert paths to a form that will make sense in a vcproj file. + + Arguments: + path: The path to convert, may contain / etc. + Returns: + The path with all slashes made into backslashes. + """ + if fixpath_prefix and path and not os.path.isabs(path) and not path[0] == '$': + path = os.path.join(fixpath_prefix, path) + path = path.replace('/', '\\') + path = _NormalizedSource(path) + if path and path[-1] == '\\': + path = path[:-1] + return path + + +def _FixPaths(paths): + """Fix each of the paths of the list.""" + return [_FixPath(i) for i in paths] + + +def _ConvertSourcesToFilterHierarchy(sources, prefix=None, excluded=None, + list_excluded=True): + """Converts a list split source file paths into a vcproj folder hierarchy. + + Arguments: + sources: A list of source file paths split. + prefix: A list of source file path layers meant to apply to each of sources. + excluded: A set of excluded files. + + Returns: + A hierarchy of filenames and MSVSProject.Filter objects that matches the + layout of the source tree. + For example: + _ConvertSourcesToFilterHierarchy([['a', 'bob1.c'], ['b', 'bob2.c']], + prefix=['joe']) + --> + [MSVSProject.Filter('a', contents=['joe\\a\\bob1.c']), + MSVSProject.Filter('b', contents=['joe\\b\\bob2.c'])] + """ + if not prefix: prefix = [] + result = [] + excluded_result = [] + folders = dict() + # Gather files into the final result, excluded, or folders. + for s in sources: + if len(s) == 1: + filename = _NormalizedSource('\\'.join(prefix + s)) + if filename in excluded: + excluded_result.append(filename) + else: + result.append(filename) + else: + if not folders.get(s[0]): + folders[s[0]] = [] + folders[s[0]].append(s[1:]) + # Add a folder for excluded files. + if excluded_result and list_excluded: + excluded_folder = MSVSProject.Filter('_excluded_files', + contents=excluded_result) + result.append(excluded_folder) + # Populate all the folders. + for f in folders: + contents = _ConvertSourcesToFilterHierarchy(folders[f], prefix=prefix + [f], + excluded=excluded, + list_excluded=list_excluded) + contents = MSVSProject.Filter(f, contents=contents) + result.append(contents) + + return result + + +def _ToolAppend(tools, tool_name, setting, value, only_if_unset=False): + if not value: return + # TODO(bradnelson): ugly hack, fix this more generally!!! + if 'Directories' in setting or 'Dependencies' in setting: + if type(value) == str: + value = value.replace('/', '\\') + else: + value = [i.replace('/', '\\') for i in value] + if not tools.get(tool_name): + tools[tool_name] = dict() + tool = tools[tool_name] + if tool.get(setting): + if only_if_unset: return + if type(tool[setting]) == list: + tool[setting] += value + else: + raise TypeError( + 'Appending "%s" to a non-list setting "%s" for tool "%s" is ' + 'not allowed, previous value: %s' % ( + value, setting, tool_name, str(tool[setting]))) + else: + tool[setting] = value + + +def _ConfigPlatform(config_data): + return config_data.get('msvs_configuration_platform', 'Win32') + + +def _ConfigBaseName(config_name, platform_name): + if config_name.endswith('_' + platform_name): + return config_name[0:-len(platform_name)-1] + else: + return config_name + + +def _ConfigFullName(config_name, config_data): + platform_name = _ConfigPlatform(config_data) + return '%s|%s' % (_ConfigBaseName(config_name, platform_name), platform_name) + + +def _BuildCommandLineForRuleRaw(spec, cmd, cygwin_shell, has_input_path, + quote_cmd, do_setup_env): + + if [x for x in cmd if '$(InputDir)' in x]: + input_dir_preamble = ( + 'set INPUTDIR=$(InputDir)\n' + 'set INPUTDIR=%INPUTDIR:$(ProjectDir)=%\n' + 'set INPUTDIR=%INPUTDIR:~0,-1%\n' + ) + else: + input_dir_preamble = '' + + if cygwin_shell: + # Find path to cygwin. + cygwin_dir = _FixPath(spec.get('msvs_cygwin_dirs', ['.'])[0]) + # Prepare command. + direct_cmd = cmd + direct_cmd = [i.replace('$(IntDir)', + '`cygpath -m "${INTDIR}"`') for i in direct_cmd] + direct_cmd = [i.replace('$(OutDir)', + '`cygpath -m "${OUTDIR}"`') for i in direct_cmd] + direct_cmd = [i.replace('$(InputDir)', + '`cygpath -m "${INPUTDIR}"`') for i in direct_cmd] + if has_input_path: + direct_cmd = [i.replace('$(InputPath)', + '`cygpath -m "${INPUTPATH}"`') + for i in direct_cmd] + direct_cmd = ['\\"%s\\"' % i.replace('"', '\\\\\\"') for i in direct_cmd] + #direct_cmd = gyp.common.EncodePOSIXShellList(direct_cmd) + direct_cmd = ' '.join(direct_cmd) + # TODO(quote): regularize quoting path names throughout the module + cmd = '' + if do_setup_env: + cmd += 'call "$(ProjectDir)%(cygwin_dir)s\\setup_env.bat" && ' + cmd += 'set CYGWIN=nontsec&& ' + if direct_cmd.find('NUMBER_OF_PROCESSORS') >= 0: + cmd += 'set /a NUMBER_OF_PROCESSORS_PLUS_1=%%NUMBER_OF_PROCESSORS%%+1&& ' + if direct_cmd.find('INTDIR') >= 0: + cmd += 'set INTDIR=$(IntDir)&& ' + if direct_cmd.find('OUTDIR') >= 0: + cmd += 'set OUTDIR=$(OutDir)&& ' + if has_input_path and direct_cmd.find('INPUTPATH') >= 0: + cmd += 'set INPUTPATH=$(InputPath) && ' + cmd += 'bash -c "%(cmd)s"' + cmd = cmd % {'cygwin_dir': cygwin_dir, + 'cmd': direct_cmd} + return input_dir_preamble + cmd + else: + # Convert cat --> type to mimic unix. + if cmd[0] == 'cat': + command = ['type'] + else: + command = [cmd[0].replace('/', '\\')] + # Add call before command to ensure that commands can be tied together one + # after the other without aborting in Incredibuild, since IB makes a bat + # file out of the raw command string, and some commands (like python) are + # actually batch files themselves. + command.insert(0, 'call') + # Fix the paths + # TODO(quote): This is a really ugly heuristic, and will miss path fixing + # for arguments like "--arg=path" or "/opt:path". + # If the argument starts with a slash or dash, it's probably a command line + # switch + arguments = [i if (i[:1] in "/-") else _FixPath(i) for i in cmd[1:]] + arguments = [i.replace('$(InputDir)','%INPUTDIR%') for i in arguments] + arguments = [MSVSSettings.FixVCMacroSlashes(i) for i in arguments] + if quote_cmd: + # Support a mode for using cmd directly. + # Convert any paths to native form (first element is used directly). + # TODO(quote): regularize quoting path names throughout the module + arguments = ['"%s"' % i for i in arguments] + # Collapse into a single command. + return input_dir_preamble + ' '.join(command + arguments) + + +def _BuildCommandLineForRule(spec, rule, has_input_path, do_setup_env): + # Currently this weird argument munging is used to duplicate the way a + # python script would need to be run as part of the chrome tree. + # Eventually we should add some sort of rule_default option to set this + # per project. For now the behavior chrome needs is the default. + mcs = rule.get('msvs_cygwin_shell') + if mcs is None: + mcs = int(spec.get('msvs_cygwin_shell', 1)) + elif isinstance(mcs, str): + mcs = int(mcs) + quote_cmd = int(rule.get('msvs_quote_cmd', 1)) + return _BuildCommandLineForRuleRaw(spec, rule['action'], mcs, has_input_path, + quote_cmd, do_setup_env=do_setup_env) + + +def _AddActionStep(actions_dict, inputs, outputs, description, command): + """Merge action into an existing list of actions. + + Care must be taken so that actions which have overlapping inputs either don't + get assigned to the same input, or get collapsed into one. + + Arguments: + actions_dict: dictionary keyed on input name, which maps to a list of + dicts describing the actions attached to that input file. + inputs: list of inputs + outputs: list of outputs + description: description of the action + command: command line to execute + """ + # Require there to be at least one input (call sites will ensure this). + assert inputs + + action = { + 'inputs': inputs, + 'outputs': outputs, + 'description': description, + 'command': command, + } + + # Pick where to stick this action. + # While less than optimal in terms of build time, attach them to the first + # input for now. + chosen_input = inputs[0] + + # Add it there. + if chosen_input not in actions_dict: + actions_dict[chosen_input] = [] + actions_dict[chosen_input].append(action) + + +def _AddCustomBuildToolForMSVS(p, spec, primary_input, + inputs, outputs, description, cmd): + """Add a custom build tool to execute something. + + Arguments: + p: the target project + spec: the target project dict + primary_input: input file to attach the build tool to + inputs: list of inputs + outputs: list of outputs + description: description of the action + cmd: command line to execute + """ + inputs = _FixPaths(inputs) + outputs = _FixPaths(outputs) + tool = MSVSProject.Tool( + 'VCCustomBuildTool', + {'Description': description, + 'AdditionalDependencies': ';'.join(inputs), + 'Outputs': ';'.join(outputs), + 'CommandLine': cmd, + }) + # Add to the properties of primary input for each config. + for config_name, c_data in spec['configurations'].iteritems(): + p.AddFileConfig(_FixPath(primary_input), + _ConfigFullName(config_name, c_data), tools=[tool]) + + +def _AddAccumulatedActionsToMSVS(p, spec, actions_dict): + """Add actions accumulated into an actions_dict, merging as needed. + + Arguments: + p: the target project + spec: the target project dict + actions_dict: dictionary keyed on input name, which maps to a list of + dicts describing the actions attached to that input file. + """ + for primary_input in actions_dict: + inputs = set() + outputs = set() + descriptions = [] + commands = [] + for action in actions_dict[primary_input]: + inputs.update(set(action['inputs'])) + outputs.update(set(action['outputs'])) + descriptions.append(action['description']) + commands.append(action['command']) + # Add the custom build step for one input file. + description = ', and also '.join(descriptions) + command = '\r\n'.join(commands) + _AddCustomBuildToolForMSVS(p, spec, + primary_input=primary_input, + inputs=inputs, + outputs=outputs, + description=description, + cmd=command) + + +def _RuleExpandPath(path, input_file): + """Given the input file to which a rule applied, string substitute a path. + + Arguments: + path: a path to string expand + input_file: the file to which the rule applied. + Returns: + The string substituted path. + """ + path = path.replace('$(InputName)', + os.path.splitext(os.path.split(input_file)[1])[0]) + path = path.replace('$(InputDir)', os.path.dirname(input_file)) + path = path.replace('$(InputExt)', + os.path.splitext(os.path.split(input_file)[1])[1]) + path = path.replace('$(InputFileName)', os.path.split(input_file)[1]) + path = path.replace('$(InputPath)', input_file) + return path + + +def _FindRuleTriggerFiles(rule, sources): + """Find the list of files which a particular rule applies to. + + Arguments: + rule: the rule in question + sources: the set of all known source files for this project + Returns: + The list of sources that trigger a particular rule. + """ + rule_ext = rule['extension'] + return [s for s in sources if s.endswith('.' + rule_ext)] + + +def _RuleInputsAndOutputs(rule, trigger_file): + """Find the inputs and outputs generated by a rule. + + Arguments: + rule: the rule in question. + trigger_file: the main trigger for this rule. + Returns: + The pair of (inputs, outputs) involved in this rule. + """ + raw_inputs = _FixPaths(rule.get('inputs', [])) + raw_outputs = _FixPaths(rule.get('outputs', [])) + inputs = set() + outputs = set() + inputs.add(trigger_file) + for i in raw_inputs: + inputs.add(_RuleExpandPath(i, trigger_file)) + for o in raw_outputs: + outputs.add(_RuleExpandPath(o, trigger_file)) + return (inputs, outputs) + + +def _GenerateNativeRulesForMSVS(p, rules, output_dir, spec, options): + """Generate a native rules file. + + Arguments: + p: the target project + rules: the set of rules to include + output_dir: the directory in which the project/gyp resides + spec: the project dict + options: global generator options + """ + rules_filename = '%s%s.rules' % (spec['target_name'], + options.suffix) + rules_file = MSVSToolFile.Writer(os.path.join(output_dir, rules_filename), + spec['target_name']) + # Add each rule. + for r in rules: + rule_name = r['rule_name'] + rule_ext = r['extension'] + inputs = _FixPaths(r.get('inputs', [])) + outputs = _FixPaths(r.get('outputs', [])) + # Skip a rule with no action and no inputs. + if 'action' not in r and not r.get('rule_sources', []): + continue + cmd = _BuildCommandLineForRule(spec, r, has_input_path=True, + do_setup_env=True) + rules_file.AddCustomBuildRule(name=rule_name, + description=r.get('message', rule_name), + extensions=[rule_ext], + additional_dependencies=inputs, + outputs=outputs, + cmd=cmd) + # Write out rules file. + rules_file.WriteIfChanged() + + # Add rules file to project. + p.AddToolFile(rules_filename) + + +def _Cygwinify(path): + path = path.replace('$(OutDir)', '$(OutDirCygwin)') + path = path.replace('$(IntDir)', '$(IntDirCygwin)') + return path + + +def _GenerateExternalRules(rules, output_dir, spec, + sources, options, actions_to_add): + """Generate an external makefile to do a set of rules. + + Arguments: + rules: the list of rules to include + output_dir: path containing project and gyp files + spec: project specification data + sources: set of sources known + options: global generator options + actions_to_add: The list of actions we will add to. + """ + filename = '%s_rules%s.mk' % (spec['target_name'], options.suffix) + mk_file = gyp.common.WriteOnDiff(os.path.join(output_dir, filename)) + # Find cygwin style versions of some paths. + mk_file.write('OutDirCygwin:=$(shell cygpath -u "$(OutDir)")\n') + mk_file.write('IntDirCygwin:=$(shell cygpath -u "$(IntDir)")\n') + # Gather stuff needed to emit all: target. + all_inputs = set() + all_outputs = set() + all_output_dirs = set() + first_outputs = [] + for rule in rules: + trigger_files = _FindRuleTriggerFiles(rule, sources) + for tf in trigger_files: + inputs, outputs = _RuleInputsAndOutputs(rule, tf) + all_inputs.update(set(inputs)) + all_outputs.update(set(outputs)) + # Only use one target from each rule as the dependency for + # 'all' so we don't try to build each rule multiple times. + first_outputs.append(list(outputs)[0]) + # Get the unique output directories for this rule. + output_dirs = [os.path.split(i)[0] for i in outputs] + for od in output_dirs: + all_output_dirs.add(od) + first_outputs_cyg = [_Cygwinify(i) for i in first_outputs] + # Write out all: target, including mkdir for each output directory. + mk_file.write('all: %s\n' % ' '.join(first_outputs_cyg)) + for od in all_output_dirs: + if od: + mk_file.write('\tmkdir -p `cygpath -u "%s"`\n' % od) + mk_file.write('\n') + # Define how each output is generated. + for rule in rules: + trigger_files = _FindRuleTriggerFiles(rule, sources) + for tf in trigger_files: + # Get all the inputs and outputs for this rule for this trigger file. + inputs, outputs = _RuleInputsAndOutputs(rule, tf) + inputs = [_Cygwinify(i) for i in inputs] + outputs = [_Cygwinify(i) for i in outputs] + # Prepare the command line for this rule. + cmd = [_RuleExpandPath(c, tf) for c in rule['action']] + cmd = ['"%s"' % i for i in cmd] + cmd = ' '.join(cmd) + # Add it to the makefile. + mk_file.write('%s: %s\n' % (' '.join(outputs), ' '.join(inputs))) + mk_file.write('\t%s\n\n' % cmd) + # Close up the file. + mk_file.close() + + # Add makefile to list of sources. + sources.add(filename) + # Add a build action to call makefile. + cmd = ['make', + 'OutDir=$(OutDir)', + 'IntDir=$(IntDir)', + '-j', '${NUMBER_OF_PROCESSORS_PLUS_1}', + '-f', filename] + cmd = _BuildCommandLineForRuleRaw(spec, cmd, True, False, True, True) + # Insert makefile as 0'th input, so it gets the action attached there, + # as this is easier to understand from in the IDE. + all_inputs = list(all_inputs) + all_inputs.insert(0, filename) + _AddActionStep(actions_to_add, + inputs=_FixPaths(all_inputs), + outputs=_FixPaths(all_outputs), + description='Running external rules for %s' % + spec['target_name'], + command=cmd) + + +def _EscapeEnvironmentVariableExpansion(s): + """Escapes % characters. + + Escapes any % characters so that Windows-style environment variable + expansions will leave them alone. + See http://connect.microsoft.com/VisualStudio/feedback/details/106127/cl-d-name-text-containing-percentage-characters-doesnt-compile + to understand why we have to do this. + + Args: + s: The string to be escaped. + + Returns: + The escaped string. + """ + s = s.replace('%', '%%') + return s + + +quote_replacer_regex = re.compile(r'(\\*)"') + + +def _EscapeCommandLineArgumentForMSVS(s): + """Escapes a Windows command-line argument. + + So that the Win32 CommandLineToArgv function will turn the escaped result back + into the original string. + See http://msdn.microsoft.com/en-us/library/17w5ykft.aspx + ("Parsing C++ Command-Line Arguments") to understand why we have to do + this. + + Args: + s: the string to be escaped. + Returns: + the escaped string. + """ + + def _Replace(match): + # For a literal quote, CommandLineToArgv requires an odd number of + # backslashes preceding it, and it produces half as many literal backslashes + # (rounded down). So we need to produce 2n+1 backslashes. + return 2 * match.group(1) + '\\"' + + # Escape all quotes so that they are interpreted literally. + s = quote_replacer_regex.sub(_Replace, s) + # Now add unescaped quotes so that any whitespace is interpreted literally. + s = '"' + s + '"' + return s + + +delimiters_replacer_regex = re.compile(r'(\\*)([,;]+)') + + +def _EscapeVCProjCommandLineArgListItem(s): + """Escapes command line arguments for MSVS. + + The VCProj format stores string lists in a single string using commas and + semi-colons as separators, which must be quoted if they are to be + interpreted literally. However, command-line arguments may already have + quotes, and the VCProj parser is ignorant of the backslash escaping + convention used by CommandLineToArgv, so the command-line quotes and the + VCProj quotes may not be the same quotes. So to store a general + command-line argument in a VCProj list, we need to parse the existing + quoting according to VCProj's convention and quote any delimiters that are + not already quoted by that convention. The quotes that we add will also be + seen by CommandLineToArgv, so if backslashes precede them then we also have + to escape those backslashes according to the CommandLineToArgv + convention. + + Args: + s: the string to be escaped. + Returns: + the escaped string. + """ + + def _Replace(match): + # For a non-literal quote, CommandLineToArgv requires an even number of + # backslashes preceding it, and it produces half as many literal + # backslashes. So we need to produce 2n backslashes. + return 2 * match.group(1) + '"' + match.group(2) + '"' + + segments = s.split('"') + # The unquoted segments are at the even-numbered indices. + for i in range(0, len(segments), 2): + segments[i] = delimiters_replacer_regex.sub(_Replace, segments[i]) + # Concatenate back into a single string + s = '"'.join(segments) + if len(segments) % 2 == 0: + # String ends while still quoted according to VCProj's convention. This + # means the delimiter and the next list item that follow this one in the + # .vcproj file will be misinterpreted as part of this item. There is nothing + # we can do about this. Adding an extra quote would correct the problem in + # the VCProj but cause the same problem on the final command-line. Moving + # the item to the end of the list does works, but that's only possible if + # there's only one such item. Let's just warn the user. + print >> sys.stderr, ('Warning: MSVS may misinterpret the odd number of ' + + 'quotes in ' + s) + return s + + +def _EscapeCppDefineForMSVS(s): + """Escapes a CPP define so that it will reach the compiler unaltered.""" + s = _EscapeEnvironmentVariableExpansion(s) + s = _EscapeCommandLineArgumentForMSVS(s) + s = _EscapeVCProjCommandLineArgListItem(s) + # cl.exe replaces literal # characters with = in preprocesor definitions for + # some reason. Octal-encode to work around that. + s = s.replace('#', '\\%03o' % ord('#')) + return s + + +quote_replacer_regex2 = re.compile(r'(\\+)"') + + +def _EscapeCommandLineArgumentForMSBuild(s): + """Escapes a Windows command-line argument for use by MSBuild.""" + + def _Replace(match): + return (len(match.group(1))/2*4)*'\\' + '\\"' + + # Escape all quotes so that they are interpreted literally. + s = quote_replacer_regex2.sub(_Replace, s) + return s + + +def _EscapeMSBuildSpecialCharacters(s): + escape_dictionary = { + '%': '%25', + '$': '%24', + '@': '%40', + "'": '%27', + ';': '%3B', + '?': '%3F', + '*': '%2A' + } + result = ''.join([escape_dictionary.get(c, c) for c in s]) + return result + + +def _EscapeCppDefineForMSBuild(s): + """Escapes a CPP define so that it will reach the compiler unaltered.""" + s = _EscapeEnvironmentVariableExpansion(s) + s = _EscapeCommandLineArgumentForMSBuild(s) + s = _EscapeMSBuildSpecialCharacters(s) + # cl.exe replaces literal # characters with = in preprocesor definitions for + # some reason. Octal-encode to work around that. + s = s.replace('#', '\\%03o' % ord('#')) + return s + + +def _GenerateRulesForMSVS(p, output_dir, options, spec, + sources, excluded_sources, + actions_to_add): + """Generate all the rules for a particular project. + + Arguments: + p: the project + output_dir: directory to emit rules to + options: global options passed to the generator + spec: the specification for this project + sources: the set of all known source files in this project + excluded_sources: the set of sources excluded from normal processing + actions_to_add: deferred list of actions to add in + """ + rules = spec.get('rules', []) + rules_native = [r for r in rules if not int(r.get('msvs_external_rule', 0))] + rules_external = [r for r in rules if int(r.get('msvs_external_rule', 0))] + + # Handle rules that use a native rules file. + if rules_native: + _GenerateNativeRulesForMSVS(p, rules_native, output_dir, spec, options) + + # Handle external rules (non-native rules). + if rules_external: + _GenerateExternalRules(rules_external, output_dir, spec, + sources, options, actions_to_add) + _AdjustSourcesForRules(rules, sources, excluded_sources) + + +def _AdjustSourcesForRules(rules, sources, excluded_sources): + # Add outputs generated by each rule (if applicable). + for rule in rules: + # Done if not processing outputs as sources. + if int(rule.get('process_outputs_as_sources', False)): + # Add in the outputs from this rule. + trigger_files = _FindRuleTriggerFiles(rule, sources) + for trigger_file in trigger_files: + inputs, outputs = _RuleInputsAndOutputs(rule, trigger_file) + inputs = set(_FixPaths(inputs)) + outputs = set(_FixPaths(outputs)) + inputs.remove(_FixPath(trigger_file)) + sources.update(inputs) + excluded_sources.update(inputs) + sources.update(outputs) + + +def _FilterActionsFromExcluded(excluded_sources, actions_to_add): + """Take inputs with actions attached out of the list of exclusions. + + Arguments: + excluded_sources: list of source files not to be built. + actions_to_add: dict of actions keyed on source file they're attached to. + Returns: + excluded_sources with files that have actions attached removed. + """ + must_keep = set(_FixPaths(actions_to_add.keys())) + return [s for s in excluded_sources if s not in must_keep] + + +def _GetDefaultConfiguration(spec): + return spec['configurations'][spec['default_configuration']] + + +def _GetGuidOfProject(proj_path, spec): + """Get the guid for the project. + + Arguments: + proj_path: Path of the vcproj or vcxproj file to generate. + spec: The target dictionary containing the properties of the target. + Returns: + the guid. + Raises: + ValueError: if the specified GUID is invalid. + """ + # Pluck out the default configuration. + default_config = _GetDefaultConfiguration(spec) + # Decide the guid of the project. + guid = default_config.get('msvs_guid') + if guid: + if VALID_MSVS_GUID_CHARS.match(guid) is None: + raise ValueError('Invalid MSVS guid: "%s". Must match regex: "%s".' % + (guid, VALID_MSVS_GUID_CHARS.pattern)) + guid = '{%s}' % guid + guid = guid or MSVSNew.MakeGuid(proj_path) + return guid + + +def _GetMsbuildToolsetOfProject(proj_path, spec, version): + """Get the platform toolset for the project. + + Arguments: + proj_path: Path of the vcproj or vcxproj file to generate. + spec: The target dictionary containing the properties of the target. + version: The MSVSVersion object. + Returns: + the platform toolset string or None. + """ + # Pluck out the default configuration. + default_config = _GetDefaultConfiguration(spec) + toolset = default_config.get('msbuild_toolset') + if not toolset and version.DefaultToolset(): + toolset = version.DefaultToolset() + return toolset + + +def _GenerateProject(project, options, version, generator_flags): + """Generates a vcproj file. + + Arguments: + project: the MSVSProject object. + options: global generator options. + version: the MSVSVersion object. + generator_flags: dict of generator-specific flags. + Returns: + A list of source files that cannot be found on disk. + """ + default_config = _GetDefaultConfiguration(project.spec) + + # Skip emitting anything if told to with msvs_existing_vcproj option. + if default_config.get('msvs_existing_vcproj'): + return [] + + if version.UsesVcxproj(): + return _GenerateMSBuildProject(project, options, version, generator_flags) + else: + return _GenerateMSVSProject(project, options, version, generator_flags) + + +def _GenerateMSVSProject(project, options, version, generator_flags): + """Generates a .vcproj file. It may create .rules and .user files too. + + Arguments: + project: The project object we will generate the file for. + options: Global options passed to the generator. + version: The VisualStudioVersion object. + generator_flags: dict of generator-specific flags. + """ + spec = project.spec + vcproj_dir = os.path.dirname(project.path) + if vcproj_dir and not os.path.exists(vcproj_dir): + os.makedirs(vcproj_dir) + + platforms = _GetUniquePlatforms(spec) + p = MSVSProject.Writer(project.path, version, spec['target_name'], + project.guid, platforms) + + # Get directory project file is in. + project_dir = os.path.split(project.path)[0] + gyp_path = _NormalizedSource(project.build_file) + relative_path_of_gyp_file = gyp.common.RelativePath(gyp_path, project_dir) + + config_type = _GetMSVSConfigurationType(spec, project.build_file) + for config_name, config in spec['configurations'].iteritems(): + _AddConfigurationToMSVSProject(p, spec, config_type, config_name, config) + + # Prepare list of sources and excluded sources. + gyp_file = os.path.split(project.build_file)[1] + sources, excluded_sources = _PrepareListOfSources(spec, generator_flags, + gyp_file) + + # Add rules. + actions_to_add = {} + _GenerateRulesForMSVS(p, project_dir, options, spec, + sources, excluded_sources, + actions_to_add) + list_excluded = generator_flags.get('msvs_list_excluded_files', True) + sources, excluded_sources, excluded_idl = ( + _AdjustSourcesAndConvertToFilterHierarchy( + spec, options, project_dir, sources, excluded_sources, list_excluded)) + + # Add in files. + missing_sources = _VerifySourcesExist(sources, project_dir) + p.AddFiles(sources) + + _AddToolFilesToMSVS(p, spec) + _HandlePreCompiledHeaders(p, sources, spec) + _AddActions(actions_to_add, spec, relative_path_of_gyp_file) + _AddCopies(actions_to_add, spec) + _WriteMSVSUserFile(project.path, version, spec) + + # NOTE: this stanza must appear after all actions have been decided. + # Don't excluded sources with actions attached, or they won't run. + excluded_sources = _FilterActionsFromExcluded( + excluded_sources, actions_to_add) + _ExcludeFilesFromBeingBuilt(p, spec, excluded_sources, excluded_idl, + list_excluded) + _AddAccumulatedActionsToMSVS(p, spec, actions_to_add) + + # Write it out. + p.WriteIfChanged() + + return missing_sources + + +def _GetUniquePlatforms(spec): + """Returns the list of unique platforms for this spec, e.g ['win32', ...]. + + Arguments: + spec: The target dictionary containing the properties of the target. + Returns: + The MSVSUserFile object created. + """ + # Gather list of unique platforms. + platforms = set() + for configuration in spec['configurations']: + platforms.add(_ConfigPlatform(spec['configurations'][configuration])) + platforms = list(platforms) + return platforms + + +def _CreateMSVSUserFile(proj_path, version, spec): + """Generates a .user file for the user running this Gyp program. + + Arguments: + proj_path: The path of the project file being created. The .user file + shares the same path (with an appropriate suffix). + version: The VisualStudioVersion object. + spec: The target dictionary containing the properties of the target. + Returns: + The MSVSUserFile object created. + """ + (domain, username) = _GetDomainAndUserName() + vcuser_filename = '.'.join([proj_path, domain, username, 'user']) + user_file = MSVSUserFile.Writer(vcuser_filename, version, + spec['target_name']) + return user_file + + +def _GetMSVSConfigurationType(spec, build_file): + """Returns the configuration type for this project. + + It's a number defined by Microsoft. May raise an exception. + + Args: + spec: The target dictionary containing the properties of the target. + build_file: The path of the gyp file. + Returns: + An integer, the configuration type. + """ + try: + config_type = { + 'executable': '1', # .exe + 'shared_library': '2', # .dll + 'loadable_module': '2', # .dll + 'static_library': '4', # .lib + 'none': '10', # Utility type + }[spec['type']] + except KeyError: + if spec.get('type'): + raise Exception('Target type %s is not a valid target type for ' + 'target %s in %s.' % + (spec['type'], spec['target_name'], build_file)) + else: + raise Exception('Missing type field for target %s in %s.' % + (spec['target_name'], build_file)) + return config_type + + +def _AddConfigurationToMSVSProject(p, spec, config_type, config_name, config): + """Adds a configuration to the MSVS project. + + Many settings in a vcproj file are specific to a configuration. This + function the main part of the vcproj file that's configuration specific. + + Arguments: + p: The target project being generated. + spec: The target dictionary containing the properties of the target. + config_type: The configuration type, a number as defined by Microsoft. + config_name: The name of the configuration. + config: The dictionnary that defines the special processing to be done + for this configuration. + """ + # Get the information for this configuration + include_dirs, resource_include_dirs = _GetIncludeDirs(config) + libraries = _GetLibraries(spec) + out_file, vc_tool, _ = _GetOutputFilePathAndTool(spec) + defines = _GetDefines(config) + defines = [_EscapeCppDefineForMSVS(d) for d in defines] + disabled_warnings = _GetDisabledWarnings(config) + prebuild = config.get('msvs_prebuild') + postbuild = config.get('msvs_postbuild') + def_file = _GetModuleDefinition(spec) + precompiled_header = config.get('msvs_precompiled_header') + + # Prepare the list of tools as a dictionary. + tools = dict() + # Add in user specified msvs_settings. + msvs_settings = config.get('msvs_settings', {}) + MSVSSettings.ValidateMSVSSettings(msvs_settings) + for tool in msvs_settings: + settings = config['msvs_settings'][tool] + for setting in settings: + _ToolAppend(tools, tool, setting, settings[setting]) + # Add the information to the appropriate tool + _ToolAppend(tools, 'VCCLCompilerTool', + 'AdditionalIncludeDirectories', include_dirs) + _ToolAppend(tools, 'VCResourceCompilerTool', + 'AdditionalIncludeDirectories', resource_include_dirs) + # Add in libraries. + _ToolAppend(tools, 'VCLinkerTool', 'AdditionalDependencies', libraries) + if out_file: + _ToolAppend(tools, vc_tool, 'OutputFile', out_file, only_if_unset=True) + # Add defines. + _ToolAppend(tools, 'VCCLCompilerTool', 'PreprocessorDefinitions', defines) + _ToolAppend(tools, 'VCResourceCompilerTool', 'PreprocessorDefinitions', + defines) + # Change program database directory to prevent collisions. + _ToolAppend(tools, 'VCCLCompilerTool', 'ProgramDataBaseFileName', + '$(IntDir)$(ProjectName)\\vc80.pdb', only_if_unset=True) + # Add disabled warnings. + _ToolAppend(tools, 'VCCLCompilerTool', + 'DisableSpecificWarnings', disabled_warnings) + # Add Pre-build. + _ToolAppend(tools, 'VCPreBuildEventTool', 'CommandLine', prebuild) + # Add Post-build. + _ToolAppend(tools, 'VCPostBuildEventTool', 'CommandLine', postbuild) + # Turn on precompiled headers if appropriate. + if precompiled_header: + precompiled_header = os.path.split(precompiled_header)[1] + _ToolAppend(tools, 'VCCLCompilerTool', 'UsePrecompiledHeader', '2') + _ToolAppend(tools, 'VCCLCompilerTool', + 'PrecompiledHeaderThrough', precompiled_header) + _ToolAppend(tools, 'VCCLCompilerTool', + 'ForcedIncludeFiles', precompiled_header) + # Loadable modules don't generate import libraries; + # tell dependent projects to not expect one. + if spec['type'] == 'loadable_module': + _ToolAppend(tools, 'VCLinkerTool', 'IgnoreImportLibrary', 'true') + # Set the module definition file if any. + if def_file: + _ToolAppend(tools, 'VCLinkerTool', 'ModuleDefinitionFile', def_file) + + _AddConfigurationToMSVS(p, spec, tools, config, config_type, config_name) + + +def _GetIncludeDirs(config): + """Returns the list of directories to be used for #include directives. + + Arguments: + config: The dictionnary that defines the special processing to be done + for this configuration. + Returns: + The list of directory paths. + """ + # TODO(bradnelson): include_dirs should really be flexible enough not to + # require this sort of thing. + include_dirs = ( + config.get('include_dirs', []) + + config.get('msvs_system_include_dirs', [])) + resource_include_dirs = config.get('resource_include_dirs', include_dirs) + include_dirs = _FixPaths(include_dirs) + resource_include_dirs = _FixPaths(resource_include_dirs) + return include_dirs, resource_include_dirs + + +def _GetLibraries(spec): + """Returns the list of libraries for this configuration. + + Arguments: + spec: The target dictionary containing the properties of the target. + Returns: + The list of directory paths. + """ + libraries = spec.get('libraries', []) + # Strip out -l, as it is not used on windows (but is needed so we can pass + # in libraries that are assumed to be in the default library path). + # Also remove duplicate entries, leaving only the last duplicate, while + # preserving order. + found = set() + unique_libraries_list = [] + for entry in reversed(libraries): + library = re.sub('^\-l', '', entry) + if library not in found: + found.add(library) + unique_libraries_list.append(library) + unique_libraries_list.reverse() + return unique_libraries_list + + +def _GetOutputFilePathAndTool(spec): + """Returns the path and tool to use for this target. + + Figures out the path of the file this spec will create and the name of + the VC tool that will create it. + + Arguments: + spec: The target dictionary containing the properties of the target. + Returns: + A triple of (file path, name of the vc tool, name of the msbuild tool) + """ + # Select a name for the output file. + out_file = '' + vc_tool = '' + msbuild_tool = '' + output_file_map = { + 'executable': ('VCLinkerTool', 'Link', '$(OutDir)', '.exe'), + 'shared_library': ('VCLinkerTool', 'Link', '$(OutDir)', '.dll'), + 'loadable_module': ('VCLinkerTool', 'Link', '$(OutDir)', '.dll'), + 'static_library': ('VCLibrarianTool', 'Lib', '$(OutDir)lib\\', '.lib'), + } + output_file_props = output_file_map.get(spec['type']) + if output_file_props and int(spec.get('msvs_auto_output_file', 1)): + vc_tool, msbuild_tool, out_dir, suffix = output_file_props + out_dir = spec.get('product_dir', out_dir) + product_extension = spec.get('product_extension') + if product_extension: + suffix = '.' + product_extension + prefix = spec.get('product_prefix', '') + product_name = spec.get('product_name', '$(ProjectName)') + out_file = ntpath.join(out_dir, prefix + product_name + suffix) + return out_file, vc_tool, msbuild_tool + + +def _GetDefines(config): + """Returns the list of preprocessor definitions for this configuation. + + Arguments: + config: The dictionnary that defines the special processing to be done + for this configuration. + Returns: + The list of preprocessor definitions. + """ + defines = [] + for d in config.get('defines', []): + if type(d) == list: + fd = '='.join([str(dpart) for dpart in d]) + else: + fd = str(d) + defines.append(fd) + return defines + + +def _GetDisabledWarnings(config): + return [str(i) for i in config.get('msvs_disabled_warnings', [])] + + +def _GetModuleDefinition(spec): + def_file = '' + if spec['type'] in ['shared_library', 'loadable_module', 'executable']: + def_files = [s for s in spec.get('sources', []) if s.endswith('.def')] + if len(def_files) == 1: + def_file = _FixPath(def_files[0]) + elif def_files: + raise ValueError( + 'Multiple module definition files in one target, target %s lists ' + 'multiple .def files: %s' % ( + spec['target_name'], ' '.join(def_files))) + return def_file + + +def _ConvertToolsToExpectedForm(tools): + """Convert tools to a form expected by Visual Studio. + + Arguments: + tools: A dictionnary of settings; the tool name is the key. + Returns: + A list of Tool objects. + """ + tool_list = [] + for tool, settings in tools.iteritems(): + # Collapse settings with lists. + settings_fixed = {} + for setting, value in settings.iteritems(): + if type(value) == list: + if ((tool == 'VCLinkerTool' and + setting == 'AdditionalDependencies') or + setting == 'AdditionalOptions'): + settings_fixed[setting] = ' '.join(value) + else: + settings_fixed[setting] = ';'.join(value) + else: + settings_fixed[setting] = value + # Add in this tool. + tool_list.append(MSVSProject.Tool(tool, settings_fixed)) + return tool_list + + +def _AddConfigurationToMSVS(p, spec, tools, config, config_type, config_name): + """Add to the project file the configuration specified by config. + + Arguments: + p: The target project being generated. + spec: the target project dict. + tools: A dictionnary of settings; the tool name is the key. + config: The dictionnary that defines the special processing to be done + for this configuration. + config_type: The configuration type, a number as defined by Microsoft. + config_name: The name of the configuration. + """ + attributes = _GetMSVSAttributes(spec, config, config_type) + # Add in this configuration. + tool_list = _ConvertToolsToExpectedForm(tools) + p.AddConfig(_ConfigFullName(config_name, config), + attrs=attributes, tools=tool_list) + + +def _GetMSVSAttributes(spec, config, config_type): + # Prepare configuration attributes. + prepared_attrs = {} + source_attrs = config.get('msvs_configuration_attributes', {}) + for a in source_attrs: + prepared_attrs[a] = source_attrs[a] + # Add props files. + vsprops_dirs = config.get('msvs_props', []) + vsprops_dirs = _FixPaths(vsprops_dirs) + if vsprops_dirs: + prepared_attrs['InheritedPropertySheets'] = ';'.join(vsprops_dirs) + # Set configuration type. + prepared_attrs['ConfigurationType'] = config_type + output_dir = prepared_attrs.get('OutputDirectory', + '$(SolutionDir)$(ConfigurationName)') + prepared_attrs['OutputDirectory'] = _FixPath(output_dir) + '\\' + if 'IntermediateDirectory' not in prepared_attrs: + intermediate = '$(ConfigurationName)\\obj\\$(ProjectName)' + prepared_attrs['IntermediateDirectory'] = _FixPath(intermediate) + '\\' + else: + intermediate = _FixPath(prepared_attrs['IntermediateDirectory']) + '\\' + intermediate = MSVSSettings.FixVCMacroSlashes(intermediate) + prepared_attrs['IntermediateDirectory'] = intermediate + return prepared_attrs + + +def _AddNormalizedSources(sources_set, sources_array): + sources = [_NormalizedSource(s) for s in sources_array] + sources_set.update(set(sources)) + + +def _PrepareListOfSources(spec, generator_flags, gyp_file): + """Prepare list of sources and excluded sources. + + Besides the sources specified directly in the spec, adds the gyp file so + that a change to it will cause a re-compile. Also adds appropriate sources + for actions and copies. Assumes later stage will un-exclude files which + have custom build steps attached. + + Arguments: + spec: The target dictionary containing the properties of the target. + gyp_file: The name of the gyp file. + Returns: + A pair of (list of sources, list of excluded sources). + The sources will be relative to the gyp file. + """ + sources = set() + _AddNormalizedSources(sources, spec.get('sources', [])) + excluded_sources = set() + # Add in the gyp file. + if not generator_flags.get('standalone'): + sources.add(gyp_file) + + # Add in 'action' inputs and outputs. + for a in spec.get('actions', []): + inputs = a['inputs'] + inputs = [_NormalizedSource(i) for i in inputs] + # Add all inputs to sources and excluded sources. + inputs = set(inputs) + sources.update(inputs) + excluded_sources.update(inputs) + if int(a.get('process_outputs_as_sources', False)): + _AddNormalizedSources(sources, a.get('outputs', [])) + # Add in 'copies' inputs and outputs. + for cpy in spec.get('copies', []): + _AddNormalizedSources(sources, cpy.get('files', [])) + return (sources, excluded_sources) + + +def _AdjustSourcesAndConvertToFilterHierarchy( + spec, options, gyp_dir, sources, excluded_sources, list_excluded): + """Adjusts the list of sources and excluded sources. + + Also converts the sets to lists. + + Arguments: + spec: The target dictionary containing the properties of the target. + options: Global generator options. + gyp_dir: The path to the gyp file being processed. + sources: A set of sources to be included for this project. + excluded_sources: A set of sources to be excluded for this project. + Returns: + A trio of (list of sources, list of excluded sources, + path of excluded IDL file) + """ + # Exclude excluded sources coming into the generator. + excluded_sources.update(set(spec.get('sources_excluded', []))) + # Add excluded sources into sources for good measure. + sources.update(excluded_sources) + # Convert to proper windows form. + # NOTE: sources goes from being a set to a list here. + # NOTE: excluded_sources goes from being a set to a list here. + sources = _FixPaths(sources) + # Convert to proper windows form. + excluded_sources = _FixPaths(excluded_sources) + + excluded_idl = _IdlFilesHandledNonNatively(spec, sources) + + precompiled_related = _GetPrecompileRelatedFiles(spec) + # Find the excluded ones, minus the precompiled header related ones. + fully_excluded = [i for i in excluded_sources if i not in precompiled_related] + + # Convert to folders and the right slashes. + sources = [i.split('\\') for i in sources] + sources = _ConvertSourcesToFilterHierarchy(sources, excluded=fully_excluded, + list_excluded=list_excluded) + + return sources, excluded_sources, excluded_idl + + +def _IdlFilesHandledNonNatively(spec, sources): + # If any non-native rules use 'idl' as an extension exclude idl files. + # Gather a list here to use later. + using_idl = False + for rule in spec.get('rules', []): + if rule['extension'] == 'idl' and int(rule.get('msvs_external_rule', 0)): + using_idl = True + break + if using_idl: + excluded_idl = [i for i in sources if i.endswith('.idl')] + else: + excluded_idl = [] + return excluded_idl + + +def _GetPrecompileRelatedFiles(spec): + # Gather a list of precompiled header related sources. + precompiled_related = [] + for _, config in spec['configurations'].iteritems(): + for k in precomp_keys: + f = config.get(k) + if f: + precompiled_related.append(_FixPath(f)) + return precompiled_related + + +def _ExcludeFilesFromBeingBuilt(p, spec, excluded_sources, excluded_idl, + list_excluded): + exclusions = _GetExcludedFilesFromBuild(spec, excluded_sources, excluded_idl) + for file_name, excluded_configs in exclusions.iteritems(): + if (not list_excluded and + len(excluded_configs) == len(spec['configurations'])): + # If we're not listing excluded files, then they won't appear in the + # project, so don't try to configure them to be excluded. + pass + else: + for config_name, config in excluded_configs: + p.AddFileConfig(file_name, _ConfigFullName(config_name, config), + {'ExcludedFromBuild': 'true'}) + + +def _GetExcludedFilesFromBuild(spec, excluded_sources, excluded_idl): + exclusions = {} + # Exclude excluded sources from being built. + for f in excluded_sources: + excluded_configs = [] + for config_name, config in spec['configurations'].iteritems(): + precomped = [_FixPath(config.get(i, '')) for i in precomp_keys] + # Don't do this for ones that are precompiled header related. + if f not in precomped: + excluded_configs.append((config_name, config)) + exclusions[f] = excluded_configs + # If any non-native rules use 'idl' as an extension exclude idl files. + # Exclude them now. + for f in excluded_idl: + excluded_configs = [] + for config_name, config in spec['configurations'].iteritems(): + excluded_configs.append((config_name, config)) + exclusions[f] = excluded_configs + return exclusions + + +def _AddToolFilesToMSVS(p, spec): + # Add in tool files (rules). + tool_files = set() + for _, config in spec['configurations'].iteritems(): + for f in config.get('msvs_tool_files', []): + tool_files.add(f) + for f in tool_files: + p.AddToolFile(f) + + +def _HandlePreCompiledHeaders(p, sources, spec): + # Pre-compiled header source stubs need a different compiler flag + # (generate precompiled header) and any source file not of the same + # kind (i.e. C vs. C++) as the precompiled header source stub needs + # to have use of precompiled headers disabled. + extensions_excluded_from_precompile = [] + for config_name, config in spec['configurations'].iteritems(): + source = config.get('msvs_precompiled_source') + if source: + source = _FixPath(source) + # UsePrecompiledHeader=1 for if using precompiled headers. + tool = MSVSProject.Tool('VCCLCompilerTool', + {'UsePrecompiledHeader': '1'}) + p.AddFileConfig(source, _ConfigFullName(config_name, config), + {}, tools=[tool]) + basename, extension = os.path.splitext(source) + if extension == '.c': + extensions_excluded_from_precompile = ['.cc', '.cpp', '.cxx'] + else: + extensions_excluded_from_precompile = ['.c'] + def DisableForSourceTree(source_tree): + for source in source_tree: + if isinstance(source, MSVSProject.Filter): + DisableForSourceTree(source.contents) + else: + basename, extension = os.path.splitext(source) + if extension in extensions_excluded_from_precompile: + for config_name, config in spec['configurations'].iteritems(): + tool = MSVSProject.Tool('VCCLCompilerTool', + {'UsePrecompiledHeader': '0', + 'ForcedIncludeFiles': '$(NOINHERIT)'}) + p.AddFileConfig(_FixPath(source), + _ConfigFullName(config_name, config), + {}, tools=[tool]) + # Do nothing if there was no precompiled source. + if extensions_excluded_from_precompile: + DisableForSourceTree(sources) + + +def _AddActions(actions_to_add, spec, relative_path_of_gyp_file): + # Add actions. + actions = spec.get('actions', []) + # Don't setup_env every time. When all the actions are run together in one + # batch file in VS, the PATH will grow too long. + # Membership in this set means that the cygwin environment has been set up, + # and does not need to be set up again. + have_setup_env = set() + for a in actions: + # Attach actions to the gyp file if nothing else is there. + inputs = a.get('inputs') or [relative_path_of_gyp_file] + attached_to = inputs[0] + need_setup_env = attached_to not in have_setup_env + cmd = _BuildCommandLineForRule(spec, a, has_input_path=False, + do_setup_env=need_setup_env) + have_setup_env.add(attached_to) + # Add the action. + _AddActionStep(actions_to_add, + inputs=inputs, + outputs=a.get('outputs', []), + description=a.get('message', a['action_name']), + command=cmd) + + +def _WriteMSVSUserFile(project_path, version, spec): + # Add run_as and test targets. + if 'run_as' in spec: + run_as = spec['run_as'] + action = run_as.get('action', []) + environment = run_as.get('environment', []) + working_directory = run_as.get('working_directory', '.') + elif int(spec.get('test', 0)): + action = ['$(TargetPath)', '--gtest_print_time'] + environment = [] + working_directory = '.' + else: + return # Nothing to add + # Write out the user file. + user_file = _CreateMSVSUserFile(project_path, version, spec) + for config_name, c_data in spec['configurations'].iteritems(): + user_file.AddDebugSettings(_ConfigFullName(config_name, c_data), + action, environment, working_directory) + user_file.WriteIfChanged() + + +def _AddCopies(actions_to_add, spec): + copies = _GetCopies(spec) + for inputs, outputs, cmd, description in copies: + _AddActionStep(actions_to_add, inputs=inputs, outputs=outputs, + description=description, command=cmd) + + +def _GetCopies(spec): + copies = [] + # Add copies. + for cpy in spec.get('copies', []): + for src in cpy.get('files', []): + dst = os.path.join(cpy['destination'], os.path.basename(src)) + # _AddCustomBuildToolForMSVS() will call _FixPath() on the inputs and + # outputs, so do the same for our generated command line. + if src.endswith('/'): + src_bare = src[:-1] + base_dir = posixpath.split(src_bare)[0] + outer_dir = posixpath.split(src_bare)[1] + cmd = 'cd "%s" && xcopy /e /f /y "%s" "%s\\%s\\"' % ( + _FixPath(base_dir), outer_dir, _FixPath(dst), outer_dir) + copies.append(([src], ['dummy_copies', dst], cmd, + 'Copying %s to %s' % (src, dst))) + else: + cmd = 'mkdir "%s" 2>nul & set ERRORLEVEL=0 & copy /Y "%s" "%s"' % ( + _FixPath(cpy['destination']), _FixPath(src), _FixPath(dst)) + copies.append(([src], [dst], cmd, 'Copying %s to %s' % (src, dst))) + return copies + + +def _GetPathDict(root, path): + # |path| will eventually be empty (in the recursive calls) if it was initially + # relative; otherwise it will eventually end up as '\', 'D:\', etc. + if not path or path.endswith(os.sep): + return root + parent, folder = os.path.split(path) + parent_dict = _GetPathDict(root, parent) + if folder not in parent_dict: + parent_dict[folder] = dict() + return parent_dict[folder] + + +def _DictsToFolders(base_path, bucket, flat): + # Convert to folders recursively. + children = [] + for folder, contents in bucket.iteritems(): + if type(contents) == dict: + folder_children = _DictsToFolders(os.path.join(base_path, folder), + contents, flat) + if flat: + children += folder_children + else: + folder_children = MSVSNew.MSVSFolder(os.path.join(base_path, folder), + name='(' + folder + ')', + entries=folder_children) + children.append(folder_children) + else: + children.append(contents) + return children + + +def _CollapseSingles(parent, node): + # Recursively explorer the tree of dicts looking for projects which are + # the sole item in a folder which has the same name as the project. Bring + # such projects up one level. + if (type(node) == dict and + len(node) == 1 and + node.keys()[0] == parent + '.vcproj'): + return node[node.keys()[0]] + if type(node) != dict: + return node + for child in node: + node[child] = _CollapseSingles(child, node[child]) + return node + + +def _GatherSolutionFolders(sln_projects, project_objects, flat): + root = {} + # Convert into a tree of dicts on path. + for p in sln_projects: + gyp_file, target = gyp.common.ParseQualifiedTarget(p)[0:2] + gyp_dir = os.path.dirname(gyp_file) + path_dict = _GetPathDict(root, gyp_dir) + path_dict[target + '.vcproj'] = project_objects[p] + # Walk down from the top until we hit a folder that has more than one entry. + # In practice, this strips the top-level "src/" dir from the hierarchy in + # the solution. + while len(root) == 1 and type(root[root.keys()[0]]) == dict: + root = root[root.keys()[0]] + # Collapse singles. + root = _CollapseSingles('', root) + # Merge buckets until everything is a root entry. + return _DictsToFolders('', root, flat) + + +def _GetPathOfProject(qualified_target, spec, options, msvs_version): + default_config = _GetDefaultConfiguration(spec) + proj_filename = default_config.get('msvs_existing_vcproj') + if not proj_filename: + proj_filename = (spec['target_name'] + options.suffix + + msvs_version.ProjectExtension()) + + build_file = gyp.common.BuildFile(qualified_target) + proj_path = os.path.join(os.path.dirname(build_file), proj_filename) + fix_prefix = None + if options.generator_output: + project_dir_path = os.path.dirname(os.path.abspath(proj_path)) + proj_path = os.path.join(options.generator_output, proj_path) + fix_prefix = gyp.common.RelativePath(project_dir_path, + os.path.dirname(proj_path)) + return proj_path, fix_prefix + + +def _GetPlatformOverridesOfProject(spec): + # Prepare a dict indicating which project configurations are used for which + # solution configurations for this target. + config_platform_overrides = {} + for config_name, c in spec['configurations'].iteritems(): + config_fullname = _ConfigFullName(config_name, c) + platform = c.get('msvs_target_platform', _ConfigPlatform(c)) + fixed_config_fullname = '%s|%s' % ( + _ConfigBaseName(config_name, _ConfigPlatform(c)), platform) + config_platform_overrides[config_fullname] = fixed_config_fullname + return config_platform_overrides + + +def _CreateProjectObjects(target_list, target_dicts, options, msvs_version): + """Create a MSVSProject object for the targets found in target list. + + Arguments: + target_list: the list of targets to generate project objects for. + target_dicts: the dictionary of specifications. + options: global generator options. + msvs_version: the MSVSVersion object. + Returns: + A set of created projects, keyed by target. + """ + global fixpath_prefix + # Generate each project. + projects = {} + for qualified_target in target_list: + spec = target_dicts[qualified_target] + if spec['toolset'] != 'target': + raise Exception( + 'Multiple toolsets not supported in msvs build (target %s)' % + qualified_target) + proj_path, fixpath_prefix = _GetPathOfProject(qualified_target, spec, + options, msvs_version) + guid = _GetGuidOfProject(proj_path, spec) + overrides = _GetPlatformOverridesOfProject(spec) + build_file = gyp.common.BuildFile(qualified_target) + # Create object for this project. + obj = MSVSNew.MSVSProject( + _FixPath(proj_path), + name=spec['target_name'], + guid=guid, + spec=spec, + build_file=build_file, + config_platform_overrides=overrides, + fixpath_prefix=fixpath_prefix) + # Set project toolset if any (MS build only) + if msvs_version.UsesVcxproj(): + obj.set_msbuild_toolset( + _GetMsbuildToolsetOfProject(proj_path, spec, msvs_version)) + projects[qualified_target] = obj + # Set all the dependencies + for project in projects.values(): + deps = project.spec.get('dependencies', []) + deps = [projects[d] for d in deps] + project.set_dependencies(deps) + return projects + + +def CalculateVariables(default_variables, params): + """Generated variables that require params to be known.""" + + generator_flags = params.get('generator_flags', {}) + + # Select project file format version (if unset, default to auto detecting). + msvs_version = MSVSVersion.SelectVisualStudioVersion( + generator_flags.get('msvs_version', 'auto')) + # Stash msvs_version for later (so we don't have to probe the system twice). + params['msvs_version'] = msvs_version + + # Set a variable so conditions can be based on msvs_version. + default_variables['MSVS_VERSION'] = msvs_version.ShortName() + + # To determine processor word size on Windows, in addition to checking + # PROCESSOR_ARCHITECTURE (which reflects the word size of the current + # process), it is also necessary to check PROCESSOR_ARCITEW6432 (which + # contains the actual word size of the system when running thru WOW64). + if (os.environ.get('PROCESSOR_ARCHITECTURE', '').find('64') >= 0 or + os.environ.get('PROCESSOR_ARCHITEW6432', '').find('64') >= 0): + default_variables['MSVS_OS_BITS'] = 64 + else: + default_variables['MSVS_OS_BITS'] = 32 + + +def _ShardName(name, number): + """Add a shard number to the end of a target. + + Arguments: + name: name of the target (foo#target) + number: shard number + Returns: + Target name with shard added (foo_1#target) + """ + parts = name.rsplit('#', 1) + parts[0] = '%s_%d' % (parts[0], number) + return '#'.join(parts) + + +def _ShardTargets(target_list, target_dicts): + """Shard some targets apart to work around the linkers limits. + + Arguments: + target_list: List of target pairs: 'base/base.gyp:base'. + target_dicts: Dict of target properties keyed on target pair. + Returns: + Tuple of the new sharded versions of the inputs. + """ + # Gather the targets to shard, and how many pieces. + targets_to_shard = {} + for t in target_dicts: + shards = int(target_dicts[t].get('msvs_shard', 0)) + if shards: + targets_to_shard[t] = shards + # Shard target_list. + new_target_list = [] + for t in target_list: + if t in targets_to_shard: + for i in range(targets_to_shard[t]): + new_target_list.append(_ShardName(t, i)) + else: + new_target_list.append(t) + # Shard target_dict. + new_target_dicts = {} + for t in target_dicts: + if t in targets_to_shard: + for i in range(targets_to_shard[t]): + name = _ShardName(t, i) + new_target_dicts[name] = copy.copy(target_dicts[t]) + new_target_dicts[name]['target_name'] = _ShardName( + new_target_dicts[name]['target_name'], i) + sources = new_target_dicts[name].get('sources', []) + new_sources = [] + for pos in range(i, len(sources), targets_to_shard[t]): + new_sources.append(sources[pos]) + new_target_dicts[name]['sources'] = new_sources + else: + new_target_dicts[t] = target_dicts[t] + # Shard dependencies. + for t in new_target_dicts: + dependencies = copy.copy(new_target_dicts[t].get('dependencies', [])) + new_dependencies = [] + for d in dependencies: + if d in targets_to_shard: + for i in range(targets_to_shard[d]): + new_dependencies.append(_ShardName(d, i)) + else: + new_dependencies.append(d) + new_target_dicts[t]['dependencies'] = new_dependencies + + return (new_target_list, new_target_dicts) + + +def GenerateOutput(target_list, target_dicts, data, params): + """Generate .sln and .vcproj files. + + This is the entry point for this generator. + Arguments: + target_list: List of target pairs: 'base/base.gyp:base'. + target_dicts: Dict of target properties keyed on target pair. + data: Dictionary containing per .gyp data. + """ + global fixpath_prefix + + options = params['options'] + + # Get the project file format version back out of where we stashed it in + # GeneratorCalculatedVariables. + msvs_version = params['msvs_version'] + + generator_flags = params.get('generator_flags', {}) + + # Optionally shard targets marked with 'msvs_shard': SHARD_COUNT. + (target_list, target_dicts) = _ShardTargets(target_list, target_dicts) + + # Prepare the set of configurations. + configs = set() + for qualified_target in target_list: + spec = target_dicts[qualified_target] + for config_name, config in spec['configurations'].iteritems(): + configs.add(_ConfigFullName(config_name, config)) + configs = list(configs) + + # Figure out all the projects that will be generated and their guids + project_objects = _CreateProjectObjects(target_list, target_dicts, options, + msvs_version) + + # Generate each project. + missing_sources = [] + for project in project_objects.values(): + fixpath_prefix = project.fixpath_prefix + missing_sources.extend(_GenerateProject(project, options, msvs_version, + generator_flags)) + fixpath_prefix = None + + for build_file in data: + # Validate build_file extension + if not build_file.endswith('.gyp'): + continue + sln_path = os.path.splitext(build_file)[0] + options.suffix + '.sln' + if options.generator_output: + sln_path = os.path.join(options.generator_output, sln_path) + # Get projects in the solution, and their dependents. + sln_projects = gyp.common.BuildFileTargets(target_list, build_file) + sln_projects += gyp.common.DeepDependencyTargets(target_dicts, sln_projects) + # Create folder hierarchy. + root_entries = _GatherSolutionFolders( + sln_projects, project_objects, flat=msvs_version.FlatSolution()) + # Create solution. + sln = MSVSNew.MSVSSolution(sln_path, + entries=root_entries, + variants=configs, + websiteProperties=False, + version=msvs_version) + sln.Write() + + if missing_sources: + error_message = "Missing input files:\n" + \ + '\n'.join(set(missing_sources)) + if generator_flags.get('msvs_error_on_missing_sources', False): + raise Exception(error_message) + else: + print >>sys.stdout, "Warning: " + error_message + + +def _GenerateMSBuildFiltersFile(filters_path, source_files, + extension_to_rule_name): + """Generate the filters file. + + This file is used by Visual Studio to organize the presentation of source + files into folders. + + Arguments: + filters_path: The path of the file to be created. + source_files: The hierarchical structure of all the sources. + extension_to_rule_name: A dictionary mapping file extensions to rules. + """ + filter_group = [] + source_group = [] + _AppendFiltersForMSBuild('', source_files, extension_to_rule_name, + filter_group, source_group) + if filter_group: + content = ['Project', + {'ToolsVersion': '4.0', + 'xmlns': 'http://schemas.microsoft.com/developer/msbuild/2003' + }, + ['ItemGroup'] + filter_group, + ['ItemGroup'] + source_group + ] + easy_xml.WriteXmlIfChanged(content, filters_path, pretty=True, win32=True) + elif os.path.exists(filters_path): + # We don't need this filter anymore. Delete the old filter file. + os.unlink(filters_path) + + +def _AppendFiltersForMSBuild(parent_filter_name, sources, + extension_to_rule_name, + filter_group, source_group): + """Creates the list of filters and sources to be added in the filter file. + + Args: + parent_filter_name: The name of the filter under which the sources are + found. + sources: The hierarchy of filters and sources to process. + extension_to_rule_name: A dictionary mapping file extensions to rules. + filter_group: The list to which filter entries will be appended. + source_group: The list to which source entries will be appeneded. + """ + for source in sources: + if isinstance(source, MSVSProject.Filter): + # We have a sub-filter. Create the name of that sub-filter. + if not parent_filter_name: + filter_name = source.name + else: + filter_name = '%s\\%s' % (parent_filter_name, source.name) + # Add the filter to the group. + filter_group.append( + ['Filter', {'Include': filter_name}, + ['UniqueIdentifier', MSVSNew.MakeGuid(source.name)]]) + # Recurse and add its dependents. + _AppendFiltersForMSBuild(filter_name, source.contents, + extension_to_rule_name, + filter_group, source_group) + else: + # It's a source. Create a source entry. + _, element = _MapFileToMsBuildSourceType(source, extension_to_rule_name) + source_entry = [element, {'Include': source}] + # Specify the filter it is part of, if any. + if parent_filter_name: + source_entry.append(['Filter', parent_filter_name]) + source_group.append(source_entry) + + +def _MapFileToMsBuildSourceType(source, extension_to_rule_name): + """Returns the group and element type of the source file. + + Arguments: + source: The source file name. + extension_to_rule_name: A dictionary mapping file extensions to rules. + + Returns: + A pair of (group this file should be part of, the label of element) + """ + _, ext = os.path.splitext(source) + if ext in extension_to_rule_name: + group = 'rule' + element = extension_to_rule_name[ext] + elif ext in ['.cc', '.cpp', '.c', '.cxx']: + group = 'compile' + element = 'ClCompile' + elif ext in ['.h', '.hxx']: + group = 'include' + element = 'ClInclude' + elif ext == '.rc': + group = 'resource' + element = 'ResourceCompile' + elif ext == '.idl': + group = 'midl' + element = 'Midl' + else: + group = 'none' + element = 'None' + return (group, element) + + +def _GenerateRulesForMSBuild(output_dir, options, spec, + sources, excluded_sources, + props_files_of_rules, targets_files_of_rules, + actions_to_add, extension_to_rule_name): + # MSBuild rules are implemented using three files: an XML file, a .targets + # file and a .props file. + # See http://blogs.msdn.com/b/vcblog/archive/2010/04/21/quick-help-on-vs2010-custom-build-rule.aspx + # for more details. + rules = spec.get('rules', []) + rules_native = [r for r in rules if not int(r.get('msvs_external_rule', 0))] + rules_external = [r for r in rules if int(r.get('msvs_external_rule', 0))] + + msbuild_rules = [] + for rule in rules_native: + # Skip a rule with no action and no inputs. + if 'action' not in rule and not rule.get('rule_sources', []): + continue + msbuild_rule = MSBuildRule(rule, spec) + msbuild_rules.append(msbuild_rule) + extension_to_rule_name[msbuild_rule.extension] = msbuild_rule.rule_name + if msbuild_rules: + base = spec['target_name'] + options.suffix + props_name = base + '.props' + targets_name = base + '.targets' + xml_name = base + '.xml' + + props_files_of_rules.add(props_name) + targets_files_of_rules.add(targets_name) + + props_path = os.path.join(output_dir, props_name) + targets_path = os.path.join(output_dir, targets_name) + xml_path = os.path.join(output_dir, xml_name) + + _GenerateMSBuildRulePropsFile(props_path, msbuild_rules) + _GenerateMSBuildRuleTargetsFile(targets_path, msbuild_rules) + _GenerateMSBuildRuleXmlFile(xml_path, msbuild_rules) + + if rules_external: + _GenerateExternalRules(rules_external, output_dir, spec, + sources, options, actions_to_add) + _AdjustSourcesForRules(rules, sources, excluded_sources) + + +class MSBuildRule(object): + """Used to store information used to generate an MSBuild rule. + + Attributes: + rule_name: The rule name, sanitized to use in XML. + target_name: The name of the target. + after_targets: The name of the AfterTargets element. + before_targets: The name of the BeforeTargets element. + depends_on: The name of the DependsOn element. + compute_output: The name of the ComputeOutput element. + dirs_to_make: The name of the DirsToMake element. + inputs: The name of the _inputs element. + tlog: The name of the _tlog element. + extension: The extension this rule applies to. + description: The message displayed when this rule is invoked. + additional_dependencies: A string listing additional dependencies. + outputs: The outputs of this rule. + command: The command used to run the rule. + """ + + def __init__(self, rule, spec): + self.display_name = rule['rule_name'] + # Assure that the rule name is only characters and numbers + self.rule_name = re.sub(r'\W', '_', self.display_name) + # Create the various element names, following the example set by the + # Visual Studio 2008 to 2010 conversion. I don't know if VS2010 + # is sensitive to the exact names. + self.target_name = '_' + self.rule_name + self.after_targets = self.rule_name + 'AfterTargets' + self.before_targets = self.rule_name + 'BeforeTargets' + self.depends_on = self.rule_name + 'DependsOn' + self.compute_output = 'Compute%sOutput' % self.rule_name + self.dirs_to_make = self.rule_name + 'DirsToMake' + self.inputs = self.rule_name + '_inputs' + self.tlog = self.rule_name + '_tlog' + self.extension = rule['extension'] + if not self.extension.startswith('.'): + self.extension = '.' + self.extension + + self.description = MSVSSettings.ConvertVCMacrosToMSBuild( + rule.get('message', self.rule_name)) + old_additional_dependencies = _FixPaths(rule.get('inputs', [])) + self.additional_dependencies = ( + ';'.join([MSVSSettings.ConvertVCMacrosToMSBuild(i) + for i in old_additional_dependencies])) + old_outputs = _FixPaths(rule.get('outputs', [])) + self.outputs = ';'.join([MSVSSettings.ConvertVCMacrosToMSBuild(i) + for i in old_outputs]) + old_command = _BuildCommandLineForRule(spec, rule, has_input_path=True, + do_setup_env=True) + self.command = MSVSSettings.ConvertVCMacrosToMSBuild(old_command) + + +def _GenerateMSBuildRulePropsFile(props_path, msbuild_rules): + """Generate the .props file.""" + content = ['Project', + {'xmlns': 'http://schemas.microsoft.com/developer/msbuild/2003'}] + for rule in msbuild_rules: + content.extend([ + ['PropertyGroup', + {'Condition': "'$(%s)' == '' and '$(%s)' == '' and " + "'$(ConfigurationType)' != 'Makefile'" % (rule.before_targets, + rule.after_targets) + }, + [rule.before_targets, 'Midl'], + [rule.after_targets, 'CustomBuild'], + ], + ['PropertyGroup', + [rule.depends_on, + {'Condition': "'$(ConfigurationType)' != 'Makefile'"}, + '_SelectedFiles;$(%s)' % rule.depends_on + ], + ], + ['ItemDefinitionGroup', + [rule.rule_name, + ['CommandLineTemplate', rule.command], + ['Outputs', rule.outputs], + ['ExecutionDescription', rule.description], + ['AdditionalDependencies', rule.additional_dependencies], + ], + ] + ]) + easy_xml.WriteXmlIfChanged(content, props_path, pretty=True, win32=True) + + +def _GenerateMSBuildRuleTargetsFile(targets_path, msbuild_rules): + """Generate the .targets file.""" + content = ['Project', + {'xmlns': 'http://schemas.microsoft.com/developer/msbuild/2003' + } + ] + item_group = [ + 'ItemGroup', + ['PropertyPageSchema', + {'Include': '$(MSBuildThisFileDirectory)$(MSBuildThisFileName).xml'} + ] + ] + for rule in msbuild_rules: + item_group.append( + ['AvailableItemName', + {'Include': rule.rule_name}, + ['Targets', rule.target_name], + ]) + content.append(item_group) + + for rule in msbuild_rules: + content.append( + ['UsingTask', + {'TaskName': rule.rule_name, + 'TaskFactory': 'XamlTaskFactory', + 'AssemblyName': 'Microsoft.Build.Tasks.v4.0' + }, + ['Task', '$(MSBuildThisFileDirectory)$(MSBuildThisFileName).xml'], + ]) + for rule in msbuild_rules: + rule_name = rule.rule_name + target_outputs = '%%(%s.Outputs)' % rule_name + target_inputs = ('%%(%s.Identity);%%(%s.AdditionalDependencies);' + '$(MSBuildProjectFile)') % (rule_name, rule_name) + rule_inputs = '%%(%s.Identity)' % rule_name + extension_condition = ("'%(Extension)'=='.obj' or " + "'%(Extension)'=='.res' or " + "'%(Extension)'=='.rsc' or " + "'%(Extension)'=='.lib'") + remove_section = [ + 'ItemGroup', + {'Condition': "'@(SelectedFiles)' != ''"}, + [rule_name, + {'Remove': '@(%s)' % rule_name, + 'Condition': "'%(Identity)' != '@(SelectedFiles)'" + } + ] + ] + inputs_section = [ + 'ItemGroup', + [rule.inputs, {'Include': '%%(%s.AdditionalDependencies)' % rule_name}] + ] + logging_section = [ + 'ItemGroup', + [rule.tlog, + {'Include': '%%(%s.Outputs)' % rule_name, + 'Condition': ("'%%(%s.Outputs)' != '' and " + "'%%(%s.ExcludedFromBuild)' != 'true'" % + (rule_name, rule_name)) + }, + ['Source', "@(%s, '|')" % rule_name], + ['Inputs', "@(%s -> '%%(Fullpath)', ';')" % rule.inputs], + ], + ] + message_section = [ + 'Message', + {'Importance': 'High', + 'Text': '%%(%s.ExecutionDescription)' % rule_name + } + ] + write_tlog_section = [ + 'WriteLinesToFile', + {'Condition': "'@(%s)' != '' and '%%(%s.ExcludedFromBuild)' != " + "'true'" % (rule.tlog, rule.tlog), + 'File': '$(IntDir)$(ProjectName).write.1.tlog', + 'Lines': "^%%(%s.Source);@(%s->'%%(Fullpath)')" % (rule.tlog, + rule.tlog) + } + ] + read_tlog_section = [ + 'WriteLinesToFile', + {'Condition': "'@(%s)' != '' and '%%(%s.ExcludedFromBuild)' != " + "'true'" % (rule.tlog, rule.tlog), + 'File': '$(IntDir)$(ProjectName).read.1.tlog', + 'Lines': "^%%(%s.Source);%%(%s.Inputs)" % (rule.tlog, rule.tlog) + } + ] + command_and_input_section = [ + rule_name, + {'Condition': "'@(%s)' != '' and '%%(%s.ExcludedFromBuild)' != " + "'true'" % (rule_name, rule_name), + 'CommandLineTemplate': '%%(%s.CommandLineTemplate)' % rule_name, + 'AdditionalOptions': '%%(%s.AdditionalOptions)' % rule_name, + 'Inputs': rule_inputs + } + ] + content.extend([ + ['Target', + {'Name': rule.target_name, + 'BeforeTargets': '$(%s)' % rule.before_targets, + 'AfterTargets': '$(%s)' % rule.after_targets, + 'Condition': "'@(%s)' != ''" % rule_name, + 'DependsOnTargets': '$(%s);%s' % (rule.depends_on, + rule.compute_output), + 'Outputs': target_outputs, + 'Inputs': target_inputs + }, + remove_section, + inputs_section, + logging_section, + message_section, + write_tlog_section, + read_tlog_section, + command_and_input_section, + ], + ['PropertyGroup', + ['ComputeLinkInputsTargets', + '$(ComputeLinkInputsTargets);', + '%s;' % rule.compute_output + ], + ['ComputeLibInputsTargets', + '$(ComputeLibInputsTargets);', + '%s;' % rule.compute_output + ], + ], + ['Target', + {'Name': rule.compute_output, + 'Condition': "'@(%s)' != ''" % rule_name + }, + ['ItemGroup', + [rule.dirs_to_make, + {'Condition': "'@(%s)' != '' and " + "'%%(%s.ExcludedFromBuild)' != 'true'" % (rule_name, rule_name), + 'Include': '%%(%s.Outputs)' % rule_name + } + ], + ['Link', + {'Include': '%%(%s.Identity)' % rule.dirs_to_make, + 'Condition': extension_condition + } + ], + ['Lib', + {'Include': '%%(%s.Identity)' % rule.dirs_to_make, + 'Condition': extension_condition + } + ], + ['ImpLib', + {'Include': '%%(%s.Identity)' % rule.dirs_to_make, + 'Condition': extension_condition + } + ], + ], + ['MakeDir', + {'Directories': ("@(%s->'%%(RootDir)%%(Directory)')" % + rule.dirs_to_make) + } + ] + ], + ]) + easy_xml.WriteXmlIfChanged(content, targets_path, pretty=True, win32=True) + + +def _GenerateMSBuildRuleXmlFile(xml_path, msbuild_rules): + # Generate the .xml file + content = [ + 'ProjectSchemaDefinitions', + {'xmlns': ('clr-namespace:Microsoft.Build.Framework.XamlTypes;' + 'assembly=Microsoft.Build.Framework'), + 'xmlns:x': 'http://schemas.microsoft.com/winfx/2006/xaml', + 'xmlns:sys': 'clr-namespace:System;assembly=mscorlib', + 'xmlns:transformCallback': + 'Microsoft.Cpp.Dev10.ConvertPropertyCallback' + } + ] + for rule in msbuild_rules: + content.extend([ + ['Rule', + {'Name': rule.rule_name, + 'PageTemplate': 'tool', + 'DisplayName': rule.display_name, + 'Order': '200' + }, + ['Rule.DataSource', + ['DataSource', + {'Persistence': 'ProjectFile', + 'ItemType': rule.rule_name + } + ] + ], + ['Rule.Categories', + ['Category', + {'Name': 'General'}, + ['Category.DisplayName', + ['sys:String', 'General'], + ], + ], + ['Category', + {'Name': 'Command Line', + 'Subtype': 'CommandLine' + }, + ['Category.DisplayName', + ['sys:String', 'Command Line'], + ], + ], + ], + ['StringListProperty', + {'Name': 'Inputs', + 'Category': 'Command Line', + 'IsRequired': 'true', + 'Switch': ' ' + }, + ['StringListProperty.DataSource', + ['DataSource', + {'Persistence': 'ProjectFile', + 'ItemType': rule.rule_name, + 'SourceType': 'Item' + } + ] + ], + ], + ['StringProperty', + {'Name': 'CommandLineTemplate', + 'DisplayName': 'Command Line', + 'Visible': 'False', + 'IncludeInCommandLine': 'False' + } + ], + ['DynamicEnumProperty', + {'Name': rule.before_targets, + 'Category': 'General', + 'EnumProvider': 'Targets', + 'IncludeInCommandLine': 'False' + }, + ['DynamicEnumProperty.DisplayName', + ['sys:String', 'Execute Before'], + ], + ['DynamicEnumProperty.Description', + ['sys:String', 'Specifies the targets for the build customization' + ' to run before.' + ], + ], + ['DynamicEnumProperty.ProviderSettings', + ['NameValuePair', + {'Name': 'Exclude', + 'Value': '^%s|^Compute' % rule.before_targets + } + ] + ], + ['DynamicEnumProperty.DataSource', + ['DataSource', + {'Persistence': 'ProjectFile', + 'HasConfigurationCondition': 'true' + } + ] + ], + ], + ['DynamicEnumProperty', + {'Name': rule.after_targets, + 'Category': 'General', + 'EnumProvider': 'Targets', + 'IncludeInCommandLine': 'False' + }, + ['DynamicEnumProperty.DisplayName', + ['sys:String', 'Execute After'], + ], + ['DynamicEnumProperty.Description', + ['sys:String', ('Specifies the targets for the build customization' + ' to run after.') + ], + ], + ['DynamicEnumProperty.ProviderSettings', + ['NameValuePair', + {'Name': 'Exclude', + 'Value': '^%s|^Compute' % rule.after_targets + } + ] + ], + ['DynamicEnumProperty.DataSource', + ['DataSource', + {'Persistence': 'ProjectFile', + 'ItemType': '', + 'HasConfigurationCondition': 'true' + } + ] + ], + ], + ['StringListProperty', + {'Name': 'Outputs', + 'DisplayName': 'Outputs', + 'Visible': 'False', + 'IncludeInCommandLine': 'False' + } + ], + ['StringProperty', + {'Name': 'ExecutionDescription', + 'DisplayName': 'Execution Description', + 'Visible': 'False', + 'IncludeInCommandLine': 'False' + } + ], + ['StringListProperty', + {'Name': 'AdditionalDependencies', + 'DisplayName': 'Additional Dependencies', + 'IncludeInCommandLine': 'False', + 'Visible': 'false' + } + ], + ['StringProperty', + {'Subtype': 'AdditionalOptions', + 'Name': 'AdditionalOptions', + 'Category': 'Command Line' + }, + ['StringProperty.DisplayName', + ['sys:String', 'Additional Options'], + ], + ['StringProperty.Description', + ['sys:String', 'Additional Options'], + ], + ], + ], + ['ItemType', + {'Name': rule.rule_name, + 'DisplayName': rule.display_name + } + ], + ['FileExtension', + {'Name': '*' + rule.extension, + 'ContentType': rule.rule_name + } + ], + ['ContentType', + {'Name': rule.rule_name, + 'DisplayName': '', + 'ItemType': rule.rule_name + } + ] + ]) + easy_xml.WriteXmlIfChanged(content, xml_path, pretty=True, win32=True) + + +def _GetConfigurationAndPlatform(name, settings): + configuration = name.rsplit('_', 1)[0] + platform = settings.get('msvs_configuration_platform', 'Win32') + return (configuration, platform) + + +def _GetConfigurationCondition(name, settings): + return (r"'$(Configuration)|$(Platform)'=='%s|%s'" % + _GetConfigurationAndPlatform(name, settings)) + + +def _GetMSBuildProjectConfigurations(configurations): + group = ['ItemGroup', {'Label': 'ProjectConfigurations'}] + for (name, settings) in sorted(configurations.iteritems()): + configuration, platform = _GetConfigurationAndPlatform(name, settings) + designation = '%s|%s' % (configuration, platform) + group.append( + ['ProjectConfiguration', {'Include': designation}, + ['Configuration', configuration], + ['Platform', platform]]) + return [group] + + +def _GetMSBuildGlobalProperties(spec, guid, gyp_file_name): + namespace = os.path.splitext(gyp_file_name)[0] + return [ + ['PropertyGroup', {'Label': 'Globals'}, + ['ProjectGuid', guid], + ['Keyword', 'Win32Proj'], + ['RootNamespace', namespace], + ] + ] + + +def _GetMSBuildConfigurationDetails(spec, build_file): + properties = {} + for name, settings in spec['configurations'].iteritems(): + msbuild_attributes = _GetMSBuildAttributes(spec, settings, build_file) + condition = _GetConfigurationCondition(name, settings) + character_set = msbuild_attributes.get('CharacterSet') + _AddConditionalProperty(properties, condition, 'ConfigurationType', + msbuild_attributes['ConfigurationType']) + if character_set: + _AddConditionalProperty(properties, condition, 'CharacterSet', + character_set) + return _GetMSBuildPropertyGroup(spec, 'Configuration', properties) + + +def _GetMSBuildLocalProperties(msbuild_toolset): + # Currently the only local property we support is PlatformToolset + properties = {} + if msbuild_toolset: + properties = [ + ['PropertyGroup', {'Label': 'Locals'}, + ['PlatformToolset', msbuild_toolset], + ] + ] + return properties + + +def _GetMSBuildPropertySheets(configurations): + user_props = r'$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props' + additional_props = {} + props_specified = False + for name, settings in sorted(configurations.iteritems()): + configuration = _GetConfigurationCondition(name, settings) + if settings.has_key('msbuild_props'): + additional_props[configuration] = _FixPaths(settings['msbuild_props']) + props_specified = True + else: + additional_props[configuration] = '' + + if not props_specified: + return [ + ['ImportGroup', + {'Label': 'PropertySheets'}, + ['Import', + {'Project': user_props, + 'Condition': "exists('%s')" % user_props, + 'Label': 'LocalAppDataPlatform' + } + ] + ] + ] + else: + sheets = [] + for condition, props in additional_props.iteritems(): + import_group = [ + 'ImportGroup', + {'Label': 'PropertySheets', + 'Condition': condition + }, + ['Import', + {'Project': user_props, + 'Condition': "exists('%s')" % user_props, + 'Label': 'LocalAppDataPlatform' + } + ] + ] + for props_file in props: + import_group.append(['Import', {'Project':props_file}]) + sheets.append(import_group) + return sheets + +def _ConvertMSVSBuildAttributes(spec, config, build_file): + config_type = _GetMSVSConfigurationType(spec, build_file) + msvs_attributes = _GetMSVSAttributes(spec, config, config_type) + msbuild_attributes = {} + for a in msvs_attributes: + if a in ['IntermediateDirectory', 'OutputDirectory']: + directory = MSVSSettings.ConvertVCMacrosToMSBuild(msvs_attributes[a]) + if not directory.endswith('\\'): + directory += '\\' + msbuild_attributes[a] = directory + elif a == 'CharacterSet': + msbuild_attributes[a] = _ConvertMSVSCharacterSet(msvs_attributes[a]) + elif a == 'ConfigurationType': + msbuild_attributes[a] = _ConvertMSVSConfigurationType(msvs_attributes[a]) + else: + print 'Warning: Do not know how to convert MSVS attribute ' + a + return msbuild_attributes + + +def _ConvertMSVSCharacterSet(char_set): + if char_set.isdigit(): + char_set = { + '0': 'MultiByte', + '1': 'Unicode', + '2': 'MultiByte', + }[char_set] + return char_set + + +def _ConvertMSVSConfigurationType(config_type): + if config_type.isdigit(): + config_type = { + '1': 'Application', + '2': 'DynamicLibrary', + '4': 'StaticLibrary', + '10': 'Utility' + }[config_type] + return config_type + + +def _GetMSBuildAttributes(spec, config, build_file): + if 'msbuild_configuration_attributes' not in config: + msbuild_attributes = _ConvertMSVSBuildAttributes(spec, config, build_file) + + else: + config_type = _GetMSVSConfigurationType(spec, build_file) + config_type = _ConvertMSVSConfigurationType(config_type) + msbuild_attributes = config.get('msbuild_configuration_attributes', {}) + msbuild_attributes['ConfigurationType'] = config_type + output_dir = msbuild_attributes.get('OutputDirectory', + '$(SolutionDir)$(Configuration)\\') + msbuild_attributes['OutputDirectory'] = _FixPath(output_dir) + if 'IntermediateDirectory' not in msbuild_attributes: + intermediate = '$(Configuration)\\' + msbuild_attributes['IntermediateDirectory'] = _FixPath(intermediate) + if 'CharacterSet' in msbuild_attributes: + msbuild_attributes['CharacterSet'] = _ConvertMSVSCharacterSet( + msbuild_attributes['CharacterSet']) + if 'TargetName' not in msbuild_attributes: + prefix = spec.get('product_prefix', '') + product_name = spec.get('product_name', '$(ProjectName)') + target_name = prefix + product_name + msbuild_attributes['TargetName'] = target_name + + # Make sure that 'TargetPath' matches 'Lib.OutputFile' or 'Link.OutputFile' + # (depending on the tool used) to avoid MSB8012 warning. + msbuild_tool_map = { + 'executable': 'Link', + 'shared_library': 'Link', + 'loadable_module': 'Link', + 'static_library': 'Lib', + } + msbuild_tool = msbuild_tool_map.get(spec['type']) + if msbuild_tool: + msbuild_settings = config['finalized_msbuild_settings'] + out_file = msbuild_settings[msbuild_tool].get('OutputFile') + if out_file: + msbuild_attributes['TargetPath'] = _FixPath(out_file) + + return msbuild_attributes + + +def _GetMSBuildConfigurationGlobalProperties(spec, configurations, build_file): + # TODO(jeanluc) We could optimize out the following and do it only if + # there are actions. + # TODO(jeanluc) Handle the equivalent of setting 'CYGWIN=nontsec'. + new_paths = [] + cygwin_dirs = spec.get('msvs_cygwin_dirs', ['.'])[0] + if cygwin_dirs: + cyg_path = '$(MSBuildProjectDirectory)\\%s\\bin\\' % _FixPath(cygwin_dirs) + new_paths.append(cyg_path) + # TODO(jeanluc) Change the convention to have both a cygwin_dir and a + # python_dir. + python_path = cyg_path.replace('cygwin\\bin', 'python_26') + new_paths.append(python_path) + if new_paths: + new_paths = '$(ExecutablePath);' + ';'.join(new_paths) + + properties = {} + for (name, configuration) in sorted(configurations.iteritems()): + condition = _GetConfigurationCondition(name, configuration) + attributes = _GetMSBuildAttributes(spec, configuration, build_file) + msbuild_settings = configuration['finalized_msbuild_settings'] + _AddConditionalProperty(properties, condition, 'IntDir', + attributes['IntermediateDirectory']) + _AddConditionalProperty(properties, condition, 'OutDir', + attributes['OutputDirectory']) + _AddConditionalProperty(properties, condition, 'TargetName', + attributes['TargetName']) + + if attributes.get('TargetPath'): + _AddConditionalProperty(properties, condition, 'TargetPath', + attributes['TargetPath']) + + if new_paths: + _AddConditionalProperty(properties, condition, 'ExecutablePath', + new_paths) + tool_settings = msbuild_settings.get('', {}) + for name, value in sorted(tool_settings.iteritems()): + formatted_value = _GetValueFormattedForMSBuild('', name, value) + _AddConditionalProperty(properties, condition, name, formatted_value) + return _GetMSBuildPropertyGroup(spec, None, properties) + + +def _AddConditionalProperty(properties, condition, name, value): + """Adds a property / conditional value pair to a dictionary. + + Arguments: + properties: The dictionary to be modified. The key is the name of the + property. The value is itself a dictionary; its key is the value and + the value a list of condition for which this value is true. + condition: The condition under which the named property has the value. + name: The name of the property. + value: The value of the property. + """ + if name not in properties: + properties[name] = {} + values = properties[name] + if value not in values: + values[value] = [] + conditions = values[value] + conditions.append(condition) + + +# Regex for msvs variable references ( i.e. $(FOO) ). +MSVS_VARIABLE_REFERENCE = re.compile('\$\(([a-zA-Z_][a-zA-Z0-9_]*)\)') + + +def _GetMSBuildPropertyGroup(spec, label, properties): + """Returns a PropertyGroup definition for the specified properties. + + Arguments: + spec: The target project dict. + label: An optional label for the PropertyGroup. + properties: The dictionary to be converted. The key is the name of the + property. The value is itself a dictionary; its key is the value and + the value a list of condition for which this value is true. + """ + group = ['PropertyGroup'] + if label: + group.append({'Label': label}) + num_configurations = len(spec['configurations']) + def GetEdges(node): + # Use a definition of edges such that user_of_variable -> used_varible. + # This happens to be easier in this case, since a variable's + # definition contains all variables it references in a single string. + edges = set() + for value in sorted(properties[node].keys()): + # Add to edges all $(...) references to variables. + # + # Variable references that refer to names not in properties are excluded + # These can exist for instance to refer built in definitions like + # $(SolutionDir). + # + # Self references are ignored. Self reference is used in a few places to + # append to the default value. I.e. PATH=$(PATH);other_path + edges.update(set([v for v in MSVS_VARIABLE_REFERENCE.findall(value) + if v in properties and v != node])) + return edges + properties_ordered = gyp.common.TopologicallySorted( + properties.keys(), GetEdges) + # Walk properties in the reverse of a topological sort on + # user_of_variable -> used_variable as this ensures variables are + # defined before they are used. + # NOTE: reverse(topsort(DAG)) = topsort(reverse_edges(DAG)) + for name in reversed(properties_ordered): + values = properties[name] + for value, conditions in sorted(values.iteritems()): + if len(conditions) == num_configurations: + # If the value is the same all configurations, + # just add one unconditional entry. + group.append([name, value]) + else: + for condition in conditions: + group.append([name, {'Condition': condition}, value]) + return [group] + + +def _GetMSBuildToolSettingsSections(spec, configurations): + groups = [] + for (name, configuration) in sorted(configurations.iteritems()): + msbuild_settings = configuration['finalized_msbuild_settings'] + group = ['ItemDefinitionGroup', + {'Condition': _GetConfigurationCondition(name, configuration)} + ] + for tool_name, tool_settings in sorted(msbuild_settings.iteritems()): + # Skip the tool named '' which is a holder of global settings handled + # by _GetMSBuildConfigurationGlobalProperties. + if tool_name: + if tool_settings: + tool = [tool_name] + for name, value in sorted(tool_settings.iteritems()): + formatted_value = _GetValueFormattedForMSBuild(tool_name, name, + value) + tool.append([name, formatted_value]) + group.append(tool) + groups.append(group) + return groups + + +def _FinalizeMSBuildSettings(spec, configuration): + if 'msbuild_settings' in configuration: + converted = False + msbuild_settings = configuration['msbuild_settings'] + MSVSSettings.ValidateMSBuildSettings(msbuild_settings) + else: + converted = True + msvs_settings = configuration.get('msvs_settings', {}) + msbuild_settings = MSVSSettings.ConvertToMSBuildSettings(msvs_settings) + include_dirs, resource_include_dirs = _GetIncludeDirs(configuration) + libraries = _GetLibraries(spec) + out_file, _, msbuild_tool = _GetOutputFilePathAndTool(spec) + defines = _GetDefines(configuration) + if converted: + # Visual Studio 2010 has TR1 + defines = [d for d in defines if d != '_HAS_TR1=0'] + # Warn of ignored settings + ignored_settings = ['msvs_prebuild', 'msvs_postbuild', 'msvs_tool_files'] + for ignored_setting in ignored_settings: + value = configuration.get(ignored_setting) + if value: + print ('Warning: The automatic conversion to MSBuild does not handle ' + '%s. Ignoring setting of %s' % (ignored_setting, str(value))) + + defines = [_EscapeCppDefineForMSBuild(d) for d in defines] + disabled_warnings = _GetDisabledWarnings(configuration) + # TODO(jeanluc) Validate & warn that we don't translate + # prebuild = configuration.get('msvs_prebuild') + # postbuild = configuration.get('msvs_postbuild') + def_file = _GetModuleDefinition(spec) + precompiled_header = configuration.get('msvs_precompiled_header') + + # Add the information to the appropriate tool + # TODO(jeanluc) We could optimize and generate these settings only if + # the corresponding files are found, e.g. don't generate ResourceCompile + # if you don't have any resources. + _ToolAppend(msbuild_settings, 'ClCompile', + 'AdditionalIncludeDirectories', include_dirs) + _ToolAppend(msbuild_settings, 'ResourceCompile', + 'AdditionalIncludeDirectories', resource_include_dirs) + # Add in libraries. + _ToolAppend(msbuild_settings, 'Link', 'AdditionalDependencies', libraries) + if out_file: + _ToolAppend(msbuild_settings, msbuild_tool, 'OutputFile', out_file, + only_if_unset=True) + # Add defines. + _ToolAppend(msbuild_settings, 'ClCompile', + 'PreprocessorDefinitions', defines) + _ToolAppend(msbuild_settings, 'ResourceCompile', + 'PreprocessorDefinitions', defines) + # Add disabled warnings. + _ToolAppend(msbuild_settings, 'ClCompile', + 'DisableSpecificWarnings', disabled_warnings) + # Turn on precompiled headers if appropriate. + if precompiled_header: + precompiled_header = os.path.split(precompiled_header)[1] + _ToolAppend(msbuild_settings, 'ClCompile', 'PrecompiledHeader', 'Use') + _ToolAppend(msbuild_settings, 'ClCompile', + 'PrecompiledHeaderFile', precompiled_header) + _ToolAppend(msbuild_settings, 'ClCompile', + 'ForcedIncludeFiles', precompiled_header) + # Loadable modules don't generate import libraries; + # tell dependent projects to not expect one. + if spec['type'] == 'loadable_module': + _ToolAppend(msbuild_settings, '', 'IgnoreImportLibrary', 'true') + # Set the module definition file if any. + if def_file: + _ToolAppend(msbuild_settings, 'Link', 'ModuleDefinitionFile', def_file) + configuration['finalized_msbuild_settings'] = msbuild_settings + + +def _GetValueFormattedForMSBuild(tool_name, name, value): + if type(value) == list: + # For some settings, VS2010 does not automatically extends the settings + # TODO(jeanluc) Is this what we want? + if name in ['AdditionalDependencies', + 'AdditionalIncludeDirectories', + 'AdditionalLibraryDirectories', + 'AdditionalOptions', + 'DelayLoadDLLs', + 'DisableSpecificWarnings', + 'PreprocessorDefinitions']: + value.append('%%(%s)' % name) + # For most tools, entries in a list should be separated with ';' but some + # settings use a space. Check for those first. + exceptions = { + 'ClCompile': ['AdditionalOptions'], + 'Link': ['AdditionalOptions'], + 'Lib': ['AdditionalOptions']} + if tool_name in exceptions and name in exceptions[tool_name]: + char = ' ' + else: + char = ';' + formatted_value = char.join( + [MSVSSettings.ConvertVCMacrosToMSBuild(i) for i in value]) + else: + formatted_value = MSVSSettings.ConvertVCMacrosToMSBuild(value) + return formatted_value + + +def _VerifySourcesExist(sources, root_dir): + """Verifies that all source files exist on disk. + + Checks that all regular source files, i.e. not created at run time, + exist on disk. Missing files cause needless recompilation but no otherwise + visible errors. + + Arguments: + sources: A recursive list of Filter/file names. + root_dir: The root directory for the relative path names. + Returns: + A list of source files that cannot be found on disk. + """ + missing_sources = [] + for source in sources: + if isinstance(source, MSVSProject.Filter): + missing_sources.extend(_VerifySourcesExist(source.contents, root_dir)) + else: + if '$' not in source: + full_path = os.path.join(root_dir, source) + if not os.path.exists(full_path): + missing_sources.append(full_path) + return missing_sources + + +def _GetMSBuildSources(spec, sources, exclusions, extension_to_rule_name, + actions_spec, sources_handled_by_action, list_excluded): + groups = ['none', 'midl', 'include', 'compile', 'resource', 'rule'] + grouped_sources = {} + for g in groups: + grouped_sources[g] = [] + + _AddSources2(spec, sources, exclusions, grouped_sources, + extension_to_rule_name, sources_handled_by_action, list_excluded) + sources = [] + for g in groups: + if grouped_sources[g]: + sources.append(['ItemGroup'] + grouped_sources[g]) + if actions_spec: + sources.append(['ItemGroup'] + actions_spec) + return sources + + +def _AddSources2(spec, sources, exclusions, grouped_sources, + extension_to_rule_name, sources_handled_by_action, + list_excluded): + extensions_excluded_from_precompile = [] + for source in sources: + if isinstance(source, MSVSProject.Filter): + _AddSources2(spec, source.contents, exclusions, grouped_sources, + extension_to_rule_name, sources_handled_by_action, + list_excluded) + else: + if not source in sources_handled_by_action: + detail = [] + excluded_configurations = exclusions.get(source, []) + if len(excluded_configurations) == len(spec['configurations']): + detail.append(['ExcludedFromBuild', 'true']) + else: + for config_name, configuration in sorted(excluded_configurations): + condition = _GetConfigurationCondition(config_name, configuration) + detail.append(['ExcludedFromBuild', + {'Condition': condition}, + 'true']) + # Add precompile if needed + for config_name, configuration in spec['configurations'].iteritems(): + precompiled_source = configuration.get('msvs_precompiled_source', '') + if precompiled_source != '': + precompiled_source = _FixPath(precompiled_source) + if not extensions_excluded_from_precompile: + # If the precompiled header is generated by a C source, we must + # not try to use it for C++ sources, and vice versa. + basename, extension = os.path.splitext(precompiled_source) + if extension == '.c': + extensions_excluded_from_precompile = ['.cc', '.cpp', '.cxx'] + else: + extensions_excluded_from_precompile = ['.c'] + + if precompiled_source == source: + condition = _GetConfigurationCondition(config_name, configuration) + detail.append(['PrecompiledHeader', + {'Condition': condition}, + 'Create' + ]) + else: + # Turn off precompiled header usage for source files of a + # different type than the file that generated the + # precompiled header. + for extension in extensions_excluded_from_precompile: + if source.endswith(extension): + detail.append(['PrecompiledHeader', '']) + detail.append(['ForcedIncludeFiles', '']) + + group, element = _MapFileToMsBuildSourceType(source, + extension_to_rule_name) + grouped_sources[group].append([element, {'Include': source}] + detail) + + +def _GetMSBuildProjectReferences(project): + references = [] + if project.dependencies: + group = ['ItemGroup'] + for dependency in project.dependencies: + guid = dependency.guid + project_dir = os.path.split(project.path)[0] + relative_path = gyp.common.RelativePath(dependency.path, project_dir) + project_ref = ['ProjectReference', + {'Include': relative_path}, + ['Project', guid], + ['ReferenceOutputAssembly', 'false'] + ] + for config in dependency.spec.get('configurations', {}).itervalues(): + # If it's disabled in any config, turn it off in the reference. + if config.get('msvs_2010_disable_uldi_when_referenced', 0): + project_ref.append(['UseLibraryDependencyInputs', 'false']) + break + group.append(project_ref) + references.append(group) + return references + + +def _GenerateMSBuildProject(project, options, version, generator_flags): + spec = project.spec + configurations = spec['configurations'] + project_dir, project_file_name = os.path.split(project.path) + msbuildproj_dir = os.path.dirname(project.path) + if msbuildproj_dir and not os.path.exists(msbuildproj_dir): + os.makedirs(msbuildproj_dir) + # Prepare list of sources and excluded sources. + gyp_path = _NormalizedSource(project.build_file) + relative_path_of_gyp_file = gyp.common.RelativePath(gyp_path, project_dir) + + gyp_file = os.path.split(project.build_file)[1] + sources, excluded_sources = _PrepareListOfSources(spec, generator_flags, + gyp_file) + # Add rules. + actions_to_add = {} + props_files_of_rules = set() + targets_files_of_rules = set() + extension_to_rule_name = {} + list_excluded = generator_flags.get('msvs_list_excluded_files', True) + _GenerateRulesForMSBuild(project_dir, options, spec, + sources, excluded_sources, + props_files_of_rules, targets_files_of_rules, + actions_to_add, extension_to_rule_name) + sources, excluded_sources, excluded_idl = ( + _AdjustSourcesAndConvertToFilterHierarchy(spec, options, + project_dir, sources, + excluded_sources, + list_excluded)) + _AddActions(actions_to_add, spec, project.build_file) + _AddCopies(actions_to_add, spec) + + # NOTE: this stanza must appear after all actions have been decided. + # Don't excluded sources with actions attached, or they won't run. + excluded_sources = _FilterActionsFromExcluded( + excluded_sources, actions_to_add) + + exclusions = _GetExcludedFilesFromBuild(spec, excluded_sources, excluded_idl) + actions_spec, sources_handled_by_action = _GenerateActionsForMSBuild( + spec, actions_to_add) + + _GenerateMSBuildFiltersFile(project.path + '.filters', sources, + extension_to_rule_name) + missing_sources = _VerifySourcesExist(sources, project_dir) + + for (_, configuration) in configurations.iteritems(): + _FinalizeMSBuildSettings(spec, configuration) + + # Add attributes to root element + + import_default_section = [ + ['Import', {'Project': r'$(VCTargetsPath)\Microsoft.Cpp.Default.props'}]] + import_cpp_props_section = [ + ['Import', {'Project': r'$(VCTargetsPath)\Microsoft.Cpp.props'}]] + import_cpp_targets_section = [ + ['Import', {'Project': r'$(VCTargetsPath)\Microsoft.Cpp.targets'}]] + macro_section = [['PropertyGroup', {'Label': 'UserMacros'}]] + + content = [ + 'Project', + {'xmlns': 'http://schemas.microsoft.com/developer/msbuild/2003', + 'ToolsVersion': version.ProjectVersion(), + 'DefaultTargets': 'Build' + }] + + content += _GetMSBuildProjectConfigurations(configurations) + content += _GetMSBuildGlobalProperties(spec, project.guid, project_file_name) + content += import_default_section + content += _GetMSBuildConfigurationDetails(spec, project.build_file) + content += _GetMSBuildLocalProperties(project.msbuild_toolset) + content += import_cpp_props_section + content += _GetMSBuildExtensions(props_files_of_rules) + content += _GetMSBuildPropertySheets(configurations) + content += macro_section + content += _GetMSBuildConfigurationGlobalProperties(spec, configurations, + project.build_file) + content += _GetMSBuildToolSettingsSections(spec, configurations) + content += _GetMSBuildSources( + spec, sources, exclusions, extension_to_rule_name, actions_spec, + sources_handled_by_action, list_excluded) + content += _GetMSBuildProjectReferences(project) + content += import_cpp_targets_section + content += _GetMSBuildExtensionTargets(targets_files_of_rules) + + # TODO(jeanluc) File a bug to get rid of runas. We had in MSVS: + # has_run_as = _WriteMSVSUserFile(project.path, version, spec) + + easy_xml.WriteXmlIfChanged(content, project.path, pretty=True, win32=True) + + return missing_sources + + +def _GetMSBuildExtensions(props_files_of_rules): + extensions = ['ImportGroup', {'Label': 'ExtensionSettings'}] + for props_file in props_files_of_rules: + extensions.append(['Import', {'Project': props_file}]) + return [extensions] + + +def _GetMSBuildExtensionTargets(targets_files_of_rules): + targets_node = ['ImportGroup', {'Label': 'ExtensionTargets'}] + for targets_file in sorted(targets_files_of_rules): + targets_node.append(['Import', {'Project': targets_file}]) + return [targets_node] + + +def _GenerateActionsForMSBuild(spec, actions_to_add): + """Add actions accumulated into an actions_to_add, merging as needed. + + Arguments: + spec: the target project dict + actions_to_add: dictionary keyed on input name, which maps to a list of + dicts describing the actions attached to that input file. + + Returns: + A pair of (action specification, the sources handled by this action). + """ + sources_handled_by_action = set() + actions_spec = [] + for primary_input, actions in actions_to_add.iteritems(): + inputs = set() + outputs = set() + descriptions = [] + commands = [] + for action in actions: + inputs.update(set(action['inputs'])) + outputs.update(set(action['outputs'])) + descriptions.append(action['description']) + cmd = action['command'] + # For most actions, add 'call' so that actions that invoke batch files + # return and continue executing. msbuild_use_call provides a way to + # disable this but I have not seen any adverse effect from doing that + # for everything. + if action.get('msbuild_use_call', True): + cmd = 'call ' + cmd + commands.append(cmd) + # Add the custom build action for one input file. + description = ', and also '.join(descriptions) + + # We can't join the commands simply with && because the command line will + # get too long. See also _AddActions: cygwin's setup_env mustn't be called + # for every invocation or the command that sets the PATH will grow too + # long. + command = ( + '\r\nif %errorlevel% neq 0 exit /b %errorlevel%\r\n'.join(commands)) + _AddMSBuildAction(spec, + primary_input, + inputs, + outputs, + command, + description, + sources_handled_by_action, + actions_spec) + return actions_spec, sources_handled_by_action + + +def _AddMSBuildAction(spec, primary_input, inputs, outputs, cmd, description, + sources_handled_by_action, actions_spec): + command = MSVSSettings.ConvertVCMacrosToMSBuild(cmd) + primary_input = _FixPath(primary_input) + inputs_array = _FixPaths(inputs) + outputs_array = _FixPaths(outputs) + additional_inputs = ';'.join([i for i in inputs_array + if i != primary_input]) + outputs = ';'.join(outputs_array) + sources_handled_by_action.add(primary_input) + action_spec = ['CustomBuild', {'Include': primary_input}] + action_spec.extend( + # TODO(jeanluc) 'Document' for all or just if as_sources? + [['FileType', 'Document'], + ['Command', command], + ['Message', description], + ['Outputs', outputs] + ]) + if additional_inputs: + action_spec.append(['AdditionalInputs', additional_inputs]) + actions_spec.append(action_spec) diff --git a/node-v0.8.14/tools/gyp/pylib/gyp/generator/msvs_test.py b/node-v0.8.14/tools/gyp/pylib/gyp/generator/msvs_test.py new file mode 100755 index 0000000..5a69c1c --- /dev/null +++ b/node-v0.8.14/tools/gyp/pylib/gyp/generator/msvs_test.py @@ -0,0 +1,35 @@ +#!/usr/bin/env python + +# Copyright (c) 2011 Google Inc. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +""" Unit tests for the msvs.py file. """ + +import gyp.generator.msvs as msvs +import unittest +import StringIO + + +class TestSequenceFunctions(unittest.TestCase): + + def setUp(self): + self.stderr = StringIO.StringIO() + + def test_GetLibraries(self): + self.assertEqual( + msvs._GetLibraries({}), + []) + self.assertEqual( + msvs._GetLibraries({'libraries': []}), + []) + self.assertEqual( + msvs._GetLibraries({'other':'foo', 'libraries': ['a.lib']}), + ['a.lib']) + self.assertEqual( + msvs._GetLibraries({'libraries': ['a.lib', 'b.lib', 'c.lib', '-lb.lib', + '-lb.lib', 'd.lib', 'a.lib']}), + ['c.lib', 'b.lib', 'd.lib', 'a.lib']) + +if __name__ == '__main__': + unittest.main() diff --git a/node-v0.8.14/tools/gyp/pylib/gyp/generator/ninja.py b/node-v0.8.14/tools/gyp/pylib/gyp/generator/ninja.py new file mode 100644 index 0000000..d2b8fdc --- /dev/null +++ b/node-v0.8.14/tools/gyp/pylib/gyp/generator/ninja.py @@ -0,0 +1,1712 @@ +# Copyright (c) 2012 Google Inc. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +import copy +import hashlib +import os.path +import re +import subprocess +import sys +import gyp +import gyp.common +import gyp.msvs_emulation +import gyp.MSVSVersion +import gyp.system_test +import gyp.xcode_emulation + +from gyp.common import GetEnvironFallback +import gyp.ninja_syntax as ninja_syntax + +generator_default_variables = { + 'EXECUTABLE_PREFIX': '', + 'EXECUTABLE_SUFFIX': '', + 'STATIC_LIB_PREFIX': 'lib', + 'STATIC_LIB_SUFFIX': '.a', + 'SHARED_LIB_PREFIX': 'lib', + + # Gyp expects the following variables to be expandable by the build + # system to the appropriate locations. Ninja prefers paths to be + # known at gyp time. To resolve this, introduce special + # variables starting with $! and $| (which begin with a $ so gyp knows it + # should be treated specially, but is otherwise an invalid + # ninja/shell variable) that are passed to gyp here but expanded + # before writing out into the target .ninja files; see + # ExpandSpecial. + # $! is used for variables that represent a path and that can only appear at + # the start of a string, while $| is used for variables that can appear + # anywhere in a string. + 'INTERMEDIATE_DIR': '$!INTERMEDIATE_DIR', + 'SHARED_INTERMEDIATE_DIR': '$!PRODUCT_DIR/gen', + 'PRODUCT_DIR': '$!PRODUCT_DIR', + 'CONFIGURATION_NAME': '$|CONFIGURATION_NAME', + + # Special variables that may be used by gyp 'rule' targets. + # We generate definitions for these variables on the fly when processing a + # rule. + 'RULE_INPUT_ROOT': '${root}', + 'RULE_INPUT_DIRNAME': '${dirname}', + 'RULE_INPUT_PATH': '${source}', + 'RULE_INPUT_EXT': '${ext}', + 'RULE_INPUT_NAME': '${name}', +} + +# Placates pylint. +generator_additional_non_configuration_keys = [] +generator_additional_path_sections = [] +generator_extra_sources_for_rules = [] + +# TODO: figure out how to not build extra host objects in the non-cross-compile +# case when this is enabled, and enable unconditionally. +generator_supports_multiple_toolsets = ( + os.environ.get('GYP_CROSSCOMPILE') or + os.environ.get('AR_host') or + os.environ.get('CC_host') or + os.environ.get('CXX_host') or + os.environ.get('AR_target') or + os.environ.get('CC_target') or + os.environ.get('CXX_target')) + + +def StripPrefix(arg, prefix): + if arg.startswith(prefix): + return arg[len(prefix):] + return arg + + +def QuoteShellArgument(arg, flavor): + """Quote a string such that it will be interpreted as a single argument + by the shell.""" + # Rather than attempting to enumerate the bad shell characters, just + # whitelist common OK ones and quote anything else. + if re.match(r'^[a-zA-Z0-9_=.\\/-]+$', arg): + return arg # No quoting necessary. + if flavor == 'win': + return gyp.msvs_emulation.QuoteForRspFile(arg) + return "'" + arg.replace("'", "'" + '"\'"' + "'") + "'" + + +def Define(d, flavor): + """Takes a preprocessor define and returns a -D parameter that's ninja- and + shell-escaped.""" + if flavor == 'win': + # cl.exe replaces literal # characters with = in preprocesor definitions for + # some reason. Octal-encode to work around that. + d = d.replace('#', '\\%03o' % ord('#')) + return QuoteShellArgument(ninja_syntax.escape('-D' + d), flavor) + + +def InvertRelativePath(path): + """Given a relative path like foo/bar, return the inverse relative path: + the path from the relative path back to the origin dir. + + E.g. os.path.normpath(os.path.join(path, InvertRelativePath(path))) + should always produce the empty string.""" + + if not path: + return path + # Only need to handle relative paths into subdirectories for now. + assert '..' not in path, path + depth = len(path.split(os.path.sep)) + return os.path.sep.join(['..'] * depth) + + +class Target: + """Target represents the paths used within a single gyp target. + + Conceptually, building a single target A is a series of steps: + + 1) actions/rules/copies generates source/resources/etc. + 2) compiles generates .o files + 3) link generates a binary (library/executable) + 4) bundle merges the above in a mac bundle + + (Any of these steps can be optional.) + + From a build ordering perspective, a dependent target B could just + depend on the last output of this series of steps. + + But some dependent commands sometimes need to reach inside the box. + For example, when linking B it needs to get the path to the static + library generated by A. + + This object stores those paths. To keep things simple, member + variables only store concrete paths to single files, while methods + compute derived values like "the last output of the target". + """ + def __init__(self, type): + # Gyp type ("static_library", etc.) of this target. + self.type = type + # File representing whether any input dependencies necessary for + # dependent actions have completed. + self.preaction_stamp = None + # File representing whether any input dependencies necessary for + # dependent compiles have completed. + self.precompile_stamp = None + # File representing the completion of actions/rules/copies, if any. + self.actions_stamp = None + # Path to the output of the link step, if any. + self.binary = None + # Path to the file representing the completion of building the bundle, + # if any. + self.bundle = None + # On Windows, incremental linking requires linking against all the .objs + # that compose a .lib (rather than the .lib itself). That list is stored + # here. + self.component_objs = None + # Windows only. The import .lib is the output of a build step, but + # because dependents only link against the lib (not both the lib and the + # dll) we keep track of the import library here. + self.import_lib = None + + def Linkable(self): + """Return true if this is a target that can be linked against.""" + return self.type in ('static_library', 'shared_library') + + def UsesToc(self, flavor): + """Return true if the target should produce a restat rule based on a TOC + file.""" + # For bundles, the .TOC should be produced for the binary, not for + # FinalOutput(). But the naive approach would put the TOC file into the + # bundle, so don't do this for bundles for now. + if flavor == 'win' or self.bundle: + return False + return self.type in ('shared_library', 'loadable_module') + + def PreActionInput(self, flavor): + """Return the path, if any, that should be used as a dependency of + any dependent action step.""" + if self.UsesToc(flavor): + return self.FinalOutput() + '.TOC' + return self.FinalOutput() or self.preaction_stamp + + def PreCompileInput(self): + """Return the path, if any, that should be used as a dependency of + any dependent compile step.""" + return self.actions_stamp or self.precompile_stamp + + def FinalOutput(self): + """Return the last output of the target, which depends on all prior + steps.""" + return self.bundle or self.binary or self.actions_stamp + + +# A small discourse on paths as used within the Ninja build: +# All files we produce (both at gyp and at build time) appear in the +# build directory (e.g. out/Debug). +# +# Paths within a given .gyp file are always relative to the directory +# containing the .gyp file. Call these "gyp paths". This includes +# sources as well as the starting directory a given gyp rule/action +# expects to be run from. We call the path from the source root to +# the gyp file the "base directory" within the per-.gyp-file +# NinjaWriter code. +# +# All paths as written into the .ninja files are relative to the build +# directory. Call these paths "ninja paths". +# +# We translate between these two notions of paths with two helper +# functions: +# +# - GypPathToNinja translates a gyp path (i.e. relative to the .gyp file) +# into the equivalent ninja path. +# +# - GypPathToUniqueOutput translates a gyp path into a ninja path to write +# an output file; the result can be namespaced such that it is unique +# to the input file name as well as the output target name. + +class NinjaWriter: + def __init__(self, qualified_target, target_outputs, base_dir, build_dir, + output_file, flavor, abs_build_dir=None): + """ + base_dir: path from source root to directory containing this gyp file, + by gyp semantics, all input paths are relative to this + build_dir: path from source root to build output + abs_build_dir: absolute path to the build directory + """ + + self.qualified_target = qualified_target + self.target_outputs = target_outputs + self.base_dir = base_dir + self.build_dir = build_dir + self.ninja = ninja_syntax.Writer(output_file) + self.flavor = flavor + self.abs_build_dir = abs_build_dir + self.obj_ext = '.obj' if flavor == 'win' else '.o' + if flavor == 'win': + # See docstring of msvs_emulation.GenerateEnvironmentFiles(). + self.win_env = {} + for arch in ('x86', 'x64'): + self.win_env[arch] = 'environment.' + arch + + # Relative path from build output dir to base dir. + self.build_to_base = os.path.join(InvertRelativePath(build_dir), base_dir) + # Relative path from base dir to build dir. + self.base_to_build = os.path.join(InvertRelativePath(base_dir), build_dir) + + def ExpandSpecial(self, path, product_dir=None): + """Expand specials like $!PRODUCT_DIR in |path|. + + If |product_dir| is None, assumes the cwd is already the product + dir. Otherwise, |product_dir| is the relative path to the product + dir. + """ + + PRODUCT_DIR = '$!PRODUCT_DIR' + if PRODUCT_DIR in path: + if product_dir: + path = path.replace(PRODUCT_DIR, product_dir) + else: + path = path.replace(PRODUCT_DIR + '/', '') + path = path.replace(PRODUCT_DIR + '\\', '') + path = path.replace(PRODUCT_DIR, '.') + + INTERMEDIATE_DIR = '$!INTERMEDIATE_DIR' + if INTERMEDIATE_DIR in path: + int_dir = self.GypPathToUniqueOutput('gen') + # GypPathToUniqueOutput generates a path relative to the product dir, + # so insert product_dir in front if it is provided. + path = path.replace(INTERMEDIATE_DIR, + os.path.join(product_dir or '', int_dir)) + + CONFIGURATION_NAME = '$|CONFIGURATION_NAME' + path = path.replace(CONFIGURATION_NAME, self.config_name) + + return path + + def ExpandRuleVariables(self, path, root, dirname, source, ext, name): + if self.flavor == 'win': + path = self.msvs_settings.ConvertVSMacros( + path, config=self.config_name) + path = path.replace(generator_default_variables['RULE_INPUT_ROOT'], root) + path = path.replace(generator_default_variables['RULE_INPUT_DIRNAME'], + dirname) + path = path.replace(generator_default_variables['RULE_INPUT_PATH'], source) + path = path.replace(generator_default_variables['RULE_INPUT_EXT'], ext) + path = path.replace(generator_default_variables['RULE_INPUT_NAME'], name) + return path + + def GypPathToNinja(self, path, env=None): + """Translate a gyp path to a ninja path, optionally expanding environment + variable references in |path| with |env|. + + See the above discourse on path conversions.""" + if env: + if self.flavor == 'mac': + path = gyp.xcode_emulation.ExpandEnvVars(path, env) + elif self.flavor == 'win': + path = gyp.msvs_emulation.ExpandMacros(path, env) + if path.startswith('$!'): + expanded = self.ExpandSpecial(path) + if self.flavor == 'win': + expanded = os.path.normpath(expanded) + return expanded + if '$|' in path: + path = self.ExpandSpecial(path) + assert '$' not in path, path + return os.path.normpath(os.path.join(self.build_to_base, path)) + + def GypPathToUniqueOutput(self, path, qualified=True): + """Translate a gyp path to a ninja path for writing output. + + If qualified is True, qualify the resulting filename with the name + of the target. This is necessary when e.g. compiling the same + path twice for two separate output targets. + + See the above discourse on path conversions.""" + + path = self.ExpandSpecial(path) + assert not path.startswith('$'), path + + # Translate the path following this scheme: + # Input: foo/bar.gyp, target targ, references baz/out.o + # Output: obj/foo/baz/targ.out.o (if qualified) + # obj/foo/baz/out.o (otherwise) + # (and obj.host instead of obj for cross-compiles) + # + # Why this scheme and not some other one? + # 1) for a given input, you can compute all derived outputs by matching + # its path, even if the input is brought via a gyp file with '..'. + # 2) simple files like libraries and stamps have a simple filename. + + obj = 'obj' + if self.toolset != 'target': + obj += '.' + self.toolset + + path_dir, path_basename = os.path.split(path) + if qualified: + path_basename = self.name + '.' + path_basename + return os.path.normpath(os.path.join(obj, self.base_dir, path_dir, + path_basename)) + + def WriteCollapsedDependencies(self, name, targets): + """Given a list of targets, return a path for a single file + representing the result of building all the targets or None. + + Uses a stamp file if necessary.""" + + assert targets == filter(None, targets), targets + if len(targets) == 0: + return None + if len(targets) > 1: + stamp = self.GypPathToUniqueOutput(name + '.stamp') + targets = self.ninja.build(stamp, 'stamp', targets) + self.ninja.newline() + return targets[0] + + def WriteSpec(self, spec, config_name, generator_flags): + """The main entry point for NinjaWriter: write the build rules for a spec. + + Returns a Target object, which represents the output paths for this spec. + Returns None if there are no outputs (e.g. a settings-only 'none' type + target).""" + + self.config_name = config_name + self.name = spec['target_name'] + self.toolset = spec['toolset'] + config = spec['configurations'][config_name] + self.target = Target(spec['type']) + + self.is_mac_bundle = gyp.xcode_emulation.IsMacBundle(self.flavor, spec) + self.xcode_settings = self.msvs_settings = None + if self.flavor == 'mac': + self.xcode_settings = gyp.xcode_emulation.XcodeSettings(spec) + if self.flavor == 'win': + self.msvs_settings = gyp.msvs_emulation.MsvsSettings(spec, + generator_flags) + target_platform = self.msvs_settings.GetTargetPlatform(config_name) + self.ninja.variable('arch', self.win_env[target_platform]) + + # Compute predepends for all rules. + # actions_depends is the dependencies this target depends on before running + # any of its action/rule/copy steps. + # compile_depends is the dependencies this target depends on before running + # any of its compile steps. + actions_depends = [] + compile_depends = [] + # TODO(evan): it is rather confusing which things are lists and which + # are strings. Fix these. + if 'dependencies' in spec: + for dep in spec['dependencies']: + if dep in self.target_outputs: + target = self.target_outputs[dep] + actions_depends.append(target.PreActionInput(self.flavor)) + compile_depends.append(target.PreCompileInput()) + actions_depends = filter(None, actions_depends) + compile_depends = filter(None, compile_depends) + actions_depends = self.WriteCollapsedDependencies('actions_depends', + actions_depends) + compile_depends = self.WriteCollapsedDependencies('compile_depends', + compile_depends) + self.target.preaction_stamp = actions_depends + self.target.precompile_stamp = compile_depends + + # Write out actions, rules, and copies. These must happen before we + # compile any sources, so compute a list of predependencies for sources + # while we do it. + extra_sources = [] + mac_bundle_depends = [] + self.target.actions_stamp = self.WriteActionsRulesCopies( + spec, extra_sources, actions_depends, mac_bundle_depends) + + # If we have actions/rules/copies, we depend directly on those, but + # otherwise we depend on dependent target's actions/rules/copies etc. + # We never need to explicitly depend on previous target's link steps, + # because no compile ever depends on them. + compile_depends_stamp = (self.target.actions_stamp or compile_depends) + + # Write out the compilation steps, if any. + link_deps = [] + sources = spec.get('sources', []) + extra_sources + if sources: + pch = None + if self.flavor == 'win': + pch = gyp.msvs_emulation.PrecompiledHeader( + self.msvs_settings, config_name, self.GypPathToNinja) + else: + pch = gyp.xcode_emulation.MacPrefixHeader( + self.xcode_settings, self.GypPathToNinja, + lambda path, lang: self.GypPathToUniqueOutput(path + '-' + lang)) + link_deps = self.WriteSources( + config_name, config, sources, compile_depends_stamp, pch) + # Some actions/rules output 'sources' that are already object files. + link_deps += [self.GypPathToNinja(f) + for f in sources if f.endswith(self.obj_ext)] + + if self.flavor == 'win' and self.target.type == 'static_library': + self.target.component_objs = link_deps + + # Write out a link step, if needed. + output = None + if link_deps or self.target.actions_stamp or actions_depends: + output = self.WriteTarget(spec, config_name, config, link_deps, + self.target.actions_stamp or actions_depends) + if self.is_mac_bundle: + mac_bundle_depends.append(output) + + # Bundle all of the above together, if needed. + if self.is_mac_bundle: + output = self.WriteMacBundle(spec, mac_bundle_depends) + + if not output: + return None + + assert self.target.FinalOutput(), output + return self.target + + def _WinIdlRule(self, source, prebuild, outputs): + """Handle the implicit VS .idl rule for one source file. Fills |outputs| + with files that are generated.""" + outdir, output, vars, flags = self.msvs_settings.GetIdlBuildData( + source, self.config_name) + outdir = self.GypPathToNinja(outdir) + def fix_path(path, rel=None): + path = os.path.join(outdir, path) + dirname, basename = os.path.split(source) + root, ext = os.path.splitext(basename) + path = self.ExpandRuleVariables( + path, root, dirname, source, ext, basename) + if rel: + path = os.path.relpath(path, rel) + return path + vars = [(name, fix_path(value, outdir)) for name, value in vars] + output = [fix_path(p) for p in output] + vars.append(('outdir', outdir)) + vars.append(('idlflags', flags)) + input = self.GypPathToNinja(source) + self.ninja.build(output, 'idl', input, + variables=vars, order_only=prebuild) + outputs.extend(output) + + def WriteWinIdlFiles(self, spec, prebuild): + """Writes rules to match MSVS's implicit idl handling.""" + assert self.flavor == 'win' + if self.msvs_settings.HasExplicitIdlRules(spec): + return [] + outputs = [] + for source in filter(lambda x: x.endswith('.idl'), spec['sources']): + self._WinIdlRule(source, prebuild, outputs) + return outputs + + def WriteActionsRulesCopies(self, spec, extra_sources, prebuild, + mac_bundle_depends): + """Write out the Actions, Rules, and Copies steps. Return a path + representing the outputs of these steps.""" + outputs = [] + extra_mac_bundle_resources = [] + + if 'actions' in spec: + outputs += self.WriteActions(spec['actions'], extra_sources, prebuild, + extra_mac_bundle_resources) + if 'rules' in spec: + outputs += self.WriteRules(spec['rules'], extra_sources, prebuild, + extra_mac_bundle_resources) + if 'copies' in spec: + outputs += self.WriteCopies(spec['copies'], prebuild) + + if 'sources' in spec and self.flavor == 'win': + outputs += self.WriteWinIdlFiles(spec, prebuild) + + stamp = self.WriteCollapsedDependencies('actions_rules_copies', outputs) + + if self.is_mac_bundle: + mac_bundle_resources = spec.get('mac_bundle_resources', []) + \ + extra_mac_bundle_resources + self.WriteMacBundleResources(mac_bundle_resources, mac_bundle_depends) + self.WriteMacInfoPlist(mac_bundle_depends) + + return stamp + + def GenerateDescription(self, verb, message, fallback): + """Generate and return a description of a build step. + + |verb| is the short summary, e.g. ACTION or RULE. + |message| is a hand-written description, or None if not available. + |fallback| is the gyp-level name of the step, usable as a fallback. + """ + if self.toolset != 'target': + verb += '(%s)' % self.toolset + if message: + return '%s %s' % (verb, self.ExpandSpecial(message)) + else: + return '%s %s: %s' % (verb, self.name, fallback) + + def WriteActions(self, actions, extra_sources, prebuild, + extra_mac_bundle_resources): + # Actions cd into the base directory. + env = self.GetSortedXcodeEnv() + if self.flavor == 'win': + env = self.msvs_settings.GetVSMacroEnv( + '$!PRODUCT_DIR', config=self.config_name) + all_outputs = [] + for action in actions: + # First write out a rule for the action. + name = '%s_%s' % (action['action_name'], + hashlib.md5(self.qualified_target).hexdigest()) + description = self.GenerateDescription('ACTION', + action.get('message', None), + name) + is_cygwin = (self.msvs_settings.IsRuleRunUnderCygwin(action) + if self.flavor == 'win' else False) + args = action['action'] + args = [self.msvs_settings.ConvertVSMacros( + arg, self.base_to_build, config=self.config_name) + for arg in args] if self.flavor == 'win' else args + rule_name = self.WriteNewNinjaRule(name, args, description, + is_cygwin, env=env) + + inputs = [self.GypPathToNinja(i, env) for i in action['inputs']] + if int(action.get('process_outputs_as_sources', False)): + extra_sources += action['outputs'] + if int(action.get('process_outputs_as_mac_bundle_resources', False)): + extra_mac_bundle_resources += action['outputs'] + outputs = [self.GypPathToNinja(o, env) for o in action['outputs']] + + # Then write out an edge using the rule. + self.ninja.build(outputs, rule_name, inputs, + order_only=prebuild) + all_outputs += outputs + + self.ninja.newline() + + return all_outputs + + def WriteRules(self, rules, extra_sources, prebuild, + extra_mac_bundle_resources): + all_outputs = [] + for rule in rules: + # First write out a rule for the rule action. + name = '%s_%s' % (rule['rule_name'], + hashlib.md5(self.qualified_target).hexdigest()) + # Skip a rule with no action and no inputs. + if 'action' not in rule and not rule.get('rule_sources', []): + continue + args = rule['action'] + description = self.GenerateDescription( + 'RULE', + rule.get('message', None), + ('%s ' + generator_default_variables['RULE_INPUT_PATH']) % name) + is_cygwin = (self.msvs_settings.IsRuleRunUnderCygwin(rule) + if self.flavor == 'win' else False) + args = [self.msvs_settings.ConvertVSMacros( + arg, self.base_to_build, config=self.config_name) + for arg in args] if self.flavor == 'win' else args + rule_name = self.WriteNewNinjaRule(name, args, description, is_cygwin) + + # TODO: if the command references the outputs directly, we should + # simplify it to just use $out. + + # Rules can potentially make use of some special variables which + # must vary per source file. + # Compute the list of variables we'll need to provide. + special_locals = ('source', 'root', 'dirname', 'ext', 'name') + needed_variables = set(['source']) + for argument in args: + for var in special_locals: + if ('${%s}' % var) in argument: + needed_variables.add(var) + + def cygwin_munge(path): + if is_cygwin: + return path.replace('\\', '/') + return path + + # For each source file, write an edge that generates all the outputs. + for source in rule.get('rule_sources', []): + dirname, basename = os.path.split(source) + root, ext = os.path.splitext(basename) + + # Gather the list of inputs and outputs, expanding $vars if possible. + outputs = [self.ExpandRuleVariables(o, root, dirname, + source, ext, basename) + for o in rule['outputs']] + inputs = [self.ExpandRuleVariables(i, root, dirname, + source, ext, basename) + for i in rule.get('inputs', [])] + + if int(rule.get('process_outputs_as_sources', False)): + extra_sources += outputs + if int(rule.get('process_outputs_as_mac_bundle_resources', False)): + extra_mac_bundle_resources += outputs + + extra_bindings = [] + for var in needed_variables: + if var == 'root': + extra_bindings.append(('root', cygwin_munge(root))) + elif var == 'dirname': + extra_bindings.append(('dirname', cygwin_munge(dirname))) + elif var == 'source': + # '$source' is a parameter to the rule action, which means + # it shouldn't be converted to a Ninja path. But we don't + # want $!PRODUCT_DIR in there either. + source_expanded = self.ExpandSpecial(source, self.base_to_build) + extra_bindings.append(('source', cygwin_munge(source_expanded))) + elif var == 'ext': + extra_bindings.append(('ext', ext)) + elif var == 'name': + extra_bindings.append(('name', cygwin_munge(basename))) + else: + assert var == None, repr(var) + + inputs = map(self.GypPathToNinja, inputs) + outputs = map(self.GypPathToNinja, outputs) + extra_bindings.append(('unique_name', + re.sub('[^a-zA-Z0-9_]', '_', outputs[0]))) + self.ninja.build(outputs, rule_name, self.GypPathToNinja(source), + implicit=inputs, + order_only=prebuild, + variables=extra_bindings) + + all_outputs.extend(outputs) + + return all_outputs + + def WriteCopies(self, copies, prebuild): + outputs = [] + env = self.GetSortedXcodeEnv() + for copy in copies: + for path in copy['files']: + # Normalize the path so trailing slashes don't confuse us. + path = os.path.normpath(path) + basename = os.path.split(path)[1] + src = self.GypPathToNinja(path, env) + dst = self.GypPathToNinja(os.path.join(copy['destination'], basename), + env) + outputs += self.ninja.build(dst, 'copy', src, order_only=prebuild) + + return outputs + + def WriteMacBundleResources(self, resources, bundle_depends): + """Writes ninja edges for 'mac_bundle_resources'.""" + for output, res in gyp.xcode_emulation.GetMacBundleResources( + self.ExpandSpecial(generator_default_variables['PRODUCT_DIR']), + self.xcode_settings, map(self.GypPathToNinja, resources)): + self.ninja.build(output, 'mac_tool', res, + variables=[('mactool_cmd', 'copy-bundle-resource')]) + bundle_depends.append(output) + + def WriteMacInfoPlist(self, bundle_depends): + """Write build rules for bundle Info.plist files.""" + info_plist, out, defines, extra_env = gyp.xcode_emulation.GetMacInfoPlist( + self.ExpandSpecial(generator_default_variables['PRODUCT_DIR']), + self.xcode_settings, self.GypPathToNinja) + if not info_plist: + return + if defines: + # Create an intermediate file to store preprocessed results. + intermediate_plist = self.GypPathToUniqueOutput( + os.path.basename(info_plist)) + defines = ' '.join([Define(d, self.flavor) for d in defines]) + info_plist = self.ninja.build(intermediate_plist, 'infoplist', info_plist, + variables=[('defines',defines)]) + + env = self.GetSortedXcodeEnv(additional_settings=extra_env) + env = self.ComputeExportEnvString(env) + + self.ninja.build(out, 'mac_tool', info_plist, + variables=[('mactool_cmd', 'copy-info-plist'), + ('env', env)]) + bundle_depends.append(out) + + def WriteSources(self, config_name, config, sources, predepends, + precompiled_header): + """Write build rules to compile all of |sources|.""" + if self.toolset == 'host': + self.ninja.variable('ar', '$ar_host') + self.ninja.variable('cc', '$cc_host') + self.ninja.variable('cxx', '$cxx_host') + self.ninja.variable('ld', '$ld_host') + + extra_defines = [] + if self.flavor == 'mac': + cflags = self.xcode_settings.GetCflags(config_name) + cflags_c = self.xcode_settings.GetCflagsC(config_name) + cflags_cc = self.xcode_settings.GetCflagsCC(config_name) + cflags_objc = ['$cflags_c'] + \ + self.xcode_settings.GetCflagsObjC(config_name) + cflags_objcc = ['$cflags_cc'] + \ + self.xcode_settings.GetCflagsObjCC(config_name) + elif self.flavor == 'win': + cflags = self.msvs_settings.GetCflags(config_name) + cflags_c = self.msvs_settings.GetCflagsC(config_name) + cflags_cc = self.msvs_settings.GetCflagsCC(config_name) + extra_defines = self.msvs_settings.GetComputedDefines(config_name) + self.WriteVariableList('pdbname', [self.name + '.pdb']) + self.WriteVariableList('pchprefix', [self.name]) + else: + cflags = config.get('cflags', []) + cflags_c = config.get('cflags_c', []) + cflags_cc = config.get('cflags_cc', []) + + defines = config.get('defines', []) + extra_defines + self.WriteVariableList('defines', [Define(d, self.flavor) for d in defines]) + if self.flavor == 'win': + self.WriteVariableList('rcflags', + [QuoteShellArgument(self.ExpandSpecial(f), self.flavor) + for f in self.msvs_settings.GetRcflags(config_name, + self.GypPathToNinja)]) + + include_dirs = config.get('include_dirs', []) + if self.flavor == 'win': + include_dirs = self.msvs_settings.AdjustIncludeDirs(include_dirs, + config_name) + self.WriteVariableList('includes', + [QuoteShellArgument('-I' + self.GypPathToNinja(i), self.flavor) + for i in include_dirs]) + + pch_commands = precompiled_header.GetPchBuildCommands() + if self.flavor == 'mac': + self.WriteVariableList('cflags_pch_c', + [precompiled_header.GetInclude('c')]) + self.WriteVariableList('cflags_pch_cc', + [precompiled_header.GetInclude('cc')]) + self.WriteVariableList('cflags_pch_objc', + [precompiled_header.GetInclude('m')]) + self.WriteVariableList('cflags_pch_objcc', + [precompiled_header.GetInclude('mm')]) + + self.WriteVariableList('cflags', map(self.ExpandSpecial, cflags)) + self.WriteVariableList('cflags_c', map(self.ExpandSpecial, cflags_c)) + self.WriteVariableList('cflags_cc', map(self.ExpandSpecial, cflags_cc)) + if self.flavor == 'mac': + self.WriteVariableList('cflags_objc', map(self.ExpandSpecial, + cflags_objc)) + self.WriteVariableList('cflags_objcc', map(self.ExpandSpecial, + cflags_objcc)) + self.ninja.newline() + outputs = [] + for source in sources: + filename, ext = os.path.splitext(source) + ext = ext[1:] + obj_ext = self.obj_ext + if ext in ('cc', 'cpp', 'cxx'): + command = 'cxx' + elif ext == 'c' or (ext in ('s', 'S') and self.flavor != 'win'): + command = 'cc' + elif (self.flavor == 'win' and ext == 'asm' and + self.msvs_settings.GetTargetPlatform(config_name) == 'Win32'): + # Asm files only get auto assembled for x86 (not x64). + command = 'asm' + # Add the _asm suffix as msvs is capable of handling .cc and + # .asm files of the same name without collision. + obj_ext = '_asm.obj' + elif self.flavor == 'mac' and ext == 'm': + command = 'objc' + elif self.flavor == 'mac' and ext == 'mm': + command = 'objcxx' + elif self.flavor == 'win' and ext == 'rc': + command = 'rc' + obj_ext = '.res' + else: + # Ignore unhandled extensions. + continue + input = self.GypPathToNinja(source) + output = self.GypPathToUniqueOutput(filename + obj_ext) + implicit = precompiled_header.GetObjDependencies([input], [output]) + self.ninja.build(output, command, input, + implicit=[gch for _, _, gch in implicit], + order_only=predepends) + outputs.append(output) + + self.WritePchTargets(pch_commands) + + self.ninja.newline() + return outputs + + def WritePchTargets(self, pch_commands): + """Writes ninja rules to compile prefix headers.""" + if not pch_commands: + return + + for gch, lang_flag, lang, input in pch_commands: + var_name = { + 'c': 'cflags_pch_c', + 'cc': 'cflags_pch_cc', + 'm': 'cflags_pch_objc', + 'mm': 'cflags_pch_objcc', + }[lang] + + map = { 'c': 'cc', 'cc': 'cxx', 'm': 'objc', 'mm': 'objcxx', } + if self.flavor == 'win': + map.update({'c': 'cc_pch', 'cc': 'cxx_pch'}) + cmd = map.get(lang) + self.ninja.build(gch, cmd, input, variables=[(var_name, lang_flag)]) + + def WriteLink(self, spec, config_name, config, link_deps): + """Write out a link step. Fills out target.binary. """ + + command = { + 'executable': 'link', + 'loadable_module': 'solink_module', + 'shared_library': 'solink', + }[spec['type']] + + implicit_deps = set() + solibs = set() + + if 'dependencies' in spec: + # Two kinds of dependencies: + # - Linkable dependencies (like a .a or a .so): add them to the link line. + # - Non-linkable dependencies (like a rule that generates a file + # and writes a stamp file): add them to implicit_deps + extra_link_deps = set() + for dep in spec['dependencies']: + target = self.target_outputs.get(dep) + if not target: + continue + linkable = target.Linkable() + if linkable: + if (self.flavor == 'win' and + target.component_objs and + self.msvs_settings.IsUseLibraryDependencyInputs(config_name)): + extra_link_deps |= set(target.component_objs) + elif self.flavor == 'win' and target.import_lib: + extra_link_deps.add(target.import_lib) + elif target.UsesToc(self.flavor): + solibs.add(target.binary) + implicit_deps.add(target.binary + '.TOC') + else: + extra_link_deps.add(target.binary) + + final_output = target.FinalOutput() + if not linkable or final_output != target.binary: + implicit_deps.add(final_output) + + link_deps.extend(list(extra_link_deps)) + + extra_bindings = [] + if self.is_mac_bundle: + output = self.ComputeMacBundleBinaryOutput() + else: + output = self.ComputeOutput(spec) + extra_bindings.append(('postbuilds', + self.GetPostbuildCommand(spec, output, output))) + + if self.flavor == 'mac': + ldflags = self.xcode_settings.GetLdflags(config_name, + self.ExpandSpecial(generator_default_variables['PRODUCT_DIR']), + self.GypPathToNinja) + elif self.flavor == 'win': + libflags = self.msvs_settings.GetLibFlags(config_name, + self.GypPathToNinja) + self.WriteVariableList( + 'libflags', gyp.common.uniquer(map(self.ExpandSpecial, libflags))) + is_executable = spec['type'] == 'executable' + manifest_name = self.GypPathToUniqueOutput( + self.ComputeOutputFileName(spec)) + ldflags, manifest_files = self.msvs_settings.GetLdflags(config_name, + self.GypPathToNinja, self.ExpandSpecial, manifest_name, is_executable) + self.WriteVariableList('manifests', manifest_files) + else: + ldflags = config.get('ldflags', []) + self.WriteVariableList('ldflags', + gyp.common.uniquer(map(self.ExpandSpecial, + ldflags))) + + libraries = gyp.common.uniquer(map(self.ExpandSpecial, + spec.get('libraries', []))) + if self.flavor == 'mac': + libraries = self.xcode_settings.AdjustLibraries(libraries) + elif self.flavor == 'win': + libraries = self.msvs_settings.AdjustLibraries(libraries) + self.WriteVariableList('libs', libraries) + + self.target.binary = output + + if command in ('solink', 'solink_module'): + extra_bindings.append(('soname', os.path.split(output)[1])) + extra_bindings.append(('lib', + gyp.common.EncodePOSIXShellArgument(output))) + if self.flavor == 'win': + self.target.import_lib = output + '.lib' + extra_bindings.append(('dll', output)) + extra_bindings.append(('implib', self.target.import_lib)) + output = [output, self.target.import_lib] + else: + output = [output, output + '.TOC'] + + if len(solibs): + extra_bindings.append(('solibs', gyp.common.EncodePOSIXShellList(solibs))) + + self.ninja.build(output, command, link_deps, + implicit=list(implicit_deps), + variables=extra_bindings) + + def WriteTarget(self, spec, config_name, config, link_deps, compile_deps): + if spec['type'] == 'none': + # TODO(evan): don't call this function for 'none' target types, as + # it doesn't do anything, and we fake out a 'binary' with a stamp file. + self.target.binary = compile_deps + elif spec['type'] == 'static_library': + self.target.binary = self.ComputeOutput(spec) + self.ninja.build(self.target.binary, 'alink', link_deps, + order_only=compile_deps, + variables=[('postbuilds', self.GetPostbuildCommand( + spec, self.target.binary, self.target.binary))]) + else: + self.WriteLink(spec, config_name, config, link_deps) + return self.target.binary + + def WriteMacBundle(self, spec, mac_bundle_depends): + assert self.is_mac_bundle + package_framework = spec['type'] in ('shared_library', 'loadable_module') + output = self.ComputeMacBundleOutput() + postbuild = self.GetPostbuildCommand(spec, output, self.target.binary, + is_command_start=not package_framework) + variables = [] + if postbuild: + variables.append(('postbuilds', postbuild)) + if package_framework: + variables.append(('version', self.xcode_settings.GetFrameworkVersion())) + self.ninja.build(output, 'package_framework', mac_bundle_depends, + variables=variables) + else: + self.ninja.build(output, 'stamp', mac_bundle_depends, + variables=variables) + self.target.bundle = output + return output + + def GetSortedXcodeEnv(self, additional_settings=None): + """Returns the variables Xcode would set for build steps.""" + assert self.abs_build_dir + abs_build_dir = self.abs_build_dir + return gyp.xcode_emulation.GetSortedXcodeEnv( + self.xcode_settings, abs_build_dir, + os.path.join(abs_build_dir, self.build_to_base), self.config_name, + additional_settings) + + def GetSortedXcodePostbuildEnv(self): + """Returns the variables Xcode would set for postbuild steps.""" + postbuild_settings = {} + # CHROMIUM_STRIP_SAVE_FILE is a chromium-specific hack. + # TODO(thakis): It would be nice to have some general mechanism instead. + strip_save_file = self.xcode_settings.GetPerTargetSetting( + 'CHROMIUM_STRIP_SAVE_FILE') + if strip_save_file: + postbuild_settings['CHROMIUM_STRIP_SAVE_FILE'] = strip_save_file + return self.GetSortedXcodeEnv(additional_settings=postbuild_settings) + + def GetPostbuildCommand(self, spec, output, output_binary, + is_command_start=False): + """Returns a shell command that runs all the postbuilds, and removes + |output| if any of them fails. If |is_command_start| is False, then the + returned string will start with ' && '.""" + if not self.xcode_settings or spec['type'] == 'none' or not output: + return '' + output = QuoteShellArgument(output, self.flavor) + target_postbuilds = self.xcode_settings.GetTargetPostbuilds( + self.config_name, + os.path.normpath(os.path.join(self.base_to_build, output)), + QuoteShellArgument( + os.path.normpath(os.path.join(self.base_to_build, output_binary)), + self.flavor), + quiet=True) + postbuilds = gyp.xcode_emulation.GetSpecPostbuildCommands(spec, quiet=True) + postbuilds = target_postbuilds + postbuilds + if not postbuilds: + return '' + # Postbuilds expect to be run in the gyp file's directory, so insert an + # implicit postbuild to cd to there. + postbuilds.insert(0, gyp.common.EncodePOSIXShellList( + ['cd', self.build_to_base])) + env = self.ComputeExportEnvString(self.GetSortedXcodePostbuildEnv()) + # G will be non-null if any postbuild fails. Run all postbuilds in a + # subshell. + commands = env + ' (F=0; ' + \ + ' '.join([ninja_syntax.escape(command) + ' || F=$$?;' + for command in postbuilds]) + command_string = (commands + ' exit $$F); G=$$?; ' + # Remove the final output if any postbuild failed. + '((exit $$G) || rm -rf %s) ' % output + '&& exit $$G)') + if is_command_start: + return '(' + command_string + ' && ' + else: + return '$ && (' + command_string + + def ComputeExportEnvString(self, env): + """Given an environment, returns a string looking like + 'export FOO=foo; export BAR="${FOO} bar;' + that exports |env| to the shell.""" + export_str = [] + for k, v in env: + export_str.append('export %s=%s;' % + (k, ninja_syntax.escape(gyp.common.EncodePOSIXShellArgument(v)))) + return ' '.join(export_str) + + def ComputeMacBundleOutput(self): + """Return the 'output' (full output path) to a bundle output directory.""" + assert self.is_mac_bundle + path = self.ExpandSpecial(generator_default_variables['PRODUCT_DIR']) + return os.path.join(path, self.xcode_settings.GetWrapperName()) + + def ComputeMacBundleBinaryOutput(self): + """Return the 'output' (full output path) to the binary in a bundle.""" + assert self.is_mac_bundle + path = self.ExpandSpecial(generator_default_variables['PRODUCT_DIR']) + return os.path.join(path, self.xcode_settings.GetExecutablePath()) + + def ComputeOutputFileName(self, spec, type=None): + """Compute the filename of the final output for the current target.""" + if not type: + type = spec['type'] + + default_variables = copy.copy(generator_default_variables) + CalculateVariables(default_variables, {'flavor': self.flavor}) + + # Compute filename prefix: the product prefix, or a default for + # the product type. + DEFAULT_PREFIX = { + 'loadable_module': default_variables['SHARED_LIB_PREFIX'], + 'shared_library': default_variables['SHARED_LIB_PREFIX'], + 'static_library': default_variables['STATIC_LIB_PREFIX'], + 'executable': default_variables['EXECUTABLE_PREFIX'], + } + prefix = spec.get('product_prefix', DEFAULT_PREFIX.get(type, '')) + + # Compute filename extension: the product extension, or a default + # for the product type. + DEFAULT_EXTENSION = { + 'loadable_module': default_variables['SHARED_LIB_SUFFIX'], + 'shared_library': default_variables['SHARED_LIB_SUFFIX'], + 'static_library': default_variables['STATIC_LIB_SUFFIX'], + 'executable': default_variables['EXECUTABLE_SUFFIX'], + } + extension = spec.get('product_extension') + if extension: + extension = '.' + extension + else: + extension = DEFAULT_EXTENSION.get(type, '') + + if 'product_name' in spec: + # If we were given an explicit name, use that. + target = spec['product_name'] + else: + # Otherwise, derive a name from the target name. + target = spec['target_name'] + if prefix == 'lib': + # Snip out an extra 'lib' from libs if appropriate. + target = StripPrefix(target, 'lib') + + if type in ('static_library', 'loadable_module', 'shared_library', + 'executable'): + return '%s%s%s' % (prefix, target, extension) + elif type == 'none': + return '%s.stamp' % target + else: + raise Exception('Unhandled output type %s' % type) + + def ComputeOutput(self, spec, type=None): + """Compute the path for the final output of the spec.""" + assert not self.is_mac_bundle or type + + if not type: + type = spec['type'] + + if self.flavor == 'win': + override = self.msvs_settings.GetOutputName(self.config_name, + self.ExpandSpecial) + if override: + return override + + if self.flavor == 'mac' and type in ( + 'static_library', 'executable', 'shared_library', 'loadable_module'): + filename = self.xcode_settings.GetExecutablePath() + else: + filename = self.ComputeOutputFileName(spec, type) + + if 'product_dir' in spec: + path = os.path.join(spec['product_dir'], filename) + return self.ExpandSpecial(path) + + # Some products go into the output root, libraries go into shared library + # dir, and everything else goes into the normal place. + type_in_output_root = ['executable', 'loadable_module'] + if self.flavor == 'mac' and self.toolset == 'target': + type_in_output_root += ['shared_library', 'static_library'] + elif self.flavor == 'win' and self.toolset == 'target': + type_in_output_root += ['shared_library'] + + if type in type_in_output_root: + return filename + elif type == 'shared_library': + libdir = 'lib' + if self.toolset != 'target': + libdir = os.path.join('lib', '%s' % self.toolset) + return os.path.join(libdir, filename) + else: + return self.GypPathToUniqueOutput(filename, qualified=False) + + def WriteVariableList(self, var, values): + assert not isinstance(values, str) + if values is None: + values = [] + self.ninja.variable(var, ' '.join(values)) + + def WriteNewNinjaRule(self, name, args, description, is_cygwin, env={}): + """Write out a new ninja "rule" statement for a given command. + + Returns the name of the new rule.""" + + # TODO: we shouldn't need to qualify names; we do it because + # currently the ninja rule namespace is global, but it really + # should be scoped to the subninja. + rule_name = self.name + if self.toolset == 'target': + rule_name += '.' + self.toolset + rule_name += '.' + name + rule_name = re.sub('[^a-zA-Z0-9_]', '_', rule_name) + + args = args[:] + + if self.flavor == 'win': + description = self.msvs_settings.ConvertVSMacros( + description, config=self.config_name) + + # gyp dictates that commands are run from the base directory. + # cd into the directory before running, and adjust paths in + # the arguments to point to the proper locations. + rspfile = None + rspfile_content = None + args = [self.ExpandSpecial(arg, self.base_to_build) for arg in args] + if self.flavor == 'win': + rspfile = rule_name + '.$unique_name.rsp' + # The cygwin case handles this inside the bash sub-shell. + run_in = '' if is_cygwin else ' ' + self.build_to_base + if is_cygwin: + rspfile_content = self.msvs_settings.BuildCygwinBashCommandLine( + args, self.build_to_base) + else: + rspfile_content = gyp.msvs_emulation.EncodeRspFileList(args) + command = ('%s gyp-win-tool action-wrapper $arch ' % sys.executable + + rspfile + run_in) + else: + env = self.ComputeExportEnvString(env) + command = gyp.common.EncodePOSIXShellList(args) + if env: + # If an environment is passed in, variables in the command should be + # read from it, instead of from ninja's internal variables. + command = ninja_syntax.escape(command) + command = 'cd %s; ' % self.build_to_base + env + command + + # GYP rules/actions express being no-ops by not touching their outputs. + # Avoid executing downstream dependencies in this case by specifying + # restat=1 to ninja. + self.ninja.rule(rule_name, command, description, restat=True, + rspfile=rspfile, rspfile_content=rspfile_content) + self.ninja.newline() + + return rule_name + + +def CalculateVariables(default_variables, params): + """Calculate additional variables for use in the build (called by gyp).""" + global generator_additional_non_configuration_keys + global generator_additional_path_sections + flavor = gyp.common.GetFlavor(params) + if flavor == 'mac': + default_variables.setdefault('OS', 'mac') + default_variables.setdefault('SHARED_LIB_SUFFIX', '.dylib') + default_variables.setdefault('SHARED_LIB_DIR', + generator_default_variables['PRODUCT_DIR']) + default_variables.setdefault('LIB_DIR', + generator_default_variables['PRODUCT_DIR']) + + # Copy additional generator configuration data from Xcode, which is shared + # by the Mac Ninja generator. + import gyp.generator.xcode as xcode_generator + generator_additional_non_configuration_keys = getattr(xcode_generator, + 'generator_additional_non_configuration_keys', []) + generator_additional_path_sections = getattr(xcode_generator, + 'generator_additional_path_sections', []) + global generator_extra_sources_for_rules + generator_extra_sources_for_rules = getattr(xcode_generator, + 'generator_extra_sources_for_rules', []) + elif flavor == 'win': + default_variables.setdefault('OS', 'win') + default_variables['EXECUTABLE_SUFFIX'] = '.exe' + default_variables['STATIC_LIB_PREFIX'] = '' + default_variables['STATIC_LIB_SUFFIX'] = '.lib' + default_variables['SHARED_LIB_PREFIX'] = '' + default_variables['SHARED_LIB_SUFFIX'] = '.dll' + generator_flags = params.get('generator_flags', {}) + + # Copy additional generator configuration data from VS, which is shared + # by the Windows Ninja generator. + import gyp.generator.msvs as msvs_generator + generator_additional_non_configuration_keys = getattr(msvs_generator, + 'generator_additional_non_configuration_keys', []) + generator_additional_path_sections = getattr(msvs_generator, + 'generator_additional_path_sections', []) + + # Set a variable so conditions can be based on msvs_version. + msvs_version = gyp.msvs_emulation.GetVSVersion(generator_flags) + default_variables['MSVS_VERSION'] = msvs_version.ShortName() + + # To determine processor word size on Windows, in addition to checking + # PROCESSOR_ARCHITECTURE (which reflects the word size of the current + # process), it is also necessary to check PROCESSOR_ARCHITEW6432 (which + # contains the actual word size of the system when running thru WOW64). + if ('64' in os.environ.get('PROCESSOR_ARCHITECTURE', '') or + '64' in os.environ.get('PROCESSOR_ARCHITEW6432', '')): + default_variables['MSVS_OS_BITS'] = 64 + else: + default_variables['MSVS_OS_BITS'] = 32 + else: + operating_system = flavor + if flavor == 'android': + operating_system = 'linux' # Keep this legacy behavior for now. + default_variables.setdefault('OS', operating_system) + default_variables.setdefault('SHARED_LIB_SUFFIX', '.so') + default_variables.setdefault('SHARED_LIB_DIR', + os.path.join('$!PRODUCT_DIR', 'lib')) + default_variables.setdefault('LIB_DIR', + os.path.join('$!PRODUCT_DIR', 'obj')) + + +def OpenOutput(path, mode='w'): + """Open |path| for writing, creating directories if necessary.""" + try: + os.makedirs(os.path.dirname(path)) + except OSError: + pass + return open(path, mode) + + +def GenerateOutputForConfig(target_list, target_dicts, data, params, + config_name): + options = params['options'] + flavor = gyp.common.GetFlavor(params) + generator_flags = params.get('generator_flags', {}) + + # build_dir: relative path from source root to our output files. + # e.g. "out/Debug" + build_dir = os.path.join(generator_flags.get('output_dir', 'out'), + config_name) + + toplevel_build = os.path.join(options.toplevel_dir, build_dir) + + master_ninja = ninja_syntax.Writer( + OpenOutput(os.path.join(toplevel_build, 'build.ninja')), + width=120) + + # Put build-time support tools in out/{config_name}. + gyp.common.CopyTool(flavor, toplevel_build) + + # Grab make settings for CC/CXX. + # The rules are + # - The priority from low to high is gcc/g++, the 'make_global_settings' in + # gyp, the environment variable. + # - If there is no 'make_global_settings' for CC.host/CXX.host or + # 'CC_host'/'CXX_host' enviroment variable, cc_host/cxx_host should be set + # to cc/cxx. + if flavor == 'win': + cc = 'cl.exe' + cxx = 'cl.exe' + ld = 'link.exe' + gyp.msvs_emulation.GenerateEnvironmentFiles( + toplevel_build, generator_flags, OpenOutput) + ld_host = '$ld' + else: + cc = 'gcc' + cxx = 'g++' + ld = '$cxx' + ld_host = '$cxx_host' + + cc_host = None + cxx_host = None + cc_host_global_setting = None + cxx_host_global_setting = None + + build_file, _, _ = gyp.common.ParseQualifiedTarget(target_list[0]) + make_global_settings = data[build_file].get('make_global_settings', []) + build_to_root = InvertRelativePath(build_dir) + for key, value in make_global_settings: + if key == 'CC': + cc = os.path.join(build_to_root, value) + if key == 'CXX': + cxx = os.path.join(build_to_root, value) + if key == 'LD': + ld = os.path.join(build_to_root, value) + if key == 'CC.host': + cc_host = os.path.join(build_to_root, value) + cc_host_global_setting = value + if key == 'CXX.host': + cxx_host = os.path.join(build_to_root, value) + cxx_host_global_setting = value + if key == 'LD.host': + ld_host = os.path.join(build_to_root, value) + + flock = 'flock' + if flavor == 'mac': + flock = './gyp-mac-tool flock' + cc = GetEnvironFallback(['CC_target', 'CC'], cc) + master_ninja.variable('cc', cc) + cxx = GetEnvironFallback(['CXX_target', 'CXX'], cxx) + master_ninja.variable('cxx', cxx) + ld = GetEnvironFallback(['LD_target', 'LD'], ld) + + if not cc_host: + cc_host = cc + if not cxx_host: + cxx_host = cxx + + if flavor == 'win': + master_ninja.variable('ld', ld) + master_ninja.variable('idl', 'midl.exe') + master_ninja.variable('ar', 'lib.exe') + master_ninja.variable('rc', 'rc.exe') + master_ninja.variable('asm', 'ml.exe') + master_ninja.variable('mt', 'mt.exe') + master_ninja.variable('use_dep_database', '1') + else: + master_ninja.variable('ld', flock + ' linker.lock ' + ld) + master_ninja.variable('ar', GetEnvironFallback(['AR_target', 'AR'], 'ar')) + + master_ninja.variable('ar_host', GetEnvironFallback(['AR_host'], 'ar')) + cc_host = GetEnvironFallback(['CC_host'], cc_host) + cxx_host = GetEnvironFallback(['CXX_host'], cxx_host) + ld_host = GetEnvironFallback(['LD_host'], ld_host) + + # The environment variable could be used in 'make_global_settings', like + # ['CC.host', '$(CC)'] or ['CXX.host', '$(CXX)'], transform them here. + if '$(CC)' in cc_host and cc_host_global_setting: + cc_host = cc_host_global_setting.replace('$(CC)', cc) + if '$(CXX)' in cxx_host and cxx_host_global_setting: + cxx_host = cxx_host_global_setting.replace('$(CXX)', cxx) + master_ninja.variable('cc_host', cc_host) + master_ninja.variable('cxx_host', cxx_host) + if flavor == 'win': + master_ninja.variable('ld_host', ld_host) + else: + master_ninja.variable('ld_host', flock + ' linker.lock ' + ld_host) + + if flavor == 'mac': + master_ninja.variable('mac_tool', os.path.join('.', 'gyp-mac-tool')) + master_ninja.newline() + + if flavor != 'win': + master_ninja.rule( + 'cc', + description='CC $out', + command=('$cc -MMD -MF $out.d $defines $includes $cflags $cflags_c ' + '$cflags_pch_c -c $in -o $out'), + depfile='$out.d') + master_ninja.rule( + 'cxx', + description='CXX $out', + command=('$cxx -MMD -MF $out.d $defines $includes $cflags $cflags_cc ' + '$cflags_pch_cc -c $in -o $out'), + depfile='$out.d') + else: + # TODO(scottmg): Requires fork of ninja for dependency and linking + # support: https://github.com/sgraham/ninja + # Template for compile commands mostly shared between compiling files + # and generating PCH. In the case of PCH, the "output" is specified by /Fp + # rather than /Fo (for object files), but we still need to specify an /Fo + # when compiling PCH. + cc_template = ('ninja-deplist-helper -r . -q -f cl -o $out.dl -e $arch ' + '--command ' + '$cc /nologo /showIncludes /FC ' + '@$out.rsp ' + '$cflags_pch_c /c $in %(outspec)s /Fd$pdbname ') + cxx_template = ('ninja-deplist-helper -r . -q -f cl -o $out.dl -e $arch ' + '--command ' + '$cxx /nologo /showIncludes /FC ' + '@$out.rsp ' + '$cflags_pch_cc /c $in %(outspec)s $pchobj /Fd$pdbname ') + master_ninja.rule( + 'cc', + description='CC $out', + command=cc_template % {'outspec': '/Fo$out'}, + depfile='$out.dl', + rspfile='$out.rsp', + rspfile_content='$defines $includes $cflags $cflags_c') + master_ninja.rule( + 'cc_pch', + description='CC PCH $out', + command=cc_template % {'outspec': '/Fp$out /Fo$out.obj'}, + depfile='$out.dl', + rspfile='$out.rsp', + rspfile_content='$defines $includes $cflags $cflags_c') + master_ninja.rule( + 'cxx', + description='CXX $out', + command=cxx_template % {'outspec': '/Fo$out'}, + depfile='$out.dl', + rspfile='$out.rsp', + rspfile_content='$defines $includes $cflags $cflags_cc') + master_ninja.rule( + 'cxx_pch', + description='CXX PCH $out', + command=cxx_template % {'outspec': '/Fp$out /Fo$out.obj'}, + depfile='$out.dl', + rspfile='$out.rsp', + rspfile_content='$defines $includes $cflags $cflags_cc') + master_ninja.rule( + 'idl', + description='IDL $in', + command=('%s gyp-win-tool midl-wrapper $arch $outdir ' + '$tlb $h $dlldata $iid $proxy $in ' + '$idlflags' % sys.executable)) + master_ninja.rule( + 'rc', + description='RC $in', + # Note: $in must be last otherwise rc.exe complains. + command=('%s gyp-win-tool rc-wrapper ' + '$arch $rc $defines $includes $rcflags /fo$out $in' % + sys.executable)) + master_ninja.rule( + 'asm', + description='ASM $in', + command=('%s gyp-win-tool asm-wrapper ' + '$arch $asm $defines $includes /c /Fo $out $in' % + sys.executable)) + + if flavor != 'mac' and flavor != 'win': + master_ninja.rule( + 'alink', + description='AR $out', + command='rm -f $out && $ar rcsT $out $in') + + # This allows targets that only need to depend on $lib's API to declare an + # order-only dependency on $lib.TOC and avoid relinking such downstream + # dependencies when $lib changes only in non-public ways. + # The resulting string leaves an uninterpolated %{suffix} which + # is used in the final substitution below. + mtime_preserving_solink_base = ( + 'if [ ! -e $lib -o ! -e ${lib}.TOC ]; then ' + '%(solink)s && %(extract_toc)s > ${lib}.TOC; else ' + '%(solink)s && %(extract_toc)s > ${lib}.tmp && ' + 'if ! cmp -s ${lib}.tmp ${lib}.TOC; then mv ${lib}.tmp ${lib}.TOC ; ' + 'fi; fi' + % { 'solink': + '$ld -shared $ldflags -o $lib -Wl,-soname=$soname %(suffix)s', + 'extract_toc': + ('{ readelf -d ${lib} | grep SONAME ; ' + 'nm -gD -f p ${lib} | cut -f1-2 -d\' \'; }')}) + + master_ninja.rule( + 'solink', + description='SOLINK $lib', + restat=True, + command=(mtime_preserving_solink_base % { + 'suffix': '-Wl,--whole-archive $in $solibs -Wl,--no-whole-archive ' + '$libs'})) + master_ninja.rule( + 'solink_module', + description='SOLINK(module) $lib', + restat=True, + command=(mtime_preserving_solink_base % { + 'suffix': '-Wl,--start-group $in $solibs -Wl,--end-group $libs'})) + master_ninja.rule( + 'link', + description='LINK $out', + command=('$ld $ldflags -o $out -Wl,-rpath=\$$ORIGIN/lib ' + '-Wl,--start-group $in $solibs -Wl,--end-group $libs')) + elif flavor == 'win': + master_ninja.rule( + 'alink', + description='LIB $out', + command=('%s gyp-win-tool link-wrapper $arch ' + '$ar /nologo /ignore:4221 /OUT:$out @$out.rsp' % + sys.executable), + rspfile='$out.rsp', + rspfile_content='$in_newline $libflags') + dlldesc = 'LINK(DLL) $dll' + dllcmd = ('%s gyp-win-tool link-wrapper $arch ' + '$ld /nologo /IMPLIB:$implib /DLL /OUT:$dll ' + '/PDB:$dll.pdb @$dll.rsp' % sys.executable) + dllcmd += (' && %s gyp-win-tool manifest-wrapper $arch ' + '$mt -nologo -manifest $manifests -out:$dll.manifest' % + sys.executable) + master_ninja.rule('solink', description=dlldesc, command=dllcmd, + rspfile='$dll.rsp', + rspfile_content='$libs $in_newline $ldflags', + restat=True) + master_ninja.rule('solink_module', description=dlldesc, command=dllcmd, + rspfile='$dll.rsp', + rspfile_content='$libs $in_newline $ldflags', + restat=True) + # Note that ldflags goes at the end so that it has the option of + # overriding default settings earlier in the command line. + master_ninja.rule( + 'link', + description='LINK $out', + command=('%s gyp-win-tool link-wrapper $arch ' + '$ld /nologo /OUT:$out /PDB:$out.pdb @$out.rsp && ' + '%s gyp-win-tool manifest-wrapper $arch ' + '$mt -nologo -manifest $manifests -out:$out.manifest' % + (sys.executable, sys.executable)), + rspfile='$out.rsp', + rspfile_content='$in_newline $libs $ldflags') + else: + master_ninja.rule( + 'objc', + description='OBJC $out', + command=('$cc -MMD -MF $out.d $defines $includes $cflags $cflags_objc ' + '$cflags_pch_objc -c $in -o $out'), + depfile='$out.d') + master_ninja.rule( + 'objcxx', + description='OBJCXX $out', + command=('$cxx -MMD -MF $out.d $defines $includes $cflags $cflags_objcc ' + '$cflags_pch_objcc -c $in -o $out'), + depfile='$out.d') + master_ninja.rule( + 'alink', + description='LIBTOOL-STATIC $out, POSTBUILDS', + command='rm -f $out && ' + './gyp-mac-tool filter-libtool libtool -static -o $out $in' + '$postbuilds') + + # Record the public interface of $lib in $lib.TOC. See the corresponding + # comment in the posix section above for details. + mtime_preserving_solink_base = ( + 'if [ ! -e $lib -o ! -e ${lib}.TOC ] || ' + # Always force dependent targets to relink if this library + # reexports something. Handling this correctly would require + # recursive TOC dumping but this is rare in practice, so punt. + 'otool -l $lib | grep -q LC_REEXPORT_DYLIB ; then ' + '%(solink)s && %(extract_toc)s > ${lib}.TOC; ' + 'else ' + '%(solink)s && %(extract_toc)s > ${lib}.tmp && ' + 'if ! cmp -s ${lib}.tmp ${lib}.TOC; then ' + 'mv ${lib}.tmp ${lib}.TOC ; ' + 'fi; ' + 'fi' + % { 'solink': '$ld -shared $ldflags -o $lib %(suffix)s', + 'extract_toc': + '{ otool -l $lib | grep LC_ID_DYLIB -A 5; ' + 'nm -gP $lib | cut -f1-2 -d\' \' | grep -v U$$; true; }'}) + + # TODO(thakis): The solink_module rule is likely wrong. Xcode seems to pass + # -bundle -single_module here (for osmesa.so). + master_ninja.rule( + 'solink', + description='SOLINK $lib, POSTBUILDS', + restat=True, + command=(mtime_preserving_solink_base % { + 'suffix': '$in $solibs $libs$postbuilds'})) + master_ninja.rule( + 'solink_module', + description='SOLINK(module) $lib, POSTBUILDS', + restat=True, + command=(mtime_preserving_solink_base % { + 'suffix': '$in $solibs $libs$postbuilds'})) + + master_ninja.rule( + 'link', + description='LINK $out, POSTBUILDS', + command=('$ld $ldflags -o $out ' + '$in $solibs $libs$postbuilds')) + master_ninja.rule( + 'infoplist', + description='INFOPLIST $out', + command=('$cc -E -P -Wno-trigraphs -x c $defines $in -o $out && ' + 'plutil -convert xml1 $out $out')) + master_ninja.rule( + 'mac_tool', + description='MACTOOL $mactool_cmd $in', + command='$env $mac_tool $mactool_cmd $in $out') + master_ninja.rule( + 'package_framework', + description='PACKAGE FRAMEWORK $out, POSTBUILDS', + command='$mac_tool package-framework $out $version$postbuilds ' + '&& touch $out') + if flavor == 'win': + master_ninja.rule( + 'stamp', + description='STAMP $out', + command='%s gyp-win-tool stamp $out' % sys.executable) + master_ninja.rule( + 'copy', + description='COPY $in $out', + command='%s gyp-win-tool recursive-mirror $in $out' % sys.executable) + else: + master_ninja.rule( + 'stamp', + description='STAMP $out', + command='${postbuilds}touch $out') + master_ninja.rule( + 'copy', + description='COPY $in $out', + command='ln -f $in $out 2>/dev/null || (rm -rf $out && cp -af $in $out)') + master_ninja.newline() + + all_targets = set() + for build_file in params['build_files']: + for target in gyp.common.AllTargets(target_list, + target_dicts, + os.path.normpath(build_file)): + all_targets.add(target) + all_outputs = set() + + # target_outputs is a map from qualified target name to a Target object. + target_outputs = {} + # target_short_names is a map from target short name to a list of Target + # objects. + target_short_names = {} + for qualified_target in target_list: + # qualified_target is like: third_party/icu/icu.gyp:icui18n#target + build_file, name, toolset = \ + gyp.common.ParseQualifiedTarget(qualified_target) + + this_make_global_settings = data[build_file].get('make_global_settings', []) + assert make_global_settings == this_make_global_settings, ( + "make_global_settings needs to be the same for all targets.") + + spec = target_dicts[qualified_target] + if flavor == 'mac': + gyp.xcode_emulation.MergeGlobalXcodeSettingsToSpec(data[build_file], spec) + + build_file = gyp.common.RelativePath(build_file, options.toplevel_dir) + + base_path = os.path.dirname(build_file) + obj = 'obj' + if toolset != 'target': + obj += '.' + toolset + output_file = os.path.join(obj, base_path, name + '.ninja') + + abs_build_dir = os.path.abspath(toplevel_build) + writer = NinjaWriter(qualified_target, target_outputs, base_path, build_dir, + OpenOutput(os.path.join(toplevel_build, output_file)), + flavor, abs_build_dir=abs_build_dir) + master_ninja.subninja(output_file) + + target = writer.WriteSpec(spec, config_name, generator_flags) + if target: + if name != target.FinalOutput() and spec['toolset'] == 'target': + target_short_names.setdefault(name, []).append(target) + target_outputs[qualified_target] = target + if qualified_target in all_targets: + all_outputs.add(target.FinalOutput()) + + if target_short_names: + # Write a short name to build this target. This benefits both the + # "build chrome" case as well as the gyp tests, which expect to be + # able to run actions and build libraries by their short name. + master_ninja.newline() + master_ninja.comment('Short names for targets.') + for short_name in target_short_names: + master_ninja.build(short_name, 'phony', [x.FinalOutput() for x in + target_short_names[short_name]]) + + if all_outputs: + master_ninja.newline() + master_ninja.build('all', 'phony', list(all_outputs)) + master_ninja.default('all') + + +def GenerateOutput(target_list, target_dicts, data, params): + if params['options'].generator_output: + raise NotImplementedError, "--generator_output not implemented for ninja" + + user_config = params.get('generator_flags', {}).get('config', None) + if user_config: + GenerateOutputForConfig(target_list, target_dicts, data, params, + user_config) + else: + config_names = target_dicts[target_list[0]]['configurations'].keys() + for config_name in config_names: + GenerateOutputForConfig(target_list, target_dicts, data, params, + config_name) diff --git a/node-v0.8.14/tools/gyp/pylib/gyp/generator/ninja_test.py b/node-v0.8.14/tools/gyp/pylib/gyp/generator/ninja_test.py new file mode 100644 index 0000000..90dd153 --- /dev/null +++ b/node-v0.8.14/tools/gyp/pylib/gyp/generator/ninja_test.py @@ -0,0 +1,44 @@ +#!/usr/bin/env python + +# Copyright (c) 2012 Google Inc. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +""" Unit tests for the ninja.py file. """ + +import gyp.generator.ninja as ninja +import unittest +import StringIO +import sys +import TestCommon + + +class TestPrefixesAndSuffixes(unittest.TestCase): + if sys.platform in ('win32', 'cygwin'): + def test_BinaryNamesWindows(self): + writer = ninja.NinjaWriter('foo', 'wee', '.', '.', 'ninja.build', 'win') + spec = { 'target_name': 'wee' } + self.assertTrue(writer.ComputeOutputFileName(spec, 'executable'). + endswith('.exe')) + self.assertTrue(writer.ComputeOutputFileName(spec, 'shared_library'). + endswith('.dll')) + self.assertTrue(writer.ComputeOutputFileName(spec, 'static_library'). + endswith('.lib')) + + if sys.platform == 'linux2': + def test_BinaryNamesLinux(self): + writer = ninja.NinjaWriter('foo', 'wee', '.', '.', 'ninja.build', 'linux') + spec = { 'target_name': 'wee' } + self.assertTrue('.' not in writer.ComputeOutputFileName(spec, + 'executable')) + self.assertTrue(writer.ComputeOutputFileName(spec, 'shared_library'). + startswith('lib')) + self.assertTrue(writer.ComputeOutputFileName(spec, 'static_library'). + startswith('lib')) + self.assertTrue(writer.ComputeOutputFileName(spec, 'shared_library'). + endswith('.so')) + self.assertTrue(writer.ComputeOutputFileName(spec, 'static_library'). + endswith('.a')) + +if __name__ == '__main__': + unittest.main() diff --git a/node-v0.8.14/tools/gyp/pylib/gyp/generator/scons.py b/node-v0.8.14/tools/gyp/pylib/gyp/generator/scons.py new file mode 100644 index 0000000..4d0feb0 --- /dev/null +++ b/node-v0.8.14/tools/gyp/pylib/gyp/generator/scons.py @@ -0,0 +1,1047 @@ +# Copyright (c) 2012 Google Inc. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +import gyp +import gyp.common +import gyp.SCons as SCons +import os.path +import pprint +import re + + +# TODO: remove when we delete the last WriteList() call in this module +WriteList = SCons.WriteList + + +generator_default_variables = { + 'EXECUTABLE_PREFIX': '', + 'EXECUTABLE_SUFFIX': '', + 'STATIC_LIB_PREFIX': '${LIBPREFIX}', + 'SHARED_LIB_PREFIX': '${SHLIBPREFIX}', + 'STATIC_LIB_SUFFIX': '${LIBSUFFIX}', + 'SHARED_LIB_SUFFIX': '${SHLIBSUFFIX}', + 'INTERMEDIATE_DIR': '${INTERMEDIATE_DIR}', + 'SHARED_INTERMEDIATE_DIR': '${SHARED_INTERMEDIATE_DIR}', + 'OS': 'linux', + 'PRODUCT_DIR': '$TOP_BUILDDIR', + 'SHARED_LIB_DIR': '$LIB_DIR', + 'LIB_DIR': '$LIB_DIR', + 'RULE_INPUT_ROOT': '${SOURCE.filebase}', + 'RULE_INPUT_DIRNAME': '${SOURCE.dir}', + 'RULE_INPUT_EXT': '${SOURCE.suffix}', + 'RULE_INPUT_NAME': '${SOURCE.file}', + 'RULE_INPUT_PATH': '${SOURCE.abspath}', + 'CONFIGURATION_NAME': '${CONFIG_NAME}', +} + +# Tell GYP how to process the input for us. +generator_handles_variants = True +generator_wants_absolute_build_file_paths = True + + +def FixPath(path, prefix): + if not os.path.isabs(path) and not path[0] == '$': + path = prefix + path + return path + + +header = """\ +# This file is generated; do not edit. +""" + + +_alias_template = """ +if GetOption('verbose'): + _action = Action([%(action)s]) +else: + _action = Action([%(action)s], %(message)s) +_outputs = env.Alias( + ['_%(target_name)s_action'], + %(inputs)s, + _action +) +env.AlwaysBuild(_outputs) +""" + +_run_as_template = """ +if GetOption('verbose'): + _action = Action([%(action)s]) +else: + _action = Action([%(action)s], %(message)s) +""" + +_run_as_template_suffix = """ +_run_as_target = env.Alias('run_%(target_name)s', target_files, _action) +env.Requires(_run_as_target, [ + Alias('%(target_name)s'), +]) +env.AlwaysBuild(_run_as_target) +""" + +_command_template = """ +if GetOption('verbose'): + _action = Action([%(action)s]) +else: + _action = Action([%(action)s], %(message)s) +_outputs = env.Command( + %(outputs)s, + %(inputs)s, + _action +) +""" + +# This is copied from the default SCons action, updated to handle symlinks. +_copy_action_template = """ +import shutil +import SCons.Action + +def _copy_files_or_dirs_or_symlinks(dest, src): + SCons.Node.FS.invalidate_node_memos(dest) + if SCons.Util.is_List(src) and os.path.isdir(dest): + for file in src: + shutil.copy2(file, dest) + return 0 + elif os.path.islink(src): + linkto = os.readlink(src) + os.symlink(linkto, dest) + return 0 + elif os.path.isfile(src): + return shutil.copy2(src, dest) + else: + return shutil.copytree(src, dest, 1) + +def _copy_files_or_dirs_or_symlinks_str(dest, src): + return 'Copying %s to %s ...' % (src, dest) + +GYPCopy = SCons.Action.ActionFactory(_copy_files_or_dirs_or_symlinks, + _copy_files_or_dirs_or_symlinks_str, + convert=str) +""" + +_rule_template = """ +%(name)s_additional_inputs = %(inputs)s +%(name)s_outputs = %(outputs)s +def %(name)s_emitter(target, source, env): + return (%(name)s_outputs, source + %(name)s_additional_inputs) +if GetOption('verbose'): + %(name)s_action = Action([%(action)s]) +else: + %(name)s_action = Action([%(action)s], %(message)s) +env['BUILDERS']['%(name)s'] = Builder(action=%(name)s_action, + emitter=%(name)s_emitter) + +_outputs = [] +_processed_input_files = [] +for infile in input_files: + if (type(infile) == type('') + and not os.path.isabs(infile) + and not infile[0] == '$'): + infile = %(src_dir)r + infile + if str(infile).endswith('.%(extension)s'): + _generated = env.%(name)s(infile) + env.Precious(_generated) + _outputs.append(_generated) + %(process_outputs_as_sources_line)s + else: + _processed_input_files.append(infile) +prerequisites.extend(_outputs) +input_files = _processed_input_files +""" + +_spawn_hack = """ +import re +import SCons.Platform.posix +needs_shell = re.compile('["\\'>= 2.5: + return os.sysconf('SC_NPROCESSORS_ONLN') + else: # Mac OS X with Python < 2.5: + return int(os.popen2("sysctl -n hw.ncpu")[1].read()) + # Windows: + if os.environ.has_key('NUMBER_OF_PROCESSORS'): + return max(int(os.environ.get('NUMBER_OF_PROCESSORS', '1')), 1) + return 1 # Default + +# Support PROGRESS= to show progress in different ways. +p = ARGUMENTS.get('PROGRESS') +if p == 'spinner': + Progress(['/\\r', '|\\r', '\\\\\\r', '-\\r'], + interval=5, + file=open('/dev/tty', 'w')) +elif p == 'name': + Progress('$TARGET\\r', overwrite=True, file=open('/dev/tty', 'w')) + +# Set the default -j value based on the number of processors. +SetOption('num_jobs', GetProcessorCount() + 1) + +# Have SCons use its cached dependency information. +SetOption('implicit_cache', 1) + +# Only re-calculate MD5 checksums if a timestamp has changed. +Decider('MD5-timestamp') + +# Since we set the -j value by default, suppress SCons warnings about being +# unable to support parallel build on versions of Python with no threading. +default_warnings = ['no-no-parallel-support'] +SetOption('warn', default_warnings + GetOption('warn')) + +AddOption('--mode', nargs=1, dest='conf_list', default=[], + action='append', help='Configuration to build.') + +AddOption('--verbose', dest='verbose', default=False, + action='store_true', help='Verbose command-line output.') + + +# +sconscript_file_map = %(sconscript_files)s + +class LoadTarget: + ''' + Class for deciding if a given target sconscript is to be included + based on a list of included target names, optionally prefixed with '-' + to exclude a target name. + ''' + def __init__(self, load): + ''' + Initialize a class with a list of names for possible loading. + + Arguments: + load: list of elements in the LOAD= specification + ''' + self.included = set([c for c in load if not c.startswith('-')]) + self.excluded = set([c[1:] for c in load if c.startswith('-')]) + + if not self.included: + self.included = set(['all']) + + def __call__(self, target): + ''' + Returns True if the specified target's sconscript file should be + loaded, based on the initialized included and excluded lists. + ''' + return (target in self.included or + ('all' in self.included and not target in self.excluded)) + +if 'LOAD' in ARGUMENTS: + load = ARGUMENTS['LOAD'].split(',') +else: + load = [] +load_target = LoadTarget(load) + +sconscript_files = [] +for target, sconscript in sconscript_file_map.iteritems(): + if load_target(target): + sconscript_files.append(sconscript) + + +target_alias_list= [] + +conf_list = GetOption('conf_list') +if conf_list: + # In case the same --mode= value was specified multiple times. + conf_list = list(set(conf_list)) +else: + conf_list = [%(default_configuration)r] + +sconsbuild_dir = Dir(%(sconsbuild_dir)s) + + +def FilterOut(self, **kw): + kw = SCons.Environment.copy_non_reserved_keywords(kw) + for key, val in kw.items(): + envval = self.get(key, None) + if envval is None: + # No existing variable in the environment, so nothing to delete. + continue + + for vremove in val: + # Use while not if, so we can handle duplicates. + while vremove in envval: + envval.remove(vremove) + + self[key] = envval + + # TODO(sgk): SCons.Environment.Append() has much more logic to deal + # with various types of values. We should handle all those cases in here + # too. (If variable is a dict, etc.) + + +non_compilable_suffixes = { + 'LINUX' : set([ + '.bdic', + '.css', + '.dat', + '.fragment', + '.gperf', + '.h', + '.hh', + '.hpp', + '.html', + '.hxx', + '.idl', + '.in', + '.in0', + '.in1', + '.js', + '.mk', + '.rc', + '.sigs', + '', + ]), + 'WINDOWS' : set([ + '.h', + '.hh', + '.hpp', + '.dat', + '.idl', + '.in', + '.in0', + '.in1', + ]), +} + +def compilable(env, file): + base, ext = os.path.splitext(str(file)) + if ext in non_compilable_suffixes[env['TARGET_PLATFORM']]: + return False + return True + +def compilable_files(env, sources): + return [x for x in sources if compilable(env, x)] + +def GypProgram(env, target, source, *args, **kw): + source = compilable_files(env, source) + result = env.Program(target, source, *args, **kw) + if env.get('INCREMENTAL'): + env.Precious(result) + return result + +def GypTestProgram(env, target, source, *args, **kw): + source = compilable_files(env, source) + result = env.Program(target, source, *args, **kw) + if env.get('INCREMENTAL'): + env.Precious(*result) + return result + +def GypLibrary(env, target, source, *args, **kw): + source = compilable_files(env, source) + result = env.Library(target, source, *args, **kw) + return result + +def GypLoadableModule(env, target, source, *args, **kw): + source = compilable_files(env, source) + result = env.LoadableModule(target, source, *args, **kw) + return result + +def GypStaticLibrary(env, target, source, *args, **kw): + source = compilable_files(env, source) + result = env.StaticLibrary(target, source, *args, **kw) + return result + +def GypSharedLibrary(env, target, source, *args, **kw): + source = compilable_files(env, source) + result = env.SharedLibrary(target, source, *args, **kw) + if env.get('INCREMENTAL'): + env.Precious(result) + return result + +def add_gyp_methods(env): + env.AddMethod(GypProgram) + env.AddMethod(GypTestProgram) + env.AddMethod(GypLibrary) + env.AddMethod(GypLoadableModule) + env.AddMethod(GypStaticLibrary) + env.AddMethod(GypSharedLibrary) + + env.AddMethod(FilterOut) + + env.AddMethod(compilable) + + +base_env = Environment( + tools = %(scons_tools)s, + INTERMEDIATE_DIR='$OBJ_DIR/${COMPONENT_NAME}/_${TARGET_NAME}_intermediate', + LIB_DIR='$TOP_BUILDDIR/lib', + OBJ_DIR='$TOP_BUILDDIR/obj', + SCONSBUILD_DIR=sconsbuild_dir.abspath, + SHARED_INTERMEDIATE_DIR='$OBJ_DIR/_global_intermediate', + SRC_DIR=Dir(%(src_dir)r), + TARGET_PLATFORM='LINUX', + TOP_BUILDDIR='$SCONSBUILD_DIR/$CONFIG_NAME', + LIBPATH=['$LIB_DIR'], +) + +if not GetOption('verbose'): + base_env.SetDefault( + ARCOMSTR='Creating library $TARGET', + ASCOMSTR='Assembling $TARGET', + CCCOMSTR='Compiling $TARGET', + CONCATSOURCECOMSTR='ConcatSource $TARGET', + CXXCOMSTR='Compiling $TARGET', + LDMODULECOMSTR='Building loadable module $TARGET', + LINKCOMSTR='Linking $TARGET', + MANIFESTCOMSTR='Updating manifest for $TARGET', + MIDLCOMSTR='Compiling IDL $TARGET', + PCHCOMSTR='Precompiling $TARGET', + RANLIBCOMSTR='Indexing $TARGET', + RCCOMSTR='Compiling resource $TARGET', + SHCCCOMSTR='Compiling $TARGET', + SHCXXCOMSTR='Compiling $TARGET', + SHLINKCOMSTR='Linking $TARGET', + SHMANIFESTCOMSTR='Updating manifest for $TARGET', + ) + +add_gyp_methods(base_env) + +for conf in conf_list: + env = base_env.Clone(CONFIG_NAME=conf) + SConsignFile(env.File('$TOP_BUILDDIR/.sconsign').abspath) + for sconscript in sconscript_files: + target_alias = env.SConscript(sconscript, exports=['env']) + if target_alias: + target_alias_list.extend(target_alias) + +Default(Alias('all', target_alias_list)) + +help_fmt = ''' +Usage: hammer [SCONS_OPTIONS] [VARIABLES] [TARGET] ... + +Local command-line build options: + --mode=CONFIG Configuration to build: + --mode=Debug [default] + --mode=Release + --verbose Print actual executed command lines. + +Supported command-line build variables: + LOAD=[module,...] Comma-separated list of components to load in the + dependency graph ('-' prefix excludes) + PROGRESS=type Display a progress indicator: + name: print each evaluated target name + spinner: print a spinner every 5 targets + +The following TARGET names can also be used as LOAD= module names: + +%%s +''' + +if GetOption('help'): + def columnar_text(items, width=78, indent=2, sep=2): + result = [] + colwidth = max(map(len, items)) + sep + cols = (width - indent) / colwidth + if cols < 1: + cols = 1 + rows = (len(items) + cols - 1) / cols + indent = '%%*s' %% (indent, '') + sep = indent + for row in xrange(0, rows): + result.append(sep) + for i in xrange(row, len(items), rows): + result.append('%%-*s' %% (colwidth, items[i])) + sep = '\\n' + indent + result.append('\\n') + return ''.join(result) + + load_list = set(sconscript_file_map.keys()) + target_aliases = set(map(str, target_alias_list)) + + common = load_list and target_aliases + load_only = load_list - common + target_only = target_aliases - common + help_text = [help_fmt %% columnar_text(sorted(list(common)))] + if target_only: + fmt = "The following are additional TARGET names:\\n\\n%%s\\n" + help_text.append(fmt %% columnar_text(sorted(list(target_only)))) + if load_only: + fmt = "The following are additional LOAD= module names:\\n\\n%%s\\n" + help_text.append(fmt %% columnar_text(sorted(list(load_only)))) + Help(''.join(help_text)) +""" + +# TEMPLATE END +############################################################################# + + +def GenerateSConscriptWrapper(build_file, build_file_data, name, + output_filename, sconscript_files, + default_configuration): + """ + Generates the "wrapper" SConscript file (analogous to the Visual Studio + solution) that calls all the individual target SConscript files. + """ + output_dir = os.path.dirname(output_filename) + src_dir = build_file_data['_DEPTH'] + src_dir_rel = gyp.common.RelativePath(src_dir, output_dir) + if not src_dir_rel: + src_dir_rel = '.' + scons_settings = build_file_data.get('scons_settings', {}) + sconsbuild_dir = scons_settings.get('sconsbuild_dir', '#') + scons_tools = scons_settings.get('tools', ['default']) + + sconscript_file_lines = ['dict('] + for target in sorted(sconscript_files.keys()): + sconscript = sconscript_files[target] + sconscript_file_lines.append(' %s = %r,' % (target, sconscript)) + sconscript_file_lines.append(')') + + fp = open(output_filename, 'w') + fp.write(header) + fp.write(_wrapper_template % { + 'default_configuration' : default_configuration, + 'name' : name, + 'scons_tools' : repr(scons_tools), + 'sconsbuild_dir' : repr(sconsbuild_dir), + 'sconscript_files' : '\n'.join(sconscript_file_lines), + 'src_dir' : src_dir_rel, + }) + fp.close() + + # Generate the SConstruct file that invokes the wrapper SConscript. + dir, fname = os.path.split(output_filename) + SConstruct = os.path.join(dir, 'SConstruct') + fp = open(SConstruct, 'w') + fp.write(header) + fp.write('SConscript(%s)\n' % repr(fname)) + fp.close() + + +def TargetFilename(target, build_file=None, output_suffix=''): + """Returns the .scons file name for the specified target. + """ + if build_file is None: + build_file, target = gyp.common.ParseQualifiedTarget(target)[:2] + output_file = os.path.join(os.path.dirname(build_file), + target + output_suffix + '.scons') + return output_file + + +def GenerateOutput(target_list, target_dicts, data, params): + """ + Generates all the output files for the specified targets. + """ + options = params['options'] + + if options.generator_output: + def output_path(filename): + return filename.replace(params['cwd'], options.generator_output) + else: + def output_path(filename): + return filename + + default_configuration = None + + for qualified_target in target_list: + spec = target_dicts[qualified_target] + if spec['toolset'] != 'target': + raise Exception( + 'Multiple toolsets not supported in scons build (target %s)' % + qualified_target) + scons_target = SCons.Target(spec) + if scons_target.is_ignored: + continue + + # TODO: assumes the default_configuration of the first target + # non-Default target is the correct default for all targets. + # Need a better model for handle variation between targets. + if (not default_configuration and + spec['default_configuration'] != 'Default'): + default_configuration = spec['default_configuration'] + + build_file, target = gyp.common.ParseQualifiedTarget(qualified_target)[:2] + output_file = TargetFilename(target, build_file, options.suffix) + if options.generator_output: + output_file = output_path(output_file) + + if not spec.has_key('libraries'): + spec['libraries'] = [] + + # Add dependent static library targets to the 'libraries' value. + deps = spec.get('dependencies', []) + spec['scons_dependencies'] = [] + for d in deps: + td = target_dicts[d] + target_name = td['target_name'] + spec['scons_dependencies'].append("Alias('%s')" % target_name) + if td['type'] in ('static_library', 'shared_library'): + libname = td.get('product_name', target_name) + spec['libraries'].append('lib' + libname) + if td['type'] == 'loadable_module': + prereqs = spec.get('scons_prerequisites', []) + # TODO: parameterize with <(SHARED_LIBRARY_*) variables? + td_target = SCons.Target(td) + td_target.target_prefix = '${SHLIBPREFIX}' + td_target.target_suffix = '${SHLIBSUFFIX}' + + GenerateSConscript(output_file, spec, build_file, data[build_file]) + + if not default_configuration: + default_configuration = 'Default' + + for build_file in sorted(data.keys()): + path, ext = os.path.splitext(build_file) + if ext != '.gyp': + continue + output_dir, basename = os.path.split(path) + output_filename = path + '_main' + options.suffix + '.scons' + + all_targets = gyp.common.AllTargets(target_list, target_dicts, build_file) + sconscript_files = {} + for t in all_targets: + scons_target = SCons.Target(target_dicts[t]) + if scons_target.is_ignored: + continue + bf, target = gyp.common.ParseQualifiedTarget(t)[:2] + target_filename = TargetFilename(target, bf, options.suffix) + tpath = gyp.common.RelativePath(target_filename, output_dir) + sconscript_files[target] = tpath + + output_filename = output_path(output_filename) + if sconscript_files: + GenerateSConscriptWrapper(build_file, data[build_file], basename, + output_filename, sconscript_files, + default_configuration) diff --git a/node-v0.8.14/tools/gyp/pylib/gyp/generator/xcode.py b/node-v0.8.14/tools/gyp/pylib/gyp/generator/xcode.py new file mode 100644 index 0000000..9ea4fbd --- /dev/null +++ b/node-v0.8.14/tools/gyp/pylib/gyp/generator/xcode.py @@ -0,0 +1,1211 @@ +# Copyright (c) 2012 Google Inc. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +import filecmp +import gyp.common +import gyp.xcodeproj_file +import errno +import os +import sys +import posixpath +import re +import shutil +import subprocess +import tempfile + + +# Project files generated by this module will use _intermediate_var as a +# custom Xcode setting whose value is a DerivedSources-like directory that's +# project-specific and configuration-specific. The normal choice, +# DERIVED_FILE_DIR, is target-specific, which is thought to be too restrictive +# as it is likely that multiple targets within a single project file will want +# to access the same set of generated files. The other option, +# PROJECT_DERIVED_FILE_DIR, is unsuitable because while it is project-specific, +# it is not configuration-specific. INTERMEDIATE_DIR is defined as +# $(PROJECT_DERIVED_FILE_DIR)/$(CONFIGURATION). +_intermediate_var = 'INTERMEDIATE_DIR' + +# SHARED_INTERMEDIATE_DIR is the same, except that it is shared among all +# targets that share the same BUILT_PRODUCTS_DIR. +_shared_intermediate_var = 'SHARED_INTERMEDIATE_DIR' + +_library_search_paths_var = 'LIBRARY_SEARCH_PATHS' + +generator_default_variables = { + 'EXECUTABLE_PREFIX': '', + 'EXECUTABLE_SUFFIX': '', + 'STATIC_LIB_PREFIX': 'lib', + 'SHARED_LIB_PREFIX': 'lib', + 'STATIC_LIB_SUFFIX': '.a', + 'SHARED_LIB_SUFFIX': '.dylib', + # INTERMEDIATE_DIR is a place for targets to build up intermediate products. + # It is specific to each build environment. It is only guaranteed to exist + # and be constant within the context of a project, corresponding to a single + # input file. Some build environments may allow their intermediate directory + # to be shared on a wider scale, but this is not guaranteed. + 'INTERMEDIATE_DIR': '$(%s)' % _intermediate_var, + 'OS': 'mac', + 'PRODUCT_DIR': '$(BUILT_PRODUCTS_DIR)', + 'LIB_DIR': '$(BUILT_PRODUCTS_DIR)', + 'RULE_INPUT_ROOT': '$(INPUT_FILE_BASE)', + 'RULE_INPUT_EXT': '$(INPUT_FILE_SUFFIX)', + 'RULE_INPUT_NAME': '$(INPUT_FILE_NAME)', + 'RULE_INPUT_PATH': '$(INPUT_FILE_PATH)', + 'RULE_INPUT_DIRNAME': '$(INPUT_FILE_DIRNAME)', + 'SHARED_INTERMEDIATE_DIR': '$(%s)' % _shared_intermediate_var, + 'CONFIGURATION_NAME': '$(CONFIGURATION)', +} + +# The Xcode-specific sections that hold paths. +generator_additional_path_sections = [ + 'mac_bundle_resources', + 'mac_framework_headers', + 'mac_framework_private_headers', + # 'mac_framework_dirs', input already handles _dirs endings. +] + +# The Xcode-specific keys that exist on targets and aren't moved down to +# configurations. +generator_additional_non_configuration_keys = [ + 'mac_bundle', + 'mac_bundle_resources', + 'mac_framework_headers', + 'mac_framework_private_headers', + 'xcode_create_dependents_test_runner', +] + +# We want to let any rules apply to files that are resources also. +generator_extra_sources_for_rules = [ + 'mac_bundle_resources', + 'mac_framework_headers', + 'mac_framework_private_headers', +] + +# Xcode's standard set of library directories, which don't need to be duplicated +# in LIBRARY_SEARCH_PATHS. This list is not exhaustive, but that's okay. +xcode_standard_library_dirs = frozenset([ + '$(SDKROOT)/usr/lib', + '$(SDKROOT)/usr/local/lib', +]) + +def CreateXCConfigurationList(configuration_names): + xccl = gyp.xcodeproj_file.XCConfigurationList({'buildConfigurations': []}) + if len(configuration_names) == 0: + configuration_names = ['Default'] + for configuration_name in configuration_names: + xcbc = gyp.xcodeproj_file.XCBuildConfiguration({ + 'name': configuration_name}) + xccl.AppendProperty('buildConfigurations', xcbc) + xccl.SetProperty('defaultConfigurationName', configuration_names[0]) + return xccl + + +class XcodeProject(object): + def __init__(self, gyp_path, path, build_file_dict): + self.gyp_path = gyp_path + self.path = path + self.project = gyp.xcodeproj_file.PBXProject(path=path) + projectDirPath = gyp.common.RelativePath( + os.path.dirname(os.path.abspath(self.gyp_path)), + os.path.dirname(path) or '.') + self.project.SetProperty('projectDirPath', projectDirPath) + self.project_file = \ + gyp.xcodeproj_file.XCProjectFile({'rootObject': self.project}) + self.build_file_dict = build_file_dict + + # TODO(mark): add destructor that cleans up self.path if created_dir is + # True and things didn't complete successfully. Or do something even + # better with "try"? + self.created_dir = False + try: + os.makedirs(self.path) + self.created_dir = True + except OSError, e: + if e.errno != errno.EEXIST: + raise + + def Finalize1(self, xcode_targets, serialize_all_tests): + # Collect a list of all of the build configuration names used by the + # various targets in the file. It is very heavily advised to keep each + # target in an entire project (even across multiple project files) using + # the same set of configuration names. + configurations = [] + for xct in self.project.GetProperty('targets'): + xccl = xct.GetProperty('buildConfigurationList') + xcbcs = xccl.GetProperty('buildConfigurations') + for xcbc in xcbcs: + name = xcbc.GetProperty('name') + if name not in configurations: + configurations.append(name) + + # Replace the XCConfigurationList attached to the PBXProject object with + # a new one specifying all of the configuration names used by the various + # targets. + try: + xccl = CreateXCConfigurationList(configurations) + self.project.SetProperty('buildConfigurationList', xccl) + except: + sys.stderr.write("Problem with gyp file %s\n" % self.gyp_path) + raise + + # The need for this setting is explained above where _intermediate_var is + # defined. The comments below about wanting to avoid project-wide build + # settings apply here too, but this needs to be set on a project-wide basis + # so that files relative to the _intermediate_var setting can be displayed + # properly in the Xcode UI. + # + # Note that for configuration-relative files such as anything relative to + # _intermediate_var, for the purposes of UI tree view display, Xcode will + # only resolve the configuration name once, when the project file is + # opened. If the active build configuration is changed, the project file + # must be closed and reopened if it is desired for the tree view to update. + # This is filed as Apple radar 6588391. + xccl.SetBuildSetting(_intermediate_var, + '$(PROJECT_DERIVED_FILE_DIR)/$(CONFIGURATION)') + xccl.SetBuildSetting(_shared_intermediate_var, + '$(SYMROOT)/DerivedSources/$(CONFIGURATION)') + + # Set user-specified project-wide build settings and config files. This + # is intended to be used very sparingly. Really, almost everything should + # go into target-specific build settings sections. The project-wide + # settings are only intended to be used in cases where Xcode attempts to + # resolve variable references in a project context as opposed to a target + # context, such as when resolving sourceTree references while building up + # the tree tree view for UI display. + # Any values set globally are applied to all configurations, then any + # per-configuration values are applied. + for xck, xcv in self.build_file_dict.get('xcode_settings', {}).iteritems(): + xccl.SetBuildSetting(xck, xcv) + if 'xcode_config_file' in self.build_file_dict: + config_ref = self.project.AddOrGetFileInRootGroup( + self.build_file_dict['xcode_config_file']) + xccl.SetBaseConfiguration(config_ref) + build_file_configurations = self.build_file_dict.get('configurations', {}) + if build_file_configurations: + for config_name in configurations: + build_file_configuration_named = \ + build_file_configurations.get(config_name, {}) + if build_file_configuration_named: + xcc = xccl.ConfigurationNamed(config_name) + for xck, xcv in build_file_configuration_named.get('xcode_settings', + {}).iteritems(): + xcc.SetBuildSetting(xck, xcv) + if 'xcode_config_file' in build_file_configuration_named: + config_ref = self.project.AddOrGetFileInRootGroup( + build_file_configurations[config_name]['xcode_config_file']) + xcc.SetBaseConfiguration(config_ref) + + # Sort the targets based on how they appeared in the input. + # TODO(mark): Like a lot of other things here, this assumes internal + # knowledge of PBXProject - in this case, of its "targets" property. + + # ordinary_targets are ordinary targets that are already in the project + # file. run_test_targets are the targets that run unittests and should be + # used for the Run All Tests target. support_targets are the action/rule + # targets used by GYP file targets, just kept for the assert check. + ordinary_targets = [] + run_test_targets = [] + support_targets = [] + + # targets is full list of targets in the project. + targets = [] + + # does the it define it's own "all"? + has_custom_all = False + + # targets_for_all is the list of ordinary_targets that should be listed + # in this project's "All" target. It includes each non_runtest_target + # that does not have suppress_wildcard set. + targets_for_all = [] + + for target in self.build_file_dict['targets']: + target_name = target['target_name'] + toolset = target['toolset'] + qualified_target = gyp.common.QualifiedTarget(self.gyp_path, target_name, + toolset) + xcode_target = xcode_targets[qualified_target] + # Make sure that the target being added to the sorted list is already in + # the unsorted list. + assert xcode_target in self.project._properties['targets'] + targets.append(xcode_target) + ordinary_targets.append(xcode_target) + if xcode_target.support_target: + support_targets.append(xcode_target.support_target) + targets.append(xcode_target.support_target) + + if not int(target.get('suppress_wildcard', False)): + targets_for_all.append(xcode_target) + + if target_name.lower() == 'all': + has_custom_all = True; + + # If this target has a 'run_as' attribute, add its target to the + # targets, and add it to the test targets. + if target.get('run_as'): + # Make a target to run something. It should have one + # dependency, the parent xcode target. + xccl = CreateXCConfigurationList(configurations) + run_target = gyp.xcodeproj_file.PBXAggregateTarget({ + 'name': 'Run ' + target_name, + 'productName': xcode_target.GetProperty('productName'), + 'buildConfigurationList': xccl, + }, + parent=self.project) + run_target.AddDependency(xcode_target) + + command = target['run_as'] + script = '' + if command.get('working_directory'): + script = script + 'cd "%s"\n' % \ + gyp.xcodeproj_file.ConvertVariablesToShellSyntax( + command.get('working_directory')) + + if command.get('environment'): + script = script + "\n".join( + ['export %s="%s"' % + (key, gyp.xcodeproj_file.ConvertVariablesToShellSyntax(val)) + for (key, val) in command.get('environment').iteritems()]) + "\n" + + # Some test end up using sockets, files on disk, etc. and can get + # confused if more then one test runs at a time. The generator + # flag 'xcode_serialize_all_test_runs' controls the forcing of all + # tests serially. It defaults to True. To get serial runs this + # little bit of python does the same as the linux flock utility to + # make sure only one runs at a time. + command_prefix = '' + if serialize_all_tests: + command_prefix = \ +"""python -c "import fcntl, subprocess, sys +file = open('$TMPDIR/GYP_serialize_test_runs', 'a') +fcntl.flock(file.fileno(), fcntl.LOCK_EX) +sys.exit(subprocess.call(sys.argv[1:]))" """ + + # If we were unable to exec for some reason, we want to exit + # with an error, and fixup variable references to be shell + # syntax instead of xcode syntax. + script = script + 'exec ' + command_prefix + '%s\nexit 1\n' % \ + gyp.xcodeproj_file.ConvertVariablesToShellSyntax( + gyp.common.EncodePOSIXShellList(command.get('action'))) + + ssbp = gyp.xcodeproj_file.PBXShellScriptBuildPhase({ + 'shellScript': script, + 'showEnvVarsInLog': 0, + }) + run_target.AppendProperty('buildPhases', ssbp) + + # Add the run target to the project file. + targets.append(run_target) + run_test_targets.append(run_target) + xcode_target.test_runner = run_target + + + # Make sure that the list of targets being replaced is the same length as + # the one replacing it, but allow for the added test runner targets. + assert len(self.project._properties['targets']) == \ + len(ordinary_targets) + len(support_targets) + + self.project._properties['targets'] = targets + + # Get rid of unnecessary levels of depth in groups like the Source group. + self.project.RootGroupsTakeOverOnlyChildren(True) + + # Sort the groups nicely. Do this after sorting the targets, because the + # Products group is sorted based on the order of the targets. + self.project.SortGroups() + + # Create an "All" target if there's more than one target in this project + # file and the project didn't define its own "All" target. Put a generated + # "All" target first so that people opening up the project for the first + # time will build everything by default. + if len(targets_for_all) > 1 and not has_custom_all: + xccl = CreateXCConfigurationList(configurations) + all_target = gyp.xcodeproj_file.PBXAggregateTarget( + { + 'buildConfigurationList': xccl, + 'name': 'All', + }, + parent=self.project) + + for target in targets_for_all: + all_target.AddDependency(target) + + # TODO(mark): This is evil because it relies on internal knowledge of + # PBXProject._properties. It's important to get the "All" target first, + # though. + self.project._properties['targets'].insert(0, all_target) + + # The same, but for run_test_targets. + if len(run_test_targets) > 1: + xccl = CreateXCConfigurationList(configurations) + run_all_tests_target = gyp.xcodeproj_file.PBXAggregateTarget( + { + 'buildConfigurationList': xccl, + 'name': 'Run All Tests', + }, + parent=self.project) + for run_test_target in run_test_targets: + run_all_tests_target.AddDependency(run_test_target) + + # Insert after the "All" target, which must exist if there is more than + # one run_test_target. + self.project._properties['targets'].insert(1, run_all_tests_target) + + def Finalize2(self, xcode_targets, xcode_target_to_target_dict): + # Finalize2 needs to happen in a separate step because the process of + # updating references to other projects depends on the ordering of targets + # within remote project files. Finalize1 is responsible for sorting duty, + # and once all project files are sorted, Finalize2 can come in and update + # these references. + + # To support making a "test runner" target that will run all the tests + # that are direct dependents of any given target, we look for + # xcode_create_dependents_test_runner being set on an Aggregate target, + # and generate a second target that will run the tests runners found under + # the marked target. + for bf_tgt in self.build_file_dict['targets']: + if int(bf_tgt.get('xcode_create_dependents_test_runner', 0)): + tgt_name = bf_tgt['target_name'] + toolset = bf_tgt['toolset'] + qualified_target = gyp.common.QualifiedTarget(self.gyp_path, + tgt_name, toolset) + xcode_target = xcode_targets[qualified_target] + if isinstance(xcode_target, gyp.xcodeproj_file.PBXAggregateTarget): + # Collect all the run test targets. + all_run_tests = [] + pbxtds = xcode_target.GetProperty('dependencies') + for pbxtd in pbxtds: + pbxcip = pbxtd.GetProperty('targetProxy') + dependency_xct = pbxcip.GetProperty('remoteGlobalIDString') + if hasattr(dependency_xct, 'test_runner'): + all_run_tests.append(dependency_xct.test_runner) + + # Directly depend on all the runners as they depend on the target + # that builds them. + if len(all_run_tests) > 0: + run_all_target = gyp.xcodeproj_file.PBXAggregateTarget({ + 'name': 'Run %s Tests' % tgt_name, + 'productName': tgt_name, + }, + parent=self.project) + for run_test_target in all_run_tests: + run_all_target.AddDependency(run_test_target) + + # Insert the test runner after the related target. + idx = self.project._properties['targets'].index(xcode_target) + self.project._properties['targets'].insert(idx + 1, run_all_target) + + # Update all references to other projects, to make sure that the lists of + # remote products are complete. Otherwise, Xcode will fill them in when + # it opens the project file, which will result in unnecessary diffs. + # TODO(mark): This is evil because it relies on internal knowledge of + # PBXProject._other_pbxprojects. + for other_pbxproject in self.project._other_pbxprojects.keys(): + self.project.AddOrGetProjectReference(other_pbxproject) + + self.project.SortRemoteProductReferences() + + # Give everything an ID. + self.project_file.ComputeIDs() + + # Make sure that no two objects in the project file have the same ID. If + # multiple objects wind up with the same ID, upon loading the file, Xcode + # will only recognize one object (the last one in the file?) and the + # results are unpredictable. + self.project_file.EnsureNoIDCollisions() + + def Write(self): + # Write the project file to a temporary location first. Xcode watches for + # changes to the project file and presents a UI sheet offering to reload + # the project when it does change. However, in some cases, especially when + # multiple projects are open or when Xcode is busy, things don't work so + # seamlessly. Sometimes, Xcode is able to detect that a project file has + # changed but can't unload it because something else is referencing it. + # To mitigate this problem, and to avoid even having Xcode present the UI + # sheet when an open project is rewritten for inconsequential changes, the + # project file is written to a temporary file in the xcodeproj directory + # first. The new temporary file is then compared to the existing project + # file, if any. If they differ, the new file replaces the old; otherwise, + # the new project file is simply deleted. Xcode properly detects a file + # being renamed over an open project file as a change and so it remains + # able to present the "project file changed" sheet under this system. + # Writing to a temporary file first also avoids the possible problem of + # Xcode rereading an incomplete project file. + (output_fd, new_pbxproj_path) = \ + tempfile.mkstemp(suffix='.tmp', prefix='project.pbxproj.gyp.', + dir=self.path) + + try: + output_file = os.fdopen(output_fd, 'wb') + + self.project_file.Print(output_file) + output_file.close() + + pbxproj_path = os.path.join(self.path, 'project.pbxproj') + + same = False + try: + same = filecmp.cmp(pbxproj_path, new_pbxproj_path, False) + except OSError, e: + if e.errno != errno.ENOENT: + raise + + if same: + # The new file is identical to the old one, just get rid of the new + # one. + os.unlink(new_pbxproj_path) + else: + # The new file is different from the old one, or there is no old one. + # Rename the new file to the permanent name. + # + # tempfile.mkstemp uses an overly restrictive mode, resulting in a + # file that can only be read by the owner, regardless of the umask. + # There's no reason to not respect the umask here, which means that + # an extra hoop is required to fetch it and reset the new file's mode. + # + # No way to get the umask without setting a new one? Set a safe one + # and then set it back to the old value. + umask = os.umask(077) + os.umask(umask) + + os.chmod(new_pbxproj_path, 0666 & ~umask) + os.rename(new_pbxproj_path, pbxproj_path) + + except Exception: + # Don't leave turds behind. In fact, if this code was responsible for + # creating the xcodeproj directory, get rid of that too. + os.unlink(new_pbxproj_path) + if self.created_dir: + shutil.rmtree(self.path, True) + raise + + +cached_xcode_version = None +def InstalledXcodeVersion(): + """Fetches the installed version of Xcode, returns empty string if it is + unable to figure it out.""" + + global cached_xcode_version + if not cached_xcode_version is None: + return cached_xcode_version + + # Default to an empty string + cached_xcode_version = '' + + # Collect the xcodebuild's version information. + try: + import subprocess + cmd = ['/usr/bin/xcodebuild', '-version'] + proc = subprocess.Popen(cmd, stdout=subprocess.PIPE) + xcodebuild_version_info = proc.communicate()[0] + # Any error, return empty string + if proc.returncode: + xcodebuild_version_info = '' + except OSError: + # We failed to launch the tool + xcodebuild_version_info = '' + + # Pull out the Xcode version itself. + match_line = re.search('^Xcode (.*)$', xcodebuild_version_info, re.MULTILINE) + if match_line: + cached_xcode_version = match_line.group(1) + # Done! + return cached_xcode_version + + +def AddSourceToTarget(source, type, pbxp, xct): + # TODO(mark): Perhaps source_extensions and library_extensions can be made a + # little bit fancier. + source_extensions = ['c', 'cc', 'cpp', 'cxx', 'm', 'mm', 's'] + + # .o is conceptually more of a "source" than a "library," but Xcode thinks + # of "sources" as things to compile and "libraries" (or "frameworks") as + # things to link with. Adding an object file to an Xcode target's frameworks + # phase works properly. + library_extensions = ['a', 'dylib', 'framework', 'o'] + + basename = posixpath.basename(source) + (root, ext) = posixpath.splitext(basename) + if ext: + ext = ext[1:].lower() + + if ext in source_extensions and type != 'none': + xct.SourcesPhase().AddFile(source) + elif ext in library_extensions and type != 'none': + xct.FrameworksPhase().AddFile(source) + else: + # Files that aren't added to a sources or frameworks build phase can still + # go into the project file, just not as part of a build phase. + pbxp.AddOrGetFileInRootGroup(source) + + +def AddResourceToTarget(resource, pbxp, xct): + # TODO(mark): Combine with AddSourceToTarget above? Or just inline this call + # where it's used. + xct.ResourcesPhase().AddFile(resource) + + +def AddHeaderToTarget(header, pbxp, xct, is_public): + # TODO(mark): Combine with AddSourceToTarget above? Or just inline this call + # where it's used. + settings = '{ATTRIBUTES = (%s, ); }' % ('Private', 'Public')[is_public] + xct.HeadersPhase().AddFile(header, settings) + + +_xcode_variable_re = re.compile('(\$\((.*?)\))') +def ExpandXcodeVariables(string, expansions): + """Expands Xcode-style $(VARIABLES) in string per the expansions dict. + + In some rare cases, it is appropriate to expand Xcode variables when a + project file is generated. For any substring $(VAR) in string, if VAR is a + key in the expansions dict, $(VAR) will be replaced with expansions[VAR]. + Any $(VAR) substring in string for which VAR is not a key in the expansions + dict will remain in the returned string. + """ + + matches = _xcode_variable_re.findall(string) + if matches == None: + return string + + matches.reverse() + for match in matches: + (to_replace, variable) = match + if not variable in expansions: + continue + + replacement = expansions[variable] + string = re.sub(re.escape(to_replace), replacement, string) + + return string + + +def EscapeXCodeArgument(s): + """We must escape the arguments that we give to XCode so that it knows not to + split on spaces and to respect backslash and quote literals.""" + s = s.replace('\\', '\\\\') + s = s.replace('"', '\\"') + return '"' + s + '"' + + +def GenerateOutput(target_list, target_dicts, data, params): + options = params['options'] + generator_flags = params.get('generator_flags', {}) + parallel_builds = generator_flags.get('xcode_parallel_builds', True) + serialize_all_tests = \ + generator_flags.get('xcode_serialize_all_test_runs', True) + project_version = generator_flags.get('xcode_project_version', None) + skip_excluded_files = \ + not generator_flags.get('xcode_list_excluded_files', True) + xcode_projects = {} + for build_file, build_file_dict in data.iteritems(): + (build_file_root, build_file_ext) = os.path.splitext(build_file) + if build_file_ext != '.gyp': + continue + xcodeproj_path = build_file_root + options.suffix + '.xcodeproj' + if options.generator_output: + xcodeproj_path = os.path.join(options.generator_output, xcodeproj_path) + xcp = XcodeProject(build_file, xcodeproj_path, build_file_dict) + xcode_projects[build_file] = xcp + pbxp = xcp.project + + if parallel_builds: + pbxp.SetProperty('attributes', + {'BuildIndependentTargetsInParallel': 'YES'}) + if project_version: + xcp.project_file.SetXcodeVersion(project_version) + + # Add gyp/gypi files to project + if not generator_flags.get('standalone'): + main_group = pbxp.GetProperty('mainGroup') + build_group = gyp.xcodeproj_file.PBXGroup({'name': 'Build'}) + main_group.AppendChild(build_group) + for included_file in build_file_dict['included_files']: + build_group.AddOrGetFileByPath(included_file, False) + + xcode_targets = {} + xcode_target_to_target_dict = {} + for qualified_target in target_list: + [build_file, target_name, toolset] = \ + gyp.common.ParseQualifiedTarget(qualified_target) + + spec = target_dicts[qualified_target] + if spec['toolset'] != 'target': + raise Exception( + 'Multiple toolsets not supported in xcode build (target %s)' % + qualified_target) + configuration_names = [spec['default_configuration']] + for configuration_name in sorted(spec['configurations'].keys()): + if configuration_name not in configuration_names: + configuration_names.append(configuration_name) + xcp = xcode_projects[build_file] + pbxp = xcp.project + + # Set up the configurations for the target according to the list of names + # supplied. + xccl = CreateXCConfigurationList(configuration_names) + + # Create an XCTarget subclass object for the target. The type with + # "+bundle" appended will be used if the target has "mac_bundle" set. + # loadable_modules not in a mac_bundle are mapped to + # com.googlecode.gyp.xcode.bundle, a pseudo-type that xcode.py interprets + # to create a single-file mh_bundle. + _types = { + 'executable': 'com.apple.product-type.tool', + 'loadable_module': 'com.googlecode.gyp.xcode.bundle', + 'shared_library': 'com.apple.product-type.library.dynamic', + 'static_library': 'com.apple.product-type.library.static', + 'executable+bundle': 'com.apple.product-type.application', + 'loadable_module+bundle': 'com.apple.product-type.bundle', + 'shared_library+bundle': 'com.apple.product-type.framework', + } + + target_properties = { + 'buildConfigurationList': xccl, + 'name': target_name, + } + + type = spec['type'] + is_bundle = int(spec.get('mac_bundle', 0)) + if type != 'none': + type_bundle_key = type + if is_bundle: + type_bundle_key += '+bundle' + xctarget_type = gyp.xcodeproj_file.PBXNativeTarget + try: + target_properties['productType'] = _types[type_bundle_key] + except KeyError, e: + gyp.common.ExceptionAppend(e, "-- unknown product type while " + "writing target %s" % target_name) + raise + else: + xctarget_type = gyp.xcodeproj_file.PBXAggregateTarget + assert not is_bundle, ( + 'mac_bundle targets cannot have type none (target "%s")' % + target_name) + + target_product_name = spec.get('product_name') + if target_product_name is not None: + target_properties['productName'] = target_product_name + + xct = xctarget_type(target_properties, parent=pbxp, + force_outdir=spec.get('product_dir'), + force_prefix=spec.get('product_prefix'), + force_extension=spec.get('product_extension')) + pbxp.AppendProperty('targets', xct) + xcode_targets[qualified_target] = xct + xcode_target_to_target_dict[xct] = spec + + spec_actions = spec.get('actions', []) + spec_rules = spec.get('rules', []) + + # Xcode has some "issues" with checking dependencies for the "Compile + # sources" step with any source files/headers generated by actions/rules. + # To work around this, if a target is building anything directly (not + # type "none"), then a second target is used to run the GYP actions/rules + # and is made a dependency of this target. This way the work is done + # before the dependency checks for what should be recompiled. + support_xct = None + if type != 'none' and (spec_actions or spec_rules): + support_xccl = CreateXCConfigurationList(configuration_names); + support_target_properties = { + 'buildConfigurationList': support_xccl, + 'name': target_name + ' Support', + } + if target_product_name: + support_target_properties['productName'] = \ + target_product_name + ' Support' + support_xct = \ + gyp.xcodeproj_file.PBXAggregateTarget(support_target_properties, + parent=pbxp) + pbxp.AppendProperty('targets', support_xct) + xct.AddDependency(support_xct) + # Hang the support target off the main target so it can be tested/found + # by the generator during Finalize. + xct.support_target = support_xct + + prebuild_index = 0 + + # Add custom shell script phases for "actions" sections. + for action in spec_actions: + # There's no need to write anything into the script to ensure that the + # output directories already exist, because Xcode will look at the + # declared outputs and automatically ensure that they exist for us. + + # Do we have a message to print when this action runs? + message = action.get('message') + if message: + message = 'echo note: ' + gyp.common.EncodePOSIXShellArgument(message) + else: + message = '' + + # Turn the list into a string that can be passed to a shell. + action_string = gyp.common.EncodePOSIXShellList(action['action']) + + # Convert Xcode-type variable references to sh-compatible environment + # variable references. + message_sh = gyp.xcodeproj_file.ConvertVariablesToShellSyntax(message) + action_string_sh = gyp.xcodeproj_file.ConvertVariablesToShellSyntax( + action_string) + + script = '' + # Include the optional message + if message_sh: + script += message_sh + '\n' + # Be sure the script runs in exec, and that if exec fails, the script + # exits signalling an error. + script += 'exec ' + action_string_sh + '\nexit 1\n' + ssbp = gyp.xcodeproj_file.PBXShellScriptBuildPhase({ + 'inputPaths': action['inputs'], + 'name': 'Action "' + action['action_name'] + '"', + 'outputPaths': action['outputs'], + 'shellScript': script, + 'showEnvVarsInLog': 0, + }) + + if support_xct: + support_xct.AppendProperty('buildPhases', ssbp) + else: + # TODO(mark): this assumes too much knowledge of the internals of + # xcodeproj_file; some of these smarts should move into xcodeproj_file + # itself. + xct._properties['buildPhases'].insert(prebuild_index, ssbp) + prebuild_index = prebuild_index + 1 + + # TODO(mark): Should verify that at most one of these is specified. + if int(action.get('process_outputs_as_sources', False)): + for output in action['outputs']: + AddSourceToTarget(output, type, pbxp, xct) + + if int(action.get('process_outputs_as_mac_bundle_resources', False)): + for output in action['outputs']: + AddResourceToTarget(output, pbxp, xct) + + # tgt_mac_bundle_resources holds the list of bundle resources so + # the rule processing can check against it. + if is_bundle: + tgt_mac_bundle_resources = spec.get('mac_bundle_resources', []) + else: + tgt_mac_bundle_resources = [] + + # Add custom shell script phases driving "make" for "rules" sections. + # + # Xcode's built-in rule support is almost powerful enough to use directly, + # but there are a few significant deficiencies that render them unusable. + # There are workarounds for some of its inadequacies, but in aggregate, + # the workarounds added complexity to the generator, and some workarounds + # actually require input files to be crafted more carefully than I'd like. + # Consequently, until Xcode rules are made more capable, "rules" input + # sections will be handled in Xcode output by shell script build phases + # performed prior to the compilation phase. + # + # The following problems with Xcode rules were found. The numbers are + # Apple radar IDs. I hope that these shortcomings are addressed, I really + # liked having the rules handled directly in Xcode during the period that + # I was prototyping this. + # + # 6588600 Xcode compiles custom script rule outputs too soon, compilation + # fails. This occurs when rule outputs from distinct inputs are + # interdependent. The only workaround is to put rules and their + # inputs in a separate target from the one that compiles the rule + # outputs. This requires input file cooperation and it means that + # process_outputs_as_sources is unusable. + # 6584932 Need to declare that custom rule outputs should be excluded from + # compilation. A possible workaround is to lie to Xcode about a + # rule's output, giving it a dummy file it doesn't know how to + # compile. The rule action script would need to touch the dummy. + # 6584839 I need a way to declare additional inputs to a custom rule. + # A possible workaround is a shell script phase prior to + # compilation that touches a rule's primary input files if any + # would-be additional inputs are newer than the output. Modifying + # the source tree - even just modification times - feels dirty. + # 6564240 Xcode "custom script" build rules always dump all environment + # variables. This is a low-prioroty problem and is not a + # show-stopper. + rules_by_ext = {} + for rule in spec_rules: + rules_by_ext[rule['extension']] = rule + + # First, some definitions: + # + # A "rule source" is a file that was listed in a target's "sources" + # list and will have a rule applied to it on the basis of matching the + # rule's "extensions" attribute. Rule sources are direct inputs to + # rules. + # + # Rule definitions may specify additional inputs in their "inputs" + # attribute. These additional inputs are used for dependency tracking + # purposes. + # + # A "concrete output" is a rule output with input-dependent variables + # resolved. For example, given a rule with: + # 'extension': 'ext', 'outputs': ['$(INPUT_FILE_BASE).cc'], + # if the target's "sources" list contained "one.ext" and "two.ext", + # the "concrete output" for rule input "two.ext" would be "two.cc". If + # a rule specifies multiple outputs, each input file that the rule is + # applied to will have the same number of concrete outputs. + # + # If any concrete outputs are outdated or missing relative to their + # corresponding rule_source or to any specified additional input, the + # rule action must be performed to generate the concrete outputs. + + # concrete_outputs_by_rule_source will have an item at the same index + # as the rule['rule_sources'] that it corresponds to. Each item is a + # list of all of the concrete outputs for the rule_source. + concrete_outputs_by_rule_source = [] + + # concrete_outputs_all is a flat list of all concrete outputs that this + # rule is able to produce, given the known set of input files + # (rule_sources) that apply to it. + concrete_outputs_all = [] + + # messages & actions are keyed by the same indices as rule['rule_sources'] + # and concrete_outputs_by_rule_source. They contain the message and + # action to perform after resolving input-dependent variables. The + # message is optional, in which case None is stored for each rule source. + messages = [] + actions = [] + + for rule_source in rule.get('rule_sources', []): + rule_source_dirname, rule_source_basename = \ + posixpath.split(rule_source) + (rule_source_root, rule_source_ext) = \ + posixpath.splitext(rule_source_basename) + + # These are the same variable names that Xcode uses for its own native + # rule support. Because Xcode's rule engine is not being used, they + # need to be expanded as they are written to the makefile. + rule_input_dict = { + 'INPUT_FILE_BASE': rule_source_root, + 'INPUT_FILE_SUFFIX': rule_source_ext, + 'INPUT_FILE_NAME': rule_source_basename, + 'INPUT_FILE_PATH': rule_source, + 'INPUT_FILE_DIRNAME': rule_source_dirname, + } + + concrete_outputs_for_this_rule_source = [] + for output in rule.get('outputs', []): + # Fortunately, Xcode and make both use $(VAR) format for their + # variables, so the expansion is the only transformation necessary. + # Any remaning $(VAR)-type variables in the string can be given + # directly to make, which will pick up the correct settings from + # what Xcode puts into the environment. + concrete_output = ExpandXcodeVariables(output, rule_input_dict) + concrete_outputs_for_this_rule_source.append(concrete_output) + + # Add all concrete outputs to the project. + pbxp.AddOrGetFileInRootGroup(concrete_output) + + concrete_outputs_by_rule_source.append( \ + concrete_outputs_for_this_rule_source) + concrete_outputs_all.extend(concrete_outputs_for_this_rule_source) + + # TODO(mark): Should verify that at most one of these is specified. + if int(rule.get('process_outputs_as_sources', False)): + for output in concrete_outputs_for_this_rule_source: + AddSourceToTarget(output, type, pbxp, xct) + + # If the file came from the mac_bundle_resources list or if the rule + # is marked to process outputs as bundle resource, do so. + was_mac_bundle_resource = rule_source in tgt_mac_bundle_resources + if was_mac_bundle_resource or \ + int(rule.get('process_outputs_as_mac_bundle_resources', False)): + for output in concrete_outputs_for_this_rule_source: + AddResourceToTarget(output, pbxp, xct) + + # Do we have a message to print when this rule runs? + message = rule.get('message') + if message: + message = gyp.common.EncodePOSIXShellArgument(message) + message = ExpandXcodeVariables(message, rule_input_dict) + messages.append(message) + + # Turn the list into a string that can be passed to a shell. + action_string = gyp.common.EncodePOSIXShellList(rule['action']) + + action = ExpandXcodeVariables(action_string, rule_input_dict) + actions.append(action) + + if len(concrete_outputs_all) > 0: + # TODO(mark): There's a possibilty for collision here. Consider + # target "t" rule "A_r" and target "t_A" rule "r". + makefile_name = '%s.make' % re.sub( + '[^a-zA-Z0-9_]', '_' , '%s_%s' % (target_name, rule['rule_name'])) + makefile_path = os.path.join(xcode_projects[build_file].path, + makefile_name) + # TODO(mark): try/close? Write to a temporary file and swap it only + # if it's got changes? + makefile = open(makefile_path, 'wb') + + # make will build the first target in the makefile by default. By + # convention, it's called "all". List all (or at least one) + # concrete output for each rule source as a prerequisite of the "all" + # target. + makefile.write('all: \\\n') + for concrete_output_index in \ + xrange(0, len(concrete_outputs_by_rule_source)): + # Only list the first (index [0]) concrete output of each input + # in the "all" target. Otherwise, a parallel make (-j > 1) would + # attempt to process each input multiple times simultaneously. + # Otherwise, "all" could just contain the entire list of + # concrete_outputs_all. + concrete_output = \ + concrete_outputs_by_rule_source[concrete_output_index][0] + if concrete_output_index == len(concrete_outputs_by_rule_source) - 1: + eol = '' + else: + eol = ' \\' + makefile.write(' %s%s\n' % (concrete_output, eol)) + + for (rule_source, concrete_outputs, message, action) in \ + zip(rule['rule_sources'], concrete_outputs_by_rule_source, + messages, actions): + makefile.write('\n') + + # Add a rule that declares it can build each concrete output of a + # rule source. Collect the names of the directories that are + # required. + concrete_output_dirs = [] + for concrete_output_index in xrange(0, len(concrete_outputs)): + concrete_output = concrete_outputs[concrete_output_index] + if concrete_output_index == 0: + bol = '' + else: + bol = ' ' + makefile.write('%s%s \\\n' % (bol, concrete_output)) + + concrete_output_dir = posixpath.dirname(concrete_output) + if (concrete_output_dir and + concrete_output_dir not in concrete_output_dirs): + concrete_output_dirs.append(concrete_output_dir) + + makefile.write(' : \\\n') + + # The prerequisites for this rule are the rule source itself and + # the set of additional rule inputs, if any. + prerequisites = [rule_source] + prerequisites.extend(rule.get('inputs', [])) + for prerequisite_index in xrange(0, len(prerequisites)): + prerequisite = prerequisites[prerequisite_index] + if prerequisite_index == len(prerequisites) - 1: + eol = '' + else: + eol = ' \\' + makefile.write(' %s%s\n' % (prerequisite, eol)) + + # Make sure that output directories exist before executing the rule + # action. + if len(concrete_output_dirs) > 0: + makefile.write('\t@mkdir -p "%s"\n' % + '" "'.join(concrete_output_dirs)) + + # The rule message and action have already had the necessary variable + # substitutions performed. + if message: + # Mark it with note: so Xcode picks it up in build output. + makefile.write('\t@echo note: %s\n' % message) + makefile.write('\t%s\n' % action) + + makefile.close() + + # It might be nice to ensure that needed output directories exist + # here rather than in each target in the Makefile, but that wouldn't + # work if there ever was a concrete output that had an input-dependent + # variable anywhere other than in the leaf position. + + # Don't declare any inputPaths or outputPaths. If they're present, + # Xcode will provide a slight optimization by only running the script + # phase if any output is missing or outdated relative to any input. + # Unfortunately, it will also assume that all outputs are touched by + # the script, and if the outputs serve as files in a compilation + # phase, they will be unconditionally rebuilt. Since make might not + # rebuild everything that could be declared here as an output, this + # extra compilation activity is unnecessary. With inputPaths and + # outputPaths not supplied, make will always be called, but it knows + # enough to not do anything when everything is up-to-date. + + # To help speed things up, pass -j COUNT to make so it does some work + # in parallel. Don't use ncpus because Xcode will build ncpus targets + # in parallel and if each target happens to have a rules step, there + # would be ncpus^2 things going. With a machine that has 2 quad-core + # Xeons, a build can quickly run out of processes based on + # scheduling/other tasks, and randomly failing builds are no good. + script = \ +"""JOB_COUNT="$(/usr/sbin/sysctl -n hw.ncpu)" +if [ "${JOB_COUNT}" -gt 4 ]; then + JOB_COUNT=4 +fi +exec "${DEVELOPER_BIN_DIR}/make" -f "${PROJECT_FILE_PATH}/%s" -j "${JOB_COUNT}" +exit 1 +""" % makefile_name + ssbp = gyp.xcodeproj_file.PBXShellScriptBuildPhase({ + 'name': 'Rule "' + rule['rule_name'] + '"', + 'shellScript': script, + 'showEnvVarsInLog': 0, + }) + + if support_xct: + support_xct.AppendProperty('buildPhases', ssbp) + else: + # TODO(mark): this assumes too much knowledge of the internals of + # xcodeproj_file; some of these smarts should move into xcodeproj_file + # itself. + xct._properties['buildPhases'].insert(prebuild_index, ssbp) + prebuild_index = prebuild_index + 1 + + # Extra rule inputs also go into the project file. Concrete outputs were + # already added when they were computed. + groups = ['inputs', 'inputs_excluded'] + if skip_excluded_files: + groups = [x for x in groups if not x.endswith('_excluded')] + for group in groups: + for item in rule.get(group, []): + pbxp.AddOrGetFileInRootGroup(item) + + # Add "sources". + for source in spec.get('sources', []): + (source_root, source_extension) = posixpath.splitext(source) + if source_extension[1:] not in rules_by_ext: + # AddSourceToTarget will add the file to a root group if it's not + # already there. + AddSourceToTarget(source, type, pbxp, xct) + else: + pbxp.AddOrGetFileInRootGroup(source) + + # Add "mac_bundle_resources" and "mac_framework_private_headers" if + # it's a bundle of any type. + if is_bundle: + for resource in tgt_mac_bundle_resources: + (resource_root, resource_extension) = posixpath.splitext(resource) + if resource_extension[1:] not in rules_by_ext: + AddResourceToTarget(resource, pbxp, xct) + else: + pbxp.AddOrGetFileInRootGroup(resource) + + for header in spec.get('mac_framework_private_headers', []): + AddHeaderToTarget(header, pbxp, xct, False) + + # Add "mac_framework_headers". These can be valid for both frameworks + # and static libraries. + if is_bundle or type == 'static_library': + for header in spec.get('mac_framework_headers', []): + AddHeaderToTarget(header, pbxp, xct, True) + + # Add "copies". + for copy_group in spec.get('copies', []): + pbxcp = gyp.xcodeproj_file.PBXCopyFilesBuildPhase({ + 'name': 'Copy to ' + copy_group['destination'] + }, + parent=xct) + dest = copy_group['destination'] + if dest[0] not in ('/', '$'): + # Relative paths are relative to $(SRCROOT). + dest = '$(SRCROOT)/' + dest + pbxcp.SetDestination(dest) + + # TODO(mark): The usual comment about this knowing too much about + # gyp.xcodeproj_file internals applies. + xct._properties['buildPhases'].insert(prebuild_index, pbxcp) + + for file in copy_group['files']: + pbxcp.AddFile(file) + + # Excluded files can also go into the project file. + if not skip_excluded_files: + for key in ['sources', 'mac_bundle_resources', 'mac_framework_headers', + 'mac_framework_private_headers']: + excluded_key = key + '_excluded' + for item in spec.get(excluded_key, []): + pbxp.AddOrGetFileInRootGroup(item) + + # So can "inputs" and "outputs" sections of "actions" groups. + groups = ['inputs', 'inputs_excluded', 'outputs', 'outputs_excluded'] + if skip_excluded_files: + groups = [x for x in groups if not x.endswith('_excluded')] + for action in spec.get('actions', []): + for group in groups: + for item in action.get(group, []): + # Exclude anything in BUILT_PRODUCTS_DIR. They're products, not + # sources. + if not item.startswith('$(BUILT_PRODUCTS_DIR)/'): + pbxp.AddOrGetFileInRootGroup(item) + + for postbuild in spec.get('postbuilds', []): + action_string_sh = gyp.common.EncodePOSIXShellList(postbuild['action']) + script = 'exec ' + action_string_sh + '\nexit 1\n' + + # Make the postbuild step depend on the output of ld or ar from this + # target. Apparently putting the script step after the link step isn't + # sufficient to ensure proper ordering in all cases. With an input + # declared but no outputs, the script step should run every time, as + # desired. + ssbp = gyp.xcodeproj_file.PBXShellScriptBuildPhase({ + 'inputPaths': ['$(BUILT_PRODUCTS_DIR)/$(EXECUTABLE_PATH)'], + 'name': 'Postbuild "' + postbuild['postbuild_name'] + '"', + 'shellScript': script, + 'showEnvVarsInLog': 0, + }) + xct.AppendProperty('buildPhases', ssbp) + + # Add dependencies before libraries, because adding a dependency may imply + # adding a library. It's preferable to keep dependencies listed first + # during a link phase so that they can override symbols that would + # otherwise be provided by libraries, which will usually include system + # libraries. On some systems, ld is finicky and even requires the + # libraries to be ordered in such a way that unresolved symbols in + # earlier-listed libraries may only be resolved by later-listed libraries. + # The Mac linker doesn't work that way, but other platforms do, and so + # their linker invocations need to be constructed in this way. There's + # no compelling reason for Xcode's linker invocations to differ. + + if 'dependencies' in spec: + for dependency in spec['dependencies']: + xct.AddDependency(xcode_targets[dependency]) + # The support project also gets the dependencies (in case they are + # needed for the actions/rules to work). + if support_xct: + support_xct.AddDependency(xcode_targets[dependency]) + + if 'libraries' in spec: + for library in spec['libraries']: + xct.FrameworksPhase().AddFile(library) + # Add the library's directory to LIBRARY_SEARCH_PATHS if necessary. + # I wish Xcode handled this automatically. + library_dir = posixpath.dirname(library) + if library_dir not in xcode_standard_library_dirs and ( + not xct.HasBuildSetting(_library_search_paths_var) or + library_dir not in xct.GetBuildSetting(_library_search_paths_var)): + xct.AppendBuildSetting(_library_search_paths_var, library_dir) + + for configuration_name in configuration_names: + configuration = spec['configurations'][configuration_name] + xcbc = xct.ConfigurationNamed(configuration_name) + for include_dir in configuration.get('mac_framework_dirs', []): + xcbc.AppendBuildSetting('FRAMEWORK_SEARCH_PATHS', include_dir) + for include_dir in configuration.get('include_dirs', []): + xcbc.AppendBuildSetting('HEADER_SEARCH_PATHS', include_dir) + if 'defines' in configuration: + for define in configuration['defines']: + set_define = EscapeXCodeArgument(define) + xcbc.AppendBuildSetting('GCC_PREPROCESSOR_DEFINITIONS', set_define) + if 'xcode_settings' in configuration: + for xck, xcv in configuration['xcode_settings'].iteritems(): + xcbc.SetBuildSetting(xck, xcv) + if 'xcode_config_file' in configuration: + config_ref = pbxp.AddOrGetFileInRootGroup( + configuration['xcode_config_file']) + xcbc.SetBaseConfiguration(config_ref) + + build_files = [] + for build_file, build_file_dict in data.iteritems(): + if build_file.endswith('.gyp'): + build_files.append(build_file) + + for build_file in build_files: + xcode_projects[build_file].Finalize1(xcode_targets, serialize_all_tests) + + for build_file in build_files: + xcode_projects[build_file].Finalize2(xcode_targets, + xcode_target_to_target_dict) + + for build_file in build_files: + xcode_projects[build_file].Write() diff --git a/node-v0.8.14/tools/gyp/pylib/gyp/input.py b/node-v0.8.14/tools/gyp/pylib/gyp/input.py new file mode 100644 index 0000000..2678bab --- /dev/null +++ b/node-v0.8.14/tools/gyp/pylib/gyp/input.py @@ -0,0 +1,2485 @@ +# Copyright (c) 2012 Google Inc. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +from compiler.ast import Const +from compiler.ast import Dict +from compiler.ast import Discard +from compiler.ast import List +from compiler.ast import Module +from compiler.ast import Node +from compiler.ast import Stmt +import compiler +import copy +import gyp.common +import optparse +import os.path +import re +import shlex +import subprocess +import sys + + +# A list of types that are treated as linkable. +linkable_types = ['executable', 'shared_library', 'loadable_module'] + +# A list of sections that contain links to other targets. +dependency_sections = ['dependencies', 'export_dependent_settings'] + +# base_path_sections is a list of sections defined by GYP that contain +# pathnames. The generators can provide more keys, the two lists are merged +# into path_sections, but you should call IsPathSection instead of using either +# list directly. +base_path_sections = [ + 'destination', + 'files', + 'include_dirs', + 'inputs', + 'libraries', + 'outputs', + 'sources', +] +path_sections = [] + + +def IsPathSection(section): + # If section ends in one of these characters, it's applied to a section + # without the trailing characters. '/' is notably absent from this list, + # because there's no way for a regular expression to be treated as a path. + while section[-1:] in ('=', '+', '?', '!'): + section = section[0:-1] + + if section in path_sections or \ + section.endswith('_dir') or section.endswith('_dirs') or \ + section.endswith('_file') or section.endswith('_files') or \ + section.endswith('_path') or section.endswith('_paths'): + return True + return False + + +# base_non_configuraiton_keys is a list of key names that belong in the target +# itself and should not be propagated into its configurations. It is merged +# with a list that can come from the generator to +# create non_configuration_keys. +base_non_configuration_keys = [ + # Sections that must exist inside targets and not configurations. + 'actions', + 'configurations', + 'copies', + 'default_configuration', + 'dependencies', + 'dependencies_original', + 'link_languages', + 'libraries', + 'postbuilds', + 'product_dir', + 'product_extension', + 'product_name', + 'product_prefix', + 'rules', + 'run_as', + 'sources', + 'suppress_wildcard', + 'target_name', + 'toolset', + 'toolsets', + 'type', + 'variants', + + # Sections that can be found inside targets or configurations, but that + # should not be propagated from targets into their configurations. + 'variables', +] +non_configuration_keys = [] + +# Keys that do not belong inside a configuration dictionary. +invalid_configuration_keys = [ + 'actions', + 'all_dependent_settings', + 'configurations', + 'dependencies', + 'direct_dependent_settings', + 'libraries', + 'link_settings', + 'sources', + 'target_name', + 'type', +] + +# Controls how the generator want the build file paths. +absolute_build_file_paths = False + +# Controls whether or not the generator supports multiple toolsets. +multiple_toolsets = False + + +def GetIncludedBuildFiles(build_file_path, aux_data, included=None): + """Return a list of all build files included into build_file_path. + + The returned list will contain build_file_path as well as all other files + that it included, either directly or indirectly. Note that the list may + contain files that were included into a conditional section that evaluated + to false and was not merged into build_file_path's dict. + + aux_data is a dict containing a key for each build file or included build + file. Those keys provide access to dicts whose "included" keys contain + lists of all other files included by the build file. + + included should be left at its default None value by external callers. It + is used for recursion. + + The returned list will not contain any duplicate entries. Each build file + in the list will be relative to the current directory. + """ + + if included == None: + included = [] + + if build_file_path in included: + return included + + included.append(build_file_path) + + for included_build_file in aux_data[build_file_path].get('included', []): + GetIncludedBuildFiles(included_build_file, aux_data, included) + + return included + + +def CheckedEval(file_contents): + """Return the eval of a gyp file. + + The gyp file is restricted to dictionaries and lists only, and + repeated keys are not allowed. + + Note that this is slower than eval() is. + """ + + ast = compiler.parse(file_contents) + assert isinstance(ast, Module) + c1 = ast.getChildren() + assert c1[0] is None + assert isinstance(c1[1], Stmt) + c2 = c1[1].getChildren() + assert isinstance(c2[0], Discard) + c3 = c2[0].getChildren() + assert len(c3) == 1 + return CheckNode(c3[0], []) + + +def CheckNode(node, keypath): + if isinstance(node, Dict): + c = node.getChildren() + dict = {} + for n in range(0, len(c), 2): + assert isinstance(c[n], Const) + key = c[n].getChildren()[0] + if key in dict: + raise KeyError, "Key '" + key + "' repeated at level " + \ + repr(len(keypath) + 1) + " with key path '" + \ + '.'.join(keypath) + "'" + kp = list(keypath) # Make a copy of the list for descending this node. + kp.append(key) + dict[key] = CheckNode(c[n + 1], kp) + return dict + elif isinstance(node, List): + c = node.getChildren() + children = [] + for index, child in enumerate(c): + kp = list(keypath) # Copy list. + kp.append(repr(index)) + children.append(CheckNode(child, kp)) + return children + elif isinstance(node, Const): + return node.getChildren()[0] + else: + raise TypeError, "Unknown AST node at key path '" + '.'.join(keypath) + \ + "': " + repr(node) + + +def LoadOneBuildFile(build_file_path, data, aux_data, variables, includes, + is_target, check): + if build_file_path in data: + return data[build_file_path] + + if os.path.exists(build_file_path): + build_file_contents = open(build_file_path).read() + else: + raise Exception("%s not found (cwd: %s)" % (build_file_path, os.getcwd())) + + build_file_data = None + try: + if check: + build_file_data = CheckedEval(build_file_contents) + else: + build_file_data = eval(build_file_contents, {'__builtins__': None}, + None) + except SyntaxError, e: + e.filename = build_file_path + raise + except Exception, e: + gyp.common.ExceptionAppend(e, 'while reading ' + build_file_path) + raise + + data[build_file_path] = build_file_data + aux_data[build_file_path] = {} + + # Scan for includes and merge them in. + try: + if is_target: + LoadBuildFileIncludesIntoDict(build_file_data, build_file_path, data, + aux_data, variables, includes, check) + else: + LoadBuildFileIncludesIntoDict(build_file_data, build_file_path, data, + aux_data, variables, None, check) + except Exception, e: + gyp.common.ExceptionAppend(e, + 'while reading includes of ' + build_file_path) + raise + + return build_file_data + + +def LoadBuildFileIncludesIntoDict(subdict, subdict_path, data, aux_data, + variables, includes, check): + includes_list = [] + if includes != None: + includes_list.extend(includes) + if 'includes' in subdict: + for include in subdict['includes']: + # "include" is specified relative to subdict_path, so compute the real + # path to include by appending the provided "include" to the directory + # in which subdict_path resides. + relative_include = \ + os.path.normpath(os.path.join(os.path.dirname(subdict_path), include)) + includes_list.append(relative_include) + # Unhook the includes list, it's no longer needed. + del subdict['includes'] + + # Merge in the included files. + for include in includes_list: + if not 'included' in aux_data[subdict_path]: + aux_data[subdict_path]['included'] = [] + aux_data[subdict_path]['included'].append(include) + + gyp.DebugOutput(gyp.DEBUG_INCLUDES, "Loading Included File: '%s'" % include) + + MergeDicts(subdict, + LoadOneBuildFile(include, data, aux_data, variables, None, + False, check), + subdict_path, include) + + # Recurse into subdictionaries. + for k, v in subdict.iteritems(): + if v.__class__ == dict: + LoadBuildFileIncludesIntoDict(v, subdict_path, data, aux_data, variables, + None, check) + elif v.__class__ == list: + LoadBuildFileIncludesIntoList(v, subdict_path, data, aux_data, variables, + check) + + +# This recurses into lists so that it can look for dicts. +def LoadBuildFileIncludesIntoList(sublist, sublist_path, data, aux_data, + variables, check): + for item in sublist: + if item.__class__ == dict: + LoadBuildFileIncludesIntoDict(item, sublist_path, data, aux_data, + variables, None, check) + elif item.__class__ == list: + LoadBuildFileIncludesIntoList(item, sublist_path, data, aux_data, + variables, check) + +# Processes toolsets in all the targets. This recurses into condition entries +# since they can contain toolsets as well. +def ProcessToolsetsInDict(data): + if 'targets' in data: + target_list = data['targets'] + new_target_list = [] + for target in target_list: + # If this target already has an explicit 'toolset', and no 'toolsets' + # list, don't modify it further. + if 'toolset' in target and 'toolsets' not in target: + new_target_list.append(target) + continue + if multiple_toolsets: + toolsets = target.get('toolsets', ['target']) + else: + toolsets = ['target'] + # Make sure this 'toolsets' definition is only processed once. + if 'toolsets' in target: + del target['toolsets'] + if len(toolsets) > 0: + # Optimization: only do copies if more than one toolset is specified. + for build in toolsets[1:]: + new_target = copy.deepcopy(target) + new_target['toolset'] = build + new_target_list.append(new_target) + target['toolset'] = toolsets[0] + new_target_list.append(target) + data['targets'] = new_target_list + if 'conditions' in data: + for condition in data['conditions']: + if isinstance(condition, list): + for condition_dict in condition[1:]: + ProcessToolsetsInDict(condition_dict) + + +# TODO(mark): I don't love this name. It just means that it's going to load +# a build file that contains targets and is expected to provide a targets dict +# that contains the targets... +def LoadTargetBuildFile(build_file_path, data, aux_data, variables, includes, + depth, check): + # If depth is set, predefine the DEPTH variable to be a relative path from + # this build file's directory to the directory identified by depth. + if depth: + # TODO(dglazkov) The backslash/forward-slash replacement at the end is a + # temporary measure. This should really be addressed by keeping all paths + # in POSIX until actual project generation. + d = gyp.common.RelativePath(depth, os.path.dirname(build_file_path)) + if d == '': + variables['DEPTH'] = '.' + else: + variables['DEPTH'] = d.replace('\\', '/') + + # If the generator needs absolue paths, then do so. + if absolute_build_file_paths: + build_file_path = os.path.abspath(build_file_path) + + if build_file_path in data['target_build_files']: + # Already loaded. + return + data['target_build_files'].add(build_file_path) + + gyp.DebugOutput(gyp.DEBUG_INCLUDES, + "Loading Target Build File '%s'" % build_file_path) + + build_file_data = LoadOneBuildFile(build_file_path, data, aux_data, variables, + includes, True, check) + + # Store DEPTH for later use in generators. + build_file_data['_DEPTH'] = depth + + # Set up the included_files key indicating which .gyp files contributed to + # this target dict. + if 'included_files' in build_file_data: + raise KeyError, build_file_path + ' must not contain included_files key' + + included = GetIncludedBuildFiles(build_file_path, aux_data) + build_file_data['included_files'] = [] + for included_file in included: + # included_file is relative to the current directory, but it needs to + # be made relative to build_file_path's directory. + included_relative = \ + gyp.common.RelativePath(included_file, + os.path.dirname(build_file_path)) + build_file_data['included_files'].append(included_relative) + + # Do a first round of toolsets expansion so that conditions can be defined + # per toolset. + ProcessToolsetsInDict(build_file_data) + + # Apply "pre"/"early" variable expansions and condition evaluations. + ProcessVariablesAndConditionsInDict( + build_file_data, PHASE_EARLY, variables, build_file_path) + + # Since some toolsets might have been defined conditionally, perform + # a second round of toolsets expansion now. + ProcessToolsetsInDict(build_file_data) + + # Look at each project's target_defaults dict, and merge settings into + # targets. + if 'target_defaults' in build_file_data: + index = 0 + if 'targets' in build_file_data: + while index < len(build_file_data['targets']): + # This procedure needs to give the impression that target_defaults is + # used as defaults, and the individual targets inherit from that. + # The individual targets need to be merged into the defaults. Make + # a deep copy of the defaults for each target, merge the target dict + # as found in the input file into that copy, and then hook up the + # copy with the target-specific data merged into it as the replacement + # target dict. + old_target_dict = build_file_data['targets'][index] + new_target_dict = copy.deepcopy(build_file_data['target_defaults']) + MergeDicts(new_target_dict, old_target_dict, + build_file_path, build_file_path) + build_file_data['targets'][index] = new_target_dict + index = index + 1 + else: + raise Exception, \ + "Unable to find targets in build file %s" % build_file_path + + # No longer needed. + del build_file_data['target_defaults'] + + # Look for dependencies. This means that dependency resolution occurs + # after "pre" conditionals and variable expansion, but before "post" - + # in other words, you can't put a "dependencies" section inside a "post" + # conditional within a target. + + if 'targets' in build_file_data: + for target_dict in build_file_data['targets']: + if 'dependencies' not in target_dict: + continue + for dependency in target_dict['dependencies']: + other_build_file = \ + gyp.common.ResolveTarget(build_file_path, dependency, None)[0] + try: + LoadTargetBuildFile(other_build_file, data, aux_data, variables, + includes, depth, check) + except Exception, e: + gyp.common.ExceptionAppend( + e, 'while loading dependencies of %s' % build_file_path) + raise + + return data + + +# Look for the bracket that matches the first bracket seen in a +# string, and return the start and end as a tuple. For example, if +# the input is something like "<(foo <(bar)) blah", then it would +# return (1, 13), indicating the entire string except for the leading +# "<" and trailing " blah". +def FindEnclosingBracketGroup(input): + brackets = { '}': '{', + ']': '[', + ')': '(', } + stack = [] + count = 0 + start = -1 + for char in input: + if char in brackets.values(): + stack.append(char) + if start == -1: + start = count + if char in brackets.keys(): + try: + last_bracket = stack.pop() + except IndexError: + return (-1, -1) + if last_bracket != brackets[char]: + return (-1, -1) + if len(stack) == 0: + return (start, count + 1) + count = count + 1 + return (-1, -1) + + +canonical_int_re = re.compile('^(0|-?[1-9][0-9]*)$') + + +def IsStrCanonicalInt(string): + """Returns True if |string| is in its canonical integer form. + + The canonical form is such that str(int(string)) == string. + """ + if not isinstance(string, str) or not canonical_int_re.match(string): + return False + + return True + + +# This matches things like "<(asdf)", "(?P<(?:(?:!?@?)|\|)?)' + '(?P[-a-zA-Z0-9_.]+)?' + '\((?P\s*\[?)' + '(?P.*?)(\]?)\))') + +# This matches the same as early_variable_re, but with '>' instead of '<'. +late_variable_re = re.compile( + '(?P(?P>(?:(?:!?@?)|\|)?)' + '(?P[-a-zA-Z0-9_.]+)?' + '\((?P\s*\[?)' + '(?P.*?)(\]?)\))') + +# This matches the same as early_variable_re, but with '^' instead of '<'. +latelate_variable_re = re.compile( + '(?P(?P[\^](?:(?:!?@?)|\|)?)' + '(?P[-a-zA-Z0-9_.]+)?' + '\((?P\s*\[?)' + '(?P.*?)(\]?)\))') + +# Global cache of results from running commands so they don't have to be run +# more then once. +cached_command_results = {} + + +def FixupPlatformCommand(cmd): + if sys.platform == 'win32': + if type(cmd) == list: + cmd = [re.sub('^cat ', 'type ', cmd[0])] + cmd[1:] + else: + cmd = re.sub('^cat ', 'type ', cmd) + return cmd + + +PHASE_EARLY = 0 +PHASE_LATE = 1 +PHASE_LATELATE = 2 + + +def ExpandVariables(input, phase, variables, build_file): + # Look for the pattern that gets expanded into variables + if phase == PHASE_EARLY: + variable_re = early_variable_re + expansion_symbol = '<' + elif phase == PHASE_LATE: + variable_re = late_variable_re + expansion_symbol = '>' + elif phase == PHASE_LATELATE: + variable_re = latelate_variable_re + expansion_symbol = '^' + else: + assert False + + input_str = str(input) + if IsStrCanonicalInt(input_str): + return int(input_str) + + # Do a quick scan to determine if an expensive regex search is warranted. + if expansion_symbol not in input_str: + return input_str + + # Get the entire list of matches as a list of MatchObject instances. + # (using findall here would return strings instead of MatchObjects). + matches = [match for match in variable_re.finditer(input_str)] + if not matches: + return input_str + + output = input_str + # Reverse the list of matches so that replacements are done right-to-left. + # That ensures that earlier replacements won't mess up the string in a + # way that causes later calls to find the earlier substituted text instead + # of what's intended for replacement. + matches.reverse() + for match_group in matches: + match = match_group.groupdict() + gyp.DebugOutput(gyp.DEBUG_VARIABLES, + "Matches: %s" % repr(match)) + # match['replace'] is the substring to look for, match['type'] + # is the character code for the replacement type (< > ! <| >| <@ + # >@ !@), match['is_array'] contains a '[' for command + # arrays, and match['content'] is the name of the variable (< >) + # or command to run (!). match['command_string'] is an optional + # command string. Currently, only 'pymod_do_main' is supported. + + # run_command is true if a ! variant is used. + run_command = '!' in match['type'] + command_string = match['command_string'] + + # file_list is true if a | variant is used. + file_list = '|' in match['type'] + + # Capture these now so we can adjust them later. + replace_start = match_group.start('replace') + replace_end = match_group.end('replace') + + # Find the ending paren, and re-evaluate the contained string. + (c_start, c_end) = FindEnclosingBracketGroup(input_str[replace_start:]) + + # Adjust the replacement range to match the entire command + # found by FindEnclosingBracketGroup (since the variable_re + # probably doesn't match the entire command if it contained + # nested variables). + replace_end = replace_start + c_end + + # Find the "real" replacement, matching the appropriate closing + # paren, and adjust the replacement start and end. + replacement = input_str[replace_start:replace_end] + + # Figure out what the contents of the variable parens are. + contents_start = replace_start + c_start + 1 + contents_end = replace_end - 1 + contents = input_str[contents_start:contents_end] + + # Do filter substitution now for <|(). + # Admittedly, this is different than the evaluation order in other + # contexts. However, since filtration has no chance to run on <|(), + # this seems like the only obvious way to give them access to filters. + if file_list: + processed_variables = copy.deepcopy(variables) + ProcessListFiltersInDict(contents, processed_variables) + # Recurse to expand variables in the contents + contents = ExpandVariables(contents, phase, + processed_variables, build_file) + else: + # Recurse to expand variables in the contents + contents = ExpandVariables(contents, phase, variables, build_file) + + # Strip off leading/trailing whitespace so that variable matches are + # simpler below (and because they are rarely needed). + contents = contents.strip() + + # expand_to_list is true if an @ variant is used. In that case, + # the expansion should result in a list. Note that the caller + # is to be expecting a list in return, and not all callers do + # because not all are working in list context. Also, for list + # expansions, there can be no other text besides the variable + # expansion in the input string. + expand_to_list = '@' in match['type'] and input_str == replacement + + if run_command or file_list: + # Find the build file's directory, so commands can be run or file lists + # generated relative to it. + build_file_dir = os.path.dirname(build_file) + if build_file_dir == '': + # If build_file is just a leaf filename indicating a file in the + # current directory, build_file_dir might be an empty string. Set + # it to None to signal to subprocess.Popen that it should run the + # command in the current directory. + build_file_dir = None + + # Support <|(listfile.txt ...) which generates a file + # containing items from a gyp list, generated at gyp time. + # This works around actions/rules which have more inputs than will + # fit on the command line. + if file_list: + if type(contents) == list: + contents_list = contents + else: + contents_list = contents.split(' ') + replacement = contents_list[0] + path = replacement + if not os.path.isabs(path): + path = os.path.join(build_file_dir, path) + f = gyp.common.WriteOnDiff(path) + for i in contents_list[1:]: + f.write('%s\n' % i) + f.close() + + elif run_command: + use_shell = True + if match['is_array']: + contents = eval(contents) + use_shell = False + + # Check for a cached value to avoid executing commands, or generating + # file lists more than once. + # TODO(http://code.google.com/p/gyp/issues/detail?id=112): It is + # possible that the command being invoked depends on the current + # directory. For that case the syntax needs to be extended so that the + # directory is also used in cache_key (it becomes a tuple). + # TODO(http://code.google.com/p/gyp/issues/detail?id=111): In theory, + # someone could author a set of GYP files where each time the command + # is invoked it produces different output by design. When the need + # arises, the syntax should be extended to support no caching off a + # command's output so it is run every time. + cache_key = str(contents) + cached_value = cached_command_results.get(cache_key, None) + if cached_value is None: + gyp.DebugOutput(gyp.DEBUG_VARIABLES, + "Executing command '%s' in directory '%s'" % + (contents,build_file_dir)) + + replacement = '' + + if command_string == 'pymod_do_main': + # (sources/) etc. to resolve to + # and empty list if undefined. This allows actions to: + # 'action!': [ + # '>@(_sources!)', + # ], + # 'action/': [ + # '>@(_sources/)', + # ], + replacement = [] + else: + raise KeyError, 'Undefined variable ' + contents + \ + ' in ' + build_file + else: + replacement = variables[contents] + + if isinstance(replacement, list): + for item in replacement: + if (not contents[-1] == '/' and + not isinstance(item, str) and not isinstance(item, int)): + raise TypeError, 'Variable ' + contents + \ + ' must expand to a string or list of strings; ' + \ + 'list contains a ' + \ + item.__class__.__name__ + # Run through the list and handle variable expansions in it. Since + # the list is guaranteed not to contain dicts, this won't do anything + # with conditions sections. + ProcessVariablesAndConditionsInList(replacement, phase, variables, + build_file) + elif not isinstance(replacement, str) and \ + not isinstance(replacement, int): + raise TypeError, 'Variable ' + contents + \ + ' must expand to a string or list of strings; ' + \ + 'found a ' + replacement.__class__.__name__ + + if expand_to_list: + # Expanding in list context. It's guaranteed that there's only one + # replacement to do in |input_str| and that it's this replacement. See + # above. + if isinstance(replacement, list): + # If it's already a list, make a copy. + output = replacement[:] + else: + # Split it the same way sh would split arguments. + output = shlex.split(str(replacement)) + else: + # Expanding in string context. + encoded_replacement = '' + if isinstance(replacement, list): + # When expanding a list into string context, turn the list items + # into a string in a way that will work with a subprocess call. + # + # TODO(mark): This isn't completely correct. This should + # call a generator-provided function that observes the + # proper list-to-argument quoting rules on a specific + # platform instead of just calling the POSIX encoding + # routine. + encoded_replacement = gyp.common.EncodePOSIXShellList(replacement) + else: + encoded_replacement = replacement + + output = output[:replace_start] + str(encoded_replacement) + \ + output[replace_end:] + # Prepare for the next match iteration. + input_str = output + + # Look for more matches now that we've replaced some, to deal with + # expanding local variables (variables defined in the same + # variables block as this one). + gyp.DebugOutput(gyp.DEBUG_VARIABLES, + "Found output %s, recursing." % repr(output)) + if isinstance(output, list): + if output and isinstance(output[0], list): + # Leave output alone if it's a list of lists. + # We don't want such lists to be stringified. + pass + else: + new_output = [] + for item in output: + new_output.append( + ExpandVariables(item, phase, variables, build_file)) + output = new_output + else: + output = ExpandVariables(output, phase, variables, build_file) + + # Convert all strings that are canonically-represented integers into integers. + if isinstance(output, list): + for index in xrange(0, len(output)): + if IsStrCanonicalInt(output[index]): + output[index] = int(output[index]) + elif IsStrCanonicalInt(output): + output = int(output) + + return output + + +def ProcessConditionsInDict(the_dict, phase, variables, build_file): + # Process a 'conditions' or 'target_conditions' section in the_dict, + # depending on phase. + # early -> conditions + # late -> target_conditions + # latelate -> no conditions + # + # Each item in a conditions list consists of cond_expr, a string expression + # evaluated as the condition, and true_dict, a dict that will be merged into + # the_dict if cond_expr evaluates to true. Optionally, a third item, + # false_dict, may be present. false_dict is merged into the_dict if + # cond_expr evaluates to false. + # + # Any dict merged into the_dict will be recursively processed for nested + # conditionals and other expansions, also according to phase, immediately + # prior to being merged. + + if phase == PHASE_EARLY: + conditions_key = 'conditions' + elif phase == PHASE_LATE: + conditions_key = 'target_conditions' + elif phase == PHASE_LATELATE: + return + else: + assert False + + if not conditions_key in the_dict: + return + + conditions_list = the_dict[conditions_key] + # Unhook the conditions list, it's no longer needed. + del the_dict[conditions_key] + + for condition in conditions_list: + if not isinstance(condition, list): + raise TypeError, conditions_key + ' must be a list' + if len(condition) != 2 and len(condition) != 3: + # It's possible that condition[0] won't work in which case this + # attempt will raise its own IndexError. That's probably fine. + raise IndexError, conditions_key + ' ' + condition[0] + \ + ' must be length 2 or 3, not ' + str(len(condition)) + + [cond_expr, true_dict] = condition[0:2] + false_dict = None + if len(condition) == 3: + false_dict = condition[2] + + # Do expansions on the condition itself. Since the conditon can naturally + # contain variable references without needing to resort to GYP expansion + # syntax, this is of dubious value for variables, but someone might want to + # use a command expansion directly inside a condition. + cond_expr_expanded = ExpandVariables(cond_expr, phase, variables, + build_file) + if not isinstance(cond_expr_expanded, str) and \ + not isinstance(cond_expr_expanded, int): + raise ValueError, \ + 'Variable expansion in this context permits str and int ' + \ + 'only, found ' + expanded.__class__.__name__ + + try: + ast_code = compile(cond_expr_expanded, '', 'eval') + + if eval(ast_code, {'__builtins__': None}, variables): + merge_dict = true_dict + else: + merge_dict = false_dict + except SyntaxError, e: + syntax_error = SyntaxError('%s while evaluating condition \'%s\' in %s ' + 'at character %d.' % + (str(e.args[0]), e.text, build_file, e.offset), + e.filename, e.lineno, e.offset, e.text) + raise syntax_error + except NameError, e: + gyp.common.ExceptionAppend(e, 'while evaluating condition \'%s\' in %s' % + (cond_expr_expanded, build_file)) + raise + + if merge_dict != None: + # Expand variables and nested conditinals in the merge_dict before + # merging it. + ProcessVariablesAndConditionsInDict(merge_dict, phase, + variables, build_file) + + MergeDicts(the_dict, merge_dict, build_file, build_file) + + +def LoadAutomaticVariablesFromDict(variables, the_dict): + # Any keys with plain string values in the_dict become automatic variables. + # The variable name is the key name with a "_" character prepended. + for key, value in the_dict.iteritems(): + if isinstance(value, str) or isinstance(value, int) or \ + isinstance(value, list): + variables['_' + key] = value + + +def LoadVariablesFromVariablesDict(variables, the_dict, the_dict_key): + # Any keys in the_dict's "variables" dict, if it has one, becomes a + # variable. The variable name is the key name in the "variables" dict. + # Variables that end with the % character are set only if they are unset in + # the variables dict. the_dict_key is the name of the key that accesses + # the_dict in the_dict's parent dict. If the_dict's parent is not a dict + # (it could be a list or it could be parentless because it is a root dict), + # the_dict_key will be None. + for key, value in the_dict.get('variables', {}).iteritems(): + if not isinstance(value, str) and not isinstance(value, int) and \ + not isinstance(value, list): + continue + + if key.endswith('%'): + variable_name = key[:-1] + if variable_name in variables: + # If the variable is already set, don't set it. + continue + if the_dict_key is 'variables' and variable_name in the_dict: + # If the variable is set without a % in the_dict, and the_dict is a + # variables dict (making |variables| a varaibles sub-dict of a + # variables dict), use the_dict's definition. + value = the_dict[variable_name] + else: + variable_name = key + + variables[variable_name] = value + + +def ProcessVariablesAndConditionsInDict(the_dict, phase, variables_in, + build_file, the_dict_key=None): + """Handle all variable and command expansion and conditional evaluation. + + This function is the public entry point for all variable expansions and + conditional evaluations. The variables_in dictionary will not be modified + by this function. + """ + + # Make a copy of the variables_in dict that can be modified during the + # loading of automatics and the loading of the variables dict. + variables = variables_in.copy() + LoadAutomaticVariablesFromDict(variables, the_dict) + + if 'variables' in the_dict: + # Make sure all the local variables are added to the variables + # list before we process them so that you can reference one + # variable from another. They will be fully expanded by recursion + # in ExpandVariables. + for key, value in the_dict['variables'].iteritems(): + variables[key] = value + + # Handle the associated variables dict first, so that any variable + # references within can be resolved prior to using them as variables. + # Pass a copy of the variables dict to avoid having it be tainted. + # Otherwise, it would have extra automatics added for everything that + # should just be an ordinary variable in this scope. + ProcessVariablesAndConditionsInDict(the_dict['variables'], phase, + variables, build_file, 'variables') + + LoadVariablesFromVariablesDict(variables, the_dict, the_dict_key) + + for key, value in the_dict.iteritems(): + # Skip "variables", which was already processed if present. + if key != 'variables' and isinstance(value, str): + expanded = ExpandVariables(value, phase, variables, build_file) + if not isinstance(expanded, str) and not isinstance(expanded, int): + raise ValueError, \ + 'Variable expansion in this context permits str and int ' + \ + 'only, found ' + expanded.__class__.__name__ + ' for ' + key + the_dict[key] = expanded + + # Variable expansion may have resulted in changes to automatics. Reload. + # TODO(mark): Optimization: only reload if no changes were made. + variables = variables_in.copy() + LoadAutomaticVariablesFromDict(variables, the_dict) + LoadVariablesFromVariablesDict(variables, the_dict, the_dict_key) + + # Process conditions in this dict. This is done after variable expansion + # so that conditions may take advantage of expanded variables. For example, + # if the_dict contains: + # {'type': '<(library_type)', + # 'conditions': [['_type=="static_library"', { ... }]]}, + # _type, as used in the condition, will only be set to the value of + # library_type if variable expansion is performed before condition + # processing. However, condition processing should occur prior to recursion + # so that variables (both automatic and "variables" dict type) may be + # adjusted by conditions sections, merged into the_dict, and have the + # intended impact on contained dicts. + # + # This arrangement means that a "conditions" section containing a "variables" + # section will only have those variables effective in subdicts, not in + # the_dict. The workaround is to put a "conditions" section within a + # "variables" section. For example: + # {'conditions': [['os=="mac"', {'variables': {'define': 'IS_MAC'}}]], + # 'defines': ['<(define)'], + # 'my_subdict': {'defines': ['<(define)']}}, + # will not result in "IS_MAC" being appended to the "defines" list in the + # current scope but would result in it being appended to the "defines" list + # within "my_subdict". By comparison: + # {'variables': {'conditions': [['os=="mac"', {'define': 'IS_MAC'}]]}, + # 'defines': ['<(define)'], + # 'my_subdict': {'defines': ['<(define)']}}, + # will append "IS_MAC" to both "defines" lists. + + # Evaluate conditions sections, allowing variable expansions within them + # as well as nested conditionals. This will process a 'conditions' or + # 'target_conditions' section, perform appropriate merging and recursive + # conditional and variable processing, and then remove the conditions section + # from the_dict if it is present. + ProcessConditionsInDict(the_dict, phase, variables, build_file) + + # Conditional processing may have resulted in changes to automatics or the + # variables dict. Reload. + variables = variables_in.copy() + LoadAutomaticVariablesFromDict(variables, the_dict) + LoadVariablesFromVariablesDict(variables, the_dict, the_dict_key) + + # Recurse into child dicts, or process child lists which may result in + # further recursion into descendant dicts. + for key, value in the_dict.iteritems(): + # Skip "variables" and string values, which were already processed if + # present. + if key == 'variables' or isinstance(value, str): + continue + if isinstance(value, dict): + # Pass a copy of the variables dict so that subdicts can't influence + # parents. + ProcessVariablesAndConditionsInDict(value, phase, variables, + build_file, key) + elif isinstance(value, list): + # The list itself can't influence the variables dict, and + # ProcessVariablesAndConditionsInList will make copies of the variables + # dict if it needs to pass it to something that can influence it. No + # copy is necessary here. + ProcessVariablesAndConditionsInList(value, phase, variables, + build_file) + elif not isinstance(value, int): + raise TypeError, 'Unknown type ' + value.__class__.__name__ + \ + ' for ' + key + + +def ProcessVariablesAndConditionsInList(the_list, phase, variables, + build_file): + # Iterate using an index so that new values can be assigned into the_list. + index = 0 + while index < len(the_list): + item = the_list[index] + if isinstance(item, dict): + # Make a copy of the variables dict so that it won't influence anything + # outside of its own scope. + ProcessVariablesAndConditionsInDict(item, phase, variables, build_file) + elif isinstance(item, list): + ProcessVariablesAndConditionsInList(item, phase, variables, build_file) + elif isinstance(item, str): + expanded = ExpandVariables(item, phase, variables, build_file) + if isinstance(expanded, str) or isinstance(expanded, int): + the_list[index] = expanded + elif isinstance(expanded, list): + the_list[index:index+1] = expanded + index += len(expanded) + + # index now identifies the next item to examine. Continue right now + # without falling into the index increment below. + continue + else: + raise ValueError, \ + 'Variable expansion in this context permits strings and ' + \ + 'lists only, found ' + expanded.__class__.__name__ + ' at ' + \ + index + elif not isinstance(item, int): + raise TypeError, 'Unknown type ' + item.__class__.__name__ + \ + ' at index ' + index + index = index + 1 + + +def BuildTargetsDict(data): + """Builds a dict mapping fully-qualified target names to their target dicts. + + |data| is a dict mapping loaded build files by pathname relative to the + current directory. Values in |data| are build file contents. For each + |data| value with a "targets" key, the value of the "targets" key is taken + as a list containing target dicts. Each target's fully-qualified name is + constructed from the pathname of the build file (|data| key) and its + "target_name" property. These fully-qualified names are used as the keys + in the returned dict. These keys provide access to the target dicts, + the dicts in the "targets" lists. + """ + + targets = {} + for build_file in data['target_build_files']: + for target in data[build_file].get('targets', []): + target_name = gyp.common.QualifiedTarget(build_file, + target['target_name'], + target['toolset']) + if target_name in targets: + raise KeyError, 'Duplicate target definitions for ' + target_name + targets[target_name] = target + + return targets + + +def QualifyDependencies(targets): + """Make dependency links fully-qualified relative to the current directory. + + |targets| is a dict mapping fully-qualified target names to their target + dicts. For each target in this dict, keys known to contain dependency + links are examined, and any dependencies referenced will be rewritten + so that they are fully-qualified and relative to the current directory. + All rewritten dependencies are suitable for use as keys to |targets| or a + similar dict. + """ + + all_dependency_sections = [dep + op + for dep in dependency_sections + for op in ('', '!', '/')] + + for target, target_dict in targets.iteritems(): + target_build_file = gyp.common.BuildFile(target) + toolset = target_dict['toolset'] + for dependency_key in all_dependency_sections: + dependencies = target_dict.get(dependency_key, []) + for index in xrange(0, len(dependencies)): + dep_file, dep_target, dep_toolset = gyp.common.ResolveTarget( + target_build_file, dependencies[index], toolset) + if not multiple_toolsets: + # Ignore toolset specification in the dependency if it is specified. + dep_toolset = toolset + dependency = gyp.common.QualifiedTarget(dep_file, + dep_target, + dep_toolset) + dependencies[index] = dependency + + # Make sure anything appearing in a list other than "dependencies" also + # appears in the "dependencies" list. + if dependency_key != 'dependencies' and \ + dependency not in target_dict['dependencies']: + raise KeyError, 'Found ' + dependency + ' in ' + dependency_key + \ + ' of ' + target + ', but not in dependencies' + + +def ExpandWildcardDependencies(targets, data): + """Expands dependencies specified as build_file:*. + + For each target in |targets|, examines sections containing links to other + targets. If any such section contains a link of the form build_file:*, it + is taken as a wildcard link, and is expanded to list each target in + build_file. The |data| dict provides access to build file dicts. + + Any target that does not wish to be included by wildcard can provide an + optional "suppress_wildcard" key in its target dict. When present and + true, a wildcard dependency link will not include such targets. + + All dependency names, including the keys to |targets| and the values in each + dependency list, must be qualified when this function is called. + """ + + for target, target_dict in targets.iteritems(): + toolset = target_dict['toolset'] + target_build_file = gyp.common.BuildFile(target) + for dependency_key in dependency_sections: + dependencies = target_dict.get(dependency_key, []) + + # Loop this way instead of "for dependency in" or "for index in xrange" + # because the dependencies list will be modified within the loop body. + index = 0 + while index < len(dependencies): + (dependency_build_file, dependency_target, dependency_toolset) = \ + gyp.common.ParseQualifiedTarget(dependencies[index]) + if dependency_target != '*' and dependency_toolset != '*': + # Not a wildcard. Keep it moving. + index = index + 1 + continue + + if dependency_build_file == target_build_file: + # It's an error for a target to depend on all other targets in + # the same file, because a target cannot depend on itself. + raise KeyError, 'Found wildcard in ' + dependency_key + ' of ' + \ + target + ' referring to same build file' + + # Take the wildcard out and adjust the index so that the next + # dependency in the list will be processed the next time through the + # loop. + del dependencies[index] + index = index - 1 + + # Loop through the targets in the other build file, adding them to + # this target's list of dependencies in place of the removed + # wildcard. + dependency_target_dicts = data[dependency_build_file]['targets'] + for dependency_target_dict in dependency_target_dicts: + if int(dependency_target_dict.get('suppress_wildcard', False)): + continue + dependency_target_name = dependency_target_dict['target_name'] + if (dependency_target != '*' and + dependency_target != dependency_target_name): + continue + dependency_target_toolset = dependency_target_dict['toolset'] + if (dependency_toolset != '*' and + dependency_toolset != dependency_target_toolset): + continue + dependency = gyp.common.QualifiedTarget(dependency_build_file, + dependency_target_name, + dependency_target_toolset) + index = index + 1 + dependencies.insert(index, dependency) + + index = index + 1 + + +def Unify(l): + """Removes duplicate elements from l, keeping the first element.""" + seen = {} + return [seen.setdefault(e, e) for e in l if e not in seen] + + +def RemoveDuplicateDependencies(targets): + """Makes sure every dependency appears only once in all targets's dependency + lists.""" + for target_name, target_dict in targets.iteritems(): + for dependency_key in dependency_sections: + dependencies = target_dict.get(dependency_key, []) + if dependencies: + target_dict[dependency_key] = Unify(dependencies) + + +class DependencyGraphNode(object): + """ + + Attributes: + ref: A reference to an object that this DependencyGraphNode represents. + dependencies: List of DependencyGraphNodes on which this one depends. + dependents: List of DependencyGraphNodes that depend on this one. + """ + + class CircularException(Exception): + pass + + def __init__(self, ref): + self.ref = ref + self.dependencies = [] + self.dependents = [] + + def FlattenToList(self): + # flat_list is the sorted list of dependencies - actually, the list items + # are the "ref" attributes of DependencyGraphNodes. Every target will + # appear in flat_list after all of its dependencies, and before all of its + # dependents. + flat_list = [] + + # in_degree_zeros is the list of DependencyGraphNodes that have no + # dependencies not in flat_list. Initially, it is a copy of the children + # of this node, because when the graph was built, nodes with no + # dependencies were made implicit dependents of the root node. + in_degree_zeros = set(self.dependents[:]) + + while in_degree_zeros: + # Nodes in in_degree_zeros have no dependencies not in flat_list, so they + # can be appended to flat_list. Take these nodes out of in_degree_zeros + # as work progresses, so that the next node to process from the list can + # always be accessed at a consistent position. + node = in_degree_zeros.pop() + flat_list.append(node.ref) + + # Look at dependents of the node just added to flat_list. Some of them + # may now belong in in_degree_zeros. + for node_dependent in node.dependents: + is_in_degree_zero = True + for node_dependent_dependency in node_dependent.dependencies: + if not node_dependent_dependency.ref in flat_list: + # The dependent one or more dependencies not in flat_list. There + # will be more chances to add it to flat_list when examining + # it again as a dependent of those other dependencies, provided + # that there are no cycles. + is_in_degree_zero = False + break + + if is_in_degree_zero: + # All of the dependent's dependencies are already in flat_list. Add + # it to in_degree_zeros where it will be processed in a future + # iteration of the outer loop. + in_degree_zeros.add(node_dependent) + + return flat_list + + def DirectDependencies(self, dependencies=None): + """Returns a list of just direct dependencies.""" + if dependencies == None: + dependencies = [] + + for dependency in self.dependencies: + # Check for None, corresponding to the root node. + if dependency.ref != None and dependency.ref not in dependencies: + dependencies.append(dependency.ref) + + return dependencies + + def _AddImportedDependencies(self, targets, dependencies=None): + """Given a list of direct dependencies, adds indirect dependencies that + other dependencies have declared to export their settings. + + This method does not operate on self. Rather, it operates on the list + of dependencies in the |dependencies| argument. For each dependency in + that list, if any declares that it exports the settings of one of its + own dependencies, those dependencies whose settings are "passed through" + are added to the list. As new items are added to the list, they too will + be processed, so it is possible to import settings through multiple levels + of dependencies. + + This method is not terribly useful on its own, it depends on being + "primed" with a list of direct dependencies such as one provided by + DirectDependencies. DirectAndImportedDependencies is intended to be the + public entry point. + """ + + if dependencies == None: + dependencies = [] + + index = 0 + while index < len(dependencies): + dependency = dependencies[index] + dependency_dict = targets[dependency] + # Add any dependencies whose settings should be imported to the list + # if not already present. Newly-added items will be checked for + # their own imports when the list iteration reaches them. + # Rather than simply appending new items, insert them after the + # dependency that exported them. This is done to more closely match + # the depth-first method used by DeepDependencies. + add_index = 1 + for imported_dependency in \ + dependency_dict.get('export_dependent_settings', []): + if imported_dependency not in dependencies: + dependencies.insert(index + add_index, imported_dependency) + add_index = add_index + 1 + index = index + 1 + + return dependencies + + def DirectAndImportedDependencies(self, targets, dependencies=None): + """Returns a list of a target's direct dependencies and all indirect + dependencies that a dependency has advertised settings should be exported + through the dependency for. + """ + + dependencies = self.DirectDependencies(dependencies) + return self._AddImportedDependencies(targets, dependencies) + + def DeepDependencies(self, dependencies=None): + """Returns a list of all of a target's dependencies, recursively.""" + if dependencies == None: + dependencies = [] + + for dependency in self.dependencies: + # Check for None, corresponding to the root node. + if dependency.ref != None and dependency.ref not in dependencies: + dependencies.append(dependency.ref) + dependency.DeepDependencies(dependencies) + + return dependencies + + def LinkDependencies(self, targets, dependencies=None, initial=True): + """Returns a list of dependency targets that are linked into this target. + + This function has a split personality, depending on the setting of + |initial|. Outside callers should always leave |initial| at its default + setting. + + When adding a target to the list of dependencies, this function will + recurse into itself with |initial| set to False, to collect dependencies + that are linked into the linkable target for which the list is being built. + """ + if dependencies == None: + dependencies = [] + + # Check for None, corresponding to the root node. + if self.ref == None: + return dependencies + + # It's kind of sucky that |targets| has to be passed into this function, + # but that's presently the easiest way to access the target dicts so that + # this function can find target types. + + if not 'target_name' in targets[self.ref]: + raise Exception("Missing 'target_name' field in target.") + + try: + target_type = targets[self.ref]['type'] + except KeyError, e: + raise Exception("Missing 'type' field in target %s" % + targets[self.ref]['target_name']) + + is_linkable = target_type in linkable_types + + if initial and not is_linkable: + # If this is the first target being examined and it's not linkable, + # return an empty list of link dependencies, because the link + # dependencies are intended to apply to the target itself (initial is + # True) and this target won't be linked. + return dependencies + + # Don't traverse 'none' targets if explicitly excluded. + if (target_type == 'none' and + not targets[self.ref].get('dependencies_traverse', True)): + if self.ref not in dependencies: + dependencies.append(self.ref) + return dependencies + + # Executables and loadable modules are already fully and finally linked. + # Nothing else can be a link dependency of them, there can only be + # dependencies in the sense that a dependent target might run an + # executable or load the loadable_module. + if not initial and target_type in ('executable', 'loadable_module'): + return dependencies + + # The target is linkable, add it to the list of link dependencies. + if self.ref not in dependencies: + dependencies.append(self.ref) + if initial or not is_linkable: + # If this is a subsequent target and it's linkable, don't look any + # further for linkable dependencies, as they'll already be linked into + # this target linkable. Always look at dependencies of the initial + # target, and always look at dependencies of non-linkables. + for dependency in self.dependencies: + dependency.LinkDependencies(targets, dependencies, False) + + return dependencies + + +def BuildDependencyList(targets): + # Create a DependencyGraphNode for each target. Put it into a dict for easy + # access. + dependency_nodes = {} + for target, spec in targets.iteritems(): + if not target in dependency_nodes: + dependency_nodes[target] = DependencyGraphNode(target) + + # Set up the dependency links. Targets that have no dependencies are treated + # as dependent on root_node. + root_node = DependencyGraphNode(None) + for target, spec in targets.iteritems(): + target_node = dependency_nodes[target] + target_build_file = gyp.common.BuildFile(target) + if not 'dependencies' in spec or len(spec['dependencies']) == 0: + target_node.dependencies = [root_node] + root_node.dependents.append(target_node) + else: + dependencies = spec['dependencies'] + for index in xrange(0, len(dependencies)): + try: + dependency = dependencies[index] + dependency_node = dependency_nodes[dependency] + target_node.dependencies.append(dependency_node) + dependency_node.dependents.append(target_node) + except KeyError, e: + gyp.common.ExceptionAppend(e, + 'while trying to load target %s' % target) + raise + + flat_list = root_node.FlattenToList() + + # If there's anything left unvisited, there must be a circular dependency + # (cycle). If you need to figure out what's wrong, look for elements of + # targets that are not in flat_list. + if len(flat_list) != len(targets): + raise DependencyGraphNode.CircularException, \ + 'Some targets not reachable, cycle in dependency graph detected: ' + \ + ' '.join(set(flat_list) ^ set(targets)) + + return [dependency_nodes, flat_list] + + +def VerifyNoGYPFileCircularDependencies(targets): + # Create a DependencyGraphNode for each gyp file containing a target. Put + # it into a dict for easy access. + dependency_nodes = {} + for target in targets.iterkeys(): + build_file = gyp.common.BuildFile(target) + if not build_file in dependency_nodes: + dependency_nodes[build_file] = DependencyGraphNode(build_file) + + # Set up the dependency links. + for target, spec in targets.iteritems(): + build_file = gyp.common.BuildFile(target) + build_file_node = dependency_nodes[build_file] + target_dependencies = spec.get('dependencies', []) + for dependency in target_dependencies: + try: + dependency_build_file = gyp.common.BuildFile(dependency) + if dependency_build_file == build_file: + # A .gyp file is allowed to refer back to itself. + continue + dependency_node = dependency_nodes[dependency_build_file] + if dependency_node not in build_file_node.dependencies: + build_file_node.dependencies.append(dependency_node) + dependency_node.dependents.append(build_file_node) + except KeyError, e: + gyp.common.ExceptionAppend( + e, 'while computing dependencies of .gyp file %s' % build_file) + raise + + # Files that have no dependencies are treated as dependent on root_node. + root_node = DependencyGraphNode(None) + for build_file_node in dependency_nodes.itervalues(): + if len(build_file_node.dependencies) == 0: + build_file_node.dependencies.append(root_node) + root_node.dependents.append(build_file_node) + + flat_list = root_node.FlattenToList() + + # If there's anything left unvisited, there must be a circular dependency + # (cycle). + if len(flat_list) != len(dependency_nodes): + bad_files = [] + for file in dependency_nodes.iterkeys(): + if not file in flat_list: + bad_files.append(file) + raise DependencyGraphNode.CircularException, \ + 'Some files not reachable, cycle in .gyp file dependency graph ' + \ + 'detected involving some or all of: ' + \ + ' '.join(bad_files) + + +def DoDependentSettings(key, flat_list, targets, dependency_nodes): + # key should be one of all_dependent_settings, direct_dependent_settings, + # or link_settings. + + for target in flat_list: + target_dict = targets[target] + build_file = gyp.common.BuildFile(target) + + if key == 'all_dependent_settings': + dependencies = dependency_nodes[target].DeepDependencies() + elif key == 'direct_dependent_settings': + dependencies = \ + dependency_nodes[target].DirectAndImportedDependencies(targets) + elif key == 'link_settings': + dependencies = dependency_nodes[target].LinkDependencies(targets) + else: + raise KeyError, "DoDependentSettings doesn't know how to determine " + \ + 'dependencies for ' + key + + for dependency in dependencies: + dependency_dict = targets[dependency] + if not key in dependency_dict: + continue + dependency_build_file = gyp.common.BuildFile(dependency) + MergeDicts(target_dict, dependency_dict[key], + build_file, dependency_build_file) + + +def AdjustStaticLibraryDependencies(flat_list, targets, dependency_nodes, + sort_dependencies): + # Recompute target "dependencies" properties. For each static library + # target, remove "dependencies" entries referring to other static libraries, + # unless the dependency has the "hard_dependency" attribute set. For each + # linkable target, add a "dependencies" entry referring to all of the + # target's computed list of link dependencies (including static libraries + # if no such entry is already present. + for target in flat_list: + target_dict = targets[target] + target_type = target_dict['type'] + + if target_type == 'static_library': + if not 'dependencies' in target_dict: + continue + + target_dict['dependencies_original'] = target_dict.get( + 'dependencies', [])[:] + + # A static library should not depend on another static library unless + # the dependency relationship is "hard," which should only be done when + # a dependent relies on some side effect other than just the build + # product, like a rule or action output. Further, if a target has a + # non-hard dependency, but that dependency exports a hard dependency, + # the non-hard dependency can safely be removed, but the exported hard + # dependency must be added to the target to keep the same dependency + # ordering. + dependencies = \ + dependency_nodes[target].DirectAndImportedDependencies(targets) + index = 0 + while index < len(dependencies): + dependency = dependencies[index] + dependency_dict = targets[dependency] + + # Remove every non-hard static library dependency and remove every + # non-static library dependency that isn't a direct dependency. + if (dependency_dict['type'] == 'static_library' and \ + not dependency_dict.get('hard_dependency', False)) or \ + (dependency_dict['type'] != 'static_library' and \ + not dependency in target_dict['dependencies']): + # Take the dependency out of the list, and don't increment index + # because the next dependency to analyze will shift into the index + # formerly occupied by the one being removed. + del dependencies[index] + else: + index = index + 1 + + # Update the dependencies. If the dependencies list is empty, it's not + # needed, so unhook it. + if len(dependencies) > 0: + target_dict['dependencies'] = dependencies + else: + del target_dict['dependencies'] + + elif target_type in linkable_types: + # Get a list of dependency targets that should be linked into this + # target. Add them to the dependencies list if they're not already + # present. + + link_dependencies = dependency_nodes[target].LinkDependencies(targets) + for dependency in link_dependencies: + if dependency == target: + continue + if not 'dependencies' in target_dict: + target_dict['dependencies'] = [] + if not dependency in target_dict['dependencies']: + target_dict['dependencies'].append(dependency) + # Sort the dependencies list in the order from dependents to dependencies. + # e.g. If A and B depend on C and C depends on D, sort them in A, B, C, D. + # Note: flat_list is already sorted in the order from dependencies to + # dependents. + if sort_dependencies and 'dependencies' in target_dict: + target_dict['dependencies'] = [dep for dep in reversed(flat_list) + if dep in target_dict['dependencies']] + + +# Initialize this here to speed up MakePathRelative. +exception_re = re.compile(r'''["']?[-/$<>^]''') + + +def MakePathRelative(to_file, fro_file, item): + # If item is a relative path, it's relative to the build file dict that it's + # coming from. Fix it up to make it relative to the build file dict that + # it's going into. + # Exception: any |item| that begins with these special characters is + # returned without modification. + # / Used when a path is already absolute (shortcut optimization; + # such paths would be returned as absolute anyway) + # $ Used for build environment variables + # - Used for some build environment flags (such as -lapr-1 in a + # "libraries" section) + # < Used for our own variable and command expansions (see ExpandVariables) + # > Used for our own variable and command expansions (see ExpandVariables) + # ^ Used for our own variable and command expansions (see ExpandVariables) + # + # "/' Used when a value is quoted. If these are present, then we + # check the second character instead. + # + if to_file == fro_file or exception_re.match(item): + return item + else: + # TODO(dglazkov) The backslash/forward-slash replacement at the end is a + # temporary measure. This should really be addressed by keeping all paths + # in POSIX until actual project generation. + ret = os.path.normpath(os.path.join( + gyp.common.RelativePath(os.path.dirname(fro_file), + os.path.dirname(to_file)), + item)).replace('\\', '/') + if item[-1] == '/': + ret += '/' + return ret + +def MergeLists(to, fro, to_file, fro_file, is_paths=False, append=True): + def is_hashable(x): + try: + hash(x) + except TypeError: + return False + return True + # If x is hashable, returns whether x is in s. Else returns whether x is in l. + def is_in_set_or_list(x, s, l): + if is_hashable(x): + return x in s + return x in l + + prepend_index = 0 + + # Make membership testing of hashables in |to| (in particular, strings) + # faster. + hashable_to_set = set([x for x in to if is_hashable(x)]) + + for item in fro: + singleton = False + if isinstance(item, str) or isinstance(item, int): + # The cheap and easy case. + if is_paths: + to_item = MakePathRelative(to_file, fro_file, item) + else: + to_item = item + + if not isinstance(item, str) or not item.startswith('-'): + # Any string that doesn't begin with a "-" is a singleton - it can + # only appear once in a list, to be enforced by the list merge append + # or prepend. + singleton = True + elif isinstance(item, dict): + # Make a copy of the dictionary, continuing to look for paths to fix. + # The other intelligent aspects of merge processing won't apply because + # item is being merged into an empty dict. + to_item = {} + MergeDicts(to_item, item, to_file, fro_file) + elif isinstance(item, list): + # Recurse, making a copy of the list. If the list contains any + # descendant dicts, path fixing will occur. Note that here, custom + # values for is_paths and append are dropped; those are only to be + # applied to |to| and |fro|, not sublists of |fro|. append shouldn't + # matter anyway because the new |to_item| list is empty. + to_item = [] + MergeLists(to_item, item, to_file, fro_file) + else: + raise TypeError, \ + 'Attempt to merge list item of unsupported type ' + \ + item.__class__.__name__ + + if append: + # If appending a singleton that's already in the list, don't append. + # This ensures that the earliest occurrence of the item will stay put. + if not singleton or not is_in_set_or_list(to_item, hashable_to_set, to): + to.append(to_item) + if is_hashable(to_item): + hashable_to_set.add(to_item) + else: + # If prepending a singleton that's already in the list, remove the + # existing instance and proceed with the prepend. This ensures that the + # item appears at the earliest possible position in the list. + while singleton and to_item in to: + to.remove(to_item) + + # Don't just insert everything at index 0. That would prepend the new + # items to the list in reverse order, which would be an unwelcome + # surprise. + to.insert(prepend_index, to_item) + if is_hashable(to_item): + hashable_to_set.add(to_item) + prepend_index = prepend_index + 1 + + +def MergeDicts(to, fro, to_file, fro_file): + # I wanted to name the parameter "from" but it's a Python keyword... + for k, v in fro.iteritems(): + # It would be nice to do "if not k in to: to[k] = v" but that wouldn't give + # copy semantics. Something else may want to merge from the |fro| dict + # later, and having the same dict ref pointed to twice in the tree isn't + # what anyone wants considering that the dicts may subsequently be + # modified. + if k in to: + bad_merge = False + if isinstance(v, str) or isinstance(v, int): + if not (isinstance(to[k], str) or isinstance(to[k], int)): + bad_merge = True + elif v.__class__ != to[k].__class__: + bad_merge = True + + if bad_merge: + raise TypeError, \ + 'Attempt to merge dict value of type ' + v.__class__.__name__ + \ + ' into incompatible type ' + to[k].__class__.__name__ + \ + ' for key ' + k + if isinstance(v, str) or isinstance(v, int): + # Overwrite the existing value, if any. Cheap and easy. + is_path = IsPathSection(k) + if is_path: + to[k] = MakePathRelative(to_file, fro_file, v) + else: + to[k] = v + elif isinstance(v, dict): + # Recurse, guaranteeing copies will be made of objects that require it. + if not k in to: + to[k] = {} + MergeDicts(to[k], v, to_file, fro_file) + elif isinstance(v, list): + # Lists in dicts can be merged with different policies, depending on + # how the key in the "from" dict (k, the from-key) is written. + # + # If the from-key has ...the to-list will have this action + # this character appended:... applied when receiving the from-list: + # = replace + # + prepend + # ? set, only if to-list does not yet exist + # (none) append + # + # This logic is list-specific, but since it relies on the associated + # dict key, it's checked in this dict-oriented function. + ext = k[-1] + append = True + if ext == '=': + list_base = k[:-1] + lists_incompatible = [list_base, list_base + '?'] + to[list_base] = [] + elif ext == '+': + list_base = k[:-1] + lists_incompatible = [list_base + '=', list_base + '?'] + append = False + elif ext == '?': + list_base = k[:-1] + lists_incompatible = [list_base, list_base + '=', list_base + '+'] + else: + list_base = k + lists_incompatible = [list_base + '=', list_base + '?'] + + # Some combinations of merge policies appearing together are meaningless. + # It's stupid to replace and append simultaneously, for example. Append + # and prepend are the only policies that can coexist. + for list_incompatible in lists_incompatible: + if list_incompatible in fro: + raise KeyError, 'Incompatible list policies ' + k + ' and ' + \ + list_incompatible + + if list_base in to: + if ext == '?': + # If the key ends in "?", the list will only be merged if it doesn't + # already exist. + continue + if not isinstance(to[list_base], list): + # This may not have been checked above if merging in a list with an + # extension character. + raise TypeError, \ + 'Attempt to merge dict value of type ' + v.__class__.__name__ + \ + ' into incompatible type ' + to[list_base].__class__.__name__ + \ + ' for key ' + list_base + '(' + k + ')' + else: + to[list_base] = [] + + # Call MergeLists, which will make copies of objects that require it. + # MergeLists can recurse back into MergeDicts, although this will be + # to make copies of dicts (with paths fixed), there will be no + # subsequent dict "merging" once entering a list because lists are + # always replaced, appended to, or prepended to. + is_paths = IsPathSection(list_base) + MergeLists(to[list_base], v, to_file, fro_file, is_paths, append) + else: + raise TypeError, \ + 'Attempt to merge dict value of unsupported type ' + \ + v.__class__.__name__ + ' for key ' + k + + +def MergeConfigWithInheritance(new_configuration_dict, build_file, + target_dict, configuration, visited): + # Skip if previously visted. + if configuration in visited: + return + + # Look at this configuration. + configuration_dict = target_dict['configurations'][configuration] + + # Merge in parents. + for parent in configuration_dict.get('inherit_from', []): + MergeConfigWithInheritance(new_configuration_dict, build_file, + target_dict, parent, visited + [configuration]) + + # Merge it into the new config. + MergeDicts(new_configuration_dict, configuration_dict, + build_file, build_file) + + # Drop abstract. + if 'abstract' in new_configuration_dict: + del new_configuration_dict['abstract'] + + +def SetUpConfigurations(target, target_dict): + # key_suffixes is a list of key suffixes that might appear on key names. + # These suffixes are handled in conditional evaluations (for =, +, and ?) + # and rules/exclude processing (for ! and /). Keys with these suffixes + # should be treated the same as keys without. + key_suffixes = ['=', '+', '?', '!', '/'] + + build_file = gyp.common.BuildFile(target) + + # Provide a single configuration by default if none exists. + # TODO(mark): Signal an error if default_configurations exists but + # configurations does not. + if not 'configurations' in target_dict: + target_dict['configurations'] = {'Default': {}} + if not 'default_configuration' in target_dict: + concrete = [i for i in target_dict['configurations'].keys() + if not target_dict['configurations'][i].get('abstract')] + target_dict['default_configuration'] = sorted(concrete)[0] + + for configuration in target_dict['configurations'].keys(): + old_configuration_dict = target_dict['configurations'][configuration] + # Skip abstract configurations (saves work only). + if old_configuration_dict.get('abstract'): + continue + # Configurations inherit (most) settings from the enclosing target scope. + # Get the inheritance relationship right by making a copy of the target + # dict. + new_configuration_dict = copy.deepcopy(target_dict) + + # Take out the bits that don't belong in a "configurations" section. + # Since configuration setup is done before conditional, exclude, and rules + # processing, be careful with handling of the suffix characters used in + # those phases. + delete_keys = [] + for key in new_configuration_dict: + key_ext = key[-1:] + if key_ext in key_suffixes: + key_base = key[:-1] + else: + key_base = key + if key_base in non_configuration_keys: + delete_keys.append(key) + + for key in delete_keys: + del new_configuration_dict[key] + + # Merge in configuration (with all its parents first). + MergeConfigWithInheritance(new_configuration_dict, build_file, + target_dict, configuration, []) + + # Put the new result back into the target dict as a configuration. + target_dict['configurations'][configuration] = new_configuration_dict + + # Now drop all the abstract ones. + for configuration in target_dict['configurations'].keys(): + old_configuration_dict = target_dict['configurations'][configuration] + if old_configuration_dict.get('abstract'): + del target_dict['configurations'][configuration] + + # Now that all of the target's configurations have been built, go through + # the target dict's keys and remove everything that's been moved into a + # "configurations" section. + delete_keys = [] + for key in target_dict: + key_ext = key[-1:] + if key_ext in key_suffixes: + key_base = key[:-1] + else: + key_base = key + if not key_base in non_configuration_keys: + delete_keys.append(key) + for key in delete_keys: + del target_dict[key] + + # Check the configurations to see if they contain invalid keys. + for configuration in target_dict['configurations'].keys(): + configuration_dict = target_dict['configurations'][configuration] + for key in configuration_dict.keys(): + if key in invalid_configuration_keys: + raise KeyError, ('%s not allowed in the %s configuration, found in ' + 'target %s' % (key, configuration, target)) + + + +def ProcessListFiltersInDict(name, the_dict): + """Process regular expression and exclusion-based filters on lists. + + An exclusion list is in a dict key named with a trailing "!", like + "sources!". Every item in such a list is removed from the associated + main list, which in this example, would be "sources". Removed items are + placed into a "sources_excluded" list in the dict. + + Regular expression (regex) filters are contained in dict keys named with a + trailing "/", such as "sources/" to operate on the "sources" list. Regex + filters in a dict take the form: + 'sources/': [ ['exclude', '_(linux|mac|win)\\.cc$'], + ['include', '_mac\\.cc$'] ], + The first filter says to exclude all files ending in _linux.cc, _mac.cc, and + _win.cc. The second filter then includes all files ending in _mac.cc that + are now or were once in the "sources" list. Items matching an "exclude" + filter are subject to the same processing as would occur if they were listed + by name in an exclusion list (ending in "!"). Items matching an "include" + filter are brought back into the main list if previously excluded by an + exclusion list or exclusion regex filter. Subsequent matching "exclude" + patterns can still cause items to be excluded after matching an "include". + """ + + # Look through the dictionary for any lists whose keys end in "!" or "/". + # These are lists that will be treated as exclude lists and regular + # expression-based exclude/include lists. Collect the lists that are + # needed first, looking for the lists that they operate on, and assemble + # then into |lists|. This is done in a separate loop up front, because + # the _included and _excluded keys need to be added to the_dict, and that + # can't be done while iterating through it. + + lists = [] + del_lists = [] + for key, value in the_dict.iteritems(): + operation = key[-1] + if operation != '!' and operation != '/': + continue + + if not isinstance(value, list): + raise ValueError, name + ' key ' + key + ' must be list, not ' + \ + value.__class__.__name__ + + list_key = key[:-1] + if list_key not in the_dict: + # This happens when there's a list like "sources!" but no corresponding + # "sources" list. Since there's nothing for it to operate on, queue up + # the "sources!" list for deletion now. + del_lists.append(key) + continue + + if not isinstance(the_dict[list_key], list): + raise ValueError, name + ' key ' + list_key + \ + ' must be list, not ' + \ + value.__class__.__name__ + ' when applying ' + \ + {'!': 'exclusion', '/': 'regex'}[operation] + + if not list_key in lists: + lists.append(list_key) + + # Delete the lists that are known to be unneeded at this point. + for del_list in del_lists: + del the_dict[del_list] + + for list_key in lists: + the_list = the_dict[list_key] + + # Initialize the list_actions list, which is parallel to the_list. Each + # item in list_actions identifies whether the corresponding item in + # the_list should be excluded, unconditionally preserved (included), or + # whether no exclusion or inclusion has been applied. Items for which + # no exclusion or inclusion has been applied (yet) have value -1, items + # excluded have value 0, and items included have value 1. Includes and + # excludes override previous actions. All items in list_actions are + # initialized to -1 because no excludes or includes have been processed + # yet. + list_actions = list((-1,) * len(the_list)) + + exclude_key = list_key + '!' + if exclude_key in the_dict: + for exclude_item in the_dict[exclude_key]: + for index in xrange(0, len(the_list)): + if exclude_item == the_list[index]: + # This item matches the exclude_item, so set its action to 0 + # (exclude). + list_actions[index] = 0 + + # The "whatever!" list is no longer needed, dump it. + del the_dict[exclude_key] + + regex_key = list_key + '/' + if regex_key in the_dict: + for regex_item in the_dict[regex_key]: + [action, pattern] = regex_item + pattern_re = re.compile(pattern) + + if action == 'exclude': + # This item matches an exclude regex, so set its value to 0 (exclude). + action_value = 0 + elif action == 'include': + # This item matches an include regex, so set its value to 1 (include). + action_value = 1 + else: + # This is an action that doesn't make any sense. + raise ValueError, 'Unrecognized action ' + action + ' in ' + name + \ + ' key ' + regex_key + + for index in xrange(0, len(the_list)): + list_item = the_list[index] + if list_actions[index] == action_value: + # Even if the regex matches, nothing will change so continue (regex + # searches are expensive). + continue + if pattern_re.search(list_item): + # Regular expression match. + list_actions[index] = action_value + + # The "whatever/" list is no longer needed, dump it. + del the_dict[regex_key] + + # Add excluded items to the excluded list. + # + # Note that exclude_key ("sources!") is different from excluded_key + # ("sources_excluded"). The exclude_key list is input and it was already + # processed and deleted; the excluded_key list is output and it's about + # to be created. + excluded_key = list_key + '_excluded' + if excluded_key in the_dict: + raise KeyError, \ + name + ' key ' + excluded_key + ' must not be present prior ' + \ + ' to applying exclusion/regex filters for ' + list_key + + excluded_list = [] + + # Go backwards through the list_actions list so that as items are deleted, + # the indices of items that haven't been seen yet don't shift. That means + # that things need to be prepended to excluded_list to maintain them in the + # same order that they existed in the_list. + for index in xrange(len(list_actions) - 1, -1, -1): + if list_actions[index] == 0: + # Dump anything with action 0 (exclude). Keep anything with action 1 + # (include) or -1 (no include or exclude seen for the item). + excluded_list.insert(0, the_list[index]) + del the_list[index] + + # If anything was excluded, put the excluded list into the_dict at + # excluded_key. + if len(excluded_list) > 0: + the_dict[excluded_key] = excluded_list + + # Now recurse into subdicts and lists that may contain dicts. + for key, value in the_dict.iteritems(): + if isinstance(value, dict): + ProcessListFiltersInDict(key, value) + elif isinstance(value, list): + ProcessListFiltersInList(key, value) + + +def ProcessListFiltersInList(name, the_list): + for item in the_list: + if isinstance(item, dict): + ProcessListFiltersInDict(name, item) + elif isinstance(item, list): + ProcessListFiltersInList(name, item) + + +def ValidateTargetType(target, target_dict): + """Ensures the 'type' field on the target is one of the known types. + + Arguments: + target: string, name of target. + target_dict: dict, target spec. + + Raises an exception on error. + """ + VALID_TARGET_TYPES = ('executable', 'loadable_module', + 'static_library', 'shared_library', + 'none') + target_type = target_dict.get('type', None) + if target_type not in VALID_TARGET_TYPES: + raise Exception("Target %s has an invalid target type '%s'. " + "Must be one of %s." % + (target, target_type, '/'.join(VALID_TARGET_TYPES))) + + +def ValidateSourcesInTarget(target, target_dict, build_file): + # TODO: Check if MSVC allows this for non-static_library targets. + if target_dict.get('type', None) != 'static_library': + return + sources = target_dict.get('sources', []) + basenames = {} + for source in sources: + name, ext = os.path.splitext(source) + is_compiled_file = ext in [ + '.c', '.cc', '.cpp', '.cxx', '.m', '.mm', '.s', '.S'] + if not is_compiled_file: + continue + basename = os.path.basename(name) # Don't include extension. + basenames.setdefault(basename, []).append(source) + + error = '' + for basename, files in basenames.iteritems(): + if len(files) > 1: + error += ' %s: %s\n' % (basename, ' '.join(files)) + + if error: + print ('static library %s has several files with the same basename:\n' % + target + error + 'Some build systems, e.g. MSVC08, ' + 'cannot handle that.') + raise KeyError, 'Duplicate basenames in sources section, see list above' + + +def ValidateRulesInTarget(target, target_dict, extra_sources_for_rules): + """Ensures that the rules sections in target_dict are valid and consistent, + and determines which sources they apply to. + + Arguments: + target: string, name of target. + target_dict: dict, target spec containing "rules" and "sources" lists. + extra_sources_for_rules: a list of keys to scan for rule matches in + addition to 'sources'. + """ + + # Dicts to map between values found in rules' 'rule_name' and 'extension' + # keys and the rule dicts themselves. + rule_names = {} + rule_extensions = {} + + rules = target_dict.get('rules', []) + for rule in rules: + # Make sure that there's no conflict among rule names and extensions. + rule_name = rule['rule_name'] + if rule_name in rule_names: + raise KeyError, 'rule %s exists in duplicate, target %s' % \ + (rule_name, target) + rule_names[rule_name] = rule + + rule_extension = rule['extension'] + if rule_extension in rule_extensions: + raise KeyError, ('extension %s associated with multiple rules, ' + + 'target %s rules %s and %s') % \ + (rule_extension, target, + rule_extensions[rule_extension]['rule_name'], + rule_name) + rule_extensions[rule_extension] = rule + + # Make sure rule_sources isn't already there. It's going to be + # created below if needed. + if 'rule_sources' in rule: + raise KeyError, \ + 'rule_sources must not exist in input, target %s rule %s' % \ + (target, rule_name) + extension = rule['extension'] + + rule_sources = [] + source_keys = ['sources'] + source_keys.extend(extra_sources_for_rules) + for source_key in source_keys: + for source in target_dict.get(source_key, []): + (source_root, source_extension) = os.path.splitext(source) + if source_extension.startswith('.'): + source_extension = source_extension[1:] + if source_extension == extension: + rule_sources.append(source) + + if len(rule_sources) > 0: + rule['rule_sources'] = rule_sources + + +def ValidateRunAsInTarget(target, target_dict, build_file): + target_name = target_dict.get('target_name') + run_as = target_dict.get('run_as') + if not run_as: + return + if not isinstance(run_as, dict): + raise Exception("The 'run_as' in target %s from file %s should be a " + "dictionary." % + (target_name, build_file)) + action = run_as.get('action') + if not action: + raise Exception("The 'run_as' in target %s from file %s must have an " + "'action' section." % + (target_name, build_file)) + if not isinstance(action, list): + raise Exception("The 'action' for 'run_as' in target %s from file %s " + "must be a list." % + (target_name, build_file)) + working_directory = run_as.get('working_directory') + if working_directory and not isinstance(working_directory, str): + raise Exception("The 'working_directory' for 'run_as' in target %s " + "in file %s should be a string." % + (target_name, build_file)) + environment = run_as.get('environment') + if environment and not isinstance(environment, dict): + raise Exception("The 'environment' for 'run_as' in target %s " + "in file %s should be a dictionary." % + (target_name, build_file)) + + +def ValidateActionsInTarget(target, target_dict, build_file): + '''Validates the inputs to the actions in a target.''' + target_name = target_dict.get('target_name') + actions = target_dict.get('actions', []) + for action in actions: + action_name = action.get('action_name') + if not action_name: + raise Exception("Anonymous action in target %s. " + "An action must have an 'action_name' field." % + target_name) + inputs = action.get('inputs', None) + if inputs is None: + raise Exception('Action in target %s has no inputs.' % target_name) + action_command = action.get('action') + if action_command and not action_command[0]: + raise Exception("Empty action as command in target %s." % target_name) + + +def TurnIntIntoStrInDict(the_dict): + """Given dict the_dict, recursively converts all integers into strings. + """ + # Use items instead of iteritems because there's no need to try to look at + # reinserted keys and their associated values. + for k, v in the_dict.items(): + if isinstance(v, int): + v = str(v) + the_dict[k] = v + elif isinstance(v, dict): + TurnIntIntoStrInDict(v) + elif isinstance(v, list): + TurnIntIntoStrInList(v) + + if isinstance(k, int): + the_dict[str(k)] = v + del the_dict[k] + + +def TurnIntIntoStrInList(the_list): + """Given list the_list, recursively converts all integers into strings. + """ + for index in xrange(0, len(the_list)): + item = the_list[index] + if isinstance(item, int): + the_list[index] = str(item) + elif isinstance(item, dict): + TurnIntIntoStrInDict(item) + elif isinstance(item, list): + TurnIntIntoStrInList(item) + + +def VerifyNoCollidingTargets(targets): + """Verify that no two targets in the same directory share the same name. + + Arguments: + targets: A list of targets in the form 'path/to/file.gyp:target_name'. + """ + # Keep a dict going from 'subdirectory:target_name' to 'foo.gyp'. + used = {} + for target in targets: + # Separate out 'path/to/file.gyp, 'target_name' from + # 'path/to/file.gyp:target_name'. + path, name = target.rsplit(':', 1) + # Separate out 'path/to', 'file.gyp' from 'path/to/file.gyp'. + subdir, gyp = os.path.split(path) + # Use '.' for the current directory '', so that the error messages make + # more sense. + if not subdir: + subdir = '.' + # Prepare a key like 'path/to:target_name'. + key = subdir + ':' + name + if key in used: + # Complain if this target is already used. + raise Exception('Duplicate target name "%s" in directory "%s" used both ' + 'in "%s" and "%s".' % (name, subdir, gyp, used[key])) + used[key] = gyp + + +def Load(build_files, variables, includes, depth, generator_input_info, check, + circular_check): + # Set up path_sections and non_configuration_keys with the default data plus + # the generator-specifc data. + global path_sections + path_sections = base_path_sections[:] + path_sections.extend(generator_input_info['path_sections']) + + global non_configuration_keys + non_configuration_keys = base_non_configuration_keys[:] + non_configuration_keys.extend(generator_input_info['non_configuration_keys']) + + # TODO(mark) handle variants if the generator doesn't want them directly. + generator_handles_variants = \ + generator_input_info['generator_handles_variants'] + + global absolute_build_file_paths + absolute_build_file_paths = \ + generator_input_info['generator_wants_absolute_build_file_paths'] + + global multiple_toolsets + multiple_toolsets = generator_input_info[ + 'generator_supports_multiple_toolsets'] + + # A generator can have other lists (in addition to sources) be processed + # for rules. + extra_sources_for_rules = generator_input_info['extra_sources_for_rules'] + + # Load build files. This loads every target-containing build file into + # the |data| dictionary such that the keys to |data| are build file names, + # and the values are the entire build file contents after "early" or "pre" + # processing has been done and includes have been resolved. + # NOTE: data contains both "target" files (.gyp) and "includes" (.gypi), as + # well as meta-data (e.g. 'included_files' key). 'target_build_files' keeps + # track of the keys corresponding to "target" files. + data = {'target_build_files': set()} + aux_data = {} + for build_file in build_files: + # Normalize paths everywhere. This is important because paths will be + # used as keys to the data dict and for references between input files. + build_file = os.path.normpath(build_file) + try: + LoadTargetBuildFile(build_file, data, aux_data, variables, includes, + depth, check) + except Exception, e: + gyp.common.ExceptionAppend(e, 'while trying to load %s' % build_file) + raise + + # Build a dict to access each target's subdict by qualified name. + targets = BuildTargetsDict(data) + + # Fully qualify all dependency links. + QualifyDependencies(targets) + + # Expand dependencies specified as build_file:*. + ExpandWildcardDependencies(targets, data) + + # Apply exclude (!) and regex (/) list filters only for dependency_sections. + for target_name, target_dict in targets.iteritems(): + tmp_dict = {} + for key_base in dependency_sections: + for op in ('', '!', '/'): + key = key_base + op + if key in target_dict: + tmp_dict[key] = target_dict[key] + del target_dict[key] + ProcessListFiltersInDict(target_name, tmp_dict) + # Write the results back to |target_dict|. + for key in tmp_dict: + target_dict[key] = tmp_dict[key] + + # Make sure every dependency appears at most once. + RemoveDuplicateDependencies(targets) + + if circular_check: + # Make sure that any targets in a.gyp don't contain dependencies in other + # .gyp files that further depend on a.gyp. + VerifyNoGYPFileCircularDependencies(targets) + + [dependency_nodes, flat_list] = BuildDependencyList(targets) + + # Check that no two targets in the same directory have the same name. + VerifyNoCollidingTargets(flat_list) + + # Handle dependent settings of various types. + for settings_type in ['all_dependent_settings', + 'direct_dependent_settings', + 'link_settings']: + DoDependentSettings(settings_type, flat_list, targets, dependency_nodes) + + # Take out the dependent settings now that they've been published to all + # of the targets that require them. + for target in flat_list: + if settings_type in targets[target]: + del targets[target][settings_type] + + # Make sure static libraries don't declare dependencies on other static + # libraries, but that linkables depend on all unlinked static libraries + # that they need so that their link steps will be correct. + gii = generator_input_info + if gii['generator_wants_static_library_dependencies_adjusted']: + AdjustStaticLibraryDependencies(flat_list, targets, dependency_nodes, + gii['generator_wants_sorted_dependencies']) + + # Apply "post"/"late"/"target" variable expansions and condition evaluations. + for target in flat_list: + target_dict = targets[target] + build_file = gyp.common.BuildFile(target) + ProcessVariablesAndConditionsInDict( + target_dict, PHASE_LATE, variables, build_file) + + # Move everything that can go into a "configurations" section into one. + for target in flat_list: + target_dict = targets[target] + SetUpConfigurations(target, target_dict) + + # Apply exclude (!) and regex (/) list filters. + for target in flat_list: + target_dict = targets[target] + ProcessListFiltersInDict(target, target_dict) + + # Apply "latelate" variable expansions and condition evaluations. + for target in flat_list: + target_dict = targets[target] + build_file = gyp.common.BuildFile(target) + ProcessVariablesAndConditionsInDict( + target_dict, PHASE_LATELATE, variables, build_file) + + # Make sure that the rules make sense, and build up rule_sources lists as + # needed. Not all generators will need to use the rule_sources lists, but + # some may, and it seems best to build the list in a common spot. + # Also validate actions and run_as elements in targets. + for target in flat_list: + target_dict = targets[target] + build_file = gyp.common.BuildFile(target) + ValidateTargetType(target, target_dict) + # TODO(thakis): Get vpx_scale/arm/scalesystemdependent.c to be renamed to + # scalesystemdependent_arm_additions.c or similar. + if 'arm' not in variables.get('target_arch', ''): + ValidateSourcesInTarget(target, target_dict, build_file) + ValidateRulesInTarget(target, target_dict, extra_sources_for_rules) + ValidateRunAsInTarget(target, target_dict, build_file) + ValidateActionsInTarget(target, target_dict, build_file) + + # Generators might not expect ints. Turn them into strs. + TurnIntIntoStrInDict(data) + + # TODO(mark): Return |data| for now because the generator needs a list of + # build files that came in. In the future, maybe it should just accept + # a list, and not the whole data dict. + return [flat_list, targets, data] diff --git a/node-v0.8.14/tools/gyp/pylib/gyp/mac_tool.py b/node-v0.8.14/tools/gyp/pylib/gyp/mac_tool.py new file mode 100755 index 0000000..b918c58 --- /dev/null +++ b/node-v0.8.14/tools/gyp/pylib/gyp/mac_tool.py @@ -0,0 +1,209 @@ +#!/usr/bin/env python +# Copyright (c) 2012 Google Inc. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +"""Utility functions to perform Xcode-style build steps. + +These functions are executed via gyp-mac-tool when using the Makefile generator. +""" + +import fcntl +import os +import plistlib +import re +import shutil +import string +import subprocess +import sys + + +def main(args): + executor = MacTool() + exit_code = executor.Dispatch(args) + if exit_code is not None: + sys.exit(exit_code) + + +class MacTool(object): + """This class performs all the Mac tooling steps. The methods can either be + executed directly, or dispatched from an argument list.""" + + def Dispatch(self, args): + """Dispatches a string command to a method.""" + if len(args) < 1: + raise Exception("Not enough arguments") + + method = "Exec%s" % self._CommandifyName(args[0]) + return getattr(self, method)(*args[1:]) + + def _CommandifyName(self, name_string): + """Transforms a tool name like copy-info-plist to CopyInfoPlist""" + return name_string.title().replace('-', '') + + def ExecCopyBundleResource(self, source, dest): + """Copies a resource file to the bundle/Resources directory, performing any + necessary compilation on each resource.""" + extension = os.path.splitext(source)[1].lower() + if os.path.isdir(source): + # Copy tree. + if os.path.exists(dest): + shutil.rmtree(dest) + shutil.copytree(source, dest) + elif extension == '.xib': + return self._CopyXIBFile(source, dest) + elif extension == '.strings': + self._CopyStringsFile(source, dest) + else: + shutil.copyfile(source, dest) + + def _CopyXIBFile(self, source, dest): + """Compiles a XIB file with ibtool into a binary plist in the bundle.""" + tools_dir = os.environ.get('DEVELOPER_BIN_DIR', '/usr/bin') + args = [os.path.join(tools_dir, 'ibtool'), '--errors', '--warnings', + '--notices', '--output-format', 'human-readable-text', '--compile', + dest, source] + ibtool_section_re = re.compile(r'/\*.*\*/') + ibtool_re = re.compile(r'.*note:.*is clipping its content') + ibtoolout = subprocess.Popen(args, stdout=subprocess.PIPE) + current_section_header = None + for line in ibtoolout.stdout: + if ibtool_section_re.match(line): + current_section_header = line + elif not ibtool_re.match(line): + if current_section_header: + sys.stdout.write(current_section_header) + current_section_header = None + sys.stdout.write(line) + return ibtoolout.returncode + + def _CopyStringsFile(self, source, dest): + """Copies a .strings file using iconv to reconvert the input into UTF-16.""" + input_code = self._DetectInputEncoding(source) or "UTF-8" + fp = open(dest, 'w') + args = ['/usr/bin/iconv', '--from-code', input_code, '--to-code', + 'UTF-16', source] + subprocess.call(args, stdout=fp) + fp.close() + + def _DetectInputEncoding(self, file_name): + """Reads the first few bytes from file_name and tries to guess the text + encoding. Returns None as a guess if it can't detect it.""" + fp = open(file_name, 'rb') + try: + header = fp.read(3) + except e: + fp.close() + return None + fp.close() + if header.startswith("\xFE\xFF"): + return "UTF-16BE" + elif header.startswith("\xFF\xFE"): + return "UTF-16LE" + elif header.startswith("\xEF\xBB\xBF"): + return "UTF-8" + else: + return None + + def ExecCopyInfoPlist(self, source, dest): + """Copies the |source| Info.plist to the destination directory |dest|.""" + # Read the source Info.plist into memory. + fd = open(source, 'r') + lines = fd.read() + fd.close() + + # Go through all the environment variables and replace them as variables in + # the file. + for key in os.environ: + if key.startswith('_'): + continue + evar = '${%s}' % key + lines = string.replace(lines, evar, os.environ[key]) + + # Write out the file with variables replaced. + fd = open(dest, 'w') + fd.write(lines) + fd.close() + + # Now write out PkgInfo file now that the Info.plist file has been + # "compiled". + self._WritePkgInfo(dest) + + def _WritePkgInfo(self, info_plist): + """This writes the PkgInfo file from the data stored in Info.plist.""" + plist = plistlib.readPlist(info_plist) + if not plist: + return + + # Only create PkgInfo for executable types. + package_type = plist['CFBundlePackageType'] + if package_type != 'APPL': + return + + # The format of PkgInfo is eight characters, representing the bundle type + # and bundle signature, each four characters. If that is missing, four + # '?' characters are used instead. + signature_code = plist.get('CFBundleSignature', '????') + if len(signature_code) != 4: # Wrong length resets everything, too. + signature_code = '?' * 4 + + dest = os.path.join(os.path.dirname(info_plist), 'PkgInfo') + fp = open(dest, 'w') + fp.write('%s%s' % (package_type, signature_code)) + fp.close() + + def ExecFlock(self, lockfile, *cmd_list): + """Emulates the most basic behavior of Linux's flock(1).""" + # Rely on exception handling to report errors. + fd = os.open(lockfile, os.O_RDONLY|os.O_NOCTTY|os.O_CREAT, 0o666) + fcntl.flock(fd, fcntl.LOCK_EX) + return subprocess.call(cmd_list) + + def ExecFilterLibtool(self, *cmd_list): + """Calls libtool and filters out 'libtool: file: foo.o has no symbols'.""" + libtool_re = re.compile(r'^libtool: file: .* has no symbols$') + libtoolout = subprocess.Popen(cmd_list, stderr=subprocess.PIPE) + for line in libtoolout.stderr: + if not libtool_re.match(line): + sys.stderr.write(line) + return libtoolout.returncode + + def ExecPackageFramework(self, framework, version): + """Takes a path to Something.framework and the Current version of that and + sets up all the symlinks.""" + # Find the name of the binary based on the part before the ".framework". + binary = os.path.basename(framework).split('.')[0] + + CURRENT = 'Current' + RESOURCES = 'Resources' + VERSIONS = 'Versions' + + if not os.path.exists(os.path.join(framework, VERSIONS, version, binary)): + # Binary-less frameworks don't seem to contain symlinks (see e.g. + # chromium's out/Debug/org.chromium.Chromium.manifest/ bundle). + return + + # Move into the framework directory to set the symlinks correctly. + pwd = os.getcwd() + os.chdir(framework) + + # Set up the Current version. + self._Relink(version, os.path.join(VERSIONS, CURRENT)) + + # Set up the root symlinks. + self._Relink(os.path.join(VERSIONS, CURRENT, binary), binary) + self._Relink(os.path.join(VERSIONS, CURRENT, RESOURCES), RESOURCES) + + # Back to where we were before! + os.chdir(pwd) + + def _Relink(self, dest, link): + """Creates a symlink to |dest| named |link|. If |link| already exists, + it is overwritten.""" + if os.path.lexists(link): + os.remove(link) + os.symlink(dest, link) + + +if __name__ == '__main__': + sys.exit(main(sys.argv[1:])) diff --git a/node-v0.8.14/tools/gyp/pylib/gyp/msvs_emulation.py b/node-v0.8.14/tools/gyp/pylib/gyp/msvs_emulation.py new file mode 100644 index 0000000..4a55aca --- /dev/null +++ b/node-v0.8.14/tools/gyp/pylib/gyp/msvs_emulation.py @@ -0,0 +1,691 @@ +# Copyright (c) 2012 Google Inc. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +""" +This module helps emulate Visual Studio 2008 behavior on top of other +build systems, primarily ninja. +""" + +import os +import re +import subprocess +import sys + +import gyp.MSVSVersion + +windows_quoter_regex = re.compile(r'(\\*)"') + +def QuoteForRspFile(arg): + """Quote a command line argument so that it appears as one argument when + processed via cmd.exe and parsed by CommandLineToArgvW (as is typical for + Windows programs).""" + # See http://goo.gl/cuFbX and http://goo.gl/dhPnp including the comment + # threads. This is actually the quoting rules for CommandLineToArgvW, not + # for the shell, because the shell doesn't do anything in Windows. This + # works more or less because most programs (including the compiler, etc.) + # use that function to handle command line arguments. + + # For a literal quote, CommandLineToArgvW requires 2n+1 backslashes + # preceding it, and results in n backslashes + the quote. So we substitute + # in 2* what we match, +1 more, plus the quote. + arg = windows_quoter_regex.sub(lambda mo: 2 * mo.group(1) + '\\"', arg) + + # %'s also need to be doubled otherwise they're interpreted as batch + # positional arguments. Also make sure to escape the % so that they're + # passed literally through escaping so they can be singled to just the + # original %. Otherwise, trying to pass the literal representation that + # looks like an environment variable to the shell (e.g. %PATH%) would fail. + arg = arg.replace('%', '%%') + + # These commands are used in rsp files, so no escaping for the shell (via ^) + # is necessary. + + # Finally, wrap the whole thing in quotes so that the above quote rule + # applies and whitespace isn't a word break. + return '"' + arg + '"' + + +def EncodeRspFileList(args): + """Process a list of arguments using QuoteCmdExeArgument.""" + # Note that the first argument is assumed to be the command. Don't add + # quotes around it because then built-ins like 'echo', etc. won't work. + # Take care to normpath only the path in the case of 'call ../x.bat' because + # otherwise the whole thing is incorrectly interpreted as a path and not + # normalized correctly. + if not args: return '' + if args[0].startswith('call '): + call, program = args[0].split(' ', 1) + program = call + ' ' + os.path.normpath(program) + else: + program = os.path.normpath(args[0]) + return program + ' ' + ' '.join(QuoteForRspFile(arg) for arg in args[1:]) + + +def _GenericRetrieve(root, default, path): + """Given a list of dictionary keys |path| and a tree of dicts |root|, find + value at path, or return |default| if any of the path doesn't exist.""" + if not root: + return default + if not path: + return root + return _GenericRetrieve(root.get(path[0]), default, path[1:]) + + +def _AddPrefix(element, prefix): + """Add |prefix| to |element| or each subelement if element is iterable.""" + if element is None: + return element + # Note, not Iterable because we don't want to handle strings like that. + if isinstance(element, list) or isinstance(element, tuple): + return [prefix + e for e in element] + else: + return prefix + element + + +def _DoRemapping(element, map): + """If |element| then remap it through |map|. If |element| is iterable then + each item will be remapped. Any elements not found will be removed.""" + if map is not None and element is not None: + if not callable(map): + map = map.get # Assume it's a dict, otherwise a callable to do the remap. + if isinstance(element, list) or isinstance(element, tuple): + element = filter(None, [map(elem) for elem in element]) + else: + element = map(element) + return element + + +def _AppendOrReturn(append, element): + """If |append| is None, simply return |element|. If |append| is not None, + then add |element| to it, adding each item in |element| if it's a list or + tuple.""" + if append is not None and element is not None: + if isinstance(element, list) or isinstance(element, tuple): + append.extend(element) + else: + append.append(element) + else: + return element + + +def _FindDirectXInstallation(): + """Try to find an installation location for the DirectX SDK. Check for the + standard environment variable, and if that doesn't exist, try to find + via the registry. May return None if not found in either location.""" + # Return previously calculated value, if there is one + if hasattr(_FindDirectXInstallation, 'dxsdk_dir'): + return _FindDirectXInstallation.dxsdk_dir + + dxsdk_dir = os.environ.get('DXSDK_DIR') + if not dxsdk_dir: + # Setup params to pass to and attempt to launch reg.exe. + cmd = ['reg.exe', 'query', r'HKLM\Software\Microsoft\DirectX', '/s'] + p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE) + for line in p.communicate()[0].splitlines(): + if 'InstallPath' in line: + dxsdk_dir = line.split(' ')[3] + "\\" + + # Cache return value + _FindDirectXInstallation.dxsdk_dir = dxsdk_dir + return dxsdk_dir + + +class MsvsSettings(object): + """A class that understands the gyp 'msvs_...' values (especially the + msvs_settings field). They largely correpond to the VS2008 IDE DOM. This + class helps map those settings to command line options.""" + + def __init__(self, spec, generator_flags): + self.spec = spec + self.vs_version = GetVSVersion(generator_flags) + self.dxsdk_dir = _FindDirectXInstallation() + + # Try to find an installation location for the Windows DDK by checking + # the WDK_DIR environment variable, may be None. + self.wdk_dir = os.environ.get('WDK_DIR') + + supported_fields = [ + ('msvs_configuration_attributes', dict), + ('msvs_settings', dict), + ('msvs_system_include_dirs', list), + ('msvs_disabled_warnings', list), + ('msvs_precompiled_header', str), + ('msvs_precompiled_source', str), + ('msvs_target_platform', str), + ] + configs = spec['configurations'] + for field, default in supported_fields: + setattr(self, field, {}) + for configname, config in configs.iteritems(): + getattr(self, field)[configname] = config.get(field, default()) + + self.msvs_cygwin_dirs = spec.get('msvs_cygwin_dirs', ['.']) + + def GetVSMacroEnv(self, base_to_build=None, config=None): + """Get a dict of variables mapping internal VS macro names to their gyp + equivalents.""" + target_platform = self.GetTargetPlatform(config) + target_platform = {'x86': 'Win32'}.get(target_platform, target_platform) + replacements = { + '$(VSInstallDir)': self.vs_version.Path(), + '$(VCInstallDir)': os.path.join(self.vs_version.Path(), 'VC') + '\\', + '$(OutDir)\\': base_to_build + '\\' if base_to_build else '', + '$(IntDir)': '$!INTERMEDIATE_DIR', + '$(InputPath)': '${source}', + '$(InputName)': '${root}', + '$(ProjectName)': self.spec['target_name'], + '$(PlatformName)': target_platform, + '$(ProjectDir)\\': '', + } + # Chromium uses DXSDK_DIR in include/lib paths, but it may or may not be + # set. This happens when the SDK is sync'd via src-internal, rather than + # by typical end-user installation of the SDK. If it's not set, we don't + # want to leave the unexpanded variable in the path, so simply strip it. + replacements['$(DXSDK_DIR)'] = self.dxsdk_dir if self.dxsdk_dir else '' + replacements['$(WDK_DIR)'] = self.wdk_dir if self.wdk_dir else '' + return replacements + + def ConvertVSMacros(self, s, base_to_build=None, config=None): + """Convert from VS macro names to something equivalent.""" + env = self.GetVSMacroEnv(base_to_build, config=config) + return ExpandMacros(s, env) + + def AdjustLibraries(self, libraries): + """Strip -l from library if it's specified with that.""" + return [lib[2:] if lib.startswith('-l') else lib for lib in libraries] + + def _GetAndMunge(self, field, path, default, prefix, append, map): + """Retrieve a value from |field| at |path| or return |default|. If + |append| is specified, and the item is found, it will be appended to that + object instead of returned. If |map| is specified, results will be + remapped through |map| before being returned or appended.""" + result = _GenericRetrieve(field, default, path) + result = _DoRemapping(result, map) + result = _AddPrefix(result, prefix) + return _AppendOrReturn(append, result) + + class _GetWrapper(object): + def __init__(self, parent, field, base_path, append=None): + self.parent = parent + self.field = field + self.base_path = [base_path] + self.append = append + def __call__(self, name, map=None, prefix='', default=None): + return self.parent._GetAndMunge(self.field, self.base_path + [name], + default=default, prefix=prefix, append=self.append, map=map) + + def GetTargetPlatform(self, config): + target_platform = self.msvs_target_platform.get(config, '') + if not target_platform: + target_platform = 'Win32' + return {'Win32': 'x86'}.get(target_platform, target_platform) + + def _RealConfig(self, config): + target_platform = self.GetTargetPlatform(config) + if target_platform == 'x64' and not config.endswith('_x64'): + config += '_x64' + return config + + def _Setting(self, path, config, + default=None, prefix='', append=None, map=None): + """_GetAndMunge for msvs_settings.""" + config = self._RealConfig(config) + return self._GetAndMunge( + self.msvs_settings[config], path, default, prefix, append, map) + + def _ConfigAttrib(self, path, config, + default=None, prefix='', append=None, map=None): + """_GetAndMunge for msvs_configuration_attributes.""" + config = self._RealConfig(config) + return self._GetAndMunge( + self.msvs_configuration_attributes[config], + path, default, prefix, append, map) + + def AdjustIncludeDirs(self, include_dirs, config): + """Updates include_dirs to expand VS specific paths, and adds the system + include dirs used for platform SDK and similar.""" + config = self._RealConfig(config) + includes = include_dirs + self.msvs_system_include_dirs[config] + includes.extend(self._Setting( + ('VCCLCompilerTool', 'AdditionalIncludeDirectories'), config, default=[])) + return [self.ConvertVSMacros(p, config=config) for p in includes] + + def GetComputedDefines(self, config): + """Returns the set of defines that are injected to the defines list based + on other VS settings.""" + config = self._RealConfig(config) + defines = [] + if self._ConfigAttrib(['CharacterSet'], config) == '1': + defines.extend(('_UNICODE', 'UNICODE')) + if self._ConfigAttrib(['CharacterSet'], config) == '2': + defines.append('_MBCS') + defines.extend(self._Setting( + ('VCCLCompilerTool', 'PreprocessorDefinitions'), config, default=[])) + return defines + + def GetOutputName(self, config, expand_special): + """Gets the explicitly overridden output name for a target or returns None + if it's not overridden.""" + config = self._RealConfig(config) + type = self.spec['type'] + root = 'VCLibrarianTool' if type == 'static_library' else 'VCLinkerTool' + # TODO(scottmg): Handle OutputDirectory without OutputFile. + output_file = self._Setting((root, 'OutputFile'), config) + if output_file: + output_file = expand_special(self.ConvertVSMacros( + output_file, config=config)) + return output_file + + def GetCflags(self, config): + """Returns the flags that need to be added to .c and .cc compilations.""" + config = self._RealConfig(config) + cflags = [] + cflags.extend(['/wd' + w for w in self.msvs_disabled_warnings[config]]) + cl = self._GetWrapper(self, self.msvs_settings[config], + 'VCCLCompilerTool', append=cflags) + cl('Optimization', + map={'0': 'd', '1': '1', '2': '2', '3': 'x'}, prefix='/O') + cl('InlineFunctionExpansion', prefix='/Ob') + cl('OmitFramePointers', map={'false': '-', 'true': ''}, prefix='/Oy') + cl('FavorSizeOrSpeed', map={'1': 't', '2': 's'}, prefix='/O') + cl('WholeProgramOptimization', map={'true': '/GL'}) + cl('WarningLevel', prefix='/W') + cl('WarnAsError', map={'true': '/WX'}) + cl('DebugInformationFormat', + map={'1': '7', '3': 'i', '4': 'I'}, prefix='/Z') + cl('RuntimeTypeInfo', map={'true': '/GR', 'false': '/GR-'}) + cl('EnableFunctionLevelLinking', map={'true': '/Gy', 'false': '/Gy-'}) + cl('MinimalRebuild', map={'true': '/Gm'}) + cl('BufferSecurityCheck', map={'true': '/GS', 'false': '/GS-'}) + cl('BasicRuntimeChecks', map={'1': 's', '2': 'u', '3': '1'}, prefix='/RTC') + cl('RuntimeLibrary', + map={'0': 'T', '1': 'Td', '2': 'D', '3': 'Dd'}, prefix='/M') + cl('ExceptionHandling', map={'1': 'sc','2': 'a'}, prefix='/EH') + cl('AdditionalOptions', prefix='') + # ninja handles parallelism by itself, don't have the compiler do it too. + cflags = filter(lambda x: not x.startswith('/MP'), cflags) + return cflags + + def GetPrecompiledHeader(self, config, gyp_to_build_path): + """Returns an object that handles the generation of precompiled header + build steps.""" + config = self._RealConfig(config) + return _PchHelper(self, config, gyp_to_build_path) + + def _GetPchFlags(self, config, extension): + """Get the flags to be added to the cflags for precompiled header support. + """ + config = self._RealConfig(config) + # The PCH is only built once by a particular source file. Usage of PCH must + # only be for the same language (i.e. C vs. C++), so only include the pch + # flags when the language matches. + if self.msvs_precompiled_header[config]: + source_ext = os.path.splitext(self.msvs_precompiled_source[config])[1] + if _LanguageMatchesForPch(source_ext, extension): + pch = os.path.split(self.msvs_precompiled_header[config])[1] + return ['/Yu' + pch, '/FI' + pch, '/Fp${pchprefix}.' + pch + '.pch'] + return [] + + def GetCflagsC(self, config): + """Returns the flags that need to be added to .c compilations.""" + config = self._RealConfig(config) + return self._GetPchFlags(config, '.c') + + def GetCflagsCC(self, config): + """Returns the flags that need to be added to .cc compilations.""" + config = self._RealConfig(config) + return ['/TP'] + self._GetPchFlags(config, '.cc') + + def _GetAdditionalLibraryDirectories(self, root, config, gyp_to_build_path): + """Get and normalize the list of paths in AdditionalLibraryDirectories + setting.""" + config = self._RealConfig(config) + libpaths = self._Setting((root, 'AdditionalLibraryDirectories'), + config, default=[]) + libpaths = [os.path.normpath( + gyp_to_build_path(self.ConvertVSMacros(p, config=config))) + for p in libpaths] + return ['/LIBPATH:"' + p + '"' for p in libpaths] + + def GetLibFlags(self, config, gyp_to_build_path): + """Returns the flags that need to be added to lib commands.""" + config = self._RealConfig(config) + libflags = [] + lib = self._GetWrapper(self, self.msvs_settings[config], + 'VCLibrarianTool', append=libflags) + libflags.extend(self._GetAdditionalLibraryDirectories( + 'VCLibrarianTool', config, gyp_to_build_path)) + lib('AdditionalOptions') + return libflags + + def _GetDefFileAsLdflags(self, spec, ldflags, gyp_to_build_path): + """.def files get implicitly converted to a ModuleDefinitionFile for the + linker in the VS generator. Emulate that behaviour here.""" + def_file = '' + if spec['type'] in ('shared_library', 'loadable_module', 'executable'): + def_files = [s for s in spec.get('sources', []) if s.endswith('.def')] + if len(def_files) == 1: + ldflags.append('/DEF:"%s"' % gyp_to_build_path(def_files[0])) + elif len(def_files) > 1: + raise Exception("Multiple .def files") + + def GetLdflags(self, config, gyp_to_build_path, expand_special, + manifest_base_name, is_executable): + """Returns the flags that need to be added to link commands, and the + manifest files.""" + config = self._RealConfig(config) + ldflags = [] + ld = self._GetWrapper(self, self.msvs_settings[config], + 'VCLinkerTool', append=ldflags) + self._GetDefFileAsLdflags(self.spec, ldflags, gyp_to_build_path) + ld('GenerateDebugInformation', map={'true': '/DEBUG'}) + ld('TargetMachine', map={'1': 'X86', '17': 'X64'}, prefix='/MACHINE:') + ldflags.extend(self._GetAdditionalLibraryDirectories( + 'VCLinkerTool', config, gyp_to_build_path)) + ld('DelayLoadDLLs', prefix='/DELAYLOAD:') + out = self.GetOutputName(config, expand_special) + if out: + ldflags.append('/OUT:' + out) + ld('AdditionalOptions', prefix='') + ld('SubSystem', map={'1': 'CONSOLE', '2': 'WINDOWS'}, prefix='/SUBSYSTEM:') + ld('LinkIncremental', map={'1': ':NO', '2': ''}, prefix='/INCREMENTAL') + ld('FixedBaseAddress', map={'1': ':NO', '2': ''}, prefix='/FIXED') + ld('RandomizedBaseAddress', + map={'1': ':NO', '2': ''}, prefix='/DYNAMICBASE') + ld('DataExecutionPrevention', + map={'1': ':NO', '2': ''}, prefix='/NXCOMPAT') + ld('OptimizeReferences', map={'1': 'NOREF', '2': 'REF'}, prefix='/OPT:') + ld('EnableCOMDATFolding', map={'1': 'NOICF', '2': 'ICF'}, prefix='/OPT:') + ld('LinkTimeCodeGeneration', map={'1': '/LTCG'}) + ld('IgnoreDefaultLibraryNames', prefix='/NODEFAULTLIB:') + ld('ResourceOnlyDLL', map={'true': '/NOENTRY'}) + ld('EntryPointSymbol', prefix='/ENTRY:') + # TODO(scottmg): This should sort of be somewhere else (not really a flag). + ld('AdditionalDependencies', prefix='') + # TODO(scottmg): These too. + ldflags.extend(('kernel32.lib', 'user32.lib', 'gdi32.lib', 'winspool.lib', + 'comdlg32.lib', 'advapi32.lib', 'shell32.lib', 'ole32.lib', + 'oleaut32.lib', 'uuid.lib', 'odbc32.lib', 'DelayImp.lib')) + + # If the base address is not specifically controlled, DYNAMICBASE should + # be on by default. + base_flags = filter(lambda x: 'DYNAMICBASE' in x or x == '/FIXED', + ldflags) + if not base_flags: + ldflags.append('/DYNAMICBASE') + + # If the NXCOMPAT flag has not been specified, default to on. Despite the + # documentation that says this only defaults to on when the subsystem is + # Vista or greater (which applies to the linker), the IDE defaults it on + # unless it's explicitly off. + if not filter(lambda x: 'NXCOMPAT' in x, ldflags): + ldflags.append('/NXCOMPAT') + + have_def_file = filter(lambda x: x.startswith('/DEF:'), ldflags) + manifest_flags, intermediate_manifest_file = self._GetLdManifestFlags( + config, manifest_base_name, is_executable and not have_def_file) + ldflags.extend(manifest_flags) + manifest_files = self._GetAdditionalManifestFiles(config, gyp_to_build_path) + manifest_files.append(intermediate_manifest_file) + + return ldflags, manifest_files + + def _GetLdManifestFlags(self, config, name, allow_isolation): + """Returns the set of flags that need to be added to the link to generate + a default manifest, as well as the name of the generated file.""" + # Add manifest flags that mirror the defaults in VS. Chromium dev builds + # do not currently use any non-default settings, but we could parse + # VCManifestTool blocks if Chromium or other projects need them in the + # future. Of particular note, we do not yet support EmbedManifest because + # it complicates incremental linking. + output_name = name + '.intermediate.manifest' + flags = [ + '/MANIFEST', + '/ManifestFile:' + output_name, + '''/MANIFESTUAC:"level='asInvoker' uiAccess='false'"''' + ] + if allow_isolation: + flags.append('/ALLOWISOLATION') + return flags, output_name + + def _GetAdditionalManifestFiles(self, config, gyp_to_build_path): + """Gets additional manifest files that are added to the default one + generated by the linker.""" + files = self._Setting(('VCManifestTool', 'AdditionalManifestFiles'), config, + default=[]) + if (self._Setting( + ('VCManifestTool', 'EmbedManifest'), config, default='') == 'true'): + print 'gyp/msvs_emulation.py: "EmbedManifest: true" not yet supported.' + if isinstance(files, str): + files = files.split(';') + return [os.path.normpath( + gyp_to_build_path(self.ConvertVSMacros(f, config=config))) + for f in files] + + def IsUseLibraryDependencyInputs(self, config): + """Returns whether the target should be linked via Use Library Dependency + Inputs (using component .objs of a given .lib).""" + config = self._RealConfig(config) + uldi = self._Setting(('VCLinkerTool', 'UseLibraryDependencyInputs'), config) + return uldi == 'true' + + def GetRcflags(self, config, gyp_to_ninja_path): + """Returns the flags that need to be added to invocations of the resource + compiler.""" + config = self._RealConfig(config) + rcflags = [] + rc = self._GetWrapper(self, self.msvs_settings[config], + 'VCResourceCompilerTool', append=rcflags) + rc('AdditionalIncludeDirectories', map=gyp_to_ninja_path, prefix='/I') + rcflags.append('/I' + gyp_to_ninja_path('.')) + rc('PreprocessorDefinitions', prefix='/d') + # /l arg must be in hex without leading '0x' + rc('Culture', prefix='/l', map=lambda x: hex(int(x))[2:]) + return rcflags + + def BuildCygwinBashCommandLine(self, args, path_to_base): + """Build a command line that runs args via cygwin bash. We assume that all + incoming paths are in Windows normpath'd form, so they need to be + converted to posix style for the part of the command line that's passed to + bash. We also have to do some Visual Studio macro emulation here because + various rules use magic VS names for things. Also note that rules that + contain ninja variables cannot be fixed here (for example ${source}), so + the outer generator needs to make sure that the paths that are written out + are in posix style, if the command line will be used here.""" + cygwin_dir = os.path.normpath( + os.path.join(path_to_base, self.msvs_cygwin_dirs[0])) + cd = ('cd %s' % path_to_base).replace('\\', '/') + args = [a.replace('\\', '/').replace('"', '\\"') for a in args] + args = ["'%s'" % a.replace("'", "'\\''") for a in args] + bash_cmd = ' '.join(args) + cmd = ( + 'call "%s\\setup_env.bat" && set CYGWIN=nontsec && ' % cygwin_dir + + 'bash -c "%s ; %s"' % (cd, bash_cmd)) + return cmd + + def IsRuleRunUnderCygwin(self, rule): + """Determine if an action should be run under cygwin. If the variable is + unset, or set to 1 we use cygwin.""" + return int(rule.get('msvs_cygwin_shell', + self.spec.get('msvs_cygwin_shell', 1))) != 0 + + def HasExplicitIdlRules(self, spec): + """Determine if there's an explicit rule for idl files. When there isn't we + need to generate implicit rules to build MIDL .idl files.""" + for rule in spec.get('rules', []): + if rule['extension'] == 'idl' and int(rule.get('msvs_external_rule', 0)): + return True + return False + + def GetIdlBuildData(self, source, config): + """Determine the implicit outputs for an idl file. Returns output + directory, outputs, and variables and flags that are required.""" + config = self._RealConfig(config) + midl_get = self._GetWrapper(self, self.msvs_settings[config], 'VCMIDLTool') + def midl(name, default=None): + return self.ConvertVSMacros(midl_get(name, default=default), + config=config) + tlb = midl('TypeLibraryName', default='${root}.tlb') + header = midl('HeaderFileName', default='${root}.h') + dlldata = midl('DLLDataFileName', default='dlldata.c') + iid = midl('InterfaceIdentifierFileName', default='${root}_i.c') + proxy = midl('ProxyFileName', default='${root}_p.c') + # Note that .tlb is not included in the outputs as it is not always + # generated depending on the content of the input idl file. + outdir = midl('OutputDirectory', default='') + output = [header, dlldata, iid, proxy] + variables = [('tlb', tlb), + ('h', header), + ('dlldata', dlldata), + ('iid', iid), + ('proxy', proxy)] + # TODO(scottmg): Are there configuration settings to set these flags? + flags = ['/char', 'signed', '/env', 'win32', '/Oicf'] + return outdir, output, variables, flags + + +def _LanguageMatchesForPch(source_ext, pch_source_ext): + c_exts = ('.c',) + cc_exts = ('.cc', '.cxx', '.cpp') + return ((source_ext in c_exts and pch_source_ext in c_exts) or + (source_ext in cc_exts and pch_source_ext in cc_exts)) + +class PrecompiledHeader(object): + """Helper to generate dependencies and build rules to handle generation of + precompiled headers. Interface matches the GCH handler in xcode_emulation.py. + """ + def __init__(self, settings, config, gyp_to_build_path): + self.settings = settings + self.config = config + self.gyp_to_build_path = gyp_to_build_path + + def _PchHeader(self): + """Get the header that will appear in an #include line for all source + files.""" + return os.path.split(self.settings.msvs_precompiled_header[self.config])[1] + + def _PchSource(self): + """Get the source file that is built once to compile the pch data.""" + return self.gyp_to_build_path( + self.settings.msvs_precompiled_source[self.config]) + + def _PchOutput(self): + """Get the name of the output of the compiled pch data.""" + return '${pchprefix}.' + self._PchHeader() + '.pch' + + def GetObjDependencies(self, sources, objs): + """Given a list of sources files and the corresponding object files, + returns a list of the pch files that should be depended upon. The + additional wrapping in the return value is for interface compatability + with make.py on Mac, and xcode_emulation.py.""" + if not self._PchHeader(): + return [] + source = self._PchSource() + assert source + pch_ext = os.path.splitext(self._PchSource())[1] + for source in sources: + if _LanguageMatchesForPch(os.path.splitext(source)[1], pch_ext): + return [(None, None, self._PchOutput())] + return [] + + def GetPchBuildCommands(self): + """Returns [(path_to_pch, language_flag, language, header)]. + |path_to_gch| and |header| are relative to the build directory.""" + header = self._PchHeader() + source = self._PchSource() + if not source or not header: + return [] + ext = os.path.splitext(source)[1] + lang = 'c' if ext == '.c' else 'cc' + return [(self._PchOutput(), '/Yc' + header, lang, source)] + + +vs_version = None +def GetVSVersion(generator_flags): + global vs_version + if not vs_version: + vs_version = gyp.MSVSVersion.SelectVisualStudioVersion( + generator_flags.get('msvs_version', 'auto')) + return vs_version + +def _GetVsvarsSetupArgs(generator_flags, arch): + vs = GetVSVersion(generator_flags) + return vs.SetupScript() + +def ExpandMacros(string, expansions): + """Expand $(Variable) per expansions dict. See MsvsSettings.GetVSMacroEnv + for the canonical way to retrieve a suitable dict.""" + if '$' in string: + for old, new in expansions.iteritems(): + assert '$(' not in new, new + string = string.replace(old, new) + return string + +def _ExtractImportantEnvironment(output_of_set): + """Extracts environment variables required for the toolchain to run from + a textual dump output by the cmd.exe 'set' command.""" + envvars_to_save = ( + 'goma_.*', # TODO(scottmg): This is ugly, but needed for goma. + 'include', + 'lib', + 'libpath', + 'path', + 'pathext', + 'systemroot', + 'temp', + 'tmp', + ) + env = {} + for line in output_of_set.splitlines(): + for envvar in envvars_to_save: + if re.match(envvar + '=', line.lower()): + var, setting = line.split('=', 1) + if envvar == 'path': + # Our own rules (for running gyp-win-tool) and other actions in + # Chromium rely on python being in the path. Add the path to this + # python here so that if it's not in the path when ninja is run + # later, python will still be found. + setting = os.path.dirname(sys.executable) + os.pathsep + setting + env[var.upper()] = setting + break + for required in ('SYSTEMROOT', 'TEMP', 'TMP'): + if required not in env: + raise Exception('Environment variable "%s" ' + 'required to be set to valid path' % required) + return env + +def _FormatAsEnvironmentBlock(envvar_dict): + """Format as an 'environment block' directly suitable for CreateProcess. + Briefly this is a list of key=value\0, terminated by an additional \0. See + CreateProcess documentation for more details.""" + block = '' + nul = '\0' + for key, value in envvar_dict.iteritems(): + block += key + '=' + value + nul + block += nul + return block + +def GenerateEnvironmentFiles(toplevel_build_dir, generator_flags, open_out): + """It's not sufficient to have the absolute path to the compiler, linker, + etc. on Windows, as those tools rely on .dlls being in the PATH. We also + need to support both x86 and x64 compilers within the same build (to support + msvs_target_platform hackery). Different architectures require a different + compiler binary, and different supporting environment variables (INCLUDE, + LIB, LIBPATH). So, we extract the environment here, wrap all invocations + of compiler tools (cl, link, lib, rc, midl, etc.) via win_tool.py which + sets up the environment, and then we do not prefix the compiler with + an absolute path, instead preferring something like "cl.exe" in the rule + which will then run whichever the environment setup has put in the path.""" + vs = GetVSVersion(generator_flags) + for arch in ('x86', 'x64'): + args = vs.SetupScript(arch) + args.extend(('&&', 'set')) + popen = subprocess.Popen( + args, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) + variables, _ = popen.communicate() + env = _ExtractImportantEnvironment(variables) + env_block = _FormatAsEnvironmentBlock(env) + f = open_out(os.path.join(toplevel_build_dir, 'environment.' + arch), 'wb') + f.write(env_block) + f.close() diff --git a/node-v0.8.14/tools/gyp/pylib/gyp/ninja_syntax.py b/node-v0.8.14/tools/gyp/pylib/gyp/ninja_syntax.py new file mode 100644 index 0000000..ae85d0f --- /dev/null +++ b/node-v0.8.14/tools/gyp/pylib/gyp/ninja_syntax.py @@ -0,0 +1,153 @@ +# This file comes from +# https://github.com/martine/ninja/blob/master/misc/ninja_syntax.py +# Do not edit! Edit the upstream one instead. + +"""Python module for generating .ninja files. + +Note that this is emphatically not a required piece of Ninja; it's +just a helpful utility for build-file-generation systems that already +use Python. +""" + +import textwrap +import re + +def escape_spaces(word): + return word.replace('$ ','$$ ').replace(' ','$ ') + +class Writer(object): + def __init__(self, output, width=78): + self.output = output + self.width = width + + def newline(self): + self.output.write('\n') + + def comment(self, text): + for line in textwrap.wrap(text, self.width - 2): + self.output.write('# ' + line + '\n') + + def variable(self, key, value, indent=0): + if value is None: + return + if isinstance(value, list): + value = ' '.join(filter(None, value)) # Filter out empty strings. + self._line('%s = %s' % (key, value), indent) + + def rule(self, name, command, description=None, depfile=None, + generator=False, restat=False, rspfile=None, + rspfile_content=None): + self._line('rule %s' % name) + self.variable('command', command, indent=1) + if description: + self.variable('description', description, indent=1) + if depfile: + self.variable('depfile', depfile, indent=1) + if generator: + self.variable('generator', '1', indent=1) + if restat: + self.variable('restat', '1', indent=1) + if rspfile: + self.variable('rspfile', rspfile, indent=1) + if rspfile_content: + self.variable('rspfile_content', rspfile_content, indent=1) + + def build(self, outputs, rule, inputs=None, implicit=None, order_only=None, + variables=None): + outputs = self._as_list(outputs) + all_inputs = self._as_list(inputs)[:] + out_outputs = list(map(escape_spaces, outputs)) + all_inputs = list(map(escape_spaces, all_inputs)) + + if implicit: + implicit = map(escape_spaces, self._as_list(implicit)) + all_inputs.append('|') + all_inputs.extend(implicit) + if order_only: + order_only = map(escape_spaces, self._as_list(order_only)) + all_inputs.append('||') + all_inputs.extend(order_only) + + self._line('build %s: %s %s' % (' '.join(out_outputs), + rule, + ' '.join(all_inputs))) + + if variables: + if isinstance(variables, dict): + iterator = variables.iteritems() + else: + iterator = iter(variables) + + for key, val in iterator: + self.variable(key, val, indent=1) + + return outputs + + def include(self, path): + self._line('include %s' % path) + + def subninja(self, path): + self._line('subninja %s' % path) + + def default(self, paths): + self._line('default %s' % ' '.join(self._as_list(paths))) + + def _count_dollars_before_index(self, s, i): + """Returns the number of '$' characters right in front of s[i].""" + dollar_count = 0 + dollar_index = i - 1 + while dollar_index > 0 and s[dollar_index] == '$': + dollar_count += 1 + dollar_index -= 1 + return dollar_count + + def _line(self, text, indent=0): + """Write 'text' word-wrapped at self.width characters.""" + leading_space = ' ' * indent + while len(leading_space) + len(text) > self.width: + # The text is too wide; wrap if possible. + + # Find the rightmost space that would obey our width constraint and + # that's not an escaped space. + available_space = self.width - len(leading_space) - len(' $') + space = available_space + while True: + space = text.rfind(' ', 0, space) + if space < 0 or \ + self._count_dollars_before_index(text, space) % 2 == 0: + break + + if space < 0: + # No such space; just use the first unescaped space we can find. + space = available_space - 1 + while True: + space = text.find(' ', space + 1) + if space < 0 or \ + self._count_dollars_before_index(text, space) % 2 == 0: + break + if space < 0: + # Give up on breaking. + break + + self.output.write(leading_space + text[0:space] + ' $\n') + text = text[space+1:] + + # Subsequent lines are continuations, so indent them. + leading_space = ' ' * (indent+2) + + self.output.write(leading_space + text + '\n') + + def _as_list(self, input): + if input is None: + return [] + if isinstance(input, list): + return input + return [input] + + +def escape(string): + """Escape a string such that it can be embedded into a Ninja file without + further interpretation.""" + assert '\n' not in string, 'Ninja syntax does not allow newlines' + # We only have one special metacharacter: '$'. + return string.replace('$', '$$') diff --git a/node-v0.8.14/tools/gyp/pylib/gyp/sun_tool.py b/node-v0.8.14/tools/gyp/pylib/gyp/sun_tool.py new file mode 100755 index 0000000..90d59c8 --- /dev/null +++ b/node-v0.8.14/tools/gyp/pylib/gyp/sun_tool.py @@ -0,0 +1,51 @@ +#!/usr/bin/env python +# Copyright (c) 2011 Google Inc. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +"""These functions are executed via gyp-sun-tool when using the Makefile +generator.""" + +import fcntl +import os +import struct +import subprocess +import sys + + +def main(args): + executor = SunTool() + executor.Dispatch(args) + + +class SunTool(object): + """This class performs all the SunOS tooling steps. The methods can either be + executed directly, or dispatched from an argument list.""" + + def Dispatch(self, args): + """Dispatches a string command to a method.""" + if len(args) < 1: + raise Exception("Not enough arguments") + + method = "Exec%s" % self._CommandifyName(args[0]) + getattr(self, method)(*args[1:]) + + def _CommandifyName(self, name_string): + """Transforms a tool name like copy-info-plist to CopyInfoPlist""" + return name_string.title().replace('-', '') + + def ExecFlock(self, lockfile, *cmd_list): + """Emulates the most basic behavior of Linux's flock(1).""" + # Rely on exception handling to report errors. + # Note that the stock python on SunOS has a bug + # where fcntl.flock(fd, LOCK_EX) always fails + # with EBADF, that's why we use this F_SETLK + # hack instead. + fd = os.open(lockfile, os.O_WRONLY|os.O_NOCTTY|os.O_CREAT, 0666) + op = struct.pack('hhllhhl', fcntl.F_WRLCK, 0, 0, 0, 0, 0, 0) + fcntl.fcntl(fd, fcntl.F_SETLK, op) + return subprocess.call(cmd_list) + + +if __name__ == '__main__': + sys.exit(main(sys.argv[1:])) diff --git a/node-v0.8.14/tools/gyp/pylib/gyp/system_test.py b/node-v0.8.14/tools/gyp/pylib/gyp/system_test.py new file mode 100755 index 0000000..51c71e3 --- /dev/null +++ b/node-v0.8.14/tools/gyp/pylib/gyp/system_test.py @@ -0,0 +1,68 @@ +#!/usr/bin/env python + +# Copyright (c) 2011 Google Inc. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +import os +import tempfile +import shutil +import subprocess + + +def TestCommands(commands, files={}, env={}): + """Run commands in a temporary directory, returning true if they all succeed. + Return false on failures or if any commands produce output. + + Arguments: + commands: an array of shell-interpretable commands, e.g. ['ls -l', 'pwd'] + each will be expanded with Python %-expansion using env first. + files: a dictionary mapping filename to contents; + files will be created in the temporary directory before running + the command. + env: a dictionary of strings to expand commands with. + """ + tempdir = tempfile.mkdtemp() + try: + for name, contents in files.items(): + f = open(os.path.join(tempdir, name), 'wb') + f.write(contents) + f.close() + for command in commands: + proc = subprocess.Popen(command % env, shell=True, + stdout=subprocess.PIPE, + stderr=subprocess.STDOUT, + cwd=tempdir) + output = proc.communicate()[0] + if proc.returncode != 0 or output: + return False + return True + finally: + shutil.rmtree(tempdir) + return False + + +def TestArSupportsT(ar_command='ar', cc_command='cc'): + """Test whether 'ar' supports the 'T' flag.""" + return TestCommands(['%(cc)s -c test.c', + '%(ar)s crsT test.a test.o', + '%(cc)s test.a'], + files={'test.c': 'int main(){}'}, + env={'ar': ar_command, 'cc': cc_command}) + + +def main(): + # Run the various test functions and print the results. + def RunTest(description, function, **kwargs): + print "Testing " + description + ':', + if function(**kwargs): + print 'ok' + else: + print 'fail' + RunTest("ar 'T' flag", TestArSupportsT) + RunTest("ar 'T' flag with ccache", TestArSupportsT, cc_command='ccache cc') + return 0 + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/node-v0.8.14/tools/gyp/pylib/gyp/win_tool.py b/node-v0.8.14/tools/gyp/pylib/gyp/win_tool.py new file mode 100644 index 0000000..c9c6a7b --- /dev/null +++ b/node-v0.8.14/tools/gyp/pylib/gyp/win_tool.py @@ -0,0 +1,194 @@ +#!/usr/bin/env python + +# Copyright (c) 2012 Google Inc. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +"""Utility functions for Windows builds. + +These functions are executed via gyp-win-tool when using the ninja generator. +""" + +import os +import shutil +import subprocess +import sys +import win32con +import win32file +import pywintypes + + +def main(args): + executor = WinTool() + exit_code = executor.Dispatch(args) + if exit_code is not None: + sys.exit(exit_code) + + +class LinkLock(object): + """A flock-style lock to limit the number of concurrent links to one. Based on + http://code.activestate.com/recipes/65203-portalocker-cross-platform-posixnt-api-for-flock-s/ + """ + def __enter__(self): + self.file = open('LinkLock', 'w+') + self.file_handle = win32file._get_osfhandle(self.file.fileno()) + win32file.LockFileEx(self.file_handle, win32con.LOCKFILE_EXCLUSIVE_LOCK, + 0, -0x10000, pywintypes.OVERLAPPED()) + + def __exit__(self, type, value, traceback): + win32file.UnlockFileEx( + self.file_handle, 0, -0x10000, pywintypes.OVERLAPPED()) + self.file.close() + + +class WinTool(object): + """This class performs all the Windows tooling steps. The methods can either + be executed directly, or dispatched from an argument list.""" + + def Dispatch(self, args): + """Dispatches a string command to a method.""" + if len(args) < 1: + raise Exception("Not enough arguments") + + method = "Exec%s" % self._CommandifyName(args[0]) + return getattr(self, method)(*args[1:]) + + def _CommandifyName(self, name_string): + """Transforms a tool name like recursive-mirror to RecursiveMirror.""" + return name_string.title().replace('-', '') + + def _GetEnv(self, arch): + """Gets the saved environment from a file for a given architecture.""" + # The environment is saved as an "environment block" (see CreateProcess + # and msvs_emulation for details). We convert to a dict here. + # Drop last 2 NULs, one for list terminator, one for trailing vs. separator. + pairs = open(arch).read()[:-2].split('\0') + kvs = [item.split('=', 1) for item in pairs] + return dict(kvs) + + def ExecStamp(self, path): + """Simple stamp command.""" + open(path, 'w').close() + + def ExecRecursiveMirror(self, source, dest): + """Emulation of rm -rf out && cp -af in out.""" + if os.path.exists(dest): + if os.path.isdir(dest): + shutil.rmtree(dest) + else: + os.unlink(dest) + if os.path.isdir(source): + shutil.copytree(source, dest) + else: + shutil.copy2(source, dest) + + def ExecLinkWrapper(self, arch, *args): + """Filter diagnostic output from link that looks like: + ' Creating library ui.dll.lib and object ui.dll.exp' + This happens when there are exports from the dll or exe. + """ + with LinkLock(): + env = self._GetEnv(arch) + popen = subprocess.Popen(args, shell=True, env=env, + stdout=subprocess.PIPE, stderr=subprocess.STDOUT) + out, _ = popen.communicate() + for line in out.splitlines(): + if not line.startswith(' Creating library '): + print line + return popen.returncode + + def ExecManifestWrapper(self, arch, *args): + """Run manifest tool with environment set. Strip out undesirable warning + (some XML blocks are recognized by the OS loader, but not the manifest + tool).""" + env = self._GetEnv(arch) + popen = subprocess.Popen(args, shell=True, env=env, + stdout=subprocess.PIPE, stderr=subprocess.STDOUT) + out, _ = popen.communicate() + for line in out.splitlines(): + if line and 'manifest authoring warning 81010002' not in line: + print line + return popen.returncode + + def ExecMidlWrapper(self, arch, outdir, tlb, h, dlldata, iid, proxy, idl, + *flags): + """Filter noisy filenames output from MIDL compile step that isn't + quietable via command line flags. + """ + args = ['midl', '/nologo'] + list(flags) + [ + '/out', outdir, + '/tlb', tlb, + '/h', h, + '/dlldata', dlldata, + '/iid', iid, + '/proxy', proxy, + idl] + env = self._GetEnv(arch) + popen = subprocess.Popen(args, shell=True, env=env, + stdout=subprocess.PIPE, stderr=subprocess.STDOUT) + out, _ = popen.communicate() + # Filter junk out of stdout, and write filtered versions. Output we want + # to filter is pairs of lines that look like this: + # Processing C:\Program Files (x86)\Microsoft SDKs\...\include\objidl.idl + # objidl.idl + lines = out.splitlines() + prefix = 'Processing ' + processing = set(os.path.basename(x) for x in lines if x.startswith(prefix)) + for line in lines: + if not line.startswith(prefix) and line not in processing: + print line + return popen.returncode + + def ExecAsmWrapper(self, arch, *args): + """Filter logo banner from invocations of asm.exe.""" + env = self._GetEnv(arch) + # MSVS doesn't assemble x64 asm files. + if arch == 'environment.x64': + return 0 + popen = subprocess.Popen(args, shell=True, env=env, + stdout=subprocess.PIPE, stderr=subprocess.STDOUT) + out, _ = popen.communicate() + for line in out.splitlines(): + if (not line.startswith('Copyright (C) Microsoft Corporation') and + not line.startswith('Microsoft (R) Macro Assembler') and + not line.startswith(' Assembling: ') and + line): + print line + return popen.returncode + + def ExecRcWrapper(self, arch, *args): + """Filter logo banner from invocations of rc.exe. Older versions of RC + don't support the /nologo flag.""" + env = self._GetEnv(arch) + popen = subprocess.Popen(args, shell=True, env=env, + stdout=subprocess.PIPE, stderr=subprocess.STDOUT) + out, _ = popen.communicate() + for line in out.splitlines(): + if (not line.startswith('Microsoft (R) Windows (R) Resource Compiler') and + not line.startswith('Copyright (C) Microsoft Corporation') and + line): + print line + return popen.returncode + + def ExecClWrapper(self, arch, depname, *args): + """Runs cl.exe and filters output through ninja-deplist-helper to get + dependendency information which is stored in |depname|.""" + env = self._GetEnv(arch) + args = ' '.join(args) + \ + '| ninja-deplist-helper -r . -q -f cl -o ' + depname + '"' + popen = subprocess.Popen(args, shell=True, env=env) + popen.wait() + return popen.returncode + + def ExecActionWrapper(self, arch, rspfile, *dir): + """Runs an action command line from a response file using the environment + for |arch|. If |dir| is supplied, use that as the working directory.""" + env = self._GetEnv(arch) + args = open(rspfile).read() + dir = dir[0] if dir else None + popen = subprocess.Popen(args, shell=True, env=env, cwd=dir) + popen.wait() + return popen.returncode + +if __name__ == '__main__': + sys.exit(main(sys.argv[1:])) diff --git a/node-v0.8.14/tools/gyp/pylib/gyp/xcode_emulation.py b/node-v0.8.14/tools/gyp/pylib/gyp/xcode_emulation.py new file mode 100644 index 0000000..32b6f35 --- /dev/null +++ b/node-v0.8.14/tools/gyp/pylib/gyp/xcode_emulation.py @@ -0,0 +1,1044 @@ +# Copyright (c) 2012 Google Inc. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +""" +This module contains classes that help to emulate xcodebuild behavior on top of +other build systems, such as make and ninja. +""" + +import gyp.common +import os.path +import re +import shlex + +class XcodeSettings(object): + """A class that understands the gyp 'xcode_settings' object.""" + + # Computed lazily by _GetSdkBaseDir(). Shared by all XcodeSettings, so cached + # at class-level for efficiency. + _sdk_base_dir = None + + def __init__(self, spec): + self.spec = spec + + # Per-target 'xcode_settings' are pushed down into configs earlier by gyp. + # This means self.xcode_settings[config] always contains all settings + # for that config -- the per-target settings as well. Settings that are + # the same for all configs are implicitly per-target settings. + self.xcode_settings = {} + configs = spec['configurations'] + for configname, config in configs.iteritems(): + self.xcode_settings[configname] = config.get('xcode_settings', {}) + + # This is only non-None temporarily during the execution of some methods. + self.configname = None + + # Used by _AdjustLibrary to match .a and .dylib entries in libraries. + self.library_re = re.compile(r'^lib([^/]+)\.(a|dylib)$') + + def _Settings(self): + assert self.configname + return self.xcode_settings[self.configname] + + def _Test(self, test_key, cond_key, default): + return self._Settings().get(test_key, default) == cond_key + + def _Appendf(self, lst, test_key, format_str, default=None): + if test_key in self._Settings(): + lst.append(format_str % str(self._Settings()[test_key])) + elif default: + lst.append(format_str % str(default)) + + def _WarnUnimplemented(self, test_key): + if test_key in self._Settings(): + print 'Warning: Ignoring not yet implemented key "%s".' % test_key + + def _IsBundle(self): + return int(self.spec.get('mac_bundle', 0)) != 0 + + def GetFrameworkVersion(self): + """Returns the framework version of the current target. Only valid for + bundles.""" + assert self._IsBundle() + return self.GetPerTargetSetting('FRAMEWORK_VERSION', default='A') + + def GetWrapperExtension(self): + """Returns the bundle extension (.app, .framework, .plugin, etc). Only + valid for bundles.""" + assert self._IsBundle() + if self.spec['type'] in ('loadable_module', 'shared_library'): + default_wrapper_extension = { + 'loadable_module': 'bundle', + 'shared_library': 'framework', + }[self.spec['type']] + wrapper_extension = self.GetPerTargetSetting( + 'WRAPPER_EXTENSION', default=default_wrapper_extension) + return '.' + self.spec.get('product_extension', wrapper_extension) + elif self.spec['type'] == 'executable': + return '.app' + else: + assert False, "Don't know extension for '%s', target '%s'" % ( + self.spec['type'], self.spec['target_name']) + + def GetProductName(self): + """Returns PRODUCT_NAME.""" + return self.spec.get('product_name', self.spec['target_name']) + + def GetFullProductName(self): + """Returns FULL_PRODUCT_NAME.""" + if self._IsBundle(): + return self.GetWrapperName() + else: + return self._GetStandaloneBinaryPath() + + def GetWrapperName(self): + """Returns the directory name of the bundle represented by this target. + Only valid for bundles.""" + assert self._IsBundle() + return self.GetProductName() + self.GetWrapperExtension() + + def GetBundleContentsFolderPath(self): + """Returns the qualified path to the bundle's contents folder. E.g. + Chromium.app/Contents or Foo.bundle/Versions/A. Only valid for bundles.""" + assert self._IsBundle() + if self.spec['type'] == 'shared_library': + return os.path.join( + self.GetWrapperName(), 'Versions', self.GetFrameworkVersion()) + else: + # loadable_modules have a 'Contents' folder like executables. + return os.path.join(self.GetWrapperName(), 'Contents') + + def GetBundleResourceFolder(self): + """Returns the qualified path to the bundle's resource folder. E.g. + Chromium.app/Contents/Resources. Only valid for bundles.""" + assert self._IsBundle() + return os.path.join(self.GetBundleContentsFolderPath(), 'Resources') + + def GetBundlePlistPath(self): + """Returns the qualified path to the bundle's plist file. E.g. + Chromium.app/Contents/Info.plist. Only valid for bundles.""" + assert self._IsBundle() + if self.spec['type'] in ('executable', 'loadable_module'): + return os.path.join(self.GetBundleContentsFolderPath(), 'Info.plist') + else: + return os.path.join(self.GetBundleContentsFolderPath(), + 'Resources', 'Info.plist') + + def GetProductType(self): + """Returns the PRODUCT_TYPE of this target.""" + if self._IsBundle(): + return { + 'executable': 'com.apple.product-type.application', + 'loadable_module': 'com.apple.product-type.bundle', + 'shared_library': 'com.apple.product-type.framework', + }[self.spec['type']] + else: + return { + 'executable': 'com.apple.product-type.tool', + 'loadable_module': 'com.apple.product-type.library.dynamic', + 'shared_library': 'com.apple.product-type.library.dynamic', + 'static_library': 'com.apple.product-type.library.static', + }[self.spec['type']] + + def GetMachOType(self): + """Returns the MACH_O_TYPE of this target.""" + # Weird, but matches Xcode. + if not self._IsBundle() and self.spec['type'] == 'executable': + return '' + return { + 'executable': 'mh_execute', + 'static_library': 'staticlib', + 'shared_library': 'mh_dylib', + 'loadable_module': 'mh_bundle', + }[self.spec['type']] + + def _GetBundleBinaryPath(self): + """Returns the name of the bundle binary of by this target. + E.g. Chromium.app/Contents/MacOS/Chromium. Only valid for bundles.""" + assert self._IsBundle() + if self.spec['type'] in ('shared_library'): + path = self.GetBundleContentsFolderPath() + elif self.spec['type'] in ('executable', 'loadable_module'): + path = os.path.join(self.GetBundleContentsFolderPath(), 'MacOS') + return os.path.join(path, self.GetExecutableName()) + + def _GetStandaloneExecutableSuffix(self): + if 'product_extension' in self.spec: + return '.' + self.spec['product_extension'] + return { + 'executable': '', + 'static_library': '.a', + 'shared_library': '.dylib', + 'loadable_module': '.so', + }[self.spec['type']] + + def _GetStandaloneExecutablePrefix(self): + return self.spec.get('product_prefix', { + 'executable': '', + 'static_library': 'lib', + 'shared_library': 'lib', + # Non-bundled loadable_modules are called foo.so for some reason + # (that is, .so and no prefix) with the xcode build -- match that. + 'loadable_module': '', + }[self.spec['type']]) + + def _GetStandaloneBinaryPath(self): + """Returns the name of the non-bundle binary represented by this target. + E.g. hello_world. Only valid for non-bundles.""" + assert not self._IsBundle() + assert self.spec['type'] in ( + 'executable', 'shared_library', 'static_library', 'loadable_module'), ( + 'Unexpected type %s' % self.spec['type']) + target = self.spec['target_name'] + if self.spec['type'] == 'static_library': + if target[:3] == 'lib': + target = target[3:] + elif self.spec['type'] in ('loadable_module', 'shared_library'): + if target[:3] == 'lib': + target = target[3:] + + target_prefix = self._GetStandaloneExecutablePrefix() + target = self.spec.get('product_name', target) + target_ext = self._GetStandaloneExecutableSuffix() + return target_prefix + target + target_ext + + def GetExecutableName(self): + """Returns the executable name of the bundle represented by this target. + E.g. Chromium.""" + if self._IsBundle(): + return self.spec.get('product_name', self.spec['target_name']) + else: + return self._GetStandaloneBinaryPath() + + def GetExecutablePath(self): + """Returns the directory name of the bundle represented by this target. E.g. + Chromium.app/Contents/MacOS/Chromium.""" + if self._IsBundle(): + return self._GetBundleBinaryPath() + else: + return self._GetStandaloneBinaryPath() + + def _GetSdkBaseDir(self): + """Returns the root of the 'Developer' directory. On Xcode 4.2 and prior, + this is usually just /Developer. Xcode 4.3 moved that folder into the Xcode + bundle.""" + if not XcodeSettings._sdk_base_dir: + import subprocess + job = subprocess.Popen(['xcode-select', '-print-path'], + stdout=subprocess.PIPE, + stderr=subprocess.STDOUT) + out, err = job.communicate() + if job.returncode != 0: + print out + raise Exception('Error %d running xcode-select' % job.returncode) + # The Developer folder moved in Xcode 4.3. + xcode43_sdk_path = os.path.join( + out.rstrip(), 'Platforms/MacOSX.platform/Developer/SDKs') + if os.path.isdir(xcode43_sdk_path): + XcodeSettings._sdk_base_dir = xcode43_sdk_path + else: + XcodeSettings._sdk_base_dir = os.path.join(out.rstrip(), 'SDKs') + return XcodeSettings._sdk_base_dir + + def _SdkPath(self): + sdk_root = self.GetPerTargetSetting('SDKROOT', default='macosx10.5') + if sdk_root.startswith('macosx'): + return os.path.join(self._GetSdkBaseDir(), + 'MacOSX' + sdk_root[len('macosx'):] + '.sdk') + return sdk_root + + def GetCflags(self, configname): + """Returns flags that need to be added to .c, .cc, .m, and .mm + compilations.""" + # This functions (and the similar ones below) do not offer complete + # emulation of all xcode_settings keys. They're implemented on demand. + + self.configname = configname + cflags = [] + + sdk_root = self._SdkPath() + if 'SDKROOT' in self._Settings(): + cflags.append('-isysroot %s' % sdk_root) + + if self._Test('GCC_CHAR_IS_UNSIGNED_CHAR', 'YES', default='NO'): + cflags.append('-funsigned-char') + + if self._Test('GCC_CW_ASM_SYNTAX', 'YES', default='YES'): + cflags.append('-fasm-blocks') + + if 'GCC_DYNAMIC_NO_PIC' in self._Settings(): + if self._Settings()['GCC_DYNAMIC_NO_PIC'] == 'YES': + cflags.append('-mdynamic-no-pic') + else: + pass + # TODO: In this case, it depends on the target. xcode passes + # mdynamic-no-pic by default for executable and possibly static lib + # according to mento + + if self._Test('GCC_ENABLE_PASCAL_STRINGS', 'YES', default='YES'): + cflags.append('-mpascal-strings') + + self._Appendf(cflags, 'GCC_OPTIMIZATION_LEVEL', '-O%s', default='s') + + if self._Test('GCC_GENERATE_DEBUGGING_SYMBOLS', 'YES', default='YES'): + dbg_format = self._Settings().get('DEBUG_INFORMATION_FORMAT', 'dwarf') + if dbg_format == 'dwarf': + cflags.append('-gdwarf-2') + elif dbg_format == 'stabs': + raise NotImplementedError('stabs debug format is not supported yet.') + elif dbg_format == 'dwarf-with-dsym': + cflags.append('-gdwarf-2') + else: + raise NotImplementedError('Unknown debug format %s' % dbg_format) + + if self._Test('GCC_SYMBOLS_PRIVATE_EXTERN', 'YES', default='NO'): + cflags.append('-fvisibility=hidden') + + if self._Test('GCC_TREAT_WARNINGS_AS_ERRORS', 'YES', default='NO'): + cflags.append('-Werror') + + if self._Test('GCC_WARN_ABOUT_MISSING_NEWLINE', 'YES', default='NO'): + cflags.append('-Wnewline-eof') + + self._Appendf(cflags, 'MACOSX_DEPLOYMENT_TARGET', '-mmacosx-version-min=%s') + + # TODO: + if self._Test('COPY_PHASE_STRIP', 'YES', default='NO'): + self._WarnUnimplemented('COPY_PHASE_STRIP') + self._WarnUnimplemented('GCC_DEBUGGING_SYMBOLS') + self._WarnUnimplemented('GCC_ENABLE_OBJC_EXCEPTIONS') + + # TODO: This is exported correctly, but assigning to it is not supported. + self._WarnUnimplemented('MACH_O_TYPE') + self._WarnUnimplemented('PRODUCT_TYPE') + + archs = self._Settings().get('ARCHS', ['i386']) + if len(archs) != 1: + # TODO: Supporting fat binaries will be annoying. + self._WarnUnimplemented('ARCHS') + archs = ['i386'] + cflags.append('-arch ' + archs[0]) + + if archs[0] in ('i386', 'x86_64'): + if self._Test('GCC_ENABLE_SSE3_EXTENSIONS', 'YES', default='NO'): + cflags.append('-msse3') + if self._Test('GCC_ENABLE_SUPPLEMENTAL_SSE3_INSTRUCTIONS', 'YES', + default='NO'): + cflags.append('-mssse3') # Note 3rd 's'. + if self._Test('GCC_ENABLE_SSE41_EXTENSIONS', 'YES', default='NO'): + cflags.append('-msse4.1') + if self._Test('GCC_ENABLE_SSE42_EXTENSIONS', 'YES', default='NO'): + cflags.append('-msse4.2') + + cflags += self._Settings().get('WARNING_CFLAGS', []) + + config = self.spec['configurations'][self.configname] + framework_dirs = config.get('mac_framework_dirs', []) + for directory in framework_dirs: + cflags.append('-F' + directory.replace('$(SDKROOT)', sdk_root)) + + self.configname = None + return cflags + + def GetCflagsC(self, configname): + """Returns flags that need to be added to .c, and .m compilations.""" + self.configname = configname + cflags_c = [] + self._Appendf(cflags_c, 'GCC_C_LANGUAGE_STANDARD', '-std=%s') + cflags_c += self._Settings().get('OTHER_CFLAGS', []) + self.configname = None + return cflags_c + + def GetCflagsCC(self, configname): + """Returns flags that need to be added to .cc, and .mm compilations.""" + self.configname = configname + cflags_cc = [] + if self._Test('GCC_ENABLE_CPP_RTTI', 'NO', default='YES'): + cflags_cc.append('-fno-rtti') + if self._Test('GCC_ENABLE_CPP_EXCEPTIONS', 'NO', default='YES'): + cflags_cc.append('-fno-exceptions') + if self._Test('GCC_INLINES_ARE_PRIVATE_EXTERN', 'YES', default='NO'): + cflags_cc.append('-fvisibility-inlines-hidden') + if self._Test('GCC_THREADSAFE_STATICS', 'NO', default='YES'): + cflags_cc.append('-fno-threadsafe-statics') + if self._Test('GCC_WARN_ABOUT_INVALID_OFFSETOF_MACRO', 'NO', default='YES'): + cflags_cc.append('-Wno-invalid-offsetof') + + other_ccflags = [] + + for flag in self._Settings().get('OTHER_CPLUSPLUSFLAGS', ['$(inherited)']): + # TODO: More general variable expansion. Missing in many other places too. + if flag in ('$inherited', '$(inherited)', '${inherited}'): + flag = '$OTHER_CFLAGS' + if flag in ('$OTHER_CFLAGS', '$(OTHER_CFLAGS)', '${OTHER_CFLAGS}'): + other_ccflags += self._Settings().get('OTHER_CFLAGS', []) + else: + other_ccflags.append(flag) + cflags_cc += other_ccflags + + self.configname = None + return cflags_cc + + def _AddObjectiveCGarbageCollectionFlags(self, flags): + gc_policy = self._Settings().get('GCC_ENABLE_OBJC_GC', 'unsupported') + if gc_policy == 'supported': + flags.append('-fobjc-gc') + elif gc_policy == 'required': + flags.append('-fobjc-gc-only') + + def GetCflagsObjC(self, configname): + """Returns flags that need to be added to .m compilations.""" + self.configname = configname + cflags_objc = [] + + self._AddObjectiveCGarbageCollectionFlags(cflags_objc) + + self.configname = None + return cflags_objc + + def GetCflagsObjCC(self, configname): + """Returns flags that need to be added to .mm compilations.""" + self.configname = configname + cflags_objcc = [] + self._AddObjectiveCGarbageCollectionFlags(cflags_objcc) + if self._Test('GCC_OBJC_CALL_CXX_CDTORS', 'YES', default='NO'): + cflags_objcc.append('-fobjc-call-cxx-cdtors') + self.configname = None + return cflags_objcc + + def GetInstallNameBase(self): + """Return DYLIB_INSTALL_NAME_BASE for this target.""" + # Xcode sets this for shared_libraries, and for nonbundled loadable_modules. + if (self.spec['type'] != 'shared_library' and + (self.spec['type'] != 'loadable_module' or self._IsBundle())): + return None + install_base = self.GetPerTargetSetting( + 'DYLIB_INSTALL_NAME_BASE', + default='/Library/Frameworks' if self._IsBundle() else '/usr/local/lib') + return install_base + + def _StandardizePath(self, path): + """Do :standardizepath processing for path.""" + # I'm not quite sure what :standardizepath does. Just call normpath(), + # but don't let @executable_path/../foo collapse to foo. + if '/' in path: + prefix, rest = '', path + if path.startswith('@'): + prefix, rest = path.split('/', 1) + rest = os.path.normpath(rest) # :standardizepath + path = os.path.join(prefix, rest) + return path + + def GetInstallName(self): + """Return LD_DYLIB_INSTALL_NAME for this target.""" + # Xcode sets this for shared_libraries, and for nonbundled loadable_modules. + if (self.spec['type'] != 'shared_library' and + (self.spec['type'] != 'loadable_module' or self._IsBundle())): + return None + + default_install_name = \ + '$(DYLIB_INSTALL_NAME_BASE:standardizepath)/$(EXECUTABLE_PATH)' + install_name = self.GetPerTargetSetting( + 'LD_DYLIB_INSTALL_NAME', default=default_install_name) + + # Hardcode support for the variables used in chromium for now, to + # unblock people using the make build. + if '$' in install_name: + assert install_name in ('$(DYLIB_INSTALL_NAME_BASE:standardizepath)/' + '$(WRAPPER_NAME)/$(PRODUCT_NAME)', default_install_name), ( + 'Variables in LD_DYLIB_INSTALL_NAME are not generally supported ' + 'yet in target \'%s\' (got \'%s\')' % + (self.spec['target_name'], install_name)) + + install_name = install_name.replace( + '$(DYLIB_INSTALL_NAME_BASE:standardizepath)', + self._StandardizePath(self.GetInstallNameBase())) + if self._IsBundle(): + # These are only valid for bundles, hence the |if|. + install_name = install_name.replace( + '$(WRAPPER_NAME)', self.GetWrapperName()) + install_name = install_name.replace( + '$(PRODUCT_NAME)', self.GetProductName()) + else: + assert '$(WRAPPER_NAME)' not in install_name + assert '$(PRODUCT_NAME)' not in install_name + + install_name = install_name.replace( + '$(EXECUTABLE_PATH)', self.GetExecutablePath()) + return install_name + + def _MapLinkerFlagFilename(self, ldflag, gyp_to_build_path): + """Checks if ldflag contains a filename and if so remaps it from + gyp-directory-relative to build-directory-relative.""" + # This list is expanded on demand. + # They get matched as: + # -exported_symbols_list file + # -Wl,exported_symbols_list file + # -Wl,exported_symbols_list,file + LINKER_FILE = '(\S+)' + WORD = '\S+' + linker_flags = [ + ['-exported_symbols_list', LINKER_FILE], # Needed for NaCl. + ['-unexported_symbols_list', LINKER_FILE], + ['-reexported_symbols_list', LINKER_FILE], + ['-sectcreate', WORD, WORD, LINKER_FILE], # Needed for remoting. + ] + for flag_pattern in linker_flags: + regex = re.compile('(?:-Wl,)?' + '[ ,]'.join(flag_pattern)) + m = regex.match(ldflag) + if m: + ldflag = ldflag[:m.start(1)] + gyp_to_build_path(m.group(1)) + \ + ldflag[m.end(1):] + # Required for ffmpeg (no idea why they don't use LIBRARY_SEARCH_PATHS, + # TODO(thakis): Update ffmpeg.gyp): + if ldflag.startswith('-L'): + ldflag = '-L' + gyp_to_build_path(ldflag[len('-L'):]) + return ldflag + + def GetLdflags(self, configname, product_dir, gyp_to_build_path): + """Returns flags that need to be passed to the linker. + + Args: + configname: The name of the configuration to get ld flags for. + product_dir: The directory where products such static and dynamic + libraries are placed. This is added to the library search path. + gyp_to_build_path: A function that converts paths relative to the + current gyp file to paths relative to the build direcotry. + """ + self.configname = configname + ldflags = [] + + # The xcode build is relative to a gyp file's directory, and OTHER_LDFLAGS + # can contain entries that depend on this. Explicitly absolutify these. + for ldflag in self._Settings().get('OTHER_LDFLAGS', []): + ldflags.append(self._MapLinkerFlagFilename(ldflag, gyp_to_build_path)) + + if self._Test('DEAD_CODE_STRIPPING', 'YES', default='NO'): + ldflags.append('-Wl,-dead_strip') + + if self._Test('PREBINDING', 'YES', default='NO'): + ldflags.append('-Wl,-prebind') + + self._Appendf( + ldflags, 'DYLIB_COMPATIBILITY_VERSION', '-compatibility_version %s') + self._Appendf( + ldflags, 'DYLIB_CURRENT_VERSION', '-current_version %s') + self._Appendf( + ldflags, 'MACOSX_DEPLOYMENT_TARGET', '-mmacosx-version-min=%s') + if 'SDKROOT' in self._Settings(): + ldflags.append('-isysroot ' + self._SdkPath()) + + for library_path in self._Settings().get('LIBRARY_SEARCH_PATHS', []): + ldflags.append('-L' + gyp_to_build_path(library_path)) + + if 'ORDER_FILE' in self._Settings(): + ldflags.append('-Wl,-order_file ' + + '-Wl,' + gyp_to_build_path( + self._Settings()['ORDER_FILE'])) + + archs = self._Settings().get('ARCHS', ['i386']) + if len(archs) != 1: + # TODO: Supporting fat binaries will be annoying. + self._WarnUnimplemented('ARCHS') + archs = ['i386'] + ldflags.append('-arch ' + archs[0]) + + # Xcode adds the product directory by default. + ldflags.append('-L' + product_dir) + + install_name = self.GetInstallName() + if install_name: + ldflags.append('-install_name ' + install_name.replace(' ', r'\ ')) + + for rpath in self._Settings().get('LD_RUNPATH_SEARCH_PATHS', []): + ldflags.append('-Wl,-rpath,' + rpath) + + config = self.spec['configurations'][self.configname] + framework_dirs = config.get('mac_framework_dirs', []) + for directory in framework_dirs: + ldflags.append('-F' + directory.replace('$(SDKROOT)', self._SdkPath())) + + self.configname = None + return ldflags + + def GetPerTargetSettings(self): + """Gets a list of all the per-target settings. This will only fetch keys + whose values are the same across all configurations.""" + first_pass = True + result = {} + for configname in sorted(self.xcode_settings.keys()): + if first_pass: + result = dict(self.xcode_settings[configname]) + first_pass = False + else: + for key, value in self.xcode_settings[configname].iteritems(): + if key not in result: + continue + elif result[key] != value: + del result[key] + return result + + def GetPerTargetSetting(self, setting, default=None): + """Tries to get xcode_settings.setting from spec. Assumes that the setting + has the same value in all configurations and throws otherwise.""" + first_pass = True + result = None + for configname in sorted(self.xcode_settings.keys()): + if first_pass: + result = self.xcode_settings[configname].get(setting, None) + first_pass = False + else: + assert result == self.xcode_settings[configname].get(setting, None), ( + "Expected per-target setting for '%s', got per-config setting " + "(target %s)" % (setting, spec['target_name'])) + if result is None: + return default + return result + + def _GetStripPostbuilds(self, configname, output_binary, quiet): + """Returns a list of shell commands that contain the shell commands + neccessary to strip this target's binary. These should be run as postbuilds + before the actual postbuilds run.""" + self.configname = configname + + result = [] + if (self._Test('DEPLOYMENT_POSTPROCESSING', 'YES', default='NO') and + self._Test('STRIP_INSTALLED_PRODUCT', 'YES', default='NO')): + + default_strip_style = 'debugging' + if self._IsBundle(): + default_strip_style = 'non-global' + elif self.spec['type'] == 'executable': + default_strip_style = 'all' + + strip_style = self._Settings().get('STRIP_STYLE', default_strip_style) + strip_flags = { + 'all': '', + 'non-global': '-x', + 'debugging': '-S', + }[strip_style] + + explicit_strip_flags = self._Settings().get('STRIPFLAGS', '') + if explicit_strip_flags: + strip_flags += ' ' + _NormalizeEnvVarReferences(explicit_strip_flags) + + if not quiet: + result.append('echo STRIP\\(%s\\)' % self.spec['target_name']) + result.append('strip %s %s' % (strip_flags, output_binary)) + + self.configname = None + return result + + def _GetDebugInfoPostbuilds(self, configname, output, output_binary, quiet): + """Returns a list of shell commands that contain the shell commands + neccessary to massage this target's debug information. These should be run + as postbuilds before the actual postbuilds run.""" + self.configname = configname + + # For static libraries, no dSYMs are created. + result = [] + if (self._Test('GCC_GENERATE_DEBUGGING_SYMBOLS', 'YES', default='YES') and + self._Test( + 'DEBUG_INFORMATION_FORMAT', 'dwarf-with-dsym', default='dwarf') and + self.spec['type'] != 'static_library'): + if not quiet: + result.append('echo DSYMUTIL\\(%s\\)' % self.spec['target_name']) + result.append('dsymutil %s -o %s' % (output_binary, output + '.dSYM')) + + self.configname = None + return result + + def GetTargetPostbuilds(self, configname, output, output_binary, quiet=False): + """Returns a list of shell commands that contain the shell commands + to run as postbuilds for this target, before the actual postbuilds.""" + # dSYMs need to build before stripping happens. + return ( + self._GetDebugInfoPostbuilds(configname, output, output_binary, quiet) + + self._GetStripPostbuilds(configname, output_binary, quiet)) + + def _AdjustLibrary(self, library): + if library.endswith('.framework'): + l = '-framework ' + os.path.splitext(os.path.basename(library))[0] + else: + m = self.library_re.match(library) + if m: + l = '-l' + m.group(1) + else: + l = library + return l.replace('$(SDKROOT)', self._SdkPath()) + + def AdjustLibraries(self, libraries): + """Transforms entries like 'Cocoa.framework' in libraries into entries like + '-framework Cocoa', 'libcrypto.dylib' into '-lcrypto', etc. + """ + libraries = [ self._AdjustLibrary(library) for library in libraries] + return libraries + + +class MacPrefixHeader(object): + """A class that helps with emulating Xcode's GCC_PREFIX_HEADER feature. + + This feature consists of several pieces: + * If GCC_PREFIX_HEADER is present, all compilations in that project get an + additional |-include path_to_prefix_header| cflag. + * If GCC_PRECOMPILE_PREFIX_HEADER is present too, then the prefix header is + instead compiled, and all other compilations in the project get an + additional |-include path_to_compiled_header| instead. + + Compiled prefix headers have the extension gch. There is one gch file for + every language used in the project (c, cc, m, mm), since gch files for + different languages aren't compatible. + + gch files themselves are built with the target's normal cflags, but they + obviously don't get the |-include| flag. Instead, they need a -x flag that + describes their language. + + All o files in the target need to depend on the gch file, to make sure + it's built before any o file is built. + + This class helps with some of these tasks, but it needs help from the build + system for writing dependencies to the gch files, for writing build commands + for the gch files, and for figuring out the location of the gch files. + """ + def __init__(self, xcode_settings, + gyp_path_to_build_path, gyp_path_to_build_output): + """If xcode_settings is None, all methods on this class are no-ops. + + Args: + gyp_path_to_build_path: A function that takes a gyp-relative path, + and returns a path relative to the build directory. + gyp_path_to_build_output: A function that takes a gyp-relative path and + a language code ('c', 'cc', 'm', or 'mm'), and that returns a path + to where the output of precompiling that path for that language + should be placed (without the trailing '.gch'). + """ + # This doesn't support per-configuration prefix headers. Good enough + # for now. + self.header = None + self.compile_headers = False + if xcode_settings: + self.header = xcode_settings.GetPerTargetSetting('GCC_PREFIX_HEADER') + self.compile_headers = xcode_settings.GetPerTargetSetting( + 'GCC_PRECOMPILE_PREFIX_HEADER', default='NO') != 'NO' + self.compiled_headers = {} + if self.header: + if self.compile_headers: + for lang in ['c', 'cc', 'm', 'mm']: + self.compiled_headers[lang] = gyp_path_to_build_output( + self.header, lang) + self.header = gyp_path_to_build_path(self.header) + + def GetInclude(self, lang): + """Gets the cflags to include the prefix header for language |lang|.""" + if self.compile_headers and lang in self.compiled_headers: + return '-include %s' % self.compiled_headers[lang] + elif self.header: + return '-include %s' % self.header + else: + return '' + + def _Gch(self, lang): + """Returns the actual file name of the prefix header for language |lang|.""" + assert self.compile_headers + return self.compiled_headers[lang] + '.gch' + + def GetObjDependencies(self, sources, objs): + """Given a list of source files and the corresponding object files, returns + a list of (source, object, gch) tuples, where |gch| is the build-directory + relative path to the gch file each object file depends on. |compilable[i]| + has to be the source file belonging to |objs[i]|.""" + if not self.header or not self.compile_headers: + return [] + + result = [] + for source, obj in zip(sources, objs): + ext = os.path.splitext(source)[1] + lang = { + '.c': 'c', + '.cpp': 'cc', '.cc': 'cc', '.cxx': 'cc', + '.m': 'm', + '.mm': 'mm', + }.get(ext, None) + if lang: + result.append((source, obj, self._Gch(lang))) + return result + + def GetPchBuildCommands(self): + """Returns [(path_to_gch, language_flag, language, header)]. + |path_to_gch| and |header| are relative to the build directory. + """ + if not self.header or not self.compile_headers: + return [] + return [ + (self._Gch('c'), '-x c-header', 'c', self.header), + (self._Gch('cc'), '-x c++-header', 'cc', self.header), + (self._Gch('m'), '-x objective-c-header', 'm', self.header), + (self._Gch('mm'), '-x objective-c++-header', 'mm', self.header), + ] + + +def MergeGlobalXcodeSettingsToSpec(global_dict, spec): + """Merges the global xcode_settings dictionary into each configuration of the + target represented by spec. For keys that are both in the global and the local + xcode_settings dict, the local key gets precendence. + """ + # The xcode generator special-cases global xcode_settings and does something + # that amounts to merging in the global xcode_settings into each local + # xcode_settings dict. + global_xcode_settings = global_dict.get('xcode_settings', {}) + for config in spec['configurations'].values(): + if 'xcode_settings' in config: + new_settings = global_xcode_settings.copy() + new_settings.update(config['xcode_settings']) + config['xcode_settings'] = new_settings + + +def IsMacBundle(flavor, spec): + """Returns if |spec| should be treated as a bundle. + + Bundles are directories with a certain subdirectory structure, instead of + just a single file. Bundle rules do not produce a binary but also package + resources into that directory.""" + is_mac_bundle = (int(spec.get('mac_bundle', 0)) != 0 and flavor == 'mac') + if is_mac_bundle: + assert spec['type'] != 'none', ( + 'mac_bundle targets cannot have type none (target "%s")' % + spec['target_name']) + return is_mac_bundle + + +def GetMacBundleResources(product_dir, xcode_settings, resources): + """Yields (output, resource) pairs for every resource in |resources|. + Only call this for mac bundle targets. + + Args: + product_dir: Path to the directory containing the output bundle, + relative to the build directory. + xcode_settings: The XcodeSettings of the current target. + resources: A list of bundle resources, relative to the build directory. + """ + dest = os.path.join(product_dir, + xcode_settings.GetBundleResourceFolder()) + for res in resources: + output = dest + + # The make generator doesn't support it, so forbid it everywhere + # to keep the generators more interchangable. + assert ' ' not in res, ( + "Spaces in resource filenames not supported (%s)" % res) + + # Split into (path,file). + res_parts = os.path.split(res) + + # Now split the path into (prefix,maybe.lproj). + lproj_parts = os.path.split(res_parts[0]) + # If the resource lives in a .lproj bundle, add that to the destination. + if lproj_parts[1].endswith('.lproj'): + output = os.path.join(output, lproj_parts[1]) + + output = os.path.join(output, res_parts[1]) + # Compiled XIB files are referred to by .nib. + if output.endswith('.xib'): + output = output[0:-3] + 'nib' + + yield output, res + + +def GetMacInfoPlist(product_dir, xcode_settings, gyp_path_to_build_path): + """Returns (info_plist, dest_plist, defines, extra_env), where: + * |info_plist| is the sourc plist path, relative to the + build directory, + * |dest_plist| is the destination plist path, relative to the + build directory, + * |defines| is a list of preprocessor defines (empty if the plist + shouldn't be preprocessed, + * |extra_env| is a dict of env variables that should be exported when + invoking |mac_tool copy-info-plist|. + + Only call this for mac bundle targets. + + Args: + product_dir: Path to the directory containing the output bundle, + relative to the build directory. + xcode_settings: The XcodeSettings of the current target. + gyp_to_build_path: A function that converts paths relative to the + current gyp file to paths relative to the build direcotry. + """ + info_plist = xcode_settings.GetPerTargetSetting('INFOPLIST_FILE') + if not info_plist: + return None, None, [], {} + + # The make generator doesn't support it, so forbid it everywhere + # to keep the generators more interchangable. + assert ' ' not in info_plist, ( + "Spaces in Info.plist filenames not supported (%s)" % info_plist) + + info_plist = gyp_path_to_build_path(info_plist) + + # If explicitly set to preprocess the plist, invoke the C preprocessor and + # specify any defines as -D flags. + if xcode_settings.GetPerTargetSetting( + 'INFOPLIST_PREPROCESS', default='NO') == 'YES': + # Create an intermediate file based on the path. + defines = shlex.split(xcode_settings.GetPerTargetSetting( + 'INFOPLIST_PREPROCESSOR_DEFINITIONS', default='')) + else: + defines = [] + + dest_plist = os.path.join(product_dir, xcode_settings.GetBundlePlistPath()) + extra_env = xcode_settings.GetPerTargetSettings() + + return info_plist, dest_plist, defines, extra_env + + +def _GetXcodeEnv(xcode_settings, built_products_dir, srcroot, configuration, + additional_settings=None): + """Return the environment variables that Xcode would set. See + http://developer.apple.com/library/mac/#documentation/DeveloperTools/Reference/XcodeBuildSettingRef/1-Build_Setting_Reference/build_setting_ref.html#//apple_ref/doc/uid/TP40003931-CH3-SW153 + for a full list. + + Args: + xcode_settings: An XcodeSettings object. If this is None, this function + returns an empty dict. + built_products_dir: Absolute path to the built products dir. + srcroot: Absolute path to the source root. + configuration: The build configuration name. + additional_settings: An optional dict with more values to add to the + result. + """ + if not xcode_settings: return {} + + # This function is considered a friend of XcodeSettings, so let it reach into + # its implementation details. + spec = xcode_settings.spec + + # These are filled in on a as-needed basis. + env = { + 'BUILT_PRODUCTS_DIR' : built_products_dir, + 'CONFIGURATION' : configuration, + 'PRODUCT_NAME' : xcode_settings.GetProductName(), + # See /Developer/Platforms/MacOSX.platform/Developer/Library/Xcode/Specifications/MacOSX\ Product\ Types.xcspec for FULL_PRODUCT_NAME + 'SRCROOT' : srcroot, + 'SOURCE_ROOT': '${SRCROOT}', + # This is not true for static libraries, but currently the env is only + # written for bundles: + 'TARGET_BUILD_DIR' : built_products_dir, + 'TEMP_DIR' : '${TMPDIR}', + } + if spec['type'] in ( + 'executable', 'static_library', 'shared_library', 'loadable_module'): + env['EXECUTABLE_NAME'] = xcode_settings.GetExecutableName() + env['EXECUTABLE_PATH'] = xcode_settings.GetExecutablePath() + env['FULL_PRODUCT_NAME'] = xcode_settings.GetFullProductName() + mach_o_type = xcode_settings.GetMachOType() + if mach_o_type: + env['MACH_O_TYPE'] = mach_o_type + env['PRODUCT_TYPE'] = xcode_settings.GetProductType() + if xcode_settings._IsBundle(): + env['CONTENTS_FOLDER_PATH'] = \ + xcode_settings.GetBundleContentsFolderPath() + env['UNLOCALIZED_RESOURCES_FOLDER_PATH'] = \ + xcode_settings.GetBundleResourceFolder() + env['INFOPLIST_PATH'] = xcode_settings.GetBundlePlistPath() + env['WRAPPER_NAME'] = xcode_settings.GetWrapperName() + + install_name = xcode_settings.GetInstallName() + if install_name: + env['LD_DYLIB_INSTALL_NAME'] = install_name + install_name_base = xcode_settings.GetInstallNameBase() + if install_name_base: + env['DYLIB_INSTALL_NAME_BASE'] = install_name_base + + if not additional_settings: + additional_settings = {} + else: + # Flatten lists to strings. + for k in additional_settings: + if not isinstance(additional_settings[k], str): + additional_settings[k] = ' '.join(additional_settings[k]) + additional_settings.update(env) + + for k in additional_settings: + additional_settings[k] = _NormalizeEnvVarReferences(additional_settings[k]) + + return additional_settings + + +def _NormalizeEnvVarReferences(str): + """Takes a string containing variable references in the form ${FOO}, $(FOO), + or $FOO, and returns a string with all variable references in the form ${FOO}. + """ + # $FOO -> ${FOO} + str = re.sub(r'\$([a-zA-Z_][a-zA-Z0-9_]*)', r'${\1}', str) + + # $(FOO) -> ${FOO} + matches = re.findall(r'(\$\(([a-zA-Z0-9\-_]+)\))', str) + for match in matches: + to_replace, variable = match + assert '$(' not in match, '$($(FOO)) variables not supported: ' + match + str = str.replace(to_replace, '${' + variable + '}') + + return str + + +def ExpandEnvVars(string, expansions): + """Expands ${VARIABLES}, $(VARIABLES), and $VARIABLES in string per the + expansions list. If the variable expands to something that references + another variable, this variable is expanded as well if it's in env -- + until no variables present in env are left.""" + for k, v in reversed(expansions): + string = string.replace('${' + k + '}', v) + string = string.replace('$(' + k + ')', v) + string = string.replace('$' + k, v) + return string + + +def _TopologicallySortedEnvVarKeys(env): + """Takes a dict |env| whose values are strings that can refer to other keys, + for example env['foo'] = '$(bar) and $(baz)'. Returns a list L of all keys of + env such that key2 is after key1 in L if env[key2] refers to env[key1]. + + Throws an Exception in case of dependency cycles. + """ + # Since environment variables can refer to other variables, the evaluation + # order is important. Below is the logic to compute the dependency graph + # and sort it. + regex = re.compile(r'\$\{([a-zA-Z0-9\-_]+)\}') + def GetEdges(node): + # Use a definition of edges such that user_of_variable -> used_varible. + # This happens to be easier in this case, since a variable's + # definition contains all variables it references in a single string. + # We can then reverse the result of the topological sort at the end. + # Since: reverse(topsort(DAG)) = topsort(reverse_edges(DAG)) + matches = set([v for v in regex.findall(env[node]) if v in env]) + for dependee in matches: + assert '${' not in dependee, 'Nested variables not supported: ' + dependee + return matches + + try: + # Topologically sort, and then reverse, because we used an edge definition + # that's inverted from the expected result of this function (see comment + # above). + order = gyp.common.TopologicallySorted(env.keys(), GetEdges) + order.reverse() + return order + except gyp.common.CycleError, e: + raise Exception( + 'Xcode environment variables are cyclically dependent: ' + str(e.nodes)) + + +def GetSortedXcodeEnv(xcode_settings, built_products_dir, srcroot, + configuration, additional_settings=None): + env = _GetXcodeEnv(xcode_settings, built_products_dir, srcroot, configuration, + additional_settings) + return [(key, env[key]) for key in _TopologicallySortedEnvVarKeys(env)] + + +def GetSpecPostbuildCommands(spec, quiet=False): + """Returns the list of postbuilds explicitly defined on |spec|, in a form + executable by a shell.""" + postbuilds = [] + for postbuild in spec.get('postbuilds', []): + if not quiet: + postbuilds.append('echo POSTBUILD\\(%s\\) %s' % ( + spec['target_name'], postbuild['postbuild_name'])) + postbuilds.append(gyp.common.EncodePOSIXShellList(postbuild['action'])) + return postbuilds diff --git a/node-v0.8.14/tools/gyp/pylib/gyp/xcodeproj_file.py b/node-v0.8.14/tools/gyp/pylib/gyp/xcodeproj_file.py new file mode 100644 index 0000000..5124ed0 --- /dev/null +++ b/node-v0.8.14/tools/gyp/pylib/gyp/xcodeproj_file.py @@ -0,0 +1,2834 @@ +# Copyright (c) 2012 Google Inc. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +"""Xcode project file generator. + +This module is both an Xcode project file generator and a documentation of the +Xcode project file format. Knowledge of the project file format was gained +based on extensive experience with Xcode, and by making changes to projects in +Xcode.app and observing the resultant changes in the associated project files. + +XCODE PROJECT FILES + +The generator targets the file format as written by Xcode 3.2 (specifically, +3.2.6), but past experience has taught that the format has not changed +significantly in the past several years, and future versions of Xcode are able +to read older project files. + +Xcode project files are "bundled": the project "file" from an end-user's +perspective is actually a directory with an ".xcodeproj" extension. The +project file from this module's perspective is actually a file inside this +directory, always named "project.pbxproj". This file contains a complete +description of the project and is all that is needed to use the xcodeproj. +Other files contained in the xcodeproj directory are simply used to store +per-user settings, such as the state of various UI elements in the Xcode +application. + +The project.pbxproj file is a property list, stored in a format almost +identical to the NeXTstep property list format. The file is able to carry +Unicode data, and is encoded in UTF-8. The root element in the property list +is a dictionary that contains several properties of minimal interest, and two +properties of immense interest. The most important property is a dictionary +named "objects". The entire structure of the project is represented by the +children of this property. The objects dictionary is keyed by unique 96-bit +values represented by 24 uppercase hexadecimal characters. Each value in the +objects dictionary is itself a dictionary, describing an individual object. + +Each object in the dictionary is a member of a class, which is identified by +the "isa" property of each object. A variety of classes are represented in a +project file. Objects can refer to other objects by ID, using the 24-character +hexadecimal object key. A project's objects form a tree, with a root object +of class PBXProject at the root. As an example, the PBXProject object serves +as parent to an XCConfigurationList object defining the build configurations +used in the project, a PBXGroup object serving as a container for all files +referenced in the project, and a list of target objects, each of which defines +a target in the project. There are several different types of target object, +such as PBXNativeTarget and PBXAggregateTarget. In this module, this +relationship is expressed by having each target type derive from an abstract +base named XCTarget. + +The project.pbxproj file's root dictionary also contains a property, sibling to +the "objects" dictionary, named "rootObject". The value of rootObject is a +24-character object key referring to the root PBXProject object in the +objects dictionary. + +In Xcode, every file used as input to a target or produced as a final product +of a target must appear somewhere in the hierarchy rooted at the PBXGroup +object referenced by the PBXProject's mainGroup property. A PBXGroup is +generally represented as a folder in the Xcode application. PBXGroups can +contain other PBXGroups as well as PBXFileReferences, which are pointers to +actual files. + +Each XCTarget contains a list of build phases, represented in this module by +the abstract base XCBuildPhase. Examples of concrete XCBuildPhase derivations +are PBXSourcesBuildPhase and PBXFrameworksBuildPhase, which correspond to the +"Compile Sources" and "Link Binary With Libraries" phases displayed in the +Xcode application. Files used as input to these phases (for example, source +files in the former case and libraries and frameworks in the latter) are +represented by PBXBuildFile objects, referenced by elements of "files" lists +in XCTarget objects. Each PBXBuildFile object refers to a PBXBuildFile +object as a "weak" reference: it does not "own" the PBXBuildFile, which is +owned by the root object's mainGroup or a descendant group. In most cases, the +layer of indirection between an XCBuildPhase and a PBXFileReference via a +PBXBuildFile appears extraneous, but there's actually one reason for this: +file-specific compiler flags are added to the PBXBuildFile object so as to +allow a single file to be a member of multiple targets while having distinct +compiler flags for each. These flags can be modified in the Xcode applciation +in the "Build" tab of a File Info window. + +When a project is open in the Xcode application, Xcode will rewrite it. As +such, this module is careful to adhere to the formatting used by Xcode, to +avoid insignificant changes appearing in the file when it is used in the +Xcode application. This will keep version control repositories happy, and +makes it possible to compare a project file used in Xcode to one generated by +this module to determine if any significant changes were made in the +application. + +Xcode has its own way of assigning 24-character identifiers to each object, +which is not duplicated here. Because the identifier only is only generated +once, when an object is created, and is then left unchanged, there is no need +to attempt to duplicate Xcode's behavior in this area. The generator is free +to select any identifier, even at random, to refer to the objects it creates, +and Xcode will retain those identifiers and use them when subsequently +rewriting the project file. However, the generator would choose new random +identifiers each time the project files are generated, leading to difficulties +comparing "used" project files to "pristine" ones produced by this module, +and causing the appearance of changes as every object identifier is changed +when updated projects are checked in to a version control repository. To +mitigate this problem, this module chooses identifiers in a more deterministic +way, by hashing a description of each object as well as its parent and ancestor +objects. This strategy should result in minimal "shift" in IDs as successive +generations of project files are produced. + +THIS MODULE + +This module introduces several classes, all derived from the XCObject class. +Nearly all of the "brains" are built into the XCObject class, which understands +how to create and modify objects, maintain the proper tree structure, compute +identifiers, and print objects. For the most part, classes derived from +XCObject need only provide a _schema class object, a dictionary that +expresses what properties objects of the class may contain. + +Given this structure, it's possible to build a minimal project file by creating +objects of the appropriate types and making the proper connections: + + config_list = XCConfigurationList() + group = PBXGroup() + project = PBXProject({'buildConfigurationList': config_list, + 'mainGroup': group}) + +With the project object set up, it can be added to an XCProjectFile object. +XCProjectFile is a pseudo-class in the sense that it is a concrete XCObject +subclass that does not actually correspond to a class type found in a project +file. Rather, it is used to represent the project file's root dictionary. +Printing an XCProjectFile will print the entire project file, including the +full "objects" dictionary. + + project_file = XCProjectFile({'rootObject': project}) + project_file.ComputeIDs() + project_file.Print() + +Xcode project files are always encoded in UTF-8. This module will accept +strings of either the str class or the unicode class. Strings of class str +are assumed to already be encoded in UTF-8. Obviously, if you're just using +ASCII, you won't encounter difficulties because ASCII is a UTF-8 subset. +Strings of class unicode are handled properly and encoded in UTF-8 when +a project file is output. +""" + +import gyp.common +import posixpath +import re +import struct +import sys + +# hashlib is supplied as of Python 2.5 as the replacement interface for sha +# and other secure hashes. In 2.6, sha is deprecated. Import hashlib if +# available, avoiding a deprecation warning under 2.6. Import sha otherwise, +# preserving 2.4 compatibility. +try: + import hashlib + _new_sha1 = hashlib.sha1 +except ImportError: + import sha + _new_sha1 = sha.new + + +# See XCObject._EncodeString. This pattern is used to determine when a string +# can be printed unquoted. Strings that match this pattern may be printed +# unquoted. Strings that do not match must be quoted and may be further +# transformed to be properly encoded. Note that this expression matches the +# characters listed with "+", for 1 or more occurrences: if a string is empty, +# it must not match this pattern, because it needs to be encoded as "". +_unquoted = re.compile('^[A-Za-z0-9$./_]+$') + +# Strings that match this pattern are quoted regardless of what _unquoted says. +# Oddly, Xcode will quote any string with a run of three or more underscores. +_quoted = re.compile('___') + +# This pattern should match any character that needs to be escaped by +# XCObject._EncodeString. See that function. +_escaped = re.compile('[\\\\"]|[^ -~]') + + +# Used by SourceTreeAndPathFromPath +_path_leading_variable = re.compile('^\$\((.*?)\)(/(.*))?$') + +def SourceTreeAndPathFromPath(input_path): + """Given input_path, returns a tuple with sourceTree and path values. + + Examples: + input_path (source_tree, output_path) + '$(VAR)/path' ('VAR', 'path') + '$(VAR)' ('VAR', None) + 'path' (None, 'path') + """ + + source_group_match = _path_leading_variable.match(input_path) + if source_group_match: + source_tree = source_group_match.group(1) + output_path = source_group_match.group(3) # This may be None. + else: + source_tree = None + output_path = input_path + + return (source_tree, output_path) + +def ConvertVariablesToShellSyntax(input_string): + return re.sub('\$\((.*?)\)', '${\\1}', input_string) + +class XCObject(object): + """The abstract base of all class types used in Xcode project files. + + Class variables: + _schema: A dictionary defining the properties of this class. The keys to + _schema are string property keys as used in project files. Values + are a list of four or five elements: + [ is_list, property_type, is_strong, is_required, default ] + is_list: True if the property described is a list, as opposed + to a single element. + property_type: The type to use as the value of the property, + or if is_list is True, the type to use for each + element of the value's list. property_type must + be an XCObject subclass, or one of the built-in + types str, int, or dict. + is_strong: If property_type is an XCObject subclass, is_strong + is True to assert that this class "owns," or serves + as parent, to the property value (or, if is_list is + True, values). is_strong must be False if + property_type is not an XCObject subclass. + is_required: True if the property is required for the class. + Note that is_required being True does not preclude + an empty string ("", in the case of property_type + str) or list ([], in the case of is_list True) from + being set for the property. + default: Optional. If is_requried is True, default may be set + to provide a default value for objects that do not supply + their own value. If is_required is True and default + is not provided, users of the class must supply their own + value for the property. + Note that although the values of the array are expressed in + boolean terms, subclasses provide values as integers to conserve + horizontal space. + _should_print_single_line: False in XCObject. Subclasses whose objects + should be written to the project file in the + alternate single-line format, such as + PBXFileReference and PBXBuildFile, should + set this to True. + _encode_transforms: Used by _EncodeString to encode unprintable characters. + The index into this list is the ordinal of the + character to transform; each value is a string + used to represent the character in the output. XCObject + provides an _encode_transforms list suitable for most + XCObject subclasses. + _alternate_encode_transforms: Provided for subclasses that wish to use + the alternate encoding rules. Xcode seems + to use these rules when printing objects in + single-line format. Subclasses that desire + this behavior should set _encode_transforms + to _alternate_encode_transforms. + _hashables: A list of XCObject subclasses that can be hashed by ComputeIDs + to construct this object's ID. Most classes that need custom + hashing behavior should do it by overriding Hashables, + but in some cases an object's parent may wish to push a + hashable value into its child, and it can do so by appending + to _hashables. + Attribues: + id: The object's identifier, a 24-character uppercase hexadecimal string. + Usually, objects being created should not set id until the entire + project file structure is built. At that point, UpdateIDs() should + be called on the root object to assign deterministic values for id to + each object in the tree. + parent: The object's parent. This is set by a parent XCObject when a child + object is added to it. + _properties: The object's property dictionary. An object's properties are + described by its class' _schema variable. + """ + + _schema = {} + _should_print_single_line = False + + # See _EncodeString. + _encode_transforms = [] + i = 0 + while i < ord(' '): + _encode_transforms.append('\\U%04x' % i) + i = i + 1 + _encode_transforms[7] = '\\a' + _encode_transforms[8] = '\\b' + _encode_transforms[9] = '\\t' + _encode_transforms[10] = '\\n' + _encode_transforms[11] = '\\v' + _encode_transforms[12] = '\\f' + _encode_transforms[13] = '\\n' + + _alternate_encode_transforms = list(_encode_transforms) + _alternate_encode_transforms[9] = chr(9) + _alternate_encode_transforms[10] = chr(10) + _alternate_encode_transforms[11] = chr(11) + + def __init__(self, properties=None, id=None, parent=None): + self.id = id + self.parent = parent + self._properties = {} + self._hashables = [] + self._SetDefaultsFromSchema() + self.UpdateProperties(properties) + + def __repr__(self): + try: + name = self.Name() + except NotImplementedError: + return '<%s at 0x%x>' % (self.__class__.__name__, id(self)) + return '<%s %r at 0x%x>' % (self.__class__.__name__, name, id(self)) + + def Copy(self): + """Make a copy of this object. + + The new object will have its own copy of lists and dicts. Any XCObject + objects owned by this object (marked "strong") will be copied in the + new object, even those found in lists. If this object has any weak + references to other XCObjects, the same references are added to the new + object without making a copy. + """ + + that = self.__class__(id=self.id, parent=self.parent) + for key, value in self._properties.iteritems(): + is_strong = self._schema[key][2] + + if isinstance(value, XCObject): + if is_strong: + new_value = value.Copy() + new_value.parent = that + that._properties[key] = new_value + else: + that._properties[key] = value + elif isinstance(value, str) or isinstance(value, unicode) or \ + isinstance(value, int): + that._properties[key] = value + elif isinstance(value, list): + if is_strong: + # If is_strong is True, each element is an XCObject, so it's safe to + # call Copy. + that._properties[key] = [] + for item in value: + new_item = item.Copy() + new_item.parent = that + that._properties[key].append(new_item) + else: + that._properties[key] = value[:] + elif isinstance(value, dict): + # dicts are never strong. + if is_strong: + raise TypeError, 'Strong dict for key ' + key + ' in ' + \ + self.__class__.__name__ + else: + that._properties[key] = value.copy() + else: + raise TypeError, 'Unexpected type ' + value.__class__.__name__ + \ + ' for key ' + key + ' in ' + self.__class__.__name__ + + return that + + def Name(self): + """Return the name corresponding to an object. + + Not all objects necessarily need to be nameable, and not all that do have + a "name" property. Override as needed. + """ + + # If the schema indicates that "name" is required, try to access the + # property even if it doesn't exist. This will result in a KeyError + # being raised for the property that should be present, which seems more + # appropriate than NotImplementedError in this case. + if 'name' in self._properties or \ + ('name' in self._schema and self._schema['name'][3]): + return self._properties['name'] + + raise NotImplementedError, \ + self.__class__.__name__ + ' must implement Name' + + def Comment(self): + """Return a comment string for the object. + + Most objects just use their name as the comment, but PBXProject uses + different values. + + The returned comment is not escaped and does not have any comment marker + strings applied to it. + """ + + return self.Name() + + def Hashables(self): + hashables = [self.__class__.__name__] + + name = self.Name() + if name != None: + hashables.append(name) + + hashables.extend(self._hashables) + + return hashables + + def ComputeIDs(self, recursive=True, overwrite=True, hash=None): + """Set "id" properties deterministically. + + An object's "id" property is set based on a hash of its class type and + name, as well as the class type and name of all ancestor objects. As + such, it is only advisable to call ComputeIDs once an entire project file + tree is built. + + If recursive is True, recurse into all descendant objects and update their + hashes. + + If overwrite is True, any existing value set in the "id" property will be + replaced. + """ + + def _HashUpdate(hash, data): + """Update hash with data's length and contents. + + If the hash were updated only with the value of data, it would be + possible for clowns to induce collisions by manipulating the names of + their objects. By adding the length, it's exceedingly less likely that + ID collisions will be encountered, intentionally or not. + """ + + hash.update(struct.pack('>i', len(data))) + hash.update(data) + + if hash is None: + hash = _new_sha1() + + hashables = self.Hashables() + assert len(hashables) > 0 + for hashable in hashables: + _HashUpdate(hash, hashable) + + if recursive: + for child in self.Children(): + child.ComputeIDs(recursive, overwrite, hash.copy()) + + if overwrite or self.id is None: + # Xcode IDs are only 96 bits (24 hex characters), but a SHA-1 digest is + # is 160 bits. Instead of throwing out 64 bits of the digest, xor them + # into the portion that gets used. + assert hash.digest_size % 4 == 0 + digest_int_count = hash.digest_size / 4 + digest_ints = struct.unpack('>' + 'I' * digest_int_count, hash.digest()) + id_ints = [0, 0, 0] + for index in xrange(0, digest_int_count): + id_ints[index % 3] ^= digest_ints[index] + self.id = '%08X%08X%08X' % tuple(id_ints) + + def EnsureNoIDCollisions(self): + """Verifies that no two objects have the same ID. Checks all descendants. + """ + + ids = {} + descendants = self.Descendants() + for descendant in descendants: + if descendant.id in ids: + other = ids[descendant.id] + raise KeyError, \ + 'Duplicate ID %s, objects "%s" and "%s" in "%s"' % \ + (descendant.id, str(descendant._properties), + str(other._properties), self._properties['rootObject'].Name()) + ids[descendant.id] = descendant + + def Children(self): + """Returns a list of all of this object's owned (strong) children.""" + + children = [] + for property, attributes in self._schema.iteritems(): + (is_list, property_type, is_strong) = attributes[0:3] + if is_strong and property in self._properties: + if not is_list: + children.append(self._properties[property]) + else: + children.extend(self._properties[property]) + return children + + def Descendants(self): + """Returns a list of all of this object's descendants, including this + object. + """ + + children = self.Children() + descendants = [self] + for child in children: + descendants.extend(child.Descendants()) + return descendants + + def PBXProjectAncestor(self): + # The base case for recursion is defined at PBXProject.PBXProjectAncestor. + if self.parent: + return self.parent.PBXProjectAncestor() + return None + + def _EncodeComment(self, comment): + """Encodes a comment to be placed in the project file output, mimicing + Xcode behavior. + """ + + # This mimics Xcode behavior by wrapping the comment in "/*" and "*/". If + # the string already contains a "*/", it is turned into "(*)/". This keeps + # the file writer from outputting something that would be treated as the + # end of a comment in the middle of something intended to be entirely a + # comment. + + return '/* ' + comment.replace('*/', '(*)/') + ' */' + + def _EncodeTransform(self, match): + # This function works closely with _EncodeString. It will only be called + # by re.sub with match.group(0) containing a character matched by the + # the _escaped expression. + char = match.group(0) + + # Backslashes (\) and quotation marks (") are always replaced with a + # backslash-escaped version of the same. Everything else gets its + # replacement from the class' _encode_transforms array. + if char == '\\': + return '\\\\' + if char == '"': + return '\\"' + return self._encode_transforms[ord(char)] + + def _EncodeString(self, value): + """Encodes a string to be placed in the project file output, mimicing + Xcode behavior. + """ + + # Use quotation marks when any character outside of the range A-Z, a-z, 0-9, + # $ (dollar sign), . (period), and _ (underscore) is present. Also use + # quotation marks to represent empty strings. + # + # Escape " (double-quote) and \ (backslash) by preceding them with a + # backslash. + # + # Some characters below the printable ASCII range are encoded specially: + # 7 ^G BEL is encoded as "\a" + # 8 ^H BS is encoded as "\b" + # 11 ^K VT is encoded as "\v" + # 12 ^L NP is encoded as "\f" + # 127 ^? DEL is passed through as-is without escaping + # - In PBXFileReference and PBXBuildFile objects: + # 9 ^I HT is passed through as-is without escaping + # 10 ^J NL is passed through as-is without escaping + # 13 ^M CR is passed through as-is without escaping + # - In other objects: + # 9 ^I HT is encoded as "\t" + # 10 ^J NL is encoded as "\n" + # 13 ^M CR is encoded as "\n" rendering it indistinguishable from + # 10 ^J NL + # All other nonprintable characters within the ASCII range (0 through 127 + # inclusive) are encoded as "\U001f" referring to the Unicode code point in + # hexadecimal. For example, character 14 (^N SO) is encoded as "\U000e". + # Characters above the ASCII range are passed through to the output encoded + # as UTF-8 without any escaping. These mappings are contained in the + # class' _encode_transforms list. + + if _unquoted.search(value) and not _quoted.search(value): + return value + + return '"' + _escaped.sub(self._EncodeTransform, value) + '"' + + def _XCPrint(self, file, tabs, line): + file.write('\t' * tabs + line) + + def _XCPrintableValue(self, tabs, value, flatten_list=False): + """Returns a representation of value that may be printed in a project file, + mimicing Xcode's behavior. + + _XCPrintableValue can handle str and int values, XCObjects (which are + made printable by returning their id property), and list and dict objects + composed of any of the above types. When printing a list or dict, and + _should_print_single_line is False, the tabs parameter is used to determine + how much to indent the lines corresponding to the items in the list or + dict. + + If flatten_list is True, single-element lists will be transformed into + strings. + """ + + printable = '' + comment = None + + if self._should_print_single_line: + sep = ' ' + element_tabs = '' + end_tabs = '' + else: + sep = '\n' + element_tabs = '\t' * (tabs + 1) + end_tabs = '\t' * tabs + + if isinstance(value, XCObject): + printable += value.id + comment = value.Comment() + elif isinstance(value, str): + printable += self._EncodeString(value) + elif isinstance(value, unicode): + printable += self._EncodeString(value.encode('utf-8')) + elif isinstance(value, int): + printable += str(value) + elif isinstance(value, list): + if flatten_list and len(value) <= 1: + if len(value) == 0: + printable += self._EncodeString('') + else: + printable += self._EncodeString(value[0]) + else: + printable = '(' + sep + for item in value: + printable += element_tabs + \ + self._XCPrintableValue(tabs + 1, item, flatten_list) + \ + ',' + sep + printable += end_tabs + ')' + elif isinstance(value, dict): + printable = '{' + sep + for item_key, item_value in sorted(value.iteritems()): + printable += element_tabs + \ + self._XCPrintableValue(tabs + 1, item_key, flatten_list) + ' = ' + \ + self._XCPrintableValue(tabs + 1, item_value, flatten_list) + ';' + \ + sep + printable += end_tabs + '}' + else: + raise TypeError, "Can't make " + value.__class__.__name__ + ' printable' + + if comment != None: + printable += ' ' + self._EncodeComment(comment) + + return printable + + def _XCKVPrint(self, file, tabs, key, value): + """Prints a key and value, members of an XCObject's _properties dictionary, + to file. + + tabs is an int identifying the indentation level. If the class' + _should_print_single_line variable is True, tabs is ignored and the + key-value pair will be followed by a space insead of a newline. + """ + + if self._should_print_single_line: + printable = '' + after_kv = ' ' + else: + printable = '\t' * tabs + after_kv = '\n' + + # Xcode usually prints remoteGlobalIDString values in PBXContainerItemProxy + # objects without comments. Sometimes it prints them with comments, but + # the majority of the time, it doesn't. To avoid unnecessary changes to + # the project file after Xcode opens it, don't write comments for + # remoteGlobalIDString. This is a sucky hack and it would certainly be + # cleaner to extend the schema to indicate whether or not a comment should + # be printed, but since this is the only case where the problem occurs and + # Xcode itself can't seem to make up its mind, the hack will suffice. + # + # Also see PBXContainerItemProxy._schema['remoteGlobalIDString']. + if key == 'remoteGlobalIDString' and isinstance(self, + PBXContainerItemProxy): + value_to_print = value.id + else: + value_to_print = value + + # PBXBuildFile's settings property is represented in the output as a dict, + # but a hack here has it represented as a string. Arrange to strip off the + # quotes so that it shows up in the output as expected. + if key == 'settings' and isinstance(self, PBXBuildFile): + strip_value_quotes = True + else: + strip_value_quotes = False + + # In another one-off, let's set flatten_list on buildSettings properties + # of XCBuildConfiguration objects, because that's how Xcode treats them. + if key == 'buildSettings' and isinstance(self, XCBuildConfiguration): + flatten_list = True + else: + flatten_list = False + + try: + printable_key = self._XCPrintableValue(tabs, key, flatten_list) + printable_value = self._XCPrintableValue(tabs, value_to_print, + flatten_list) + if strip_value_quotes and len(printable_value) > 1 and \ + printable_value[0] == '"' and printable_value[-1] == '"': + printable_value = printable_value[1:-1] + printable += printable_key + ' = ' + printable_value + ';' + after_kv + except TypeError, e: + gyp.common.ExceptionAppend(e, + 'while printing key "%s"' % key) + raise + + self._XCPrint(file, 0, printable) + + def Print(self, file=sys.stdout): + """Prints a reprentation of this object to file, adhering to Xcode output + formatting. + """ + + self.VerifyHasRequiredProperties() + + if self._should_print_single_line: + # When printing an object in a single line, Xcode doesn't put any space + # between the beginning of a dictionary (or presumably a list) and the + # first contained item, so you wind up with snippets like + # ...CDEF = {isa = PBXFileReference; fileRef = 0123... + # If it were me, I would have put a space in there after the opening + # curly, but I guess this is just another one of those inconsistencies + # between how Xcode prints PBXFileReference and PBXBuildFile objects as + # compared to other objects. Mimic Xcode's behavior here by using an + # empty string for sep. + sep = '' + end_tabs = 0 + else: + sep = '\n' + end_tabs = 2 + + # Start the object. For example, '\t\tPBXProject = {\n'. + self._XCPrint(file, 2, self._XCPrintableValue(2, self) + ' = {' + sep) + + # "isa" isn't in the _properties dictionary, it's an intrinsic property + # of the class which the object belongs to. Xcode always outputs "isa" + # as the first element of an object dictionary. + self._XCKVPrint(file, 3, 'isa', self.__class__.__name__) + + # The remaining elements of an object dictionary are sorted alphabetically. + for property, value in sorted(self._properties.iteritems()): + self._XCKVPrint(file, 3, property, value) + + # End the object. + self._XCPrint(file, end_tabs, '};\n') + + def UpdateProperties(self, properties, do_copy=False): + """Merge the supplied properties into the _properties dictionary. + + The input properties must adhere to the class schema or a KeyError or + TypeError exception will be raised. If adding an object of an XCObject + subclass and the schema indicates a strong relationship, the object's + parent will be set to this object. + + If do_copy is True, then lists, dicts, strong-owned XCObjects, and + strong-owned XCObjects in lists will be copied instead of having their + references added. + """ + + if properties is None: + return + + for property, value in properties.iteritems(): + # Make sure the property is in the schema. + if not property in self._schema: + raise KeyError, property + ' not in ' + self.__class__.__name__ + + # Make sure the property conforms to the schema. + (is_list, property_type, is_strong) = self._schema[property][0:3] + if is_list: + if value.__class__ != list: + raise TypeError, \ + property + ' of ' + self.__class__.__name__ + \ + ' must be list, not ' + value.__class__.__name__ + for item in value: + if not isinstance(item, property_type) and \ + not (item.__class__ == unicode and property_type == str): + # Accept unicode where str is specified. str is treated as + # UTF-8-encoded. + raise TypeError, \ + 'item of ' + property + ' of ' + self.__class__.__name__ + \ + ' must be ' + property_type.__name__ + ', not ' + \ + item.__class__.__name__ + elif not isinstance(value, property_type) and \ + not (value.__class__ == unicode and property_type == str): + # Accept unicode where str is specified. str is treated as + # UTF-8-encoded. + raise TypeError, \ + property + ' of ' + self.__class__.__name__ + ' must be ' + \ + property_type.__name__ + ', not ' + value.__class__.__name__ + + # Checks passed, perform the assignment. + if do_copy: + if isinstance(value, XCObject): + if is_strong: + self._properties[property] = value.Copy() + else: + self._properties[property] = value + elif isinstance(value, str) or isinstance(value, unicode) or \ + isinstance(value, int): + self._properties[property] = value + elif isinstance(value, list): + if is_strong: + # If is_strong is True, each element is an XCObject, so it's safe + # to call Copy. + self._properties[property] = [] + for item in value: + self._properties[property].append(item.Copy()) + else: + self._properties[property] = value[:] + elif isinstance(value, dict): + self._properties[property] = value.copy() + else: + raise TypeError, "Don't know how to copy a " + \ + value.__class__.__name__ + ' object for ' + \ + property + ' in ' + self.__class__.__name__ + else: + self._properties[property] = value + + # Set up the child's back-reference to this object. Don't use |value| + # any more because it may not be right if do_copy is true. + if is_strong: + if not is_list: + self._properties[property].parent = self + else: + for item in self._properties[property]: + item.parent = self + + def HasProperty(self, key): + return key in self._properties + + def GetProperty(self, key): + return self._properties[key] + + def SetProperty(self, key, value): + self.UpdateProperties({key: value}) + + def DelProperty(self, key): + if key in self._properties: + del self._properties[key] + + def AppendProperty(self, key, value): + # TODO(mark): Support ExtendProperty too (and make this call that)? + + # Schema validation. + if not key in self._schema: + raise KeyError, key + ' not in ' + self.__class__.__name__ + + (is_list, property_type, is_strong) = self._schema[key][0:3] + if not is_list: + raise TypeError, key + ' of ' + self.__class__.__name__ + ' must be list' + if not isinstance(value, property_type): + raise TypeError, 'item of ' + key + ' of ' + self.__class__.__name__ + \ + ' must be ' + property_type.__name__ + ', not ' + \ + value.__class__.__name__ + + # If the property doesn't exist yet, create a new empty list to receive the + # item. + if not key in self._properties: + self._properties[key] = [] + + # Set up the ownership link. + if is_strong: + value.parent = self + + # Store the item. + self._properties[key].append(value) + + def VerifyHasRequiredProperties(self): + """Ensure that all properties identified as required by the schema are + set. + """ + + # TODO(mark): A stronger verification mechanism is needed. Some + # subclasses need to perform validation beyond what the schema can enforce. + for property, attributes in self._schema.iteritems(): + (is_list, property_type, is_strong, is_required) = attributes[0:4] + if is_required and not property in self._properties: + raise KeyError, self.__class__.__name__ + ' requires ' + property + + def _SetDefaultsFromSchema(self): + """Assign object default values according to the schema. This will not + overwrite properties that have already been set.""" + + defaults = {} + for property, attributes in self._schema.iteritems(): + (is_list, property_type, is_strong, is_required) = attributes[0:4] + if is_required and len(attributes) >= 5 and \ + not property in self._properties: + default = attributes[4] + + defaults[property] = default + + if len(defaults) > 0: + # Use do_copy=True so that each new object gets its own copy of strong + # objects, lists, and dicts. + self.UpdateProperties(defaults, do_copy=True) + + +class XCHierarchicalElement(XCObject): + """Abstract base for PBXGroup and PBXFileReference. Not represented in a + project file.""" + + # TODO(mark): Do name and path belong here? Probably so. + # If path is set and name is not, name may have a default value. Name will + # be set to the basename of path, if the basename of path is different from + # the full value of path. If path is already just a leaf name, name will + # not be set. + _schema = XCObject._schema.copy() + _schema.update({ + 'comments': [0, str, 0, 0], + 'fileEncoding': [0, str, 0, 0], + 'includeInIndex': [0, int, 0, 0], + 'indentWidth': [0, int, 0, 0], + 'lineEnding': [0, int, 0, 0], + 'sourceTree': [0, str, 0, 1, ''], + 'tabWidth': [0, int, 0, 0], + 'usesTabs': [0, int, 0, 0], + 'wrapsLines': [0, int, 0, 0], + }) + + def __init__(self, properties=None, id=None, parent=None): + # super + XCObject.__init__(self, properties, id, parent) + if 'path' in self._properties and not 'name' in self._properties: + path = self._properties['path'] + name = posixpath.basename(path) + if name != '' and path != name: + self.SetProperty('name', name) + + if 'path' in self._properties and \ + (not 'sourceTree' in self._properties or \ + self._properties['sourceTree'] == ''): + # If the pathname begins with an Xcode variable like "$(SDKROOT)/", take + # the variable out and make the path be relative to that variable by + # assigning the variable name as the sourceTree. + (source_tree, path) = SourceTreeAndPathFromPath(self._properties['path']) + if source_tree != None: + self._properties['sourceTree'] = source_tree + if path != None: + self._properties['path'] = path + if source_tree != None and path is None and \ + not 'name' in self._properties: + # The path was of the form "$(SDKROOT)" with no path following it. + # This object is now relative to that variable, so it has no path + # attribute of its own. It does, however, keep a name. + del self._properties['path'] + self._properties['name'] = source_tree + + def Name(self): + if 'name' in self._properties: + return self._properties['name'] + elif 'path' in self._properties: + return self._properties['path'] + else: + # This happens in the case of the root PBXGroup. + return None + + def Hashables(self): + """Custom hashables for XCHierarchicalElements. + + XCHierarchicalElements are special. Generally, their hashes shouldn't + change if the paths don't change. The normal XCObject implementation of + Hashables adds a hashable for each object, which means that if + the hierarchical structure changes (possibly due to changes caused when + TakeOverOnlyChild runs and encounters slight changes in the hierarchy), + the hashes will change. For example, if a project file initially contains + a/b/f1 and a/b becomes collapsed into a/b, f1 will have a single parent + a/b. If someone later adds a/f2 to the project file, a/b can no longer be + collapsed, and f1 winds up with parent b and grandparent a. That would + be sufficient to change f1's hash. + + To counteract this problem, hashables for all XCHierarchicalElements except + for the main group (which has neither a name nor a path) are taken to be + just the set of path components. Because hashables are inherited from + parents, this provides assurance that a/b/f1 has the same set of hashables + whether its parent is b or a/b. + + The main group is a special case. As it is permitted to have no name or + path, it is permitted to use the standard XCObject hash mechanism. This + is not considered a problem because there can be only one main group. + """ + + if self == self.PBXProjectAncestor()._properties['mainGroup']: + # super + return XCObject.Hashables(self) + + hashables = [] + + # Put the name in first, ensuring that if TakeOverOnlyChild collapses + # children into a top-level group like "Source", the name always goes + # into the list of hashables without interfering with path components. + if 'name' in self._properties: + # Make it less likely for people to manipulate hashes by following the + # pattern of always pushing an object type value onto the list first. + hashables.append(self.__class__.__name__ + '.name') + hashables.append(self._properties['name']) + + # NOTE: This still has the problem that if an absolute path is encountered, + # including paths with a sourceTree, they'll still inherit their parents' + # hashables, even though the paths aren't relative to their parents. This + # is not expected to be much of a problem in practice. + path = self.PathFromSourceTreeAndPath() + if path != None: + components = path.split(posixpath.sep) + for component in components: + hashables.append(self.__class__.__name__ + '.path') + hashables.append(component) + + hashables.extend(self._hashables) + + return hashables + + def Compare(self, other): + # Allow comparison of these types. PBXGroup has the highest sort rank; + # PBXVariantGroup is treated as equal to PBXFileReference. + valid_class_types = { + PBXFileReference: 'file', + PBXGroup: 'group', + PBXVariantGroup: 'file', + } + self_type = valid_class_types[self.__class__] + other_type = valid_class_types[other.__class__] + + if self_type == other_type: + # If the two objects are of the same sort rank, compare their names. + return cmp(self.Name(), other.Name()) + + # Otherwise, sort groups before everything else. + if self_type == 'group': + return -1 + return 1 + + def CompareRootGroup(self, other): + # This function should be used only to compare direct children of the + # containing PBXProject's mainGroup. These groups should appear in the + # listed order. + # TODO(mark): "Build" is used by gyp.generator.xcode, perhaps the + # generator should have a way of influencing this list rather than having + # to hardcode for the generator here. + order = ['Source', 'Intermediates', 'Projects', 'Frameworks', 'Products', + 'Build'] + + # If the groups aren't in the listed order, do a name comparison. + # Otherwise, groups in the listed order should come before those that + # aren't. + self_name = self.Name() + other_name = other.Name() + self_in = isinstance(self, PBXGroup) and self_name in order + other_in = isinstance(self, PBXGroup) and other_name in order + if not self_in and not other_in: + return self.Compare(other) + if self_name in order and not other_name in order: + return -1 + if other_name in order and not self_name in order: + return 1 + + # If both groups are in the listed order, go by the defined order. + self_index = order.index(self_name) + other_index = order.index(other_name) + if self_index < other_index: + return -1 + if self_index > other_index: + return 1 + return 0 + + def PathFromSourceTreeAndPath(self): + # Turn the object's sourceTree and path properties into a single flat + # string of a form comparable to the path parameter. If there's a + # sourceTree property other than "", wrap it in $(...) for the + # comparison. + components = [] + if self._properties['sourceTree'] != '': + components.append('$(' + self._properties['sourceTree'] + ')') + if 'path' in self._properties: + components.append(self._properties['path']) + + if len(components) > 0: + return posixpath.join(*components) + + return None + + def FullPath(self): + # Returns a full path to self relative to the project file, or relative + # to some other source tree. Start with self, and walk up the chain of + # parents prepending their paths, if any, until no more parents are + # available (project-relative path) or until a path relative to some + # source tree is found. + xche = self + path = None + while isinstance(xche, XCHierarchicalElement) and \ + (path is None or \ + (not path.startswith('/') and not path.startswith('$'))): + this_path = xche.PathFromSourceTreeAndPath() + if this_path != None and path != None: + path = posixpath.join(this_path, path) + elif this_path != None: + path = this_path + xche = xche.parent + + return path + + +class PBXGroup(XCHierarchicalElement): + """ + Attributes: + _children_by_path: Maps pathnames of children of this PBXGroup to the + actual child XCHierarchicalElement objects. + _variant_children_by_name_and_path: Maps (name, path) tuples of + PBXVariantGroup children to the actual child PBXVariantGroup objects. + """ + + _schema = XCHierarchicalElement._schema.copy() + _schema.update({ + 'children': [1, XCHierarchicalElement, 1, 1, []], + 'name': [0, str, 0, 0], + 'path': [0, str, 0, 0], + }) + + def __init__(self, properties=None, id=None, parent=None): + # super + XCHierarchicalElement.__init__(self, properties, id, parent) + self._children_by_path = {} + self._variant_children_by_name_and_path = {} + for child in self._properties.get('children', []): + self._AddChildToDicts(child) + + def _AddChildToDicts(self, child): + # Sets up this PBXGroup object's dicts to reference the child properly. + child_path = child.PathFromSourceTreeAndPath() + if child_path: + if child_path in self._children_by_path: + raise ValueError, 'Found multiple children with path ' + child_path + self._children_by_path[child_path] = child + + if isinstance(child, PBXVariantGroup): + child_name = child._properties.get('name', None) + key = (child_name, child_path) + if key in self._variant_children_by_name_and_path: + raise ValueError, 'Found multiple PBXVariantGroup children with ' + \ + 'name ' + str(child_name) + ' and path ' + \ + str(child_path) + self._variant_children_by_name_and_path[key] = child + + def AppendChild(self, child): + # Callers should use this instead of calling + # AppendProperty('children', child) directly because this function + # maintains the group's dicts. + self.AppendProperty('children', child) + self._AddChildToDicts(child) + + def GetChildByName(self, name): + # This is not currently optimized with a dict as GetChildByPath is because + # it has few callers. Most callers probably want GetChildByPath. This + # function is only useful to get children that have names but no paths, + # which is rare. The children of the main group ("Source", "Products", + # etc.) is pretty much the only case where this likely to come up. + # + # TODO(mark): Maybe this should raise an error if more than one child is + # present with the same name. + if not 'children' in self._properties: + return None + + for child in self._properties['children']: + if child.Name() == name: + return child + + return None + + def GetChildByPath(self, path): + if not path: + return None + + if path in self._children_by_path: + return self._children_by_path[path] + + return None + + def GetChildByRemoteObject(self, remote_object): + # This method is a little bit esoteric. Given a remote_object, which + # should be a PBXFileReference in another project file, this method will + # return this group's PBXReferenceProxy object serving as a local proxy + # for the remote PBXFileReference. + # + # This function might benefit from a dict optimization as GetChildByPath + # for some workloads, but profiling shows that it's not currently a + # problem. + if not 'children' in self._properties: + return None + + for child in self._properties['children']: + if not isinstance(child, PBXReferenceProxy): + continue + + container_proxy = child._properties['remoteRef'] + if container_proxy._properties['remoteGlobalIDString'] == remote_object: + return child + + return None + + def AddOrGetFileByPath(self, path, hierarchical): + """Returns an existing or new file reference corresponding to path. + + If hierarchical is True, this method will create or use the necessary + hierarchical group structure corresponding to path. Otherwise, it will + look in and create an item in the current group only. + + If an existing matching reference is found, it is returned, otherwise, a + new one will be created, added to the correct group, and returned. + + If path identifies a directory by virtue of carrying a trailing slash, + this method returns a PBXFileReference of "folder" type. If path + identifies a variant, by virtue of it identifying a file inside a directory + with an ".lproj" extension, this method returns a PBXVariantGroup + containing the variant named by path, and possibly other variants. For + all other paths, a "normal" PBXFileReference will be returned. + """ + + # Adding or getting a directory? Directories end with a trailing slash. + is_dir = False + if path.endswith('/'): + is_dir = True + path = posixpath.normpath(path) + if is_dir: + path = path + '/' + + # Adding or getting a variant? Variants are files inside directories + # with an ".lproj" extension. Xcode uses variants for localization. For + # a variant path/to/Language.lproj/MainMenu.nib, put a variant group named + # MainMenu.nib inside path/to, and give it a variant named Language. In + # this example, grandparent would be set to path/to and parent_root would + # be set to Language. + variant_name = None + parent = posixpath.dirname(path) + grandparent = posixpath.dirname(parent) + parent_basename = posixpath.basename(parent) + (parent_root, parent_ext) = posixpath.splitext(parent_basename) + if parent_ext == '.lproj': + variant_name = parent_root + if grandparent == '': + grandparent = None + + # Putting a directory inside a variant group is not currently supported. + assert not is_dir or variant_name is None + + path_split = path.split(posixpath.sep) + if len(path_split) == 1 or \ + ((is_dir or variant_name != None) and len(path_split) == 2) or \ + not hierarchical: + # The PBXFileReference or PBXVariantGroup will be added to or gotten from + # this PBXGroup, no recursion necessary. + if variant_name is None: + # Add or get a PBXFileReference. + file_ref = self.GetChildByPath(path) + if file_ref != None: + assert file_ref.__class__ == PBXFileReference + else: + file_ref = PBXFileReference({'path': path}) + self.AppendChild(file_ref) + else: + # Add or get a PBXVariantGroup. The variant group name is the same + # as the basename (MainMenu.nib in the example above). grandparent + # specifies the path to the variant group itself, and path_split[-2:] + # is the path of the specific variant relative to its group. + variant_group_name = posixpath.basename(path) + variant_group_ref = self.AddOrGetVariantGroupByNameAndPath( + variant_group_name, grandparent) + variant_path = posixpath.sep.join(path_split[-2:]) + variant_ref = variant_group_ref.GetChildByPath(variant_path) + if variant_ref != None: + assert variant_ref.__class__ == PBXFileReference + else: + variant_ref = PBXFileReference({'name': variant_name, + 'path': variant_path}) + variant_group_ref.AppendChild(variant_ref) + # The caller is interested in the variant group, not the specific + # variant file. + file_ref = variant_group_ref + return file_ref + else: + # Hierarchical recursion. Add or get a PBXGroup corresponding to the + # outermost path component, and then recurse into it, chopping off that + # path component. + next_dir = path_split[0] + group_ref = self.GetChildByPath(next_dir) + if group_ref != None: + assert group_ref.__class__ == PBXGroup + else: + group_ref = PBXGroup({'path': next_dir}) + self.AppendChild(group_ref) + return group_ref.AddOrGetFileByPath(posixpath.sep.join(path_split[1:]), + hierarchical) + + def AddOrGetVariantGroupByNameAndPath(self, name, path): + """Returns an existing or new PBXVariantGroup for name and path. + + If a PBXVariantGroup identified by the name and path arguments is already + present as a child of this object, it is returned. Otherwise, a new + PBXVariantGroup with the correct properties is created, added as a child, + and returned. + + This method will generally be called by AddOrGetFileByPath, which knows + when to create a variant group based on the structure of the pathnames + passed to it. + """ + + key = (name, path) + if key in self._variant_children_by_name_and_path: + variant_group_ref = self._variant_children_by_name_and_path[key] + assert variant_group_ref.__class__ == PBXVariantGroup + return variant_group_ref + + variant_group_properties = {'name': name} + if path != None: + variant_group_properties['path'] = path + variant_group_ref = PBXVariantGroup(variant_group_properties) + self.AppendChild(variant_group_ref) + + return variant_group_ref + + def TakeOverOnlyChild(self, recurse=False): + """If this PBXGroup has only one child and it's also a PBXGroup, take + it over by making all of its children this object's children. + + This function will continue to take over only children when those children + are groups. If there are three PBXGroups representing a, b, and c, with + c inside b and b inside a, and a and b have no other children, this will + result in a taking over both b and c, forming a PBXGroup for a/b/c. + + If recurse is True, this function will recurse into children and ask them + to collapse themselves by taking over only children as well. Assuming + an example hierarchy with files at a/b/c/d1, a/b/c/d2, and a/b/c/d3/e/f + (d1, d2, and f are files, the rest are groups), recursion will result in + a group for a/b/c containing a group for d3/e. + """ + + # At this stage, check that child class types are PBXGroup exactly, + # instead of using isinstance. The only subclass of PBXGroup, + # PBXVariantGroup, should not participate in reparenting in the same way: + # reparenting by merging different object types would be wrong. + while len(self._properties['children']) == 1 and \ + self._properties['children'][0].__class__ == PBXGroup: + # Loop to take over the innermost only-child group possible. + + child = self._properties['children'][0] + + # Assume the child's properties, including its children. Save a copy + # of this object's old properties, because they'll still be needed. + # This object retains its existing id and parent attributes. + old_properties = self._properties + self._properties = child._properties + self._children_by_path = child._children_by_path + + if not 'sourceTree' in self._properties or \ + self._properties['sourceTree'] == '': + # The child was relative to its parent. Fix up the path. Note that + # children with a sourceTree other than "" are not relative to + # their parents, so no path fix-up is needed in that case. + if 'path' in old_properties: + if 'path' in self._properties: + # Both the original parent and child have paths set. + self._properties['path'] = posixpath.join(old_properties['path'], + self._properties['path']) + else: + # Only the original parent has a path, use it. + self._properties['path'] = old_properties['path'] + if 'sourceTree' in old_properties: + # The original parent had a sourceTree set, use it. + self._properties['sourceTree'] = old_properties['sourceTree'] + + # If the original parent had a name set, keep using it. If the original + # parent didn't have a name but the child did, let the child's name + # live on. If the name attribute seems unnecessary now, get rid of it. + if 'name' in old_properties and old_properties['name'] != None and \ + old_properties['name'] != self.Name(): + self._properties['name'] = old_properties['name'] + if 'name' in self._properties and 'path' in self._properties and \ + self._properties['name'] == self._properties['path']: + del self._properties['name'] + + # Notify all children of their new parent. + for child in self._properties['children']: + child.parent = self + + # If asked to recurse, recurse. + if recurse: + for child in self._properties['children']: + if child.__class__ == PBXGroup: + child.TakeOverOnlyChild(recurse) + + def SortGroup(self): + self._properties['children'] = \ + sorted(self._properties['children'], cmp=lambda x,y: x.Compare(y)) + + # Recurse. + for child in self._properties['children']: + if isinstance(child, PBXGroup): + child.SortGroup() + + +class XCFileLikeElement(XCHierarchicalElement): + # Abstract base for objects that can be used as the fileRef property of + # PBXBuildFile. + + def PathHashables(self): + # A PBXBuildFile that refers to this object will call this method to + # obtain additional hashables specific to this XCFileLikeElement. Don't + # just use this object's hashables, they're not specific and unique enough + # on their own (without access to the parent hashables.) Instead, provide + # hashables that identify this object by path by getting its hashables as + # well as the hashables of ancestor XCHierarchicalElement objects. + + hashables = [] + xche = self + while xche != None and isinstance(xche, XCHierarchicalElement): + xche_hashables = xche.Hashables() + for index in xrange(0, len(xche_hashables)): + hashables.insert(index, xche_hashables[index]) + xche = xche.parent + return hashables + + +class XCContainerPortal(XCObject): + # Abstract base for objects that can be used as the containerPortal property + # of PBXContainerItemProxy. + pass + + +class XCRemoteObject(XCObject): + # Abstract base for objects that can be used as the remoteGlobalIDString + # property of PBXContainerItemProxy. + pass + + +class PBXFileReference(XCFileLikeElement, XCContainerPortal, XCRemoteObject): + _schema = XCFileLikeElement._schema.copy() + _schema.update({ + 'explicitFileType': [0, str, 0, 0], + 'lastKnownFileType': [0, str, 0, 0], + 'name': [0, str, 0, 0], + 'path': [0, str, 0, 1], + }) + + # Weird output rules for PBXFileReference. + _should_print_single_line = True + # super + _encode_transforms = XCFileLikeElement._alternate_encode_transforms + + def __init__(self, properties=None, id=None, parent=None): + # super + XCFileLikeElement.__init__(self, properties, id, parent) + if 'path' in self._properties and self._properties['path'].endswith('/'): + self._properties['path'] = self._properties['path'][:-1] + is_dir = True + else: + is_dir = False + + if 'path' in self._properties and \ + not 'lastKnownFileType' in self._properties and \ + not 'explicitFileType' in self._properties: + # TODO(mark): This is the replacement for a replacement for a quick hack. + # It is no longer incredibly sucky, but this list needs to be extended. + extension_map = { + 'a': 'archive.ar', + 'app': 'wrapper.application', + 'bdic': 'file', + 'bundle': 'wrapper.cfbundle', + 'c': 'sourcecode.c.c', + 'cc': 'sourcecode.cpp.cpp', + 'cpp': 'sourcecode.cpp.cpp', + 'css': 'text.css', + 'cxx': 'sourcecode.cpp.cpp', + 'dylib': 'compiled.mach-o.dylib', + 'framework': 'wrapper.framework', + 'h': 'sourcecode.c.h', + 'hxx': 'sourcecode.cpp.h', + 'icns': 'image.icns', + 'java': 'sourcecode.java', + 'js': 'sourcecode.javascript', + 'm': 'sourcecode.c.objc', + 'mm': 'sourcecode.cpp.objcpp', + 'nib': 'wrapper.nib', + 'o': 'compiled.mach-o.objfile', + 'pdf': 'image.pdf', + 'pl': 'text.script.perl', + 'plist': 'text.plist.xml', + 'pm': 'text.script.perl', + 'png': 'image.png', + 'py': 'text.script.python', + 'r': 'sourcecode.rez', + 'rez': 'sourcecode.rez', + 's': 'sourcecode.asm', + 'strings': 'text.plist.strings', + 'ttf': 'file', + 'xcconfig': 'text.xcconfig', + 'xib': 'file.xib', + 'y': 'sourcecode.yacc', + } + + if is_dir: + file_type = 'folder' + else: + basename = posixpath.basename(self._properties['path']) + (root, ext) = posixpath.splitext(basename) + # Check the map using a lowercase extension. + # TODO(mark): Maybe it should try with the original case first and fall + # back to lowercase, in case there are any instances where case + # matters. There currently aren't. + if ext != '': + ext = ext[1:].lower() + + # TODO(mark): "text" is the default value, but "file" is appropriate + # for unrecognized files not containing text. Xcode seems to choose + # based on content. + file_type = extension_map.get(ext, 'text') + + self._properties['lastKnownFileType'] = file_type + + +class PBXVariantGroup(PBXGroup, XCFileLikeElement): + """PBXVariantGroup is used by Xcode to represent localizations.""" + # No additions to the schema relative to PBXGroup. + pass + + +# PBXReferenceProxy is also an XCFileLikeElement subclass. It is defined below +# because it uses PBXContainerItemProxy, defined below. + + +class XCBuildConfiguration(XCObject): + _schema = XCObject._schema.copy() + _schema.update({ + 'baseConfigurationReference': [0, PBXFileReference, 0, 0], + 'buildSettings': [0, dict, 0, 1, {}], + 'name': [0, str, 0, 1], + }) + + def HasBuildSetting(self, key): + return key in self._properties['buildSettings'] + + def GetBuildSetting(self, key): + return self._properties['buildSettings'][key] + + def SetBuildSetting(self, key, value): + # TODO(mark): If a list, copy? + self._properties['buildSettings'][key] = value + + def AppendBuildSetting(self, key, value): + if not key in self._properties['buildSettings']: + self._properties['buildSettings'][key] = [] + self._properties['buildSettings'][key].append(value) + + def DelBuildSetting(self, key): + if key in self._properties['buildSettings']: + del self._properties['buildSettings'][key] + + def SetBaseConfiguration(self, value): + self._properties['baseConfigurationReference'] = value + +class XCConfigurationList(XCObject): + # _configs is the default list of configurations. + _configs = [ XCBuildConfiguration({'name': 'Debug'}), + XCBuildConfiguration({'name': 'Release'}) ] + + _schema = XCObject._schema.copy() + _schema.update({ + 'buildConfigurations': [1, XCBuildConfiguration, 1, 1, _configs], + 'defaultConfigurationIsVisible': [0, int, 0, 1, 1], + 'defaultConfigurationName': [0, str, 0, 1, 'Release'], + }) + + def Name(self): + return 'Build configuration list for ' + \ + self.parent.__class__.__name__ + ' "' + self.parent.Name() + '"' + + def ConfigurationNamed(self, name): + """Convenience accessor to obtain an XCBuildConfiguration by name.""" + for configuration in self._properties['buildConfigurations']: + if configuration._properties['name'] == name: + return configuration + + raise KeyError, name + + def DefaultConfiguration(self): + """Convenience accessor to obtain the default XCBuildConfiguration.""" + return self.ConfigurationNamed(self._properties['defaultConfigurationName']) + + def HasBuildSetting(self, key): + """Determines the state of a build setting in all XCBuildConfiguration + child objects. + + If all child objects have key in their build settings, and the value is the + same in all child objects, returns 1. + + If no child objects have the key in their build settings, returns 0. + + If some, but not all, child objects have the key in their build settings, + or if any children have different values for the key, returns -1. + """ + + has = None + value = None + for configuration in self._properties['buildConfigurations']: + configuration_has = configuration.HasBuildSetting(key) + if has is None: + has = configuration_has + elif has != configuration_has: + return -1 + + if configuration_has: + configuration_value = configuration.GetBuildSetting(key) + if value is None: + value = configuration_value + elif value != configuration_value: + return -1 + + if not has: + return 0 + + return 1 + + def GetBuildSetting(self, key): + """Gets the build setting for key. + + All child XCConfiguration objects must have the same value set for the + setting, or a ValueError will be raised. + """ + + # TODO(mark): This is wrong for build settings that are lists. The list + # contents should be compared (and a list copy returned?) + + value = None + for configuration in self._properties['buildConfigurations']: + configuration_value = configuration.GetBuildSetting(key) + if value is None: + value = configuration_value + else: + if value != configuration_value: + raise ValueError, 'Variant values for ' + key + + return value + + def SetBuildSetting(self, key, value): + """Sets the build setting for key to value in all child + XCBuildConfiguration objects. + """ + + for configuration in self._properties['buildConfigurations']: + configuration.SetBuildSetting(key, value) + + def AppendBuildSetting(self, key, value): + """Appends value to the build setting for key, which is treated as a list, + in all child XCBuildConfiguration objects. + """ + + for configuration in self._properties['buildConfigurations']: + configuration.AppendBuildSetting(key, value) + + def DelBuildSetting(self, key): + """Deletes the build setting key from all child XCBuildConfiguration + objects. + """ + + for configuration in self._properties['buildConfigurations']: + configuration.DelBuildSetting(key) + + def SetBaseConfiguration(self, value): + """Sets the build configuration in all child XCBuildConfiguration objects. + """ + + for configuration in self._properties['buildConfigurations']: + configuration.SetBaseConfiguration(value) + + +class PBXBuildFile(XCObject): + _schema = XCObject._schema.copy() + _schema.update({ + 'fileRef': [0, XCFileLikeElement, 0, 1], + 'settings': [0, str, 0, 0], # hack, it's a dict + }) + + # Weird output rules for PBXBuildFile. + _should_print_single_line = True + _encode_transforms = XCObject._alternate_encode_transforms + + def Name(self): + # Example: "main.cc in Sources" + return self._properties['fileRef'].Name() + ' in ' + self.parent.Name() + + def Hashables(self): + # super + hashables = XCObject.Hashables(self) + + # It is not sufficient to just rely on Name() to get the + # XCFileLikeElement's name, because that is not a complete pathname. + # PathHashables returns hashables unique enough that no two + # PBXBuildFiles should wind up with the same set of hashables, unless + # someone adds the same file multiple times to the same target. That + # would be considered invalid anyway. + hashables.extend(self._properties['fileRef'].PathHashables()) + + return hashables + + +class XCBuildPhase(XCObject): + """Abstract base for build phase classes. Not represented in a project + file. + + Attributes: + _files_by_path: A dict mapping each path of a child in the files list by + path (keys) to the corresponding PBXBuildFile children (values). + _files_by_xcfilelikeelement: A dict mapping each XCFileLikeElement (keys) + to the corresponding PBXBuildFile children (values). + """ + + # TODO(mark): Some build phase types, like PBXShellScriptBuildPhase, don't + # actually have a "files" list. XCBuildPhase should not have "files" but + # another abstract subclass of it should provide this, and concrete build + # phase types that do have "files" lists should be derived from that new + # abstract subclass. XCBuildPhase should only provide buildActionMask and + # runOnlyForDeploymentPostprocessing, and not files or the various + # file-related methods and attributes. + + _schema = XCObject._schema.copy() + _schema.update({ + 'buildActionMask': [0, int, 0, 1, 0x7fffffff], + 'files': [1, PBXBuildFile, 1, 1, []], + 'runOnlyForDeploymentPostprocessing': [0, int, 0, 1, 0], + }) + + def __init__(self, properties=None, id=None, parent=None): + # super + XCObject.__init__(self, properties, id, parent) + + self._files_by_path = {} + self._files_by_xcfilelikeelement = {} + for pbxbuildfile in self._properties.get('files', []): + self._AddBuildFileToDicts(pbxbuildfile) + + def FileGroup(self, path): + # Subclasses must override this by returning a two-element tuple. The + # first item in the tuple should be the PBXGroup to which "path" should be + # added, either as a child or deeper descendant. The second item should + # be a boolean indicating whether files should be added into hierarchical + # groups or one single flat group. + raise NotImplementedError, \ + self.__class__.__name__ + ' must implement FileGroup' + + def _AddPathToDict(self, pbxbuildfile, path): + """Adds path to the dict tracking paths belonging to this build phase. + + If the path is already a member of this build phase, raises an exception. + """ + + if path in self._files_by_path: + raise ValueError, 'Found multiple build files with path ' + path + self._files_by_path[path] = pbxbuildfile + + def _AddBuildFileToDicts(self, pbxbuildfile, path=None): + """Maintains the _files_by_path and _files_by_xcfilelikeelement dicts. + + If path is specified, then it is the path that is being added to the + phase, and pbxbuildfile must contain either a PBXFileReference directly + referencing that path, or it must contain a PBXVariantGroup that itself + contains a PBXFileReference referencing the path. + + If path is not specified, either the PBXFileReference's path or the paths + of all children of the PBXVariantGroup are taken as being added to the + phase. + + If the path is already present in the phase, raises an exception. + + If the PBXFileReference or PBXVariantGroup referenced by pbxbuildfile + are already present in the phase, referenced by a different PBXBuildFile + object, raises an exception. This does not raise an exception when + a PBXFileReference or PBXVariantGroup reappear and are referenced by the + same PBXBuildFile that has already introduced them, because in the case + of PBXVariantGroup objects, they may correspond to multiple paths that are + not all added simultaneously. When this situation occurs, the path needs + to be added to _files_by_path, but nothing needs to change in + _files_by_xcfilelikeelement, and the caller should have avoided adding + the PBXBuildFile if it is already present in the list of children. + """ + + xcfilelikeelement = pbxbuildfile._properties['fileRef'] + + paths = [] + if path != None: + # It's best when the caller provides the path. + if isinstance(xcfilelikeelement, PBXVariantGroup): + paths.append(path) + else: + # If the caller didn't provide a path, there can be either multiple + # paths (PBXVariantGroup) or one. + if isinstance(xcfilelikeelement, PBXVariantGroup): + for variant in xcfilelikeelement._properties['children']: + paths.append(variant.FullPath()) + else: + paths.append(xcfilelikeelement.FullPath()) + + # Add the paths first, because if something's going to raise, the + # messages provided by _AddPathToDict are more useful owing to its + # having access to a real pathname and not just an object's Name(). + for a_path in paths: + self._AddPathToDict(pbxbuildfile, a_path) + + # If another PBXBuildFile references this XCFileLikeElement, there's a + # problem. + if xcfilelikeelement in self._files_by_xcfilelikeelement and \ + self._files_by_xcfilelikeelement[xcfilelikeelement] != pbxbuildfile: + raise ValueError, 'Found multiple build files for ' + \ + xcfilelikeelement.Name() + self._files_by_xcfilelikeelement[xcfilelikeelement] = pbxbuildfile + + def AppendBuildFile(self, pbxbuildfile, path=None): + # Callers should use this instead of calling + # AppendProperty('files', pbxbuildfile) directly because this function + # maintains the object's dicts. Better yet, callers can just call AddFile + # with a pathname and not worry about building their own PBXBuildFile + # objects. + self.AppendProperty('files', pbxbuildfile) + self._AddBuildFileToDicts(pbxbuildfile, path) + + def AddFile(self, path, settings=None): + (file_group, hierarchical) = self.FileGroup(path) + file_ref = file_group.AddOrGetFileByPath(path, hierarchical) + + if file_ref in self._files_by_xcfilelikeelement and \ + isinstance(file_ref, PBXVariantGroup): + # There's already a PBXBuildFile in this phase corresponding to the + # PBXVariantGroup. path just provides a new variant that belongs to + # the group. Add the path to the dict. + pbxbuildfile = self._files_by_xcfilelikeelement[file_ref] + self._AddBuildFileToDicts(pbxbuildfile, path) + else: + # Add a new PBXBuildFile to get file_ref into the phase. + if settings is None: + pbxbuildfile = PBXBuildFile({'fileRef': file_ref}) + else: + pbxbuildfile = PBXBuildFile({'fileRef': file_ref, 'settings': settings}) + self.AppendBuildFile(pbxbuildfile, path) + + +class PBXHeadersBuildPhase(XCBuildPhase): + # No additions to the schema relative to XCBuildPhase. + + def Name(self): + return 'Headers' + + def FileGroup(self, path): + return self.PBXProjectAncestor().RootGroupForPath(path) + + +class PBXResourcesBuildPhase(XCBuildPhase): + # No additions to the schema relative to XCBuildPhase. + + def Name(self): + return 'Resources' + + def FileGroup(self, path): + return self.PBXProjectAncestor().RootGroupForPath(path) + + +class PBXSourcesBuildPhase(XCBuildPhase): + # No additions to the schema relative to XCBuildPhase. + + def Name(self): + return 'Sources' + + def FileGroup(self, path): + return self.PBXProjectAncestor().RootGroupForPath(path) + + +class PBXFrameworksBuildPhase(XCBuildPhase): + # No additions to the schema relative to XCBuildPhase. + + def Name(self): + return 'Frameworks' + + def FileGroup(self, path): + (root, ext) = posixpath.splitext(path) + if ext != '': + ext = ext[1:].lower() + if ext == 'o': + # .o files are added to Xcode Frameworks phases, but conceptually aren't + # frameworks, they're more like sources or intermediates. Redirect them + # to show up in one of those other groups. + return self.PBXProjectAncestor().RootGroupForPath(path) + else: + return (self.PBXProjectAncestor().FrameworksGroup(), False) + + +class PBXShellScriptBuildPhase(XCBuildPhase): + _schema = XCBuildPhase._schema.copy() + _schema.update({ + 'inputPaths': [1, str, 0, 1, []], + 'name': [0, str, 0, 0], + 'outputPaths': [1, str, 0, 1, []], + 'shellPath': [0, str, 0, 1, '/bin/sh'], + 'shellScript': [0, str, 0, 1], + 'showEnvVarsInLog': [0, int, 0, 0], + }) + + def Name(self): + if 'name' in self._properties: + return self._properties['name'] + + return 'ShellScript' + + +class PBXCopyFilesBuildPhase(XCBuildPhase): + _schema = XCBuildPhase._schema.copy() + _schema.update({ + 'dstPath': [0, str, 0, 1], + 'dstSubfolderSpec': [0, int, 0, 1], + 'name': [0, str, 0, 0], + }) + + # path_tree_re matches "$(DIR)/path" or just "$(DIR)". Match group 1 is + # "DIR", match group 3 is "path" or None. + path_tree_re = re.compile('^\\$\\((.*)\\)(/(.*)|)$') + + # path_tree_to_subfolder maps names of Xcode variables to the associated + # dstSubfolderSpec property value used in a PBXCopyFilesBuildPhase object. + path_tree_to_subfolder = { + 'BUILT_PRODUCTS_DIR': 16, # Products Directory + # Other types that can be chosen via the Xcode UI. + # TODO(mark): Map Xcode variable names to these. + # : 1, # Wrapper + # : 6, # Executables: 6 + # : 7, # Resources + # : 15, # Java Resources + # : 10, # Frameworks + # : 11, # Shared Frameworks + # : 12, # Shared Support + # : 13, # PlugIns + } + + def Name(self): + if 'name' in self._properties: + return self._properties['name'] + + return 'CopyFiles' + + def FileGroup(self, path): + return self.PBXProjectAncestor().RootGroupForPath(path) + + def SetDestination(self, path): + """Set the dstSubfolderSpec and dstPath properties from path. + + path may be specified in the same notation used for XCHierarchicalElements, + specifically, "$(DIR)/path". + """ + + path_tree_match = self.path_tree_re.search(path) + if path_tree_match: + # Everything else needs to be relative to an Xcode variable. + path_tree = path_tree_match.group(1) + relative_path = path_tree_match.group(3) + + if path_tree in self.path_tree_to_subfolder: + subfolder = self.path_tree_to_subfolder[path_tree] + if relative_path is None: + relative_path = '' + else: + # The path starts with an unrecognized Xcode variable + # name like $(SRCROOT). Xcode will still handle this + # as an "absolute path" that starts with the variable. + subfolder = 0 + relative_path = path + elif path.startswith('/'): + # Special case. Absolute paths are in dstSubfolderSpec 0. + subfolder = 0 + relative_path = path[1:] + else: + raise ValueError, 'Can\'t use path %s in a %s' % \ + (path, self.__class__.__name__) + + self._properties['dstPath'] = relative_path + self._properties['dstSubfolderSpec'] = subfolder + + +class PBXBuildRule(XCObject): + _schema = XCObject._schema.copy() + _schema.update({ + 'compilerSpec': [0, str, 0, 1], + 'filePatterns': [0, str, 0, 0], + 'fileType': [0, str, 0, 1], + 'isEditable': [0, int, 0, 1, 1], + 'outputFiles': [1, str, 0, 1, []], + 'script': [0, str, 0, 0], + }) + + def Name(self): + # Not very inspired, but it's what Xcode uses. + return self.__class__.__name__ + + def Hashables(self): + # super + hashables = XCObject.Hashables(self) + + # Use the hashables of the weak objects that this object refers to. + hashables.append(self._properties['fileType']) + if 'filePatterns' in self._properties: + hashables.append(self._properties['filePatterns']) + return hashables + + +class PBXContainerItemProxy(XCObject): + # When referencing an item in this project file, containerPortal is the + # PBXProject root object of this project file. When referencing an item in + # another project file, containerPortal is a PBXFileReference identifying + # the other project file. + # + # When serving as a proxy to an XCTarget (in this project file or another), + # proxyType is 1. When serving as a proxy to a PBXFileReference (in another + # project file), proxyType is 2. Type 2 is used for references to the + # producs of the other project file's targets. + # + # Xcode is weird about remoteGlobalIDString. Usually, it's printed without + # a comment, indicating that it's tracked internally simply as a string, but + # sometimes it's printed with a comment (usually when the object is initially + # created), indicating that it's tracked as a project file object at least + # sometimes. This module always tracks it as an object, but contains a hack + # to prevent it from printing the comment in the project file output. See + # _XCKVPrint. + _schema = XCObject._schema.copy() + _schema.update({ + 'containerPortal': [0, XCContainerPortal, 0, 1], + 'proxyType': [0, int, 0, 1], + 'remoteGlobalIDString': [0, XCRemoteObject, 0, 1], + 'remoteInfo': [0, str, 0, 1], + }) + + def __repr__(self): + props = self._properties + name = '%s.gyp:%s' % (props['containerPortal'].Name(), props['remoteInfo']) + return '<%s %r at 0x%x>' % (self.__class__.__name__, name, id(self)) + + def Name(self): + # Admittedly not the best name, but it's what Xcode uses. + return self.__class__.__name__ + + def Hashables(self): + # super + hashables = XCObject.Hashables(self) + + # Use the hashables of the weak objects that this object refers to. + hashables.extend(self._properties['containerPortal'].Hashables()) + hashables.extend(self._properties['remoteGlobalIDString'].Hashables()) + return hashables + + +class PBXTargetDependency(XCObject): + # The "target" property accepts an XCTarget object, and obviously not + # NoneType. But XCTarget is defined below, so it can't be put into the + # schema yet. The definition of PBXTargetDependency can't be moved below + # XCTarget because XCTarget's own schema references PBXTargetDependency. + # Python doesn't deal well with this circular relationship, and doesn't have + # a real way to do forward declarations. To work around, the type of + # the "target" property is reset below, after XCTarget is defined. + # + # At least one of "name" and "target" is required. + _schema = XCObject._schema.copy() + _schema.update({ + 'name': [0, str, 0, 0], + 'target': [0, None.__class__, 0, 0], + 'targetProxy': [0, PBXContainerItemProxy, 1, 1], + }) + + def __repr__(self): + name = self._properties.get('name') or self._properties['target'].Name() + return '<%s %r at 0x%x>' % (self.__class__.__name__, name, id(self)) + + def Name(self): + # Admittedly not the best name, but it's what Xcode uses. + return self.__class__.__name__ + + def Hashables(self): + # super + hashables = XCObject.Hashables(self) + + # Use the hashables of the weak objects that this object refers to. + hashables.extend(self._properties['targetProxy'].Hashables()) + return hashables + + +class PBXReferenceProxy(XCFileLikeElement): + _schema = XCFileLikeElement._schema.copy() + _schema.update({ + 'fileType': [0, str, 0, 1], + 'path': [0, str, 0, 1], + 'remoteRef': [0, PBXContainerItemProxy, 1, 1], + }) + + +class XCTarget(XCRemoteObject): + # An XCTarget is really just an XCObject, the XCRemoteObject thing is just + # to allow PBXProject to be used in the remoteGlobalIDString property of + # PBXContainerItemProxy. + # + # Setting a "name" property at instantiation may also affect "productName", + # which may in turn affect the "PRODUCT_NAME" build setting in children of + # "buildConfigurationList". See __init__ below. + _schema = XCRemoteObject._schema.copy() + _schema.update({ + 'buildConfigurationList': [0, XCConfigurationList, 1, 1, + XCConfigurationList()], + 'buildPhases': [1, XCBuildPhase, 1, 1, []], + 'dependencies': [1, PBXTargetDependency, 1, 1, []], + 'name': [0, str, 0, 1], + 'productName': [0, str, 0, 1], + }) + + def __init__(self, properties=None, id=None, parent=None, + force_outdir=None, force_prefix=None, force_extension=None): + # super + XCRemoteObject.__init__(self, properties, id, parent) + + # Set up additional defaults not expressed in the schema. If a "name" + # property was supplied, set "productName" if it is not present. Also set + # the "PRODUCT_NAME" build setting in each configuration, but only if + # the setting is not present in any build configuration. + if 'name' in self._properties: + if not 'productName' in self._properties: + self.SetProperty('productName', self._properties['name']) + + if 'productName' in self._properties: + if 'buildConfigurationList' in self._properties: + configs = self._properties['buildConfigurationList'] + if configs.HasBuildSetting('PRODUCT_NAME') == 0: + configs.SetBuildSetting('PRODUCT_NAME', + self._properties['productName']) + + def AddDependency(self, other): + pbxproject = self.PBXProjectAncestor() + other_pbxproject = other.PBXProjectAncestor() + if pbxproject == other_pbxproject: + # Add a dependency to another target in the same project file. + container = PBXContainerItemProxy({'containerPortal': pbxproject, + 'proxyType': 1, + 'remoteGlobalIDString': other, + 'remoteInfo': other.Name()}) + dependency = PBXTargetDependency({'target': other, + 'targetProxy': container}) + self.AppendProperty('dependencies', dependency) + else: + # Add a dependency to a target in a different project file. + other_project_ref = \ + pbxproject.AddOrGetProjectReference(other_pbxproject)[1] + container = PBXContainerItemProxy({ + 'containerPortal': other_project_ref, + 'proxyType': 1, + 'remoteGlobalIDString': other, + 'remoteInfo': other.Name(), + }) + dependency = PBXTargetDependency({'name': other.Name(), + 'targetProxy': container}) + self.AppendProperty('dependencies', dependency) + + # Proxy all of these through to the build configuration list. + + def ConfigurationNamed(self, name): + return self._properties['buildConfigurationList'].ConfigurationNamed(name) + + def DefaultConfiguration(self): + return self._properties['buildConfigurationList'].DefaultConfiguration() + + def HasBuildSetting(self, key): + return self._properties['buildConfigurationList'].HasBuildSetting(key) + + def GetBuildSetting(self, key): + return self._properties['buildConfigurationList'].GetBuildSetting(key) + + def SetBuildSetting(self, key, value): + return self._properties['buildConfigurationList'].SetBuildSetting(key, \ + value) + + def AppendBuildSetting(self, key, value): + return self._properties['buildConfigurationList'].AppendBuildSetting(key, \ + value) + + def DelBuildSetting(self, key): + return self._properties['buildConfigurationList'].DelBuildSetting(key) + + +# Redefine the type of the "target" property. See PBXTargetDependency._schema +# above. +PBXTargetDependency._schema['target'][1] = XCTarget + + +class PBXNativeTarget(XCTarget): + # buildPhases is overridden in the schema to be able to set defaults. + # + # NOTE: Contrary to most objects, it is advisable to set parent when + # constructing PBXNativeTarget. A parent of an XCTarget must be a PBXProject + # object. A parent reference is required for a PBXNativeTarget during + # construction to be able to set up the target defaults for productReference, + # because a PBXBuildFile object must be created for the target and it must + # be added to the PBXProject's mainGroup hierarchy. + _schema = XCTarget._schema.copy() + _schema.update({ + 'buildPhases': [1, XCBuildPhase, 1, 1, + [PBXSourcesBuildPhase(), PBXFrameworksBuildPhase()]], + 'buildRules': [1, PBXBuildRule, 1, 1, []], + 'productReference': [0, PBXFileReference, 0, 1], + 'productType': [0, str, 0, 1], + }) + + # Mapping from Xcode product-types to settings. The settings are: + # filetype : used for explicitFileType in the project file + # prefix : the prefix for the file name + # suffix : the suffix for the filen ame + _product_filetypes = { + 'com.apple.product-type.application': ['wrapper.application', + '', '.app'], + 'com.apple.product-type.bundle': ['wrapper.cfbundle', + '', '.bundle'], + 'com.apple.product-type.framework': ['wrapper.framework', + '', '.framework'], + 'com.apple.product-type.library.dynamic': ['compiled.mach-o.dylib', + 'lib', '.dylib'], + 'com.apple.product-type.library.static': ['archive.ar', + 'lib', '.a'], + 'com.apple.product-type.tool': ['compiled.mach-o.executable', + '', ''], + 'com.googlecode.gyp.xcode.bundle': ['compiled.mach-o.dylib', + '', '.so'], + } + + def __init__(self, properties=None, id=None, parent=None, + force_outdir=None, force_prefix=None, force_extension=None): + # super + XCTarget.__init__(self, properties, id, parent) + + if 'productName' in self._properties and \ + 'productType' in self._properties and \ + not 'productReference' in self._properties and \ + self._properties['productType'] in self._product_filetypes: + products_group = None + pbxproject = self.PBXProjectAncestor() + if pbxproject != None: + products_group = pbxproject.ProductsGroup() + + if products_group != None: + (filetype, prefix, suffix) = \ + self._product_filetypes[self._properties['productType']] + # Xcode does not have a distinct type for loadable modules that are + # pure BSD targets (not in a bundle wrapper). GYP allows such modules + # to be specified by setting a target type to loadable_module without + # having mac_bundle set. These are mapped to the pseudo-product type + # com.googlecode.gyp.xcode.bundle. + # + # By picking up this special type and converting it to a dynamic + # library (com.apple.product-type.library.dynamic) with fix-ups, + # single-file loadable modules can be produced. + # + # MACH_O_TYPE is changed to mh_bundle to produce the proper file type + # (as opposed to mh_dylib). In order for linking to succeed, + # DYLIB_CURRENT_VERSION and DYLIB_COMPATIBILITY_VERSION must be + # cleared. They are meaningless for type mh_bundle. + # + # Finally, the .so extension is forcibly applied over the default + # (.dylib), unless another forced extension is already selected. + # .dylib is plainly wrong, and .bundle is used by loadable_modules in + # bundle wrappers (com.apple.product-type.bundle). .so seems an odd + # choice because it's used as the extension on many other systems that + # don't distinguish between linkable shared libraries and non-linkable + # loadable modules, but there's precedent: Python loadable modules on + # Mac OS X use an .so extension. + if self._properties['productType'] == 'com.googlecode.gyp.xcode.bundle': + self._properties['productType'] = \ + 'com.apple.product-type.library.dynamic' + self.SetBuildSetting('MACH_O_TYPE', 'mh_bundle') + self.SetBuildSetting('DYLIB_CURRENT_VERSION', '') + self.SetBuildSetting('DYLIB_COMPATIBILITY_VERSION', '') + if force_extension is None: + force_extension = suffix[1:] + + if force_extension is not None: + # If it's a wrapper (bundle), set WRAPPER_EXTENSION. + if filetype.startswith('wrapper.'): + self.SetBuildSetting('WRAPPER_EXTENSION', force_extension) + else: + # Extension override. + suffix = '.' + force_extension + self.SetBuildSetting('EXECUTABLE_EXTENSION', force_extension) + + if filetype.startswith('compiled.mach-o.executable'): + product_name = self._properties['productName'] + product_name += suffix + suffix = '' + self.SetProperty('productName', product_name) + self.SetBuildSetting('PRODUCT_NAME', product_name) + + # Xcode handles most prefixes based on the target type, however there + # are exceptions. If a "BSD Dynamic Library" target is added in the + # Xcode UI, Xcode sets EXECUTABLE_PREFIX. This check duplicates that + # behavior. + if force_prefix is not None: + prefix = force_prefix + if filetype.startswith('wrapper.'): + self.SetBuildSetting('WRAPPER_PREFIX', prefix) + else: + self.SetBuildSetting('EXECUTABLE_PREFIX', prefix) + + if force_outdir is not None: + self.SetBuildSetting('TARGET_BUILD_DIR', force_outdir) + + # TODO(tvl): Remove the below hack. + # http://code.google.com/p/gyp/issues/detail?id=122 + + # Some targets include the prefix in the target_name. These targets + # really should just add a product_name setting that doesn't include + # the prefix. For example: + # target_name = 'libevent', product_name = 'event' + # This check cleans up for them. + product_name = self._properties['productName'] + prefix_len = len(prefix) + if prefix_len and (product_name[:prefix_len] == prefix): + product_name = product_name[prefix_len:] + self.SetProperty('productName', product_name) + self.SetBuildSetting('PRODUCT_NAME', product_name) + + ref_props = { + 'explicitFileType': filetype, + 'includeInIndex': 0, + 'path': prefix + product_name + suffix, + 'sourceTree': 'BUILT_PRODUCTS_DIR', + } + file_ref = PBXFileReference(ref_props) + products_group.AppendChild(file_ref) + self.SetProperty('productReference', file_ref) + + def GetBuildPhaseByType(self, type): + if not 'buildPhases' in self._properties: + return None + + the_phase = None + for phase in self._properties['buildPhases']: + if isinstance(phase, type): + # Some phases may be present in multiples in a well-formed project file, + # but phases like PBXSourcesBuildPhase may only be present singly, and + # this function is intended as an aid to GetBuildPhaseByType. Loop + # over the entire list of phases and assert if more than one of the + # desired type is found. + assert the_phase is None + the_phase = phase + + return the_phase + + def HeadersPhase(self): + headers_phase = self.GetBuildPhaseByType(PBXHeadersBuildPhase) + if headers_phase is None: + headers_phase = PBXHeadersBuildPhase() + + # The headers phase should come before the resources, sources, and + # frameworks phases, if any. + insert_at = len(self._properties['buildPhases']) + for index in xrange(0, len(self._properties['buildPhases'])): + phase = self._properties['buildPhases'][index] + if isinstance(phase, PBXResourcesBuildPhase) or \ + isinstance(phase, PBXSourcesBuildPhase) or \ + isinstance(phase, PBXFrameworksBuildPhase): + insert_at = index + break + + self._properties['buildPhases'].insert(insert_at, headers_phase) + headers_phase.parent = self + + return headers_phase + + def ResourcesPhase(self): + resources_phase = self.GetBuildPhaseByType(PBXResourcesBuildPhase) + if resources_phase is None: + resources_phase = PBXResourcesBuildPhase() + + # The resources phase should come before the sources and frameworks + # phases, if any. + insert_at = len(self._properties['buildPhases']) + for index in xrange(0, len(self._properties['buildPhases'])): + phase = self._properties['buildPhases'][index] + if isinstance(phase, PBXSourcesBuildPhase) or \ + isinstance(phase, PBXFrameworksBuildPhase): + insert_at = index + break + + self._properties['buildPhases'].insert(insert_at, resources_phase) + resources_phase.parent = self + + return resources_phase + + def SourcesPhase(self): + sources_phase = self.GetBuildPhaseByType(PBXSourcesBuildPhase) + if sources_phase is None: + sources_phase = PBXSourcesBuildPhase() + self.AppendProperty('buildPhases', sources_phase) + + return sources_phase + + def FrameworksPhase(self): + frameworks_phase = self.GetBuildPhaseByType(PBXFrameworksBuildPhase) + if frameworks_phase is None: + frameworks_phase = PBXFrameworksBuildPhase() + self.AppendProperty('buildPhases', frameworks_phase) + + return frameworks_phase + + def AddDependency(self, other): + # super + XCTarget.AddDependency(self, other) + + static_library_type = 'com.apple.product-type.library.static' + shared_library_type = 'com.apple.product-type.library.dynamic' + framework_type = 'com.apple.product-type.framework' + if isinstance(other, PBXNativeTarget) and \ + 'productType' in self._properties and \ + self._properties['productType'] != static_library_type and \ + 'productType' in other._properties and \ + (other._properties['productType'] == static_library_type or \ + ((other._properties['productType'] == shared_library_type or \ + other._properties['productType'] == framework_type) and \ + ((not other.HasBuildSetting('MACH_O_TYPE')) or + other.GetBuildSetting('MACH_O_TYPE') != 'mh_bundle'))): + + file_ref = other.GetProperty('productReference') + + pbxproject = self.PBXProjectAncestor() + other_pbxproject = other.PBXProjectAncestor() + if pbxproject != other_pbxproject: + other_project_product_group = \ + pbxproject.AddOrGetProjectReference(other_pbxproject)[0] + file_ref = other_project_product_group.GetChildByRemoteObject(file_ref) + + self.FrameworksPhase().AppendProperty('files', + PBXBuildFile({'fileRef': file_ref})) + + +class PBXAggregateTarget(XCTarget): + pass + + +class PBXProject(XCContainerPortal): + # A PBXProject is really just an XCObject, the XCContainerPortal thing is + # just to allow PBXProject to be used in the containerPortal property of + # PBXContainerItemProxy. + """ + + Attributes: + path: "sample.xcodeproj". TODO(mark) Document me! + _other_pbxprojects: A dictionary, keyed by other PBXProject objects. Each + value is a reference to the dict in the + projectReferences list associated with the keyed + PBXProject. + """ + + _schema = XCContainerPortal._schema.copy() + _schema.update({ + 'attributes': [0, dict, 0, 0], + 'buildConfigurationList': [0, XCConfigurationList, 1, 1, + XCConfigurationList()], + 'compatibilityVersion': [0, str, 0, 1, 'Xcode 3.2'], + 'hasScannedForEncodings': [0, int, 0, 1, 1], + 'mainGroup': [0, PBXGroup, 1, 1, PBXGroup()], + 'projectDirPath': [0, str, 0, 1, ''], + 'projectReferences': [1, dict, 0, 0], + 'projectRoot': [0, str, 0, 1, ''], + 'targets': [1, XCTarget, 1, 1, []], + }) + + def __init__(self, properties=None, id=None, parent=None, path=None): + self.path = path + self._other_pbxprojects = {} + # super + return XCContainerPortal.__init__(self, properties, id, parent) + + def Name(self): + name = self.path + if name[-10:] == '.xcodeproj': + name = name[:-10] + return posixpath.basename(name) + + def Path(self): + return self.path + + def Comment(self): + return 'Project object' + + def Children(self): + # super + children = XCContainerPortal.Children(self) + + # Add children that the schema doesn't know about. Maybe there's a more + # elegant way around this, but this is the only case where we need to own + # objects in a dictionary (that is itself in a list), and three lines for + # a one-off isn't that big a deal. + if 'projectReferences' in self._properties: + for reference in self._properties['projectReferences']: + children.append(reference['ProductGroup']) + + return children + + def PBXProjectAncestor(self): + return self + + def _GroupByName(self, name): + if not 'mainGroup' in self._properties: + self.SetProperty('mainGroup', PBXGroup()) + + main_group = self._properties['mainGroup'] + group = main_group.GetChildByName(name) + if group is None: + group = PBXGroup({'name': name}) + main_group.AppendChild(group) + + return group + + # SourceGroup and ProductsGroup are created by default in Xcode's own + # templates. + def SourceGroup(self): + return self._GroupByName('Source') + + def ProductsGroup(self): + return self._GroupByName('Products') + + # IntermediatesGroup is used to collect source-like files that are generated + # by rules or script phases and are placed in intermediate directories such + # as DerivedSources. + def IntermediatesGroup(self): + return self._GroupByName('Intermediates') + + # FrameworksGroup and ProjectsGroup are top-level groups used to collect + # frameworks and projects. + def FrameworksGroup(self): + return self._GroupByName('Frameworks') + + def ProjectsGroup(self): + return self._GroupByName('Projects') + + def RootGroupForPath(self, path): + """Returns a PBXGroup child of this object to which path should be added. + + This method is intended to choose between SourceGroup and + IntermediatesGroup on the basis of whether path is present in a source + directory or an intermediates directory. For the purposes of this + determination, any path located within a derived file directory such as + PROJECT_DERIVED_FILE_DIR is treated as being in an intermediates + directory. + + The returned value is a two-element tuple. The first element is the + PBXGroup, and the second element specifies whether that group should be + organized hierarchically (True) or as a single flat list (False). + """ + + # TODO(mark): make this a class variable and bind to self on call? + # Also, this list is nowhere near exhaustive. + # INTERMEDIATE_DIR and SHARED_INTERMEDIATE_DIR are used by + # gyp.generator.xcode. There should probably be some way for that module + # to push the names in, rather than having to hard-code them here. + source_tree_groups = { + 'DERIVED_FILE_DIR': (self.IntermediatesGroup, True), + 'INTERMEDIATE_DIR': (self.IntermediatesGroup, True), + 'PROJECT_DERIVED_FILE_DIR': (self.IntermediatesGroup, True), + 'SHARED_INTERMEDIATE_DIR': (self.IntermediatesGroup, True), + } + + (source_tree, path) = SourceTreeAndPathFromPath(path) + if source_tree != None and source_tree in source_tree_groups: + (group_func, hierarchical) = source_tree_groups[source_tree] + group = group_func() + return (group, hierarchical) + + # TODO(mark): make additional choices based on file extension. + + return (self.SourceGroup(), True) + + def AddOrGetFileInRootGroup(self, path): + """Returns a PBXFileReference corresponding to path in the correct group + according to RootGroupForPath's heuristics. + + If an existing PBXFileReference for path exists, it will be returned. + Otherwise, one will be created and returned. + """ + + (group, hierarchical) = self.RootGroupForPath(path) + return group.AddOrGetFileByPath(path, hierarchical) + + def RootGroupsTakeOverOnlyChildren(self, recurse=False): + """Calls TakeOverOnlyChild for all groups in the main group.""" + + for group in self._properties['mainGroup']._properties['children']: + if isinstance(group, PBXGroup): + group.TakeOverOnlyChild(recurse) + + def SortGroups(self): + # Sort the children of the mainGroup (like "Source" and "Products") + # according to their defined order. + self._properties['mainGroup']._properties['children'] = \ + sorted(self._properties['mainGroup']._properties['children'], + cmp=lambda x,y: x.CompareRootGroup(y)) + + # Sort everything else by putting group before files, and going + # alphabetically by name within sections of groups and files. SortGroup + # is recursive. + for group in self._properties['mainGroup']._properties['children']: + if not isinstance(group, PBXGroup): + continue + + if group.Name() == 'Products': + # The Products group is a special case. Instead of sorting + # alphabetically, sort things in the order of the targets that + # produce the products. To do this, just build up a new list of + # products based on the targets. + products = [] + for target in self._properties['targets']: + if not isinstance(target, PBXNativeTarget): + continue + product = target._properties['productReference'] + # Make sure that the product is already in the products group. + assert product in group._properties['children'] + products.append(product) + + # Make sure that this process doesn't miss anything that was already + # in the products group. + assert len(products) == len(group._properties['children']) + group._properties['children'] = products + else: + group.SortGroup() + + def AddOrGetProjectReference(self, other_pbxproject): + """Add a reference to another project file (via PBXProject object) to this + one. + + Returns [ProductGroup, ProjectRef]. ProductGroup is a PBXGroup object in + this project file that contains a PBXReferenceProxy object for each + product of each PBXNativeTarget in the other project file. ProjectRef is + a PBXFileReference to the other project file. + + If this project file already references the other project file, the + existing ProductGroup and ProjectRef are returned. The ProductGroup will + still be updated if necessary. + """ + + if not 'projectReferences' in self._properties: + self._properties['projectReferences'] = [] + + product_group = None + project_ref = None + + if not other_pbxproject in self._other_pbxprojects: + # This project file isn't yet linked to the other one. Establish the + # link. + product_group = PBXGroup({'name': 'Products'}) + + # ProductGroup is strong. + product_group.parent = self + + # There's nothing unique about this PBXGroup, and if left alone, it will + # wind up with the same set of hashables as all other PBXGroup objects + # owned by the projectReferences list. Add the hashables of the + # remote PBXProject that it's related to. + product_group._hashables.extend(other_pbxproject.Hashables()) + + # The other project reports its path as relative to the same directory + # that this project's path is relative to. The other project's path + # is not necessarily already relative to this project. Figure out the + # pathname that this project needs to use to refer to the other one. + this_path = posixpath.dirname(self.Path()) + projectDirPath = self.GetProperty('projectDirPath') + if projectDirPath: + if posixpath.isabs(projectDirPath[0]): + this_path = projectDirPath + else: + this_path = posixpath.join(this_path, projectDirPath) + other_path = gyp.common.RelativePath(other_pbxproject.Path(), this_path) + + # ProjectRef is weak (it's owned by the mainGroup hierarchy). + project_ref = PBXFileReference({ + 'lastKnownFileType': 'wrapper.pb-project', + 'path': other_path, + 'sourceTree': 'SOURCE_ROOT', + }) + self.ProjectsGroup().AppendChild(project_ref) + + ref_dict = {'ProductGroup': product_group, 'ProjectRef': project_ref} + self._other_pbxprojects[other_pbxproject] = ref_dict + self.AppendProperty('projectReferences', ref_dict) + + # Xcode seems to sort this list case-insensitively + self._properties['projectReferences'] = \ + sorted(self._properties['projectReferences'], cmp=lambda x,y: + cmp(x['ProjectRef'].Name().lower(), + y['ProjectRef'].Name().lower())) + else: + # The link already exists. Pull out the relevnt data. + project_ref_dict = self._other_pbxprojects[other_pbxproject] + product_group = project_ref_dict['ProductGroup'] + project_ref = project_ref_dict['ProjectRef'] + + self._SetUpProductReferences(other_pbxproject, product_group, project_ref) + + return [product_group, project_ref] + + def _SetUpProductReferences(self, other_pbxproject, product_group, + project_ref): + # TODO(mark): This only adds references to products in other_pbxproject + # when they don't exist in this pbxproject. Perhaps it should also + # remove references from this pbxproject that are no longer present in + # other_pbxproject. Perhaps it should update various properties if they + # change. + for target in other_pbxproject._properties['targets']: + if not isinstance(target, PBXNativeTarget): + continue + + other_fileref = target._properties['productReference'] + if product_group.GetChildByRemoteObject(other_fileref) is None: + # Xcode sets remoteInfo to the name of the target and not the name + # of its product, despite this proxy being a reference to the product. + container_item = PBXContainerItemProxy({ + 'containerPortal': project_ref, + 'proxyType': 2, + 'remoteGlobalIDString': other_fileref, + 'remoteInfo': target.Name() + }) + # TODO(mark): Does sourceTree get copied straight over from the other + # project? Can the other project ever have lastKnownFileType here + # instead of explicitFileType? (Use it if so?) Can path ever be + # unset? (I don't think so.) Can other_fileref have name set, and + # does it impact the PBXReferenceProxy if so? These are the questions + # that perhaps will be answered one day. + reference_proxy = PBXReferenceProxy({ + 'fileType': other_fileref._properties['explicitFileType'], + 'path': other_fileref._properties['path'], + 'sourceTree': other_fileref._properties['sourceTree'], + 'remoteRef': container_item, + }) + + product_group.AppendChild(reference_proxy) + + def SortRemoteProductReferences(self): + # For each remote project file, sort the associated ProductGroup in the + # same order that the targets are sorted in the remote project file. This + # is the sort order used by Xcode. + + def CompareProducts(x, y, remote_products): + # x and y are PBXReferenceProxy objects. Go through their associated + # PBXContainerItem to get the remote PBXFileReference, which will be + # present in the remote_products list. + x_remote = x._properties['remoteRef']._properties['remoteGlobalIDString'] + y_remote = y._properties['remoteRef']._properties['remoteGlobalIDString'] + x_index = remote_products.index(x_remote) + y_index = remote_products.index(y_remote) + + # Use the order of each remote PBXFileReference in remote_products to + # determine the sort order. + return cmp(x_index, y_index) + + for other_pbxproject, ref_dict in self._other_pbxprojects.iteritems(): + # Build up a list of products in the remote project file, ordered the + # same as the targets that produce them. + remote_products = [] + for target in other_pbxproject._properties['targets']: + if not isinstance(target, PBXNativeTarget): + continue + remote_products.append(target._properties['productReference']) + + # Sort the PBXReferenceProxy children according to the list of remote + # products. + product_group = ref_dict['ProductGroup'] + product_group._properties['children'] = sorted( + product_group._properties['children'], + cmp=lambda x, y: CompareProducts(x, y, remote_products)) + + +class XCProjectFile(XCObject): + _schema = XCObject._schema.copy() + _schema.update({ + 'archiveVersion': [0, int, 0, 1, 1], + 'classes': [0, dict, 0, 1, {}], + 'objectVersion': [0, int, 0, 1, 45], + 'rootObject': [0, PBXProject, 1, 1], + }) + + def SetXcodeVersion(self, version): + version_to_object_version = { + '2.4': 45, + '3.0': 45, + '3.1': 45, + '3.2': 46, + } + if not version in version_to_object_version: + supported_str = ', '.join(sorted(version_to_object_version.keys())) + raise Exception( + 'Unsupported Xcode version %s (supported: %s)' % + ( version, supported_str ) ) + compatibility_version = 'Xcode %s' % version + self._properties['rootObject'].SetProperty('compatibilityVersion', + compatibility_version) + self.SetProperty('objectVersion', version_to_object_version[version]); + + def ComputeIDs(self, recursive=True, overwrite=True, hash=None): + # Although XCProjectFile is implemented here as an XCObject, it's not a + # proper object in the Xcode sense, and it certainly doesn't have its own + # ID. Pass through an attempt to update IDs to the real root object. + if recursive: + self._properties['rootObject'].ComputeIDs(recursive, overwrite, hash) + + def Print(self, file=sys.stdout): + self.VerifyHasRequiredProperties() + + # Add the special "objects" property, which will be caught and handled + # separately during printing. This structure allows a fairly standard + # loop do the normal printing. + self._properties['objects'] = {} + self._XCPrint(file, 0, '// !$*UTF8*$!\n') + if self._should_print_single_line: + self._XCPrint(file, 0, '{ ') + else: + self._XCPrint(file, 0, '{\n') + for property, value in sorted(self._properties.iteritems(), + cmp=lambda x, y: cmp(x, y)): + if property == 'objects': + self._PrintObjects(file) + else: + self._XCKVPrint(file, 1, property, value) + self._XCPrint(file, 0, '}\n') + del self._properties['objects'] + + def _PrintObjects(self, file): + if self._should_print_single_line: + self._XCPrint(file, 0, 'objects = {') + else: + self._XCPrint(file, 1, 'objects = {\n') + + objects_by_class = {} + for object in self.Descendants(): + if object == self: + continue + class_name = object.__class__.__name__ + if not class_name in objects_by_class: + objects_by_class[class_name] = [] + objects_by_class[class_name].append(object) + + for class_name in sorted(objects_by_class): + self._XCPrint(file, 0, '\n') + self._XCPrint(file, 0, '/* Begin ' + class_name + ' section */\n') + for object in sorted(objects_by_class[class_name], + cmp=lambda x, y: cmp(x.id, y.id)): + object.Print(file) + self._XCPrint(file, 0, '/* End ' + class_name + ' section */\n') + + if self._should_print_single_line: + self._XCPrint(file, 0, '}; ') + else: + self._XCPrint(file, 1, '};\n') diff --git a/node-v0.8.14/tools/gyp/pylib/gyp/xml_fix.py b/node-v0.8.14/tools/gyp/pylib/gyp/xml_fix.py new file mode 100644 index 0000000..5de8481 --- /dev/null +++ b/node-v0.8.14/tools/gyp/pylib/gyp/xml_fix.py @@ -0,0 +1,69 @@ +# Copyright (c) 2011 Google Inc. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +"""Applies a fix to CR LF TAB handling in xml.dom. + +Fixes this: http://code.google.com/p/chromium/issues/detail?id=76293 +Working around this: http://bugs.python.org/issue5752 +TODO(bradnelson): Consider dropping this when we drop XP support. +""" + + +import xml.dom.minidom + + +def _Replacement_write_data(writer, data, is_attrib=False): + """Writes datachars to writer.""" + data = data.replace("&", "&").replace("<", "<") + data = data.replace("\"", """).replace(">", ">") + if is_attrib: + data = data.replace( + "\r", " ").replace( + "\n", " ").replace( + "\t", " ") + writer.write(data) + + +def _Replacement_writexml(self, writer, indent="", addindent="", newl=""): + # indent = current indentation + # addindent = indentation to add to higher levels + # newl = newline string + writer.write(indent+"<" + self.tagName) + + attrs = self._get_attributes() + a_names = attrs.keys() + a_names.sort() + + for a_name in a_names: + writer.write(" %s=\"" % a_name) + _Replacement_write_data(writer, attrs[a_name].value, is_attrib=True) + writer.write("\"") + if self.childNodes: + writer.write(">%s" % newl) + for node in self.childNodes: + node.writexml(writer, indent + addindent, addindent, newl) + writer.write("%s%s" % (indent, self.tagName, newl)) + else: + writer.write("/>%s" % newl) + + +class XmlFix(object): + """Object to manage temporary patching of xml.dom.minidom.""" + + def __init__(self): + # Preserve current xml.dom.minidom functions. + self.write_data = xml.dom.minidom._write_data + self.writexml = xml.dom.minidom.Element.writexml + # Inject replacement versions of a function and a method. + xml.dom.minidom._write_data = _Replacement_write_data + xml.dom.minidom.Element.writexml = _Replacement_writexml + + def Cleanup(self): + if self.write_data: + xml.dom.minidom._write_data = self.write_data + xml.dom.minidom.Element.writexml = self.writexml + self.write_data = None + + def __del__(self): + self.Cleanup() diff --git a/node-v0.8.14/tools/gyp/pylintrc b/node-v0.8.14/tools/gyp/pylintrc new file mode 100644 index 0000000..d7c23d2 --- /dev/null +++ b/node-v0.8.14/tools/gyp/pylintrc @@ -0,0 +1,307 @@ +[MASTER] + +# Specify a configuration file. +#rcfile= + +# Python code to execute, usually for sys.path manipulation such as +# pygtk.require(). +#init-hook= + +# Profiled execution. +profile=no + +# Add files or directories to the blacklist. They should be base names, not +# paths. +ignore=CVS + +# Pickle collected data for later comparisons. +persistent=yes + +# List of plugins (as comma separated values of python modules names) to load, +# usually to register additional checkers. +load-plugins= + + +[MESSAGES CONTROL] + +# Enable the message, report, category or checker with the given id(s). You can +# either give multiple identifier separated by comma (,) or put this option +# multiple time. +#enable= + +# Disable the message, report, category or checker with the given id(s). You +# can either give multiple identifier separated by comma (,) or put this option +# multiple time (only on the command line, not in the configuration file where +# it should appear only once). +# C0103: Invalid name "NN" (should match [a-z_][a-z0-9_]{2,30}$) +# C0111: Missing docstring +# C0302: Too many lines in module (NN) +# R0902: Too many instance attributes (N/7) +# R0903: Too few public methods (N/2) +# R0904: Too many public methods (NN/20) +# R0912: Too many branches (NN/12) +# R0913: Too many arguments (N/5) +# R0914: Too many local variables (NN/15) +# R0915: Too many statements (NN/50) +# W0141: Used builtin function 'map' +# W0142: Used * or ** magic +# W0232: Class has no __init__ method +# W0511: TODO +# W0603: Using the global statement +# +# These should be enabled eventually: +# C0112: Empty docstring +# C0301: Line too long (NN/80) +# C0321: More than one statement on single line +# C0322: Operator not preceded by a space +# C0323: Operator not followed by a space +# C0324: Comma not followed by a space +# E0101: Explicit return in __init__ +# E0102: function already defined line NN +# E1002: Use of super on an old style class +# E1101: Instance of 'XX' has no 'YY' member +# E1103: Instance of 'XX' has no 'XX' member (but some types could not be inferred) +# E0602: Undefined variable 'XX' +# F0401: Unable to import 'XX' +# R0201: Method could be a function +# R0801: Similar lines in N files +# W0102: Dangerous default value {} as argument +# W0104: Statement seems to have no effect +# W0105: String statement has no effect +# W0108: Lambda may not be necessary +# W0201: Attribute 'XX' defined outside __init__ +# W0212: Access to a protected member XX of a client class +# W0221: Arguments number differs from overridden method +# W0223: Method 'XX' is abstract in class 'YY' but is not overridden +# W0231: __init__ method from base class 'XX' is not called +# W0301: Unnecessary semicolon +# W0311: Bad indentation. Found NN spaces, expected NN +# W0401: Wildcard import XX +# W0402: Uses of a deprecated module 'string' +# W0403: Relative import 'XX', should be 'YY.XX' +# W0404: Reimport 'XX' (imported line NN) +# W0601: Global variable 'XX' undefined at the module level +# W0602: Using global for 'XX' but no assignment is done +# W0611: Unused import pprint +# W0612: Unused variable 'XX' +# W0613: Unused argument 'XX' +# W0614: Unused import XX from wildcard import +# W0621: Redefining name 'XX' from outer scope (line NN) +# W0622: Redefining built-in 'NN' +# W0631: Using possibly undefined loop variable 'XX' +# W0701: Raising a string exception +# W0702: No exception type(s) specified +disable=C0103,C0111,C0302,R0902,R0903,R0904,R0912,R0913,R0914,R0915,W0141,W0142,W0232,W0511,W0603,C0112,C0301,C0321,C0322,C0323,C0324,E0101,E0102,E1002,E1101,E1103,E0602,F0401,R0201,R0801,W0102,W0104,W0105,W0108,W0201,W0212,W0221,W0223,W0231,W0301,W0311,W0401,W0402,W0403,W0404,W0601,W0602,W0611,W0612,W0613,W0614,W0621,W0622,W0631,W0701,W0702 + + +[REPORTS] + +# Set the output format. Available formats are text, parseable, colorized, msvs +# (visual studio) and html +output-format=text + +# Include message's id in output +include-ids=yes + +# Put messages in a separate file for each module / package specified on the +# command line instead of printing them on stdout. Reports (if any) will be +# written in a file name "pylint_global.[txt|html]". +files-output=no + +# Tells whether to display a full report or only the messages +reports=no + +# Python expression which should return a note less than 10 (10 is the highest +# note). You have access to the variables errors warning, statement which +# respectively contain the number of errors / warnings messages and the total +# number of statements analyzed. This is used by the global evaluation report +# (RP0004). +evaluation=10.0 - ((float(5 * error + warning + refactor + convention) / statement) * 10) + +# Add a comment according to your evaluation note. This is used by the global +# evaluation report (RP0004). +comment=no + + +[VARIABLES] + +# Tells whether we should check for unused import in __init__ files. +init-import=no + +# A regular expression matching the beginning of the name of dummy variables +# (i.e. not used). +dummy-variables-rgx=_|dummy + +# List of additional names supposed to be defined in builtins. Remember that +# you should avoid to define new builtins when possible. +additional-builtins= + + +[TYPECHECK] + +# Tells whether missing members accessed in mixin class should be ignored. A +# mixin class is detected if its name ends with "mixin" (case insensitive). +ignore-mixin-members=yes + +# List of classes names for which member attributes should not be checked +# (useful for classes with attributes dynamically set). +ignored-classes=SQLObject + +# When zope mode is activated, add a predefined set of Zope acquired attributes +# to generated-members. +zope=no + +# List of members which are set dynamically and missed by pylint inference +# system, and so shouldn't trigger E0201 when accessed. Python regular +# expressions are accepted. +generated-members=REQUEST,acl_users,aq_parent + + +[MISCELLANEOUS] + +# List of note tags to take in consideration, separated by a comma. +notes=FIXME,XXX,TODO + + +[SIMILARITIES] + +# Minimum lines number of a similarity. +min-similarity-lines=4 + +# Ignore comments when computing similarities. +ignore-comments=yes + +# Ignore docstrings when computing similarities. +ignore-docstrings=yes + + +[FORMAT] + +# Maximum number of characters on a single line. +max-line-length=80 + +# Maximum number of lines in a module +max-module-lines=1000 + +# String used as indentation unit. This is usually " " (4 spaces) or "\t" (1 +# tab). +indent-string=' ' + + +[BASIC] + +# Required attributes for module, separated by a comma +required-attributes= + +# List of builtins function names that should not be used, separated by a comma +bad-functions=map,filter,apply,input + +# Regular expression which should only match correct module names +module-rgx=(([a-z_][a-z0-9_]*)|([A-Z][a-zA-Z0-9]+))$ + +# Regular expression which should only match correct module level names +const-rgx=(([A-Z_][A-Z0-9_]*)|(__.*__))$ + +# Regular expression which should only match correct class names +class-rgx=[A-Z_][a-zA-Z0-9]+$ + +# Regular expression which should only match correct function names +function-rgx=[a-z_][a-z0-9_]{2,30}$ + +# Regular expression which should only match correct method names +method-rgx=[a-z_][a-z0-9_]{2,30}$ + +# Regular expression which should only match correct instance attribute names +attr-rgx=[a-z_][a-z0-9_]{2,30}$ + +# Regular expression which should only match correct argument names +argument-rgx=[a-z_][a-z0-9_]{2,30}$ + +# Regular expression which should only match correct variable names +variable-rgx=[a-z_][a-z0-9_]{2,30}$ + +# Regular expression which should only match correct list comprehension / +# generator expression variable names +inlinevar-rgx=[A-Za-z_][A-Za-z0-9_]*$ + +# Good variable names which should always be accepted, separated by a comma +good-names=i,j,k,ex,Run,_ + +# Bad variable names which should always be refused, separated by a comma +bad-names=foo,bar,baz,toto,tutu,tata + +# Regular expression which should only match functions or classes name which do +# not require a docstring +no-docstring-rgx=__.*__ + + +[DESIGN] + +# Maximum number of arguments for function / method +max-args=5 + +# Argument names that match this expression will be ignored. Default to name +# with leading underscore +ignored-argument-names=_.* + +# Maximum number of locals for function / method body +max-locals=15 + +# Maximum number of return / yield for function / method body +max-returns=6 + +# Maximum number of branch for function / method body +max-branchs=12 + +# Maximum number of statements in function / method body +max-statements=50 + +# Maximum number of parents for a class (see R0901). +max-parents=7 + +# Maximum number of attributes for a class (see R0902). +max-attributes=7 + +# Minimum number of public methods for a class (see R0903). +min-public-methods=2 + +# Maximum number of public methods for a class (see R0904). +max-public-methods=20 + + +[CLASSES] + +# List of interface methods to ignore, separated by a comma. This is used for +# instance to not check methods defines in Zope's Interface base class. +ignore-iface-methods=isImplementedBy,deferred,extends,names,namesAndDescriptions,queryDescriptionFor,getBases,getDescriptionFor,getDoc,getName,getTaggedValue,getTaggedValueTags,isEqualOrExtendedBy,setTaggedValue,isImplementedByInstancesOf,adaptWith,is_implemented_by + +# List of method names used to declare (i.e. assign) instance attributes. +defining-attr-methods=__init__,__new__,setUp + +# List of valid names for the first argument in a class method. +valid-classmethod-first-arg=cls + + +[IMPORTS] + +# Deprecated modules which should not be used, separated by a comma +deprecated-modules=regsub,string,TERMIOS,Bastion,rexec + +# Create a graph of every (i.e. internal and external) dependencies in the +# given file (report RP0402 must not be disabled) +import-graph= + +# Create a graph of external dependencies in the given file (report RP0402 must +# not be disabled) +ext-import-graph= + +# Create a graph of internal dependencies in the given file (report RP0402 must +# not be disabled) +int-import-graph= + + +[EXCEPTIONS] + +# Exceptions that will emit a warning when being caught. Defaults to +# "Exception" +overgeneral-exceptions=Exception diff --git a/node-v0.8.14/tools/gyp/samples/samples b/node-v0.8.14/tools/gyp/samples/samples new file mode 100755 index 0000000..804b618 --- /dev/null +++ b/node-v0.8.14/tools/gyp/samples/samples @@ -0,0 +1,81 @@ +#!/usr/bin/python + +# Copyright (c) 2009 Google Inc. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +import os.path +import shutil +import sys + + +gyps = [ + 'app/app.gyp', + 'base/base.gyp', + 'build/temp_gyp/googleurl.gyp', + 'build/all.gyp', + 'build/common.gypi', + 'build/external_code.gypi', + 'chrome/test/security_tests/security_tests.gyp', + 'chrome/third_party/hunspell/hunspell.gyp', + 'chrome/chrome.gyp', + 'media/media.gyp', + 'net/net.gyp', + 'printing/printing.gyp', + 'sdch/sdch.gyp', + 'skia/skia.gyp', + 'testing/gmock.gyp', + 'testing/gtest.gyp', + 'third_party/bzip2/bzip2.gyp', + 'third_party/icu38/icu38.gyp', + 'third_party/libevent/libevent.gyp', + 'third_party/libjpeg/libjpeg.gyp', + 'third_party/libpng/libpng.gyp', + 'third_party/libxml/libxml.gyp', + 'third_party/libxslt/libxslt.gyp', + 'third_party/lzma_sdk/lzma_sdk.gyp', + 'third_party/modp_b64/modp_b64.gyp', + 'third_party/npapi/npapi.gyp', + 'third_party/sqlite/sqlite.gyp', + 'third_party/zlib/zlib.gyp', + 'v8/tools/gyp/v8.gyp', + 'webkit/activex_shim/activex_shim.gyp', + 'webkit/activex_shim_dll/activex_shim_dll.gyp', + 'webkit/build/action_csspropertynames.py', + 'webkit/build/action_cssvaluekeywords.py', + 'webkit/build/action_jsconfig.py', + 'webkit/build/action_makenames.py', + 'webkit/build/action_maketokenizer.py', + 'webkit/build/action_useragentstylesheets.py', + 'webkit/build/rule_binding.py', + 'webkit/build/rule_bison.py', + 'webkit/build/rule_gperf.py', + 'webkit/tools/test_shell/test_shell.gyp', + 'webkit/webkit.gyp', +] + + +def Main(argv): + if len(argv) != 3 or argv[1] not in ['push', 'pull']: + print 'Usage: %s push/pull PATH_TO_CHROME' % argv[0] + return 1 + + path_to_chrome = argv[2] + + for g in gyps: + chrome_file = os.path.join(path_to_chrome, g) + local_file = os.path.join(os.path.dirname(argv[0]), os.path.split(g)[1]) + if argv[1] == 'push': + print 'Copying %s to %s' % (local_file, chrome_file) + shutil.copyfile(local_file, chrome_file) + elif argv[1] == 'pull': + print 'Copying %s to %s' % (chrome_file, local_file) + shutil.copyfile(chrome_file, local_file) + else: + assert False + + return 0 + + +if __name__ == '__main__': + sys.exit(Main(sys.argv)) diff --git a/node-v0.8.14/tools/gyp/samples/samples.bat b/node-v0.8.14/tools/gyp/samples/samples.bat new file mode 100644 index 0000000..778d9c9 --- /dev/null +++ b/node-v0.8.14/tools/gyp/samples/samples.bat @@ -0,0 +1,5 @@ +@rem Copyright (c) 2009 Google Inc. All rights reserved. +@rem Use of this source code is governed by a BSD-style license that can be +@rem found in the LICENSE file. + +@python %~dp0/samples %* diff --git a/node-v0.8.14/tools/gyp/setup.py b/node-v0.8.14/tools/gyp/setup.py new file mode 100755 index 0000000..ed2b41a --- /dev/null +++ b/node-v0.8.14/tools/gyp/setup.py @@ -0,0 +1,26 @@ +#!/usr/bin/env python + +# Copyright (c) 2009 Google Inc. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +from distutils.core import setup +from distutils.command.install import install +from distutils.command.install_lib import install_lib +from distutils.command.install_scripts import install_scripts + +setup( + name='gyp', + version='0.1', + description='Generate Your Projects', + author='Chromium Authors', + author_email='chromium-dev@googlegroups.com', + url='http://code.google.com/p/gyp', + package_dir = {'': 'pylib'}, + packages=['gyp', 'gyp.generator'], + + scripts = ['gyp'], + cmdclass = {'install': install, + 'install_lib': install_lib, + 'install_scripts': install_scripts}, +) diff --git a/node-v0.8.14/tools/gyp/tools/README b/node-v0.8.14/tools/gyp/tools/README new file mode 100644 index 0000000..712e4ef --- /dev/null +++ b/node-v0.8.14/tools/gyp/tools/README @@ -0,0 +1,15 @@ +pretty_vcproj: + Usage: pretty_vcproj.py "c:\path\to\vcproj.vcproj" [key1=value1] [key2=value2] + + They key/value pair are used to resolve vsprops name. + + For example, if I want to diff the base.vcproj project: + + pretty_vcproj.py z:\dev\src-chrome\src\base\build\base.vcproj "$(SolutionDir)=z:\dev\src-chrome\src\chrome\\" "$(CHROMIUM_BUILD)=" "$(CHROME_BUILD_TYPE)=" > orignal.txt + pretty_vcproj.py z:\dev\src-chrome\src\base\base_gyp.vcproj "$(SolutionDir)=z:\dev\src-chrome\src\chrome\\" "$(CHROMIUM_BUILD)=" "$(CHROME_BUILD_TYPE)=" > gyp.txt + + And you can use your favorite diff tool to see the changes. + + Note: In the case of base.vcproj, the original vcproj is one level up the generated one. + I suggest you do a search and replace for '"..\' and replace it with '"' in original.txt + before you perform the diff. \ No newline at end of file diff --git a/node-v0.8.14/tools/gyp/tools/Xcode/README b/node-v0.8.14/tools/gyp/tools/Xcode/README new file mode 100644 index 0000000..2492a2c --- /dev/null +++ b/node-v0.8.14/tools/gyp/tools/Xcode/README @@ -0,0 +1,5 @@ +Specifications contains syntax formatters for Xcode 3. These do not appear to be supported yet on Xcode 4. To use these with Xcode 3 please install both the gyp.pbfilespec and gyp.xclangspec files in + +~/Library/Application Support/Developer/Shared/Xcode/Specifications/ + +and restart Xcode. \ No newline at end of file diff --git a/node-v0.8.14/tools/gyp/tools/Xcode/Specifications/gyp.pbfilespec b/node-v0.8.14/tools/gyp/tools/Xcode/Specifications/gyp.pbfilespec new file mode 100644 index 0000000..85e2e26 --- /dev/null +++ b/node-v0.8.14/tools/gyp/tools/Xcode/Specifications/gyp.pbfilespec @@ -0,0 +1,27 @@ +/* + gyp.pbfilespec + GYP source file spec for Xcode 3 + + There is not much documentation available regarding the format + of .pbfilespec files. As a starting point, see for instance the + outdated documentation at: + http://maxao.free.fr/xcode-plugin-interface/specifications.html + and the files in: + /Developer/Library/PrivateFrameworks/XcodeEdit.framework/Versions/A/Resources/ + + Place this file in directory: + ~/Library/Application Support/Developer/Shared/Xcode/Specifications/ +*/ + +( + { + Identifier = sourcecode.gyp; + BasedOn = sourcecode; + Name = "GYP Files"; + Extensions = ("gyp", "gypi"); + MIMETypes = ("text/gyp"); + Language = "xcode.lang.gyp"; + IsTextFile = YES; + IsSourceFile = YES; + } +) diff --git a/node-v0.8.14/tools/gyp/tools/Xcode/Specifications/gyp.xclangspec b/node-v0.8.14/tools/gyp/tools/Xcode/Specifications/gyp.xclangspec new file mode 100644 index 0000000..3b3506d --- /dev/null +++ b/node-v0.8.14/tools/gyp/tools/Xcode/Specifications/gyp.xclangspec @@ -0,0 +1,226 @@ +/* + Copyright (c) 2011 Google Inc. All rights reserved. + Use of this source code is governed by a BSD-style license that can be + found in the LICENSE file. + + gyp.xclangspec + GYP language specification for Xcode 3 + + There is not much documentation available regarding the format + of .xclangspec files. As a starting point, see for instance the + outdated documentation at: + http://maxao.free.fr/xcode-plugin-interface/specifications.html + and the files in: + /Developer/Library/PrivateFrameworks/XcodeEdit.framework/Versions/A/Resources/ + + Place this file in directory: + ~/Library/Application Support/Developer/Shared/Xcode/Specifications/ +*/ + +( + + { + Identifier = "xcode.lang.gyp.keyword"; + Syntax = { + Words = ( + "and", + "or", + " (caar gyp-parse-history) target-point) + (setq gyp-parse-history (cdr gyp-parse-history)))) + +(defun gyp-parse-point () + "The point of the last parse state added by gyp-parse-to." + (caar gyp-parse-history)) + +(defun gyp-parse-sections () + "A list of section symbols holding at the last parse state point." + (cdar gyp-parse-history)) + +(defun gyp-inside-dictionary-p () + "Predicate returning true if the parser is inside a dictionary." + (not (eq (cadar gyp-parse-history) 'list))) + +(defun gyp-add-parse-history (point sections) + "Add parse state SECTIONS to the parse history at POINT so that parsing can be + resumed instantly." + (while (>= (caar gyp-parse-history) point) + (setq gyp-parse-history (cdr gyp-parse-history))) + (setq gyp-parse-history (cons (cons point sections) gyp-parse-history))) + +(defun gyp-parse-to (target-point) + "Parses from (point) to TARGET-POINT adding the parse state information to + gyp-parse-state-history. Parsing stops if TARGET-POINT is reached or if a + string literal has been parsed. Returns nil if no further parsing can be + done, otherwise returns the position of the start of a parsed string, leaving + the point at the end of the string." + (let ((parsing t) + string-start) + (while parsing + (setq string-start nil) + ;; Parse up to a character that starts a sexp, or if the nesting + ;; level decreases. + (let ((state (parse-partial-sexp (gyp-parse-point) + target-point + -1 + t)) + (sections (gyp-parse-sections))) + (if (= (nth 0 state) -1) + (setq sections (cdr sections)) ; pop out a level + (cond ((looking-at-p "['\"]") ; a string + (setq string-start (point)) + (forward-sexp 1) + (if (gyp-inside-dictionary-p) + ;; Look for sections inside a dictionary + (let ((section (gyp-section-name + (buffer-substring-no-properties + (+ 1 string-start) + (- (point) 1))))) + (setq sections (cons section (cdr sections))))) + ;; Stop after the string so it can be fontified. + (setq target-point (point))) + ((looking-at-p "{") + ;; Inside a dictionary. Increase nesting. + (forward-char 1) + (setq sections (cons 'unknown sections))) + ((looking-at-p "\\[") + ;; Inside a list. Increase nesting + (forward-char 1) + (setq sections (cons 'list sections))) + ((not (eobp)) + ;; other + (forward-char 1)))) + (gyp-add-parse-history (point) sections) + (setq parsing (< (point) target-point)))) + string-start)) + +(defun gyp-section-at-point () + "Transform the last parse state, which is a list of nested sections and return + the section symbol that should be used to determine font-lock information for + the string. Can return nil indicating the string should not have any attached + section." + (let ((sections (gyp-parse-sections))) + (cond + ((eq (car sections) 'conditions) + ;; conditions can occur in a variables section, but we still want to + ;; highlight it as a keyword. + nil) + ((and (eq (car sections) 'list) + (eq (cadr sections) 'list)) + ;; conditions and sources can have items in [[ ]] + (caddr sections)) + (t (cadr sections))))) + +(defun gyp-section-match (limit) + "Parse from (point) to LIMIT returning by means of match data what was + matched. The group of the match indicates what style font-lock should apply. + See also `gyp-add-font-lock-keywords'." + (gyp-invalidate-parse-states-after (point)) + (let ((group nil) + (string-start t)) + (while (and (< (point) limit) + (not group) + string-start) + (setq string-start (gyp-parse-to limit)) + (if string-start + (setq group (case (gyp-section-at-point) + ('dependencies 1) + ('variables 2) + ('conditions 2) + ('sources 3) + ('defines 4) + (nil nil))))) + (if group + (progn + ;; Set the match data to indicate to the font-lock mechanism the + ;; highlighting to be performed. + (set-match-data (append (list string-start (point)) + (make-list (* (1- group) 2) nil) + (list (1+ string-start) (1- (point))))) + t)))) + +;;; Please see http://code.google.com/p/gyp/wiki/GypLanguageSpecification for +;;; canonical list of keywords. +(defun gyp-add-font-lock-keywords () + "Add gyp-mode keywords to font-lock mechanism." + ;; TODO(jknotten): Move all the keyword highlighting into gyp-section-match + ;; so that we can do the font-locking in a single font-lock pass. + (font-lock-add-keywords + nil + (list + ;; Top-level keywords + (list (concat "['\"]\\(" + (regexp-opt (list "action" "action_name" "actions" "cflags" + "conditions" "configurations" "copies" "defines" + "dependencies" "destination" + "direct_dependent_settings" + "export_dependent_settings" "extension" "files" + "include_dirs" "includes" "inputs" "libraries" + "link_settings" "mac_bundle" "message" + "msvs_external_rule" "outputs" "product_name" + "process_outputs_as_sources" "rules" "rule_name" + "sources" "suppress_wildcard" + "target_conditions" "target_defaults" + "target_defines" "target_name" "toolsets" + "targets" "type" "variables" "xcode_settings")) + "[!/+=]?\\)") 1 'font-lock-keyword-face t) + ;; Type of target + (list (concat "['\"]\\(" + (regexp-opt (list "loadable_module" "static_library" + "shared_library" "executable" "none")) + "\\)") 1 'font-lock-type-face t) + (list "\\(?:target\\|action\\)_name['\"]\\s-*:\\s-*['\"]\\([^ '\"]*\\)" 1 + 'font-lock-function-name-face t) + (list 'gyp-section-match + (list 1 'font-lock-function-name-face t t) ; dependencies + (list 2 'font-lock-variable-name-face t t) ; variables, conditions + (list 3 'font-lock-constant-face t t) ; sources + (list 4 'font-lock-preprocessor-face t t)) ; preprocessor + ;; Variable expansion + (list "<@?(\\([^\n )]+\\))" 1 'font-lock-variable-name-face t) + ;; Command expansion + (list " "%s"' % (src, dst) + + print '}' + + +def main(): + if len(sys.argv) < 2: + print >>sys.stderr, __doc__ + print >>sys.stderr + print >>sys.stderr, 'usage: %s target1 target2...' % (sys.argv[0]) + return 1 + + edges = LoadEdges('dump.json', sys.argv[1:]) + + WriteGraph(edges) + return 0 + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/node-v0.8.14/tools/gyp/tools/pretty_gyp.py b/node-v0.8.14/tools/gyp/tools/pretty_gyp.py new file mode 100755 index 0000000..c51d358 --- /dev/null +++ b/node-v0.8.14/tools/gyp/tools/pretty_gyp.py @@ -0,0 +1,155 @@ +#!/usr/bin/env python + +# Copyright (c) 2012 Google Inc. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +"""Pretty-prints the contents of a GYP file.""" + +import sys +import re + + +# Regex to remove comments when we're counting braces. +COMMENT_RE = re.compile(r'\s*#.*') + +# Regex to remove quoted strings when we're counting braces. +# It takes into account quoted quotes, and makes sure that the quotes match. +# NOTE: It does not handle quotes that span more than one line, or +# cases where an escaped quote is preceeded by an escaped backslash. +QUOTE_RE_STR = r'(?P[\'"])(.*?)(? 0: + after = True + + # This catches the special case of a closing brace having something + # other than just whitespace ahead of it -- we don't want to + # unindent that until after this line is printed so it stays with + # the previous indentation level. + if cnt < 0 and closing_prefix_re.match(stripline): + after = True + return (cnt, after) + + +def prettyprint_input(lines): + """Does the main work of indenting the input based on the brace counts.""" + indent = 0 + basic_offset = 2 + last_line = "" + for line in lines: + if COMMENT_RE.match(line): + print line + else: + line = line.strip('\r\n\t ') # Otherwise doesn't strip \r on Unix. + if len(line) > 0: + (brace_diff, after) = count_braces(line) + if brace_diff != 0: + if after: + print " " * (basic_offset * indent) + line + indent += brace_diff + else: + indent += brace_diff + print " " * (basic_offset * indent) + line + else: + print " " * (basic_offset * indent) + line + else: + print "" + last_line = line + + +def main(): + if len(sys.argv) > 1: + data = open(sys.argv[1]).read().splitlines() + else: + data = sys.stdin.read().splitlines() + # Split up the double braces. + lines = split_double_braces(data) + + # Indent and print the output. + prettyprint_input(lines) + return 0 + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/node-v0.8.14/tools/gyp/tools/pretty_sln.py b/node-v0.8.14/tools/gyp/tools/pretty_sln.py new file mode 100755 index 0000000..3195d85 --- /dev/null +++ b/node-v0.8.14/tools/gyp/tools/pretty_sln.py @@ -0,0 +1,168 @@ +#!/usr/bin/env python + +# Copyright (c) 2012 Google Inc. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +"""Prints the information in a sln file in a diffable way. + + It first outputs each projects in alphabetical order with their + dependencies. + + Then it outputs a possible build order. +""" + +__author__ = 'nsylvain (Nicolas Sylvain)' + +import os +import re +import sys +import pretty_vcproj + +def BuildProject(project, built, projects, deps): + # if all dependencies are done, we can build it, otherwise we try to build the + # dependency. + # This is not infinite-recursion proof. + for dep in deps[project]: + if dep not in built: + BuildProject(dep, built, projects, deps) + print project + built.append(project) + +def ParseSolution(solution_file): + # All projects, their clsid and paths. + projects = dict() + + # A list of dependencies associated with a project. + dependencies = dict() + + # Regular expressions that matches the SLN format. + # The first line of a project definition. + begin_project = re.compile(('^Project\("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942' + '}"\) = "(.*)", "(.*)", "(.*)"$')) + # The last line of a project definition. + end_project = re.compile('^EndProject$') + # The first line of a dependency list. + begin_dep = re.compile('ProjectSection\(ProjectDependencies\) = postProject$') + # The last line of a dependency list. + end_dep = re.compile('EndProjectSection$') + # A line describing a dependency. + dep_line = re.compile(' *({.*}) = ({.*})$') + + in_deps = False + solution = open(solution_file) + for line in solution: + results = begin_project.search(line) + if results: + # Hack to remove icu because the diff is too different. + if results.group(1).find('icu') != -1: + continue + # We remove "_gyp" from the names because it helps to diff them. + current_project = results.group(1).replace('_gyp', '') + projects[current_project] = [results.group(2).replace('_gyp', ''), + results.group(3), + results.group(2)] + dependencies[current_project] = [] + continue + + results = end_project.search(line) + if results: + current_project = None + continue + + results = begin_dep.search(line) + if results: + in_deps = True + continue + + results = end_dep.search(line) + if results: + in_deps = False + continue + + results = dep_line.search(line) + if results and in_deps and current_project: + dependencies[current_project].append(results.group(1)) + continue + + # Change all dependencies clsid to name instead. + for project in dependencies: + # For each dependencies in this project + new_dep_array = [] + for dep in dependencies[project]: + # Look for the project name matching this cldis + for project_info in projects: + if projects[project_info][1] == dep: + new_dep_array.append(project_info) + dependencies[project] = sorted(new_dep_array) + + return (projects, dependencies) + +def PrintDependencies(projects, deps): + print "---------------------------------------" + print "Dependencies for all projects" + print "---------------------------------------" + print "-- --" + + for (project, dep_list) in sorted(deps.items()): + print "Project : %s" % project + print "Path : %s" % projects[project][0] + if dep_list: + for dep in dep_list: + print " - %s" % dep + print "" + + print "-- --" + +def PrintBuildOrder(projects, deps): + print "---------------------------------------" + print "Build order " + print "---------------------------------------" + print "-- --" + + built = [] + for (project, _) in sorted(deps.items()): + if project not in built: + BuildProject(project, built, projects, deps) + + print "-- --" + +def PrintVCProj(projects): + + for project in projects: + print "-------------------------------------" + print "-------------------------------------" + print project + print project + print project + print "-------------------------------------" + print "-------------------------------------" + + project_path = os.path.abspath(os.path.join(os.path.dirname(sys.argv[1]), + projects[project][2])) + + pretty = pretty_vcproj + argv = [ '', + project_path, + '$(SolutionDir)=%s\\' % os.path.dirname(sys.argv[1]), + ] + argv.extend(sys.argv[3:]) + pretty.main(argv) + +def main(): + # check if we have exactly 1 parameter. + if len(sys.argv) < 2: + print 'Usage: %s "c:\\path\\to\\project.sln"' % sys.argv[0] + return 1 + + (projects, deps) = ParseSolution(sys.argv[1]) + PrintDependencies(projects, deps) + PrintBuildOrder(projects, deps) + + if '--recursive' in sys.argv: + PrintVCProj(projects) + return 0 + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/node-v0.8.14/tools/gyp/tools/pretty_vcproj.py b/node-v0.8.14/tools/gyp/tools/pretty_vcproj.py new file mode 100755 index 0000000..6099bd7 --- /dev/null +++ b/node-v0.8.14/tools/gyp/tools/pretty_vcproj.py @@ -0,0 +1,329 @@ +#!/usr/bin/env python + +# Copyright (c) 2012 Google Inc. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +"""Make the format of a vcproj really pretty. + + This script normalize and sort an xml. It also fetches all the properties + inside linked vsprops and include them explicitly in the vcproj. + + It outputs the resulting xml to stdout. +""" + +__author__ = 'nsylvain (Nicolas Sylvain)' + +import os +import sys + +from xml.dom.minidom import parse +from xml.dom.minidom import Node + +REPLACEMENTS = dict() +ARGUMENTS = None + + +class CmpTuple(object): + """Compare function between 2 tuple.""" + def __call__(self, x, y): + return cmp(x[0], y[0]) + + +class CmpNode(object): + """Compare function between 2 xml nodes.""" + + def __call__(self, x, y): + def get_string(node): + node_string = "node" + node_string += node.nodeName + if node.nodeValue: + node_string += node.nodeValue + + if node.attributes: + # We first sort by name, if present. + node_string += node.getAttribute("Name") + + all_nodes = [] + for (name, value) in node.attributes.items(): + all_nodes.append((name, value)) + + all_nodes.sort(CmpTuple()) + for (name, value) in all_nodes: + node_string += name + node_string += value + + return node_string + + return cmp(get_string(x), get_string(y)) + + +def PrettyPrintNode(node, indent=0): + if node.nodeType == Node.TEXT_NODE: + if node.data.strip(): + print '%s%s' % (' '*indent, node.data.strip()) + return + + if node.childNodes: + node.normalize() + # Get the number of attributes + attr_count = 0 + if node.attributes: + attr_count = node.attributes.length + + # Print the main tag + if attr_count == 0: + print '%s<%s>' % (' '*indent, node.nodeName) + else: + print '%s<%s' % (' '*indent, node.nodeName) + + all_attributes = [] + for (name, value) in node.attributes.items(): + all_attributes.append((name, value)) + all_attributes.sort(CmpTuple()) + for (name, value) in all_attributes: + print '%s %s="%s"' % (' '*indent, name, value) + print '%s>' % (' '*indent) + if node.nodeValue: + print '%s %s' % (' '*indent, node.nodeValue) + + for sub_node in node.childNodes: + PrettyPrintNode(sub_node, indent=indent+2) + print '%s' % (' '*indent, node.nodeName) + + +def FlattenFilter(node): + """Returns a list of all the node and sub nodes.""" + node_list = [] + + if (node.attributes and + node.getAttribute('Name') == '_excluded_files'): + # We don't add the "_excluded_files" filter. + return [] + + for current in node.childNodes: + if current.nodeName == 'Filter': + node_list.extend(FlattenFilter(current)) + else: + node_list.append(current) + + return node_list + + +def FixFilenames(filenames, current_directory): + new_list = [] + for filename in filenames: + if filename: + for key in REPLACEMENTS: + filename = filename.replace(key, REPLACEMENTS[key]) + os.chdir(current_directory) + filename = filename.strip('"\' ') + if filename.startswith('$'): + new_list.append(filename) + else: + new_list.append(os.path.abspath(filename)) + return new_list + + +def AbsoluteNode(node): + """Makes all the properties we know about in this node absolute.""" + if node.attributes: + for (name, value) in node.attributes.items(): + if name in ['InheritedPropertySheets', 'RelativePath', + 'AdditionalIncludeDirectories', + 'IntermediateDirectory', 'OutputDirectory', + 'AdditionalLibraryDirectories']: + # We want to fix up these paths + path_list = value.split(';') + new_list = FixFilenames(path_list, os.path.dirname(ARGUMENTS[1])) + node.setAttribute(name, ';'.join(new_list)) + if not value: + node.removeAttribute(name) + + +def CleanupVcproj(node): + """For each sub node, we call recursively this function.""" + for sub_node in node.childNodes: + AbsoluteNode(sub_node) + CleanupVcproj(sub_node) + + # Normalize the node, and remove all extranous whitespaces. + for sub_node in node.childNodes: + if sub_node.nodeType == Node.TEXT_NODE: + sub_node.data = sub_node.data.replace("\r", "") + sub_node.data = sub_node.data.replace("\n", "") + sub_node.data = sub_node.data.rstrip() + + # Fix all the semicolon separated attributes to be sorted, and we also + # remove the dups. + if node.attributes: + for (name, value) in node.attributes.items(): + sorted_list = sorted(value.split(';')) + unique_list = [] + for i in sorted_list: + if not unique_list.count(i): + unique_list.append(i) + node.setAttribute(name, ';'.join(unique_list)) + if not value: + node.removeAttribute(name) + + if node.childNodes: + node.normalize() + + # For each node, take a copy, and remove it from the list. + node_array = [] + while node.childNodes and node.childNodes[0]: + # Take a copy of the node and remove it from the list. + current = node.childNodes[0] + node.removeChild(current) + + # If the child is a filter, we want to append all its children + # to this same list. + if current.nodeName == 'Filter': + node_array.extend(FlattenFilter(current)) + else: + node_array.append(current) + + + # Sort the list. + node_array.sort(CmpNode()) + + # Insert the nodes in the correct order. + for new_node in node_array: + # But don't append empty tool node. + if new_node.nodeName == 'Tool': + if new_node.attributes and new_node.attributes.length == 1: + # This one was empty. + continue + if new_node.nodeName == 'UserMacro': + continue + node.appendChild(new_node) + + +def GetConfiguationNodes(vcproj): + #TODO(nsylvain): Find a better way to navigate the xml. + nodes = [] + for node in vcproj.childNodes: + if node.nodeName == "Configurations": + for sub_node in node.childNodes: + if sub_node.nodeName == "Configuration": + nodes.append(sub_node) + + return nodes + + +def GetChildrenVsprops(filename): + dom = parse(filename) + if dom.documentElement.attributes: + vsprops = dom.documentElement.getAttribute('InheritedPropertySheets') + return FixFilenames(vsprops.split(';'), os.path.dirname(filename)) + return [] + +def SeekToNode(node1, child2): + # A text node does not have properties. + if child2.nodeType == Node.TEXT_NODE: + return None + + # Get the name of the current node. + current_name = child2.getAttribute("Name") + if not current_name: + # There is no name. We don't know how to merge. + return None + + # Look through all the nodes to find a match. + for sub_node in node1.childNodes: + if sub_node.nodeName == child2.nodeName: + name = sub_node.getAttribute("Name") + if name == current_name: + return sub_node + + # No match. We give up. + return None + + +def MergeAttributes(node1, node2): + # No attributes to merge? + if not node2.attributes: + return + + for (name, value2) in node2.attributes.items(): + # Don't merge the 'Name' attribute. + if name == 'Name': + continue + value1 = node1.getAttribute(name) + if value1: + # The attribute exist in the main node. If it's equal, we leave it + # untouched, otherwise we concatenate it. + if value1 != value2: + node1.setAttribute(name, ';'.join([value1, value2])) + else: + # The attribute does nto exist in the main node. We append this one. + node1.setAttribute(name, value2) + + # If the attribute was a property sheet attributes, we remove it, since + # they are useless. + if name == 'InheritedPropertySheets': + node1.removeAttribute(name) + + +def MergeProperties(node1, node2): + MergeAttributes(node1, node2) + for child2 in node2.childNodes: + child1 = SeekToNode(node1, child2) + if child1: + MergeProperties(child1, child2) + else: + node1.appendChild(child2.cloneNode(True)) + + +def main(argv): + """Main function of this vcproj prettifier.""" + global ARGUMENTS + ARGUMENTS = argv + + # check if we have exactly 1 parameter. + if len(argv) < 2: + print ('Usage: %s "c:\\path\\to\\vcproj.vcproj" [key1=value1] ' + '[key2=value2]' % argv[0]) + return 1 + + # Parse the keys + for i in range(2, len(argv)): + (key, value) = argv[i].split('=') + REPLACEMENTS[key] = value + + # Open the vcproj and parse the xml. + dom = parse(argv[1]) + + # First thing we need to do is find the Configuration Node and merge them + # with the vsprops they include. + for configuration_node in GetConfiguationNodes(dom.documentElement): + # Get the property sheets associated with this configuration. + vsprops = configuration_node.getAttribute('InheritedPropertySheets') + + # Fix the filenames to be absolute. + vsprops_list = FixFilenames(vsprops.strip().split(';'), + os.path.dirname(argv[1])) + + # Extend the list of vsprops with all vsprops contained in the current + # vsprops. + for current_vsprops in vsprops_list: + vsprops_list.extend(GetChildrenVsprops(current_vsprops)) + + # Now that we have all the vsprops, we need to merge them. + for current_vsprops in vsprops_list: + MergeProperties(configuration_node, + parse(current_vsprops).documentElement) + + # Now that everything is merged, we need to cleanup the xml. + CleanupVcproj(dom.documentElement) + + # Finally, we use the prett xml function to print the vcproj back to the + # user. + #print dom.toprettyxml(newl="\n") + PrettyPrintNode(dom.documentElement) + return 0 + + +if __name__ == '__main__': + sys.exit(main(sys.argv)) diff --git a/node-v0.8.14/tools/gyp_addon b/node-v0.8.14/tools/gyp_addon new file mode 100755 index 0000000..b6f2d64 --- /dev/null +++ b/node-v0.8.14/tools/gyp_addon @@ -0,0 +1,42 @@ +#!/usr/bin/env python +import os +import sys + +script_dir = os.path.dirname(__file__) +node_root = os.path.abspath(os.path.join(script_dir, os.pardir)) +module_root = os.getcwd() +if sys.platform == 'win32': + output_dir = os.path.join(module_root, 'build') +else: + output_dir = 'build' + +sys.path.insert(0, os.path.join(node_root, 'tools', 'gyp', 'pylib')) +import gyp + +if __name__ == '__main__': + args = sys.argv[1:] + addon_gypi = os.path.join(node_root, 'tools', 'addon.gypi') + common_gypi = os.path.join(node_root, 'common.gypi') + config_gypi = os.path.join(node_root, 'config.gypi') + args.extend(['-I', addon_gypi]) + args.extend(['-I', common_gypi]) + if os.path.exists(config_gypi): + args.extend(['-I', config_gypi]) + args.extend(['-Dlibrary=shared_library']) + args.extend(['-Dvisibility=default']) + args.extend(['-Dnode_root_dir=%s' % node_root]) + args.extend(['-Dmodule_root_dir=%s' % module_root]) + args.extend(['--depth=.']); + + # Tell gyp to write the Makefile/Solution files into output_dir + args.extend(['--generator-output', output_dir]) + + # Tell make to write its output into the same dir + args.extend(['-Goutput_dir=.']) + + gyp_args = list(args) + rc = gyp.main(gyp_args) + if rc != 0: + print 'Error running GYP' + sys.exit(rc) + diff --git a/node-v0.8.14/tools/gyp_node b/node-v0.8.14/tools/gyp_node new file mode 100755 index 0000000..5c4882f --- /dev/null +++ b/node-v0.8.14/tools/gyp_node @@ -0,0 +1,58 @@ +#!/usr/bin/env python +import glob +import os +import shlex +import sys + +script_dir = os.path.dirname(__file__) +node_root = os.path.normpath(os.path.join(script_dir, os.pardir)) + +sys.path.insert(0, os.path.join(node_root, 'tools', 'gyp', 'pylib')) +import gyp + +# Directory within which we want all generated files (including Makefiles) +# to be written. +output_dir = os.path.join(os.path.abspath(node_root), 'out') + +def run_gyp(args): + rc = gyp.main(args) + if rc != 0: + print 'Error running GYP' + sys.exit(rc) + +if __name__ == '__main__': + args = sys.argv[1:] + + # GYP bug. + # On msvs it will crash if it gets an absolute path. + # On Mac/make it will crash if it doesn't get an absolute path. + if sys.platform == 'win32': + args.append(os.path.join(node_root, 'node.gyp')) + common_fn = os.path.join(node_root, 'common.gypi') + options_fn = os.path.join(node_root, 'config.gypi') + else: + args.append(os.path.join(os.path.abspath(node_root), 'node.gyp')) + common_fn = os.path.join(os.path.abspath(node_root), 'common.gypi') + options_fn = os.path.join(os.path.abspath(node_root), 'config.gypi') + + if os.path.exists(common_fn): + args.extend(['-I', common_fn]) + + if os.path.exists(options_fn): + args.extend(['-I', options_fn]) + + args.append('--depth=' + node_root) + + # There's a bug with windows which doesn't allow this feature. + if sys.platform != 'win32': + + # Tell gyp to write the Makefiles into output_dir + args.extend(['--generator-output', output_dir]) + + # Tell make to write its output into the same dir + args.extend(['-Goutput_dir=' + output_dir]) + + args.append('-Dcomponent=static_library') + args.append('-Dlibrary=static_library') + gyp_args = list(args) + run_gyp(gyp_args) diff --git a/node-v0.8.14/tools/install.py b/node-v0.8.14/tools/install.py new file mode 100755 index 0000000..028e5ca --- /dev/null +++ b/node-v0.8.14/tools/install.py @@ -0,0 +1,225 @@ +#!/usr/bin/env python + +import errno +import json +import os +import re +import shutil +import sys + +# set at init time +dst_dir = None +node_prefix = None # dst_dir without DESTDIR prefix +target_defaults = None +variables = None + +def abspath(*args): + path = os.path.join(*args) + return os.path.abspath(path) + +def load_config(): + s = open('config.gypi').read() + s = re.sub(r'#.*?\n', '', s) # strip comments + s = re.sub(r'\'', '"', s) # convert quotes + return json.loads(s) + +def try_unlink(path): + try: + os.unlink(path) + except OSError, e: + if e.errno != errno.ENOENT: raise + +def try_symlink(source_path, link_path): + print 'symlinking %s -> %s' % (source_path, link_path) + try_unlink(link_path) + os.symlink(source_path, link_path) + +def try_mkdir_r(path): + try: + os.makedirs(path) + except OSError, e: + if e.errno != errno.EEXIST: raise + +def try_rmdir_r(path): + path = abspath(path) + while path.startswith(dst_dir): + try: + os.rmdir(path) + except OSError, e: + if e.errno == errno.ENOTEMPTY: return + if e.errno == errno.ENOENT: return + raise + path = abspath(path, '..') + +def mkpaths(path, dst): + if dst.endswith('/'): + target_path = abspath(dst_dir, dst, os.path.basename(path)) + else: + target_path = abspath(dst_dir, dst) + return path, target_path + +def try_copy(path, dst): + source_path, target_path = mkpaths(path, dst) + print 'installing %s' % target_path + try_mkdir_r(os.path.dirname(target_path)) + try_unlink(target_path) # prevent ETXTBSY errors + return shutil.copy2(source_path, target_path) + +def try_remove(path, dst): + source_path, target_path = mkpaths(path, dst) + print 'removing %s' % target_path + try_unlink(target_path) + try_rmdir_r(os.path.dirname(target_path)) + +def install(paths, dst): map(lambda path: try_copy(path, dst), paths) +def uninstall(paths, dst): map(lambda path: try_remove(path, dst), paths) + +def waf_files(action): + action(['tools/node-waf'], 'bin/node-waf') + action(['tools/wafadmin/ansiterm.py', + 'tools/wafadmin/Build.py', + 'tools/wafadmin/Configure.py', + 'tools/wafadmin/Constants.py', + 'tools/wafadmin/Environment.py', + 'tools/wafadmin/__init__.py', + 'tools/wafadmin/Logs.py', + 'tools/wafadmin/Node.py', + 'tools/wafadmin/Options.py', + 'tools/wafadmin/pproc.py', + 'tools/wafadmin/py3kfixes.py', + 'tools/wafadmin/Runner.py', + 'tools/wafadmin/Scripting.py', + 'tools/wafadmin/TaskGen.py', + 'tools/wafadmin/Task.py', + 'tools/wafadmin/Utils.py'], + 'lib/node/wafadmin/') + action(['tools/wafadmin/Tools/ar.py', + 'tools/wafadmin/Tools/cc.py', + 'tools/wafadmin/Tools/ccroot.py', + 'tools/wafadmin/Tools/compiler_cc.py', + 'tools/wafadmin/Tools/compiler_cxx.py', + 'tools/wafadmin/Tools/compiler_d.py', + 'tools/wafadmin/Tools/config_c.py', + 'tools/wafadmin/Tools/cxx.py', + 'tools/wafadmin/Tools/dmd.py', + 'tools/wafadmin/Tools/d.py', + 'tools/wafadmin/Tools/gas.py', + 'tools/wafadmin/Tools/gcc.py', + 'tools/wafadmin/Tools/gdc.py', + 'tools/wafadmin/Tools/gnu_dirs.py', + 'tools/wafadmin/Tools/gob2.py', + 'tools/wafadmin/Tools/gxx.py', + 'tools/wafadmin/Tools/icc.py', + 'tools/wafadmin/Tools/icpc.py', + 'tools/wafadmin/Tools/__init__.py', + 'tools/wafadmin/Tools/intltool.py', + 'tools/wafadmin/Tools/libtool.py', + 'tools/wafadmin/Tools/misc.py', + 'tools/wafadmin/Tools/nasm.py', + 'tools/wafadmin/Tools/node_addon.py', + 'tools/wafadmin/Tools/osx.py', + 'tools/wafadmin/Tools/preproc.py', + 'tools/wafadmin/Tools/python.py', + 'tools/wafadmin/Tools/suncc.py', + 'tools/wafadmin/Tools/suncxx.py', + 'tools/wafadmin/Tools/unittestw.py', + 'tools/wafadmin/Tools/winres.py', + 'tools/wafadmin/Tools/xlc.py', + 'tools/wafadmin/Tools/xlcxx.py'], + 'lib/node/wafadmin/Tools/') + +def update_shebang(path, shebang): + print 'updating shebang of %s to %s' % (path, shebang) + s = open(path, 'r').read() + s = re.sub(r'#!.*\n', '#!' + shebang + '\n', s) + open(path, 'w').write(s) + +def npm_files(action): + target_path = 'lib/node_modules/npm/' + + # don't install npm if the target path is a symlink, it probably means + # that a dev version of npm is installed there + if os.path.islink(abspath(dst_dir, target_path)): return + + # npm has a *lot* of files and it'd be a pain to maintain a fixed list here + # so we walk its source directory instead... + for dirname, subdirs, basenames in os.walk('deps/npm', topdown=True): + subdirs[:] = filter('test'.__ne__, subdirs) # skip test suites + paths = [os.path.join(dirname, basename) for basename in basenames] + action(paths, target_path + dirname[9:] + '/') + + # create/remove symlink + link_path = abspath(dst_dir, 'bin/npm') + if action == uninstall: + action([link_path], 'bin/npm') + elif action == install: + try_symlink('../lib/node_modules/npm/bin/npm-cli.js', link_path) + if os.environ.get('PORTABLE'): + # This crazy hack is necessary to make the shebang execute the copy + # of node relative to the same directory as the npm script. The precompiled + # binary tarballs use a prefix of "/" which gets translated to "/bin/node" + # in the regular shebang modifying logic, which is incorrect since the + # precompiled bundle should be able to be extracted anywhere and "just work" + shebang = '/bin/sh\n// 2>/dev/null; exec "`dirname "$0"`/node" "$0" "$@"' + else: + shebang = os.path.join(node_prefix, 'bin/node') + update_shebang(link_path, shebang) + else: + assert(0) # unhandled action type + +def files(action): + action(['deps/uv/include/ares.h', + 'deps/uv/include/ares_version.h', + 'deps/uv/include/uv.h', + 'deps/v8/include/v8-debug.h', + 'deps/v8/include/v8-preparser.h', + 'deps/v8/include/v8-profiler.h', + 'deps/v8/include/v8-testing.h', + 'deps/v8/include/v8.h', + 'deps/v8/include/v8stdint.h', + 'src/eio-emul.h', + 'src/ev-emul.h', + 'src/node.h', + 'src/node_buffer.h', + 'src/node_object_wrap.h', + 'src/node_version.h'], + 'include/node/') + action(['deps/uv/include/uv-private/eio.h', + 'deps/uv/include/uv-private/ev.h', + 'deps/uv/include/uv-private/ngx-queue.h', + 'deps/uv/include/uv-private/tree.h', + 'deps/uv/include/uv-private/uv-unix.h', + 'deps/uv/include/uv-private/uv-win.h'], + 'include/node/uv-private/') + action(['doc/node.1'], 'share/man/man1/') + action(['out/Release/node'], 'bin/node') + + # install unconditionally, checking if the platform supports dtrace doesn't + # work when cross-compiling and besides, there's at least one linux flavor + # with dtrace support now (oracle's "unbreakable" linux) + action(['src/node.d'], 'lib/dtrace/') + + if 'true' == variables.get('node_install_waf'): waf_files(action) + if 'true' == variables.get('node_install_npm'): npm_files(action) + +def run(args): + global dst_dir, node_prefix, target_defaults, variables + + # chdir to the project's top-level directory + os.chdir(abspath(os.path.dirname(__file__), '..')) + + conf = load_config() + variables = conf['variables'] + target_defaults = conf['target_defaults'] + + # argv[2] is a custom install prefix for packagers (think DESTDIR) + dst_dir = node_prefix = variables.get('node_prefix') or '/usr/local' + if len(args) > 2: dst_dir = abspath(args[2] + '/' + dst_dir) + + cmd = args[1] if len(args) > 1 else 'install' + if cmd == 'install': return files(install) + if cmd == 'uninstall': return files(uninstall) + raise RuntimeError('Bad command: %s\n' % cmd) + +if __name__ == '__main__': + run(sys.argv[:]) diff --git a/node-v0.8.14/tools/js2c.py b/node-v0.8.14/tools/js2c.py new file mode 100755 index 0000000..69ec8a8 --- /dev/null +++ b/node-v0.8.14/tools/js2c.py @@ -0,0 +1,368 @@ +#!/usr/bin/env python +# +# Copyright 2006-2008 the V8 project authors. All rights reserved. +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above +# copyright notice, this list of conditions and the following +# disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of Google Inc. nor the names of its +# contributors may be used to endorse or promote products derived +# from this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +# This is a utility for converting JavaScript source code into C-style +# char arrays. It is used for embedded JavaScript code in the V8 +# library. + +import os +from os.path import dirname +import re +import sys +import string + +sys.path.append(dirname(__file__) + "/../deps/v8/tools"); +import jsmin + + +def ToCArray(filename, lines): + result = [] + row = 1 + col = 0 + for chr in lines: + col += 1 + if chr == "\n" or chr == "\r": + row += 1 + col = 0 + + value = ord(chr) + + if value >= 128: + print 'non-ascii value ' + filename + ':' + str(row) + ':' + str(col) + sys.exit(1); + + result.append(str(value)) + result.append("0") + return ", ".join(result) + + +def CompressScript(lines, do_jsmin): + # If we're not expecting this code to be user visible, we can run it through + # a more aggressive minifier. + if do_jsmin: + minifier = JavaScriptMinifier() + return minifier.JSMinify(lines) + + # Remove stuff from the source that we don't want to appear when + # people print the source code using Function.prototype.toString(). + # Note that we could easily compress the scripts mode but don't + # since we want it to remain readable. + #lines = re.sub('//.*\n', '\n', lines) # end-of-line comments + #lines = re.sub(re.compile(r'/\*.*?\*/', re.DOTALL), '', lines) # comments. + #lines = re.sub('\s+\n+', '\n', lines) # trailing whitespace + return lines + + +def ReadFile(filename): + file = open(filename, "rt") + try: + lines = file.read() + finally: + file.close() + return lines + + +def ReadLines(filename): + result = [] + for line in open(filename, "rt"): + if '#' in line: + line = line[:line.index('#')] + line = line.strip() + if len(line) > 0: + result.append(line) + return result + + +def LoadConfigFrom(name): + import ConfigParser + config = ConfigParser.ConfigParser() + config.read(name) + return config + + +def ParseValue(string): + string = string.strip() + if string.startswith('[') and string.endswith(']'): + return string.lstrip('[').rstrip(']').split() + else: + return string + + +def ExpandConstants(lines, constants): + for key, value in constants.items(): + lines = lines.replace(key, str(value)) + return lines + + +def ExpandMacros(lines, macros): + for name, macro in macros.items(): + start = lines.find(name + '(', 0) + while start != -1: + # Scan over the arguments + assert lines[start + len(name)] == '(' + height = 1 + end = start + len(name) + 1 + last_match = end + arg_index = 0 + mapping = { } + def add_arg(str): + # Remember to expand recursively in the arguments + replacement = ExpandMacros(str.strip(), macros) + mapping[macro.args[arg_index]] = replacement + while end < len(lines) and height > 0: + # We don't count commas at higher nesting levels. + if lines[end] == ',' and height == 1: + add_arg(lines[last_match:end]) + last_match = end + 1 + elif lines[end] in ['(', '{', '[']: + height = height + 1 + elif lines[end] in [')', '}', ']']: + height = height - 1 + end = end + 1 + # Remember to add the last match. + add_arg(lines[last_match:end-1]) + result = macro.expand(mapping) + # Replace the occurrence of the macro with the expansion + lines = lines[:start] + result + lines[end:] + start = lines.find(name + '(', end) + return lines + +class TextMacro: + def __init__(self, args, body): + self.args = args + self.body = body + def expand(self, mapping): + result = self.body + for key, value in mapping.items(): + result = result.replace(key, value) + return result + +class PythonMacro: + def __init__(self, args, fun): + self.args = args + self.fun = fun + def expand(self, mapping): + args = [] + for arg in self.args: + args.append(mapping[arg]) + return str(self.fun(*args)) + +CONST_PATTERN = re.compile('^const\s+([a-zA-Z0-9_]+)\s*=\s*([^;]*);$') +MACRO_PATTERN = re.compile('^macro\s+([a-zA-Z0-9_]+)\s*\(([^)]*)\)\s*=\s*([^;]*);$') +PYTHON_MACRO_PATTERN = re.compile('^python\s+macro\s+([a-zA-Z0-9_]+)\s*\(([^)]*)\)\s*=\s*([^;]*);$') + +def ReadMacros(lines): + constants = { } + macros = { } + for line in lines: + hash = line.find('#') + if hash != -1: line = line[:hash] + line = line.strip() + if len(line) is 0: continue + const_match = CONST_PATTERN.match(line) + if const_match: + name = const_match.group(1) + value = const_match.group(2).strip() + constants[name] = value + else: + macro_match = MACRO_PATTERN.match(line) + if macro_match: + name = macro_match.group(1) + args = map(string.strip, macro_match.group(2).split(',')) + body = macro_match.group(3).strip() + macros[name] = TextMacro(args, body) + else: + python_match = PYTHON_MACRO_PATTERN.match(line) + if python_match: + name = python_match.group(1) + args = map(string.strip, python_match.group(2).split(',')) + body = python_match.group(3).strip() + fun = eval("lambda " + ",".join(args) + ': ' + body) + macros[name] = PythonMacro(args, fun) + else: + raise ("Illegal line: " + line) + return (constants, macros) + + +HEADER_TEMPLATE = """\ +#ifndef node_natives_h +#define node_natives_h +namespace node { + +%(source_lines)s\ + +struct _native { + const char* name; + const char* source; + size_t source_len; +}; + +static const struct _native natives[] = { + +%(native_lines)s\ + + { NULL, NULL } /* sentinel */ + +}; + +} +#endif +""" + + +NATIVE_DECLARATION = """\ + { "%(id)s", %(id)s_native, sizeof(%(id)s_native)-1 }, +""" + +SOURCE_DECLARATION = """\ + const char %(id)s_native[] = { %(data)s }; +""" + + +GET_DELAY_INDEX_CASE = """\ + if (strcmp(name, "%(id)s") == 0) return %(i)i; +""" + + +GET_DELAY_SCRIPT_SOURCE_CASE = """\ + if (index == %(i)i) return Vector(%(id)s, %(length)i); +""" + + +GET_DELAY_SCRIPT_NAME_CASE = """\ + if (index == %(i)i) return Vector("%(name)s", %(length)i); +""" + +def JS2C(source, target): + ids = [] + delay_ids = [] + modules = [] + # Locate the macros file name. + consts = {} + macros = {} + + for s in source: + if 'macros.py' == (os.path.split(str(s))[1]): + (consts, macros) = ReadMacros(ReadLines(str(s))) + else: + modules.append(s) + + # Build source code lines + source_lines = [ ] + source_lines_empty = [] + + native_lines = [] + + for s in modules: + delay = str(s).endswith('-delay.js') + lines = ReadFile(str(s)) + do_jsmin = lines.find('// jsminify this file, js2c: jsmin') != -1 + + lines = ExpandConstants(lines, consts) + lines = ExpandMacros(lines, macros) + lines = CompressScript(lines, do_jsmin) + data = ToCArray(s, lines) + id = os.path.basename(str(s)).split('.')[0] + if delay: id = id[:-6] + if delay: + delay_ids.append((id, len(lines))) + else: + ids.append((id, len(lines))) + source_lines.append(SOURCE_DECLARATION % { 'id': id, 'data': data }) + source_lines_empty.append(SOURCE_DECLARATION % { 'id': id, 'data': 0 }) + native_lines.append(NATIVE_DECLARATION % { 'id': id }) + + # Build delay support functions + get_index_cases = [ ] + get_script_source_cases = [ ] + get_script_name_cases = [ ] + + i = 0 + for (id, length) in delay_ids: + native_name = "native %s.js" % id + get_index_cases.append(GET_DELAY_INDEX_CASE % { 'id': id, 'i': i }) + get_script_source_cases.append(GET_DELAY_SCRIPT_SOURCE_CASE % { + 'id': id, + 'length': length, + 'i': i + }) + get_script_name_cases.append(GET_DELAY_SCRIPT_NAME_CASE % { + 'name': native_name, + 'length': len(native_name), + 'i': i + }); + i = i + 1 + + for (id, length) in ids: + native_name = "native %s.js" % id + get_index_cases.append(GET_DELAY_INDEX_CASE % { 'id': id, 'i': i }) + get_script_source_cases.append(GET_DELAY_SCRIPT_SOURCE_CASE % { + 'id': id, + 'length': length, + 'i': i + }) + get_script_name_cases.append(GET_DELAY_SCRIPT_NAME_CASE % { + 'name': native_name, + 'length': len(native_name), + 'i': i + }); + i = i + 1 + + # Emit result + output = open(str(target[0]), "w") + output.write(HEADER_TEMPLATE % { + 'builtin_count': len(ids) + len(delay_ids), + 'delay_count': len(delay_ids), + 'source_lines': "\n".join(source_lines), + 'native_lines': "\n".join(native_lines), + 'get_index_cases': "".join(get_index_cases), + 'get_script_source_cases': "".join(get_script_source_cases), + 'get_script_name_cases': "".join(get_script_name_cases) + }) + output.close() + + if len(target) > 1: + output = open(str(target[1]), "w") + output.write(HEADER_TEMPLATE % { + 'builtin_count': len(ids) + len(delay_ids), + 'delay_count': len(delay_ids), + 'source_lines': "\n".join(source_lines_empty), + 'get_index_cases': "".join(get_index_cases), + 'get_script_source_cases': "".join(get_script_source_cases), + 'get_script_name_cases': "".join(get_script_name_cases) + }) + output.close() + +def main(): + natives = sys.argv[1] + source_files = sys.argv[2:] + JS2C(source_files, [natives]) + +if __name__ == "__main__": + main() diff --git a/node-v0.8.14/tools/license2rtf.js b/node-v0.8.14/tools/license2rtf.js new file mode 100644 index 0000000..f5a75a1 --- /dev/null +++ b/node-v0.8.14/tools/license2rtf.js @@ -0,0 +1,334 @@ + +var assert = require('assert'), + Stream = require('stream'), + inherits = require('util').inherits; + + +/* + * This filter consumes a stream of characters and emits one string per line. + */ +function LineSplitter() { + var self = this, + buffer = ""; + + Stream.call(this); + this.writable = true; + + this.write = function(data) { + var lines = (buffer + data).split(/\r\n|\n\r|\n|\r/); + for (var i = 0; i < lines.length - 1; i++) { + self.emit('data', lines[i]); + } + buffer = lines[lines.length - 1]; + return true; + }; + + this.end = function(data) { + this.write(data || ''); + if (buffer) { + self.emit('data', buffer); + } + self.emit('end'); + }; +} +inherits(LineSplitter, Stream); + + +/* + * This filter consumes lines and emits paragraph objects. + */ +function ParagraphParser() { + var self = this, + block_is_license_block = false, + block_has_c_style_comment, + is_first_line_in_paragraph, + paragraph_line_indent, + paragraph; + + Stream.call(this); + this.writable = true; + + resetBlock(false); + + this.write = function(data) { + parseLine(data + ''); + return true; + }; + + this.end = function(data) { + if (data) { + parseLine(data + ''); + } + flushParagraph(); + self.emit('end'); + }; + + function resetParagraph() { + is_first_line_in_paragraph = true; + paragraph_line_indent = -1; + + paragraph = { + li: '', + in_license_block: block_is_license_block, + lines: [] + }; + } + + function resetBlock(is_license_block) { + block_is_license_block = is_license_block; + block_has_c_style_comment = false; + resetParagraph(); + } + + function flushParagraph() { + if (paragraph.lines.length || paragraph.li) { + self.emit('data', paragraph); + } + resetParagraph(); + } + + function parseLine(line) { + // Strip trailing whitespace + line = line.replace(/\s*$/, ''); + + // Detect block separator + if (/^\s*(=|"){3,}\s*$/.test(line)) { + flushParagraph(); + resetBlock(!block_is_license_block); + return; + } + + // Strip comments around block + if (block_is_license_block) { + if (!block_has_c_style_comment) + block_has_c_style_comment = /^\s*(\/\*)/.test(line); + if (block_has_c_style_comment) { + var prev = line; + line = line.replace(/^(\s*?)(?:\s?\*\/|\/\*\s|\s\*\s?)/, '$1'); + if (prev == line) + line = line.replace(/^\s{2}/, ''); + if (/\*\//.test(prev)) + block_has_c_style_comment = false; + } else { + // Strip C++ and perl style comments. + line = line.replace(/^(\s*)(?:\/\/\s?|#\s?)/, '$1'); + } + } + + // Detect blank line (paragraph separator) + if (!/\S/.test(line)) { + flushParagraph(); + return; + } + + // Detect separator "lines" within a block. These mark a paragraph break + // and are stripped from the output. + if (/^\s*[=*\-]{5,}\s*$/.test(line)) { + flushParagraph(); + return; + } + + // Find out indentation level and the start of a lied or numbered list; + var result = /^(\s*)(\d+\.|\*|-)?\s*/.exec(line); + assert.ok(result); + // The number of characters that will be stripped from the beginning of + // the line. + var line_strip_length = result[0].length; + // The indentation size that will be used to detect indentation jumps. + // Fudge by 1 space. + var line_indent = Math.floor(result[0].length / 2) * 2; + // The indentation level that will be exported + var level = Math.floor(result[1].length / 2); + // The list indicator that precedes the actual content, if any. + var line_li = result[2]; + + // Flush the paragraph when there is a li or an indentation jump + if (line_li || (line_indent != paragraph_line_indent && + paragraph_line_indent != -1)) { + flushParagraph(); + paragraph.li = line_li; + } + + // Set the paragraph indent that we use to detect indentation jumps. When + // we just detected a list indicator, wait + // for the next line to arrive before setting this. + if (!line_li && paragraph_line_indent != -1) { + paragraph_line_indent = line_indent; + } + + // Set the output indent level if it has not been set yet. + if (paragraph.level === undefined) + paragraph.level = level; + + // Strip leading whitespace and li. + line = line.slice(line_strip_length); + + if (line) + paragraph.lines.push(line); + + is_first_line_in_paragraph = false; + } +} +inherits(ParagraphParser, Stream); + + +/* + * This filter consumes paragraph objects and emits modified paragraph objects. + * The lines within the paragraph are unwrapped where appropriate. It also + * replaces multiple consecutive whitespace characters by a single one. + */ +function Unwrapper() { + var self = this; + + Stream.call(this); + this.writable = true; + + this.write = function(paragraph) { + var lines = paragraph.lines, + break_after = [], + i; + + for (i = 0; i < lines.length - 1; i++) { + var line = lines[i]; + + // When a line is really short, the line was probably kept separate for a + // reason. + if (line.length < 50) { + // If the first word on the next line really didn't fit after the line, + // it probably was just ordinary wrapping after all. + var next_first_word_length = lines[i + 1].replace(/\s.*$/, '').length; + if (line.length + next_first_word_length < 60) { + break_after[i] = true; + } + } + } + + for (i = 0; i < lines.length - 1; ) { + if (!break_after[i]) { + lines[i] += ' ' + lines.splice(i + 1, 1)[0]; + } else { + i++; + } + } + + for (i = 0; i < lines.length; i++) { + // Replace multiple whitespace characters by a single one, and strip + // trailing whitespace. + lines[i] = lines[i].replace(/\s+/g, ' ').replace(/\s+$/, ''); + } + + self.emit('data', paragraph); + }; + + this.end = function(data) { + if (data) + self.write(data); + self.emit('end'); + }; +} +inherits(Unwrapper, Stream); + + +/* + * This filter generates an rtf document from a stream of paragraph objects. + */ +function RtfGenerator() { + var self = this, + did_write_anything = false; + + Stream.call(this); + this.writable = true; + + this.write = function(paragraph) { + if (!did_write_anything) { + emitHeader(); + did_write_anything = true; + } + + var li = paragraph.li, + level = paragraph.level + (li ? 1 : 0), + lic = paragraph.in_license_block; + + var rtf = "\\pard"; + rtf += '\\sa150\\sl300\\slmult1'; + if (level > 0) + rtf += '\\li' + (level * 240); + if (li) { + rtf += '\\tx' + (level) * 240; + rtf += '\\fi-240'; + } + if (lic) + rtf += '\\ri240'; + if (!lic) + rtf += '\\b'; + if (li) + rtf += ' ' + li + '\\tab'; + rtf += ' '; + rtf += paragraph.lines.map(rtfEscape).join('\\line '); + if (!lic) + rtf += '\\b0'; + rtf += '\\par\n'; + + self.emit('data', rtf); + }; + + this.end = function(data) { + if (data) + self.write(data); + if (did_write_anything) + emitFooter(); + self.emit('end'); + }; + + function toHex(number, length) { + var hex = (~~number).toString(16); + while (hex.length < length) + hex = '0' + hex; + return hex; + } + + function rtfEscape(string) { + return string + .replace(/[\\\{\}]/g, function(m) { + return '\\' + m; + }) + .replace(/\t/g, function() { + return '\\tab '; + }) + .replace(/[\x00-\x1f\x7f-\xff]/g, function(m) { + return '\\\'' + toHex(m.charCodeAt(0), 2); + }) + .replace(/\ufeff/g, '') + .replace(/[\u0100-\uffff]/g, function(m) { + return '\\u' + toHex(m.charCodeAt(0), 4) + '?'; + }); + } + + function emitHeader() { + self.emit('data', '{\\rtf1\\ansi\\ansicpg1252\\uc1\\deff0\\deflang1033' + + '{\\fonttbl{\\f0\\fswiss\\fcharset0 Tahoma;}}\\fs20\n' + + '{\\*\\generator txt2rtf 0.0.1;}\n'); + } + + function emitFooter() { + self.emit('data', '}'); + } +} +inherits(RtfGenerator, Stream); + + +var stdin = process.stdin, + stdout = process.stdout, + line_splitter = new LineSplitter(), + paragraph_parser = new ParagraphParser(), + unwrapper = new Unwrapper(), + rtf_generator = new RtfGenerator(); + +stdin.setEncoding('utf-8'); +stdin.resume(); + +stdin.pipe(line_splitter); +line_splitter.pipe(paragraph_parser); +paragraph_parser.pipe(unwrapper); +unwrapper.pipe(rtf_generator); +rtf_generator.pipe(stdout); diff --git a/node-v0.8.14/tools/msvs/msi/nodemsi.sln b/node-v0.8.14/tools/msvs/msi/nodemsi.sln new file mode 100644 index 0000000..f95b00f --- /dev/null +++ b/node-v0.8.14/tools/msvs/msi/nodemsi.sln @@ -0,0 +1,26 @@ + +Microsoft Visual Studio Solution File, Format Version 11.00 +# Visual Studio 2010 +Project("{930C7802-8A8C-48F9-8165-68863BCCD9DD}") = "nodemsi", "nodemsi.wixproj", "{1D808FF0-B5A9-4BE9-859D-B334B6F48BE2}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|x64 = Debug|x64 + Debug|x86 = Debug|x86 + Release|x64 = Release|x64 + Release|x86 = Release|x86 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {1D808FF0-B5A9-4BE9-859D-B334B6F48BE2}.Debug|x64.ActiveCfg = Debug|x64 + {1D808FF0-B5A9-4BE9-859D-B334B6F48BE2}.Debug|x64.Build.0 = Debug|x64 + {1D808FF0-B5A9-4BE9-859D-B334B6F48BE2}.Debug|x86.ActiveCfg = Debug|x86 + {1D808FF0-B5A9-4BE9-859D-B334B6F48BE2}.Debug|x86.Build.0 = Debug|x86 + {1D808FF0-B5A9-4BE9-859D-B334B6F48BE2}.Release|x64.ActiveCfg = Release|x64 + {1D808FF0-B5A9-4BE9-859D-B334B6F48BE2}.Release|x64.Build.0 = Release|x64 + {1D808FF0-B5A9-4BE9-859D-B334B6F48BE2}.Release|x86.ActiveCfg = Release|x86 + {1D808FF0-B5A9-4BE9-859D-B334B6F48BE2}.Release|x86.Build.0 = Release|x86 + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/node-v0.8.14/tools/msvs/msi/nodemsi.wixproj b/node-v0.8.14/tools/msvs/msi/nodemsi.wixproj new file mode 100644 index 0000000..7cc35c0 --- /dev/null +++ b/node-v0.8.14/tools/msvs/msi/nodemsi.wixproj @@ -0,0 +1,55 @@ + + + + + Debug + x86 + 3.5 + {1d808ff0-b5a9-4be9-859d-b334b6f48be2} + 2.0 + node-v$(NodeVersion)-$(Platform) + Package + $(MSBuildExtensionsPath32)\Microsoft\WiX\v3.x\Wix.targets + $(MSBuildExtensionsPath)\Microsoft\WiX\v3.x\Wix.targets + 0.0.0.0 + + + ..\..\..\$(Configuration)\ + obj\$(Configuration)\ + Debug;ProductVersion=$(NodeVersion);NoETW=$(NoETW);NPMSourceDir=..\..\..\deps\npm\;ProgramFilesFolderId=ProgramFilesFolder + + + ..\..\..\$(Configuration)\ + obj\$(Configuration)\ + Debug;ProductVersion=$(NodeVersion);NoETW=$(NoETW);NPMSourceDir=..\..\..\deps\npm\;ProgramFilesFolderId=ProgramFilesFolder + + + ..\..\..\$(Configuration)\ + obj\$(Configuration)\ + Debug;ProductVersion=$(NodeVersion);NoETW=$(NoETW);NPMSourceDir=..\..\..\deps\npm\;ProgramFilesFolderId=ProgramFiles64Folder + + + ..\..\..\$(Configuration)\ + obj\$(Configuration)\ + Debug;ProductVersion=$(NodeVersion);NoETW=$(NoETW);NPMSourceDir=..\..\..\deps\npm\;ProgramFilesFolderId=ProgramFiles64Folder + + + + + + + + $(WixExtDir)\WixUIExtension.dll + WixUIExtension + + + $(WixExtDir)\WiXUtilExtension.dll + WiXUtilExtension + + + + + + + + diff --git a/node-v0.8.14/tools/msvs/msi/product.wxs b/node-v0.8.14/tools/msvs/msi/product.wxs new file mode 100755 index 0000000..443739d --- /dev/null +++ b/node-v0.8.14/tools/msvs/msi/product.wxs @@ -0,0 +1,182 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + + + + + + + + + + + + + diff --git a/node-v0.8.14/tools/msvs/nodejsvars.bat b/node-v0.8.14/tools/msvs/nodejsvars.bat new file mode 100644 index 0000000..ff2315d --- /dev/null +++ b/node-v0.8.14/tools/msvs/nodejsvars.bat @@ -0,0 +1,16 @@ +@echo off + +rem Ensure this Node.js and NPM are first in the PATH +set PATH=%APPDATA%\npm;%~dp0;%PATH% + +rem Figure out node version and architecture and print it. +setlocal +pushd "%~dp0" +set print_version=.\node.exe -p -e "process.versions.node + ' (' + process.arch + ')'" +for /F "usebackq delims=" %%v in (`%print_version%`) do set version=%%v +echo Your environment has been set up for using Node.js %version% and NPM +popd +endlocal + +rem If we're in the node.js directory, change to the user's home dir. +if "%CD%\"=="%~dp0" cd /d "%HOMEDRIVE%%HOMEPATH%" diff --git a/node-v0.8.14/tools/msvs/npm/npmrc b/node-v0.8.14/tools/msvs/npm/npmrc new file mode 100644 index 0000000..cbea674 --- /dev/null +++ b/node-v0.8.14/tools/msvs/npm/npmrc @@ -0,0 +1 @@ +prefix=${APPDATA}\npm diff --git a/node-v0.8.14/tools/node-waf b/node-v0.8.14/tools/node-waf new file mode 100755 index 0000000..cbf0d0b --- /dev/null +++ b/node-v0.8.14/tools/node-waf @@ -0,0 +1,17 @@ +#!/usr/bin/env python +import os, sys + + +join = os.path.join +bindir = os.path.dirname(os.path.realpath(__file__)) +prefix = join(bindir, "..") +wafdir = join(prefix, "lib", "node") + +w = join(wafdir, 'wafadmin') +t = join(w, 'Tools') +sys.path = [w, t] + sys.path + +import Scripting +VERSION="1.5.16" +Scripting.prepare(t, os.getcwd(), VERSION, wafdir) +sys.exit(0) diff --git a/node-v0.8.14/tools/osx-codesign.sh b/node-v0.8.14/tools/osx-codesign.sh new file mode 100644 index 0000000..65a8d48 --- /dev/null +++ b/node-v0.8.14/tools/osx-codesign.sh @@ -0,0 +1,12 @@ +#!/bin/bash + +set -x +set -e + +if ! [ -n "$SIGN" ] && [ $STEP -eq 1 ]; then + echo "No SIGN environment var. Skipping codesign." >&2 + exit 0 +fi + +codesign -s "$SIGN" "$PKGDIR"/usr/local/bin/node +codesign -s "$SIGN" "$PKGDIR"/32/usr/local/bin/node diff --git a/node-v0.8.14/tools/osx-pkg-postinstall.sh b/node-v0.8.14/tools/osx-pkg-postinstall.sh new file mode 100644 index 0000000..c4c872f --- /dev/null +++ b/node-v0.8.14/tools/osx-pkg-postinstall.sh @@ -0,0 +1,5 @@ +#!/bin/sh +# TODO Can this be done inside the .pmdoc? +# TODO Can we extract $PREFIX from the installer? +cd /usr/local/bin +ln -sf ../lib/node_modules/npm/bin/npm-cli.js npm diff --git a/node-v0.8.14/tools/osx-pkg.pmdoc/01local-contents.xml b/node-v0.8.14/tools/osx-pkg.pmdoc/01local-contents.xml new file mode 100644 index 0000000..bc1e5a7 --- /dev/null +++ b/node-v0.8.14/tools/osx-pkg.pmdoc/01local-contents.xml @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/node-v0.8.14/tools/osx-pkg.pmdoc/01local.xml b/node-v0.8.14/tools/osx-pkg.pmdoc/01local.xml new file mode 100644 index 0000000..18fd871 --- /dev/null +++ b/node-v0.8.14/tools/osx-pkg.pmdoc/01local.xml @@ -0,0 +1 @@ +org.nodejs.pkg1.0../out/dist-osx/usr/local//usr/localinstallTo.isRelativeTypeinstallTolocationTyperelocatableinstallFrom.pathinstallTo.isAbsoluteTypeidentifierparentinstallTo.pathinstallFrom.isRelativeType \ No newline at end of file diff --git a/node-v0.8.14/tools/osx-pkg.pmdoc/02npm-contents.xml b/node-v0.8.14/tools/osx-pkg.pmdoc/02npm-contents.xml new file mode 100644 index 0000000..bc1e5a7 --- /dev/null +++ b/node-v0.8.14/tools/osx-pkg.pmdoc/02npm-contents.xml @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/node-v0.8.14/tools/osx-pkg.pmdoc/02npm.xml b/node-v0.8.14/tools/osx-pkg.pmdoc/02npm.xml new file mode 100644 index 0000000..4f7799f --- /dev/null +++ b/node-v0.8.14/tools/osx-pkg.pmdoc/02npm.xml @@ -0,0 +1 @@ +org.nodejs.node.npm.pkg1.0../deps/npm/usr/local/lib/node_modules/npminstallTo.pathinstallFrom.isRelativeTypeinstallToscripts.postinstall.isRelativeTypeparentinstallTo.isAbsoluteTypeosx-pkg-postinstall.sh \ No newline at end of file diff --git a/node-v0.8.14/tools/osx-pkg.pmdoc/index.xml b/node-v0.8.14/tools/osx-pkg.pmdoc/index.xml new file mode 100644 index 0000000..2233f1c --- /dev/null +++ b/node-v0.8.14/tools/osx-pkg.pmdoc/index.xml @@ -0,0 +1,19 @@ +Node/Users/ryan/Desktop/Node.pkgorg.nodejs../doc/mac_osx_nodejs_installer_logo.png../LICENSE01local.xml02npm.xmlproperties.titleproperties.userDomainproperties.anywhereDomainproperties.systemDomain \ No newline at end of file diff --git a/node-v0.8.14/tools/osx-productsign.sh b/node-v0.8.14/tools/osx-productsign.sh new file mode 100644 index 0000000..4834c9b --- /dev/null +++ b/node-v0.8.14/tools/osx-productsign.sh @@ -0,0 +1,12 @@ +#!/bin/bash + +set -x +set -e + +if ! [ -n "$SIGN" ]; then + echo "No SIGN environment var. Skipping codesign." >&2 + exit 0 +fi + +productsign --sign "$SIGN" "$PKG" "$PKG"-SIGNED +mv "$PKG"-SIGNED "$PKG" diff --git a/node-v0.8.14/tools/test.py b/node-v0.8.14/tools/test.py new file mode 100755 index 0000000..d711f9c --- /dev/null +++ b/node-v0.8.14/tools/test.py @@ -0,0 +1,1440 @@ +#!/usr/bin/env python +# +# Copyright 2008 the V8 project authors. All rights reserved. +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above +# copyright notice, this list of conditions and the following +# disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of Google Inc. nor the names of its +# contributors may be used to endorse or promote products derived +# from this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + +import imp +import optparse +import os +from os.path import join, dirname, abspath, basename, isdir, exists +import platform +import re +import signal +import subprocess +import sys +import tempfile +import time +import threading +from Queue import Queue, Empty + +sys.path.append(dirname(__file__) + "/../deps/v8/tools"); +import utils + +VERBOSE = False + + +# --------------------------------------------- +# --- P r o g r e s s I n d i c a t o r s --- +# --------------------------------------------- + + +class ProgressIndicator(object): + + def __init__(self, cases): + self.cases = cases + self.queue = Queue(len(cases)) + for case in cases: + self.queue.put_nowait(case) + self.succeeded = 0 + self.remaining = len(cases) + self.total = len(cases) + self.failed = [ ] + self.crashed = 0 + self.terminate = False + self.lock = threading.Lock() + + def PrintFailureHeader(self, test): + if test.IsNegative(): + negative_marker = '[negative] ' + else: + negative_marker = '' + print "=== %(label)s %(negative)s===" % { + 'label': test.GetLabel(), + 'negative': negative_marker + } + print "Path: %s" % "/".join(test.path) + + def Run(self, tasks): + self.Starting() + threads = [] + # Spawn N-1 threads and then use this thread as the last one. + # That way -j1 avoids threading altogether which is a nice fallback + # in case of threading problems. + for i in xrange(tasks - 1): + thread = threading.Thread(target=self.RunSingle, args=[]) + threads.append(thread) + thread.start() + try: + self.RunSingle() + # Wait for the remaining threads + for thread in threads: + # Use a timeout so that signals (ctrl-c) will be processed. + thread.join(timeout=10000000) + except Exception, e: + # If there's an exception we schedule an interruption for any + # remaining threads. + self.terminate = True + # ...and then reraise the exception to bail out + raise + self.Done() + return not self.failed + + def RunSingle(self): + while not self.terminate: + try: + test = self.queue.get_nowait() + except Empty: + return + case = test.case + self.lock.acquire() + self.AboutToRun(case) + self.lock.release() + try: + start = time.time() + output = case.Run() + case.duration = (time.time() - start) + except IOError, e: + assert self.terminate + return + if self.terminate: + return + self.lock.acquire() + if output.UnexpectedOutput(): + self.failed.append(output) + if output.HasCrashed(): + self.crashed += 1 + else: + self.succeeded += 1 + self.remaining -= 1 + self.HasRun(output) + self.lock.release() + + +def EscapeCommand(command): + parts = [] + for part in command: + if ' ' in part: + # Escape spaces. We may need to escape more characters for this + # to work properly. + parts.append('"%s"' % part) + else: + parts.append(part) + return " ".join(parts) + + +class SimpleProgressIndicator(ProgressIndicator): + + def Starting(self): + print 'Running %i tests' % len(self.cases) + + def Done(self): + print + for failed in self.failed: + self.PrintFailureHeader(failed.test) + if failed.output.stderr: + print "--- stderr ---" + print failed.output.stderr.strip() + if failed.output.stdout: + print "--- stdout ---" + print failed.output.stdout.strip() + print "Command: %s" % EscapeCommand(failed.command) + if failed.HasCrashed(): + print "--- CRASHED ---" + if failed.HasTimedOut(): + print "--- TIMEOUT ---" + if len(self.failed) == 0: + print "===" + print "=== All tests succeeded" + print "===" + else: + print + print "===" + print "=== %i tests failed" % len(self.failed) + if self.crashed > 0: + print "=== %i tests CRASHED" % self.crashed + print "===" + + +class VerboseProgressIndicator(SimpleProgressIndicator): + + def AboutToRun(self, case): + print 'Starting %s...' % case.GetLabel() + sys.stdout.flush() + + def HasRun(self, output): + if output.UnexpectedOutput(): + if output.HasCrashed(): + outcome = 'CRASH' + else: + outcome = 'FAIL' + else: + outcome = 'pass' + print 'Done running %s: %s' % (output.test.GetLabel(), outcome) + + +class DotsProgressIndicator(SimpleProgressIndicator): + + def AboutToRun(self, case): + pass + + def HasRun(self, output): + total = self.succeeded + len(self.failed) + if (total > 1) and (total % 50 == 1): + sys.stdout.write('\n') + if output.UnexpectedOutput(): + if output.HasCrashed(): + sys.stdout.write('C') + sys.stdout.flush() + elif output.HasTimedOut(): + sys.stdout.write('T') + sys.stdout.flush() + else: + sys.stdout.write('F') + sys.stdout.flush() + else: + sys.stdout.write('.') + sys.stdout.flush() + + +class CompactProgressIndicator(ProgressIndicator): + + def __init__(self, cases, templates): + super(CompactProgressIndicator, self).__init__(cases) + self.templates = templates + self.last_status_length = 0 + self.start_time = time.time() + + def Starting(self): + pass + + def Done(self): + self.PrintProgress('Done') + + def AboutToRun(self, case): + self.PrintProgress(case.GetLabel()) + + def HasRun(self, output): + if output.UnexpectedOutput(): + self.ClearLine(self.last_status_length) + self.PrintFailureHeader(output.test) + stdout = output.output.stdout.strip() + if len(stdout): + print self.templates['stdout'] % stdout + stderr = output.output.stderr.strip() + if len(stderr): + print self.templates['stderr'] % stderr + print "Command: %s" % EscapeCommand(output.command) + if output.HasCrashed(): + print "--- CRASHED ---" + if output.HasTimedOut(): + print "--- TIMEOUT ---" + + def Truncate(self, str, length): + if length and (len(str) > (length - 3)): + return str[:(length-3)] + "..." + else: + return str + + def PrintProgress(self, name): + self.ClearLine(self.last_status_length) + elapsed = time.time() - self.start_time + status = self.templates['status_line'] % { + 'passed': self.succeeded, + 'remaining': (((self.total - self.remaining) * 100) // self.total), + 'failed': len(self.failed), + 'test': name, + 'mins': int(elapsed) / 60, + 'secs': int(elapsed) % 60 + } + status = self.Truncate(status, 78) + self.last_status_length = len(status) + print status, + sys.stdout.flush() + + +class ColorProgressIndicator(CompactProgressIndicator): + + def __init__(self, cases): + templates = { + 'status_line': "[%(mins)02i:%(secs)02i|\033[34m%%%(remaining) 4d\033[0m|\033[32m+%(passed) 4d\033[0m|\033[31m-%(failed) 4d\033[0m]: %(test)s", + 'stdout': "\033[1m%s\033[0m", + 'stderr': "\033[31m%s\033[0m", + } + super(ColorProgressIndicator, self).__init__(cases, templates) + + def ClearLine(self, last_line_length): + print "\033[1K\r", + + +class MonochromeProgressIndicator(CompactProgressIndicator): + + def __init__(self, cases): + templates = { + 'status_line': "[%(mins)02i:%(secs)02i|%%%(remaining) 4d|+%(passed) 4d|-%(failed) 4d]: %(test)s", + 'stdout': '%s', + 'stderr': '%s', + 'clear': lambda last_line_length: ("\r" + (" " * last_line_length) + "\r"), + 'max_length': 78 + } + super(MonochromeProgressIndicator, self).__init__(cases, templates) + + def ClearLine(self, last_line_length): + print ("\r" + (" " * last_line_length) + "\r"), + + +PROGRESS_INDICATORS = { + 'verbose': VerboseProgressIndicator, + 'dots': DotsProgressIndicator, + 'color': ColorProgressIndicator, + 'mono': MonochromeProgressIndicator +} + + +# ------------------------- +# --- F r a m e w o r k --- +# ------------------------- + + +class CommandOutput(object): + + def __init__(self, exit_code, timed_out, stdout, stderr): + self.exit_code = exit_code + self.timed_out = timed_out + self.stdout = stdout + self.stderr = stderr + self.failed = None + + +class TestCase(object): + + def __init__(self, context, path, mode): + self.path = path + self.context = context + self.duration = None + self.mode = mode + + def IsNegative(self): + return False + + def CompareTime(self, other): + return cmp(other.duration, self.duration) + + def DidFail(self, output): + if output.failed is None: + output.failed = self.IsFailureOutput(output) + return output.failed + + def IsFailureOutput(self, output): + return output.exit_code != 0 + + def GetSource(self): + return "(no source available)" + + def RunCommand(self, command): + full_command = self.context.processor(command) + output = Execute(full_command, + self.context, + self.context.GetTimeout(self.mode)) + self.Cleanup() + return TestOutput(self, + full_command, + output, + self.context.store_unexpected_output) + + def BeforeRun(self): + pass + + def AfterRun(self, result): + pass + + def Run(self): + self.BeforeRun() + try: + result = self.RunCommand(self.GetCommand()) + finally: + self.AfterRun(result) + return result + + def Cleanup(self): + return + + +class TestOutput(object): + + def __init__(self, test, command, output, store_unexpected_output): + self.test = test + self.command = command + self.output = output + self.store_unexpected_output = store_unexpected_output + + def UnexpectedOutput(self): + if self.HasCrashed(): + outcome = CRASH + elif self.HasTimedOut(): + outcome = TIMEOUT + elif self.HasFailed(): + outcome = FAIL + else: + outcome = PASS + return not outcome in self.test.outcomes + + def HasPreciousOutput(self): + return self.UnexpectedOutput() and self.store_unexpected_output + + def HasCrashed(self): + if utils.IsWindows(): + return 0x80000000 & self.output.exit_code and not (0x3FFFFF00 & self.output.exit_code) + else: + # Timed out tests will have exit_code -signal.SIGTERM. + if self.output.timed_out: + return False + return self.output.exit_code < 0 and \ + self.output.exit_code != -signal.SIGABRT + + def HasTimedOut(self): + return self.output.timed_out; + + def HasFailed(self): + execution_failed = self.test.DidFail(self.output) + if self.test.IsNegative(): + return not execution_failed + else: + return execution_failed + + +def KillProcessWithID(pid): + if utils.IsWindows(): + os.popen('taskkill /T /F /PID %d' % pid) + else: + os.kill(pid, signal.SIGTERM) + + +MAX_SLEEP_TIME = 0.1 +INITIAL_SLEEP_TIME = 0.0001 +SLEEP_TIME_FACTOR = 1.25 + +SEM_INVALID_VALUE = -1 +SEM_NOGPFAULTERRORBOX = 0x0002 # Microsoft Platform SDK WinBase.h + +def Win32SetErrorMode(mode): + prev_error_mode = SEM_INVALID_VALUE + try: + import ctypes + prev_error_mode = ctypes.windll.kernel32.SetErrorMode(mode); + except ImportError: + pass + return prev_error_mode + +def RunProcess(context, timeout, args, **rest): + if context.verbose: print "#", " ".join(args) + popen_args = args + prev_error_mode = SEM_INVALID_VALUE; + if utils.IsWindows(): + if context.suppress_dialogs: + # Try to change the error mode to avoid dialogs on fatal errors. Don't + # touch any existing error mode flags by merging the existing error mode. + # See http://blogs.msdn.com/oldnewthing/archive/2004/07/27/198410.aspx. + error_mode = SEM_NOGPFAULTERRORBOX; + prev_error_mode = Win32SetErrorMode(error_mode); + Win32SetErrorMode(error_mode | prev_error_mode); + process = subprocess.Popen( + shell = utils.IsWindows(), + args = popen_args, + **rest + ) + if utils.IsWindows() and context.suppress_dialogs and prev_error_mode != SEM_INVALID_VALUE: + Win32SetErrorMode(prev_error_mode) + # Compute the end time - if the process crosses this limit we + # consider it timed out. + if timeout is None: end_time = None + else: end_time = time.time() + timeout + timed_out = False + # Repeatedly check the exit code from the process in a + # loop and keep track of whether or not it times out. + exit_code = None + sleep_time = INITIAL_SLEEP_TIME + while exit_code is None: + if (not end_time is None) and (time.time() >= end_time): + # Kill the process and wait for it to exit. + KillProcessWithID(process.pid) + exit_code = process.wait() + timed_out = True + else: + exit_code = process.poll() + time.sleep(sleep_time) + sleep_time = sleep_time * SLEEP_TIME_FACTOR + if sleep_time > MAX_SLEEP_TIME: + sleep_time = MAX_SLEEP_TIME + return (process, exit_code, timed_out) + + +def PrintError(str): + sys.stderr.write(str) + sys.stderr.write('\n') + + +def CheckedUnlink(name): + try: + os.unlink(name) + except OSError, e: + PrintError("os.unlink() " + str(e)) + + +def Execute(args, context, timeout=None): + (fd_out, outname) = tempfile.mkstemp() + (fd_err, errname) = tempfile.mkstemp() + (process, exit_code, timed_out) = RunProcess( + context, + timeout, + args = args, + stdout = fd_out, + stderr = fd_err, + ) + os.close(fd_out) + os.close(fd_err) + output = file(outname).read() + errors = file(errname).read() + CheckedUnlink(outname) + CheckedUnlink(errname) + return CommandOutput(exit_code, timed_out, output, errors) + + +def ExecuteNoCapture(args, context, timeout=None): + (process, exit_code, timed_out) = RunProcess( + context, + timeout, + args = args, + ) + return CommandOutput(exit_code, False, "", "") + + +def CarCdr(path): + if len(path) == 0: + return (None, [ ]) + else: + return (path[0], path[1:]) + + +class TestConfiguration(object): + + def __init__(self, context, root): + self.context = context + self.root = root + + def Contains(self, path, file): + if len(path) > len(file): + return False + for i in xrange(len(path)): + if not path[i].match(file[i]): + return False + return True + + def GetTestStatus(self, sections, defs): + pass + + +class TestSuite(object): + + def __init__(self, name): + self.name = name + + def GetName(self): + return self.name + + +# Use this to run several variants of the tests, e.g.: +# VARIANT_FLAGS = [[], ['--always_compact', '--noflush_code']] +VARIANT_FLAGS = [[]] + + +class TestRepository(TestSuite): + + def __init__(self, path): + normalized_path = abspath(path) + super(TestRepository, self).__init__(basename(normalized_path)) + self.path = normalized_path + self.is_loaded = False + self.config = None + + def GetConfiguration(self, context): + if self.is_loaded: + return self.config + self.is_loaded = True + file = None + try: + (file, pathname, description) = imp.find_module('testcfg', [ self.path ]) + module = imp.load_module('testcfg', file, pathname, description) + self.config = module.GetConfiguration(context, self.path) + finally: + if file: + file.close() + return self.config + + def GetBuildRequirements(self, path, context): + return self.GetConfiguration(context).GetBuildRequirements() + + def AddTestsToList(self, result, current_path, path, context, mode): + for v in VARIANT_FLAGS: + tests = self.GetConfiguration(context).ListTests(current_path, path, mode) + for t in tests: t.variant_flags = v + result += tests + + + def GetTestStatus(self, context, sections, defs): + self.GetConfiguration(context).GetTestStatus(sections, defs) + + +class LiteralTestSuite(TestSuite): + + def __init__(self, tests): + super(LiteralTestSuite, self).__init__('root') + self.tests = tests + + def GetBuildRequirements(self, path, context): + (name, rest) = CarCdr(path) + result = [ ] + for test in self.tests: + if not name or name.match(test.GetName()): + result += test.GetBuildRequirements(rest, context) + return result + + def ListTests(self, current_path, path, context, mode): + (name, rest) = CarCdr(path) + result = [ ] + for test in self.tests: + test_name = test.GetName() + if not name or name.match(test_name): + full_path = current_path + [test_name] + test.AddTestsToList(result, full_path, path, context, mode) + return result + + def GetTestStatus(self, context, sections, defs): + for test in self.tests: + test.GetTestStatus(context, sections, defs) + + +SUFFIX = { + 'debug' : '_g', + 'release' : '' } +FLAGS = { + 'debug' : ['--enable-slow-asserts', '--debug-code', '--verify-heap'], + 'release' : []} +TIMEOUT_SCALEFACTOR = { + 'debug' : 4, + 'release' : 1 } + + +class Context(object): + + def __init__(self, workspace, buildspace, verbose, vm, timeout, processor, suppress_dialogs, store_unexpected_output): + self.workspace = workspace + self.buildspace = buildspace + self.verbose = verbose + self.vm_root = vm + self.timeout = timeout + self.processor = processor + self.suppress_dialogs = suppress_dialogs + self.store_unexpected_output = store_unexpected_output + + def GetVm(self, mode): + if mode == 'debug': + name = 'out/Debug/node' + else: + name = 'out/Release/node' + + # Currently GYP does not support output_dir for MSVS. + # http://code.google.com/p/gyp/issues/detail?id=40 + # It will put the builds into Release/node.exe or Debug/node.exe + if utils.IsWindows(): + out_dir = os.path.join(dirname(__file__), "..", "out") + if not exists(out_dir): + if mode == 'debug': + name = os.path.abspath('Debug/node.exe') + else: + name = os.path.abspath('Release/node.exe') + else: + name = os.path.abspath(name + '.exe') + + return name + + def GetVmCommand(self, testcase, mode): + return [self.GetVm(mode)] + self.GetVmFlags(testcase, mode) + + def GetVmFlags(self, testcase, mode): + return testcase.variant_flags + FLAGS[mode] + + def GetTimeout(self, mode): + return self.timeout * TIMEOUT_SCALEFACTOR[mode] + +def RunTestCases(cases_to_run, progress, tasks): + progress = PROGRESS_INDICATORS[progress](cases_to_run) + return progress.Run(tasks) + + +def BuildRequirements(context, requirements, mode, scons_flags): + command_line = (['scons', '-Y', context.workspace, 'mode=' + ",".join(mode)] + + requirements + + scons_flags) + output = ExecuteNoCapture(command_line, context) + return output.exit_code == 0 + + +# ------------------------------------------- +# --- T e s t C o n f i g u r a t i o n --- +# ------------------------------------------- + + +SKIP = 'skip' +FAIL = 'fail' +PASS = 'pass' +OKAY = 'okay' +TIMEOUT = 'timeout' +CRASH = 'crash' +SLOW = 'slow' + + +class Expression(object): + pass + + +class Constant(Expression): + + def __init__(self, value): + self.value = value + + def Evaluate(self, env, defs): + return self.value + + +class Variable(Expression): + + def __init__(self, name): + self.name = name + + def GetOutcomes(self, env, defs): + if self.name in env: return ListSet([env[self.name]]) + else: return Nothing() + + +class Outcome(Expression): + + def __init__(self, name): + self.name = name + + def GetOutcomes(self, env, defs): + if self.name in defs: + return defs[self.name].GetOutcomes(env, defs) + else: + return ListSet([self.name]) + + +class Set(object): + pass + + +class ListSet(Set): + + def __init__(self, elms): + self.elms = elms + + def __str__(self): + return "ListSet%s" % str(self.elms) + + def Intersect(self, that): + if not isinstance(that, ListSet): + return that.Intersect(self) + return ListSet([ x for x in self.elms if x in that.elms ]) + + def Union(self, that): + if not isinstance(that, ListSet): + return that.Union(self) + return ListSet(self.elms + [ x for x in that.elms if x not in self.elms ]) + + def IsEmpty(self): + return len(self.elms) == 0 + + +class Everything(Set): + + def Intersect(self, that): + return that + + def Union(self, that): + return self + + def IsEmpty(self): + return False + + +class Nothing(Set): + + def Intersect(self, that): + return self + + def Union(self, that): + return that + + def IsEmpty(self): + return True + + +class Operation(Expression): + + def __init__(self, left, op, right): + self.left = left + self.op = op + self.right = right + + def Evaluate(self, env, defs): + if self.op == '||' or self.op == ',': + return self.left.Evaluate(env, defs) or self.right.Evaluate(env, defs) + elif self.op == 'if': + return False + elif self.op == '==': + inter = self.left.GetOutcomes(env, defs).Intersect(self.right.GetOutcomes(env, defs)) + return not inter.IsEmpty() + else: + assert self.op == '&&' + return self.left.Evaluate(env, defs) and self.right.Evaluate(env, defs) + + def GetOutcomes(self, env, defs): + if self.op == '||' or self.op == ',': + return self.left.GetOutcomes(env, defs).Union(self.right.GetOutcomes(env, defs)) + elif self.op == 'if': + if self.right.Evaluate(env, defs): return self.left.GetOutcomes(env, defs) + else: return Nothing() + else: + assert self.op == '&&' + return self.left.GetOutcomes(env, defs).Intersect(self.right.GetOutcomes(env, defs)) + + +def IsAlpha(str): + for char in str: + if not (char.isalpha() or char.isdigit() or char == '_'): + return False + return True + + +class Tokenizer(object): + """A simple string tokenizer that chops expressions into variables, + parens and operators""" + + def __init__(self, expr): + self.index = 0 + self.expr = expr + self.length = len(expr) + self.tokens = None + + def Current(self, length = 1): + if not self.HasMore(length): return "" + return self.expr[self.index:self.index+length] + + def HasMore(self, length = 1): + return self.index < self.length + (length - 1) + + def Advance(self, count = 1): + self.index = self.index + count + + def AddToken(self, token): + self.tokens.append(token) + + def SkipSpaces(self): + while self.HasMore() and self.Current().isspace(): + self.Advance() + + def Tokenize(self): + self.tokens = [ ] + while self.HasMore(): + self.SkipSpaces() + if not self.HasMore(): + return None + if self.Current() == '(': + self.AddToken('(') + self.Advance() + elif self.Current() == ')': + self.AddToken(')') + self.Advance() + elif self.Current() == '$': + self.AddToken('$') + self.Advance() + elif self.Current() == ',': + self.AddToken(',') + self.Advance() + elif IsAlpha(self.Current()): + buf = "" + while self.HasMore() and IsAlpha(self.Current()): + buf += self.Current() + self.Advance() + self.AddToken(buf) + elif self.Current(2) == '&&': + self.AddToken('&&') + self.Advance(2) + elif self.Current(2) == '||': + self.AddToken('||') + self.Advance(2) + elif self.Current(2) == '==': + self.AddToken('==') + self.Advance(2) + else: + return None + return self.tokens + + +class Scanner(object): + """A simple scanner that can serve out tokens from a given list""" + + def __init__(self, tokens): + self.tokens = tokens + self.length = len(tokens) + self.index = 0 + + def HasMore(self): + return self.index < self.length + + def Current(self): + return self.tokens[self.index] + + def Advance(self): + self.index = self.index + 1 + + +def ParseAtomicExpression(scan): + if scan.Current() == "true": + scan.Advance() + return Constant(True) + elif scan.Current() == "false": + scan.Advance() + return Constant(False) + elif IsAlpha(scan.Current()): + name = scan.Current() + scan.Advance() + return Outcome(name.lower()) + elif scan.Current() == '$': + scan.Advance() + if not IsAlpha(scan.Current()): + return None + name = scan.Current() + scan.Advance() + return Variable(name.lower()) + elif scan.Current() == '(': + scan.Advance() + result = ParseLogicalExpression(scan) + if (not result) or (scan.Current() != ')'): + return None + scan.Advance() + return result + else: + return None + + +BINARIES = ['=='] +def ParseOperatorExpression(scan): + left = ParseAtomicExpression(scan) + if not left: return None + while scan.HasMore() and (scan.Current() in BINARIES): + op = scan.Current() + scan.Advance() + right = ParseOperatorExpression(scan) + if not right: + return None + left = Operation(left, op, right) + return left + + +def ParseConditionalExpression(scan): + left = ParseOperatorExpression(scan) + if not left: return None + while scan.HasMore() and (scan.Current() == 'if'): + scan.Advance() + right = ParseOperatorExpression(scan) + if not right: + return None + left= Operation(left, 'if', right) + return left + + +LOGICALS = ["&&", "||", ","] +def ParseLogicalExpression(scan): + left = ParseConditionalExpression(scan) + if not left: return None + while scan.HasMore() and (scan.Current() in LOGICALS): + op = scan.Current() + scan.Advance() + right = ParseConditionalExpression(scan) + if not right: + return None + left = Operation(left, op, right) + return left + + +def ParseCondition(expr): + """Parses a logical expression into an Expression object""" + tokens = Tokenizer(expr).Tokenize() + if not tokens: + print "Malformed expression: '%s'" % expr + return None + scan = Scanner(tokens) + ast = ParseLogicalExpression(scan) + if not ast: + print "Malformed expression: '%s'" % expr + return None + if scan.HasMore(): + print "Malformed expression: '%s'" % expr + return None + return ast + + +class ClassifiedTest(object): + + def __init__(self, case, outcomes): + self.case = case + self.outcomes = outcomes + + +class Configuration(object): + """The parsed contents of a configuration file""" + + def __init__(self, sections, defs): + self.sections = sections + self.defs = defs + + def ClassifyTests(self, cases, env): + sections = [s for s in self.sections if s.condition.Evaluate(env, self.defs)] + all_rules = reduce(list.__add__, [s.rules for s in sections], []) + unused_rules = set(all_rules) + result = [ ] + all_outcomes = set([]) + for case in cases: + matches = [ r for r in all_rules if r.Contains(case.path) ] + outcomes = set([]) + for rule in matches: + outcomes = outcomes.union(rule.GetOutcomes(env, self.defs)) + unused_rules.discard(rule) + if not outcomes: + outcomes = [PASS] + case.outcomes = outcomes + all_outcomes = all_outcomes.union(outcomes) + result.append(ClassifiedTest(case, outcomes)) + return (result, list(unused_rules), all_outcomes) + + +class Section(object): + """A section of the configuration file. Sections are enabled or + disabled prior to running the tests, based on their conditions""" + + def __init__(self, condition): + self.condition = condition + self.rules = [ ] + + def AddRule(self, rule): + self.rules.append(rule) + + +class Rule(object): + """A single rule that specifies the expected outcome for a single + test.""" + + def __init__(self, raw_path, path, value): + self.raw_path = raw_path + self.path = path + self.value = value + + def GetOutcomes(self, env, defs): + set = self.value.GetOutcomes(env, defs) + assert isinstance(set, ListSet) + return set.elms + + def Contains(self, path): + if len(self.path) > len(path): + return False + for i in xrange(len(self.path)): + if not self.path[i].match(path[i]): + return False + return True + + +HEADER_PATTERN = re.compile(r'\[([^]]+)\]') +RULE_PATTERN = re.compile(r'\s*([^: ]*)\s*:(.*)') +DEF_PATTERN = re.compile(r'^def\s*(\w+)\s*=(.*)$') +PREFIX_PATTERN = re.compile(r'^\s*prefix\s+([\w\_\.\-\/]+)$') + + +def ReadConfigurationInto(path, sections, defs): + current_section = Section(Constant(True)) + sections.append(current_section) + prefix = [] + for line in utils.ReadLinesFrom(path): + header_match = HEADER_PATTERN.match(line) + if header_match: + condition_str = header_match.group(1).strip() + condition = ParseCondition(condition_str) + new_section = Section(condition) + sections.append(new_section) + current_section = new_section + continue + rule_match = RULE_PATTERN.match(line) + if rule_match: + path = prefix + SplitPath(rule_match.group(1).strip()) + value_str = rule_match.group(2).strip() + value = ParseCondition(value_str) + if not value: + return False + current_section.AddRule(Rule(rule_match.group(1), path, value)) + continue + def_match = DEF_PATTERN.match(line) + if def_match: + name = def_match.group(1).lower() + value = ParseCondition(def_match.group(2).strip()) + if not value: + return False + defs[name] = value + continue + prefix_match = PREFIX_PATTERN.match(line) + if prefix_match: + prefix = SplitPath(prefix_match.group(1).strip()) + continue + print "Malformed line: '%s'." % line + return False + return True + + +# --------------- +# --- M a i n --- +# --------------- + + +ARCH_GUESS = utils.GuessArchitecture() + + +def BuildOptions(): + result = optparse.OptionParser() + result.add_option("-m", "--mode", help="The test modes in which to run (comma-separated)", + default='release') + result.add_option("-v", "--verbose", help="Verbose output", + default=False, action="store_true") + result.add_option("-S", dest="scons_flags", help="Flag to pass through to scons", + default=[], action="append") + result.add_option("-p", "--progress", + help="The style of progress indicator (verbose, dots, color, mono)", + choices=PROGRESS_INDICATORS.keys(), default="mono") + result.add_option("--no-build", help="Don't build requirements", + default=True, action="store_true") + result.add_option("--build-only", help="Only build requirements, don't run the tests", + default=False, action="store_true") + result.add_option("--report", help="Print a summary of the tests to be run", + default=False, action="store_true") + result.add_option("-s", "--suite", help="A test suite", + default=[], action="append") + result.add_option("-t", "--timeout", help="Timeout in seconds", + default=60, type="int") + result.add_option("--arch", help='The architecture to run tests for', + default='none') + result.add_option("--snapshot", help="Run the tests with snapshot turned on", + default=False, action="store_true") + result.add_option("--simulator", help="Run tests with architecture simulator", + default='none') + result.add_option("--special-command", default=None) + result.add_option("--use-http1", help="Pass --use-http1 switch to node", + default=False, action="store_true") + result.add_option("--valgrind", help="Run tests through valgrind", + default=False, action="store_true") + result.add_option("--cat", help="Print the source of the tests", + default=False, action="store_true") + result.add_option("--warn-unused", help="Report unused rules", + default=False, action="store_true") + result.add_option("-j", help="The number of parallel tasks to run", + default=1, type="int") + result.add_option("--time", help="Print timing information after running", + default=False, action="store_true") + result.add_option("--suppress-dialogs", help="Suppress Windows dialogs for crashing tests", + dest="suppress_dialogs", default=True, action="store_true") + result.add_option("--no-suppress-dialogs", help="Display Windows dialogs for crashing tests", + dest="suppress_dialogs", action="store_false") + result.add_option("--shell", help="Path to V8 shell", default="shell") + result.add_option("--store-unexpected-output", + help="Store the temporary JS files from tests that fails", + dest="store_unexpected_output", default=True, action="store_true") + result.add_option("--no-store-unexpected-output", + help="Deletes the temporary JS files from tests that fails", + dest="store_unexpected_output", action="store_false") + return result + + +def ProcessOptions(options): + global VERBOSE + VERBOSE = options.verbose + options.mode = options.mode.split(',') + for mode in options.mode: + if not mode in ['debug', 'release']: + print "Unknown mode %s" % mode + return False + if options.simulator != 'none': + # Simulator argument was set. Make sure arch and simulator agree. + if options.simulator != options.arch: + if options.arch == 'none': + options.arch = options.simulator + else: + print "Architecture %s does not match sim %s" %(options.arch, options.simulator) + return False + # Ensure that the simulator argument is handed down to scons. + options.scons_flags.append("simulator=" + options.simulator) + else: + # If options.arch is not set by the command line and no simulator setting + # was found, set the arch to the guess. + if options.arch == 'none': + options.arch = ARCH_GUESS + options.scons_flags.append("arch=" + options.arch) + if options.snapshot: + options.scons_flags.append("snapshot=on") + return True + + +REPORT_TEMPLATE = """\ +Total: %(total)i tests + * %(skipped)4d tests will be skipped + * %(nocrash)4d tests are expected to be flaky but not crash + * %(pass)4d tests are expected to pass + * %(fail_ok)4d tests are expected to fail that we won't fix + * %(fail)4d tests are expected to fail that we should fix\ +""" + +def PrintReport(cases): + def IsFlaky(o): + return (PASS in o) and (FAIL in o) and (not CRASH in o) and (not OKAY in o) + def IsFailOk(o): + return (len(o) == 2) and (FAIL in o) and (OKAY in o) + unskipped = [c for c in cases if not SKIP in c.outcomes] + print REPORT_TEMPLATE % { + 'total': len(cases), + 'skipped': len(cases) - len(unskipped), + 'nocrash': len([t for t in unskipped if IsFlaky(t.outcomes)]), + 'pass': len([t for t in unskipped if list(t.outcomes) == [PASS]]), + 'fail_ok': len([t for t in unskipped if IsFailOk(t.outcomes)]), + 'fail': len([t for t in unskipped if list(t.outcomes) == [FAIL]]) + } + + +class Pattern(object): + + def __init__(self, pattern): + self.pattern = pattern + self.compiled = None + + def match(self, str): + if not self.compiled: + pattern = "^" + self.pattern.replace('*', '.*') + "$" + self.compiled = re.compile(pattern) + return self.compiled.match(str) + + def __str__(self): + return self.pattern + + +def SplitPath(s): + stripped = [ c.strip() for c in s.split('/') ] + return [ Pattern(s) for s in stripped if len(s) > 0 ] + + +def GetSpecialCommandProcessor(value): + if (not value) or (value.find('@') == -1): + def ExpandCommand(args): + return args + return ExpandCommand + else: + pos = value.find('@') + import urllib + prefix = urllib.unquote(value[:pos]).split() + suffix = urllib.unquote(value[pos+1:]).split() + def ExpandCommand(args): + return prefix + args + suffix + return ExpandCommand + + +BUILT_IN_TESTS = ['simple', 'pummel', 'message', 'internet', 'gc'] + + +def GetSuites(test_root): + def IsSuite(path): + return isdir(path) and exists(join(path, 'testcfg.py')) + return [ f for f in os.listdir(test_root) if IsSuite(join(test_root, f)) ] + + +def FormatTime(d): + millis = round(d * 1000) % 1000 + return time.strftime("%M:%S.", time.gmtime(d)) + ("%03i" % millis) + + +def Main(): + parser = BuildOptions() + (options, args) = parser.parse_args() + if not ProcessOptions(options): + parser.print_help() + return 1 + + workspace = abspath(join(dirname(sys.argv[0]), '..')) + suites = GetSuites(join(workspace, 'test')) + repositories = [TestRepository(join(workspace, 'test', name)) for name in suites] + repositories += [TestRepository(a) for a in options.suite] + + root = LiteralTestSuite(repositories) + if len(args) == 0: + paths = [SplitPath(t) for t in BUILT_IN_TESTS] + else: + paths = [ ] + for arg in args: + path = SplitPath(arg) + paths.append(path) + + # Check for --valgrind option. If enabled, we overwrite the special + # command flag with a command that uses the run-valgrind.py script. + if options.valgrind: + run_valgrind = join(workspace, "tools", "run-valgrind.py") + options.special_command = "python -u " + run_valgrind + " @" + + shell = abspath(options.shell) + buildspace = dirname(shell) + + processor = GetSpecialCommandProcessor(options.special_command) + if options.use_http1: + def wrap(processor): + return lambda args: processor(args[:1] + ['--use-http1'] + args[1:]) + processor = wrap(processor) + + context = Context(workspace, + buildspace, + VERBOSE, + shell, + options.timeout, + processor, + options.suppress_dialogs, + options.store_unexpected_output) + # First build the required targets + if not options.no_build: + reqs = [ ] + for path in paths: + reqs += root.GetBuildRequirements(path, context) + reqs = list(set(reqs)) + if len(reqs) > 0: + if options.j != 1: + options.scons_flags += ['-j', str(options.j)] + if not BuildRequirements(context, reqs, options.mode, options.scons_flags): + return 1 + + # Just return if we are only building the targets for running the tests. + if options.build_only: + return 0 + + # Get status for tests + sections = [ ] + defs = { } + root.GetTestStatus(context, sections, defs) + config = Configuration(sections, defs) + + # List the tests + all_cases = [ ] + all_unused = [ ] + unclassified_tests = [ ] + globally_unused_rules = None + for path in paths: + for mode in options.mode: + if not exists(context.GetVm(mode)): + print "Can't find shell executable: '%s'" % context.GetVm(mode) + continue + env = { + 'mode': mode, + 'system': utils.GuessOS(), + 'arch': options.arch, + 'simulator': options.simulator + } + test_list = root.ListTests([], path, context, mode) + unclassified_tests += test_list + (cases, unused_rules, all_outcomes) = config.ClassifyTests(test_list, env) + if globally_unused_rules is None: + globally_unused_rules = set(unused_rules) + else: + globally_unused_rules = globally_unused_rules.intersection(unused_rules) + all_cases += cases + all_unused.append(unused_rules) + + if options.cat: + visited = set() + for test in unclassified_tests: + key = tuple(test.path) + if key in visited: + continue + visited.add(key) + print "--- begin source: %s ---" % test.GetLabel() + source = test.GetSource().strip() + print source + print "--- end source: %s ---" % test.GetLabel() + return 0 + + if options.warn_unused: + for rule in globally_unused_rules: + print "Rule for '%s' was not used." % '/'.join([str(s) for s in rule.path]) + + if options.report: + PrintReport(all_cases) + + result = None + def DoSkip(case): + return SKIP in case.outcomes or SLOW in case.outcomes + cases_to_run = [ c for c in all_cases if not DoSkip(c) ] + if len(cases_to_run) == 0: + print "No tests to run." + return 0 + else: + try: + start = time.time() + if RunTestCases(cases_to_run, options.progress, options.j): + result = 0 + else: + result = 1 + duration = time.time() - start + except KeyboardInterrupt: + print "Interrupted" + return 1 + + if options.time: + # Write the times to stderr to make it easy to separate from the + # test output. + print + sys.stderr.write("--- Total time: %s ---\n" % FormatTime(duration)) + timed_tests = [ t.case for t in cases_to_run if not t.case.duration is None ] + timed_tests.sort(lambda a, b: a.CompareTime(b)) + index = 1 + for entry in timed_tests[:20]: + t = FormatTime(entry.duration) + sys.stderr.write("%4i (%s) %s\n" % (index, t, entry.GetLabel())) + index += 1 + + return result + + +if __name__ == '__main__': + sys.exit(Main()) diff --git a/node-v0.8.14/tools/updateAuthors.awk b/node-v0.8.14/tools/updateAuthors.awk new file mode 100644 index 0000000..4ede6ff --- /dev/null +++ b/node-v0.8.14/tools/updateAuthors.awk @@ -0,0 +1,13 @@ +# git log --pretty='format:%ae %an' | tac | awk -f tools/updateAuthors.awk +{ + if (!x[$1]++) { + #print $0 + n = split($0, a, " "); + s = a[2]; + for (i = 3; i <= n ; i++) { + s = s " " a[i]; + } + print s " <" $1 ">"; + } +} + diff --git a/node-v0.8.14/tools/waf-light b/node-v0.8.14/tools/waf-light new file mode 100755 index 0000000..b4acc4b --- /dev/null +++ b/node-v0.8.14/tools/waf-light @@ -0,0 +1,159 @@ +#!/usr/bin/env python +# encoding: ISO8859-1 +# Thomas Nagy, 2005-2010 + +""" +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: + +1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + +3. The name of the author may not be used to endorse or promote products + derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE AUTHOR "AS IS" AND ANY EXPRESS OR +IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, +INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) +HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, +STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING +IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +POSSIBILITY OF SUCH DAMAGE. +""" + +import os, sys +if sys.hexversion<0x203000f: raise ImportError("Waf requires Python >= 2.3") + +if 'PSYCOWAF' in os.environ: + try:import psyco;psyco.full() + except:pass + +VERSION="1.5.16" +REVISION="x" +INSTALL="x" +C1='x' +C2='x' +cwd = os.getcwd() +join = os.path.join + +WAF='waf' +def b(x): + return x + +if sys.hexversion>0x300000f: + WAF='waf3' + def b(x): + return x.encode() + +def err(m): + print(('\033[91mError: %s\033[0m' % m)) + sys.exit(1) + +def unpack_wafdir(dir): + f = open(sys.argv[0],'rb') + c = "corrupted waf (%d)" + while 1: + line = f.readline() + if not line: err("run waf-light from a folder containing wafadmin") + if line == b('#==>\n'): + txt = f.readline() + if not txt: err(c % 1) + if f.readline()!=b('#<==\n'): err(c % 2) + break + if not txt: err(c % 3) + txt = txt[1:-1].replace(b(C1), b('\n')).replace(b(C2), b('\r')) + + import shutil, tarfile + try: shutil.rmtree(dir) + except OSError: pass + try: + for x in ['Tools', '3rdparty']: + os.makedirs(join(dir, 'wafadmin', x)) + except OSError: + err("Cannot unpack waf lib into %s\nMove waf into a writeable directory" % dir) + + os.chdir(dir) + tmp = 't.bz2' + t = open(tmp,'wb') + t.write(txt) + t.close() + + t = None + try: + t = tarfile.open(tmp) + except: + try: + os.system('bunzip2 t.bz2') + t = tarfile.open('t') + except: + os.chdir(cwd) + try: shutil.rmtree(dir) + except OSError: pass + err("Waf cannot be unpacked, check that bzip2 support is present") + + for x in t: t.extract(x) + t.close() + + for x in ['Tools', '3rdparty']: + os.chmod(join('wafadmin',x), 493) + + if sys.hexversion>0x300000f: + sys.path = [join(dir, 'wafadmin')] + sys.path + import py3kfixes + py3kfixes.fixdir(dir) + + os.chdir(cwd) + +def test(dir): + try: os.stat(join(dir, 'wafadmin')); return os.path.abspath(dir) + except OSError: pass + +def find_lib(): + name = sys.argv[0] + base = os.path.dirname(os.path.abspath(name)) + + #devs use $WAFDIR + w=test(os.environ.get('WAFDIR', '')) + if w: return w + + #waf-light + if name.endswith('waf-light'): + w = test(base) + if w: return w + err("waf-light requires wafadmin -> export WAFDIR=/folder") + + dir = "/lib/%s-%s-%s/" % (WAF, VERSION, REVISION) + for i in [INSTALL,'/usr','/usr/local','/opt']: + w = test(i+dir) + if w: return w + + #waf-local + s = '.%s-%s-%s' + if sys.platform == 'win32': s = s[1:] + dir = join(base, s % (WAF, VERSION, REVISION)) + w = test(dir) + if w: return w + + #unpack + unpack_wafdir(dir) + return dir + +wafdir = find_lib() +w = join(wafdir, 'wafadmin') +t = join(w, 'Tools') +f = join(w, '3rdparty') +sys.path = [w, t, f] + sys.path + +if __name__ == '__main__': + import Scripting + Scripting.prepare(t, cwd, VERSION, wafdir) + diff --git a/node-v0.8.14/tools/wafadmin/Build.py b/node-v0.8.14/tools/wafadmin/Build.py new file mode 100644 index 0000000..675bca1 --- /dev/null +++ b/node-v0.8.14/tools/wafadmin/Build.py @@ -0,0 +1,1021 @@ +#!/usr/bin/env python +# encoding: utf-8 +# Thomas Nagy, 2005 (ita) + +""" +Dependency tree holder + +The class Build holds all the info related to a build: +* file system representation (tree of Node instances) +* various cached objects (task signatures, file scan results, ..) + +There is only one Build object at a time (bld singleton) +""" + +import os, sys, errno, re, glob, gc, datetime, shutil +try: import cPickle +except: import pickle as cPickle +import Runner, TaskGen, Node, Scripting, Utils, Environment, Task, Logs, Options +from Logs import debug, error, info +from Constants import * + +SAVED_ATTRS = 'root srcnode bldnode node_sigs node_deps raw_deps task_sigs id_nodes'.split() +"Build class members to save" + +bld = None +"singleton - safe to use when Waf is not used as a library" + +class BuildError(Utils.WafError): + def __init__(self, b=None, t=[]): + self.bld = b + self.tasks = t + self.ret = 1 + Utils.WafError.__init__(self, self.format_error()) + + def format_error(self): + lst = ['Build failed:'] + for tsk in self.tasks: + txt = tsk.format_error() + if txt: lst.append(txt) + sep = ' ' + if len(lst) > 2: + sep = '\n' + return sep.join(lst) + +def group_method(fun): + """ + sets a build context method to execute after the current group has finished executing + this is useful for installing build files: + * calling install_files/install_as will fail if called too early + * people do not want to define install method in their task classes + + TODO: try it + """ + def f(*k, **kw): + if not k[0].is_install: + return False + + postpone = True + if 'postpone' in kw: + postpone = kw['postpone'] + del kw['postpone'] + + # TODO waf 1.6 in theory there should be no reference to the TaskManager internals here + if postpone: + m = k[0].task_manager + if not m.groups: m.add_group() + m.groups[m.current_group].post_funs.append((fun, k, kw)) + if not 'cwd' in kw: + kw['cwd'] = k[0].path + else: + fun(*k, **kw) + return f + +class BuildContext(Utils.Context): + "holds the dependency tree" + def __init__(self): + + # not a singleton, but provided for compatibility + global bld + bld = self + + self.task_manager = Task.TaskManager() + + # instead of hashing the nodes, we assign them a unique id when they are created + self.id_nodes = 0 + self.idx = {} + + # map names to environments, the 'Release' must be defined + self.all_envs = {} + + # ======================================= # + # code for reading the scripts + + # project build directory - do not reset() from load_dirs() + self.bdir = '' + + # the current directory from which the code is run + # the folder changes everytime a wscript is read + self.path = None + + # Manual dependencies. + self.deps_man = Utils.DefaultDict(list) + + # ======================================= # + # cache variables + + # local cache for absolute paths - cache_node_abspath[variant][node] + self.cache_node_abspath = {} + + # list of folders that are already scanned + # so that we do not need to stat them one more time + self.cache_scanned_folders = {} + + # list of targets to uninstall for removing the empty folders after uninstalling + self.uninstall = [] + + # ======================================= # + # tasks and objects + + # build dir variants (release, debug, ..) + for v in 'cache_node_abspath task_sigs node_deps raw_deps node_sigs'.split(): + var = {} + setattr(self, v, var) + + self.cache_dir_contents = {} + + self.all_task_gen = [] + self.task_gen_cache_names = {} + self.cache_sig_vars = {} + self.log = None + + self.root = None + self.srcnode = None + self.bldnode = None + + # bind the build context to the nodes in use + # this means better encapsulation and no build context singleton + class node_class(Node.Node): + pass + self.node_class = node_class + self.node_class.__module__ = "Node" + self.node_class.__name__ = "Nodu" + self.node_class.bld = self + + self.is_install = None + + def __copy__(self): + "nodes are not supposed to be copied" + raise Utils.WafError('build contexts are not supposed to be cloned') + + def load(self): + "load the cache from the disk" + try: + env = Environment.Environment(os.path.join(self.cachedir, 'build.config.py')) + except (IOError, OSError): + pass + else: + if env['version'] < HEXVERSION: + raise Utils.WafError('Version mismatch! reconfigure the project') + for t in env['tools']: + self.setup(**t) + + try: + gc.disable() + f = data = None + + Node.Nodu = self.node_class + + try: + f = open(os.path.join(self.bdir, DBFILE), 'rb') + except (IOError, EOFError): + # handle missing file/empty file + pass + + try: + if f: data = cPickle.load(f) + except AttributeError: + # handle file of an old Waf version + # that has an attribute which no longer exist + # (e.g. AttributeError: 'module' object has no attribute 'BuildDTO') + if Logs.verbose > 1: raise + + if data: + for x in SAVED_ATTRS: setattr(self, x, data[x]) + else: + debug('build: Build cache loading failed') + + finally: + if f: f.close() + gc.enable() + + def save(self): + "store the cache on disk, see self.load" + gc.disable() + self.root.__class__.bld = None + + # some people are very nervous with ctrl+c so we have to make a temporary file + Node.Nodu = self.node_class + db = os.path.join(self.bdir, DBFILE) + file = open(db + '.tmp', 'wb') + data = {} + for x in SAVED_ATTRS: data[x] = getattr(self, x) + cPickle.dump(data, file, -1) + file.close() + + # do not use shutil.move + try: os.unlink(db) + except OSError: pass + os.rename(db + '.tmp', db) + self.root.__class__.bld = self + gc.enable() + + # ======================================= # + + def clean(self): + debug('build: clean called') + + # does not clean files created during the configuration + precious = set([]) + for env in self.all_envs.values(): + for x in env[CFG_FILES]: + node = self.srcnode.find_resource(x) + if node: + precious.add(node.id) + + def clean_rec(node): + for x in list(node.childs.keys()): + nd = node.childs[x] + + tp = nd.id & 3 + if tp == Node.DIR: + clean_rec(nd) + elif tp == Node.BUILD: + if nd.id in precious: continue + for env in self.all_envs.values(): + try: os.remove(nd.abspath(env)) + except OSError: pass + node.childs.__delitem__(x) + + clean_rec(self.srcnode) + + for v in 'node_sigs node_deps task_sigs raw_deps cache_node_abspath'.split(): + setattr(self, v, {}) + + def compile(self): + """The cache file is not written if nothing was build at all (build is up to date)""" + debug('build: compile called') + + """ + import cProfile, pstats + cProfile.run("import Build\nBuild.bld.flush()", 'profi.txt') + p = pstats.Stats('profi.txt') + p.sort_stats('cumulative').print_stats(80) + """ + self.flush() + #""" + + self.generator = Runner.Parallel(self, Options.options.jobs) + + def dw(on=True): + if Options.options.progress_bar: + if on: sys.stderr.write(Logs.colors.cursor_on) + else: sys.stderr.write(Logs.colors.cursor_off) + + debug('build: executor starting') + + back = os.getcwd() + os.chdir(self.bldnode.abspath()) + + try: + try: + dw(on=False) + self.generator.start() + except KeyboardInterrupt: + dw() + if Runner.TaskConsumer.consumers: + self.save() + raise + except Exception: + dw() + # do not store anything, for something bad happened + raise + else: + dw() + if Runner.TaskConsumer.consumers: + self.save() + + if self.generator.error: + raise BuildError(self, self.task_manager.tasks_done) + + finally: + os.chdir(back) + + def install(self): + "this function is called for both install and uninstall" + debug('build: install called') + + self.flush() + + # remove empty folders after uninstalling + if self.is_install < 0: + lst = [] + for x in self.uninstall: + dir = os.path.dirname(x) + if not dir in lst: lst.append(dir) + lst.sort() + lst.reverse() + + nlst = [] + for y in lst: + x = y + while len(x) > 4: + if not x in nlst: nlst.append(x) + x = os.path.dirname(x) + + nlst.sort() + nlst.reverse() + for x in nlst: + try: os.rmdir(x) + except OSError: pass + + def new_task_gen(self, *k, **kw): + if self.task_gen_cache_names: + self.task_gen_cache_names = {} + + kw['bld'] = self + if len(k) == 0: + ret = TaskGen.task_gen(*k, **kw) + else: + cls_name = k[0] + + try: cls = TaskGen.task_gen.classes[cls_name] + except KeyError: raise Utils.WscriptError('%s is not a valid task generator -> %s' % + (cls_name, [x for x in TaskGen.task_gen.classes])) + ret = cls(*k, **kw) + return ret + + def __call__(self, *k, **kw): + if self.task_gen_cache_names: + self.task_gen_cache_names = {} + + kw['bld'] = self + return TaskGen.task_gen(*k, **kw) + + def load_envs(self): + try: + lst = Utils.listdir(self.cachedir) + except OSError, e: + if e.errno == errno.ENOENT: + raise Utils.WafError('The project was not configured: run "waf configure" first!') + else: + raise + + if not lst: + raise Utils.WafError('The cache directory is empty: reconfigure the project') + + for file in lst: + if file.endswith(CACHE_SUFFIX): + env = Environment.Environment(os.path.join(self.cachedir, file)) + name = file[:-len(CACHE_SUFFIX)] + + self.all_envs[name] = env + + self.init_variants() + + for env in self.all_envs.values(): + for f in env[CFG_FILES]: + newnode = self.path.find_or_declare(f) + try: + hash = Utils.h_file(newnode.abspath(env)) + except (IOError, AttributeError): + error("cannot find "+f) + hash = SIG_NIL + self.node_sigs[env.variant()][newnode.id] = hash + + # TODO: hmmm, these nodes are removed from the tree when calling rescan() + self.bldnode = self.root.find_dir(self.bldnode.abspath()) + self.path = self.srcnode = self.root.find_dir(self.srcnode.abspath()) + self.cwd = self.bldnode.abspath() + + def setup(self, tool, tooldir=None, funs=None): + "setup tools for build process" + if isinstance(tool, list): + for i in tool: self.setup(i, tooldir) + return + + if not tooldir: tooldir = Options.tooldir + + module = Utils.load_tool(tool, tooldir) + if hasattr(module, "setup"): module.setup(self) + + def init_variants(self): + debug('build: init variants') + + lstvariants = [] + for env in self.all_envs.values(): + if not env.variant() in lstvariants: + lstvariants.append(env.variant()) + self.lst_variants = lstvariants + + debug('build: list of variants is %r', lstvariants) + + for name in lstvariants+[0]: + for v in 'node_sigs cache_node_abspath'.split(): + var = getattr(self, v) + if not name in var: + var[name] = {} + + # ======================================= # + # node and folder handling + + # this should be the main entry point + def load_dirs(self, srcdir, blddir, load_cache=1): + "this functions should be the start of everything" + + assert(os.path.isabs(srcdir)) + assert(os.path.isabs(blddir)) + + self.cachedir = os.path.join(blddir, CACHE_DIR) + + if srcdir == blddir: + raise Utils.WafError("build dir must be different from srcdir: %s <-> %s " % (srcdir, blddir)) + + self.bdir = blddir + + # try to load the cache file, if it does not exist, nothing happens + self.load() + + if not self.root: + Node.Nodu = self.node_class + self.root = Node.Nodu('', None, Node.DIR) + + if not self.srcnode: + self.srcnode = self.root.ensure_dir_node_from_path(srcdir) + debug('build: srcnode is %s and srcdir %s', self.srcnode.name, srcdir) + + self.path = self.srcnode + + # create this build dir if necessary + try: os.makedirs(blddir) + except OSError: pass + + if not self.bldnode: + self.bldnode = self.root.ensure_dir_node_from_path(blddir) + + self.init_variants() + + def rescan(self, src_dir_node): + """ + look the contents of a (folder)node and update its list of childs + + The intent is to perform the following steps + * remove the nodes for the files that have disappeared + * remove the signatures for the build files that have disappeared + * cache the results of os.listdir + * create the build folder equivalent (mkdir) for each variant + src/bar -> build/Release/src/bar, build/Debug/src/bar + + when a folder in the source directory is removed, we do not check recursively + to remove the unused nodes. To do that, call 'waf clean' and build again. + """ + + # do not rescan over and over again + # TODO use a single variable in waf 1.6 + if self.cache_scanned_folders.get(src_dir_node.id, None): return + self.cache_scanned_folders[src_dir_node.id] = True + + # TODO remove in waf 1.6 + if hasattr(self, 'repository'): self.repository(src_dir_node) + + if not src_dir_node.name and sys.platform == 'win32': + # the root has no name, contains drive letters, and cannot be listed + return + + + # first, take the case of the source directory + parent_path = src_dir_node.abspath() + try: + lst = set(Utils.listdir(parent_path)) + except OSError: + lst = set([]) + + # TODO move this at the bottom + self.cache_dir_contents[src_dir_node.id] = lst + + # hash the existing source files, remove the others + cache = self.node_sigs[0] + for x in src_dir_node.childs.values(): + if x.id & 3 != Node.FILE: continue + if x.name in lst: + try: + cache[x.id] = Utils.h_file(x.abspath()) + except IOError: + raise Utils.WafError('The file %s is not readable or has become a dir' % x.abspath()) + else: + try: del cache[x.id] + except KeyError: pass + + del src_dir_node.childs[x.name] + + + # first obtain the differences between srcnode and src_dir_node + h1 = self.srcnode.height() + h2 = src_dir_node.height() + + lst = [] + child = src_dir_node + while h2 > h1: + lst.append(child.name) + child = child.parent + h2 -= 1 + lst.reverse() + + # list the files in the build dirs + try: + for variant in self.lst_variants: + sub_path = os.path.join(self.bldnode.abspath(), variant , *lst) + self.listdir_bld(src_dir_node, sub_path, variant) + except OSError: + + # listdir failed, remove the build node signatures for all variants + for node in src_dir_node.childs.values(): + if node.id & 3 != Node.BUILD: + continue + + for dct in self.node_sigs.values(): + if node.id in dct: + dct.__delitem__(node.id) + + # the policy is to avoid removing nodes representing directories + src_dir_node.childs.__delitem__(node.name) + + for variant in self.lst_variants: + sub_path = os.path.join(self.bldnode.abspath(), variant , *lst) + try: + os.makedirs(sub_path) + except OSError: + pass + + # ======================================= # + def listdir_src(self, parent_node): + """do not use, kept for compatibility""" + pass + + def remove_node(self, node): + """do not use, kept for compatibility""" + pass + + def listdir_bld(self, parent_node, path, variant): + """in this method we do not add timestamps but we remove them + when the files no longer exist (file removed in the build dir)""" + + i_existing_nodes = [x for x in parent_node.childs.values() if x.id & 3 == Node.BUILD] + + lst = set(Utils.listdir(path)) + node_names = set([x.name for x in i_existing_nodes]) + remove_names = node_names - lst + + # remove the stamps of the build nodes that no longer exist on the filesystem + ids_to_remove = [x.id for x in i_existing_nodes if x.name in remove_names] + cache = self.node_sigs[variant] + for nid in ids_to_remove: + if nid in cache: + cache.__delitem__(nid) + + def get_env(self): + return self.env_of_name('Release') + def set_env(self, name, val): + self.all_envs[name] = val + + env = property(get_env, set_env) + + def add_manual_dependency(self, path, value): + if isinstance(path, Node.Node): + node = path + elif os.path.isabs(path): + node = self.root.find_resource(path) + else: + node = self.path.find_resource(path) + self.deps_man[node.id].append(value) + + def launch_node(self): + """return the launch directory as a node""" + # p_ln is kind of private, but public in case if + try: + return self.p_ln + except AttributeError: + self.p_ln = self.root.find_dir(Options.launch_dir) + return self.p_ln + + def glob(self, pattern, relative=True): + "files matching the pattern, seen from the current folder" + path = self.path.abspath() + files = [self.root.find_resource(x) for x in glob.glob(path+os.sep+pattern)] + if relative: + files = [x.path_to_parent(self.path) for x in files if x] + else: + files = [x.abspath() for x in files if x] + return files + + ## the following methods are candidates for the stable apis ## + + def add_group(self, *k): + self.task_manager.add_group(*k) + + def set_group(self, *k, **kw): + self.task_manager.set_group(*k, **kw) + + def hash_env_vars(self, env, vars_lst): + """hash environment variables + ['CXX', ..] -> [env['CXX'], ..] -> md5()""" + + # ccroot objects use the same environment for building the .o at once + # the same environment and the same variables are used + + idx = str(id(env)) + str(vars_lst) + try: return self.cache_sig_vars[idx] + except KeyError: pass + + lst = [str(env[a]) for a in vars_lst] + ret = Utils.h_list(lst) + debug('envhash: %r %r', ret, lst) + + # next time + self.cache_sig_vars[idx] = ret + return ret + + def name_to_obj(self, name, env): + """retrieve a task generator from its name or its target name + remember that names must be unique""" + cache = self.task_gen_cache_names + if not cache: + # create the index lazily + for x in self.all_task_gen: + vt = x.env.variant() + '_' + if x.name: + cache[vt + x.name] = x + else: + if isinstance(x.target, str): + target = x.target + else: + target = ' '.join(x.target) + v = vt + target + if not cache.get(v, None): + cache[v] = x + return cache.get(env.variant() + '_' + name, None) + + def flush(self, all=1): + """tell the task generators to create the tasks""" + + self.ini = datetime.datetime.now() + # force the initialization of the mapping name->object in flush + # name_to_obj can be used in userland scripts, in that case beware of incomplete mapping + self.task_gen_cache_names = {} + self.name_to_obj('', self.env) + + debug('build: delayed operation TaskGen.flush() called') + + if Options.options.compile_targets: + debug('task_gen: posting objects listed in compile_targets') + + # ensure the target names exist, fail before any post() + target_objects = Utils.DefaultDict(list) + for target_name in Options.options.compile_targets.split(','): + # trim target_name (handle cases when the user added spaces to targets) + target_name = target_name.strip() + for env in self.all_envs.values(): + obj = self.name_to_obj(target_name, env) + if obj: + target_objects[target_name].append(obj) + if not target_name in target_objects and all: + raise Utils.WafError("target '%s' does not exist" % target_name) + + to_compile = [] + for x in target_objects.values(): + for y in x: + to_compile.append(id(y)) + + # tasks must be posted in order of declaration + # we merely apply a filter to discard the ones we are not interested in + for i in xrange(len(self.task_manager.groups)): + g = self.task_manager.groups[i] + self.task_manager.current_group = i + if Logs.verbose: + Logs.debug('group: group %s' % ([x for x in self.task_manager.groups_names if id(self.task_manager.groups_names[x]) == id(g)][0])) + + for tg in g.tasks_gen: + if id(tg) in to_compile: + if Logs.verbose: + Logs.debug('group: %s' % tg) + tg.post() + + else: + debug('task_gen: posting objects (normal)') + ln = self.launch_node() + # if the build is started from the build directory, do as if it was started from the top-level + # for the pretty-printing (Node.py), the two lines below cannot be moved to Build::launch_node + if ln.is_child_of(self.bldnode) or not ln.is_child_of(self.srcnode): + ln = self.srcnode + + # if the project file is located under the source directory, build all targets by default + # else 'waf configure build' does nothing + proj_node = self.root.find_dir(os.path.split(Utils.g_module.root_path)[0]) + if proj_node.id != self.srcnode.id: + ln = self.srcnode + + for i in xrange(len(self.task_manager.groups)): + g = self.task_manager.groups[i] + self.task_manager.current_group = i + if Logs.verbose: + Logs.debug('group: group %s' % ([x for x in self.task_manager.groups_names if id(self.task_manager.groups_names[x]) == id(g)][0])) + for tg in g.tasks_gen: + if not tg.path.is_child_of(ln): + continue + if Logs.verbose: + Logs.debug('group: %s' % tg) + tg.post() + + def env_of_name(self, name): + try: + return self.all_envs[name] + except KeyError: + error('no such environment: '+name) + return None + + def progress_line(self, state, total, col1, col2): + n = len(str(total)) + + Utils.rot_idx += 1 + ind = Utils.rot_chr[Utils.rot_idx % 4] + + ini = self.ini + + pc = (100.*state)/total + eta = Utils.get_elapsed_time(ini) + fs = "[%%%dd/%%%dd][%%s%%2d%%%%%%s][%s][" % (n, n, ind) + left = fs % (state, total, col1, pc, col2) + right = '][%s%s%s]' % (col1, eta, col2) + + cols = Utils.get_term_cols() - len(left) - len(right) + 2*len(col1) + 2*len(col2) + if cols < 7: cols = 7 + + ratio = int((cols*state)/total) - 1 + + bar = ('='*ratio+'>').ljust(cols) + msg = Utils.indicator % (left, bar, right) + + return msg + + + # do_install is not used anywhere + def do_install(self, src, tgt, chmod=O644): + """returns true if the file was effectively installed or uninstalled, false otherwise""" + if self.is_install > 0: + if not Options.options.force: + # check if the file is already there to avoid a copy + try: + st1 = os.stat(tgt) + st2 = os.stat(src) + except OSError: + pass + else: + # same size and identical timestamps -> make no copy + if st1.st_mtime >= st2.st_mtime and st1.st_size == st2.st_size: + return False + + srclbl = src.replace(self.srcnode.abspath(None)+os.sep, '') + info("* installing %s as %s" % (srclbl, tgt)) + + # following is for shared libs and stale inodes (-_-) + try: os.remove(tgt) + except OSError: pass + + try: + shutil.copy2(src, tgt) + if chmod >= 0: os.chmod(tgt, chmod) + except IOError: + try: + os.stat(src) + except (OSError, IOError): + error('File %r does not exist' % src) + raise Utils.WafError('Could not install the file %r' % tgt) + return True + + elif self.is_install < 0: + info("* uninstalling %s" % tgt) + + self.uninstall.append(tgt) + + try: + os.remove(tgt) + except OSError, e: + if e.errno != errno.ENOENT: + if not getattr(self, 'uninstall_error', None): + self.uninstall_error = True + Logs.warn('build: some files could not be uninstalled (retry with -vv to list them)') + if Logs.verbose > 1: + Logs.warn('could not remove %s (error code %r)' % (e.filename, e.errno)) + return True + + red = re.compile(r"^([A-Za-z]:)?[/\\\\]*") + def get_install_path(self, path, env=None): + "installation path prefixed by the destdir, the variables like in '${PREFIX}/bin' are substituted" + if not env: env = self.env + destdir = env.get_destdir() + path = path.replace('/', os.sep) + destpath = Utils.subst_vars(path, env) + if destdir: + destpath = os.path.join(destdir, self.red.sub('', destpath)) + return destpath + + def install_dir(self, path, env=None): + """ + create empty folders for the installation (very rarely used) + """ + if env: + assert isinstance(env, Environment.Environment), "invalid parameter" + else: + env = self.env + + if not path: + return [] + + destpath = self.get_install_path(path, env) + + if self.is_install > 0: + info('* creating %s' % destpath) + Utils.check_dir(destpath) + elif self.is_install < 0: + info('* removing %s' % destpath) + self.uninstall.append(destpath + '/xxx') # yes, ugly + + def install_files(self, path, files, env=None, chmod=O644, relative_trick=False, cwd=None): + """To install files only after they have been built, put the calls in a method named + post_build on the top-level wscript + + The files must be a list and contain paths as strings or as Nodes + + The relative_trick flag can be set to install folders, use bld.path.ant_glob() with it + """ + if env: + assert isinstance(env, Environment.Environment), "invalid parameter" + else: + env = self.env + + if not path: return [] + + if not cwd: + cwd = self.path + + if isinstance(files, str) and '*' in files: + gl = cwd.abspath() + os.sep + files + lst = glob.glob(gl) + else: + lst = Utils.to_list(files) + + if not getattr(lst, '__iter__', False): + lst = [lst] + + destpath = self.get_install_path(path, env) + + Utils.check_dir(destpath) + + installed_files = [] + for filename in lst: + if isinstance(filename, str) and os.path.isabs(filename): + alst = Utils.split_path(filename) + destfile = os.path.join(destpath, alst[-1]) + else: + if isinstance(filename, Node.Node): + nd = filename + else: + nd = cwd.find_resource(filename) + if not nd: + raise Utils.WafError("Unable to install the file %r (not found in %s)" % (filename, cwd)) + + if relative_trick: + destfile = os.path.join(destpath, filename) + Utils.check_dir(os.path.dirname(destfile)) + else: + destfile = os.path.join(destpath, nd.name) + + filename = nd.abspath(env) + + if self.do_install(filename, destfile, chmod): + installed_files.append(destfile) + return installed_files + + def install_as(self, path, srcfile, env=None, chmod=O644, cwd=None): + """ + srcfile may be a string or a Node representing the file to install + + returns True if the file was effectively installed, False otherwise + """ + if env: + assert isinstance(env, Environment.Environment), "invalid parameter" + else: + env = self.env + + if not path: + raise Utils.WafError("where do you want to install %r? (%r?)" % (srcfile, path)) + + if not cwd: + cwd = self.path + + destpath = self.get_install_path(path, env) + + dir, name = os.path.split(destpath) + Utils.check_dir(dir) + + # the source path + if isinstance(srcfile, Node.Node): + src = srcfile.abspath(env) + else: + src = srcfile + if not os.path.isabs(srcfile): + node = cwd.find_resource(srcfile) + if not node: + raise Utils.WafError("Unable to install the file %r (not found in %s)" % (srcfile, cwd)) + src = node.abspath(env) + + return self.do_install(src, destpath, chmod) + + def symlink_as(self, path, src, env=None, cwd=None): + """example: bld.symlink_as('${PREFIX}/lib/libfoo.so', 'libfoo.so.1.2.3') """ + + if sys.platform == 'win32': + # well, this *cannot* work + return + + if not path: + raise Utils.WafError("where do you want to install %r? (%r?)" % (src, path)) + + tgt = self.get_install_path(path, env) + + dir, name = os.path.split(tgt) + Utils.check_dir(dir) + + if self.is_install > 0: + link = False + if not os.path.islink(tgt): + link = True + elif os.readlink(tgt) != src: + link = True + + if link: + try: os.remove(tgt) + except OSError: pass + + info('* symlink %s (-> %s)' % (tgt, src)) + os.symlink(src, tgt) + return 0 + + else: # UNINSTALL + try: + info('* removing %s' % (tgt)) + os.remove(tgt) + return 0 + except OSError: + return 1 + + def exec_command(self, cmd, **kw): + # 'runner' zone is printed out for waf -v, see wafadmin/Options.py + debug('runner: system command -> %s', cmd) + if self.log: + self.log.write('%s\n' % cmd) + kw['log'] = self.log + try: + if not kw.get('cwd', None): + kw['cwd'] = self.cwd + except AttributeError: + self.cwd = kw['cwd'] = self.bldnode.abspath() + return Utils.exec_command(cmd, **kw) + + def printout(self, s): + f = self.log or sys.stderr + f.write(s) + f.flush() + + def add_subdirs(self, dirs): + self.recurse(dirs, 'build') + + def pre_recurse(self, name_or_mod, path, nexdir): + if not hasattr(self, 'oldpath'): + self.oldpath = [] + self.oldpath.append(self.path) + self.path = self.root.find_dir(nexdir) + return {'bld': self, 'ctx': self} + + def post_recurse(self, name_or_mod, path, nexdir): + self.path = self.oldpath.pop() + + ###### user-defined behaviour + + def pre_build(self): + if hasattr(self, 'pre_funs'): + for m in self.pre_funs: + m(self) + + def post_build(self): + if hasattr(self, 'post_funs'): + for m in self.post_funs: + m(self) + + def add_pre_fun(self, meth): + try: self.pre_funs.append(meth) + except AttributeError: self.pre_funs = [meth] + + def add_post_fun(self, meth): + try: self.post_funs.append(meth) + except AttributeError: self.post_funs = [meth] + + def use_the_magic(self): + Task.algotype = Task.MAXPARALLEL + Task.file_deps = Task.extract_deps + self.magic = True + + install_as = group_method(install_as) + install_files = group_method(install_files) + symlink_as = group_method(symlink_as) + diff --git a/node-v0.8.14/tools/wafadmin/Configure.py b/node-v0.8.14/tools/wafadmin/Configure.py new file mode 100644 index 0000000..846e185 --- /dev/null +++ b/node-v0.8.14/tools/wafadmin/Configure.py @@ -0,0 +1,387 @@ +#!/usr/bin/env python +# encoding: utf-8 +# Thomas Nagy, 2005-2008 (ita) + +""" +Configuration system + +A configuration instance is created when "waf configure" is called, it is used to: +* create data dictionaries (Environment instances) +* store the list of modules to import + +The old model (copied from Scons) was to store logic (mapping file extensions to functions) +along with the data. In Waf a way was found to separate that logic by adding an indirection +layer (storing the names in the Environment instances) + +In the new model, the logic is more object-oriented, and the user scripts provide the +logic. The data files (Environments) must contain configuration data only (flags, ..). + +Note: the c/c++ related code is in the module config_c +""" + +import os, shlex, sys, time +try: import cPickle +except ImportError: import pickle as cPickle +import Environment, Utils, Options, Logs +from Logs import warn +from Constants import * + +try: + from urllib import request +except: + from urllib import urlopen +else: + urlopen = request.urlopen + +conf_template = '''# project %(app)s configured on %(now)s by +# waf %(wafver)s (abi %(abi)s, python %(pyver)x on %(systype)s) +# using %(args)s +# +''' + +class ConfigurationError(Utils.WscriptError): + pass + +autoconfig = False +"reconfigure the project automatically" + +def find_file(filename, path_list): + """find a file in a list of paths + @param filename: name of the file to search for + @param path_list: list of directories to search + @return: the first occurrence filename or '' if filename could not be found +""" + for directory in Utils.to_list(path_list): + if os.path.exists(os.path.join(directory, filename)): + return directory + return '' + +def find_program_impl(env, filename, path_list=[], var=None, environ=None): + """find a program in folders path_lst, and sets env[var] + @param env: environment + @param filename: name of the program to search for + @param path_list: list of directories to search for filename + @param var: environment value to be checked for in env or os.environ + @return: either the value that is referenced with [var] in env or os.environ + or the first occurrence filename or '' if filename could not be found +""" + + if not environ: + environ = os.environ + + try: path_list = path_list.split() + except AttributeError: pass + + if var: + if env[var]: return env[var] + if var in environ: env[var] = environ[var] + + if not path_list: path_list = environ.get('PATH', '').split(os.pathsep) + + ext = (Options.platform == 'win32') and '.exe,.com,.bat,.cmd' or '' + for y in [filename+x for x in ext.split(',')]: + for directory in path_list: + x = os.path.join(directory, y) + if os.path.isfile(x): + if var: env[var] = x + return x + return '' + +class ConfigurationContext(Utils.Context): + tests = {} + error_handlers = [] + def __init__(self, env=None, blddir='', srcdir=''): + self.env = None + self.envname = '' + + self.environ = dict(os.environ) + + self.line_just = 40 + + self.blddir = blddir + self.srcdir = srcdir + self.all_envs = {} + + # curdir: necessary for recursion + self.cwd = self.curdir = os.getcwd() + + self.tools = [] # tools loaded in the configuration, and that will be loaded when building + + self.setenv(DEFAULT) + + self.lastprog = '' + + self.hash = 0 + self.files = [] + + self.tool_cache = [] + + if self.blddir: + self.post_init() + + def post_init(self): + + self.cachedir = os.path.join(self.blddir, CACHE_DIR) + + path = os.path.join(self.blddir, WAF_CONFIG_LOG) + try: os.unlink(path) + except (OSError, IOError): pass + + try: + self.log = open(path, 'w') + except (OSError, IOError): + self.fatal('could not open %r for writing' % path) + + app = Utils.g_module.APPNAME + if app: + ver = getattr(Utils.g_module, 'VERSION', '') + if ver: + app = "%s (%s)" % (app, ver) + + now = time.ctime() + pyver = sys.hexversion + systype = sys.platform + args = " ".join(sys.argv) + wafver = WAFVERSION + abi = ABI + self.log.write(conf_template % vars()) + + def __del__(self): + """cleanup function: close config.log""" + + # may be ran by the gc, not always after initialization + if hasattr(self, 'log') and self.log: + self.log.close() + + def fatal(self, msg): + raise ConfigurationError(msg) + + def check_tool(self, input, tooldir=None, funs=None): + "load a waf tool" + + tools = Utils.to_list(input) + if tooldir: tooldir = Utils.to_list(tooldir) + for tool in tools: + tool = tool.replace('++', 'xx') + if tool == 'java': tool = 'javaw' + if tool.lower() == 'unittest': tool = 'unittestw' + # avoid loading the same tool more than once with the same functions + # used by composite projects + + mag = (tool, id(self.env), funs) + if mag in self.tool_cache: + continue + self.tool_cache.append(mag) + + if not tooldir: + # check if the tool exists in the Tools or 3rdparty folders + _Tools = Options.tooldir[0] + _3rdparty = os.sep.join((_Tools, '..', '3rdparty')) + for d in (_Tools, _3rdparty): + lst = os.listdir(d) + if tool + '.py' in lst: + break + else: + # try to download the tool from the repository then + for x in Utils.to_list(Options.remote_repo): + for sub in ['branches/waf-%s/wafadmin/3rdparty' % WAFVERSION, 'trunk/wafadmin/3rdparty']: + url = '/'.join((x, sub, tool + '.py')) + try: + web = urlopen(url) + if web.getcode() != 200: + continue + except Exception, e: + # on python3 urlopen throws an exception + continue + else: + try: + loc = open(_3rdparty + os.sep + tool + '.py', 'wb') + loc.write(web.read()) + web.close() + finally: + loc.close() + Logs.warn('downloaded %s from %s' % (tool, url)) + else: + break + + module = Utils.load_tool(tool, tooldir) + + if funs is not None: + self.eval_rules(funs) + else: + func = getattr(module, 'detect', None) + if func: + if type(func) is type(find_file): func(self) + else: self.eval_rules(func) + + self.tools.append({'tool':tool, 'tooldir':tooldir, 'funs':funs}) + + def sub_config(self, k): + "executes the configure function of a wscript module" + self.recurse(k, name='configure') + + def pre_recurse(self, name_or_mod, path, nexdir): + return {'conf': self, 'ctx': self} + + def post_recurse(self, name_or_mod, path, nexdir): + if not autoconfig: + return + self.hash = hash((self.hash, getattr(name_or_mod, 'waf_hash_val', name_or_mod))) + self.files.append(path) + + def store(self, file=''): + "save the config results into the cache file" + if not os.path.isdir(self.cachedir): + os.makedirs(self.cachedir) + + if not file: + file = open(os.path.join(self.cachedir, 'build.config.py'), 'w') + file.write('version = 0x%x\n' % HEXVERSION) + file.write('tools = %r\n' % self.tools) + file.close() + + if not self.all_envs: + self.fatal('nothing to store in the configuration context!') + for key in self.all_envs: + tmpenv = self.all_envs[key] + tmpenv.store(os.path.join(self.cachedir, key + CACHE_SUFFIX)) + + def set_env_name(self, name, env): + "add a new environment called name" + self.all_envs[name] = env + return env + + def retrieve(self, name, fromenv=None): + "retrieve an environment called name" + try: + env = self.all_envs[name] + except KeyError: + env = Environment.Environment() + env['PREFIX'] = os.path.abspath(os.path.expanduser(Options.options.prefix)) + self.all_envs[name] = env + else: + if fromenv: warn("The environment %s may have been configured already" % name) + return env + + def setenv(self, name): + "enable the environment called name" + self.env = self.retrieve(name) + self.envname = name + + def add_os_flags(self, var, dest=None): + # do not use 'get' to make certain the variable is not defined + try: self.env.append_value(dest or var, Utils.to_list(self.environ[var])) + except KeyError: pass + + def check_message_1(self, sr): + self.line_just = max(self.line_just, len(sr)) + for x in ('\n', self.line_just * '-', '\n', sr, '\n'): + self.log.write(x) + Utils.pprint('NORMAL', "%s :" % sr.ljust(self.line_just), sep='') + + def check_message_2(self, sr, color='GREEN'): + self.log.write(sr) + self.log.write('\n') + Utils.pprint(color, sr) + + def check_message(self, th, msg, state, option=''): + sr = 'Checking for %s %s' % (th, msg) + self.check_message_1(sr) + p = self.check_message_2 + if state: p('ok ' + str(option)) + else: p('not found', 'YELLOW') + + # FIXME remove in waf 1.6 + # the parameter 'option' is not used (kept for compatibility) + def check_message_custom(self, th, msg, custom, option='', color='PINK'): + sr = 'Checking for %s %s' % (th, msg) + self.check_message_1(sr) + self.check_message_2(custom, color) + + def find_program(self, filename, path_list=[], var=None, mandatory=False): + "wrapper that adds a configuration message" + + ret = None + if var: + if self.env[var]: + ret = self.env[var] + elif var in os.environ: + ret = os.environ[var] + + if not isinstance(filename, list): filename = [filename] + if not ret: + for x in filename: + ret = find_program_impl(self.env, x, path_list, var, environ=self.environ) + if ret: break + + self.check_message_1('Checking for program %s' % ' or '.join(filename)) + self.log.write(' find program=%r paths=%r var=%r\n -> %r\n' % (filename, path_list, var, ret)) + if ret: + Utils.pprint('GREEN', str(ret)) + else: + Utils.pprint('YELLOW', 'not found') + if mandatory: + self.fatal('The program %r is required' % filename) + + if var: + self.env[var] = ret + return ret + + def cmd_to_list(self, cmd): + "commands may be written in pseudo shell like 'ccache g++'" + if isinstance(cmd, str) and cmd.find(' '): + try: + os.stat(cmd) + except OSError: + return shlex.split(cmd) + else: + return [cmd] + return cmd + + def __getattr__(self, name): + r = self.__class__.__dict__.get(name, None) + if r: return r + if name and name.startswith('require_'): + + for k in ['check_', 'find_']: + n = name.replace('require_', k) + ret = self.__class__.__dict__.get(n, None) + if ret: + def run(*k, **kw): + r = ret(self, *k, **kw) + if not r: + self.fatal('requirement failure') + return r + return run + self.fatal('No such method %r' % name) + + def eval_rules(self, rules): + self.rules = Utils.to_list(rules) + for x in self.rules: + f = getattr(self, x) + if not f: self.fatal("No such method '%s'." % x) + try: + f() + except Exception, e: + ret = self.err_handler(x, e) + if ret == BREAK: + break + elif ret == CONTINUE: + continue + else: + self.fatal(e) + + def err_handler(self, fun, error): + pass + +def conf(f): + "decorator: attach new configuration functions" + setattr(ConfigurationContext, f.__name__, f) + return f + +def conftest(f): + "decorator: attach new configuration tests (registered as strings)" + ConfigurationContext.tests[f.__name__] = f + return conf(f) + + diff --git a/node-v0.8.14/tools/wafadmin/Constants.py b/node-v0.8.14/tools/wafadmin/Constants.py new file mode 100644 index 0000000..2b531c2 --- /dev/null +++ b/node-v0.8.14/tools/wafadmin/Constants.py @@ -0,0 +1,76 @@ +#!/usr/bin/env python +# encoding: utf-8 +# Yinon dot me gmail 2008 + +""" +these constants are somewhat public, try not to mess them + +maintainer: the version number is updated from the top-level wscript file +""" + +# do not touch these three lines, they are updated automatically +HEXVERSION=0x105016 +WAFVERSION="1.5.16" +WAFREVISION = "7610:7647M" +ABI = 7 + +# permissions +O644 = 420 +O755 = 493 + +MAXJOBS = 99999999 + +CACHE_DIR = 'c4che' +CACHE_SUFFIX = '.cache.py' +DBFILE = '.wafpickle-%d' % ABI +WSCRIPT_FILE = 'wscript' +WSCRIPT_BUILD_FILE = 'wscript_build' +WAF_CONFIG_LOG = 'config.log' +WAF_CONFIG_H = 'config.h' + +SIG_NIL = 'iluvcuteoverload' + +VARIANT = '_VARIANT_' +DEFAULT = 'Release' + +SRCDIR = 'srcdir' +BLDDIR = 'blddir' +APPNAME = 'APPNAME' +VERSION = 'VERSION' + +DEFINES = 'defines' +UNDEFINED = () + +BREAK = "break" +CONTINUE = "continue" + +# task scheduler options +JOBCONTROL = "JOBCONTROL" +MAXPARALLEL = "MAXPARALLEL" +NORMAL = "NORMAL" + +# task state +NOT_RUN = 0 +MISSING = 1 +CRASHED = 2 +EXCEPTION = 3 +SKIPPED = 8 +SUCCESS = 9 + +ASK_LATER = -1 +SKIP_ME = -2 +RUN_ME = -3 + + +LOG_FORMAT = "%(asctime)s %(c1)s%(zone)s%(c2)s %(message)s" +HOUR_FORMAT = "%H:%M:%S" + +TEST_OK = True + +CFG_FILES = 'cfg_files' + +# positive '->' install +# negative '<-' uninstall +INSTALL = 1337 +UNINSTALL = -1337 + diff --git a/node-v0.8.14/tools/wafadmin/Environment.py b/node-v0.8.14/tools/wafadmin/Environment.py new file mode 100644 index 0000000..0b6e72c --- /dev/null +++ b/node-v0.8.14/tools/wafadmin/Environment.py @@ -0,0 +1,210 @@ +#!/usr/bin/env python +# encoding: utf-8 +# Thomas Nagy, 2005 (ita) + +"""Environment representation + +There is one gotcha: getitem returns [] if the contents evals to False +This means env['foo'] = {}; print env['foo'] will print [] not {} +""" + +import os, copy, re +import Logs, Options, Utils +from Constants import * +re_imp = re.compile('^(#)*?([^#=]*?)\ =\ (.*?)$', re.M) + +class Environment(object): + """A safe-to-use dictionary, but do not attach functions to it please (break cPickle) + An environment instance can be stored into a file and loaded easily + """ + __slots__ = ("table", "parent") + def __init__(self, filename=None): + self.table = {} + #self.parent = None + + if filename: + self.load(filename) + + def __contains__(self, key): + if key in self.table: return True + try: return self.parent.__contains__(key) + except AttributeError: return False # parent may not exist + + def __str__(self): + keys = set() + cur = self + while cur: + keys.update(cur.table.keys()) + cur = getattr(cur, 'parent', None) + keys = list(keys) + keys.sort() + return "\n".join(["%r %r" % (x, self.__getitem__(x)) for x in keys]) + + def __getitem__(self, key): + try: + while 1: + x = self.table.get(key, None) + if not x is None: + return x + self = self.parent + except AttributeError: + return [] + + def __setitem__(self, key, value): + self.table[key] = value + + def __delitem__(self, key): + del self.table[key] + + def pop(self, key, *args): + if len(args): + return self.table.pop(key, *args) + return self.table.pop(key) + + def set_variant(self, name): + self.table[VARIANT] = name + + def variant(self): + try: + while 1: + x = self.table.get(VARIANT, None) + if not x is None: + return x + self = self.parent + except AttributeError: + return DEFAULT + + def copy(self): + # TODO waf 1.6 rename this method derive, #368 + newenv = Environment() + newenv.parent = self + return newenv + + def detach(self): + """TODO try it + modifying the original env will not change the copy""" + tbl = self.get_merged_dict() + try: + delattr(self, 'parent') + except AttributeError: + pass + else: + keys = tbl.keys() + for x in keys: + tbl[x] = copy.deepcopy(tbl[x]) + self.table = tbl + + def get_flat(self, key): + s = self[key] + if isinstance(s, str): return s + return ' '.join(s) + + def _get_list_value_for_modification(self, key): + """Gets a value that must be a list for further modification. The + list may be modified inplace and there is no need to + "self.table[var] = value" afterwards. + """ + try: + value = self.table[key] + except KeyError: + try: value = self.parent[key] + except AttributeError: value = [] + if isinstance(value, list): + value = value[:] + else: + value = [value] + else: + if not isinstance(value, list): + value = [value] + self.table[key] = value + return value + + def append_value(self, var, value): + current_value = self._get_list_value_for_modification(var) + + if isinstance(value, list): + current_value.extend(value) + else: + current_value.append(value) + + def prepend_value(self, var, value): + current_value = self._get_list_value_for_modification(var) + + if isinstance(value, list): + current_value = value + current_value + # a new list: update the dictionary entry + self.table[var] = current_value + else: + current_value.insert(0, value) + + # prepend unique would be ambiguous + def append_unique(self, var, value): + current_value = self._get_list_value_for_modification(var) + + if isinstance(value, list): + for value_item in value: + if value_item not in current_value: + current_value.append(value_item) + else: + if value not in current_value: + current_value.append(value) + + def get_merged_dict(self): + """compute a merged table""" + table_list = [] + env = self + while 1: + table_list.insert(0, env.table) + try: env = env.parent + except AttributeError: break + merged_table = {} + for table in table_list: + merged_table.update(table) + return merged_table + + def store(self, filename): + "Write the variables into a file" + file = open(filename, 'w') + merged_table = self.get_merged_dict() + keys = list(merged_table.keys()) + keys.sort() + for k in keys: file.write('%s = %r\n' % (k, merged_table[k])) + file.close() + + def load(self, filename): + "Retrieve the variables from a file" + tbl = self.table + code = Utils.readf(filename) + for m in re_imp.finditer(code): + g = m.group + tbl[g(2)] = eval(g(3)) + Logs.debug('env: %s', self.table) + + def get_destdir(self): + "return the destdir, useful for installing" + if self.__getitem__('NOINSTALL'): return '' + return Options.options.destdir + + def update(self, d): + for k, v in d.iteritems(): + self[k] = v + + + def __getattr__(self, name): + if name in self.__slots__: + return object.__getattr__(self, name) + else: + return self[name] + + def __setattr__(self, name, value): + if name in self.__slots__: + object.__setattr__(self, name, value) + else: + self[name] = value + + def __delattr__(self, name): + if name in self.__slots__: + object.__delattr__(self, name) + else: + del self[name] + diff --git a/node-v0.8.14/tools/wafadmin/Logs.py b/node-v0.8.14/tools/wafadmin/Logs.py new file mode 100644 index 0000000..c160b37 --- /dev/null +++ b/node-v0.8.14/tools/wafadmin/Logs.py @@ -0,0 +1,134 @@ +#!/usr/bin/env python +# encoding: utf-8 +# Thomas Nagy, 2005 (ita) + +import ansiterm +import os, re, logging, traceback, sys +from Constants import * + +zones = '' +verbose = 0 + +colors_lst = { +'USE' : True, +'BOLD' :'\x1b[01;1m', +'RED' :'\x1b[01;31m', +'GREEN' :'\x1b[32m', +'YELLOW':'\x1b[33m', +'PINK' :'\x1b[35m', +'BLUE' :'\x1b[01;34m', +'CYAN' :'\x1b[36m', +'NORMAL':'\x1b[0m', +'cursor_on' :'\x1b[?25h', +'cursor_off' :'\x1b[?25l', +} + +got_tty = False +term = os.environ.get('TERM', 'dumb') +if not term in ['dumb', 'emacs']: + try: + got_tty = sys.stderr.isatty() or (sys.platform == 'win32' and term in ['xterm', 'msys']) + except AttributeError: + pass + +import Utils + +if not got_tty or 'NOCOLOR' in os.environ: + colors_lst['USE'] = False + +# test +#if sys.platform == 'win32': +# colors_lst['USE'] = True + +def get_color(cl): + if not colors_lst['USE']: return '' + return colors_lst.get(cl, '') + +class foo(object): + def __getattr__(self, a): + return get_color(a) + def __call__(self, a): + return get_color(a) + +colors = foo() + +re_log = re.compile(r'(\w+): (.*)', re.M) +class log_filter(logging.Filter): + def __init__(self, name=None): + pass + + def filter(self, rec): + rec.c1 = colors.PINK + rec.c2 = colors.NORMAL + rec.zone = rec.module + if rec.levelno >= logging.INFO: + if rec.levelno >= logging.ERROR: + rec.c1 = colors.RED + elif rec.levelno >= logging.WARNING: + rec.c1 = colors.YELLOW + else: + rec.c1 = colors.GREEN + return True + + zone = '' + m = re_log.match(rec.msg) + if m: + zone = rec.zone = m.group(1) + rec.msg = m.group(2) + + if zones: + return getattr(rec, 'zone', '') in zones or '*' in zones + elif not verbose > 2: + return False + return True + +class formatter(logging.Formatter): + def __init__(self): + logging.Formatter.__init__(self, LOG_FORMAT, HOUR_FORMAT) + + def format(self, rec): + if rec.levelno >= logging.WARNING or rec.levelno == logging.INFO: + try: + return '%s%s%s' % (rec.c1, rec.msg.decode('utf-8'), rec.c2) + except: + return rec.c1+rec.msg+rec.c2 + return logging.Formatter.format(self, rec) + +def debug(*k, **kw): + if verbose: + k = list(k) + k[0] = k[0].replace('\n', ' ') + logging.debug(*k, **kw) + +def error(*k, **kw): + logging.error(*k, **kw) + if verbose > 1: + if isinstance(k[0], Utils.WafError): + st = k[0].stack + else: + st = traceback.extract_stack() + if st: + st = st[:-1] + buf = [] + for filename, lineno, name, line in st: + buf.append(' File "%s", line %d, in %s' % (filename, lineno, name)) + if line: + buf.append(' %s' % line.strip()) + if buf: logging.error("\n".join(buf)) + +warn = logging.warn +info = logging.info + +def init_log(): + log = logging.getLogger() + log.handlers = [] + log.filters = [] + hdlr = logging.StreamHandler() + hdlr.setFormatter(formatter()) + log.addHandler(hdlr) + log.addFilter(log_filter()) + log.setLevel(logging.DEBUG) + +# may be initialized more than once +init_log() + diff --git a/node-v0.8.14/tools/wafadmin/Node.py b/node-v0.8.14/tools/wafadmin/Node.py new file mode 100644 index 0000000..33d12f9 --- /dev/null +++ b/node-v0.8.14/tools/wafadmin/Node.py @@ -0,0 +1,693 @@ +#!/usr/bin/env python +# encoding: utf-8 +# Thomas Nagy, 2005 (ita) + +""" +Node: filesystem structure, contains lists of nodes + +IMPORTANT: +1. Each file/folder is represented by exactly one node. + +2. Most would-be class properties are stored in Build: nodes to depend on, signature, flags, .. +unused class members increase the .wafpickle file size sensibly with lots of objects. + +3. The build is launched from the top of the build dir (for example, in _build_/). + +4. Node should not be instantiated directly. +Each instance of Build.BuildContext has a Node subclass. +(aka: 'Nodu', see BuildContext initializer) +The BuildContext is referenced here as self.__class__.bld +Its Node class is referenced here as self.__class__ + +The public and advertised apis are the following: +${TGT} -> dir/to/file.ext +${TGT[0].base()} -> dir/to/file +${TGT[0].dir(env)} -> dir/to +${TGT[0].file()} -> file.ext +${TGT[0].file_base()} -> file +${TGT[0].suffix()} -> .ext +${TGT[0].abspath(env)} -> /path/to/dir/to/file.ext + +""" + +import os, sys, fnmatch, re, stat +import Utils, Constants + +UNDEFINED = 0 +DIR = 1 +FILE = 2 +BUILD = 3 + +type_to_string = {UNDEFINED: "unk", DIR: "dir", FILE: "src", BUILD: "bld"} + +# These fnmatch expressions are used by default to prune the directory tree +# while doing the recursive traversal in the find_iter method of the Node class. +prune_pats = '.git .bzr .hg .svn _MTN _darcs CVS SCCS'.split() + +# These fnmatch expressions are used by default to exclude files and dirs +# while doing the recursive traversal in the find_iter method of the Node class. +exclude_pats = prune_pats + '*~ #*# .#* %*% ._* .gitignore .cvsignore vssver.scc .DS_Store'.split() + +# These Utils.jar_regexp expressions are used by default to exclude files and dirs and also prune the directory tree +# while doing the recursive traversal in the ant_glob method of the Node class. +exclude_regs = ''' +**/*~ +**/#*# +**/.#* +**/%*% +**/._* +**/CVS +**/CVS/** +**/.cvsignore +**/SCCS +**/SCCS/** +**/vssver.scc +**/.svn +**/.svn/** +**/.git +**/.git/** +**/.gitignore +**/.bzr +**/.bzr/** +**/.hg +**/.hg/** +**/_MTN +**/_MTN/** +**/_darcs +**/_darcs/** +**/.DS_Store''' + +class Node(object): + __slots__ = ("name", "parent", "id", "childs") + def __init__(self, name, parent, node_type = UNDEFINED): + self.name = name + self.parent = parent + + # assumption: one build object at a time + self.__class__.bld.id_nodes += 4 + self.id = self.__class__.bld.id_nodes + node_type + + if node_type == DIR: self.childs = {} + + # We do not want to add another type attribute (memory) + # use the id to find out: type = id & 3 + # for setting: new type = type + x - type & 3 + + if parent and name in parent.childs: + raise Utils.WafError('node %s exists in the parent files %r already' % (name, parent)) + + if parent: parent.childs[name] = self + + def __setstate__(self, data): + if len(data) == 4: + (self.parent, self.name, self.id, self.childs) = data + else: + (self.parent, self.name, self.id) = data + + def __getstate__(self): + if getattr(self, 'childs', None) is None: + return (self.parent, self.name, self.id) + else: + return (self.parent, self.name, self.id, self.childs) + + def __str__(self): + if not self.parent: return '' + return "%s://%s" % (type_to_string[self.id & 3], self.abspath()) + + def __repr__(self): + return self.__str__() + + def __hash__(self): + "expensive, make certain it is not used" + raise Utils.WafError('nodes, you are doing it wrong') + + def __copy__(self): + "nodes are not supposed to be copied" + raise Utils.WafError('nodes are not supposed to be cloned') + + def get_type(self): + return self.id & 3 + + def set_type(self, t): + "dangerous, you are not supposed to use this" + self.id = self.id + t - self.id & 3 + + def dirs(self): + return [x for x in self.childs.values() if x.id & 3 == DIR] + + def files(self): + return [x for x in self.childs.values() if x.id & 3 == FILE] + + def get_dir(self, name, default=None): + node = self.childs.get(name, None) + if not node or node.id & 3 != DIR: return default + return node + + def get_file(self, name, default=None): + node = self.childs.get(name, None) + if not node or node.id & 3 != FILE: return default + return node + + def get_build(self, name, default=None): + node = self.childs.get(name, None) + if not node or node.id & 3 != BUILD: return default + return node + + def find_resource(self, lst): + "Find an existing input file: either a build node declared previously or a source node" + if isinstance(lst, str): + lst = Utils.split_path(lst) + + if len(lst) == 1: + parent = self + else: + parent = self.find_dir(lst[:-1]) + if not parent: return None + self.__class__.bld.rescan(parent) + + name = lst[-1] + node = parent.childs.get(name, None) + if node: + tp = node.id & 3 + if tp == FILE or tp == BUILD: + return node + else: + return None + + tree = self.__class__.bld + if not name in tree.cache_dir_contents[parent.id]: + return None + + path = parent.abspath() + os.sep + name + try: + st = Utils.h_file(path) + except IOError: + return None + + child = self.__class__(name, parent, FILE) + tree.node_sigs[0][child.id] = st + return child + + def find_or_declare(self, lst): + "Used for declaring a build node representing a file being built" + if isinstance(lst, str): + lst = Utils.split_path(lst) + + if len(lst) == 1: + parent = self + else: + parent = self.find_dir(lst[:-1]) + if not parent: return None + self.__class__.bld.rescan(parent) + + name = lst[-1] + node = parent.childs.get(name, None) + if node: + tp = node.id & 3 + if tp != BUILD: + raise Utils.WafError('find_or_declare cannot return a build node (build files in the source directory %r?)' % lst) + return node + node = self.__class__(name, parent, BUILD) + return node + + def find_dir(self, lst): + "search a folder in the filesystem" + + if isinstance(lst, str): + lst = Utils.split_path(lst) + + current = self + for name in lst: + self.__class__.bld.rescan(current) + prev = current + + if not current.parent and name == current.name: + continue + elif not name: + continue + elif name == '.': + continue + elif name == '..': + current = current.parent or current + else: + current = prev.childs.get(name, None) + if current is None: + dir_cont = self.__class__.bld.cache_dir_contents + if prev.id in dir_cont and name in dir_cont[prev.id]: + if not prev.name: + if os.sep == '/': + # cygwin //machine/share + dirname = os.sep + name + else: + # windows c: + dirname = name + else: + # regular path + dirname = prev.abspath() + os.sep + name + if not os.path.isdir(dirname): + return None + current = self.__class__(name, prev, DIR) + elif (not prev.name and len(name) == 2 and name[1] == ':') or name.startswith('\\\\'): + # drive letter or \\ path for windows + current = self.__class__(name, prev, DIR) + else: + return None + else: + if current.id & 3 != DIR: + return None + return current + + def ensure_dir_node_from_path(self, lst): + "used very rarely, force the construction of a branch of node instance for representing folders" + + if isinstance(lst, str): + lst = Utils.split_path(lst) + + current = self + for name in lst: + if not name: + continue + elif name == '.': + continue + elif name == '..': + current = current.parent or current + else: + prev = current + current = prev.childs.get(name, None) + if current is None: + current = self.__class__(name, prev, DIR) + return current + + def exclusive_build_node(self, path): + """ + create a hierarchy in the build dir (no source folders) for ill-behaving compilers + the node is not hashed, so you must do it manually + + after declaring such a node, find_dir and find_resource should work as expected + """ + lst = Utils.split_path(path) + name = lst[-1] + if len(lst) > 1: + parent = None + try: + parent = self.find_dir(lst[:-1]) + except OSError: + pass + if not parent: + parent = self.ensure_dir_node_from_path(lst[:-1]) + self.__class__.bld.rescan(parent) + else: + try: + self.__class__.bld.rescan(parent) + except OSError: + pass + else: + parent = self + + node = parent.childs.get(name, None) + if not node: + node = self.__class__(name, parent, BUILD) + + return node + + def path_to_parent(self, parent): + "path relative to a direct ancestor, as string" + lst = [] + p = self + h1 = parent.height() + h2 = p.height() + while h2 > h1: + h2 -= 1 + lst.append(p.name) + p = p.parent + if lst: + lst.reverse() + ret = os.path.join(*lst) + else: + ret = '' + return ret + + def find_ancestor(self, node): + "find a common ancestor for two nodes - for the shortest path in hierarchy" + dist = self.height() - node.height() + if dist < 0: return node.find_ancestor(self) + # now the real code + cand = self + while dist > 0: + cand = cand.parent + dist -= 1 + if cand == node: return cand + cursor = node + while cand.parent: + cand = cand.parent + cursor = cursor.parent + if cand == cursor: return cand + + def relpath_gen(self, from_node): + "string representing a relative path between self to another node" + + if self == from_node: return '.' + if from_node.parent == self: return '..' + + # up_path is '../../../' and down_path is 'dir/subdir/subdir/file' + ancestor = self.find_ancestor(from_node) + lst = [] + cand = self + while not cand.id == ancestor.id: + lst.append(cand.name) + cand = cand.parent + cand = from_node + while not cand.id == ancestor.id: + lst.append('..') + cand = cand.parent + lst.reverse() + return os.sep.join(lst) + + def nice_path(self, env=None): + "printed in the console, open files easily from the launch directory" + tree = self.__class__.bld + ln = tree.launch_node() + + if self.id & 3 == FILE: return self.relpath_gen(ln) + else: return os.path.join(tree.bldnode.relpath_gen(ln), env.variant(), self.relpath_gen(tree.srcnode)) + + def is_child_of(self, node): + "does this node belong to the subtree node" + p = self + diff = self.height() - node.height() + while diff > 0: + diff -= 1 + p = p.parent + return p.id == node.id + + def variant(self, env): + "variant, or output directory for this node, a source has for variant 0" + if not env: return 0 + elif self.id & 3 == FILE: return 0 + else: return env.variant() + + def height(self): + "amount of parents" + # README a cache can be added here if necessary + d = self + val = -1 + while d: + d = d.parent + val += 1 + return val + + # helpers for building things + + def abspath(self, env=None): + """ + absolute path + @param env [Environment]: + * obligatory for build nodes: build/variant/src/dir/bar.o + * optional for dirs: get either src/dir or build/variant/src/dir + * excluded for source nodes: src/dir/bar.c + + Instead of computing the absolute path each time again, + store the already-computed absolute paths in one of (variants+1) dictionaries: + bld.cache_node_abspath[0] holds absolute paths for source nodes. + bld.cache_node_abspath[variant] holds the absolute path for the build nodes + which reside in the variant given by env. + """ + ## absolute path - hot zone, so do not touch + + # less expensive + variant = (env and (self.id & 3 != FILE) and env.variant()) or 0 + + ret = self.__class__.bld.cache_node_abspath[variant].get(self.id, None) + if ret: return ret + + if not variant: + # source directory + if not self.parent: + val = os.sep == '/' and os.sep or '' + elif not self.parent.name: # root + val = (os.sep == '/' and os.sep or '') + self.name + else: + val = self.parent.abspath() + os.sep + self.name + else: + # build directory + val = os.sep.join((self.__class__.bld.bldnode.abspath(), variant, self.path_to_parent(self.__class__.bld.srcnode))) + self.__class__.bld.cache_node_abspath[variant][self.id] = val + return val + + def change_ext(self, ext): + "node of the same path, but with a different extension - hot zone so do not touch" + name = self.name + k = name.rfind('.') + if k >= 0: + name = name[:k] + ext + else: + name = name + ext + + return self.parent.find_or_declare([name]) + + def src_dir(self, env): + "src path without the file name" + return self.parent.srcpath(env) + + def bld_dir(self, env): + "build path without the file name" + return self.parent.bldpath(env) + + def bld_base(self, env): + "build path without the extension: src/dir/foo(.cpp)" + s = os.path.splitext(self.name)[0] + return os.path.join(self.bld_dir(env), s) + + def bldpath(self, env=None): + "path seen from the build dir default/src/foo.cpp" + if self.id & 3 == FILE: + return self.relpath_gen(self.__class__.bld.bldnode) + p = self.path_to_parent(self.__class__.bld.srcnode) + if p is not '': + return env.variant() + os.sep + p + return env.variant() + + def srcpath(self, env=None): + "path in the srcdir from the build dir ../src/foo.cpp" + if self.id & 3 == BUILD: + return self.bldpath(env) + return self.relpath_gen(self.__class__.bld.bldnode) + + def read(self, env): + "get the contents of a file, it is not used anywhere for the moment" + return Utils.readf(self.abspath(env)) + + def dir(self, env): + "scons-like" + return self.parent.abspath(env) + + def file(self): + "scons-like" + return self.name + + def file_base(self): + "scons-like" + return os.path.splitext(self.name)[0] + + def suffix(self): + "scons-like - hot zone so do not touch" + k = max(0, self.name.rfind('.')) + return self.name[k:] + + def find_iter_impl(self, src=True, bld=True, dir=True, accept_name=None, is_prune=None, maxdepth=25): + """find nodes in the filesystem hierarchy, try to instanciate the nodes passively; same gotcha as ant_glob""" + bld_ctx = self.__class__.bld + bld_ctx.rescan(self) + for name in bld_ctx.cache_dir_contents[self.id]: + if accept_name(self, name): + node = self.find_resource(name) + if node: + if src and node.id & 3 == FILE: + yield node + else: + node = self.find_dir(name) + if node and node.id != bld_ctx.bldnode.id: + if dir: + yield node + if not is_prune(self, name): + if maxdepth: + for k in node.find_iter_impl(src, bld, dir, accept_name, is_prune, maxdepth=maxdepth - 1): + yield k + else: + if not is_prune(self, name): + node = self.find_resource(name) + if not node: + # not a file, it is a dir + node = self.find_dir(name) + if node and node.id != bld_ctx.bldnode.id: + if maxdepth: + for k in node.find_iter_impl(src, bld, dir, accept_name, is_prune, maxdepth=maxdepth - 1): + yield k + + if bld: + for node in self.childs.values(): + if node.id == bld_ctx.bldnode.id: + continue + if node.id & 3 == BUILD: + if accept_name(self, node.name): + yield node + raise StopIteration + + def find_iter(self, in_pat=['*'], ex_pat=exclude_pats, prune_pat=prune_pats, src=True, bld=True, dir=False, maxdepth=25, flat=False): + """find nodes recursively, this returns everything but folders by default; same gotcha as ant_glob""" + + if not (src or bld or dir): + raise StopIteration + + if self.id & 3 != DIR: + raise StopIteration + + in_pat = Utils.to_list(in_pat) + ex_pat = Utils.to_list(ex_pat) + prune_pat = Utils.to_list(prune_pat) + + def accept_name(node, name): + for pat in ex_pat: + if fnmatch.fnmatchcase(name, pat): + return False + for pat in in_pat: + if fnmatch.fnmatchcase(name, pat): + return True + return False + + def is_prune(node, name): + for pat in prune_pat: + if fnmatch.fnmatchcase(name, pat): + return True + return False + + ret = self.find_iter_impl(src, bld, dir, accept_name, is_prune, maxdepth=maxdepth) + if flat: + return " ".join([x.relpath_gen(self) for x in ret]) + + return ret + + def ant_glob(self, *k, **kw): + """ + known gotcha: will enumerate the files, but only if the folder exists in the source directory + """ + + src=kw.get('src', 1) + bld=kw.get('bld', 0) + dir=kw.get('dir', 0) + excl = kw.get('excl', exclude_regs) + incl = k and k[0] or kw.get('incl', '**') + + def to_pat(s): + lst = Utils.to_list(s) + ret = [] + for x in lst: + x = x.replace('//', '/') + if x.endswith('/'): + x += '**' + lst2 = x.split('/') + accu = [] + for k in lst2: + if k == '**': + accu.append(k) + else: + k = k.replace('.', '[.]').replace('*', '.*').replace('?', '.') + k = '^%s$' % k + #print "pattern", k + accu.append(re.compile(k)) + ret.append(accu) + return ret + + def filtre(name, nn): + ret = [] + for lst in nn: + if not lst: + pass + elif lst[0] == '**': + ret.append(lst) + if len(lst) > 1: + if lst[1].match(name): + ret.append(lst[2:]) + else: + ret.append([]) + elif lst[0].match(name): + ret.append(lst[1:]) + return ret + + def accept(name, pats): + nacc = filtre(name, pats[0]) + nrej = filtre(name, pats[1]) + if [] in nrej: + nacc = [] + return [nacc, nrej] + + def ant_iter(nodi, maxdepth=25, pats=[]): + nodi.__class__.bld.rescan(nodi) + for name in nodi.__class__.bld.cache_dir_contents[nodi.id]: + npats = accept(name, pats) + if npats and npats[0]: + accepted = [] in npats[0] + #print accepted, nodi, name + + node = nodi.find_resource(name) + if node and accepted: + if src and node.id & 3 == FILE: + yield node + else: + node = nodi.find_dir(name) + if node and node.id != nodi.__class__.bld.bldnode.id: + if accepted and dir: + yield node + if maxdepth: + for k in ant_iter(node, maxdepth=maxdepth - 1, pats=npats): + yield k + if bld: + for node in nodi.childs.values(): + if node.id == nodi.__class__.bld.bldnode.id: + continue + if node.id & 3 == BUILD: + npats = accept(node.name, pats) + if npats and npats[0] and [] in npats[0]: + yield node + raise StopIteration + + ret = [x for x in ant_iter(self, pats=[to_pat(incl), to_pat(excl)])] + + if kw.get('flat', True): + return " ".join([x.relpath_gen(self) for x in ret]) + + return ret + + def update_build_dir(self, env=None): + + if not env: + for env in bld.all_envs: + self.update_build_dir(env) + return + + path = self.abspath(env) + + lst = Utils.listdir(path) + try: + self.__class__.bld.cache_dir_contents[self.id].update(lst) + except KeyError: + self.__class__.bld.cache_dir_contents[self.id] = set(lst) + self.__class__.bld.cache_scanned_folders[self.id] = True + + for k in lst: + npath = path + os.sep + k + st = os.stat(npath) + if stat.S_ISREG(st[stat.ST_MODE]): + ick = self.find_or_declare(k) + if not (ick.id in self.__class__.bld.node_sigs[env.variant()]): + self.__class__.bld.node_sigs[env.variant()][ick.id] = Constants.SIG_NIL + elif stat.S_ISDIR(st[stat.ST_MODE]): + child = self.find_dir(k) + if not child: + child = self.ensure_dir_node_from_path(k) + child.update_build_dir(env) + + +class Nodu(Node): + pass + diff --git a/node-v0.8.14/tools/wafadmin/Options.py b/node-v0.8.14/tools/wafadmin/Options.py new file mode 100644 index 0000000..c90bb99 --- /dev/null +++ b/node-v0.8.14/tools/wafadmin/Options.py @@ -0,0 +1,279 @@ +#!/usr/bin/env python +# encoding: utf-8 +# Scott Newton, 2005 (scottn) +# Thomas Nagy, 2006 (ita) + +"Custom command-line options" + +import os, sys, imp, types, tempfile, optparse +import Logs, Utils +from Constants import * + +cmds = 'distclean configure build install clean uninstall check dist distcheck'.split() + +# TODO remove in waf 1.6 the following two +commands = {} +is_install = False + +options = {} +arg_line = [] +launch_dir = '' +tooldir = '' +lockfile = os.environ.get('WAFLOCK', '.lock-wscript') +try: cache_global = os.path.abspath(os.environ['WAFCACHE']) +except KeyError: cache_global = '' +platform = Utils.unversioned_sys_platform() +conf_file = 'conf-runs-%s-%d.pickle' % (platform, ABI) + +remote_repo = ['http://waf.googlecode.com/svn/'] +"""remote directory for the plugins""" + + +# Such a command-line should work: JOBS=4 PREFIX=/opt/ DESTDIR=/tmp/ahoj/ waf configure +default_prefix = os.environ.get('PREFIX') +if not default_prefix: + if platform == 'win32': default_prefix = tempfile.gettempdir() + else: default_prefix = '/usr/local/' + +default_jobs = os.environ.get('JOBS', -1) +if default_jobs < 1: + try: + if 'SC_NPROCESSORS_ONLN' in os.sysconf_names: + default_jobs = os.sysconf('SC_NPROCESSORS_ONLN') + else: + default_jobs = int(Utils.cmd_output(['sysctl', '-n', 'hw.ncpu'])) + except: + if os.name == 'java': # platform.system() == 'Java' + from java.lang import Runtime + default_jobs = Runtime.getRuntime().availableProcessors() + else: + # environment var defined on win32 + default_jobs = int(os.environ.get('NUMBER_OF_PROCESSORS', 1)) + +default_destdir = os.environ.get('DESTDIR', '') + +def get_usage(self): + cmds_str = [] + module = Utils.g_module + if module: + # create the help messages for commands + tbl = module.__dict__ + keys = list(tbl.keys()) + keys.sort() + + if 'build' in tbl: + if not module.build.__doc__: + module.build.__doc__ = 'builds the project' + if 'configure' in tbl: + if not module.configure.__doc__: + module.configure.__doc__ = 'configures the project' + + ban = ['set_options', 'init', 'shutdown'] + + optlst = [x for x in keys if not x in ban + and type(tbl[x]) is type(parse_args_impl) + and tbl[x].__doc__ + and not x.startswith('_')] + + just = max([len(x) for x in optlst]) + + for x in optlst: + cmds_str.append(' %s: %s' % (x.ljust(just), tbl[x].__doc__)) + ret = '\n'.join(cmds_str) + else: + ret = ' '.join(cmds) + return '''waf [command] [options] + +Main commands (example: ./waf build -j4) +%s +''' % ret + + +setattr(optparse.OptionParser, 'get_usage', get_usage) + +def create_parser(module=None): + Logs.debug('options: create_parser is called') + parser = optparse.OptionParser(conflict_handler="resolve", version = 'waf %s (%s)' % (WAFVERSION, WAFREVISION)) + + parser.formatter.width = Utils.get_term_cols() + p = parser.add_option + + p('-j', '--jobs', + type = 'int', + default = default_jobs, + help = 'amount of parallel jobs (%r)' % default_jobs, + dest = 'jobs') + + p('-k', '--keep', + action = 'store_true', + default = False, + help = 'keep running happily on independent task groups', + dest = 'keep') + + p('-v', '--verbose', + action = 'count', + default = 0, + help = 'verbosity level -v -vv or -vvv [default: 0]', + dest = 'verbose') + + p('--nocache', + action = 'store_true', + default = False, + help = 'ignore the WAFCACHE (if set)', + dest = 'nocache') + + p('--zones', + action = 'store', + default = '', + help = 'debugging zones (task_gen, deps, tasks, etc)', + dest = 'zones') + + p('-p', '--progress', + action = 'count', + default = 0, + help = '-p: progress bar; -pp: ide output', + dest = 'progress_bar') + + p('--targets', + action = 'store', + default = '', + help = 'build given task generators, e.g. "target1,target2"', + dest = 'compile_targets') + + gr = optparse.OptionGroup(parser, 'configuration options') + parser.add_option_group(gr) + gr.add_option('-b', '--blddir', + action = 'store', + default = '', + help = 'build dir for the project (configuration)', + dest = 'blddir') + gr.add_option('-s', '--srcdir', + action = 'store', + default = '', + help = 'src dir for the project (configuration)', + dest = 'srcdir') + gr.add_option('--prefix', + help = 'installation prefix (configuration) [default: %r]' % default_prefix, + default = default_prefix, + dest = 'prefix') + + gr = optparse.OptionGroup(parser, 'installation options') + parser.add_option_group(gr) + gr.add_option('--destdir', + help = 'installation root [default: %r]' % default_destdir, + default = default_destdir, + dest = 'destdir') + gr.add_option('-f', '--force', + action = 'store_true', + default = False, + help = 'force file installation', + dest = 'force') + + return parser + +def parse_args_impl(parser, _args=None): + global options, commands, arg_line + (options, args) = parser.parse_args(args=_args) + + arg_line = args + #arg_line = args[:] # copy + + # By default, 'waf' is equivalent to 'waf build' + commands = {} + for var in cmds: commands[var] = 0 + if not args: + commands['build'] = 1 + args.append('build') + + # Parse the command arguments + for arg in args: + commands[arg] = True + + # the check thing depends on the build + if 'check' in args: + idx = args.index('check') + try: + bidx = args.index('build') + if bidx > idx: + raise ValueError('build before check') + except ValueError, e: + args.insert(idx, 'build') + + if args[0] != 'init': + args.insert(0, 'init') + + # TODO -k => -j0 + if options.keep: options.jobs = 1 + if options.jobs < 1: options.jobs = 1 + + if 'install' in sys.argv or 'uninstall' in sys.argv: + # absolute path only if set + options.destdir = options.destdir and os.path.abspath(os.path.expanduser(options.destdir)) + + Logs.verbose = options.verbose + Logs.init_log() + + if options.zones: + Logs.zones = options.zones.split(',') + if not Logs.verbose: Logs.verbose = 1 + elif Logs.verbose > 0: + Logs.zones = ['runner'] + if Logs.verbose > 2: + Logs.zones = ['*'] + +# TODO waf 1.6 +# 1. rename the class to OptionsContext +# 2. instead of a class attribute, use a module (static 'parser') +# 3. parse_args_impl was made in times when we did not know about binding new methods to classes + +class Handler(Utils.Context): + """loads wscript modules in folders for adding options + This class should be named 'OptionsContext' + A method named 'recurse' is bound when used by the module Scripting""" + + parser = None + # make it possible to access the reference, like Build.bld + + def __init__(self, module=None): + self.parser = create_parser(module) + self.cwd = os.getcwd() + Handler.parser = self + + def add_option(self, *k, **kw): + self.parser.add_option(*k, **kw) + + def add_option_group(self, *k, **kw): + return self.parser.add_option_group(*k, **kw) + + def get_option_group(self, opt_str): + return self.parser.get_option_group(opt_str) + + def sub_options(self, *k, **kw): + if not k: raise Utils.WscriptError('folder expected') + self.recurse(k[0], name='set_options') + + def tool_options(self, *k, **kw): + Utils.python_24_guard() + + if not k[0]: + raise Utils.WscriptError('invalid tool_options call %r %r' % (k, kw)) + tools = Utils.to_list(k[0]) + + # TODO waf 1.6 remove the global variable tooldir + path = Utils.to_list(kw.get('tdir', kw.get('tooldir', tooldir))) + + for tool in tools: + tool = tool.replace('++', 'xx') + if tool == 'java': tool = 'javaw' + if tool.lower() == 'unittest': tool = 'unittestw' + module = Utils.load_tool(tool, path) + try: + fun = module.set_options + except AttributeError: + pass + else: + fun(kw.get('option_group', self)) + + def parse_args(self, args=None): + parse_args_impl(self.parser, args) + diff --git a/node-v0.8.14/tools/wafadmin/Runner.py b/node-v0.8.14/tools/wafadmin/Runner.py new file mode 100644 index 0000000..5237c1a --- /dev/null +++ b/node-v0.8.14/tools/wafadmin/Runner.py @@ -0,0 +1,229 @@ +#!/usr/bin/env python +# encoding: utf-8 +# Thomas Nagy, 2005-2008 (ita) + +"Execute the tasks" + +import sys, random, time, threading, traceback +try: from Queue import Queue +except ImportError: from queue import Queue +import Build, Utils, Logs, Options +from Logs import debug, error +from Constants import * + +GAP = 15 + +run_old = threading.Thread.run +def run(*args, **kwargs): + try: + run_old(*args, **kwargs) + except (KeyboardInterrupt, SystemExit): + raise + except: + sys.excepthook(*sys.exc_info()) +threading.Thread.run = run + +class TaskConsumer(threading.Thread): + ready = Queue(0) + consumers = [] + + def __init__(self): + threading.Thread.__init__(self) + self.setDaemon(1) + self.start() + + def run(self): + try: + self.loop() + except: + pass + + def loop(self): + while 1: + tsk = TaskConsumer.ready.get() + m = tsk.master + if m.stop: + m.out.put(tsk) + continue + + try: + tsk.generator.bld.printout(tsk.display()) + if tsk.__class__.stat: ret = tsk.__class__.stat(tsk) + # actual call to task's run() function + else: ret = tsk.call_run() + except Exception, e: + tsk.err_msg = Utils.ex_stack() + tsk.hasrun = EXCEPTION + + # TODO cleanup + m.error_handler(tsk) + m.out.put(tsk) + continue + + if ret: + tsk.err_code = ret + tsk.hasrun = CRASHED + else: + try: + tsk.post_run() + except Utils.WafError: + pass + except Exception: + tsk.err_msg = Utils.ex_stack() + tsk.hasrun = EXCEPTION + else: + tsk.hasrun = SUCCESS + if tsk.hasrun != SUCCESS: + m.error_handler(tsk) + + m.out.put(tsk) + +class Parallel(object): + """ + keep the consumer threads busy, and avoid consuming cpu cycles + when no more tasks can be added (end of the build, etc) + """ + def __init__(self, bld, j=2): + + # number of consumers + self.numjobs = j + + self.manager = bld.task_manager + self.manager.current_group = 0 + + self.total = self.manager.total() + + # tasks waiting to be processed - IMPORTANT + self.outstanding = [] + self.maxjobs = MAXJOBS + + # tasks that are awaiting for another task to complete + self.frozen = [] + + # tasks returned by the consumers + self.out = Queue(0) + + self.count = 0 # tasks not in the producer area + + self.processed = 1 # progress indicator + + self.stop = False # error condition to stop the build + self.error = False # error flag + + def get_next(self): + "override this method to schedule the tasks in a particular order" + if not self.outstanding: + return None + return self.outstanding.pop(0) + + def postpone(self, tsk): + "override this method to schedule the tasks in a particular order" + # TODO consider using a deque instead + if random.randint(0, 1): + self.frozen.insert(0, tsk) + else: + self.frozen.append(tsk) + + def refill_task_list(self): + "called to set the next group of tasks" + + while self.count > self.numjobs + GAP or self.count >= self.maxjobs: + self.get_out() + + while not self.outstanding: + if self.count: + self.get_out() + + if self.frozen: + self.outstanding += self.frozen + self.frozen = [] + elif not self.count: + (jobs, tmp) = self.manager.get_next_set() + if jobs != None: self.maxjobs = jobs + if tmp: self.outstanding += tmp + break + + def get_out(self): + "the tasks that are put to execute are all collected using get_out" + ret = self.out.get() + self.manager.add_finished(ret) + if not self.stop and getattr(ret, 'more_tasks', None): + self.outstanding += ret.more_tasks + self.total += len(ret.more_tasks) + self.count -= 1 + + def error_handler(self, tsk): + "by default, errors make the build stop (not thread safe so be careful)" + if not Options.options.keep: + self.stop = True + self.error = True + + def start(self): + "execute the tasks" + + if TaskConsumer.consumers: + # the worker pool is usually loaded lazily (see below) + # in case it is re-used with a different value of numjobs: + while len(TaskConsumer.consumers) < self.numjobs: + TaskConsumer.consumers.append(TaskConsumer()) + + while not self.stop: + + self.refill_task_list() + + # consider the next task + tsk = self.get_next() + if not tsk: + if self.count: + # tasks may add new ones after they are run + continue + else: + # no tasks to run, no tasks running, time to exit + break + + if tsk.hasrun: + # if the task is marked as "run", just skip it + self.processed += 1 + self.manager.add_finished(tsk) + continue + + try: + st = tsk.runnable_status() + except Exception, e: + self.processed += 1 + if self.stop and not Options.options.keep: + tsk.hasrun = SKIPPED + self.manager.add_finished(tsk) + continue + self.error_handler(tsk) + self.manager.add_finished(tsk) + tsk.hasrun = EXCEPTION + tsk.err_msg = Utils.ex_stack() + continue + + if st == ASK_LATER: + self.postpone(tsk) + elif st == SKIP_ME: + self.processed += 1 + tsk.hasrun = SKIPPED + self.manager.add_finished(tsk) + else: + # run me: put the task in ready queue + tsk.position = (self.processed, self.total) + self.count += 1 + tsk.master = self + TaskConsumer.ready.put(tsk) + self.processed += 1 + + # create the consumer threads only if there is something to consume + if not TaskConsumer.consumers: + TaskConsumer.consumers = [TaskConsumer() for i in xrange(self.numjobs)] + + # self.count represents the tasks that have been made available to the consumer threads + # collect all the tasks after an error else the message may be incomplete + while self.error and self.count: + self.get_out() + + #print loop + assert (self.count == 0 or self.stop) + diff --git a/node-v0.8.14/tools/wafadmin/Scripting.py b/node-v0.8.14/tools/wafadmin/Scripting.py new file mode 100644 index 0000000..d975bd9 --- /dev/null +++ b/node-v0.8.14/tools/wafadmin/Scripting.py @@ -0,0 +1,586 @@ +#!/usr/bin/env python +# encoding: utf-8 +# Thomas Nagy, 2005 (ita) + +"Module called for configuring, compiling and installing targets" + +import os, sys, shutil, traceback, datetime, inspect, errno + +import Utils, Configure, Build, Logs, Options, Environment, Task +from Logs import error, warn, info +from Constants import * + +g_gz = 'bz2' +commands = [] + +def prepare_impl(t, cwd, ver, wafdir): + Options.tooldir = [t] + Options.launch_dir = cwd + + # some command-line options can be processed immediately + if '--version' in sys.argv: + opt_obj = Options.Handler() + opt_obj.curdir = cwd + opt_obj.parse_args() + sys.exit(0) + + # now find the wscript file + msg1 = 'Waf: Please run waf from a directory containing a file named "%s" or run distclean' % WSCRIPT_FILE + + # in theory projects can be configured in an autotool-like manner: + # mkdir build && cd build && ../waf configure && ../waf + build_dir_override = None + candidate = None + + lst = os.listdir(cwd) + + search_for_candidate = True + if WSCRIPT_FILE in lst: + candidate = cwd + + elif 'configure' in sys.argv and not WSCRIPT_BUILD_FILE in lst: + # autotool-like configuration + calldir = os.path.abspath(os.path.dirname(sys.argv[0])) + if WSCRIPT_FILE in os.listdir(calldir): + candidate = calldir + search_for_candidate = False + else: + error('arg[0] directory does not contain a wscript file') + sys.exit(1) + build_dir_override = cwd + + # climb up to find a script if it is not found + while search_for_candidate: + if len(cwd) <= 3: + break # stop at / or c: + dirlst = os.listdir(cwd) + if WSCRIPT_FILE in dirlst: + candidate = cwd + if 'configure' in sys.argv and candidate: + break + if Options.lockfile in dirlst: + env = Environment.Environment() + try: + env.load(os.path.join(cwd, Options.lockfile)) + except: + error('could not load %r' % Options.lockfile) + try: + os.stat(env['cwd']) + except: + candidate = cwd + else: + candidate = env['cwd'] + break + cwd = os.path.dirname(cwd) # climb up + + if not candidate: + # check if the user only wanted to display the help + if '-h' in sys.argv or '--help' in sys.argv: + warn('No wscript file found: the help message may be incomplete') + opt_obj = Options.Handler() + opt_obj.curdir = cwd + opt_obj.parse_args() + else: + error(msg1) + sys.exit(0) + + # We have found wscript, but there is no guarantee that it is valid + try: + os.chdir(candidate) + except OSError: + raise Utils.WafError("the folder %r is unreadable" % candidate) + + # define the main module containing the functions init, shutdown, .. + Utils.set_main_module(os.path.join(candidate, WSCRIPT_FILE)) + + if build_dir_override: + d = getattr(Utils.g_module, BLDDIR, None) + if d: + # test if user has set the blddir in wscript. + msg = ' Overriding build directory %s with %s' % (d, build_dir_override) + warn(msg) + Utils.g_module.blddir = build_dir_override + + # bind a few methods and classes by default + + def set_def(obj, name=''): + n = name or obj.__name__ + if not n in Utils.g_module.__dict__: + setattr(Utils.g_module, n, obj) + + for k in [dist, distclean, distcheck, clean, install, uninstall]: + set_def(k) + + set_def(Configure.ConfigurationContext, 'configure_context') + + for k in ['build', 'clean', 'install', 'uninstall']: + set_def(Build.BuildContext, k + '_context') + + # now parse the options from the user wscript file + opt_obj = Options.Handler(Utils.g_module) + opt_obj.curdir = candidate + try: + f = Utils.g_module.set_options + except AttributeError: + pass + else: + opt_obj.sub_options(['']) + opt_obj.parse_args() + + if not 'init' in Utils.g_module.__dict__: + Utils.g_module.init = Utils.nada + if not 'shutdown' in Utils.g_module.__dict__: + Utils.g_module.shutdown = Utils.nada + + main() + +def prepare(t, cwd, ver, wafdir): + if WAFVERSION != ver: + msg = 'Version mismatch: waf %s <> wafadmin %s (wafdir %s)' % (ver, WAFVERSION, wafdir) + print('\033[91mError: %s\033[0m' % msg) + sys.exit(1) + + #""" + try: + prepare_impl(t, cwd, ver, wafdir) + except Utils.WafError, e: + error(str(e)) + sys.exit(1) + except KeyboardInterrupt: + Utils.pprint('RED', 'Interrupted') + sys.exit(68) + """ + import cProfile, pstats + cProfile.runctx("import Scripting; Scripting.prepare_impl(t, cwd, ver, wafdir)", {}, + {'t': t, 'cwd':cwd, 'ver':ver, 'wafdir':wafdir}, + 'profi.txt') + p = pstats.Stats('profi.txt') + p.sort_stats('time').print_stats(45) + #""" + +def main(): + global commands + commands = Options.arg_line[:] + + while commands: + x = commands.pop(0) + + ini = datetime.datetime.now() + if x == 'configure': + fun = configure + elif x == 'build': + fun = build + else: + fun = getattr(Utils.g_module, x, None) + + if not fun: + raise Utils.WscriptError('No such command %r' % x) + + ctx = getattr(Utils.g_module, x + '_context', Utils.Context)() + + if x in ['init', 'shutdown', 'dist', 'distclean', 'distcheck']: + # compatibility TODO remove in waf 1.6 + try: + fun(ctx) + except TypeError: + fun() + else: + fun(ctx) + + ela = '' + if not Options.options.progress_bar: + ela = ' (%s)' % Utils.get_elapsed_time(ini) + + if x != 'init' and x != 'shutdown': + info('%r finished successfully%s' % (x, ela)) + + if not commands and x != 'shutdown': + commands.append('shutdown') + +def configure(conf): + + src = getattr(Options.options, SRCDIR, None) + if not src: src = getattr(Utils.g_module, SRCDIR, None) + if not src: src = getattr(Utils.g_module, 'top', None) + if not src: + src = '.' + incomplete_src = 1 + src = os.path.abspath(src) + + bld = getattr(Options.options, BLDDIR, None) + if not bld: bld = getattr(Utils.g_module, BLDDIR, None) + if not bld: bld = getattr(Utils.g_module, 'out', None) + if not bld: + bld = 'build' + incomplete_bld = 1 + if bld == '.': + raise Utils.WafError('Setting blddir="." may cause distclean problems') + bld = os.path.abspath(bld) + + try: os.makedirs(bld) + except OSError: pass + + # It is not possible to compile specific targets in the configuration + # this may cause configuration errors if autoconfig is set + targets = Options.options.compile_targets + Options.options.compile_targets = None + Options.is_install = False + + conf.srcdir = src + conf.blddir = bld + conf.post_init() + + if 'incomplete_src' in vars(): + conf.check_message_1('Setting srcdir to') + conf.check_message_2(src) + if 'incomplete_bld' in vars(): + conf.check_message_1('Setting blddir to') + conf.check_message_2(bld) + + # calling to main wscript's configure() + conf.sub_config(['']) + + conf.store() + + # this will write a configure lock so that subsequent builds will + # consider the current path as the root directory (see prepare_impl). + # to remove: use 'waf distclean' + env = Environment.Environment() + env[BLDDIR] = bld + env[SRCDIR] = src + env['argv'] = sys.argv + env['commands'] = Options.commands + env['options'] = Options.options.__dict__ + + # conf.hash & conf.files hold wscript files paths and hash + # (used only by Configure.autoconfig) + env['hash'] = conf.hash + env['files'] = conf.files + env['environ'] = dict(conf.environ) + env['cwd'] = os.path.split(Utils.g_module.root_path)[0] + + if Utils.g_module.root_path != src: + # in case the source dir is somewhere else + env.store(os.path.join(src, Options.lockfile)) + + env.store(Options.lockfile) + + Options.options.compile_targets = targets + +def clean(bld): + '''removes the build files''' + try: + proj = Environment.Environment(Options.lockfile) + except IOError: + raise Utils.WafError('Nothing to clean (project not configured)') + + bld.load_dirs(proj[SRCDIR], proj[BLDDIR]) + bld.load_envs() + + bld.is_install = 0 # False + + # read the scripts - and set the path to the wscript path (useful for srcdir='/foo/bar') + bld.add_subdirs([os.path.split(Utils.g_module.root_path)[0]]) + + try: + bld.clean() + finally: + bld.save() + +def check_configured(bld): + if not Configure.autoconfig: + return bld + + conf_cls = getattr(Utils.g_module, 'configure_context', Utils.Context) + bld_cls = getattr(Utils.g_module, 'build_context', Utils.Context) + + def reconf(proj): + back = (Options.commands, Options.options.__dict__, Logs.zones, Logs.verbose) + + Options.commands = proj['commands'] + Options.options.__dict__ = proj['options'] + conf = conf_cls() + conf.environ = proj['environ'] + configure(conf) + + (Options.commands, Options.options.__dict__, Logs.zones, Logs.verbose) = back + + try: + proj = Environment.Environment(Options.lockfile) + except IOError: + conf = conf_cls() + configure(conf) + else: + try: + bld = bld_cls() + bld.load_dirs(proj[SRCDIR], proj[BLDDIR]) + bld.load_envs() + except Utils.WafError: + reconf(proj) + return bld_cls() + + try: + proj = Environment.Environment(Options.lockfile) + except IOError: + raise Utils.WafError('Auto-config: project does not configure (bug)') + + h = 0 + try: + for file in proj['files']: + if file.endswith('configure'): + h = hash((h, Utils.readf(file))) + else: + mod = Utils.load_module(file) + h = hash((h, mod.waf_hash_val)) + except (OSError, IOError): + warn('Reconfiguring the project: a file is unavailable') + reconf(proj) + else: + if (h != proj['hash']): + warn('Reconfiguring the project: the configuration has changed') + reconf(proj) + + return bld_cls() + +def install(bld): + '''installs the build files''' + bld = check_configured(bld) + + Options.commands['install'] = True + Options.commands['uninstall'] = False + Options.is_install = True + + bld.is_install = INSTALL + + build_impl(bld) + bld.install() + +def uninstall(bld): + '''removes the installed files''' + Options.commands['install'] = False + Options.commands['uninstall'] = True + Options.is_install = True + + bld.is_install = UNINSTALL + + try: + def runnable_status(self): + return SKIP_ME + setattr(Task.Task, 'runnable_status_back', Task.Task.runnable_status) + setattr(Task.Task, 'runnable_status', runnable_status) + + build_impl(bld) + bld.install() + finally: + setattr(Task.Task, 'runnable_status', Task.Task.runnable_status_back) + +def build(bld): + bld = check_configured(bld) + + Options.commands['install'] = False + Options.commands['uninstall'] = False + Options.is_install = False + + bld.is_install = 0 # False + + return build_impl(bld) + +def build_impl(bld): + # compile the project and/or install the files + try: + proj = Environment.Environment(Options.lockfile) + except IOError: + raise Utils.WafError("Project not configured (run 'waf configure' first)") + + bld.load_dirs(proj[SRCDIR], proj[BLDDIR]) + bld.load_envs() + + info("Waf: Entering directory `%s'" % bld.bldnode.abspath()) + bld.add_subdirs([os.path.split(Utils.g_module.root_path)[0]]) + + # execute something immediately before the build starts + bld.pre_build() + + try: + bld.compile() + finally: + if Options.options.progress_bar: print('') + info("Waf: Leaving directory `%s'" % bld.bldnode.abspath()) + + # execute something immediately after a successful build + bld.post_build() + + bld.install() + +excludes = '.bzr .bzrignore .git .gitignore .svn CVS .cvsignore .arch-ids {arch} SCCS BitKeeper .hg _MTN _darcs Makefile Makefile.in config.log .gitattributes .hgignore .hgtags'.split() +dist_exts = '~ .rej .orig .pyc .pyo .bak .tar.bz2 tar.gz .zip .swp'.split() +def dont_dist(name, src, build_dir): + global excludes, dist_exts + + if (name.startswith(',,') + or name.startswith('++') + or name.startswith('.waf') + or (src == '.' and name == Options.lockfile) + or name in excludes + or name == build_dir + ): + return True + + for ext in dist_exts: + if name.endswith(ext): + return True + + return False + +# like shutil.copytree +# exclude files and to raise exceptions immediately +def copytree(src, dst, build_dir): + names = os.listdir(src) + os.makedirs(dst) + for name in names: + srcname = os.path.join(src, name) + dstname = os.path.join(dst, name) + + if dont_dist(name, src, build_dir): + continue + + if os.path.isdir(srcname): + copytree(srcname, dstname, build_dir) + else: + shutil.copy2(srcname, dstname) + +# TODO in waf 1.6, change this method if "srcdir == blddir" is allowed +def distclean(ctx=None): + '''removes the build directory''' + global commands + lst = os.listdir('.') + for f in lst: + if f == Options.lockfile: + try: + proj = Environment.Environment(f) + except: + Logs.warn('could not read %r' % f) + continue + + try: + shutil.rmtree(proj[BLDDIR]) + except IOError: + pass + except OSError, e: + if e.errno != errno.ENOENT: + Logs.warn('project %r cannot be removed' % proj[BLDDIR]) + + try: + os.remove(f) + except OSError, e: + if e.errno != errno.ENOENT: + Logs.warn('file %r cannot be removed' % f) + + # remove the local waf cache + if not commands and f.startswith('.waf'): + shutil.rmtree(f, ignore_errors=True) + +# FIXME waf 1.6 a unique ctx parameter, and remove the optional appname and version +def dist(appname='', version=''): + '''makes a tarball for redistributing the sources''' + # return return (distdirname, tarballname) + import tarfile + + if not appname: appname = Utils.g_module.APPNAME + if not version: version = Utils.g_module.VERSION + + tmp_folder = appname + '-' + version + if g_gz in ['gz', 'bz2']: + arch_name = tmp_folder + '.tar.' + g_gz + else: + arch_name = tmp_folder + '.' + 'zip' + + # remove the previous dir + try: + shutil.rmtree(tmp_folder) + except (OSError, IOError): + pass + + # remove the previous archive + try: + os.remove(arch_name) + except (OSError, IOError): + pass + + # copy the files into the temporary folder + blddir = getattr(Utils.g_module, BLDDIR, None) + if not blddir: + blddir = getattr(Utils.g_module, 'out', None) + copytree('.', tmp_folder, blddir) + + # undocumented hook for additional cleanup + dist_hook = getattr(Utils.g_module, 'dist_hook', None) + if dist_hook: + back = os.getcwd() + os.chdir(tmp_folder) + try: + dist_hook() + finally: + # go back to the root directory + os.chdir(back) + + if g_gz in ['gz', 'bz2']: + tar = tarfile.open(arch_name, 'w:' + g_gz) + tar.add(tmp_folder) + tar.close() + else: + Utils.zip_folder(tmp_folder, arch_name, tmp_folder) + + try: from hashlib import sha1 as sha + except ImportError: from sha import sha + try: + digest = " (sha=%r)" % sha(Utils.readf(arch_name)).hexdigest() + except: + digest = '' + + info('New archive created: %s%s' % (arch_name, digest)) + + if os.path.exists(tmp_folder): shutil.rmtree(tmp_folder) + return arch_name + +# FIXME waf 1.6 a unique ctx parameter, and remove the optional appname and version +def distcheck(appname='', version='', subdir=''): + '''checks if the sources compile (tarball from 'dist')''' + import tempfile, tarfile + + if not appname: appname = Utils.g_module.APPNAME + if not version: version = Utils.g_module.VERSION + + waf = os.path.abspath(sys.argv[0]) + tarball = dist(appname, version) + + path = appname + '-' + version + + # remove any previous instance + if os.path.exists(path): + shutil.rmtree(path) + + t = tarfile.open(tarball) + for x in t: t.extract(x) + t.close() + + # build_path is the directory for the waf invocation + if subdir: + build_path = os.path.join(path, subdir) + else: + build_path = path + + instdir = tempfile.mkdtemp('.inst', '%s-%s' % (appname, version)) + ret = Utils.pproc.Popen([waf, 'configure', 'build', 'install', 'uninstall', '--destdir=' + instdir], cwd=build_path).wait() + if ret: + raise Utils.WafError('distcheck failed with code %i' % ret) + + if os.path.exists(instdir): + raise Utils.WafError('distcheck succeeded, but files were left in %s' % instdir) + + shutil.rmtree(path) + +# FIXME remove in Waf 1.6 (kept for compatibility) +def add_subdir(dir, bld): + bld.recurse(dir, 'build') + diff --git a/node-v0.8.14/tools/wafadmin/Task.py b/node-v0.8.14/tools/wafadmin/Task.py new file mode 100644 index 0000000..24edf2c --- /dev/null +++ b/node-v0.8.14/tools/wafadmin/Task.py @@ -0,0 +1,1171 @@ +#!/usr/bin/env python +# encoding: utf-8 +# Thomas Nagy, 2005-2008 (ita) + +""" +Running tasks in parallel is a simple problem, but in practice it is more complicated: +* dependencies discovered during the build (dynamic task creation) +* dependencies discovered after files are compiled +* the amount of tasks and dependencies (graph size) can be huge + +This is why the dependency management is split on three different levels: +1. groups of tasks that run all after another group of tasks +2. groups of tasks that can be run in parallel +3. tasks that can run in parallel, but with possible unknown ad-hoc dependencies + +The point #1 represents a strict sequential order between groups of tasks, for example a compiler is produced +and used to compile the rest, whereas #2 and #3 represent partial order constraints where #2 applies to the kind of task +and #3 applies to the task instances. + +#1 is held by the task manager: ordered list of TaskGroups (see bld.add_group) +#2 is held by the task groups and the task types: precedence after/before (topological sort), + and the constraints extracted from file extensions +#3 is held by the tasks individually (attribute run_after), + and the scheduler (Runner.py) use Task::runnable_status to reorder the tasks + +-- + +To try, use something like this in your code: +import Constants, Task +Task.algotype = Constants.MAXPARALLEL + +-- + +There are two concepts with the tasks (individual units of change): +* dependency (if 1 is recompiled, recompile 2) +* order (run 2 after 1) + +example 1: if t1 depends on t2 and t2 depends on t3 it is not necessary to make t1 depend on t3 (dependency is transitive) +example 2: if t1 depends on a node produced by t2, it is not immediately obvious that t1 must run after t2 (order is not obvious) + +The role of the Task Manager is to give the tasks in order (groups of task that may be run in parallel one after the other) + +""" + +import os, shutil, sys, re, random, datetime, tempfile, shlex +from Utils import md5 +import Build, Runner, Utils, Node, Logs, Options +from Logs import debug, warn, error +from Constants import * + +algotype = NORMAL +#algotype = JOBCONTROL +#algotype = MAXPARALLEL + +COMPILE_TEMPLATE_SHELL = ''' +def f(task): + env = task.env + wd = getattr(task, 'cwd', None) + p = env.get_flat + cmd = \'\'\' %s \'\'\' % s + return task.exec_command(cmd, cwd=wd) +''' + +COMPILE_TEMPLATE_NOSHELL = ''' +def f(task): + env = task.env + wd = getattr(task, 'cwd', None) + def to_list(xx): + if isinstance(xx, str): return [xx] + return xx + lst = [] + %s + lst = [x for x in lst if x] + return task.exec_command(lst, cwd=wd) +''' + + +""" +Enable different kind of dependency algorithms: +1 make groups: first compile all cpps and then compile all links (NORMAL) +2 parallelize all (each link task run after its dependencies) (MAXPARALLEL) +3 like 1 but provide additional constraints for the parallelization (MAXJOBS) + +In theory 1. will be faster than 2 for waf, but might be slower for builds +The scheme 2 will not allow for running tasks one by one so it can cause disk thrashing on huge builds +""" + +file_deps = Utils.nada +""" +Additional dependency pre-check may be added by replacing the function file_deps. +e.g. extract_outputs, extract_deps below. +""" + +class TaskManager(object): + """The manager is attached to the build object, it holds a list of TaskGroup""" + def __init__(self): + self.groups = [] + self.tasks_done = [] + self.current_group = 0 + self.groups_names = {} + + def get_next_set(self): + """return the next set of tasks to execute + the first parameter is the maximum amount of parallelization that may occur""" + ret = None + while not ret and self.current_group < len(self.groups): + ret = self.groups[self.current_group].get_next_set() + if ret: return ret + else: + self.groups[self.current_group].process_install() + self.current_group += 1 + return (None, None) + + def add_group(self, name=None, set=True): + #if self.groups and not self.groups[0].tasks: + # error('add_group: an empty group is already present') + g = TaskGroup() + + if name and name in self.groups_names: + error('add_group: name %s already present' % name) + self.groups_names[name] = g + self.groups.append(g) + if set: + self.current_group = len(self.groups) - 1 + + def set_group(self, idx): + if isinstance(idx, str): + g = self.groups_names[idx] + for x in xrange(len(self.groups)): + if id(g) == id(self.groups[x]): + self.current_group = x + else: + self.current_group = idx + + def add_task_gen(self, tgen): + if not self.groups: self.add_group() + self.groups[self.current_group].tasks_gen.append(tgen) + + def add_task(self, task): + if not self.groups: self.add_group() + self.groups[self.current_group].tasks.append(task) + + def total(self): + total = 0 + if not self.groups: return 0 + for group in self.groups: + total += len(group.tasks) + return total + + def add_finished(self, tsk): + self.tasks_done.append(tsk) + bld = tsk.generator.bld + if bld.is_install: + f = None + if 'install' in tsk.__dict__: + f = tsk.__dict__['install'] + # install=0 to prevent installation + if f: f(tsk) + else: + tsk.install() + +class TaskGroup(object): + "the compilation of one group does not begin until the previous group has finished (in the manager)" + def __init__(self): + self.tasks = [] # this list will be consumed + self.tasks_gen = [] + + self.cstr_groups = Utils.DefaultDict(list) # tasks having equivalent constraints + self.cstr_order = Utils.DefaultDict(set) # partial order between the cstr groups + self.temp_tasks = [] # tasks put on hold + self.ready = 0 + self.post_funs = [] + + def reset(self): + "clears the state of the object (put back the tasks into self.tasks)" + for x in self.cstr_groups: + self.tasks += self.cstr_groups[x] + self.tasks = self.temp_tasks + self.tasks + self.temp_tasks = [] + self.cstr_groups = Utils.DefaultDict(list) + self.cstr_order = Utils.DefaultDict(set) + self.ready = 0 + + def process_install(self): + for (f, k, kw) in self.post_funs: + f(*k, **kw) + + def prepare(self): + "prepare the scheduling" + self.ready = 1 + file_deps(self.tasks) + self.make_cstr_groups() + self.extract_constraints() + + def get_next_set(self): + "next list of tasks to execute using max job settings, returns (maxjobs, task_list)" + global algotype + if algotype == NORMAL: + tasks = self.tasks_in_parallel() + maxj = MAXJOBS + elif algotype == JOBCONTROL: + (maxj, tasks) = self.tasks_by_max_jobs() + elif algotype == MAXPARALLEL: + tasks = self.tasks_with_inner_constraints() + maxj = MAXJOBS + else: + raise Utils.WafError("unknown algorithm type %s" % (algotype)) + + if not tasks: return () + return (maxj, tasks) + + def make_cstr_groups(self): + "unite the tasks that have similar constraints" + self.cstr_groups = Utils.DefaultDict(list) + for x in self.tasks: + h = x.hash_constraints() + self.cstr_groups[h].append(x) + + def set_order(self, a, b): + self.cstr_order[a].add(b) + + def compare_exts(self, t1, t2): + "extension production" + x = "ext_in" + y = "ext_out" + in_ = t1.attr(x, ()) + out_ = t2.attr(y, ()) + for k in in_: + if k in out_: + return -1 + in_ = t2.attr(x, ()) + out_ = t1.attr(y, ()) + for k in in_: + if k in out_: + return 1 + return 0 + + def compare_partial(self, t1, t2): + "partial relations after/before" + m = "after" + n = "before" + name = t2.__class__.__name__ + if name in Utils.to_list(t1.attr(m, ())): return -1 + elif name in Utils.to_list(t1.attr(n, ())): return 1 + name = t1.__class__.__name__ + if name in Utils.to_list(t2.attr(m, ())): return 1 + elif name in Utils.to_list(t2.attr(n, ())): return -1 + return 0 + + def extract_constraints(self): + "extract the parallelization constraints from the tasks with different constraints" + keys = self.cstr_groups.keys() + max = len(keys) + # hopefully the length of this list is short + for i in xrange(max): + t1 = self.cstr_groups[keys[i]][0] + for j in xrange(i + 1, max): + t2 = self.cstr_groups[keys[j]][0] + + # add the constraints based on the comparisons + val = (self.compare_exts(t1, t2) + or self.compare_partial(t1, t2) + ) + if val > 0: + self.set_order(keys[i], keys[j]) + elif val < 0: + self.set_order(keys[j], keys[i]) + + def tasks_in_parallel(self): + "(NORMAL) next list of tasks that may be executed in parallel" + + if not self.ready: self.prepare() + + keys = self.cstr_groups.keys() + + unconnected = [] + remainder = [] + + for u in keys: + for k in self.cstr_order.values(): + if u in k: + remainder.append(u) + break + else: + unconnected.append(u) + + toreturn = [] + for y in unconnected: + toreturn.extend(self.cstr_groups[y]) + + # remove stuff only after + for y in unconnected: + try: self.cstr_order.__delitem__(y) + except KeyError: pass + self.cstr_groups.__delitem__(y) + + if not toreturn and remainder: + raise Utils.WafError("circular order constraint detected %r" % remainder) + + return toreturn + + def tasks_by_max_jobs(self): + "(JOBCONTROL) returns the tasks that can run in parallel with the max amount of jobs" + if not self.ready: self.prepare() + if not self.temp_tasks: self.temp_tasks = self.tasks_in_parallel() + if not self.temp_tasks: return (None, None) + + maxjobs = MAXJOBS + ret = [] + remaining = [] + for t in self.temp_tasks: + m = getattr(t, "maxjobs", getattr(self.__class__, "maxjobs", MAXJOBS)) + if m > maxjobs: + remaining.append(t) + elif m < maxjobs: + remaining += ret + ret = [t] + maxjobs = m + else: + ret.append(t) + self.temp_tasks = remaining + return (maxjobs, ret) + + def tasks_with_inner_constraints(self): + """(MAXPARALLEL) returns all tasks in this group, but add the constraints on each task instance + as an optimization, it might be desirable to discard the tasks which do not have to run""" + if not self.ready: self.prepare() + + if getattr(self, "done", None): return None + + for p in self.cstr_order: + for v in self.cstr_order[p]: + for m in self.cstr_groups[p]: + for n in self.cstr_groups[v]: + n.set_run_after(m) + self.cstr_order = Utils.DefaultDict(set) + self.cstr_groups = Utils.DefaultDict(list) + self.done = 1 + return self.tasks[:] # make a copy + +class store_task_type(type): + "store the task types that have a name ending in _task into a map (remember the existing task types)" + def __init__(cls, name, bases, dict): + super(store_task_type, cls).__init__(name, bases, dict) + name = cls.__name__ + + if name.endswith('_task'): + name = name.replace('_task', '') + if name != 'TaskBase': + TaskBase.classes[name] = cls + +class TaskBase(object): + """Base class for all Waf tasks + + The most important methods are (by usual order of call): + 1 runnable_status: ask the task if it should be run, skipped, or if we have to ask later + 2 __str__: string to display to the user + 3 run: execute the task + 4 post_run: after the task is run, update the cache about the task + + This class should be seen as an interface, it provides the very minimum necessary for the scheduler + so it does not do much. + + For illustration purposes, TaskBase instances try to execute self.fun (if provided) + """ + + __metaclass__ = store_task_type + + color = "GREEN" + maxjobs = MAXJOBS + classes = {} + stat = None + + def __init__(self, *k, **kw): + self.hasrun = NOT_RUN + + try: + self.generator = kw['generator'] + except KeyError: + self.generator = self + self.bld = Build.bld + + if kw.get('normal', 1): + self.generator.bld.task_manager.add_task(self) + + def __repr__(self): + "used for debugging" + return '\n\t{task: %s %s}' % (self.__class__.__name__, str(getattr(self, "fun", ""))) + + def __str__(self): + "string to display to the user" + if hasattr(self, 'fun'): + return 'executing: %s\n' % self.fun.__name__ + return self.__class__.__name__ + '\n' + + def exec_command(self, *k, **kw): + "use this for executing commands from tasks" + # TODO in waf 1.6, eliminate bld.exec_command, and move the cwd processing to here + if self.env['env']: + kw['env'] = self.env['env'] + return self.generator.bld.exec_command(*k, **kw) + + def runnable_status(self): + "RUN_ME SKIP_ME or ASK_LATER" + return RUN_ME + + def can_retrieve_cache(self): + return False + + def call_run(self): + if self.can_retrieve_cache(): + return 0 + return self.run() + + def run(self): + "called if the task must run" + if hasattr(self, 'fun'): + return self.fun(self) + return 0 + + def post_run(self): + "update the dependency tree (node stats)" + pass + + def display(self): + "print either the description (using __str__) or the progress bar or the ide output" + col1 = Logs.colors(self.color) + col2 = Logs.colors.NORMAL + + if Options.options.progress_bar == 1: + return self.generator.bld.progress_line(self.position[0], self.position[1], col1, col2) + + if Options.options.progress_bar == 2: + ela = Utils.get_elapsed_time(self.generator.bld.ini) + try: + ins = ','.join([n.name for n in self.inputs]) + except AttributeError: + ins = '' + try: + outs = ','.join([n.name for n in self.outputs]) + except AttributeError: + outs = '' + return '|Total %s|Current %s|Inputs %s|Outputs %s|Time %s|\n' % (self.position[1], self.position[0], ins, outs, ela) + + total = self.position[1] + n = len(str(total)) + fs = '[%%%dd/%%%dd] %%s%%s%%s' % (n, n) + return fs % (self.position[0], self.position[1], col1, str(self), col2) + + def attr(self, att, default=None): + "retrieve an attribute from the instance or from the class (microoptimization here)" + ret = getattr(self, att, self) + if ret is self: return getattr(self.__class__, att, default) + return ret + + def hash_constraints(self): + "identify a task type for all the constraints relevant for the scheduler: precedence, file production" + a = self.attr + sum = hash((self.__class__.__name__, + str(a('before', '')), + str(a('after', '')), + str(a('ext_in', '')), + str(a('ext_out', '')), + self.__class__.maxjobs)) + return sum + + def format_error(self): + "error message to display to the user (when a build fails)" + if getattr(self, "err_msg", None): + return self.err_msg + elif self.hasrun == CRASHED: + try: + return " -> task failed (err #%d): %r" % (self.err_code, self) + except AttributeError: + return " -> task failed: %r" % self + elif self.hasrun == MISSING: + return " -> missing files: %r" % self + else: + return '' + + def install(self): + """ + installation is performed by looking at the task attributes: + * install_path: installation path like "${PREFIX}/bin" + * filename: install the first node in the outputs as a file with a particular name, be certain to give os.sep + * chmod: permissions + """ + bld = self.generator.bld + d = self.attr('install') + + if self.attr('install_path'): + lst = [a.relpath_gen(bld.srcnode) for a in self.outputs] + perm = self.attr('chmod', O644) + if self.attr('src'): + # if src is given, install the sources too + lst += [a.relpath_gen(bld.srcnode) for a in self.inputs] + if self.attr('filename'): + dir = self.install_path.rstrip(os.sep) + os.sep + self.attr('filename') + bld.install_as(dir, lst[0], self.env, perm) + else: + bld.install_files(self.install_path, lst, self.env, perm) + +class Task(TaskBase): + """The parent class is quite limited, in this version: + * file system interaction: input and output nodes + * persistence: do not re-execute tasks that have already run + * caching: same files can be saved and retrieved from a cache directory + * dependencies: + implicit, like .c files depending on .h files + explicit, like the input nodes or the dep_nodes + environment variables, like the CXXFLAGS in self.env + """ + vars = [] + def __init__(self, env, **kw): + TaskBase.__init__(self, **kw) + self.env = env + + # inputs and outputs are nodes + # use setters when possible + self.inputs = [] + self.outputs = [] + + self.deps_nodes = [] + self.run_after = [] + + # Additionally, you may define the following + #self.dep_vars = 'PREFIX DATADIR' + + def __str__(self): + "string to display to the user" + env = self.env + src_str = ' '.join([a.nice_path(env) for a in self.inputs]) + tgt_str = ' '.join([a.nice_path(env) for a in self.outputs]) + if self.outputs: sep = ' -> ' + else: sep = '' + return '%s: %s%s%s\n' % (self.__class__.__name__.replace('_task', ''), src_str, sep, tgt_str) + + def __repr__(self): + return "".join(['\n\t{task: ', self.__class__.__name__, " ", ",".join([x.name for x in self.inputs]), " -> ", ",".join([x.name for x in self.outputs]), '}']) + + def unique_id(self): + "get a unique id: hash the node paths, the variant, the class, the function" + try: + return self.uid + except AttributeError: + "this is not a real hot zone, but we want to avoid surprizes here" + m = md5() + up = m.update + up(self.__class__.__name__) + up(self.env.variant()) + p = None + for x in self.inputs + self.outputs: + if p != x.parent.id: + p = x.parent.id + up(x.parent.abspath()) + up(x.name) + self.uid = m.digest() + return self.uid + + def set_inputs(self, inp): + if isinstance(inp, list): self.inputs += inp + else: self.inputs.append(inp) + + def set_outputs(self, out): + if isinstance(out, list): self.outputs += out + else: self.outputs.append(out) + + def set_run_after(self, task): + "set (scheduler) order on another task" + # TODO: handle list or object + assert isinstance(task, TaskBase) + self.run_after.append(task) + + def add_file_dependency(self, filename): + "TODO user-provided file dependencies" + node = self.generator.bld.path.find_resource(filename) + self.deps_nodes.append(node) + + def signature(self): + # compute the result one time, and suppose the scan_signature will give the good result + try: return self.cache_sig[0] + except AttributeError: pass + + self.m = md5() + + # explicit deps + exp_sig = self.sig_explicit_deps() + + # env vars + var_sig = self.sig_vars() + + # implicit deps + + imp_sig = SIG_NIL + if self.scan: + try: + imp_sig = self.sig_implicit_deps() + except ValueError: + return self.signature() + + # we now have the signature (first element) and the details (for debugging) + ret = self.m.digest() + self.cache_sig = (ret, exp_sig, imp_sig, var_sig) + return ret + + def runnable_status(self): + "SKIP_ME RUN_ME or ASK_LATER" + #return 0 # benchmarking + + if self.inputs and (not self.outputs): + if not getattr(self.__class__, 'quiet', None): + warn("invalid task (no inputs OR outputs): override in a Task subclass or set the attribute 'quiet' %r" % self) + + for t in self.run_after: + if not t.hasrun: + return ASK_LATER + + env = self.env + bld = self.generator.bld + + # first compute the signature + new_sig = self.signature() + + # compare the signature to a signature computed previously + key = self.unique_id() + try: + prev_sig = bld.task_sigs[key][0] + except KeyError: + debug("task: task %r must run as it was never run before or the task code changed", self) + return RUN_ME + + # compare the signatures of the outputs + for node in self.outputs: + variant = node.variant(env) + try: + if bld.node_sigs[variant][node.id] != new_sig: + return RUN_ME + except KeyError: + debug("task: task %r must run as the output nodes do not exist", self) + return RUN_ME + + # debug if asked to + if Logs.verbose: self.debug_why(bld.task_sigs[key]) + + if new_sig != prev_sig: + return RUN_ME + return SKIP_ME + + def post_run(self): + "called after a successful task run" + bld = self.generator.bld + env = self.env + sig = self.signature() + ssig = sig.encode('hex') + + variant = env.variant() + for node in self.outputs: + # check if the node exists .. + try: + os.stat(node.abspath(env)) + except OSError: + self.hasrun = MISSING + self.err_msg = '-> missing file: %r' % node.abspath(env) + raise Utils.WafError + + # important, store the signature for the next run + bld.node_sigs[variant][node.id] = sig + bld.task_sigs[self.unique_id()] = self.cache_sig + + # file caching, if possible + # try to avoid data corruption as much as possible + if not Options.cache_global or Options.options.nocache or not self.outputs: + return None + + if getattr(self, 'cached', None): + return None + + dname = os.path.join(Options.cache_global, ssig) + tmpdir = tempfile.mkdtemp(prefix=Options.cache_global) + + try: + shutil.rmtree(dname) + except: + pass + + try: + for node in self.outputs: + variant = node.variant(env) + dest = os.path.join(tmpdir, node.name) + shutil.copy2(node.abspath(env), dest) + except (OSError, IOError): + try: + shutil.rmtree(tmpdir) + except: + pass + else: + try: + os.rename(tmpdir, dname) + except OSError: + try: + shutil.rmtree(tmpdir) + except: + pass + else: + try: + os.chmod(dname, O755) + except: + pass + + def can_retrieve_cache(self): + """ + Retrieve build nodes from the cache + update the file timestamps to help cleaning the least used entries from the cache + additionally, set an attribute 'cached' to avoid re-creating the same cache files + + suppose there are files in cache/dir1/file1 and cache/dir2/file2 + first, read the timestamp of dir1 + then try to copy the files + then look at the timestamp again, if it has changed, the data may have been corrupt (cache update by another process) + should an exception occur, ignore the data + """ + if not Options.cache_global or Options.options.nocache or not self.outputs: + return None + + env = self.env + sig = self.signature() + ssig = sig.encode('hex') + + # first try to access the cache folder for the task + dname = os.path.join(Options.cache_global, ssig) + try: + t1 = os.stat(dname).st_mtime + except OSError: + return None + + for node in self.outputs: + variant = node.variant(env) + + orig = os.path.join(dname, node.name) + try: + shutil.copy2(orig, node.abspath(env)) + # mark the cache file as used recently (modified) + os.utime(orig, None) + except (OSError, IOError): + debug('task: failed retrieving file') + return None + + # is it the same folder? + try: + t2 = os.stat(dname).st_mtime + except OSError: + return None + + if t1 != t2: + return None + + for node in self.outputs: + self.generator.bld.node_sigs[variant][node.id] = sig + if Options.options.progress_bar < 1: + self.generator.bld.printout('restoring from cache %r\n' % node.bldpath(env)) + + self.cached = True + return 1 + + def debug_why(self, old_sigs): + "explains why a task is run" + + new_sigs = self.cache_sig + def v(x): + return x.encode('hex') + + debug("Task %r", self) + msgs = ['Task must run', '* Source file or manual dependency', '* Implicit dependency', '* Environment variable'] + tmp = 'task: -> %s: %s %s' + for x in xrange(len(msgs)): + if (new_sigs[x] != old_sigs[x]): + debug(tmp, msgs[x], v(old_sigs[x]), v(new_sigs[x])) + + def sig_explicit_deps(self): + bld = self.generator.bld + up = self.m.update + + # the inputs + for x in self.inputs + getattr(self, 'dep_nodes', []): + if not x.parent.id in bld.cache_scanned_folders: + bld.rescan(x.parent) + + variant = x.variant(self.env) + try: + up(bld.node_sigs[variant][x.id]) + except KeyError: + raise Utils.WafError('Missing node signature for %r (required by %r)' % (x, self)) + + # manual dependencies, they can slow down the builds + if bld.deps_man: + additional_deps = bld.deps_man + for x in self.inputs + self.outputs: + try: + d = additional_deps[x.id] + except KeyError: + continue + + for v in d: + if isinstance(v, Node.Node): + bld.rescan(v.parent) + variant = v.variant(self.env) + try: + v = bld.node_sigs[variant][v.id] + except KeyError: + raise Utils.WafError('Missing node signature for %r (required by %r)' % (v, self)) + elif hasattr(v, '__call__'): + v = v() # dependency is a function, call it + up(v) + + for x in self.deps_nodes: + v = bld.node_sigs[x.variant(self.env)][x.id] + up(v) + + return self.m.digest() + + def sig_vars(self): + bld = self.generator.bld + env = self.env + + # dependencies on the environment vars + act_sig = bld.hash_env_vars(env, self.__class__.vars) + self.m.update(act_sig) + + # additional variable dependencies, if provided + dep_vars = getattr(self, 'dep_vars', None) + if dep_vars: + self.m.update(bld.hash_env_vars(env, dep_vars)) + + return self.m.digest() + + #def scan(self, node): + # """this method returns a tuple containing: + # * a list of nodes corresponding to real files + # * a list of names for files not found in path_lst + # the input parameters may have more parameters that the ones used below + # """ + # return ((), ()) + scan = None + + # compute the signature, recompute it if there is no match in the cache + def sig_implicit_deps(self): + "the signature obtained may not be the one if the files have changed, we do it in two steps" + + bld = self.generator.bld + + # get the task signatures from previous runs + key = self.unique_id() + prev_sigs = bld.task_sigs.get(key, ()) + if prev_sigs: + try: + # for issue #379 + if prev_sigs[2] == self.compute_sig_implicit_deps(): + return prev_sigs[2] + except (KeyError, OSError): + pass + del bld.task_sigs[key] + raise ValueError('rescan') + + # no previous run or the signature of the dependencies has changed, rescan the dependencies + (nodes, names) = self.scan() + if Logs.verbose: + debug('deps: scanner for %s returned %s %s', str(self), str(nodes), str(names)) + + # store the dependencies in the cache + bld.node_deps[key] = nodes + bld.raw_deps[key] = names + + # recompute the signature and return it + try: + sig = self.compute_sig_implicit_deps() + except KeyError: + try: + nodes = [] + for k in bld.node_deps.get(self.unique_id(), []): + if k.id & 3 == 2: # Node.FILE: + if not k.id in bld.node_sigs[0]: + nodes.append(k) + else: + if not k.id in bld.node_sigs[self.env.variant()]: + nodes.append(k) + except: + nodes = '?' + raise Utils.WafError('Missing node signature for %r (for implicit dependencies %r)' % (nodes, self)) + + return sig + + def compute_sig_implicit_deps(self): + """it is intended for .cpp and inferred .h files + there is a single list (no tree traversal) + this is the hot spot so ... do not touch""" + upd = self.m.update + + bld = self.generator.bld + tstamp = bld.node_sigs + env = self.env + + for k in bld.node_deps.get(self.unique_id(), []): + # unlikely but necessary if it happens + if not k.parent.id in bld.cache_scanned_folders: + # if the parent folder is removed, an OSError may be thrown + bld.rescan(k.parent) + + # if the parent folder is removed, a KeyError will be thrown + if k.id & 3 == 2: # Node.FILE: + upd(tstamp[0][k.id]) + else: + upd(tstamp[env.variant()][k.id]) + + return self.m.digest() + +def funex(c): + dc = {} + exec(c, dc) + return dc['f'] + +reg_act = re.compile(r"(?P\\)|(?P\$\$)|(?P\$\{(?P\w+)(?P.*?)\})", re.M) +def compile_fun_shell(name, line): + """Compiles a string (once) into a function, eg: + simple_task_type('c++', '${CXX} -o ${TGT[0]} ${SRC} -I ${SRC[0].parent.bldpath()}') + + The env variables (CXX, ..) on the task must not hold dicts (order) + The reserved keywords TGT and SRC represent the task input and output nodes + + quick test: + bld(source='wscript', rule='echo "foo\\${SRC[0].name}\\bar"') + """ + + extr = [] + def repl(match): + g = match.group + if g('dollar'): return "$" + elif g('backslash'): return '\\\\' + elif g('subst'): extr.append((g('var'), g('code'))); return "%s" + return None + + line = reg_act.sub(repl, line) + + parm = [] + dvars = [] + app = parm.append + for (var, meth) in extr: + if var == 'SRC': + if meth: app('task.inputs%s' % meth) + else: app('" ".join([a.srcpath(env) for a in task.inputs])') + elif var == 'TGT': + if meth: app('task.outputs%s' % meth) + else: app('" ".join([a.bldpath(env) for a in task.outputs])') + else: + if not var in dvars: dvars.append(var) + app("p('%s')" % var) + if parm: parm = "%% (%s) " % (',\n\t\t'.join(parm)) + else: parm = '' + + c = COMPILE_TEMPLATE_SHELL % (line, parm) + + debug('action: %s', c) + return (funex(c), dvars) + +def compile_fun_noshell(name, line): + + extr = [] + def repl(match): + g = match.group + if g('dollar'): return "$" + elif g('subst'): extr.append((g('var'), g('code'))); return "<<|@|>>" + return None + + line2 = reg_act.sub(repl, line) + params = line2.split('<<|@|>>') + + buf = [] + dvars = [] + app = buf.append + for x in xrange(len(extr)): + params[x] = params[x].strip() + if params[x]: + app("lst.extend(%r)" % params[x].split()) + (var, meth) = extr[x] + if var == 'SRC': + if meth: app('lst.append(task.inputs%s)' % meth) + else: app("lst.extend([a.srcpath(env) for a in task.inputs])") + elif var == 'TGT': + if meth: app('lst.append(task.outputs%s)' % meth) + else: app("lst.extend([a.bldpath(env) for a in task.outputs])") + else: + app('lst.extend(to_list(env[%r]))' % var) + if not var in dvars: dvars.append(var) + + if params[-1]: + app("lst.extend(%r)" % shlex.split(params[-1])) + + fun = COMPILE_TEMPLATE_NOSHELL % "\n\t".join(buf) + debug('action: %s', fun) + return (funex(fun), dvars) + +def compile_fun(name, line, shell=None): + "commands can be launched by the shell or not" + if line.find('<') > 0 or line.find('>') > 0 or line.find('&&') > 0: + shell = True + #else: + # shell = False + + if shell is None: + if sys.platform == 'win32': + shell = False + else: + shell = True + + if shell: + return compile_fun_shell(name, line) + else: + return compile_fun_noshell(name, line) + +def simple_task_type(name, line, color='GREEN', vars=[], ext_in=[], ext_out=[], before=[], after=[], shell=None): + """return a new Task subclass with the function run compiled from the line given""" + (fun, dvars) = compile_fun(name, line, shell) + fun.code = line + return task_type_from_func(name, fun, vars or dvars, color, ext_in, ext_out, before, after) + +def task_type_from_func(name, func, vars=[], color='GREEN', ext_in=[], ext_out=[], before=[], after=[]): + """return a new Task subclass with the function run compiled from the line given""" + params = { + 'run': func, + 'vars': vars, + 'color': color, + 'name': name, + 'ext_in': Utils.to_list(ext_in), + 'ext_out': Utils.to_list(ext_out), + 'before': Utils.to_list(before), + 'after': Utils.to_list(after), + } + + cls = type(Task)(name, (Task,), params) + TaskBase.classes[name] = cls + return cls + +def always_run(cls): + """Set all task instances of this class to be executed whenever a build is started + The task signature is calculated, but the result of the comparation between + task signatures is bypassed + """ + old = cls.runnable_status + def always(self): + old(self) + return RUN_ME + cls.runnable_status = always + +def update_outputs(cls): + """When a command is always run, it is possible that the output only change + sometimes. By default the build node have as a hash the signature of the task + which may not change. With this, the output nodes (produced) are hashed, + and the hashes are set to the build nodes + + This may avoid unnecessary recompilations, but it uses more resources + (hashing the output files) so it is not used by default + """ + old_post_run = cls.post_run + def post_run(self): + old_post_run(self) + bld = self.outputs[0].__class__.bld + for output in self.outputs: + bld.node_sigs[self.env.variant()][output.id] = Utils.h_file(output.abspath(self.env)) + cls.post_run = post_run + + old_runnable_status = cls.runnable_status + def runnable_status(self): + status = old_runnable_status(self) + if status != RUN_ME: + return status + + try: + bld = self.outputs[0].__class__.bld + new_sig = self.signature() + prev_sig = bld.task_sigs[self.unique_id()][0] + if prev_sig == new_sig: + for x in self.outputs: + if not x.id in bld.node_sigs[self.env.variant()]: + return RUN_ME + return SKIP_ME + except KeyError: + pass + except IndexError: + pass + return RUN_ME + cls.runnable_status = runnable_status + +def extract_outputs(tasks): + """file_deps: Infer additional dependencies from task input and output nodes + """ + v = {} + for x in tasks: + try: + (ins, outs) = v[x.env.variant()] + except KeyError: + ins = {} + outs = {} + v[x.env.variant()] = (ins, outs) + + for a in getattr(x, 'inputs', []): + try: ins[a.id].append(x) + except KeyError: ins[a.id] = [x] + for a in getattr(x, 'outputs', []): + try: outs[a.id].append(x) + except KeyError: outs[a.id] = [x] + + for (ins, outs) in v.values(): + links = set(ins.iterkeys()).intersection(outs.iterkeys()) + for k in links: + for a in ins[k]: + for b in outs[k]: + a.set_run_after(b) + +def extract_deps(tasks): + """file_deps: Infer additional dependencies from task input and output nodes and from implicit dependencies + returned by the scanners - that will only work if all tasks are created + + this is aimed at people who have pathological builds and who do not care enough + to implement the build dependencies properly + + with two loops over the list of tasks, do not expect this to be really fast + """ + + # first reuse the function above + extract_outputs(tasks) + + # map the output nodes to the tasks producing them + out_to_task = {} + for x in tasks: + v = x.env.variant() + try: + lst = x.outputs + except AttributeError: + pass + else: + for node in lst: + out_to_task[(v, node.id)] = x + + # map the dependencies found to the tasks compiled + dep_to_task = {} + for x in tasks: + try: + x.signature() + except: # this is on purpose + pass + + v = x.env.variant() + key = x.unique_id() + for k in x.generator.bld.node_deps.get(x.unique_id(), []): + try: dep_to_task[(v, k.id)].append(x) + except KeyError: dep_to_task[(v, k.id)] = [x] + + # now get the intersection + deps = set(dep_to_task.keys()).intersection(set(out_to_task.keys())) + + # and add the dependencies from task to task + for idx in deps: + for k in dep_to_task[idx]: + k.set_run_after(out_to_task[idx]) + + # cleanup, remove the signatures + for x in tasks: + try: + delattr(x, 'cache_sig') + except AttributeError: + pass + diff --git a/node-v0.8.14/tools/wafadmin/TaskGen.py b/node-v0.8.14/tools/wafadmin/TaskGen.py new file mode 100644 index 0000000..260d999 --- /dev/null +++ b/node-v0.8.14/tools/wafadmin/TaskGen.py @@ -0,0 +1,588 @@ +#!/usr/bin/env python +# encoding: utf-8 +# Thomas Nagy, 2005-2008 (ita) + +""" +The class task_gen encapsulates the creation of task objects (low-level code) +The instances can have various parameters, but the creation of task nodes (Task.py) +is delayed. To achieve this, various methods are called from the method "apply" + +The class task_gen contains lots of methods, and a configuration table: +* the methods to call (self.meths) can be specified dynamically (removing, adding, ..) +* the order of the methods (self.prec or by default task_gen.prec) is configurable +* new methods can be inserted dynamically without pasting old code + +Additionally, task_gen provides the method apply_core +* file extensions are mapped to methods: def meth(self, name_or_node) +* if a mapping is not found in self.mappings, it is searched in task_gen.mappings +* when called, the functions may modify self.allnodes to re-add source to process +* the mappings can map an extension or a filename (see the code below) + +WARNING: subclasses must reimplement the clone method +""" + +import os, traceback, copy +import Build, Task, Utils, Logs, Options +from Logs import debug, error, warn +from Constants import * + +typos = { +'sources':'source', +'targets':'target', +'include':'includes', +'define':'defines', +'importpath':'importpaths', +'install_var':'install_path', +'install_subdir':'install_path', +'inst_var':'install_path', +'inst_dir':'install_path', +'feature':'features', +} + +class register_obj(type): + """no decorators for classes, so we use a metaclass + we store into task_gen.classes the classes that inherit task_gen + and whose names end in '_taskgen' + """ + def __init__(cls, name, bases, dict): + super(register_obj, cls).__init__(name, bases, dict) + name = cls.__name__ + suffix = '_taskgen' + if name.endswith(suffix): + task_gen.classes[name.replace(suffix, '')] = cls + +class task_gen(object): + """ + Most methods are of the form 'def meth(self):' without any parameters + there are many of them, and they do many different things: + * task creation + * task results installation + * environment modification + * attribute addition/removal + + The inheritance approach is complicated + * mixing several languages at once + * subclassing is needed even for small changes + * inserting new methods is complicated + + This new class uses a configuration table: + * adding new methods easily + * obtaining the order in which to call the methods + * postponing the method calls (post() -> apply) + + Additionally, a 'traits' static attribute is provided: + * this list contains methods + * the methods can remove or add methods from self.meths + Example1: the attribute 'staticlib' is set on an instance + a method set in the list of traits is executed when the + instance is posted, it finds that flag and adds another method for execution + Example2: a method set in the list of traits finds the msvc + compiler (from self.env['MSVC']==1); more methods are added to self.meths + """ + + __metaclass__ = register_obj + mappings = {} + mapped = {} + prec = Utils.DefaultDict(list) + traits = Utils.DefaultDict(set) + classes = {} + + def __init__(self, *kw, **kwargs): + self.prec = Utils.DefaultDict(list) + "map precedence of function names to call" + # so we will have to play with directed acyclic graphs + # detect cycles, etc + + self.source = '' + self.target = '' + + # list of methods to execute - does not touch it by hand unless you know + self.meths = [] + + # list of mappings extension -> function + self.mappings = {} + + # list of features (see the documentation on traits) + self.features = list(kw) + + # not always a good idea + self.tasks = [] + + self.default_chmod = O644 + self.default_install_path = None + + # kind of private, beware of what you put in it, also, the contents are consumed + self.allnodes = [] + + self.bld = kwargs.get('bld', Build.bld) + self.env = self.bld.env.copy() + + self.path = self.bld.path # emulate chdir when reading scripts + self.name = '' # give a name to the target (static+shlib with the same targetname ambiguity) + + # provide a unique id + self.idx = self.bld.idx[self.path.id] = self.bld.idx.get(self.path.id, 0) + 1 + + for key, val in kwargs.iteritems(): + setattr(self, key, val) + + self.bld.task_manager.add_task_gen(self) + self.bld.all_task_gen.append(self) + + def __str__(self): + return ("" + % (self.name or self.target, self.__class__.__name__, str(self.path))) + + def __setattr__(self, name, attr): + real = typos.get(name, name) + if real != name: + warn('typo %s -> %s' % (name, real)) + if Logs.verbose > 0: + traceback.print_stack() + object.__setattr__(self, real, attr) + + def to_list(self, value): + "helper: returns a list" + if isinstance(value, str): return value.split() + else: return value + + def apply(self): + "order the methods to execute using self.prec or task_gen.prec" + keys = set(self.meths) + + # add the methods listed in the features + self.features = Utils.to_list(self.features) + for x in self.features + ['*']: + st = task_gen.traits[x] + if not st: + warn('feature %r does not exist - bind at least one method to it' % x) + keys.update(st) + + # copy the precedence table + prec = {} + prec_tbl = self.prec or task_gen.prec + for x in prec_tbl: + if x in keys: + prec[x] = prec_tbl[x] + + # elements disconnected + tmp = [] + for a in keys: + for x in prec.values(): + if a in x: break + else: + tmp.append(a) + + # topological sort + out = [] + while tmp: + e = tmp.pop() + if e in keys: out.append(e) + try: + nlst = prec[e] + except KeyError: + pass + else: + del prec[e] + for x in nlst: + for y in prec: + if x in prec[y]: + break + else: + tmp.append(x) + + if prec: raise Utils.WafError("graph has a cycle %s" % str(prec)) + out.reverse() + self.meths = out + + # then we run the methods in order + debug('task_gen: posting %s %d', self, id(self)) + for x in out: + try: + v = getattr(self, x) + except AttributeError: + raise Utils.WafError("tried to retrieve %s which is not a valid method" % x) + debug('task_gen: -> %s (%d)', x, id(self)) + v() + + def post(self): + "runs the code to create the tasks, do not subclass" + if not self.name: + if isinstance(self.target, list): + self.name = ' '.join(self.target) + else: + self.name = self.target + + if getattr(self, 'posted', None): + #error("OBJECT ALREADY POSTED" + str( self)) + return + self.apply() + debug('task_gen: posted %s', self.name) + self.posted = True + + def get_hook(self, ext): + try: return self.mappings[ext] + except KeyError: + try: return task_gen.mappings[ext] + except KeyError: return None + + # TODO waf 1.6: always set the environment + # TODO waf 1.6: create_task(self, name, inputs, outputs) + def create_task(self, name, src=None, tgt=None, env=None): + env = env or self.env + task = Task.TaskBase.classes[name](env.copy(), generator=self) + if src: + task.set_inputs(src) + if tgt: + task.set_outputs(tgt) + self.tasks.append(task) + return task + + def name_to_obj(self, name): + return self.bld.name_to_obj(name, self.env) + + def find_sources_in_dirs(self, dirnames, excludes=[], exts=[]): + """ + The attributes "excludes" and "exts" must be lists to avoid the confusion + find_sources_in_dirs('a', 'b', 'c') <-> find_sources_in_dirs('a b c') + + do not use absolute paths + do not use paths outside of the source tree + the files or folder beginning by . are not returned + + # TODO: remove in Waf 1.6 + """ + + err_msg = "'%s' attribute must be a list" + if not isinstance(excludes, list): + raise Utils.WscriptError(err_msg % 'excludes') + if not isinstance(exts, list): + raise Utils.WscriptError(err_msg % 'exts') + + lst = [] + + #make sure dirnames is a list helps with dirnames with spaces + dirnames = self.to_list(dirnames) + + ext_lst = exts or list(self.mappings.keys()) + list(task_gen.mappings.keys()) + + for name in dirnames: + anode = self.path.find_dir(name) + + if not anode or not anode.is_child_of(self.bld.srcnode): + raise Utils.WscriptError("Unable to use '%s' - either because it's not a relative path" \ + ", or it's not child of '%s'." % (name, self.bld.srcnode)) + + self.bld.rescan(anode) + for name in self.bld.cache_dir_contents[anode.id]: + + # ignore hidden files + if name.startswith('.'): + continue + + (base, ext) = os.path.splitext(name) + if ext in ext_lst and not name in lst and not name in excludes: + lst.append((anode.relpath_gen(self.path) or '.') + os.path.sep + name) + + lst.sort() + self.source = self.to_list(self.source) + if not self.source: self.source = lst + else: self.source += lst + + def clone(self, env): + "" + newobj = task_gen(bld=self.bld) + for x in self.__dict__: + if x in ['env', 'bld']: + continue + elif x in ["path", "features"]: + setattr(newobj, x, getattr(self, x)) + else: + setattr(newobj, x, copy.copy(getattr(self, x))) + + newobj.__class__ = self.__class__ + if isinstance(env, str): + newobj.env = self.bld.all_envs[env].copy() + else: + newobj.env = env.copy() + + return newobj + + def get_inst_path(self): + return getattr(self, '_install_path', getattr(self, 'default_install_path', '')) + + def set_inst_path(self, val): + self._install_path = val + + install_path = property(get_inst_path, set_inst_path) + + + def get_chmod(self): + return getattr(self, '_chmod', getattr(self, 'default_chmod', O644)) + + def set_chmod(self, val): + self._chmod = val + + chmod = property(get_chmod, set_chmod) + +def declare_extension(var, func): + try: + for x in Utils.to_list(var): + task_gen.mappings[x] = func + except: + raise Utils.WscriptError('declare_extension takes either a list or a string %r' % var) + task_gen.mapped[func.__name__] = func + +def declare_order(*k): + assert(len(k) > 1) + n = len(k) - 1 + for i in xrange(n): + f1 = k[i] + f2 = k[i+1] + if not f1 in task_gen.prec[f2]: + task_gen.prec[f2].append(f1) + +def declare_chain(name='', action='', ext_in='', ext_out='', reentrant=True, color='BLUE', + install=0, before=[], after=[], decider=None, rule=None, scan=None): + """ + see Tools/flex.py for an example + while i do not like such wrappers, some people really do + """ + + action = action or rule + if isinstance(action, str): + act = Task.simple_task_type(name, action, color=color) + else: + act = Task.task_type_from_func(name, action, color=color) + act.ext_in = tuple(Utils.to_list(ext_in)) + act.ext_out = tuple(Utils.to_list(ext_out)) + act.before = Utils.to_list(before) + act.after = Utils.to_list(after) + act.scan = scan + + def x_file(self, node): + if decider: + ext = decider(self, node) + else: + ext = ext_out + + if isinstance(ext, str): + out_source = node.change_ext(ext) + if reentrant: + self.allnodes.append(out_source) + elif isinstance(ext, list): + out_source = [node.change_ext(x) for x in ext] + if reentrant: + for i in xrange((reentrant is True) and len(out_source) or reentrant): + self.allnodes.append(out_source[i]) + else: + # XXX: useless: it will fail on Utils.to_list above... + raise Utils.WafError("do not know how to process %s" % str(ext)) + + tsk = self.create_task(name, node, out_source) + + if node.__class__.bld.is_install: + tsk.install = install + + declare_extension(act.ext_in, x_file) + +def bind_feature(name, methods): + lst = Utils.to_list(methods) + task_gen.traits[name].update(lst) + +""" +All the following decorators are registration decorators, i.e add an attribute to current class + (task_gen and its derivatives), with same name as func, which points to func itself. +For example: + @taskgen + def sayHi(self): + print("hi") +Now taskgen.sayHi() may be called + +If python were really smart, it could infer itself the order of methods by looking at the +attributes. A prerequisite for execution is to have the attribute set before. +Intelligent compilers binding aspect-oriented programming and parallelization, what a nice topic for studies. +""" +def taskgen(func): + setattr(task_gen, func.__name__, func) + return func + +def feature(*k): + def deco(func): + setattr(task_gen, func.__name__, func) + for name in k: + task_gen.traits[name].update([func.__name__]) + return func + return deco + +def before(*k): + def deco(func): + setattr(task_gen, func.__name__, func) + for fun_name in k: + if not func.__name__ in task_gen.prec[fun_name]: + task_gen.prec[fun_name].append(func.__name__) + return func + return deco + +def after(*k): + def deco(func): + setattr(task_gen, func.__name__, func) + for fun_name in k: + if not fun_name in task_gen.prec[func.__name__]: + task_gen.prec[func.__name__].append(fun_name) + return func + return deco + +def extension(var): + def deco(func): + setattr(task_gen, func.__name__, func) + try: + for x in Utils.to_list(var): + task_gen.mappings[x] = func + except: + raise Utils.WafError('extension takes either a list or a string %r' % var) + task_gen.mapped[func.__name__] = func + return func + return deco + +# TODO make certain the decorators may be used here + +def apply_core(self): + """Process the attribute source + transform the names into file nodes + try to process the files by name first, later by extension""" + # get the list of folders to use by the scanners + # all our objects share the same include paths anyway + find_resource = self.path.find_resource + + for filename in self.to_list(self.source): + # if self.mappings or task_gen.mappings contains a file of the same name + x = self.get_hook(filename) + if x: + x(self, filename) + else: + node = find_resource(filename) + if not node: raise Utils.WafError("source not found: '%s' in '%s'" % (filename, str(self.path))) + self.allnodes.append(node) + + for node in self.allnodes: + # self.mappings or task_gen.mappings map the file extension to a function + x = self.get_hook(node.suffix()) + + if not x: + raise Utils.WafError("Cannot guess how to process %s (got mappings %r in %r) -> try conf.check_tool(..)?" % \ + (str(node), self.__class__.mappings.keys(), self.__class__)) + x(self, node) +feature('*')(apply_core) + +def exec_rule(self): + """Process the attribute rule, when provided the method apply_core will be disabled + """ + if not getattr(self, 'rule', None): + return + + # someone may have removed it already + try: + self.meths.remove('apply_core') + except ValueError: + pass + + # get the function and the variables + func = self.rule + + vars2 = [] + if isinstance(func, str): + # use the shell by default for user-defined commands + (func, vars2) = Task.compile_fun('', self.rule, shell=getattr(self, 'shell', True)) + func.code = self.rule + + # create the task class + name = getattr(self, 'name', None) or self.target or self.rule + if not isinstance(name, str): + name = str(self.idx) + cls = Task.task_type_from_func(name, func, getattr(self, 'vars', vars2)) + + # now create one instance + tsk = self.create_task(name) + + dep_vars = getattr(self, 'dep_vars', ['ruledeps']) + if dep_vars: + tsk.dep_vars = dep_vars + if isinstance(self.rule, str): + tsk.env.ruledeps = self.rule + else: + # only works if the function is in a global module such as a waf tool + tsk.env.ruledeps = Utils.h_fun(self.rule) + + # we assume that the user knows that without inputs or outputs + #if not getattr(self, 'target', None) and not getattr(self, 'source', None): + # cls.quiet = True + + if getattr(self, 'target', None): + cls.quiet = True + tsk.outputs = [self.path.find_or_declare(x) for x in self.to_list(self.target)] + + if getattr(self, 'source', None): + cls.quiet = True + tsk.inputs = [] + for x in self.to_list(self.source): + y = self.path.find_resource(x) + if not y: + raise Utils.WafError('input file %r could not be found (%r)' % (x, self.path.abspath())) + tsk.inputs.append(y) + + if self.allnodes: + tsk.inputs.extend(self.allnodes) + + if getattr(self, 'scan', None): + cls.scan = self.scan + + if getattr(self, 'install_path', None): + tsk.install_path = self.install_path + + if getattr(self, 'cwd', None): + tsk.cwd = self.cwd + + if getattr(self, 'on_results', None): + Task.update_outputs(cls) + + if getattr(self, 'always', None): + Task.always_run(cls) + + for x in ['after', 'before', 'ext_in', 'ext_out']: + setattr(cls, x, getattr(self, x, [])) +feature('*')(exec_rule) +before('apply_core')(exec_rule) + +def sequence_order(self): + """ + add a strict sequential constraint between the tasks generated by task generators + it uses the fact that task generators are posted in order + it will not post objects which belong to other folders + there is also an awesome trick for executing the method in last position + + to use: + bld(features='javac seq') + bld(features='jar seq') + + to start a new sequence, set the attribute seq_start, for example: + obj.seq_start = True + """ + if self.meths and self.meths[-1] != 'sequence_order': + self.meths.append('sequence_order') + return + + if getattr(self, 'seq_start', None): + return + + # all the tasks previously declared must be run before these + if getattr(self.bld, 'prev', None): + self.bld.prev.post() + for x in self.bld.prev.tasks: + for y in self.tasks: + y.set_run_after(x) + + self.bld.prev = self + +feature('seq')(sequence_order) + diff --git a/node-v0.8.14/tools/wafadmin/Tools/__init__.py b/node-v0.8.14/tools/wafadmin/Tools/__init__.py new file mode 100644 index 0000000..bc6ca23 --- /dev/null +++ b/node-v0.8.14/tools/wafadmin/Tools/__init__.py @@ -0,0 +1,4 @@ +#!/usr/bin/env python +# encoding: utf-8 +# Thomas Nagy, 2006 (ita) + diff --git a/node-v0.8.14/tools/wafadmin/Tools/ar.py b/node-v0.8.14/tools/wafadmin/Tools/ar.py new file mode 100644 index 0000000..af9b17f --- /dev/null +++ b/node-v0.8.14/tools/wafadmin/Tools/ar.py @@ -0,0 +1,36 @@ +#!/usr/bin/env python +# encoding: utf-8 +# Thomas Nagy, 2006-2008 (ita) +# Ralf Habacker, 2006 (rh) + +"ar and ranlib" + +import os, sys +import Task, Utils +from Configure import conftest + +ar_str = '${AR} ${ARFLAGS} ${AR_TGT_F}${TGT} ${AR_SRC_F}${SRC}' +cls = Task.simple_task_type('static_link', ar_str, color='YELLOW', ext_in='.o', ext_out='.bin', shell=False) +cls.maxjobs = 1 +cls.install = Utils.nada + +# remove the output in case it already exists +old = cls.run +def wrap(self): + try: os.remove(self.outputs[0].abspath(self.env)) + except OSError: pass + return old(self) +setattr(cls, 'run', wrap) + +def detect(conf): + conf.find_program('ar', var='AR') + conf.find_program('ranlib', var='RANLIB') + conf.env.ARFLAGS = 'rcs' + +@conftest +def find_ar(conf): + v = conf.env + conf.check_tool('ar') + if not v['AR']: conf.fatal('ar is required for static libraries - not found') + + diff --git a/node-v0.8.14/tools/wafadmin/Tools/cc.py b/node-v0.8.14/tools/wafadmin/Tools/cc.py new file mode 100644 index 0000000..59edae4 --- /dev/null +++ b/node-v0.8.14/tools/wafadmin/Tools/cc.py @@ -0,0 +1,100 @@ +#!/usr/bin/env python +# encoding: utf-8 +# Thomas Nagy, 2006 (ita) + +"Base for c programs/libraries" + +import os +import TaskGen, Build, Utils, Task +from Logs import debug +import ccroot +from TaskGen import feature, before, extension, after + +g_cc_flag_vars = [ +'CCDEPS', 'FRAMEWORK', 'FRAMEWORKPATH', +'STATICLIB', 'LIB', 'LIBPATH', 'LINKFLAGS', 'RPATH', +'CCFLAGS', 'CPPPATH', 'CPPFLAGS', 'CCDEFINES'] + +EXT_CC = ['.c'] + +g_cc_type_vars = ['CCFLAGS', 'LINKFLAGS'] + +# TODO remove in waf 1.6 +class cc_taskgen(ccroot.ccroot_abstract): + pass + +@feature('cc') +@before('apply_type_vars') +@after('default_cc') +def init_cc(self): + self.p_flag_vars = set(self.p_flag_vars).union(g_cc_flag_vars) + self.p_type_vars = set(self.p_type_vars).union(g_cc_type_vars) + + if not self.env['CC_NAME']: + raise Utils.WafError("At least one compiler (gcc, ..) must be selected") + +@feature('cc') +@after('apply_incpaths') +def apply_obj_vars_cc(self): + """after apply_incpaths for INC_PATHS""" + env = self.env + app = env.append_unique + cpppath_st = env['CPPPATH_ST'] + + # local flags come first + # set the user-defined includes paths + for i in env['INC_PATHS']: + app('_CCINCFLAGS', cpppath_st % i.bldpath(env)) + app('_CCINCFLAGS', cpppath_st % i.srcpath(env)) + + # set the library include paths + for i in env['CPPPATH']: + app('_CCINCFLAGS', cpppath_st % i) + +@feature('cc') +@after('apply_lib_vars') +def apply_defines_cc(self): + """after uselib is set for CCDEFINES""" + self.defines = getattr(self, 'defines', []) + lst = self.to_list(self.defines) + self.to_list(self.env['CCDEFINES']) + milst = [] + + # now process the local defines + for defi in lst: + if not defi in milst: + milst.append(defi) + + # CCDEFINES_ + libs = self.to_list(self.uselib) + for l in libs: + val = self.env['CCDEFINES_'+l] + if val: milst += val + self.env['DEFLINES'] = ["%s %s" % (x[0], Utils.trimquotes('='.join(x[1:]))) for x in [y.split('=') for y in milst]] + y = self.env['CCDEFINES_ST'] + self.env['_CCDEFFLAGS'] = [y%x for x in milst] + +@extension(EXT_CC) +def c_hook(self, node): + # create the compilation task: cpp or cc + if getattr(self, 'obj_ext', None): + obj_ext = self.obj_ext + else: + obj_ext = '_%d.o' % self.idx + + task = self.create_task('cc', node, node.change_ext(obj_ext)) + try: + self.compiled_tasks.append(task) + except AttributeError: + raise Utils.WafError('Have you forgotten to set the feature "cc" on %s?' % str(self)) + return task + +cc_str = '${CC} ${CCFLAGS} ${CPPFLAGS} ${_CCINCFLAGS} ${_CCDEFFLAGS} ${CC_SRC_F}${SRC} ${CC_TGT_F}${TGT}' +cls = Task.simple_task_type('cc', cc_str, 'GREEN', ext_out='.o', ext_in='.c', shell=False) +cls.scan = ccroot.scan +cls.vars.append('CCDEPS') + +link_str = '${LINK_CC} ${CCLNK_SRC_F}${SRC} ${CCLNK_TGT_F}${TGT[0].abspath(env)} ${LINKFLAGS}' +cls = Task.simple_task_type('cc_link', link_str, color='YELLOW', ext_in='.o', ext_out='.bin', shell=False) +cls.maxjobs = 1 +cls.install = Utils.nada + diff --git a/node-v0.8.14/tools/wafadmin/Tools/ccroot.py b/node-v0.8.14/tools/wafadmin/Tools/ccroot.py new file mode 100644 index 0000000..5e7fcf3 --- /dev/null +++ b/node-v0.8.14/tools/wafadmin/Tools/ccroot.py @@ -0,0 +1,625 @@ +#!/usr/bin/env python +# encoding: utf-8 +# Thomas Nagy, 2005-2008 (ita) + +"base for all c/c++ programs and libraries" + +import os, sys, re +import TaskGen, Task, Utils, preproc, Logs, Build, Options +from Logs import error, debug, warn +from Utils import md5 +from TaskGen import taskgen, after, before, feature +from Constants import * +from Configure import conftest +try: + from cStringIO import StringIO +except ImportError: + from io import StringIO + +import config_c # <- necessary for the configuration, do not touch + +USE_TOP_LEVEL = False + +def get_cc_version(conf, cc, gcc=False, icc=False): + + cmd = cc + ['-dM', '-E', '-'] + try: + p = Utils.pproc.Popen(cmd, stdin=Utils.pproc.PIPE, stdout=Utils.pproc.PIPE, stderr=Utils.pproc.PIPE) + p.stdin.write('\n') + out = p.communicate()[0] + except: + conf.fatal('could not determine the compiler version %r' % cmd) + + # PY3K: do not touch + out = str(out) + + if gcc: + if out.find('__INTEL_COMPILER') >= 0: + conf.fatal('The intel compiler pretends to be gcc') + if out.find('__GNUC__') < 0: + conf.fatal('Could not determine the compiler type') + + if icc and out.find('__INTEL_COMPILER') < 0: + conf.fatal('Not icc/icpc') + + k = {} + if icc or gcc: + out = out.split('\n') + import shlex + + for line in out: + lst = shlex.split(line) + if len(lst)>2: + key = lst[1] + val = lst[2] + k[key] = val + + def isD(var): + return var in k + + def isT(var): + return var in k and k[var] != '0' + + # Some documentation is available at http://predef.sourceforge.net + # The names given to DEST_OS must match what Utils.unversioned_sys_platform() returns. + mp1 = { + '__linux__' : 'linux', + '__GNU__' : 'hurd', + '__FreeBSD__' : 'freebsd', + '__NetBSD__' : 'netbsd', + '__OpenBSD__' : 'openbsd', + '__sun' : 'sunos', + '__hpux' : 'hpux', + '__sgi' : 'irix', + '_AIX' : 'aix', + '__CYGWIN__' : 'cygwin', + '__MSYS__' : 'msys', + '_UWIN' : 'uwin', + '_WIN64' : 'win32', + '_WIN32' : 'win32', + } + + for i in mp1: + if isD(i): + conf.env.DEST_OS = mp1[i] + break + else: + if isD('__APPLE__') and isD('__MACH__'): + conf.env.DEST_OS = 'darwin' + elif isD('__unix__'): # unix must be tested last as it's a generic fallback + conf.env.DEST_OS = 'generic' + + if isD('__ELF__'): + conf.env.DEST_BINFMT = 'elf' + + mp2 = { + '__x86_64__' : 'x86_64', + '__i386__' : 'x86', + '__ia64__' : 'ia', + '__mips__' : 'mips', + '__sparc__' : 'sparc', + '__alpha__' : 'alpha', + '__arm__' : 'arm', + '__hppa__' : 'hppa', + '__powerpc__' : 'powerpc', + } + for i in mp2: + if isD(i): + conf.env.DEST_CPU = mp2[i] + break + + debug('ccroot: dest platform: ' + ' '.join([conf.env[x] or '?' for x in ('DEST_OS', 'DEST_BINFMT', 'DEST_CPU')])) + conf.env['CC_VERSION'] = (k['__GNUC__'], k['__GNUC_MINOR__'], k['__GNUC_PATCHLEVEL__']) + return k + +class DEBUG_LEVELS: + """Will disappear in waf 1.6""" + ULTRADEBUG = "ultradebug" + DEBUG = "debug" + RELEASE = "release" + OPTIMIZED = "optimized" + CUSTOM = "custom" + + ALL = [ULTRADEBUG, DEBUG, RELEASE, OPTIMIZED, CUSTOM] + +def scan(self): + "look for .h the .cpp need" + debug('ccroot: _scan_preprocessor(self, node, env, path_lst)') + + # TODO waf 1.6 - assume the default input has exactly one file + + if len(self.inputs) == 1: + node = self.inputs[0] + (nodes, names) = preproc.get_deps(node, self.env, nodepaths = self.env['INC_PATHS']) + if Logs.verbose: + debug('deps: deps for %s: %r; unresolved %r', str(node), nodes, names) + return (nodes, names) + + all_nodes = [] + all_names = [] + seen = set() + for node in self.inputs: + (nodes, names) = preproc.get_deps(node, self.env, nodepaths = self.env['INC_PATHS']) + if Logs.verbose: + debug('deps: deps for %s: %r; unresolved %r', str(node), nodes, names) + for x in nodes: + if id(x) in seen: continue + seen.add(id(x)) + all_nodes.append(x) + for x in names: + if not x in all_names: + all_names.append(x) + return (all_nodes, all_names) + +class ccroot_abstract(TaskGen.task_gen): + "Parent class for programs and libraries in languages c, c++ and moc (Qt)" + def __init__(self, *k, **kw): + # COMPAT remove in waf 1.6 TODO + if len(k) > 1: + k = list(k) + if k[1][0] != 'c': + k[1] = 'c' + k[1] + TaskGen.task_gen.__init__(self, *k, **kw) + +def get_target_name(self): + tp = 'program' + for x in self.features: + if x in ['cshlib', 'cstaticlib']: + tp = x.lstrip('c') + + pattern = self.env[tp + '_PATTERN'] + if not pattern: pattern = '%s' + + dir, name = os.path.split(self.target) + + if self.env.DEST_BINFMT == 'pe' and getattr(self, 'vnum', None) and 'cshlib' in self.features: + # include the version in the dll file name, + # the import lib file name stays unversionned. + name = name + '-' + self.vnum.split('.')[0] + + return os.path.join(dir, pattern % name) + +@feature('cc', 'cxx') +@before('apply_core') +def default_cc(self): + """compiled_tasks attribute must be set before the '.c->.o' tasks can be created""" + Utils.def_attrs(self, + includes = '', + defines= '', + rpaths = '', + uselib = '', + uselib_local = '', + add_objects = '', + p_flag_vars = [], + p_type_vars = [], + compiled_tasks = [], + link_task = None) + + # The only thing we need for cross-compilation is DEST_BINFMT. + # At some point, we may reach a case where DEST_BINFMT is not enough, but for now it's sufficient. + # Currently, cross-compilation is auto-detected only for the gnu and intel compilers. + if not self.env.DEST_BINFMT: + # Infer the binary format from the os name. + self.env.DEST_BINFMT = Utils.unversioned_sys_platform_to_binary_format( + self.env.DEST_OS or Utils.unversioned_sys_platform()) + + if not self.env.BINDIR: self.env.BINDIR = Utils.subst_vars('${PREFIX}/bin', self.env) + if not self.env.LIBDIR: self.env.LIBDIR = Utils.subst_vars('${PREFIX}/lib${LIB_EXT}', self.env) + +@feature('cprogram', 'dprogram', 'cstaticlib', 'dstaticlib', 'cshlib', 'dshlib') +def apply_verif(self): + """no particular order, used for diagnostic""" + if not (self.source or getattr(self, 'add_objects', None) or getattr(self, 'uselib_local', None) or getattr(self, 'obj_files', None)): + raise Utils.WafError('no source files specified for %s' % self) + if not self.target: + raise Utils.WafError('no target for %s' % self) + +# TODO reference the d programs, shlibs in d.py, not here + +@feature('cprogram', 'dprogram') +@after('default_cc') +@before('apply_core') +def vars_target_cprogram(self): + self.default_install_path = self.env.BINDIR + self.default_chmod = O755 + +@after('default_cc') +@feature('cshlib', 'dshlib') +@before('apply_core') +def vars_target_cshlib(self): + if self.env.DEST_BINFMT == 'pe': + # set execute bit on libs to avoid 'permission denied' (issue 283) + self.default_chmod = O755 + self.default_install_path = self.env.BINDIR + else: + self.default_install_path = self.env.LIBDIR + +@feature('cprogram', 'dprogram', 'cstaticlib', 'dstaticlib', 'cshlib', 'dshlib') +@after('apply_link', 'vars_target_cprogram', 'vars_target_cshlib') +def default_link_install(self): + """you may kill this method to inject your own installation for the first element + any other install should only process its own nodes and not those from the others""" + if self.install_path: + self.bld.install_files(self.install_path, self.link_task.outputs[0], env=self.env, chmod=self.chmod) + +@feature('cc', 'cxx') +@after('apply_type_vars', 'apply_lib_vars', 'apply_core') +def apply_incpaths(self): + """used by the scanner + after processing the uselib for CPPPATH + after apply_core because some processing may add include paths + """ + lst = [] + # TODO move the uselib processing out of here + for lib in self.to_list(self.uselib): + for path in self.env['CPPPATH_' + lib]: + if not path in lst: + lst.append(path) + if preproc.go_absolute: + for path in preproc.standard_includes: + if not path in lst: + lst.append(path) + + for path in self.to_list(self.includes): + if not path in lst: + if preproc.go_absolute or not os.path.isabs(path): + lst.append(path) + else: + self.env.prepend_value('CPPPATH', path) + + for path in lst: + node = None + if os.path.isabs(path): + if preproc.go_absolute: + node = self.bld.root.find_dir(path) + elif path[0] == '#': + node = self.bld.srcnode + if len(path) > 1: + node = node.find_dir(path[1:]) + else: + node = self.path.find_dir(path) + + if node: + self.env.append_value('INC_PATHS', node) + + # TODO WAF 1.6 + if USE_TOP_LEVEL: + self.env.append_value('INC_PATHS', self.bld.srcnode) + +@feature('cc', 'cxx') +@after('init_cc', 'init_cxx') +@before('apply_lib_vars') +def apply_type_vars(self): + """before apply_lib_vars because we modify uselib + after init_cc and init_cxx because web need p_type_vars + """ + for x in self.features: + if not x in ['cprogram', 'cstaticlib', 'cshlib']: + continue + x = x.lstrip('c') + + # if the type defines uselib to add, add them + st = self.env[x + '_USELIB'] + if st: self.uselib = self.uselib + ' ' + st + + # each compiler defines variables like 'shlib_CXXFLAGS', 'shlib_LINKFLAGS', etc + # so when we make a task generator of the type shlib, CXXFLAGS are modified accordingly + for var in self.p_type_vars: + compvar = '%s_%s' % (x, var) + #print compvar + value = self.env[compvar] + if value: self.env.append_value(var, value) + +@feature('cprogram', 'cshlib', 'cstaticlib') +@after('apply_core') +def apply_link(self): + """executes after apply_core for collecting 'compiled_tasks' + use a custom linker if specified (self.link='name-of-custom-link-task')""" + link = getattr(self, 'link', None) + if not link: + if 'cstaticlib' in self.features: link = 'static_link' + elif 'cxx' in self.features: link = 'cxx_link' + else: link = 'cc_link' + + tsk = self.create_task(link) + outputs = [t.outputs[0] for t in self.compiled_tasks] + tsk.set_inputs(outputs) + tsk.set_outputs(self.path.find_or_declare(get_target_name(self))) + + self.link_task = tsk + +@feature('cc', 'cxx') +@after('apply_link', 'init_cc', 'init_cxx', 'apply_core') +def apply_lib_vars(self): + """after apply_link because of 'link_task' + after default_cc because of the attribute 'uselib'""" + + # after 'apply_core' in case if 'cc' if there is no link + + env = self.env + + # 1. the case of the libs defined in the project (visit ancestors first) + # the ancestors external libraries (uselib) will be prepended + self.uselib = self.to_list(self.uselib) + names = self.to_list(self.uselib_local) + + seen = set([]) + tmp = Utils.deque(names) # consume a copy of the list of names + while tmp: + lib_name = tmp.popleft() + # visit dependencies only once + if lib_name in seen: + continue + + y = self.name_to_obj(lib_name) + if not y: + raise Utils.WafError('object %r was not found in uselib_local (required by %r)' % (lib_name, self.name)) + y.post() + seen.add(lib_name) + + # object has ancestors to process (shared libraries): add them to the end of the list + if getattr(y, 'uselib_local', None): + lst = y.to_list(y.uselib_local) + if 'cshlib' in y.features or 'cprogram' in y.features: + lst = [x for x in lst if not 'cstaticlib' in self.name_to_obj(x).features] + tmp.extend(lst) + + # link task and flags + if getattr(y, 'link_task', None): + + link_name = y.target[y.target.rfind(os.sep) + 1:] + if 'cstaticlib' in y.features: + env.append_value('STATICLIB', link_name) + elif 'cshlib' in y.features or 'cprogram' in y.features: + # WARNING some linkers can link against programs + env.append_value('LIB', link_name) + + # the order + self.link_task.set_run_after(y.link_task) + + # for the recompilation + dep_nodes = getattr(self.link_task, 'dep_nodes', []) + self.link_task.dep_nodes = dep_nodes + y.link_task.outputs + + # add the link path too + tmp_path = y.link_task.outputs[0].parent.bldpath(self.env) + if not tmp_path in env['LIBPATH']: env.prepend_value('LIBPATH', tmp_path) + + # add ancestors uselib too - but only propagate those that have no staticlib + for v in self.to_list(y.uselib): + if not env['STATICLIB_' + v]: + if not v in self.uselib: + self.uselib.insert(0, v) + + # if the library task generator provides 'export_incdirs', add to the include path + # the export_incdirs must be a list of paths relative to the other library + if getattr(y, 'export_incdirs', None): + for x in self.to_list(y.export_incdirs): + node = y.path.find_dir(x) + if not node: + raise Utils.WafError('object %r: invalid folder %r in export_incdirs' % (y.target, x)) + self.env.append_unique('INC_PATHS', node) + + # 2. the case of the libs defined outside + for x in self.uselib: + for v in self.p_flag_vars: + val = self.env[v + '_' + x] + if val: self.env.append_value(v, val) + +@feature('cprogram', 'cstaticlib', 'cshlib') +@after('init_cc', 'init_cxx', 'apply_link') +def apply_objdeps(self): + "add the .o files produced by some other object files in the same manner as uselib_local" + if not getattr(self, 'add_objects', None): return + + seen = [] + names = self.to_list(self.add_objects) + while names: + x = names[0] + + # visit dependencies only once + if x in seen: + names = names[1:] + continue + + # object does not exist ? + y = self.name_to_obj(x) + if not y: + raise Utils.WafError('object %r was not found in uselib_local (required by add_objects %r)' % (x, self.name)) + + # object has ancestors to process first ? update the list of names + if getattr(y, 'add_objects', None): + added = 0 + lst = y.to_list(y.add_objects) + lst.reverse() + for u in lst: + if u in seen: continue + added = 1 + names = [u]+names + if added: continue # list of names modified, loop + + # safe to process the current object + y.post() + seen.append(x) + + for t in y.compiled_tasks: + self.link_task.inputs.extend(t.outputs) + +@feature('cprogram', 'cshlib', 'cstaticlib') +@after('apply_lib_vars') +def apply_obj_vars(self): + """after apply_lib_vars for uselib""" + v = self.env + lib_st = v['LIB_ST'] + staticlib_st = v['STATICLIB_ST'] + libpath_st = v['LIBPATH_ST'] + staticlibpath_st = v['STATICLIBPATH_ST'] + rpath_st = v['RPATH_ST'] + + app = v.append_unique + + if v['FULLSTATIC']: + v.append_value('LINKFLAGS', v['FULLSTATIC_MARKER']) + + for i in v['RPATH']: + if i and rpath_st: + app('LINKFLAGS', rpath_st % i) + + for i in v['LIBPATH']: + app('LINKFLAGS', libpath_st % i) + app('LINKFLAGS', staticlibpath_st % i) + + if v['STATICLIB']: + v.append_value('LINKFLAGS', v['STATICLIB_MARKER']) + k = [(staticlib_st % i) for i in v['STATICLIB']] + app('LINKFLAGS', k) + + # fully static binaries ? + if not v['FULLSTATIC']: + if v['STATICLIB'] or v['LIB']: + v.append_value('LINKFLAGS', v['SHLIB_MARKER']) + + app('LINKFLAGS', [lib_st % i for i in v['LIB']]) + +@after('apply_link') +def process_obj_files(self): + if not hasattr(self, 'obj_files'): return + for x in self.obj_files: + node = self.path.find_resource(x) + self.link_task.inputs.append(node) + +@taskgen +def add_obj_file(self, file): + """Small example on how to link object files as if they were source + obj = bld.create_obj('cc') + obj.add_obj_file('foo.o')""" + if not hasattr(self, 'obj_files'): self.obj_files = [] + if not 'process_obj_files' in self.meths: self.meths.append('process_obj_files') + self.obj_files.append(file) + +c_attrs = { +'cxxflag' : 'CXXFLAGS', +'cflag' : 'CCFLAGS', +'ccflag' : 'CCFLAGS', +'linkflag' : 'LINKFLAGS', +'ldflag' : 'LINKFLAGS', +'lib' : 'LIB', +'libpath' : 'LIBPATH', +'staticlib': 'STATICLIB', +'staticlibpath': 'STATICLIBPATH', +'rpath' : 'RPATH', +'framework' : 'FRAMEWORK', +'frameworkpath' : 'FRAMEWORKPATH' +} + +@feature('cc', 'cxx') +@before('init_cxx', 'init_cc') +@before('apply_lib_vars', 'apply_obj_vars', 'apply_incpaths', 'init_cc') +def add_extra_flags(self): + """case and plural insensitive + before apply_obj_vars for processing the library attributes + """ + for x in self.__dict__.keys(): + y = x.lower() + if y[-1] == 's': + y = y[:-1] + if c_attrs.get(y, None): + self.env.append_unique(c_attrs[y], getattr(self, x)) + +# ============ the code above must not know anything about import libs ========== + +@feature('cshlib') +@after('apply_link', 'default_cc') +@before('apply_lib_vars', 'apply_objdeps', 'default_link_install') +def apply_implib(self): + """On mswindows, handle dlls and their import libs + the .dll.a is the import lib and it is required for linking so it is installed too + """ + if not self.env.DEST_BINFMT == 'pe': + return + + self.meths.remove('default_link_install') + + bindir = self.install_path + if not bindir: return + + # install the dll in the bin dir + dll = self.link_task.outputs[0] + self.bld.install_files(bindir, dll, self.env, self.chmod) + + # add linker flags to generate the import lib + implib = self.env['implib_PATTERN'] % os.path.split(self.target)[1] + + implib = dll.parent.find_or_declare(implib) + self.link_task.outputs.append(implib) + self.bld.install_as('${LIBDIR}/%s' % implib.name, implib, self.env) + + self.env.append_value('LINKFLAGS', (self.env['IMPLIB_ST'] % implib.bldpath(self.env)).split()) + +# ============ the code above must not know anything about vnum processing on unix platforms ========= + +@feature('cshlib') +@after('apply_link') +@before('apply_lib_vars', 'default_link_install') +def apply_vnum(self): + """ + libfoo.so is installed as libfoo.so.1.2.3 + """ + if not getattr(self, 'vnum', '') or not 'cshlib' in self.features or os.name != 'posix' or self.env.DEST_BINFMT not in ('elf', 'mac-o'): + return + + self.meths.remove('default_link_install') + + link = self.link_task + nums = self.vnum.split('.') + node = link.outputs[0] + + libname = node.name + if libname.endswith('.dylib'): + name3 = libname.replace('.dylib', '.%s.dylib' % self.vnum) + name2 = libname.replace('.dylib', '.%s.dylib' % nums[0]) + else: + name3 = libname + '.' + self.vnum + name2 = libname + '.' + nums[0] + + if self.env.SONAME_ST: + v = self.env.SONAME_ST % name2 + self.env.append_value('LINKFLAGS', v.split()) + + bld = self.bld + nums = self.vnum.split('.') + + path = self.install_path + if not path: return + + bld.install_as(path + os.sep + name3, node, env=self.env) + bld.symlink_as(path + os.sep + name2, name3) + bld.symlink_as(path + os.sep + libname, name3) + + # the following task is just to enable execution from the build dir :-/ + tsk = self.create_task('vnum') + tsk.set_inputs([node]) + tsk.set_outputs(node.parent.find_or_declare(name2)) + +def exec_vnum_link(self): + path = self.outputs[0].abspath(self.env) + try: + os.remove(path) + except OSError: + pass + + try: + os.symlink(self.inputs[0].name, path) + except OSError: + return 1 + +cls = Task.task_type_from_func('vnum', func=exec_vnum_link, ext_in='.bin', color='CYAN') +cls.quiet = 1 + +# ============ the --as-needed flag should added during the configuration, not at runtime ========= + +@conftest +def add_as_needed(conf): + if conf.env.DEST_BINFMT == 'elf' and 'gcc' in (conf.env.CXX_NAME, conf.env.CC_NAME): + conf.env.append_unique('LINKFLAGS', '--as-needed') + diff --git a/node-v0.8.14/tools/wafadmin/Tools/compiler_cc.py b/node-v0.8.14/tools/wafadmin/Tools/compiler_cc.py new file mode 100644 index 0000000..f3cb8cd --- /dev/null +++ b/node-v0.8.14/tools/wafadmin/Tools/compiler_cc.py @@ -0,0 +1,66 @@ +#!/usr/bin/env python +# encoding: utf-8 +# Matthias Jahn jahn dôt matthias ât freenet dôt de, 2007 (pmarat) + +import os, sys, imp, types, ccroot +import optparse +import Utils, Configure, Options +from Logs import debug + +c_compiler = { + 'win32': ['gcc'], + 'cygwin': ['gcc'], + 'darwin': ['gcc'], + 'aix': ['xlc', 'gcc'], + 'linux': ['gcc', 'icc', 'suncc'], + 'sunos': ['gcc', 'suncc'], + 'irix': ['gcc'], + 'hpux': ['gcc'], + 'default': ['gcc'] +} + +def __list_possible_compiler(platform): + try: + return c_compiler[platform] + except KeyError: + return c_compiler["default"] + +def detect(conf): + """ + for each compiler for the platform, try to configure the compiler + in theory the tools should raise a configuration error if the compiler + pretends to be something it is not (setting CC=icc and trying to configure gcc) + """ + try: test_for_compiler = Options.options.check_c_compiler + except AttributeError: conf.fatal("Add set_options(opt): opt.tool_options('compiler_cc')") + orig = conf.env + for compiler in test_for_compiler.split(): + conf.env = orig.copy() + try: + conf.check_tool(compiler) + except Configure.ConfigurationError, e: + debug('compiler_cc: %r' % e) + else: + if conf.env['CC']: + orig.table = conf.env.get_merged_dict() + conf.env = orig + conf.check_message(compiler, '', True) + conf.env['COMPILER_CC'] = compiler + break + conf.check_message(compiler, '', False) + break + else: + conf.fatal('could not configure a c compiler!') + +def set_options(opt): + build_platform = Utils.unversioned_sys_platform() + possible_compiler_list = __list_possible_compiler(build_platform) + test_for_compiler = ' '.join(possible_compiler_list) + cc_compiler_opts = opt.add_option_group("C Compiler Options") + cc_compiler_opts.add_option('--check-c-compiler', default="%s" % test_for_compiler, + help='On this platform (%s) the following C-Compiler will be checked by default: "%s"' % (build_platform, test_for_compiler), + dest="check_c_compiler") + + for c_compiler in test_for_compiler.split(): + opt.tool_options('%s' % c_compiler, option_group=cc_compiler_opts) + diff --git a/node-v0.8.14/tools/wafadmin/Tools/compiler_cxx.py b/node-v0.8.14/tools/wafadmin/Tools/compiler_cxx.py new file mode 100644 index 0000000..6cad191 --- /dev/null +++ b/node-v0.8.14/tools/wafadmin/Tools/compiler_cxx.py @@ -0,0 +1,61 @@ +#!/usr/bin/env python +# encoding: utf-8 +# Matthias Jahn jahn dôt matthias ât freenet dôt de 2007 (pmarat) + +import os, sys, imp, types, ccroot +import optparse +import Utils, Configure, Options +from Logs import debug + +cxx_compiler = { +'win32': ['g++'], +'cygwin': ['g++'], +'darwin': ['g++'], +'aix': ['xlc++', 'g++'], +'linux': ['g++', 'icpc', 'sunc++'], +'sunos': ['g++', 'sunc++'], +'irix': ['g++'], +'hpux': ['g++'], +'default': ['g++'] +} + +def __list_possible_compiler(platform): + try: + return cxx_compiler[platform] + except KeyError: + return cxx_compiler["default"] + +def detect(conf): + try: test_for_compiler = Options.options.check_cxx_compiler + except AttributeError: raise Configure.ConfigurationError("Add set_options(opt): opt.tool_options('compiler_cxx')") + orig = conf.env + for compiler in test_for_compiler.split(): + try: + conf.env = orig.copy() + conf.check_tool(compiler) + except Configure.ConfigurationError, e: + debug('compiler_cxx: %r' % e) + else: + if conf.env['CXX']: + orig.table = conf.env.get_merged_dict() + conf.env = orig + conf.check_message(compiler, '', True) + conf.env['COMPILER_CXX'] = compiler + break + conf.check_message(compiler, '', False) + break + else: + conf.fatal('could not configure a cxx compiler!') + +def set_options(opt): + build_platform = Utils.unversioned_sys_platform() + possible_compiler_list = __list_possible_compiler(build_platform) + test_for_compiler = ' '.join(possible_compiler_list) + cxx_compiler_opts = opt.add_option_group('C++ Compiler Options') + cxx_compiler_opts.add_option('--check-cxx-compiler', default="%s" % test_for_compiler, + help='On this platform (%s) the following C++ Compiler will be checked by default: "%s"' % (build_platform, test_for_compiler), + dest="check_cxx_compiler") + + for cxx_compiler in test_for_compiler.split(): + opt.tool_options('%s' % cxx_compiler, option_group=cxx_compiler_opts) + diff --git a/node-v0.8.14/tools/wafadmin/Tools/compiler_d.py b/node-v0.8.14/tools/wafadmin/Tools/compiler_d.py new file mode 100644 index 0000000..1ea5efa --- /dev/null +++ b/node-v0.8.14/tools/wafadmin/Tools/compiler_d.py @@ -0,0 +1,33 @@ +#!/usr/bin/env python +# encoding: utf-8 +# Carlos Rafael Giani, 2007 (dv) + +import os, sys, imp, types +import Utils, Configure, Options + +def detect(conf): + if getattr(Options.options, 'check_dmd_first', None): + test_for_compiler = ['dmd', 'gdc'] + else: + test_for_compiler = ['gdc', 'dmd'] + + for d_compiler in test_for_compiler: + try: + conf.check_tool(d_compiler) + except: + pass + else: + break + else: + conf.fatal('no suitable d compiler was found') + +def set_options(opt): + d_compiler_opts = opt.add_option_group('D Compiler Options') + d_compiler_opts.add_option('--check-dmd-first', action='store_true', + help='checks for the gdc compiler before dmd (default is the other way round)', + dest='check_dmd_first', + default=False) + + for d_compiler in ['gdc', 'dmd']: + opt.tool_options('%s' % d_compiler, option_group=d_compiler_opts) + diff --git a/node-v0.8.14/tools/wafadmin/Tools/config_c.py b/node-v0.8.14/tools/wafadmin/Tools/config_c.py new file mode 100644 index 0000000..21729d4 --- /dev/null +++ b/node-v0.8.14/tools/wafadmin/Tools/config_c.py @@ -0,0 +1,729 @@ +#!/usr/bin/env python +# encoding: utf-8 +# Thomas Nagy, 2005-2008 (ita) + +""" +c/c++ configuration routines +""" + +import os, imp, sys, shlex, shutil +from Utils import md5 +import Build, Utils, Configure, Task, Options, Logs, TaskGen +from Constants import * +from Configure import conf, conftest + +cfg_ver = { + 'atleast-version': '>=', + 'exact-version': '==', + 'max-version': '<=', +} + +SNIP1 = ''' + int main() { + void *p; + p=(void*)(%s); + return 0; +} +''' + +SNIP2 = ''' +int main() { + if ((%(type_name)s *) 0) return 0; + if (sizeof (%(type_name)s)) return 0; +} +''' + +SNIP3 = ''' +int main() { + return 0; +} +''' + +def parse_flags(line, uselib, env): + """pkg-config still has bugs on some platforms, and there are many -config programs, parsing flags is necessary :-/""" + + lst = shlex.split(line) + while lst: + x = lst.pop(0) + st = x[:2] + ot = x[2:] + + if st == '-I' or st == '/I': + if not ot: ot = lst.pop(0) + env.append_unique('CPPPATH_' + uselib, ot) + elif st == '-D': + if not ot: ot = lst.pop(0) + env.append_unique('CXXDEFINES_' + uselib, ot) + env.append_unique('CCDEFINES_' + uselib, ot) + elif st == '-l': + if not ot: ot = lst.pop(0) + env.append_unique('LIB_' + uselib, ot) + elif st == '-L': + if not ot: ot = lst.pop(0) + env.append_unique('LIBPATH_' + uselib, ot) + elif x == '-pthread' or x.startswith('+'): + env.append_unique('CCFLAGS_' + uselib, x) + env.append_unique('CXXFLAGS_' + uselib, x) + env.append_unique('LINKFLAGS_' + uselib, x) + elif x == '-framework': + env.append_unique('FRAMEWORK_' + uselib, lst.pop(0)) + elif x.startswith('-F'): + env.append_unique('FRAMEWORKPATH_' + uselib, x[2:]) + elif x.startswith('-std'): + env.append_unique('CCFLAGS_' + uselib, x) + env.append_unique('LINKFLAGS_' + uselib, x) + elif x.startswith('-Wl'): + env.append_unique('LINKFLAGS_' + uselib, x) + elif x.startswith('-m') or x.startswith('-f'): + env.append_unique('CCFLAGS_' + uselib, x) + env.append_unique('CXXFLAGS_' + uselib, x) + +@conf +def ret_msg(self, f, kw): + """execute a function, when provided""" + if isinstance(f, str): + return f + return f(kw) + +@conf +def validate_cfg(self, kw): + if not 'path' in kw: + kw['path'] = 'pkg-config --errors-to-stdout --print-errors' + + # pkg-config version + if 'atleast_pkgconfig_version' in kw: + if not 'msg' in kw: + kw['msg'] = 'Checking for pkg-config version >= %s' % kw['atleast_pkgconfig_version'] + return + + # pkg-config --modversion + if 'modversion' in kw: + return + + if 'variables' in kw: + if not 'msg' in kw: + kw['msg'] = 'Checking for %s variables' % kw['package'] + return + + # checking for the version of a module, for the moment, one thing at a time + for x in cfg_ver.keys(): + y = x.replace('-', '_') + if y in kw: + if not 'package' in kw: + raise ValueError('%s requires a package' % x) + + if not 'msg' in kw: + kw['msg'] = 'Checking for %s %s %s' % (kw['package'], cfg_ver[x], kw[y]) + return + + if not 'msg' in kw: + kw['msg'] = 'Checking for %s' % (kw['package'] or kw['path']) + if not 'okmsg' in kw: + kw['okmsg'] = 'yes' + if not 'errmsg' in kw: + kw['errmsg'] = 'not found' + +@conf +def cmd_and_log(self, cmd, kw): + Logs.debug('runner: %s\n' % cmd) + if self.log: + self.log.write('%s\n' % cmd) + + try: + p = Utils.pproc.Popen(cmd, stdout=Utils.pproc.PIPE, stderr=Utils.pproc.PIPE, shell=True) + (out, err) = p.communicate() + except OSError, e: + self.log.write('error %r' % e) + self.fatal(str(e)) + + out = str(out) + err = str(err) + + if self.log: + self.log.write(out) + self.log.write(err) + + if p.returncode: + if not kw.get('errmsg', ''): + if kw.get('mandatory', False): + kw['errmsg'] = out.strip() + else: + kw['errmsg'] = 'no' + self.fatal('fail') + return out + +@conf +def exec_cfg(self, kw): + + # pkg-config version + if 'atleast_pkgconfig_version' in kw: + cmd = '%s --atleast-pkgconfig-version=%s' % (kw['path'], kw['atleast_pkgconfig_version']) + self.cmd_and_log(cmd, kw) + if not 'okmsg' in kw: + kw['okmsg'] = 'yes' + return + + # checking for the version of a module + for x in cfg_ver: + y = x.replace('-', '_') + if y in kw: + self.cmd_and_log('%s --%s=%s %s' % (kw['path'], x, kw[y], kw['package']), kw) + if not 'okmsg' in kw: + kw['okmsg'] = 'yes' + self.define(self.have_define(kw.get('uselib_store', kw['package'])), 1, 0) + break + + # retrieving the version of a module + if 'modversion' in kw: + version = self.cmd_and_log('%s --modversion %s' % (kw['path'], kw['modversion']), kw).strip() + self.define('%s_VERSION' % Utils.quote_define_name(kw.get('uselib_store', kw['modversion'])), version) + return version + + # retrieving variables of a module + if 'variables' in kw: + env = kw.get('env', self.env) + uselib = kw.get('uselib_store', kw['package'].upper()) + vars = Utils.to_list(kw['variables']) + for v in vars: + val = self.cmd_and_log('%s --variable=%s %s' % (kw['path'], v, kw['package']), kw).strip() + var = '%s_%s' % (uselib, v) + env[var] = val + if not 'okmsg' in kw: + kw['okmsg'] = 'yes' + return + + lst = [kw['path']] + for key, val in kw.get('define_variable', {}).iteritems(): + lst.append('--define-variable=%s=%s' % (key, val)) + + lst.append(kw.get('args', '')) + lst.append(kw['package']) + + # so we assume the command-line will output flags to be parsed afterwards + cmd = ' '.join(lst) + ret = self.cmd_and_log(cmd, kw) + if not 'okmsg' in kw: + kw['okmsg'] = 'yes' + + self.define(self.have_define(kw.get('uselib_store', kw['package'])), 1, 0) + parse_flags(ret, kw.get('uselib_store', kw['package'].upper()), kw.get('env', self.env)) + return ret + +@conf +def check_cfg(self, *k, **kw): + """ + for pkg-config mostly, but also all the -config tools + conf.check_cfg(path='mpicc', args='--showme:compile --showme:link', package='', uselib_store='OPEN_MPI') + conf.check_cfg(package='dbus-1', variables='system_bus_default_address session_bus_services_dir') + """ + + self.validate_cfg(kw) + if 'msg' in kw: + self.check_message_1(kw['msg']) + ret = None + try: + ret = self.exec_cfg(kw) + except Configure.ConfigurationError, e: + if 'errmsg' in kw: + self.check_message_2(kw['errmsg'], 'YELLOW') + if 'mandatory' in kw and kw['mandatory']: + if Logs.verbose > 1: + raise + else: + self.fatal('the configuration failed (see %r)' % self.log.name) + else: + kw['success'] = ret + if 'okmsg' in kw: + self.check_message_2(self.ret_msg(kw['okmsg'], kw)) + + return ret + +# the idea is the following: now that we are certain +# that all the code here is only for c or c++, it is +# easy to put all the logic in one function +# +# this should prevent code duplication (ita) + +# env: an optional environment (modified -> provide a copy) +# compiler: cc or cxx - it tries to guess what is best +# type: cprogram, cshlib, cstaticlib +# code: a c code to execute +# uselib_store: where to add the variables +# uselib: parameters to use for building +# define: define to set, like FOO in #define FOO, if not set, add /* #undef FOO */ +# execute: True or False - will return the result of the execution + +@conf +def validate_c(self, kw): + """validate the parameters for the test method""" + + if not 'env' in kw: + kw['env'] = self.env.copy() + + env = kw['env'] + if not 'compiler' in kw: + kw['compiler'] = 'cc' + if env['CXX_NAME'] and Task.TaskBase.classes.get('cxx', None): + kw['compiler'] = 'cxx' + if not self.env['CXX']: + self.fatal('a c++ compiler is required') + else: + if not self.env['CC']: + self.fatal('a c compiler is required') + + if not 'type' in kw: + kw['type'] = 'cprogram' + + assert not(kw['type'] != 'cprogram' and kw.get('execute', 0)), 'can only execute programs' + + + #if kw['type'] != 'program' and kw.get('execute', 0): + # raise ValueError, 'can only execute programs' + + def to_header(dct): + if 'header_name' in dct: + dct = Utils.to_list(dct['header_name']) + return ''.join(['#include <%s>\n' % x for x in dct]) + return '' + + # set the file name + if not 'compile_mode' in kw: + kw['compile_mode'] = (kw['compiler'] == 'cxx') and 'cxx' or 'cc' + + if not 'compile_filename' in kw: + kw['compile_filename'] = 'test.c' + ((kw['compile_mode'] == 'cxx') and 'pp' or '') + + #OSX + if 'framework_name' in kw: + try: TaskGen.task_gen.create_task_macapp + except AttributeError: self.fatal('frameworks require the osx tool') + + fwkname = kw['framework_name'] + if not 'uselib_store' in kw: + kw['uselib_store'] = fwkname.upper() + + if not kw.get('no_header', False): + if not 'header_name' in kw: + kw['header_name'] = [] + fwk = '%s/%s.h' % (fwkname, fwkname) + if kw.get('remove_dot_h', None): + fwk = fwk[:-2] + kw['header_name'] = Utils.to_list(kw['header_name']) + [fwk] + + kw['msg'] = 'Checking for framework %s' % fwkname + kw['framework'] = fwkname + #kw['frameworkpath'] = set it yourself + + if 'function_name' in kw: + fu = kw['function_name'] + if not 'msg' in kw: + kw['msg'] = 'Checking for function %s' % fu + kw['code'] = to_header(kw) + SNIP1 % fu + if not 'uselib_store' in kw: + kw['uselib_store'] = fu.upper() + if not 'define_name' in kw: + kw['define_name'] = self.have_define(fu) + + elif 'type_name' in kw: + tu = kw['type_name'] + if not 'msg' in kw: + kw['msg'] = 'Checking for type %s' % tu + if not 'header_name' in kw: + kw['header_name'] = 'stdint.h' + kw['code'] = to_header(kw) + SNIP2 % {'type_name' : tu} + if not 'define_name' in kw: + kw['define_name'] = self.have_define(tu.upper()) + + elif 'header_name' in kw: + if not 'msg' in kw: + kw['msg'] = 'Checking for header %s' % kw['header_name'] + + l = Utils.to_list(kw['header_name']) + assert len(l)>0, 'list of headers in header_name is empty' + + kw['code'] = to_header(kw) + SNIP3 + + if not 'uselib_store' in kw: + kw['uselib_store'] = l[0].upper() + + if not 'define_name' in kw: + kw['define_name'] = self.have_define(l[0]) + + if 'lib' in kw: + if not 'msg' in kw: + kw['msg'] = 'Checking for library %s' % kw['lib'] + if not 'uselib_store' in kw: + kw['uselib_store'] = kw['lib'].upper() + + if 'staticlib' in kw: + if not 'msg' in kw: + kw['msg'] = 'Checking for static library %s' % kw['staticlib'] + if not 'uselib_store' in kw: + kw['uselib_store'] = kw['staticlib'].upper() + + if 'fragment' in kw: + # an additional code fragment may be provided to replace the predefined code + # in custom headers + kw['code'] = kw['fragment'] + if not 'msg' in kw: + kw['msg'] = 'Checking for custom code' + if not 'errmsg' in kw: + kw['errmsg'] = 'no' + + for (flagsname,flagstype) in [('cxxflags','compiler'), ('cflags','compiler'), ('linkflags','linker')]: + if flagsname in kw: + if not 'msg' in kw: + kw['msg'] = 'Checking for %s flags %s' % (flagstype, kw[flagsname]) + if not 'errmsg' in kw: + kw['errmsg'] = 'no' + + if not 'execute' in kw: + kw['execute'] = False + + if not 'errmsg' in kw: + kw['errmsg'] = 'not found' + + if not 'okmsg' in kw: + kw['okmsg'] = 'yes' + + if not 'code' in kw: + kw['code'] = SNIP3 + + if not kw.get('success'): kw['success'] = None + + assert 'msg' in kw, 'invalid parameters, read http://freehackers.org/~tnagy/wafbook/single.html#config_helpers_c' + +@conf +def post_check(self, *k, **kw): + "set the variables after a test was run successfully" + + is_success = False + if kw['execute']: + if kw['success']: + is_success = True + else: + is_success = (kw['success'] == 0) + + if 'define_name' in kw: + if 'header_name' in kw or 'function_name' in kw or 'type_name' in kw or 'fragment' in kw: + if kw['execute']: + key = kw['success'] + if isinstance(key, str): + if key: + self.define(kw['define_name'], key, quote=kw.get('quote', 1)) + else: + self.define_cond(kw['define_name'], True) + else: + self.define_cond(kw['define_name'], False) + else: + self.define_cond(kw['define_name'], is_success) + + if is_success and 'uselib_store' in kw: + import cc, cxx + for k in set(cc.g_cc_flag_vars).union(cxx.g_cxx_flag_vars): + lk = k.lower() + # inconsistency: includes -> CPPPATH + if k == 'CPPPATH': lk = 'includes' + if k == 'CXXDEFINES': lk = 'defines' + if k == 'CCDEFINES': lk = 'defines' + if lk in kw: + val = kw[lk] + # remove trailing slash + if isinstance(val, str): + val = val.rstrip(os.path.sep) + self.env.append_unique(k + '_' + kw['uselib_store'], val) + +@conf +def check(self, *k, **kw): + # so this will be the generic function + # it will be safer to use check_cxx or check_cc + self.validate_c(kw) + self.check_message_1(kw['msg']) + ret = None + try: + ret = self.run_c_code(*k, **kw) + except Configure.ConfigurationError, e: + self.check_message_2(kw['errmsg'], 'YELLOW') + if 'mandatory' in kw and kw['mandatory']: + if Logs.verbose > 1: + raise + else: + self.fatal('the configuration failed (see %r)' % self.log.name) + else: + kw['success'] = ret + self.check_message_2(self.ret_msg(kw['okmsg'], kw)) + + self.post_check(*k, **kw) + if not kw.get('execute', False): + return ret == 0 + return ret + +@conf +def run_c_code(self, *k, **kw): + test_f_name = kw['compile_filename'] + + k = 0 + while k < 10000: + # make certain to use a fresh folder - necessary for win32 + dir = os.path.join(self.blddir, '.conf_check_%d' % k) + + # if the folder already exists, remove it + try: + shutil.rmtree(dir) + except OSError: + pass + + try: + os.stat(dir) + except OSError: + break + + k += 1 + + try: + os.makedirs(dir) + except: + self.fatal('cannot create a configuration test folder %r' % dir) + + try: + os.stat(dir) + except: + self.fatal('cannot use the configuration test folder %r' % dir) + + bdir = os.path.join(dir, 'testbuild') + + if not os.path.exists(bdir): + os.makedirs(bdir) + + env = kw['env'] + + dest = open(os.path.join(dir, test_f_name), 'w') + dest.write(kw['code']) + dest.close() + + back = os.path.abspath('.') + + bld = Build.BuildContext() + bld.log = self.log + bld.all_envs.update(self.all_envs) + bld.all_envs['Release'] = env + bld.lst_variants = bld.all_envs.keys() + bld.load_dirs(dir, bdir) + + os.chdir(dir) + + bld.rescan(bld.srcnode) + + if not 'features' in kw: + # conf.check(features='cc cprogram pyext', ...) + kw['features'] = [kw['compile_mode'], kw['type']] # "cprogram cc" + + o = bld(features=kw['features'], source=test_f_name, target='testprog') + + for k, v in kw.iteritems(): + setattr(o, k, v) + + self.log.write("==>\n%s\n<==\n" % kw['code']) + + # compile the program + try: + bld.compile() + except Utils.WafError: + ret = Utils.ex_stack() + else: + ret = 0 + + # chdir before returning + os.chdir(back) + + if ret: + self.log.write('command returned %r' % ret) + self.fatal(str(ret)) + + # if we need to run the program, try to get its result + # keep the name of the program to execute + if kw['execute']: + lastprog = o.link_task.outputs[0].abspath(env) + + args = Utils.to_list(kw.get('exec_args', [])) + proc = Utils.pproc.Popen([lastprog] + args, stdout=Utils.pproc.PIPE, stderr=Utils.pproc.PIPE) + (out, err) = proc.communicate() + w = self.log.write + w(str(out)) + w('\n') + w(str(err)) + w('\n') + w('returncode %r' % proc.returncode) + w('\n') + if proc.returncode: + self.fatal(Utils.ex_stack()) + ret = out + + return ret + +@conf +def check_cxx(self, *k, **kw): + kw['compiler'] = 'cxx' + return self.check(*k, **kw) + +@conf +def check_cc(self, *k, **kw): + kw['compiler'] = 'cc' + return self.check(*k, **kw) + +@conf +def define(self, define, value, quote=1): + """store a single define and its state into an internal list for later + writing to a config header file. Value can only be + a string or int; other types not supported. String + values will appear properly quoted in the generated + header file.""" + assert define and isinstance(define, str) + + # ordered_dict is for writing the configuration header in order + tbl = self.env[DEFINES] or Utils.ordered_dict() + + # the user forgot to tell if the value is quoted or not + if isinstance(value, str): + if quote: + tbl[define] = '"%s"' % repr('"'+value)[2:-1].replace('"', '\\"') + else: + tbl[define] = value + elif isinstance(value, int): + tbl[define] = value + else: + raise TypeError('define %r -> %r must be a string or an int' % (define, value)) + + # add later to make reconfiguring faster + self.env[DEFINES] = tbl + self.env[define] = value # <- not certain this is necessary + +@conf +def undefine(self, define): + """store a single define and its state into an internal list + for later writing to a config header file""" + assert define and isinstance(define, str) + + tbl = self.env[DEFINES] or Utils.ordered_dict() + + value = UNDEFINED + tbl[define] = value + + # add later to make reconfiguring faster + self.env[DEFINES] = tbl + self.env[define] = value + +@conf +def define_cond(self, name, value): + """Conditionally define a name. + Formally equivalent to: if value: define(name, 1) else: undefine(name)""" + if value: + self.define(name, 1) + else: + self.undefine(name) + +@conf +def is_defined(self, key): + defines = self.env[DEFINES] + if not defines: + return False + try: + value = defines[key] + except KeyError: + return False + else: + return value != UNDEFINED + +@conf +def get_define(self, define): + "get the value of a previously stored define" + try: return self.env[DEFINES][define] + except KeyError: return None + +@conf +def have_define(self, name): + "prefix the define with 'HAVE_' and make sure it has valid characters." + return self.__dict__.get('HAVE_PAT', 'HAVE_%s') % Utils.quote_define_name(name) + +@conf +def write_config_header(self, configfile='', env='', guard='', top=False): + "save the defines into a file" + if not configfile: configfile = WAF_CONFIG_H + waf_guard = guard or '_%s_WAF' % Utils.quote_define_name(configfile) + + # configfile -> absolute path + # there is a good reason to concatenate first and to split afterwards + if not env: env = self.env + if top: + diff = '' + else: + diff = Utils.diff_path(self.srcdir, self.curdir) + full = os.sep.join([self.blddir, env.variant(), diff, configfile]) + full = os.path.normpath(full) + (dir, base) = os.path.split(full) + + try: os.makedirs(dir) + except: pass + + dest = open(full, 'w') + dest.write('/* Configuration header created by Waf - do not edit */\n') + dest.write('#ifndef %s\n#define %s\n\n' % (waf_guard, waf_guard)) + + dest.write(self.get_config_header()) + + # config files are not removed on "waf clean" + env.append_unique(CFG_FILES, os.path.join(diff, configfile)) + + dest.write('\n#endif /* %s */\n' % waf_guard) + dest.close() + +@conf +def get_config_header(self): + """Fill-in the contents of the config header. Override when you need to write your own config header.""" + config_header = [] + + tbl = self.env[DEFINES] or Utils.ordered_dict() + for key in tbl.allkeys: + value = tbl[key] + if value is None: + config_header.append('#define %s' % key) + elif value is UNDEFINED: + config_header.append('/* #undef %s */' % key) + else: + config_header.append('#define %s %s' % (key, value)) + return "\n".join(config_header) + +@conftest +def find_cpp(conf): + v = conf.env + cpp = None + if v['CPP']: cpp = v['CPP'] + elif 'CPP' in conf.environ: cpp = conf.environ['CPP'] + if not cpp: cpp = conf.find_program('cpp', var='CPP') + if not cpp: cpp = v['CC'] + if not cpp: cpp = v['CXX'] + v['CPP'] = cpp + +@conftest +def cc_add_flags(conf): + conf.add_os_flags('CFLAGS', 'CCFLAGS') + conf.add_os_flags('CPPFLAGS') + +@conftest +def cxx_add_flags(conf): + conf.add_os_flags('CXXFLAGS') + conf.add_os_flags('CPPFLAGS') + +@conftest +def link_add_flags(conf): + conf.add_os_flags('LINKFLAGS') + conf.add_os_flags('LDFLAGS', 'LINKFLAGS') + +@conftest +def cc_load_tools(conf): + conf.check_tool('cc') + +@conftest +def cxx_load_tools(conf): + conf.check_tool('cxx') + diff --git a/node-v0.8.14/tools/wafadmin/Tools/cxx.py b/node-v0.8.14/tools/wafadmin/Tools/cxx.py new file mode 100644 index 0000000..052bcef --- /dev/null +++ b/node-v0.8.14/tools/wafadmin/Tools/cxx.py @@ -0,0 +1,104 @@ +#!/usr/bin/env python +# encoding: utf-8 +# Thomas Nagy, 2005 (ita) + +"Base for c++ programs and libraries" + +import TaskGen, Task, Utils +from Logs import debug +import ccroot # <- do not remove +from TaskGen import feature, before, extension, after + +g_cxx_flag_vars = [ +'CXXDEPS', 'FRAMEWORK', 'FRAMEWORKPATH', +'STATICLIB', 'LIB', 'LIBPATH', 'LINKFLAGS', 'RPATH', +'CXXFLAGS', 'CCFLAGS', 'CPPPATH', 'CPPFLAGS', 'CXXDEFINES'] +"main cpp variables" + +EXT_CXX = ['.cpp', '.cc', '.cxx', '.C', '.c++'] + +g_cxx_type_vars=['CXXFLAGS', 'LINKFLAGS'] + +# TODO remove in waf 1.6 +class cxx_taskgen(ccroot.ccroot_abstract): + pass + +@feature('cxx') +@before('apply_type_vars') +@after('default_cc') +def init_cxx(self): + if not 'cc' in self.features: + self.mappings['.c'] = TaskGen.task_gen.mappings['.cxx'] + + self.p_flag_vars = set(self.p_flag_vars).union(g_cxx_flag_vars) + self.p_type_vars = set(self.p_type_vars).union(g_cxx_type_vars) + + if not self.env['CXX_NAME']: + raise Utils.WafError("At least one compiler (g++, ..) must be selected") + +@feature('cxx') +@after('apply_incpaths') +def apply_obj_vars_cxx(self): + """after apply_incpaths for INC_PATHS""" + env = self.env + app = env.append_unique + cxxpath_st = env['CPPPATH_ST'] + + # local flags come first + # set the user-defined includes paths + for i in env['INC_PATHS']: + app('_CXXINCFLAGS', cxxpath_st % i.bldpath(env)) + app('_CXXINCFLAGS', cxxpath_st % i.srcpath(env)) + + # set the library include paths + for i in env['CPPPATH']: + app('_CXXINCFLAGS', cxxpath_st % i) + +@feature('cxx') +@after('apply_lib_vars') +def apply_defines_cxx(self): + """after uselib is set for CXXDEFINES""" + self.defines = getattr(self, 'defines', []) + lst = self.to_list(self.defines) + self.to_list(self.env['CXXDEFINES']) + milst = [] + + # now process the local defines + for defi in lst: + if not defi in milst: + milst.append(defi) + + # CXXDEFINES_USELIB + libs = self.to_list(self.uselib) + for l in libs: + val = self.env['CXXDEFINES_'+l] + if val: milst += self.to_list(val) + + self.env['DEFLINES'] = ["%s %s" % (x[0], Utils.trimquotes('='.join(x[1:]))) for x in [y.split('=') for y in milst]] + y = self.env['CXXDEFINES_ST'] + self.env['_CXXDEFFLAGS'] = [y%x for x in milst] + +@extension(EXT_CXX) +def cxx_hook(self, node): + # create the compilation task: cpp or cc + if getattr(self, 'obj_ext', None): + obj_ext = self.obj_ext + else: + obj_ext = '_%d.o' % self.idx + + task = self.create_task('cxx', node, node.change_ext(obj_ext)) + try: + self.compiled_tasks.append(task) + except AttributeError: + raise Utils.WafError('Have you forgotten to set the feature "cxx" on %s?' % str(self)) + return task + +cxx_str = '${CXX} ${CXXFLAGS} ${CPPFLAGS} ${_CXXINCFLAGS} ${_CXXDEFFLAGS} ${CXX_SRC_F}${SRC} ${CXX_TGT_F}${TGT}' +cls = Task.simple_task_type('cxx', cxx_str, color='GREEN', ext_out='.o', ext_in='.cxx', shell=False) +cls.scan = ccroot.scan +cls.vars.append('CXXDEPS') + +link_str = '${LINK_CXX} ${CXXLNK_SRC_F}${SRC} ${CXXLNK_TGT_F}${TGT[0].abspath(env)} ${LINKFLAGS}' +cls = Task.simple_task_type('cxx_link', link_str, color='YELLOW', ext_in='.o', ext_out='.bin', shell=False) +cls.maxjobs = 1 +cls.install = Utils.nada + diff --git a/node-v0.8.14/tools/wafadmin/Tools/d.py b/node-v0.8.14/tools/wafadmin/Tools/d.py new file mode 100644 index 0000000..602f5af --- /dev/null +++ b/node-v0.8.14/tools/wafadmin/Tools/d.py @@ -0,0 +1,540 @@ +#!/usr/bin/env python +# encoding: utf-8 +# Carlos Rafael Giani, 2007 (dv) +# Thomas Nagy, 2007-2008 (ita) + +import os, sys, re, optparse +import ccroot # <- leave this +import TaskGen, Utils, Task, Configure, Logs, Build +from Logs import debug, error +from TaskGen import taskgen, feature, after, before, extension +from Configure import conftest + +EXT_D = ['.d', '.di', '.D'] +D_METHS = ['apply_core', 'apply_vnum', 'apply_objdeps'] # additional d methods + +def filter_comments(filename): + txt = Utils.readf(filename) + buf = [] + + i = 0 + max = len(txt) + while i < max: + c = txt[i] + # skip a string + if c == '"': + i += 1 + c = '' + while i < max: + p = c + c = txt[i] + i += 1 + if i == max: return buf + if c == '"': + cnt = 0 + while i < cnt and i < max: + #print "cntcnt = ", str(cnt), self.txt[self.i-2-cnt] + if txt[i-2-cnt] == '\\': cnt+=1 + else: break + #print "cnt is ", str(cnt) + if (cnt%2)==0: break + i += 1 + # skip a char + elif c == "'": + i += 1 + if i == max: return buf + c = txt[i] + if c == '\\': + i += 1 + if i == max: return buf + c = txt[i] + if c == 'x': + i += 2 # skip two chars + elif c == 'u': + i += 4 # skip unicode chars + i += 1 + if i == max: return buf + c = txt[i] + if c != '\'': error("uh-oh, invalid character") + + # skip a comment + elif c == '/': + if i == max: break + c = txt[i+1] + # eat /+ +/ comments + if c == '+': + i += 1 + nesting = 1 + prev = 0 + while i < max: + c = txt[i] + if c == '+': + prev = 1 + elif c == '/': + if prev: + nesting -= 1 + if nesting == 0: break + else: + if i < max: + i += 1 + c = txt[i] + if c == '+': + nesting += 1 + else: + return buf + else: + prev = 0 + i += 1 + # eat /* */ comments + elif c == '*': + i += 1 + while i < max: + c = txt[i] + if c == '*': + prev = 1 + elif c == '/': + if prev: break + else: + prev = 0 + i += 1 + # eat // comments + elif c == '/': + i += 1 + c = txt[i] + while i < max and c != '\n': + i += 1 + c = txt[i] + # a valid char, add it to the buffer + else: + buf.append(c) + i += 1 + return buf + +class d_parser(object): + def __init__(self, env, incpaths): + #self.code = '' + #self.module = '' + #self.imports = [] + + self.allnames = [] + + self.re_module = re.compile("module\s+([^;]+)") + self.re_import = re.compile("import\s+([^;]+)") + self.re_import_bindings = re.compile("([^:]+):(.*)") + self.re_import_alias = re.compile("[^=]+=(.+)") + + self.env = env + + self.nodes = [] + self.names = [] + + self.incpaths = incpaths + + def tryfind(self, filename): + found = 0 + for n in self.incpaths: + found = n.find_resource(filename.replace('.', '/') + '.d') + if found: + self.nodes.append(found) + self.waiting.append(found) + break + if not found: + if not filename in self.names: + self.names.append(filename) + + def get_strings(self, code): + #self.imports = [] + self.module = '' + lst = [] + + # get the module name (if present) + + mod_name = self.re_module.search(code) + if mod_name: + self.module = re.sub('\s+', '', mod_name.group(1)) # strip all whitespaces + + # go through the code, have a look at all import occurrences + + # first, lets look at anything beginning with "import" and ending with ";" + import_iterator = self.re_import.finditer(code) + if import_iterator: + for import_match in import_iterator: + import_match_str = re.sub('\s+', '', import_match.group(1)) # strip all whitespaces + + # does this end with an import bindings declaration? + # (import bindings always terminate the list of imports) + bindings_match = self.re_import_bindings.match(import_match_str) + if bindings_match: + import_match_str = bindings_match.group(1) + # if so, extract the part before the ":" (since the module declaration(s) is/are located there) + + # split the matching string into a bunch of strings, separated by a comma + matches = import_match_str.split(',') + + for match in matches: + alias_match = self.re_import_alias.match(match) + if alias_match: + # is this an alias declaration? (alias = module name) if so, extract the module name + match = alias_match.group(1) + + lst.append(match) + return lst + + def start(self, node): + self.waiting = [node] + # while the stack is not empty, add the dependencies + while self.waiting: + nd = self.waiting.pop(0) + self.iter(nd) + + def iter(self, node): + path = node.abspath(self.env) # obtain the absolute path + code = "".join(filter_comments(path)) # read the file and filter the comments + names = self.get_strings(code) # obtain the import strings + for x in names: + # optimization + if x in self.allnames: continue + self.allnames.append(x) + + # for each name, see if it is like a node or not + self.tryfind(x) + +def scan(self): + "look for .d/.di the .d source need" + env = self.env + gruik = d_parser(env, env['INC_PATHS']) + gruik.start(self.inputs[0]) + + if Logs.verbose: + debug('deps: nodes found for %s: %s %s' % (str(self.inputs[0]), str(gruik.nodes), str(gruik.names))) + #debug("deps found for %s: %s" % (str(node), str(gruik.deps)), 'deps') + return (gruik.nodes, gruik.names) + +def get_target_name(self): + "for d programs and libs" + v = self.env + tp = 'program' + for x in self.features: + if x in ['dshlib', 'dstaticlib']: + tp = x.lstrip('d') + return v['D_%s_PATTERN' % tp] % self.target + +d_params = { +'dflags': '', +'importpaths':'', +'libs':'', +'libpaths':'', +'generate_headers':False, +} + +@feature('d') +@before('apply_type_vars') +def init_d(self): + for x in d_params: + setattr(self, x, getattr(self, x, d_params[x])) + +class d_taskgen(TaskGen.task_gen): + def __init__(self, *k, **kw): + TaskGen.task_gen.__init__(self, *k, **kw) + + # COMPAT + if len(k) > 1: + self.features.append('d' + k[1]) + +# okay, we borrow a few methods from ccroot +TaskGen.bind_feature('d', D_METHS) + +@feature('d') +@before('apply_d_libs') +def init_d(self): + Utils.def_attrs(self, + dflags='', + importpaths='', + libs='', + libpaths='', + uselib='', + uselib_local='', + generate_headers=False, # set to true if you want .di files as well as .o + compiled_tasks=[], + add_objects=[], + link_task=None) + +@feature('d') +@after('apply_d_link', 'init_d') +@before('apply_vnum') +def apply_d_libs(self): + """after apply_link because of 'link_task' + after default_cc because of the attribute 'uselib'""" + env = self.env + + # 1. the case of the libs defined in the project (visit ancestors first) + # the ancestors external libraries (uselib) will be prepended + self.uselib = self.to_list(self.uselib) + names = self.to_list(self.uselib_local) + + seen = set([]) + tmp = Utils.deque(names) # consume a copy of the list of names + while tmp: + lib_name = tmp.popleft() + # visit dependencies only once + if lib_name in seen: + continue + + y = self.name_to_obj(lib_name) + if not y: + raise Utils.WafError('object %r was not found in uselib_local (required by %r)' % (lib_name, self.name)) + y.post() + seen.add(lib_name) + + # object has ancestors to process (shared libraries): add them to the end of the list + if getattr(y, 'uselib_local', None): + lst = y.to_list(y.uselib_local) + if 'dshlib' in y.features or 'dprogram' in y.features: + lst = [x for x in lst if not 'dstaticlib' in self.name_to_obj(x).features] + tmp.extend(lst) + + # link task and flags + if getattr(y, 'link_task', None): + + link_name = y.target[y.target.rfind(os.sep) + 1:] + if 'dstaticlib' in y.features or 'dshlib' in y.features: + env.append_unique('DLINKFLAGS', env.DLIB_ST % link_name) + env.append_unique('DLINKFLAGS', env.DLIBPATH_ST % y.link_task.outputs[0].parent.bldpath(env)) + + # the order + self.link_task.set_run_after(y.link_task) + + # for the recompilation + dep_nodes = getattr(self.link_task, 'dep_nodes', []) + self.link_task.dep_nodes = dep_nodes + y.link_task.outputs + + # add ancestors uselib too - but only propagate those that have no staticlib + for v in self.to_list(y.uselib): + if not v in self.uselib: + self.uselib.insert(0, v) + + # if the library task generator provides 'export_incdirs', add to the include path + # the export_incdirs must be a list of paths relative to the other library + if getattr(y, 'export_incdirs', None): + for x in self.to_list(y.export_incdirs): + node = y.path.find_dir(x) + if not node: + raise Utils.WafError('object %r: invalid folder %r in export_incdirs' % (y.target, x)) + self.env.append_unique('INC_PATHS', node) + +@feature('dprogram', 'dshlib', 'dstaticlib') +@after('apply_core') +def apply_d_link(self): + link = getattr(self, 'link', None) + if not link: + if 'dstaticlib' in self.features: link = 'static_link' + else: link = 'd_link' + + outputs = [t.outputs[0] for t in self.compiled_tasks] + self.link_task = self.create_task(link, outputs, self.path.find_or_declare(get_target_name(self))) + +@feature('d') +@after('apply_core') +def apply_d_vars(self): + env = self.env + dpath_st = env['DPATH_ST'] + lib_st = env['DLIB_ST'] + libpath_st = env['DLIBPATH_ST'] + + importpaths = self.to_list(self.importpaths) + libpaths = [] + libs = [] + uselib = self.to_list(self.uselib) + + for i in uselib: + if env['DFLAGS_' + i]: + env.append_unique('DFLAGS', env['DFLAGS_' + i]) + + for x in self.features: + if not x in ['dprogram', 'dstaticlib', 'dshlib']: + continue + x.lstrip('d') + d_shlib_dflags = env['D_' + x + '_DFLAGS'] + if d_shlib_dflags: + env.append_unique('DFLAGS', d_shlib_dflags) + + # add import paths + for i in uselib: + if env['DPATH_' + i]: + for entry in self.to_list(env['DPATH_' + i]): + if not entry in importpaths: + importpaths.append(entry) + + # now process the import paths + for path in importpaths: + if os.path.isabs(path): + env.append_unique('_DIMPORTFLAGS', dpath_st % path) + else: + node = self.path.find_dir(path) + self.env.append_unique('INC_PATHS', node) + env.append_unique('_DIMPORTFLAGS', dpath_st % node.srcpath(env)) + env.append_unique('_DIMPORTFLAGS', dpath_st % node.bldpath(env)) + + # add library paths + for i in uselib: + if env['LIBPATH_' + i]: + for entry in self.to_list(env['LIBPATH_' + i]): + if not entry in libpaths: + libpaths.append(entry) + libpaths = self.to_list(self.libpaths) + libpaths + + # now process the library paths + # apply same path manipulation as used with import paths + for path in libpaths: + if not os.path.isabs(path): + node = self.path.find_resource(path) + if not node: + raise Utils.WafError('could not find libpath %r from %r' % (path, self)) + path = node.abspath(self.env) + + env.append_unique('DLINKFLAGS', libpath_st % path) + + # add libraries + for i in uselib: + if env['LIB_' + i]: + for entry in self.to_list(env['LIB_' + i]): + if not entry in libs: + libs.append(entry) + libs.extend(self.to_list(self.libs)) + + # process user flags + for flag in self.to_list(self.dflags): + env.append_unique('DFLAGS', flag) + + # now process the libraries + for lib in libs: + env.append_unique('DLINKFLAGS', lib_st % lib) + + # add linker flags + for i in uselib: + dlinkflags = env['DLINKFLAGS_' + i] + if dlinkflags: + for linkflag in dlinkflags: + env.append_unique('DLINKFLAGS', linkflag) + +@feature('dshlib') +@after('apply_d_vars') +def add_shlib_d_flags(self): + for linkflag in self.env['D_shlib_LINKFLAGS']: + self.env.append_unique('DLINKFLAGS', linkflag) + +@extension(EXT_D) +def d_hook(self, node): + # create the compilation task: cpp or cc + task = self.create_task(self.generate_headers and 'd_with_header' or 'd') + try: obj_ext = self.obj_ext + except AttributeError: obj_ext = '_%d.o' % self.idx + + task.inputs = [node] + task.outputs = [node.change_ext(obj_ext)] + self.compiled_tasks.append(task) + + if self.generate_headers: + header_node = node.change_ext(self.env['DHEADER_ext']) + task.outputs += [header_node] + +d_str = '${D_COMPILER} ${DFLAGS} ${_DIMPORTFLAGS} ${D_SRC_F}${SRC} ${D_TGT_F}${TGT}' +d_with_header_str = '${D_COMPILER} ${DFLAGS} ${_DIMPORTFLAGS} \ +${D_HDR_F}${TGT[1].bldpath(env)} \ +${D_SRC_F}${SRC} \ +${D_TGT_F}${TGT[0].bldpath(env)}' +link_str = '${D_LINKER} ${DLNK_SRC_F}${SRC} ${DLNK_TGT_F}${TGT} ${DLINKFLAGS}' + +def override_exec(cls): + """stupid dmd wants -of stuck to the file name""" + old_exec = cls.exec_command + def exec_command(self, *k, **kw): + if isinstance(k[0], list): + lst = k[0] + for i in xrange(len(lst)): + if lst[i] == '-of': + del lst[i] + lst[i] = '-of' + lst[i] + break + return old_exec(self, *k, **kw) + cls.exec_command = exec_command + +cls = Task.simple_task_type('d', d_str, 'GREEN', before='static_link d_link', shell=False) +cls.scan = scan +override_exec(cls) + +cls = Task.simple_task_type('d_with_header', d_with_header_str, 'GREEN', before='static_link d_link', shell=False) +override_exec(cls) + +cls = Task.simple_task_type('d_link', link_str, color='YELLOW', shell=False) +override_exec(cls) + +# for feature request #104 +@taskgen +def generate_header(self, filename, install_path): + if not hasattr(self, 'header_lst'): self.header_lst = [] + self.meths.append('process_header') + self.header_lst.append([filename, install_path]) + +@before('apply_core') +def process_header(self): + env = self.env + for i in getattr(self, 'header_lst', []): + node = self.path.find_resource(i[0]) + + if not node: + raise Utils.WafError('file not found on d obj '+i[0]) + + task = self.create_task('d_header') + task.set_inputs(node) + task.set_outputs(node.change_ext('.di')) + +d_header_str = '${D_COMPILER} ${D_HEADER} ${SRC}' +Task.simple_task_type('d_header', d_header_str, color='BLUE', shell=False) + +@conftest +def d_platform_flags(conf): + v = conf.env + binfmt = v.DEST_BINFMT or Utils.unversioned_sys_platform_to_binary_format( + v.DEST_OS or Utils.unversioned_sys_platform()) + if binfmt == 'pe': + v['D_program_PATTERN'] = '%s.exe' + v['D_shlib_PATTERN'] = 'lib%s.dll' + v['D_staticlib_PATTERN'] = 'lib%s.a' + else: + v['D_program_PATTERN'] = '%s' + v['D_shlib_PATTERN'] = 'lib%s.so' + v['D_staticlib_PATTERN'] = 'lib%s.a' + +# quick test # +if __name__ == "__main__": + #Logs.verbose = 2 + + try: arg = sys.argv[1] + except IndexError: arg = "file.d" + + print("".join(filter_comments(arg))) + # TODO + paths = ['.'] + + #gruik = filter() + #gruik.start(arg) + + #code = "".join(gruik.buf) + + #print "we have found the following code" + #print code + + #print "now parsing" + #print "-------------------------------------------" + """ + parser_ = d_parser() + parser_.start(arg) + + print "module: %s" % parser_.module + print "imports: ", + for imp in parser_.imports: + print imp + " ", + print +""" + diff --git a/node-v0.8.14/tools/wafadmin/Tools/dmd.py b/node-v0.8.14/tools/wafadmin/Tools/dmd.py new file mode 100644 index 0000000..9c74908 --- /dev/null +++ b/node-v0.8.14/tools/wafadmin/Tools/dmd.py @@ -0,0 +1,64 @@ +#!/usr/bin/env python +# encoding: utf-8 +# Carlos Rafael Giani, 2007 (dv) +# Thomas Nagy, 2008 (ita) + +import sys +import Utils, ar +from Configure import conftest + +@conftest +def find_dmd(conf): + conf.find_program(['dmd', 'ldc'], var='D_COMPILER', mandatory=True) + +@conftest +def common_flags_ldc(conf): + v = conf.env + v['DFLAGS'] = ['-d-version=Posix'] + v['DLINKFLAGS'] = [] + v['D_shlib_DFLAGS'] = ['-relocation-model=pic'] + +@conftest +def common_flags_dmd(conf): + v = conf.env + + # _DFLAGS _DIMPORTFLAGS + + # Compiler is dmd so 'gdc' part will be ignored, just + # ensure key is there, so wscript can append flags to it + v['DFLAGS'] = ['-version=Posix'] + + v['D_SRC_F'] = '' + v['D_TGT_F'] = ['-c', '-of'] + v['DPATH_ST'] = '-I%s' # template for adding import paths + + # linker + v['D_LINKER'] = v['D_COMPILER'] + v['DLNK_SRC_F'] = '' + v['DLNK_TGT_F'] = '-of' + + v['DLIB_ST'] = '-L-l%s' # template for adding libs + v['DLIBPATH_ST'] = '-L-L%s' # template for adding libpaths + + # linker debug levels + v['DFLAGS_OPTIMIZED'] = ['-O'] + v['DFLAGS_DEBUG'] = ['-g', '-debug'] + v['DFLAGS_ULTRADEBUG'] = ['-g', '-debug'] + v['DLINKFLAGS'] = ['-quiet'] + + v['D_shlib_DFLAGS'] = ['-fPIC'] + v['D_shlib_LINKFLAGS'] = ['-L-shared'] + + v['DHEADER_ext'] = '.di' + v['D_HDR_F'] = ['-H', '-Hf'] + +def detect(conf): + conf.find_dmd() + conf.check_tool('ar') + conf.check_tool('d') + conf.common_flags_dmd() + conf.d_platform_flags() + + if conf.env.D_COMPILER.find('ldc') > -1: + conf.common_flags_ldc() + diff --git a/node-v0.8.14/tools/wafadmin/Tools/gas.py b/node-v0.8.14/tools/wafadmin/Tools/gas.py new file mode 100644 index 0000000..c983b0a --- /dev/null +++ b/node-v0.8.14/tools/wafadmin/Tools/gas.py @@ -0,0 +1,38 @@ +#!/usr/bin/env python +# encoding: utf-8 +# Thomas Nagy, 2008 (ita) + +"as and gas" + +import os, sys +import Task +from TaskGen import extension, taskgen, after, before + +EXT_ASM = ['.s', '.S', '.asm', '.ASM', '.spp', '.SPP'] + +as_str = '${AS} ${ASFLAGS} ${_ASINCFLAGS} ${SRC} -o ${TGT}' +Task.simple_task_type('asm', as_str, 'PINK', ext_out='.o', shell=False) + +@extension(EXT_ASM) +def asm_hook(self, node): + # create the compilation task: cpp or cc + try: obj_ext = self.obj_ext + except AttributeError: obj_ext = '_%d.o' % self.idx + + task = self.create_task('asm', node, node.change_ext(obj_ext)) + self.compiled_tasks.append(task) + self.meths.append('asm_incflags') + +@after('apply_obj_vars_cc') +@after('apply_obj_vars_cxx') +@before('apply_link') +def asm_incflags(self): + self.env.append_value('_ASINCFLAGS', self.env.ASINCFLAGS) + var = ('cxx' in self.features) and 'CXX' or 'CC' + self.env.append_value('_ASINCFLAGS', self.env['_%sINCFLAGS' % var]) + +def detect(conf): + conf.find_program(['gas', 'as'], var='AS') + if not conf.env.AS: conf.env.AS = conf.env.CC + #conf.env.ASFLAGS = ['-c'] <- may be necesary for .S files + diff --git a/node-v0.8.14/tools/wafadmin/Tools/gcc.py b/node-v0.8.14/tools/wafadmin/Tools/gcc.py new file mode 100644 index 0000000..40a788e --- /dev/null +++ b/node-v0.8.14/tools/wafadmin/Tools/gcc.py @@ -0,0 +1,137 @@ +#!/usr/bin/env python +# encoding: utf-8 +# Thomas Nagy, 2006-2008 (ita) +# Ralf Habacker, 2006 (rh) +# Yinon Ehrlich, 2009 + +import os, sys +import Configure, Options, Utils +import ccroot, ar +from Configure import conftest + +@conftest +def find_gcc(conf): + cc = conf.find_program(['gcc', 'cc'], var='CC', mandatory=True) + cc = conf.cmd_to_list(cc) + ccroot.get_cc_version(conf, cc, gcc=True) + conf.env.CC_NAME = 'gcc' + conf.env.CC = cc + +@conftest +def gcc_common_flags(conf): + v = conf.env + + # CPPFLAGS CCDEFINES _CCINCFLAGS _CCDEFFLAGS + + v['CCFLAGS_DEBUG'] = ['-g'] + + v['CCFLAGS_RELEASE'] = ['-O2'] + + v['CC_SRC_F'] = '' + v['CC_TGT_F'] = ['-c', '-o', ''] # shell hack for -MD + v['CPPPATH_ST'] = '-I%s' # template for adding include paths + + # linker + if not v['LINK_CC']: v['LINK_CC'] = v['CC'] + v['CCLNK_SRC_F'] = '' + v['CCLNK_TGT_F'] = ['-o', ''] # shell hack for -MD + + v['LIB_ST'] = '-l%s' # template for adding libs + v['LIBPATH_ST'] = '-L%s' # template for adding libpaths + v['STATICLIB_ST'] = '-l%s' + v['STATICLIBPATH_ST'] = '-L%s' + v['RPATH_ST'] = '-Wl,-rpath,%s' + v['CCDEFINES_ST'] = '-D%s' + + v['SONAME_ST'] = '-Wl,-h,%s' + v['SHLIB_MARKER'] = '-Wl,-Bdynamic' + v['STATICLIB_MARKER'] = '-Wl,-Bstatic' + v['FULLSTATIC_MARKER'] = '-static' + + # program + v['program_PATTERN'] = '%s' + + # shared library + v['shlib_CCFLAGS'] = ['-fPIC', '-DPIC'] # avoid using -DPIC, -fPIC aleady defines the __PIC__ macro + v['shlib_LINKFLAGS'] = ['-shared'] + v['shlib_PATTERN'] = 'lib%s.so' + + # static lib + v['staticlib_LINKFLAGS'] = ['-Wl,-Bstatic'] + v['staticlib_PATTERN'] = 'lib%s.a' + + # osx stuff + v['LINKFLAGS_MACBUNDLE'] = ['-bundle', '-undefined', 'dynamic_lookup'] + v['CCFLAGS_MACBUNDLE'] = ['-fPIC'] + v['macbundle_PATTERN'] = '%s.bundle' + +@conftest +def gcc_modifier_win32(conf): + v = conf.env + v['program_PATTERN'] = '%s.exe' + + v['shlib_PATTERN'] = '%s.dll' + v['implib_PATTERN'] = 'lib%s.dll.a' + v['IMPLIB_ST'] = '-Wl,--out-implib,%s' + + dest_arch = v['DEST_CPU'] + if dest_arch == 'x86': + # On 32-bit x86, gcc emits a message telling the -fPIC option is ignored on this arch, so we remove that flag. + v['shlib_CCFLAGS'] = ['-DPIC'] # TODO this is a wrong define, we don't use -fPIC! + + v.append_value('shlib_CCFLAGS', '-DDLL_EXPORT') # TODO adding nonstandard defines like this DLL_EXPORT is not a good idea + + # Auto-import is enabled by default even without this option, + # but enabling it explicitly has the nice effect of suppressing the rather boring, debug-level messages + # that the linker emits otherwise. + v.append_value('LINKFLAGS', '-Wl,--enable-auto-import') + +@conftest +def gcc_modifier_cygwin(conf): + gcc_modifier_win32(conf) + v = conf.env + v['shlib_PATTERN'] = 'cyg%s.dll' + v.append_value('shlib_LINKFLAGS', '-Wl,--enable-auto-image-base') + +@conftest +def gcc_modifier_darwin(conf): + v = conf.env + v['shlib_CCFLAGS'] = ['-fPIC', '-compatibility_version', '1', '-current_version', '1'] + v['shlib_LINKFLAGS'] = ['-dynamiclib'] + v['shlib_PATTERN'] = 'lib%s.dylib' + + v['staticlib_LINKFLAGS'] = [] + + v['SHLIB_MARKER'] = '' + v['STATICLIB_MARKER'] = '' + v['SONAME_ST'] = '' + +@conftest +def gcc_modifier_aix(conf): + v = conf.env + v['program_LINKFLAGS'] = ['-Wl,-brtl'] + + v['shlib_LINKFLAGS'] = ['-shared','-Wl,-brtl,-bexpfull'] + + v['SHLIB_MARKER'] = '' + +@conftest +def gcc_modifier_platform(conf): + # * set configurations specific for a platform. + # * the destination platform is detected automatically by looking at the macros the compiler predefines, + # and if it's not recognised, it fallbacks to sys.platform. + dest_os = conf.env['DEST_OS'] or Utils.unversioned_sys_platform() + gcc_modifier_func = globals().get('gcc_modifier_' + dest_os) + if gcc_modifier_func: + gcc_modifier_func(conf) + +def detect(conf): + conf.find_gcc() + conf.find_cpp() + conf.find_ar() + conf.gcc_common_flags() + conf.gcc_modifier_platform() + conf.cc_load_tools() + conf.cc_add_flags() + conf.link_add_flags() + diff --git a/node-v0.8.14/tools/wafadmin/Tools/gdc.py b/node-v0.8.14/tools/wafadmin/Tools/gdc.py new file mode 100644 index 0000000..4d2a321 --- /dev/null +++ b/node-v0.8.14/tools/wafadmin/Tools/gdc.py @@ -0,0 +1,52 @@ +#!/usr/bin/env python +# encoding: utf-8 +# Carlos Rafael Giani, 2007 (dv) + +import sys +import Utils, ar +from Configure import conftest + +@conftest +def find_gdc(conf): + conf.find_program('gdc', var='D_COMPILER', mandatory=True) + +@conftest +def common_flags_gdc(conf): + v = conf.env + + # _DFLAGS _DIMPORTFLAGS + + # for mory info about the meaning of this dict see dmd.py + v['DFLAGS'] = [] + + v['D_SRC_F'] = '' + v['D_TGT_F'] = ['-c', '-o', ''] + v['DPATH_ST'] = '-I%s' # template for adding import paths + + # linker + v['D_LINKER'] = v['D_COMPILER'] + v['DLNK_SRC_F'] = '' + v['DLNK_TGT_F'] = ['-o', ''] + + v['DLIB_ST'] = '-l%s' # template for adding libs + v['DLIBPATH_ST'] = '-L%s' # template for adding libpaths + + # debug levels + v['DLINKFLAGS'] = [] + v['DFLAGS_OPTIMIZED'] = ['-O3'] + v['DFLAGS_DEBUG'] = ['-O0'] + v['DFLAGS_ULTRADEBUG'] = ['-O0'] + + v['D_shlib_DFLAGS'] = [] + v['D_shlib_LINKFLAGS'] = ['-shared'] + + v['DHEADER_ext'] = '.di' + v['D_HDR_F'] = '-fintfc -fintfc-file=' + +def detect(conf): + conf.find_gdc() + conf.check_tool('ar') + conf.check_tool('d') + conf.common_flags_gdc() + conf.d_platform_flags() + diff --git a/node-v0.8.14/tools/wafadmin/Tools/gnu_dirs.py b/node-v0.8.14/tools/wafadmin/Tools/gnu_dirs.py new file mode 100644 index 0000000..856e4a7 --- /dev/null +++ b/node-v0.8.14/tools/wafadmin/Tools/gnu_dirs.py @@ -0,0 +1,111 @@ +#!/usr/bin/env python +# encoding: utf-8 +# Ali Sabil, 2007 + +""" +To use this module do not forget to call +opt.tool_options('gnu_dirs') +AND +conf.check_tool('gnu_dirs') + +Add options for the standard GNU directories, this tool will add the options +found in autotools, and will update the environment with the following +installation variables: + + * PREFIX : architecture-independent files [/usr/local] + * EXEC_PREFIX : architecture-dependent files [PREFIX] + * BINDIR : user executables [EXEC_PREFIX/bin] + * SBINDIR : user executables [EXEC_PREFIX/sbin] + * LIBEXECDIR : program executables [EXEC_PREFIX/libexec] + * SYSCONFDIR : read-only single-machine data [PREFIX/etc] + * SHAREDSTATEDIR : modifiable architecture-independent data [PREFIX/com] + * LOCALSTATEDIR : modifiable single-machine data [PREFIX/var] + * LIBDIR : object code libraries [EXEC_PREFIX/lib] + * INCLUDEDIR : C header files [PREFIX/include] + * OLDINCLUDEDIR : C header files for non-gcc [/usr/include] + * DATAROOTDIR : read-only arch.-independent data root [PREFIX/share] + * DATADIR : read-only architecture-independent data [DATAROOTDIR] + * INFODIR : info documentation [DATAROOTDIR/info] + * LOCALEDIR : locale-dependent data [DATAROOTDIR/locale] + * MANDIR : man documentation [DATAROOTDIR/man] + * DOCDIR : documentation root [DATAROOTDIR/doc/telepathy-glib] + * HTMLDIR : html documentation [DOCDIR] + * DVIDIR : dvi documentation [DOCDIR] + * PDFDIR : pdf documentation [DOCDIR] + * PSDIR : ps documentation [DOCDIR] +""" + +import Utils, Options + +_options = [x.split(', ') for x in ''' +bindir, user executables, ${EXEC_PREFIX}/bin +sbindir, system admin executables, ${EXEC_PREFIX}/sbin +libexecdir, program executables, ${EXEC_PREFIX}/libexec +sysconfdir, read-only single-machine data, ${PREFIX}/etc +sharedstatedir, modifiable architecture-independent data, ${PREFIX}/com +localstatedir, modifiable single-machine data, ${PREFIX}/var +libdir, object code libraries, ${EXEC_PREFIX}/lib +includedir, C header files, ${PREFIX}/include +oldincludedir, C header files for non-gcc, /usr/include +datarootdir, read-only arch.-independent data root, ${PREFIX}/share +datadir, read-only architecture-independent data, ${DATAROOTDIR} +infodir, info documentation, ${DATAROOTDIR}/info +localedir, locale-dependent data, ${DATAROOTDIR}/locale +mandir, man documentation, ${DATAROOTDIR}/man +docdir, documentation root, ${DATAROOTDIR}/doc/${PACKAGE} +htmldir, html documentation, ${DOCDIR} +dvidir, dvi documentation, ${DOCDIR} +pdfdir, pdf documentation, ${DOCDIR} +psdir, ps documentation, ${DOCDIR} +'''.split('\n') if x] + +def detect(conf): + def get_param(varname, default): + return getattr(Options.options, varname, '') or default + + env = conf.env + env['EXEC_PREFIX'] = get_param('EXEC_PREFIX', env['PREFIX']) + env['PACKAGE'] = Utils.g_module.APPNAME + + complete = False + iter = 0 + while not complete and iter < len(_options) + 1: + iter += 1 + complete = True + for name, help, default in _options: + name = name.upper() + if not env[name]: + try: + env[name] = Utils.subst_vars(get_param(name, default), env) + except TypeError: + complete = False + if not complete: + lst = [name for name, _, _ in _options if not env[name.upper()]] + raise Utils.WafError('Variable substitution failure %r' % lst) + +def set_options(opt): + + inst_dir = opt.add_option_group('Installation directories', +'By default, "waf install" will put the files in\ + "/usr/local/bin", "/usr/local/lib" etc. An installation prefix other\ + than "/usr/local" can be given using "--prefix", for example "--prefix=$HOME"') + + for k in ('--prefix', '--destdir'): + option = opt.parser.get_option(k) + if option: + opt.parser.remove_option(k) + inst_dir.add_option(option) + + inst_dir.add_option('--exec-prefix', + help = 'installation prefix [Default: ${PREFIX}]', + default = '', + dest = 'EXEC_PREFIX') + + dirs_options = opt.add_option_group('Pre-defined installation directories', '') + + for name, help, default in _options: + option_name = '--' + name + str_default = default + str_help = '%s [Default: %s]' % (help, str_default) + dirs_options.add_option(option_name, help=str_help, default='', dest=name.upper()) + diff --git a/node-v0.8.14/tools/wafadmin/Tools/gob2.py b/node-v0.8.14/tools/wafadmin/Tools/gob2.py new file mode 100644 index 0000000..00aaa32 --- /dev/null +++ b/node-v0.8.14/tools/wafadmin/Tools/gob2.py @@ -0,0 +1,18 @@ +#!/usr/bin/env python +# encoding: utf-8 +# Ali Sabil, 2007 + +import TaskGen + +TaskGen.declare_chain( + name = 'gob2', + rule = '${GOB2} -o ${TGT[0].bld_dir(env)} ${GOB2FLAGS} ${SRC}', + ext_in = '.gob', + ext_out = '.c' +) + +def detect(conf): + gob2 = conf.find_program('gob2', var='GOB2', mandatory=True) + conf.env['GOB2'] = gob2 + conf.env['GOB2FLAGS'] = '' + diff --git a/node-v0.8.14/tools/wafadmin/Tools/gxx.py b/node-v0.8.14/tools/wafadmin/Tools/gxx.py new file mode 100644 index 0000000..133e116 --- /dev/null +++ b/node-v0.8.14/tools/wafadmin/Tools/gxx.py @@ -0,0 +1,134 @@ +#!/usr/bin/env python +# encoding: utf-8 +# Thomas Nagy, 2006 (ita) +# Ralf Habacker, 2006 (rh) +# Yinon Ehrlich, 2009 + +import os, sys +import Configure, Options, Utils +import ccroot, ar +from Configure import conftest + +@conftest +def find_gxx(conf): + cxx = conf.find_program(['g++', 'c++'], var='CXX', mandatory=True) + cxx = conf.cmd_to_list(cxx) + ccroot.get_cc_version(conf, cxx, gcc=True) + conf.env.CXX_NAME = 'gcc' + conf.env.CXX = cxx + +@conftest +def gxx_common_flags(conf): + v = conf.env + + # CPPFLAGS CXXDEFINES _CXXINCFLAGS _CXXDEFFLAGS + v['CXXFLAGS_DEBUG'] = ['-g'] + v['CXXFLAGS_RELEASE'] = ['-O2'] + + v['CXX_SRC_F'] = '' + v['CXX_TGT_F'] = ['-c', '-o', ''] # shell hack for -MD + v['CPPPATH_ST'] = '-I%s' # template for adding include paths + + # linker + if not v['LINK_CXX']: v['LINK_CXX'] = v['CXX'] + v['CXXLNK_SRC_F'] = '' + v['CXXLNK_TGT_F'] = ['-o', ''] # shell hack for -MD + + v['LIB_ST'] = '-l%s' # template for adding libs + v['LIBPATH_ST'] = '-L%s' # template for adding libpaths + v['STATICLIB_ST'] = '-l%s' + v['STATICLIBPATH_ST'] = '-L%s' + v['RPATH_ST'] = '-Wl,-rpath,%s' + v['CXXDEFINES_ST'] = '-D%s' + + v['SONAME_ST'] = '-Wl,-h,%s' + v['SHLIB_MARKER'] = '-Wl,-Bdynamic' + v['STATICLIB_MARKER'] = '-Wl,-Bstatic' + v['FULLSTATIC_MARKER'] = '-static' + + # program + v['program_PATTERN'] = '%s' + + # shared library + v['shlib_CXXFLAGS'] = ['-fPIC', '-DPIC'] # avoid using -DPIC, -fPIC aleady defines the __PIC__ macro + v['shlib_LINKFLAGS'] = ['-shared'] + v['shlib_PATTERN'] = 'lib%s.so' + + # static lib + v['staticlib_LINKFLAGS'] = ['-Wl,-Bstatic'] + v['staticlib_PATTERN'] = 'lib%s.a' + + # osx stuff + v['LINKFLAGS_MACBUNDLE'] = ['-bundle', '-undefined', 'dynamic_lookup'] + v['CCFLAGS_MACBUNDLE'] = ['-fPIC'] + v['macbundle_PATTERN'] = '%s.bundle' + +@conftest +def gxx_modifier_win32(conf): + v = conf.env + v['program_PATTERN'] = '%s.exe' + + v['shlib_PATTERN'] = '%s.dll' + v['implib_PATTERN'] = 'lib%s.dll.a' + v['IMPLIB_ST'] = '-Wl,--out-implib,%s' + + dest_arch = v['DEST_CPU'] + if dest_arch == 'x86': + # On 32-bit x86, gcc emits a message telling the -fPIC option is ignored on this arch, so we remove that flag. + v['shlib_CXXFLAGS'] = ['-DPIC'] # TODO this is a wrong define, we don't use -fPIC! + + v.append_value('shlib_CXXFLAGS', '-DDLL_EXPORT') # TODO adding nonstandard defines like this DLL_EXPORT is not a good idea + + # Auto-import is enabled by default even without this option, + # but enabling it explicitly has the nice effect of suppressing the rather boring, debug-level messages + # that the linker emits otherwise. + v.append_value('LINKFLAGS', '-Wl,--enable-auto-import') + +@conftest +def gxx_modifier_cygwin(conf): + gxx_modifier_win32(conf) + v = conf.env + v['shlib_PATTERN'] = 'cyg%s.dll' + v.append_value('shlib_LINKFLAGS', '-Wl,--enable-auto-image-base') + +@conftest +def gxx_modifier_darwin(conf): + v = conf.env + v['shlib_CXXFLAGS'] = ['-fPIC', '-compatibility_version', '1', '-current_version', '1'] + v['shlib_LINKFLAGS'] = ['-dynamiclib'] + v['shlib_PATTERN'] = 'lib%s.dylib' + + v['staticlib_LINKFLAGS'] = [] + + v['SHLIB_MARKER'] = '' + v['STATICLIB_MARKER'] = '' + v['SONAME_ST'] = '' + +@conftest +def gxx_modifier_aix(conf): + v = conf.env + v['program_LINKFLAGS'] = ['-Wl,-brtl'] + + v['shlib_LINKFLAGS'] = ['-shared', '-Wl,-brtl,-bexpfull'] + + v['SHLIB_MARKER'] = '' + +@conftest +def gxx_modifier_platform(conf): + # * set configurations specific for a platform. + # * the destination platform is detected automatically by looking at the macros the compiler predefines, + # and if it's not recognised, it fallbacks to sys.platform. + dest_os = conf.env['DEST_OS'] or Utils.unversioned_sys_platform() + gxx_modifier_func = globals().get('gxx_modifier_' + dest_os) + if gxx_modifier_func: + gxx_modifier_func(conf) + +def detect(conf): + conf.find_gxx() + conf.find_cpp() + conf.find_ar() + conf.gxx_common_flags() + conf.gxx_modifier_platform() + conf.cxx_load_tools() + conf.cxx_add_flags() + diff --git a/node-v0.8.14/tools/wafadmin/Tools/icc.py b/node-v0.8.14/tools/wafadmin/Tools/icc.py new file mode 100644 index 0000000..9c9a926 --- /dev/null +++ b/node-v0.8.14/tools/wafadmin/Tools/icc.py @@ -0,0 +1,37 @@ +#!/usr/bin/env python +# encoding: utf-8 +# Stian Selnes, 2008 +# Thomas Nagy 2009 + +import os, sys +import Configure, Options, Utils +import ccroot, ar, gcc +from Configure import conftest + +@conftest +def find_icc(conf): + if sys.platform == 'cygwin': + conf.fatal('The Intel compiler does not work on Cygwin') + + v = conf.env + cc = None + if v['CC']: cc = v['CC'] + elif 'CC' in conf.environ: cc = conf.environ['CC'] + if not cc: cc = conf.find_program('icc', var='CC') + if not cc: cc = conf.find_program('ICL', var='CC') + if not cc: conf.fatal('Intel C Compiler (icc) was not found') + cc = conf.cmd_to_list(cc) + + ccroot.get_cc_version(conf, cc, icc=True) + v['CC'] = cc + v['CC_NAME'] = 'icc' + +detect = ''' +find_icc +find_ar +gcc_common_flags +gcc_modifier_platform +cc_load_tools +cc_add_flags +link_add_flags +''' diff --git a/node-v0.8.14/tools/wafadmin/Tools/icpc.py b/node-v0.8.14/tools/wafadmin/Tools/icpc.py new file mode 100644 index 0000000..726e3a4 --- /dev/null +++ b/node-v0.8.14/tools/wafadmin/Tools/icpc.py @@ -0,0 +1,34 @@ +#!/usr/bin/env python +# encoding: utf-8 +# Thomas Nagy 2009 + +import os, sys +import Configure, Options, Utils +import ccroot, ar, gxx +from Configure import conftest + +@conftest +def find_icpc(conf): + if sys.platform == 'cygwin': + conf.fatal('The Intel compiler does not work on Cygwin') + + v = conf.env + cxx = None + if v['CXX']: cxx = v['CXX'] + elif 'CXX' in conf.environ: cxx = conf.environ['CXX'] + if not cxx: cxx = conf.find_program('icpc', var='CXX') + if not cxx: conf.fatal('Intel C++ Compiler (icpc) was not found') + cxx = conf.cmd_to_list(cxx) + + ccroot.get_cc_version(conf, cxx, icc=True) + v['CXX'] = cxx + v['CXX_NAME'] = 'icc' + +detect = ''' +find_icpc +find_ar +gxx_common_flags +gxx_modifier_platform +cxx_load_tools +cxx_add_flags +''' diff --git a/node-v0.8.14/tools/wafadmin/Tools/intltool.py b/node-v0.8.14/tools/wafadmin/Tools/intltool.py new file mode 100644 index 0000000..deb8f4a --- /dev/null +++ b/node-v0.8.14/tools/wafadmin/Tools/intltool.py @@ -0,0 +1,139 @@ +#!/usr/bin/env python +# encoding: utf-8 +# Thomas Nagy, 2006 (ita) + +"intltool support" + +import os, re +import Configure, TaskGen, Task, Utils, Runner, Options, Build, config_c +from TaskGen import feature, before, taskgen +from Logs import error + +""" +Usage: + +bld(features='intltool_in', source='a.po b.po', podir='po', cache='.intlcache', flags='') + +""" + +class intltool_in_taskgen(TaskGen.task_gen): + """deprecated""" + def __init__(self, *k, **kw): + TaskGen.task_gen.__init__(self, *k, **kw) + +@before('apply_core') +@feature('intltool_in') +def iapply_intltool_in_f(self): + try: self.meths.remove('apply_core') + except ValueError: pass + + for i in self.to_list(self.source): + node = self.path.find_resource(i) + + podir = getattr(self, 'podir', 'po') + podirnode = self.path.find_dir(podir) + if not podirnode: + error("could not find the podir %r" % podir) + continue + + cache = getattr(self, 'intlcache', '.intlcache') + self.env['INTLCACHE'] = os.path.join(self.path.bldpath(self.env), podir, cache) + self.env['INTLPODIR'] = podirnode.srcpath(self.env) + self.env['INTLFLAGS'] = getattr(self, 'flags', ['-q', '-u', '-c']) + + task = self.create_task('intltool', node, node.change_ext('')) + task.install_path = self.install_path + +class intltool_po_taskgen(TaskGen.task_gen): + """deprecated""" + def __init__(self, *k, **kw): + TaskGen.task_gen.__init__(self, *k, **kw) + + +@feature('intltool_po') +def apply_intltool_po(self): + try: self.meths.remove('apply_core') + except ValueError: pass + + self.default_install_path = '${LOCALEDIR}' + appname = getattr(self, 'appname', 'set_your_app_name') + podir = getattr(self, 'podir', '') + + def install_translation(task): + out = task.outputs[0] + filename = out.name + (langname, ext) = os.path.splitext(filename) + inst_file = langname + os.sep + 'LC_MESSAGES' + os.sep + appname + '.mo' + self.bld.install_as(os.path.join(self.install_path, inst_file), out, self.env, self.chmod) + + linguas = self.path.find_resource(os.path.join(podir, 'LINGUAS')) + if linguas: + # scan LINGUAS file for locales to process + file = open(linguas.abspath()) + langs = [] + for line in file.readlines(): + # ignore lines containing comments + if not line.startswith('#'): + langs += line.split() + file.close() + re_linguas = re.compile('[-a-zA-Z_@.]+') + for lang in langs: + # Make sure that we only process lines which contain locales + if re_linguas.match(lang): + node = self.path.find_resource(os.path.join(podir, re_linguas.match(lang).group() + '.po')) + task = self.create_task('po') + task.set_inputs(node) + task.set_outputs(node.change_ext('.mo')) + if self.bld.is_install: task.install = install_translation + else: + Utils.pprint('RED', "Error no LINGUAS file found in po directory") + +Task.simple_task_type('po', '${POCOM} -o ${TGT} ${SRC}', color='BLUE', shell=False) +Task.simple_task_type('intltool', + '${INTLTOOL} ${INTLFLAGS} ${INTLCACHE} ${INTLPODIR} ${SRC} ${TGT}', + color='BLUE', after="cc_link cxx_link", shell=False) + +def detect(conf): + pocom = conf.find_program('msgfmt') + if not pocom: + # if msgfmt should not be mandatory, catch the thrown exception in your wscript + conf.fatal('The program msgfmt (gettext) is mandatory!') + conf.env['POCOM'] = pocom + + # NOTE: it is possible to set INTLTOOL in the environment, but it must not have spaces in it + + intltool = conf.find_program('intltool-merge', var='INTLTOOL') + if not intltool: + # if intltool-merge should not be mandatory, catch the thrown exception in your wscript + if Options.platform == 'win32': + perl = conf.find_program('perl', var='PERL') + if not perl: + conf.fatal('The program perl (required by intltool) could not be found') + + intltooldir = Configure.find_file('intltool-merge', os.environ['PATH'].split(os.pathsep)) + if not intltooldir: + conf.fatal('The program intltool-merge (intltool, gettext-devel) is mandatory!') + + conf.env['INTLTOOL'] = Utils.to_list(conf.env['PERL']) + [intltooldir + os.sep + 'intltool-merge'] + conf.check_message('intltool', '', True, ' '.join(conf.env['INTLTOOL'])) + else: + conf.fatal('The program intltool-merge (intltool, gettext-devel) is mandatory!') + + def getstr(varname): + return getattr(Options.options, varname, '') + + prefix = conf.env['PREFIX'] + datadir = getstr('datadir') + if not datadir: datadir = os.path.join(prefix,'share') + + conf.define('LOCALEDIR', os.path.join(datadir, 'locale')) + conf.define('DATADIR', datadir) + + if conf.env['CC'] or conf.env['CXX']: + # Define to 1 if is present + conf.check(header_name='locale.h') + +def set_options(opt): + opt.add_option('--want-rpath', type='int', default=1, dest='want_rpath', help='set rpath to 1 or 0 [Default 1]') + opt.add_option('--datadir', type='string', default='', dest='datadir', help='read-only application data') + diff --git a/node-v0.8.14/tools/wafadmin/Tools/libtool.py b/node-v0.8.14/tools/wafadmin/Tools/libtool.py new file mode 100644 index 0000000..a9b5689 --- /dev/null +++ b/node-v0.8.14/tools/wafadmin/Tools/libtool.py @@ -0,0 +1,330 @@ +#!/usr/bin/env python +# encoding: utf-8 +# Matthias Jahn, 2008, jahn matthias ath freenet punto de +# Thomas Nagy, 2008 (ita) + +import sys, re, os, optparse + +import TaskGen, Task, Utils, preproc +from Logs import error, debug, warn +from TaskGen import taskgen, after, before, feature + +REVISION="0.1.3" + +""" +if you want to use the code here, you must use something like this: +obj = obj.create(...) +obj.features.append("libtool") +obj.vnum = "1.2.3" # optional, but versioned libraries are common +""" + +# fake libtool files +fakelibtool_vardeps = ['CXX', 'PREFIX'] +def fakelibtool_build(task): + # Writes a .la file, used by libtool + env = task.env + dest = open(task.outputs[0].abspath(env), 'w') + sname = task.inputs[0].name + fu = dest.write + fu("# Generated by ltmain.sh - GNU libtool 1.5.18 - (pwn3d by BKsys II code name WAF)\n") + if env['vnum']: + nums = env['vnum'].split('.') + libname = task.inputs[0].name + name3 = libname+'.'+env['vnum'] + name2 = libname+'.'+nums[0] + name1 = libname + fu("dlname='%s'\n" % name2) + strn = " ".join([name3, name2, name1]) + fu("library_names='%s'\n" % (strn) ) + else: + fu("dlname='%s'\n" % sname) + fu("library_names='%s %s %s'\n" % (sname, sname, sname) ) + fu("old_library=''\n") + vars = ' '.join(env['libtoolvars']+env['LINKFLAGS']) + fu("dependency_libs='%s'\n" % vars) + fu("current=0\n") + fu("age=0\nrevision=0\ninstalled=yes\nshouldnotlink=no\n") + fu("dlopen=''\ndlpreopen=''\n") + fu("libdir='%s/lib'\n" % env['PREFIX']) + dest.close() + return 0 + +def read_la_file(path): + sp = re.compile(r'^([^=]+)=\'(.*)\'$') + dc={} + file = open(path, "r") + for line in file.readlines(): + try: + #print sp.split(line.strip()) + _, left, right, _ = sp.split(line.strip()) + dc[left]=right + except ValueError: + pass + file.close() + return dc + +@feature("libtool") +@after('apply_link') +def apply_link_libtool(self): + if self.type != 'program': + linktask = self.link_task + self.latask = self.create_task('fakelibtool', linktask.outputs, linktask.outputs[0].change_ext('.la')) + + if self.bld.is_install: + self.bld.install_files('${PREFIX}/lib', linktask.outputs[0], self.env) + +@feature("libtool") +@before('apply_core') +def apply_libtool(self): + self.env['vnum']=self.vnum + + paths=[] + libs=[] + libtool_files=[] + libtool_vars=[] + + for l in self.env['LINKFLAGS']: + if l[:2]=='-L': + paths.append(l[2:]) + elif l[:2]=='-l': + libs.append(l[2:]) + + for l in libs: + for p in paths: + dict = read_la_file(p+'/lib'+l+'.la') + linkflags2 = dict.get('dependency_libs', '') + for v in linkflags2.split(): + if v.endswith('.la'): + libtool_files.append(v) + libtool_vars.append(v) + continue + self.env.append_unique('LINKFLAGS', v) + break + + self.env['libtoolvars']=libtool_vars + + while libtool_files: + file = libtool_files.pop() + dict = read_la_file(file) + for v in dict['dependency_libs'].split(): + if v[-3:] == '.la': + libtool_files.append(v) + continue + self.env.append_unique('LINKFLAGS', v) + +Task.task_type_from_func('fakelibtool', vars=fakelibtool_vardeps, func=fakelibtool_build, color='BLUE', after="cc_link cxx_link static_link") + +class libtool_la_file: + def __init__ (self, la_filename): + self.__la_filename = la_filename + #remove path and .la suffix + self.linkname = str(os.path.split(la_filename)[-1])[:-3] + if self.linkname.startswith("lib"): + self.linkname = self.linkname[3:] + # The name that we can dlopen(3). + self.dlname = None + # Names of this library + self.library_names = None + # The name of the static archive. + self.old_library = None + # Libraries that this one depends upon. + self.dependency_libs = None + # Version information for libIlmImf. + self.current = None + self.age = None + self.revision = None + # Is this an already installed library? + self.installed = None + # Should we warn about portability when linking against -modules? + self.shouldnotlink = None + # Files to dlopen/dlpreopen + self.dlopen = None + self.dlpreopen = None + # Directory that this library needs to be installed in: + self.libdir = '/usr/lib' + if not self.__parse(): + raise "file %s not found!!" %(la_filename) + + def __parse(self): + "Retrieve the variables from a file" + if not os.path.isfile(self.__la_filename): return 0 + la_file=open(self.__la_filename, 'r') + for line in la_file: + ln = line.strip() + if not ln: continue + if ln[0]=='#': continue + (key, value) = str(ln).split('=', 1) + key = key.strip() + value = value.strip() + if value == "no": value = False + elif value == "yes": value = True + else: + try: value = int(value) + except ValueError: value = value.strip("'") + setattr(self, key, value) + la_file.close() + return 1 + + def get_libs(self): + """return linkflags for this lib""" + libs = [] + if self.dependency_libs: + libs = str(self.dependency_libs).strip().split() + if libs == None: + libs = [] + # add la lib and libdir + libs.insert(0, "-l%s" % self.linkname.strip()) + libs.insert(0, "-L%s" % self.libdir.strip()) + return libs + + def __str__(self): + return '''\ +dlname = "%(dlname)s" +library_names = "%(library_names)s" +old_library = "%(old_library)s" +dependency_libs = "%(dependency_libs)s" +version = %(current)s.%(age)s.%(revision)s +installed = "%(installed)s" +shouldnotlink = "%(shouldnotlink)s" +dlopen = "%(dlopen)s" +dlpreopen = "%(dlpreopen)s" +libdir = "%(libdir)s"''' % self.__dict__ + +class libtool_config: + def __init__ (self, la_filename): + self.__libtool_la_file = libtool_la_file(la_filename) + tmp = self.__libtool_la_file + self.__version = [int(tmp.current), int(tmp.age), int(tmp.revision)] + self.__sub_la_files = [] + self.__sub_la_files.append(la_filename) + self.__libs = None + + def __cmp__(self, other): + """make it compareable with X.Y.Z versions (Y and Z are optional)""" + if not other: + return 1 + othervers = [int(s) for s in str(other).split(".")] + selfvers = self.__version + return cmp(selfvers, othervers) + + def __str__(self): + return "\n".join([ + str(self.__libtool_la_file), + ' '.join(self.__libtool_la_file.get_libs()), + '* New getlibs:', + ' '.join(self.get_libs()) + ]) + + def __get_la_libs(self, la_filename): + return libtool_la_file(la_filename).get_libs() + + def get_libs(self): + """return the complete uniqe linkflags that do not + contain .la files anymore""" + libs_list = list(self.__libtool_la_file.get_libs()) + libs_map = {} + while len(libs_list) > 0: + entry = libs_list.pop(0) + if entry: + if str(entry).endswith(".la"): + ## prevents duplicate .la checks + if entry not in self.__sub_la_files: + self.__sub_la_files.append(entry) + libs_list.extend(self.__get_la_libs(entry)) + else: + libs_map[entry]=1 + self.__libs = libs_map.keys() + return self.__libs + + def get_libs_only_L(self): + if not self.__libs: self.get_libs() + libs = self.__libs + libs = [s for s in libs if str(s).startswith('-L')] + return libs + + def get_libs_only_l(self): + if not self.__libs: self.get_libs() + libs = self.__libs + libs = [s for s in libs if str(s).startswith('-l')] + return libs + + def get_libs_only_other(self): + if not self.__libs: self.get_libs() + libs = self.__libs + libs = [s for s in libs if not(str(s).startswith('-L')or str(s).startswith('-l'))] + return libs + +def useCmdLine(): + """parse cmdline args and control build""" + usage = '''Usage: %prog [options] PathToFile.la +example: %prog --atleast-version=2.0.0 /usr/lib/libIlmImf.la +nor: %prog --libs /usr/lib/libamarok.la''' + parser = optparse.OptionParser(usage) + a = parser.add_option + a("--version", dest = "versionNumber", + action = "store_true", default = False, + help = "output version of libtool-config" + ) + a("--debug", dest = "debug", + action = "store_true", default = False, + help = "enable debug" + ) + a("--libs", dest = "libs", + action = "store_true", default = False, + help = "output all linker flags" + ) + a("--libs-only-l", dest = "libs_only_l", + action = "store_true", default = False, + help = "output -l flags" + ) + a("--libs-only-L", dest = "libs_only_L", + action = "store_true", default = False, + help = "output -L flags" + ) + a("--libs-only-other", dest = "libs_only_other", + action = "store_true", default = False, + help = "output other libs (e.g. -pthread)" + ) + a("--atleast-version", dest = "atleast_version", + default=None, + help = "return 0 if the module is at least version ATLEAST_VERSION" + ) + a("--exact-version", dest = "exact_version", + default=None, + help = "return 0 if the module is exactly version EXACT_VERSION" + ) + a("--max-version", dest = "max_version", + default=None, + help = "return 0 if the module is at no newer than version MAX_VERSION" + ) + + (options, args) = parser.parse_args() + if len(args) != 1 and not options.versionNumber: + parser.error("incorrect number of arguments") + if options.versionNumber: + print("libtool-config version %s" % REVISION) + return 0 + ltf = libtool_config(args[0]) + if options.debug: + print(ltf) + if options.atleast_version: + if ltf >= options.atleast_version: return 0 + sys.exit(1) + if options.exact_version: + if ltf == options.exact_version: return 0 + sys.exit(1) + if options.max_version: + if ltf <= options.max_version: return 0 + sys.exit(1) + + def p(x): + print(" ".join(x)) + if options.libs: p(ltf.get_libs()) + elif options.libs_only_l: p(ltf.get_libs_only_l()) + elif options.libs_only_L: p(ltf.get_libs_only_L()) + elif options.libs_only_other: p(ltf.get_libs_only_other()) + return 0 + +if __name__ == '__main__': + useCmdLine() + diff --git a/node-v0.8.14/tools/wafadmin/Tools/misc.py b/node-v0.8.14/tools/wafadmin/Tools/misc.py new file mode 100644 index 0000000..9903ee4 --- /dev/null +++ b/node-v0.8.14/tools/wafadmin/Tools/misc.py @@ -0,0 +1,430 @@ +#!/usr/bin/env python +# encoding: utf-8 +# Thomas Nagy, 2006 (ita) + +""" +Custom objects: + - execute a function everytime + - copy a file somewhere else +""" + +import shutil, re, os +import TaskGen, Node, Task, Utils, Build, Constants +from TaskGen import feature, taskgen, after, before +from Logs import debug + +def copy_func(tsk): + "Make a file copy. This might be used to make other kinds of file processing (even calling a compiler is possible)" + env = tsk.env + infile = tsk.inputs[0].abspath(env) + outfile = tsk.outputs[0].abspath(env) + try: + shutil.copy2(infile, outfile) + except (OSError, IOError): + return 1 + else: + if tsk.chmod: os.chmod(outfile, tsk.chmod) + return 0 + +def action_process_file_func(tsk): + "Ask the function attached to the task to process it" + if not tsk.fun: raise Utils.WafError('task must have a function attached to it for copy_func to work!') + return tsk.fun(tsk) + +class cmd_taskgen(TaskGen.task_gen): + def __init__(self, *k, **kw): + TaskGen.task_gen.__init__(self, *k, **kw) + +@feature('cmd') +def apply_cmd(self): + "call a command everytime" + if not self.fun: raise Utils.WafError('cmdobj needs a function!') + tsk = Task.TaskBase() + tsk.fun = self.fun + tsk.env = self.env + self.tasks.append(tsk) + tsk.install_path = self.install_path + +class copy_taskgen(TaskGen.task_gen): + "By default, make a file copy, if fun is provided, fun will make the copy (or call a compiler, etc)" + def __init__(self, *k, **kw): + TaskGen.task_gen.__init__(self, *k, **kw) + +@feature('copy') +@before('apply_core') +def apply_copy(self): + Utils.def_attrs(self, fun=copy_func) + self.default_install_path = 0 + + lst = self.to_list(self.source) + self.meths.remove('apply_core') + + for filename in lst: + node = self.path.find_resource(filename) + if not node: raise Utils.WafError('cannot find input file %s for processing' % filename) + + target = self.target + if not target or len(lst)>1: target = node.name + + # TODO the file path may be incorrect + newnode = self.path.find_or_declare(target) + + tsk = self.create_task('copy', node, newnode) + tsk.fun = self.fun + tsk.chmod = self.chmod + tsk.install_path = self.install_path + + if not tsk.env: + tsk.debug() + raise Utils.WafError('task without an environment') + +def subst_func(tsk): + "Substitutes variables in a .in file" + + m4_re = re.compile('@(\w+)@', re.M) + + env = tsk.env + infile = tsk.inputs[0].abspath(env) + outfile = tsk.outputs[0].abspath(env) + + code = Utils.readf(infile) + + # replace all % by %% to prevent errors by % signs in the input file while string formatting + code = code.replace('%', '%%') + + s = m4_re.sub(r'%(\1)s', code) + + di = tsk.dict or {} + if not di: + names = m4_re.findall(code) + for i in names: + di[i] = env.get_flat(i) or env.get_flat(i.upper()) + + file = open(outfile, 'w') + file.write(s % di) + file.close() + if tsk.chmod: os.chmod(outfile, tsk.chmod) + +class subst_taskgen(TaskGen.task_gen): + def __init__(self, *k, **kw): + TaskGen.task_gen.__init__(self, *k, **kw) + +@feature('subst') +@before('apply_core') +def apply_subst(self): + Utils.def_attrs(self, fun=subst_func) + self.default_install_path = 0 + lst = self.to_list(self.source) + self.meths.remove('apply_core') + + self.dict = getattr(self, 'dict', {}) + + for filename in lst: + node = self.path.find_resource(filename) + if not node: raise Utils.WafError('cannot find input file %s for processing' % filename) + + if self.target: + newnode = self.path.find_or_declare(self.target) + else: + newnode = node.change_ext('') + + try: + self.dict = self.dict.get_merged_dict() + except AttributeError: + pass + + if self.dict and not self.env['DICT_HASH']: + self.env = self.env.copy() + keys = list(self.dict.keys()) + keys.sort() + lst = [self.dict[x] for x in keys] + self.env['DICT_HASH'] = str(Utils.h_list(lst)) + + tsk = self.create_task('copy', node, newnode) + tsk.fun = self.fun + tsk.dict = self.dict + tsk.dep_vars = ['DICT_HASH'] + tsk.install_path = self.install_path + tsk.chmod = self.chmod + + if not tsk.env: + tsk.debug() + raise Utils.WafError('task without an environment') + +#################### +## command-output #### +#################### + +class cmd_arg(object): + """command-output arguments for representing files or folders""" + def __init__(self, name, template='%s'): + self.name = name + self.template = template + self.node = None + +class input_file(cmd_arg): + def find_node(self, base_path): + assert isinstance(base_path, Node.Node) + self.node = base_path.find_resource(self.name) + if self.node is None: + raise Utils.WafError("Input file %s not found in " % (self.name, base_path)) + + def get_path(self, env, absolute): + if absolute: + return self.template % self.node.abspath(env) + else: + return self.template % self.node.srcpath(env) + +class output_file(cmd_arg): + def find_node(self, base_path): + assert isinstance(base_path, Node.Node) + self.node = base_path.find_or_declare(self.name) + if self.node is None: + raise Utils.WafError("Output file %s not found in " % (self.name, base_path)) + + def get_path(self, env, absolute): + if absolute: + return self.template % self.node.abspath(env) + else: + return self.template % self.node.bldpath(env) + +class cmd_dir_arg(cmd_arg): + def find_node(self, base_path): + assert isinstance(base_path, Node.Node) + self.node = base_path.find_dir(self.name) + if self.node is None: + raise Utils.WafError("Directory %s not found in " % (self.name, base_path)) + +class input_dir(cmd_dir_arg): + def get_path(self, dummy_env, dummy_absolute): + return self.template % self.node.abspath() + +class output_dir(cmd_dir_arg): + def get_path(self, env, dummy_absolute): + return self.template % self.node.abspath(env) + + +class command_output(Task.Task): + color = "BLUE" + def __init__(self, env, command, command_node, command_args, stdin, stdout, cwd, os_env, stderr): + Task.Task.__init__(self, env, normal=1) + assert isinstance(command, (str, Node.Node)) + self.command = command + self.command_args = command_args + self.stdin = stdin + self.stdout = stdout + self.cwd = cwd + self.os_env = os_env + self.stderr = stderr + + if command_node is not None: self.dep_nodes = [command_node] + self.dep_vars = [] # additional environment variables to look + + def run(self): + task = self + #assert len(task.inputs) > 0 + + def input_path(node, template): + if task.cwd is None: + return template % node.bldpath(task.env) + else: + return template % node.abspath() + def output_path(node, template): + fun = node.abspath + if task.cwd is None: fun = node.bldpath + return template % fun(task.env) + + if isinstance(task.command, Node.Node): + argv = [input_path(task.command, '%s')] + else: + argv = [task.command] + + for arg in task.command_args: + if isinstance(arg, str): + argv.append(arg) + else: + assert isinstance(arg, cmd_arg) + argv.append(arg.get_path(task.env, (task.cwd is not None))) + + if task.stdin: + stdin = open(input_path(task.stdin, '%s')) + else: + stdin = None + + if task.stdout: + stdout = open(output_path(task.stdout, '%s'), "w") + else: + stdout = None + + if task.stderr: + stderr = open(output_path(task.stderr, '%s'), "w") + else: + stderr = None + + if task.cwd is None: + cwd = ('None (actually %r)' % os.getcwd()) + else: + cwd = repr(task.cwd) + debug("command-output: cwd=%s, stdin=%r, stdout=%r, argv=%r" % + (cwd, stdin, stdout, argv)) + + if task.os_env is None: + os_env = os.environ + else: + os_env = task.os_env + command = Utils.pproc.Popen(argv, stdin=stdin, stdout=stdout, stderr=stderr, cwd=task.cwd, env=os_env) + return command.wait() + +class cmd_output_taskgen(TaskGen.task_gen): + def __init__(self, *k, **kw): + TaskGen.task_gen.__init__(self, *k, **kw) + +@feature('command-output') +def init_cmd_output(self): + Utils.def_attrs(self, + stdin = None, + stdout = None, + stderr = None, + # the command to execute + command = None, + + # whether it is an external command; otherwise it is assumed + # to be an executable binary or script that lives in the + # source or build tree. + command_is_external = False, + + # extra parameters (argv) to pass to the command (excluding + # the command itself) + argv = [], + + # dependencies to other objects -> this is probably not what you want (ita) + # values must be 'task_gen' instances (not names!) + dependencies = [], + + # dependencies on env variable contents + dep_vars = [], + + # input files that are implicit, i.e. they are not + # stdin, nor are they mentioned explicitly in argv + hidden_inputs = [], + + # output files that are implicit, i.e. they are not + # stdout, nor are they mentioned explicitly in argv + hidden_outputs = [], + + # change the subprocess to this cwd (must use obj.input_dir() or output_dir() here) + cwd = None, + + # OS environment variables to pass to the subprocess + # if None, use the default environment variables unchanged + os_env = None) + +@feature('command-output') +@after('init_cmd_output') +def apply_cmd_output(self): + if self.command is None: + raise Utils.WafError("command-output missing command") + if self.command_is_external: + cmd = self.command + cmd_node = None + else: + cmd_node = self.path.find_resource(self.command) + assert cmd_node is not None, ('''Could not find command '%s' in source tree. +Hint: if this is an external command, +use command_is_external=True''') % (self.command,) + cmd = cmd_node + + if self.cwd is None: + cwd = None + else: + assert isinstance(cwd, CmdDirArg) + self.cwd.find_node(self.path) + + args = [] + inputs = [] + outputs = [] + + for arg in self.argv: + if isinstance(arg, cmd_arg): + arg.find_node(self.path) + if isinstance(arg, input_file): + inputs.append(arg.node) + if isinstance(arg, output_file): + outputs.append(arg.node) + + if self.stdout is None: + stdout = None + else: + assert isinstance(self.stdout, str) + stdout = self.path.find_or_declare(self.stdout) + if stdout is None: + raise Utils.WafError("File %s not found" % (self.stdout,)) + outputs.append(stdout) + + if self.stderr is None: + stderr = None + else: + assert isinstance(self.stderr, str) + stderr = self.path.find_or_declare(self.stderr) + if stderr is None: + raise Utils.WafError("File %s not found" % (self.stderr,)) + outputs.append(stderr) + + if self.stdin is None: + stdin = None + else: + assert isinstance(self.stdin, str) + stdin = self.path.find_resource(self.stdin) + if stdin is None: + raise Utils.WafError("File %s not found" % (self.stdin,)) + inputs.append(stdin) + + for hidden_input in self.to_list(self.hidden_inputs): + node = self.path.find_resource(hidden_input) + if node is None: + raise Utils.WafError("File %s not found in dir %s" % (hidden_input, self.path)) + inputs.append(node) + + for hidden_output in self.to_list(self.hidden_outputs): + node = self.path.find_or_declare(hidden_output) + if node is None: + raise Utils.WafError("File %s not found in dir %s" % (hidden_output, self.path)) + outputs.append(node) + + if not (inputs or getattr(self, 'no_inputs', None)): + raise Utils.WafError('command-output objects must have at least one input file or give self.no_inputs') + if not (outputs or getattr(self, 'no_outputs', None)): + raise Utils.WafError('command-output objects must have at least one output file or give self.no_outputs') + + task = command_output(self.env, cmd, cmd_node, self.argv, stdin, stdout, cwd, self.os_env, stderr) + Utils.copy_attrs(self, task, 'before after ext_in ext_out', only_if_set=True) + self.tasks.append(task) + + task.inputs = inputs + task.outputs = outputs + task.dep_vars = self.to_list(self.dep_vars) + + for dep in self.dependencies: + assert dep is not self + dep.post() + for dep_task in dep.tasks: + task.set_run_after(dep_task) + + if not task.inputs: + # the case for svnversion, always run, and update the output nodes + task.runnable_status = type(Task.TaskBase.run)(runnable_status, task, task.__class__) # always run + task.post_run = type(Task.TaskBase.run)(post_run, task, task.__class__) + + # TODO the case with no outputs? + +def post_run(self): + for x in self.outputs: + h = Utils.h_file(x.abspath(self.env)) + self.generator.bld.node_sigs[self.env.variant()][x.id] = h + +def runnable_status(self): + return Constants.RUN_ME + +Task.task_type_from_func('copy', vars=[], func=action_process_file_func) +TaskGen.task_gen.classes['command-output'] = cmd_output_taskgen + diff --git a/node-v0.8.14/tools/wafadmin/Tools/nasm.py b/node-v0.8.14/tools/wafadmin/Tools/nasm.py new file mode 100644 index 0000000..b99c3c7 --- /dev/null +++ b/node-v0.8.14/tools/wafadmin/Tools/nasm.py @@ -0,0 +1,49 @@ +#!/usr/bin/env python +# encoding: utf-8 +# Thomas Nagy, 2008 + +""" +Nasm processing +""" + +import os +import TaskGen, Task, Utils +from TaskGen import taskgen, before, extension + +nasm_str = '${NASM} ${NASM_FLAGS} ${NASM_INCLUDES} ${SRC} -o ${TGT}' + +EXT_NASM = ['.s', '.S', '.asm', '.ASM', '.spp', '.SPP'] + +@before('apply_link') +def apply_nasm_vars(self): + + # flags + if hasattr(self, 'nasm_flags'): + for flag in self.to_list(self.nasm_flags): + self.env.append_value('NASM_FLAGS', flag) + + # includes - well, if we suppose it works with c processing + if hasattr(self, 'includes'): + for inc in self.to_list(self.includes): + node = self.path.find_dir(inc) + if not node: + raise Utils.WafError('cannot find the dir' + inc) + self.env.append_value('NASM_INCLUDES', '-I%s' % node.srcpath(self.env)) + self.env.append_value('NASM_INCLUDES', '-I%s' % node.bldpath(self.env)) + +@extension(EXT_NASM) +def nasm_file(self, node): + try: obj_ext = self.obj_ext + except AttributeError: obj_ext = '_%d.o' % self.idx + + task = self.create_task('nasm', node, node.change_ext(obj_ext)) + self.compiled_tasks.append(task) + + self.meths.append('apply_nasm_vars') + +# create our action here +Task.simple_task_type('nasm', nasm_str, color='BLUE', ext_out='.o', shell=False) + +def detect(conf): + nasm = conf.find_program(['nasm', 'yasm'], var='NASM', mandatory=True) + diff --git a/node-v0.8.14/tools/wafadmin/Tools/node_addon.py b/node-v0.8.14/tools/wafadmin/Tools/node_addon.py new file mode 100644 index 0000000..6ea65ae --- /dev/null +++ b/node-v0.8.14/tools/wafadmin/Tools/node_addon.py @@ -0,0 +1,86 @@ +import os +import TaskGen, Utils, Runner, Options, Build +from TaskGen import extension, taskgen, before, after, feature +from Configure import conf, conftest + +@taskgen +@before('apply_incpaths', 'apply_lib_vars', 'apply_type_vars') +@feature('node_addon') +@before('apply_bundle') +def init_node_addon(self): + self.default_install_path = self.env['NODE_PATH'] + self.uselib = self.to_list(getattr(self, 'uselib', '')) + if not 'NODE' in self.uselib: self.uselib.append('NODE') + self.env['MACBUNDLE'] = True + +@taskgen +@before('apply_link', 'apply_lib_vars', 'apply_type_vars') +@after('apply_bundle') +@feature('node_addon') +def node_addon_shlib_ext(self): + self.env['shlib_PATTERN'] = "%s.node" + +def detect(conf): + join = os.path.join + + conf.env['PREFIX_NODE'] = get_prefix() + prefix = conf.env['PREFIX_NODE'] + lib = join(prefix, 'lib') + nodebin = join(prefix, 'bin', 'node') + + conf.env['LIBPATH_NODE'] = lib + conf.env['CPPPATH_NODE'] = join(prefix, 'include', 'node') + + conf.env.append_value('CPPFLAGS_NODE', '-D_GNU_SOURCE') + + conf.env.append_value('CCFLAGS_NODE', '-D_LARGEFILE_SOURCE') + conf.env.append_value('CCFLAGS_NODE', '-D_FILE_OFFSET_BITS=64') + + conf.env.append_value('CXXFLAGS_NODE', '-D_LARGEFILE_SOURCE') + conf.env.append_value('CXXFLAGS_NODE', '-D_FILE_OFFSET_BITS=64') + + # with symbols + conf.env.append_value('CCFLAGS', ['-g']) + conf.env.append_value('CXXFLAGS', ['-g']) + # install path + conf.env['NODE_PATH'] = get_node_path() + # this changes the install path of cxx task_gen + conf.env['LIBDIR'] = conf.env['NODE_PATH'] + + found = os.path.exists(conf.env['NODE_PATH']) + conf.check_message('node path', '', found, conf.env['NODE_PATH']) + + found = os.path.exists(nodebin) + conf.check_message('node prefix', '', found, prefix) + + ## On Cygwin we need to link to the generated symbol definitions + if Options.platform.startswith('cygwin'): conf.env['LIB_NODE'] = 'node' + + ## On Mac OSX we need to use mac bundles + if Options.platform == 'darwin': + if 'i386' in Utils.cmd_output(['file', nodebin]): + conf.env.append_value('CPPFLAGS_NODE', ['-arch', 'i386']) + conf.env.append_value('CXXFLAGS_NODE', ['-arch', 'i386']) + conf.env.append_value('LINKFLAGS', ['-arch', 'i386']) + conf.env['DEST_CPU'] = 'i386' + conf.check_tool('osx') + +def get_node_path(): + join = os.path.join + nodePath = None + if not os.environ.has_key('NODE_PATH'): + if not os.environ.has_key('HOME'): + nodePath = join(get_prefix(), 'lib', 'node') + else: + nodePath = join(os.environ['HOME'], '.node_libraries') + else: + nodePath = os.environ['NODE_PATH'] + return nodePath + +def get_prefix(): + prefix = None + if not os.environ.has_key('PREFIX_NODE'): + prefix = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..', '..', '..')) + else: + prefix = os.environ['PREFIX_NODE'] + return prefix diff --git a/node-v0.8.14/tools/wafadmin/Tools/osx.py b/node-v0.8.14/tools/wafadmin/Tools/osx.py new file mode 100644 index 0000000..7ca95f5 --- /dev/null +++ b/node-v0.8.14/tools/wafadmin/Tools/osx.py @@ -0,0 +1,187 @@ +#!/usr/bin/env python +# encoding: utf-8 +# Thomas Nagy 2008 + +"""MacOSX related tools + +To compile an executable into a Mac application bundle (a .app), set its 'mac_app' attribute + obj.mac_app = True + +To make a bundled shared library (a .bundle), set the 'mac_bundle' attribute: + obj.mac_bundle = True +""" + +import os, shutil, sys, platform +import TaskGen, Task, Build, Options, Utils +from TaskGen import taskgen, feature, after, before +from Logs import error, debug + +# plist template +app_info = ''' + + + + + CFBundlePackageType + APPL + CFBundleGetInfoString + Created by Waf + CFBundleSignature + ???? + NOTE + THIS IS A GENERATED FILE, DO NOT MODIFY + CFBundleExecutable + %s + + +''' + +# see WAF issue 285 +# and also http://trac.macports.org/ticket/17059 +@feature('cc', 'cxx') +@before('apply_lib_vars') +def set_macosx_deployment_target(self): + if self.env['MACOSX_DEPLOYMENT_TARGET']: + os.environ['MACOSX_DEPLOYMENT_TARGET'] = self.env['MACOSX_DEPLOYMENT_TARGET'] + elif 'MACOSX_DEPLOYMENT_TARGET' not in os.environ: + if sys.platform == 'darwin': + os.environ['MACOSX_DEPLOYMENT_TARGET'] = '.'.join(platform.mac_ver()[0].split('.')[:2]) + +@feature('cc', 'cxx') +@after('apply_lib_vars') +def apply_framework(self): + for x in self.to_list(self.env['FRAMEWORKPATH']): + frameworkpath_st = '-F%s' + self.env.append_unique('CXXFLAGS', frameworkpath_st % x) + self.env.append_unique('CCFLAGS', frameworkpath_st % x) + self.env.append_unique('LINKFLAGS', frameworkpath_st % x) + + for x in self.to_list(self.env['FRAMEWORK']): + self.env.append_value('LINKFLAGS', ['-framework', x]) + +@taskgen +def create_bundle_dirs(self, name, out): + bld = self.bld + dir = out.parent.get_dir(name) + + if not dir: + dir = out.__class__(name, out.parent, 1) + bld.rescan(dir) + contents = out.__class__('Contents', dir, 1) + bld.rescan(contents) + macos = out.__class__('MacOS', contents, 1) + bld.rescan(macos) + return dir + +def bundle_name_for_output(out): + name = out.name + k = name.rfind('.') + if k >= 0: + name = name[:k] + '.app' + else: + name = name + '.app' + return name + +@taskgen +@after('apply_link') +@feature('cprogram') +def create_task_macapp(self): + """Use env['MACAPP'] to force *all* executables to be transformed into Mac applications + or use obj.mac_app = True to build specific targets as Mac apps""" + if self.env['MACAPP'] or getattr(self, 'mac_app', False): + apptask = self.create_task('macapp') + apptask.set_inputs(self.link_task.outputs) + + out = self.link_task.outputs[0] + + name = bundle_name_for_output(out) + dir = self.create_bundle_dirs(name, out) + + n1 = dir.find_or_declare(['Contents', 'MacOS', out.name]) + + apptask.set_outputs([n1]) + apptask.chmod = 0755 + apptask.install_path = os.path.join(self.install_path, name, 'Contents', 'MacOS') + self.apptask = apptask + +@after('apply_link') +@feature('cprogram') +def create_task_macplist(self): + """Use env['MACAPP'] to force *all* executables to be transformed into Mac applications + or use obj.mac_app = True to build specific targets as Mac apps""" + if self.env['MACAPP'] or getattr(self, 'mac_app', False): + # check if the user specified a plist before using our template + if not getattr(self, 'mac_plist', False): + self.mac_plist = app_info + + plisttask = self.create_task('macplist') + plisttask.set_inputs(self.link_task.outputs) + + out = self.link_task.outputs[0] + self.mac_plist = self.mac_plist % (out.name) + + name = bundle_name_for_output(out) + dir = self.create_bundle_dirs(name, out) + + n1 = dir.find_or_declare(['Contents', 'Info.plist']) + + plisttask.set_outputs([n1]) + plisttask.mac_plist = self.mac_plist + plisttask.install_path = os.path.join(self.install_path, name, 'Contents') + self.plisttask = plisttask + +@after('apply_link') +@feature('cshlib') +def apply_link_osx(self): + name = self.link_task.outputs[0].name + if not self.install_path: + return + if getattr(self, 'vnum', None): + name = name.replace('.dylib', '.%s.dylib' % self.vnum) + + path = os.path.join(Utils.subst_vars(self.install_path, self.env), name) + if '-dynamiclib' in self.env['LINKFLAGS']: + self.env.append_value('LINKFLAGS', '-install_name') + self.env.append_value('LINKFLAGS', path) + +@before('apply_link', 'apply_lib_vars') +@feature('cc', 'cxx') +def apply_bundle(self): + """use env['MACBUNDLE'] to force all shlibs into mac bundles + or use obj.mac_bundle = True for specific targets only""" + if not ('cshlib' in self.features or 'shlib' in self.features): return + if self.env['MACBUNDLE'] or getattr(self, 'mac_bundle', False): + self.env['shlib_PATTERN'] = self.env['macbundle_PATTERN'] + uselib = self.uselib = self.to_list(self.uselib) + if not 'MACBUNDLE' in uselib: uselib.append('MACBUNDLE') + +@after('apply_link') +@feature('cshlib') +def apply_bundle_remove_dynamiclib(self): + if self.env['MACBUNDLE'] or getattr(self, 'mac_bundle', False): + if not getattr(self, 'vnum', None): + try: + self.env['LINKFLAGS'].remove('-dynamiclib') + except ValueError: + pass + +# TODO REMOVE IN 1.6 (global variable) +app_dirs = ['Contents', 'Contents/MacOS', 'Contents/Resources'] + +def app_build(task): + env = task.env + shutil.copy2(task.inputs[0].srcpath(env), task.outputs[0].abspath(env)) + + return 0 + +def plist_build(task): + env = task.env + f = open(task.outputs[0].abspath(env), "w") + f.write(task.mac_plist) + f.close() + + return 0 + +Task.task_type_from_func('macapp', vars=[], func=app_build, after="cxx_link cc_link static_link") +Task.task_type_from_func('macplist', vars=[], func=plist_build, after="cxx_link cc_link static_link") + diff --git a/node-v0.8.14/tools/wafadmin/Tools/preproc.py b/node-v0.8.14/tools/wafadmin/Tools/preproc.py new file mode 100644 index 0000000..1a9b0ff --- /dev/null +++ b/node-v0.8.14/tools/wafadmin/Tools/preproc.py @@ -0,0 +1,813 @@ +#!/usr/bin/env python +# encoding: utf-8 +# Thomas Nagy, 2006-2009 (ita) + +""" +C/C++ preprocessor for finding dependencies + +Reasons for using the Waf preprocessor by default +1. Some c/c++ extensions (Qt) require a custom preprocessor for obtaining the dependencies (.moc files) +2. Not all compilers provide .d files for obtaining the dependencies (portability) +3. A naive file scanner will not catch the constructs such as "#include foo()" +4. A naive file scanner will catch unnecessary dependencies (change an unused header -> recompile everything) + +Regarding the speed concerns: +a. the preprocessing is performed only when files must be compiled +b. the macros are evaluated only for #if/#elif/#include +c. the time penalty is about 10% +d. system headers are not scanned + +Now if you do not want the Waf preprocessor, the tool "gccdeps" uses the .d files produced +during the compilation to track the dependencies (useful when used with the boost libraries). +It only works with gcc though, and it cannot be used with Qt builds. A dumb +file scanner will be added in the future, so we will have most bahaviours. +""" +# TODO: more varargs, pragma once +# TODO: dumb file scanner tracking all includes + +import re, sys, os, string +import Logs, Build, Utils +from Logs import debug, error +import traceback + +class PreprocError(Utils.WafError): + pass + +POPFILE = '-' + + +recursion_limit = 100 +"do not loop too much on header inclusion" + +go_absolute = 0 +"set to 1 to track headers on files in /usr/include - else absolute paths are ignored" + +standard_includes = ['/usr/include'] +if sys.platform == "win32": + standard_includes = [] + +use_trigraphs = 0 +'apply the trigraph rules first' + +strict_quotes = 0 +"Keep <> for system includes (do not search for those includes)" + +g_optrans = { +'not':'!', +'and':'&&', +'bitand':'&', +'and_eq':'&=', +'or':'||', +'bitor':'|', +'or_eq':'|=', +'xor':'^', +'xor_eq':'^=', +'compl':'~', +} +"these ops are for c++, to reset, set an empty dict" + +# ignore #warning and #error +re_lines = re.compile(\ + '^[ \t]*(#|%:)[ \t]*(ifdef|ifndef|if|else|elif|endif|include|import|define|undef|pragma)[ \t]*(.*)\r*$', + re.IGNORECASE | re.MULTILINE) + +re_mac = re.compile("^[a-zA-Z_]\w*") +re_fun = re.compile('^[a-zA-Z_][a-zA-Z0-9_]*[(]') +re_pragma_once = re.compile('^\s*once\s*', re.IGNORECASE) +re_nl = re.compile('\\\\\r*\n', re.MULTILINE) +re_cpp = re.compile(\ + r"""(/\*[^*]*\*+([^/*][^*]*\*+)*/)|//[^\n]*|("(\\.|[^"\\])*"|'(\\.|[^'\\])*'|.[^/"'\\]*)""", + re.MULTILINE) +trig_def = [('??'+a, b) for a, b in zip("=-/!'()<>", r'#~\|^[]{}')] +chr_esc = {'0':0, 'a':7, 'b':8, 't':9, 'n':10, 'f':11, 'v':12, 'r':13, '\\':92, "'":39} + +NUM = 'i' +OP = 'O' +IDENT = 'T' +STR = 's' +CHAR = 'c' + +tok_types = [NUM, STR, IDENT, OP] +exp_types = [ + r"""0[xX](?P[a-fA-F0-9]+)(?P[uUlL]*)|L*?'(?P(\\.|[^\\'])+)'|(?P\d+)[Ee](?P[+-]*?\d+)(?P[fFlL]*)|(?P\d*\.\d+)([Ee](?P[+-]*?\d+))?(?P[fFlL]*)|(?P\d+\.\d*)([Ee](?P[+-]*?\d+))?(?P[fFlL]*)|(?P0*)(?P\d+)(?P[uUlL]*)""", + r'L?"([^"\\]|\\.)*"', + r'[a-zA-Z_]\w*', + r'%:%:|<<=|>>=|\.\.\.|<<|<%|<:|<=|>>|>=|\+\+|\+=|--|->|-=|\*=|/=|%:|%=|%>|==|&&|&=|\|\||\|=|\^=|:>|!=|##|[\(\)\{\}\[\]<>\?\|\^\*\+&=:!#;,%/\-\?\~\.]', +] +re_clexer = re.compile('|'.join(["(?P<%s>%s)" % (name, part) for name, part in zip(tok_types, exp_types)]), re.M) + +accepted = 'a' +ignored = 'i' +undefined = 'u' +skipped = 's' + +def repl(m): + s = m.group(1) + if s is not None: return ' ' + s = m.group(3) + if s is None: return '' + return s + +def filter_comments(filename): + # return a list of tuples : keyword, line + code = Utils.readf(filename) + if use_trigraphs: + for (a, b) in trig_def: code = code.split(a).join(b) + code = re_nl.sub('', code) + code = re_cpp.sub(repl, code) + return [(m.group(2), m.group(3)) for m in re.finditer(re_lines, code)] + +prec = {} +# op -> number, needed for such expressions: #if 1 && 2 != 0 +ops = ['* / %', '+ -', '<< >>', '< <= >= >', '== !=', '& | ^', '&& ||', ','] +for x in range(len(ops)): + syms = ops[x] + for u in syms.split(): + prec[u] = x + +def reduce_nums(val_1, val_2, val_op): + """apply arithmetic rules and try to return an integer result""" + #print val_1, val_2, val_op + + # now perform the operation, make certain a and b are numeric + try: a = 0 + val_1 + except TypeError: a = int(val_1) + try: b = 0 + val_2 + except TypeError: b = int(val_2) + + d = val_op + if d == '%': c = a%b + elif d=='+': c = a+b + elif d=='-': c = a-b + elif d=='*': c = a*b + elif d=='/': c = a/b + elif d=='^': c = a^b + elif d=='|': c = a|b + elif d=='||': c = int(a or b) + elif d=='&': c = a&b + elif d=='&&': c = int(a and b) + elif d=='==': c = int(a == b) + elif d=='!=': c = int(a != b) + elif d=='<=': c = int(a <= b) + elif d=='<': c = int(a < b) + elif d=='>': c = int(a > b) + elif d=='>=': c = int(a >= b) + elif d=='^': c = int(a^b) + elif d=='<<': c = a<>': c = a>>b + else: c = 0 + return c + +def get_num(lst): + if not lst: raise PreprocError("empty list for get_num") + (p, v) = lst[0] + if p == OP: + if v == '(': + count_par = 1 + i = 1 + while i < len(lst): + (p, v) = lst[i] + + if p == OP: + if v == ')': + count_par -= 1 + if count_par == 0: + break + elif v == '(': + count_par += 1 + i += 1 + else: + raise PreprocError("rparen expected %r" % lst) + + (num, _) = get_term(lst[1:i]) + return (num, lst[i+1:]) + + elif v == '+': + return get_num(lst[1:]) + elif v == '-': + num, lst = get_num(lst[1:]) + return (reduce_nums('-1', num, '*'), lst) + elif v == '!': + num, lst = get_num(lst[1:]) + return (int(not int(num)), lst) + elif v == '~': + return (~ int(num), lst) + else: + raise PreprocError("invalid op token %r for get_num" % lst) + elif p == NUM: + return v, lst[1:] + elif p == IDENT: + # all macros should have been replaced, remaining identifiers eval to 0 + return 0, lst[1:] + else: + raise PreprocError("invalid token %r for get_num" % lst) + +def get_term(lst): + if not lst: raise PreprocError("empty list for get_term") + num, lst = get_num(lst) + if not lst: + return (num, []) + (p, v) = lst[0] + if p == OP: + if v == '&&' and not num: + return (num, []) + elif v == '||' and num: + return (num, []) + elif v == ',': + # skip + return get_term(lst[1:]) + elif v == '?': + count_par = 0 + i = 1 + while i < len(lst): + (p, v) = lst[i] + + if p == OP: + if v == ')': + count_par -= 1 + elif v == '(': + count_par += 1 + elif v == ':': + if count_par == 0: + break + i += 1 + else: + raise PreprocError("rparen expected %r" % lst) + + if int(num): + return get_term(lst[1:i]) + else: + return get_term(lst[i+1:]) + + else: + num2, lst = get_num(lst[1:]) + + if not lst: + # no more tokens to process + num2 = reduce_nums(num, num2, v) + return get_term([(NUM, num2)] + lst) + + # operator precedence + p2, v2 = lst[0] + if p2 != OP: + raise PreprocError("op expected %r" % lst) + + if prec[v2] >= prec[v]: + num2 = reduce_nums(num, num2, v) + return get_term([(NUM, num2)] + lst) + else: + num3, lst = get_num(lst[1:]) + num3 = reduce_nums(num2, num3, v2) + return get_term([(NUM, num), (p, v), (NUM, num3)] + lst) + + + raise PreprocError("cannot reduce %r" % lst) + +def reduce_eval(lst): + """take a list of tokens and output true or false (#if/#elif conditions)""" + num, lst = get_term(lst) + return (NUM, num) + +def stringize(lst): + """use for converting a list of tokens to a string""" + lst = [str(v2) for (p2, v2) in lst] + return "".join(lst) + +def paste_tokens(t1, t2): + """ + here is what we can paste: + a ## b -> ab + > ## = -> >= + a ## 2 -> a2 + """ + p1 = None + if t1[0] == OP and t2[0] == OP: + p1 = OP + elif t1[0] == IDENT and (t2[0] == IDENT or t2[0] == NUM): + p1 = IDENT + elif t1[0] == NUM and t2[0] == NUM: + p1 = NUM + if not p1: + raise PreprocError('tokens do not make a valid paste %r and %r' % (t1, t2)) + return (p1, t1[1] + t2[1]) + +def reduce_tokens(lst, defs, ban=[]): + """replace the tokens in lst, using the macros provided in defs, and a list of macros that cannot be re-applied""" + i = 0 + + while i < len(lst): + (p, v) = lst[i] + + if p == IDENT and v == "defined": + del lst[i] + if i < len(lst): + (p2, v2) = lst[i] + if p2 == IDENT: + if v2 in defs: + lst[i] = (NUM, 1) + else: + lst[i] = (NUM, 0) + elif p2 == OP and v2 == '(': + del lst[i] + (p2, v2) = lst[i] + del lst[i] # remove the ident, and change the ) for the value + if v2 in defs: + lst[i] = (NUM, 1) + else: + lst[i] = (NUM, 0) + else: + raise PreprocError("invalid define expression %r" % lst) + + elif p == IDENT and v in defs: + + if isinstance(defs[v], str): + a, b = extract_macro(defs[v]) + defs[v] = b + macro_def = defs[v] + to_add = macro_def[1] + + if isinstance(macro_def[0], list): + # macro without arguments + del lst[i] + for x in xrange(len(to_add)): + lst.insert(i, to_add[x]) + i += 1 + else: + # collect the arguments for the funcall + + args = [] + del lst[i] + + if i >= len(lst): + raise PreprocError("expected '(' after %r (got nothing)" % v) + + (p2, v2) = lst[i] + if p2 != OP or v2 != '(': + raise PreprocError("expected '(' after %r" % v) + + del lst[i] + + one_param = [] + count_paren = 0 + while i < len(lst): + p2, v2 = lst[i] + + del lst[i] + if p2 == OP and count_paren == 0: + if v2 == '(': + one_param.append((p2, v2)) + count_paren += 1 + elif v2 == ')': + if one_param: args.append(one_param) + break + elif v2 == ',': + if not one_param: raise PreprocError("empty param in funcall %s" % p) + args.append(one_param) + one_param = [] + else: + one_param.append((p2, v2)) + else: + one_param.append((p2, v2)) + if v2 == '(': count_paren += 1 + elif v2 == ')': count_paren -= 1 + else: + raise PreprocError('malformed macro') + + # substitute the arguments within the define expression + accu = [] + arg_table = macro_def[0] + j = 0 + while j < len(to_add): + (p2, v2) = to_add[j] + + if p2 == OP and v2 == '#': + # stringize is for arguments only + if j+1 < len(to_add) and to_add[j+1][0] == IDENT and to_add[j+1][1] in arg_table: + toks = args[arg_table[to_add[j+1][1]]] + accu.append((STR, stringize(toks))) + j += 1 + else: + accu.append((p2, v2)) + elif p2 == OP and v2 == '##': + # token pasting, how can man invent such a complicated system? + if accu and j+1 < len(to_add): + # we have at least two tokens + + t1 = accu[-1] + + if to_add[j+1][0] == IDENT and to_add[j+1][1] in arg_table: + toks = args[arg_table[to_add[j+1][1]]] + + if toks: + accu[-1] = paste_tokens(t1, toks[0]) #(IDENT, accu[-1][1] + toks[0][1]) + accu.extend(toks[1:]) + else: + # error, case "a##" + accu.append((p2, v2)) + accu.extend(toks) + elif to_add[j+1][0] == IDENT and to_add[j+1][1] == '__VA_ARGS__': + # TODO not sure + # first collect the tokens + va_toks = [] + st = len(macro_def[0]) + pt = len(args) + for x in args[pt-st+1:]: + va_toks.extend(x) + va_toks.append((OP, ',')) + if va_toks: va_toks.pop() # extra comma + if len(accu)>1: + (p3, v3) = accu[-1] + (p4, v4) = accu[-2] + if v3 == '##': + # remove the token paste + accu.pop() + if v4 == ',' and pt < st: + # remove the comma + accu.pop() + accu += va_toks + else: + accu[-1] = paste_tokens(t1, to_add[j+1]) + + j += 1 + else: + # invalid paste, case "##a" or "b##" + accu.append((p2, v2)) + + elif p2 == IDENT and v2 in arg_table: + toks = args[arg_table[v2]] + reduce_tokens(toks, defs, ban+[v]) + accu.extend(toks) + else: + accu.append((p2, v2)) + + j += 1 + + + reduce_tokens(accu, defs, ban+[v]) + + for x in xrange(len(accu)-1, -1, -1): + lst.insert(i, accu[x]) + + i += 1 + + +def eval_macro(lst, adefs): + """reduce the tokens from the list lst, and try to return a 0/1 result""" + reduce_tokens(lst, adefs, []) + if not lst: raise PreprocError("missing tokens to evaluate") + (p, v) = reduce_eval(lst) + return int(v) != 0 + +def extract_macro(txt): + """process a macro definition from "#define f(x, y) x * y" into a function or a simple macro without arguments""" + t = tokenize(txt) + if re_fun.search(txt): + p, name = t[0] + + p, v = t[1] + if p != OP: raise PreprocError("expected open parenthesis") + + i = 1 + pindex = 0 + params = {} + prev = '(' + + while 1: + i += 1 + p, v = t[i] + + if prev == '(': + if p == IDENT: + params[v] = pindex + pindex += 1 + prev = p + elif p == OP and v == ')': + break + else: + raise PreprocError("unexpected token (3)") + elif prev == IDENT: + if p == OP and v == ',': + prev = v + elif p == OP and v == ')': + break + else: + raise PreprocError("comma or ... expected") + elif prev == ',': + if p == IDENT: + params[v] = pindex + pindex += 1 + prev = p + elif p == OP and v == '...': + raise PreprocError("not implemented (1)") + else: + raise PreprocError("comma or ... expected (2)") + elif prev == '...': + raise PreprocError("not implemented (2)") + else: + raise PreprocError("unexpected else") + + #~ print (name, [params, t[i+1:]]) + return (name, [params, t[i+1:]]) + else: + (p, v) = t[0] + return (v, [[], t[1:]]) + +re_include = re.compile('^\s*(<(?P.*)>|"(?P.*)")') +def extract_include(txt, defs): + """process a line in the form "#include foo" to return a string representing the file""" + m = re_include.search(txt) + if m: + if m.group('a'): return '<', m.group('a') + if m.group('b'): return '"', m.group('b') + + # perform preprocessing and look at the result, it must match an include + toks = tokenize(txt) + reduce_tokens(toks, defs, ['waf_include']) + + if not toks: + raise PreprocError("could not parse include %s" % txt) + + if len(toks) == 1: + if toks[0][0] == STR: + return '"', toks[0][1] + else: + if toks[0][1] == '<' and toks[-1][1] == '>': + return stringize(toks).lstrip('<').rstrip('>') + + raise PreprocError("could not parse include %s." % txt) + +def parse_char(txt): + if not txt: raise PreprocError("attempted to parse a null char") + if txt[0] != '\\': + return ord(txt) + c = txt[1] + if c == 'x': + if len(txt) == 4 and txt[3] in string.hexdigits: return int(txt[2:], 16) + return int(txt[2:], 16) + elif c.isdigit(): + if c == '0' and len(txt)==2: return 0 + for i in 3, 2, 1: + if len(txt) > i and txt[1:1+i].isdigit(): + return (1+i, int(txt[1:1+i], 8)) + else: + try: return chr_esc[c] + except KeyError: raise PreprocError("could not parse char literal '%s'" % txt) + +def tokenize(s): + """convert a string into a list of tokens (shlex.split does not apply to c/c++/d)""" + ret = [] + for match in re_clexer.finditer(s): + m = match.group + for name in tok_types: + v = m(name) + if v: + if name == IDENT: + try: v = g_optrans[v]; name = OP + except KeyError: + # c++ specific + if v.lower() == "true": + v = 1 + name = NUM + elif v.lower() == "false": + v = 0 + name = NUM + elif name == NUM: + if m('oct'): v = int(v, 8) + elif m('hex'): v = int(m('hex'), 16) + elif m('n0'): v = m('n0') + else: + v = m('char') + if v: v = parse_char(v) + else: v = m('n2') or m('n4') + elif name == OP: + if v == '%:': v = '#' + elif v == '%:%:': v = '##' + elif name == STR: + # remove the quotes around the string + v = v[1:-1] + ret.append((name, v)) + break + return ret + +class c_parser(object): + def __init__(self, nodepaths=None, defines=None): + #self.lines = txt.split('\n') + self.lines = [] + + if defines is None: + self.defs = {} + else: + self.defs = dict(defines) # make a copy + self.state = [] + + self.env = None # needed for the variant when searching for files + + self.count_files = 0 + self.currentnode_stack = [] + + self.nodepaths = nodepaths or [] + + self.nodes = [] + self.names = [] + + # file added + self.curfile = '' + self.ban_includes = [] + + def tryfind(self, filename): + self.curfile = filename + + # for msvc it should be a for loop on the whole stack + found = self.currentnode_stack[-1].find_resource(filename) + + for n in self.nodepaths: + if found: + break + found = n.find_resource(filename) + + if not found: + if not filename in self.names: + self.names.append(filename) + else: + self.nodes.append(found) + if filename[-4:] != '.moc': + self.addlines(found) + return found + + def addlines(self, node): + + self.currentnode_stack.append(node.parent) + filepath = node.abspath(self.env) + + self.count_files += 1 + if self.count_files > recursion_limit: raise PreprocError("recursion limit exceeded") + pc = self.parse_cache + debug('preproc: reading file %r', filepath) + try: + lns = pc[filepath] + except KeyError: + pass + else: + self.lines = lns + self.lines + return + + try: + lines = filter_comments(filepath) + lines.append((POPFILE, '')) + pc[filepath] = lines # cache the lines filtered + self.lines = lines + self.lines + except IOError: + raise PreprocError("could not read the file %s" % filepath) + except Exception: + if Logs.verbose > 0: + error("parsing %s failed" % filepath) + traceback.print_exc() + + def start(self, node, env): + debug('preproc: scanning %s (in %s)', node.name, node.parent.name) + + self.env = env + variant = node.variant(env) + bld = node.__class__.bld + try: + self.parse_cache = bld.parse_cache + except AttributeError: + bld.parse_cache = {} + self.parse_cache = bld.parse_cache + + self.addlines(node) + if env['DEFLINES']: + self.lines = [('define', x) for x in env['DEFLINES']] + self.lines + + while self.lines: + (kind, line) = self.lines.pop(0) + if kind == POPFILE: + self.currentnode_stack.pop() + continue + try: + self.process_line(kind, line) + except Exception, e: + if Logs.verbose: + debug('preproc: line parsing failed (%s): %s %s', e, line, Utils.ex_stack()) + + def process_line(self, token, line): + ve = Logs.verbose + if ve: debug('preproc: line is %s - %s state is %s', token, line, self.state) + state = self.state + + # make certain we define the state if we are about to enter in an if block + if token in ['ifdef', 'ifndef', 'if']: + state.append(undefined) + elif token == 'endif': + state.pop() + + # skip lines when in a dead 'if' branch, wait for the endif + if not token in ['else', 'elif', 'endif']: + if skipped in self.state or ignored in self.state: + return + + if token == 'if': + ret = eval_macro(tokenize(line), self.defs) + if ret: state[-1] = accepted + else: state[-1] = ignored + elif token == 'ifdef': + m = re_mac.search(line) + if m and m.group(0) in self.defs: state[-1] = accepted + else: state[-1] = ignored + elif token == 'ifndef': + m = re_mac.search(line) + if m and m.group(0) in self.defs: state[-1] = ignored + else: state[-1] = accepted + elif token == 'include' or token == 'import': + (kind, inc) = extract_include(line, self.defs) + if inc in self.ban_includes: return + if token == 'import': self.ban_includes.append(inc) + if ve: debug('preproc: include found %s (%s) ', inc, kind) + if kind == '"' or not strict_quotes: + self.tryfind(inc) + elif token == 'elif': + if state[-1] == accepted: + state[-1] = skipped + elif state[-1] == ignored: + if eval_macro(tokenize(line), self.defs): + state[-1] = accepted + elif token == 'else': + if state[-1] == accepted: state[-1] = skipped + elif state[-1] == ignored: state[-1] = accepted + elif token == 'define': + m = re_mac.search(line) + if m: + name = m.group(0) + if ve: debug('preproc: define %s %s', name, line) + self.defs[name] = line + else: + raise PreprocError("invalid define line %s" % line) + elif token == 'undef': + m = re_mac.search(line) + if m and m.group(0) in self.defs: + self.defs.__delitem__(m.group(0)) + #print "undef %s" % name + elif token == 'pragma': + if re_pragma_once.search(line.lower()): + self.ban_includes.append(self.curfile) + +def get_deps(node, env, nodepaths=[]): + """ + Get the dependencies using a c/c++ preprocessor, this is required for finding dependencies of the kind + #include some_macro() + """ + + gruik = c_parser(nodepaths) + gruik.start(node, env) + return (gruik.nodes, gruik.names) + +#################### dumb dependency scanner + +re_inc = re.compile(\ + '^[ \t]*(#|%:)[ \t]*(include)[ \t]*(.*)\r*$', + re.IGNORECASE | re.MULTILINE) + +def lines_includes(filename): + code = Utils.readf(filename) + if use_trigraphs: + for (a, b) in trig_def: code = code.split(a).join(b) + code = re_nl.sub('', code) + code = re_cpp.sub(repl, code) + return [(m.group(2), m.group(3)) for m in re.finditer(re_inc, code)] + +def get_deps_simple(node, env, nodepaths=[], defines={}): + """ + Get the dependencies by just looking recursively at the #include statements + """ + + nodes = [] + names = [] + + def find_deps(node): + lst = lines_includes(node.abspath(env)) + + for (_, line) in lst: + (t, filename) = extract_include(line, defines) + if filename in names: + continue + + if filename.endswith('.moc'): + names.append(filename) + + found = None + for n in nodepaths: + if found: + break + found = n.find_resource(filename) + + if not found: + if not filename in names: + names.append(filename) + elif not found in nodes: + nodes.append(found) + find_deps(node) + + find_deps(node) + return (nodes, names) + + diff --git a/node-v0.8.14/tools/wafadmin/Tools/python.py b/node-v0.8.14/tools/wafadmin/Tools/python.py new file mode 100644 index 0000000..e9f9048 --- /dev/null +++ b/node-v0.8.14/tools/wafadmin/Tools/python.py @@ -0,0 +1,401 @@ +#!/usr/bin/env python +# encoding: utf-8 +# Thomas Nagy, 2007 (ita) +# Gustavo Carneiro (gjc), 2007 + +"Python support" + +import os, sys +import TaskGen, Utils, Utils, Runner, Options, Build +from Logs import debug, warn, info +from TaskGen import extension, taskgen, before, after, feature +from Configure import conf + +EXT_PY = ['.py'] +FRAG_2 = ''' +#ifdef __cplusplus +extern "C" { +#endif + void Py_Initialize(void); + void Py_Finalize(void); +#ifdef __cplusplus +} +#endif +int main() +{ + Py_Initialize(); + Py_Finalize(); + return 0; +} +''' + +@before('apply_incpaths', 'apply_lib_vars', 'apply_type_vars') +@feature('pyext') +@before('apply_bundle') +def init_pyext(self): + self.default_install_path = '${PYTHONDIR}' + self.uselib = self.to_list(getattr(self, 'uselib', '')) + if not 'PYEXT' in self.uselib: + self.uselib.append('PYEXT') + self.env['MACBUNDLE'] = True + +@before('apply_link', 'apply_lib_vars', 'apply_type_vars') +@after('apply_bundle') +@feature('pyext') +def pyext_shlib_ext(self): + # override shlib_PATTERN set by the osx module + self.env['shlib_PATTERN'] = self.env['pyext_PATTERN'] + +@before('apply_incpaths', 'apply_lib_vars', 'apply_type_vars') +@feature('pyembed') +def init_pyembed(self): + self.uselib = self.to_list(getattr(self, 'uselib', '')) + if not 'PYEMBED' in self.uselib: + self.uselib.append('PYEMBED') + +@extension(EXT_PY) +def process_py(self, node): + if not (self.bld.is_install and self.install_path): + return + def inst_py(ctx): + install_pyfile(self, node) + self.bld.add_post_fun(inst_py) + +def install_pyfile(self, node): + path = self.bld.get_install_path(self.install_path + os.sep + node.name, self.env) + + self.bld.install_files(self.install_path, [node], self.env, self.chmod, postpone=False) + if self.bld.is_install < 0: + info("* removing byte compiled python files") + for x in 'co': + try: + os.remove(path + x) + except OSError: + pass + + if self.bld.is_install > 0: + if self.env['PYC'] or self.env['PYO']: + info("* byte compiling %r" % path) + + if self.env['PYC']: + program = (""" +import sys, py_compile +for pyfile in sys.argv[1:]: + py_compile.compile(pyfile, pyfile + 'c') +""") + argv = [self.env['PYTHON'], '-c', program, path] + ret = Utils.pproc.Popen(argv).wait() + if ret: + raise Utils.WafError('bytecode compilation failed %r' % path) + + if self.env['PYO']: + program = (""" +import sys, py_compile +for pyfile in sys.argv[1:]: + py_compile.compile(pyfile, pyfile + 'o') +""") + argv = [self.env['PYTHON'], self.env['PYFLAGS_OPT'], '-c', program, path] + ret = Utils.pproc.Popen(argv).wait() + if ret: + raise Utils.WafError('bytecode compilation failed %r' % path) + +# COMPAT +class py_taskgen(TaskGen.task_gen): + def __init__(self, *k, **kw): + TaskGen.task_gen.__init__(self, *k, **kw) + +@before('apply_core') +@after('vars_target_cprogram', 'vars_target_cstaticlib') +@feature('py') +def init_py(self): + self.default_install_path = '${PYTHONDIR}' + +def _get_python_variables(python_exe, variables, imports=['import sys']): + """Run a python interpreter and print some variables""" + program = list(imports) + program.append('') + for v in variables: + program.append("print(repr(%s))" % v) + os_env = dict(os.environ) + try: + del os_env['MACOSX_DEPLOYMENT_TARGET'] # see comments in the OSX tool + except KeyError: + pass + proc = Utils.pproc.Popen([python_exe, "-c", '\n'.join(program)], stdout=Utils.pproc.PIPE, env=os_env) + output = proc.communicate()[0].split("\n") # do not touch, python3 + if proc.returncode: + if Options.options.verbose: + warn("Python program to extract python configuration variables failed:\n%s" + % '\n'.join(["line %03i: %s" % (lineno+1, line) for lineno, line in enumerate(program)])) + raise RuntimeError + return_values = [] + for s in output: + s = s.strip() + if not s: + continue + if s == 'None': + return_values.append(None) + elif s[0] == "'" and s[-1] == "'": + return_values.append(s[1:-1]) + elif s[0].isdigit(): + return_values.append(int(s)) + else: break + return return_values + +@conf +def check_python_headers(conf): + """Check for headers and libraries necessary to extend or embed python. + + On success the environment variables xxx_PYEXT and xxx_PYEMBED are added for uselib + + PYEXT: for compiling python extensions + PYEMBED: for embedding a python interpreter""" + + if not conf.env['CC_NAME'] and not conf.env['CXX_NAME']: + conf.fatal('load a compiler first (gcc, g++, ..)') + + if not conf.env['PYTHON_VERSION']: + conf.check_python_version() + + env = conf.env + python = env['PYTHON'] + if not python: + conf.fatal('could not find the python executable') + + ## On Mac OSX we need to use mac bundles for python plugins + if Options.platform == 'darwin': + conf.check_tool('osx') + + try: + # Get some python configuration variables using distutils + v = 'prefix SO SYSLIBS LDFLAGS SHLIBS LIBDIR LIBPL INCLUDEPY Py_ENABLE_SHARED MACOSX_DEPLOYMENT_TARGET'.split() + (python_prefix, python_SO, python_SYSLIBS, python_LDFLAGS, python_SHLIBS, + python_LIBDIR, python_LIBPL, INCLUDEPY, Py_ENABLE_SHARED, + python_MACOSX_DEPLOYMENT_TARGET) = \ + _get_python_variables(python, ["get_config_var('%s')" % x for x in v], + ['from distutils.sysconfig import get_config_var']) + except RuntimeError: + conf.fatal("Python development headers not found (-v for details).") + + conf.log.write("""Configuration returned from %r: +python_prefix = %r +python_SO = %r +python_SYSLIBS = %r +python_LDFLAGS = %r +python_SHLIBS = %r +python_LIBDIR = %r +python_LIBPL = %r +INCLUDEPY = %r +Py_ENABLE_SHARED = %r +MACOSX_DEPLOYMENT_TARGET = %r +""" % (python, python_prefix, python_SO, python_SYSLIBS, python_LDFLAGS, python_SHLIBS, + python_LIBDIR, python_LIBPL, INCLUDEPY, Py_ENABLE_SHARED, python_MACOSX_DEPLOYMENT_TARGET)) + + if python_MACOSX_DEPLOYMENT_TARGET: + conf.env['MACOSX_DEPLOYMENT_TARGET'] = python_MACOSX_DEPLOYMENT_TARGET + conf.environ['MACOSX_DEPLOYMENT_TARGET'] = python_MACOSX_DEPLOYMENT_TARGET + + env['pyext_PATTERN'] = '%s'+python_SO + + # Check for python libraries for embedding + if python_SYSLIBS is not None: + for lib in python_SYSLIBS.split(): + if lib.startswith('-l'): + lib = lib[2:] # strip '-l' + env.append_value('LIB_PYEMBED', lib) + + if python_SHLIBS is not None: + for lib in python_SHLIBS.split(): + if lib.startswith('-l'): + env.append_value('LIB_PYEMBED', lib[2:]) # strip '-l' + else: + env.append_value('LINKFLAGS_PYEMBED', lib) + + if Options.platform != 'darwin' and python_LDFLAGS: + env.append_value('LINKFLAGS_PYEMBED', python_LDFLAGS.split()) + + result = False + name = 'python' + env['PYTHON_VERSION'] + + if python_LIBDIR is not None: + path = [python_LIBDIR] + conf.log.write("\n\n# Trying LIBDIR: %r\n" % path) + result = conf.check(lib=name, uselib='PYEMBED', libpath=path) + + if not result and python_LIBPL is not None: + conf.log.write("\n\n# try again with -L$python_LIBPL (some systems don't install the python library in $prefix/lib)\n") + path = [python_LIBPL] + result = conf.check(lib=name, uselib='PYEMBED', libpath=path) + + if not result: + conf.log.write("\n\n# try again with -L$prefix/libs, and pythonXY name rather than pythonX.Y (win32)\n") + path = [os.path.join(python_prefix, "libs")] + name = 'python' + env['PYTHON_VERSION'].replace('.', '') + result = conf.check(lib=name, uselib='PYEMBED', libpath=path) + + if result: + env['LIBPATH_PYEMBED'] = path + env.append_value('LIB_PYEMBED', name) + else: + conf.log.write("\n\n### LIB NOT FOUND\n") + + # under certain conditions, python extensions must link to + # python libraries, not just python embedding programs. + if (sys.platform == 'win32' or sys.platform.startswith('os2') + or sys.platform == 'darwin' or Py_ENABLE_SHARED): + env['LIBPATH_PYEXT'] = env['LIBPATH_PYEMBED'] + env['LIB_PYEXT'] = env['LIB_PYEMBED'] + + # We check that pythonX.Y-config exists, and if it exists we + # use it to get only the includes, else fall back to distutils. + python_config = conf.find_program( + 'python%s-config' % ('.'.join(env['PYTHON_VERSION'].split('.')[:2])), + var='PYTHON_CONFIG') + if not python_config: + python_config = conf.find_program( + 'python-config-%s' % ('.'.join(env['PYTHON_VERSION'].split('.')[:2])), + var='PYTHON_CONFIG') + + includes = [] + if python_config: + for incstr in Utils.cmd_output("%s %s --includes" % (python, python_config)).strip().split(): + # strip the -I or /I + if (incstr.startswith('-I') + or incstr.startswith('/I')): + incstr = incstr[2:] + # append include path, unless already given + if incstr not in includes: + includes.append(incstr) + conf.log.write("Include path for Python extensions " + "(found via python-config --includes): %r\n" % (includes,)) + env['CPPPATH_PYEXT'] = includes + env['CPPPATH_PYEMBED'] = includes + else: + conf.log.write("Include path for Python extensions " + "(found via distutils module): %r\n" % (INCLUDEPY,)) + env['CPPPATH_PYEXT'] = [INCLUDEPY] + env['CPPPATH_PYEMBED'] = [INCLUDEPY] + + # Code using the Python API needs to be compiled with -fno-strict-aliasing + if env['CC_NAME'] == 'gcc': + env.append_value('CCFLAGS_PYEMBED', '-fno-strict-aliasing') + env.append_value('CCFLAGS_PYEXT', '-fno-strict-aliasing') + if env['CXX_NAME'] == 'gcc': + env.append_value('CXXFLAGS_PYEMBED', '-fno-strict-aliasing') + env.append_value('CXXFLAGS_PYEXT', '-fno-strict-aliasing') + + # See if it compiles + conf.check(header_name='Python.h', define_name='HAVE_PYTHON_H', + uselib='PYEMBED', fragment=FRAG_2, + errmsg='Could not find the python development headers', mandatory=1) + +@conf +def check_python_version(conf, minver=None): + """ + Check if the python interpreter is found matching a given minimum version. + minver should be a tuple, eg. to check for python >= 2.4.2 pass (2,4,2) as minver. + + If successful, PYTHON_VERSION is defined as 'MAJOR.MINOR' + (eg. '2.4') of the actual python version found, and PYTHONDIR is + defined, pointing to the site-packages directory appropriate for + this python version, where modules/packages/extensions should be + installed. + """ + assert minver is None or isinstance(minver, tuple) + python = conf.env['PYTHON'] + if not python: + conf.fatal('could not find the python executable') + + # Get python version string + cmd = [python, "-c", "import sys\nfor x in sys.version_info: print(str(x))"] + debug('python: Running python command %r' % cmd) + proc = Utils.pproc.Popen(cmd, stdout=Utils.pproc.PIPE) + lines = proc.communicate()[0].split() + assert len(lines) == 5, "found %i lines, expected 5: %r" % (len(lines), lines) + pyver_tuple = (int(lines[0]), int(lines[1]), int(lines[2]), lines[3], int(lines[4])) + + # compare python version with the minimum required + result = (minver is None) or (pyver_tuple >= minver) + + if result: + # define useful environment variables + pyver = '.'.join([str(x) for x in pyver_tuple[:2]]) + conf.env['PYTHON_VERSION'] = pyver + + if 'PYTHONDIR' in conf.environ: + pydir = conf.environ['PYTHONDIR'] + else: + if sys.platform == 'win32': + (python_LIBDEST, pydir) = \ + _get_python_variables(python, + ["get_config_var('LIBDEST')", + "get_python_lib(standard_lib=0, prefix=%r)" % conf.env['PREFIX']], + ['from distutils.sysconfig import get_config_var, get_python_lib']) + else: + python_LIBDEST = None + (pydir,) = \ + _get_python_variables(python, + ["get_python_lib(standard_lib=0, prefix=%r)" % conf.env['PREFIX']], + ['from distutils.sysconfig import get_config_var, get_python_lib']) + if python_LIBDEST is None: + if conf.env['LIBDIR']: + python_LIBDEST = os.path.join(conf.env['LIBDIR'], "python" + pyver) + else: + python_LIBDEST = os.path.join(conf.env['PREFIX'], "lib", "python" + pyver) + + if hasattr(conf, 'define'): # conf.define is added by the C tool, so may not exist + conf.define('PYTHONDIR', pydir) + conf.env['PYTHONDIR'] = pydir + + # Feedback + pyver_full = '.'.join(map(str, pyver_tuple[:3])) + if minver is None: + conf.check_message_custom('Python version', '', pyver_full) + else: + minver_str = '.'.join(map(str, minver)) + conf.check_message('Python version', ">= %s" % minver_str, result, option=pyver_full) + + if not result: + conf.fatal('The python version is too old (%r)' % pyver_full) + +@conf +def check_python_module(conf, module_name): + """ + Check if the selected python interpreter can import the given python module. + """ + result = not Utils.pproc.Popen([conf.env['PYTHON'], "-c", "import %s" % module_name], + stderr=Utils.pproc.PIPE, stdout=Utils.pproc.PIPE).wait() + conf.check_message('Python module', module_name, result) + if not result: + conf.fatal('Could not find the python module %r' % module_name) + +def detect(conf): + + if not conf.env.PYTHON: + conf.env.PYTHON = sys.executable + + python = conf.find_program('python', var='PYTHON') + if not python: + conf.fatal('Could not find the path of the python executable') + + v = conf.env + + v['PYCMD'] = '"import sys, py_compile;py_compile.compile(sys.argv[1], sys.argv[2])"' + v['PYFLAGS'] = '' + v['PYFLAGS_OPT'] = '-O' + + v['PYC'] = getattr(Options.options, 'pyc', 1) + v['PYO'] = getattr(Options.options, 'pyo', 1) + +def set_options(opt): + opt.add_option('--nopyc', + action='store_false', + default=1, + help = 'Do not install bytecode compiled .pyc files (configuration) [Default:install]', + dest = 'pyc') + opt.add_option('--nopyo', + action='store_false', + default=1, + help='Do not install optimised compiled .pyo files (configuration) [Default:install]', + dest='pyo') + diff --git a/node-v0.8.14/tools/wafadmin/Tools/suncc.py b/node-v0.8.14/tools/wafadmin/Tools/suncc.py new file mode 100644 index 0000000..1387229 --- /dev/null +++ b/node-v0.8.14/tools/wafadmin/Tools/suncc.py @@ -0,0 +1,77 @@ +#!/usr/bin/env python +# encoding: utf-8 +# Thomas Nagy, 2006 (ita) +# Ralf Habacker, 2006 (rh) + +import os, optparse +import Utils, Options, Configure +import ccroot, ar +from Configure import conftest + +@conftest +def find_scc(conf): + v = conf.env + cc = None + if v['CC']: cc = v['CC'] + elif 'CC' in conf.environ: cc = conf.environ['CC'] + #if not cc: cc = conf.find_program('gcc', var='CC') + if not cc: cc = conf.find_program('cc', var='CC') + if not cc: conf.fatal('suncc was not found') + cc = conf.cmd_to_list(cc) + + try: + if not Utils.cmd_output(cc + ['-flags']): + conf.fatal('suncc %r was not found' % cc) + except ValueError: + conf.fatal('suncc -flags could not be executed') + + v['CC'] = cc + v['CC_NAME'] = 'sun' + +@conftest +def scc_common_flags(conf): + v = conf.env + + # CPPFLAGS CCDEFINES _CCINCFLAGS _CCDEFFLAGS + + v['CC_SRC_F'] = '' + v['CC_TGT_F'] = ['-c', '-o', ''] + v['CPPPATH_ST'] = '-I%s' # template for adding include paths + + # linker + if not v['LINK_CC']: v['LINK_CC'] = v['CC'] + v['CCLNK_SRC_F'] = '' + v['CCLNK_TGT_F'] = ['-o', ''] # solaris hack, separate the -o from the target + + v['LIB_ST'] = '-l%s' # template for adding libs + v['LIBPATH_ST'] = '-L%s' # template for adding libpaths + v['STATICLIB_ST'] = '-l%s' + v['STATICLIBPATH_ST'] = '-L%s' + v['CCDEFINES_ST'] = '-D%s' + + v['SONAME_ST'] = '-Wl,-h -Wl,%s' + v['SHLIB_MARKER'] = '-Bdynamic' + v['STATICLIB_MARKER'] = '-Bstatic' + + # program + v['program_PATTERN'] = '%s' + + # shared library + v['shlib_CCFLAGS'] = ['-Kpic', '-DPIC'] + v['shlib_LINKFLAGS'] = ['-G'] + v['shlib_PATTERN'] = 'lib%s.so' + + # static lib + v['staticlib_LINKFLAGS'] = ['-Bstatic'] + v['staticlib_PATTERN'] = 'lib%s.a' + +detect = ''' +find_scc +find_cpp +find_ar +scc_common_flags +cc_load_tools +cc_add_flags +link_add_flags +''' + diff --git a/node-v0.8.14/tools/wafadmin/Tools/suncxx.py b/node-v0.8.14/tools/wafadmin/Tools/suncxx.py new file mode 100644 index 0000000..b6e9ef8 --- /dev/null +++ b/node-v0.8.14/tools/wafadmin/Tools/suncxx.py @@ -0,0 +1,75 @@ +#!/usr/bin/env python +# encoding: utf-8 +# Thomas Nagy, 2006 (ita) +# Ralf Habacker, 2006 (rh) + +import os, optparse +import Utils, Options, Configure +import ccroot, ar +from Configure import conftest + +@conftest +def find_sxx(conf): + v = conf.env + cc = None + if v['CXX']: cc = v['CXX'] + elif 'CXX' in conf.environ: cc = conf.environ['CXX'] + if not cc: cc = conf.find_program('c++', var='CXX') + if not cc: conf.fatal('sunc++ was not found') + cc = conf.cmd_to_list(cc) + + try: + if not Utils.cmd_output(cc + ['-flags']): + conf.fatal('sunc++ %r was not found' % cc) + except ValueError: + conf.fatal('sunc++ -flags could not be executed') + + v['CXX'] = cc + v['CXX_NAME'] = 'sun' + +@conftest +def sxx_common_flags(conf): + v = conf.env + + # CPPFLAGS CXXDEFINES _CXXINCFLAGS _CXXDEFFLAGS + + v['CXX_SRC_F'] = '' + v['CXX_TGT_F'] = ['-c', '-o', ''] + v['CPPPATH_ST'] = '-I%s' # template for adding include paths + + # linker + if not v['LINK_CXX']: v['LINK_CXX'] = v['CXX'] + v['CXXLNK_SRC_F'] = '' + v['CXXLNK_TGT_F'] = ['-o', ''] # solaris hack, separate the -o from the target + + v['LIB_ST'] = '-l%s' # template for adding libs + v['LIBPATH_ST'] = '-L%s' # template for adding libpaths + v['STATICLIB_ST'] = '-l%s' + v['STATICLIBPATH_ST'] = '-L%s' + v['CXXDEFINES_ST'] = '-D%s' + + v['SONAME_ST'] = '-Wl,-h -Wl,%s' + v['SHLIB_MARKER'] = '-Bdynamic' + v['STATICLIB_MARKER'] = '-Bstatic' + + # program + v['program_PATTERN'] = '%s' + + # shared library + v['shlib_CXXFLAGS'] = ['-Kpic', '-DPIC'] + v['shlib_LINKFLAGS'] = ['-G'] + v['shlib_PATTERN'] = 'lib%s.so' + + # static lib + v['staticlib_LINKFLAGS'] = ['-Bstatic'] + v['staticlib_PATTERN'] = 'lib%s.a' + +detect = ''' +find_sxx +find_cpp +find_ar +sxx_common_flags +cxx_load_tools +cxx_add_flags +''' + diff --git a/node-v0.8.14/tools/wafadmin/Tools/unittestw.py b/node-v0.8.14/tools/wafadmin/Tools/unittestw.py new file mode 100644 index 0000000..b85ccc0 --- /dev/null +++ b/node-v0.8.14/tools/wafadmin/Tools/unittestw.py @@ -0,0 +1,305 @@ +#!/usr/bin/env python +# encoding: utf-8 +# Carlos Rafael Giani, 2006 + +""" +Unit tests run in the shutdown() method, and for c/c++ programs + +One should NOT have to give parameters to programs to execute + +In the shutdown method, add the following code: + + >>> def shutdown(): + ... ut = UnitTest.unit_test() + ... ut.run() + ... ut.print_results() + + +Each object to use as a unit test must be a program and must have X{obj.unit_test=1} +""" +import os, sys +import Build, TaskGen, Utils, Options, Logs, Task +from TaskGen import before, after, feature +from Constants import * + +class unit_test(object): + "Unit test representation" + def __init__(self): + self.returncode_ok = 0 # Unit test returncode considered OK. All returncodes differing from this one + # will cause the unit test to be marked as "FAILED". + + # The following variables are filled with data by run(). + + # print_results() uses these for printing the unit test summary, + # but if there is need for direct access to the results, + # they can be retrieved here, after calling run(). + + self.num_tests_ok = 0 # Number of successful unit tests + self.num_tests_failed = 0 # Number of failed unit tests + self.num_tests_err = 0 # Tests that have not even run + self.total_num_tests = 0 # Total amount of unit tests + self.max_label_length = 0 # Maximum label length (pretty-print the output) + + self.unit_tests = Utils.ordered_dict() # Unit test dictionary. Key: the label (unit test filename relative + # to the build dir), value: unit test filename with absolute path + self.unit_test_results = {} # Dictionary containing the unit test results. + # Key: the label, value: result (true = success false = failure) + self.unit_test_erroneous = {} # Dictionary indicating erroneous unit tests. + # Key: the label, value: true = unit test has an error false = unit test is ok + self.change_to_testfile_dir = False #True if the test file needs to be executed from the same dir + self.want_to_see_test_output = False #True to see the stdout from the testfile (for example check suites) + self.want_to_see_test_error = False #True to see the stderr from the testfile (for example check suites) + self.run_if_waf_does = 'check' #build was the old default + + def run(self): + "Run the unit tests and gather results (note: no output here)" + + self.num_tests_ok = 0 + self.num_tests_failed = 0 + self.num_tests_err = 0 + self.total_num_tests = 0 + self.max_label_length = 0 + + self.unit_tests = Utils.ordered_dict() + self.unit_test_results = {} + self.unit_test_erroneous = {} + + ld_library_path = [] + + # If waf is not building, don't run anything + if not Options.commands[self.run_if_waf_does]: return + + # Get the paths for the shared libraries, and obtain the unit tests to execute + for obj in Build.bld.all_task_gen: + try: + link_task = obj.link_task + except AttributeError: + pass + else: + lib_path = link_task.outputs[0].parent.abspath(obj.env) + if lib_path not in ld_library_path: + ld_library_path.append(lib_path) + + unit_test = getattr(obj, 'unit_test', '') + if unit_test and 'cprogram' in obj.features: + try: + output = obj.path + filename = os.path.join(output.abspath(obj.env), obj.target) + srcdir = output.abspath() + label = os.path.join(output.bldpath(obj.env), obj.target) + self.max_label_length = max(self.max_label_length, len(label)) + self.unit_tests[label] = (filename, srcdir) + except KeyError: + pass + self.total_num_tests = len(self.unit_tests) + # Now run the unit tests + Utils.pprint('GREEN', 'Running the unit tests') + count = 0 + result = 1 + + for label in self.unit_tests.allkeys: + file_and_src = self.unit_tests[label] + filename = file_and_src[0] + srcdir = file_and_src[1] + count += 1 + line = Build.bld.progress_line(count, self.total_num_tests, Logs.colors.GREEN, Logs.colors.NORMAL) + if Options.options.progress_bar and line: + sys.stderr.write(line) + sys.stderr.flush() + try: + kwargs = {} + kwargs['env'] = os.environ.copy() + if self.change_to_testfile_dir: + kwargs['cwd'] = srcdir + if not self.want_to_see_test_output: + kwargs['stdout'] = Utils.pproc.PIPE # PIPE for ignoring output + if not self.want_to_see_test_error: + kwargs['stderr'] = Utils.pproc.PIPE # PIPE for ignoring output + if ld_library_path: + v = kwargs['env'] + def add_path(dct, path, var): + dct[var] = os.pathsep.join(Utils.to_list(path) + [os.environ.get(var, '')]) + if sys.platform == 'win32': + add_path(v, ld_library_path, 'PATH') + elif sys.platform == 'darwin': + add_path(v, ld_library_path, 'DYLD_LIBRARY_PATH') + add_path(v, ld_library_path, 'LD_LIBRARY_PATH') + else: + add_path(v, ld_library_path, 'LD_LIBRARY_PATH') + + pp = Utils.pproc.Popen(filename, **kwargs) + pp.wait() + + result = int(pp.returncode == self.returncode_ok) + + if result: + self.num_tests_ok += 1 + else: + self.num_tests_failed += 1 + + self.unit_test_results[label] = result + self.unit_test_erroneous[label] = 0 + except OSError: + self.unit_test_erroneous[label] = 1 + self.num_tests_err += 1 + except KeyboardInterrupt: + pass + if Options.options.progress_bar: sys.stdout.write(Logs.colors.cursor_on) + + def print_results(self): + "Pretty-prints a summary of all unit tests, along with some statistics" + + # If waf is not building, don't output anything + if not Options.commands[self.run_if_waf_does]: return + + p = Utils.pprint + # Early quit if no tests were performed + if self.total_num_tests == 0: + p('YELLOW', 'No unit tests present') + return + + for label in self.unit_tests.allkeys: + filename = self.unit_tests[label] + err = 0 + result = 0 + + try: err = self.unit_test_erroneous[label] + except KeyError: pass + + try: result = self.unit_test_results[label] + except KeyError: pass + + n = self.max_label_length - len(label) + if err: n += 4 + elif result: n += 7 + else: n += 3 + + line = '%s %s' % (label, '.' * n) + + if err: p('RED', '%sERROR' % line) + elif result: p('GREEN', '%sOK' % line) + else: p('YELLOW', '%sFAILED' % line) + + percentage_ok = float(self.num_tests_ok) / float(self.total_num_tests) * 100.0 + percentage_failed = float(self.num_tests_failed) / float(self.total_num_tests) * 100.0 + percentage_erroneous = float(self.num_tests_err) / float(self.total_num_tests) * 100.0 + + p('NORMAL', ''' +Successful tests: %i (%.1f%%) +Failed tests: %i (%.1f%%) +Erroneous tests: %i (%.1f%%) + +Total number of tests: %i +''' % (self.num_tests_ok, percentage_ok, self.num_tests_failed, percentage_failed, + self.num_tests_err, percentage_erroneous, self.total_num_tests)) + p('GREEN', 'Unit tests finished') + + +############################################################################################ + +""" +New unit test system + +The targets with feature 'test' are executed after they are built +bld(features='cprogram cc test', ...) + +To display the results: +import UnitTest +bld.add_post_fun(UnitTest.summary) +""" + +import threading +testlock = threading.Lock() + +def set_options(opt): + opt.add_option('--alltests', action='store_true', default=True, help='Exec all unit tests', dest='all_tests') + +@feature('test') +@after('apply_link', 'vars_target_cprogram') +def make_test(self): + if not 'cprogram' in self.features: + Logs.error('test cannot be executed %s' % self) + return + + self.default_install_path = None + self.create_task('utest', self.link_task.outputs) + +def exec_test(self): + + status = 0 + + variant = self.env.variant() + filename = self.inputs[0].abspath(self.env) + + try: + fu = getattr(self.generator.bld, 'all_test_paths') + except AttributeError: + fu = os.environ.copy() + self.generator.bld.all_test_paths = fu + + lst = [] + for obj in self.generator.bld.all_task_gen: + link_task = getattr(obj, 'link_task', None) + if link_task and link_task.env.variant() == variant: + lst.append(link_task.outputs[0].parent.abspath(obj.env)) + + def add_path(dct, path, var): + dct[var] = os.pathsep.join(Utils.to_list(path) + [os.environ.get(var, '')]) + + if sys.platform == 'win32': + add_path(fu, lst, 'PATH') + elif sys.platform == 'darwin': + add_path(fu, lst, 'DYLD_LIBRARY_PATH') + add_path(fu, lst, 'LD_LIBRARY_PATH') + else: + add_path(fu, lst, 'LD_LIBRARY_PATH') + + + cwd = getattr(self.generator, 'ut_cwd', '') or self.inputs[0].parent.abspath(self.env) + proc = Utils.pproc.Popen(filename, cwd=cwd, env=fu, stderr=Utils.pproc.PIPE, stdout=Utils.pproc.PIPE) + (stdout, stderr) = proc.communicate() + + tup = (filename, proc.returncode, stdout, stderr) + self.generator.utest_result = tup + + testlock.acquire() + try: + bld = self.generator.bld + Logs.debug("ut: %r", tup) + try: + bld.utest_results.append(tup) + except AttributeError: + bld.utest_results = [tup] + finally: + testlock.release() + +cls = Task.task_type_from_func('utest', func=exec_test, color='PINK', ext_in='.bin') + +old = cls.runnable_status +def test_status(self): + if getattr(Options.options, 'all_tests', False): + return RUN_ME + return old(self) + +cls.runnable_status = test_status +cls.quiet = 1 + +def summary(bld): + lst = getattr(bld, 'utest_results', []) + if lst: + Utils.pprint('CYAN', 'execution summary') + + total = len(lst) + tfail = len([x for x in lst if x[1]]) + + Utils.pprint('CYAN', ' tests that pass %d/%d' % (total-tfail, total)) + for (f, code, out, err) in lst: + if not code: + Utils.pprint('CYAN', ' %s' % f) + + Utils.pprint('CYAN', ' tests that fail %d/%d' % (tfail, total)) + for (f, code, out, err) in lst: + if code: + Utils.pprint('CYAN', ' %s' % f) + + diff --git a/node-v0.8.14/tools/wafadmin/Tools/winres.py b/node-v0.8.14/tools/wafadmin/Tools/winres.py new file mode 100644 index 0000000..2500d43 --- /dev/null +++ b/node-v0.8.14/tools/wafadmin/Tools/winres.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python +# encoding: utf-8 +# Brant Young, 2007 + +"This hook is called when the class cpp/cc task generator encounters a '.rc' file: X{.rc -> [.res|.rc.o]}" + +import os, sys, re +import TaskGen, Task +from Utils import quote_whitespace +from TaskGen import extension + +EXT_WINRC = ['.rc'] + +winrc_str = '${WINRC} ${_CPPDEFFLAGS} ${_CCDEFFLAGS} ${WINRCFLAGS} ${_CPPINCFLAGS} ${_CCINCFLAGS} ${WINRC_TGT_F} ${TGT} ${WINRC_SRC_F} ${SRC}' + +@extension(EXT_WINRC) +def rc_file(self, node): + obj_ext = '.rc.o' + if self.env['WINRC_TGT_F'] == '/fo': obj_ext = '.res' + + rctask = self.create_task('winrc', node, node.change_ext(obj_ext)) + self.compiled_tasks.append(rctask) + +# create our action, for use with rc file +Task.simple_task_type('winrc', winrc_str, color='BLUE', before='cc cxx', shell=False) + +def detect(conf): + v = conf.env + + winrc = v['WINRC'] + v['WINRC_TGT_F'] = '-o' + v['WINRC_SRC_F'] = '-i' + # find rc.exe + if not winrc: + if v['CC_NAME'] in ['gcc', 'cc', 'g++', 'c++']: + winrc = conf.find_program('windres', var='WINRC', path_list = v['PATH']) + elif v['CC_NAME'] == 'msvc': + winrc = conf.find_program('RC', var='WINRC', path_list = v['PATH']) + v['WINRC_TGT_F'] = '/fo' + v['WINRC_SRC_F'] = '' + if not winrc: + conf.fatal('winrc was not found!') + + v['WINRCFLAGS'] = '' + diff --git a/node-v0.8.14/tools/wafadmin/Tools/xlc.py b/node-v0.8.14/tools/wafadmin/Tools/xlc.py new file mode 100644 index 0000000..e787f7d --- /dev/null +++ b/node-v0.8.14/tools/wafadmin/Tools/xlc.py @@ -0,0 +1,77 @@ +#!/usr/bin/env python +# encoding: utf-8 +# Thomas Nagy, 2006-2008 (ita) +# Ralf Habacker, 2006 (rh) +# Yinon Ehrlich, 2009 +# Michael Kuhn, 2009 + +import os, sys +import Configure, Options, Utils +import ccroot, ar +from Configure import conftest + +@conftest +def find_xlc(conf): + cc = conf.find_program(['xlc_r', 'xlc'], var='CC', mandatory=True) + cc = conf.cmd_to_list(cc) + conf.env.CC_NAME = 'xlc' + conf.env.CC = cc + +@conftest +def find_cpp(conf): + v = conf.env + cpp = None + if v['CPP']: cpp = v['CPP'] + elif 'CPP' in conf.environ: cpp = conf.environ['CPP'] + if not cpp: cpp = v['CC'] + v['CPP'] = cpp + +@conftest +def xlc_common_flags(conf): + v = conf.env + + # CPPFLAGS CCDEFINES _CCINCFLAGS _CCDEFFLAGS + v['CCFLAGS_DEBUG'] = ['-g'] + v['CCFLAGS_RELEASE'] = ['-O2'] + + v['CC_SRC_F'] = '' + v['CC_TGT_F'] = ['-c', '-o', ''] # shell hack for -MD + v['CPPPATH_ST'] = '-I%s' # template for adding include paths + + # linker + if not v['LINK_CC']: v['LINK_CC'] = v['CC'] + v['CCLNK_SRC_F'] = '' + v['CCLNK_TGT_F'] = ['-o', ''] # shell hack for -MD + + v['LIB_ST'] = '-l%s' # template for adding libs + v['LIBPATH_ST'] = '-L%s' # template for adding libpaths + v['STATICLIB_ST'] = '-l%s' + v['STATICLIBPATH_ST'] = '-L%s' + v['RPATH_ST'] = '-Wl,-rpath,%s' + v['CCDEFINES_ST'] = '-D%s' + + v['SONAME_ST'] = '' + v['SHLIB_MARKER'] = '' + v['STATICLIB_MARKER'] = '' + v['FULLSTATIC_MARKER'] = '-static' + + # program + v['program_LINKFLAGS'] = ['-Wl,-brtl'] + v['program_PATTERN'] = '%s' + + # shared library + v['shlib_CCFLAGS'] = ['-fPIC', '-DPIC'] # avoid using -DPIC, -fPIC aleady defines the __PIC__ macro + v['shlib_LINKFLAGS'] = ['-G', '-Wl,-brtl,-bexpfull'] + v['shlib_PATTERN'] = 'lib%s.so' + + # static lib + v['staticlib_LINKFLAGS'] = '' + v['staticlib_PATTERN'] = 'lib%s.a' + +def detect(conf): + conf.find_xlc() + conf.find_cpp() + conf.find_ar() + conf.xlc_common_flags() + conf.cc_load_tools() + conf.cc_add_flags() diff --git a/node-v0.8.14/tools/wafadmin/Tools/xlcxx.py b/node-v0.8.14/tools/wafadmin/Tools/xlcxx.py new file mode 100644 index 0000000..696fcae --- /dev/null +++ b/node-v0.8.14/tools/wafadmin/Tools/xlcxx.py @@ -0,0 +1,77 @@ +#!/usr/bin/env python +# encoding: utf-8 +# Thomas Nagy, 2006 (ita) +# Ralf Habacker, 2006 (rh) +# Yinon Ehrlich, 2009 +# Michael Kuhn, 2009 + +import os, sys +import Configure, Options, Utils +import ccroot, ar +from Configure import conftest + +@conftest +def find_xlcxx(conf): + cxx = conf.find_program(['xlc++_r', 'xlc++'], var='CXX', mandatory=True) + cxx = conf.cmd_to_list(cxx) + conf.env.CXX_NAME = 'xlc++' + conf.env.CXX = cxx + +@conftest +def find_cpp(conf): + v = conf.env + cpp = None + if v['CPP']: cpp = v['CPP'] + elif 'CPP' in conf.environ: cpp = conf.environ['CPP'] + if not cpp: cpp = v['CXX'] + v['CPP'] = cpp + +@conftest +def xlcxx_common_flags(conf): + v = conf.env + + # CPPFLAGS CXXDEFINES _CXXINCFLAGS _CXXDEFFLAGS + v['CXXFLAGS_DEBUG'] = ['-g'] + v['CXXFLAGS_RELEASE'] = ['-O2'] + + v['CXX_SRC_F'] = '' + v['CXX_TGT_F'] = ['-c', '-o', ''] # shell hack for -MD + v['CPPPATH_ST'] = '-I%s' # template for adding include paths + + # linker + if not v['LINK_CXX']: v['LINK_CXX'] = v['CXX'] + v['CXXLNK_SRC_F'] = '' + v['CXXLNK_TGT_F'] = ['-o', ''] # shell hack for -MD + + v['LIB_ST'] = '-l%s' # template for adding libs + v['LIBPATH_ST'] = '-L%s' # template for adding libpaths + v['STATICLIB_ST'] = '-l%s' + v['STATICLIBPATH_ST'] = '-L%s' + v['RPATH_ST'] = '-Wl,-rpath,%s' + v['CXXDEFINES_ST'] = '-D%s' + + v['SONAME_ST'] = '' + v['SHLIB_MARKER'] = '' + v['STATICLIB_MARKER'] = '' + v['FULLSTATIC_MARKER'] = '-static' + + # program + v['program_LINKFLAGS'] = ['-Wl,-brtl'] + v['program_PATTERN'] = '%s' + + # shared library + v['shlib_CXXFLAGS'] = ['-fPIC', '-DPIC'] # avoid using -DPIC, -fPIC aleady defines the __PIC__ macro + v['shlib_LINKFLAGS'] = ['-G', '-Wl,-brtl,-bexpfull'] + v['shlib_PATTERN'] = 'lib%s.so' + + # static lib + v['staticlib_LINKFLAGS'] = '' + v['staticlib_PATTERN'] = 'lib%s.a' + +def detect(conf): + conf.find_xlcxx() + conf.find_cpp() + conf.find_ar() + conf.xlcxx_common_flags() + conf.cxx_load_tools() + conf.cxx_add_flags() diff --git a/node-v0.8.14/tools/wafadmin/Utils.py b/node-v0.8.14/tools/wafadmin/Utils.py new file mode 100644 index 0000000..b86b76f --- /dev/null +++ b/node-v0.8.14/tools/wafadmin/Utils.py @@ -0,0 +1,707 @@ +#!/usr/bin/env python +# encoding: utf-8 +# Thomas Nagy, 2005 (ita) + +""" +Utilities, the stable ones are the following: + +* h_file: compute a unique value for a file (hash), it uses + the module fnv if it is installed (see waf/utils/fnv & http://code.google.com/p/waf/wiki/FAQ) + else, md5 (see the python docs) + + For large projects (projects with more than 15000 files) or slow hard disks and filesystems (HFS) + it is possible to use a hashing based on the path and the size (may give broken cache results) + The method h_file MUST raise an OSError if the file is a folder + + import stat + def h_file(filename): + st = os.stat(filename) + if stat.S_ISDIR(st[stat.ST_MODE]): raise IOError('not a file') + m = Utils.md5() + m.update(str(st.st_mtime)) + m.update(str(st.st_size)) + m.update(filename) + return m.digest() + + To replace the function in your project, use something like this: + import Utils + Utils.h_file = h_file + +* h_list +* h_fun +* get_term_cols +* ordered_dict + +""" + +import os, sys, imp, string, errno, traceback, inspect, re, shutil, datetime, gc + +# In python 3.0 we can get rid of all this +try: from UserDict import UserDict +except ImportError: from collections import UserDict +if sys.hexversion >= 0x2060000 or os.name == 'java': + import subprocess as pproc +else: + import pproc +import Logs +from Constants import * + +try: + from collections import deque +except ImportError: + class deque(list): + def popleft(self): + return self.pop(0) + +is_win32 = sys.platform == 'win32' + +try: + # defaultdict in python 2.5 + from collections import defaultdict as DefaultDict +except ImportError: + class DefaultDict(dict): + def __init__(self, default_factory): + super(DefaultDict, self).__init__() + self.default_factory = default_factory + def __getitem__(self, key): + try: + return super(DefaultDict, self).__getitem__(key) + except KeyError: + value = self.default_factory() + self[key] = value + return value + +class WafError(Exception): + def __init__(self, *args): + self.args = args + try: + self.stack = traceback.extract_stack() + except: + pass + Exception.__init__(self, *args) + def __str__(self): + return str(len(self.args) == 1 and self.args[0] or self.args) + +class WscriptError(WafError): + def __init__(self, message, wscript_file=None): + if wscript_file: + self.wscript_file = wscript_file + self.wscript_line = None + else: + try: + (self.wscript_file, self.wscript_line) = self.locate_error() + except: + (self.wscript_file, self.wscript_line) = (None, None) + + msg_file_line = '' + if self.wscript_file: + msg_file_line = "%s:" % self.wscript_file + if self.wscript_line: + msg_file_line += "%s:" % self.wscript_line + err_message = "%s error: %s" % (msg_file_line, message) + WafError.__init__(self, err_message) + + def locate_error(self): + stack = traceback.extract_stack() + stack.reverse() + for frame in stack: + file_name = os.path.basename(frame[0]) + is_wscript = (file_name == WSCRIPT_FILE or file_name == WSCRIPT_BUILD_FILE) + if is_wscript: + return (frame[0], frame[1]) + return (None, None) + +indicator = is_win32 and '\x1b[A\x1b[K%s%s%s\r' or '\x1b[K%s%s%s\r' + +try: + from fnv import new as md5 + import Constants + Constants.SIG_NIL = 'signofnv' + + def h_file(filename): + m = md5() + try: + m.hfile(filename) + x = m.digest() + if x is None: raise OSError("not a file") + return x + except SystemError: + raise OSError("not a file" + filename) + +except ImportError: + try: + try: + from hashlib import md5 + except ImportError: + from md5 import md5 + + def h_file(filename): + f = open(filename, 'rb') + m = md5() + while (filename): + filename = f.read(100000) + m.update(filename) + f.close() + return m.digest() + except ImportError: + # portability fixes may be added elsewhere (although, md5 should be everywhere by now) + md5 = None + +class ordered_dict(UserDict): + def __init__(self, dict = None): + self.allkeys = [] + UserDict.__init__(self, dict) + + def __delitem__(self, key): + self.allkeys.remove(key) + UserDict.__delitem__(self, key) + + def __setitem__(self, key, item): + if key not in self.allkeys: self.allkeys.append(key) + UserDict.__setitem__(self, key, item) + +def exec_command(s, **kw): + if 'log' in kw: + kw['stdout'] = kw['stderr'] = kw['log'] + del(kw['log']) + kw['shell'] = isinstance(s, str) + + try: + proc = pproc.Popen(s, **kw) + return proc.wait() + except OSError: + return -1 + +if is_win32: + def exec_command(s, **kw): + if 'log' in kw: + kw['stdout'] = kw['stderr'] = kw['log'] + del(kw['log']) + kw['shell'] = isinstance(s, str) + + if len(s) > 2000: + startupinfo = pproc.STARTUPINFO() + startupinfo.dwFlags |= pproc.STARTF_USESHOWWINDOW + kw['startupinfo'] = startupinfo + + try: + if 'stdout' not in kw: + kw['stdout'] = pproc.PIPE + kw['stderr'] = pproc.PIPE + proc = pproc.Popen(s,**kw) + (stdout, stderr) = proc.communicate() + Logs.info(stdout) + if stderr: + Logs.error(stderr) + return proc.returncode + else: + proc = pproc.Popen(s,**kw) + return proc.wait() + except OSError: + return -1 + +listdir = os.listdir +if is_win32: + def listdir_win32(s): + if re.match('^[A-Za-z]:$', s): + # os.path.isdir fails if s contains only the drive name... (x:) + s += os.sep + if not os.path.isdir(s): + e = OSError() + e.errno = errno.ENOENT + raise e + return os.listdir(s) + listdir = listdir_win32 + +def waf_version(mini = 0x010000, maxi = 0x100000): + "Halts if the waf version is wrong" + ver = HEXVERSION + try: min_val = mini + 0 + except TypeError: min_val = int(mini.replace('.', '0'), 16) + + if min_val > ver: + Logs.error("waf version should be at least %s (%s found)" % (mini, ver)) + sys.exit(0) + + try: max_val = maxi + 0 + except TypeError: max_val = int(maxi.replace('.', '0'), 16) + + if max_val < ver: + Logs.error("waf version should be at most %s (%s found)" % (maxi, ver)) + sys.exit(0) + +def python_24_guard(): + if sys.hexversion < 0x20400f0 or sys.hexversion >= 0x3000000: + raise ImportError("Waf requires Python >= 2.3 but the raw source requires Python 2.4, 2.5 or 2.6") + +def ex_stack(): + exc_type, exc_value, tb = sys.exc_info() + if Logs.verbose > 1: + exc_lines = traceback.format_exception(exc_type, exc_value, tb) + return ''.join(exc_lines) + return str(exc_value) + +def to_list(sth): + if isinstance(sth, str): + return sth.split() + else: + return sth + +g_loaded_modules = {} +"index modules by absolute path" + +g_module=None +"the main module is special" + +def load_module(file_path, name=WSCRIPT_FILE): + "this function requires an absolute path" + try: + return g_loaded_modules[file_path] + except KeyError: + pass + + module = imp.new_module(name) + + try: + code = readf(file_path, m='rU') + except (IOError, OSError): + raise WscriptError('Could not read the file %r' % file_path) + + module.waf_hash_val = code + + sys.path.insert(0, os.path.dirname(file_path)) + try: + exec(compile(code, file_path, 'exec'), module.__dict__) + except Exception: + exc_type, exc_value, tb = sys.exc_info() + raise WscriptError("".join(traceback.format_exception(exc_type, exc_value, tb)), file_path) + sys.path.pop(0) + + g_loaded_modules[file_path] = module + + return module + +def set_main_module(file_path): + "Load custom options, if defined" + global g_module + g_module = load_module(file_path, 'wscript_main') + g_module.root_path = file_path + + try: + g_module.APPNAME + except: + g_module.APPNAME = 'noname' + try: + g_module.VERSION + except: + g_module.VERSION = '1.0' + + # note: to register the module globally, use the following: + # sys.modules['wscript_main'] = g_module + +def to_hashtable(s): + "used for importing env files" + tbl = {} + lst = s.split('\n') + for line in lst: + if not line: continue + mems = line.split('=') + tbl[mems[0]] = mems[1] + return tbl + +def get_term_cols(): + "console width" + return 80 +try: + import struct, fcntl, termios +except ImportError: + pass +else: + if Logs.got_tty: + def myfun(): + dummy_lines, cols = struct.unpack("HHHH", \ + fcntl.ioctl(sys.stderr.fileno(),termios.TIOCGWINSZ , \ + struct.pack("HHHH", 0, 0, 0, 0)))[:2] + return cols + # we actually try the function once to see if it is suitable + try: + myfun() + except: + pass + else: + get_term_cols = myfun + +rot_idx = 0 +rot_chr = ['\\', '|', '/', '-'] +"the rotation character in the progress bar" + + +def split_path(path): + return path.split('/') + +def split_path_cygwin(path): + if path.startswith('//'): + ret = path.split('/')[2:] + ret[0] = '/' + ret[0] + return ret + return path.split('/') + +re_sp = re.compile('[/\\\\]') +def split_path_win32(path): + if path.startswith('\\\\'): + ret = re.split(re_sp, path)[2:] + ret[0] = '\\' + ret[0] + return ret + return re.split(re_sp, path) + +if sys.platform == 'cygwin': + split_path = split_path_cygwin +elif is_win32: + split_path = split_path_win32 + +def copy_attrs(orig, dest, names, only_if_set=False): + for a in to_list(names): + u = getattr(orig, a, ()) + if u or not only_if_set: + setattr(dest, a, u) + +def def_attrs(cls, **kw): + ''' + set attributes for class. + @param cls [any class]: the class to update the given attributes in. + @param kw [dictionary]: dictionary of attributes names and values. + + if the given class hasn't one (or more) of these attributes, add the attribute with its value to the class. + ''' + for k, v in kw.iteritems(): + if not hasattr(cls, k): + setattr(cls, k, v) + +def quote_define_name(path): + fu = re.compile("[^a-zA-Z0-9]").sub("_", path) + fu = fu.upper() + return fu + +def quote_whitespace(path): + return (path.strip().find(' ') > 0 and '"%s"' % path or path).replace('""', '"') + +def trimquotes(s): + if not s: return '' + s = s.rstrip() + if s[0] == "'" and s[-1] == "'": return s[1:-1] + return s + +def h_list(lst): + m = md5() + m.update(str(lst)) + return m.digest() + +def h_fun(fun): + try: + return fun.code + except AttributeError: + try: + h = inspect.getsource(fun) + except IOError: + h = "nocode" + try: + fun.code = h + except AttributeError: + pass + return h + +def pprint(col, str, label='', sep=os.linesep): + "print messages in color" + sys.stderr.write("%s%s%s %s%s" % (Logs.colors(col), str, Logs.colors.NORMAL, label, sep)) + +def check_dir(dir): + """If a folder doesn't exists, create it.""" + try: + os.stat(dir) + except OSError: + try: + os.makedirs(dir) + except OSError, e: + raise WafError("Cannot create folder '%s' (original error: %s)" % (dir, e)) + +def cmd_output(cmd, **kw): + + silent = False + if 'silent' in kw: + silent = kw['silent'] + del(kw['silent']) + + if 'e' in kw: + tmp = kw['e'] + del(kw['e']) + kw['env'] = tmp + + kw['shell'] = isinstance(cmd, str) + kw['stdout'] = pproc.PIPE + if silent: + kw['stderr'] = pproc.PIPE + + try: + p = pproc.Popen(cmd, **kw) + output = p.communicate()[0] + except OSError, e: + raise ValueError(str(e)) + + if p.returncode: + if not silent: + msg = "command execution failed: %s -> %r" % (cmd, str(output)) + raise ValueError(msg) + output = '' + return output + +reg_subst = re.compile(r"(\\\\)|(\$\$)|\$\{([^}]+)\}") +def subst_vars(expr, params): + "substitute ${PREFIX}/bin in /usr/local/bin" + def repl_var(m): + if m.group(1): + return '\\' + if m.group(2): + return '$' + try: + # environments may contain lists + return params.get_flat(m.group(3)) + except AttributeError: + return params[m.group(3)] + return reg_subst.sub(repl_var, expr) + +def unversioned_sys_platform_to_binary_format(unversioned_sys_platform): + "infers the binary format from the unversioned_sys_platform name." + + if unversioned_sys_platform in ('linux', 'freebsd', 'netbsd', 'openbsd', 'sunos'): + return 'elf' + elif unversioned_sys_platform == 'darwin': + return 'mac-o' + elif unversioned_sys_platform in ('win32', 'cygwin', 'uwin', 'msys'): + return 'pe' + # TODO we assume all other operating systems are elf, which is not true. + # we may set this to 'unknown' and have ccroot and other tools handle the case "gracefully" (whatever that means). + return 'elf' + +def unversioned_sys_platform(): + """returns an unversioned name from sys.platform. + sys.plaform is not very well defined and depends directly on the python source tree. + The version appended to the names is unreliable as it's taken from the build environment at the time python was built, + i.e., it's possible to get freebsd7 on a freebsd8 system. + So we remove the version from the name, except for special cases where the os has a stupid name like os2 or win32. + Some possible values of sys.platform are, amongst others: + aix3 aix4 atheos beos5 darwin freebsd2 freebsd3 freebsd4 freebsd5 freebsd6 freebsd7 + generic irix5 irix6 linux2 mac netbsd1 next3 os2emx riscos sunos5 unixware7 + Investigating the python source tree may reveal more values. + """ + s = sys.platform + if s == 'java': + # The real OS is hidden under the JVM. + from java.lang import System + s = System.getProperty('os.name') + # see http://lopica.sourceforge.net/os.html for a list of possible values + if s == 'Mac OS X': + return 'darwin' + elif s.startswith('Windows '): + return 'win32' + elif s == 'OS/2': + return 'os2' + elif s == 'HP-UX': + return 'hpux' + elif s in ('SunOS', 'Solaris'): + return 'sunos' + else: s = s.lower() + if s == 'win32' or s.endswith('os2') and s != 'sunos2': return s + return re.split('\d+$', s)[0] + +#@deprecated('use unversioned_sys_platform instead') +def detect_platform(): + """this function has been in the Utils module for some time. + It's hard to guess what people have used it for. + It seems its goal is to return an unversionned sys.platform, but it's not handling all platforms. + For example, the version is not removed on freebsd and netbsd, amongst others. + """ + s = sys.platform + + # known POSIX + for x in 'cygwin linux irix sunos hpux aix darwin'.split(): + # sys.platform may be linux2 + if s.find(x) >= 0: + return x + + # unknown POSIX + if os.name in 'posix java os2'.split(): + return os.name + + return s + +def load_tool(tool, tooldir=None): + ''' + load_tool: import a Python module, optionally using several directories. + @param tool [string]: name of tool to import. + @param tooldir [list]: directories to look for the tool. + @return: the loaded module. + + Warning: this function is not thread-safe: plays with sys.path, + so must run in sequence. + ''' + if tooldir: + assert isinstance(tooldir, list) + sys.path = tooldir + sys.path + try: + try: + return __import__(tool) + except ImportError, e: + Logs.error('Could not load the tool %r in %r:\n%s' % (tool, sys.path, e)) + raise + finally: + if tooldir: + sys.path = sys.path[len(tooldir):] + +def readf(fname, m='r'): + "get the contents of a file, it is not used anywhere for the moment" + f = open(fname, m) + try: + txt = f.read() + finally: + f.close() + return txt + +def nada(*k, **kw): + """A function that does nothing""" + pass + +def diff_path(top, subdir): + """difference between two absolute paths""" + top = os.path.normpath(top).replace('\\', '/').split('/') + subdir = os.path.normpath(subdir).replace('\\', '/').split('/') + if len(top) == len(subdir): return '' + diff = subdir[len(top) - len(subdir):] + return os.path.join(*diff) + +class Context(object): + """A base class for commands to be executed from Waf scripts""" + + def set_curdir(self, dir): + self.curdir_ = dir + + def get_curdir(self): + try: + return self.curdir_ + except AttributeError: + self.curdir_ = os.getcwd() + return self.get_curdir() + + curdir = property(get_curdir, set_curdir) + + def recurse(self, dirs, name=''): + """The function for calling scripts from folders, it tries to call wscript + function_name + and if that file does not exist, it will call the method 'function_name' from a file named wscript + the dirs can be a list of folders or a string containing space-separated folder paths + """ + if not name: + name = inspect.stack()[1][3] + + if isinstance(dirs, str): + dirs = to_list(dirs) + + for x in dirs: + if os.path.isabs(x): + nexdir = x + else: + nexdir = os.path.join(self.curdir, x) + + base = os.path.join(nexdir, WSCRIPT_FILE) + file_path = base + '_' + name + + try: + txt = readf(file_path, m='rU') + except (OSError, IOError): + try: + module = load_module(base) + except OSError: + raise WscriptError('No such script %s' % base) + + try: + f = module.__dict__[name] + except KeyError: + raise WscriptError('No function %s defined in %s' % (name, base)) + + if getattr(self.__class__, 'pre_recurse', None): + self.pre_recurse(f, base, nexdir) + old = self.curdir + self.curdir = nexdir + try: + f(self) + finally: + self.curdir = old + if getattr(self.__class__, 'post_recurse', None): + self.post_recurse(module, base, nexdir) + else: + dc = {'ctx': self} + if getattr(self.__class__, 'pre_recurse', None): + dc = self.pre_recurse(txt, file_path, nexdir) + old = self.curdir + self.curdir = nexdir + try: + try: + exec(compile(txt, file_path, 'exec'), dc) + except Exception: + exc_type, exc_value, tb = sys.exc_info() + raise WscriptError("".join(traceback.format_exception(exc_type, exc_value, tb)), base) + finally: + self.curdir = old + if getattr(self.__class__, 'post_recurse', None): + self.post_recurse(txt, file_path, nexdir) + +if is_win32: + old = shutil.copy2 + def copy2(src, dst): + old(src, dst) + shutil.copystat(src, src) + setattr(shutil, 'copy2', copy2) + +def zip_folder(dir, zip_file_name, prefix): + """ + prefix represents the app to add in the archive + """ + import zipfile + zip = zipfile.ZipFile(zip_file_name, 'w', compression=zipfile.ZIP_DEFLATED) + base = os.path.abspath(dir) + + if prefix: + if prefix[-1] != os.sep: + prefix += os.sep + + n = len(base) + for root, dirs, files in os.walk(base): + for f in files: + archive_name = prefix + root[n:] + os.sep + f + zip.write(root + os.sep + f, archive_name, zipfile.ZIP_DEFLATED) + zip.close() + +def get_elapsed_time(start): + "Format a time delta (datetime.timedelta) using the format DdHhMmS.MSs" + delta = datetime.datetime.now() - start + # cast to int necessary for python 3.0 + days = int(delta.days) + hours = int(delta.seconds / 3600) + minutes = int((delta.seconds - hours * 3600) / 60) + seconds = delta.seconds - hours * 3600 - minutes * 60 \ + + float(delta.microseconds) / 1000 / 1000 + result = '' + if days: + result += '%dd' % days + if days or hours: + result += '%dh' % hours + if days or hours or minutes: + result += '%dm' % minutes + return '%s%.3fs' % (result, seconds) + +if os.name == 'java': + # For Jython (they should really fix the inconsistency) + try: + gc.disable() + gc.enable() + except NotImplementedError: + gc.disable = gc.enable + diff --git a/node-v0.8.14/tools/wafadmin/__init__.py b/node-v0.8.14/tools/wafadmin/__init__.py new file mode 100644 index 0000000..01273cf --- /dev/null +++ b/node-v0.8.14/tools/wafadmin/__init__.py @@ -0,0 +1,3 @@ +#!/usr/bin/env python +# encoding: utf-8 +# Thomas Nagy, 2005 (ita) diff --git a/node-v0.8.14/tools/wafadmin/ansiterm.py b/node-v0.8.14/tools/wafadmin/ansiterm.py new file mode 100644 index 0000000..8e71313 --- /dev/null +++ b/node-v0.8.14/tools/wafadmin/ansiterm.py @@ -0,0 +1,221 @@ +import sys, os +try: + if (not sys.stderr.isatty()) or (not sys.stdout.isatty()): + raise ValueError('not a tty') + + from ctypes import * + + class COORD(Structure): + _fields_ = [("X", c_short), ("Y", c_short)] + + class SMALL_RECT(Structure): + _fields_ = [("Left", c_short), ("Top", c_short), ("Right", c_short), ("Bottom", c_short)] + + class CONSOLE_SCREEN_BUFFER_INFO(Structure): + _fields_ = [("Size", COORD), ("CursorPosition", COORD), ("Attributes", c_short), ("Window", SMALL_RECT), ("MaximumWindowSize", COORD)] + + class CONSOLE_CURSOR_INFO(Structure): + _fields_ = [('dwSize',c_ulong), ('bVisible', c_int)] + + sbinfo = CONSOLE_SCREEN_BUFFER_INFO() + csinfo = CONSOLE_CURSOR_INFO() + hconsole = windll.kernel32.GetStdHandle(-11) + windll.kernel32.GetConsoleScreenBufferInfo(hconsole, byref(sbinfo)) + if sbinfo.Size.X < 10 or sbinfo.Size.Y < 10: raise Exception('small console') + windll.kernel32.GetConsoleCursorInfo(hconsole, byref(csinfo)) +except Exception: + pass +else: + import re, threading + + to_int = lambda number, default: number and int(number) or default + wlock = threading.Lock() + + STD_OUTPUT_HANDLE = -11 + STD_ERROR_HANDLE = -12 + + class AnsiTerm(object): + def __init__(self): + self.hconsole = windll.kernel32.GetStdHandle(STD_OUTPUT_HANDLE) + self.cursor_history = [] + + def screen_buffer_info(self): + sbinfo = CONSOLE_SCREEN_BUFFER_INFO() + windll.kernel32.GetConsoleScreenBufferInfo(self.hconsole, byref(sbinfo)) + return sbinfo + + def clear_line(self, param): + mode = param and int(param) or 0 + sbinfo = self.screen_buffer_info() + if mode == 1: # Clear from begining of line to cursor position + line_start = COORD(0, sbinfo.CursorPosition.Y) + line_length = sbinfo.Size.X + elif mode == 2: # Clear entire line + line_start = COORD(sbinfo.CursorPosition.X, sbinfo.CursorPosition.Y) + line_length = sbinfo.Size.X - sbinfo.CursorPosition.X + else: # Clear from cursor position to end of line + line_start = sbinfo.CursorPosition + line_length = sbinfo.Size.X - sbinfo.CursorPosition.X + chars_written = c_int() + windll.kernel32.FillConsoleOutputCharacterA(self.hconsole, c_char(' '), line_length, line_start, byref(chars_written)) + windll.kernel32.FillConsoleOutputAttribute(self.hconsole, sbinfo.Attributes, line_length, line_start, byref(chars_written)) + + def clear_screen(self, param): + mode = to_int(param, 0) + sbinfo = self.screen_buffer_info() + if mode == 1: # Clear from begining of screen to cursor position + clear_start = COORD(0, 0) + clear_length = sbinfo.CursorPosition.X * sbinfo.CursorPosition.Y + elif mode == 2: # Clear entire screen and return cursor to home + clear_start = COORD(0, 0) + clear_length = sbinfo.Size.X * sbinfo.Size.Y + windll.kernel32.SetConsoleCursorPosition(self.hconsole, clear_start) + else: # Clear from cursor position to end of screen + clear_start = sbinfo.CursorPosition + clear_length = ((sbinfo.Size.X - sbinfo.CursorPosition.X) + sbinfo.Size.X * (sbinfo.Size.Y - sbinfo.CursorPosition.Y)) + chars_written = c_int() + windll.kernel32.FillConsoleOutputCharacterA(self.hconsole, c_char(' '), clear_length, clear_start, byref(chars_written)) + windll.kernel32.FillConsoleOutputAttribute(self.hconsole, sbinfo.Attributes, clear_length, clear_start, byref(chars_written)) + + def push_cursor(self, param): + sbinfo = self.screen_buffer_info() + self.cursor_history.push(sbinfo.CursorPosition) + + def pop_cursor(self, param): + if self.cursor_history: + old_pos = self.cursor_history.pop() + windll.kernel32.SetConsoleCursorPosition(self.hconsole, old_pos) + + def set_cursor(self, param): + x, sep, y = param.partition(';') + x = to_int(x, 1) - 1 + y = to_int(y, 1) - 1 + sbinfo = self.screen_buffer_info() + new_pos = COORD( + min(max(0, x), sbinfo.Size.X), + min(max(0, y), sbinfo.Size.Y) + ) + windll.kernel32.SetConsoleCursorPosition(self.hconsole, new_pos) + + def set_column(self, param): + x = to_int(param, 1) - 1 + sbinfo = self.screen_buffer_info() + new_pos = COORD( + min(max(0, x), sbinfo.Size.X), + sbinfo.CursorPosition.Y + ) + windll.kernel32.SetConsoleCursorPosition(self.hconsole, new_pos) + + def move_cursor(self, x_offset=0, y_offset=0): + sbinfo = self.screen_buffer_info() + new_pos = COORD( + min(max(0, sbinfo.CursorPosition.X + x_offset), sbinfo.Size.X), + min(max(0, sbinfo.CursorPosition.Y + y_offset), sbinfo.Size.Y) + ) + windll.kernel32.SetConsoleCursorPosition(self.hconsole, new_pos) + + def move_up(self, param): + self.move_cursor(y_offset = -to_int(param, 1)) + + def move_down(self, param): + self.move_cursor(y_offset = to_int(param, 1)) + + def move_left(self, param): + self.move_cursor(x_offset = -to_int(param, 1)) + + def move_right(self, param): + self.move_cursor(x_offset = to_int(param, 1)) + + def next_line(self, param): + sbinfo = self.screen_buffer_info() + self.move_cursor( + x_offset = -sbinfo.CursorPosition.X, + y_offset = to_int(param, 1) + ) + + def prev_line(self, param): + sbinfo = self.screen_buffer_info() + self.move_cursor( + x_offset = -sbinfo.CursorPosition.X, + y_offset = -to_int(param, 1) + ) + + escape_to_color = { (0, 30): 0x0, #black + (0, 31): 0x4, #red + (0, 32): 0x2, #green + (0, 33): 0x4+0x2, #dark yellow + (0, 34): 0x1, #blue + (0, 35): 0x1+0x4, #purple + (0, 36): 0x2+0x4, #cyan + (0, 37): 0x1+0x2+0x4, #grey + (1, 30): 0x1+0x2+0x4, #dark gray + (1, 31): 0x4+0x8, #red + (1, 32): 0x2+0x8, #light green + (1, 33): 0x4+0x2+0x8, #yellow + (1, 34): 0x1+0x8, #light blue + (1, 35): 0x1+0x4+0x8, #light purple + (1, 36): 0x1+0x2+0x8, #light cyan + (1, 37): 0x1+0x2+0x4+0x8, #white + } + + def set_color(self, param): + intensity, sep, color = param.partition(';') + intensity = to_int(intensity, 0) + color = to_int(color, 0) + if intensity and not color: + color, intensity = intensity, color + attrib = self.escape_to_color.get((intensity, color), 0x7) + windll.kernel32.SetConsoleTextAttribute(self.hconsole, attrib) + + def show_cursor(self,param): + csinfo.bVisible = 1 + windll.kernel32.SetConsoleCursorInfo(self.hconsole, byref(csinfo)) + + def hide_cursor(self,param): + csinfo.bVisible = 0 + windll.kernel32.SetConsoleCursorInfo(self.hconsole, byref(csinfo)) + + ansi_command_table = { + 'A': move_up, + 'B': move_down, + 'C': move_right, + 'D': move_left, + 'E': next_line, + 'F': prev_line, + 'G': set_column, + 'H': set_cursor, + 'f': set_cursor, + 'J': clear_screen, + 'K': clear_line, + 'h': show_cursor, + 'l': hide_cursor, + 'm': set_color, + 's': push_cursor, + 'u': pop_cursor, + } + # Match either the escape sequence or text not containing escape sequence + ansi_tokans = re.compile('(?:\x1b\[([0-9?;]*)([a-zA-Z])|([^\x1b]+))') + def write(self, text): + wlock.acquire() + for param, cmd, txt in self.ansi_tokans.findall(text): + if cmd: + cmd_func = self.ansi_command_table.get(cmd) + if cmd_func: + cmd_func(self, param) + else: + chars_written = c_int() + if isinstance(txt, unicode): + windll.kernel32.WriteConsoleW(self.hconsole, txt, len(txt), byref(chars_written), None) + else: + windll.kernel32.WriteConsoleA(self.hconsole, txt, len(txt), byref(chars_written), None) + wlock.release() + + def flush(self): + pass + + def isatty(self): + return True + + sys.stderr = sys.stdout = AnsiTerm() + os.environ['TERM'] = 'vt100' + diff --git a/node-v0.8.14/tools/wafadmin/pproc.py b/node-v0.8.14/tools/wafadmin/pproc.py new file mode 100644 index 0000000..cb15178 --- /dev/null +++ b/node-v0.8.14/tools/wafadmin/pproc.py @@ -0,0 +1,620 @@ +# borrowed from python 2.5.2c1 +# Copyright (c) 2003-2005 by Peter Astrand +# Licensed to PSF under a Contributor Agreement. + +import sys +mswindows = (sys.platform == "win32") + +import os +import types +import traceback +import gc + +class CalledProcessError(Exception): + def __init__(self, returncode, cmd): + self.returncode = returncode + self.cmd = cmd + def __str__(self): + return "Command '%s' returned non-zero exit status %d" % (self.cmd, self.returncode) + +if mswindows: + import threading + import msvcrt + if 0: + import pywintypes + from win32api import GetStdHandle, STD_INPUT_HANDLE, \ + STD_OUTPUT_HANDLE, STD_ERROR_HANDLE + from win32api import GetCurrentProcess, DuplicateHandle, \ + GetModuleFileName, GetVersion + from win32con import DUPLICATE_SAME_ACCESS, SW_HIDE + from win32pipe import CreatePipe + from win32process import CreateProcess, STARTUPINFO, \ + GetExitCodeProcess, STARTF_USESTDHANDLES, \ + STARTF_USESHOWWINDOW, CREATE_NEW_CONSOLE + from win32event import WaitForSingleObject, INFINITE, WAIT_OBJECT_0 + else: + from _subprocess import * + class STARTUPINFO: + dwFlags = 0 + hStdInput = None + hStdOutput = None + hStdError = None + wShowWindow = 0 + class pywintypes: + error = IOError +else: + import select + import errno + import fcntl + import pickle + +__all__ = ["Popen", "PIPE", "STDOUT", "call", "check_call", "CalledProcessError"] + +try: + MAXFD = os.sysconf("SC_OPEN_MAX") +except: + MAXFD = 256 + +try: + False +except NameError: + False = 0 + True = 1 + +_active = [] + +def _cleanup(): + for inst in _active[:]: + if inst.poll(_deadstate=sys.maxint) >= 0: + try: + _active.remove(inst) + except ValueError: + pass + +PIPE = -1 +STDOUT = -2 + + +def call(*popenargs, **kwargs): + return Popen(*popenargs, **kwargs).wait() + +def check_call(*popenargs, **kwargs): + retcode = call(*popenargs, **kwargs) + cmd = kwargs.get("args") + if cmd is None: + cmd = popenargs[0] + if retcode: + raise CalledProcessError(retcode, cmd) + return retcode + + +def list2cmdline(seq): + result = [] + needquote = False + for arg in seq: + bs_buf = [] + + if result: + result.append(' ') + + needquote = (" " in arg) or ("\t" in arg) or arg == "" + if needquote: + result.append('"') + + for c in arg: + if c == '\\': + bs_buf.append(c) + elif c == '"': + result.append('\\' * len(bs_buf)*2) + bs_buf = [] + result.append('\\"') + else: + if bs_buf: + result.extend(bs_buf) + bs_buf = [] + result.append(c) + + if bs_buf: + result.extend(bs_buf) + + if needquote: + result.extend(bs_buf) + result.append('"') + + return ''.join(result) + +class Popen(object): + def __init__(self, args, bufsize=0, executable=None, + stdin=None, stdout=None, stderr=None, + preexec_fn=None, close_fds=False, shell=False, + cwd=None, env=None, universal_newlines=False, + startupinfo=None, creationflags=0): + _cleanup() + + self._child_created = False + if not isinstance(bufsize, (int, long)): + raise TypeError("bufsize must be an integer") + + if mswindows: + if preexec_fn is not None: + raise ValueError("preexec_fn is not supported on Windows platforms") + if close_fds: + raise ValueError("close_fds is not supported on Windows platforms") + else: + if startupinfo is not None: + raise ValueError("startupinfo is only supported on Windows platforms") + if creationflags != 0: + raise ValueError("creationflags is only supported on Windows platforms") + + self.stdin = None + self.stdout = None + self.stderr = None + self.pid = None + self.returncode = None + self.universal_newlines = universal_newlines + + (p2cread, p2cwrite, + c2pread, c2pwrite, + errread, errwrite) = self._get_handles(stdin, stdout, stderr) + + self._execute_child(args, executable, preexec_fn, close_fds, + cwd, env, universal_newlines, + startupinfo, creationflags, shell, + p2cread, p2cwrite, + c2pread, c2pwrite, + errread, errwrite) + + if mswindows: + if stdin is None and p2cwrite is not None: + os.close(p2cwrite) + p2cwrite = None + if stdout is None and c2pread is not None: + os.close(c2pread) + c2pread = None + if stderr is None and errread is not None: + os.close(errread) + errread = None + + if p2cwrite: + self.stdin = os.fdopen(p2cwrite, 'wb', bufsize) + if c2pread: + if universal_newlines: + self.stdout = os.fdopen(c2pread, 'rU', bufsize) + else: + self.stdout = os.fdopen(c2pread, 'rb', bufsize) + if errread: + if universal_newlines: + self.stderr = os.fdopen(errread, 'rU', bufsize) + else: + self.stderr = os.fdopen(errread, 'rb', bufsize) + + + def _translate_newlines(self, data): + data = data.replace("\r\n", "\n") + data = data.replace("\r", "\n") + return data + + + def __del__(self, sys=sys): + if not self._child_created: + return + self.poll(_deadstate=sys.maxint) + if self.returncode is None and _active is not None: + _active.append(self) + + + def communicate(self, input=None): + if [self.stdin, self.stdout, self.stderr].count(None) >= 2: + stdout = None + stderr = None + if self.stdin: + if input: + self.stdin.write(input) + self.stdin.close() + elif self.stdout: + stdout = self.stdout.read() + elif self.stderr: + stderr = self.stderr.read() + self.wait() + return (stdout, stderr) + + return self._communicate(input) + + + if mswindows: + def _get_handles(self, stdin, stdout, stderr): + if stdin is None and stdout is None and stderr is None: + return (None, None, None, None, None, None) + + p2cread, p2cwrite = None, None + c2pread, c2pwrite = None, None + errread, errwrite = None, None + + if stdin is None: + p2cread = GetStdHandle(STD_INPUT_HANDLE) + if p2cread is not None: + pass + elif stdin is None or stdin == PIPE: + p2cread, p2cwrite = CreatePipe(None, 0) + p2cwrite = p2cwrite.Detach() + p2cwrite = msvcrt.open_osfhandle(p2cwrite, 0) + elif isinstance(stdin, int): + p2cread = msvcrt.get_osfhandle(stdin) + else: + p2cread = msvcrt.get_osfhandle(stdin.fileno()) + p2cread = self._make_inheritable(p2cread) + + if stdout is None: + c2pwrite = GetStdHandle(STD_OUTPUT_HANDLE) + if c2pwrite is not None: + pass + elif stdout is None or stdout == PIPE: + c2pread, c2pwrite = CreatePipe(None, 0) + c2pread = c2pread.Detach() + c2pread = msvcrt.open_osfhandle(c2pread, 0) + elif isinstance(stdout, int): + c2pwrite = msvcrt.get_osfhandle(stdout) + else: + c2pwrite = msvcrt.get_osfhandle(stdout.fileno()) + c2pwrite = self._make_inheritable(c2pwrite) + + if stderr is None: + errwrite = GetStdHandle(STD_ERROR_HANDLE) + if errwrite is not None: + pass + elif stderr is None or stderr == PIPE: + errread, errwrite = CreatePipe(None, 0) + errread = errread.Detach() + errread = msvcrt.open_osfhandle(errread, 0) + elif stderr == STDOUT: + errwrite = c2pwrite + elif isinstance(stderr, int): + errwrite = msvcrt.get_osfhandle(stderr) + else: + errwrite = msvcrt.get_osfhandle(stderr.fileno()) + errwrite = self._make_inheritable(errwrite) + + return (p2cread, p2cwrite, + c2pread, c2pwrite, + errread, errwrite) + def _make_inheritable(self, handle): + return DuplicateHandle(GetCurrentProcess(), handle, GetCurrentProcess(), 0, 1, DUPLICATE_SAME_ACCESS) + + def _find_w9xpopen(self): + w9xpopen = os.path.join(os.path.dirname(GetModuleFileName(0)), "w9xpopen.exe") + if not os.path.exists(w9xpopen): + w9xpopen = os.path.join(os.path.dirname(sys.exec_prefix), "w9xpopen.exe") + if not os.path.exists(w9xpopen): + raise RuntimeError("Cannot locate w9xpopen.exe, which is needed for Popen to work with your shell or platform.") + return w9xpopen + + def _execute_child(self, args, executable, preexec_fn, close_fds, + cwd, env, universal_newlines, + startupinfo, creationflags, shell, + p2cread, p2cwrite, + c2pread, c2pwrite, + errread, errwrite): + + if not isinstance(args, types.StringTypes): + args = list2cmdline(args) + + if startupinfo is None: + startupinfo = STARTUPINFO() + if None not in (p2cread, c2pwrite, errwrite): + startupinfo.dwFlags |= STARTF_USESTDHANDLES + startupinfo.hStdInput = p2cread + startupinfo.hStdOutput = c2pwrite + startupinfo.hStdError = errwrite + + if shell: + startupinfo.dwFlags |= STARTF_USESHOWWINDOW + startupinfo.wShowWindow = SW_HIDE + comspec = os.environ.get("COMSPEC", "cmd.exe") + args = comspec + " /c " + args + if (GetVersion() >= 0x80000000L or + os.path.basename(comspec).lower() == "command.com"): + w9xpopen = self._find_w9xpopen() + args = '"%s" %s' % (w9xpopen, args) + creationflags |= CREATE_NEW_CONSOLE + + try: + hp, ht, pid, tid = CreateProcess(executable, args, None, None, 1, creationflags, env, cwd, startupinfo) + except pywintypes.error, e: + raise WindowsError(*e.args) + + self._child_created = True + self._handle = hp + self.pid = pid + ht.Close() + + if p2cread is not None: + p2cread.Close() + if c2pwrite is not None: + c2pwrite.Close() + if errwrite is not None: + errwrite.Close() + + + def poll(self, _deadstate=None): + if self.returncode is None: + if WaitForSingleObject(self._handle, 0) == WAIT_OBJECT_0: + self.returncode = GetExitCodeProcess(self._handle) + return self.returncode + + + def wait(self): + if self.returncode is None: + obj = WaitForSingleObject(self._handle, INFINITE) + self.returncode = GetExitCodeProcess(self._handle) + return self.returncode + + def _readerthread(self, fh, buffer): + buffer.append(fh.read()) + + def _communicate(self, input): + stdout = None + stderr = None + + if self.stdout: + stdout = [] + stdout_thread = threading.Thread(target=self._readerthread, args=(self.stdout, stdout)) + stdout_thread.setDaemon(True) + stdout_thread.start() + if self.stderr: + stderr = [] + stderr_thread = threading.Thread(target=self._readerthread, args=(self.stderr, stderr)) + stderr_thread.setDaemon(True) + stderr_thread.start() + + if self.stdin: + if input is not None: + self.stdin.write(input) + self.stdin.close() + + if self.stdout: + stdout_thread.join() + if self.stderr: + stderr_thread.join() + + if stdout is not None: + stdout = stdout[0] + if stderr is not None: + stderr = stderr[0] + + if self.universal_newlines and hasattr(file, 'newlines'): + if stdout: + stdout = self._translate_newlines(stdout) + if stderr: + stderr = self._translate_newlines(stderr) + + self.wait() + return (stdout, stderr) + + else: + def _get_handles(self, stdin, stdout, stderr): + p2cread, p2cwrite = None, None + c2pread, c2pwrite = None, None + errread, errwrite = None, None + + if stdin is None: + pass + elif stdin == PIPE: + p2cread, p2cwrite = os.pipe() + elif isinstance(stdin, int): + p2cread = stdin + else: + p2cread = stdin.fileno() + + if stdout is None: + pass + elif stdout == PIPE: + c2pread, c2pwrite = os.pipe() + elif isinstance(stdout, int): + c2pwrite = stdout + else: + c2pwrite = stdout.fileno() + + if stderr is None: + pass + elif stderr == PIPE: + errread, errwrite = os.pipe() + elif stderr == STDOUT: + errwrite = c2pwrite + elif isinstance(stderr, int): + errwrite = stderr + else: + errwrite = stderr.fileno() + + return (p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite) + + def _set_cloexec_flag(self, fd): + try: + cloexec_flag = fcntl.FD_CLOEXEC + except AttributeError: + cloexec_flag = 1 + + old = fcntl.fcntl(fd, fcntl.F_GETFD) + fcntl.fcntl(fd, fcntl.F_SETFD, old | cloexec_flag) + + def _close_fds(self, but): + for i in xrange(3, MAXFD): + if i == but: + continue + try: + os.close(i) + except: + pass + + def _execute_child(self, args, executable, preexec_fn, close_fds, + cwd, env, universal_newlines, startupinfo, creationflags, shell, + p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite): + + if isinstance(args, types.StringTypes): + args = [args] + else: + args = list(args) + + if shell: + args = ["/bin/sh", "-c"] + args + + if executable is None: + executable = args[0] + + errpipe_read, errpipe_write = os.pipe() + self._set_cloexec_flag(errpipe_write) + + gc_was_enabled = gc.isenabled() + gc.disable() + try: + self.pid = os.fork() + except: + if gc_was_enabled: + gc.enable() + raise + self._child_created = True + if self.pid == 0: + try: + if p2cwrite: + os.close(p2cwrite) + if c2pread: + os.close(c2pread) + if errread: + os.close(errread) + os.close(errpipe_read) + + if p2cread: + os.dup2(p2cread, 0) + if c2pwrite: + os.dup2(c2pwrite, 1) + if errwrite: + os.dup2(errwrite, 2) + + if p2cread and p2cread not in (0,): + os.close(p2cread) + if c2pwrite and c2pwrite not in (p2cread, 1): + os.close(c2pwrite) + if errwrite and errwrite not in (p2cread, c2pwrite, 2): + os.close(errwrite) + + if close_fds: + self._close_fds(but=errpipe_write) + + if cwd is not None: + os.chdir(cwd) + + if preexec_fn: + apply(preexec_fn) + + if env is None: + os.execvp(executable, args) + else: + os.execvpe(executable, args, env) + + except: + exc_type, exc_value, tb = sys.exc_info() + exc_lines = traceback.format_exception(exc_type, exc_value, tb) + exc_value.child_traceback = ''.join(exc_lines) + os.write(errpipe_write, pickle.dumps(exc_value)) + + os._exit(255) + + if gc_was_enabled: + gc.enable() + os.close(errpipe_write) + if p2cread and p2cwrite: + os.close(p2cread) + if c2pwrite and c2pread: + os.close(c2pwrite) + if errwrite and errread: + os.close(errwrite) + + data = os.read(errpipe_read, 1048576) + os.close(errpipe_read) + if data != "": + os.waitpid(self.pid, 0) + child_exception = pickle.loads(data) + raise child_exception + + def _handle_exitstatus(self, sts): + if os.WIFSIGNALED(sts): + self.returncode = -os.WTERMSIG(sts) + elif os.WIFEXITED(sts): + self.returncode = os.WEXITSTATUS(sts) + else: + raise RuntimeError("Unknown child exit status!") + + def poll(self, _deadstate=None): + if self.returncode is None: + try: + pid, sts = os.waitpid(self.pid, os.WNOHANG) + if pid == self.pid: + self._handle_exitstatus(sts) + except os.error: + if _deadstate is not None: + self.returncode = _deadstate + return self.returncode + + def wait(self): + if self.returncode is None: + pid, sts = os.waitpid(self.pid, 0) + self._handle_exitstatus(sts) + return self.returncode + + def _communicate(self, input): + read_set = [] + write_set = [] + stdout = None + stderr = None + + if self.stdin: + self.stdin.flush() + if input: + write_set.append(self.stdin) + else: + self.stdin.close() + if self.stdout: + read_set.append(self.stdout) + stdout = [] + if self.stderr: + read_set.append(self.stderr) + stderr = [] + + input_offset = 0 + while read_set or write_set: + rlist, wlist, xlist = select.select(read_set, write_set, []) + + if self.stdin in wlist: + bytes_written = os.write(self.stdin.fileno(), buffer(input, input_offset, 512)) + input_offset += bytes_written + if input_offset >= len(input): + self.stdin.close() + write_set.remove(self.stdin) + + if self.stdout in rlist: + data = os.read(self.stdout.fileno(), 1024) + if data == "": + self.stdout.close() + read_set.remove(self.stdout) + stdout.append(data) + + if self.stderr in rlist: + data = os.read(self.stderr.fileno(), 1024) + if data == "": + self.stderr.close() + read_set.remove(self.stderr) + stderr.append(data) + + if stdout is not None: + stdout = ''.join(stdout) + if stderr is not None: + stderr = ''.join(stderr) + + if self.universal_newlines and hasattr(file, 'newlines'): + if stdout: + stdout = self._translate_newlines(stdout) + if stderr: + stderr = self._translate_newlines(stderr) + + self.wait() + return (stdout, stderr) + diff --git a/node-v0.8.14/tools/wafadmin/py3kfixes.py b/node-v0.8.14/tools/wafadmin/py3kfixes.py new file mode 100644 index 0000000..6aeb26b --- /dev/null +++ b/node-v0.8.14/tools/wafadmin/py3kfixes.py @@ -0,0 +1,122 @@ +#!/usr/bin/env python +# encoding: utf-8 +# Thomas Nagy, 2009 (ita) + +""" +Fixes for py3k go here +""" + +import os + +all_modifs = {} + +def modif(dir, name, fun): + if name == '*': + lst = [] + for y in '. Tools 3rdparty'.split(): + for x in os.listdir(os.path.join(dir, y)): + if x.endswith('.py'): + lst.append(y + os.sep + x) + #lst = [y + os.sep + x for x in os.listdir(os.path.join(dir, y)) for y in '. Tools 3rdparty'.split() if x.endswith('.py')] + for x in lst: + modif(dir, x, fun) + return + + filename = os.path.join(dir, name) + f = open(filename, 'r') + txt = f.read() + f.close() + + txt = fun(txt) + + f = open(filename, 'w') + f.write(txt) + f.close() + +def subst(filename): + def do_subst(fun): + global all_modifs + try: + all_modifs[filename] += fun + except KeyError: + all_modifs[filename] = [fun] + return fun + return do_subst + +@subst('Constants.py') +def r1(code): + code = code.replace("'iluvcuteoverload'", "b'iluvcuteoverload'") + code = code.replace("ABI=7", "ABI=37") + return code + +@subst('Tools/ccroot.py') +def r2(code): + code = code.replace("p.stdin.write('\\n')", "p.stdin.write(b'\\n')") + code = code.replace('p.communicate()[0]', 'p.communicate()[0].decode("utf-8")') + return code + +@subst('Utils.py') +def r3(code): + code = code.replace("m.update(str(lst))", "m.update(str(lst).encode())") + code = code.replace('p.communicate()[0]', 'p.communicate()[0].decode("utf-8")') + return code + +@subst('ansiterm.py') +def r33(code): + code = code.replace('unicode', 'str') + return code + +@subst('Task.py') +def r4(code): + code = code.replace("up(self.__class__.__name__)", "up(self.__class__.__name__.encode())") + code = code.replace("up(self.env.variant())", "up(self.env.variant().encode())") + code = code.replace("up(x.parent.abspath())", "up(x.parent.abspath().encode())") + code = code.replace("up(x.name)", "up(x.name.encode())") + code = code.replace('class TaskBase(object):\n\t__metaclass__=store_task_type', 'import binascii\n\nclass TaskBase(object, metaclass=store_task_type):') + code = code.replace('keys=self.cstr_groups.keys()', 'keys=list(self.cstr_groups.keys())') + code = code.replace("sig.encode('hex')", 'binascii.hexlify(sig)') + return code + +@subst('Build.py') +def r5(code): + code = code.replace("cPickle.dump(data,file,-1)", "cPickle.dump(data,file)") + code = code.replace('for node in src_dir_node.childs.values():', 'for node in list(src_dir_node.childs.values()):') + return code + +@subst('*') +def r6(code): + code = code.replace('xrange', 'range') + code = code.replace('iteritems', 'items') + code = code.replace('maxint', 'maxsize') + code = code.replace('iterkeys', 'keys') + code = code.replace('Error,e:', 'Error as e:') + code = code.replace('Exception,e:', 'Exception as e:') + return code + +@subst('TaskGen.py') +def r7(code): + code = code.replace('class task_gen(object):\n\t__metaclass__=register_obj', 'class task_gen(object, metaclass=register_obj):') + return code + +@subst('Tools/python.py') +def r8(code): + code = code.replace('proc.communicate()[0]', 'proc.communicate()[0].decode("utf-8")') + return code + +@subst('Tools/glib2.py') +def r9(code): + code = code.replace('f.write(c)', 'f.write(c.encode("utf-8"))') + return code + +@subst('Tools/config_c.py') +def r10(code): + code = code.replace("key=kw['success']", "key=kw['success']\n\t\t\t\ttry:\n\t\t\t\t\tkey=key.decode('utf-8')\n\t\t\t\texcept:\n\t\t\t\t\tpass") + return code + +def fixdir(dir): + global all_modifs + for k in all_modifs: + for v in all_modifs[k]: + modif(os.path.join(dir, 'wafadmin'), k, v) + #print('substitutions finished') + diff --git a/node-v0.8.14/vcbuild.bat b/node-v0.8.14/vcbuild.bat new file mode 100644 index 0000000..a957626 --- /dev/null +++ b/node-v0.8.14/vcbuild.bat @@ -0,0 +1,198 @@ +@echo off + +cd %~dp0 + +if /i "%1"=="help" goto help +if /i "%1"=="--help" goto help +if /i "%1"=="-help" goto help +if /i "%1"=="/help" goto help +if /i "%1"=="?" goto help +if /i "%1"=="-?" goto help +if /i "%1"=="--?" goto help +if /i "%1"=="/?" goto help + +@rem Process arguments. +set config=Release +set msiplatform=x86 +set target=Build +set target_arch=ia32 +set debug_arg= +set nosnapshot_arg= +set noprojgen= +set nobuild= +set nosign= +set nosnapshot= +set test= +set test_args= +set msi= +set licensertf= +set upload= +set jslint= +set buildnodeweak= +set noetw= +set noetw_arg= +set noetw_msi_arg= + +:next-arg +if "%1"=="" goto args-done +if /i "%1"=="debug" set config=Debug&goto arg-ok +if /i "%1"=="release" set config=Release&goto arg-ok +if /i "%1"=="clean" set target=Clean&goto arg-ok +if /i "%1"=="ia32" set target_arch=ia32&goto arg-ok +if /i "%1"=="x86" set target_arch=ia32&goto arg-ok +if /i "%1"=="x64" set target_arch=x64&goto arg-ok +if /i "%1"=="noprojgen" set noprojgen=1&goto arg-ok +if /i "%1"=="nobuild" set nobuild=1&goto arg-ok +if /i "%1"=="nosign" set nosign=1&goto arg-ok +if /i "%1"=="nosnapshot" set nosnapshot=1&goto arg-ok +if /i "%1"=="noetw" set noetw=1&goto arg-ok +if /i "%1"=="licensertf" set licensertf=1&goto arg-ok +if /i "%1"=="test-uv" set test=test-uv&goto arg-ok +if /i "%1"=="test-internet" set test=test-internet&goto arg-ok +if /i "%1"=="test-pummel" set test=test-pummel&goto arg-ok +if /i "%1"=="test-simple" set test=test-simple&goto arg-ok +if /i "%1"=="test-message" set test=test-message&goto arg-ok +if /i "%1"=="test-gc" set test=test-gc&set buildnodeweak=1&goto arg-ok +if /i "%1"=="test-all" set test=test-all&set buildnodeweak=1&goto arg-ok +if /i "%1"=="test" set test=test&goto arg-ok +if /i "%1"=="msi" set msi=1&set licensertf=1&goto arg-ok +if /i "%1"=="upload" set upload=1&goto arg-ok +if /i "%1"=="jslint" set jslint=1&goto arg-ok + +echo Warning: ignoring invalid command line option `%1`. + +:arg-ok +:arg-ok +shift +goto next-arg + +:args-done +if defined upload goto upload +if defined jslint goto jslint + +if "%config%"=="Debug" set debug_arg=--debug +if "%target_arch%"=="x64" set msiplatform=x64 +if defined nosnapshot set nosnapshot_arg=--without-snapshot +if defined noetw set noetw_arg=--without-etw& set noetw_msi_arg=/p:NoETW=1 + +:project-gen +@rem Skip project generation if requested. +if defined noprojgen goto msbuild + +@rem Generate the VS project. +python configure %debug_arg% %nosnapshot_arg% %noetw_arg% --dest-cpu=%target_arch% +if errorlevel 1 goto create-msvs-files-failed +if not exist node.sln goto create-msvs-files-failed +echo Project files generated. + +:msbuild +@rem Skip project generation if requested. +if defined nobuild goto sign + +@rem Bail out early if not running in VS build env. +if defined VCINSTALLDIR goto msbuild-found +if not defined VS100COMNTOOLS goto msbuild-not-found +if not exist "%VS100COMNTOOLS%\..\..\vc\vcvarsall.bat" goto msbuild-not-found +call "%VS100COMNTOOLS%\..\..\vc\vcvarsall.bat" +if not defined VCINSTALLDIR goto msbuild-not-found +goto msbuild-found + +:msbuild-not-found +echo Build skipped. To build, this file needs to run from VS cmd prompt. +goto run + +:msbuild-found +@rem Build the sln with msbuild. +msbuild node.sln /m /t:%target% /p:Configuration=%config% /clp:NoSummary;NoItemAndPropertyList;Verbosity=minimal /nologo +if errorlevel 1 goto exit + +:sign +@rem Skip signing if the `nosign` option was specified. +if defined nosign goto licensertf + +signtool sign /a Release\node.exe + +:licensertf +@rem Skip license.rtf generation if not requested. +if not defined licensertf goto msi + +%config%\node tools\license2rtf.js < LICENSE > %config%\license.rtf +if errorlevel 1 echo Failed to generate license.rtf&goto exit + +:msi +@rem Skip msi generation if not requested +if not defined msi goto run +python "%~dp0tools\getnodeversion.py" > "%temp%\node_version.txt" +if not errorlevel 0 echo Cannot determine current version of node.js & goto exit +for /F "tokens=*" %%i in (%temp%\node_version.txt) do set NODE_VERSION=%%i +msbuild "%~dp0tools\msvs\msi\nodemsi.sln" /m /t:Clean,Build /p:Configuration=%config% /p:Platform=%msiplatform% /p:NodeVersion=%NODE_VERSION% %noetw_msi_arg% /clp:NoSummary;NoItemAndPropertyList;Verbosity=minimal /nologo +if errorlevel 1 goto exit + +if defined nosign goto run +signtool sign /a Release\node-v%NODE_VERSION%-%msiplatform%.msi + +:run +@rem Run tests if requested. +if "%test%"=="" goto exit + +if "%config%"=="Debug" set test_args=--mode=debug +if "%config%"=="Release" set test_args=--mode=release + +if "%test%"=="test" set test_args=%test_args% simple message +if "%test%"=="test-internet" set test_args=%test_args% internet +if "%test%"=="test-pummel" set test_args=%test_args% pummel +if "%test%"=="test-simple" set test_args=%test_args% simple +if "%test%"=="test-message" set test_args=%test_args% message +if "%test%"=="test-gc" set test_args=%test_args% gc +if "%test%"=="test-all" set test_args=%test_args% + +:build-node-weak +@rem Build node-weak if required +if "%buildnodeweak%"=="" goto run-tests +"%config%\node" deps\npm\node_modules\node-gyp\bin\node-gyp rebuild --directory="%~dp0test\gc\node_modules\weak" --nodedir="%~dp0." +if errorlevel 1 goto build-node-weak-failed +goto run-tests + +:build-node-weak-failed +echo Failed to build node-weak. +goto exit + +:run-tests +echo running 'python tools/test.py %test_args%' +python tools/test.py %test_args% +if "%test%"=="test" goto jslint +goto exit + +:create-msvs-files-failed +echo Failed to create vc project files. +goto exit + +:upload +echo uploading .exe .msi .pdb to nodejs.org +python "%~dp0tools\getnodeversion.py" > "%temp%\node_version.txt" +if not errorlevel 0 echo Cannot determine current version of node.js & goto exit +for /F "tokens=*" %%i in (%temp%\node_version.txt) do set NODE_VERSION=%%i +@echo on +ssh node@nodejs.org mkdir -p web/nodejs.org/dist/v%NODE_VERSION% +scp Release\node.msi node@nodejs.org:~/web/nodejs.org/dist/v%NODE_VERSION%/node-v%NODE_VERSION%.msi +scp Release\node.exe node@nodejs.org:~/web/nodejs.org/dist/v%NODE_VERSION%/node.exe +scp Release\node.pdb node@nodejs.org:~/web/nodejs.org/dist/v%NODE_VERSION%/node.pdb +@echo off +goto exit + +:jslint +echo running jslint +set PYTHONPATH=tools/closure_linter/ +python tools/closure_linter/closure_linter/gjslint.py --unix_mode --strict --nojsdoc -r lib/ -r src/ -r test/ --exclude_files lib/punycode.js +goto exit + +:help +echo vcbuild.bat [debug/release] [msi] [test-all/test-uv/test-internet/test-pummel/test-simple/test-message] [clean] [noprojgen] [nobuild] [nosign] [x86/x64] +echo Examples: +echo vcbuild.bat : builds release build +echo vcbuild.bat debug : builds debug build +echo vcbuild.bat release msi : builds release build and MSI installer package +echo vcbuild.bat test : builds debug build and runs tests +goto exit + +:exit diff --git a/node_modules/.bin/sardines b/node_modules/.bin/sardines deleted file mode 120000 index 6a4bc8f..0000000 --- a/node_modules/.bin/sardines +++ /dev/null @@ -1 +0,0 @@ -../sardines/bin/sardines \ No newline at end of file diff --git a/node_modules/celeri/.cupboard b/node_modules/celeri/.cupboard deleted file mode 100644 index 46d2b19..0000000 --- a/node_modules/celeri/.cupboard +++ /dev/null @@ -1,2 +0,0 @@ -[commands] -proj = subl --project project.sublime-project diff --git a/node_modules/celeri/.gitignore b/node_modules/celeri/.gitignore deleted file mode 100755 index 6e9e865..0000000 --- a/node_modules/celeri/.gitignore +++ /dev/null @@ -1,2 +0,0 @@ -node_modulesnode_modules - diff --git a/node_modules/celeri/MIT-LICENSE.txt b/node_modules/celeri/MIT-LICENSE.txt deleted file mode 100755 index 31d6550..0000000 --- a/node_modules/celeri/MIT-LICENSE.txt +++ /dev/null @@ -1,20 +0,0 @@ -Copyright (c) 2011 Craig Condon - -Permission is hereby granted, free of charge, to any person obtaining -a copy of this software and associated documentation files (the -"Software"), to deal in the Software without restriction, including -without limitation the rights to use, copy, modify, merge, publish, -distribute, sublicense, and/or sell copies of the Software, and to -permit persons to whom the Software is furnished to do so, subject to -the following conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/celeri/README.md b/node_modules/celeri/README.md deleted file mode 100755 index bc81c9a..0000000 --- a/node_modules/celeri/README.md +++ /dev/null @@ -1,357 +0,0 @@ - -### C-e-L-er-I - -![Alt command line](http://i.imgur.com/DA77U.png) - -### Features: - -- History (up/down arrows) -- Progress Bar -- Loading/busy spinner -- Password input -- Confirmation -- Prompt -- Multi-line tables -- Build flexible commands via [beanpole](https://github.com/spiceapps/beanpole) - - OR statement - - Middleware - - Parameters -- Trees - -### To Do: - -- Help menu api -- Title View -- Custom colors for each view (input, loader, progress, table, etc.): exports.colors = {} -- Error handling (display of command not found) -- Add transports instead of depending on native stdin/stdout - - Ability to use online - -## Usage: - - -### .on(event, callback) - -Listens for a key (enter, up, left, backspace, etc.), or command. See [beanpole](https://github.com/spiceapps/beanpole) for documentation. - -#### Hello World: - -```javascript - -var celeri = require('celeri'); - -celeri.on('hello :name', function(data) -{ - console.log("Hello %s!", data.name); -}); - -//open up character input! -celeri.open(); - -//parse the command line args -celeri.parse(process.argv); - -``` - -In terminal: - - node ./hello ↩ - > hello world ↩ - hello world! - -passed as arguments: - - node ./hello hello:world ↩ - hello world! - -#### "OR" statement: - -```javascript - - -celeri.on('hello :name OR hi :name', function(data) -{ - console.log('Hello ' + data.name +'!'); -}); - -celeri.on('set address :zip OR set address :city :state :zip', function(data) -{ - console.log("City: %s, State: %s, Zip: %s ", data.city || 'None provided', data.state || 'None provided', data.zip); -}); - -``` - -#### Middleware "->" statement: - - -```javascript - -celeri.on('delay :seconds', function(data) -{ - console.log("delaying for %s seconds", data.seconds); - - setTimeout(function(self) - { - if(!self.next()) console.log("done!"); - }, Number(data.seconds) * 1000, this); -}); - - -celeri.on('delay 1 -> say hello :name', function(data) -{ - console.log('hello %s!', data.name); -}); - -``` - -here's what you get: - - > delay 5 ↩ - delaying for 5 seconds - done - > say hello craig ↩ - delaying for 1 seconds - hello craig! - - - -### .progress(label, percent) - -```javascript - -var i = 0; - -var interval = setInterval(function() -{ - celeri.progress('Label: ', i++); - - if(i == 100) clearInterval(i); -}, 10); - -``` - -### .loading(label) - -```javascript - -var spinner = celeri.loading('Processing: '); - -setTimeout(function() -{ - spinner.done(true);//undefined = done, true = success, false = fail -}, 1000); - -```` - -### .prompt(label, callback) - -```javascript - -celeri.prompt('Username: ', function(input) -{ - -}); - -```` - -### .confirm(message, callback) - -```javascript - -celeri.confirm("Do you want to continue?", function(yes) -{ - if(yes) - { - //continue - } -}); - -``` - -### .password(label[, mask], callback) - -```javascript - -//mask = * -celeri.password('Password: ', '*', function(input) -{ - //password -}); - -//no mask -celeri.password('Password: ', function(input) -{ - //password -}); - -``` - -### .auth(callback) - -```javascript - -celeri.auth(function(user, pass) -{ - //auth here -}); - -``` - -### .loadHelp(filePath) - -```javascript - -celeri.on('help', function() -{ - celeri.loadHelp(__dirname +'/help.txt'); -}); - -``` - - -### .drawTable(objects, ops) - -```javascript - -var objects = [ - - { - name: 'Craig', - age: 21, - interests: 'Cooking, espresso, backpacking, coding' - }, - - - { - name: 'Tim', - age: 21, - interests: 'Design, Traveling, Photography' - - } - -]; - -celeri.drawTable(objects, { - columns: ['name','age','interests'] -}); - - -``` - - -Gives you something like: - - -![Alt command line](http://i.imgur.com/oUtC9.png) - - -Here's a multi-line table: - - -![Alt command line](http://i.imgur.com/O5o47.png) - -### .drawTree(tree) - -Draws a tree - -````javascript - -//print out the contents of the celeri object -celeri.drawTree(celeri); - -```` - -Here's another example: - -![Alt command line](http://i.imgur.com/4F0e0.png) - - -### Let's kick it up a notch - - -```javascript - -var celeri = require('../lib'); - - -var credentials; - - - -celeri.on('login OR login :user :pass', function(data) -{ - - //reference to the current request - var self = this; - - - //called after auth credentials have been entered in - function onAuth(creds) - { - - //credits wrong? DO NOT CONTINUE - if(creds.user != 'user' || creds.pass != 'pass') - { - return console.log("Incorrect user / pass".red); - } - - //otherwise, add the user to the CURRENT request so it can be passed - //onto the next route listener - self.user = creds.user; - - //cache the credentials so the user doesn't have to login each time - credentials = creds; - - //not another listener? display a success response - if(!self.next()) console.log("Logged in as %s", creds.user.green); - } - - - //user already logged in? pass! - if(credentials) - { - onAuth(credentials); - } - - //otherwise check if the user is passed in the route - else - if(data.user && data.pass) - { - onAuth(data); - } - - //or prompt for authentication - else - { - celeri.auth(function(user, pass) - { - onAuth({ user: user, pass: pass }); - }); - } -}); - - - -/** - * This stuff's private. The user has to be authenticated *before* this command is executed - */ - -celeri.on('login -> account', function() -{ - console.log('Here\'s your account info %s!', this.user.green); -}); - -celeri.open(); - - - -celeri.parse(process.argv); - - -``` - -Here's what you get: - -![Alt command line](http://i.imgur.com/g7ywq.png) - - diff --git a/node_modules/celeri/examples/auth.js b/node_modules/celeri/examples/auth.js deleted file mode 100755 index 921aab6..0000000 --- a/node_modules/celeri/examples/auth.js +++ /dev/null @@ -1,13 +0,0 @@ -var celery = require('../lib'); - -celery.prompt('Username: ', function(user) -{ - celery.password('Password: ', function(pass) - { - console.log('user: %s'.green, user); - console.log('pass: %s'.green, pass); - }); -}); - - -celery.open(); \ No newline at end of file diff --git a/node_modules/celeri/examples/authadv.js b/node_modules/celeri/examples/authadv.js deleted file mode 100755 index b53875e..0000000 --- a/node_modules/celeri/examples/authadv.js +++ /dev/null @@ -1,69 +0,0 @@ -var celery = require('../lib'); - -celery.open({ - - //required for middleware / or statements - //delimiter: '/', -}); - - -var credentials; - - - -celery.on('login OR login :user :pass', function(data) -{ - var self = this; - - function onAuth(creds) - { - if(creds.user != 'user' || creds.pass != 'pass') - { - return console.log("Incorrect user / pass".red); - } - - self.user = creds.user; - - //cache the credentials so the user doesn't have to login each time - credentials = creds; - - if(!self.next()) console.log("Logged in as %s", creds.user.green); - } - - - //user already logged in? pass! - if(credentials) - { - onAuth(credentials); - } - - //otherwise check if the user is passed in the route - else - if(data.user && data.pass) - { - onAuth(data); - } - - //or prompt for authentication - else - { - celery.auth(function(user, pass) - { - onAuth({ user: user, pass: pass }); - }); - } -}); - - - -/** - * private account into - */ - -celery.on('login -> account', function() -{ - console.log('Here\'s your account info %s!', this.user.green); -}); - - -celery.parse(process.argv); \ No newline at end of file diff --git a/node_modules/celeri/examples/confirm.js b/node_modules/celeri/examples/confirm.js deleted file mode 100755 index 6573244..0000000 --- a/node_modules/celeri/examples/confirm.js +++ /dev/null @@ -1,16 +0,0 @@ -var celery = require('../lib'); - -celery.confirm('Do you want to continue?', function(yes) -{ - if(yes) - { - console.log("YES!".green); - } - else - { - console.log("NO!".red); - } -}); - - -celery.open(); \ No newline at end of file diff --git a/node_modules/celeri/examples/exec.js b/node_modules/celeri/examples/exec.js deleted file mode 100755 index 016b5b0..0000000 --- a/node_modules/celeri/examples/exec.js +++ /dev/null @@ -1,11 +0,0 @@ -var celeri = require('../lib'); - - -celeri.exec('ls', ['-help'], { - exit: function() - { - console.log("DONE"); - } -}); - -celeri.open(); \ No newline at end of file diff --git a/node_modules/celeri/examples/hello.js b/node_modules/celeri/examples/hello.js deleted file mode 100755 index f9bf4bb..0000000 --- a/node_modules/celeri/examples/hello.js +++ /dev/null @@ -1,52 +0,0 @@ -var celery = require('../lib'); - -celery.open({ - prefix: 'hello > ' -}); -celery.on('hello :name', function(data) -{ - console.log('hello %s, how are you doing?', data.name); -}); - -celery.on('download/:file', function(data) -{ - console.log("starting"); - - var i = 0; - - data.file = decodeURIComponent(data.file); - - var interval = setInterval(function() - { - - celery.progress('Downloading '+data.file+':', i++); - - if(i > 100) - { - clearInterval(interval); - celery.newLine('done!'); - } - }, 10); -}); - - -celery.on(['timeout :ttl','timeout :ttl :status'], function(data) -{ - var loader = celery.loading('timeout for '+data.ttl+' seconds: '); - - setTimeout(function() - { - if(data.status != undefined) - { - loader.done(data.status == 'success'); - } - else - { - loader.done(); - } - - }, Number(data.ttl) * 1000); -}); - - -celery.parse(process.argv); \ No newline at end of file diff --git a/node_modules/celeri/examples/hello2.js b/node_modules/celeri/examples/hello2.js deleted file mode 100755 index cfbd773..0000000 --- a/node_modules/celeri/examples/hello2.js +++ /dev/null @@ -1,19 +0,0 @@ -var celery = require('../lib'); - -celery.on('delay :seconds', function(data) -{ - console.log("delaying for %s seconds", data.seconds); - - setTimeout(function(self) - { - if(!self.next()) console.log("done!"); - }, Number(data.seconds) * 1000, this); -}); - - -celery.on('delay 1 -> say hello :name', function(data) -{ - console.log('hello %s!', data.name); -}); - -celery.open(); \ No newline at end of file diff --git a/node_modules/celeri/examples/table.js b/node_modules/celeri/examples/table.js deleted file mode 100755 index ae06cb0..0000000 --- a/node_modules/celeri/examples/table.js +++ /dev/null @@ -1,44 +0,0 @@ -var celery = require('../lib'); - -var objects = [ - - { - name: 'Craig', - age: 21, - bio: 'Cras dictum convallis fermentum. Quisque ut urna velit, at porta nibh. Nam iaculis dignissim nisl, non elementum tortor iaculis et. Curabitur vulputate, sapien eget' - }, - - - { - name: 'Tim', - age: 21, - bio: 'Praesent ligula est, pellentesque vel euismod vitae, condimentum convallis odio. Suspendisse potenti. Fusce lacus arcu, bibendum in gravida at, dictum vitae mauris. Cras viverra, dui ac elementum fringilla, purus mauris rutrum nibh, id ultrices diam magna id ante. Integer elit ligula, cursus at accumsan in, scelerisque at dui. Sed pellentesque justo sit amet nibh sodales sed malesuada nulla cursus. Maecenas eu felis leo, a volutpat sapien. Duis eget porta urna. Maecenas ligula elit, vulputate ac bibendum eu, dapibus ut lacus. Fusce ac tincidunt eros. Pellentesque ut turpis ac ante interdum rutrum. Suspendisse tempor lobortis semper.' - }, - - { - name: 'Michael', - age: 23, - bio: 'Vestibulum ligula elit, vehicula a lacinia at, aliquet sed felis. In rutrum pulvinar ultrices. Donec interdum ullamcorper neque ut pretium. Donec varius massa vitae ipsum feugiat feugiat. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Fusce a nulla a odio congue hendrerit in non tellus. Cras gravida vestibulum augue vitae dapibus. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Fusce porttitor rutrum faucibus. Vivamus interdum porta orci, vitae fermentum nunc vestibulum at. Maecenas porttitor sollicitudin pharetra. Ut risus mauris, tincidunt vitae laoreet quis, rhoncus eget risus' - }, - - { - name: 'Sarah', - age: 19, - bio: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin fringilla interdum nibh eget luctus. In facilisis varius lacus, ut adipiscing turpis posuere a. Nunc id sapien eu urna' - } - -]; - - -celery.drawTable(objects, { - columns: { - name: 15, - age: 5, - bio: 30 - }, - - horz: ' ', - -}); - -celery.open(); \ No newline at end of file diff --git a/node_modules/celeri/examples/table2.js b/node_modules/celeri/examples/table2.js deleted file mode 100644 index 13c47d1..0000000 --- a/node_modules/celeri/examples/table2.js +++ /dev/null @@ -1,29 +0,0 @@ -var celery = require('../lib'); - -var objects = [ { name: 'bean.cupboard.scaffold', - hasUpdates: '', - published: 'published: 2 hours agofdsfsafsfadffdsf afsd fasf as fsd fsdf sdf sdf sd ' }, - { name: 'teamdigest', - hasUpdates: '', - published: 'published: 2 hours ago' }]; - -console.log(celery.columns()) - -celery.drawTable(objects, { - columns: [{ - width: 15, - minWidth:20, - name: 'name' - }, - { - name: 'published', - width:15, - align:'right' - }], - - horz: ' ', - vert: '|' - -}); - -celery.open(); \ No newline at end of file diff --git a/node_modules/celeri/examples/table3.js b/node_modules/celeri/examples/table3.js deleted file mode 100644 index f7ac0c4..0000000 --- a/node_modules/celeri/examples/table3.js +++ /dev/null @@ -1,59 +0,0 @@ -var celery = require('../lib'); - -var objects = [ { command: 'init', - desc: 'Adds a project in cwd to cupboard.' }, - { command: 'remove ', - desc: 'Removes project from cupboard.' }, - { command: ' ', - desc: 'Calls custom command specified in project cupboard config.' }, - { command: 'untouch ', - desc: 'Flags given project as updated.' }, - { command: 'publish ', - desc: 'Publishes target project.' }, - { command: 'updates', - desc: 'List all projects with updates.' }, - { command: 'list', - desc: 'List all projects in cupboard organized by most recently updated.' }, - { command: 'install ', - desc: 'Installs a third-party cupboard plugin.' }, - { command: 'uninstall ', - desc: 'Uninstalls a third-party cupboard plugin.' }, - { command: 'plugins', - desc: 'Lists all third-party plugins.' }, - { command: 'scaffold ', - desc: 'Initializes target scaffold in cwd' }, - { command: 'github ', - desc: 'Open github page of target project' }, - { command: 'github-issues ', - desc: 'Open github issues of target project.' }, - { command: 'help', desc: 'Shows the help menu.' }, - { command: 'dir ', - desc: 'Returns the project path.' }, - { command: 'details ', - desc: 'Returns details about the given project such as modified files, and number of updates.' } ]; - - -celery.drawTable(objects, { - columns: [ { - minWidth: 25, - width: 20, - name: 'command' - }, - { - name: 'desc', - width: 80, - align: 'left' - } ], - - pad: { - left: 10, - right: 10, - top: 2, - bottom: 2 - }, - -ellipsis: true - -}); - -celery.open(); \ No newline at end of file diff --git a/node_modules/celeri/examples/tree.js b/node_modules/celeri/examples/tree.js deleted file mode 100755 index 48f5087..0000000 --- a/node_modules/celeri/examples/tree.js +++ /dev/null @@ -1,34 +0,0 @@ -var celeri = require('../lib'); - -celeri.drawTree({ - 'home/':{ - 'network/':{ - 'apps/' :[ - "cliqly", - "clove", - "team digest" - ], - 'public/': { - 'git/':{ - 'some-project':[ - 'index.js' - ] - }, - 'npm/':{ - 'some-project':['index.js'] - } - } - } - }, - 'downloads/': { - 'libcpp': [ - 'makefile' - ] - } -}) - - -//celeri.drawTree(celeri); - - -celeri.open(); \ No newline at end of file diff --git a/node_modules/celeri/images/screen.png b/node_modules/celeri/images/screen.png deleted file mode 100755 index 69fa5c5554fee77217b8279e1a39a68aa24297fe..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 51631 zcmZU)RahKL)ToUHcXtbJ2|BpD6WrYiPJp1n9fG_2pc&j<1Hs+h-R;ai|M~XL_xu-J zP}5!ARkeJ*9j>e>g@Q8Z zT-n*d!rIOp0>T4wHrY}Qdl+}HqLmhI3Ym)Bc!YW{K&+cxkRW5H3 z%1aC0zEDh1!j!Dq8^c*4Drx#^Fom3e`2AK3c+UMD9nEpl%=+4m>ANA5zW z6otfoTd$$une7@2*S6sxb_e!>`Pmc0U~QC`+VM``!nf}A+sSt4$wZXXh0fm4#}Wt6 zt%a{hoVsJI(w8V&dxdI3CFbK%muNZ`UkkUn{nUW$wu@vLV^4Qg4=88ra}XyGaN3G-#2z*chb{m%PCIzNH)7%fp@XGqlE&;qc^3Vc4ufd1!M7jW5xk#UP z$4g`pryHGr!{m`N2@>+?ZF(-W#p)+a6e>f|{+H}!7 ze&7huaD>%^YZT!=fDSamj|$KhWH z*d#idYyg)SUmkxcIzuo+uFiqx0hB9j3&O2%Y%Ycsloy;&2u3Q@v@wAe>|F3~BfbTa zyU_Wb$qPvU)_BN$7qug`H|E!%>aNC3K@WUiSS1Pw3MyoA(n-lNbhthu1c`if$U2;1 ziHLaFLQ-oH-uUOCPgjJGLEXky_%xD4rr}QgFh+pX=+w$oZ+ZIS57S|XT`Pl8Ml_!d zYt?`p8d$ag=Ei}wlM5Vns15kK(E_pUA*a1D#wAVwV(5|x_WtHAQAejHg(mM63_a*7 zl=(oSeud3T51BTaHN^91%k6|qo(Hjqgon`wgBScassQ;oDtz=zggh8hW4OFj#~+U2 zf8;zwQmG@*lfrSu9Vk;$MVQD*sT$DFF$TkaeN_3$FdVU?6hUQAn-q5>GcPSxcyGq0 z9bl(upb$fC880_fGR!?hwWEanIpRZq0H&l&-bo&D2}p%hW$jCu8csPgXJWeis#s-_ zL6KmQFLpk{A$)C6ljw5LNDyJLSMVAo+Ee^f zLi?zgf{H2a8-N$-D|UONAUzAs*N>!h*(?S$zAE0S0iV?HnIxeK{GCE3Cmz~FErM4g zhHzRnXQ~hMKU3AJ_GnP5QflUlNYKW*)2pflr2KHb{{LD`?Ni>N! zY27OPnfbG1%A$z3XmCW_oP8I6H*h3tgq@+BL4=`IEnRIuomx%1JgwZVT+Bv|lc+x0 zCdmeE#_7o7=<-Nvrj^qO#WWf}nl1W!dQEY-1#l1JHz_kPxfxffLe*9{Bj3Ixt6aZC zAiwv|<)6j8>B4JCO&M;rZ#iE}&NKx~+hN*Gy#k+1p1wZu-RRz|6IkIpB99=G;;W)$ zp)?Y35p{4*aYS(N+T8p}wK%bE8*N&Bhzu_a?ror#Sh=Y=^e0#y8)RBP3E`Pr zS@X{DtazkF!iqGDWXJW>w$UBX&8{IfENWqJo~>0c&_L9%t3a$Uwk>vRx}BKo<+|ds z%aF~mY=~&kTeexob3bx-a;H6ATR2`sI+<9W0B8a1oUB~LiS>zHNLn-dGNCeMv$A;^ z0aASPJW4J2t#;1VF8wVnt!FMIM#D7#pw3)jM%glMBkH$^)|~HU&+KR@XaQ1@v?qsq z&Fd~ha*L7svpXnl+H244IS-{zb~lgqoL}oFj_PJ7d~SWXpWUA(U*?{(E;8;K?^!R% zkd=|75vj$iV2XLAi4;b?p zzuKzL7gx78E86Jyv_u{U&;OdwK^Y8z3(kShG5!9Faq$ZVFsv6Nff#OFWSp^zxiO3n z!x~2$|B-Tpq5P8#{}O|j-;H>bg1pn%u~z89)Iy_EmD8>h`{ml@;PyV&4@^Q#gz(L9 zJP(sL4}-xEiztUgUJvOn#BUdpk$K~!+p@D+XX^BP-iv2;*JWrB)un1^aQL#4+-}b_ zN?l>WXZ`)PgS++_!#l>c=}D}9E6O*r zrB}|BjPHy}tknPqmYf8?W7^joS>N<^too9QuELE2gB63dwKpHGXB$KbBz7dJ`|oEC zOeVOyxITcIx31qN1zT5vg@N>Np>q7P>1gyMOW&=kIEq2lV;#WFnw!nlP|Fy{*c;M% z0Ubk@FWH)JkNXQbWExFs92(_nxSE^gsukH}Nc?k;k&CSLv#PV6vxYI(F=+D-bFMS# zb932of-1^z^F=cXnaF&LJ|mZEF756<63_({=Ny16=cnE3&Ca_VC!uNIxf8oro?VyF ziRtluF41U$=mdq&3cbH6ehc8Ouz(u18ZzG%_8Ye=uPV*)`dM-HDD_7=IQ)37uhfV- zPj8bB7z<91m*J{E82bFFZ7DcTf37E*&#E>&1s%6}_Z~?eD@11CeN9`nX|Z>1y^Oic zy8ae@o_)@CXwzotRo%SY)>>q#K2clBqQBhqYl>5FZywG(acGi0- zg%G*s*aMbH7*0yyudt^ev)89%5H`uUbhH0rD9 zWAGw+CUM%-?QtA*Eq*`B$vS9oY52Qi{PD}pM6bilTITcUT{T}qcY>({ti%5LZfAA)(cYqRBCxUp>hVaPU zrf^jg$*5t55VX2(gssWjZ2XYSL_hM!D4yIIi$Nh`e}BDT3B4M%D<$CZak2REk#)9o z&J$U9`R3;b!>|GPKjUzdt$Z$2^K7==*X^$;$$t*`Ouur=fg@1_M`>*r2nZysfBqmL z(lhZPAjlzP#6{FRAWyR3QnCBzLTsIvGKXc*)!66|^GzTmuq7nqJ=E1$JaE)L{V?gu z>>Bg?ZPHgEjSfwoD-KD$Pn^7J?vh^f{^(U%+n9Ektj z4@2VCdZT^%_df8PGdxgCCdVt(+o)eYoq^nl1;6XTMb?#!(Ne zv|PDTt=*K`Dz+u8GRPxZ+*?w0uc@Q8$>pyn0YYFXF@W)j7*e`pq?{N;c^_>EvjN=Tyoq z$f?kF8swziIDqFnTN*ZtQKJ)I7H#T(#6ghki|${XY2a1ba&$#(@t>S^g$oNaGSxc` zldHAJCkT#|_ii4AFnlQxZ5R-@w5z{pYBUCH!rOpv^??s$u_5>*UjSAVjyZ&N~;ZG%neY( zgLkno6tQ9&fIgoesDZ;-ldoRh!>?s zVN@xaC0$-BQN$b7as=pEYHEoZOXwK;GH6cd4X`&T1u2^+j=Y5ab)0T-{@6jP+e3g5 zOa=v16;`F>fY>`_jfRTKl5sIlH$4(bgXkt3ZIfOt#*uyy; znh_jQ>60Yyf_y)kgWUf2vL%EgWZJJQMu%!{%moNi1g9{Pov4KLJPUh=pOzdwEjWR- z>bSM_AB~Dq)t=o6i$Y@n=AhktwXFAVbz9cc^-gZuLFOG?S=)ch5)#Y|rOK*d8tHh7 z`RpTGra~I5YvL5e^h^gY@GGqv@0EEA7jUNX2=t@ia~1?iq6tO^@~A6;=5t+UG$M5r z5qH(-pFA_U8YEA3M#$mrd+$E zNdGW@8q4UAE4FAhZxqn@o~ohzg;E1i$(2S;3sKFjgG*tcD7G&8{pq-x$l1k(?B>xs?3d|(G7o`O zDgmWYq24zzAn3AWUE(8NvUq)8HnXK35?_Q8D)-OK4DgHPVGHT0iV&0Z`lU5Gi6h?j z>5u0h%vx?vB_t#Q+YGeo7XQ*ju*v0uJgDmF>0vzN&zXjd)(~-2CFVtm9f*(ll!+{7 zm=OXP8EKd?-cest*XavMlg$;VB}Vsl!`}s2Z^AH*q#>9Pb*{&HQIG&9YNnEtlOtZn zm})I2tG6zSfA<*b6(%+U^eHtr%- z6;Ro-pFjWt|2phha)?)n*}O?n1R8ji9d(Hz)p{zD8*}r@+9cfC^yzZAV$@NSC5}F@ z;#B&p_lhpqnFUJ-{!YPp)_9?4@ZnYv=gZ1BcCM2KJbvU&&?a7M)Fgg#sn_Z-tF`i6 zOv*Q&XX%kKx8nj5Af1|JJXRz}Y%LlhY05`Q+s{Zh5pk*aIdpgEQ+^-RiEn@6-aO%! z7I)(n*y5T$(_!(|xv#(I^ALC5#*W8c7kz;CjgNN|w&QOS1+Ls?G+iW$Y|Rv}A}=Ga zepfVy8svt2Ip{+hZrRyEvySX{mT!r!hj?((pWd&obdN>&C`b>sXq>Ve=bX|JxCJ2; z8hOj)2D@7y1t{eDv1yNo0N!rtyg(K#l_u5okLoo&BZ|2RSHgrnn=nA8lEiMf#_T{? z_xBN@z8F>^tl#`BPO8rNR&L#}`IB9v!NVrF-#eZa?VdNKYCX>lYPTyUa&09Fs#aY) z#c?Xmaz=w3?glBD`>E11FM_+U`{@ZH3L8-XM)-S>G&uW4Ek{orE3MY}<*&*znG9cP{wRLWO|bX1%TTYlfE| zpxPHbmG4_sEV!b|#4*L!G=?~}~UnSv5~et!9^nY(*K(_Xr5U+Z}X zV>+j;MrA{c#cntjEn@5-)mig?c7f;8Msu-J4ogSDL>>K?VwhS z*EfRhpTT6=K7Mgj^NNGI{AssTe>x8mGS=6lSk|hR$YlBKJiT^c6C_jh?rNBejg=Q z5DsouU_uA790tSoRLWsp+s$Xkv=S8EsD>HdCfD$=0x5eEecX5(RQPYk*;<`;wOXAI z+?kr7+Vp;F$m*Jm*PbI#*h#*>aMlB43jJf=n}_BE-ej$LzFR0@Gt3>qHc>_k`dNH2 zuSjj>Bh%Yz4~AR^j}GWgOJeiNE?&tEsw_~9v!w8~**?667nuK87T$xki_Qgi2V9`y z+V=?V9HWh>OzXjsGE_U$ssr-$7X#%3cGWj3f`%@d(@G;o_JmMN(Vn>4JXt^%Y3* zZ0lafl^Z_Mbxn;K+zu>T+uKRcCKnssBe5UCmLZ`(gatsuMXdWiE9eO;Ef)61wz!`z z4O{)0FV6XX)(myp{wen5U2Z3u09NU^;b`h6fvF15rAW|^EGEWu7sYj~I z$QH{OX2pC0<%|VZH;rhSQsLItIguDfsM=%DD~mls_`4q3_Rh{_5d8$m7sdCf zF#08V^l#;h+TbW4)JAnM*|W4-o#)DnuExByt4UR_HnrX6cguY4Ny274sUO0ymYX86FIDVzcXk*oo*y331Wcu>j2kd?EOCXtF&hw&tETR zH4PEG55FDHDF}b+ydLL^(6X8?j>c4ymPYr${=RJAh~RY?X0=e0H#9M!c@#^?DJ!4B zr2y3aCF!}s=e#3r?k94xk370qtdNn|lEwE8mr629Ioo&W{o954Lr(mR{7|VMU^E1U zsL${H*|64jo(0n4_4!_tlzlq1WC|e)fvKzIONru0fkWdm$;mI$>vRH%evQHfJ&;wr zGs&eE@%)Y9`%{WZ-mGa%a>whPuDLAyK;ZFbi!uCNn7Y;33eCv-weLzBQj<8EdU^1J z5dx))_(0&)CZYFbKi*bBtRUi>bdLb->RhF+1dV`GZvuqp#0FvK-IDEA-6#u|&+}c9 zM1LlaOJc3y^T{uf3g$V$$y&Q^a|nL5otOsOQ6$r#AQnIbVM9#Ch8P_RarbGaLu<>608qg(b`Eq%HTj3Y`g2ACeR$!njsrO$%|4s7aDM zTm)CcQ)Q2#4IZv6x3)cH13CFsBxrsugZ`_6qT;uT8g0n=e*ZO0{#f)!DE896tjN`z5up)X!qIsU~YXa;)uz zUH(l0()|T9mf4ae zYbP*_4g?vGD7Ofy^LRwjj)-yuz z`BG#)YI=UJw}{aERoS16e^7Qk-y9aeH-qC_y%pzCW?2IMCEu-ZT5%g2o0nTaV+6QC+8l3HyOk!DTr~6rKo=YFwOA-Bee9Od`-_XY0lj#E8S8QuuUq+5FN`N^ z+r(&pXW`o{YbaqSE0PUvTdhUX@jB z&C(%(k4E+<>u)=CakK0+icJSdt0KRY?BAR>OYP+b6mA+28Ba+!!Xh!bZ05H>NbCsa zPl?Q|TlWZ9;aUkvxHQ6H7Af#p2!`z)EhJwzX(%@Hm^)86`nwfms}5hD!g1gV~A{ z$`2GjYRFN3Kx*iZoeFG6vH!3yTNY`Z5|OT`bYv6AM2r08-rsTJ(DY^;^Rd`U@B3*z z6t4Qxm~NUSG6u}?-Va!$L@tU03S!-Q8){zn6MW+DAIHr7C@_t8qh>axK8%;R;bT?N z0yj5Y#(DO`$b26}tciSjiQIcW54LIQZ98;4N;VH@<H^2Bf||KA#sQ^J)wqP=H{eQ`qQG>&R40Q3CW{$ z3B-6;Cfo<#)IWOpOeXIFumAz@!dimUs9O@n^ z^J@uJyY#Oac~9fkw{^Q(pVWnU!|K4+IP&1YN+Q)rkx{(z91V5<=k8|3wiQ`y&L%mc6FHgNVf*sd{korK5Z=>No98v6o4Ky6`7Bx3 zs=)WVQq`NlR4n>IYPpfOkYloeg%&qk^CI3OVdQ$dMO7y4I`Km)(&mcmBD$X^(W#@p zU2w7Lpdk*``6j3BxK=KIdZwhSNp2W2;CX7DaUXHdLqDD&wvxbYqDfgFHq1+|zgX*y z2B~=je9zCUw&W$>`M%qD`zO>H@90qGV18PA>PP>#uzf*IiSJ!o|oR{-;;L>CtI+e)jF z$Xu#cAPv7_iB@M{(K-K`qDj7Z7S{~Cf@{Afs9paBhr#<$8IBCW7aa0JxnoY!! zu?EV?87d!_`rg^$nDkmReYeo#46lx!k>}_EW7-0*H`9TiE{2GoX-9dFSl!cT`eT7X zY)1_$s7~6X#%{zKY}%yeW}bGiu(mWXh)hAIgE1(3*2_QllLc`vyV&r{dI9ESW+a|5 zj<0gEvZ_y^mm@qix(#+J8dU|%VPgCv8jXz0;^`PJi)at%fi>__N93hq+WE8lDfZnA z5wmv(38XGNVuhw}S0y>V3<_$-*1k z!UQg*XvDH;yhI9jtoai78Qvf<$Z$<9)9>yFbYAXZyGi=B$MF}T~+0RZjDai`AE^AD@sswG3J8&&D|&Vj+(=G(o^6@zsSAF)3{iV3{<0v zJYRfHR<%uVAT1jtJz(aY7846ANkaR)^S#5QEU+|wOI@HuMPDkU-tYiiOJl2Iu8tnH zr5x>*4HFPRBjqo(%LtO-be{EWYN!k-O{(MuKgi>oq7$z2~+1 zLoTslw27rLYPtmJi@%}5rBT0)A-EKi*nGlQ{Bb5I&?wZ=elkC}2j|)ZY;KK9xF#>~!uazL&#mRp zK@xh`d%v*~Xq7bjjtgZH68ppGuw;j}o_focg;z>h>3U-jGP_`YctzoF2*vAwWSQak z;d^BaBWA8g?>cDO(gO~~FWNj|UFsYL=l zCwG(d$uhg)!Zv@thzl(Wgnq)fxaOpI>>XnNn}BCN-6>_=3hr?O!sn&h?tYWryhTbX z2E!&oKJhO3R$}FxO{-Ia;L*Okc27#a0%ccgk6KEj+b8<(y>HxC+2Zjd5=x84f<&lKMK?&n)5+ z)jZrcVSh0X(+N{g#aru|FOUX`5S!75WIj(fDtkT!sKf(NWTe#{Pvs`f0|2An!AS(y zAx`Z(FWU09-K4*qb>IhLUospzw5`EC%~*1sUek9) zK}3v{u+XRiq^7YdDz*u0MGA!2ha3x)%qu~mmwK49F=g0<1}i+&g$9xbE_Cy&X*FF8 z;Sa`;@FjY`hrOGYcE~sr%bLW0O}z_-{CL0EZR}E z3ls^a*OJg7HNHOc^re(T8$(2$!r_`FDJ`E;3FfKgIM{u@t6ttH4E>-u1sWu|w~-{u z8o!*HHvxCD-8Ac3O>6;5esRM;&Hpk%Hw;ur5FMB`l2&b4LEC z&^6BD8P*?mlvBS$heE9Pagtu!w}LLb0Q@^K+@_#o3-S$ zbi?T(UuT2w4(`3o6xVlg%r?qu|BRd|vvrbrhH{ zLcus4UkrH46w}etTs(wP1(g#e=BsDnvM`O7`_z|8v|!iE5LU zKbm34U3ctkp?gF0w1AR;n$CHlFU}E7za>|L6JY8LYtImkOSmFSf7`d-t2h7N=}YL7 z3D=K3*dMoVWtc5q!w1A75X(Uwy|*4+)Se{Vt$4jojZQbXaBO?Ms_vKd9^`QOay;uL zxy;tTX_!apg(A#ALaA1ZWQZt>7J{2g<^;%a#`>G#qC3i{in?4=PqMos5n4q*yUBR) z7e(Co)dU1%kLEJ6p%?=yt(cW6x7O3KYw^S8hB*$Y3hisEXhx&QTIMo>~&{u~Ul6cJ6>7JqEm^p60Cqpq%6 zx{7;c(<)U{RW#yur3v|_j?SN^Se2OHD_8=t{YBDYii0j0r2l^t>12p_kMPtwGeGjf zw9^EaMNy%^5nqAK6Qhpa%Er!M>evA#Cz&_1*3Ml+3C8sDVvh^)5Mad!Q7XRCJTMyk zuL%ckkIFzzmnb>-+oS1%tnyBb0%6Y=p3s+XjPv+#drZl!9{@XwGz+n5M<~V9_Jz<} zI6XL_$Q3?8VkD{$J@X;-GBOFC7e!xsIEubx(Om!VRc8VRJ4ANUSbrjP%|**U3;_g7OMqiT(@ryZZFnuu+{~5oONZCel8G751KCo5INj8y zD=htPL8b};2+Os`f37frB*}iH>87`cN@zx9`ZZzS^6!I^7tVoj)uQvEam$)ZsU#>G zb)LPdFbPL-6Xg-!8IBosKH_&vXQ~)aF|KDlu9^5>`+x!k&g2as*f#%%1yFAwOsdWf z*;Oa4ne%*eoe=$%~K?Yqq{cKJEjr> zqgwBE9eI8}^T(OC_tm$RON~pGT1|won5ziI6#Ah}W>}qePt9hl-6*NFsugEe(bX-1 z01fZ*WrwQ&UP_G|!smlP$YWI=C|zERnjnO=zd}C2DY4>n38TqjKLo&&j&{0;tX#g7 z!_AW*q*`Ey14^4lO;@Tg`kY(PYvlY3qK$5!0dz{Xdzs4&cY(8XA1=vc z9-$&YXS?ESV=PY2(Ot&z|L_6;4EUS#b;Au<6^{h^z3wfX6@c%lb!3sU{+TCv+{t1J7TB^e zaP#<*@X}Va&xX%t=Chk;khxw+eTT~T%>OnDJPSHSKpMMcgrkcIr-Bt{T2w(QFVlAV zQH#n<3a;Mjk4-l41S1Xgfg)buUhiQYvG<`_dKB4a&d;Se=jF8C6}*P#Kbti?@(SA- zCVtxe+VU2kFQ>v)=3P6MaP}j(S=Z~^Zq^N7`Myo({eCOs_Q8DK9jT5edA(H_W-fUj zbyL{4&3s+!c=*KN>(L8WJMng7_eP}IiSc|BtF*s8`LKXAAenbMj6{RS&$D0leE4pX>VD>xgTp>X#?k zZmCg07OtZl72ndgvgP^Xl(FOGJIdz+7pd=F9LL7%nYD}DFOi!(qwcKLvyWp}D<}V+ zstSUh^DuROX{of)gceT{#5CgGSXzNZ{;UZbscf}1Y*|Z`oo2E1=*Wxgqw|?{5rcYd z&03c^X?n8pVJN?T-~q?=1eLFhUB=Yh)1Ro&tFzbj_GTUl9!Q?(ZzJ_zOsbB(vTPqx z-p3DbZK|UJAK{=QrI;0EuRf*|>u@vPYZ$ZdNc%P}@3cfs=CR=G{GFm(ym#*U4B@oCi9w2o$c49B7Eac~5f zlqm&hOVB^qgksNu8sD;7mnUNuP2Ipmhar&I<~)^58Om| z4=!$7Mo%O_;hx4xqk7n7*S!ARXXEW0Ji}ehaBmamG?M#{hVWqNxXPOf@3a zu$^_XWVKUPi$E#*sg)n-hMaYA_aoTjVQ1#qYKxMJF&6e6(hRRw4cBpEdHm!Pu{ExO z;GEHn3_-cqa4%3Un$ek)k4~gEgB&iaW4S{i>I*h3oy3yc?7W>S;PWHcC8~Fr5i0pj zPplCd?#q$*6NlewHoL>ZYdHPY_JauD18_I`23So`c8h?uTeZ0$3XLa0D8mpmO!#K^XKlr%m=1hSLY zl`Mwy@zZ|%4y*GK1RrrxyC3Vs9qs^y1nfdWQ^u!M*Z6UZHm563t>tIb9xI-RKVuw+ zq@l$`!>i{3a5TLq(kDXwTG|lC#_Lz}9{zsw-aMKe8RIUw-A+(!I>s~(O8etPRpDx{%~dx0eQ(2#kNuH+Dqt=?#CxD)wogO)EX20 z8CFJ8cGD`6HPaUK0{ZRaecSVP-llaTB3+6TWn7Va?pWkL9>fr$k^S;mPo|e4;C3+6 zL|u^l5ibcBHo~XhWC%_SRV;UtiD;Vp(cSX=5>JJ9C90l1g2JTY3h>+?z&fzimATAr za26ka7d7s8KmTpNgY%(sK>^J{)&OL$av1EOmwMZ|{Dv3HlNTR_whzDGGn@0C;~B2i z^ucmQsNhBUW%jh<88>1gas9oTF4{dc)oXgj!>(DrvE2H$W7fd#b8*$^e-K#i5zJDf z1KElsk|+)(&a!p);GK>IKXkDeFV8H*+@cMj{wz{DPGeWkBTI9^OKau&n*|-2bsj3y zmxO7SYscd&xRMt+cKV9)o(D)S=ExAmmZ&ty$4RSnD4 zU*DVl0}GW4V8DUjBo2j+REy4x&2}j!1GD&-c8EdPc0c7;pl8bmG_w0kW|M&WOkRU#3| zJcHZT;~qQlQdhPWXe%s#Jzh~9>Q<+Z6b(;pUjl1T?7j)@ue7o>0pj4ErbpxCg#|UuMsu4auT|oL;DPFQPy=lY(-8o zY5=80UxShGXzq^ZCt|pa%(J*13@FF1XTB&&R2sDNdQM~ulyR?l6tMrivm8r}_rG&Q zCgHsaqelVrEQ(DVKafsR41JqT-(DWW@dsb;*A2UEysw67b!ikc@!MSwrwY|8G^h(I zDa1kmlR|%|vVeGmnMEIy>ZUD3I0WAL)5i7ec8lMHhOO?Wz{|_a2)fRlpK`?2oo`-D zFidNBZ623fA3fvYP>EA-mmNAi!F@V&ioCRkX(b^XA#i!VneKW0{f(Q2hez9*ii>Mb z{tKktIT$an>kUC+-X4e^^#SK_1@UAu&(-aBIvvx89RGADKC8Wlks*=rxr6k-t-4kH z8s{B-8|OR6?lO7q!&2%S&*E!zeZ1OT1A#cM$I{rbWZJw2W65$t-#RY`h-y&?IRN?0 zJY4?;7GTUHAHDP!Wiqb%qKk{mD7p0X^fWZMV{thedAFNlh`Wu?X_NR|oblD!)S!GU zK`?x}2@D8*AC^t0nwFK74SKrl>^J$$`E_MMG@p|Z9X{-{>3}$e(9b)+hs{t`&~q0w zTB%_-jZ)FWOx3S%=W7HRT=uF@im%aM*E`yADBY(DWomhNcmlxi6-jauoni^vawgNj ze@X_XcLf4?ZD+rqx8EaD9L!beXI#zcI`oUaNO;w+d~H0KtIUXIs_pl3%f*+0u@vj- zxjmewO<)2Bd$}H{&S_{;&dTV5;1nwyyZlG`J!0A5BD ziZ|(|;^~q1l`8$#C0u5m#G4Vu>OOI2rxw>k6ZVYXGlA>nm}k7$90LxpKGa7bHf0mDUp zUI{;cGJ!l~Jxy_$GE1_(%H395+&W%fUb?crtsM?PvFd+v5Lb zDH||U=(R?CYfXj4#p#`3CHBCqE(0r#Y*D`k!UBfT{n={w;5(>po!j$j$2(m&y~$;N zJaOIcU4Wnm52?p0UW0|X+}Y?D_-jINSe=2TfUVO3{!ctmNx&~=hd<;my6i-i2ij*@` z!}$b7-r+j8V+|o~qd;@3a!6o7F_-{>4R%<-Iy4KiH7t=8*XC&N4ifw+jb+861>Mp{^im;@ib{QX14*(PfvIKobiCmJQ zLMgbpbrq&HW}(6TFbwUKhDvs5LuPyn`AWSFAIeLoEra$nlau>ZEPn}>Y_J0BST&Wj zHDyvoaF|nm5D5`+WN6DvJgqkrEoBq_3-i{F;o%SI18`#_VTB(kQQd$f>XB`u2w(d8yG)HoEjxTH4TONUxsoL zp(acK^&Empwf7BlKzJ%`RQw1sn+=7{{#zANA>hH6jh{o`iq>zpRjdg7D>42E#GFv? zV><#iB|BJu$@M?qpd4WsVdx6@>Sg@x2RHE1Hx6Oc{j=lZj9Q+KDgqr?Qo(Lvcp#d{ z_RI%l{KVmLVYL5rd+c-bGk8N03A_#8wu_KJ@MA>9I_+|T8ZY(a)_GainJ(i_rPH-3 z=cOtI&a>9w4-ljhAl$i{!Cr%5CFLf$r!JmKYVN@Y%*n|i8K8?HDYfU_)o_i>JM-MH zxST#j@p)X3vqJsp*#v-1ixk+fCNF?lfs(20Y7{Gn1&$>uu3!Ui^w4&rSbSsVk4B>v z*#h5}oc?DHGvs}4MHZ9@`GO(X!7(w0OrY1v!2E;vjBDpD_f_ z>W`~C*O0`gx zO^pieCVpX>E>?(q2m3oru3JpDJ%Jr-P9z?w_xiWnXQ+h~;B+L*oDzLD;7+LmOkF4P{Stl}6n4?K>Q6rab!BH?=MzQVshpLeoq ztS7_=Ikewu;H^30SDk+4`VgRp*{noZtY&g8YPsbBQ;4$nf4X-dF`L3sjU#u_71s?jVSy$58@^7iO_h3-&=+||nP1mIcUzNXPI%i~ zzm<-Y_ze(PE*uUzu?T9`pMoj=bg%^Of2^>EG}w&xE}6FO$(~ESGE0n|_kO>bR-(Sa zr4T}xtNWrPFbf8Hv?iA7ZGD7ZF2sV#JeOQt{%;B${F!Vc*m?aO-foq?d4`xBXk6d)@n2Mlm{IsK-u}%xsl_-QwfMD3sHY%O)I|xAMp9jW0w9lCSd( zO0g)=|HMR)+G><+!3VS4gqR!CY`LD;2-N*oA|J2<-Q7Su#GkuVab@yS` z0VxmsL-_S&g7H37%+EaE?@lh)zpeYIfMr{Oax*msO{Q$JuTx%+|3|{g+FW8-(oVQ&oLNaA5@n4EF)vL64KVIc>G7}rMUt3yOB-h)_j);nK z#4};`qY2z7v$PK`h*zgY%PA^qbZ}UC1*I8$&Sss{umqT+w>6x22Qh>9=h}Uh86FlU{_@N=7zS~W?jA|k*;K)o^t~OZRell&)byd z@zB~zGAvi~eS(on>>0*aGRQW(_rB=fOI_?$6+vWss7#wX2hjWA_A92b6+sAsPTIsD=DOFowrD@?j(Ch0N(fZV0C*yibigv-_j zHt4V}dt>zajbF2JH1_s3G=(aO@8f3Yq#|*LBrPyMy4%TtKeaqv@9d=d{CQHm!XwyQ z+ZK$K8{BQ>Oelt?$CfV7B|bPCeljFdEpbc3XHcXxMp_s|T@{5Izt z^?cWjb?;j9hYN>c=AHfS=XpN0Egb4^Z{EHq-BoEGe_CkL(ODHb$(L7wUCGhzPqBC*lxv5NZn zBCm%dg^F^RB!51ATTn%w=)+_>tbEk;fe&t+yE!x;t2FW=4x^-vXCYxV>a@zl{HG)w z8y%8Qm5fw>{``r1o)j6xa{hpoU?rLE%9}p%r^YoN~?3(qW>>*pU~C6t8-Pft&`H}pYgKkuKK7up}{K_rXb;Rccfxln|%8jjL&P~J9(Y;>i0 zhB}sFS()==!$7o@75yaqS&Du4fGEQuoFDV8=$E8o|fm;>U^D>1PGcoD{Vtkya%JuQMs_sy*%VC~}QHV~e|$H_9^t5K@5T zDQEKGYYiFhXN76^gxInh6_e0KxET~*eDcq3Z*WQ(VnMaTt}?sIGr15x4rnzEH65zltd_(*t$MNk^qr&ogo+&ciay@mcu0y;L0o&W=_WHi{yz%usvFZS{(Y~ssm}0aj#Q*7O2mYQ>NMCW9wD-hfbKitfKy1e(CD0t}D{frQ24pX! z*C{SwBj_Zf^p;jU(O1*KhQ+PBlcb#GGjxlzXh9S)U!a6{BA7K_60*8m(S$a}L1b~~ z+buN1f(kl5<4Xos8nC^h>vB54!4@W)l9Z(krNI)@W4&H4fru9Uz6>%DP3v?^y8^ks zPYKSr17xhpY_uVWtF5g21f{-3-!vXNu^Z?vc#ri3oo$Wrrq;RC7L?Pyd*+K?t^3bz zozY$MF{}_BkAbeG>#;slihDdYksv{Sx0Ww1y>Ab5r-=PzQvGO_0^@d(lXrY1rOVNP zNaq?ue2Qk}z<{0ogYyPp|8uRBtRK&|BMb_HQxwk+u+F}FZJD*G4{d&AR3?Oe&nZ8D zP@4f$@@c--lCk%jZl9K9+HT&K`yVHl`o#!LXt|Lzy6_57$4Sj-xpgF%>VMoT4yqJh z^YU(zx^<)BCP1%V4_0~NOge5Ll?S((g5I-sG;P-O(8Q_UYm)%i zZsAgA;X#=5n`pHQi(VLZ*ax)V*D8}%>|GbcXFSh(JYSRe@|yr*xXC1LyOim8At?h< zPgKD9@tFGK6)DV@HC!&5Y6ePKy)>mQLuKJQJ6)K?8}WMTr#STMKg>p5-EOThCrnoJ zXIk!dRz@CpARb#$&tads25<}llMPnljI=KpthV~v+uz08EFiEw=$tX|o~~q_c(jm- zNB7FP_3=wcC$c*!Z9Md@?g_8Px>-bt;)zmzijRI`k%$(<Z5-bxVd1M$=&>ge)~p7&|X>DqXCQ;T{1cCMwl)Q-#`vB`?ZY%=B&5%s$`$_sTgU ze(=>GF%c)w9C)IPPuw+kD8vqOa*)-)sG%?L=d%sjU}m;&_QsYuqM$`b9;Hs;yWlyk z4tH!^M4?Kv9WY_?8IQpgzW4X&EB7&c$ zy!Z{{BU)>U013(4lYrXIRr{JAiGmQh>MjvWF?ZSvwcgK#*d^UkJC})BTQ2>3Fm7|ZrK}Zn_jqYN z_K12$!g6N)ClcLdnC(c8sa5Nw$=v$oZ^}Or0HoqZs3ssTEF?tzmWnFEDdbOJCCIP31hhNwSymX%%Tm`VuP_$ zg9C&uJR?&iQO#!@bmTA2FAw`LP3UELS%OE>*gaZ^_?$TC3kOwv|2sz~ zK0^hsruTVsKaQCi$}&`HmJcCU`1AH71$0qw zMksb}$yg4iXf^xD;?Ei2~4Z8EssYOs)PgZ!z{sk zp_h`LjMDN?cm;xsZH%6&-jDH2M=? zdFh7OsnT!`fZnzX?Df0E+%`r#z)K|-%x|&WPUvt&_9kZy`2S>PjiEO!tmDZ}T!F#R zGycwZYE~C;SWZ_2;|bpl61)d-K9Wh@t~r^F5f@|&yOVS1$5=}(Y|jz@Sh?2~@$%ml za)Wc}-{66z;6lTJ@r!Z!q8{v-MwEWp8=xVi3w|MLbpKImD!|y^)8)KP-?(T0zMc$2 zJa-DlruiIMNy`}c3E|Fwe=cZurv;E8XpEK2#E=Ku9}#@{CKUNUm`?ow={qVRI!V&} z=H}+ej!yh1KkHY_IG%hyYFCeXd8;cMpM25W+ex}qB0)Ao zjSPw!o=>6`Bab)I6P^cMlS*mUq}t~QiRs4i=TE*TP>bGre&bl1A9j5w*N(5^LH>dG zzcCeH31PT$Rpc82nd&td4bHqUh&D}TDoZ?9v;ILhmE>`(#kp}#0W|zU@KA$SwaTXC z`^e}US(G2V#6do|PM)!Di7giZpvJ)d)i71PrYceVl8t^Hz6K5=UTQ_Y5cp>FxJ0T8Kl)p317mbGaDaS>uiPZEonF`hqtW9<4s!D3 z#-qE|oc|lPGE9gR^29kQx_L39Zs_&d+acoo?L~n~Aey7|6;wIL8u%{^`WBCf2zaG} z*kO|;wA-=6DJc}Pf`V>QxCUp(t@sCbLQ(HTx>o^Aw60GsqoEtNjYY;J=zkXIC;&lotec&X|JkVj*|lAxpS{}^+McP|wKy@c zw(-P!GR)GfJrWOOBD~RYnpNw|=rGBp=-~@P`)rOw``=f~bqOG_xO`Yjl>iRM zHy;i?^sLXLzY;Lsz-7NKgMeh>EP8zXTwanKW+k7;jm%6`%G_j62y;kYnzprEi;(H~ zI(pP=t4;e)@dBku>V7=6SDV%Q_q5_as0NIR#zS8$a>RxoMBU~`T%>#8oG?f?n@>fR z$wyk4DeMOC>^ryFoA4V(8ul$!$>thCJ+U$9tvDB5pY0$p$cjcv$ipI~SsIdyF#2c0( z*Wb;|t6bo3&w~!a%*U*&dP~?H^LG2Lph7p+lNzZLnBlB1=U(%5=pvr)ARAvX=|&i> zntU4hU&rcjT6(UL%a;DWrNIQANVla3YjT1-+%aic2P2icO%`{LF4C>6H}O;xP;?pkF4>arJqG- zCCi3ZkadeZhiUrPI3o^eimQkvpJs^JW@;dIjj)~mc2sbvNK_V=+DduS)Wh7Qga zmU9WULxWO9trd%**U_G$>&KAeCDnp7oRgflliv$k*q56~Cn|(0koNKsSLBVd&5^$FO8d`HX$>BAzPPnw1dH~ZscbV~jpTawNGB8hWYaOLV z?>M2%KfrZ0&9*iKu+cGY=hDb~XEGdTEsNtzAzvTpToj*3!kgR>sb$uIllH%;+iwWVk-{(+A#mc zxQQxczB*|msk!Z#0vCCjMzhH0{W+rS%Kpr)M>i5NbBWr|77{lyF(EB<@v&CboM#q5 zzxO=&6FoKk6LDJxde~rjm&{b})^M>b9rJEv)ZTbD5NTdsLxl<%gHLxa;ZmAUd+=uY zTpT+c$FA5*wVN=)&R~w^54~=eh@1k zPEY!T_X&l**wOOj-mtdiWGu2Qw#(eUznTeb%~UX9Y;Vs*rQcPif(`J~Rth!iR* zvAW}K<(Vc&3|oXb0wTKmJ-_C#3%Vve2$g8b@5k=lSRvRKigCE|qu^JmlC0IqA5pNut^Wc^$SvP`jLIEu$155NMBwHJD=oNfd_xb+*+KV z?<<8?oOh9_*E1sPy1tyGA<586*hJ`j2qn)HRL>ehd_v(NsNuJT&JRQ_S*0^%T;x2& zJM(Q>zMF@)Sia&P6Ng}5uG>ebo~tbk#&tOfUwPHnC2c)4shWtE#YgQWLyZ??1dHD2 zO&*k5JCt!s^N$)l1A6DVcV;D9wVb1ZeMs_m`cGxssXUFQF&2fX&hA5jSgSf`%$iBT zQ)-$a$TJI4Y8(~caGmV)-H7iN;K$>>o46?E>nqjjgYZR*e|)()EfYT!V_nudSnR&W z;K(rfy6Rc=%iS>K(7A-7IjGE(A7Mv4#gK;|B&c$`xGPpDRS1W!HW&_p84#`RFie$X z7r$Doh+K7V zz@XFl4qO%AT7HtHb8N})8vnSDntwQwGvLqn!hgq&ER6vJP3!v`?d$1a%g052g}3vq z22GGApabO4V>{yVc~^bHT}J!5d39OS4!Jc?Fx?v9`xO0TmkeNh%wk_G5h=f`40ASu zYujg7!cfNaq=~p#O*%3tJFwDQbVdjd8oo6dVr0wVzMVONIot25BV49opJsNR6>QYZ z2cQ>@@|W`|IoH0u$jc>fD(F>YRx|nXI;{b6F*6>!=3+l<=77}7<~)9M%3&K@F|6=h zONA*7&&8e;a_BJtRDcRYf%mTFUoa;B|2j#}!z3E6#=wciU1hT2xI3T#vRZuYgC z`-bTsY~b%gDR4!p(YP3IhT#`+-HX0LF6mfL=Jhw(yiZ7MzVZ4EIR?bw;M)d_+8CLr z65}GbRO+*F5-k4Gp7Lw~C1px%T|!Yqb796p-;W>MZ;Bra)M06_V=gE0XzjL5g4d;3 zb~|TP8<4YjWsTwLjts^;l+P!INzz<(9Y<~IY=Y%eu260pQI)c4$3Q--Zyg;3oNgXt zt}%6v!99N`b4gJk1L=o>M#;y!7*#V2bhv)`6Gpy4EJYL9gx}GulIEm`$ZjKnw5zW& z=MG$n+8QJtNmBo5%24k-72z0u)$xin3HAPF&?5QktxZqw5e(nof8p=xRB-qcHaaae z_wNSc??}FP>3|Q;k&W=<{-0*-7Dxy@_q#9N8}lMn|&`LMfA{zUVE z=0qTl{9XEqPk;v;g!#+>KYP0Ezz?B@u{PoNc?@A2Ksf@Nw(KimHyZCRbUZPc0|cQ_ zxwMg_e;>@o?}moM1xk*|d`)-L-C5tf-5eiFLTTd%#605_E>{ka8EG6iDPR0~yR+uM zgZhn>W+;4oXQpb(qzcA1GiEkp-bSYPX@pXJ7$A1FI z+QJ3mo)8iTwG9IbUHoQpP>W0Rz;0VG3+*F}WYQLH1fJW+=0LJl+!*T4y<0sb8T6GG zaXwb30;X-Tr!O?VEFE+)+V(H)hoTVM)sr)J+{IJT_!}fRflWnJYBabtGpJVHp&zr8 zoC5JJPfI|~jZQRr^bIB5mS8m~YG<5#@EpYdfS&ILCn#V4;kO-p1X(#Il!UxUu$eRv zgYMnu@>dzKj6WfqcLcLNHT#!= z(;M{T3*3BWtuG7XlBCPy%+M&AG^%Qr|wQ))HnP1)2OHd5E? zuFq+sVx6p+zds~ez?Qx;le@GPvQ6*V3lwulG?Z#~$m~mnOlUoV>{gKLo~H2O*hx;< z86Lb&!1N9Yph~Ie$wQcH4<0Q#4(f#lie0=k)Y-h9po(wqvTG=1<5YeKU*7$>gE&Bh z*i0SPB@lbV4{O}m1zF+;tVWu$( zIJ4DM`{*;N^r0ibZnyQjrQg@80i&xY*iLiv8)l!xMFNxZhO2Jo zz9#}-q~f?(uXD;~pGUsX6r6=#A3}g$dgu|L!z0u_e4x;0(C@Zii(4z-%B`|^dwI4C zlE5-5EZ3e{Zw}M&Qc1JGsVT!urYR=FG~ z0-jQ|Upico4=8@E9r%Dg1zv{0@2=*J^e%M+X@H{i`4Q)EMTtSArG#Y=Z!@243?73^ z3yuQE*9T7*$>0-Mwap{=5D0{)3>&&x=i@?6F@T9V2YjHh0cZ8#E=ZbtvBIzA-#Yhy z!}-Gh=6qF~23NWw906iw#!vCx?l=&_&xg5Gf2r=Rz>$1S>$#2@*Eah@2pzqg80ffm z!vfpmY+rMWr1MD<)Y!;-j`Q_{(*nbAMeNP~A zKY5QXo!xZA;PWwN#^`+0Q};|+KGo4t-MX;L=sA?CM8>5m{$aK@UnK{hvqCN67@J@B zgkZG6vV~VQd6a%q{d@|+7I9N3*gHj@{_fH+DBcni|o)g_zDB$@Rt zyFNHDp%s?0mGElRZe`jE_QOCk7H2GO^{=+UE3Cwe#r*1f<@^+oGu2*GsgtCRVx9BR#g!u4(8X`M^rMNR5uzfe`j6~)GpTAyJPMd>%v%T6BkWrH|1#E9;VD(yL~h76*}NBjVs$Dn&6u|a^?-{F3r zTUi&QJd-O^KBE+{?UGQpU1oZXox929aHjWiER8Lw^xh@X{-qnK4`Rkb`GD3hPx?m} z<#&9$P#T<@@k-&uv+0-WI8zWrEEMEtifXW|m8i5_#R&{y-Qf*q3l1v^^^ox4d13vf z*~F)7<-JE><--p`gvTi*QhW~KYYoF*$qWAHR2R1fFlaOUL*C-OZ|^ELbZil=z&RT!81hnIu(~naNnLs&R3U=^$-h^&|Jgr~4vL^F78Nu8{peZ9Yn-Zv1P?2F$k>ZG@|{LYwd}i{9IYD^80i$UPr)7y@juYz z{|z#{lS59bTgaT8l*#p~h}*OeWwmxtlmk&AYxE2ZxCzd1rGoQ%;gisGp3>Gv5_>6c zh~ln(-3LfBmJ)l{kK|CCuSfBE zl8b0S9(fRod(onN(%nOsou&%*?_1f^2tob4p4|C4KY215^kuOZVduI2w9&K9)C~)nsWTvpoeq>hPu zDKqDGXcKTAbX~8Bml>3B)6jcHxoi?TIp{zTt{ z8r>dliYffkKxY0ICD7@Lu~O@ZyL}vazwb6)yECe1fH~u#rugLhy&V6X+H17T3s|P&l^|_JxK%VfIP2 zQ>@7d^pPKMWI{YX7M<6rLtI~&7xT)#Y^KS!C>FbZp@f8!^tzE16TQ_0i2m4pcz07H z)S`u43eTs5;p(bXgZVNDGGi(g&TSI`?niGH-bIiOgg@>uG%eu8rSJC*0?N3E@Ni(4 zeQaD27G&S4-{;M5th`bMWN}4%r7xl_qmj30R_TV$4(m&}mPC{zxdg}f0!y#Ok{|@B zKt+rT^Yl|C30=THR)0xqSa6$LQ-gsu`}E~Z`$;pGB)jA~j%62fjdrKEw~vm)YOPzn zLLa@H3q{RIeO?9mvjoV+PNnjDC$+jrtG1vC^0{h~a_7;}u#H;t2&pa#?C2Motzl>f zPF172XSGmmxnP-Vg+4}F2}5kd4aY5mcvAyM`Uh3z^~&(Bwyh`P**Ej0F7&qt65Q$y zXE90mBwNYF#GW_&vj%pPtJPEa3&kgHxa%)ZcsDouKww8w}{ zO_P2Dp!io0nhAcGjbmtXmxdW+I zmscb7H}ZZnybs^mEb{im3H=|Y>zB>uXID$yf7~*+9^bl&xrh9+ivPU<{r`x$<LB z78bnNnYFD@*il`%vfe_TG4>`i*s`NtDyR~=xCb+4>iuizt2=>HRbkhOVvZ4ipT0vS z?2>J5ilBwHaJzeQ!*K@}`CnE+*tc=jlxb? zQ5GVz^qZ)@5m>*tvsp}8DpJI31h@ts>TtmT^MBa}mgOw=*J1q82Ej-CD$r+`(NAii zjn~68V^TiOpZ2B-xFJ(fzQtxMO{sGh=XENF2xk5Qdo4?GDH*9m?c~7DslLXru{5tm z0^OjO$0id~flD_|OU^2}-T5v1l4H*QhOL7Q8%)x(ISx}MF!QX703p-oc_a_-Cc>Ia zpJtYse|>JzJxI0zE$_W5+=v+T`ot5PARC)ygnYS7DgB1mX`pF7g{w8(1H0<`d>wN(pNb*m!e>@$U&SJ1<^e~rp7T$dsQ;)fT&l?j}51R57=^%CS2vV@FR1DD5jlm}-qk znIWNh)<#PI!-yDXzrn0@}*ek@J+A4#as!AGENhyFByB znS&?%lu;BRvovIESWjfIxoz_4evG$#-MQcCR^@m1l~BQt-1VK0qjCttE1xVw}$nB8A~Ngv|T;j!k#$G#SOGJH{^V81$j5TS;evw?PuEPv>Lt~r_sf+O~HNRo@%9tJ8!@I z`}jeM6+vdxtVaHwnBZ9P*&QP{+J*xC!5=)lXOAI#1$MKTkde8QYiAr$G|}Ftu;jYPk*EnD9iH+X(t*>%*sOJ>p%KHKnH|(SDefHU*^u@`{v%u^9p>zkieQ&^n`KV-E{>Wl%vV-6V~~XyqcLS%%2${g;QA4 z3Cb5nJe9ix@l?HzWLwM7hl~t4^oIDHW;!o7XUP|Bulo+S^5R%4kk9rR{TY>^Q|FDr zw}qcUOV5kW2T%gwYG<8cx|R{OCIQTFer<8Tbi8y4E}Qq84;Qn1*%|~X4lzeZP1<^q z`_zt%MsXNbWzHKiF+twf_(d<0(1jJ`+g?w}-113P&7AN>?>%YtJ*&~hW52CFm&Mrk zL`9`Zqe(lr7fwGD{P*Kw-+a7M6z>VYPh<0UQ|_s|YqzxGJS>Xn&1o`0S|`Xwc6WRz zrBZ6H)C3jgkNCMXGCIcAv6)&mt1w5ggVI|ezBc+x*F<;rTBk*N)O-4OhXubdoq)-mfbYv8BaOa84KXpwqZb-AaRAmTBP zG`-#A^R`VGb`{Zrz2*S=h#gaA!OsFwoBMlN<5OO9AlN^2R4dmw3ZY8ABc`rUnrprp zOYpjqA@VSg1!nl!r2w6;Xf8+HNLQzB?C5CODxz!QAVD_es(|>{JGzBd%MmEZzS?K4j!5x1Xl=f#!IWqZWz>7MoZ6X-26aT3j`rT$5*s@U z+_iOj@A5hRFg(OWid(myrenlJPzvTW8713YunI=zIhKmPNg|VeESMTUjO!p zX#i|Wz0UYs94bB)Ayb1NUNuR*7o2DldjPf-K42W<_>6GwgLGyKq)Mzw#1ylGK=S+Wlg@T7wCGa0PEe(krf75bDcu5LnjD5@hWcVEO`x`{KUZ5Q*} zd09-AyQpOx3h!gQuGo&`YonmAbFsgcse-ILh4<%couW2Tjmytq2k!a@Grw#=#PQdH z^OCxF{(N(9Uf0to)7~}qiijx1z2~c01i@ct*RZP=8$UwQ z+w!O9%g5$#u!W;{ z68IfzEp6ySj@y6s2NGBLM~U9XlrQ9|er*|G@9^eD@*N*nzuo(*blv=VVi@>!WiRGmvb!gTl0`62fB*=82Oyf6 zFmqzHys-kH`=Zj*(c!q6s=k&OR>9>})?zKC4hB=j36@t{TW-MLw+&b;w-e8;0f_!JX_2+}v z7rW|DHr+7_s^128^ABI{(fa~b)+Z3_p0f@9Z;l}=k1OHEl(DlKW15S#U<4!Q255A# zVO|Z})h-m_xB`4tgagl$;4K_4kRq}}W*w#%p7I;f9Ky_ZwPSuvsPqC)naFxn{OUpZ<5+a)j3Ol9OA8@EDk;XjUj^$ksGDZM zm&;{4Wz23XB^4;n7pIpR+!h=E+SUh>mCFflvY^%MSz;Xkd67b= zUR$jJU>{LnA^!ZGhnO*v$G#9T04xfxc|rE&XE<VCK-U0Bt}5rN<1u^SnO8u!^>}y5RM*%jI0i_au;Uv;{`{@ExvL%9(T7+&mjF>Y zCOit-x&~g%Wi8?{70Up`WHJI+>W1iPXEqMk`udd1%`{!|)M}y^#FQuwMIhkrGCc=& z?ij{~1Ab5X@A>MQwHK!|wgoD9`1k}dfioovWPv=Ug>?zZjwceAcHI@6a_rX?`6iR< zm2#b#o3v|j(Vo`|mn)cO?MtUd+x8W~{vBNZ_HJ0xcP@X>#XozPbTIFZsRwwLs=6EO zF1{DK+#cL=V*so^fukpbBrx8gW0fe8o`oaNL-UlxkkkcNsmZ=^<8oS*F06;xJElGY|ZZ6mal z7zF18$UI-{vjqz+9q3IR?ZM@rYaJXMeCETeNI7CpN(>kuvQ{6RYrQIg4FIJxeF9*3 zL2g0{XjvP*2rb?QqrOznIP=jrYMgE!A=@7if%G(^Yl55x?Wl5;6udejR1LeaN4-zEb$=VEe@)D0iVbAz`yLyrGP@iuGFu)Fy{9Aov^&Ip7o~Ie zY~9b-aP~C+hp9>UMb2D8n6liip~L)P9xd(GW^@{{rGDjU_ea4CNP?46fvkMxMG(qv z!X!6s6Ju=;Q{?Zh@fny-;J}HR(ZFQB_=eF*YvJT`9qK`$ERj)RA^x7`W|9~2Cbmq) zemi;4(dCvpqLT|`#QT!+>B^0M^zk_LjKo&&yMJT}%-dl;9CU9gvb#qT0K=`ek3{bX z@aY`$XA+UOm}1B*#c&{USq~@g-UmC^JMN)pjGj0hy|>W7lkNFDiYl1Dcq`jxoXr6L z%IM{rW^SSWDxnW}>}+gYH`7dRm5fRE`iqp@t<>ue^srPa#F}E~|CZWZ2@Nlt0!6tYbXvYV`q?x*_B&oY;WnMmKM~2Rmds99SQNiv+uR=^*xYkOW7pY=vHJiQ)?~@zvM^>>qyXBQzd}v_3ISh`H zOivb*WB!YW*(K9G7mWu5Y;>IcnC_+V{J9Xf?8*zMwTk^pn3{b7I_gw9(dk4zjdorC5tlpSd%dudJ+8tgH}j zK`gTq8>EM4pD@}j2$3iy72)0O=|WeP1JtCbT+;o03vg_QLm<~?#vA*I^jGp2hAo(* zk5o^!!g!*k+H!9n90VPsI)H!z&?PO655H77b<_@{Ko_7DLTc6VRN|JoPzL_J^uO4_hEtT}w_~&Pa^P3zT%@ zX0Vnx@}!(KMsA|hy+^q6KEQ6hgbSVfP`yWGd3XW)8pFTp{^iON6wxM?X=qP)DdNf| z+0L2eJQ`znrpa=2);UCt$M(%=l;g4FPrMkX0K*tW8mX~uhlH(l$OUu%IvSaa%q%l+ zm|=zMtpVY`o92ERG^0aIwe(osZ=$cVdG_jW;~Yft+X9LBU2xKuK`o7cag_HrEBpPQ zF;0Q3uZ!GgBH3|L-q?>Q!Woq+L2?WUc3h2*dBBV$l%NpMB^ z$BD(&`a5y=KTlS0SL9UBH48H@D)3=tjVgVJZ%8p*-3Sg$mFX5UE zKWr1Dvx%#(p-_h6w0Eg?6yhi_<(5_Ydc@Sd{5G;kvF(AR{<)-tl_BS+ar8O7ZAG-O zs`YR!u>I+*Y1#4sV@>T!#CPAXguA6=^0j*_*ZZ3Vo>_SnEc0Fu&zJQm6E7n~Bk2^ACXOe|HK*kL_|dq#gNEjs%SK2{0OXE(O^y5iT_O=Co|D4TK+haeJ%qf68F|<{48r zO(3<+NPDp-eBBy*Md7xL{=TO7+I|8JlB-5=+=k_5CCU8vTq%G@N`lTiv*6&>w6w42 zIMIchDxbX@5xE;F&}C%pXVw0Ao5@Y{C!wN7W1aS?tvu%PNZ?;K%)*mAiG3_VR*A2> zmCGh3@GlgC-f5w$3N}yn`Y8Qpv_c~74-=x3fA#c#r?6bqcg?LMD~me+oudT4kcFQh z{h4;Z2~1-rdIwaAx1#;qZvWkMziU1q{*CS23~JoSs%p*GXYI7rB0DY~h%RAsTTej= zj*%s6!oiFA=A{$D)d|ilg^0Rv(s%jZzh_t!a;&jN6y%*CuORe_itAI-$JJE3))wzS zRp)}5JYEgqSh_y4F3YBM+MaHE3E^B*kIG8VVep_=be{b4wi9Wwy$!J)mv=;-U7uy} zr+=*^xk@{sjb_=J^nGWoC5PK_>D~jIS=k*ujvh5!`ceg_nOq5?F{gqHE zF11@;o7T`9Ve{v@y+E_FZy2Ihk6-s)NHtZ@rO%-`Oqdq;Q_F0y*Q3z2Iy0Qa$)oD? z`SoEEt--{wmqOX`N$=3cb}enS^3jZsJia|)$Btf~tL^ovO>cyPbFkmi;A=#GdwcI}z--h_&XTNkXpT+exYE@sc9 zSM*By=*>&$u&E@6>7G4}q4+49Q_;?p4Win>aJ8ZG4;Grwi+Ue{lC8AW;3NtTQ;5@|g# zJwNl4tpfGGTWbft;AV0-AE&|PxBZ_MJ2B)x`+kiG0O!Tp{a=Ll!t3?*{LEpXix3=r z|2N2s2(D84)Nb;c$Jqo{w7*^};uz1d>ysUVV684MF3mPrt`F|WunqE_JLB)mtFsx^ z=}NG-G7(@Jpy=ZqgviuG724B0Sz0>lSf^P?!A8rt^2!O8=CBzp-gmPXQI*arhU0$NlZ- z5lVh`wo`mUTDDyM$QmmXA{%spIWwHUrVY&&3j@0FubIy)B#81#YfBBrrd4N-YtNsh zd;DLJ+v1th!^x^CwH?lgo{lIs+mC133D4fW*?Qt6i8EDAKHGg)NbPiaGVnp;gY|U+t(KDKm#`Yub^vR;fmv$C7I5wMz z*r_QV30l8S?i&~%9;e{Gdn&gLYcdrV7Z)>R8Y}Ha}q_ zI0Y^+x(tpfRf!p_@%*yb=>)s#VFB^N3GMh$jr0l96so0?lC@sC4p&V)Zp;%8o*5KA zheR>8Q?V9|yBX`><>dZfFj$FRvsvfPnT?-?hK+Nx2xZF6JX+N??%KJ1(X*fSy~*fGbiA^0DwtvUytLJhpFu0PKCGlwv%o|YqF47tD%x%4#` zGj)SC^&X8Zzv_oT1o^zt{e7le)z!tv{G`kiwHrRb4&c!mKYHf~ zEtnw_Y5(G^aPbQ*&CA)lsQha5MDq_`s;Z4{Y;^qPH(+|zbpI!D9ytI^LH@d=ACBTh zKM^PNLh;Wf+vd0}DvT2&>lc~JuU`DfagTD2-OWzPwf>9jhmG;ua3)12IUoBFc4 zG9iRWT?@*zC=812{lSNroG;M-R4NiFG!2|k*Iy;$Zvb=A_m+^6iYkLt_BPSHb#-qlu@K$vfACTg*K+cHN*gLvA?N9G^I2enOuJqR;)g@| z*gjm@(Gl?2nJof*0k$!a?B&=K&H4~zP|ev)P>pUKbHRZOu-V`L!5RST=JIWfyZTOA z$-CZJ@&PdPI}qDWlAOqTZF^vUHVP#&t4I2IGX}oAwyCIHSZ%WScmMFFbS+o&;RSu` zW5$}J!EXr*mD`0~)l_l7$VNwsLcsm~48<@D?#EC`y%NAa+dc!tsx!K}x&gp>8gzX8 zl72VCuGRnPMwWcebEowrua}7ZAgB(5a%nbJX&`erRh!y_*dP@d~f3p&Cb91rXr5m6caJxs&?{7jU&E7!1G+p2vePRRcmb--k1*tGxgkvlIZ>v5FE0;Yq~vOd!f_*87vKIY5BZdym&mAoU3^xQ@CtOm4~_ocffc0gi5(sRb(5YT)I~^5hnzzK&Ga)J)p? znI7K>!dMdSn|;~cbvfbQx`%3eeUprZao%Q)0LY#NQ;=b9MJp6GfQWb8*$5BYIXXLB zTccMge^IB9r`BVZN(XS!pc}R96$ljViAYQ^`O5j@TSUYfA4qAlxZd;Pe-ikVIW1;- z>YDFG?X-B*qSTP2ie6<>FG$wf8VT$JdiqN+73=PljH%H8n9dw&(_7j!-bt%}&TBeP z6hMQo_&WO$0DFo~gFXEPJ%6H_$J32-{;_&V@`2cCuR#J;(dpy_q%n349e_MMTquZ7 zJzh*#3XYB4t_JJ&<+5iwu9kCpoQ;J~{gJ?)Gk_7Sf$aTwb#=A!&7F~U{>@qNPKq8O zTY*sj32+3k*$REx^!w{{{wtbeKoxXu%+(=UH#a|fox14}T6QyuDyaOQ_P+a_>OcJ7 zCY4C`9z|x>u{pLf%O*Q}C!0{=*qIs04B6uxdzMkQaO{jw;SfUh_j!5`-rw)_`2)V! z_34LxIG5}7dcN-Gy6?yRxF5Hh!aJDs9B93of!@Q*0DpW+1Ma|d);+T%?QbF8^KHT5 zlmIwRM`681tLD8n_MGf&cp5)2=5m?g@kb^F=8yi_D{MKHm)uG9B0IoR6C~w*F$;+N zR*Up6c`S-MUt>o*)wX}rf1z1aG3Us8IawM7ABjgR1u(CxF#3l$$b#0>f$OfvR;TI* z*)Q3oC8*`|lG+%4gL(?GjPYZZTQdid^C~y8Up<~M5A&h-S&F+?GJ)>OoBH_b8d|;f z5Y&<{JpD+vWf(Z3CY2 zv*X+R21zsS(eFEWx0mUA;*UfOObUw+x4Ib|mfn^N*6&eycz8rVXjOd5UccNL&04SY zAR;1S6^OG^%O@7ldyL+vLJN((JH}8ZHknLHN|HJV)@44{T0T`Zs&zKbIA$yq`1bF0 z_CyhEQwvkD%Bg8d+0=i%XCr@F?pe28m9TrQvZTaNDt+&3>f_TX7x9xU=7e=5<4W8g1R<sIStwZipQ@$sqmi0&+XZ-^W7>v*{-Vfm2alYNs=&BMkgK5iVCH($rIKdv#x&DaEoN8&|Yp`mzT1W|Y}lXdc-mMwO}Q$CG{ zl@~73XM?1yHV~C&^ogp_V(>(E(7TdGOjq5~NU-2RoM%m=~rP=up zNHno9BN^XY3wX;@qa_KuR^fFliI)qqc*k*9HD0)krP{nnW!|8~t%`rh&AFDeJuyoy zK^yps&7z+rr(PGgL{u^F8}A0=GKbkPeQ`bWamiaGNF&U!xR(e5UF+->7i2=xKt7UC zA5Ni{DqlZG4S>#oo}x03faOy}2S<6z*OzuOya=5@Fq*K{$KDW{_!;hj8XG3owa_TdF=Tq{^r%yNc+8Dv5z)Z zR-zsVB8&Db|Dc=HA`{0?h?wnZ^>N3VV7JslqdU3Z-!AqRU5wGB>K`B=j;&g)zps1N zv^f4FDZqc{6y)smPL_ECZ(r_aNWfNs%|e+z?+6dlodn?@u20vN)9@C4;_$o7xLOp{ zki8PSU4v5}_9$)!m6#OJs;m&`+v1ulL(f?V6Pi~d|NOu?mGK!u)p8~Q{Q6K!YlL0= zE}YU5=<9Inb|C2f2}`~^;?%?zt!7n+{sn-3_!Ay9AG2(FgSPgD$1JgY+N$%NSwLh9 z$q{xHAfWsPSNT|rAF5SNE$dY-TD-iK9kRMwcpztM`KEm(tf~fYi&TBC!dx!*cUg++}{aJn_EM&+8!(6cxf~(9U;PX04#O* zaf#FRCn;jQ^RkIIiL&nZbp@H7ZCSmfrpgRLCfGgVOKfkvbCgV??k2tppnkMmp?hqm zwH%U$V}Nk)$^G$UU5t_UOg~4~o0?`)dCT*P&+}iqOS`5^!h2N{m=_$!=DKTt|%sn=3>(%wX zbQ$u{&+VJC?b<=4M&UJHbMvG+jZ7)$t$nr5%YppDXB<{_2bNL<6Vm%&C-ilmj5}UB z)0@HaXBMPc#y5P{6qUrqOKknI{%v?&O~<>wQW@RJH73JOHc>K-t4m+{-e0@zGt60d z`GsgzowIfXyJrs(p00S}Cw06}Gudr<9e+g|P@7xx6eJlw@$D;kmD@mCTl=Hs=|i8R z1`^H;W-gVE!Kx6;0)U;;4od8(zI80OY9=5p(Lj9YuFlG8yJ>NorX|6mNZ?3-O2e;t8B4Dsr^b*fo3J{6Q34CDLzaD^ua%>@c*${7TVj^#r6 z9QUv}E&lLZzP=?{5(RD#hDs*!Zf&#eGosMmzB)h~v46TkYmwA-`mQQ|wQJQT>lOU{ zR(F$I%un-9q{ZHjZSTPcI{C6pfl-Q&Apf{=m2K};Qh;}Dv(I`0V!84?2j}#q#cI@k zZ;ehn5srGQT+Z)7>P7d~eE~vlawhl6M#MbceHP^+64WO>uQvVlrdZW_K>ywE2ISRvw z8KM6L`y7~qV!0_XI`4A_2Qv8B*+;@vOmVv+BZ`*{8O+kFz!1DB!j&Lq= z>WcJ~)I`jA^g5M}er^qJ$7*~g&EV7R*Vlh-t#LbCUJnT2tR3I%J9s*BL?(nc$0o8q zTD(@AUbI&9+*y#e23z;sF2O{M#I>B2bZt2*o|EL5ml=~hl44fzA|`lz+<)f%9eOdw zT?&-)nl)-3vV1xCIxYI~Yu&FQ>E9=T2=2vZ!lU|4I#HIB>AQ1FfP-crwQAx$ zk9&H0zo4kB=13jVqn9~X z$!Msh(|;S70FX`~exOQ=Kf~1I#LC26G23BOEB9XLnS=M%bnln4-MaKyy=tv0WBgxY zj9Z^}GW!xI1bmQ7Rcd7E{s(rrNTIca*07`5OPed?c@%YJPnV1MZ}V>IP4F^Fa}RQ~ zZk`-*YJ3J{nSS_fEh;*9ZrD8l}#BA?@}qxFT}%pp6QjJfPJr6;a)W=r&GoaTyFCT|ooWl7O$A za<+4P=wPE(2A%y64_EqVtdDvk=W65f#wvZlknLtt`9lMU*N-)i?>6g!UCHDcyy~e> z*7HX1R+k~Vu8f_jv8k)b9l(^79B&ujuGJNzC^^V!cl_#E59-G^*QNG?Eh7WeqGQ%# zTct|viUZe1C?qlv-Y1KP)tMp%+S8+uQL)j0dBn}?QXjx0wr|rJRT>NstcEwh-9V|M zi``>Ez1yX?lQxWWLB{MwNlbgn`6d#>4z44w6z*?+_YjxMEP}w{SDmD~#45voAYWW# zBhzVkF@a{k5)DJe2<9dAOYVT!J0``kRz$m_H&{*sAIXAws){&{e~@4(JIn$e>Yinn zW}=PsQ_o8{T<^{I>1yh;-?hiBZix}i9JF=ZuFg+P-DOb|r&I6#!+>2HQR>iOgiDd> zJ?knuEE-B;rc2rVcV3jUG6*^lFk{o27K2%*kOhZd;S%m*@uUfKX!5v5;30ftgh6_D zGgfS^(Eu@5dQ{eFZzD*nC2>2s7kXFc?qxSN&U7_{+Xf`{q^xzNJS${O; zH+X8oiFks7)-`zi>pk{T2gi)E&^m>eI?FFMk-RnhRdY_hzK2??0;a%lrW6`AQiZB0sBkFF>LA}?G1D~a}l>3Ok{N=4XYT@`Z5pcVF{8 zRO%#&a8V<$ZGTY00Ear;et(?z=7r9$ooe(FMok(%%0 zF4UpYVolzfgEHZ*Uk)8)J~Z#nKJt1#^TAWRq;vd3A0&+@$?fcTF|#-32cTa)p7dQS zoQ>VS;%BSR=O2W9aI8)*CQA2hf1c`^byh5%TVoxluTa@XRl2<29}h5f-8;2m%ltV= z8sV^nTjrZNcl4gx`F$K|lUAtu-Cm9U%j`cr)T7QP&CKt*>(rd0Fn)KhiqTH6#l$+k zJRi}7kW-iUJ3^o6%2n6}1bY;dv*Lts?@9R#{PXx!_g>r;Lbq4xX={cpcJ&%wc(A+- z1N?wT`HvcO$xbTz?-d#hz8ToE7S|$e9uRu#kh^WrudMF1;_d!gnylPeHMz9;kypt3 z;WOcer4WU)-J>ass4tVvv!><76JnY8M~_nfrOHlh{7*o4JIQ^bt3x4DnIJ`S&IN|r zK=Io`?w{w8f6~XT#1TD#O`dht?|vaMc^t;4NpSRCOf%QJN=E+={a1L3Wao>v!6>Uz z`eAHM>|znOS|`yYQ*ja|gQ$qjnR|kj*E4$p{kr=zfrlqQdLi5nZM`nmUPwwEBX%=2 zcGZ8=#~rVsuP7?{*k&%VX)-sm|KeTGWM?o^PNKV1qO*r9&08pba+cAe;068uVq_)p z{G@5q2x3OYT6Et%HmoVzT4x))-A=VXFg3ZW@`E?JfdUmH7i@FypY#s#AOO(69;_lh z%;>#3zH)Zsg1-ji#A@}~?iz!OUd)mQ)1_i4tjGB8`fQy0UBm@Ai^z=m#YkTD15n1g z2KuLl>26+mnUL^R0*!M1N^1tJVFUixtEH$Xk-vWH(sxJet)Pm0aI5c3+-XYa)USOi5Gp229JiFR# z`@yr1(D)hDXtUgmxCIE*A3nb(Rc8w-hLMqB#0X#-_b$N2Hbj_zz-x)3yh4jYo4W#= zWP(Xyo#;sbofApLJS!IRzLu68Nh8awV5!J>%@@=5P+!ouVzsYIEgfR;ez!K3Anonn zYib>ao+KzQ65z;bztGfFbQcfYZ4p5o6b!9X=>y1_)qou|{@!P2WtoUtuy9shTx$4M z8G#*8?o4l* z`3qog&2H;U2Y`lKK8x-tu?;{gVtYSUOh3G|q-6aL3C;Rp$RcNKihxoSrMX)?*>0kq ziO)?McZHWp4Shg5Q{f4n>{jH9K=?jI8U6;vjzD0_5hgzE%b$S5y5!qzvPK%zzQOw& zwrDuHX)_}Y_{07k8yI_Qb3ia$x)v~f$6fcwLGzP0*iya$onFoJX%1y}TXO{g$IyL- zuJ<;7nwpFP{Sf5$99MVjOgk(1QSi`F2ad(Jfn1@8jL_z|xNc1D?Czhb`0BK&`m& zE7+Td@cJM5={?K%P;drI&VqJtF83+QaOe=%X;#rTk9xgbIN313q7!P4R$^(Pj zA%$v56q+S`a?wohM||%py!e^Cz5UqXt=2JyQ4<*tr}IFD=hP?eZwCLs%xO|BWNzs< zUE;@ki%j0dXc-x;c`<;jfpCeB+8YVcd5$7jL?2*6cL5CCGP34X)04R>U!}tiyvC=* z+1bB)cAY_^3LF9+l7w(H<#rY*Q6>CR6hvT zxw(ID3UJb$W+SPnsMHCzL88S^rS8aK3T|h<$@^6s`<9&Xnd{fDr$kqmK(RlvYSIaq5i{LC9I!vmDuP*WM@kB zD{~e;v1Rs+s<1PczXMIQPL=ZQU7WZ$bBQ$vYQOjv>rPwjs-C))C6HAC2m57`NNh<5 zvM6ZmX&+_8b>1wQHfCDC^~!Xn&p+#^#05U~=%yO93fZlHWQ<+r{D6o{nouN|bluIl zea-Xa{Z_zAs!fps{8sPR{SMG%?_gf~c5&q=X6rR3*AM+SA3SaUUE6))0S-Xj9>i`B zp?|ytQ(-e`z4V}iyHo7dh`KoUyV89<5xnfOK#|jhL*zDeTyMfigF`mD9JPG=IjQ)q zj}gw56_*+t%21Sl-NfsZIE#iIizF>Rss2)#*v0OjK7AsRc-%#p@!RikUx_TUVG4-I zydV>`&J6y%7;knW7nP(^O?v=(!N6uNfi8qxtxDC+lF>VSgCv}#1jOH&^Ilg`uTTt& zxcs8JOH6@PTXJ0gh-`9>9yOZOzAjfYZXZupLH@dbyC$#ST~68;e0HZvK1c;RVEOY{ zolP6MMHbcr#eord|C@@;7A(sYQPT3RMw`4_3wzJ-fLqux_iLPwp)?D6z$W{W^VKeEF$&Ppsrw;D_ukOR7KUOIwTrBlB6kx7@Qo zalm5l4>Wdc-u8*1d*S@ZLA~e45^{^YGej6G+Rvq1JxxSGUu>n=p28tNzQW z12+$z-F4=}P0`WauscM;EnjGcyRy54k6swP{B7$}SXgMgWjS2(;Vny%em~JrrRhz||6nUVAVH2l`FZM|xMjX>wg>X+Kk4aM&D{sKt@Zw-4UDW{Z z`+Z+@b@NMi638IM%AT@6KP4+jZ58b9{TS(vmK0fbtI^XP@NeiT2tem2z29+tzqJE0 z=YiD}T>56sS@}*=)L~yE$?PVNzp%N7omDR%9RVHl@t#OEdV(3(ueHghS*M2Xfw=b9 zra>liI%v#wt5m(aH(Y-=RC4AZcc8&z&Hr(K!q1P!Cbp{2{cs;jYm)Q4XgIZ{`Sg2* za_^{@>vAHIP>avmC;LVt6Lr;YQM}bK$e)-nm@d5y@~ohEzO4uem=DH07Q=^AvHm9o zKQ#iahgxo6V9@8>m6y>z)JiLRpZX236TGY=291RsX&y}p(G@<#F}q~K7>{b+?&Ph8 z*0gN*@L(IsGag8r7Nf8`iSJCrVMxJ$&p)eUenL7o@X%-NOKSs7A)Ox!mFwH zid}LO|2PU{!~!<$$8UP__F@B|C}X1+>R0jtSn)0M;q^xjWmrD-oCYCnNs+9HWr-MbEG0y8^oyxu?MD)iw%cv^*LX2-uUFjnYCbaF!s&DRFzz zQuDbSjcoF)K?u`HsoqOxoys+dpCQ&!-NWDIbcJZPyy=gIV(7$cmVk4$chr;P52nI1 zQlE&OXjmP`2h)TtzV=*HSgjV{6xB;#o5XPFuy%6O52L_x*I4(#Nuzwq&J~Z- zpZ!Vht_nw=6MRnk`TCy}ZuR>P=k;%4&jz|8+Al|WoAZvI735H*JD~#&GbJX*NU7Pa zGcDQ)FB-pS%W2t;igvo|VR*-9mS#>@2NcP!kl)T-Y+NA6tV) z=noM$d6uEqzoa1X&V(EYa`s5ATMk(8ZQl4;Z==~G_C8#*1i}RVf|y595l3w+%6h-r zu5aLN+e+>LeJySd9v&j!+_<9}oJZoNj~s<=I`gDkDM-x6zHlRRArrR}627l9cCF3I)q#qo5Y8-?U(Y@*d+GhLhdOpO`I8`GY-2m1F- z%3{(SBqf$VUj8Um8}5Bcb4KW%CoAUVdnk`H1@+fLe?`3w%$Q{zo}I;05$^FIB=v;HD@Hso_dUpG-J%}Xv-JekFfznSu#}k0@Efj;8A=ckTFVdT!a1h1i z-t6}L%k}*0e?Ar{35~!n+6!2jGNU2ZjmqJ8OYw8)hcP$>&0MDPCAv_M%1X=)FnQZg zm2?*%d1xP+34KKp|L+o{KZGh+GGJxFmoCEE%8b@vIF_Mru>Xx^0njh60>*9l*iq@9 z&=YMJ0WcgsxxwIbAOS>mH^I2MMQi>pO!@0ARA4wM+27hOe&8^ugpE$71*SV6WJeSj zPT!Eb*~JgEy`1bSTDfidbAzZ4gI0DD&DrSqY_ggSz8btOwH{fkea8RE~t2izE%cyaM9 zHE4VGX6F9Ko-)9mgtm^d7vEw8hEusbIQ$=bG6H+z3PPCvSn{vT0SrC86WiauU$p0a zVlZwj>h%Ax>Cn^bc;Noz;s>&Wb)bkDt@a;#qNlg!SXAud2i`z0%b>1X7vEBep5Fg8 zBglsRuNnVdRR6mg|2e_r|94aW&F%RA_iSX99}fM`(YP2CH2BSZzOb~^Lt9t3t38S( zlUc!WsYE~F{ET0Wfr5g^ug(K;swo>dahetvk~56K>Iy;3HCo0*>i?=*fD25;4CoqE zW6v=YW3;H@xtm(M6?d9GR&I;m+`@cJ;JTg{< zHeOc$ARs9wMT&e5&uy9PdJ_w0K>p|64{8H6>&+A)hva41EG*>DaD)S&pVTvwP8nqk`rDiw{J$#aV25d=a^rkJgg^16FI|Fq#2hc> z9?@TO8W;JTG_jYKx0mZyn4plMyc)9l-0I?O1;NV3DOn(;c}K3*oL}h#*R^3;WqUwE zWBbG%Lx8Ttxk9W0Ukq#aZ_oelwM#?5Wl+WXosbKMOZSlz(@XWs1#6DR@Q-Ou{ZAtA zE$};$RAwJS*dFEgLn`n&v>LmtY4ZPbW3yrei+OF#1o7Z-m@Pc05Go`e(MM6^SLf1N zQTM^8rf6$*J8G=2?=_?;Ip(`v&sW>AjuN~`s(>cqsAlSERhV!cy`S1K3aeNXN>S^# zPENOT549I|YX4mNZp{@Ugj>FuXcm=Y*O3-VfE2V?8VhambEuypDZa{^WJeFl8w;hZ zkzB6R`d94%?L7bm68#!SgM9!T)>P@Zd&C9j-bAPpWzt@KEJ)4gC^CvC^Ui0&weTt* z(Fl)0tJ+9m?vE9Dg6yd;%*Y#M9QI?@ga(b?A!cK8oh1?a2o}hZrnsY6vH?+g4EJ5m zQb-5EUfpC*>-j7U)nA&x%_LNa=JSKy>n{!(rS!~G<14bVmvf}3v^J>NvmfVs0+s-1 z3#!&p(@k!a5)~n%%B~5e^Sh&gWo1pr{oJPVwrZR%Uol@7WQ{SFKLd2et6{L%#xGqH zz9Vz)KxL!^y-UBNHl}WUg)bZ8RmMNfoM z*#R$-d}ilR^ON`7i+o~&Rb>7ov?yFKl&(Q}N7=!|vigeM1c_kja>eAdtt2S#ykc7} zGh&@-NUk$u!mNwm-Jwl9HL{Wyr>L1OiN|hitPsd9>|}V$n)7=~J{`oV*iPWf6kNe? zr0d@T9E?j(bg_!wK6&cNZ8ca-pg_wN-2zudyrP;ulBaKvLa4icaw$2OJG^}89I522U)0g#Lq(&|IAN%b1{+*i=i- z&ftzrk!Oc*REazeu8SFELA&aUJp94DtZDVn>d<*7^^#{Hq!G#RZ^zmAY*R z|MLoFBcX1h1HA_^ocpukHM@*!7AU(pkR?Y|Qa=nX@B4M$b-#X*`+9xBW@i@6+9 zT{g8|X@GCXtwhbFKlAX=sD1?zU8B_~S-$7Ah=ffzQHR|z!^#gDl}KYO4FgAZ(C}Ub zlM5bMDaXD0_z)a~9knNd2`Sf0B5)oSKqamR;mK-VwOY}!&3QNi>xY9UcG)YH?5fdx zCdeT4$+R`kk zH73_`I9~$?GE`L+m$j$A={BXB_-7Fem1*W^vxre^l^xSjIjR=fU`iCphqA8|JJzYl zxYdg$^TNprAl6n&wHv!{nEy;0Wle7kP8NgWYeuYMIlVoazG~6SbrEX}oH6@!7FBS!FNmYb(p)@$rD7)f2Y0@Yr3%=W0lvCfbm#K4U?IbY>P^d~mt=rr9h-~g> zx9>v!{y>>Z|ot#hF~IjfpflRJ-ZB@(_OM8_4n@tI#@7zroTi#D$<7|VAeb{K+p z+1GY2^q_WYKY=^L0!kovHF(=FRKM3F2ZkxzS-5AFoJ+ULXxqHrGD&Pp>iiw&>p=&Pj3@&ND??LD49)hUoEuy=XxfWDZz3`2ZspCuC$o5%J5nx`u1dM3k6eD zc2K@&Hznv)?lLHzC5?DoAyNXnio6p<_Z*k>xfsc7LHS!);9jy`K`?~m$?5_uN-hf9 z31!D;0HM>^F}&t;A?f{{5Jy{y35h}X)~6#)crDGdn%2(mi=$04I6i;SuJf(dsK69E zEL^oj@X}xb&kD=i9m{u#zjlylR}}pgM6oNGbPI=+L};N*yGIXgi#_01AQzqv^THaE z_MLx-^>)m_UFnv_ah|^1wx9aMtM4QMJ*nEWZ*N&Dxbx7-ohXZ_*(~W$qDIijim$Smb<6uM|}Z(sZ-$ z^3Aapoyz8wglmvhvyV&l@tKc9lvx;E@cJDblld;xhh`)N+24xxcmqDBpGB7`qCuG@ z#j~`$5;-oCGHVj!i@wee(~WoTcanrpF!FlgQWGZ#;byCwtl@Ed2nUC)vl^QHWuR>0_eVNMFIA*xxh8}n1oPGoIWnSg(ALHCfjK@I{lprp==qbF zv}@$K^gZigz^g;@uN7Xcw7d37F>o&kLM>QYX%#z~gptHTUMXhrl9E(28^$5VGyzw2 zV!uX#LFgo;Xn4&yd`#l-a|`eU+v$ak0*{K9TMbf}&yVQeOj*<)r7RKYe4o>l0{R_j zKjvGNh9elFhmlwInheO@8g!T;ZT5~?!FTvzav53qLPVpAPPVzu*i+Z0Qt?;qrL?K7 z2&|3!jc|>61^X|6m5b3qtK5Cl!0R$BgLGtnHgrY~>ljq`y+OJOLZ&~E3&O3*$TQ&g zI`AmTNS`aq6C@(Tb7PW=`|Tec4?lL_CF`^o?zAlwocjJ+&}qfII?Q!>@9^RTa9zR~ z(Gp`zO!p9U>dOAS$G^1OMwte&L^wq8tGTG*y-r9*aCk-;)I08B1qL_}#x%_ytMK%=)G zVqKq4!UE3Q*KsZ=4lXgELLzgBynR^7YVv-#Ur?X?G;4w9qwewM$6k#=E5c_cn zi)vE=C#3lWV%cJ9kUi_`=c&jhyAeSPwe;Ol>n_7_=MhgB3A{cpYCK)2b~M~nqu@Bz2R8`&N4XA-KPq7rh2QZKDE*cL z@pD8fr8dv>P51WmABkAE?!l2xTC_>xn2PZF8{b(~-6+{hYm_ZUhkcPRjqvXqRZK`x zlooha^Zv)P>fppAOI$eyhfcDc)WfL5!rZVGBhqval-&~DaNYGR<56a${mf@!@>@7s zf}!{DIi9Pb78cDc?ZgvVCU*Lf$$>2IMyhb#&jSKtaV!p~Tz{L1(hha5Qx<#*tJ5zST94)2;LVW;b{PM(~`?@>Z21`QC4Eq3z! ziX`Pzu&ikEd2cue&n`EUS!#P`N0Z0wO& zlNHm=tn!W5QXvAR%P^sd-mx$Fb^V-`V!kwbk4|Ql-}A5=r7M~4L8b!h_^athE*MS& zM>f0@YUOFfdZ4_T(zm`l-Go(~;Wc`%WUri5?>^OCdJoOHFN#O-Zo@g}YsurHIGhC+ z@a_g`%*NBoZ*DEYj`p>$5RkbIiD{>sx;EsG6v#U{?jh_M)0<;bg-5av@AP6toAcVd zIY&4^zNB#oo@rU}c*Hq>Sn8paCY{5KZSChOYW&|L!<>~XFMU7fQ-<`v8HZFj&`hj* zATkV;ruolv4Z(C7&^+o-B{umz;ll(_YFm8{orxi8-qZbFj3F@vH58vJTsO zWXHxJ7j~nW5{nr{>R!{QT!fX(TJ1hziF(xsc`iHxmPe%=VkAbi;l$B->VzK4+-PK;dWyOJg=CAkL~uopHi5!}g4vqE zh@}WeJphSBxLWBJvp7eZIjI=A6aCG?`15=T5}2|#o@ll%VwRq>e9xy#z9TIGCOeeY zAD6F;AT_^W^Y^5-Nty^RipvZ3157K-$k$gsqZsW`#{3%RF)!D~`7F%pMN z#_bz5!G++be-{m%TvqiZB-DnAf*CT@fj!CYiG4pi`g~r~E_FN?iT-8iahrtZ$KC1+ z+PyEK{-my*`@cl}E+!A?;?VR#?=hc&e_z2${0$@uz8+&eK0N=ef(4{eW=YD$22;;p zw)h&PBVL([\w\W]*?)<\/\1>/)) - { - var colorAttrs = coloredText[1].split(' '), - text = coloredText[2]; - - colorAttrs.forEach(function (attr) - { - text = text[attr]; - }); - - helpTxt = helpTxt.replace(coloredText[0],text); - } - - /*helpTxt.split('\n').forEach(function(line) - { - console.log(prefix+line); - });*/ - - console.log(helpTxt); - } - - - /*cli.on('help', function() - { - cli.help(); - });*/ -} \ No newline at end of file diff --git a/node_modules/celeri/lib/modules/history.js b/node_modules/celeri/lib/modules/history.js deleted file mode 100755 index 127c5e1..0000000 --- a/node_modules/celeri/lib/modules/history.js +++ /dev/null @@ -1,33 +0,0 @@ -exports.plugin = function(cli) -{ - var history = [], cursor = 0, max = 20; - - cli.on('enter', function() - { - history.push(cli.buffer()); - - if(history.length > max) - { - history.shift(); - } - - - cursor = history.length-1; - - }); - - - cli.on('up', function() - { - if(cursor == -1) return; - - cli.replaceLine(history[cursor--]); - }); - - cli.on('down', function() - { - if(cursor == history.length-1) return; - - cli.replaceLine(history[++cursor]); - }); -} \ No newline at end of file diff --git a/node_modules/celeri/lib/modules/loading.js b/node_modules/celeri/lib/modules/loading.js deleted file mode 100755 index 8475752..0000000 --- a/node_modules/celeri/lib/modules/loading.js +++ /dev/null @@ -1,43 +0,0 @@ -exports.plugin = function(cli) -{ - cli.loading = function(label, callback) - { - - if(typeof label == 'function') - { - callback = label; - label = ''; - } - - if(!label) label = ''; - - - function done(message, success) - { - if(!message) message = success == undefined ? 'done' : (success ? 'success' : 'fail') ; - - var color = success == undefined ? 'grey' : (success ? 'green' : 'red'); - - - clearInterval(interval); - cli.replaceLine(label + message[color]['bold']); - cli.newLine(); - } - - if(callback) callback(done); - - var seq = '–\|/'; - pos = 0, - interval = setInterval(function() - { - cli.replaceLine(label+'['+seq[pos++%seq.length].blue+'] '); - }, 200); - - - return { - done: done - }; - - - } -} \ No newline at end of file diff --git a/node_modules/celeri/lib/modules/nav.js b/node_modules/celeri/lib/modules/nav.js deleted file mode 100755 index 277d114..0000000 --- a/node_modules/celeri/lib/modules/nav.js +++ /dev/null @@ -1,13 +0,0 @@ -exports.plugin = function(cli) -{ - - cli.on('left', function() - { - cli.cursor(cli.cursor()-1); - }); - - cli.on('right', function() - { - cli.cursor(cli.cursor()+1); - }); -} \ No newline at end of file diff --git a/node_modules/celeri/lib/modules/password.js b/node_modules/celeri/lib/modules/password.js deleted file mode 100755 index 667fd20..0000000 --- a/node_modules/celeri/lib/modules/password.js +++ /dev/null @@ -1,58 +0,0 @@ -exports.plugin = function(cli) -{ - - function getMask(mask, length) - { - if(!mask) return ''; - - var buffer = ''; - - for(var i = length; i--;) - { - buffer += mask; - } - - return buffer; - } - - - cli.password = cli.queue(function(label, mask, callback) - { - if(typeof mask == 'function') - { - callback = mask; - mask = undefined; - } - - - - cli.write(label); - - var input = '', - self = this; - - self.attach(callback); - - - var disposable = cli.on({ - 'backspace': function() - { - if(!input.length) return; - - input = input.substr(0, input.length-1); - }, - 'keypress': function(data) - { - if(data.key.name != 'backspace') - input += data.char; - - cli.buffer(label+getMask(mask, input.length)); - }, - 'enter': function() - { - setTimeout(self.next,1,input); - disposable.dispose(); - } - }); - }); -} \ No newline at end of file diff --git a/node_modules/celeri/lib/modules/progress.js b/node_modules/celeri/lib/modules/progress.js deleted file mode 100755 index 25751b0..0000000 --- a/node_modules/celeri/lib/modules/progress.js +++ /dev/null @@ -1,33 +0,0 @@ -exports.plugin = function(cli) -{ - var spaces = 20, - perc = 0; - - function percentBuffer(label, color) - { - var diff = Math.round((spaces/100) * perc); - - - return label + ' ['+ cli.utils.fill('#'[color],diff,' ', spaces-diff) + '] '+ perc +'% '; - } - - cli.progress = function(label, percent) - { - //fail - if(percent === false) - { - cli.replaceLine(percentBuffer(label, perc, 'red')); - return cli.newLine(); - } - - perc = Math.min(percent, 100); - - cli.replaceLine(percentBuffer(label, perc == 100 ? 'green' : 'blue')); - - if(perc == 100) - { - return cli.newLine(); - } - - }; -} \ No newline at end of file diff --git a/node_modules/celeri/lib/modules/prompt.js b/node_modules/celeri/lib/modules/prompt.js deleted file mode 100755 index f248b02..0000000 --- a/node_modules/celeri/lib/modules/prompt.js +++ /dev/null @@ -1,41 +0,0 @@ -exports.plugin = function(cli) -{ - cli.prompt = cli.queue(function(label, callback) - { - var input = '', - self = this; - - self.attach(callback); - - - function write() - { - cli.replaceLine(label+input); - } - - - var disp = cli.on({ - 'backspace': function() - { - if(!input.length) return; - - input = input.substr(0, input.length-1); - }, - 'keypress': function(data) - { - if(data.key.name != 'backspace') - input += data.char; - - write(); - }, - 'enter': function() - { - setTimeout(self.next, 1, input); - disp.dispose(); - } - }); - - write(); - }); - -} \ No newline at end of file diff --git a/node_modules/celeri/lib/modules/quit.js b/node_modules/celeri/lib/modules/quit.js deleted file mode 100755 index b5b5de8..0000000 --- a/node_modules/celeri/lib/modules/quit.js +++ /dev/null @@ -1,7 +0,0 @@ -exports.plugin = function(cli) -{ - cli.on('ctrl-c', function() - { - process.exit(); - }); -} \ No newline at end of file diff --git a/node_modules/celeri/lib/modules/section.js b/node_modules/celeri/lib/modules/section.js deleted file mode 100755 index 31c468a..0000000 --- a/node_modules/celeri/lib/modules/section.js +++ /dev/null @@ -1,6 +0,0 @@ -exports.plugin = function(cli) -{ - cli.section = function(message) - { - } -} \ No newline at end of file diff --git a/node_modules/celeri/lib/modules/table.js b/node_modules/celeri/lib/modules/table.js deleted file mode 100644 index a0cbf97..0000000 --- a/node_modules/celeri/lib/modules/table.js +++ /dev/null @@ -1,292 +0,0 @@ -var Structr = require('structr'); - -exports.plugin = function(cli) -{ - function normalizeOptions(ops) - { - var cliWidth = cli.columns(); - - var columns = ops.columns, - normCols = [], - vert = ops.vertical || ops.vert || ' ', - horz = ops.horizontal || ops.horz || '', - pad = Structr.copy(ops.pad, { left: 0, right: 0, top: 0, bottom: 0 }); - - if(ops.padRight) pad.right = ops.padRight; - if(ops.padLeft) pad.left = ops.padLeft; - if(ops.padTop) pad.top = ops.padTop; - if(ops.padBottom) pad.bottom = ops.padBottom; - if(!ops.width) ops.width = cliWidth; - - ops.width = Math.min(ops.width, cliWidth - pad.left - pad.right); - - - if(ops.border) - { - if(vert == ' ') vert = ' | '; - if(horz == '') horz = '–'; - } - - - //sum width of all columns combined - var sumWidth = 0; - - for(var prop in columns) - { - var columnValue = columns[prop], - normCol = { minWidth: 6, align: 'left' }, - tocv = typeof columnValue; - - normCols.push(normCol) - - //['columnName'] - if(tocv == 'string') - { - normCol.name = columnValue; - } - else - { - //{columnName:value} - if(typeof prop == 'string') - { - normCol.name = prop; - } - - - if(tocv == 'number') - { - normCol.width = columnValue; - } - else - if(tocv == 'object') - { - Structr.copy(columnValue, normCol); - } - } - - if(!normCol.width) normCol.width = 100/columns.length; - - - - sumWidth += normCol.width; - } - - - //subtract vert padding - - - var sumActualWidth = 0, - colsTaken = 0, - numCols = normCols.length; - var tableWidth = ops.width - vert.length * numCols; - - - for(var i = 0; i < numCols; i++) - { - - var column = normCols[i]/*, - isLast = i == numCols-1, - align = column.align; - - if(!align) - { - column.align = isLast ? 'right' : 'left'; - }*/ - - var percWidth = Math.round(column.width/sumWidth * tableWidth); - actualWidth = Math.max(column.minWidth, percWidth), - - //diff between calculated perc width, and min width. used for penalization - difference = actualWidth - percWidth; - - sumActualWidth += actualWidth; - - - //this may happen if there are too many minWidths specified. In which case, not all columns - //will be shown. Actual width will be set to zero - if(sumActualWidth > ops.width) actualWidth -= Math.min(actualWidth, sumActualWidth - tableWidth); - - //actual width CANNOT be less than min width. e.g: single char column couold be huge. - if(actualWidth < column.minWidth) actualWidth = 0; - - column.actualWidth = actualWidth; - - //penalize the rest of the columns. Width must *not* cli width - sumWidth -= difference; - } - - return { - columns: normCols, - ellipsis: ops.ellipsis, - vert: vert, - horz: horz, - pad: pad, - width: ops.width, - numColumns: numCols, - showLabels: !!ops.showLabels - } - } - - function addLines(colLines, value, column) - { - var newLines = (value ? value.toString() : '').split(/[\r\n]/g); - - for(var i = 0, n = newLines.length; i < n; i++) - { - //trim whitespace off the ends. line breaks = whitespace - var buffer = newLines[i].replace(/^\s+|\s+$/g,''); - - var colors = buffer.match(/\u001b\[\d+m/g) || []; - - var padding = column.actualWidth - buffer.length + colors.join('').length; - - switch(column.align) - { - case 'right': - buffer = cli.utils.padLeft(buffer, padding, ' '); - break; - - case 'center': - buffer = cli.utils.pad(buffer, Math.floor(padding/2), ' ', Math.ceil(padding/2)); - break; - - default: - buffer = cli.utils.padRight(buffer, padding, ' '); - break; - } - - colLines.push(buffer); - } - } - - function getRowLineTable(item, ops) - { - var lineTable = [], - numLines = 0, - cols = ops.numColumns; - - - //get the lines. - for(var j = 0, jn = cols; j < jn; j++) - { - var column = ops.columns[j], - value = item[ops.columns[j].name] || '', - colLines = [], - actualWidth = column.actualWidth; - - //width not present? skip the column - if(!actualWidth) continue; - - - if(value.length > actualWidth) - { - if(ops.ellipsis) - { - var newBuffer = value.substr(0, actualWidth-3) + cli.utils.repeat('.', Math.min(actualWidth, 3)); - - addLines(colLines, newBuffer, column); - } - else - { - var start = 0; - - //splice apart the single line, treating each chunk as a new line - for(var k = actualWidth; k < value.length + actualWidth; k += actualWidth) - { - addLines(colLines, value.substr(start, actualWidth), column); - start = k; - } - } - } - else - { - addLines(colLines, value, column); - } - - //if this column lines - numLines = Math.max(numLines, colLines.length); - - - //next add the line - need to check against all lines now - lineTable.push(colLines); - - - //need to go through all the column lines again, and - //make sure all the lines match up properly - for(var k = 0, kn = lineTable.length; k < kn; k++) - { - var line = lineTable[k]; - - //must have same number of lineTable - if(line.length < numLines) - { - addLines(lineTable[k], cli.utils.repeat('\n', numLines - line.length -1), ops.columns[k]); - } - } - } - - var rows = []; - //inversed - for(var i = 0, n = lineTable.length; i < n; i++) - { - var col = lineTable[i]; - - //each row - for(var j = 0, jn = col.length; j < jn; j++) - { - if(!rows[j]) rows[j] = []; - - rows[j].push(col[j]); - } - } - - return rows; - } - - function logRow(ops, buffer) - { - console.log(cli.utils.repeat(' ', ops.pad.left) + buffer); - } - - function drawBreak(ops) - { - if(ops.horz) logRow(ops, cli.utils.repeat(ops.horz, ops.width)); - } - - function drawRow(lineTable, ops) - { - for(var i = 0, n = lineTable.length; i < n; i++) - { - logRow(ops, lineTable[i].join(ops.vert)) - } - - drawBreak(ops); - } - - function drawTable(source, ops) - { - if(ops.pad.top) console.log(cli.utils.repeat('\n', ops.pad.top-1)); - - drawBreak(ops); - - for(var i = source.length; i--;) - { - var lineTable = getRowLineTable(source[i], ops) - - drawRow(lineTable, ops); - } - - if(ops.pad.bottom) console.log(cli.utils.repeat('\n', ops.pad.bottom-1)); - - } - - - cli.drawTable = function(source, ops) - { - ops = normalizeOptions(ops); - drawTable(source, ops); - - // console.log(ops) - - } -} \ No newline at end of file diff --git a/node_modules/celeri/lib/modules/table2.js b/node_modules/celeri/lib/modules/table2.js deleted file mode 100755 index 6062344..0000000 --- a/node_modules/celeri/lib/modules/table2.js +++ /dev/null @@ -1,275 +0,0 @@ -//oh my god what have I written. Quick, look away!!! - -exports.plugin = function(cli) -{ - - //draw table params & columns - //cli.drawTable(..., {name: 20, age: 20} - //TODO - - function addLines(ops) - { - var columnWidth = ops.columnWidth, - lines = ops.lines, - buffer = ops.buffer, - currentWidth = ops.currentWidth, - align = ops.align, - ellipsis = ops.ellipsis, - windowWidth = ops.windowWidth, - columnIndex = ops.columnIndex, - columns = ops.columns, - vert; - - - //last element? fill in the rest - if(columnIndex == columns.length-1) - { - columnWidth = windowWidth - currentWidth; - vert = ''; - } - else - { - vert = ops.vert; - } - - - var maxWidth = columnWidth - vert.length; - - - buffer.split('\n').forEach(function(line, index) - { - - if(line.length > maxWidth) - { - - //text too long? option to still keep it a one-liner - if(ellipsis) - { - line = line.substr(0, maxWidth-3) + '...'; - } - else - { - var start = 0; - var newLines = []; - - - for(var i = maxWidth; i < line.length + maxWidth; i += maxWidth) - { - newLines.push(line.substr(start, maxWidth)); - start = i; - } - - - return addLines({ - buffer: newLines.join('\n'), - columnWidth: columnWidth, - currentWidth: currentWidth, - align: ops.align, - windowWidth: windowWidth, - vert: vert, - lines: lines, - columnIndex: columnIndex, - columns: columns - }); - } - } - - padding = Math.max(columnWidth - line.length, 0); - - var colStr = ''; - - - - switch(align) - { - case 'right': - colStr = cli.utils.padLeft(line, padding, ' '); - break; - - case 'center': - colStr = cli.utils.pad(str, Math.floor(padding/2), ' ', Math.ceil(padding/2)); - break; - - default: - colStr = cli.utils.padRight(line, padding, ' '); - break; - - } - - - - if(!lines[index] ) - { - var buffer = ''; - - - for(var i = 0, n = columnIndex; i < n; i++) - { - buffer += cli.utils.padLeft(vert, columns[i].width-vert.length, ' '); - } - - lines[index] = buffer; - } -else -{ - console.log('GGG'+colStr); - console.log(index) -} - - - - - //console.log(maxWidth + " " + currentWidth+" "+lines[index].length); - - - - lines[index] += colStr + vert; - }); - } - - cli.drawTable2 = cli.table = function(objects, ops) - { - if(!(objects instanceof Array)) objects = [objects]; - - var windowWidth = ops.width || cli.columns(), - columns = ops.columns, - colArray = [], - vert = ops.vertical || ops.vert || ' ', - horz = ops.horizontal || ops.horz || '', - ellipsis = ops.ellipsis; - - - if(ops.padRight) windowWidth -= ops.padRight; - - - if(ops.border) - { - if(vert == ' ') vert = ' | '; - if(horz == '') horz = '–'; - } - - - - var tableWidth = 0, - title = {}, - medianColWidth; - - //convert the object into an array - if(columns instanceof Array) - { - colArray = columns; - - var numColumns = colArray.length, medianColWidth = Math.round(numColumns/windowWidth) - - for(var i = numColumns; i--;) - { - var col = colArray[i]; - - if(typeof col == 'string') - { - colArray[i] = col = { - name: col, - width: medianColWidth - }; - } - - title[col.name] = col.name; - tableWidth += col.width; - } - } - else - { - for(var property in columns) - { - var param = columns[property]; - - if(typeof param == 'number') - { - param = { - width: param, - }; - } - - param.name = property; - tableWidth += param.width || 0; - - title[param.name] = param.name; - colArray.push(param); - } - } - - //objects.unshift(title); - - - objects.forEach(function(object) - { - - var lines = []; - - var buffer = '', currentWidth = 0; - - for(var i = 0, n = colArray.length; i < n; i++) - { - var columnInfo = colArray[i]; - - if(typeof columnInfo == 'string') - { - columnInfo = { - name: columnInfo - }; - } - - if(!columnInfo.width) columnInfo.width = Math.round(100/n) + '%'; - - columnName = columnInfo.name; - - //percent - if(true || typeof columnInfo.width == 'string') - { - - //var cw = columnInfo.width.substr(0, columnInfo.width.length-1); - - columnWidth = Math.min(columnInfo.width, Math.floor((columnInfo.width/tableWidth) * windowWidth)); - - } - else - { - columnWidth = columnInfo.width; - } - - - //the string element. could be from a method, prop, or it's undefined - var str = (columnInfo.get ? columnInfo.get(object) : object[columnName] || 'Undefined').toString(); - - - - addLines({ - buffer: str, - lines: lines, - columnWidth: columnWidth, - currentWidth: currentWidth, - align: columnInfo.align, - windowWidth: windowWidth, - vert: vert, - ellipsis: ellipsis, - columnIndex: i, - columns: colArray - }); - - - currentWidth += columnWidth + vert.length; - - } - - if(horz.length) console.log(cli.utils.repeat(horz, windowWidth)); - - lines.forEach(function(line) - { - console.log(line); - }); - }); - - - if(horz) console.log(cli.utils.repeat(horz,windowWidth)); - } -} \ No newline at end of file diff --git a/node_modules/celeri/lib/modules/tree.js b/node_modules/celeri/lib/modules/tree.js deleted file mode 100755 index 00ef79e..0000000 --- a/node_modules/celeri/lib/modules/tree.js +++ /dev/null @@ -1,95 +0,0 @@ -utils = require('../utils'), -Structr = require('structr'); - -//see http://en.wikipedia.org/wiki/Box-drawing_characters -exports.plugin = function(cli) -{ - - //┌── - //├── - //└── - - cli.drawTree = cli.tree = function(tree, ops, tab) - { - if(!ops) ops = {}; - - - var parts = { }; - - if(ops.pretty) - { - parts = { - pipe: '|', - tee: '┬', - dash: '─', - leftCorner: '└', - left: '├', - branch: utils.repeat('─', 1) - } - } - - //plays a little more nicely with fonts such as terminus - else - { - parts = { - pipe: '|', - tee: '+', - dash: '-', - leftCorner: '+', - left: '|', - branch: utils.repeat('-', 1) - } - } - - Structr.copy(ops.parts || {}, parts); - - - parts.tabs = utils.repeat(' ',parts.branch.length+1); - - - if(!tab) tab = ''; - - var n = utils.objectSize(tree), - i = 0, - printedBreak = false; - - - for(var index in tree) - { - - var childrenOrValue = tree[index], - toc = typeof childrenOrValue, - toi = typeof index, - edge = i < n-1 ? parts.left : parts.leftCorner; - - - var value = !isNaN(Number(index)) ? childrenOrValue : index + ': ' + childrenOrValue; - - - console.log('%s%s%s %s', tab, edge, parts.branch + ((toc == 'object') ? parts.tee : parts.dash), toc != 'object' ? value: index); - - - if(toc == 'object') - { - printedBreak = cli.drawTree(childrenOrValue, ops, n > 1 && i < n-1 ? tab + parts.pipe + parts.tabs.substr(1) : tab + parts.tabs); - } - /*else - if(toc == 'string' || toc == 'number') - { - - }*/ - - i++; - } - - - //add extra breaks for folders - a little more readable - if(!printedBreak) - { - console.log('%s',tab); - printedBreak = true; - } - - return printedBreak; - } -} \ No newline at end of file diff --git a/node_modules/celeri/lib/utils.js b/node_modules/celeri/lib/utils.js deleted file mode 100755 index f208e47..0000000 --- a/node_modules/celeri/lib/utils.js +++ /dev/null @@ -1,44 +0,0 @@ -exports.padLeft = function(buffer, n, char) -{ - return exports.repeat(char, n) + buffer; -} - -exports.padRight = function(buffer, n, char) -{ - return buffer + exports.repeat(char, n); -} - - -//pad on left & right -exports.pad = function(buffer, ln, char, rn) -{ - return exports.repeat(char, ln) + buffer + exports.repeat(char, rn || ln); -} - - -exports.fill = function(leftChar, ln, rightChar, rn) -{ - return exports.repeat(leftChar, ln) + exports.repeat(rightChar, rn); -} - - -exports.repeat = function(char, n) -{ - var buffer = ''; - - for(var i = Math.abs(n); i--;) - { - buffer += char; - } - - return buffer; -} - -exports.objectSize = function(target) -{ - var n = 0; - - for(var i in target) n++; - - return n; -} \ No newline at end of file diff --git a/node_modules/celeri/node_modules/beanpole/.cupboard b/node_modules/celeri/node_modules/beanpole/.cupboard deleted file mode 100644 index 46d2b19..0000000 --- a/node_modules/celeri/node_modules/beanpole/.cupboard +++ /dev/null @@ -1,2 +0,0 @@ -[commands] -proj = subl --project project.sublime-project diff --git a/node_modules/celeri/node_modules/beanpole/.gitignore b/node_modules/celeri/node_modules/beanpole/.gitignore deleted file mode 100644 index a051526..0000000 --- a/node_modules/celeri/node_modules/beanpole/.gitignore +++ /dev/null @@ -1,2 +0,0 @@ -node_modules -n diff --git a/node_modules/celeri/node_modules/beanpole/MIT-LICENSE.txt b/node_modules/celeri/node_modules/beanpole/MIT-LICENSE.txt deleted file mode 100644 index 31d6550..0000000 --- a/node_modules/celeri/node_modules/beanpole/MIT-LICENSE.txt +++ /dev/null @@ -1,20 +0,0 @@ -Copyright (c) 2011 Craig Condon - -Permission is hereby granted, free of charge, to any person obtaining -a copy of this software and associated documentation files (the -"Software"), to deal in the Software without restriction, including -without limitation the rights to use, copy, modify, merge, publish, -distribute, sublicense, and/or sell copies of the Software, and to -permit persons to whom the Software is furnished to do so, subject to -the following conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/celeri/node_modules/beanpole/README.md b/node_modules/celeri/node_modules/beanpole/README.md deleted file mode 100644 index 78665d0..0000000 --- a/node_modules/celeri/node_modules/beanpole/README.md +++ /dev/null @@ -1,392 +0,0 @@ -## Beanpole - Routing framework - - -### What are some features? - -- Syntactic sugar (see below). -- Works with many protocols: amqp, http, websockets, etc. -- Hooking with other applications is a breeze with [daisy](https://github.com/spiceapps/daisy). -- Works well with coffeescript - - -### Projects using Beanpole - -- [celeri](https://github.com/spiceapps/celeri) - CLI library -- [bonsai](https://github.com/spiceapps/bonsai) - application server -- [leche](https://github.com/spiceapps/leche) - Framework to build frontend / backend applications with the same code. -- [daisy](https://github.com/spiceapps/daisy) - Expose beanpole to: http, websockets, amqp (rabbitmq), etc. -- [beandocs](https://github.com/spiceapps/beandocs) - Generate documentation from your beanpole route comments. -- [beanprep](https://github.com/spiceapps/beanprep) - Scans beans in a given directory, and installs their dependencies. -- [cupboard](https://github.com/spiceapps/beanprep) - Reverse package manager. - -### Beanpole ports - -- [Actionscript](https://github.com/spiceapps/beanpole.as) -- [C++](https://github.com/spiceapps/beanpoll) - -### Overview - - -![Alt ebnf diagram](http://i.imgur.com/v1wdO.png) - - -The basic route consists of a few parts: the `type` of route, and the `channel`. Here are some examples: - - router.on('pull hello/:name', ...); - -and - - router.on('push hello/:name', ...); - - -#### Push Routes: - -- Used to broadcast a message, or change (1 to many). -- Doesn't expect a response. -- Multiple listeners per route. - -#### Pull Routes: - -- Used to request data from a particular route (1 to 1). -- Expects a response. -- One listener per route. -- examples: - - request to http-exposed route - - - -Using both `push`, and `pull` allows you to **bind** to a particular route. For example: - - -````javascript - -var _numUsers = 0; - - -//numUser getter / setter function -function numUsers(value) -{ - if(!arguments.length) return _numUsers; - - _numUsers = value; - - router.push('users/online', value); -} - - -//the request handler. This could be called in-app. It's also just as easily exposable as an API to http, websockets, etc. -router.on('pull users/online', function(request) -{ - request.end(numUsers()); -}); - -//pull num users initially, then listen for when num users changes. -router.on('push -pull users/online', function(response) -{ - //handle change here.. - console.log(response); //0, 3, 10... -}); - - - -//triggers above listener -numUsers(3); -numUsers(10); - -```` - -Okay, so you might have noticed I added something funky here: `-pull` - that's a tag. Tags are structured like so: - - router.on('pull -tagName hello/:route', ...); - -or, you can add a value to it: - - router.on('pull -method=GET hello/:route', ...); - -As mentioned above, you can only have *one* listener per `pull` route. HOWEVER, you can have multiple listeners per `pull` route *if* you provide different tag values. For example: - -````javascript - -router.on({ - - /** - * returns the given user - */ - - 'pull -method=GET users/:userId': function(request) - { - //get the specific user - }, - - /** - * updates a user - */ - - 'pull -method=UPDATE users/:userId': function(request) - { - //update user here - }, - - /** - * deletes a user - */ - - 'pull -method=DELETE users/:userId': function(request) - { - //delete user - } - -}); -```` - -The above chunk of code is well suited for a REST-ful api without explicilty writing it *for* an http server. It can be used for any protocol. For example - say I wanted to *delete* a user using the code above: - -````javascript - -router.pull('users/' + someUserId, { tag: { method: 'DELETE'} }, function() -{ - //delete user response -}); - -```` - -You might have guessed - tags can be used to filter routes. Okay, onto something a little more advanced: **middleware**. Here's an example: - -````javascript - - -router.on({ - - /** - */ - - 'pull authorize': function(request) - { - if(request.data.secret != 'superSecret') - { - request.end('You shall not pass!'); - } - else - { - - //onto the next route - request.next(); - } - }, - - /** - */ - - 'pull -method=GET authorize -> my/profile': function(request) - { - request.end('Super secret stuff!'); - } - -}); - - -```` - -The token `->` denotes `my/profile` must go *through* the `authorize` route. Here are a few more use-cases: - -````javascript - -router.on({ - - /** - */ - - 'pull post/body': function(request) - { - //post http request body here. This is implemented in daisy - }, - - /** - */ - - 'pull session': function(request) - { - //initialize cookies for the user. Again, implemented in daisy - }, - - /** - */ - - 'pull -method=POST post/body -> session -> upload/video': function() - { - //passed through 2 routes before getting here. - }, - - /** - */ - - 'pull cache/:ttl': function(request) - { - //used to check if the *next* route is cached. If it is, then return the value vs continuing - }, - - /** - */ - - 'pull cache/10000 -> some/heavy/request': function(request) - { - //do some heavy stuff here, but go through the cache route so it's not called on each request - } - - -}) - -```` - -Middleware is especially useful for a REST-ful interface: - -````javascript - -router.on({ - - /** - * returns the given user - * @example /users/665468459 - */ - - 'pull users/:userId': function(request) - { - getUser(request.data.postId, funciton(user) - { - request.user = user; - - //route being used as middleware? - if(request.hasNext()) return request.next(); - - //return the user - request.end(user); - }) - }, - - /** - * Returns a post made by a particular user - * @example /users/665468459/posts/54353499534 - */ - - 'pull users/:userId -> users/:userId/posts/:postId': function(request) - { - getPosts(request.user, request.data.postId, function(posts) - { - request.end(posts); - }) - } -}); - -```` - -Middleware can also be specified without using the token: `->`.An example: - - -````javascript - -router.on({ - - /** - */ - - 'pull my/*': function() - { - //authorize user - }, - - /** - */ - - 'pull my/profile': function() - { - //goes through authorization first - } -}); - -```` - -Providing a wildcard `*` tells the router that **anything** after the route must go through it. - - -### Methods - -#### router.on(type[,listener]) - -Listens to the given routes - -- `type` - string or object. String would contain the route. Object would contain multiple routes / listeners -- `listener` - function listening to the route given. - - -#### router.push(route[, data][, options]) - -- `type` - the channel broadcast a message to. -- `data` - the data to push to the given route -- `options` - options for the given route - - `meta` - tags to use to filter out listeners - -#### router.pull(route[, data][, options][, callback]) - -same as push, but expects a response - -#### router.channels() - -returns all registered channels - -#### router.getRoute(route) - -returns route expression - -#### request.write(chunk) - -Initializes a streamed response. Great for sending files - -#### request.end([chunk]) - -Ends a response - -#### request.hasNext() - -Returns TRUE if there's a listener after the current one. - -#### request.next() - -Moves onto the next route. - -#### request.forward(channel, callback) - -Forwards the current request to the given channel - -#### request.thru(channel[ ,options]) - -Treats the given channel as middleware - -#### request.data - -Data is added here - - -### One last goodie - -Beanpole works well with coffeescript: - - -````coffeescript - -router.on - - # - 'pull -method=GET say/hello': -> - "hello world!" - -```` - - - - - - - - - - diff --git a/node_modules/celeri/node_modules/beanpole/beanpole.tmproj b/node_modules/celeri/node_modules/beanpole/beanpole.tmproj deleted file mode 100644 index 115e82d..0000000 --- a/node_modules/celeri/node_modules/beanpole/beanpole.tmproj +++ /dev/null @@ -1,185 +0,0 @@ - - - - - currentDocument - lib/core/middleware/route/pushPull/pull/request.js - documents - - - expanded - - name - beanpole - regexFolderFilter - !.*/(\.[^/]*|CVS|_darcs|_MTN|\{arch\}|blib|.*~\.nib|.*\.(framework|app|pbproj|pbxproj|xcode(proj)?|bundle))$ - sourceDirectory - - - - fileHierarchyDrawerWidth - 200 - metaData - - examples/bean.hello/beans/hello.core/index.js - - caret - - column - 14 - line - 9 - - columnSelection - - firstVisibleColumn - 0 - firstVisibleLine - 0 - selectFrom - - column - 3 - line - 9 - - selectTo - - column - 14 - line - 9 - - - examples/bean.hook.hello/beans/test/index.js - - caret - - column - 0 - line - 0 - - firstVisibleColumn - 0 - firstVisibleLine - 0 - - examples/ws/server.js - - caret - - column - 14 - line - 34 - - columnSelection - - firstVisibleColumn - 0 - firstVisibleLine - 0 - selectFrom - - column - 3 - line - 34 - - selectTo - - column - 14 - line - 34 - - - lib/core/concrete/collection.js - - caret - - column - 0 - line - 13 - - firstVisibleColumn - 0 - firstVisibleLine - 0 - - lib/core/concrete/router.js - - caret - - column - 37 - line - 162 - - firstVisibleColumn - 0 - firstVisibleLine - 142 - - lib/core/controller.js - - caret - - column - 1 - line - 8 - - firstVisibleColumn - 0 - firstVisibleLine - 0 - - lib/core/middleware/meta/rotate.js - - caret - - column - 60 - line - 22 - - firstVisibleColumn - 0 - firstVisibleLine - 0 - - lib/core/middleware/route/pushPull/pull/request.js - - caret - - column - 0 - line - 14 - - firstVisibleColumn - 0 - firstVisibleLine - 0 - - - openDocuments - - lib/core/controller.js - examples/bean.hello/beans/hello.core/index.js - examples/bean.hook.hello/beans/test/index.js - lib/core/concrete/collection.js - lib/core/concrete/router.js - lib/core/middleware/meta/rotate.js - lib/core/middleware/route/pushPull/pull/request.js - examples/ws/server.js - - showFileHierarchyDrawer - - windowFrame - {{0, 4}, {1470, 1024}} - - diff --git a/node_modules/celeri/node_modules/beanpole/docs/beans/README.md b/node_modules/celeri/node_modules/beanpole/docs/beans/README.md deleted file mode 100644 index 6f7a6f6..0000000 --- a/node_modules/celeri/node_modules/beanpole/docs/beans/README.md +++ /dev/null @@ -1,76 +0,0 @@ -### Beans - -Beans are a fancy name for **plugin**. - -### Organization - -This is still very much a work in progress, but personally, I try to stick to a few conventions which help organize my "beans". Here are some general rules I follow: - -- All beans are placed in a single directory. The directory name depends on what the application does. - - If the app serves one platform, then place the beans in `app/beans`; - - If the app serves multiple platforms, then place the beans in: - - `app/node/beans` for node.js specific beans. - - `app/web/beans` for web-specific beans. - - `app/shared/beans` for beans usable across all platforms. - -- Bean names should reflect any RESTful API used in the bean. -- Beans in NPM have `bean` prepended to the name e.g: `bean.database.mongo`. - - - -### Naming Conventions - - -Start off with the category of the bean first, and then the subject. A few examples: - -- database.mongo -- database.redis -- database.mysql - -Using `database` as the category tells that all beans share the same API. I can easily add / remove any `database` bean I want without breaking the application. - - -If you have a plugin that uses many plugins, then try this naming convention: - -- `category`.core - -And for beans that make up `category.core`: - -- `category`.part.`subject` - -For example: - - -- stream.core -- stream.part.facebook -- stream.part.twitter -- stream.part.google - - -Where all the **parts** make up `stream.core`. Remember that parts shouldn't do **anything**. They make-up core plugins. If you have a plugin that serves several plugins, split it up like so: - -- posting.part.facebook -- friends.part.facebook - -You could also do something like: - -- stream.core -- group.core -- group.part.stream.core `part of stream.core` - - -Try and follow a RESTful naming convention. For example: - - -- stream.core -- stream.part.subscription.core `listening for streamed content, and sending off to registered subscribers` -- stream.part.subscription.email `subscription listening to stream, and sending a newsletter` -- stream.part.subscription.facebook `subscription listening to a stream, and posting out to facebook` - -Note that `part` was dropped after `subscription`. I find it reduntant to use it after the first instance. We already know that `stream.part.subscription.core` is nothing without `stream.core`, so anything *after* that is also useless without the root plugin. - - - - - - diff --git a/node_modules/celeri/node_modules/beanpole/docs/brainstorming/README.txt b/node_modules/celeri/node_modules/beanpole/docs/brainstorming/README.txt deleted file mode 100644 index 1da1f1d..0000000 --- a/node_modules/celeri/node_modules/beanpole/docs/brainstorming/README.txt +++ /dev/null @@ -1 +0,0 @@ -These notes are just so I can straighten out ideas about the architecture. \ No newline at end of file diff --git a/node_modules/celeri/node_modules/beanpole/docs/brainstorming/analogy.txt b/node_modules/celeri/node_modules/beanpole/docs/brainstorming/analogy.txt deleted file mode 100644 index b2804d4..0000000 --- a/node_modules/celeri/node_modules/beanpole/docs/brainstorming/analogy.txt +++ /dev/null @@ -1 +0,0 @@ -- modularized skyscraper \ No newline at end of file diff --git a/node_modules/celeri/node_modules/beanpole/docs/brainstorming/ideas.txt b/node_modules/celeri/node_modules/beanpole/docs/brainstorming/ideas.txt deleted file mode 100644 index fe71bbc..0000000 --- a/node_modules/celeri/node_modules/beanpole/docs/brainstorming/ideas.txt +++ /dev/null @@ -1,155 +0,0 @@ ---------------------------------- -Abstracting beanpole: ---------------------------------- - -Plugins *MUST NOT* know if whether a computer is networked. That job is delegated for *one* particular module: glue.core. If a client connects to a server, and contains a hook which acts like a plugin, the backend should treat it exactly as it would with a another networked server, or even internally. Glue.core would handle the handshake / authentication. - -Likewise, connected servers using brazen must not handle communication with other servers differently than internally. - - -For security sake, each channel must provide metadata identifying whether it's private, protected, or public. Channels default to private if it's absent. - - - Public channels are available to call without authentication - - Protected channels are available to call only by other crusted servers / clients - - Private channels can only be handled within the application. - -All metadata is handled by the parser / router. - - ---------------------------------- -Routing: ---------------------------------- - -The routing mechanism should parse syntactic sugar to identify how a particular channel is handled. Each channel must be separated by backslashes to allow for parameters. This is primarily for future implementation where beanpole might support HTTP requests. - -'[type] [meta]* [channel_name]* [channel/:param] [additional]*' - -- type: the type of channel - push, pull, ??? -- meta: information attached to channel help glue.core, and other handlers. -- channel_name: the name of the channel. Private use from channel. Useful if channel needs to change, like a variable name. -- channel: the physical channel separated/by/backslashes -- additional: additional parameters specific to the channel type. - -on push application/ready: function(data){} - -'push private -pull application/ready' - -on private pull of application ready passing through application exists: - -'pull private application/exists -> application/ready': function(pull){ } - - -Calling back: - -There needs to be a way for modules handling a particular request to identify where it's coming from. - ---------------------------------- -Types of channels: ---------------------------------- - -- pull - (getting) channels which respond to a particular request which maybe pushed out at a later time. This is from the source that makes the "push" with the same name. -- push - (setting) channels which are pushed out are used after a particular change has occurred. This is one to many. - -Why I chose for push/pull to be different handlers with the same name: - -Inspiration was actually taken back in the day when I was developing in Actionscript (I know, stfu). Bindable metadata was a slick way of getting a particular property from an object, and then sticking to it for any changes. For beanpole, "pull" would be the action of getting the current value of a particular "pod" (object), and "push" is the method of sticking to it. - -Problems: - -How do we distinguish single pulls from multiple pulls? For instance, for multiple pulls, I may want to "pull" stats from all the servers, but for a single pull, I may want to register a particular queue, and *only* send it to one instance. - -Possible solutions: - -on('pull multi…') - -proxy.pull('multi…') - -is a different channel handing than - -on('pull…') -proxy.pull('…') - -So technically, if I register - -proxy.on('pull get.name', …') -proxy.on('pull multi get.name') - -there wouldn't be any complaining, since I can call only one, or the other. Where the first one can be the *only* one, and the second one can have multiple. SO - -proxy.pull('get.name') - -would be the first one, and - -proxy.pull('multi get.name') - -would be the second one. - - -Multiple pulls also need to return to the requestor how many items are handling the request. This probably needs to take on a response, ondata, and end approach similar to node.js's streaming api - -Streaming: - -Without adding too much shit to the architecture, there may come a time where content is streamed to the particular requestor. This could be highly beneficial for programs which send files back and forth. Something which beanpole isn't necessarily equipped for at the moment. So, without changing the architecture, perhaps providing a method for supporting such a feature. For example: - -This could be used: - -proxy.pull('get.file','text.txt', { - data: function(buffer) - { - }, - end: function() - { - } -}); - -or this could be used: - -proxy.pull('get.file','text.txt',function(body) -{ -}); - - -But what about pulling from multiple sources? - -proxy.pull('multi get.file', 'text.txt', function(source) //callback multiple times -{ - source.on('data… -}); - - -Hmmmm… - - --------------------------------- -Network Topology --------------------------------- - -The architecture, mainly glue.core must have the ability to manage connected servers. Many of which should only communicate to particular applications. For instance: Currently there are two applications on spice.io which register queue's to the queue app . Each application has a slave which handles the cue, but the queue must know which slaves to send to. So: - -- Each app must have an identifier shared amongst other apps it needs to communicate with (_appId) -- Since queues are protected, the handshake to between the queue app and the requester must be authenticated. -- The queue must receive the app id, and know what apps to send to via registered channels. - -What if there are dozens of slaves running across a cluster of servers? - -there *must* be a way for glue.core to use a load-balancing mechanism to send individual pulls to servers: round robin, least connected, etc. Stats from servers to see which is less busy? - -What if there are multiple singleton pulls registered to glue.core? - -Duh, fucking round-robin that shit when a pull-request is made. - - - - - - - - - - - - - - - - diff --git a/node_modules/celeri/node_modules/beanpole/docs/build-ebnf b/node_modules/celeri/node_modules/beanpole/docs/build-ebnf deleted file mode 100755 index a4a085d..0000000 --- a/node_modules/celeri/node_modules/beanpole/docs/build-ebnf +++ /dev/null @@ -1,5 +0,0 @@ -#!/usr/bin/env node - -var ebnf = require('ebnf-diagram'); - -ebnf.fromFile(__dirname + '/syntax.ebnf', __dirname + '/diagram.png',3000, 1654); diff --git a/node_modules/celeri/node_modules/beanpole/docs/diagram.png b/node_modules/celeri/node_modules/beanpole/docs/diagram.png deleted file mode 100644 index a2489a661cdf52fee2c9ceeda848ec223c774e3e..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 63906 zcmeFXi9gic|2{ra+-=-F{Ra)bi6yF7nI+!3)nXLH8$p{32A z8S~vT6<=hOdic~YSB!;5gn1g>lRxLpe*ePwDCFfj5PSM~7g|t)H(ss@za;}hB zD8U70^M9}Zi@^Uy;Qu18K{i;-G|1UZ}d@nrW`|l4guk!x)FQCK}@JM7HJa_{-DvsyJIKQMY zpl)t=IlL0%S_t+XjAFqjHUDgidGUM~G(bo`3u>T*sDinwg!i4qOkIX45;f9duE63l zHWZ6+X6dXS$C&1>-s8@g09dUCu^pO_=A1!Mft|H$T6@n-c86nFu$l13u^m#xwIRkM zXn@v}4etM)OWyOtdkaC=Fyf}ci@y5_5>iykh zk9i5Ahf!~5eIiX*a(5Zpn6KIW6IyM`U<|d-eI5*XQ@c);qi>vswaXLX!M=ykj&KHh zD6FIQ)3)bvSfNq_T8S8KH%1?ZTAX(>$Qa~@IJoIV&}Z71zkYT`<3#`XfEaHIS+uox zi`|OB+#sbK8EfCBO*Ybhe2i~HP^*yLhai>7Ap=_8oJZWe3#5f>53MgeYS(hkrZgd= zor=DMrNsoKz+ZK!6Jtq|d5U7RIxCAU&rva2Ry}b^BmWLLPhyu)-!>~%kk*hDsX?R{ zK-a8oF}lCcY&V%==(iZA$mmbi6g}A53-xP-^~6mJsokBL*s45AkOwuuoY77?eh#9^ z-Qwl#t+*Ddoh8}if^ow6-PEY7uTM9})urF_di&R*%H*y~#wmU3@HD6?HoeyeUv!Hx zgrH9H#((6!RKr*KdVGBRnRdZ|UfPsA(GN2vLoB?Jz$Za$Ie4#BP!#em6TJA;;dQcp z30;aM{dqCng?q+N4c0or{GHSm=~Q!Wpqr zn(Qzb``6*oC>xBpm^{Y=~O}7%u2|rV?c62-ADsMwlSLKvaq+>@q<0*n#w9RB` z7!CgQ<9v2rUQ2(VX3R}Yf<)7O0?P+am%-k8#ro7nm!TiqJW(e6I%O&F->{*nH?LkJyVXI?1fm->rHi5%XBcKFuo=7rzd z$=Jtcp`NkqQR4kgL>gJof5M)`+ zYd1vQYHu5*wnb}-uxaIzgT~=iPPZW+RP%je=USm1F~5F%R0P{ylxTk3*JI%-SwufC zT>ou}Xz;!%@^o{NX&$6q&M$cPrfXhQ>oxq^s)yGHA7H_#F~@D>fU4V!piP8rv02QWMarNoB=4FxfR|`~G2QnO-6^8e zSS;2l!^*#i(vmi%WlYtctIDA4><70a?7 zi&HjU3^jPUK~gtgO3o0y#h}y|DMH>ojcS`IM&T7rt~7pHxQiK0T_8ufVA!9HcmwTn zsNpUAGFaU!L{?pJ>IRE2(tVOA-hljL>|vc*<7C@4>3NH^DZdOC1ye>Xh?~8b?t@<; z!b0aEf!oUmW&V8SJbzD*-hiNqv_aducfW>DrkpJ8xgC(#X@H~Yu?H&m5A7n5i#&1H zQbeO-rd~p;#hv25{JYKjT)so6TWV11WL*?P7si(=Uu}CM8KeH1Maf4nbhWnbcDKKz z%%Aq`5F~~`98lOv8aow1?G27$#DI!R%E`%@++?y6o}apgS^N;LVIXwEb)3EIQuuC8w979#~JXy&_;Wrg-v5}FFXd-taRQU}NnkvYJWMYJ7eDop3e zw*<+?QAE)&E!^!d>l=0O-wExzCrAT{?D6`}q6o~CJ~0(ra9S58mM`ERh)jUSMNiDE zz$TBg(qL<8#d-vTf`)G9_>#UyFWrLi2FkP_3s5KW=PxwH{Y{jY>_K1fyYyrb{0MnC z7uGzz){D^%ezPBl-$KTJ{1Gv%p2GbD3PQ`oOtm9(i!2zGB0Aq@=WCE-A)_O(;Q6JFg8CbaMJr0bARlCMOLsGd@)2`qO{Dq7PVjVy!o(hu2;b;C zMQN1RFg|nN=undC;Kc7250e`}y*q_z7j*R8WVEI;de9wl)gSL%0HB&*r7d&<-IC6D zC8BdI*ay!Ks%tRM%K6=0=+{BC1hFyy6WTsSez5RPN44bckNZt&lyk5umGG1fgK5a% z2PNYKK3Ofa*tZ}FVpYx7>62R9A4vcF7)rbNfRC32B{Q@YzX)saRHCmn4yFbsv>t@1q8j+WHfH0I~T&$?aH3%RQ9$1T(@Hm@k4brwT;);1%gxQ5D}W zJ%U$(bnjWG%es<4VT*UZJp@7BQ4(rx9NGH;eKt3bP0#8Z7?^pWZTWFeg?Dd3DJ}e; zb*98_3}z4u*Bym|q|+iE@n9BJ3hs6rFE))kjK8cux|zH^E<)qtq}S_x;OH5j-c=)_ zjC#e*ndhK1r6)i{4ApC_g`~yUV>Uw}ZgV#|#QK{iK% zn5ME0+@O31>G>zH0b#`of_?*;-VtVUk;@l${P^(zWbOhE(|WJ+_hV>B4&^UW;xPxs zkdTla5xxWt`Q|!#i^(#+H>YC^fjEubQTpBD-^g6D>T!E6K&OUkb7XNEe=GT(k9t+a z@|h?cf-yPNvoNt26iXNy;L6fEWw!&mTW76FC!1ArV$EklV)dSP=mub>G-&kg?4iNm zzm}`b^F-XjpFs_-Owd0f(-u3SikeTT`bxyZ0ZPHjRG3b0~hEDxl@A7 zrNbF75@!YZdE)KOFNrL5PcW zHgH3z2U{aUd?uMB{#CU<9`_f2rN+_CIyd;F^t&IX>k;h2Jv?% z$kdyo?U5MWcGJgrKS5iT9sqnSVLo}=w}hg9eAjAf$_rFZgo4rSvMX014u(LV8AR` zyRx0CH7a(jewJ%s3MjWhIOE}Z?a#p9E!M|)A!DU`EOy?od1FguUtgbYFk<~f)QhWR zF_Ve2J*lu@4z$g3_YpKs4gU)AP@WnsHNvsL{8T-}HTF3r-O5$V^|nb)s{wc3m)AEE z)-vvmItz0#=W8I|Rq4S+iCY>{j`>!aAfoDyqwnVm^`ZyzOrY=h!p(Fb z>Nnwxtm64gu=ZTa4P@F91cF)s4R6Gkn!)T1K$e$CNxXM-oSdEauaZ=s!MuzO>%b<4 zgWu3`=L7?jV@H3R;I~{z#|}frW{Ely^P)N{h;O45TXpr@AJ?S^8eV&1HBlm0jixj?kS z@JluA1bG5H0AV3Zl;DkUlD-n;tu88nONJ*2DSN=7T<~5b(1@fCuVwVBr za#os1Zn*PplO|96mca-LUzFpn>FW-Vj@(>dzlkTM%=y-Mbf;K|Xa;^DpT^-w_HwLx z3c5!EwE7=ZC6*$^tWX6x;Ud2BgppJ^1qF1_L{R=)APa;S#-xROI>?;W`q@XyI^Lk& zHVcji!mofZ;sQQVk&mo;UZn>=&=lEDi$N+0#pq4ezx1yjZ5a*JoYJ9bjv>6fy!2HJ z3^<9%?vJILInO1&no8$YRdH1S7v|37@>bNSC|^PrNW*7oQ$N4Fyc9AwX{uEbvdDQo zl537jgCcV!VeJkkyFZ49hna$cg5)f}z3Y$4TV{TnNYB?Ik9=BC7vZCW5EGHzK@AQF z#NKqhqSTN2%0Th?V3ZOFv6cZ75+!2g0c(e82?tQnhzzEry4p*@gOP|(&3 zlDLa7q9fHrWIUaJT2HmaRT0?Tk$I)(Mi2&h6mD$#4xoxu=((z0!$ETcN0X-I`uIC2 zK2D1R%r|h379PxH_9GKi|Pj|LyOLY74@Vc7K*4 ztK_h)k)WIF0>C(mg-jOX!sPh6vE5IjDba0#uS=g?^9BZOpVndjt9>mx`X5{6zVOFUp9^%u;%O zWqphI)cnJOk_g}8XW`Co2tALQiwg@21LAxM1_hLM!pK1VoMYEk+WsPF_jH>`iR+=th-yE;*O}u_JAZDZO+A=cH-kwLW7AsSj#Bmh zZf82ib=Rv`5yZ0XE_SapOJryLqtP#@`S{n3DX^#o`p`u939o z-OVd2U-oV`dgaz9_DsVDbdu*3^kaVi;;eYL95K=57_9WNO-JzBdT$S}J-7!?SY-ZT6MCfr6-{U$b>3Ma+$V~m5rZqO5*fAYo zF7anW>p^xT@QFrQVvbvEe3eaeE}&e+uo0haPzAEs)hfc8PX9|Av0>GII55rP7LsJE z#)eNun@V$>QDJUB?)m3Z5a8i>4==BUBtYS=p#}Ak-F2)snf!DBL{26o)l`7Hi`HWV z$=&G_-RFOgByJ6wOB`#cKXCL+q&teN zQ6;gF((`_%rl#UR^l~1|XV|Z~(SKv^0V7D8Ff#cap;$$5jXHL8Yx1C0&&q8c+u4azlF)q_C9!5v$|4HLq`ZB zf(uaM27)T(4W6V8uyqY;3afqp{{3GUC1Jo8;ph>aj0^??au?7ru{;V-g{U>EZ3!@4 zM;ax_(tyjsGy$`Z!aU17ZbW~oi+i`6!!7zy{_cTA23ipF+DWDl-k=sZ39WdHuG_~z zV3`yE5>$p2x}e%t4l`Y)h;+)BSZ82zhLu9W<-LUR!-qbUq&}}ck;d=0{9NCUlCU=T25da0p-a!Yo2fM7Bs6IGGMpP zE9)0@etw3NbVG_CyQ75p61q- z<2wm8_{MVt)lh0|zEed-g`d8|47jBuIx)WR3mAyKU{JAw1}Tcq8mJu)jmwe`X|n~V zsbrPp3wQ9aSKRLebg73o3PsQJC0K}`;EBtut9#Q?#Rr%+5=_wwzeST8qp=T~j;XTj zv0Nb6Zb;AD&3S^M;tuqdrjMqGxjyfdKX}RZ9X&aDU3&iIX+x=~h6K_TP%SVF-Ni2& zzf}O%i8H=|EBekSru%zvF+XI$;v2#s^6@k}I6Qp&X7Uk;=E(wcZ$=Zv3#b+a>!Um) zKt@3F5P*%{Fgn$>k-(T?PXe{jqH(3P?(1uy^ZHJ2@rZ$mKYKl;rIMQCz@Z!%9=KCS zA>BeJc*M_23It2qHWU@Ut!1&+00Os#l zbYK*#U_@rh9u9m1?q9VCDD5%=Ix52@9B@1*v&8qFGsNjT7zT&gC$HC9B{lQ>PYvab zo8h+-EBq=6?RO3mPFQGg+!rW{{T-_wZ~Jldwdzsk%ah6f$b0OpO^=#0=H@)H>Go#Q zB9IjOG?5TDkV2HE#ln^dlXVF0K0vW@E%l+D1DI(%fSF9tj@*D%H4Zme^(=z48?uzP!@0(#{?Z(*!#f3YN%16NAl1dVrrfw-@n<%|Af_~*1s|VIZVWsPM+|K>6 z@D%NOP|SVMXR=_f`hOEwKR^A~E|Bu&r8jgrSwMaS;ie9@)nP~+s-@Y`z5|RP10DRG zhiSqmRahRUyA)xys!syPqQXJf*51<)U)(%*=Mp!<6kzH5){(vAj-E1&Ry`KJfwv$| zBLf9GZU~f~lHE5rqYv4|jkH~fE(wrkdsMuK8O#MON@QVuz{%s!*x@+bRz2ge;SvNRU zvB=NMV>U=XIqYqAFgqm3#y3_yjaBtPW-fwSCyy;voP^dk^lT<@B}J5wS$r}}-R=lN%+A^8VpRwqU`u(dLsk#}$u<#WTTa~XkO zi!cOBN;{c+PxL#&E#KD2uZ-}PbExvARZoCqQ&i=B&>6?TQewUT)dup?U{V$C!Uo^O zDbupmbu#Wj)UoEc5W20p=y;7s!s|&3-xv1?gG(uZ0ki@x#oyiV$z1?P7o-P{((_p$ zo9#Ri>ka&V9pnvk55(2oPI>z$OM!4+#@XmqG01H@1(K0M`lx@!=bYow^Fc|1RQ zttlFmA_}uwFt+Jdo48oKuo?^!a?*Q#=aU+ds-c-527r(zlQ%F4`a!scs?bAuU*Hue z5xcv4O{6UVUK?D&zW8xI4QN-Di5!Z$EQl$a#?xIZEiWgx?}V`c8@GM1aTWkgB7h?u zyjn+jmCpDDO(;Ec7J~D-jVfq$0|$2pU4v=qnbTi=_(ZigC!l0yOEwe4D2(*SKlt*I zX7_^Xk-c(|4BwMeyxV}$&Ho+2Us;bQEti2UEa(JW_!GA0;aOnS)0)-I^=hR{eGnn9`U2@Ef7DzHy@Q4S91k^!z{pUPJxvJB>ySE zxQ|eaoXcxKmT0KMH$G&faE*)}G*y7w@q`iLQ#o<4D`|1nfkr-fL3}N;Vg#1}CQ&Tw zw-l;f5qlQm%nfo_ToJ3QPb-t`4VT=dg3&-XcicSh0A2^Q02CKz^q}xea3Il9Gqmn& z2mZgV!ngV7Q=U&=$|TkPI#cOtlPfwkG<)DByJ{!Dg1q+v{Udz@!CAZ+1P-nNt&=>= z9mbU4q$xBKxy*vCY1b@+Y>TgbvQWHGS>s;NoX*%y=DSz?4Pjr&89{uH;~E(Q>y*Xl zdcS$#Ej^zB6stQXCpq<)dFubn3*dH>Y(|z}MNH}dA{8Ml`b9mWsGiK-m>qt> zo2%%E69N=27TTdh>!mN#}_8R~n;>8^9^X^ojX6qz4#nxBB{u-MYAj(+3 zDR`Cgei=yo3VWGqLe)0<(N@qTSjA}Ge^=oOh}|8()s!|*7>Ndxws;;@JP5z2swsU? z%moOl)6VC5pUJU3puGctjtBvSa(&`rqvUC+1OTAG?Y2mz zXyqBhCOhYFrJ{f2dp-p<1H+~lnFil;cLF7Yf|FuiBXhmOT3kA(KIM#m2jMT9q_xLt zinL!MMwqSLHi@*5p7($D>{%B4qJBeyK-wZ~csaDe7i3N?f@MD~c!%}vfbxNLb!AtS z1ZS*Ty3Az(-!6=l%+GJv=rO?s`Jnc0;@9k{NZjl6*^R$p!8DXx^bW`}zk?I;gwCI_ zrqVlKR^q&~Bq9&|(yu&E|3JMiq5V|uTkrhxv7r%Y#(j`eGgduCk~wDSZZ9ZVrqUfC zgUI8{p)>6<0)}Z99@aB??6KVS^U_8b7-=F0m zkUTpOX-kqSIQQ^|`K#CLPQcJ;K<$ogu5>-Zh{h;_416A0ELENfc=zRSh z5rCn*8Cv-cQ*fiAe64$nkicJZouF><;pd4cJjc$Y>5lwh)A)Bp3pRb4FakbHNy~lT z5CFRet2V--kf{4bZHzBBn2&%8N zr!jtu3a|o2O7T0LJ*a)6$qv19Zjzi|6 zCz?Nl^9%!tm$%)f?otpq?xh{Z}$blh*1=o!@{doVQSw z?>M71-uu#Tp#oObF)-@TGa+F+V8OTn1BafrNO4^SbLQ2ENKC}yZ(ah?!#sQ-2tE;c zLGc!|AjTGxii>>|RI8~7o7DVy8xwb4G@^9C#Z`zef!{HH1HN|~zhzDhoPqo87S`l{ zFrU1-`2MHv=$IhJ`9W@Xs1Lr;B)9?}RV2)bQ{JQR0#OZDDTU9bt7*ztR*o5Cdpsex`2(HjCVea!ZbbN^P_lo~BIQkkfO*^kCZRR*$2LzJbq-4x(p zxpr>kf9d#+Q1jPL96DavG|%j`ivz7cxgx9hq$GdJ`Ho7QV)e$ZMYkbRxP%5{nr(lt zC%!tZc75vQHaaM6XwM$AAB)L2FP5K2NkK->ubMF#zvf{2Z9Prmx!X+)TO{2D7gd0Y znyM9sHo2tCRA;7r^d@mCJVVY&9LG$B;Ws|bZz6j#*wK1X*(h*0#vge6K% z{$FC7fnPz8UaT?+_R2tl_M%2F}_?&1+-q7BBu}2l+E?JUTKtj9qm&PuzohRsd8T$WWmc-&V zMuyP;o#lpccfJ9_-~~mT)NZUh85*)l|1pK2(*7scdV_uAMeTrZdWG1ua$eTQ$e^4c z1`96U`sb+K-{8KOF%72EN?#<|m5CR6B-EfCFm8P{0!8Z{b|$Z?8(1?i^cBCZ0B1NO z6RL=i_{@YxI;RvguKk3~WKtsRw0Kf1Q7+ooEJDVTG7|!doXt}t-Pf!s+!#cXMiL6C`(wl<)0l{w$32@xgccF&x!kY*S22HOXD=io{EGjF_z=;ey4UM8>3KlQAaFoRMwaI*=oxp)$d_=D6F!)PteH zO)2s0dU>%|qaTLrx$i^+m-ju7QRe_$=fue17D*CokV#2Hx?#X23yCe2;r7eAX_@PA zOg9exI8L9)OR{^jE!h-?$*T&U+ApN$a)}n(`hc?6+RF z*iO84o#-j71ToH(`8ZaYRyS&IJXw|1u(MrQnSV9z`ozoRne6cNByg=sv?yzP{Fjyo zbH+V1B^BEyE()7G%_>CFl|lGsZQXSXsQJVo3;3jPVBCajZEx}QX(ifab8=C`;&g?5 zlh~vKo=|Mwh8Hzqm}+UuOh(|^s`c-0hD1*MrN>q$dRiyFwBGm)C8w#^Y<(0d@R`>} zCM+8m$Vz>UQ}w&PPeUfWA?Iw9KN3jlR?+SgPs?D;lzSIxmo4l|V&iJ1{N6AZidjW< zCNa2>0u`;b8kiWSp_|1^(ic8KG8YXVg+^E~r+$61oxKE+Q2zBdFY%=g@?15(C zhwJb)Gz{%uSolLnO^urUAJ7htz9r0P`8^v)VPh|}Uyu@4XPXj6>@%&{k!|iey&^>I zn9*+tI-tRO^{wyu6kT%wXBBVD9NLnagMIwc9tDJ48Eu&+Kwnyxf-f#HtOJ-R0ay>Aj$! z04-9BFFvlWBD8zx#e>t>MPOeC$YM85rQ;D)4bpb@WN=6iQ1#;oYCH;0E=aRCsWxM5 zS@n#f@W+v-1qOP+`l;Yz?)!xu;5S8`>fp0X`kA zvz^d_x3iqE5U$v$r$h^hHrS-%n^?QyxUy_p!tbwZdAZwdEmylRFHQX%*(|$P#S%0x zub{%k=-hEJnatgy-jWjW_e_ocN+;9daMHt)lU@xKE%wuT#~%MU7Ey$9Bz0-qPVy?J zvs}0S6fi8r%LEhr>A#MK6}n{JiXtQpJ|v+_W>prrZDM!|*!x@81nS5LUWt6!I1c%9fT;NcLVOy9OI$79p-) zXRodyKR>5<`|X>nk?lzv6ytIsk@ll?UZm%z*3D z?%3B!v-MML&slSMv)gde@}#iHXXYwb0yqoVrz>iDmsj7>g)j>#f_lH0KevagqibzJ+m zzRZ2?n|~g5?k!BX@JGs*jTl9hXVbC#0;4&j$TietQ;y4pW#@>&=2P`8JW!gC7j;@M zc;`!B)zGltT+=B%yRHv$a(^kL%e}0rsS&Rj6Bhiiq9*k8r={1nkiaF|$^O6F7r!O0 z2$NLxT=ar3mXmKg`>HGivFj%+aO>go_Q(RS9czsjjgI-ZWQ&0l31btR74 z%50ae)$>M4F016mKAMw~IYwydZ|?pywRJJ{&Yd5pof>?X6VsZ})_A*}laGId$Yfsh z#a&$1@d`ID9{T-rY-|iJn$l^W^k(T%WMQ0nm&r-m^PF+}4PB1UpN9=hFcih{ZgUM=0Aq-*aELKTYe)?`Zk1Fc;NAcuZ~#3)ZI{2~`ocRgSjC zDBL1#7VB(07?buUsNb}#$K{C1E=#YmHFEXt_*@;H>tA*C+U|qG(9_AUWG&Aaa!PV0 zN7I*=%IS+f;p@&aJSAa_$bLC<(=P819cAxtM``#eF74ZO9ob`+j}?XD8#pIEOC+03 z<6NFT(H(TB?|d!wC?qe`l!lBffQ(#gCoC^SkW^VKS9JR;N1q9loi`kslxPc0i8ZTM zt+Qxi@(-)Bu$ntGiJ&uvQgU;1{H9UY^0tEnxZ||P%iMeO6)PUlbnLp`3h&s|T%S5^ z>nmMzMv}nVj{qH7>;^|YWzM)Ix>}ALn4WZqd?eRJH!F!MR>1RTtaTk(SiR!Ce(?Jw zm<;L23c2F)3-Px!dg4zT@+PWR-^b0t>C1-PHk#kkGLS5}?C2+ED#LRwI|=n9D?+oh zqLgRFoWpdUvf%LB#Ut(nsal(cE#w^#F@HTEk z!YFlXL!!VyO_rr6W3({S)t8c!o&7sV=&8k*+Da*}dz;V7u^+q%Ez!8srB7DsTfc=e zuX|a9YM)~^l?axPk%Qx4(WcEENzc}*Eo;P`sb!RKX0ZGOg>p~mFb%a7F%!9nQ6RUU z|2JsgIfCQX&yFGVPm@KT{#?#e_nVklYj;3co@uk|3a-Vkc!As2u$glA3&+2%b^$;y zmdRY}Fzh<={btv5j38>^iT&vI@hWZ^FI%-aXOzG>QPH*=!{;zF=M0A`parElg10Kx z*om4c5f&JVAND{0TIH~H8?xtbEixU~h?o@8HtSx%*KLW9QWAPMx_p0`$6pj=<^)~b z$wRZ4PbUVw0vc>g6^ic>5VTjigM*|#t`DSkr*a$f^I)Kc$)uZNMl((myY+E4*hGb8v{DFzR4SfnkjBS*Q!Z< ziNf)i8F9m*LS!!6So-24fq$N9L*Dh3W`2#lCG@mfsjl(9*R?ISSNL6#Zhkn1GALoV zsuNj=qh)S{?GQ{i&j>^DS@q@ESWY>;zgO2HRey%i=|LmEc9Btd=&H9RA@C#zXBt(N z6pP9XbF4PO);4rvo~6Bc|NcUd2q&Zf>=&H3Enk1EuyJzK}mVLAT)yjeOavrW$X z*oV$v+^r+2wqgI{uym4iBp`3kCzdPb$G07lYP3-#E(aQCS@SQ0jX@6$Ym8D2?5gD8 zBvQrq72M+snoeDqLQ>x}8KB?o+*0p!fj@O zdH#0mA=&Anu0+SLM>;z@nTwI=N2S}Yg$rxN*ZypU!Z3sBXHFi^s<<3Hh)8~8RbKA| zL%o(%?HGN+CD1iAXLF_>_w3yqM!~YCnXIT9@iTUYp&Jn0cE{%&N^W5D-ivq%`R+`i z;q9G&L!bmF;v%tkv-P-g?3$9?%;}oe1_>CW;d0VI_>P5zpVar&u)9Kh-j3lu(#sD8 zO6P|0kcSc(-j3S}0?|hr)&gP!A~>Z$p0?`E;{NZCxlNNpK z>T(vJfYfHottf}yxmEdP`h+gKN=BiqalkynPn^|$Mo?javKAe&iqo#Xq!!)8?Gm?J!$m26fElTgvD1OyY<}%-f?1=9YwlZ>}4_nDzFa}mhB@8 z4PMMfx~+r`L{uy2#n}!gNEFB{-xBEBpyDQ6FE1C!*!^(8%r-%rqH!HglhotcS*A99 z*9}a%#J2E@|3;%0<8Y;Mya@7XSxjNm;na>Z3RcR$<}SlHueRwVZW$i#&}KgFKBwH$ zxSrZoWsGZe=A)lp;U+>)6=kK)y{lE?7KJolhLbn||Lh4sUapT+!7=u9``IM?e|Vawy6H!%eMujwmQD|v4|ls!CO(!ORS+TuicGi zr%Ts17R#9$lZIVaXyr*<0wk3QI+j)^5>dZ8YOYcjuibamn>-Ww_Pftc@5cVK+_rnu z!hpC3PyLNY1c?|-Oq0pOy3))40=PvONp6-HlwJO(=;E@BfFLCpCVqRpnW+Q|uv$m7 zTXsFf-B61*#30=)l~F7DGBYY@y!)Rc7iC=MBxXkK>xgo_=812XcwqGJ+p#+R(*~!W z{ygcJ>0;xqFE?N-eoZYyWQ+NMB=jy+mN@nYRwb`B-ir8L!6nwIY*@W5l^H;4q{`Be7 z6mo0iMke3R4Stonyy@5xt9`HV7nuQ)L3LaLMRoo!Hn{~B$9ng)mA4}DBnCG`{cb!O z@K4)B!lZ6#TMk>>I;)%`ZBvEmUk6+~erF^RPgq#3>;H}xpv&`?3BB496ma^PvCJp1 zcv`Cbfq|}T7okMQcE5^VI=g6TU2{UCBgElYWNs-(pnIJ@#q#iJR`B%lHnQAoQH6K7 zxa+^7TVCaTr~oK_1RM~F=_o4)JxV&hN-7lTUYCYpTCtVBtiO9}4L%3uzmJ}p@b)r( z`~IIM75}VF30U>*8eU+JmtAhIUwg#vkTD>LPxj|xTHG3^2HUQGD@|Hdu}f8|8->Cc3z#c-6U#Hx)6;_^ z+q3D=`89UFT(7>pox)~`MY#~Rqou*^exAasxZ9JwW_s_I^+(@kAK7}Xp4wxO`|oKIzj{s&}ulfT@y7OI@m= z<)*qouP?c4Ixf3(*-Z*I9Hi*C*-#$RJ|ggqvSu7E{po$upvCB0o%oX#xmt-o6}&zd ze$!br#jMEK-J9@RK~2yJ8(p)#Hm&4+eA46n&60Rafv%-u8#I@TjGb2#yel(?_wD-` zlCM>ldaOpc##y^&C`|wK)1TQnv96QViH9-z=brxj%Q2JSZ^3h?5U9heM;m;{YqgTz zbXN#@#*Q-JYv?Gv9Wx3jndXhQ*KfwwO$k~*HR`&3kV%7r7JA*>Hu=7sYr|naalu8m z_TpsN@;HkHbg_HGSA>9JIv(B~kh!@~-aT#6MRcut^Mj$&?^?RHt)5!*g6;S;A%R}u zo@t}g+q|=9@>e%s`kA%=cNbtiu7%0Uo$On6IWuUwezCvx_N54eoLQ}j_jZOqmuE2B z-}>;X4Q1Kzr~rZL#YaiwS2}DhH)F^msgZAzKHhFAznssq>T)f_gi@{8N4^$ept}zM zP&P$xTqU+mvGg$P_DW|5)vQfNfr{HAW$q1OZ{OVd>fiDr#3n{^-!!j1oOM#5TFWgx z)J;I8Ilx+3MXzXX{p_BuPP9S!@4lGCk`|!-MJz3EHQngy8}^g$rY|*pz2QTc2#PH1 zXvOZ@-xboA=)ID(7~40^8SG;>!AIMSjEuI$MMYiKu6;j^sd8Lcd~Yh!4e)%IM*)2^J4n7`#jE1M!&N$y0uGp zaA3;9nuaUOKG#9F8BrD(_4T(3qTRnZc%;uX)6)%TOgEbo$BG(0_6=Y*?IpSn?TH-; zg4S%k4?UANtZN1FyJ2%oU8?Pm6i)I zjD1!Hl5ni^SGi2)M$5C7IGNtso%AzD+X9>ohnN$5td62Rp9LR|HcDpZnL@_qv(oK0 zn=>olhf{3jU>I=6X6crIN*NTk#(u7uVvq|ZKA!0wQu%CiB76L0kz6fDoj}IDC#^q= z1+GItZiSHMUbm=-Mp5^5x)6|tbd9_k?0TkA@%kn_PrX0-heDKfre{aeoBPgPR%0rZ zNOWsSW4OV0M$ir}e5qLrZq1{kknERB-b!{ut;tihw*u^xg=5>h6}KbLMt67#t95+8 zzp&x(p|u3L_qseJc~L{n;Npo+?|Y8hPilj?SaO$jAdpHgzy@Ak)hPdv9b*vU=e1Y1 zj;k;Wlg?@452@(9o{Zche);mHY7HIJq94JjaqxejKk%(@{!`<7W}S^(@6)w&s&x?! z_0umr$4yOO@!!AL^j+EgCn@8W>&0bx8LyNz{OonIhKXrHA?VkOsx$xgC|tzTr6ISQ zflR&Y#jDzwGj7`5-5qCdCn;BMHhhGpJ;nO1h8n4)2N!yt?q0u$(Uyk~LewF$M!BVm z0n?eE`ev%s@cLH6oq3Z}tSz9E%S&!m*a2l@M^YEE zHXm8Vu0Ncg#h@$QwPuSY^o)kD$qdw0Wo*)A?2d9lVF!K4%38Irze*kVC#9Gu#~jG3 zpk`#tVVZ}TUc-~1M70KE~anVsqtd=LO$n^!`&+a@y&VDmy+Hr zX8y%9o#8pIh0N7&Sf*~)s%+^TTY}tfKdQnU&1~odEvUORa_^s(h~|gZIr;hf{QXmt z;rgXJr`(eCzC~LJJvD|!nIx>`b$|Y>u;x{WK6CgZvcGYfH6holO-p`0fBHRBTHcQg zCv8%(B_Dm}F*B0OMG|eU!_hW!k$YAGDx}4_d}X^FKspA5Cxb4fJQjzpS^%+r7#6Lr zHlJaF-FmFM=bY)8<+I(OMoIzow&cIy$ahzWT~KmqVk>9-iDTyU@cb>vyGj6DDPGl& z!;>7=k2xrTWqjoZZ&f9+tn&&Sj55&}&vA)0bXbeNijGpsT-w>+FG$gejcljNKQ3Lm z)RH^Cyt2>cC==Yyid(<^zM_vQ{5o~^@W*rR%iC2I-+fYTlu0`ZYiu`(F0O{MF)BC_ zQb_-|%VG74Fv4G4?CH;VQ`jL$UEBNl?JUrBWMH8mgL`cAxf?vZ!uLQ1JoV>6n1F$J zv&V@Ad;P0%Ejhf9=CUp4IennKO4FfN#fu;ELG(UNJMFB;#^CKH@##vj&_5nWlx1^i zK5OB`3OyZM4K69HzuWorC6P!}k)Tafk*BN8N$K;{@C$!DUcA4seJsu#L#gweckE~A z8ob6X*UI%eT;saxb_+w{#h|CByu1dbrTHLJz~{IjAv!ZPvfwNrdo#C`{4&%wVQtHL z@kNl}CHX|96FWWt7_1g;m)l*cM|D_jT(7FJ$f!ta641>dRa|m^0(4vgd>HF8TmXm1 z12NrHsmuBshH*35L*URV(Vk}v2dVBQh1M0{*D^iF9lgTuB-~(_U>TCi%ozQ`k(kbD zgG*jTS+C!WJN*??`}_jrorBkQd1fijXW@c8WJxBeWznw?kT*Wv$ams|(&fV+k`~tRi|6AmAzwY0yV~&vgtX1W zY}h_mc#8ENQ@fd=3MaoF=$+3k$pWg(ZKd<&hK_8?TqiK;vRlXzDV_Sx)uYwRh%$Y( zD_3eON^ay$_B|h8lmICi2&3la9;{%umI3+TPKjhY_B$JT4^C(9tEG17Jyb&y2_e3sjacT-JbrFu<+UyOrZa4Tro@ zgb8Jr9-Fr(h1H+`=kD)-HFRc)-h$@luqu3<=_dx@=92109Z3|R%bQBwikudMx7cOD z;^Jaq)1%ywXX&2f;u0>?Q<;mqHKKgH5Bu*RQ2~2 zVzt;QYiM|GDJ}^+xk&w*Icad#pv5ZNk!k|LR~JCODx$vyw`{fXK$;~}=D49JHPn*9 zi&avoyYyBUh9N;+w7QiawHSoN#O$L$=Na0ct43`Rs7mu8GzW-uR|oA>--?=Y?rvu8 z0_-j}9fG_P+%KEozU%oP$euv7800EH49N7$Noz0asiBh;3gr<-K}OM*157~-0>4cM z>cw*St4M;F$l;HZ#g`|b%fYa$Bi90_fBg6%t`RVkUlzArpE9c{M%;)ISJ5#Wwu~$k zmyuS=i#~1}(Ghk3{!)ot?{F2=g{yD%>dv_e`+=~aqrDYjiF2|hFfNErz~|`1oSOgW zJRAmmbEh}*-!M!=#u?t}tdsowMXLJxY=0PUg!cXakG=N{YbyQP#bZTBg_*GpLvu8M zNR=wxGNPL*MUajP0i?Ge9d$-VMbI633rbVzT?kDPnb1O!8bT}}AP|%)HD_(q_dTEf zU;giP&UKyZx4$TmJp0*CTWj5G?fbrVdvR7sSQtAre?np_R`PEhdVU;1bJ3Uy-r@td z-zoVrdt3MqjXTKDYe#r<4L=GHOc%_K<9@F@_MT-TUz<-+9{s&;^96`YhP3V|bZ>M9Q=SZFc^c##40(n%DivNYT5GCDJXFSb2Q=o9SO2W9;%X zuh&Sif~P;y3B({%(^PKu0lyS>S2aV$7($8f9E0%zkV&$5-R;K8AqcEg!GdL+|J5^{v{hq3GH1vq|h= z#pWUfr@s%<7;E=oP75b_asFZPrBw*It03k z`%c(<__A#iGV|MKT7SA!I2dHv?6NQ@K?@JLcjLwlx-#DmoT}^ViCD_Cf$`5c2QL=Y zKBrp*%og64{X9LGzrP#+Ks0ll+w5I~7tTSLHcK~4=y~$n>Q)nkBgSqzdhW0c<S=l%K zxvz-*cClvkTbo*5{>s9&Uu_X{a!hcNbZc<|$ie<%cK0j*R{EV+OO_=xnU@J<$Un@Y zLQR}qql8s!+2X>Yn>n7v8d{0mGMczKK^Z5$Hv~g#+=bgcG}GNxmLmWQ{GD#!=&|a{ zTDL%Wnt-Q4L2LOum`G}1mceHn}+KXt-zg2H-n#%waJAX>*st0dbI_|>nGTG&WA7u_C zxHK0{ilQ|Ja8|*>azM@@N|!pVJ`L4WLIft{TietUtRySz-T$#QvD|ySVpFQy)>8#T zL9bPE$9L|;eY~+*31=hMM8YqXrdw+*e>O4~-(6n{ZjReR5;-oePyWP-6HrI4aBrl) zuyQabb8}_=|$y1~CeufEM zUgZ)2j7xc@qZu(gMfze?)kGPkyhdXan*MYX-I~0NroVs`NHYNJ|H2_v>rIN+F~<4;#U(gyW87$6!sYod@J0( zPo^>57h8r|JRd&fv_*6`w&Zy&)@Qm=RyNsvd@%#&k8#xTYQJLW$S{ke#Nth5-m4R; zPTt;g3U>B5<6A1Ud^gii^EK$^LcBcD`O32=!F11*w21rn#pzcU??Gx0mK-isJ+6O~ zc)4OP?m*}-gHZlHCJG*0^Hf-L^fnyvc6{sgHAu>S(rw&a=gIT?@0A(`vu62D?@y?K z6~N(avRY2`I#kDOwsFN)1FqeqW%6YVo$H~IIQT$f#yXu3F>_~q!QcR{Jx1JIUaRtP zg*a{YY7+unLByA-6!of#KXzA7L9}i0AxKcH!9=e{)RPx!!5VQrBBN% z#P#nKwA&PV)?;y0mMLHCrj;NDeLIh~OgdqH^twUY)08V6FX z0Y$>$PBJ|f^~z*b@7$x{me1xID_`ooiiHz~;G%|7-b~Ez!ZY5yv5nRo8L=CI=ih}T zE+L4MFZTcsju)&m4mX!9)?D+4<5fdL!5udt4CTNbc*$Us2`Q0GKyLlud!a%V>3XsX z&sTPV4VRCKf*XsS{CO+5X~z1#1XH4`sb6R?mY2cd)*LK4DP{vH0uVge{k17{38LKd zzU&ohU43_bSj?|Ga5%`W zu5jS@=s;)3>gwv^1qqv%4;(y*O?|Aq+fY?Q%Q_`v>5&I-?X#$pxPmQUL3BHR5pQKb zjh9i~lbp;m)=*+tTuaG`B4rBwPE0{xgfUaWcElcryQ&uojta;tULT@WBHOnZw z`&?XqBKVh+fHe*28w;f}zuY*84Wskv&YftPTk*nK;3xRNJ;?ZTmEAt%m|a6C+#-HX2;yKmPR z7No*3^mfWt4>I(e9IYl;qtMY%gVUSpqK@8;h?)~eN@MauARBY{*Tb9Y0!Ii77D$Mr ztM?+QUMjE{FDeYH`9V6&78~+Rq!KMJN_@3^a}hae->yr)fDOdqQm5@8p@5Jb9EZ9X zlK+6GYiGMT^yu9bvGFjJ=rq3kvsU?*F%AS>?PrjML|j}IiVa~OMG@MF@NG*tQzPI^ zJ&Y_mxcV*@lkk4#NMY#yTN~TOc(Y#D+%~iggL!}PWgA0^Tf{Ln$`)sw_DE_s6F;7f zzK^N#0;?7KtMsP2$F`=#JL$C-3w_!wTPFMU_gPA-s8oe0QgOIT(c57(r{1*8mWl^4 zsYR1y{0Jj*TaMVq2o)G;XF4t~qBUN^zOPOtgfgByXuY^fS(FkJIU5b+0rC0 z%8GrbY*0+!BJW8u_=$9s(E4ZWTpff5*+=hM2@}$`Ku8Kp=h)rHWJJlbSa@erV&-_) z8|k-u>fVF11-wd{(rOp~WZNXxoN1kWfAnq*1d;j-&h0jKyXrq**58+WaO;b0DCe~) zg<@ZTPIx^|?K(+@BrgwZ{REO|R{0EF2S947*x2nkviD_mtgjH*Vj_;?GKijZF&UzuE~(vm&y2HIywwkfM%!G! ze!W&|H(MOMw${nRNTicjpRq4H43AieP$|5>;9`to><&^^w%{!XGXo@L0(|$K4FTVC z3&doXkXx1!J8*S(FTg>=S^s$i#{Jm1J-V*ZAa|eeH2oj|LWc{R_7|j^v5Pn1G!LBZ zFh#BU-gx^1Vy7 zXFHq(lZ70gcb#IXT_dOy7qf33dM-qpg$TR#SXtjYFIe6U6|dXhRJ>MW1*fKSWVb#u z7RUSpzj^<)XA-tsjgxy+e}(NCy8kMeF*AeIQs|*x$n;x+%nA*TE(t>NmP_$MP)b3AN2AI8e!pC6d4k9h-~Ug# za6-$gSoaXY~ zbn4O|t>yV!E?g*7u#NhS-Dd?GBxJ5+I4%e4t8m2Zm%+}A0<&;fMrz13ICL)v3t~u! zpkpm(BW+@{RA@Afp)4Vza#5CToHA;k<>+sUg|f7`fq^kcEJg=dpq|0*Y2km|)=ZJ9 z+kp#xY0=9cEIDq@TJINYmiT3we6si3X1MkN@W5l^1_;2QDW`tsg>s9v*2$AdKxIH{ zi>pbYvkY$VBda%||4F(z;7f;g#ewx11Eg)^ke7jeQSkw+{^|KC-U{{*RIEuc?--otZCgdfGGs< zK}8T#;BcbaG2mR{*HR}B!B2Ikr8@V*zdx>xFZ}r7&K7y|NIe$`_CZ2a`^u- z2*?&Yun?(Y9=y{M<5Ir0k(BAH1UX-UAS6xc=vqUO_t)3IKT+YYDPC`KYY1 zC-}VIu4QaV);+^)o^^(S-_7(!s2R+nw>rOGv>Ii(xSi9N6&W8zYmzg^xdgi@{NQnI zT%l^1BUfSVbnH03(`n*TdkZ;~ zaC0eDBl5SBiKluPNU;%d0`~F05-dD>3(_7-@JQ?ZV?}roP z!EoBEnG2<^@&=j@*6pEwBMnk+owu4f4U3*pY7a+z(BtCbVrETB1vTMw9bFw{e@_FC z`FjImdpEw{l2aO5lR0%GPHSJ|7w~{>k$StZ@%^k|GT7rUCnCrfh%svWkY}v9DZN`{)esU!02!vx?*|64UWk|Hiwkc1b_<-1>BdyY;gR(#gkFX6i^rlrG&OZeK0c~+vGbi5 zZxNND*H$zc6@5v??fApYaqu>SZpQ~*j`*P6xe=9_zgUirSFKzsqgY?UqN9zgZsrjN zeE-X!xjFi4ikw>h6H%qrESAnP(U*okBdmw~1^12i(TFOt-SZU<=+xFY$)zYq{37!S^Y(o)Kq)AKLZb zfid8r9C+3UX>dzK_^H<~Yplz^)jYrVa9Q)`tu+1P<{<<3G0TrdU*E16F4$FLr(kS^ z$0IT`H~EHGnfm$nfBpJZOEA~1*PfsN-RS26tD%HScWV+YtgCb`(KOZa-bN@cku&#KHe0{_^iaA4vkz= z&9=%XOO9XVtGsn+huN-%Y%74*A9_b-3c1PtP8P!=sg29V53ElpfAr{*vY?K<90R;K z!{(;0dowB_W$7eZ_dRUI@-ux^#6`*Ndm=|nzOuw{(hsJEhCZ5&kQc#rLBnRKg6$PD}Y z@>eBf(HRSh0I&SsQ2RD)2S9-4Bxt9j(+&I5(I?KQI^oT=(y+w-1Y!_`sYlQmiF2QL zVC+tJ+D$FDOnyOgD0lqzO3i})im!f_v7`k)f`R6t?@gXG!9YuXz?&8V5I0vxHKpD4 zGEM(>X~EMvgyqq}Cy1@f@c+?2;(7#~|U9NJ)_toSqA26wa``bed0;GlO6EOuSePn-U zKJbo=SuiXTqf~^S{N7k73tQLKZaEzeDuxEt8Ee%51>}dHw8Lr~l}aadR9jmlraY5^ z<^C9-A@Tt@+&Lmv{TLuy6G1*k=lTewDy%gQeQ)igFE+DkQfg|!$rN&GyiE2ML;$i0 za;0q-^M2FuGCGG9HOSxYTR8r>pVip|5sf3%cse{gCERg`LW5;b(OEjI_76 z&uZ=bv9rgNuw^I=+3BM6z2*t64BC$R&jI@Trc5>Rq@S-?@m0D;%MP`QHK!kYni(J9 zPV25Y>X*Xodz9_7G_xO8nJ{G~8jWyT@}l>1;Z)KJuYJM3>en1N6m)nSv$VCfS2a4Ds<_x0e#8Q&9Y z4px$u_Iw3aGoG-JBOk^~AWS<#Iu6hj69Vxe#X5O(Ne*@8=I0+8oNCd^=y3ScFGcTQ zhoylPA!UEMpUulkC@zv1zvb3nbXIFEZc1BMmy_dEL0*RguML3%QEFjCJ}hbE^`$!y zvf#)nwBrKsWaAn$#dc}r{fG$HsJTffCiuv**Q~TotUrcExGx^Ti|n}Da85`_NmtEE zGX(Wsvlh^#s7%1N|1n6F=IY#_)1c3s}YmozZrqm!J%*`ef%lE&pXF z!D`C*f}~*e*-m9aRU?BZSM+9s=R&$de&gj0oYWMRw>Pa_FaGhgm4B;3ly)g@7rlgW zX#4=OA6fk5ibXIRSAh|R%q&O5%MFxLR%{NY1b1-`e2}oc^y__%t4|D>fCAep{8wA; zyEZ8_v9W!CRuEJ z5zT|5lQkQJc9A+=4=F1;Ycy_jNnG&N57#i&d!t+S*ROwlU07HqH*;ur{h4AhiZeHP z{T#|KGv7TakC2@mDd#)81Q~{%j^aTI=PNIE{-Gt{F~r}V*U{oS>G{Jk#`$m7dJY5G zmZ_6irde5WX7Nny(zs;QoX~!mrU|s{{PLr86J+3xC$yO#J*SHBWJNHKjyE6s>65Q+ zX{ki4T3Ovf!*A$ZDv^&s9Qjp6?Z@Z^g~4(S4fd%>4=9xf003Wou9*_Hm|~8*)QNO`FHz?k#_VCVbvI)`YRh_|C7BYU-dxmGnGAU4#uaMyVz)QI*#nh66GFb~S!aCZ zcHAt_H7zCtnVgv~0Oxd|MQJKXZJcHABlq)<=TW^4E?#OrV2+m&U+=M+UPxF3HPWQ!pQpne7X;!eo< zbOg3vA(0w8)k%9%21>FHbB(-M4@5YjZO@=&%S{FhkmpSM1uKcF8Xc>x!^jvfN4_g@;jEzpguV=xTe$f&ku6#cKc(GAu2xLU9`b~e#-I&}Yy!CtO zju2$7YZauV3OZUMqGT@+Q?1^zdY`W}1CHzWzkT{_3jn4$4&aZBvxF1-JaRcO|S$B!bX`u!?jw0vT%FF~_7kh&yE0_TpbV@DVsg< zimj+uDg5-AEy4e{+s*DCxJ{e3+3vew>D+5c(=l-?GKd0&(O4epB)RLdIg6V4Nz^LRgzfg$Hs$et@Hge zJ|#gCKI>S#Zf1>7+Ycl2Kl?!cY3)BF@c;SICt$Ap1^ycNE zcD&!nz?wYuh<)7m!1Qg-n-(lvzHv=%2M6Zcg_R$EyUwGNi9R^pXL!H!u3t}up~H{% zzOE%`n@du~Nn(QIIi-6@fwBl&RysL$7|1%~hA*L#LQ8YEtAv}syDkNy(WV@4)8Qri z!Qno*c`qv#AF1U@3%|?wVEp?NWa#1WA}P>y@2I*Y^(sl_Fm?5IO^Ei)<5FM%p{RYg zdv$sCI~R)$sZaWXvb5LvWATeRGfoIA@b2uC*32wYBdj2iB1|yy( z;Gl1L!bI$;kg>|L-Ux2G?uo{OBwp>Jqz-gq7q|F$@V(M?SCp(X^8ty_KGC=+SkYVA zcn%FbnwIgFg0K=gW3vp*a&m3M8CntD-6*R6!>f zAgpADa|6{Ovu$3cp9y@CNS?XE$CGH5P{m56Jm%tVTmg3l2Wh%;R5tbN`=vYUi-eNE zm7R+TQVW|Z)<=hnkrWco0UBvI0Z(glD8pQLxav}DcP@I>-vDu%&SnR$S@0VtYT2>Qg@BXQ4gh!FtpHJ zLP?{4?J7U;J>O%q=s*C{PSGrWl%7jbe|jC%cZOb7sMWI8ll6`-WXpp<)!vz?ab&Df1pNYCSG{Cnhwo(l`+Y+cWcP0gntm=#ZE#u)QKC+e zR<+P>pQ~2I3-i?oe-)AKfz%Lkr`*v*;R=#b;&l(6-uYN4fQyt?woulG6eOZkYa$KBaA zGc+q-m0xISh!p<4fxe5d?tH6+sRF~dW!i+73^W=RBz4Eslk`umPRsjEIiahkHH!O$ zlcy^XwSv6dTB_Igl{WcPj62iZDrFeh{AFOvCXqYVKTsXEFZr{hh8tzfT-S7w12V_{ z3OPolpuDXP+iv!1p9oHqv^R>X4MHix6?m#9sweChfF9u%-xKmOwrsBD+kD^%Ex)py zv+MXSSP)$Dt*C)nbz_WQ`2I~g6~3u~%uFD8 zx}ImzY}6vrR*jm$ExtFTqw))gms~Y$`;M5nYwT<9zk83QGPdt(&4XcutOwsG%EsLE zWpe8iWZiLU0-udok%#S3-Xx8q-xtf2tfQXOZ=*NyzBC7+WgRpr*7m`07c!JQT-lHL znE(6L76&0>u}m$nVeW5?6sWavb#*Otp##~{Akiw-F`?dt&hMH)kOG2Q8V4x02%4MtY{GK(w}n)>&{x`&nz!np z%}%+o@M%3D$ff`xuxrnw@1M0B(BjyVv`Yy%9Mwx*R!}^p^mxgv)`Hwokplbv+CZkGRps;NUqekfzU}=u?2L0J0WT#v(=o-` zY07ovx!HtIM%0Kw)59{CNN1CjOvjJca;xzxq(NDv-!`SeY+@Eu#sOOLSokaBS5U_kYk?@&PZ9Z273FCsGI9s_G!NPv zsnk9k85zk29`O*-j6l8Id7Z4^*3)1ne(Cyt7D;J=InK(LffX}|pCxUNGFX2O?1pq$ zChH;}2TDp$FL#ktl&Kx0-D{E9%p@8B)f`-**a|$M1GHi)PmkH?eTiKkvJT=9=>wCmARy(XjQ^@Vpi`W!$BcJ~I zLr=Ri`3nA9=bi%2-uDEM2kA| zZB=PQNnhOoSfPD8E#;_QB;Ld;NqmLC(f1h7(Kz32Ccsmx{;l!i2b*`)^?=k{-SY^u zi9~35B{RwX94|0q1C?2b&R9))*LdKX(UxxwD}a^}`OOrOE040q%8{A!fe|-vpO|OG z+FrK6sAsh@6AAXfps1c-YNe0|@>_L|qu;*j`Xs98!EoIjbCC>%59b3?upYiKlN9I$ z2LG=!Gcz1n$@XE8=ldwPclkAI(>Fs}5DO#h+}a!A1nj_<2To-^a-l2ej8&HOPB5Gk zzDMuG1ZeAHt8hj4Up2mZGXItU(~&63%h%gmHZ_&W`^_ZSoWok`1p47znRm=q;1UH1%NWdxSkNr9kVNVV3Wsjv6jVQG_Z0MnLkHnHw8l@WEMt4&%bBkJAr1+$5l zCExMQN&GhN&{omC0~1Du+NSifsT`Sa>qEP~#+2iPIWXS~h-Rp`_b8sA0HI;5K@1`J zYNSK)n!vA>eqj6=0zykK<;fwE&!wnm5d%#>ZJ=nS6RlHwmL)Ty5?yB%l`GZ*Oh|#A z%Crzp3ZD9YU@Z&dt7p~8)hJOd=w;a%QNg+M?J#dXr9D@b-NkXCI@zT$22H?BH>)M0 zOOaUGvM-&^Oj(3&9DMW>*-oHOn{D?sDiQ_NX- zj#o>XNS&X$;KVS|R6MwAY!||bM{?&+q7=As-jmXyAda?xm+>u6fESnxnJL8Q>v(qI z7hA{Vxbc4WsGiP=GJJ(0+T0V7jpS(qUD-JWk6a2NH!f+o9vPyzPMQc-oYPRBHOXNJ z#hWYBreux<3+T+eD5V>l7>S+LW&W zg48c&*$M@^k9w9r0$p*760DFq4OqzqehPXs?RZ8hy|#5vNbLGal&LjycTXeZIF*L4 z=#TTViXDz61rFnTD|OJ2;zyuuQYA|zNgpdAe^y1-k5SpmAI*IAW}?D>`pRP&KWyUZ znwJ9*WU`RU8hDs>{8-Vh`JxY``XKCqM9NmDgM7D zJxoK|5`F$reN0%{<>m{_*0PAE$cLCgwTX>IrxuF`={9?#bcS(8)T!K3O7dt`n)GOobW{N6U9DHG8L3n%ZO}l@WbByUK^|LvBq*z9Fh`hJi$TQO-hfN z>A_FahdmOzOI%iRGot=B(9G}gCz(w&WJE2I_>7#UKn|jpyIO+&WoY7ev|5j!22sUNBDRAQoY4kWsuK|AxgYon5(M@3;F3HJt z0reC2p#0vg`AOXgQQz~P?Bi2FRQS(Puk(i|zhXSochRI3~<7PWmS40D2!^N<9& zY0te;>XQpA3*kSF@x)%MJ(gD8I33dwKAULkGW|Jx;TJuP;@-xk>#mm$>1nKxnWOuH z4(2;iE~4hbib=zXy{d(0;wa!%<8+jUTA_tI&UO&azYg_Ngxe)YnD zQ&#jInDaD{%uq?Yi1Z7=N>5a96q+cBiQ_NlBBE8tl`oxiOUQicGij(EYrhcedV1wi zX+Dqrd8Q(@i)7)6dMyZ*gg9!`XM~my^p-NNOidW*uAREsU^qt`_yX+RZTM;JnJPF_ z>7Y`jDwoE+&SSketwx;etH#Ji!Kx5x5gfQSwPaxC4R8{8#WU)Hq{x7LQlhOKvi+8a z@@F{tz8&_RpFVxk>>9kTTyN%Nulb8w%y7fi0d<*77rM5YZgrIOAa#P}nQi_Xo$3%d zJ1diLXFU&ZlAnAvZa4y|kt3=9(~&YfC_KS4T8yl(f)D(>!K>}f!z1U^Qic(5K@~Hi z?Cnd8*vq{$Wk4h=4i1v1pWl*>47?37>3`7b`n$i+Me?sTn@y~}_6{ik;XDf~tD(tb zs?fp7%h=G#KDDvXR1ATxk@zHHB7u3;eQ@`jS@yVmqE~GA-BHk*Eg5|NHMq!hoIdg@ zeCeKyS+0%UPrXUcV5BPW>Q!KeDIj5ir`k1SMDE~X&x0y;eO zU^s=RGD6U=2MBkgOIM%+Nn2c1qJIr7yq0UC<1j4_a*4JBewi6P{u4W=z%scGze>zq z@%q4(#}KC;$$aq63sH;eP)pIH&9CIUd7Gm7iKkQeii?V7VqmTUfY5r65!^qud3~UFvA=e>LcHn)%u>9&AOJ$e0CjDIPNUzEqpdk5HS&X zc(g>gG-nbK*DBMm{2+l-9^oXJ5jfNS=nUrO9Q=AoV_UzZYax4@WbshHWBGCT-A@9o z4%@%B3iEmuIVHO?AuuPRiTDaHv;p5p3RI+y_Rb{ffS%fQO^B2H&~wQSVi|+AAfkhL zs&2RYaiQD^;5i4O%)a)(ZrDTR{ED8hH05AaMy0^d5I>qxRot^2ciggk(pzZ}v>&G9 z{Gaf7erY%;3BD>v_=FREA;&Mpe6B%TB8B`ciZGv7kr(u4r?u|Pf?>F#c?o#K zU%=;!I-w9;fY9ELt`CD%S;AfKJd-vO+lv?!5 z`sEY6YN84jL%|Rav((#;a^j@604?{T-prl}IpAelKp9HChFJY0#2^w}7-6FtvLXWP==l z{@YXNGBnp0z2JOxIgCF9?KDzS5ZZ-D}*xP%4Tm;RZ+IWIcpDPyP8#x6vVDq%ta*PWnr3z8dJET&<`4gL(gO#fl zC{M+|w{Jpm)KmIo-Fzu^bDO?c?ye2{#e682e%I17Y>hEi_3X<2oq{jOrq26IGSD zSQ}_obRn;M@HB{-Llkn|rM9i%r>&U4F}xC9gu``pXnC&8?}1h1mZFcvkHo^DVoqE^ zFD$o35Mj*%RW3PX6n|zK^!==|x)d!m{j^YD&=3k*1qB~6txbZ@ZwM&T#YuyiQJ$c2 zv|id{9wY7ea%o;uL=skaNX@N&8)LP&;TmE7Cu&}2KTG4_IgHKwX;hThYaFN-RQ8h(fH*Hl&}xRxj4MN50q=*iiR2^D5e)3ThZ z#!f-&V2O&S+DhnPF>3EtGs@q42d5B0v7zx=^*SA-a-DB`90KJf1yf7QYTw-XHpCSe z_g#Q)9iWDlN*7HLQ6wVT;I<1rScp2Bn7Q;BP7Mm^MR>a_=aA0L1!5djt-xT}O!;9@v6!fEcX|Q#Yvtse=!IE0B|IvsXkUqYMs|DR(Vz zes=(4%qN>;JD)h(f4@hqy{=+Zi-%tz4*99g5$hntbC(hRvdT*TF#O1$9`YVl;u+Y=+6wTa@)@jM)2A5_9TjuFh?yk&;1)6sn*PRC zsKUB9bPR`J9qR`Cqc&+6fmO)tF(W@9NsiahOAxD4u=_7>!Da!Bs1GUaxv%~~?fi>3 zVq#*0WsV8L7#tvrg;_aU8#=K)XJ*n7}X0l z6T7y|MId>Yjt+XhE?mEuJAXlBWDlrMjKi){Z&TvZHl&w@DTv+64Q-3~H1EF%E6Wp2 zY*lJLAdX*JgnNUm_tFxeI9xQPpXMCHu^EfSLsEbZXP331 z(^@6onl#LbNW>chIsx?k!q;*Ipw;@OrY7Yg1wvzeSz=~-6s3>BGXvpYy*h2Ap8JEq4u?I!jbOuL3CWj5V`5{~8B;_jjkB}(_-O$Az>tzt z>?GQhGP=fB!wi}}C@9wG%seui*q;%l2XbCdT%S_p`jHr=^JNLqL42s;@tV9Qe`Sm|h!vi#@Tv)?d zuo!(XC7pN4dc>=k;*gD<-N++YGS7PaS4g|Xkzm00Vqn3%cN|HCbNt}iP+TrB{TE%% z-gDweMwGJ4_0>XCtjyiU*AQwS+Aa#TRc;0apX zz;Z&oKKL}oaVzeGd9_RZ2aY!UHhYL3d_fe-P)|BNx3tDq>NgeEpI-tGJ_UH#4OFWl zMKV_PQKick$czB!MNUgMIODQ191}QP94b9Qp)&ZJxtxbh8tP?0FLN7c_htg}I{v({ zVB0+aaS1b;dgoy2sPb}JM-BJw^K$9#0PrvyV`2aL*YOp4S&%OJ_jtqR6XML`cVBqy zv0yq>6)Q|SA)K3&138WCUb$9~6RQ% zKtS^LCSI?M~MslpzatQ(7kd!xjl6VEUO_jUi++W zB;Zl6*)&Myb4=H=JlyWYDcPVj}rp|tBYJ0^ETJ$;H8$jZXC&V~DU;dQMCA{<& z>$D}{qi?OjVY+6AHl1tF< z5_;dQgjwpCun6w%IohEE6sGuVIgDz)Nip*yo;DTJ)$-#0q@L$2ULoG+=eQWqamxoG zM>n0B;XRh6Q8UwU1j9U9K*N)kn3Pb z`z0U|=Dlt^Hc2pkk_uLB)o;uM%t6x^W~2>VkA~uZ8(9WUmcR85$+p@Im}bIZv;J2e z%jgzv^f4&JsN~V7tn@YgPNBQx=eW>7UvOC%+_rFrzZJuFxReI`;yrAW*Lb#*wyz|W zmY|92TyeMZy@=9MQAPeS+G_*V!JZrB{;f!_(h>dyxtS1PUg?_N5jqtHN;a=L2F za5AC>YANm_BTZ%#r5RCahX3}z<~X8oRoE&ErwdV2&FbTO68`f5dZYlFY=F+b-VJ@^Aq9T8qwrO4 zMuSaUu|X+16ITMj=>Rz0ZSY;Q#Y5Z9$;smG^+9)`F-rN$=8ULvh{*jYG|G!ck_F|= z=uqtN`|!Jw)(KLCKd65r5rW+1je!bjFGtcxX7vam8UhF6yjh0x`LySfX;(%*%X%i| zncKU>vkaQ@r`qKr8rcG5P;mtDPP*PZB}9HLU=F+^;l-7;`}92Mex2i&?I4^aw2>=8 zvtT(}Yt4}06Zi^;*M*_gkFb300g{R$HS2Zw(hGbfXr$q5llApi5>XXd>Xg?ShcBnF zpE=4-w)G?R*6N@KZRh^DK_0piLK?n|)QG2@Ubu7j<3+@ZG`#<~7kS)VXC?upXng># zx?jwRc>?{|+i^CSw(cmp>Wtb$AEw1XuZ&tge7pI2z3xOVqwI=ejC@LT8ZwlGIrmA! z4Lr+>!WHZRIOKz>bx^Vy#ad>0T@Hys0|QVB-p^k{i#8o4w1M01Q3RD*>XWgMEIf_s z5FgZs$ffN!v9fYntHy#uQ&8u|y`4;lrR?r+483S3RjE+@Fw`X_F_B`OJ5S7r$_KRg zlIQi`14xS`3z@$sCLIArCVuo$3gKw;JH|{N?l4#Rn1QTc=P1JW(oW`aw>}tht)Hx0 z%8&ohP#h?t~mv+;ML=Y zK^4v2rA2qC4X_<{NzBr%ieRouim+d&8CyZvuZ#2JB}+<1kCIphFa3rSuovvr6lsoc zn@+4p@pgP#Zp^~bq!0vr{fSlGTw($UxVb2-^uhX1V<YOUn*zW%R;X)dy%vs+k0>4y2A-$Z7!3204J{>IY)F3_!Q5&F;q77 z{E92l!EvgXnn+r`ps{WC9tmWHPjT;WW~-%5ckEP0hn0I+XNTlb z7UsX2wUH`_92=Q^?PxeZaY>-7nHp78QdkYyq~~AgwwVE`!~?(V{vR_jpFX!+Ooy-GuCD9j5H_fgF@%-*oXZ=9BU_nZkKL3m6u zJ0bion{2JjJnKYzHxqt$M!md28#;lbpx?$7!XeOG=I;uQG#!pd^Z9x~EPYgDwC~xfl2LM)oR09%A~O@KReTeYqx9aH&SzYOw)xXxorrN6VECe8_`gj@P`iEPU<5 z;d3&}DUoY6!b^PzHgc4cW|)C>Ck&B?3$G4L`>!vJT6>SRKf2Y$Swg~GJrbd}*DODd zn4CcRx@YkLzP!ajWBDAqdKN`Hq*>NO?k$DkgnTz=J#>*EyRv#2 zaV;lCglNuWaf`oLf4j4>`j52J%TR|Po@V-aMcQop`YxxSX~m^3tbnBtq9@v9J~y3GgDWwW^YbkMCU`icVK=*eDPv zm}<*Zn1zoDUCYf+Y4^c&Ao&dU6yE|MC=IoceYBFF6~9qtL%g{$HID!iN-$`$IlV}d ztor=x&_k>2kkZjA74koLX)q-S|%Cxat`Uv=5KxSYK( z1Rn0JQ|`SFN`P)UqR}Gu*v<`gDUW5o+JXzUyb8jjlA;-6dSf+J;1XVbcB4!`tIN+5 zEajLQCizPPR~xQ6UCi4Ib#cdL&V|0-gWO(SfkaG@;jR)@fRoqm7&I-CZCiHb*DQak zH`Ic|4u@05ygytS=23Rxr;{-d@EU-CW@yEDhLX!DKsDCdGt;`#AE&X1CTsr=>`PcC z9*1)#mqpD$JT)P-2a;Cc1Fh$S6GzvT=`#i`Z6=gLK<>jg#kQ||Wnn777*)Ezv8<)` zU_()G{~P4yXNDdT=3eLqctIcTI{@m%I$6!%l-l(;E1C5v14A2HPQInBTzG zzg7Jc2OxhABUP*ewLVOM%xI7!tirDd@210JSme&@10qlgvY}8Yuqeo_d;A*e4f>oC z0MVaA-9W$W6Z@A4a9)ZbXshqqu~9(Kg;_bAG8Q(AgKzmXBWhH5Jjr&<52;Cun&E>6 zuZxWAE$s=B$gqHUvk@+m)9Hec;bx|zM0TlFj1G%x<)jLj-Y1Zoe@nY@XAmrXM zdj1Pm#uMs=RdV49>hmf-CQP8K7Faot$cQ~U89nks9bB;?5Y!#bxrH@ZCyTwAP!|Pb zRxapw4wg+BK2p!KKm5r3i7R;Lysie3Kdk$O|_BI)=%O?=_bvM_c$_i15V7(^=J7vtk2dZ`2Db-y zqkhOS&au@&4L&}La~gb$4`1y6W&ftLMkf~<4s1=hR+%k*I6GT9W%itHhiQL&_eDnh zFVX!>nooCkyxX4|gV7f)xqs2Cn*Psw8~+ot_n$WYGXnn^f&Y6Wz>J>l`cVt;f3Fw+ z=kA<(-k6Bn_ZnaQWT{UuDDRaRMLHP6wZC0;(q}gX_5N~xS!32iXdIXU`=h^j{rDpe z7xOfA^1puqhC>d_|NXD)zh5`Oe)a#&>w_GzR$i}Y$Hn7$-x zcV0$0(S2Iav?@y~avKH=J2$n8QRL{?&|uN=va^Ki`m=>v%Y(XviTMSkr<(r%q%#C_ zon0p)(Y&6{p^*RT4X*jGXg-`4F+IIYkgwCu@9?-ZVqaRyf!1^cCL#Wr=_^|P$>}R4 zxf5uO@Hpv{)oyqx`QhB5k!^FXc@O8f5fh05-TdNt|A5>D(%fbw(rEM--fL)$#CR=U z?m+yWI`=0zR@MI9K#BPb7|Zq3I-bM;K`va|Ph}XyCnP85=2}z~l{t20>NMrYV}Hm< zy2c7qeoc7gHGVE-) zcd7PZ|8i+{qo#l94F4$O6>9aQ%7$&_Bk_34Z=1WX&Hn?M1n^R()sl`*7_FrxJU$+1 zyBbh_ea}C!oBp=rzQzXw8D%1YprOAn16{Wv^xByc^<(VVGODUUmi^o?g#{C-p=u{| zjjZC5KcK)owteL6fE>DT!Kz?rh}Ml?3-YR-NAn)Y<_2E+dL;Vb4Z-o_Xq$=Jz5s>z zbRI#5pyT6;SceN;Av?;T4oj!`>_x4zg?ir~sWt(zDsiFE zsuKt*pD(SRcc~2>y60RyG_(^Xx~bJzExCVAzD@8&m_};9)^$Z69MnVS`p-prZW$O zdi($XwBJ%`E}?|7l$}CIXt6XS6xsKL#MqbYT1|wS?0d`*vhOC;rIcZW?1mzy3FBIa z#_)U1{d|A@bFVV)AMUaT{^kM|w zoxR1Gx!FO9kfsefuSEgi!wUGJ8Imoj{~cK`zyD)>{rFpbL z&a;Pv?=}rI>m+F&sFtJ^Z4@vZIYDY_1819C()Vwdg&0i)qy^3&Y)$qYDtD;-+Q$9} zn)~a%t8PCw$b#;2ud1CMOjpUo6T4QeUaoMaO{j&3@F<+|lB)#UP;4ov8H8lIo7hbL zL7=&x{@7AbP@w8v$ZefW@0y#31J>3kg+03L^dr)y_uIE`3yFp<>tyk0gI6ntpvPp> zPRULd{c_6tL^hB;>Ea@1;5VP{+q3ea{0%DSz}lTIxh&6@eu;QB(SA{V< z)$%vgJCg6Y*mC4t0(?~z01_AUMp`gE&xzZ5Y55B;61cMu!WSVy@F}Mj!;!n@^?Dcz`iPC8K^Gq zNh`nMD7hR>4@V!YTz_%$FWG~w|K4;>8@DvL!oDWJbRPXUjgk2-C`C&bb55cP=n%PGd|jl5Y3>0Ef*hzH@(n5A?BK?xcX=kdaih~Gc0eDp1NKNL~f zF8OE{_xs!@4)xioO?4$313;m=g=upA-=glsz$!TxH&xKU^c0;}0{oEB381sF>2**4 zo`T!6e-9?+1h2To3P73{e)EK0-RN*5|OO;MgWKa(96(M!gtGGh%q zGf8%~ekp6+MN;Uu!25IHVJhfbV*}>{HP!U{vJ(^k_nf|PHHK(dZpnridxa&xWEWf> zed#zHDNvh?--os=d3QG?9#I2TC~??&XSxokro36aIH|2>am!tzO&W(Z_Fc2ayJ)NaX+Oe7|B<;wHWY zkd@UnG@3n_W$cm}-#>tvh}r+}`;)ZojX)Qi=(a5oWZ};xPrw)*K1r@qa|%w(}S z-SG0t*$wJBqcK)>Ej9aPLeeYPdFTsK9E)JylgzhX28?5qsHuvG=7v>uagJ2}riTMSKnPaOSN&zx(pP*vfz4XM3;z z?(z68?Bd)a$;+}+)`!8b8szEB>XeA5`x zPmyXGLmk=u$|6ZW&Eoj(4_(H_#>yykNJISP-tY=w-D)NPIUSK>12UYFYOV6V3^qCS z$*7(0uiXxObP-xJZtdX1lYR{EK)W7NW{O1@rJz$A)v=WcP=uF_sESSMNBf^1Acsz+}->3quBt&hStmozuRVfNHet1$MFv zIF35py8<7DHw+jib(rSl!smSXNQRVavUm>QYs%6yGs80QQF<3X zb((g`%nml_&Yq{(tOnb7p8&j0GBDSL_51WhyVgPr-tX+3n`xNX$ZsNbz{o~^VDA(8 zBLz&H{q(IXC{A}ZZ#l7e{J!&5?-ZkRfx2A`cT$YQ;i^{qfjcuPikh(zv#z-PaRxNp zOxZIvrvT`0Dfm9%4~ulZU2$cO0dHtu`tWkA{5##=I>4bftEj3ryqwzMF*ZE9Brju?x^EEK_fESuGC*3q~S8+rR z=PoP8P9MJR0*c^1-J2^Gfe~4Im;aEnERvcuy+FPR?8c zxF2Ynfmm)4!R8&B!aA*xey%Dw$;m31ukf~W1wN4;{vvh0_VZwDJ#!Y&b|8GkKy?JC z6kcbzhE37~laIpcv418Tz$mP|dhmckNF+WC^b-tkatk;*yAVU(Jx=aQ8J3}II5;a< zBoWk~-*G-)8tOq~iOn|*@isDj)2V`<2?;CmT=Gn@P4 zv+JD|8xAndRH}-huypC+p#C@uEiW!~v1y5Ay3_F0O6icdM9t=)2X3dj54U>N0oG5t z@TS(M@N-qIl%~}UC9zN7T+FK>+1WNUG_*4dh`S6zprfMdRdXj;pqsgfBl|ECM=kor zSOb)nY^PzTzP>)?!uqK{DxegkcVWCUOVl-f{%wRc-_va1_9cQzd(QnN%ZK5{2BU`8 zs zQU`GQk2u++mDe+>eKg$Rxit`V%LRy~49!zapO=e^xKn{>+WSmKUpI+ukr0m@j!-}E zjC2B3vM5wAkw-Rb+q%~mB#xM`L?sCK$1g(=sgW-FrD}{7V|hPitpMf`F8AT;v(({d z7)){^j%_H1b^sy>#=Pa)@!8rqq85g;>UnLGLBwHER5RfEeY@s%;dqW;*!l%n zsfsuDLr&G%%$jU|wlQ7?(;F#J9lZKm2{&Fs&kMTay!HXW=fD-j?9s7`76sOJBXgpW zsm}41F$lBB#=J<-&3S@I_yVFkId~QLj`v2f*Mj3yOMcfrObvsc1h1jKzKw}}Dd97? z-3Y+aH{z{$%op&0b+Wl7ey{~-f8PfDT43>B{XdVw-dYs!72^KcZ(*`6fG*6qS=`_J zW(VINV14V2v7B&QV@`?DOId59=`P+D=c;&Xm2BWw=;C7R$hce!B5q0AWlB=|ur7Q2 zL@^Sw{c(kZv&wOCam}}S7lH?`Y@fE{zdN|Z ztqqAeI{Bjokg(Fz((bj8!YqnG)eekV$DZKa1FozLI!qK^5 zW2~bbZyxO5v9M9Fx8%M?0Yvb^w36Q%XZ~=cUmfIp4p4nb*Y2eJr^Ibtiy-(=q}ZQ{-{%$@ z{?ofNJepB(27p|^##`H~Q0#B%;T&IPT5J!*R%#;q!~ufDmUcAH zh5XmSne$iW`qJg5NToCSeRhpZDpC3{gyRM>ieJgkM4Jjr=J`qY4T9lA-)(`#EJI6> zjaj(fw~~20QX;PrJbXNTtJwocXawz<5C5itLf#|%@@U$GtgH5Z_TK68PByhu3`9yA zYS}IW!h_s}YF9sZ)?yC^qh;Wdr?!Yu=t2w8&0LRP8>F0m1 z@w2Epp>Jnk%e@-~vA^*EM>Nk2=}pI<;XSeM>b-mSez(Pe!F+f%^4{qY|@_16%FUImF9G;iCrR*KLXq~B<{jm^WlfzIrg;EiUG;yCT7#?no5*o_;Mb60U^62NBHZ#)S;l}{ zY{0YK<9l3vNS$x|7nr4&KX^y~n`sd19Plem$<35kU~j7{JfkFPdu$-|4wzJ)L6GA@ zd~JJh3L)LqlX<*r?%_jUZsETkauB6Q6b`mBxsN-0KZJ}>j7G!EYk~sDJTD5a5jp*K zw4q%N)}M;rg!WCpm-x4>xhM7e@}kL)et;=bgI5Y+r$KD)uhxzNc9Z%_C-bt+aHP{0%EBNaOuSni zu%_}f`e1-1Fz1p+8}{uTy`JRMo$P03#hid~IEE7Ws0)_vy$?HV<#7!S4UO<`;BSJJ zV&|2S+u6wM%H+8vnYil!xwjuCNLZfupJznPGE9%wk=r)MZ9 z|9ZMQcGWq+rXV2D?mShH?=Tn>p1_DSJRZ{%GpVxm;hcas`?>b8VVW_DYHGxMVF*D^yK@0^Xbt4qjA_JA3B6luSf_E2MPhN0WtJ zZ}n;_wV1B?>N=kvE>!>PVSP4}k_GEuuzhh4eQOV@c$8;io^E)pZ^gxly}pn3aVxFMwdN=+(8;zA5wL`*80TDu!6p(0}b$D8I* z5ORR#2e?DUvzpM%eJ}gqkp^NY$o3x%p@B_?8EYI&uE&7)Z-($&h$N#LnP=%+_fZAc zMyg1Ssdz)+UkBG5`oK;C?W4LfL#$tKrttG!fDi*78e|KFK!pr7f9As()CCEMo5fgl zsWuSoJAw9>GCEB{g>-@uJpEZJ!MXMe#f5ZmFNC~l?IOh#b$8Z@ z^Hroj-$d5FCbcU|YUY0=58G^*RMAjuce<* z-i>xp92G{*aGmZGaOsIC%9tpvIc$hto@%18Gp*X~gz@$WCI0Rf#j`FRpG;(u_+y{u ziZ9JD&(6|8r^DR0DYb!77$j5h{N*eHv8#Och4+PDJ^O zhVIzI?P83<&D(*RyGJT^{t3rzS#ES?W#0&&TfaY@w|-skkJEB-U(}BSsCMz~@wFS_ z*Fl`MTZ{#jzYFNzyhI@dTM1fJ2Zv|=yY+zQcqLqEqF+{H{Bgz8v~}k=iYO+@uL>U{ z>YpJJvLo-FU`r!Ya+OM5+lPu`_&mb2_&V9j3nZ=_nQoCwKHA`@z~8g!8z1(kJf4Gi zo#P1)J-jJ(-l+YXo{Er?LQHzRnPj#zX8b(*9qeP~J6V#=TM|zRi+QtO`jZ$gPD)M7 z;^{{He?mR>|8}k-HflPKX*5rO)W~0SGJDHC8Uj=wS*%uvuHAkykgw}Y;GLpgyxiL@ z+GMvJFUCmr%g5h~!epJMO^AjCJ_u{N)vI8Yl$rDHuPsBIZU5LphAt}jIlg7E_Tvvn z(I!(Xj)Hkr@-2-7mFUHj)7l?q#W0ep9355e+uvmrTJJ-9Nn9wq_0oR!V*jq1zv0=_ zTIU!)a78#vu5#zwq0}LsEGbh%K`c53cN_dwyd@7KU)hoHC75b=Ri5Od1O`q zoIxv?n)=j!N?6{~k1J7?W{pH4aNnc^J3rgIO%e*ko4o?gwI3*4fh|TGUWMkM4Ysd= z>EO&mWL`jpG%!y&^T@7TP#~TrRT@eO$?_oNACIxHGt_@~j9PeBPW!HV1R9F6$P~|6 z|I-Q~cBH;c^{r!x;HvE0T$wMIXg*uXOEgbQj$gB4P3A_uwVBIeECL>?aLs{|Ib{ic zwM)5-3>ln(iEZS3?c9zuyGxq-8~)LO_eLMiGpcKnnZ{`oqqp5}ZK;zw!$IPuj(4L` zoB!Cc)YQz(`PG%1A?d?z>G7nwe#@CI;l>?Si!;n>(~Vn3`}8cEGUvx+X(s}=^&_TsB0B!w z{h^t@bq>WjPA=+m4!D}+6ait4Y@i`<;(IzvC4{Lb6{=+D&5&+8K_SbP9&S0T`gA|o z1r+Y*Id9$b^4}&^vOs~0U__NyLvNrq7HZ}{b_st=xAS30frb!z|FNf+LE4B-J@22c z8lr52Wp<&kHbD^NMZ!^j?>8oZvQ0@4DKXf(8I$hsB9r1SyC=%p=TgVeBsHK`E+Z;!t2oH zrAr(78AgosL-d}_oec@y9L-HmA+^;|8RXR{4y|XLxohRC{f6oPr3W>#iNjAE?pU1t z_3PIufPSyw9Onw&A?i^Z?^dnEYO) z3WJvaf@;Wo?WhM)-_US78PBCAP41kNqK60IM3Z?kOE|aQlH1*kyCOzIt_!^mU0-<; zj1HK^1e-b2EzegD{>9u;hKn`8p42>^!Q4$e{wua@mn zU>2sby4WotJ#4MiGH9B-#&fjFUnF;G7ZVyJcEEnnsiPk&rXTM8oCH9ulny2mw0 z;OI9selo8--BMBf>){iRv6$*r9c;KH#B6U!UBs)~3PN64`7~{uEYR~Ea2ls+^|k(4 zP+nm``7WzAXnE$@q=+mhJZvD&_8cflltO(TAFB1jv>mw5RiH!p3e>#I4~KCgh!5qX zbLI4c??pM8?YaDKM`2+h#{u$g`~9^ga7gRIfrmMx+Ufn0`MiHv37mOB$x9sRPvonV zGDj#)rnjCtfO11~2;k%gYCkSF;#;5u7@v3Fwp3AH4i@_l=YXfRwr$Cx4a_M>nIg(T zXK)cWxdRb!1?qQwow6^!*qOR4edsZGCunSg6#ZDjz%X!>I(4@D$N6#uQeWD8|Do^xBc#ydWhbaO;X9 z;ysxk@)oO++WU0eI21^FxVs-r$Fs8+95Impip=w=``xmnVAs-p*Bp4uMZZwg$o>uQ znGY}~P)-dLQ_m?0Yr^ZEK`oWtzP34?3-t>!)Ht7w1biNLgi6VvSZoqB&C4IL7o{Yr za(Rrkg^BSvTQvnLFv^Rn7tP+<6mCB4GSw|kX;`Vf)|j)gUee(iaJL23pCDwY-V}L} z&`8Y+IbY0NIlGVN$d7B&c|5jKu9cCjF4}q%$TaIdI99$~3HIeXJ>E!=+0R2lc zC`YlMmI08UckASNzr{mlKq-I(xXiMI$Gc<);;Y(aZf(04D{TWhf!PTw)leEM+N|e& zf3E!q9Z`PGHLWy0_ioG*N6d1{@U8?#8m-`;s2kQ*&RxH0G#cxIj6zj5wzKN$EEGm< zXJ;aP>!&DcAo->1u|~aKAu$k$o$83mKZJ5i$0&;n9V(pAkfLqj4ktm=E134bTuPAeWmt8+WqsmI9p04~fB386lkAXdjBwA<&y{b>k@a8I;7rxq>6Aa? zEvM*PLy*+M1lX22J6;Lb51TJCDHc>$Q)3FC;xpU=84z}I;IiI^DuU?WIbQHXqUr@D z8wLt$Vkq2|_+rG|iD0(Lb)tt~E!aa3ch6=tp*KFZ9YeLymYeA{PNXEq{*5YO5bq^6 zzd7+pIy%=ZW%!+~6{M7qZ{E0QHx7%TtgCWvH!9*DCXitk<*?2>jo*oo*5-Q}F-wma z9tiaZP4rXx#?jQ}CbM3p4o{x27fXVlndm>IcthTV*ZHBcYjP5DSs)`}u0Z(>3rpz394ZJ-v@p{VVaTnt)dQdWcMI<;;tqoc-TiEvw|r&#nc4XVtEDc z6Wkf zKiI}jjHh#psm9;Ddxv0Lm2kFiH(HF{APyd$7PZWR9T>_f!@i;fnJy9fmbbS6FCwV~ zL`X|FPq&$t>GiElo?C(h{KWko@BhZT1{dPv)D5bnL!K@DIL!Q^))7M6EH@mT(18cg z7nli21{L_N0+{`haZ_i|!8&f~#B5OSKEOPd8wh5o2ya-U)B+u=JksY~2y=68?SgB; zXshKAa7%_ApLfk+oy*4T0xf6g-F=($6_#viknFK}_1k!Y@mPJ6C?XtuJ(BHTh7rNS5J5vT$dC_R6L-J4hV9K!B zOmiiaKw>l5iUmpeKj;(l)$cnGLz^mM)wN|%d?83-xM04U>*BfH%d=pQv#B2LXZxP%OFMLQbtfcgYe}aSs@8l9Y(T|I$Yk^{ zKjO>?vCYsz8H2SWq9x0@)i; zVh(=O17r7-9?|2Pnkpt``gZ+FPwLkQkPkKO6|zdZZp56R+dw6G`&lZhn%yzCgqHjJ z+RnKr_Zkk*(OwRkWckcY0qK{)#R`WoHr*7}Rp6+~4yL)%?%8s$J z#gwA;6kl9HEkA7uWN=0^Fy`OH!m4XNblT?Z*xWvhxLPDx*u=-!fwI_d5t#**IXCA3 z$K;Ppa%X3#`NqQ5CFl$~(6{3Dm~Pau-wt=;z9%EMotL9I=v$#E5wU5D+A-GK+Wa#g zz25~&I3N(CUJTwE4bF$(Csf0CJl(|`vcrC#BIjd`aZE#MCg0N^OtDy=#&C(MPFCiTj$Ubl5p|r85jPP1x1<$Px(0abT<@ z;I>Fk(>sFi3{WQIzNpD4R<**UZacZE1^tLK=s)F+&&Qmc*=o^pN7D~z`!MA0ZRvjs zVTV`FhSzgKaRZYTq?ZuZ6O&XAb;o01I$F|8e6+51xM_rYx)RUp0@^-)ke zb+FYJZX)Niwc1JWN$T`1Nq>nfy+6wkON2xpRC+VUdR&{o;0ZDyj>jy%3c)TVN!sK< z?a99c?O?kD7+JUNkkIj`hxi*~kMBPCTofhi%jovE@^FsoB9p^Uf#Heitl1?A@OY*lOOu83B(B1R`O|8`HgU;?q}{7LK^^n)i|+=s)*i>z+9=V7}<# zZ5hiG?VO-Ld}7*I$DinJh8tG{e;#(Z;)bxoR7x;%ENq;42fEeVdk|m$p)~CM>)=`T z0^?#gkci9)^zV_@A&N*~gg>|T1neKE?k_eglaRlCMruk$L-k;5w~IwU5!Oo~B4)?SF>GkIU{~rpKRv(6M=NyzpwqL=Dt9x-r9Q5^;w{+5vwSN=vTbCXU zgaE*XJ(t16?5k6!j_u+T=AbNcAk6XXO>1V7iJW>PVaVcckgdc+r|@2&UCZr{(S=8) zOgmRDm?b%VSXuFNcV^ZzPl3X&6wQHdYtu$@5o>zIVIHFlxb}Lsa2H`}fV0VGj zl?b>mAqA_6ky`kcnuCM!({BcwjzFL79Ll(9?DSU-_WmK*Dpzck=KMZx4CZs%HvY5gu_@1LoXW@3p#jo5w)W&0!zhbH(; z!zgFM6s7e+fx=DG$06vrkdWQrT}4YO zBPn&>hTZ;@>hn3O-9y0*kkw%aL&a)v=9NQ9dH3f>Y7%Wdyg--72*>bAzr+bek0R9Z zOgH(eykq|e@Cm|(ZA7GlJWLS`-%~k-Dj38Fwc@fDD>qP_N($^v$4^1`%C0hXxM{ml zjvm_DiIXOgVeV1G_AB9abaW1PR=%yFoxgce2o1}NNBgF*M4B6HT~WWp@my!eit+N! zmDaAg5A^12{G&w9X*ix$r-T!aw#*)Pc81Lla!KZ& z7*RC1oqV<);*AAc&4+QsB z5HtALU2zzO&czs%hSYHZ>27XYG6j*%C9{bWFN9IB!(tygH!{xXEeH|5vn>&? z_@TXKU`rXE^=U^*_yeuMgE}j2z#@b>}qQH|Q5%&N5z4O7>)a!wneO8&&t+QS6S!qS7s9t}Az-}fh zxL?Yq+xH&1KuUqKnz0a+<)U&iuSq2%e+Eu8ZXg%4qgsDpgeMa`6GpC3e`d5)9sS%2 zWGmmB+}Y2ubxBSeSt^ac4=CoA&ayRI!`^!50*>S6%d->yu z+HKu48F@gEeqB0SXKJzY z%j|=K)xaLX&&yZ;PU-&UZ^OKzxkJ;5Zj@dkAjSc5pS%7;V+K zJ;%eZ(>4kxoJmPZNzKCnDFPk=%dax3YD@#`9A(#LGHlvzkMw@}Sj^!=E@;elPbV8l zs1wAab%DU3X=iB}Y&ZH~i1NEJYvSTAbwc(1hpi5SLql%MH??nGlou8hLQ*q+ij|-x z!n^KWPK2X!OYWCsX`bvlE0UM&0vHz_eV8&*S04jUZ1Gd zLeo;F-F?Z;8&B@g+xzOlF3x%>}i?G2QLK0Kp+w zBebrLshYx?eVQ}S>RigEY=4uxu3J^Ju&9VMdbpMT%IJbh<+~D#lNoUXFf>GwNs3E` z_ovj^+1bD@)d?A44;Z27lx)V3JKN@#b0>;Z>C{ZWkFn`E<*}TZZUvny@TLh7w!}qnc+FoCc znwf3P`Yq4|SPZ?_=7+5$siDI&gonQ5I`^}OiMMWY2YylAw$S1(@LHD_*5E}7=}Cm0 zBKUpuQn4N(1}^kwsfX0Qy<1URTN{YMV8Xkz)SEJvV`m$iO|-_82!14$jqB~c#^?wo zP0ff8F#au`Ca19~TU0MJt+KY#+RWG2SFiNz#hC67D{o+2{EkW3RGy5k`f}m%FwxjTc zNYg3AKvMX`;i%SB82Js@@n@?w_NH{!N~_IAWOAR#?S*Hy#EJ_&9MqYaEhd}qUMtC^ zbwVJ-z4ccMfZ*`Ha9I!bbr)w$e&oqHW^%fBr^Hhd-7P^zQMskJ4Jy1uLEID z!0h`SE43M_7dfb%f(P`yJxw>i#M)eiZnmeqtKXlsAo3(_AwEx8w((|`OvR$b)<>lG z+Os&4st`(|NrJjr3-9p4NXxr-7h~_6d2TY6k&ENl`@;Y+Vwjn%Mke&OicF4iy$h%X z%ugL0aW^$F5lYojF)(!WxKpWpXztwTZ8>Q~Waeq==J3mWHQlx^2Qt0Tup(o@&@WHz zjwtXU>-vzprASLHz~>o!E|sP1>gq~Mcd}@HCr#R?-4-K!`}VX3!B3~4Z=;11mT6AI z<2h&Tn;Be4D#nBVa1?JHh#A*@gOkx8z1=G|pTm*+su~?&fxb0 z_{Q?0qN!-AzNNXjijhgbwv)wHsMbY==8#7VDj~2Eh2}@=7MT3e?et{f$*gpKAMz)` zauWNzxAi^~ldy}z9s2rAIK$0Zml$Q^S;KfSSh_N zN!{d-AjoBWuU`NJWLN;-tMWZY=sdmb2n-yYk12V)BT^=SZHKv#*~4R|gR4ze(XFz^ z+#fxu8Qp3hPT9dc3UW6wk;6K+zaPD9lQcaFX9R?JkX$Y))QlMTSE`OyOT*ncQ`kMU zhV;H`Y~1A1oyA#`xG&`}Z!rQ9e+dVM|vHn9^{Sgmc=A3$AUTiz2fadZW&u( zbl;QbB3^HqXmQZm{5DgYvHYvs1u@hEgdHoLwD2L^H)|o_NRA01Tf84$-71tOaR}co ze0^=u%*LeOPOHr>>w8MJWb~wg{+`=rzqQ(a>3@g!$%eWjtaV{a)VAS?%x7ByE zd!~KO^dTF@<%O8H)(n7WmKFABER-1ZXQkCHA^N~_BD@3u$Q`aGJbu1+vs$J0#jb)o zjzTrSv)J;nNa~KmHh#Ef<%$6l*usT;l~faQ31G;mR}Y2+$QPG86@(`rzML7AS)cP|spAgsw}l#_F3BdX3ODSL98l6K=3ecOB$jtRB-{hn6p1D z*~DaZ=5*_I5|ED~@CjQ$E1m~??lEvjFrXH&s8>~~nu4xdLojQYraN~S11A~br4B&d z0-d&z{QPhRw)d|NdOeHX~1+U)9&bA|cw_G|;-}h2J=8 zV#0Fd4~leVn*{dSh(iMGXYV8U-JI>?IXzI zL+!5r;49iO!nqT7js#@E1vrq4Z(q*H%~ObsLd?${Y3!v|uG9f*HtJ^vud?z?hTPn0 za0|s$ytV}v!9tfR@6;b3@^-IZ*3;{Mnms~+9J8VGs{9om$Tw$@ixavdWu2;;!l$LX z_alfmvfxmJyOwoh!&$=0uUv84V_da+AF5b#u0QY=kRZgL&mbVd>IlW;DK82R!e;&E zGTOzt6JRpK9r+`>luwsvwOuU(0!gt|^d3caRo6a-P0RTk86SiFkw25*+YFMsEr0P= z@+~+|9XCclVozNqe!?*)i*VUbc5Tt{bNcxcQJJp+6j-J&p&o<}YXH9tezdF(cK~7O z1B8)QC) z^rr&3;GBfC+VrM=MSG{)fFWzQ{JdN7I{PL$V0Gj}0;bZea{uy8?gcZMx0?JX!ku$CboCH|-1>s4W_hu5` zcAhjTx#kGR-3QR{e9tq=cSHSDT;?-Dq<0y19RQN7ReAo*LlT7X`Za*Me)UT_J)O}W z9-&IDSlCxU@PJ7M5K-`Qqwy;y$VFe6tr(65g#D;Fq%sk}qSlPdezp~cTFhoo z`5XbZ88v46f~jA)=;@iYgx*jzZG-Dr(N6^8*e;aT$lo8a^Ql@|fh9+;w$QBg{XAfH|bDr-A#3r%v04(*}3uKJ4#gtKk5$vRk{2G`ZgL zs#t>14gfbzk5l|#g<(&2q=W=%iH-XyMJ{?eHbOcQVZr_JsP@fw^^gI{36HVDgOA(r z(C<2;^}7+SBfkzDLLz%;e$Q_jT!jfXa}4JA8}Vo}9&K-J@`fSg%x9y*Rj8ruFkv~B zGLeW{I0mDcYSiec^)BQ(;{*2o3|QKu5ZkN*P{@T!rFwq#(yEQB$gbf(9>RUrVXmq$ zLh^T`pxPRii|W8gn`JN=^wr>Qx#-Cyh(wIhbtinscts|&fD_lRzi;=53uwqiN?2N2 zHmV5If%BZ5XcTOuH7B6@b1!nSEn}H0Cf7U$8?V#$5kh-k@xE!b@Cm&N z!ngfC1-*n)0h)$v{ZTF(Jvkvf*@yIY)e04%hWhV18|6JYu@Pz(CnNjsOvb_ye#iKX z0K*~tZ*X|DM1(ofwn03)%|IIt~d1& z5=?!_dByse27?0Fcm!T-*$7=nR-I@nokbO&)jGjaTdxE=SO9s^bynKJa&>m-bR9yQ ze&ZP`)lLKGOfFhup8t4W-7Yv`Zi*FUmJaGrAzvOuRL|M}okS@0C_OMO2oQ{{WaRcQh>kLmd*;ZA*tJskG>~ z6eem%q(Bb*-v-QxL#kA&PFvpX&<~AVNX_a+EcVkULAzLNx}tZkjlEJnae8p_Q=Wue z95y=!Oa0W7`1hJlo8hM(Rz9S$E&P3QS-M&$uvmUwEqCr)LXG`r*el*Zg5prTJw`cA zSb2?If9aY{RU0(ZY03KDiuAs0k(4b->Z6Yb*mEhs-sj_$0JTL~Br&>GClrLo1)XnJ zvND8_ygF_1wE~a(#?fe6ZbGjBR0yz>st9W}_S>zL7E)7C@Eyh8H_3Qfe4=9h7IJX} zyI!MW`M&w`34y?iQgJ-}Ej_l12EP8}4Iv{m1MHwJnDwIhOP84JNawhzNxv?{-CkgY z&QL=yYi%xgUFJ~fn$Cb}4(2Zz@`Dzj`CoJg!gKz-HKP0#gpgYy7D@5&RdWfwc_NcC z-hNJkcdsImoX@dVAA63iu~aTdu|8p*PF7drjQ-e@H@>J+eT$14y8&oyIQlwrzV&Z9 z0wH4o>4K@&JNv1#ph6fJ545h)Sf`&JiAEPhsMgojbkQ_DRTt)wtg$-b+YSdJ=!Zlm zzkV9*8)7m?>dy(w#_dh^oG1@kU`RP0Snwq`T$j)Xod{X4pcAa^vnCP*LdNosjAgO^ z7T&g{Nq@VeqtjuM*v|J!R>uL_9Gj;Qsiu8%?5r^T2$HJZR^mh6XN+Dx^wS)hH_GGf zGh6X-aKRYO^d&2guLlQ7ZO<8dwWu@>Zh+xc7MUDIE@oiYE3o&&Pc&6*PM>8tjSWr` z9pk|du1aJ~k$O6PR@5kFB9mN)G76%x9}{}T{B7(mz}s2`r=*Fg-u0Zo4inVhg7iiN zR3?T3j-;7ze=O5(n;HR86dV5de4C0zECjurkiXWv06d@H&19#IXLs|xKA!J|a@rAH zjzNrhEOz@CQfTyB?cd0iAA8v$ptb2aX zbUShkm9jL;_JcEiT;d8U6s!XK{Yh0Bm1fY=SB&?aa{ z-p1cbnPPGDknx1A`cI9evFZpu(m^0N+`UQO`1f%szw+^)Z@`k(LblmKMX6HxV`o)9 zFkxT6H77WgR~l~F$B@L0z2m;0lmadYIC3IB{l{?QAtW@Pdp)buv#I?STH60$*Lz&E zARo=*LQ?iqUX24;`g<_=*R&N2H6Ua!A3xNWVSuL1OkFUL=h^jLksV7TWJc;dC!CPp zo0c=kOu)oPCQ|zJ5(T4Jqt`Rypc6Jts#{*s&V2viR_4m@wK=tYK)igk5Y#ImQ=58q_idmkKxtE)j8eqP-pba@Yhm1tZ^16rQXTnS9iD;lqPn`wrt1 z=t{4dcKQCcu(?l|dJ#M>vJMc%%C3r?EB?Zh1!q>mq(7DI-iu&|0$(Aq)qL(|C@~Me z!s&6LTM^*+8j8YeakIs!DORz zYY2O`pGMrZ0AmG_*7I3C33XZFXlE|{_AM5Zb0$OREF?ssY`FOlVGh2q#G9R|rIarj zlQ&!-_+y+u;cB_|Gb3B2RD=M6M|+K}{5c{s4I#iojF^EfKC_Yu!2j&8cT!v}U`R_6 zdNEiw_^Om{6l|%5KfQeYD!Y_G-gx(4MyDifdOU9T`@{dS@J69E z!b?a<`m{<&5F7@Qa*tnr$t~`WQ2USEPqC9DEoJJ@u)ne&?llUkY$;z^*%0jvndAkq zE04sC<+AI)Y%`%ig2{V;81nw#iZPGIn(6AiMZ1WKtZN?0F@XVDMSC)_$#Ae zwwS9`-s{o=cF9!h-AQ3`n%Cz<$X}{ITtm#=V88wHu(#T6RkxSi=cQgVK~<=i4Kn%u1|&T_wc8eSwbXyS7{=ZYh5&gO5V;>_a5hpQ@G(MTsT~i} z#qfeSbu+D~NTb(Y77+k4OK=j&87j=hP<%J^x^{-Jl9DSf3vv1bWJSU2yJr+e=L3W+ zlcxDaCS44D=A^){xp2LP15=BTetJQKXy`M<8XOoHXE!4RkX)WGFy;jiX%>h_Ls_Hj z(_{5+5n&(lLP^o@Jzd(n>BQFyw1q%&^*M9&aKCgH^7`QNUDYz-pyamK#DAMHYiCQ zaYC29a%u}2i;5;>qHmuy&`4*3gLRM~L><*WdtD+-Rk#`IejU~S5E7!XDh1Lcs9k5q z*1l?%rEa#Ica9ih0P~>sS*5hy$n0to)WeP;xip77-Fy7PZ3d|TNQVYN^Kqov&y3{! zMCcrK>a?kX_ZGRmcI%S>zr}==N&kX&+wbbi9p!55u3HSe$Zi-;3}zo#^f+bECz@Dbw7m4)VrBR)aNFX9C&#cVfoTwHmaR6` zsS4X#nDp!Y)9H&S-Sr=0^E~?_(4e}4hFy47*1Fl?RpMnxMr^)jZ3WCD#(+QT4R&2? z)S@&`3IaPx(vtS;`-k8A-`RTs;hx!Jl}mZE*F6Dt8 zhnYAe>~F()Ud|%PD9!Wi;c~T-M5hfis2YY&fql6uG6_+_jnUVi>V*k@H!YGpqp?Nv z^00NrzcWRGpje}x@W4$5#%&F|&V=|pC!tqFWHKKUbv)6x`LytOW#Gd2pn$5+o!9dh z5p#z}?-^?$hQ37St`}nOQvBz0Um^ieu0To6ewg!xS%*#lwUkqj)NGWjw=01?5n$0_3@{SRU zUB5%#pg?}=tM#@nVOOLL$gm=6uR#+f4jb=z?|6cfs!;T`OIOzxCL-9qH6B&!0?7Ed zK)za%DDP9yXVIx@CxA=_d~BGvgTs%{2>|q%Gk`VCr`0yTpa`d&$JnATI39%^1*H?S zt7MYugd)MunH;1+y_ong7`~xs_RlpfYYm8$Xb>sY<$DVv)}faHBMuPKG%)08Ln}-r zYUrz?B3VziRPg&+1?bI?et6Y4m^a%dImro|j(iJ46eAJT4OEXk-* zPmg^}x3;9Qbm84b5Smtb^ezl)la zH)=%m<3W8=*_D0R`~CTI@TA4q_3rdh5bAVgQ%e4`2({+m7@f4Nn+jde6IPxl{lE6E z{-vof3J(m*V3V7bhREVdlnIF+g=?u;D|3U!G{0#MEH?JxQpwNIRg~AIg^*@6tSmJ( zOiMQjr>j;9(&k5$vg~6KLv4x~PN}(`TmM2oZtSyqXHildqr8Y$&d!5(GUMmz9q;V?JoR1s?sjT27NI*@@<4`r7B1 zsDGo+oN1w{w!^$bB`M2H*TPKs{l30FgT5X|fbTNl|Mnxvd!ynwa>NJ$P73O9UxqBB z4V@Ycd$a>S)gJYOW*s#bFY=$|pew00d_7N_9eL*%r+Dk);tMm>xw zC|B#aX|-C}a&8csE#>+aGa8%m+*jE0ZsnOn$mXZxI?{dtWo7^FlCT-DYUA%ml=?O)8aw4jNpVA#*eFANF^&B>(^b diff --git a/node_modules/celeri/node_modules/beanpole/docs/syntax.ebnf b/node_modules/celeri/node_modules/beanpole/docs/syntax.ebnf deleted file mode 100644 index 83db97a..0000000 --- a/node_modules/celeri/node_modules/beanpole/docs/syntax.ebnf +++ /dev/null @@ -1,5 +0,0 @@ -"" { -syntax = ('push' | 'pull') { tag } channel { '->' channel }. -tag = '-' name [ '=' value ]. -channel = '/' { [':'] name '/' } ['*']. -} \ No newline at end of file diff --git a/node_modules/celeri/node_modules/beanpole/examples/bean.hello/beans/hello.core/index.js b/node_modules/celeri/node_modules/beanpole/examples/bean.hello/beans/hello.core/index.js deleted file mode 100644 index b65b64b..0000000 --- a/node_modules/celeri/node_modules/beanpole/examples/bean.hello/beans/hello.core/index.js +++ /dev/null @@ -1,18 +0,0 @@ -exports.plugin = function(mediator) -{ - - function init() - { - console.log('calling plugins to say hello...'); - - mediator.pull(' -multi say/hello', function(response) - { - console.log(response); - }); - } - - mediator.on({ - 'push init': init - }); - -} \ No newline at end of file diff --git a/node_modules/celeri/node_modules/beanpole/examples/bean.hello/beans/hello.friend/index.js b/node_modules/celeri/node_modules/beanpole/examples/bean.hello/beans/hello.friend/index.js deleted file mode 100644 index ccc4b5a..0000000 --- a/node_modules/celeri/node_modules/beanpole/examples/bean.hello/beans/hello.friend/index.js +++ /dev/null @@ -1,13 +0,0 @@ -exports.plugin = function(mediator) -{ - - function sayHello(pull) - { - pull.end('Hello Friend!'); - } - - - mediator.on({ - 'pull -multi -public say/hello': sayHello - }); -} \ No newline at end of file diff --git a/node_modules/celeri/node_modules/beanpole/examples/bean.hello/beans/hello.neighbor/index.js b/node_modules/celeri/node_modules/beanpole/examples/bean.hello/beans/hello.neighbor/index.js deleted file mode 100644 index 22c6918..0000000 --- a/node_modules/celeri/node_modules/beanpole/examples/bean.hello/beans/hello.neighbor/index.js +++ /dev/null @@ -1,13 +0,0 @@ -exports.plugin = function(mediator) -{ - - function sayHello(pull) - { - pull.end('Hello Neighbor!'); - } - - - mediator.on({ - 'pull -multi -public say/hello': sayHello - }) -} \ No newline at end of file diff --git a/node_modules/celeri/node_modules/beanpole/examples/bean.hello/index.js b/node_modules/celeri/node_modules/beanpole/examples/bean.hello/index.js deleted file mode 100644 index 5682f02..0000000 --- a/node_modules/celeri/node_modules/beanpole/examples/bean.hello/index.js +++ /dev/null @@ -1,3 +0,0 @@ -var beanpole = require('../../lib/node'); - -beanpole.require(__dirname + '/beans').push('init'); \ No newline at end of file diff --git a/node_modules/celeri/node_modules/beanpole/examples/bean.hook.call.receive/beans/test/index.js b/node_modules/celeri/node_modules/beanpole/examples/bean.hook.call.receive/beans/test/index.js deleted file mode 100644 index b5b1122..0000000 --- a/node_modules/celeri/node_modules/beanpole/examples/bean.hook.call.receive/beans/test/index.js +++ /dev/null @@ -1,72 +0,0 @@ -var lazy = require('sk/core/lazy').callback; - - -exports.plugin = function(mediator) -{ - var ops, sent = 0, received = 0, pulls = 0, capp = 0, interval; - - function testSend(pull) - { - // console.log('received: %d', ++received); - - /*if(received != sent) - { - console.log(recieved-sent) - }*/ - - - pull.end(++received); - } - - function pushHook(data, err, request) - { - console.success('starting test.'); - - timeout(data, ++capp, request); - } - - function timeout(data, index, request) - { - var margin = 0; - - setTimeout(function() - { - for(var i = ops.concurrent; i--;) - { - // console.log('sent %d', ++sent); - - margin++; - - - request.from.pull('test/send', function(rcv) - { - // console.log('received: %d', rcv); - - //wait till everything's done. Stop if anything's missed. - if(!(--margin)) - { - console.log('#%d: done pulling %d requests from app #%d', ++pulls, ops.concurrent, index); - timeout(request, index); - } - - }); - } - - }, ops.speed); - } - - function init(op) - { - ops = op; - console.success('ready: speed=%d, concurrent=%d', ops.speed, ops.concurrent); - - console.success('Now open another terminal window with the same script'.underline); - } - - mediator.on({ - 'push init': init, - 'pull -public test/send': testSend, - 'push hook/connection': pushHook - }); - -} \ No newline at end of file diff --git a/node_modules/celeri/node_modules/beanpole/examples/bean.hook.call.receive/index.js b/node_modules/celeri/node_modules/beanpole/examples/bean.hook.call.receive/index.js deleted file mode 100644 index d4c0b1d..0000000 --- a/node_modules/celeri/node_modules/beanpole/examples/bean.hook.call.receive/index.js +++ /dev/null @@ -1,28 +0,0 @@ -var beanpole = require('../../lib/node'), -cli = require('sk/node/cli'); - -var ops = {}; - -process.stdout.write('num concurrent calls: '); - -cli.next(function(arg) -{ - ops.concurrent = Number(arg) || 10; - - process.stdout.write('speed (ms): '); - - cli.next(function(arg) - { - ops.speed = Number(arg) || 200; - - - beanpole.require(['hook.core','hook.http.mesh']). - require(__dirname + '/beans').push('init', ops); - }) -}) - - - - -// - \ No newline at end of file diff --git a/node_modules/celeri/node_modules/beanpole/examples/bean.hook.hello/beans/test/index.js b/node_modules/celeri/node_modules/beanpole/examples/bean.hook.hello/beans/test/index.js deleted file mode 100644 index 764cc88..0000000 --- a/node_modules/celeri/node_modules/beanpole/examples/bean.hook.hello/beans/test/index.js +++ /dev/null @@ -1,41 +0,0 @@ -var lazy = require('sk/core/lazy').callback; - - -exports.plugin = function(mediator) -{ - var myName; - - function pushSayHello(guestName) - { - console.log('hello %s!', guestName); - - if(this.from) - { - this.from.push('say/hello/back', myName); - } - } - - function pushSayHelloBack(guestName, err, push) - { - console.log('%s said hello back!', guestName); - } - - function pushHook(data, err, push) - { - console.success('A person decided to join the partayyy.'); - push.from.push('say/hello', myName) - } - - function init(n) - { - myName = n; - pushSayHello(n); - } - - mediator.on({ - 'push init': init, - 'push hook/connection': pushHook, - 'push -public say/hello': pushSayHello, - 'push -public say/hello/back': pushSayHelloBack, - }) -} \ No newline at end of file diff --git a/node_modules/celeri/node_modules/beanpole/examples/bean.hook.hello/index.js b/node_modules/celeri/node_modules/beanpole/examples/bean.hook.hello/index.js deleted file mode 100644 index 2d17c36..0000000 --- a/node_modules/celeri/node_modules/beanpole/examples/bean.hook.hello/index.js +++ /dev/null @@ -1,26 +0,0 @@ -var beanpole = require('../../lib/node'), - argv = process.argv.concat(); - -argv.splice(0,2); - -var name = argv[0]; - -function onName(name) -{ - beanpole.require(['hook.core','hook.http.mesh']). - require(__dirname + '/beans').push('init', name.toString().replace('\n','')); - - process.stdin.removeListener('data', onName); -}; - -if(name) -{ - onName(name) -} -else -{ - process.stdout.write('Name: '); - process.stdin.on('data', onName); - - process.openStdin(); -} diff --git a/node_modules/celeri/node_modules/beanpole/examples/bean.hook.middleware/beans/test/index.js b/node_modules/celeri/node_modules/beanpole/examples/bean.hook.middleware/beans/test/index.js deleted file mode 100644 index 577f98f..0000000 --- a/node_modules/celeri/node_modules/beanpole/examples/bean.hook.middleware/beans/test/index.js +++ /dev/null @@ -1,41 +0,0 @@ -var lazy = require('sk/core/lazy').callback; - - -exports.plugin = function(mediator) -{ - var myName; - - function pushSayHello(guestName) - { - console.log('hello %s!', guestName); - - if(this.from) - { - this.from.push('say/hello/back', myName); - } - } - - function pushSayHelloBack(guestName, push) - { - console.log('%s said hello back!', guestName); - } - - function pushHook(data, push) - { - console.success('A person decided to join the partayyy.'); - push.from.push('say/hello', myName) - } - - function init(n) - { - myName = n; - pushSayHello(n); - } - - mediator.on({ - 'push init': init, - 'push hook/connection': pushHook, - 'push -public say/hello': pushSayHello, - 'push -public say/hello/back': pushSayHelloBack, - }) -} \ No newline at end of file diff --git a/node_modules/celeri/node_modules/beanpole/examples/bean.hook.middleware/hook1.js b/node_modules/celeri/node_modules/beanpole/examples/bean.hook.middleware/hook1.js deleted file mode 100644 index 8d0796c..0000000 --- a/node_modules/celeri/node_modules/beanpole/examples/bean.hook.middleware/hook1.js +++ /dev/null @@ -1,32 +0,0 @@ -var beanpole = require('../../lib/node'), - argv = process.argv.concat(); - -beanpole.require(['hook.http.mesh','hook.core']); - -beanpole.on({ - 'pull -public hook2': function() - { - this.next(); - }, - 'pull -public hook2 -> thru/hook2 -> test/hook': function() - { - console.log("fetching account..."); - - return "Successfuly passed through remote middleware"; - }, - 'push -public hook2/ready': function() - { - console.log("Connected to hook 2"); - - beanpole.pull('test/hook', function(message) - { - console.success(message); - }) - } -}); - -beanpole.push('init'); -beanpole.push('ready','hook1'); - - -console.log('hook1 is ready'); \ No newline at end of file diff --git a/node_modules/celeri/node_modules/beanpole/examples/bean.hook.middleware/hook2.js b/node_modules/celeri/node_modules/beanpole/examples/bean.hook.middleware/hook2.js deleted file mode 100644 index 0d4a81b..0000000 --- a/node_modules/celeri/node_modules/beanpole/examples/bean.hook.middleware/hook2.js +++ /dev/null @@ -1,32 +0,0 @@ -var beanpole = require('../../lib/node'), - argv = process.argv.concat(); - -beanpole.require(['hook.http.mesh','hook.core']); - -beanpole.on({ - - 'pull -public thru/hook2': function() - { - console.log("Through hook 2"); - - - setTimeout(function(self) - { - console.success("done!") - self.next(); - }, 500, this) - }, - - 'push -public hook1/ready': function() - { - console.log("Connected to hook 1"); - } -}); - - -beanpole.push('init'); -beanpole.push('ready','hook2'); - - -console.log('hook2 is ready'); - diff --git a/node_modules/celeri/node_modules/beanpole/examples/bean.hook.middleware/hook3.js b/node_modules/celeri/node_modules/beanpole/examples/bean.hook.middleware/hook3.js deleted file mode 100644 index ee113e4..0000000 --- a/node_modules/celeri/node_modules/beanpole/examples/bean.hook.middleware/hook3.js +++ /dev/null @@ -1,26 +0,0 @@ -var beanpole = require('../../lib/node'), - argv = process.argv.concat(); - -beanpole.require(['hook.http.mesh','hook.core']); - -beanpole.on({ - - 'pull -public thru/hook3': function() - { - console.log('thru hook 3'); - - if(!this.next()) return "authenticated" - }, - 'push -public hook1/ready': function() - { - console.log("connected to hook 1"); - } -}); - - -beanpole.push('init'); -beanpole.push('ready','hook2'); - - -console.log('hook2 is ready'); - diff --git a/node_modules/celeri/node_modules/beanpole/examples/bean.http.middleware/index.js b/node_modules/celeri/node_modules/beanpole/examples/bean.http.middleware/index.js deleted file mode 100644 index c043b11..0000000 --- a/node_modules/celeri/node_modules/beanpole/examples/bean.http.middleware/index.js +++ /dev/null @@ -1,101 +0,0 @@ -var beanpole = require('../../lib/node').router(), -express = require('express'), -Url = require('url'); - -beanpole.require('middleware.core'); - -beanpole.on({ - - - /** - */ - - 'pull -public basic/auth/root/pass -> basic/auth': function() - { - if(!this.next()) return 'authorized!'; - }, - - /** - */ - - 'pull -public basic/auth -> auth/text': function() - { - return "authorized: " + this.user.name; - }, - - - /** - */ - - 'pull -public session -> test/session': function() - { - var sess = this.session.data; - - if(!sess.numVisits) sess.numVisits = 0; - - sess.numVisits++; - - return 'Num Visits: '+sess.numVisits; - }, - - /** - */ - - 'push init': function(init) - { - var srv = express.createServer(), - channels = beanpole.channels(); - - - function initPath(path, expr) - { - srv.get('/' + path, function(req, res) - { - beanpole.pull(Url.parse(req.url).pathname, null, { meta: { stream: 1 }, req: req }, function(writer) - { - writer.on({ - response: function(headers) - { - if(headers.session) - { - res.setHeader('Set-Cookie', headers.session.http) - } - - if(headers.authorization) - { - res.statusCode = 401; - res.setHeader('WWW-Authenticate', headers.authorization.http); - } - }, - write: function(data) - { - res.write(typeof data == 'object' ? JSON.stringify(data) : data); - }, - end: function() - { - res.end(); - } - }); - - }) - }); - } - - for(var channel in channels) - { - var expr = channels[channel]; - - if(expr.type == 'pull' && expr.meta.public) - { - initPath(channel, expr); - } - } - - srv.listen(8032); - } - - -}); - - -beanpole.push('init'); \ No newline at end of file diff --git a/node_modules/celeri/node_modules/beanpole/examples/bean.http.server/beans/hello.core/index.js b/node_modules/celeri/node_modules/beanpole/examples/bean.http.server/beans/hello.core/index.js deleted file mode 100644 index 17a9ff1..0000000 --- a/node_modules/celeri/node_modules/beanpole/examples/bean.http.server/beans/hello.core/index.js +++ /dev/null @@ -1,34 +0,0 @@ -exports.plugin = function(mediator) -{ - - function meta1(pull) - { - pull.end('metadata 1'); - } - - function meta2(pull) - { - pull.end('metadata 2'); - } - - function meta3(pull) - { - pull.end('metadata 3'); - } - - function filterMeta(pull) - { - mediator.pull('meta', null, { meta: { group: pull.data.group } }, function(data) - { - pull.end(data || ''); - }); - } - - mediator.on({ - 'pull -public -rotate -group=1 meta': meta1, - 'pull -public -rotate -group=2 meta': meta2, - 'pull -public -rotate -group=3 meta': meta3, - 'pull -public meta/:group': filterMeta - }); - -} \ No newline at end of file diff --git a/node_modules/celeri/node_modules/beanpole/examples/bean.http.server/beans/http.server/index.js b/node_modules/celeri/node_modules/beanpole/examples/bean.http.server/beans/http.server/index.js deleted file mode 100644 index 059848d..0000000 --- a/node_modules/celeri/node_modules/beanpole/examples/bean.http.server/beans/http.server/index.js +++ /dev/null @@ -1,41 +0,0 @@ -var express = require('express'); - -exports.plugin = function(mediator) -{ - - function init(pull) - { - var srv = express.createServer(); - - mediator.pull('hook', function(data) - { - data.channels.forEach(function(channel) - { - srv.get('/'+channel.name, function(req, res) - { - var name = channel.name; - - for(var param in req.params) - { - name = name.replace(':'+param,req.params[param]) - } - - mediator.pull('-stream ' + name, function(writer) - { - writer.pipe(res); - }) - }); - }); - - srv.listen(8032); - }); - - } - - console.log('Server running on port ' + 8032+'. try http://localhost:8032/meta/[1,2,3], or omit the number and watch them rotate.'); - - - mediator.on({ - 'push init': init - }); -} \ No newline at end of file diff --git a/node_modules/celeri/node_modules/beanpole/examples/bean.http.server/index.js b/node_modules/celeri/node_modules/beanpole/examples/bean.http.server/index.js deleted file mode 100644 index ca57080..0000000 --- a/node_modules/celeri/node_modules/beanpole/examples/bean.http.server/index.js +++ /dev/null @@ -1,3 +0,0 @@ -var beanpole = require('../../lib/node'); - -beanpole.require(['hook.core','hook.http.mesh']).require(__dirname + '/beans').push('init'); \ No newline at end of file diff --git a/node_modules/celeri/node_modules/beanpole/examples/bean.website.load/beans/hello.core/index.js b/node_modules/celeri/node_modules/beanpole/examples/bean.website.load/beans/hello.core/index.js deleted file mode 100644 index 21c8ea4..0000000 --- a/node_modules/celeri/node_modules/beanpole/examples/bean.website.load/beans/hello.core/index.js +++ /dev/null @@ -1,46 +0,0 @@ -exports.plugin = function(mediator) -{ - - function init() - { - var i = 0; - - //default - mediator.pull('load/site', { site: 'http://www.google.com/' }, function(chunk) - { - console.log('http://www.google.com chunk #%d', i++); - }); - - //letting brazilnut handle the combining of buffers - mediator.pull('-batch load/site', { site: 'http://www.engadget.com/' }, function(buffer) - { - console.log('done reading http://engadget.com with %d chunks.', buffer.length); - }); - - - //streaming data - mediator.pull('-stream load/site', { site: 'http://www.google.com/' }, function(reader) - { - var buffer = []; - - reader.on({ - write: function(chunk) - { - buffer.push(chunk) - }, - end: function() - { - console.log('done reading http://google.com with %d chunks.', buffer.length); - } - }) - }); - - - - } - - mediator.on({ - 'push init': init - }); - -} \ No newline at end of file diff --git a/node_modules/celeri/node_modules/beanpole/examples/bean.website.load/index.js b/node_modules/celeri/node_modules/beanpole/examples/bean.website.load/index.js deleted file mode 100644 index a1e015a..0000000 --- a/node_modules/celeri/node_modules/beanpole/examples/bean.website.load/index.js +++ /dev/null @@ -1,3 +0,0 @@ -var brazilnut = require('../../lib/node'); - -brazilnut.require(__dirname + '/beans').push('init'); \ No newline at end of file diff --git a/node_modules/celeri/node_modules/beanpole/examples/benchmark.silly/index.js b/node_modules/celeri/node_modules/beanpole/examples/benchmark.silly/index.js deleted file mode 100644 index 27cb531..0000000 --- a/node_modules/celeri/node_modules/beanpole/examples/benchmark.silly/index.js +++ /dev/null @@ -1,32 +0,0 @@ -var beanpole = require('../../lib/node').router(), -Structr = require('structr'); - - - -function hello() -{ - return "hello!."; -} - - - - - -beanpole.on({ - 'pull hello/silly/world': hello -}) - -var start = new Date(); - -for(var i = 10000; i--;) -{ - beanpole.pull('hello/silly/world', function (res) - { - // console.log(res) - }); - -} - -console.log(new Date().getTime() - start.getTime()); - - \ No newline at end of file diff --git a/node_modules/celeri/node_modules/beanpole/examples/default/index.js b/node_modules/celeri/node_modules/beanpole/examples/default/index.js deleted file mode 100644 index eb8ccbc..0000000 --- a/node_modules/celeri/node_modules/beanpole/examples/default/index.js +++ /dev/null @@ -1,49 +0,0 @@ -var beanpole = require('../../lib/node').router(); - -function all() -{ - console.log('all'); - - if(!this.next()) - { - console.log("DONE!") - } -} - -function all2() -{ - console.log("ROTATE") -} - -function thru() -{ - console.log('thru'); - - if(!this.next()) - { - console.log("CANNOT CONTINUE!") - } -} - -function thru2() -{ - console.log("THRU 2"); - this.next(); -} - -function sayHi(message) -{ - console.log(message); -} - -beanpole.on({ - 'dispatch /*': all, - // 'dispatch -d /*': all2, - 'dispatch thru2': thru2, - 'dispatch thru2 -> thru': thru, - 'dispatch thru2 -> thru -> thru -> hello': sayHi -}); - -// beanpole.dispatch('hello','world!'); -// beanpole.dispatch('hello','world!'); -beanpole.dispatch('hello','world!'); \ No newline at end of file diff --git a/node_modules/celeri/node_modules/beanpole/examples/filter.metadata.rotate/beans/test/index.js b/node_modules/celeri/node_modules/beanpole/examples/filter.metadata.rotate/beans/test/index.js deleted file mode 100644 index 1599c1d..0000000 --- a/node_modules/celeri/node_modules/beanpole/examples/filter.metadata.rotate/beans/test/index.js +++ /dev/null @@ -1,6 +0,0 @@ -exports.plugin = function(mediator) -{ - - -} - diff --git a/node_modules/celeri/node_modules/beanpole/examples/filter.metadata.rotate/index.js b/node_modules/celeri/node_modules/beanpole/examples/filter.metadata.rotate/index.js deleted file mode 100644 index 2e57072..0000000 --- a/node_modules/celeri/node_modules/beanpole/examples/filter.metadata.rotate/index.js +++ /dev/null @@ -1,75 +0,0 @@ -var beanpole = require('../../lib/node').router(); - - -function hello1(pull) -{ - return "hello 1!"; -} - -function hello2(pull) -{ - return "hello 2!"; -} - -function hello3(pull) -{ - return "hello 3!"; -} - - -function init() -{ - //hello 3! - beanpole.pull('say/hello', function(msg) - { - console.log(msg) - }); - - //hello 1! - beanpole.pull('say/hello', function(msg) - { - console.log(msg) - }); - - //hello 2! - beanpole.pull('say/hello', function(msg) - { - console.log(msg) - }); - - //hello 2! - beanpole.pull('-name=group1 say/hello', function(msg) - { - console.log(msg) - }); - - //hello 3! - beanpole.pull('-name=group1 say/hello', function(msg) - { - console.log(msg) - }); - - //hello 1! - beanpole.pull('-name=group2 say/hello', function(msg) - { - console.log(msg) - }); - - //hello 1! - beanpole.pull('-name=group2 say/hello', function(msg) - { - console.log(msg) - }); -} - -beanpole.on({ - 'push init': init, - - //NOTE: rotate=N is provided just so the properties aren't overridden - 'pull -name=group2 -rotate=3 say/hello': hello1, - 'pull -name=group1 -rotate=2 say/hello': hello2, - 'pull -name=group1 -rotate=1 say/hello': hello3 -}); - - -beanpole.push('init'); \ No newline at end of file diff --git a/node_modules/celeri/node_modules/beanpole/examples/filter.metadata/index.js b/node_modules/celeri/node_modules/beanpole/examples/filter.metadata/index.js deleted file mode 100644 index cba0c8e..0000000 --- a/node_modules/celeri/node_modules/beanpole/examples/filter.metadata/index.js +++ /dev/null @@ -1,53 +0,0 @@ -var beanpole = require('../../lib/node').router(); - - -function groupHello1(pull) -{ - return "hello!"; -} - -function groupHello2(pull) -{ - return "hello again!"; -} - -function groupHello3(pull) -{ - return "hello for a third time!"; -} - - -function init() -{ - //hello! - //hello again! - //hello for a third time! - beanpole.pull('-multi say/hello', function(msg) - { - console.log(msg) - }); - - //hello! - //hello again! - beanpole.pull('-multi -name=group1 say/hello', function(msg) - { - console.log(msg) - }); - - //hello for a third time! - beanpole.pull('-multi -name=group2 say/hello', function(msg) - { - console.log(msg) - }); -} - -beanpole.on({ - 'push init': init, - - //-multi=N is set so props aren't overridden - 'pull -name=group2 -multi=3 say/hello': groupHello3, - 'pull -name=group1 -multi=2 say/hello': groupHello2, - 'pull -name=group1 -multi=1 say/hello': groupHello1 -}); - -beanpole.push('init') \ No newline at end of file diff --git a/node_modules/celeri/node_modules/beanpole/examples/http.gateway/direct.js b/node_modules/celeri/node_modules/beanpole/examples/http.gateway/direct.js deleted file mode 100644 index 5cbe6b4..0000000 --- a/node_modules/celeri/node_modules/beanpole/examples/http.gateway/direct.js +++ /dev/null @@ -1,33 +0,0 @@ -var beanpole = require('../../lib/node'); - - -var router = beanpole.router(); - - -router.params({ - 'http.gateway': { - http:{ - port: 8080 - } - } -}); - - - -router.on({ - - 'push -public spice.io/theurld/ready': function() - { - console.log("READY"); - } -}); - -router.require(['http.server', 'http.gateway','hook.http','hook.core']); - - -router.push('init'); - -router.push('hook/add','http://theurld.spice.io'); - - - diff --git a/node_modules/celeri/node_modules/beanpole/examples/http.gateway/hook.js b/node_modules/celeri/node_modules/beanpole/examples/http.gateway/hook.js deleted file mode 100644 index 396267f..0000000 --- a/node_modules/celeri/node_modules/beanpole/examples/http.gateway/hook.js +++ /dev/null @@ -1,43 +0,0 @@ -var beanpole = require('../../lib/node'); - - -var router = beanpole.router(); - - -router.params({ - 'http.gateway': { - http:{ - port: 8081 - } - } -}); - - -router.on({ - - 'pull -http hello': function() - { - return "Hello world!"; - }, - - 'push -public head/ready': function() - { - console.log("READ READY"); - }, - - 'push -public hook/ready': function() - { - console.log("LOL HOOKKS"); - } -}); - -router.require(['http.server', 'http.gateway','hook.http.mesh2','hook.core']); - - -router.push('init'); -router.push('ready','hook'); - -router.pull('hooks/add', 'http://localhost:8080', function(){}); - - - diff --git a/node_modules/celeri/node_modules/beanpole/examples/http.gateway/hook2.js b/node_modules/celeri/node_modules/beanpole/examples/http.gateway/hook2.js deleted file mode 100644 index 6e0dc26..0000000 --- a/node_modules/celeri/node_modules/beanpole/examples/http.gateway/hook2.js +++ /dev/null @@ -1,38 +0,0 @@ -var beanpole = require('../../lib/node'); - - -var router = beanpole.router(); - - -router.params({ - 'http.gateway': { - http:{ - port: 8082 - } - } -}); - - -router.on({ - - 'pull -http hello': function() - { - return "Hello world!"; - }, - - 'push -public head/ready': function() - { - console.log("READ READY"); - } -}); - -router.require(['http.server', 'http.gateway','hook.http.mesh2','hook.core']); - - -router.push('init'); -router.push('ready','hook'); - -router.pull('hooks/add', 'http://localhost:8080', function(){}); - - - diff --git a/node_modules/celeri/node_modules/beanpole/examples/http.gateway/hook3.js b/node_modules/celeri/node_modules/beanpole/examples/http.gateway/hook3.js deleted file mode 100644 index 0d1a6f4..0000000 --- a/node_modules/celeri/node_modules/beanpole/examples/http.gateway/hook3.js +++ /dev/null @@ -1,43 +0,0 @@ -var beanpole = require('../../lib/node'); - - -var router = beanpole.router(); - - -router.params({ - 'http.gateway': { - http:{ - port: 8083 - } - } -}); - - -router.on({ - - 'pull -http hello': function() - { - return "Hello world!"; - }, - - 'push -public head/ready': function() - { - console.log("READ READY"); - }, - - 'push -public hook/ready': function() - { - console.log("LOL HOOKKS"); - } -}); - -router.require(['hook.http.mesh','hook.core']); - - -router.push('init'); -router.push('ready','hook'); - -router.pull('hooks/add', 'http://localhost:8080', function(){}); - - - diff --git a/node_modules/celeri/node_modules/beanpole/examples/http.gateway/hook4.js b/node_modules/celeri/node_modules/beanpole/examples/http.gateway/hook4.js deleted file mode 100644 index c9c401b..0000000 --- a/node_modules/celeri/node_modules/beanpole/examples/http.gateway/hook4.js +++ /dev/null @@ -1,48 +0,0 @@ -var beanpole = require('../../lib/node'); - - -var router = beanpole.router(); - - -router.params({ - 'http.gateway': { - http:{ - port: 8083 - } - } -}); - -var id = Date.now(); - -console.log(id); - - -router.on({ - - 'pull -http hello': function() - { - return "Hello world!"; - }, - - 'push -public sibling/ready': function(id) - { - console.log("SIBLING READY: " + id); - }, - - 'push -public hook/ready': function() - { - if(this.from == router) return; - - this.from.push('sibling/ready', id); - } -}); - -router.require(['hook.http.mesh','hook.core']); - - -router.push('init'); -router.push('ready','hook'); - - - - diff --git a/node_modules/celeri/node_modules/beanpole/examples/http.gateway/index.js b/node_modules/celeri/node_modules/beanpole/examples/http.gateway/index.js deleted file mode 100644 index a642d9d..0000000 --- a/node_modules/celeri/node_modules/beanpole/examples/http.gateway/index.js +++ /dev/null @@ -1,41 +0,0 @@ -var beanpole = require('../../lib/node'); - - -var router = beanpole.router(); - - -router.params({ - 'http.gateway': { - http:{ - port: 8080 - } - } -}); - - -router.on({ - - 'pull -http hello': function() - { - return "Hello world!"; - }, - - 'push -public hook/ready': function() - { - console.log("READY"); - }, - - 'push -public duck': function() - { - console.log("DUCK!"); - } -}); - -router.require(['http.server', 'http.gateway','hook.http.mesh2','hook.core']); - - -router.push('init'); -router.push('ready','head'); - - - diff --git a/node_modules/celeri/node_modules/beanpole/examples/interception-old/index.js b/node_modules/celeri/node_modules/beanpole/examples/interception-old/index.js deleted file mode 100644 index 9b86aea..0000000 --- a/node_modules/celeri/node_modules/beanpole/examples/interception-old/index.js +++ /dev/null @@ -1,31 +0,0 @@ -var beanpole = require('../../lib/node').router(); - -function intercept(pull) -{ - //change the data - pull.data.sport = 'soccer'; - - pull.next(); -} - -function test(pull) -{ - pull.end(pull.data.sport) -} - -function init() -{ - beanpole.pull('test', { sport: 'football' }, function(result) - { - console.log(result) - }); -} - -beanpole.on({ - 'push init': init, - 'pull -intercept=sport te`st/interception': intercept, - 'pull test': test -}) - - -beanpole.push('init'); \ No newline at end of file diff --git a/node_modules/celeri/node_modules/beanpole/examples/multi.routes/index.js b/node_modules/celeri/node_modules/beanpole/examples/multi.routes/index.js deleted file mode 100644 index b5d53ee..0000000 --- a/node_modules/celeri/node_modules/beanpole/examples/multi.routes/index.js +++ /dev/null @@ -1,20 +0,0 @@ -var beanpole = require('../../lib/node'), - argv = process.argv.concat(); - -var router = beanpole.router(), -router2 = beanpole.router(); - - - -var listen = { - 'push hello': function() - { - console.log('hello!') - } -} - - -router.on(listen).dispose(); -router2.on(listen); - -router.push('hello') \ No newline at end of file diff --git a/node_modules/celeri/node_modules/beanpole/examples/or.hello/index.js b/node_modules/celeri/node_modules/beanpole/examples/or.hello/index.js deleted file mode 100644 index 1d10fcc..0000000 --- a/node_modules/celeri/node_modules/beanpole/examples/or.hello/index.js +++ /dev/null @@ -1,32 +0,0 @@ -var beanpole = require('../../lib/node').router(); - -function delay() -{ - setTimeout(function (self){ self.next(); }, this.data.seconds * 1000, this); -} - - - -beanpole.on({ - 'push -filter=BOMB (say/hello or say/hello/world) or blah': function() - { - console.log("hello world!") - }, - 'push -filter=GOLD blah': function() - { - console.log("GO") - }, - - 'pull /*': function() - { - console.log("G") - } -}) - - - -beanpole.push('say/hello'); -beanpole.push('say/hello/world'); -beanpole.push('-filter=GOLD blah'); -beanpole.push('-filter=BOMB blah'); -beanpole.push('/'); \ No newline at end of file diff --git a/node_modules/celeri/node_modules/beanpole/examples/override.pull/index.js b/node_modules/celeri/node_modules/beanpole/examples/override.pull/index.js deleted file mode 100644 index a8f1d4e..0000000 --- a/node_modules/celeri/node_modules/beanpole/examples/override.pull/index.js +++ /dev/null @@ -1,21 +0,0 @@ -var beanpole = require('../../lib/node').router(); - - - -beanpole.on({ - - /** - */ - - 'pull -overridable say/hello': function() - { - return "hello"; - }, - - - 'pull say/hello': function() - { - return "hello world!" - } -}); - diff --git a/node_modules/celeri/node_modules/beanpole/examples/pull.thru/index.js b/node_modules/celeri/node_modules/beanpole/examples/pull.thru/index.js deleted file mode 100644 index 1182fc1..0000000 --- a/node_modules/celeri/node_modules/beanpole/examples/pull.thru/index.js +++ /dev/null @@ -1,61 +0,0 @@ -var beanpole = require('../../lib/node').router(); - - - -function sayHi() -{ - console.log(this.data) - console.log('hi') - // this.next(); - if(!this.next()) return "don't pass " + this.data.name+ " "+this.data.last; -} - -function sayHi2() -{ - console.log('pass!'); - - if(!this.next()) - { - this.end("GO") - } -} - -function sayHiCraig() -{ - if(!this.next()) return "GO" -} - -function sayHi3() -{ - if(!this.next()) return "hello"; -} - - -function init() -{ - beanpole.pull('hello2/craig', function(result) - { - console.log(result) - }); - -} - -function test2() -{ - -} - -beanpole.on({ - 'push init': init, - 'pull /*': function() - { - console.log("PSSS") ; - this.next(); - }, - 'pull hellotest': sayHi2, - 'pull hellotest -> hellotest -> hello2/:name': sayHi3 -}); - -// console.log(beanpole.routeMiddleware._routers.pull._collection._routes) - -beanpole.push('init'); \ No newline at end of file diff --git a/node_modules/celeri/node_modules/beanpole/examples/push.pull/index.js b/node_modules/celeri/node_modules/beanpole/examples/push.pull/index.js deleted file mode 100644 index b76590b..0000000 --- a/node_modules/celeri/node_modules/beanpole/examples/push.pull/index.js +++ /dev/null @@ -1,46 +0,0 @@ -var beanpole = require('../../lib/node').router(); - - - -beanpole.on({ - 'pull name': function() - { - setTimeout(function() - { - beanpole.push('name', function() - { - return "SLAYERS!"; - }); - - beanpole.push('name', 'PUSH'); - // beanpole.push('name', 'PUSH'); - // beanpole.push('name', 'PUSH'); - // beanpole.push('name', 'PUSH'); - // beanpole.push('name', 'PUSH'); - }, 100); - - return 'PULL'; - }, - 'push /*': function() - { - console.log("PUSH INITIALIZED!"); - this.next(); - }, - 'push through': function(data) - { - console.log("delay!") - setTimeout(function(self){ self.next(); }, 500, this) - }, - 'push -pull name': function(name) - { - console.log(name) - }, - 'push -pull name': function(name) - { - console.log(name) - }, - /*'push name': function(name) - { - console.log(name +' PUSH') - }*/ -}); \ No newline at end of file diff --git a/node_modules/celeri/node_modules/beanpole/examples/push.thru/index.js b/node_modules/celeri/node_modules/beanpole/examples/push.thru/index.js deleted file mode 100644 index 8e04edc..0000000 --- a/node_modules/celeri/node_modules/beanpole/examples/push.thru/index.js +++ /dev/null @@ -1,35 +0,0 @@ -var beanpole = require('../../lib/node').router(); - - - -function sayHi2() -{ - console.log('pass!'); - - // return 'ga' - if(!this.next()) - { - console.log("FAIL") - } -} - -function sayHi3() -{ - console.log(this.data) -} - - -function init() -{ - beanpole.push('hello3', 'craig!'); -} - -beanpole.on({ - 'push init': init, - 'push hello2 -> hello2 -> hello2 -> hello2 -> hello2 -> hello2 -> hello': sayHi2, - 'push hello2': sayHi2, - 'push hello -> hello2 -> hello3': sayHi3 -}) - - -beanpole.push('init'); \ No newline at end of file diff --git a/node_modules/celeri/node_modules/beanpole/examples/rotate.hello/index.js b/node_modules/celeri/node_modules/beanpole/examples/rotate.hello/index.js deleted file mode 100644 index cbe55a9..0000000 --- a/node_modules/celeri/node_modules/beanpole/examples/rotate.hello/index.js +++ /dev/null @@ -1,43 +0,0 @@ -var beanpole = require('../../lib/node').router(); - -function delay() -{ - setTimeout(function (self){ self.next(); }, this.data.seconds * 1000, this); -} - -function sayHi() -{ - return "I."; -} - -function sayHi2() -{ - return "Love."; -} - -function sayHi3() -{ - return "Coffee."; -} - -function init() -{ - for(var i = 3; i--;) - { - beanpole.pull('say/hi', function (res) - { - console.log(res) - }); - } -} - -beanpole.on({ - 'push init': init, - 'pull delay/:seconds': delay, - 'pull -rotate delay/1 -> say/hi': sayHi, - 'pull -rotate delay/2 -> say/hi': sayHi2, - 'pull -rotate delay/3 -> say/hi': sayHi3 -}) - - -beanpole.push('init'); \ No newline at end of file diff --git a/node_modules/celeri/node_modules/beanpole/examples/thru/index.js b/node_modules/celeri/node_modules/beanpole/examples/thru/index.js deleted file mode 100644 index acc04d5..0000000 --- a/node_modules/celeri/node_modules/beanpole/examples/thru/index.js +++ /dev/null @@ -1,87 +0,0 @@ -var beanpole = require('../../lib/node'); - -var router = beanpole.router(); - - - -router.on({ - /** - */ - - 'pull /*': function() - { - console.log("THRU"); - - this.next(); - }, - - /** - */ - - 'pull -two /*': function() - { - console.log("THRU MOO"); - - this.next(); - }, - - /** - */ - - 'pull -two /hello/*': function() - { - console.log("THRU hoo"); - - this.next(); - }, - - /** - */ - - 'pull /hello/param/*': function() - { - console.log("THRU AGAIN"); - this.next(); - }, - - /** - */ - - 'pull -t /hello/param/*': function() - { - console.log("THRU AGAIN"); - this.next(); - }, - - /** - */ - - 'pull -t2 /hello/param/*': function() - { - console.log("THRU AGAIN"); - this.next(); - }, - - /** - */ - - 'pull -t3 /hello/param/*': function() - { - console.log("THRU AGAIN"); - this.next(); - }, - - - /** - */ - - 'pull hello/param': function() - { - console.log("HELLO!"); - } -}); - - -router.pull('hello/param', function() -{ -}); \ No newline at end of file diff --git a/node_modules/celeri/node_modules/beanpole/examples/ws/client/release/index.html b/node_modules/celeri/node_modules/beanpole/examples/ws/client/release/index.html deleted file mode 100644 index 29bd56c..0000000 --- a/node_modules/celeri/node_modules/beanpole/examples/ws/client/release/index.html +++ /dev/null @@ -1,9 +0,0 @@ - - - Socket Test - - - - - - \ No newline at end of file diff --git a/node_modules/celeri/node_modules/beanpole/examples/ws/client/release/index.js b/node_modules/celeri/node_modules/beanpole/examples/ws/client/release/index.js deleted file mode 100644 index 14d1056..0000000 --- a/node_modules/celeri/node_modules/beanpole/examples/ws/client/release/index.js +++ /dev/null @@ -1,2139 +0,0 @@ -var sardModule0 = {}; -var Structr = function(fhClass, parent) { - if (!parent) parent = Structr.fh({}); - var that = Structr.extend(parent, fhClass); - if (!that.__construct) { - that.__construct = function() {}; - } - that.__construct.prototype = that; - that.__construct.extend = function(child) { - return Structr(child, that); - }; - return that.__construct; -}; - -Structr.copy = function(from, to, lite) { - if (typeof to == "boolean") { - lite = to; - to = undefined; - } - if (!to) to = from instanceof Array ? [] : {}; - var i; - for (i in from) { - var fromValue = from[i], toValue = to[i], newValue; - if (!lite && typeof fromValue == "object" && (!fromValue || fromValue.__proto__ == Object.prototype || fromValue.__proto__ == Array.prototype)) { - if (toValue && fromValue instanceof toValue.constructor) { - newValue = toValue; - } else { - newValue = fromValue instanceof Array ? [] : {}; - } - Structr.copy(fromValue, newValue); - } else { - newValue = fromValue; - } - to[i] = newValue; - } - return to; -}; - -Structr.getMethod = function(that, property) { - return function() { - return that[property].apply(that, arguments); - }; -}; - -Structr.wrap = function(that) { - if (that._wrapped) return that; - that._wrapped = true; - function wrap(target) { - return function() { - return target.apply(that, arguments); - }; - } - for (var property in that) { - var target = that[property]; - if (typeof target == "function") { - that[property] = wrap(target); - } - } - return that; -}; - -Structr.findProperties = function(target, modifier) { - var props = [], property; - for (property in target) { - var v = target[property]; - if (v && v[modifier]) { - props.push(property); - } - } - return props; -}; - -Structr.nArgs = function(func) { - var inf = func.toString().replace(/\{[\W\S]+\}/g, "").match(/\w+(?=[,\)])/g); - return inf ? inf.length : 0; -}; - -Structr.getFuncsByNArgs = function(that, property) { - return that.__private["overload::" + property] || (that.__private["overload::" + property] = {}); -}; - -Structr.getOverloadedMethod = function(that, property, nArgs) { - var funcsByNArgs = Structr.getFuncsByNArgs(that, property); - return funcsByNArgs[nArgs]; -}; - -Structr.setOverloadedMethod = function(that, property, func, nArgs) { - var funcsByNArgs = Structr.getFuncsByNArgs(that, property); - if (func.overloaded) return funcsByNArgs; - funcsByNArgs[nArgs || Structr.nArgs(func)] = func; - return funcsByNArgs; -}; - -Structr.modifiers = { - m_override: function(that, property, newMethod) { - var oldMethod = that.__private && that.__private[property] || that[property] || function() {}, parentMethod = oldMethod; - if (oldMethod.overloaded) { - var overloadedMethod = oldMethod, nArgs = Structr.nArgs(newMethod); - parentMethod = Structr.getOverloadedMethod(that, property, nArgs); - } - var wrappedMethod = function() { - this._super = parentMethod; - var ret = newMethod.apply(this, arguments); - delete this._super; - return ret; - }; - if (oldMethod.overloaded) { - return Structr.modifiers.m_overload(that, property, wrappedMethod, nArgs); - } - return wrappedMethod; - }, - m_explicit: function(that, property, gs) { - var pprop = "__" + property; - if (typeof gs != "object") { - gs = {}; - } - if (!gs.get) gs.get = function() { - return this._value; - }; - if (!gs.set) gs.set = function(value) { - this._value = value; - }; - return function(value) { - if (!arguments.length) { - this._value = this[pprop]; - var ret = gs.get.apply(this); - delete this._value; - return ret; - } else { - if (this[pprop] == value) return; - this._value = this[pprop]; - gs.set.apply(this, [ value ]); - this[pprop] = this._value; - } - }; - }, - m_implicit: function(that, property, egs) { - that.__private[property] = egs; - that.__defineGetter__(property, egs); - that.__defineSetter__(property, egs); - }, - m_overload: function(that, property, value, nArgs) { - var funcsByNArgs = Structr.setOverloadedMethod(that, property, value, nArgs); - var multiFunc = function() { - var func = funcsByNArgs[arguments.length]; - if (func) { - return funcsByNArgs[arguments.length].apply(this, arguments); - } else { - var expected = []; - for (var sizes in funcsByNArgs) { - expected.push(sizes); - } - throw new Error("Expected " + expected.join(",") + " parameters, got " + arguments.length + "."); - } - }; - multiFunc.overloaded = true; - return multiFunc; - } -}; - -Structr.extend = function(from, to) { - if (!to) to = {}; - var that = { - __private: { - propertyModifiers: {} - } - }; - if (to instanceof Function) to = to(); - Structr.copy(from, that); - var usedProperties = {}, property; - for (property in to) { - var value = to[property]; - var propModifiersAr = property.split(" "), propertyName = propModifiersAr.pop(), modifierList = that.__private.propertyModifiers[propertyName] || (that.__private.propertyModifiers[propertyName] = []); - if (propModifiersAr.length) { - var propModifiers = {}; - for (var i = propModifiersAr.length; i--; ) { - var modifier = propModifiersAr[i]; - propModifiers["m_" + propModifiersAr[i]] = 1; - if (modifierList.indexOf(modifier) == -1) { - modifierList.push(modifier); - } - } - if (propModifiers.m_explicit || propModifiers.m_implicit) { - value = Structr.modifiers.m_explicit(that, propertyName, value); - } - if (propModifiers.m_override) { - value = Structr.modifiers.m_override(that, propertyName, value); - } - if (propModifiers.m_implicit) { - Structr.modifiers.m_implicit(that, propertyName, value); - continue; - } - } - for (var j = modifierList.length; j--; ) { - value[modifierList[j]] = true; - } - if (usedProperties[propertyName]) { - var oldValue = that[propertyName]; - if (!oldValue.overloaded) Structr.modifiers.m_overload(that, propertyName, oldValue, undefined); - value = Structr.modifiers.m_overload(that, propertyName, value, undefined); - } - usedProperties[propertyName] = 1; - that.__private[propertyName] = that[propertyName] = value; - } - if (that.__construct && from.__construct && that.__construct == from.__construct) { - that.__construct = Structr.modifiers.m_override(that, "__construct", function() { - this._super.apply(this, arguments); - }); - } - var propertyName; - for (propertyName in that) { - var value = that[propertyName]; - if (value && value["static"]) { - that.__construct[propertyName] = value; - delete that[propertyName]; - } - } - return that; -}; - -Structr.fh = function(that) { - that = Structr.extend({}, that); - that.getMethod = function(property) { - return Structr.getMethod(this, property); - }; - that.extend = function(target) { - return Structr.extend(this, target); - }; - that.copyTo = function(target, lite) { - Structr.copy(this, target, lite); - }; - that.wrap = function() { - return Structr.wrap(this); - }; - return that; -}; - -sardModule0 = Structr; -var sardModule6 = {}; -var sardVar5 = sardModule0; - -var Token = { - WORD: 1, - METADATA: 1 << 1, - NUMBER: 1 << 2, - PARAM: 1 << 3, - TO: 1 << 4, - BACKSLASH: 1 << 5, - DOT: 1 << 6, - STAR: 1 << 7, - OR: 1 << 8, - LP: 1 << 9, - RP: 1 << 10, - EQ: 1 << 11, - WHITESPACE: 1 << 12 -}; - -var Reversed = { - or: Token.OR -}; - -var Tokenizer = function() { - var source = "", pos = 0, currentToken, self = this; - this.source = function(value) { - if (value) { - source = value + " "; - pos = 0; - } - return source; - }; - this.next = function(keepWhite) { - return currentToken = nextToken(keepWhite); - }; - this.peekChars = function(n) { - return source.substr(pos, n); - }; - this.current = function(keepWhite) { - return currentToken || self.next(keepWhite); - }; - this.position = function() { - return pos; - }; - var nextToken = function(keepWhite) { - if (!keepWhite) skipWhite(); - if (eof()) return null; - var c = currentChar(), ccode = c.charCodeAt(0); - if (isWhite(ccode)) { - skipWhite(); - return token(" ", Token.WHITESPACE); - } - if (isAlpha(ccode)) { - var w = nextWord(); - return token(w, Reversed[w.toLowerCase()] || Token.WORD); - } - if (isNumber(ccode)) { - return token(nextNumber(), Token.NUMBER); - } - switch (c) { - case "-": - if (nextChar() == ">") return token("->", Token.TO, true); - if (isAlpha(currentCharCode())) return token(nextWord(), Token.METADATA); - error(); - case ":": - if (isAlpha(nextCharCode())) return token(nextWord(), Token.PARAM); - error(); - case "/": - return token("/", Token.BACKSLASH, true); - case ".": - return token(".", Token.DOT, true); - case "*": - return token("*", Token.STAR, true); - case "(": - return token("(", Token.LP, true); - case ")": - return token(")", Token.RP, true); - case "=": - return token("=", Token.EQ, true); - default: - error(); - } - return null; - }; - var error = function() { - throw new Error('Unexpected character "' + currentChar() + '" at position ' + pos + ' in "' + source + '"'); - }; - var token = function(value, type, skipOne) { - if (skipOne) nextChar(); - return { - value: value, - type: type - }; - }; - var nextChar = this.nextChar = function() { - return source[++pos]; - }; - var currentChar = this.currentChar = function() { - return source[pos]; - }; - var isAlpha = this.isAlpha = function(c) { - return c > 96 && c < 123 || c > 64 && c < 91 || isNumber(c); - }; - var isWhite = this.isWhite = function(c) { - return c == 32 || c == 9 || c == 10; - }; - var isNumber = this.isNumber = function(c) { - return c > 47 && c < 58; - }; - var nextCharCode = function() { - return nextChar().charCodeAt(0); - }; - var currentCharCode = function() { - return currentChar().charCodeAt(0); - }; - var rewind = function(steps) { - pos -= steps || 1; - }; - var skipWhite = function() { - var end = false; - while (!(end = eof())) { - if (!isWhite(currentCharCode())) break; - nextChar(); - } - return !end; - }; - var nextNumber = function() { - var buffer = currentChar(); - while (!eof()) { - if (isNumber(nextCharCode())) { - buffer += currentChar(); - } else { - break; - } - } - return buffer; - }; - var nextWord = function() { - var buffer = currentChar(); - while (!eof()) { - if (!isWhite(nextCharCode()) && !currentChar().match(/[\/=()]/g)) { - buffer += currentChar(); - } else { - break; - } - } - return buffer; - }; - var eof = function() { - return pos > source.length - 2; - }; -}; - -var ChannelParser = function() { - var tokenizer = new Tokenizer, cache = {}; - this.parse = function(source) { - if (!source) throw new Error("Source is not defined"); - if (cache[source]) return sardVar5.copy(cache[source]); - tokenizer.source(source); - return sardVar5.copy(cache[source] = rootExpr()); - }; - var rootExpr = function() { - var expr = tokenizer.current(), type, meta = {}; - if (expr.type == Token.WORD && tokenizer.isWhite(tokenizer.peekChars(1).charCodeAt(0)) && tokenizer.position() < tokenizer.source().length - 1) { - type = expr.value; - tokenizer.next(); - } - var token, channels = []; - while (token = tokenizer.current()) { - switch (token.type) { - case Token.METADATA: - meta[token.value] = metadataValue(); - break; - case Token.BACKSLASH: - case Token.WORD: - case Token.STAR: - channels = channels.concat(channelsExpr()); - break; - case Token.OR: - tokenizer.next(); - break; - default: - tokenizer.next(); - break; - } - } - return { - type: type, - meta: meta, - channels: channels - }; - }; - var metadataValue = function() { - if (tokenizer.currentChar() == "=") { - tokenizer.next(); - var v = tokenizer.next().value; - tokenizer.next(); - return v; - } - tokenizer.next(); - return 1; - }; - var channelsExpr = function() { - var channels = [], to; - while (hasNext()) { - if (currentTypeIs(Token.LP)) { - tokenizer.next(); - } - if (currentTypeIs(Token.WORD | Token.PARAM | Token.STAR | Token.BACKSLASH)) { - channels.push([ channelPathsExpr() ]); - while (currentTypeIs(Token.OR)) { - tokenizer.next(); - channels[channels.length - 1].push(channelPathsExpr()); - } - } else { - break; - } - if (currentTypeIs(Token.RP)) { - tokenizer.next(); - } - if (currentTypeIs(Token.TO)) { - tokenizer.next(); - } - } - var _orChannels = splitChannelExpr(channels.concat(), []), channelsThru = []; - for (var i = _orChannels.length; i--; ) { - var chain = sardVar5.copy(_orChannels[i]), current = channel = chain[chain.length - 1]; - for (var j = chain.length - 1; j--; ) { - current = current.thru = chain[j]; - } - channelsThru.push(channel); - } - return channelsThru; - }; - var splitChannelExpr = function(orChannels, stack) { - if (!orChannels.length) return [ stack ]; - var current = orChannels.shift(); - if (current.length == 1) { - stack.push(current[0]); - return splitChannelExpr(orChannels, stack); - } else { - var split = []; - for (var i = current.length; i--; ) { - var stack2 = stack.concat(); - stack2.push(current[i]); - split = split.concat(splitChannelExpr(orChannels.concat(), stack2)); - } - return split; - } - }; - var channelPathsExpr = function(type) { - var paths = [], token, isMiddleware = false, cont = true; - while (cont && (token = tokenizer.current())) { - switch (token.type) { - case Token.WORD: - case Token.PARAM: - case Token.NUMBER: - paths.push({ - name: token.value, - param: token.type == Token.PARAM - }); - break; - case Token.BACKSLASH: - break; - default: - cont = false; - break; - } - if (cont) tokenizer.next(); - } - if (currentTypeIs(Token.STAR)) { - isMiddleware = true; - tokenizer.next(); - } - return { - paths: paths, - isMiddleware: isMiddleware - }; - }; - var currentToken = function(type, igError) { - return checkToken(tokenizer.current(), type, igError); - }; - var nextToken = function(type, igError, keepWhite) { - return checkToken(tokenizer.next(keepWhite), type, igError); - }; - var checkToken = function(token, type, igError) { - if (!token || !(type & token.type)) { - if (!igError) throw new Error('Unexpected token "' + (token || {}).value + '" at position ' + tokenizer.position() + " in " + tokenizer.source()); - return null; - } - return token; - }; - var currentTypeIs = function(type) { - var current = tokenizer.current(); - return current && !!(type & current.type); - }; - var hasNext = function() { - return !!tokenizer.current(); - }; -}; - -sardModule6.parse = (new ChannelParser).parse; -var sardModule8 = {}; -sardModule8.replaceParams = function(expr, params) { - var path; - for (var i = expr.channel.paths.length; i--; ) { - path = expr.channel.paths[i]; - if (path.param) { - path.param = false; - path.name = params[path.name]; - if (!path.name) expr.channel.paths.splice(i, 1); - } - } - return expr; -}; - -sardModule8.channel = function(expr, index) { - return { - type: expr.type, - channel: expr.channels[index], - meta: expr.meta || {} - }; -}; - -sardModule8.pathToString = function(path) { - var paths = []; - for (var i = 0, n = path.length; i < n; i++) { - var pt = path[i]; - paths.push(pt.param ? ":" + pt.name : pt.name); - } - return paths.join("/"); -}; - -sardModule8.passThrusToArray = function(channel) { - var cpt = channel.thru, thru = []; - while (cpt) { - thru.push(this._pathToString(cpt.paths)); - cpt = cpt.thru; - } - return thru; -}; -var sardModule11 = {}; -sardModule11.rotator = function(target, meta) { - if (!target) target = {}; - target.meta = [ meta ]; - target.allowMultiple = true; - target.getRoute = function(ops) { - var route = ops.route, listeners = ops.listeners; - if (!ops.router._allowMultiple && route && route.meta && route.meta[meta] != undefined && listeners.length) { - route.meta[meta] = ++route.meta[meta] % listeners.length; - ops.listeners = [ listeners[route.meta[meta]] ]; - } - }; - target.setRoute = function(ops) {}; -}; - -sardModule11.rotator(sardModule11, "rotate"); -var sardModule13 = {}; -var sardVar10 = sardModule0; - -sardModule13 = function() { - var mw = new sardModule13.Middleware; - mw.add(sardModule11); - return mw; -}; - -sardModule13.Middleware = sardVar10({ - __construct: function() { - this._toMetadata = {}; - this._universal = {}; - }, - add: function(module) { - var self = this; - if (module.all) { - module.all.forEach(function(type) { - if (!self._universal[type]) self._universal[type] = []; - self._universal[type].push(module); - }); - } - module.meta.forEach(function(name) { - self._toMetadata[name] = module; - }); - }, - getRoute: function(ops) { - var mw = this._getMW(ops.route ? ops.route.meta : {}, "getRoute").concat(this._getMW(ops.expr.meta)); - return this._eachMW(ops, mw, function(cur, ops) { - return cur.getRoute(ops); - }); - }, - setRoute: function(ops) { - var mw = this._getMW(ops.meta, "setRoute"); - return this._eachMW(ops, mw, function(cur, ops) { - return cur.setRoute(ops); - }); - }, - allowMultiple: function(expr) { - var mw = this._getMW(expr.meta); - for (var i = mw.length; i--; ) { - if (mw[i].allowMultiple) return true; - } - return false; - }, - _getMW: function(meta, uni) { - var mw = (this._universal[uni] || []).concat(); - for (var name in meta) { - if (!meta[name]) continue; - var handler = this._toMetadata[name]; - if (handler && mw.indexOf(handler) == -1) mw.push(handler); - } - return mw; - }, - _eachMW: function(ops, mw, each) { - var cops = ops, newOps; - for (var i = mw.length; i--; ) { - if (newOps = each(mw[i], cops)) { - cops = newOps; - } - } - return cops; - } -}); -var sardModule17 = {}; -var sardVar15 = sardModule0, sardVar16 = sardModule6; - -var Request = sardVar15({ - __construct: function(listener, batch) { - this.data = batch.data; - this.inner = batch.inner; - this.callback = batch.callback; - this._used = {}; - this._queue = []; - this._add(listener, this.data, batch.paths); - if (batch._next) { - this.add(batch._next); - } - }, - init: function() { - return this; - }, - hasNext: function() { - return !!this._queue.length; - }, - next: function() { - if (this._queue.length) { - var thru = this._queue.pop(), target = thru.target; - this.current = target; - if (target.paths) { - var route = this.origin.getRoute({ - channel: target - }); - this._addListeners(route.listeners, route.data, target.paths); - return this.next(); - } - if (this._used[target.id]) return this.next(); - this._used[target.id] = thru; - this._prepare(target, thru.data, thru.paths); - return true; - } - return false; - }, - _addListeners: function(listeners, data, paths) { - if (listeners instanceof Array) { - for (var i = listeners.length; i--; ) { - this._add(listeners[i], data, paths); - } - return; - } - }, - add: function(callback) { - this._queue.unshift(this._func(callback)); - }, - unshift: function(callback) { - this._queue.push(this._func(callback)); - }, - _func: function(callback) { - return { - target: { - callback: callback - }, - data: {} - }; - }, - _add: function(route, data, paths) { - var current = route, _queue = this._queue; - if (!data) data = {}; - while (current) { - for (var i = paths.length; i--; ) { - var opath = paths[i], cpath = route.path[i], param, value; - if (cpath.param && !opath.param) { - param = cpath.name; - value = opath.name; - } else if (cpath.param && opath.param) { - param = cpath.name; - value = this.data[opath.name]; - } - this.data[param] = data[param] = value; - } - _queue.push({ - target: current, - data: data || {}, - paths: paths - }); - current = current.thru; - } - }, - _prepare: function(target, data, paths) { - if (target.meta.one) { - target.dispose(); - } - this._callback(target, data); - }, - _callback: function(target, data) { - return target.callback.call(this, this); - } -}); - -sardModule17 = Request; -var sardModule23 = {}; -if (!Array.prototype.indexOf) { - Array.prototype.indexOf = function(obj) { - for (var i = 0; i < this.length; i++) { - if (this[i] == obj) { - return i; - } - } - return -1; - }; -} - -if (this.window && !window.console) { - var console = { - log: function() {} - }; -} - -var sk = {}; -var sardModule26 = {}; -sardModule23; - -sardModule26 = sardModule0; -var sardModule28 = {}; -var sardVar27 = sardModule26; - -sardModule28.Janitor = sardVar27({ - __construct: function() { - this.dispose(); - }, - addDisposable: function() { - var args = arguments[0] instanceof Array ? arguments[0] : arguments; - for (var i = args.length; i--; ) { - var target = args[i]; - if (target && target["dispose"]) { - if (this.disposables.indexOf(target) == -1) this.disposables.push(target); - } - } - }, - dispose: function() { - if (this.disposables) for (var i = this.disposables.length; i--; ) { - this.disposables[i].dispose(); - } - this.disposables = []; - } -}); -var sardModule30 = {}; -var sardVar19 = sardModule0, sardVar20 = sardModule6, sardVar21 = sardModule8, sardVar22 = sardModule17, Janitor = sardModule28.Janitor; - -var Collection = sardVar19({ - __construct: function(ops) { - this._ops = ops || {}; - this._routes = this._newRoute(); - this._middleware = this._newRoute(); - this._routeIndex = 0; - }, - has: function(expr) { - var routes = this.routes(expr); - for (var i = routes.length; i--; ) { - if (routes[i].target) return true; - } - return false; - }, - route: function(channel) { - return this._route(channel.paths); - }, - routes: function(expr) { - var channels = expr.channels, routes = []; - for (var i = channels.length; i--; ) { - routes.push(this.route(channels[i])); - } - return routes; - }, - add: function(expr, callback) { - var janitor = new Janitor; - for (var i = expr.channels.length; i--; ) { - janitor.addDisposable(this._add(expr.channels[i], expr.meta, callback)); - } - return janitor; - }, - _add: function(channel, meta, callback) { - var paths = channel.paths, isMiddleware = channel.isMiddleware, middleware = channel.thru, currentRoute = this._start(paths, isMiddleware ? this._middleware : this._routes); - var before = this._before(paths, currentRoute); - if (middleware) this._endMiddleware(middleware).thru = before; - var listener = { - callback: callback, - meta: meta, - id: "r" + this._routeIndex++, - thru: middleware || before, - path: paths, - dispose: function() { - var i = currentRoute.listeners.indexOf(listener); - if (i > -1) currentRoute.listeners.splice(i, 1); - } - }; - currentRoute.meta = sardVar19.copy(meta, currentRoute.meta); - if (isMiddleware) this._injectMiddleware(listener, paths); - if (!currentRoute.listeners) currentRoute.listeners = []; - currentRoute.listeners.push(listener); - return listener; - }, - _endMiddleware: function(target) { - var current = target || {}; - while (current.thru) { - current = current.thru; - } - return current; - }, - _injectMiddleware: function(listener, paths) { - listener.level = paths.length; - var afterListeners = this._after(paths, this._routes).concat(this._after(paths, this._middleware)); - for (var i = afterListeners.length; i--; ) { - var currentListener = afterListeners[i]; - var currentMiddleware = currentListener.thru, previousMiddleware = currentListener; - while (currentMiddleware) { - if (currentMiddleware.level != undefined) { - if (currentMiddleware.level < listener.level) { - previousMiddleware.thru = listener; - } - break; - } - previousMiddleware = currentMiddleware; - currentMiddleware = currentMiddleware.thru; - } - if (!currentMiddleware) previousMiddleware.thru = listener; - } - }, - _before: function(paths, after) { - var current = this._middleware._route, listeners = []; - for (var i = 0, n = paths.length; i < n; i++) { - if (current.listeners) listeners = current.listeners; - var path = paths[i], newCurrent = path.param ? current._param : current[path.name]; - if (!newCurrent || !newCurrent._route || !newCurrent._route.listeners) break; - current = newCurrent._route; - if (current != after) listeners = current.listeners; - } - return listeners[0]; - }, - _after: function(paths, routes) { - return this._flatten(this._start(paths, routes)); - }, - _route: function(paths, routes, create) { - var current = (routes || this._routes)._route; - for (var i = 0, n = paths.length; i < n; i++) { - var path = paths[i], name = path.param ? "_param" : path.name; - if (!current[name] && create) { - current[name] = this._newRoute(i); - } - if (current[name]) { - current = current[name]; - } else { - current = current._param; - } - if (!current) return {}; - current = current._route; - } - return current; - }, - _start: function(paths, routes) { - return this._route(paths, routes, true); - }, - _newRoute: function(level) { - return { - _route: {}, - _level: level || 0 - }; - }, - _flatten: function(route) { - var listeners = route.listeners ? route.listeners.concat() : []; - for (var path in route) { - listeners = listeners.concat(this._flatten(route[path]._route || {})); - } - return listeners; - } -}); - -sardModule30 = Collection; -var sardModule32 = {}; -var sardVar4 = sardModule0, sardVar7 = sardModule6, sardVar9 = sardModule8, sardVar14 = sardModule13, sardVar18 = sardModule17, sardVar31 = sardModule30; - -var Router = sardVar4({ - __construct: function(ops) { - if (!ops) ops = {}; - this.RequestClass = ops.RequestClass || sardVar18; - this._collection = new sardVar31(ops); - this._allowMultiple = !!ops.multi; - }, - on: function(expr, ops, callback) { - if (!callback) { - callback = ops; - ops = null; - } - for (var i = expr.channels.length; i--; ) { - var single = sardVar9.channel(expr, i), existingRoute = this.getRoute(single); - if (existingRoute.listeners.length && !this._allowMultiple && !this._middleware().allowMultiple(single)) { - if (existingRoute.listeners[0].meta.overridable) { - existingRoute.listeners[0].dispose(); - } else { - throw new Error('Path "' + sardVar9.pathToString(single.channel.paths) + '" already exists'); - } - } - this._middleware().setRoute(channel); - } - return this._collection.add(expr, callback); - }, - _middleware: function() { - return this.controller.metaMiddleware; - }, - hasRoute: function(channel, data) { - return !!this.getRoute(channel, data).listeners.length; - }, - hasRoutes: function(expr, data) { - for (var i = expr.channels.length; i--; ) { - if (this.hasRoute(sardVar9.channel(expr, i), data)) return true; - } - return false; - }, - getRoute: function(single, data) { - var route = this._collection.route(single.channel); - return this._middleware().getRoute({ - expr: single, - router: this, - route: route, - data: data, - listeners: this._filterRoute(single, route) - }); - }, - dispatch: function(expr, data, ops, callback) { - for (var i = expr.channels.length; i--; ) { - if (this._dispatch(sardVar9.channel(expr, i), data, ops, callback)) return true; - } - return false; - }, - _dispatch: function(expr, data, ops, callback) { - if (data instanceof Function) { - callback = data; - data = undefined; - ops = undefined; - } - if (ops instanceof Function) { - callback = ops; - ops = undefined; - } - if (!ops) ops = {}; - if (!data) data = {}; - var inf = this.getRoute(expr, data); - if (!inf.listeners.length) { - if (!ops.ignoreWarning && !expr.meta.passive) console.warn('The %s route "%s" does not exist', expr.type, sardVar9.pathToString(expr.channel.paths)); - if (expr.meta.passive && callback) { - callback(null, "Route Exists"); - } - return false; - } - var newOps = { - router: this.controller, - origin: this, - data: inf.data, - inner: ops.inner || {}, - paths: inf.expr.channel.paths, - meta: expr.meta, - from: ops.from || this.controller, - listeners: inf.listeners, - callback: callback - }; - sardVar4.copy(newOps, ops, true); - this._callListeners(ops); - return true; - }, - _callListeners: function(newOps) { - for (var i = newOps.listeners.length; i--; ) { - sardVar4.copy(newOps, new this.RequestClass(newOps.listeners[i], newOps), true).init().next(); - } - }, - _filterRoute: function(expr, route) { - if (!route) return []; - var listeners = (route.listeners || []).concat(); - for (var name in expr.meta) { - var value = expr.meta[name]; - if (value === 1) continue; - for (var i = listeners.length; i--; ) { - var listener = listeners[i]; - if (listener.meta[name] != value) { - listeners.splice(i, 1); - } - } - } - if (!this._allowMultiple && listeners.length) { - return [ listeners[0] ]; - } - return listeners; - } -}); - -sardModule32 = Router; -var sardModule36 = {}; -var sardVar35 = sardModule26; - -sardModule36.EventEmitter = { - __construct: function() { - this._listeners = {}; - }, - addListener: function(type, callback) { - (this._listeners[type] || (this._listeners[type] = [])).push(callback); - var self = this; - return { - dispose: function() { - self.removeListener(type, callback); - } - }; - }, - hasEventListener: function(type, callback) { - return !!this._listeners[type]; - }, - getNumListeners: function(type, callback) { - return this.getEventListeners(type).length; - }, - removeListener: function(type, callback) { - var lists = this._listeners[type], i, self = this; - if (!lists) return; - if ((i = lists.indexOf(callback)) > -1) { - lists.splice(i, 1); - if (!lists.length) { - delete self._listeners[type]; - } - } - }, - getEventListeners: function(type) { - return this._listeners[type] || []; - }, - removeListeners: function(type) { - delete this._listeners[type]; - }, - removeAllListeners: function() { - this._listeners = {}; - }, - dispose: function() { - this._listeners = {}; - }, - emit: function() { - var args = [], type = arguments[0], lists; - for (var i = 1, n = arguments.length; i < n; i++) { - args[i - 1] = arguments[i]; - } - if (lists = this._listeners[type]) for (var i = lists.length; i--; ) { - lists[i].apply(this, args); - } - } -}; - -sardModule36.EventEmitter = sardVar35(sardModule36.EventEmitter); -var sardModule38 = {}; -var sardVar34 = sardModule0, EventEmitter = sardModule36.EventEmitter; - -var proto = { - _init: function(ttl) { - this._em = new EventEmitter; - this.response = {}; - if (ttl) { - this.cache(ttl); - } - }, - cache: function(ttl) { - if (this._caching) return; - this._caching = true; - var buffer = this._buffer = [], self = this; - this.on({ - write: function(chunk) { - buffer.push(chunk); - } - }); - }, - on: function(listeners) { - for (var type in listeners) { - this._em.addListener(type, listeners[type]); - } - }, - "second on": function(type, callback) { - this._em.addListener(type, callback); - }, - respond: function(data) { - sardVar34.copy(data, this.response, true); - return this; - }, - error: function(data) { - if (!data) return this._error; - this._error = data; - this._em.emit("error", data); - return this; - }, - _sendResponse: function() { - if (!this._sentResponse) { - this.response = JSON.parse(JSON.stringify(this.response)); - this._em.emit("response", this.response); - } - }, - write: function(data) { - this._sendResponse(); - this._em.emit("write", data); - return this; - }, - end: function(data) { - if (data) this.write(data); - this._sendResponse(); - this.finished = true; - this._em.emit("end", data); - this._em.dispose(); - return this; - }, - pipe: function(stream) { - if (stream.response) stream.response = this.response; - if (this._buffer && this._buffer.length) { - for (var i = 0, n = this._buffer.length; i < n; i++) { - stream.write(this._buffer[i]); - } - } - if (this.finished) { - return stream.end(); - } - this.on({ - write: function(data) { - stream.write(data); - }, - end: function() { - stream.end(); - }, - error: function(e) { - if (stream.error) stream.error(e); - }, - response: function(data) { - if (stream.respond) stream.respond(data); - } - }); - } -}; - -var Stream = sardVar34(sardVar34.copy(proto, { - __construct: function(ttl) { - this._init(ttl); - } -})); - -Stream.proto = proto; - -sardModule38 = Stream; -var sardModule40 = {}; -var sardVar33 = sardModule32, sardVar39 = sardModule38; - -var PushRouter = sardVar33.extend({ - "override on": function(expr, ops, callback) { - if (!callback) { - callback = ops; - ops = {}; - } - var ret = this._super(expr, ops, callback); - if (expr.meta.pull) { - this.controller.pull(expr, ops.data, { - ignoreWarning: true - }, callback); - } - return ret; - }, - "override _callListeners": function(ops) { - var stream = new sardVar39(true), callback = ops.callback || function(stream) { - return ops.data; - }; - var ret = callback(stream); - if (ret != undefined) { - stream.end(ret); - } - ops.stream = stream; - this._super.apply(this, arguments); - } -}); - -sardModule40 = PushRouter; -var sardModule46 = {}; -var sardVar43 = sardModule17, sardVar44 = sardModule38, sardVar45 = sardModule0; - -var PushPullRequest = sardVar43.extend(sardVar45.copy(sardVar44.proto, { - init: function() { - this._init(); - return this; - }, - _listen: function(listener, meta) { - if (!meta.stream) { - var buffer = [], self = this; - function end(err) { - if (err) return; - if (meta.batch) { - listener.call(self, buffer, err, self); - } else { - if (!buffer.length) { - listener(); - } else for (var i = 0, n = buffer.length; i < n; i++) { - listener.call(self, buffer[i], err, self); - } - } - } - this.pipe({ - write: function(data) { - buffer.push(data); - }, - error: end, - end: end - }); - } else { - listener.call(this, this); - } - } -})); - -sardModule46 = PushPullRequest; -var sardModule48 = {}; -var sardVar42 = sardModule38, sardVar47 = sardModule46; - -var PushRequest = sardVar47.extend({ - "override init": function() { - this._super(); - this.cache(); - this.stream.pipe(this); - return this; - }, - "override _callback": function(route, data) { - this._listen(route.callback, route.meta); - } -}); - -sardModule48 = PushRequest; -var sardModule50 = {}; -var sardVar41 = sardModule40, sardVar49 = sardModule48; - -sardModule50.types = [ "push" ]; - -sardModule50.test = function(expr) { - return expr.type == "push" ? "push" : null; -}; - -sardModule50.newRouter = function() { - return new sardVar41({ - multi: true, - RequestClass: sardVar49 - }); -}; -var sardModule55 = {}; -var sardVar53 = sardModule46, sardVar54 = sardModule0; - -var PullRequest = sardVar53.extend({ - "override init": function() { - this._super(); - this._listen(this.callback, this.meta); - return this; - }, - "override _callback": function() { - var ret = this._super.apply(this, arguments); - if (ret != undefined) { - this.end(ret); - } - } -}); - -sardModule55 = PullRequest; -var sardModule57 = {}; -var sardVar52 = sardModule32, sardVar56 = sardModule55; - -sardModule57.types = [ "pull", "pullMulti" ]; - -sardModule57.test = function(expr) { - if (expr.type == "pullMulti") return "pullMulti"; - return expr.type == "pull" ? expr.meta.multi ? "pullMulti" : "pull" : null; -}; - -sardModule57.newRouter = function(type) { - var ops = { - RequestClass: sardVar56 - }; - if (type == "pullMulti") ops.multi = true; - return new sardVar52(ops); -}; -var sardModule60 = {}; -var sardVar59 = sardModule32; - -sardModule60.types = [ "dispatch" ]; - -sardModule60.test = function(expr) { - return !expr.type || expr.type == "dispatch" ? "dispatch" : null; -}; - -sardModule60.newRouter = function() { - return new sardVar59({ - multi: true - }); -}; -var sardModule62 = {}; -var sardVar3 = sardModule0; - -sardModule62 = function(controller) { - var mw = new sardModule62.Middleware(controller); - mw.add(sardModule50); - mw.add(sardModule57); - mw.add(sardModule60); - return mw; -}; - -sardModule62.Middleware = sardVar3({ - __construct: function(controller) { - this._middleware = []; - this._controller = controller; - this._routers = {}; - this.types = []; - }, - add: function(module) { - this._middleware.push(module); - this.types = module.types.concat(this.types); - for (var i = module.types.length; i--; ) { - this._controller._createTypeMethod(module.types[i]); - } - }, - router: function(expr) { - for (var i = this._middleware.length; i--; ) { - var mw = this._middleware[i], name = mw.test(expr); - if (name) return this._router(mw, name); - } - return null; - }, - _router: function(tester, name) { - return this._routers[name] || this._newRouter(tester, name); - }, - _newRouter: function(tester, name) { - var router = tester.newRouter(name); - router.type = name; - router.controller = this._controller; - this._routers[name] = router; - return router; - } -}); -var sardModule68 = {}; -var sardVar2 = sardModule0, sardVar63 = sardModule62, sardVar64 = sardModule13, sardVar65 = sardModule6, Janitor = sardModule28.Janitor, sardVar67 = sardModule8; - -var AbstractController = sardVar2({ - __construct: function(target) { - this.metaMiddleware = sardVar64(this); - this.routeMiddleware = sardVar63(this); - this._channels = {}; - }, - has: function(type, ops) { - var expr = this._parse(type, ops); - return this._router(expr).hasRoutes(expr); - }, - getRoute: function(type, ops) { - var expr = this._parse(type, ops); - return this._router(expr).getRoute(sardVar67.channel(expr, 0)); - }, - on: function(target) { - var ja = new Janitor; - for (var type in target) { - ja.addDisposable(this.on(type, {}, target[type])); - } - return ja; - }, - "second on": function(type, callback) { - return this.on(type, {}, callback); - }, - "third on": function(type, ops, callback) { - var expr = this._parse(type, ops), router = this.routeMiddleware.router(expr); - for (var i = expr.channels.length; i--; ) { - var pathStr = sardVar67.pathToString(expr.channels[i].paths); - if (!this._channels[pathStr]) { - this.addChannel(pathStr, sardVar67.channel(expr, i)); - } - } - return router.on(expr, ops, callback); - }, - channels: function() { - return this._channels; - }, - addChannel: function(path, singleChannel) { - this._channels[path] = singleChannel; - }, - _parse: function(type, ops) { - var expr = typeof type != "object" ? sardVar65.parse(type) : type; - if (ops) { - if (ops.meta) sardVar2.copy(ops.meta, expr.meta); - if (ops.type) expr.type = ops.type; - } - return expr; - }, - _router: function(expr) { - return this.routeMiddleware.router(expr); - }, - _createTypeMethod: function(method) { - var self = this; - this[method] = function(type, data, ops, callback) { - if (!ops) ops = {}; - ops.type = method; - var expr = this._parse(type, ops); - return self._router(expr).dispatch(expr, data, ops, callback); - }; - } -}); - -var ConcreteController = AbstractController.extend({ - "override __construct": function() { - this._super(); - var self = this; - this.on({ - "pull channels": function() { - return self.channels(); - } - }); - }, - "override addChannel": function(path, singleChannel) { - this._super(path, singleChannel); - var toPush = {}; - toPush[path] = singleChannel; - this.push("channels", toPush, { - ignoreWarning: true - }); - } -}); - -sardModule68 = ConcreteController; -var sardModule70 = {}; -var sardVar1 = sardModule0, sardVar69 = sardModule68; - -try { - require.paths.unshift(__dirname + "/beans"); -} catch (e) {} - -var Loader = sardVar69.extend({ - "override __construct": function() { - this._super(); - this._params = {}; - }, - params: function(params) { - sardVar1.copy(params || {}, this._params); - return this; - }, - require: function(source) { - if (source instanceof Array) { - for (var i = source.length; i--; ) { - this.require(source[i]); - } - } else if (typeof src == "object" && typeof src.bean == "function") { - source.plugin(this._controller, source.params || this._params[source.name] || {}); - } else { - return false; - } - return this; - } -}); - -sardModule70 = Loader; -var sardModule72 = {}; -var sardVar71 = sardModule70; - -sardModule72.router = function() { - return new sardVar71; -}; - -sardModule72.router().copyTo(sardModule72, true); -var sardModule78 = {}; -var sardVar74 = sardModule0, EventEmitter = sardModule36.EventEmitter, sardVar76 = sardModule68, Janitor = sardModule28.Janitor; - -var Message = sardVar74({ - __construct: function(name, manager) { - this._name = name; - this._manager = manager; - this._data = {}; - }, - action: function(value) { - this._action = value; - return this; - }, - data: function(value) { - this._data = value; - return this; - }, - send: function(action, value) { - if (action) { - this.action(action); - this.data(value); - } - var self = this; - this._manager._connection._target.send(sardVar74.copy(this._buildMessage()), function(err, result) { - if (err) { - self.onError(err); - } - }); - return this; - }, - onError: function(e) {}, - _buildMessage: function() { - return { - name: this._name, - action: this._action, - data: this._data - }; - } -}); - -var Transaction = Message.extend({ - "override __construct": function(name, uid, manager) { - this._super(name, manager); - this._uid = uid; - this._manager = manager; - var em = this._em = new EventEmitter, oldDispose = this._em.dispose, self = this; - this._em.dispose = function() { - this.disposed = true; - oldDispose.call(em); - self.dispose(); - }; - }, - "override _buildMessage": function() { - var message = this._super(); - message.uid = this._uid; - return message; - }, - response: function(message) { - this._em.emit(message.action, message.data); - return this; - }, - on: function(listen) { - for (var type in listen) { - this.on(type, listen[type]); - } - return this; - }, - "second on": function(type, listener) { - this._em.addListener(type, listener); - return this; - }, - register: function() { - this._manager._addTransaction(this); - return this; - }, - onError: function(e) { - this._em.emit("error", e); - }, - disposeOn: function(type) { - var self = this; - return this.on(type, function() { - self.dispose(); - }); - }, - dispose: function() { - if (!this._em.disposed) this._em.dispose(); - this._manager.remove(this._uid); - } -}); - -var CommunicationManager = sardVar74({ - __construct: function(connection) { - this._connection = connection; - this._liveTransactions = {}; - this._connection._target.onMessage = this.getMethod("onMessage"); - this._em = new EventEmitter; - }, - message: function(name) { - return new Message(name, this); - }, - on: function(listen) { - for (var type in listen) { - this._em.addListener(type, listen[type]); - } - }, - onMessage: function(message) { - var trans = this._liveTransactions[message.uid]; - this._connection._hook.ignore(message.name, true); - if (trans) { - trans.response(message); - } else { - var msg; - if (message.uid) { - msg = this.request(message).action(message.action).data(message.data); - } else { - msg = this.message(message.name).action(message.action).data(message.data); - } - this._em.emit(msg._action, msg); - } - this._connection._hook.ignore(message.name, false); - return false; - }, - onDisconnect: function(err) { - for (var uid in this._liveTransactions) { - var transaction = this._liveTransactions[uid]; - transaction.response({ - action: "error", - data: "unable to fullfill request" - }).dispose(); - } - }, - transaction: function(name) { - return (new Transaction(name, this._uid(), this)).register(); - }, - request: function(message) { - return new Transaction(message.name, message.uid, this); - }, - remove: function(uid) { - var trans = this._liveTransactions[uid]; - delete this._liveTransactions[uid]; - return trans; - }, - _addTransaction: function(trans) { - this._liveTransactions[trans._uid] = trans; - }, - _uid: function() { - var uid = (new Date).getTime() + "." + Math.round(Math.random() * 99999); - while (this._liveTransactions[uid]) uid = this._uid(); - return uid; - } -}); - -var RemoteInvoker = sardVar74({ - __construct: function(hook) { - this._janitor = new Janitor; - this._hook = hook; - this.remote = Math.random(); - var self = this; - this._hook._router.on("push -pull hook", { - data: { - all: hook._target.bussed - } - }, function(hook) { - self._hook._transaction().send("hook", hook).dispose(); - }); - this.reset(); - }, - reset: function() { - this.dispose(); - this._janitor.addDisposable(this._virtualRouter = new sardVar76); - this.push = this._virtualRouter.getMethod("push"); - this.pull = this._virtualRouter.getMethod("pull"); - var self = this; - }, - dispose: function() { - this._janitor.dispose(); - }, - hook: function(type, channel) { - switch (type) { - case "push": - return this._hookPush(channel); - case "pull": - return this._hookPull(channel); - default: - return null; - } - }, - _hookPull: function(channel) { - var self = this; - this._janitor.addDisposable(this._virtualRouter.on("pull -stream " + channel, function(request) { - this.wrap(); - if (!this.inner.key) this.inner.key = self.id; - self._hook._transaction(channel).send("pull", { - hasNext: this.hasNext(), - data: this.data, - inner: this.inner - }).on(this).on({ - next: this.next - }).disposeOn("end"); - })); - }, - _hookPush: function(channel) { - var self = this; - this._janitor.addDisposable(this._virtualRouter.on("push -stream " + channel, function() { - if (!this.inner.key) this.inner.key = self.id; - var trans = self._hook._transaction(channel).send("push", { - hasNext: this.hasNext(), - inner: this.inner - }).on({ - next: this.next - }); - this.pipe({ - write: function(chunk) { - trans.send("write", chunk); - }, - end: function() { - trans.send("end").dispose(); - } - }); - })); - } -}); - -var LocalInvoker = sardVar74({ - __construct: function(connection) { - this._con = connection; - this._router = connection._router; - this._janitor = new Janitor; - }, - hook: function(type, channel, ops) { - var self = this, remoteMethod = this._con._remote.getMethod(type); - if (!ops) ops = {}; - if (!ops.meta) ops.meta = {}; - ops.meta.stream = true; - this._janitor.addDisposable(this._router.on(type + " " + channel, ops, function(localRequest) { - if (self._con._hook.ignore(channel) && (!self._con._target.bussed || !this.inner.key || !self._con._remote.id || self._con._remote.id == this.inner.key)) return; - var _next = this.hasNext() ? function() { - localRequest.next(); - } : null; - remoteMethod(channel, localRequest.data, { - meta: { - stream: true - }, - _next: _next, - inner: this.inner - }, function(remoteRequest) { - if (type == "pull") { - remoteRequest.pipe(localRequest); - } else { - localRequest.pipe(remoteRequest); - } - }); - })); - }, - reset: function() { - this._janitor.dispose(); - }, - dispose: function() { - this._janitor.dispose(); - }, - push: function(trans) { - this._router.push(" -stream " + trans._name, {}, { - from: this._con._remote, - meta: this._meta(trans, "push"), - _next: this._next(trans), - inner: this._inner(trans) - }, function(stream) { - trans.register().on(stream.wrap()).disposeOn("end"); - }); - }, - pull: function(trans) { - var id = this._con._remote.id; - this._router.pull(" -stream " + trans._name, trans._data.data, { - from: this._con._remote, - meta: this._meta(trans, "pull"), - _next: this._next(trans), - inner: this._inner(trans) - }, function() { - this.pipe({ - respond: function(response) { - trans.send("respond", response); - }, - write: function(chunk) { - trans.send("write", chunk); - }, - end: function(err) { - trans.send("end"); - trans.dispose(); - } - }); - }); - }, - _next: function(trans) { - return trans._data.hasNext ? function() { - trans.send("next"); - } : null; - }, - _inner: function(trans) { - if (!trans._data.inner.key) trans._data.inner.key = this._con._remote.id; - return trans._data.inner; - }, - _meta: function(trans, type) { - var inner = this._inner(trans); - if (inner.key != this._con._remote.id && this._router.has(trans._name, { - type: type, - meta: { - target: inner.key - } - })) { - return { - target: inner.key - }; - } - return null; - } -}); - -var Connection = sardVar74({ - __construct: function(target, hook) { - this._target = target; - this._hook = hook; - this._router = hook._router; - this._comm = new CommunicationManager(this); - this._janitor = new Janitor; - this._local = (new LocalInvoker(this)).wrap(); - this._remote = new RemoteInvoker(this); - this.janitor = new Janitor; - this._comm.on({ - push: this._local.push, - pull: this._local.pull, - hook: this.getMethod("onHook") - }); - this._onClose(); - }, - _onClose: function() { - var self = this; - this._target.onExit = function(err) { - self._comm.onDisconnect(); - self.dispose(); - }; - }, - onHook: function(trans) { - this._reset(); - var self = this, hook = trans._data; - for (var i = hook.channels.length; i--; ) { - try { - self._listen(hook.channels[i], hook); - } catch (e) {} - } - this._connected(); - return this; - }, - hook: function(type, path, ops) { - this._remote.hook(type, path, ops); - this._local.hook(type, path, ops); - }, - _connected: function() { - if (this._dispatchedConnected) return; - this._dispatchedConnected = true; - this._router.push("hook/connection", null, { - from: this._remote - }); - }, - _listen: function(channel, hook) { - var ops = { - meta: sardVar74.copy(channel.meta || {}) - }, meta = ops.meta; - ops.meta.pull = ops.meta.rotate = ops.meta.bussed = undefined; - ops.meta.stream = ops.meta.hooked = ops.meta.overridable = ops.meta["public"] = 1; - if (this._target.bussed) { - ops.meta.bussed = 1; - } - meta.target = this._remote.id = hook.id; - this.hook("push", channel.path, ops); - var route = this._router.getRoute("pull " + channel.path, ops); - if (route && route.route && route.route.meta) { - if (route.route.meta.hooked == undefined && !route.router._allowMultiple) { - return console.warn("local channel %s exists. Cannot hook remote channel.", channel.path); - } - } - this.hook("pull", channel.path, ops); - }, - _reset: function() { - this._remote.reset(); - this._local.reset(); - }, - dispose: function() { - this._remote.dispose(); - this._local.dispose(); - this.janitor.dispose(); - }, - _response: function(message) { - return this._comm.response(message); - }, - _transaction: function(name) { - return this._comm.transaction(name); - }, - _message: function(name) { - return this._comm.message(name); - } -}); - -var Hook = sardVar74({ - __construct: function(transport, router) { - this._router = router; - var connections = this._connections = [], self = this; - transport.connect(function(connection) { - var con = new Connection(connection, self); - connections.push(con); - con.janitor.addDisposable({ - dispose: function() { - var i = connections.indexOf(con); - if (i > -1) connections.splice(i, 1); - } - }); - }); - }, - ignore: function(name, value) { - if (!this._ignoring) this._ignoring = []; - var i = this._ignoring.indexOf(name); - if (value == undefined) return i > -1; - if (!value && i > -1) { - this._ignoring.splice(i, 1); - } else if (value && i == -1) { - this._ignoring.push(name); - } - } -}); - -sardModule78 = Hook; -var sardModule80 = {}; -sardModule80.callback = function(callback, timeout) { - var interval; - return function() { - clearTimeout(interval); - var args = arguments; - interval = setTimeout(function() { - callback.apply(callback, args); - }, timeout); - }; -}; - -sardModule80.lazy = { - callback: sardModule80.callback -}; -var sardModule82 = {}; -var sardVar79 = sardModule78, sardVar81 = sardModule80; - -sardModule82.plugin = function(mediator, host) { - var oldAddChannel = mediator.addChannel, readyBeans = {}, identifier; - mediator.addChannel = function(path, expr) { - oldAddChannel.apply(mediator, arguments); - lazyPush(); - }; - function init() { - mediator.pullMulti("hook/transport", function(transport) { - new sardVar79(transport, mediator); - }); - } - function onBeanReady(name) { - readyBeans[name] = 1; - mediator.on("pull " + name + "/ready", { - meta: { - "public": 1, - rotate: 1 - } - }, function() { - return true; - }); - } - function getHook(data) { - var d = data || {}; - var channels = [], ch = mediator.channels(); - for (var channel in ch) { - var expr = ch[channel]; - if (!d.all && !expr.meta.bussed && expr.meta.hooked || !expr.meta["public"]) continue; - channels.push({ - meta: expr.meta, - path: channel - }); - } - var info = { - id: identifier, - channels: channels - }; - return info; - } - function pullHook(request) { - return getHook(request.data); - } - function pushHook() { - mediator.push("hook", getHook()); - } - var lazyPush = sardVar81.callback(pushHook, 1); - function onAppId(data) { - console.log(data); - } - function setId(value) { - identifier = value; - pushHook(); - } - function onConnection(data) { - for (var bean in readyBeans) { - this.from.push(bean + "/ready", true, { - ignoreWarning: true - }); - } - } - mediator.on({ - "push init": init, - "push ready": onBeanReady, - "pull hook": pullHook, - "push set/id": setId, - "push hook/connection": onConnection - }); -}; -var sardModule85 = {}; -var sardVar84 = sardModule0; - -sardModule85 = sardVar84({ - __construct: function(socket) { - this._socket = socket; - this._id = socket.id; - var self = this; - socket.on("message", function(batch) { - batch.forEach(function(msg) { - self.onMessage(msg); - }); - }); - socket.on("disconnect", function() { - console.log("socket disconnect :%d", self._id); - self.onExit(); - }); - }, - send: function(message, callback) { - if (!this._batch) { - this._batch = []; - setTimeout(this.getMethod("_sendBatch"), 1); - } - this._batch.push(message); - }, - _sendBatch: function() { - this._socket.json.send(this._batch); - this._batch = null; - }, - onExit: function() {}, - onMessage: function() {} -}); -var sardModule87 = {}; -var sardVar86 = sardModule85; - -sardModule87.plugin = function(router) { - return { - connect: function(onConnection) { - var socket = io.connect("http://localhost:6032"), socket; - socket.on("connect", function() { - router.push("set/id", socket.socket.sessionid); - onConnection(new sardVar86(socket)); - }); - } - }; -}; -var sardModule89 = {}; -var sardVar88 = sardModule87; - -sardModule89.plugin = function(router) { - var con = sardVar88.plugin(router); - router.on({ - "pull -multi hook/transport": function() { - return con; - } - }); -}; -var sardModule91 = {}; -var beanpole = sardModule72.router(); - -function pluginExample(router) { - var name = prompt("What's your name?", "craig"); - var time = Number(prompt("When do you want an alert? (in seconds)", 1)); - function appendBody(message) { - var div = document.createElement("div"); - div.innerHTML = message; - document.body.appendChild(div); - } - router.on({ - "pull -public some/random/callback": function(request) { - appendBody(request.data.message); - this.from.push("notify/clients", request.data); - request.end(); - }, - "push send/message": function(data) { - beanpole.push("call/later", { - channel: "some/random/callback", - data: { - _id: (new Date).getTime(), - message: data.message - }, - sendAt: (new Date).getTime() + data.delay - }); - }, - "push -public notify/clients": function(data) { - appendBody("notified from another client: " + data.message); - } - }); - beanpole.on({ - "push -public -one spice.io/ready": function() { - beanpole.push("send/message", { - message: "hello " + name + "!", - name: name, - delay: time * 1e3 - }); - } - }); -} - -sardModule82.plugin(beanpole); - -sardModule89.plugin(beanpole); - -pluginExample(beanpole); - -beanpole.push("ready", "client"); - -beanpole.push("init"); diff --git a/node_modules/celeri/node_modules/beanpole/examples/ws/hook.js b/node_modules/celeri/node_modules/beanpole/examples/ws/hook.js deleted file mode 100644 index a3d4500..0000000 --- a/node_modules/celeri/node_modules/beanpole/examples/ws/hook.js +++ /dev/null @@ -1,37 +0,0 @@ -var beanpole = require('../../lib/node').router(); - - -beanpole.require(['hook.core','hook.http.mesh']); - -beanpole.on({ - - /** - */ - - 'push init': function() - { - beanpole.push('ready', 'spice.io'); - }, - - /** - */ - - - 'push -public call/later': function(data) - { - console.log('calling later'); - - var self = this; - - setTimeout(function() - { - self.from.pull(data.channel, data.data, { inner: self.inner }, function(result) - { - console.log(result) - }) - },Math.max(0, data.sendAt - new Date().getTime())); - // setTimeout() - } -}); - -beanpole.push('init'); \ No newline at end of file diff --git a/node_modules/celeri/node_modules/beanpole/examples/ws/server.js b/node_modules/celeri/node_modules/beanpole/examples/ws/server.js deleted file mode 100644 index 4ce2c61..0000000 --- a/node_modules/celeri/node_modules/beanpole/examples/ws/server.js +++ /dev/null @@ -1,40 +0,0 @@ -var beanpole = require('../../lib/node').router(); - - -beanpole.require(['hook.core','hook.socket.io.server','hook.http.mesh']); - -beanpole.on({ - - /** - */ - - 'push init': function() - { - beanpole.push('ready', 'spice.io'); - }, - - /** - */ - - - 'pull -public say/hello': function() - { - return "hello MADRE!"; - }, - - - /** - */ - - - 'push -public client/ready': function() - { - console.log("CLIENT READY"); - this.from.pull('get/name', function(name) - { - console.log(name) - }) - } -}); - -beanpole.push('init'); \ No newline at end of file diff --git a/node_modules/celeri/node_modules/beanpole/lib/core/concrete/collection.js b/node_modules/celeri/node_modules/beanpole/lib/core/concrete/collection.js deleted file mode 100644 index 3a59784..0000000 --- a/node_modules/celeri/node_modules/beanpole/lib/core/concrete/collection.js +++ /dev/null @@ -1,338 +0,0 @@ -var Structr = require('structr'), -Parser = require('./parser'), -utils = require('./utils'), -Request = require('./request'), -Janitor = require('sk/core/garbage').Janitor; - - - - - -/** - * collection for routes - */ - -/** - * IMPORTANT notes regarding this class - * 1. you can have multiple explicit middleware (/path/*) -*/ - - -var Collection = Structr({ - - /** - * Constructor. What else do you think it is? - */ - - '__construct': function(ops) - { - - //the options for the router - this._ops = ops || {}; - - //these are the channels parsed into a traversable route - this._routes = this._newRoute(); - - //these get executed whenever there's a new "on" - this._middleware = this._newRoute(); - - //the current route index. increments on every route! - this._routeIndex = 0; - }, - - /** - */ - - 'has': function(expr) - { - var routes = this.routes(expr); - - for(var i = routes.length; i--;) - { - if(routes[i].target) return true; - } - - return false; - }, - - /** - */ - - 'route': function(channel) - { - return this._route(channel.paths); - }, - - /** - */ - - 'routes': function(expr) - { - var channels = expr.channels, - routes = []; - - for(var i = channels.length; i--;) - { - routes.push(this.route(channels[i])); - } - - return routes; - }, - - /** - * listens to the given expression for any chandage - */ - - 'add': function(expr, callback) - { - var janitor = new Janitor(); - - for(var i = expr.channels.length; i--;) - { - janitor.addDisposable(this._add(expr.channels[i], expr.meta, callback)); - } - - - - return janitor; - }, - - /** - */ - - '_add': function(channel, meta, callback) - { - var paths = channel.paths, - isMiddleware = channel.isMiddleware, - middleware = channel.thru, - - //middleware isn't used explicitly. Rather, it's *injected* into the routes which ARE used. Remember that. - //explicit middleware looks like some/path/* - currentRoute = this._start(paths, isMiddleware ? this._middleware : this._routes, true); - - //some explicit middleware might already be defined, so we need to get the *one* to pass through. - var before = this._before(paths, currentRoute); - - - if(middleware) this._endMiddleware(middleware).thru = before; - - - //the final callback for the route - var listener = { - callback: callback, - - //metadata for the expression - meta: meta, - - //keeps tabs for later use (in request) - id: 'r'+(this._routeIndex++), - - //this is a queue where the first item is executed first, then on until we reach the last item - thru: middleware || before, - - isMiddleware: channel.isMiddleware, - - path: paths, - - dispose: function() - { - var i = currentRoute.listeners.indexOf(listener); - if(i > -1) currentRoute.listeners.splice(i, 1); - } - }; - - currentRoute.meta = Structr.copy(meta, currentRoute.meta); - - //at this point we can inject the listener into the current route IF it's middleware. - if(isMiddleware) this._injectMiddleware(listener, paths); - - - //now that we're in the clear, need to add the listener! - if(!currentRoute.listeners) currentRoute.listeners = []; - - - //now to add it. Please take remember, for MOST CASES, "_listeners" will only have one, especially for http / requests - currentRoute.listeners.push(listener); - - - - //the return statement allows for the item to be disposed of - return listener; - }, - - /** - */ - - '_endMiddleware': function(target) - { - var current = target || {}; - - while(current.thru) - { - current = current.thru; - } - - return current; - }, - - /** - * injects explicit middleware (/path/*) in all the routes which go through its path - */ - - '_injectMiddleware': function(listener, paths) - { - //level is only important for - listener.level = paths.length; - - //need to go through *all* routes ~ even middleware, because middleware also have - //routes to pass through ~ Inception. - var afterListeners = this._after(paths, this._routes).concat(this._after(paths, this._middleware)); - - //go through ALL items to put before this route, but make sure the item we're replacing isn't higher - //in the middleware chain, because higher methods will already *have* reference to this pass-thru - for(var i = afterListeners.length; i--;) - { - var currentListener = afterListeners[i]; - - var currentMiddleware = currentListener.thru, - previousMiddleware = currentListener; - - while(currentMiddleware) - { - if(currentMiddleware.level != undefined) - { - if(currentMiddleware.level < listener.level) - { - previousMiddleware.thru = listener; - } - break; - } - - previousMiddleware = currentMiddleware; - currentMiddleware = currentMiddleware.thru; - } - - if(!currentMiddleware) previousMiddleware.thru = listener; - } - }, - - /** - * reveals routes which must come *before* a middleware - * after beats circular references - * TODO: following code is __ugly as fuck__. - */ - - '_before': function(paths, after) - { - var current = this._middleware, - listeners = []; - - for(var i = 0, n = paths.length; i < n; i++) - { - - //this makes sure we don't get to the end for pass thrus - if(current.listeners) listeners = current.listeners; - - - var path = paths[i], - - newCurrent = path.param ? current._route._param : current._route[path.name]; - - - if(current == after || !newCurrent) break; - - current = newCurrent; - } - - - // if(current != after) - //this is a check against pass thrus to beat circular references. It *also* allows this: hello/* -> hello - if(current != after && current.listeners) listeners = current.listeners; - - return listeners[0]; - }, - - /** - * reveals everyhing that comes *after* a route (for pass-thru's) - */ - - '_after': function(paths, routes) - { - return this._flatten(this._start(paths, routes)); - }, - - /** - * returns the starting point of a route - */ - - '_route': function(paths, routes, create, retControl) - { - var control = (routes || this._routes), - current = control._route; - - for(var i = 0, n = paths.length; i < n; i++) - { - var path = paths[i], - name = path.param ? '_param' : path.name; - - if(!current[name] && create) - { - current[name] = this._newRoute(i); - } - - if(current[name]) - { - current = current[name]; - } - else - { - current = current._param; - } - - - if(!current) return {}; - - control = current; - current = current._route; - } - - - return control; - }, - - /** - */ - - '_start': function(paths, routes) - { - return this._route(paths, routes, true); - }, - - /** - */ - - '_newRoute': function(level) - { - return { _route: { }, _level: level || 0 }; - }, - - /** - * flattens all routes into a single array - */ - - '_flatten': function(route) - { - var listeners = route.listeners ? route.listeners.concat() : []; - - - for(var path in route._route) - { - listeners = listeners.concat(this._flatten(route[path] || {})); - } - - return listeners; - } -}); - - -module.exports = Collection; \ No newline at end of file diff --git a/node_modules/celeri/node_modules/beanpole/lib/core/concrete/parser.js b/node_modules/celeri/node_modules/beanpole/lib/core/concrete/parser.js deleted file mode 100644 index 1570fc8..0000000 --- a/node_modules/celeri/node_modules/beanpole/lib/core/concrete/parser.js +++ /dev/null @@ -1,595 +0,0 @@ - -var Structr = require('structr'); - -/** - * parses syntactic sugar. - - Why the hell are you using a parser for something so simple? Because I wanted to. Yeah, I could have done it in Regexp, but fuck that >.>... This - Is much more fun. - */ - - - -//follow the pattern below when adding tokens plz. - -var Token = { - - // A-Z - WORD: 1, - - // -metadata - METADATA: 1 << 1, - - - // = - PATH: 1 << 2, - - - // :param - PARAM: 1 << 3, - - // -> - TO: 1 << 4, - - // for routing - BACKSLASH: 1 << 5, - - // . - DOT: 1 << 6, - - // * - this is an auto-middleware - STAR: 1 << 7, - - // "or" - OR: 1 << 8, - - // ( - LP: 1 << 9, - - // ) - RP: 1 << 10, - - // = - EQ: 1 << 11, - - - //whitespace - WHITESPACE: 1 << 12 -}; - - -//reserved keywords -var Reversed = { - or: Token.OR -} - - -var Tokenizer = function() -{ - - //source of the string to tokenize - var source = '', - - //the position of the parser - pos = 0, - - //the current token - currentToken, - - self = this; - - - /** - * getter / setter for the source - */ - - this.source = function(value) - { - if(value) - { - source = value+' '; //padding - pos = 0; - } - - return source; - } - - /** - * next token - */ - - this.next = function(keepWhite) - { - return currentToken = nextToken(keepWhite); - } - - /** - */ - - this.peekChars = function(n) - { - return source.substr(pos, n); - } - - - - /** - */ - - this.current = function(keepWhite) - { - return currentToken || self.next(keepWhite); - } - - - /** - */ - - this.position = function() - { - return pos; - } - - /** - */ - - var nextToken = function(keepWhite, ignoreError) - { - if(!keepWhite) skipWhite(); - - if(eof()) return null; - - var c = currentChar(), ccode = c.charCodeAt(0); - - if(isWhite(ccode)) - { - - skipWhite(); - return token(' ',Token.WHITESPACE); - } - - //a-z0-9 - if(isAlpha(ccode)) - { - var w = nextPath(); - - return token(w, Reversed[w.toLowerCase()] || Token.WORD); - } - - - - switch(c) - { - - //for middleware - case '-': - if(nextChar() == '>') return token('->', Token.TO, true); - if(isAlpha(currentCharCode())) return token(nextPath(), Token.METADATA); - - error(); - - //parameters for routes - case ':': - if(isAlpha(nextCharCode())) return token(nextPath(), Token.PARAM); - - error(); - - case '/': return token('/', Token.BACKSLASH, true); - case '.': return token('.', Token.DOT, true); - case '*': return token('*', Token.STAR, true); - case '(': return token('(', Token.LP, true); - case ')': return token(')', Token.RP, true); - case '=': return token('=', Token.EQ, true); - - //path part - default: return token(nextPath(), Token.PATH); - } - - //eof - return null; - } - - var error = function() - { - throw new Error('Unexpected character "'+currentChar()+'" at position '+pos+' in "'+source+'"'); - } - - /** - */ - - var token = function(value, type, skipOne) - { - if(skipOne) nextChar(); - - - return { value: value, type: type }; - } - - - /** - */ - - var nextChar = this.nextChar = function() - { - return source[++pos]; - } - - /** - */ - - var currentChar = this.currentChar = function() - { - return source[pos]; - } - - /** - */ - - var isAlpha = this.isAlpha = function(c) - { - return (c > 96 && c < 123) || (c > 64 && c < 91) || isNumber(c) || c == 95; - } - - /** - */ - - var isWhite = this.isWhite = function(c) - { - return c == 32 || c == 9 || c == 10; - } - - /** - */ - - var isNumber = this.isNumber = function(c) - { - return c > 47 && c < 58; - } - - /** - */ - - var nextCharCode = function() - { - return nextChar().charCodeAt(0); - } - /** - */ - - var currentCharCode = function() - { - return currentChar().charCodeAt(0); - } - - /** - */ - - var rewind = function(steps) - { - pos -= (steps || 1); - } - - - /** - */ - - var skipWhite = function() - { - var end = false; - - while(!(end = eof())) - { - if(!isWhite(currentCharCode())) break; - - nextChar(); - } - return !end; - } - - - /** - */ - - var nextNumber = function() - { - var buffer = currentChar(); - - while(!eof()) - { - if(isNumber(nextCharCode())) - { - buffer += currentChar(); - } - else - { - break; - } - } - - return buffer; - } - - - /** - */ - - var nextPath = function() - { - var buffer = currentChar(); - - while(!eof()) - { - if(!isWhite(nextCharCode()) && !currentChar().match(/[\/=()]/g)) - // if(isAlpha(nextCharCode()) || isNumber(currentCharCode())) - { - buffer += currentChar(); - } - else - { - break; - } - } - - return buffer; - } - - - /** - * end of file - */ - - var eof = function() - { - return pos > source.length-2; - } -} - - -var ChannelParser = function() -{ - var tokenizer = new Tokenizer(), - cache = {}; - - /** - * parses a string into a handleable expression - */ - - this.parse = function(source) - { - if(!source) throw new Error('Source is not defined'); - - //stuff might have happened to the expression, so we need to clone it. it DEFINITELY changes - //when pull requests are made... - if(cache[source]) return Structr.copy(cache[source]); - - tokenizer.source(source); - - return Structr.copy(cache[source] = rootExpr()); - } - - - var rootExpr = function() - { - var expr = tokenizer.current(), - type, - meta = {}; - //type is not defined, but that's okay! - - if(expr.type == Token.WORD && tokenizer.isWhite(tokenizer.peekChars(1).charCodeAt(0)) && tokenizer.position() < tokenizer.source().length-1) - { - type = expr.value; - tokenizer.next(); - } - - var token, channels = []; - - while(token = tokenizer.current()) - { - switch(token.type) - { - - //-metadata=test - case Token.METADATA: - meta[token.value] = metadataValue(); - break; - - case Token.BACKSLASH: - case Token.WORD: - case Token.STAR: - channels = channels.concat(channelsExpr()); - break; - case Token.OR: - tokenizer.next(); - break; - default: - tokenizer.next(); - break; - } - } - - return { type: type, meta: meta, channels: channels }; - } - - var metadataValue = function() - { - if(tokenizer.currentChar() == '=') - { - tokenizer.next(); - var v = tokenizer.next().value; - tokenizer.next(); - return v; - } - - tokenizer.next(); - - return 1; - } - - var channelsExpr = function() - { - var channels = [], - to; - - - while(hasNext()) - { - - if(currentTypeIs(Token.LP)) - { - tokenizer.next(); - } - - - - if(currentTypeIs(Token.WORD | Token.PARAM | Token.STAR | Token.BACKSLASH)) - { - channels.push([channelPathsExpr()]); - - while(currentTypeIs(Token.OR)) - { - tokenizer.next(); - channels[channels.length-1].push(channelPathsExpr()); - } - } - else - { - break; - } - - - if(currentTypeIs(Token.RP)) - { - tokenizer.next(); - } - - if(currentTypeIs(Token.TO)) - { - tokenizer.next(); - } - } - - - var _orChannels = splitChannelExpr(channels.concat(), []), - channelsThru = []; - - for(var i = _orChannels.length; i--;) - { - var chain = Structr.copy(_orChannels[i]), - current = channel = chain[chain.length-1]; - - for(var j = chain.length-1; j--;) - { - current = current.thru = chain[j]; - } - - - channelsThru.push(channel); - } - - return channelsThru; - } - - var splitChannelExpr = function(orChannels, stack) - { - if(!orChannels.length) return [stack]; - - var current = orChannels.shift(); - - if(current.length == 1) - { - stack.push(current[0]); - - return splitChannelExpr(orChannels, stack); - } - else - { - var split = []; - - for(var i = current.length; i--;) - { - var stack2 = stack.concat(); - - stack2.push(current[i]); - - split = split.concat(splitChannelExpr(orChannels.concat(), stack2)); - } - - return split; - } - - } - - var channelPathsExpr = function(type) - { - var paths = [], - token, - isMiddleware = false, - cont = true; - - while(cont && (token = tokenizer.current())) - { - - switch(token.type) - { - case Token.WORD: - case Token.PARAM: - case Token.PATH: - paths.push({ name: token.value, param: token.type == Token.PARAM }); - break; - case Token.BACKSLASH: - break; - default: - cont = false; - break; - } - - if(cont) tokenizer.next(); - } - - if(currentTypeIs(Token.STAR)) - { - isMiddleware = true; - tokenizer.next(); - } - - - return { paths: paths, isMiddleware: isMiddleware }; - } - - - var currentToken = function(type, igError) - { - return checkToken(tokenizer.current(), type, igError); - } - - var nextToken = function(type, igError, keepWhite) - { - return checkToken(tokenizer.next(keepWhite), type, igError); - } - - var checkToken = function(token, type, igError) - { - if(!token || !(type & token.type)) - { - if(!igError) throw new Error('Unexpected token "'+(token || {}).value+'" at position '+tokenizer.position()+' in '+tokenizer.source()); - - return null; - } - - return token; - } - - var currentTypeIs = function(type) - { - var current = tokenizer.current(); - - return current && !!(type & current.type); - } - - var hasNext = function() - { - return !!tokenizer.current(); - } -} - -exports.parse = new ChannelParser().parse; \ No newline at end of file diff --git a/node_modules/celeri/node_modules/beanpole/lib/core/concrete/request.js b/node_modules/celeri/node_modules/beanpole/lib/core/concrete/request.js deleted file mode 100644 index 67606d8..0000000 --- a/node_modules/celeri/node_modules/beanpole/lib/core/concrete/request.js +++ /dev/null @@ -1,310 +0,0 @@ -var Structr = require('structr'), -Parser = require('./parser'), -utils = require('./utils'); - - -var Request = Structr({ - - /** - */ - - '__construct': function(listener, batch) - { - //data necessary for the request - this.data = batch.data; - - //inner data which is invisible to the request, but contains data which needs to get passed along - this.inner = batch.inner; - - //the end callback - this.callback = batch.callback; - - this._used = {}; - this._queue = []; - - //yes, and I know what you're thinking: why the hell are you copying data? - //Well, we work backwards, and we don't know if parameters might override data passed to the current URI - we need to be prepared for that. SO - //as we're working our way back up, data will be set, and the original data will be mapped the way it should be for the given URI - this._add(listener, Structr.copy(this.data, true), batch.paths); - - - if(batch._next) - { - this.add(batch._next); - } - - this.last = this._queue[0].target; - }, - - /** - */ - - 'init': function() - { - return this; - }, - - /** - */ - - 'hasNext': function() - { - return !!this._queue.length; - }, - - /** - */ - - 'next': function() - { - if(this._queue.length) - { - var thru = this._queue.pop(), - target = thru.target; - - this.current = target; - - if(target.paths) - { - var route = this.origin.getRoute({ channel: target }); - - this._addListeners(route.listeners, route.data, target.paths); - return this.next(); - } - - - //heavier... - /*var route = this.expandRoute(this._queue.length-1); - - if(!route) return this.next(); - - target = route.target, - thru = route.thru; - this._queue.pop();*/ - - - this.current = target; - - - if(target.isMiddleware && this._used[target.id]) return this.next(); - - //keep tabs of what's used so there's no overlap. this will happen when we get back to the router - //for middleware specified in path -> to -> route - this._used[target.id] = thru; - - this._prepare(target, thru.data, thru.hasParams, thru.paths); - - - return true; - } - - return false; - }, - - /** - * expands all the routes (middleware even). See leche for example - */ - - /*'expandThru': function() - { - - var i = 0; - - while(i < this._queue.length) - { - if(this.expandRoute(i)) - { - i++; - } - else - { - i = 0; - } - } - - },*/ - - /** - */ - - /*'expandRoute': function(index) - { - var thru = this._queue[index], - target = thru.target; - - if(target.paths) - { - this._queue.splice(index, 1); - var route = this.origin.getRoute({ channel: target }), n = this._queue.length; - - - this._addListeners(route.listeners, route.data, target.paths); - - return false; - } - - return { target: target, thru: thru }; - },*/ - - /** - */ - - 'forward': function(channel, callback) - { - return this.origin.dispatch(Parser.parse(channel), this.data, { inner: this.inner, req: this.req }, callback); - }, - - /** - */ - - 'thru': function(channel, ops) - { - var self = this; - - if(ops) Structr.copy(ops, this, true); - - - this._queue.push({ target: Parser.parse('-stream ' + channel).channels[0] }); - - this.next(); - - /*this.origin.dispatch(Parser.parse('-stream' + channel), this.data, Structr.copy({ inner: this.inner, req: this.req, _next: callback }, ops, true), function(request) - { - request.pipe(self); - })*/ - }, - - /** - */ - - '_addListeners': function(listeners, data, paths) - { - if(listeners instanceof Array) - { - for(var i = listeners.length; i--;) - { - this._add(listeners[i], data, paths); - } - return; - } - }, - - /** - * adds middleware to the END of the call stack - */ - - 'add': function(callback) - { - this._queue.unshift(this._func(callback)); - }, - - /** - * adds middleware to the beginning of the call stack - */ - - 'unshift': function(callback) - { - this._queue.push(this._func(callback)); - }, - - /** - */ - - '_func': function(callback) - { - return { target: { callback: callback }, data: {} }; - }, - - /** - */ - - '_add': function(route, data, paths) - { - var current = route, _queue = this._queue, - hasParams = false; - - if(!data) data = {}; - - while(current) - { - for(var i = paths.length; i--;) - { - var opath = paths[i], - cpath = route.path[i], - param, - value; - - - if(cpath.param && !opath.param) - { - param = cpath.name; - value = opath.name; - } - else - if(cpath.param && opath.param) - { - param = cpath.name; - value = this.data[opath.name]; - } - else - { - continue; - } - - hasParams = true; - - - this.data[param] = data[param] = value; - - - // if(!this.data[param]) this.data[param] = value; - } - - //make sure not to use the same route twice. this will happen especially with middleware specified as /middleware/* - _queue.push({ target: current, data: data, hasParams: hasParams, paths: paths }); - - current = current.thru; - } - }, - - - /** - */ - - '_prepare': function(target, data, hasParams, paths) - { - //call once, then dispose - if(target.meta && target.meta.one) - { - target.dispose(); - } - - if(hasParams) - { - Structr.copy(data, this.data,true); - } - - - if(target.path) this.currentChannel = utils.pathToString(target.path, this.data); - - this._callback(target, data); - }, - - /** - */ - - 'channelPath': function(index) - { - return utils.pathToString(this._queue[index].target.path || [], this.data); - }, - - /** - */ - - '_callback': function(target, data) - { - return target.callback.call(this, this); - } -}); - -module.exports = Request; \ No newline at end of file diff --git a/node_modules/celeri/node_modules/beanpole/lib/core/concrete/router.js b/node_modules/celeri/node_modules/beanpole/lib/core/concrete/router.js deleted file mode 100644 index 22333fe..0000000 --- a/node_modules/celeri/node_modules/beanpole/lib/core/concrete/router.js +++ /dev/null @@ -1,282 +0,0 @@ -var Structr = require('structr'), -Parser = require('./parser'), -utils = require('./utils'), -middleware = require('../middleware/meta'), -Request = require('./request'), -Collection = require('./collection'); - - - -/** - * Glorious. - */ - -var Router = Structr({ - - /** - * Constructor. What else do you think it is? - */ - - '__construct': function(ops) - { - if(!ops) ops = {}; - - this.RequestClass = ops.RequestClass || Request; - this._collection = new Collection(ops); - this._allowMultiple = !!ops.multi; - - }, - - /** - * listens to the given expression for any change - */ - - 'on': function(expr, ops, callback) - { - if(!callback) - { - callback = ops; - ops = null; - } - - for(var i = expr.channels.length; i--;) - { - var single = utils.channel(expr, i), - existingRoute = this.getRoute(single); - - if(existingRoute.listeners.length && !this._allowMultiple && !this._middleware().allowMultiple(single)) - { - var epath = existingRoute.listeners[0].path; - - //use-case: server crashes, and reboots. Needs to override current registered path (which is trash) - if(existingRoute.listeners[0].meta.overridable) - { - existingRoute.listeners[0].dispose(); - } - else - - //if both are params, then there's a collission. - if(single.channel.paths[single.channel.paths.length-1].param == epath[epath.length-1].param) - { - throw new Error('Path "'+utils.pathToString(single.channel.paths)+'" already exists'); - } - }; - - this._middleware().setRoute(channel); - } - - - return this._collection.add(expr, callback); - }, - - /** - */ - - '_middleware': function() - { - return this.controller.metaMiddleware; - }, - - /** - */ - - 'hasRoute': function(channel, data) - { - return !!this.getRoute(channel, data).listeners.length; - }, - - /** - */ - - 'hasRoutes': function(expr, data) - { - for(var i = expr.channels.length; i--;) - { - if(this.hasRoute(utils.channel(expr, i), data)) return true; - } - - return false; - }, - - /** - */ - - 'getRoute': function(single, data) - { - var route = this._collection.route(single.channel); - - var r = this._middleware().getRoute({ - expr: single, - router: this, - route: route, - data: data, - listeners: this._filterRoute(single, route) - }); - - //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! - //this chunk is experimental. Moreso to test its usefulness over anything. The initial - //thought is enable the ability for routes with *different* metadata to share the same channel. This is great - //If say, you have web-workers which use the same channels, but different cluster IDs, so a master server knows - //what data to send to what web-worker. This COULD be specified in the URI structure, but that feels a bit messy. We'll see if this works first. It's nice and clean. - //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! - if(!this._middleware().allowMultiple(route) && !this._allowMultiple && r.listeners.length) - { - r.listeners = [r.listeners[0]]; - } - - return r; - }, - - /** - */ - - 'dispatch': function(expr, data, ops, callback) - { - //only one for now. may change later on. - for(var i = expr.channels.length; i--;) - { - if(this._dispatch(utils.channel(expr, i), data, ops, callback)) return true; - } - - return false; - }, - - /** - */ - - '_dispatch': function(expr, data, ops, callback) - { - if(data instanceof Function) - { - callback = data; - data = undefined; - ops = undefined; - } - - if(ops instanceof Function) - { - callback = ops; - ops = undefined; - } - - if(!ops) ops = {}; - if(!data) data = {}; - - channel = utils.pathToString(expr.channel.paths); - - var inf = this.getRoute(expr, data); - - //warnings are good incase this shouldn't happen - if(!inf.listeners.length) - { - if(!ops.ignoreWarning && !expr.meta.passive) - { - console.warn('The %s route "%s" does not exist', expr.type, channel); - } - - //some callbacks are passive, meaning the dispatched request is *optional* ~ like a plugin - if(expr.meta.passive && callback) - { - callback(null, 'Route Exists'); - } - return false; - } - - - var newOps = { - - //router is set to controller because router() is used in loader. keeps things consistent, and using "this.controller.pull" is vague - router: this.controller, - - //where the route lives - origin: this, - - //data attached, duh. - data: inf.data, - - //inner data - inner: ops.inner || {}, - - channel: channel, - - paths: inf.expr.channel.paths, - - //the metadata attached to the expression. Tells all about how it should be handled - meta: expr.meta, - - //where is the dispatch coming from? Useful for hooks - from: ops.from || this.controller, - - //the listeners to dispatch - listeners: inf.listeners, - - //the final callback after everything's done ;) - callback: callback - }; - - Structr.copy(newOps, ops, true); - - this._callListeners(ops); - - return true; - }, - - /** - */ - - '_callListeners': function(newOps) - { - for(var i = newOps.listeners.length; i--;) - { - Structr.copy(newOps, new this.RequestClass(newOps.listeners[i], newOps), true).init().next(); - } - }, - - /** - * filters routes based on metadata - */ - - '_filterRoute': function(expr, route) - { - if(!route) return [ ]; - - var listeners = (route.listeners || []).concat(); - - - //Useful if there are groups of listeners with the same channel, but should not communicate - //with each other. E.g: two apps with slaves, sending queues to thyme. Thyme would need to know exactly where the slaves are - for(var name in expr.meta) - { - //the value of the metadata to search - var value = expr.meta[name]; - - //make sure that it's not *just* defined. This is important - //for metadata such as streams - if(value === 1) continue; - - //loop through the listeners and start filtering - for(var i = listeners.length; i--;) - { - var listener = listeners[i]; - - if(listener.meta.unfilterable) break; - - var metaV = listener.meta[name]; - - //if value == 1, then the tag just needs to exist - if(metaV != value && metaV != '*') - { - listeners.splice(i, 1); - } - } - } - - - - return listeners; - } -}); - - - -module.exports = Router; \ No newline at end of file diff --git a/node_modules/celeri/node_modules/beanpole/lib/core/concrete/utils.js b/node_modules/celeri/node_modules/beanpole/lib/core/concrete/utils.js deleted file mode 100644 index b82174c..0000000 --- a/node_modules/celeri/node_modules/beanpole/lib/core/concrete/utils.js +++ /dev/null @@ -1,115 +0,0 @@ - -/** - * replaces params of the given expression - */ - - -exports.replaceParams = function(expr, params) -{ - - var path; - - for(var i = expr.channel.paths.length; i--;) - { - path = expr.channel.paths[i]; - - if(path.param) - { - - path.param = false; - path.name = params[path.name]; - - //no name? IT MUST EXIST. DELETE! - if(!path.name) expr.channel.paths.splice(i, 1); - } - } - - return expr; -} - - -exports.channel = function(expr, index) -{ - return { type: expr.type, channel: expr.channels[index], meta: expr.meta || {} }; -} - - -exports.pathToString = function(path, data) -{ - var paths = []; - - if(!data) data = {}; - - for(var i = 0, n = path.length; i < n; i++) - { - var pt = path[i], - part; - - if(pt.param && data[pt.name]) - { - part = data[pt.name]; - } - else - { - part = pt.param ? ':' + pt.name : pt.name; - } - - paths.push(part); - } - - return paths.join('/'); -} - -//old -/*exports.channelToStr = function(channel, omit) -{ - var buffer = []; - - if(!omit) omit = []; - - if(expr.type && !omit.type) buffer.push(expr.type); - - if(!omit.meta) - for(var key in channel.meta) - { - buffer.push('-'+key+'='+expr.meta[key]); - } - - var current = expr.channel; - - var middleware = []; - - while(current) - { - var paths = []; - - for(var i = 0, n = current.paths.length; i < n; i++) - { - var path = current.paths[i]; - - paths.push((path.param ? ':' : '')+ path.name); - } - - middleware.unshift(paths.join('/')); - - current = current.thru; - } - - buffer.push(middleware.join(' -> ')); - - return buffer.join(' '); -}*/ - -exports.passThrusToArray = function(channel) -{ - var cpt = channel.thru, - thru = []; - - while(cpt) - { - thru.push(this._pathToString(cpt.paths)); - cpt = cpt.thru; - } - - return thru; -} \ No newline at end of file diff --git a/node_modules/celeri/node_modules/beanpole/lib/core/controller.js b/node_modules/celeri/node_modules/beanpole/lib/core/controller.js deleted file mode 100644 index 4180d6a..0000000 --- a/node_modules/celeri/node_modules/beanpole/lib/core/controller.js +++ /dev/null @@ -1,200 +0,0 @@ -var Structr = require('structr'), -routeMiddleware = require('./middleware/route'), -metaMiddleware = require('./middleware/meta'), -Parser = require('./concrete/parser'), -Janitor = require('sk/core/garbage').Janitor, -utils = require('./concrete/utils'); - -var AbstractController = Structr({ - - /** - */ - - - '__construct': function(target) - { - this.metaMiddleware = metaMiddleware(this); - this.routeMiddleware = routeMiddleware(this); - - this.metaMiddleware.init(); - this.routeMiddleware.init(); - - this._channels = {}; - }, - - /** - */ - - 'has': function(type, ops) - { - var expr = this._parse(type, ops); - return this._router(expr).hasRoutes(expr); - }, - - /** - */ - - 'getRoute': function(type, ops) - { - var expr = this._parse(type, ops); - return this._router(expr).getRoute(utils.channel(expr, 0)); - }, - - /** - */ - - 'on': function(target) - { - var ja = new Janitor(); - - for(var type in target) - { - ja.addDisposable(this.on(type, {}, target[type])); - } - - return ja; - }, - - /** - */ - - 'second on': function(type, callback) - { - return this.on(type, {}, callback); - }, - - /** - */ - - 'third on': function(type, ops, callback) - { - var expr = this._parse(type, ops), - router = this.routeMiddleware.router(expr); - - for(var i = expr.channels.length; i--;) - { - var pathStr = utils.pathToString(expr.channels[i].paths); - - if(!this._channels[pathStr]) - { - this.addChannel(pathStr, Structr.copy(utils.channel(expr, i))); - } - } - - return router.on(expr, ops, callback); - }, - - /** - */ - - 'channels': function() - { - return this._channels; - }, - - /** - */ - - 'addChannel': function(path, singleChannel) - { - for(var prop in singleChannel.meta) - { - singleChannel.meta[prop] = '*'; - } - - this._channels[path] = singleChannel; - }, - - /** - * flavor picker for operations. In the string, or in the ops ;) - */ - - '_parse': function(type, ops) - { - var expr = typeof type != 'object' ? Parser.parse(type) : Structr.copy(type); - - if(ops) - { - if(ops.meta) Structr.copy(ops.meta, expr.meta); - if(ops.type) expr.type = ops.type; - } - - return expr; - }, - - /** - */ - - '_router': function(expr) - { - return this.routeMiddleware.router(expr); - }, - - /** - */ - - '_createTypeMethod': function(method) - { - var self = this; - - var func = this[ method ] = function(channel, data, ops, callback) - { - if(!ops) ops = {}; - ops.type = method; - - var expr = this._parse(channel, ops); - - return self._router(expr).dispatch(expr, data, ops, callback); - } - - - var router = self._router( { type: method }); - - - Structr.copy(router, func, true); - - } -}); - - -var ConcreteController = AbstractController.extend({ - - /** - */ - - 'override __construct': function() - { - this._super(); - - var self = this; - - //make channels data-bindable - this.on({ - - /** - */ - - 'pull channels': function() - { - return self.channels(); - } - }); - }, - - /** - */ - - 'override addChannel': function(path, singleChannel) - { - this._super(path, singleChannel); - - //keep the same format as the channels so the end-point is handled exactly the same - var toPush = {}; - - toPush[path] = singleChannel; - - this.push('channels', toPush, { ignoreWarning: true }); - } -}) - -module.exports = ConcreteController; \ No newline at end of file diff --git a/node_modules/celeri/node_modules/beanpole/lib/core/index.js b/node_modules/celeri/node_modules/beanpole/lib/core/index.js deleted file mode 100644 index 3db2139..0000000 --- a/node_modules/celeri/node_modules/beanpole/lib/core/index.js +++ /dev/null @@ -1,11 +0,0 @@ -var Loader = require('./loader'); - - -//or a new, sandboxed router -exports.router = function() -{ - return new Loader(); -} - -//singleton to boot -exports.router().copyTo(module.exports, true); diff --git a/node_modules/celeri/node_modules/beanpole/lib/core/loader.js b/node_modules/celeri/node_modules/beanpole/lib/core/loader.js deleted file mode 100644 index 83ecc76..0000000 --- a/node_modules/celeri/node_modules/beanpole/lib/core/loader.js +++ /dev/null @@ -1,76 +0,0 @@ -var Structr = require('structr'), -Controller = require('./controller'); - -try -{ - require.paths.unshift(__dirname + '/beans'); -}catch(e) -{ - //break the web. -} - -var Loader = Controller.extend({ - - /** - */ - - - 'override __construct': function() - { - this._super(); - - this._params = {}; - }, - - /** - */ - - 'params': function(params) - { - if(typeof params == 'string') return this._params[params]; - - Structr.copy(params || {}, this._params); - return this; - }, - - /** - */ - - 'require': function() - { - for(var i = arguments.length; i--;) - { - this._require(arguments[i]); - } - - return this; - }, - - /** - */ - - '_require': function(source) - { - if(source instanceof Array) - { - for(var i = source.length; i--;) - { - this._require(source[i]); - } - } - else - if(typeof src == 'object' && typeof src.bean == 'function') - { - source.plugin(this._controller, source.params || this._params[ source.name ] || {}); - } - else - { - return false; - } - - return true; - } - -}); - -module.exports = Loader; diff --git a/node_modules/celeri/node_modules/beanpole/lib/core/middleware/meta/index.js b/node_modules/celeri/node_modules/beanpole/lib/core/middleware/meta/index.js deleted file mode 100644 index ecae203..0000000 --- a/node_modules/celeri/node_modules/beanpole/lib/core/middleware/meta/index.js +++ /dev/null @@ -1,138 +0,0 @@ -var Structr = require('structr'); - -module.exports = function() -{ - var mw = new exports.Middleware(); - - mw.init = function() - { - //needs to be useable online = manual - mw.add(require('./rotate')); - } - - return mw; -} - -exports.Middleware = Structr({ - - /** - */ - - '__construct': function() - { - - //middleware specific to metadata - this._toMetadata = {}; - - //middleware which handles everything - this._universal = {}; - }, - - /** - */ - - 'add': function(module) - { - var self = this; - - if(module.all) - { - module.all.forEach(function(type) - { - if(!self._universal[type]) self._universal[type] = []; - - self._universal[type].push(module); - }); - } - - module.meta.forEach(function(name) - { - self._toMetadata[name] = module; - }); - }, - - /** - */ - - 'getRoute': function(ops) - { - //parse metadata TO, and FROM - var mw = this._getMW(ops.route ? ops.route.meta : {}, 'getRoute').concat(this._getMW(ops.expr.meta)); - - return this._eachMW(ops, mw, function(cur, ops) - { - return cur.getRoute(ops); - }); - }, - - /** - */ - - 'setRoute': function(ops) - { - var mw = this._getMW(ops.meta, 'setRoute'); - - return this._eachMW(ops, mw, function(cur, ops) - { - return cur.setRoute(ops); - }); - }, - - /** - */ - - 'allowMultiple': function(expr) - { - var mw = this._getMW(expr.meta); - - for(var i = mw.length; i--;) - { - if(mw[i].allowMultiple) return true; - } - - - return false; - }, - - /** - */ - - '_getMW': function(meta, uni) - { - var mw = (this._universal[uni] || []).concat(); - - for(var name in meta) - { - if(meta[name] == undefined) continue; - - var handler = this._toMetadata[name]; - - if(handler && mw.indexOf(handler) == -1) mw.push(handler); - } - - return mw; - }, - - /** - */ - - '_eachMW': function(ops, mw, each) - { - var cops = ops, - newOps; - - - for(var i = mw.length; i--;) - { - if(newOps = each(mw[i], cops)) - { - cops = newOps; - } - } - - return cops; - } - -}); - - diff --git a/node_modules/celeri/node_modules/beanpole/lib/core/middleware/meta/rotate.js b/node_modules/celeri/node_modules/beanpole/lib/core/middleware/meta/rotate.js deleted file mode 100644 index 77ac794..0000000 --- a/node_modules/celeri/node_modules/beanpole/lib/core/middleware/meta/rotate.js +++ /dev/null @@ -1,39 +0,0 @@ - - - -exports.rotator = function(target, meta) -{ - - if(!target) target = {}; - - target.meta = [meta]; - target.allowMultiple = true; - - target.getRoute = function(ops) - { - var route = ops.route, - listeners = ops.listeners; - - - //if rotate is specified, then we need to rotate it (round-robin). There's a catch though... - //because the above *might* have filtered down to metadata values, we need to only rotate what's left, AND - //the rotate index must be stuck with the routes rotate metadata. - //Also, if the router can have multiple, then we cannot do round-robin. FUcKs ShiT Up. - if(!ops.router._allowMultiple && route && route.meta && route.meta[meta] != undefined && listeners.length) - { - route.meta[meta] = (++route.meta[meta]) % listeners.length; - - //only ONE listener now.. - ops.listeners = [listeners[route.meta[meta]]]; - } - - } - - - target.setRoute = function(ops) - { - - } -} - -exports.rotator(exports, 'rotate'); diff --git a/node_modules/celeri/node_modules/beanpole/lib/core/middleware/meta/store.js b/node_modules/celeri/node_modules/beanpole/lib/core/middleware/meta/store.js deleted file mode 100644 index 6f379ba..0000000 --- a/node_modules/celeri/node_modules/beanpole/lib/core/middleware/meta/store.js +++ /dev/null @@ -1,8 +0,0 @@ -exports.meta = ['store']; - - - -exports.getRoute = function(){}; -exports.setRoute = function(ops) -{ -}; \ No newline at end of file diff --git a/node_modules/celeri/node_modules/beanpole/lib/core/middleware/route/default/index.js b/node_modules/celeri/node_modules/beanpole/lib/core/middleware/route/default/index.js deleted file mode 100644 index 36bfc88..0000000 --- a/node_modules/celeri/node_modules/beanpole/lib/core/middleware/route/default/index.js +++ /dev/null @@ -1,13 +0,0 @@ -var Router = require('../../../concrete/router'); - -exports.types = ['dispatch']; - -exports.test = function(expr) -{ - return !expr.type || expr.type == 'dispatch' ? 'dispatch' : null; -} - -exports.newRouter = function() -{ - return new Router({multi:true}); -} \ No newline at end of file diff --git a/node_modules/celeri/node_modules/beanpole/lib/core/middleware/route/index.js b/node_modules/celeri/node_modules/beanpole/lib/core/middleware/route/index.js deleted file mode 100644 index 4d6b3c7..0000000 --- a/node_modules/celeri/node_modules/beanpole/lib/core/middleware/route/index.js +++ /dev/null @@ -1,91 +0,0 @@ -var Structr = require('structr'); - - -module.exports = function(controller) -{ - var mw = new exports.Middleware(controller); - - mw.init = function() - { - //needs to be useable online = manual - mw.add(require('./pushPull/push')); - mw.add(require('./pushPull/pull')); - mw.add(require('./default')); - } - - return mw; -} - -exports.Middleware = Structr({ - - /** - */ - - '__construct': function(controller) - { - this._middleware = []; - - this._controller = controller; - - //instantiated routers - this._routers = {}; - - //types of routers - this.types = []; - }, - - /** - */ - - 'add': function(module) - { - this._middleware.push(module); - - this.types = module.types.concat(this.types); - - for(var i = module.types.length; i--;) - { - this._controller._createTypeMethod(module.types[i]); - } - }, - - /** - */ - - 'router': function(expr) - { - for(var i = this._middleware.length; i--;) - { - //get the factory name. some middleware may return different routers depending on the expression metadata, such as pull -multi - var mw = this._middleware[i], name = mw.test(expr); - - if(name) return this._router(mw, name); - } - - return null; - }, - - /** - */ - - '_router': function(tester, name) - { - return this._routers[ name ] || this._newRouter(tester, name); - }, - - /** - */ - - '_newRouter': function(tester, name) - { - var router = tester.newRouter(name); - - router.type = name; - router.controller = this._controller; - - this._routers[ name ] = router; - - return router; - } -}); - diff --git a/node_modules/celeri/node_modules/beanpole/lib/core/middleware/route/pushPull/pull/index.js b/node_modules/celeri/node_modules/beanpole/lib/core/middleware/route/pushPull/pull/index.js deleted file mode 100644 index 7554036..0000000 --- a/node_modules/celeri/node_modules/beanpole/lib/core/middleware/route/pushPull/pull/index.js +++ /dev/null @@ -1,19 +0,0 @@ -var Router = require('../../../../concrete/router'), -Request = require('./request'); - -exports.types = ['pull','pullMulti']; - -exports.test = function(expr) -{ - if(expr.type == 'pullMulti') return 'pullMulti'; - return expr.type == 'pull' ? (expr.meta && expr.meta.multi ? 'pullMulti' : 'pull') : null; -} - -exports.newRouter = function(type) -{ - var ops = { RequestClass: Request }; - - if(type == 'pullMulti') ops.multi = true; - - return new Router(ops); -} \ No newline at end of file diff --git a/node_modules/celeri/node_modules/beanpole/lib/core/middleware/route/pushPull/pull/request.js b/node_modules/celeri/node_modules/beanpole/lib/core/middleware/route/pushPull/pull/request.js deleted file mode 100644 index 1b3ecf5..0000000 --- a/node_modules/celeri/node_modules/beanpole/lib/core/middleware/route/pushPull/pull/request.js +++ /dev/null @@ -1,45 +0,0 @@ -var Request = require('../request'), - Structr = require('structr'); - - -var PullRequest = Request.extend({ - - /** - */ - - 'override init': function() - { - this._super(); - - this._listen(this.callback, this.meta); - - return this; - }, - - /** - */ - - 'override _callback': function() - { - var ret = this._super.apply(this, arguments); - - if(ret != undefined) - { - if(ret == true) - { - } - - if(ret.send) - { - ret.send(this); - } - else - { - this.end(ret); - } - } - } -}); - - -module.exports = PullRequest; diff --git a/node_modules/celeri/node_modules/beanpole/lib/core/middleware/route/pushPull/push/index.js b/node_modules/celeri/node_modules/beanpole/lib/core/middleware/route/pushPull/push/index.js deleted file mode 100644 index 4316c1f..0000000 --- a/node_modules/celeri/node_modules/beanpole/lib/core/middleware/route/pushPull/push/index.js +++ /dev/null @@ -1,14 +0,0 @@ -var Router = require('./router'), -PushRequest = require('./request'); - -exports.types = ['push']; - -exports.test = function(expr) -{ - return expr.type == 'push' ? 'push' : null; -} - -exports.newRouter = function() -{ - return new Router({ multi: true, RequestClass: PushRequest }); -} \ No newline at end of file diff --git a/node_modules/celeri/node_modules/beanpole/lib/core/middleware/route/pushPull/push/request.js b/node_modules/celeri/node_modules/beanpole/lib/core/middleware/route/pushPull/push/request.js deleted file mode 100644 index 363a562..0000000 --- a/node_modules/celeri/node_modules/beanpole/lib/core/middleware/route/pushPull/push/request.js +++ /dev/null @@ -1,30 +0,0 @@ -var Stream = require('../stream'), - PushPullRequest = require('../request'); - - -var PushRequest = PushPullRequest.extend({ - - /** - */ - - 'override init': function() - { - this._super(); - - this.cache(); - this.stream.pipe(this); - - - return this; - }, - - /** - */ - - 'override _callback': function(route, data) - { - this._listen(route.callback, route.meta || {}); - } -}); - -module.exports = PushRequest; diff --git a/node_modules/celeri/node_modules/beanpole/lib/core/middleware/route/pushPull/push/router.js b/node_modules/celeri/node_modules/beanpole/lib/core/middleware/route/pushPull/push/router.js deleted file mode 100644 index 5f38709..0000000 --- a/node_modules/celeri/node_modules/beanpole/lib/core/middleware/route/pushPull/push/router.js +++ /dev/null @@ -1,63 +0,0 @@ -var Router = require('../../../../concrete/router'), -Stream = require('../stream'), -utils = require('../../../../concrete/utils'), -Structr = require('structr'); - - -var PushRouter = Router.extend({ - - /** - */ - - 'override on': function(expr, ops, callback) - { - if(!callback) - { - callback = ops; - ops = {}; - } - - var ret = this._super(expr, ops, callback); - - - if(expr.meta.pull) - { - this.controller.pull(expr, Structr.copy(ops.data), { ignoreWarning: true }, callback); - } - - return ret; - }, - - /** - */ - - 'override _callListeners': function(ops) - { - - //the stream for pushing content. must be cached incase there's latency. - var stream = new Stream(true), - - //no callback? then data's just being pushed, which is okay - callback = ops.callback || function(stream) - { - return ops.data; - } - - //of there's a callback, it can return a value which is pushed to the stream - var ret = callback(stream); - - //IF there's a value, then we're done - if(ret != undefined) - { - stream.end(ret); - } - - //make the stream visible to all listeners - ops.stream = stream; - - //SHIBLAM. call the listeners ;) - this._super.apply(this, arguments); - } -}); - -module.exports = PushRouter; diff --git a/node_modules/celeri/node_modules/beanpole/lib/core/middleware/route/pushPull/request.js b/node_modules/celeri/node_modules/beanpole/lib/core/middleware/route/pushPull/request.js deleted file mode 100644 index 326cb9a..0000000 --- a/node_modules/celeri/node_modules/beanpole/lib/core/middleware/route/pushPull/request.js +++ /dev/null @@ -1,88 +0,0 @@ -var Request = require('../../../concrete/request'), -Stream = require('./stream'), -Structr = require('structr'); - -/** - */ - -var PushPullRequest = Request.extend(Structr.copy(Stream.proto, { - - /** - */ - - 'init': function() - { - this._init(); - - return this; - }, - - /** - */ - - '_listen': function(listener, meta) - { - //because the framework needs to be easy to use, streams are turned off by default. This - //would be a huge pain in the pass if every time they're required, but they're SUPER important - //if we're trying to stream a large amount of data. What about HTTP? So if it's false, we need to - //add a stream handler. - if(!meta.stream) - { - //the buffer for the streams - var buffer = [], self = this; - - function end(err) - { - if(err) return; - - //again, it would be a pain in the ass if everytimg we have to do: var value = response[0]. So - //a "batch" must be specified if we're expecting an array, because 99% of the time for in-app route handling, - //only ONE value will be returned. - if(meta.batch) - { - listener.call(self, buffer, err, self); - } - else - { - if(!buffer.length) - { - listener(); - } - else - //so again, by default callback the listener as many times as there are batch values - for(var i = 0, n = buffer.length; i < n; i++) - { - listener.call(self, buffer[i], err, self); - } - } - } - - this.pipe({ - - - //on write, throw the data into the buffer - write: function(data) - { - buffer.push(data); - }, - - error: end, - - //on end, callback the listener - end: end - }); - } - - //is the listener expecting a stream? Okay, then pass on the writer to the listener. Only use this for files, http requests, and the - //likes plz, omg you're code would look like shit otherwise >.> - else - { - //more flavor picking. Use this, or the passed obj - listener.call(this, this); - } - } -})); - - - -module.exports = PushPullRequest; diff --git a/node_modules/celeri/node_modules/beanpole/lib/core/middleware/route/pushPull/stream.js b/node_modules/celeri/node_modules/beanpole/lib/core/middleware/route/pushPull/stream.js deleted file mode 100644 index d373ec5..0000000 --- a/node_modules/celeri/node_modules/beanpole/lib/core/middleware/route/pushPull/stream.js +++ /dev/null @@ -1,209 +0,0 @@ -var Structr = require('structr'), -EventEmitter = require('sk/core/events').EventEmitter; - -/** - the bridge between the listener, and responder. Yeah, Yeah. the listener -94 */ - -var proto = { - - /** - */ - - '_init': function(ttl) - { - this._em = new EventEmitter(); - - this.response = {}; - - if(ttl) - { - this.cache(ttl); - } - }, - - /** - */ - - 'cache': function(ttl) - { - if(this._caching) return; - this._caching = true; - - - //store the buffer incase data comes a little quicker than we can handle it. - var buffer = this._buffer = [], self = this; - - this.on({ - write: function(chunk) - { - buffer.push(chunk) - } - }); - }, - - /** - */ - - 'on': function(listeners) - { - for(var type in listeners) - { - this._em.addListener(type, listeners[type]); - } - }, - - - /** - */ - - 'second on': function(type, callback) - { - this._em.addListener(type, callback); - }, - - /** - */ - - 'respond': function(data) - { - this.responded = true; - - Structr.copy(data, this.response, true); - - return this; - }, - - /** - */ - - 'error': function(data) - { - if(!data) return this._error; - this._error = data; - this._em.emit('error', data); - return this; - }, - - /** - */ - - '_sendResponse': function() - { - if(!this._sentResponse) - { - this._sentResponse = true; - - //WHOOAAHH, what are you doing!? Okay, I know it looks stupid, it is. BUT, consider this scenario: - //via HTTP, the session object is *saved* to the database once toJSON is called, which is ONLY called when *this* happens. We do not want - //the session to save before we're done writing to it, or handling it. - this.response = JSON.parse(JSON.stringify(this.response)); - - this._em.emit('response', this.response); - - return true; - } - - return false; - }, - - /** - */ - - - 'write': function(data) - { - this._sendResponse(); - - this._em.emit('write', data); - - return this; - }, - - /** - */ - - 'end': function(data) - { - //SUPER NOTE: end can be called *once*. After that, all the listeners are disposed of - if(data) this.write(data); - - this._sendResponse(); - - this.finished = true; - - this._em.emit('end', data); - - //remove the event listeners to avoid mem leaks - this._em.dispose(); - - return this; - }, - - /** - */ - - 'pipe': function(stream) - { - - //IF there is a buffer, that means it came faster than we can handle it. This sort of thing - //occurrs when there are pass-thru routes which hold up the final callback. e.g: authenticating a user against - //a database - // if(stream.response) stream.response = this.response; - - if(stream.respond && this.responded) stream.respond(this.response); - - if(this._buffer && this._buffer.length) - { - for(var i = 0, n = this._buffer.length; i < n; i++) - { - stream.write(this._buffer[i]); - } - } - - //already finished? return - if(this.finished) - { - return stream.end(); - } - - //looks like the bridge is still handling data, so listen for the rest - this.on({ - write: function(data) - { - if(stream.write) stream.write(data); - }, - end: function() - { - if(stream.end) stream.end(); - }, - error: function(e) - { - if(stream.error) stream.error(e); - }, - response: function(data) - { - if(stream.respond) stream.respond(data); - } - }); - } -}; - -var Stream = Structr(Structr.copy(proto, { - - /** - * @param the current request - * @param ttl time to keep cached version in memory before dumping it - */ - - '__construct': function(ttl) - { - this._init(ttl); - } - -})); - -Stream.proto = proto; - - -module.exports = Stream; \ No newline at end of file diff --git a/node_modules/celeri/node_modules/beanpole/lib/node/beans/system.core/index.js b/node_modules/celeri/node_modules/beanpole/lib/node/beans/system.core/index.js deleted file mode 100644 index d1ebe48..0000000 --- a/node_modules/celeri/node_modules/beanpole/lib/node/beans/system.core/index.js +++ /dev/null @@ -1,26 +0,0 @@ -var exec = require('child_process').exec; - -exports.plugin = function(router) -{ - - router.on({ - - /** - */ - - 'push init': function() - { - exec('hostname', function(err, hostname) - { - router.on('pull hostname', function() - { - return hostname; - }); - - router.push('hostname', hostname.replace('\n','')); - }); - }, - - - }) -} \ No newline at end of file diff --git a/node_modules/celeri/node_modules/beanpole/lib/node/index.js b/node_modules/celeri/node_modules/beanpole/lib/node/index.js deleted file mode 100644 index 4a0eae2..0000000 --- a/node_modules/celeri/node_modules/beanpole/lib/node/index.js +++ /dev/null @@ -1,21 +0,0 @@ -require('sk/node/log'); - -//need this for global beanpole ~ not cached with NPM. -if(global.beanpole) -{ - module.exports = global.beanpole; -} -else -{ - var Loader = require('./loader'); - - exports.router = function() - { - return new Loader(); - } - - - exports.router().copyTo(module.exports, true); - - global.beanpole = module.exports; -} \ No newline at end of file diff --git a/node_modules/celeri/node_modules/beanpole/lib/node/loader.js b/node_modules/celeri/node_modules/beanpole/lib/node/loader.js deleted file mode 100644 index 98f8eed..0000000 --- a/node_modules/celeri/node_modules/beanpole/lib/node/loader.js +++ /dev/null @@ -1,171 +0,0 @@ -var Structr = require('structr'), -Loader = require('../core/loader'), -fs = require('fs'), -pt = require('path'); - -//let coffeescript inject require hooks -require('coffee-script'); - -function unableToLoad(bean) -{ - console.error('Unable to load bean "%s"', bean); -} - - -//replaces relative paths, with abs paths for beans. Primarily used for the package.json -//config -function replaceRelWithAbsPath(config, cwd) -{ - for(var property in config) - { - var value = config[property]; - - if(typeof value == 'string' && value.substr(0,2) == './') - { - config[property] = fs.realpathSync(cwd+value.substr(1)); - } - else - if(value instanceof Object) - { - replaceRelWithAbsPath(value, cwd); - } - } - - - return config; -} - - -//quick, temporary fix for node > 5.x. breaks -try -{ - require.paths.unshift(__dirname + '/beans'); -} -catch(e) -{ - -} -var NodeLoader = Loader.extend({ - - /** - */ - - - 'override __construct': function() - { - this._super(); - - this._loaded = []; - }, - - /** - */ - - 'override _require': function(source) - { - if(!this._super(source)) - { - if(typeof source == 'object') - { - for(var bean in source) - { - this._require2(bean).plugin(this, source[bean]); - } - } - else - if(typeof source == 'string') - { - var bean, self = this, basename = pt.basename(source); - - - if(basename == 'package.json') - { - var pkg = JSON.parse(fs.readFileSync(source, 'utf8')); - - for(var bean in pkg.beans) - { - var params = pkg.beans[bean], - plugin = self._require2(bean); - - - if(!plugin) - { - unableToLoad(bean); - continue; - } - - - plugin.plugin(self, replaceRelWithAbsPath(typeof params != 'boolean' ? params : self._params[bean] || {}, pt.dirname(source))); - } - } - else - if(!(bean = this._require2(source))) - { - try - { - - //NOT a bean, but a directory for the beans. - fs.readdirSync(source).forEach(function(name) - { - //hidden file - if(name.substr(0,1) == '.') return; - - self._require2(source + '/' + name).plugin(self, self._params[name] || {}); - }); - } - catch(e) - { - console.log(e.stack) - console.warn('Unable to load beans from directory %s', source); - unableToLoad(source); - } - } - else - { - bean.plugin(this, self._params[source.split('/').pop()] || {}); - } - } - else - { - return false; - } - - return this; - } - - //this gets hit if old require is true - return this; - }, - - /** - */ - - '_require2': function(bean) - { - try - { - var path = require.resolve(bean); - } - catch(e) - { - return false; - } - - var ret = require(bean), - name = pt.dirname(path).split('/').pop(); - - - if(this._loaded.indexOf(path) > -1) - { - console.notice('Cannot reload bean "%s"', bean); - - return { plugin: function() {} }; - } - - this._loaded.push(path); - - return ret; - } -}); - -module.exports = NodeLoader; diff --git a/node_modules/celeri/node_modules/beanpole/lib/web/index.js b/node_modules/celeri/node_modules/beanpole/lib/web/index.js deleted file mode 100644 index 36572d8..0000000 --- a/node_modules/celeri/node_modules/beanpole/lib/web/index.js +++ /dev/null @@ -1 +0,0 @@ -module.exports = require('../core') \ No newline at end of file diff --git a/node_modules/celeri/node_modules/beanpole/package.json b/node_modules/celeri/node_modules/beanpole/package.json deleted file mode 100644 index 21e4b72..0000000 --- a/node_modules/celeri/node_modules/beanpole/package.json +++ /dev/null @@ -1,25 +0,0 @@ -{ - "name": "beanpole", - "description": "Routing on Steroids", - "version": "0.1.16", - "author": "Craig Condon", - "repository": { - "type": "git", - "url": "http://github.com/crcn/beanpole.git" - }, - "directories" : { "lib" : "./lib" }, - "dependencies": { - "sk":"*", - "vine":"*", - "mime":"*", - "gumbo":"*", - "cashew":"*", - "structr":"*", - "coffee-script":"*" - }, - "devDependencies": { - "ebnf-diagram":"*" - }, - - "main": "./lib/node/index.js" -} diff --git a/node_modules/celeri/node_modules/beanpole/project.sublime-project b/node_modules/celeri/node_modules/beanpole/project.sublime-project deleted file mode 100644 index 00dbc17..0000000 --- a/node_modules/celeri/node_modules/beanpole/project.sublime-project +++ /dev/null @@ -1,23 +0,0 @@ -{ - "folders": - [ - { - "path": "." - } - ], - "build_systems": - [ - { - "name":"cbd make", - "cmd":["cbd","make","beanpole"] - }, - { - "name":"cbd start", - "cmd":["cbd","start","beanpole"] - }, - { - "name":"cbd make+start", - "cmd":["cbd","make+start","beanpole"] - } - ] -} \ No newline at end of file diff --git a/node_modules/celeri/node_modules/beanpole/project.tmproj b/node_modules/celeri/node_modules/beanpole/project.tmproj deleted file mode 100644 index ff44ef4..0000000 --- a/node_modules/celeri/node_modules/beanpole/project.tmproj +++ /dev/null @@ -1,168 +0,0 @@ - - - - - currentDocument - lib/core/concrete/router.js - documents - - - expanded - - name - project - regexFolderFilter - !.*/(\.[^/]*|CVS|_darcs|_MTN|\{arch\}|blib|.*~\.nib|.*\.(framework|app|pbproj|pbxproj|xcode(proj)?|bundle))$ - sourceDirectory - - - - fileHierarchyDrawerWidth - 200 - metaData - - MIT-LICENSE.txt - - caret - - column - 61 - line - 10 - - firstVisibleColumn - 0 - firstVisibleLine - 0 - - docs/beans/README.md - - caret - - column - 8 - line - 43 - - columnSelection - - firstVisibleColumn - 0 - firstVisibleLine - 0 - selectFrom - - column - 2 - line - 43 - - selectTo - - column - 8 - line - 43 - - - examples/ws/client/release/index.js - - caret - - column - 0 - line - 1232 - - firstVisibleColumn - 0 - firstVisibleLine - 1216 - - lib/core/concrete/router.js - - caret - - column - 7 - line - 266 - - firstVisibleColumn - 0 - firstVisibleLine - 234 - - lib/core/controller.js - - caret - - column - 4 - line - 9 - - firstVisibleColumn - 0 - firstVisibleLine - 0 - - lib/core/index.js - - caret - - column - 0 - line - 0 - - firstVisibleColumn - 0 - firstVisibleLine - 0 - - lib/core/loader.js - - caret - - column - 1 - line - 7 - - firstVisibleColumn - 0 - firstVisibleLine - 0 - - lib/core/middleware/route/pushPull/push/router.js - - caret - - column - 4 - line - 9 - - firstVisibleColumn - 0 - firstVisibleLine - 17 - - - openDocuments - - MIT-LICENSE.txt - docs/beans/README.md - examples/ws/client/release/index.js - lib/core/controller.js - lib/core/loader.js - lib/core/concrete/router.js - lib/core/index.js - - showFileHierarchyDrawer - - windowFrame - {{210, 4}, {1230, 874}} - - diff --git a/node_modules/celeri/node_modules/colors/MIT-LICENSE.txt b/node_modules/celeri/node_modules/colors/MIT-LICENSE.txt deleted file mode 100644 index 7df0d5e..0000000 --- a/node_modules/celeri/node_modules/colors/MIT-LICENSE.txt +++ /dev/null @@ -1,19 +0,0 @@ -Copyright (c) 2010 Alexis Sellier (cloudhead) , Marak Squires - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. \ No newline at end of file diff --git a/node_modules/celeri/node_modules/colors/ReadMe.md b/node_modules/celeri/node_modules/colors/ReadMe.md deleted file mode 100644 index 74acead..0000000 --- a/node_modules/celeri/node_modules/colors/ReadMe.md +++ /dev/null @@ -1,30 +0,0 @@ -

colors.js - get color and style in your node.js console like what

- - - - var sys = require('sys'); - var colors = require('./colors'); - - sys.puts('hello'.green); // outputs green text - sys.puts('i like cake and pies'.underline.red) // outputs red underlined text - sys.puts('inverse the color'.inverse); // inverses the color - sys.puts('OMG Rainbows!'.rainbow); // rainbow (ignores spaces) - -

colors and styles!

-- bold -- italic -- underline -- inverse -- yellow -- cyan -- white -- magenta -- green -- red -- grey -- blue - - -### Authors - -#### Alexis Sellier (cloudhead) , Marak Squires , Justin Campbell, Dustin Diaz (@ded) diff --git a/node_modules/celeri/node_modules/colors/colors.js b/node_modules/celeri/node_modules/colors/colors.js deleted file mode 100644 index 8c1d706..0000000 --- a/node_modules/celeri/node_modules/colors/colors.js +++ /dev/null @@ -1,230 +0,0 @@ -/* -colors.js - -Copyright (c) 2010 Alexis Sellier (cloudhead) , Marak Squires - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. - -*/ - -exports.mode = "console"; - -// prototypes the string object to have additional method calls that add terminal colors - -var addProperty = function (color, func) { - exports[color] = function(str) { - return func.apply(str); - }; - String.prototype.__defineGetter__(color, func); -} - -var isHeadless = (typeof module !== 'undefined'); -['bold', 'underline', 'italic', 'inverse', 'grey', 'black', 'yellow', 'red', 'green', 'blue', 'white', 'cyan', 'magenta'].forEach(function (style) { - - // __defineGetter__ at the least works in more browsers - // http://robertnyman.com/javascript/javascript-getters-setters.html - // Object.defineProperty only works in Chrome - addProperty(style, function () { - return isHeadless ? - stylize(this, style) : // for those running in node (headless environments) - this.replace(/( )/, '$1'); // and for those running in browsers: - // re: ^ you'd think 'return this' works (but doesn't) so replace coerces the string to be a real string - }); -}); - -// prototypes string with method "rainbow" -// rainbow will apply a the color spectrum to a string, changing colors every letter -addProperty('rainbow', function () { - if (!isHeadless) { - return this.replace(/( )/, '$1'); - } - var rainbowcolors = ['red','yellow','green','blue','magenta']; //RoY G BiV - var exploded = this.split(""); - var i=0; - exploded = exploded.map(function(letter) { - if (letter==" ") { - return letter; - } - else { - return stylize(letter,rainbowcolors[i++ % rainbowcolors.length]); - } - }); - return exploded.join(""); -}); - -function stylize(str, style) { - if (exports.mode == 'console') { - var styles = { - //styles - 'bold' : ['\033[1m', '\033[22m'], - 'italic' : ['\033[3m', '\033[23m'], - 'underline' : ['\033[4m', '\033[24m'], - 'inverse' : ['\033[7m', '\033[27m'], - //grayscale - 'white' : ['\033[37m', '\033[39m'], - 'grey' : ['\033[90m', '\033[39m'], - 'black' : ['\033[30m', '\033[39m'], - //colors - 'blue' : ['\033[34m', '\033[39m'], - 'cyan' : ['\033[36m', '\033[39m'], - 'green' : ['\033[32m', '\033[39m'], - 'magenta' : ['\033[35m', '\033[39m'], - 'red' : ['\033[31m', '\033[39m'], - 'yellow' : ['\033[33m', '\033[39m'] - }; - } else if (exports.mode == 'browser') { - var styles = { - //styles - 'bold' : ['', ''], - 'italic' : ['', ''], - 'underline' : ['', ''], - 'inverse' : ['', ''], - //grayscale - 'white' : ['', ''], - 'grey' : ['', ''], - 'black' : ['', ''], - //colors - 'blue' : ['', ''], - 'cyan' : ['', ''], - 'green' : ['', ''], - 'magenta' : ['', ''], - 'red' : ['', ''], - 'yellow' : ['', ''] - }; - } else if (exports.mode == 'none') { - return str; - } else { - console.log('unsupported mode, try "browser", "console" or "none"'); - } - - return styles[style][0] + str + styles[style][1]; -}; - -// don't summon zalgo -addProperty('zalgo', function () { - return zalgo(this); -}); - -// please no -function zalgo(text, options) { - var soul = { - "up" : [ - '̍','̎','̄','̅', - '̿','̑','̆','̐', - '͒','͗','͑','̇', - '̈','̊','͂','̓', - '̈','͊','͋','͌', - '̃','̂','̌','͐', - '̀','́','̋','̏', - '̒','̓','̔','̽', - '̉','ͣ','ͤ','ͥ', - 'ͦ','ͧ','ͨ','ͩ', - 'ͪ','ͫ','ͬ','ͭ', - 'ͮ','ͯ','̾','͛', - '͆','̚' - ], - "down" : [ - '̖','̗','̘','̙', - '̜','̝','̞','̟', - '̠','̤','̥','̦', - '̩','̪','̫','̬', - '̭','̮','̯','̰', - '̱','̲','̳','̹', - '̺','̻','̼','ͅ', - '͇','͈','͉','͍', - '͎','͓','͔','͕', - '͖','͙','͚','̣' - ], - "mid" : [ - '̕','̛','̀','́', - '͘','̡','̢','̧', - '̨','̴','̵','̶', - '͜','͝','͞', - '͟','͠','͢','̸', - '̷','͡',' ҉' - ] - }, - all = [].concat(soul.up, soul.down, soul.mid), - zalgo = {}; - - function randomNumber(range) { - r = Math.floor(Math.random()*range); - return r; - }; - - function is_char(character) { - var bool = false; - all.filter(function(i){ - bool = (i == character); - }); - return bool; - } - - function heComes(text, options){ - result = ''; - options = options || {}; - options["up"] = options["up"] || true; - options["mid"] = options["mid"] || true; - options["down"] = options["down"] || true; - options["size"] = options["size"] || "maxi"; - var counts; - text = text.split(''); - for(var l in text){ - if(is_char(l)) { continue; } - result = result + text[l]; - - counts = {"up" : 0, "down" : 0, "mid" : 0}; - - switch(options.size) { - case 'mini': - counts.up = randomNumber(8); - counts.min= randomNumber(2); - counts.down = randomNumber(8); - break; - case 'maxi': - counts.up = randomNumber(16) + 3; - counts.min = randomNumber(4) + 1; - counts.down = randomNumber(64) + 3; - break; - default: - counts.up = randomNumber(8) + 1; - counts.mid = randomNumber(6) / 2; - counts.down= randomNumber(8) + 1; - break; - } - - var arr = ["up", "mid", "down"]; - for(var d in arr){ - var index = arr[d]; - for (var i = 0 ; i <= counts[index]; i++) - { - if(options[index]) { - result = result + soul[index][randomNumber(soul[index].length)]; - } - } - } - } - return result; - }; - return heComes(text); -} - -addProperty('stripColors', function() { - return ("" + this).replace(/\u001b\[\d+m/g,''); -}); diff --git a/node_modules/celeri/node_modules/colors/example.html b/node_modules/celeri/node_modules/colors/example.html deleted file mode 100644 index c9cd68c..0000000 --- a/node_modules/celeri/node_modules/colors/example.html +++ /dev/null @@ -1,20 +0,0 @@ - - - - - Colors Example - - - - - - - \ No newline at end of file diff --git a/node_modules/celeri/node_modules/colors/example.js b/node_modules/celeri/node_modules/colors/example.js deleted file mode 100644 index 12d8b1a..0000000 --- a/node_modules/celeri/node_modules/colors/example.js +++ /dev/null @@ -1,20 +0,0 @@ -var util = require('util'); -var colors = require('./colors'); - -//colors.mode = "browser"; - -var test = colors.red("hopefully colorless output"); -util.puts('Rainbows are fun!'.rainbow); -util.puts('So '.italic + 'are'.underline + ' styles! '.bold + 'inverse'.inverse); // styles not widely supported -util.puts('Chains are also cool.'.bold.italic.underline.red); // styles not widely supported -//util.puts('zalgo time!'.zalgo); -util.puts(test.stripColors); -util.puts("a".grey + " b".black); - -util.puts(colors.rainbow('Rainbows are fun!')); -util.puts(colors.italic('So ') + colors.underline('are') + colors.bold(' styles! ') + colors.inverse('inverse')); // styles not widely supported -util.puts(colors.bold(colors.italic(colors.underline(colors.red('Chains are also cool.'))))); // styles not widely supported -//util.puts(colors.zalgo('zalgo time!')); -util.puts(colors.stripColors(test)); -util.puts(colors.grey("a") + colors.black(" b")); - diff --git a/node_modules/celeri/node_modules/colors/package.json b/node_modules/celeri/node_modules/colors/package.json deleted file mode 100644 index 8fffef5..0000000 --- a/node_modules/celeri/node_modules/colors/package.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "name": "colors", - "description": "get colors in your node.js console like what", - "version": "0.5.1", - "author": "Marak Squires", - "repository": { - "type": "git", - "url": "http://github.com/Marak/colors.js.git" - }, - "engines": { - "node": ">=0.1.90" - }, - "main": "colors" -} diff --git a/node_modules/celeri/node_modules/structr/package.json b/node_modules/celeri/node_modules/structr/package.json deleted file mode 100644 index 95d53c7..0000000 --- a/node_modules/celeri/node_modules/structr/package.json +++ /dev/null @@ -1,11 +0,0 @@ -{ - "name": "structr", - "description": "Clean OO structure for Javascript.", - "version": "0.0.10", - "author": "Craig Condon", - "repository": { - "type": "git", - "url": "http://github.com/spiceapps/Structr.git" - }, - "main": "./structr.js" -} diff --git a/node_modules/celeri/node_modules/structr/structr.js b/node_modules/celeri/node_modules/structr/structr.js deleted file mode 100644 index 7a8ffa7..0000000 --- a/node_modules/celeri/node_modules/structr/structr.js +++ /dev/null @@ -1,488 +0,0 @@ -var Structr = function (target, parent) -{ - if (!parent) parent = Structr.fh({}); - - var that = Structr.extend.apply(null, [parent].concat(target)) - - that.__construct.prototype = that; - - if(!that.__construct.extend) - //allow for easy extending. - that.__construct.extend = function() - { - return Structr(Structr.argsToArray(arguments), that); - }; - - //return the constructor - return that.__construct; -}; - - -Structr.argsToArray = function(args) -{ - var ar = new Array(args.length); - for(var i = args.length; i--;) ar[i] = args[i]; - return ar; -} - -Structr.copy = function (from, to, lite) -{ - if(typeof to == 'boolean') - { - lite = to; - to = undefined; - } - - if (!to) to = from instanceof Array ? [] : {}; - - var i; - - for(i in from) - { - var fromValue = from[i], - toValue = to[i], - newValue; - - //don't copy anything fancy other than objects and arrays. this could really screw classes up, such as dates.... (yuck) - if (!lite && typeof fromValue == 'object' && (!fromValue || fromValue.__proto__ == Object.prototype || fromValue.__proto__ == Array.prototype)) - { - - //if the toValue exists, and the fromValue is the same data type as the TO value, then - //merge the FROM value with the TO value, instead of replacing it - if (toValue && fromValue instanceof toValue.constructor) - { - newValue = toValue; - } - - //otherwise replace it, because FROM has priority over TO - else - { - newValue = fromValue instanceof Array ? [] : {}; - } - - Structr.copy(fromValue, newValue); - } - else - { - newValue = fromValue; - } - - to[i] = newValue; - } - - return to; -}; - - -//returns a method owned by an object -Structr.getMethod = function (that, property) -{ - return function() - { - return that[property].apply(that, arguments); - }; -}; - -Structr.wrap = function(that, prop) -{ - if(that._wrapped) return that; - - that._wrapped = true; - - function wrap(target) - { - return function() - { - return target.apply(that, arguments); - } - } - - if(prop) - { - that[prop] = wrap(target[prop]); - return that; - } - - for(var property in that) - { - var target = that[property]; - - if(typeof target == 'function') - { - that[property] = wrap(target); - } - } - - return that; -} - -//finds all properties with modifiers -Structr.findProperties = function (target, modifier) -{ - var props = [], - property; - - for(property in target) - { - var v = target[property]; - - if (v && v[modifier]) - { - props.push(property); - } - } - - return props; -}; - -Structr.nArgs = function(func) -{ - var inf = func.toString().replace(/\{[\W\S]+\}/g, '').match(/\w+(?=[,\)])/g); - return inf ? inf.length :0; -} - -Structr.getFuncsByNArgs = function(that, property) -{ - return that.__private['overload::' + property] || (that.__private['overload::' + property] = {}); -} - -Structr.getOverloadedMethod = function(that, property, nArgs) -{ - var funcsByNArgs = Structr.getFuncsByNArgs(that, property); - - return funcsByNArgs[nArgs]; -} - -Structr.setOverloadedMethod = function(that, property, func, nArgs) -{ - var funcsByNArgs = Structr.getFuncsByNArgs(that, property); - - if(func.overloaded) return funcsByNArgs; - - funcsByNArgs[nArgs || Structr.nArgs(func)] = func; - - return funcsByNArgs; -} - -//modifies how properties behave in a class -Structr.modifiers = { - - /** - * overrides given method - */ - - m_override: function (that, property, newMethod) - { - var oldMethod = (that.__private && that.__private[property]) || that[property] || function (){}, - parentMethod = oldMethod; - - if(oldMethod.overloaded) - { - var overloadedMethod = oldMethod, - nArgs = Structr.nArgs(newMethod); - parentMethod = Structr.getOverloadedMethod(that, property, nArgs); - } - - //wrap the method so we can access the parent overloaded function - var wrappedMethod = function () - { - this._super = parentMethod; - var ret = newMethod.apply(this, arguments); - delete this._super; - return ret; - } - - if(oldMethod.overloaded) - { - return Structr.modifiers.m_overload(that, property, wrappedMethod, nArgs); - } - - return wrappedMethod; - }, - - - /** - * getter / setter which are physical functions: e.g: test.myName(), and test.myName('craig') - */ - - m_explicit: function (that, property, gs) - { - var pprop = '__'+property; - - //if GS is not defined, then set defaults. - if (typeof gs != 'object') - { - gs = {}; - } - - if (!gs.get) - gs.get = function () - { - return this._value; - } - - if (!gs.set) - gs.set = function (value) - { - this._value = value; - } - - - return function (value) - { - //getter - if (!arguments.length) - { - this._value = this[pprop]; - var ret = gs.get.apply(this); - delete this._value; - return ret; - } - - //setter - else - { - //don't call the gs if the value isn't the same - if (this[pprop] == value ) - return; - - //set the current value to the setter value - this._value = this[pprop]; - - //set - gs.set.apply(this, [value]); - - //set the new value. this only matters if the setter set it - this[pprop] = this._value; - } - }; - }, - - /** - */ - - m_implicit: function (that, property, egs) - { - //keep the original function available so we can override it - that.__private[property] = egs; - - that.__defineGetter__(property, egs); - that.__defineSetter__(property, egs); - }, - - /** - */ - - m_overload: function (that, property, value, nArgs) - { - var funcsByNArgs = Structr.setOverloadedMethod(that, property, value, nArgs); - - var multiFunc = function() - { - var func = funcsByNArgs[arguments.length]; - - if(func) - { - return funcsByNArgs[arguments.length].apply(this, arguments); - } - else - { - var expected = []; - - for(var sizes in funcsByNArgs) - { - expected.push(sizes); - } - - throw new Error('Expected '+expected.join(',')+' parameters, got '+arguments.length+'.'); - } - } - - multiFunc.overloaded = true; - - return multiFunc; - } -} - - -//extends from one class to another. note: the TO object should be the parent. a copy is returned. -Structr.extend = function () -{ - var from = arguments[0], - to = {}; - - for(var i = 1, n = arguments.length; i < n; i++) - { - var obj = arguments[i]; - - Structr.copy(obj instanceof Function ? obj() : obj, to); - } - - - var that = { - __private: { - - //contains modifiers for all properties of object - propertyModifiers: {} - } - }; - - - Structr.copy(from, that); - - var usedProperties = {}, - property; - - for(property in to) - { - var value = to[property]; - - - var propModifiersAr = property.split(' '), //property is at the end of the modifiers. e.g: override bindable testProperty - propertyName = propModifiersAr.pop(), - - modifierList = that.__private.propertyModifiers[propertyName] || (that.__private.propertyModifiers[propertyName] = []); - - - if (propModifiersAr.length) - { - var propModifiers = {}; - for(var i = propModifiersAr.length; i--;) - { - var modifier = propModifiersAr[i]; - - propModifiers['m_' + propModifiersAr[i]] = 1; - - if (modifierList.indexOf(modifier) == -1) - { - modifierList.push(modifier); - } - } - - if(propModifiers.m_merge) - { - value = Structr.copy(from[propertyName], value); - } - - //if explicit, or implicit modifiers are set, then we need an explicit modifier first - if (propModifiers.m_explicit || propModifiers.m_implicit) - { - value = Structr.modifiers.m_explicit(that, propertyName, value); - } - - if (propModifiers.m_override) - { - value = Structr.modifiers.m_override(that, propertyName, value); - } - - if (propModifiers.m_implicit) - { - //getter is set, don't continue. - Structr.modifiers.m_implicit(that, propertyName, value); - continue; - } - } - - for(var j = modifierList.length; j--;) - { - value[modifierList[j]] = true; - } - - if(usedProperties[propertyName]) - { - var oldValue = that[propertyName]; - - //first property will NOT be overloaded, so we need to check it here - if(!oldValue.overloaded) Structr.modifiers.m_overload(that, propertyName, oldValue, undefined); - - value = Structr.modifiers.m_overload(that, propertyName, value, undefined); - } - - usedProperties[propertyName] = 1; - - that.__private[propertyName] = that[propertyName] = value; - } - - //if the parent constructor exists, and the child constructor IS the parent constructor, it means - //the PARENT constructor was defined, and the CHILD constructor wasn't, so the parent prop was copied over. We need to create a new function, and - //call the parent constructor when the child is instantiated, otherwise it'll be the same class essentially (setting proto) - if (that.__construct && from.__construct && that.__construct == from.__construct) - { - that.__construct = Structr.modifiers.m_override(that, '__construct', function() - { - this._super.apply(this, arguments); - }); - } - else - if(!that.__construct) - { - that.__construct = function() {}; - } - - - //copy - for(var property in from.__construct) - { - if(from.__construct[property]['static'] && !that[property]) - { - that.__construct[property] = from.__construct[property]; - } - } - - - var propertyName; - - //apply the static props - for(propertyName in that) - { - var value = that[propertyName]; - - //if the value is static, then tack it onto the constructor - if (value && value['static']) - { - that.__construct[propertyName] = value; - delete that[propertyName]; - } - } - - - - return that; -} - - -//really.. this isn't the greatest idea if a LOT of objects -//are being allocated in a short perioud of time. use the closure -//method instead. This is great for objects which are instantiated ONCE, or a couple of times :P. -Structr.fh = function (that) -{ - that = Structr.extend({}, that); - - //deprecated - that.getMethod = function (property) - { - return Structr.getMethod(this, property); - } - - that.extend = function () - { - return Structr.extend.apply(null, [this].concat(arguments)) - } - - //copy to target object - that.copyTo = function (target, lite) - { - Structr.copy(this, target, lite); - } - - //wraps the objects methods so this always points to the right place - that.wrap = function(property) - { - return Structr.wrap(this, property); - } - - return that; -} - -module.exports = Structr; - diff --git a/node_modules/celeri/node_modules/structr/structr.min.js b/node_modules/celeri/node_modules/structr/structr.min.js deleted file mode 100644 index 930f670..0000000 --- a/node_modules/celeri/node_modules/structr/structr.min.js +++ /dev/null @@ -1,8 +0,0 @@ -var Structr=function(a,c){c||(c=Structr.fh({}));var b=Structr.extend(c,a);if(!b.__construct)b.__construct=function(){};b.__construct.prototype=b;b.__construct.extend=function(a){return Structr(a,b)};return b.__construct};Structr.copy=function(a,c){c||(c={});for(var b in a){var d=a[b],e=c[b];typeof d=="object"?(e=e&&d instanceof e.constructor?e:d instanceof Array?[]:{},Structr.copy(d,e)):e=d;c[b]=e}return c};Structr.getMethod=function(a,c){return function(){return a[c].apply(a,arguments)}}; -Structr.findProperties=function(a,c){var b=[],d;for(d in a){var e=a[d];e&&e[c]&&b.push(d)}return b};Structr.getNArgs=function(a){return(a=a.toString().replace(/\{[\W\S]+\}/g,"").match(/\w+(?=[,\)])/g))?a.length:0};Structr.getFuncsByNArgs=function(a,c){return a.__private["overload::"+c]||(a.__private["overload::"+c]={})};Structr.getOverloadedMethod=function(a,c,b){return Structr.getFuncsByNArgs(a,c)[b]}; -Structr.setOverloadedMethod=function(a,c,b,d){a=Structr.getFuncsByNArgs(a,c);if(b.overloaded)return a;a[d||Structr.getNArgs(b)]=b;return a}; -Structr.modifiers={m_override:function(a,c,b){var d=a.__private&&a.__private[c]||a[c]||function(){},e=d;if(d.overloaded)var g=Structr.getNArgs(b),e=Structr.getOverloadedMethod(a,c,g);var h=function(){this._super=e;var a=b.apply(this,arguments);delete this._super;return a};if(d.overloaded)return Structr.modifiers.m_overload(a,c,h,g);return h},m_explicit:function(a,c,b){var d="_gs::"+c;typeof b!="object"&&(b={});if(!b.get)b.get=function(){return this._value};if(!b.set)b.set=function(b){this._value= -b};return function(a){if(arguments.length){if(this[d]!=a)this._value=this[d],b.set.apply(this,[a]),this[d]=this._value}else{this._value=this[d];var c=b.get.apply(this);delete this._value;return c}}},m_implicit:function(a,c,b){a.__private[c]=b;a.__defineGetter__(c,b);a.__defineSetter__(c,b)},m_overload:function(a,c,b,d){var e=Structr.setOverloadedMethod(a,c,b,d),a=function(){return e[arguments.length].apply(this,arguments)};a.overloaded=!0;return a}}; -Structr.extend=function(a,c){c||(c={});var b={__private:{propertyModifiers:{}}};c instanceof Function&&(c=c());Structr.copy(a,b);var d={},e;for(e in c){var g=c[e],h=e.split(" "),f=h.pop(),i=b.__private.propertyModifiers[f]||(b.__private.propertyModifiers[f]=[]);if(h.length){for(var j={},k=h.length;k--;){var l=h[k];j["m_"+h[k]]=1;i.indexOf(l)==-1&&i.push(l)}if(j.m_explicit||j.m_implicit)g=Structr.modifiers.m_explicit(b,f,g);j.m_override&&(g=Structr.modifiers.m_override(b,f,g));if(j.m_implicit){Structr.modifiers.m_implicit(b, -f,g);continue}}for(h=i.length;h--;)g[i[h]]=!0;d[f]&&(i=b[f],i.overloaded||Structr.modifiers.m_overload(b,f,i,void 0),g=Structr.modifiers.m_overload(b,f,g,void 0));d[f]=1;b.__private[f]=b[f]=g}if(b.__construct&&a.__construct&&b.__construct==a.__construct)b.__construct=Structr.modifiers.m_override(b,"__construct",function(){this._super.apply(this,arguments)});for(f in b)if((g=b[f])&&g["static"])b.__construct[f]=g,delete b[f];return b}; -Structr.fh=function(a){a=Structr.extend({},a);a.getMethod=function(a){return Structr.getMethod(this,a)};a.extend=function(a){return Structr.extend(this,a)};a.copyTo=function(a){Structr.copy(this,a)};return a};if(this.exports)exports.Structr=Structr; \ No newline at end of file diff --git a/node_modules/celeri/package.json b/node_modules/celeri/package.json deleted file mode 100755 index e27956d..0000000 --- a/node_modules/celeri/package.json +++ /dev/null @@ -1,18 +0,0 @@ -{ - "name": "celeri", - "description": "CLI lib", - "version": "0.1.3", - "author": "Craig Condon", - "repository": { - "type": "git", - "url": "http://github.com/crcn/celeri.git" - }, - "directories" : { "lib" : "./lib" }, - "dependencies": { - "structr":"0.0.10", - "beanpole":"*", - "colors":"*" - }, - - "main": "./lib/index.js" -} diff --git a/node_modules/celeri/project.sublime-project b/node_modules/celeri/project.sublime-project deleted file mode 100644 index 1d5af0e..0000000 --- a/node_modules/celeri/project.sublime-project +++ /dev/null @@ -1,23 +0,0 @@ -{ - "folders": - [ - { - "path": "." - } - ], - "build_systems": - [ - { - "name":"cbd make", - "cmd":["cbd","make","celeri"] - }, - { - "name":"cbd start", - "cmd":["cbd","start","celeri"] - }, - { - "name":"cbd make+start", - "cmd":["cbd","make+start","celeri"] - } - ] -} \ No newline at end of file diff --git a/node_modules/celeri/project.tmproj b/node_modules/celeri/project.tmproj deleted file mode 100644 index 3b8d49d..0000000 --- a/node_modules/celeri/project.tmproj +++ /dev/null @@ -1,48 +0,0 @@ - - - - - currentDocument - lib/utils.js - documents - - - expanded - - name - project - regexFolderFilter - !.*/(\.[^/]*|CVS|_darcs|_MTN|\{arch\}|blib|.*~\.nib|.*\.(framework|app|pbproj|pbxproj|xcode(proj)?|bundle))$ - sourceDirectory - - - - fileHierarchyDrawerWidth - 200 - metaData - - lib/utils.js - - caret - - column - 0 - line - 22 - - firstVisibleColumn - 0 - firstVisibleLine - 0 - - - openDocuments - - lib/utils.js - - showFileHierarchyDrawer - - windowFrame - {{0, 4}, {1230, 874}} - - diff --git a/node_modules/findit/README.markdown b/node_modules/findit/README.markdown deleted file mode 100644 index 8b82ef5..0000000 --- a/node_modules/findit/README.markdown +++ /dev/null @@ -1,91 +0,0 @@ -findit -====== - -Recursively walk directory trees. Think `/usr/bin/find`. - -example time! -============= - -callback style --------------- - -````javascript -require('findit').find(__dirname, function (file) { - console.log(file); -}) -```` - -emitter style -------------- - -````javascript -var finder = require('findit').find(__dirname); - -finder.on('directory', function (dir) { - console.log(dir + '/'); -}); - -finder.on('file', function (file) { - console.log(file); -}); -```` - -synchronous ------------ - -````javascript -var files = require('findit').sync(__dirname); - console.dir(files); -```` - -methods -======= - -find(basedir) -------------- -find(basedir, cb) ------------------ - -Do an asynchronous recursive walk starting at `basedir`. -Optionally supply a callback that will get the same arguments as the path event -documented below in "events". - -If `basedir` is actually a non-directory regular file, findit emits a single -"file" event for it then emits "end". - -Findit uses `fs.stat()` so symlinks are traversed automatically. Findit won't -traverse an inode that it has seen before so directories can have symlink cycles -and findit won't blow up. - -Returns an EventEmitter. See "events". - -sync(basedir, cb) ------------------ - -Return an array of files and directories from a synchronous recursive walk -starting at `basedir`. - -An optional callback `cb` will get called with `cb(file, stat)` if specified. - -events -====== - -file: [ file, stat ] --------------------- - -Emitted for just files which are not directories. - -directory : [ directory, stat ] -------------------------------- - -Emitted for directories. - -path : [ file, stat ] ---------------------- - -Emitted for both files and directories. - -end ---- - -Emitted when the recursive walk is done. diff --git a/node_modules/findit/examples/callback.js b/node_modules/findit/examples/callback.js deleted file mode 100644 index 829630e..0000000 --- a/node_modules/findit/examples/callback.js +++ /dev/null @@ -1,3 +0,0 @@ -require('findit').find(__dirname, function (file) { - console.log(file); -}) diff --git a/node_modules/findit/examples/emitter.js b/node_modules/findit/examples/emitter.js deleted file mode 100644 index f97adf3..0000000 --- a/node_modules/findit/examples/emitter.js +++ /dev/null @@ -1,9 +0,0 @@ -var finder = require('findit').find(__dirname); - -finder.on('directory', function (dir) { - console.log(dir + '/'); -}); - -finder.on('file', function (file) { - console.log(file); -}); diff --git a/node_modules/findit/examples/sync.js b/node_modules/findit/examples/sync.js deleted file mode 100644 index b09e0b2..0000000 --- a/node_modules/findit/examples/sync.js +++ /dev/null @@ -1,2 +0,0 @@ -var files = require('findit').findSync(__dirname); -console.dir(files); diff --git a/node_modules/findit/index.js b/node_modules/findit/index.js deleted file mode 100644 index 818e72d..0000000 --- a/node_modules/findit/index.js +++ /dev/null @@ -1,88 +0,0 @@ -var fs = require('fs'); -var EventEmitter = require('events').EventEmitter; -var Seq = require('seq'); - -exports = module.exports = find; -exports.find = find; -function find (base, cb) { - var em = new EventEmitter; - var inodes = {}; - - function finder (dir, f) { - Seq() - .seq(fs.readdir, dir, Seq) - .flatten() - .seqEach(function (file) { - var p = dir + '/' + file; - fs.stat(p, this.into(p)); - }) - .seq(function () { - this(null, Object.keys(this.vars)); - }) - .flatten() - .seqEach(function (file) { - var stat = this.vars[file]; - if (cb) cb(file, stat); - - if (inodes[stat.ino]) { - // already seen this inode, probably a recursive symlink - this(null); - } - else { - em.emit('path', file, stat); - - if (stat.isDirectory()) { - em.emit('directory', file, stat); - finder(file, this); - } - else { - em.emit('file', file, stat); - this(null); - } - - inodes[stat.ino] = true; - } - }) - .seq(f.bind({}, null)) - .catch(em.emit.bind(em, 'error')) - ; - } - - fs.stat(base, function (err, s) { - if (err) { - em.emit('error', err); - } - else if (s.isDirectory()) { - finder(base, em.emit.bind(em, 'end')); - } - else { - em.emit('file', base); - em.emit('end'); - } - }); - - return em; -}; - -exports.findSync = function findSync (dir, cb) { - var rootStat = fs.statSync(dir); - if (!rootStat.isDirectory()) { - if (cb) cb(dir, rootStat); - return [dir]; - } - - return fs.readdirSync(dir).reduce(function (files, file) { - var p = dir + '/' + file; - var stat = fs.statSync(p); - if (cb) cb(p, stat); - files.push(p); - - if (stat.isDirectory()) { - files.push.apply(files, findSync(p, cb)); - } - - return files; - }, []); -}; - -exports.find.sync = exports.findSync; diff --git a/node_modules/findit/node_modules/seq/.npmignore b/node_modules/findit/node_modules/seq/.npmignore deleted file mode 100644 index 3c3629e..0000000 --- a/node_modules/findit/node_modules/seq/.npmignore +++ /dev/null @@ -1 +0,0 @@ -node_modules diff --git a/node_modules/findit/node_modules/seq/README.markdown b/node_modules/findit/node_modules/seq/README.markdown deleted file mode 100644 index 3689261..0000000 --- a/node_modules/findit/node_modules/seq/README.markdown +++ /dev/null @@ -1,442 +0,0 @@ -Seq -=== - -Seq is an asynchronous flow control library with a chainable interface for -sequential and parallel actions. Even the error handling is chainable. - -Each action in the chain operates on a stack of values. -There is also a variables hash for storing values by name. - -[TOC] - - - -Examples -======== - -stat_all.js ------------ - -````javascript -var fs = require('fs'); -var Hash = require('hashish'); -var Seq = require('seq'); - -Seq() - .seq(function () { - fs.readdir(__dirname, this); - }) - .flatten() - .parEach(function (file) { - fs.stat(__dirname + '/' + file, this.into(file)); - }) - .seq(function () { - var sizes = Hash.map(this.vars, function (s) { return s.size }) - console.dir(sizes); - }) -; -```` - -Output: - - { 'stat_all.js': 404, 'parseq.js': 464 } - -parseq.js ---------- - -````javascript -var fs = require('fs'); -var exec = require('child_process').exec; - -var Seq = require('seq'); -Seq() - .seq(function () { - exec('whoami', this) - }) - .par(function (who) { - exec('groups ' + who, this); - }) - .par(function (who) { - fs.readFile(__filename, 'ascii', this); - }) - .seq(function (groups, src) { - console.log('Groups: ' + groups.trim()); - console.log('This file has ' + src.length + ' bytes'); - }) -; -```` - -Output: - - Groups: substack : substack dialout cdrom floppy audio src video plugdev games netdev fuse www - This file has 464 bytes - - - - -API -=== - -Each method executes callbacks with a context (its `this`) described in the next -section. Every method returns `this`. - -Whenever `this()` is called with a non-falsy first argument, the error value -propagates down to the first `catch` it sees, skipping over all actions in -between. There is an implicit `catch` at the end of all chains that prints the -error stack if available and otherwise just prints the error. - - - -Seq(xs=[]) ----------- - -The constructor function creates a new `Seq` chain with the methods described -below. The optional array argument becomes the new context stack. - -Array argument is new in 0.3. `Seq()` now behaves like `Seq.ap()`. - - -.seq(cb) --------- -.seq(key, cb, *args) --------------------- - -This eponymous function executes actions sequentially. -Once all running parallel actions are finished executing, -the supplied callback is `apply()`'d with the context stack. - -To execute the next action in the chain, call `this()`. The first -argument must be the error value. The rest of the values will become the stack -for the next action in the chain and are also available at `this.args`. - -If `key` is specified, the second argument sent to `this` goes to -`this.vars[key]` in addition to the stack and `this.args`. -`this.vars` persists across all requests unless it is overwritten. - -All arguments after `cb` will be bound to `cb`, which is useful because -`.bind()` makes you set `this`. If you pass in `Seq` in the arguments list, -it'll get transformed into `this` so that you can do: - -````javascript -Seq() - .seq(fs.readdir, __dirname, Seq) - .seq(function (files) { console.dir(files) }) -; -```` - -which prints an array of files in `__dirname`. - - -.par(cb) --------- -.par(key, cb, *args) --------------------- - -Use `par` to execute actions in parallel. -Chain multiple parallel actions together and collect all the responses on the -stack with a sequential operation like `seq`. - -Each `par` sets one element in the stack with the second argument to `this()` in -the order in which it appears, so multiple `par`s can be chained together. - -Like with `seq`, the first argument to `this()` should be the error value and -the second will get pushed to the stack. Further arguments are available in -`this.args`. - -If `key` is specified, the result from the second argument send to `this()` goes -to `this.vars[key]`. -`this.vars` persists across all requests unless it is overwritten. - -All arguments after `cb` will be bound to `cb`, which is useful because -`.bind()` makes you set `this`. Like `.seq()`, you can pass along `Seq` in these -bound arguments and it will get tranformed into `this`. - - -.catch(cb) ----------- - -Catch errors. Whenever a function calls `this` with a non-falsy first argument, -the message propagates down the chain to the first `catch` it sees. -The callback `cb` fires with the error object as its first argument and the key -that the action that caused the error was populating, which may be undefined. - -`catch` is a sequential action and further actions may appear after a `catch` in -a chain. If the execution reaches a `catch` in a chain and no error has occured, -the `catch` is skipped over. - -For convenience, there is a default error handler at the end of all chains. -This default error handler looks like this: - -````javascript -.catch(function (err) { - console.error(err.stack ? err.stack : err) -}) -```` - - -.forEach(cb) ------------- - -Execute each action in the stack under the context of the chain object. -`forEach` does not wait for any of the actions to finish and does not itself -alter the stack, but the callback may alter the stack itself by modifying -`this.stack`. - -The callback is executed `cb(x,i)` where `x` is the element and `i` is the -index. - -`forEach` is a sequential operation like `seq` and won't run until all pending -parallel requests yield results. - - -.seqEach(cb) ------------- - -Like `forEach`, call `cb` for each element on the stack, but unlike `forEach`, -`seqEach` waits for the callback to yield with `this` before moving on to the -next element in the stack. - -The callback is executed `cb(x,i)` where `x` is the element and `i` is the -index. - -If `this()` is supplied non-falsy error, the error propagates downward but any -other arguments are ignored. `seqEach` does not modify the stack itself. - - -.parEach(cb) ------------- -.parEach(limit, cb) -------------------- - -Like `forEach`, calls cb for each element in the stack and doesn't wait for the -callback to yield a result with `this()` before moving on to the next iteration. -Unlike `forEach`, `parEach` waits for all actions to call `this()` before moving -along to the next action in the chain. - -The callback is executed `cb(x,i)` where `x` is the element and `i` is the -index. - -`parEach` does not modify the stack itself and errors supplied to `this()` -propagate. - -Optionally, if limit is supplied to `parEach`, at most `limit` callbacks will be -active at a time. - - -.seqMap(cb) ------------ - -Like `seqEach`, but collect the values supplied to `this` and set the stack to -these values. - - -.parMap(cb) ------------ -.parMap(limit, cb) ------------------- - -Like `parEach`, but collect the values supplied to `this` and set the stack to -these values. - - -.seqFilter(cb) ------------ - -Executes the callback `cb(x, idx)` against each element on the stack, waiting for the -callback to yield with `this` before moving on to the next element. If the callback -returns an error or a falsey value, the element will not be included in the resulting -stack. - -Any errors from the callback are consumed and **do not** propagate. - -Calls to `this.into(i)` will place the value, if accepted by the callback, at the index in -the results as if it were ordered at i-th index on the stack before filtering (with ties -broken by the values). This implies `this.into` will never override another stack value -even if their indices collide. Finally, the value will only actually appear at `i` if the -callback accepts or moves enough values before `i`. - - -.parFilter(cb) ------------ -.parFilter(limit, cb) ------------------- - -Executes the callback `cb(x, idx)` against each element on the stack, but **does not** -wait for it to yield before moving on to the next element. If the callback returns an -error or a falsey value, the element will not be included in the resulting stack. - -Any errors from the callback are consumed and **do not** propagate. - -Calls to `this.into(i)` will place the value, if accepted by the callback, at the index in -the results as if it were ordered at i-th index on the stack before filtering (with ties -broken by the values). This implies `this.into` will never override another stack value -even if their indices collide. Finally, the value will only actually appear at `i` if the -callback accepts or moves enough values before `i`. - -Optionally, if limit is supplied to `parEach`, at most `limit` callbacks will be -active at a time. - - -.do(cb) -------- -Create a new nested context. `cb`'s first argument is the previous context, and `this` -is the nested `Seq` object. - - -.flatten(fully=true) --------------------- - -Recursively flatten all the arrays in the stack. Set `fully=false` to flatten -only one level. - - -.unflatten() ------------- - -Turn the contents of the stack into a single array item. You can think of it -as the inverse of `flatten(false)`. - - -.extend([x,y...]) ------------------ - -Like `push`, but takes an array. This is like python's `[].extend()`. - - -.set(xs) --------- - -Set the stack to a new array. This assigns the reference, it does not copy. - - -.empty() --------- - -Set the stack to []. - - -.push(x,y...), .pop(), .shift(), .unshift(x), .splice(...), reverse() ---------------------------------------------------------------------- -.map(...), .filter(...), .reduce(...) -------------------------------------- - -Executes an array operation on the stack. - -The methods `map`, `filter`, and `reduce` are also proxies to their Array counterparts: -they have identical signatures to the Array methods, operate synchronously on the context -stack, and do not pass a Context object (unlike `seqMap` and `parMap`). - -The result of the transformation is assigned to the context stack; in the case of `reduce`, -if you do not return an array, the value will be wrapped in one. - -````javascript -Seq([1, 2, 3]) - .reduce(function(sum, x){ return sum + x; }, 0) - .seq(function(sum){ - console.log('sum: %s', sum); - // sum: 6 - console.log('stack is Array?', Array.isArray(this.stack)); - // stack is Array: true - console.log('stack:', this.stack); - // stack: [6] - }) -; -```` - - - - -Explicit Parameters -------------------- - -For environments like coffee-script or nested logic where threading `this` is -bothersome, you can use: - -* seq_ -* par_ -* forEach_ -* seqEach_ -* parEach_ -* seqMap_ -* parMap_ - -which work exactly like their un-underscored counterparts except for the first -parameter to the supplied callback is set to the context, `this`. - - - -Context Object -============== - -Each callback gets executed with its `this` set to a function in order to yield -results, error values, and control. The function also has these useful fields: - -this.stack ----------- - -The execution stack. - -this.stack_ ------------ - -The previous stack value, mostly used internally for hackish purposes. - -this.vars ---------- - -A hash of key/values populated with `par(key, ...)`, `seq(key, ...)` and -`this.into(key)`. - -this.into(key) --------------- - -Instead of sending values to the stack, sets a key and returns `this`. -Use `this.into(key)` interchangeably with `this` for yielding keyed results. -`into` overrides the optional key set by `par(key, ...)` and `seq(key, ...)`. - -this.ok -------- - -Set the `err` to null. Equivalent to `this.bind(this, null)`. - -this.args ---------- - -`this.args` is like `this.stack`, but it contains all the arguments to `this()` -past the error value, not just the first. `this.args` is an array with the same -indices as `this.stack` but also stores keyed values for the last sequential -operation. Each element in `this.array` is set to `[].slice.call(arguments, 1)` -from inside `this()`. - -this.error ----------- - -This is used for error propagation. You probably shouldn't mess with it. - - - -Installation -============ - -With [npm](http://github.com/isaacs/npm), just do: - - npm install seq - -or clone this project on github: - - git clone http://github.com/substack/node-seq.git - -To run the tests with [expresso](http://github.com/visionmedia/expresso), -just do: - - expresso - - - -Dependencies ------------- - -This module uses [chainsaw](http://github.com/substack/node-chainsaw) -When you `npm install seq` this dependency will automatically be installed. - - diff --git a/node_modules/findit/node_modules/seq/examples/join.js b/node_modules/findit/node_modules/seq/examples/join.js deleted file mode 100644 index cc05c4f..0000000 --- a/node_modules/findit/node_modules/seq/examples/join.js +++ /dev/null @@ -1,18 +0,0 @@ -var Seq = require('seq'); -Seq() - .par(function () { - var that = this; - setTimeout(function () { that(null, 'a') }, 300); - }) - .par(function () { - var that = this; - setTimeout(function () { that(null, 'b') }, 200); - }) - .par(function () { - var that = this; - setTimeout(function () { that(null, 'c') }, 100); - }) - .seq(function (a, b, c) { - console.dir([ a, b, c ]) - }) -; diff --git a/node_modules/findit/node_modules/seq/examples/parseq.coffee b/node_modules/findit/node_modules/seq/examples/parseq.coffee deleted file mode 100644 index d4ca0ab..0000000 --- a/node_modules/findit/node_modules/seq/examples/parseq.coffee +++ /dev/null @@ -1,12 +0,0 @@ -fs = require 'fs' -exec = require('child_process').exec -Seq = require 'seq' - -Seq() - .seq_((next) -> exec 'whoami', next) - .par_((next, who) -> exec('groups ' + who, next)) - .par_((next, who) -> fs.readFile(__filename, 'utf8', next)) - .seq_((next, groups, src) -> - console.log('Groups: ' + groups.trim()) - console.log('This file has ' + src.length + ' bytes') - ) diff --git a/node_modules/findit/node_modules/seq/examples/parseq.js b/node_modules/findit/node_modules/seq/examples/parseq.js deleted file mode 100644 index 2cdcf21..0000000 --- a/node_modules/findit/node_modules/seq/examples/parseq.js +++ /dev/null @@ -1,19 +0,0 @@ -var fs = require('fs'); -var exec = require('child_process').exec; - -var Seq = require('seq'); -Seq() - .seq(function () { - exec('whoami', this) - }) - .par(function (who) { - exec('groups ' + who, this); - }) - .par(function (who) { - fs.readFile(__filename, 'utf8', this); - }) - .seq(function (groups, src) { - console.log('Groups: ' + groups.trim()); - console.log('This file has ' + src.length + ' bytes'); - }) -; diff --git a/node_modules/findit/node_modules/seq/examples/stat_all.coffee b/node_modules/findit/node_modules/seq/examples/stat_all.coffee deleted file mode 100644 index 83ec0b2..0000000 --- a/node_modules/findit/node_modules/seq/examples/stat_all.coffee +++ /dev/null @@ -1,16 +0,0 @@ -fs = require 'fs' -Hash = require 'hashish' -Seq = require 'seq' - -Seq() - .seq_((next) -> - fs.readdir(__dirname, next) - ) - .flatten() - .parEach_((next, file) -> - fs.stat(__dirname + '/' + file, next.into(file)) - ) - .seq_((next) -> - sizes = Hash.map(next.vars, (s) -> s.size) - console.dir sizes - ) diff --git a/node_modules/findit/node_modules/seq/examples/stat_all.js b/node_modules/findit/node_modules/seq/examples/stat_all.js deleted file mode 100644 index b9962eb..0000000 --- a/node_modules/findit/node_modules/seq/examples/stat_all.js +++ /dev/null @@ -1,17 +0,0 @@ -var fs = require('fs'); -var Hash = require('hashish'); -var Seq = require('seq'); - -Seq() - .seq(function () { - fs.readdir(__dirname, this); - }) - .flatten() - .parEach(function (file) { - fs.stat(__dirname + '/' + file, this.into(file)); - }) - .seq(function () { - var sizes = Hash.map(this.vars, function (s) { return s.size }) - console.dir(sizes); - }) -; diff --git a/node_modules/findit/node_modules/seq/index.js b/node_modules/findit/node_modules/seq/index.js deleted file mode 100755 index 4e0888b..0000000 --- a/node_modules/findit/node_modules/seq/index.js +++ /dev/null @@ -1,520 +0,0 @@ -var EventEmitter = require('events').EventEmitter; -var Hash = require('hashish'); -var Chainsaw = require('chainsaw'); - -module.exports = Seq; -function Seq (xs) { - if (xs && !Array.isArray(xs) || arguments.length > 1) { - throw new Error('Optional argument to Seq() is exactly one Array'); - } - - var ch = Chainsaw(function (saw) { - builder.call(this, saw, xs || []); - }); - - process.nextTick(function () { - ch['catch'](function (err) { - console.error(err.stack ? err.stack : err) - }); - }); - return ch; -} - -Seq.ap = Seq; // for compatability with versions <0.3 - -function builder (saw, xs) { - var context = { - vars : {}, - args : {}, - stack : xs, - error : null - }; - context.stack_ = context.stack; - - function action (step, key, f, g) { - var cb = function (err) { - var args = [].slice.call(arguments, 1); - if (err) { - context.error = { message : err, key : key }; - saw.jump(lastPar); - saw.down('catch'); - g(); - } - else { - if (typeof key == 'number') { - context.stack_[key] = args[0]; - context.args[key] = args; - } - else { - context.stack_.push.apply(context.stack_, args); - if (key !== undefined) { - context.vars[key] = args[0]; - context.args[key] = args; - } - } - if (g) g(args, key); - } - }; - Hash(context).forEach(function (v,k) { cb[k] = v }); - - cb.into = function (k) { - key = k; - return cb; - }; - - cb.next = function (err, xs) { - context.stack_.push.apply(context.stack_, xs); - cb.apply(cb, [err].concat(context.stack)); - }; - - cb.pass = function (err) { - cb.apply(cb, [err].concat(context.stack)); - }; - - cb.ok = cb.bind(cb, null); - - f.apply(cb, context.stack); - } - - var running = 0; - var errors = 0; - - this.seq = function (key, cb) { - var bound = [].slice.call(arguments, 2); - - if (typeof key === 'function') { - if (arguments.length > 1) bound.unshift(cb); - cb = key; - key = undefined; - } - - if (context.error) saw.next() - else if (running === 0) { - action(saw.step, key, - function () { - context.stack_ = []; - var args = [].slice.call(arguments); - args.unshift.apply(args, bound.map(function (arg) { - return arg === Seq ? this : arg - }, this)); - - cb.apply(this, args); - }, function () { - context.stack = context.stack_; - saw.next() - } - ); - } - }; - - var lastPar = null; - this.par = function (key, cb) { - lastPar = saw.step; - - if (running == 0) { - // empty the active stack for the first par() in a chain - context.stack_ = []; - } - - var bound = [].slice.call(arguments, 2); - if (typeof key === 'function') { - if (arguments.length > 1) bound.unshift(cb); - cb = key; - key = context.stack_.length; - context.stack_.push(null); - } - var cb_ = function () { - var args = [].slice.call(arguments); - args.unshift.apply(args, bound.map(function (arg) { - return arg === Seq ? this : arg - }, this)); - - cb.apply(this, args); - }; - - running ++; - - var step = saw.step; - process.nextTick(function () { - action(step, key, cb_, function (args) { - if (!args) errors ++; - - running --; - if (running == 0) { - context.stack = context.stack_.slice(); - saw.step = lastPar; - if (errors > 0) saw.down('catch'); - errors = 0; - saw.next(); - } - }); - }); - saw.next(); - }; - - [ 'seq', 'par' ].forEach(function (name) { - this[name + '_'] = function (key) { - var args = [].slice.call(arguments); - - var cb = typeof key === 'function' - ? args[0] : args[1]; - - var fn = function () { - var argv = [].slice.call(arguments); - argv.unshift(this); - cb.apply(this, argv); - }; - - if (typeof key === 'function') { - args[0] = fn; - } - else { - args[1] = fn; - } - - this[name].apply(this, args); - }; - }, this); - - this['catch'] = function (cb) { - if (context.error) { - cb.call(context, context.error.message, context.error.key); - context.error = null; - } - saw.next(); - }; - - this.forEach = function (cb) { - this.seq(function () { - context.stack_ = context.stack.slice(); - var end = context.stack.length; - - if (end === 0) this(null) - else context.stack.forEach(function (x, i) { - action(saw.step, i, function () { - cb.call(this, x, i); - if (i == end - 1) saw.next(); - }); - }); - }); - }; - - this.seqEach = function (cb) { - this.seq(function () { - context.stack_ = context.stack.slice(); - var xs = context.stack.slice(); - if (xs.length === 0) this(null); - else (function next (i) { - action( - saw.step, i, - function () { cb.call(this, xs[i], i) }, - function (args) { - if (!args || i === xs.length - 1) saw.next(); - else next(i + 1); - } - ); - }).bind(this)(0); - }); - }; - - this.parEach = function (limit, cb) { - var xs = context.stack.slice(); - if (cb === undefined) { cb = limit; limit = xs.length } - context.stack_ = []; - - var active = 0; - var finished = 0; - var queue = []; - - if (xs.length === 0) saw.next() - else xs.forEach(function call (x, i) { - if (active >= limit) { - queue.push(call.bind(this, x, i)); - } - else { - active ++; - action(saw.step, i, - function () { - cb.call(this, x, i); - }, - function () { - active --; - finished ++; - if (queue.length > 0) queue.shift()(); - else if (finished === xs.length) { - saw.next(); - } - } - ); - } - }); - }; - - this.parMap = function (limit, cb) { - var res = []; - var len = context.stack.length; - if (cb === undefined) { cb = limit; limit = len } - var res = []; - - Seq() - .extend(context.stack) - .parEach(limit, function (x, i) { - var self = this; - - var next = function () { - res[i] = arguments[1]; - self.apply(self, arguments); - }; - - next.stack = self.stack; - next.stack_ = self.stack_; - next.vars = self.vars; - next.args = self.args; - next.error = self.error; - - next.into = function (key) { - return function () { - res[key] = arguments[1]; - self.apply(self, arguments); - }; - }; - - next.ok = function () { - var args = [].slice.call(arguments); - args.unshift(null); - return next.apply(next, args); - }; - - cb.apply(next, arguments); - }) - .seq(function () { - context.stack = res; - saw.next(); - }) - ; - }; - - this.seqMap = function (cb) { - var res = []; - var lastIdx = context.stack.length - 1; - - this.seqEach(function (x, i) { - var self = this; - - var next = function () { - res[i] = arguments[1]; - if (i === lastIdx) - context.stack = res; - self.apply(self, arguments); - }; - - next.stack = self.stack; - next.stack_ = self.stack_; - next.vars = self.vars; - next.args = self.args; - next.error = self.error; - - next.into = function (key) { - return function () { - res[key] = arguments[1]; - if (i === lastIdx) - context.stack = res; - self.apply(self, arguments); - }; - }; - - next.ok = function () { - var args = [].slice.call(arguments); - args.unshift(null); - return next.apply(next, args); - }; - - cb.apply(next, arguments); - }); - }; - - /** - * Consumes any errors that occur in `cb`. Calls to `this.into(i)` will place - * that value, if accepted by the filter, at the index in the results as - * if it were the i-th index before filtering. (This means it will never - * override another value, and will only actually appear at i if the filter - * accepts all values before i.) - */ - this.parFilter = function (limit, cb) { - var res = []; - var len = context.stack.length; - if (cb === undefined) { cb = limit; limit = len } - var res = []; - - Seq() - .extend(context.stack) - .parEach(limit, function (x, i) { - var self = this; - - var next = function (err, ok) { - if (!err && ok) - res.push([i, x]); - arguments[0] = null; // discard errors - self.apply(self, arguments); - }; - - next.stack = self.stack; - next.stack_ = self.stack_; - next.vars = self.vars; - next.args = self.args; - next.error = self.error; - - next.into = function (key) { - return function (err, ok) { - if (!err && ok) - res.push([key, x]); - arguments[0] = null; // discard errors - self.apply(self, arguments); - }; - }; - - next.ok = function () { - var args = [].slice.call(arguments); - args.unshift(null); - return next.apply(next, args); - }; - - cb.apply(next, arguments); - }) - .seq(function () { - context.stack = res.sort().map(function(pair){ return pair[1]; }); - saw.next(); - }) - ; - }; - - /** - * Consumes any errors that occur in `cb`. Calls to `this.into(i)` will place - * that value, if accepted by the filter, at the index in the results as - * if it were the i-th index before filtering. (This means it will never - * override another value, and will only actually appear at i if the filter - * accepts all values before i.) - */ - this.seqFilter = function (cb) { - var res = []; - var lastIdx = context.stack.length - 1; - - this.seqEach(function (x, i) { - var self = this; - - var next = function (err, ok) { - if (!err && ok) - res.push([i, x]); - if (i === lastIdx) - context.stack = res.sort().map(function(pair){ return pair[1]; }); - arguments[0] = null; // discard errors - self.apply(self, arguments); - }; - - next.stack = self.stack; - next.stack_ = self.stack_; - next.vars = self.vars; - next.args = self.args; - next.error = self.error; - - next.into = function (key) { - return function (err, ok) { - if (!err && ok) - res.push([key, x]); - if (i === lastIdx) - context.stack = res.sort().map(function(pair){ return pair[1]; }); - arguments[0] = null; // discard errors - self.apply(self, arguments); - }; - }; - - next.ok = function () { - var args = [].slice.call(arguments); - args.unshift(null); - return next.apply(next, args); - }; - - cb.apply(next, arguments); - }); - }; - - [ 'forEach', 'seqEach', 'parEach', 'seqMap', 'parMap', 'seqFilter', 'parFilter' ] - .forEach(function (name) { - this[name + '_'] = function (cb) { - this[name].call(this, function () { - var args = [].slice.call(arguments); - args.unshift(this); - cb.apply(this, args); - }); - }; - }, this) - ; - - ['push','pop','shift','unshift','splice','reverse'] - .forEach(function (name) { - this[name] = function () { - context.stack[name].apply( - context.stack, - [].slice.call(arguments) - ); - saw.next(); - return this; - }; - }, this) - ; - - [ 'map', 'filter', 'reduce' ] - .forEach(function (name) { - this[name] = function () { - var res = context.stack[name].apply( - context.stack, - [].slice.call(arguments) - ); - // stack must be an array, or bad things happen - context.stack = (Array.isArray(res) ? res : [res]); - saw.next(); - return this; - }; - }, this) - ; - - this.extend = function (xs) { - if (!Array.isArray(xs)) { - throw new Error('argument to .extend() is not an Array'); - } - context.stack.push.apply(context.stack, xs); - saw.next(); - }; - - this.flatten = function (pancake) { - var xs = []; - // should we fully flatten this array? (default: true) - if (pancake === undefined) { pancake = true; } - context.stack.forEach(function f (x) { - if (Array.isArray(x) && pancake) x.forEach(f); - else if (Array.isArray(x)) xs = xs.concat(x); - else xs.push(x); - }); - context.stack = xs; - saw.next(); - }; - - this.unflatten = function () { - context.stack = [context.stack]; - saw.next(); - }; - - this.empty = function () { - context.stack = []; - saw.next(); - }; - - this.set = function (stack) { - context.stack = stack; - saw.next(); - }; - - this['do'] = function (cb) { - saw.nest(cb, context); - }; -} diff --git a/node_modules/findit/node_modules/seq/node_modules/chainsaw/.npmignore b/node_modules/findit/node_modules/seq/node_modules/chainsaw/.npmignore deleted file mode 100644 index 3c3629e..0000000 --- a/node_modules/findit/node_modules/seq/node_modules/chainsaw/.npmignore +++ /dev/null @@ -1 +0,0 @@ -node_modules diff --git a/node_modules/findit/node_modules/seq/node_modules/chainsaw/README.markdown b/node_modules/findit/node_modules/seq/node_modules/chainsaw/README.markdown deleted file mode 100644 index 9bb1259..0000000 --- a/node_modules/findit/node_modules/seq/node_modules/chainsaw/README.markdown +++ /dev/null @@ -1,140 +0,0 @@ -Chainsaw -======== - -Build chainable fluent interfaces the easy way in node.js. - -With this meta-module you can write modules with chainable interfaces. -Chainsaw takes care of all of the boring details and makes nested flow control -super simple too. - -Just call `Chainsaw` with a constructor function like in the examples below. -In your methods, just do `saw.next()` to move along to the next event and -`saw.nest()` to create a nested chain. - -Examples -======== - -add_do.js ---------- - -This silly example adds values with a chainsaw. - - var Chainsaw = require('chainsaw'); - - function AddDo (sum) { - return Chainsaw(function (saw) { - this.add = function (n) { - sum += n; - saw.next(); - }; - - this.do = function (cb) { - saw.nest(cb, sum); - }; - }); - } - - AddDo(0) - .add(5) - .add(10) - .do(function (sum) { - if (sum > 12) this.add(-10); - }) - .do(function (sum) { - console.log('Sum: ' + sum); - }) - ; - -Output: - Sum: 5 - -prompt.js ---------- - -This example provides a wrapper on top of stdin with the help of -[node-lazy](https://github.com/pkrumins/node-lazy) for line-processing. - - var Chainsaw = require('chainsaw'); - var Lazy = require('lazy'); - - module.exports = Prompt; - function Prompt (stream) { - var waiting = []; - var lines = []; - var lazy = Lazy(stream).lines.map(String) - .forEach(function (line) { - if (waiting.length) { - var w = waiting.shift(); - w(line); - } - else lines.push(line); - }) - ; - - var vars = {}; - return Chainsaw(function (saw) { - this.getline = function (f) { - var g = function (line) { - saw.nest(f, line, vars); - }; - - if (lines.length) g(lines.shift()); - else waiting.push(g); - }; - - this.do = function (cb) { - saw.nest(cb, vars); - }; - }); - } - -And now for the new Prompt() module in action: - - var util = require('util'); - var stdin = process.openStdin(); - - Prompt(stdin) - .do(function () { - util.print('x = '); - }) - .getline(function (line, vars) { - vars.x = parseInt(line, 10); - }) - .do(function () { - util.print('y = '); - }) - .getline(function (line, vars) { - vars.y = parseInt(line, 10); - }) - .do(function (vars) { - if (vars.x + vars.y < 10) { - util.print('z = '); - this.getline(function (line) { - vars.z = parseInt(line, 10); - }) - } - else { - vars.z = 0; - } - }) - .do(function (vars) { - console.log('x + y + z = ' + (vars.x + vars.y + vars.z)); - process.exit(); - }) - ; - -Installation -============ - -With [npm](http://github.com/isaacs/npm), just do: - npm install chainsaw - -or clone this project on github: - - git clone http://github.com/substack/node-chainsaw.git - -To run the tests with [expresso](http://github.com/visionmedia/expresso), -just do: - - expresso - diff --git a/node_modules/findit/node_modules/seq/node_modules/chainsaw/examples/add_do.js b/node_modules/findit/node_modules/seq/node_modules/chainsaw/examples/add_do.js deleted file mode 100644 index 378705d..0000000 --- a/node_modules/findit/node_modules/seq/node_modules/chainsaw/examples/add_do.js +++ /dev/null @@ -1,25 +0,0 @@ -var Chainsaw = require('chainsaw'); - -function AddDo (sum) { - return Chainsaw(function (saw) { - this.add = function (n) { - sum += n; - saw.next(); - }; - - this.do = function (cb) { - saw.nest(cb, sum); - }; - }); -} - -AddDo(0) - .add(5) - .add(10) - .do(function (sum) { - if (sum > 12) this.add(-10); - }) - .do(function (sum) { - console.log('Sum: ' + sum); - }) -; diff --git a/node_modules/findit/node_modules/seq/node_modules/chainsaw/examples/prompt.js b/node_modules/findit/node_modules/seq/node_modules/chainsaw/examples/prompt.js deleted file mode 100644 index 0a06d71..0000000 --- a/node_modules/findit/node_modules/seq/node_modules/chainsaw/examples/prompt.js +++ /dev/null @@ -1,67 +0,0 @@ -var Chainsaw = require('chainsaw'); -var Lazy = require('lazy'); - -module.exports = Prompt; -function Prompt (stream) { - var waiting = []; - var lines = []; - var lazy = Lazy(stream).lines.map(String) - .forEach(function (line) { - if (waiting.length) { - var w = waiting.shift(); - w(line); - } - else lines.push(line); - }) - ; - - var vars = {}; - return Chainsaw(function (saw) { - this.getline = function (f) { - var g = function (line) { - saw.nest(f, line, vars); - }; - - if (lines.length) g(lines.shift()); - else waiting.push(g); - }; - - this.do = function (cb) { - saw.nest(cb, vars); - }; - }); -} - -var util = require('util'); -if (__filename === process.argv[1]) { - var stdin = process.openStdin(); - Prompt(stdin) - .do(function () { - util.print('x = '); - }) - .getline(function (line, vars) { - vars.x = parseInt(line, 10); - }) - .do(function () { - util.print('y = '); - }) - .getline(function (line, vars) { - vars.y = parseInt(line, 10); - }) - .do(function (vars) { - if (vars.x + vars.y < 10) { - util.print('z = '); - this.getline(function (line) { - vars.z = parseInt(line, 10); - }) - } - else { - vars.z = 0; - } - }) - .do(function (vars) { - console.log('x + y + z = ' + (vars.x + vars.y + vars.z)); - process.exit(); - }) - ; -} diff --git a/node_modules/findit/node_modules/seq/node_modules/chainsaw/index.js b/node_modules/findit/node_modules/seq/node_modules/chainsaw/index.js deleted file mode 100755 index 597cc48..0000000 --- a/node_modules/findit/node_modules/seq/node_modules/chainsaw/index.js +++ /dev/null @@ -1,108 +0,0 @@ -var Traverse = require('traverse'); -var EventEmitter = require('events').EventEmitter; - -module.exports = Chainsaw; -function Chainsaw (builder) { - var saw = Chainsaw.saw(builder, {}); - var r = builder.call(saw.handlers, saw); - if (r !== undefined) saw.handlers = r; - return saw.chain(); -}; - -Chainsaw.saw = function (builder, handlers) { - var saw = new EventEmitter; - saw.handlers = handlers; - saw.actions = []; - saw.step = 0; - - saw.chain = function () { - var ch = Traverse(saw.handlers).map(function (node) { - if (this.isRoot) return node; - var ps = this.path; - - if (typeof node === 'function') { - this.update(function () { - saw.actions.push({ - path : ps, - args : [].slice.call(arguments) - }); - return ch; - }); - } - }); - - process.nextTick(function () { - saw.emit('begin'); - saw.next(); - }); - - return ch; - }; - - saw.next = function () { - var action = saw.actions[saw.step]; - saw.step ++; - - if (!action) { - saw.emit('end'); - } - else if (!action.trap) { - var node = saw.handlers; - action.path.forEach(function (key) { node = node[key] }); - node.apply(saw.handlers, action.args); - } - }; - - saw.nest = function (cb) { - var args = [].slice.call(arguments, 1); - var autonext = true; - - if (typeof cb === 'boolean') { - var autonext = cb; - cb = args.shift(); - } - - var s = Chainsaw.saw(builder, {}); - var r = builder.call(s.handlers, s); - - if (r !== undefined) s.handlers = r; - cb.apply(s.chain(), args); - if (autonext !== false) s.on('end', saw.next); - }; - - saw.trap = function (name, cb) { - var ps = Array.isArray(name) ? name : [name]; - saw.actions.push({ - path : ps, - step : saw.step, - cb : cb, - trap : true - }); - }; - - saw.down = function (name) { - var ps = (Array.isArray(name) ? name : [name]).join('/'); - var i = saw.actions.slice(saw.step).map(function (x) { - if (x.trap && x.step <= saw.step) return false; - return x.path.join('/') == ps; - }).indexOf(true); - - if (i >= 0) saw.step += i; - else saw.step = saw.actions.length; - - var act = saw.actions[saw.step - 1]; - if (act && act.trap) { - // It's a trap! - saw.step = act.step; - act.cb(); - } - else saw.next(); - }; - - saw.jump = function (step) { - saw.step = step; - saw.next(); - }; - - return saw; -}; diff --git a/node_modules/findit/node_modules/seq/node_modules/chainsaw/node_modules/traverse/.npmignore b/node_modules/findit/node_modules/seq/node_modules/chainsaw/node_modules/traverse/.npmignore deleted file mode 100644 index 3c3629e..0000000 --- a/node_modules/findit/node_modules/seq/node_modules/chainsaw/node_modules/traverse/.npmignore +++ /dev/null @@ -1 +0,0 @@ -node_modules diff --git a/node_modules/findit/node_modules/seq/node_modules/chainsaw/node_modules/traverse/LICENSE b/node_modules/findit/node_modules/seq/node_modules/chainsaw/node_modules/traverse/LICENSE deleted file mode 100644 index 7b75500..0000000 --- a/node_modules/findit/node_modules/seq/node_modules/chainsaw/node_modules/traverse/LICENSE +++ /dev/null @@ -1,24 +0,0 @@ -Copyright 2010 James Halliday (mail@substack.net) - -This project is free software released under the MIT/X11 license: -http://www.opensource.org/licenses/mit-license.php - -Copyright 2010 James Halliday (mail@substack.net) - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. diff --git a/node_modules/findit/node_modules/seq/node_modules/chainsaw/node_modules/traverse/README.markdown b/node_modules/findit/node_modules/seq/node_modules/chainsaw/node_modules/traverse/README.markdown deleted file mode 100644 index 5728639..0000000 --- a/node_modules/findit/node_modules/seq/node_modules/chainsaw/node_modules/traverse/README.markdown +++ /dev/null @@ -1,247 +0,0 @@ -traverse -======== - -Traverse and transform objects by visiting every node on a recursive walk. - -examples -======== - -transform negative numbers in-place ------------------------------------ - -negative.js - -````javascript -var traverse = require('traverse'); -var obj = [ 5, 6, -3, [ 7, 8, -2, 1 ], { f : 10, g : -13 } ]; - -traverse(obj).forEach(function (x) { - if (x < 0) this.update(x + 128); -}); - -console.dir(obj); -```` - -Output: - - [ 5, 6, 125, [ 7, 8, 126, 1 ], { f: 10, g: 115 } ] - -collect leaf nodes ------------------- - -leaves.js - -````javascript -var traverse = require('traverse'); - -var obj = { - a : [1,2,3], - b : 4, - c : [5,6], - d : { e : [7,8], f : 9 }, -}; - -var leaves = traverse(obj).reduce(function (acc, x) { - if (this.isLeaf) acc.push(x); - return acc; -}, []); - -console.dir(leaves); -```` - -Output: - - [ 1, 2, 3, 4, 5, 6, 7, 8, 9 ] - -context -======= - -Each method that takes a callback has a context (its `this` object) with these -attributes: - -this.node ---------- - -The present node on the recursive walk - -this.path ---------- - -An array of string keys from the root to the present node - -this.parent ------------ - -The context of the node's parent. -This is `undefined` for the root node. - -this.key --------- - -The name of the key of the present node in its parent. -This is `undefined` for the root node. - -this.isRoot, this.notRoot -------------------------- - -Whether the present node is the root node - -this.isLeaf, this.notLeaf -------------------------- - -Whether or not the present node is a leaf node (has no children) - -this.level ----------- - -Depth of the node within the traversal - -this.circular -------------- - -If the node equals one of its parents, the `circular` attribute is set to the -context of that parent and the traversal progresses no deeper. - -this.update(value) ------------------- - -Set a new value for the present node. - -this.remove() -------------- - -Remove the current element from the output. If the node is in an Array it will -be spliced off. Otherwise it will be deleted from its parent. - -this.delete() -------------- - -Delete the current element from its parent in the output. Calls `delete` even on -Arrays. - -this.before(fn) ---------------- - -Call this function before any of the children are traversed. - -this.after(fn) --------------- - -Call this function after any of the children are traversed. - -this.pre(fn) ------------- - -Call this function before each of the children are traversed. - -this.post(fn) -------------- - -Call this function after each of the children are traversed. - -methods -======= - -.map(fn) --------- - -Execute `fn` for each node in the object and return a new object with the -results of the walk. To update nodes in the result use `this.update(value)`. - -.forEach(fn) ------------- - -Execute `fn` for each node in the object but unlike `.map()`, when -`this.update()` is called it updates the object in-place. - -.reduce(fn, acc) ----------------- - -For each node in the object, perform a -[left-fold](http://en.wikipedia.org/wiki/Fold_(higher-order_function)) -with the return value of `fn(acc, node)`. - -If `acc` isn't specified, `acc` is set to the root object for the first step -and the root element is skipped. - -.deepEqual(obj) ---------------- - -Returns a boolean, whether the instance value is equal to the supplied object -along a deep traversal using some opinionated choices. - -Some notes: - -* RegExps are equal if their .toString()s match, but not functions since -functions can close over different variables. - -* Date instances are compared using `.getTime()` just like `assert.deepEqual()`. - -* Circular references must refer to the same paths within the data structure for -both objects. For instance, in this snippet: - -````javascript -var a = [1]; -a.push(a); // a = [ 1, *a ] - -var b = [1]; -b.push(a); // b = [ 1, [ 1, *a ] ] -```` - -`a` is not the same as `b` since even though the expansion is the same, the -circular references in each refer to different paths into the data structure. - -However, in: - -````javascript -var c = [1]; -c.push(c); // c = [ 1, *c ]; -```` - -`c` is equal to `a` in a `deepEqual()` because they have the same terminal node -structure. - -* Arguments objects are not arrays and neither are they the same as regular -objects. - -* Instances created with `new` of String, Boolean, and Number types are never -equal to the native versions. - -.paths() --------- - -Return an `Array` of every possible non-cyclic path in the object. -Paths are `Array`s of string keys. - -.nodes() --------- - -Return an `Array` of every node in the object. - -.clone() --------- - -Create a deep clone of the object. - -installation -============ - -Using npm: - npm install traverse - -Or check out the repository and link your development copy: - git clone http://github.com/substack/js-traverse.git - cd js-traverse - npm link . - -You can test traverse with "expresso":http://github.com/visionmedia/expresso -(`npm install expresso`): - js-traverse $ expresso - - 100% wahoo, your stuff is not broken! - -hash transforms -=============== - -This library formerly had a hash transformation component. It has been -[moved to the hashish package](https://github.com/substack/node-hashish). diff --git a/node_modules/findit/node_modules/seq/node_modules/chainsaw/node_modules/traverse/examples/json.js b/node_modules/findit/node_modules/seq/node_modules/chainsaw/node_modules/traverse/examples/json.js deleted file mode 100755 index f3bd989..0000000 --- a/node_modules/findit/node_modules/seq/node_modules/chainsaw/node_modules/traverse/examples/json.js +++ /dev/null @@ -1,16 +0,0 @@ -var Traverse = require('traverse'); - -var id = 54; -var callbacks = {}; -var obj = { moo : function () {}, foo : [2,3,4, function () {}] }; - -var scrubbed = Traverse(obj).map(function (x) { - if (typeof x === 'function') { - callbacks[id] = { id : id, f : x, path : this.path }; - this.update('[Function]'); - id++; - } -}); - -console.dir(scrubbed); -console.dir(callbacks); diff --git a/node_modules/findit/node_modules/seq/node_modules/chainsaw/node_modules/traverse/examples/leaves.js b/node_modules/findit/node_modules/seq/node_modules/chainsaw/node_modules/traverse/examples/leaves.js deleted file mode 100755 index ef5325f..0000000 --- a/node_modules/findit/node_modules/seq/node_modules/chainsaw/node_modules/traverse/examples/leaves.js +++ /dev/null @@ -1,15 +0,0 @@ -var Traverse = require('traverse'); - -var obj = { - a : [1,2,3], - b : 4, - c : [5,6], - d : { e : [7,8], f : 9 }, -}; - -var leaves = Traverse(obj).reduce(function (acc, x) { - if (this.isLeaf) acc.push(x); - return acc; -}, []); - -console.dir(leaves); diff --git a/node_modules/findit/node_modules/seq/node_modules/chainsaw/node_modules/traverse/examples/negative.js b/node_modules/findit/node_modules/seq/node_modules/chainsaw/node_modules/traverse/examples/negative.js deleted file mode 100755 index a3996c5..0000000 --- a/node_modules/findit/node_modules/seq/node_modules/chainsaw/node_modules/traverse/examples/negative.js +++ /dev/null @@ -1,8 +0,0 @@ -var Traverse = require('traverse'); -var obj = [ 5, 6, -3, [ 7, 8, -2, 1 ], { f : 10, g : -13 } ]; - -Traverse(obj).forEach(function (x) { - if (x < 0) this.update(x + 128); -}); - -console.dir(obj); diff --git a/node_modules/findit/node_modules/seq/node_modules/chainsaw/node_modules/traverse/examples/stringify.js b/node_modules/findit/node_modules/seq/node_modules/chainsaw/node_modules/traverse/examples/stringify.js deleted file mode 100755 index 0cef7ec..0000000 --- a/node_modules/findit/node_modules/seq/node_modules/chainsaw/node_modules/traverse/examples/stringify.js +++ /dev/null @@ -1,38 +0,0 @@ -#!/usr/bin/env node -var Traverse = require('traverse'); - -var obj = [ 'five', 6, -3, [ 7, 8, -2, 1 ], { f : 10, g : -13 } ]; - -var s = ''; -Traverse(obj).forEach(function to_s (node) { - if (Array.isArray(node)) { - this.before(function () { s += '[' }); - this.post(function (child) { - if (!child.isLast) s += ','; - }); - this.after(function () { s += ']' }); - } - else if (typeof node == 'object') { - this.before(function () { s += '{' }); - this.pre(function (x, key) { - to_s(key); - s += ':'; - }); - this.post(function (child) { - if (!child.isLast) s += ','; - }); - this.after(function () { s += '}' }); - } - else if (typeof node == 'string') { - s += '"' + node.toString().replace(/"/g, '\\"') + '"'; - } - else if (typeof node == 'function') { - s += 'null'; - } - else { - s += node.toString(); - } -}); - -console.log('JSON.stringify: ' + JSON.stringify(obj)); -console.log('this stringify: ' + s); diff --git a/node_modules/findit/node_modules/seq/node_modules/chainsaw/node_modules/traverse/index.js b/node_modules/findit/node_modules/seq/node_modules/chainsaw/node_modules/traverse/index.js deleted file mode 100755 index 7a34c8a..0000000 --- a/node_modules/findit/node_modules/seq/node_modules/chainsaw/node_modules/traverse/index.js +++ /dev/null @@ -1,322 +0,0 @@ -module.exports = Traverse; -function Traverse (obj) { - if (!(this instanceof Traverse)) return new Traverse(obj); - this.value = obj; -} - -Traverse.prototype.get = function (ps) { - var node = this.value; - for (var i = 0; i < ps.length; i ++) { - var key = ps[i]; - if (!Object.hasOwnProperty.call(node, key)) { - node = undefined; - break; - } - node = node[key]; - } - return node; -}; - -Traverse.prototype.set = function (ps, value) { - var node = this.value; - for (var i = 0; i < ps.length - 1; i ++) { - var key = ps[i]; - if (!Object.hasOwnProperty.call(node, key)) node[key] = {}; - node = node[key]; - } - node[ps[i]] = value; - return value; -}; - -Traverse.prototype.map = function (cb) { - return walk(this.value, cb, true); -}; - -Traverse.prototype.forEach = function (cb) { - this.value = walk(this.value, cb, false); - return this.value; -}; - -Traverse.prototype.reduce = function (cb, init) { - var skip = arguments.length === 1; - var acc = skip ? this.value : init; - this.forEach(function (x) { - if (!this.isRoot || !skip) { - acc = cb.call(this, acc, x); - } - }); - return acc; -}; - -Traverse.prototype.deepEqual = function (obj) { - if (arguments.length !== 1) { - throw new Error( - 'deepEqual requires exactly one object to compare against' - ); - } - - var equal = true; - var node = obj; - - this.forEach(function (y) { - var notEqual = (function () { - equal = false; - //this.stop(); - return undefined; - }).bind(this); - - //if (node === undefined || node === null) return notEqual(); - - if (!this.isRoot) { - /* - if (!Object.hasOwnProperty.call(node, this.key)) { - return notEqual(); - } - */ - if (typeof node !== 'object') return notEqual(); - node = node[this.key]; - } - - var x = node; - - this.post(function () { - node = x; - }); - - var toS = function (o) { - return Object.prototype.toString.call(o); - }; - - if (this.circular) { - if (Traverse(obj).get(this.circular.path) !== x) notEqual(); - } - else if (typeof x !== typeof y) { - notEqual(); - } - else if (x === null || y === null || x === undefined || y === undefined) { - if (x !== y) notEqual(); - } - else if (x.__proto__ !== y.__proto__) { - notEqual(); - } - else if (x === y) { - // nop - } - else if (typeof x === 'function') { - if (x instanceof RegExp) { - // both regexps on account of the __proto__ check - if (x.toString() != y.toString()) notEqual(); - } - else if (x !== y) notEqual(); - } - else if (typeof x === 'object') { - if (toS(y) === '[object Arguments]' - || toS(x) === '[object Arguments]') { - if (toS(x) !== toS(y)) { - notEqual(); - } - } - else if (x instanceof Date || y instanceof Date) { - if (!(x instanceof Date) || !(y instanceof Date) - || x.getTime() !== y.getTime()) { - notEqual(); - } - } - else { - var kx = Object.keys(x); - var ky = Object.keys(y); - if (kx.length !== ky.length) return notEqual(); - for (var i = 0; i < kx.length; i++) { - var k = kx[i]; - if (!Object.hasOwnProperty.call(y, k)) { - notEqual(); - } - } - } - } - }); - - return equal; -}; - -Traverse.prototype.paths = function () { - var acc = []; - this.forEach(function (x) { - acc.push(this.path); - }); - return acc; -}; - -Traverse.prototype.nodes = function () { - var acc = []; - this.forEach(function (x) { - acc.push(this.node); - }); - return acc; -}; - -Traverse.prototype.clone = function () { - var parents = [], nodes = []; - - return (function clone (src) { - for (var i = 0; i < parents.length; i++) { - if (parents[i] === src) { - return nodes[i]; - } - } - - if (typeof src === 'object' && src !== null) { - var dst = copy(src); - - parents.push(src); - nodes.push(dst); - - Object.keys(src).forEach(function (key) { - dst[key] = clone(src[key]); - }); - - parents.pop(); - nodes.pop(); - return dst; - } - else { - return src; - } - })(this.value); -}; - -function walk (root, cb, immutable) { - var path = []; - var parents = []; - var alive = true; - - return (function walker (node_) { - var node = immutable ? copy(node_) : node_; - var modifiers = {}; - - var state = { - node : node, - node_ : node_, - path : [].concat(path), - parent : parents.slice(-1)[0], - key : path.slice(-1)[0], - isRoot : path.length === 0, - level : path.length, - circular : null, - update : function (x) { - if (!state.isRoot) { - state.parent.node[state.key] = x; - } - state.node = x; - }, - 'delete' : function () { - delete state.parent.node[state.key]; - }, - remove : function () { - if (Array.isArray(state.parent.node)) { - state.parent.node.splice(state.key, 1); - } - else { - delete state.parent.node[state.key]; - } - }, - before : function (f) { modifiers.before = f }, - after : function (f) { modifiers.after = f }, - pre : function (f) { modifiers.pre = f }, - post : function (f) { modifiers.post = f }, - stop : function () { alive = false } - }; - - if (!alive) return state; - - if (typeof node === 'object' && node !== null) { - state.isLeaf = Object.keys(node).length == 0; - - for (var i = 0; i < parents.length; i++) { - if (parents[i].node_ === node_) { - state.circular = parents[i]; - break; - } - } - } - else { - state.isLeaf = true; - } - - state.notLeaf = !state.isLeaf; - state.notRoot = !state.isRoot; - - // use return values to update if defined - var ret = cb.call(state, state.node); - if (ret !== undefined && state.update) state.update(ret); - if (modifiers.before) modifiers.before.call(state, state.node); - - if (typeof state.node == 'object' - && state.node !== null && !state.circular) { - parents.push(state); - - var keys = Object.keys(state.node); - keys.forEach(function (key, i) { - path.push(key); - - if (modifiers.pre) modifiers.pre.call(state, state.node[key], key); - - var child = walker(state.node[key]); - if (immutable && Object.hasOwnProperty.call(state.node, key)) { - state.node[key] = child.node; - } - - child.isLast = i == keys.length - 1; - child.isFirst = i == 0; - - if (modifiers.post) modifiers.post.call(state, child); - - path.pop(); - }); - parents.pop(); - } - - if (modifiers.after) modifiers.after.call(state, state.node); - - return state; - })(root).node; -} - -Object.keys(Traverse.prototype).forEach(function (key) { - Traverse[key] = function (obj) { - var args = [].slice.call(arguments, 1); - var t = Traverse(obj); - return t[key].apply(t, args); - }; -}); - -function copy (src) { - if (typeof src === 'object' && src !== null) { - var dst; - - if (Array.isArray(src)) { - dst = []; - } - else if (src instanceof Date) { - dst = new Date(src); - } - else if (src instanceof Boolean) { - dst = new Boolean(src); - } - else if (src instanceof Number) { - dst = new Number(src); - } - else if (src instanceof String) { - dst = new String(src); - } - else { - dst = Object.create(Object.getPrototypeOf(src)); - } - - Object.keys(src).forEach(function (key) { - dst[key] = src[key]; - }); - return dst; - } - else return src; -} diff --git a/node_modules/findit/node_modules/seq/node_modules/chainsaw/node_modules/traverse/package.json b/node_modules/findit/node_modules/seq/node_modules/chainsaw/node_modules/traverse/package.json deleted file mode 100644 index 5ab3fc6..0000000 --- a/node_modules/findit/node_modules/seq/node_modules/chainsaw/node_modules/traverse/package.json +++ /dev/null @@ -1,18 +0,0 @@ -{ - "name" : "traverse", - "version" : "0.3.9", - "description" : "Traverse and transform objects by visiting every node on a recursive walk", - "author" : "James Halliday", - "license" : "MIT/X11", - "main" : "./index", - "repository" : { - "type" : "git", - "url" : "http://github.com/substack/js-traverse.git" - }, - "devDependencies" : { - "expresso" : "0.7.x" - }, - "scripts" : { - "test" : "expresso" - } -} diff --git a/node_modules/findit/node_modules/seq/node_modules/chainsaw/node_modules/traverse/test/circular.js b/node_modules/findit/node_modules/seq/node_modules/chainsaw/node_modules/traverse/test/circular.js deleted file mode 100644 index e1eef3f..0000000 --- a/node_modules/findit/node_modules/seq/node_modules/chainsaw/node_modules/traverse/test/circular.js +++ /dev/null @@ -1,114 +0,0 @@ -var assert = require('assert'); -var Traverse = require('traverse'); -var util = require('util'); - -exports.circular = function () { - var obj = { x : 3 }; - obj.y = obj; - var foundY = false; - Traverse(obj).forEach(function (x) { - if (this.path.join('') == 'y') { - assert.equal( - util.inspect(this.circular.node), - util.inspect(obj) - ); - foundY = true; - } - }); - assert.ok(foundY); -}; - -exports.deepCirc = function () { - var obj = { x : [ 1, 2, 3 ], y : [ 4, 5 ] }; - obj.y[2] = obj; - - var times = 0; - Traverse(obj).forEach(function (x) { - if (this.circular) { - assert.deepEqual(this.circular.path, []); - assert.deepEqual(this.path, [ 'y', 2 ]); - times ++; - } - }); - - assert.deepEqual(times, 1); -}; - -exports.doubleCirc = function () { - var obj = { x : [ 1, 2, 3 ], y : [ 4, 5 ] }; - obj.y[2] = obj; - obj.x.push(obj.y); - - var circs = []; - Traverse(obj).forEach(function (x) { - if (this.circular) { - circs.push({ circ : this.circular, self : this, node : x }); - } - }); - - assert.deepEqual(circs[0].self.path, [ 'x', 3, 2 ]); - assert.deepEqual(circs[0].circ.path, []); - - assert.deepEqual(circs[1].self.path, [ 'y', 2 ]); - assert.deepEqual(circs[1].circ.path, []); - - assert.deepEqual(circs.length, 2); -}; - -exports.circDubForEach = function () { - var obj = { x : [ 1, 2, 3 ], y : [ 4, 5 ] }; - obj.y[2] = obj; - obj.x.push(obj.y); - - Traverse(obj).forEach(function (x) { - if (this.circular) this.update('...'); - }); - - assert.deepEqual(obj, { x : [ 1, 2, 3, [ 4, 5, '...' ] ], y : [ 4, 5, '...' ] }); -}; - -exports.circDubMap = function () { - var obj = { x : [ 1, 2, 3 ], y : [ 4, 5 ] }; - obj.y[2] = obj; - obj.x.push(obj.y); - - var c = Traverse(obj).map(function (x) { - if (this.circular) { - this.update('...'); - } - }); - - assert.deepEqual(c, { x : [ 1, 2, 3, [ 4, 5, '...' ] ], y : [ 4, 5, '...' ] }); -}; - -exports.circClone = function () { - var obj = { x : [ 1, 2, 3 ], y : [ 4, 5 ] }; - obj.y[2] = obj; - obj.x.push(obj.y); - - var clone = Traverse.clone(obj); - assert.ok(obj !== clone); - - assert.ok(clone.y[2] === clone); - assert.ok(clone.y[2] !== obj); - assert.ok(clone.x[3][2] === clone); - assert.ok(clone.x[3][2] !== obj); - assert.deepEqual(clone.x.slice(0,3), [1,2,3]); - assert.deepEqual(clone.y.slice(0,2), [4,5]); -}; - -exports.circMapScrub = function () { - var obj = { a : 1, b : 2 }; - obj.c = obj; - - var scrubbed = Traverse(obj).map(function (node) { - if (this.circular) this.remove(); - }); - assert.deepEqual( - Object.keys(scrubbed).sort(), - [ 'a', 'b' ] - ); - assert.ok(Traverse.deepEqual(scrubbed, { a : 1, b : 2 })); - - assert.equal(obj.c, obj); -}; diff --git a/node_modules/findit/node_modules/seq/node_modules/chainsaw/node_modules/traverse/test/date.js b/node_modules/findit/node_modules/seq/node_modules/chainsaw/node_modules/traverse/test/date.js deleted file mode 100644 index 2cb8252..0000000 --- a/node_modules/findit/node_modules/seq/node_modules/chainsaw/node_modules/traverse/test/date.js +++ /dev/null @@ -1,35 +0,0 @@ -var assert = require('assert'); -var Traverse = require('traverse'); - -exports.dateEach = function () { - var obj = { x : new Date, y : 10, z : 5 }; - - var counts = {}; - - Traverse(obj).forEach(function (node) { - var t = (node instanceof Date && 'Date') || typeof node; - counts[t] = (counts[t] || 0) + 1; - }); - - assert.deepEqual(counts, { - object : 1, - Date : 1, - number : 2, - }); -}; - -exports.dateMap = function () { - var obj = { x : new Date, y : 10, z : 5 }; - - var res = Traverse(obj).map(function (node) { - if (typeof node === 'number') this.update(node + 100); - }); - - assert.ok(obj.x !== res.x); - assert.deepEqual(res, { - x : obj.x, - y : 110, - z : 105, - }); -}; - diff --git a/node_modules/findit/node_modules/seq/node_modules/chainsaw/node_modules/traverse/test/equal.js b/node_modules/findit/node_modules/seq/node_modules/chainsaw/node_modules/traverse/test/equal.js deleted file mode 100644 index 4d732fa..0000000 --- a/node_modules/findit/node_modules/seq/node_modules/chainsaw/node_modules/traverse/test/equal.js +++ /dev/null @@ -1,219 +0,0 @@ -var assert = require('assert'); -var traverse = require('traverse'); - -exports.deepDates = function () { - assert.ok( - traverse.deepEqual( - { d : new Date, x : [ 1, 2, 3 ] }, - { d : new Date, x : [ 1, 2, 3 ] } - ), - 'dates should be equal' - ); - - var d0 = new Date; - setTimeout(function () { - assert.ok( - !traverse.deepEqual( - { d : d0, x : [ 1, 2, 3 ], }, - { d : new Date, x : [ 1, 2, 3 ] } - ), - 'microseconds should count in date equality' - ); - }, 5); -}; - -exports.deepCircular = function () { - var a = [1]; - a.push(a); // a = [ 1, *a ] - - var b = [1]; - b.push(a); // b = [ 1, [ 1, *a ] ] - - assert.ok( - !traverse.deepEqual(a, b), - 'circular ref mount points count towards equality' - ); - - var c = [1]; - c.push(c); // c = [ 1, *c ] - assert.ok( - traverse.deepEqual(a, c), - 'circular refs are structurally the same here' - ); - - var d = [1]; - d.push(a); // c = [ 1, [ 1, *d ] ] - assert.ok( - traverse.deepEqual(b, d), - 'non-root circular ref structural comparison' - ); -}; - -exports.deepInstances = function () { - assert.ok( - !traverse.deepEqual([ new Boolean(false) ], [ false ]), - 'boolean instances are not real booleans' - ); - - assert.ok( - !traverse.deepEqual([ new String('x') ], [ 'x' ]), - 'string instances are not real strings' - ); - - assert.ok( - !traverse.deepEqual([ new Number(4) ], [ 4 ]), - 'number instances are not real numbers' - ); - - assert.ok( - traverse.deepEqual([ new RegExp('x') ], [ /x/ ]), - 'regexp instances are real regexps' - ); - - assert.ok( - !traverse.deepEqual([ new RegExp(/./) ], [ /../ ]), - 'these regexps aren\'t the same' - ); - - assert.ok( - !traverse.deepEqual( - [ function (x) { return x * 2 } ], - [ function (x) { return x * 2 } ] - ), - 'functions with the same .toString() aren\'t necessarily the same' - ); - - var f = function (x) { return x * 2 }; - assert.ok( - traverse.deepEqual([ f ], [ f ]), - 'these functions are actually equal' - ); -}; - -exports.deepEqual = function () { - assert.ok( - !traverse.deepEqual([ 1, 2, 3 ], { 0 : 1, 1 : 2, 2 : 3 }), - 'arrays are not objects' - ); -}; - -exports.falsy = function () { - assert.ok( - !traverse.deepEqual([ undefined ], [ null ]), - 'null is not undefined!' - ); - - assert.ok( - !traverse.deepEqual([ null ], [ undefined ]), - 'undefined is not null!' - ); - - assert.ok( - !traverse.deepEqual( - { a : 1, b : 2, c : [ 3, undefined, 5 ] }, - { a : 1, b : 2, c : [ 3, null, 5 ] } - ), - 'undefined is not null, however deeply!' - ); - - assert.ok( - !traverse.deepEqual( - { a : 1, b : 2, c : [ 3, undefined, 5 ] }, - { a : 1, b : 2, c : [ 3, null, 5 ] } - ), - 'null is not undefined, however deeply!' - ); - - assert.ok( - !traverse.deepEqual( - { a : 1, b : 2, c : [ 3, undefined, 5 ] }, - { a : 1, b : 2, c : [ 3, null, 5 ] } - ), - 'null is not undefined, however deeply!' - ); -}; - -exports.deletedArrayEqual = function () { - var xs = [ 1, 2, 3, 4 ]; - delete xs[2]; - - var ys = Object.create(Array.prototype); - ys[0] = 1; - ys[1] = 2; - ys[3] = 4; - - assert.ok( - traverse.deepEqual(xs, ys), - 'arrays with deleted elements are only equal to' - + ' arrays with similarly deleted elements' - ); - - assert.ok( - !traverse.deepEqual(xs, [ 1, 2, undefined, 4 ]), - 'deleted array elements cannot be undefined' - ); - - assert.ok( - !traverse.deepEqual(xs, [ 1, 2, null, 4 ]), - 'deleted array elements cannot be null' - ); -}; - -exports.deletedObjectEqual = function () { - var obj = { a : 1, b : 2, c : 3 }; - delete obj.c; - - assert.ok( - traverse.deepEqual(obj, { a : 1, b : 2 }), - 'deleted object elements should not show up' - ); - - assert.ok( - !traverse.deepEqual(obj, { a : 1, b : 2, c : undefined }), - 'deleted object elements are not undefined' - ); - - assert.ok( - !traverse.deepEqual(obj, { a : 1, b : 2, c : null }), - 'deleted object elements are not null' - ); -}; - -exports.emptyKeyEqual = function () { - assert.ok(!traverse.deepEqual( - { a : 1 }, { a : 1, '' : 55 } - )); -}; - -exports.deepArguments = function () { - assert.ok( - !traverse.deepEqual( - [ 4, 5, 6 ], - (function () { return arguments })(4, 5, 6) - ), - 'arguments are not arrays' - ); - - assert.ok( - traverse.deepEqual( - (function () { return arguments })(4, 5, 6), - (function () { return arguments })(4, 5, 6) - ), - 'arguments should equal' - ); -}; - -exports.deepUn = function () { - assert.ok(!traverse.deepEqual({ a : 1, b : 2 }, undefined)); - assert.ok(!traverse.deepEqual({ a : 1, b : 2 }, {})); - assert.ok(!traverse.deepEqual(undefined, { a : 1, b : 2 })); - assert.ok(!traverse.deepEqual({}, { a : 1, b : 2 })); - assert.ok(traverse.deepEqual(undefined, undefined)); - assert.ok(traverse.deepEqual(null, null)); - assert.ok(!traverse.deepEqual(undefined, null)); -}; - -exports.deepLevels = function () { - var xs = [ 1, 2, [ 3, 4, [ 5, 6 ] ] ]; - assert.ok(!traverse.deepEqual(xs, [])); -}; diff --git a/node_modules/findit/node_modules/seq/node_modules/chainsaw/node_modules/traverse/test/instance.js b/node_modules/findit/node_modules/seq/node_modules/chainsaw/node_modules/traverse/test/instance.js deleted file mode 100644 index 501981f..0000000 --- a/node_modules/findit/node_modules/seq/node_modules/chainsaw/node_modules/traverse/test/instance.js +++ /dev/null @@ -1,17 +0,0 @@ -var assert = require('assert'); -var Traverse = require('traverse'); -var EventEmitter = require('events').EventEmitter; - -exports['check instanceof on node elems'] = function () { - - var counts = { emitter : 0 }; - - Traverse([ new EventEmitter, 3, 4, { ev : new EventEmitter }]) - .forEach(function (node) { - if (node instanceof EventEmitter) counts.emitter ++; - }) - ; - - assert.equal(counts.emitter, 2); -}; - diff --git a/node_modules/findit/node_modules/seq/node_modules/chainsaw/node_modules/traverse/test/interface.js b/node_modules/findit/node_modules/seq/node_modules/chainsaw/node_modules/traverse/test/interface.js deleted file mode 100644 index df5b037..0000000 --- a/node_modules/findit/node_modules/seq/node_modules/chainsaw/node_modules/traverse/test/interface.js +++ /dev/null @@ -1,42 +0,0 @@ -var assert = require('assert'); -var Traverse = require('traverse'); - -exports['interface map'] = function () { - var obj = { a : [ 5,6,7 ], b : { c : [8] } }; - - assert.deepEqual( - Traverse.paths(obj) - .sort() - .map(function (path) { return path.join('/') }) - .slice(1) - .join(' ') - , - 'a a/0 a/1 a/2 b b/c b/c/0' - ); - - assert.deepEqual( - Traverse.nodes(obj), - [ - { a: [ 5, 6, 7 ], b: { c: [ 8 ] } }, - [ 5, 6, 7 ], 5, 6, 7, - { c: [ 8 ] }, [ 8 ], 8 - ] - ); - - assert.deepEqual( - Traverse.map(obj, function (node) { - if (typeof node == 'number') { - return node + 1000; - } - else if (Array.isArray(node)) { - return node.join(' '); - } - }), - { a: '5 6 7', b: { c: '8' } } - ); - - var nodes = 0; - Traverse.forEach(obj, function (node) { nodes ++ }); - assert.deepEqual(nodes, 8); -}; - diff --git a/node_modules/findit/node_modules/seq/node_modules/chainsaw/node_modules/traverse/test/json.js b/node_modules/findit/node_modules/seq/node_modules/chainsaw/node_modules/traverse/test/json.js deleted file mode 100644 index bf36620..0000000 --- a/node_modules/findit/node_modules/seq/node_modules/chainsaw/node_modules/traverse/test/json.js +++ /dev/null @@ -1,47 +0,0 @@ -var assert = require('assert'); -var Traverse = require('traverse'); - -exports['json test'] = function () { - var id = 54; - var callbacks = {}; - var obj = { moo : function () {}, foo : [2,3,4, function () {}] }; - - var scrubbed = Traverse(obj).map(function (x) { - if (typeof x === 'function') { - callbacks[id] = { id : id, f : x, path : this.path }; - this.update('[Function]'); - id++; - } - }); - - assert.equal( - scrubbed.moo, '[Function]', - 'obj.moo replaced with "[Function]"' - ); - - assert.equal( - scrubbed.foo[3], '[Function]', - 'obj.foo[3] replaced with "[Function]"' - ); - - assert.deepEqual(scrubbed, { - moo : '[Function]', - foo : [ 2, 3, 4, "[Function]" ] - }, 'Full JSON string matches'); - - assert.deepEqual( - typeof obj.moo, 'function', - 'Original obj.moo still a function' - ); - - assert.deepEqual( - typeof obj.foo[3], 'function', - 'Original obj.foo[3] still a function' - ); - - assert.deepEqual(callbacks, { - 54: { id: 54, f : obj.moo, path: [ 'moo' ] }, - 55: { id: 55, f : obj.foo[3], path: [ 'foo', '3' ] }, - }, 'Check the generated callbacks list'); -}; - diff --git a/node_modules/findit/node_modules/seq/node_modules/chainsaw/node_modules/traverse/test/leaves.js b/node_modules/findit/node_modules/seq/node_modules/chainsaw/node_modules/traverse/test/leaves.js deleted file mode 100644 index 4e8d280..0000000 --- a/node_modules/findit/node_modules/seq/node_modules/chainsaw/node_modules/traverse/test/leaves.js +++ /dev/null @@ -1,21 +0,0 @@ -var assert = require('assert'); -var Traverse = require('traverse'); - -exports['leaves test'] = function () { - var acc = []; - Traverse({ - a : [1,2,3], - b : 4, - c : [5,6], - d : { e : [7,8], f : 9 } - }).forEach(function (x) { - if (this.isLeaf) acc.push(x); - }); - - assert.equal( - acc.join(' '), - '1 2 3 4 5 6 7 8 9', - 'Traversal in the right(?) order' - ); -}; - diff --git a/node_modules/findit/node_modules/seq/node_modules/chainsaw/node_modules/traverse/test/mutability.js b/node_modules/findit/node_modules/seq/node_modules/chainsaw/node_modules/traverse/test/mutability.js deleted file mode 100644 index 5a4d6dd..0000000 --- a/node_modules/findit/node_modules/seq/node_modules/chainsaw/node_modules/traverse/test/mutability.js +++ /dev/null @@ -1,203 +0,0 @@ -var assert = require('assert'); -var Traverse = require('traverse'); - -exports.mutate = function () { - var obj = { a : 1, b : 2, c : [ 3, 4 ] }; - var res = Traverse(obj).forEach(function (x) { - if (typeof x === 'number' && x % 2 === 0) { - this.update(x * 10); - } - }); - assert.deepEqual(obj, res); - assert.deepEqual(obj, { a : 1, b : 20, c : [ 3, 40 ] }); -}; - -exports.mutateT = function () { - var obj = { a : 1, b : 2, c : [ 3, 4 ] }; - var res = Traverse.forEach(obj, function (x) { - if (typeof x === 'number' && x % 2 === 0) { - this.update(x * 10); - } - }); - assert.deepEqual(obj, res); - assert.deepEqual(obj, { a : 1, b : 20, c : [ 3, 40 ] }); -}; - -exports.map = function () { - var obj = { a : 1, b : 2, c : [ 3, 4 ] }; - var res = Traverse(obj).map(function (x) { - if (typeof x === 'number' && x % 2 === 0) { - this.update(x * 10); - } - }); - assert.deepEqual(obj, { a : 1, b : 2, c : [ 3, 4 ] }); - assert.deepEqual(res, { a : 1, b : 20, c : [ 3, 40 ] }); -}; - -exports.mapT = function () { - var obj = { a : 1, b : 2, c : [ 3, 4 ] }; - var res = Traverse.map(obj, function (x) { - if (typeof x === 'number' && x % 2 === 0) { - this.update(x * 10); - } - }); - assert.deepEqual(obj, { a : 1, b : 2, c : [ 3, 4 ] }); - assert.deepEqual(res, { a : 1, b : 20, c : [ 3, 40 ] }); -}; - -exports.clone = function () { - var obj = { a : 1, b : 2, c : [ 3, 4 ] }; - var res = Traverse(obj).clone(); - assert.deepEqual(obj, res); - assert.ok(obj !== res); - obj.a ++; - assert.deepEqual(res.a, 1); - obj.c.push(5); - assert.deepEqual(res.c, [ 3, 4 ]); -}; - -exports.cloneT = function () { - var obj = { a : 1, b : 2, c : [ 3, 4 ] }; - var res = Traverse.clone(obj); - assert.deepEqual(obj, res); - assert.ok(obj !== res); - obj.a ++; - assert.deepEqual(res.a, 1); - obj.c.push(5); - assert.deepEqual(res.c, [ 3, 4 ]); -}; - -exports.reduce = function () { - var obj = { a : 1, b : 2, c : [ 3, 4 ] }; - var res = Traverse(obj).reduce(function (acc, x) { - if (this.isLeaf) acc.push(x); - return acc; - }, []); - assert.deepEqual(obj, { a : 1, b : 2, c : [ 3, 4 ] }); - assert.deepEqual(res, [ 1, 2, 3, 4 ]); -}; - -exports.reduceInit = function () { - var obj = { a : 1, b : 2, c : [ 3, 4 ] }; - var res = Traverse(obj).reduce(function (acc, x) { - if (this.isRoot) assert.fail('got root'); - return acc; - }); - assert.deepEqual(obj, { a : 1, b : 2, c : [ 3, 4 ] }); - assert.deepEqual(res, obj); -}; - -exports.remove = function () { - var obj = { a : 1, b : 2, c : [ 3, 4 ] }; - Traverse(obj).forEach(function (x) { - if (this.isLeaf && x % 2 == 0) this.remove(); - }); - - assert.deepEqual(obj, { a : 1, c : [ 3 ] }); -}; - -exports.removeMap = function () { - var obj = { a : 1, b : 2, c : [ 3, 4 ] }; - var res = Traverse(obj).map(function (x) { - if (this.isLeaf && x % 2 == 0) this.remove(); - }); - - assert.deepEqual(obj, { a : 1, b : 2, c : [ 3, 4 ] }); - assert.deepEqual(res, { a : 1, c : [ 3 ] }); -}; - -exports.delete = function () { - var obj = { a : 1, b : 2, c : [ 3, 4 ] }; - Traverse(obj).forEach(function (x) { - if (this.isLeaf && x % 2 == 0) this.delete(); - }); - - assert.ok(!Traverse.deepEqual( - obj, { a : 1, c : [ 3, undefined ] } - )); - - assert.ok(Traverse.deepEqual( - obj, { a : 1, c : [ 3 ] } - )); - - assert.ok(!Traverse.deepEqual( - obj, { a : 1, c : [ 3, null ] } - )); -}; - -exports.deleteRedux = function () { - var obj = { a : 1, b : 2, c : [ 3, 4, 5 ] }; - Traverse(obj).forEach(function (x) { - if (this.isLeaf && x % 2 == 0) this.delete(); - }); - - assert.ok(!Traverse.deepEqual( - obj, { a : 1, c : [ 3, undefined, 5 ] } - )); - - assert.ok(Traverse.deepEqual( - obj, { a : 1, c : [ 3 ,, 5 ] } - )); - - assert.ok(!Traverse.deepEqual( - obj, { a : 1, c : [ 3, null, 5 ] } - )); - - assert.ok(!Traverse.deepEqual( - obj, { a : 1, c : [ 3, 5 ] } - )); -}; - -exports.deleteMap = function () { - var obj = { a : 1, b : 2, c : [ 3, 4 ] }; - var res = Traverse(obj).map(function (x) { - if (this.isLeaf && x % 2 == 0) this.delete(); - }); - - assert.ok(Traverse.deepEqual( - obj, - { a : 1, b : 2, c : [ 3, 4 ] } - )); - - var xs = [ 3, 4 ]; - delete xs[1]; - - assert.ok(Traverse.deepEqual( - res, { a : 1, c : xs } - )); - - assert.ok(Traverse.deepEqual( - res, { a : 1, c : [ 3, ] } - )); - - assert.ok(Traverse.deepEqual( - res, { a : 1, c : [ 3 ] } - )); -}; - -exports.deleteMapRedux = function () { - var obj = { a : 1, b : 2, c : [ 3, 4, 5 ] }; - var res = Traverse(obj).map(function (x) { - if (this.isLeaf && x % 2 == 0) this.delete(); - }); - - assert.ok(Traverse.deepEqual( - obj, - { a : 1, b : 2, c : [ 3, 4, 5 ] } - )); - - var xs = [ 3, 4, 5 ]; - delete xs[1]; - - assert.ok(Traverse.deepEqual( - res, { a : 1, c : xs } - )); - - assert.ok(!Traverse.deepEqual( - res, { a : 1, c : [ 3, 5 ] } - )); - - assert.ok(Traverse.deepEqual( - res, { a : 1, c : [ 3 ,, 5 ] } - )); -}; diff --git a/node_modules/findit/node_modules/seq/node_modules/chainsaw/node_modules/traverse/test/negative.js b/node_modules/findit/node_modules/seq/node_modules/chainsaw/node_modules/traverse/test/negative.js deleted file mode 100644 index 6cf287d..0000000 --- a/node_modules/findit/node_modules/seq/node_modules/chainsaw/node_modules/traverse/test/negative.js +++ /dev/null @@ -1,20 +0,0 @@ -var Traverse = require('traverse'); -var assert = require('assert'); - -exports['negative update test'] = function () { - var obj = [ 5, 6, -3, [ 7, 8, -2, 1 ], { f : 10, g : -13 } ]; - var fixed = Traverse.map(obj, function (x) { - if (x < 0) this.update(x + 128); - }); - - assert.deepEqual(fixed, - [ 5, 6, 125, [ 7, 8, 126, 1 ], { f: 10, g: 115 } ], - 'Negative values += 128' - ); - - assert.deepEqual(obj, - [ 5, 6, -3, [ 7, 8, -2, 1 ], { f: 10, g: -13 } ], - 'Original references not modified' - ); -} - diff --git a/node_modules/findit/node_modules/seq/node_modules/chainsaw/node_modules/traverse/test/obj.js b/node_modules/findit/node_modules/seq/node_modules/chainsaw/node_modules/traverse/test/obj.js deleted file mode 100644 index 9c3b0db..0000000 --- a/node_modules/findit/node_modules/seq/node_modules/chainsaw/node_modules/traverse/test/obj.js +++ /dev/null @@ -1,15 +0,0 @@ -var assert = require('assert'); -var Traverse = require('traverse'); - -exports['traverse an object with nested functions'] = function () { - var to = setTimeout(function () { - assert.fail('never ran'); - }, 1000); - - function Cons (x) { - clearTimeout(to); - assert.equal(x, 10); - }; - Traverse(new Cons(10)); -}; - diff --git a/node_modules/findit/node_modules/seq/node_modules/chainsaw/node_modules/traverse/test/stop.js b/node_modules/findit/node_modules/seq/node_modules/chainsaw/node_modules/traverse/test/stop.js deleted file mode 100644 index ef6b36e..0000000 --- a/node_modules/findit/node_modules/seq/node_modules/chainsaw/node_modules/traverse/test/stop.js +++ /dev/null @@ -1,41 +0,0 @@ -var assert = require('assert'); -var traverse = require('traverse'); - -exports.stop = function () { - var visits = 0; - traverse('abcdefghij'.split('')).forEach(function (node) { - if (typeof node === 'string') { - visits ++; - if (node === 'e') this.stop() - } - }); - - assert.equal(visits, 5); -}; - -exports.stopMap = function () { - var s = traverse('abcdefghij'.split('')).map(function (node) { - if (typeof node === 'string') { - if (node === 'e') this.stop() - return node.toUpperCase(); - } - }).join(''); - - assert.equal(s, 'ABCDEfghij'); -}; - -exports.stopReduce = function () { - var obj = { - a : [ 4, 5 ], - b : [ 6, [ 7, 8, 9 ] ] - }; - var xs = traverse(obj).reduce(function (acc, node) { - if (this.isLeaf) { - if (node === 7) this.stop(); - else acc.push(node) - } - return acc; - }, []); - - assert.deepEqual(xs, [ 4, 5, 6 ]); -}; diff --git a/node_modules/findit/node_modules/seq/node_modules/chainsaw/node_modules/traverse/test/stringify.js b/node_modules/findit/node_modules/seq/node_modules/chainsaw/node_modules/traverse/test/stringify.js deleted file mode 100644 index bf36f63..0000000 --- a/node_modules/findit/node_modules/seq/node_modules/chainsaw/node_modules/traverse/test/stringify.js +++ /dev/null @@ -1,36 +0,0 @@ -var assert = require('assert'); -var Traverse = require('traverse'); - -exports.stringify = function () { - var obj = [ 5, 6, -3, [ 7, 8, -2, 1 ], { f : 10, g : -13 } ]; - - var s = ''; - Traverse(obj).forEach(function (node) { - if (Array.isArray(node)) { - this.before(function () { s += '[' }); - this.post(function (child) { - if (!child.isLast) s += ','; - }); - this.after(function () { s += ']' }); - } - else if (typeof node == 'object') { - this.before(function () { s += '{' }); - this.pre(function (x, key) { - s += '"' + key + '"' + ':'; - }); - this.post(function (child) { - if (!child.isLast) s += ','; - }); - this.after(function () { s += '}' }); - } - else if (typeof node == 'function') { - s += 'null'; - } - else { - s += node.toString(); - } - }); - - assert.equal(s, JSON.stringify(obj)); -} - diff --git a/node_modules/findit/node_modules/seq/node_modules/chainsaw/node_modules/traverse/test/super_deep.js b/node_modules/findit/node_modules/seq/node_modules/chainsaw/node_modules/traverse/test/super_deep.js deleted file mode 100644 index 974181e..0000000 --- a/node_modules/findit/node_modules/seq/node_modules/chainsaw/node_modules/traverse/test/super_deep.js +++ /dev/null @@ -1,54 +0,0 @@ -var assert = require('assert'); -var traverse = require('traverse'); - -exports.super_deep = function () { - var util = require('util'); - var a0 = make(); - var a1 = make(); - assert.ok(traverse.deepEqual(a0, a1)); - - a0.c.d.moo = true; - assert.ok(!traverse.deepEqual(a0, a1)); - - a1.c.d.moo = true; - assert.ok(traverse.deepEqual(a0, a1)); - - // TODO: this one - //a0.c.a = a1; - //assert.ok(!traverse.deepEqual(a0, a1)); -}; - -function make () { - var a = { self : 'a' }; - var b = { self : 'b' }; - var c = { self : 'c' }; - var d = { self : 'd' }; - var e = { self : 'e' }; - - a.a = a; - a.b = b; - a.c = c; - - b.a = a; - b.b = b; - b.c = c; - - c.a = a; - c.b = b; - c.c = c; - c.d = d; - - d.a = a; - d.b = b; - d.c = c; - d.d = d; - d.e = e; - - e.a = a; - e.b = b; - e.c = c; - e.d = d; - e.e = e; - - return a; -} diff --git a/node_modules/findit/node_modules/seq/node_modules/chainsaw/package.json b/node_modules/findit/node_modules/seq/node_modules/chainsaw/package.json deleted file mode 100644 index 01aedf4..0000000 --- a/node_modules/findit/node_modules/seq/node_modules/chainsaw/package.json +++ /dev/null @@ -1,23 +0,0 @@ -{ - "name" : "chainsaw", - "version" : "0.0.9", - "description" : "Build chainable fluent interfaces the easy way... with a freakin' chainsaw!", - "main" : "./index.js", - "repository" : { - "type" : "git", - "url" : "http://github.com/substack/node-chainsaw.git" - }, - "dependencies" : { - "traverse" : ">=0.3.0 <0.4" - }, - "keywords" : [ - "chain", - "fluent", - "interface", - "monad", - "monadic" - ], - "author" : "James Halliday (http://substack.net)", - "license" : "MIT/X11", - "engine" : { "node" : ">=0.4.0" } -} diff --git a/node_modules/findit/node_modules/seq/node_modules/chainsaw/test/chainsaw.js b/node_modules/findit/node_modules/seq/node_modules/chainsaw/test/chainsaw.js deleted file mode 100644 index 0c24729..0000000 --- a/node_modules/findit/node_modules/seq/node_modules/chainsaw/test/chainsaw.js +++ /dev/null @@ -1,418 +0,0 @@ -var assert = require('assert'); -var Chainsaw = require('chainsaw'); - -exports.getset = function () { - var to = setTimeout(function () { - assert.fail('builder never fired'); - }, 1000); - - var ch = Chainsaw(function (saw) { - clearTimeout(to); - var num = 0; - - this.get = function (cb) { - cb(num); - saw.next(); - }; - - this.set = function (n) { - num = n; - saw.next(); - }; - - var ti = setTimeout(function () { - assert.fail('end event not emitted'); - }, 50); - - saw.on('end', function () { - clearTimeout(ti); - assert.equal(times, 3); - }); - }); - - var times = 0; - ch - .get(function (x) { - assert.equal(x, 0); - times ++; - }) - .set(10) - .get(function (x) { - assert.equal(x, 10); - times ++; - }) - .set(20) - .get(function (x) { - assert.equal(x, 20); - times ++; - }) - ; -}; - -exports.nest = function () { - var ch = (function () { - var vars = {}; - return Chainsaw(function (saw) { - this.do = function (cb) { - saw.nest(cb, vars); - }; - }); - })(); - - var order = []; - var to = setTimeout(function () { - assert.fail("Didn't get to the end"); - }, 50); - - ch - .do(function (vars) { - vars.x = 'y'; - order.push(1); - - this - .do(function (vs) { - order.push(2); - vs.x = 'x'; - }) - .do(function (vs) { - order.push(3); - vs.z = 'z'; - }) - ; - }) - .do(function (vars) { - vars.y = 'y'; - order.push(4); - }) - .do(function (vars) { - assert.eql(order, [1,2,3,4]); - assert.eql(vars, { x : 'x', y : 'y', z : 'z' }); - clearTimeout(to); - }) - ; -}; - -exports.nestWait = function () { - var ch = (function () { - var vars = {}; - return Chainsaw(function (saw) { - this.do = function (cb) { - saw.nest(cb, vars); - }; - - this.wait = function (n) { - setTimeout(function () { - saw.next(); - }, n); - }; - }); - })(); - - var order = []; - var to = setTimeout(function () { - assert.fail("Didn't get to the end"); - }, 1000); - - var times = {}; - - ch - .do(function (vars) { - vars.x = 'y'; - order.push(1); - - this - .do(function (vs) { - order.push(2); - vs.x = 'x'; - times.x = Date.now(); - }) - .wait(50) - .do(function (vs) { - order.push(3); - vs.z = 'z'; - - times.z = Date.now(); - var dt = times.z - times.x; - assert.ok(dt >= 50 && dt < 75); - }) - ; - }) - .do(function (vars) { - vars.y = 'y'; - order.push(4); - - times.y = Date.now(); - }) - .wait(100) - .do(function (vars) { - assert.eql(order, [1,2,3,4]); - assert.eql(vars, { x : 'x', y : 'y', z : 'z' }); - clearTimeout(to); - - times.end = Date.now(); - var dt = times.end - times.y; - assert.ok(dt >= 100 && dt < 125) - }) - ; -}; - -exports.nestNext = function () { - var ch = (function () { - var vars = {}; - return Chainsaw(function (saw) { - this.do = function (cb) { - saw.nest(false, function () { - var args = [].slice.call(arguments); - args.push(saw.next); - cb.apply(this, args); - }, vars); - }; - }); - })(); - - var order = []; - var to = setTimeout(function () { - assert.fail("Didn't get to the end"); - }, 500); - - var times = []; - - ch - .do(function (vars, next_) { - vars.x = 'y'; - order.push(1); - - this - .do(function (vs, next) { - order.push(2); - vs.x = 'x'; - setTimeout(next, 30); - }) - .do(function (vs, next) { - order.push(3); - vs.z = 'z'; - setTimeout(next, 10); - }) - .do(function () { - setTimeout(next_, 20); - }) - ; - }) - .do(function (vars, next) { - vars.y = 'y'; - order.push(4); - setTimeout(next, 5); - }) - .do(function (vars) { - assert.eql(order, [1,2,3,4]); - assert.eql(vars, { x : 'x', y : 'y', z : 'z' }); - - clearTimeout(to); - }) - ; -}; - -exports.builder = function () { - var cx = Chainsaw(function (saw) { - this.x = function () {}; - }); - assert.ok(cx.x); - - var cy = Chainsaw(function (saw) { - return { y : function () {} }; - }); - assert.ok(cy.y); - - var cz = Chainsaw(function (saw) { - return { z : function (cb) { saw.nest(cb) } }; - }); - assert.ok(cz.z); - - var to = setTimeout(function () { - assert.fail("Nested z didn't run"); - }, 50); - - cz.z(function () { - clearTimeout(to); - assert.ok(this.z); - }); -}; - -this.attr = function () { - var to = setTimeout(function () { - assert.fail("attr chain didn't finish"); - }, 50); - - var xy = []; - var ch = Chainsaw(function (saw) { - this.h = { - x : function () { - xy.push('x'); - saw.next(); - }, - y : function () { - xy.push('y'); - saw.next(); - assert.eql(xy, ['x','y']); - clearTimeout(to); - } - }; - }); - assert.ok(ch.h); - assert.ok(ch.h.x); - assert.ok(ch.h.y); - - ch.h.x().h.y(); -}; - -exports.down = function () { - var error = null; - var s; - var ch = Chainsaw(function (saw) { - s = saw; - this.raise = function (err) { - error = err; - saw.down('catch'); - }; - - this.do = function (cb) { - cb.call(this); - }; - - this.catch = function (cb) { - if (error) { - saw.nest(cb, error); - error = null; - } - else saw.next(); - }; - }); - - var to = setTimeout(function () { - assert.fail(".do() after .catch() didn't fire"); - }, 50); - - ch - .do(function () { - this.raise('pow'); - }) - .do(function () { - assert.fail("raise didn't skip over this do block"); - }) - .catch(function (err) { - assert.equal(err, 'pow'); - }) - .do(function () { - clearTimeout(to); - }) - ; -}; - -exports.trap = function () { - var error = null; - var ch = Chainsaw(function (saw) { - var pars = 0; - var stack = []; - var i = 0; - - this.par = function (cb) { - pars ++; - var j = i ++; - cb.call(function () { - pars --; - stack[j] = [].slice.call(arguments); - saw.down('result'); - }); - saw.next(); - }; - - this.join = function (cb) { - saw.trap('result', function () { - if (pars == 0) { - cb.apply(this, stack); - saw.next(); - } - }); - }; - - this.raise = function (err) { - error = err; - saw.down('catch'); - }; - - this.do = function (cb) { - cb.call(this); - }; - - this.catch = function (cb) { - if (error) { - saw.nest(cb, error); - error = null; - } - else saw.next(); - }; - }); - - var to = setTimeout(function () { - assert.fail(".do() after .join() didn't fire"); - }, 100); - var tj = setTimeout(function () { - assert.fail('.join() never fired'); - }, 100); - - var joined = false; - ch - .par(function () { - setTimeout(this.bind(null, 1), 50); - }) - .par(function () { - setTimeout(this.bind(null, 2), 25); - }) - .join(function (x, y) { - assert.equal(x[0], 1); - assert.equal(y[0], 2); - clearTimeout(tj); - joined = true; - }) - .do(function () { - clearTimeout(to); - assert.ok(joined); - }) - ; -}; - -exports.jump = function () { - var to = setTimeout(function () { - assert.fail('builder never fired'); - }, 50); - - var xs = [ 4, 5, 6, -4, 8, 9, -1, 8 ]; - var xs_ = []; - - var ch = Chainsaw(function (saw) { - this.x = function (i) { - xs_.push(i); - saw.next(); - }; - - this.y = function (step) { - var x = xs.shift(); - if (x > 0) saw.jump(step); - else saw.next(); - }; - - saw.on('end', function () { - clearTimeout(to); - assert.eql(xs, [ 8 ]); - assert.eql(xs_, [ 1, 1, 1, 1, 2, 3, 2, 3, 2, 3 ]); - }); - }); - - ch - .x(1) - .y(0) - .x(2) - .x(3) - .y(2) - ; -}; diff --git a/node_modules/findit/node_modules/seq/node_modules/hashish/README.markdown b/node_modules/findit/node_modules/seq/node_modules/hashish/README.markdown deleted file mode 100644 index 1f39d59..0000000 --- a/node_modules/findit/node_modules/seq/node_modules/hashish/README.markdown +++ /dev/null @@ -1,191 +0,0 @@ -Hashish -======= - -Hashish is a node.js library for manipulating hash data structures. -It is distilled from the finest that ruby, perl, and haskell have to offer by -way of hash/map interfaces. - -Hashish provides a chaining interface, where you can do: - - var Hash = require('hashish'); - - Hash({ a : 1, b : 2, c : 3, d : 4 }) - .map(function (x) { return x * 10 }) - .filter(function (x) { return x < 30 }) - .forEach(function (x, key) { - console.log(key + ' => ' + x); - }) - ; - -Output: - - a => 10 - b => 20 - -Some functions and attributes in the chaining interface are terminal, like -`.items` or `.detect()`. They return values of their own instead of the chain -context. - -Each function in the chainable interface is also attached to `Hash` in chainless -form: - - var Hash = require('hashish'); - var obj = { a : 1, b : 2, c : 3, d : 4 }; - - var mapped = Hash.map(obj, function (x) { - return x * 10 - }); - - console.dir(mapped); - -Output: - - { a: 10, b: 20, c: 30, d: 40 } - -In either case, the 'this' context of the function calls is the same object that -the chained functions return, so you can make nested chains. - -Methods -======= - -forEach(cb) ------------ - -For each key/value in the hash, calls `cb(value, key)`. - -map(cb) -------- - -For each key/value in the hash, calls `cb(value, key)`. -The return value of `cb` is the new value at `key` in the resulting hash. - -filter(cb) ----------- - -For each key/value in the hash, calls `cb(value, key)`. -The resulting hash omits key/value pairs where `cb` returned a falsy value. - -detect(cb) ----------- - -Returns the first value in the hash for which `cb(value, key)` is non-falsy. -Order of hashes is not well-defined so watch out for that. - -reduce(cb) ----------- - -Returns the accumulated value of a left-fold over the key/value pairs. - -some(cb) --------- - -Returns a boolean: whether or not `cb(value, key)` ever returned a non-falsy -value. - -update(obj1, [obj2, obj3, ...]) ------------ - -Mutate the context hash, merging the key/value pairs from the passed objects -and overwriting keys from the context hash if the current `obj` has keys of -the same name. Falsy arguments are silently ignored. - -updateAll([ obj1, obj2, ... ]) ------------------------------- - -Like multi-argument `update()` but operate on an array directly. - -merge(obj1, [obj2, obj3, ...]) ----------- - -Merge the key/value pairs from the passed objects into the resultant hash -without modifying the context hash. Falsy arguments are silently ignored. - -mergeAll([ obj1, obj2, ... ]) ------------------------------- - -Like multi-argument `merge()` but operate on an array directly. - -has(key) --------- - -Return whether the hash has a key, `key`. - -valuesAt(keys) --------------- - -Return an Array with the values at the keys from `keys`. - -tap(cb) -------- - -Call `cb` with the present raw hash. -This function is chainable. - -extract(keys) -------------- - -Filter by including only those keys in `keys` in the resulting hash. - -exclude(keys) -------------- - -Filter by excluding those keys in `keys` in the resulting hash. - -Attributes -========== - -These are attributes in the chaining interface and functions in the `Hash.xxx` -interface. - -keys ----- - -Return all the enumerable attribute keys in the hash. - -values ------- - -Return all the enumerable attribute values in the hash. - -compact -------- - -Filter out values which are `=== undefined`. - -clone ------ - -Make a deep copy of the hash. - -copy ----- - -Make a shallow copy of the hash. - -length ------- - -Return the number of key/value pairs in the hash. -Note: use `Hash.size()` for non-chain mode. - -size ----- - -Alias for `length` since `Hash.length` is masked by `Function.prototype`. - -See Also -======== - -See also [creationix's pattern/hash](http://github.com/creationix/pattern), -which does a similar thing except with hash inputs and array outputs. - -Installation -============ - -To install with [npm](http://github.com/isaacs/npm): - - npm install hashish - -To run the tests with [expresso](http://github.com/visionmedia/expresso): - - expresso diff --git a/node_modules/findit/node_modules/seq/node_modules/hashish/examples/chain.js b/node_modules/findit/node_modules/seq/node_modules/hashish/examples/chain.js deleted file mode 100644 index 74ded5e..0000000 --- a/node_modules/findit/node_modules/seq/node_modules/hashish/examples/chain.js +++ /dev/null @@ -1,9 +0,0 @@ -var Hash = require('hashish'); - -Hash({ a : 1, b : 2, c : 3, d : 4 }) - .map(function (x) { return x * 10 }) - .filter(function (x) { return x < 30 }) - .forEach(function (x, key) { - console.log(key + ' => ' + x); - }) -; diff --git a/node_modules/findit/node_modules/seq/node_modules/hashish/examples/map.js b/node_modules/findit/node_modules/seq/node_modules/hashish/examples/map.js deleted file mode 100644 index 119d3d9..0000000 --- a/node_modules/findit/node_modules/seq/node_modules/hashish/examples/map.js +++ /dev/null @@ -1,7 +0,0 @@ -var Hash = require('hashish'); -var obj = { a : 1, b : 2, c : 3, d : 4 }; - -var mapped = Hash.map(obj, function (x) { - return x * 10 -}); -console.dir(mapped); diff --git a/node_modules/findit/node_modules/seq/node_modules/hashish/index.js b/node_modules/findit/node_modules/seq/node_modules/hashish/index.js deleted file mode 100644 index 1bc28e2..0000000 --- a/node_modules/findit/node_modules/seq/node_modules/hashish/index.js +++ /dev/null @@ -1,253 +0,0 @@ -module.exports = Hash; -var Traverse = require('traverse'); - -function Hash (hash, xs) { - if (Array.isArray(hash) && Array.isArray(xs)) { - var to = Math.min(hash.length, xs.length); - var acc = {}; - for (var i = 0; i < to; i++) { - acc[hash[i]] = xs[i]; - } - return Hash(acc); - } - - if (hash === undefined) return Hash({}); - - var self = { - map : function (f) { - var acc = { __proto__ : hash.__proto__ }; - Object.keys(hash).forEach(function (key) { - acc[key] = f.call(self, hash[key], key); - }); - return Hash(acc); - }, - forEach : function (f) { - Object.keys(hash).forEach(function (key) { - f.call(self, hash[key], key); - }); - return self; - }, - filter : function (f) { - var acc = { __proto__ : hash.__proto__ }; - Object.keys(hash).forEach(function (key) { - if (f.call(self, hash[key], key)) { - acc[key] = hash[key]; - } - }); - return Hash(acc); - }, - detect : function (f) { - for (var key in hash) { - if (f.call(self, hash[key], key)) { - return hash[key]; - } - } - return undefined; - }, - reduce : function (f, acc) { - var keys = Object.keys(hash); - if (acc === undefined) acc = keys.shift(); - keys.forEach(function (key) { - acc = f.call(self, acc, hash[key], key); - }); - return acc; - }, - some : function (f) { - for (var key in hash) { - if (f.call(self, hash[key], key)) return true; - } - return false; - }, - update : function (obj) { - if (arguments.length > 1) { - self.updateAll([].slice.call(arguments)); - } - else { - Object.keys(obj).forEach(function (key) { - hash[key] = obj[key]; - }); - } - return self; - }, - updateAll : function (xs) { - xs.filter(Boolean).forEach(function (x) { - self.update(x); - }); - return self; - }, - merge : function (obj) { - if (arguments.length > 1) { - return self.copy.updateAll([].slice.call(arguments)); - } - else { - return self.copy.update(obj); - } - }, - mergeAll : function (xs) { - return self.copy.updateAll(xs); - }, - has : function (key) { // only operates on enumerables - return Array.isArray(key) - ? key.every(function (k) { return self.has(k) }) - : self.keys.indexOf(key.toString()) >= 0; - }, - valuesAt : function (keys) { - return Array.isArray(keys) - ? keys.map(function (key) { return hash[key] }) - : hash[keys] - ; - }, - tap : function (f) { - f.call(self, hash); - return self; - }, - extract : function (keys) { - var acc = {}; - keys.forEach(function (key) { - acc[key] = hash[key]; - }); - return Hash(acc); - }, - exclude : function (keys) { - return self.filter(function (_, key) { - return keys.indexOf(key) < 0 - }); - }, - end : hash, - items : hash - }; - - var props = { - keys : function () { return Object.keys(hash) }, - values : function () { - return Object.keys(hash).map(function (key) { return hash[key] }); - }, - compact : function () { - return self.filter(function (x) { return x !== undefined }); - }, - clone : function () { return Hash(Hash.clone(hash)) }, - copy : function () { return Hash(Hash.copy(hash)) }, - length : function () { return Object.keys(hash).length }, - size : function () { return self.length } - }; - - if (Object.defineProperty) { - // es5-shim has an Object.defineProperty but it throws for getters - try { - for (var key in props) { - Object.defineProperty(self, key, { get : props[key] }); - } - } - catch (err) { - for (var key in props) { - if (key !== 'clone' && key !== 'copy' && key !== 'compact') { - // ^ those keys use Hash() so can't call them without - // a stack overflow - self[key] = props[key](); - } - } - } - } - else if (self.__defineGetter__) { - for (var key in props) { - self.__defineGetter__(key, props[key]); - } - } - else { - // non-lazy version for browsers that suck >_< - for (var key in props) { - self[key] = props[key](); - } - } - - return self; -}; - -// deep copy -Hash.clone = function (ref) { - return Traverse.clone(ref); -}; - -// shallow copy -Hash.copy = function (ref) { - var hash = { __proto__ : ref.__proto__ }; - Object.keys(ref).forEach(function (key) { - hash[key] = ref[key]; - }); - return hash; -}; - -Hash.map = function (ref, f) { - return Hash(ref).map(f).items; -}; - -Hash.forEach = function (ref, f) { - Hash(ref).forEach(f); -}; - -Hash.filter = function (ref, f) { - return Hash(ref).filter(f).items; -}; - -Hash.detect = function (ref, f) { - return Hash(ref).detect(f); -}; - -Hash.reduce = function (ref, f, acc) { - return Hash(ref).reduce(f, acc); -}; - -Hash.some = function (ref, f) { - return Hash(ref).some(f); -}; - -Hash.update = function (a /*, b, c, ... */) { - var args = Array.prototype.slice.call(arguments, 1); - var hash = Hash(a); - return hash.update.apply(hash, args).items; -}; - -Hash.merge = function (a /*, b, c, ... */) { - var args = Array.prototype.slice.call(arguments, 1); - var hash = Hash(a); - return hash.merge.apply(hash, args).items; -}; - -Hash.has = function (ref, key) { - return Hash(ref).has(key); -}; - -Hash.valuesAt = function (ref, keys) { - return Hash(ref).valuesAt(keys); -}; - -Hash.tap = function (ref, f) { - return Hash(ref).tap(f).items; -}; - -Hash.extract = function (ref, keys) { - return Hash(ref).extract(keys).items; -}; - -Hash.exclude = function (ref, keys) { - return Hash(ref).exclude(keys).items; -}; - -Hash.concat = function (xs) { - var hash = Hash({}); - xs.forEach(function (x) { hash.update(x) }); - return hash.items; -}; - -Hash.zip = function (xs, ys) { - return Hash(xs, ys).items; -}; - -// .length is already defined for function prototypes -Hash.size = function (ref) { - return Hash(ref).size; -}; - -Hash.compact = function (ref) { - return Hash(ref).compact.items; -}; diff --git a/node_modules/findit/node_modules/seq/node_modules/hashish/node_modules/traverse/.npmignore b/node_modules/findit/node_modules/seq/node_modules/hashish/node_modules/traverse/.npmignore deleted file mode 100644 index 3c3629e..0000000 --- a/node_modules/findit/node_modules/seq/node_modules/hashish/node_modules/traverse/.npmignore +++ /dev/null @@ -1 +0,0 @@ -node_modules diff --git a/node_modules/findit/node_modules/seq/node_modules/hashish/node_modules/traverse/LICENSE b/node_modules/findit/node_modules/seq/node_modules/hashish/node_modules/traverse/LICENSE deleted file mode 100644 index 7b75500..0000000 --- a/node_modules/findit/node_modules/seq/node_modules/hashish/node_modules/traverse/LICENSE +++ /dev/null @@ -1,24 +0,0 @@ -Copyright 2010 James Halliday (mail@substack.net) - -This project is free software released under the MIT/X11 license: -http://www.opensource.org/licenses/mit-license.php - -Copyright 2010 James Halliday (mail@substack.net) - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. diff --git a/node_modules/findit/node_modules/seq/node_modules/hashish/node_modules/traverse/README.markdown b/node_modules/findit/node_modules/seq/node_modules/hashish/node_modules/traverse/README.markdown deleted file mode 100644 index f86ef76..0000000 --- a/node_modules/findit/node_modules/seq/node_modules/hashish/node_modules/traverse/README.markdown +++ /dev/null @@ -1,237 +0,0 @@ -traverse -======== - -Traverse and transform objects by visiting every node on a recursive walk. - -examples -======== - -transform negative numbers in-place ------------------------------------ - -negative.js - -````javascript -var traverse = require('traverse'); -var obj = [ 5, 6, -3, [ 7, 8, -2, 1 ], { f : 10, g : -13 } ]; - -traverse(obj).forEach(function (x) { - if (x < 0) this.update(x + 128); -}); - -console.dir(obj); -```` - -Output: - - [ 5, 6, 125, [ 7, 8, 126, 1 ], { f: 10, g: 115 } ] - -collect leaf nodes ------------------- - -leaves.js - -````javascript -var traverse = require('traverse'); - -var obj = { - a : [1,2,3], - b : 4, - c : [5,6], - d : { e : [7,8], f : 9 }, -}; - -var leaves = traverse(obj).reduce(function (acc, x) { - if (this.isLeaf) acc.push(x); - return acc; -}, []); - -console.dir(leaves); -```` - -Output: - - [ 1, 2, 3, 4, 5, 6, 7, 8, 9 ] - -scrub circular references -------------------------- - -scrub.js: - -````javascript -var traverse = require('traverse'); - -var obj = { a : 1, b : 2, c : [ 3, 4 ] }; -obj.c.push(obj); - -var scrubbed = traverse(obj).map(function (x) { - if (this.circular) this.remove() -}); -console.dir(scrubbed); -```` - -output: - - { a: 1, b: 2, c: [ 3, 4 ] } - -context -======= - -Each method that takes a callback has a context (its `this` object) with these -attributes: - -this.node ---------- - -The present node on the recursive walk - -this.path ---------- - -An array of string keys from the root to the present node - -this.parent ------------ - -The context of the node's parent. -This is `undefined` for the root node. - -this.key --------- - -The name of the key of the present node in its parent. -This is `undefined` for the root node. - -this.isRoot, this.notRoot -------------------------- - -Whether the present node is the root node - -this.isLeaf, this.notLeaf -------------------------- - -Whether or not the present node is a leaf node (has no children) - -this.level ----------- - -Depth of the node within the traversal - -this.circular -------------- - -If the node equals one of its parents, the `circular` attribute is set to the -context of that parent and the traversal progresses no deeper. - -this.update(value, stopHere=false) ----------------------------------- - -Set a new value for the present node. - -All the elements in `value` will be recursively traversed unless `stopHere` is -true. - -this.remove(stopHere=false) -------------- - -Remove the current element from the output. If the node is in an Array it will -be spliced off. Otherwise it will be deleted from its parent. - -this.delete(stopHere=false) -------------- - -Delete the current element from its parent in the output. Calls `delete` even on -Arrays. - -this.before(fn) ---------------- - -Call this function before any of the children are traversed. - -You can assign into `this.keys` here to traverse in a custom order. - -this.after(fn) --------------- - -Call this function after any of the children are traversed. - -this.pre(fn) ------------- - -Call this function before each of the children are traversed. - -this.post(fn) -------------- - -Call this function after each of the children are traversed. - -methods -======= - -.map(fn) --------- - -Execute `fn` for each node in the object and return a new object with the -results of the walk. To update nodes in the result use `this.update(value)`. - -.forEach(fn) ------------- - -Execute `fn` for each node in the object but unlike `.map()`, when -`this.update()` is called it updates the object in-place. - -.reduce(fn, acc) ----------------- - -For each node in the object, perform a -[left-fold](http://en.wikipedia.org/wiki/Fold_(higher-order_function)) -with the return value of `fn(acc, node)`. - -If `acc` isn't specified, `acc` is set to the root object for the first step -and the root element is skipped. - -.paths() --------- - -Return an `Array` of every possible non-cyclic path in the object. -Paths are `Array`s of string keys. - -.nodes() --------- - -Return an `Array` of every node in the object. - -.clone() --------- - -Create a deep clone of the object. - -install -======= - -Using [npm](http://npmjs.org) do: - - $ npm install traverse - -test -==== - -Using [expresso](http://github.com/visionmedia/expresso) do: - - $ expresso - - 100% wahoo, your stuff is not broken! - -in the browser -============== - -Use [browserify](https://github.com/substack/node-browserify) to run traverse in -the browser. - -traverse has been tested and works with: - -* Internet Explorer 5.5, 6.0, 7.0, 8.0, 9.0 -* Firefox 3.5 -* Chrome 6.0 -* Opera 10.6 -* Safari 5.0 diff --git a/node_modules/findit/node_modules/seq/node_modules/hashish/node_modules/traverse/examples/json.js b/node_modules/findit/node_modules/seq/node_modules/hashish/node_modules/traverse/examples/json.js deleted file mode 100755 index 50d612e..0000000 --- a/node_modules/findit/node_modules/seq/node_modules/hashish/node_modules/traverse/examples/json.js +++ /dev/null @@ -1,16 +0,0 @@ -var traverse = require('traverse'); - -var id = 54; -var callbacks = {}; -var obj = { moo : function () {}, foo : [2,3,4, function () {}] }; - -var scrubbed = traverse(obj).map(function (x) { - if (typeof x === 'function') { - callbacks[id] = { id : id, f : x, path : this.path }; - this.update('[Function]'); - id++; - } -}); - -console.dir(scrubbed); -console.dir(callbacks); diff --git a/node_modules/findit/node_modules/seq/node_modules/hashish/node_modules/traverse/examples/leaves.js b/node_modules/findit/node_modules/seq/node_modules/hashish/node_modules/traverse/examples/leaves.js deleted file mode 100755 index c1b310b..0000000 --- a/node_modules/findit/node_modules/seq/node_modules/hashish/node_modules/traverse/examples/leaves.js +++ /dev/null @@ -1,15 +0,0 @@ -var traverse = require('traverse'); - -var obj = { - a : [1,2,3], - b : 4, - c : [5,6], - d : { e : [7,8], f : 9 }, -}; - -var leaves = traverse(obj).reduce(function (acc, x) { - if (this.isLeaf) acc.push(x); - return acc; -}, []); - -console.dir(leaves); diff --git a/node_modules/findit/node_modules/seq/node_modules/hashish/node_modules/traverse/examples/negative.js b/node_modules/findit/node_modules/seq/node_modules/hashish/node_modules/traverse/examples/negative.js deleted file mode 100755 index 78608a0..0000000 --- a/node_modules/findit/node_modules/seq/node_modules/hashish/node_modules/traverse/examples/negative.js +++ /dev/null @@ -1,8 +0,0 @@ -var traverse = require('traverse'); -var obj = [ 5, 6, -3, [ 7, 8, -2, 1 ], { f : 10, g : -13 } ]; - -traverse(obj).forEach(function (x) { - if (x < 0) this.update(x + 128); -}); - -console.dir(obj); diff --git a/node_modules/findit/node_modules/seq/node_modules/hashish/node_modules/traverse/examples/scrub.js b/node_modules/findit/node_modules/seq/node_modules/hashish/node_modules/traverse/examples/scrub.js deleted file mode 100755 index 5d15b91..0000000 --- a/node_modules/findit/node_modules/seq/node_modules/hashish/node_modules/traverse/examples/scrub.js +++ /dev/null @@ -1,10 +0,0 @@ -// scrub out circular references -var traverse = require('traverse'); - -var obj = { a : 1, b : 2, c : [ 3, 4 ] }; -obj.c.push(obj); - -var scrubbed = traverse(obj).map(function (x) { - if (this.circular) this.remove() -}); -console.dir(scrubbed); diff --git a/node_modules/findit/node_modules/seq/node_modules/hashish/node_modules/traverse/examples/stringify.js b/node_modules/findit/node_modules/seq/node_modules/hashish/node_modules/traverse/examples/stringify.js deleted file mode 100755 index 167b68b..0000000 --- a/node_modules/findit/node_modules/seq/node_modules/hashish/node_modules/traverse/examples/stringify.js +++ /dev/null @@ -1,38 +0,0 @@ -#!/usr/bin/env node -var traverse = require('traverse'); - -var obj = [ 'five', 6, -3, [ 7, 8, -2, 1 ], { f : 10, g : -13 } ]; - -var s = ''; -traverse(obj).forEach(function to_s (node) { - if (Array.isArray(node)) { - this.before(function () { s += '[' }); - this.post(function (child) { - if (!child.isLast) s += ','; - }); - this.after(function () { s += ']' }); - } - else if (typeof node == 'object') { - this.before(function () { s += '{' }); - this.pre(function (x, key) { - to_s(key); - s += ':'; - }); - this.post(function (child) { - if (!child.isLast) s += ','; - }); - this.after(function () { s += '}' }); - } - else if (typeof node == 'string') { - s += '"' + node.toString().replace(/"/g, '\\"') + '"'; - } - else if (typeof node == 'function') { - s += 'null'; - } - else { - s += node.toString(); - } -}); - -console.log('JSON.stringify: ' + JSON.stringify(obj)); -console.log('this stringify: ' + s); diff --git a/node_modules/findit/node_modules/seq/node_modules/hashish/node_modules/traverse/index.js b/node_modules/findit/node_modules/seq/node_modules/hashish/node_modules/traverse/index.js deleted file mode 100644 index 038a1ad..0000000 --- a/node_modules/findit/node_modules/seq/node_modules/hashish/node_modules/traverse/index.js +++ /dev/null @@ -1,267 +0,0 @@ -module.exports = Traverse; -function Traverse (obj) { - if (!(this instanceof Traverse)) return new Traverse(obj); - this.value = obj; -} - -Traverse.prototype.get = function (ps) { - var node = this.value; - for (var i = 0; i < ps.length; i ++) { - var key = ps[i]; - if (!Object.hasOwnProperty.call(node, key)) { - node = undefined; - break; - } - node = node[key]; - } - return node; -}; - -Traverse.prototype.set = function (ps, value) { - var node = this.value; - for (var i = 0; i < ps.length - 1; i ++) { - var key = ps[i]; - if (!Object.hasOwnProperty.call(node, key)) node[key] = {}; - node = node[key]; - } - node[ps[i]] = value; - return value; -}; - -Traverse.prototype.map = function (cb) { - return walk(this.value, cb, true); -}; - -Traverse.prototype.forEach = function (cb) { - this.value = walk(this.value, cb, false); - return this.value; -}; - -Traverse.prototype.reduce = function (cb, init) { - var skip = arguments.length === 1; - var acc = skip ? this.value : init; - this.forEach(function (x) { - if (!this.isRoot || !skip) { - acc = cb.call(this, acc, x); - } - }); - return acc; -}; - -Traverse.prototype.paths = function () { - var acc = []; - this.forEach(function (x) { - acc.push(this.path); - }); - return acc; -}; - -Traverse.prototype.nodes = function () { - var acc = []; - this.forEach(function (x) { - acc.push(this.node); - }); - return acc; -}; - -Traverse.prototype.clone = function () { - var parents = [], nodes = []; - - return (function clone (src) { - for (var i = 0; i < parents.length; i++) { - if (parents[i] === src) { - return nodes[i]; - } - } - - if (typeof src === 'object' && src !== null) { - var dst = copy(src); - - parents.push(src); - nodes.push(dst); - - forEach(Object_keys(src), function (key) { - dst[key] = clone(src[key]); - }); - - parents.pop(); - nodes.pop(); - return dst; - } - else { - return src; - } - })(this.value); -}; - -function walk (root, cb, immutable) { - var path = []; - var parents = []; - var alive = true; - - return (function walker (node_) { - var node = immutable ? copy(node_) : node_; - var modifiers = {}; - - var keepGoing = true; - - var state = { - node : node, - node_ : node_, - path : [].concat(path), - parent : parents[parents.length - 1], - parents : parents, - key : path.slice(-1)[0], - isRoot : path.length === 0, - level : path.length, - circular : null, - update : function (x, stopHere) { - if (!state.isRoot) { - state.parent.node[state.key] = x; - } - state.node = x; - if (stopHere) keepGoing = false; - }, - 'delete' : function (stopHere) { - delete state.parent.node[state.key]; - if (stopHere) keepGoing = false; - }, - remove : function (stopHere) { - if (Array_isArray(state.parent.node)) { - state.parent.node.splice(state.key, 1); - } - else { - delete state.parent.node[state.key]; - } - if (stopHere) keepGoing = false; - }, - keys : null, - before : function (f) { modifiers.before = f }, - after : function (f) { modifiers.after = f }, - pre : function (f) { modifiers.pre = f }, - post : function (f) { modifiers.post = f }, - stop : function () { alive = false }, - block : function () { keepGoing = false } - }; - - if (!alive) return state; - - if (typeof node === 'object' && node !== null) { - state.keys = Object_keys(node); - - state.isLeaf = state.keys.length == 0; - - for (var i = 0; i < parents.length; i++) { - if (parents[i].node_ === node_) { - state.circular = parents[i]; - break; - } - } - } - else { - state.isLeaf = true; - } - - state.notLeaf = !state.isLeaf; - state.notRoot = !state.isRoot; - - // use return values to update if defined - var ret = cb.call(state, state.node); - if (ret !== undefined && state.update) state.update(ret); - - if (modifiers.before) modifiers.before.call(state, state.node); - - if (!keepGoing) return state; - - if (typeof state.node == 'object' - && state.node !== null && !state.circular) { - parents.push(state); - - forEach(state.keys, function (key, i) { - path.push(key); - - if (modifiers.pre) modifiers.pre.call(state, state.node[key], key); - - var child = walker(state.node[key]); - if (immutable && Object.hasOwnProperty.call(state.node, key)) { - state.node[key] = child.node; - } - - child.isLast = i == state.keys.length - 1; - child.isFirst = i == 0; - - if (modifiers.post) modifiers.post.call(state, child); - - path.pop(); - }); - parents.pop(); - } - - if (modifiers.after) modifiers.after.call(state, state.node); - - return state; - })(root).node; -} - -function copy (src) { - if (typeof src === 'object' && src !== null) { - var dst; - - if (Array_isArray(src)) { - dst = []; - } - else if (src instanceof Date) { - dst = new Date(src); - } - else if (src instanceof Boolean) { - dst = new Boolean(src); - } - else if (src instanceof Number) { - dst = new Number(src); - } - else if (src instanceof String) { - dst = new String(src); - } - else if (Object.create && Object.getPrototypeOf) { - dst = Object.create(Object.getPrototypeOf(src)); - } - else if (src.__proto__ || src.constructor.prototype) { - var proto = src.__proto__ || src.constructor.prototype || {}; - var T = function () {}; - T.prototype = proto; - dst = new T; - if (!dst.__proto__) dst.__proto__ = proto; - } - - forEach(Object_keys(src), function (key) { - dst[key] = src[key]; - }); - return dst; - } - else return src; -} - -var Object_keys = Object.keys || function keys (obj) { - var res = []; - for (var key in obj) res.push(key) - return res; -}; - -var Array_isArray = Array.isArray || function isArray (xs) { - return Object.prototype.toString.call(xs) === '[object Array]'; -}; - -var forEach = function (xs, fn) { - if (xs.forEach) return xs.forEach(fn) - else for (var i = 0; i < xs.length; i++) { - fn(xs[i], i, xs); - } -}; - -forEach(Object_keys(Traverse.prototype), function (key) { - Traverse[key] = function (obj) { - var args = [].slice.call(arguments, 1); - var t = Traverse(obj); - return t[key].apply(t, args); - }; -}); diff --git a/node_modules/findit/node_modules/seq/node_modules/hashish/node_modules/traverse/main.js b/node_modules/findit/node_modules/seq/node_modules/hashish/node_modules/traverse/main.js deleted file mode 100755 index d562d37..0000000 --- a/node_modules/findit/node_modules/seq/node_modules/hashish/node_modules/traverse/main.js +++ /dev/null @@ -1,10 +0,0 @@ -// scrub out circular references -var traverse = require('./index.js'); - -var obj = { a : 1, b : 2, c : [ 3, 4 ] }; -obj.c.push(obj); - -var scrubbed = traverse(obj).map(function (x) { - if (this.circular) this.remove() -}); -console.dir(scrubbed); diff --git a/node_modules/findit/node_modules/seq/node_modules/hashish/node_modules/traverse/package.json b/node_modules/findit/node_modules/seq/node_modules/hashish/node_modules/traverse/package.json deleted file mode 100644 index f86322a..0000000 --- a/node_modules/findit/node_modules/seq/node_modules/hashish/node_modules/traverse/package.json +++ /dev/null @@ -1,18 +0,0 @@ -{ - "name" : "traverse", - "version" : "0.5.2", - "description" : "Traverse and transform objects by visiting every node on a recursive walk", - "author" : "James Halliday", - "license" : "MIT/X11", - "main" : "./index", - "repository" : { - "type" : "git", - "url" : "http://github.com/substack/js-traverse.git" - }, - "devDependencies" : { - "expresso" : "0.7.x" - }, - "scripts" : { - "test" : "expresso" - } -} diff --git a/node_modules/findit/node_modules/seq/node_modules/hashish/node_modules/traverse/test/circular.js b/node_modules/findit/node_modules/seq/node_modules/hashish/node_modules/traverse/test/circular.js deleted file mode 100644 index 9162601..0000000 --- a/node_modules/findit/node_modules/seq/node_modules/hashish/node_modules/traverse/test/circular.js +++ /dev/null @@ -1,115 +0,0 @@ -var assert = require('assert'); -var Traverse = require('../'); -var deepEqual = require('./lib/deep_equal'); -var util = require('util'); - -exports.circular = function () { - var obj = { x : 3 }; - obj.y = obj; - var foundY = false; - Traverse(obj).forEach(function (x) { - if (this.path.join('') == 'y') { - assert.equal( - util.inspect(this.circular.node), - util.inspect(obj) - ); - foundY = true; - } - }); - assert.ok(foundY); -}; - -exports.deepCirc = function () { - var obj = { x : [ 1, 2, 3 ], y : [ 4, 5 ] }; - obj.y[2] = obj; - - var times = 0; - Traverse(obj).forEach(function (x) { - if (this.circular) { - assert.deepEqual(this.circular.path, []); - assert.deepEqual(this.path, [ 'y', 2 ]); - times ++; - } - }); - - assert.deepEqual(times, 1); -}; - -exports.doubleCirc = function () { - var obj = { x : [ 1, 2, 3 ], y : [ 4, 5 ] }; - obj.y[2] = obj; - obj.x.push(obj.y); - - var circs = []; - Traverse(obj).forEach(function (x) { - if (this.circular) { - circs.push({ circ : this.circular, self : this, node : x }); - } - }); - - assert.deepEqual(circs[0].self.path, [ 'x', 3, 2 ]); - assert.deepEqual(circs[0].circ.path, []); - - assert.deepEqual(circs[1].self.path, [ 'y', 2 ]); - assert.deepEqual(circs[1].circ.path, []); - - assert.deepEqual(circs.length, 2); -}; - -exports.circDubForEach = function () { - var obj = { x : [ 1, 2, 3 ], y : [ 4, 5 ] }; - obj.y[2] = obj; - obj.x.push(obj.y); - - Traverse(obj).forEach(function (x) { - if (this.circular) this.update('...'); - }); - - assert.deepEqual(obj, { x : [ 1, 2, 3, [ 4, 5, '...' ] ], y : [ 4, 5, '...' ] }); -}; - -exports.circDubMap = function () { - var obj = { x : [ 1, 2, 3 ], y : [ 4, 5 ] }; - obj.y[2] = obj; - obj.x.push(obj.y); - - var c = Traverse(obj).map(function (x) { - if (this.circular) { - this.update('...'); - } - }); - - assert.deepEqual(c, { x : [ 1, 2, 3, [ 4, 5, '...' ] ], y : [ 4, 5, '...' ] }); -}; - -exports.circClone = function () { - var obj = { x : [ 1, 2, 3 ], y : [ 4, 5 ] }; - obj.y[2] = obj; - obj.x.push(obj.y); - - var clone = Traverse.clone(obj); - assert.ok(obj !== clone); - - assert.ok(clone.y[2] === clone); - assert.ok(clone.y[2] !== obj); - assert.ok(clone.x[3][2] === clone); - assert.ok(clone.x[3][2] !== obj); - assert.deepEqual(clone.x.slice(0,3), [1,2,3]); - assert.deepEqual(clone.y.slice(0,2), [4,5]); -}; - -exports.circMapScrub = function () { - var obj = { a : 1, b : 2 }; - obj.c = obj; - - var scrubbed = Traverse(obj).map(function (node) { - if (this.circular) this.remove(); - }); - assert.deepEqual( - Object.keys(scrubbed).sort(), - [ 'a', 'b' ] - ); - assert.ok(deepEqual(scrubbed, { a : 1, b : 2 })); - - assert.equal(obj.c, obj); -}; diff --git a/node_modules/findit/node_modules/seq/node_modules/hashish/node_modules/traverse/test/date.js b/node_modules/findit/node_modules/seq/node_modules/hashish/node_modules/traverse/test/date.js deleted file mode 100644 index 4ca06dc..0000000 --- a/node_modules/findit/node_modules/seq/node_modules/hashish/node_modules/traverse/test/date.js +++ /dev/null @@ -1,35 +0,0 @@ -var assert = require('assert'); -var Traverse = require('../'); - -exports.dateEach = function () { - var obj = { x : new Date, y : 10, z : 5 }; - - var counts = {}; - - Traverse(obj).forEach(function (node) { - var t = (node instanceof Date && 'Date') || typeof node; - counts[t] = (counts[t] || 0) + 1; - }); - - assert.deepEqual(counts, { - object : 1, - Date : 1, - number : 2, - }); -}; - -exports.dateMap = function () { - var obj = { x : new Date, y : 10, z : 5 }; - - var res = Traverse(obj).map(function (node) { - if (typeof node === 'number') this.update(node + 100); - }); - - assert.ok(obj.x !== res.x); - assert.deepEqual(res, { - x : obj.x, - y : 110, - z : 105, - }); -}; - diff --git a/node_modules/findit/node_modules/seq/node_modules/hashish/node_modules/traverse/test/equal.js b/node_modules/findit/node_modules/seq/node_modules/hashish/node_modules/traverse/test/equal.js deleted file mode 100644 index decc755..0000000 --- a/node_modules/findit/node_modules/seq/node_modules/hashish/node_modules/traverse/test/equal.js +++ /dev/null @@ -1,220 +0,0 @@ -var assert = require('assert'); -var traverse = require('../'); -var deepEqual = require('./lib/deep_equal'); - -exports.deepDates = function () { - assert.ok( - deepEqual( - { d : new Date, x : [ 1, 2, 3 ] }, - { d : new Date, x : [ 1, 2, 3 ] } - ), - 'dates should be equal' - ); - - var d0 = new Date; - setTimeout(function () { - assert.ok( - !deepEqual( - { d : d0, x : [ 1, 2, 3 ], }, - { d : new Date, x : [ 1, 2, 3 ] } - ), - 'microseconds should count in date equality' - ); - }, 5); -}; - -exports.deepCircular = function () { - var a = [1]; - a.push(a); // a = [ 1, *a ] - - var b = [1]; - b.push(a); // b = [ 1, [ 1, *a ] ] - - assert.ok( - !deepEqual(a, b), - 'circular ref mount points count towards equality' - ); - - var c = [1]; - c.push(c); // c = [ 1, *c ] - assert.ok( - deepEqual(a, c), - 'circular refs are structurally the same here' - ); - - var d = [1]; - d.push(a); // c = [ 1, [ 1, *d ] ] - assert.ok( - deepEqual(b, d), - 'non-root circular ref structural comparison' - ); -}; - -exports.deepInstances = function () { - assert.ok( - !deepEqual([ new Boolean(false) ], [ false ]), - 'boolean instances are not real booleans' - ); - - assert.ok( - !deepEqual([ new String('x') ], [ 'x' ]), - 'string instances are not real strings' - ); - - assert.ok( - !deepEqual([ new Number(4) ], [ 4 ]), - 'number instances are not real numbers' - ); - - assert.ok( - deepEqual([ new RegExp('x') ], [ /x/ ]), - 'regexp instances are real regexps' - ); - - assert.ok( - !deepEqual([ new RegExp(/./) ], [ /../ ]), - 'these regexps aren\'t the same' - ); - - assert.ok( - !deepEqual( - [ function (x) { return x * 2 } ], - [ function (x) { return x * 2 } ] - ), - 'functions with the same .toString() aren\'t necessarily the same' - ); - - var f = function (x) { return x * 2 }; - assert.ok( - deepEqual([ f ], [ f ]), - 'these functions are actually equal' - ); -}; - -exports.deepEqual = function () { - assert.ok( - !deepEqual([ 1, 2, 3 ], { 0 : 1, 1 : 2, 2 : 3 }), - 'arrays are not objects' - ); -}; - -exports.falsy = function () { - assert.ok( - !deepEqual([ undefined ], [ null ]), - 'null is not undefined!' - ); - - assert.ok( - !deepEqual([ null ], [ undefined ]), - 'undefined is not null!' - ); - - assert.ok( - !deepEqual( - { a : 1, b : 2, c : [ 3, undefined, 5 ] }, - { a : 1, b : 2, c : [ 3, null, 5 ] } - ), - 'undefined is not null, however deeply!' - ); - - assert.ok( - !deepEqual( - { a : 1, b : 2, c : [ 3, undefined, 5 ] }, - { a : 1, b : 2, c : [ 3, null, 5 ] } - ), - 'null is not undefined, however deeply!' - ); - - assert.ok( - !deepEqual( - { a : 1, b : 2, c : [ 3, undefined, 5 ] }, - { a : 1, b : 2, c : [ 3, null, 5 ] } - ), - 'null is not undefined, however deeply!' - ); -}; - -exports.deletedArrayEqual = function () { - var xs = [ 1, 2, 3, 4 ]; - delete xs[2]; - - var ys = Object.create(Array.prototype); - ys[0] = 1; - ys[1] = 2; - ys[3] = 4; - - assert.ok( - deepEqual(xs, ys), - 'arrays with deleted elements are only equal to' - + ' arrays with similarly deleted elements' - ); - - assert.ok( - !deepEqual(xs, [ 1, 2, undefined, 4 ]), - 'deleted array elements cannot be undefined' - ); - - assert.ok( - !deepEqual(xs, [ 1, 2, null, 4 ]), - 'deleted array elements cannot be null' - ); -}; - -exports.deletedObjectEqual = function () { - var obj = { a : 1, b : 2, c : 3 }; - delete obj.c; - - assert.ok( - deepEqual(obj, { a : 1, b : 2 }), - 'deleted object elements should not show up' - ); - - assert.ok( - !deepEqual(obj, { a : 1, b : 2, c : undefined }), - 'deleted object elements are not undefined' - ); - - assert.ok( - !deepEqual(obj, { a : 1, b : 2, c : null }), - 'deleted object elements are not null' - ); -}; - -exports.emptyKeyEqual = function () { - assert.ok(!deepEqual( - { a : 1 }, { a : 1, '' : 55 } - )); -}; - -exports.deepArguments = function () { - assert.ok( - !deepEqual( - [ 4, 5, 6 ], - (function () { return arguments })(4, 5, 6) - ), - 'arguments are not arrays' - ); - - assert.ok( - deepEqual( - (function () { return arguments })(4, 5, 6), - (function () { return arguments })(4, 5, 6) - ), - 'arguments should equal' - ); -}; - -exports.deepUn = function () { - assert.ok(!deepEqual({ a : 1, b : 2 }, undefined)); - assert.ok(!deepEqual({ a : 1, b : 2 }, {})); - assert.ok(!deepEqual(undefined, { a : 1, b : 2 })); - assert.ok(!deepEqual({}, { a : 1, b : 2 })); - assert.ok(deepEqual(undefined, undefined)); - assert.ok(deepEqual(null, null)); - assert.ok(!deepEqual(undefined, null)); -}; - -exports.deepLevels = function () { - var xs = [ 1, 2, [ 3, 4, [ 5, 6 ] ] ]; - assert.ok(!deepEqual(xs, [])); -}; diff --git a/node_modules/findit/node_modules/seq/node_modules/hashish/node_modules/traverse/test/instance.js b/node_modules/findit/node_modules/seq/node_modules/hashish/node_modules/traverse/test/instance.js deleted file mode 100644 index 8d73525..0000000 --- a/node_modules/findit/node_modules/seq/node_modules/hashish/node_modules/traverse/test/instance.js +++ /dev/null @@ -1,17 +0,0 @@ -var assert = require('assert'); -var Traverse = require('../'); -var EventEmitter = require('events').EventEmitter; - -exports['check instanceof on node elems'] = function () { - - var counts = { emitter : 0 }; - - Traverse([ new EventEmitter, 3, 4, { ev : new EventEmitter }]) - .forEach(function (node) { - if (node instanceof EventEmitter) counts.emitter ++; - }) - ; - - assert.equal(counts.emitter, 2); -}; - diff --git a/node_modules/findit/node_modules/seq/node_modules/hashish/node_modules/traverse/test/interface.js b/node_modules/findit/node_modules/seq/node_modules/hashish/node_modules/traverse/test/interface.js deleted file mode 100644 index fce5bf9..0000000 --- a/node_modules/findit/node_modules/seq/node_modules/hashish/node_modules/traverse/test/interface.js +++ /dev/null @@ -1,42 +0,0 @@ -var assert = require('assert'); -var Traverse = require('../'); - -exports['interface map'] = function () { - var obj = { a : [ 5,6,7 ], b : { c : [8] } }; - - assert.deepEqual( - Traverse.paths(obj) - .sort() - .map(function (path) { return path.join('/') }) - .slice(1) - .join(' ') - , - 'a a/0 a/1 a/2 b b/c b/c/0' - ); - - assert.deepEqual( - Traverse.nodes(obj), - [ - { a: [ 5, 6, 7 ], b: { c: [ 8 ] } }, - [ 5, 6, 7 ], 5, 6, 7, - { c: [ 8 ] }, [ 8 ], 8 - ] - ); - - assert.deepEqual( - Traverse.map(obj, function (node) { - if (typeof node == 'number') { - return node + 1000; - } - else if (Array.isArray(node)) { - return node.join(' '); - } - }), - { a: '5 6 7', b: { c: '8' } } - ); - - var nodes = 0; - Traverse.forEach(obj, function (node) { nodes ++ }); - assert.deepEqual(nodes, 8); -}; - diff --git a/node_modules/findit/node_modules/seq/node_modules/hashish/node_modules/traverse/test/json.js b/node_modules/findit/node_modules/seq/node_modules/hashish/node_modules/traverse/test/json.js deleted file mode 100644 index 0a04529..0000000 --- a/node_modules/findit/node_modules/seq/node_modules/hashish/node_modules/traverse/test/json.js +++ /dev/null @@ -1,47 +0,0 @@ -var assert = require('assert'); -var Traverse = require('../'); - -exports['json test'] = function () { - var id = 54; - var callbacks = {}; - var obj = { moo : function () {}, foo : [2,3,4, function () {}] }; - - var scrubbed = Traverse(obj).map(function (x) { - if (typeof x === 'function') { - callbacks[id] = { id : id, f : x, path : this.path }; - this.update('[Function]'); - id++; - } - }); - - assert.equal( - scrubbed.moo, '[Function]', - 'obj.moo replaced with "[Function]"' - ); - - assert.equal( - scrubbed.foo[3], '[Function]', - 'obj.foo[3] replaced with "[Function]"' - ); - - assert.deepEqual(scrubbed, { - moo : '[Function]', - foo : [ 2, 3, 4, "[Function]" ] - }, 'Full JSON string matches'); - - assert.deepEqual( - typeof obj.moo, 'function', - 'Original obj.moo still a function' - ); - - assert.deepEqual( - typeof obj.foo[3], 'function', - 'Original obj.foo[3] still a function' - ); - - assert.deepEqual(callbacks, { - 54: { id: 54, f : obj.moo, path: [ 'moo' ] }, - 55: { id: 55, f : obj.foo[3], path: [ 'foo', '3' ] }, - }, 'Check the generated callbacks list'); -}; - diff --git a/node_modules/findit/node_modules/seq/node_modules/hashish/node_modules/traverse/test/keys.js b/node_modules/findit/node_modules/seq/node_modules/hashish/node_modules/traverse/test/keys.js deleted file mode 100644 index 7ecd545..0000000 --- a/node_modules/findit/node_modules/seq/node_modules/hashish/node_modules/traverse/test/keys.js +++ /dev/null @@ -1,29 +0,0 @@ -var assert = require('assert'); -var Traverse = require('../'); - -exports['sort test'] = function () { - var acc = []; - Traverse({ - a: 30, - b: 22, - id: 9 - }).forEach(function (node) { - if ((! Array.isArray(node)) && typeof node === 'object') { - this.before(function(node) { - this.keys = Object.keys(node); - this.keys.sort(function(a, b) { - a = [a === "id" ? 0 : 1, a]; - b = [b === "id" ? 0 : 1, b]; - return a < b ? -1 : a > b ? 1 : 0; - }); - }); - } - if (this.isLeaf) acc.push(node); - }); - - assert.equal( - acc.join(' '), - '9 30 22', - 'Traversal in a custom order' - ); -}; diff --git a/node_modules/findit/node_modules/seq/node_modules/hashish/node_modules/traverse/test/leaves.js b/node_modules/findit/node_modules/seq/node_modules/hashish/node_modules/traverse/test/leaves.js deleted file mode 100644 index e520b72..0000000 --- a/node_modules/findit/node_modules/seq/node_modules/hashish/node_modules/traverse/test/leaves.js +++ /dev/null @@ -1,21 +0,0 @@ -var assert = require('assert'); -var Traverse = require('../'); - -exports['leaves test'] = function () { - var acc = []; - Traverse({ - a : [1,2,3], - b : 4, - c : [5,6], - d : { e : [7,8], f : 9 } - }).forEach(function (x) { - if (this.isLeaf) acc.push(x); - }); - - assert.equal( - acc.join(' '), - '1 2 3 4 5 6 7 8 9', - 'Traversal in the right(?) order' - ); -}; - diff --git a/node_modules/findit/node_modules/seq/node_modules/hashish/node_modules/traverse/test/lib/deep_equal.js b/node_modules/findit/node_modules/seq/node_modules/hashish/node_modules/traverse/test/lib/deep_equal.js deleted file mode 100644 index 4fa07bb..0000000 --- a/node_modules/findit/node_modules/seq/node_modules/hashish/node_modules/traverse/test/lib/deep_equal.js +++ /dev/null @@ -1,92 +0,0 @@ -var traverse = require('../../'); - -module.exports = function (a, b) { - if (arguments.length !== 2) { - throw new Error( - 'deepEqual requires exactly two objects to compare against' - ); - } - - var equal = true; - var node = b; - - traverse(a).forEach(function (y) { - var notEqual = (function () { - equal = false; - //this.stop(); - return undefined; - }).bind(this); - - //if (node === undefined || node === null) return notEqual(); - - if (!this.isRoot) { - /* - if (!Object.hasOwnProperty.call(node, this.key)) { - return notEqual(); - } - */ - if (typeof node !== 'object') return notEqual(); - node = node[this.key]; - } - - var x = node; - - this.post(function () { - node = x; - }); - - var toS = function (o) { - return Object.prototype.toString.call(o); - }; - - if (this.circular) { - if (traverse(b).get(this.circular.path) !== x) notEqual(); - } - else if (typeof x !== typeof y) { - notEqual(); - } - else if (x === null || y === null || x === undefined || y === undefined) { - if (x !== y) notEqual(); - } - else if (x.__proto__ !== y.__proto__) { - notEqual(); - } - else if (x === y) { - // nop - } - else if (typeof x === 'function') { - if (x instanceof RegExp) { - // both regexps on account of the __proto__ check - if (x.toString() != y.toString()) notEqual(); - } - else if (x !== y) notEqual(); - } - else if (typeof x === 'object') { - if (toS(y) === '[object Arguments]' - || toS(x) === '[object Arguments]') { - if (toS(x) !== toS(y)) { - notEqual(); - } - } - else if (x instanceof Date || y instanceof Date) { - if (!(x instanceof Date) || !(y instanceof Date) - || x.getTime() !== y.getTime()) { - notEqual(); - } - } - else { - var kx = Object.keys(x); - var ky = Object.keys(y); - if (kx.length !== ky.length) return notEqual(); - for (var i = 0; i < kx.length; i++) { - var k = kx[i]; - if (!Object.hasOwnProperty.call(y, k)) { - notEqual(); - } - } - } - } - }); - - return equal; -}; diff --git a/node_modules/findit/node_modules/seq/node_modules/hashish/node_modules/traverse/test/mutability.js b/node_modules/findit/node_modules/seq/node_modules/hashish/node_modules/traverse/test/mutability.js deleted file mode 100644 index 2236f56..0000000 --- a/node_modules/findit/node_modules/seq/node_modules/hashish/node_modules/traverse/test/mutability.js +++ /dev/null @@ -1,252 +0,0 @@ -var assert = require('assert'); -var Traverse = require('../'); -var deepEqual = require('./lib/deep_equal'); - -exports.mutate = function () { - var obj = { a : 1, b : 2, c : [ 3, 4 ] }; - var res = Traverse(obj).forEach(function (x) { - if (typeof x === 'number' && x % 2 === 0) { - this.update(x * 10); - } - }); - assert.deepEqual(obj, res); - assert.deepEqual(obj, { a : 1, b : 20, c : [ 3, 40 ] }); -}; - -exports.mutateT = function () { - var obj = { a : 1, b : 2, c : [ 3, 4 ] }; - var res = Traverse.forEach(obj, function (x) { - if (typeof x === 'number' && x % 2 === 0) { - this.update(x * 10); - } - }); - assert.deepEqual(obj, res); - assert.deepEqual(obj, { a : 1, b : 20, c : [ 3, 40 ] }); -}; - -exports.map = function () { - var obj = { a : 1, b : 2, c : [ 3, 4 ] }; - var res = Traverse(obj).map(function (x) { - if (typeof x === 'number' && x % 2 === 0) { - this.update(x * 10); - } - }); - assert.deepEqual(obj, { a : 1, b : 2, c : [ 3, 4 ] }); - assert.deepEqual(res, { a : 1, b : 20, c : [ 3, 40 ] }); -}; - -exports.mapT = function () { - var obj = { a : 1, b : 2, c : [ 3, 4 ] }; - var res = Traverse.map(obj, function (x) { - if (typeof x === 'number' && x % 2 === 0) { - this.update(x * 10); - } - }); - assert.deepEqual(obj, { a : 1, b : 2, c : [ 3, 4 ] }); - assert.deepEqual(res, { a : 1, b : 20, c : [ 3, 40 ] }); -}; - -exports.clone = function () { - var obj = { a : 1, b : 2, c : [ 3, 4 ] }; - var res = Traverse(obj).clone(); - assert.deepEqual(obj, res); - assert.ok(obj !== res); - obj.a ++; - assert.deepEqual(res.a, 1); - obj.c.push(5); - assert.deepEqual(res.c, [ 3, 4 ]); -}; - -exports.cloneT = function () { - var obj = { a : 1, b : 2, c : [ 3, 4 ] }; - var res = Traverse.clone(obj); - assert.deepEqual(obj, res); - assert.ok(obj !== res); - obj.a ++; - assert.deepEqual(res.a, 1); - obj.c.push(5); - assert.deepEqual(res.c, [ 3, 4 ]); -}; - -exports.reduce = function () { - var obj = { a : 1, b : 2, c : [ 3, 4 ] }; - var res = Traverse(obj).reduce(function (acc, x) { - if (this.isLeaf) acc.push(x); - return acc; - }, []); - assert.deepEqual(obj, { a : 1, b : 2, c : [ 3, 4 ] }); - assert.deepEqual(res, [ 1, 2, 3, 4 ]); -}; - -exports.reduceInit = function () { - var obj = { a : 1, b : 2, c : [ 3, 4 ] }; - var res = Traverse(obj).reduce(function (acc, x) { - if (this.isRoot) assert.fail('got root'); - return acc; - }); - assert.deepEqual(obj, { a : 1, b : 2, c : [ 3, 4 ] }); - assert.deepEqual(res, obj); -}; - -exports.remove = function () { - var obj = { a : 1, b : 2, c : [ 3, 4 ] }; - Traverse(obj).forEach(function (x) { - if (this.isLeaf && x % 2 == 0) this.remove(); - }); - - assert.deepEqual(obj, { a : 1, c : [ 3 ] }); -}; - -exports.removeNoStop = function() { - var obj = { a : 1, b : 2, c : { d: 3, e: 4 }, f: 5 }; - - var keys = []; - Traverse(obj).forEach(function (x) { - keys.push(this.key) - if (this.key == 'c') this.remove(); - }); - - assert.deepEqual(keys, [undefined, 'a', 'b', 'c', 'd', 'e', 'f']) -} - -exports.removeStop = function() { - var obj = { a : 1, b : 2, c : { d: 3, e: 4 }, f: 5 }; - - var keys = []; - Traverse(obj).forEach(function (x) { - keys.push(this.key) - if (this.key == 'c') this.remove(true); - }); - - assert.deepEqual(keys, [undefined, 'a', 'b', 'c', 'f']) -} - -exports.removeMap = function () { - var obj = { a : 1, b : 2, c : [ 3, 4 ] }; - var res = Traverse(obj).map(function (x) { - if (this.isLeaf && x % 2 == 0) this.remove(); - }); - - assert.deepEqual(obj, { a : 1, b : 2, c : [ 3, 4 ] }); - assert.deepEqual(res, { a : 1, c : [ 3 ] }); -}; - -exports.delete = function () { - var obj = { a : 1, b : 2, c : [ 3, 4 ] }; - Traverse(obj).forEach(function (x) { - if (this.isLeaf && x % 2 == 0) this.delete(); - }); - - assert.ok(!deepEqual( - obj, { a : 1, c : [ 3, undefined ] } - )); - - assert.ok(deepEqual( - obj, { a : 1, c : [ 3 ] } - )); - - assert.ok(!deepEqual( - obj, { a : 1, c : [ 3, null ] } - )); -}; - -exports.deleteNoStop = function() { - var obj = { a : 1, b : 2, c : { d: 3, e: 4 } }; - - var keys = []; - Traverse(obj).forEach(function (x) { - keys.push(this.key) - if (this.key == 'c') this.delete(); - }); - - assert.deepEqual(keys, [undefined, 'a', 'b', 'c', 'd', 'e']) -} - -exports.deleteStop = function() { - var obj = { a : 1, b : 2, c : { d: 3, e: 4 } }; - - var keys = []; - Traverse(obj).forEach(function (x) { - keys.push(this.key) - if (this.key == 'c') this.delete(true); - }); - - assert.deepEqual(keys, [undefined, 'a', 'b', 'c']) -} - -exports.deleteRedux = function () { - var obj = { a : 1, b : 2, c : [ 3, 4, 5 ] }; - Traverse(obj).forEach(function (x) { - if (this.isLeaf && x % 2 == 0) this.delete(); - }); - - assert.ok(!deepEqual( - obj, { a : 1, c : [ 3, undefined, 5 ] } - )); - - assert.ok(deepEqual( - obj, { a : 1, c : [ 3 ,, 5 ] } - )); - - assert.ok(!deepEqual( - obj, { a : 1, c : [ 3, null, 5 ] } - )); - - assert.ok(!deepEqual( - obj, { a : 1, c : [ 3, 5 ] } - )); -}; - -exports.deleteMap = function () { - var obj = { a : 1, b : 2, c : [ 3, 4 ] }; - var res = Traverse(obj).map(function (x) { - if (this.isLeaf && x % 2 == 0) this.delete(); - }); - - assert.ok(deepEqual( - obj, - { a : 1, b : 2, c : [ 3, 4 ] } - )); - - var xs = [ 3, 4 ]; - delete xs[1]; - - assert.ok(deepEqual( - res, { a : 1, c : xs } - )); - - assert.ok(deepEqual( - res, { a : 1, c : [ 3, ] } - )); - - assert.ok(deepEqual( - res, { a : 1, c : [ 3 ] } - )); -}; - -exports.deleteMapRedux = function () { - var obj = { a : 1, b : 2, c : [ 3, 4, 5 ] }; - var res = Traverse(obj).map(function (x) { - if (this.isLeaf && x % 2 == 0) this.delete(); - }); - - assert.ok(deepEqual( - obj, - { a : 1, b : 2, c : [ 3, 4, 5 ] } - )); - - var xs = [ 3, 4, 5 ]; - delete xs[1]; - - assert.ok(deepEqual( - res, { a : 1, c : xs } - )); - - assert.ok(!deepEqual( - res, { a : 1, c : [ 3, 5 ] } - )); - - assert.ok(deepEqual( - res, { a : 1, c : [ 3 ,, 5 ] } - )); -}; diff --git a/node_modules/findit/node_modules/seq/node_modules/hashish/node_modules/traverse/test/negative.js b/node_modules/findit/node_modules/seq/node_modules/hashish/node_modules/traverse/test/negative.js deleted file mode 100644 index f92dfb0..0000000 --- a/node_modules/findit/node_modules/seq/node_modules/hashish/node_modules/traverse/test/negative.js +++ /dev/null @@ -1,20 +0,0 @@ -var Traverse = require('../'); -var assert = require('assert'); - -exports['negative update test'] = function () { - var obj = [ 5, 6, -3, [ 7, 8, -2, 1 ], { f : 10, g : -13 } ]; - var fixed = Traverse.map(obj, function (x) { - if (x < 0) this.update(x + 128); - }); - - assert.deepEqual(fixed, - [ 5, 6, 125, [ 7, 8, 126, 1 ], { f: 10, g: 115 } ], - 'Negative values += 128' - ); - - assert.deepEqual(obj, - [ 5, 6, -3, [ 7, 8, -2, 1 ], { f: 10, g: -13 } ], - 'Original references not modified' - ); -} - diff --git a/node_modules/findit/node_modules/seq/node_modules/hashish/node_modules/traverse/test/obj.js b/node_modules/findit/node_modules/seq/node_modules/hashish/node_modules/traverse/test/obj.js deleted file mode 100644 index d46fd38..0000000 --- a/node_modules/findit/node_modules/seq/node_modules/hashish/node_modules/traverse/test/obj.js +++ /dev/null @@ -1,15 +0,0 @@ -var assert = require('assert'); -var Traverse = require('../'); - -exports['traverse an object with nested functions'] = function () { - var to = setTimeout(function () { - assert.fail('never ran'); - }, 1000); - - function Cons (x) { - clearTimeout(to); - assert.equal(x, 10); - }; - Traverse(new Cons(10)); -}; - diff --git a/node_modules/findit/node_modules/seq/node_modules/hashish/node_modules/traverse/test/siblings.js b/node_modules/findit/node_modules/seq/node_modules/hashish/node_modules/traverse/test/siblings.js deleted file mode 100644 index 99c0f1b..0000000 --- a/node_modules/findit/node_modules/seq/node_modules/hashish/node_modules/traverse/test/siblings.js +++ /dev/null @@ -1,35 +0,0 @@ -var assert = require('assert'); -var traverse = require('../'); - -exports.siblings = function () { - var obj = { a : 1, b : 2, c : [ 4, 5, 6 ] }; - - var res = traverse(obj).reduce(function (acc, x) { - var p = '/' + this.path.join('/'); - if (this.parent) { - acc[p] = { - siblings : this.parent.keys, - key : this.key, - index : this.parent.keys.indexOf(this.key) - }; - } - else { - acc[p] = { - siblings : [], - key : this.key, - index : -1 - } - } - return acc; - }, {}); - - assert.deepEqual(res, { - '/' : { siblings : [], key : undefined, index : -1 }, - '/a' : { siblings : [ 'a', 'b', 'c' ], key : 'a', index : 0 }, - '/b' : { siblings : [ 'a', 'b', 'c' ], key : 'b', index : 1 }, - '/c' : { siblings : [ 'a', 'b', 'c' ], key : 'c', index : 2 }, - '/c/0' : { siblings : [ '0', '1', '2' ], key : '0', index : 0 }, - '/c/1' : { siblings : [ '0', '1', '2' ], key : '1', index : 1 }, - '/c/2' : { siblings : [ '0', '1', '2' ], key : '2', index : 2 } - }); -}; diff --git a/node_modules/findit/node_modules/seq/node_modules/hashish/node_modules/traverse/test/stop.js b/node_modules/findit/node_modules/seq/node_modules/hashish/node_modules/traverse/test/stop.js deleted file mode 100644 index 3529847..0000000 --- a/node_modules/findit/node_modules/seq/node_modules/hashish/node_modules/traverse/test/stop.js +++ /dev/null @@ -1,41 +0,0 @@ -var assert = require('assert'); -var traverse = require('../'); - -exports.stop = function () { - var visits = 0; - traverse('abcdefghij'.split('')).forEach(function (node) { - if (typeof node === 'string') { - visits ++; - if (node === 'e') this.stop() - } - }); - - assert.equal(visits, 5); -}; - -exports.stopMap = function () { - var s = traverse('abcdefghij'.split('')).map(function (node) { - if (typeof node === 'string') { - if (node === 'e') this.stop() - return node.toUpperCase(); - } - }).join(''); - - assert.equal(s, 'ABCDEfghij'); -}; - -exports.stopReduce = function () { - var obj = { - a : [ 4, 5 ], - b : [ 6, [ 7, 8, 9 ] ] - }; - var xs = traverse(obj).reduce(function (acc, node) { - if (this.isLeaf) { - if (node === 7) this.stop(); - else acc.push(node) - } - return acc; - }, []); - - assert.deepEqual(xs, [ 4, 5, 6 ]); -}; diff --git a/node_modules/findit/node_modules/seq/node_modules/hashish/node_modules/traverse/test/stringify.js b/node_modules/findit/node_modules/seq/node_modules/hashish/node_modules/traverse/test/stringify.js deleted file mode 100644 index 932f5d3..0000000 --- a/node_modules/findit/node_modules/seq/node_modules/hashish/node_modules/traverse/test/stringify.js +++ /dev/null @@ -1,36 +0,0 @@ -var assert = require('assert'); -var Traverse = require('../'); - -exports.stringify = function () { - var obj = [ 5, 6, -3, [ 7, 8, -2, 1 ], { f : 10, g : -13 } ]; - - var s = ''; - Traverse(obj).forEach(function (node) { - if (Array.isArray(node)) { - this.before(function () { s += '[' }); - this.post(function (child) { - if (!child.isLast) s += ','; - }); - this.after(function () { s += ']' }); - } - else if (typeof node == 'object') { - this.before(function () { s += '{' }); - this.pre(function (x, key) { - s += '"' + key + '"' + ':'; - }); - this.post(function (child) { - if (!child.isLast) s += ','; - }); - this.after(function () { s += '}' }); - } - else if (typeof node == 'function') { - s += 'null'; - } - else { - s += node.toString(); - } - }); - - assert.equal(s, JSON.stringify(obj)); -} - diff --git a/node_modules/findit/node_modules/seq/node_modules/hashish/node_modules/traverse/test/subexpr.js b/node_modules/findit/node_modules/seq/node_modules/hashish/node_modules/traverse/test/subexpr.js deleted file mode 100644 index a217beb..0000000 --- a/node_modules/findit/node_modules/seq/node_modules/hashish/node_modules/traverse/test/subexpr.js +++ /dev/null @@ -1,34 +0,0 @@ -var traverse = require('../'); -var assert = require('assert'); - -exports.subexpr = function () { - var obj = [ 'a', 4, 'b', 5, 'c', 6 ]; - var r = traverse(obj).map(function (x) { - if (typeof x === 'number') { - this.update([ x - 0.1, x, x + 0.1 ], true); - } - }); - - assert.deepEqual(obj, [ 'a', 4, 'b', 5, 'c', 6 ]); - assert.deepEqual(r, [ - 'a', [ 3.9, 4, 4.1 ], - 'b', [ 4.9, 5, 5.1 ], - 'c', [ 5.9, 6, 6.1 ], - ]); -}; - -exports.block = function () { - var obj = [ [ 1 ], [ 2 ], [ 3 ] ]; - var r = traverse(obj).map(function (x) { - if (Array.isArray(x) && !this.isRoot) { - if (x[0] === 5) this.block() - else this.update([ [ x[0] + 1 ] ]) - } - }); - - assert.deepEqual(r, [ - [ [ [ [ [ 5 ] ] ] ] ], - [ [ [ [ 5 ] ] ] ], - [ [ [ 5 ] ] ], - ]); -}; diff --git a/node_modules/findit/node_modules/seq/node_modules/hashish/node_modules/traverse/test/super_deep.js b/node_modules/findit/node_modules/seq/node_modules/hashish/node_modules/traverse/test/super_deep.js deleted file mode 100644 index acac2fd..0000000 --- a/node_modules/findit/node_modules/seq/node_modules/hashish/node_modules/traverse/test/super_deep.js +++ /dev/null @@ -1,55 +0,0 @@ -var assert = require('assert'); -var traverse = require('../'); -var deepEqual = require('./lib/deep_equal'); - -exports.super_deep = function () { - var util = require('util'); - var a0 = make(); - var a1 = make(); - assert.ok(deepEqual(a0, a1)); - - a0.c.d.moo = true; - assert.ok(!deepEqual(a0, a1)); - - a1.c.d.moo = true; - assert.ok(deepEqual(a0, a1)); - - // TODO: this one - //a0.c.a = a1; - //assert.ok(!deepEqual(a0, a1)); -}; - -function make () { - var a = { self : 'a' }; - var b = { self : 'b' }; - var c = { self : 'c' }; - var d = { self : 'd' }; - var e = { self : 'e' }; - - a.a = a; - a.b = b; - a.c = c; - - b.a = a; - b.b = b; - b.c = c; - - c.a = a; - c.b = b; - c.c = c; - c.d = d; - - d.a = a; - d.b = b; - d.c = c; - d.d = d; - d.e = e; - - e.a = a; - e.b = b; - e.c = c; - e.d = d; - e.e = e; - - return a; -} diff --git a/node_modules/findit/node_modules/seq/node_modules/hashish/package.json b/node_modules/findit/node_modules/seq/node_modules/hashish/package.json deleted file mode 100644 index 33c7f22..0000000 --- a/node_modules/findit/node_modules/seq/node_modules/hashish/package.json +++ /dev/null @@ -1,33 +0,0 @@ -{ - "name" : "hashish", - "version" : "0.0.4", - "description" : "Hash data structure manipulation functions", - "main" : "./index.js", - "repository" : { - "type" : "git", - "url" : "http://github.com/substack/node-hashish.git" - }, - "keywords": [ - "hash", - "object", - "convenience", - "manipulation", - "data structure" - ], - "author" : { - "name" : "James Halliday", - "email" : "mail@substack.net", - "url" : "http://substack.net" - }, - "dependencies" : { - "traverse" : ">=0.2.4" - }, - "devDependencies" : { - "expresso" : ">=0.6.0" - }, - "scripts" : { - "test" : "expresso" - }, - "license" : "MIT/X11", - "engine" : ["node >=0.2.0"] -} diff --git a/node_modules/findit/node_modules/seq/node_modules/hashish/test/hash.js b/node_modules/findit/node_modules/seq/node_modules/hashish/test/hash.js deleted file mode 100644 index 6afce60..0000000 --- a/node_modules/findit/node_modules/seq/node_modules/hashish/test/hash.js +++ /dev/null @@ -1,250 +0,0 @@ -var Hash = require('hashish'); -var assert = require('assert'); - -exports.map = function () { - var ref = { a : 1, b : 2 }; - var items = Hash(ref).map(function (v) { return v + 1 }).items; - var hash = Hash.map(ref, function (v) { return v + 1 }); - assert.deepEqual(ref, { a : 1, b : 2 }); - assert.deepEqual(items, { a : 2, b : 3 }); - assert.deepEqual(hash, { a : 2, b : 3 }); -}; - -exports['cloned map'] = function () { - var ref = { foo : [1,2], bar : [4,5] }; - var hash = Hash(ref).clone.map( - function (v) { v.unshift(v[0] - 1); return v } - ).items; - assert.deepEqual(ref.foo, [1,2]); - assert.deepEqual(ref.bar, [4,5]); - assert.deepEqual(hash.foo, [0,1,2]); - assert.deepEqual(hash.bar, [3,4,5]); -}; - -exports.forEach = function () { - var ref = { a : 5, b : 2, c : 7, 1337 : 'leet' }; - var xs = []; - Hash(ref).forEach(function (x, i) { - xs.push([ i, x ]); - }); - - assert.eql( - xs.map(function (x) { return x[0] }).sort(), - [ '1337', 'a', 'b', 'c' ] - ); - - assert.eql( - xs.map(function (x) { return x[1] }).sort(), - [ 2, 5, 7, 'leet' ] - ); - - var ys = []; - Hash.forEach(ref, function (x, i) { - ys.push([ i, x ]); - }); - - assert.eql(xs.sort(), ys.sort()); -}; - -exports.filter_items = function () { - var ref = { a : 5, b : 2, c : 7, 1337 : 'leet' }; - var items = Hash(ref).filter(function (v, k) { - return v > 5 || k > 5 - }).items; - var hash = Hash.filter(ref, function (v, k) { return v > 5 || k > 5 }); - assert.deepEqual(items, { 1337 : 'leet', c : 7 }); - assert.deepEqual(hash, { 1337 : 'leet', c : 7 }); - assert.deepEqual(ref, { a : 5, b : 2, c : 7, 1337 : 'leet' }); - assert.equal(Hash(ref).length, 4); -}; - -exports.detect = function () { - var h = { a : 5, b : 6, c : 7, d : 8 }; - var hh = Hash(h); - var gt6hh = hh.detect(function (x) { return x > 6 }); - assert.ok(gt6hh == 7 || gt6hh == 8); - var gt6h = Hash.detect(h, function (x) { return x > 6 }); - assert.ok(gt6h == 7 || gt6h == 8); - assert.equal(hh.detect(function (x) { return x > 100 }), undefined); -}; - -exports.reduce = function () { - var ref = { foo : [1,2], bar : [4,5] }; - - var sum1 = Hash(ref).reduce(function (acc, v) { - return acc + v.length - }, 0); - assert.equal(sum1, 4); - - var sum2 = Hash.reduce(ref, function (acc, v) { - return acc + v.length - }, 0); - assert.equal(sum2, 4); -}; - -exports.some = function () { - var h = { a : 5, b : 6, c : 7, d : 8 }; - var hh = Hash(h); - assert.ok(Hash.some(h, function (x) { return x > 7 })); - assert.ok(Hash.some(h, function (x) { return x < 6 })); - assert.ok(!Hash.some(h, function (x) { return x > 10 })); - assert.ok(!Hash.some(h, function (x) { return x < 0 })); - - assert.ok(hh.some(function (x) { return x > 7 })); - assert.ok(hh.some(function (x) { return x < 6 })); - assert.ok(!hh.some(function (x) { return x > 10 })); - assert.ok(!hh.some(function (x) { return x < 0 })); -}; - -exports.update = function () { - var ref = { a : 1, b : 2 }; - var items = Hash(ref).clone.update({ c : 3, a : 0 }).items; - assert.deepEqual(ref, { a : 1, b : 2 }); - assert.deepEqual(items, { a : 0, b : 2, c : 3 }); - - var hash = Hash.update(ref, { c : 3, a : 0 }); - assert.deepEqual(ref, hash); - assert.deepEqual(hash, { a : 0, b : 2, c : 3 }); - - var ref2 = {a: 1}; - var hash2 = Hash.update(ref2, { b: 2, c: 3 }, undefined, { d: 4 }); - assert.deepEqual(ref2, { a: 1, b: 2, c: 3, d: 4 }); -}; - -exports.merge = function () { - var ref = { a : 1, b : 2 }; - var items = Hash(ref).merge({ b : 3, c : 3.14 }).items; - var hash = Hash.merge(ref, { b : 3, c : 3.14 }); - - assert.deepEqual(ref, { a : 1, b : 2 }); - assert.deepEqual(items, { a : 1, b : 3, c : 3.14 }); - assert.deepEqual(hash, { a : 1, b : 3, c : 3.14 }); - - var ref2 = { a : 1 }; - var hash2 = Hash.merge(ref, { b: 2, c: 3 }, undefined, { d: 4 }); - assert.deepEqual(hash2, { a: 1, b: 2, c: 3, d: 4 }); -}; - -exports.has = function () { - var h = { a : 4, b : 5 }; - var hh = Hash(h); - - assert.ok(hh.has('a')); - assert.equal(hh.has('c'), false); - assert.ok(hh.has(['a','b'])); - assert.equal(hh.has(['a','b','c']), false); - - assert.ok(Hash.has(h, 'a')); - assert.equal(Hash.has(h, 'c'), false); - assert.ok(Hash.has(h, ['a','b'])); - assert.equal(Hash.has(h, ['a','b','c']), false); -}; - -exports.valuesAt = function () { - var h = { a : 4, b : 5, c : 6 }; - assert.equal(Hash(h).valuesAt('a'), 4); - assert.equal(Hash(h).valuesAt(['a'])[0], 4); - assert.deepEqual(Hash(h).valuesAt(['a','b']), [4,5]); - assert.equal(Hash.valuesAt(h, 'a'), 4); - assert.deepEqual(Hash.valuesAt(h, ['a']), [4]); - assert.deepEqual(Hash.valuesAt(h, ['a','b']), [4,5]); -}; - -exports.tap = function () { - var h = { a : 4, b : 5, c : 6 }; - var hh = Hash(h); - hh.tap(function (x) { - assert.ok(this === hh) - assert.eql(x, h); - }); - - Hash.tap(h, function (x) { - assert.eql( - Object.keys(this).sort(), - Object.keys(hh).sort() - ); - assert.eql(x, h); - }); -}; - -exports.extract = function () { - var hash = Hash({ a : 1, b : 2, c : 3 }).clone; - var extracted = hash.extract(['a','b']); - assert.equal(extracted.length, 2); - assert.deepEqual(extracted.items, { a : 1, b : 2 }); -}; - -exports.exclude = function () { - var hash = Hash({ a : 1, b : 2, c : 3 }).clone; - var extracted = hash.exclude(['a','b']); - assert.equal(extracted.length, 1); - assert.deepEqual(extracted.items, { c : 3 }); -}; - -exports.concat = function () { - var ref1 = { a : 1, b : 2 }; - var ref2 = { foo : 100, bar : 200 }; - var ref3 = { b : 3, c : 4, bar : 300 }; - - assert.deepEqual( - Hash.concat([ ref1, ref2 ]), - { a : 1, b : 2, foo : 100, bar : 200 } - ); - - assert.deepEqual( - Hash.concat([ ref1, ref2, ref3 ]), - { a : 1, b : 3, c : 4, foo : 100, bar : 300 } - ); -}; - -exports.zip = function () { - var xs = ['a','b','c']; - var ys = [1,2,3,4]; - var h = Hash(xs,ys); - assert.equal(h.length, 3); - assert.deepEqual(h.items, { a : 1, b : 2, c : 3 }); - - var zipped = Hash.zip(xs,ys); - assert.deepEqual(zipped, { a : 1, b : 2, c : 3 }); -}; - -exports.length = function () { - assert.equal(Hash({ a : 1, b : [2,3], c : 4 }).length, 3); - assert.equal(Hash({ a : 1, b : [2,3], c : 4 }).size, 3); - assert.equal(Hash.size({ a : 1, b : [2,3], c : 4 }), 3); -}; - -exports.compact = function () { - var hash = { - a : 1, - b : undefined, - c : false, - d : 4, - e : [ undefined, 4 ], - f : null - }; - var compacted = Hash(hash).compact; - assert.deepEqual( - { - a : 1, - b : undefined, - c : false, - d : 4, - e : [ undefined, 4 ], - f : null - }, - hash, 'compact modified the hash' - ); - assert.deepEqual( - compacted.items, - { - a : 1, - c : false, - d : 4, - e : [ undefined, 4 ], - f : null - } - ); - var h = Hash.compact(hash); - assert.deepEqual(h, compacted.items); -}; diff --git a/node_modules/findit/node_modules/seq/node_modules/hashish/test/property.js b/node_modules/findit/node_modules/seq/node_modules/hashish/test/property.js deleted file mode 100644 index 1183c5d..0000000 --- a/node_modules/findit/node_modules/seq/node_modules/hashish/test/property.js +++ /dev/null @@ -1,69 +0,0 @@ -var Hash = require('hashish'); -var assert = require('assert'); -var vm = require('vm'); -var fs = require('fs'); - -var src = fs.readFileSync(__dirname + '/../index.js', 'utf8'); - -exports.defineGetter = function () { - var context = { - module : { exports : {} }, - Object : { - keys : Object.keys, - defineProperty : undefined, - }, - require : require, - }; - context.exports = context.module.exports; - - vm.runInNewContext('(function () {' + src + '})()', context); - var Hash_ = context.module.exports; - - var times = 0; - Hash_.__proto__.__proto__.__defineGetter__ = function () { - times ++; - return Object.__defineGetter__.apply(this, arguments); - }; - - assert.equal(vm.runInNewContext('Object.defineProperty', context), null); - - assert.deepEqual( - Hash_({ a : 1, b : 2, c : 3 }).values, - [ 1, 2, 3 ] - ); - - assert.ok(times > 5); -}; - -exports.defineProperty = function () { - var times = 0; - var context = { - module : { exports : {} }, - Object : { - keys : Object.keys, - defineProperty : function (prop) { - times ++; - if (prop.get) throw new TypeError('engine does not support') - assert.fail('should have asserted by now'); - }, - }, - require : require - }; - context.exports = context.module.exports; - - vm.runInNewContext('(function () {' + src + '})()', context); - var Hash_ = context.module.exports; - - Hash_.__proto__.__proto__.__defineGetter__ = function () { - assert.fail('getter called when a perfectly good' - + ' defineProperty was available' - ); - }; - - assert.deepEqual( - Hash_({ a : 1, b : 2, c : 3 }).values, - [ 1, 2, 3 ] - ); - - assert.equal(times, 1); -}; diff --git a/node_modules/findit/node_modules/seq/package.json b/node_modules/findit/node_modules/seq/package.json deleted file mode 100644 index 0c971d6..0000000 --- a/node_modules/findit/node_modules/seq/package.json +++ /dev/null @@ -1,33 +0,0 @@ -{ - "name" : "seq", - "version" : "0.3.5", - "description" : "Chainable asynchronous flow control with sequential and parallel primitives and pipeline-style error handling", - "main" : "./index.js", - "repository" : { - "type" : "git", - "url" : "http://github.com/substack/node-seq.git" - }, - "dependencies" : { - "chainsaw" : ">=0.0.7 <0.1", - "hashish" : ">=0.0.2 <0.1" - }, - "devDependencies" : { - "expresso" : ">=0.7.x" - }, - "script" : { - "test" : "expresso" - }, - "keywords" : [ - "flow-control", "flow", "control", "async", "asynchronous", "chain", - "pipeline", "sequence", "sequential", "parallel", "error" - ], - "author" : { - "name" : "James Halliday", - "email" : "mail@substack.net", - "url" : "http://substack.net" - }, - "license" : "MIT/X11", - "engine" : { - "node" : ">=0.4.0" - } -} diff --git a/node_modules/findit/node_modules/seq/test/readdir.js b/node_modules/findit/node_modules/seq/test/readdir.js deleted file mode 100644 index fe1a38b..0000000 --- a/node_modules/findit/node_modules/seq/test/readdir.js +++ /dev/null @@ -1,35 +0,0 @@ -var assert = require('assert'); -var Seq = require('seq'); -var fs = require('fs'); - -exports.readdir = function () { - var to = setTimeout(function () { - assert.fail('never got to the end of the chain'); - }, 500); - - Seq() - .seq(fs.readdir, __dirname, Seq) - .seq(function (files) { - clearTimeout(to); - assert.ok(files.length >= 2); - }) - .catch(assert.fail) - ; -}; - -exports.readdirs = function () { - var to = setTimeout(function () { - assert.fail('never got to the end of the chain'); - }, 500); - - Seq() - .par(fs.readdir, __dirname, Seq) - .par(fs.readdir, __dirname + '/../examples', Seq) - .seq(function (tests, examples) { - clearTimeout(to); - assert.ok(tests.length >= 2); - assert.ok(examples.length >= 2); - }) - .catch(assert.fail) - ; -}; diff --git a/node_modules/findit/node_modules/seq/test/seq.js b/node_modules/findit/node_modules/seq/test/seq.js deleted file mode 100644 index 2e34aec..0000000 --- a/node_modules/findit/node_modules/seq/test/seq.js +++ /dev/null @@ -1,946 +0,0 @@ -var Seq = require('seq'); -var assert = require('assert'); - -exports.seq = function () { - var to = setTimeout(function () { - assert.fail('never got to the end of the chain'); - }, 100); - - Seq([0]) - .seq('pow', function (n) { - this(null, 1); - }) - .seq(function (n) { - assert.eql(n, 1); - assert.eql(n, this.vars.pow); - var seq = this; - setTimeout(function () { seq(null, 2) }, 25); - assert.eql(this.stack, [n]); - }) - .seq(function (n) { - assert.eql(n, 2); - assert.eql(this.stack, [n]); - this(null, 5, 6, 7); - }) - .seq(function (x, y, z) { - clearTimeout(to); - assert.eql([x,y,z], [5,6,7]); - }) - ; -}; - -exports.into = function () { - var to = setTimeout(function () { - assert.fail('never got to the end of the chain'); - }, 10); - var calls = 0; - - Seq([3,4,5]) - .seq(function () { - this.into('w')(null, 5); - }) - .seq(function (w) { - clearTimeout(to); - assert.eql(w, this.vars.w); - assert.eql(arguments.length, 1); - assert.eql(w, 5); - }) - ; -}; - -exports.catchSeq = function () { - var to = setTimeout(function () { - assert.fail('never caught the error'); - }, 100); - - var tf = setTimeout(function () { - assert.fail('final action never executed'); - }, 100); - - var calls = {}; - Seq([1]) - .seq(function (n) { - assert.eql(n, 1); - calls.before = true; - this('pow!'); - calls.after = true; - }) - .seq(function (n) { - calls.next = true; - assert.fail('should have skipped this'); - }) - .catch(function (err) { - assert.eql(err, 'pow!'); - assert.ok(calls.before); - assert.ok(!calls.after); - assert.ok(!calls.next); - clearTimeout(to); - }) - .do(function () { - //assert.ok(calls.after); - clearTimeout(tf); - }) - ; -}; - -exports.par = function () { - var to = setTimeout(function () { - assert.fail('seq never fired'); - }, 1000); - - Seq() - .seq(function () { - this(null, 'mew'); - }) - .par(function () { - var seq = this; - setTimeout(function () { seq(null, 'x') }, 50); - }) - .par(function () { - var seq = this; - setTimeout(function () { seq(null, 'y') }, 25); - }) - .par('z', function () { - this(null, 42); - }) - .seq(function (x, y, z) { - clearTimeout(to); - assert.eql(x, 'x'); - assert.eql(y, 'y'); - assert.eql(z, 42); - assert.eql(this.args, { 0 : ['x'], 1 : ['y'], z : [42] }); - assert.eql(this.stack, [ 'x', 'y', 42 ]); - assert.eql(this.vars, { z : 42 }); - }) - ; -}; - -exports.catchPar = function () { - var done = false, caught = false; - var tc = setTimeout(function () { - assert.fail('error not caught'); - }, 1000); - - Seq() - .par('one', function () { - setTimeout(this.bind({}, 'rawr'), 25); - }) - .par('two', function () { - setTimeout(this.bind({}, null, 'y'), 50); - }) - .seq(function (x, y) { - assert.fail('seq fired with error above'); - }) - .catch(function (err, key) { - clearTimeout(tc); - assert.eql(err, 'rawr'); - assert.eql(key, 'one'); - }) - ; -}; - -exports.catchParWithoutSeq = function () { - var done = false, caught = false; - var tc = setTimeout(function () { - assert.fail('error not caught'); - }, 5000); - - Seq() - .par('one', function () { - setTimeout(this.bind({}, 'rawr'), 25); - }) - .par('two', function () { - setTimeout(this.bind({}, null, 'y'), 50); - }) - .catch(function (err, key) { - clearTimeout(tc); - assert.eql(err, 'rawr'); - assert.eql(key, 'one'); - }) - ; -} - -exports.catchParMultipleErrors = function() { - var caught={}; - var to = setTimeout(function() { - assert.fail('Never finished'); - }, 1000); - var times = 0; - - Seq() - .par('one', function() { - setTimeout(this.bind({}, 'rawr1'), 25); - }) - .par('two', function() { - setTimeout(this.bind({}, 'rawr2'), 50); - }) - .catch(function(err,key) { - caught[key] = err; - }) - .seq(function() { - clearTimeout(to); - times ++; - assert.eql(times, 1); - assert.eql(caught, { one:'rawr1', two:'rawr2' }); - }) - ; -}; - -exports.catchParThenSeq = function () { - var tc = setTimeout(function () { - assert.fail('error not caught'); - }, 1000); - var tf = setTimeout(function () { - assert.fail('final seq not run'); - }, 500); - var times = 0; - var errs = [ - { key : 'one', msg : 'rawr' }, - { key : 'four', msg : 'pow' }, - ]; - - Seq() - .par('one', function () { - setTimeout(this.bind({}, 'rawr'), 25); - }) - .par('two', function () { - setTimeout(this.bind({}, null, 'y'), 50); - }) - .par('three', function () { - setTimeout(this.bind({}, null, 'z'), 30); - }) - .par('four', function () { - setTimeout(this.bind({}, 'pow'), 45); - }) - .seq(function (x, y) { - assert.fail('seq fired with error above'); - }) - .catch(function (err, key) { - clearTimeout(tc); - var e = errs.shift(); - assert.eql(err, e.msg); - assert.eql(key, e.key); - }) - .seq(function () { - clearTimeout(tf); - times ++; - assert.eql(times, 1); - }) - ; -} - -exports.forEach = function () { - var to = setTimeout(function () { - assert.fail('seq never fired after forEach'); - }, 25); - - var count = 0; - Seq([1,2,3]) - .push(4) - .forEach(function (x, i) { - assert.eql(x - 1, i); - count ++; - }) - .seq(function () { - clearTimeout(to); - assert.eql(count, 4); - }) - ; -}; - -exports.seqEach = function () { - var to = setTimeout(function () { - assert.fail('seqEach never finished'); - }, 25); - - var count = 0; - var ii = 0; - Seq([1,2,3]) - .seqEach(function (x, i) { - assert.eql(i, ii++); - assert.eql(x, [1,2,3][i]); - count ++; - this(null); - }) - .seq(function () { - clearTimeout(to); - assert.eql(count, 3); - }) - ; -}; - -exports.seqEachCatch = function () { - var to = setTimeout(function () { - assert.fail('never caught the error'); - }, 25); - var tf = setTimeout(function () { - assert.fail('never resumed afterwards'); - }, 25); - - var meows = []; - - var values = []; - Seq([1,2,3,4]) - .seqEach(function (x, i) { - values.push([i,x]); - assert.eql(x - 1, i); - if (i >= 2) this('meow ' + i) - else this(null, x * 10); - }) - .seq(function (xs) { - assert.fail('should fail before this action'); - }) - .catch(function (err) { - clearTimeout(to); - meows.push(err); - assert.eql(err, 'meow 2'); - assert.eql(values, [[0,1],[1,2],[2,3]]); - }) - .seq(function () { - clearTimeout(tf); - }) - ; -}; - -exports.parEach = function () { - var to = setTimeout(function () { - assert.fail('never finished'); - }, 100); - - var values = []; - Seq([1,2,3,4]) - .parEach(function (x, i) { - values.push([i,x]); - setTimeout(this.bind({}, null), 20); - }) - .seq(function () { - assert.deepEqual(this.stack, [1,2,3,4]) - assert.deepEqual(values, [[0,1],[1,2],[2,3],[3,4]]); - clearTimeout(to); - }) - ; -}; - -exports.parEachVars = function () { - var to = setTimeout(function () { - assert.fail('never finished'); - }, 1000); - var values = []; - - Seq() - .seq('abc', function () { - this(null, 'a', 'b', 'c'); - }) - .parEach(function (x) { - values.push(x); - setTimeout(this.bind(this, null), Math.floor(Math.random() * 50)); - }) - .seq(function () { - clearTimeout(to); - assert.eql(values, ['a','b','c']); - assert.eql(this.stack, ['a','b','c']); - assert.eql(this.vars.abc, 'a'); - }) - ; -}; - -exports.parEachInto = function () { - var to = setTimeout(function () { - assert.fail('never finished'); - }, 100); - - Seq([1,2,3,4]) - .parEach(function (x, i) { - setTimeout((function () { - this.into('abcd'.charAt(i))(null, x); - }).bind(this), 20); - }) - .seq(function () { - clearTimeout(to); - assert.deepEqual(this.stack, [1,2,3,4]) - assert.deepEqual(this.vars, { a : 1, b : 2, c : 3, d : 4 }); - }) - ; -}; - -exports.parEachCatch = function () { - var to = setTimeout(function () { - assert.fail('never finished'); - }, 100); - - var values = []; - Seq([1,2,3,4]) - .parEach(function (x, i) { - values.push([i,x]); - setTimeout(this.bind({}, 'zing'), 10); - }) - .seq(function () { - assert.fail('should have errored before this point') - }) - .catch(function (err) { - clearTimeout(to); - assert.eql(err, 'zing'); - assert.deepEqual(values, [[0,1],[1,2],[2,3],[3,4]]); - }) - ; -}; - -exports.parEachLimited = function () { - var to = setTimeout(function () { - assert.fail('never finished'); - }, 500); - - var running = 0; - var values = []; - Seq([1,2,3,4,5,6,7,8,9,10]) - .parEach(3, function (x, i) { - running ++; - - assert.ok(running <= 3); - - values.push([i,x]); - setTimeout((function () { - running --; - this(null); - }).bind(this), 10); - }) - .seq(function () { - clearTimeout(to); - assert.eql(values, - [[0,1],[1,2],[2,3],[3,4],[4,5],[5,6],[6,7],[7,8],[8,9],[9,10]] - ); - }) - ; -}; - -exports.parMap = function () { - var to = setTimeout(function () { - assert.fail('never finished'); - }, 500); - - var running = 0; - var values = []; - Seq([1,2,3,4,5,6,7,8,9,10]) - .parMap(2, function (x, i) { - running ++; - - assert.ok(running <= 2); - - setTimeout((function () { - running --; - this(null, x * 10); - }).bind(this), Math.floor(Math.random() * 100)); - }) - .seq(function () { - clearTimeout(to); - assert.eql(this.stack, [10,20,30,40,50,60,70,80,90,100]); - assert.eql(this.stack, [].slice.call(arguments)); - }) - ; -}; - -exports.parMapFast = function () { - var to = setTimeout(function () { - assert.fail('never finished'); - }, 500); - - var values = []; - Seq([1,2,3,4,5,6,7,8,9,10]) - .parMap(function (x, i) { - this(null, x * 10); - }) - .seq(function () { - clearTimeout(to); - assert.eql(this.stack, [10,20,30,40,50,60,70,80,90,100]); - assert.eql(this.stack, [].slice.call(arguments)); - }) - ; -}; - -exports.parMapInto = function () { - var to = setTimeout(function () { - assert.fail('never finished'); - }, 500); - - var values = []; - Seq([1,2,3,4,5,6,7,8,9,10]) - .parMap(function (x, i) { - this.into(9 - i)(null, x * 10); - }) - .seq(function () { - clearTimeout(to); - assert.eql(this.stack, [100, 90, 80, 70, 60, 50, 40, 30, 20, 10]); - assert.eql(this.stack, [].slice.call(arguments)); - }) - ; -}; - -exports.seqMap = function () { - var to = setTimeout(function () { - assert.fail('never finished'); - }, 500); - - var running = 0; - var values = []; - Seq([1,2,3,4,5,6,7,8,9,10]) - .seqMap(function (x, i) { - running ++; - - assert.eql(running, 1); - - setTimeout((function () { - running --; - this(null, x * 10); - }).bind(this), 10); - }) - .seq(function () { - clearTimeout(to); - assert.eql(this.stack, [10,20,30,40,50,60,70,80,90,100]); - }) - ; -}; - - -exports.seqMapInto = function () { - var to = setTimeout(function () { - assert.fail('never finished'); - }, 500); - - var running = 0; - var values = []; - Seq([1,2,3,4,5,6,7,8,9,10]) - .seqMap(function (x, i) { - running ++; - - assert.eql(running, 1); - - setTimeout((function () { - running --; - this.into(9 - i)(null, x * 10); - }).bind(this), 10); - }) - .seq(function () { - clearTimeout(to); - assert.eql(this.stack, [100, 90, 80, 70, 60, 50, 40, 30, 20, 10]); - }) - ; -}; - -exports.parFilter = function () { - var to = setTimeout(function () { - assert.fail('never finished'); - }, 500); - - var running = 0; - var values = []; - Seq([1,2,3,4,5,6,7,8,9,10]) - .parFilter(2, function (x, i) { - running ++; - - assert.ok(running <= 2); - - setTimeout((function () { - running --; - this(null, x % 2 === 0); - }).bind(this), Math.floor(Math.random() * 100)); - }) - .seq(function () { - clearTimeout(to); - assert.eql(this.stack, [2,4,6,8,10]); - assert.eql(this.stack, [].slice.call(arguments)); - }) - ; -}; - -exports.seqFilter = function () { - var to = setTimeout(function () { - assert.fail('never finished'); - }, 500); - - var running = 0; - var values = []; - Seq([1,2,3,4,5,6,7,8,9,10]) - .seqFilter(function (x, i) { - running ++; - - assert.eql(running, 1); - - setTimeout((function () { - running --; - this(null, x % 2 === 0); - }).bind(this), 10); - }) - .seq(function () { - clearTimeout(to); - assert.eql(this.stack, [2,4,6,8,10]); - }) - ; -}; - -exports.parFilterInto = function () { - var to = setTimeout(function () { - assert.fail('never finished'); - }, 500); - - var running = 0; - var values = []; - Seq([1,2,3,4,5,6,7,8,9,10]) - .parFilter(2, function (x, i) { - running ++; - - assert.ok(running <= 2); - - setTimeout((function () { - running --; - this.into(x % 3)(null, x % 2 === 0); - }).bind(this), Math.floor(Math.random() * 100)); - }) - .seq(function () { - clearTimeout(to); - assert.eql(this.stack, [ 6, 10, 4, 2, 8 ]); - assert.eql(this.stack, [].slice.call(arguments)); - }) - ; -}; - -exports.seqFilterInto = function () { - var to = setTimeout(function () { - assert.fail('never finished'); - }, 500); - - var running = 0; - var values = []; - Seq([1,2,3,4,5,6,7,8,9,10]) - .seqFilter(function (x, i) { - running ++; - - assert.eql(running, 1); - - setTimeout((function () { - running --; - this.into(x % 3)(null, x % 2 === 0); - }).bind(this), 10); - }) - .seq(function () { - clearTimeout(to); - assert.eql(this.stack, [ 6, 10, 4, 2, 8 ]); - }) - ; -}; - -exports.stack = function () { - var to = setTimeout(function () { - assert.fail('never finished'); - }, 100); - - Seq([4,5,6]) - .seq(function (x, y, z) { - assert.eql(arguments.length, 3); - assert.eql([x,y,z], [4,5,6]); - assert.eql(this.stack, [4,5,6]); - this(null); - }) - .set([3,4]) - .seq(function (x, y) { - assert.eql(arguments.length, 2); - assert.eql([x,y], [3,4]); - assert.eql(this.stack, [3,4]); - this(null); - }) - .empty() - .seq(function () { - assert.eql(arguments.length, 0); - assert.eql(this.stack, []); - this.next(null, ['a']); - }) - .extend(['b','c']) - .seq(function (a, b, c) { - assert.eql(arguments.length, 3); - assert.eql([a,b,c], ['a','b','c']); - assert.eql(this.stack, ['a','b','c']); - this.pass(null); - }) - .pop() - .push('c', 'd', 'e') - .seq(function (a, b, c, d, e) { - assert.eql(arguments.length, 5); - assert.eql([a,b,c,d,e], ['a','b','c','d','e']); - assert.eql(this.stack, ['a','b','c','d','e']); - this.pass(null); - }) - .shift() - .shift() - .seq(function (c, d, e) { - assert.eql(arguments.length, 3); - assert.eql([c,d,e], ['c','d','e']); - assert.eql(this.stack, ['c','d','e']); - this.pass(null); - }) - .set([['a',['b']],['c','d',['e']]]) - .flatten(false) // only flatten one level - .seq(function (a, b, c, d, e) { - assert.eql(arguments.length, 5); - assert.eql([a,b,c,d,e], ['a',['b'],'c','d',['e']]); - assert.eql(this.stack, ['a',['b'],'c','d',['e']]); - this.pass(null); - }) - .set([['a','b'],['c','d',['e']]]) - .flatten() - .seq(function (a, b, c, d, e) { - assert.eql(arguments.length, 5); - assert.eql([a,b,c,d,e], ['a','b','c','d','e']); - assert.eql(this.stack, ['a','b','c','d','e']); - this.pass(null); - }) - .splice(2, 2) - .seq(function (a, b, e) { - assert.eql(arguments.length, 3); - assert.eql([a,b,e], ['a','b','e']); - assert.eql(this.stack, ['a','b','e']); - this.pass(null); - }) - .reverse() - .seq(function (a, b, e){ - assert.eql(arguments.length, 3); - assert.eql([a,b,e], ['e','b','a']); - assert.eql(this.stack, ['e','b','a']); - this.pass(null); - }) - .map(function(ch){ return ch.toUpperCase(); }) - .seq(function (A, B, E){ - assert.eql(arguments.length, 3); - assert.eql([A,B,E], ['E','B','A']); - assert.eql(this.stack, ['E','B','A']); - this.pass(null); - }) - .reduce(function(s, ch){ return s + ':' + ch; }) - .seq(function (acc){ - assert.eql(arguments.length, 1); - assert.eql(acc, 'E:B:A'); - assert.eql(this.stack, ['E:B:A']); - this.pass(null); - }) - .seq(function () { - clearTimeout(to); - this(null); - }) - ; -}; - -exports.ap = function () { - var to = setTimeout(function () { - assert.fail('never finished'); - }, 100); - - var cmp = [1,2,3]; - Seq.ap([1,2,3]) - .seqEach(function (x) { - assert.eql(cmp.shift(), x); - this(null); - }) - .seq(function () { - clearTimeout(to); - assert.eql(cmp, []); - }) - ; - - assert.throws(function () { - Seq.ap({ a : 1, b : 2 }); - }); -}; - -exports.seqBind = function () { - var to = setTimeout(function () { - assert.fail('never finished'); - }, 100); - - Seq([4,5]) - .seq(function (a, b, c, d) { - assert.eql(a, 2); - assert.eql(b, 3); - assert.eql(c, 4); - assert.eql(d, 5); - this(null); - }, 2, 3) - .seq(function () { - clearTimeout(to); - }) - ; -}; - -exports.parBind = function () { - var t1 = setTimeout(function () { - assert.fail('1 never finished'); - }, 500); - var t2 = setTimeout(function () { - assert.fail('2 never finished'); - }, 500); - var t3 = setTimeout(function () { - assert.fail('3 never finished'); - }, 500); - - Seq(['c']) - .par(function (a, b, c) { - clearTimeout(t1); - assert.eql(a, 'a'); - assert.eql(b, 'b'); - assert.eql(c, 'c'); - this(null); - }, 'a', 'b') - .par(function (x, c) { - clearTimeout(t2); - assert.eql(x, 'x'); - assert.eql(c, 'c'); - this(null); - }, 'x') - .seq(function () { - clearTimeout(t3); - }) - ; -}; - -exports.emptySeqEach = function () { - var to = setTimeout(function () { - assert.fail('never finished'); - }, 100); - - Seq() - .seqEach(function (x) { - assert.fail('no elements'); - }) - .seq(function () { - clearTimeout(to); - }) - ; -}; - -exports.emptyForEach = function () { - var to = setTimeout(function () { - assert.fail('seq never fired'); - }, 500); - - Seq() - .forEach(function () { - assert.fail('non-empty stack'); - }) - .seq(function () { - clearTimeout(to); - }) - ; -}; - -exports.emptyParEach = function () { - var to = setTimeout(function () { - assert.fail('seq never fired'); - }, 500); - - Seq() - .parEach(function () { - assert.fail('non-empty stack'); - }) - .seq(function () { - clearTimeout(to); - }) - ; -}; - -exports.emptyParMap = function () { - var to = setTimeout(function () { - assert.fail('seq never fired'); - }, 500); - - Seq() - .parMap(function () { - assert.fail('non-empty stack'); - }) - .seq(function () { - clearTimeout(to); - }) - ; -}; - -exports.emptySeqMap = function () { - var to = setTimeout(function () { - assert.fail('seq never fired'); - }, 500); - - Seq() - .seqMap(function () { - assert.fail('non-empty stack'); - }) - .seq(function () { - clearTimeout(to); - }) - ; -}; - -exports.ok = function () { - var to = setTimeout(function () { - assert.fail('seq never fired'); - }, 500); - - function moo1 (cb) { cb(3) } - function moo2 (cb) { cb(4) } - - Seq() - .par(function () { moo1(this.ok) }) - .par(function () { moo2(this.ok) }) - .seq(function (x, y) { - clearTimeout(to); - assert.eql(x, 3); - assert.eql(y, 4); - }) - ; -}; - -exports.nextOk = function () { - var to = setTimeout(function () { - assert.fail('seq never fired'); - }, 500); - - function moo1 (cb) { cb(3) } - function moo2 (cb) { cb(4) } - - Seq() - .par_(function (next) { moo1(next.ok) }) - .par_(function (next) { moo2(next.ok) }) - .seq_(function (next, x, y) { - assert.eql(x, 3); - assert.eql(y, 4); - next.ok([ 1, 2, 3 ]) - }) - .flatten() - .parMap_(function (next, x) { - next.ok(x * 100) - }) - .seq_(function (next) { - clearTimeout(to); - assert.deepEqual(next.stack, [ 100, 200, 300 ]); - }) - ; -}; - -exports.regressionTestForAccidentalDeepTraversalOfTheContext = function () { - // Create a single-item stack with a bunch of references to other objects: - var stack = [{}]; - for (var i = 0 ; i < 10000 ; i += 1) { - stack[0][i] = stack[0]; - } - - var startTime = new Date(), - numCalled = 0, - to = setTimeout(function () { - assert.fail('never got to the end of the chain'); - }, 1000); - - Seq(stack) - .parEach(function (item) { - numCalled += 1; - this(); - }) - .seq(function () { - clearTimeout(to); - assert.eql(numCalled, 1); - assert.ok((new Date().getTime() - startTime) < 1000, 'if this test takes longer than a second, the bug must have been reintroduced'); - }); -}; diff --git a/node_modules/findit/node_modules/seq/test/seq_.js b/node_modules/findit/node_modules/seq/test/seq_.js deleted file mode 100644 index 369cc86..0000000 --- a/node_modules/findit/node_modules/seq/test/seq_.js +++ /dev/null @@ -1,149 +0,0 @@ -var Seq = require('seq'); -var assert = require('assert'); - -exports.seq_ = function () { - var to = setTimeout(function () { - assert.fail('never got to the end of the chain'); - }, 5000); - - Seq(['xxx']) - .seq_('pow', function (next, x) { - assert.eql(next, this); - assert.eql(x, 'xxx'); - next(null, 'yyy'); - }) - .seq(function (y) { - clearTimeout(to); - assert.eql(y, 'yyy'); - assert.eql(this.vars.pow, 'yyy'); - }) - ; -}; - -exports.par_ = function () { - var to = setTimeout(function () { - assert.fail('never got to the end of the chain'); - }, 5000); - - Seq() - .par_(function (next) { - assert.eql(next, this); - next(null, 111); - }) - .par_(function (next) { - assert.eql(next, this); - next(null, 222); - }) - .seq(function (x, y) { - clearTimeout(to); - assert.eql(x, 111); - assert.eql(y, 222); - }) - ; -}; - -exports.forEach_ = function () { - var to = setTimeout(function () { - assert.fail('never got to the end of the chain'); - }, 5000); - - var acc = []; - Seq([7,8,9]) - .forEach_(function (next, x) { - assert.eql(next, this); - acc.push(x); - }) - .seq(function () { - clearTimeout(to); - assert.eql(acc, [ 7, 8, 9 ]); - }) - ; -}; - -exports.seqEach_ = function () { - var to = setTimeout(function () { - assert.fail('never got to the end of the chain'); - }, 5000); - - var acc = []; - Seq([7,8,9]) - .seqEach_(function (next, x) { - assert.eql(next, this); - acc.push(x); - setTimeout(function () { - next(null, x); - }, Math.random() * 10); - }) - .seq(function () { - clearTimeout(to); - assert.eql(acc, [ 7, 8, 9 ]); - assert.eql(this.stack, [ 7, 8, 9 ]); - }) - ; -}; - -exports.parEach_ = function () { - var to = setTimeout(function () { - assert.fail('never got to the end of the chain'); - }, 5000); - - var acc = []; - Seq([7,8,9]) - .parEach_(function (next, x) { - assert.eql(next, this); - acc.push(x); - setTimeout(function () { - next(null, x); - }, Math.random() * 10); - }) - .seq(function () { - clearTimeout(to); - assert.eql(acc, [ 7, 8, 9 ]); - assert.eql(this.stack, [ 7, 8, 9 ]); - }) - ; -}; - -exports.seqMap_ = function () { - var to = setTimeout(function () { - assert.fail('never got to the end of the chain'); - }, 5000); - - var acc = []; - Seq([7,8,9]) - .seqMap_(function (next, x) { - assert.eql(next, this); - acc.push(x); - setTimeout(function () { - next(null, x * 10); - }, Math.random() * 10); - }) - .seq(function () { - clearTimeout(to); - assert.eql(acc, [ 7, 8, 9 ]); - assert.eql(this.stack, [ 70, 80, 90 ]); - }) - ; -}; - -exports.parMap_ = function () { - var to = setTimeout(function () { - assert.fail('never got to the end of the chain'); - }, 5000); - - var acc = []; - Seq([7,8,9]) - .parMap_(function (next, x) { - assert.eql(next, this); - acc.push(x); - setTimeout(function () { - next(null, x * 10); - }, Math.random() * 10); - }) - .seq(function () { - clearTimeout(to); - assert.eql(acc, [ 7, 8, 9 ]); - assert.eql(this.stack, [ 70, 80, 90 ]); - }) - ; -}; diff --git a/node_modules/findit/package.json b/node_modules/findit/package.json deleted file mode 100644 index d0c2ec9..0000000 --- a/node_modules/findit/package.json +++ /dev/null @@ -1,31 +0,0 @@ -{ - "name" : "findit", - "version" : "0.1.1", - "description" : "Walk a directory tree.", - "main" : "./index.js", - "dependencies" : { - "seq" : ">=0.1.7" - }, - "devDependencies" : { - "hashish" : ">=0.0.2 <0.1", - "expresso" : "0.7.x" - }, - "repository" : { - "type" : "git", - "url" : "http://github.com/substack/node-findit.git" - }, - "keywords" : [ - "find", - "walk", - "directory", - "recursive", - "tree" - ], - "author" : { - "name" : "James Halliday", - "email" : "mail@substack.net", - "url" : "http://substack.net" - }, - "license" : "MIT/X11", - "engine" : ["node >=0.2.0"] -} diff --git a/node_modules/findit/test/cb.js b/node_modules/findit/test/cb.js deleted file mode 100644 index dd535e7..0000000 --- a/node_modules/findit/test/cb.js +++ /dev/null @@ -1,24 +0,0 @@ -var assert = require('assert'); -var path = require('path'); -var find = require('../'); - -exports.cbSync = function () { - var files = []; - var dirs = []; - find.sync(__dirname + '/foo', function (file, stat) { - if (stat.isDirectory()) dirs.push(file) - else files.push(file) - }); - - function equal (xs, ys) { - assert.deepEqual( - xs.sort().map(function (x) { - return path.relative(__dirname + '/foo', x) - }), - ys.sort() - ); - } - - equal(dirs, [ 'a', 'a/b', 'a/b/c' ]); - equal(files, [ 'x', 'a/y', 'a/b/z', 'a/b/c/w' ]); -}; diff --git a/node_modules/findit/test/cycle.js b/node_modules/findit/test/cycle.js deleted file mode 100644 index 3296387..0000000 --- a/node_modules/findit/test/cycle.js +++ /dev/null @@ -1,41 +0,0 @@ -var assert = require('assert'); -var findit = require('../'); -var Hash = require('hashish'); - -exports.cycle = function () { - var find = findit.find(__dirname + '/cycle'); - var found = { directory : [], file : [], path : [] }; - - find.on('directory', function (dir) { - found.directory.push(dir); - }); - - find.on('file', function (file) { - found.file.push(file); - }); - - find.on('path', function (file) { - found.path.push(file); - }); - - var to = setTimeout(function () { - assert.fail('never ended'); - }, 5000); - - find.on('end', function () { - clearTimeout(to); - var dirs = Hash.map({ - directory : [ 'meep', 'meep/moop' ], - file : [], - path : [ 'meep', 'meep/moop' ] - }, function (x) { - return x.map(function (dir) { - return __dirname + '/cycle/' + dir - }) - }); - - assert.deepEqual(dirs.directory, found.directory); - assert.deepEqual(dirs.file, found.file); - assert.deepEqual(dirs.path, found.path); - }); -}; diff --git a/node_modules/findit/test/foo.js b/node_modules/findit/test/foo.js deleted file mode 100644 index ba0c1cb..0000000 --- a/node_modules/findit/test/foo.js +++ /dev/null @@ -1,79 +0,0 @@ -var assert = require('assert'); -var find = require('../').find; -var findSync = require('../').findSync; - -exports.foo = function () { - var to = setTimeout(function () { - assert.fail('Never caught "end"'); - }, 5000); - - var ps = {}; - var finder = find(__dirname + '/foo', function (file, stat) { - ps[file] = stat.isDirectory(); - }); - - var paths = [] - finder.on('path', function (p) { - paths.push(p); - }); - - var dirs = [] - finder.on('directory', function (dir) { - dirs.push(dir); - }); - - var files = [] - finder.on('file', function (file) { - files.push(file); - }); - - finder.on('end', function () { - clearTimeout(to); - var ref = { - 'a' : true, - 'a/b' : true, - 'a/b/c' : true, - 'x' : false, - 'a/y' : false, - 'a/b/z' : false, - 'a/b/c/w' : false, - }; - - assert.eql(Object.keys(ref).length, Object.keys(ps).length); - var count = { dirs : 0, files : 0, paths : 0 }; - - Object.keys(ref).forEach(function (key) { - var file = __dirname + '/foo/' + key; - assert.eql(ref[key], ps[file]); - if (ref[key]) { - assert.ok(dirs.indexOf(file) >= 0); - count.dirs ++; - } - else { - assert.ok(files.indexOf(file) >= 0); - count.files ++; - } - }); - - assert.eql(count.dirs, dirs.length); - assert.eql(count.files, files.length); - assert.eql(paths.sort(), Object.keys(ps).sort()); - }); -}; - -exports.fooSync = function () { - assert.eql( - findSync(__dirname + '/foo') - .reduce(function (files, file) { - files[file] = true; - return files; - }, {}), - [ 'a', 'a/b', 'a/b/c', 'x', 'a/y', 'a/b/z', 'a/b/c/w' ] - .reduce(function (files, file) { - files[__dirname + '/foo/' + file] = true; - return files; - }, {}) - ); - - assert.eql(findSync(__dirname + '/foo/x'), [ __dirname + '/foo/x' ]); -}; diff --git a/node_modules/findit/test/module.js b/node_modules/findit/test/module.js deleted file mode 100644 index 046274f..0000000 --- a/node_modules/findit/test/module.js +++ /dev/null @@ -1,29 +0,0 @@ -var assert = require('assert'); -var find = require('../'); - -exports.module = function () { - assert.eql(find.findSync, find.find.sync); - assert.eql(find, find.find); -}; - -exports.file = function () { - var to = setTimeout(function () { - assert.fail('never ended'); - }, 5000); - - var finder = find(__filename); - var files = []; - finder.on('file', function (file) { - assert.equal(file, __filename); - files.push(file); - }); - - finder.on('directory', function (dir) { - assert.fail(dir); - }); - - finder.on('end', function () { - clearTimeout(to); - assert.deepEqual(files, [ __filename ]); - }); -}; diff --git a/node_modules/mkdirp/.gitignore b/node_modules/mkdirp/.gitignore deleted file mode 100644 index 9303c34..0000000 --- a/node_modules/mkdirp/.gitignore +++ /dev/null @@ -1,2 +0,0 @@ -node_modules/ -npm-debug.log \ No newline at end of file diff --git a/node_modules/mkdirp/.gitignore.orig b/node_modules/mkdirp/.gitignore.orig deleted file mode 100644 index 9303c34..0000000 --- a/node_modules/mkdirp/.gitignore.orig +++ /dev/null @@ -1,2 +0,0 @@ -node_modules/ -npm-debug.log \ No newline at end of file diff --git a/node_modules/mkdirp/.gitignore.rej b/node_modules/mkdirp/.gitignore.rej deleted file mode 100644 index 69244ff..0000000 --- a/node_modules/mkdirp/.gitignore.rej +++ /dev/null @@ -1,5 +0,0 @@ ---- /dev/null -+++ .gitignore -@@ -0,0 +1,2 @@ -+node_modules/ -+npm-debug.log \ No newline at end of file diff --git a/node_modules/mkdirp/LICENSE b/node_modules/mkdirp/LICENSE deleted file mode 100644 index 432d1ae..0000000 --- a/node_modules/mkdirp/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -Copyright 2010 James Halliday (mail@substack.net) - -This project is free software released under the MIT/X11 license: - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. diff --git a/node_modules/mkdirp/README.markdown b/node_modules/mkdirp/README.markdown deleted file mode 100644 index c7cec72..0000000 --- a/node_modules/mkdirp/README.markdown +++ /dev/null @@ -1,50 +0,0 @@ -mkdirp -====== - -Like `mkdir -p`, but in node.js! - -example -======= - -pow.js ------- - var mkdirp = require('mkdirp'); - - mkdirp('/tmp/foo/bar/baz', 0755, function (err) { - if (err) console.error(err) - else console.log('pow!') - }); - -Output - pow! - -And now /tmp/foo/bar/baz exists, huzzah! - -methods -======= - -var mkdirp = require('mkdirp'); - -mkdirp(dir, mode, cb) ---------------------- - -Create a new directory and any necessary subdirectories at `dir` with octal -permission string `mode`. - -mkdirp.sync(dir, mode) ----------------------- - -Synchronously create a new directory and any necessary subdirectories at `dir` -with octal permission string `mode`. - -install -======= - -With [npm](http://npmjs.org) do: - - npm install mkdirp - -license -======= - -MIT/X11 diff --git a/node_modules/mkdirp/examples/pow.js b/node_modules/mkdirp/examples/pow.js deleted file mode 100644 index 7741462..0000000 --- a/node_modules/mkdirp/examples/pow.js +++ /dev/null @@ -1,6 +0,0 @@ -var mkdirp = require('mkdirp'); - -mkdirp('/tmp/foo/bar/baz', 0755, function (err) { - if (err) console.error(err) - else console.log('pow!') -}); diff --git a/node_modules/mkdirp/examples/pow.js.orig b/node_modules/mkdirp/examples/pow.js.orig deleted file mode 100644 index 7741462..0000000 --- a/node_modules/mkdirp/examples/pow.js.orig +++ /dev/null @@ -1,6 +0,0 @@ -var mkdirp = require('mkdirp'); - -mkdirp('/tmp/foo/bar/baz', 0755, function (err) { - if (err) console.error(err) - else console.log('pow!') -}); diff --git a/node_modules/mkdirp/examples/pow.js.rej b/node_modules/mkdirp/examples/pow.js.rej deleted file mode 100644 index 81e7f43..0000000 --- a/node_modules/mkdirp/examples/pow.js.rej +++ /dev/null @@ -1,19 +0,0 @@ ---- examples/pow.js -+++ examples/pow.js -@@ -1,6 +1,15 @@ --var mkdirp = require('mkdirp').mkdirp; -+var mkdirp = require('../').mkdirp, -+ mkdirpSync = require('../').mkdirpSync; - - mkdirp('/tmp/foo/bar/baz', 0755, function (err) { - if (err) console.error(err) - else console.log('pow!') - }); -+ -+try { -+ mkdirpSync('/tmp/bar/foo/baz', 0755); -+ console.log('double pow!'); -+} -+catch (ex) { -+ console.log(ex); -+} \ No newline at end of file diff --git a/node_modules/mkdirp/index.js b/node_modules/mkdirp/index.js deleted file mode 100644 index f6e4f2b..0000000 --- a/node_modules/mkdirp/index.js +++ /dev/null @@ -1,85 +0,0 @@ -var path = require('path'); -var fs = require('fs'); - -module.exports = mkdirP.mkdirp = mkdirP.mkdirP = mkdirP; - -function mkdirP (p, mode, f) { - if (mode === undefined) throw new Error('mode not specified'); - - var cb = f || function () {}; - if (typeof mode === 'string') mode = parseInt(mode, 8); - p = path.resolve(p); - - fs.mkdir(p, mode, function (er) { - if (!er) return cb(); - switch (er.code) { - case 'ENOENT': - mkdirP(path.dirname(p), mode, function (er) { - if (er) cb(er); - else mkdirP(p, mode, cb); - }); - break; - - case 'EEXIST': - fs.stat(p, function (er2, stat) { - // if the stat fails, then that's super weird. - // let the original EEXIST be the failure reason. - if (er2 || !stat.isDirectory()) cb(er) - else if ((stat.mode & 0777) !== mode) fs.chmod(p, mode, cb); - else cb(); - }); - break; - - default: - cb(er); - break; - } - }); -} - -mkdirP.sync = function sync (p, mode) { - if (mode === undefined) throw new Error('mode not specified'); - - if (typeof mode === 'string') mode = parseInt(mode, 8); - p = path.resolve(p); - - try { - fs.mkdirSync(p, mode) - } - catch (err0) { - switch (err0.code) { - case 'ENOENT' : - var err1 = sync(path.dirname(p), mode) - if (err1) throw err1; - else return sync(p, mode); - break; - - case 'EEXIST' : - var stat; - try { - stat = fs.statSync(p); - } - catch (err1) { - throw err0 - } - if (!stat.isDirectory()) throw err0; - else if ((stat.mode & 0777) !== mode) { - try { - fs.chmodSync(p, mode); - } - catch (err) { - if (err && err.code === 'EPERM') return null; - else throw err; - } - return null; - } - else return null; - break; - default : - throw err0 - break; - } - } - - return null; -}; diff --git a/node_modules/mkdirp/package.json b/node_modules/mkdirp/package.json deleted file mode 100644 index a783046..0000000 --- a/node_modules/mkdirp/package.json +++ /dev/null @@ -1,23 +0,0 @@ -{ - "name" : "mkdirp", - "description" : "Recursively mkdir, like `mkdir -p`", - "version" : "0.2.1", - "author" : "James Halliday (http://substack.net)", - "main" : "./index", - "keywords" : [ - "mkdir", - "directory" - ], - "repository" : { - "type" : "git", - "url" : "http://github.com/substack/node-mkdirp.git" - }, - "scripts" : { - "test" : "tap test/*.js" - }, - "devDependencies" : { - "tap" : "0.0.x" - }, - "license" : "MIT/X11", - "engines": { "node": "*" } -} diff --git a/node_modules/mkdirp/test/chmod.js b/node_modules/mkdirp/test/chmod.js deleted file mode 100644 index 0609694..0000000 --- a/node_modules/mkdirp/test/chmod.js +++ /dev/null @@ -1,39 +0,0 @@ -var mkdirp = require('../').mkdirp; -var path = require('path'); -var fs = require('fs'); -var test = require('tap').test; - -var ps = [ '', 'tmp' ]; - -for (var i = 0; i < 25; i++) { - var dir = Math.floor(Math.random() * Math.pow(16,4)).toString(16); - ps.push(dir); -} - -var file = ps.join('/'); - -test('chmod-pre', function (t) { - var mode = 0744 - mkdirp(file, mode, function (er) { - t.ifError(er, 'should not error'); - fs.stat(file, function (er, stat) { - t.ifError(er, 'should exist'); - t.ok(stat && stat.isDirectory(), 'should be directory'); - t.equal(stat && stat.mode & 0777, mode, 'should be 0744'); - t.end(); - }); - }); -}); - -test('chmod', function (t) { - var mode = 0755 - mkdirp(file, mode, function (er) { - t.ifError(er, 'should not error'); - fs.stat(file, function (er, stat) { - t.ifError(er, 'should exist'); - t.ok(stat && stat.isDirectory(), 'should be directory'); - t.equal(stat && stat.mode & 0777, mode, 'should be 0755'); - t.end(); - }); - }); -}); diff --git a/node_modules/mkdirp/test/clobber.js b/node_modules/mkdirp/test/clobber.js deleted file mode 100644 index 0eb7099..0000000 --- a/node_modules/mkdirp/test/clobber.js +++ /dev/null @@ -1,37 +0,0 @@ -var mkdirp = require('../').mkdirp; -var path = require('path'); -var fs = require('fs'); -var test = require('tap').test; - -var ps = [ '', 'tmp' ]; - -for (var i = 0; i < 25; i++) { - var dir = Math.floor(Math.random() * Math.pow(16,4)).toString(16); - ps.push(dir); -} - -var file = ps.join('/'); - -// a file in the way -var itw = ps.slice(0, 3).join('/'); - - -test('clobber-pre', function (t) { - console.error("about to write to "+itw) - fs.writeFileSync(itw, 'I AM IN THE WAY, THE TRUTH, AND THE LIGHT.'); - - fs.stat(itw, function (er, stat) { - t.ifError(er) - t.ok(stat && stat.isFile(), 'should be file') - t.end() - }) -}) - -test('clobber', function (t) { - t.plan(2); - mkdirp(file, 0755, function (err) { - t.ok(err); - t.equal(err.code, 'ENOTDIR'); - t.end(); - }); -}); diff --git a/node_modules/mkdirp/test/mkdirp.js b/node_modules/mkdirp/test/mkdirp.js deleted file mode 100644 index b07cd70..0000000 --- a/node_modules/mkdirp/test/mkdirp.js +++ /dev/null @@ -1,28 +0,0 @@ -var mkdirp = require('../'); -var path = require('path'); -var fs = require('fs'); -var test = require('tap').test; - -test('woo', function (t) { - t.plan(2); - var x = Math.floor(Math.random() * Math.pow(16,4)).toString(16); - var y = Math.floor(Math.random() * Math.pow(16,4)).toString(16); - var z = Math.floor(Math.random() * Math.pow(16,4)).toString(16); - - var file = '/tmp/' + [x,y,z].join('/'); - - mkdirp(file, 0755, function (err) { - if (err) t.fail(err); - else path.exists(file, function (ex) { - if (!ex) t.fail('file not created') - else fs.stat(file, function (err, stat) { - if (err) t.fail(err) - else { - t.equal(stat.mode & 0777, 0755); - t.ok(stat.isDirectory(), 'target not a directory'); - t.end(); - } - }) - }) - }); -}); diff --git a/node_modules/mkdirp/test/perm.js b/node_modules/mkdirp/test/perm.js deleted file mode 100644 index 23a7abb..0000000 --- a/node_modules/mkdirp/test/perm.js +++ /dev/null @@ -1,32 +0,0 @@ -var mkdirp = require('../'); -var path = require('path'); -var fs = require('fs'); -var test = require('tap').test; - -test('async perm', function (t) { - t.plan(2); - var file = '/tmp/' + (Math.random() * (1<<30)).toString(16); - - mkdirp(file, 0755, function (err) { - if (err) t.fail(err); - else path.exists(file, function (ex) { - if (!ex) t.fail('file not created') - else fs.stat(file, function (err, stat) { - if (err) t.fail(err) - else { - t.equal(stat.mode & 0777, 0755); - t.ok(stat.isDirectory(), 'target not a directory'); - t.end(); - } - }) - }) - }); -}); - -test('async root perm', function (t) { - mkdirp('/tmp', 0755, function (err) { - if (err) t.fail(err); - t.end(); - }); - t.end(); -}); diff --git a/node_modules/mkdirp/test/perm_sync.js b/node_modules/mkdirp/test/perm_sync.js deleted file mode 100644 index f685f60..0000000 --- a/node_modules/mkdirp/test/perm_sync.js +++ /dev/null @@ -1,39 +0,0 @@ -var mkdirp = require('../'); -var path = require('path'); -var fs = require('fs'); -var test = require('tap').test; - -test('sync perm', function (t) { - t.plan(2); - var file = '/tmp/' + (Math.random() * (1<<30)).toString(16) + '.json'; - - mkdirp.sync(file, 0755); - path.exists(file, function (ex) { - if (!ex) t.fail('file not created') - else fs.stat(file, function (err, stat) { - if (err) t.fail(err) - else { - t.equal(stat.mode & 0777, 0755); - t.ok(stat.isDirectory(), 'target not a directory'); - t.end(); - } - }) - }); -}); - -test('sync root perm', function (t) { - t.plan(1); - - var file = '/tmp'; - mkdirp.sync(file, 0755); - path.exists(file, function (ex) { - if (!ex) t.fail('file not created') - else fs.stat(file, function (err, stat) { - if (err) t.fail(err) - else { - t.ok(stat.isDirectory(), 'target not a directory'); - t.end(); - } - }) - }); -}); diff --git a/node_modules/mkdirp/test/race.js b/node_modules/mkdirp/test/race.js deleted file mode 100644 index 96a0447..0000000 --- a/node_modules/mkdirp/test/race.js +++ /dev/null @@ -1,41 +0,0 @@ -var mkdirp = require('../').mkdirp; -var path = require('path'); -var fs = require('fs'); -var test = require('tap').test; - -test('race', function (t) { - t.plan(4); - var ps = [ '', 'tmp' ]; - - for (var i = 0; i < 25; i++) { - var dir = Math.floor(Math.random() * Math.pow(16,4)).toString(16); - ps.push(dir); - } - var file = ps.join('/'); - - var res = 2; - mk(file, function () { - if (--res === 0) t.end(); - }); - - mk(file, function () { - if (--res === 0) t.end(); - }); - - function mk (file, cb) { - mkdirp(file, 0755, function (err) { - if (err) t.fail(err); - else path.exists(file, function (ex) { - if (!ex) t.fail('file not created') - else fs.stat(file, function (err, stat) { - if (err) t.fail(err) - else { - t.equal(stat.mode & 0777, 0755); - t.ok(stat.isDirectory(), 'target not a directory'); - if (cb) cb(); - } - }) - }) - }); - } -}); diff --git a/node_modules/mkdirp/test/rel.js b/node_modules/mkdirp/test/rel.js deleted file mode 100644 index 7985824..0000000 --- a/node_modules/mkdirp/test/rel.js +++ /dev/null @@ -1,32 +0,0 @@ -var mkdirp = require('../'); -var path = require('path'); -var fs = require('fs'); -var test = require('tap').test; - -test('rel', function (t) { - t.plan(2); - var x = Math.floor(Math.random() * Math.pow(16,4)).toString(16); - var y = Math.floor(Math.random() * Math.pow(16,4)).toString(16); - var z = Math.floor(Math.random() * Math.pow(16,4)).toString(16); - - var cwd = process.cwd(); - process.chdir('/tmp'); - - var file = [x,y,z].join('/'); - - mkdirp(file, 0755, function (err) { - if (err) t.fail(err); - else path.exists(file, function (ex) { - if (!ex) t.fail('file not created') - else fs.stat(file, function (err, stat) { - if (err) t.fail(err) - else { - process.chdir(cwd); - t.equal(stat.mode & 0777, 0755); - t.ok(stat.isDirectory(), 'target not a directory'); - t.end(); - } - }) - }) - }); -}); diff --git a/node_modules/mkdirp/test/sync.js b/node_modules/mkdirp/test/sync.js deleted file mode 100644 index e0e389d..0000000 --- a/node_modules/mkdirp/test/sync.js +++ /dev/null @@ -1,27 +0,0 @@ -var mkdirp = require('../'); -var path = require('path'); -var fs = require('fs'); -var test = require('tap').test; - -test('sync', function (t) { - t.plan(2); - var x = Math.floor(Math.random() * Math.pow(16,4)).toString(16); - var y = Math.floor(Math.random() * Math.pow(16,4)).toString(16); - var z = Math.floor(Math.random() * Math.pow(16,4)).toString(16); - - var file = '/tmp/' + [x,y,z].join('/'); - - var err = mkdirp.sync(file, 0755); - if (err) t.fail(err); - else path.exists(file, function (ex) { - if (!ex) t.fail('file not created') - else fs.stat(file, function (err, stat) { - if (err) t.fail(err) - else { - t.equal(stat.mode & 0777, 0755); - t.ok(stat.isDirectory(), 'target not a directory'); - t.end(); - } - }) - }) -}); diff --git a/node_modules/optimist/.gitignore b/node_modules/optimist/.gitignore deleted file mode 100644 index 7ff5a9e..0000000 --- a/node_modules/optimist/.gitignore +++ /dev/null @@ -1,2 +0,0 @@ -node_modules/ -node_modules/* \ No newline at end of file diff --git a/node_modules/optimist/.npmignore b/node_modules/optimist/.npmignore deleted file mode 100644 index bfdb82c..0000000 --- a/node_modules/optimist/.npmignore +++ /dev/null @@ -1,4 +0,0 @@ -lib-cov/* -*.swp -*.swo -node_modules diff --git a/node_modules/optimist/README.markdown b/node_modules/optimist/README.markdown index deb493c..ad9d3fd 100644 --- a/node_modules/optimist/README.markdown +++ b/node_modules/optimist/README.markdown @@ -7,6 +7,8 @@ and -whistlz of program usage but think optstrings are a waste of time. With optimist, option parsing doesn't have to suck (as much). +[![build status](https://secure.travis-ci.org/substack/node-optimist.png)](http://travis-ci.org/substack/node-optimist) + examples ======== @@ -452,6 +454,17 @@ all the values in order. '$0': 'node ./examples/reflect.js', x: [ 5, 8, 0 ] } +dot notation +------------ + +When you use dots (`.`s) in argument names, an implicit object path is assumed. +This lets you organize arguments into nested objects. + + $ node examples/reflect.js --foo.bar.baz=33 --foo.quux=5 + { _: [], + '$0': 'node ./examples/reflect.js', + foo: { bar: { baz: 33 }, quux: 5 } } + installation ============ diff --git a/node_modules/optimist/examples/bool.js b/node_modules/optimist/examples/bool.js deleted file mode 100644 index a998fb7..0000000 --- a/node_modules/optimist/examples/bool.js +++ /dev/null @@ -1,10 +0,0 @@ -#!/usr/bin/env node -var util = require('util'); -var argv = require('optimist').argv; - -if (argv.s) { - util.print(argv.fr ? 'Le chat dit: ' : 'The cat says: '); -} -console.log( - (argv.fr ? 'miaou' : 'meow') + (argv.p ? '.' : '') -); diff --git a/node_modules/optimist/examples/boolean_double.js b/node_modules/optimist/examples/boolean_double.js deleted file mode 100644 index a35a7e6..0000000 --- a/node_modules/optimist/examples/boolean_double.js +++ /dev/null @@ -1,7 +0,0 @@ -#!/usr/bin/env node -var argv = require('optimist') - .boolean(['x','y','z']) - .argv -; -console.dir([ argv.x, argv.y, argv.z ]); -console.dir(argv._); diff --git a/node_modules/optimist/examples/boolean_single.js b/node_modules/optimist/examples/boolean_single.js deleted file mode 100644 index 017bb68..0000000 --- a/node_modules/optimist/examples/boolean_single.js +++ /dev/null @@ -1,7 +0,0 @@ -#!/usr/bin/env node -var argv = require('optimist') - .boolean('v') - .argv -; -console.dir(argv.v); -console.dir(argv._); diff --git a/node_modules/optimist/examples/default_hash.js b/node_modules/optimist/examples/default_hash.js deleted file mode 100644 index ade7768..0000000 --- a/node_modules/optimist/examples/default_hash.js +++ /dev/null @@ -1,8 +0,0 @@ -#!/usr/bin/env node - -var argv = require('optimist') - .default({ x : 10, y : 10 }) - .argv -; - -console.log(argv.x + argv.y); diff --git a/node_modules/optimist/examples/default_singles.js b/node_modules/optimist/examples/default_singles.js deleted file mode 100644 index d9b1ff4..0000000 --- a/node_modules/optimist/examples/default_singles.js +++ /dev/null @@ -1,7 +0,0 @@ -#!/usr/bin/env node -var argv = require('optimist') - .default('x', 10) - .default('y', 10) - .argv -; -console.log(argv.x + argv.y); diff --git a/node_modules/optimist/examples/divide.js b/node_modules/optimist/examples/divide.js deleted file mode 100644 index 5e2ee82..0000000 --- a/node_modules/optimist/examples/divide.js +++ /dev/null @@ -1,8 +0,0 @@ -#!/usr/bin/env node - -var argv = require('optimist') - .usage('Usage: $0 -x [num] -y [num]') - .demand(['x','y']) - .argv; - -console.log(argv.x / argv.y); diff --git a/node_modules/optimist/examples/line_count.js b/node_modules/optimist/examples/line_count.js deleted file mode 100644 index b5f95bf..0000000 --- a/node_modules/optimist/examples/line_count.js +++ /dev/null @@ -1,20 +0,0 @@ -#!/usr/bin/env node -var argv = require('optimist') - .usage('Count the lines in a file.\nUsage: $0') - .demand('f') - .alias('f', 'file') - .describe('f', 'Load a file') - .argv -; - -var fs = require('fs'); -var s = fs.createReadStream(argv.file); - -var lines = 0; -s.on('data', function (buf) { - lines += buf.toString().match(/\n/g).length; -}); - -s.on('end', function () { - console.log(lines); -}); diff --git a/node_modules/optimist/examples/line_count_options.js b/node_modules/optimist/examples/line_count_options.js deleted file mode 100644 index d9ac709..0000000 --- a/node_modules/optimist/examples/line_count_options.js +++ /dev/null @@ -1,29 +0,0 @@ -#!/usr/bin/env node -var argv = require('optimist') - .usage('Count the lines in a file.\nUsage: $0') - .options({ - file : { - demand : true, - alias : 'f', - description : 'Load a file' - }, - base : { - alias : 'b', - description : 'Numeric base to use for output', - default : 10, - }, - }) - .argv -; - -var fs = require('fs'); -var s = fs.createReadStream(argv.file); - -var lines = 0; -s.on('data', function (buf) { - lines += buf.toString().match(/\n/g).length; -}); - -s.on('end', function () { - console.log(lines.toString(argv.base)); -}); diff --git a/node_modules/optimist/examples/line_count_wrap.js b/node_modules/optimist/examples/line_count_wrap.js deleted file mode 100644 index 4267511..0000000 --- a/node_modules/optimist/examples/line_count_wrap.js +++ /dev/null @@ -1,29 +0,0 @@ -#!/usr/bin/env node -var argv = require('optimist') - .usage('Count the lines in a file.\nUsage: $0') - .wrap(80) - .demand('f') - .alias('f', [ 'file', 'filename' ]) - .describe('f', - "Load a file. It's pretty important." - + " Required even. So you'd better specify it." - ) - .alias('b', 'base') - .describe('b', 'Numeric base to display the number of lines in') - .default('b', 10) - .describe('x', 'Super-secret optional parameter which is secret') - .default('x', '') - .argv -; - -var fs = require('fs'); -var s = fs.createReadStream(argv.file); - -var lines = 0; -s.on('data', function (buf) { - lines += buf.toString().match(/\n/g).length; -}); - -s.on('end', function () { - console.log(lines.toString(argv.base)); -}); diff --git a/node_modules/optimist/examples/nonopt.js b/node_modules/optimist/examples/nonopt.js deleted file mode 100644 index ee633ee..0000000 --- a/node_modules/optimist/examples/nonopt.js +++ /dev/null @@ -1,4 +0,0 @@ -#!/usr/bin/env node -var argv = require('optimist').argv; -console.log('(%d,%d)', argv.x, argv.y); -console.log(argv._); diff --git a/node_modules/optimist/examples/reflect.js b/node_modules/optimist/examples/reflect.js deleted file mode 100644 index 816b3e1..0000000 --- a/node_modules/optimist/examples/reflect.js +++ /dev/null @@ -1,2 +0,0 @@ -#!/usr/bin/env node -console.dir(require('optimist').argv); diff --git a/node_modules/optimist/examples/short.js b/node_modules/optimist/examples/short.js deleted file mode 100644 index 1db0ad0..0000000 --- a/node_modules/optimist/examples/short.js +++ /dev/null @@ -1,3 +0,0 @@ -#!/usr/bin/env node -var argv = require('optimist').argv; -console.log('(%d,%d)', argv.x, argv.y); diff --git a/node_modules/optimist/examples/string.js b/node_modules/optimist/examples/string.js deleted file mode 100644 index a8e5aeb..0000000 --- a/node_modules/optimist/examples/string.js +++ /dev/null @@ -1,11 +0,0 @@ -#!/usr/bin/env node -var argv = require('optimist') - .string('x', 'y') - .argv -; -console.dir([ argv.x, argv.y ]); - -/* Turns off numeric coercion: - ./node string.js -x 000123 -y 9876 - [ '000123', '9876' ] -*/ diff --git a/node_modules/optimist/examples/usage-options.js b/node_modules/optimist/examples/usage-options.js deleted file mode 100644 index b999977..0000000 --- a/node_modules/optimist/examples/usage-options.js +++ /dev/null @@ -1,19 +0,0 @@ -var optimist = require('./../index'); - -var argv = optimist.usage('This is my awesome program', { - 'about': { - description: 'Provide some details about the author of this program', - required: true, - short: 'a', - }, - 'info': { - description: 'Provide some information about the node.js agains!!!!!!', - boolean: true, - short: 'i' - } -}).argv; - -optimist.showHelp(); - -console.log('\n\nInspecting options'); -console.dir(argv); \ No newline at end of file diff --git a/node_modules/optimist/examples/xup.js b/node_modules/optimist/examples/xup.js deleted file mode 100644 index 8f6ecd2..0000000 --- a/node_modules/optimist/examples/xup.js +++ /dev/null @@ -1,10 +0,0 @@ -#!/usr/bin/env node -var argv = require('optimist').argv; - -if (argv.rif - 5 * argv.xup > 7.138) { - console.log('Buy more riffiwobbles'); -} -else { - console.log('Sell the xupptumblers'); -} - diff --git a/node_modules/optimist/index.js b/node_modules/optimist/index.js index 070d642..e69bef9 100644 --- a/node_modules/optimist/index.js +++ b/node_modules/optimist/index.js @@ -168,7 +168,9 @@ function Argv (args, cwd) { else { if (opt.alias) self.alias(key, opt.alias); if (opt.demand) self.demand(key); - if (opt.default) self.default(key, opt.default); + if (typeof opt.default !== 'undefined') { + self.default(key, opt.default); + } if (opt.boolean || opt.type === 'boolean') { self.boolean(key); @@ -311,15 +313,7 @@ function Argv (args, cwd) { var value = typeof val !== 'string' || isNaN(num) ? val : num; if (flags.strings[key]) value = val; - if (key in argv && !flags.bools[key]) { - if (!Array.isArray(argv[key])) { - argv[key] = [ argv[key] ]; - } - argv[key].push(value); - } - else { - argv[key] = value; - } + setKey(argv, key.split('.'), value); (aliases[key] || []).forEach(function (x) { argv[x] = argv[key]; @@ -345,11 +339,12 @@ function Argv (args, cwd) { var key = arg.match(/^--(.+)/)[1]; var next = args[i + 1]; if (next !== undefined && !next.match(/^-/) - && !flags.bools[key]) { + && !flags.bools[key] + && (aliases[key] ? !flags.bools[aliases[key]] : true)) { setArg(key, next); i++; } - else if (flags.bools[key] && /true|false/.test(next)) { + else if (/^(true|false)$/.test(next)) { setArg(key, next === 'true'); i++; } @@ -376,11 +371,12 @@ function Argv (args, cwd) { var key = arg.slice(-1)[0]; if (args[i+1] && !args[i+1].match(/^-/) - && !flags.bools[key]) { + && !flags.bools[key] + && (aliases[key] ? !flags.bools[aliases[key]] : true)) { setArg(key, args[i+1]); i++; } - else if (args[i+1] && flags.bools[key] && /true|false/.test(args[i+1])) { + else if (args[i+1] && /true|false/.test(args[i+1])) { setArg(key, args[i+1] === 'true'); i++; } @@ -398,6 +394,9 @@ function Argv (args, cwd) { Object.keys(defaults).forEach(function (key) { if (!(key in argv)) { argv[key] = defaults[key]; + if (key in aliases) { + argv[aliases[key]] = defaults[key]; + } } }); @@ -455,3 +454,22 @@ function rebase (base, dir) { ).replace(/\/$/,'').replace(/^$/, '.'); return p.match(/^[.\/]/) ? p : './' + p; }; + +function setKey (obj, keys, value) { + var o = obj; + keys.slice(0,-1).forEach(function (key) { + if (o[key] === undefined) o[key] = {}; + o = o[key]; + }); + + var key = keys[keys.length - 1]; + if (o[key] === undefined || typeof o[key] === 'boolean') { + o[key] = value; + } + else if (Array.isArray(o[key])) { + o[key].push(value); + } + else { + o[key] = [ o[key], value ]; + } +} diff --git a/node_modules/optimist/package.json b/node_modules/optimist/package.json index 2b5c8c9..7d09ace 100644 --- a/node_modules/optimist/package.json +++ b/node_modules/optimist/package.json @@ -1,43 +1,47 @@ { - "name" : "optimist", - "version" : "0.2.8", - "description" : "Light-weight option parsing with an argv hash. No optstrings attached.", - "main" : "./index.js", - "directories" : { - "lib" : ".", - "test" : "test", - "example" : "examples" - }, - "dependencies" : { - "wordwrap" : ">=0.0.1 <0.1.0" - }, - "devDependencies" : { - "hashish": "0.0.x", - "expresso" : "0.7.x" - }, - "scripts" : { - "test" : "expresso" - }, - "repository" : { - "type" : "git", - "url" : "http://github.com/substack/node-optimist.git" - }, - "keywords" : [ - "argument", - "args", - "option", - "parser", - "parsing", - "cli", - "command" - ], - "author" : { - "name" : "James Halliday", - "email" : "mail@substack.net", - "url" : "http://substack.net" - }, - "license" : "MIT/X11", - "engine" : { - "node" : ">=0.4" - } + "name": "optimist", + "version": "0.3.5", + "description": "Light-weight option parsing with an argv hash. No optstrings attached.", + "main": "./index.js", + "directories": { + "lib": ".", + "test": "test", + "example": "example" + }, + "dependencies": { + "wordwrap": "~0.0.2" + }, + "devDependencies": { + "hashish": "~0.0.4", + "tap": "~0.2.4" + }, + "scripts": { + "test": "tap ./test/*.js" + }, + "repository": { + "type": "git", + "url": "http://github.com/substack/node-optimist.git" + }, + "keywords": [ + "argument", + "args", + "option", + "parser", + "parsing", + "cli", + "command" + ], + "author": { + "name": "James Halliday", + "email": "mail@substack.net", + "url": "http://substack.net" + }, + "license": "MIT/X11", + "engine": { + "node": ">=0.4" + }, + "readme": "optimist\n========\n\nOptimist is a node.js library for option parsing for people who hate option\nparsing. More specifically, this module is for people who like all the --bells\nand -whistlz of program usage but think optstrings are a waste of time.\n\nWith optimist, option parsing doesn't have to suck (as much).\n\n[![build status](https://secure.travis-ci.org/substack/node-optimist.png)](http://travis-ci.org/substack/node-optimist)\n\nexamples\n========\n\nWith Optimist, the options are just a hash! No optstrings attached.\n-------------------------------------------------------------------\n\nxup.js:\n\n````javascript\n#!/usr/bin/env node\nvar argv = require('optimist').argv;\n\nif (argv.rif - 5 * argv.xup > 7.138) {\n console.log('Buy more riffiwobbles');\n}\nelse {\n console.log('Sell the xupptumblers');\n}\n````\n\n***\n\n $ ./xup.js --rif=55 --xup=9.52\n Buy more riffiwobbles\n \n $ ./xup.js --rif 12 --xup 8.1\n Sell the xupptumblers\n\n![This one's optimistic.](http://substack.net/images/optimistic.png)\n\nBut wait! There's more! You can do short options:\n-------------------------------------------------\n \nshort.js:\n\n````javascript\n#!/usr/bin/env node\nvar argv = require('optimist').argv;\nconsole.log('(%d,%d)', argv.x, argv.y);\n````\n\n***\n\n $ ./short.js -x 10 -y 21\n (10,21)\n\nAnd booleans, both long and short (and grouped):\n----------------------------------\n\nbool.js:\n\n````javascript\n#!/usr/bin/env node\nvar util = require('util');\nvar argv = require('optimist').argv;\n\nif (argv.s) {\n util.print(argv.fr ? 'Le chat dit: ' : 'The cat says: ');\n}\nconsole.log(\n (argv.fr ? 'miaou' : 'meow') + (argv.p ? '.' : '')\n);\n````\n\n***\n\n $ ./bool.js -s\n The cat says: meow\n \n $ ./bool.js -sp\n The cat says: meow.\n\n $ ./bool.js -sp --fr\n Le chat dit: miaou.\n\nAnd non-hypenated options too! Just use `argv._`!\n-------------------------------------------------\n \nnonopt.js:\n\n````javascript\n#!/usr/bin/env node\nvar argv = require('optimist').argv;\nconsole.log('(%d,%d)', argv.x, argv.y);\nconsole.log(argv._);\n````\n\n***\n\n $ ./nonopt.js -x 6.82 -y 3.35 moo\n (6.82,3.35)\n [ 'moo' ]\n \n $ ./nonopt.js foo -x 0.54 bar -y 1.12 baz\n (0.54,1.12)\n [ 'foo', 'bar', 'baz' ]\n\nPlus, Optimist comes with .usage() and .demand()!\n-------------------------------------------------\n\ndivide.js:\n\n````javascript\n#!/usr/bin/env node\nvar argv = require('optimist')\n .usage('Usage: $0 -x [num] -y [num]')\n .demand(['x','y'])\n .argv;\n\nconsole.log(argv.x / argv.y);\n````\n\n***\n \n $ ./divide.js -x 55 -y 11\n 5\n \n $ node ./divide.js -x 4.91 -z 2.51\n Usage: node ./divide.js -x [num] -y [num]\n\n Options:\n -x [required]\n -y [required]\n\n Missing required arguments: y\n\nEVEN MORE HOLY COW\n------------------\n\ndefault_singles.js:\n\n````javascript\n#!/usr/bin/env node\nvar argv = require('optimist')\n .default('x', 10)\n .default('y', 10)\n .argv\n;\nconsole.log(argv.x + argv.y);\n````\n\n***\n\n $ ./default_singles.js -x 5\n 15\n\ndefault_hash.js:\n\n````javascript\n#!/usr/bin/env node\nvar argv = require('optimist')\n .default({ x : 10, y : 10 })\n .argv\n;\nconsole.log(argv.x + argv.y);\n````\n\n***\n\n $ ./default_hash.js -y 7\n 17\n\nAnd if you really want to get all descriptive about it...\n---------------------------------------------------------\n\nboolean_single.js\n\n````javascript\n#!/usr/bin/env node\nvar argv = require('optimist')\n .boolean('v')\n .argv\n;\nconsole.dir(argv);\n````\n\n***\n\n $ ./boolean_single.js -v foo bar baz\n true\n [ 'bar', 'baz', 'foo' ]\n\nboolean_double.js\n\n````javascript\n#!/usr/bin/env node\nvar argv = require('optimist')\n .boolean(['x','y','z'])\n .argv\n;\nconsole.dir([ argv.x, argv.y, argv.z ]);\nconsole.dir(argv._);\n````\n\n***\n\n $ ./boolean_double.js -x -z one two three\n [ true, false, true ]\n [ 'one', 'two', 'three' ]\n\nOptimist is here to help...\n---------------------------\n\nYou can describe parameters for help messages and set aliases. Optimist figures\nout how to format a handy help string automatically.\n\nline_count.js\n\n````javascript\n#!/usr/bin/env node\nvar argv = require('optimist')\n .usage('Count the lines in a file.\\nUsage: $0')\n .demand('f')\n .alias('f', 'file')\n .describe('f', 'Load a file')\n .argv\n;\n\nvar fs = require('fs');\nvar s = fs.createReadStream(argv.file);\n\nvar lines = 0;\ns.on('data', function (buf) {\n lines += buf.toString().match(/\\n/g).length;\n});\n\ns.on('end', function () {\n console.log(lines);\n});\n````\n\n***\n\n $ node line_count.js\n Count the lines in a file.\n Usage: node ./line_count.js\n\n Options:\n -f, --file Load a file [required]\n\n Missing required arguments: f\n\n $ node line_count.js --file line_count.js \n 20\n \n $ node line_count.js -f line_count.js \n 20\n\nmethods\n=======\n\nBy itself,\n\n````javascript\nrequire('optimist').argv\n`````\n\nwill use `process.argv` array to construct the `argv` object.\n\nYou can pass in the `process.argv` yourself:\n\n````javascript\nrequire('optimist')([ '-x', '1', '-y', '2' ]).argv\n````\n\nor use .parse() to do the same thing:\n\n````javascript\nrequire('optimist').parse([ '-x', '1', '-y', '2' ])\n````\n\nThe rest of these methods below come in just before the terminating `.argv`.\n\n.alias(key, alias)\n------------------\n\nSet key names as equivalent such that updates to a key will propagate to aliases\nand vice-versa.\n\nOptionally `.alias()` can take an object that maps keys to aliases.\n\n.default(key, value)\n--------------------\n\nSet `argv[key]` to `value` if no option was specified on `process.argv`.\n\nOptionally `.default()` can take an object that maps keys to default values.\n\n.demand(key)\n------------\n\nIf `key` is a string, show the usage information and exit if `key` wasn't\nspecified in `process.argv`.\n\nIf `key` is a number, demand at least as many non-option arguments, which show\nup in `argv._`.\n\nIf `key` is an Array, demand each element.\n\n.describe(key, desc)\n--------------------\n\nDescribe a `key` for the generated usage information.\n\nOptionally `.describe()` can take an object that maps keys to descriptions.\n\n.options(key, opt)\n------------------\n\nInstead of chaining together `.alias().demand().default()`, you can specify\nkeys in `opt` for each of the chainable methods.\n\nFor example:\n\n````javascript\nvar argv = require('optimist')\n .options('f', {\n alias : 'file',\n default : '/etc/passwd',\n })\n .argv\n;\n````\n\nis the same as\n\n````javascript\nvar argv = require('optimist')\n .alias('f', 'file')\n .default('f', '/etc/passwd')\n .argv\n;\n````\n\nOptionally `.options()` can take an object that maps keys to `opt` parameters.\n\n.usage(message)\n---------------\n\nSet a usage message to show which commands to use. Inside `message`, the string\n`$0` will get interpolated to the current script name or node command for the\npresent script similar to how `$0` works in bash or perl.\n\n.check(fn)\n----------\n\nCheck that certain conditions are met in the provided arguments.\n\nIf `fn` throws or returns `false`, show the thrown error, usage information, and\nexit.\n\n.boolean(key)\n-------------\n\nInterpret `key` as a boolean. If a non-flag option follows `key` in\n`process.argv`, that string won't get set as the value of `key`.\n\nIf `key` never shows up as a flag in `process.arguments`, `argv[key]` will be\n`false`.\n\nIf `key` is an Array, interpret all the elements as booleans.\n\n.string(key)\n------------\n\nTell the parser logic not to interpret `key` as a number or boolean.\nThis can be useful if you need to preserve leading zeros in an input.\n\nIf `key` is an Array, interpret all the elements as strings.\n\n.wrap(columns)\n--------------\n\nFormat usage output to wrap at `columns` many columns.\n\n.help()\n-------\n\nReturn the generated usage string.\n\n.showHelp(fn=console.error)\n---------------------------\n\nPrint the usage data using `fn` for printing.\n\n.parse(args)\n------------\n\nParse `args` instead of `process.argv`. Returns the `argv` object.\n\n.argv\n-----\n\nGet the arguments as a plain old object.\n\nArguments without a corresponding flag show up in the `argv._` array.\n\nThe script name or node command is available at `argv.$0` similarly to how `$0`\nworks in bash or perl.\n\nparsing tricks\n==============\n\nstop parsing\n------------\n\nUse `--` to stop parsing flags and stuff the remainder into `argv._`.\n\n $ node examples/reflect.js -a 1 -b 2 -- -c 3 -d 4\n { _: [ '-c', '3', '-d', '4' ],\n '$0': 'node ./examples/reflect.js',\n a: 1,\n b: 2 }\n\nnegate fields\n-------------\n\nIf you want to explicity set a field to false instead of just leaving it\nundefined or to override a default you can do `--no-key`.\n\n $ node examples/reflect.js -a --no-b\n { _: [],\n '$0': 'node ./examples/reflect.js',\n a: true,\n b: false }\n\nnumbers\n-------\n\nEvery argument that looks like a number (`!isNaN(Number(arg))`) is converted to\none. This way you can just `net.createConnection(argv.port)` and you can add\nnumbers out of `argv` with `+` without having that mean concatenation,\nwhich is super frustrating.\n\nduplicates\n----------\n\nIf you specify a flag multiple times it will get turned into an array containing\nall the values in order.\n\n $ node examples/reflect.js -x 5 -x 8 -x 0\n { _: [],\n '$0': 'node ./examples/reflect.js',\n x: [ 5, 8, 0 ] }\n\ndot notation\n------------\n\nWhen you use dots (`.`s) in argument names, an implicit object path is assumed.\nThis lets you organize arguments into nested objects.\n\n $ node examples/reflect.js --foo.bar.baz=33 --foo.quux=5\n { _: [],\n '$0': 'node ./examples/reflect.js',\n foo: { bar: { baz: 33 }, quux: 5 } }\n\ninstallation\n============\n\nWith [npm](http://github.com/isaacs/npm), just do:\n npm install optimist\n \nor clone this project on github:\n\n git clone http://github.com/substack/node-optimist.git\n\nTo run the tests with [expresso](http://github.com/visionmedia/expresso),\njust do:\n \n expresso\n\ninspired By\n===========\n\nThis module is loosely inspired by Perl's\n[Getopt::Casual](http://search.cpan.org/~photo/Getopt-Casual-0.13.1/Casual.pm).\n", + "readmeFilename": "README.markdown", + "_id": "optimist@0.3.5", + "_from": "optimist" } diff --git a/node_modules/optimist/test/_.js b/node_modules/optimist/test/_.js index 3d6df6e..d9c58b3 100644 --- a/node_modules/optimist/test/_.js +++ b/node_modules/optimist/test/_.js @@ -1,66 +1,71 @@ var spawn = require('child_process').spawn; -var assert = require('assert'); +var test = require('tap').test; -exports.dotSlashEmpty = function () { - testCmd('./bin.js', []); -}; +test('dotSlashEmpty', testCmd('./bin.js', [])); -exports.dotSlashArgs = function () { - testCmd('./bin.js', [ 'a', 'b', 'c' ]); -}; +test('dotSlashArgs', testCmd('./bin.js', [ 'a', 'b', 'c' ])); -exports.nodeEmpty = function () { - testCmd('node bin.js', []); -}; +test('nodeEmpty', testCmd('node bin.js', [])); -exports.nodeArgs = function () { - testCmd('node bin.js', [ 'x', 'y', 'z' ]); -}; +test('nodeArgs', testCmd('node bin.js', [ 'x', 'y', 'z' ])); -exports.whichNodeEmpty = function () { +test('whichNodeEmpty', function (t) { var which = spawn('which', ['node']); which.stdout.on('data', function (buf) { - testCmd(buf.toString().trim() + ' bin.js', []); + t.test( + testCmd(buf.toString().trim() + ' bin.js', []) + ); + t.end(); }); which.stderr.on('data', function (err) { - assert.fail(err.toString()); + assert.error(err); + t.end(); }); -}; +}); -exports.whichNodeArgs = function () { +test('whichNodeArgs', function (t) { var which = spawn('which', ['node']); - + which.stdout.on('data', function (buf) { - testCmd(buf.toString().trim() + ' bin.js', [ 'q', 'r' ]); + t.test( + testCmd(buf.toString().trim() + ' bin.js', [ 'q', 'r' ]) + ); + t.end(); }); which.stderr.on('data', function (err) { - assert.fail(err.toString()); + t.error(err); + t.end(); }); -}; +}); function testCmd (cmd, args) { - var to = setTimeout(function () { - assert.fail('Never got stdout data.') - }, 5000); - - var oldDir = process.cwd(); - process.chdir(__dirname + '/_'); - - var cmds = cmd.split(' '); - - var bin = spawn(cmds[0], cmds.slice(1).concat(args.map(String))); - process.chdir(oldDir); - - bin.stderr.on('data', function (err) { - assert.fail(err.toString()); - }); - - bin.stdout.on('data', function (buf) { - clearTimeout(to); - var _ = JSON.parse(buf.toString()); - assert.eql(_.map(String), args.map(String)); - }); + + return function (t) { + var to = setTimeout(function () { + assert.fail('Never got stdout data.') + }, 5000); + + var oldDir = process.cwd(); + process.chdir(__dirname + '/_'); + + var cmds = cmd.split(' '); + + var bin = spawn(cmds[0], cmds.slice(1).concat(args.map(String))); + process.chdir(oldDir); + + bin.stderr.on('data', function (err) { + t.error(err); + t.end(); + }); + + bin.stdout.on('data', function (buf) { + clearTimeout(to); + var _ = JSON.parse(buf.toString()); + t.same(_.map(String), args.map(String)); + t.end(); + }); + }; } diff --git a/node_modules/optimist/test/parse.js b/node_modules/optimist/test/parse.js index eed467e..a6ce9f1 100644 --- a/node_modules/optimist/test/parse.js +++ b/node_modules/optimist/test/parse.js @@ -1,128 +1,136 @@ var optimist = require('../index'); -var assert = require('assert'); var path = require('path'); +var test = require('tap').test; -var localExpresso = path.normalize( - __dirname + '/../node_modules/.bin/expresso' -); +var $0 = 'node ./' + path.relative(process.cwd(), __filename); -var expresso = process.argv[1] === localExpresso - ? 'node ./node_modules/.bin/expresso' - : 'expresso' -; - -exports['short boolean'] = function () { +test('short boolean', function (t) { var parse = optimist.parse([ '-b' ]); - assert.eql(parse, { b : true, _ : [], $0 : expresso }); - assert.eql(typeof parse.b, 'boolean'); -}; + t.same(parse, { b : true, _ : [], $0 : $0 }); + t.same(typeof parse.b, 'boolean'); + t.end(); +}); -exports['long boolean'] = function () { - assert.eql( +test('long boolean', function (t) { + t.same( optimist.parse([ '--bool' ]), - { bool : true, _ : [], $0 : expresso } + { bool : true, _ : [], $0 : $0 } ); -}; + t.end(); +}); -exports.bare = function () { - assert.eql( +test('bare', function (t) { + t.same( optimist.parse([ 'foo', 'bar', 'baz' ]), - { _ : [ 'foo', 'bar', 'baz' ], $0 : expresso } + { _ : [ 'foo', 'bar', 'baz' ], $0 : $0 } ); -}; + t.end(); +}); -exports['short group'] = function () { - assert.eql( +test('short group', function (t) { + t.same( optimist.parse([ '-cats' ]), - { c : true, a : true, t : true, s : true, _ : [], $0 : expresso } + { c : true, a : true, t : true, s : true, _ : [], $0 : $0 } ); -}; + t.end(); +}); -exports['short group next'] = function () { - assert.eql( +test('short group next', function (t) { + t.same( optimist.parse([ '-cats', 'meow' ]), - { c : true, a : true, t : true, s : 'meow', _ : [], $0 : expresso } + { c : true, a : true, t : true, s : 'meow', _ : [], $0 : $0 } ); -}; + t.end(); +}); -exports['short capture'] = function () { - assert.eql( +test('short capture', function (t) { + t.same( optimist.parse([ '-h', 'localhost' ]), - { h : 'localhost', _ : [], $0 : expresso } + { h : 'localhost', _ : [], $0 : $0 } ); -}; + t.end(); +}); -exports['short captures'] = function () { - assert.eql( +test('short captures', function (t) { + t.same( optimist.parse([ '-h', 'localhost', '-p', '555' ]), - { h : 'localhost', p : 555, _ : [], $0 : expresso } + { h : 'localhost', p : 555, _ : [], $0 : $0 } ); -}; + t.end(); +}); -exports['long capture sp'] = function () { - assert.eql( +test('long capture sp', function (t) { + t.same( optimist.parse([ '--pow', 'xixxle' ]), - { pow : 'xixxle', _ : [], $0 : expresso } + { pow : 'xixxle', _ : [], $0 : $0 } ); -}; + t.end(); +}); -exports['long capture eq'] = function () { - assert.eql( +test('long capture eq', function (t) { + t.same( optimist.parse([ '--pow=xixxle' ]), - { pow : 'xixxle', _ : [], $0 : expresso } + { pow : 'xixxle', _ : [], $0 : $0 } ); -}; + t.end() +}); -exports['long captures sp'] = function () { - assert.eql( +test('long captures sp', function (t) { + t.same( optimist.parse([ '--host', 'localhost', '--port', '555' ]), - { host : 'localhost', port : 555, _ : [], $0 : expresso } + { host : 'localhost', port : 555, _ : [], $0 : $0 } ); -}; + t.end(); +}); -exports['long captures eq'] = function () { - assert.eql( +test('long captures eq', function (t) { + t.same( optimist.parse([ '--host=localhost', '--port=555' ]), - { host : 'localhost', port : 555, _ : [], $0 : expresso } + { host : 'localhost', port : 555, _ : [], $0 : $0 } ); -}; + t.end(); +}); -exports['mixed short bool and capture'] = function () { - assert.eql( +test('mixed short bool and capture', function (t) { + t.same( optimist.parse([ '-h', 'localhost', '-fp', '555', 'script.js' ]), { f : true, p : 555, h : 'localhost', - _ : [ 'script.js' ], $0 : expresso, + _ : [ 'script.js' ], $0 : $0, } ); -}; + t.end(); +}); -exports['short and long'] = function () { - assert.eql( +test('short and long', function (t) { + t.same( optimist.parse([ '-h', 'localhost', '-fp', '555', 'script.js' ]), { f : true, p : 555, h : 'localhost', - _ : [ 'script.js' ], $0 : expresso, + _ : [ 'script.js' ], $0 : $0, } ); -}; + t.end(); +}); -exports.no = function () { - assert.eql( +test('no', function (t) { + t.same( optimist.parse([ '--no-moo' ]), - { moo : false, _ : [], $0 : expresso } + { moo : false, _ : [], $0 : $0 } ); -}; + t.end(); +}); -exports.multi = function () { - assert.eql( +test('multi', function (t) { + t.same( optimist.parse([ '-v', 'a', '-v', 'b', '-v', 'c' ]), - { v : ['a','b','c'], _ : [], $0 : expresso } + { v : ['a','b','c'], _ : [], $0 : $0 } ); -}; + t.end(); +}); -exports.comprehensive = function () { - assert.eql( +test('comprehensive', function (t) { + t.same( optimist.parse([ '--name=meowmers', 'bare', '-cats', 'woo', '-h', 'awesome', '--multi=quux', @@ -143,12 +151,13 @@ exports.comprehensive = function () { meep : false, name : 'meowmers', _ : [ 'bare', '--not-a-flag', 'eek' ], - $0 : expresso + $0 : $0 } ); -}; + t.end(); +}); -exports.nums = function () { +test('nums', function (t) { var argv = optimist.parse([ '-x', '1234', '-y', '5.67', @@ -157,131 +166,141 @@ exports.nums = function () { '--hex', '0xdeadbeef', '789', ]); - assert.eql(argv, { + t.same(argv, { x : 1234, y : 5.67, z : 1e7, w : '10f', hex : 0xdeadbeef, _ : [ 789 ], - $0 : expresso + $0 : $0 }); - assert.eql(typeof argv.x, 'number'); - assert.eql(typeof argv.y, 'number'); - assert.eql(typeof argv.z, 'number'); - assert.eql(typeof argv.w, 'string'); - assert.eql(typeof argv.hex, 'number'); - assert.eql(typeof argv._[0], 'number'); -}; + t.same(typeof argv.x, 'number'); + t.same(typeof argv.y, 'number'); + t.same(typeof argv.z, 'number'); + t.same(typeof argv.w, 'string'); + t.same(typeof argv.hex, 'number'); + t.same(typeof argv._[0], 'number'); + t.end(); +}); -exports['flag boolean'] = function () { +test('flag boolean', function (t) { var parse = optimist([ '-t', 'moo' ]).boolean(['t']).argv; - assert.eql(parse, { t : true, _ : [ 'moo' ], $0 : expresso }); - assert.eql(typeof parse.t, 'boolean'); -}; + t.same(parse, { t : true, _ : [ 'moo' ], $0 : $0 }); + t.same(typeof parse.t, 'boolean'); + t.end(); +}); -exports['flag boolean value'] = function () { +test('flag boolean value', function (t) { var parse = optimist(['--verbose', 'false', 'moo', '-t', 'true']) .boolean(['t', 'verbose']).default('verbose', true).argv; - assert.eql(parse, { + t.same(parse, { verbose: false, t: true, _: ['moo'], - $0 : expresso + $0 : $0 }); - assert.eql(typeof parse.verbose, 'boolean'); - assert.eql(typeof parse.t, 'boolean'); -}; + t.same(typeof parse.verbose, 'boolean'); + t.same(typeof parse.t, 'boolean'); + t.end(); +}); -exports['flag boolean default false'] = function () { +test('flag boolean default false', function (t) { var parse = optimist(['moo']) .boolean(['t', 'verbose']) .default('verbose', false) .default('t', false).argv; - assert.eql(parse, { + t.same(parse, { verbose: false, t: false, _: ['moo'], - $0 : expresso + $0 : $0 }); - assert.eql(typeof parse.verbose, 'boolean'); - assert.eql(typeof parse.t, 'boolean'); - -}; + t.same(typeof parse.verbose, 'boolean'); + t.same(typeof parse.t, 'boolean'); + t.end(); -exports['boolean groups'] = function () { +}); + +test('boolean groups', function (t) { var parse = optimist([ '-x', '-z', 'one', 'two', 'three' ]) .boolean(['x','y','z']).argv; - assert.eql(parse, { + t.same(parse, { x : true, y : false, z : true, _ : [ 'one', 'two', 'three' ], - $0 : expresso + $0 : $0 }); - assert.eql(typeof parse.x, 'boolean'); - assert.eql(typeof parse.y, 'boolean'); - assert.eql(typeof parse.z, 'boolean'); -}; + t.same(typeof parse.x, 'boolean'); + t.same(typeof parse.y, 'boolean'); + t.same(typeof parse.z, 'boolean'); + t.end(); +}); -exports.strings = function () { +test('strings' , function (t) { var s = optimist([ '-s', '0001234' ]).string('s').argv.s; - assert.eql(s, '0001234'); - assert.eql(typeof s, 'string'); + t.same(s, '0001234'); + t.same(typeof s, 'string'); var x = optimist([ '-x', '56' ]).string('x').argv.x; - assert.eql(x, '56'); - assert.eql(typeof x, 'string'); -}; + t.same(x, '56'); + t.same(typeof x, 'string'); + t.end(); +}); -exports.stringArgs = function () { +test('stringArgs', function (t) { var s = optimist([ ' ', ' ' ]).string('_').argv._; - assert.eql(s.length, 2); - assert.eql(typeof s[0], 'string'); - assert.eql(s[0], ' '); - assert.eql(typeof s[1], 'string'); - assert.eql(s[1], ' '); -}; + t.same(s.length, 2); + t.same(typeof s[0], 'string'); + t.same(s[0], ' '); + t.same(typeof s[1], 'string'); + t.same(s[1], ' '); + t.end(); +}); -exports.slashBreak = function () { - assert.eql( +test('slashBreak', function (t) { + t.same( optimist.parse([ '-I/foo/bar/baz' ]), - { I : '/foo/bar/baz', _ : [], $0 : expresso } + { I : '/foo/bar/baz', _ : [], $0 : $0 } ); - assert.eql( + t.same( optimist.parse([ '-xyz/foo/bar/baz' ]), - { x : true, y : true, z : '/foo/bar/baz', _ : [], $0 : expresso } + { x : true, y : true, z : '/foo/bar/baz', _ : [], $0 : $0 } ); -}; + t.end(); +}); -exports.alias = function () { +test('alias', function (t) { var argv = optimist([ '-f', '11', '--zoom', '55' ]) .alias('z', 'zoom') .argv ; - assert.equal(argv.zoom, 55); - assert.equal(argv.z, argv.zoom); - assert.equal(argv.f, 11); -}; + t.equal(argv.zoom, 55); + t.equal(argv.z, argv.zoom); + t.equal(argv.f, 11); + t.end(); +}); -exports.multiAlias = function () { +test('multiAlias', function (t) { var argv = optimist([ '-f', '11', '--zoom', '55' ]) .alias('z', [ 'zm', 'zoom' ]) .argv ; - assert.equal(argv.zoom, 55); - assert.equal(argv.z, argv.zoom); - assert.equal(argv.z, argv.zm); - assert.equal(argv.f, 11); -}; + t.equal(argv.zoom, 55); + t.equal(argv.z, argv.zoom); + t.equal(argv.z, argv.zm); + t.equal(argv.f, 11); + t.end(); +}); -exports['boolean default true'] = function () { +test('boolean default true', function (t) { var argv = optimist.options({ sometrue: { boolean: true, @@ -289,10 +308,11 @@ exports['boolean default true'] = function () { } }).argv; - assert.equal(argv.sometrue, true); -}; + t.equal(argv.sometrue, true); + t.end(); +}); -exports['boolean default false'] = function () { +test('boolean default false', function (t) { var argv = optimist.options({ somefalse: { boolean: true, @@ -300,5 +320,114 @@ exports['boolean default false'] = function () { } }).argv; - assert.equal(argv.somefalse, false); -}; + t.equal(argv.somefalse, false); + t.end(); +}); + +test('nested dotted objects', function (t) { + var argv = optimist([ + '--foo.bar', '3', '--foo.baz', '4', + '--foo.quux.quibble', '5', '--foo.quux.o_O', + '--beep.boop' + ]).argv; + + t.same(argv.foo, { + bar : 3, + baz : 4, + quux : { + quibble : 5, + o_O : true + }, + }); + t.same(argv.beep, { boop : true }); + t.end(); +}); + +test('boolean and alias with chainable api', function (t) { + var aliased = [ '-h', 'derp' ]; + var regular = [ '--herp', 'derp' ]; + var opts = { + herp: { alias: 'h', boolean: true } + }; + var aliasedArgv = optimist(aliased) + .boolean('herp') + .alias('h', 'herp') + .argv; + var propertyArgv = optimist(regular) + .boolean('herp') + .alias('h', 'herp') + .argv; + var expected = { + herp: true, + h: true, + '_': [ 'derp' ], + '$0': $0, + }; + + t.same(aliasedArgv, expected); + t.same(propertyArgv, expected); + t.end(); +}); + +test('boolean and alias with options hash', function (t) { + var aliased = [ '-h', 'derp' ]; + var regular = [ '--herp', 'derp' ]; + var opts = { + herp: { alias: 'h', boolean: true } + }; + var aliasedArgv = optimist(aliased) + .options(opts) + .argv; + var propertyArgv = optimist(regular).options(opts).argv; + var expected = { + herp: true, + h: true, + '_': [ 'derp' ], + '$0': $0, + }; + + t.same(aliasedArgv, expected); + t.same(propertyArgv, expected); + + t.end(); +}); + +test('boolean and alias using explicit true', function (t) { + var aliased = [ '-h', 'true' ]; + var regular = [ '--herp', 'true' ]; + var opts = { + herp: { alias: 'h', boolean: true } + }; + var aliasedArgv = optimist(aliased) + .boolean('h') + .alias('h', 'herp') + .argv; + var propertyArgv = optimist(regular) + .boolean('h') + .alias('h', 'herp') + .argv; + var expected = { + herp: true, + h: true, + '_': [ ], + '$0': $0, + }; + + t.same(aliasedArgv, expected); + t.same(propertyArgv, expected); + t.end(); +}); + +// regression, see https://github.com/substack/node-optimist/issues/71 +test('boolean and --x=true', function(t) { + var parsed = optimist(['--boool', '--other=true']).boolean('boool').argv; + + t.same(parsed.boool, true); + t.same(parsed.other, 'true'); + + parsed = optimist(['--boool', '--other=false']).boolean('boool').argv; + + t.same(parsed.boool, true); + t.same(parsed.other, 'false'); + t.end(); +}); diff --git a/node_modules/optimist/test/usage.js b/node_modules/optimist/test/usage.js index 6593b9b..300454c 100644 --- a/node_modules/optimist/test/usage.js +++ b/node_modules/optimist/test/usage.js @@ -1,20 +1,20 @@ var Hash = require('hashish'); var optimist = require('../index'); -var assert = require('assert'); +var test = require('tap').test; -exports.usageFail = function () { +test('usageFail', function (t) { var r = checkUsage(function () { return optimist('-x 10 -z 20'.split(' ')) .usage('Usage: $0 -x NUM -y NUM') .demand(['x','y']) .argv; }); - assert.deepEqual( + t.same( r.result, { x : 10, z : 20, _ : [], $0 : './usage' } ); - - assert.deepEqual( + + t.same( r.errors.join('\n').split(/\n+/), [ 'Usage: ./usage -x NUM -y NUM', @@ -24,26 +24,29 @@ exports.usageFail = function () { 'Missing required arguments: y', ] ); - assert.deepEqual(r.logs, []); - assert.ok(r.exit); -}; + t.same(r.logs, []); + t.ok(r.exit); + t.end(); +}); -exports.usagePass = function () { + +test('usagePass', function (t) { var r = checkUsage(function () { return optimist('-x 10 -y 20'.split(' ')) .usage('Usage: $0 -x NUM -y NUM') .demand(['x','y']) .argv; }); - assert.deepEqual(r, { + t.same(r, { result : { x : 10, y : 20, _ : [], $0 : './usage' }, errors : [], logs : [], exit : false, }); -}; + t.end(); +}); -exports.checkPass = function () { +test('checkPass', function (t) { var r = checkUsage(function () { return optimist('-x 10 -y 20'.split(' ')) .usage('Usage: $0 -x NUM -y NUM') @@ -53,15 +56,16 @@ exports.checkPass = function () { }) .argv; }); - assert.deepEqual(r, { + t.same(r, { result : { x : 10, y : 20, _ : [], $0 : './usage' }, errors : [], logs : [], exit : false, }); -}; + t.end(); +}); -exports.checkFail = function () { +test('checkFail', function (t) { var r = checkUsage(function () { return optimist('-x 10 -z 20'.split(' ')) .usage('Usage: $0 -x NUM -y NUM') @@ -71,110 +75,115 @@ exports.checkFail = function () { }) .argv; }); - - assert.deepEqual( + + t.same( r.result, { x : 10, z : 20, _ : [], $0 : './usage' } ); - - assert.deepEqual( + + t.same( r.errors.join('\n').split(/\n+/), [ 'Usage: ./usage -x NUM -y NUM', 'You forgot about -y' ] ); - - assert.deepEqual(r.logs, []); - assert.ok(r.exit); -}; -exports.checkCondPass = function () { + t.same(r.logs, []); + t.ok(r.exit); + t.end(); +}); + +test('checkCondPass', function (t) { function checker (argv) { return 'x' in argv && 'y' in argv; } - + var r = checkUsage(function () { return optimist('-x 10 -y 20'.split(' ')) .usage('Usage: $0 -x NUM -y NUM') .check(checker) .argv; }); - assert.deepEqual(r, { + t.same(r, { result : { x : 10, y : 20, _ : [], $0 : './usage' }, errors : [], logs : [], exit : false, }); -}; + t.end(); +}); -exports.checkCondFail = function () { +test('checkCondFail', function (t) { function checker (argv) { return 'x' in argv && 'y' in argv; } - + var r = checkUsage(function () { return optimist('-x 10 -z 20'.split(' ')) .usage('Usage: $0 -x NUM -y NUM') .check(checker) .argv; }); - - assert.deepEqual( + + t.same( r.result, { x : 10, z : 20, _ : [], $0 : './usage' } ); - - assert.deepEqual( + + t.same( r.errors.join('\n').split(/\n+/).join('\n'), 'Usage: ./usage -x NUM -y NUM\n' + 'Argument check failed: ' + checker.toString() ); - - assert.deepEqual(r.logs, []); - assert.ok(r.exit); -}; -exports.countPass = function () { + t.same(r.logs, []); + t.ok(r.exit); + t.end(); +}); + +test('countPass', function (t) { var r = checkUsage(function () { return optimist('1 2 3 --moo'.split(' ')) .usage('Usage: $0 [x] [y] [z] {OPTIONS}') .demand(3) .argv; }); - assert.deepEqual(r, { + t.same(r, { result : { _ : [ '1', '2', '3' ], moo : true, $0 : './usage' }, errors : [], logs : [], exit : false, }); -}; + t.end(); +}); -exports.countFail = function () { +test('countFail', function (t) { var r = checkUsage(function () { return optimist('1 2 --moo'.split(' ')) .usage('Usage: $0 [x] [y] [z] {OPTIONS}') .demand(3) .argv; }); - assert.deepEqual( + t.same( r.result, { _ : [ '1', '2' ], moo : true, $0 : './usage' } ); - - assert.deepEqual( + + t.same( r.errors.join('\n').split(/\n+/), [ 'Usage: ./usage [x] [y] [z] {OPTIONS}', 'Not enough non-option arguments: got 2, need at least 3', ] ); - - assert.deepEqual(r.logs, []); - assert.ok(r.exit); -}; -exports.defaultSingles = function () { + t.same(r.logs, []); + t.ok(r.exit); + t.end(); +}); + +test('defaultSingles', function (t) { var r = checkUsage(function () { return optimist('--foo 50 --baz 70 --powsy'.split(' ')) .default('foo', 5) @@ -183,7 +192,7 @@ exports.defaultSingles = function () { .argv ; }); - assert.eql(r.result, { + t.same(r.result, { foo : '50', bar : 6, baz : '70', @@ -191,62 +200,89 @@ exports.defaultSingles = function () { _ : [], $0 : './usage', }); -}; + t.end(); +}); -exports.defaultHash = function () { +test('defaultAliases', function (t) { + var r = checkUsage(function () { + return optimist('') + .alias('f', 'foo') + .default('f', 5) + .argv + ; + }); + t.same(r.result, { + f : '5', + foo : '5', + _ : [], + $0 : './usage', + }); + t.end(); +}); + +test('defaultHash', function (t) { var r = checkUsage(function () { return optimist('--foo 50 --baz 70'.split(' ')) .default({ foo : 10, bar : 20, quux : 30 }) .argv ; }); - assert.eql(r.result, { - foo : '50', - bar : 20, - baz : 70, - quux : 30, + t.same(r.result, { _ : [], $0 : './usage', + foo : 50, + baz : 70, + bar : 20, + quux : 30, }); -}; + t.end(); +}); -exports.rebase = function () { - assert.equal( +test('rebase', function (t) { + t.equal( optimist.rebase('/home/substack', '/home/substack/foo/bar/baz'), './foo/bar/baz' ); - assert.equal( + t.equal( optimist.rebase('/home/substack/foo/bar/baz', '/home/substack'), '../../..' ); - assert.equal( + t.equal( optimist.rebase('/home/substack/foo', '/home/substack/pow/zoom.txt'), '../pow/zoom.txt' ); -}; + t.end(); +}); function checkUsage (f) { - var _process = process; - process = Hash.copy(process); + var exit = false; - process.exit = function () { exit = true }; + + process._exit = process.exit; + process._env = process.env; + process._argv = process.argv; + + process.exit = function (t) { exit = true }; process.env = Hash.merge(process.env, { _ : 'node' }); process.argv = [ './usage' ]; - + var errors = []; var logs = []; - + console._error = console.error; console.error = function (msg) { errors.push(msg) }; console._log = console.log; console.log = function (msg) { logs.push(msg) }; - + var result = f(); - - process = _process; + + process.exit = process._exit; + process.env = process._env; + process.argv = process._argv; + console.error = console._error; console.log = console._log; - + return { errors : errors, logs : logs, diff --git a/node_modules/request/README.md b/node_modules/request/README.md index c29d086..d1f5c56 100644 --- a/node_modules/request/README.md +++ b/node_modules/request/README.md @@ -16,7 +16,7 @@ Or from source: ## Super simple to use -Request is designed to be the simplest way possible to make http calls. It support HTTPS and follows redirects by default. +Request is designed to be the simplest way possible to make http calls. It supports HTTPS and follows redirects by default. ```javascript var request = require('request'); @@ -38,7 +38,7 @@ request('http://google.com/doodle.png').pipe(fs.createWriteStream('doodle.png')) You can also stream a file to a PUT or POST request. This method will also check the file extension against a mapping of file extensions to content-types, in this case `application/json`, and use the proper content-type in the PUT request if one is not already provided in the headers. ```javascript -fs.readStream('file.json').pipe(request.put('http://mysite.com/obj.json')) +fs.createReadStream('file.json').pipe(request.put('http://mysite.com/obj.json')) ``` Request can also pipe to itself. When doing so the content-type and content-length will be preserved in the PUT headers. @@ -90,9 +90,31 @@ http.createServer(function (req, resp) { } }) ``` - You can still use intermediate proxies, the requests will still follow HTTP forwards, etc. +## Forms + +`request` supports `application/x-www-form-urlencoded` and `multipart/form-data` form uploads. For `multipart/related` refer to the `multipart` API. + +Url encoded forms are simple + +```javascript +request.post('http://service.com/upload', {form:{key:'value'}}) +// or +request.post('http://service.com/upload').form({key:'value'}) +``` + +For `multipart/form-data` we use the [form-data](https://github.com/felixge/node-form-data) library by [@felixge](https://github.com/felixge). You don't need to worry about piping the form object or setting the headers, `request` will handle that for you. + +```javascript +var r = request.post('http://service.com/upload') +var form = r.form() +form.append('my_field', 'my_value') +form.append('my_buffer', new Buffer([1, 2, 3])) +form.append('my_file', fs.createReadStream(path.join(__dirname, 'doodle.png')) +form.append('remote_file', request('http://google.com/doodle.png')) +``` + ## OAuth Signing ```javascript @@ -146,15 +168,17 @@ request.post({url:url, oauth:oauth}, function (e, r, body) { The first argument can be either a url or an options object. The only required option is uri, all others are optional. * `uri` || `url` - fully qualified uri or a parsed url object from url.parse() +* `qs` - object containing querystring values to be appended to the uri * `method` - http method, defaults to GET * `headers` - http headers, defaults to {} * `body` - entity body for POST and PUT requests. Must be buffer or string. -* `json` - sets `body` but to JSON representation of value and adds `Content-type: application/json` header. +* `form` - when passed an object this will set `body` but to a querystring representation of value and adds `Content-type: application/x-www-form-urlencoded; charset=utf-8` header. When passed no option a FormData instance is returned that will be piped to request. +* `json` - sets `body` but to JSON representation of value and adds `Content-type: application/json` header. Additionally, parses the response body as json. * `multipart` - (experimental) array of objects which contains their own headers and `body` attribute. Sends `multipart/related` request. See example below. * `followRedirect` - follow HTTP 3xx responses as redirects. defaults to true. +* `followAllRedirects` - follow non-GET HTTP 3xx responses as redirects. defaults to false. * `maxRedirects` - the maximum number of redirects to follow, defaults to 10. -* `onResponse` - If true the callback will be fired on the "response" event instead of "end". If a function it will be called on "response" and not effect the regular semantics of the main callback on "end". -* `encoding` - Encoding to be used on response.setEncoding when buffering the response data. +* `encoding` - Encoding to be used on `setEncoding` of response data. If set to `null`, the body is returned as a Buffer. * `pool` - A hash object containing the agents for these requests. If omitted this request will use the global pool which is set to node's default maxSockets. * `pool.maxSockets` - Integer containing the maximum amount of sockets in the pool. * `timeout` - Integer containing the number of milliseconds to wait for a request to respond before aborting the request @@ -162,9 +186,10 @@ The first argument can be either a url or an options object. The only required o * `oauth` - Options for OAuth HMAC-SHA1 signing, see documentation above. * `strictSSL` - Set to `true` to require that SSL certificates be valid. Note: to use your own certificate authority, you need to specify an agent that was created with that ca as an option. * `jar` - Set to `false` if you don't want cookies to be remembered for future use or define your custom cookie jar (see examples section) +* `aws` - object containing aws signing information, should have the properties `key` and `secret` as well as `bucket` unless you're specifying your bucket as part of the path, or you are making a request that doesn't use a bucket (i.e. GET Services) -The callback argument gets 3 arguments. The first is an error when applicable (usually from the http.Client option not the http.ClientRequest object). The second in an http.ClientResponse object. The third is the response body buffer. +The callback argument gets 3 arguments. The first is an error when applicable (usually from the http.Client option not the http.ClientRequest object). The second in an http.ClientResponse object. The third is the response body String or Buffer. ## Convenience methods @@ -237,7 +262,7 @@ request.jar() ; request( { method: 'PUT' - , uri: 'http://mikeal.couchone.com/testjs/' + rand + , uri: 'http://mikeal.iriscouch.com/testjs/' + rand , multipart: [ { 'content-type': 'application/json' , body: JSON.stringify({foo: 'bar', _attachments: {'message.txt': {follows: true, length: 18, 'content_type': 'text/plain' }}}) @@ -247,7 +272,7 @@ request.jar() } , function (error, response, body) { if(response.statusCode == 201){ - console.log('document saved as: http://mikeal.couchone.com/testjs/'+ rand) + console.log('document saved as: http://mikeal.iriscouch.com/testjs/'+ rand) } else { console.log('error: '+ response.statusCode) console.log(body) diff --git a/node_modules/request/main.js b/node_modules/request/main.js index 26f877d..27b470b 100644 --- a/node_modules/request/main.js +++ b/node_modules/request/main.js @@ -1,4 +1,4 @@ -// Copyright 2010-2011 Mikeal Rogers +// Copyright 2010-2012 Mikeal Rogers // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -19,13 +19,22 @@ var http = require('http') , util = require('util') , stream = require('stream') , qs = require('querystring') - , mimetypes = require('./mimetypes') , oauth = require('./oauth') , uuid = require('./uuid') + , ForeverAgent = require('./forever') , Cookie = require('./vendor/cookie') , CookieJar = require('./vendor/cookie/jar') , cookieJar = new CookieJar + , tunnel = require('./tunnel') + , aws = require('./aws') + + , mime = require('mime') + , FormData = require('form-data') ; + +if (process.logging) { + var log = process.logging('request') +} try { https = require('https') @@ -45,8 +54,8 @@ if (https && !https.Agent) { http.Agent.call(this, options) } util.inherits(https.Agent, http.Agent) - https.Agent.prototype._getConnection = function(host, port, cb) { - var s = tls.connect(port, host, this.options, function() { + https.Agent.prototype._getConnection = function (host, port, cb) { + var s = tls.connect(port, host, this.options, function () { // do other checks here? if (cb) cb() }) @@ -62,7 +71,9 @@ function isReadStream (rs) { function copy (obj) { var o = {} - for (var i in obj) o[i] = obj[i] + Object.keys(obj).forEach(function (i) { + o[i] = obj[i] + }) return o } @@ -78,24 +89,31 @@ function Request (options) { if (typeof options === 'string') { options = {uri:options} } - + + var reserved = Object.keys(Request.prototype) for (var i in options) { - this[i] = options[i] + if (reserved.indexOf(i) === -1) { + this[i] = options[i] + } else { + if (typeof options[i] === 'function') { + delete options[i] + } + } } - if (!this.pool) this.pool = globalPool - this.dests = [] - this.__isRequestRequest = true + options = copy(options) + + this.init(options) } util.inherits(Request, stream.Stream) -Request.prototype.getAgent = function (host, port) { - if (!this.pool[host+':'+port]) { - this.pool[host+':'+port] = new this.httpModule.Agent({host:host, port:port}) - } - return this.pool[host+':'+port] -} -Request.prototype.request = function () { +Request.prototype.init = function (options) { var self = this - + + if (!options) options = {} + if (process.env.NODE_DEBUG && /request/.test(process.env.NODE_DEBUG)) console.error('REQUEST', options) + if (!self.pool && self.pool !== false) self.pool = globalPool + self.dests = [] + self.__isRequestRequest = true + // Protect against double callback if (!self._callback && self.callback) { self._callback = self.callback @@ -104,6 +122,8 @@ Request.prototype.request = function () { self._callback.apply(self, arguments) self._callbackCalled = true } + self.on('error', self.callback.bind()) + self.on('complete', self.callback.bind(self, null)) } if (self.url) { @@ -113,23 +133,54 @@ Request.prototype.request = function () { } if (!self.uri) { - throw new Error("options.uri is a required argument") + // this will throw if unhandled but is handleable when in a redirect + return self.emit('error', new Error("options.uri is a required argument")) } else { if (typeof self.uri == "string") self.uri = url.parse(self.uri) } if (self.proxy) { if (typeof self.proxy == 'string') self.proxy = url.parse(self.proxy) + + // do the HTTP CONNECT dance using koichik/node-tunnel + if (http.globalAgent && self.uri.protocol === "https:") { + var tunnelFn = self.proxy.protocol === "http:" + ? tunnel.httpsOverHttp : tunnel.httpsOverHttps + + var tunnelOptions = { proxy: { host: self.proxy.hostname + , port: +self.proxy.port + , proxyAuth: self.proxy.auth } + , ca: this.ca } + + self.agent = tunnelFn(tunnelOptions) + self.tunnel = true + } + } + + if (!self.uri.host || !self.uri.pathname) { + // Invalid URI: it may generate lot of bad errors, like "TypeError: Cannot call method 'indexOf' of undefined" in CookieJar + // Detect and reject it as soon as possible + var faultyUri = url.format(self.uri) + var message = 'Invalid URI "' + faultyUri + '"' + if (Object.keys(options).length === 0) { + // No option ? This can be the sign of a redirect + // As this is a case where the user cannot do anything (he didn't call request directly with this URL) + // he should be warned that it can be caused by a redirection (can save some hair) + message += '. This can be caused by a crappy redirection.' + } + self.emit('error', new Error(message)) + return // This error was fatal } self._redirectsFollowed = self._redirectsFollowed || 0 self.maxRedirects = (self.maxRedirects !== undefined) ? self.maxRedirects : 10 self.followRedirect = (self.followRedirect !== undefined) ? self.followRedirect : true - if (self.followRedirect) + self.followAllRedirects = (self.followAllRedirects !== undefined) ? self.followAllRedirects : false + if (self.followRedirect || self.followAllRedirects) self.redirects = self.redirects || [] self.headers = self.headers ? copy(self.headers) : {} - var setHost = false + self.setHost = false if (!self.headers.host) { self.headers.host = self.uri.hostname if (self.uri.port) { @@ -137,21 +188,10 @@ Request.prototype.request = function () { !(self.uri.port === 443 && self.uri.protocol === 'https:') ) self.headers.host += (':'+self.uri.port) } - setHost = true + self.setHost = true } - - if (self.jar === false) { - // disable cookies - var cookies = false; - self._disableCookies = true; - } else if (self.jar) { - // fetch cookie from the user defined cookie jar - var cookies = self.jar.get({ url: self.uri.href }) - } else { - // fetch cookie from the global cookie jar - var cookies = cookieJar.get({ url: self.uri.href }) - } - if (cookies) {self.headers.Cookie = cookies} + + self.jar(self._jar || options.jar) if (!self.uri.pathname) {self.uri.pathname = '/'} if (!self.uri.port) { @@ -159,7 +199,7 @@ Request.prototype.request = function () { else if (self.uri.protocol == 'https:') {self.uri.port = 443} } - if (self.proxy) { + if (self.proxy && !self.tunnel) { self.port = self.proxy.port self.host = self.proxy.hostname } else { @@ -167,73 +207,57 @@ Request.prototype.request = function () { self.host = self.uri.hostname } - if (self.onResponse === true) { - self.onResponse = self.callback - delete self.callback - } - - var clientErrorHandler = function (error) { - if (setHost) delete self.headers.host - if (self.timeout && self.timeoutTimer) clearTimeout(self.timeoutTimer) + self.clientErrorHandler = function (error) { + if (self._aborted) return + + if (self.setHost) delete self.headers.host + if (self.req._reusedSocket && error.code === 'ECONNRESET' + && self.agent.addRequestNoreuse) { + self.agent = { addRequest: self.agent.addRequestNoreuse.bind(self.agent) } + self.start() + self.req.end() + return + } + if (self.timeout && self.timeoutTimer) { + clearTimeout(self.timeoutTimer) + self.timeoutTimer = null + } self.emit('error', error) } - if (self.onResponse) self.on('error', function (e) {self.onResponse(e)}) - if (self.callback) self.on('error', function (e) {self.callback(e)}) - if (self.form) { - self.headers['content-type'] = 'application/x-www-form-urlencoded; charset=utf-8' - self.body = qs.stringify(self.form).toString('utf8') + self._parserErrorHandler = function (error) { + if (this.res) { + if (this.res.request) { + this.res.request.emit('error', error) + } else { + this.res.emit('error', error) + } + } else { + this._httpMessage.emit('error', error) + } } - if (self.oauth) { - var form - if (self.headers['content-type'] && - self.headers['content-type'].slice(0, 'application/x-www-form-urlencoded'.length) === - 'application/x-www-form-urlencoded' - ) { - form = qs.parse(self.body) - } - if (self.uri.query) { - form = qs.parse(self.uri.query) - } - if (!form) form = {} - var oa = {} - for (i in form) oa[i] = form[i] - for (i in self.oauth) oa['oauth_'+i] = self.oauth[i] - if (!oa.oauth_version) oa.oauth_version = '1.0' - if (!oa.oauth_timestamp) oa.oauth_timestamp = Math.floor( (new Date()).getTime() / 1000 ).toString() - if (!oa.oauth_nonce) oa.oauth_nonce = uuid().replace(/-/g, '') - - oa.oauth_signature_method = 'HMAC-SHA1' - - var consumer_secret = oa.oauth_consumer_secret - delete oa.oauth_consumer_secret - var token_secret = oa.oauth_token_secret - delete oa.oauth_token_secret - - var baseurl = self.uri.protocol + '//' + self.uri.host + self.uri.pathname - var signature = oauth.hmacsign(self.method, baseurl, oa, consumer_secret, token_secret) - - // oa.oauth_signature = signature - for (i in form) { - if ( i.slice(0, 'oauth_') in self.oauth) { - // skip - } else { - delete oa['oauth_'+i] - } - } - self.headers.authorization = - 'OAuth '+Object.keys(oa).sort().map(function (i) {return i+'="'+encodeURIComponent(oa[i])+'"'}).join(',') - self.headers.authorization += ',oauth_signature="'+encodeURIComponent(signature)+'"' + if (options.form) { + self.form(options.form) + } + + if (options.oauth) { + self.oauth(options.oauth) + } + + if (options.aws) { + self.aws(options.aws) } if (self.uri.auth && !self.headers.authorization) { self.headers.authorization = "Basic " + toBase64(self.uri.auth.split(':').map(function(item){ return qs.unescape(item)}).join(':')) } - if (self.proxy && self.proxy.auth && !self.headers['proxy-authorization']) { + if (self.proxy && self.proxy.auth && !self.headers['proxy-authorization'] && !self.tunnel) { self.headers['proxy-authorization'] = "Basic " + toBase64(self.proxy.auth.split(':').map(function(item){ return qs.unescape(item)}).join(':')) } + if (options.qs) self.qs(options.qs) + if (self.uri.path) { self.path = self.uri.path } else { @@ -242,222 +266,79 @@ Request.prototype.request = function () { if (self.path.length === 0) self.path = '/' - if (self.proxy) self.path = (self.uri.protocol + '//' + self.uri.host + self.path) + if (self.proxy && !self.tunnel) self.path = (self.uri.protocol + '//' + self.uri.host + self.path) - if (self.json) { - self.headers['content-type'] = 'application/json' - if (typeof self.json === 'boolean') { - if (typeof self.body === 'object') self.body = JSON.stringify(self.body) - } else { - self.body = JSON.stringify(self.json) - } - - } else if (self.multipart) { - self.body = '' - self.headers['content-type'] = 'multipart/related;boundary="frontier"' - if (!self.multipart.forEach) throw new Error('Argument error, options.multipart.') - - self.multipart.forEach(function (part) { - var body = part.body - if(!body) throw Error('Body attribute missing in multipart.') - delete part.body - self.body += '--frontier\r\n' - Object.keys(part).forEach(function(key){ - self.body += key + ': ' + part[key] + '\r\n' - }) - self.body += '\r\n' + body + '\r\n' - }) - self.body += '--frontier--' + if (options.json) { + self.json(options.json) + } else if (options.multipart) { + self.boundary = uuid() + self.multipart(options.multipart) } if (self.body) { + var length = 0 if (!Buffer.isBuffer(self.body)) { - self.body = new Buffer(self.body) + if (Array.isArray(self.body)) { + for (var i = 0; i < self.body.length; i++) { + length += self.body[i].length + } + } else { + self.body = new Buffer(self.body) + length = self.body.length + } + } else { + length = self.body.length } - if (self.body.length) { - self.headers['content-length'] = self.body.length + if (length) { + if(!self.headers['content-length'] && !self.headers['Content-Length']) + self.headers['content-length'] = length } else { throw new Error('Argument error, options.body.') } } - self.httpModule = - {"http:":http, "https:":https}[self.proxy ? self.proxy.protocol : self.uri.protocol] + var protocol = self.proxy && !self.tunnel ? self.proxy.protocol : self.uri.protocol + , defaultModules = {'http:':http, 'https:':https} + , httpModules = self.httpModules || {} + ; + self.httpModule = httpModules[protocol] || defaultModules[protocol] - if (!self.httpModule) throw new Error("Invalid protocol") + if (!self.httpModule) return this.emit('error', new Error("Invalid protocol")) + + if (options.ca) self.ca = options.ca + + if (!self.agent) { + if (options.agentOptions) self.agentOptions = options.agentOptions + + if (options.agentClass) { + self.agentClass = options.agentClass + } else if (options.forever) { + self.agentClass = protocol === 'http:' ? ForeverAgent : ForeverAgent.SSL + } else { + self.agentClass = self.httpModule.Agent + } + } if (self.pool === false) { self.agent = false } else { + self.agent = self.agent || self.getAgent() if (self.maxSockets) { // Don't use our pooling if node has the refactored client - self.agent = self.httpModule.globalAgent || self.getAgent(self.host, self.port) self.agent.maxSockets = self.maxSockets } if (self.pool.maxSockets) { // Don't use our pooling if node has the refactored client - self.agent = self.httpModule.globalAgent || self.getAgent(self.host, self.port) self.agent.maxSockets = self.pool.maxSockets } } - self.start = function () { - self._started = true - self.method = self.method || 'GET' - - self.req = self.httpModule.request(self, function (response) { - self.response = response - response.request = self - - if (self.httpModule === https && - self.strictSSL && - !response.client.authorized) { - var sslErr = response.client.authorizationError - self.emit('error', new Error('SSL Error: '+ sslErr)) - return - } - - if (setHost) delete self.headers.host - if (self.timeout && self.timeoutTimer) clearTimeout(self.timeoutTimer) - - if (response.statusCode >= 300 && - response.statusCode < 400 && - self.followRedirect && - self.method !== 'PUT' && - self.method !== 'POST' && - response.headers.location) { - if (self._redirectsFollowed >= self.maxRedirects) { - self.emit('error', new Error("Exceeded maxRedirects. Probably stuck in a redirect loop.")) - return - } - self._redirectsFollowed += 1 - - if (!isUrl.test(response.headers.location)) { - response.headers.location = url.resolve(self.uri.href, response.headers.location) - } - self.uri = response.headers.location - self.redirects.push( { statusCode : response.statusCode, - redirectUri: response.headers.location }) - delete self.req - delete self.agent - delete self._started - if (self.headers) { - delete self.headers.host - } - request(self, self.callback) - return // Ignore the rest of the response - } else { - self._redirectsFollowed = self._redirectsFollowed || 0 - // Be a good stream and emit end when the response is finished. - // Hack to emit end on close because of a core bug that never fires end - response.on('close', function () { - if (!self._ended) self.response.emit('end') - }) - - if (self.encoding) { - if (self.dests.length !== 0) { - console.error("Ingoring encoding parameter as this stream is being piped to another stream which makes the encoding option invalid.") - } else { - response.setEncoding(self.encoding) - } - } - - self.pipeDest = function (dest) { - if (dest.headers) { - dest.headers['content-type'] = response.headers['content-type'] - if (response.headers['content-length']) { - dest.headers['content-length'] = response.headers['content-length'] - } - } - if (dest.setHeader) { - for (var i in response.headers) { - dest.setHeader(i, response.headers[i]) - } - dest.statusCode = response.statusCode - } - if (self.pipefilter) self.pipefilter(response, dest) - } - - self.dests.forEach(function (dest) { - self.pipeDest(dest) - }) - - response.on("data", function (chunk) { - self._destdata = true - self.emit("data", chunk) - }) - response.on("end", function (chunk) { - self._ended = true - self.emit("end", chunk) - }) - response.on("close", function () {self.emit("close")}) - - self.emit('response', response) - - if (self.onResponse) { - self.onResponse(null, response) - } - if (self.callback) { - var buffer = [] - var bodyLen = 0 - self.on("data", function (chunk) { - buffer.push(chunk) - bodyLen += chunk.length - }) - self.on("end", function () { - if (buffer.length && Buffer.isBuffer(buffer[0])) { - var body = new Buffer(bodyLen) - var i = 0 - buffer.forEach(function (chunk) { - chunk.copy(body, i, 0, chunk.length) - i += chunk.length - }) - response.body = body.toString() - } else if (buffer.length) { - response.body = buffer.join('') - } - - if (self.json) { - try { - response.body = JSON.parse(response.body) - } catch (e) {} - } - if (response.statusCode == 200 && response.headers['set-cookie'] && (!self._disableCookies)) { - response.headers['set-cookie'].forEach(function(cookie) { - if (self.jar) { - // custom defined jar - self.jar.add(new Cookie(cookie)); - } else { - // add to the global cookie jar if user don't define his own - cookieJar.add(new Cookie(cookie)); - } - }); - } - - self.callback(null, response, response.body) - }) - } - } - }) - - if (self.timeout) { - self.timeoutTimer = setTimeout(function() { - self.req.abort() - var e = new Error("ETIMEDOUT") - e.code = "ETIMEDOUT" - self.emit("error", e) - }, self.timeout) - } - - self.req.on('error', clientErrorHandler) - } - self.once('pipe', function (src) { - if (self.ntick) throw new Error("You cannot pipe to this stream after the first nextTick() after creation of the request stream.") + if (self.ntick && self._started) throw new Error("You cannot pipe to this stream after the outbound request has started.") self.src = src if (isReadStream(src)) { if (!self.headers['content-type'] && !self.headers['Content-Type']) - self.headers['content-type'] = mimetypes.lookup(src.path.slice(src.path.lastIndexOf('.')+1)) + self.headers['content-type'] = mime.lookup(src.path) } else { if (src.headers) { for (var i in src.headers) { @@ -466,6 +347,8 @@ Request.prototype.request = function () { } } } + if (self._json && !self.headers['content-type'] && !self.headers['Content-Type']) + self.headers['content-type'] = 'application/json' if (src.method && !self.method) { self.method = src.method } @@ -477,73 +360,661 @@ Request.prototype.request = function () { }) process.nextTick(function () { + if (self._aborted) return + + if (self._form) { + self.setHeaders(self._form.getHeaders()) + self._form.pipe(self) + } if (self.body) { - self.write(self.body) + if (Array.isArray(self.body)) { + self.body.forEach(function (part) { + self.write(part) + }) + } else { + self.write(self.body) + } self.end() } else if (self.requestBodyStream) { console.warn("options.requestBodyStream is deprecated, please pass the request object to stream.pipe.") self.requestBodyStream.pipe(self) } else if (!self.src) { - self.headers['content-length'] = 0 + if (self.method !== 'GET' && typeof self.method !== 'undefined') { + self.headers['content-length'] = 0 + } self.end() } self.ntick = true }) } -Request.prototype.pipe = function (dest) { + +// Must call this when following a redirect from https to http or vice versa +// Attempts to keep everything as identical as possible, but update the +// httpModule, Tunneling agent, and/or Forever Agent in use. +Request.prototype._updateProtocol = function () { + var self = this + var protocol = self.uri.protocol + + if (protocol === 'https:') { + // previously was doing http, now doing https + // if it's https, then we might need to tunnel now. + if (self.proxy) { + self.tunnel = true + var tunnelFn = self.proxy.protocol === 'http:' + ? tunnel.httpsOverHttp : tunnel.httpsOverHttps + var tunnelOptions = { proxy: { host: self.proxy.hostname + , post: +self.proxy.port + , proxyAuth: self.proxy.auth } + , ca: self.ca } + self.agent = tunnelFn(tunnelOptions) + return + } + + self.httpModule = https + switch (self.agentClass) { + case ForeverAgent: + self.agentClass = ForeverAgent.SSL + break + case http.Agent: + self.agentClass = https.Agent + break + default: + // nothing we can do. Just hope for the best. + return + } + + // if there's an agent, we need to get a new one. + if (self.agent) self.agent = self.getAgent() + + } else { + if (log) log('previously https, now http') + // previously was doing https, now doing http + // stop any tunneling. + if (self.tunnel) self.tunnel = false + self.httpModule = http + switch (self.agentClass) { + case ForeverAgent.SSL: + self.agentClass = ForeverAgent + break + case https.Agent: + self.agentClass = http.Agent + break + default: + // nothing we can do. just hope for the best + return + } + + // if there's an agent, then get a new one. + if (self.agent) { + self.agent = null + self.agent = self.getAgent() + } + } +} + +Request.prototype.getAgent = function () { + var Agent = this.agentClass + var options = {} + if (this.agentOptions) { + for (var i in this.agentOptions) { + options[i] = this.agentOptions[i] + } + } + if (this.ca) options.ca = this.ca + + var poolKey = '' + + // different types of agents are in different pools + if (Agent !== this.httpModule.Agent) { + poolKey += Agent.name + } + + if (!this.httpModule.globalAgent) { + // node 0.4.x + options.host = this.host + options.port = this.port + if (poolKey) poolKey += ':' + poolKey += this.host + ':' + this.port + } + + // ca option is only relevant if proxy or destination are https + var proxy = this.proxy + if (typeof proxy === 'string') proxy = url.parse(proxy) + var caRelevant = (proxy && proxy.protocol === 'https:') || this.uri.protocol === 'https:' + if (options.ca && caRelevant) { + if (poolKey) poolKey += ':' + poolKey += options.ca + } + + if (!poolKey && Agent === this.httpModule.Agent && this.httpModule.globalAgent) { + // not doing anything special. Use the globalAgent + return this.httpModule.globalAgent + } + + // we're using a stored agent. Make sure it's protocol-specific + poolKey = this.uri.protocol + poolKey + + // already generated an agent for this setting + if (this.pool[poolKey]) return this.pool[poolKey] + + return this.pool[poolKey] = new Agent(options) +} + +Request.prototype.start = function () { + var self = this + + if (self._aborted) return + + self._started = true + self.method = self.method || 'GET' + self.href = self.uri.href + if (log) log('%method %href', self) + + if (self.src && self.src.stat && self.src.stat.size && !self.headers['content-length'] && !self.headers['Content-Length']) { + self.headers['content-length'] = self.src.stat.size + } + if (self._aws) { + self.aws(self._aws, true) + } + self.req = self.httpModule.request(self, function (response) { + if (response.connection.listeners('error').indexOf(self._parserErrorHandler) === -1) { + response.connection.once('error', self._parserErrorHandler) + } + if (self._aborted) return + if (self._paused) response.pause() + + self.response = response + response.request = self + response.toJSON = toJSON + + if (self.httpModule === https && + self.strictSSL && + !response.client.authorized) { + var sslErr = response.client.authorizationError + self.emit('error', new Error('SSL Error: '+ sslErr)) + return + } + + if (self.setHost) delete self.headers.host + if (self.timeout && self.timeoutTimer) { + clearTimeout(self.timeoutTimer) + self.timeoutTimer = null + } + + var addCookie = function (cookie) { + if (self._jar) self._jar.add(new Cookie(cookie)) + else cookieJar.add(new Cookie(cookie)) + } + + if (response.headers['set-cookie'] && (!self._disableCookies)) { + if (Array.isArray(response.headers['set-cookie'])) response.headers['set-cookie'].forEach(addCookie) + else addCookie(response.headers['set-cookie']) + } + + if (response.statusCode >= 300 && response.statusCode < 400 && + (self.followAllRedirects || + (self.followRedirect && (self.method !== 'PUT' && self.method !== 'POST' && self.method !== 'DELETE'))) && + response.headers.location) { + if (self._redirectsFollowed >= self.maxRedirects) { + self.emit('error', new Error("Exceeded maxRedirects. Probably stuck in a redirect loop "+self.uri.href)) + return + } + self._redirectsFollowed += 1 + + if (!isUrl.test(response.headers.location)) { + response.headers.location = url.resolve(self.uri.href, response.headers.location) + } + + var uriPrev = self.uri + self.uri = url.parse(response.headers.location) + + // handle the case where we change protocol from https to http or vice versa + if (self.uri.protocol !== uriPrev.protocol) { + self._updateProtocol() + } + + self.redirects.push( + { statusCode : response.statusCode + , redirectUri: response.headers.location + } + ) + if (self.followAllRedirects) self.method = 'GET' + // self.method = 'GET' // Force all redirects to use GET || commented out fixes #215 + delete self.src + delete self.req + delete self.agent + delete self._started + delete self.body + delete self._form + if (self.headers) { + delete self.headers.host + delete self.headers['content-type'] + delete self.headers['content-length'] + } + if (log) log('Redirect to %uri', self) + self.init() + return // Ignore the rest of the response + } else { + self._redirectsFollowed = self._redirectsFollowed || 0 + // Be a good stream and emit end when the response is finished. + // Hack to emit end on close because of a core bug that never fires end + response.on('close', function () { + if (!self._ended) self.response.emit('end') + }) + + if (self.encoding) { + if (self.dests.length !== 0) { + console.error("Ingoring encoding parameter as this stream is being piped to another stream which makes the encoding option invalid.") + } else { + response.setEncoding(self.encoding) + } + } + + self.dests.forEach(function (dest) { + self.pipeDest(dest) + }) + + response.on("data", function (chunk) { + self._destdata = true + self.emit("data", chunk) + }) + response.on("end", function (chunk) { + self._ended = true + self.emit("end", chunk) + }) + response.on("close", function () {self.emit("close")}) + + self.emit('response', response) + + if (self.callback) { + var buffer = [] + var bodyLen = 0 + self.on("data", function (chunk) { + buffer.push(chunk) + bodyLen += chunk.length + }) + self.on("end", function () { + if (self._aborted) return + + if (buffer.length && Buffer.isBuffer(buffer[0])) { + var body = new Buffer(bodyLen) + var i = 0 + buffer.forEach(function (chunk) { + chunk.copy(body, i, 0, chunk.length) + i += chunk.length + }) + if (self.encoding === null) { + response.body = body + } else { + response.body = body.toString(self.encoding) + } + } else if (buffer.length) { + response.body = buffer.join('') + } + + if (self._json) { + try { + response.body = JSON.parse(response.body) + } catch (e) {} + } + + self.emit('complete', response, response.body) + }) + } + } + }) + + if (self.timeout && !self.timeoutTimer) { + self.timeoutTimer = setTimeout(function () { + self.req.abort() + var e = new Error("ETIMEDOUT") + e.code = "ETIMEDOUT" + self.emit("error", e) + }, self.timeout) + + // Set additional timeout on socket - in case if remote + // server freeze after sending headers + if (self.req.setTimeout) { // only works on node 0.6+ + self.req.setTimeout(self.timeout, function () { + if (self.req) { + self.req.abort() + var e = new Error("ESOCKETTIMEDOUT") + e.code = "ESOCKETTIMEDOUT" + self.emit("error", e) + } + }) + } + } + + self.req.on('error', self.clientErrorHandler) + self.req.on('drain', function() { + self.emit('drain') + }) + self.on('end', function() { + if ( self.req.connection ) self.req.connection.removeListener('error', self._parserErrorHandler) + }) + self.emit('request', self.req) +} + +Request.prototype.abort = function () { + this._aborted = true + + if (this.req) { + this.req.abort() + } + else if (this.response) { + this.response.abort() + } + + this.emit("abort") +} + +Request.prototype.pipeDest = function (dest) { + var response = this.response + // Called after the response is received + if (dest.headers) { + dest.headers['content-type'] = response.headers['content-type'] + if (response.headers['content-length']) { + dest.headers['content-length'] = response.headers['content-length'] + } + } + if (dest.setHeader) { + for (var i in response.headers) { + dest.setHeader(i, response.headers[i]) + } + dest.statusCode = response.statusCode + } + if (this.pipefilter) this.pipefilter(response, dest) +} + +// Composable API +Request.prototype.setHeader = function (name, value, clobber) { + if (clobber === undefined) clobber = true + if (clobber || !this.headers.hasOwnProperty(name)) this.headers[name] = value + else this.headers[name] += ',' + value + return this +} +Request.prototype.setHeaders = function (headers) { + for (var i in headers) {this.setHeader(i, headers[i])} + return this +} +Request.prototype.qs = function (q, clobber) { + var base + if (!clobber && this.uri.query) base = qs.parse(this.uri.query) + else base = {} + + for (var i in q) { + base[i] = q[i] + } + + this.uri = url.parse(this.uri.href.split('?')[0] + '?' + qs.stringify(base)) + this.url = this.uri + + return this +} +Request.prototype.form = function (form) { + if (form) { + this.headers['content-type'] = 'application/x-www-form-urlencoded; charset=utf-8' + this.body = qs.stringify(form).toString('utf8') + return this + } + // create form-data object + this._form = new FormData() + return this._form +} +Request.prototype.multipart = function (multipart) { + var self = this + self.body = [] + + if (!self.headers['content-type']) { + self.headers['content-type'] = 'multipart/related; boundary=' + self.boundary + } else { + self.headers['content-type'] = self.headers['content-type'].split(';')[0] + '; boundary=' + self.boundary + } + + if (!multipart.forEach) throw new Error('Argument error, options.multipart.') + + if (self.preambleCRLF) { + self.body.push(new Buffer('\r\n')) + } + + multipart.forEach(function (part) { + var body = part.body + if(body == null) throw Error('Body attribute missing in multipart.') + delete part.body + var preamble = '--' + self.boundary + '\r\n' + Object.keys(part).forEach(function (key) { + preamble += key + ': ' + part[key] + '\r\n' + }) + preamble += '\r\n' + self.body.push(new Buffer(preamble)) + self.body.push(new Buffer(body)) + self.body.push(new Buffer('\r\n')) + }) + self.body.push(new Buffer('--' + self.boundary + '--')) + return self +} +Request.prototype.json = function (val) { + this.setHeader('accept', 'application/json') + this._json = true + if (typeof val === 'boolean') { + if (typeof this.body === 'object') { + this.setHeader('content-type', 'application/json') + this.body = JSON.stringify(this.body) + } + } else { + this.setHeader('content-type', 'application/json') + this.body = JSON.stringify(val) + } + return this +} +function getHeader(name, headers) { + var result, re, match + Object.keys(headers).forEach(function (key) { + re = new RegExp(name, 'i') + match = key.match(re) + if (match) result = headers[key] + }) + return result +} +Request.prototype.aws = function (opts, now) { + if (!now) { + this._aws = opts + return this + } + var date = new Date() + this.setHeader('date', date.toUTCString()) + var auth = + { key: opts.key + , secret: opts.secret + , verb: this.method.toUpperCase() + , date: date + , contentType: getHeader('content-type', this.headers) || '' + , md5: getHeader('content-md5', this.headers) || '' + , amazonHeaders: aws.canonicalizeHeaders(this.headers) + } + if (opts.bucket && this.path) { + auth.resource = '/' + opts.bucket + this.path + } else if (opts.bucket && !this.path) { + auth.resource = '/' + opts.bucket + } else if (!opts.bucket && this.path) { + auth.resource = this.path + } else if (!opts.bucket && !this.path) { + auth.resource = '/' + } + auth.resource = aws.canonicalizeResource(auth.resource) + this.setHeader('authorization', aws.authorization(auth)) + + return this +} + +Request.prototype.oauth = function (_oauth) { + var form + if (this.headers['content-type'] && + this.headers['content-type'].slice(0, 'application/x-www-form-urlencoded'.length) === + 'application/x-www-form-urlencoded' + ) { + form = qs.parse(this.body) + } + if (this.uri.query) { + form = qs.parse(this.uri.query) + } + if (!form) form = {} + var oa = {} + for (var i in form) oa[i] = form[i] + for (var i in _oauth) oa['oauth_'+i] = _oauth[i] + if (!oa.oauth_version) oa.oauth_version = '1.0' + if (!oa.oauth_timestamp) oa.oauth_timestamp = Math.floor( (new Date()).getTime() / 1000 ).toString() + if (!oa.oauth_nonce) oa.oauth_nonce = uuid().replace(/-/g, '') + + oa.oauth_signature_method = 'HMAC-SHA1' + + var consumer_secret = oa.oauth_consumer_secret + delete oa.oauth_consumer_secret + var token_secret = oa.oauth_token_secret + delete oa.oauth_token_secret + + var baseurl = this.uri.protocol + '//' + this.uri.host + this.uri.pathname + var signature = oauth.hmacsign(this.method, baseurl, oa, consumer_secret, token_secret) + + // oa.oauth_signature = signature + for (var i in form) { + if ( i.slice(0, 'oauth_') in _oauth) { + // skip + } else { + delete oa['oauth_'+i] + if (i !== 'x_auth_mode') delete oa[i] + } + } + this.headers.Authorization = + 'OAuth '+Object.keys(oa).sort().map(function (i) {return i+'="'+oauth.rfc3986(oa[i])+'"'}).join(',') + this.headers.Authorization += ',oauth_signature="' + oauth.rfc3986(signature) + '"' + return this +} +Request.prototype.jar = function (jar) { + var cookies + + if (this._redirectsFollowed === 0) { + this.originalCookieHeader = this.headers.cookie + } + + if (jar === false) { + // disable cookies + cookies = false + this._disableCookies = true + } else if (jar) { + // fetch cookie from the user defined cookie jar + cookies = jar.get({ url: this.uri.href }) + } else { + // fetch cookie from the global cookie jar + cookies = cookieJar.get({ url: this.uri.href }) + } + + if (cookies && cookies.length) { + var cookieString = cookies.map(function (c) { + return c.name + "=" + c.value + }).join("; ") + + if (this.originalCookieHeader) { + // Don't overwrite existing Cookie header + this.headers.cookie = this.originalCookieHeader + '; ' + cookieString + } else { + this.headers.cookie = cookieString + } + } + this._jar = jar + return this +} + + +// Stream API +Request.prototype.pipe = function (dest, opts) { if (this.response) { if (this._destdata) { throw new Error("You cannot pipe after data has been emitted from the response.") } else if (this._ended) { throw new Error("You cannot pipe after the response has been ended.") } else { - stream.Stream.prototype.pipe.call(this, dest) + stream.Stream.prototype.pipe.call(this, dest, opts) this.pipeDest(dest) return dest } } else { this.dests.push(dest) - stream.Stream.prototype.pipe.call(this, dest) + stream.Stream.prototype.pipe.call(this, dest, opts) return dest } } Request.prototype.write = function () { if (!this._started) this.start() - if (!this.req) throw new Error("This request has been piped before http.request() was called.") - this.req.write.apply(this.req, arguments) + return this.req.write.apply(this.req, arguments) } -Request.prototype.end = function () { +Request.prototype.end = function (chunk) { + if (chunk) this.write(chunk) if (!this._started) this.start() - if (!this.req) throw new Error("This request has been piped before http.request() was called.") - this.req.end.apply(this.req, arguments) + this.req.end() } Request.prototype.pause = function () { - if (!this.response) throw new Error("This request has been piped before http.request() was called.") - this.response.pause.apply(this.response, arguments) + if (!this.response) this._paused = true + else this.response.pause.apply(this.response, arguments) } Request.prototype.resume = function () { - if (!this.response) throw new Error("This request has been piped before http.request() was called.") - this.response.resume.apply(this.response, arguments) + if (!this.response) this._paused = false + else this.response.resume.apply(this.response, arguments) +} +Request.prototype.destroy = function () { + if (!this._ended) this.end() } -function request (options, callback) { - if (typeof options === 'string') options = {uri:options} +// organize params for post, put, head, del +function initParams(uri, options, callback) { + if ((typeof options === 'function') && !callback) callback = options + if (options && typeof options === 'object') { + options.uri = uri + } else if (typeof uri === 'string') { + options = {uri:uri} + } else { + options = uri + uri = options.uri + } + return { uri: uri, options: options, callback: callback } +} + +function request (uri, options, callback) { + if (typeof uri === 'undefined') throw new Error('undefined is not a valid uri or options object.') + if ((typeof options === 'function') && !callback) callback = options + if (options && typeof options === 'object') { + options.uri = uri + } else if (typeof uri === 'string') { + options = {uri:uri} + } else { + options = uri + } + if (callback) options.callback = callback var r = new Request(options) - r.request() return r } module.exports = request -request.defaults = function (options) { +request.initParams = initParams + +request.defaults = function (options, requester) { var def = function (method) { - var d = function (opts, callback) { - if (typeof opts === 'string') opts = {uri:opts} + var d = function (uri, opts, callback) { + var params = initParams(uri, opts, callback) for (var i in options) { - if (opts[i] === undefined) opts[i] = options[i] + if (params.options[i] === undefined) params.options[i] = options[i] } - return method(opts, callback) + if(typeof requester === 'function') { + if(method === request) { + method = requester + } else { + params.options._requester = requester + } + } + return method(params.options, params.callback) } return d } @@ -554,38 +1025,99 @@ request.defaults = function (options) { de.head = def(request.head) de.del = def(request.del) de.cookie = def(request.cookie) - de.jar = def(request.jar) + de.jar = request.jar return de } +request.forever = function (agentOptions, optionsArg) { + var options = {} + if (optionsArg) { + for (option in optionsArg) { + options[option] = optionsArg[option] + } + } + if (agentOptions) options.agentOptions = agentOptions + options.forever = true + return request.defaults(options) +} + request.get = request -request.post = function (options, callback) { - if (typeof options === 'string') options = {uri:options} - options.method = 'POST' - return request(options, callback) +request.post = function (uri, options, callback) { + var params = initParams(uri, options, callback) + params.options.method = 'POST' + return request(params.uri || null, params.options, params.callback) } -request.put = function (options, callback) { - if (typeof options === 'string') options = {uri:options} - options.method = 'PUT' - return request(options, callback) +request.put = function (uri, options, callback) { + var params = initParams(uri, options, callback) + params.options.method = 'PUT' + return request(params.uri || null, params.options, params.callback) } -request.head = function (options, callback) { - if (typeof options === 'string') options = {uri:options} - options.method = 'HEAD' - if (options.body || options.requestBodyStream || options.json || options.multipart) { +request.head = function (uri, options, callback) { + var params = initParams(uri, options, callback) + params.options.method = 'HEAD' + if (params.options.body || + params.options.requestBodyStream || + (params.options.json && typeof params.options.json !== 'boolean') || + params.options.multipart) { throw new Error("HTTP HEAD requests MUST NOT include a request body.") } - return request(options, callback) + return request(params.uri || null, params.options, params.callback) } -request.del = function (options, callback) { - if (typeof options === 'string') options = {uri:options} - options.method = 'DELETE' - return request(options, callback) +request.del = function (uri, options, callback) { + var params = initParams(uri, options, callback) + params.options.method = 'DELETE' + if(typeof params.options._requester === 'function') { + request = params.options._requester + } + return request(params.uri || null, params.options, params.callback) } request.jar = function () { return new CookieJar } request.cookie = function (str) { + if (str && str.uri) str = str.uri if (typeof str !== 'string') throw new Error("The cookie function only accepts STRING as param") return new Cookie(str) } + +// Safe toJSON + +function getSafe (self, uuid) { + if (typeof self === 'object' || typeof self === 'function') var safe = {} + if (Array.isArray(self)) var safe = [] + + var recurse = [] + + Object.defineProperty(self, uuid, {}) + + var attrs = Object.keys(self).filter(function (i) { + if (i === uuid) return false + if ( (typeof self[i] !== 'object' && typeof self[i] !== 'function') || self[i] === null) return true + return !(Object.getOwnPropertyDescriptor(self[i], uuid)) + }) + + + for (var i=0;i" -, "repository" : - { "type" : "git" - , "url" : "http://github.com/mikeal/request.git" - } -, "bugs" : - { "url" : "http://github.com/mikeal/request/issues" } -, "engines" : ["node >= 0.3.6"] -, "main" : "./main" -, "scripts": { "test": "bash tests/run.sh" } +{ + "name": "request", + "description": "Simplified HTTP request client.", + "tags": [ + "http", + "simple", + "util", + "utility" + ], + "version": "2.12.0", + "author": { + "name": "Mikeal Rogers", + "email": "mikeal.rogers@gmail.com" + }, + "repository": { + "type": "git", + "url": "http://github.com/mikeal/request.git" + }, + "bugs": { + "url": "http://github.com/mikeal/request/issues" + }, + "engines": [ + "node >= 0.3.6" + ], + "main": "./main", + "dependencies": { + "form-data": "~0.0.3", + "mime": "~1.2.7" + }, + "bundleDependencies": [ + "form-data", + "mime" + ], + "scripts": { + "test": "node tests/run.js" + }, + "readme": "# Request -- Simplified HTTP request method\n\n## Install\n\n
\n  npm install request\n
\n\nOr from source:\n\n
\n  git clone git://github.com/mikeal/request.git \n  cd request\n  npm link\n
\n\n## Super simple to use\n\nRequest is designed to be the simplest way possible to make http calls. It supports HTTPS and follows redirects by default.\n\n```javascript\nvar request = require('request');\nrequest('http://www.google.com', function (error, response, body) {\n if (!error && response.statusCode == 200) {\n console.log(body) // Print the google web page.\n }\n})\n```\n\n## Streaming\n\nYou can stream any response to a file stream.\n\n```javascript\nrequest('http://google.com/doodle.png').pipe(fs.createWriteStream('doodle.png'))\n```\n\nYou can also stream a file to a PUT or POST request. This method will also check the file extension against a mapping of file extensions to content-types, in this case `application/json`, and use the proper content-type in the PUT request if one is not already provided in the headers.\n\n```javascript\nfs.createReadStream('file.json').pipe(request.put('http://mysite.com/obj.json'))\n```\n\nRequest can also pipe to itself. When doing so the content-type and content-length will be preserved in the PUT headers.\n\n```javascript\nrequest.get('http://google.com/img.png').pipe(request.put('http://mysite.com/img.png'))\n```\n\nNow let's get fancy.\n\n```javascript\nhttp.createServer(function (req, resp) {\n if (req.url === '/doodle.png') {\n if (req.method === 'PUT') {\n req.pipe(request.put('http://mysite.com/doodle.png'))\n } else if (req.method === 'GET' || req.method === 'HEAD') {\n request.get('http://mysite.com/doodle.png').pipe(resp)\n } \n }\n})\n```\n\nYou can also pipe() from a http.ServerRequest instance and to a http.ServerResponse instance. The HTTP method and headers will be sent as well as the entity-body data. Which means that, if you don't really care about security, you can do:\n\n```javascript\nhttp.createServer(function (req, resp) {\n if (req.url === '/doodle.png') {\n var x = request('http://mysite.com/doodle.png')\n req.pipe(x)\n x.pipe(resp)\n }\n})\n```\n\nAnd since pipe() returns the destination stream in node 0.5.x you can do one line proxying :)\n\n```javascript\nreq.pipe(request('http://mysite.com/doodle.png')).pipe(resp)\n```\n\nAlso, none of this new functionality conflicts with requests previous features, it just expands them.\n\n```javascript\nvar r = request.defaults({'proxy':'http://localproxy.com'})\n\nhttp.createServer(function (req, resp) {\n if (req.url === '/doodle.png') {\n r.get('http://google.com/doodle.png').pipe(resp)\n }\n})\n```\nYou can still use intermediate proxies, the requests will still follow HTTP forwards, etc.\n\n## Forms\n\n`request` supports `application/x-www-form-urlencoded` and `multipart/form-data` form uploads. For `multipart/related` refer to the `multipart` API.\n\nUrl encoded forms are simple\n\n```javascript\nrequest.post('http://service.com/upload', {form:{key:'value'}})\n// or\nrequest.post('http://service.com/upload').form({key:'value'})\n```\n\nFor `multipart/form-data` we use the [form-data](https://github.com/felixge/node-form-data) library by [@felixge](https://github.com/felixge). You don't need to worry about piping the form object or setting the headers, `request` will handle that for you.\n\n```javascript\nvar r = request.post('http://service.com/upload')\nvar form = r.form()\nform.append('my_field', 'my_value')\nform.append('my_buffer', new Buffer([1, 2, 3]))\nform.append('my_file', fs.createReadStream(path.join(__dirname, 'doodle.png'))\nform.append('remote_file', request('http://google.com/doodle.png'))\n```\n\n## OAuth Signing\n\n```javascript\n// Twitter OAuth\nvar qs = require('querystring')\n , oauth =\n { callback: 'http://mysite.com/callback/'\n , consumer_key: CONSUMER_KEY\n , consumer_secret: CONSUMER_SECRET\n }\n , url = 'https://api.twitter.com/oauth/request_token'\n ;\nrequest.post({url:url, oauth:oauth}, function (e, r, body) {\n // Assume by some stretch of magic you aquired the verifier\n var access_token = qs.parse(body)\n , oauth = \n { consumer_key: CONSUMER_KEY\n , consumer_secret: CONSUMER_SECRET\n , token: access_token.oauth_token\n , verifier: VERIFIER\n , token_secret: access_token.oauth_token_secret\n }\n , url = 'https://api.twitter.com/oauth/access_token'\n ;\n request.post({url:url, oauth:oauth}, function (e, r, body) {\n var perm_token = qs.parse(body)\n , oauth = \n { consumer_key: CONSUMER_KEY\n , consumer_secret: CONSUMER_SECRET\n , token: perm_token.oauth_token\n , token_secret: perm_token.oauth_token_secret\n }\n , url = 'https://api.twitter.com/1/users/show.json?'\n , params = \n { screen_name: perm_token.screen_name\n , user_id: perm_token.user_id\n }\n ;\n url += qs.stringify(params)\n request.get({url:url, oauth:oauth, json:true}, function (e, r, user) {\n console.log(user)\n })\n })\n})\n```\n\n\n\n### request(options, callback)\n\nThe first argument can be either a url or an options object. The only required option is uri, all others are optional.\n\n* `uri` || `url` - fully qualified uri or a parsed url object from url.parse()\n* `qs` - object containing querystring values to be appended to the uri\n* `method` - http method, defaults to GET\n* `headers` - http headers, defaults to {}\n* `body` - entity body for POST and PUT requests. Must be buffer or string.\n* `form` - when passed an object this will set `body` but to a querystring representation of value and adds `Content-type: application/x-www-form-urlencoded; charset=utf-8` header. When passed no option a FormData instance is returned that will be piped to request.\n* `json` - sets `body` but to JSON representation of value and adds `Content-type: application/json` header. Additionally, parses the response body as json.\n* `multipart` - (experimental) array of objects which contains their own headers and `body` attribute. Sends `multipart/related` request. See example below.\n* `followRedirect` - follow HTTP 3xx responses as redirects. defaults to true.\n* `followAllRedirects` - follow non-GET HTTP 3xx responses as redirects. defaults to false.\n* `maxRedirects` - the maximum number of redirects to follow, defaults to 10.\n* `encoding` - Encoding to be used on `setEncoding` of response data. If set to `null`, the body is returned as a Buffer.\n* `pool` - A hash object containing the agents for these requests. If omitted this request will use the global pool which is set to node's default maxSockets.\n* `pool.maxSockets` - Integer containing the maximum amount of sockets in the pool.\n* `timeout` - Integer containing the number of milliseconds to wait for a request to respond before aborting the request\t\n* `proxy` - An HTTP proxy to be used. Support proxy Auth with Basic Auth the same way it's supported with the `url` parameter by embedding the auth info in the uri.\n* `oauth` - Options for OAuth HMAC-SHA1 signing, see documentation above.\n* `strictSSL` - Set to `true` to require that SSL certificates be valid. Note: to use your own certificate authority, you need to specify an agent that was created with that ca as an option.\n* `jar` - Set to `false` if you don't want cookies to be remembered for future use or define your custom cookie jar (see examples section)\n* `aws` - object containing aws signing information, should have the properties `key` and `secret` as well as `bucket` unless you're specifying your bucket as part of the path, or you are making a request that doesn't use a bucket (i.e. GET Services)\n\n\nThe callback argument gets 3 arguments. The first is an error when applicable (usually from the http.Client option not the http.ClientRequest object). The second in an http.ClientResponse object. The third is the response body String or Buffer.\n\n## Convenience methods\n\nThere are also shorthand methods for different HTTP METHODs and some other conveniences.\n\n### request.defaults(options) \n \nThis method returns a wrapper around the normal request API that defaults to whatever options you pass in to it.\n\n### request.put\n\nSame as request() but defaults to `method: \"PUT\"`.\n\n```javascript\nrequest.put(url)\n```\n\n### request.post\n\nSame as request() but defaults to `method: \"POST\"`.\n\n```javascript\nrequest.post(url)\n```\n\n### request.head\n\nSame as request() but defaults to `method: \"HEAD\"`.\n\n```javascript\nrequest.head(url)\n```\n\n### request.del\n\nSame as request() but defaults to `method: \"DELETE\"`.\n\n```javascript\nrequest.del(url)\n```\n\n### request.get\n\nAlias to normal request method for uniformity.\n\n```javascript\nrequest.get(url)\n```\n### request.cookie\n\nFunction that creates a new cookie.\n\n```javascript\nrequest.cookie('cookie_string_here')\n```\n### request.jar\n\nFunction that creates a new cookie jar.\n\n```javascript\nrequest.jar()\n```\n\n\n## Examples:\n\n```javascript\n var request = require('request')\n , rand = Math.floor(Math.random()*100000000).toString()\n ;\n request(\n { method: 'PUT'\n , uri: 'http://mikeal.iriscouch.com/testjs/' + rand\n , multipart: \n [ { 'content-type': 'application/json'\n , body: JSON.stringify({foo: 'bar', _attachments: {'message.txt': {follows: true, length: 18, 'content_type': 'text/plain' }}})\n }\n , { body: 'I am an attachment' }\n ] \n }\n , function (error, response, body) {\n if(response.statusCode == 201){\n console.log('document saved as: http://mikeal.iriscouch.com/testjs/'+ rand)\n } else {\n console.log('error: '+ response.statusCode)\n console.log(body)\n }\n }\n )\n```\nCookies are enabled by default (so they can be used in subsequent requests). To disable cookies set jar to false (either in defaults or in the options sent).\n\n```javascript\nvar request = request.defaults({jar: false})\nrequest('http://www.google.com', function () {\n request('http://images.google.com')\n})\n```\n\nIf you to use a custom cookie jar (instead of letting request use its own global cookie jar) you do so by setting the jar default or by specifying it as an option:\n\n```javascript\nvar j = request.jar()\nvar request = request.defaults({jar:j})\nrequest('http://www.google.com', function () {\n request('http://images.google.com')\n})\n```\nOR\n\n```javascript\nvar j = request.jar()\nvar cookie = request.cookie('your_cookie_here')\nj.add(cookie)\nrequest({url: 'http://www.google.com', jar: j}, function () {\n request('http://images.google.com')\n})\n```\n", + "readmeFilename": "README.md", + "_id": "request@2.12.0", + "_from": "request" } diff --git a/node_modules/request/tests/run.sh b/node_modules/request/tests/run.sh deleted file mode 100755 index 57d0f64..0000000 --- a/node_modules/request/tests/run.sh +++ /dev/null @@ -1,6 +0,0 @@ -FAILS=0 -for i in tests/test-*.js; do - echo $i - node $i || let FAILS++ -done -exit $FAILS diff --git a/node_modules/request/tests/server.js b/node_modules/request/tests/server.js index bad1e50..b6eacba 100644 --- a/node_modules/request/tests/server.js +++ b/node_modules/request/tests/server.js @@ -1,4 +1,7 @@ -var http = require('http') +var fs = require('fs') + , http = require('http') + , path = require('path') + , https = require('https') , events = require('events') , stream = require('stream') , assert = require('assert') @@ -14,6 +17,28 @@ exports.createServer = function (port) { return s; } +exports.createSSLServer = function(port, opts) { + port = port || 16767 + + var options = { 'key' : path.join(__dirname, 'ssl', 'test.key') + , 'cert': path.join(__dirname, 'ssl', 'test.crt') + } + if (opts) { + for (var i in opts) options[i] = opts[i] + } + + for (var i in options) { + options[i] = fs.readFileSync(options[i]) + } + + var s = https.createServer(options, function (req, resp) { + s.emit(req.url, req, resp); + }) + s.port = port + s.url = 'https://localhost:'+port + return s; +} + exports.createPostStream = function (text) { var postStream = new stream.Stream(); postStream.writeable = true; @@ -21,16 +46,24 @@ exports.createPostStream = function (text) { setTimeout(function () {postStream.emit('data', new Buffer(text)); postStream.emit('end')}, 0); return postStream; } -exports.createPostValidator = function (text) { +exports.createPostValidator = function (text, reqContentType) { var l = function (req, resp) { var r = ''; req.on('data', function (chunk) {r += chunk}) req.on('end', function () { - if (r !== text) console.log(r, text); - assert.equal(r, text) - resp.writeHead(200, {'content-type':'text/plain'}) - resp.write('OK') - resp.end() + if (req.headers['content-type'] && req.headers['content-type'].indexOf('boundary=') >= 0) { + var boundary = req.headers['content-type'].split('boundary=')[1]; + text = text.replace(/__BOUNDARY__/g, boundary); + } + if (r !== text) console.log(r, text); + assert.equal(r, text) + if (reqContentType) { + assert.ok(req.headers['content-type']) + assert.ok(~req.headers['content-type'].indexOf(reqContentType)) + } + resp.writeHead(200, {'content-type':'text/plain'}) + resp.write('OK') + resp.end() }) } return l; diff --git a/node_modules/request/tests/test-body.js b/node_modules/request/tests/test-body.js index 18ad5b9..a624397 100644 --- a/node_modules/request/tests/test-body.js +++ b/node_modules/request/tests/test-body.js @@ -25,11 +25,21 @@ var tests = ]) , expectBody: "Ω☃" } - , testGetJSON : - { resp : server.createGetResponse('{"test":true}', 'application/json') - , json : true - , expectBody: {"test":true} + , testGetBuffer : + { resp : server.createGetResponse(new Buffer("TESTING!")) + , encoding: null + , expectBody: new Buffer("TESTING!") } + , testGetEncoding : + { resp : server.createGetResponse(new Buffer('efa3bfcea9e29883', 'hex')) + , encoding: 'hex' + , expectBody: "efa3bfcea9e29883" + } + , testGetJSON : + { resp : server.createGetResponse('{"test":true}', 'application/json') + , json : true + , expectBody: {"test":true} + } , testPutString : { resp : server.createPostValidator("PUTTINGDATA") , method : "PUT" @@ -47,13 +57,13 @@ var tests = } , testPutMultipart : { resp: server.createPostValidator( - '--frontier\r\n' + + '--__BOUNDARY__\r\n' + 'content-type: text/html\r\n' + '\r\n' + 'Oh hi.' + - '\r\n--frontier\r\n\r\n' + + '\r\n--__BOUNDARY__\r\n\r\n' + 'Oh hi.' + - '\r\n--frontier--' + '\r\n--__BOUNDARY__--' ) , method: "PUT" , multipart: @@ -61,6 +71,23 @@ var tests = , {'body': 'Oh hi.'} ] } + , testPutMultipartPreambleCRLF : + { resp: server.createPostValidator( + '\r\n--__BOUNDARY__\r\n' + + 'content-type: text/html\r\n' + + '\r\n' + + 'Oh hi.' + + '\r\n--__BOUNDARY__\r\n\r\n' + + 'Oh hi.' + + '\r\n--__BOUNDARY__--' + ) + , method: "PUT" + , preambleCRLF: true + , multipart: + [ {'content-type': 'text/html', 'body': 'Oh hi.'} + , {'body': 'Oh hi.'} + ] + } } s.listen(s.port, function () { diff --git a/node_modules/request/tests/test-cookie.js b/node_modules/request/tests/test-cookie.js index aeafd10..6c6a7a7 100644 --- a/node_modules/request/tests/test-cookie.js +++ b/node_modules/request/tests/test-cookie.js @@ -1,7 +1,7 @@ var Cookie = require('../vendor/cookie') , assert = require('assert'); -var str = 'sid=s543qactge.wKE61E01Bs%2BKhzmxrwrnug; path=/; httpOnly; expires=Sat, 04 Dec 2010 23:27:28 GMT'; +var str = 'Sid="s543qactge.wKE61E01Bs%2BKhzmxrwrnug="; Path=/; httpOnly; Expires=Sat, 04 Dec 2010 23:27:28 GMT'; var cookie = new Cookie(str); // test .toString() @@ -14,10 +14,10 @@ assert.equal(cookie.path, '/'); assert.equal(cookie.httpOnly, true); // test .name -assert.equal(cookie.name, 'sid'); +assert.equal(cookie.name, 'Sid'); // test .value -assert.equal(cookie.value, 's543qactge.wKE61E01Bs%2BKhzmxrwrnug'); +assert.equal(cookie.value, '"s543qactge.wKE61E01Bs%2BKhzmxrwrnug="'); // test .expires assert.equal(cookie.expires instanceof Date, true); diff --git a/node_modules/request/tests/test-errors.js b/node_modules/request/tests/test-errors.js index a7db1f7..1986a59 100644 --- a/node_modules/request/tests/test-errors.js +++ b/node_modules/request/tests/test-errors.js @@ -27,4 +27,11 @@ try { assert.equal(e.message, 'Body attribute missing in multipart.') } +try { + request(local, {multipart: [{}]}) + assert.fail("Should have throw") +} catch(e) { + assert.equal(e.message, 'Body attribute missing in multipart.') +} + console.log("All tests passed.") diff --git a/node_modules/request/tests/test-oauth.js b/node_modules/request/tests/test-oauth.js index 7d969a0..72ca923 100644 --- a/node_modules/request/tests/test-oauth.js +++ b/node_modules/request/tests/test-oauth.js @@ -6,7 +6,7 @@ var hmacsign = require('../oauth').hmacsign function getsignature (r) { var sign - r.headers.authorization.slice('OAuth '.length).replace(/,\ /g, ',').split(',').forEach(function (v) { + r.headers.Authorization.slice('OAuth '.length).replace(/,\ /g, ',').split(',').forEach(function (v) { if (v.slice(0, 'oauth_signature="'.length) === 'oauth_signature="') sign = v.slice('oauth_signature="'.length, -1) }) return decodeURIComponent(sign) @@ -56,7 +56,7 @@ console.log('yOahq5m0YjDDjfjxHaXEsW9D+X0=') assert.equal(upsign, 'yOahq5m0YjDDjfjxHaXEsW9D+X0=') -var r = request.post( +var rsign = request.post( { url: 'https://api.twitter.com/oauth/request_token' , oauth: { callback: 'http://localhost:3005/the_dance/process_callback?service_provider_id=11' @@ -68,10 +68,12 @@ var r = request.post( } }) -console.log(getsignature(r)) -assert.equal(reqsign, getsignature(r)) +setTimeout(function () { + console.log(getsignature(rsign)) + assert.equal(reqsign, getsignature(rsign)) +}) -var r = request.post( +var raccsign = request.post( { url: 'https://api.twitter.com/oauth/access_token' , oauth: { consumer_key: 'GDdmIQH6jhtmLUypg82g' @@ -86,10 +88,12 @@ var r = request.post( } }) -console.log(getsignature(r)) -assert.equal(accsign, getsignature(r)) +setTimeout(function () { + console.log(getsignature(raccsign)) + assert.equal(accsign, getsignature(raccsign)) +}, 1) -var r = request.post( +var rupsign = request.post( { url: 'http://api.twitter.com/1/statuses/update.json' , oauth: { consumer_key: "GDdmIQH6jhtmLUypg82g" @@ -103,7 +107,11 @@ var r = request.post( } , form: {status: 'setting up my twitter 私のさえずりを設定する'} }) +setTimeout(function () { + console.log(getsignature(rupsign)) + assert.equal(upsign, getsignature(rupsign)) +}, 1) + + -console.log(getsignature(r)) -assert.equal(upsign, getsignature(r)) diff --git a/node_modules/request/tests/test-pipes.js b/node_modules/request/tests/test-pipes.js index 0774647..7162981 100644 --- a/node_modules/request/tests/test-pipes.js +++ b/node_modules/request/tests/test-pipes.js @@ -58,6 +58,20 @@ s.listen(s.port, function () { mydata.emit('data', 'mydata'); mydata.emit('end'); + // Test pipeing to a request object with a json body + s.once('/push-json', server.createPostValidator("{\"foo\":\"bar\"}", "application/json")); + + var mybodydata = new stream.Stream(); + mybodydata.readable = true + + counter++ + var r2 = request.put({url:'http://localhost:3453/push-json',json:true}, function () { + check(); + }) + mybodydata.pipe(r2) + + mybodydata.emit('data', JSON.stringify({foo:"bar"})); + mybodydata.emit('end'); // Test pipeing from a request object. s.once('/pull', server.createGetResponse("mypulldata")); @@ -99,7 +113,7 @@ s.listen(s.port, function () { }) s.on('/pushjs', function (req, resp) { if (req.method === "PUT") { - assert.equal(req.headers['content-type'], 'text/javascript'); + assert.equal(req.headers['content-type'], 'application/javascript'); check(); } }) @@ -163,5 +177,40 @@ s.listen(s.port, function () { afterresp.pipe(v) v.on('end', check) }) + + s.on('/forward1', function (req, resp) { + resp.writeHead(302, {location:'/forward2'}) + resp.end() + }) + s.on('/forward2', function (req, resp) { + resp.writeHead('200', {'content-type':'image/png'}) + resp.write('d') + resp.end() + }) + + counter++ + var validateForward = new ValidationStream('d') + validateForward.on('end', check) + request.get('http://localhost:3453/forward1').pipe(validateForward) + // Test pipe options + s.once('/opts', server.createGetResponse('opts response')); + + var optsStream = new stream.Stream(); + optsStream.writable = true + + var optsData = ''; + optsStream.write = function (buf) { + optsData += buf; + if (optsData === 'opts response') { + setTimeout(check, 10); + } + } + + optsStream.end = function () { + assert.fail('end called') + }; + + counter++ + request({url:'http://localhost:3453/opts'}).pipe(optsStream, { end : false }) }) diff --git a/node_modules/request/uuid.js b/node_modules/request/uuid.js index 1d83bd5..fc0588b 100644 --- a/node_modules/request/uuid.js +++ b/node_modules/request/uuid.js @@ -1,19 +1,19 @@ module.exports = function () { - var s = [], itoh = '0123456789ABCDEF'; + var s = [], itoh = '0123456789ABCDEF' // Make array of random hex digits. The UUID only has 32 digits in it, but we // allocate an extra items to make room for the '-'s we'll be inserting. - for (var i = 0; i <36; i++) s[i] = Math.floor(Math.random()*0x10); + for (var i = 0; i <36; i++) s[i] = Math.floor(Math.random()*0x10) // Conform to RFC-4122, section 4.4 s[14] = 4; // Set 4 high bits of time_high field to version - s[19] = (s[19] & 0x3) | 0x8; // Specify 2 high bits of clock sequence + s[19] = (s[19] & 0x3) | 0x8 // Specify 2 high bits of clock sequence // Convert to hex chars - for (var i = 0; i <36; i++) s[i] = itoh[s[i]]; + for (var i = 0; i <36; i++) s[i] = itoh[s[i]] // Insert '-'s - s[8] = s[13] = s[18] = s[23] = '-'; + s[8] = s[13] = s[18] = s[23] = '-' - return s.join(''); + return s.join('') } diff --git a/node_modules/request/vendor/cookie/index.js b/node_modules/request/vendor/cookie/index.js index 4ba20d6..ff44b3e 100644 --- a/node_modules/request/vendor/cookie/index.js +++ b/node_modules/request/vendor/cookie/index.js @@ -21,18 +21,26 @@ var url = require('url'); var Cookie = exports = module.exports = function Cookie(str, req) { this.str = str; - // First key is the name - this.name = str.substr(0, str.indexOf('=')); - // Map the key/val pairs str.split(/ *; */).reduce(function(obj, pair){ - pair = pair.split(/ *= */); - obj[pair[0]] = pair[1] || true; - return obj; - }, this); + var p = pair.indexOf('='); + var key = p > 0 ? pair.substring(0, p).trim() : pair.trim(); + var lowerCasedKey = key.toLowerCase(); + var value = p > 0 ? pair.substring(p + 1).trim() : true; - // Assign value - this.value = this[this.name]; + if (!obj.name) { + // First key is the name + obj.name = key; + obj.value = value; + } + else if (lowerCasedKey === 'httponly') { + obj.httpOnly = value; + } + else { + obj[lowerCasedKey] = value; + } + return obj; + }, this); // Expires this.expires = this.expires @@ -41,8 +49,8 @@ var Cookie = exports = module.exports = function Cookie(str, req) { // Default or trim path this.path = this.path - ? this.path.trim() - : url.parse(req.url).pathname; + ? this.path.trim(): req + ? url.parse(req.url).pathname: '/'; }; /** diff --git a/node_modules/sardines b/node_modules/sardines deleted file mode 120000 index 6bcbfd5..0000000 --- a/node_modules/sardines +++ /dev/null @@ -1 +0,0 @@ -/usr/local/lib/node_modules/sardines \ No newline at end of file diff --git a/node_modules/sk b/node_modules/sk deleted file mode 120000 index b9da99e..0000000 --- a/node_modules/sk +++ /dev/null @@ -1 +0,0 @@ -/usr/local/lib/node_modules/sk \ No newline at end of file diff --git a/node_modules/tar-async/header.js b/node_modules/tar-async/header.js deleted file mode 100644 index 1cdddff..0000000 --- a/node_modules/tar-async/header.js +++ /dev/null @@ -1,124 +0,0 @@ -(function () { - "use strict"; - -/* -struct posix_header { // byte offset - char name[100]; // 0 - char mode[8]; // 100 - char uid[8]; // 108 - char gid[8]; // 116 - char size[12]; // 124 - char mtime[12]; // 136 - char chksum[8]; // 148 - char typeflag; // 156 - char linkname[100]; // 157 - char magic[6]; // 257 - char version[2]; // 263 - char uname[32]; // 265 - char gname[32]; // 297 - char devmajor[8]; // 329 - char devminor[8]; // 337 - char prefix[155]; // 345 - // 500 -}; -*/ - - var utils = require("./utils"), - headerFormat; - - headerFormat = [ - { - 'field': 'filename', - 'length': 100, - 'type': 'string' - }, - { - 'field': 'mode', - 'length': 8, - 'type': 'number' - }, - { - 'field': 'uid', - 'length': 8, - 'type': 'number' - }, - { - 'field': 'gid', - 'length': 8, - 'type': 'number' - }, - { - 'field': 'size', - 'length': 12, - 'type': 'number' - }, - { - 'field': 'mtime', - 'length': 12, - 'type': 'number' - }, - { - 'field': 'checksum', - 'length': 8, - 'type': 'number' - }, - { - 'field': 'type', - 'length': 1, - 'type': 'number' - }, - { - 'field': 'linkName', - 'length': 100, - 'type': 'string' - }, - { - 'field': 'ustar', - 'length': 8, - 'type': 'string' - }, - { - 'field': 'owner', - 'length': 32, - 'type': 'string' - }, - { - 'field': 'group', - 'length': 32, - 'type': 'string' - }, - { - 'field': 'majorNumber', - 'length': 8, - 'type': 'number' - }, - { - 'field': 'minorNumber', - 'length': 8, - 'type': 'number' - }, - { - 'field': 'filenamePrefix', - 'length': 155, - 'type': 'string' - }, - { - 'field': 'padding', - 'length': 12 - } - ]; - - function formatHeader(data) { - var buffer = utils.clean(512), - offset = 0; - - headerFormat.forEach(function (value) { - buffer.write(data[value.field] || "", offset); - offset += value.length; - }); - return buffer; - } - - module.exports.structure = headerFormat; - module.exports.format = formatHeader; -}()); diff --git a/node_modules/tar-async/index.js b/node_modules/tar-async/index.js deleted file mode 100644 index 4f440c2..0000000 --- a/node_modules/tar-async/index.js +++ /dev/null @@ -1,8 +0,0 @@ -(function () { - 'use strict'; - - module.exports = require('./tar'); - - module.exports.Tar = require('./tar'); - module.exports.Untar = require('./untar'); -}()); diff --git a/node_modules/tar-async/package.json b/node_modules/tar-async/package.json deleted file mode 100644 index 199d160..0000000 --- a/node_modules/tar-async/package.json +++ /dev/null @@ -1,20 +0,0 @@ -{ - "author": "T. Jameson Little ", - "name": "tar-async", - "description": "Asynchronous tar and untar", - "keywords": ["tar", "untar", "asynchronous", "stream", "async", "chunk", "chunked"], - "version": "1.1.1", - "repository": { - "type": "git", - "url": "git://github.com/beatgammit/tar-async.git" - }, - "main": "index.js", - "directories": { - "lib": "." - }, - "engines": { - "node": ">=0.1.90" - }, - "dependencies": {}, - "devDependencies": {} -} diff --git a/node_modules/tar-async/tar.js b/node_modules/tar-async/tar.js deleted file mode 100644 index e4952ca..0000000 --- a/node_modules/tar-async/tar.js +++ /dev/null @@ -1,156 +0,0 @@ -(function () { - "use strict"; - - var path = require('path'), - Stream = require('stream').Stream, - header = require("./header"), - utils = require("./utils"), - recordSize = 512, - blockSize, - queue = []; - - function Tar(opt) { - var tape; - - opt = opt || {}; - - blockSize = (opt.recordsPerBlock ? opt.recordsPerBlock : 20) * recordSize; - - Stream.apply(this, arguments); - - tape = this; - - this.written = 0; - - this.consolidate = 'consolidate' in opt ? opt.consolidate : false; - this.normalize = 'normalize' in opt ? opt.normalize : true; - - this.on('end', function () { - tape.emit('data', utils.clean(blockSize - (tape.written % blockSize))); - }); - - if (opt && opt.output) { - this.pipe(opt.output); - } - } - - Tar.prototype = Object.create(Stream.prototype, { - constructor: { value: Tar } - }); - - Tar.prototype.close = function () { - this.emit('end'); - }; - - Tar.prototype.append = function (filepath, input, opts, callback) { - var data, - checksum, - mode, - mtime, - uid, - gid, - size, - tape = this, - extraBytes, - headerBuf; - - if (typeof opts === 'function') { - callback = opts; - opts = {}; - } - - if (this.processing || queue.length) { - queue.push({ - filepath: filepath, - input: input, - opts: opts, - cb: callback - }); - return; - } - - opts = opts || {}; - - mode = opts.mode || parseInt('777', 8) & 0xfff; - mtime = opts.mtime || parseInt(+new Date() / 1000); - uid = opts.uid || 0; - gid = opts.gid || 0; - size = opts.size || input.length; - - data = { - filename: this.consolidate ? path.basename(filepath) : filepath, - mode: utils.pad(mode, 7), - uid: utils.pad(uid, 7), - gid: utils.pad(gid, 7), - size: utils.pad(size, 11), - mtime: utils.pad(mtime, 11), - checksum: ' ', - type: '0', // just a file - ustar: 'ustar ', - owner: '', - group: '' - }; - - if (this.normalize && !this.consolidate) { - data.filename = path.normalize(data.filename); - } - - // calculate the checksum - checksum = 0; - Object.keys(data).forEach(function (key) { - var i, value = data[key], length; - - for (i = 0, length = value.length; i < length; i += 1) { - checksum += value.charCodeAt(i); - } - }); - - data.checksum = utils.pad(checksum, 6) + "\u0000 "; - - headerBuf = header.format(data); - this.emit('data', header.format(data)); - this.written += headerBuf.length; - - if (typeof input === 'string') { - this.emit('data', input); - this.written += input.length; - - extraBytes = recordSize - (size % recordSize || recordSize); - this.emit('data', utils.clean(recordSize - (size % recordSize))); - this.written += extraBytes; - - if (typeof callback === 'function') { - callback(); - } - } else { - this.processing = true; - - input.on('data', function (chunk) { - tape.emit('data', chunk); - tape.written += chunk.length; - }); - - input.on('end', function () { - extraBytes = recordSize - (size % recordSize || recordSize); - tape.emit('data', utils.clean(extraBytes)); - tape.written += extraBytes; - - if (queue.length) { - setTimeout(function () { - var elem = queue.splice(0, 1)[0]; - - tape.append(elem.filepath, elem.input, elem.opts, elem.cb); - }, 0); - - tape.processing = false; - } - - if (typeof callback === 'function') { - callback(); - } - }); - } - }; - - module.exports = Tar; -}()); diff --git a/node_modules/tar-async/untar.js b/node_modules/tar-async/untar.js deleted file mode 100644 index 5c608b4..0000000 --- a/node_modules/tar-async/untar.js +++ /dev/null @@ -1,244 +0,0 @@ -(function () { - "use strict"; - - var Stream = require('stream').Stream, - headerFormat = require('./header').structure, - buffer, - totalRead = 0, - recordSize = 512, - fileStream, - leftToRead, - fileTypes = [ - 'normal', 'hard-link', 'symbolic-link', 'character-special', 'block-special', 'directory', 'fifo', 'contiguous-file' - ]; - - function filterDecoder(input) { - var filter = []; - if (!input) { - return [0, 7]; - } - - if (typeof input === 'string') { - input = [].push(input); - } - - if (!(input instanceof Array)) { - console.error('Invalid fileType. Only Arrays or strings are accepted'); - return; - } - - input.forEach(function (i) { - var index = fileTypes.indexOf(i); - if (index < 0) { - console.error('Filetype not valid. Ignoring input:', i); - return; - } - - filter.push(i); - }); - - return filter; - } - - function readInt(value) { - return parseInt(value.replace(/^0*/, ''), 8) || 0; - } - - function readString(buf) { - var i, length; - for (i = 0, length = buf.length; i < buf.length; i += 1) { - if (buf[i] === 0) { - return buf.toString('utf8', 0, i); - } - } - } - - function doHeader(buf, cb) { - var data = {}, offset = 0, checksum = 0; - - function updateChecksum(value) { - var i, length; - - for (i = 0, length = value.length; i < length; i += 1) { - checksum += value.charCodeAt(i); - } - } - - headerFormat.some(function (field) { - var tBuf = buf.slice(offset, offset + field.length), - tString = tBuf.toString(); - - offset += field.length; - - if (field.field === 'ustar' && !/ustar/.test(tString)) { - // end the loop if not using the extended header - return true; - } else if (field.field === 'checksum') { - updateChecksum(' '); - } else { - updateChecksum(tString); - } - - if (field.type === 'string') { - data[field.field] = readString(tBuf); - } else if (field.type === 'number') { - data[field.field] = readInt(tString); - } - }); - - if (typeof cb === 'function') { - if (checksum !== data.checksum) { - return cb.call(this, 'Checksum not equal', checksum, data.checksum); - } - cb.call(this, null, data, recordSize); - } - } - - /* - * Extract data from an input. - * - * @param opts- object of options - * @param cb- callback for each file - */ - function Untar(opts, cb) { - if (typeof opts === 'function') { - cb = opts; - opts = {}; - } - - // I should probably actually add some options... - opts = opts || {}; - - this.fileTypes = filterDecoder(opts.filter); - - this.cb = cb; - } - - Untar.prototype = Object.create(Stream.prototype, { - constructor: { - value: Untar - } - }); - - Untar.prototype.end = function (data, encoding) { - if (data) { - this.write(data, encoding); - } - }; - - Untar.prototype.write = function write(data, encoding) { - var buf, tBuf, bytesBuffer; - - // get a Buffer object - if (typeof data === 'string') { - buf = new Buffer(data, encoding); - } else if (typeof data === 'array') { - buf = new Buffer(data); - } else { - buf = data; - } - - if (!buf) { - tBuf = buffer; - } else if (buffer) { - // create new buffer with old and new data - tBuf = new Buffer(buffer.length + buf.length); - buffer.copy(tBuf); - buf.copy(tBuf, buffer.length); - } else { - tBuf = buf; - } - - // clear old buffer - buffer = undefined; - - // nothing to do, just give up ='( - if (!tBuf || tBuf.length === 0) { - return; - } - - // stream the file - if (fileStream) { - if (tBuf.length >= leftToRead) { - fileStream.emit('data', tBuf.slice(0, leftToRead)); - fileStream.emit('end'); - fileStream = undefined; - - buffer = tBuf.slice(leftToRead); - totalRead += leftToRead; - leftToRead = 0; - return; - } - - fileStream.emit('data', tBuf); - leftToRead -= tBuf.length; - totalRead += tBuf.length; - return; - } - - // no file to read, so let's try reading a header - - // if we're not an even multiple, account for trailing nulls - if (totalRead % recordSize) { - bytesBuffer = recordSize - (totalRead % recordSize); - - // if we don't have enough bytes to account for the nulls - if (tBuf.length < bytesBuffer) { - totalRead += bytesBuffer; - return; - } - - // throw away trailing nulls - tBuf = tBuf.slice(bytesBuffer); - totalRead += bytesBuffer; - } - - // if we don't have enough for a full header, wait 'til we do... - if (tBuf.length < recordSize) { - buffer = tBuf; - return; - } - - doHeader.call(this, tBuf, function (err, data, rOffset) { - if (err) { - if (rOffset === 0) { - return; - } - return this.cb(err); - } - - // update total; rOffset should always be 512 - totalRead += rOffset; - buffer = tBuf.slice(rOffset); - - fileStream = new Stream(); - - if (this.fileTypes.indexOf(data.type) >= 0) { - // we'll let the user know if they want this type of file - this.cb(err, data, fileStream); - } - - if (buffer.length >= data.size) { - fileStream.emit('data', buffer.slice(0, data.size)); - fileStream.emit('end'); - totalRead += data.size; - buffer = buffer.slice(data.size); - - fileStream = undefined; - - // recurse, we still have data - return write.call(this); - } - - leftToRead = data.size - buffer.length; - fileStream.emit('data', buffer); - totalRead += buffer.length; - - buffer = undefined; - }); - }; - - Untar.prototype.writable = true; - - module.exports = Untar; -}()); diff --git a/node_modules/tar-async/utils.js b/node_modules/tar-async/utils.js deleted file mode 100644 index e3647aa..0000000 --- a/node_modules/tar-async/utils.js +++ /dev/null @@ -1,19 +0,0 @@ -(function () { - "use strict"; - - function clean(length) { - var i, buffer = new Buffer(length); - for (i = 0; i < length; i += 1) { - buffer[i] = 0; - } - return buffer; - } - - function pad(num, bytes, base) { - num = num.toString(base || 8); - return "000000000000".substr(num.length + 12 - bytes) + num; - } - - module.exports.clean = clean; - module.exports.pad = pad; -}()); diff --git a/node_modules/tar/.gitignore b/node_modules/tar/.gitignore deleted file mode 100644 index f96c7db..0000000 --- a/node_modules/tar/.gitignore +++ /dev/null @@ -1,4 +0,0 @@ -.*.swp -node_modules -examples/extract/ -test/tmp/ diff --git a/node_modules/tar/README.md b/node_modules/tar/README.md deleted file mode 100644 index 7cfe3bb..0000000 --- a/node_modules/tar/README.md +++ /dev/null @@ -1,50 +0,0 @@ -# node-tar - -Tar for Node.js. - -## Goals of this project - -1. Be able to parse and reasonably extract the contents of any tar file - created by any program that creates tar files, period. - - At least, this includes every version of: - - * bsdtar - * gnutar - * solaris posix tar - * Joerg Schilling's star ("Schilly tar") - -2. Create tar files that can be extracted by any of the following tar - programs: - - * bsdtar/libarchive version 2.6.2 - * gnutar 1.15 and above - * SunOS Posix tar - * Joerg Schilling's star ("Schilly tar") - -3. 100% test coverage. Speed is important. Correctness is slightly - more important. - -4. Create the kind of tar interface that Node users would want to use. - -5. Satisfy npm's needs for a portable tar implementation with a - JavaScript interface. - -6. No excuses. No complaining. No tolerance for failure. - -## But isn't there already a tar.js? - -Yes, there are a few. This one is going to be better, and it will be -fanatically maintained, because npm will depend on it. - -That's why I need to write it from scratch. Creating and extracting -tarballs is such a large part of what npm does, I simply can't have it -be a black box any longer. - -## Didn't you have something already? Where'd it go? - -It's in the "old" folder. It's not functional. Don't use it. - -It was a useful exploration to learn the issues involved, but like most -software of any reasonable complexity, node-tar won't be useful until -it's been written at least 3 times. diff --git a/node_modules/tar/examples/extracter.js b/node_modules/tar/examples/extracter.js deleted file mode 100644 index e150abf..0000000 --- a/node_modules/tar/examples/extracter.js +++ /dev/null @@ -1,11 +0,0 @@ -var tar = require("../tar.js") - , fs = require("fs") - -fs.createReadStream(__dirname + "/../test/fixtures/c.tar") - .pipe(tar.Extract({ path: __dirname + "/extract" })) - .on("error", function (er) { - console.error("error here") - }) - .on("end", function () { - console.error("done") - }) diff --git a/node_modules/tar/examples/reader.js b/node_modules/tar/examples/reader.js deleted file mode 100644 index c2584d3..0000000 --- a/node_modules/tar/examples/reader.js +++ /dev/null @@ -1,36 +0,0 @@ -var tar = require("../tar.js") - , fs = require("fs") - -fs.createReadStream(__dirname + "/../test/fixtures/c.tar") - .pipe(tar.Reader()) - .on("extendedHeader", function (e) { - console.error("extended pax header", e.props) - e.on("end", function () { - console.error("extended pax fields:", e.fields) - }) - }) - .on("ignoredEntry", function (e) { - console.error("ignoredEntry?!?", e.props) - }) - .on("longLinkpath", function (e) { - console.error("longLinkpath entry", e.props) - e.on("end", function () { - console.error("value=%j", e.body.toString()) - }) - }) - .on("longPath", function (e) { - console.error("longPath entry", e.props) - e.on("end", function () { - console.error("value=%j", e.body.toString()) - }) - }) - .on("entry", function (e) { - console.error("entry", e.props) - e.on("data", function (c) { - console.error(" >>>" + c.toString().replace(/\n/g, "\\n")) - }) - e.on("end", function () { - console.error(" << 0 - return !this._needDrain -} - -EntryWriter.prototype.end = function (c) { - // console.error(".. ew end") - if (c) this._buffer.push(c) - this._buffer.push(EOF) - this._ended = true - this._process() - this._needDrain = this._buffer.length > 0 -} - -EntryWriter.prototype.pause = function () { - // console.error(".. ew pause") - this._paused = true - this.emit("pause") -} - -EntryWriter.prototype.resume = function () { - // console.error(".. ew resume") - this._paused = false - this.emit("resume") - this._process() -} - -EntryWriter.prototype.add = function (entry) { - // console.error(".. ew add") - if (!this.parent) return this.emit("error", new Error("no parent")) - - // make sure that the _header and such is emitted, and clear out - // the _currentEntry link on the parent. - if (!this._ended) this.end() - - return this.parent.add(entry) -} - -EntryWriter.prototype._header = function () { - // console.error(".. ew header") - if (this._didHeader) return - this._didHeader = true - - var headerBlock = TarHeader.encode(this.props) - - if (this.props.needExtended && !this._meta) { - var me = this - - ExtendedHeaderWriter = ExtendedHeaderWriter || - require("./extended-header-writer.js") - - ExtendedHeaderWriter(this.props) - .on("data", function (c) { - me.emit("data", c) - }) - .on("error", function (er) { - me.emit("error", er) - }) - .end() - } - - // console.error(".. .. ew headerBlock emitting") - this.emit("data", headerBlock) - this.emit("header") -} - -EntryWriter.prototype._process = function () { - // console.error(".. .. ew process") - if (!this._didHeader && !this._meta) { - this._header() - } - - if (this._paused || this._processing) { - // console.error(".. .. .. paused=%j, processing=%j", this._paused, this._processing) - return - } - - this._processing = true - - var buf = this._buffer - for (var i = 0; i < buf.length; i ++) { - // console.error(".. .. .. i=%d", i) - - var c = buf[i] - - if (c === EOF) this._stream.end() - else this._stream.write(c) - - if (this._paused) { - // console.error(".. .. .. paused mid-emission") - this._processing = false - if (i < buf.length) { - this._needDrain = true - this._buffer = buf.slice(i + 1) - } - return - } - } - - // console.error(".. .. .. emitted") - this._buffer.length = 0 - this._processing = false - - // console.error(".. .. .. emitting drain") - this.emit("drain") -} - -EntryWriter.prototype.destroy = function () {} diff --git a/node_modules/tar/lib/entry.js b/node_modules/tar/lib/entry.js deleted file mode 100644 index 4fc331e..0000000 --- a/node_modules/tar/lib/entry.js +++ /dev/null @@ -1,212 +0,0 @@ -// A passthrough read/write stream that sets its properties -// based on a header, extendedHeader, and globalHeader -// -// Can be either a file system object of some sort, or -// a pax/ustar metadata entry. - -module.exports = Entry - -var TarHeader = require("./header.js") - , tar = require("../tar") - , assert = require("assert").ok - , Stream = require("stream").Stream - , inherits = require("inherits") - , fstream = require("fstream").Abstract - -function Entry (header, extended, global) { - Stream.call(this) - this.readable = true - this.writable = true - - this._needDrain = false - this._paused = false - this._reading = false - this._ending = false - this._ended = false - this._remaining = 0 - this._queue = [] - this._index = 0 - this._queueLen = 0 - - this._read = this._read.bind(this) - - this.props = {} - this._header = header - this._extended = extended || {} - - // globals can change throughout the course of - // a file parse operation. Freeze it at its current state. - this._global = {} - var me = this - Object.keys(global || {}).forEach(function (g) { - me._global[g] = global[g] - }) - - this._setProps() -} - -inherits(Entry, Stream, -{ write: function (c) { - if (this._ending) this.error("write() after end()", null, true) - if (this._remaining === 0) { - this.error("invalid bytes past eof") - } - - // often we'll get a bunch of \0 at the end of the last write, - // since chunks will always be 512 bytes when reading a tarball. - if (c.length > this._remaining) { - c = c.slice(0, this._remaining) - } - this._remaining -= c.length - - // put it on the stack. - var ql = this._queueLen - this._queue.push(c) - this._queueLen ++ - - this._read() - - // either paused, or buffered - if (this._paused || ql > 0) { - this._needDrain = true - return false - } - - return true - } - -, end: function (c) { - if (c) this.write(c) - this._ending = true - this._read() - } - -, pause: function () { - this._paused = true - this.emit("pause") - } - -, resume: function () { - // console.error(" Tar Entry resume", this.path) - this.emit("resume") - this._paused = false - this._read() - return this._queueLen - this._index > 1 - } - - // This is bound to the instance -, _read: function () { - // console.error(" Tar Entry _read", this.path) - - if (this._paused || this._reading || this._ended) return - - // set this flag so that event handlers don't inadvertently - // get multiple _read() calls running. - this._reading = true - - // have any data to emit? - if (this._index < this._queueLen) { - var chunk = this._queue[this._index ++] - this.emit("data", chunk) - } - - // check if we're drained - if (this._index >= this._queueLen) { - this._queue.length = this._queueLen = this._index = 0 - if (this._needDrain) { - this._needDrain = false - this.emit("drain") - } - if (this._ending) { - this._ended = true - this.emit("end") - } - } - - // if the queue gets too big, then pluck off whatever we can. - // this should be fairly rare. - var mql = this._maxQueueLen - if (this._queueLen > mql && this._index > 0) { - mql = Math.min(this._index, mql) - this._index -= mql - this._queueLen -= mql - this._queue = this._queue.slice(mql) - } - - this._reading = false - } - -, _setProps: function () { - // props = extended->global->header->{} - var header = this._header - , extended = this._extended - , global = this._global - , props = this.props - - // first get the values from the normal header. - var fields = tar.fields - for (var f = 0; fields[f] !== null; f ++) { - var field = fields[f] - , val = header[field] - if (typeof val !== "undefined") props[field] = val - } - - // next, the global header for this file. - // numeric values, etc, will have already been parsed. - ;[global, extended].forEach(function (p) { - Object.keys(p).forEach(function (f) { - if (typeof p[f] !== "undefined") props[f] = p[f] - }) - }) - - // no nulls allowed in path or linkpath - ;["path", "linkpath"].forEach(function (p) { - if (props.hasOwnProperty(p)) { - props[p] = props[p].split("\0")[0] - } - }) - - - // set date fields to be a proper date - ;["mtime", "ctime", "atime"].forEach(function (p) { - if (props.hasOwnProperty(p)) { - props[p] = new Date(props[p] * 1000) - } - }) - - // set the type so that we know what kind of file to create - var type - switch (tar.types[props.type]) { - case "OldFile": - case "ContiguousFile": - type = "File" - break - - case "GNUDumpDir": - type = "Directory" - break - - case undefined: - type = "Unknown" - break - - case "Link": - case "SymbolicLink": - case "CharacterDevice": - case "BlockDevice": - case "Directory": - case "FIFO": - default: - type = tar.types[props.type] - } - - this.type = type - this.path = props.path - this.size = props.size - - // size is special, since it signals when the file needs to end. - this._remaining = props.size - } -, warn: fstream.warn -, error: fstream.error -}) diff --git a/node_modules/tar/lib/extended-header-writer.js b/node_modules/tar/lib/extended-header-writer.js deleted file mode 100644 index f28d530..0000000 --- a/node_modules/tar/lib/extended-header-writer.js +++ /dev/null @@ -1,179 +0,0 @@ - -module.exports = ExtendedHeaderWriter - -var inherits = require("inherits") - , EntryWriter = require("./entry-writer.js") - -inherits(ExtendedHeaderWriter, EntryWriter) - -var tar = require("../tar.js") - , path = require("path") - , inherits = require("inherits") - , TarHeader = require("./header.js") - -// props is the props of the thing we need to write an -// extended header for. -// Don't be shy with it. Just encode everything. -function ExtendedHeaderWriter (props) { - // console.error(">> ehw ctor") - var me = this - - if (!(me instanceof ExtendedHeaderWriter)) { - return new ExtendedHeaderWriter(props) - } - - me.fields = props - - var p = - { path : ("PaxHeader" + path.join("/", props.path || "")) - .replace(/\\/g, "/").substr(0, 100) - , mode : props.mode || 0666 - , uid : props.uid || 0 - , gid : props.gid || 0 - , size : 0 // will be set later - , mtime : props.mtime || Date.now() / 1000 - , type : "x" - , linkpath : "" - , ustar : "ustar\0" - , ustarver : "00" - , uname : props.uname || "" - , gname : props.gname || "" - , devmaj : props.devmaj || 0 - , devmin : props.devmin || 0 - } - - - EntryWriter.call(me, p) - // console.error(">> ehw props", me.props) - me.props = p - - me._meta = true -} - -ExtendedHeaderWriter.prototype.end = function () { - // console.error(">> ehw end") - var me = this - - if (me._ended) return - me._ended = true - - me._encodeFields() - me._stream.write(TarHeader.encode(me.props)) - me.body.forEach(function (l) { - me._stream.write(l) - }) - me._ready = true - - // console.error(">> ehw _process calling end()", me.props) - this._stream.end() -} - -ExtendedHeaderWriter.prototype._encodeFields = function () { - // console.error(">> ehw _encodeFields") - this.body = [] - if (this.fields.prefix) { - this.fields.path = this.fields.prefix + "/" + this.fields.path - this.fields.prefix = "" - } - encodeFields(this.fields, "", this.body) - var me = this - this.body.forEach(function (l) { - me.props.size += l.length - }) -} - -function encodeFields (fields, prefix, body) { - // console.error(">> >> ehw encodeFields") - // "%d %s=%s\n", , , - // The length is a decimal number, and includes itself and the \n - // Numeric values are decimal strings. - - Object.keys(fields).forEach(function (k) { - var val = fields[k] - , numeric = tar.numeric[k] - - if (prefix) k = prefix + "." + k - - // already including NODETAR.type, don't need File=true also - if (k === fields.type && val === true) return - - switch (k) { - // don't include anything that's always handled just fine - // in the normal header, or only meaningful in the context - // of nodetar - case "mode": - case "cksum": - case "ustar": - case "ustarver": - case "prefix": - case "basename": - case "dirname": - case "needExtended": - case "block": - case "filter": - return - - case "rdev": - if (val === 0) return - break - - case "nlink": - case "dev": // Truly a hero among men, Creator of Star! - case "ino": // Speak his name with reverent awe! It is: - k = "SCHILY." + k - break - - default: break - } - - if (val && typeof val === "object" && - !Buffer.isBuffer(val)) encodeFields(val, k, body) - else if (val === null || val === undefined) return - else body.push.apply(body, encodeField(k, val)) - }) - - return body -} - -function encodeField (k, v) { - // lowercase keys must be valid, otherwise prefix with - // "NODETAR." - if (k.charAt(0) === k.charAt(0).toLowerCase()) { - var m = k.split(".")[0] - if (!tar.knownExtended[m]) k = "NODETAR." + k - } - - if (typeof val === "number") val = val.toString(10) - - var s = new Buffer(" " + k + "=" + v + "\n") - , digits = Math.floor(Math.log(s.length) / Math.log(10)) + 1 - - // console.error("1 s=%j digits=%j s.length=%d", s.toString(), digits, s.length) - - // if adding that many digits will make it go over that length, - // then add one to it. For example, if the string is: - // " foo=bar\n" - // then that's 9 characters. With the "9", that bumps the length - // up to 10. However, this is invalid: - // "10 foo=bar\n" - // but, since that's actually 11 characters, since 10 adds another - // character to the length, and the length includes the number - // itself. In that case, just bump it up again. - if (s.length + digits >= Math.pow(10, digits)) digits += 1 - // console.error("2 s=%j digits=%j s.length=%d", s.toString(), digits, s.length) - - var len = digits + s.length - // console.error("3 s=%j digits=%j s.length=%d len=%d", s.toString(), digits, s.length, len) - var lenBuf = new Buffer("" + len) - if (lenBuf.length + s.length !== len) { - throw new Error("Bad length calculation\n"+ - "len="+len+"\n"+ - "lenBuf="+JSON.stringify(lenBuf.toString())+"\n"+ - "lenBuf.length="+lenBuf.length+"\n"+ - "digits="+digits+"\n"+ - "s="+JSON.stringify(s.toString())+"\n"+ - "s.length="+s.length) - } - - return [lenBuf, s] -} diff --git a/node_modules/tar/lib/extended-header.js b/node_modules/tar/lib/extended-header.js deleted file mode 100644 index 4346d6c..0000000 --- a/node_modules/tar/lib/extended-header.js +++ /dev/null @@ -1,139 +0,0 @@ -// An Entry consisting of: -// -// "%d %s=%s\n", , , -// -// The length is a decimal number, and includes itself and the \n -// \0 does not terminate anything. Only the length terminates the string. -// Numeric values are decimal strings. - -module.exports = ExtendedHeader - -var Entry = require("./entry.js") - , inherits = require("inherits") - , tar = require("../tar.js") - , numeric = tar.numeric - , keyTrans = { "SCHILY.dev": "dev" - , "SCHILY.ino": "ino" - , "SCHILY.nlink": "nlink" } - -function ExtendedHeader () { - Entry.apply(this, arguments) - this.on("data", this._parse) - this.fields = {} - this._position = 0 - this._fieldPos = 0 - this._state = SIZE - this._sizeBuf = [] - this._keyBuf = [] - this._valBuf = [] - this._size = -1 - this._key = "" -} - -inherits(ExtendedHeader, Entry, { _parse: parse }) - -var s = 0 - , states = ExtendedHeader.states = {} - , SIZE = states.SIZE = s++ - , KEY = states.KEY = s++ - , VAL = states.VAL = s++ - , ERR = states.ERR = s++ - -Object.keys(states).forEach(function (s) { - states[states[s]] = states[s] -}) - -states[s] = null - -// char code values for comparison -var _0 = "0".charCodeAt(0) - , _9 = "9".charCodeAt(0) - , point = ".".charCodeAt(0) - , a = "a".charCodeAt(0) - , Z = "Z".charCodeAt(0) - , a = "a".charCodeAt(0) - , z = "z".charCodeAt(0) - , space = " ".charCodeAt(0) - , eq = "=".charCodeAt(0) - , cr = "\n".charCodeAt(0) - -function parse (c) { - if (this._state === ERR) return - - for ( var i = 0, l = c.length - ; i < l - ; this._position++, this._fieldPos++, i++) { - // console.error("top of loop, size="+this._size) - - var b = c[i] - - if (this._size >= 0 && this._fieldPos > this._size) { - error(this, "field exceeds length="+this._size) - return - } - - switch (this._state) { - case ERR: return - - case SIZE: - // console.error("parsing size, b=%d, rest=%j", b, c.slice(i).toString()) - if (b === space) { - this._state = KEY - // this._fieldPos = this._sizeBuf.length - this._size = parseInt(new Buffer(this._sizeBuf).toString(), 10) - this._sizeBuf.length = 0 - continue - } - if (b < _0 || b > _9) { - error(this, "expected [" + _0 + ".." + _9 + "], got " + b) - return - } - this._sizeBuf.push(b) - continue - - case KEY: - // can be any char except =, not > size. - if (b === eq) { - this._state = VAL - this._key = new Buffer(this._keyBuf).toString() - if (keyTrans[this._key]) this._key = keyTrans[this._key] - this._keyBuf.length = 0 - continue - } - this._keyBuf.push(b) - continue - - case VAL: - // field must end with cr - if (this._fieldPos === this._size - 1) { - // console.error("finished with "+this._key) - if (b !== cr) { - error(this, "expected \\n at end of field") - return - } - var val = new Buffer(this._valBuf).toString() - if (numeric[this._key]) { - val = parseFloat(val) - } - this.fields[this._key] = val - - this._valBuf.length = 0 - this._state = SIZE - this._size = -1 - this._fieldPos = -1 - continue - } - this._valBuf.push(b) - continue - } - } -} - -function error (me, msg) { - msg = "invalid header: " + msg - + "\nposition=" + me._position - + "\nfield position=" + me._fieldPos - - me.error(msg) - me.state = ERR -} diff --git a/node_modules/tar/lib/extract.js b/node_modules/tar/lib/extract.js deleted file mode 100644 index e45974c..0000000 --- a/node_modules/tar/lib/extract.js +++ /dev/null @@ -1,64 +0,0 @@ -// give it a tarball and a path, and it'll dump the contents - -module.exports = Extract - -var tar = require("../tar.js") - , fstream = require("fstream") - , inherits = require("inherits") - , path = require("path") - -function Extract (opts) { - if (!(this instanceof Extract)) return new Extract(opts) - tar.Parse.apply(this) - - // have to dump into a directory - opts.type = "Directory" - opts.Directory = true - - if (typeof opts !== "object") { - opts = { path: opts } - } - - // better to drop in cwd? seems more standard. - opts.path = opts.path || path.resolve("node-tar-extract") - opts.type = "Directory" - opts.Directory = true - - this._fst = fstream.Writer(opts) - - this.pause() - var me = this - - // Hardlinks in tarballs are relative to the root - // of the tarball. So, they need to be resolved against - // the target directory in order to be created properly. - me.on("entry", function (entry) { - if (entry.type !== "Link") return - entry.linkpath = entry.props.linkpath = - path.join(opts.path, path.join("/", entry.props.linkpath)) - }) - - this._fst.on("ready", function () { - me.pipe(me._fst, { end: false }) - me.resume() - }) - - // this._fst.on("end", function () { - // console.error("\nEEEE Extract End", me._fst.path) - // }) - - this._fst.on("close", function () { - // console.error("\nEEEE Extract End", me._fst.path) - me.emit("end") - me.emit("close") - }) -} - -inherits(Extract, tar.Parse) - -Extract.prototype._streamEnd = function () { - var me = this - if (!me._ended) me.error("unexpected eof") - me._fst.end() - // my .end() is coming later. -} diff --git a/node_modules/tar/lib/global-header-writer.js b/node_modules/tar/lib/global-header-writer.js deleted file mode 100644 index 0bfc7b8..0000000 --- a/node_modules/tar/lib/global-header-writer.js +++ /dev/null @@ -1,14 +0,0 @@ -module.exports = GlobalHeaderWriter - -var ExtendedHeaderWriter = require("./extended-header-writer.js") - , inherits = require("inherits") - -inherits(GlobalHeaderWriter, ExtendedHeaderWriter) - -function GlobalHeaderWriter (props) { - if (!(this instanceof GlobalHeaderWriter)) { - return new GlobalHeaderWriter(props) - } - ExtendedHeaderWriter.call(this, props) - this.props.type = "g" -} diff --git a/node_modules/tar/lib/header.js b/node_modules/tar/lib/header.js deleted file mode 100644 index 05b237c..0000000 --- a/node_modules/tar/lib/header.js +++ /dev/null @@ -1,385 +0,0 @@ -// parse a 512-byte header block to a data object, or vice-versa -// If the data won't fit nicely in a simple header, then generate -// the appropriate extended header file, and return that. - -module.exports = TarHeader - -var tar = require("../tar.js") - , fields = tar.fields - , fieldOffs = tar.fieldOffs - , fieldEnds = tar.fieldEnds - , fieldSize = tar.fieldSize - , numeric = tar.numeric - , assert = require("assert").ok - , space = " ".charCodeAt(0) - , slash = "/".charCodeAt(0) - , bslash = process.platform === "win32" ? "\\".charCodeAt(0) : null - -function TarHeader (block) { - if (!(this instanceof TarHeader)) return new TarHeader(block) - if (block) this.decode(block) -} - -TarHeader.prototype = - { decode : decode - , encode: encode - , calcSum: calcSum - , checkSum: checkSum - } - -TarHeader.parseNumeric = parseNumeric -TarHeader.encode = encode -TarHeader.decode = decode - -// note that this will only do the normal ustar header, not any kind -// of extended posix header file. If something doesn't fit comfortably, -// then it will set obj.needExtended = true, and set the block to -// the closest approximation. -function encode (obj) { - if (!obj && !(this instanceof TarHeader)) throw new Error( - "encode must be called on a TarHeader, or supplied an object") - - obj = obj || this - var block = obj.block = new Buffer(512) - - // if the object has a "prefix", then that's actually an extension of - // the path field. - if (obj.prefix) { - // console.error("%% header encoding, got a prefix", obj.prefix) - obj.path = obj.prefix + "/" + obj.path - // console.error("%% header encoding, prefixed path", obj.path) - obj.prefix = "" - } - - obj.needExtended = false - - if (obj.mode) { - if (typeof obj.mode === "string") obj.mode = parseInt(obj.mode, 8) - obj.mode = obj.mode & 0777 - } - - for (var f = 0; fields[f] !== null; f ++) { - var field = fields[f] - , off = fieldOffs[f] - , end = fieldEnds[f] - , ret - - switch (field) { - case "cksum": - // special, done below, after all the others - break - - case "prefix": - // special, this is an extension of the "path" field. - // console.error("%% header encoding, skip prefix later") - break - - case "type": - // convert from long name to a single char. - var type = obj.type || "0" - if (type.length > 1) { - type = tar.types[obj.type] - if (!type) type = "0" - } - writeText(block, off, end, type) - break - - case "path": - // uses the "prefix" field if > 100 bytes, but <= 255 - var pathLen = Buffer.byteLength(obj.path) - , pathFSize = fieldSize[fields.path] - , prefFSize = fieldSize[fields.prefix] - - // paths between 100 and 255 should use the prefix field. - // longer than 255 - if (pathLen > pathFSize && - pathLen <= pathFSize + prefFSize) { - // need to find a slash somewhere in the middle so that - // path and prefix both fit in their respective fields - var searchStart = pathLen - 1 - pathFSize - , searchEnd = prefFSize - , found = false - , pathBuf = new Buffer(obj.path) - - for ( var s = searchStart - ; (s <= searchEnd) - ; s ++ ) { - if (pathBuf[s] === slash || pathBuf[s] === bslash) { - found = s - break - } - } - - if (found !== false) { - prefix = pathBuf.slice(0, found).toString("utf8") - path = pathBuf.slice(found + 1).toString("utf8") - - ret = writeText(block, off, end, path) - off = fieldOffs[fields.prefix] - end = fieldEnds[fields.prefix] - // console.error("%% header writing prefix", off, end, prefix) - ret = writeText(block, off, end, prefix) || ret - break - } - } - - // paths less than 100 chars don't need a prefix - // and paths longer than 255 need an extended header and will fail - // on old implementations no matter what we do here. - // Null out the prefix, and fallthrough to default. - // console.error("%% header writing no prefix") - var poff = fieldOffs[fields.prefix] - , pend = fieldEnds[fields.prefix] - writeText(block, poff, pend, "") - // fallthrough - - // all other fields are numeric or text - default: - ret = numeric[field] - ? writeNumeric(block, off, end, obj[field]) - : writeText(block, off, end, obj[field] || "") - break - } - obj.needExtended = obj.needExtended || ret - } - - var off = fieldOffs[fields.cksum] - , end = fieldEnds[fields.cksum] - - writeNumeric(block, off, end, calcSum.call(this, block)) - - return block -} - -// if it's a negative number, or greater than will fit, -// then use write256. -var MAXNUM = { 12: 077777777777 - , 11: 07777777777 - , 8 : 07777777 - , 7 : 0777777 } -function writeNumeric (block, off, end, num) { - var writeLen = end - off - , maxNum = MAXNUM[writeLen] || 0 - - num = num || 0 - // console.error(" numeric", num) - - if (num instanceof Date || - Object.prototype.toString.call(num) === "[object Date]") { - num = num.getTime() / 1000 - } - - if (num > maxNum || num < 0) { - write256(block, off, end, num) - // need an extended header if negative or too big. - return true - } - - // god, tar is so annoying - // if the string is small enough, you should put a space - // between the octal string and the \0, but if it doesn't - // fit, then don't. - var numStr = Math.floor(num).toString(8) - if (num < MAXNUM[writeLen - 1]) numStr += " " - - // pad with "0" chars - if (numStr.length < writeLen) { - numStr = (new Array(writeLen - numStr.length).join("0")) + numStr - } - - if (numStr.length !== writeLen - 1) { - throw new Error("invalid length: " + JSON.stringify(numStr) + "\n" + - "expected: "+writeLen) - } - block.write(numStr, off, writeLen, "utf8") - block[end - 1] = 0 -} - -function write256 (block, off, end, num) { - var buf = block.slice(off, end) - var positive = num >= 0 - buf[0] = positive ? 0x80 : 0xFF - - // get the number as a base-256 tuple - if (!positive) num *= -1 - var tuple = [] - do { - var n = num % 256 - tuple.push(n) - num = (num - n) / 256 - } while (num) - - var bytes = tuple.length - - var fill = buf.length - bytes - for (var i = 1; i < fill; i ++) { - buf[i] = positive ? 0 : 0xFF - } - - // tuple is a base256 number, with [0] as the *least* significant byte - // if it's negative, then we need to flip all the bits once we hit the - // first non-zero bit. The 2's-complement is (0x100 - n), and the 1's- - // complement is (0xFF - n). - var zero = true - for (i = bytes; i > 0; i --) { - var byte = tuple[bytes - i] - if (positive) buf[fill + i] = byte - else if (zero && byte === 0) buf[fill + i] = 0 - else if (zero) { - zero = false - buf[fill + i] = 0x100 - byte - } else buf[fill + i] = 0xFF - byte - } -} - -function writeText (block, off, end, str) { - // strings are written as utf8, then padded with \0 - var strLen = Buffer.byteLength(str) - , writeLen = Math.min(strLen, end - off) - // non-ascii fields need extended headers - // long fields get truncated - , needExtended = strLen !== str.length || strLen > writeLen - - // write the string, and null-pad - if (writeLen > 0) block.write(str, off, writeLen, "utf8") - for (var i = off + writeLen; i < end; i ++) block[i] = 0 - - return needExtended -} - -function calcSum (block) { - block = block || this.block - assert(Buffer.isBuffer(block) && block.length === 512) - - if (!block) throw new Error("Need block to checksum") - - // now figure out what it would be if the cksum was " " - var sum = 0 - , start = fieldOffs[fields.cksum] - , end = fieldEnds[fields.cksum] - - for (var i = 0; i < fieldOffs[fields.cksum]; i ++) { - sum += block[i] - } - - for (var i = start; i < end; i ++) { - sum += space - } - - for (var i = end; i < 512; i ++) { - sum += block[i] - } - - return sum -} - - -function checkSum (block) { - var sum = calcSum.call(this, block) - block = block || this.block - - var cksum = block.slice(fieldOffs[fields.cksum], fieldEnds[fields.cksum]) - cksum = parseNumeric(cksum) - - return cksum === sum -} - -function decode (block) { - block = block || this.block - assert(Buffer.isBuffer(block) && block.length === 512) - - this.block = block - this.cksumValid = this.checkSum() - - var prefix = null - - // slice off each field. - for (var f = 0; fields[f] !== null; f ++) { - var field = fields[f] - , val = block.slice(fieldOffs[f], fieldEnds[f]) - - switch (field) { - case "ustar": - // if not ustar, then everything after that is just padding. - if (val.toString() !== "ustar\0") { - this.ustar = false - return - } else { - // console.error("ustar:", val, val.toString()) - this.ustar = val.toString() - } - break - - // prefix is special, since it might signal the xstar header - case "prefix": - var atime = parseNumeric(val.slice(131, 131 + 12)) - , ctime = parseNumeric(val.slice(131 + 12, 131 + 12 + 12)) - if ((val[130] === 0 || val[130] === space) && - typeof atime === "number" && - typeof ctime === "number" && - val[131 + 12] === space && - val[131 + 12 + 12] === space) { - this.atime = atime - this.ctime = ctime - val = val.slice(0, 130) - } - prefix = val.toString("utf8").replace(/\0+$/, "") - // console.error("%% header reading prefix", prefix) - break - - // all other fields are null-padding text - // or a number. - default: - if (numeric[field]) { - this[field] = parseNumeric(val) - } else { - this[field] = val.toString("utf8").replace(/\0+$/, "") - } - break - } - } - - // if we got a prefix, then prepend it to the path. - if (prefix) { - this.path = prefix + "/" + this.path - // console.error("%% header got a prefix", this.path) - } -} - -function parse256 (buf) { - // first byte MUST be either 80 or FF - // 80 for positive, FF for 2's comp - var positive - if (buf[0] === 0x80) positive = true - else if (buf[0] === 0xFF) positive = false - else return null - - // build up a base-256 tuple from the least sig to the highest - var zero = false - , tuple = [] - for (var i = buf.length - 1; i > 0; i --) { - var byte = buf[i] - if (positive) tuple.push(byte) - else if (zero && byte === 0) tuple.push(0) - else if (zero) { - zero = false - tuple.push(0x100 - byte) - } else tuple.push(0xFF - byte) - } - - for (var sum = 0, i = 0, l = tuple.length; i < l; i ++) { - sum += tuple[i] * Math.pow(256, i) - } - - return positive ? sum : -1 * sum -} - -function parseNumeric (f) { - if (f[0] & 0x80) return parse256(f) - - var str = f.toString("utf8").split("\0")[0].trim() - , res = parseInt(str, 8) - - return isNaN(res) ? null : res -} - diff --git a/node_modules/tar/lib/pack.js b/node_modules/tar/lib/pack.js deleted file mode 100644 index 411b8b6..0000000 --- a/node_modules/tar/lib/pack.js +++ /dev/null @@ -1,212 +0,0 @@ -// pipe in an fstream, and it'll make a tarball. -// key-value pair argument is global extended header props. - -module.exports = Pack - -var EntryWriter = require("./entry-writer.js") - , Stream = require("stream").Stream - , path = require("path") - , inherits = require("inherits") - , GlobalHeaderWriter = require("./global-header-writer.js") - , collect = require("fstream").collect - , eof = new Buffer(512) - -for (var i = 0; i < 512; i ++) eof[i] = 0 - -inherits(Pack, Stream) - -function Pack (props) { - // console.error("-- p ctor") - var me = this - if (!(me instanceof Pack)) return new Pack(props) - - me._global = props - - me.readable = true - me.writable = true - me._buffer = [] - // console.error("-- -- set current to null in ctor") - me._currentEntry = null - me._processing = false - - me._pipeRoot = null - me.on("pipe", function (src) { - if (src.root === me._pipeRoot) return - me._pipeRoot = src - src.on("end", function () { - me._pipeRoot = null - }) - me.add(src) - }) -} - -Pack.prototype.addGlobal = function (props) { - // console.error("-- p addGlobal") - if (this._didGlobal) return - this._didGlobal = true - - var me = this - GlobalHeaderWriter(props) - .on("data", function (c) { - me.emit("data", c) - }) - .end() -} - -Pack.prototype.add = function (stream) { - if (this._global && !this._didGlobal) this.addGlobal(this._global) - - if (this._ended) return this.emit("error", new Error("add after end")) - - collect(stream) - this._buffer.push(stream) - this._process() - this._needDrain = this._buffer.length > 0 - return !this._needDrain -} - -Pack.prototype.pause = function () { - this._paused = true - if (this._currentEntry) this._currentEntry.pause() - this.emit("pause") -} - -Pack.prototype.resume = function () { - this._paused = false - if (this._currentEntry) this._currentEntry.resume() - this.emit("resume") - this._process() -} - -Pack.prototype.end = function () { - this._ended = true - this._buffer.push(eof) - this._process() -} - -Pack.prototype._process = function () { - var me = this - if (me._paused || me._processing) { - return - } - - var entry = me._buffer.shift() - - if (!entry) { - if (me._needDrain) { - me.emit("drain") - } - return - } - - if (entry.ready === false) { - // console.error("-- entry is not ready", entry) - me._buffer.unshift(entry) - entry.on("ready", function () { - // console.error("-- -- ready!", entry) - me._process() - }) - return - } - - me._processing = true - - if (entry === eof) { - // need 2 ending null blocks. - me.emit("data", eof) - me.emit("data", eof) - me.emit("end") - me.emit("close") - return - } - - // Change the path to be relative to the root dir that was - // added to the tarball. - // - // XXX This should be more like how -C works, so you can - // explicitly set a root dir, and also explicitly set a pathname - // in the tarball to use. That way we can skip a lot of extra - // work when resolving symlinks for bundled dependencies in npm. - - var root = path.dirname((entry.root || entry).path) - var wprops = {} - - Object.keys(entry.props).forEach(function (k) { - wprops[k] = entry.props[k] - }) - - wprops.path = path.relative(root, entry.path) - - switch (wprops.type) { - case "Directory": - wprops.path += "/" - wprops.size = 0 - break - case "Link": - var lp = path.resolve(path.dirname(entry.path), entry.linkpath) - wprops.linkpath = path.relative(root, lp) - wprops.size = 0 - break - case "SymbolicLink": - var lp = path.resolve(path.dirname(entry.path), entry.linkpath) - wprops.linkpath = path.relative(path.dirname(entry.path), lp) - wprops.size = 0 - break - } - - // console.error("-- new writer", wprops) - // if (!wprops.type) { - // // console.error("-- no type?", entry.constructor.name, entry) - // } - - // console.error("-- -- set current to new writer", wprops.path) - var writer = me._currentEntry = EntryWriter(wprops) - - writer.parent = me - - // writer.on("end", function () { - // // console.error("-- -- writer end", writer.path) - // }) - - writer.on("data", function (c) { - me.emit("data", c) - }) - - writer.on("header", function () { - Buffer.prototype.toJSON = function () { - return this.toString().split(/\0/).join(".") - } - // console.error("-- -- writer header %j", writer.props) - if (writer.props.size === 0) nextEntry() - }) - writer.on("close", nextEntry) - - var ended = false - function nextEntry () { - if (ended) return - ended = true - - // console.error("-- -- writer close", writer.path) - // console.error("-- -- set current to null", wprops.path) - me._currentEntry = null - me._processing = false - me._process() - } - - writer.on("error", function (er) { - // console.error("-- -- writer error", writer.path) - me.emit("error", er) - }) - - // if it's the root, then there's no need to add its entries, - // or data, since they'll be added directly. - if (entry === me._pipeRoot) { - // console.error("-- is the root, don't auto-add") - writer.add = null - } - - entry.pipe(writer) -} - -Pack.prototype.destroy = function () {} -Pack.prototype.write = function () {} diff --git a/node_modules/tar/lib/parse.js b/node_modules/tar/lib/parse.js deleted file mode 100644 index d9784b5..0000000 --- a/node_modules/tar/lib/parse.js +++ /dev/null @@ -1,253 +0,0 @@ - -// A writable stream. -// It emits "entry" events, which provide a readable stream that has -// header info attached. - -module.exports = Parse.create = Parse - -var stream = require("stream") - , Stream = stream.Stream - , BlockStream = require("block-stream") - , tar = require("../tar.js") - , TarHeader = require("./header.js") - , Entry = require("./entry.js") - , BufferEntry = require("./buffer-entry.js") - , ExtendedHeader = require("./extended-header.js") - , assert = require("assert").ok - , inherits = require("inherits") - , fstream = require("fstream") - -// reading a tar is a lot like reading a directory -// However, we're actually not going to run the ctor, -// since it does a stat and various other stuff. -// This inheritance gives us the pause/resume/pipe -// behavior that is desired. -inherits(Parse, fstream.Reader) - -function Parse () { - var me = this - if (!(me instanceof Parse)) return new Parse() - - // doesn't apply fstream.Reader ctor? - // no, becasue we don't want to stat/etc, we just - // want to get the entry/add logic from .pipe() - Stream.apply(me) - - me.writable = true - me.readable = true - me._stream = new BlockStream(512) - - me._stream.on("error", function (e) { - me.emit("error", e) - }) - - me._stream.on("data", function (c) { - me._process(c) - }) - - me._stream.on("end", function () { - me._streamEnd() - }) - - me._stream.on("drain", function () { - me.emit("drain") - }) -} - -// overridden in Extract class, since it needs to -// wait for its DirWriter part to finish before -// emitting "end" -Parse.prototype._streamEnd = function () { - var me = this - if (!me._ended) me.error("unexpected eof") - me.emit("end") -} - -// a tar reader is actually a filter, not just a readable stream. -// So, you should pipe a tarball stream into it, and it needs these -// write/end methods to do that. -Parse.prototype.write = function (c) { - if (this._ended) { - return this.error("write() after end()") - } - return this._stream.write(c) -} - -Parse.prototype.end = function (c) { - this._ended = true - return this._stream.end(c) -} - -// don't need to do anything, since we're just -// proxying the data up from the _stream. -// Just need to override the parent's "Not Implemented" -// error-thrower. -Parse.prototype._read = function () {} - -Parse.prototype._process = function (c) { - assert(c && c.length === 512, "block size should be 512") - - // one of three cases. - // 1. A new header - // 2. A part of a file/extended header - // 3. One of two or more EOF null blocks - - if (this._entry) { - var entry = this._entry - entry.write(c) - if (entry._remaining === 0) { - entry.end() - this._entry = null - } - } else { - // either zeroes or a header - var zero = true - for (var i = 0; i < 512 && zero; i ++) { - zero = c[i] === 0 - } - - // eof is *at least* 2 blocks of nulls, and then the end of the - // file. you can put blocks of nulls between entries anywhere, - // so appending one tarball to another is technically valid. - // ending without the eof null blocks is not allowed, however. - if (zero) { - this._ended = this._eofStarted - this._eofStarted = true - } else { - this._ended = this._eofStarted = false - this._startEntry(c) - } - - } -} - -// take a header chunk, start the right kind of entry. -Parse.prototype._startEntry = function (c) { - var header = new TarHeader(c) - , self = this - , entry - , ev - , EntryType - , onend - , meta = false - - switch (tar.types[header.type]) { - case "File": - case "OldFile": - case "Link": - case "SymbolicLink": - case "CharacterDevice": - case "BlockDevice": - case "Directory": - case "FIFO": - case "ContiguousFile": - case "GNUDumpDir": - // start a file. - // pass in any extended headers - // These ones consumers are typically most interested in. - EntryType = Entry - ev = "entry" - break - - case "GlobalExtendedHeader": - // extended headers that apply to the rest of the tarball - EntryType = ExtendedHeader - onend = function () { - self._global = self._global || {} - Object.keys(entry.fields).forEach(function (k) { - self._global[k] = entry.fields[k] - }) - } - ev = "globalExtendedHeader" - meta = true - break - - case "ExtendedHeader": - case "OldExtendedHeader": - // extended headers that apply to the next entry - EntryType = ExtendedHeader - onend = function () { - self._extended = entry.fields - } - ev = "extendedHeader" - meta = true - break - - case "NextFileHasLongLinkpath": - // set linkpath= in extended header - EntryType = BufferEntry - onend = function () { - self._extended = self._extended || {} - self._extended.linkpath = entry.body - } - ev = "longLinkpath" - meta = true - break - - case "NextFileHasLongPath": - case "OldGnuLongPath": - // set path= in file-extended header - EntryType = BufferEntry - onend = function () { - self._extended = self._extended || {} - self._extended.path = entry.body - } - ev = "longPath" - meta = true - break - - default: - // all the rest we skip, but still set the _entry - // member, so that we can skip over their data appropriately. - // emit an event to say that this is an ignored entry type? - EntryType = Entry - ev = "ignoredEntry" - break - } - - var global, extended - if (meta) { - global = extended = null - } else { - var global = this._global - var extended = this._extended - - // extendedHeader only applies to one entry, so once we start - // an entry, it's over. - this._extended = null - } - entry = new EntryType(header, extended, global) - entry.meta = meta - - // only proxy data events of normal files. - if (!meta) { - entry.on("data", function (c) { - me.emit("data", c) - }) - } - - if (onend) entry.on("end", onend) - - this._entry = entry - var me = this - - entry.on("pause", function () { - me.pause() - }) - - entry.on("resume", function () { - me.resume() - }) - - if (this.listeners("*").length) { - this.emit("*", ev, entry) - } - - this.emit(ev, entry) - - // Zero-byte entry. End immediately. - if (entry.props.size === 0) { - entry.end() - this._entry = null - } -} diff --git a/node_modules/tar/old/README.md b/node_modules/tar/old/README.md deleted file mode 100644 index aef9844..0000000 --- a/node_modules/tar/old/README.md +++ /dev/null @@ -1 +0,0 @@ -tar for node diff --git a/node_modules/tar/old/doc/example.js b/node_modules/tar/old/doc/example.js deleted file mode 100644 index d29517e..0000000 --- a/node_modules/tar/old/doc/example.js +++ /dev/null @@ -1,24 +0,0 @@ -// request a tar file, and then write it -require("http").request({...}, function (resp) { - resp.pipe(tar.createParser(function (file) { - if (file.isDirectory()) { - this.pause() - return fs.mkdir(file.name, function (er) { - if (er) return this.emit("error", er) - this.resume() - }) - } else if (file.isSymbolicLink()) { - this.pause() - return fs.symlink(file.link, file.name, function (er) { - if (er) return this.emit("error", er) - this.resume() - }) - } else if (file.isFile()) { - file.pipe(fs.createWriteStream(file.name)) - } - })) - // or maybe just have it do all that internally? - resp.pipe(tar.createParser(function (file) { - this.create("/extract/target/path", file) - })) -}) diff --git a/node_modules/tar/old/generator.js b/node_modules/tar/old/generator.js deleted file mode 100644 index c2506c4..0000000 --- a/node_modules/tar/old/generator.js +++ /dev/null @@ -1,387 +0,0 @@ -module.exports = Generator -Generator.create = create - -var tar = require("./tar") - , Stream = require("stream").Stream - , Parser = require("./parser") - , fs = require("fs") - -function create (opts) { - return new Generator(opts) -} - -function Generator (opts) { - this.readable = true - this.currentFile = null - - this._paused = false - this._ended = false - this._queue = [] - - this.options = { cwd: process.cwd() } - Object.keys(opts).forEach(function (o) { - this.options[o] = opts[o] - }, this) - if (this.options.cwd.slice(-1) !== "/") { - this.options.cwd += "/" - } - - Stream.apply(this) -} - -Generator.prototype = Object.create(Stream.prototype) - -Generator.prototype.pause = function () { - if (this.currentFile) this.currentFile.pause() - this.paused = true - this.emit("pause") -} - -Generator.prototype.resume = function () { - this.paused = false - if (this.currentFile) this.currentFile.resume() - this.emit("resume") - this._processQueue() -} - -Generator.prototype.end = function () { - this._ended = true - this._processQueue() -} - -Generator.prototype.append = function (f, st) { - if (this._ended) return this.emit("error", new Error( - "Cannot append after ending")) - - // if it's a string, then treat it as a filename. - // if it's a number, then treat it as a fd - // if it's a Stats, then treat it as a stat object - // if it's a Stream, then stream it in. - var s = toFileStream(f, st) - if (!s) return this.emit("error", new TypeError( - "Invalid argument: "+f)) - - // make sure it's in the folder being added. - if (s.name.indexOf(this.options.cwd) !== 0) { - this.emit("error", new Error( - "Invalid argument: "+s.name+"\nOutside of "+this.options.cwd)) - } - - s.name = s.name.substr(this.options.cwd.length) - s.pause() - this._queue.push(s) - - if (!s._needStat) return this._processQueue() - - var self = this - fs.lstat(s.name, function (er, st) { - if (er) return self.emit("error", new Error( - "invalid file "+s.name+"\n"+er.message)) - s.mode = st.mode & 0777 - s.uid = st.uid - s.gid = st.gid - s.size = st.size - s.mtime = +st.mtime / 1000 - s.type = st.isFile() ? "0" - : st.isSymbolicLink() ? "2" - : st.isCharacterDevice() ? "3" - : st.isBlockDevice() ? "4" - : st.isDirectory() ? "5" - : st.isFIFO() ? "6" - : null - - // TODO: handle all the types in - // http://cdrecord.berlios.de/private/man/star/star.4.html - // for now, skip over unknown ones. - if (s.type === null) { - console.error("Unknown file type: " + s.name) - // kick out of the queue - var i = self._queue.indexOf(s) - if (i !== -1) self._queue.splice(i, 1) - self._processQueue() - return - } - - if (s.type === "2") return fs.readlink(s.name, function (er, n) { - if (er) return self.emit("error", new Error( - "error reading link value "+s.name+"\n"+er.message)) - s.linkname = n - s._needStat = false - self._processQueue() - }) - s._needStat = false - self._processQueue() - }) - return false -} - -function toFileStream (thing) { - if (typeof thing === "string") { - return toFileStream(fs.createReadStream(thing)) - } - - if (thing && typeof thing === "object") { - if (thing instanceof (Parser.File)) return thing - - if (thing instanceof Stream) { - if (thing.hasOwnProperty("name") && - thing.hasOwnProperty("mode") && - thing.hasOwnProperty("uid") && - thing.hasOwnProperty("gid") && - thing.hasOwnProperty("size") && - thing.hasOwnProperty("mtime") && - thing.hasOwnProperty("type")) return thing - - if (thing instanceof (fs.ReadStream)) { - thing.name = thing.path - } - - if (thing.name) { - thing._needStat = true - return thing - } - } - } - - return null -} - -Generator.prototype._processQueue = function processQueue () { - console.error("processQueue", this._queue[0]) - if (this._paused) return false - - if (this.currentFile || - this._queue.length && this._queue[0]._needStat) { - // either already processing one, or waiting on something. - return - } - - var f = this.currentFile = this._queue.shift() - if (!f) { - if (this._ended) { - // close it off with 2 blocks of nulls. - this.emit("data", new Buffer(new Array(512 * 2))) - this.emit("end") - this.emit("close") - } - return true - } - - if (f.type === Parser.File.types.Directory && - f.name.slice(-1) !== "/") { - f.name += "/" - } - - // write out a Pax header if the file isn't kosher. - if (this._needPax(f)) this._emitPax(f) - - // write out the header - f.ustar = true - this._emitHeader(f) - var fpos = 0 - , self = this - console.error("about to read body data", f) - f.on("data", function (c) { - self.emit("data", c) - self.fpos += c.length - }) - f.on("error", function (er) { self.emit("error", er) }) - f.on("end", function $END () { - // pad with \0 out to an even multiple of 512 bytes. - // this ensures that every file starts on a block. - var b = new Buffer(fpos % 512 || 512) - - for (var i = 0, l = b.length; i < l; i ++) b[i] = 0 - //console.log(b.length, b) - self.emit("data", b) - self.currentFile = null - self._processQueue() - }) - f.resume() -} - -Generator.prototype._needPax = function (f) { - // meh. why not? - return true - - return oddTextField(f.name, "NAME") || - oddTextField(f.link, "LINK") || - oddTextField(f.gname, "GNAME") || - oddTextField(f.uname, "UNAME") || - oddTextField(f.prefix, "PREFIX") -} - -// check if a text field is too long or non-ascii -function oddTextField (val, field) { - var nl = Buffer.byteLength(val) - , len = tar.fieldSize[field] - if (nl > len || nl !== val.length) return true -} - -// emit a Pax header of "key = val" for any file with -// odd or too-long field values. -Generator.prototype._emitPax = function (f) { - // since these tend to be relatively small, just go ahead - // and emit it all in-band. That saves having to keep - // track of the pax state in the generator, and we can - // go right back to emitting the file in the same tick. - var dir = f.name.replace(/[^\/]+\/?$/, "") - , base = f.name.substr(dir.length) - var pax = { name: dir + "PaxHeader/" +base - , mode: 0644 - , uid: f.uid - , gid: f.gid - , mtime: +f.mtime - // don't know size yet. - , size: -1 - , type: "x" // extended header - , ustar: true - , ustarVersion: "00" - , user: f.user || f.uname || "" - , group: f.group || f.gname || "" - , dev: { major: f.dev && f.dev.major || 0 - , minor: f.dev && f.dev.minor || 0 } - , prefix: f.prefix - , linkname: "" } - - // generate the Pax body - var kv = { path: (f.prefix ? f.prefix + "/" : "") + f.name - , atime: f.atime - , mtime: f.mtime - , ctime: f.ctime - , charset: "UTF-8" - , gid: f.gid - , uid: f.uid - , uname: f.user || f.uname || "" - , gname: f.group || f.gname || "" - , linkpath: f.linkpath || "" - , size: f.size - } - // "%d %s=%s\n", , , - // length includes the length of the length number, - // the key=val, and the \n. - var body = new Buffer(Object.keys(kv).map(function (key) { - if (!kv[key]) return ["", ""] - - var s = new Buffer(" " + key + "=" + kv[key]+"\n") - , digits = Math.floor(Math.log(s.length) / Math.log(10)) + 1 - - // if adding that many digits will make it go over that length, - // then add one to it - if (s.length > Math.pow(10, digits) - digits) digits ++ - - return [s.length + digits, s] - }).reduce(function (l, r) { - return l + r[0] + r[1] - }, "")) - - pax.size = body.length - this._emitHeader(pax) - this.emit("data", body) - // now the trailing buffer to make it an even number of 512 blocks - var b = new Buffer(512 + (body.length % 512 || 512)) - for (var i = 0, l = b.length; i < l; i ++) b[i] = 0 - this.emit("data", b) -} - -Generator.prototype._emitHeader = function (f) { - var header = new Buffer(new Array(512)) - , fields = tar.fields - , offs = tar.fieldOffs - , sz = tar.fieldSize - - addField(header, "NAME", f.name) - addField(header, "MODE", f.mode) - addField(header, "UID", f.uid) - addField(header, "GID", f.gid) - addField(header, "SIZE", f.size) - addField(header, "MTIME", +f.mtime) - // checksum is generated based on it being spaces - // then it's written as: "######\0 " - // where ### is a zero-lead 6-digit octal number - addField(header, "CKSUM", " ") - - addField(header, "TYPE", f.type) - addField(header, "LINKNAME", f.linkname || "") - if (f.ustar) { - console.error(">>> ustar!!") - addField(header, "USTAR", tar.ustar) - addField(header, "USTARVER", 0) - addField(header, "UNAME", f.user || "") - addField(header, "GNAME", f.group || "") - if (f.dev) { - addField(header, "DEVMAJ", f.dev.major || 0) - addField(header, "DEVMIN", f.dev.minor || 0) - } - addField(header, "PREFIX", f.prefix) - } else { - console.error(">>> no ustar!") - } - - // now the header is written except for checksum. - var ck = 0 - for (var i = 0; i < 512; i ++) ck += header[i] - addField(header, "CKSUM", nF(ck, 7)) - header[ offs[fields.CKSUM] + 7 ] = 0 - - this.emit("data", header) -} - -function addField (buf, field, val) { - var f = tar.fields[field] - console.error("Adding field", field, val) - val = typeof val === "number" - ? nF(val, tar.fieldSize[f]) - : new Buffer(val || "") - val.copy(buf, tar.fieldOffs[f]) -} - -function toBase256 (num, len) { - console.error("toBase256", num, len) - var positive = num > 0 - , buf = new Buffer(len) - if (!positive) { - // rare and slow - var b = num.toString(2).substr(1) - , padTo = (len - 1) * 8 - b = new Array(padTo - b.length + 1).join("0") + b - - // take the 2's complement - var ht = b.match(/^([01]*)(10*)?$/) - , head = ht[1] - , tail = ht[2] - head = head.split("1").join("2") - .split("0").join("1") - .split("2").join("0") - b = head + tail - - buf[0] = 0xFF - for (var i = 1; i < len; i ++) { - buf[i] = parseInt(buf.substr(i * 8, 8), 2) - } - return buf - } - - buf[0] = 0x80 - for (var i = 1, l = len, p = l - 1; i < l; i ++, p --) { - buf[p] = num % 256 - num = Math.floor(num / 256) - } - return buf -} - -function nF (num, size) { - var ns = num.toString(8) - - if (num < 0 || ns.length >= size) { - // make a base 256 buffer - // then return it - return toBase256(num, size) - } - - var buf = new Buffer(size) - ns = new Array(size - ns.length - 1).join("0") + ns + " " - buf[size - 1] = 0 - buf.asciiWrite(ns) - return buf -} diff --git a/node_modules/tar/old/parser.js b/node_modules/tar/old/parser.js deleted file mode 100644 index 1582ee7..0000000 --- a/node_modules/tar/old/parser.js +++ /dev/null @@ -1,344 +0,0 @@ -module.exports = Parser -Parser.create = create -Parser.File = File - -var tar = require("./tar") - , Stream = require("stream").Stream - , fs = require("fs") - -function create (cb) { - return new Parser(cb) -} - -var s = 0 - , HEADER = s ++ - , BODY = s ++ - , PAD = s ++ - -function Parser (cb) { - this.fields = tar.fields - this.fieldSize = tar.fieldSize - this.state = HEADER - this.position = 0 - this.currentFile = null - this._header = [] - this._headerPosition = 0 - this._bodyPosition = 0 - this.writable = true - Stream.apply(this) - if (cb) this.on("file", cb) -} - -Parser.prototype = Object.create(Stream.prototype) - -Parser.prototype.write = function (chunk) { - switch (this.state) { - case HEADER: - // buffer up to 512 bytes in memory, and then - // parse it, emit a "file" event, and stream the rest - this._header.push(chunk) - this._headerPosition += chunk.length - if (this._headerPosition >= tar.headerSize) { - return this._parseHeader() - } - return true - - case BODY: - // stream it through until the end of the file is reached, - // and then step over any \0 byte padding. - var cl = chunk.length - , bp = this._bodyPosition - , np = cl + bp - , s = this.currentFile.size - if (np < s) { - this._bodyPosition = np - return this.currentFile.write(chunk) - } - var c = chunk.slice(0, (s - bp)) - this.currentFile.write(c) - this._closeFile() - return this.write(chunk.slice(s - bp)) - - case PAD: - for (var i = 0, l = chunk.length; i < l; i ++) { - if (chunk[i] !== 0) { - this.state = HEADER - return this.write(chunk.slice(i)) - } - } - } - return true -} - -Parser.prototype.end = function (chunk) { - if (chunk) this.write(chunk) - if (this.currentFile) this._closeFile() - this.emit("end") - this.emit("close") -} - -// at this point, we have at least 512 bytes of header chunks -Parser.prototype._parseHeader = function () { - var hp = this._headerPosition - , last = this._header.pop() - , rem - - if (hp < 512) return this.emit("error", new Error( - "Trying to parse header before finished")) - - if (hp > 512) { - var ll = last.length - , llIntend = 512 - hp + ll - rem = last.slice(llIntend) - last = last.slice(0, llIntend) - } - this._header.push(last) - - var fields = tar.fields - , pos = 0 - , field = 0 - , fieldEnds = tar.fieldEnds - , fieldSize = tar.fieldSize - , set = {} - , fpos = 0 - - Object.keys(fieldSize).forEach(function (f) { - set[ fields[f] ] = new Buffer(fieldSize[f]) - }) - - this._header.forEach(function (chunk) { - for (var i = 0, l = chunk.length; i < l; i ++, pos ++, fpos ++) { - if (pos >= fieldEnds[field]) { - field ++ - fpos = 0 - } - // header is null-padded, so when the fields run out, - // just finish. - if (null === fields[field]) return - set[fields[field]][fpos] = chunk[i] - } - }) - - this._header.length = 0 - - // type definitions here: - // http://cdrecord.berlios.de/private/man/star/star.4.html - var type = set.TYPE.toString() - , file = this.currentFile = new File(set) - if (type === "\0" || - type >= "0" && type <= "7") { - this._addExtended(file) - this.emit("file", file) - } else if (type === "g") { - this._global = this._global || {} - readPax(this, file, this._global) - } else if (type === "h" || type === "x" || type === "X") { - this._extended = this._extended || {} - readPax(this, file, this._extended) - } else if (type === "K") { - this._readLongField(file, "linkname") - } else if (type === "L") { - this._readLongField(file, "name") - } - - this.state = BODY - if (rem) return this.write(rem) - return true -} - -function readPax (self, file, obj) { - var buf = "" - file.on("data", function (c) { - buf += c - var lines = buf.split(/\r?\n/) - buf = lines.pop() - lines.forEach(function (line) { - line = line.match(/^[0-9]+ ([^=]+)=(.*)/) - if (!line) return - obj[line[1]] = line[2] - }) - }) -} - -Parser.prototype._readLongField = function (f, field) { - var self = this - this._longFields[field] = "" - f.on("data", function (c) { - self._longFields[field] += c - }) -} - -Parser.prototype._addExtended = function (file) { - var g = this._global || {} - , e = this._extended || {} - file.extended = {} - ;[g, e].forEach(function (h) { - Object.keys(h).forEach(function (k) { - file.extended[k] = h[k] - // handle known fields - switch (k) { - case "path": file.name = h[k]; break - case "ctime": file.ctime = new Date(1000 * h[k]); break - case "mtime": file.mtime = new Date(1000 * h[k]); break - case "gid": file.gid = parseInt(h[k], 10); break - case "uid": file.uid = parseInt(h[k], 10); break - case "charset": file.charset = h[k]; break - case "gname": file.group = h[k]; break - case "uname": file.user = h[k]; break - case "linkpath": file.linkname = h[k]; break - case "size": file.size = parseInt(h[k], 10); break - case "SCHILY.devmajor": file.dev.major = parseInt(h[k], 10); break - case "SCHILY.devminor": file.dev.minor = parseInt(h[k], 10); break - } - }) - }) - var lf = this._longFields || {} - Object.keys(lf).forEach(function (f) { - file[f] = lf[f] - }) - this._extended = {} - this._longFields = {} -} - -Parser.prototype._closeFile = function () { - if (!this.currentFile) return this.emit("error", new Error( - "Trying to close without current file")) - - this._headerPosition = this._bodyPosition = 0 - this.currentFile.end() - this.currentFile = null - this.state = PAD -} - - -// file stuff - -function strF (f) { - return f.toString("ascii").split("\0").shift() || "" -} - -function parse256 (buf) { - // first byte MUST be either 80 or FF - // 80 for positive, FF for 2's comp - var positive - if (buf[0] === 0x80) positive = true - else if (buf[0] === 0xFF) positive = false - else return 0 - - if (!positive) { - // this is rare enough that the string slowness - // is not a big deal. You need *very* old files - // to ever hit this path. - var s = "" - for (var i = 1, l = buf.length; i < l; i ++) { - var byte = buf[i].toString(2) - if (byte.length < 8) { - byte = new Array(byte.length - 8 + 1).join("1") + byte - } - s += byte - } - var ht = s.match(/^([01]*)(10*)$/) - , head = ht[1] - , tail = ht[2] - head = head.split("1").join("2") - .split("0").join("1") - .split("2").join("0") - return -1 * parseInt(head + tail, 2) - } - - var sum = 0 - for (var i = 1, l = buf.length, p = l - 1; i < l; i ++, p--) { - sum += buf[i] * Math.pow(256, p) - } - return sum -} - -function nF (f) { - if (f[0] & 128 === 128) { - return parse256(f) - } - return parseInt(f.toString("ascii").replace(/\0+/g, "").trim(), 8) || 0 -} - -function bufferMatch (a, b) { - if (a.length != b.length) return false - for (var i = 0, l = a.length; i < l; i ++) { - if (a[i] !== b[i]) return false - } - return true -} - -function File (fields) { - this._raw = fields - this.name = strF(fields.NAME) - this.mode = nF(fields.MODE) - this.uid = nF(fields.UID) - this.gid = nF(fields.GID) - this.size = nF(fields.SIZE) - this.mtime = new Date(nF(fields.MTIME) * 1000) - this.cksum = nF(fields.CKSUM) - this.type = strF(fields.TYPE) - this.linkname = strF(fields.LINKNAME) - - this.ustar = bufferMatch(fields.USTAR, tar.ustar) - - if (this.ustar) { - this.ustarVersion = nF(fields.USTARVER) - this.user = strF(fields.UNAME) - this.group = strF(fields.GNAME) - this.dev = { major: nF(fields.DEVMAJ) - , minor: nF(fields.DEVMIN) } - this.prefix = strF(fields.PREFIX) - if (this.prefix) { - this.name = this.prefix + "/" + this.name - } - } - - this.writable = true - this.readable = true - Stream.apply(this) -} - -File.prototype = Object.create(Stream.prototype) - -File.types = { File: "0" - , HardLink: "1" - , SymbolicLink: "2" - , CharacterDevice: "3" - , BlockDevice: "4" - , Directory: "5" - , FIFO: "6" - , ContiguousFile: "7" } - -Object.keys(File.types).forEach(function (t) { - File.prototype["is"+t] = function () { - return File.types[t] === this.type - } - File.types[ File.types[t] ] = File.types[t] -}) - -// contiguous files are treated as regular files for most purposes. -File.prototype.isFile = function () { - return this.type === "0" && this.name.slice(-1) !== "/" - || this.type === "7" -} - -File.prototype.isDirectory = function () { - return this.type === "5" - || this.type === "0" && this.name.slice(-1) === "/" -} - -File.prototype.write = function (c) { - this.emit("data", c) - return true -} - -File.prototype.end = function (c) { - if (c) this.write(c) - this.emit("end") - this.emit("close") -} - -File.prototype.pause = function () { this.emit("pause") } - -File.prototype.resume = function () { this.emit("resume") } diff --git a/node_modules/tar/old/tar.js b/node_modules/tar/old/tar.js deleted file mode 100644 index f70c081..0000000 --- a/node_modules/tar/old/tar.js +++ /dev/null @@ -1,74 +0,0 @@ -// field names that every tar file must have. -// header is padded to 512 bytes. -var f = 0 - , fields = {} - , NAME = fields.NAME = f++ - , MODE = fields.MODE = f++ - , UID = fields.UID = f++ - , GID = fields.GID = f++ - , SIZE = fields.SIZE = f++ - , MTIME = fields.MTIME = f++ - , CKSUM = fields.CKSUM = f++ - , TYPE = fields.TYPE = f++ - , LINKNAME = fields.LINKNAME = f++ - , headerSize = 512 - , fieldSize = [] - -fieldSize[NAME] = 100 -fieldSize[MODE] = 8 -fieldSize[UID] = 8 -fieldSize[GID] = 8 -fieldSize[SIZE] = 12 -fieldSize[MTIME] = 12 -fieldSize[CKSUM] = 8 -fieldSize[TYPE] = 1 -fieldSize[LINKNAME] = 100 - -// "ustar\0" may introduce another bunch of headers. -// these are optional, and will be nulled out if not present. -var ustar = new Buffer(6) -ustar.asciiWrite("ustar\0") - -var USTAR = fields.USTAR = f++ - , USTARVER = fields.USTARVER = f++ - , UNAME = fields.UNAME = f++ - , GNAME = fields.GNAME = f++ - , DEVMAJ = fields.DEVMAJ = f++ - , DEVMIN = fields.DEVMIN = f++ - , PREFIX = fields.PREFIX = f++ -// terminate fields. -fields[f] = null - -fieldSize[USTAR] = 6 -fieldSize[USTARVER] = 2 -fieldSize[UNAME] = 32 -fieldSize[GNAME] = 32 -fieldSize[DEVMAJ] = 8 -fieldSize[DEVMIN] = 8 -fieldSize[PREFIX] = 155 - -var fieldEnds = {} - , fieldOffs = {} - , fe = 0 -for (var i = 0; i < f; i ++) { - fieldOffs[i] = fe - fieldEnds[i] = (fe += fieldSize[i]) -} - -// build a translation table of field names. -Object.keys(fields).forEach(function (f) { - fields[fields[f]] = f -}) - -exports.ustar = ustar -exports.fields = fields -exports.fieldSize = fieldSize -exports.fieldOffs = fieldOffs -exports.fieldEnds = fieldEnds -exports.headerSize = headerSize - -var Parser = exports.Parser = require("./parser") -exports.createParser = Parser.create - -var Generator = exports.Generator = require("./generator") -exports.createGenerator = Generator.create diff --git a/node_modules/tar/old/test/test-generator.js b/node_modules/tar/old/test/test-generator.js deleted file mode 100644 index dea2732..0000000 --- a/node_modules/tar/old/test/test-generator.js +++ /dev/null @@ -1,13 +0,0 @@ -// pipe this file to tar vt - -var Generator = require("../generator") - , fs = require("fs") - , path = require("path") - , ohm = fs.createReadStream(path.resolve(__dirname, "tar-files/Ω.txt")) - , foo = path.resolve(__dirname, "tar-files/foo.js") - , gen = Generator.create({cwd: __dirname}) - -gen.pipe(process.stdout) -gen.append(ohm) -//gen.append(foo) -gen.end() diff --git a/node_modules/tar/old/test/test-generator.tar b/node_modules/tar/old/test/test-generator.tar deleted file mode 100644 index 6752aa51de2f8362d8db9c622e8c44e5ae7c8463..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 3260 zcmeHHOA5j;5Y0NLm?o4@kU<8GnrD|xR6Q;-Q;cZVZJYu z7hE+tlxJVh)~;E3xA)cT`Iv?#u)%=-RpCKa0%tbTarjZD=iHt1G|%} zY9H)&vz*NN0*>Y03gjf=*6x%pDBjlP-CM!?mysJ=8T(SM l_)}Ub!Cui5jfPUL#4^Tme?G>_obzS|G6R``%)qz|yZ~{8NM-;4 diff --git a/node_modules/tar/old/test/test-generator.txt b/node_modules/tar/old/test/test-generator.txt deleted file mode 100644 index 349757ba692925ea24ac27eb77f256c6c0052fb3..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 3261 zcmeHHOA5j;5Y0NLm?o4@kU;zXEMbK;-VB(5Y5}!K5mV_1>9us@awi47_IyE*&~S8NXQK%1Ke)X<7YK)tAG{@rB(&1fa5Avk zxuW#JE*I0mm``AvudP5%5>8D|>5SrRnV-EC{0sP{6n<5K=O6nCp0TJqoeKr9N9Uqg hDF}?c>?VE4w9XZ;`%Bc9zoeZ=Ck2uMNr9vQ<5vbbNZP$|5kL z1Z1mJA^WRUFmusQ7k!&bsXOm?-Q~oTR#lh7Lo;JjawhYxLS*E(kMCuIFua5R=?en6 zi}hzHQ2}bRA?wbXA2oK&#-K=pe0|(LJ-@B?;kP8EokJiNq(;4NzLIV&ZI}hRQEm=( z^HHL>D;$d}W;*v<07z>-yZ`AonC!o{426VS6f?bZ;ro9&PJv`U6UYQIflOct1pWYk CGhK-Q diff --git a/node_modules/tar/old/test/test-tar.txt b/node_modules/tar/old/test/test-tar.txt deleted file mode 100644 index d9ac62cc5823cde33a0c0052136308972fa421b6..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 3073 zcmeH{&2GXl499!UQ{)8z+xcn_J#k^u4oIAKj3Cvbv2JR!sjtM#@Js~JUMkTONJxz@ zk^i (http://blog.izs.me/)", - "name": "tar", - "description": "tar for node", - "version": "0.1.3", - "repository": { - "type": "git", - "url": "git://github.com/isaacs/node-tar.git" - }, - "main": "tar.js", - "scripts": { - "test": "rm -rf test/tmp; tap test/*.js" - }, - "engines": { - "node": "~0.5.9 || 0.6 || 0.7 || 0.8" - }, - "dependencies": { - "inherits": "1.x", - "block-stream": "*", - "fstream": "0.1" - }, - "devDependencies": { - "tap": "0.x", - "rimraf": "1.x" - } -} diff --git a/node_modules/tar/tar.js b/node_modules/tar/tar.js deleted file mode 100644 index b9dbca4..0000000 --- a/node_modules/tar/tar.js +++ /dev/null @@ -1,172 +0,0 @@ -// field paths that every tar file must have. -// header is padded to 512 bytes. -var f = 0 - , fields = {} - , path = fields.path = f++ - , mode = fields.mode = f++ - , uid = fields.uid = f++ - , gid = fields.gid = f++ - , size = fields.size = f++ - , mtime = fields.mtime = f++ - , cksum = fields.cksum = f++ - , type = fields.type = f++ - , linkpath = fields.linkpath = f++ - , headerSize = 512 - , blockSize = 512 - , fieldSize = [] - -fieldSize[path] = 100 -fieldSize[mode] = 8 -fieldSize[uid] = 8 -fieldSize[gid] = 8 -fieldSize[size] = 12 -fieldSize[mtime] = 12 -fieldSize[cksum] = 8 -fieldSize[type] = 1 -fieldSize[linkpath] = 100 - -// "ustar\0" may introduce another bunch of headers. -// these are optional, and will be nulled out if not present. - -var ustar = fields.ustar = f++ - , ustarver = fields.ustarver = f++ - , uname = fields.uname = f++ - , gname = fields.gname = f++ - , devmaj = fields.devmaj = f++ - , devmin = fields.devmin = f++ - , prefix = fields.prefix = f++ - , fill = fields.fill = f++ - -// terminate fields. -fields[f] = null - -fieldSize[ustar] = 6 -fieldSize[ustarver] = 2 -fieldSize[uname] = 32 -fieldSize[gname] = 32 -fieldSize[devmaj] = 8 -fieldSize[devmin] = 8 -fieldSize[prefix] = 155 -fieldSize[fill] = 12 - -// nb: prefix field may in fact be 130 bytes of prefix, -// a null char, 12 bytes for atime, 12 bytes for ctime. -// -// To recognize this format: -// 1. prefix[130] === ' ' or '\0' -// 2. atime and ctime are octal numeric values -// 3. atime and ctime have ' ' in their last byte - -var fieldEnds = {} - , fieldOffs = {} - , fe = 0 -for (var i = 0; i < f; i ++) { - fieldOffs[i] = fe - fieldEnds[i] = (fe += fieldSize[i]) -} - -// build a translation table of field paths. -Object.keys(fields).forEach(function (f) { - if (fields[f] !== null) fields[fields[f]] = f -}) - -// different values of the 'type' field -// paths match the values of Stats.isX() functions, where appropriate -var types = - { 0: "File" - , "\0": "OldFile" // like 0 - , 1: "Link" - , 2: "SymbolicLink" - , 3: "CharacterDevice" - , 4: "BlockDevice" - , 5: "Directory" - , 6: "FIFO" - , 7: "ContiguousFile" // like 0 - // posix headers - , g: "GlobalExtendedHeader" // k=v for the rest of the archive - , x: "ExtendedHeader" // k=v for the next file - // vendor-specific stuff - , A: "SolarisACL" // skip - , D: "GNUDumpDir" // like 5, but with data, which should be skipped - , I: "Inode" // metadata only, skip - , K: "NextFileHasLongLinkpath" // data = link path of next file - , L: "NextFileHasLongPath" // data = path of next file - , M: "ContinuationFile" // skip - , N: "OldGnuLongPath" // like L - , S: "SparseFile" // skip - , V: "TapeVolumeHeader" // skip - , X: "OldExtendedHeader" // like x - } - -Object.keys(types).forEach(function (t) { - types[types[t]] = types[types[t]] || t -}) - -// values for the mode field -var modes = - { suid: 04000 // set uid on extraction - , sgid: 02000 // set gid on extraction - , svtx: 01000 // set restricted deletion flag on dirs on extraction - , uread: 0400 - , uwrite: 0200 - , uexec: 0100 - , gread: 040 - , gwrite: 020 - , gexec: 010 - , oread: 4 - , owrite: 2 - , oexec: 1 - , all: 07777 - } - -var numeric = - { mode: true - , uid: true - , gid: true - , size: true - , mtime: true - , devmaj: true - , devmin: true - , cksum: true - , atime: true - , ctime: true - , dev: true - , ino: true - , nlink: true - } - -Object.keys(modes).forEach(function (t) { - modes[modes[t]] = modes[modes[t]] || t -}) - -var knownExtended = - { atime: true - , charset: true - , comment: true - , ctime: true - , gid: true - , gname: true - , linkpath: true - , mtime: true - , path: true - , realtime: true - , security: true - , size: true - , uid: true - , uname: true } - - -exports.fields = fields -exports.fieldSize = fieldSize -exports.fieldOffs = fieldOffs -exports.fieldEnds = fieldEnds -exports.types = types -exports.modes = modes -exports.numeric = numeric -exports.headerSize = headerSize -exports.blockSize = blockSize -exports.knownExtended = knownExtended - -exports.Pack = require("./lib/pack.js") -exports.Parse = require("./lib/parse.js") -exports.Extract = require("./lib/extract.js") diff --git a/node_modules/tar/test/extract.js b/node_modules/tar/test/extract.js deleted file mode 100644 index e2dea5c..0000000 --- a/node_modules/tar/test/extract.js +++ /dev/null @@ -1,406 +0,0 @@ -var tap = require("tap") - , tar = require("../tar.js") - , fs = require("fs") - , path = require("path") - , file = path.resolve(__dirname, "fixtures/c.tar") - , target = path.resolve(__dirname, "tmp/extract-test") - , index = 0 - , fstream = require("fstream") - - , ee = 0 - , expectEntries = -[ { path: 'c.txt', - mode: '644', - type: '0', - depth: undefined, - size: 513, - linkpath: '', - nlink: undefined, - dev: undefined, - ino: undefined }, - { path: 'cc.txt', - mode: '644', - type: '0', - depth: undefined, - size: 513, - linkpath: '', - nlink: undefined, - dev: undefined, - ino: undefined }, - { path: 'r/e/a/l/l/y/-/d/e/e/p/-/f/o/l/d/e/r/-/p/a/t/h/cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc', - mode: '644', - type: '0', - depth: undefined, - size: 100, - linkpath: '', - nlink: undefined, - dev: undefined, - ino: undefined }, - { path: 'Ω.txt', - mode: '644', - type: '0', - depth: undefined, - size: 2, - linkpath: '', - nlink: undefined, - dev: undefined, - ino: undefined }, - { path: 'Ω.txt', - mode: '644', - type: '0', - depth: undefined, - size: 2, - linkpath: '', - nlink: 1, - dev: 234881026, - ino: 51693379 }, - { path: '200ccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc', - mode: '644', - type: '0', - depth: undefined, - size: 200, - linkpath: '', - nlink: 1, - dev: 234881026, - ino: 51681874 }, - { path: '200ccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc', - mode: '644', - type: '0', - depth: undefined, - size: 201, - linkpath: '', - nlink: undefined, - dev: undefined, - ino: undefined }, - { path: '200LLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLL', - mode: '777', - type: '2', - depth: undefined, - size: 0, - linkpath: '200ccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc', - nlink: undefined, - dev: undefined, - ino: undefined }, - { path: '200-hard', - mode: '644', - type: '0', - depth: undefined, - size: 200, - linkpath: '', - nlink: 2, - dev: 234881026, - ino: 51681874 }, - { path: '200ccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc', - mode: '644', - type: '1', - depth: undefined, - size: 0, - linkpath: path.resolve(target, '200-hard'), - nlink: 2, - dev: 234881026, - ino: 51681874 } ] - - , ef = 0 - , expectFiles = -[ { path: '', - mode: '40755', - type: 'Directory', - depth: 0, - size: 306, - linkpath: undefined, - nlink: 9 }, - { path: '/200-hard', - mode: '100644', - type: 'File', - depth: 1, - size: 200, - linkpath: undefined, - nlink: 2 }, - { path: '/200ccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc', - mode: '100644', - type: 'Link', - depth: 1, - size: 200, - linkpath: '/Users/isaacs/dev-src/js/node-tar/test/tmp/extract-test/200-hard', - nlink: 2 }, - { path: '/200LLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLL', - mode: '120777', - type: 'SymbolicLink', - depth: 1, - size: 200, - linkpath: '200ccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc', - nlink: 1 }, - { path: '/c.txt', - mode: '100644', - type: 'File', - depth: 1, - size: 513, - linkpath: undefined, - nlink: 1 }, - { path: '/cc.txt', - mode: '100644', - type: 'File', - depth: 1, - size: 513, - linkpath: undefined, - nlink: 1 }, - { path: '/r', - mode: '40755', - type: 'Directory', - depth: 1, - size: 102, - linkpath: undefined, - nlink: 3 }, - { path: '/r/e', - mode: '40755', - type: 'Directory', - depth: 2, - size: 102, - linkpath: undefined, - nlink: 3 }, - { path: '/r/e/a', - mode: '40755', - type: 'Directory', - depth: 3, - size: 102, - linkpath: undefined, - nlink: 3 }, - { path: '/r/e/a/l', - mode: '40755', - type: 'Directory', - depth: 4, - size: 102, - linkpath: undefined, - nlink: 3 }, - { path: '/r/e/a/l/l', - mode: '40755', - type: 'Directory', - depth: 5, - size: 102, - linkpath: undefined, - nlink: 3 }, - { path: '/r/e/a/l/l/y', - mode: '40755', - type: 'Directory', - depth: 6, - size: 102, - linkpath: undefined, - nlink: 3 }, - { path: '/r/e/a/l/l/y/-', - mode: '40755', - type: 'Directory', - depth: 7, - size: 102, - linkpath: undefined, - nlink: 3 }, - { path: '/r/e/a/l/l/y/-/d', - mode: '40755', - type: 'Directory', - depth: 8, - size: 102, - linkpath: undefined, - nlink: 3 }, - { path: '/r/e/a/l/l/y/-/d/e', - mode: '40755', - type: 'Directory', - depth: 9, - size: 102, - linkpath: undefined, - nlink: 3 }, - { path: '/r/e/a/l/l/y/-/d/e/e', - mode: '40755', - type: 'Directory', - depth: 10, - size: 102, - linkpath: undefined, - nlink: 3 }, - { path: '/r/e/a/l/l/y/-/d/e/e/p', - mode: '40755', - type: 'Directory', - depth: 11, - size: 102, - linkpath: undefined, - nlink: 3 }, - { path: '/r/e/a/l/l/y/-/d/e/e/p/-', - mode: '40755', - type: 'Directory', - depth: 12, - size: 102, - linkpath: undefined, - nlink: 3 }, - { path: '/r/e/a/l/l/y/-/d/e/e/p/-/f', - mode: '40755', - type: 'Directory', - depth: 13, - size: 102, - linkpath: undefined, - nlink: 3 }, - { path: '/r/e/a/l/l/y/-/d/e/e/p/-/f/o', - mode: '40755', - type: 'Directory', - depth: 14, - size: 102, - linkpath: undefined, - nlink: 3 }, - { path: '/r/e/a/l/l/y/-/d/e/e/p/-/f/o/l', - mode: '40755', - type: 'Directory', - depth: 15, - size: 102, - linkpath: undefined, - nlink: 3 }, - { path: '/r/e/a/l/l/y/-/d/e/e/p/-/f/o/l/d', - mode: '40755', - type: 'Directory', - depth: 16, - size: 102, - linkpath: undefined, - nlink: 3 }, - { path: '/r/e/a/l/l/y/-/d/e/e/p/-/f/o/l/d/e', - mode: '40755', - type: 'Directory', - depth: 17, - size: 102, - linkpath: undefined, - nlink: 3 }, - { path: '/r/e/a/l/l/y/-/d/e/e/p/-/f/o/l/d/e/r', - mode: '40755', - type: 'Directory', - depth: 18, - size: 102, - linkpath: undefined, - nlink: 3 }, - { path: '/r/e/a/l/l/y/-/d/e/e/p/-/f/o/l/d/e/r/-', - mode: '40755', - type: 'Directory', - depth: 19, - size: 102, - linkpath: undefined, - nlink: 3 }, - { path: '/r/e/a/l/l/y/-/d/e/e/p/-/f/o/l/d/e/r/-/p', - mode: '40755', - type: 'Directory', - depth: 20, - size: 102, - linkpath: undefined, - nlink: 3 }, - { path: '/r/e/a/l/l/y/-/d/e/e/p/-/f/o/l/d/e/r/-/p/a', - mode: '40755', - type: 'Directory', - depth: 21, - size: 102, - linkpath: undefined, - nlink: 3 }, - { path: '/r/e/a/l/l/y/-/d/e/e/p/-/f/o/l/d/e/r/-/p/a/t', - mode: '40755', - type: 'Directory', - depth: 22, - size: 102, - linkpath: undefined, - nlink: 3 }, - { path: '/r/e/a/l/l/y/-/d/e/e/p/-/f/o/l/d/e/r/-/p/a/t/h', - mode: '40755', - type: 'Directory', - depth: 23, - size: 102, - linkpath: undefined, - nlink: 3 }, - { path: '/r/e/a/l/l/y/-/d/e/e/p/-/f/o/l/d/e/r/-/p/a/t/h/cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc', - mode: '100644', - type: 'File', - depth: 24, - size: 100, - linkpath: undefined, - nlink: 1 }, - { path: '/Ω.txt', - mode: '100644', - type: 'File', - depth: 1, - size: 2, - linkpath: undefined, - nlink: 1 } ] - - - -// The extract class basically just pipes the input -// to a Reader, and then to a fstream.DirWriter - -// So, this is as much a test of fstream.Reader and fstream.Writer -// as it is of tar.Extract, but it sort of makes sense. - -tap.test("extract test", function (t) { - var extract = tar.Extract(target) - var inp = fs.createReadStream(file) - - // give it a weird buffer size to try to break in odd places - inp.bufferSize = 1234 - - inp.pipe(extract) - - extract.on("end", function () { - t.equal(ee, expectEntries.length, "should see "+ee+" entries") - - // should get no more entries after end - extract.removeAllListeners("entry") - extract.on("entry", function (e) { - t.fail("Should not get entries after end!") - }) - - next() - }) - - extract.on("entry", function (entry) { - var found = - { path: entry.path - , mode: entry.props.mode.toString(8) - , type: entry.props.type - , depth: entry.props.depth - , size: entry.props.size - , linkpath: entry.props.linkpath - , nlink: entry.props.nlink - , dev: entry.props.dev - , ino: entry.props.ino - } - - var wanted = expectEntries[ee ++] - - t.equivalent(found, wanted, "tar entry " + ee + " " + wanted.path) - }) - - function next () { - var r = fstream.Reader({ path: target - , type: "Directory" - // this is just to encourage consistency - , sort: "alpha" }) - - r.on("ready", function () { - foundEntry(r) - }) - - r.on("end", finish) - - function foundEntry (entry) { - var p = entry.path.substr(target.length) - var found = - { path: p - , mode: entry.props.mode.toString(8) - , type: entry.props.type - , depth: entry.props.depth - , size: entry.props.size - , linkpath: entry.props.linkpath - , nlink: entry.props.nlink - } - - var wanted = expectFiles[ef ++] - - t.equivalent(found, wanted, "unpacked file " + ef + " " + wanted.path) - - entry.on("entry", foundEntry) - } - - function finish () { - t.equal(ef, expectFiles.length, "should have "+ef+" items") - t.end() - } - } -}) diff --git a/node_modules/tar/test/fixtures/200.tar b/node_modules/tar/test/fixtures/200.tar deleted file mode 100644 index 7e3a8f3e77fa6081a8c32bfcfcdab57557bb60e2..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 3072 zcmeHHO;5ux49z*eBEMkR&PT%`2S7-hv;zVOiDT4dq5?Y97POy_E3G>)t*2$0pw1!6 z^Go8`etC%7d5WvlToFK-!-N0;XN(eHi^3t#Y}BuJW(_JtX9+E8c7QgdL8z@bgMGDK zY&evvjj?QxU&yre`nY@dnBh@sgn3aeLQtQvdkwkDpQEM5&XfeI?5d9xP~)}p{phi{ z#|nc;PHL}~i`$#WyZPezepWV#8Jl{~>i1ca+>TGoSia0w={t}%-XrjC(gR-An_$s- z^o5b=2e^K(>bHRMqN;ru%o)nwOJh|3ntSk<{f~ OrwmLPm@@FUGw=gL<}U)LWSD>|5lc=c#xhHE6ydzL=6+;bbZ%9j9p)5 zS>KQb_ya^D4n!yCQvivWHHc@La>7$TZl5+GV6%1)nQ(Q*huODTNyNDZ+(z)i3hfG= ze}y1S4z1e!n;MYgsnmGK@&6}pzc+QQwfA_^eE9o6dddTc6iYS8kr|LBjROdo!<^3f YU)(g!F5coRKEAUtO@XFBQ=mu%z6f;$5C8xG diff --git a/node_modules/tar/test/fixtures/200longname.tar b/node_modules/tar/test/fixtures/200longname.tar deleted file mode 100644 index 5556567e1511b94317eded255d1827ea936402a1..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 3072 zcmeH{K?=km3`MiUSkcc&cFxQL|-}>^KU4?+vxh+=W>P(NjZ&US%<3Gf0fEPAs zj{OHyYo&t6Y2c5)j~t}0|A{pBk`)gcP)daw1m diff --git a/node_modules/tar/test/fixtures/a.hex b/node_modules/tar/test/fixtures/a.hex deleted file mode 100644 index 529e9cb..0000000 --- a/node_modules/tar/test/fixtures/a.hex +++ /dev/null @@ -1,14 +0,0 @@ --- header -- -612e7478740000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000303030363434200030353737363120003030303032342000303030303030303034303120313136353133363033333320303132343531002030000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 a.txt...............................................................................................000644..057761..000024..00000000401.11651360333.012451..0................................................................................................... -00757374617200303069736161637300000000000000000000000000000000000000000000000000007374616666000000000000000000000000000000000000000000000000000000303030303030200030303030303020000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 .ustar.00isaacs..........................staff...........................000000..000000......................................................................................................................................................................... - --- file contents -- -61616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -61000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 a............................................................................................................................................................................................................................................................... - --- tar eof -- -00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 ................................................................................................................................................................................................................................................................ -00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 ................................................................................................................................................................................................................................................................ -00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 ................................................................................................................................................................................................................................................................ -00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 ................................................................................................................................................................................................................................................................ - diff --git a/node_modules/tar/test/fixtures/a.tar b/node_modules/tar/test/fixtures/a.tar deleted file mode 100644 index 27604d7ec37fb71f6906a9ca689a05947faf3421..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 2048 zcmeHENeX~44D3_#0!f-K?+HS|tF7SkjaZNMRuSx6LYR=uOk^s1F@1rE!8tJKV+^EK zVb8w8ApueF!~vNZkgW4$0Q<_iwr{z}s#2CLGUxV19ZRWAS2MRMc$oYYC4a}KzA?m% M1V#cQf%g(P0GjxA*Z=?k diff --git a/node_modules/tar/test/fixtures/a.txt b/node_modules/tar/test/fixtures/a.txt deleted file mode 100644 index a6c4069..0000000 --- a/node_modules/tar/test/fixtures/a.txt +++ /dev/null @@ -1 +0,0 @@ -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa \ No newline at end of file diff --git a/node_modules/tar/test/fixtures/b.hex b/node_modules/tar/test/fixtures/b.hex deleted file mode 100644 index cf36eb6..0000000 --- a/node_modules/tar/test/fixtures/b.hex +++ /dev/null @@ -1,14 +0,0 @@ --- normal header -- -622e7478740000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000303030363434200030353737363120003030303032342000303030303030303130303020313136353133363036373720303132343631002030000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 b.txt...............................................................................................000644..057761..000024..00000001000.11651360677.012461..0................................................................................................... -00757374617200303069736161637300000000000000000000000000000000000000000000000000007374616666000000000000000000000000000000000000000000000000000000303030303030200030303030303020000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 .ustar.00isaacs..........................staff...........................000000..000000......................................................................................................................................................................... - --- file contents - exactly 512 bytes, no null padding -- -62626262626262626262626262626262626262626262626262626262626262626262626262626262626262626262626262626262626262626262626262626262626262626262626262626262626262626262626262626262626262626262626262626262626262626262626262626262626262626262626262626262626262626262626262626262626262626262626262626262626262626262626262626262626262626262626262626262626262626262626262626262626262626262626262626262626262626262626262626262626262626262626262626262626262626262626262626262626262626262626262626262626262626262626262626262 bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb -62626262626262626262626262626262626262626262626262626262626262626262626262626262626262626262626262626262626262626262626262626262626262626262626262626262626262626262626262626262626262626262626262626262626262626262626262626262626262626262626262626262626262626262626262626262626262626262626262626262626262626262626262626262626262626262626262626262626262626262626262626262626262626262626262626262626262626262626262626262626262626262626262626262626262626262626262626262626262626262626262626262626262626262626262626262 bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb - --- tar eof blocks -- -00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 ................................................................................................................................................................................................................................................................ -00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 ................................................................................................................................................................................................................................................................ -00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 ................................................................................................................................................................................................................................................................ -00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 ................................................................................................................................................................................................................................................................ - diff --git a/node_modules/tar/test/fixtures/b.tar b/node_modules/tar/test/fixtures/b.tar deleted file mode 100644 index 2d8e7b3ac7a3d7a20bc21576e0b65c745c8efdda..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 2048 zcmeHF(F%Yd4D?g>1+kgV@6kZ$H4Xaw7S^M^8A9I67(2GRV`0iiR&9ZZYz!#0&M`?9 z=&LUvDL}-QW=3`nkhEb^fNf=!?R(086De!*eo6IE$NYRnVzY$QdCC{ksQd5 zWqa2FX?HgJnD^|C^6~m^9r-N)V3dj@(AFBHCl%r9bwL1(5sjul3rfU*LTMAl;CET| z=)Z2)SxHM-+-6yR`}~a5?eg+@@WW=BO~oBO2L;MQIcW@x2E~nGG29r)bN>c_)cgzd zzj6BC2p#l42QQqo@(Y{KgZ}4`vf<9bAp$-6ACQ6r=l=`TsHKcSNr~#f^?#WZNtRsG z?@w};%&Ar+H}rOytfd*}Nzdf104z{#)3Re+};Z?~Vf_Cw~5iI=;!) zSJRsMBLQ)~Ui>VkC~;z?oxsGkWslk>U~ojow_o0$U(CLZ=f&@-kSa|Pgc%9hv@e#c zDV^v}Bn>jcv}s;mFP1;17{U$?-rivje^S4hyifjv{omk<`z_diZj29WzK#7C0A7N@ z$X$(fo&SPX_5GiV|0P)#kV;4h_Md}O1VZfq_#(d-p6VF1?ZTMU{kB{fg+i;5Oyk+b zySJaojrsavoRg+c#&k@xLE4+rDJS}6zpolsK%;A9-FuH?UYI#4D5mHn4mX=@^o zQUPoJAIX1T{$C$_SY+LKH5~NcmQ^41aG4y|A+jK*Qdqyh>sFJ1SNJ@ z%Ef(rTT-EpXjD%O+KZ&uzX|4;6J-1k4M=Rahc`t$gP|&5&>iv!QGj>xP@+~1GgqIgnYM0_(4I+AGa5#u~ z(yHl>{s{xoz`Yj~CP3;ui35C<>N>uaHDpDZO9)d%gs#O{0Xl!VpMuKfuSR3Y&98tA O#tfJNGhhZjF|Y%u7Z)G^ diff --git a/node_modules/tar/test/fixtures/hardlink-1 b/node_modules/tar/test/fixtures/hardlink-1 deleted file mode 100644 index c2b6e50..0000000 --- a/node_modules/tar/test/fixtures/hardlink-1 +++ /dev/null @@ -1 +0,0 @@ -200ccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc \ No newline at end of file diff --git a/node_modules/tar/test/fixtures/hardlink-2 b/node_modules/tar/test/fixtures/hardlink-2 deleted file mode 100644 index c2b6e50..0000000 --- a/node_modules/tar/test/fixtures/hardlink-2 +++ /dev/null @@ -1 +0,0 @@ -200ccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc \ No newline at end of file diff --git a/node_modules/tar/test/fixtures/omega.hex b/node_modules/tar/test/fixtures/omega.hex deleted file mode 100644 index eef8796..0000000 --- a/node_modules/tar/test/fixtures/omega.hex +++ /dev/null @@ -1,22 +0,0 @@ --- pax header -- -5061784865616465722fcea92e747874000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000303030363434200030353737363120003030303032342000303030303030303031373020313135343337313036313120303135303531002078000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 PaxHeader/Ω.txt....................................................................................000644..057761..000024..00000000170.11543710611.015051..x................................................................................................... -00757374617200303069736161637300000000000000000000000000000000000000000000000000007374616666000000000000000000000000000000000000000000000000000000303030303030200030303030303020000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 .ustar.00isaacs..........................staff...........................000000..000000......................................................................................................................................................................... - --- pax header contents -- -313520706174683dcea92e7478740a3230206374696d653d313330313435393237380a3230206174696d653d313330313431353738330a323420534348494c592e6465763d3233343838313032360a323320534348494c592e696e6f3d32333737323936360a313820534348494c592e6e6c696e6b3d310a00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 15.path=Ω.txt.20.ctime=1301459278.20.atime=1301415783.24.SCHILY.dev=234881026.23.SCHILY.ino=23772966.18.SCHILY.nlink=1......................................................................................................................................... -00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 ................................................................................................................................................................................................................................................................ - --- normal header -- -cea92e74787400000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000303030363434200030353737363120003030303032342000303030303030303030303220313135343337313036313120303133303732002030000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 Ω.txt..............................................................................................000644..057761..000024..00000000002.11543710611.013072..0................................................................................................... -00757374617200303069736161637300000000000000000000000000000000000000000000000000007374616666000000000000000000000000000000000000000000000000000000303030303030200030303030303020000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 .ustar.00isaacs..........................staff...........................000000..000000......................................................................................................................................................................... - --- file contents -- -cea90000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 Ω.............................................................................................................................................................................................................................................................. -00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 ................................................................................................................................................................................................................................................................ - --- tar eof marker -- -00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 ................................................................................................................................................................................................................................................................ -00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 ................................................................................................................................................................................................................................................................ -00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 ................................................................................................................................................................................................................................................................ -00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 ................................................................................................................................................................................................................................................................ - diff --git a/node_modules/tar/test/fixtures/omega.tar b/node_modules/tar/test/fixtures/omega.tar deleted file mode 100644 index 6590e58ce41c56920dfe19fa8b9d18c6f5d8d839..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 3072 zcmeH{&x*n@5XO7XQ{)NUnf#l0=xHws9u_=#3|iT;S{ECoujI@0nKs3(1qL6ZasFs;GvD|uLI8kKif5pS42Cs?=<@$S0*4)Ou3)56k^Izw`^ZV;F0etJrW09i-RC+GR zcA6VB)MO^V z)agG^)c>n|JV@-#HqZIC`a0F@C!n>Y?!rI&xXBpmDeY|ioD f>wnLG0a{1>?-2~Qi~1i9+ZZ__5D|z73>kq>zL21R diff --git a/node_modules/tar/test/fixtures/packtest/omega.txt b/node_modules/tar/test/fixtures/packtest/omega.txt deleted file mode 100644 index 1ca042f..0000000 --- a/node_modules/tar/test/fixtures/packtest/omega.txt +++ /dev/null @@ -1 +0,0 @@ -Ω \ No newline at end of file diff --git a/node_modules/tar/test/fixtures/packtest/star.4.html b/node_modules/tar/test/fixtures/packtest/star.4.html deleted file mode 100644 index b600d77..0000000 --- a/node_modules/tar/test/fixtures/packtest/star.4.html +++ /dev/null @@ -1,1184 +0,0 @@ - - -Manpage for star.4 - - - - -
-

NAME

-     star - tape archive file format
-
-
-
-

DESCRIPTION

-     Tar Archives are layered archives.  The basic  structure  is
-     defined by the POSIX.1-1988 archive format and documented in
-     the BASIC TAR HEADER DESCRIPTION section below.  The  higher
-     level  structure  is  defined  by  the POSIX.1-2001 extended
-     headers and documented in  the  EXTENDED  TAR  (PAX)  HEADER
-     STRUCTURE  section below.  POSIX.1-2001 extended headers are
-     pseudo files that contain an unlimited  number  of  extended
-     header  keywords  and associated values. The header keywords
-     are documented in the EXTENDED  TAR  (PAX)  HEADER  KEYWORDS
-     section below.
-
-
-
-

BASIC TAR HEADER DESCRIPTION

-     Physically, a POSIX.1-1988 tar archive consists of a  series
-     of  fixed  sized blocks of TBLOCK (512) characters.  It con-
-     tains a series of  file  entries  terminated  by  a  logical
-     end-of-archive  marker,  which consists of two blocks of 512
-     bytes of binary zeroes.  Each file entry is represented by a
-     header block that describes the file followed by one or more
-     blocks with the content of the file. The length of each file
-     is rounded up to a multiple of 512 bytes.
-
-     A number of TBLOCK sizes blocks are grouped  together  to  a
-     tape  record  for  physical I/O operations. Each record of n
-     blocks is written with a single write(2) operation.  On mag-
-     netic tapes, this results in a single tape record.
-
-     The header block is defined in star.h as follows:
-     /*
-      * POSIX.1-1988 field size values and magic.
-      */
-     #define   TBLOCK         512
-     #define   NAMSIZ         100
-     #define   PFXSIZ         155
-
-     #define   TMODLEN        8
-     #define   TUIDLEN        8
-     #define   TGIDLEN        8
-     #define   TSIZLEN        12
-     #define   TMTMLEN        12
-     #define   TCKSLEN        8
-
-     #define   TMAGIC         "ustar"   /* ustar magic 6 chars + '\0' */
-     #define   TMAGLEN        6         /* "ustar" including '\0' */
-     #define   TVERSION       "00"
-     #define   TVERSLEN       2
-     #define   TUNMLEN        32
-     #define   TGNMLEN        32
-     #define   TDEVLEN        8
-
-Joerg Schilling       Last change: 05/10/19                     1
-
-
-Schily's USER COMMANDS                                   STAR(4L)
-
-     /*
-      * POSIX.1-1988 typeflag values
-      */
-     #define   REGTYPE        '0'  /* Regular File          */
-     #define   AREGTYPE       '\0' /* Regular File (outdated) */
-     #define   LNKTYPE        '1'  /* Hard Link             */
-     #define   SYMTYPE        '2'  /* Symbolic Link         */
-     #define   CHRTYPE        '3'  /* Character Special     */
-     #define   BLKTYPE        '4'  /* Block Special         */
-     #define   DIRTYPE        '5'  /* Directory             */
-     #define   FIFOTYPE       '6'  /* FIFO (named pipe)     */
-     #define   CONTTYPE       '7'  /* Contiguous File       */
-
-     /*
-      * POSIX.1-2001 typeflag extensions.
-      * POSIX.1-2001 calls the extended USTAR format PAX although it is
-      * definitely derived from and based on USTAR. The reason may be that
-      * POSIX.1-2001 calls the tar program outdated and lists the
-      * pax program as the successor.
-      */
-     #define   LF_GHDR        'g'  /* POSIX.1-2001 global extended header */
-     #define   LF_XHDR        'x'  /* POSIX.1-2001 extended header */
-
-     See section EXTENDED TAR  (PAX)  HEADER  KEYWORDS  for  more
-     information about the structure of a POSIX.1-2001 header.
-
-     /*
-      * star/gnu/Sun tar extensions:
-      *
-      * Note that the standards committee allows only capital A through
-      * capital Z for user-defined expansion.  This means that defining
-      * something as, say '8' is a *bad* idea.
-      */
-
-     #define   LF_ACL         'A'  /* Solaris Access Control List     */
-     #define   LF_DUMPDIR     'D'  /* GNU dump dir                    */
-     #define   LF_EXTATTR     'E'  /* Solaris Extended Attribute File */
-     #define   LF_META        'I'  /* Inode (metadata only) no file content */
-     #define   LF_LONGLINK    'K'  /* NEXT file has a long linkname   */
-     #define   LF_LONGNAME    'L'  /* NEXT file has a long name       */
-     #define   LF_MULTIVOL    'M'  /* Continuation file rest to be skipped */
-     #define   LF_NAMES       'N'  /* OLD GNU for names > 100 characters*/
-     #define   LF_SPARSE      'S'  /* This is for sparse files        */
-     #define   LF_VOLHDR      'V'  /* tape/volume header Ignore on extraction */
-     #define   LF_VU_XHDR     'X'  /* POSIX.1-2001 xtended (Sun VU version) */
-
-     /*
-      * Definitions for the t_mode field
-      */
-     #define   TSUID     04000     /* Set UID on execution  */
-     #define   TSGID     02000     /* Set GID on execution  */
-     #define   TSVTX     01000     /* On directories, restricted deletion flag */
-
-Joerg Schilling       Last change: 05/10/19                     2
-
-
-Schily's USER COMMANDS                                   STAR(4L)
-
-     #define   TUREAD    00400     /* Read by owner         */
-     #define   TUWRITE   00200     /* Write by owner special */
-     #define   TUEXEC    00100     /* Execute/search by owner */
-     #define   TGREAD    00040     /* Read by group         */
-     #define   TGWRITE   00020     /* Write by group        */
-     #define   TGEXEC    00010     /* Execute/search by group */
-     #define   TOREAD    00004     /* Read by other         */
-     #define   TOWRITE   00002     /* Write by other        */
-     #define   TOEXEC    00001     /* Execute/search by other */
-
-     #define   TALLMODES 07777     /* The low 12 bits       */
-
-     /*
-      * This is the ustar (Posix 1003.1) header.
-      */
-     struct header {
-          char t_name[NAMSIZ];     /*   0 Filename               */
-          char t_mode[8];          /* 100 Permissions            */
-          char t_uid[8];           /* 108 Numerical User ID      */
-          char t_gid[8];           /* 116 Numerical Group ID     */
-          char t_size[12];         /* 124 Filesize               */
-          char t_mtime[12];        /* 136 st_mtime               */
-          char t_chksum[8];        /* 148 Checksum               */
-          char t_typeflag;         /* 156 Typ of File            */
-          char t_linkname[NAMSIZ]; /* 157 Target of Links        */
-          char t_magic[TMAGLEN];   /* 257 "ustar"                */
-          char t_version[TVERSLEN]; /* 263 Version fixed to 00   */
-          char t_uname[TUNMLEN];   /* 265 User Name              */
-          char t_gname[TGNMLEN];   /* 297 Group Name             */
-          char t_devmajor[8];      /* 329 Major for devices      */
-          char t_devminor[8];      /* 337 Minor for devices      */
-          char t_prefix[PFXSIZ];   /* 345 Prefix for t_name      */
-                                   /* 500 End                    */
-          char t_mfill[12];        /* 500 Filler up to 512       */
-     };
-
-     /*
-      * star header specific definitions
-      */
-     #define   STMAGIC        "tar"     /* star magic */
-     #define   STMAGLEN       4         /* "tar" including '\0' */
-
-     /*
-      * This is the new (post Posix 1003.1-1988) xstar header
-      * defined in 1994.
-      *
-      * t_prefix[130]    is guaranteed to be ' ' to prevent ustar
-      *                  compliant implementations from failing.
-      * t_mfill & t_xmagic need to be zero for a 100% ustar compliant
-      *                  implementation, so setting t_xmagic to
-      *                  "tar" should be avoided in the future.
-      *
-
-Joerg Schilling       Last change: 05/10/19                     3
-
-
-Schily's USER COMMANDS                                   STAR(4L)
-
-      * A different method to recognize this format is to verify that
-      * t_prefix[130]              is equal to ' ' and
-      * t_atime[0]/t_ctime[0]      is an octal number and
-      * t_atime[11]                is equal to ' ' and
-      * t_ctime[11]                is equal to ' '.
-      *
-      * Note that t_atime[11]/t_ctime[11] may be changed in future.
-      */
-     struct xstar_header {
-          char t_name[NAMSIZ];     /*   0 Filename               */
-          char t_mode[8];          /* 100 Permissions            */
-          char t_uid[8];           /* 108 Numerical User ID      */
-          char t_gid[8];           /* 116 Numerical Group ID     */
-          char t_size[12];         /* 124 Filesize               */
-          char t_mtime[12];        /* 136 st_mtime               */
-          char t_chksum[8];        /* 148 Checksum               */
-          char t_typeflag;         /* 156 Typ of File            */
-          char t_linkname[NAMSIZ]; /* 157 Target of Links        */
-          char t_magic[TMAGLEN];   /* 257 "ustar"                */
-          char t_version[TVERSLEN]; /* 263 Version fixed to 00   */
-          char t_uname[TUNMLEN];   /* 265 User Name              */
-          char t_gname[TGNMLEN];   /* 297 Group Name             */
-          char t_devmajor[8];      /* 329 Major for devices      */
-          char t_devminor[8];      /* 337 Minor for devices      */
-          char t_prefix[131];      /* 345 Prefix for t_name      */
-          char t_atime[12];        /* 476 st_atime               */
-          char t_ctime[12];        /* 488 st_ctime               */
-          char t_mfill[8];         /* 500 Filler up to star magic     */
-          char t_xmagic[4];        /* 508 "tar"                  */
-     };
-
-     struct sparse {
-          char t_offset[12];
-          char t_numbytes[12];
-     };
-
-     #define   SPARSE_EXT_HDR  21
-
-     struct xstar_ext_header {
-          struct sparse t_sp[21];
-          char t_isextended;
-     };
-
-     typedef union hblock {
-          char dummy[TBLOCK];
-          long ldummy[TBLOCK/sizeof (long)]; /* force long alignment */
-          struct header            dbuf;
-          struct xstar_header      xstar_dbuf;
-          struct xstar_ext_header  xstar_ext_dbuf;
-     } TCB;
-
-Joerg Schilling       Last change: 05/10/19                     4
-
-
-Schily's USER COMMANDS                                   STAR(4L)
-
-     For maximum portability, all fields that  contain  character
-     strings should be limited to use the low 7 bits of a charac-
-     ter.
-
-     The  name,  linkname  and  prefix  field  contain  character
-     strings.  The  strings  are null terminated except when they
-     use the full space of 100 characters for the name  or  link-
-     name field or 155 characters for the prefix field.
-
-     If the prefix does not start with  a  null  character,  then
-     prefix and name need to be concatenated by using the prefix,
-     followed a slash character followed by the name field.  If a
-     null  character appears in name or prefix before the maximum
-     size is reached, the field in question is terminated.   This
-     way  file  names  up to 256 characters may be archived.  The
-     prefix is not used together with the linkname field, so  the
-     maximum length of a link name is 100 characters.
-
-     The fields magic, uname and gname  contain  null  terminated
-     character strings.
-
-     The version field contains the string "00" without a  trail-
-     ing  zero.  It cannot be set to different values as POSIX.1-
-     1988 did not specify  a  way  to  handle  different  version
-     strings.  The typeflag field contains a single character.
-
-     All  numeric  fields  contain  size-1  leading   zero-filled
-     numbers  using  octal  digits.   They are followed by one or
-     more space or null characters.  All  recent  implementations
-     only use one space or null character at the end of a numeri-
-     cal field to get maximum space for the octal  number.   Star
-     always uses a space character as terminator.  Numeric fields
-     with 8 characters may hold up to 7  octal  digits  (7777777)
-     which results is a maximum value of 2097151.  Numeric fields
-     with  12  characters  may  hold  up  to  11   octal   digits
-     (77777777777)   which   results   is   a  maximum  value  of
-     8589934591.
-
-     Star implements  a  vendor  specific  (and  thus  non-POSIX)
-     extension  to  put  bigger  numbers into the numeric fields.
-     This is done by using a base 256 coding.  The top bit of the
-     first character in the appropriate 8 character or 12 charac-
-     ter field is set to flag non octal coding.  If base 256 cod-
-     ing  is  in  use,  then all remaining characters are used to
-     code the number. This results in 7  base  256  digits  in  8
-     character  fields  and in 11 base 256 digits in 12 character
-     fields.  All base 256 numbers are two's complement  numbers.
-     A base 256 number in a 8 character field may hold 56 bits, a
-     base 256 number in a 12 character field may  hold  88  bits.
-     This  may  extended to 64 bits for 8 character fields and to
-     95 bits for 12 character fields. For a negative  number  the
-     first  character  currently  is set to a value of 255 (all 8
-
-Joerg Schilling       Last change: 05/10/19                     5
-
-
-Schily's USER COMMANDS                                   STAR(4L)
-
-     bits are set).  The rightmost character in a 8 or 12 charac-
-     ter  field  contains  the least significant base 256 number.
-     Recent GNU tar versions implement the same extension.
-
-     While the POSIX standard makes obvious that the fields mode,
-     uid,  gid,    size,  chksum, devmajor and devminor should be
-     treated as unsigned numbers, there is no such definition for
-     the time field.
-
-     The mode field contains 12  bits  holding  permissions,  see
-     above for the definitions for each of the permission bits.
-
-     The uid and gid fields contain the numerical user id of  the
-     file.
-
-     The size field contains the size of the file in  characters.
-     If  the tar header is followed by file data, then the amount
-     of data that follows is computed by (size + 511) / 512.
-
-     The mtime filed contains the number of seconds since Jan 1st
-     1970 00:00 UTC as retrived via stat(2) in st_mtime.
-
-     The chksum field contains a simple checksum over  all  bytes
-     of  the header.  To compute the value, all characters in the
-     header are treated as unsigned integers and  the  characters
-     in  the chksum field are treated as if they were all spaces.
-     When the computation starts, the checksum value is  initial-
-     ized to 0.
-
-     The typeflag field specifies the type of the  file  that  is
-     archived.  If a specific tar implementation does not include
-     support for a specific typeflag value,  this  implementation
-     will  extract  the  unknown file types as if they were plain
-     files.
-
-     '0' REGTYPE
-          A regular file.  If the size field is  non  zero,  then
-          file data follows the header.
-
-     '\0' AREGTYPE
-          For backwards compatibility with pre  POSIX.1-1988  tar
-          implementations,  a nul character is also recognized as
-          marker for plain files.  It is not generated by  recent
-          tar  implementations.   If  the size field is non zero,
-          then file data follows the header.
-
-     '1' LNKTYPE
-          The file is a hard link to another file.  The  name  of
-          the  file that the file is linked to is in the linkname
-          part of the header.  For tar archives  written  by  pre
-          POSIX.1-1988  implementations,  the  size field usually
-          contains the size of the file and needs to  be  ignored
-
-Joerg Schilling       Last change: 05/10/19                     6
-
-
-Schily's USER COMMANDS                                   STAR(4L)
-
-          as  no  data may follow this header type.  For POSIX.1-
-          1988 compliant archives, the size field needs to be  0.
-          For POSIX.1-2001 compliant archives, the size field may
-          be non zero, indicating that file data is  included  in
-          the archive.
-
-     '2' SYMTYPE
-          The file is a symbolic link to another file.  The  name
-          of  the file that the file is linked to is in the link-
-          name part of the header.  The size field needs to be 0.
-          No file data may follow the header.
-
-     '3' CHRTYPE
-          A character special file.  The fields devmajor and dev-
-          minor  contain  information that defines the file.  The
-          meaning of the size field is unspecified by  the  POSIX
-          standard.  No file data may follow the header.
-
-     '4' BLKTYPE
-          A block special file.  The fields devmajor and devminor
-          contain information that defines the file.  The meaning
-          of the size field is unspecified by the POSIX standard.
-          No file data may follow the header.
-
-     '5' DIRTYPE
-          A directory or sub directory.  Old  (pre  POSIX.1-1988)
-          tar  implementations did use the same typeflag value as
-          for plain files and added a slash to the name.  If  the
-          size  field  is  non zero then it indicates the maximum
-          size in characters the system  may  allocate  for  this
-          directory.  If  the  size  field  is 0, then the system
-          shall not limit the size of the directory. On operating
-          systems  where  the  disk  allocation  is not done on a
-          directory base, the size field is  ignored  on  extrac-
-          tion.  No file data may follow the header.
-
-     '6' FIFOTYPE
-          A named  pipe.   The  meaning  of  the  size  field  is
-          unspecified by the POSIX standard.  The size field must
-          be ignored on extraction.  No file data may follow  the
-          header.
-
-     '7' CONTTYPE
-          A contiguous file.  This is a file that  gives  special
-          performance  attributes.   Operating systems that don't
-          support this file type extract this file type as  plain
-          files.   If  the size field is non zero, then file data
-          follows the header.
-
-     'g' GLOBAL POSIX.1-2001 HEADER
-          With POSIX.1-2001 pax archives,  this  type  defines  a
-          global  extended  header.   The size is always non zero
-
-Joerg Schilling       Last change: 05/10/19                     7
-
-
-Schily's USER COMMANDS                                   STAR(4L)
-
-          and denotes  the  sum  of  the  length  fields  in  the
-          extended header data.  The data that follows the header
-          is in the pax extended  header  format.   The  extended
-          header records in this header type affect all following
-          files in the archive unless they are overwritten by new
-          values.   See  EXTENDED TAR (PAX) HEADER FORMAT section
-          below.
-
-     'x' EXTENDED POSIX.1-2001 HEADER
-          With POSIX.1-2001 pax archives, this  type  defines  an
-          extended  header.   The  size  is  always  non zero and
-          denotes the sum of the length fields  in  the  extended
-          header  data.   The  data that follows the header is in
-          the pax extended header format.   The  extended  header
-          records  in  this header type only affect the following
-          file in the archive.  See  EXTENDED  TAR  (PAX)  HEADER
-          FORMAT section below.
-
-     'A' - 'Z'
-          Reserved for vendor specific implementations.
-
-     'A'  A Solaris ACL entry as used by the  tar  implementation
-          from  Sun.  The size is always non zero and denotes the
-          length of the  data  that  follows  the  header.   Star
-          currently is not able to handle this header type.
-
-     'D'  A GNU dump directory.  This header type is not  created
-          by  star and handled like a directory during an extract
-          operation, so the content is ignored by star.  The size
-          field  denotes  the length of the data that follows the
-          header.
-
-     'E'  A Solaris Extended  Attribute  File.   The  size  field
-          denotes the length of the data that follows the header.
-          Star currently is not able to handle this header type.
-
-     'I'  A inode metadata entry.  This header type  is  used  by
-          star  to archive inode meta data only.  To archive more
-          inode meta data than possible with a  POSIX-1.1988  tar
-          header, a header with type 'I' is usually preceded by a
-          'x' header.  It is used with incremental backups.   The
-          size  field holds the length of the file.  No file data
-          follows this header.
-
-     'K'  A long link name.  Star is able to read and write  this
-          type  of  header.  With the xustar and exustar formats,
-          star  prefers  to  store  long  link  names  using  the
-          POSIX.1-2001  method.   The size is always non zero and
-          denotes the length of the long link name including  the
-          trailing  null  byte. The link name is in the data that
-          follows the header.
-
-Joerg Schilling       Last change: 05/10/19                     8
-
-
-Schily's USER COMMANDS                                   STAR(4L)
-
-     'L'  A long file name.  Star is able to read and write  this
-          type  of  header.  With the xustar and exustar formats,
-          star  prefers  to  store  long  file  names  using  the
-          POSIX.1-2001  method.   The size is always non zero and
-          denotes the length of the long file name including  the
-          trailing  null  byte. The file name is in the data that
-          follows the header.
-
-     'M'  A multi volume continuation entry.  It is used by  star
-          to  tell the extraction program via the size field when
-          the next regular  archive  header  will  follow.   This
-          allows to start extracting multi volume archives with a
-          volume number greater than one.  It is used by GNU  tar
-          to  verify  multi  volume  continuation volumes.  Other
-          fields in the GNU multi volume continuation header  are
-          a  result  of  a  GNU tar miss conception and cannot be
-          used.  If the size field is non zero the data following
-          the header is skipped by star if the volume that starts
-          with it is mounted as the first volume.  This header is
-          ignored if the volume that starts with it is mounted as
-          continuation volume.
-
-     'N'  An outdated linktype used by old GNU  tar  versions  to
-          store  long  file  names.   This type is unsupported by
-          star.
-
-     'S'  A sparse file.  This header type is used  by  star  and
-          GNU  tar.   A  sparse header is uses instead of a plain
-          file header to  denote  a  sparse  file  that  follows.
-          Directly  after  the  header,  a  list  of  sparse hole
-          descriptors follows  followed  by  the  compacted  file
-          data.   With  star formats, the size field holds a size
-          that represents the sum of the sparse hole  descriptors
-          plus  the  size of the compacted file data. This allows
-          other tar implementations to correctly skip to the next
-          tar header.  With GNU tar, up to 4 sparse hole descrip-
-          tors fit  into  the  sparse  header.   Additional  hole
-          descriptors  are not needed if the file has less than 4
-          holes.  With GNU tar, the size field breaks general tar
-          header rules and is meaningless because the size of the
-          sparse hole descriptors does not count.
-
-     'V'  A volume header.  The name field is is used to hold the
-          volume  name.   Star  uses  the atime field to hold the
-          volume number in case there is no POSIX.1-2001 extended
-          header.   This header type is used by star and GNU tar.
-          If the size field is non zero the  data  following  the
-          header is skipped by star.
-
-     'X'  A vendor unique variant of  the  POSIX.1-2001  extended
-          header type.  It has been implemented by Sun many years
-          before the POSIX.1-2001  standard  has  been  approved.
-
-Joerg Schilling       Last change: 05/10/19                     9
-
-
-Schily's USER COMMANDS                                   STAR(4L)
-
-          See also the typeflag 'x' header type.  Star is able to
-          read and write this type of header.
-
-
-
-

EXTENDED TAR (PAX) HEADER STRUCTURE

-     Block type                            Description
-
-     Ustar Header [typeflag='g']      Global Extended Header
-     Global Extended Data
-     Ustar Header [typeflag='h']         Extended Header
-     Extended Data
-     Ustar header [typeflag='0']    File with Extended Header
-     Data for File #1
-     Ustar header [typeflag='0']   File without Extended Header
-     Data for File #2
-     Block of binary zeroes              First EOF Block
-     Block of binary zeroes              Second EOF Block
-
-
-
-

EXTENDED TAR (PAX) HEADER FORMAT

-     The data block  that  follows  a  tar  archive  header  with
-     typeflag 'g' or 'x' contains one or more records in the fol-
-     lowing format:
-
-          "%d %s=%s\n", <length>, <keyword>, <value>
-
-     Each record starts with a a decimal length field. The length
-     includes  the  total  size  of a record including the length
-     field itself and the trailing new line.
-
-     The keyword may not include an  equal  sign.   All  keywords
-     beginning  with  lower  case letters and digits are reserved
-     for future use by the POSIX standard.
-
-     If the value field is of zero length, it deletes any  header
-     field  of  the  same  name  that  is in effect from the same
-     extended header or from a previous global header.
-
-     Null characters do not delimit any value. The value is  only
-     limited by its implicit length.
-
-
-
-

EXTENDED TAR (PAX) HEADER KEYWORDS

-     POSIX.1-2001 extended pax  header  keywords.  All  numerical
-     values  are  represented  as decimal strings.  All texts are
-     represented as 7-bit ascii or UTF-8:
-
-     atime
-          The time from st_atime in sub second granularity.  Star
-          currently supports a nanosecond granularity.
-
-     charset
-          The name of the character set used to encode  the  data
-          in  the  following  file(s).  This keyword is currently
-
-Joerg Schilling       Last change: 05/10/19                    10
-
-
-Schily's USER COMMANDS                                   STAR(4L)
-
-          ignored by star.
-
-     comment
-          Any number of characters that  should  be  treated  as
-          comment.  Star ignores the comment as documented by the
-          POSIX standard.
-
-     ctime
-          The time from st_ctime in sub second granularity.  Star
-          currently supports a nanosecond granularity.
-
-     gid  The group ID of the group  that  owns  the  file.   The
-          argument  is  a  decimal number.  This field is used if
-          the group ID of a file is greater than  2097151  (octal
-          7777777).
-
-     gname
-          The group name of the following file(s) coded in  UTF-8
-          if  the  group name does not fit into 323 characters or
-          cannot be expressed in 7-Bit ASCII.
-
-     linkpath
-          The name of the linkpath coded in UTF-8 if it is longer
-          than  100  characters  or  cannot be expressed in 7-Bit
-          ASCII.
-
-     mtime
-          The time from st_mtime in sub second granularity.  Star
-          currently supports a nanosecond granularity.
-
-     path The name of the linkpath coded in UTF-8 if it does  not
-          fit into 100 characters + 155 characters prefix or can-
-          not be expressed in 7-Bit ASCII.
-
-     realtime.any
-          The keywords prefixed by  realtime.  are  reserved  for
-          future standardization.
-
-     security.any
-          The keywords prefixed by  security.  are  reserved  for
-          future standardization.
-
-     size The size of the file as decimal number if the file size
-          is  greater  than  8589934591  (octal 77777777777). The
-          size keyword may not refer to the real file size but is
-          related  to  the  size if the file in the archive.  See
-          also SCHILY.realsize for more information.
-
-     uid  The uid ID of the group that owns the file.  The  argu-
-          ment  is  a  decimal number.  This field is used if the
-          uid ID  of  a  file  is  greater  than  2097151  (octal
-          7777777).
-
-Joerg Schilling       Last change: 05/10/19                    11
-
-
-Schily's USER COMMANDS                                   STAR(4L)
-
-     uname
-          The user name of the following file(s) coded  in  UTF-8
-          if  the  user  name does not fit into 323 characters or
-          cannot be expressed in 7-Bit ASCII.
-
-     VENDOR.keyword
-          Any keyword that starts with a vendor name  in  capital
-          letters  is  reserved for vendor specific extensions by
-          the standard.  Star uses a lot of these vendor specific
-          extension. See below for more informations.
-
-
-
-

SCHILY PAX EXTENSION KEYWORDS

-     Star uses own vendor specific extensions. The SCHILY  vendor
-     specific extended pax header keywords are:
-
-     SCHILY.acl.access
-          The ACL for a file.
-
-          Since no official backup format for POSIX  access  con-
-          trol  lists  has  been  defined,  star  uses the vendor
-          defined      attributes      SCHILY.acl.access      and
-          SCHILY.acl.default  for storing the ACL and Default ACL
-          of a file, respectively.  The access control lists  are
-          stored  in  the  short  text  form  as defined in POSIX
-          1003.1e draft standard 17.
-
-          To each named user ACL entry a fourth  colon  separated
-          field field containing the user identifier (UID) of the
-          associated user is appended.  To each named group entry
-          a  fourth  colon  separated  field containing the group
-          identifier (GID) of the associated group  is  appended.
-          (POSIX  1003.1e  draft standard 17 allows to add fields
-          to ACL entries.)
-
-          This  is  an   example   of   the   format   used   for
-          SCHILY.acl.access  (a space has been inserted after the
-          equal sign and lines are broken [marked with '\' ]  for
-          readability, additional fields in bold):
-
-          SCHILY.acl.access= user::rwx,user:lisa:r-x:502, \
-                             group::r-x,group:toolies:rwx:102, \
-                             mask::rwx,other::r--x
-
-          The numerical user and group identifiers are  essential
-          when  restoring  a  system completely from a backup, as
-          initially the name-to-identifier mappings  may  not  be
-          available,  and  then  file ownership restoration would
-          not work.
-
-          As the archive format  that  is  used  for  backing  up
-          access control lists is compatible with the pax archive
-          format, archives created that way can  be  restored  by
-
-Joerg Schilling       Last change: 05/10/19                    12
-
-
-Schily's USER COMMANDS                                   STAR(4L)
-
-          star  or  a POSIX.1-2001 compliant pax.  Note that pro-
-          grams other than star will ignore the ACL information.
-
-     SCHILY.acl.default
-          The default ACL for a file. See  SCHILY.acl.access  for
-          more information.
-
-          This  is  an   example   of   the   format   used   for
-          SCHILY.acl.default (a space has been inserted after the
-          equal sign and lines are broken [marked with '\' ]  for
-          readability, additional fields in bold):
-
-          SCHILY.acl.default= user::rwx,user:lisa:r-x:502, \
-                              group::r-x,mask::r-x,other::r-x
-
-     SCHILY.ddev
-          The device ids for names used is  the  SCHILY.dir  dump
-          directory  list  from  st_dev  of  the  file as decimal
-          number.  The SCHILY.ddev keyword is followed by a space
-          separated  list  of device id numbers. Each corresponds
-          exactly to a name in the list found in SCHILY.dir.   If
-          a  specific  device  id number is repeated, a comma (,)
-          without a following space may be use to denote that the
-          current  device  id number is identical to the previous
-          number.  This keyword is used in dump mode.  This  key-
-          word is not yet implemented.
-
-          The value is a signed int.  An implementation should be
-          able  to  handle at least 64 bit values.  Note that the
-          value is signed because POSIX  does  not  specify  more
-          than the type should be an int.
-
-     SCHILY.dev
-          The device id  from  st_dev  of  the  file  as  decimal
-          number.  This keyword is used in dump mode.
-
-          The value is a signed int.  An implementation should be
-          able  to  handle at least 64 bit values.  Note that the
-          value is signed because POSIX  does  not  specify  more
-          than the type should be an int.
-
-     SCHILY.devmajor
-          The device major number of the file if it is a  charac-
-          ter  or  block special file.  The argument is a decimal
-          number.  This field is used if the device major of  the
-          file is greater than 2097151 (octal 7777777).
-
-          The value is a signed int.  An implementation should be
-          able  to  handle at least 64 bit values.  Note that the
-          value is signed because POSIX  does  not  specify  more
-          than the type should be an int.
-
-Joerg Schilling       Last change: 05/10/19                    13
-
-
-Schily's USER COMMANDS                                   STAR(4L)
-
-     SCHILY.devminor
-          The device minor number of the file if it is a  charac-
-          ter  or  block special file.  The argument is a decimal
-          number.  This field is used if the device minor of  the
-          file is greater than 2097151 (octal 7777777).
-
-          The value is a signed int.  An implementation should be
-          able  to  handle at least 64 bit values.  Note that the
-          value is signed because POSIX  does  not  specify  more
-          than the type should be an int.
-
-     SCHILY.dino
-          The inode numbers for names used is the SCHILY.dir dump
-          directory  list  from  st_ino  of  the  file as decimal
-          number.  The SCHILY.dino keyword is followed by a space
-          separated  list  of  inode  numbers.  Each  corresponds
-          exactly to a name in  the  list  found  in  SCHILY.dir.
-          This keyword is used in dump mode.
-
-          The values are unsigned int.  An implementation  should
-          be able to handle at least 64 bit unsigned values.
-
-     SCHILY.dir
-          A list of  filenames  (the  content)  for  the  current
-          directory.   The  names  are coded in UTF-8.  Each file
-          name is prefixed by a single character that is used  as
-          a flag.  Each file name is limited by a null character.
-          The null character is  directly  followed  by  he  flag
-          character  for  the  next file name in case the list is
-          not terminated by the  current  file  name.   The  flag
-          character  must not be a null character.  By default, a
-          ^A (octal  001)  is  used.   The  following  flags  are
-          defined:
-
-          \000 This is the list terminator character - the second
-               null byte, see below.
-
-          ^A   The default flag that is used in case the dump dir
-               features have not been active.
-
-          Y    A non  directory  file  that  is  in  the  current
-               (incremental) dump.
-
-          N    A non directory file that is not  in  the  current
-               (incremental) dump.
-
-          D    A directory that is in the  current  (incremental)
-               dump.
-
-          d    A directory that is not in the current  (incremen-
-               tal) dump.
-
-Joerg Schilling       Last change: 05/10/19                    14
-
-
-Schily's USER COMMANDS                                   STAR(4L)
-
-          The list is terminated by two  successive  null  bytes.
-          The first is the null byte for the last file name.  The
-          second null byte is at the position where a flag  char-
-          acter  would be expected, it acts ad a list terminator.
-          The length tag for the SCHILY.dir  data  includes  both
-          null bytes.
-
-          If a dump mode has been selected  that  writes  compact
-          complete  directory information to the beginning of the
-          archive, the flag character  may  contain  values  dif-
-          ferent from ^A.  Star implementations up to star-1.5 do
-          not include this  feature.   Tar  implementations  that
-          like  to read archives that use the SCHILY.dir keyword,
-          shall not rely on values other than \000 (^@)  or  \001
-          (^A).
-
-          This keyword is used in dump mode.
-
-     SCHILY.fflags
-          A textual version of the BSD  or  Linux  extended  file
-          flags.  As this tag has not yet been documented, please
-          look into the  star  source,  file  fflags.c  for  more
-          information.
-
-     SCHILY.filetype
-          A textual version of the real file type  of  the  file.
-          The following names are used:
-
-          unallocated             An unknown file type  that  may
-                                  be  a  result  of  a  unlink(2)
-                                  operation.  This  should  never
-                                  happen.
-
-          regular                 A regular file.
-
-          contiguous              A contiguous file. On operating
-                                  systems  or  file  systems that
-                                  don't support this  file  type,
-                                  it  is  handled  like a regular
-                                  file.
-
-          symlink                 A symbolic  link  to  any  file
-                                  type.
-
-          directory               A directory.
-
-          character special       A character special file.
-
-          block special           A block special file.
-
-          fifo                    A named pipe.
-
-Joerg Schilling       Last change: 05/10/19                    15
-
-
-Schily's USER COMMANDS                                   STAR(4L)
-
-          socket                  A UNIX domain socket.
-
-          mpx character special   A multiplexed character special
-                                  file.
-
-          mpx block special       A  multiplexed  block   special
-                                  file.
-
-          XENIX nsem              A XENIX named semaphore.
-
-          XENIX nshd              XENIX shared data.
-
-          door                    A Solaris door.
-
-          eventcount              A UNOS event count.
-
-          whiteout                A BSD whiteout directory entry.
-
-          sparse                  A sparse regular file.
-
-          volheader               A volume header.
-
-          unknown/bad             Any other  unknown  file  type.
-                                  This should never happen.
-
-     SCHILY.ino
-          The inode number from st_ino of  the  file  as  decimal
-          number.  This keyword is used in dump mode.
-
-          The value is an unsigned int.  An implementation should
-          be able to handle at least 64 bit unsigned values.
-
-     SCHILY.nlink
-          The link count of the file  as  decimal  number.   This
-          keyword is used in dump mode.
-
-          The value is an unsigned int.  An implementation should
-          be able to handle at least 32 bit unsigned values.
-
-     SCHILY.offset
-          The  offset  value  for  a  multi  volume  continuation
-          header.   This  keyword  is used with multi volume con-
-          tinuation headers.  Multi volume  continuation  headers
-          are  used  to  allow  to  start  reading a multi volume
-          archive past the first volume.
-
-          The value is an unsigned int.  An implementation should
-          be able to handle at least 64 bit unsigned values.
-
-     SCHILY.realsize
-          The real size of the  file  as  decimal  number.   This
-
-Joerg Schilling       Last change: 05/10/19                    16
-
-
-Schily's USER COMMANDS                                   STAR(4L)
-
-          keyword  is  used  if the real size of the file differs
-          from the visible size of the file in the archive.   The
-          real  file size differs from the size in the archive if
-          the file type is sparse or if the file is  a  continua-
-          tion  file  on  a  multi  volume  archive.  In case the
-          SCHILY.realsize keyword is needed, it must be past  any
-          size keyword in case a size keyword is also present.
-
-          The value is an unsigned int.  An implementation should
-          be able to handle at least 64 bit unsigned values.
-
-     SCHILY.tarfiletype
-          The  following  additional  file  types  are  used   in
-          SCHILY.tarfiletype:
-
-          hardlink
-               A hard link to any file type.
-
-          dumpdir
-               A directory with dump entries
-
-          multivol continuation
-               A multi volume continuation for any file type.
-
-          meta A meta entry (inode meta data only) for  any  file
-               type.
-
-     SCHILY.xattr.attr
-          A POSIX.1-2001 coded version of the Linux extended file
-          attributes.    Linux   extended   file  attributes  are
-          name/value pairs. Every attribute  name  results  in  a
-          SCHILY.xattr.name  tag  and  the  value of the extended
-          attribute is used as  the  value  of  the  POSIX.1-2001
-          header  tag.  Note that this way of coding is not port-
-          able across  platforms.   A  version  for  BSD  may  be
-          created  but  Solaris  includes  far more features with
-          extended attribute files than Linux does.
-
-          A future version  of  star  will  implement  a  similar
-          method  as  the  tar program on Solaris currently uses.
-          When    this    implementation    is     ready,     the
-          SCHILY.xattr.name  feature may be removed in favor of a
-          truly portable  implementation  that  supports  Solaris
-          also.
-
-
-
-

SCHILY 'G'LOBAL PAX EXTENSION KEYWORDS

-     The following star vendor unique extensions may only  appear
-     in 'g'lobal extended pax headers:
-
-     SCHILY.archtype
-          The textual version of  the  archive  type  used.   The
-
-Joerg Schilling       Last change: 05/10/19                    17
-
-
-Schily's USER COMMANDS                                   STAR(4L)
-
-          textual  values  used  for SCHILY.archtype are the same
-          names that are used in the star command line options to
-          set up a specific archive type.
-
-          In order to allow archive type  recognition  from  this
-          keyword,  the  minimum  tape  block  size must be 2x512
-          bytes (1024  bytes)  and  the  SCHILY.archtype  keyword
-          needs  to  be  in the first 512 bytes of the content of
-          the first 'g'lobal pax  header.  Then  the  first  tape
-          block may be scanned to recognize the archive type.
-
-     SCHILY.release
-          The textual version of the star version string and  the
-          platform  name  where this star has been compiled.  The
-          same text appears when calling star -version.
-
-     SCHILY.volhdr.blockoff
-          This keyword is used for  multi  volume  archives.   It
-          represents   the   offset   within  the  whole  archive
-          expressed in 512 byte units.
-
-          The value is an unsigned int with a valid range between
-          1  and  infinity.  An  implementation should be able to
-          handle at least 64 bit unsigned values.
-
-     SCHILY.volhdr.blocksize
-          The tape blocksize expressed in 512 byte units that was
-          used when writing the archive.
-
-          The value is an unsigned int with a valid range between
-          1  and  infinity.  An  implementation should be able to
-          handle at least 31 bit unsigned values.
-
-     SCHILY.volhdr.cwd
-          This keyword is used in dump mode.  It is only used  to
-          contain  the  real  backup  working  directory  if  the
-          fs-name= option  of  star  is  used  to  overwrite  the
-          SCHILY.volhdr.filesys         value.        Overwriting
-          SCHILY.volhdr.filesys is needed when backups are run on
-          file system snapshots rather than on the real file sys-
-          tem.
-
-     SCHILY.volhdr.device
-          This keyword is used in dump mode.  It  represents  the
-          name of the device that holds the file system data. For
-          disk based file systems, this is the device name of the
-          mounted device.
-
-          This keyword is optional. It helps to  correctly  iden-
-          tify  the  file  system  from  which this dump has been
-          made.
-
-Joerg Schilling       Last change: 05/10/19                    18
-
-
-Schily's USER COMMANDS                                   STAR(4L)
-
-     SCHILY.volhdr.dumpdate
-          This keyword is used in dump mode.  It  represents  the
-          time the current dump did start.
-
-     SCHILY.volhdr.dumplevel
-          This keyword is used in dump mode.  It  represents  the
-          level  of  the  current  dump.   Dump  levels are small
-          numbers, the lowest possible number is 0.  Dump level 0
-          represents  a  full  backup.  Dump level 1 represents a
-          backup that contains all changes that did  occur  since
-          the  last  level  0  dump.   Dump  level 2 represents a
-          backup that contains all changes that did  occur  since
-          the last level 1 dump.  Star does not specify a maximum
-          allowed dump level but  you  should  try  to  keep  the
-          numbers less than 100.
-
-          The value is an unsigned int with a valid range between
-          0 and at least 100.
-
-     SCHILY.volhdr.dumptype
-          This keyword is used in dump mode.  If the  dump  is  a
-          complete  dump  of  a file system, then the argument is
-          the text full, else the argument is the text partial.
-
-     SCHILY.volhdr.filesys
-          This keyword is used in dump mode.  It  represents  the
-          top level directory for the file system from which this
-          dump has been made.  If the dump represents a dump that
-          has  an associated level, then the this directory needs
-          to be identical to the root directory of this file sys-
-          tem which is the mount point.
-
-     SCHILY.volhdr.hostname
-          This keyword is  used  in  dump  mode.   The  value  is
-          retrieved from gethostname(3) or uname(2).
-
-     SCHILY.volhdr.label
-          The textual volume label.  The  volume  label  must  be
-          identical within a set of multi volume archives.
-
-     SCHILY.volhdr.refdate
-          This keyword is used in dump mode if the  current  dump
-          is an incremental dump with a level > 0.  It represents
-          the time the related dump did start.
-
-     SCHILY.volhdr.reflevel
-          This keyword is used in dump mode if the  current  dump
-          is an incremental dump with a level > 0.  It represents
-          the level of the related dump.  The related dump is the
-          last  dump with a level that is lower that the level of
-          this dump.  If a dump with the  level  of  the  current
-          dump  -1  exists,  then this is the related dump level.
-
-Joerg Schilling       Last change: 05/10/19                    19
-
-
-Schily's USER COMMANDS                                   STAR(4L)
-
-          Otherwise, the dump level is decremented until a  valid
-          dump level could be found in the dump database.
-
-          The value is an unsigned int with a valid range between
-          0 and at least 100.
-
-     SCHILY.volhdr.tapesize
-          This keyword is used for multi volume archives and  may
-          be  used  to  verify  the volume size on read back.  It
-          represents the tape size expressed in 512  byte  units.
-          If  this  keyword is set in multi volume mode, the size
-          of the tape is not autodetected but set from a  command
-          line option.
-
-          The value is an unsigned int with a valid range between
-          1  and  infinity.  An  implementation should be able to
-          handle at least 64 bit unsigned values.
-
-     SCHILY.volhdr.volume
-          This keyword is used for  multi  volume  archives.   It
-          represents  the volume number within a volume set.  The
-          number used for the first volume is 1.
-
-          The value is an unsigned int with a valid range between
-          1  and  infinity.  An  implementation should be able to
-          handle at least 31 bit unsigned values.
-
-
-
-

MULTI VOLUME ARCHIVE HANDLING

-     To be documented in the future.
-
-
-
-

SEE ALSO

-
-
-

NOTES

-
-
-

BUGS

-
-
-

AUTHOR

-
-Joerg Schilling       Last change: 05/10/19                    20
-
-
-
-
-Man(1) output converted with -man2html -
-


-FhG -FhG FOKUS -BerliOS - -Schily -Schily's Home -VED powered - - - diff --git a/node_modules/tar/test/fixtures/packtest/Ω.txt b/node_modules/tar/test/fixtures/packtest/Ω.txt deleted file mode 100644 index 1ca042f..0000000 --- a/node_modules/tar/test/fixtures/packtest/Ω.txt +++ /dev/null @@ -1 +0,0 @@ -Ω \ No newline at end of file diff --git a/node_modules/tar/test/fixtures/r/e/a/l/l/y/-/d/e/e/p/-/f/o/l/d/e/r/-/p/a/t/h/cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc b/node_modules/tar/test/fixtures/r/e/a/l/l/y/-/d/e/e/p/-/f/o/l/d/e/r/-/p/a/t/h/cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc deleted file mode 100644 index 5a5d18e..0000000 --- a/node_modules/tar/test/fixtures/r/e/a/l/l/y/-/d/e/e/p/-/f/o/l/d/e/r/-/p/a/t/h/cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc +++ /dev/null @@ -1 +0,0 @@ -cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc \ No newline at end of file diff --git a/node_modules/tar/test/fixtures/symlink b/node_modules/tar/test/fixtures/symlink deleted file mode 120000 index 218c28e..0000000 --- a/node_modules/tar/test/fixtures/symlink +++ /dev/null @@ -1 +0,0 @@ -hardlink-1 \ No newline at end of file diff --git a/node_modules/tar/test/fixtures/Ω.txt b/node_modules/tar/test/fixtures/Ω.txt deleted file mode 100644 index 1ca042f..0000000 --- a/node_modules/tar/test/fixtures/Ω.txt +++ /dev/null @@ -1 +0,0 @@ -Ω \ No newline at end of file diff --git a/node_modules/tar/test/header.js b/node_modules/tar/test/header.js deleted file mode 100644 index 8ea6f79..0000000 --- a/node_modules/tar/test/header.js +++ /dev/null @@ -1,183 +0,0 @@ -var tap = require("tap") -var TarHeader = require("../lib/header.js") -var tar = require("../tar.js") -var fs = require("fs") - - -var headers = - { "a.txt file header": - [ "612e747874000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000030303036343420003035373736312000303030303234200030303030303030303430312031313635313336303333332030313234353100203000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000757374617200303069736161637300000000000000000000000000000000000000000000000000007374616666000000000000000000000000000000000000000000000000000000303030303030200030303030303020000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000" - , { cksumValid: true - , path: 'a.txt' - , mode: 420 - , uid: 24561 - , gid: 20 - , size: 257 - , mtime: 1319493851 - , cksum: 5417 - , type: '0' - , linkpath: '' - , ustar: 'ustar\0' - , ustarver: '00' - , uname: 'isaacs' - , gname: 'staff' - , devmaj: 0 - , devmin: 0 - , fill: '' } - ] - - , "omega pax": // the extended header from omega tar. - [ "5061784865616465722fcea92e74787400000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000030303036343420003035373736312000303030303234200030303030303030303137302031313534333731303631312030313530353100207800000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000757374617200303069736161637300000000000000000000000000000000000000000000000000007374616666000000000000000000000000000000000000000000000000000000303030303030200030303030303020000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000" - , { cksumValid: true - , path: 'PaxHeader/Ω.txt' - , mode: 420 - , uid: 24561 - , gid: 20 - , size: 120 - , mtime: 1301254537 - , cksum: 6697 - , type: 'x' - , linkpath: '' - , ustar: 'ustar\0' - , ustarver: '00' - , uname: 'isaacs' - , gname: 'staff' - , devmaj: 0 - , devmin: 0 - , fill: '' } ] - - , "omega file header": - [ "cea92e7478740000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000030303036343420003035373736312000303030303234200030303030303030303030322031313534333731303631312030313330373200203000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000757374617200303069736161637300000000000000000000000000000000000000000000000000007374616666000000000000000000000000000000000000000000000000000000303030303030200030303030303020000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000" - , { cksumValid: true - , path: 'Ω.txt' - , mode: 420 - , uid: 24561 - , gid: 20 - , size: 2 - , mtime: 1301254537 - , cksum: 5690 - , type: '0' - , linkpath: '' - , ustar: 'ustar\0' - , ustarver: '00' - , uname: 'isaacs' - , gname: 'staff' - , devmaj: 0 - , devmin: 0 - , fill: '' } ] - - , "foo.js file header": - [ "666f6f2e6a730000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000030303036343420003035373736312000303030303234200030303030303030303030342031313534333637303734312030313236313700203000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000757374617200303069736161637300000000000000000000000000000000000000000000000000007374616666000000000000000000000000000000000000000000000000000000303030303030200030303030303020000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000" - , { cksumValid: true - , path: 'foo.js' - , mode: 420 - , uid: 24561 - , gid: 20 - , size: 4 - , mtime: 1301246433 - , cksum: 5519 - , type: '0' - , linkpath: '' - , ustar: 'ustar\0' - , ustarver: '00' - , uname: 'isaacs' - , gname: 'staff' - , devmaj: 0 - , devmin: 0 - , fill: '' } - ] - - , "b.txt file header": - [ "622e747874000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000030303036343420003035373736312000303030303234200030303030303030313030302031313635313336303637372030313234363100203000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000757374617200303069736161637300000000000000000000000000000000000000000000000000007374616666000000000000000000000000000000000000000000000000000000303030303030200030303030303020000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000" - , { cksumValid: true - , path: 'b.txt' - , mode: 420 - , uid: 24561 - , gid: 20 - , size: 512 - , mtime: 1319494079 - , cksum: 5425 - , type: '0' - , linkpath: '' - , ustar: 'ustar\0' - , ustarver: '00' - , uname: 'isaacs' - , gname: 'staff' - , devmaj: 0 - , devmin: 0 - , fill: '' } - ] - - , "deep nested file": - [ "636363636363636363636363636363636363636363636363636363636363636363636363636363636363636363636363636363636363636363636363636363636363636363636363636363636363636363636363636363636363636363636363636363633030303634342000303537373631200030303030323420003030303030303030313434203131363532313531353333203034333331340020300000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000075737461720030306973616163730000000000000000000000000000000000000000000000000000737461666600000000000000000000000000000000000000000000000000000030303030303020003030303030302000722f652f612f6c2f6c2f792f2d2f642f652f652f702f2d2f662f6f2f6c2f642f652f722f2d2f702f612f742f680000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000" - , { cksumValid: true, - path: 'r/e/a/l/l/y/-/d/e/e/p/-/f/o/l/d/e/r/-/p/a/t/h/cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc' - , mode: 420 - , uid: 24561 - , gid: 20 - , size: 100 - , mtime: 1319687003 - , cksum: 18124 - , type: '0' - , linkpath: '' - , ustar: 'ustar\0' - , ustarver: '00' - , uname: 'isaacs' - , gname: 'staff' - , devmaj: 0 - , devmin: 0 - , fill: '' } - ] - } - -tap.test("parsing", function (t) { - Object.keys(headers).forEach(function (name) { - var h = headers[name] - , header = new Buffer(h[0], "hex") - , expect = h[1] - , parsed = new TarHeader(header) - - // console.error(parsed) - t.has(parsed, expect, "parse " + name) - }) - t.end() -}) - -tap.test("encoding", function (t) { - Object.keys(headers).forEach(function (name) { - var h = headers[name] - , expect = new Buffer(h[0], "hex") - , encoded = TarHeader.encode(h[1]) - - // might have slightly different bytes, since the standard - // isn't very strict, but should have the same semantics - // checkSum will be different, but cksumValid will be true - - var th = new TarHeader(encoded) - delete h[1].block - delete h[1].needExtended - delete h[1].cksum - t.has(th, h[1], "fields "+name) - }) - t.end() -}) - -// test these manually. they're a bit rare to find in the wild -tap.test("parseNumeric tests", function (t) { - var parseNumeric = TarHeader.parseNumeric - , numbers = - { "303737373737373700": 2097151 - , "30373737373737373737373700": 8589934591 - , "303030303036343400": 420 - , "800000ffffffffffff": 281474976710655 - , "ffffff000000000001": -281474976710654 - , "ffffff000000000000": -281474976710655 - , "800000000000200000": 2097152 - , "8000000000001544c5": 1393861 - , "ffffffffffff1544c5": -15383354 } - Object.keys(numbers).forEach(function (n) { - var b = new Buffer(n, "hex") - t.equal(parseNumeric(b), numbers[n], n + " === " + numbers[n]) - }) - t.end() -}) diff --git a/node_modules/tar/test/pack.js b/node_modules/tar/test/pack.js deleted file mode 100644 index 3fc808d..0000000 --- a/node_modules/tar/test/pack.js +++ /dev/null @@ -1,953 +0,0 @@ -var tap = require("tap") - , tar = require("../tar.js") - , pkg = require("../package.json") - , Pack = tar.Pack - , fstream = require("fstream") - , Reader = fstream.Reader - , Writer = fstream.Writer - , path = require("path") - , input = path.resolve(__dirname, "fixtures/") - , target = path.resolve(__dirname, "tmp/pack.tar") - , uid = process.getuid ? process.getuid() : 0 - , gid = process.getgid ? process.getgid() : 0 - - , entries = - - // the global header and root fixtures/ dir are going to get - // a different date each time, so omit that bit. - // Also, dev/ino values differ across machines, so that's not - // included. Rather than use - [ [ 'globalExtendedHeader', - { path: 'PaxHeader/', - mode: 438, - uid: 0, - gid: 0, - type: 'g', - linkpath: '', - ustar: 'ustar\u0000', - ustarver: '00', - uname: '', - gname: '', - devmaj: 0, - devmin: 0, - fill: '' }, - { "NODETAR.author": pkg.author, - "NODETAR.name": pkg.name, - "NODETAR.description": pkg.description, - "NODETAR.version": pkg.version, - "NODETAR.repository.type": pkg.repository.type, - "NODETAR.repository.url": pkg.repository.url, - "NODETAR.main": pkg.main, - "NODETAR.scripts.test": pkg.scripts.test, - "NODETAR.engines.node": pkg.engines.node } ] - - , [ 'entry', - { path: 'fixtures/', - mode: 493, - uid: uid, - gid: gid, - size: 0, - type: '5', - linkpath: '', - ustar: 'ustar\u0000', - ustarver: '00', - uname: '', - gname: '', - devmaj: 0, - devmin: 0, - fill: '' } ] - - , [ 'extendedHeader', - { path: 'PaxHeader/fixtures/200cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc', - mode: 420, - uid: uid, - gid: gid, - size: 402, - mtime: new Date('Thu, 27 Oct 2011 03:41:08 GMT'), - cksum: 13492, - type: 'x', - linkpath: '', - ustar: 'ustar\u0000', - ustarver: '00', - uname: '', - gname: '', - devmaj: 0, - devmin: 0, - fill: '' }, - { path: 'fixtures/200ccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc', - 'NODETAR.depth': '1', - 'NODETAR.type': 'File', - nlink: 1, - uid: uid, - gid: gid, - size: 200, - 'NODETAR.blksize': '4096', - 'NODETAR.blocks': '8' } ] - - , [ 'entry', - { path: 'fixtures/200ccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc', - mode: 420, - uid: uid, - gid: gid, - size: 200, - mtime: new Date('Thu, 27 Oct 2011 03:41:08 GMT'), - cksum: 13475, - type: '0', - linkpath: '', - ustar: 'ustar\u0000', - ustarver: '00', - uname: '', - gname: '', - devmaj: 0, - devmin: 0, - fill: '', - 'NODETAR.depth': '1', - 'NODETAR.type': 'File', - nlink: 1, - 'NODETAR.blksize': '4096', - 'NODETAR.blocks': '8' } ] - - , [ 'entry', - { path: 'fixtures/a.txt', - mode: 420, - uid: uid, - gid: gid, - size: 257, - mtime: new Date('Mon, 24 Oct 2011 22:04:11 GMT'), - cksum: 5114, - type: '0', - linkpath: '', - ustar: 'ustar\u0000', - ustarver: '00', - uname: '', - gname: '', - devmaj: 0, - devmin: 0, - fill: '' } ] - - , [ 'entry', - { path: 'fixtures/b.txt', - mode: 420, - uid: uid, - gid: gid, - size: 512, - mtime: new Date('Mon, 24 Oct 2011 22:07:59 GMT'), - cksum: 5122, - type: '0', - linkpath: '', - ustar: 'ustar\u0000', - ustarver: '00', - uname: '', - gname: '', - devmaj: 0, - devmin: 0, - fill: '' } ] - - , [ 'entry', - { path: 'fixtures/c.txt', - mode: 420, - uid: uid, - gid: gid, - size: 513, - mtime: new Date('Wed, 26 Oct 2011 01:10:58 GMT'), - cksum: 5119, - type: '0', - linkpath: '', - ustar: 'ustar\u0000', - ustarver: '00', - uname: '', - gname: '', - devmaj: 0, - devmin: 0, - fill: '' } ] - - , [ 'entry', - { path: 'fixtures/cc.txt', - mode: 420, - uid: uid, - gid: gid, - size: 513, - mtime: new Date('Wed, 26 Oct 2011 01:11:02 GMT'), - cksum: 5222, - type: '0', - linkpath: '', - ustar: 'ustar\u0000', - ustarver: '00', - uname: '', - gname: '', - devmaj: 0, - devmin: 0, - fill: '' } ] - - , [ 'entry', - { path: 'fixtures/foo.js', - mode: 420, - uid: uid, - gid: gid, - size: 4, - mtime: new Date('Fri, 21 Oct 2011 21:19:29 GMT'), - cksum: 5211, - type: '0', - linkpath: '', - ustar: 'ustar\u0000', - ustarver: '00', - uname: '', - gname: '', - devmaj: 0, - devmin: 0, - fill: '' } ] - - , [ 'entry', - { path: 'fixtures/hardlink-1', - mode: 420, - uid: uid, - gid: gid, - size: 200, - mtime: new Date('Tue, 15 Nov 2011 03:10:09 GMT'), - cksum: 5554, - type: '0', - linkpath: '', - ustar: 'ustar\u0000', - ustarver: '00', - uname: '', - gname: '', - devmaj: 0, - devmin: 0, - fill: '' } ] - - , [ 'entry', - { path: 'fixtures/hardlink-2', - mode: 420, - uid: uid, - gid: gid, - size: 0, - mtime: new Date('Tue, 15 Nov 2011 03:10:09 GMT'), - cksum: 7428, - type: '1', - linkpath: 'fixtures/hardlink-1', - ustar: 'ustar\u0000', - ustarver: '00', - uname: '', - gname: '', - devmaj: 0, - devmin: 0, - fill: '' } ] - - , [ 'entry', - { path: 'fixtures/omega.txt', - mode: 420, - uid: uid, - gid: gid, - size: 2, - mtime: new Date('Fri, 21 Oct 2011 21:19:29 GMT'), - cksum: 5537, - type: '0', - linkpath: '', - ustar: 'ustar\u0000', - ustarver: '00', - uname: '', - gname: '', - devmaj: 0, - devmin: 0, - fill: '' } ] - - , [ 'entry', - { path: 'fixtures/packtest/', - mode: 493, - uid: uid, - gid: gid, - size: 0, - type: '5', - linkpath: '', - ustar: 'ustar\u0000', - ustarver: '00', - uname: '', - gname: '', - devmaj: 0, - devmin: 0, - fill: '' } ] - - , [ 'entry', - { path: 'fixtures/packtest/omega.txt', - mode: 420, - uid: uid, - gid: gid, - size: 2, - mtime: new Date('Mon, 14 Nov 2011 21:42:24 GMT'), - cksum: 6440, - type: '0', - linkpath: '', - ustar: 'ustar\u0000', - ustarver: '00', - uname: '', - gname: '', - devmaj: 0, - devmin: 0, - fill: '' } ] - - , [ 'entry', - { path: 'fixtures/packtest/star.4.html', - mode: 420, - uid: uid, - gid: gid, - size: 54081, - mtime: new Date("Sun, 06 May 2007 13:25:06 GMT"), - cksum: 6566, - type: '0', - linkpath: '', - ustar: 'ustar\u0000', - ustarver: '00', - uname: '', - gname: '', - devmaj: 0, - devmin: 0, - fill: '' } ] - - , [ 'extendedHeader', - { path: 'PaxHeader/fixtures/packtest/Ω.txt', - mode: 420, - uid: uid, - gid: gid, - size: 213, - mtime: new Date('Mon, 14 Nov 2011 21:39:39 GMT'), - cksum: 7306, - type: 'x', - linkpath: '', - ustar: 'ustar\u0000', - ustarver: '00', - uname: '', - gname: '', - devmaj: 0, - devmin: 0, - fill: '' }, - { path: 'fixtures/packtest/Ω.txt', - 'NODETAR.depth': '2', - 'NODETAR.type': 'File', - nlink: 1, - uid: uid, - gid: gid, - size: 2, - 'NODETAR.blksize': '4096', - 'NODETAR.blocks': '8' } ] - - , [ 'entry', - { path: 'fixtures/packtest/Ω.txt', - mode: 420, - uid: uid, - gid: gid, - size: 2, - mtime: new Date('Mon, 14 Nov 2011 21:39:39 GMT'), - cksum: 6297, - type: '0', - linkpath: '', - ustar: 'ustar\u0000', - ustarver: '00', - uname: '', - gname: '', - devmaj: 0, - devmin: 0, - fill: '', - 'NODETAR.depth': '2', - 'NODETAR.type': 'File', - nlink: 1, - 'NODETAR.blksize': '4096', - 'NODETAR.blocks': '8' } ] - - , [ 'entry', - { path: 'fixtures/r/', - mode: 493, - uid: uid, - gid: gid, - size: 0, - mtime: new Date('Thu, 27 Oct 2011 03:42:46 GMT'), - cksum: 4789, - type: '5', - linkpath: '', - ustar: 'ustar\u0000', - ustarver: '00', - uname: '', - gname: '', - devmaj: 0, - devmin: 0, - fill: '' } ] - - , [ 'entry', - { path: 'fixtures/r/e/', - mode: 493, - uid: uid, - gid: gid, - size: 0, - mtime: new Date('Thu, 27 Oct 2011 03:42:46 GMT'), - cksum: 4937, - type: '5', - linkpath: '', - ustar: 'ustar\u0000', - ustarver: '00', - uname: '', - gname: '', - devmaj: 0, - devmin: 0, - fill: '' } ] - - , [ 'entry', - { path: 'fixtures/r/e/a/', - mode: 493, - uid: uid, - gid: gid, - size: 0, - mtime: new Date('Thu, 27 Oct 2011 03:42:46 GMT'), - cksum: 5081, - type: '5', - linkpath: '', - ustar: 'ustar\u0000', - ustarver: '00', - uname: '', - gname: '', - devmaj: 0, - devmin: 0, - fill: '' } ] - - , [ 'entry', - { path: 'fixtures/r/e/a/l/', - mode: 493, - uid: uid, - gid: gid, - size: 0, - mtime: new Date('Thu, 27 Oct 2011 03:42:46 GMT'), - cksum: 5236, - type: '5', - linkpath: '', - ustar: 'ustar\u0000', - ustarver: '00', - uname: '', - gname: '', - devmaj: 0, - devmin: 0, - fill: '' } ] - - , [ 'entry', - { path: 'fixtures/r/e/a/l/l/', - mode: 493, - uid: uid, - gid: gid, - size: 0, - mtime: new Date('Thu, 27 Oct 2011 03:42:46 GMT'), - cksum: 5391, - type: '5', - linkpath: '', - ustar: 'ustar\u0000', - ustarver: '00', - uname: '', - gname: '', - devmaj: 0, - devmin: 0, - fill: '' } ] - - , [ 'entry', - { path: 'fixtures/r/e/a/l/l/y/', - mode: 493, - uid: uid, - gid: gid, - size: 0, - mtime: new Date('Thu, 27 Oct 2011 03:42:46 GMT'), - cksum: 5559, - type: '5', - linkpath: '', - ustar: 'ustar\u0000', - ustarver: '00', - uname: '', - gname: '', - devmaj: 0, - devmin: 0, - fill: '' } ] - - , [ 'entry', - { path: 'fixtures/r/e/a/l/l/y/-/', - mode: 493, - uid: uid, - gid: gid, - size: 0, - mtime: new Date('Thu, 27 Oct 2011 03:42:46 GMT'), - cksum: 5651, - type: '5', - linkpath: '', - ustar: 'ustar\u0000', - ustarver: '00', - uname: '', - gname: '', - devmaj: 0, - devmin: 0, - fill: '' } ] - - , [ 'entry', - { path: 'fixtures/r/e/a/l/l/y/-/d/', - mode: 493, - uid: uid, - gid: gid, - size: 0, - mtime: new Date('Thu, 27 Oct 2011 03:42:46 GMT'), - cksum: 5798, - type: '5', - linkpath: '', - ustar: 'ustar\u0000', - ustarver: '00', - uname: '', - gname: '', - devmaj: 0, - devmin: 0, - fill: '' } ] - - , [ 'entry', - { path: 'fixtures/r/e/a/l/l/y/-/d/e/', - mode: 493, - uid: uid, - gid: gid, - size: 0, - mtime: new Date('Thu, 27 Oct 2011 03:42:46 GMT'), - cksum: 5946, - type: '5', - linkpath: '', - ustar: 'ustar\u0000', - ustarver: '00', - uname: '', - gname: '', - devmaj: 0, - devmin: 0, - fill: '' } ] - - , [ 'entry', - { path: 'fixtures/r/e/a/l/l/y/-/d/e/e/', - mode: 493, - uid: uid, - gid: gid, - size: 0, - mtime: new Date('Thu, 27 Oct 2011 03:42:46 GMT'), - cksum: 6094, - type: '5', - linkpath: '', - ustar: 'ustar\u0000', - ustarver: '00', - uname: '', - gname: '', - devmaj: 0, - devmin: 0, - fill: '' } ] - - , [ 'entry', - { path: 'fixtures/r/e/a/l/l/y/-/d/e/e/p/', - mode: 493, - uid: uid, - gid: gid, - size: 0, - mtime: new Date('Thu, 27 Oct 2011 03:42:46 GMT'), - cksum: 6253, - type: '5', - linkpath: '', - ustar: 'ustar\u0000', - ustarver: '00', - uname: '', - gname: '', - devmaj: 0, - devmin: 0, - fill: '' } ] - - , [ 'entry', - { path: 'fixtures/r/e/a/l/l/y/-/d/e/e/p/-/', - mode: 493, - uid: uid, - gid: gid, - size: 0, - mtime: new Date('Thu, 27 Oct 2011 03:42:46 GMT'), - cksum: 6345, - type: '5', - linkpath: '', - ustar: 'ustar\u0000', - ustarver: '00', - uname: '', - gname: '', - devmaj: 0, - devmin: 0, - fill: '' } ] - - , [ 'entry', - { path: 'fixtures/r/e/a/l/l/y/-/d/e/e/p/-/f/', - mode: 493, - uid: uid, - gid: gid, - size: 0, - mtime: new Date('Thu, 27 Oct 2011 03:42:46 GMT'), - cksum: 6494, - type: '5', - linkpath: '', - ustar: 'ustar\u0000', - ustarver: '00', - uname: '', - gname: '', - devmaj: 0, - devmin: 0, - fill: '' } ] - - , [ 'entry', - { path: 'fixtures/r/e/a/l/l/y/-/d/e/e/p/-/f/o/', - mode: 493, - uid: uid, - gid: gid, - size: 0, - mtime: new Date('Thu, 27 Oct 2011 03:42:46 GMT'), - cksum: 6652, - type: '5', - linkpath: '', - ustar: 'ustar\u0000', - ustarver: '00', - uname: '', - gname: '', - devmaj: 0, - devmin: 0, - fill: '' } ] - - , [ 'entry', - { path: 'fixtures/r/e/a/l/l/y/-/d/e/e/p/-/f/o/l/', - mode: 493, - uid: uid, - gid: gid, - size: 0, - mtime: new Date('Thu, 27 Oct 2011 03:42:46 GMT'), - cksum: 6807, - type: '5', - linkpath: '', - ustar: 'ustar\u0000', - ustarver: '00', - uname: '', - gname: '', - devmaj: 0, - devmin: 0, - fill: '' } ] - - , [ 'entry', - { path: 'fixtures/r/e/a/l/l/y/-/d/e/e/p/-/f/o/l/d/', - mode: 493, - uid: uid, - gid: gid, - size: 0, - mtime: new Date('Thu, 27 Oct 2011 03:42:46 GMT'), - cksum: 6954, - type: '5', - linkpath: '', - ustar: 'ustar\u0000', - ustarver: '00', - uname: '', - gname: '', - devmaj: 0, - devmin: 0, - fill: '' } ] - - , [ 'entry', - { path: 'fixtures/r/e/a/l/l/y/-/d/e/e/p/-/f/o/l/d/e/', - mode: 493, - uid: uid, - gid: gid, - size: 0, - mtime: new Date('Thu, 27 Oct 2011 03:42:46 GMT'), - cksum: 7102, - type: '5', - linkpath: '', - ustar: 'ustar\u0000', - ustarver: '00', - uname: '', - gname: '', - devmaj: 0, - devmin: 0, - fill: '' } ] - - , [ 'entry', - { path: 'fixtures/r/e/a/l/l/y/-/d/e/e/p/-/f/o/l/d/e/r/', - mode: 493, - uid: uid, - gid: gid, - size: 0, - mtime: new Date('Thu, 27 Oct 2011 03:42:46 GMT'), - cksum: 7263, - type: '5', - linkpath: '', - ustar: 'ustar\u0000', - ustarver: '00', - uname: '', - gname: '', - devmaj: 0, - devmin: 0, - fill: '' } ] - - , [ 'entry', - { path: 'fixtures/r/e/a/l/l/y/-/d/e/e/p/-/f/o/l/d/e/r/-/', - mode: 493, - uid: uid, - gid: gid, - size: 0, - mtime: new Date('Thu, 27 Oct 2011 03:42:46 GMT'), - cksum: 7355, - type: '5', - linkpath: '', - ustar: 'ustar\u0000', - ustarver: '00', - uname: '', - gname: '', - devmaj: 0, - devmin: 0, - fill: '' } ] - - , [ 'entry', - { path: 'fixtures/r/e/a/l/l/y/-/d/e/e/p/-/f/o/l/d/e/r/-/p/', - mode: 493, - uid: uid, - gid: gid, - size: 0, - mtime: new Date('Thu, 27 Oct 2011 03:42:46 GMT'), - cksum: 7514, - type: '5', - linkpath: '', - ustar: 'ustar\u0000', - ustarver: '00', - uname: '', - gname: '', - devmaj: 0, - devmin: 0, - fill: '' } ] - - , [ 'entry', - { path: 'fixtures/r/e/a/l/l/y/-/d/e/e/p/-/f/o/l/d/e/r/-/p/a/', - mode: 493, - uid: uid, - gid: gid, - size: 0, - mtime: new Date('Thu, 27 Oct 2011 03:42:46 GMT'), - cksum: 7658, - type: '5', - linkpath: '', - ustar: 'ustar\u0000', - ustarver: '00', - uname: '', - gname: '', - devmaj: 0, - devmin: 0, - fill: '' } ] - - , [ 'entry', - { path: 'fixtures/r/e/a/l/l/y/-/d/e/e/p/-/f/o/l/d/e/r/-/p/a/t/', - mode: 493, - uid: uid, - gid: gid, - size: 0, - mtime: new Date('Thu, 27 Oct 2011 03:42:46 GMT'), - cksum: 7821, - type: '5', - linkpath: '', - ustar: 'ustar\u0000', - ustarver: '00', - uname: '', - gname: '', - devmaj: 0, - devmin: 0, - fill: '' } ] - - , [ 'entry', - { path: 'fixtures/r/e/a/l/l/y/-/d/e/e/p/-/f/o/l/d/e/r/-/p/a/t/h/', - mode: 493, - uid: uid, - gid: gid, - size: 0, - mtime: new Date('Thu, 27 Oct 2011 03:43:23 GMT'), - cksum: 7967, - type: '5', - linkpath: '', - ustar: 'ustar\u0000', - ustarver: '00', - uname: '', - gname: '', - devmaj: 0, - devmin: 0, - fill: '' } ] - - , [ 'entry', - { path: 'fixtures/r/e/a/l/l/y/-/d/e/e/p/-/f/o/l/d/e/r/-/p/a/t/h/cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc', - mode: 420, - uid: uid, - gid: gid, - size: 100, - mtime: new Date('Thu, 27 Oct 2011 03:43:23 GMT'), - cksum: 17821, - type: '0', - linkpath: '', - ustar: 'ustar\u0000', - ustarver: '00', - uname: '', - gname: '', - devmaj: 0, - devmin: 0, - fill: '' } ] - - , [ 'entry', - { path: 'fixtures/symlink', - mode: 493, - uid: uid, - gid: gid, - size: 0, - mtime: new Date('Tue, 15 Nov 2011 19:57:48 GMT'), - cksum: 6337, - type: '2', - linkpath: 'hardlink-1', - ustar: 'ustar\u0000', - ustarver: '00', - uname: '', - gname: '', - devmaj: 0, - devmin: 0, - fill: '' } ] - - , [ 'extendedHeader', - { path: 'PaxHeader/fixtures/Ω.txt', - mode: 420, - uid: uid, - gid: gid, - size: 204, - mtime: new Date('Thu, 27 Oct 2011 17:51:49 GMT'), - cksum: 6399, - type: 'x', - linkpath: '', - ustar: 'ustar\u0000', - ustarver: '00', - uname: '', - gname: '', - devmaj: 0, - devmin: 0, - fill: '' }, - { path: "fixtures/Ω.txt" - , "NODETAR.depth": "1" - , "NODETAR.type": "File" - , nlink: 1 - , uid: uid - , gid: gid - , size: 2 - , "NODETAR.blksize": "4096" - , "NODETAR.blocks": "8" } ] - - , [ 'entry', - { path: 'fixtures/Ω.txt', - mode: 420, - uid: uid, - gid: gid, - size: 2, - mtime: new Date('Thu, 27 Oct 2011 17:51:49 GMT'), - cksum: 5392, - type: '0', - linkpath: '', - ustar: 'ustar\u0000', - ustarver: '00', - uname: '', - gname: '', - devmaj: 0, - devmin: 0, - fill: '', - 'NODETAR.depth': '1', - 'NODETAR.type': 'File', - nlink: 1, - 'NODETAR.blksize': '4096', - 'NODETAR.blocks': '8' } ] - ] - - -// first, make sure that the hardlinks are actually hardlinks, or this -// won't work. Git has a way of replacing them with a copy. -var hard1 = path.resolve(__dirname, "fixtures/hardlink-1") - , hard2 = path.resolve(__dirname, "fixtures/hardlink-2") - , fs = require("fs") - -try { fs.unlinkSync(hard2) } catch (e) {} -fs.linkSync(hard1, hard2) - -tap.test("with global header", { timeout: 10000 }, function (t) { - runTest(t, true) -}) - -tap.test("without global header", { timeout: 10000 }, function (t) { - runTest(t, false) -}) - -function runTest (t, doGH) { - var reader = Reader({ path: input - , filter: function () { - return !this.path.match(/\.(tar|hex)$/) - } - }) - - var pack = Pack(doGH ? pkg : null) - var writer = Writer(target) - - // skip the global header if we're not doing that. - var entry = doGH ? 0 : 1 - - t.ok(reader, "reader ok") - t.ok(pack, "pack ok") - t.ok(writer, "writer ok") - - pack.pipe(writer) - - var parse = tar.Parse() - t.ok(parse, "parser should be ok") - - pack.on("data", function (c) { - // console.error("PACK DATA") - t.equal(c.length, 512, "parser should emit data in 512byte blocks") - parse.write(c) - }) - - pack.on("end", function () { - // console.error("PACK END") - t.pass("parser ends") - parse.end() - }) - - pack.on("error", function (er) { - t.fail("pack error", er) - }) - - parse.on("error", function (er) { - t.fail("parse error", er) - }) - - writer.on("error", function (er) { - t.fail("writer error", er) - }) - - reader.on("error", function (er) { - t.fail("reader error", er) - }) - - parse.on("*", function (ev, e) { - var wanted = entries[entry++] - if (!wanted) { - t.fail("unexpected event: "+ev) - return - } - t.equal(ev, wanted[0], "event type should be "+wanted[0]) - // if (ev !== wanted[0] || e.path !== wanted[1].path) { - // console.error(wanted) - // console.error([ev, e.props]) - // throw "break" - // } - t.has(e.props, wanted[1], "properties "+wanted[1].path) - if (wanted[2]) { - e.on("end", function () { - t.has(e.fields, wanted[2], "should get expected fields") - }) - } - }) - - reader.pipe(pack) - - writer.on("close", function () { - t.equal(entry, entries.length, "should get all expected entries") - t.pass("it finished") - t.end() - }) - -} diff --git a/node_modules/tar/test/parse.js b/node_modules/tar/test/parse.js deleted file mode 100644 index f765a50..0000000 --- a/node_modules/tar/test/parse.js +++ /dev/null @@ -1,359 +0,0 @@ -var tap = require("tap") - , tar = require("../tar.js") - , fs = require("fs") - , path = require("path") - , file = path.resolve(__dirname, "fixtures/c.tar") - , index = 0 - - , expect = -[ [ 'entry', - { path: 'c.txt', - mode: 420, - uid: 24561, - gid: 20, - size: 513, - mtime: new Date('Wed, 26 Oct 2011 01:10:58 GMT'), - cksum: 5422, - type: '0', - linkpath: '', - ustar: 'ustar\0', - ustarver: '00', - uname: 'isaacs', - gname: 'staff', - devmaj: 0, - devmin: 0, - fill: '' }, - undefined ], - [ 'entry', - { path: 'cc.txt', - mode: 420, - uid: 24561, - gid: 20, - size: 513, - mtime: new Date('Wed, 26 Oct 2011 01:11:02 GMT'), - cksum: 5525, - type: '0', - linkpath: '', - ustar: 'ustar\0', - ustarver: '00', - uname: 'isaacs', - gname: 'staff', - devmaj: 0, - devmin: 0, - fill: '' }, - undefined ], - [ 'entry', - { path: 'r/e/a/l/l/y/-/d/e/e/p/-/f/o/l/d/e/r/-/p/a/t/h/cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc', - mode: 420, - uid: 24561, - gid: 20, - size: 100, - mtime: new Date('Thu, 27 Oct 2011 03:43:23 GMT'), - cksum: 18124, - type: '0', - linkpath: '', - ustar: 'ustar\0', - ustarver: '00', - uname: 'isaacs', - gname: 'staff', - devmaj: 0, - devmin: 0, - fill: '' }, - undefined ], - [ 'entry', - { path: 'Ω.txt', - mode: 420, - uid: 24561, - gid: 20, - size: 2, - mtime: new Date('Thu, 27 Oct 2011 17:51:49 GMT'), - cksum: 5695, - type: '0', - linkpath: '', - ustar: 'ustar\0', - ustarver: '00', - uname: 'isaacs', - gname: 'staff', - devmaj: 0, - devmin: 0, - fill: '' }, - undefined ], - [ 'extendedHeader', - { path: 'PaxHeader/Ω.txt', - mode: 420, - uid: 24561, - gid: 20, - size: 120, - mtime: new Date('Thu, 27 Oct 2011 17:51:49 GMT'), - cksum: 6702, - type: 'x', - linkpath: '', - ustar: 'ustar\0', - ustarver: '00', - uname: 'isaacs', - gname: 'staff', - devmaj: 0, - devmin: 0, - fill: '' }, - { path: 'Ω.txt', - ctime: 1319737909, - atime: 1319739061, - dev: 234881026, - ino: 51693379, - nlink: 1 } ], - [ 'entry', - { path: 'Ω.txt', - mode: 420, - uid: 24561, - gid: 20, - size: 2, - mtime: new Date('Thu, 27 Oct 2011 17:51:49 GMT'), - cksum: 5695, - type: '0', - linkpath: '', - ustar: 'ustar\0', - ustarver: '00', - uname: 'isaacs', - gname: 'staff', - devmaj: 0, - devmin: 0, - fill: '', - ctime: new Date('Thu, 27 Oct 2011 17:51:49 GMT'), - atime: new Date('Thu, 27 Oct 2011 18:11:01 GMT'), - dev: 234881026, - ino: 51693379, - nlink: 1 }, - undefined ], - [ 'extendedHeader', - { path: 'PaxHeader/200ccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc', - mode: 420, - uid: 24561, - gid: 20, - size: 353, - mtime: new Date('Thu, 27 Oct 2011 03:41:08 GMT'), - cksum: 14488, - type: 'x', - linkpath: '', - ustar: 'ustar\0', - ustarver: '00', - uname: 'isaacs', - gname: 'staff', - devmaj: 0, - devmin: 0, - fill: '' }, - { path: '200ccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc', - ctime: 1319686868, - atime: 1319741254, - 'LIBARCHIVE.creationtime': '1319686852', - dev: 234881026, - ino: 51681874, - nlink: 1 } ], - [ 'entry', - { path: '200ccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc', - mode: 420, - uid: 24561, - gid: 20, - size: 200, - mtime: new Date('Thu, 27 Oct 2011 03:41:08 GMT'), - cksum: 14570, - type: '0', - linkpath: '', - ustar: 'ustar\0', - ustarver: '00', - uname: 'isaacs', - gname: 'staff', - devmaj: 0, - devmin: 0, - fill: '', - ctime: new Date('Thu, 27 Oct 2011 03:41:08 GMT'), - atime: new Date('Thu, 27 Oct 2011 18:47:34 GMT'), - 'LIBARCHIVE.creationtime': '1319686852', - dev: 234881026, - ino: 51681874, - nlink: 1 }, - undefined ], - [ 'longPath', - { path: '././@LongLink', - mode: 0, - uid: 0, - gid: 0, - size: 201, - mtime: new Date('Thu, 01 Jan 1970 00:00:00 GMT'), - cksum: 4976, - type: 'L', - linkpath: '', - ustar: false }, - '200ccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc' ], - [ 'entry', - { path: '200ccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc', - mode: 420, - uid: 1000, - gid: 1000, - size: 201, - mtime: new Date('Thu, 27 Oct 2011 22:21:50 GMT'), - cksum: 14086, - type: '0', - linkpath: '', - ustar: false }, - undefined ], - [ 'longLinkpath', - { path: '././@LongLink', - mode: 0, - uid: 0, - gid: 0, - size: 201, - mtime: new Date('Thu, 01 Jan 1970 00:00:00 GMT'), - cksum: 4975, - type: 'K', - linkpath: '', - ustar: false }, - '200ccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc' ], - [ 'longPath', - { path: '././@LongLink', - mode: 0, - uid: 0, - gid: 0, - size: 201, - mtime: new Date('Thu, 01 Jan 1970 00:00:00 GMT'), - cksum: 4976, - type: 'L', - linkpath: '', - ustar: false }, - '200LLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLL' ], - [ 'entry', - { path: '200LLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLL', - mode: 511, - uid: 1000, - gid: 1000, - size: 0, - mtime: new Date('Fri, 28 Oct 2011 23:05:17 GMT'), - cksum: 21603, - type: '2', - linkpath: '200ccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc', - ustar: false }, - undefined ], - [ 'extendedHeader', - { path: 'PaxHeader/200-hard', - mode: 420, - uid: 24561, - gid: 20, - size: 143, - mtime: new Date('Thu, 27 Oct 2011 03:41:08 GMT'), - cksum: 6533, - type: 'x', - linkpath: '', - ustar: 'ustar\0', - ustarver: '00', - uname: 'isaacs', - gname: 'staff', - devmaj: 0, - devmin: 0, - fill: '' }, - { ctime: 1320617144, - atime: 1320617232, - 'LIBARCHIVE.creationtime': '1319686852', - dev: 234881026, - ino: 51681874, - nlink: 2 } ], - [ 'entry', - { path: '200-hard', - mode: 420, - uid: 24561, - gid: 20, - size: 200, - mtime: new Date('Thu, 27 Oct 2011 03:41:08 GMT'), - cksum: 5526, - type: '0', - linkpath: '', - ustar: 'ustar\0', - ustarver: '00', - uname: 'isaacs', - gname: 'staff', - devmaj: 0, - devmin: 0, - fill: '', - ctime: new Date('Sun, 06 Nov 2011 22:05:44 GMT'), - atime: new Date('Sun, 06 Nov 2011 22:07:12 GMT'), - 'LIBARCHIVE.creationtime': '1319686852', - dev: 234881026, - ino: 51681874, - nlink: 2 }, - undefined ], - [ 'extendedHeader', - { path: 'PaxHeader/200ccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc', - mode: 420, - uid: 24561, - gid: 20, - size: 353, - mtime: new Date('Thu, 27 Oct 2011 03:41:08 GMT'), - cksum: 14488, - type: 'x', - linkpath: '', - ustar: 'ustar\0', - ustarver: '00', - uname: 'isaacs', - gname: 'staff', - devmaj: 0, - devmin: 0, - fill: '' }, - { path: '200ccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc', - ctime: 1320617144, - atime: 1320617406, - 'LIBARCHIVE.creationtime': '1319686852', - dev: 234881026, - ino: 51681874, - nlink: 2 } ], - [ 'entry', - { path: '200ccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc', - mode: 420, - uid: 24561, - gid: 20, - size: 0, - mtime: new Date('Thu, 27 Oct 2011 03:41:08 GMT'), - cksum: 15173, - type: '1', - linkpath: '200-hard', - ustar: 'ustar\0', - ustarver: '00', - uname: 'isaacs', - gname: 'staff', - devmaj: 0, - devmin: 0, - fill: '', - ctime: new Date('Sun, 06 Nov 2011 22:05:44 GMT'), - atime: new Date('Sun, 06 Nov 2011 22:10:06 GMT'), - 'LIBARCHIVE.creationtime': '1319686852', - dev: 234881026, - ino: 51681874, - nlink: 2 }, - undefined ] ] - - -tap.test("parser test", function (t) { - var parser = tar.Parse() - - parser.on("end", function () { - t.equal(index, expect.length, "saw all expected events") - t.end() - }) - - fs.createReadStream(file) - .pipe(parser) - .on("*", function (ev, entry) { - var wanted = expect[index] - if (!wanted) { - return t.fail("Unexpected event: " + ev) - } - var result = [ev, entry.props] - entry.on("end", function () { - result.push(entry.fields || entry.body) - - t.equal(ev, wanted[0], index + " event type") - t.equivalent(entry.props, wanted[1], wanted[1].path + " entry properties") - if (wanted[2]) { - t.equivalent(result[2], wanted[2], "metadata values") - } - index ++ - }) - }) -}) diff --git a/node_modules/vine b/node_modules/vine deleted file mode 120000 index 5c1d60b..0000000 --- a/node_modules/vine +++ /dev/null @@ -1 +0,0 @@ -/usr/local/lib/node_modules/vine \ No newline at end of file diff --git a/package.json b/package.json index 6f499c1..25e9811 100644 --- a/package.json +++ b/package.json @@ -2,17 +2,19 @@ "author": "Craig Condon ", "name": "nexe", "description": "Roll node.s applications into a single executable", - "version": "0.0.1", + "version": "0.1.0", "repository": { "type": "git", "url": "git://github.com/crcn/nexe.git" }, "main": "./lib/index.js", "dependencies": { - "optimist": "*", - "sardines": "*", - "mkdirp": "*", - "celeri": "*" + "outcome": "0.0.x", + "sprintf": "0.1.x", + "step": "0.0.x", + "optimist": "0.3.x", + "browserify": "1.16.x", + "request": "2.12.x" }, "bin": { "nexe": "./bin/nexe" diff --git a/project.sublime-project b/project.sublime-project deleted file mode 100644 index 9b0403a..0000000 --- a/project.sublime-project +++ /dev/null @@ -1,23 +0,0 @@ -{ - "folders": - [ - { - "path": "." - } - ], - "build_systems": - [ - { - "name":"cbd make", - "cmd":["cbd","make","nexe"] - }, - { - "name":"cbd start", - "cmd":["cbd","start","nexe"] - }, - { - "name":"cbd make+start", - "cmd":["cbd","make+start","nexe"] - } - ] -} \ No newline at end of file diff --git a/project.sublime-workspace b/project.sublime-workspace deleted file mode 100644 index 2d7ac37..0000000 --- a/project.sublime-workspace +++ /dev/null @@ -1,547 +0,0 @@ -{ - "auto_complete": - { - "selected_items": - [ - ] - }, - "buffers": - [ - { - "file": "README.md", - "settings": - { - "buffer_size": 931, - "line_ending": "Unix" - } - }, - { - "file": "lib/index.js", - "settings": - { - "buffer_size": 4441, - "line_ending": "Unix" - } - }, - { - "file": "package.json", - "settings": - { - "buffer_size": 447, - "line_ending": "Unix" - } - }, - { - "file": "node_modules/sardines/lib/core/index.js", - "settings": - { - "buffer_size": 1408, - "line_ending": "Unix" - } - }, - { - "file": "node_modules/sardines/lib/core/combine.js", - "settings": - { - "buffer_size": 6969, - "line_ending": "Unix" - } - }, - { - "file": "bin/nexe", - "settings": - { - "buffer_size": 650, - "line_ending": "Unix" - } - } - ], - "build_system": "", - "command_palette": - { - "height": 0.0, - "selected_items": - [ - ], - "width": 0.0 - }, - "console": - { - "height": 51.0 - }, - "distraction_free": - { - "menu_visible": true, - "show_minimap": false, - "show_open_files": false, - "show_tabs": false, - "side_bar_visible": false, - "status_bar_visible": false - }, - "file_history": - [ - "/Volumes/minimac/Users/craig/Dropbox/Developer/Public/nexe/node_modules/sardines/lib/index.js", - "/Volumes/minimac/Users/craig/Dropbox/Developer/Public/nexe/package.json", - "/tmp/subl stdin sPb7bK.txt", - "/Volumes/minimac/Users/craig/Dropbox/Developer/Public/nexe/bin/nexe", - "/Users/craig/.cupboard/projects/teamdigest/node_modules/fig/lib/core/views/concrete.js", - "/Users/craig/.cupboard/projects/teamdigest/node_modules/fig/lib/core/views/abstract.js", - "/Users/craig/.cupboard/projects/teamdigest/node_modules/fig/lib/core/views/model.js", - "/Users/craig/.cupboard/projects/teamdigest/node_modules/fig/lib/core/views/template.js", - "/Users/craig/.cupboard/projects/teamdigest/node_modules/spice.io/beans/groups.part.saved.core/delegates.js", - "/Users/craig/.cupboard/projects/teamdigest/lib/front/node_modules/bean.http/plugin/beans/http.gateway/index.js", - "/Users/craig/.cupboard/projects/teamdigest/node_modules/spice.io/beans/groups.part.saved.core/index.js", - "/Users/craig/.cupboard/projects/teamdigest/node_modules/spice.io/beans/groups.part.saved.subscription.email/index.js", - "/Users/craig/.cupboard/projects/teamdigest/lib/front/shared/beans/teamdigest.creation/index.js", - "/Volumes/minimac/Users/craig/Dropbox/Developer/Jobs/Spice/private/teamdigest/package.json", - "/Users/craig/.cupboard/projects/teamdigest/lib/front/shared/beans/teamdigest.core/index.js", - "/Users/craig/Desktop/global-lock.png", - "/Users/craig/.cupboard/projects/teamdigest/lib/front/web/views/tpl/digest.mu", - "/Users/craig/.cupboard/projects/teamdigest/lib/front/shared/beans/teamdigest.digest/views.js", - "/Users/craig/.cupboard/projects/teamdigest/lib/front/shared/beans/teamdigest.bookmarklet/index.js", - "/Users/craig/.cupboard/projects/teamdigest/lib/front/node_modules/malt/lib/core/models/item.js", - "/Users/craig/.cupboard/projects/teamdigest/node_modules/spice.io/beans/groups.core/index.js", - "/Users/craig/.cupboard/projects/teamdigest/lib/front/shared/beans/teamdigest.digest/index.js", - "/Users/craig/.cupboard/projects/teamdigest/node_modules/leche.spice.io/shared/beans/spice.io.core/models.js", - "/Users/craig/.cupboard/projects/teamdigest/lib/front/shared/beans/teamdigest.creation/views.js", - "/Users/craig/.cupboard/projects/teamdigest/node_modules/leche.spice.io/shared/beans/connect.core/index.js", - "/Users/craig/.cupboard/projects/teamdigest/lib/front/web/views/tpl/creation.mu", - "/tmp/subl stdin D0Hull.txt", - "/Users/craig/.cupboard/projects/teamdigest/lib/front/node_modules/malt/lib/core/models/remote.js", - "/Users/craig/.cupboard/projects/teamdigest/lib/front/node_modules/malt/lib/core/models/abstract.js", - "/Users/craig/.cupboard/projects/teamdigest/lib/front/node_modules/malt/lib/core/models/concrete.js", - "/tmp/subl stdin 9SDm50.txt", - "/Users/craig/.cupboard/projects/teamdigest/lib/front/node_modules/malt/lib/core/models/collection.js", - "/Users/craig/.cupboard/projects/teamdigest/node_modules/spice.io/beans/auth.profile/index.js", - "/Users/craig/Library/Application Support/Sublime Text 2/Packages/User/Base File.sublime-settings", - "/tmp/subl stdin qOmgFT.txt" - ], - "find": - { - "height": 33.0 - }, - "find_in_files": - { - "height": 0.0, - "where_history": - [ - ] - }, - "find_state": - { - "case_sensitive": false, - "find_history": - [ - ".complete", - "include", - "onDataChange", - "_setEleme", - "'update", - "update", - "group", - "c_savedArticles", - "group:", - "urlParts", - "request", - "Removing", - "EditArt", - "editArt", - "editArticle", - "Digest:", - "recipients", - "specificEmails", - "/login", - "stat", - "find", - "store/pr", - "rawProfile", - "_load", - "load", - "Profil", - "Profile", - "args", - "--all" - ], - "highlight": true, - "in_selection": false, - "preserve_case": false, - "regex": false, - "replace_history": - [ - ], - "reverse": false, - "show_context": true, - "use_buffer2": true, - "whole_word": false, - "wrap": true - }, - "groups": - [ - { - "selected": 1, - "sheets": - [ - { - "buffer": 0, - "file": "README.md", - "settings": - { - "buffer_size": 931, - "regions": - { - }, - "selection": - [ - [ - 617, - 617 - ] - ], - "settings": - { - "syntax": "Packages/Markdown/Markdown.tmLanguage" - }, - "translation.x": 0.0, - "translation.y": 89.0, - "zoom_level": 1.0 - }, - "type": "text" - }, - { - "buffer": 1, - "file": "lib/index.js", - "settings": - { - "buffer_size": 4441, - "regions": - { - }, - "selection": - [ - [ - 1725, - 1725 - ] - ], - "settings": - { - "syntax": "Packages/JavaScript/JavaScript.tmLanguage", - "translate_tabs_to_spaces": false - }, - "translation.x": 0.0, - "translation.y": 1270.0, - "zoom_level": 1.0 - }, - "type": "text" - }, - { - "buffer": 2, - "file": "package.json", - "settings": - { - "buffer_size": 447, - "regions": - { - }, - "selection": - [ - [ - 375, - 375 - ] - ], - "settings": - { - "syntax": "Packages/JavaScript/JSON.tmLanguage", - "tab_size": 2, - "translate_tabs_to_spaces": true - }, - "translation.x": 0.0, - "translation.y": 0.0, - "zoom_level": 1.0 - }, - "type": "text" - }, - { - "buffer": 3, - "file": "node_modules/sardines/lib/core/index.js", - "settings": - { - "buffer_size": 1408, - "regions": - { - }, - "selection": - [ - [ - 603, - 610 - ] - ], - "settings": - { - "syntax": "Packages/JavaScript/JavaScript.tmLanguage", - "translate_tabs_to_spaces": false - }, - "translation.x": 0.0, - "translation.y": 0.0, - "zoom_level": 1.0 - }, - "type": "text" - }, - { - "buffer": 4, - "file": "node_modules/sardines/lib/core/combine.js", - "settings": - { - "buffer_size": 6969, - "regions": - { - }, - "selection": - [ - [ - 2109, - 2109 - ] - ], - "settings": - { - "syntax": "Packages/JavaScript/JavaScript.tmLanguage", - "translate_tabs_to_spaces": false - }, - "translation.x": 0.0, - "translation.y": 6039.0, - "zoom_level": 1.0 - }, - "type": "text" - }, - { - "buffer": 5, - "file": "bin/nexe", - "settings": - { - "buffer_size": 650, - "regions": - { - }, - "selection": - [ - [ - 494, - 494 - ] - ], - "settings": - { - "syntax": "Packages/JavaScript/JavaScript.tmLanguage", - "translate_tabs_to_spaces": false - }, - "translation.x": 0.0, - "translation.y": 0.0, - "zoom_level": 1.0 - }, - "type": "text" - } - ] - } - ], - "incremental_find": - { - "height": 0.0 - }, - "input": - { - "height": 30.0 - }, - "layout": - { - "cells": - [ - [ - 0, - 0, - 1, - 1 - ] - ], - "cols": - [ - 0.0, - 1.0 - ], - "rows": - [ - 0.0, - 1.0 - ] - }, - "menu_visible": true, - "replace": - { - "height": 0.0 - }, - "save_all_on_build": true, - "select_file": - { - "height": 0.0, - "selected_items": - [ - [ - "figabst", - "node_modules/fig/lib/core/views/abstract.js" - ], - [ - "figmode", - "node_modules/fig/lib/core/views/model.js" - ], - [ - "figtemplat", - "node_modules/fig/lib/core/views/template.js" - ], - [ - "figmodel", - "node_modules/fig/lib/core/views/model.js" - ], - [ - "figabs", - "node_modules/fig/lib/core/views/abstract.js" - ], - [ - "figviews/", - "node_modules/fig/lib/core/views/concrete.js" - ], - [ - "figviews", - "node_modules/fig/lib/core/views/model.js" - ], - [ - "saveddelegat", - "node_modules/spice.io/beans/groups.part.saved.core/delegates.js" - ], - [ - "spicesavedinde", - "node_modules/spice.io/beans/groups.part.saved.subscription.email/index.js" - ], - [ - "saveddelega", - "node_modules/spice.io/beans/groups.part.saved.core/delegates.js" - ], - [ - "spice.iosaved", - "node_modules/spice.io/beans/groups.part.saved.core/index.js" - ], - [ - "spice.iosaveddele", - "node_modules/spice.io/beans/groups.part.saved.core/delegates.js" - ], - [ - "spice.iosavedind", - "node_modules/spice.io/beans/groups.part.saved.core/index.js" - ], - [ - "bean.http", - "lib/front/node_modules/bean.http/plugin/beans/http.gateway/index.js" - ], - [ - "maltconcr", - "lib/front/node_modules/malt/lib/core/models/concrete.js" - ], - [ - "maltabst", - "lib/front/node_modules/malt/lib/core/models/abstract.js" - ], - [ - "maltremot", - "lib/front/node_modules/malt/lib/core/models/remote.js" - ], - [ - "bean.http.gat", - "lib/front/node_modules/bean.http/plugin/beans/http.gateway/index.js" - ], - [ - "bean.httpgateway", - "lib/front/node_modules/bean.http/plugin/beans/http.gateway/index.js" - ], - [ - "spice.iosaveditem", - "node_modules/spice.io/beans/groups.part.saved.subscription.email/index.js" - ], - [ - "connect.core/", - "node_modules/leche.spice.io/shared/beans/connect.core/index.js" - ], - [ - "maltmodels", - "lib/front/node_modules/malt/lib/core/models/item.js" - ], - [ - "", - "node_modules/leche.spice.io/shared/beans/connect.core/index.js" - ], - [ - "malt/models", - "lib/front/node_modules/malt/lib/core/models/concrete.js" - ], - [ - "maltabs", - "lib/front/node_modules/malt/lib/core/models/abstract.js" - ], - [ - "maltremo", - "lib/front/node_modules/malt/lib/core/models/remote.js" - ], - [ - "maltcolle", - "lib/front/node_modules/malt/lib/core/models/collection.js" - ], - [ - "maltremote", - "lib/front/node_modules/malt/lib/core/models/remote.js" - ], - [ - "leche.spice.iomodel", - "node_modules/leche.spice.io/shared/beans/spice.io.core/models.js" - ], - [ - "spice.ioauthprofileind", - "node_modules/spice.io/beans/auth.profile/index.js" - ], - [ - "spice.iogroups", - "node_modules/spice.io/beans/groups.core/index.js" - ], - [ - "leche.spice.iomode", - "node_modules/leche.spice.io/shared/beans/spice.io.core/models.js" - ], - [ - "leche.spice.ioconne", - "node_modules/leche.spice.io/shared/beans/connect.core/index.js" - ], - [ - "leche.spice.io/beanconnect", - "node_modules/leche.spice.io/shared/beans/connect.core/index.js" - ], - [ - "lechespice.iomodel", - "node_modules/leche.spice.io/shared/beans/spice.io.core/models.js" - ] - ], - "width": 0.0 - }, - "select_project": - { - "height": 0.0, - "selected_items": - [ - ], - "width": 0.0 - }, - "show_minimap": true, - "show_open_files": false, - "show_tabs": true, - "side_bar_visible": true, - "side_bar_width": 219.0, - "status_bar_visible": true -}
-
-
-Schily's USER COMMANDS                                   STAR(4L)
-
-
-